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.

Support localized text input placeholders

yhhce652e7b122c
diff --git a/examples/ui-localization-debug/README.md b/examples/ui-localization-debug/README.md
index 41f965d5e..3e16841ab 100644
--- a/examples/ui-localization-debug/README.md
+++ b/examples/ui-localization-debug/README.md
@@ -169,3 +169,25 @@ In the Play fixture, L enables caption binding and switches English/Chinese;
P toggles length-stress preview and U replaces the active catalog entry.
These shortcuts exercise the actual localization binding helper and rendered
Text on Inside, including warmed-cache invalidation. Reopen Play to reset them.
+
+
+TextInput and createTextInput now accept optional `placeholderI18nKey`. With a
+Localization resource, an empty field resolves this key every frame through
+`t`; locale, catalog and preview updates apply immediately. A missing entry
+shows its key, matching Text binding; an intentionally empty translation stays
+empty. Without a resource or with an empty key, the literal placeholder is used.
+The authored placeholder, value and native editing state are not rewritten.
+Scene-authored placeholder bindings trigger runtime localization/table loading,
+including scenes with no localized Text. Dynamically created fields need the
+app's LocalizationPlugin already installed.
+
+The Play fixture includes a scene-authored Localized input. Its binding causes
+the production loader to install Localization; the fixture script supplies the
+English/Chinese catalogs. Start Play shows Your name, L shows 请输入姓名, P
+expands the hint and U replaces it with Updated hint 更新提示. Turn P off to
+read the updated hint. Click the field and type hello; click an empty game area
+and press L again: the caption switches language while hello remains. T-created
+inputs bind the same hint key. Shortcuts intentionally do not run while editing.
+This verifies the built SDK TextInput plugin in the actual Web/WASM Play host;
+it does not certify a device IME session or focus preservation during an
+application-triggered locale switch inside an active IME composition.
diff --git a/sdk/etc/index.api.md b/sdk/etc/index.api.md
index dc0c46f52..e8e9ce04a 100644
--- a/sdk/etc/index.api.md
+++ b/sdk/etc/index.api.md
@@ -8523,6 +8523,7 @@ padding: number
password: boolean
placeholder: string
placeholderColor: Color
+placeholderI18nKey: string | undefined
readOnly: boolean
renderMode: TextRenderMode
textAlign: TextAlign
@@ -8555,6 +8556,7 @@ parent: number | undefined
password: boolean | undefined
placeholder: string | undefined
placeholderColor: Color | undefined
+placeholderI18nKey: string | undefined
readOnly: boolean | undefined
renderMode: TextRenderMode | undefined
tabIndex: number | undefined
diff --git a/sdk/etc/index.native.api.md b/sdk/etc/index.native.api.md
index 6a25b55ce..d983f0ed0 100644
--- a/sdk/etc/index.native.api.md
+++ b/sdk/etc/index.native.api.md
@@ -8724,6 +8724,7 @@ padding: number
password: boolean
placeholder: string
placeholderColor: Color
+placeholderI18nKey: string | undefined
readOnly: boolean
renderMode: TextRenderMode
textAlign: TextAlign
@@ -8756,6 +8757,7 @@ parent: number | undefined
password: boolean | undefined
placeholder: string | undefined
placeholderColor: Color | undefined
+placeholderI18nKey: string | undefined
readOnly: boolean | undefined
renderMode: TextRenderMode | undefined
tabIndex: number | undefined
diff --git a/sdk/etc/index.node.api.md b/sdk/etc/index.node.api.md
index 5bc846b98..463665f1c 100644
--- a/sdk/etc/index.node.api.md
+++ b/sdk/etc/index.node.api.md
@@ -8518,6 +8518,7 @@ padding: number
password: boolean
placeholder: string
placeholderColor: Color
+placeholderI18nKey: string | undefined
readOnly: boolean
renderMode: TextRenderMode
textAlign: TextAlign
@@ -8550,6 +8551,7 @@ parent: number | undefined
password: boolean | undefined
placeholder: string | undefined
placeholderColor: Color | undefined
+placeholderI18nKey: string | undefined
readOnly: boolean | undefined
renderMode: TextRenderMode | undefined
tabIndex: number | undefined
diff --git a/sdk/etc/minigame.api.md b/sdk/etc/minigame.api.md
index 48ff6d749..02add0c88 100644
--- a/sdk/etc/minigame.api.md
+++ b/sdk/etc/minigame.api.md
@@ -8791,6 +8791,7 @@ padding: number
password: boolean
placeholder: string
placeholderColor: Color
+placeholderI18nKey: string | undefined
readOnly: boolean
renderMode: TextRenderMode
textAlign: TextAlign
@@ -8823,6 +8824,7 @@ parent: number | undefined
password: boolean | undefined
placeholder: string | undefined
placeholderColor: Color | undefined
+placeholderI18nKey: string | undefined
readOnly: boolean | undefined
renderMode: TextRenderMode | undefined
tabIndex: number | undefined
diff --git a/sdk/etc/wechat.api.md b/sdk/etc/wechat.api.md
index 49796187b..0eb7c6ac8 100644
--- a/sdk/etc/wechat.api.md
+++ b/sdk/etc/wechat.api.md
@@ -8525,6 +8525,7 @@ padding: number
password: boolean
placeholder: string
placeholderColor: Color
+placeholderI18nKey: string | undefined
readOnly: boolean
renderMode: TextRenderMode
textAlign: TextAlign
@@ -8557,6 +8558,7 @@ parent: number | undefined
password: boolean | undefined
placeholder: string | undefined
placeholderColor: Color | undefined
+placeholderI18nKey: string | undefined
readOnly: boolean | undefined
renderMode: TextRenderMode | undefined
tabIndex: number | undefined
diff --git a/sdk/src/runtime/runtimeLoader.ts b/sdk/src/runtime/runtimeLoader.ts
index b251a6e78..9abe4a756 100644
--- a/sdk/src/runtime/runtimeLoader.ts
+++ b/sdk/src/runtime/runtimeLoader.ts
@@ -242,14 +242,15 @@ export function sceneUses3DPhysics(sceneData: SceneData): boolean {
return false;
}
-/** True if any Text binds its content to a localization key — the scene needs
+/** True if any Text or TextInput hint binds to a localization key — the scene needs
* the Localization resource + the project's `.eslocale` tables to render as
* authored (an unbound key would show as the raw key string). */
export function sceneUsesI18n(sceneData: SceneData): boolean {
for (const entity of sceneData.entities ?? []) {
for (const comp of entity.components ?? []) {
- if (comp.type !== 'Text') continue;
- const key = (comp.data as { i18nKey?: unknown } | undefined)?.i18nKey;
+ const data = comp.data as { i18nKey?: unknown; placeholderI18nKey?: unknown } | undefined;
+ const key = comp.type === 'Text' ? data?.i18nKey
+ : comp.type === 'TextInput' ? data?.placeholderI18nKey : undefined;
if (typeof key === 'string' && key.length > 0) return true;
}
}
@@ -527,7 +528,7 @@ export async function prepareRuntimeScene(
if (autoInstalled) app.addPlugin(new LocalizationPlugin());
const tables = (source.listAssetPaths?.() ?? []).filter((p) => p.toLowerCase().endsWith('.eslocale'));
if (tables.length === 0) {
- log.warn('i18n', 'scene binds Text.i18nKey but this realm lists no .eslocale tables — keys will render raw');
+ log.warn('i18n', 'scene binds a localization key but this realm lists no .eslocale tables — keys will render raw');
} else {
await Promise.all(tables.map((p) => sceneAssets.loadLocaleTable(p).catch((e: unknown) => {
log.error('i18n', `locale table ${p} failed to load: ${e instanceof Error ? e.message : String(e)}`);
diff --git a/sdk/src/ui/text/text-input-plugin.ts b/sdk/src/ui/text/text-input-plugin.ts
index 6497be428..10c298942 100644
--- a/sdk/src/ui/text/text-input-plugin.ts
+++ b/sdk/src/ui/text/text-input-plugin.ts
@@ -36,6 +36,7 @@ import { platformCreateTextEditor, platformDevicePixelRatio } from '../../platfo
import { CURSOR_BLINK_INTERVAL, TEXT_INPUT_LINE_HEIGHT_RATIO } from '../util/constants';
import { SystemLabel, PluginName } from '../../ecs/systemLabels';
import { log } from '../../util/logger';
+import { Localization } from '../../i18n/Localization';
/** Masking bullet for password fields. */
const PASSWORD_CHAR = '●';
@@ -420,7 +421,8 @@ export class TextInputPlugin implements Plugin {
world.update(entity, TextInput, (d) => { d.cursorPos = sel.caret; });
}
- const disp = textFieldDisplay(val, ti.password, ti.placeholder, PASSWORD_CHAR);
+ const disp = textFieldDisplay(val, ti.password, ti.placeholder, PASSWORD_CHAR,
+ ti.placeholderI18nKey, app.hasResource(Localization) ? app.getResource(Localization) : undefined);
const atlas = ensureMeasure().atlas;
const family = resolveTextFamily(ti.font, ti.fontFamily);
const mw = (s: string): number => measureWidth(s, atlas, family, ti.fontSize, 0);
diff --git a/sdk/src/ui/text/text-input-view.ts b/sdk/src/ui/text/text-input-view.ts
index 1798aa5c4..e820acac8 100644
--- a/sdk/src/ui/text/text-input-view.ts
+++ b/sdk/src/ui/text/text-input-view.ts
@@ -12,6 +12,8 @@
* IME preedit, and native shift/Ctrl-A selection all land there).
*/
+import type { LocalizationAPI } from '../../i18n/Localization';
+
export interface TextFieldDisplay {
/** The glyph string to render: the value, the placeholder when empty, or a
* run of bullets when the field is a password. */
@@ -27,8 +29,13 @@ export function textFieldDisplay(
password: boolean,
placeholder: string,
bullet: string,
+ placeholderI18nKey?: string,
+ localization?: Pick<LocalizationAPI, 't'>,
): TextFieldDisplay {
- if (value.length === 0) return { text: placeholder, isPlaceholder: true };
+ if (value.length === 0) return {
+ text: placeholderI18nKey && localization ? localization.t(placeholderI18nKey) : placeholder,
+ isPlaceholder: true,
+ };
return { text: password ? bullet.repeat(value.length) : value, isPlaceholder: false };
}
diff --git a/sdk/src/ui/text/text-input.ts b/sdk/src/ui/text/text-input.ts
index 641ab79f7..7bcac7950 100644
--- a/sdk/src/ui/text/text-input.ts
+++ b/sdk/src/ui/text/text-input.ts
@@ -7,6 +7,8 @@ import { TextAlign, TextRenderMode } from '../core/text';
export interface TextInputData {
value: string;
placeholder: string;
+ /** Optional catalog key for the displayed hint. Does not change the value or authored placeholder. */
+ placeholderI18nKey?: string;
placeholderColor: Color;
/** A font asset the game SHIPS. When set it wins over {@link fontFamily},
* exactly as `Text.font` does — a field on a skinned panel is drawn in the
@@ -35,6 +37,7 @@ export interface TextInputData {
export const TextInput = defineComponent<TextInputData>('TextInput', {
value: '',
placeholder: '',
+ placeholderI18nKey: '',
placeholderColor: { r: 0.6, g: 0.6, b: 0.6, a: 1 },
font: 0,
fontFamily: '',
@@ -53,6 +56,7 @@ export const TextInput = defineComponent<TextInputData>('TextInput', {
}, {
assetFields: [{ field: 'font', type: 'font' }],
fields: {
+ placeholderI18nKey: { label: 'Placeholder I18n Key', enumSource: 'localeKeys', tooltip: 'Translate the empty-field hint through the Localization resource. Leave empty for a literal placeholder.' },
font: { label: 'Font', tooltip: 'A font file this project ships (.ttf / .otf). Overrides Font Family when set; leave empty to use a font the host already has.' },
fontFamily: { tooltip: 'A font the HOST already has (system or page-loaded). Ignored when Font is set.' },
textAlign: {
diff --git a/sdk/src/ui/widgets/text-input.ts b/sdk/src/ui/widgets/text-input.ts
index bf77a3bf7..8e73ccb0b 100644
--- a/sdk/src/ui/widgets/text-input.ts
+++ b/sdk/src/ui/widgets/text-input.ts
@@ -22,6 +22,8 @@ export interface TextInputOptions {
value?: string;
placeholder?: string;
+ /** Catalog key for the empty-field hint; requires a Localization resource. */
+ placeholderI18nKey?: string;
fontFamily?: string;
/** Default: the theme's label size. */
fontSize?: number;
@@ -76,6 +78,7 @@ export function createTextInput(opts: TextInputOptions): TextInputHandle {
world.insert(entity, TextInput, {
value: opts.value ?? '',
placeholder: opts.placeholder ?? '',
+ placeholderI18nKey: opts.placeholderI18nKey ?? '',
placeholderColor: opts.placeholderColor ?? { ...c.text, a: c.text.a * 0.5 },
fontFamily: opts.fontFamily ?? '',
fontSize: opts.fontSize ?? themeType().label,
diff --git a/sdk/tests/locale-table.test.ts b/sdk/tests/locale-table.test.ts
index f78f817f6..d0a23a87f 100644
--- a/sdk/tests/locale-table.test.ts
+++ b/sdk/tests/locale-table.test.ts
@@ -91,6 +91,13 @@ describe('sceneUsesI18n', () => {
entities: [{ id: 1, name: 'E', parent: null, children: [], components }],
} as unknown as SceneData);
+ it('detects placeholder-only scenes and rejects unrelated or malformed bindings', () => {
+ expect(sceneUsesI18n(scene([{ type: 'TextInput', data: { placeholderI18nKey: 'hint' } }]))).toBe(true);
+ for (const data of [undefined, {}, { placeholderI18nKey: '' }, { placeholderI18nKey: 42 }, { i18nKey: 'hint' }])
+ expect(sceneUsesI18n(scene([{ type: 'TextInput', data }]))).toBe(false);
+ expect(sceneUsesI18n(scene([{ type: 'Sprite', data: { placeholderI18nKey: 'hint' } }]))).toBe(false);
+ });
+
it('true only for a Text with a non-empty i18nKey', () => {
expect(sceneUsesI18n(scene([{ type: 'Text', data: { i18nKey: 'menu.play' } }]))).toBe(true);
expect(sceneUsesI18n(scene([{ type: 'Text', data: { i18nKey: '' } }]))).toBe(false);
diff --git a/sdk/tests/ui-text-input-view.test.ts b/sdk/tests/ui-text-input-view.test.ts
index b1266ec6e..76fd3e30d 100644
--- a/sdk/tests/ui-text-input-view.test.ts
+++ b/sdk/tests/ui-text-input-view.test.ts
@@ -15,6 +15,8 @@ import {
splitLines, caretLineCol, lineSelections, imeAnchorCss,
} from '../src/ui/text/text-input-view';
+import { LocalizationAPI } from '../src/i18n/Localization';
+
const BULLET = '●';
describe('textFieldDisplay', () => {
@@ -215,3 +217,39 @@ describe('alignOffset', () => {
expect(alignOffset(2, -10, 40)).toBe(0);
});
});
+
+
+describe('localized placeholders', () => {
+ it('tracks locale, catalog and preview changes without rewriting authored data', () => {
+ const locale = new LocalizationAPI();
+ locale.addCatalog('en', { hint: 'Your name' });
+ locale.addCatalog('zh', { hint: '姓名' });
+ const field = { value: '', placeholder: 'Literal hint', focused: true, cursorPos: 0 };
+ const before = { ...field };
+ const display = () => textFieldDisplay(field.value, false, field.placeholder, BULLET, 'hint', locale);
+ expect(display()).toEqual({ text: 'Your name', isPlaceholder: true });
+ locale.setLocale('zh');
+ expect(display().text).toBe('姓名');
+ locale.addCatalog('zh', { hint: '请输入姓名' });
+ expect(display().text).toBe('请输入姓名');
+ locale.setPseudoLocalization({ expansion: 1 });
+ expect(display().text).toBe(locale.t('hint'));
+ expect(display().text).not.toBe('请输入姓名');
+ locale.setPseudoLocalization(null);
+ expect(display().text).toBe('请输入姓名');
+ expect(field).toEqual(before);
+ });
+ it('preserves literal hints without a resource/key and the normal missing-key contract', () => {
+ const locale = new LocalizationAPI();
+ locale.addCatalog('en', { hint: '' });
+ expect(textFieldDisplay('', false, 'Literal', BULLET, 'hint').text).toBe('Literal');
+ expect(textFieldDisplay('', false, 'Literal', BULLET, '', locale).text).toBe('Literal');
+ expect(textFieldDisplay('', false, 'Literal', BULLET, 'missing', locale).text).toBe('missing');
+ expect(textFieldDisplay('', false, 'Literal', BULLET, 'hint', locale).text).toBe('');
+ });
+ it('does not resolve hints over typed values or masked passwords', () => {
+ const locale = { t: () => { throw new Error('Nonempty values must not translate'); } };
+ expect(textFieldDisplay('hello 中文', false, 'Literal', BULLET, 'hint', locale)).toEqual({ text: 'hello 中文', isPlaceholder: false });
+ expect(textFieldDisplay('secret', true, 'Literal', BULLET, 'hint', locale)).toEqual({ text: BULLET.repeat(6), isPlaceholder: false });
+ });
+});
diff --git a/tools/ui-events-play-browser.tsx b/tools/ui-events-play-browser.tsx
index 702404fe1..bb45c8172 100644
--- a/tools/ui-events-play-browser.tsx
+++ b/tools/ui-events-play-browser.tsx
@@ -23,6 +23,15 @@ for (const entity of scene.entities) {
if (['InnerMask', 'OuterMask', 'Canvas'].includes(entity.name))
entity.components.push({ type: 'Interactable', data: { enabled: true, raycastTarget: false, blockRaycast: false } });
}
+// A scene-authored binding exercises runtime self-installation before scripts run.
+scene.entities.push({ id: 100, name: 'Localized input', parent: 1, children: [], visible: true, components: [
+ { type: 'Transform', data: {} },
+ { type: 'UINode', data: { position: 1, width: { unit: 0, value: 320 }, height: { unit: 0, value: 34 }, insetLeft: { unit: 0, value: 40 }, insetTop: { unit: 0, value: 350 } } },
+ { type: 'TextInput', data: { placeholder: 'Authored hint', placeholderI18nKey: 'hint', fontFamily: 'Arial', fontSize: 18 } },
+ { type: 'Interactable', data: { enabled: true, raycastTarget: true, blockRaycast: true } },
+ { type: 'Focusable', data: { tabIndex: 4 } },
+] });
+scene.entities.find((entity: any) => entity.id === 1).children.push(100);
function Fixture() {
const realm = useSyncExternalStore(PlayRealm.subscribe, PlayRealm.getSnapshot);
const selected = useSelection(state => state.selectedRef);
@@ -39,7 +48,7 @@ function Fixture() {
return <main style={{ padding: 16, height: '100vh', display: 'flex', flexDirection: 'column', gap: 12 }}>
<h2>UI Events · production Play realm browser verification</h2>
<div><button onClick={() => void start()}>Start Play</button> <button onClick={() => { PlayInspect.stop(); PlayRealm.stop(); }}>Stop Play</button> <button onClick={() => setMounted(value => !value)}>Toggle panel</button> <button onClick={() => void inspect()}>Read runtime snapshot</button></div>
- <small>Game keys: M opens a dialog; N opens a nested confirmation; R closes dialogs; D disables current focus; E restores controls; H hides the dialog parent; V shows it; O cycles text overflow; K changes text/font cache keys; T toggles a text input (outside text editing).</small>
+ <small>Game keys: M opens a dialog; N opens a nested confirmation; R closes dialogs; D disables current focus; E restores controls; H hides the dialog parent; V shows it; O cycles text overflow; K changes text/font cache keys; T toggles a text input; L switches language; P toggles expanded preview; U updates the active catalog (outside text editing).</small>
<p role="status">{realm.playing ? 'Playing' : 'Stopped'} · {realm.ready ? 'Ready' : 'Not ready'} · {realm.error ?? ''}</p>
<div style={{ display: 'flex', gap: 16, flex: 1, minHeight: 0 }}>
<div style={{ width: 800, height: 600, flexShrink: 0 }} ref={attach} />
@@ -50,4 +59,3 @@ function Fixture() {
</main>;
}
createRoot(document.getElementById('root')!).render(<Fixture />);
-
diff --git a/tools/ui-events-play-project.ts b/tools/ui-events-play-project.ts
index a32d7f56b..119baf704 100644
--- a/tools/ui-events-play-project.ts
+++ b/tools/ui-events-play-project.ts
@@ -1,10 +1,10 @@
// SPDX-License-Identifier: Apache-2.0
// Disposable browser game script: reactions are driven by real UI clicks.
import { addSystemToSchedule, defineSystem, Schedule, Res, GetWorld, UIEvents, Text, UINode, Transform, UIVisual, Interactable, Focusable, px, Input, FocusManager, UIDialog, UIDisplay, createTextInput, Name, TextInput, type TextInputHandle, type InputState, type FocusManagerState, type Entity, type UIEventQueue, type World } from 'esengine';
-import { LocalizationAPI, type TextData } from 'esengine';
+import { Localization, type LocalizationAPI, type TextData } from 'esengine';
import { applyTextLocalization } from '../sdk/src/ui/text/localize';
const installed = new WeakMap<World, () => void>();
-addSystemToSchedule(Schedule.Update, defineSystem([Res(UIEvents), GetWorld(), Res(Input), Res(FocusManager)], (events: UIEventQueue, world: World, input: InputState, focus: FocusManagerState) => {
+addSystemToSchedule(Schedule.Update, defineSystem([Res(UIEvents), GetWorld(), Res(Input), Res(FocusManager), Res(Localization)], (events: UIEventQueue, world: World, input: InputState, focus: FocusManagerState, locale: LocalizationAPI) => {
const update = installed.get(world);
if (update) { update(); return; }
const inside = world.findEntityByName('Inside');
@@ -14,9 +14,8 @@ addSystemToSchedule(Schedule.Update, defineSystem([Res(UIEvents), GetWorld(), Re
let count = 0, dynamic: Entity | null = null, dialogHost: Entity | null = null, nested: Entity | null = null;
let textField: TextInputHandle | null = null;
const restore = new Set<Entity>();
- const locale = new LocalizationAPI();
- locale.addCatalog('en', { caption: 'Settings' });
- locale.addCatalog('zh', { caption: '设置' });
+ locale.addCatalog('en', { caption: 'Settings', hint: 'Your name' });
+ locale.addCatalog('zh', { caption: '设置', hint: '请输入姓名' });
let localized = false, preview = false;
const boundText = { getEntitiesWithComponents: () => [inside],
get: (entity: Entity) => world.get(entity, Text),
@@ -33,7 +32,7 @@ addSystemToSchedule(Schedule.Update, defineSystem([Res(UIEvents), GetWorld(), Re
if (input.isKeyPressed('KeyP') && localized) {
preview = !preview; locale.setPseudoLocalization(preview ? { expansion: 1 } : null);
}
- if (input.isKeyPressed('KeyU') && localized) locale.addCatalog(locale.locale, { caption: 'Updated 更新' });
+ if (input.isKeyPressed('KeyU') && localized) locale.addCatalog(locale.locale, { caption: 'Updated 更新', hint: 'Updated hint 更新提示' });
if (input.isKeyPressed('KeyK')) {
const text = world.get(inside, Text);
const first = text.content !== 'A|B';
@@ -50,7 +49,7 @@ addSystemToSchedule(Schedule.Update, defineSystem([Res(UIEvents), GetWorld(), Re
else {
textField = createTextInput({ world, events, parent: world.findEntityByName('Canvas')!,
node: { position: 1, width: px(260), height: px(34), insetLeft: px(40), insetTop: px(420) },
- placeholder: 'Type English / 中文', fontFamily: 'Arial', fontSize: 18, tabIndex: 3,
+ placeholder: 'Type English / 中文', placeholderI18nKey: 'hint', fontFamily: 'Arial', fontSize: 18, tabIndex: 3,
onChange: value => world.insert(inside, Text, { ...world.get(inside, Text), content: `Input ${value}` }),
onSubmit: value => world.insert(inside, Text, { ...world.get(inside, Text), content: `Submit ${value}` }),
});