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.
TypeScript 2d-game-engine3d3d-game-engineandroidcppecsgame-editorgame-enginegamedeviostypescriptwebassemblywebglwebgpuwechat-minigame
feat(editor): .eslocale gets a real editor - the Details panel, translator-shaped
yhh2dedffc88fa6
diff --git a/desktop/src/i18n/messages/details.ts b/desktop/src/i18n/messages/details.tsindex 2d2e8b0e3..b0dd72013 100644--- a/desktop/src/i18n/messages/details.ts+++ b/desktop/src/i18n/messages/details.ts@@ -137,6 +137,27 @@ export const detailsMessages = defineMessages({'det.bindRight': { en: 'Right', zh: '右' },'det.stickAria': { en: 'Stick', zh: '摇杆' },+ // — Locale-table asset editor (.eslocale, embedded in the inspector) —+ 'det.localeStrings': { en: 'Strings', zh: '字符串' },+ 'det.addKey': { en: '+ Key', zh: '+ 键' },+ 'det.localeTag': { en: 'Locale', zh: '语言' },+ 'det.noStrings': {+ en: 'No strings yet — add a key, or backfill from the other tables below.',+ zh: '还没有字符串——添加一个键,或从下方其他表补齐。',+ },+ 'det.toPlural': { en: 'Convert to plural forms', zh: '转为复数形式' },+ 'det.toSingle': { en: 'Collapse to a single string (keeps “other”)', zh: '折叠为单条字符串(保留 other)' },+ 'det.removeEntry': { en: 'Remove key', zh: '移除键' },+ 'det.removeForm': { en: 'Remove form', zh: '移除形式' },+ 'det.addForm': { en: '+ form', zh: '+ 形式' },+ 'det.pluralFormAria': { en: 'Add plural form', zh: '添加复数形式' },+ 'det.missingKeys': { en: 'Missing here — in other tables', zh: '本表缺失——其他表已有' },+ 'det.addMissingKey': { en: 'Add this key', zh: '补齐此键' },+ 'det.localeParseError': {+ en: 'This table has a syntax error — fix the file externally, then reselect it.',+ zh: '此表存在语法错误——请在外部修复文件后重新选中。',+ },+// — Generic asset inspector (import settings + metadata) —'det.importSettings': { en: 'Import Settings', zh: '导入设置' },'det.saveImportTip': { en: 'Save import settings', zh: '保存导入设置' },diff --git a/desktop/src/panels/Details.tsx b/desktop/src/panels/Details.tsxindex 5798fed8e..1bb28f214 100644--- a/desktop/src/panels/Details.tsx+++ b/desktop/src/panels/Details.tsx@@ -44,10 +44,11 @@ import { InspectorClipboard } from '@/engine/inspectorClipboard';import { SceneCommands, toModelValue } from '@/engine/SceneCommands';import { ENTITY_SOURCES, createFromSource } from '@/engine/entitySources';import { PlayInspect } from '@/engine/PlayInspect';-import { DimensionUnit, AnchorAxis, detectAnchor, UIPositionType } from 'esengine';-import type { SceneData, InputMapAsset, ActionType, Binding } from 'esengine';+import { DimensionUnit, AnchorAxis, detectAnchor, UIPositionType, parseLocaleTable } from 'esengine';+import type { SceneData, InputMapAsset, ActionType, Binding, LocaleTableAsset, PluralCategory } from 'esengine';import { modelAddableComponentEntries, subscribeSchemas, getSchemaRevision, prettyLabel, hexToRgba, dynamicEnumOptions, boxGroupsFor, type BoxGroupDef } from '@/engine/schema';import * as imap from '@/project/inputMapDoc';+import * as ldoc from '@/project/localeTableDoc';import { buildImporterComponent, applyImporterEdit } from '@/project/assetImporter';import { referencingPaths } from '@/project/assetRefs';import { ProjectStore } from '@/project/ProjectStore';@@ -1901,6 +1902,206 @@ function InputMapAssetInspector({ path }: { path: string }) {);}+// The .eslocale editor, embedded in the unified inspector (the input-map+// precedent): edits the SAME JSON the runtime's LocaleAssetLoader reads, saving+// on every edit. The project's OTHER tables provide a dimmed reference+// translation per key plus a missing-key backfill list — the translator's+// actual workflow. A syntax error shows read-only guidance instead of an+// editor whose first save would clobber the file.+function LocaleTableAssetInspector({ path }: { path: string }) {+ const [table, setTable] = useState<LocaleTableAsset | null>(null);+ const [loadError, setLoadError] = useState<string | null>(null);+ // key → (locale → text) across the project's other .eslocale tables.+ const [siblings, setSiblings] = useState<Map<string, Map<string, string>> | null>(null);++ useEffect(() => {+ let alive = true;+ setTable(null);+ setLoadError(null);+ void window.estella.fs+ .read(path)+ .then((text) => {+ if (!alive) return;+ try {+ setTable(parseLocaleTable(text, path));+ } catch (e) {+ setLoadError(e instanceof Error ? e.message : String(e));+ }+ })+ .catch((e) => alive && setLoadError(e instanceof Error ? e.message : String(e)));+ return () => {+ alive = false;+ };+ }, [path]);++ useEffect(() => {+ let alive = true;+ setSiblings(null);+ void (async () => {+ const map = new Map<string, Map<string, string>>();+ for (const asset of ProjectStore.listAssets('locale')) {+ if (asset.path === path) continue;+ try {+ const sib = parseLocaleTable(await window.estella.fs.read(asset.path), asset.path);+ for (const [key, entry] of Object.entries(sib.entries)) {+ let byLocale = map.get(key);+ if (!byLocale) {+ byLocale = new Map();+ map.set(key, byLocale);+ }+ byLocale.set(sib.locale, typeof entry === 'string' ? entry : entry.other);+ }+ } catch {+ /* malformed sibling — selecting IT surfaces the error */+ }+ }+ if (alive) setSiblings(map);+ })();+ return () => {+ alive = false;+ };+ }, [path]);++ if (loadError) {+ return (+ <div className="insp input-map">+ <div className="empty-line">{t('det.localeParseError')}</div>+ <div className="lt-ref" title={loadError}>{loadError}</div>+ </div>+ );+ }+ if (!table) return <div className="insp"><div className="empty-line">{t('det.loading')}</div></div>;++ const commit = (next: LocaleTableAsset) => {+ setTable(next);+ void window.estella.fs.write(path, ldoc.serializeLocaleTable(next));+ };+ const uniqueKey = () => {+ let n = 'new.key';+ for (let i = 2; table.entries[n] !== undefined; i++) n = `new.key${i}`;+ return n;+ };+ // Reference language for a key: 'en' when this table isn't en, else the+ // first other locale that carries it.+ const refFor = (key: string): { tag: string; text: string } | null => {+ const byLocale = siblings?.get(key);+ if (!byLocale || byLocale.size === 0) return null;+ const tag = table.locale !== 'en' && byLocale.has('en')+ ? 'en'+ : ([...byLocale.keys()].find((l) => l !== table.locale) ?? [...byLocale.keys()][0]);+ return { tag, text: byLocale.get(tag)! };+ };+ const missing = siblings ? [...siblings.keys()].filter((k) => table.entries[k] === undefined).sort() : [];+ const entries = Object.entries(table.entries);++ return (+ <div className="insp input-map">+ <div className="im-head">+ <span>{t('det.localeStrings')}</span>+ <button type="button" className="im-add" onClick={() => commit(ldoc.addEntry(table, uniqueKey()))}>{t('det.addKey')}</button>+ </div>+ <div className="im-action">+ <div className="im-action-head">+ <span className="lt-form">{t('det.localeTag')}</span>+ <input+ className="im-name"+ key={table.locale}+ defaultValue={table.locale}+ spellCheck={false}+ onBlur={(e) => {+ if (e.target.value.trim() && e.target.value !== table.locale) commit(ldoc.setLocaleTag(table, e.target.value));+ }}+ />+ </div>+ </div>+ {entries.length === 0 && <div className="empty-line">{t('det.noStrings')}</div>}+ {entries.map(([key, entry]) => {+ const ref = refFor(key);+ const plural = typeof entry !== 'string';+ return (+ <div className="im-action" key={key}>+ <div className="im-action-head">+ <input+ className="im-name"+ key={key}+ defaultValue={key}+ spellCheck={false}+ onBlur={(e) => {+ if (e.target.value.trim() && e.target.value !== key) commit(ldoc.renameEntry(table, key, e.target.value));+ }}+ />+ <button+ type="button"+ className="im-x"+ title={plural ? t('det.toSingle') : t('det.toPlural')}+ onClick={() => commit(plural ? ldoc.toSingle(table, key) : ldoc.toPlural(table, key))}+ >+ {plural ? '1' : 'N'}+ </button>+ <button type="button" className="im-x" title={t('det.removeEntry')} onClick={() => commit(ldoc.removeEntry(table, key))}>×</button>+ </div>+ {!plural ? (+ <input+ className="im-in lt-text"+ key={`${key}:s`}+ defaultValue={entry}+ spellCheck={false}+ onBlur={(e) => commit(ldoc.setEntryText(table, key, e.target.value))}+ />+ ) : (+ <>+ {ldoc.PLURAL_CATEGORIES.filter((c) => entry[c] !== undefined).map((c) => (+ <div className="im-binding" key={c}>+ <span className="lt-form">{c}</span>+ <input+ className="im-in lt-text"+ key={`${key}:${c}`}+ defaultValue={entry[c]}+ spellCheck={false}+ onBlur={(e) => commit(ldoc.setPluralForm(table, key, c, e.target.value))}+ />+ {c !== 'other' && (+ <button type="button" className="im-x" title={t('det.removeForm')} onClick={() => commit(ldoc.removePluralForm(table, key, c))}>×</button>+ )}+ </div>+ ))}+ {ldoc.absentPluralForms(entry).length > 0 && (+ <Select+ className="im-in kind"+ ariaLabel={t('det.pluralFormAria')}+ value=""+ options={[+ { value: '', label: t('det.addForm') },+ ...ldoc.absentPluralForms(entry).map((c) => ({ value: c, label: c })),+ ]}+ onChange={(v) => v && commit(ldoc.setPluralForm(table, key, v as PluralCategory, ''))}+ />+ )}+ </>+ )}+ {ref && <div className="lt-ref" title={`${ref.tag} · ${ref.text}`}>{ref.tag} · {ref.text}</div>}+ </div>+ );+ })}+ {missing.length > 0 && (+ <>+ <div className="im-head"><span>{t('det.missingKeys')}</span></div>+ {missing.map((k) => {+ const ref = refFor(k);+ return (+ <div className="im-binding" key={k}>+ <button type="button" className="im-addb" title={t('det.addMissingKey')} onClick={() => commit(ldoc.addEntry(table, k))}>+</button>+ <span className="lt-miss" title={k}>{k}</span>+ {ref && <span className="lt-ref" title={ref.text}>{ref.tag} · {ref.text}</span>}+ </div>+ );+ })}+ </>+ )}+ </div>+ );+}+// rows); other assets show their fs metadata + the image/type glyph preview.function AssetInspector({ path }: { path: string }) {const type = assetTypeOf(baseName(path));@@ -1910,6 +2111,9 @@ function AssetInspector({ path }: { path: string }) {if (type === 'inputmap') {return <InputMapAssetInspector path={path} />;}+ if (type === 'locale') {+ return <LocaleTableAssetInspector path={path} />;+ }return <GenericAssetInspector path={path} />;}diff --git a/desktop/src/project/localeTableDoc.ts b/desktop/src/project/localeTableDoc.tsnew file mode 100644index 000000000..af5aced53--- /dev/null+++ b/desktop/src/project/localeTableDoc.ts@@ -0,0 +1,102 @@+// SPDX-License-Identifier: Apache-2.0+// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team+/**+ * @file localeTableDoc.ts+ * @brief Pure, immutable edits over a LocaleTableAsset (the `.eslocale` content:+ * one locale's key → string | plural forms). The data model is the SDK's+ * (parseLocaleTable / LocaleAssetLoader ship the same JSON), so the editor+ * authors exactly what the runtime loads — the inputMapDoc pattern.+ * Engine/DOM-free → unit-tests in isolation; the panel renders + dispatches.+ */+import type { LocaleTableAsset, LocaleEntry, PluralForms, PluralCategory } from 'esengine';++export const LOCALE_TABLE_VERSION = 1;++/** CLDR plural categories, in display order. `other` is the required catch-all. */+export const PLURAL_CATEGORIES: readonly PluralCategory[] = ['zero', 'one', 'two', 'few', 'many', 'other'];++export const blankLocaleTable = (locale = 'en'): LocaleTableAsset =>+ ({ version: LOCALE_TABLE_VERSION, locale, entries: {} });++const withEntries = (table: LocaleTableAsset, entries: Record<string, LocaleEntry>): LocaleTableAsset =>+ ({ ...table, entries });++/** The stable on-disk form (2-space indent + trailing newline — what+ * createLocaleTableFile writes and git diffs expect). */+export const serializeLocaleTable = (table: LocaleTableAsset): string =>+ JSON.stringify(table, null, 2) + '\n';++export function setLocaleTag(table: LocaleTableAsset, locale: string): LocaleTableAsset {+ const tag = locale.trim();+ if (!tag || tag === table.locale) return table;+ return { ...table, locale: tag };+}++export function addEntry(table: LocaleTableAsset, key: string, text = ''): LocaleTableAsset {+ const k = key.trim();+ if (!k || table.entries[k] !== undefined) return table;+ return withEntries(table, { ...table.entries, [k]: text });+}++/** Rename a key, preserving its position in the (ordered) entry list. */+export function renameEntry(table: LocaleTableAsset, from: string, to: string): LocaleTableAsset {+ const t = to.trim();+ if (from === t || table.entries[from] === undefined || !t || table.entries[t] !== undefined) return table;+ const entries: Record<string, LocaleEntry> = {};+ for (const [k, v] of Object.entries(table.entries)) entries[k === from ? t : k] = v;+ return withEntries(table, entries);+}++export function removeEntry(table: LocaleTableAsset, key: string): LocaleTableAsset {+ if (table.entries[key] === undefined) return table;+ const entries = { ...table.entries };+ delete entries[key];+ return withEntries(table, entries);+}++/** Set a plain-string entry's text (no-op on plural entries — edit their forms). */+export function setEntryText(table: LocaleTableAsset, key: string, text: string): LocaleTableAsset {+ const cur = table.entries[key];+ if (cur === undefined || typeof cur !== 'string' || cur === text) return table;+ return withEntries(table, { ...table.entries, [key]: text });+}++/** Convert a plain entry to plural forms (its text becomes `other`). */+export function toPlural(table: LocaleTableAsset, key: string): LocaleTableAsset {+ const cur = table.entries[key];+ if (cur === undefined || typeof cur !== 'string') return table;+ return withEntries(table, { ...table.entries, [key]: { other: cur } });+}++/** Collapse a plural entry back to a plain string (keeps its `other` form). */+export function toSingle(table: LocaleTableAsset, key: string): LocaleTableAsset {+ const cur = table.entries[key];+ if (cur === undefined || typeof cur === 'string') return table;+ return withEntries(table, { ...table.entries, [key]: cur.other });+}++/** Set one plural form's text; adds the form if absent. */+export function setPluralForm(+ table: LocaleTableAsset, key: string, form: PluralCategory, text: string,+): LocaleTableAsset {+ const cur = table.entries[key];+ if (cur === undefined || typeof cur === 'string' || cur[form] === text) return table;+ return withEntries(table, { ...table.entries, [key]: { ...cur, [form]: text } });+}++/** Remove a plural form. `other` is the required catch-all — never removable. */+export function removePluralForm(+ table: LocaleTableAsset, key: string, form: PluralCategory,+): LocaleTableAsset {+ const cur = table.entries[key];+ if (cur === undefined || typeof cur === 'string' || form === 'other' || cur[form] === undefined) return table;+ const forms: PluralForms = { ...cur };+ delete forms[form];+ return withEntries(table, { ...table.entries, [key]: forms });+}++/** The plural categories an entry does NOT carry yet (for the add-form picker). */+export function absentPluralForms(entry: LocaleEntry): PluralCategory[] {+ if (typeof entry === 'string') return [];+ return PLURAL_CATEGORIES.filter((c) => entry[c] === undefined);+}diff --git a/desktop/src/theme/inspector.css b/desktop/src/theme/inspector.cssindex be722e2b2..3d9eba9e1 100644--- a/desktop/src/theme/inspector.css+++ b/desktop/src/theme/inspector.css@@ -270,3 +270,11 @@.im-x { color: var(--text-mute); width: 18px; height: 18px; border-radius: var(--r-xs); flex-shrink: 0; line-height: 1; transition: color var(--t-fast), background var(--t-fast); }.im-x:hover { color: var(--error); background: var(--srf-4); }.im-addb { align-self: flex-start; }++/* Locale-table editor (.eslocale) — rides the .im-* frame; these add the+ translator-specific bits: the plural-form tag, the dimmed sibling-locale+ reference line, and the missing-key backfill rows. */+.lt-form { flex-shrink: 0; width: 42px; font-family: var(--mono); font-size: var(--fs-2xs); color: var(--text-mute); text-align: right; }+.lt-text { flex: 1; min-width: 0; }+.lt-ref { font-size: var(--fs-2xs); color: var(--text-mute); overflow: hidden; text-overflow: ellipsis; white-space: nowrap; padding-left: 2px; }+.lt-miss { flex: 1; min-width: 0; font-family: var(--mono); font-size: var(--fs-xs); color: var(--text-dim); overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }diff --git a/desktop/tests/locale-table-doc.test.ts b/desktop/tests/locale-table-doc.test.tsnew file mode 100644index 000000000..b59e02287--- /dev/null+++ b/desktop/tests/locale-table-doc.test.ts@@ -0,0 +1,72 @@+// SPDX-License-Identifier: Apache-2.0+// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team+/**+ * @file Pure edits over a LocaleTableAsset (the .eslocale editor's document+ * model) — add/rename/remove keys (order-preserving, collision-safe),+ * string ↔ plural conversion, per-form edits, and the stable+ * serialization the runtime parses back.+ */+import { describe, it, expect } from 'vitest';+import { parseLocaleTable } from 'esengine';+import * as ldoc from '@/project/localeTableDoc';++const base = () => ldoc.addEntry(ldoc.addEntry(ldoc.blankLocaleTable('zh-CN'), 'a', '甲'), 'b', '乙');++describe('localeTableDoc', () => {+ it('addEntry: unique keys only; blank names rejected', () => {+ const t = base();+ expect(Object.keys(t.entries)).toEqual(['a', 'b']);+ expect(ldoc.addEntry(t, 'a', 'dup')).toBe(t);+ expect(ldoc.addEntry(t, ' ')).toBe(t);+ });++ it('renameEntry preserves order and refuses collisions', () => {+ const t = ldoc.renameEntry(base(), 'a', 'z');+ expect(Object.keys(t.entries)).toEqual(['z', 'b']); // position kept+ expect(t.entries.z).toBe('甲');+ expect(ldoc.renameEntry(t, 'z', 'b')).toBe(t); // collision → no-op+ });++ it('removeEntry / setEntryText', () => {+ const t = ldoc.setEntryText(base(), 'a', '改');+ expect(t.entries.a).toBe('改');+ expect(Object.keys(ldoc.removeEntry(t, 'a').entries)).toEqual(['b']);+ });++ it('string ↔ plural round-trips through the `other` form', () => {+ let t = ldoc.toPlural(base(), 'a');+ expect(t.entries.a).toEqual({ other: '甲' });+ t = ldoc.setPluralForm(t, 'a', 'one', '一');+ expect(t.entries.a).toEqual({ other: '甲', one: '一' });+ t = ldoc.toSingle(t, 'a');+ expect(t.entries.a).toBe('甲'); // collapses to other, dropping one+ });++ it('removePluralForm never removes the required `other`', () => {+ let t = ldoc.setPluralForm(ldoc.toPlural(base(), 'a'), 'a', 'few', '几');+ t = ldoc.removePluralForm(t, 'a', 'few');+ expect(t.entries.a).toEqual({ other: '甲' });+ expect(ldoc.removePluralForm(t, 'a', 'other')).toBe(t);+ });++ it('absentPluralForms lists what the add-form picker offers', () => {+ const t = ldoc.setPluralForm(ldoc.toPlural(base(), 'a'), 'a', 'one', '一');+ expect(ldoc.absentPluralForms(t.entries.a)).toEqual(['zero', 'two', 'few', 'many']);+ expect(ldoc.absentPluralForms('plain')).toEqual([]);+ });++ it('setLocaleTag trims and no-ops on empty/same', () => {+ const t = base();+ expect(ldoc.setLocaleTag(t, ' en ').locale).toBe('en');+ expect(ldoc.setLocaleTag(t, '')).toBe(t);+ });++ it('serialization round-trips through the runtime parser', () => {+ const t = ldoc.setPluralForm(ldoc.toPlural(base(), 'b'), 'b', 'one', '壹');+ const text = ldoc.serializeLocaleTable(t);+ expect(text.endsWith('\n')).toBe(true);+ const back = parseLocaleTable(text, 'x.eslocale');+ expect(back.locale).toBe('zh-CN');+ expect(back.entries).toEqual(t.entries);+ });+});diff --git a/docs/astro/src/content/docs/guides/localization.mdx b/docs/astro/src/content/docs/guides/localization.mdxindex 4b22a2e68..6a6bcc74e 100644--- a/docs/astro/src/content/docs/guides/localization.mdx+++ b/docs/astro/src/content/docs/guides/localization.mdx@@ -87,7 +87,10 @@ locale's catalog, so a game loads only the languages it needs.```Create one in the editor (Content Browser → right-click → **New Locale Table**) or-by hand. Load explicitly with `Assets.loadLocaleTable(path)` (requires the+by hand. **Selecting a table turns the Details panel into its editor**: key/text+rows (with plural forms), a dimmed reference translation from the project's other+tables, and a missing-key list you backfill with one click — every edit saves+immediately. Load explicitly with `Assets.loadLocaleTable(path)` (requires thelocalization plugin — it fails loud otherwise), preload via`new LocalizationPlugin({ tables: ['assets/i18n/zh-CN.eslocale'] })`, or let the[Text binding below](#bind-ui-text-to-keys) load everything automatically. Thediff --git a/docs/astro/src/content/docs/zh-cn/guides/localization.mdx b/docs/astro/src/content/docs/zh-cn/guides/localization.mdxindex 6ccce6494..e696a73d2 100644--- a/docs/astro/src/content/docs/zh-cn/guides/localization.mdx+++ b/docs/astro/src/content/docs/zh-cn/guides/localization.mdx@@ -81,7 +81,9 @@ i18n.t('apples', { count: 3 }); // "3 apples"}```-在编辑器里创建(内容浏览器 → 右键 → **新建本地化表**)或手写皆可。显式加载用+在编辑器里创建(内容浏览器 → 右键 → **新建本地化表**)或手写皆可。**选中一张表,细节面板+就是它的编辑器**:键/译文行(支持复数形式)、其他表的参照译文淡显在每行下方、缺失的 key+一键补齐——每次编辑立即保存。显式加载用`Assets.loadLocaleTable(path)`(需要本地化插件——否则大声报错),预载用`new LocalizationPlugin({ tables: ['assets/i18n/zh-CN.eslocale'] })`,或者让[下面的 Text 绑定](#把-ui-text-绑到-key)全自动加载。导出 cook 永远会把 `.eslocale`