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(editor): i18n key binding UI - .eslocale asset type, key picker, cook inclusion

yhh6abd865686f4
diff --git a/desktop/electron/cookAssets.ts b/desktop/electron/cookAssets.ts
index afb3ad682..6914eeb43 100644
--- a/desktop/electron/cookAssets.ts
+++ b/desktop/electron/cookAssets.ts
@@ -231,6 +231,13 @@ export async function cookAssets(
for (const e of index.entries) {
if (subpackageOf(e.path)) seed(e.uuid);
}
+ // Force-include locale string tables: translations load by code / plugin
+ // option (a scene never references them — Text carries KEYS, not paths), so
+ // reachability would always cull them, and a build missing its languages is
+ // strictly wrong. Text is tiny; dead tables cost nothing.
+ for (const e of index.entries) {
+ if (e.path.toLowerCase().endsWith('.eslocale')) seed(e.uuid);
+ }
// …then take the transitive closure over the dependency graph.
while (queue.length > 0) {
const uuid = queue.shift()!;
diff --git a/desktop/src/engine/schema.ts b/desktop/src/engine/schema.ts
index 2081df323..94d12cb94 100644
--- a/desktop/src/engine/schema.ts
+++ b/desktop/src/engine/schema.ts
@@ -306,17 +306,24 @@ export function readonlyFieldsFor(compType: string): readonly string[] {
// Some string fields are really a choice from a list that depends on the entity's
// runtime state, not a static enum (e.g. a spine animation/skin name from the loaded
// skeleton). A provider, keyed by `component|field`, yields the options for one
-// entity; the inspector renders a dropdown when it returns any.
-const dynamicEnums = new Map<string, (sourceId: number) => readonly string[]>();
+// entity; the inspector renders a dropdown when it returns any. An option may
+// carry a display label distinct from the stored value (e.g. an i18n key with
+// its translated preview); plain strings stay valid for label-less providers.
+export interface DynamicEnumOption { value: string; label?: string }
-export function registerDynamicEnum(component: string, field: string, provider: (sourceId: number) => readonly string[]): void {
+const dynamicEnums = new Map<string, (sourceId: number) => readonly (string | DynamicEnumOption)[]>();
+
+export function registerDynamicEnum(
+ component: string, field: string, provider: (sourceId: number) => readonly (string | DynamicEnumOption)[],
+): void {
dynamicEnums.set(`${component}|${field}`, provider);
}
/** Dynamic enum options for a field on an entity, or null if the field has no provider / no options. */
-export function dynamicEnumOptions(component: string, field: string, sourceId: number): string[] | null {
+export function dynamicEnumOptions(component: string, field: string, sourceId: number): DynamicEnumOption[] | null {
const opts = dynamicEnums.get(`${component}|${field}`)?.(sourceId);
- return opts && opts.length ? [...opts] : null;
+ if (!opts || !opts.length) return null;
+ return opts.map((o) => (typeof o === 'string' ? { value: o } : o));
}
// — Field presentation metadata (the SDK's UPROPERTY analog) —
diff --git a/desktop/src/i18n/messages/content.ts b/desktop/src/i18n/messages/content.ts
index 33218f0cc..c3a9dfe70 100644
--- a/desktop/src/i18n/messages/content.ts
+++ b/desktop/src/i18n/messages/content.ts
@@ -62,6 +62,7 @@ export const contentMessages = defineMessages({
'cb.menuNewScene': { en: 'New Scene', zh: '新建场景' },
'cb.menuNewAnimation': { en: 'New Animation', zh: '新建动画' },
'cb.menuNewInputMap': { en: 'New Input Map', zh: '新建输入映射' },
+ 'cb.menuNewLocaleTable': { en: 'New Locale Table', zh: '新建本地化表' },
'cb.menuNewMaterial': { en: 'New Material', zh: '新建材质' },
'cb.menuNewMaterialGraph': { en: 'New Material Graph', zh: '新建材质图' },
'cb.menuNewStateMachine': { en: 'New State Machine', zh: '新建状态机' },
@@ -106,6 +107,7 @@ export const contentMessages = defineMessages({
'cb.newFolderFailed': { en: 'New folder failed: {error}', zh: '新建文件夹失败:{error}' },
'cb.newSceneFailed': { en: 'New scene failed: {error}', zh: '新建场景失败:{error}' },
'cb.newInputMapFailed': { en: 'New input map failed: {error}', zh: '新建输入映射失败:{error}' },
+ 'cb.newLocaleTableFailed': { en: 'New locale table failed: {error}', zh: '新建本地化表失败:{error}' },
'cb.revealFailed': { en: 'Couldn’t reveal: {error}', zh: '无法在资源管理器中显示:{error}' },
'cb.copiedPath': { en: 'Copied path', zh: '已复制路径' },
'cb.copiedReference': { en: 'Copied reference', zh: '已复制引用' },
diff --git a/desktop/src/main.tsx b/desktop/src/main.tsx
index 1d7d67409..5ab21dcfd 100644
--- a/desktop/src/main.tsx
+++ b/desktop/src/main.tsx
@@ -52,6 +52,8 @@ import { initFsWatch } from './project/fsWatch';
import { initBackgroundThrottle } from './engine/backgroundThrottle';
// Register the built-in settings (side effect) and replay persisted ones.
import './settings';
+// Register the Text.i18nKey picker's key index (side effect, like spineEnums).
+import './project/localeKeys';
import { applySettings } from './store/settingsStore';
// Capture console (editor + SDK + wasm) into the Output Log panel from startup.
diff --git a/desktop/src/panels/ContentBrowser.tsx b/desktop/src/panels/ContentBrowser.tsx
index b4bc8a643..15ab7a059 100644
--- a/desktop/src/panels/ContentBrowser.tsx
+++ b/desktop/src/panels/ContentBrowser.tsx
@@ -645,6 +645,17 @@ export function ContentBrowser() {
}
};
+ const newLocaleTable = async () => {
+ try {
+ const path = await ProjectStore.createLocaleTableFile(cwd);
+ refreshFs();
+ selectAsset(path);
+ setRenaming(path);
+ } catch (e) {
+ Toasts.push(t('cb.newLocaleTableFailed', { error: errMsg(e) }), 'error');
+ }
+ };
+
const showInExplorer = async (path: string) => {
try {
await window.estella.shell.showItem(path);
@@ -838,6 +849,7 @@ export function ContentBrowser() {
{ label: t('cb.menuNewScene'), onClick: () => void newScene() },
{ label: t('cb.menuNewAnimation'), onClick: () => void createAnimationClip(cwd) },
{ label: t('cb.menuNewInputMap'), onClick: () => void newInputMap() },
+ { label: t('cb.menuNewLocaleTable'), onClick: () => void newLocaleTable() },
{
label: t('cb.menuNewMaterial'),
children: BUILTIN_SHADER_TEMPLATES.map((tpl) => ({
diff --git a/desktop/src/panels/Details.tsx b/desktop/src/panels/Details.tsx
index dbb9239e2..5798fed8e 100644
--- a/desktop/src/panels/Details.tsx
+++ b/desktop/src/panels/Details.tsx
@@ -887,11 +887,12 @@ function FieldRow({ entities, comp, field, write }: { entities: EntityId[]; comp
});
// A string field whose choices depend on the entity's runtime state (e.g. a spine
- // animation/skin name) renders as a dropdown of the live options, falling back to
- // the text field when none are available (no skeleton loaded).
+ // animation/skin name) or on project content (an i18n key with its translated
+ // preview) renders as a dropdown of the live options, falling back to the text
+ // field when none are available (no skeleton loaded / no locale tables yet).
const dynOpts =
field.type === 'select'
- ? field.selectOptions ?? []
+ ? (field.selectOptions ?? []).map((o) => ({ value: o }))
: !mixed && !write && field.type === 'string'
? dynamicEnumOptions(comp, field.key, entities[0])
: null;
@@ -905,8 +906,8 @@ function FieldRow({ entities, comp, field, write }: { entities: EntityId[]; comp
value={cur}
ariaLabel={field.key}
options={[
- ...(dynOpts.includes(cur) ? [] : [{ value: cur, label: cur || t('det.noneOption') }]),
- ...dynOpts.map((o) => ({ value: o })),
+ ...(dynOpts.some((o) => o.value === cur) ? [] : [{ value: cur, label: cur || t('det.noneOption') }]),
+ ...dynOpts,
]}
onChange={(v) => {
begin();
diff --git a/desktop/src/project/ProjectStore.ts b/desktop/src/project/ProjectStore.ts
index ebd9e4813..1632e5fc6 100644
--- a/desktop/src/project/ProjectStore.ts
+++ b/desktop/src/project/ProjectStore.ts
@@ -404,6 +404,13 @@ class ProjectStoreImpl {
return window.estella.project.createAsset(destDir, 'input.inputmap', content, 'inputmap');
}
+ /** Create a blank `.eslocale` string table (ONE locale's key → text; ship one
+ * file per language) under `destDir`. */
+ async createLocaleTableFile(destDir: string): Promise<string> {
+ const content = JSON.stringify({ version: 1, locale: 'en', entries: {} }, null, 2) + '\n';
+ return window.estella.project.createAsset(destDir, 'strings.eslocale', content, 'locale');
+ }
+
/**
* Load the project's asset index (the main-process AssetDatabase scan)
* into a uuid→path registry, then point the engine
diff --git a/desktop/src/project/assetTypes.ts b/desktop/src/project/assetTypes.ts
index f0aa1bdde..598976784 100644
--- a/desktop/src/project/assetTypes.ts
+++ b/desktop/src/project/assetTypes.ts
@@ -13,7 +13,7 @@
*/
import {
Folder, Film, Image, FileImage, PersonStanding, Music,
- Component, Blend, FileCode2, Clapperboard, Grid3x3, File, Workflow, Gamepad2, GitBranch, ListTree,
+ Component, Blend, FileCode2, Clapperboard, Grid3x3, File, Workflow, Gamepad2, GitBranch, ListTree, Languages,
type LucideIcon,
} from 'lucide-react';
import type { AssetType } from '@/types';
@@ -50,6 +50,7 @@ export const ASSET_TYPES: Record<AssetType, AssetTypeDef> = {
inputmap: { extensions: ['inputmap'], badge: 'INP', icon: Gamepad2, tint: '#a0b88f' },
statemachine: { extensions: ['esfsm'], badge: 'FSM', icon: GitBranch, tint: '#8fb0a0' },
behaviortree: { extensions: ['esbt'], badge: 'BT', icon: ListTree, tint: '#8fa0c4' },
+ locale: { extensions: ['eslocale'], badge: 'LOC', icon: Languages, tint: '#b8a98a' },
file: { badge: '', icon: File, tint: 'var(--text-dim)' },
};
diff --git a/desktop/src/project/localeKeys.ts b/desktop/src/project/localeKeys.ts
new file mode 100644
index 000000000..2b680770d
--- /dev/null
+++ b/desktop/src/project/localeKeys.ts
@@ -0,0 +1,77 @@
+// SPDX-License-Identifier: Apache-2.0
+// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team
+/**
+ * @file localeKeys.ts — the project's i18n key index behind the Text.i18nKey
+ * picker. Scans every `.eslocale` table and serves the union of keys as
+ * dynamic-enum options, each labeled with a translated preview (in the
+ * EDITOR's language when that locale ships, else the first table's).
+ *
+ * The dynamic-enum provider is synchronous (called during inspector render),
+ * so the index is a sync cache refreshed asynchronously: a render kicks a scan
+ * when stale, and a finished scan that CHANGED the list bumps `fsRefresh` so
+ * open inspectors re-render with the fresh options (no change → no bump, so
+ * the kick can't loop). File edits mark the cache stale via the same signal.
+ */
+import { parseLocaleTable } from 'esengine';
+import { registerDynamicEnum, type DynamicEnumOption } from '@/engine/schema';
+import { ProjectStore } from './ProjectStore';
+import { fsRefresh } from './fsWatch';
+import { editorLocale } from '@/i18n';
+
+let options: DynamicEnumOption[] = [];
+let stale = true;
+let scanning = false;
+
+async function scan(): Promise<DynamicEnumOption[]> {
+ // key → per-locale preview text (plural entries preview their `other` form).
+ const previews = new Map<string, Map<string, string>>();
+ for (const { path } of ProjectStore.listAssets('locale')) {
+ let text: string;
+ try {
+ text = await window.estella.fs.read(path);
+ } catch {
+ continue; // deleted between scan start and read — the next bump rescans
+ }
+ try {
+ const table = parseLocaleTable(text, path);
+ for (const [key, value] of Object.entries(table.entries)) {
+ let byLocale = previews.get(key);
+ if (!byLocale) { byLocale = new Map(); previews.set(key, byLocale); }
+ byLocale.set(table.locale, typeof value === 'string' ? value : value.other);
+ }
+ } catch (e) {
+ // A malformed table must not hide the others' keys; the loader/runtime
+ // surfaces the same error loudly when the game ships it.
+ console.warn('[i18n] skipping malformed locale table', path, e);
+ }
+ }
+ return [...previews.entries()]
+ .sort(([a], [b]) => a.localeCompare(b))
+ .map(([key, byLocale]) => {
+ const preview = byLocale.get(editorLocale) ?? byLocale.values().next().value ?? '';
+ return { value: key, label: preview ? `${key} · ${preview}` : key };
+ });
+}
+
+function kickScan(): void {
+ if (!stale || scanning) return;
+ scanning = true;
+ void scan()
+ .then((next) => {
+ stale = false;
+ const changed = next.length !== options.length
+ || next.some((o, i) => o.value !== options[i].value || o.label !== options[i].label);
+ options = next;
+ if (changed) fsRefresh.bump();
+ })
+ .finally(() => { scanning = false; });
+}
+
+// Any on-disk change may add/remove keys — mark stale; the next inspector
+// render (or directory re-read) kicks the rescan.
+fsRefresh.subscribe(() => { stale = true; });
+
+registerDynamicEnum('Text', 'i18nKey', () => {
+ kickScan();
+ return options;
+});
diff --git a/desktop/src/types.ts b/desktop/src/types.ts
index 39368bf74..dbf25a144 100644
--- a/desktop/src/types.ts
+++ b/desktop/src/types.ts
@@ -165,6 +165,7 @@ export type AssetType =
| 'inputmap'
| 'statemachine'
| 'behaviortree'
+ | 'locale'
| 'file';
export interface AssetItem {
diff --git a/desktop/tests/cook-assets.test.ts b/desktop/tests/cook-assets.test.ts
index 4964a131f..1d12ef16e 100644
--- a/desktop/tests/cook-assets.test.ts
+++ b/desktop/tests/cook-assets.test.ts
@@ -24,6 +24,7 @@ const ORPHAN_TEX = '22222222-2222-4222-8222-222222222222';
const STRAY_TEX = '99999999-9999-4999-8999-999999999999';
const ENTRY_SCENE = 'aaaaaaaa-aaaa-4aaa-8aaa-aaaaaaaaaaaa';
const ORPHAN_SCENE = 'bbbbbbbb-bbbb-4bbb-8bbb-bbbbbbbbbbbb';
+const LOCALE_TABLE = 'cccccccc-cccc-4ccc-8ccc-cccccccccccc';
function writeAsset(rel: string, type: string, uuid: string, body = ''): void {
const abs = path.join(root, rel);
@@ -48,6 +49,10 @@ beforeAll(() => {
writeAsset('assets/textures/stray.png', 'texture', STRAY_TEX, 'STRAY'); // referenced by nobody
writeAsset('assets/scenes/main.esscene', 'scene', ENTRY_SCENE, sprite(USED_TEX));
writeAsset('assets/scenes/orphan.esscene', 'scene', ORPHAN_SCENE, sprite(ORPHAN_TEX));
+ // Referenced by nothing — but locale tables load by code (Text carries keys,
+ // not paths), so the cook force-includes them instead of culling.
+ writeAsset('assets/i18n/zh-CN.eslocale', 'locale', LOCALE_TABLE,
+ JSON.stringify({ version: 1, locale: 'zh-CN', entries: { play: '开始' } }));
});
afterAll(() => {
@@ -59,8 +64,8 @@ describe('cookAssets (A4)', () => {
const res = await cookAssets(root, { entryScenes: ['assets/scenes/main.esscene'], outDir: 'build' });
expect(res.ok).toBe(true);
- // Reachable: the entry scene + its texture.
- expect(res.included.sort()).toEqual([ENTRY_SCENE, USED_TEX].sort());
+ // Reachable: the entry scene + its texture, plus the force-included locale table.
+ expect(res.included.sort()).toEqual([ENTRY_SCENE, USED_TEX, LOCALE_TABLE].sort());
// Culled: the orphan scene, its texture, and the totally-unreferenced one.
expect(res.unused.sort()).toEqual([ORPHAN_SCENE, ORPHAN_TEX, STRAY_TEX].sort());
});
@@ -70,6 +75,7 @@ describe('cookAssets (A4)', () => {
expect(existsSync(path.join(res.outDir, 'assets/textures/used.png'))).toBe(true);
expect(existsSync(path.join(res.outDir, 'assets/scenes/main.esscene'))).toBe(true);
+ expect(existsSync(path.join(res.outDir, 'assets/i18n/zh-CN.eslocale'))).toBe(true);
// Culled assets are not staged.
expect(existsSync(path.join(res.outDir, 'assets/textures/orphan.png'))).toBe(false);
expect(existsSync(path.join(res.outDir, 'assets/textures/stray.png'))).toBe(false);
@@ -77,13 +83,14 @@ describe('cookAssets (A4)', () => {
const manifest = JSON.parse(readFileSync(res.manifestPath!, 'utf8')) as AssetManifest;
expect(manifest.version).toBe('1.0');
const paths = manifest.entries.map((e) => e.path).sort();
- expect(paths).toEqual(['assets/scenes/main.esscene', 'assets/textures/used.png']);
+ expect(paths).toEqual(['assets/i18n/zh-CN.eslocale', 'assets/scenes/main.esscene', 'assets/textures/used.png']);
});
it('warns when an entry scene is not a tracked asset', async () => {
const res = await cookAssets(root, { entryScenes: ['assets/scenes/missing.esscene'], outDir: 'build' });
expect(res.warnings.some((w) => w.includes('missing.esscene'))).toBe(true);
- expect(res.included).toEqual([]);
+ // Scene-reachable set is empty; the locale table still force-includes.
+ expect(res.included).toEqual([LOCALE_TABLE]);
});
it('records a contentHash + size for each staged asset', async () => {
diff --git a/desktop/tests/dynamic-enum.test.ts b/desktop/tests/dynamic-enum.test.ts
index 8d9679ff5..ee8298785 100644
--- a/desktop/tests/dynamic-enum.test.ts
+++ b/desktop/tests/dynamic-enum.test.ts
@@ -9,9 +9,14 @@ import { describe, it, expect } from 'vitest';
import { registerDynamicEnum, dynamicEnumOptions } from '@/engine/schema';
describe('dynamic enum registry', () => {
- it('returns a provider\'s options for the registered (component, field)', () => {
+ it('returns a provider\'s options for the registered (component, field), normalized', () => {
registerDynamicEnum('Foo', 'anim', () => ['walk', 'run']);
- expect(dynamicEnumOptions('Foo', 'anim', 1)).toEqual(['walk', 'run']);
+ expect(dynamicEnumOptions('Foo', 'anim', 1)).toEqual([{ value: 'walk' }, { value: 'run' }]);
+ });
+
+ it('keeps a provider\'s display labels (value ≠ label, e.g. i18n key + preview)', () => {
+ registerDynamicEnum('Foo', 'key', () => [{ value: 'menu.play', label: 'menu.play · 开始' }]);
+ expect(dynamicEnumOptions('Foo', 'key', 1)).toEqual([{ value: 'menu.play', label: 'menu.play · 开始' }]);
});
it('is null for an unregistered field, and for empty options (falls back to a text field)', () => {