From cf0322c5cb2b320c5feeb7654256390d2fc13d58 Mon Sep 17 00:00:00 2001 From: robert dennis <31261583+robertdrakedennis@users.noreply.github.com> Date: Mon, 12 Oct 2026 16:11:44 -0400 Subject: [PATCH] theme samples --- .../Scaffolding/ExtensionScaffolder.php | 33 +- .../Scaffolding/stubs/theme-css.stub | 28 +- .../Scaffolding/stubs/theme-layout.stub | 14 + .../Scaffolding/stubs/theme-package.stub | 5 +- .../Scaffolding/stubs/theme-readme.stub | 59 +-- .../Scaffolding/stubs/theme-skins.stub | 34 ++ .../Scaffolding/stubs/theme-test.stub | 21 +- .../Scaffolding/stubs/theme-tsx.stub | 31 +- packages/sdk/README.md | 136 +++--- packages/sdk/docs-samples.spec.ts | 50 +++ .../sdk/docs-samples/aurora/extension.json | 56 +++ .../docs-samples/aurora/src/SchemeSwitch.tsx | 34 ++ packages/sdk/docs-samples/aurora/src/skins.ts | 68 +++ .../docs-samples/aurora/src/theme-types.ts | 20 + .../sdk/docs-samples/aurora/src/theme.css | 98 +++++ .../docs-samples/aurora/src/theme.spec.tsx | 52 +++ .../sdk/docs-samples/aurora/src/theme.tsx | 23 + .../aurora/src/views/AppShell.tsx | 65 +++ .../aurora/src/views/AuthLayout.tsx | 32 ++ .../aurora/src/views/ConsolePage.tsx | 34 ++ .../aurora/src/views/LoginForm.tsx | 55 +++ .../docs-samples/aurora/src/views/Power.tsx | 50 +++ .../aurora/src/views/ServerCard.tsx | 46 ++ .../aurora/src/views/ServerGrid.tsx | 133 ++++++ .../aurora/src/views/ServerLayout.tsx | 37 ++ .../docs-samples/aurora/src/views/Stats.tsx | 40 ++ .../aurora/src/views/Terminal.tsx | 58 +++ .../sdk/docs-samples/aurora/vite.config.mjs | 3 + .../docs-samples/child-theme/extension.json | 14 + .../docs-samples/child-theme/src/theme.tsx | 12 + .../sdk/docs-samples/snippets/FileDetails.tsx | 6 + .../sdk/docs-samples/snippets/extension.tsx | 60 +++ .../sdk/docs-samples/snippets/navigation.tsx | 59 +++ packages/sdk/docs-samples/snippets/skins.tsx | 51 +++ packages/sdk/docs-samples/snippets/views.tsx | 75 ++++ packages/sdk/docs-samples/tsconfig.json | 21 +- packages/sdk/docs-samples/vitest.config.ts | 15 + .../sdk/types/components/elements/Portal.d.ts | 8 +- packages/sdk/types/sdk/testing.d.ts | 5 +- packages/sdk/types/themes/gallery.d.ts | 17 +- resources/scripts/sdk/testing.spec.tsx | 23 + resources/scripts/sdk/testing.tsx | 23 +- scripts/generate-sdk-docs.mjs | 414 ++++++++++++++++++ .../Extensions/ExtensionScaffolderTest.php | 25 +- .../Services/Themes/ThemeManifestTest.php | 9 + vitest.config.ts | 6 +- 46 files changed, 2021 insertions(+), 137 deletions(-) create mode 100644 app/Services/Extensions/Scaffolding/stubs/theme-layout.stub create mode 100644 app/Services/Extensions/Scaffolding/stubs/theme-skins.stub create mode 100644 packages/sdk/docs-samples.spec.ts create mode 100644 packages/sdk/docs-samples/aurora/extension.json create mode 100644 packages/sdk/docs-samples/aurora/src/SchemeSwitch.tsx create mode 100644 packages/sdk/docs-samples/aurora/src/skins.ts create mode 100644 packages/sdk/docs-samples/aurora/src/theme-types.ts create mode 100644 packages/sdk/docs-samples/aurora/src/theme.css create mode 100644 packages/sdk/docs-samples/aurora/src/theme.spec.tsx create mode 100644 packages/sdk/docs-samples/aurora/src/theme.tsx create mode 100644 packages/sdk/docs-samples/aurora/src/views/AppShell.tsx create mode 100644 packages/sdk/docs-samples/aurora/src/views/AuthLayout.tsx create mode 100644 packages/sdk/docs-samples/aurora/src/views/ConsolePage.tsx create mode 100644 packages/sdk/docs-samples/aurora/src/views/LoginForm.tsx create mode 100644 packages/sdk/docs-samples/aurora/src/views/Power.tsx create mode 100644 packages/sdk/docs-samples/aurora/src/views/ServerCard.tsx create mode 100644 packages/sdk/docs-samples/aurora/src/views/ServerGrid.tsx create mode 100644 packages/sdk/docs-samples/aurora/src/views/ServerLayout.tsx create mode 100644 packages/sdk/docs-samples/aurora/src/views/Stats.tsx create mode 100644 packages/sdk/docs-samples/aurora/src/views/Terminal.tsx create mode 100644 packages/sdk/docs-samples/aurora/vite.config.mjs create mode 100644 packages/sdk/docs-samples/child-theme/extension.json create mode 100644 packages/sdk/docs-samples/child-theme/src/theme.tsx create mode 100644 packages/sdk/docs-samples/snippets/FileDetails.tsx create mode 100644 packages/sdk/docs-samples/snippets/extension.tsx create mode 100644 packages/sdk/docs-samples/snippets/navigation.tsx create mode 100644 packages/sdk/docs-samples/snippets/skins.tsx create mode 100644 packages/sdk/docs-samples/snippets/views.tsx create mode 100644 packages/sdk/docs-samples/vitest.config.ts create mode 100644 scripts/generate-sdk-docs.mjs diff --git a/app/Services/Extensions/Scaffolding/ExtensionScaffolder.php b/app/Services/Extensions/Scaffolding/ExtensionScaffolder.php index 2e9483f48..c472deb65 100644 --- a/app/Services/Extensions/Scaffolding/ExtensionScaffolder.php +++ b/app/Services/Extensions/Scaffolding/ExtensionScaffolder.php @@ -127,7 +127,7 @@ class ExtensionScaffolder 'id' => $id, 'name' => $replacements['{{name}}'], 'version' => '1.0.0', - 'requires' => ['panel' => '^2.0.0-dev', 'sdk' => '^2.0.0-beta.4', 'php' => '^8.3'], + 'requires' => ['panel' => '^2.0.0-dev', 'sdk' => $this->sdkConstraint(), 'php' => '^8.3'], 'description' => $replacements['{{description}}'] ?: null, 'author' => $replacements['{{author}}'] ?: null, 'provider' => $namespace.'\\'.$namespace.'Provider', @@ -142,8 +142,9 @@ class ExtensionScaffolder } /** - * A theme with a stylesheet, a layout override and a skin, three settings and a test. It - * needs no PHP; a provider can be added like an extension's. + * A theme with a stylesheet for both schemes, a skin, a layout override, four settings and a + * test, laid out as the SDK README's theme chapter describes. It needs no PHP; a provider can be + * added like an extension's. * * @param array $replacements stub placeholder => literal substitution */ @@ -155,7 +156,7 @@ class ExtensionScaffolder 'type' => 'theme', 'name' => $replacements['{{name}}'], 'version' => '1.0.0', - 'requires' => ['panel' => '^2.0.0-dev', 'sdk' => '^'.config()->string('extensions.sdk_version')], + 'requires' => ['panel' => '^2.0.0-dev', 'sdk' => $this->sdkConstraint()], 'description' => $replacements['{{description}}'] ?: null, 'author' => $replacements['{{author}}'] ?: null, 'icon' => 'palette', @@ -165,9 +166,10 @@ class ExtensionScaffolder 'stylesheet' => ThemeDefinition::STYLESHEET, 'schemes' => ThemeDefinition::SCHEMES, 'settings' => [ - 'accent' => ['type' => 'color', 'label' => 'Accent', 'default' => '#8b5cf6', 'token' => '--accent'], + 'accent' => ['type' => 'color', 'label' => 'Accent', 'default' => '#8b5cf6', 'token' => "--{$id}-accent"], 'radius' => ['type' => 'number', 'label' => 'Corner radius', 'default' => 0.75, 'min' => 0, 'max' => 1.5, 'step' => 0.125, 'unit' => 'rem', 'token' => '--radius'], 'compact' => ['type' => 'toggle', 'label' => 'Compact spacing', 'default' => false, 'attribute' => "data-{$id}-compact"], + 'logo' => ['type' => 'image', 'label' => 'Logo', 'help' => 'Shown in place of the panel name.', 'token' => '--brand-logo'], ], ], ], fn (array|string|null $value): bool => $value !== null); @@ -175,6 +177,7 @@ class ExtensionScaffolder File::put($target.DIRECTORY_SEPARATOR.ExtensionManifest::FILENAME, json_encode($manifest, JSON_PRETTY_PRINT | JSON_UNESCAPED_SLASHES | JSON_PRESERVE_ZERO_FRACTION)."\n"); $this->files[] = ExtensionManifest::FILENAME; + $replacements['{{artisan}}'] = $this->artisanPath($target); foreach ([ 'theme-package.stub' => 'package.json', 'theme-vite.config.stub' => 'vite.config.mjs', @@ -183,6 +186,8 @@ class ExtensionScaffolder 'vitest.config.stub' => 'vitest.config.mjs', 'theme-css.stub' => 'src/theme.css', 'theme-tsx.stub' => 'src/theme.tsx', + 'theme-skins.stub' => 'src/skins.ts', + 'theme-layout.stub' => 'src/views/AppLayout.tsx', 'theme-test.stub' => 'src/theme.spec.tsx', 'gitignore.stub' => '.gitignore', 'theme-readme.stub' => 'README.md', @@ -191,6 +196,20 @@ class ExtensionScaffolder } } + /** The `requires.sdk` constraint of a new package: this SDK or a later 2.x one. */ + private function sdkConstraint(): string + { + return '>='.config()->string('extensions.sdk_version').' <3.0'; + } + + /** The panel's artisan as the package's npm scripts reach it: relative when they share a root. */ + private function artisanPath(string $target): string + { + $relative = $this->relativePath($target, base_path()); + + return $relative === null ? str_replace('\\', '/', base_path('artisan')) : mb_rtrim($relative, '/').'/artisan'; + } + /** * The PSR-4 map lives in composer.json, where Composer, editors and static analysis read * it, and the panel reads it from there too. The autoloader suffix keeps the class a @@ -239,7 +258,7 @@ class ExtensionScaffolder { $sdk = base_path('packages'.DIRECTORY_SEPARATOR.'sdk'); if (! is_file($sdk.DIRECTORY_SEPARATOR.'package.json')) { - return '^2.0.0-beta.4'; + return '^'.config()->string('extensions.sdk_version'); } $relative = $this->relativePath($target, $sdk); @@ -249,7 +268,7 @@ class ExtensionScaffolder $version = File::json($sdk.DIRECTORY_SEPARATOR.'package.json')['version'] ?? null; - return '^'.(is_string($version) ? $version : '2.0.0-beta.4'); + return '^'.(is_string($version) ? $version : config()->string('extensions.sdk_version')); } private function relativePath(string $from, string $to): ?string diff --git a/app/Services/Extensions/Scaffolding/stubs/theme-css.stub b/app/Services/Extensions/Scaffolding/stubs/theme-css.stub index 6137d88cf..01c1b6e10 100644 --- a/app/Services/Extensions/Scaffolding/stubs/theme-css.stub +++ b/app/Services/Extensions/Scaffolding/stubs/theme-css.stub @@ -1,14 +1,38 @@ /* * The panel stylesheet with every class the panel uses, then this theme's own. Write plain - * Tailwind: there is no prefix, and anything here can retune the panel's tokens. + * Tailwind: there is no prefix, and anything here can retune the panel's tokens. The SDK + * README lists every token under "Tokens". */ @import '@pterodactyl/sdk/theme-entry.css'; +/* Both schemes. The "accent" setting writes --{{id}}-accent; the roles below derive from it. */ :root { + --primary: var(--{{id}}-accent, #8b5cf6); + --ring: color-mix(in oklab, var(--primary) 60%, transparent); --layout-content-width: 80rem; } -/* The "compact" setting writes data-{{id}}-compact on . */ +/* Dark: the first scheme in extension.json, so the default. */ +.dark { + --background: oklch(0.2 0.02 275); + --card: oklch(0.25 0.025 275); + --popover: oklch(0.3 0.03 275); + --border: oklch(0.33 0.03 275); +} + +/* Light. Classic's light palette is provisional, so a theme that offers light sets its own. */ +.light { + --background: oklch(0.98 0.005 275); + --foreground: oklch(0.22 0.02 275); + --card: oklch(1 0 0); + --card-foreground: oklch(0.22 0.02 275); + --popover: oklch(0.96 0.01 275); + --popover-foreground: oklch(0.22 0.02 275); + --muted-foreground: oklch(0.5 0.02 275); + --border: oklch(0.9 0.01 275); +} + +/* The "compact" setting writes data-{{id}}-compact on ; spacing utilities multiply --spacing. */ [data-{{id}}-compact='true'] { --spacing: 0.2rem; } diff --git a/app/Services/Extensions/Scaffolding/stubs/theme-layout.stub b/app/Services/Extensions/Scaffolding/stubs/theme-layout.stub new file mode 100644 index 000000000..ae5ea42ec --- /dev/null +++ b/app/Services/Extensions/Scaffolding/stubs/theme-layout.stub @@ -0,0 +1,14 @@ +import type { ViewProps } from '@pterodactyl/sdk/theme'; + +/** + * A layer over classic's app layout: `Default` renders classic's navigation bar and the page. To + * draw your own shell, render `model.links` and `model.brand`, keep the `nav.items.before` and + * `nav.items.after` slots, and place `children` inside `
`. + */ +export default function AppLayout({ Default }: ViewProps<'layout.app'>) { + return ( +
+ +
+ ); +} diff --git a/app/Services/Extensions/Scaffolding/stubs/theme-package.stub b/app/Services/Extensions/Scaffolding/stubs/theme-package.stub index da2335ba1..f5db1d5b8 100644 --- a/app/Services/Extensions/Scaffolding/stubs/theme-package.stub +++ b/app/Services/Extensions/Scaffolding/stubs/theme-package.stub @@ -8,7 +8,10 @@ "dev": "vite build --watch", "typecheck": "tsc", "test": "vitest run", - "test:watch": "vitest" + "test:watch": "vitest", + "doctor": "php {{artisan}} p:extension:doctor .", + "types": "php {{artisan}} p:extension:types .", + "pack": "php {{artisan}} p:extension:pack ." }, "devDependencies": { "@pterodactyl/sdk": "{{sdkDependency}}", diff --git a/app/Services/Extensions/Scaffolding/stubs/theme-readme.stub b/app/Services/Extensions/Scaffolding/stubs/theme-readme.stub index 5891bf82e..c80c6f744 100644 --- a/app/Services/Extensions/Scaffolding/stubs/theme-readme.stub +++ b/app/Services/Extensions/Scaffolding/stubs/theme-readme.stub @@ -1,38 +1,45 @@ # {{name}} -A Pterodactyl panel theme, scaffolded by `p:extension:make --theme`. +A Pterodactyl panel theme, scaffolded by `p:extension:make --theme`. The "Themes" chapter of the +SDK README (`node_modules/@pterodactyl/sdk/README.md`) documents everything used here: the +manifest, the stylesheet and tokens, skins, views, the workbench, the CLI and the test helpers. -## Layout +## Files -- `extension.json`: the manifest. `"type": "theme"` and its `theme` section declare the - stylesheet, the colour schemes and the settings administrators change on the Themes page. -- `src/theme.css`: the panel stylesheet with this theme's styles. It starts with - `@import '@pterodactyl/sdk/theme-entry.css';`, so the build holds every class the panel - uses and replaces the panel's stylesheet. Write plain Tailwind; there is no prefix. -- `src/theme.tsx`: `defineTheme` with skins for the UI kit and view overrides. Render - `Default` from an override to keep the layer below. -- `src/theme.spec.tsx`: renders a view with the theme through `@pterodactyl/sdk/testing`. +| File | | +| --- | --- | +| `extension.json` | The manifest. `"type": "theme"` and its `theme` section declare the stylesheet, the colour schemes and the settings administrators change on the Themes page. | +| `src/theme.css` | The panel stylesheet with this theme's tokens and classes. It starts with `@import '@pterodactyl/sdk/theme-entry.css';` and replaces the panel's stylesheet. Plain Tailwind, no prefix. | +| `src/theme.tsx` | `defineTheme`: skins for the UI kit and views by name. | +| `src/skins.ts` | Class recipes for UI primitives such as `Button` and `Card`. | +| `src/views/AppLayout.tsx` | A layer over classic's app layout. | +| `src/theme.spec.tsx` | Renders views and primitives with the theme through `@pterodactyl/sdk/testing`. | -Each setting writes a CSS token (`token`), an `` attribute (`attribute`), or both, -before the page renders. `php artisan p:extension:types` generates `src/theme-types.ts`, -whose `ThemeSettings` types `useThemeSettings()`. +Each setting writes a CSS token (`token`), an `` attribute (`attribute`), or both, before the +page renders. `npm run types` writes `src/theme-types.ts`, whose `ThemeSettings` types +`useThemeSettings()`. + +## Scripts + +| Script | | +| --- | --- | +| `npm run build` | `dist/client.js`, `dist/theme.css` and `dist/theme.json`. | +| `npm run dev` | Rebuilds on change; `p:extension:dev --watch` runs it. | +| `npm run typecheck` | Checks the theme against the SDK's types. | +| `npm test` | Runs the tests. | +| `npm run doctor` | The panel's checks: manifest, build, budgets, remote URLs and view names. | +| `npm run types` | Generates `src/theme-types.ts` from the settings. | +| `npm run pack` | Packs a `.pteroext` archive to install on another panel. | ## Develop ```sh npm install -npm run build -php artisan p:extension:dev /path/to/{{id}} --enable --watch -php artisan p:theme:activate {{id}} +php {{artisan}} p:extension:dev . --enable +php {{artisan}} p:theme:activate {{id}} +php {{artisan}} p:extension:dev . --watch ``` -While `p:extension:dev --watch` runs, a change to `src/theme.css` is swapped into open pages -without a reload; a change to the JavaScript reloads them. - -## Install - -```sh -php artisan p:extension:pack /path/to/{{id}} -php artisan p:extension:install {{id}}-1.0.0.pteroext --enable -php artisan p:theme:activate {{id}} -``` +The first command builds, installs and enables the theme. While the last one runs on a panel with +`APP_DEBUG=true`, a change to `src/theme.css` swaps into open pages without a reload, and any other +change reloads them. `/panel/theme-workbench` renders every view and primitive from fixtures. diff --git a/app/Services/Extensions/Scaffolding/stubs/theme-skins.stub b/app/Services/Extensions/Scaffolding/stubs/theme-skins.stub new file mode 100644 index 000000000..dc1f003a9 --- /dev/null +++ b/app/Services/Extensions/Scaffolding/stubs/theme-skins.stub @@ -0,0 +1,34 @@ +import { skin, type PrimitiveState, type ThemeSkins } from '@pterodactyl/sdk/theme'; + +type ButtonState = PrimitiveState<'Button'>; + +const fills: Record = { + primary: 'bg-primary text-primary-foreground hover:not-disabled:bg-primary/85', + grey: 'bg-popover text-foreground hover:not-disabled:bg-secondary', + green: 'bg-success text-success-foreground hover:not-disabled:bg-success/85', + red: 'bg-destructive text-destructive-foreground hover:not-disabled:bg-destructive/85', + orange: 'bg-caution text-caution-foreground hover:not-disabled:bg-caution/85', +}; + +/** + * Class recipes by primitive and part; a part left out keeps classic's recipe. `npx pterodactyl-theme + * skins Button` prints classic's skin of a primitive to start from. + */ +export const skins: ThemeSkins = { + // Replaces the root recipe; the spinner and label keep classic's. + Button: skin('Button', { + root: ({ color, size, secondary }) => + [ + 'relative inline-flex items-center justify-center gap-2 rounded-full font-medium transition-colors disabled:opacity-50', + size === 'xsmall' ? 'h-7 px-3 text-xs' : 'h-9 px-4 text-sm', + size === 'xlarge' && 'w-full', + secondary ? 'bg-transparent text-foreground ring-1 ring-border hover:not-disabled:bg-popover' : fills[color], + ] + .filter(Boolean) + .join(' '), + }), + // Builds on classic's card by adding classes it does not set. + Card: skin('Card', (classic) => ({ + root: (state) => `${classic.root(state)} ring-1 ring-border/60`, + })), +}; diff --git a/app/Services/Extensions/Scaffolding/stubs/theme-test.stub b/app/Services/Extensions/Scaffolding/stubs/theme-test.stub index 5d56a2b6f..731f52cab 100644 --- a/app/Services/Extensions/Scaffolding/stubs/theme-test.stub +++ b/app/Services/Extensions/Scaffolding/stubs/theme-test.stub @@ -1,12 +1,21 @@ -import { afterEach, expect, test } from 'vitest'; -import { cleanup } from '@testing-library/react'; -import { renderView } from '@pterodactyl/sdk/testing'; +import { afterEach, beforeAll, expect, test } from 'vitest'; +import { preloadTheme, renderPrimitive, renderView, type RenderedView } from '@pterodactyl/sdk/testing'; import theme from './theme'; -afterEach(cleanup); +let rendered: RenderedView | undefined; + +// Loads the chunks of views declared with lazyView, so renderView renders them at once. +beforeAll(() => preloadTheme(theme)); +afterEach(() => rendered?.unmount()); test('frames the classic app layout', () => { - const { container } = renderView('layout.app', { theme }); + rendered = renderView('layout.app', { theme, fixture: 'admin' }); - expect(container.querySelector('[data-{{id}}-layout]')).not.toBeNull(); + expect(rendered.container.querySelector('[data-{{id}}-layout] main')).not.toBeNull(); +}); + +test('draws buttons as pills', () => { + rendered = renderPrimitive('Button', { children: 'Save' }, { theme }); + + expect(rendered.container.querySelector('button')?.className).toContain('rounded-full'); }); diff --git a/app/Services/Extensions/Scaffolding/stubs/theme-tsx.stub b/app/Services/Extensions/Scaffolding/stubs/theme-tsx.stub index 2854a7bf6..8453d2298 100644 --- a/app/Services/Extensions/Scaffolding/stubs/theme-tsx.stub +++ b/app/Services/Extensions/Scaffolding/stubs/theme-tsx.stub @@ -1,27 +1,14 @@ -import { defineTheme, skin, type ViewProps } from '@pterodactyl/sdk/theme'; - -/** Puts the classic app layout inside a frame of this theme's own. */ -function AppLayout({ Default }: ViewProps<'layout.app'>) { - return ( -
- -
- ); -} +import { defineTheme } from '@pterodactyl/sdk/theme'; +import { skins } from './skins'; +import AppLayout from './views/AppLayout'; +/** + * Skins for the UI kit and views by name. `npx pterodactyl-theme list` lists every view, and + * `npx pterodactyl-theme eject ` copies classic's source for one into src/views. Wrap pages + * and blocks in lazyView(() => import('./views/…')) so they load when first shown. + */ export default defineTheme({ - ui: { - Button: skin('Button', { - root: { - base: 'inline-flex h-9 items-center justify-center gap-2 rounded-full px-4 text-sm font-medium transition-colors', - variants: { - color: { - primary: 'bg-accent text-accent-foreground hover:bg-accent/90', - }, - }, - }, - }), - }, + ui: skins, views: { 'layout.app': AppLayout, }, diff --git a/packages/sdk/README.md b/packages/sdk/README.md index f4f4281b7..6bf64c857 100644 --- a/packages/sdk/README.md +++ b/packages/sdk/README.md @@ -1,12 +1,19 @@ # @pterodactyl/sdk -Build extensions for the Pterodactyl panel (v2+). This package provides: +Build extensions and themes for the Pterodactyl panel (v2+). This package provides: - **Types** for the runtime API. The implementation is provided *by the panel* through its import map, so your built extension never bundles the SDK, React, or TanStack Query: it shares the panel's own instances. -- **The Vite build preset** (`@pterodactyl/sdk/vite`) that keeps those modules external - and emits `dist/client.js` plus lazy screen chunks. +- **The Vite build presets** (`@pterodactyl/sdk/vite`): `defineExtensionConfig` keeps those + modules external and emits `dist/client.js` plus lazy screen chunks; `defineThemeConfig` + also builds a theme's stylesheet. +- **Test helpers** (`@pterodactyl/sdk/testing`, `@pterodactyl/sdk/vitest`) that render views, + UI primitives and screens with the real runtime and no backend. +- **The `pterodactyl-theme` CLI**, which lists the panel's views, ejects the stock theme's source + for one, and prints its skins. + +Extensions start at [Quick start](#quick-start). Themes start at [Themes](#themes). ## Quick start @@ -143,17 +150,13 @@ matches the panel's empty states; pass it as a `Table`'s `emptyState`. `resources/lang//messages.php` group. Extension CSS is built with the extension's own Tailwind prefix (see [Styling](#styling)). The Vite preset waits for entry CSS before setup. -Themes override the panel's CSS tokens: colour roles, the `--terminal-*` -and `--editor-*` palettes, `--selection`, `--scrollbar-*`, `--color-scheme`, `--theme-color`, -and the layout tokens `--layout-content-width`, `--layout-auth-width`, -`--layout-sidebar-width` (`max-w-panel`, `max-w-auth`, `w-sidebar`) and `--spacing` (density). -Extension utilities read the same live tokens (`hw:bg-card`, `hw:w-sidebar`, `hw:p-4` for the prefix `hw`). -`document.documentElement.dataset.subNavigation = 'side'` moves the account and server -sub-navigation into a sidebar. The console and the `theme-color` meta re-read their tokens -when a stylesheet or an inline property on `` changes; `onThemeChange(listener)` gives -canvas or chart code the same signal, `readThemeToken('--name')` reads a value, and -`notifyThemeChange()` reports changes made through the CSSOM. Only the panel's own -`theme-color` tag follows the token; one registered with `registerHeadTags` is left as rendered. +The active theme sets the panel's CSS tokens (see [Tokens](#tokens)). Extension utilities read +the same live tokens (`hw:bg-card`, `hw:w-sidebar`, `hw:p-4` for the prefix `hw`), so an +extension follows the theme without knowing it. The console and the `theme-color` meta re-read +their tokens when a stylesheet or an inline property on `` changes; `onThemeChange(listener)` +gives canvas or chart code the same signal, `readThemeToken('--name')` reads a value, and +`notifyThemeChange()` reports changes made through the CSSOM. Only the panel's own `theme-color` +tag follows the token; one registered with `registerHeadTags` is left as rendered. ## Conditional screens, badges, and icons @@ -733,55 +736,68 @@ build with either layer and no `ui.prefix` is rejected with the line to add. Every layout, page and block of the panel is a named view: an engine hook that produces its model, and a stack of layers that render it. Classic, the stock UI, is the bottom layer; the -active theme and its parents stack above it, then extension overrides in the configured -order. Each layer receives `{ model, Default, ...inputs, children }`, and `Default` renders -the layer below. The catalog of names, with each view's kind, context, slots and fixtures, -ships as `@pterodactyl/sdk/views.json`. +active theme and its parents stack above it, then extension overrides in the configured order. +Each layer receives `{ model, Default, ...inputs, children }`, and `Default` renders the layer +below. Themes and extensions write layers the same way; [Views](#views-1) in the Themes chapter +covers the API in full, and the [view catalogue](#view-catalogue) lists every view with its +model, inputs, slots and fixtures. The catalogue also ships as `@pterodactyl/sdk/views.json`. + +### Overriding a view Declare the views an extension overrides in `extension.json` under `ui.views`, with a -`requires.sdk` constraint of `>=2.0.0-beta.4 <3.0`. Overrides are not exclusive: several enabled -extensions and the active theme may override the same view, and `p:extension:doctor` reports a -name under a core namespace that the panel does not have. +`requires.sdk` constraint such as `>=2.0.0-beta.5 <3.0`, and register each layer with +`views.override(name, layer)` during `setup`. A layer is a component, or `{ load }` with an +importer the panel calls when the view first renders. Overrides are not exclusive: several +enabled extensions and the active theme may override the same view, and each layer's `Default` +renders the one below. `p:extension:doctor` reports a name under a core namespace that the +panel does not have. -```tsx -import { definePterodactylExtension, type ViewProps } from '@pterodactyl/sdk'; - -function ServerCard({ Default }: ViewProps<'dashboard.serverCard'>) { - return ; -} - -export default definePterodactylExtension({ - setup({ views }) { - views.override('dashboard.serverCard', ServerCard); - views.override('server.files.details', { load: () => import('./FileDetails') }); - }, -}); +```json +{ "ui": { "entry": "dist/client.js", "prefix": "hw", "views": ["dashboard.serverCard", "server.files.details"] } } ``` -`packages/hello-world` overrides the server card, the file details and the file editor, each with a test. + + -`Default` takes optional `model`, `className` and `children`, which replace what this layer -received for the layer below: ``. -Views with parts also receive `parts`, the parts of the layer below, and `Default` accepts -partial `parts` overrides. A part receives the model and the view's inputs, typed by -`ViewPartProps`; define parts outside the layer's render function. + + -| Name | Model | Inputs | Parts | -| --- | --- | --- | --- | -| `dashboard.serverCard` | `ServerCardModel` | `server` | `identity`, `address`, `metrics` | -| `server.files.details` | `FileDetailsModel` | `file` | `icon`, `name`, `size`, `modified` | -| `server.files.editor` | `FileEditorModel` | | `notice`, `editor`, `language`, `actions` | -| `server.files.manager` | `FileManagerModel` | | `toolbar`, `list`, `selection` | +`packages/hello-world` overrides the server card, the file details and the file editor, each with +a test. Classes passed to `Default` merge with the layer below's under the extension's prefix (see +[Styling](#styling)). -The server card and file details render inside core links. Keep interactive controls in -action slots. The panel retains queries, permissions, navigation, accessible link names, -selection, and menus. The classic server-card identity part includes the -`dashboard.serverRow.name.after` slot. +The server card and file details render inside core links. Keep interactive controls in action +slots. The panel retains queries, permissions, navigation, accessible link names, selection, and +menus. The classic server-card identity part includes the `dashboard.serverRow.name.after` slot. -`views.define(name, { context, use, Default, fixtures })` adds a view of the extension's own, -so a theme can restyle or place it. `Default` is its bottom layer. A theme renders it with -``, which renders nothing while the extension is not -installed. +### Defining a view + +`views.define(name, { context, use, Default, fixtures, placeholder })` adds a view of the +extension's own, so themes and other extensions can restyle or place it: + +| Option | | +| --- | --- | +| `context` | Where it can render: `app` (every signed-in page), `server`, `account`, `admin` or `auth`. | +| `use(inputs)` | The hook that produces the model. It is the view's only data source. | +| `Default` | The bottom layer, typed by `ExtensionViewProps`. Build it from the [UI kit](#ui-kit) and it takes the active theme's skins. | +| `fixtures` | Models by name, which the workbench and tests render without a backend. The first is the default. | +| `placeholder` | Shown while a layer above it loads. | + +Use a namespace of your own, such as your extension id: `layout.` and `page.` names are refused, +and so is a second definition of a name. The view renders wherever a layer or a slot places it +with ``; a theme that may run without the extension places it +with `optional`, which renders nothing while no installed package defines it. + + + + +### Slots inside views + +A view renders the slots listed for it in the catalogue, and a layer that replaces it has to +render them too, or the extensions mounted there disappear. Rendering `Default` renders the +slots of the layers below. In development, a layer that renders none of its view's slots logs +a warning naming them after three seconds. The before and after slots of a page are rendered by +the engine around the page view, so no layer can drop them. ### File editor @@ -851,3 +867,15 @@ export default function Browser({ model, parts }: ViewProps<'server.files.manage While a bundle that declares a view loads, the view shows its placeholder; mounts of one page share that decision. After five seconds, or when the import or the layer fails, the layers below render instead, and a late bundle cannot replace a view already shown. A layer that throws while rendering is reported against its package and replaced by the layer below. Core state remains outside the layer. Use local Suspense for extension-owned asynchronous rendering and `useExtensionAction` for callbacks. The testing entry exports `createViewTestHost(name, { model?, fixture?, input?, extensionId?, prefix? })`, which resolves to a `Wrapper`, the typed `props` of a layer above classic, and `dispose`, plus the model fixtures `createTestServerCard`, `createTestFileDetails`, `createTestFileEditor`, `createTestFileManager` and `createTestFileManagerEntry`. It exercises classic's layers and parts without issuing core queries; nested views read their fixtures. Pass `vi.fn()` callbacks in the model to assert on `save`, `change` or an action, and call `dispose()` after unmounting. + +## UI kit + +The SDK's components are the panel's design system: `Button`, `Input`, `Select`, `Card`, +`ListRow`, `Badge`, `Dialog`, `Table`, `Empty` and the rest of the [primitives](#primitives). +Each one takes its classes from the active theme's skin and marks its parts with `data-ui`, +`data-part` and its state (`data-color="red"`). An extension built from them looks native under +every theme, and a theme restyles it without knowing it exists. The workbench's UI kit shows each +primitive in every variant under the active theme. + +A `className` passed to a primitive is appended to its skin's classes, and a conflicting utility +replaces the skin's: ` + ))} + + ); +} diff --git a/packages/sdk/docs-samples/aurora/src/skins.ts b/packages/sdk/docs-samples/aurora/src/skins.ts new file mode 100644 index 000000000..33919cf88 --- /dev/null +++ b/packages/sdk/docs-samples/aurora/src/skins.ts @@ -0,0 +1,68 @@ +import { skin, type PrimitiveState, type ThemeSkins } from '@pterodactyl/sdk/theme'; + +// #region button +type ButtonState = PrimitiveState<'Button'>; + +const fills: Record = { + primary: 'bg-primary text-primary-foreground hover:not-disabled:bg-primary/85', + grey: 'glass text-foreground hover:not-disabled:bg-popover', + green: 'bg-success text-success-foreground hover:not-disabled:bg-success/85', + red: 'bg-destructive text-destructive-foreground hover:not-disabled:bg-destructive/85', + orange: 'bg-caution text-caution-foreground hover:not-disabled:bg-caution/85', +}; +const sizes: Record = { + xsmall: 'h-7 px-3 text-xs', + small: 'h-9 px-4 text-sm', + large: 'h-11 px-6 text-sm', + xlarge: 'h-11 w-full px-6 text-sm', +}; + +/** A pill button. Only `root` is replaced; `spinner` and `label` keep classic's recipes. */ +const button = skin('Button', { + root: ({ color, size, secondary }) => + [ + 'relative inline-flex items-center justify-center gap-2 rounded-full font-medium transition disabled:opacity-50', + sizes[size], + secondary ? 'bg-transparent text-foreground ring-1 ring-border hover:not-disabled:bg-popover' : fills[color], + ].join(' '), +}); +// #endregion button + +// #region glass +/** Frosted surfaces. Each recipe here replaces classic's for that part. */ +const glass = { + Card: skin('Card', { + root: { + base: 'glass rounded-2xl shadow-xl shadow-black/10', + variants: { titled: { false: 'p-5' }, loading: { true: 'relative' } }, + }, + header: 'flex items-center gap-3 border-b border-(--glass-border) px-5 py-3', + title: 'text-sm font-semibold text-foreground', + body: 'p-5', + }), + ListRow: skin('ListRow', { + root: { + base: 'glass flex items-center rounded-xl p-4 text-foreground no-underline', + variants: { interactive: { true: 'transition hover:-translate-y-0.5 hover:shadow-lg' } }, + }, + }), + DropdownMenu: skin('DropdownMenu', { + root: [ + 'glass min-w-56 rounded-xl p-1.5 text-sm text-popover-foreground shadow-xl outline-hidden', + 'origin-(--transform-origin) transition duration-100', + 'data-starting-style:scale-95 data-starting-style:opacity-0 data-ending-style:scale-95 data-ending-style:opacity-0', + ].join(' '), + }), + Tooltip: skin('Tooltip', { root: 'glass z-9999 rounded-md px-2.5 py-1.5 text-xs text-foreground' }), +} satisfies ThemeSkins; +// #endregion glass + +// #region extend +/** Builds on the recipes below this layer by adding classes they do not set. */ +const dialog = skin('Dialog', (below) => ({ + backdrop: (state) => `${below.backdrop(state)} backdrop-blur-sm`, + description: (state) => `${below.description(state)} text-balance`, +})); +// #endregion extend + +export const auroraSkins: ThemeSkins = { Button: button, Dialog: dialog, ...glass }; diff --git a/packages/sdk/docs-samples/aurora/src/theme-types.ts b/packages/sdk/docs-samples/aurora/src/theme-types.ts new file mode 100644 index 000000000..e63ea8c84 --- /dev/null +++ b/packages/sdk/docs-samples/aurora/src/theme-types.ts @@ -0,0 +1,20 @@ +// Generated by p:extension:types. Do not edit. +import type { ExtensionConfig as SdkExtensionConfig, ExtensionConfigValue } from '@pterodactyl/sdk'; + +export type ExtensionId = 'aurora'; +export type ExtensionScreenId = never; +export type ExtensionPermission = never; +export interface ExtensionConfig extends SdkExtensionConfig {} +// Visitors who are not signed in receive only these keys; every other key is absent for them. +export type ExtensionPublicConfigKey = never; +export type ExtensionPublicConfig = Pick; +// The theme's settings, as useThemeSettings() returns them. +export interface ThemeSettings { + readonly accent: string; + readonly sidebar: 'left' | 'right'; + readonly density: 'comfortable' | 'compact'; + readonly blur: number; + readonly logo: string | null; + readonly tagline: string; + readonly liveStats: boolean; +} diff --git a/packages/sdk/docs-samples/aurora/src/theme.css b/packages/sdk/docs-samples/aurora/src/theme.css new file mode 100644 index 000000000..39c721afc --- /dev/null +++ b/packages/sdk/docs-samples/aurora/src/theme.css @@ -0,0 +1,98 @@ +/* The panel stylesheet, every class the panel uses, then Aurora's own. Plain Tailwind: no prefix. */ +@import '@pterodactyl/sdk/theme-entry.css'; + +/* #region font */ +/* Bundled with the theme: the build copies the file beside dist/theme.css. */ +@font-face { + font-family: 'Aurora Sans'; + font-style: normal; + font-weight: 100 900; + font-display: swap; + src: url('./fonts/aurora-sans.woff2') format('woff2'); +} + +@theme { + --font-sans: 'Aurora Sans', system-ui, sans-serif; + --font-header: 'Aurora Sans', system-ui, sans-serif; +} +/* #endregion font */ + +/* #region tokens */ +/* Both schemes. The "accent" setting writes --aurora-accent; the colour roles derive from it. */ +:root { + --radius: 0.875rem; + --layout-sidebar-width: 15rem; + --primary: var(--aurora-accent, #8b5cf6); + --primary-foreground: oklch(0.985 0 0); + --ring: color-mix(in oklab, var(--primary) 60%, transparent); + --accent: color-mix(in oklab, var(--primary) 65%, white); + --accent-foreground: oklch(0.2 0.02 280); + --selection: color-mix(in oklab, var(--primary) 35%, transparent); + --glass: color-mix(in oklab, var(--card) 60%, transparent); + --glass-border: color-mix(in oklab, var(--foreground) 12%, transparent); +} + +.dark { + --background: oklch(0.17 0.02 280); + --foreground: oklch(0.94 0.01 280); + --card: oklch(0.23 0.025 280); + --card-foreground: var(--foreground); + --popover: oklch(0.27 0.03 280); + --popover-foreground: var(--foreground); + --muted: oklch(0.25 0.02 280); + --muted-foreground: oklch(0.7 0.02 280); + --secondary: oklch(0.3 0.03 280); + --border: oklch(0.32 0.03 280); + --terminal-background: oklch(0.13 0.02 280); +} + +.light { + --background: oklch(0.97 0.01 280); + --foreground: oklch(0.22 0.03 280); + --card: oklch(1 0 0); + --card-foreground: var(--foreground); + --popover: oklch(0.99 0.005 280); + --popover-foreground: var(--foreground); + --muted: oklch(0.94 0.01 280); + --muted-foreground: oklch(0.5 0.02 280); + --secondary: oklch(0.92 0.015 280); + --border: oklch(0.88 0.015 280); + --terminal-background: oklch(0.2 0.02 280); + --terminal-foreground: oklch(0.92 0.01 280); +} +/* #endregion tokens */ + +/* #region settings */ +/* `sidebar-right:` applies while the "sidebar" setting is "right". */ +@custom-variant sidebar-right (&:where([data-aurora-sidebar='right'] *)); + +/* The "density" setting retunes the spacing scale every utility reads. */ +[data-aurora-density='compact'] { + --spacing: 0.2rem; +} +/* #endregion settings */ + +/* #region glass */ +/* A frosted surface for skins and views: `glass`. The "blur" setting writes --aurora-blur. */ +@utility glass { + background-color: var(--glass); + border: 1px solid var(--glass-border); + backdrop-filter: blur(var(--aurora-blur, 16px)) saturate(1.4); +} + +@layer base { + body { + background: + radial-gradient(60rem 40rem at 10% -10%, color-mix(in oklab, var(--primary) 22%, transparent), transparent), + radial-gradient(50rem 30rem at 110% 0%, color-mix(in oklab, var(--accent) 16%, transparent), transparent), + var(--background); + background-attachment: fixed; + } +} + +@media (prefers-reduced-transparency: reduce) { + :root { + --glass: var(--card); + } +} +/* #endregion glass */ diff --git a/packages/sdk/docs-samples/aurora/src/theme.spec.tsx b/packages/sdk/docs-samples/aurora/src/theme.spec.tsx new file mode 100644 index 000000000..7ee34fbde --- /dev/null +++ b/packages/sdk/docs-samples/aurora/src/theme.spec.tsx @@ -0,0 +1,52 @@ +import { afterEach, beforeAll, expect, test } from 'vitest'; +import { screen } from '@testing-library/react'; +import { preloadTheme, renderPrimitive, renderView, type RenderedView } from '@pterodactyl/sdk/testing'; +import theme from './theme'; + +let rendered: RenderedView | undefined; + +// Aurora's views are lazy; loading their chunks first lets renderView render them synchronously. +beforeAll(() => preloadTheme(theme)); +afterEach(() => rendered?.unmount()); + +// #region tests +test('lays the dashboard out as cards with power buttons beside their links', () => { + rendered = renderView('dashboard.serverList', { theme, fixture: 'servers' }); + + const survival = screen.getByRole('link', { name: 'Survival' }); + + expect(survival.getAttribute('href')).toBe('/server/a1b2c3d4'); + expect(survival.closest('li')?.textContent).toContain('Restart'); + expect(screen.getByRole('link', { name: 'Creative' }).closest('li')?.textContent).toContain('Start'); +}); + +test('puts the power controls in the server header and asks before a kill', () => { + rendered = renderView('layout.server', { theme, fixture: 'owner' }); + + const header = screen.getByRole('heading', { name: 'Survival' }).closest('header'); + + expect(header?.textContent).toContain('Restart'); + + rendered = renderView('server.power', { theme, fixture: 'stopping' }); + expect(screen.getByRole('button', { name: 'Kill' }).hasAttribute('disabled')).toBe(false); +}); + +test('keeps the engine field attributes on the sign-in form', () => { + rendered = renderView('auth.loginForm', { theme, fixture: 'invalid' }); + + const password = screen.getByLabelText('Password'); + + expect(password.getAttribute('autocomplete')).toBe('current-password'); + expect(password.getAttribute('aria-invalid')).toBe('true'); + expect(screen.getByText('Please enter your account password.')).not.toBeNull(); +}); + +test('draws buttons as pills and keeps their state attributes', () => { + rendered = renderPrimitive('Button', { children: 'Save', color: 'red' }, { theme }); + + const button = rendered.container.querySelector('button'); + + expect(button?.className).toContain('rounded-full'); + expect(button?.dataset).toMatchObject({ ui: 'button', part: 'root', color: 'red', size: 'small' }); +}); +// #endregion tests diff --git a/packages/sdk/docs-samples/aurora/src/theme.tsx b/packages/sdk/docs-samples/aurora/src/theme.tsx new file mode 100644 index 000000000..462569051 --- /dev/null +++ b/packages/sdk/docs-samples/aurora/src/theme.tsx @@ -0,0 +1,23 @@ +import { Boxes } from 'lucide-react'; +import { defineTheme, lazyView } from '@pterodactyl/sdk/theme'; +import { auroraSkins } from './skins'; +import AuthLayout from './views/AuthLayout'; + +export default defineTheme({ + ui: auroraSkins, + views: { + // The sign-in screen renders without waiting for a chunk. + 'layout.auth': AuthLayout, + 'auth.loginForm': lazyView(() => import('./views/LoginForm')), + 'layout.app': lazyView(() => import('./views/AppShell')), + 'layout.server': lazyView(() => import('./views/ServerLayout')), + 'server.power': lazyView(() => import('./views/Power')), + 'page.server.console': lazyView(() => import('./views/ConsolePage')), + 'server.terminal': lazyView(() => import('./views/Terminal')), + 'server.stats': lazyView(() => import('./views/Stats')), + 'dashboard.serverList': lazyView(() => import('./views/ServerGrid')), + 'dashboard.serverCard': lazyView(() => import('./views/ServerCard')), + }, + // Every draws this in place of lucide's, such as a navigation item naming it. + icons: { server: Boxes }, +}); diff --git a/packages/sdk/docs-samples/aurora/src/views/AppShell.tsx b/packages/sdk/docs-samples/aurora/src/views/AppShell.tsx new file mode 100644 index 000000000..72967cb95 --- /dev/null +++ b/packages/sdk/docs-samples/aurora/src/views/AppShell.tsx @@ -0,0 +1,65 @@ +import { LayoutGrid, LogOut, Shield, UserRound, type LucideIcon } from 'lucide-react'; +import { Avatar, PanelLink, SpinnerOverlay, Tooltip, cn } from '@pterodactyl/sdk'; +import { Main, Slot, View, type AppLayoutLink, type AppLayoutModel, type ViewProps } from '@pterodactyl/sdk/theme'; +import SchemeSwitch from '../SchemeSwitch'; + +const icons: Record = { dashboard: LayoutGrid, admin: Shield, account: UserRound }; + +const linkClass = cn( + 'flex items-center gap-3 rounded-lg px-3 py-2 text-sm text-muted-foreground no-underline transition', + 'hover:bg-popover hover:text-foreground data-[status=active]:bg-primary/15 data-[status=active]:text-foreground' +); + +function Brand({ brand }: { brand: AppLayoutModel['brand'] }) { + return ( + + {brand.logoUrl ? {brand.name} : brand.name} + + ); +} + +function Links({ model }: { model: AppLayoutModel }) { + return ( + <> + + {model.links.map((link) => { + const Glyph = icons[link.id]; + + return ( + + + {link.label} + + ); + })} + + + ); +} + +/** A sidebar on large screens and a top bar below them; the "sidebar" setting picks the side. */ +export default function AppShell({ model, children }: ViewProps<'layout.app'>) { + return ( +
+ + +
{children}
+
+ ); +} diff --git a/packages/sdk/docs-samples/aurora/src/views/AuthLayout.tsx b/packages/sdk/docs-samples/aurora/src/views/AuthLayout.tsx new file mode 100644 index 000000000..ed795f1ca --- /dev/null +++ b/packages/sdk/docs-samples/aurora/src/views/AuthLayout.tsx @@ -0,0 +1,32 @@ +import { Main, useThemeSettings, type ViewProps } from '@pterodactyl/sdk/theme'; +import type { ThemeSettings } from '../theme-types'; +import SchemeSwitch from '../SchemeSwitch'; + +/** + * A split screen: the brand on one side, the sign-in pages on the other. It imports nothing from + * `@pterodactyl/sdk`, so the sign-in screen renders without loading the full SDK first. + */ +export default function AuthLayout({ model, children }: ViewProps<'layout.auth'>) { + const { tagline } = useThemeSettings(); + + return ( +
+
+ {model.brand.logoUrl ? ( + {model.brand.name} + ) : ( +

{model.brand.name}

+ )} +

{tagline}

+
+
+
+ +
+
+
{children}
+
+
+
+ ); +} diff --git a/packages/sdk/docs-samples/aurora/src/views/ConsolePage.tsx b/packages/sdk/docs-samples/aurora/src/views/ConsolePage.tsx new file mode 100644 index 000000000..5e9ecbf93 --- /dev/null +++ b/packages/sdk/docs-samples/aurora/src/views/ConsolePage.tsx @@ -0,0 +1,34 @@ +import { Alert, ServerContentBlock } from '@pterodactyl/sdk'; +import { Slot, View, type ServerConsoleModel, type ViewProps } from '@pterodactyl/sdk/theme'; + +const notices: Record, string> = { + maintenance: 'This node is under maintenance, so the server cannot be controlled.', + installing: 'The server is installing; most actions wait until it finishes.', + transferring: 'The server is moving to another node.', +}; + +/** + * The console without its power controls, which the server layout shows in its header. The page stays + * mounted while another server page shows, so it only titles the document while `active`. + */ +export default function ConsolePage({ model, active }: ViewProps<'page.server.console'>) { + return ( + + {model.notice && ( + + {notices[model.notice]} + + )} + +
+ + +
+
+ +
+ + +
+ ); +} diff --git a/packages/sdk/docs-samples/aurora/src/views/LoginForm.tsx b/packages/sdk/docs-samples/aurora/src/views/LoginForm.tsx new file mode 100644 index 000000000..1610e7fe0 --- /dev/null +++ b/packages/sdk/docs-samples/aurora/src/views/LoginForm.tsx @@ -0,0 +1,55 @@ +import { useId, type FormEvent } from 'react'; +import { Button, Input, Label, PanelLink, type FieldModel } from '@pterodactyl/sdk'; +import { Slot, type ViewProps } from '@pterodactyl/sdk/theme'; + +/** + * Spreads the engine's `fieldProps` (name, type, autocomplete, value and handlers) onto each input, + * so password managers, validation and the disabled state while signing in keep working. + */ +function Field({ field, label }: { field: FieldModel; label: string }) { + const id = useId(); + + return ( +
+ + + {field.error && ( +

+ {field.error} +

+ )} +
+ ); +} + +/** The engine owns the request, the CSRF cookie, the captcha, two-factor and the redirect. */ +export default function LoginForm({ model }: ViewProps<'auth.loginForm'>) { + const { fields, Captcha } = model; + const submit = (event: FormEvent) => { + event.preventDefault(); + model.submit(); + }; + + return ( +
+

Sign in

+ + + {/* A panel with reCAPTCHA turned on cannot sign anyone in without it. */} + {Captcha && } + + + + Forgot your password? + + + ); +} diff --git a/packages/sdk/docs-samples/aurora/src/views/Power.tsx b/packages/sdk/docs-samples/aurora/src/views/Power.tsx new file mode 100644 index 000000000..7bcffed11 --- /dev/null +++ b/packages/sdk/docs-samples/aurora/src/views/Power.tsx @@ -0,0 +1,50 @@ +import { Play, RotateCcw, Square, Zap } from 'lucide-react'; +import { Button, Dialog } from '@pterodactyl/sdk'; +import { Slot, type ViewProps } from '@pterodactyl/sdk/theme'; + +/** + * Compact power controls. The model says what the user may do and what the server allows right now; + * stopping a server that is already stopping kills it, so that asks first. + */ +export default function Power({ model }: ViewProps<'server.power'>) { + const { permissions, enabled, actions } = model; + + return ( +
+ + {permissions.start && ( + + )} + {permissions.restart && ( + + )} + {permissions.stop && + (model.killable ? ( + ( + + )} + onConfirmed={(_event, close) => { + close(); + actions.kill(); + }} + > + Killing a server can corrupt its data. + + ) : ( + + ))} + +
+ ); +} diff --git a/packages/sdk/docs-samples/aurora/src/views/ServerCard.tsx b/packages/sdk/docs-samples/aurora/src/views/ServerCard.tsx new file mode 100644 index 000000000..e92f2368b --- /dev/null +++ b/packages/sdk/docs-samples/aurora/src/views/ServerCard.tsx @@ -0,0 +1,46 @@ +import { Badge, ProgressBar, Spinner, bytesToString } from '@pterodactyl/sdk'; +import { Slot, useThemeSettings, type ServerCardMetric, type ViewProps } from '@pterodactyl/sdk/theme'; +import type { ThemeSettings } from '../theme-types'; + +const percent = ({ value, limit }: ServerCardMetric) => (limit > 0 ? Math.min((value / limit) * 100, 100) : null); + +/** A server's name and address, with its usage as the panel polls it (every 20 seconds at most). */ +export default function ServerCard({ model, server }: ViewProps<'dashboard.serverCard'>) { + const { liveStats } = useThemeSettings(); + const { state } = model; + + return ( +
+
+
+

{model.name}

+

{model.address ?? 'No address'}

+
+ + {state.kind === 'ready' && ( + + {state.power} + + )} + {state.kind === 'unavailable' && {state.reason.replace('-', ' ')}} +
+ {state.kind === 'loading' && } + {liveStats && state.kind === 'ready' && ( +
+
+ CPU {state.cpu.value.toFixed(0)}% + +
+
+ {bytesToString(state.memory.value)} + +
+
+ {bytesToString(state.disk.value)} + +
+
+ )} +
+ ); +} diff --git a/packages/sdk/docs-samples/aurora/src/views/ServerGrid.tsx b/packages/sdk/docs-samples/aurora/src/views/ServerGrid.tsx new file mode 100644 index 000000000..4b13a8274 --- /dev/null +++ b/packages/sdk/docs-samples/aurora/src/views/ServerGrid.tsx @@ -0,0 +1,133 @@ +import { Play, RotateCcw, Server as ServerIcon, Square } from 'lucide-react'; +import { + Button, + Empty, + EmptyDescription, + EmptyHeader, + EmptyMedia, + EmptyTitle, + PageHeading, + PanelLink, + Spinner, + Switch, + useSendServerPower, + type SdkPowerSignal, +} from '@pterodactyl/sdk'; +import { Slot, View, type ServerListItem, type ServerListModel, type ViewProps } from '@pterodactyl/sdk/theme'; + +/** + * Sends a signal through the client API, so it works without a console connection. The panel checks + * the user's control permissions and shows its own notice when the request fails. + */ +function PowerButtons({ item }: { item: ServerListItem }) { + const power = useSendServerPower(item.server.attributes.uuid); + const send = (signal: SdkPowerSignal) => () => void power.mutateAsync({ signal }).catch(() => {}); + const running = item.power !== null && item.power !== 'offline'; + + return ( +
+ {running ? ( + <> + + + + ) : ( + + )} +
+ ); +} + +function Tile({ item }: { item: ServerListItem }) { + const { server } = item; + + return ( +
  • + + + + + + + +
  • + ); +} + +function Pager({ model }: { model: ServerListModel }) { + const { pagination, actions } = model; + + if (!pagination || pagination.totalPages < 2) { + return null; + } + + return ( + + ); +} + +/** The dashboard's servers as a grid of cards, each with power buttons outside its link. */ +export default function ServerGrid({ model }: ViewProps<'dashboard.serverList'>) { + const others = model.scope === 'others'; + + return ( + <> + model.actions.setScope(others ? 'mine' : 'others')} + label="Show other users' servers" + controlPosition='end' + /> + ) + } + /> + + {model.loading && } + {!model.loading && model.servers.length === 0 && ( + + + + + + No servers yet + Servers you own or are invited to show up here. + + + )} +
      + {model.servers.map((item) => ( + + ))} +
    + + + + ); +} diff --git a/packages/sdk/docs-samples/aurora/src/views/ServerLayout.tsx b/packages/sdk/docs-samples/aurora/src/views/ServerLayout.tsx new file mode 100644 index 000000000..2847a6d91 --- /dev/null +++ b/packages/sdk/docs-samples/aurora/src/views/ServerLayout.tsx @@ -0,0 +1,37 @@ +import { NamedIcon, cn } from '@pterodactyl/sdk'; +import { Main, Navigation, NavigationLink, Slot, View, type ViewProps } from '@pterodactyl/sdk/theme'; + +const tabClass = + 'flex shrink-0 items-center gap-2 rounded-full px-3 py-1.5 text-sm text-muted-foreground no-underline hover:text-foreground'; + +/** The server's name with its power controls in the header, then its pages as tabs. */ +export default function ServerLayout({ model, children }: ViewProps<'layout.server'>) { + const items = model.adminLink ? [...model.nav.items, model.adminLink] : model.nav.items; + + return ( +
    +
    +
    +

    {model.name}

    +

    {model.identifier}

    +
    + {/* Power controls make no sense while the server installs, transfers or restores. */} + {model.conflict === null && } +
    + +
    {children}
    +
    + ); +} diff --git a/packages/sdk/docs-samples/aurora/src/views/Stats.tsx b/packages/sdk/docs-samples/aurora/src/views/Stats.tsx new file mode 100644 index 000000000..90ae9e749 --- /dev/null +++ b/packages/sdk/docs-samples/aurora/src/views/Stats.tsx @@ -0,0 +1,40 @@ +import { Badge, Card, ProgressBar, bytesToString } from '@pterodactyl/sdk'; +import type { ServerStatMetric, UiTone, ViewProps } from '@pterodactyl/sdk/theme'; + +const tones: Record, UiTone> = { warning: 'warning', critical: 'danger' }; + +/** A limit of 0 is unlimited, which has no percentage to show. */ +const percent = ({ value, limit }: ServerStatMetric) => (limit > 0 ? Math.min((value / limit) * 100, 100) : null); + +function Meter({ label, metric, format }: { label: string; metric: ServerStatMetric; format: (value: number) => string }) { + return ( +
    +
    + {label} + + {format(metric.value)} + {metric.limit > 0 && / {format(metric.limit)}} + +
    + +
    + ); +} + +/** Live values from the server's websocket; they update several times a second while it runs. */ +export default function Stats({ model }: ViewProps<'server.stats'>) { + return ( + {model.state ?? 'unknown'}}> +
    + `${value.toFixed(1)}%`} /> + + +

    {model.address ?? 'No allocation'}

    +
    +
    + ); +} diff --git a/packages/sdk/docs-samples/aurora/src/views/Terminal.tsx b/packages/sdk/docs-samples/aurora/src/views/Terminal.tsx new file mode 100644 index 000000000..b44521ff3 --- /dev/null +++ b/packages/sdk/docs-samples/aurora/src/views/Terminal.tsx @@ -0,0 +1,58 @@ +import type { KeyboardEvent } from 'react'; +import { Button, Spinner } from '@pterodactyl/sdk'; +import type { ServerConsoleCommand, ViewProps } from '@pterodactyl/sdk/theme'; + +function onKey(command: ServerConsoleCommand, event: KeyboardEvent) { + if (event.key === 'Enter') { + command.submit(); + } else if (event.key === 'ArrowUp') { + event.preventDefault(); + command.previous(); + } else if (event.key === 'ArrowDown') { + command.next(); + } +} + +/** The engine draws the output on `model.Terminal`; the theme sizes it and owns the command line. */ +export default function Terminal({ model }: ViewProps<'server.terminal'>) { + const { command } = model; + + return ( +
    +
    + + {model.loading && ( +
    + +
    + )} + {model.failed && ( +
    + The console could not be loaded. + +
    + )} + {model.scrolledUp && ( + + )} +
    + {command.allowed && ( + command.setValue(event.currentTarget.value)} + onKeyDown={(event) => onKey(command, event)} + className='border-0 border-t border-(--glass-border) bg-transparent px-4 py-3 font-mono text-sm focus:ring-0' + /> + )} +
    + ); +} diff --git a/packages/sdk/docs-samples/aurora/vite.config.mjs b/packages/sdk/docs-samples/aurora/vite.config.mjs new file mode 100644 index 000000000..ebc715b64 --- /dev/null +++ b/packages/sdk/docs-samples/aurora/vite.config.mjs @@ -0,0 +1,3 @@ +import { defineThemeConfig } from '@pterodactyl/sdk/vite'; + +export default defineThemeConfig({ entry: 'src/theme.tsx', stylesheet: 'src/theme.css' }); diff --git a/packages/sdk/docs-samples/child-theme/extension.json b/packages/sdk/docs-samples/child-theme/extension.json new file mode 100644 index 000000000..acf68cb6b --- /dev/null +++ b/packages/sdk/docs-samples/child-theme/extension.json @@ -0,0 +1,14 @@ +{ + "id": "aurora-sunset", + "type": "theme", + "name": "Aurora Sunset", + "version": "1.0.0", + "requires": { "panel": "^2.0.0-dev", "sdk": ">=2.0.0-beta.5 <3.0", "extensions": { "aurora": "^1.0" } }, + "ui": { "entry": "dist/client.js" }, + "theme": { + "extends": "aurora", + "settings": { + "accent": { "type": "color", "label": "Accent", "default": "#f97316", "token": "--aurora-accent" } + } + } +} diff --git a/packages/sdk/docs-samples/child-theme/src/theme.tsx b/packages/sdk/docs-samples/child-theme/src/theme.tsx new file mode 100644 index 000000000..5ee83991a --- /dev/null +++ b/packages/sdk/docs-samples/child-theme/src/theme.tsx @@ -0,0 +1,12 @@ +import { defineTheme, type ViewProps } from '@pterodactyl/sdk/theme'; + +/** Aurora's server card is the layer below, so `Default` renders it. */ +function SunsetCard({ Default }: ViewProps<'dashboard.serverCard'>) { + return ( +
    + +
    + ); +} + +export default defineTheme({ views: { 'dashboard.serverCard': SunsetCard } }); diff --git a/packages/sdk/docs-samples/snippets/FileDetails.tsx b/packages/sdk/docs-samples/snippets/FileDetails.tsx new file mode 100644 index 000000000..817c7a670 --- /dev/null +++ b/packages/sdk/docs-samples/snippets/FileDetails.tsx @@ -0,0 +1,6 @@ +import type { ViewProps } from '@pterodactyl/sdk'; + +/** Loaded with the file browser, which shows the view's placeholder until the chunk has loaded. */ +export default function FileDetails({ model, Default }: ViewProps<'server.files.details'>) { + return model.kind === 'archive' ? : ; +} diff --git a/packages/sdk/docs-samples/snippets/extension.tsx b/packages/sdk/docs-samples/snippets/extension.tsx new file mode 100644 index 000000000..0b9500e0c --- /dev/null +++ b/packages/sdk/docs-samples/snippets/extension.tsx @@ -0,0 +1,60 @@ +import { + Badge, + Button, + Card, + definePterodactylExtension, + type ExtensionViewProps, + type ViewProps, +} from '@pterodactyl/sdk'; +import { View } from '@pterodactyl/sdk/theme'; + +// #region override +/** A layer over the server card: it keeps the layers below and adds a note. */ +function ServerCard({ Default, model }: ViewProps<'dashboard.serverCard'>) { + return ( + <> + + {model.state.kind === 'unavailable' &&

    Ask support about {model.name}.

    } + + ); +} +// #endregion override + +// #region define +interface BalanceModel { + readonly credits: number; + readonly topUp: () => void; +} + +function useBalance(): BalanceModel { + return { credits: 120, topUp: () => window.open('/billing', '_self') }; +} + +/** The bottom layer of the extension's own view; themes restyle or move it. Built from the UI kit, it takes their skins. */ +function Balance({ model, className }: ExtensionViewProps) { + return ( + {model.credits} credits}> + + + ); +} +// #endregion define + +export default definePterodactylExtension({ + setup({ views, slots }) { + // #region setup + views.override('dashboard.serverCard', ServerCard); + views.override('server.files.details', { load: () => import('./FileDetails') }); + views.define('billing.balance', { + context: 'app', + use: useBalance, + Default: Balance, + fixtures: { funded: () => ({ credits: 120, topUp: () => {} }), empty: () => ({ credits: 0, topUp: () => {} }) }, + }); + // Wherever classic has no place for it yet, a slot places the view. + slots.register('dashboard.after', () => ); + // #endregion setup + }, +}); diff --git a/packages/sdk/docs-samples/snippets/navigation.tsx b/packages/sdk/docs-samples/snippets/navigation.tsx new file mode 100644 index 000000000..a2eb3f584 --- /dev/null +++ b/packages/sdk/docs-samples/snippets/navigation.tsx @@ -0,0 +1,59 @@ +import { NamedIcon, cn } from '@pterodactyl/sdk'; +import { + Main, + Navigation, + NavigationLink, + Slot, + useActiveNavItem, + useNavigation, + type ViewProps, +} from '@pterodactyl/sdk/theme'; + +// #region account +/** The account pages with a vertical menu. `model.nav` lists them, extension screens included. */ +export function AccountLayout({ model, children }: ViewProps<'layout.account'>) { + const current = useActiveNavItem(model.nav.items); + + return ( +
    + +
    +

    {current?.label}

    + {children} +
    +
    + ); +} +// #endregion account + +// #region anywhere +/** The account links anywhere: `useNavigation` reads an area's live navigation. */ +export function AccountShortcuts() { + const { items } = useNavigation('account'); + + return ( +
      + {items.map((item) => ( +
    • + {item.label} +
    • + ))} +
    + ); +} +// #endregion anywhere diff --git a/packages/sdk/docs-samples/snippets/skins.tsx b/packages/sdk/docs-samples/snippets/skins.tsx new file mode 100644 index 000000000..a035099b0 --- /dev/null +++ b/packages/sdk/docs-samples/snippets/skins.tsx @@ -0,0 +1,51 @@ +import type { ReactNode } from 'react'; +import { defineTheme, skin, useSkin, type PrimitiveProps } from '@pterodactyl/sdk/theme'; + +// #region recipe +/** A class-variance-authority recipe: variant keys are the primitive's state, `true`/`false` for booleans. */ +const badge = skin('Badge', { + root: { + base: 'inline-flex items-center gap-1 rounded-full font-medium', + variants: { + size: { sm: 'px-2 text-[0.6875rem]', md: 'px-2.5 py-0.5 text-xs' }, + variant: { solid: 'text-white', soft: 'bg-transparent ring-1 ring-inset' }, + }, + compoundVariants: [ + { variant: 'solid', tone: ['success', 'info'], class: 'bg-success' }, + { variant: 'solid', tone: ['danger', 'warning'], class: 'bg-destructive' }, + { variant: 'solid', tone: ['neutral', 'accent'], class: 'bg-primary' }, + { variant: 'soft', tone: 'danger', class: 'text-destructive ring-destructive/40' }, + ], + defaultVariants: { size: 'md' }, + }, +}); +// #endregion recipe + +// #region component +/** A presentational primitive can be replaced by a component that takes the same props. */ +function Banner({ type, title, className, children }: PrimitiveProps<'Alert'>) { + return ( +
    + {title &&

    {title}

    } + {children} +
    + ); +} +// #endregion component + +// #region use-skin +/** A theme's own element styled with the active skin of a primitive, attributes included. */ +function ButtonLikeLink({ href, children }: { href: string; children: ReactNode }) { + const ui = useSkin('Button', { color: 'primary', size: 'small', secondary: true, loading: false }); + + return ( + + {children} + + ); +} +// #endregion use-skin + +export default defineTheme({ ui: { Badge: badge, Alert: Banner } }); + +export { ButtonLikeLink }; diff --git a/packages/sdk/docs-samples/snippets/views.tsx b/packages/sdk/docs-samples/snippets/views.tsx new file mode 100644 index 000000000..ab0a95edc --- /dev/null +++ b/packages/sdk/docs-samples/snippets/views.tsx @@ -0,0 +1,75 @@ +import { PageContentBlock } from '@pterodactyl/sdk'; +import { defineTheme, Slot, View, type ViewPartProps, type ViewProps } from '@pterodactyl/sdk/theme'; + +// #region wrap +/** Keeps the layer below and frames it. */ +function FramedCard({ Default }: ViewProps<'dashboard.serverCard'>) { + return ( +
    + +
    + ); +} +// #endregion wrap + +// #region transform +/** Hands the layer below another model and an extra class. */ +function LoudCard({ model, Default }: ViewProps<'dashboard.serverCard'>) { + return ; +} +// #endregion transform + +// #region parts +/** Replaces one part of classic's card and keeps the others. */ +function Uptime({ model }: ViewPartProps<'dashboard.serverCard'>) { + return {model.state.kind === 'ready' ? model.state.power : 'unknown'}; +} + +function CardWithUptime({ Default }: ViewProps<'dashboard.serverCard'>) { + return ; +} +// #endregion parts + +// #region compose +/** A page is a composition of blocks: this one lays classic's account cards out in two columns. */ +function AccountOverview({ model }: ViewProps<'page.account.overview'>) { + return ( + + {model.twoFactorRequired &&

    Turn on two-factor authentication to continue.

    } + +
    + + + +
    + +
    + ); +} +// #endregion compose + +// #region optional +/** Places a block a billing extension defines; nothing renders while that extension is not installed. */ +function SidebarFooter() { + return ; +} + +/** Restyles that block. Its model is `unknown` here: the theme does not know the extension's types. */ +function Balance({ Default }: ViewProps<'billing.balance'>) { + return ( +
    + +
    + ); +} +// #endregion optional + +export default defineTheme({ + views: { + 'dashboard.serverCard': FramedCard, + 'page.account.overview': AccountOverview, + 'billing.balance': Balance, + }, +}); + +export { CardWithUptime, LoudCard, SidebarFooter }; diff --git a/packages/sdk/docs-samples/tsconfig.json b/packages/sdk/docs-samples/tsconfig.json index 6c152a2ea..fad1f1cb1 100644 --- a/packages/sdk/docs-samples/tsconfig.json +++ b/packages/sdk/docs-samples/tsconfig.json @@ -1,7 +1,18 @@ { - "compilerOptions": { - "target": "ES2022", "module": "ESNext", "moduleResolution": "bundler", "jsx": "react-jsx", - "lib": ["ES2022", "DOM", "DOM.Iterable"], "types": [], "strict": true, "noEmit": true, "skipLibCheck": true - }, - "include": ["**/*.ts", "**/*.tsx"] + // The README's code samples. `npm run sdk:check` compiles them against the SDK's published types, + // which "@pterodactyl/sdk" resolves to from inside this package. + "compilerOptions": { + "target": "ES2022", + "module": "ESNext", + "moduleResolution": "bundler", + "jsx": "react-jsx", + "lib": ["ES2022", "DOM", "DOM.Iterable"], + "types": [], + "strict": true, + "noEmit": true, + "skipLibCheck": true, + "isolatedModules": true + }, + "include": ["**/*.ts", "**/*.tsx"], + "exclude": ["vitest.config.ts"] } diff --git a/packages/sdk/docs-samples/vitest.config.ts b/packages/sdk/docs-samples/vitest.config.ts new file mode 100644 index 000000000..5e9a35e28 --- /dev/null +++ b/packages/sdk/docs-samples/vitest.config.ts @@ -0,0 +1,15 @@ +import { defineConfig } from 'vitest/config'; +import { fileURLToPath } from 'node:url'; +import { pterodactylTestAliases, pterodactylTestSetup } from '../vitest.mjs'; + +// Runs the README's sample theme tests against the SDK test runtime, as a theme's own vitest.config does. +export default defineConfig({ + root: fileURLToPath(new URL('.', import.meta.url)), + resolve: { alias: pterodactylTestAliases() }, + test: { + name: 'docs-samples', + environment: 'jsdom', + setupFiles: [pterodactylTestSetup], + include: ['**/*.spec.{ts,tsx}'], + }, +}); diff --git a/packages/sdk/types/components/elements/Portal.d.ts b/packages/sdk/types/components/elements/Portal.d.ts index 671ffde11..53307172d 100644 --- a/packages/sdk/types/components/elements/Portal.d.ts +++ b/packages/sdk/types/components/elements/Portal.d.ts @@ -1,5 +1,11 @@ // Generated by scripts/generate-sdk-types.mjs. Do not edit. -import type React from 'react'; +import React from 'react'; +/** Where overlays render instead of the page's own portal; a workbench preview sets the body of its frame. */ +export declare const PortalContainerContext: React.Context; +/** The element overlays portal into, or undefined for the default (the document body). */ +export declare function usePortalContainer(): HTMLElement | undefined; +/** The document the content renders into: a preview frame's, or the page's. */ +export declare function useOwnerDocument(): Document; export default function Portal({ children }: { children: React.ReactNode; }): React.ReactPortal; diff --git a/packages/sdk/types/sdk/testing.d.ts b/packages/sdk/types/sdk/testing.d.ts index 6f2630150..cd90b36fd 100644 --- a/packages/sdk/types/sdk/testing.d.ts +++ b/packages/sdk/types/sdk/testing.d.ts @@ -91,9 +91,12 @@ export interface RenderedView { container: HTMLElement; unmount(): void; } +/** Loads the chunks of a theme's `lazyView` views, which `renderView` renders synchronously. */ +export declare function preloadTheme(theme: ThemeDefinition): Promise; /** * 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. + * replaces what was rendered before it; nested views read their fixtures too. Await `preloadTheme(theme)` + * first when the theme has lazy views. */ export declare function renderView(name: N, options?: RenderViewOptions): RenderedView; export interface RenderPrimitiveOptions { diff --git a/packages/sdk/types/themes/gallery.d.ts b/packages/sdk/types/themes/gallery.d.ts index d143bc3f0..fd650a5da 100644 --- a/packages/sdk/types/themes/gallery.d.ts +++ b/packages/sdk/types/themes/gallery.d.ts @@ -1,6 +1,6 @@ // Generated by scripts/generate-sdk-types.mjs. Do not edit. -import type { ComponentProps, JSXElementConstructor, ReactElement } from 'react'; -import { Alert, Avatar, Button, Checkbox, ContentBox, CopyOnClick, DropdownMenu, Empty, Input, Label, NumberInput, PageHeading, Pagination, Select, Spinner, Switch, Table, TextArea, TitledGreyBox, Tooltip } from "../sdk/index.js"; +import { type ComponentProps, type JSXElementConstructor, type ReactElement } from 'react'; +import { Alert, Avatar, Badge, Button, Card, Checkbox, Code, ContentBox, CopyOnClick, Dialog, DropdownMenu, Empty, FileInput, Input, Label, ListRow, NewButton, NumberInput, PageHeading, Pagination, ProgressBar, Select, Spinner, SpinnerOverlay, Switch, Table, TextArea, TitledGreyBox, Tooltip } from "../sdk/index.js"; export interface UiPrimitive = JSXElementConstructor> { readonly component: C; /** Rendered by the workbench's UI kit, by variant; the first is the default. */ @@ -9,25 +9,34 @@ 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; } /** * Every UI kit primitive with sample renders: the workbench's gallery and `renderPrimitive` read diff --git a/resources/scripts/sdk/testing.spec.tsx b/resources/scripts/sdk/testing.spec.tsx index 8052452ab..005552df3 100644 --- a/resources/scripts/sdk/testing.spec.tsx +++ b/resources/scripts/sdk/testing.spec.tsx @@ -1,9 +1,11 @@ /** @vitest-environment jsdom */ import { cleanup, fireEvent, render, screen } from '@testing-library/react'; import { afterEach, expect, it, vi } from 'vitest'; +import { lazyView } from '@/views/lazy'; import type { ViewPartProps, ViewProps } from '@/views/registry'; import { defineTheme } from '@/views/theme'; import { + preloadTheme, renderPrimitive, renderView, createTestFileEditor, @@ -152,6 +154,27 @@ it('renders a view synchronously from fixtures with a theme layered over classic expect(container.isConnected).toBe(false); }); +it('renders the lazy views of a theme once they are preloaded', async () => { + const theme = defineTheme({ + views: { + 'page.dashboard': lazyView(async () => ({ + default: ({ model }: ViewProps<'page.dashboard'>) =>

    {`lazy dashboard ${model.error ?? 'ok'}`}

    , + })), + }, + }); + + expect(() => renderView('page.dashboard', { theme })).toThrow( + "The theme's views page.dashboard are lazy and not loaded yet." + ); + + await preloadTheme(theme); + + const { container, unmount } = renderView('page.dashboard', { theme, fixture: 'error' }); + + expect(container).toHaveTextContent('lazy dashboard Request failed with status code 500.'); + unmount(); +}); + 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({}) }); diff --git a/resources/scripts/sdk/testing.tsx b/resources/scripts/sdk/testing.tsx index 00fab35af..3cb0f8428 100644 --- a/resources/scripts/sdk/testing.tsx +++ b/resources/scripts/sdk/testing.tsx @@ -31,6 +31,7 @@ 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 { isPendingLazyView } from '@/views/lazy'; import { createViewHarness, LooseView, preloadView, ViewFixtureProvider } from '@/views/View'; import { act, @@ -389,11 +390,31 @@ function mount(content: ReactNode, theme: ThemeDefinition | undefined): Rendered return rendered; } +const pendingViews = (theme: ThemeDefinition | undefined): string[] => + Object.entries(theme?.views ?? {}).flatMap(([name, view]) => (view && isPendingLazyView(view) ? [name] : [])); + +/** Loads the chunks of a theme's `lazyView` views, which `renderView` renders synchronously. */ +export async function preloadTheme(theme: ThemeDefinition): Promise { + await Promise.all( + Object.values(theme.views ?? {}).map((view) => (view && isPendingLazyView(view) ? view.preload() : null)) + ); +} + /** * 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. + * replaces what was rendered before it; nested views read their fixtures too. Await `preloadTheme(theme)` + * first when the theme has lazy views. */ export function renderView(name: N, options: RenderViewOptions = {}): RenderedView { + const pending = pendingViews(options.theme); + + if (pending.length) { + throw new Error( + `The theme's views ${pending.join(', ')} are lazy and not loaded yet. ` + + 'Await preloadTheme(theme) before renderView, for example in beforeAll.' + ); + } + // The model is the one of the view being rendered. const models = options.model === undefined ? undefined : ({ [name]: options.model } as Partial); const fixtures = options.fixture === undefined ? undefined : { [name]: options.fixture }; diff --git a/scripts/generate-sdk-docs.mjs b/scripts/generate-sdk-docs.mjs new file mode 100644 index 000000000..bdc08b524 --- /dev/null +++ b/scripts/generate-sdk-docs.mjs @@ -0,0 +1,414 @@ +import ts from 'typescript'; +import { readFileSync, writeFileSync } from 'node:fs'; +import { dirname, extname, resolve } from 'node:path'; +import { fileURLToPath } from 'node:url'; + +// Fills the generated parts of packages/sdk/README.md: the view catalogue (views.json and the published +// view models), the UI primitive reference, the token reference, and every code sample, which is read +// from packages/sdk/docs-samples where `npm run sdk:check` compiles it. `--check` fails on a stale README. +const root = resolve(dirname(fileURLToPath(import.meta.url)), '..'); +const sdk = resolve(root, 'packages/sdk'); +const readmePath = resolve(sdk, 'README.md'); +const read = (path) => readFileSync(resolve(sdk, path), 'utf8'); + +const program = ts.createProgram( + ['types/index.d.ts', 'types/theme.d.ts', 'types/testing.d.ts'].map((path) => resolve(sdk, path)), + { + strict: true, + noEmit: true, + skipLibCheck: true, + target: ts.ScriptTarget.ES2022, + module: ts.ModuleKind.ESNext, + moduleResolution: ts.ModuleResolutionKind.Bundler, + jsx: ts.JsxEmit.ReactJSX, + types: [], + } +); +const checker = program.getTypeChecker(); + +/** An interface the SDK declares, with every module augmentation merged in. */ +function declared(file, name) { + const source = program.getSourceFile(resolve(sdk, file)); + const symbol = checker.getExportsOfModule(checker.getSymbolAtLocation(source)).find((entry) => entry.name === name); + + if (!symbol) throw new Error(`${file} does not export ${name}.`); + + return checker.getDeclaredTypeOfSymbol(symbol); +} + +const properties = (type) => new Map(checker.getPropertiesOfType(type).map((property) => [property.name, property])); + +const opaque = checker.getDeclaredTypeOfSymbol( + checker + .getExportsOfModule(checker.getSymbolAtLocation(program.getSourceFile(resolve(sdk, 'types/views/layouts.d.ts')))) + .find((entry) => entry.name === 'OpaqueModel') +); + +/** The type a property is declared with, as written, or as the checker prints it. */ +function typeText(property) { + const declaration = property.valueDeclaration ?? property.declarations?.[0]; + + if (declaration && ts.isPropertySignature(declaration) && declaration.type) { + return declaration.type.getText().replace(/\s+/g, ' '); + } + + // Pages mapped from `Record` lose the alias. + return checker.getTypeOfSymbol(property) === opaque + ? 'OpaqueModel' + : checker.typeToString(checker.getTypeOfSymbol(property)); +} + +/** The union a type node spells out, following type aliases, so its members keep their written order. */ +function unionNode(node) { + if (!node) return null; + if (ts.isUnionTypeNode(node)) return node; + if (!ts.isTypeReferenceNode(node)) return null; + + const symbol = checker.getSymbolAtLocation(node.typeName); + const target = symbol && symbol.flags & ts.SymbolFlags.Alias ? checker.getAliasedSymbol(symbol) : symbol; + + return unionNode(target?.declarations?.find(ts.isTypeAliasDeclaration)?.type); +} + +const optional = (property) => (property.flags & ts.SymbolFlags.Optional ? '?' : ''); +const code = (text) => `\`${text.replaceAll('|', '\\|')}\``; +const documentation = (symbol) => ts.displayPartsToString(symbol.getDocumentationComment(checker)).replace(/\s+/g, ' '); + +/** The literal values of a property's union type, such as `'sm' | 'md'`, in written order; null for any other type. */ +function literals(property) { + const declaration = property.valueDeclaration; + const node = declaration && ts.isPropertySignature(declaration) ? unionNode(declaration.type) : null; + + if (node?.types.every((member) => ts.isLiteralTypeNode(member) && ts.isStringLiteral(member.literal))) { + return node.types.map((member) => member.literal.text); + } + + const type = checker.getTypeOfSymbol(property); + const members = (type.isUnion() ? type.types : [type]).filter( + (member) => !(member.flags & (ts.TypeFlags.Undefined | ts.TypeFlags.Null)) + ); + + if (members.every((member) => member.flags & ts.TypeFlags.BooleanLiteral)) return 'boolean'; + if (members.every((member) => member.isStringLiteral() || member.isNumberLiteral())) { + return members.map((member) => String(member.value)); + } + + return null; +} + +function viewCatalogue() { + const views = JSON.parse(read('views.json')); + const models = properties(declared('types/views/registry.d.ts', 'ViewModels')); + const inputs = properties(declared('types/views/registry.d.ts', 'ViewInputs')); + const parts = properties(declared('types/views/registry.d.ts', 'ViewPartNames')); + const model = (name) => { + const property = models.get(name); + + if (!property) throw new Error(`views.json names ${name}, which has no published model.`); + + return typeText(property); + }; + const row = ([name, view]) => { + const input = inputs.get(name); + const inputText = input + ? [...properties(checker.getTypeOfSymbol(input)).values()] + .map((property) => code(`${property.name}${optional(property)}: ${typeText(property)}`)) + .join(', ') + : ''; + const partNames = parts.get(name) ? literals(parts.get(name)) : null; + + return [ + code(name), + view.context, + code(model(name)), + [inputText, partNames ? `parts: ${partNames.map(code).join(', ')}` : ''].filter(Boolean).join('
    '), + view.slots.map(code).join(' '), + view.fixtures.join(', '), + ]; + }; + const table = (title, entries) => + [ + `#### ${title}`, + '', + '| View | Context | Model | Inputs and parts | Slots | Fixtures |', + '| --- | --- | --- | --- | --- | --- |', + ...entries.map(row).map((cells) => `| ${cells.join(' | ')} |`), + ].join('\n'); + const all = Object.entries(views); + const opaquePages = all.filter(([name, view]) => view.kind === 'page' && model(name) === 'OpaqueModel'); + + return [ + table( + 'Layouts', + all.filter(([, view]) => view.kind === 'layout') + ), + table( + 'Pages', + all.filter(([name, view]) => view.kind === 'page' && model(name) !== 'OpaqueModel') + ), + table( + 'Blocks', + all.filter(([, view]) => view.kind === 'block') + ), + [ + '#### Opaque pages', + '', + "These pages still render the panel's own containers: their model is `OpaqueModel` (empty), they have no", + 'fixtures, and `Default` renders the container. Wrap them, or place blocks around them.', + '', + '| View | Slots the engine renders around it |', + '| --- | --- |', + ...opaquePages.map(([name, view]) => `| ${code(name)} | ${view.slots.map(code).join(' ')} |`), + ].join('\n'), + ].join('\n\n'); +} + +const kebab = (name) => name.replaceAll(/[A-Z]/g, (letter) => `-${letter.toLowerCase()}`); + +function primitiveReference() { + const primitives = properties(declared('types/themes/primitives.d.ts', 'UiPrimitives')); + const rows = [...primitives.values()].map((primitive) => { + const shape = properties(checker.getTypeOfSymbol(primitive)); + const parts = literals(shape.get('parts')); + const state = [...properties(checker.getTypeOfSymbol(shape.get('state'))).values()].map((property) => { + const values = literals(property); + const attribute = code(`data-${kebab(property.name)}`); + + return values === 'boolean' || values === null ? attribute : `${attribute}: ${values.join(', ')}`; + }); + const notes = [documentation(primitive), documentation(shape.get('state'))].filter(Boolean).join(' '); + + return [ + primitive.name, + parts.map(code).join(', '), + state.join('; ') || 'none', + shape.has('props') ? 'yes' : 'no', + notes, + ]; + }); + + return [ + '| Primitive | Parts | State on `root` | Replaceable | Notes |', + '| --- | --- | --- | --- | --- |', + ...rows.map((cells) => `| ${cells.join(' | ')} |`), + ].join('\n'); +} + +/* + * Every custom property the panel stylesheet declares, by group, with its role. A token the stylesheet + * declares without an entry here, or an entry for one it no longer declares, fails the generator. + */ +const tokens = [ + [ + 'Surfaces and text', + [ + ['--background', 'Page background.'], + ['--foreground', 'Body text.'], + ['--card', 'Cards, rows and raised panels.'], + ['--card-foreground', 'Text on cards.'], + ['--popover', 'Menus, tooltips, hover fills and the panel navigation bar.'], + ['--popover-foreground', 'Text on popovers.'], + ['--muted', 'Quiet fills: table heads, disabled inputs.'], + ['--muted-foreground', 'Secondary text, icons and placeholders.'], + ['--sunken', 'A recessed surface on a card: meter tracks, code chips.'], + ['--border', 'Borders and dividers.'], + ['--input', 'Input fills and borders.'], + ['--ring', 'Focus rings and outlines.'], + ], + ], + [ + 'Actions and states', + [ + ['--primary', 'Primary buttons, links in focus, selected items.'], + ['--primary-foreground', 'Text on primary.'], + ['--secondary', 'Secondary fills and hover states.'], + ['--secondary-foreground', 'Text on secondary.'], + ['--accent', 'Highlights: the active navigation underline, info alerts, the page progress bar.'], + ['--accent-foreground', 'Text on accent.'], + ['--destructive', 'Danger buttons, errors, offline status.'], + ['--destructive-foreground', 'Text on destructive.'], + ['--success', 'Success states and running servers.'], + ['--success-foreground', 'Text on success.'], + ['--warning', 'Warnings and starting servers.'], + ['--warning-foreground', 'Text on warning.'], + ['--caution', 'The orange button colour.'], + ['--caution-foreground', 'Text on caution.'], + ['--state-foreground', 'The text colour the success and warning foregrounds default to.'], + ['--chart-*', 'Five chart series colours (`--chart-1` to `--chart-5`).'], + ], + ], + [ + 'Sidebar', + [ + ['--sidebar', 'Sidebar background; defaults to `--card`.'], + ['--sidebar-foreground', 'Sidebar text.'], + ['--sidebar-primary', 'The active sidebar item.'], + ['--sidebar-primary-foreground', 'Text on the active sidebar item.'], + ['--sidebar-accent', 'Sidebar hover fill.'], + ['--sidebar-accent-foreground', 'Text on the sidebar hover fill.'], + ['--sidebar-border', 'Sidebar borders.'], + ['--sidebar-ring', 'Sidebar focus rings.'], + ], + ], + [ + 'Shape, type and layout', + [ + ['--radius', 'The radius scale `rounded-sm` to `rounded-4xl` is computed from.'], + ['--spacing', "Tailwind's spacing unit, which every `p-*`, `m-*`, `gap-*` and `w-*` multiplies: density."], + ['--font-sans', 'Body typeface (`font-sans`).'], + ['--font-header', 'Heading typeface (`font-header`).'], + ['--layout-content-width', 'Width of page content (`max-w-panel`).'], + ['--layout-auth-width', 'Width of the sign-in card (`max-w-auth`).'], + ['--layout-sidebar-width', 'Width of sidebars (`w-sidebar`).'], + ['--spinner-overlay-opacity', 'Opacity of the background behind a loading overlay.'], + ], + ], + [ + 'Browser chrome', + [ + ['--color-scheme', 'The `color-scheme` of native widgets: `light` or `dark`.'], + ['--theme-color', 'The `` the panel keeps in sync.'], + ['--selection', 'Text selection background; unset keeps the browser default.'], + ['--selection-foreground', 'Text selection colour.'], + ['--scrollbar-thumb', 'Scrollbar thumb on hover, and `scrollbar-color`.'], + ['--scrollbar-thumb-fill', 'Scrollbar thumb at rest.'], + ['--scrollbar-track', 'Scrollbar track.'], + ['--brand-logo', 'A `url(…)` the layouts show as the logo, usually written by an image setting.'], + ], + ], + [ + 'Console', + [ + ['--terminal-background', 'Console background (`bg-terminal`).'], + ['--terminal-foreground', 'Uncoloured console output.'], + ['--terminal-cursor', 'Console cursor; matches the background to hide it.'], + ['--terminal-selection', 'Selected console text background.'], + ['--terminal-selection-foreground', 'Selected console text.'], + ['--terminal-ansi-*', 'The 16 ANSI colours: `black`, `red`, `green`, `yellow`, `blue`, `magenta`, `cyan`, `white` and their `bright-` forms.'], + ], + ], + [ + 'File editor', + [ + ['--editor-background', 'Editor background.'], + ['--editor-foreground', 'Editor text.'], + ['--editor-caret', 'The caret.'], + ['--editor-selection', 'Selected text background.'], + ['--editor-selected-foreground', 'Text in selected search matches and completions.'], + ['--editor-border', 'Editor borders and gutters.'], + ['--editor-muted', 'Line numbers and other quiet text.'], + ['--editor-active-line', 'The line with the caret.'], + ['--editor-search-match', 'Search matches.'], + ['--editor-search-match-selected', 'The current search match.'], + ['--editor-tooltip', 'Tooltip and autocomplete background.'], + ['--editor-tooltip-border', 'Tooltip and autocomplete border.'], + ['--editor-panel-shadow', 'Shadow of the search panel.'], + ['--editor-dialog-shadow', 'Shadow of editor dialogs.'], + ['--editor-syntax-*', 'Syntax colours: `keyword`, `name`, `function`, `constant`, `definition`, `type`, `operator`, `string`, `invalid`.'], + ], + ], +]; +/** Read by the panel, but declared by Tailwind or by no stylesheet until a theme sets them. */ +const undeclared = ['--spacing', '--font-sans', '--font-header', '--selection', '--selection-foreground', '--brand-logo']; + +function tokenReference() { + const css = read('panel.css').replace(/\/\*[\s\S]*?\*\//g, ''); + const found = new Set([...css.matchAll(/(--[\w-]+)\s*:/g)].map((match) => match[1])); + const matches = (entry, token) => (entry.endsWith('*') ? token.startsWith(entry.slice(0, -1)) : entry === token); + const entries = tokens.flatMap(([, list]) => list.map(([entry]) => entry)); + const missing = [...found].filter((token) => !entries.some((entry) => matches(entry, token))); + const stale = entries.filter( + (entry) => !undeclared.includes(entry) && ![...found].some((token) => matches(entry, token)) + ); + + if (missing.length || stale.length) { + throw new Error( + `Update the token reference in scripts/generate-sdk-docs.mjs. ` + + `Undocumented: ${missing.join(', ') || 'none'}. No longer declared: ${stale.join(', ') || 'none'}.` + ); + } + + // `--color-card: var(--card)` makes `bg-card`, `text-card` and the rest. + const theme = read('theme-tokens.css'); + const utility = (token) => { + const color = new RegExp(`--color-([\\w-]+):\\s*var\\(${token}\\)`).exec(theme); + const container = new RegExp(`--container-([\\w-]+):\\s*var\\(${token}\\)`).exec(theme); + + if (color) return code(`*-${color[1]}`); + if (container) return code(`*-${container[1]}`); + + return ''; + }; + + return tokens + .map(([group, list]) => + [ + `#### ${group}`, + '', + '| Token | Role | Utilities |', + '| --- | --- | --- |', + ...list.map(([token, role]) => `| ${code(token)} | ${role} | ${token.endsWith('*') ? '' : utility(token)} |`), + ].join('\n') + ) + .join('\n\n'); +} + +const languages = { '.tsx': 'tsx', '.ts': 'ts', '.css': 'css', '.json': 'json', '.mjs': 'js', '.js': 'js' }; + +/** A sample file, or the lines between `#region name` and `#endregion` markers in it, without the markers. */ +function sample(reference) { + const [path, region] = reference.split('#'); + const source = read(`docs-samples/${path}`); + const marker = /^\s*(?:\/\/|\/\*)\s*#(?:end)?region\b.*$/; + let lines = source.split('\n'); + + if (region) { + const start = lines.findIndex((line) => new RegExp(`#region ${region}\\b`).test(line)); + const end = lines.findIndex((line, index) => index > start && /#endregion/.test(line)); + + if (start === -1 || end === -1) throw new Error(`docs-samples/${path} has no region "${region}".`); + + lines = lines.slice(start + 1, end); + const indent = Math.min(...lines.filter((line) => line.trim()).map((line) => /^\s*/.exec(line)[0].length)); + + lines = lines.map((line) => line.slice(indent)); + } + + const body = lines + .filter((line) => !marker.test(line)) + .join('\n') + .trim(); + + return `\`\`\`${languages[extname(path)] ?? ''}\n${body}\n\`\`\``; +} + +function fill(readme) { + const generated = { views: viewCatalogue, primitives: primitiveReference, tokens: tokenReference }; + const output = readme.replace( + /()[\s\S]*?()/g, + (_, open, name, close) => { + if (!generated[name]) throw new Error(`Unknown generated section "${name}".`); + + return `${open}\n${generated[name]()}\n${close}`; + } + ); + + return output.replace( + /()[\s\S]*?()/g, + (_, open, reference, close) => `${open}\n${sample(reference)}\n${close}` + ); +} + +const readme = readFileSync(readmePath, 'utf8'); +const output = fill(readme); + +if (process.argv.includes('--check')) { + if (output !== readme) { + console.error('packages/sdk/README.md is stale. Run npm run sdk:generate.'); + process.exit(1); + } +} else { + writeFileSync(readmePath, output); +} + +console.log(`SDK: README samples and references ${output === readme ? 'current' : 'regenerated'}`); diff --git a/tests/Unit/Services/Extensions/ExtensionScaffolderTest.php b/tests/Unit/Services/Extensions/ExtensionScaffolderTest.php index 1b48d919d..9c9008120 100644 --- a/tests/Unit/Services/Extensions/ExtensionScaffolderTest.php +++ b/tests/Unit/Services/Extensions/ExtensionScaffolderTest.php @@ -27,14 +27,27 @@ test('scaffolds a theme with a stylesheet, a layout override, a skin, settings a expect($manifest->isTheme())->toBeTrue() ->and($manifest->uiPrefix)->toBeNull() ->and($manifest->provider)->toBeNull() + ->and($manifest->requirements['sdk'] ?? null)->toBe('>='.config('extensions.sdk_version').' <3.0') ->and($manifest->theme->stylesheet)->toBe('dist/theme.css') - ->and(array_keys($manifest->theme->settings))->toBe(['accent', 'radius', 'compact']); - expect($this->scaffolder->files())->toBe(['extension.json', 'package.json', 'vite.config.mjs', 'postcss.config.mjs', 'tsconfig.json', 'vitest.config.mjs', 'src/theme.css', 'src/theme.tsx', 'src/theme.spec.tsx', '.gitignore', 'README.md']); + ->and($manifest->theme->schemes)->toBe(['dark', 'light']) + ->and(array_keys($manifest->theme->settings))->toBe(['accent', 'radius', 'compact', 'logo']) + ->and($manifest->theme->settings['accent']->token)->toBe('--aurora-accent'); + expect($this->scaffolder->files())->toBe(['extension.json', 'package.json', 'vite.config.mjs', 'postcss.config.mjs', 'tsconfig.json', 'vitest.config.mjs', 'src/theme.css', 'src/theme.tsx', 'src/skins.ts', 'src/views/AppLayout.tsx', 'src/theme.spec.tsx', '.gitignore', 'README.md']); expect(File::get($target.'/vite.config.mjs'))->toContain("defineThemeConfig({ entry: 'src/theme.tsx', stylesheet: 'src/theme.css' })"); - expect(File::get($target.'/src/theme.css'))->toStartWith('/*')->toContain("@import '@pterodactyl/sdk/theme-entry.css';", "[data-aurora-compact='true']"); - expect(File::get($target.'/src/theme.tsx'))->toContain("'layout.app': AppLayout", "skin('Button'"); - expect(File::get($target.'/src/theme.spec.tsx'))->toContain("renderView('layout.app', { theme })"); - expect(File::json($target.'/package.json')['devDependencies'])->toHaveKeys(['@pterodactyl/sdk', 'tailwindcss', '@tailwindcss/forms']); + expect(File::get($target.'/src/theme.css'))->toStartWith('/*')->toContain("@import '@pterodactyl/sdk/theme-entry.css';", 'var(--aurora-accent', '.light {', "[data-aurora-compact='true']"); + expect(File::get($target.'/src/theme.tsx'))->toContain("'layout.app': AppLayout", 'ui: skins'); + expect(File::get($target.'/src/skins.ts'))->toContain("skin('Button'", "skin('Card', (classic)"); + expect(File::get($target.'/src/views/AppLayout.tsx'))->toContain("data-aurora-layout=''", ''); + expect(File::get($target.'/src/theme.spec.tsx'))->toContain('preloadTheme(theme)', "renderView('layout.app', { theme, fixture: 'admin' })", '[data-aurora-layout] main'); + expect(File::get($target.'/README.md'))->toContain('"Themes" chapter', 'p:extension:dev . --watch')->not->toContain('{{'); + + $package = File::json($target.'/package.json'); + expect($package['devDependencies'])->toHaveKeys(['@pterodactyl/sdk', 'tailwindcss', '@tailwindcss/forms']) + ->and($package['scripts'])->toHaveKeys(['build', 'dev', 'typecheck', 'test', 'doctor', 'types', 'pack']) + ->and($package['scripts']['doctor'])->toMatch('~^php \S+/artisan p:extension:doctor \.$~'); + // The scripts reach the panel's artisan from the package directory. + preg_match('~^php (\S+) ~', $package['scripts']['doctor'], $doctor); + expect(realpath(str_starts_with($doctor[1], '/') ? $doctor[1] : $target.'/'.$doctor[1]))->toBe(realpath(base_path('artisan'))); expect($target.'/composer.json')->not->toBeFile(); }); diff --git a/tests/Unit/Services/Themes/ThemeManifestTest.php b/tests/Unit/Services/Themes/ThemeManifestTest.php index d0e5dc415..8ebc02ac8 100644 --- a/tests/Unit/Services/Themes/ThemeManifestTest.php +++ b/tests/Unit/Services/Themes/ThemeManifestTest.php @@ -170,6 +170,15 @@ test('settings render tokens and attributes as values that cannot break out', fu ->and($setting('text')->attributeValue(null))->toBeNull(); }); +test('the themes the SDK readme documents are valid manifests', function (string $sample, string $id): void { + $manifest = (new ExtensionManifestValidator)->fromDirectory(base_path('packages/sdk/docs-samples/'.$sample)); + + expect($manifest->id)->toBe($id)->and($manifest->isTheme())->toBeTrue(); +})->with([ + 'the sample theme' => ['aurora', 'aurora'], + 'a child of it' => ['child-theme', 'aurora-sunset'], +]); + test('stored values that no longer fit the setting read as its default', function (): void { $select = ThemeSetting::fromValidatedData('probe', ['type' => 'select', 'label' => 'Probe', 'options' => ['side' => 'Side'], 'default' => 'side']); $number = ThemeSetting::fromValidatedData('probe', ['type' => 'number', 'label' => 'Probe', 'max' => 2, 'default' => 1]); diff --git a/vitest.config.ts b/vitest.config.ts index 1d192b36a..f5ea56c2b 100644 --- a/vitest.config.ts +++ b/vitest.config.ts @@ -12,7 +12,11 @@ export default defineConfig({ }, }, test: { - projects: [{ extends: true, test: { name: 'panel' } }, 'packages/hello-world/vitest.config.ts'], + projects: [ + { extends: true, test: { name: 'panel' } }, + 'packages/hello-world/vitest.config.ts', + 'packages/sdk/docs-samples/vitest.config.ts', + ], environment: 'node', setupFiles: ['./resources/scripts/setup-tests.ts'], include: [