mirror of
https://github.com/pterodactyl/panel.git
synced 2026-12-02 12:25:44 -05:00
theme tooling
This commit is contained in:
@@ -7,6 +7,7 @@ import { router } from '@/router/router';
|
||||
import { setupInterceptors } from '@/api/interceptors';
|
||||
import AppToaster from '@/components/elements/AppToaster';
|
||||
import { ThemeFailureNotice } from '@/views/boot';
|
||||
import { ViewInspector } from '@/views/inspector/ViewInspector';
|
||||
import { ViewSessionProvider } from '@/views/session';
|
||||
|
||||
setupInterceptors();
|
||||
@@ -19,7 +20,9 @@ const App = () => {
|
||||
return (
|
||||
<QueryClientProvider client={queryClient}>
|
||||
<ViewSessionProvider>
|
||||
<RouterProvider router={router} />
|
||||
<ViewInspector>
|
||||
<RouterProvider router={router} />
|
||||
</ViewInspector>
|
||||
</ViewSessionProvider>
|
||||
<AppToaster />
|
||||
<ThemeFailureNotice />
|
||||
|
||||
@@ -0,0 +1,36 @@
|
||||
import { Component, type ReactNode } from 'react';
|
||||
|
||||
interface State {
|
||||
error: Error | null;
|
||||
}
|
||||
|
||||
/** Shows why a fixture failed to render instead of taking the workbench down with it. */
|
||||
export default class FixtureBoundary extends Component<{ children?: ReactNode }, State> {
|
||||
state: State = { error: null };
|
||||
|
||||
static getDerivedStateFromError(cause: unknown): State {
|
||||
return { error: cause instanceof Error ? cause : new Error(String(cause)) };
|
||||
}
|
||||
|
||||
render() {
|
||||
const { error } = this.state;
|
||||
|
||||
if (!error) {
|
||||
return this.props.children;
|
||||
}
|
||||
|
||||
return (
|
||||
<div role='alert' className='m-4 rounded-sm border border-destructive/40 bg-destructive/10 p-4 text-sm'>
|
||||
<p className='font-medium text-destructive'>This fixture failed to render.</p>
|
||||
<pre className='mt-2 whitespace-pre-wrap font-mono text-xs text-foreground'>{error.message}</pre>
|
||||
<button
|
||||
type='button'
|
||||
className='mt-3 rounded-sm border border-border bg-popover px-2 py-1 text-xs hover:bg-secondary'
|
||||
onClick={() => this.setState({ error: null })}
|
||||
>
|
||||
Retry
|
||||
</button>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,167 @@
|
||||
import { useEffect, useRef, useState, type ReactNode } from 'react';
|
||||
import { createPortal } from 'react-dom';
|
||||
import { onThemeChange } from '@/lib/theme';
|
||||
import type { ThemeScheme } from '@/views/theme';
|
||||
import { registerInspectableFrame } from '@/views/inspector/frames';
|
||||
import { isElement } from '@/views/inspector/geometry';
|
||||
|
||||
const FRAME_DOCUMENT =
|
||||
'<!doctype html><html><head><meta charset="utf-8"><style>body{margin:0}#root{display:flow-root}</style></head><body><div id="root"></div></body></html>';
|
||||
const MAX_HEIGHT = 4000;
|
||||
|
||||
const isStylesheet = (node: Element): node is HTMLLinkElement | HTMLStyleElement =>
|
||||
node instanceof HTMLStyleElement || (node instanceof HTMLLinkElement && node.relList.contains('stylesheet'));
|
||||
|
||||
/**
|
||||
* Keeps a frame's stylesheets, `<html>` attributes and body class equal to the panel's, so the active
|
||||
* theme and any live setting preview apply, with the frame's own colour scheme.
|
||||
*/
|
||||
export function mirrorDocument(target: Document, scheme: ThemeScheme, clones: Map<Element, Element>): void {
|
||||
const sources = [...document.head.children].filter(isStylesheet);
|
||||
|
||||
for (const [source, clone] of clones) {
|
||||
if (!sources.some((candidate) => candidate === source)) {
|
||||
clone.remove();
|
||||
clones.delete(source);
|
||||
}
|
||||
}
|
||||
|
||||
for (const source of sources) {
|
||||
const clone = clones.get(source);
|
||||
|
||||
if (clone?.outerHTML !== source.outerHTML) {
|
||||
const fresh = target.importNode(source, true);
|
||||
|
||||
clones.set(source, fresh);
|
||||
if (clone) {
|
||||
clone.replaceWith(fresh);
|
||||
} else {
|
||||
target.head.append(fresh);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
const html = target.documentElement;
|
||||
|
||||
for (const name of html.getAttributeNames()) {
|
||||
html.removeAttribute(name);
|
||||
}
|
||||
|
||||
for (const { name, value } of document.documentElement.attributes) {
|
||||
html.setAttribute(name, value);
|
||||
}
|
||||
|
||||
html.classList.remove('dark', 'light');
|
||||
html.classList.add(scheme);
|
||||
target.body.className = document.body.className;
|
||||
}
|
||||
|
||||
/** Links and forms inside a preview must not navigate the panel around it. */
|
||||
function holdNavigation(event: Event) {
|
||||
if (event.type === 'submit' || (isElement(event.target) && event.target.closest('a[href]'))) {
|
||||
event.preventDefault();
|
||||
}
|
||||
}
|
||||
|
||||
export interface PreviewFrameProps {
|
||||
label: string;
|
||||
/** CSS pixels the frame is wide, laid out at that viewport width. */
|
||||
width: number;
|
||||
/** Below 1 when the frame is shrunk to fit beside the workbench panels. */
|
||||
scale: number;
|
||||
scheme: ThemeScheme;
|
||||
children?: ReactNode;
|
||||
}
|
||||
|
||||
/**
|
||||
* Renders its children in a same-origin frame, so media queries see the preset viewport width and the
|
||||
* scheme applies to the preview alone. The children stay in this React tree and keep its context.
|
||||
*/
|
||||
export default function PreviewFrame({ label, width, scale, scheme, children }: PreviewFrameProps) {
|
||||
const [frame, setFrame] = useState<HTMLIFrameElement | null>(null);
|
||||
const [root, setRoot] = useState<HTMLElement | null>(null);
|
||||
const [height, setHeight] = useState(0);
|
||||
const schemeRef = useRef(scheme);
|
||||
|
||||
useEffect(() => {
|
||||
if (!frame) {
|
||||
return;
|
||||
}
|
||||
|
||||
let stop = () => {};
|
||||
|
||||
const ready = () => {
|
||||
const target = frame.contentDocument;
|
||||
const mount = target?.getElementById('root');
|
||||
|
||||
if (!target || !mount) {
|
||||
return;
|
||||
}
|
||||
|
||||
stop();
|
||||
|
||||
const clones = new Map<Element, Element>();
|
||||
const sync = () => mirrorDocument(target, schemeRef.current, clones);
|
||||
const measure = () => setHeight(Math.min(Math.ceil(mount.getBoundingClientRect().height), MAX_HEIGHT));
|
||||
const observer = new ResizeObserver(measure);
|
||||
// Resize observations wait for rendering, which a hidden tab skips; mutations do not.
|
||||
const mutations = new MutationObserver(measure);
|
||||
|
||||
sync();
|
||||
observer.observe(mount);
|
||||
mutations.observe(mount, { childList: true, subtree: true, attributes: true, characterData: true });
|
||||
target.addEventListener('click', holdNavigation, true);
|
||||
target.addEventListener('submit', holdNavigation, true);
|
||||
|
||||
const unwatch = onThemeChange(sync);
|
||||
const unregister = registerInspectableFrame(frame);
|
||||
|
||||
stop = () => {
|
||||
unwatch();
|
||||
unregister();
|
||||
observer.disconnect();
|
||||
mutations.disconnect();
|
||||
target.removeEventListener('click', holdNavigation, true);
|
||||
target.removeEventListener('submit', holdNavigation, true);
|
||||
};
|
||||
|
||||
setRoot(mount);
|
||||
};
|
||||
|
||||
frame.addEventListener('load', ready);
|
||||
// The srcdoc may have loaded before this effect ran.
|
||||
ready();
|
||||
|
||||
return () => {
|
||||
frame.removeEventListener('load', ready);
|
||||
stop();
|
||||
};
|
||||
}, [frame]);
|
||||
|
||||
useEffect(() => {
|
||||
schemeRef.current = scheme;
|
||||
|
||||
const html = root?.ownerDocument.documentElement;
|
||||
|
||||
html?.classList.remove('dark', 'light');
|
||||
html?.classList.add(scheme);
|
||||
}, [root, scheme]);
|
||||
|
||||
return (
|
||||
<div className='overflow-hidden' style={{ width: width * scale, height: height * scale }}>
|
||||
<iframe
|
||||
ref={setFrame}
|
||||
title={label}
|
||||
srcDoc={FRAME_DOCUMENT}
|
||||
className='block border-0 bg-background'
|
||||
style={{
|
||||
width,
|
||||
height,
|
||||
transform: scale < 1 ? `scale(${scale})` : undefined,
|
||||
transformOrigin: '0 0',
|
||||
}}
|
||||
/>
|
||||
{root && createPortal(children, root)}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,74 @@
|
||||
import { useState } from 'react';
|
||||
import type { WorkbenchWidth } from '@/router/search';
|
||||
import type { UiPrimitive } from '@/themes/gallery';
|
||||
import { CodeLine, ModelTree, Section } from '@/views/inspector/parts';
|
||||
import type { ThemeScheme } from '@/views/theme';
|
||||
import FixtureBoundary from './FixtureBoundary';
|
||||
import PreviewFrame from './PreviewFrame';
|
||||
import { frameSize, useWidth } from './stage';
|
||||
|
||||
export interface PrimitivePreviewProps {
|
||||
name: string;
|
||||
primitive: UiPrimitive;
|
||||
scheme: ThemeScheme;
|
||||
width: WorkbenchWidth;
|
||||
}
|
||||
|
||||
/** Every sample of a UI kit primitive in one frame, with the props each renders with. */
|
||||
export default function PrimitivePreview({ name, primitive, scheme, width }: PrimitivePreviewProps) {
|
||||
const [stage, setStage] = useState<HTMLElement | null>(null);
|
||||
const available = useWidth(stage);
|
||||
const size = frameSize(width, available);
|
||||
const samples = Object.entries(primitive.samples);
|
||||
|
||||
return (
|
||||
<div className='flex min-w-0 flex-1 flex-col xl:flex-row'>
|
||||
<section className='min-w-0 flex-1 p-4 lg:p-6'>
|
||||
<header className='mb-4 flex flex-wrap items-baseline gap-x-3'>
|
||||
<h2 className='font-mono text-lg font-semibold text-foreground'>{name}</h2>
|
||||
<span className='text-xs text-muted-foreground'>UI kit primitive · {samples.length} samples</span>
|
||||
</header>
|
||||
<div ref={setStage}>
|
||||
{available > 0 && (
|
||||
<div className='rounded-sm ring-1 ring-border'>
|
||||
<PreviewFrame label={name} width={size.width} scale={size.scale} scheme={scheme}>
|
||||
<div className='grid grid-cols-[repeat(auto-fill,minmax(16rem,1fr))] gap-6 p-6'>
|
||||
{samples.map(([variant, sample]) => (
|
||||
<div key={variant} className='min-w-0'>
|
||||
<p className='mb-2 font-mono text-xs text-muted-foreground'>{variant}</p>
|
||||
<FixtureBoundary>{sample}</FixtureBoundary>
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
</PreviewFrame>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
</section>
|
||||
<aside
|
||||
aria-label='Primitive details'
|
||||
className='w-full shrink-0 border-t border-border bg-card xl:w-96 xl:border-t-0 xl:border-l'
|
||||
>
|
||||
<Section title='Skin'>
|
||||
<div className='space-y-2'>
|
||||
<CodeLine code={`${name}: skin('${name}', { /* parts */ }),`} />
|
||||
<CodeLine code={`npx pterodactyl-theme skins ${name}`} />
|
||||
<p className='text-xs text-muted-foreground'>
|
||||
The command prints classic's skin for {name} to start from.
|
||||
</p>
|
||||
</div>
|
||||
</Section>
|
||||
<Section title='Sample props'>
|
||||
<div className='space-y-3'>
|
||||
{samples.map(([variant, sample]) => (
|
||||
<div key={variant}>
|
||||
<p className='mb-1 font-mono text-xs text-foreground'>{variant}</p>
|
||||
<ModelTree value={sample.props} />
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
</Section>
|
||||
</aside>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,187 @@
|
||||
import { useEffect } from 'react';
|
||||
import { Link, useNavigate, useSearch } from '@tanstack/react-router';
|
||||
import { LayoutTemplate } from 'lucide-react';
|
||||
import { getBootstrapTheme } from '@/bootstrap';
|
||||
import { parseWorkbenchSearch, type WorkbenchSearch, type WorkbenchWidth } from '@/router/search';
|
||||
import { getUiPrimitive, uiPrimitives } from '@/themes/gallery';
|
||||
import '@/views/catalog';
|
||||
import { CodeLine } from '@/views/inspector/parts';
|
||||
import { useViewDefinitions } from '@/views/registry';
|
||||
import { useTheme, type ThemeScheme } from '@/views/theme';
|
||||
import PrimitivePreview from './PrimitivePreview';
|
||||
import { Segmented } from './stage';
|
||||
import ViewPreview from './ViewPreview';
|
||||
import WorkbenchSidebar from './WorkbenchSidebar';
|
||||
|
||||
const widths: { value: WorkbenchWidth; label: string }[] = [
|
||||
{ value: 'phone', label: 'Phone 390' },
|
||||
{ value: 'tablet', label: 'Tablet 820' },
|
||||
{ value: 'desktop', label: 'Desktop 1280' },
|
||||
{ value: 'full', label: 'Full' },
|
||||
];
|
||||
|
||||
function Welcome() {
|
||||
const definitions = useViewDefinitions();
|
||||
const { inspect } = getBootstrapTheme();
|
||||
const withFixtures = definitions.filter((definition) => Object.keys(definition.fixtures ?? {}).length > 0);
|
||||
|
||||
return (
|
||||
<div className='mx-auto max-w-2xl space-y-6 p-6 lg:p-10'>
|
||||
<div>
|
||||
<h2 className='text-xl font-semibold text-foreground'>Design every view without a backend</h2>
|
||||
<p className='mt-2 text-sm leading-relaxed text-foreground/80'>
|
||||
Pick a view to render it from its fixtures through classic, the active theme and every extension
|
||||
layer, at a phone, tablet or desktop width and in either colour scheme. The UI kit shows each
|
||||
primitive in all its variants.
|
||||
</p>
|
||||
</div>
|
||||
<dl className='grid grid-cols-3 gap-3 text-center'>
|
||||
{[
|
||||
{ label: 'Views', value: definitions.length },
|
||||
{ label: 'With fixtures', value: withFixtures.length },
|
||||
{ label: 'Primitives', value: Object.keys(uiPrimitives).length },
|
||||
].map((stat) => (
|
||||
<div key={stat.label} className='rounded-sm border border-border bg-card p-3'>
|
||||
<dt className='text-xs text-muted-foreground'>{stat.label}</dt>
|
||||
<dd className='text-2xl font-semibold tabular-nums text-foreground'>{stat.value}</dd>
|
||||
</div>
|
||||
))}
|
||||
</dl>
|
||||
<ul className='space-y-2 text-sm text-foreground/80'>
|
||||
<li>
|
||||
<kbd className='rounded-xs border border-border px-1 font-mono text-xs'>/</kbd> searches views.
|
||||
</li>
|
||||
<li>
|
||||
{inspect ? (
|
||||
<>
|
||||
<kbd className='rounded-xs border border-border px-1 font-mono text-xs'>Alt+Shift+I</kbd>{' '}
|
||||
inspects any view on any page, previews here included.
|
||||
</>
|
||||
) : (
|
||||
<>
|
||||
<a href='/panel/theme-workbench?inspect=1' className='text-accent hover:underline'>
|
||||
Turn on the inspector
|
||||
</a>{' '}
|
||||
to pick any view on any page and see its layers, model and tokens.
|
||||
</>
|
||||
)}
|
||||
</li>
|
||||
</ul>
|
||||
<div className='space-y-2'>
|
||||
<p className='text-sm text-foreground/80'>
|
||||
In a theme project, list views and eject classic's source:
|
||||
</p>
|
||||
<CodeLine code='npx pterodactyl-theme list' />
|
||||
<CodeLine code='npx pterodactyl-theme eject dashboard.serverCard' />
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
function Missing({ name }: { name: string }) {
|
||||
return (
|
||||
<div className='p-6 text-sm text-muted-foreground lg:p-10'>
|
||||
No view or primitive is named <span className='font-mono text-foreground'>{name}</span>. Extension views
|
||||
appear once their extension has loaded.
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
/** `/panel/theme-workbench`: views and the UI kit rendered from fixtures, for theme authors. */
|
||||
export default function ThemeWorkbench() {
|
||||
const search = parseWorkbenchSearch(useSearch({ strict: false }));
|
||||
const navigate = useNavigate();
|
||||
const theme = useTheme();
|
||||
const { preview, safeMode } = getBootstrapTheme();
|
||||
const definitions = useViewDefinitions();
|
||||
const scheme: ThemeScheme = search.scheme && theme.schemes.includes(search.scheme) ? search.scheme : theme.scheme;
|
||||
const width = search.width ?? 'full';
|
||||
const definition = search.view ? definitions.find((candidate) => candidate.name === search.view) : undefined;
|
||||
const primitive = search.ui ? getUiPrimitive(search.ui) : undefined;
|
||||
const update = (next: Partial<WorkbenchSearch>) =>
|
||||
void navigate({ to: '.', search: { ...search, ...next }, replace: true, viewTransition: false });
|
||||
|
||||
useEffect(() => {
|
||||
document.title = 'Admin · Theme workbench';
|
||||
}, []);
|
||||
|
||||
const content = () => {
|
||||
if (definition) {
|
||||
return (
|
||||
<ViewPreview
|
||||
key={definition.name}
|
||||
definition={definition}
|
||||
search={search}
|
||||
scheme={scheme}
|
||||
width={width}
|
||||
onFixture={(fixture) => update({ fixture })}
|
||||
/>
|
||||
);
|
||||
}
|
||||
|
||||
if (search.ui && primitive) {
|
||||
return (
|
||||
<PrimitivePreview
|
||||
key={search.ui}
|
||||
name={search.ui}
|
||||
primitive={primitive}
|
||||
scheme={scheme}
|
||||
width={width}
|
||||
/>
|
||||
);
|
||||
}
|
||||
|
||||
const missing = search.view ?? search.ui;
|
||||
|
||||
return missing ? <Missing name={missing} /> : <Welcome />;
|
||||
};
|
||||
|
||||
return (
|
||||
// The inspector reaches into the previews and leaves the workbench's own controls usable.
|
||||
<div data-inspector className='flex flex-col lg:h-[calc(100dvh-3.5rem)]'>
|
||||
<div className='flex flex-wrap items-center gap-3 border-b border-border bg-card px-4 py-2'>
|
||||
<div className='flex min-w-0 flex-wrap items-center gap-2'>
|
||||
<LayoutTemplate className='h-4 w-4 text-muted-foreground' aria-hidden />
|
||||
<h1 className='text-sm font-semibold text-foreground'>Theme workbench</h1>
|
||||
<span className='font-mono text-xs text-muted-foreground' title='The layer chain, bottom first'>
|
||||
{['classic', ...theme.chain.map((entry) => entry.id)].join(' → ')}
|
||||
</span>
|
||||
{preview && (
|
||||
<span className='rounded-sm bg-accent/15 px-1.5 py-0.5 text-xs text-accent'>Previewing</span>
|
||||
)}
|
||||
{safeMode && (
|
||||
<span className='rounded-sm bg-warning/15 px-1.5 py-0.5 text-xs text-warning'>Safe mode</span>
|
||||
)}
|
||||
</div>
|
||||
<div className='ml-auto flex flex-wrap items-center gap-2'>
|
||||
<Segmented
|
||||
label='Colour scheme'
|
||||
value={scheme}
|
||||
onChange={(value) => update({ scheme: value })}
|
||||
options={(['dark', 'light'] as const).map((value) => ({
|
||||
value,
|
||||
label: value === 'dark' ? 'Dark' : 'Light',
|
||||
disabled: !theme.schemes.includes(value),
|
||||
title: theme.schemes.includes(value) ? undefined : `${theme.id} does not offer ${value}`,
|
||||
}))}
|
||||
/>
|
||||
<Segmented
|
||||
label='Viewport'
|
||||
value={width}
|
||||
onChange={(value) => update({ width: value === 'full' ? undefined : value })}
|
||||
options={widths}
|
||||
/>
|
||||
<Link to='/panel/themes' className='text-xs text-accent hover:underline'>
|
||||
Themes
|
||||
</Link>
|
||||
</div>
|
||||
</div>
|
||||
<div className='flex min-h-0 flex-1 flex-col lg:flex-row'>
|
||||
<aside className='h-72 shrink-0 border-b border-border bg-card lg:h-auto lg:w-72 lg:border-r lg:border-b-0'>
|
||||
<WorkbenchSidebar search={search} />
|
||||
</aside>
|
||||
<div className='flex min-w-0 flex-1 overflow-y-auto'>{content()}</div>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,400 @@
|
||||
import { Suspense, useCallback, useContext, useMemo, useState, useSyncExternalStore } from 'react';
|
||||
import { Link } from '@tanstack/react-router';
|
||||
import { DatabaseZap } from 'lucide-react';
|
||||
import Spinner from '@/components/elements/Spinner';
|
||||
import { Empty, EmptyDescription, EmptyHeader, EmptyMedia, EmptyTitle } from '@/components/ui/empty';
|
||||
import { cn } from '@/lib/cn';
|
||||
import type { WorkbenchSearch, WorkbenchWidth } from '@/router/search';
|
||||
import { ServerContext } from '@/state/server/context';
|
||||
import { ViewInspectionContext, type ViewInspection, type ViewProbe } from '@/views/inspect';
|
||||
import { modelJson } from '@/views/inspector/model';
|
||||
import { CopyButton, LayerStack, ModelTree, OverrideHelp, Section, SlotList } from '@/views/inspector/parts';
|
||||
import { renderingLayer } from '@/views/inspector/snippets';
|
||||
import { getViewChain, getViewDefinition, useViewDefinitions, type ViewDefinition } from '@/views/registry';
|
||||
import type { ThemeScheme } from '@/views/theme';
|
||||
import { LooseView, ViewFixtureProvider } from '@/views/View';
|
||||
import FixtureBoundary from './FixtureBoundary';
|
||||
import PreviewFrame from './PreviewFrame';
|
||||
import { frameSize, useWidth } from './stage';
|
||||
|
||||
export const ALL_FIXTURES = '*';
|
||||
|
||||
type NestedFixtures = Readonly<Record<string, string>>;
|
||||
|
||||
interface FrameOptions {
|
||||
definition: ViewDefinition;
|
||||
nested: NestedFixtures;
|
||||
/** A page view rendered inside a layout preview. */
|
||||
content: string | null;
|
||||
scheme: ThemeScheme;
|
||||
width: WorkbenchWidth;
|
||||
available: number;
|
||||
}
|
||||
|
||||
function RoutedContent({ page }: { page: string | null }) {
|
||||
if (page) {
|
||||
return <LooseView name={page} />;
|
||||
}
|
||||
|
||||
return (
|
||||
<div className='m-4 flex min-h-48 items-center justify-center rounded-sm border-2 border-dashed border-border p-8 text-sm text-muted-foreground'>
|
||||
The routed page renders here.
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
function FixtureFrame({
|
||||
fixture,
|
||||
options,
|
||||
focused,
|
||||
onFocus,
|
||||
onProbe,
|
||||
}: {
|
||||
fixture: string;
|
||||
options: FrameOptions;
|
||||
focused: boolean;
|
||||
onFocus: (() => void) | null;
|
||||
onProbe: (fixture: string, probe: ViewProbe) => () => void;
|
||||
}) {
|
||||
const { definition, nested, content, scheme, width, available } = options;
|
||||
const parent = useContext(ViewInspectionContext);
|
||||
const wrap = parent?.wrap ?? false;
|
||||
const inspection = useMemo<ViewInspection>(
|
||||
() => ({ wrap, collect: (probe) => onProbe(fixture, probe) }),
|
||||
[wrap, onProbe, fixture]
|
||||
);
|
||||
const fixtures = useMemo(() => ({ ...nested, [definition.name]: fixture }), [nested, definition.name, fixture]);
|
||||
const size = frameSize(width, available);
|
||||
const rendered = (
|
||||
<LooseView name={definition.name}>
|
||||
{definition.kind === 'layout' ? <RoutedContent page={content} /> : null}
|
||||
</LooseView>
|
||||
);
|
||||
// Pages and layouts bring their own spacing; a block sits in some, as it would on a page.
|
||||
const view = definition.kind === 'block' ? <div className='p-4'>{rendered}</div> : rendered;
|
||||
|
||||
return (
|
||||
<figure className='min-w-0'>
|
||||
<figcaption className='mb-1.5 flex items-center gap-2 text-xs text-muted-foreground'>
|
||||
{onFocus ? (
|
||||
<button
|
||||
type='button'
|
||||
className={cn('font-mono hover:text-foreground', focused && 'text-foreground underline')}
|
||||
onClick={onFocus}
|
||||
>
|
||||
{fixture}
|
||||
</button>
|
||||
) : (
|
||||
<span className='font-mono text-foreground'>{fixture}</span>
|
||||
)}
|
||||
<span>
|
||||
{size.width}px{size.scale < 1 && ` at ${Math.round(size.scale * 100)}%`}
|
||||
</span>
|
||||
</figcaption>
|
||||
<div className={cn('rounded-sm ring-1 ring-border', focused && onFocus && 'ring-2 ring-primary')}>
|
||||
<PreviewFrame
|
||||
label={`${definition.name}: ${fixture}`}
|
||||
width={size.width}
|
||||
scale={size.scale}
|
||||
scheme={scheme}
|
||||
>
|
||||
<ViewInspectionContext.Provider value={inspection}>
|
||||
<ViewFixtureProvider fixtures={fixtures}>
|
||||
<Suspense fallback={<Spinner size='large' centered />}>
|
||||
<FixtureBoundary key={`${definition.name}:${fixture}:${content}`}>
|
||||
{definition.context === 'server' ? (
|
||||
<ServerContext.Provider>{view}</ServerContext.Provider>
|
||||
) : (
|
||||
view
|
||||
)}
|
||||
</FixtureBoundary>
|
||||
</Suspense>
|
||||
</ViewFixtureProvider>
|
||||
</ViewInspectionContext.Provider>
|
||||
</PreviewFrame>
|
||||
</div>
|
||||
</figure>
|
||||
);
|
||||
}
|
||||
|
||||
function NoFixtures({ name }: { name: string }) {
|
||||
return (
|
||||
<Empty className='border bg-card'>
|
||||
<EmptyHeader>
|
||||
<EmptyMedia variant='icon'>
|
||||
<DatabaseZap />
|
||||
</EmptyMedia>
|
||||
<EmptyTitle>No fixtures yet</EmptyTitle>
|
||||
<EmptyDescription>
|
||||
<span className='font-mono'>{name}</span> still renders the panel's own component from live
|
||||
data, so it cannot render here without a backend. You can still override it; its layers and snippet
|
||||
are beside this.
|
||||
</EmptyDescription>
|
||||
</EmptyHeader>
|
||||
</Empty>
|
||||
);
|
||||
}
|
||||
|
||||
function ProbeDetails({ probe }: { probe: ViewProbe }) {
|
||||
const view = useSyncExternalStore(probe.subscribe, probe.current);
|
||||
const hasInputs = Object.keys(view.inputs).length > 0;
|
||||
|
||||
return (
|
||||
<>
|
||||
<Section title='Layers' count={view.layers.length}>
|
||||
<LayerStack view={view} />
|
||||
</Section>
|
||||
<Section title='Model'>
|
||||
<div className='mb-2 flex justify-end'>
|
||||
<CopyButton text={modelJson(view.model)} label='Copy JSON' />
|
||||
</div>
|
||||
<ModelTree value={view.model} />
|
||||
</Section>
|
||||
{hasInputs && (
|
||||
<Section title='Inputs' open={false}>
|
||||
<ModelTree value={view.inputs} />
|
||||
</Section>
|
||||
)}
|
||||
</>
|
||||
);
|
||||
}
|
||||
|
||||
function NestedViews({
|
||||
probes,
|
||||
root,
|
||||
nested,
|
||||
search,
|
||||
onNested,
|
||||
}: {
|
||||
probes: readonly ViewProbe[];
|
||||
root: string;
|
||||
nested: NestedFixtures;
|
||||
search: WorkbenchSearch;
|
||||
onNested: (name: string, fixture: string) => void;
|
||||
}) {
|
||||
const names = [...new Set(probes.map((probe) => probe.current().definition.name))].filter((name) => name !== root);
|
||||
|
||||
if (!names.length) {
|
||||
return null;
|
||||
}
|
||||
|
||||
return (
|
||||
<Section title='Nested views' count={names.length}>
|
||||
<ul className='space-y-2'>
|
||||
{names.map((name) => {
|
||||
const fixtures = Object.keys(getViewDefinition(name)?.fixtures ?? {});
|
||||
|
||||
return (
|
||||
<li key={name} className='flex items-center gap-2'>
|
||||
<Link
|
||||
to='/panel/theme-workbench'
|
||||
search={{ ...search, ui: undefined, view: name, fixture: undefined }}
|
||||
className='min-w-0 flex-1 truncate font-mono text-xs text-accent hover:underline'
|
||||
>
|
||||
{name}
|
||||
</Link>
|
||||
{fixtures.length > 1 && (
|
||||
<select
|
||||
aria-label={`Fixture of ${name}`}
|
||||
className='rounded-sm border border-border bg-background py-0.5 pr-7 pl-2 text-xs text-foreground'
|
||||
value={nested[name] ?? fixtures[0]}
|
||||
onChange={(event) => onNested(name, event.target.value)}
|
||||
>
|
||||
{fixtures.map((fixture) => (
|
||||
<option key={fixture} value={fixture}>
|
||||
{fixture}
|
||||
</option>
|
||||
))}
|
||||
</select>
|
||||
)}
|
||||
</li>
|
||||
);
|
||||
})}
|
||||
</ul>
|
||||
</Section>
|
||||
);
|
||||
}
|
||||
|
||||
function FixtureTabs({
|
||||
fixtures,
|
||||
current,
|
||||
onSelect,
|
||||
}: {
|
||||
fixtures: readonly string[];
|
||||
current: string;
|
||||
onSelect: (fixture: string) => void;
|
||||
}) {
|
||||
return (
|
||||
<div role='tablist' aria-label='Fixtures' className='flex flex-wrap gap-1'>
|
||||
{[...fixtures, ...(fixtures.length > 1 ? [ALL_FIXTURES] : [])].map((fixture) => (
|
||||
<button
|
||||
key={fixture}
|
||||
type='button'
|
||||
role='tab'
|
||||
aria-selected={fixture === current}
|
||||
className={cn(
|
||||
'rounded-sm border px-2.5 py-1 font-mono text-xs transition-colors',
|
||||
fixture === current
|
||||
? 'border-primary bg-primary/10 text-foreground'
|
||||
: 'border-border text-muted-foreground hover:text-foreground'
|
||||
)}
|
||||
onClick={() => onSelect(fixture)}
|
||||
>
|
||||
{fixture === ALL_FIXTURES ? 'All side by side' : fixture}
|
||||
</button>
|
||||
))}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
function PageInside({ value, onChange }: { value: string | null; onChange: (page: string | null) => void }) {
|
||||
const pages = useViewDefinitions().filter((page) => page.kind === 'page' && page.fixtures);
|
||||
|
||||
return (
|
||||
<label className='flex items-center gap-2 text-xs text-muted-foreground'>
|
||||
Page inside
|
||||
<select
|
||||
className='rounded-sm border border-border bg-background py-0.5 pr-7 pl-2 text-xs text-foreground'
|
||||
value={value ?? ''}
|
||||
onChange={(event) => onChange(event.target.value || null)}
|
||||
>
|
||||
<option value=''>Placeholder</option>
|
||||
{pages.map((page) => (
|
||||
<option key={page.name} value={page.name}>
|
||||
{page.name}
|
||||
</option>
|
||||
))}
|
||||
</select>
|
||||
</label>
|
||||
);
|
||||
}
|
||||
|
||||
function PreviewDetails({
|
||||
definition,
|
||||
probes,
|
||||
nested,
|
||||
search,
|
||||
onNested,
|
||||
}: {
|
||||
definition: ViewDefinition;
|
||||
probes: readonly ViewProbe[];
|
||||
nested: NestedFixtures;
|
||||
search: WorkbenchSearch;
|
||||
onNested: (name: string, fixture: string) => void;
|
||||
}) {
|
||||
const root = probes.find((probe) => probe.current().definition.name === definition.name);
|
||||
const slots = definition.slots ?? [];
|
||||
|
||||
return (
|
||||
<aside
|
||||
aria-label='View details'
|
||||
className='w-full shrink-0 border-t border-border bg-card xl:w-96 xl:border-t-0 xl:border-l'
|
||||
>
|
||||
<Section title='Override'>
|
||||
<OverrideHelp name={definition.name} />
|
||||
</Section>
|
||||
{root ? (
|
||||
<ProbeDetails probe={root} />
|
||||
) : (
|
||||
<Section title='Layers' count={getViewChain(definition.name).length}>
|
||||
<LayerStack view={{ layers: getViewChain(definition.name), failed: [] }} />
|
||||
</Section>
|
||||
)}
|
||||
<Section title='Slots' count={slots.length}>
|
||||
<SlotList slots={slots} />
|
||||
</Section>
|
||||
<NestedViews probes={probes} root={definition.name} nested={nested} search={search} onNested={onNested} />
|
||||
</aside>
|
||||
);
|
||||
}
|
||||
|
||||
/** Which fixtures show: the chosen one, or all of them side by side. */
|
||||
function fixtureSelection(definition: ViewDefinition, search: WorkbenchSearch) {
|
||||
const fixtures = Object.keys(definition.fixtures ?? {});
|
||||
const all = search.fixture === ALL_FIXTURES && fixtures.length > 1;
|
||||
const current = fixtures.find((fixture) => fixture === search.fixture) ?? fixtures[0];
|
||||
|
||||
return { fixtures, all, current, shown: all ? fixtures : fixtures.filter((fixture) => fixture === current) };
|
||||
}
|
||||
|
||||
export interface ViewPreviewProps {
|
||||
definition: ViewDefinition;
|
||||
search: WorkbenchSearch;
|
||||
scheme: ThemeScheme;
|
||||
width: WorkbenchWidth;
|
||||
onFixture: (fixture: string | undefined) => void;
|
||||
}
|
||||
|
||||
/** A view rendered from its fixtures through the full layer chain, with its layers, model and slots. */
|
||||
export default function ViewPreview({ definition, search, scheme, width, onFixture }: ViewPreviewProps) {
|
||||
const { fixtures, all, current, shown } = fixtureSelection(definition, search);
|
||||
const [focus, setFocus] = useState<string | undefined>(undefined);
|
||||
const focused = shown.find((fixture) => fixture === focus) ?? shown[0];
|
||||
const [nested, setNested] = useState<NestedFixtures>({});
|
||||
const [content, setContent] = useState<string | null>(null);
|
||||
const [probes, setProbes] = useState<ReadonlyMap<string, readonly ViewProbe[]>>(new Map());
|
||||
const [stage, setStage] = useState<HTMLElement | null>(null);
|
||||
const available = useWidth(stage);
|
||||
const collect = useCallback((fixture: string, probe: ViewProbe) => {
|
||||
setProbes((previous) => new Map(previous).set(fixture, [...(previous.get(fixture) ?? []), probe]));
|
||||
|
||||
return () =>
|
||||
setProbes((previous) =>
|
||||
new Map(previous).set(
|
||||
fixture,
|
||||
(previous.get(fixture) ?? []).filter((existing) => existing !== probe)
|
||||
)
|
||||
);
|
||||
}, []);
|
||||
const focusedProbes = probes.get(focused ?? '') ?? [];
|
||||
const root = focusedProbes.find((probe) => probe.current().definition.name === definition.name);
|
||||
const rendered = root ? renderingLayer(root.current()) : getViewChain(definition.name).at(-1);
|
||||
const options: FrameOptions = { definition, nested, content, scheme, width, available };
|
||||
|
||||
return (
|
||||
<div className='flex min-w-0 flex-1 flex-col xl:flex-row'>
|
||||
<section className='min-w-0 flex-1 p-4 lg:p-6'>
|
||||
<header className='mb-4 space-y-3'>
|
||||
<div className='flex flex-wrap items-baseline gap-x-3 gap-y-1'>
|
||||
<h2 className='font-mono text-lg font-semibold text-foreground'>{definition.name}</h2>
|
||||
<span className='text-xs text-muted-foreground'>
|
||||
{definition.kind} · {definition.context} context
|
||||
{rendered && ` · rendered by ${rendered.id}`}
|
||||
</span>
|
||||
</div>
|
||||
{fixtures.length > 0 && (
|
||||
<div className='flex flex-wrap items-center gap-3'>
|
||||
<FixtureTabs
|
||||
fixtures={fixtures}
|
||||
current={all ? ALL_FIXTURES : current}
|
||||
onSelect={(fixture) => onFixture(fixture === fixtures[0] ? undefined : fixture)}
|
||||
/>
|
||||
{definition.kind === 'layout' && <PageInside value={content} onChange={setContent} />}
|
||||
</div>
|
||||
)}
|
||||
</header>
|
||||
<div ref={setStage} className='flex flex-wrap items-start gap-6'>
|
||||
{shown.length === 0 && <NoFixtures name={definition.name} />}
|
||||
{available > 0 &&
|
||||
shown.map((fixture) => (
|
||||
<FixtureFrame
|
||||
key={fixture}
|
||||
fixture={fixture}
|
||||
options={options}
|
||||
focused={fixture === focused}
|
||||
onFocus={all ? () => setFocus(fixture) : null}
|
||||
onProbe={collect}
|
||||
/>
|
||||
))}
|
||||
</div>
|
||||
</section>
|
||||
<PreviewDetails
|
||||
definition={definition}
|
||||
probes={focusedProbes}
|
||||
nested={nested}
|
||||
search={search}
|
||||
onNested={(name, fixture) => setNested((previous) => ({ ...previous, [name]: fixture }))}
|
||||
/>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,129 @@
|
||||
import { useEffect, useRef, useState } from 'react';
|
||||
import { Link } from '@tanstack/react-router';
|
||||
import { Search } from 'lucide-react';
|
||||
import { cn } from '@/lib/cn';
|
||||
import type { WorkbenchSearch } from '@/router/search';
|
||||
import { useViewDefinitions } from '@/views/registry';
|
||||
import { workbenchGroups, type WorkbenchEntry, type WorkbenchGroupId } from './catalog';
|
||||
|
||||
function EntryLink({
|
||||
group,
|
||||
entry,
|
||||
search,
|
||||
active,
|
||||
}: {
|
||||
group: WorkbenchGroupId;
|
||||
entry: WorkbenchEntry;
|
||||
search: WorkbenchSearch;
|
||||
active: boolean;
|
||||
}) {
|
||||
const target =
|
||||
group === 'ui'
|
||||
? { ...search, view: undefined, ui: entry.name, fixture: undefined }
|
||||
: { ...search, ui: undefined, view: entry.name, fixture: undefined };
|
||||
|
||||
return (
|
||||
<Link
|
||||
to='/panel/theme-workbench'
|
||||
search={target}
|
||||
aria-current={active ? 'page' : undefined}
|
||||
className={cn(
|
||||
'flex items-center gap-2 rounded-sm px-2 py-1 font-mono text-xs no-underline transition-colors',
|
||||
active ? 'bg-primary/15 text-foreground' : 'text-foreground/80 hover:bg-popover hover:text-foreground',
|
||||
entry.fixtures.length === 0 && !active && 'text-muted-foreground'
|
||||
)}
|
||||
>
|
||||
<span className='min-w-0 flex-1 truncate' title={entry.name}>
|
||||
{entry.name}
|
||||
</span>
|
||||
{entry.overrides.length > 0 && (
|
||||
<span
|
||||
className='h-1.5 w-1.5 shrink-0 rounded-full bg-accent'
|
||||
title={`Overridden by ${entry.overrides.join(', ')}`}
|
||||
/>
|
||||
)}
|
||||
<span
|
||||
className='shrink-0 tabular-nums text-muted-foreground'
|
||||
title={entry.fixtures.length ? `${entry.fixtures.length} fixtures` : 'No fixtures yet'}
|
||||
>
|
||||
{entry.fixtures.length || '–'}
|
||||
</span>
|
||||
</Link>
|
||||
);
|
||||
}
|
||||
|
||||
/** Every view by kind and the UI kit, searchable; `/` focuses the search. */
|
||||
export default function WorkbenchSidebar({ search }: { search: WorkbenchSearch }) {
|
||||
const definitions = useViewDefinitions();
|
||||
const [query, setQuery] = useState('');
|
||||
const [overridden, setOverridden] = useState(false);
|
||||
const input = useRef<HTMLInputElement>(null);
|
||||
const groups = workbenchGroups(definitions, { query, overridden });
|
||||
|
||||
useEffect(() => {
|
||||
const onKey = (event: KeyboardEvent) => {
|
||||
const typing = event.target instanceof HTMLInputElement || event.target instanceof HTMLTextAreaElement;
|
||||
|
||||
if (event.key === '/' && !typing) {
|
||||
event.preventDefault();
|
||||
input.current?.focus();
|
||||
}
|
||||
};
|
||||
|
||||
window.addEventListener('keydown', onKey);
|
||||
|
||||
return () => window.removeEventListener('keydown', onKey);
|
||||
}, []);
|
||||
|
||||
return (
|
||||
<nav aria-label='Views' className='flex h-full flex-col'>
|
||||
<div className='space-y-2 border-b border-border p-3'>
|
||||
<label className='flex items-center gap-2 rounded-sm border border-border bg-background px-2'>
|
||||
<Search className='h-3.5 w-3.5 shrink-0 text-muted-foreground' aria-hidden />
|
||||
<input
|
||||
ref={input}
|
||||
type='search'
|
||||
value={query}
|
||||
onChange={(event) => setQuery(event.target.value)}
|
||||
placeholder='Search views /'
|
||||
aria-label='Search views'
|
||||
className='w-full min-w-0 border-0 bg-transparent px-0 py-1.5 text-sm text-foreground placeholder:text-muted-foreground focus:ring-0 focus:outline-hidden'
|
||||
/>
|
||||
</label>
|
||||
<label className='flex items-center gap-2 text-xs text-muted-foreground'>
|
||||
<input
|
||||
type='checkbox'
|
||||
checked={overridden}
|
||||
onChange={(event) => setOverridden(event.target.checked)}
|
||||
className='h-3.5 w-3.5 rounded-xs border-border bg-input text-primary'
|
||||
/>
|
||||
Only views the theme or extensions override
|
||||
</label>
|
||||
</div>
|
||||
<div className='min-h-0 flex-1 overflow-y-auto p-2'>
|
||||
{groups.length === 0 && <p className='p-2 text-sm text-muted-foreground'>Nothing matches.</p>}
|
||||
{groups.map((group) => (
|
||||
<details key={group.id} open className='mb-2'>
|
||||
<summary className='cursor-pointer select-none px-2 py-1 text-xs font-semibold uppercase tracking-wide text-muted-foreground'>
|
||||
{group.label} <span className='font-normal'>{group.entries.length}</span>
|
||||
</summary>
|
||||
<ul className='mt-0.5 space-y-px'>
|
||||
{group.entries.map((entry) => (
|
||||
<li key={entry.name}>
|
||||
<EntryLink
|
||||
group={group.id}
|
||||
entry={entry}
|
||||
search={search}
|
||||
active={
|
||||
group.id === 'ui' ? search.ui === entry.name : search.view === entry.name
|
||||
}
|
||||
/>
|
||||
</li>
|
||||
))}
|
||||
</ul>
|
||||
</details>
|
||||
))}
|
||||
</div>
|
||||
</nav>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,94 @@
|
||||
import { getViewOwners } from '@/extensions/registry';
|
||||
import { uiPrimitives } from '@/themes/gallery';
|
||||
import { getViewChain, type ViewDefinition } from '@/views/registry';
|
||||
|
||||
export type WorkbenchGroupId = 'layouts' | 'pages' | 'blocks' | 'extensions' | 'ui';
|
||||
|
||||
export interface WorkbenchEntry {
|
||||
readonly name: string;
|
||||
/** Fixture names, or variant names for a primitive. */
|
||||
readonly fixtures: readonly string[];
|
||||
/** The packages stacking a layer over classic: the theme chain, then extension overrides. */
|
||||
readonly overrides: readonly string[];
|
||||
}
|
||||
|
||||
export interface WorkbenchGroup {
|
||||
readonly id: WorkbenchGroupId;
|
||||
readonly label: string;
|
||||
readonly entries: readonly WorkbenchEntry[];
|
||||
}
|
||||
|
||||
export interface WorkbenchFilter {
|
||||
readonly query: string;
|
||||
/** Only views a theme or extension layers over. */
|
||||
readonly overridden: boolean;
|
||||
}
|
||||
|
||||
const labels = {
|
||||
layouts: 'Layouts',
|
||||
pages: 'Pages',
|
||||
blocks: 'Blocks',
|
||||
extensions: 'Extension views',
|
||||
ui: 'UI kit',
|
||||
} satisfies Record<WorkbenchGroupId, string>;
|
||||
|
||||
function groupOf(definition: ViewDefinition): WorkbenchGroupId {
|
||||
if (definition.extensionId) {
|
||||
return 'extensions';
|
||||
}
|
||||
|
||||
if (definition.kind === 'layout') {
|
||||
return 'layouts';
|
||||
}
|
||||
|
||||
return definition.kind === 'page' ? 'pages' : 'blocks';
|
||||
}
|
||||
|
||||
/** Every search term appears in the name, so `serv card` finds `dashboard.serverCard`. */
|
||||
export function matchesQuery(name: string, query: string): boolean {
|
||||
const haystack = name.toLowerCase();
|
||||
|
||||
return query
|
||||
.toLowerCase()
|
||||
.split(/\s+/)
|
||||
.filter(Boolean)
|
||||
.every((term) => haystack.includes(term));
|
||||
}
|
||||
|
||||
export function viewEntry(definition: ViewDefinition): WorkbenchEntry {
|
||||
return {
|
||||
name: definition.name,
|
||||
fixtures: Object.keys(definition.fixtures ?? {}),
|
||||
overrides: [
|
||||
...getViewChain(definition.name)
|
||||
.filter((layer) => layer.source === 'theme')
|
||||
.map((layer) => layer.id),
|
||||
...getViewOwners(definition.name),
|
||||
],
|
||||
};
|
||||
}
|
||||
|
||||
/** The workbench tree: views by kind, then extension-defined views and the UI kit, filtered. */
|
||||
export function workbenchGroups(definitions: readonly ViewDefinition[], filter: WorkbenchFilter): WorkbenchGroup[] {
|
||||
const groups = new Map<WorkbenchGroupId, WorkbenchEntry[]>(
|
||||
(['layouts', 'pages', 'blocks', 'extensions', 'ui'] as const).map((id) => [id, []])
|
||||
);
|
||||
|
||||
for (const definition of definitions) {
|
||||
const entry = viewEntry(definition);
|
||||
|
||||
if (matchesQuery(entry.name, filter.query) && (!filter.overridden || entry.overrides.length > 0)) {
|
||||
groups.get(groupOf(definition))?.push(entry);
|
||||
}
|
||||
}
|
||||
|
||||
if (!filter.overridden) {
|
||||
for (const [name, primitive] of Object.entries(uiPrimitives)) {
|
||||
if (matchesQuery(name, filter.query)) {
|
||||
groups.get('ui')?.push({ name, fixtures: Object.keys(primitive.samples), overrides: [] });
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return [...groups].flatMap(([id, entries]) => (entries.length ? [{ id, label: labels[id], entries }] : []));
|
||||
}
|
||||
@@ -0,0 +1,83 @@
|
||||
import { useLayoutEffect, useState, type ReactNode } from 'react';
|
||||
import type { WorkbenchWidth } from '@/router/search';
|
||||
import { cn } from '@/lib/cn';
|
||||
|
||||
export const VIEWPORT_WIDTHS = {
|
||||
phone: 390,
|
||||
tablet: 820,
|
||||
desktop: 1280,
|
||||
full: null,
|
||||
} satisfies Record<WorkbenchWidth, number | null>;
|
||||
|
||||
export interface FrameSize {
|
||||
readonly width: number;
|
||||
/** Below 1 when the frame is shrunk to fit the space available. */
|
||||
readonly scale: number;
|
||||
}
|
||||
|
||||
/** The width of an element, kept current. */
|
||||
export function useWidth(element: HTMLElement | null): number {
|
||||
const [width, setWidth] = useState(0);
|
||||
|
||||
useLayoutEffect(() => {
|
||||
if (!element) {
|
||||
return;
|
||||
}
|
||||
|
||||
const observer = new ResizeObserver(([entry]) => setWidth(Math.floor(entry.contentRect.width)));
|
||||
|
||||
// Observations wait for rendering, which a hidden tab skips.
|
||||
setWidth(Math.floor(element.getBoundingClientRect().width));
|
||||
observer.observe(element);
|
||||
|
||||
return () => observer.disconnect();
|
||||
}, [element]);
|
||||
|
||||
return width;
|
||||
}
|
||||
|
||||
/** The frame width for a preset, and the scale that fits it into the space available. */
|
||||
export function frameSize(preset: WorkbenchWidth, available: number): FrameSize {
|
||||
const width = VIEWPORT_WIDTHS[preset] ?? available;
|
||||
|
||||
return { width: Math.max(width, 1), scale: available > 0 && width > available ? available / width : 1 };
|
||||
}
|
||||
|
||||
export function Segmented<T extends string>({
|
||||
label,
|
||||
value,
|
||||
options,
|
||||
onChange,
|
||||
}: {
|
||||
label: string;
|
||||
value: T;
|
||||
options: readonly { value: T; label: ReactNode; disabled?: boolean; title?: string }[];
|
||||
onChange: (value: T) => void;
|
||||
}) {
|
||||
return (
|
||||
<div
|
||||
role='group'
|
||||
aria-label={label}
|
||||
className='inline-flex rounded-sm border border-border bg-background p-0.5'
|
||||
>
|
||||
{options.map((option) => (
|
||||
<button
|
||||
key={option.value}
|
||||
type='button'
|
||||
aria-pressed={option.value === value}
|
||||
disabled={option.disabled}
|
||||
title={option.title}
|
||||
className={cn(
|
||||
'rounded-xs px-2.5 py-1 text-xs font-medium transition-colors disabled:cursor-not-allowed disabled:opacity-40',
|
||||
option.value === value
|
||||
? 'bg-popover text-foreground shadow-sm'
|
||||
: 'text-muted-foreground hover:text-foreground'
|
||||
)}
|
||||
onClick={() => onChange(option.value)}
|
||||
>
|
||||
{option.label}
|
||||
</button>
|
||||
))}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,249 @@
|
||||
/** @vitest-environment jsdom */
|
||||
import { act, cleanup, fireEvent, render, screen, within } from '@testing-library/react';
|
||||
import type { ReactNode } from 'react';
|
||||
import { afterEach, beforeAll, beforeEach, describe, expect, it, vi } from 'vitest';
|
||||
import { parseWorkbenchSearch } from '@/router/search';
|
||||
import { createExtensionTestHost, type ExtensionTestHost } from '@/sdk/testing';
|
||||
import '@/views/catalog';
|
||||
import { getViewDefinition, registerViewDefinition, registerViewLayer, type ViewDefinition } from '@/views/registry';
|
||||
import { matchesQuery, workbenchGroups } from './catalog';
|
||||
import type * as PreviewFrameModule from './PreviewFrame';
|
||||
import { mirrorDocument } from './PreviewFrame';
|
||||
import { frameSize } from './stage';
|
||||
import ViewPreview, { ALL_FIXTURES } from './ViewPreview';
|
||||
|
||||
// jsdom loads no srcdoc, so previews render in place; the frame itself is covered by mirrorDocument.
|
||||
vi.mock('./PreviewFrame', async (importOriginal) => ({
|
||||
...(await importOriginal<typeof PreviewFrameModule>()),
|
||||
default: ({ label, children }: { label: string; children?: ReactNode }) => (
|
||||
<div role='figure' aria-label={label}>
|
||||
{children}
|
||||
</div>
|
||||
),
|
||||
}));
|
||||
|
||||
let host: ExtensionTestHost | undefined;
|
||||
|
||||
beforeAll(() => {
|
||||
registerViewDefinition({
|
||||
name: 'test.broken',
|
||||
kind: 'block',
|
||||
context: 'app',
|
||||
use: () => ({}),
|
||||
fixtures: { default: () => ({}) },
|
||||
});
|
||||
registerViewLayer('classic', 'classic', {
|
||||
'test.broken': () => {
|
||||
throw new Error('The fixture is missing a field.');
|
||||
},
|
||||
});
|
||||
registerViewLayer('aurora', 'theme', { 'dashboard.serverCard': () => <p>Aurora card</p> });
|
||||
});
|
||||
|
||||
beforeEach(() => {
|
||||
vi.spyOn(console, 'error').mockImplementation(() => {});
|
||||
vi.spyOn(HTMLElement.prototype, 'getBoundingClientRect').mockReturnValue(new DOMRect(0, 0, 1000, 400));
|
||||
vi.stubGlobal(
|
||||
'ResizeObserver',
|
||||
class {
|
||||
observe() {}
|
||||
disconnect() {}
|
||||
}
|
||||
);
|
||||
});
|
||||
|
||||
afterEach(() => {
|
||||
cleanup();
|
||||
host?.dispose();
|
||||
host = undefined;
|
||||
vi.restoreAllMocks();
|
||||
vi.unstubAllGlobals();
|
||||
});
|
||||
|
||||
async function preview(name: string, fixture?: string) {
|
||||
const onFixture = vi.fn();
|
||||
|
||||
host = createExtensionTestHost({ path: '/panel/theme-workbench' });
|
||||
await act(async () => {
|
||||
render(
|
||||
<ViewPreview
|
||||
definition={getViewDefinition(name)!}
|
||||
search={{ view: name, fixture }}
|
||||
scheme='dark'
|
||||
width='phone'
|
||||
onFixture={onFixture}
|
||||
/>,
|
||||
{ wrapper: host!.Wrapper }
|
||||
);
|
||||
});
|
||||
|
||||
return onFixture;
|
||||
}
|
||||
|
||||
describe('workbench catalog', () => {
|
||||
const definition = (name: string, kind: ViewDefinition['kind'], extensionId?: string): ViewDefinition => ({
|
||||
name,
|
||||
kind,
|
||||
context: 'app',
|
||||
use: () => ({}),
|
||||
fixtures: kind === 'block' ? { one: () => ({}) } : undefined,
|
||||
extensionId,
|
||||
});
|
||||
const definitions = [
|
||||
definition('layout.app', 'layout'),
|
||||
definition('page.dashboard', 'page'),
|
||||
definition('dashboard.serverCard', 'block'),
|
||||
definition('billing.balance', 'block', 'billing'),
|
||||
];
|
||||
|
||||
it('groups views by kind, then extension views and the UI kit', () => {
|
||||
const groups = workbenchGroups(definitions, { query: '', overridden: false });
|
||||
|
||||
expect(groups.map((group) => [group.label, group.entries.length])).toEqual([
|
||||
['Layouts', 1],
|
||||
['Pages', 1],
|
||||
['Blocks', 1],
|
||||
['Extension views', 1],
|
||||
['UI kit', groups.at(-1)!.entries.length],
|
||||
]);
|
||||
expect(groups[2].entries[0]).toEqual({
|
||||
name: 'dashboard.serverCard',
|
||||
fixtures: ['one'],
|
||||
overrides: ['aurora'],
|
||||
});
|
||||
expect(groups.at(-1)!.entries.find((entry) => entry.name === 'Button')?.fixtures).toContain('primary');
|
||||
});
|
||||
|
||||
it('searches by every term and filters to overridden views', () => {
|
||||
expect(matchesQuery('dashboard.serverCard', 'serv card')).toBe(true);
|
||||
expect(matchesQuery('dashboard.serverList', 'serv card')).toBe(false);
|
||||
expect(
|
||||
workbenchGroups(definitions, { query: '', overridden: true }).flatMap((group) =>
|
||||
group.entries.map((entry) => entry.name)
|
||||
)
|
||||
).toEqual(['dashboard.serverCard']);
|
||||
});
|
||||
|
||||
it('reads deep links, dropping values it does not know', () => {
|
||||
expect(
|
||||
parseWorkbenchSearch({
|
||||
view: 'page.dashboard',
|
||||
ui: 'Button',
|
||||
fixture: '*',
|
||||
scheme: 'light',
|
||||
width: 'phone',
|
||||
})
|
||||
).toEqual({ view: 'page.dashboard', fixture: '*', scheme: 'light', width: 'phone' });
|
||||
expect(parseWorkbenchSearch({ ui: 'Button', scheme: 'sepia', width: 'watch' })).toEqual({ ui: 'Button' });
|
||||
});
|
||||
|
||||
it('shrinks a viewport preset to the space available', () => {
|
||||
expect(frameSize('phone', 1000)).toEqual({ width: 390, scale: 1 });
|
||||
expect(frameSize('desktop', 640)).toEqual({ width: 1280, scale: 0.5 });
|
||||
expect(frameSize('full', 640)).toEqual({ width: 640, scale: 1 });
|
||||
});
|
||||
});
|
||||
|
||||
describe('preview frames', () => {
|
||||
it('mirror the panel stylesheets and document attributes with their own scheme', () => {
|
||||
const settings = document.head.appendChild(
|
||||
Object.assign(document.createElement('style'), { id: 'theme-settings' })
|
||||
);
|
||||
const sheet = document.head.appendChild(
|
||||
Object.assign(document.createElement('link'), { rel: 'stylesheet', href: '/assets/theme.css' })
|
||||
);
|
||||
const target = document.implementation.createHTMLDocument('frame');
|
||||
const clones = new Map<Element, Element>();
|
||||
|
||||
settings.textContent = ':root{--accent:red}';
|
||||
document.documentElement.className = 'dark';
|
||||
document.documentElement.setAttribute('data-density', 'compact');
|
||||
document.body.className = 'bg-background';
|
||||
mirrorDocument(target, 'light', clones);
|
||||
|
||||
expect(target.head.querySelector('#theme-settings')?.textContent).toBe(':root{--accent:red}');
|
||||
expect(target.head.querySelector('link')?.getAttribute('href')).toBe('/assets/theme.css');
|
||||
expect(target.documentElement.className).toBe('light');
|
||||
expect(target.documentElement.getAttribute('data-density')).toBe('compact');
|
||||
expect(target.body.className).toBe('bg-background');
|
||||
|
||||
settings.textContent = ':root{--accent:blue}';
|
||||
sheet.remove();
|
||||
mirrorDocument(target, 'dark', clones);
|
||||
|
||||
expect(target.head.querySelector('#theme-settings')?.textContent).toBe(':root{--accent:blue}');
|
||||
expect(target.head.querySelector('link')).toBeNull();
|
||||
expect(target.documentElement.className).toBe('dark');
|
||||
settings.remove();
|
||||
});
|
||||
});
|
||||
|
||||
describe('view preview', () => {
|
||||
it('renders every fixture side by side through the layer chain, with its details', async () => {
|
||||
await preview('dashboard.serverList', ALL_FIXTURES);
|
||||
|
||||
const servers = await screen.findByRole('figure', { name: 'dashboard.serverList: servers' });
|
||||
|
||||
expect(within(servers).getByRole('link', { name: 'Survival' })).toHaveAttribute('href', '/server/a1b2c3d4');
|
||||
expect(within(servers).getAllByText('Aurora card')).toHaveLength(2);
|
||||
expect(within(screen.getByRole('figure', { name: 'dashboard.serverList: empty' })).getByText('No servers yet'));
|
||||
expect(screen.getByRole('figure', { name: 'dashboard.serverList: loading' })).toBeInTheDocument();
|
||||
|
||||
const details = screen.getByRole('complementary', { name: 'View details' });
|
||||
|
||||
expect(within(details).getByText("'dashboard.serverList': ({ model, Default }) => <Default />,")).toBeVisible();
|
||||
expect(within(details).getByText('npx pterodactyl-theme eject dashboard.serverList')).toBeVisible();
|
||||
expect(within(details).getByText('dashboard.serverRow.metrics.after')).toBeInTheDocument();
|
||||
expect(within(details).getByRole('link', { name: 'dashboard.serverCard' })).toHaveAttribute(
|
||||
'href',
|
||||
'/panel/theme-workbench?view=dashboard.serverCard'
|
||||
);
|
||||
});
|
||||
|
||||
it('switches fixtures through the URL and nested fixtures in place', async () => {
|
||||
const onFixture = await preview('page.dashboard');
|
||||
|
||||
expect(await screen.findAllByText('Aurora card')).toHaveLength(2);
|
||||
|
||||
fireEvent.click(screen.getByRole('tab', { name: 'error' }));
|
||||
expect(onFixture).toHaveBeenCalledWith('error');
|
||||
|
||||
fireEvent.change(screen.getByRole('combobox', { name: 'Fixture of dashboard.serverList' }), {
|
||||
target: { value: 'empty' },
|
||||
});
|
||||
expect(await screen.findByText('No servers yet')).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('shows the layer that rendered, and why a view has nothing to show', async () => {
|
||||
await preview('dashboard.serverCard');
|
||||
|
||||
expect(await screen.findByText('Aurora card')).toBeInTheDocument();
|
||||
expect(screen.getByText(/rendered by aurora/)).toBeInTheDocument();
|
||||
|
||||
cleanup();
|
||||
host?.dispose();
|
||||
await preview('page.server.backups');
|
||||
|
||||
expect(screen.getByText('No fixtures yet')).toBeInTheDocument();
|
||||
expect(screen.getByText(/Classic has no source of its own to eject here yet/)).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('contains a fixture that fails to render', async () => {
|
||||
await preview('test.broken');
|
||||
|
||||
expect(await screen.findByRole('alert')).toHaveTextContent('The fixture is missing a field.');
|
||||
});
|
||||
|
||||
it('renders a layout around a chosen page', async () => {
|
||||
await preview('layout.app');
|
||||
|
||||
expect(screen.getByText('The routed page renders here.')).toBeInTheDocument();
|
||||
|
||||
fireEvent.change(screen.getByRole('combobox', { name: 'Page inside' }), {
|
||||
target: { value: 'page.dashboard' },
|
||||
});
|
||||
|
||||
expect(await screen.findByRole('heading', { name: 'Servers' })).toBeInTheDocument();
|
||||
expect(screen.getByRole('link', { name: 'Account Settings' })).toHaveAttribute('href', '/account');
|
||||
});
|
||||
});
|
||||
@@ -5,7 +5,7 @@ import dayjs from '@/lib/dayjs';
|
||||
import { bytesToString } from '@/lib/formatters';
|
||||
import { cn } from '@/lib/cn';
|
||||
import { fileObjectKind, type FileObject } from '@/api/server/files/queries';
|
||||
import { createTestFileDetails } from '@/views/fixtures';
|
||||
import { createTestFileDetails, createTestFileObject } from '@/views/fixtures';
|
||||
import type { FileDetailsModel } from '@/views/files';
|
||||
import { defineView, registerBaseView, type ViewPartProps, type ViewParts, type ViewProps } from '@/views/registry';
|
||||
|
||||
@@ -82,5 +82,6 @@ export const fileDetailsView = defineView('server.files.details', {
|
||||
file: () => createTestFileDetails(),
|
||||
directory: () => createTestFileDetails({ name: 'plugins', kind: 'directory', size: 0 }),
|
||||
},
|
||||
fixtureInput: (model) => ({ file: createTestFileObject(model) }),
|
||||
});
|
||||
registerBaseView('classic', 'classic', 'server.files.details', DefaultFileDetails);
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
import { createContext, createElement, useContext, useState } from 'react';
|
||||
import { createContext, createElement, useContext, useMemo, useState, type ReactNode } from 'react';
|
||||
import Button from '@/components/elements/Button';
|
||||
import CodemirrorEditor from '@/components/elements/LazyCodemirrorEditor';
|
||||
import Spinner from '@/components/elements/Spinner';
|
||||
@@ -121,9 +121,16 @@ function useFileEditorModel(): FileEditorModel {
|
||||
return session.model;
|
||||
}
|
||||
|
||||
function FixtureEditorSession({ model, children }: { model: FileEditorModel; children?: ReactNode }) {
|
||||
const value = useMemo(() => ({ model, read: () => model.content, setLanguage: () => {} }), [model]);
|
||||
|
||||
return <FileEditorContext.Provider value={value}>{children}</FileEditorContext.Provider>;
|
||||
}
|
||||
|
||||
export const fileEditorView = defineView('server.files.editor', {
|
||||
context: 'server',
|
||||
use: useFileEditorModel,
|
||||
fixtureScope: FixtureEditorSession,
|
||||
placeholder: createElement(Spinner, { size: 'large', centered: true }),
|
||||
fixtures: {
|
||||
file: () => createTestFileEditor(),
|
||||
|
||||
@@ -1,8 +1,9 @@
|
||||
import { createContext, createElement, useContext } from 'react';
|
||||
import { createContext, createElement, useContext, useLayoutEffect, useMemo, type ReactNode } from 'react';
|
||||
import { Link } from '@tanstack/react-router';
|
||||
import { FolderOpen } from 'lucide-react';
|
||||
import { useCurrentServerIdentifier } from '@/api/server/queries';
|
||||
import { fileObjectKey, type FileObject } from '@/api/server/files/queries';
|
||||
import type { ClientFileObjectResource as FileObject } from '@/api/extensionTypes';
|
||||
import { fileObjectKey } from '@/api/server/files/queries';
|
||||
import { NewButton } from '@/components/elements/NewButton';
|
||||
import ErrorBoundary from '@/components/elements/ErrorBoundary';
|
||||
import Spinner from '@/components/elements/Spinner';
|
||||
@@ -18,8 +19,10 @@ import { FileRowActionsProvider } from '@/components/server/files/useFileActions
|
||||
import Slot from '@/extensions/Slot';
|
||||
import { encodePathSegments } from '@/helpers';
|
||||
import { cn } from '@/lib/cn';
|
||||
import { ServerContext } from '@/state/server/context';
|
||||
import { useServerStore } from '@/state/server';
|
||||
import { createTestFileManager } from '@/views/fixtures';
|
||||
import type { FileManagerModel } from '@/views/files';
|
||||
import type { FileManagerEntry, FileManagerModel } from '@/views/files';
|
||||
import { defineView, registerBaseView, type ViewPartProps, type ViewParts, type ViewProps } from '@/views/registry';
|
||||
import useFileManagerExtensionData from './useFileManagerExtensionData';
|
||||
|
||||
@@ -149,9 +152,46 @@ function useFileBrowserModel(): FileManagerModel {
|
||||
return session.model;
|
||||
}
|
||||
|
||||
const fixtureFile = (entry: FileManagerEntry): FileObject => ({
|
||||
object: 'file_object',
|
||||
attributes: {
|
||||
name: entry.name,
|
||||
mode: entry.mode,
|
||||
mode_bits: entry.modeBits,
|
||||
size: entry.size,
|
||||
is_file: entry.kind !== 'directory',
|
||||
is_symlink: entry.kind === 'symlink',
|
||||
mimetype: entry.mimetype,
|
||||
created_at: entry.modifiedAt,
|
||||
modified_at: entry.modifiedAt,
|
||||
},
|
||||
});
|
||||
|
||||
function FixtureFiles({ model, children }: { model: FileManagerModel; children?: ReactNode }) {
|
||||
const setSelectedFiles = useServerStore((state) => state.files.setSelectedFiles);
|
||||
const value = useMemo(() => ({ model, files: model.entries.map(fixtureFile) }), [model]);
|
||||
const selection = model.selection.join('/');
|
||||
|
||||
useLayoutEffect(() => {
|
||||
setSelectedFiles({ directory: model.directory, files: selection ? selection.split('/') : [] });
|
||||
}, [setSelectedFiles, model.directory, selection]);
|
||||
|
||||
return <FileManagerContext.Provider value={value}>{children}</FileManagerContext.Provider>;
|
||||
}
|
||||
|
||||
/** The selection lives in a server store, so a fixture brings its own. */
|
||||
function FixtureManagerSession({ model, children }: { model: FileManagerModel; children?: ReactNode }) {
|
||||
return (
|
||||
<ServerContext.Provider>
|
||||
<FixtureFiles model={model}>{children}</FixtureFiles>
|
||||
</ServerContext.Provider>
|
||||
);
|
||||
}
|
||||
|
||||
export const fileManagerView = defineView('server.files.manager', {
|
||||
context: 'server',
|
||||
use: useFileBrowserModel,
|
||||
fixtureScope: FixtureManagerSession,
|
||||
slots: ['server.files.toolbar', 'server.files.rowActions', 'server.files.selectionActions'],
|
||||
placeholder: createElement(Spinner, { size: 'large', centered: true }),
|
||||
fixtures: {
|
||||
|
||||
@@ -13,10 +13,15 @@ export interface RawSearch {
|
||||
email?: string | number | boolean | null;
|
||||
event?: string | number | boolean | null;
|
||||
filter?: string | number | boolean | null;
|
||||
fixture?: string | number | boolean | null;
|
||||
page?: string | number | boolean | null;
|
||||
scheme?: string | number | boolean | null;
|
||||
sort?: string | number | boolean | null;
|
||||
type?: string | number | boolean | null;
|
||||
ui?: string | number | boolean | null;
|
||||
user?: string | number | boolean | null;
|
||||
view?: string | number | boolean | null;
|
||||
width?: string | number | boolean | null;
|
||||
}
|
||||
|
||||
/** The URL text of a search value the router JSON-parsed. */
|
||||
|
||||
@@ -77,7 +77,7 @@ import RootNotFound from '@/router/RootNotFound';
|
||||
import { RouteAccessDenied } from '@/router/RouteError';
|
||||
import { eggIdParam, idParam, scheduleIdParam } from '@/router/params';
|
||||
import { parseRedirectSearch } from '@/router/redirect';
|
||||
import { layoutRoute, pageRoute, requireServerPermission } from '@/router/viewRoutes';
|
||||
import { bareAreaPageRoute, layoutRoute, pageRoute, requireServerPermission } from '@/router/viewRoutes';
|
||||
import { preloadView } from '@/views/View';
|
||||
import {
|
||||
parseActivitySearch,
|
||||
@@ -93,6 +93,7 @@ import {
|
||||
parseServerListSearch,
|
||||
parseTagListSearch,
|
||||
parseUserListSearch,
|
||||
parseWorkbenchSearch,
|
||||
} from '@/router/search';
|
||||
|
||||
type RouterContext = {
|
||||
@@ -418,6 +419,21 @@ const panelRoute = createRoute({
|
||||
component: layoutRoute('layout.admin', 'admin'),
|
||||
});
|
||||
|
||||
/** Full width beside the admin area rather than inside its layout. */
|
||||
const themeWorkbenchRoute = createRoute({
|
||||
getParentRoute: () => authenticatedRoute,
|
||||
path: 'panel/theme-workbench',
|
||||
validateSearch: parseWorkbenchSearch,
|
||||
beforeLoad: async ({ context }) => {
|
||||
const user = await context.queryClient.ensureQueryData(currentUserQueryOptions());
|
||||
|
||||
if (!user.rootAdmin) {
|
||||
throw new RouteAccessDenied('You do not have permission to access the administrative area.');
|
||||
}
|
||||
},
|
||||
component: bareAreaPageRoute('page.admin.themeWorkbench', 'admin'),
|
||||
});
|
||||
|
||||
export const nodeDetailRoute = createRoute({
|
||||
getParentRoute: () => panelRoute,
|
||||
path: 'nodes/$id',
|
||||
@@ -991,7 +1007,8 @@ export function buildRouteTree(extensions: readonly SiteExtensionEntry[] = getBo
|
||||
{
|
||||
account: accountChildren.map(declaredPath),
|
||||
server: serverChildren.map(declaredPath),
|
||||
admin: [...panelChildren, ...panelResourceRoutes].map(declaredPath),
|
||||
// The workbench sits beside the admin layout rather than under it, but still owns its path.
|
||||
admin: [...[...panelChildren, ...panelResourceRoutes].map(declaredPath), 'theme-workbench'],
|
||||
},
|
||||
{
|
||||
'admin.node': nodeDetailChildren.map(declaredPath),
|
||||
@@ -1032,6 +1049,7 @@ export function buildRouteTree(extensions: readonly SiteExtensionEntry[] = getBo
|
||||
accountRoute.addChildren(accountRouteChildren),
|
||||
serverRoute.addChildren(serverRouteChildren),
|
||||
panelRoute.addChildren(panelRouteChildren),
|
||||
themeWorkbenchRoute,
|
||||
]),
|
||||
]);
|
||||
}
|
||||
|
||||
@@ -132,6 +132,47 @@ export const parseActivitySearch = (search: RawSearch): ActivitySearch => {
|
||||
return result;
|
||||
};
|
||||
|
||||
export const WORKBENCH_WIDTHS = ['phone', 'tablet', 'desktop', 'full'] as const;
|
||||
export type WorkbenchWidth = (typeof WORKBENCH_WIDTHS)[number];
|
||||
export type WorkbenchSearch = {
|
||||
view?: string;
|
||||
/** A UI kit primitive, shown instead of a view. */
|
||||
ui?: string;
|
||||
/** A fixture of the view, or `*` for all of them side by side. */
|
||||
fixture?: string;
|
||||
scheme?: 'dark' | 'light';
|
||||
width?: WorkbenchWidth;
|
||||
};
|
||||
|
||||
export const parseWorkbenchSearch = (search: RawSearch): WorkbenchSearch => {
|
||||
const result: WorkbenchSearch = {};
|
||||
const view = searchText(search.view);
|
||||
const ui = searchText(search.ui);
|
||||
const fixture = searchText(search.fixture);
|
||||
const scheme = search.scheme === 'dark' || search.scheme === 'light' ? search.scheme : undefined;
|
||||
const width = WORKBENCH_WIDTHS.find((preset) => preset === search.width);
|
||||
|
||||
if (view) {
|
||||
result.view = view;
|
||||
} else if (ui) {
|
||||
result.ui = ui;
|
||||
}
|
||||
|
||||
if (fixture) {
|
||||
result.fixture = fixture;
|
||||
}
|
||||
|
||||
if (scheme) {
|
||||
result.scheme = scheme;
|
||||
}
|
||||
|
||||
if (width) {
|
||||
result.width = width;
|
||||
}
|
||||
|
||||
return result;
|
||||
};
|
||||
|
||||
export const parseEmailSearch = (search: RawSearch): { email?: string } => {
|
||||
const email = searchText(search.email);
|
||||
|
||||
|
||||
@@ -80,3 +80,20 @@ export function pageRoute(
|
||||
|
||||
return PageRoute;
|
||||
}
|
||||
|
||||
/** A page of an area rendered outside that area's layout, as the full-width theme workbench is. */
|
||||
export function bareAreaPageRoute(name: Exclude<PageViewName, 'page.server.console'>, area: ViewContext) {
|
||||
const Page = pageRoute(name);
|
||||
|
||||
function BarePageRoute() {
|
||||
return (
|
||||
<ViewArea area={area}>
|
||||
<Page />
|
||||
</ViewArea>
|
||||
);
|
||||
}
|
||||
|
||||
BarePageRoute.preload = Page.preload;
|
||||
|
||||
return BarePageRoute;
|
||||
}
|
||||
|
||||
@@ -4,6 +4,7 @@ import { afterEach, expect, it, vi } from 'vitest';
|
||||
import type { ViewPartProps, ViewProps } from '@/views/registry';
|
||||
import { defineTheme } from '@/views/theme';
|
||||
import {
|
||||
renderPrimitive,
|
||||
renderView,
|
||||
createTestFileEditor,
|
||||
createTestFileManager,
|
||||
@@ -151,6 +152,26 @@ it('renders a view synchronously from fixtures with a theme layered over classic
|
||||
expect(container.isConnected).toBe(false);
|
||||
});
|
||||
|
||||
it('renders a UI kit primitive under a theme, replacing what was rendered before', () => {
|
||||
const first = renderPrimitive('Button', { children: 'Save changes', color: 'red' }, { theme: defineTheme({}) });
|
||||
|
||||
expect(first.container.querySelector('button')).toHaveTextContent('Save changes');
|
||||
|
||||
const second = renderPrimitive('Alert', { type: 'warning', children: 'Disk is nearly full.' });
|
||||
|
||||
expect(first.container.isConnected).toBe(false);
|
||||
expect(second.container.querySelector('[role="alert"]')).toHaveTextContent('Disk is nearly full.');
|
||||
second.unmount();
|
||||
});
|
||||
|
||||
it('renders a fixture of a view that takes inputs with the inputs it declares', () => {
|
||||
const { container, unmount } = renderView('dashboard.serverCard', { fixture: 'suspended' });
|
||||
|
||||
expect(container).toHaveTextContent('Test server');
|
||||
expect(container).toHaveTextContent('Suspended');
|
||||
unmount();
|
||||
});
|
||||
|
||||
it('renders nested views from their fixtures', () => {
|
||||
const { container } = renderView('dashboard.serverList', { fixture: 'servers' });
|
||||
|
||||
|
||||
@@ -1,10 +1,8 @@
|
||||
import { ExtensionContext } from '@/extensions/context';
|
||||
import '@/components/server/files/FileDetailsView';
|
||||
import { FileEditorContext } from '@/components/server/files/FileEditorView';
|
||||
import { FileManagerContext } from '@/components/server/files/FileManagerView';
|
||||
import type { FileObject } from '@/api/server/files/queries';
|
||||
import type { FileDetailsModel, FileEditorModel, FileManagerModel } from '@/views/files';
|
||||
import type { ServerCardModel } from '@/views/dashboard';
|
||||
import '@/components/server/files/FileEditorView';
|
||||
import '@/components/server/files/FileManagerView';
|
||||
import type { FileManagerModel } from '@/views/files';
|
||||
import { registerClassicTheme } from '@/views/classic';
|
||||
import '@/views/dashboard';
|
||||
import '@/views/layouts';
|
||||
@@ -21,8 +19,19 @@ import {
|
||||
import { registerThemeIcons, type ThemeDefinition } from '@/views/theme';
|
||||
import { clearThemeSkins, registerSkins } from '@/themes/skins';
|
||||
import classic from '@/themes/classic';
|
||||
import { uiPrimitives, type UiPrimitiveName, type UiPrimitiveProps } from '@/themes/gallery';
|
||||
import { createViewHarness, LooseView, preloadView, ViewFixtureProvider } from '@/views/View';
|
||||
import { act, createContext, useContext, useLayoutEffect, useMemo, type ComponentType, type ReactNode } from 'react';
|
||||
import {
|
||||
act,
|
||||
createContext,
|
||||
createElement,
|
||||
useContext,
|
||||
useLayoutEffect,
|
||||
useMemo,
|
||||
type ComponentType,
|
||||
type JSXElementConstructor,
|
||||
type ReactNode,
|
||||
} from 'react';
|
||||
import { createRoot } from 'react-dom/client';
|
||||
import { QueryClientProvider, type QueryClient } from '@tanstack/react-query';
|
||||
import {
|
||||
@@ -61,6 +70,7 @@ export {
|
||||
createTestServerCard,
|
||||
type TestServerOptions,
|
||||
} from '@/views/fixtures';
|
||||
export type { UiPrimitiveName, UiPrimitiveProps };
|
||||
|
||||
registerClassicTheme();
|
||||
// Classic's own views are lazy; loading them here lets a test render them synchronously.
|
||||
@@ -255,63 +265,7 @@ function fixtureModel(name: ViewName, fixture: string | undefined) {
|
||||
return factory();
|
||||
}
|
||||
|
||||
function fileObject(model: FileDetailsModel): FileObject {
|
||||
const directory = model.kind === 'directory';
|
||||
|
||||
return {
|
||||
object: 'file_object',
|
||||
attributes: {
|
||||
name: model.name,
|
||||
mode: directory ? 'drwxr-xr-x' : '-rw-r--r--',
|
||||
mode_bits: directory ? '0755' : '0644',
|
||||
size: model.size,
|
||||
is_file: !directory,
|
||||
is_symlink: model.kind === 'symlink',
|
||||
mimetype: directory ? 'inode/directory' : 'text/plain',
|
||||
created_at: model.modifiedAt,
|
||||
modified_at: model.modifiedAt,
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
type Session = ComponentType<{ children?: ReactNode }>;
|
||||
const NoSession: Session = ({ children }) => children;
|
||||
|
||||
function editorSession(model: FileEditorModel): Session {
|
||||
return function EditorSession({ children }) {
|
||||
const value = useMemo(() => ({ model, read: () => model.content, setLanguage: () => {} }), []);
|
||||
|
||||
return <FileEditorContext.Provider value={value}>{children}</FileEditorContext.Provider>;
|
||||
};
|
||||
}
|
||||
|
||||
function managerSession(model: FileManagerModel): Session {
|
||||
const files = model.entries.map((entry) => ({
|
||||
object: 'file_object',
|
||||
attributes: {
|
||||
name: entry.name,
|
||||
mode: entry.mode,
|
||||
mode_bits: entry.modeBits,
|
||||
size: entry.size,
|
||||
is_file: entry.kind !== 'directory',
|
||||
is_symlink: entry.kind === 'symlink',
|
||||
mimetype: entry.mimetype,
|
||||
created_at: entry.modifiedAt,
|
||||
modified_at: entry.modifiedAt,
|
||||
},
|
||||
}));
|
||||
|
||||
return function ManagerSession({ children }) {
|
||||
const setSelectedFiles = useServerStore((state) => state.files.setSelectedFiles);
|
||||
const value = useMemo(() => ({ model, files }), []);
|
||||
|
||||
useLayoutEffect(() => {
|
||||
setSelectedFiles({ directory: model.directory, files: [...model.selection] });
|
||||
}, [setSelectedFiles]);
|
||||
|
||||
return <FileManagerContext.Provider value={value}>{children}</FileManagerContext.Provider>;
|
||||
};
|
||||
}
|
||||
const NoSession = ({ children }: { model: unknown; children?: ReactNode }) => children;
|
||||
|
||||
/**
|
||||
* Tests a layer against the view's classic layers without issuing core queries: render it with `props`
|
||||
@@ -326,6 +280,7 @@ export async function createViewTestHost<N extends ViewName>(
|
||||
await preloadView(name);
|
||||
|
||||
const view: ViewName = name;
|
||||
const definition = getViewDefinition(view);
|
||||
const extensionId = options.extensionId ?? 'test-extension';
|
||||
const model = options.model ?? fixtureModel(view, options.fixture);
|
||||
const manager = view === 'server.files.manager' ? (model as FileManagerModel) : undefined;
|
||||
@@ -338,27 +293,8 @@ export async function createViewTestHost<N extends ViewName>(
|
||||
manager && !document.getElementById('modal-portal')
|
||||
? document.body.appendChild(Object.assign(document.createElement('div'), { id: 'modal-portal' }))
|
||||
: null;
|
||||
const derivedInput = () => {
|
||||
if (view === 'dashboard.serverCard') {
|
||||
const card = model as ServerCardModel;
|
||||
|
||||
return { server: createTestServer({ identifier: card.identifier, uuid: card.uuid, name: card.name }) };
|
||||
}
|
||||
|
||||
return view === 'server.files.details' ? { file: fileObject(model as FileDetailsModel) } : {};
|
||||
};
|
||||
|
||||
const session = (): Session => {
|
||||
if (view === 'server.files.editor') {
|
||||
return editorSession(model as FileEditorModel);
|
||||
}
|
||||
|
||||
return manager ? managerSession(manager) : NoSession;
|
||||
};
|
||||
|
||||
const input = options.input === undefined ? derivedInput() : Object(options.input);
|
||||
const Session = session();
|
||||
|
||||
const input = options.input === undefined ? (definition?.fixtureInput?.(model) ?? {}) : Object(options.input);
|
||||
const Session = definition?.fixtureScope ?? NoSession;
|
||||
const harness = createViewHarness(name, { model, inputs: input });
|
||||
|
||||
function Wrapper({ children }: { children?: ReactNode }) {
|
||||
@@ -368,7 +304,7 @@ export async function createViewTestHost<N extends ViewName>(
|
||||
<host.Wrapper>
|
||||
<ExtensionContext.Provider value={context}>
|
||||
<ViewFixtureProvider>
|
||||
<Session>
|
||||
<Session model={model}>
|
||||
<harness.Scope>{children}</harness.Scope>
|
||||
</Session>
|
||||
</ViewFixtureProvider>
|
||||
@@ -406,37 +342,28 @@ const viewRouter = createRouter({
|
||||
});
|
||||
let rendered: RenderedView | undefined;
|
||||
|
||||
/**
|
||||
* Renders a view synchronously from fixtures, with a theme's layers over classic when given. Each call
|
||||
* replaces the view rendered before it; nested views read their fixtures too.
|
||||
*/
|
||||
export function renderView<N extends ViewName>(name: N, options: RenderViewOptions<N> = {}): RenderedView {
|
||||
/** Replaces whatever was rendered before with `content`, under a theme's skins, views and icons. */
|
||||
function mount(content: ReactNode, theme: ThemeDefinition | undefined): RenderedView {
|
||||
rendered?.unmount();
|
||||
clearThemeLayers();
|
||||
clearThemeSkins();
|
||||
if (options.theme) {
|
||||
registerSkins('theme', options.theme.ui ?? {});
|
||||
registerViewLayer('theme', 'theme', options.theme.views ?? {});
|
||||
registerThemeIcons(options.theme.icons ?? {});
|
||||
if (theme) {
|
||||
registerSkins('theme', theme.ui ?? {});
|
||||
registerViewLayer('theme', 'theme', theme.views ?? {});
|
||||
registerThemeIcons(theme.icons ?? {});
|
||||
}
|
||||
|
||||
const container = document.body.appendChild(document.createElement('div'));
|
||||
const root = createRoot(container);
|
||||
// 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 };
|
||||
const view = (
|
||||
<QueryClientProvider client={queryClient}>
|
||||
<RouterContextProvider router={viewRouter}>
|
||||
<ViewFixtureProvider fixtures={fixtures} models={models}>
|
||||
<LooseView name={name} {...Object(options.input ?? {})} />
|
||||
</ViewFixtureProvider>
|
||||
</RouterContextProvider>
|
||||
</QueryClientProvider>
|
||||
);
|
||||
|
||||
Reflect.set(globalThis, 'IS_REACT_ACT_ENVIRONMENT', true);
|
||||
act(() => root.render(view));
|
||||
act(() =>
|
||||
root.render(
|
||||
<QueryClientProvider client={queryClient}>
|
||||
<RouterContextProvider router={viewRouter}>{content}</RouterContextProvider>
|
||||
</QueryClientProvider>
|
||||
)
|
||||
);
|
||||
rendered = {
|
||||
container,
|
||||
unmount: () => {
|
||||
@@ -448,3 +375,45 @@ export function renderView<N extends ViewName>(name: N, options: RenderViewOptio
|
||||
|
||||
return rendered;
|
||||
}
|
||||
|
||||
/**
|
||||
* Renders a view synchronously from fixtures, with a theme's layers over classic when given. Each call
|
||||
* replaces what was rendered before it; nested views read their fixtures too.
|
||||
*/
|
||||
export function renderView<N extends ViewName>(name: N, options: RenderViewOptions<N> = {}): RenderedView {
|
||||
// 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 };
|
||||
|
||||
return mount(
|
||||
<ViewFixtureProvider fixtures={fixtures} models={models}>
|
||||
<LooseView name={name} {...Object(options.input ?? {})} />
|
||||
</ViewFixtureProvider>,
|
||||
options.theme
|
||||
);
|
||||
}
|
||||
|
||||
export interface RenderPrimitiveOptions {
|
||||
/** The theme to render the primitive with: what its entry exports. */
|
||||
theme?: ThemeDefinition;
|
||||
}
|
||||
|
||||
/**
|
||||
* Renders a UI kit primitive synchronously with the theme's skins and replacements over classic's.
|
||||
* Each call replaces what was rendered before it.
|
||||
*/
|
||||
export function renderPrimitive<N extends UiPrimitiveName>(
|
||||
name: N,
|
||||
props: UiPrimitiveProps<N>,
|
||||
options?: RenderPrimitiveOptions
|
||||
): RenderedView;
|
||||
export function renderPrimitive(
|
||||
name: UiPrimitiveName,
|
||||
props: UiPrimitiveProps<UiPrimitiveName>,
|
||||
options: RenderPrimitiveOptions = {}
|
||||
): RenderedView {
|
||||
// The overload ties the props to the named primitive.
|
||||
const primitive = uiPrimitives[name].component as JSXElementConstructor<UiPrimitiveProps<UiPrimitiveName>>;
|
||||
|
||||
return mount(createElement(primitive, props), options.theme);
|
||||
}
|
||||
|
||||
@@ -0,0 +1,287 @@
|
||||
import type { ComponentProps, JSXElementConstructor, ReactElement } from 'react';
|
||||
import { Copy, Pencil, Server, Trash2 } from 'lucide-react';
|
||||
import {
|
||||
Alert,
|
||||
Avatar,
|
||||
Button,
|
||||
Checkbox,
|
||||
ContentBox,
|
||||
CopyOnClick,
|
||||
DropdownMenu,
|
||||
DropdownMenuItem,
|
||||
Empty,
|
||||
EmptyDescription,
|
||||
EmptyHeader,
|
||||
EmptyMedia,
|
||||
EmptyTitle,
|
||||
Input,
|
||||
Label,
|
||||
NumberInput,
|
||||
PageHeading,
|
||||
Pagination,
|
||||
Select,
|
||||
Spinner,
|
||||
Switch,
|
||||
Table,
|
||||
TextArea,
|
||||
TitledGreyBox,
|
||||
Tooltip,
|
||||
} from '@/sdk';
|
||||
|
||||
export interface UiPrimitive<C extends JSXElementConstructor<never> = JSXElementConstructor<never>> {
|
||||
readonly component: C;
|
||||
/** Rendered by the workbench's UI kit, by variant; the first is the default. */
|
||||
readonly samples: Readonly<Record<string, ReactElement>>;
|
||||
}
|
||||
|
||||
/** The component of each UI kit primitive by name; a new primitive adds itself here and to `uiPrimitives`. */
|
||||
export interface UiPrimitiveComponents {
|
||||
Button: typeof Button;
|
||||
Input: typeof Input;
|
||||
TextArea: typeof TextArea;
|
||||
NumberInput: typeof NumberInput;
|
||||
Select: typeof Select;
|
||||
Checkbox: typeof Checkbox;
|
||||
Switch: typeof Switch;
|
||||
Label: typeof Label;
|
||||
Alert: typeof Alert;
|
||||
Tooltip: typeof Tooltip;
|
||||
DropdownMenu: typeof DropdownMenu;
|
||||
Table: typeof Table;
|
||||
Pagination: typeof Pagination;
|
||||
Empty: typeof Empty;
|
||||
Spinner: typeof Spinner;
|
||||
Avatar: typeof Avatar;
|
||||
ContentBox: typeof ContentBox;
|
||||
TitledGreyBox: typeof TitledGreyBox;
|
||||
CopyOnClick: typeof CopyOnClick;
|
||||
PageHeading: typeof PageHeading;
|
||||
}
|
||||
|
||||
const noop = () => {};
|
||||
|
||||
const rows = [
|
||||
{ id: 'survival', name: 'Survival', memory: '4 GiB' },
|
||||
{ id: 'creative', name: 'Creative', memory: '2 GiB' },
|
||||
];
|
||||
const columns = [
|
||||
{ id: 'name', label: 'Name', cell: (row: (typeof rows)[number]) => row.name },
|
||||
{ id: 'memory', label: 'Memory', cell: (row: (typeof rows)[number]) => row.memory },
|
||||
];
|
||||
const page = (current: number, total: number) => ({
|
||||
data: rows,
|
||||
meta: { pagination: { total: total * 2, count: 2, per_page: 2, current_page: current, total_pages: total } },
|
||||
});
|
||||
const options = [
|
||||
{ value: 'paper', label: 'Paper' },
|
||||
{ value: 'vanilla', label: 'Vanilla' },
|
||||
];
|
||||
|
||||
/**
|
||||
* Every UI kit primitive with sample renders: the workbench's gallery and `renderPrimitive` read
|
||||
* this list, so a new primitive is added here with its variants.
|
||||
*/
|
||||
export type UiPrimitives = { readonly [N in keyof UiPrimitiveComponents]: UiPrimitive<UiPrimitiveComponents[N]> };
|
||||
|
||||
export const uiPrimitives: UiPrimitives = {
|
||||
Button: {
|
||||
component: Button,
|
||||
samples: {
|
||||
primary: <Button>Save changes</Button>,
|
||||
secondary: <Button isSecondary>Cancel</Button>,
|
||||
grey: <Button color='grey'>Details</Button>,
|
||||
danger: <Button color='red'>Delete</Button>,
|
||||
small: <Button size='xsmall'>Small</Button>,
|
||||
loading: <Button isLoading>Saving</Button>,
|
||||
disabled: <Button disabled>Unavailable</Button>,
|
||||
},
|
||||
},
|
||||
Input: {
|
||||
component: Input,
|
||||
samples: {
|
||||
default: <Input placeholder='Server name' />,
|
||||
filled: <Input defaultValue='Survival' />,
|
||||
error: <Input $hasError defaultValue='?' aria-invalid />,
|
||||
disabled: <Input disabled defaultValue='Locked' />,
|
||||
},
|
||||
},
|
||||
TextArea: {
|
||||
component: TextArea,
|
||||
samples: {
|
||||
default: <TextArea rows={3} placeholder='Description' />,
|
||||
filled: <TextArea rows={3} defaultValue={'A survival world\nwith friends.'} />,
|
||||
},
|
||||
},
|
||||
NumberInput: {
|
||||
component: NumberInput,
|
||||
samples: {
|
||||
default: <NumberInput value={1024} onValueChange={noop} aria-label='Memory' />,
|
||||
disabled: <NumberInput value={0} onValueChange={noop} disabled aria-label='Swap' />,
|
||||
},
|
||||
},
|
||||
Select: {
|
||||
component: Select,
|
||||
samples: {
|
||||
default: <Select value='paper' onChange={noop} options={options} />,
|
||||
placeholder: <Select value={null} onChange={noop} options={options} placeholder='Choose a server jar' />,
|
||||
disabled: <Select value='vanilla' onChange={noop} options={options} disabled />,
|
||||
},
|
||||
},
|
||||
Checkbox: {
|
||||
component: Checkbox,
|
||||
samples: {
|
||||
checked: <Checkbox checked onChange={noop} aria-label='Checked' />,
|
||||
unchecked: <Checkbox checked={false} onChange={noop} aria-label='Unchecked' />,
|
||||
indeterminate: <Checkbox checked={false} indeterminate onChange={noop} aria-label='Some' />,
|
||||
disabled: <Checkbox checked disabled onChange={noop} aria-label='Disabled' />,
|
||||
},
|
||||
},
|
||||
Switch: {
|
||||
component: Switch,
|
||||
samples: {
|
||||
on: <Switch checked onChange={noop} label='Start on boot' />,
|
||||
off: <Switch checked={false} onChange={noop} label='Start on boot' />,
|
||||
described: (
|
||||
<Switch
|
||||
checked
|
||||
onChange={noop}
|
||||
label='Crash detection'
|
||||
description='Restart the server after a crash.'
|
||||
/>
|
||||
),
|
||||
disabled: <Switch checked={false} disabled onChange={noop} label='Unavailable' />,
|
||||
},
|
||||
},
|
||||
Label: { component: Label, samples: { default: <Label>Server name</Label> } },
|
||||
Alert: {
|
||||
component: Alert,
|
||||
samples: {
|
||||
info: <Alert type='info'>Backups run every night at 03:00.</Alert>,
|
||||
success: (
|
||||
<Alert type='success' title='Saved'>
|
||||
Your changes are live.
|
||||
</Alert>
|
||||
),
|
||||
warning: <Alert type='warning'>This server is near its disk limit.</Alert>,
|
||||
danger: <Alert type='danger'>The node is unreachable.</Alert>,
|
||||
},
|
||||
},
|
||||
Tooltip: {
|
||||
component: Tooltip,
|
||||
samples: {
|
||||
default: (
|
||||
<Tooltip content='Copies the address'>
|
||||
<Button color='grey'>Hover me</Button>
|
||||
</Tooltip>
|
||||
),
|
||||
},
|
||||
},
|
||||
DropdownMenu: {
|
||||
component: DropdownMenu,
|
||||
samples: {
|
||||
default: (
|
||||
<DropdownMenu triggerContent='Actions'>
|
||||
<DropdownMenuItem icon={Pencil}>Rename</DropdownMenuItem>
|
||||
<DropdownMenuItem icon={Copy}>Duplicate</DropdownMenuItem>
|
||||
<DropdownMenuItem icon={Trash2} danger>
|
||||
Delete
|
||||
</DropdownMenuItem>
|
||||
</DropdownMenu>
|
||||
),
|
||||
},
|
||||
},
|
||||
Table: {
|
||||
component: Table,
|
||||
samples: {
|
||||
rows: <Table rows={rows} columns={columns} keyOf={(row) => row.id} emptyState='No servers.' />,
|
||||
empty: <Table rows={[]} columns={columns} keyOf={(row) => row.id} emptyState='No servers yet.' />,
|
||||
},
|
||||
},
|
||||
Pagination: {
|
||||
component: Pagination,
|
||||
samples: {
|
||||
first: (
|
||||
<Pagination data={page(1, 3)} onPageSelect={noop}>
|
||||
{({ items }) => items.map((row) => <p key={row.id}>{row.name}</p>)}
|
||||
</Pagination>
|
||||
),
|
||||
middle: (
|
||||
<Pagination data={page(2, 3)} onPageSelect={noop}>
|
||||
{({ items }) => items.map((row) => <p key={row.id}>{row.name}</p>)}
|
||||
</Pagination>
|
||||
),
|
||||
},
|
||||
},
|
||||
Empty: {
|
||||
component: Empty,
|
||||
samples: {
|
||||
default: (
|
||||
<Empty className='border'>
|
||||
<EmptyHeader>
|
||||
<EmptyMedia variant='icon'>
|
||||
<Server />
|
||||
</EmptyMedia>
|
||||
<EmptyTitle>No servers yet</EmptyTitle>
|
||||
<EmptyDescription>Servers you own or are invited to will appear here.</EmptyDescription>
|
||||
</EmptyHeader>
|
||||
</Empty>
|
||||
),
|
||||
},
|
||||
},
|
||||
Spinner: {
|
||||
component: Spinner,
|
||||
samples: {
|
||||
base: <Spinner />,
|
||||
small: <Spinner size='small' />,
|
||||
large: <Spinner size='large' />,
|
||||
},
|
||||
},
|
||||
Avatar: {
|
||||
component: Avatar,
|
||||
samples: {
|
||||
default: <Avatar name='11111111-1111-4111-8111-111111111111' size={40} />,
|
||||
square: <Avatar name='22222222-2222-4222-8222-222222222222' size={40} square />,
|
||||
},
|
||||
},
|
||||
ContentBox: {
|
||||
component: ContentBox,
|
||||
samples: {
|
||||
default: <ContentBox title='Resources'>Memory, disk and CPU limits.</ContentBox>,
|
||||
loading: (
|
||||
<ContentBox title='Resources' showLoadingOverlay>
|
||||
Memory, disk and CPU limits.
|
||||
</ContentBox>
|
||||
),
|
||||
},
|
||||
},
|
||||
TitledGreyBox: {
|
||||
component: TitledGreyBox,
|
||||
samples: {
|
||||
default: <TitledGreyBox title='SFTP details'>sftp://127.0.0.1:2022</TitledGreyBox>,
|
||||
},
|
||||
},
|
||||
CopyOnClick: {
|
||||
component: CopyOnClick,
|
||||
samples: {
|
||||
default: (
|
||||
<CopyOnClick text='127.0.0.1:25565'>
|
||||
<span className='font-mono text-sm'>127.0.0.1:25565</span>
|
||||
</CopyOnClick>
|
||||
),
|
||||
},
|
||||
},
|
||||
PageHeading: {
|
||||
component: PageHeading,
|
||||
samples: {
|
||||
default: <PageHeading title='Servers' description='Every server you own or are invited to.' />,
|
||||
actions: <PageHeading title='Backups' actions={<Button>Create backup</Button>} />,
|
||||
},
|
||||
},
|
||||
};
|
||||
|
||||
export type UiPrimitiveName = keyof UiPrimitiveComponents;
|
||||
export type UiPrimitiveProps<N extends UiPrimitiveName> = ComponentProps<UiPrimitiveComponents[N]>;
|
||||
|
||||
export function getUiPrimitive(name: string): UiPrimitive | undefined {
|
||||
return Object.entries(uiPrimitives).find(([key]) => key === name)?.[1];
|
||||
}
|
||||
@@ -6,6 +6,7 @@ import type * as RegistryModule from './registry';
|
||||
import type * as ViewModule from './View';
|
||||
import type * as LazyModule from './lazy';
|
||||
import type * as SessionModule from './session';
|
||||
import type { ViewProbe } from './inspect';
|
||||
import type * as ExtensionRegistry from '@/extensions/registry';
|
||||
|
||||
interface ProbeModel {
|
||||
@@ -82,6 +83,17 @@ function commitOverrides(entries: { id: string; component: ComponentType<never>
|
||||
}
|
||||
}
|
||||
|
||||
const wrapping = { wrap: true };
|
||||
const probes: ViewProbe[] = [];
|
||||
const collecting = {
|
||||
wrap: false,
|
||||
collect: (probe: ViewProbe) => {
|
||||
probes.push(probe);
|
||||
|
||||
return () => {};
|
||||
},
|
||||
};
|
||||
|
||||
describe('<View>', () => {
|
||||
it('stacks classic, the theme chain parent first, then extensions in configured order', async () => {
|
||||
define('test.order');
|
||||
@@ -309,18 +321,76 @@ describe('<View>', () => {
|
||||
expect(load).toHaveBeenCalledTimes(1);
|
||||
});
|
||||
|
||||
it('wraps each view for the inspector when inspection is on', async () => {
|
||||
vi.stubGlobal('SiteConfiguration', undefined);
|
||||
Object.assign(window, { SiteConfiguration: { theme: { inspect: true } } });
|
||||
vi.resetModules();
|
||||
const [registry, view] = await Promise.all([import('./registry'), import('./View')]);
|
||||
it('wraps each view for the inspector only while inspection is on', async () => {
|
||||
const { ViewInspectionContext } = await import('./inspect');
|
||||
|
||||
registry.registerViewDefinition({ name: 'test.inspect', kind: 'block', context: 'app', use });
|
||||
registry.registerViewLayer('classic', 'classic', { 'test.inspect': Classic });
|
||||
views.registerViewDefinition({ name: 'test.inspect', kind: 'block', context: 'app', use });
|
||||
views.registerViewLayer('classic', 'classic', { 'test.inspect': Classic });
|
||||
|
||||
const { container } = render(<view.View name='test.inspect' />);
|
||||
const { container, rerender } = render(<engine.View name='test.inspect' />);
|
||||
|
||||
expect(container.querySelector('[data-view]')).toBeNull();
|
||||
|
||||
rerender(
|
||||
<ViewInspectionContext.Provider value={wrapping}>
|
||||
<engine.View name='test.inspect' />
|
||||
</ViewInspectionContext.Provider>
|
||||
);
|
||||
|
||||
expect(container.querySelector('[data-view="test.inspect"]')).toHaveStyle({ display: 'contents' });
|
||||
Object.assign(window, { SiteConfiguration: undefined });
|
||||
});
|
||||
|
||||
it('records what each view rendered with, including a layer that failed', async () => {
|
||||
const { ViewInspectionContext } = await import('./inspect');
|
||||
|
||||
define('test.probe');
|
||||
views.registerViewLayer('classic', 'classic', { 'test.probe': Classic });
|
||||
views.registerViewLayer('aurora', 'theme', {
|
||||
'test.probe': () => {
|
||||
throw new Error('theme exploded');
|
||||
},
|
||||
});
|
||||
|
||||
render(
|
||||
<ViewInspectionContext.Provider value={collecting}>
|
||||
<engine.ViewFixtureProvider fixtures={{ 'test.probe': 'second' }}>
|
||||
<engine.View name='test.probe' />
|
||||
</engine.ViewFixtureProvider>
|
||||
</ViewInspectionContext.Provider>
|
||||
);
|
||||
|
||||
expect(screen.getByText('classic:second fixture')).toBeInTheDocument();
|
||||
expect(probes).toHaveLength(1);
|
||||
expect(probes[0].current()).toMatchObject({
|
||||
model: { name: 'second fixture' },
|
||||
layers: [{ id: 'classic' }, { id: 'aurora' }],
|
||||
failed: ['aurora'],
|
||||
});
|
||||
});
|
||||
|
||||
it('renders a fixture with the inputs and scope its view declares', () => {
|
||||
function Scope({ model, children }: { model: unknown; children?: ReactNode }) {
|
||||
return <section aria-label={`scope of ${String(Reflect.get(Object(model), 'name'))}`}>{children}</section>;
|
||||
}
|
||||
|
||||
function Card({ model, server }: ProbeProps & { server?: string }) {
|
||||
return <p>{`${model.name} on ${server}`}</p>;
|
||||
}
|
||||
|
||||
define('test.inputs', {
|
||||
fixtureInput: (model) => ({ server: `${Reflect.get(Object(model), 'name')} host` }),
|
||||
fixtureScope: Scope,
|
||||
});
|
||||
views.registerViewLayer('classic', 'classic', { 'test.inputs': Card });
|
||||
|
||||
render(
|
||||
<engine.ViewFixtureProvider>
|
||||
<engine.View name='test.inputs' />
|
||||
</engine.ViewFixtureProvider>
|
||||
);
|
||||
|
||||
expect(screen.getByRole('region', { name: 'scope of first fixture' })).toHaveTextContent(
|
||||
'first fixture on first fixture host'
|
||||
);
|
||||
});
|
||||
});
|
||||
|
||||
@@ -12,8 +12,8 @@ import {
|
||||
} from 'react';
|
||||
import ExtensionMount from '@/extensions/ExtensionMount';
|
||||
import { reportExtensionError } from '@/extensions/registry';
|
||||
import { getBootstrapTheme } from '@/bootstrap';
|
||||
import { cn } from '@/lib/cn';
|
||||
import { FailedLayerMark, InspectedViewBoundary, ViewInspectionContext } from './inspect';
|
||||
import { isPendingLazyView } from './lazy';
|
||||
import {
|
||||
declaredParts,
|
||||
@@ -43,8 +43,8 @@ export function ViewArea({ area, children }: { area: ViewContext; children?: Rea
|
||||
}
|
||||
|
||||
export interface ViewFixtureSelection {
|
||||
/** The fixture each view renders; views not listed render their first fixture. */
|
||||
readonly fixtures?: Readonly<Partial<Record<ViewName, string>>>;
|
||||
/** The fixture each view renders, extension-defined views included; views not listed render their first. */
|
||||
readonly fixtures?: { readonly [N in ViewName]?: string } & { readonly [name: string]: string | undefined };
|
||||
/** Explicit models, used before any fixture. */
|
||||
readonly models?: Readonly<Partial<ViewModels>>;
|
||||
}
|
||||
@@ -239,7 +239,12 @@ function ViewChain({
|
||||
name={name}
|
||||
layer={top}
|
||||
placeholder={placeholder}
|
||||
fallback={<ViewChain name={name} layers={below} frame={frame} placeholder={placeholder} />}
|
||||
fallback={
|
||||
<>
|
||||
<FailedLayerMark layerId={top.id} />
|
||||
<ViewChain name={name} layers={below} frame={frame} placeholder={placeholder} />
|
||||
</>
|
||||
}
|
||||
>
|
||||
{element}
|
||||
</LayerBoundary>
|
||||
@@ -257,6 +262,7 @@ interface BodyProps {
|
||||
|
||||
function ViewBody({ definition, model, inputs, className, children }: BodyProps & { model: unknown }) {
|
||||
const fixtures = useContext(FixtureContext);
|
||||
const inspection = useContext(ViewInspectionContext);
|
||||
const base = useViewChain(definition.name);
|
||||
const decision = useViewDecision(definition.name);
|
||||
const layers = useMemo(
|
||||
@@ -286,7 +292,7 @@ function ViewBody({ definition, model, inputs, className, children }: BodyProps
|
||||
}
|
||||
}
|
||||
|
||||
return (
|
||||
const chain = (
|
||||
<ViewChain
|
||||
name={definition.name}
|
||||
layers={layers}
|
||||
@@ -294,6 +300,20 @@ function ViewBody({ definition, model, inputs, className, children }: BodyProps
|
||||
frame={{ model, inputs, className, children }}
|
||||
/>
|
||||
);
|
||||
|
||||
return inspection ? (
|
||||
<InspectedViewBoundary
|
||||
inspection={inspection}
|
||||
definition={definition}
|
||||
model={model}
|
||||
inputs={inputs}
|
||||
layers={layers}
|
||||
>
|
||||
{chain}
|
||||
</InspectedViewBoundary>
|
||||
) : (
|
||||
chain
|
||||
);
|
||||
}
|
||||
|
||||
function LiveView(props: BodyProps) {
|
||||
@@ -302,8 +322,6 @@ function LiveView(props: BodyProps) {
|
||||
return <ViewBody {...props} model={useModel(props.inputs)} />;
|
||||
}
|
||||
|
||||
let inspecting: boolean | undefined;
|
||||
|
||||
type ViewElementBase = {
|
||||
readonly name: string;
|
||||
/** Renders nothing when no installed package defines the view. */
|
||||
@@ -313,6 +331,10 @@ type ViewElementBase = {
|
||||
};
|
||||
export type ViewElementProps<N extends string> = ViewElementBase & { readonly name: N } & ViewInput<N>;
|
||||
|
||||
function FixtureScope({ children }: { children?: ReactNode }) {
|
||||
return children;
|
||||
}
|
||||
|
||||
function RenderView({ name, optional = false, className, children, ...inputs }: ViewElementBase & LooseViewInput) {
|
||||
const definition = useViewDefinition(name);
|
||||
const selection = useContext(FixtureContext);
|
||||
@@ -332,17 +354,28 @@ function RenderView({ name, optional = false, className, children, ...inputs }:
|
||||
}
|
||||
|
||||
const fixture = selection ? fixtureModel(definition, selection) : undefined;
|
||||
const body = { definition, inputs, className, children };
|
||||
const content = fixture ? <ViewBody {...body} model={fixture.model} /> : <LiveView key={name} {...body} />;
|
||||
|
||||
inspecting ??= getBootstrapTheme().inspect;
|
||||
if (!fixture) {
|
||||
return (
|
||||
<LiveView key={name} definition={definition} inputs={inputs} className={className}>
|
||||
{children}
|
||||
</LiveView>
|
||||
);
|
||||
}
|
||||
|
||||
return inspecting ? (
|
||||
<div data-view={name} style={{ display: 'contents' }}>
|
||||
{content}
|
||||
</div>
|
||||
) : (
|
||||
content
|
||||
const Scope = definition.fixtureScope ?? FixtureScope;
|
||||
|
||||
return (
|
||||
<Scope model={fixture.model}>
|
||||
<ViewBody
|
||||
definition={definition}
|
||||
inputs={{ ...definition.fixtureInput?.(fixture.model), ...inputs }}
|
||||
className={className}
|
||||
model={fixture.model}
|
||||
>
|
||||
{children}
|
||||
</ViewBody>
|
||||
</Scope>
|
||||
);
|
||||
}
|
||||
|
||||
|
||||
@@ -329,6 +329,9 @@ export const dashboardViews = [
|
||||
context: 'app',
|
||||
use: useServerCardModel,
|
||||
slots: ['dashboard.serverRow.name.after'],
|
||||
fixtureInput: (card) => ({
|
||||
server: createTestServer({ identifier: card.identifier, uuid: card.uuid, name: card.name }),
|
||||
}),
|
||||
placeholder: createElement('div', {
|
||||
className: 'h-12 animate-pulse rounded-sm bg-muted',
|
||||
'aria-label': 'Loading server card',
|
||||
|
||||
@@ -1,3 +1,4 @@
|
||||
import type { ClientFileObjectResource as FileObject } from '@/api/extensionTypes';
|
||||
import type { Server } from '@/api/server/types';
|
||||
import type { ServerCardModel } from './dashboard';
|
||||
import type { FileDetailsModel, FileEditorModel, FileManagerEntry, FileManagerModel } from './files';
|
||||
@@ -70,6 +71,26 @@ export function createTestFileDetails(options: Partial<FileDetailsModel> = {}):
|
||||
return { name: 'config.json', kind: 'file', size: 1024, modifiedAt: '2026-01-01T12:00:00Z', ...options };
|
||||
}
|
||||
|
||||
/** The file object a file details model was read from. */
|
||||
export function createTestFileObject(model: FileDetailsModel): FileObject {
|
||||
const directory = model.kind === 'directory';
|
||||
|
||||
return {
|
||||
object: 'file_object',
|
||||
attributes: {
|
||||
name: model.name,
|
||||
mode: directory ? 'drwxr-xr-x' : '-rw-r--r--',
|
||||
mode_bits: directory ? '0755' : '0644',
|
||||
size: model.size,
|
||||
is_file: !directory,
|
||||
is_symlink: model.kind === 'symlink',
|
||||
mimetype: directory ? 'inode/directory' : 'text/plain',
|
||||
created_at: model.modifiedAt,
|
||||
modified_at: model.modifiedAt,
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
export function createTestFileEditor(options: Partial<FileEditorModel> = {}): FileEditorModel {
|
||||
return {
|
||||
path: '/config/server.properties',
|
||||
|
||||
@@ -0,0 +1,123 @@
|
||||
import { createContext, useContext, useLayoutEffect, useState, type ReactNode } from 'react';
|
||||
import type { LooseViewInput, ViewDefinition, ViewLayer } from './registry';
|
||||
|
||||
/** What a view last rendered with, for the inspector and the workbench. */
|
||||
export interface InspectedView {
|
||||
readonly definition: ViewDefinition;
|
||||
readonly model: unknown;
|
||||
readonly inputs: LooseViewInput;
|
||||
/** Bottom first: classic or the defining extension, the theme chain, then extension overrides. */
|
||||
readonly layers: readonly ViewLayer[];
|
||||
/** Layers that failed, so the layer below them rendered instead. */
|
||||
readonly failed: readonly string[];
|
||||
}
|
||||
|
||||
export interface ViewProbe {
|
||||
current(): InspectedView;
|
||||
subscribe(listener: () => void): () => void;
|
||||
}
|
||||
|
||||
interface MutableProbe extends ViewProbe {
|
||||
update(view: Omit<InspectedView, 'failed'>): void;
|
||||
fail(layerId: string): () => void;
|
||||
}
|
||||
|
||||
export interface ViewInspection {
|
||||
/** Render `data-view` wrappers (`display: contents`) the inspector outlines. */
|
||||
readonly wrap: boolean;
|
||||
/** Receives each view as it mounts and returns its cleanup. */
|
||||
readonly collect?: (probe: ViewProbe) => () => void;
|
||||
}
|
||||
|
||||
/** Set only while something inspects views; without it views render no wrappers and keep no records. */
|
||||
export const ViewInspectionContext = createContext<ViewInspection | null>(null);
|
||||
const ProbeContext = createContext<MutableProbe | null>(null);
|
||||
const probes = new WeakMap<Element, ViewProbe>();
|
||||
|
||||
function createProbe(initial: Omit<InspectedView, 'failed'>): MutableProbe {
|
||||
const listeners = new Set<() => void>();
|
||||
const failed = new Set<string>();
|
||||
let view = initial;
|
||||
let snapshot: InspectedView | undefined;
|
||||
const publish = () => {
|
||||
snapshot = undefined;
|
||||
for (const listener of listeners) {
|
||||
listener();
|
||||
}
|
||||
};
|
||||
|
||||
return {
|
||||
current: () => (snapshot ??= Object.freeze({ ...view, failed: [...failed] })),
|
||||
subscribe(listener) {
|
||||
listeners.add(listener);
|
||||
|
||||
return () => {
|
||||
listeners.delete(listener);
|
||||
};
|
||||
},
|
||||
update(next) {
|
||||
if (next.model !== view.model || next.inputs !== view.inputs || next.layers !== view.layers) {
|
||||
view = next;
|
||||
publish();
|
||||
}
|
||||
},
|
||||
fail(layerId) {
|
||||
failed.add(layerId);
|
||||
publish();
|
||||
|
||||
return () => {
|
||||
failed.delete(layerId);
|
||||
publish();
|
||||
};
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
/** The view whose `data-view` wrapper this is. */
|
||||
export function getViewProbe(element: Element): ViewProbe | undefined {
|
||||
return probes.get(element);
|
||||
}
|
||||
|
||||
export function InspectedViewBoundary({
|
||||
inspection,
|
||||
children,
|
||||
...view
|
||||
}: Omit<InspectedView, 'failed'> & { inspection: ViewInspection; children?: ReactNode }) {
|
||||
const [probe] = useState(() => createProbe(view));
|
||||
const { definition, model, inputs, layers } = view;
|
||||
|
||||
useLayoutEffect(
|
||||
() => probe.update({ definition, model, inputs, layers }),
|
||||
[probe, definition, model, inputs, layers]
|
||||
);
|
||||
useLayoutEffect(() => inspection.collect?.(probe), [inspection, probe]);
|
||||
|
||||
const content = <ProbeContext.Provider value={probe}>{children}</ProbeContext.Provider>;
|
||||
|
||||
if (!inspection.wrap) {
|
||||
return content;
|
||||
}
|
||||
|
||||
return (
|
||||
<div
|
||||
data-view={definition.name}
|
||||
style={{ display: 'contents' }}
|
||||
ref={(element) => {
|
||||
if (element) {
|
||||
probes.set(element, probe);
|
||||
}
|
||||
}}
|
||||
>
|
||||
{content}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
/** Rendered in place of a layer that failed, so inspection shows which layer rendered. */
|
||||
export function FailedLayerMark({ layerId }: { layerId: string }) {
|
||||
const probe = useContext(ProbeContext);
|
||||
|
||||
useLayoutEffect(() => probe?.fail(layerId), [probe, layerId]);
|
||||
|
||||
return null;
|
||||
}
|
||||
@@ -0,0 +1,163 @@
|
||||
import { useEffect, useReducer, useRef, useState, useSyncExternalStore } from 'react';
|
||||
import { createPortal } from 'react-dom';
|
||||
import { getViewProbe } from '@/views/inspect';
|
||||
import { cn } from '@/lib/cn';
|
||||
import { getInspectableFrames, subscribeInspectableFrames } from './frames';
|
||||
import { closestView, isElement, viewRect } from './geometry';
|
||||
import { InspectorPanel } from './InspectorPanel';
|
||||
import { renderingLayer } from './snippets';
|
||||
|
||||
/** Pointer events the page must not see while the inspector picks views. */
|
||||
const BLOCKED = ['pointerdown', 'mousedown', 'pointerup', 'mouseup', 'dblclick', 'contextmenu'] as const;
|
||||
|
||||
const inInspector = (target: EventTarget | null) => isElement(target) && !!target.closest('[data-inspector]');
|
||||
|
||||
function Outline({ element, pinned }: { element: Element; pinned?: boolean }) {
|
||||
const rect = viewRect(element);
|
||||
const name = element.getAttribute('data-view');
|
||||
const probe = getViewProbe(element);
|
||||
const layer = probe && renderingLayer(probe.current());
|
||||
|
||||
if (!rect) {
|
||||
return null;
|
||||
}
|
||||
|
||||
return (
|
||||
<div
|
||||
className={cn(
|
||||
'fixed rounded-xs border-2',
|
||||
pinned ? 'border-accent bg-accent/5' : 'border-primary bg-primary/10'
|
||||
)}
|
||||
style={{ left: rect.left, top: rect.top, width: rect.width, height: rect.height }}
|
||||
>
|
||||
{!pinned && (
|
||||
<span
|
||||
className={cn(
|
||||
'absolute left-[-2px] whitespace-nowrap rounded-xs bg-primary px-1.5 py-0.5 font-mono text-xs text-primary-foreground',
|
||||
rect.top > 24 ? 'bottom-full mb-0.5' : 'top-full mt-0.5'
|
||||
)}
|
||||
>
|
||||
{name}
|
||||
{layer && layer.source !== 'classic' && <span className='opacity-75'> · {layer.id}</span>}
|
||||
</span>
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
/** Outlines views under the pointer and pins one in the panel; loaded only while inspecting. */
|
||||
export default function InspectorOverlay({ onExit }: { onExit: () => void }) {
|
||||
const [hovered, setHovered] = useState<Element | null>(null);
|
||||
const [pinned, setPinned] = useState<Element | null>(null);
|
||||
const [, redraw] = useReducer((count: number) => count + 1, 0);
|
||||
const frames = useSyncExternalStore(subscribeInspectableFrames, getInspectableFrames);
|
||||
const pinnedRef = useRef(pinned);
|
||||
const exitRef = useRef(onExit);
|
||||
|
||||
pinnedRef.current = pinned;
|
||||
exitRef.current = onExit;
|
||||
|
||||
useEffect(() => {
|
||||
const documents = [document, ...frames.flatMap((frame) => frame.contentDocument ?? [])];
|
||||
let frame = 0;
|
||||
const schedule = () => {
|
||||
frame ||= requestAnimationFrame(() => {
|
||||
frame = 0;
|
||||
redraw();
|
||||
});
|
||||
};
|
||||
|
||||
const onMove = (event: PointerEvent) => {
|
||||
const { target } = event;
|
||||
|
||||
setHovered(isElement(target) && !inInspector(target) ? closestView(target) : null);
|
||||
schedule();
|
||||
};
|
||||
|
||||
const block = (event: Event) => {
|
||||
if (!inInspector(event.target)) {
|
||||
event.preventDefault();
|
||||
event.stopPropagation();
|
||||
}
|
||||
};
|
||||
|
||||
const onClick = (event: MouseEvent) => {
|
||||
if (inInspector(event.target)) {
|
||||
return;
|
||||
}
|
||||
|
||||
block(event);
|
||||
const view = isElement(event.target) ? closestView(event.target) : null;
|
||||
|
||||
if (view) {
|
||||
setPinned(view);
|
||||
}
|
||||
};
|
||||
|
||||
const onKey = (event: KeyboardEvent) => {
|
||||
if (event.key !== 'Escape') {
|
||||
return;
|
||||
}
|
||||
|
||||
event.preventDefault();
|
||||
if (pinnedRef.current) {
|
||||
setPinned(null);
|
||||
} else {
|
||||
exitRef.current();
|
||||
}
|
||||
};
|
||||
|
||||
const cursor = Object.assign(document.createElement('style'), {
|
||||
textContent: '* { cursor: crosshair !important; } [data-inspector] * { cursor: auto !important; }',
|
||||
});
|
||||
|
||||
document.head.append(cursor);
|
||||
for (const target of documents) {
|
||||
target.addEventListener('pointermove', onMove, true);
|
||||
target.addEventListener('click', onClick, true);
|
||||
target.addEventListener('keydown', onKey, true);
|
||||
target.addEventListener('scroll', schedule, true);
|
||||
for (const type of BLOCKED) {
|
||||
target.addEventListener(type, block, true);
|
||||
}
|
||||
}
|
||||
|
||||
window.addEventListener('resize', schedule);
|
||||
|
||||
return () => {
|
||||
cancelAnimationFrame(frame);
|
||||
cursor.remove();
|
||||
window.removeEventListener('resize', schedule);
|
||||
for (const target of documents) {
|
||||
target.removeEventListener('pointermove', onMove, true);
|
||||
target.removeEventListener('click', onClick, true);
|
||||
target.removeEventListener('keydown', onKey, true);
|
||||
target.removeEventListener('scroll', schedule, true);
|
||||
for (const type of BLOCKED) {
|
||||
target.removeEventListener(type, block, true);
|
||||
}
|
||||
}
|
||||
};
|
||||
}, [frames]);
|
||||
|
||||
return createPortal(
|
||||
<div data-inspector className='pointer-events-none fixed inset-0 z-[2147483000]'>
|
||||
{pinned?.isConnected && <Outline element={pinned} pinned />}
|
||||
{hovered && hovered !== pinned && hovered.isConnected && <Outline element={hovered} />}
|
||||
<div
|
||||
role='status'
|
||||
className='pointer-events-auto fixed top-3 left-1/2 flex -translate-x-1/2 items-center gap-3 rounded-full border border-border bg-popover px-4 py-1.5 text-xs text-popover-foreground shadow-lg'
|
||||
>
|
||||
<span>
|
||||
<strong className='font-semibold'>Inspecting views.</strong> Click one to pin it, Esc to{' '}
|
||||
{pinned ? 'unpin' : 'stop'}.
|
||||
</span>
|
||||
<button type='button' className='text-accent hover:underline' onClick={onExit}>
|
||||
Stop
|
||||
</button>
|
||||
</div>
|
||||
{pinned && <InspectorPanel element={pinned} onPin={setPinned} onClose={() => setPinned(null)} />}
|
||||
</div>,
|
||||
document.body
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,147 @@
|
||||
import { useMemo, useSyncExternalStore } from 'react';
|
||||
import { ChevronRight, X } from 'lucide-react';
|
||||
import { getViewProbe, type ViewProbe } from '@/views/inspect';
|
||||
import { parentViews, viewElements } from './geometry';
|
||||
import { modelJson } from './model';
|
||||
import { CopyButton, LayerStack, ModelTree, OverrideHelp, Section, SlotList, TokenList } from './parts';
|
||||
import { themeSettingTokens, tokensInUse } from './tokens';
|
||||
|
||||
interface PanelProps {
|
||||
element: Element;
|
||||
onPin: (element: Element) => void;
|
||||
onClose: () => void;
|
||||
}
|
||||
|
||||
/** Views below this one, by name, with the first of each to pin. */
|
||||
function nestedViews(wrapper: Element): { name: string; count: number; element: Element }[] {
|
||||
const found = new Map<string, { name: string; count: number; element: Element }>();
|
||||
|
||||
for (const element of wrapper.querySelectorAll('[data-view]')) {
|
||||
const name = element.getAttribute('data-view') ?? '';
|
||||
const entry = found.get(name);
|
||||
|
||||
found.set(name, entry ? { ...entry, count: entry.count + 1 } : { name, count: 1, element });
|
||||
}
|
||||
|
||||
return [...found.values()];
|
||||
}
|
||||
|
||||
function ViewPanel({ element, probe, onPin, onClose }: PanelProps & { probe: ViewProbe }) {
|
||||
const view = useSyncExternalStore(probe.subscribe, probe.current);
|
||||
const { definition } = view;
|
||||
const parents = useMemo(
|
||||
() =>
|
||||
parentViews(element)
|
||||
.map((parent, level) => ({ parent, level }))
|
||||
.reverse(),
|
||||
[element]
|
||||
);
|
||||
const nested = useMemo(() => nestedViews(element), [element]);
|
||||
const tokens = useMemo(() => tokensInUse(viewElements(element)), [element]);
|
||||
const settings = useMemo(() => themeSettingTokens(document), []);
|
||||
const hasInputs = Object.keys(view.inputs).length > 0;
|
||||
|
||||
return (
|
||||
<aside
|
||||
aria-label='View inspector'
|
||||
className='pointer-events-auto fixed inset-y-0 right-0 flex w-[26rem] max-w-full flex-col border-l border-border bg-card text-card-foreground shadow-2xl'
|
||||
>
|
||||
<header className='border-b border-border px-4 py-3'>
|
||||
{parents.length > 0 && (
|
||||
<nav aria-label='Enclosing views' className='mb-1 flex flex-wrap items-center gap-1 text-xs'>
|
||||
{parents.map(({ parent, level }) => (
|
||||
<span key={level} className='inline-flex items-center gap-1'>
|
||||
<button
|
||||
type='button'
|
||||
className='font-mono text-muted-foreground hover:text-foreground'
|
||||
onClick={() => onPin(parent)}
|
||||
>
|
||||
{parent.getAttribute('data-view')}
|
||||
</button>
|
||||
<ChevronRight className='h-3 w-3 text-muted-foreground' aria-hidden />
|
||||
</span>
|
||||
))}
|
||||
</nav>
|
||||
)}
|
||||
<div className='flex items-start gap-3'>
|
||||
<div className='min-w-0 flex-1'>
|
||||
<h2 className='truncate font-mono text-base font-semibold'>{definition.name}</h2>
|
||||
<p className='text-xs text-muted-foreground'>
|
||||
{definition.kind} · {definition.context} context
|
||||
{definition.extensionId && ` · defined by ${definition.extensionId}`}
|
||||
</p>
|
||||
</div>
|
||||
<button
|
||||
type='button'
|
||||
aria-label='Close the inspector panel'
|
||||
className='rounded-sm p-1 text-muted-foreground hover:bg-popover hover:text-foreground'
|
||||
onClick={onClose}
|
||||
>
|
||||
<X className='h-4 w-4' aria-hidden />
|
||||
</button>
|
||||
</div>
|
||||
{!element.isConnected && (
|
||||
<p className='mt-2 text-xs text-warning'>This view is no longer on the page.</p>
|
||||
)}
|
||||
</header>
|
||||
<div className='min-h-0 flex-1 overflow-y-auto'>
|
||||
<Section title='Override'>
|
||||
<OverrideHelp name={definition.name} />
|
||||
</Section>
|
||||
<Section title='Layers' count={view.layers.length}>
|
||||
<LayerStack view={view} />
|
||||
</Section>
|
||||
<Section title='Model'>
|
||||
<div className='mb-2 flex justify-end'>
|
||||
<CopyButton text={modelJson(view.model)} label='Copy JSON' />
|
||||
</div>
|
||||
<ModelTree value={view.model} />
|
||||
</Section>
|
||||
{hasInputs && (
|
||||
<Section title='Inputs' open={false}>
|
||||
<ModelTree value={view.inputs} />
|
||||
</Section>
|
||||
)}
|
||||
<Section title='Slots' count={definition.slots?.length ?? 0}>
|
||||
<SlotList slots={definition.slots ?? []} />
|
||||
</Section>
|
||||
{nested.length > 0 && (
|
||||
<Section title='Nested views' count={nested.length}>
|
||||
<ul className='space-y-1'>
|
||||
{nested.map((entry) => (
|
||||
<li key={entry.name}>
|
||||
<button
|
||||
type='button'
|
||||
className='font-mono text-xs text-accent hover:underline'
|
||||
onClick={() => onPin(entry.element)}
|
||||
>
|
||||
{entry.name}
|
||||
</button>
|
||||
{entry.count > 1 && (
|
||||
<span className='ml-1 text-xs text-muted-foreground'>×{entry.count}</span>
|
||||
)}
|
||||
</li>
|
||||
))}
|
||||
</ul>
|
||||
</Section>
|
||||
)}
|
||||
<Section title='Tokens in use' count={tokens.length}>
|
||||
<TokenList tokens={tokens} empty='No rule on this view reads a custom property.' />
|
||||
</Section>
|
||||
<Section title='Theme settings' open={false}>
|
||||
<TokenList tokens={settings.tokens} empty='The active theme sets no tokens.' />
|
||||
<div className='mt-3'>
|
||||
<TokenList tokens={settings.attributes} empty='No attributes on the document.' />
|
||||
</div>
|
||||
</Section>
|
||||
</div>
|
||||
</aside>
|
||||
);
|
||||
}
|
||||
|
||||
/** The pinned view's name, layers, model, slots and tokens, with the snippet to override it. */
|
||||
export function InspectorPanel(props: PanelProps) {
|
||||
const probe = getViewProbe(props.element);
|
||||
|
||||
return probe ? <ViewPanel {...props} probe={probe} /> : null;
|
||||
}
|
||||
@@ -0,0 +1,64 @@
|
||||
import { lazy, Suspense, useEffect, useState, type ReactNode } from 'react';
|
||||
import { ScanSearch } from 'lucide-react';
|
||||
import { getBootstrapTheme } from '@/bootstrap';
|
||||
import { cn } from '@/lib/cn';
|
||||
import { ViewInspectionContext, type ViewInspection } from '@/views/inspect';
|
||||
|
||||
const InspectorOverlay = lazy(() => import('./InspectorOverlay'));
|
||||
const inspection: ViewInspection = { wrap: true };
|
||||
|
||||
/** Alt+Shift+I, by key position so macOS's dead keys do not get in the way. */
|
||||
export const isInspectorShortcut = (event: KeyboardEvent): boolean =>
|
||||
event.altKey && event.shiftKey && !event.ctrlKey && !event.metaKey && event.code === 'KeyI';
|
||||
|
||||
function InspectorRoot({ children }: { children?: ReactNode }) {
|
||||
const [on, setOn] = useState(false);
|
||||
|
||||
useEffect(() => {
|
||||
const onKey = (event: KeyboardEvent) => {
|
||||
if (isInspectorShortcut(event)) {
|
||||
event.preventDefault();
|
||||
setOn((current) => !current);
|
||||
}
|
||||
};
|
||||
|
||||
window.addEventListener('keydown', onKey);
|
||||
|
||||
return () => window.removeEventListener('keydown', onKey);
|
||||
}, []);
|
||||
|
||||
return (
|
||||
<>
|
||||
<ViewInspectionContext.Provider value={on ? inspection : null}>{children}</ViewInspectionContext.Provider>
|
||||
<button
|
||||
type='button'
|
||||
data-inspector
|
||||
aria-pressed={on}
|
||||
aria-label='Inspect views'
|
||||
title='Inspect views (Alt+Shift+I)'
|
||||
className={cn(
|
||||
'fixed bottom-4 left-4 z-[2147483001] flex h-9 w-9 items-center justify-center rounded-full border shadow-lg transition-colors',
|
||||
on
|
||||
? 'border-primary bg-primary text-primary-foreground'
|
||||
: 'border-border bg-popover text-muted-foreground opacity-60 hover:opacity-100'
|
||||
)}
|
||||
onClick={() => setOn((current) => !current)}
|
||||
>
|
||||
<ScanSearch className='h-4 w-4' aria-hidden />
|
||||
</button>
|
||||
{on && (
|
||||
<Suspense fallback={null}>
|
||||
<InspectorOverlay onExit={() => setOn(false)} />
|
||||
</Suspense>
|
||||
)}
|
||||
</>
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* The view inspector, when the server allows it (debug mode, or a root admin with `?inspect=1`).
|
||||
* Off, it renders no wrappers and listens only for its shortcut.
|
||||
*/
|
||||
export function ViewInspector({ children }: { children?: ReactNode }) {
|
||||
return getBootstrapTheme().inspect ? <InspectorRoot>{children}</InspectorRoot> : children;
|
||||
}
|
||||
@@ -0,0 +1,33 @@
|
||||
const frames = new Set<HTMLIFrameElement>();
|
||||
const listeners = new Set<() => void>();
|
||||
let snapshot: readonly HTMLIFrameElement[] = [];
|
||||
|
||||
const publish = () => {
|
||||
snapshot = [...frames];
|
||||
for (const listener of listeners) {
|
||||
listener();
|
||||
}
|
||||
};
|
||||
|
||||
/** A same-origin frame, such as a workbench preview, whose views the inspector reaches too. */
|
||||
export function registerInspectableFrame(frame: HTMLIFrameElement): () => void {
|
||||
frames.add(frame);
|
||||
publish();
|
||||
|
||||
return () => {
|
||||
frames.delete(frame);
|
||||
publish();
|
||||
};
|
||||
}
|
||||
|
||||
export function getInspectableFrames(): readonly HTMLIFrameElement[] {
|
||||
return snapshot;
|
||||
}
|
||||
|
||||
export function subscribeInspectableFrames(listener: () => void): () => void {
|
||||
listeners.add(listener);
|
||||
|
||||
return () => {
|
||||
listeners.delete(listener);
|
||||
};
|
||||
}
|
||||
@@ -0,0 +1,80 @@
|
||||
/** Works across documents, where `instanceof Element` does not. */
|
||||
export const isElement = (node: EventTarget | null): node is Element =>
|
||||
!!node && 'nodeType' in node && node.nodeType === Node.ELEMENT_NODE;
|
||||
|
||||
const isContents = (element: Element) =>
|
||||
element.ownerDocument.defaultView?.getComputedStyle(element).display === 'contents';
|
||||
|
||||
/** The elements that draw a view: its wrapper and nested wrappers are `display: contents`. */
|
||||
export function viewElements(wrapper: Element): Element[] {
|
||||
return [...wrapper.children].flatMap((child) => (isContents(child) ? viewElements(child) : [child]));
|
||||
}
|
||||
|
||||
interface FrameOffset {
|
||||
readonly x: number;
|
||||
readonly y: number;
|
||||
readonly scale: number;
|
||||
}
|
||||
|
||||
/** Where a document's coordinates sit in the top window, for views inside a workbench frame. */
|
||||
function frameOffset(element: Element): FrameOffset {
|
||||
const frame = element.ownerDocument.defaultView?.frameElement;
|
||||
|
||||
if (!frame || !(frame instanceof HTMLElement) || !frame.offsetWidth) {
|
||||
return { x: 0, y: 0, scale: 1 };
|
||||
}
|
||||
|
||||
const rect = frame.getBoundingClientRect();
|
||||
const scale = rect.width / frame.offsetWidth;
|
||||
|
||||
return { x: rect.left + frame.clientLeft * scale, y: rect.top + frame.clientTop * scale, scale };
|
||||
}
|
||||
|
||||
/** The box a view's content covers in the top window, or null when it draws nothing. */
|
||||
export function viewRect(wrapper: Element): DOMRect | null {
|
||||
const boxes: DOMRect[] = [];
|
||||
const visit = (node: Node) => {
|
||||
for (const child of node.childNodes) {
|
||||
if (isElement(child)) {
|
||||
if (isContents(child)) {
|
||||
visit(child);
|
||||
} else {
|
||||
boxes.push(child.getBoundingClientRect());
|
||||
}
|
||||
} else if (child.nodeType === Node.TEXT_NODE && child.textContent?.trim()) {
|
||||
const range = child.ownerDocument?.createRange();
|
||||
|
||||
range?.selectNodeContents(child);
|
||||
boxes.push(range?.getBoundingClientRect() ?? new DOMRect());
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
visit(wrapper);
|
||||
|
||||
const drawn = boxes.filter((box) => box.width > 0 || box.height > 0);
|
||||
|
||||
if (!drawn.length) {
|
||||
return null;
|
||||
}
|
||||
|
||||
const { x, y, scale } = frameOffset(wrapper);
|
||||
const left = Math.min(...drawn.map((box) => box.left));
|
||||
const top = Math.min(...drawn.map((box) => box.top));
|
||||
const right = Math.max(...drawn.map((box) => box.right));
|
||||
const bottom = Math.max(...drawn.map((box) => box.bottom));
|
||||
|
||||
return new DOMRect(x + left * scale, y + top * scale, (right - left) * scale, (bottom - top) * scale);
|
||||
}
|
||||
|
||||
/** The nearest view wrapper enclosing a node, itself included. */
|
||||
export function closestView(node: Element): Element | null {
|
||||
return node.closest('[data-view]');
|
||||
}
|
||||
|
||||
/** Views enclosing this one, nearest first. */
|
||||
export function parentViews(wrapper: Element): Element[] {
|
||||
const parent = wrapper.parentElement?.closest('[data-view]');
|
||||
|
||||
return parent ? [parent, ...parentViews(parent)] : [];
|
||||
}
|
||||
@@ -0,0 +1,223 @@
|
||||
/** @vitest-environment jsdom */
|
||||
import { act, cleanup, fireEvent, render, screen, within } from '@testing-library/react';
|
||||
import { createElement, type ReactElement, type ReactNode } from 'react';
|
||||
import { afterEach, beforeAll, beforeEach, describe, expect, it, vi } from 'vitest';
|
||||
import { registerViewDefinition, registerViewLayer } from '@/views/registry';
|
||||
import { View } from '@/views/View';
|
||||
import { describeModel, modelJson } from './model';
|
||||
import { isEjectable, overrideSnippet, renderingLayer } from './snippets';
|
||||
import { tokensInUse } from './tokens';
|
||||
import { ViewInspector } from './ViewInspector';
|
||||
|
||||
const copy = vi.hoisted(() => vi.fn(async () => true));
|
||||
|
||||
vi.mock('@/lib/clipboard', () => ({ default: copy }));
|
||||
|
||||
interface CardModel {
|
||||
name: string;
|
||||
open: () => void;
|
||||
}
|
||||
|
||||
const open = vi.fn();
|
||||
|
||||
beforeAll(() => {
|
||||
registerViewDefinition({
|
||||
name: 'test.page',
|
||||
kind: 'page',
|
||||
context: 'app',
|
||||
use: () => ({}),
|
||||
slots: ['dashboard.before'],
|
||||
});
|
||||
registerViewDefinition({
|
||||
name: 'test.card',
|
||||
kind: 'block',
|
||||
context: 'app',
|
||||
use: (): CardModel => ({ name: 'Survival', open }),
|
||||
slots: ['dashboard.serverRow.name.after'],
|
||||
});
|
||||
registerViewLayer('classic', 'classic', {
|
||||
'test.page': () => (
|
||||
<main>
|
||||
<View name='test.card' />
|
||||
</main>
|
||||
),
|
||||
'test.card': ({ model }: { model: CardModel }) => (
|
||||
<button type='button' onClick={model.open}>
|
||||
{`Card ${model.name}`}
|
||||
</button>
|
||||
),
|
||||
});
|
||||
registerViewLayer('aurora', 'theme', {
|
||||
'test.card': ({ Default }: { Default: () => ReactNode }) => (
|
||||
<div className='aurora-card'>
|
||||
<Default />
|
||||
</div>
|
||||
),
|
||||
});
|
||||
});
|
||||
|
||||
beforeEach(() => {
|
||||
Object.assign(window, { SiteConfiguration: { theme: { inspect: true } } });
|
||||
vi.spyOn(Element.prototype, 'getBoundingClientRect').mockReturnValue(new DOMRect(10, 40, 200, 30));
|
||||
});
|
||||
|
||||
afterEach(() => {
|
||||
cleanup();
|
||||
vi.restoreAllMocks();
|
||||
open.mockReset();
|
||||
Object.assign(window, { SiteConfiguration: undefined });
|
||||
});
|
||||
|
||||
const page = () => render(<ViewInspector>{createElement(View, { name: 'test.page' })}</ViewInspector>);
|
||||
const toggle = () =>
|
||||
act(async () => {
|
||||
fireEvent.keyDown(window, { code: 'KeyI', key: 'ˆ', altKey: true, shiftKey: true });
|
||||
});
|
||||
|
||||
describe('ViewInspector', () => {
|
||||
it('adds nothing at all when the server does not allow inspection', async () => {
|
||||
Object.assign(window, { SiteConfiguration: { theme: { inspect: false } } });
|
||||
|
||||
const { container } = page();
|
||||
|
||||
await toggle();
|
||||
|
||||
expect(screen.queryByRole('button', { name: 'Inspect views' })).not.toBeInTheDocument();
|
||||
expect(container.querySelector('[data-view]')).toBeNull();
|
||||
});
|
||||
|
||||
it('wraps views only while on, toggled by Alt+Shift+I or its button', async () => {
|
||||
const { container } = page();
|
||||
const button = screen.getByRole('button', { name: 'Inspect views' });
|
||||
|
||||
expect(button).toHaveAttribute('aria-pressed', 'false');
|
||||
expect(container.querySelector('[data-view]')).toBeNull();
|
||||
|
||||
await toggle();
|
||||
|
||||
expect(await screen.findByText(/Inspecting views/)).toBeInTheDocument();
|
||||
expect([...container.querySelectorAll('[data-view]')].map((node) => node.getAttribute('data-view'))).toEqual([
|
||||
'test.page',
|
||||
'test.card',
|
||||
]);
|
||||
|
||||
fireEvent.click(button);
|
||||
|
||||
expect(button).toHaveAttribute('aria-pressed', 'false');
|
||||
expect(container.querySelector('[data-view]')).toBeNull();
|
||||
expect(screen.queryByText(/Inspecting views/)).not.toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('outlines the view under the pointer and pins it on click instead of clicking the page', async () => {
|
||||
page();
|
||||
await toggle();
|
||||
await screen.findByText(/Inspecting views/);
|
||||
|
||||
const card = screen.getByRole('button', { name: 'Card Survival' });
|
||||
|
||||
fireEvent.pointerMove(card);
|
||||
expect(await screen.findByText('test.card')).toHaveTextContent('test.card · aurora');
|
||||
|
||||
fireEvent.click(card);
|
||||
|
||||
const panel = await screen.findByRole('complementary', { name: 'View inspector' });
|
||||
|
||||
expect(open).not.toHaveBeenCalled();
|
||||
expect(within(panel).getByRole('heading', { name: 'test.card' })).toBeInTheDocument();
|
||||
expect(within(panel).getByRole('button', { name: 'test.page' })).toBeInTheDocument();
|
||||
expect(within(panel).getByText("'test.card': ({ model, Default }) => <Default />,")).toBeInTheDocument();
|
||||
expect(within(panel).getByText('dashboard.serverRow.name.after')).toBeInTheDocument();
|
||||
expect(within(panel).getByText('"Survival"')).toBeInTheDocument();
|
||||
expect(
|
||||
within(panel)
|
||||
.getAllByRole('listitem')
|
||||
.filter((item) => item.textContent?.includes('renders'))
|
||||
.map((item) => item.textContent)
|
||||
).toEqual(['auroraThemerenders']);
|
||||
|
||||
fireEvent.click(within(panel).getByRole('button', { name: 'Copy override' }));
|
||||
expect(await within(panel).findByText('Copied')).toBeInTheDocument();
|
||||
expect(copy).toHaveBeenCalledWith("'test.card': ({ model, Default }) => <Default />,");
|
||||
|
||||
fireEvent.click(within(panel).getByRole('button', { name: 'test.page' }));
|
||||
expect(within(panel).getByRole('heading', { name: 'test.page' })).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('unpins on Escape, then stops inspecting', async () => {
|
||||
const { container } = page();
|
||||
|
||||
await toggle();
|
||||
await screen.findByText(/Inspecting views/);
|
||||
fireEvent.click(screen.getByRole('button', { name: 'Card Survival' }));
|
||||
await screen.findByRole('complementary', { name: 'View inspector' });
|
||||
|
||||
fireEvent.keyDown(document, { key: 'Escape' });
|
||||
expect(screen.queryByRole('complementary', { name: 'View inspector' })).not.toBeInTheDocument();
|
||||
|
||||
fireEvent.keyDown(document, { key: 'Escape' });
|
||||
expect(screen.queryByText(/Inspecting views/)).not.toBeInTheDocument();
|
||||
expect(container.querySelector('[data-view]')).toBeNull();
|
||||
|
||||
fireEvent.click(screen.getByRole('button', { name: 'Card Survival' }));
|
||||
expect(open).toHaveBeenCalledTimes(1);
|
||||
});
|
||||
});
|
||||
|
||||
describe('inspector helpers', () => {
|
||||
it('builds the override snippet and knows which views classic can eject', () => {
|
||||
expect(overrideSnippet('server.power')).toBe("'server.power': ({ model, Default }) => <Default />,");
|
||||
expect(isEjectable('dashboard.serverCard')).toBe(true);
|
||||
expect(isEjectable('page.server.backups')).toBe(false);
|
||||
});
|
||||
|
||||
it('names the top layer that did not fail as the one that rendered', () => {
|
||||
const layer = (id: string) => ({ id, source: 'theme' as const, component: () => null });
|
||||
|
||||
expect(renderingLayer({ layers: [layer('classic'), layer('aurora')], failed: [] })?.id).toBe('aurora');
|
||||
expect(renderingLayer({ layers: [layer('classic'), layer('aurora')], failed: ['aurora'] })?.id).toBe('classic');
|
||||
});
|
||||
|
||||
it('prints models with functions, elements and cycles', () => {
|
||||
interface Cyclic {
|
||||
save(): void;
|
||||
icon: ReactElement;
|
||||
when: Date;
|
||||
self?: Cyclic;
|
||||
}
|
||||
const model: Cyclic = { save: function save() {}, icon: <svg />, when: new Date(0) };
|
||||
|
||||
model.self = model;
|
||||
|
||||
expect(describeModel(model)).toEqual({
|
||||
kind: 'branch',
|
||||
summary: '{4}',
|
||||
entries: [
|
||||
{ key: 'save', node: { kind: 'value', text: 'ƒ save()', tone: 'function' } },
|
||||
{ key: 'icon', node: { kind: 'value', text: '<svg />', tone: 'other' } },
|
||||
{ key: 'when', node: { kind: 'value', text: '1970-01-01T00:00:00.000Z', tone: 'other' } },
|
||||
{ key: 'self', node: { kind: 'value', text: '[circular]', tone: 'other' } },
|
||||
],
|
||||
});
|
||||
expect(JSON.parse(modelJson({ open: function open() {}, count: 2 }))).toEqual({ open: 'ƒ open()', count: 2 });
|
||||
});
|
||||
|
||||
it('collects the custom properties the rules on a view read, without Tailwind internals', () => {
|
||||
const style = document.head.appendChild(document.createElement('style'));
|
||||
|
||||
style.textContent = [
|
||||
'.tone { color: var(--accent); }',
|
||||
'.row .icon { background: var(--popover); }',
|
||||
'.hover-tint:hover { border-color: var(--border); }',
|
||||
'.ring { --tw-ring: var(--tw-shadow); }',
|
||||
'.unused { color: var(--destructive); }',
|
||||
].join('\n');
|
||||
document.body.innerHTML = "<div class='row tone hover-tint ring'><span class='icon'></span></div>";
|
||||
|
||||
expect(tokensInUse([document.body.firstElementChild!]).map((token) => token.name)).toEqual([
|
||||
'--accent',
|
||||
'--border',
|
||||
'--popover',
|
||||
]);
|
||||
style.remove();
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,92 @@
|
||||
import { isValidElement } from 'react';
|
||||
import { isNumber, isObject, isString } from '@/lib/objects';
|
||||
|
||||
export type ModelTone = 'string' | 'number' | 'boolean' | 'empty' | 'function' | 'other';
|
||||
export type ModelNode =
|
||||
| { readonly kind: 'value'; readonly text: string; readonly tone: ModelTone }
|
||||
| { readonly kind: 'branch'; readonly summary: string; readonly entries: readonly ModelEntry[] };
|
||||
export interface ModelEntry {
|
||||
readonly key: string;
|
||||
readonly node: ModelNode;
|
||||
}
|
||||
|
||||
const MAX_DEPTH = 8;
|
||||
|
||||
function elementName<T>(type: T): string {
|
||||
if (isString(type)) {
|
||||
return type;
|
||||
}
|
||||
|
||||
return type instanceof Function && type.name ? type.name : 'Component';
|
||||
}
|
||||
|
||||
const leaf = (text: string, tone: ModelTone): ModelNode => ({ kind: 'value', text, tone });
|
||||
|
||||
/** A value printed on one line, or null for an object or array to expand. */
|
||||
function describeLeaf<T>(value: T): ModelNode | null {
|
||||
if (value === null || value === undefined) {
|
||||
return leaf(String(value), 'empty');
|
||||
}
|
||||
|
||||
if (isString(value)) {
|
||||
return leaf(JSON.stringify(value), 'string');
|
||||
}
|
||||
|
||||
if (isNumber(value)) {
|
||||
return leaf(String(value), 'number');
|
||||
}
|
||||
|
||||
if (value === true || value === false) {
|
||||
return leaf(String(value), 'boolean');
|
||||
}
|
||||
|
||||
if (value instanceof Function) {
|
||||
return leaf(`ƒ ${value.name || 'anonymous'}()`, 'function');
|
||||
}
|
||||
|
||||
if (value instanceof Date) {
|
||||
return leaf(value.toISOString(), 'other');
|
||||
}
|
||||
|
||||
if (isValidElement(value)) {
|
||||
return leaf(`<${elementName(value.type)} />`, 'other');
|
||||
}
|
||||
|
||||
return Array.isArray(value) || isObject(value) ? null : leaf(String(value), 'other');
|
||||
}
|
||||
|
||||
/** A model as a tree of printable values: functions, elements and cycles become labels. */
|
||||
export function describeModel<T>(value: T, depth = 0, seen: readonly object[] = []): ModelNode {
|
||||
const printed = describeLeaf(value);
|
||||
|
||||
if (printed || (!Array.isArray(value) && !isObject(value))) {
|
||||
return printed ?? leaf(String(value), 'other');
|
||||
}
|
||||
|
||||
if (seen.includes(value)) {
|
||||
return leaf('[circular]', 'other');
|
||||
}
|
||||
|
||||
if (depth >= MAX_DEPTH) {
|
||||
return leaf('…', 'other');
|
||||
}
|
||||
|
||||
const pairs: [string, ModelNode][] = Array.isArray(value)
|
||||
? value.map((item, index) => [String(index), describeModel(item, depth + 1, [...seen, value])])
|
||||
: Object.entries(value).map(([key, item]) => [key, describeModel(item, depth + 1, [...seen, value])]);
|
||||
|
||||
return {
|
||||
kind: 'branch',
|
||||
summary: Array.isArray(value) ? `Array(${pairs.length})` : `{${pairs.length}}`,
|
||||
entries: pairs.map(([key, node]) => ({ key, node })),
|
||||
};
|
||||
}
|
||||
|
||||
/** JSON of a model for the clipboard; functions become their names. */
|
||||
export function modelJson<T>(value: T): string {
|
||||
return JSON.stringify(
|
||||
value,
|
||||
(_key, item) => (item instanceof Function ? `ƒ ${item.name || 'anonymous'}()` : item),
|
||||
2
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,220 @@
|
||||
import { useEffect, useMemo, useState, type ReactNode } from 'react';
|
||||
import { Check, Copy } from 'lucide-react';
|
||||
import copyToClipboard from '@/lib/clipboard';
|
||||
import { cn } from '@/lib/cn';
|
||||
import type { InspectedView } from '@/views/inspect';
|
||||
import { describeModel, type ModelNode, type ModelTone } from './model';
|
||||
import { ejectCommand, isEjectable, overrideSnippet, renderingLayer } from './snippets';
|
||||
import type { CssToken } from './tokens';
|
||||
|
||||
export function Section({
|
||||
title,
|
||||
count,
|
||||
open = true,
|
||||
children,
|
||||
}: {
|
||||
title: string;
|
||||
count?: number;
|
||||
open?: boolean;
|
||||
children?: ReactNode;
|
||||
}) {
|
||||
return (
|
||||
<details open={open} className='group border-b border-border'>
|
||||
<summary className='flex cursor-pointer select-none items-center gap-2 px-4 py-2.5 text-xs font-semibold uppercase tracking-wide text-muted-foreground hover:text-foreground'>
|
||||
<span className='transition-transform group-open:rotate-90'>›</span>
|
||||
{title}
|
||||
{count !== undefined && <span className='font-normal normal-case tracking-normal'>{count}</span>}
|
||||
</summary>
|
||||
<div className='px-4 pb-3'>{children}</div>
|
||||
</details>
|
||||
);
|
||||
}
|
||||
|
||||
export function CopyButton({ text, label, className }: { text: string; label: string; className?: string }) {
|
||||
const [copied, setCopied] = useState(false);
|
||||
|
||||
useEffect(() => {
|
||||
if (!copied) {
|
||||
return;
|
||||
}
|
||||
|
||||
const timer = setTimeout(() => setCopied(false), 1500);
|
||||
|
||||
return () => clearTimeout(timer);
|
||||
}, [copied]);
|
||||
|
||||
return (
|
||||
<button
|
||||
type='button'
|
||||
className={cn(
|
||||
'inline-flex shrink-0 items-center gap-1.5 rounded-sm border border-border bg-popover px-2 py-1 text-xs text-foreground transition-colors hover:bg-secondary',
|
||||
className
|
||||
)}
|
||||
onClick={() => void copyToClipboard(text).then(setCopied)}
|
||||
>
|
||||
{copied ? (
|
||||
<Check className='h-3.5 w-3.5 text-success' aria-hidden />
|
||||
) : (
|
||||
<Copy className='h-3.5 w-3.5' aria-hidden />
|
||||
)}
|
||||
{copied ? 'Copied' : label}
|
||||
</button>
|
||||
);
|
||||
}
|
||||
|
||||
const tones = {
|
||||
string: 'text-success',
|
||||
number: 'text-accent',
|
||||
boolean: 'text-warning',
|
||||
empty: 'text-muted-foreground',
|
||||
function: 'text-muted-foreground italic',
|
||||
other: 'text-foreground',
|
||||
} satisfies Record<ModelTone, string>;
|
||||
|
||||
function ModelBranch({ label, node, depth }: { label: string | null; node: ModelNode; depth: number }) {
|
||||
const key = label !== null && <span className='text-foreground/80'>{label}: </span>;
|
||||
|
||||
if (node.kind === 'value') {
|
||||
return (
|
||||
<div className='truncate py-px' title={node.text}>
|
||||
{key}
|
||||
<span className={tones[node.tone]}>{node.text}</span>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
return (
|
||||
<details open={depth < 2} className='group/branch'>
|
||||
<summary className='cursor-pointer select-none py-px marker:text-muted-foreground'>
|
||||
{key}
|
||||
<span className='text-muted-foreground'>{node.summary}</span>
|
||||
</summary>
|
||||
<div className='ml-2 border-l border-border pl-3'>
|
||||
{node.entries.map((entry) => (
|
||||
<ModelBranch key={entry.key} label={entry.key} node={entry.node} depth={depth + 1} />
|
||||
))}
|
||||
</div>
|
||||
</details>
|
||||
);
|
||||
}
|
||||
|
||||
/** A model or inputs as a collapsible tree. */
|
||||
export function ModelTree({ value }: { value: unknown }) {
|
||||
const node = useMemo(() => describeModel(value), [value]);
|
||||
|
||||
return (
|
||||
<div className='font-mono text-xs leading-5'>
|
||||
<ModelBranch label={null} node={node} depth={0} />
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
const sources = { classic: 'Classic', theme: 'Theme', extension: 'Extension' };
|
||||
|
||||
/** The layer chain top first, marking the layer that rendered and any that failed. */
|
||||
export function LayerStack({ view }: { view: Pick<InspectedView, 'layers' | 'failed'> }) {
|
||||
const rendered = renderingLayer(view);
|
||||
|
||||
if (!view.layers.length) {
|
||||
return <p className='text-sm text-muted-foreground'>No layer implements this view.</p>;
|
||||
}
|
||||
|
||||
return (
|
||||
<ol className='space-y-1.5'>
|
||||
{[...view.layers].reverse().map((layer) => {
|
||||
const failed = view.failed.includes(layer.id);
|
||||
|
||||
return (
|
||||
<li
|
||||
key={`${layer.source}:${layer.id}`}
|
||||
className={cn(
|
||||
'flex items-center gap-2 rounded-sm border px-2.5 py-1.5 text-sm',
|
||||
layer === rendered ? 'border-primary bg-primary/10' : 'border-border',
|
||||
failed && 'border-destructive/50 bg-destructive/10'
|
||||
)}
|
||||
>
|
||||
<span className='font-mono'>{layer.id}</span>
|
||||
<span className='text-xs text-muted-foreground'>{sources[layer.source]}</span>
|
||||
<span className='ml-auto text-xs'>
|
||||
{layer === rendered && <span className='text-primary'>renders</span>}
|
||||
{failed && <span className='text-destructive'>failed, fell back</span>}
|
||||
</span>
|
||||
</li>
|
||||
);
|
||||
})}
|
||||
</ol>
|
||||
);
|
||||
}
|
||||
|
||||
export function SlotList({ slots }: { slots: readonly string[] }) {
|
||||
if (!slots.length) {
|
||||
return <p className='text-sm text-muted-foreground'>This view renders no slots.</p>;
|
||||
}
|
||||
|
||||
return (
|
||||
<ul className='space-y-1 font-mono text-xs'>
|
||||
{slots.map((slot) => (
|
||||
<li key={slot}>{slot}</li>
|
||||
))}
|
||||
</ul>
|
||||
);
|
||||
}
|
||||
|
||||
export function TokenList({ tokens, empty }: { tokens: readonly CssToken[]; empty: string }) {
|
||||
if (!tokens.length) {
|
||||
return <p className='text-sm text-muted-foreground'>{empty}</p>;
|
||||
}
|
||||
|
||||
return (
|
||||
<dl className='grid grid-cols-[minmax(0,1fr)_minmax(0,1fr)] gap-x-3 gap-y-1 font-mono text-xs'>
|
||||
{tokens.map((token) => (
|
||||
<div key={token.name} className='contents'>
|
||||
<dt className='truncate text-foreground/80' title={token.name}>
|
||||
{token.name}
|
||||
</dt>
|
||||
<dd className='flex min-w-0 items-center gap-1.5'>
|
||||
{token.value && CSS.supports('color', token.value) && (
|
||||
<span
|
||||
aria-hidden
|
||||
className='h-3 w-3 shrink-0 rounded-xs border border-border'
|
||||
style={{ background: token.value }}
|
||||
/>
|
||||
)}
|
||||
<span className='truncate' title={token.value}>
|
||||
{token.value || '(unset)'}
|
||||
</span>
|
||||
</dd>
|
||||
</div>
|
||||
))}
|
||||
</dl>
|
||||
);
|
||||
}
|
||||
|
||||
/** A line of code to paste somewhere, with its copy button. */
|
||||
export function CodeLine({ code, label = 'Copy' }: { code: string; label?: string }) {
|
||||
return (
|
||||
<div className='flex items-start gap-2'>
|
||||
<code className='min-w-0 flex-1 rounded-sm bg-sunken px-2 py-1.5 font-mono text-xs break-words whitespace-pre-wrap'>
|
||||
{code}
|
||||
</code>
|
||||
<CopyButton text={code} label={label} />
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
/** The snippet to start overriding a view, and the command that ejects classic's source for it. */
|
||||
export function OverrideHelp({ name }: { name: string }) {
|
||||
return (
|
||||
<div className='space-y-2'>
|
||||
<CodeLine code={overrideSnippet(name)} label='Copy override' />
|
||||
{isEjectable(name) ? (
|
||||
<CodeLine code={ejectCommand(name)} />
|
||||
) : (
|
||||
<p className='text-xs text-muted-foreground'>
|
||||
Classic has no source of its own to eject here yet; wrap <code className='font-mono'>Default</code>{' '}
|
||||
instead.
|
||||
</p>
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,16 @@
|
||||
import classic from '@/themes/classic';
|
||||
import type { InspectedView } from '@/views/inspect';
|
||||
import type { ViewLayer } from '@/views/registry';
|
||||
|
||||
/** The entry to add to a theme's `views` to start overriding a view. */
|
||||
export const overrideSnippet = (name: string): string => `'${name}': ({ model, Default }) => <Default />,`;
|
||||
|
||||
/** Classic's own views have source to eject; the rest render the panel's own components. */
|
||||
export const isEjectable = (name: string): boolean => Object.hasOwn(classic.views ?? {}, name);
|
||||
|
||||
export const ejectCommand = (name: string): string => `npx pterodactyl-theme eject ${name}`;
|
||||
|
||||
/** The layer that rendered: the top one that did not fail. */
|
||||
export function renderingLayer(view: Pick<InspectedView, 'layers' | 'failed'>): ViewLayer | undefined {
|
||||
return [...view.layers].reverse().find((layer) => !view.failed.includes(layer.id));
|
||||
}
|
||||
@@ -0,0 +1,169 @@
|
||||
export interface CssToken {
|
||||
readonly name: string;
|
||||
readonly value: string;
|
||||
}
|
||||
|
||||
interface TokenRule {
|
||||
readonly selector: string;
|
||||
/** The class an element needs for the selector to match, when it starts with one. */
|
||||
readonly className: string | null;
|
||||
readonly tokens: readonly string[];
|
||||
}
|
||||
|
||||
const TOKEN_REFERENCE = /var\(\s*(--[\w-]+)/g;
|
||||
const LEADING_CLASS = /^\.((?:\\.|[\w-])+)/;
|
||||
const STATES = /:(?:hover|focus-visible|focus-within|focus|active)\b/g;
|
||||
const ELEMENT_LIMIT = 150;
|
||||
|
||||
const isStyleRule = (rule: CSSRule): rule is CSSStyleRule => 'selectorText' in rule;
|
||||
const isGroupingRule = (rule: CSSRule): rule is CSSGroupingRule => 'cssRules' in rule;
|
||||
/** Declarations nested in an at-rule inside a style rule, such as `&:hover { @media (hover: hover) { … } }`. */
|
||||
const hasDeclarations = (rule: CSSRule): rule is CSSRule & Pick<CSSStyleRule, 'style'> => 'style' in rule;
|
||||
const withoutArguments = (selector: string) => selector.replaceAll(/\([^)]*\)/g, '');
|
||||
|
||||
// Tailwind's own `--tw-*` plumbing is not something a theme sets.
|
||||
const references = (cssText: string): string[] =>
|
||||
[...cssText.matchAll(TOKEN_REFERENCE)].map((match) => match[1]).filter((name) => !name.startsWith('--tw-'));
|
||||
|
||||
/** A selector that matches the element itself, not one of its descendants: `.a:hover`, not `.a .b`. */
|
||||
const isCompound = (selector: string) => !/[\s>+~,]/.test(withoutArguments(selector));
|
||||
|
||||
/** The class a compound selector requires, to skip `matches()` on elements that lack it. */
|
||||
const leadingClass = (selector: string) =>
|
||||
isCompound(selector) ? (LEADING_CLASS.exec(selector)?.[1]?.replaceAll(/\\(.)/g, '$1') ?? null) : null;
|
||||
|
||||
/** A nested rule's selector is relative to its parent's, as Tailwind emits variants: `.x { &:hover { … } }`. */
|
||||
function nestedSelector(selector: string, parent: TokenRule | null): string {
|
||||
if (!parent) {
|
||||
return selector;
|
||||
}
|
||||
|
||||
return selector.includes('&')
|
||||
? selector.replaceAll('&', `:is(${parent.selector})`)
|
||||
: `:is(${parent.selector}) ${selector}`;
|
||||
}
|
||||
|
||||
function requiredClass(rule: CSSStyleRule, selector: string, parent: TokenRule | null): string | null {
|
||||
if (!parent) {
|
||||
return leadingClass(selector);
|
||||
}
|
||||
|
||||
// `&:hover` still needs the parent's class on the element itself; `& .icon` does not.
|
||||
return rule.selectorText.startsWith('&') && isCompound(rule.selectorText) ? parent.className : null;
|
||||
}
|
||||
|
||||
function collectRules(rules: CSSRuleList, into: TokenRule[], parent: TokenRule | null = null): void {
|
||||
for (const rule of rules) {
|
||||
let scope = parent;
|
||||
|
||||
if (isStyleRule(rule)) {
|
||||
const selector = nestedSelector(rule.selectorText, parent);
|
||||
|
||||
scope = {
|
||||
selector,
|
||||
className: requiredClass(rule, selector, parent),
|
||||
tokens: references(rule.style.cssText),
|
||||
};
|
||||
|
||||
if (scope.tokens.length) {
|
||||
into.push(scope);
|
||||
}
|
||||
} else if (parent && hasDeclarations(rule)) {
|
||||
const tokens = references(rule.style.cssText);
|
||||
|
||||
if (tokens.length) {
|
||||
into.push({ ...parent, tokens });
|
||||
}
|
||||
}
|
||||
|
||||
if (isGroupingRule(rule)) {
|
||||
collectRules(rule.cssRules, into, scope);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
function tokenRules(document: Document): TokenRule[] {
|
||||
const rules: TokenRule[] = [];
|
||||
|
||||
for (const sheet of document.styleSheets) {
|
||||
try {
|
||||
collectRules(sheet.cssRules, rules);
|
||||
} catch {
|
||||
// A cross-origin stylesheet cannot be read.
|
||||
}
|
||||
}
|
||||
|
||||
return rules;
|
||||
}
|
||||
|
||||
function matches(element: Element, selector: string): boolean {
|
||||
try {
|
||||
return element.matches(selector) || element.matches(selector.replaceAll(STATES, ''));
|
||||
} catch {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
function subtree(roots: readonly Element[]): Element[] {
|
||||
const elements: Element[] = [];
|
||||
const queue = [...roots];
|
||||
|
||||
while (queue.length && elements.length < ELEMENT_LIMIT) {
|
||||
const element = queue.shift()!;
|
||||
|
||||
elements.push(element);
|
||||
queue.push(...element.children);
|
||||
}
|
||||
|
||||
return elements;
|
||||
}
|
||||
|
||||
/**
|
||||
* The custom properties the rules matching these elements read, including their hover and focus
|
||||
* states, with their values resolved on the first element.
|
||||
*/
|
||||
export function tokensInUse(roots: readonly Element[]): CssToken[] {
|
||||
const [first] = roots;
|
||||
|
||||
if (!first) {
|
||||
return [];
|
||||
}
|
||||
|
||||
const rules = tokenRules(first.ownerDocument);
|
||||
const elements = subtree(roots);
|
||||
const applies = (rule: TokenRule, element: Element) =>
|
||||
(!rule.className || element.classList.contains(rule.className)) && matches(element, rule.selector);
|
||||
const names = new Set([
|
||||
...elements.flatMap((element) => rules.filter((rule) => applies(rule, element)).flatMap((rule) => rule.tokens)),
|
||||
...elements.flatMap((element) => references(element.getAttribute('style') ?? '')),
|
||||
]);
|
||||
const style = first.ownerDocument.defaultView?.getComputedStyle(first);
|
||||
|
||||
return [...names]
|
||||
.sort((a, b) => a.localeCompare(b))
|
||||
.map((name) => ({ name, value: style?.getPropertyValue(name).trim() ?? '' }));
|
||||
}
|
||||
|
||||
const DECLARATION = /(--[\w-]+)\s*:\s*([^;}]+)/g;
|
||||
|
||||
export interface ThemeSettingTokens {
|
||||
/** Set by the settings style and any live preview of unsaved settings. */
|
||||
readonly tokens: readonly CssToken[];
|
||||
readonly attributes: readonly CssToken[];
|
||||
}
|
||||
|
||||
/** What the active theme's settings put on `<html>`: tokens in the settings style, and attributes. */
|
||||
export function themeSettingTokens(document: Document): ThemeSettingTokens {
|
||||
const declared = document.getElementById('theme-settings')?.textContent ?? '';
|
||||
const inline = document.documentElement.getAttribute('style') ?? '';
|
||||
|
||||
return {
|
||||
tokens: [...`${declared};${inline}`.matchAll(DECLARATION)].map(([, name, value]) => ({
|
||||
name,
|
||||
value: value.trim(),
|
||||
})),
|
||||
attributes: [...document.documentElement.attributes]
|
||||
.filter((attribute) => attribute.name.startsWith('data-') || attribute.name === 'class')
|
||||
.map((attribute) => ({ name: attribute.name, value: attribute.value })),
|
||||
};
|
||||
}
|
||||
@@ -81,5 +81,6 @@ export const opaqueViews = {
|
||||
'page.admin.tags': page(() => import('@/components/admin/tags/TagsContainer')),
|
||||
'page.admin.extensions': page(() => import('@/components/admin/extensions/ExtensionsContainer')),
|
||||
'page.admin.themes': page(() => import('@/components/admin/themes/ThemesContainer')),
|
||||
'page.admin.themeWorkbench': page(() => import('@/components/admin/themes/workbench/ThemeWorkbench')),
|
||||
'page.admin.apiKeys': page(() => import('@/components/admin/api/ApiKeysContainer')),
|
||||
} satisfies ThemeViews & Record<OpaquePageName, JSXElementConstructor<never>>;
|
||||
|
||||
@@ -172,6 +172,7 @@ export const OPAQUE_PAGES = {
|
||||
'page.admin.tags': { context: 'admin', slots: ['panel.tags.before', 'panel.tags.after'] },
|
||||
'page.admin.extensions': { context: 'admin', slots: ['panel.extensions.before', 'panel.extensions.after'] },
|
||||
'page.admin.themes': { context: 'admin', slots: ['panel.themes.before', 'panel.themes.after'] },
|
||||
'page.admin.themeWorkbench': { context: 'admin' },
|
||||
'page.admin.apiKeys': { context: 'admin', slots: ['panel.apiKeys.before', 'panel.apiKeys.after'] },
|
||||
} as const satisfies Record<`page.${string}`, PageSpec>;
|
||||
|
||||
|
||||
@@ -50,12 +50,18 @@ export type ViewProps<N> = {
|
||||
/** A layer of a view; `parts` declares the parts it renders for the layers above it. */
|
||||
export type ViewComponent<N> = ComponentType<ViewProps<N>> & { readonly parts?: ViewParts<N> };
|
||||
|
||||
/** Wraps a view rendered from a fixture, for views whose parts read an engine session. */
|
||||
export type ViewFixtureScope<N> = ComponentType<{ readonly model: ViewModel<N>; readonly children?: ReactNode }>;
|
||||
|
||||
export interface ViewOptions<N extends ViewName> {
|
||||
readonly context: ViewContext;
|
||||
/** The engine hook producing the model; the only data source of the view. */
|
||||
use(input: ViewInput<N>): ViewModel<N>;
|
||||
/** Models for the workbench and tests; the first is the default. */
|
||||
readonly fixtures?: Readonly<Record<string, () => ViewModel<N>>>;
|
||||
/** The inputs a fixture renders with, for views that take inputs. */
|
||||
fixtureInput?(model: ViewModel<N>): ViewInput<N>;
|
||||
readonly fixtureScope?: ViewFixtureScope<N>;
|
||||
readonly slots?: readonly SlotName[];
|
||||
/** Shown while extension layers of this view load. */
|
||||
readonly placeholder?: ReactNode;
|
||||
@@ -67,6 +73,8 @@ export interface ViewDefinition<N extends string = string> {
|
||||
readonly context: ViewContext;
|
||||
use(input: ViewInput<N>): ViewModel<N>;
|
||||
readonly fixtures?: Readonly<Record<string, () => ViewModel<N>>>;
|
||||
fixtureInput?(model: ViewModel<N>): ViewInput<N>;
|
||||
readonly fixtureScope?: ViewFixtureScope<N>;
|
||||
readonly slots?: readonly SlotName[];
|
||||
readonly placeholder?: ReactNode;
|
||||
/** The extension that defined the view; core views have none. */
|
||||
@@ -127,9 +135,11 @@ const layers = new Map<string, LayerSet>();
|
||||
const chains = new Map<string, readonly ViewLayer[]>();
|
||||
const listeners = new Set<() => void>();
|
||||
const emptyChain: readonly ViewLayer[] = Object.freeze([]);
|
||||
let sortedDefinitions: readonly ViewDefinition[] | undefined;
|
||||
|
||||
function publish(): void {
|
||||
chains.clear();
|
||||
sortedDefinitions = undefined;
|
||||
for (const listener of listeners) {
|
||||
listener();
|
||||
}
|
||||
@@ -180,7 +190,14 @@ export function getViewDefinition(name: string): ViewDefinition | undefined {
|
||||
}
|
||||
|
||||
export function getViewDefinitions(): readonly ViewDefinition[] {
|
||||
return [...definitions.values()].sort((a, b) => a.name.localeCompare(b.name));
|
||||
return (sortedDefinitions ??= Object.freeze(
|
||||
[...definitions.values()].sort((a, b) => a.name.localeCompare(b.name))
|
||||
));
|
||||
}
|
||||
|
||||
/** Every defined view by name, including those extensions define as they load. */
|
||||
export function useViewDefinitions(): readonly ViewDefinition[] {
|
||||
return useSyncExternalStore(subscribeViews, getViewDefinitions);
|
||||
}
|
||||
|
||||
export function useViewDefinition(name: string): ViewDefinition | undefined {
|
||||
|
||||
Reference in New Issue
Block a user