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(i18n): translations ship as data - .eslocale tables + Text.i18nKey binding
yhh70c299c3a02b
diff --git a/sdk/etc/index.api.md b/sdk/etc/index.api.mdindex a4bf00a76..b9cf572af 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: 1120 stable · 17 beta · 1 deprecated+Symbols: 1123 stable · 17 beta · 1 deprecated## ABI_LAYOUT_HASH — const```@@ -3238,6 +3238,19 @@ Record<string, LocaleEntry>string | PluralForms```+## LocaleResult — interface+```+keyCount: number+locale: string+```++## LocaleTableAsset — interface+```+entries: LocaleCatalog+locale: string+version: number+```+## Localization — const```ResourceDef<LocalizationApi>@@ -3263,6 +3276,7 @@ static prototype: LocalizationApicatalogs: Record<string, LocaleCatalog> | undefinedfallback: string | undefinedlocale: string | undefined+tables: string[] | undefined```## LocalizationPlugin — class@@ -5830,6 +5844,7 @@ content: stringenabled: booleanfontFamily: stringfontSize: number+i18nKey: stringitalic: booleanlineHeight: numberoverflow: TextOverflow@@ -5854,6 +5869,7 @@ content: string | undefinedenabled: boolean | undefinedfontFamily: string | undefinedfontSize: number | undefined+i18nKey: string | undefineditalic: boolean | undefinedlineHeight: number | undefinedoverflow: TextOverflow | undefined@@ -8081,6 +8097,11 @@ NavPlugin(raw: any): TimelineAsset```+## parseLocaleTable — function+```+(text: string, path: string): LocaleTableAsset+```+## parseRichText — function```(input: string): RichTextRun[]diff --git a/sdk/etc/index.node.api.md b/sdk/etc/index.node.api.mdindex 343b5f3cd..1598c406e 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: 1119 stable · 19 beta · 1 deprecated+Symbols: 1122 stable · 19 beta · 1 deprecated## ANCHOR_AXES — const```@@ -3233,6 +3233,19 @@ Record<string, LocaleEntry>string | PluralForms```+## LocaleResult — interface+```+keyCount: number+locale: string+```++## LocaleTableAsset — interface+```+entries: LocaleCatalog+locale: string+version: number+```+## Localization — const```ResourceDef<LocalizationApi>@@ -3258,6 +3271,7 @@ static prototype: LocalizationApicatalogs: Record<string, LocaleCatalog> | undefinedfallback: string | undefinedlocale: string | undefined+tables: string[] | undefined```## LocalizationPlugin — class@@ -5825,6 +5839,7 @@ content: stringenabled: booleanfontFamily: stringfontSize: number+i18nKey: stringitalic: booleanlineHeight: numberoverflow: TextOverflow@@ -5849,6 +5864,7 @@ content: string | undefinedenabled: boolean | undefinedfontFamily: string | undefinedfontSize: number | undefined+i18nKey: string | undefineditalic: boolean | undefinedlineHeight: number | undefinedoverflow: TextOverflow | undefined@@ -8086,6 +8102,11 @@ NodePlatformAdapter(raw: any): TimelineAsset```+## parseLocaleTable — function+```+(text: string, path: string): LocaleTableAsset+```+## parseRichText — function```(input: string): RichTextRun[]diff --git a/sdk/src/asset/AssetLoader.ts b/sdk/src/asset/AssetLoader.tsindex 43e1eb04e..2906832a0 100644--- a/sdk/src/asset/AssetLoader.ts+++ b/sdk/src/asset/AssetLoader.ts@@ -54,6 +54,13 @@ export interface FsmResult {fsmId: string;}+export interface LocaleResult {+ /** The locale the table's entries were merged into. */+ locale: string;+ /** How many keys the table carried. */+ keyCount: number;+}+export interface BtResult {btId: string;}@@ -95,6 +102,13 @@ export interface LoadContext {* like {@link getAudio}. Returns null when no AnimationPlugin is installed.*/getSpriteAnimation(): import('../animation/SpriteAnimator').SpriteAnimationApi | null;+ /**+ * Localization service for the owning app, resolved lazily like+ * {@link getAudio}. Returns null when no LocalizationPlugin is installed —+ * loading a `.eslocale` then fails loud (a table with nowhere to register+ * is a setup error, not a soft skip).+ */+ getLocalization(): import('../i18n/Localization').LocalizationApi | null;}export interface AssetLoader<T> {diff --git a/sdk/src/asset/AssetPlugin.ts b/sdk/src/asset/AssetPlugin.tsindex 439ad6ce5..5ec6cdee7 100644--- a/sdk/src/asset/AssetPlugin.ts+++ b/sdk/src/asset/AssetPlugin.ts@@ -9,6 +9,7 @@ import { initBuiltinAssetFields } from './AssetFieldRegistry';import { AssetRefCounter } from './AssetRefCounter';import { Audio, type AudioAPI } from '../audio/Audio';import { SpriteAnimation, type SpriteAnimationApi } from '../animation/SpriteAnimator';+import { Localization, type LocalizationApi } from '../i18n/Localization';import { log } from '../logger';export type AssetsData = AssetsClass;@@ -37,6 +38,8 @@ export class AssetPlugin implements Plugin {app.hasResource(Audio) ? app.getResource(Audio) : null,getSpriteAnimation: (): SpriteAnimationApi | null =>app.hasResource(SpriteAnimation) ? app.getResource(SpriteAnimation) : null,+ getLocalization: (): LocalizationApi | null =>+ app.hasResource(Localization) ? app.getResource(Localization) : null,});// Lazily acquire the Basis transcoder for KTX2 textures the same waydiff --git a/sdk/src/asset/Assets.ts b/sdk/src/asset/Assets.tsindex cd504e7e2..8149b9a50 100644--- a/sdk/src/asset/Assets.ts+++ b/sdk/src/asset/Assets.ts@@ -8,6 +8,7 @@ import type {AssetLoader, LoadContext, TextureResult, SpineResult,MaterialResult, FontResult, AudioResult, AnimClipResult,TilemapResult, TilesetResult, TimelineResult, PrefabResult,+ LocaleResult,} from './AssetLoader';import { AsyncCache } from './AsyncCache';import type { ESEngineModule } from '../wasm';@@ -26,6 +27,7 @@ import { TimelineAssetLoader } from './loaders/TimelineAssetLoader';import { PrefabAssetLoader } from './loaders/PrefabAssetLoader';import { FsmAssetLoader } from './loaders/FsmAssetLoader';import { BtAssetLoader } from './loaders/BtAssetLoader';+import { LocaleAssetLoader } from './loaders/LocaleAssetLoader';import type { SpineModuleController } from '../spine/SpineController';import { getAssetFields } from './AssetFieldRegistry';import { getComponentDefaults } from '../component';@@ -96,6 +98,9 @@ export interface AssetsOptions {*/getAudio?: () => import('../audio/Audio').AudioAPI | null;getSpriteAnimation?: () => import('../animation/SpriteAnimator').SpriteAnimationApi | null;+ /** Lazy accessor for the owning app's Localization service, same contract+ * as {@link getAudio} — `.eslocale` tables register through it. */+ getLocalization?: () => import('../i18n/Localization').LocalizationApi | null;}export interface AssetBundle {@@ -154,6 +159,7 @@ export class Assets {private manifestModel_: ManifestModel | null = null;private getAudio_: () => import('../audio/Audio').AudioAPI | null;private getSpriteAnimation_: () => import('../animation/SpriteAnimator').SpriteAnimationApi | null;+ private getLocalization_: () => import('../i18n/Localization').LocalizationApi | null;private loaders_ = new Map<string, AssetLoader<unknown>>();private textureLoader_: TextureLoader;private textureImportResolver_: TextureImportSettingsResolver | null = null;@@ -183,6 +189,7 @@ export class Assets {this.module_ = options.module;this.getAudio_ = options.getAudio ?? (() => null);this.getSpriteAnimation_ = options.getSpriteAnimation ?? (() => null);+ this.getLocalization_ = options.getLocalization ?? (() => null);this.setManifest(options.manifest ?? null);this.textureLoader_ = new TextureLoader(options.module);@@ -324,6 +331,12 @@ export class Assets {return this.loadTyped('timeline', ref);}+ /** Load a `.eslocale` string table and merge it into the app's Localization+ * catalogs. Requires the LocalizationPlugin (fails loud otherwise). */+ async loadLocaleTable(ref: string): Promise<LocaleResult> {+ return this.loadTyped('locale', ref);+ }+async loadPrefab(ref: string): Promise<PrefabResult> {return this.loadTyped('prefab', ref);}@@ -1111,6 +1124,7 @@ export class Assets {this.register(new PrefabAssetLoader());this.register(new FsmAssetLoader());this.register(new BtAssetLoader());+ this.register(new LocaleAssetLoader());}private textureCacheKey_(path: string, flip: boolean): string {@@ -1173,6 +1187,9 @@ export class Assets {getSpriteAnimation() {return self.getSpriteAnimation_();},+ getLocalization() {+ return self.getLocalization_();+ },};return this.loadContext_;}diff --git a/sdk/src/asset/index.ts b/sdk/src/asset/index.tsindex 51c1d2443..1b61de281 100644--- a/sdk/src/asset/index.ts+++ b/sdk/src/asset/index.ts@@ -29,7 +29,7 @@ export {type AssetEntry,type AssetManifest,} from './AssetRegistry';-export { type AssetLoader, type LoadContext, type TextureResult, type TextureResult as TextureInfo, type SpineResult, type SpineLoadResult, type MaterialResult, type FontResult, type AudioResult } from './AssetLoader';+export { type AssetLoader, type LoadContext, type TextureResult, type TextureResult as TextureInfo, type SpineResult, type SpineLoadResult, type MaterialResult, type FontResult, type AudioResult, type LocaleResult } from './AssetLoader';export { TextureLoader, type TextureImportSettings, type TextureImportSettingsResolver } from './loaders/TextureLoader';export { SceneHandle } from './SceneHandle';export {diff --git a/sdk/src/asset/loaders/LocaleAssetLoader.ts b/sdk/src/asset/loaders/LocaleAssetLoader.tsnew file mode 100644index 000000000..8bd7a3535--- /dev/null+++ b/sdk/src/asset/loaders/LocaleAssetLoader.ts@@ -0,0 +1,39 @@+// SPDX-License-Identifier: Apache-2.0+// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team+/**+ * @file LocaleAssetLoader.ts+ * @brief Loads a `.eslocale` string table and merges it into the app's+ * Localization catalogs — translations ship as data, not code.+ *+ * One file carries ONE locale (`{ version, locale, entries }`), so a game+ * loads only the languages it needs. Requires the LocalizationPlugin: with no+ * Localization resource the table has nowhere to register, and that is a+ * setup error worth failing loud over — not a silent no-op.+ */++import type { AssetLoader, LoadContext, LocaleResult } from '../AssetLoader';+import { parseLocaleTable } from '../../i18n/Localization';++export class LocaleAssetLoader implements AssetLoader<LocaleResult> {+ readonly type = 'locale';+ readonly extensions = ['.eslocale'];++ async load(path: string, ctx: LoadContext): Promise<LocaleResult> {+ const i18n = ctx.getLocalization();+ if (!i18n) {+ throw new Error(+ `${path}: no Localization resource — add localizationPlugin to the app before loading locale tables`,+ );+ }+ const buildPath = ctx.catalog.getBuildPath(path);+ const text = await ctx.loadText(buildPath);+ const table = parseLocaleTable(text, path);+ i18n.addCatalog(table.locale, table.entries);+ return { locale: table.locale, keyCount: Object.keys(table.entries).length };+ }++ unload(): void {+ // Catalogs merge; there is no per-table removal (same contract as the+ // FSM/BT stores). A reloaded table simply re-merges its keys.+ }+}diff --git a/sdk/src/assetTypes.ts b/sdk/src/assetTypes.tsindex 5e5e6a34f..f845e2002 100644--- a/sdk/src/assetTypes.ts+++ b/sdk/src/assetTypes.ts@@ -47,6 +47,8 @@ const ASSET_TYPE_REGISTRY: readonly AssetTypeEntry[] = [{ extensions: ['esanim'], contentType: 'json', editorType: 'anim-clip', addressableType: null, wechatPackInclude: true, hasTransitiveDeps: true },{ extensions: ['tmj'], contentType: 'json', editorType: 'tilemap', addressableType: 'json', wechatPackInclude: true, hasTransitiveDeps: true },{ extensions: ['estimeline'], contentType: 'json', editorType: 'timeline', addressableType: 'json', wechatPackInclude: true, hasTransitiveDeps: true },+ // Locale string table (LocaleAssetLoader → Localization.addCatalog) — one locale per file.+ { extensions: ['eslocale'], contentType: 'json', editorType: 'json', addressableType: 'json', wechatPackInclude: true, hasTransitiveDeps: false },// State machine (registerFsm / FsmAssetLoader) — data-driven FSM definition.{ extensions: ['esfsm'], contentType: 'json', editorType: 'json', addressableType: 'json', wechatPackInclude: true, hasTransitiveDeps: false },// Behavior tree (registerBt / BtAssetLoader) — data-driven BT definition.@@ -76,6 +78,7 @@ const MIME_MAP: Record<string, string> = {esprefab: 'application/json',esanim: 'application/json',estimeline: 'application/json',+ eslocale: 'application/json',esfsm: 'application/json',esbt: 'application/json',bmfont: 'application/json',diff --git a/sdk/src/core-content.ts b/sdk/src/core-content.tsindex ccf493bd4..fedf173cc 100644--- a/sdk/src/core-content.ts+++ b/sdk/src/core-content.ts@@ -70,6 +70,7 @@ export {type AssetsData,type TextureInfo,type SpineLoadResult,+ type LocaleResult,type AssetRefInfo,} from './asset';diff --git a/sdk/src/core-sys.ts b/sdk/src/core-sys.tsindex 07e98c355..85a8846a4 100644--- a/sdk/src/core-sys.ts+++ b/sdk/src/core-sys.ts@@ -30,6 +30,8 @@ export {interpolate,selectPluralForm,defaultPluralSelector,+ parseLocaleTable,+ type LocaleTableAsset,type LocalizationOptions,type PluralCategory,type PluralForms,diff --git a/sdk/src/i18n/Localization.ts b/sdk/src/i18n/Localization.tsindex 86f499b48..13bff9a2f 100644--- a/sdk/src/i18n/Localization.ts+++ b/sdk/src/i18n/Localization.ts@@ -118,3 +118,53 @@ export class LocalizationApi {* `app.getResource(Localization)`.*/export const Localization = defineResource<LocalizationApi>(null!, 'Localization');++// =============================================================================+// String-table asset (`.eslocale`)+// =============================================================================++/**+ * The serialized shape of a `.eslocale` asset — ONE locale's catalog, shipped+ * as data (via `Assets.loadLocaleTable`) instead of baked into code. Ship one+ * file per locale so a game loads only the languages it needs.+ */+export interface LocaleTableAsset {+ version: number;+ /** BCP-47-ish tag the entries register under (e.g. 'en', 'zh-CN'). */+ locale: string;+ entries: LocaleCatalog;+}++const LOCALE_TABLE_VERSION = 1;++/**+ * Parse + validate `.eslocale` text. Fail-loud: a malformed table names the+ * offending file and field instead of silently registering nothing. Pure.+ */+export function parseLocaleTable(text: string, path: string): LocaleTableAsset {+ let raw: unknown;+ try {+ raw = JSON.parse(text);+ } catch (e) {+ throw new Error(`${path}: not valid JSON — ${e instanceof Error ? e.message : String(e)}`);+ }+ const table = raw as Partial<LocaleTableAsset>;+ if (typeof table !== 'object' || table === null) {+ throw new Error(`${path}: expected an object { version, locale, entries }`);+ }+ if (table.version !== undefined && table.version !== LOCALE_TABLE_VERSION) {+ throw new Error(`${path}: unsupported locale-table version ${String(table.version)} (expected ${LOCALE_TABLE_VERSION})`);+ }+ if (typeof table.locale !== 'string' || table.locale.length === 0) {+ throw new Error(`${path}: 'locale' must be a non-empty string (e.g. "en", "zh-CN")`);+ }+ if (typeof table.entries !== 'object' || table.entries === null || Array.isArray(table.entries)) {+ throw new Error(`${path}: 'entries' must be an object of key → string | plural forms`);+ }+ for (const [key, entry] of Object.entries(table.entries)) {+ if (typeof entry === 'string') continue;+ if (typeof entry === 'object' && entry !== null && typeof (entry as PluralForms).other === 'string') continue;+ throw new Error(`${path}: entry '${key}' must be a string or plural forms with an 'other' catch-all`);+ }+ return { version: LOCALE_TABLE_VERSION, locale: table.locale, entries: table.entries };+}diff --git a/sdk/src/i18n/LocalizationPlugin.ts b/sdk/src/i18n/LocalizationPlugin.tsindex d3278ea30..48eb7f5b0 100644--- a/sdk/src/i18n/LocalizationPlugin.ts+++ b/sdk/src/i18n/LocalizationPlugin.ts@@ -5,8 +5,10 @@* @brief Registers the per-App Localization resource. Opt-in: add it via* `app.addPlugin(localizationPlugin)` or with options.*/-import type { App, Plugin } from '../app';+import { Schedule, defineSystem } from '../system';+import { Assets } from '../asset/AssetPlugin';+import { log } from '../logger';import { Localization, LocalizationApi, type LocaleCatalog } from './Localization';export interface LocalizationOptions {@@ -16,6 +18,12 @@ export interface LocalizationOptions {fallback?: string;/** Catalogs to preload, keyed by locale. */catalogs?: Record<string, LocaleCatalog>;+ /**+ * `.eslocale` string-table assets to load at startup (paths or `@uuid:`+ * refs). Loaded through the app's Assets resource — bound Text re-flows+ * the frame each table lands. Requires the AssetPlugin.+ */+ tables?: string[];}export class LocalizationPlugin implements Plugin {@@ -31,6 +39,26 @@ export class LocalizationPlugin implements Plugin {}}app.insertResource(Localization, loc);++ const tables = this.opts.tables;+ if (tables && tables.length > 0) {+ // Startup runs after every plugin build, so the Assets resource is+ // there regardless of install order. Loads are fire-and-forget —+ // the resolve system re-flows bound text the frame a table lands —+ // but a failed table is a shipped-content error: log it loud.+ app.addSystemToSchedule(Schedule.Startup, defineSystem([], () => {+ if (!app.hasResource(Assets)) {+ log.error('i18n', `LocalizationPlugin: 'tables' needs the AssetPlugin — ${tables.length} table(s) not loaded`);+ return;+ }+ const assets = app.getResource(Assets);+ for (const ref of tables) {+ assets.loadLocaleTable(ref).catch((e: unknown) => {+ log.error('i18n', `failed to load locale table ${ref}: ${e instanceof Error ? e.message : String(e)}`);+ });+ }+ }, { name: 'LocaleTableStartupSystem' }));+ }}}diff --git a/sdk/src/i18n/index.ts b/sdk/src/i18n/index.tsindex 586f325d4..6a5f7ab82 100644--- a/sdk/src/i18n/index.ts+++ b/sdk/src/i18n/index.ts@@ -11,6 +11,8 @@ export {interpolate,selectPluralForm,defaultPluralSelector,+ parseLocaleTable,+ type LocaleTableAsset,type PluralCategory,type PluralForms,type LocaleEntry,diff --git a/sdk/src/runtimeLoader.ts b/sdk/src/runtimeLoader.tsindex 1c307846a..48ad03a96 100644--- a/sdk/src/runtimeLoader.ts+++ b/sdk/src/runtimeLoader.ts@@ -24,6 +24,7 @@ import { SceneManager, type SceneConfig } from './sceneManager';import { DEFAULT_GRAVITY, DEFAULT_FIXED_TIMESTEP } from './defaults';import { SpriteAnimation } from './animation/SpriteAnimator';import { Audio } from './audio/Audio';+import { Localization } from './i18n/Localization';import { flushPendingSystems } from './app';import { requireResourceManager } from './resourceManager';import { log } from './logger';@@ -85,6 +86,7 @@ function ensureRuntimeAssets(catalog,getAudio: () => (app.hasResource(Audio) ? app.getResource(Audio) : null),getSpriteAnimation: () => (app.hasResource(SpriteAnimation) ? app.getResource(SpriteAnimation) : null),+ getLocalization: () => (app.hasResource(Localization) ? app.getResource(Localization) : null),});if (source.resolveRef) assets.setAssetRefResolver(source.resolveRef);diff --git a/sdk/src/ui/core/text.ts b/sdk/src/ui/core/text.tsindex 7f54b35ae..1c97658ab 100644--- a/sdk/src/ui/core/text.ts+++ b/sdk/src/ui/core/text.ts@@ -37,6 +37,14 @@ export type TextRenderMode = (typeof TextRenderMode)[keyof typeof TextRenderModeexport interface TextData {content: string;+ /**+ * Localization key. Non-empty ⇒ `content` is DERIVED: every frame the+ * text-localization system resolves the key through the app's Localization+ * resource (opt-in plugin) and writes the result into `content`, so a+ * `setLocale` re-flows every bound label. Empty (default) or no+ * Localization resource ⇒ `content` stands as authored.+ */+ i18nKey: string;fontFamily: string;fontSize: number;color: Color;@@ -61,6 +69,7 @@ export interface TextData {export const Text = defineComponent<TextData>('Text', {content: '',+ i18nKey: '',fontFamily: 'Arial',fontSize: 24,color: { r: 1, g: 1, b: 1, a: 1 },@@ -82,6 +91,7 @@ export const Text = defineComponent<TextData>('Text', {enabled: true,}, {fields: {+ i18nKey: { tooltip: 'Localization key — when set, content is resolved from the Localization catalogs (and re-resolved on locale switch). Leave empty for plain text.' },align: { enum: enumOptions(TextAlign), tooltip: 'Horizontal alignment: within the layout box when the entity has a UINode, else it anchors the text to the entity origin (left/center/right edge).' },verticalAlign: { enum: enumOptions(TextVerticalAlign), tooltip: 'Vertical alignment: within the layout box when the entity has a UINode, else it anchors the text to the entity origin (top/middle/bottom).' },overflow: { enum: enumOptions(TextOverflow) },diff --git a/sdk/src/ui/text/localize.ts b/sdk/src/ui/text/localize.tsnew file mode 100644index 000000000..37986f5c0--- /dev/null+++ b/sdk/src/ui/text/localize.ts@@ -0,0 +1,45 @@+// SPDX-License-Identifier: Apache-2.0+// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team+/**+ * @file ui/text/localize.ts+ * @brief The Text ↔ Localization binding: a Text whose `i18nKey` is set gets+ * its `content` written from the app's Localization catalogs.+ *+ * Runs as a frame system (TextPlugin registers it, gated on the Localization+ * resource being present — the plugin is opt-in). A frame-scan with a+ * diff-write is deliberately the whole design: UI labels number in the tens,+ * a no-param `t()` is one map lookup, and writing only on change keeps the+ * text renderer's caches cold — while `setLocale`/`addCatalog` re-flow every+ * bound label on the very next frame with zero extra bookkeeping.+ */+import type { Entity } from '../../types';+import type { LocalizationApi } from '../../i18n/Localization';+import { Text, type TextData } from '../core/text';++/** The slice of World the binding needs — mirrors FsmWorldView so tests can+ * drive it with an in-memory fake. */+export interface TextWorldView {+ getEntitiesWithComponents(components: unknown[]): readonly number[];+ get(entity: Entity, component: unknown): unknown;+ insert(entity: Entity, component: unknown, data: unknown): void;+}++/**+ * Resolve every bound Text once: non-empty `i18nKey` → `t(key)` → write+ * `content` when it differs (missing keys resolve to the key itself — the+ * catalogs' visible, greppable fallback). Returns how many contents changed.+ */+export function applyTextLocalization(world: TextWorldView, i18n: LocalizationApi): number {+ let changed = 0;+ for (const e of world.getEntitiesWithComponents([Text])) {+ const entity = e as Entity;+ const text = world.get(entity, Text) as TextData;+ if (!text.i18nKey) continue;+ const resolved = i18n.t(text.i18nKey);+ if (resolved === text.content) continue;+ text.content = resolved;+ world.insert(entity, Text, text);+ changed++;+ }+ return changed;+}diff --git a/sdk/src/ui/text/plugin.ts b/sdk/src/ui/text/plugin.tsindex 7a4491275..69def106f 100644--- a/sdk/src/ui/text/plugin.ts+++ b/sdk/src/ui/text/plugin.ts@@ -19,6 +19,8 @@ import type { RGBA } from './layout';import { composeTRS, rectTextBox, UI_TEXT_BOLD, UI_TEXT_ITALIC } from './text-transform';import { Text, TextRenderMode, type TextData } from '../core/text';import { UINode } from '../core/ui-node';+import { Localization } from '../../i18n/Localization';+import { applyTextLocalization, type TextWorldView } from './localize';import { UICameraInfo, type UICameraData } from '../core/ui-camera-info';import { getUINodeWidth, getUINodeHeight, ensureUIVisual } from '../util/helpers';import { platformDevicePixelRatio } from '../../platform';@@ -71,6 +73,15 @@ export class TextPlugin implements Plugin {}}, { name: 'TextRenderNodeSystem' }));+ // Localized text: an `i18nKey` binds content to the Localization+ // resource. Gated per frame on the resource so localizationPlugin+ // stays opt-in and install order doesn't matter; without it, authored+ // content stands (see ui/text/localize.ts for the resolve contract).+ app.addSystemToSchedule(Schedule.PreUpdate, defineSystem([], () => {+ if (!app.hasResource(Localization)) return;+ applyTextLocalization(world as unknown as TextWorldView, app.getResource(Localization));+ }, { name: 'TextLocalizeSystem' }));+const pipeline = app.pipeline;if (!pipeline) return; // logic-only host → nothing to drawdiff --git a/sdk/src/ui/widgets/helpers.ts b/sdk/src/ui/widgets/helpers.tsindex f728cdf6f..ed3fc976c 100644--- a/sdk/src/ui/widgets/helpers.ts+++ b/sdk/src/ui/widgets/helpers.ts@@ -125,6 +125,7 @@ export interface TextInit extends Partial<TextData> {}export function buildText(init: TextInit = {}): TextData {return {content: init.content ?? '',+ i18nKey: init.i18nKey ?? '',fontFamily: init.fontFamily ?? 'Arial',fontSize: init.fontSize ?? 14,color: init.color ?? { r: 1, g: 1, b: 1, a: 1 },diff --git a/sdk/src/ui/widgets/prefabs/Button.esprefab b/sdk/src/ui/widgets/prefabs/Button.esprefabindex 80ee5cb41..a29141788 100644--- a/sdk/src/ui/widgets/prefabs/Button.esprefab+++ b/sdk/src/ui/widgets/prefabs/Button.esprefab@@ -333,6 +333,7 @@"type": "Text","data": {"content": "Button",+ "i18nKey": "","fontFamily": "Arial","fontSize": 14,"color": {diff --git a/sdk/src/ui/widgets/prefabs/Dropdown.esprefab b/sdk/src/ui/widgets/prefabs/Dropdown.esprefabindex a4b8607a8..5e1e21b68 100644--- a/sdk/src/ui/widgets/prefabs/Dropdown.esprefab+++ b/sdk/src/ui/widgets/prefabs/Dropdown.esprefab@@ -333,6 +333,7 @@"type": "Text","data": {"content": "One",+ "i18nKey": "","fontFamily": "Arial","fontSize": 14,"color": {diff --git a/sdk/src/ui/widgets/prefabs/ListView.esprefab b/sdk/src/ui/widgets/prefabs/ListView.esprefabindex 4c692121d..a0a804975 100644--- a/sdk/src/ui/widgets/prefabs/ListView.esprefab+++ b/sdk/src/ui/widgets/prefabs/ListView.esprefab@@ -298,6 +298,7 @@"type": "Text","data": {"content": "List View",+ "i18nKey": "","fontFamily": "Arial","fontSize": 14,"color": {diff --git a/sdk/src/ui/widgets/prefabs/generated.ts b/sdk/src/ui/widgets/prefabs/generated.tsindex fdb11d418..3767801e3 100644--- a/sdk/src/ui/widgets/prefabs/generated.ts+++ b/sdk/src/ui/widgets/prefabs/generated.ts@@ -337,6 +337,7 @@ export const BUILTIN_UI_PREFABS: Record<string, PrefabData> = {"type": "Text","data": {"content": "Button",+ "i18nKey": "","fontFamily": "Arial","fontSize": 14,"color": {@@ -1859,6 +1860,7 @@ export const BUILTIN_UI_PREFABS: Record<string, PrefabData> = {"type": "Text","data": {"content": "One",+ "i18nKey": "","fontFamily": "Arial","fontSize": 14,"color": {@@ -2200,6 +2202,7 @@ export const BUILTIN_UI_PREFABS: Record<string, PrefabData> = {"type": "Text","data": {"content": "List View",+ "i18nKey": "","fontFamily": "Arial","fontSize": 14,"color": {diff --git a/sdk/tests/locale-table.test.ts b/sdk/tests/locale-table.test.tsnew file mode 100644index 000000000..0e1e9e51d--- /dev/null+++ b/sdk/tests/locale-table.test.ts@@ -0,0 +1,182 @@+// SPDX-License-Identifier: Apache-2.0+// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team+/**+ * The `.eslocale` string-table pipeline: parseLocaleTable's fail-loud+ * validation, the LocaleAssetLoader registering into the app's Localization,+ * and the Text ↔ Localization binding (applyTextLocalization) that turns an+ * `i18nKey` into live `content` and re-flows it on locale switch.+ */+import { describe, it, expect } from 'vitest';+import { LocalizationApi, parseLocaleTable } from '../src/i18n/Localization';+import { LocaleAssetLoader } from '../src/asset/loaders/LocaleAssetLoader';+import type { LoadContext } from '../src/asset/AssetLoader';+import { applyTextLocalization, type TextWorldView } from '../src/ui/text/localize';+import { Text, type TextData } from '../src/ui/core/text';+import type { Entity } from '../src/types';++// =============================================================================+// parseLocaleTable+// =============================================================================++describe('parseLocaleTable', () => {+ it('accepts a valid table (strings + plural forms)', () => {+ const table = parseLocaleTable(JSON.stringify({+ version: 1,+ locale: 'zh-CN',+ entries: { play: '开始', apples: { other: '{count} 个苹果' } },+ }), 'i18n/zh-CN.eslocale');+ expect(table.locale).toBe('zh-CN');+ expect(Object.keys(table.entries)).toEqual(['play', 'apples']);+ });++ it('accepts a missing version (defaults to current)', () => {+ const table = parseLocaleTable('{"locale":"en","entries":{}}', 'a.eslocale');+ expect(table.version).toBe(1);+ });++ it('names the file on malformed JSON', () => {+ expect(() => parseLocaleTable('{oops', 'bad.eslocale')).toThrow(/bad\.eslocale.*not valid JSON/);+ });++ it('rejects a missing/empty locale', () => {+ expect(() => parseLocaleTable('{"entries":{}}', 'x.eslocale')).toThrow(/'locale' must be a non-empty string/);+ expect(() => parseLocaleTable('{"locale":"","entries":{}}', 'x.eslocale')).toThrow(/'locale'/);+ });++ it('rejects missing or non-object entries', () => {+ expect(() => parseLocaleTable('{"locale":"en"}', 'x.eslocale')).toThrow(/'entries' must be an object/);+ expect(() => parseLocaleTable('{"locale":"en","entries":[1]}', 'x.eslocale')).toThrow(/'entries'/);+ });++ it('rejects an entry that is neither string nor plural-with-other, naming the key', () => {+ expect(() => parseLocaleTable('{"locale":"en","entries":{"bad":42}}', 'x.eslocale')).toThrow(/entry 'bad'/);+ expect(() => parseLocaleTable('{"locale":"en","entries":{"bad":{"one":"x"}}}', 'x.eslocale')).toThrow(/'other' catch-all/);+ });++ it('rejects an unsupported version', () => {+ expect(() => parseLocaleTable('{"version":9,"locale":"en","entries":{}}', 'x.eslocale')).toThrow(/version 9/);+ });+});++// =============================================================================+// LocaleAssetLoader+// =============================================================================++function loaderCtx(text: string, i18n: LocalizationApi | null): LoadContext {+ return {+ catalog: { getBuildPath: (p: string) => p },+ loadText: async () => text,+ getLocalization: () => i18n,+ } as unknown as LoadContext;+}++describe('LocaleAssetLoader', () => {+ it('merges the table into the app catalogs and reports locale + key count', async () => {+ const i18n = new LocalizationApi('en', 'en');+ const loader = new LocaleAssetLoader();+ const result = await loader.load('i18n/zh-CN.eslocale', loaderCtx(JSON.stringify({+ version: 1,+ locale: 'zh-CN',+ entries: { play: '开始', quit: '退出' },+ }), i18n));+ expect(result).toEqual({ locale: 'zh-CN', keyCount: 2 });+ i18n.setLocale('zh-CN');+ expect(i18n.t('play')).toBe('开始');+ });++ it('fails loud without a Localization resource', async () => {+ const loader = new LocaleAssetLoader();+ await expect(loader.load('i18n/en.eslocale', loaderCtx('{"locale":"en","entries":{}}', null)))+ .rejects.toThrow(/localizationPlugin/);+ });++ it('propagates table validation errors (bad content never half-registers)', async () => {+ const i18n = new LocalizationApi('en', 'en');+ const loader = new LocaleAssetLoader();+ await expect(loader.load('i18n/en.eslocale', loaderCtx('{"entries":{}}', i18n)))+ .rejects.toThrow(/'locale'/);+ expect(i18n.availableLocales()).toEqual([]);+ });+});++// =============================================================================+// applyTextLocalization (the Text ↔ Localization binding)+// =============================================================================++/** Minimal in-memory world with only Text components. */+class FakeWorld implements TextWorldView {+ private texts = new Map<number, TextData>();+ private next = 1;+ inserts = 0;++ spawn(data: Partial<TextData>): Entity {+ const e = this.next++;+ this.texts.set(e, Text.create(data));+ return e as Entity;+ }+ text(e: Entity): TextData {+ return this.texts.get(e as number)!;+ }+ getEntitiesWithComponents(): readonly number[] {+ return [...this.texts.keys()];+ }+ get(entity: Entity): unknown {+ return this.texts.get(entity as number);+ }+ insert(entity: Entity, _c: unknown, data: unknown): void {+ this.texts.set(entity as number, data as TextData);+ this.inserts++;+ }+}++describe('applyTextLocalization', () => {+ function setup() {+ const world = new FakeWorld();+ const i18n = new LocalizationApi('en', 'en');+ i18n.addCatalog('en', { play: 'Play' });+ i18n.addCatalog('zh-CN', { play: '开始' });+ return { world, i18n };+ }++ it('writes resolved content for a bound key; plain text is untouched', () => {+ const { world, i18n } = setup();+ const bound = world.spawn({ i18nKey: 'play' });+ const plain = world.spawn({ content: 'hand-written' });+ expect(applyTextLocalization(world, i18n)).toBe(1);+ expect(world.text(bound).content).toBe('Play');+ expect(world.text(plain).content).toBe('hand-written');+ });++ it('re-flows on locale switch, and diff-writes (no redundant inserts)', () => {+ const { world, i18n } = setup();+ const e = world.spawn({ i18nKey: 'play' });+ applyTextLocalization(world, i18n);+ expect(world.inserts).toBe(1);++ // Same locale, same key → resolved equals content → zero writes.+ expect(applyTextLocalization(world, i18n)).toBe(0);+ expect(world.inserts).toBe(1);++ i18n.setLocale('zh-CN');+ expect(applyTextLocalization(world, i18n)).toBe(1);+ expect(world.text(e).content).toBe('开始');+ });++ it('a missing key resolves to the key itself (greppable fallback)', () => {+ const { world, i18n } = setup();+ const e = world.spawn({ i18nKey: 'no.such.key', content: 'authored' });+ applyTextLocalization(world, i18n);+ expect(world.text(e).content).toBe('no.such.key');+ });++ it('a late-loaded catalog re-flows already-bound text (the .eslocale flow)', () => {+ const { world, i18n } = setup();+ const e = world.spawn({ i18nKey: 'quit' });+ applyTextLocalization(world, i18n);+ expect(world.text(e).content).toBe('quit'); // not shipped yet → key++ i18n.addCatalog('en', { quit: 'Quit' }); // table lands (LocaleAssetLoader)+ applyTextLocalization(world, i18n);+ expect(world.text(e).content).toBe('Quit');+ });+});