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): per-App localization with interpolation + pluggable plurals (T4)
yhhb1504ebb01e5
diff --git a/sdk/src/core-sys.ts b/sdk/src/core-sys.tsindex 0de249d31..1d4a02f38 100644--- a/sdk/src/core-sys.ts+++ b/sdk/src/core-sys.ts@@ -18,6 +18,27 @@export { scalar, v2, v3 } from './math';+// =============================================================================+// Localization (i18n)+// =============================================================================++export {+ Localization,+ LocalizationApi,+ LocalizationPlugin,+ localizationPlugin,+ interpolate,+ selectPluralForm,+ defaultPluralSelector,+ type LocalizationOptions,+ type PluralCategory,+ type PluralForms,+ type LocaleEntry,+ type LocaleCatalog,+ type TParams,+ type PluralSelector,+} from './i18n';+// =============================================================================// Entity Utils// =============================================================================diff --git a/sdk/src/i18n/Localization.ts b/sdk/src/i18n/Localization.tsnew file mode 100644index 000000000..86f499b48--- /dev/null+++ b/sdk/src/i18n/Localization.ts@@ -0,0 +1,120 @@+// SPDX-License-Identifier: Apache-2.0+// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team+/**+ * @file Localization.ts+ * @brief String localization (pure TypeScript). A per-App catalog registry ++ * `t(key, params)` with `{placeholder}` interpolation and pluggable+ * plural rules. Deliberately free of `Intl` so it behaves identically+ * on web and WeChat (which lacks full Intl); supply a PluralSelector+ * per locale for languages whose rules differ from the default.+ */++import { defineResource } from '../resource';++export type PluralCategory = 'zero' | 'one' | 'two' | 'few' | 'many' | 'other';++/** A pluralized message. `other` is required (the catch-all). */+export interface PluralForms {+ zero?: string;+ one?: string;+ two?: string;+ few?: string;+ many?: string;+ other: string;+}++export type LocaleEntry = string | PluralForms;+export type LocaleCatalog = Record<string, LocaleEntry>;+export type TParams = Record<string, string | number>;+export type PluralSelector = (count: number) => PluralCategory;++/** Default (English-like) rule: exactly 1 → `one`, everything else → `other`.+ * `zero` is honored separately by selectPluralForm when count is 0. */+export const defaultPluralSelector: PluralSelector = (count) => (count === 1 ? 'one' : 'other');++/** Replace `{name}` placeholders from `params`; unknown placeholders are left+ * intact so a missing binding is visible rather than silently blank. Pure. */+export function interpolate(template: string, params?: TParams): string {+ if (!params) return template;+ return template.replace(/\{(\w+)\}/g, (whole, key: string) =>+ Object.prototype.hasOwnProperty.call(params, key) ? String(params[key]) : whole,+ );+}++/** Pick a plural form: explicit `zero` when count is 0, else the selector's+ * category, falling back to `other`. Pure. */+export function selectPluralForm(forms: PluralForms, count: number, selector: PluralSelector): string {+ if (count === 0 && forms.zero !== undefined) return forms.zero;+ const category = selector(count);+ return forms[category] ?? forms.other;+}++/**+ * Per-App localization service: catalogs keyed by locale, an active locale + a+ * fallback, and `t()` resolution (active → fallback → the key itself). Published+ * as the {@link Localization} resource; read it as `app.getResource(Localization)`.+ */+export class LocalizationApi {+ private readonly catalogs = new Map<string, Map<string, LocaleEntry>>();+ private readonly selectors = new Map<string, PluralSelector>();+ private locale_: string;+ private fallback_: string;++ constructor(locale = 'en', fallback = 'en') {+ this.locale_ = locale;+ this.fallback_ = fallback;+ }++ /** Merge `entries` into a locale's catalog (later calls override keys). */+ addCatalog(locale: string, entries: LocaleCatalog): void {+ let m = this.catalogs.get(locale);+ if (!m) { m = new Map(); this.catalogs.set(locale, m); }+ for (const k of Object.keys(entries)) m.set(k, entries[k]);+ }++ setLocale(locale: string): void { this.locale_ = locale; }+ get locale(): string { return this.locale_; }++ setFallbackLocale(locale: string): void { this.fallback_ = locale; }+ get fallbackLocale(): string { return this.fallback_; }++ /** Override the plural rule for a locale (e.g. languages with few/many). */+ setPluralSelector(locale: string, selector: PluralSelector): void {+ this.selectors.set(locale, selector);+ }++ /** Locales that have a catalog, in insertion order. */+ availableLocales(): string[] {+ return [...this.catalogs.keys()];+ }++ /** True if the key resolves in the active locale or the fallback. */+ has(key: string): boolean {+ return this.lookup_(key) !== undefined;+ }++ /**+ * Translate `key`, interpolating `{params}`. A pluralized entry selects a+ * form from `params.count` (default 0). Unknown keys return the key itself+ * (a visible, greppable fallback) rather than throwing.+ */+ t(key: string, params?: TParams): string {+ const entry = this.lookup_(key);+ if (entry === undefined) return key;+ if (typeof entry === 'string') return interpolate(entry, params);+ const count = typeof params?.count === 'number' ? params.count : 0;+ const selector = this.selectors.get(this.locale_) ?? defaultPluralSelector;+ return interpolate(selectPluralForm(entry, count, selector), params);+ }++ private lookup_(key: string): LocaleEntry | undefined {+ return this.catalogs.get(this.locale_)?.get(key)+ ?? this.catalogs.get(this.fallback_)?.get(key);+ }+}++/**+ * Per-App localization resource, published by `LocalizationPlugin`. Read as+ * `app.getResource(Localization)`.+ */+export const Localization = defineResource<LocalizationApi>(null!, 'Localization');diff --git a/sdk/src/i18n/LocalizationPlugin.ts b/sdk/src/i18n/LocalizationPlugin.tsnew file mode 100644index 000000000..d3278ea30--- /dev/null+++ b/sdk/src/i18n/LocalizationPlugin.ts@@ -0,0 +1,37 @@+// SPDX-License-Identifier: Apache-2.0+// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team+/**+ * @file LocalizationPlugin.ts+ * @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 { Localization, LocalizationApi, type LocaleCatalog } from './Localization';++export interface LocalizationOptions {+ /** Active locale (default 'en'). */+ locale?: string;+ /** Fallback locale when a key is missing in the active one (default 'en'). */+ fallback?: string;+ /** Catalogs to preload, keyed by locale. */+ catalogs?: Record<string, LocaleCatalog>;+}++export class LocalizationPlugin implements Plugin {+ name = 'localization';++ constructor(private readonly opts: LocalizationOptions = {}) {}++ build(app: App): void {+ const loc = new LocalizationApi(this.opts.locale, this.opts.fallback);+ if (this.opts.catalogs) {+ for (const locale of Object.keys(this.opts.catalogs)) {+ loc.addCatalog(locale, this.opts.catalogs[locale]);+ }+ }+ app.insertResource(Localization, loc);+ }+}++export const localizationPlugin = new LocalizationPlugin();diff --git a/sdk/src/i18n/index.ts b/sdk/src/i18n/index.tsnew file mode 100644index 000000000..586f325d4--- /dev/null+++ b/sdk/src/i18n/index.ts@@ -0,0 +1,26 @@+// SPDX-License-Identifier: Apache-2.0+// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team+/**+ * @file index.ts+ * @brief Localization (i18n) module barrel.+ */++export {+ Localization,+ LocalizationApi,+ interpolate,+ selectPluralForm,+ defaultPluralSelector,+ type PluralCategory,+ type PluralForms,+ type LocaleEntry,+ type LocaleCatalog,+ type TParams,+ type PluralSelector,+} from './Localization';++export {+ LocalizationPlugin,+ localizationPlugin,+ type LocalizationOptions,+} from './LocalizationPlugin';diff --git a/sdk/tests/i18n.test.ts b/sdk/tests/i18n.test.tsnew file mode 100644index 000000000..efac281da--- /dev/null+++ b/sdk/tests/i18n.test.ts@@ -0,0 +1,99 @@+// SPDX-License-Identifier: Apache-2.0+// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team+import { describe, it, expect } from 'vitest';+import {+ LocalizationApi,+ interpolate,+ selectPluralForm,+ defaultPluralSelector,+ type PluralSelector,+} from '../src/i18n/Localization';++describe('interpolate', () => {+ it('replaces {placeholders} from params', () => {+ expect(interpolate('Hello {name}!', { name: 'Bob' })).toBe('Hello Bob!');+ expect(interpolate('{a}+{b}={c}', { a: 1, b: 2, c: 3 })).toBe('1+2=3');+ });+ it('leaves unknown placeholders intact', () => {+ expect(interpolate('Hi {name}', {})).toBe('Hi {name}');+ expect(interpolate('Hi {name}')).toBe('Hi {name}');+ });+});++describe('selectPluralForm', () => {+ const forms = { zero: 'no items', one: 'one item', other: '{count} items' };+ it('honors explicit zero at count 0', () => {+ expect(selectPluralForm(forms, 0, defaultPluralSelector)).toBe('no items');+ });+ it('default selector: 1 → one, else other', () => {+ expect(selectPluralForm(forms, 1, defaultPluralSelector)).toBe('one item');+ expect(selectPluralForm(forms, 5, defaultPluralSelector)).toBe('{count} items');+ });+ it('falls back to other when a category form is absent', () => {+ expect(selectPluralForm({ other: 'x' }, 1, defaultPluralSelector)).toBe('x');+ });+ it('supports a custom selector', () => {+ const ru: PluralSelector = (n) => (n % 10 === 1 && n % 100 !== 11 ? 'one' : 'many');+ expect(selectPluralForm({ one: 'один', many: 'много', other: 'o' }, 21, ru)).toBe('один');+ expect(selectPluralForm({ one: 'один', many: 'много', other: 'o' }, 5, ru)).toBe('много');+ });+});++describe('LocalizationApi', () => {+ function setup() {+ const loc = new LocalizationApi('en', 'en');+ loc.addCatalog('en', {+ greeting: 'Hello {name}',+ apples: { zero: 'no apples', one: 'one apple', other: '{count} apples' },+ onlyEn: 'english only',+ });+ loc.addCatalog('zh', {+ greeting: '你好 {name}',+ apples: { other: '{count} 个苹果' },+ });+ return loc;+ }++ it('translates + interpolates in the active locale', () => {+ const loc = setup();+ expect(loc.t('greeting', { name: 'Bob' })).toBe('Hello Bob');+ loc.setLocale('zh');+ expect(loc.t('greeting', { name: '小明' })).toBe('你好 小明');+ });++ it('pluralizes from params.count', () => {+ const loc = setup();+ expect(loc.t('apples', { count: 0 })).toBe('no apples');+ expect(loc.t('apples', { count: 1 })).toBe('one apple');+ expect(loc.t('apples', { count: 7 })).toBe('7 apples');+ loc.setLocale('zh');+ expect(loc.t('apples', { count: 3 })).toBe('3 个苹果');+ });++ it('falls back to the fallback locale for missing keys', () => {+ const loc = setup();+ loc.setLocale('zh'); // zh has no 'onlyEn'+ expect(loc.t('onlyEn')).toBe('english only');+ });++ it('returns the key itself when unresolved anywhere', () => {+ const loc = setup();+ expect(loc.t('does.not.exist')).toBe('does.not.exist');+ expect(loc.has('does.not.exist')).toBe(false);+ expect(loc.has('greeting')).toBe(true);+ });++ it('addCatalog merges (later overrides)', () => {+ const loc = setup();+ loc.addCatalog('en', { greeting: 'Hi {name}' });+ expect(loc.t('greeting', { name: 'A' })).toBe('Hi A');+ expect(loc.t('onlyEn')).toBe('english only'); // untouched+ });++ it('availableLocales + custom plural selector', () => {+ const loc = setup();+ expect(loc.availableLocales()).toEqual(['en', 'zh']);+ loc.setPluralSelector('en', () => 'other');+ expect(loc.t('apples', { count: 1 })).toBe('1 apples'); // selector forces other+ });+});