ServerKit is a lightweight, modern server control panel for managing web applications, databases, and services on your VPS or dedicated server. Built with Python/Flask backend and React frontend.
Python astracloudflarecontrol-panelcyberpaneldnsfablehosting-control-panelhosting-panelkimi-k3server-managementserverkitubuntu-web-panelwebserver
feat(themes): theme gallery + runtime skins (plan 60 Phase 1)
Juan Denis0016b1ff22bf
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex d6df82e3..57c18156 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -20,6 +20,15 @@ awaiting a stable release:### Added+- **Themes — pick a color theme, or build and share your own.** Settings →+ Appearance now has a Theme Gallery: swap the whole panel's palette instantly+ with one click (Paper, Nord Deep, Gruvbox, Phosphor, High Contrast, or the+ stock look), previewed live as you hover. Your choice is personal, and the+ dark/light toggle still works on top of it. A theme is just data — a small map+ of color tokens, no code, no build step — so anyone can make one: a built-in+ Theme Studio lets you edit colors over the live panel and export a shareable+ `theme.json`, and a public themes registry means community themes install with+ one click. See [`docs/THEMING.md`](docs/THEMING.md).- **Extensions render on a production panel without a rebuild.** An extension thatships a prebuilt ESM bundle (`frontend_entry: "dist/index.mjs"`) now lights up itsUI the moment it's installed — the panel fetches the bundle through the autheddiff --git a/frontend/package.json b/frontend/package.jsonindex 6f32a060..4cdd86c9 100644--- a/frontend/package.json+++ b/frontend/package.json@@ -6,7 +6,7 @@"scripts": {"dev": "vite","build": "vite build",- "lint": "eslint . && node scripts/check-settings-index.mjs && node ../scripts/check-html-sinks.mjs",+ "lint": "eslint . && node scripts/check-settings-index.mjs && node scripts/check-theme-tokens.mjs && node ../scripts/check-html-sinks.mjs","lint:settings-index": "node scripts/check-settings-index.mjs","lint:html-sinks": "node ../scripts/check-html-sinks.mjs","capture:skeletons": "node scripts/capture-skeletons.mjs",diff --git a/frontend/scripts/check-theme-tokens.mjs b/frontend/scripts/check-theme-tokens.mjsnew file mode 100644index 00000000..33dd563f--- /dev/null+++ b/frontend/scripts/check-theme-tokens.mjs@@ -0,0 +1,101 @@+#!/usr/bin/env node+// Proving guard for the themes platform (plan 60), wired into the frontend+// `lint` script (the frontend has no unit-test runner, so a lint-stage guard is+// the house-consistent check). Exercises the token whitelist + validators, the+// alias expansion, the dark/light skin resolution fallback, and asserts every+// bundled seed theme is valid. Dependency-free ESM.++import { readFileSync, readdirSync } from 'node:fs';+import { fileURLToPath } from 'node:url';+import { dirname, resolve } from 'node:path';++const here = dirname(fileURLToPath(import.meta.url));+const root = resolve(here, '..');++const {+ validateTokenValue,+ sanitizeTokens,+ expandAliases,+ CANONICAL_TOKENS,+ ALIAS_MAP,+} = await import(new URL('../src/data/themeTokens.js', import.meta.url));+const { resolveSkinTokens } = await import(new URL('../src/utils/applySkin.js', import.meta.url));++let failures = 0;+function check(name, cond) {+ if (!cond) {+ console.error(` ✖ ${name}`);+ failures += 1;+ }+}++// --- value validation: accepts good values ---+check('hex color accepted', validateTokenValue('--surface', '#101218') === '#101218');+check('rgba wash accepted', validateTokenValue('--green-bg', 'rgba(61,220,151,0.12)') !== null);+check('length accepted', validateTokenValue('--radius', '10px') === '10px');+check('font stack accepted', validateTokenValue('--mono', '"IBM Plex Mono", monospace') !== null);+check('shadow accepted', validateTokenValue('--shadow-md', '0 8px 24px -8px rgba(0,0,0,0.55)') !== null);+check('named color accepted', validateTokenValue('--text', 'white') === 'white');++// --- value validation: rejects malicious / malformed / out-of-whitelist ---+check('unknown token rejected', validateTokenValue('--evil', '#fff') === null);+check('url() rejected', validateTokenValue('--surface', 'url(https://x/y.png)') === null);+check('semicolon rejected', validateTokenValue('--surface', '#fff;color:red') === null);+check('brace rejected', validateTokenValue('--surface', '#fff}html{display:none') === null);+check('at-rule rejected', validateTokenValue('--surface', '@import x') === null);+check('expression() rejected', validateTokenValue('--surface', 'expression(alert(1))') === null);+check('non-color in color slot rejected', validateTokenValue('--surface', '10px') === null);+check('non-string rejected', validateTokenValue('--surface', 123) === null);++// --- sanitizeTokens drops unknown/invalid, keeps valid ---+const cleaned = sanitizeTokens({+ '--surface': '#101218',+ '--evil': 'url(x)',+ '--radius': 'not-a-length',+ '--text': '#e9ebf0',+});+check('sanitize keeps valid', cleaned['--surface'] === '#101218' && cleaned['--text'] === '#e9ebf0');+check('sanitize drops unknown', !('--evil' in cleaned));+check('sanitize drops invalid value', !('--radius' in cleaned));++// --- alias expansion fans canonical names out to legacy names ---+const expanded = expandAliases({ '--surface': '#111', '--text': '#eee', '--border': '#222' });+check('alias --surface -> --bg-card', expanded['--bg-card'] === '#111');+check('alias --text -> --text-primary', expanded['--text-primary'] === '#eee');+check('alias --border -> --border-default', expanded['--border-default'] === '#222');+check('canonical retained after expand', expanded['--surface'] === '#111');++// --- every alias target is NOT itself a canonical token (no self-collision) ---+const canonicalSet = new Set(CANONICAL_TOKENS);+for (const [token, aliases] of Object.entries(ALIAS_MAP)) {+ check(`alias source ${token} is canonical`, canonicalSet.has(token));+ for (const a of aliases) check(`alias target ${a} not canonical`, !canonicalSet.has(a));+}++// --- skin resolution + light fallback ---+const darkOnly = { tokens: { dark: { '--surface': '#111' } } };+check('dark resolves dark tokens', resolveSkinTokens(darkOnly, 'dark')?.['--surface'] === '#111');+check('light falls back to stock when no light tokens', resolveSkinTokens(darkOnly, 'light') === null);+const bothModes = { tokens: { dark: { '--surface': '#111' }, light: { '--surface': '#fff' } } };+check('light resolves light tokens', resolveSkinTokens(bothModes, 'light')?.['--surface'] === '#fff');+check('null theme resolves null', resolveSkinTokens(null, 'dark') === null);++// --- every bundled seed theme validates end-to-end ---+const themesDir = resolve(root, 'src/data/themes');+for (const file of readdirSync(themesDir).filter((f) => f.endsWith('.json'))) {+ const theme = JSON.parse(readFileSync(resolve(themesDir, file), 'utf8'));+ check(`${file}: has slug`, typeof theme.slug === 'string' && theme.slug.length > 0);+ check(`${file}: preview has 4 swatches`, Array.isArray(theme.preview) && theme.preview.length === 4);+ for (const mode of Object.keys(theme.tokens || {})) {+ const raw = theme.tokens[mode];+ const clean = sanitizeTokens(raw);+ const dropped = Object.keys(raw).filter((k) => !(k in clean));+ check(`${file}[${mode}]: all tokens valid (dropped: ${dropped.join(',') || 'none'})`, dropped.length === 0);+ }+}++if (failures) {+ console.error(`\n✖ theme-tokens check failed: ${failures} assertion(s)\n`);+ process.exit(1);+}+console.log('✓ theme-tokens: validators, alias expansion, skin resolution, and all bundled themes pass.');diff --git a/frontend/src/components/settings/AppearanceTab.jsx b/frontend/src/components/settings/AppearanceTab.jsxindex d5d7ae9e..ef054723 100644--- a/frontend/src/components/settings/AppearanceTab.jsx+++ b/frontend/src/components/settings/AppearanceTab.jsx@@ -4,6 +4,7 @@ import { ChevronDown, ChevronUp, RotateCcw } from 'lucide-react';import { Button } from '@/components/ui/button';import { Switch } from '@/components/ui/switch';import useSettingFocus from '../../hooks/useSettingFocus';+import ThemeGallery from './ThemeGallery';const ACCENT_PRESETS = [{ label: 'Indigo', color: '#6366f1' },@@ -17,7 +18,7 @@ const ACCENT_PRESETS = [];const AppearanceTab = () => {- const { theme, setTheme, accentColor, setAccentColor } = useTheme();+ const { theme, setTheme, accentColor, setAccentColor, hasCustomAccent, resetAccentColor } = useTheme();const { widgets, toggleWidget, moveWidget, resetLayout } = useDashboardLayout();const register = useSettingFocus();@@ -74,6 +75,12 @@ const AppearanceTab = () => {</div></div>+ <div {...register('appearance-theme-gallery', 'settings-card')}>+ <h3>Theme</h3>+ <p>Pick a color theme. Applies instantly and stays your personal choice; the dark/light toggle above still works on top of it.</p>+ <ThemeGallery />+ </div>+<div {...register('appearance-accent-color', 'settings-card')}><h3>Accent Color</h3><p>Choose the primary accent color used across the interface</p>@@ -99,6 +106,16 @@ const AppearanceTab = () => {onChange={(e) => setAccentColor(e.target.value)}/><span className="accent-custom-hex">{accentColor.toUpperCase()}</span>+ {hasCustomAccent && (+ <button+ type="button"+ className="accent-custom-reset"+ onClick={resetAccentColor}+ title="Use the theme's accent"+ >+ <RotateCcw size={13} /> Use theme accent+ </button>+ )}</div></div></div>diff --git a/frontend/src/components/settings/ThemeGallery.jsx b/frontend/src/components/settings/ThemeGallery.jsxnew file mode 100644index 00000000..a83df965--- /dev/null+++ b/frontend/src/components/settings/ThemeGallery.jsx@@ -0,0 +1,56 @@+import { Check } from 'lucide-react';+import { useTheme } from '../../contexts/ThemeContext';+import { DEFAULT_THEME_SLUG } from '../../data/bundledThemes';++// Theme Gallery — cards for every selectable skin (bundled seeds + installed).+// Apply is instant (tokens are already local); hovering a card previews it live+// and leaving restores the selected skin. Dark/light toggle stays orthogonal.+const ThemeGallery = () => {+ const { availableThemes, skin, setSkin, previewSkin, clearPreview } = useTheme();++ return (+ <div className="theme-gallery">+ {availableThemes.map((t) => {+ const isDefault = t.slug === DEFAULT_THEME_SLUG;+ const active = skin === t.slug;+ const swatches = Array.isArray(t.preview) ? t.preview.slice(0, 4) : [];+ return (+ <button+ type="button"+ key={t.slug}+ className={`theme-card${active ? ' theme-card--active' : ''}`}+ onClick={() => setSkin(t.slug)}+ onMouseEnter={() => previewSkin(isDefault ? null : t)}+ onMouseLeave={clearPreview}+ onFocus={() => previewSkin(isDefault ? null : t)}+ onBlur={clearPreview}+ >+ <div className="theme-card__swatches">+ {swatches.map((color, i) => (+ <span+ key={i}+ className="theme-card__swatch"+ style={{ background: color }}+ />+ ))}+ </div>+ <div className="theme-card__meta">+ <span className="theme-card__name">{t.name || t.slug}</span>+ {t.base && <span className="theme-card__base">{t.base}</span>}+ </div>+ {t.description && (+ <p className="theme-card__desc">{t.description}</p>+ )}+ {active && (+ <span className="theme-card__applied">+ <Check size={13} /> Applied+ </span>+ )}+ </button>+ );+ })}+ </div>+ );+};++export default ThemeGallery;diff --git a/frontend/src/contexts/ThemeContext.jsx b/frontend/src/contexts/ThemeContext.jsxindex 7af2572b..f8a73f82 100644--- a/frontend/src/contexts/ThemeContext.jsx+++ b/frontend/src/contexts/ThemeContext.jsx@@ -1,4 +1,6 @@-import { createContext, useContext, useState, useEffect, useCallback } from 'react';+import { createContext, useContext, useState, useEffect, useCallback, useMemo } from 'react';+import { BUNDLED_THEMES, BUNDLED_THEME_MAP, DEFAULT_THEME_SLUG } from '../data/bundledThemes';+import { applySkin } from '../utils/applySkin';const ThemeContext = createContext(null);@@ -68,6 +70,17 @@ function applyAccentToDOM(hex) {style.setProperty('--accent-shadow', v.shadow);}+// Accent precedence (highest wins): an active workspace's brand color, then the+// user's explicit custom accent, then the active skin's declared accent, then+// the stock default. This keeps workspace/white-label independent of skins and+// lets a theme ship a cohesive accent without stomping a user's choice.+function computeEffectiveAccent({ workspaceAccent, hasCustomAccent, accentColor, skinAccent }) {+ if (workspaceAccent) return workspaceAccent;+ if (hasCustomAccent && accentColor) return accentColor;+ if (skinAccent) return skinAccent;+ return DEFAULT_ACCENT;+}+export function ThemeProvider({ children }) {const [theme, setThemeState] = useState(() => {return localStorage.getItem('theme') || 'dark';@@ -82,6 +95,21 @@ export function ThemeProvider({ children }) {return localStorage.getItem('accent_color') || DEFAULT_ACCENT;});+ // Whether the user has explicitly chosen an accent (vs. inheriting the+ // skin/default). Drives accent precedence.+ const [hasCustomAccent, setHasCustomAccent] = useState(() => {+ return localStorage.getItem('accent_color') != null;+ });++ // Selected skin slug (per-user, like dark/light). 'default' = stock look.+ const [skin, setSkinState] = useState(() => {+ return localStorage.getItem('skin') || DEFAULT_THEME_SLUG;+ });++ // Registry/imported themes merged on top of the bundled seeds at runtime+ // (populated in Phase 2 by fetching installed themes from the API).+ const [installedThemes, setInstalledThemes] = useState({});+const [whiteLabel, setWhiteLabelState] = useState(() => {try {const stored = localStorage.getItem('white_label');@@ -97,6 +125,17 @@ export function ThemeProvider({ children }) {// reloads on switch — so a one-time read is deterministic and sufficient.const workspaceAccent = localStorage.getItem('workspace_accent') || null;+ // All selectable themes (bundled seeds + installed), keyed by slug.+ const themesMap = useMemo(+ () => ({ ...BUNDLED_THEME_MAP, ...installedThemes }),+ [installedThemes],+ );+ const availableThemes = useMemo(() => {+ const merged = { ...BUNDLED_THEME_MAP, ...installedThemes };+ const extras = Object.values(installedThemes).filter((t) => !(t.slug in BUNDLED_THEME_MAP));+ return [...BUNDLED_THEMES, ...extras].map((t) => merged[t.slug] || t);+ }, [installedThemes]);+// Update the DOM attribute and resolved themeconst applyTheme = useCallback((newTheme) => {document.documentElement.setAttribute('data-theme', newTheme);@@ -110,13 +149,57 @@ export function ThemeProvider({ children }) {applyTheme(newTheme);}, [applyTheme]);- // Public setter for accent color. Persists the user's choice but keeps an- // active workspace's brand color in precedence while one is selected.+ // Public setter for accent color. Persists the user's explicit choice.const setAccentColor = useCallback((hex) => {setAccentColorState(hex);+ setHasCustomAccent(true);localStorage.setItem('accent_color', hex);- applyAccentToDOM(workspaceAccent || hex);- }, [workspaceAccent]);+ }, []);++ // Clear the explicit accent so the active skin's accent (or the default)+ // takes over again.+ const resetAccentColor = useCallback(() => {+ setHasCustomAccent(false);+ setAccentColorState(DEFAULT_ACCENT);+ localStorage.removeItem('accent_color');+ }, []);++ // Public setter for the selected skin (per-user).+ const setSkin = useCallback((slug) => {+ const next = slug || DEFAULT_THEME_SLUG;+ setSkinState(next);+ localStorage.setItem('skin', next);+ }, []);++ // Live preview: temporarily apply a theme (or null for stock) without+ // persisting it — used by the gallery on hover. clearPreview restores the+ // currently-selected skin.+ const previewSkin = useCallback((themeObj) => {+ const skinAccent = applySkin(themeObj, resolvedTheme);+ applyAccentToDOM(+ computeEffectiveAccent({ workspaceAccent, hasCustomAccent, accentColor, skinAccent }),+ );+ }, [resolvedTheme, workspaceAccent, hasCustomAccent, accentColor]);++ const clearPreview = useCallback(() => {+ const skinTheme = skin !== DEFAULT_THEME_SLUG ? themesMap[skin] : null;+ const skinAccent = applySkin(skinTheme, resolvedTheme);+ applyAccentToDOM(+ computeEffectiveAccent({ workspaceAccent, hasCustomAccent, accentColor, skinAccent }),+ );+ }, [skin, themesMap, resolvedTheme, workspaceAccent, hasCustomAccent, accentColor]);++ // Merge installed (registry/imported) themes into the selectable set.+ const registerInstalledThemes = useCallback((list) => {+ if (!Array.isArray(list)) return;+ setInstalledThemes((prev) => {+ const next = { ...prev };+ for (const t of list) {+ if (t && t.slug) next[t.slug] = t;+ }+ return next;+ });+ }, []);// Public setter for white label config (accepts partial updates)const setWhiteLabel = useCallback((partial) => {@@ -141,18 +224,39 @@ export function ThemeProvider({ children }) {return () => mediaQuery.removeEventListener('change', handleChange);}, [theme]);- // Apply theme and accent on mount (workspace brand color wins when active).+ // Apply the theme mode attribute on mount / change.useEffect(() => {applyTheme(theme);- applyAccentToDOM(workspaceAccent || accentColor);- }, [theme, applyTheme, accentColor, workspaceAccent]);+ }, [theme, applyTheme]);++ // Apply the active skin's tokens and the effective accent whenever anything+ // that feeds them changes. The 'default' slug means "no skin" — applySkin+ // is handed null so it clears any overrides and the stock stylesheet shows.+ useEffect(() => {+ const skinTheme = skin !== DEFAULT_THEME_SLUG ? themesMap[skin] : null;+ const skinAccent = applySkin(skinTheme, resolvedTheme);+ applyAccentToDOM(+ computeEffectiveAccent({ workspaceAccent, hasCustomAccent, accentColor, skinAccent }),+ );+ }, [skin, resolvedTheme, accentColor, hasCustomAccent, workspaceAccent, themesMap]);++ const activeTheme = skin !== DEFAULT_THEME_SLUG ? (themesMap[skin] || null) : null;const value = {theme, // Current setting: 'dark' | 'light' | 'system'resolvedTheme, // Actual appearance: 'dark' | 'light'setTheme, // Function to change theme- accentColor, // Current accent hex color+ accentColor, // Current accent hex color (user's explicit choice)setAccentColor, // Function to change accent color+ hasCustomAccent, // Whether the accent is an explicit user override+ resetAccentColor,// Clear the explicit accent (fall back to skin/default)+ skin, // Selected skin slug ('default' = stock)+ setSkin, // Function to change the selected skin+ activeTheme, // The active skin's theme object (null for stock)+ availableThemes, // Selectable themes (bundled + installed)+ previewSkin, // Temporarily apply a theme (hover preview)+ clearPreview, // Restore the selected skin after a preview+ registerInstalledThemes, // Merge registry/imported themes into the setwhiteLabel, // White label config objectsetWhiteLabel, // Function to update white label config};diff --git a/frontend/src/data/bundledThemes.js b/frontend/src/data/bundledThemes.jsnew file mode 100644index 00000000..78c94d55--- /dev/null+++ b/frontend/src/data/bundledThemes.js@@ -0,0 +1,31 @@+// Bundled seed themes shipped with the panel (plan 60).+//+// These are the always-present gallery entries — the "default" stock look plus+// a handful of first-party skins — so the Theme Gallery has content on day one+// without any network fetch. Registry-installed themes are merged on top of+// these at runtime (see ThemeContext). The JSON files are the reference+// implementations linked from docs/THEMING.md and seed the serverkit-themes+// registry repo.+//+// The backend keeps its own copy (backend/app/data/themes/) for the pre-auth+// GET /public/active default and the offline registry fallback; the two are+// kept in sync (frontend/scripts/sync-bundled-themes.mjs).++const modules = import.meta.glob('./themes/*.json', { eager: true });++// The stock look is always first; the rest sort alphabetically by name.+export const BUNDLED_THEMES = Object.values(modules)+ .map((m) => m.default ?? m)+ .sort((a, b) => {+ if (a.slug === 'default') return -1;+ if (b.slug === 'default') return 1;+ return (a.name || a.slug).localeCompare(b.name || b.slug);+ });++export const BUNDLED_THEME_MAP = Object.fromEntries(+ BUNDLED_THEMES.map((t) => [t.slug, t]),+);++// The slug that means "no skin" — clears any applied skin and shows the stock+// stylesheet tokens. Always present, never uninstallable.+export const DEFAULT_THEME_SLUG = 'default';diff --git a/frontend/src/data/settingsIndex.js b/frontend/src/data/settingsIndex.jsindex cbba7d07..ef5689dd 100644--- a/frontend/src/data/settingsIndex.js+++ b/frontend/src/data/settingsIndex.js@@ -34,6 +34,7 @@ export const SETTINGS_INDEX = [{ id: 'notifications-webhook', label: 'Generic notification webhook', description: 'Send notifications to a custom webhook endpoint', keywords: 'webhook generic json payload', tab: 'notifications', adminOnly: true },{ id: 'appearance-theme', label: 'Theme mode', description: 'Choose between dark, light, or system default theme', keywords: 'theme dark light system mode', tab: 'appearance', adminOnly: false },+ { id: 'appearance-theme-gallery', label: 'Color theme', description: 'Pick a color theme from the gallery (Paper, Nord Deep, Gruvbox, Phosphor, High Contrast)', keywords: 'theme color skin gallery paper nord gruvbox phosphor high contrast palette', tab: 'appearance', adminOnly: false },{ id: 'appearance-accent-color', label: 'Accent color', description: 'Select the primary accent color for the UI', keywords: 'color accent primary indigo ocean forest sunset rose', tab: 'appearance', adminOnly: false },{ id: 'appearance-widgets', label: 'Dashboard widgets', description: 'Toggle visibility and reorder widgets on the dashboard', keywords: 'widgets dashboard visibility order', tab: 'appearance', adminOnly: false },diff --git a/frontend/src/data/themeTokens.js b/frontend/src/data/themeTokens.jsnew file mode 100644index 00000000..c7983650--- /dev/null+++ b/frontend/src/data/themeTokens.js@@ -0,0 +1,166 @@+// ============================================+// ServerKit theme token whitelist + alias table + validators+// ============================================+// A ServerKit theme is DATA, not code (see docs/THEMING.md and plan 60): a map+// of canonical CSS custom-property names to values. This module is the single+// client-side source of truth for+// - which token names a theme may set (the whitelist),+// - how canonical names expand to the legacy `--bg-*/--text-*/--border-*`+// aliases the stylesheet still reads (the alias table), and+// - what a token's value may look like (the validators).+//+// KEEP IN SYNC with backend/app/services/theme_tokens.py — the backend runs the+// same whitelist + validation server-side on import and registry install.+//+// Accent tokens (--accent*, --accent-primary, …) are intentionally NOT in the+// whitelist: they are derived at runtime from a theme's single `accent` field+// by ThemeContext.applyAccentToDOM, so a workspace/user accent keeps precedence.++// Canonical writable tokens, grouped for the Theme Studio color-picker UI.+// Authors write these ~37 names; the alias table below fans each out to the+// legacy names so all ~60 theme-sensitive stylesheet variables get painted.+export const TOKEN_GROUPS = {+ surfaces: ['--bg-body', '--bg-sidebar', '--surface', '--surface-2', '--surface-3', '--surface-hover'],+ borders: ['--border', '--border-soft', '--border-strong'],+ text: ['--text', '--text-dim', '--text-faint', '--text-ghost'],+ semantic: ['--green', '--green-bg', '--amber', '--amber-bg', '--red', '--red-bg', '--cyan', '--cyan-bg', '--violet', '--violet-bg'],+ radius: ['--radius', '--radius-sm', '--radius-lg'],+ fonts: ['--sans', '--mono'],+ shadows: ['--shadow-sm', '--shadow-md', '--shadow-lg'],+ scrollbar: ['--scrollbar-track', '--scrollbar-thumb', '--scrollbar-thumb-hover'],+ code: ['--bg-code', '--text-code'],+ chrome: ['--grid-color'],+};++// Human labels for each group (Theme Studio section headers).+export const GROUP_LABELS = {+ surfaces: 'Surfaces',+ borders: 'Borders',+ text: 'Text',+ semantic: 'Semantic colors',+ radius: 'Radius',+ fonts: 'Fonts',+ shadows: 'Shadows',+ scrollbar: 'Scrollbar',+ code: 'Code / terminal',+ chrome: 'Chrome',+};++// Which validator applies to each group.+const GROUP_TYPE = {+ surfaces: 'color',+ borders: 'color',+ text: 'color',+ semantic: 'color',+ radius: 'length',+ fonts: 'font',+ shadows: 'shadow',+ scrollbar: 'color',+ code: 'color',+ chrome: 'color',+};++// Flat whitelist + token -> value-type index.+export const CANONICAL_TOKENS = Object.values(TOKEN_GROUPS).flat();++export const TOKEN_TYPE = (() => {+ const out = {};+ for (const [group, tokens] of Object.entries(TOKEN_GROUPS)) {+ for (const t of tokens) out[t] = GROUP_TYPE[group];+ }+ return out;+})();++// Canonical name -> legacy names that must receive the same value. Applying a+// canonical token also sets its aliases so pages still reading `$bg-card` etc.+// (which resolve to the legacy custom properties) track the skin.+export const ALIAS_MAP = {+ '--surface': ['--bg-card'],+ '--surface-2': ['--bg-elevated', '--bg-secondary'],+ '--surface-3': ['--bg-tertiary'],+ '--surface-hover': ['--bg-hover'],+ '--border': ['--border-default'],+ '--border-soft': ['--border-subtle'],+ '--border-strong': ['--border-active', '--border-hover'],+ '--text': ['--text-primary'],+ '--text-dim': ['--text-secondary'],+ '--text-faint': ['--text-tertiary'],+};++// Every property name a skin may ever set (canonical + aliases). Used to clear+// a previous skin cleanly before applying the next one — never touches accent.+export const ALL_SKIN_PROPERTIES = [+ ...CANONICAL_TOKENS,+ ...Object.values(ALIAS_MAP).flat(),+];++// --------------------------------------------+// Value validation+// --------------------------------------------+// Reject anything that could break out of a single CSS declaration or smuggle a+// network fetch / script. Even though we apply per-token via setProperty (which+// the browser sanitises), this keeps the stored/exported theme.json clean and+// makes the same rules enforceable server-side and in the registry CI.+const FORBIDDEN = /url\(|expression\(|javascript:|@import|[@;{}<>]|\/\*/i;++const HEX = /^#([0-9a-fA-F]{3,4}|[0-9a-fA-F]{6}|[0-9a-fA-F]{8})$/;+const FUNC_COLOR = /^(rgb|rgba|hsl|hsla)\(\s*[0-9.,%\s/]+\)$/i;+const NAMED_COLOR = /^[a-zA-Z]{3,24}$/; // transparent, currentColor, white, …+const LENGTH = /^-?(?:0|\d*\.?\d+)(px|rem|em|%|vh|vw)?$/;+const FONT_STACK = /^[a-zA-Z0-9 ,"'-]{1,200}$/;+const SHADOW = /^[0-9a-zA-Z.,%()#\s/-]{1,200}$/; // numbers, rgba(), inset, none++function isColor(v) {+ return HEX.test(v) || FUNC_COLOR.test(v) || NAMED_COLOR.test(v);+}++const VALIDATORS = {+ color: isColor,+ length: (v) => LENGTH.test(v),+ font: (v) => FONT_STACK.test(v),+ shadow: (v) => SHADOW.test(v) || v === 'none',+};++/**+ * Validate a single token value. Returns the trimmed value if the token is+ * whitelisted and the value passes its type check (and contains no forbidden+ * substring), otherwise null.+ */+export function validateTokenValue(token, value) {+ const type = TOKEN_TYPE[token];+ if (!type) return null; // not whitelisted+ if (typeof value !== 'string') return null;+ const v = value.trim();+ if (!v || v.length > 200) return null;+ if (FORBIDDEN.test(v)) return null;+ return VALIDATORS[type](v) ? v : null;+}++/**+ * Drop unknown / invalid entries from a raw token map, returning only the+ * whitelisted, validated canonical tokens. Unknown keys degrade gracefully+ * (forward-compat: a newer theme on an older panel just loses the new tokens).+ */+export function sanitizeTokens(raw) {+ const out = {};+ if (!raw || typeof raw !== 'object') return out;+ for (const [token, value] of Object.entries(raw)) {+ const clean = validateTokenValue(token, value);+ if (clean !== null) out[token] = clean;+ }+ return out;+}++/**+ * Expand a validated canonical token map to include its legacy aliases, ready+ * to hand to setProperty. Canonical values win over any alias collision.+ */+export function expandAliases(cleanTokens) {+ const out = { ...cleanTokens };+ for (const [token, value] of Object.entries(cleanTokens)) {+ for (const alias of ALIAS_MAP[token] || []) {+ if (!(alias in cleanTokens)) out[alias] = value;+ }+ }+ return out;+}diff --git a/frontend/src/data/themes/default.json b/frontend/src/data/themes/default.jsonnew file mode 100644index 00000000..e534983d--- /dev/null+++ b/frontend/src/data/themes/default.json@@ -0,0 +1,82 @@+{+ "schema_version": 1,+ "slug": "default",+ "name": "ServerKit",+ "author": "serverkit",+ "version": "1.0.0",+ "description": "The stock ServerKit look — deep slate surfaces with a periwinkle accent.",+ "base": "dark",+ "builtin": true,+ "tokens": {+ "dark": {+ "--bg-body": "#0a0b0e",+ "--bg-sidebar": "#0d0f15",+ "--surface": "#101218",+ "--surface-2": "#161922",+ "--surface-3": "#1c2029",+ "--surface-hover": "#1a1e27",+ "--border": "#23272f",+ "--border-soft": "#191c23",+ "--border-strong": "#2c313b",+ "--text": "#e9ebf0",+ "--text-dim": "#9aa1af",+ "--text-faint": "#646b7a",+ "--text-ghost": "#444b58",+ "--green": "#3ddc97",+ "--green-bg": "rgba(61,220,151,0.12)",+ "--amber": "#f5b945",+ "--amber-bg": "rgba(245,185,69,0.12)",+ "--red": "#fb6f6f",+ "--red-bg": "rgba(251,111,111,0.12)",+ "--cyan": "#49c7f0",+ "--cyan-bg": "rgba(73,199,240,0.12)",+ "--violet": "#b07bf5",+ "--violet-bg": "rgba(176,123,245,0.12)",+ "--radius": "10px",+ "--radius-sm": "7px",+ "--radius-lg": "14px",+ "--scrollbar-track": "#101218",+ "--scrollbar-thumb": "#2a2f3a",+ "--scrollbar-thumb-hover": "#363c49",+ "--bg-code": "#0d1017",+ "--text-code": "#e2e8f0",+ "--grid-color": "rgba(255,255,255,0.02)"+ },+ "light": {+ "--bg-body": "#f6f7fb",+ "--bg-sidebar": "#f1f3f9",+ "--surface": "#ffffff",+ "--surface-2": "#f6f7fb",+ "--surface-3": "#eef1f7",+ "--surface-hover": "#eef1f7",+ "--border": "#e2e6ef",+ "--border-soft": "#eef1f7",+ "--border-strong": "#cdd3e0",+ "--text": "#161a23",+ "--text-dim": "#515a6b",+ "--text-faint": "#79818f",+ "--text-ghost": "#a6adba",+ "--green": "#3ddc97",+ "--green-bg": "rgba(61,220,151,0.12)",+ "--amber": "#f5b945",+ "--amber-bg": "rgba(245,185,69,0.12)",+ "--red": "#fb6f6f",+ "--red-bg": "rgba(251,111,111,0.12)",+ "--cyan": "#49c7f0",+ "--cyan-bg": "rgba(73,199,240,0.12)",+ "--violet": "#b07bf5",+ "--violet-bg": "rgba(176,123,245,0.12)",+ "--radius": "10px",+ "--radius-sm": "7px",+ "--radius-lg": "14px",+ "--scrollbar-track": "#f1f3f9",+ "--scrollbar-thumb": "#cdd3e0",+ "--scrollbar-thumb-hover": "#aab2c2",+ "--bg-code": "#f1f3f9",+ "--text-code": "#334155",+ "--grid-color": "rgba(109,124,255,0.06)"+ }+ },+ "accent": "#6d7cff",+ "preview": ["#0a0b0e", "#101218", "#6d7cff", "#e9ebf0"]+}diff --git a/frontend/src/data/themes/gruvbox.json b/frontend/src/data/themes/gruvbox.jsonnew file mode 100644index 00000000..bbcf0290--- /dev/null+++ b/frontend/src/data/themes/gruvbox.json@@ -0,0 +1,46 @@+{+ "schema_version": 1,+ "slug": "gruvbox",+ "name": "Gruvbox",+ "author": "serverkit",+ "version": "1.0.0",+ "description": "A warm retro terminal palette with earthy browns and an orange accent.",+ "base": "dark",+ "builtin": true,+ "tokens": {+ "dark": {+ "--bg-body": "#1d2021",+ "--bg-sidebar": "#1b1e1f",+ "--surface": "#282828",+ "--surface-2": "#3c3836",+ "--surface-3": "#504945",+ "--surface-hover": "#32302f",+ "--border": "#504945",+ "--border-soft": "#3c3836",+ "--border-strong": "#665c54",+ "--text": "#ebdbb2",+ "--text-dim": "#d5c4a1",+ "--text-faint": "#a89984",+ "--text-ghost": "#7c6f64",+ "--green": "#b8bb26",+ "--green-bg": "rgba(184,187,38,0.14)",+ "--amber": "#fabd2f",+ "--amber-bg": "rgba(250,189,47,0.14)",+ "--red": "#fb4934",+ "--red-bg": "rgba(251,73,52,0.14)",+ "--cyan": "#83a598",+ "--cyan-bg": "rgba(131,165,152,0.14)",+ "--violet": "#d3869b",+ "--violet-bg": "rgba(211,134,155,0.14)",+ "--scrollbar-track": "#282828",+ "--scrollbar-thumb": "#504945",+ "--scrollbar-thumb-hover": "#665c54",+ "--bg-code": "#1d2021",+ "--text-code": "#ebdbb2",+ "--grid-color": "rgba(235,219,178,0.03)",+ "--mono": "\"IBM Plex Mono\", ui-monospace, \"SF Mono\", Menlo, monospace"+ }+ },+ "accent": "#fe8019",+ "preview": ["#1d2021", "#282828", "#fe8019", "#ebdbb2"]+}diff --git a/frontend/src/data/themes/high-contrast.json b/frontend/src/data/themes/high-contrast.jsonnew file mode 100644index 00000000..8f049bbc--- /dev/null+++ b/frontend/src/data/themes/high-contrast.json@@ -0,0 +1,76 @@+{+ "schema_version": 1,+ "slug": "high-contrast",+ "name": "High Contrast",+ "author": "serverkit",+ "version": "1.0.0",+ "description": "A maximum-contrast theme tuned for accessibility, in dark and light.",+ "base": "dark",+ "builtin": true,+ "tokens": {+ "dark": {+ "--bg-body": "#000000",+ "--bg-sidebar": "#000000",+ "--surface": "#0a0a0a",+ "--surface-2": "#141414",+ "--surface-3": "#1f1f1f",+ "--surface-hover": "#1a1a1a",+ "--border": "#ffffff",+ "--border-soft": "#808080",+ "--border-strong": "#ffffff",+ "--text": "#ffffff",+ "--text-dim": "#e0e0e0",+ "--text-faint": "#b0b0b0",+ "--text-ghost": "#808080",+ "--green": "#00ff66",+ "--green-bg": "rgba(0,255,102,0.18)",+ "--amber": "#ffcc00",+ "--amber-bg": "rgba(255,204,0,0.18)",+ "--red": "#ff3333",+ "--red-bg": "rgba(255,51,51,0.18)",+ "--cyan": "#00ffff",+ "--cyan-bg": "rgba(0,255,255,0.18)",+ "--violet": "#cc66ff",+ "--violet-bg": "rgba(204,102,255,0.18)",+ "--scrollbar-track": "#000000",+ "--scrollbar-thumb": "#808080",+ "--scrollbar-thumb-hover": "#ffffff",+ "--bg-code": "#000000",+ "--text-code": "#ffffff",+ "--grid-color": "rgba(255,255,255,0.06)"+ },+ "light": {+ "--bg-body": "#ffffff",+ "--bg-sidebar": "#ffffff",+ "--surface": "#ffffff",+ "--surface-2": "#f2f2f2",+ "--surface-3": "#e6e6e6",+ "--surface-hover": "#ededed",+ "--border": "#000000",+ "--border-soft": "#444444",+ "--border-strong": "#000000",+ "--text": "#000000",+ "--text-dim": "#1a1a1a",+ "--text-faint": "#333333",+ "--text-ghost": "#555555",+ "--green": "#007a1f",+ "--green-bg": "rgba(0,122,31,0.14)",+ "--amber": "#8a5a00",+ "--amber-bg": "rgba(138,90,0,0.14)",+ "--red": "#cc0000",+ "--red-bg": "rgba(204,0,0,0.14)",+ "--cyan": "#005f73",+ "--cyan-bg": "rgba(0,95,115,0.14)",+ "--violet": "#6a1b9a",+ "--violet-bg": "rgba(106,27,154,0.14)",+ "--scrollbar-track": "#ffffff",+ "--scrollbar-thumb": "#444444",+ "--scrollbar-thumb-hover": "#000000",+ "--bg-code": "#f2f2f2",+ "--text-code": "#000000",+ "--grid-color": "rgba(0,0,0,0.08)"+ }+ },+ "accent": "#00d0ff",+ "preview": ["#000000", "#0a0a0a", "#00d0ff", "#ffffff"]+}diff --git a/frontend/src/data/themes/nord-deep.json b/frontend/src/data/themes/nord-deep.jsonnew file mode 100644index 00000000..a12b49fa--- /dev/null+++ b/frontend/src/data/themes/nord-deep.json@@ -0,0 +1,45 @@+{+ "schema_version": 1,+ "slug": "nord-deep",+ "name": "Nord Deep",+ "author": "serverkit",+ "version": "1.0.0",+ "description": "A deep arctic dark theme with cool blue surfaces and frosty accents.",+ "base": "dark",+ "builtin": true,+ "tokens": {+ "dark": {+ "--bg-body": "#242933",+ "--bg-sidebar": "#20242d",+ "--surface": "#2e3440",+ "--surface-2": "#3b4252",+ "--surface-3": "#434c5e",+ "--surface-hover": "#3b4252",+ "--border": "#4c566a",+ "--border-soft": "#3b4252",+ "--border-strong": "#5b667c",+ "--text": "#eceff4",+ "--text-dim": "#d8dee9",+ "--text-faint": "#9aa5b8",+ "--text-ghost": "#6b7488",+ "--green": "#a3be8c",+ "--green-bg": "rgba(163,190,140,0.14)",+ "--amber": "#ebcb8b",+ "--amber-bg": "rgba(235,203,139,0.14)",+ "--red": "#bf616a",+ "--red-bg": "rgba(191,97,106,0.14)",+ "--cyan": "#88c0d0",+ "--cyan-bg": "rgba(136,192,208,0.14)",+ "--violet": "#b48ead",+ "--violet-bg": "rgba(180,142,173,0.14)",+ "--scrollbar-track": "#2e3440",+ "--scrollbar-thumb": "#434c5e",+ "--scrollbar-thumb-hover": "#4c566a",+ "--bg-code": "#272c36",+ "--text-code": "#d8dee9",+ "--grid-color": "rgba(216,222,233,0.03)"+ }+ },+ "accent": "#88c0d0",+ "preview": ["#242933", "#2e3440", "#88c0d0", "#eceff4"]+}diff --git a/frontend/src/data/themes/paper.json b/frontend/src/data/themes/paper.jsonnew file mode 100644index 00000000..110cbe9b--- /dev/null+++ b/frontend/src/data/themes/paper.json@@ -0,0 +1,45 @@+{+ "schema_version": 1,+ "slug": "paper",+ "name": "Paper",+ "author": "serverkit",+ "version": "1.0.0",+ "description": "A clean, bright light theme with crisp white surfaces and a blue accent.",+ "base": "light",+ "builtin": true,+ "tokens": {+ "light": {+ "--bg-body": "#fbfbfd",+ "--bg-sidebar": "#f4f5f8",+ "--surface": "#ffffff",+ "--surface-2": "#f7f8fa",+ "--surface-3": "#eef0f4",+ "--surface-hover": "#f0f2f6",+ "--border": "#e4e7ee",+ "--border-soft": "#eef0f4",+ "--border-strong": "#cfd4de",+ "--text": "#1a1d24",+ "--text-dim": "#545b68",+ "--text-faint": "#808896",+ "--text-ghost": "#aab0bd",+ "--green": "#16a34a",+ "--green-bg": "rgba(22,163,74,0.10)",+ "--amber": "#d97706",+ "--amber-bg": "rgba(217,119,6,0.10)",+ "--red": "#dc2626",+ "--red-bg": "rgba(220,38,38,0.10)",+ "--cyan": "#0891b2",+ "--cyan-bg": "rgba(8,145,178,0.10)",+ "--violet": "#7c3aed",+ "--violet-bg": "rgba(124,58,237,0.10)",+ "--scrollbar-track": "#f4f5f8",+ "--scrollbar-thumb": "#cfd4de",+ "--scrollbar-thumb-hover": "#b3bac6",+ "--bg-code": "#f4f5f8",+ "--text-code": "#24303f",+ "--grid-color": "rgba(37,99,235,0.05)"+ }+ },+ "accent": "#2563eb",+ "preview": ["#fbfbfd", "#ffffff", "#2563eb", "#1a1d24"]+}diff --git a/frontend/src/data/themes/phosphor.json b/frontend/src/data/themes/phosphor.jsonnew file mode 100644index 00000000..09a728ad--- /dev/null+++ b/frontend/src/data/themes/phosphor.json@@ -0,0 +1,46 @@+{+ "schema_version": 1,+ "slug": "phosphor",+ "name": "Phosphor",+ "author": "serverkit",+ "version": "1.0.0",+ "description": "A near-black OLED theme with glowing terminal-green text.",+ "base": "dark",+ "builtin": true,+ "tokens": {+ "dark": {+ "--bg-body": "#000000",+ "--bg-sidebar": "#030503",+ "--surface": "#0a0f0a",+ "--surface-2": "#0f150f",+ "--surface-3": "#142014",+ "--surface-hover": "#111a11",+ "--border": "#1a241a",+ "--border-soft": "#101810",+ "--border-strong": "#294029",+ "--text": "#c8f7c8",+ "--text-dim": "#7fcf7f",+ "--text-faint": "#4f8f4f",+ "--text-ghost": "#2f5f2f",+ "--green": "#33ff66",+ "--green-bg": "rgba(51,255,102,0.12)",+ "--amber": "#ffcc33",+ "--amber-bg": "rgba(255,204,51,0.12)",+ "--red": "#ff5555",+ "--red-bg": "rgba(255,85,85,0.12)",+ "--cyan": "#33ffff",+ "--cyan-bg": "rgba(51,255,255,0.12)",+ "--violet": "#cc99ff",+ "--violet-bg": "rgba(204,153,255,0.12)",+ "--scrollbar-track": "#050805",+ "--scrollbar-thumb": "#1a301a",+ "--scrollbar-thumb-hover": "#294029",+ "--bg-code": "#000000",+ "--text-code": "#33ff66",+ "--grid-color": "rgba(51,255,102,0.04)",+ "--mono": "\"IBM Plex Mono\", ui-monospace, \"SF Mono\", Menlo, monospace"+ }+ },+ "accent": "#33ff66",+ "preview": ["#000000", "#0a0f0a", "#33ff66", "#c8f7c8"]+}diff --git a/frontend/src/styles/pages/_service-detail.scss b/frontend/src/styles/pages/_service-detail.scssindex 1f09f7dd..0042d9bd 100644--- a/frontend/src/styles/pages/_service-detail.scss+++ b/frontend/src/styles/pages/_service-detail.scss@@ -340,7 +340,7 @@background: rgba(61, 220, 151, 0.1);border: 1px solid rgba(61, 220, 151, 0.2);border-radius: $radius-full;- color: #3ddc97;+ color: var(--green);font-size: $font-size-xs;font-weight: $font-weight-medium;}diff --git a/frontend/src/styles/pages/_services.scss b/frontend/src/styles/pages/_services.scssindex 123704d9..299866aa 100644--- a/frontend/src/styles/pages/_services.scss+++ b/frontend/src/styles/pages/_services.scss@@ -27,13 +27,13 @@&--manual {background: rgba(245, 185, 69, 0.08);border-color: rgba(245, 185, 69, 0.2);- color: #f5b945;+ color: var(--amber);}&--upload {background: rgba(176, 123, 245, 0.08);border-color: rgba(176, 123, 245, 0.2);- color: #b07bf5;+ color: var(--violet);}}diff --git a/frontend/src/styles/pages/_settings.scss b/frontend/src/styles/pages/_settings.scssindex 4c2b2ba6..9bb5e556 100644--- a/frontend/src/styles/pages/_settings.scss+++ b/frontend/src/styles/pages/_settings.scss@@ -1326,6 +1326,115 @@color: $text-secondary;}+.accent-custom-reset {+ display: inline-flex;+ align-items: center;+ gap: 4px;+ margin-left: auto;+ padding: 4px 10px;+ font-size: $font-size-xs;+ font-weight: $font-weight-medium;+ color: var(--text-dim);+ background: transparent;+ border: 1px solid var(--border);+ border-radius: $radius-md;+ cursor: pointer;+ transition: all $transition-fast;++ &:hover {+ color: var(--text);+ border-color: var(--border-strong);+ }+}++// ============================================+// THEME GALLERY (plan 60 — community themes)+// ============================================++.theme-gallery {+ display: grid;+ grid-template-columns: repeat(auto-fill, minmax(180px, 1fr));+ gap: $space-3;++ @media (max-width: $breakpoint-md) {+ grid-template-columns: repeat(auto-fill, minmax(150px, 1fr));+ }+}++.theme-card {+ position: relative;+ display: flex;+ flex-direction: column;+ gap: $space-2;+ padding: $space-3;+ text-align: left;+ background: var(--surface-2);+ border: 2px solid var(--border);+ border-radius: $radius-lg;+ cursor: pointer;+ transition: all $transition-fast;++ &:hover {+ border-color: var(--border-strong);+ }++ &--active {+ border-color: var(--accent-primary);+ box-shadow: 0 0 0 1px var(--accent-primary);+ }++ &__swatches {+ display: flex;+ height: 44px;+ border-radius: $radius-md;+ overflow: hidden;+ border: 1px solid var(--border-soft);+ }++ &__swatch {+ flex: 1;+ }++ &__meta {+ display: flex;+ align-items: center;+ justify-content: space-between;+ gap: $space-2;+ }++ &__name {+ font-size: $font-size-sm;+ font-weight: $font-weight-semibold;+ color: var(--text);+ }++ &__base {+ font-size: $font-size-xs;+ text-transform: uppercase;+ letter-spacing: 0.04em;+ color: var(--text-faint);+ padding: 1px 6px;+ border: 1px solid var(--border);+ border-radius: $radius-sm;+ }++ &__desc {+ margin: 0;+ font-size: $font-size-xs;+ line-height: 1.4;+ color: var(--text-dim);+ }++ &__applied {+ display: inline-flex;+ align-items: center;+ gap: 4px;+ font-size: $font-size-xs;+ font-weight: $font-weight-medium;+ color: var(--accent-primary);+ }+}+// ============================================// DASHBOARD WIDGET CONFIG// ============================================diff --git a/frontend/src/utils/applySkin.js b/frontend/src/utils/applySkin.jsnew file mode 100644index 00000000..f911acb5--- /dev/null+++ b/frontend/src/utils/applySkin.js@@ -0,0 +1,67 @@+// Runtime skin applier (plan 60).+//+// A "skin" is a theme's validated token map applied on top of the stock+// stylesheet at runtime. We set each canonical token (plus its legacy aliases)+// as an inline custom property on <html> via setProperty — inline properties+// win over the stylesheet's :root / [data-theme] rules, and setProperty is+// inherently injection-safe (the browser drops anything malformed). Accent+// tokens are never touched here; ThemeContext.applyAccentToDOM owns those so a+// workspace/user accent keeps precedence over the skin.++import { sanitizeTokens, expandAliases, ALL_SKIN_PROPERTIES } from '../data/themeTokens.js';++/**+ * Pick the token map to apply for the current resolved mode, with the+ * light-mode fallback: a `base:"dark"` theme that ships no `light` tokens+ * degrades to the stock light theme when the user toggles to light (we return+ * null, which clears the skin so the stylesheet's [data-theme="light"] shows).+ *+ * @param {object|null} theme a theme object with `tokens: { dark, light }`+ * @param {'dark'|'light'} resolvedTheme+ * @returns {object|null} raw token map for that mode, or null to clear+ */+export function resolveSkinTokens(theme, resolvedTheme) {+ if (!theme || !theme.tokens) return null;+ const mode = resolvedTheme === 'light' ? 'light' : 'dark';+ const map = theme.tokens[mode];+ if (map && typeof map === 'object' && Object.keys(map).length) return map;+ return null; // no tokens for this mode → fall back to stock+}++/**+ * Clear every property a skin could have set (canonical + aliases). Never+ * touches accent properties, which are managed separately.+ */+export function clearSkin(root = document.documentElement) {+ const style = root.style;+ for (const name of ALL_SKIN_PROPERTIES) style.removeProperty(name);+}++/**+ * Apply a raw token map to the document root: sanitise → expand aliases →+ * setProperty. Always clears the previous skin first so switching themes (or+ * toggling dark/light) never leaves stale overrides behind.+ *+ * @param {object|null} rawTokens token map (unsanitised is fine), or null to clear+ * @param {HTMLElement} root defaults to <html>+ */+export function applySkinTokens(rawTokens, root = document.documentElement) {+ clearSkin(root);+ if (!rawTokens) return;+ const clean = expandAliases(sanitizeTokens(rawTokens));+ const style = root.style;+ for (const [token, value] of Object.entries(clean)) {+ style.setProperty(token, value);+ }+}++/**+ * Convenience: resolve the right mode's tokens for a theme and apply them.+ * Returns the theme's declared `accent` (if any) so the caller can fold it into+ * accent precedence.+ */+export function applySkin(theme, resolvedTheme, root = document.documentElement) {+ const tokens = resolveSkinTokens(theme, resolvedTheme);+ applySkinTokens(tokens, root);+ return theme && typeof theme.accent === 'string' ? theme.accent : null;+}