Skip to content

A fast 2D and 3D game engine — TypeScript SDK, C++/WebAssembly core, visual editor. Ship one project to web, desktop, WeChat MiniGames, playable ads, and native Android / iOS.

feat(ui): project-level theme token overrides, end to end

esengine0c9b24d49b80
diff --git a/desktop/electron/exportGame.ts b/desktop/electron/exportGame.ts
index 412245fba..5b290df51 100644
--- a/desktop/electron/exportGame.ts
+++ b/desktop/electron/exportGame.ts
@@ -302,6 +302,10 @@ export async function exportGame(opts: {
/** Project camera fit (Project Settings → Display) — the main camera letterboxes this
* design resolution regardless of any UI Canvas. Absent ⇒ no fit (raw orthoSize). */
screenFit?: { designWidth: number; designHeight: number; scaleMode: number; matchWidthOrHeight: number };
+ /** Project widget theme (Project Settings → UI); absent = dark. */
+ uiTheme?: 'light';
+ /** Project theme color overrides (role → #rrggbbaa hex) — the host parses them. */
+ uiThemeColors?: Record<string, string>;
}): Promise<ExportGameResult> {
const platform = opts.platform ?? 'web';
const title = opts.title ?? 'Game';
@@ -328,6 +332,8 @@ export async function exportGame(opts: {
ySortLayers: opts.ySortLayers,
colorSpace: opts.colorSpace,
screenFit: opts.screenFit,
+ uiTheme: opts.uiTheme,
+ uiThemeColors: opts.uiThemeColors,
minify: opts.minify,
contentAddressed: opts.contentAddressed,
compressTextures: opts.compressTextures,
@@ -354,6 +360,8 @@ export async function exportGame(opts: {
ySortLayers: opts.ySortLayers,
colorSpace: opts.colorSpace,
screenFit: opts.screenFit,
+ uiTheme: opts.uiTheme,
+ uiThemeColors: opts.uiThemeColors,
onProgress: opts.onProgress,
});
}
@@ -425,6 +433,8 @@ export async function exportGame(opts: {
...(opts.ySortLayers ? { ySortLayers: opts.ySortLayers } : {}),
...(opts.colorSpace === 'linear' ? { colorSpace: opts.colorSpace } : {}),
...(opts.screenFit && opts.screenFit.scaleMode >= 0 ? { screenFit: opts.screenFit } : {}),
+ ...(opts.uiTheme === 'light' ? { uiTheme: opts.uiTheme } : {}),
+ ...(opts.uiThemeColors && Object.keys(opts.uiThemeColors).length > 0 ? { uiThemeColors: opts.uiThemeColors } : {}),
},
null, 2,
) + '\n',
diff --git a/desktop/electron/exportMiniGame.ts b/desktop/electron/exportMiniGame.ts
index 9bd5f3cdb..f12586b32 100644
--- a/desktop/electron/exportMiniGame.ts
+++ b/desktop/electron/exportMiniGame.ts
@@ -225,6 +225,10 @@ export async function exportMiniGame(profile: MiniGameExportProfile, opts: {
/** Project camera fit (Project Settings → Display) — letterboxes the design resolution
* without a UI Canvas; absent = no fit. */
screenFit?: { designWidth: number; designHeight: number; scaleMode: number; matchWidthOrHeight: number };
+ /** Project widget theme (Project Settings → UI); absent = dark. */
+ uiTheme?: 'light';
+ /** Project theme color overrides (role → #rrggbbaa hex) — parsed by the generated boot. */
+ uiThemeColors?: Record<string, string>;
minify?: boolean;
/** Emit content-addressed asset filenames (<hash><ext>) for dedup + immutable caching. */
contentAddressed?: boolean;
@@ -336,11 +340,12 @@ export async function exportMiniGame(profile: MiniGameExportProfile, opts: {
// which glue it staged (esengine.wxgame vs the web-aligned esengine), and the
// runtime must instantiate the staged glue's .wasm twin, not guess a name.
const engineWasmPath = `wasm/${engineGlueFile.replace(/\.js$/, '.wasm')}`;
+ const themeColors = opts.uiThemeColors && Object.keys(opts.uiThemeColors).length > 0 ? opts.uiThemeColors : undefined;
const entrySrc =
- `import { ${profile.runtimeInit} } from 'esengine';\n` +
+ `import { ${profile.runtimeInit}${themeColors ? ', parseThemeOverrides' : ''} } from 'esengine';\n` +
(scriptsAbs && existsSync(scriptsAbs) ? `import ${JSON.stringify(scriptsAbs)};\n` : '') +
`export function boot(engineFactory, sideModuleFactories) {\n` +
- ` return ${profile.runtimeInit}({ engineFactory, engineWasmPath: ${JSON.stringify(engineWasmPath)}, sideModuleFactories, sceneNames: ${JSON.stringify(scenes.map((s) => s.name))}, firstScene: ${JSON.stringify(sceneName)}${opts.ySortLayers ? `, ySortLayers: ${opts.ySortLayers >>> 0}` : ''}${opts.colorSpace === 'linear' ? `, colorSpace: 'linear'` : ''}${opts.screenFit && opts.screenFit.scaleMode >= 0 ? `, screenFit: ${JSON.stringify(opts.screenFit)}` : ''} });\n` +
+ ` return ${profile.runtimeInit}({ engineFactory, engineWasmPath: ${JSON.stringify(engineWasmPath)}, sideModuleFactories, sceneNames: ${JSON.stringify(scenes.map((s) => s.name))}, firstScene: ${JSON.stringify(sceneName)}${opts.ySortLayers ? `, ySortLayers: ${opts.ySortLayers >>> 0}` : ''}${opts.colorSpace === 'linear' ? `, colorSpace: 'linear'` : ''}${opts.screenFit && opts.screenFit.scaleMode >= 0 ? `, screenFit: ${JSON.stringify(opts.screenFit)}` : ''}${opts.uiTheme === 'light' ? `, uiTheme: 'light'` : ''}${themeColors ? `, uiThemeOverrides: parseThemeOverrides(${JSON.stringify(themeColors)})` : ''} });\n` +
`}\n`;
progress({ phase: 'Bundling game' });
try {
diff --git a/desktop/electron/exportPlayable.ts b/desktop/electron/exportPlayable.ts
index 6518b20d6..18f384486 100644
--- a/desktop/electron/exportPlayable.ts
+++ b/desktop/electron/exportPlayable.ts
@@ -158,6 +158,10 @@ export async function exportPlayable(opts: {
/** Project camera fit (design resolution + scale mode) — letterboxes the main camera
* without a UI Canvas; absent = no fit. */
screenFit?: { designWidth: number; designHeight: number; scaleMode: number; matchWidthOrHeight: number };
+ /** Project widget theme (Project Settings → UI); absent = dark. */
+ uiTheme?: 'light';
+ /** Project theme color overrides (role → #rrggbbaa hex) — the host parses them. */
+ uiThemeColors?: Record<string, string>;
onProgress?: OnExportProgress;
}): Promise<ExportPlayableResult> {
const title = opts.title ?? 'Game';
@@ -275,7 +279,9 @@ export async function exportPlayable(opts: {
`window.__GAME_FIRST__=${JSON.stringify(sceneName)};` +
`window.__GAME_YSORT__=${(opts.ySortLayers ?? 0) >>> 0};` +
`window.__GAME_COLORSPACE__=${JSON.stringify(opts.colorSpace === 'linear' ? 'linear' : 'gamma')};` +
- (opts.screenFit && opts.screenFit.scaleMode >= 0 ? `window.__GAME_SCREENFIT__=${JSON.stringify(opts.screenFit)};` : '');
+ (opts.screenFit && opts.screenFit.scaleMode >= 0 ? `window.__GAME_SCREENFIT__=${JSON.stringify(opts.screenFit)};` : '') +
+ (opts.uiTheme === 'light' ? `window.__GAME_UITHEME__='light';` : '') +
+ (opts.uiThemeColors && Object.keys(opts.uiThemeColors).length > 0 ? `window.__GAME_UITHEMECOLORS__=${JSON.stringify(opts.uiThemeColors)};` : '');
const outFile = path.join(absOut, 'index.html');
await writeFile(outFile, indexHtml(title, globals, bundle, orientation));
await rm(cookDir, { recursive: true, force: true });
diff --git a/desktop/electron/main.ts b/desktop/electron/main.ts
index 42f302897..55ec8badd 100644
--- a/desktop/electron/main.ts
+++ b/desktop/electron/main.ts
@@ -665,6 +665,8 @@ ipcMain.handle(
// Project camera fit → runtime screenFit (only when the project opts in; scaleMode < 0 = off).
const fit = resolveScreenFit(manifest);
const screenFit = fit.scaleMode >= 0 ? fit : undefined;
+ const uiTheme = manifest.features?.ui?.theme === 'light' ? 'light' as const : undefined;
+ const uiThemeColors = manifest.features?.ui?.colors;
return exportGame({
root,
entryScene,
@@ -673,6 +675,8 @@ ipcMain.handle(
ySortLayers,
colorSpace,
screenFit,
+ uiTheme,
+ uiThemeColors,
gameHostEntry: path.join(HOSTS_DIR, 'gameHost.js'),
playableHostEntry: path.join(HOSTS_DIR, 'playableHost.js'),
scriptsEntry: resolveScripts(manifest).main,
diff --git a/desktop/src/components/SettingsDialog.tsx b/desktop/src/components/SettingsDialog.tsx
index 78856567e..e52ba6092 100644
--- a/desktop/src/components/SettingsDialog.tsx
+++ b/desktop/src/components/SettingsDialog.tsx
@@ -21,6 +21,7 @@ import { IconButton } from '@/components/IconButton';
import { SearchField } from '@/components/SearchField';
import { Segmented } from '@/components/Segmented';
import { Select } from '@/components/Select';
+import { ColorControl } from '@/components/ColorControl';
import type { Setting, NumberSetting, KeybindingSetting, StringListSetting, MatrixSetting, FlagListSetting } from '@/settings/types';
import { t } from '@/i18n';
@@ -276,6 +277,18 @@ function Control({ setting }: { setting: Setting }) {
))}
</div>
);
+ case 'colorpicker': {
+ const hex = String(value ?? '');
+ return (
+ <div className={`set-colorpicker${hex ? '' : ' inherited'}`}>
+ <ColorControl
+ value={hex || setting.placeholderColor?.() || '#00000000'}
+ onChange={(v) => setValue(setting.id, v)}
+ />
+ {!hex && <span className="set-inherit">{t('set.inherited')}</span>}
+ </div>
+ );
+ }
case 'keybinding':
return <KeybindCapture setting={setting} />;
case 'string':
diff --git a/desktop/src/engine/entitySources.ts b/desktop/src/engine/entitySources.ts
index caa8344ee..f070aa7cc 100644
--- a/desktop/src/engine/entitySources.ts
+++ b/desktop/src/engine/entitySources.ts
@@ -12,11 +12,12 @@
*/
import type { LucideIcon } from 'lucide-react';
import { CircleDot, LayoutPanelTop, ToggleLeft, SlidersHorizontal, List, ChevronDown, SquareMousePointer, RectangleHorizontal, Box, Type, Image as ImageIcon, SquareDashed, ScrollText, AppWindow, TextCursorInput } from 'lucide-react';
-import { BUILTIN_UI_PREFABS, BUILTIN_UI_WIDGET_NAMES, PREFAB_FORMAT_VERSION, getUserComponents, type PrefabData } from 'esengine';
+import { BUILTIN_UI_PREFABS, BUILTIN_UI_WIDGET_NAMES, PREFAB_FORMAT_VERSION, getUserComponents, applyThemeToWorld, type PrefabData } from 'esengine';
import type { EntityId } from '@/types';
import { componentByName, componentDefaults, prettyLabel, componentCategory } from './schema';
import { componentGlyph } from '@/components/icons';
import { SceneCommands } from './SceneCommands';
+import { EngineHost } from './EngineHost';
/** Where a source is created: the target parent + (for asset/drop sources) its origin. */
export interface CreateContext {
@@ -341,5 +342,12 @@ export async function createFromSource(source: EntitySource, ctx: CreateContext)
linkPrefabRef: source.linkPrefabRef?.(ctx),
});
if (id != null) source.afterCreate?.(ctx, id);
+ // Built-in widget prefabs bake the default dark palette; re-resolve the fresh
+ // ThemeStyle tags against the ACTIVE tokens so a themed project's palette drops
+ // don't flash dark (the active tokens were set by applyWidgetTheme at scene open).
+ if (id != null && source.placement === 'under-canvas') {
+ const world = EngineHost.mutableWorld();
+ if (world) applyThemeToWorld(world);
+ }
return id;
}
diff --git a/desktop/src/engine/playProtocol.ts b/desktop/src/engine/playProtocol.ts
index eb036fddf..cbca7694f 100644
--- a/desktop/src/engine/playProtocol.ts
+++ b/desktop/src/engine/playProtocol.ts
@@ -11,7 +11,7 @@
* import of an editor module here would break the realm bundle. Type-only
* imports are erased before resolution and are safe.
*/
-import type { SceneData, PhysicsPluginConfig, AudioProjectConfig } from 'esengine';
+import type { SceneData, PhysicsPluginConfig, AudioProjectConfig, ThemeOverrides } from 'esengine';
/**
* Editor↔realm message-contract version. The realm reports it in `hello`; the editor
@@ -61,6 +61,8 @@ export interface PlayPayload {
audioConfig?: AudioProjectConfig;
/** Project widget theme; absent = dark (the default). */
uiTheme?: 'light';
+ /** Project theme token overrides (partial re-skin over the base) — forwarded. */
+ uiThemeOverrides?: ThemeOverrides;
/** Bitmask of render layers (0..31) that y-sort within the layer — forwarded. */
ySortLayers?: number;
/** Project color space — 'linear' boots the realm on the linear-light pipeline. */
diff --git a/desktop/src/engine/widgetTheme.ts b/desktop/src/engine/widgetTheme.ts
new file mode 100644
index 000000000..4bd1ef17d
--- /dev/null
+++ b/desktop/src/engine/widgetTheme.ts
@@ -0,0 +1,19 @@
+// SPDX-License-Identifier: Apache-2.0
+// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team
+/**
+ * @file widgetTheme.ts — live widget-theme preview in the EDIT world. Re-resolves
+ * every ThemeStyle-tagged widget against the project's effective theme
+ * (base + token overrides), matching what a shipped runtime boots with —
+ * WYSIWYG for Project Settings → UI. Callers pass the project values so
+ * this module stays free of ProjectStore (no import cycle).
+ */
+import { switchTheme, resolveThemeTokens, type ThemeOverrides } from 'esengine';
+import { EngineHost } from './EngineHost';
+
+/** Apply the effective widget theme to the edit world (no-op before engine boot).
+ * Writes the world directly — theme resolution is a projection like scene load,
+ * not an undoable document edit. */
+export function applyWidgetTheme(theme: 'dark' | 'light', overrides?: ThemeOverrides): void {
+ const world = EngineHost.mutableWorld();
+ if (world) switchTheme(world, resolveThemeTokens(theme, overrides));
+}
diff --git a/desktop/src/gameHost.ts b/desktop/src/gameHost.ts
index 9e1206f81..c7b22ac48 100644
--- a/desktop/src/gameHost.ts
+++ b/desktop/src/gameHost.ts
@@ -11,7 +11,7 @@
* Builtin scenes run as-is; project custom-script bundles are a follow-up
* (shared with the play realm's import-map work).
*/
-import { createWebApp, setEditorMode, setPlayMode, initPlayRealmRuntime, atlasCatalogFields } from 'esengine';
+import { createWebApp, setEditorMode, setPlayMode, initPlayRealmRuntime, atlasCatalogFields, parseThemeOverrides } from 'esengine';
import type { CatalogData, CookedAtlasInfo, ESEngineModule, SceneData } from 'esengine';
interface GameConfig {
@@ -25,6 +25,10 @@ interface GameConfig {
/** Project camera fit (design resolution + scale mode) — letterboxes the main camera
* without a UI Canvas; absent = no fit. */
screenFit?: { designWidth: number; designHeight: number; scaleMode: number; matchWidthOrHeight: number };
+ /** Project widget theme; absent = dark. */
+ uiTheme?: 'light';
+ /** Project theme color overrides (role → #rrggbbaa hex). */
+ uiThemeColors?: Record<string, string>;
}
interface CookedManifest {
entries: { uuid: string; path: string; sourcePath?: string; type: string; atlas?: CookedAtlasInfo }[];
@@ -146,6 +150,8 @@ async function boot(): Promise<void> {
assetPathMap: pathMap,
catalogData: catalog,
wasmBaseUrl: wasmBase.replace(/\/$/, ''),
+ uiTheme: cfg.uiTheme,
+ uiThemeOverrides: parseThemeOverrides(cfg.uiThemeColors),
});
}
diff --git a/desktop/src/i18n/messages/settings.ts b/desktop/src/i18n/messages/settings.ts
index 2b059ac8f..af76a4bcc 100644
--- a/desktop/src/i18n/messages/settings.ts
+++ b/desktop/src/i18n/messages/settings.ts
@@ -45,6 +45,12 @@ export const settingsMessages = defineMessages({
},
'set.project.ui.theme.dark': { en: 'Dark', zh: '暗色' },
'set.project.ui.theme.light': { en: 'Light', zh: '亮色' },
+ 'set.group.uiThemeColors': { en: 'Theme Colors', zh: '主题颜色' },
+ 'set.project.ui.color.desc': {
+ en: 'Overrides this role for the whole project; unset inherits the base theme. The viewport and shipped builds resolve identically.',
+ zh: '为整个项目覆盖该颜色角色;不设置则继承基础主题。视口与导出成品解析一致。',
+ },
+ 'set.inherited': { en: 'inherited', zh: '继承' },
'set.section.packaging': { en: 'Packaging', zh: '打包' },
// — Group headers —
diff --git a/desktop/src/playHost.ts b/desktop/src/playHost.ts
index 779c38e1d..64148d6b3 100644
--- a/desktop/src/playHost.ts
+++ b/desktop/src/playHost.ts
@@ -212,6 +212,7 @@ async function buildAppAndRun(msg: InitMessage): Promise<void> {
physicsConfig: msg.physicsConfig,
audioConfig: msg.audioConfig,
uiTheme: msg.uiTheme,
+ uiThemeOverrides: msg.uiThemeOverrides,
enableStats: true, // editor profiler: per-phase / per-system frame timing
});
// Realm-local debug handle for automation/diagnostics (mirrors the headless
diff --git a/desktop/src/playableHost.ts b/desktop/src/playableHost.ts
index 8e6a9c65a..4ea489dba 100644
--- a/desktop/src/playableHost.ts
+++ b/desktop/src/playableHost.ts
@@ -9,7 +9,7 @@
* the SAME shipping runtime via initPlayableRuntime (play == ship). Nothing
* is fetched — the whole game is one self-contained .html (ad-network ready).
*/
-import { createWebApp, setEditorMode, setPlayMode, initPlayableRuntime, createEmbeddedSideModuleHost } from 'esengine';
+import { createWebApp, setEditorMode, setPlayMode, initPlayableRuntime, createEmbeddedSideModuleHost, parseThemeOverrides } from 'esengine';
import type { ESEngineModule as EngineModule, SceneData, EmbeddedSideModuleRegistry } from 'esengine';
type EngineFactory = (opts?: Record<string, unknown>) => Promise<EngineModule>;
@@ -28,6 +28,8 @@ declare const __GAME_FIRST__: string;
declare const __GAME_YSORT__: number;
declare const __GAME_COLORSPACE__: 'gamma' | 'linear';
declare const __GAME_SCREENFIT__: { designWidth: number; designHeight: number; scaleMode: number; matchWidthOrHeight: number };
+declare const __GAME_UITHEME__: 'light';
+declare const __GAME_UITHEMECOLORS__: Record<string, string>;
function decodeBase64(b64: string): Uint8Array {
const raw = atob(b64);
@@ -97,6 +99,9 @@ async function boot(): Promise<void> {
firstScene: __GAME_FIRST__,
// Older exports predate y-sort; treat the global as optional.
ySortLayers: typeof __GAME_YSORT__ !== 'undefined' ? __GAME_YSORT__ : undefined,
+ // Project widget theme + token overrides; optional like the rest.
+ uiTheme: typeof __GAME_UITHEME__ !== 'undefined' ? __GAME_UITHEME__ : undefined,
+ uiThemeOverrides: parseThemeOverrides(typeof __GAME_UITHEMECOLORS__ !== 'undefined' ? __GAME_UITHEMECOLORS__ : undefined),
});
}
diff --git a/desktop/src/project/ProjectStore.ts b/desktop/src/project/ProjectStore.ts
index 9eb4736a2..afd5fa5df 100644
--- a/desktop/src/project/ProjectStore.ts
+++ b/desktop/src/project/ProjectStore.ts
@@ -1,10 +1,11 @@
// SPDX-License-Identifier: Apache-2.0
// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team
import { createStore } from 'zustand/vanilla';
-import { getComponent, getEditorType, Assets, migratePrefabData, extractPrefab, diffAgainstSource, applyOverridesToSource, setTextureParams, TextureFilter, TextureWrap, Renderer, RETIRED_COMPONENT_TYPES } from 'esengine';
+import { getComponent, getEditorType, Assets, migratePrefabData, extractPrefab, diffAgainstSource, applyOverridesToSource, setTextureParams, TextureFilter, TextureWrap, Renderer, RETIRED_COMPONENT_TYPES, parseThemeOverrides } from 'esengine';
import { readTextureImportSettings } from './assetImporter';
-import type { SceneData, PrefabData, ExtractEntity, ProcessedEntity, PhysicsPluginConfig, AudioProjectConfig, AssetsData } from 'esengine';
+import type { SceneData, PrefabData, ExtractEntity, ProcessedEntity, PhysicsPluginConfig, AudioProjectConfig, AssetsData, ThemeOverrides } from 'esengine';
import { EngineHost } from '@/engine/EngineHost';
+import { applyWidgetTheme } from '@/engine/widgetTheme';
import { bootProfiler } from '@/engine/bootProfiler';
import { SceneModel } from '@/engine/SceneModel';
import { Reconciler } from '@/engine/Reconciler';
@@ -444,6 +445,9 @@ class ProjectStoreImpl {
for (const { id, tag } of tags) SceneModel.setPrefabTag(id, tag);
EngineHost.syncEditorViewToScene();
+ // Edit-world live theme: re-resolve ThemeStyle-tagged widgets against the
+ // project's effective theme, matching what a shipped runtime boots with.
+ applyWidgetTheme(this.uiTheme(), this.uiThemeOverrides());
this.store.setState({ project: { ...st, currentScene: rel } });
this.knownSceneText = text;
this.knownScenePath = rel;
@@ -1066,6 +1070,7 @@ class ProjectStoreImpl {
physicsConfig?: PhysicsPluginConfig;
audioConfig?: AudioProjectConfig;
uiTheme?: 'light';
+ uiThemeOverrides?: ThemeOverrides;
ySortLayers?: number;
colorSpace?: 'gamma' | 'linear';
screenFit?: { designWidth: number; designHeight: number; scaleMode: number; matchWidthOrHeight: number };
@@ -1103,10 +1108,12 @@ class ProjectStoreImpl {
// scene with no fit boots exactly as before.
const screenFit = this.screenFit();
const uiTheme = this.uiTheme();
+ const uiThemeOverrides = this.uiThemeOverrides();
return {
sceneData, assetManifest, physicsEnabled: f.enabled, physicsConfig,
...(audioConfig.buses ? { audioConfig } : {}),
...(uiTheme === 'light' ? { uiTheme } : {}),
+ ...(uiThemeOverrides ? { uiThemeOverrides } : {}),
...(ySortLayers !== 0 ? { ySortLayers } : {}),
...(colorSpace === 'linear' ? { colorSpace } : {}),
...(screenFit.scaleMode >= 0 ? { screenFit } : {}),
@@ -1123,15 +1130,51 @@ class ProjectStoreImpl {
return this.state?.features?.ui?.theme === 'light' ? 'light' : 'dark';
}
- /** Persist the widget theme; dark (the default) is expressed by absence. */
+ /** The project's theme color overrides (role → #rrggbbaa hex), possibly empty. */
+ uiThemeColors(): Record<string, string> {
+ return this.state?.features?.ui?.colors ?? {};
+ }
+
+ /** The color overrides as SDK {@link ThemeOverrides} (hex → 0..1 Color), or
+ * undefined when the project overrides nothing — the payload/boot shape. */
+ uiThemeOverrides(): ThemeOverrides | undefined {
+ return parseThemeOverrides(this.uiThemeColors());
+ }
+
+ /** Persist the widget theme; dark (the default) is expressed by absence.
+ * Color overrides survive a base-theme switch (they re-skin either base). */
async setUiTheme(theme: 'dark' | 'light'): Promise<void> {
+ await this.patchUiFeature_({ theme: theme === 'light' ? 'light' : undefined });
+ }
+
+ /** Set or clear one theme color override (`#rrggbbaa`; null clears the role). */
+ async setUiThemeColor(role: string, hex: string | null): Promise<void> {
+ const colors = { ...this.uiThemeColors() };
+ if (hex) colors[role] = hex.toLowerCase();
+ else delete colors[role];
+ await this.patchUiFeature_({ colors: Object.keys(colors).length > 0 ? colors : undefined });
+ }
+
+ /** Merge a patch into `features.ui` and persist — a key set to undefined is
+ * removed, and an empty `ui` disappears entirely (dark + no overrides). */
+ private async patchUiFeature_(patch: { theme?: 'light'; colors?: Record<string, string> }): Promise<void> {
const st = this.state;
if (!st) return;
- const ui = theme === 'light' ? { theme } : undefined;
+ const cur: { theme?: 'light'; colors?: Record<string, string> } = { ...(st.features?.ui ?? {}) };
+ if ('theme' in patch) {
+ if (patch.theme) cur.theme = patch.theme;
+ else delete cur.theme;
+ }
+ if ('colors' in patch) {
+ if (patch.colors) cur.colors = patch.colors;
+ else delete cur.colors;
+ }
+ const ui = Object.keys(cur).length > 0 ? cur : undefined;
const features: ProjectFeatures = { ...st.features };
if (ui) features.ui = ui;
else delete features.ui;
this.store.setState({ project: { ...st, features } });
+ applyWidgetTheme(this.uiTheme(), this.uiThemeOverrides());
try {
const raw = JSON.parse(await window.estella.fs.read(PROJECT_MANIFEST_FILE)) as Record<string, unknown>;
const rf = { ...(raw.features as Record<string, unknown> ?? {}) };
@@ -1141,7 +1184,7 @@ class ProjectStoreImpl {
await window.estella.fs.write(PROJECT_MANIFEST_FILE, JSON.stringify(raw, null, 2) + '\n');
} catch (e) {
Toasts.push(t('proj.saveUiThemeFailed'), 'error');
- console.error('[project] setUiTheme write failed', e);
+ console.error('[project] patchUiFeature write failed', e);
}
}
diff --git a/desktop/src/project/format.ts b/desktop/src/project/format.ts
index f7600a295..b94ee0af8 100644
--- a/desktop/src/project/format.ts
+++ b/desktop/src/project/format.ts
@@ -18,7 +18,7 @@
* into workspace.json.
*/
-import { parseAudioProjectConfig, type AudioProjectConfig } from 'esengine';
+import { parseAudioProjectConfig, THEME_COLOR_ROLES, type AudioProjectConfig } from 'esengine';
export const PROJECT_FORMAT_VERSION = '1';
export const PROJECT_MANIFEST_FILE = 'project.esproject';
@@ -105,6 +105,9 @@ export interface ProjectFeatures {
/** Built-in widget theme. Only 'light' persists; dark (the default) is
* expressed by absence — like rendering.colorSpace. */
theme?: 'light';
+ /** Partial re-skin over the base theme: color role → #rrggbbaa hex. Only
+ * known roles with valid hex persist; absence means "inherit the base". */
+ colors?: Record<string, string>;
};
}
@@ -329,7 +332,17 @@ export function parseManifest(raw: unknown): ProjectManifest {
}
if (f.ui && typeof f.ui === 'object') {
const u = f.ui as Record<string, unknown>;
- if (u.theme === 'light') features.ui = { theme: 'light' };
+ const ui: NonNullable<ProjectFeatures['ui']> = {};
+ if (u.theme === 'light') ui.theme = 'light';
+ if (u.colors && typeof u.colors === 'object') {
+ const colors: Record<string, string> = {};
+ for (const role of THEME_COLOR_ROLES) {
+ const v = (u.colors as Record<string, unknown>)[role];
+ if (typeof v === 'string' && /^#[0-9a-f]{6}(?:[0-9a-f]{2})?$/i.test(v)) colors[role] = v.toLowerCase();
+ }
+ if (Object.keys(colors).length > 0) ui.colors = colors;
+ }
+ if (Object.keys(ui).length > 0) features.ui = ui;
}
if (Object.keys(features).length > 0) manifest.features = features;
}
diff --git a/desktop/src/settings/projectSettings.ts b/desktop/src/settings/projectSettings.ts
index 953278178..ad41054ca 100644
--- a/desktop/src/settings/projectSettings.ts
+++ b/desktop/src/settings/projectSettings.ts
@@ -7,8 +7,10 @@
* them under the "Project" category with no UI change. Bound to
* ProjectStore, which owns manifest read/write.
*/
+import { resolveThemeTokens, THEME_COLOR_ROLES } from 'esengine';
import { settingsRegistry } from './registry';
import { ProjectStore } from '@/project/ProjectStore';
+import { rgbaToHex8 } from '@/components/ColorControl';
import { EngineHost } from '@/engine/EngineHost';
import { Toasts } from '@/store/Toasts';
import { useEditorMode } from '@/store/editorModeStore';
@@ -258,6 +260,32 @@ settingsRegistry.register({
},
});
+// Per-role token overrides — one picker per semantic color. Unset (the default)
+// inherits the base theme's value, shown as the picker's placeholder; the row's
+// standard reset affordance clears the override. Live-applied to the edit world
+// by ProjectStore.patchUiFeature_ → applyWidgetTheme.
+const roleLabel = (role: string): string => role.replace(/([A-Z])/g, ' $1').replace(/^./, (c) => c.toUpperCase());
+for (const role of THEME_COLOR_ROLES) {
+ settingsRegistry.register({
+ id: `project.ui.color.${role}`,
+ type: 'colorpicker',
+ scope: 'project',
+ section: 'ui',
+ group: t('set.group.uiThemeColors'),
+ label: roleLabel(role),
+ ...(role === 'surface' ? { description: t('set.project.ui.color.desc') } : {}),
+ default: '',
+ placeholderColor: () => {
+ const c = resolveThemeTokens(ProjectStore.uiTheme()).colors[role];
+ return rgbaToHex8(c.r, c.g, c.b, c.a);
+ },
+ bind: {
+ get: () => ProjectStore.uiThemeColors()[role] ?? '',
+ set: (v) => { void ProjectStore.setUiThemeColor(role, v || null); },
+ },
+ });
+}
+
settingsRegistry.registerSection({ id: 'packaging', label: t('set.section.packaging'), category: 'project', order: 4 });
settingsRegistry.register({
diff --git a/desktop/src/settings/types.ts b/desktop/src/settings/types.ts
index 8094da8d9..a51ce0af8 100644
--- a/desktop/src/settings/types.ts
+++ b/desktop/src/settings/types.ts
@@ -76,6 +76,15 @@ export interface ColorSetting extends BaseSetting<string> {
swatches: string[];
}
+/** A full HSV/alpha color picker (ColorControl), value `#rrggbbaa`. An empty
+ * string means "unset" — the control shows {@link placeholderColor} (e.g. the
+ * inherited base value) and the standard reset affordance clears the override. */
+export interface ColorPickerSetting extends BaseSetting<string> {
+ type: 'colorpicker';
+ /** The effective color shown while unset, read at render time. */
+ placeholderColor?: () => string;
+}
+
/** Read-only display of a command's keybinding (editing is a later feature). */
export interface KeybindingSetting extends BaseSetting<string> {
type: 'keybinding';
@@ -118,6 +127,7 @@ export type Setting =
| EnumSetting
| StringSetting
| ColorSetting
+ | ColorPickerSetting
| KeybindingSetting
| StringListSetting
| MatrixSetting
diff --git a/desktop/src/theme/settings.css b/desktop/src/theme/settings.css
index c9c982c66..5a308489c 100644
--- a/desktop/src/theme/settings.css
+++ b/desktop/src/theme/settings.css
@@ -198,6 +198,10 @@
transition: box-shadow var(--t-fast);
}
.set-swatch.on { box-shadow: 0 0 0 2px var(--srf-2), 0 0 0 4px var(--acc); }
+/* Full color picker row (theme token overrides): picker + "inherited" tag while unset. */
+.set-colorpicker { display: flex; align-items: center; gap: 8px; }
+.set-colorpicker.inherited { opacity: 0.75; }
+.set-inherit { font-size: var(--fs-2xs); color: var(--text-faint); }
/* The pill toggle is the shared `.toggle` primitive (controls.css). */
diff --git a/desktop/tests/export-playable.test.ts b/desktop/tests/export-playable.test.ts
index 721e6df77..65c29e02a 100644
--- a/desktop/tests/export-playable.test.ts
+++ b/desktop/tests/export-playable.test.ts
@@ -42,7 +42,7 @@ beforeAll(() => {
// Stub SDK dist exporting what the real host + scripts import (bundles for real).
mkdirSync(path.join(root, '_sdk'), { recursive: true });
writeFileSync(path.join(root, '_sdk', 'index.js'),
- `export function createWebApp(){return{GL:{registerContext(){}}};}\nexport function setEditorMode(){}\nexport function setPlayMode(){}\nexport function initPlayableRuntime(){return Promise.resolve();}\nexport function createEmbeddedSideModuleHost(){return{acquire(){return Promise.resolve(null);}};}\nexport function defineComponent(){}\n`);
+ `export function createWebApp(){return{GL:{registerContext(){}}};}\nexport function setEditorMode(){}\nexport function setPlayMode(){}\nexport function initPlayableRuntime(){return Promise.resolve();}\nexport function createEmbeddedSideModuleHost(){return{acquire(){return Promise.resolve(null);}};}\nexport function defineComponent(){}\nexport function parseThemeOverrides(){}\n`);
// Stub web wasm runtime (glue text + wasm) — playable inlines these, no separate build.
mkdirSync(path.join(root, '_wasm'), { recursive: true });
writeFileSync(path.join(root, '_wasm', 'esengine.js'), `export default function(){}/*WEB_GLUE*/\n`);
@@ -147,7 +147,7 @@ describe('exportGame (playable) — side-module embedding', () => {
writeFileSync(path.join(r, 'scenes', 'main.esscene.meta'), meta(PSCN, 'scene'));
mkdirSync(path.join(r, '_sdk'), { recursive: true });
writeFileSync(path.join(r, '_sdk', 'index.js'),
- `export function createWebApp(){return{GL:{registerContext(){}}};}\nexport function setEditorMode(){}\nexport function setPlayMode(){}\nexport function initPlayableRuntime(){return Promise.resolve();}\nexport function createEmbeddedSideModuleHost(){return{acquire(){return Promise.resolve(null);}};}\n`);
+ `export function createWebApp(){return{GL:{registerContext(){}}};}\nexport function setEditorMode(){}\nexport function setPlayMode(){}\nexport function initPlayableRuntime(){return Promise.resolve();}\nexport function createEmbeddedSideModuleHost(){return{acquire(){return Promise.resolve(null);}};}\nexport function parseThemeOverrides(){}\n`);
mkdirSync(path.join(r, '_wasm'), { recursive: true });
writeFileSync(path.join(r, '_wasm', 'esengine.js'), `export default function(){}\n`);
writeFileSync(path.join(r, '_wasm', 'esengine.wasm'), 'WASMBYTES');
@@ -221,7 +221,7 @@ describe('exportGame (playable) — spine embedding', () => {
writeFileSync(path.join(r, 'scenes', 'main.esscene.meta'), meta(SSCN, 'scene'));
mkdirSync(path.join(r, '_sdk'), { recursive: true });
writeFileSync(path.join(r, '_sdk', 'index.js'),
- `export function createWebApp(){return{GL:{registerContext(){}}};}\nexport function setEditorMode(){}\nexport function setPlayMode(){}\nexport function initPlayableRuntime(){return Promise.resolve();}\nexport function createEmbeddedSideModuleHost(){return{acquire(){return Promise.resolve(null);}};}\n`);
+ `export function createWebApp(){return{GL:{registerContext(){}}};}\nexport function setEditorMode(){}\nexport function setPlayMode(){}\nexport function initPlayableRuntime(){return Promise.resolve();}\nexport function createEmbeddedSideModuleHost(){return{acquire(){return Promise.resolve(null);}};}\nexport function parseThemeOverrides(){}\n`);
mkdirSync(path.join(r, '_wasm'), { recursive: true });
writeFileSync(path.join(r, '_wasm', 'esengine.js'), `export default function(){}\n`);
writeFileSync(path.join(r, '_wasm', 'esengine.wasm'), 'WASMBYTES');
diff --git a/desktop/tests/project-ui-theme.test.ts b/desktop/tests/project-ui-theme.test.ts
new file mode 100644
index 000000000..41aae0e01
--- /dev/null
+++ b/desktop/tests/project-ui-theme.test.ts
@@ -0,0 +1,44 @@
+// SPDX-License-Identifier: Apache-2.0
+// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team
+/**
+ * @file parseManifest — ui feature (Project Settings → UI). Guards the widget
+ * theme + per-role color overrides: 'light' persists (dark = absence),
+ * overrides keep only known roles with valid hex, and an empty ui block
+ * disappears entirely.
+ */
+import { describe, it, expect } from 'vitest';
+import { parseManifest } from '../src/project/format';
+
+describe('parseManifest — features.ui', () => {
+ it("keeps theme 'light'; dark/junk = absence", () => {
+ expect(parseManifest({ name: 'X', features: { ui: { theme: 'light' } } }).features?.ui?.theme).toBe('light');
+ for (const v of ['dark', 'LIGHT', 42, null]) {
+ expect(parseManifest({ name: 'X', features: { ui: { theme: v } } }).features?.ui).toBeUndefined();
+ }
+ });
+
+ it('keeps only known roles with valid hex (lowercased), drops the rest', () => {
+ const m = parseManifest({
+ name: 'X',
+ features: {
+ ui: {
+ colors: {
+ primary: '#FF0000',
+ backdrop: '#00000080',
+ surface: 'red',
+ notARole: '#00ff00',
+ control: 42,
+ },
+ },
+ },
+ });
+ expect(m.features?.ui?.colors).toEqual({ primary: '#ff0000', backdrop: '#00000080' });
+ });
+
+ it('colors coexist with a light base; all-junk colors vanish', () => {
+ const m = parseManifest({ name: 'X', features: { ui: { theme: 'light', colors: { primary: '#123456' } } } });
+ expect(m.features?.ui).toEqual({ theme: 'light', colors: { primary: '#123456' } });
+ const m2 = parseManifest({ name: 'X', features: { ui: { colors: { nope: 'junk' } } } });
+ expect(m2.features?.ui).toBeUndefined();
+ });
+});
diff --git a/sdk/etc/index.api.md b/sdk/etc/index.api.md
index ed614ac4a..998482c78 100644
--- a/sdk/etc/index.api.md
+++ b/sdk/etc/index.api.md
@@ -1,7 +1,7 @@
# API surface — esengine/index
<!-- Generated by tools/api-surface.mjs — do not edit. Run --update to accept changes. -->
-Symbols: 1243 stable · 17 beta · 1 deprecated
+Symbols: 1247 stable · 17 beta · 1 deprecated
## ABI_LAYOUT_HASH — const
```
@@ -3352,6 +3352,7 @@ source: RuntimeAssetSource
spineManager: SpineManager | null | undefined
spineModule: SpineWasmModule | null | undefined
uiTheme: "dark" | "light" | undefined
+uiThemeOverrides: ThemeOverrides | undefined
```
## LoadedTilemapLayer — interface
@@ -4400,6 +4401,7 @@ physicsConfig: PhysicsPluginConfig | undefined
physicsEnabled: boolean | undefined
sceneData: SceneData
uiTheme: "dark" | "light" | undefined
+uiThemeOverrides: ThemeOverrides | undefined
wasmBaseUrl: string | undefined
```
@@ -4416,6 +4418,7 @@ module: ESEngineModule
physicsConfig: { gravity?: Vec2; fixedTimestep?: number; subStepCount?: number; } | undefined
scenes: { name: string; data: SceneData; }[]
uiTheme: "dark" | "light" | undefined
+uiThemeOverrides: ThemeOverrides | undefined
ySortLayers: number | undefined
```
@@ -5150,6 +5153,7 @@ source: RuntimeAssetSource
spineManager: SpineManager | null | undefined
spineModule: SpineWasmModule | null | undefined
uiTheme: "dark" | "light" | undefined
+uiThemeOverrides: ThemeOverrides | undefined
```
## RuntimeOnly — const
@@ -6071,6 +6075,11 @@ static prototype: SystemRunner
readonly { dx: number; dy: number; bit: number; }[]
```
+## THEME_COLOR_ROLES — const
+```
+readonly (keyof ThemeColors)[]
+```
+
## TILESET_FORMAT_VERSION — const
```
"1"
@@ -6347,6 +6356,12 @@ text: Color
track: Color
```
+## ThemeOverrides — interface
+```
+colors: Partial<ThemeColors> | undefined
+type: Partial<ThemeType> | undefined
+```
+
## ThemeStyle — const
```
ComponentDef<ThemeStyleData>
@@ -8875,6 +8890,11 @@ NavPlugin
(input: string): RichTextRun[]
```
+## parseThemeOverrides — function
+```
+(colors?: Record<string, string>): ThemeOverrides | undefined
+```
+
## parseTileset — function
```
(raw: any): TilesetAsset
@@ -9155,6 +9175,11 @@ ReplicationPlugin
(basePath: string, relativePath: string): string
```
+## resolveThemeTokens — function
+```
+(base: "dark" | "light", overrides?: ThemeOverrides): ThemeTokens
+```
+
## resolveTilesetModel — function
```
(tilesets: ResolvedTileset[]): TilesetModel
diff --git a/sdk/etc/index.node.api.md b/sdk/etc/index.node.api.md
index a01b5febc..51a71aa4a 100644
--- a/sdk/etc/index.node.api.md
+++ b/sdk/etc/index.node.api.md
@@ -1,7 +1,7 @@
# API surface — esengine/index.node
<!-- Generated by tools/api-surface.mjs — do not edit. Run --update to accept changes. -->
-Symbols: 1242 stable · 19 beta · 1 deprecated
+Symbols: 1246 stable · 19 beta · 1 deprecated
## ANCHOR_AXES — const
```
@@ -3347,6 +3347,7 @@ source: RuntimeAssetSource
spineManager: SpineManager | null | undefined
spineModule: SpineWasmModule | null | undefined
uiTheme: "dark" | "light" | undefined
+uiThemeOverrides: ThemeOverrides | undefined
```
## LoadedTilemapLayer — interface
@@ -4395,6 +4396,7 @@ physicsConfig: PhysicsPluginConfig | undefined
physicsEnabled: boolean | undefined
sceneData: SceneData
uiTheme: "dark" | "light" | undefined
+uiThemeOverrides: ThemeOverrides | undefined
wasmBaseUrl: string | undefined
```
@@ -4411,6 +4413,7 @@ module: ESEngineModule
physicsConfig: { gravity?: Vec2; fixedTimestep?: number; subStepCount?: number; } | undefined
scenes: { name: string; data: SceneData; }[]
uiTheme: "dark" | "light" | undefined
+uiThemeOverrides: ThemeOverrides | undefined
ySortLayers: number | undefined
```
@@ -5145,6 +5148,7 @@ source: RuntimeAssetSource
spineManager: SpineManager | null | undefined
spineModule: SpineWasmModule | null | undefined
uiTheme: "dark" | "light" | undefined
+uiThemeOverrides: ThemeOverrides | undefined
```
## RuntimeOnly — const
@@ -6066,6 +6070,11 @@ static prototype: SystemRunner
readonly { dx: number; dy: number; bit: number; }[]
```
+## THEME_COLOR_ROLES — const
+```
+readonly (keyof ThemeColors)[]
+```
+
## TILESET_FORMAT_VERSION — const
```
"1"
@@ -6342,6 +6351,12 @@ text: Color
track: Color
```
+## ThemeOverrides — interface
+```
+colors: Partial<ThemeColors> | undefined
+type: Partial<ThemeType> | undefined
+```
+
## ThemeStyle — const
```
ComponentDef<ThemeStyleData>
@@ -8880,6 +8895,11 @@ NodePlatformAdapter
(input: string): RichTextRun[]
```
+## parseThemeOverrides — function
+```
+(colors?: Record<string, string>): ThemeOverrides | undefined
+```
+
## parseTileset — function
```
(raw: any): TilesetAsset
@@ -9160,6 +9180,11 @@ ReplicationPlugin
(basePath: string, relativePath: string): string
```
+## resolveThemeTokens — function
+```
+(base: "dark" | "light", overrides?: ThemeOverrides): ThemeTokens
+```
+
## resolveTilesetModel — function
```
(tilesets: ResolvedTileset[]): TilesetModel
diff --git a/sdk/src/core-ui.ts b/sdk/src/core-ui.ts
index 5ba61094f..2d233b9f2 100644
--- a/sdk/src/core-ui.ts
+++ b/sdk/src/core-ui.ts
@@ -84,9 +84,13 @@ export {
setTheme,
themeColors,
themeType,
+ resolveThemeTokens,
+ parseThemeOverrides,
+ THEME_COLOR_ROLES,
type ThemeTokens,
type ThemeColors,
type ThemeType,
+ type ThemeOverrides,
// Live re-theming
ThemeStyle,
markThemed,
diff --git a/sdk/src/playRealmRuntime.ts b/sdk/src/playRealmRuntime.ts
index c193ccd55..d4ce9f308 100644
--- a/sdk/src/playRealmRuntime.ts
+++ b/sdk/src/playRealmRuntime.ts
@@ -20,6 +20,7 @@ import type { ESEngineModule } from './wasm';
import { Audio } from './audio/Audio';
import { VideoPlayer } from './video/VideoAPI';
import { initRuntime } from './runtimeLoader';
+import type { ThemeOverrides } from './ui';
import type { RuntimeAssetSource } from './runtimeAssets';
import { HttpBackend } from './asset/Backend';
import { Catalog, type CatalogData } from './asset/Catalog';
@@ -75,6 +76,8 @@ export interface PlayRealmRuntimeConfig {
physicsConfig?: PhysicsPluginConfig;
/** Project-declared UI theme; 'light' re-skins ThemeStyle-tagged widgets at boot. */
uiTheme?: 'dark' | 'light';
+ /** Project-declared theme token overrides (partial re-skin over the base). */
+ uiThemeOverrides?: ThemeOverrides;
/** Project-declared mixer state (bus volumes / effects / duck rules). */
audioConfig?: AudioProjectConfig;
/** Turn on per-phase / per-system frame timing (editor profiler; off in shipped games). */
@@ -185,6 +188,7 @@ export async function initPlayRealmRuntime(config: PlayRealmRuntimeConfig): Prom
physicsEnabled: config.physicsEnabled,
physicsConfig: config.physicsConfig,
uiTheme: config.uiTheme,
+ uiThemeOverrides: config.uiThemeOverrides,
audioConfig: config.audioConfig,
// Physics (and spine) are acquired from app.sideModules — the fetch host
// createWebApp built from this realm's wasmBaseUrl.
diff --git a/sdk/src/playableRuntime.ts b/sdk/src/playableRuntime.ts
index 681dbaa37..e233c215d 100644
--- a/sdk/src/playableRuntime.ts
+++ b/sdk/src/playableRuntime.ts
@@ -14,6 +14,7 @@ import type { App } from './app';
import type { ESEngineModule } from './wasm';
import type { AudioProjectConfig } from './audio/AudioProjectConfig';
import { initRuntime } from './runtimeLoader';
+import type { ThemeOverrides } from './ui';
import type { RuntimeAssetSource } from './runtimeAssets';
import { EmbeddedBackend } from './asset/Backend';
import type { AddressableManifest } from './asset/AddressableManifest';
@@ -40,6 +41,8 @@ export interface PlayableRuntimeConfig {
physicsConfig?: { gravity?: Vec2; fixedTimestep?: number; subStepCount?: number };
/** Project-declared UI theme; 'light' re-skins ThemeStyle-tagged widgets at boot. */
uiTheme?: 'dark' | 'light';
+ /** Project-declared theme token overrides (partial re-skin over the base). */
+ uiThemeOverrides?: ThemeOverrides;
/** Project-declared mixer state (bus volumes / effects / duck rules). */
audioConfig?: AudioProjectConfig;
/** Bitmask of render layers (0..31) that y-sort within the layer (Project Settings → Rendering). */
@@ -135,6 +138,7 @@ export async function initPlayableRuntime(config: PlayableRuntimeConfig): Promis
firstScene,
physicsConfig: config.physicsConfig,
uiTheme: config.uiTheme,
+ uiThemeOverrides: config.uiThemeOverrides,
audioConfig: config.audioConfig,
aspectRatio: config.canvas.width / config.canvas.height,
});
diff --git a/sdk/src/runtimeLoader.ts b/sdk/src/runtimeLoader.ts
index b9ac20ef5..4f8c4fbb2 100644
--- a/sdk/src/runtimeLoader.ts
+++ b/sdk/src/runtimeLoader.ts
@@ -7,7 +7,7 @@
import { SceneOwner } from './component';
import { loadSceneData, updateCameraAspectRatio, type SceneData } from './scene';
-import { switchTheme, LIGHT_TOKENS } from './ui';
+import { switchTheme, resolveThemeTokens, type ThemeOverrides } from './ui';
import { discoverSceneAssets } from './asset/discoverAssets';
import type { ESEngineModule } from './wasm';
import type { SpineWasmModule } from './spine/SpineModuleLoader';
@@ -180,6 +180,9 @@ export interface LoadRuntimeSceneOptions {
* 'light' switches the token set AND re-resolves already-instantiated
* ThemeStyle-tagged widgets (prefab instances carry dark baked values). */
uiTheme?: 'dark' | 'light';
+ /** Project-declared partial re-skin over the base theme (Project Settings →
+ * UI theme colors); merged via {@link resolveThemeTokens}. */
+ uiThemeOverrides?: ThemeOverrides;
sceneName?: string;
}
@@ -224,7 +227,7 @@ export function sceneUsesPhysics(sceneData: SceneData): boolean {
}
export async function loadRuntimeScene(options: LoadRuntimeSceneOptions): Promise<void> {
- const { app, module, sceneData, source, physicsConfig, physicsEnabled, uiTheme, sceneName } = options;
+ const { app, module, sceneData, source, physicsConfig, physicsEnabled, uiTheme, uiThemeOverrides, sceneName } = options;
// The SpineManager is owned by SpinePlugin (built from the realm's
// app.sideModules host); read it from there so every realm — play / playable /
@@ -332,8 +335,11 @@ export async function loadRuntimeScene(options: LoadRuntimeSceneOptions): Promis
const entityMap = loadSceneData(app.world, sceneData);
// Apply the project theme over the freshly instantiated scene: prefabs bake
- // the dark palette, so a light project re-resolves every ThemeStyle tag.
- if (uiTheme === 'light') switchTheme(app.world, LIGHT_TOKENS);
+ // the default dark palette, so a light base or any token override re-resolves
+ // every ThemeStyle tag.
+ if (uiTheme === 'light' || uiThemeOverrides) {
+ switchTheme(app.world, resolveThemeTokens(uiTheme ?? 'dark', uiThemeOverrides));
+ }
const cppRegistry = app.world.getCppRegistry();
if (cppRegistry) {
@@ -410,6 +416,8 @@ export interface RuntimeInitConfig {
audioConfig?: AudioProjectConfig;
/** Project-declared UI theme; see {@link LoadRuntimeSceneOptions.uiTheme}. */
uiTheme?: 'dark' | 'light';
+ /** Project-declared theme token overrides; see {@link LoadRuntimeSceneOptions.uiThemeOverrides}. */
+ uiThemeOverrides?: ThemeOverrides;
aspectRatio?: number;
}
@@ -439,6 +447,7 @@ export async function initRuntime(config: RuntimeInitConfig): Promise<void> {
physicsConfig: config.physicsConfig,
physicsEnabled: config.physicsEnabled,
uiTheme: config.uiTheme,
+ uiThemeOverrides: config.uiThemeOverrides,
};
const mgr = app.getResource(SceneManager);
diff --git a/sdk/src/ui/index.ts b/sdk/src/ui/index.ts
index db083ead2..3739a8b66 100644
--- a/sdk/src/ui/index.ts
+++ b/sdk/src/ui/index.ts
@@ -387,9 +387,13 @@ export {
setTheme,
themeColors,
themeType,
+ resolveThemeTokens,
+ parseThemeOverrides,
+ THEME_COLOR_ROLES,
type ThemeTokens,
type ThemeColors,
type ThemeType,
+ type ThemeOverrides,
} from './theme/tokens';
export {
diff --git a/sdk/src/ui/theme/tokens.ts b/sdk/src/ui/theme/tokens.ts
index 38020e181..f61fff68d 100644
--- a/sdk/src/ui/theme/tokens.ts
+++ b/sdk/src/ui/theme/tokens.ts
@@ -37,6 +37,13 @@ export interface ThemeColors {
backdrop: Color;
}
+/** Every color role, in display order — THE list a theme editor or a project
+ * format validator iterates (keyof ThemeColors, as a runtime value). */
+export const THEME_COLOR_ROLES: readonly (keyof ThemeColors)[] = [
+ 'surface', 'surfaceElevated', 'control', 'controlHover', 'controlActive',
+ 'track', 'primary', 'primaryHover', 'primaryActive', 'onPrimary', 'text', 'backdrop',
+];
+
/** Typographic scale (font sizes in px) consumed by widget text. */
export interface ThemeType {
/** Control / label text (buttons, options). */
@@ -93,6 +100,53 @@ export const LIGHT_TOKENS: ThemeTokens = {
type: TYPE_SCALE,
};
+/** A project's partial re-skin over a base theme: any subset of color roles
+ * and type-scale steps. Absent keys inherit from the base. */
+export interface ThemeOverrides {
+ colors?: Partial<ThemeColors>;
+ type?: Partial<ThemeType>;
+}
+
+/**
+ * Parse a JSON-transportable color override map (role → `#rrggbb[aa]` hex — the
+ * shape project manifests and shipped game configs carry) into {@link ThemeOverrides}.
+ * Unknown roles and malformed hex are dropped; undefined when nothing valid remains.
+ * The ONE config→overrides converter shared by the editor and every shipped host.
+ */
+export function parseThemeOverrides(colors?: Record<string, string>): ThemeOverrides | undefined {
+ if (!colors) return undefined;
+ const out: Partial<ThemeColors> = {};
+ let any = false;
+ for (const role of THEME_COLOR_ROLES) {
+ const hex = colors[role];
+ const m = typeof hex === 'string' ? /^#([0-9a-f]{6})([0-9a-f]{2})?$/i.exec(hex.trim()) : null;
+ if (!m) continue;
+ const n = parseInt(m[1]!, 16);
+ out[role] = {
+ r: ((n >> 16) & 255) / 255,
+ g: ((n >> 8) & 255) / 255,
+ b: (n & 255) / 255,
+ a: m[2] ? parseInt(m[2], 16) / 255 : 1,
+ };
+ any = true;
+ }
+ return any ? { colors: out } : undefined;
+}
+
+/**
+ * The effective tokens for a base theme name plus a project's partial overrides —
+ * the ONE merge every runtime and the editor resolve through, so a project that
+ * overrides `primary` alone re-tints the accent while inheriting the rest.
+ */
+export function resolveThemeTokens(base: 'dark' | 'light', overrides?: ThemeOverrides): ThemeTokens {
+ const baseTokens = base === 'light' ? LIGHT_TOKENS : DARK_TOKENS;
+ if (!overrides || (!overrides.colors && !overrides.type)) return baseTokens;
+ return {
+ colors: { ...baseTokens.colors, ...overrides.colors },
+ type: { ...baseTokens.type, ...overrides.type },
+ };
+}
+
let activeTheme: ThemeTokens = DARK_TOKENS;
/** The active design tokens widgets resolve their defaults from. */
diff --git a/sdk/src/wechatRuntime.ts b/sdk/src/wechatRuntime.ts
index 7c895c7e9..93cafec2c 100644
--- a/sdk/src/wechatRuntime.ts
+++ b/sdk/src/wechatRuntime.ts
@@ -11,6 +11,7 @@ import { createWebApp } from './webAppFactory';
import type { ESEngineModule } from './wasm';
import type { AudioProjectConfig } from './audio/AudioProjectConfig';
import { initRuntime } from './runtimeLoader';
+import type { ThemeOverrides } from './ui';
import type { RuntimeAssetSource } from './runtimeAssets';
import { FileSystemBackend } from './asset/Backend';
import { applyBuildRuntimeConfig, type RuntimeBuildConfig } from './defaults';
@@ -74,6 +75,8 @@ export interface WeChatRuntimeConfig {
physicsConfig?: { gravity?: Vec2; fixedTimestep?: number; subStepCount?: number };
/** Project-declared UI theme; 'light' re-skins ThemeStyle-tagged widgets at boot. */
uiTheme?: 'dark' | 'light';
+ /** Project-declared theme token overrides (partial re-skin over the base). */
+ uiThemeOverrides?: ThemeOverrides;
/** Project-declared mixer state (routing labels only on WeChat — no DSP graph). */
audioConfig?: AudioProjectConfig;
/** Bitmask of render layers (0..31) that y-sort within the layer (Project Settings → Rendering). */
@@ -204,6 +207,7 @@ export async function initWeChatRuntime(config: WeChatRuntimeConfig): Promise<vo
firstScene: config.firstScene,
physicsConfig: config.physicsConfig,
uiTheme: config.uiTheme,
+ uiThemeOverrides: config.uiThemeOverrides,
audioConfig: config.audioConfig,
aspectRatio: canvas.width / canvas.height,
});
diff --git a/sdk/tests/ui-theme.test.ts b/sdk/tests/ui-theme.test.ts
index ce297fa0e..09dc1202b 100644
--- a/sdk/tests/ui-theme.test.ts
+++ b/sdk/tests/ui-theme.test.ts
@@ -12,6 +12,8 @@ import {
setTheme,
themeColors,
themeType,
+ resolveThemeTokens,
+ parseThemeOverrides,
type ThemeTokens,
} from '../src/ui/theme/tokens';
import { themeButtonStates } from '../src/ui/widgets/button';
@@ -58,3 +60,53 @@ describe('ThemeTokens', () => {
expect(s.disabled.color).toMatchObject({ a: LIGHT_TOKENS.colors.control.a * 0.5 });
});
});
+
+describe('resolveThemeTokens', () => {
+ it('returns the base tokens untouched without overrides', () => {
+ expect(resolveThemeTokens('dark')).toBe(DARK_TOKENS);
+ expect(resolveThemeTokens('light', {})).toBe(LIGHT_TOKENS);
+ });
+
+ it('merges partial color overrides over the base, inheriting the rest', () => {
+ const red = { r: 1, g: 0, b: 0, a: 1 };
+ const t = resolveThemeTokens('dark', { colors: { primary: red } });
+ expect(t.colors.primary).toEqual(red);
+ expect(t.colors.surface).toEqual(DARK_TOKENS.colors.surface);
+ expect(t.type).toEqual(DARK_TOKENS.type);
+ expect(DARK_TOKENS.colors.primary).not.toEqual(red); // base untouched
+ });
+
+ it('merges type-scale overrides independently of colors', () => {
+ const t = resolveThemeTokens('light', { type: { title: 28 } });
+ expect(t.type.title).toBe(28);
+ expect(t.type.body).toBe(LIGHT_TOKENS.type.body);
+ expect(t.colors).toEqual(LIGHT_TOKENS.colors);
+ });
+});
+
+describe('parseThemeOverrides', () => {
+ it('parses #rrggbb and #rrggbbaa per role, dropping junk', () => {
+ const o = parseThemeOverrides({
+ primary: '#ff0000',
+ backdrop: '#00000080',
+ surface: 'not-a-color',
+ bogusRole: '#00ff00',
+ });
+ expect(o?.colors?.primary).toEqual({ r: 1, g: 0, b: 0, a: 1 });
+ expect(o?.colors?.backdrop?.a).toBeCloseTo(128 / 255);
+ expect(o?.colors?.surface).toBeUndefined();
+ expect(Object.keys(o?.colors ?? {})).toEqual(['primary', 'backdrop']);
+ });
+
+ it('returns undefined when nothing valid remains', () => {
+ expect(parseThemeOverrides(undefined)).toBeUndefined();
+ expect(parseThemeOverrides({})).toBeUndefined();
+ expect(parseThemeOverrides({ nope: '#zzz' })).toBeUndefined();
+ });
+
+ it('round-trips into resolveThemeTokens', () => {
+ const t = resolveThemeTokens('dark', parseThemeOverrides({ primary: '#ff0000' }));
+ expect(t.colors.primary).toEqual({ r: 1, g: 0, b: 0, a: 1 });
+ expect(t.colors.text).toEqual(DARK_TOKENS.colors.text);
+ });
+});