mirror of
https://github.com/pterodactyl/panel.git
synced 2026-12-05 22:05:47 -05:00
theme inheritance
This commit is contained in:
@@ -75,6 +75,10 @@ final readonly class SetExtensionEnabled implements SetsExtensionEnabled
|
||||
$this->compatibility->assertCompatible($manifest, $this->extensions->configuredEnabled());
|
||||
$this->compatibility->assertMigrationsAreUnique($manifest, $this->extensions->discovered());
|
||||
throw_if($reason = $this->assets->unusableBuildReason($manifest), InvalidExtensionException::class, $reason);
|
||||
if ($manifest->isTheme()) {
|
||||
throw_if($problem = $this->themes->parentBuildProblem($manifest), InvalidExtensionException::class, $problem);
|
||||
$this->themes->declarations($manifest);
|
||||
}
|
||||
}
|
||||
|
||||
private function activate(ExtensionManifest $manifest): void
|
||||
|
||||
@@ -34,6 +34,10 @@ class DoctorCommand extends Command
|
||||
|
||||
$unknown = $views->unknown($manifest->views);
|
||||
throw_if($unknown !== [], InvalidExtensionException::class, 'Manifest "ui.views" names views the panel does not have: '.implode(', ', $unknown).'.');
|
||||
if ($manifest->isTheme()) {
|
||||
throw_if($problem = $themes->parentBuildProblem($manifest), InvalidExtensionException::class, $problem);
|
||||
$themes->declarations($manifest);
|
||||
}
|
||||
} catch (InvalidExtensionException $invalidExtensionException) {
|
||||
$this->components->error($invalidExtensionException->getMessage());
|
||||
|
||||
@@ -48,8 +52,8 @@ class DoctorCommand extends Command
|
||||
$this->components->warn($problem.' The extension list shows its initials instead.');
|
||||
}
|
||||
|
||||
if ($manifest->isTheme() && ($mismatch = $themes->coreMismatch($manifest)) !== null) {
|
||||
$this->components->warn($mismatch);
|
||||
foreach ($manifest->isTheme() ? array_filter([$themes->coreMismatch($manifest), ...$themes->staleParents($manifest)]) : [] as $warning) {
|
||||
$this->components->warn($warning);
|
||||
}
|
||||
|
||||
foreach ($composer->warnings($manifest) as $warning) {
|
||||
|
||||
@@ -21,6 +21,7 @@ use Pterodactyl\Services\Extensions\Scaffolding\ExtensionScaffolder;
|
||||
{--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.}
|
||||
{--extends= : With --theme: the theme to build on. Scaffolds a child that inherits its views, skins, stylesheet and settings.}
|
||||
{--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.}')]
|
||||
@@ -41,6 +42,7 @@ class MakeCommand extends Command implements PromptsForMissingInput
|
||||
theme: (bool) $this->option('theme'),
|
||||
path: $this->option('path'),
|
||||
cssOnly: (bool) $this->option('css-only'),
|
||||
extends: $this->option('extends'),
|
||||
);
|
||||
} catch (InvalidExtensionException $invalidExtensionException) {
|
||||
$this->components->error($invalidExtensionException->getMessage());
|
||||
|
||||
@@ -29,8 +29,8 @@ class PackCommand extends Command
|
||||
{
|
||||
try {
|
||||
$manifest = $validator->fromDirectory($this->argument('path'));
|
||||
throw_if($reason = $assets->unusableBuildReason($manifest), InvalidExtensionException::class, $reason);
|
||||
foreach (array_filter([...$composer->warnings($manifest), $manifest->isTheme() ? $themes->coreMismatch($manifest) : null]) as $warning) {
|
||||
throw_if($reason = $assets->unusableBuildReason($manifest) ?? ($manifest->isTheme() ? $themes->parentBuildProblem($manifest) : null), InvalidExtensionException::class, $reason);
|
||||
foreach (array_filter([...$composer->warnings($manifest), ...$manifest->isTheme() ? [$themes->coreMismatch($manifest), ...$themes->staleParents($manifest)] : []]) as $warning) {
|
||||
$this->components->warn($warning);
|
||||
}
|
||||
|
||||
|
||||
@@ -8,17 +8,20 @@ use Illuminate\Console\Attributes\Description;
|
||||
use Illuminate\Console\Attributes\Signature;
|
||||
use Illuminate\Console\Command;
|
||||
use Illuminate\Support\Facades\File;
|
||||
use Pterodactyl\Exceptions\Extensions\InvalidExtensionException;
|
||||
use Pterodactyl\Services\Extensions\ExtensionManifest;
|
||||
use Pterodactyl\Services\Extensions\ExtensionManifestValidator;
|
||||
use Pterodactyl\Services\Extensions\ExtensionPermissionRegistry;
|
||||
use Pterodactyl\Services\Extensions\ExtensionSettingsDefinition;
|
||||
use Pterodactyl\Services\Extensions\ExtensionSettingsRegistry;
|
||||
use Pterodactyl\Services\Themes\ThemeRepository;
|
||||
use Pterodactyl\Services\Themes\ThemeSetting;
|
||||
|
||||
#[Description('Generate literal screen ids, frontend configuration types and theme settings types for an extension or theme.')]
|
||||
#[Signature('p:extension:types {path : Unpacked package path.} {--output= : Generated TypeScript file; defaults to src/client/extension-types.ts, or src/theme-types.ts for a theme.}')]
|
||||
class TypesCommand extends Command
|
||||
{
|
||||
public function handle(ExtensionManifestValidator $validator, ExtensionSettingsRegistry $settings, ExtensionPermissionRegistry $permissions): int
|
||||
public function handle(ExtensionManifestValidator $validator, ExtensionSettingsRegistry $settings, ExtensionPermissionRegistry $permissions, ThemeRepository $themes): int
|
||||
{
|
||||
$manifest = $validator->fromDirectory($this->argument('path'));
|
||||
$definition = $settings->get($manifest->id);
|
||||
@@ -45,13 +48,14 @@ class TypesCommand extends Command
|
||||
$source .= 'export type ExtensionPublicConfigKey = '.($publicNames === [] ? 'never' : implode(' | ', $publicNames)).";\n";
|
||||
$source .= "export type ExtensionPublicConfig = Pick<ExtensionConfig, ExtensionPublicConfigKey>;\n";
|
||||
if ($manifest->isTheme()) {
|
||||
$source .= $this->themeSettings($manifest->theme->settings);
|
||||
$source .= $this->themeSettings($this->chainSettings($themes, $manifest));
|
||||
}
|
||||
|
||||
$output = $this->option('output') ?: ($manifest->isTheme() ? $manifest->path('src', 'theme-types.ts') : $manifest->path('src', 'client', 'extension-types.ts'));
|
||||
File::ensureDirectoryExists(dirname($output));
|
||||
File::replace($output, $source);
|
||||
if (! $definition instanceof ExtensionSettingsDefinition) {
|
||||
// Only a provider declares configuration keys.
|
||||
if (! $definition instanceof ExtensionSettingsDefinition && $manifest->provider !== null) {
|
||||
$this->components->warn('No settings definition is loaded; enable the extension to include declared frontend configuration keys.');
|
||||
}
|
||||
|
||||
@@ -60,6 +64,28 @@ class TypesCommand extends Command
|
||||
return self::SUCCESS;
|
||||
}
|
||||
|
||||
/**
|
||||
* The settings of the whole chain, as useThemeSettings() returns them: the themes it extends, then
|
||||
* its own, each replacing a setting of the same name.
|
||||
*
|
||||
* @return array<string, ThemeSetting>
|
||||
*/
|
||||
private function chainSettings(ThemeRepository $themes, ExtensionManifest $theme): array
|
||||
{
|
||||
try {
|
||||
$settings = [];
|
||||
foreach ([...$themes->ancestors($theme), $theme] as $manifest) {
|
||||
$settings = [...$settings, ...$themes->declarations($manifest)];
|
||||
}
|
||||
|
||||
return $settings;
|
||||
} catch (InvalidExtensionException $invalidExtensionException) {
|
||||
$this->components->warn($invalidExtensionException->getMessage().' ThemeSettings lists only the settings this theme declares in full.');
|
||||
|
||||
return $theme->theme->settings ?? [];
|
||||
}
|
||||
}
|
||||
|
||||
/** @param array<string, ThemeSetting> $settings */
|
||||
private function themeSettings(array $settings): string
|
||||
{
|
||||
|
||||
@@ -197,7 +197,7 @@ class ThemeController extends AdminApiController
|
||||
private function replaceImage(ReplacesExtensionSettingFiles $files, ThemeRepository $themes, string $theme, string $setting, ?UploadedFile $upload): ApiResourceCollection
|
||||
{
|
||||
$manifest = $this->theme($themes, $theme);
|
||||
abort_unless($manifest instanceof ExtensionManifest && ($manifest->theme?->settings[$setting]->type ?? null) === 'image', Response::HTTP_NOT_FOUND, "Setting \"{$setting}\" is not an image setting.");
|
||||
abort_unless($manifest instanceof ExtensionManifest && ($themes->declared($manifest)[$setting]->type ?? null) === 'image', Response::HTTP_NOT_FOUND, "Setting \"{$setting}\" is not an image setting.");
|
||||
|
||||
$files->replace($themes->settings($manifest), $setting, $upload);
|
||||
Activity::event($upload instanceof UploadedFile ? 'admin:theme.image' : 'admin:theme.image-clear')->property(['theme' => $theme, 'setting' => $setting])->log();
|
||||
@@ -224,7 +224,7 @@ class ThemeController extends AdminApiController
|
||||
$items = array_map(fn (ThemeSetting $setting): array => [
|
||||
'setting' => $setting,
|
||||
'value' => $setting->value($stored?->get(ThemeSetting::KEY_PREFIX.$setting->key)),
|
||||
], array_values($theme?->theme->settings ?? []));
|
||||
], array_values($theme instanceof ExtensionManifest ? $themes->declared($theme) : []));
|
||||
|
||||
return ThemeSettingResource::collection($items);
|
||||
}
|
||||
|
||||
@@ -40,7 +40,7 @@ class ThemeResource extends AdminResource
|
||||
'schemes' => $this->resource['schemes'],
|
||||
'has_stylesheet' => $theme?->theme?->stylesheet !== null,
|
||||
'has_entry' => $theme?->hasUi() ?? false,
|
||||
'settings_count' => count($theme?->theme->settings ?? []),
|
||||
'settings_count' => count($theme?->theme->settings ?? []) + count($theme?->theme->overrides ?? []),
|
||||
'problem' => $this->resource['problem'],
|
||||
];
|
||||
}
|
||||
|
||||
@@ -15,12 +15,19 @@ use InvalidArgumentException;
|
||||
use JsonException;
|
||||
use Pterodactyl\Exceptions\Extensions\InvalidExtensionException;
|
||||
use Pterodactyl\Services\Themes\ThemeDefinition;
|
||||
use Pterodactyl\Services\Themes\ThemeRepository;
|
||||
use Pterodactyl\Services\Themes\ThemeSetting;
|
||||
use ReflectionClass;
|
||||
use UnexpectedValueException;
|
||||
|
||||
class ExtensionManifestValidator
|
||||
{
|
||||
private const array THEME_SETTING_MESSAGES = [
|
||||
'theme.settings.*.token.regex' => 'Theme setting tokens must be custom property names such as "--accent".',
|
||||
'theme.settings.*.attribute.regex' => 'Theme setting attributes must be data attributes such as "data-density".',
|
||||
'theme.settings.*.attribute.not_in' => 'Theme setting attributes cannot use "data-theme", which the panel sets.',
|
||||
];
|
||||
|
||||
/** @var list<string>|null */
|
||||
private ?array $panelNamespaces = null;
|
||||
|
||||
@@ -100,6 +107,23 @@ class ExtensionManifestValidator
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* A child theme's override merged over the declaration it changes, checked as a setting the
|
||||
* manifest declares in full.
|
||||
*
|
||||
* @param ExtensionThemeSettingOverride $data
|
||||
*
|
||||
* @throws InvalidExtensionException
|
||||
*/
|
||||
public function themeSetting(string $key, array $data): ThemeSetting
|
||||
{
|
||||
$validator = Validator::make(['theme' => ['settings' => [$key => $data]]], $this->themeSettingRules(), self::THEME_SETTING_MESSAGES);
|
||||
throw_if($validator->fails(), InvalidExtensionException::class, $validator->errors()->first());
|
||||
throw_unless(isset($data['type'], $data['label']), InvalidExtensionException::class, "Theme setting \"{$key}\" needs a \"type\" and a \"label\".");
|
||||
|
||||
return $this->validateThemeSetting($key, $data);
|
||||
}
|
||||
|
||||
/**
|
||||
* @phpstan-assert ExtensionManifestInput $data
|
||||
*/
|
||||
@@ -163,20 +187,7 @@ class ExtensionManifestValidator
|
||||
'theme.stylesheet' => ['sometimes', 'nullable', 'string', Rule::in([ThemeDefinition::STYLESHEET])],
|
||||
'theme.schemes' => ['sometimes', 'array', 'list', 'min:1', 'max:2'],
|
||||
'theme.schemes.*' => ['required', 'string', 'distinct:strict', Rule::in(ThemeDefinition::SCHEMES)],
|
||||
'theme.settings' => ['sometimes', 'array', 'max:64', $this->keyedBy(ThemeSetting::KEY_REGEX, 'Theme setting names must match '.ThemeSetting::KEY_REGEX.'.')],
|
||||
'theme.settings.*' => ['required', 'array:type,label,default,help,token,attribute,options,min,max,step,unit,maxLength'],
|
||||
'theme.settings.*.type' => ['required', 'string', Rule::in(ThemeSetting::TYPES)],
|
||||
'theme.settings.*.label' => ['required', 'string', 'max:100'],
|
||||
'theme.settings.*.help' => ['sometimes', 'nullable', 'string', 'max:255'],
|
||||
'theme.settings.*.token' => ['sometimes', 'nullable', 'string', 'regex:'.ThemeSetting::TOKEN_REGEX],
|
||||
'theme.settings.*.attribute' => ['sometimes', 'nullable', 'string', 'regex:'.ThemeSetting::ATTRIBUTE_REGEX, Rule::notIn(ThemeSetting::RESERVED_ATTRIBUTES)],
|
||||
'theme.settings.*.options' => ['required_if:theme.settings.*.type,select', 'prohibited_unless:theme.settings.*.type,select', 'array', 'min:1', 'max:64', $this->keyedBy(ThemeSetting::OPTION_REGEX, 'Theme setting options must be keyed by identifiers such as "side".')],
|
||||
'theme.settings.*.options.*' => ['required', 'string', 'max:100'],
|
||||
'theme.settings.*.min' => ['sometimes', 'prohibited_unless:theme.settings.*.type,number', 'numeric'],
|
||||
'theme.settings.*.max' => ['sometimes', 'prohibited_unless:theme.settings.*.type,number', 'numeric'],
|
||||
'theme.settings.*.step' => ['sometimes', 'prohibited_unless:theme.settings.*.type,number', 'numeric', 'gt:0'],
|
||||
'theme.settings.*.unit' => ['sometimes', 'prohibited_unless:theme.settings.*.type,number', 'string', 'regex:'.ThemeSetting::UNIT_REGEX],
|
||||
'theme.settings.*.maxLength' => ['sometimes', 'prohibited_unless:theme.settings.*.type,text', 'integer', 'between:1,1000'],
|
||||
...$this->themeSettingRules(),
|
||||
], [
|
||||
'id.required' => 'Manifest field "id" is required and must be a string.',
|
||||
'id.string' => 'Manifest field "id" is required and must be a string.',
|
||||
@@ -203,9 +214,7 @@ class ExtensionManifestValidator
|
||||
'ui.views.*.regex' => 'Manifest "ui.views" must contain view names such as "server.power" or "page.dashboard".',
|
||||
'theme.prohibited_unless' => 'Only a package with "type": "theme" can declare a "theme" section.',
|
||||
'theme.stylesheet.in' => 'Manifest "theme.stylesheet" must be "'.ThemeDefinition::STYLESHEET.'".',
|
||||
'theme.settings.*.token.regex' => 'Theme setting tokens must be custom property names such as "--accent".',
|
||||
'theme.settings.*.attribute.regex' => 'Theme setting attributes must be data attributes such as "data-density".',
|
||||
'theme.settings.*.attribute.not_in' => 'Theme setting attributes cannot use "data-theme", which the panel sets.',
|
||||
...self::THEME_SETTING_MESSAGES,
|
||||
'ui.screens.*.permission.prohibited_unless' => 'Screen "permission" is only supported on server screens.',
|
||||
'ui.screens.*.nav.icon.regex' => 'Navigation "icon" must be a lucide icon name such as "life-buoy".',
|
||||
'ui.screens.*.when.eggFeatures.prohibited_unless' => 'Screen "when" egg rules are only supported on server screens.',
|
||||
@@ -220,6 +229,35 @@ class ExtensionManifestValidator
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* A theme setting is declared with a `type` and a `label`, or overrides the setting of the same name
|
||||
* of a theme it extends with only the fields it changes. The fields that depend on the type are
|
||||
* checked once an override is merged over the declaration it changes.
|
||||
*
|
||||
* @return ValidationRules
|
||||
*/
|
||||
private function themeSettingRules(): array
|
||||
{
|
||||
$typed = 'exclude_without:theme.settings.*.type';
|
||||
|
||||
return [
|
||||
'theme.settings' => ['sometimes', 'array', 'max:64', $this->keyedBy(ThemeSetting::KEY_REGEX, 'Theme setting names must match '.ThemeSetting::KEY_REGEX.'.')],
|
||||
'theme.settings.*' => ['required', 'array:type,label,default,help,token,attribute,options,min,max,step,unit,maxLength'],
|
||||
'theme.settings.*.type' => ['sometimes', 'string', Rule::in(ThemeSetting::TYPES)],
|
||||
'theme.settings.*.label' => ['required_with:theme.settings.*.type', 'string', 'max:100'],
|
||||
'theme.settings.*.help' => ['sometimes', 'nullable', 'string', 'max:255'],
|
||||
'theme.settings.*.token' => ['sometimes', 'nullable', 'string', 'regex:'.ThemeSetting::TOKEN_REGEX],
|
||||
'theme.settings.*.attribute' => ['sometimes', 'nullable', 'string', 'regex:'.ThemeSetting::ATTRIBUTE_REGEX, Rule::notIn(ThemeSetting::RESERVED_ATTRIBUTES)],
|
||||
'theme.settings.*.options' => [$typed, 'required_if:theme.settings.*.type,select', 'prohibited_unless:theme.settings.*.type,select', 'array', 'min:1', 'max:64', $this->keyedBy(ThemeSetting::OPTION_REGEX, 'Theme setting options must be keyed by identifiers such as "side".')],
|
||||
'theme.settings.*.options.*' => [$typed, 'required', 'string', 'max:100'],
|
||||
'theme.settings.*.min' => [$typed, 'sometimes', 'prohibited_unless:theme.settings.*.type,number', 'numeric'],
|
||||
'theme.settings.*.max' => [$typed, 'sometimes', 'prohibited_unless:theme.settings.*.type,number', 'numeric'],
|
||||
'theme.settings.*.step' => [$typed, 'sometimes', 'prohibited_unless:theme.settings.*.type,number', 'numeric', 'gt:0'],
|
||||
'theme.settings.*.unit' => [$typed, 'sometimes', 'prohibited_unless:theme.settings.*.type,number', 'string', 'regex:'.ThemeSetting::UNIT_REGEX],
|
||||
'theme.settings.*.maxLength' => [$typed, 'sometimes', 'prohibited_unless:theme.settings.*.type,text', 'integer', 'between:1,1000'],
|
||||
];
|
||||
}
|
||||
|
||||
/** @return Closure(string, mixed, Closure(string): mixed): void */
|
||||
private function keyedBy(string $pattern, string $message): Closure
|
||||
{
|
||||
@@ -238,14 +276,11 @@ class ExtensionManifestValidator
|
||||
*/
|
||||
private function validateTheme(string $id, array $theme): void
|
||||
{
|
||||
throw_if(($theme['extends'] ?? null) === $id, InvalidExtensionException::class, "Theme \"{$id}\" cannot extend itself.");
|
||||
$extends = $theme['extends'] ?? ThemeRepository::CLASSIC;
|
||||
throw_if($extends === $id, InvalidExtensionException::class, "Theme \"{$id}\" cannot extend itself.");
|
||||
|
||||
$targets = [];
|
||||
foreach ($theme['settings'] ?? [] as $key => $setting) {
|
||||
foreach (['min', 'max', 'step'] as $limit) {
|
||||
throw_if(array_key_exists($limit, $setting) && ! is_int($setting[$limit]) && ! is_float($setting[$limit]), InvalidExtensionException::class, "Theme setting \"{$key}\" must give \"{$limit}\" as a number.");
|
||||
}
|
||||
|
||||
foreach (array_filter([$setting['token'] ?? null, $setting['attribute'] ?? null]) as $target) {
|
||||
if (isset($targets[$target])) {
|
||||
throw new InvalidExtensionException("Theme settings \"{$targets[$target]}\" and \"{$key}\" both write \"{$target}\".");
|
||||
@@ -254,10 +289,27 @@ class ExtensionManifestValidator
|
||||
$targets[$target] = $key;
|
||||
}
|
||||
|
||||
$this->validateThemeDefault(ThemeSetting::fromValidatedData($key, $setting));
|
||||
if (isset($setting['type'], $setting['label'])) {
|
||||
$this->validateThemeSetting($key, $setting);
|
||||
} else {
|
||||
throw_if($extends === ThemeRepository::CLASSIC, InvalidExtensionException::class, "Theme setting \"{$key}\" needs a \"type\" and a \"label\"; only a theme that extends another can override a setting of its parent with some of the fields.");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/** @param ExtensionThemeSettingInput $setting */
|
||||
private function validateThemeSetting(string $key, array $setting): ThemeSetting
|
||||
{
|
||||
foreach (['min', 'max', 'step'] as $limit) {
|
||||
throw_if(array_key_exists($limit, $setting) && ! is_int($setting[$limit]) && ! is_float($setting[$limit]), InvalidExtensionException::class, "Theme setting \"{$key}\" must give \"{$limit}\" as a number.");
|
||||
}
|
||||
|
||||
$theme = ThemeSetting::fromValidatedData($key, $setting);
|
||||
$this->validateThemeDefault($theme);
|
||||
|
||||
return $theme;
|
||||
}
|
||||
|
||||
private function validateThemeDefault(ThemeSetting $setting): void
|
||||
{
|
||||
$default = $setting->default;
|
||||
|
||||
@@ -23,7 +23,7 @@ class ExtensionScaffolder
|
||||
/** @var string[] package-relative paths written by the last scaffold() call */
|
||||
private array $files = [];
|
||||
|
||||
public function __construct(private readonly ExtensionManifestValidator $validator) {}
|
||||
public function __construct(private readonly ExtensionManifestValidator $validator, private readonly ThemeRepository $themes) {}
|
||||
|
||||
/**
|
||||
* Scaffolds <outDir>/<id>/, or exactly `path` when given, and returns the created
|
||||
@@ -42,6 +42,7 @@ class ExtensionScaffolder
|
||||
bool $theme = false,
|
||||
?string $path = null,
|
||||
bool $cssOnly = false,
|
||||
?string $extends = null,
|
||||
): string {
|
||||
$this->files = [];
|
||||
|
||||
@@ -53,6 +54,10 @@ class ExtensionScaffolder
|
||||
|
||||
throw_if($cssOnly && ! $theme, InvalidExtensionException::class, '--css-only scaffolds a theme: pass it with --theme.');
|
||||
|
||||
throw_if($extends !== null && ! $theme, InvalidExtensionException::class, '--extends scaffolds a theme: pass it with --theme.');
|
||||
|
||||
throw_if($extends !== null && (preg_match(ExtensionManifest::ID_REGEX, $extends) !== 1 || $extends === $id), InvalidExtensionException::class, "--extends names the theme to build on, such as \"aurora\": \"{$extends}\" is not one.");
|
||||
|
||||
$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.');
|
||||
|
||||
@@ -77,7 +82,12 @@ class ExtensionScaffolder
|
||||
];
|
||||
|
||||
if ($theme) {
|
||||
$this->scaffoldTheme($target, $id, $replacements, $cssOnly);
|
||||
if ($extends === null || $extends === ThemeRepository::CLASSIC) {
|
||||
$this->scaffoldTheme($target, $id, $replacements, $cssOnly);
|
||||
} else {
|
||||
$this->scaffoldChildTheme($target, $id, $extends, $replacements, $cssOnly);
|
||||
}
|
||||
|
||||
$this->validator->fromDirectory($target);
|
||||
|
||||
return $target;
|
||||
@@ -212,6 +222,63 @@ class ExtensionScaffolder
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* A theme that extends another and so starts from it: a manifest that names the parent, a stylesheet
|
||||
* of the one import the build adds the parent's stylesheets to, an empty `defineTheme` and a test of
|
||||
* the chain. Its settings, schemes, views and skins are the parent's until it overrides them.
|
||||
*
|
||||
* @param array<string, string> $replacements stub placeholder => literal substitution
|
||||
*/
|
||||
private function scaffoldChildTheme(string $target, string $id, string $parent, array $replacements, bool $cssOnly): void
|
||||
{
|
||||
$installed = $this->themes->installed()->get($parent);
|
||||
$chain = $installed === null ? [$parent] : [...array_map(fn (ExtensionManifest $ancestor): string => $ancestor->id, $this->themes->ancestors($installed)), $parent];
|
||||
$manifest = array_filter([
|
||||
'$schema' => './node_modules/@pterodactyl/sdk/manifest.schema.json',
|
||||
'id' => $id,
|
||||
'type' => 'theme',
|
||||
'name' => $replacements['{{name}}'],
|
||||
'version' => '1.0.0',
|
||||
'requires' => ['panel' => '^2.0.0-dev', 'sdk' => $this->sdkConstraint(), 'extensions' => [$parent => $installed === null ? '*' : '^'.$installed->version]],
|
||||
'description' => $replacements['{{description}}'] ?: null,
|
||||
'author' => $replacements['{{author}}'] ?: null,
|
||||
'icon' => 'palette',
|
||||
'ui' => $cssOnly ? null : ['entry' => ExtensionManifest::UI_ENTRY],
|
||||
'theme' => ['extends' => $parent, 'stylesheet' => ThemeDefinition::STYLESHEET],
|
||||
], fn (array|string|null $value): bool => $value !== null);
|
||||
|
||||
File::put($target.DIRECTORY_SEPARATOR.ExtensionManifest::FILENAME, json_encode($manifest, JSON_PRETTY_PRINT | JSON_UNESCAPED_SLASHES)."\n");
|
||||
$this->files[] = ExtensionManifest::FILENAME;
|
||||
|
||||
$extensions = config()->string('extensions.directory');
|
||||
$name = $installed->name ?? $parent;
|
||||
$names = array_map(fn (string $ancestor): string => in_array(Str::camel($ancestor), ['theme', 'themes'], true) ? Str::camel($ancestor).'Parent' : Str::camel($ancestor), $chain);
|
||||
$replacements += [
|
||||
'{{artisan}}' => $this->artisanPath($target),
|
||||
'{{parent}}' => $parent,
|
||||
'{{parentName}}' => $name,
|
||||
'{{extensions}}' => mb_rtrim($this->relativePath($target, $extensions) ?? str_replace('\\', '/', $extensions), '/'),
|
||||
'{{entry}}' => $cssOnly ? '' : "entry: 'src/theme.tsx', ",
|
||||
'{{parentImports}}' => implode("\n", array_map(fn (string $variable, string $ancestor): string => "import {$variable} from '{$ancestor}/dist/client.js';", $names, $chain)),
|
||||
'{{parentNames}}' => implode(', ', $names),
|
||||
'{{viewsRow}}' => $cssOnly ? '' : "| Replace or wrap one of its views; `Default` renders {$name}'s layer | `src/theme.tsx` |\n",
|
||||
'{{testsNote}}' => $cssOnly ? '' : "\n`npm test` renders views with `themes: [".implode(', ', $names).", theme]`, the chain the panel stacks, so\n`Default` in this theme's views renders {$name}'s layer. `npm run types` types `useThemeSettings()` with the\nsettings of the whole chain.\n",
|
||||
];
|
||||
$stubs = [
|
||||
$cssOnly ? 'theme-css-package.stub' : 'theme-package.stub' => 'package.json',
|
||||
'theme-child-vite.config.stub' => 'vite.config.mjs',
|
||||
'postcss.config.stub' => 'postcss.config.mjs',
|
||||
...$cssOnly ? [] : ['theme-tsconfig.stub' => 'tsconfig.json', 'theme-child-vitest.config.stub' => 'vitest.config.mjs'],
|
||||
'theme-child-css.stub' => 'src/theme.css',
|
||||
...$cssOnly ? [] : ['theme-child-tsx.stub' => 'src/theme.tsx', 'theme-child-test.stub' => 'src/theme.spec.tsx'],
|
||||
'gitignore.stub' => '.gitignore',
|
||||
'theme-child-readme.stub' => 'README.md',
|
||||
];
|
||||
foreach ($stubs as $stub => $relative) {
|
||||
$this->stub($target, $stub, $relative, $replacements);
|
||||
}
|
||||
}
|
||||
|
||||
/** The `requires.sdk` constraint of a new package: this SDK or a later 2.x one. */
|
||||
private function sdkConstraint(): string
|
||||
{
|
||||
|
||||
@@ -0,0 +1,6 @@
|
||||
/*
|
||||
* The panel stylesheet, then the stylesheets of {{parentName}} and the themes it extends, which the build
|
||||
* brings in after this import, then this theme's own rules. Retune their tokens here: an override of
|
||||
* --primary or --radius restyles everything that reads it.
|
||||
*/
|
||||
@import '@pterodactyl/sdk/theme-entry.css';
|
||||
@@ -0,0 +1,25 @@
|
||||
# {{name}}
|
||||
|
||||
A Pterodactyl panel theme that extends {{parentName}}, scaffolded by `p:extension:make --theme --extends={{parent}}`.
|
||||
Everything this theme leaves out is {{parentName}}'s: its views, skins, stylesheet and settings. The themes guide,
|
||||
`node_modules/@pterodactyl/sdk/THEMES.md`, covers each layer under "Building on another theme".
|
||||
|
||||
| To | Edit |
|
||||
| --- | --- |
|
||||
| Retune {{parentName}}'s colours, fonts, radius or spacing | `src/theme.css`, after the import |
|
||||
{{viewsRow}}| Change the default of one of its settings | `extension.json`: `"settings": { "accent": { "default": "#ff4fd8" } }` |
|
||||
| Add settings of this theme's own | `extension.json`, with a `type` and a `label` |
|
||||
|
||||
The build finds {{parentName}} in the panel's extensions directory (`extensions` in `vite.config.mjs`), else in
|
||||
`node_modules`, and builds its stylesheet and classes in after the panel's, so `src/theme.css` stays one import
|
||||
plus your own rules. Rebuild after {{parentName}} changes; `npm run doctor` says when it has.
|
||||
|
||||
## Develop
|
||||
|
||||
```sh
|
||||
npm install
|
||||
php {{artisan}} p:extension:dev . --enable
|
||||
php {{artisan}} p:theme:activate {{id}}
|
||||
php {{artisan}} p:extension:dev . --watch
|
||||
```
|
||||
{{testsNote}}
|
||||
@@ -0,0 +1,18 @@
|
||||
import { afterEach, beforeAll, expect, test } from 'vitest';
|
||||
import { preloadTheme, renderView, type RenderedView } from '@pterodactyl/sdk/testing';
|
||||
{{parentImports}}
|
||||
import theme from './theme';
|
||||
|
||||
// The chain the panel stacks over classic, oldest first: the themes this one extends, then this one.
|
||||
const themes = [{{parentNames}}, theme];
|
||||
|
||||
let rendered: RenderedView | undefined;
|
||||
|
||||
beforeAll(() => preloadTheme(themes));
|
||||
afterEach(() => rendered?.unmount());
|
||||
|
||||
test('renders a server card with the views of the themes it extends', () => {
|
||||
rendered = renderView('dashboard.serverCard', { themes, fixture: 'running' });
|
||||
|
||||
expect(rendered.container.textContent).toContain('Test server');
|
||||
});
|
||||
@@ -0,0 +1,7 @@
|
||||
import { defineTheme } from '@pterodactyl/sdk/theme';
|
||||
|
||||
/**
|
||||
* {{name}} extends {{parentName}} ("theme.extends" in extension.json): every view and skin it leaves out is
|
||||
* {{parentName}}'s, and a view it adds receives {{parentName}}'s layer as `Default`.
|
||||
*/
|
||||
export default defineTheme({});
|
||||
@@ -0,0 +1,4 @@
|
||||
import { defineThemeConfig } from '@pterodactyl/sdk/vite';
|
||||
|
||||
// {{parentName}} and the themes it extends are found in the panel's extensions directory, then in node_modules.
|
||||
export default defineThemeConfig({ {{entry}}stylesheet: 'src/theme.css', extensions: '{{extensions}}' });
|
||||
@@ -0,0 +1,9 @@
|
||||
import { defineConfig } from 'vitest/config';
|
||||
import { pterodactylTestAliases, pterodactylTestSetup, pterodactylTestDirectory } from '@pterodactyl/sdk/vitest';
|
||||
|
||||
// `extensions` lets the tests import the built entries of the themes this one extends: '{{parent}}/dist/client.js'.
|
||||
export default defineConfig({
|
||||
server: { fs: { allow: [process.cwd(), pterodactylTestDirectory] } },
|
||||
resolve: { alias: pterodactylTestAliases({ extensions: '{{extensions}}' }) },
|
||||
test: { environment: 'jsdom', setupFiles: [pterodactylTestSetup] },
|
||||
});
|
||||
@@ -1,7 +1,8 @@
|
||||
# {{name}}
|
||||
|
||||
A Pterodactyl panel theme, scaffolded by `p:extension:make --theme`. The themes guide,
|
||||
`node_modules/@pterodactyl/sdk/THEMES.md`, goes one level at a time; stop at the level you need.
|
||||
`node_modules/@pterodactyl/sdk/THEMES.md`, goes one level at a time; stop at the level you need. To start
|
||||
from another theme instead, scaffold with `--extends=<theme>`.
|
||||
|
||||
| To | Edit | Guide |
|
||||
| --- | --- | --- |
|
||||
|
||||
@@ -19,8 +19,16 @@ final readonly class ThemeBuild
|
||||
/**
|
||||
* @param string|null $core hash of the core class manifest the stylesheet was built against
|
||||
* @param list<string>|null $views the view names the theme overrides, when the preset could read them
|
||||
* @param string|null $build hash of dist/theme-source.css and dist/classes.txt, which the build of a theme extending this one imports
|
||||
* @param array<string, string|null>|null $parents the builds of the themes this one extends that its stylesheet was built over, by id
|
||||
*/
|
||||
public function __construct(public ?string $core = null, public ?string $sdk = null, public ?array $views = null) {}
|
||||
public function __construct(
|
||||
public ?string $core = null,
|
||||
public ?string $sdk = null,
|
||||
public ?array $views = null,
|
||||
public ?string $build = null,
|
||||
public ?array $parents = null,
|
||||
) {}
|
||||
|
||||
public static function of(ExtensionManifest $theme): self
|
||||
{
|
||||
@@ -30,10 +38,14 @@ final readonly class ThemeBuild
|
||||
return new self;
|
||||
}
|
||||
|
||||
$parents = $data['parents'] ?? null;
|
||||
|
||||
return new self(
|
||||
core: is_string($data['core'] ?? null) ? $data['core'] : null,
|
||||
sdk: is_string($data['sdk'] ?? null) ? $data['sdk'] : null,
|
||||
views: is_array($data['views'] ?? null) ? array_values(array_filter($data['views'], is_string(...))) : null,
|
||||
build: is_string($data['build'] ?? null) ? $data['build'] : null,
|
||||
parents: is_array($parents) ? array_filter($parents, fn (mixed $build, int|string $id): bool => is_string($id) && ($build === null || is_string($build)), ARRAY_FILTER_USE_BOTH) : null,
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -4,10 +4,6 @@ declare(strict_types=1);
|
||||
|
||||
namespace Pterodactyl\Services\Themes;
|
||||
|
||||
use Pterodactyl\Services\Extensions\ExtensionSettingDefinition;
|
||||
use Pterodactyl\Services\Extensions\ExtensionSettings;
|
||||
use Pterodactyl\Services\Extensions\ExtensionSettingsDefinition;
|
||||
|
||||
/**
|
||||
* The `theme` section of a theme package's extension.json.
|
||||
*/
|
||||
@@ -22,21 +18,28 @@ final readonly class ThemeDefinition
|
||||
|
||||
/**
|
||||
* @param list<'dark'|'light'>|null $schemes null inherits the parent's
|
||||
* @param array<string, ThemeSetting> $settings
|
||||
* @param array<string, ThemeSetting> $settings the settings declared in full
|
||||
* @param array<string, ExtensionThemeSettingOverride> $overrides the fields that change a setting of the same name of a theme this one extends
|
||||
*/
|
||||
public function __construct(
|
||||
public string $extends = ThemeRepository::CLASSIC,
|
||||
public ?string $stylesheet = null,
|
||||
public ?array $schemes = null,
|
||||
public array $settings = [],
|
||||
public array $overrides = [],
|
||||
) {}
|
||||
|
||||
/** @param ExtensionThemeInput $data */
|
||||
public static function fromValidatedData(array $data): self
|
||||
{
|
||||
$settings = [];
|
||||
$overrides = [];
|
||||
foreach ($data['settings'] ?? [] as $key => $setting) {
|
||||
$settings[$key] = ThemeSetting::fromValidatedData($key, $setting);
|
||||
if (isset($setting['type'], $setting['label'])) {
|
||||
$settings[$key] = ThemeSetting::fromValidatedData($key, $setting);
|
||||
} else {
|
||||
$overrides[$key] = $setting;
|
||||
}
|
||||
}
|
||||
|
||||
return new self(
|
||||
@@ -44,11 +47,7 @@ final readonly class ThemeDefinition
|
||||
stylesheet: $data['stylesheet'] ?? null,
|
||||
schemes: $data['schemes'] ?? null,
|
||||
settings: $settings,
|
||||
overrides: $overrides,
|
||||
);
|
||||
}
|
||||
|
||||
public function settingsDefinition(ExtensionSettings $settings): ExtensionSettingsDefinition
|
||||
{
|
||||
return new ExtensionSettingsDefinition($settings, array_values(array_map(fn (ThemeSetting $setting): ExtensionSettingDefinition => $setting->definition(), $this->settings)));
|
||||
}
|
||||
}
|
||||
|
||||
@@ -8,9 +8,12 @@ use Illuminate\Support\Collection;
|
||||
use Pterodactyl\Exceptions\Extensions\InvalidExtensionException;
|
||||
use Pterodactyl\Models\Setting;
|
||||
use Pterodactyl\Services\Extensions\ExtensionManifest;
|
||||
use Pterodactyl\Services\Extensions\ExtensionManifestValidator;
|
||||
use Pterodactyl\Services\Extensions\ExtensionRepository;
|
||||
use Pterodactyl\Services\Extensions\ExtensionSettingDefinition;
|
||||
use Pterodactyl\Services\Extensions\ExtensionSettingsDefinition;
|
||||
use Pterodactyl\Services\Helpers\AssetHashService;
|
||||
use WeakMap;
|
||||
|
||||
/**
|
||||
* Installed themes, the active one, and the chain of parents each is built on.
|
||||
@@ -28,7 +31,16 @@ class ThemeRepository
|
||||
|
||||
private ?string $active = null;
|
||||
|
||||
public function __construct(private readonly ExtensionRepository $extensions, private readonly AssetHashService $assets) {}
|
||||
/** @var WeakMap<ExtensionManifest, array<string, ThemeSetting>> */
|
||||
private WeakMap $declarations;
|
||||
|
||||
public function __construct(
|
||||
private readonly ExtensionRepository $extensions,
|
||||
private readonly AssetHashService $assets,
|
||||
private readonly ExtensionManifestValidator $validator,
|
||||
) {
|
||||
$this->declarations = new WeakMap;
|
||||
}
|
||||
|
||||
/** @return Collection<string, ExtensionManifest> */
|
||||
public function installed(): Collection
|
||||
@@ -79,7 +91,111 @@ class ThemeRepository
|
||||
$id = $manifest->theme->extends;
|
||||
}
|
||||
|
||||
return array_reverse(array_values($chain));
|
||||
$chain = array_reverse(array_values($chain));
|
||||
foreach ($chain as $theme) {
|
||||
$this->declarations($theme);
|
||||
}
|
||||
|
||||
return $chain;
|
||||
}
|
||||
|
||||
/**
|
||||
* The themes a theme extends, oldest first and without classic, found as its build finds them:
|
||||
* installed in the panel, else in the package's node_modules. The list starts after a parent
|
||||
* that is in neither.
|
||||
*
|
||||
* @return list<ExtensionManifest>
|
||||
*/
|
||||
public function ancestors(ExtensionManifest $theme): array
|
||||
{
|
||||
$ancestors = [];
|
||||
$seen = [$theme->id => true];
|
||||
$id = $theme->theme->extends ?? self::CLASSIC;
|
||||
while ($id !== self::CLASSIC && ! isset($seen[$id])) {
|
||||
$seen[$id] = true;
|
||||
$parent = $this->extensions->discovered()->get($id);
|
||||
if (! $parent instanceof ExtensionManifest && is_dir($theme->path('node_modules', $id))) {
|
||||
try {
|
||||
$parent = $this->validator->fromDirectory($theme->path('node_modules', $id));
|
||||
} catch (InvalidExtensionException) {
|
||||
}
|
||||
}
|
||||
|
||||
if (! $parent?->isTheme() || $parent->id !== $id) {
|
||||
break;
|
||||
}
|
||||
|
||||
array_unshift($ancestors, $parent);
|
||||
$id = $parent->theme->extends;
|
||||
}
|
||||
|
||||
return $ancestors;
|
||||
}
|
||||
|
||||
/**
|
||||
* The settings a theme declares: those it declares in full, and each override merged over the
|
||||
* declaration of the nearest theme it extends that has the setting.
|
||||
*
|
||||
* @return array<string, ThemeSetting>
|
||||
*
|
||||
* @throws InvalidExtensionException when an override changes no setting of those themes, or makes an invalid one
|
||||
*/
|
||||
public function declarations(ExtensionManifest $theme): array
|
||||
{
|
||||
if (isset($this->declarations[$theme])) {
|
||||
return $this->declarations[$theme];
|
||||
}
|
||||
|
||||
$ancestors = $this->ancestors($theme);
|
||||
$parent = $theme->theme->extends ?? self::CLASSIC;
|
||||
throw_if(($theme->theme->overrides ?? []) !== [] && (end($ancestors) ?: null)?->id !== $parent, InvalidExtensionException::class, sprintf('Theme "%s" overrides settings of "%s", which is not installed.', $theme->id, $parent));
|
||||
|
||||
$inherited = [];
|
||||
foreach ($ancestors as $ancestor) {
|
||||
$inherited = [...$inherited, ...$this->declaredOver($ancestor, $inherited)];
|
||||
}
|
||||
|
||||
return $this->declarations[$theme] = $this->declaredOver($theme, $inherited);
|
||||
}
|
||||
|
||||
/**
|
||||
* Why a child theme's stylesheet cannot be used: dist/theme.json does not record the builds of the
|
||||
* themes it extends, so it was not built over their stylesheets and classes.
|
||||
*/
|
||||
public function parentBuildProblem(ExtensionManifest $theme): ?string
|
||||
{
|
||||
if ($theme->theme?->stylesheet === null || $theme->theme->extends === self::CLASSIC) {
|
||||
return null;
|
||||
}
|
||||
|
||||
$ancestors = array_map(fn (ExtensionManifest $ancestor): string => $ancestor->id, $this->ancestors($theme));
|
||||
$missing = array_values(array_diff(array_unique([...$ancestors, $theme->theme->extends]), array_keys(ThemeBuild::of($theme)->parents ?? [])));
|
||||
|
||||
return $missing === [] ? null : sprintf(
|
||||
'Theme "%s" extends "%s", but its stylesheet was not built over the stylesheet of "%s". Rebuild it with this panel\'s SDK, whose build brings in the stylesheets of the themes it extends.',
|
||||
$theme->id,
|
||||
$theme->theme->extends,
|
||||
implode('", "', $missing),
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* The themes a child theme extends that were rebuilt since its stylesheet was built over them.
|
||||
*
|
||||
* @return list<string>
|
||||
*/
|
||||
public function staleParents(ExtensionManifest $theme): array
|
||||
{
|
||||
$recorded = ThemeBuild::of($theme)->parents ?? [];
|
||||
$stale = [];
|
||||
foreach ($this->ancestors($theme) as $ancestor) {
|
||||
$current = ThemeBuild::of($ancestor)->build;
|
||||
if (($recorded[$ancestor->id] ?? null) !== null && $current !== null && $recorded[$ancestor->id] !== $current) {
|
||||
$stale[] = sprintf('Theme "%s" was built over build %s of "%s", which is now build %s; rebuild "%s" to bring in its current stylesheet.', $theme->id, $recorded[$ancestor->id], $ancestor->id, $current, $theme->id);
|
||||
}
|
||||
}
|
||||
|
||||
return $stale;
|
||||
}
|
||||
|
||||
/** @throws InvalidExtensionException while the theme is the active one */
|
||||
@@ -135,8 +251,51 @@ class ThemeRepository
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* The settings a theme declares, as far as they can be resolved: an override of a parent that is
|
||||
* not installed is left out.
|
||||
*
|
||||
* @return array<string, ThemeSetting>
|
||||
*/
|
||||
public function declared(ExtensionManifest $theme): array
|
||||
{
|
||||
try {
|
||||
return $this->declarations($theme);
|
||||
} catch (InvalidExtensionException) {
|
||||
return $theme->theme->settings ?? [];
|
||||
}
|
||||
}
|
||||
|
||||
public function settings(ExtensionManifest $theme): ExtensionSettingsDefinition
|
||||
{
|
||||
return ($theme->theme ?? new ThemeDefinition)->settingsDefinition($this->extensions->settings($theme->id));
|
||||
return new ExtensionSettingsDefinition($this->extensions->settings($theme->id), array_values(array_map(fn (ThemeSetting $setting): ExtensionSettingDefinition => $setting->definition(), $this->declared($theme))));
|
||||
}
|
||||
|
||||
/**
|
||||
* @param array<string, ThemeSetting> $inherited the settings of the themes it extends, by name
|
||||
* @return array<string, ThemeSetting>
|
||||
*/
|
||||
private function declaredOver(ExtensionManifest $theme, array $inherited): array
|
||||
{
|
||||
$declared = [];
|
||||
foreach ($theme->theme->overrides ?? [] as $key => $override) {
|
||||
$parent = $inherited[$key] ?? throw new InvalidExtensionException(sprintf('Theme "%s" overrides setting "%s", which no theme it extends declares.', $theme->id, $key));
|
||||
try {
|
||||
$declared[$key] = $this->validator->themeSetting($key, $parent->overriddenBy($override));
|
||||
} catch (InvalidExtensionException $invalidExtensionException) {
|
||||
throw new InvalidExtensionException(sprintf('Theme "%s" overrides setting "%s": %s', $theme->id, $key, $invalidExtensionException->getMessage()), $invalidExtensionException->getCode(), previous: $invalidExtensionException);
|
||||
}
|
||||
}
|
||||
|
||||
$declared = [...$declared, ...$theme->theme->settings ?? []];
|
||||
$targets = [];
|
||||
foreach ($declared as $key => $setting) {
|
||||
foreach (array_filter([$setting->token, $setting->attribute]) as $target) {
|
||||
throw_if(isset($targets[$target]), InvalidExtensionException::class, sprintf('Theme settings "%s" and "%s" of "%s" both write "%s".', $targets[$target] ?? '', $key, $theme->id, $target));
|
||||
$targets[$target] = $key;
|
||||
}
|
||||
}
|
||||
|
||||
return $declared;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -103,7 +103,7 @@ class ThemeResolver
|
||||
|
||||
/**
|
||||
* The chain's setting values, and what they write as tokens and attributes. A child's
|
||||
* setting of the same name replaces its parent's.
|
||||
* setting of the same name replaces its parent's, and its value is the child's.
|
||||
*
|
||||
* @param list<ExtensionManifest> $chain
|
||||
* @return array{0: array<string, string|int|float|bool|null>, 1: array<string, string>, 2: array<string, string>}
|
||||
@@ -116,7 +116,7 @@ class ThemeResolver
|
||||
$attributes = [];
|
||||
foreach ($chain as $theme) {
|
||||
$stored = $this->themes->settings($theme);
|
||||
foreach ($theme->theme->settings ?? [] as $key => $setting) {
|
||||
foreach ($this->themes->declared($theme) as $key => $setting) {
|
||||
$value = $setting->value(rescue(fn (): mixed => $stored->get(ThemeSetting::KEY_PREFIX.$key), report: false));
|
||||
$values[$key] = $value;
|
||||
if ($setting->token !== null && ($token = $setting->tokenValue($value)) !== null) {
|
||||
|
||||
@@ -89,6 +89,33 @@ final readonly class ThemeSetting
|
||||
return '"'.$escaped.'"';
|
||||
}
|
||||
|
||||
/**
|
||||
* The declaration a child theme's override of this setting makes: these fields, with the ones the
|
||||
* override gives in their place.
|
||||
*
|
||||
* @param ExtensionThemeSettingOverride $override
|
||||
* @return ExtensionThemeSettingOverride
|
||||
*/
|
||||
public function overriddenBy(array $override): array
|
||||
{
|
||||
$declaration = array_filter([
|
||||
'type' => $this->type,
|
||||
'label' => $this->label,
|
||||
'default' => $this->default,
|
||||
'help' => $this->help,
|
||||
'token' => $this->token,
|
||||
'attribute' => $this->attribute,
|
||||
'options' => $this->type === 'select' ? $this->options : null,
|
||||
'min' => $this->min,
|
||||
'max' => $this->max,
|
||||
'step' => $this->step,
|
||||
'unit' => $this->unit,
|
||||
'maxLength' => $this->type === 'text' ? $this->maxLength : null,
|
||||
], fn (mixed $value): bool => $value !== null);
|
||||
|
||||
return [...$declaration, ...$override];
|
||||
}
|
||||
|
||||
/**
|
||||
* The extension setting that validates and stores this setting's value, with the same
|
||||
* rules as the matching `->color()`, `->field()` and `->file()` definitions. A cleared
|
||||
|
||||
@@ -929,7 +929,7 @@ 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 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?, 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).
|
||||
The testing entry exports `createViewTestHost(name, { model?, fixture?, input?, extensionId?, prefix?, strict?, theme?, themes? })`, 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
|
||||
|
||||
|
||||
+104
-15
@@ -864,19 +864,107 @@ offers both; the [sidebar shell](#a-sidebar-shell) uses it for its switch.
|
||||
### Building on another theme
|
||||
|
||||
`theme.extends` names an installed theme to build on; it is `classic` when left out. The chain runs
|
||||
classic, the parent and its parents, then the child:
|
||||
classic, the parent and its parents, then the child. `p:extension:make sunset --theme --extends=aurora`
|
||||
scaffolds a child: a manifest naming the parent, a stylesheet of one import, an empty `defineTheme` and a
|
||||
test of the chain.
|
||||
|
||||
- **Views and skins** stack in that order, so the child's `Default` renders the parent's layer.
|
||||
- **Settings** are the union of the chain's. A child's setting of the same name replaces the parent's,
|
||||
which is how a child changes a default.
|
||||
- **Views and skins** stack in that order, so the child's `Default` renders the parent's layer, and
|
||||
`skin(name, (below) => …)` builds on the parent's skin.
|
||||
- **Settings** are the union of the chain's. A child's setting of the same name changes the parent's: give
|
||||
only the fields that change, such as `"accent": { "default": "#f97316" }`, and the rest are the parent's.
|
||||
- **Schemes** are the child's when it declares them, else the nearest parent's.
|
||||
- **Stylesheet.** The panel links the nearest stylesheet in the chain. A child with its own replaces
|
||||
the parent's whole, so import the parent's source CSS into yours to build on it.
|
||||
- The parent has to be installed and enabled first, and cannot be disabled while the child is. A
|
||||
missing parent or a cycle stops the child from activating. Pin its version with `requires.extensions`.
|
||||
|
||||
[`docs-samples/child-theme`](docs-samples/child-theme) in the panel repository extends Aurora, the full
|
||||
example.
|
||||
<!-- sample: child-theme/extension.json -->
|
||||
```json
|
||||
{
|
||||
"$schema": "./node_modules/@pterodactyl/sdk/manifest.schema.json",
|
||||
"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",
|
||||
"stylesheet": "dist/theme.css",
|
||||
"settings": {
|
||||
"accent": { "default": "#f97316" },
|
||||
"glow": { "type": "toggle", "label": "Sunset glow", "default": true, "attribute": "data-sunset-glow" }
|
||||
}
|
||||
}
|
||||
}
|
||||
```
|
||||
<!-- /sample -->
|
||||
|
||||
The panel links one stylesheet, the nearest in the chain, so a child's stylesheet carries its parents'.
|
||||
The build does that: every theme build also writes `dist/theme-source.css`, its own CSS with its imports
|
||||
inlined and its fonts beside it, and `dist/classes.txt`, the classes its source files use. A child's build
|
||||
reads `theme.extends`, finds each parent, and brings in their stylesheets and classes, oldest first, right
|
||||
after the SDK's import. The child's `src/theme.css` stays one import and its own rules, and can use the
|
||||
parents' utilities, variants and fonts:
|
||||
|
||||
<!-- sample: child-theme/src/theme.css -->
|
||||
```css
|
||||
/* The panel stylesheet. The build brings in Aurora's after it, so this file only retunes Aurora. */
|
||||
@import '@pterodactyl/sdk/theme-entry.css';
|
||||
|
||||
/* Aurora's tokens, warmer. Its glass, sidebar and skins read them. */
|
||||
:root {
|
||||
--radius: 1rem;
|
||||
--glass-border: color-mix(in oklab, var(--primary) 20%, transparent);
|
||||
}
|
||||
|
||||
.dark {
|
||||
--background: oklch(0.18 0.03 40);
|
||||
--card: oklch(0.24 0.035 40);
|
||||
}
|
||||
|
||||
/* The "glow" setting writes data-sunset-glow on <html>; `glass` is Aurora's utility. */
|
||||
[data-sunset-glow='true'] .glass {
|
||||
box-shadow: 0 0 2rem -1rem var(--primary);
|
||||
}
|
||||
```
|
||||
<!-- /sample -->
|
||||
|
||||
The build looks for each parent first in `<extensions>/<id>`, where `extensions` is the panel's extensions
|
||||
directory passed to `defineThemeConfig` (the scaffold writes it), then in `node_modules/<id>`, for a parent
|
||||
installed as a dependency. It records the build of each parent in `dist/theme.json`. Doctor, pack and enable
|
||||
refuse a child built without its parents, and doctor warns when a parent was rebuilt since; rebuild the
|
||||
child then. A parent's `@plugin` is loaded from the child's packages, so install the same plugins.
|
||||
|
||||
The child's tests render the chain with `themes`, importing each parent's built entry, which
|
||||
`pterodactylTestAliases({ extensions })` finds where the build does and the SDK types:
|
||||
|
||||
<!-- sample: child-theme/src/theme.spec.tsx#tests -->
|
||||
```tsx
|
||||
// The chain the panel stacks over classic: Aurora, then this theme.
|
||||
const themes = [aurora, theme];
|
||||
let rendered: RenderedView | undefined;
|
||||
|
||||
beforeAll(() => preloadTheme(themes));
|
||||
afterEach(() => rendered?.unmount());
|
||||
|
||||
test("frames Aurora's server card", () => {
|
||||
rendered = renderView('dashboard.serverCard', { themes, fixture: 'running' });
|
||||
|
||||
// `Default` is Aurora's card, not classic's.
|
||||
expect(rendered.container.querySelector('.border-l-2 > .space-y-3 .font-mono')).not.toBeNull();
|
||||
});
|
||||
|
||||
test("adds a shadow to Aurora's pill buttons", () => {
|
||||
rendered = renderPrimitive('Button', { children: 'Save' }, { themes });
|
||||
|
||||
expect(rendered.container.querySelector('button')?.className).toContain('rounded-full');
|
||||
expect(rendered.container.querySelector('button')?.className).toContain('shadow-primary/20');
|
||||
});
|
||||
```
|
||||
<!-- /sample -->
|
||||
|
||||
`import aurora from 'aurora/dist/client.js'` brings in the parent. `npm run types` types `useThemeSettings()`
|
||||
with the settings of the whole chain. [`docs-samples/child-theme`](docs-samples/child-theme) in the panel
|
||||
repository extends the Aurora sample.
|
||||
|
||||
## Tools
|
||||
|
||||
@@ -924,14 +1012,15 @@ one that a test drives. `@pterodactyl/sdk/testing` renders with your theme:
|
||||
- `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.
|
||||
returns `{ container, unmount }`; each call replaces the previous render. A child theme passes its
|
||||
chain, oldest first, as `themes: [parent, theme]` ([Building on another theme](#building-on-another-theme)).
|
||||
- `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()`.
|
||||
- `preloadTheme(theme)` loads the theme's `lazyView` chunks, or a chain's. Await it in `beforeAll`:
|
||||
`renderView` throws until it has.
|
||||
- `createViewTestHost(name, { model, themes })` renders one layer by hand with typed `props`, for
|
||||
asserting on actions with `vi.fn()`. Its `Default` renders the top layer of `themes`, else classic.
|
||||
|
||||
`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`,
|
||||
@@ -972,8 +1061,8 @@ rendered = renderView('layout.app', {
|
||||
### 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.
|
||||
[budgets](#budgets), remote URLs, view names, whether the stylesheet was built against this panel's
|
||||
classes, and for a child theme, over the current builds of its parents.
|
||||
|
||||
`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
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
import { mkdtempSync, readFileSync, rmSync, statSync } from 'node:fs';
|
||||
import { cpSync, mkdtempSync, readFileSync, rmSync, statSync } from 'node:fs';
|
||||
import { tmpdir } from 'node:os';
|
||||
import { resolve } from 'node:path';
|
||||
import postcss from 'postcss';
|
||||
@@ -62,3 +62,51 @@ it('builds the sample theme entry and records the views it overrides', async ()
|
||||
rmSync(outDir, { recursive: true, force: true });
|
||||
}
|
||||
}, 60_000);
|
||||
|
||||
it("builds the child theme sample over Aurora's stylesheet and classes", async () => {
|
||||
const extensions = mkdtempSync(resolve(tmpdir(), 'extensions-'));
|
||||
const child = resolve(samples, 'child-theme');
|
||||
try {
|
||||
// Aurora installed in a panel: its manifest beside its build.
|
||||
cpSync(resolve(aurora, 'extension.json'), resolve(extensions, 'aurora/extension.json'));
|
||||
await build({
|
||||
...defineThemeConfig({
|
||||
entry: resolve(aurora, 'src/theme.tsx'),
|
||||
stylesheet: resolve(aurora, 'src/theme.css'),
|
||||
outDir: resolve(extensions, 'aurora/dist'),
|
||||
}),
|
||||
configFile: false,
|
||||
logLevel: 'silent',
|
||||
});
|
||||
const parent = (file: string) => readFileSync(resolve(extensions, 'aurora/dist', file), 'utf8');
|
||||
|
||||
expect(parent('theme-source.css')).toContain('@utility glass');
|
||||
expect(parent('theme-source.css')).not.toContain('@pterodactyl/sdk');
|
||||
expect(parent('classes.txt').split('\n')).toContain('glass');
|
||||
|
||||
await build({
|
||||
...defineThemeConfig({
|
||||
entry: resolve(child, 'src/theme.tsx'),
|
||||
stylesheet: resolve(child, 'src/theme.css'),
|
||||
outDir: resolve(extensions, 'aurora-sunset/dist'),
|
||||
extensions,
|
||||
}),
|
||||
// The build keeps its copy of Aurora's stylesheet in Vite's cache directory.
|
||||
cacheDir: resolve(extensions, '.vite'),
|
||||
configFile: false,
|
||||
logLevel: 'silent',
|
||||
});
|
||||
const css = readFileSync(resolve(extensions, 'aurora-sunset/dist/theme.css'), 'utf8');
|
||||
|
||||
// Aurora's utilities, variants and fonts, then the child's own rules after them.
|
||||
expect(css).toMatch(/data-aurora-sidebar=['"]?right/);
|
||||
expect(css).toMatch(/font-family:\s*['"]?Aurora Sans/);
|
||||
expect(css.search(/data-sunset-glow=['"]?true['"]?\]\s*\.glass/)).toBeGreaterThan(css.search(/\.glass\s*\{/));
|
||||
expect(css.search(/\.glass\s*\{/)).toBeGreaterThan(-1);
|
||||
expect(JSON.parse(readFileSync(resolve(extensions, 'aurora-sunset/dist/theme.json'), 'utf8')).parents).toEqual({
|
||||
aurora: JSON.parse(parent('theme.json')).build,
|
||||
});
|
||||
} finally {
|
||||
rmSync(extensions, { recursive: true, force: true });
|
||||
}
|
||||
}, 120_000);
|
||||
|
||||
@@ -1,4 +1,5 @@
|
||||
{
|
||||
"$schema": "./node_modules/@pterodactyl/sdk/manifest.schema.json",
|
||||
"id": "aurora-sunset",
|
||||
"type": "theme",
|
||||
"name": "Aurora Sunset",
|
||||
@@ -7,8 +8,10 @@
|
||||
"ui": { "entry": "dist/client.js" },
|
||||
"theme": {
|
||||
"extends": "aurora",
|
||||
"stylesheet": "dist/theme.css",
|
||||
"settings": {
|
||||
"accent": { "type": "color", "label": "Accent", "default": "#f97316", "token": "--aurora-accent" }
|
||||
"accent": { "default": "#f97316" },
|
||||
"glow": { "type": "toggle", "label": "Sunset glow", "default": true, "attribute": "data-sunset-glow" }
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,18 @@
|
||||
/* The panel stylesheet. The build brings in Aurora's after it, so this file only retunes Aurora. */
|
||||
@import '@pterodactyl/sdk/theme-entry.css';
|
||||
|
||||
/* Aurora's tokens, warmer. Its glass, sidebar and skins read them. */
|
||||
:root {
|
||||
--radius: 1rem;
|
||||
--glass-border: color-mix(in oklab, var(--primary) 20%, transparent);
|
||||
}
|
||||
|
||||
.dark {
|
||||
--background: oklch(0.18 0.03 40);
|
||||
--card: oklch(0.24 0.035 40);
|
||||
}
|
||||
|
||||
/* The "glow" setting writes data-sunset-glow on <html>; `glass` is Aurora's utility. */
|
||||
[data-sunset-glow='true'] .glass {
|
||||
box-shadow: 0 0 2rem -1rem var(--primary);
|
||||
}
|
||||
@@ -0,0 +1,27 @@
|
||||
import { afterEach, beforeAll, expect, test } from 'vitest';
|
||||
import { preloadTheme, renderPrimitive, renderView, type RenderedView } from '@pterodactyl/sdk/testing';
|
||||
import aurora from 'aurora/dist/client.js';
|
||||
import theme from './theme';
|
||||
|
||||
// #region tests
|
||||
// The chain the panel stacks over classic: Aurora, then this theme.
|
||||
const themes = [aurora, theme];
|
||||
let rendered: RenderedView | undefined;
|
||||
|
||||
beforeAll(() => preloadTheme(themes));
|
||||
afterEach(() => rendered?.unmount());
|
||||
|
||||
test("frames Aurora's server card", () => {
|
||||
rendered = renderView('dashboard.serverCard', { themes, fixture: 'running' });
|
||||
|
||||
// `Default` is Aurora's card, not classic's.
|
||||
expect(rendered.container.querySelector('.border-l-2 > .space-y-3 .font-mono')).not.toBeNull();
|
||||
});
|
||||
|
||||
test("adds a shadow to Aurora's pill buttons", () => {
|
||||
rendered = renderPrimitive('Button', { children: 'Save' }, { themes });
|
||||
|
||||
expect(rendered.container.querySelector('button')?.className).toContain('rounded-full');
|
||||
expect(rendered.container.querySelector('button')?.className).toContain('shadow-primary/20');
|
||||
});
|
||||
// #endregion tests
|
||||
@@ -1,4 +1,4 @@
|
||||
import { defineTheme, type ViewProps } from '@pterodactyl/sdk/theme';
|
||||
import { defineTheme, skin, type ViewProps } from '@pterodactyl/sdk/theme';
|
||||
|
||||
/** Aurora's server card is the layer below, so `Default` renders it. */
|
||||
function SunsetCard({ Default }: ViewProps<'dashboard.serverCard'>) {
|
||||
@@ -9,4 +9,9 @@ function SunsetCard({ Default }: ViewProps<'dashboard.serverCard'>) {
|
||||
);
|
||||
}
|
||||
|
||||
export default defineTheme({ views: { 'dashboard.serverCard': SunsetCard } });
|
||||
/** `below` is Aurora's skin: its pill buttons, with a warm shadow. */
|
||||
const button = skin('Button', (below) => ({
|
||||
root: (state) => `${below.root(state)} shadow-lg shadow-primary/20`,
|
||||
}));
|
||||
|
||||
export default defineTheme({ ui: { Button: button }, views: { 'dashboard.serverCard': SunsetCard } });
|
||||
|
||||
@@ -0,0 +1,4 @@
|
||||
import { defineThemeConfig } from '@pterodactyl/sdk/vite';
|
||||
|
||||
// Aurora is found in the panel's extensions directory, then in node_modules.
|
||||
export default defineThemeConfig({ entry: 'src/theme.tsx', stylesheet: 'src/theme.css', extensions: '..' });
|
||||
@@ -5,7 +5,16 @@ import { pterodactylTestAliases, pterodactylTestSetup } from '../vitest.mjs';
|
||||
// Runs the docs' 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() },
|
||||
resolve: {
|
||||
alias: [
|
||||
...pterodactylTestAliases(),
|
||||
// The child theme sample imports Aurora's built entry; the Aurora sample's source stands in for it.
|
||||
{
|
||||
find: /^aurora\/dist\/client\.js$/,
|
||||
replacement: fileURLToPath(new URL('./aurora/src/theme.tsx', import.meta.url)),
|
||||
},
|
||||
],
|
||||
},
|
||||
test: {
|
||||
name: 'docs-samples',
|
||||
environment: 'jsdom',
|
||||
|
||||
@@ -584,10 +584,11 @@
|
||||
"additionalProperties": {
|
||||
"type": "object",
|
||||
"additionalProperties": false,
|
||||
"required": [
|
||||
"type",
|
||||
"label"
|
||||
],
|
||||
"dependentRequired": {
|
||||
"type": [
|
||||
"label"
|
||||
]
|
||||
},
|
||||
"properties": {
|
||||
"type": {
|
||||
"enum": [
|
||||
@@ -677,6 +678,9 @@
|
||||
"allOf": [
|
||||
{
|
||||
"if": {
|
||||
"required": [
|
||||
"type"
|
||||
],
|
||||
"properties": {
|
||||
"type": {
|
||||
"const": "select"
|
||||
@@ -687,8 +691,22 @@
|
||||
"required": [
|
||||
"options"
|
||||
]
|
||||
}
|
||||
},
|
||||
{
|
||||
"if": {
|
||||
"required": [
|
||||
"type"
|
||||
],
|
||||
"properties": {
|
||||
"type": {
|
||||
"not": {
|
||||
"const": "select"
|
||||
}
|
||||
}
|
||||
}
|
||||
},
|
||||
"else": {
|
||||
"then": {
|
||||
"not": {
|
||||
"required": [
|
||||
"options"
|
||||
@@ -698,6 +716,9 @@
|
||||
},
|
||||
{
|
||||
"if": {
|
||||
"required": [
|
||||
"type"
|
||||
],
|
||||
"properties": {
|
||||
"type": {
|
||||
"not": {
|
||||
@@ -717,6 +738,9 @@
|
||||
},
|
||||
{
|
||||
"if": {
|
||||
"required": [
|
||||
"type"
|
||||
],
|
||||
"properties": {
|
||||
"type": {
|
||||
"not": {
|
||||
@@ -731,9 +755,10 @@
|
||||
}
|
||||
}
|
||||
}
|
||||
]
|
||||
],
|
||||
"description": "A setting declares a \"type\" and a \"label\". A setting of the same name as one of the theme it extends may give only the fields it changes, such as its \"default\"."
|
||||
},
|
||||
"description": "Settings administrators change on the Themes page. Each writes a token, an <html> attribute or both before the page renders; useThemeSettings() reads them all."
|
||||
"description": "Settings administrators change on the Themes page. Each writes a token, an <html> attribute or both before the page renders; useThemeSettings() reads them all. A child theme changes a setting of its parent by giving only the fields it changes."
|
||||
}
|
||||
},
|
||||
"description": "Only for \"type\": \"theme\"."
|
||||
|
||||
@@ -44,6 +44,7 @@
|
||||
"runtime-stub.mjs",
|
||||
"theme-runtime-stub.mjs",
|
||||
"vite.mjs",
|
||||
"theme-chain.mjs",
|
||||
"README.md",
|
||||
"THEMES.md",
|
||||
"testing-runtime",
|
||||
|
||||
@@ -0,0 +1,60 @@
|
||||
/**
|
||||
* Finds the themes a theme package extends, for the build preset and the test aliases. The chain
|
||||
* starts at "theme.extends" in the package's extension.json and follows each parent's own manifest.
|
||||
* Each parent is looked up, in this order:
|
||||
*
|
||||
* 1. <extensions>/<id>, when `extensions` names the panel's extensions directory (the copy the
|
||||
* panel installed, which the scaffold points at);
|
||||
* 2. node_modules/<id> of the package, for a parent installed as a dependency.
|
||||
*/
|
||||
import { existsSync, readFileSync } from 'node:fs';
|
||||
import { dirname, resolve } from 'node:path';
|
||||
|
||||
const CLASSIC = 'classic';
|
||||
|
||||
function manifest(directory) {
|
||||
const file = resolve(directory, 'extension.json');
|
||||
|
||||
return existsSync(file) ? JSON.parse(readFileSync(file, 'utf8')) : null;
|
||||
}
|
||||
|
||||
/** The nearest directory at or above `from` with an extension.json, else null. */
|
||||
export function packageRoot(from) {
|
||||
for (let directory = from; ; directory = dirname(directory)) {
|
||||
if (existsSync(resolve(directory, 'extension.json'))) return directory;
|
||||
if (dirname(directory) === directory) return null;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* The themes the package at `root` extends, oldest first and without classic, each as
|
||||
* `{ id, directory, manifest }`. Throws when a parent is in none of the places above.
|
||||
*/
|
||||
export function themeParents({ root, extensions }) {
|
||||
const parents = [];
|
||||
let child = manifest(root);
|
||||
const seen = new Set([child?.id]);
|
||||
|
||||
while (child?.type === 'theme' && (child.theme?.extends ?? CLASSIC) !== CLASSIC) {
|
||||
const id = child.theme.extends;
|
||||
if (seen.has(id)) throw new Error(`Theme "${child.id}" extends itself through "${id}".`);
|
||||
seen.add(id);
|
||||
|
||||
const candidates = [extensions && resolve(root, extensions, id), resolve(root, 'node_modules', id)].filter(Boolean);
|
||||
const directory = candidates.find((candidate) => {
|
||||
const found = manifest(candidate);
|
||||
return found?.id === id && found.type === 'theme';
|
||||
});
|
||||
if (!directory) {
|
||||
throw new Error(
|
||||
`Theme "${child.id}" extends "${id}", which is not in ${candidates.join(' or ')}. ` +
|
||||
'Install it in the panel and pass its extensions directory as `extensions`, or add it to the dependencies.'
|
||||
);
|
||||
}
|
||||
|
||||
child = manifest(directory);
|
||||
parents.unshift({ id, directory, manifest: child });
|
||||
}
|
||||
|
||||
return parents;
|
||||
}
|
||||
Vendored
+24
-18
@@ -76,7 +76,19 @@ export interface ExtensionTestHost {
|
||||
}
|
||||
/** Create one host per test; call dispose after unmounting its Wrapper. */
|
||||
export declare function createExtensionTestHost(options?: ExtensionTestHostOptions): ExtensionTestHost;
|
||||
export interface ViewTestHostOptions<N extends ViewName> {
|
||||
/** The theme a test renders with, or a chain of them. */
|
||||
export interface TestThemeOptions {
|
||||
/** The theme to render with: what its entry exports. */
|
||||
theme?: ThemeDefinition;
|
||||
/**
|
||||
* A chain of themes, oldest first, as the panel stacks them over classic: `[parent, child]`. Each
|
||||
* one's `Default` and `skin(name, (below) => …)` build on the theme before it.
|
||||
*/
|
||||
themes?: readonly ThemeDefinition[];
|
||||
}
|
||||
/** Loads the chunks of a theme's `lazyView` views, or those of a chain of themes, which `renderView` renders synchronously. */
|
||||
export declare function preloadTheme(theme: ThemeDefinition | readonly ThemeDefinition[]): Promise<void>;
|
||||
export interface ViewTestHostOptions<N extends ViewName> extends TestThemeOptions {
|
||||
/** Defaults to the named fixture, or the view's first. */
|
||||
model?: ViewModel<N>;
|
||||
fixture?: string;
|
||||
@@ -98,17 +110,16 @@ export interface ViewTestHost<N extends ViewName> {
|
||||
dispose(): void;
|
||||
}
|
||||
/**
|
||||
* Tests a layer against the view's classic layers without issuing core queries: render it with `props`
|
||||
* inside `Wrapper`, and its `Default` renders classic with the same model. Nested views read fixtures.
|
||||
* Tests a layer against the view's classic layers, or the layers of `themes` over them, without issuing
|
||||
* core queries: render it with `props` inside `Wrapper`, and its `Default` renders the layer below with
|
||||
* the same model. Nested views read fixtures.
|
||||
*/
|
||||
export declare function createViewTestHost<N extends ViewName>(name: N, options?: ViewTestHostOptions<N>): Promise<ViewTestHost<N>>;
|
||||
export interface RenderViewOptions<N extends ViewName> {
|
||||
export interface RenderViewOptions<N extends ViewName> extends TestThemeOptions {
|
||||
/** Defaults to the view's first fixture. */
|
||||
fixture?: string;
|
||||
model?: ViewModel<N>;
|
||||
input?: ViewInput<N>;
|
||||
/** The theme to render the view with: what its entry exports. */
|
||||
theme?: ThemeDefinition;
|
||||
/** Components to mount in slots, as an extension's `slots.register` would. */
|
||||
slots?: TestSlots;
|
||||
/** Fail when a theme or extension layer throws (the default); false lets it fall back to the layer below. */
|
||||
@@ -122,21 +133,16 @@ export interface RenderedView {
|
||||
/** Throws what failed after the first render, such as a layer failing on a click. */
|
||||
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. Await `preloadTheme(theme)`
|
||||
* first when the theme has lazy views. It throws when the view fails to render, and when a theme or
|
||||
* extension layer throws unless `strict` is false.
|
||||
* Renders a view synchronously from fixtures, with the layers of a theme, or a chain of `themes`, over
|
||||
* classic. Each call replaces what was rendered before it; nested views read their fixtures too. Await
|
||||
* `preloadTheme(theme)` first when the themes have lazy views. It throws when the view fails to render,
|
||||
* and when a theme or extension layer throws unless `strict` is false.
|
||||
*/
|
||||
export declare function renderView<N extends ViewName>(name: N, options?: RenderViewOptions<N>): RenderedView;
|
||||
export interface RenderPrimitiveOptions {
|
||||
/** The theme to render the primitive with: what its entry exports. */
|
||||
theme?: ThemeDefinition;
|
||||
}
|
||||
export type RenderPrimitiveOptions = TestThemeOptions;
|
||||
/**
|
||||
* Renders a UI kit primitive synchronously with the theme's skins and replacements over classic's.
|
||||
* Each call replaces what was rendered before it.
|
||||
* Renders a UI kit primitive synchronously with the skins and replacements of a theme, or a chain of
|
||||
* `themes`, over classic's. Each call replaces what was rendered before it.
|
||||
*/
|
||||
export declare function renderPrimitive<N extends UiPrimitiveName>(name: N, props: UiPrimitiveProps<N>, options?: RenderPrimitiveOptions): RenderedView;
|
||||
|
||||
Vendored
+1
@@ -1,2 +1,3 @@
|
||||
// Generated by scripts/generate-sdk-types.mjs. Do not edit.
|
||||
/// <reference path="./theme-entries.d.ts" />
|
||||
export * from './sdk/testing.js';
|
||||
|
||||
+6
@@ -0,0 +1,6 @@
|
||||
// Generated by scripts/generate-sdk-types.mjs. Do not edit.
|
||||
// A theme's built entry, as a child theme's tests import a parent: import aurora from 'aurora/dist/client.js'.
|
||||
declare module '*/dist/client.js' {
|
||||
const theme: import('./sdk/theme.js').ThemeDefinition;
|
||||
export default theme;
|
||||
}
|
||||
+250
-40
@@ -15,8 +15,12 @@
|
||||
* export default defineThemeConfig({ entry: 'src/theme.tsx', stylesheet: 'src/theme.css' });
|
||||
*/
|
||||
import { createHash } from 'node:crypto';
|
||||
import { existsSync, readFileSync } from 'node:fs';
|
||||
import { existsSync, mkdirSync, readFileSync, realpathSync, writeFileSync } from 'node:fs';
|
||||
import { createRequire } from 'node:module';
|
||||
import { dirname, isAbsolute, parse, relative, resolve, sep } from 'node:path';
|
||||
import { fileURLToPath } from 'node:url';
|
||||
import { parseAst } from 'vite';
|
||||
import { packageRoot, themeParents } from './theme-chain.mjs';
|
||||
|
||||
/** Modules provided by the panel's import map - never bundled into extensions. */
|
||||
export const SHARED_RUNTIME_MODULES = [
|
||||
@@ -99,51 +103,257 @@ function definedViews(program) {
|
||||
return found;
|
||||
}
|
||||
|
||||
/** Writes dist/theme.json, which the panel reads to decide whether the theme stylesheet can replace its own. */
|
||||
const themeBuildInfo = () => {
|
||||
let views = [];
|
||||
return {
|
||||
name: 'pterodactyl-theme-build-info',
|
||||
enforce: 'post',
|
||||
buildStart() {
|
||||
views = [];
|
||||
},
|
||||
transform(code, id) {
|
||||
if (!id.includes('/node_modules/') && /\bdefineTheme\b/.test(code))
|
||||
views.push(...definedViews(parseAst(code)));
|
||||
return null;
|
||||
},
|
||||
generateBundle(_options, bundle) {
|
||||
for (const chunk of Object.values(bundle)) {
|
||||
if (
|
||||
chunk.type === 'chunk' &&
|
||||
!chunk.facadeModuleId?.endsWith('.css') &&
|
||||
chunk.viteMetadata?.importedCss.size
|
||||
) {
|
||||
this.error(
|
||||
'Theme styles belong in the theme stylesheet: dist/client.js does not load CSS its modules import.'
|
||||
);
|
||||
}
|
||||
const sdkDirectory = fileURLToPath(new URL('.', import.meta.url));
|
||||
const sdkVersion = () => JSON.parse(readFileSync(new URL('./package.json', import.meta.url), 'utf8')).version;
|
||||
const digest = (...parts) => createHash('sha256').update(parts.join('\0')).digest('hex').slice(0, 16);
|
||||
const quote = (value) => JSON.stringify(value);
|
||||
|
||||
/** A path a stylesheet in `from` can reference `to` by, with forward slashes. */
|
||||
function cssPath(from, to) {
|
||||
const path = relative(from, to).split(sep).join('/');
|
||||
|
||||
return path.startsWith('.') ? path : `./${path}`;
|
||||
}
|
||||
|
||||
/** A module of the theme package's dependencies (its PostCSS, Tailwind's scanner), else of the SDK's. */
|
||||
function dependency(root, id, via) {
|
||||
try {
|
||||
const require = createRequire(resolve(root, 'package.json'));
|
||||
|
||||
return via ? createRequire(require.resolve(via))(id) : require(id);
|
||||
} catch {
|
||||
return createRequire(import.meta.url)(id);
|
||||
}
|
||||
}
|
||||
|
||||
/** Calls `replace` with each relative url() of a declaration value: a file beside the stylesheet. */
|
||||
const relativeUrls = (value, replace) =>
|
||||
value.replace(/url\(\s*(['"]?)([^'")]*)\1\s*\)/g, (match, _quote, url) => {
|
||||
const path = url.split(/[?#]/)[0];
|
||||
if (!path || /^(?:[a-z][a-z\d+.-]*:|\/|#)/i.test(url)) return match;
|
||||
const replaced = replace(path, url.slice(path.length));
|
||||
|
||||
return replaced === null ? match : `url(${quote(replaced)})`;
|
||||
});
|
||||
|
||||
/**
|
||||
* The theme's own stylesheet for a child theme's build: local @imports inlined, the SDK's left out
|
||||
* (the child imports it itself), url()s pointing at copies beside dist/theme-source.css, and the
|
||||
* @source paths moved out to `sources`, which classes.txt scans instead.
|
||||
*/
|
||||
function ownStylesheet(file, { postcss, asset, sources }, seen = new Set()) {
|
||||
const base = dirname(file);
|
||||
const root = postcss.parse(seen.has(file) ? '' : readFileSync(file, 'utf8'), { from: file });
|
||||
seen.add(file);
|
||||
|
||||
root.walkDecls((declaration) => {
|
||||
declaration.value = relativeUrls(declaration.value, (path, suffix) => {
|
||||
const target = resolve(base, decodeURI(path));
|
||||
|
||||
return existsSync(target) ? `./${asset(target)}${suffix}` : null;
|
||||
});
|
||||
});
|
||||
root.walkAtRules('source', (rule) => {
|
||||
const negated = /^not\s/.test(rule.params);
|
||||
const pattern = rule.params.replace(/^not\s+/, '').trim();
|
||||
if (pattern.startsWith('inline(')) return;
|
||||
sources.push({ base, pattern: pattern.replace(/^(['"])(.*)\1$/, '$2'), negated });
|
||||
rule.remove();
|
||||
});
|
||||
root.each((node) => {
|
||||
const [, , specifier, conditions = ''] =
|
||||
node.type === 'atrule' && node.name === 'import'
|
||||
? (node.params.match(/^\s*(?:url\(\s*)?(['"]?)([^'")\s]+)\1\s*\)?\s*(.*)$/s) ?? [])
|
||||
: [];
|
||||
if (!specifier || /^(?:[a-z]+:)?\/\//i.test(specifier)) return;
|
||||
if (specifier.startsWith('@pterodactyl/sdk/')) return void node.remove();
|
||||
|
||||
let target;
|
||||
try {
|
||||
target =
|
||||
specifier.startsWith('.') || isAbsolute(specifier)
|
||||
? resolve(base, specifier)
|
||||
: createRequire(file).resolve(specifier);
|
||||
} catch {
|
||||
throw new Error(`${file} imports "${specifier}", which the theme build cannot resolve to a stylesheet.`);
|
||||
}
|
||||
if (target.startsWith(sdkDirectory)) return void node.remove();
|
||||
|
||||
let inlined = ownStylesheet(target, { postcss, asset, sources }, seen).nodes;
|
||||
const [, layer, rest] = conditions.match(/^(?:layer(?:\(([^)]*)\))?\s*)?(.*)$/s);
|
||||
const [, supports, media] = rest.match(/^(?:supports\(((?:[^()]|\([^()]*\))*)\)\s*)?(.*)$/s);
|
||||
for (const [name, params] of [
|
||||
['media', media.trim()],
|
||||
['supports', supports && `(${supports})`],
|
||||
['layer', conditions.startsWith('layer') ? (layer ?? '') : undefined],
|
||||
]) {
|
||||
if (params !== undefined && (params !== '' || name === 'layer')) {
|
||||
inlined = [postcss.atRule({ name, params, nodes: inlined })];
|
||||
}
|
||||
const manifest = new URL('./core-classes.txt', import.meta.url);
|
||||
const info = {
|
||||
core: existsSync(manifest)
|
||||
? createHash('sha256').update(readFileSync(manifest)).digest('hex').slice(0, 16)
|
||||
: null,
|
||||
sdk: JSON.parse(readFileSync(new URL('./package.json', import.meta.url), 'utf8')).version,
|
||||
...(views.length === 1 && views[0] !== null ? { views: views[0] } : {}),
|
||||
};
|
||||
this.emitFile({ type: 'asset', fileName: 'theme.json', source: `${JSON.stringify(info, null, 4)}\n` });
|
||||
}
|
||||
node.replaceWith(inlined);
|
||||
});
|
||||
|
||||
return root;
|
||||
}
|
||||
|
||||
/**
|
||||
* The theme build: dist/theme.json, which the panel reads to decide whether the theme stylesheet can
|
||||
* replace its own, and what a child theme builds on, dist/theme-source.css and dist/classes.txt.
|
||||
* When the theme extends others, their stylesheets and classes come into its own after the SDK's.
|
||||
*/
|
||||
function themeBuild({ entry, stylesheet, extensions }) {
|
||||
let config;
|
||||
let root;
|
||||
let sheet;
|
||||
let parents = [];
|
||||
let views = [];
|
||||
|
||||
return [
|
||||
{
|
||||
name: 'pterodactyl-theme-parents',
|
||||
enforce: 'pre',
|
||||
configResolved(resolved) {
|
||||
config = resolved;
|
||||
// Vite names the stylesheet module by its real path.
|
||||
sheet = stylesheet && resolve(config.root, stylesheet);
|
||||
sheet = sheet && existsSync(sheet) ? realpathSync(sheet) : sheet;
|
||||
const from = dirname(sheet ?? resolve(config.root, entry));
|
||||
root = packageRoot(from) ?? from;
|
||||
},
|
||||
buildStart() {
|
||||
parents = sheet ? themeParents({ root, extensions }).map((parent) => inherit(this, parent)) : [];
|
||||
},
|
||||
transform(code, id) {
|
||||
if (id.split('?')[0] !== sheet || !parents.some((parent) => parent.build)) return null;
|
||||
|
||||
const postcss = dependency(root, 'postcss');
|
||||
const css = postcss.parse(code, { from: sheet });
|
||||
const imports = parents
|
||||
.filter((parent) => parent.build)
|
||||
.map(
|
||||
(parent) =>
|
||||
`@import ${quote(cssPath(dirname(sheet), parent.stylesheet))};\n` +
|
||||
`@source ${quote(cssPath(dirname(sheet), parent.classes))};`
|
||||
);
|
||||
const inherited = postcss.parse(`/* The themes this one extends, oldest first. */\n${imports.join('\n')}`).nodes;
|
||||
const sdk = css.nodes.find(
|
||||
(node) => node.type === 'atrule' && node.name === 'import' && /^\s*(?:url\(\s*)?['"]?@pterodactyl\/sdk\//.test(node.params)
|
||||
);
|
||||
sdk ? sdk.after(inherited) : css.prepend(inherited);
|
||||
|
||||
return { code: css.toString(), map: null };
|
||||
},
|
||||
},
|
||||
};
|
||||
};
|
||||
{
|
||||
name: 'pterodactyl-theme-build-info',
|
||||
enforce: 'post',
|
||||
buildStart() {
|
||||
views = [];
|
||||
},
|
||||
transform(code, id) {
|
||||
if (!id.includes('/node_modules/') && /\bdefineTheme\b/.test(code))
|
||||
views.push(...definedViews(parseAst(code)));
|
||||
return null;
|
||||
},
|
||||
generateBundle(_options, bundle) {
|
||||
for (const chunk of Object.values(bundle)) {
|
||||
if (
|
||||
chunk.type === 'chunk' &&
|
||||
!chunk.facadeModuleId?.endsWith('.css') &&
|
||||
chunk.viteMetadata?.importedCss.size
|
||||
) {
|
||||
this.error(
|
||||
'Theme styles belong in the theme stylesheet: dist/client.js does not load CSS its modules import.'
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
// A file the stylesheet uses, copied beside it unless the build already emitted the same bytes.
|
||||
const asset = (file) => {
|
||||
const source = readFileSync(file);
|
||||
const emitted = Object.values(bundle).find(
|
||||
(output) => output.type === 'asset' && Buffer.from(output.source).equals(source)
|
||||
);
|
||||
if (emitted) return emitted.fileName;
|
||||
const { name, ext } = parse(file);
|
||||
const fileName = `${name}.${createHash('sha256').update(source).digest('base64url').slice(0, 8)}${ext}`;
|
||||
if (!bundle[fileName]) this.emitFile({ type: 'asset', fileName, source });
|
||||
|
||||
return fileName;
|
||||
};
|
||||
const sources = [];
|
||||
const own = sheet
|
||||
? ownStylesheet(sheet, { postcss: dependency(root, 'postcss'), asset, sources }).toString().trim()
|
||||
: '';
|
||||
const source = `/* This theme's own stylesheet, without the panel's: the build of a theme that extends it imports it. */\n${own}\n`;
|
||||
const { Scanner } = dependency(root, '@tailwindcss/oxide', '@tailwindcss/postcss');
|
||||
const scanner = new Scanner({
|
||||
sources: [
|
||||
{ base: root, pattern: '**/*', negated: false },
|
||||
...sources,
|
||||
{ base: resolve(config.root, config.build.outDir), pattern: '**/*', negated: true },
|
||||
],
|
||||
});
|
||||
const classes = `${[...new Set(scanner.scan())].sort().join('\n')}\n`;
|
||||
const manifest = new URL('./core-classes.txt', import.meta.url);
|
||||
const info = {
|
||||
core: existsSync(manifest)
|
||||
? createHash('sha256').update(readFileSync(manifest)).digest('hex').slice(0, 16)
|
||||
: null,
|
||||
sdk: sdkVersion(),
|
||||
...(views.length === 1 && views[0] !== null ? { views: views[0] } : {}),
|
||||
build: digest(source, classes),
|
||||
...(parents.length ? { parents: Object.fromEntries(parents.map(({ id, build }) => [id, build])) } : {}),
|
||||
};
|
||||
this.emitFile({ type: 'asset', fileName: 'theme-source.css', source });
|
||||
this.emitFile({ type: 'asset', fileName: 'classes.txt', source: classes });
|
||||
this.emitFile({ type: 'asset', fileName: 'theme.json', source: `${JSON.stringify(info, null, 4)}\n` });
|
||||
},
|
||||
},
|
||||
];
|
||||
|
||||
/**
|
||||
* A parent's build, its stylesheet copied into Vite's cache with absolute url()s: Tailwind inlines
|
||||
* imports without rebasing their urls, and rebuilds when an imported file changes.
|
||||
*/
|
||||
function inherit(context, parent) {
|
||||
const dist = (file) => resolve(parent.directory, 'dist', file);
|
||||
if (!parent.manifest.ui && !parent.manifest.theme?.stylesheet) return { ...parent, build: null };
|
||||
|
||||
const info = existsSync(dist('theme.json')) ? JSON.parse(readFileSync(dist('theme.json'), 'utf8')) : null;
|
||||
if (!info?.build || !existsSync(dist('theme-source.css')) || !existsSync(dist('classes.txt'))) {
|
||||
throw new Error(
|
||||
`Theme "${parent.id}" in ${parent.directory} has no build to extend: build it with @pterodactyl/sdk ${sdkVersion()}, which writes dist/theme-source.css and dist/classes.txt.`
|
||||
);
|
||||
}
|
||||
|
||||
const postcss = dependency(root, 'postcss');
|
||||
const css = postcss.parse(readFileSync(dist('theme-source.css'), 'utf8'), { from: dist('theme-source.css') });
|
||||
css.walkDecls((declaration) => {
|
||||
declaration.value = relativeUrls(declaration.value, (path, suffix) => dist(path).split(sep).join('/') + suffix);
|
||||
});
|
||||
const copy = resolve(config.cacheDir, 'pterodactyl-theme', `${parent.id}.css`);
|
||||
const text = css.toString();
|
||||
if (!existsSync(copy) || readFileSync(copy, 'utf8') !== text) {
|
||||
mkdirSync(dirname(copy), { recursive: true });
|
||||
writeFileSync(copy, text);
|
||||
}
|
||||
for (const file of ['theme.json', 'theme-source.css', 'classes.txt']) context.addWatchFile(dist(file));
|
||||
|
||||
return { ...parent, build: info.build, stylesheet: copy, classes: dist('classes.txt') };
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Builds a theme: `entry` (optional) to dist/client.js with the shared modules external and
|
||||
* no stylesheet loader, `stylesheet` to dist/theme.css with Tailwind, and dist/theme.json.
|
||||
* no stylesheet loader, `stylesheet` to dist/theme.css with Tailwind, and dist/theme.json,
|
||||
* dist/theme-source.css and dist/classes.txt for themes that extend this one.
|
||||
* When extension.json extends another theme, its stylesheet and classes are built in after the
|
||||
* SDK's. Parents are found in `extensions` (the panel's extensions directory), then node_modules.
|
||||
* `sourcemap` is off: a map embeds the theme's sources, so turn it on only for builds you keep.
|
||||
*/
|
||||
export function defineThemeConfig({ entry, stylesheet, outDir = 'dist', plugins = [], sourcemap = false } = {}) {
|
||||
export function defineThemeConfig({ entry, stylesheet, extensions, outDir = 'dist', plugins = [], sourcemap = false } = {}) {
|
||||
if (!stylesheet && !entry) {
|
||||
throw new Error(
|
||||
'defineThemeConfig requires a { stylesheet } path such as "src/theme.css", an { entry } such as "src/theme.tsx", or both.'
|
||||
@@ -151,7 +361,7 @@ export function defineThemeConfig({ entry, stylesheet, outDir = 'dist', plugins
|
||||
}
|
||||
|
||||
return {
|
||||
plugins: [...plugins, themeBuildInfo()],
|
||||
plugins: [...plugins, ...themeBuild({ entry, stylesheet, extensions })],
|
||||
// The import map shares react/jsx-runtime, never the development runtime.
|
||||
oxc: { jsx: { runtime: 'automatic', development: false } },
|
||||
// The panel serves a build from its own directory, so fonts and images resolve beside the file using them.
|
||||
|
||||
+108
-3
@@ -1,8 +1,9 @@
|
||||
import { mkdtempSync, readFileSync, rmSync, writeFileSync } from 'node:fs';
|
||||
import { mkdirSync, mkdtempSync, readFileSync, rmSync, symlinkSync, writeFileSync } from 'node:fs';
|
||||
import { tmpdir } from 'node:os';
|
||||
import { resolve } from 'node:path';
|
||||
import { pathToFileURL } from 'node:url';
|
||||
import { dirname, resolve } from 'node:path';
|
||||
import { fileURLToPath, pathToFileURL } from 'node:url';
|
||||
import { spawnSync } from 'node:child_process';
|
||||
import tailwind from '@tailwindcss/postcss';
|
||||
import { build, createLogger } from 'vite';
|
||||
import { expect, it } from 'vitest';
|
||||
import { defineExtensionConfig, defineThemeConfig } from './vite.mjs';
|
||||
@@ -49,12 +50,116 @@ it('builds a theme entry without a style loader, its stylesheet and its build in
|
||||
core: info.core,
|
||||
sdk: JSON.parse(readFileSync(new URL('./package.json', import.meta.url), 'utf8')).version,
|
||||
views: ['layout.app', 'page', 'server.power'],
|
||||
build: info.build,
|
||||
});
|
||||
expect(info.build).toMatch(/^[a-f0-9]{16}$/);
|
||||
} finally {
|
||||
rmSync(directory, { recursive: true, force: true });
|
||||
}
|
||||
});
|
||||
|
||||
/** A theme package in `directory`, with the SDK linked as a theme installs it, built with Tailwind. */
|
||||
const themePackage = (directory: string) => {
|
||||
const write = (path: string, contents: string | Buffer) => {
|
||||
mkdirSync(dirname(resolve(directory, path)), { recursive: true });
|
||||
writeFileSync(resolve(directory, path), contents);
|
||||
};
|
||||
const build_ = (options: Parameters<typeof defineThemeConfig>[0]) =>
|
||||
build({
|
||||
...defineThemeConfig({ ...options, outDir: resolve(directory, 'dist') }),
|
||||
css: { postcss: { plugins: [tailwind()] } },
|
||||
cacheDir: resolve(directory, 'node_modules/.vite'),
|
||||
configFile: false,
|
||||
logLevel: 'silent',
|
||||
});
|
||||
for (const [name, target] of [
|
||||
['@pterodactyl/sdk', '.'],
|
||||
['@tailwindcss/forms', '../../node_modules/@tailwindcss/forms'],
|
||||
]) {
|
||||
mkdirSync(dirname(resolve(directory, 'node_modules', name)), { recursive: true });
|
||||
symlinkSync(fileURLToPath(new URL(target, import.meta.url)), resolve(directory, 'node_modules', name));
|
||||
}
|
||||
|
||||
return { write, build: build_, dist: (file: string) => readFileSync(resolve(directory, 'dist', file), 'utf8') };
|
||||
};
|
||||
|
||||
it('ships its own stylesheet and class candidates for the themes that extend it', async () => {
|
||||
const directory = mkdtempSync(resolve(tmpdir(), 'theme-build-'));
|
||||
try {
|
||||
const theme = themePackage(directory);
|
||||
theme.write('extension.json', JSON.stringify({ id: 'parent', type: 'theme' }));
|
||||
// Over Vite's inline limit, so the font is emitted as a file rather than a data URL.
|
||||
theme.write('src/fonts/Brand.woff2', Buffer.alloc(8192, 1));
|
||||
theme.write('src/glow.css', '@utility glow { box-shadow: 0 0 1rem var(--primary); }');
|
||||
theme.write('src/frame.css', '.frame { padding: 1rem; }');
|
||||
theme.write('src/Card.jsx', 'export const Card = () => <div className="glow sm:rounded-3xl" />;');
|
||||
theme.write(
|
||||
'src/theme.jsx',
|
||||
"import { defineTheme } from '@pterodactyl/sdk/theme'; import { Card } from './Card.jsx'; export default defineTheme({ views: { 'dashboard.serverCard': Card } });"
|
||||
);
|
||||
theme.write(
|
||||
'src/theme.css',
|
||||
[
|
||||
"@import '@pterodactyl/sdk/theme-entry.css';",
|
||||
"@import './glow.css';",
|
||||
"@import './frame.css' layer(components);",
|
||||
"@source inline('underline');",
|
||||
"@font-face { font-family: 'Brand'; src: url('./fonts/Brand.woff2') format('woff2'); }",
|
||||
].join('\n')
|
||||
);
|
||||
await theme.build({ entry: resolve(directory, 'src/theme.jsx'), stylesheet: resolve(directory, 'src/theme.css') });
|
||||
const source = theme.dist('theme-source.css');
|
||||
|
||||
expect(source).not.toContain('@pterodactyl/sdk');
|
||||
expect(source).toContain('@utility glow');
|
||||
expect(source).toMatch(/@layer components\s*\{\s*\.frame/);
|
||||
expect(source).toContain("@source inline('underline')");
|
||||
// The font is the file theme.css links, beside both in dist/.
|
||||
const font = source.match(/url\("\.\/(Brand\.[\w-]+\.woff2)"\)/)?.[1];
|
||||
expect(font).toBeDefined();
|
||||
expect(theme.dist('theme.css')).toContain(`url(./${font})`);
|
||||
expect(theme.dist('classes.txt').split('\n')).toEqual(expect.arrayContaining(['glow', 'sm:rounded-3xl']));
|
||||
expect(JSON.parse(theme.dist('theme.json'))).not.toHaveProperty('parents');
|
||||
} finally {
|
||||
rmSync(directory, { recursive: true, force: true });
|
||||
}
|
||||
}, 60_000);
|
||||
|
||||
it("builds a child theme over its parent's stylesheet and classes, which it records", async () => {
|
||||
const directory = mkdtempSync(resolve(tmpdir(), 'theme-chain-'));
|
||||
try {
|
||||
const child = themePackage(resolve(directory, 'child'));
|
||||
const parent = (path: string, contents: string | Buffer) => child.write(`../extensions/parent/${path}`, contents);
|
||||
parent('extension.json', JSON.stringify({ id: 'parent', type: 'theme', theme: { stylesheet: 'dist/theme.css' } }));
|
||||
parent('dist/theme.json', JSON.stringify({ core: null, build: '0123456789abcdef' }));
|
||||
parent('dist/Brand.woff2', Buffer.alloc(8192, 1));
|
||||
parent('dist/classes.txt', 'glow\nsm:rounded-3xl\n');
|
||||
parent(
|
||||
'dist/theme-source.css',
|
||||
"@font-face { font-family: 'Brand'; src: url('./Brand.woff2'); }\n@utility glow { color: red; }\n.parent-rule { color: blue; }"
|
||||
);
|
||||
child.write('extension.json', JSON.stringify({ id: 'child', type: 'theme', theme: { extends: 'parent' } }));
|
||||
child.write('src/theme.css', "@import '@pterodactyl/sdk/theme-entry.css';\n.child-rule { color: green; }");
|
||||
const options = { stylesheet: resolve(directory, 'child/src/theme.css'), extensions: '../extensions' };
|
||||
await child.build(options);
|
||||
const css = child.dist('theme.css');
|
||||
|
||||
expect(css).toMatch(/\.glow\s*\{/);
|
||||
expect(css).toMatch(/\.sm\\:rounded-3xl/);
|
||||
expect(css.indexOf('.child-rule')).toBeGreaterThan(css.indexOf('.parent-rule'));
|
||||
// The parent's font is copied from its build, not left pointing beside the child's stylesheet.
|
||||
expect(css).toMatch(/url\(\.\/Brand\.[\w-]+\.woff2\)/);
|
||||
expect(JSON.parse(child.dist('theme.json')).parents).toEqual({ parent: '0123456789abcdef' });
|
||||
|
||||
rmSync(resolve(directory, 'extensions/parent/dist/theme-source.css'));
|
||||
await expect(child.build(options)).rejects.toThrow('Theme "parent" in');
|
||||
rmSync(resolve(directory, 'extensions/parent'), { recursive: true });
|
||||
await expect(child.build(options)).rejects.toThrow('Theme "child" extends "parent", which is not in');
|
||||
} finally {
|
||||
rmSync(directory, { recursive: true, force: true });
|
||||
}
|
||||
}, 60_000);
|
||||
|
||||
it('ships no source map, which would embed the theme sources, unless asked to', async () => {
|
||||
const directory = mkdtempSync(resolve(tmpdir(), 'theme-build-'));
|
||||
const files = {
|
||||
|
||||
+15
-3
@@ -2,9 +2,14 @@ import { fileURLToPath } from 'node:url';
|
||||
import { createRequire } from 'node:module';
|
||||
import { readFileSync, readdirSync } from 'node:fs';
|
||||
import { resolve } from 'node:path';
|
||||
import { themeParents } from './theme-chain.mjs';
|
||||
|
||||
/** Merge these aliases into Vitest's resolve.alias to use the real SDK runtime. */
|
||||
export function pterodactylTestAliases({ root = process.cwd() } = {}) {
|
||||
/**
|
||||
* Merge these aliases into Vitest's resolve.alias to use the real SDK runtime. A theme that extends
|
||||
* others also gets `<id>/dist/…` for each of them, found as its build finds them (`extensions`, the
|
||||
* panel's extensions directory, then node_modules), so its tests import `aurora/dist/client.js`.
|
||||
*/
|
||||
export function pterodactylTestAliases({ root = process.cwd(), extensions } = {}) {
|
||||
const require = createRequire(resolve(root, 'package.json'));
|
||||
const runtime = fileURLToPath(new URL('./testing-runtime/', import.meta.url));
|
||||
const peers = Object.keys(JSON.parse(readFileSync(new URL('./package.json', import.meta.url), 'utf8')).peerDependencies);
|
||||
@@ -12,13 +17,20 @@ export function pterodactylTestAliases({ root = process.cwd() } = {}) {
|
||||
[...readFileSync(resolve(runtime, file), 'utf8').matchAll(/(?:from\s*|import\s*)["']([^"']+)["']/g)].map(match => match[1])
|
||||
));
|
||||
const shared = [...imports].filter(id => peers.some(peer => id === peer || id.startsWith(`${peer}/`)));
|
||||
const escape = (id) => id.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
|
||||
// A parent that cannot be found fails the import that names it, not every test.
|
||||
let parents = [];
|
||||
try {
|
||||
parents = themeParents({ root, extensions });
|
||||
} catch {}
|
||||
return [
|
||||
{find: /^@pterodactyl\/sdk\/testing$/, replacement: fileURLToPath(new URL('./testing-runtime/testing.js', import.meta.url))},
|
||||
{find: /^@pterodactyl\/sdk\/api$/, replacement: fileURLToPath(new URL('./testing-runtime/api.js', import.meta.url))},
|
||||
{find: /^@pterodactyl\/sdk\/theme$/, replacement: fileURLToPath(new URL('./testing-runtime/theme.js', import.meta.url))},
|
||||
{find: /^@pterodactyl\/sdk$/, replacement: fileURLToPath(new URL('./testing-runtime/sdk.js', import.meta.url))},
|
||||
// Resolve peers from the consumer even when a local SDK dependency is symlinked.
|
||||
...shared.map(id => ({ find: new RegExp(`^${id.replace(/[.*+?^${}()|[\]\\]/g, '\\$&')}$`), replacement: require.resolve(id) })),
|
||||
...shared.map(id => ({ find: new RegExp(`^${escape(id)}$`), replacement: require.resolve(id) })),
|
||||
...parents.map(({ id, directory }) => ({ find: new RegExp(`^${escape(id)}/dist/`), replacement: `${resolve(directory, 'dist')}/` })),
|
||||
];
|
||||
}
|
||||
|
||||
|
||||
+2
-1
@@ -50,7 +50,8 @@ parameters:
|
||||
ExtensionScreenCondition: 'array{eggFeatures?: ExtensionScreenMatcher, eggTags?: ExtensionScreenMatcher, match?: string, runtime?: bool}'
|
||||
ExtensionScreenDefinition: 'array{id: string, area: string, path: string, parent?: string, nav?: array{label: string, exact?: bool, params?: array<string, string>, order?: int, group?: string, badge?: string, icon?: string}, permission?: list<string>, when?: ExtensionScreenCondition}'
|
||||
ExtensionThemeSettingInput: 'array{type: string, label: string, default?: string|int|float|bool|null, help?: string|null, token?: string|null, attribute?: string|null, options?: array<string, string>, min?: int|float|null, max?: int|float|null, step?: int|float|null, unit?: string|null, maxLength?: int}'
|
||||
ExtensionThemeInput: 'array{extends?: string, stylesheet?: string|null, schemes?: list<''dark''|''light''>|null, settings?: array<string, ExtensionThemeSettingInput>}'
|
||||
ExtensionThemeSettingOverride: 'array{type?: string, label?: string, default?: string|int|float|bool|null, help?: string|null, token?: string|null, attribute?: string|null, options?: array<string, string>, min?: int|float|null, max?: int|float|null, step?: int|float|null, unit?: string|null, maxLength?: int}'
|
||||
ExtensionThemeInput: 'array{extends?: string, stylesheet?: string|null, schemes?: list<''dark''|''light''>|null, settings?: array<string, ExtensionThemeSettingOverride>}'
|
||||
ExtensionManifestInput: 'array{id: string, name: string, version: string, type?: ''extension''|''theme'', requires?: array{panel?: string, sdk?: string, php?: string, extensions?: array<string, string>}, description?: string|null, author?: string|null, provider?: string|null, icon?: string|null, autoload?: array<mixed>, ui?: array{entry: string, mode?: string, prefix?: string, screens?: list<ExtensionScreenDefinition>, views?: list<string>}, theme?: ExtensionThemeInput, routes?: array{root?: list<string>}, ...<string, mixed>}'
|
||||
paths:
|
||||
- app
|
||||
|
||||
@@ -6,6 +6,7 @@ import { lazyView } from '@/views/lazy';
|
||||
import { Navigation, NavigationLink } from '@/views/navigation';
|
||||
import type { ViewPartProps, ViewProps } from '@/views/registry';
|
||||
import { defineTheme } from '@/views/theme';
|
||||
import { skin } from '@/themes/skins';
|
||||
import { usePanelLocation } from './navigation';
|
||||
import {
|
||||
preloadTheme,
|
||||
@@ -178,6 +179,51 @@ it('renders the lazy views of a theme once they are preloaded', async () => {
|
||||
unmount();
|
||||
});
|
||||
|
||||
it('stacks a chain of themes, so a child builds on its parent rather than classic', async () => {
|
||||
function ParentLayout({ Default }: ViewProps<'layout.app'>) {
|
||||
return (
|
||||
<div data-parent-layout=''>
|
||||
<Default />
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
function ChildLayout({ Default }: ViewProps<'layout.app'>) {
|
||||
return (
|
||||
<div data-child-layout=''>
|
||||
<Default />
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
const parent = defineTheme({
|
||||
views: { 'layout.app': lazyView(async () => ({ default: ParentLayout })) },
|
||||
ui: { Button: skin('Button', { root: 'parent-pill' }) },
|
||||
});
|
||||
const child = defineTheme({
|
||||
views: { 'layout.app': ChildLayout },
|
||||
ui: { Button: skin('Button', (below) => ({ root: (state) => `${below.root(state)} child-shadow` })) },
|
||||
});
|
||||
const themes = [parent, child];
|
||||
|
||||
await preloadTheme(themes);
|
||||
|
||||
const view = renderView('layout.app', { themes, fixture: 'admin' });
|
||||
|
||||
expect(view.container.querySelector('[data-child-layout] > [data-parent-layout] main')).not.toBeNull();
|
||||
expect(renderPrimitive('Button', { children: 'Save' }, { themes }).container.querySelector('button')).toHaveClass(
|
||||
'parent-pill',
|
||||
'child-shadow'
|
||||
);
|
||||
expect(() => renderView('layout.app', { theme: child, themes })).toThrow('Pass `theme` or `themes`, not both.');
|
||||
|
||||
const mounted = await createViewTestHost('layout.app', { themes: [parent], fixture: 'admin' });
|
||||
|
||||
host = mounted;
|
||||
render(<ChildLayout {...mounted.props} />, { wrapper: mounted.Wrapper });
|
||||
await vi.waitFor(() => expect(document.querySelector('[data-child-layout] > [data-parent-layout]')).not.toBeNull());
|
||||
});
|
||||
|
||||
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({}) });
|
||||
|
||||
|
||||
@@ -365,7 +365,59 @@ export function createExtensionTestHost(options: ExtensionTestHostOptions = {}):
|
||||
return createHost(options);
|
||||
}
|
||||
|
||||
export interface ViewTestHostOptions<N extends ViewName> {
|
||||
/** The theme a test renders with, or a chain of them. */
|
||||
export interface TestThemeOptions {
|
||||
/** The theme to render with: what its entry exports. */
|
||||
theme?: ThemeDefinition;
|
||||
/**
|
||||
* A chain of themes, oldest first, as the panel stacks them over classic: `[parent, child]`. Each
|
||||
* one's `Default` and `skin(name, (below) => …)` build on the theme before it.
|
||||
*/
|
||||
themes?: readonly ThemeDefinition[];
|
||||
}
|
||||
|
||||
function chainOf({ theme, themes }: TestThemeOptions): readonly ThemeDefinition[] {
|
||||
if (theme && themes) {
|
||||
throw new Error('Pass `theme` or `themes`, not both.');
|
||||
}
|
||||
|
||||
return themes ?? (theme ? [theme] : []);
|
||||
}
|
||||
|
||||
/** How layer failures name a theme of the chain: "theme" for the last, its parents "parent", "parent 2" and so on. */
|
||||
function layerId(distance: number): string {
|
||||
if (distance === 0) {
|
||||
return 'theme';
|
||||
}
|
||||
|
||||
return distance === 1 ? 'parent' : `parent ${distance}`;
|
||||
}
|
||||
|
||||
/** Replaces the registered theme layers with the chain's skins, views and icons, parent first. */
|
||||
function registerThemes(themes: readonly ThemeDefinition[]): void {
|
||||
clearThemeLayers();
|
||||
clearThemeSkins();
|
||||
for (const [index, theme] of themes.entries()) {
|
||||
const id = layerId(themes.length - 1 - index);
|
||||
|
||||
registerSkins(id, theme.ui ?? {});
|
||||
registerViewLayer(id, 'theme', theme.views ?? {});
|
||||
registerThemeIcons(theme.icons ?? {});
|
||||
}
|
||||
}
|
||||
|
||||
/** Loads the chunks of a theme's `lazyView` views, or those of a chain of themes, which `renderView` renders synchronously. */
|
||||
export async function preloadTheme(theme: ThemeDefinition | readonly ThemeDefinition[]): Promise<void> {
|
||||
const themes: readonly ThemeDefinition[] = 'length' in theme ? theme : [theme];
|
||||
|
||||
await Promise.all(
|
||||
themes.flatMap((each) =>
|
||||
Object.values(each.views ?? {}).map((view) => (view && isPendingLazyView(view) ? view.preload() : null))
|
||||
)
|
||||
);
|
||||
}
|
||||
|
||||
export interface ViewTestHostOptions<N extends ViewName> extends TestThemeOptions {
|
||||
/** Defaults to the named fixture, or the view's first. */
|
||||
model?: ViewModel<N>;
|
||||
fixture?: string;
|
||||
@@ -442,8 +494,9 @@ function FailOnLayerError({ failures, children }: { failures: LayerFailures; chi
|
||||
}
|
||||
|
||||
/**
|
||||
* Tests a layer against the view's classic layers without issuing core queries: render it with `props`
|
||||
* inside `Wrapper`, and its `Default` renders classic with the same model. Nested views read fixtures.
|
||||
* Tests a layer against the view's classic layers, or the layers of `themes` over them, without issuing
|
||||
* core queries: render it with `props` inside `Wrapper`, and its `Default` renders the layer below with
|
||||
* the same model. Nested views read fixtures.
|
||||
*/
|
||||
export async function createViewTestHost<N extends ViewName>(
|
||||
name: N,
|
||||
@@ -451,7 +504,11 @@ export async function createViewTestHost<N extends ViewName>(
|
||||
): Promise<ViewTestHost<N>> {
|
||||
registerClassPrefixes([options.prefix]);
|
||||
registerClassicTheme();
|
||||
await preloadView(name);
|
||||
|
||||
const themes = chainOf(options);
|
||||
|
||||
await Promise.all([preloadView(name), preloadTheme(themes)]);
|
||||
registerThemes(themes);
|
||||
|
||||
const view: ViewName = name;
|
||||
const definition = getViewDefinition(view);
|
||||
@@ -500,13 +557,11 @@ export async function createViewTestHost<N extends ViewName>(
|
||||
};
|
||||
}
|
||||
|
||||
export interface RenderViewOptions<N extends ViewName> {
|
||||
export interface RenderViewOptions<N extends ViewName> extends TestThemeOptions {
|
||||
/** Defaults to the view's first fixture. */
|
||||
fixture?: string;
|
||||
model?: ViewModel<N>;
|
||||
input?: ViewInput<N>;
|
||||
/** The theme to render the view with: what its entry exports. */
|
||||
theme?: ThemeDefinition;
|
||||
/** Components to mount in slots, as an extension's `slots.register` would. */
|
||||
slots?: TestSlots;
|
||||
/** Fail when a theme or extension layer throws (the default); false lets it fall back to the layer below. */
|
||||
@@ -520,7 +575,7 @@ export interface RenderedView {
|
||||
}
|
||||
|
||||
interface MountOptions {
|
||||
theme?: ThemeDefinition;
|
||||
themes: readonly ThemeDefinition[];
|
||||
slots?: TestSlots;
|
||||
strict?: boolean;
|
||||
}
|
||||
@@ -532,18 +587,12 @@ const viewRouter = createRouter({
|
||||
let rendered: RenderedView | undefined;
|
||||
|
||||
/**
|
||||
* Replaces whatever was rendered before with `content`, under a theme's skins, views and icons, and
|
||||
* Replaces whatever was rendered before with `content`, under the themes' skins, views and icons, and
|
||||
* throws when it fails to render (and, unless `strict` is false, when one of its layers falls back).
|
||||
*/
|
||||
function mount(content: ReactNode, { theme, slots = {}, strict = true }: MountOptions): RenderedView {
|
||||
function mount(content: ReactNode, { themes, slots = {}, strict = true }: MountOptions): RenderedView {
|
||||
rendered?.unmount();
|
||||
clearThemeLayers();
|
||||
clearThemeSkins();
|
||||
if (theme) {
|
||||
registerSkins('theme', theme.ui ?? {});
|
||||
registerViewLayer('theme', 'theme', theme.views ?? {});
|
||||
registerThemeIcons(theme.icons ?? {});
|
||||
}
|
||||
registerThemes(themes);
|
||||
|
||||
// Each slot's props are typed by its name where they are given.
|
||||
const removeSlots = mountSlotComponents('test-slots', slots as Parameters<typeof mountSlotComponents>[1]);
|
||||
@@ -590,24 +639,20 @@ function mount(content: ReactNode, { theme, slots = {}, strict = true }: MountOp
|
||||
return current;
|
||||
}
|
||||
|
||||
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))
|
||||
const pendingViews = (themes: readonly ThemeDefinition[]): string[] =>
|
||||
themes.flatMap((theme) =>
|
||||
Object.entries(theme.views ?? {}).flatMap(([name, view]) => (view && isPendingLazyView(view) ? [name] : []))
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* 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. Await `preloadTheme(theme)`
|
||||
* first when the theme has lazy views. It throws when the view fails to render, and when a theme or
|
||||
* extension layer throws unless `strict` is false.
|
||||
* Renders a view synchronously from fixtures, with the layers of a theme, or a chain of `themes`, over
|
||||
* classic. Each call replaces what was rendered before it; nested views read their fixtures too. Await
|
||||
* `preloadTheme(theme)` first when the themes have lazy views. It throws when the view fails to render,
|
||||
* and when a theme or extension layer throws unless `strict` is false.
|
||||
*/
|
||||
export function renderView<N extends ViewName>(name: N, options: RenderViewOptions<N> = {}): RenderedView {
|
||||
const pending = pendingViews(options.theme);
|
||||
const themes = chainOf(options);
|
||||
const pending = pendingViews(themes);
|
||||
|
||||
if (pending.length) {
|
||||
throw new Error(
|
||||
@@ -624,18 +669,15 @@ export function renderView<N extends ViewName>(name: N, options: RenderViewOptio
|
||||
<ViewFixtureProvider fixtures={fixtures} models={models}>
|
||||
<LooseView name={name} {...Object(options.input ?? {})} />
|
||||
</ViewFixtureProvider>,
|
||||
options
|
||||
{ themes, slots: options.slots, strict: options.strict }
|
||||
);
|
||||
}
|
||||
|
||||
export interface RenderPrimitiveOptions {
|
||||
/** The theme to render the primitive with: what its entry exports. */
|
||||
theme?: ThemeDefinition;
|
||||
}
|
||||
export type RenderPrimitiveOptions = TestThemeOptions;
|
||||
|
||||
/**
|
||||
* Renders a UI kit primitive synchronously with the theme's skins and replacements over classic's.
|
||||
* Each call replaces what was rendered before it.
|
||||
* Renders a UI kit primitive synchronously with the skins and replacements of a theme, or a chain of
|
||||
* `themes`, over classic's. Each call replaces what was rendered before it.
|
||||
*/
|
||||
export function renderPrimitive<N extends UiPrimitiveName>(
|
||||
name: N,
|
||||
@@ -650,5 +692,5 @@ export function renderPrimitive(
|
||||
// The overload ties the props to the named primitive.
|
||||
const primitive = uiPrimitives[name] as JSXElementConstructor<UiPrimitiveProps<UiPrimitiveName>>;
|
||||
|
||||
return mount(createElement(primitive, props), { theme: options.theme });
|
||||
return mount(createElement(primitive, props), { themes: chainOf(options) });
|
||||
}
|
||||
|
||||
@@ -91,7 +91,21 @@ visit('sdk/index.d.ts');
|
||||
visit('sdk/api.d.ts');
|
||||
visit('sdk/theme.d.ts');
|
||||
visit('sdk/testing.d.ts');
|
||||
files.set('testing.d.ts', "// Generated by scripts/generate-sdk-types.mjs. Do not edit.\nexport * from './sdk/testing.js';\n");
|
||||
files.set(
|
||||
'testing.d.ts',
|
||||
"// Generated by scripts/generate-sdk-types.mjs. Do not edit.\n/// <reference path=\"./theme-entries.d.ts\" />\nexport * from './sdk/testing.js';\n"
|
||||
);
|
||||
// A child theme's tests import its parents' built entries, which ship no declarations of their own.
|
||||
files.set(
|
||||
'theme-entries.d.ts',
|
||||
`// Generated by scripts/generate-sdk-types.mjs. Do not edit.
|
||||
// A theme's built entry, as a child theme's tests import a parent: import aurora from 'aurora/dist/client.js'.
|
||||
declare module '*/dist/client.js' {
|
||||
const theme: import('./sdk/theme.js').ThemeDefinition;
|
||||
export default theme;
|
||||
}
|
||||
`
|
||||
);
|
||||
files.set(
|
||||
'index.d.ts',
|
||||
"// Generated by scripts/generate-sdk-types.mjs. Do not edit.\nexport * from './sdk/index.js';\n"
|
||||
|
||||
@@ -136,6 +136,25 @@ test('saves settings that pass their type and restores defaults from null', func
|
||||
expect($reset['accent']['value'])->toBe('#8b5cf6')->and($reset['navigation']['value'])->toBe('side')->and($reset['radius']['value'])->toBe(1.25);
|
||||
});
|
||||
|
||||
test('a child theme that overrides a setting lists and saves it with the declaration it changes', function (): void {
|
||||
File::ensureDirectoryExists($this->baseDirectory.'/extensions/midnight');
|
||||
File::put($this->baseDirectory.'/extensions/midnight/extension.json', json_encode([
|
||||
'id' => 'midnight', 'type' => 'theme', 'name' => 'Midnight', 'version' => '1.0.0',
|
||||
'theme' => ['extends' => 'aurora', 'settings' => ['accent' => ['default' => '#ff4fd8']]],
|
||||
], JSON_THROW_ON_ERROR));
|
||||
Extension::query()->create(['identifier' => 'midnight', 'version' => '1.0.0', 'enabled' => true]);
|
||||
app(ExtensionRepository::class)->flushDiscovery();
|
||||
$route = route('api.admin.themes.settings.update', ['theme' => 'midnight']);
|
||||
|
||||
$settings = settingsOf($this->getJson(route('api.admin.themes.settings', ['theme' => 'midnight']))->assertOk()->json());
|
||||
expect(array_keys($settings))->toBe(['accent'])
|
||||
->and($settings['accent'])->toMatchArray(['type' => 'color', 'label' => 'Accent', 'default' => '#ff4fd8', 'value' => '#ff4fd8', 'token' => '--accent']);
|
||||
|
||||
$this->patchJson($route, ['settings' => ['accent' => 'red']])->assertUnprocessable();
|
||||
expect(settingsOf($this->patchJson($route, ['settings' => ['accent' => '#00ff00']])->assertOk()->json())['accent']['value'])->toBe('#00ff00');
|
||||
$this->assertDatabaseHas('extension_settings', ['extension' => 'midnight', 'key' => 'theme.accent', 'value' => '"#00ff00"']);
|
||||
});
|
||||
|
||||
test('rejects setting values that do not fit their type', function (array $settings, string $field): void {
|
||||
$this->patchJson(route('api.admin.themes.settings.update', ['theme' => 'aurora']), ['settings' => $settings])
|
||||
->assertUnprocessable()
|
||||
|
||||
@@ -96,7 +96,7 @@ test('the active theme cannot be disabled or removed', function (): void {
|
||||
test('a child theme needs its parent enabled, and the chain resolves parent first', function (): void {
|
||||
$installer = app(InstallsExtensions::class);
|
||||
$installer->install(themePackage('base'));
|
||||
$installer->install(themePackage('child', ['extends' => 'base', 'schemes' => ['light']]));
|
||||
$installer->install(themePackage('child', ['extends' => 'base', 'schemes' => ['light']], ['theme.json' => '{"core":"f1x7ure0c0re0000","parents":{"base":null}}']));
|
||||
|
||||
expect(fn () => app(SetsExtensionEnabled::class)->setEnabled('child', true))->toThrow(InvalidExtensionException::class, 'Theme "child" extends "base", which is not an enabled theme.');
|
||||
|
||||
@@ -112,6 +112,57 @@ test('a child theme needs its parent enabled, and the chain resolves parent firs
|
||||
expect($themes->activationProblem('base'))->toBeNull();
|
||||
});
|
||||
|
||||
test('a child stylesheet must be built over the stylesheets of the themes it extends', function (): void {
|
||||
$installer = app(InstallsExtensions::class);
|
||||
$installer->install(themePackage('base', files: ['theme.json' => '{"core":"f1x7ure0c0re0000","build":"0000000000base02"}']), enable: true);
|
||||
$unbuilt = themePackage('child', ['extends' => 'base']);
|
||||
|
||||
$this->artisan('p:extension:doctor', ['path' => $unbuilt])->expectsOutputToContain('was not built over the stylesheet of "base"')->assertFailed();
|
||||
expect(fn () => $installer->install($unbuilt, enable: true))->toThrow(InvalidExtensionException::class, 'Theme "child" extends "base", but its stylesheet was not built over the stylesheet of "base".');
|
||||
|
||||
// Built over an earlier build of the parent, it still works, and doctor says to rebuild.
|
||||
$stale = themePackage('child', ['extends' => 'base'], ['theme.json' => '{"core":"f1x7ure0c0re0000","parents":{"base":"0000000000base01"}}']);
|
||||
$this->artisan('p:extension:doctor', ['path' => $stale])
|
||||
->expectsOutputToContain('was built over build 0000000000base01 of "base", which is now build 0000000000base02')
|
||||
->assertSuccessful();
|
||||
$installer->install($stale, enable: true);
|
||||
expect(app(ThemeRepository::class)->activationProblem('child'))->toBeNull();
|
||||
});
|
||||
|
||||
test('a child theme changes a setting of its parent by giving only the fields it changes', function (): void {
|
||||
$installer = app(InstallsExtensions::class);
|
||||
$built = ['theme.json' => '{"core":"f1x7ure0c0re0000","parents":{"base":null}}'];
|
||||
$installer->install(themePackage('base', ['settings' => [
|
||||
'accent' => ['type' => 'color', 'label' => 'Accent', 'help' => 'Buttons and links.', 'default' => '#111111', 'token' => '--base-accent'],
|
||||
'density' => ['type' => 'select', 'label' => 'Density', 'options' => ['cosy' => 'Cosy', 'compact' => 'Compact'], 'default' => 'cosy', 'attribute' => 'data-density'],
|
||||
]]), enable: true);
|
||||
$child = themePackage('child', ['extends' => 'base', 'settings' => [
|
||||
'accent' => ['default' => '#ff4fd8'],
|
||||
'stars' => ['type' => 'toggle', 'label' => 'Stars', 'default' => true],
|
||||
]], $built);
|
||||
$installer->install($child, enable: true);
|
||||
app(ActivatesThemes::class)->activate('child');
|
||||
|
||||
$accent = app(ThemeRepository::class)->declarations(app(ExtensionRepository::class)->discovered()->get('child'))['accent'];
|
||||
expect([$accent->type, $accent->label, $accent->help, $accent->token, $accent->default])->toBe(['color', 'Accent', 'Buttons and links.', '--base-accent', '#ff4fd8']);
|
||||
$this->get('/auth/login')->assertOk()->assertSee('--base-accent:#ff4fd8', false)->assertSee('data-density="cosy"', false);
|
||||
|
||||
$this->artisan('p:extension:types', ['path' => $child])->assertSuccessful();
|
||||
expect(File::get($child.'/src/theme-types.ts'))->toContain(<<<'TS'
|
||||
export interface ThemeSettings {
|
||||
readonly "accent": string;
|
||||
readonly "density": "cosy" | "compact";
|
||||
readonly "stars": boolean;
|
||||
}
|
||||
TS);
|
||||
|
||||
// An override needs a declaration to change, and must make a valid one.
|
||||
foreach ([[['nothing' => ['default' => 'x']], 'overrides setting "nothing", which no theme it extends declares'], [['accent' => ['default' => 'red']], 'A color setting defaults to']] as [$settings, $message]) {
|
||||
$broken = themePackage('broken', ['extends' => 'base', 'settings' => $settings], $built);
|
||||
$this->artisan('p:extension:doctor', ['path' => $broken])->expectsOutputToContain($message)->assertFailed();
|
||||
}
|
||||
});
|
||||
|
||||
test('an incompatible active theme is reported and renders as classic', function (): void {
|
||||
app(InstallsExtensions::class)->install(themePackage('aurora'), enable: true);
|
||||
app(ActivatesThemes::class)->activate('aurora');
|
||||
|
||||
@@ -8,13 +8,14 @@ use Illuminate\Support\Facades\File;
|
||||
use Pterodactyl\Exceptions\Extensions\InvalidExtensionException;
|
||||
use Pterodactyl\Services\Extensions\ExtensionManifest;
|
||||
use Pterodactyl\Services\Extensions\ExtensionManifestValidator;
|
||||
use Pterodactyl\Services\Extensions\ExtensionRepository;
|
||||
use Pterodactyl\Services\Extensions\Scaffolding\ExtensionScaffolder;
|
||||
use Pterodactyl\Tests\TestCase;
|
||||
|
||||
uses(TestCase::class);
|
||||
beforeEach(function (): void {
|
||||
$this->directory = sys_get_temp_dir().DIRECTORY_SEPARATOR.'ptero-scaffolder-'.uniqid();
|
||||
$this->scaffolder = new ExtensionScaffolder(new ExtensionManifestValidator);
|
||||
$this->scaffolder = app(ExtensionScaffolder::class);
|
||||
File::ensureDirectoryExists($this->directory);
|
||||
});
|
||||
afterEach(function (): void {
|
||||
@@ -74,6 +75,43 @@ test('scaffolds a theme of css alone, with no javascript entry', function (): vo
|
||||
->and($package['devDependencies'])->not->toHaveKey('react');
|
||||
});
|
||||
|
||||
test('scaffolds a child theme that starts as the theme it extends', function (): void {
|
||||
config(['extensions.directory' => $this->directory.'/installed']);
|
||||
foreach (['nebula' => 'classic', 'aurora' => 'nebula'] as $id => $parent) {
|
||||
File::ensureDirectoryExists($this->directory.'/installed/'.$id);
|
||||
File::put($this->directory.'/installed/'.$id.'/extension.json', json_encode(['id' => $id, 'type' => 'theme', 'name' => ucfirst($id), 'version' => '1.2.0', 'theme' => ['extends' => $parent]], JSON_THROW_ON_ERROR));
|
||||
}
|
||||
|
||||
app(ExtensionRepository::class)->flushDiscovery();
|
||||
|
||||
$this->artisan('p:extension:make', ['id' => 'midnight', '--theme' => true, '--extends' => 'aurora'])->assertSuccessful();
|
||||
$target = $this->directory.'/installed/midnight';
|
||||
$manifest = (new ExtensionManifestValidator)->fromDirectory($target);
|
||||
|
||||
expect($manifest->theme->extends)->toBe('aurora')
|
||||
->and($manifest->theme->settings)->toBe([])
|
||||
->and($manifest->theme->schemes)->toBeNull()
|
||||
->and($manifest->requiredExtensions)->toBe(['aurora' => '^1.2.0']);
|
||||
expect(File::allFiles($target, hidden: true))->toHaveCount(11)
|
||||
->and($target.'/src/skins.ts')->not->toBeFile()
|
||||
->and($target.'/src/views')->not->toBeDirectory();
|
||||
expect(File::get($target.'/src/theme.css'))->toContain("@import '@pterodactyl/sdk/theme-entry.css';")->not->toContain('{');
|
||||
expect(File::get($target.'/src/theme.tsx'))->toContain('export default defineTheme({});');
|
||||
// Its tests stack the whole chain, which the test aliases find where the build does.
|
||||
expect(File::get($target.'/src/theme.spec.tsx'))->toContain("import nebula from 'nebula/dist/client.js';\nimport aurora from 'aurora/dist/client.js';", 'const themes = [nebula, aurora, theme];', "renderView('dashboard.serverCard', { themes");
|
||||
expect(File::get($target.'/vite.config.mjs'))->toContain("defineThemeConfig({ entry: 'src/theme.tsx', stylesheet: 'src/theme.css', extensions: '..' })");
|
||||
expect(File::get($target.'/vitest.config.mjs'))->toContain("pterodactylTestAliases({ extensions: '..' })");
|
||||
expect(File::get($target.'/README.md'))->toContain('extends Aurora', '--extends=aurora', 'themes: [nebula, aurora, theme]')->not->toContain('{{');
|
||||
|
||||
$this->artisan('p:extension:make', ['id' => 'pale', '--theme' => true, '--css-only' => true, '--extends' => 'aurora', '--out' => $this->directory])->assertSuccessful();
|
||||
expect(File::get($this->directory.'/pale/vite.config.mjs'))->toContain("defineThemeConfig({ stylesheet: 'src/theme.css', extensions: '../installed' })")
|
||||
->and($this->directory.'/pale/src/theme.spec.tsx')->not->toBeFile()
|
||||
->and(File::get($this->directory.'/pale/README.md'))->not->toContain('src/theme.tsx', '{{');
|
||||
|
||||
$this->artisan('p:extension:make', ['id' => 'plain', '--extends' => 'aurora', '--out' => $this->directory])->expectsOutputToContain('pass it with --theme')->assertFailed();
|
||||
$this->artisan('p:extension:make', ['id' => 'loop', '--theme' => true, '--extends' => 'loop', '--out' => $this->directory])->expectsOutputToContain('names the theme to build on')->assertFailed();
|
||||
});
|
||||
|
||||
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()
|
||||
|
||||
@@ -127,6 +127,29 @@ test('rejects setting names that are not identifiers and two settings writing th
|
||||
]]]))->toThrow(InvalidExtensionException::class, 'Theme settings "one" and "two" both write "--accent".');
|
||||
});
|
||||
|
||||
test('a child theme overrides a setting of its parent with only the fields it changes', function (): void {
|
||||
$manifest = theme(['theme' => ['extends' => 'base', 'settings' => [
|
||||
'accent' => ['default' => '#ff4fd8'],
|
||||
'stars' => ['type' => 'toggle', 'label' => 'Stars', 'default' => true],
|
||||
]]]);
|
||||
|
||||
expect($manifest->theme->overrides)->toBe(['accent' => ['default' => '#ff4fd8']])
|
||||
->and(array_keys($manifest->theme->settings))->toBe(['stars']);
|
||||
expect(fn () => theme(['theme' => ['settings' => ['accent' => ['default' => '#ff4fd8']]]]))->toThrow(InvalidExtensionException::class, 'only a theme that extends another can override');
|
||||
// What does not depend on the type is checked before the override is merged.
|
||||
expect(fn () => theme(['theme' => ['extends' => 'base', 'settings' => ['accent' => ['token' => 'color']]]]))->toThrow(InvalidExtensionException::class, 'custom property names');
|
||||
});
|
||||
|
||||
test('an override merged over the declaration it changes is checked as a declaration', function (): void {
|
||||
$validator = new ExtensionManifestValidator;
|
||||
$accent = ThemeSetting::fromValidatedData('accent', ['type' => 'color', 'label' => 'Accent', 'help' => 'Buttons.', 'default' => '#7c5cff', 'token' => '--aurora-accent']);
|
||||
$merged = $validator->themeSetting('accent', $accent->overriddenBy(['default' => '#ff4fd8']));
|
||||
|
||||
expect([$merged->type, $merged->label, $merged->help, $merged->token, $merged->default])->toBe(['color', 'Accent', 'Buttons.', '--aurora-accent', '#ff4fd8']);
|
||||
expect(fn () => $validator->themeSetting('accent', $accent->overriddenBy(['default' => 'red'])))->toThrow(InvalidExtensionException::class, 'A color setting defaults to');
|
||||
expect(fn () => $validator->themeSetting('accent', $accent->overriddenBy(['min' => 1])))->toThrow(InvalidExtensionException::class, 'theme.settings.accent.min');
|
||||
});
|
||||
|
||||
test('settings validate saved values with the rules of the matching extension fields', function (string $type, array $extra, mixed $value, bool $valid): void {
|
||||
$setting = ThemeSetting::fromValidatedData('probe', ['type' => $type, 'label' => 'Probe', ...$extra]);
|
||||
$validator = validator(['probe' => $value], $setting->definition()->validationRules());
|
||||
|
||||
Reference in New Issue
Block a user