mirror of
https://github.com/pterodactyl/panel.git
synced 2026-12-02 20:35:50 -05:00
theme tooling
This commit is contained in:
@@ -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');
|
||||
});
|
||||
});
|
||||
Reference in New Issue
Block a user