theme samples

This commit is contained in:
robert dennis
2026-10-12 16:24:48 -04:00
parent b81895af7e
commit cf0322c5cb
46 changed files with 2021 additions and 137 deletions
@@ -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<string, string> $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
@@ -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 <html>. */
/* 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 <html>; spacing utilities multiply --spacing. */
[data-{{id}}-compact='true'] {
--spacing: 0.2rem;
}
@@ -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 `<Main>`.
*/
export default function AppLayout({ Default }: ViewProps<'layout.app'>) {
return (
<div data-{{id}}-layout='' className='min-h-dvh bg-linear-to-b from-primary/10 to-transparent'>
<Default />
</div>
);
}
@@ -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}}",
@@ -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 `<html>` attribute (`attribute`), or both,
before the page renders. `php artisan p:extension:types` generates `src/theme-types.ts`,
whose `ThemeSettings` types `useThemeSettings<ThemeSettings>()`.
Each setting writes a CSS token (`token`), an `<html>` attribute (`attribute`), or both, before the
page renders. `npm run types` writes `src/theme-types.ts`, whose `ThemeSettings` types
`useThemeSettings<ThemeSettings>()`.
## 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.
@@ -0,0 +1,34 @@
import { skin, type PrimitiveState, type ThemeSkins } from '@pterodactyl/sdk/theme';
type ButtonState = PrimitiveState<'Button'>;
const fills: Record<ButtonState['color'], string> = {
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`,
})),
};
@@ -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');
});
@@ -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 (
<div data-{{id}}-layout='' className='min-h-dvh bg-background'>
<Default />
</div>
);
}
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 <view>` 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,
},
+82 -54
View File
@@ -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/<locale>/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 `<html>` 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 `<html>` 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 <Default className="hw:gap-3" />;
}
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.
<!-- sample: snippets/extension.tsx#override -->
<!-- /sample -->
`Default` takes optional `model`, `className` and `children`, which replace what this layer
received for the layer below: `<Default model={{ ...model, name: model.name.toUpperCase() }} />`.
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<Name>`; define parts outside the layer's render function.
<!-- sample: snippets/extension.tsx#setup -->
<!-- /sample -->
| 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
`<View name="billing.balance" optional />`, 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<Model>`. 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 `<View name="billing.balance" />`; a theme that may run without the extension places it
with `optional`, which renders nothing while no installed package defines it.
<!-- sample: snippets/extension.tsx#define -->
<!-- /sample -->
### 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: `<Button className="hw:mt-4">` drops the button's own `mt-*` class.
+50
View File
@@ -0,0 +1,50 @@
import { mkdtempSync, readFileSync, rmSync, statSync } from 'node:fs';
import { tmpdir } from 'node:os';
import { resolve } from 'node:path';
import postcss from 'postcss';
import tailwind from '@tailwindcss/postcss';
import { build } from 'vite';
import { expect, it } from 'vitest';
import { defineThemeConfig } from './vite.mjs';
// The README's sample theme: its types are checked by `npm run sdk:check` and its tests run with the suite.
const aurora = resolve(__dirname, 'docs-samples/aurora');
it('compiles the sample theme stylesheet within the stylesheet budget', async () => {
const from = resolve(aurora, 'src/theme.css');
const { css } = await postcss([tailwind()]).process(readFileSync(from, 'utf8'), { from });
expect(css).toContain("font-family: 'Aurora Sans'");
expect(css).toMatch(/\.glass \{/);
expect(css).toContain("[data-aurora-sidebar='right']");
expect(Buffer.byteLength(css)).toBeLessThan(250 * 1024);
}, 60_000);
it('builds the sample theme entry and records the views it overrides', async () => {
const outDir = mkdtempSync(resolve(tmpdir(), 'aurora-build-'));
try {
await build({
...defineThemeConfig({ entry: resolve(aurora, 'src/theme.tsx'), outDir }),
configFile: false,
logLevel: 'silent',
});
const info = JSON.parse(readFileSync(resolve(outDir, 'theme.json'), 'utf8'));
expect(info.views).toEqual([
'layout.auth',
'auth.loginForm',
'layout.app',
'layout.server',
'server.power',
'page.server.console',
'server.terminal',
'server.stats',
'dashboard.serverList',
'dashboard.serverCard',
]);
expect(statSync(resolve(outDir, 'client.js')).size).toBeLessThan(200 * 1024);
} finally {
rmSync(outDir, { recursive: true, force: true });
}
}, 60_000);
@@ -0,0 +1,56 @@
{
"$schema": "./node_modules/@pterodactyl/sdk/manifest.schema.json",
"id": "aurora",
"type": "theme",
"name": "Aurora",
"version": "1.0.0",
"description": "A glass sidebar theme with a light and a dark scheme.",
"icon": "palette",
"requires": { "panel": "^2.0.0-dev", "sdk": ">=2.0.0-beta.5 <3.0" },
"ui": { "entry": "dist/client.js" },
"theme": {
"extends": "classic",
"stylesheet": "dist/theme.css",
"schemes": ["dark", "light"],
"settings": {
"accent": { "type": "color", "label": "Accent", "default": "#8b5cf6", "token": "--aurora-accent" },
"sidebar": {
"type": "select",
"label": "Sidebar",
"options": { "left": "Left", "right": "Right" },
"default": "left",
"attribute": "data-aurora-sidebar"
},
"density": {
"type": "select",
"label": "Density",
"options": { "comfortable": "Comfortable", "compact": "Compact" },
"default": "comfortable",
"attribute": "data-aurora-density"
},
"blur": {
"type": "number",
"label": "Glass blur",
"default": 16,
"min": 0,
"max": 40,
"step": 4,
"unit": "px",
"token": "--aurora-blur"
},
"logo": {
"type": "image",
"label": "Logo",
"help": "Shown in the sidebar and on the sign-in page.",
"token": "--brand-logo"
},
"tagline": {
"type": "text",
"label": "Sign-in tagline",
"default": "Every server, one place.",
"maxLength": 80
},
"liveStats": { "type": "toggle", "label": "Live stats on the dashboard", "default": true }
}
}
}
@@ -0,0 +1,34 @@
import { Monitor, Moon, Sun } from 'lucide-react';
import { useTheme, type ThemeScheme } from '@pterodactyl/sdk/theme';
const options = [
{ value: 'light', label: 'Light', icon: Sun },
{ value: 'dark', label: 'Dark', icon: Moon },
{ value: 'system', label: 'System', icon: Monitor },
] satisfies { value: ThemeScheme | 'system'; label: string; icon: typeof Sun }[];
/** Light, dark or the system's: stored in a cookie and applied without a reload. */
export default function SchemeSwitch() {
const { scheme, schemes, setScheme } = useTheme();
if (schemes.length < 2) {
return null;
}
return (
<div role='group' aria-label='Colour scheme' className='glass inline-flex rounded-full p-0.5'>
{options.map(({ value, label, icon: Glyph }) => (
<button
key={value}
type='button'
aria-label={label}
aria-pressed={value === scheme}
onClick={() => setScheme(value)}
className='rounded-full p-1.5 text-muted-foreground aria-pressed:bg-primary aria-pressed:text-primary-foreground'
>
<Glyph className='size-4' aria-hidden />
</button>
))}
</div>
);
}
@@ -0,0 +1,68 @@
import { skin, type PrimitiveState, type ThemeSkins } from '@pterodactyl/sdk/theme';
// #region button
type ButtonState = PrimitiveState<'Button'>;
const fills: Record<ButtonState['color'], string> = {
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<ButtonState['size'], string> = {
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 };
@@ -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<ExtensionConfig, ExtensionPublicConfigKey>;
// The theme's settings, as useThemeSettings<ThemeSettings>() 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;
}
@@ -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 */
@@ -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
@@ -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 <NamedIcon name="server"/> draws this in place of lucide's, such as a navigation item naming it.
icons: { server: Boxes },
});
@@ -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<AppLayoutLink['id'], LucideIcon> = { 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 (
<PanelLink destination={{ to: '/' }} className='flex h-10 items-center px-3 font-semibold no-underline'>
{brand.logoUrl ? <img src={brand.logoUrl} alt={brand.name} className='h-8 w-auto' /> : brand.name}
</PanelLink>
);
}
function Links({ model }: { model: AppLayoutModel }) {
return (
<>
<Slot name='nav.items.before' />
{model.links.map((link) => {
const Glyph = icons[link.id];
return (
<PanelLink key={link.id} destination={link.destination} exact={link.exact} className={linkClass}>
<Glyph className='size-4' aria-hidden />
<span className='max-lg:sr-only'>{link.label}</span>
</PanelLink>
);
})}
<Slot name='nav.items.after' />
</>
);
}
/** 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 (
<div className='flex min-h-dvh flex-col lg:flex-row sidebar-right:lg:flex-row-reverse'>
<SpinnerOverlay visible={model.signingOut} fixed />
<aside className='glass flex shrink-0 items-center gap-2 p-3 lg:sticky lg:top-0 lg:h-dvh lg:w-sidebar lg:flex-col lg:items-stretch lg:gap-6 lg:p-4'>
<Brand brand={model.brand} />
<nav aria-label='Main' className='flex flex-1 gap-1 lg:flex-none lg:flex-col'>
<Links model={model} />
</nav>
<View name='app.search' className={linkClass} />
<div className='flex items-center gap-2 lg:mt-auto'>
<Avatar name={model.user.uuid} size={28} />
<span className='min-w-0 flex-1 truncate text-sm max-lg:sr-only'>{model.user.username}</span>
<SchemeSwitch />
<Tooltip content='Sign out'>
<button type='button' aria-label='Sign out' onClick={model.signOut} className={linkClass}>
<LogOut className='size-4' aria-hidden />
</button>
</Tooltip>
</div>
</aside>
<Main className='min-w-0 flex-1'>{children}</Main>
</div>
);
}
@@ -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<ThemeSettings>();
return (
<div className='grid min-h-dvh lg:grid-cols-2'>
<section className='relative hidden flex-col justify-between overflow-hidden bg-primary p-12 text-primary-foreground lg:flex'>
{model.brand.logoUrl ? (
<img src={model.brand.logoUrl} alt={model.brand.name} className='h-10 w-auto self-start' />
) : (
<p className='text-2xl font-semibold'>{model.brand.name}</p>
)}
<p className='max-w-sm text-4xl leading-tight font-semibold text-balance'>{tagline}</p>
</section>
<div className='flex flex-col'>
<div className='flex justify-end p-4'>
<SchemeSwitch />
</div>
<Main className='flex flex-1 items-center justify-center p-6'>
<div className='w-full max-w-sm'>{children}</div>
</Main>
</div>
</div>
);
}
@@ -0,0 +1,34 @@
import { Alert, ServerContentBlock } from '@pterodactyl/sdk';
import { Slot, View, type ServerConsoleModel, type ViewProps } from '@pterodactyl/sdk/theme';
const notices: Record<NonNullable<ServerConsoleModel['notice']>, 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 (
<ServerContentBlock title={active ? 'Console' : undefined}>
{model.notice && (
<Alert type='warning' className='mb-4'>
{notices[model.notice]}
</Alert>
)}
<Slot name='server.console.before' data={model.server} />
<div className='grid gap-4 xl:grid-cols-[minmax(0,1fr)_18rem]'>
<View name='server.terminal' />
<View name='server.stats' />
</div>
<div className='mt-4 grid gap-4 md:grid-cols-3'>
<View name='server.graphs' />
</div>
<Slot name='server.console.after' data={model.server} />
<View name='server.features' />
</ServerContentBlock>
);
}
@@ -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 (
<div className='space-y-1.5'>
<Label htmlFor={id}>{label}</Label>
<Input
{...field.fieldProps}
id={id}
$hasError={field.error !== null}
aria-invalid={field.error !== null || undefined}
aria-describedby={field.error ? `${id}-error` : undefined}
/>
{field.error && (
<p id={`${id}-error`} className='input-help error'>
{field.error}
</p>
)}
</div>
);
}
/** 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 (
<form onSubmit={submit} className='space-y-5'>
<h1 className='text-2xl font-semibold'>Sign in</h1>
<Field field={fields.username} label='Username or email' />
<Field field={fields.password} label='Password' />
{/* A panel with reCAPTCHA turned on cannot sign anyone in without it. */}
{Captcha && <Captcha />}
<Button type='submit' size='xlarge' disabled={!model.canSubmit} isLoading={model.submitting}>
Sign in
</Button>
<Slot name='auth.login.form.after' data={model.route} />
<PanelLink destination={model.forgotPassword} className='block text-center text-sm text-muted-foreground'>
Forgot your password?
</PanelLink>
</form>
);
}
@@ -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 (
<div className='flex items-center gap-2'>
<Slot name='server.console.power.before' data={model.server} />
{permissions.start && (
<Button size='small' color='green' disabled={!enabled.start} onClick={actions.start}>
<Play className='size-4' aria-hidden /> Start
</Button>
)}
{permissions.restart && (
<Button size='small' color='grey' disabled={!enabled.restart} onClick={actions.restart}>
<RotateCcw className='size-4' aria-hidden /> Restart
</Button>
)}
{permissions.stop &&
(model.killable ? (
<Dialog.ConfirmTrigger
title='Kill the server process?'
confirm='Kill'
trigger={({ onClick }) => (
<Button size='small' color='red' disabled={!enabled.kill} onClick={onClick}>
<Zap className='size-4' aria-hidden /> Kill
</Button>
)}
onConfirmed={(_event, close) => {
close();
actions.kill();
}}
>
Killing a server can corrupt its data.
</Dialog.ConfirmTrigger>
) : (
<Button size='small' color='red' disabled={!enabled.stop} onClick={actions.stop}>
<Square className='size-4' aria-hidden /> Stop
</Button>
))}
<Slot name='server.console.power.after' data={model.server} />
</div>
);
}
@@ -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<ThemeSettings>();
const { state } = model;
return (
<div className='space-y-3'>
<div className='flex items-start gap-2'>
<div className='min-w-0 flex-1'>
<p className='truncate font-semibold'>{model.name}</p>
<p className='truncate font-mono text-xs text-muted-foreground'>{model.address ?? 'No address'}</p>
</div>
<Slot name='dashboard.serverRow.name.after' data={server} />
{state.kind === 'ready' && (
<Badge tone={state.power === 'running' ? 'success' : 'neutral'} variant='soft'>
{state.power}
</Badge>
)}
{state.kind === 'unavailable' && <Badge tone='warning'>{state.reason.replace('-', ' ')}</Badge>}
</div>
{state.kind === 'loading' && <Spinner size='small' />}
{liveStats && state.kind === 'ready' && (
<div className='grid grid-cols-3 gap-3 text-xs text-muted-foreground'>
<div>
CPU {state.cpu.value.toFixed(0)}%
<ProgressBar value={percent(state.cpu)} label='CPU' tone={state.cpu.alarm ? 'danger' : 'accent'} />
</div>
<div>
{bytesToString(state.memory.value)}
<ProgressBar value={percent(state.memory)} label='Memory' tone={state.memory.alarm ? 'danger' : 'accent'} />
</div>
<div>
{bytesToString(state.disk.value)}
<ProgressBar value={percent(state.disk)} label='Disk' tone={state.disk.alarm ? 'danger' : 'accent'} />
</div>
</div>
)}
</div>
);
}
@@ -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 (
<div className='flex gap-2'>
{running ? (
<>
<Button size='xsmall' color='grey' disabled={power.isPending} onClick={send('restart')}>
<RotateCcw className='size-3.5' aria-hidden /> Restart
</Button>
<Button size='xsmall' color='red' disabled={power.isPending} onClick={send('stop')}>
<Square className='size-3.5' aria-hidden /> Stop
</Button>
</>
) : (
<Button size='xsmall' color='green' disabled={power.isPending || item.power === null} onClick={send('start')}>
<Play className='size-3.5' aria-hidden /> Start
</Button>
)}
</div>
);
}
function Tile({ item }: { item: ServerListItem }) {
const { server } = item;
return (
<li className='glass flex flex-col gap-4 rounded-2xl p-5'>
<Slot name='dashboard.serverRow.before' data={server} />
<PanelLink
destination={{ to: '/server/$id', params: { id: server.attributes.identifier } }}
aria-label={server.attributes.name}
className='text-foreground no-underline'
>
<View name='dashboard.serverCard' server={server} />
</PanelLink>
<Slot name='dashboard.serverRow.metrics.after' data={server} />
<PowerButtons item={item} />
<Slot name='dashboard.serverRow.after' data={server} />
</li>
);
}
function Pager({ model }: { model: ServerListModel }) {
const { pagination, actions } = model;
if (!pagination || pagination.totalPages < 2) {
return null;
}
return (
<nav aria-label='Pages' className='mt-6 flex items-center justify-center gap-3 text-sm'>
<Button size='xsmall' color='grey' disabled={pagination.currentPage === 1} onClick={() => actions.setPage(pagination.currentPage - 1)}>
Previous
</Button>
{pagination.currentPage} of {pagination.totalPages}
<Button
size='xsmall'
color='grey'
disabled={pagination.currentPage === pagination.totalPages}
onClick={() => actions.setPage(pagination.currentPage + 1)}
>
Next
</Button>
</nav>
);
}
/** 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 (
<>
<PageHeading
title='Servers'
actions={
model.canViewOthers && (
<Switch
checked={others}
onChange={() => model.actions.setScope(others ? 'mine' : 'others')}
label="Show other users' servers"
controlPosition='end'
/>
)
}
/>
<Slot name='dashboard.before' />
{model.loading && <Spinner size='large' centered />}
{!model.loading && model.servers.length === 0 && (
<Empty className='glass rounded-2xl'>
<EmptyHeader>
<EmptyMedia variant='icon'>
<ServerIcon />
</EmptyMedia>
<EmptyTitle>No servers yet</EmptyTitle>
<EmptyDescription>Servers you own or are invited to show up here.</EmptyDescription>
</EmptyHeader>
</Empty>
)}
<ul className='grid gap-4 sm:grid-cols-2 xl:grid-cols-3'>
{model.servers.map((item) => (
<Tile key={item.server.attributes.uuid} item={item} />
))}
</ul>
<Pager model={model} />
<Slot name='dashboard.after' />
</>
);
}
@@ -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 (
<div className='mx-auto w-full max-w-panel px-4 py-6 lg:px-8'>
<header className='glass mb-4 flex flex-wrap items-center gap-4 rounded-2xl px-5 py-4'>
<div className='min-w-0 flex-1'>
<h1 className='truncate text-xl font-semibold'>{model.name}</h1>
<p className='font-mono text-xs text-muted-foreground'>{model.identifier}</p>
</div>
{/* Power controls make no sense while the server installs, transfers or restores. */}
{model.conflict === null && <View name='server.power' />}
</header>
<nav aria-label='Server' className='mb-6 flex gap-1 overflow-x-auto'>
<Slot name='server.navigation.before' data={model.server} />
<Navigation items={items}>
{(item, { active, badge }) => (
<NavigationLink item={item} className={cn(tabClass, active && 'bg-primary/15 text-foreground')}>
{item.icon && <NamedIcon name={item.icon} size={16} aria-hidden />}
{item.label}
{badge}
</NavigationLink>
)}
</Navigation>
<Slot name='server.navigation.after' data={model.server} />
</nav>
<Main>{children}</Main>
</div>
);
}
@@ -0,0 +1,40 @@
import { Badge, Card, ProgressBar, bytesToString } from '@pterodactyl/sdk';
import type { ServerStatMetric, UiTone, ViewProps } from '@pterodactyl/sdk/theme';
const tones: Record<NonNullable<ServerStatMetric['alarm']>, 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 (
<div className='space-y-1.5'>
<div className='flex justify-between text-xs'>
<span className='text-muted-foreground'>{label}</span>
<span>
{format(metric.value)}
{metric.limit > 0 && <span className='text-muted-foreground'> / {format(metric.limit)}</span>}
</span>
</div>
<ProgressBar
value={percent(metric)}
label={label}
tone={metric.alarm ? tones[metric.alarm] : 'accent'}
/>
</div>
);
}
/** 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 (
<Card title='Resources' actions={<Badge tone={model.state === 'running' ? 'success' : 'neutral'}>{model.state ?? 'unknown'}</Badge>}>
<div className='space-y-4'>
<Meter label='CPU' metric={model.cpu} format={(value) => `${value.toFixed(1)}%`} />
<Meter label='Memory' metric={model.memory} format={bytesToString} />
<Meter label='Disk' metric={model.disk} format={bytesToString} />
<p className='font-mono text-xs text-muted-foreground'>{model.address ?? 'No allocation'}</p>
</div>
</Card>
);
}
@@ -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<HTMLInputElement>) {
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 (
<section aria-label='Console' className='glass flex h-[30rem] flex-col overflow-hidden rounded-2xl'>
<div className='relative min-h-0 flex-1 bg-terminal p-3 font-mono text-sm'>
<model.Terminal />
{model.loading && (
<div className='absolute inset-0 grid place-items-center'>
<Spinner size='large' />
</div>
)}
{model.failed && (
<div role='alert' className='absolute inset-0 grid place-items-center gap-2 text-sm'>
The console could not be loaded.
<Button size='xsmall' color='grey' onClick={model.retry}>
Try again
</Button>
</div>
)}
{model.scrolledUp && (
<Button size='xsmall' color='grey' className='absolute right-5 bottom-3' onClick={model.scrollToBottom}>
Latest output
</Button>
)}
</div>
{command.allowed && (
<input
aria-label='Console command'
placeholder='Type a command'
autoCapitalize='none'
autoCorrect='off'
disabled={command.disabled}
value={command.value}
onChange={(event) => 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'
/>
)}
</section>
);
}
@@ -0,0 +1,3 @@
import { defineThemeConfig } from '@pterodactyl/sdk/vite';
export default defineThemeConfig({ entry: 'src/theme.tsx', stylesheet: 'src/theme.css' });
@@ -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" }
}
}
}
@@ -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 (
<div className='border-l-2 border-primary pl-3'>
<Default />
</div>
);
}
export default defineTheme({ views: { 'dashboard.serverCard': SunsetCard } });
@@ -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' ? <Default model={{ ...model, name: `${model.name} (archive)` }} /> : <Default />;
}
@@ -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 (
<>
<Default className='hw:gap-3' />
{model.state.kind === 'unavailable' && <p className='hw:text-xs'>Ask support about {model.name}.</p>}
</>
);
}
// #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<BalanceModel>) {
return (
<Card title='Balance' className={className} actions={<Badge tone='success'>{model.credits} credits</Badge>}>
<Button size='xsmall' onClick={model.topUp}>
Top up
</Button>
</Card>
);
}
// #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<BalanceModel>('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', () => <View name='billing.balance' />);
// #endregion setup
},
});
@@ -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 (
<div className='mx-auto flex max-w-panel gap-8 p-6'>
<nav aria-label='Account' className='w-56 shrink-0 space-y-1'>
<Slot name='account.navigation.before' />
<Navigation items={model.nav.items}>
{(item, { active, badge }) => (
<NavigationLink
item={item}
className={cn('flex items-center gap-2 rounded-lg px-3 py-2', active && 'bg-primary/15')}
>
{item.icon && <NamedIcon name={item.icon} size={16} aria-hidden />}
<span className='flex-1'>{item.label}</span>
{badge}
</NavigationLink>
)}
</Navigation>
<Slot name='account.navigation.after' />
</nav>
<Main className='min-w-0 flex-1'>
<p className='text-sm text-muted-foreground'>{current?.label}</p>
{children}
</Main>
</div>
);
}
// #endregion account
// #region anywhere
/** The account links anywhere: `useNavigation` reads an area's live navigation. */
export function AccountShortcuts() {
const { items } = useNavigation('account');
return (
<ul>
{items.map((item) => (
<li key={`${item.extensionId ?? ''}:${item.id}`}>
<NavigationLink item={item}>{item.label}</NavigationLink>
</li>
))}
</ul>
);
}
// #endregion anywhere
@@ -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 (
<div role='alert' data-ui='alert' data-type={type} className={`rounded-xl border-l-4 p-4 ${className ?? ''}`}>
{title && <p className='font-semibold'>{title}</p>}
{children}
</div>
);
}
// #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 (
<a href={href} {...ui('root', 'no-underline')}>
{children}
</a>
);
}
// #endregion use-skin
export default defineTheme({ ui: { Badge: badge, Alert: Banner } });
export { ButtonLikeLink };
@@ -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 (
<div className='rounded-2xl ring-1 ring-primary/30'>
<Default />
</div>
);
}
// #endregion wrap
// #region transform
/** Hands the layer below another model and an extra class. */
function LoudCard({ model, Default }: ViewProps<'dashboard.serverCard'>) {
return <Default model={{ ...model, name: model.name.toUpperCase() }} className='gap-6' />;
}
// #endregion transform
// #region parts
/** Replaces one part of classic's card and keeps the others. */
function Uptime({ model }: ViewPartProps<'dashboard.serverCard'>) {
return <span>{model.state.kind === 'ready' ? model.state.power : 'unknown'}</span>;
}
function CardWithUptime({ Default }: ViewProps<'dashboard.serverCard'>) {
return <Default parts={{ metrics: Uptime }} />;
}
// #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 (
<PageContentBlock title='Account'>
{model.twoFactorRequired && <p role='alert'>Turn on two-factor authentication to continue.</p>}
<Slot name='account.overview.before' />
<div className='grid gap-6 lg:grid-cols-2'>
<View name='account.twoFactor' className='lg:col-span-2' />
<View name='account.password' />
<View name='account.email' />
</div>
<Slot name='account.overview.after' />
</PageContentBlock>
);
}
// #endregion compose
// #region optional
/** Places a block a billing extension defines; nothing renders while that extension is not installed. */
function SidebarFooter() {
return <View name='billing.balance' optional className='mt-auto' />;
}
/** Restyles that block. Its model is `unknown` here: the theme does not know the extension's types. */
function Balance({ Default }: ViewProps<'billing.balance'>) {
return (
<div className='glass rounded-xl p-3'>
<Default />
</div>
);
}
// #endregion optional
export default defineTheme({
views: {
'dashboard.serverCard': FramedCard,
'page.account.overview': AccountOverview,
'billing.balance': Balance,
},
});
export { CardWithUptime, LoudCard, SidebarFooter };
+16 -5
View File
@@ -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"]
}
@@ -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}'],
},
});
+7 -1
View File
@@ -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<HTMLElement | null>;
/** 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;
+4 -1
View File
@@ -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<void>;
/**
* 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<N extends ViewName>(name: N, options?: RenderViewOptions<N>): RenderedView;
export interface RenderPrimitiveOptions {
+13 -4
View File
@@ -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<C extends JSXElementConstructor<never> = JSXElementConstructor<never>> {
readonly component: C;
/** Rendered by the workbench's UI kit, by variant; the first is the default. */
@@ -9,25 +9,34 @@ export interface UiPrimitive<C extends JSXElementConstructor<never> = 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
+23
View File
@@ -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'>) => <p>{`lazy dashboard ${model.error ?? 'ok'}`}</p>,
})),
},
});
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({}) });
+22 -1
View File
@@ -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<void> {
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<N extends ViewName>(name: N, options: RenderViewOptions<N> = {}): 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<ViewModels>);
const fixtures = options.fixture === undefined ? undefined : { [name]: options.fixture };
+414
View File
@@ -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<OpaquePageName, OpaqueModel>` 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('<br>'),
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 `<meta name="theme-color">` 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(
/(<!-- generated:(\w+) -->)[\s\S]*?(<!-- \/generated:\2 -->)/g,
(_, open, name, close) => {
if (!generated[name]) throw new Error(`Unknown generated section "${name}".`);
return `${open}\n${generated[name]()}\n${close}`;
}
);
return output.replace(
/(<!-- sample: (\S+) -->)[\s\S]*?(<!-- \/sample -->)/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'}`);
@@ -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=''", '<Default />');
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();
});
@@ -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]);
+5 -1
View File
@@ -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: [