Files

487 lines
18 KiB
TypeScript
Raw Permalink Normal View History

2026-10-12 07:54:37 -04:00
import { registerClassicTheme } from '@/views/classic';
2026-10-12 16:21:19 -04:00
import { loadViewCatalog } from '@/views/catalog';
2026-10-12 08:13:40 -04:00
import {
clearThemeLayers,
2026-10-13 02:37:22 -04:00
getViewDefinition,
2026-10-12 08:13:40 -04:00
registerViewLayer,
type ViewInput,
type ViewModel,
type ViewModels,
type ViewName,
} from '@/views/registry';
import { registerThemeIcons, type ThemeDefinition } from '@/views/theme';
2026-10-12 09:04:03 -04:00
import { clearThemeSkins, registerSkins } from '@/themes/skins';
2026-10-12 08:13:40 -04:00
import classic from '@/themes/classic';
2026-10-12 16:11:44 -04:00
import { isPendingLazyView } from '@/views/lazy';
2026-10-13 02:37:22 -04:00
import { mountedSlots, mountedViews } from '@/extensions/slotWatch';
import { loadCodemirrorEditor } from '@/components/elements/LazyCodemirrorEditor';
2026-10-12 21:41:35 -04:00
import { LooseView, preloadView, ViewFixtureProvider } from '@/views/View';
2026-10-12 08:55:18 -04:00
import {
act,
createContext,
useContext,
useLayoutEffect,
type ComponentType,
2026-10-12 21:41:35 -04:00
type ReactElement,
2026-10-12 08:55:18 -04:00
type ReactNode,
} from 'react';
2026-10-12 08:13:40 -04:00
import { createRoot } from 'react-dom/client';
2026-10-05 18:10:18 -04:00
import { QueryClientProvider, type QueryClient } from '@tanstack/react-query';
import {
createMemoryHistory,
createRootRoute,
createRoute,
createRouter,
Outlet,
2026-10-12 08:13:40 -04:00
RouterContextProvider,
2026-10-05 18:10:18 -04:00
RouterProvider,
2026-10-12 23:40:08 -04:00
type HistoryState,
2026-10-05 18:10:18 -04:00
} from '@tanstack/react-router';
import { queryClient } from '@/api/queryClient';
import { currentUserQueryKey } from '@/api/account/queries';
import { siteSettingsQueryKey } from '@/api/settings/queries';
import { serverQueryOptions } from '@/api/server/queries';
2026-10-12 15:20:31 -04:00
import StatsListener from '@/components/server/StatsListener';
2026-10-05 18:10:18 -04:00
import { ServerContext } from '@/state/server/context';
import { useServerStore } from '@/state/server';
import { Websocket } from '@/plugins/Websocket';
import ExtensionMount from '@/extensions/ExtensionMount';
import { registerClassPrefixes } from '@/lib/cn';
2026-10-12 23:40:08 -04:00
import { ExtensionResourceProvider, type ExtensionResourceContext } from '@/extensions/resourceContext';
2026-10-12 17:39:58 -04:00
import {
2026-10-12 21:41:35 -04:00
clearExtensionError,
getExtensionErrors,
2026-10-12 17:39:58 -04:00
mountSlotComponents,
SCREEN_ROOTS,
type SlotComponentProps,
type SlotData,
type SlotName,
} from '@/extensions/registry';
2026-10-05 18:10:18 -04:00
import { resolvePanelDestination, type PanelDestination, type PanelSearch } from './navigation';
2026-10-12 23:40:08 -04:00
import type { SdkServer, SdkSiteSettings, SdkUser, ServerWebsocketEvent } from './index';
2026-10-05 18:10:18 -04:00
2026-10-12 16:21:19 -04:00
export { createTestServer, createTestServerCard, type TestServerOptions } from '@/views/fixtures';
2026-10-12 07:54:37 -04:00
export {
createTestFileDetails,
createTestFileEditor,
createTestFileManager,
createTestFileManagerEntry,
2026-10-12 16:21:19 -04:00
} from '@/views/server/fileFixtures';
2026-10-12 17:58:43 -04:00
2026-10-12 21:41:35 -04:00
const causeMessage = (cause: unknown): string => (cause instanceof Error ? cause.message : String(cause));
/** A theme or extension layer of a view that failed, which the strict test renderers throw. */
export class ViewLayerError extends Error {
constructor(
readonly view: string,
readonly layer: string,
cause: unknown
) {
super(`The "${layer}" layer of view "${view}" failed: ${causeMessage(cause)}`, { cause });
this.name = 'ViewLayerError';
}
}
2026-10-12 17:58:43 -04:00
2026-10-12 08:13:40 -04:00
registerClassicTheme();
2026-10-13 02:37:22 -04:00
// Views' hooks and fixtures, classic's own views and the code editor are lazy; loading them here lets a test
// render them synchronously.
await Promise.all([loadViewCatalog(), ...Object.keys(classic.views ?? {}).map(preloadView), loadCodemirrorEditor()]);
2026-10-12 08:13:40 -04:00
2026-10-05 18:10:18 -04:00
export interface ExtensionTestHostOptions {
extensionId?: string;
/** The extension's `ui.prefix`, so its prefixed classes merge with a core component's as they do in the panel. */
prefix?: string;
path?: string;
user?: SdkUser;
siteSettings?: SdkSiteSettings;
server?: SdkServer;
resource?: ExtensionResourceContext;
}
export interface ExtensionTestLocation {
pathname: string;
search: PanelSearch;
state: HistoryState;
}
export interface ExtensionTestHost {
Wrapper: ComponentType<{ children?: ReactNode }>;
queryClient: QueryClient;
navigate(destination: PanelDestination): Promise<void>;
location(): ExtensionTestLocation;
emitWebsocket(event: ServerWebsocketEvent, data: string): void;
setConnected(connected: boolean): void;
dispose(): void;
}
2026-10-12 21:41:35 -04:00
/** Create one host per test; call dispose after unmounting its Wrapper. */
export function createExtensionTestHost(options: ExtensionTestHostOptions = {}): ExtensionTestHost {
2026-10-05 18:10:18 -04:00
registerClassPrefixes([options.prefix]);
queryClient.clear();
queryClient.setQueryData(
currentUserQueryKey,
options.user ?? {
uuid: 'test-user',
username: 'Alex',
email: 'alex@example.test',
language: 'en',
rootAdmin: false,
useTotp: false,
createdAt: new Date(0),
updatedAt: new Date(0),
}
);
queryClient.setQueryData(
siteSettingsQueryKey,
options.siteSettings ?? {
name: 'Test panel',
2026-11-02 01:50:03 +01:00
logo: null,
2026-10-05 18:10:18 -04:00
locale: 'en',
2026-10-20 21:09:33 +02:00
userAvatarsEnabled: false,
2026-10-05 18:10:18 -04:00
recaptcha: { enabled: false, siteKey: '' },
}
);
if (options.server) {
queryClient.setQueryData(serverQueryOptions(options.server.attributes.identifier).queryKey, options.server);
}
2026-10-08 16:53:20 -04:00
2026-10-05 18:10:18 -04:00
const socket = new Websocket();
let updateConnected: (connected: boolean) => void = () => {
throw new Error('Mount the test host before changing its connection state.');
};
2026-10-08 16:53:20 -04:00
2026-10-05 18:10:18 -04:00
function SocketFixture() {
const setInstance = useServerStore((state) => state.socket.setInstance);
const setConnected = useServerStore((state) => state.socket.setConnectionState);
2026-10-08 16:53:20 -04:00
2026-10-05 18:10:18 -04:00
useLayoutEffect(() => {
updateConnected = setConnected;
setInstance(socket);
setConnected(true);
2026-10-08 16:53:20 -04:00
2026-10-05 18:10:18 -04:00
return () => {
setConnected(false);
setInstance(null);
socket.removeAllListeners();
};
}, [setInstance, setConnected]);
2026-10-08 16:53:20 -04:00
2026-10-05 18:10:18 -04:00
return null;
}
2026-10-08 16:53:20 -04:00
2026-10-05 18:10:18 -04:00
const Content = createContext<ReactNode>(null);
2026-10-08 16:53:20 -04:00
2026-10-05 18:10:18 -04:00
function RenderContent() {
return useContext(Content);
}
2026-10-08 16:53:20 -04:00
2026-10-12 17:39:58 -04:00
const extensionId = options.extensionId ?? 'test-extension';
2026-10-05 18:10:18 -04:00
function Root() {
const content = (
2026-10-12 21:41:35 -04:00
<ExtensionMount extensionId={extensionId} context='test host' resetKey='test'>
2026-10-05 18:10:18 -04:00
<ExtensionResourceProvider.Provider value={options.resource ?? null}>
<Outlet />
</ExtensionResourceProvider.Provider>
</ExtensionMount>
);
2026-10-08 16:53:20 -04:00
2026-10-05 18:10:18 -04:00
return options.server ? (
<ServerContext.Provider>
<SocketFixture />
2026-10-12 15:20:31 -04:00
<StatsListener />
2026-10-05 18:10:18 -04:00
{content}
</ServerContext.Provider>
) : (
content
);
}
2026-10-08 16:53:20 -04:00
2026-10-05 18:10:18 -04:00
const root = createRootRoute({ component: Root });
const authenticated = createRoute({ getParentRoute: () => root, id: 'authenticated', component: Outlet });
2026-10-07 17:29:34 -04:00
const routes = Object.values(SCREEN_ROOTS).map((path) => {
2026-10-05 18:10:18 -04:00
const parent = createRoute({ getParentRoute: () => authenticated, path, component: Outlet });
2026-10-08 16:53:20 -04:00
2026-10-05 18:10:18 -04:00
return parent.addChildren([
createRoute({ getParentRoute: () => parent, path: '/', component: RenderContent }),
createRoute({ getParentRoute: () => parent, path: '$', component: RenderContent }),
]);
});
const router = createRouter({
routeTree: root.addChildren([
authenticated.addChildren(routes),
createRoute({ getParentRoute: () => root, path: '$', component: RenderContent }),
]),
history: createMemoryHistory({
initialEntries: [
options.path ?? (options.server ? `/server/${options.server.attributes.identifier}` : '/account'),
],
}),
});
2026-10-08 16:53:20 -04:00
2026-10-05 18:10:18 -04:00
function Wrapper({ children }: { children?: ReactNode }) {
return (
<QueryClientProvider client={queryClient}>
<Content.Provider value={children}>
<RouterProvider router={router} />
</Content.Provider>
</QueryClientProvider>
);
}
2026-10-08 16:53:20 -04:00
2026-10-05 18:10:18 -04:00
return {
Wrapper,
queryClient,
navigate: async (destination) => {
const { pathname, ...navigation } = resolvePanelDestination(destination);
2026-10-08 16:53:20 -04:00
2026-10-05 18:10:18 -04:00
await router.navigate({ to: pathname as never, ...navigation, search: navigation.search as never });
},
location: () => {
const { pathname, search, state } = router.state.location;
2026-10-08 16:53:20 -04:00
2026-10-05 18:10:18 -04:00
return { pathname, search: { ...(search as PanelSearch) }, state: { ...state } };
},
emitWebsocket: (event, data) => {
socket.emit(event, data);
},
setConnected: (connected) => updateConnected(connected),
dispose: () => {
socket.removeAllListeners();
socket.close();
queryClient.clear();
},
};
}
2026-10-12 21:41:35 -04:00
/** The themes a test renders with. */
2026-10-12 19:13:11 -04:00
export interface TestThemeOptions {
/**
2026-10-12 21:41:35 -04:00
* The themes, oldest first, as the panel stacks them over classic: `[theme]`, or `[parent, child]`
* for a child theme. Each one's `Default` and the `below` of its recipes build on the theme before it.
2026-10-12 19:13:11 -04:00
*/
themes?: readonly ThemeDefinition[];
}
/** How layer failures name a theme of the chain: "theme" for the last, its parents "parent", "parent 2" and so on. */
function layerId(distance: number): string {
if (distance === 0) {
return 'theme';
}
return distance === 1 ? 'parent' : `parent ${distance}`;
}
/** Replaces the registered theme layers with the chain's skins, views and icons, parent first. */
function registerThemes(themes: readonly ThemeDefinition[]): void {
clearThemeLayers();
clearThemeSkins();
for (const [index, theme] of themes.entries()) {
const id = layerId(themes.length - 1 - index);
registerSkins(id, theme.ui ?? {});
registerViewLayer(id, 'theme', theme.views ?? {});
registerThemeIcons(theme.icons ?? {});
}
}
/** Loads the chunks of a theme's `lazyView` views, or those of a chain of themes, which `renderView` renders synchronously. */
export async function preloadTheme(theme: ThemeDefinition | readonly ThemeDefinition[]): Promise<void> {
const themes: readonly ThemeDefinition[] = 'length' in theme ? theme : [theme];
await Promise.all(
themes.flatMap((each) =>
Object.values(each.views ?? {}).map((view) => (view && isPendingLazyView(view) ? view.preload() : null))
)
);
}
export interface RenderViewOptions<N extends ViewName> extends TestThemeOptions {
2026-10-12 08:13:40 -04:00
/** Defaults to the view's first fixture. */
fixture?: string;
model?: ViewModel<N>;
input?: ViewInput<N>;
2026-10-12 19:14:14 -04:00
/** Passed to the view as `<View className>` would; it lands on the view's root element. */
className?: string;
2026-10-12 17:39:58 -04:00
/** Components to mount in slots, as an extension's `slots.register` would. */
slots?: TestSlots;
2026-10-12 21:41:35 -04:00
/** An extension's `ui.prefix`, so its prefixed classes merge with the view's as they do in the panel. */
prefix?: string;
2026-10-13 02:37:22 -04:00
/**
* Fail when a theme or extension layer throws, or when the themes leave out a slot classic renders for
* the same fixture (the default); false lets a layer fall back and slots go missing.
*/
2026-10-12 17:39:58 -04:00
strict?: boolean;
2026-10-12 08:13:40 -04:00
}
2026-10-12 17:39:58 -04:00
export type TestSlots = { readonly [N in SlotName]?: ComponentType<SlotComponentProps<SlotData<N>>> };
2026-10-12 08:13:40 -04:00
export interface RenderedView {
container: HTMLElement;
2026-10-12 17:39:58 -04:00
/** Throws what failed after the first render, such as a layer failing on a click. */
2026-10-12 08:13:40 -04:00
unmount(): void;
}
2026-10-12 17:39:58 -04:00
interface MountOptions {
2026-10-12 21:41:35 -04:00
themes?: readonly ThemeDefinition[];
2026-10-12 17:39:58 -04:00
slots?: TestSlots;
2026-10-12 21:41:35 -04:00
prefix?: string;
2026-10-12 17:39:58 -04:00
strict?: boolean;
}
2026-10-12 08:13:40 -04:00
const viewRouter = createRouter({
routeTree: createRootRoute(),
history: createMemoryHistory({ initialEntries: ['/'] }),
});
let rendered: RenderedView | undefined;
2026-10-12 21:41:35 -04:00
const viewContext = /^view "(.+)"$/;
/** Clears the failures recorded against view layers, so a render reads only its own. */
function clearLayerFailures(): void {
for (const { extensionId, context } of getExtensionErrors()) {
if (viewContext.test(context)) {
clearExtensionError(extensionId, context);
}
}
}
/** The first failure recorded against a view layer, as a `ViewLayerError`. */
function layerFailure(): ViewLayerError | undefined {
for (const { extensionId, context, message } of getExtensionErrors()) {
const view = viewContext.exec(context)?.[1];
if (view !== undefined) {
return new ViewLayerError(view, extensionId, new Error(message));
}
}
return undefined;
}
2026-10-12 17:39:58 -04:00
/**
2026-10-12 19:13:11 -04:00
* Replaces whatever was rendered before with `content`, under the themes' skins, views and icons, and
2026-10-12 17:39:58 -04:00
* throws when it fails to render (and, unless `strict` is false, when one of its layers falls back).
*/
2026-10-12 21:41:35 -04:00
function mount(content: ReactNode, { themes = [], slots = {}, prefix, strict = true }: MountOptions): RenderedView {
2026-10-12 08:13:40 -04:00
rendered?.unmount();
2026-10-12 21:41:35 -04:00
registerClassPrefixes([prefix]);
2026-10-12 19:13:11 -04:00
registerThemes(themes);
2026-10-12 21:41:35 -04:00
clearLayerFailures();
2026-10-12 08:13:40 -04:00
2026-10-12 17:39:58 -04:00
// Each slot's props are typed by its name where they are given.
const removeSlots = mountSlotComponents('test-slots', slots as Parameters<typeof mountSlotComponents>[1]);
const crashes: unknown[] = [];
2026-10-12 08:13:40 -04:00
const container = document.body.appendChild(document.createElement('div'));
2026-10-12 17:39:58 -04:00
const root = createRoot(container, { onUncaughtError: (error) => crashes.push(error) });
2026-10-12 21:41:35 -04:00
const failure = (): unknown => crashes.at(0) ?? (strict ? layerFailure() : undefined);
2026-10-12 17:39:58 -04:00
const current: RenderedView = {
container,
unmount: () => {
if (rendered !== current) {
return;
}
2026-10-12 08:13:40 -04:00
2026-10-12 17:39:58 -04:00
rendered = undefined;
act(() => root.unmount());
container.remove();
removeSlots();
const error = failure();
if (error !== undefined) {
throw error;
}
},
};
rendered = current;
2026-10-12 08:13:40 -04:00
Reflect.set(globalThis, 'IS_REACT_ACT_ENVIRONMENT', true);
2026-10-12 08:55:18 -04:00
act(() =>
root.render(
<QueryClientProvider client={queryClient}>
<RouterContextProvider router={viewRouter}>{content}</RouterContextProvider>
</QueryClientProvider>
)
);
2026-10-12 08:13:40 -04:00
2026-10-12 17:39:58 -04:00
if (failure() !== undefined) {
current.unmount();
}
return current;
2026-10-12 08:13:40 -04:00
}
2026-10-12 08:55:18 -04:00
2026-10-13 02:37:22 -04:00
const AREA_LAYOUTS = new Set(['layout.account', 'layout.server', 'layout.admin']);
2026-10-12 19:13:11 -04:00
const pendingViews = (themes: readonly ThemeDefinition[]): string[] =>
themes.flatMap((theme) =>
Object.entries(theme.views ?? {}).flatMap(([name, view]) => (view && isPendingLazyView(view) ? [name] : []))
2026-10-12 16:11:44 -04:00
);
2026-10-12 08:55:18 -04:00
/**
2026-10-12 21:41:35 -04:00
* Renders a view synchronously from fixtures, with the layers of `themes` over classic. Each call
* replaces what was rendered before it; nested views read their fixtures too. Await
* `preloadTheme(themes)` first when the themes have lazy views. It throws when the view fails to
* render, and when a theme or extension layer throws unless `strict` is false.
2026-10-12 08:55:18 -04:00
*/
export function renderView<N extends ViewName>(name: N, options: RenderViewOptions<N> = {}): RenderedView {
2026-10-12 21:41:35 -04:00
const { themes = [] } = options;
2026-10-12 19:13:11 -04:00
const pending = pendingViews(themes);
2026-10-12 16:11:44 -04:00
if (pending.length) {
throw new Error(
`The theme's views ${pending.join(', ')} are lazy and not loaded yet. ` +
'Await preloadTheme(theme) before renderView, for example in beforeAll.'
);
}
2026-10-12 08:55:18 -04:00
// The model is the one of the view being rendered.
const models = options.model === undefined ? undefined : ({ [name]: options.model } as Partial<ViewModels>);
const fixtures = options.fixture === undefined ? undefined : { [name]: options.fixture };
2026-10-13 02:37:22 -04:00
const content = (
2026-10-12 08:55:18 -04:00
<ViewFixtureProvider fixtures={fixtures} models={models}>
2026-10-12 19:14:14 -04:00
<LooseView name={name} className={options.className} {...Object(options.input ?? {})} />
2026-10-13 02:37:22 -04:00
</ViewFixtureProvider>
2026-10-12 08:55:18 -04:00
);
2026-10-13 02:37:22 -04:00
const strict = options.strict ?? true;
const mountOptions = { slots: options.slots, prefix: options.prefix, strict };
if (!strict || !themes.length) {
return mount(content, { ...mountOptions, themes });
}
// The slots classic renders here, which extensions may mount in, must survive the themes. A slot counts
// only while a view that renders it is on the page: a theme can move a view, and its slots go with it. A
// theme's app layout draws the area layouts' navigation, so their slots are its to render.
mount(content, { ...mountOptions, themes: [] });
const expected = mountedSlots();
const view = mount(content, { ...mountOptions, themes });
const shell = themes.some((theme) => theme.views?.['layout.app']);
const owned = new Set<string>(
[...mountedViews()]
.filter((viewName) => !(shell && AREA_LAYOUTS.has(viewName)))
.flatMap((viewName) => getViewDefinition(viewName)?.slots ?? [])
);
const missing = [...expected].filter((slot) => owned.has(slot) && !mountedSlots().has(slot));
if (missing.length) {
view.unmount();
throw new ViewLayerError(
name,
layerId(0),
new Error(
`The themes leave out the ${missing.map((slot) => `"${slot}"`).join(', ')} slot${missing.length > 1 ? 's' : ''} ` +
'that classic renders here, so extensions mounted there disappear. Render <Slot name="…" /> or <Default />.'
)
);
}
return view;
2026-10-12 08:55:18 -04:00
}
/**
2026-10-12 21:41:35 -04:00
* Renders any element synchronously with the skins, views and icons of `themes` over classic's, such
* as a UI kit primitive: `renderWithTheme(<Button>Save</Button>, { themes: [theme] })`. Each call
* replaces what was rendered before it.
2026-10-12 08:55:18 -04:00
*/
2026-10-12 21:41:35 -04:00
export function renderWithTheme(element: ReactElement, options: TestThemeOptions = {}): RenderedView {
return mount(element, { themes: options.themes });
2026-10-12 08:55:18 -04:00
}