From ea66bddf0afd555455d32ff26822a1b6c015bbd1 Mon Sep 17 00:00:00 2001 From: robert dennis <31261583+robertdrakedennis@users.noreply.github.com> Date: Mon, 12 Oct 2026 15:47:23 -0400 Subject: [PATCH] workbench polish --- config/extensions.php | 2 +- packages/hello-world/extension.json | 2 +- packages/sdk/bin/pterodactyl-theme.mjs | 96 ++++++- packages/sdk/package.json | 2 +- packages/sdk/theme-cli.spec.ts | 72 ++++- .../admin/themes/workbench/PreviewFrame.tsx | 27 +- .../admin/themes/workbench/workbench.spec.tsx | 27 ++ .../components/elements/PageContentBlock.tsx | 8 +- .../scripts/components/elements/Portal.tsx | 21 +- .../components/elements/dialog/Dialog.tsx | 4 +- .../elements/dropdown/DropdownMenu.tsx | 7 +- .../components/elements/tooltip/Tooltip.tsx | 4 +- resources/scripts/components/ui/Select.tsx | 25 +- resources/scripts/themes/gallery.tsx | 266 +++++++++++++++++- .../scripts/views/inspector/ViewInspector.tsx | 27 +- .../views/inspector/inspector.spec.tsx | 19 ++ tests/Integration/Http/ThemeDocumentTest.php | 4 +- .../Services/Themes/ThemeLifecycleTest.php | 4 +- 18 files changed, 553 insertions(+), 64 deletions(-) diff --git a/config/extensions.php b/config/extensions.php index eb7dc27e6..ffec04bf3 100644 --- a/config/extensions.php +++ b/config/extensions.php @@ -18,7 +18,7 @@ return [ 'enabled' => (bool) env('PTERODACTYL_EXTENSIONS_ENABLED', true), 'panel_version' => config('app.version') === 'canary' ? '2.0.0-dev' : config('app.version'), - 'sdk_version' => '2.0.0-beta.4', + 'sdk_version' => '2.0.0-beta.5', 'progress_retention_seconds' => 3600, // How long the result of a head tag callback (registerHeadTags) is cached; 0 disables it. diff --git a/packages/hello-world/extension.json b/packages/hello-world/extension.json index d1dfcfab0..60bfd830d 100644 --- a/packages/hello-world/extension.json +++ b/packages/hello-world/extension.json @@ -21,6 +21,6 @@ "views": ["dashboard.serverCard", "server.files.details", "server.files.editor"] }, "requires": { - "sdk": ">=2.0.0-beta.4 <3.0" + "sdk": ">=2.0.0-beta.5 <3.0" } } diff --git a/packages/sdk/bin/pterodactyl-theme.mjs b/packages/sdk/bin/pterodactyl-theme.mjs index 022957b36..e6327e2bf 100755 --- a/packages/sdk/bin/pterodactyl-theme.mjs +++ b/packages/sdk/bin/pterodactyl-theme.mjs @@ -1,6 +1,6 @@ #!/usr/bin/env node // Theme author tooling: list the panel's views, eject classic's source for one, print a classic skin. -import { existsSync, mkdirSync, readdirSync, readFileSync, realpathSync, statSync, writeFileSync } from 'node:fs'; +import { existsSync, mkdirSync, readFileSync, realpathSync, statSync, writeFileSync } from 'node:fs'; import { basename, dirname, extname, relative, resolve, sep } from 'node:path'; import { fileURLToPath } from 'node:url'; @@ -199,15 +199,97 @@ function eject(positional, flags, out) { out(`\nAdd it to your theme entry:\n\n ${importLine}\n\n ${viewsLine}`); } -/** Classic's skins, one file per primitive under `skins/`, by primitive name. */ +/** The top-level statements of a module: split on `;` outside brackets, strings and comments. */ +function statements(source) { + const found = []; + let depth = 0; + let start = 0; + + for (let index = 0; index < source.length; index++) { + const char = source[index]; + + if (char === '/' && source[index + 1] === '/') { + index = source.indexOf('\n', index); + if (index === -1) break; + } else if (char === '/' && source[index + 1] === '*') { + index = source.indexOf('*/', index + 2) + 1; + if (index === 0) break; + } else if (char === "'" || char === '"' || char === '`') { + for (index++; index < source.length && source[index] !== char; index++) { + if (source[index] === '\\') index++; + } + } else if ('([{'.includes(char)) depth++; + else if (')]}'.includes(char)) depth--; + else if (char === ';' && depth === 0) { + found.push(source.slice(start, index + 1).trim()); + start = index + 1; + } + } + + return found; +} + +/** The constant a statement declares, past any comments before it. */ +const declared = (statement) => + /^(?:export\s+)?const\s+(\w+)\s*=/.exec(statement.replace(/^(?:\/\/[^\n]*\n\s*|\/\*[\s\S]*?\*\/\s*)*/, ''))?.[1]; + +/** A skin's declaration in a classic skins file, after the constants of that file it reads. */ +function skinSource(file, exportName, primitive) { + const all = statements(readFileSync(file, 'utf8')); + const byName = new Map(all.flatMap((statement) => (declared(statement) ? [[declared(statement), statement]] : []))); + const needed = new Set([exportName]); + const queue = [exportName]; + + while (queue.length) { + const statement = byName.get(queue.shift()) ?? ''; + + for (const name of byName.keys()) { + if (!needed.has(name) && new RegExp(`\\b${name}\\b`).test(statement.slice(statement.indexOf('=')))) { + needed.add(name); + queue.push(name); + } + } + } + + if (!byName.has(exportName)) { + throw new CliError(`Classic's skins/${basename(file)} does not declare ${exportName}.`); + } + + return [ + `// Classic's ${primitive} skin (skins/${basename(file)}) from @pterodactyl/sdk ${version}.`, + `// Add it to defineTheme({ ui: { ${primitive}: ${exportName} } }) and edit it. Typed as Skin<'${primitive}'>`, + "// instead of CompleteSkin, it may leave parts out; those keep classic's recipe.", + "import type { CompleteSkin } from '@pterodactyl/sdk/theme';", + '', + ...all.filter((statement) => needed.has(declared(statement))).map((statement) => `${statement}\n`), + ].join('\n'); +} + +/** Classic's skin of each primitive, by primitive name, as `skins/index.ts` maps them. */ export function classicSkins(root = classicRoot) { - const directory = resolve(root, 'skins'); - const files = existsSync(directory) - ? readdirSync(directory).filter((file) => /\.tsx?$/.test(file) && !/^index\.|\.spec\./.test(file)) - : []; + const index = resolve(root, 'skins/index.ts'); + + if (!existsSync(index)) return new Map(); + + const source = readFileSync(index, 'utf8'); + const imports = new Map(); + + for (const [, names, specifier] of source.matchAll(/import\s*\{([^}]*)\}\s*from\s*'(\.{1,2}\/[^']+)'/g)) { + for (const binding of names.split(',').map((name) => name.trim()).filter(Boolean)) { + const [imported, local = imported] = binding.split(/\s+as\s+/); + + imports.set(local, { file: resolveModule(index, specifier), exportName: imported }); + } + } return new Map( - files.sort().map((file) => [basename(file, extname(file)), () => readFileSync(resolve(directory, file), 'utf8')]) + [...source.matchAll(/^\s*([A-Z]\w*):\s*(\w+),?\s*$/gm)] + .filter(([, , local]) => imports.has(local)) + .map(([, primitive, local]) => { + const { file, exportName } = imports.get(local); + + return [primitive, () => skinSource(file, exportName, primitive)]; + }) ); } diff --git a/packages/sdk/package.json b/packages/sdk/package.json index d6dd62947..a1e935106 100644 --- a/packages/sdk/package.json +++ b/packages/sdk/package.json @@ -1,6 +1,6 @@ { "name": "@pterodactyl/sdk", - "version": "2.0.0-beta.4", + "version": "2.0.0-beta.5", "description": "SDK for building Pterodactyl panel extensions: types for the runtime API and the Vite build preset.", "license": "MIT", "type": "module", diff --git a/packages/sdk/theme-cli.spec.ts b/packages/sdk/theme-cli.spec.ts index d7c9faa1e..2320c7b04 100644 --- a/packages/sdk/theme-cli.spec.ts +++ b/packages/sdk/theme-cli.spec.ts @@ -5,7 +5,7 @@ import { tmpdir } from 'node:os'; import { dirname, resolve } from 'node:path'; import { afterEach, beforeEach, describe, expect, it } from 'vitest'; // @ts-expect-error The bin is plain JavaScript without declarations. -import { classicSkins, ejectView, rewriteImports, run } from './bin/pterodactyl-theme.mjs'; +import { classicSkins, ejectView, run } from './bin/pterodactyl-theme.mjs'; const root = resolve(__dirname, '../..'); const bin = resolve(__dirname, 'bin/pterodactyl-theme.mjs'); @@ -163,22 +163,72 @@ export default defineTheme({ }); describe('skins', () => { - it('lists classic skins and prints one with SDK imports', () => { - write('classic/skins/Button.ts', "import { skin } from '@/sdk/theme';\nexport default skin('Button', {});\n"); - write('classic/skins/index.ts', 'export {};\n'); + it('lists the primitives classic skins and prints one with the constants it reads', () => { + write( + 'classic/skins/forms.ts', + [ + "import type { CompleteSkin } from '@/sdk/theme';", + '', + "// Shared by the inputs; a ; in a comment does not end it.", + "const control = { base: 'p-3 border', variants: { error: { true: 'border-destructive' } } };", + "const unused = 'x';", + "export const input = { root: control } satisfies CompleteSkin<'Input'>;", + "export const label = { root: 'block; text-sm' } satisfies CompleteSkin<'Label'>;", + '', + ].join('\n') + ); + write( + 'classic/skins/index.ts', + "import type { CompleteSkins } from '@/sdk/theme';\nimport { input, label as fieldLabel } from './forms';\n\nexport const classicSkins = {\n Input: input,\n Label: fieldLabel,\n} satisfies CompleteSkins;\n" + ); const skins: Map string> = classicSkins(resolve(directory, 'classic')); + const input = skins.get('Input')!(); - expect([...skins.keys()]).toEqual(['Button']); - expect(rewriteImports(skins.get('Button')!())).toContain("from '@pterodactyl/sdk/theme'"); + expect([...skins.keys()]).toEqual(['Input', 'Label']); + expect(input).toContain("import type { CompleteSkin } from '@pterodactyl/sdk/theme';"); + expect(input).toContain("// Shared by the inputs; a ; in a comment does not end it.\nconst control = {"); + expect(input).toContain("export const input = { root: control } satisfies CompleteSkin<'Input'>;"); + expect(input).not.toContain('unused'); + expect(input).not.toContain('export const label'); + expect(skins.get('Label')!()).toContain("export const label = { root: 'block; text-sm' }"); }); - it('explains when classic skins nothing yet', () => { - const result = cli('skins'); + it('prints classic skin of every primitive as code that typechecks against the SDK types', () => { + const listed = cli('skins'); + const primitives = listed.stdout.trim().split('\n'); - expect(result.status).toBe(0); - expect(result.stdout.trim()).toMatch(/^(Classic defines no skins yet\.|\w+(\n\w+)*)$/); - }); + expect(listed.status).toBe(0); + expect(primitives).toEqual(expect.arrayContaining(['Button', 'Card', 'Dialog', 'Select'])); + for (const primitive of primitives) { + write(`skins/${primitive}.ts`, cli('skins', primitive.toLowerCase()).stdout); + } + + expect(cli('skins', 'Buton').stderr).toContain('Classic has no skin for "Buton". It skins Alert, Avatar'); + + const program = ts.createProgram( + primitives.map((primitive) => resolve(directory, `skins/${primitive}.ts`)), + { + strict: true, + noEmit: true, + skipLibCheck: true, + target: ts.ScriptTarget.ES2022, + module: ts.ModuleKind.ESNext, + moduleResolution: ts.ModuleResolutionKind.Bundler, + types: [], + typeRoots: [resolve(root, 'node_modules/@types')], + paths: { '@pterodactyl/sdk/theme': [resolve(__dirname, 'types/theme.d.ts')] }, + } + ); + + expect( + ts.formatDiagnostics(ts.getPreEmitDiagnostics(program), { + getCanonicalFileName: (file) => file, + getCurrentDirectory: () => directory, + getNewLine: () => '\n', + }) + ).toBe(''); + }, 60_000); }); it('ships the bin and classic sources in the package', () => { diff --git a/resources/scripts/components/admin/themes/workbench/PreviewFrame.tsx b/resources/scripts/components/admin/themes/workbench/PreviewFrame.tsx index 7917efed7..5e171d3d5 100644 --- a/resources/scripts/components/admin/themes/workbench/PreviewFrame.tsx +++ b/resources/scripts/components/admin/themes/workbench/PreviewFrame.tsx @@ -1,13 +1,16 @@ import { useEffect, useRef, useState, type ReactNode } from 'react'; import { createPortal } from 'react-dom'; +import { PortalContainerContext } from '@/components/elements/Portal'; 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 = - '
'; + '
'; const MAX_HEIGHT = 4000; +/** The least height of a frame while a dialog is open in it, so the dialog is not cut off. */ +const DIALOG_HEIGHT = 640; const isStylesheet = (node: Element): node is HTMLLinkElement | HTMLStyleElement => node instanceof HTMLStyleElement || (node instanceof HTMLLinkElement && node.relList.contains('stylesheet')); @@ -75,11 +78,13 @@ export interface PreviewFrameProps { /** * 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. + * scheme applies to the preview alone. The children stay in this React tree and keep its context, and + * their dialogs, menus and tooltips portal into the frame too. */ export default function PreviewFrame({ label, width, scale, scheme, children }: PreviewFrameProps) { const [frame, setFrame] = useState(null); const [root, setRoot] = useState(null); + const [overlays, setOverlays] = useState(null); const [height, setHeight] = useState(0); const schemeRef = useRef(scheme); @@ -93,8 +98,9 @@ export default function PreviewFrame({ label, width, scale, scheme, children }: const ready = () => { const target = frame.contentDocument; const mount = target?.getElementById('root'); + const layer = target?.getElementById('overlays'); - if (!target || !mount) { + if (!target || !mount || !layer) { return; } @@ -102,7 +108,12 @@ export default function PreviewFrame({ label, width, scale, scheme, children }: const clones = new Map(); const sync = () => mirrorDocument(target, schemeRef.current, clones); - const measure = () => setHeight(Math.min(Math.ceil(mount.getBoundingClientRect().height), MAX_HEIGHT)); + const measure = () => { + const content = Math.ceil(mount.getBoundingClientRect().height); + const dialog = layer.querySelector('[role="dialog"], [role="alertdialog"]') !== null; + + setHeight(Math.min(dialog ? Math.max(content, DIALOG_HEIGHT) : content, 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); @@ -110,6 +121,7 @@ export default function PreviewFrame({ label, width, scale, scheme, children }: sync(); observer.observe(mount); mutations.observe(mount, { childList: true, subtree: true, attributes: true, characterData: true }); + mutations.observe(layer, { childList: true, subtree: true }); target.addEventListener('click', holdNavigation, true); target.addEventListener('submit', holdNavigation, true); @@ -126,6 +138,7 @@ export default function PreviewFrame({ label, width, scale, scheme, children }: }; setRoot(mount); + setOverlays(layer); }; frame.addEventListener('load', ready); @@ -161,7 +174,11 @@ export default function PreviewFrame({ label, width, scale, scheme, children }: transformOrigin: '0 0', }} /> - {root && createPortal(children, root)} + {root && + createPortal( + {children}, + root + )} ); } diff --git a/resources/scripts/components/admin/themes/workbench/workbench.spec.tsx b/resources/scripts/components/admin/themes/workbench/workbench.spec.tsx index fc71653de..1b709f91d 100644 --- a/resources/scripts/components/admin/themes/workbench/workbench.spec.tsx +++ b/resources/scripts/components/admin/themes/workbench/workbench.spec.tsx @@ -2,6 +2,9 @@ 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 PageContentBlock from '@/components/elements/PageContentBlock'; +import { PortalContainerContext } from '@/components/elements/Portal'; +import { Dialog } from '@/components/elements/dialog'; import { parseWorkbenchSearch } from '@/router/search'; import { createExtensionTestHost, type ExtensionTestHost } from '@/sdk/testing'; import '@/views/catalog'; @@ -176,6 +179,30 @@ describe('preview frames', () => { expect(target.documentElement.className).toBe('dark'); settings.remove(); }); + + it('portal dialogs into the frame and title the frame instead of the workbench', async () => { + const frame = document.implementation.createHTMLDocument('frame'); + const overlays = frame.body.appendChild(frame.createElement('div')); + + document.title = 'Admin · Theme workbench'; + await act(async () => { + render( + + + {}} title='Rename server'> + Choose a name. + + + + ); + }); + + // A document without a window, which the DOM matchers cannot read. + expect(overlays.querySelector('[role="dialog"]')?.textContent).toContain('Choose a name.'); + expect(screen.queryByRole('dialog')).toBeNull(); + expect(frame.title).toBe('Servers'); + expect(document.title).toBe('Admin · Theme workbench'); + }); }); describe('view preview', () => { diff --git a/resources/scripts/components/elements/PageContentBlock.tsx b/resources/scripts/components/elements/PageContentBlock.tsx index 425939134..0c5c4c9a7 100644 --- a/resources/scripts/components/elements/PageContentBlock.tsx +++ b/resources/scripts/components/elements/PageContentBlock.tsx @@ -1,5 +1,6 @@ import React, { useEffect } from 'react'; import ContentContainer from '@/components/elements/ContentContainer'; +import { useOwnerDocument } from '@/components/elements/Portal'; import { cn } from '@/lib/cn'; export interface PageContentBlockProps { @@ -9,9 +10,12 @@ export interface PageContentBlockProps { } const PageContentBlock = ({ title, className, children }: PageContentBlockProps) => { + // A page previewed in the theme workbench titles its frame, not the workbench. + const owner = useOwnerDocument(); + useEffect(() => { - document.title = title || document.title; - }, [title]); + owner.title = title || owner.title; + }, [owner, title]); return (
diff --git a/resources/scripts/components/elements/Portal.tsx b/resources/scripts/components/elements/Portal.tsx index 0cb2d5eba..885154008 100644 --- a/resources/scripts/components/elements/Portal.tsx +++ b/resources/scripts/components/elements/Portal.tsx @@ -1,6 +1,21 @@ -import type React from 'react'; +import React, { createContext, useContext } from 'react'; import { createPortal } from 'react-dom'; -export default function Portal({ children }: { children: React.ReactNode }) { - return createPortal(children, document.getElementById('modal-portal')!); +/** Where overlays render instead of the page's own portal; a workbench preview sets the body of its frame. */ +export const PortalContainerContext = createContext(null); + +/** The element overlays portal into, or undefined for the default (the document body). */ +export function usePortalContainer(): HTMLElement | undefined { + return useContext(PortalContainerContext) ?? undefined; +} + +/** The document the content renders into: a preview frame's, or the page's. */ +export function useOwnerDocument(): Document { + return usePortalContainer()?.ownerDocument ?? document; +} + +export default function Portal({ children }: { children: React.ReactNode }) { + const container = usePortalContainer(); + + return createPortal(children, container ?? document.getElementById('modal-portal')!); } diff --git a/resources/scripts/components/elements/dialog/Dialog.tsx b/resources/scripts/components/elements/dialog/Dialog.tsx index ce2887691..c47373867 100644 --- a/resources/scripts/components/elements/dialog/Dialog.tsx +++ b/resources/scripts/components/elements/dialog/Dialog.tsx @@ -1,6 +1,7 @@ import React, { useMemo, useState } from 'react'; import { Dialog as BaseDialog } from '@base-ui/react/dialog'; import Button from '@/components/elements/Button'; +import { usePortalContainer } from '@/components/elements/Portal'; import { Check, Info, ShieldAlert, TriangleAlert, X } from 'lucide-react'; import { useSkin, type SkinBinding } from '@/themes/skins'; import { DialogContext } from './context'; @@ -41,6 +42,7 @@ export default function DialogComponent({ const popupRef = React.useRef(null); const described = !!description; const ui = useSkin('Dialog', { described }); + const container = usePortalContainer(); const initialFocus = (interactionType: string) => { if (interactionType === 'touch') { @@ -73,7 +75,7 @@ export default function DialogComponent({ {/* Base UI unmounts the popup after its data-ending-style transition finishes. */} - +
diff --git a/resources/scripts/components/elements/dropdown/DropdownMenu.tsx b/resources/scripts/components/elements/dropdown/DropdownMenu.tsx index 0a04fdf37..d547e9019 100644 --- a/resources/scripts/components/elements/dropdown/DropdownMenu.tsx +++ b/resources/scripts/components/elements/dropdown/DropdownMenu.tsx @@ -3,6 +3,7 @@ import { Menu } from '@base-ui/react/menu'; import { ContextMenu } from '@base-ui/react/context-menu'; import type { LucideIcon } from 'lucide-react'; import Icon from '@/components/elements/Icon'; +import { usePortalContainer } from '@/components/elements/Portal'; import { useSkin } from '@/themes/skins'; type MenuItemComponent = React.ComponentType>; @@ -20,6 +21,7 @@ export interface DropdownMenuProps { function DropdownMenu({ triggerContent, triggerClassName, openOnHover, children, className }: DropdownMenuProps) { const ui = useSkin('DropdownMenu', { context: false }); + const container = usePortalContainer(); return ( @@ -30,7 +32,7 @@ function DropdownMenu({ triggerContent, triggerClassName, openOnHover, children, > {triggerContent} - + @@ -53,11 +55,12 @@ export interface ContextDropdownMenuProps { /** Opens `items` at the cursor on right-click or long-press over `children`. */ export function ContextDropdownMenu({ className, menuClassName, children, items }: ContextDropdownMenuProps) { const ui = useSkin('DropdownMenu', { context: true }); + const container = usePortalContainer(); return ( {children} - + {items} diff --git a/resources/scripts/components/elements/tooltip/Tooltip.tsx b/resources/scripts/components/elements/tooltip/Tooltip.tsx index 2541fc7a8..4262d9b7c 100644 --- a/resources/scripts/components/elements/tooltip/Tooltip.tsx +++ b/resources/scripts/components/elements/tooltip/Tooltip.tsx @@ -17,6 +17,7 @@ import { useMergeRefs, useTransitionStyles, } from '@floating-ui/react'; +import { usePortalContainer } from '@/components/elements/Portal'; import { useSkin, type SkinBinding } from '@/themes/skins'; type Interaction = 'hover' | 'click' | 'focus'; @@ -107,12 +108,13 @@ export default function Tooltip({ children, ...props }: TooltipProps) { const referenceRef = useMergeRefs([refs.setReference, children.props.ref]); const ui = useSkin('Tooltip', { side: placement.split('-')[0] as Side, arrow: !!props.arrow }); + const container = usePortalContainer(); return ( <> {cloneElement(children, getReferenceProps({ ...children.props, ref: referenceRef }))} {isMounted && ( - +
( - - - - {emptyMessage} - - - - -); +}) => { + const container = usePortalContainer(); + + return ( + + + + {emptyMessage} + + + + + ); +}; const singleSelectedValues = (value: SelectValue | null | undefined): SelectValue[] => value === null || value === undefined ? [] : [value]; diff --git a/resources/scripts/themes/gallery.tsx b/resources/scripts/themes/gallery.tsx index 0fde5cb6f..818c282d0 100644 --- a/resources/scripts/themes/gallery.tsx +++ b/resources/scripts/themes/gallery.tsx @@ -1,26 +1,36 @@ -import type { ComponentProps, JSXElementConstructor, ReactElement } from 'react'; -import { Copy, Pencil, Server, Trash2 } from 'lucide-react'; +import { useState, type ComponentProps, type JSXElementConstructor, type ReactElement } from 'react'; +import { Archive, Copy, Cpu, Pencil, RefreshCw, Server, Trash2, Upload } from 'lucide-react'; import { Alert, Avatar, + Badge, Button, + Card, Checkbox, + Code, ContentBox, CopyOnClick, + Dialog, DropdownMenu, DropdownMenuItem, Empty, + EmptyContent, EmptyDescription, EmptyHeader, EmptyMedia, EmptyTitle, + FileInput, Input, Label, + ListRow, + NewButton, NumberInput, PageHeading, Pagination, + ProgressBar, Select, Spinner, + SpinnerOverlay, Switch, Table, TextArea, @@ -37,29 +47,81 @@ export interface UiPrimitive = JSXElement /** The component of each UI kit primitive by name; a new primitive adds itself here and to `uiPrimitives`. */ export interface UiPrimitiveComponents { Button: typeof Button; + NewButton: typeof NewButton; Input: typeof Input; TextArea: typeof TextArea; NumberInput: typeof NumberInput; + FileInput: typeof FileInput; Select: typeof Select; Checkbox: typeof Checkbox; Switch: typeof Switch; Label: typeof Label; + Card: typeof Card; + ListRow: typeof ListRow; + PageHeading: typeof PageHeading; + Badge: typeof Badge; Alert: typeof Alert; + ProgressBar: typeof ProgressBar; + Dialog: typeof Dialog; Tooltip: typeof Tooltip; DropdownMenu: typeof DropdownMenu; Table: typeof Table; Pagination: typeof Pagination; Empty: typeof Empty; Spinner: typeof Spinner; + SpinnerOverlay: typeof SpinnerOverlay; Avatar: typeof Avatar; + Code: typeof Code; + CopyOnClick: typeof CopyOnClick; ContentBox: typeof ContentBox; TitledGreyBox: typeof TitledGreyBox; - CopyOnClick: typeof CopyOnClick; - PageHeading: typeof PageHeading; } const noop = () => {}; +/** A dialog the gallery can close and reopen; `open` samples start open, so the frame shows them at once. */ +function DialogSample({ + open: initiallyOpen, + danger, +}: { + open: boolean; + danger?: boolean; +}): ReactElement { + const [open, setOpen] = useState(initiallyOpen); + + return ( + <> + + {danger ? ( + setOpen(false)} + title='Delete this server?' + confirm='Delete' + onConfirmed={() => setOpen(false)} + > + Survival and its files are removed for good. + + ) : ( + setOpen(false)} + title='Rename server' + description='The new name shows on the dashboard and in the console.' + > + + + setOpen(false)}>Cancel + + + + )} + + ); +} + const rows = [ { id: 'survival', name: 'Survival', memory: '4 GiB' }, { id: 'creative', name: 'Creative', memory: '2 GiB' }, @@ -90,17 +152,36 @@ export const uiPrimitives: UiPrimitives = { primary: , secondary: , grey: , + green: , + orange: , danger: , - small: , + secondaryDanger: ( + + ), + text: Restart, + xsmall: , + small: , + large: , + xlarge: , loading: , disabled: , }, }, + NewButton: { + component: NewButton, + samples: { + default: New database, + icon: Upload, + }, + }, Input: { component: Input, samples: { default: , filled: , + light: , error: , disabled: , }, @@ -119,6 +200,13 @@ export const uiPrimitives: UiPrimitives = { disabled: , }, }, + FileInput: { + component: FileInput, + samples: { + default: , + disabled: , + }, + }, Select: { component: Select, samples: { @@ -152,7 +240,89 @@ export const uiPrimitives: UiPrimitives = { disabled: , }, }, - Label: { component: Label, samples: { default: } }, + Label: { + component: Label, + samples: { default: , light: }, + }, + Card: { + component: Card, + samples: { + plain: Memory, disk and CPU limits., + titled: Memory, disk and CPU limits., + icon: ( + + 37.52% of 100% + + ), + actions: ( + + Refresh + + } + > + 2 of 5 backups used. + + ), + loading: ( + + Memory, disk and CPU limits. + + ), + }, + }, + ListRow: { + component: ListRow, + samples: { + default: Survival · 203.0.113.10:25565, + interactive: ( + + Creative · 203.0.113.10:25566 + + ), + link: Dashboard, + list: ( +
    + world + world_nether +
+ ), + }, + }, + PageHeading: { + component: PageHeading, + samples: { + default: , + actions: Create backup} />, + }, + }, + Badge: { + component: Badge, + samples: { + neutral: Installing, + success: Running, + warning: Starting, + danger: Suspended, + info: Update, + accent: New, + soft: ( + + {(['neutral', 'success', 'warning', 'danger', 'info', 'accent'] as const).map((tone) => ( + + {tone} + + ))} + + ), + small: ( + + Beta + + ), + }, + }, Alert: { component: Alert, samples: { @@ -163,7 +333,30 @@ export const uiPrimitives: UiPrimitives = { ), warning: This server is near its disk limit., - danger: The node is unreachable., + danger: ( + + The node is unreachable. + + ), + }, + }, + ProgressBar: { + component: ProgressBar, + samples: { + neutral: , + success: , + warning: , + danger: , + accent: , + empty: , + page: , + }, + }, + Dialog: { + component: Dialog, + samples: { + open: , + confirm: , }, }, Tooltip: { @@ -188,6 +381,19 @@ export const uiPrimitives: UiPrimitives = { ), + described: ( + + + Restore + + + Lock + + + Delete + + + ), }, }, Table: { @@ -226,6 +432,24 @@ export const uiPrimitives: UiPrimitives = { ), + content: ( + + + No databases + This server has none yet. + + + New database + + + ), + compact: ( + + + No backups + + + ), }, }, Spinner: { @@ -234,6 +458,18 @@ export const uiPrimitives: UiPrimitives = { base: , small: , large: , + blue: , + centered: , + }, + }, + SpinnerOverlay: { + component: SpinnerOverlay, + samples: { + default: ( +
+ Saving +
+ ), }, }, Avatar: { @@ -241,6 +477,15 @@ export const uiPrimitives: UiPrimitives = { samples: { default: , square: , + marble: , + pixel: , + }, + }, + Code: { + component: Code, + samples: { + default: server.properties, + dark: java -Xms128M -jar server.jar, }, }, ContentBox: { @@ -270,13 +515,6 @@ export const uiPrimitives: UiPrimitives = { ), }, }, - PageHeading: { - component: PageHeading, - samples: { - default: , - actions: Create backup} />, - }, - }, }; export type UiPrimitiveName = keyof UiPrimitiveComponents; diff --git a/resources/scripts/views/inspector/ViewInspector.tsx b/resources/scripts/views/inspector/ViewInspector.tsx index 3cc05c2b7..859a3a9fc 100644 --- a/resources/scripts/views/inspector/ViewInspector.tsx +++ b/resources/scripts/views/inspector/ViewInspector.tsx @@ -11,8 +11,33 @@ const inspection: ViewInspection = { wrap: true }; export const isInspectorShortcut = (event: KeyboardEvent): boolean => event.altKey && event.shiftKey && !event.ctrlKey && !event.metaKey && event.code === 'KeyI'; +/** Keeps the inspector on across reloads of this tab, such as the reloads `p:extension:dev --watch` triggers. */ +export const INSPECTOR_STORAGE_KEY = 'pterodactyl:inspector'; + +function storedInspector(): boolean { + try { + return sessionStorage.getItem(INSPECTOR_STORAGE_KEY) === 'on'; + } catch { + return false; + } +} + +function storeInspector(on: boolean): void { + try { + if (on) { + sessionStorage.setItem(INSPECTOR_STORAGE_KEY, 'on'); + } else { + sessionStorage.removeItem(INSPECTOR_STORAGE_KEY); + } + } catch { + // Storage can be unavailable; the inspector then starts off on the next load. + } +} + function InspectorRoot({ children }: { children?: ReactNode }) { - const [on, setOn] = useState(false); + const [on, setOn] = useState(storedInspector); + + useEffect(() => storeInspector(on), [on]); useEffect(() => { const onKey = (event: KeyboardEvent) => { diff --git a/resources/scripts/views/inspector/inspector.spec.tsx b/resources/scripts/views/inspector/inspector.spec.tsx index 9ea53cda4..6339ee5ad 100644 --- a/resources/scripts/views/inspector/inspector.spec.tsx +++ b/resources/scripts/views/inspector/inspector.spec.tsx @@ -65,6 +65,7 @@ afterEach(() => { cleanup(); vi.restoreAllMocks(); open.mockReset(); + sessionStorage.clear(); Object.assign(window, { SiteConfiguration: undefined }); }); @@ -108,6 +109,24 @@ describe('ViewInspector', () => { expect(screen.queryByText(/Inspecting views/)).not.toBeInTheDocument(); }); + it('stays on across reloads of the tab until turned off', async () => { + page(); + await toggle(); + await screen.findByText(/Inspecting views/); + cleanup(); + + const { container } = page(); + + expect(await screen.findByText(/Inspecting views/)).toBeInTheDocument(); + expect(container.querySelector('[data-view]')).not.toBeNull(); + + fireEvent.click(screen.getByRole('button', { name: 'Inspect views' })); + cleanup(); + page(); + + expect(screen.getByRole('button', { name: 'Inspect views' })).toHaveAttribute('aria-pressed', 'false'); + }); + it('outlines the view under the pointer and pins it on click instead of clicking the page', async () => { page(); await toggle(); diff --git a/tests/Integration/Http/ThemeDocumentTest.php b/tests/Integration/Http/ThemeDocumentTest.php index 738c396ad..92fad5f0c 100644 --- a/tests/Integration/Http/ThemeDocumentTest.php +++ b/tests/Integration/Http/ThemeDocumentTest.php @@ -37,7 +37,7 @@ afterEach(function (): void { * @param array $theme * @param array $build */ -function installTheme(string $id, array $theme = [], array $build = ['core' => CORE, 'sdk' => '2.0.0-beta.4']): void +function installTheme(string $id, array $theme = [], array $build = ['core' => CORE, 'sdk' => '2.0.0-beta.5']): void { (function () use ($id, $theme, $build): void { $directory = $this->baseDirectory.'/extensions/'.$id; @@ -136,7 +136,7 @@ test('a theme stylesheet built against other core classes is laid over the panel expect(mb_strpos($html, 'stylesheet.test.css'))->toBeLessThan(mb_strpos($html, '/assets/extensions/aurora/theme.css')); expect(themePayload($this->get('/auth/login'))['stylesheetFallback'])->toBeTrue(); })->with([ - 'another hash' => [['core' => 'another0000hash0', 'sdk' => '2.0.0-beta.4']], + 'another hash' => [['core' => 'another0000hash0', 'sdk' => '2.0.0-beta.5']], 'no build info' => [[]], ]); diff --git a/tests/Integration/Services/Themes/ThemeLifecycleTest.php b/tests/Integration/Services/Themes/ThemeLifecycleTest.php index 78e64f3aa..251099553 100644 --- a/tests/Integration/Services/Themes/ThemeLifecycleTest.php +++ b/tests/Integration/Services/Themes/ThemeLifecycleTest.php @@ -56,7 +56,7 @@ function themePackage(string $id, array $theme = [], array $files = [], array $m 'theme' => ['stylesheet' => 'dist/theme.css', ...$theme], ...$manifest, ], JSON_THROW_ON_ERROR)); - foreach (['theme.css' => ':root{--accent:red}', 'theme.json' => '{"core":"f1x7ure0c0re0000","sdk":"2.0.0-beta.4"}', ...$files] as $name => $contents) { + foreach (['theme.css' => ':root{--accent:red}', 'theme.json' => '{"core":"f1x7ure0c0re0000","sdk":"2.0.0-beta.5"}', ...$files] as $name => $contents) { File::put($path.'/dist/'.$name, $contents); } @@ -152,7 +152,7 @@ test('doctor and enable refuse theme builds that load remote files, outgrow thei ]); test('doctor warns when a theme stylesheet was built against other core classes', function (): void { - $path = themePackage('aurora', files: ['theme.json' => '{"core":"0ther0000000hash","sdk":"2.0.0-beta.4"}']); + $path = themePackage('aurora', files: ['theme.json' => '{"core":"0ther0000000hash","sdk":"2.0.0-beta.5"}']); $this->artisan('p:extension:doctor', ['path' => $path]) ->expectsOutputToContain('built against core classes "0ther0000000hash", but this panel has "f1x7ure0c0re0000"')