mirror of
https://github.com/pterodactyl/panel.git
synced 2026-12-05 22:05:47 -05:00
theme docs
This commit is contained in:
+2
-2
@@ -35,8 +35,8 @@ Extension SDK `2.0.0-beta.5`.
|
||||
* Adds the `server.files.editor` and `server.files.manager` views, `useNavigationBlocker`, `serverResourcesQueryOptions`, `useServerResources`, `useSendServerPower` and `useSendServerCommand` to the SDK.
|
||||
* Adds themes: extensions with `"type": "theme"` that rebuild the panel stylesheet, skin the UI kit and override views through `defineTheme` (`@pterodactyl/sdk/theme`), with typed settings written as tokens and `<html>` attributes, dark and light schemes with a user switch, and child themes through `theme.extends`.
|
||||
* Adds the admin Themes page (activate, preview for me, reset, settings with a live preview), `p:theme:activate`, `p:theme:reset`, `p:theme:list`, safe mode (`?safe_mode=1`), and a fallback to classic when a theme fails to load.
|
||||
* Adds the theme workbench (`/panel/theme-workbench`), which renders every view and UI primitive from fixtures, and the view inspector (`Alt+Shift+I`, `?inspect=1`).
|
||||
* Adds the theme toolchain: `p:extension:make --theme`, `defineThemeConfig`, the `pterodactyl-theme` CLI (`list`, `eject`, `skins`), `renderView`, `renderPrimitive` and `preloadTheme` in `@pterodactyl/sdk/testing`, and the SDK's themes guide, `THEMES.md`.
|
||||
* Adds the theme toolchain: `p:extension:make --theme` (`--css-only` for a theme without JavaScript), `defineThemeConfig`, the `pterodactyl-theme` CLI (`list`, `eject`, `skins`), `renderView`, `renderPrimitive` and `preloadTheme` in `@pterodactyl/sdk/testing`, and the SDK's themes guide, `THEMES.md`.
|
||||
* `renderView` and `createViewTestHost` throw a `ViewLayerError` when a theme or extension layer fails, unless `strict` is false, and `renderView` mounts test components in slots with `slots`.
|
||||
* Adds layout, terminal, selection, scrollbar and browser chrome theme tokens, a sidebar sub-navigation mode (`data-sub-navigation="side"`), and `onThemeChange`, `notifyThemeChange` and `readThemeToken`.
|
||||
* Scaffolded extensions set `preserveSymlinks` so a linked SDK resolves its peer types from the extension.
|
||||
|
||||
|
||||
@@ -20,6 +20,7 @@ use Pterodactyl\Services\Extensions\Scaffolding\ExtensionScaffolder;
|
||||
{--prefix= : Tailwind prefix for the classes of the extension: 2-12 lowercase letters (defaults to one derived from the id).}
|
||||
{--no-ui : Skip the frontend scaffold (backend-only extension).}
|
||||
{--theme : Scaffold a theme: stylesheet, a layout override, a skin, settings and a test.}
|
||||
{--css-only : With --theme: a theme of CSS alone, with no JavaScript entry.}
|
||||
{--out= : Parent directory: the package is created in <out>/<id> (defaults to the extensions directory).}
|
||||
{--path= : The package directory itself, created exactly as given (instead of --out).}
|
||||
{--force : Overwrite the target directory if it already exists.}')]
|
||||
@@ -39,6 +40,7 @@ class MakeCommand extends Command implements PromptsForMissingInput
|
||||
prefix: $this->option('prefix'),
|
||||
theme: (bool) $this->option('theme'),
|
||||
path: $this->option('path'),
|
||||
cssOnly: (bool) $this->option('css-only'),
|
||||
);
|
||||
} catch (InvalidExtensionException $invalidExtensionException) {
|
||||
$this->components->error($invalidExtensionException->getMessage());
|
||||
|
||||
@@ -41,6 +41,7 @@ class ExtensionScaffolder
|
||||
?string $prefix = null,
|
||||
bool $theme = false,
|
||||
?string $path = null,
|
||||
bool $cssOnly = false,
|
||||
): string {
|
||||
$this->files = [];
|
||||
|
||||
@@ -50,6 +51,8 @@ class ExtensionScaffolder
|
||||
|
||||
throw_if($path !== null && $outDir !== null, InvalidExtensionException::class, 'Pass --path (the package directory) or --out (the directory it is created in), not both.');
|
||||
|
||||
throw_if($cssOnly && ! $theme, InvalidExtensionException::class, '--css-only scaffolds a theme: pass it with --theme.');
|
||||
|
||||
$prefix ??= ExtensionManifest::defaultUiPrefix($id);
|
||||
throw_unless($theme || ExtensionManifest::isUsableUiPrefix($prefix), InvalidExtensionException::class, "Tailwind prefix \"{$prefix}\" must match ".ExtensionManifest::UI_PREFIX_REGEX.' and must not be a Tailwind variant, theme namespace or panel name.');
|
||||
|
||||
@@ -74,7 +77,7 @@ class ExtensionScaffolder
|
||||
];
|
||||
|
||||
if ($theme) {
|
||||
$this->scaffoldTheme($target, $id, $replacements);
|
||||
$this->scaffoldTheme($target, $id, $replacements, $cssOnly);
|
||||
$this->validator->fromDirectory($target);
|
||||
|
||||
return $target;
|
||||
@@ -148,12 +151,12 @@ class ExtensionScaffolder
|
||||
|
||||
/**
|
||||
* A theme with a stylesheet for both schemes, a skin, a layout override, four settings and a
|
||||
* test, laid out as the SDK's THEMES.md describes. It needs no PHP; a provider can be
|
||||
* added like an extension's.
|
||||
* test, laid out as the SDK's THEMES.md describes; with `cssOnly`, the stylesheet and settings
|
||||
* alone, with no `ui` entry. It needs no PHP; a provider can be added like an extension's.
|
||||
*
|
||||
* @param array<string, string> $replacements stub placeholder => literal substitution
|
||||
*/
|
||||
private function scaffoldTheme(string $target, string $id, array $replacements): void
|
||||
private function scaffoldTheme(string $target, string $id, array $replacements, bool $cssOnly): void
|
||||
{
|
||||
$manifest = array_filter([
|
||||
'$schema' => './node_modules/@pterodactyl/sdk/manifest.schema.json',
|
||||
@@ -165,7 +168,7 @@ class ExtensionScaffolder
|
||||
'description' => $replacements['{{description}}'] ?: null,
|
||||
'author' => $replacements['{{author}}'] ?: null,
|
||||
'icon' => 'palette',
|
||||
'ui' => ['entry' => ExtensionManifest::UI_ENTRY],
|
||||
'ui' => $cssOnly ? null : ['entry' => ExtensionManifest::UI_ENTRY],
|
||||
'theme' => [
|
||||
'extends' => ThemeRepository::CLASSIC,
|
||||
'stylesheet' => ThemeDefinition::STYLESHEET,
|
||||
@@ -183,7 +186,14 @@ class ExtensionScaffolder
|
||||
$this->files[] = ExtensionManifest::FILENAME;
|
||||
|
||||
$replacements['{{artisan}}'] = $this->artisanPath($target);
|
||||
foreach ([
|
||||
$stubs = $cssOnly ? [
|
||||
'theme-css-package.stub' => 'package.json',
|
||||
'theme-css-vite.config.stub' => 'vite.config.mjs',
|
||||
'postcss.config.stub' => 'postcss.config.mjs',
|
||||
'theme-css.stub' => 'src/theme.css',
|
||||
'gitignore.stub' => '.gitignore',
|
||||
'theme-css-readme.stub' => 'README.md',
|
||||
] : [
|
||||
'theme-package.stub' => 'package.json',
|
||||
'theme-vite.config.stub' => 'vite.config.mjs',
|
||||
'postcss.config.stub' => 'postcss.config.mjs',
|
||||
@@ -196,7 +206,8 @@ class ExtensionScaffolder
|
||||
'theme-test.stub' => 'src/theme.spec.tsx',
|
||||
'gitignore.stub' => '.gitignore',
|
||||
'theme-readme.stub' => 'README.md',
|
||||
] as $stub => $relative) {
|
||||
];
|
||||
foreach ($stubs as $stub => $relative) {
|
||||
$this->stub($target, $stub, $relative, $replacements);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,20 @@
|
||||
{
|
||||
"name": "{{id}}",
|
||||
"private": true,
|
||||
"version": "1.0.0",
|
||||
"type": "module",
|
||||
"scripts": {
|
||||
"build": "vite build",
|
||||
"dev": "vite build --watch",
|
||||
"doctor": "php {{artisan}} p:extension:doctor .",
|
||||
"pack": "php {{artisan}} p:extension:pack . --force"
|
||||
},
|
||||
"devDependencies": {
|
||||
"@pterodactyl/sdk": "{{sdkDependency}}",
|
||||
"vite": "^8",
|
||||
"tailwindcss": "^4.3.0",
|
||||
"@tailwindcss/forms": "^0.5.2",
|
||||
"@tailwindcss/postcss": "^4",
|
||||
"postcss": "^8.5.6"
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,33 @@
|
||||
# {{name}}
|
||||
|
||||
A Pterodactyl panel theme of CSS alone, scaffolded by `p:extension:make --theme --css-only`. Level 1 of
|
||||
the themes guide, `node_modules/@pterodactyl/sdk/THEMES.md`, covers it: colours, fonts, radius and
|
||||
spacing, for dark and light. Skins and views (levels 2 to 4) need a theme scaffolded without `--css-only`.
|
||||
|
||||
## Files
|
||||
|
||||
| File | |
|
||||
| --- | --- |
|
||||
| `extension.json` | The manifest. `"type": "theme"` and its `theme` section declare the stylesheet, the colour schemes and the settings. |
|
||||
| `src/theme.css` | The panel stylesheet with this theme's tokens and classes. Plain Tailwind, no prefix. |
|
||||
|
||||
## Scripts
|
||||
|
||||
| Script | |
|
||||
| --- | --- |
|
||||
| `npm run build` | `dist/theme.css` and `dist/theme.json`. |
|
||||
| `npm run dev` | Rebuilds on change; `p:extension:dev --watch` runs it. |
|
||||
| `npm run doctor` | The panel's checks: manifest, build, budgets and remote URLs. |
|
||||
| `npm run pack` | Packs a `.pteroext` archive to install on another panel. |
|
||||
|
||||
## Develop
|
||||
|
||||
```sh
|
||||
npm install
|
||||
php {{artisan}} p:extension:dev . --enable
|
||||
php {{artisan}} p:theme:activate {{id}}
|
||||
php {{artisan}} p:extension:dev . --watch
|
||||
```
|
||||
|
||||
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.
|
||||
@@ -0,0 +1,4 @@
|
||||
import { defineThemeConfig } from '@pterodactyl/sdk/vite';
|
||||
|
||||
// A theme of CSS alone: no entry, so the build writes dist/theme.css and dist/theme.json.
|
||||
export default defineThemeConfig({ stylesheet: 'src/theme.css' });
|
||||
@@ -1,163 +0,0 @@
|
||||
# Theme fixes from the first dogfood: doc notes
|
||||
|
||||
Notes for the THEMES.md and README chapters. Each section says what changed and what the docs should say.
|
||||
|
||||
## The app shell knows the area (`layout.app` model `area`)
|
||||
|
||||
`AppLayoutModel.area` says where the user is and carries the model of that area's own layout:
|
||||
|
||||
```ts
|
||||
type AppArea =
|
||||
| { kind: 'dashboard' } // the dashboard and any page outside the areas below
|
||||
| ({ kind: 'account' } & AccountLayoutModel) // { nav }
|
||||
| ({ kind: 'server' } & ServerLayoutModel) // { name, identifier, uuid, internalId, state, conflict, adminLink, nav, server }
|
||||
| ({ kind: 'admin' } & AdminLayoutModel); // { nav, user }
|
||||
```
|
||||
|
||||
- `nav.items` are the same items the area's layout gets: filtered by subuser permissions and egg rules.
|
||||
Render them with `<Navigation items={area.nav.items}>`, which applies extension screen gates and badges.
|
||||
- A sidebar theme draws every navigation in `layout.app` and overrides `layout.server`, `layout.account`
|
||||
and `layout.admin` with thin layouts, e.g. `({ children }) => <Main>{children}</Main>`.
|
||||
Render the area's slots (`server.navigation.before/after` with `data={area.server}`,
|
||||
`account.navigation.*`, `panel.navigation.*`) where the shell draws that navigation. The dev-mode
|
||||
"renders none of its slots" check counts slots a view's enclosing views render, so a thin layout does
|
||||
not warn when the shell renders its slots.
|
||||
- Fixtures: `layout.app` has `accountArea`, `serverArea` and `adminArea` besides the dashboard ones
|
||||
(`user`, `admin`, `schemes`, `logo`).
|
||||
|
||||
Recipe (sidebar part):
|
||||
|
||||
```tsx
|
||||
function AreaNav({ area }: { area: AppArea }) {
|
||||
if (area.kind === 'dashboard') return null;
|
||||
const items = area.kind === 'server' && area.adminLink ? [...area.nav.items, area.adminLink] : area.nav.items;
|
||||
|
||||
return (
|
||||
<nav aria-label={area.kind === 'server' ? area.name : 'Section'}>
|
||||
{area.kind === 'server' && <Badge>{area.state ?? 'unknown'}</Badge>}
|
||||
<Navigation items={items}>
|
||||
{(item, { badge }) => (
|
||||
<NavigationLink item={item}>
|
||||
{item.icon && <NamedIcon name={item.icon} size={16} aria-hidden />}
|
||||
{item.label}
|
||||
{badge}
|
||||
</NavigationLink>
|
||||
)}
|
||||
</Navigation>
|
||||
</nav>
|
||||
);
|
||||
}
|
||||
```
|
||||
|
||||
## Server power state on `layout.server` (`state`, `uuid`)
|
||||
|
||||
`ServerLayoutModel` gained `uuid` and `state: ServerRunState | null` (`'offline' | 'starting' | 'running' |
|
||||
'stopping'`, as `server.power` and `server.stats` name it). It is the cached resources query, fetched once
|
||||
when the server opens and kept live by the server's websocket, which now writes every `status` event into
|
||||
that cache (so dashboard cards returning from a server show the latest state too). Fixtures: `owner`,
|
||||
`subuser`, `admin` are `running`; new `offline`; `installing` and `suspended` are `offline`.
|
||||
|
||||
## `<Main>`
|
||||
|
||||
- Exactly one `<main>` renders, from the outermost `<Main>`; nested ones render their children in place.
|
||||
- A nested `<Main className="…">` now keeps its classes on a `<div>` around its children instead of dropping
|
||||
them. A nested `<Main>` without a class adds no element.
|
||||
|
||||
## Failing layers
|
||||
|
||||
- A theme or extension layer that throws falls back to the layer below once. If a layer below the failed
|
||||
one throws too (classic included), the panel's standard error notice renders for that view, with a
|
||||
Retry that tries the failed layer again. Nothing re-renders in a loop (before, an effect throwing in
|
||||
classic under a failed theme layer re-mounted forever, e.g. `server.graphs` without `ResizeObserver`).
|
||||
- Each failure logs one `console.error`: `[extensions] "<layer id>" failed in view "<view>": <error>`.
|
||||
- The inspector is gone (see below); the console line is how to spot a failing layer.
|
||||
|
||||
## Strict test renderers
|
||||
|
||||
- `renderView(name, options)` throws when the view fails to render, and when any theme or extension
|
||||
layer throws: `The "theme" layer of view "server.graphs" failed: <message>` (a `ViewLayerError` with
|
||||
`view`, `layer` and `cause`). Nested views count. `{ strict: false }` lets layers fall back as in the
|
||||
panel. Failures after the first render (say on a click) are thrown by `unmount()`.
|
||||
- `createViewTestHost(name, options)` is strict too: the layer under test or a nested layer that throws
|
||||
fails the render (the error propagates out of RTL's `render`/`act`). `{ strict: false }` opts out.
|
||||
- `ViewLayerError` is exported from `@pterodactyl/sdk/testing`.
|
||||
- `renderView(name, { slots: { 'server.navigation.before': () => <span>probe</span> } })` mounts
|
||||
components in slots as an extension's `slots.register` would, typed per slot; they are removed on
|
||||
unmount. Use it to test that a view renders the slots it replaces.
|
||||
- The SDK's Vitest setup (`pterodactylTestSetup`) now provides `ResizeObserver`, `IntersectionObserver`
|
||||
(inert) and `matchMedia` (matches nothing) besides `PointerEvent` and `scrollTo`. Theme tests need no
|
||||
stubs; `vi.stubGlobal` still replaces them where a test drives them.
|
||||
- `usePanelLocation()` works in views rendered from fixtures (tests): outside a route it returns the
|
||||
path with empty `params` and `search` instead of throwing.
|
||||
|
||||
## Navigation details
|
||||
|
||||
- Every core nav item has an `icon` (lucide name for `NamedIcon`):
|
||||
- account: Account `user-round`, API Credentials `key-round`, SSH Keys `terminal`, Activity `history`;
|
||||
- server: Console `square-terminal`, Files `folder`, Databases `database`, Schedules `calendar-clock`,
|
||||
Users `users`, Backups `archive`, Network `network`, Startup `rocket`, Settings `settings`,
|
||||
Activity `history`; the admin link stays `external-link`;
|
||||
- admin: Activity is now `history` (the rest had icons already).
|
||||
- `AppLayoutLink.icon`: dashboard `layers`, admin `user-cog`, account `user-round`.
|
||||
Classic still shows its account and server tabs as text (extension screens keep their icons), through
|
||||
`views/layout/tabLabel.tsx`, which `eject` copies with those layouts; its admin sidebar now shows the
|
||||
history icon for Activity instead of the fallback puzzle.
|
||||
- `DropdownMenu.Item` takes `destination` (a `PanelDestination`): the item renders as a link (`<a href>`,
|
||||
`role="menuitem"`, same skin parts) that navigates and closes the menu.
|
||||
`<DropdownMenu.Item destination={{ to: '/account' }}>Account</DropdownMenu.Item>`
|
||||
- Closing a drawer on navigation: an effect on the path, which also works in tests.
|
||||
|
||||
```tsx
|
||||
const { pathname } = usePanelLocation();
|
||||
useEffect(() => setOpen(false), [pathname]);
|
||||
```
|
||||
|
||||
No `useOnNavigate` hook was added; this is two lines and needs no new concept.
|
||||
|
||||
## Layout spacing tokens
|
||||
|
||||
- `--layout-gutter` (default `calc(var(--spacing) * 4)`): page content's side margin until it centres.
|
||||
- `--layout-content-width` (existing): its maximum width (`max-w-panel`).
|
||||
- `page-width` utility: the geometry `PageContentBlock` and `ServerContentBlock` use (max width
|
||||
`--layout-content-width`, `--layout-gutter` at the sides, centred from `xl`). Put it on a layout's own
|
||||
header to line up with the pages below: `<header className="page-width mt-4 sm:mt-6">`.
|
||||
Core renders exactly as before.
|
||||
|
||||
## Palette
|
||||
|
||||
`text-white`, `bg-black/15` etc. work in theme builds again: `--color-white` and `--color-black` are
|
||||
defined after the palette reset. `transparent`, `current` and `inherit` always worked. The rest of
|
||||
Tailwind's default palette stays removed; add colours in `@theme` as before. Core's compiled CSS is
|
||||
unchanged.
|
||||
|
||||
## Packaging
|
||||
|
||||
- `defineThemeConfig({ …, sourcemap })`: off by default for themes, because a map embeds the sources.
|
||||
`sourcemap: true` turns it on (e.g. for a private build). Extensions keep `sourcemap: true`.
|
||||
- `p:extension:pack` leaves `*.map` files out of the archive unless given `--sourcemaps`.
|
||||
- The theme scaffold's `npm run pack` passes `--force`, so re-packing replaces the archive, and its
|
||||
`.gitignore` (shared with extensions) ignores `*.pteroext`.
|
||||
|
||||
## Scaffold paths
|
||||
|
||||
- `p:extension:make <id> --path=<dir>` creates the package in exactly `<dir>`.
|
||||
- `--out=<dir>` (unchanged) is the parent: the package goes in `<dir>/<id>`. `--help` says so.
|
||||
- Passing both fails before writing anything.
|
||||
|
||||
## Removed: the theme workbench
|
||||
|
||||
`/panel/theme-workbench`, `page.admin.themeWorkbench`, the workbench components, the UI-kit gallery
|
||||
(`themes/gallery.tsx`), preview frames and the portal-container context that sent overlays into them,
|
||||
and the Workbench button on the Themes page are gone. View fixtures, `renderView`, `renderPrimitive`
|
||||
(same primitive names), `createViewTestHost` and `preloadTheme` remain; tests are the way to render views
|
||||
without a backend. Docs should drop the workbench section, its URL parameters (`view`, `fixture`, `scheme`,
|
||||
`width`, `ui`) and the scaffold README's mention (done in the stub). `Portal` renders into
|
||||
`#modal-portal`, or the body where there is none (as in tests), so `createViewTestHost` no longer adds a
|
||||
`#modal-portal` for the file manager. Dialogs, menus, selects and tooltips portal into the body again.
|
||||
The planned `useViewDocument()` hook and the `width=` URL parameter fix were dropped with the workbench.
|
||||
|
||||
## Removed: the inspector
|
||||
|
||||
The Alt-click inspector, its floating button, the `data-view` wrappers, the view probes
|
||||
(`ViewInspectionContext`), `?inspect=1` and `SiteConfiguration.theme.inspect` (server payload and client
|
||||
type) are gone. Failing layers log a `console.error` naming the view and the layer instead.
|
||||
@@ -240,11 +240,14 @@ shows while the extension is disabled, and `p:extension:pack` adds it to the arc
|
||||
|
||||
## Author tooling and configuration
|
||||
|
||||
Use `p:extension:doctor <path>`, `p:extension:dev <path> --watch`, and
|
||||
`p:extension:make <id>` scaffolds a package in `extensions/<id>`; `--out=<dir>` creates it in
|
||||
`<dir>/<id>` and `--path=<dir>` in exactly `<dir>`. Use `p:extension:doctor <path>`, `p:extension:dev <path> --watch`, and
|
||||
`p:extension:pack <path>` for preflight checks, successful-build publishing with browser reload in debug mode, and
|
||||
runtime-only archives. Scaffolds include tests, CI, OpenAPI generation, and styling.
|
||||
runtime-only archives; pack leaves `*.map` files out unless given `--sourcemaps`, since a map can embed
|
||||
your sources. Scaffolds include tests, CI, OpenAPI generation, and styling.
|
||||
`@pterodactyl/sdk/testing` supplies `createExtensionTestHost` and `createTestServer`;
|
||||
`@pterodactyl/sdk/vitest` supplies aliases and setup for the real runtime. Unmount the
|
||||
`@pterodactyl/sdk/vitest` supplies aliases and setup for the real runtime, including the
|
||||
`ResizeObserver`, `IntersectionObserver` and `matchMedia` jsdom lacks. Unmount the
|
||||
wrapper and dispose the host after each test. The test host shares the real cache;
|
||||
create one host at a time within a test environment.
|
||||
|
||||
@@ -924,9 +927,9 @@ export default function Browser({ model, parts }: ViewProps<'server.files.manage
|
||||
|
||||
### Loading and failure
|
||||
|
||||
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.
|
||||
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 falls back to the layer below once; if that one throws too, the view shows the panel's error notice with a Retry. Each failure logs `[extensions] "<id>" failed in view "<view>": <error>` to the browser console. 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.
|
||||
The testing entry exports `createViewTestHost(name, { model?, fixture?, input?, extensionId?, prefix?, strict? })`, 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. The render fails with a `ViewLayerError` when your layer or a nested view's layer throws; `strict: false` lets it fall back as in the panel. `renderView` and its `slots` option, which mounts test components in slots, are described under [Testing](THEMES.md#testing).
|
||||
|
||||
## UI kit
|
||||
|
||||
|
||||
+215
-112
@@ -44,7 +44,8 @@ classic the stock panel
|
||||
```
|
||||
|
||||
Render `<Default />` to keep what is below and add to it; leave it out to replace it. A layer that
|
||||
throws is reported and the layer below renders instead. Whatever you do not override stays classic.
|
||||
throws gives way to the layer below ([Fallback](#fallback-and-safe-mode)). Whatever you do not override
|
||||
stays classic.
|
||||
|
||||
| I want to … | Go to |
|
||||
| --- | --- |
|
||||
@@ -64,14 +65,17 @@ From the panel's root directory, five commands scaffold a theme, build and insta
|
||||
and rebuild it on every change:
|
||||
|
||||
```sh
|
||||
php artisan p:extension:make sunrise --theme
|
||||
php artisan p:extension:make sunrise --theme --css-only
|
||||
cd extensions/sunrise && npm install
|
||||
php ../../artisan p:extension:dev . --enable
|
||||
php ../../artisan p:theme:activate sunrise
|
||||
php ../../artisan p:extension:dev . --watch
|
||||
```
|
||||
|
||||
While the last one runs on a panel with `APP_DEBUG=true`, a stylesheet change swaps into open pages
|
||||
`--css-only` leaves out the JavaScript that levels 2 to 4 need. The package goes in
|
||||
`extensions/sunrise`; `--path=<dir>` puts it in exactly `<dir>`, and `--out=<dir>` in `<dir>/sunrise`.
|
||||
|
||||
While the last command runs on a panel with `APP_DEBUG=true`, a stylesheet change swaps into open pages
|
||||
without a reload, and any other change reloads them. To try a theme without switching everyone to it,
|
||||
skip `p:theme:activate` and choose **Preview for me** on **Admin > Themes**.
|
||||
|
||||
@@ -86,8 +90,9 @@ A **token** is a CSS custom property the panel's classes read. Set one and every
|
||||
changes: `--primary` colours primary buttons and selected items, `--radius` sets every rounded corner,
|
||||
and `--spacing` scales every padding, margin and gap. [Tokens](#tokens) lists them all.
|
||||
|
||||
The colour classes are roles such as `bg-card` and `text-muted-foreground`; Tailwind's palette is not
|
||||
there. Add a colour of your own in `@theme`: `--color-brand: oklch(0.7 0.2 300);` gives `bg-brand`.
|
||||
The colour classes are roles such as `bg-card` and `text-muted-foreground`. Of Tailwind's palette only
|
||||
`white` and `black` remain (`text-white`, `bg-black/15`). Add a colour of your own in `@theme`:
|
||||
`--color-brand: oklch(0.7 0.2 300);` gives `bg-brand`.
|
||||
|
||||
### Dark and light
|
||||
|
||||
@@ -102,9 +107,6 @@ Ship font files with the theme and reference them relative to the stylesheet; th
|
||||
beside `dist/theme.css`. Set `--font-sans` (body) and `--font-header` (headings) in `@theme`. Fonts from
|
||||
another origin, such as a CDN, are refused.
|
||||
|
||||
The build warns that `/assets/fonts/ibm-plex-sans-latin-wght-normal.woff2` did not resolve. That is the
|
||||
panel's own font, served by the panel, and the warning is expected.
|
||||
|
||||
### A complete level 1 theme
|
||||
|
||||
<!-- sample: level1-css/src/theme.css -->
|
||||
@@ -177,15 +179,18 @@ panel's own font, served by the panel, and the warning is expected.
|
||||
```
|
||||
<!-- /sample -->
|
||||
|
||||
This theme has no JavaScript: its manifest has no `ui` and its `vite.config.mjs` no `entry`. The
|
||||
scaffold also writes `src/theme.tsx`, with a skin and a layout layer, for the later levels; the build
|
||||
ignores it once those two lines are gone. [`docs-samples/level1-css`](docs-samples/level1-css) in the
|
||||
panel repository holds the files.
|
||||
The manifest has no `ui` and `vite.config.mjs` no `entry`, so the build writes only the stylesheet;
|
||||
`--css-only` scaffolds a theme this way. [`docs-samples/level1-css`](docs-samples/level1-css) in the panel
|
||||
repository holds the files.
|
||||
|
||||
You now have a theme.
|
||||
|
||||
## Level 2: restyle components
|
||||
|
||||
From this level on, a theme has JavaScript: `src/theme.tsx`, built to the `dist/client.js` that the
|
||||
manifest's `ui.entry` names. Scaffold without `--css-only` to get it, with a skin, a layout and a test
|
||||
to start from; a level 1 theme moves over by copying its `src/theme.css` into the new package.
|
||||
|
||||
The panel draws its interface with a UI kit of 28 **primitives**, such as `Button`, `Card` and `Dialog`.
|
||||
Extensions use them too, so restyling a primitive restyles it everywhere.
|
||||
|
||||
@@ -364,14 +369,14 @@ that does not exist logs a warning, and a recipe that throws renders no classes.
|
||||
|
||||
## Level 3: change the layout
|
||||
|
||||
A **view** is a named piece of the interface, rendered by a stack of layers. A **layout** view frames
|
||||
the pages of an area:
|
||||
A **view** is a named piece of the interface, rendered by a stack of layers. A **layout** view frames a
|
||||
set of pages:
|
||||
|
||||
| Layout | Frames | Its model has |
|
||||
| --- | --- | --- |
|
||||
| `layout.app` | Every signed-in page | `brand`, `links`, `user`, the scheme, `signOut` |
|
||||
| `layout.app` | Every signed-in page | `brand`, `links`, `area`, `user`, the scheme, `signOut` |
|
||||
| `layout.account` | The account pages, inside `layout.app` | `nav` |
|
||||
| `layout.server` | A server's pages, inside `layout.app` | `name`, `nav`, `conflict`, `server` |
|
||||
| `layout.server` | A server's pages, inside `layout.app` | `name`, `state`, `nav`, `conflict`, `server` |
|
||||
| `layout.admin` | The admin area, inside `layout.app` | `nav`, `user` |
|
||||
| `layout.auth` | The sign-in pages | `brand` |
|
||||
|
||||
@@ -381,117 +386,191 @@ types these props. Register views by name:
|
||||
|
||||
<!-- sample: level3-sidebar/src/theme.tsx -->
|
||||
```tsx
|
||||
import { defineTheme, lazyView } from '@pterodactyl/sdk/theme';
|
||||
import type { ReactNode } from 'react';
|
||||
import { Main, defineTheme, lazyView } from '@pterodactyl/sdk/theme';
|
||||
|
||||
/** The shell draws every area's navigation, so an area's layout only places its pages. */
|
||||
function AreaLayout({ children }: { children?: ReactNode }) {
|
||||
return <Main>{children}</Main>;
|
||||
}
|
||||
|
||||
export default defineTheme({
|
||||
views: {
|
||||
'layout.app': lazyView(() => import('./views/Shell')),
|
||||
'layout.account': lazyView(() => import('./views/AccountLayout')),
|
||||
'layout.server': AreaLayout,
|
||||
'layout.account': AreaLayout,
|
||||
'layout.admin': AreaLayout,
|
||||
},
|
||||
});
|
||||
```
|
||||
<!-- /sample -->
|
||||
|
||||
`lazyView` loads a view's code the first time it renders (see [Level 4](#loading-with-lazyview)).
|
||||
[The shell knows the area](#the-shell-knows-the-area) explains `AreaLayout`.
|
||||
|
||||
### `<Main>`
|
||||
|
||||
A layout places `children` inside `<Main>`, which renders `<main id="main" tabIndex={-1}>`: the target of
|
||||
the skip link, which the engine focuses after each navigation while it announces the new page title.
|
||||
Layouts nest, and only the outermost `<Main>` renders the element. In development, a layout that never
|
||||
renders `<Main>` logs a warning.
|
||||
Layouts nest, and only the outermost `<Main>` renders the element; a nested one renders its children in
|
||||
place, in a `<div>` when it has a `className`. In development, a layout that never renders `<Main>` logs
|
||||
a warning.
|
||||
|
||||
### Navigation and the brand
|
||||
|
||||
`layout.app` has `model.links` (the dashboard, the admin area for root admins, and the account) and
|
||||
`model.brand`, the panel's `name` and a `logoUrl` (see [Branding](#branding)).
|
||||
|
||||
The other layouts have `model.nav.items`: the area's `NavItem`s, filtered by subuser permissions and egg
|
||||
rules, extension screens included. `<Navigation>` calls its child with each item and `{ active, badge }`,
|
||||
and keeps an extension screen hidden until its runtime condition allows it. `NavigationLink` links to
|
||||
an item and carries `data-status="active"` while the item is active.
|
||||
The other layouts each frame an **area**, a part of the panel with navigation of its own: the account, a
|
||||
server, or the admin area. They have `model.nav.items`: the area's `NavItem`s, filtered by subuser
|
||||
permissions and egg rules, extension screens included. Links and items have an `icon`, a lucide name for
|
||||
`<NamedIcon>`.
|
||||
`<Navigation>` calls its child with each item and `{ active, badge }`, and keeps an extension screen
|
||||
hidden until its runtime condition allows it. `NavigationLink` links to an item and carries
|
||||
`data-status="active"` while the item is active. [`AreaNav`](#the-shell-knows-the-area) below uses both.
|
||||
|
||||
<!-- sample: level3-sidebar/src/views/AccountLayout.tsx#account -->
|
||||
`useNavigation('account' | 'server' | 'admin')` returns an area's items outside its layout. Classic's tab
|
||||
bar, which folds items that do not fit into a menu, is `SubNavigation` with `SubNavigationLayout` from
|
||||
`@pterodactyl/sdk`. In a menu of your own, `<DropdownMenu.Item destination={{ to: '/account' }}>` is a
|
||||
link that navigates and closes the menu.
|
||||
|
||||
### The shell knows the area
|
||||
|
||||
`model.area` of `layout.app` says which area the user is in: `kind` is `account`, `server` or `admin`,
|
||||
with the model of that area's layout beside it, or `dashboard` on the dashboard and any page outside an
|
||||
area. So `layout.app` can draw every area's navigation itself, in one sidebar. The theme then overrides
|
||||
`layout.account`, `layout.server` and `layout.admin` with a **thin layout**, which places the page in
|
||||
`<Main>` and nothing else (`AreaLayout` above).
|
||||
|
||||
A layer that replaces a view renders the view's slots, listed in the [catalogue](#view-catalogue), or
|
||||
the extensions mounted there disappear. The area layouts' slots sit in their navigation, so the shell
|
||||
renders them where it draws that navigation (`AreaSlot` below). In development, a layer that renders
|
||||
none of its view's slots logs a warning after three seconds; slots an enclosing view renders count, so
|
||||
the thin layouts do not warn.
|
||||
|
||||
<!-- sample: level3-sidebar/src/views/AreaNav.tsx -->
|
||||
```tsx
|
||||
/** The account pages with a vertical menu. `model.nav` lists them, extension screens included. */
|
||||
export default function AccountLayout({ model, children }: ViewProps<'layout.account'>) {
|
||||
import { Badge, NamedIcon } from '@pterodactyl/sdk';
|
||||
import { Navigation, NavigationLink, Slot, type AppArea } from '@pterodactyl/sdk/theme';
|
||||
|
||||
type Area = Exclude<AppArea, { kind: 'dashboard' }>;
|
||||
|
||||
const link = [
|
||||
'flex items-center gap-3 rounded-lg px-3 py-2 text-sm text-muted-foreground no-underline',
|
||||
'hover:bg-popover hover:text-foreground data-[status=active]:bg-primary/15 data-[status=active]:text-foreground',
|
||||
].join(' ');
|
||||
|
||||
/** The slots of the area's navigation, which its own layout would render if it drew the navigation. */
|
||||
function AreaSlot({ area, at }: { area: Area; at: 'before' | 'after' }) {
|
||||
if (area.kind === 'server') return <Slot name={`server.navigation.${at}`} data={area.server} />;
|
||||
if (area.kind === 'account') return <Slot name={`account.navigation.${at}`} />;
|
||||
return <Slot name={`panel.navigation.${at}`} />;
|
||||
}
|
||||
|
||||
/** The pages of the area the user is in: a server's, the account's or the admin area's. */
|
||||
export default function AreaNav({ area }: { area: AppArea }) {
|
||||
if (area.kind === 'dashboard') return null;
|
||||
|
||||
const items = area.kind === 'server' && area.adminLink ? [...area.nav.items, area.adminLink] : area.nav.items;
|
||||
const label = { server: 'Server', account: 'Account', admin: 'Administration' }[area.kind];
|
||||
|
||||
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 gap-2 rounded-lg px-3 py-2', active && 'bg-muted')}
|
||||
>
|
||||
{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'>{children}</Main>
|
||||
</div>
|
||||
<nav aria-label={label} className='flex flex-col gap-1'>
|
||||
{area.kind === 'server' && (
|
||||
<p className='flex items-center gap-2 px-3 pb-1 text-sm font-semibold'>
|
||||
<span className='min-w-0 flex-1 truncate'>{area.name}</span>
|
||||
<Badge size='sm' tone={area.state === 'running' ? 'success' : 'neutral'}>
|
||||
{area.state ?? 'unknown'}
|
||||
</Badge>
|
||||
</p>
|
||||
)}
|
||||
<AreaSlot area={area} at='before' />
|
||||
<Navigation items={items}>
|
||||
{(item, { badge }) => (
|
||||
<NavigationLink item={item} className={link}>
|
||||
{item.icon && <NamedIcon name={item.icon} size={16} aria-hidden />}
|
||||
<span className='min-w-0 flex-1 truncate'>{item.label}</span>
|
||||
{badge}
|
||||
</NavigationLink>
|
||||
)}
|
||||
</Navigation>
|
||||
<AreaSlot area={area} at='after' />
|
||||
</nav>
|
||||
);
|
||||
}
|
||||
```
|
||||
<!-- /sample -->
|
||||
|
||||
`useNavigation('account' | 'server' | 'admin')` returns an area's items outside its layout. Classic's tab
|
||||
bar, which folds items that do not fit into a menu, is `SubNavigation` with `SubNavigationLayout` from
|
||||
`@pterodactyl/sdk`.
|
||||
The fixtures `accountArea`, `serverArea` and `adminArea` of `layout.app` render the shell in each area.
|
||||
|
||||
### A sidebar shell
|
||||
|
||||
A complete `layout.app`: the brand, the links between their slots, the panel's search, the user, the
|
||||
scheme switch, sign-out, and the page in `<Main>`. `w-sidebar` reads `--layout-sidebar-width` and
|
||||
`bg-sidebar` reads `--sidebar`.
|
||||
A complete `layout.app`: the brand, the links between their slots, the area's navigation, the panel's
|
||||
search, the user, the scheme switch, sign-out, and the page in `<Main>`. `w-sidebar` reads
|
||||
`--layout-sidebar-width` and `bg-sidebar` reads `--sidebar`. Below the `lg` breakpoint the sidebar is a
|
||||
drawer, which an effect on `usePanelLocation().pathname` closes when one of its links navigates.
|
||||
|
||||
<!-- sample: level3-sidebar/src/views/Shell.tsx -->
|
||||
```tsx
|
||||
import { LayoutGrid, LogOut, Moon, Shield, Sun, UserRound, type LucideIcon } from 'lucide-react';
|
||||
import { Avatar, PanelLink, SpinnerOverlay } from '@pterodactyl/sdk';
|
||||
import { Main, Slot, View, type AppLayoutLink, type ViewProps } from '@pterodactyl/sdk/theme';
|
||||
|
||||
const icons: Record<AppLayoutLink['id'], LucideIcon> = { dashboard: LayoutGrid, admin: Shield, account: UserRound };
|
||||
import { useEffect, useState } from 'react';
|
||||
import { LogOut, Menu, Moon, Sun } from 'lucide-react';
|
||||
import { Avatar, NamedIcon, PanelLink, SpinnerOverlay, cn, usePanelLocation } from '@pterodactyl/sdk';
|
||||
import { Main, Slot, View, type ViewProps } from '@pterodactyl/sdk/theme';
|
||||
import AreaNav from './AreaNav';
|
||||
|
||||
const item = [
|
||||
'flex items-center gap-3 rounded-lg px-3 py-2 text-sm text-muted-foreground no-underline',
|
||||
'hover:bg-popover hover:text-foreground data-[status=active]:bg-primary/15 data-[status=active]:text-foreground',
|
||||
].join(' ');
|
||||
|
||||
/** A sidebar on large screens and a top bar below them, with the page beside it. */
|
||||
/** A sidebar beside the page on large screens, and a drawer behind a menu button below them. */
|
||||
export default function Shell({ model, children }: ViewProps<'layout.app'>) {
|
||||
const { brand, user, scheme, setScheme } = model;
|
||||
const SchemeIcon = scheme === 'dark' ? Sun : Moon;
|
||||
const [open, setOpen] = useState(false);
|
||||
const { pathname } = usePanelLocation();
|
||||
|
||||
// Close the drawer when one of its links navigates.
|
||||
useEffect(() => setOpen(false), [pathname]);
|
||||
|
||||
return (
|
||||
<div className='flex min-h-dvh flex-col lg:flex-row'>
|
||||
<div className='min-h-dvh lg:flex'>
|
||||
<SpinnerOverlay visible={model.signingOut} fixed />
|
||||
<aside className='flex shrink-0 items-center gap-2 bg-sidebar p-3 lg:sticky lg:top-0 lg:h-dvh lg:w-sidebar lg:flex-col lg:items-stretch lg:p-4'>
|
||||
<button
|
||||
type='button'
|
||||
aria-expanded={open}
|
||||
aria-controls='sidebar'
|
||||
onClick={() => setOpen(!open)}
|
||||
className={cn(item, 'm-2 lg:hidden')}
|
||||
>
|
||||
<Menu className='size-4' aria-hidden />
|
||||
Menu
|
||||
</button>
|
||||
<aside
|
||||
id='sidebar'
|
||||
className={cn(
|
||||
'flex-col gap-4 bg-sidebar p-4 lg:sticky lg:top-0 lg:flex lg:h-dvh lg:w-sidebar lg:shrink-0 lg:overflow-y-auto',
|
||||
open ? 'flex' : 'hidden'
|
||||
)}
|
||||
>
|
||||
<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>
|
||||
<nav aria-label='Main' className='flex flex-1 gap-1 lg:flex-col'>
|
||||
<nav aria-label='Main' className='flex flex-col gap-1'>
|
||||
<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={item}>
|
||||
<Glyph className='size-4' aria-hidden />
|
||||
<span className='max-lg:sr-only'>{link.label}</span>
|
||||
</PanelLink>
|
||||
);
|
||||
})}
|
||||
{model.links.map((link) => (
|
||||
<PanelLink key={link.id} destination={link.destination} exact={link.exact} className={item}>
|
||||
<NamedIcon name={link.icon} size={16} aria-hidden />
|
||||
{link.label}
|
||||
</PanelLink>
|
||||
))}
|
||||
<Slot name='nav.items.after' />
|
||||
</nav>
|
||||
<AreaNav area={model.area} />
|
||||
<View name='app.search' className={item} />
|
||||
<div className='flex items-center gap-2'>
|
||||
<div className='mt-auto flex items-center gap-2'>
|
||||
<Avatar name={user.uuid} size={28} />
|
||||
<span className='min-w-0 flex-1 truncate text-sm max-lg:sr-only'>{user.username}</span>
|
||||
<span className='min-w-0 flex-1 truncate text-sm'>{user.username}</span>
|
||||
{/* setScheme is null unless the theme offers both schemes. */}
|
||||
{setScheme && (
|
||||
<button
|
||||
@@ -500,11 +579,7 @@ export default function Shell({ model, children }: ViewProps<'layout.app'>) {
|
||||
onClick={() => setScheme(scheme === 'dark' ? 'light' : 'dark')}
|
||||
className={item}
|
||||
>
|
||||
{scheme === 'dark' ? (
|
||||
<Sun className='size-4' aria-hidden />
|
||||
) : (
|
||||
<Moon className='size-4' aria-hidden />
|
||||
)}
|
||||
<SchemeIcon className='size-4' aria-hidden />
|
||||
</button>
|
||||
)}
|
||||
<button type='button' aria-label='Sign out' onClick={model.signOut} className={item}>
|
||||
@@ -519,6 +594,12 @@ export default function Shell({ model, children }: ViewProps<'layout.app'>) {
|
||||
```
|
||||
<!-- /sample -->
|
||||
|
||||
### Lining up with the page
|
||||
|
||||
Page content is at most `--layout-content-width` wide, with `--layout-gutter` at the sides until it
|
||||
centres from the `xl` breakpoint. The `page-width` class applies the same geometry, so a header a
|
||||
layout draws above its pages lines up with them: `<header className="page-width mt-4 sm:mt-6">`.
|
||||
|
||||
## Level 4: rebuild pages
|
||||
|
||||
A **page** view renders one route, such as `page.server.console`. A **block** view is a piece of a page,
|
||||
@@ -583,11 +664,9 @@ for blocks that extensions define. A layer for such a view is typed loosely: its
|
||||
|
||||
### Slots in your views
|
||||
|
||||
A layer that replaces a view renders that view's slots, listed in the [catalogue](#view-catalogue), so
|
||||
extensions mounted there keep their place. The models carry what the slots receive:
|
||||
`<Slot name="server.console.before" data={model.server} />`. `<Default />` renders the slots of the
|
||||
layers below. In development, a layer that renders none of its view's slots logs a warning after three
|
||||
seconds.
|
||||
A layer that replaces a view renders its slots ([level 3](#the-shell-knows-the-area)); `<Default />`
|
||||
renders the slots of the layers below. The models carry what the slots receive:
|
||||
`<Slot name="server.console.before" data={model.server} />`.
|
||||
|
||||
The **engine slots** of a page, listed in their own column of the catalogue, are rendered by the engine
|
||||
before and after the page view, so a layer neither renders nor drops them.
|
||||
@@ -599,15 +678,17 @@ router preloads it with its route; `lazyView(importer, 'Name')` takes a named ex
|
||||
loads, the view shows its placeholder. If it fails, the layer below renders.
|
||||
|
||||
The panel loads the theme entry before its first render, so keep it small. Make every view lazy except
|
||||
`layout.auth`, which renders before anything else, and import only `@pterodactyl/sdk/theme` in the
|
||||
modules the entry loads eagerly. Views that use components from `@pterodactyl/sdk` belong behind
|
||||
`lazyView`.
|
||||
`layout.auth`, which renders before anything else, and layers as small as a thin layout. Import only
|
||||
`@pterodactyl/sdk/theme` in the modules the entry loads eagerly; views that use components from
|
||||
`@pterodactyl/sdk` belong behind `lazyView`.
|
||||
|
||||
### A console with power controls in the header
|
||||
|
||||
`layout.server` keeps classic's layout through `Default` and adds a header that places the
|
||||
`server.power` block. `model.conflict` is set while the server installs, transfers or is suspended;
|
||||
classic then shows a notice instead of the page.
|
||||
`layout.server` keeps classic's layout through `Default` and adds a header, lined up with the page by
|
||||
[`page-width`](#lining-up-with-the-page), that places the `server.power` block. `model.conflict` is set
|
||||
while the server installs, transfers or is suspended; classic then shows a notice instead of the page.
|
||||
`model.state` is what the server is doing (`offline`, `starting`, `running` or `stopping`, or null until
|
||||
Wings reports it), kept live by the server's websocket, for a status badge.
|
||||
|
||||
<!-- sample: level4-console/src/views/ServerLayout.tsx -->
|
||||
```tsx
|
||||
@@ -617,7 +698,7 @@ import { View, type ViewProps } from '@pterodactyl/sdk/theme';
|
||||
export default function ServerLayout({ model, Default }: ViewProps<'layout.server'>) {
|
||||
return (
|
||||
<>
|
||||
<header className='mx-auto flex w-full max-w-panel flex-wrap items-center gap-4 px-4 pt-6'>
|
||||
<header className='page-width mt-4 flex flex-wrap items-center gap-4 sm:mt-6'>
|
||||
<h1 className='min-w-0 flex-1 truncate text-xl font-semibold'>{model.name}</h1>
|
||||
{/* No power controls while the server installs, transfers or is suspended. */}
|
||||
{model.conflict === null && <View name='server.power' />}
|
||||
@@ -813,8 +894,7 @@ example.
|
||||
4. **Render it.** `renderView` draws the view from its fixtures in a test, with your layers over
|
||||
classic (see [Testing](#testing)).
|
||||
|
||||
A layer that throws is logged in the browser console as `[extensions] "<theme>" failed in view "<name>"`,
|
||||
with the error, and the layer below renders in its place.
|
||||
A layer that fails names its view in the browser console ([Fallback](#fallback-and-safe-mode)).
|
||||
|
||||
### The theme CLI
|
||||
|
||||
@@ -837,33 +917,33 @@ npx pterodactyl-theme skins [primitive]
|
||||
|
||||
Every view ships **fixtures**, named stand-in models listed in the catalogue, so a test can render it
|
||||
without a panel. The scaffold's `vitest.config.mjs` uses `@pterodactyl/sdk/vitest`, which points the SDK
|
||||
at its real runtime, and `@pterodactyl/sdk/testing` renders with your theme:
|
||||
at its real runtime and adds what jsdom lacks: an inert `ResizeObserver` and `IntersectionObserver`, and
|
||||
a `matchMedia` that matches nothing. Tests need no stubs of their own; `vi.stubGlobal` still replaces
|
||||
one that a test drives. `@pterodactyl/sdk/testing` renders with your theme:
|
||||
|
||||
- `renderView(name, { theme, fixture, model, input })` renders a view synchronously with the theme's
|
||||
layers over classic, from the named fixture, the first fixture, or `model`. Nested views read their
|
||||
first fixture. It returns `{ container, unmount }`; each call replaces the previous render.
|
||||
- `renderView(name, { theme, fixture, model, input, slots })` renders a view synchronously with the
|
||||
theme's layers over classic, from the named fixture, the first fixture, or `model`. Nested views read
|
||||
their first fixture, and `usePanelLocation()` returns the path with empty `params` and `search`. It
|
||||
returns `{ container, unmount }`; each call replaces the previous render.
|
||||
- `slots` mounts components in slots, typed per slot, as an extension's `slots.register` would. Use it
|
||||
to test that a layer renders the slots of the view it replaces.
|
||||
- `renderPrimitive(name, props, { theme })` renders a primitive under the theme's skins.
|
||||
- `preloadTheme(theme)` loads the theme's `lazyView` chunks. Await it in `beforeAll`: `renderView`
|
||||
throws until it has.
|
||||
- `createViewTestHost(name, { model })` renders one layer by hand with typed `props`, for asserting on
|
||||
actions with `vi.fn()`.
|
||||
|
||||
`renderView` and `createViewTestHost` are strict: a theme or extension layer that throws, in the view or
|
||||
a nested one, fails the render with a `ViewLayerError` naming the `view`, the `layer` and the `cause`,
|
||||
such as `The "sunrise" layer of view "server.graphs" failed: …`. A failure after the first render, such
|
||||
as on a click, is thrown by `unmount()`. `{ strict: false }` lets layers fall back as in the panel.
|
||||
|
||||
<!-- sample: level4-console/src/theme.spec.tsx#tests -->
|
||||
```tsx
|
||||
let rendered: RenderedView | undefined;
|
||||
|
||||
beforeAll(async () => {
|
||||
// jsdom has no ResizeObserver; classic's server navigation, which `Default` renders, measures itself.
|
||||
vi.stubGlobal(
|
||||
'ResizeObserver',
|
||||
class {
|
||||
observe() {}
|
||||
disconnect() {}
|
||||
}
|
||||
);
|
||||
// The views are lazy; loading their chunks first lets renderView render them synchronously.
|
||||
await preloadTheme(theme);
|
||||
});
|
||||
// The views are lazy; loading their chunks first lets renderView render them synchronously.
|
||||
beforeAll(() => preloadTheme(theme));
|
||||
afterEach(() => rendered?.unmount());
|
||||
|
||||
test('puts the power controls in the server header', () => {
|
||||
@@ -876,11 +956,29 @@ test('puts the power controls in the server header', () => {
|
||||
```
|
||||
<!-- /sample -->
|
||||
|
||||
The [sidebar shell](#a-sidebar-shell)'s tests mount a component in a slot of the server's navigation,
|
||||
then check that the shell renders it:
|
||||
|
||||
<!-- sample: level3-sidebar/src/theme.spec.tsx#slots -->
|
||||
```tsx
|
||||
rendered = renderView('layout.app', {
|
||||
theme,
|
||||
fixture: 'serverArea',
|
||||
slots: { 'server.navigation.after': ({ data }) => <span>Mods for {data.attributes.name}</span> },
|
||||
});
|
||||
```
|
||||
<!-- /sample -->
|
||||
|
||||
### Doctor and pack
|
||||
|
||||
`npm run doctor` runs `p:extension:doctor` on the theme: the manifest, the build, the
|
||||
[budgets](#budgets), remote URLs, view names, and whether the stylesheet was built against this panel's
|
||||
classes. `npm run pack` writes a `.pteroext` archive to install on another panel.
|
||||
classes.
|
||||
|
||||
`npm run pack` writes a `.pteroext` archive to install on another panel, replacing an earlier one;
|
||||
`.gitignore` leaves archives out of the repository. The build writes no source maps, which would embed
|
||||
the theme's sources, unless `vite.config.mjs` passes `defineThemeConfig({ sourcemap: true })`, and pack
|
||||
leaves `*.map` files out unless `p:extension:pack` is given `--sourcemaps`.
|
||||
|
||||
## Rules and guarantees
|
||||
|
||||
@@ -890,7 +988,7 @@ classes. `npm run pack` writes a `.pteroext` archive to install on another panel
|
||||
another origin: `@import url(https://…)`, a font on a CDN, any `http:` or `//` URL. Data URLs are
|
||||
allowed.
|
||||
- **Drop slots.** A layer that replaces a view renders its slots, or the extensions mounted there
|
||||
disappear.
|
||||
disappear ([level 3](#the-shell-knows-the-area)).
|
||||
- **Replace interactive primitives.** Only presentational primitives take a component. Any other is a
|
||||
type error, and is ignored with a warning at runtime.
|
||||
- **Import CSS from JavaScript.** The build fails: the panel loads only `dist/theme.css`.
|
||||
@@ -907,8 +1005,10 @@ Beyond `<Main>`, a view owns its markup's accessibility: label controls, name na
|
||||
- **Boot.** The panel loads the chain's entries in parallel before its first render, for at most 2.5
|
||||
seconds. When an entry fails, does not export a `defineTheme` result, or is too slow, that browser
|
||||
shows classic, logs the error, and shows root admins a notice.
|
||||
- **Layers.** A layer that throws is logged against its package in the browser console, and the layer
|
||||
below renders in its place.
|
||||
- **Layers.** A layer that throws falls back to the layer below it, once. If that one throws too,
|
||||
classic included, the view shows the panel's error notice, whose Retry tries the failed layer again.
|
||||
Each failure logs one line in the browser console:
|
||||
`[extensions] "<layer id>" failed in view "<view>": <error>`.
|
||||
- **Safe mode.** Opening any page with `?safe_mode=1` renders that session with classic and no extension
|
||||
bundles; `?safe_mode=0` leaves it. The Themes page links to both.
|
||||
- **Stylesheet fallback.** `dist/theme.json` records the hash of the panel classes the stylesheet was
|
||||
@@ -1265,6 +1365,7 @@ package's types, run its tests and build it.
|
||||
|
||||
## Glossary
|
||||
|
||||
- **Area**: the account, a server or the admin area, each with a layout and navigation of its own.
|
||||
- **Block**: a view that is a piece of a page, such as `server.power`. It renders anywhere its context
|
||||
exists.
|
||||
- **Fixture**: a named stand-in model of a view, so a test can render the view without a panel.
|
||||
@@ -1279,5 +1380,7 @@ package's types, run its tests and build it.
|
||||
- **Primitive**: a component of the UI kit, such as `Button` or `Dialog`, styled by skins.
|
||||
- **Skin**: the recipes, by part, of one primitive.
|
||||
- **Slot**: a named place where extensions mount content.
|
||||
- **Thin layout**: an area layout that only places the page in `<Main>`, when `layout.app` draws the
|
||||
area's navigation.
|
||||
- **Token**: a CSS custom property the panel's classes read, such as `--primary`.
|
||||
- **View**: a named layout, page or block: an engine model and the stack of layers that render it.
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
import { afterEach, beforeAll, expect, test } from 'vitest';
|
||||
import { screen } from '@testing-library/react';
|
||||
import { fireEvent, screen } from '@testing-library/react';
|
||||
import { preloadTheme, renderView, type RenderedView } from '@pterodactyl/sdk/testing';
|
||||
import theme from './theme';
|
||||
|
||||
@@ -18,6 +18,15 @@ test('puts the links in a sidebar beside the page', () => {
|
||||
expect(rendered.container.querySelector('main#main')).not.toBeNull();
|
||||
});
|
||||
|
||||
test('opens the sidebar as a drawer from the menu button', () => {
|
||||
rendered = renderView('layout.app', { theme, fixture: 'user' });
|
||||
|
||||
const menu = screen.getByRole('button', { name: 'Menu' });
|
||||
fireEvent.click(menu);
|
||||
|
||||
expect(menu.getAttribute('aria-expanded')).toBe('true');
|
||||
});
|
||||
|
||||
test('offers the scheme switch only when the theme has both schemes', () => {
|
||||
rendered = renderView('layout.app', { theme, fixture: 'user' });
|
||||
expect(screen.queryByRole('button', { name: 'Use the light scheme' })).toBeNull();
|
||||
@@ -26,8 +35,46 @@ test('offers the scheme switch only when the theme has both schemes', () => {
|
||||
expect(screen.getByRole('button', { name: 'Use the light scheme' })).not.toBeNull();
|
||||
});
|
||||
|
||||
test('lists extension screens in the account menu', () => {
|
||||
rendered = renderView('layout.account', { theme, fixture: 'extension' });
|
||||
test('draws the server navigation, with its state and its slots, in the sidebar', () => {
|
||||
// #region slots
|
||||
rendered = renderView('layout.app', {
|
||||
theme,
|
||||
fixture: 'serverArea',
|
||||
slots: { 'server.navigation.after': ({ data }) => <span>Mods for {data.attributes.name}</span> },
|
||||
});
|
||||
// #endregion slots
|
||||
|
||||
expect(screen.getByRole('navigation', { name: 'Account' }).textContent).toContain('Tickets');
|
||||
const nav = screen.getByRole('navigation', { name: 'Server' }).textContent;
|
||||
|
||||
expect(nav).toContain('Survival');
|
||||
expect(nav).toContain('running');
|
||||
expect(nav).toContain('Backups');
|
||||
expect(nav).toContain('Mods for Survival');
|
||||
});
|
||||
|
||||
test('draws the account and admin navigation with their slots', () => {
|
||||
const probe = () => <span>probe</span>;
|
||||
|
||||
rendered = renderView('layout.app', {
|
||||
theme,
|
||||
fixture: 'accountArea',
|
||||
slots: { 'account.navigation.before': probe },
|
||||
});
|
||||
const account = screen.getByRole('navigation', { name: 'Account' }).textContent;
|
||||
|
||||
expect(account).toContain('SSH Keys');
|
||||
expect(account).toContain('probe');
|
||||
|
||||
rendered = renderView('layout.app', { theme, fixture: 'adminArea', slots: { 'panel.navigation.after': probe } });
|
||||
const admin = screen.getByRole('navigation', { name: 'Administration' }).textContent;
|
||||
|
||||
expect(admin).toContain('Themes');
|
||||
expect(admin).toContain('probe');
|
||||
});
|
||||
|
||||
test('leaves only the page to the area layouts', () => {
|
||||
rendered = renderView('layout.server', { theme, fixture: 'owner' });
|
||||
|
||||
expect(screen.queryByRole('navigation')).toBeNull();
|
||||
expect(rendered.container.querySelector('main#main')).not.toBeNull();
|
||||
});
|
||||
|
||||
@@ -1,8 +1,16 @@
|
||||
import { defineTheme, lazyView } from '@pterodactyl/sdk/theme';
|
||||
import type { ReactNode } from 'react';
|
||||
import { Main, defineTheme, lazyView } from '@pterodactyl/sdk/theme';
|
||||
|
||||
/** The shell draws every area's navigation, so an area's layout only places its pages. */
|
||||
function AreaLayout({ children }: { children?: ReactNode }) {
|
||||
return <Main>{children}</Main>;
|
||||
}
|
||||
|
||||
export default defineTheme({
|
||||
views: {
|
||||
'layout.app': lazyView(() => import('./views/Shell')),
|
||||
'layout.account': lazyView(() => import('./views/AccountLayout')),
|
||||
'layout.server': AreaLayout,
|
||||
'layout.account': AreaLayout,
|
||||
'layout.admin': AreaLayout,
|
||||
},
|
||||
});
|
||||
|
||||
@@ -1,29 +0,0 @@
|
||||
import { NamedIcon, cn } from '@pterodactyl/sdk';
|
||||
import { Main, Navigation, NavigationLink, Slot, type ViewProps } from '@pterodactyl/sdk/theme';
|
||||
|
||||
// #region account
|
||||
/** The account pages with a vertical menu. `model.nav` lists them, extension screens included. */
|
||||
export default function AccountLayout({ model, children }: ViewProps<'layout.account'>) {
|
||||
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 gap-2 rounded-lg px-3 py-2', active && 'bg-muted')}
|
||||
>
|
||||
{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'>{children}</Main>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
// #endregion account
|
||||
@@ -0,0 +1,48 @@
|
||||
import { Badge, NamedIcon } from '@pterodactyl/sdk';
|
||||
import { Navigation, NavigationLink, Slot, type AppArea } from '@pterodactyl/sdk/theme';
|
||||
|
||||
type Area = Exclude<AppArea, { kind: 'dashboard' }>;
|
||||
|
||||
const link = [
|
||||
'flex items-center gap-3 rounded-lg px-3 py-2 text-sm text-muted-foreground no-underline',
|
||||
'hover:bg-popover hover:text-foreground data-[status=active]:bg-primary/15 data-[status=active]:text-foreground',
|
||||
].join(' ');
|
||||
|
||||
/** The slots of the area's navigation, which its own layout would render if it drew the navigation. */
|
||||
function AreaSlot({ area, at }: { area: Area; at: 'before' | 'after' }) {
|
||||
if (area.kind === 'server') return <Slot name={`server.navigation.${at}`} data={area.server} />;
|
||||
if (area.kind === 'account') return <Slot name={`account.navigation.${at}`} />;
|
||||
return <Slot name={`panel.navigation.${at}`} />;
|
||||
}
|
||||
|
||||
/** The pages of the area the user is in: a server's, the account's or the admin area's. */
|
||||
export default function AreaNav({ area }: { area: AppArea }) {
|
||||
if (area.kind === 'dashboard') return null;
|
||||
|
||||
const items = area.kind === 'server' && area.adminLink ? [...area.nav.items, area.adminLink] : area.nav.items;
|
||||
const label = { server: 'Server', account: 'Account', admin: 'Administration' }[area.kind];
|
||||
|
||||
return (
|
||||
<nav aria-label={label} className='flex flex-col gap-1'>
|
||||
{area.kind === 'server' && (
|
||||
<p className='flex items-center gap-2 px-3 pb-1 text-sm font-semibold'>
|
||||
<span className='min-w-0 flex-1 truncate'>{area.name}</span>
|
||||
<Badge size='sm' tone={area.state === 'running' ? 'success' : 'neutral'}>
|
||||
{area.state ?? 'unknown'}
|
||||
</Badge>
|
||||
</p>
|
||||
)}
|
||||
<AreaSlot area={area} at='before' />
|
||||
<Navigation items={items}>
|
||||
{(item, { badge }) => (
|
||||
<NavigationLink item={item} className={link}>
|
||||
{item.icon && <NamedIcon name={item.icon} size={16} aria-hidden />}
|
||||
<span className='min-w-0 flex-1 truncate'>{item.label}</span>
|
||||
{badge}
|
||||
</NavigationLink>
|
||||
)}
|
||||
</Navigation>
|
||||
<AreaSlot area={area} at='after' />
|
||||
</nav>
|
||||
);
|
||||
}
|
||||
@@ -1,43 +1,62 @@
|
||||
import { LayoutGrid, LogOut, Moon, Shield, Sun, UserRound, type LucideIcon } from 'lucide-react';
|
||||
import { Avatar, PanelLink, SpinnerOverlay } from '@pterodactyl/sdk';
|
||||
import { Main, Slot, View, type AppLayoutLink, type ViewProps } from '@pterodactyl/sdk/theme';
|
||||
|
||||
const icons: Record<AppLayoutLink['id'], LucideIcon> = { dashboard: LayoutGrid, admin: Shield, account: UserRound };
|
||||
import { useEffect, useState } from 'react';
|
||||
import { LogOut, Menu, Moon, Sun } from 'lucide-react';
|
||||
import { Avatar, NamedIcon, PanelLink, SpinnerOverlay, cn, usePanelLocation } from '@pterodactyl/sdk';
|
||||
import { Main, Slot, View, type ViewProps } from '@pterodactyl/sdk/theme';
|
||||
import AreaNav from './AreaNav';
|
||||
|
||||
const item = [
|
||||
'flex items-center gap-3 rounded-lg px-3 py-2 text-sm text-muted-foreground no-underline',
|
||||
'hover:bg-popover hover:text-foreground data-[status=active]:bg-primary/15 data-[status=active]:text-foreground',
|
||||
].join(' ');
|
||||
|
||||
/** A sidebar on large screens and a top bar below them, with the page beside it. */
|
||||
/** A sidebar beside the page on large screens, and a drawer behind a menu button below them. */
|
||||
export default function Shell({ model, children }: ViewProps<'layout.app'>) {
|
||||
const { brand, user, scheme, setScheme } = model;
|
||||
const SchemeIcon = scheme === 'dark' ? Sun : Moon;
|
||||
const [open, setOpen] = useState(false);
|
||||
const { pathname } = usePanelLocation();
|
||||
|
||||
// Close the drawer when one of its links navigates.
|
||||
useEffect(() => setOpen(false), [pathname]);
|
||||
|
||||
return (
|
||||
<div className='flex min-h-dvh flex-col lg:flex-row'>
|
||||
<div className='min-h-dvh lg:flex'>
|
||||
<SpinnerOverlay visible={model.signingOut} fixed />
|
||||
<aside className='flex shrink-0 items-center gap-2 bg-sidebar p-3 lg:sticky lg:top-0 lg:h-dvh lg:w-sidebar lg:flex-col lg:items-stretch lg:p-4'>
|
||||
<button
|
||||
type='button'
|
||||
aria-expanded={open}
|
||||
aria-controls='sidebar'
|
||||
onClick={() => setOpen(!open)}
|
||||
className={cn(item, 'm-2 lg:hidden')}
|
||||
>
|
||||
<Menu className='size-4' aria-hidden />
|
||||
Menu
|
||||
</button>
|
||||
<aside
|
||||
id='sidebar'
|
||||
className={cn(
|
||||
'flex-col gap-4 bg-sidebar p-4 lg:sticky lg:top-0 lg:flex lg:h-dvh lg:w-sidebar lg:shrink-0 lg:overflow-y-auto',
|
||||
open ? 'flex' : 'hidden'
|
||||
)}
|
||||
>
|
||||
<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>
|
||||
<nav aria-label='Main' className='flex flex-1 gap-1 lg:flex-col'>
|
||||
<nav aria-label='Main' className='flex flex-col gap-1'>
|
||||
<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={item}>
|
||||
<Glyph className='size-4' aria-hidden />
|
||||
<span className='max-lg:sr-only'>{link.label}</span>
|
||||
</PanelLink>
|
||||
);
|
||||
})}
|
||||
{model.links.map((link) => (
|
||||
<PanelLink key={link.id} destination={link.destination} exact={link.exact} className={item}>
|
||||
<NamedIcon name={link.icon} size={16} aria-hidden />
|
||||
{link.label}
|
||||
</PanelLink>
|
||||
))}
|
||||
<Slot name='nav.items.after' />
|
||||
</nav>
|
||||
<AreaNav area={model.area} />
|
||||
<View name='app.search' className={item} />
|
||||
<div className='flex items-center gap-2'>
|
||||
<div className='mt-auto flex items-center gap-2'>
|
||||
<Avatar name={user.uuid} size={28} />
|
||||
<span className='min-w-0 flex-1 truncate text-sm max-lg:sr-only'>{user.username}</span>
|
||||
<span className='min-w-0 flex-1 truncate text-sm'>{user.username}</span>
|
||||
{/* setScheme is null unless the theme offers both schemes. */}
|
||||
{setScheme && (
|
||||
<button
|
||||
@@ -46,11 +65,7 @@ export default function Shell({ model, children }: ViewProps<'layout.app'>) {
|
||||
onClick={() => setScheme(scheme === 'dark' ? 'light' : 'dark')}
|
||||
className={item}
|
||||
>
|
||||
{scheme === 'dark' ? (
|
||||
<Sun className='size-4' aria-hidden />
|
||||
) : (
|
||||
<Moon className='size-4' aria-hidden />
|
||||
)}
|
||||
<SchemeIcon className='size-4' aria-hidden />
|
||||
</button>
|
||||
)}
|
||||
<button type='button' aria-label='Sign out' onClick={model.signOut} className={item}>
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
import { afterEach, beforeAll, expect, test, vi } from 'vitest';
|
||||
import { afterEach, beforeAll, expect, test } from 'vitest';
|
||||
import { screen } from '@testing-library/react';
|
||||
import { preloadTheme, renderView, type RenderedView } from '@pterodactyl/sdk/testing';
|
||||
import theme from './theme';
|
||||
@@ -6,18 +6,8 @@ import theme from './theme';
|
||||
// #region tests
|
||||
let rendered: RenderedView | undefined;
|
||||
|
||||
beforeAll(async () => {
|
||||
// jsdom has no ResizeObserver; classic's server navigation, which `Default` renders, measures itself.
|
||||
vi.stubGlobal(
|
||||
'ResizeObserver',
|
||||
class {
|
||||
observe() {}
|
||||
disconnect() {}
|
||||
}
|
||||
);
|
||||
// The views are lazy; loading their chunks first lets renderView render them synchronously.
|
||||
await preloadTheme(theme);
|
||||
});
|
||||
// The views are lazy; loading their chunks first lets renderView render them synchronously.
|
||||
beforeAll(() => preloadTheme(theme));
|
||||
afterEach(() => rendered?.unmount());
|
||||
|
||||
test('puts the power controls in the server header', () => {
|
||||
|
||||
@@ -4,7 +4,7 @@ import { View, type ViewProps } from '@pterodactyl/sdk/theme';
|
||||
export default function ServerLayout({ model, Default }: ViewProps<'layout.server'>) {
|
||||
return (
|
||||
<>
|
||||
<header className='mx-auto flex w-full max-w-panel flex-wrap items-center gap-4 px-4 pt-6'>
|
||||
<header className='page-width mt-4 flex flex-wrap items-center gap-4 sm:mt-6'>
|
||||
<h1 className='min-w-0 flex-1 truncate text-xl font-semibold'>{model.name}</h1>
|
||||
{/* No power controls while the server installs, transfers or is suspended. */}
|
||||
{model.conflict === null && <View name='server.power' />}
|
||||
|
||||
@@ -165,7 +165,8 @@ export function defineThemeConfig({ entry, stylesheet, outDir = 'dist', plugins
|
||||
modulePreload: false,
|
||||
rollupOptions: {
|
||||
input: { ...(entry ? { client: entry } : {}), ...(stylesheet ? { theme: stylesheet } : {}) },
|
||||
external: SHARED_RUNTIME_MODULES,
|
||||
// The panel serves /assets/ itself, such as the font panel.css links, so the build leaves those URLs alone.
|
||||
external: [...SHARED_RUNTIME_MODULES, /^\/assets\//],
|
||||
preserveEntrySignatures: 'strict',
|
||||
output: {
|
||||
format: 'es',
|
||||
|
||||
@@ -3,7 +3,7 @@ import { tmpdir } from 'node:os';
|
||||
import { resolve } from 'node:path';
|
||||
import { pathToFileURL } from 'node:url';
|
||||
import { spawnSync } from 'node:child_process';
|
||||
import { build } from 'vite';
|
||||
import { build, createLogger } from 'vite';
|
||||
import { expect, it } from 'vitest';
|
||||
import { defineExtensionConfig, defineThemeConfig } from './vite.mjs';
|
||||
|
||||
@@ -114,6 +114,30 @@ it('ships fonts beside the theme stylesheet, linked relative to it', async () =>
|
||||
}
|
||||
});
|
||||
|
||||
it("leaves the panel's own /assets/ URLs for the panel to serve, without a warning", async () => {
|
||||
const directory = mkdtempSync(resolve(tmpdir(), 'theme-build-'));
|
||||
const warnings: string[] = [];
|
||||
const logger = createLogger('warn');
|
||||
logger.warn = logger.warnOnce = (message) => void warnings.push(message);
|
||||
try {
|
||||
writeFileSync(
|
||||
resolve(directory, 'theme.css'),
|
||||
"@font-face { font-family: 'Panel'; src: url('/assets/fonts/panel.woff2') format('woff2'); }"
|
||||
);
|
||||
await build({
|
||||
...defineThemeConfig({ stylesheet: resolve(directory, 'theme.css'), outDir: resolve(directory, 'dist') }),
|
||||
configFile: false,
|
||||
logLevel: 'warn',
|
||||
customLogger: logger,
|
||||
});
|
||||
|
||||
expect(readFileSync(resolve(directory, 'dist/theme.css'), 'utf8')).toContain('url(/assets/fonts/panel.woff2)');
|
||||
expect(warnings).toEqual([]);
|
||||
} finally {
|
||||
rmSync(directory, { recursive: true, force: true });
|
||||
}
|
||||
});
|
||||
|
||||
it('refuses theme JavaScript that imports styles the panel would never load', async () => {
|
||||
const directory = mkdtempSync(resolve(tmpdir(), 'theme-build-'));
|
||||
try {
|
||||
|
||||
@@ -54,6 +54,37 @@ test('scaffolds a theme with a stylesheet, a layout override, a skin, settings a
|
||||
expect($target.'/composer.json')->not->toBeFile();
|
||||
});
|
||||
|
||||
test('scaffolds a theme of css alone, with no javascript entry', function (): void {
|
||||
$target = $this->scaffolder->scaffold(id: 'sunrise', outDir: $this->directory, theme: true, cssOnly: true);
|
||||
$manifest = (new ExtensionManifestValidator)->fromDirectory($target);
|
||||
|
||||
expect($manifest->isTheme())->toBeTrue()
|
||||
->and($manifest->hasUi())->toBeFalse()
|
||||
->and(File::json($target.'/extension.json'))->not->toHaveKey('ui')
|
||||
->and($manifest->theme->stylesheet)->toBe('dist/theme.css')
|
||||
->and(array_keys($manifest->theme->settings))->toBe(['accent', 'radius', 'compact', 'logo']);
|
||||
expect($this->scaffolder->files())->toBe(['extension.json', 'package.json', 'vite.config.mjs', 'postcss.config.mjs', 'src/theme.css', '.gitignore', 'README.md']);
|
||||
expect(File::get($target.'/vite.config.mjs'))->toContain("defineThemeConfig({ stylesheet: 'src/theme.css' })")->not->toContain('entry:');
|
||||
expect(File::get($target.'/src/theme.css'))->toContain("@import '@pterodactyl/sdk/theme-entry.css';", 'var(--sunrise-accent');
|
||||
expect(File::get($target.'/README.md'))->toContain('--css-only', 'Level 1', 'p:extension:dev . --watch')->not->toContain('{{', 'src/theme.tsx');
|
||||
|
||||
$package = File::json($target.'/package.json');
|
||||
expect(array_keys($package['scripts']))->toBe(['build', 'dev', 'doctor', 'pack'])
|
||||
->and($package['devDependencies'])->toHaveKeys(['@pterodactyl/sdk', 'vite', 'tailwindcss', '@tailwindcss/forms', '@tailwindcss/postcss'])
|
||||
->and($package['devDependencies'])->not->toHaveKey('react');
|
||||
});
|
||||
|
||||
test('takes --css-only from the command, and only with --theme', function (): void {
|
||||
$this->artisan('p:extension:make', ['id' => 'sunrise', '--theme' => true, '--css-only' => true, '--out' => $this->directory])->assertSuccessful();
|
||||
expect($this->directory.'/sunrise/src/theme.css')->toBeFile()
|
||||
->and($this->directory.'/sunrise/src/theme.tsx')->not->toBeFile();
|
||||
|
||||
$this->artisan('p:extension:make', ['id' => 'plain', '--css-only' => true, '--out' => $this->directory])
|
||||
->expectsOutputToContain('pass it with --theme')
|
||||
->assertFailed();
|
||||
expect($this->directory.'/plain')->not->toBeDirectory();
|
||||
});
|
||||
|
||||
test('scaffolds an installable package', function (): void {
|
||||
$target = $this->scaffolder->scaffold(id: 'my-widget', description: 'A test widget.', author: 'Tester', outDir: $this->directory);
|
||||
$manifest = (new ExtensionManifestValidator)->fromDirectory($target);
|
||||
|
||||
Reference in New Issue
Block a user