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(ui): rich-text example + live IME preedit for TextInput

yhhd2c97696b07a
diff --git a/docs/astro/src/content/docs/guides/ui-components.mdx b/docs/astro/src/content/docs/guides/ui-components.mdx
index fe5a290c2..2a05c920a 100644
--- a/docs/astro/src/content/docs/guides/ui-components.mdx
+++ b/docs/astro/src/content/docs/guides/ui-components.mdx
@@ -340,9 +340,14 @@ Click (or Tab to) the field to focus it; **Escape** blurs, **Enter** fires
`submit` on single-line fields. A value longer than the box **clips to it and scrolls
horizontally** so the caret stays in view as you type.
+**IME / CJK input** works: the field drives a hidden native `<textarea>`, so a
+Chinese/Japanese/Korean composition renders **live in the field** (the preedit
+string shows at the caret as you type) and only fires `change` once the
+composition commits — the same behavior as a native input.
+
<Aside type="note">
- Text input runs in **play mode only** and needs a browser DOM (it drives a
- hidden native textarea for IME support) — it's inert in the editor's edit view.
+ Text input runs in **play mode only** and needs a browser DOM (the hidden
+ native textarea) — it's inert in the editor's edit view.
</Aside>
## Lists & scrolling
diff --git a/examples/README.md b/examples/README.md
index 63b730d11..fdd8dc3c3 100644
--- a/examples/README.md
+++ b/examples/README.md
@@ -44,6 +44,7 @@ for your own game.
| **ui-list** | UI | A virtualized list and grid — `createListView`, live data, `scrollToIndex`. |
| **ui-controller** | UI | Shared UI controllers + declarative per-page gears: a tab bar, an `$interaction` button, and a tweened popup. |
| **chat** | UI | A chat log — virtualized ListView + TextInput composer with two-way binding. |
+| **rich-text** | UI | A live rich-text playground — type markup (and 中文 via IME) into a TextInput and watch a `Text` render bold/italic/color/font-size runs. |
| **enemy-ai** | AI | A state machine drives enemies to patrol, sense the player, and chase via A* navigation. |
| **camera-follow** | Gameplay | The camera director — `FollowTarget` damping + dead zone, `shakeCamera` impacts, `setViewTarget` blends to an overview camera. |
| **multiplayer-arena** | Networking | Server-authoritative multiplayer with client prediction: each player steers a replicated pawn, own-pawn input applies instantly ('2 Players' in the Play dropdown runs listen server + client). |
diff --git a/examples/rich-text/.gitignore b/examples/rich-text/.gitignore
new file mode 100644
index 000000000..359472ac2
--- /dev/null
+++ b/examples/rich-text/.gitignore
@@ -0,0 +1,7 @@
+node_modules/
+dist/
+.vscode/
+.idea/
+.DS_Store
+Thumbs.db
+.esengine/cache/
diff --git a/examples/rich-text/README.md b/examples/rich-text/README.md
new file mode 100644
index 000000000..e211c6aa7
--- /dev/null
+++ b/examples/rich-text/README.md
@@ -0,0 +1,43 @@
+# Rich Text
+
+A live playground for the **`Text`** component's rich-text markup and the
+**`createTextInput`** widget, wired together:
+
+- **The preview** (top) is one rich `Text`. It renders `<b>`, `<i>`,
+ `<color=#RRGGBB>` and `<font size=N>` runs — nested and mixed with CJK.
+- **The input** (middle) is a `TextInput` holding the *raw markup*. Every edit —
+ including **IME composition** for Chinese/Japanese/Korean — fires `change`,
+ which re-parses the markup and re-renders the preview above. **Reset** restores
+ the seed sample.
+- **The legend** (bottom) is a column of static rich `Text` lines, one per
+ supported tag, so the demo doubles as a quick reference.
+
+Type `你好 <color=#66ccff>世界</color> <b>bold</b>` into the field and watch it
+render live — the clearest way to see the markup pipeline and the text field
+(caret, focus, IME) working together.
+
+## How it works
+
+The scene (`assets/scenes/main.esscene`) lays out a `Panel` column with named
+slots — `PreviewSlot`, `ComposerRow`, `ShowcaseSlot`. The startup `BuildSystem`
+(`src/systems/build.ts`) finds them once the scene tree exists and mounts:
+
+- a rich `Text` filling the preview card, seeded with `SEED_MARKUP`;
+- a `createTextInput` whose `onChange` points the preview's `content` at the
+ current markup (a single `world.insert` — no diffing);
+- one static rich `Text` per line in `SAMPLES` (`src/config.ts`).
+
+The field text is plain (you see the literal `<b>…</b>` tags); the preview is
+what those tags *mean*.
+
+## Note on `<img>`
+
+Inline images (`<img src="…" width=N height=N/>`) **parse** into an
+`ImageSegment` but the built-in text renderer does not draw them yet, so this
+demo leaves `<img>` out of the legend. Compose an icon next to text with flexbox
+instead. See the [Text guide](../../docs/astro/src/content/docs/guides/ui-text.mdx).
+
+## Run
+
+Open the folder in the Estella editor and press **Play**, or build and run it
+like the other examples.
diff --git a/examples/rich-text/assets/scenes/main.esscene b/examples/rich-text/assets/scenes/main.esscene
new file mode 100644
index 000000000..f8ce5f9ed
--- /dev/null
+++ b/examples/rich-text/assets/scenes/main.esscene
@@ -0,0 +1,173 @@
+{
+ "version": "1.0",
+ "name": "Main",
+ "entities": [
+ {
+ "id": 0,
+ "name": "Camera",
+ "parent": null,
+ "children": [],
+ "components": [
+ { "type": "Transform", "data": { "position": { "x": 0, "y": 0, "z": 10 } } },
+ { "type": "Camera", "data": { "projectionType": 1, "orthoSize": 300, "isActive": true, "priority": 0 } }
+ ],
+ "visible": true
+ },
+ {
+ "id": 1,
+ "name": "Canvas",
+ "parent": null,
+ "children": [2],
+ "components": [
+ { "type": "Transform", "data": {} },
+ { "type": "Canvas", "data": { "designResolution": { "x": 800, "y": 600 }, "scaleMode": 2 } },
+ { "type": "UINode", "data": {} }
+ ],
+ "visible": true
+ },
+ {
+ "id": 2,
+ "name": "Panel",
+ "parent": 1,
+ "children": [3, 4, 5, 6, 7, 8],
+ "components": [
+ { "type": "Transform", "data": {} },
+ {
+ "type": "UINode",
+ "data": {
+ "position": 1,
+ "insetLeft": { "value": 20, "unit": 0 },
+ "insetTop": { "value": 20, "unit": 0 },
+ "insetRight": { "value": 20, "unit": 0 },
+ "insetBottom": { "value": 20, "unit": 0 }
+ }
+ },
+ {
+ "type": "FlexContainer",
+ "data": {
+ "direction": 1,
+ "justifyContent": 0,
+ "alignItems": 3,
+ "gap": { "x": 0, "y": 12 },
+ "padding": { "left": 20, "top": 20, "right": 20, "bottom": 20 }
+ }
+ },
+ {
+ "type": "UIVisual",
+ "data": { "visualType": 1, "color": { "r": 0.12, "g": 0.12, "b": 0.14, "a": 1 }, "enabled": true }
+ }
+ ],
+ "visible": true
+ },
+ {
+ "id": 3,
+ "name": "Title",
+ "parent": 2,
+ "children": [],
+ "components": [
+ { "type": "Transform", "data": {} },
+ { "type": "UINode", "data": { "height": { "value": 30, "unit": 0 } } },
+ {
+ "type": "Text",
+ "data": {
+ "content": "Rich Text + Input Playground",
+ "fontSize": 22,
+ "bold": true,
+ "color": { "r": 1, "g": 1, "b": 1, "a": 1 },
+ "align": 0,
+ "verticalAlign": 1
+ }
+ }
+ ],
+ "visible": true
+ },
+ {
+ "id": 4,
+ "name": "PreviewSlot",
+ "parent": 2,
+ "children": [],
+ "components": [
+ { "type": "Transform", "data": {} },
+ { "type": "UINode", "data": { "height": { "value": 180, "unit": 0 } } },
+ {
+ "type": "UIVisual",
+ "data": { "visualType": 1, "color": { "r": 0.08, "g": 0.09, "b": 0.12, "a": 1 }, "enabled": true }
+ }
+ ],
+ "visible": true
+ },
+ {
+ "id": 5,
+ "name": "Hint",
+ "parent": 2,
+ "children": [],
+ "components": [
+ { "type": "Transform", "data": {} },
+ { "type": "UINode", "data": { "height": { "value": 22, "unit": 0 } } },
+ {
+ "type": "Text",
+ "data": {
+ "content": "Edit the markup below — the preview updates live. Type 中文 to test IME.",
+ "fontSize": 14,
+ "color": { "r": 0.65, "g": 0.66, "b": 0.7, "a": 1 },
+ "align": 0,
+ "verticalAlign": 1
+ }
+ }
+ ],
+ "visible": true
+ },
+ {
+ "id": 6,
+ "name": "ComposerRow",
+ "parent": 2,
+ "children": [],
+ "components": [
+ { "type": "Transform", "data": {} },
+ { "type": "UINode", "data": { "height": { "value": 38, "unit": 0 } } },
+ {
+ "type": "FlexContainer",
+ "data": { "direction": 0, "justifyContent": 0, "alignItems": 1, "gap": { "x": 10, "y": 0 } }
+ }
+ ],
+ "visible": true
+ },
+ {
+ "id": 7,
+ "name": "ShowcaseTitle",
+ "parent": 2,
+ "children": [],
+ "components": [
+ { "type": "Transform", "data": {} },
+ { "type": "UINode", "data": { "height": { "value": 26, "unit": 0 } } },
+ {
+ "type": "Text",
+ "data": {
+ "content": "Supported tags",
+ "fontSize": 16,
+ "bold": true,
+ "color": { "r": 0.85, "g": 0.86, "b": 0.9, "a": 1 },
+ "align": 0,
+ "verticalAlign": 1
+ }
+ }
+ ],
+ "visible": true
+ },
+ {
+ "id": 8,
+ "name": "ShowcaseSlot",
+ "parent": 2,
+ "children": [],
+ "components": [
+ { "type": "Transform", "data": {} },
+ { "type": "UINode", "data": { "height": { "value": 170, "unit": 0 } } },
+ {
+ "type": "FlexContainer",
+ "data": { "direction": 1, "justifyContent": 0, "alignItems": 3, "gap": { "x": 0, "y": 6 } }
+ }
+ ],
+ "visible": true
+ }
+ ]
+}
diff --git a/examples/rich-text/assets/scenes/main.esscene.meta b/examples/rich-text/assets/scenes/main.esscene.meta
new file mode 100644
index 000000000..1f020854f
--- /dev/null
+++ b/examples/rich-text/assets/scenes/main.esscene.meta
@@ -0,0 +1,8 @@
+{
+ "uuid": "b7f3c2a1-4d6e-42b8-9c05-1e8a7f43d20b",
+ "version": "2.0",
+ "type": "scene",
+ "importer": {
+ "autoMigrate": true
+ }
+}
diff --git a/examples/rich-text/project.esproject b/examples/rich-text/project.esproject
new file mode 100644
index 000000000..95534d417
--- /dev/null
+++ b/examples/rich-text/project.esproject
@@ -0,0 +1,25 @@
+{
+ "formatVersion": "1",
+ "name": "Rich Text",
+ "description": "A live rich-text playground — type markup (and 中文 via IME) into a TextInput and see it render with bold, italic, color and font-size runs.",
+ "tag": "UI",
+ "version": "0.1.0",
+ "defaultScene": "assets/scenes/main.esscene",
+ "designResolution": {
+ "width": 800,
+ "height": 600
+ },
+ "spineVersion": "none",
+ "packaging": {
+ "platform": "playable",
+ "config": "shipping",
+ "sourceMaps": false,
+ "openFolder": true,
+ "compressTextures": false,
+ "atlasTextures": false,
+ "compressAudio": false,
+ "outDir": {
+ "playable": "dist-playable"
+ }
+ }
+}
diff --git a/examples/rich-text/src/config.ts b/examples/rich-text/src/config.ts
new file mode 100644
index 000000000..400b168da
--- /dev/null
+++ b/examples/rich-text/src/config.ts
@@ -0,0 +1,14 @@
+// The markup the field seeds with — a mix of a color run, bold, italic and a
+// CJK word so the very first frame shows rich text *and* invites an IME edit.
+export const SEED_MARKUP =
+ 'Hello <b>世界</b> <color=#ffcc33>Estella</color> <i>rich text</i>!';
+
+// The static reference panel: one line per supported tag, each rendered rich so
+// the demo doubles as a legend. `<img>` is intentionally left out — it parses
+// but the built-in renderer does not draw inline images yet (see README).
+export const SAMPLES: readonly string[] = [
+ '<b>bold</b> <i>italic</i> <b><i>bold italic</i></b>',
+ '<color=#ff5a5a>red</color> <color=#5aff8c>green</color> <color=#5a9cff>blue</color> <color=#ffd24a>gold</color>',
+ 'font size <font size=14>14</font> <font size=22>22</font> <font size=32>32</font>',
+ 'nested <color=#ffcc33>gold <b>bold</b> and <i>italic</i></color> back to plain',
+];
diff --git a/examples/rich-text/src/main.ts b/examples/rich-text/src/main.ts
new file mode 100644
index 000000000..b4ecb51b6
--- /dev/null
+++ b/examples/rich-text/src/main.ts
@@ -0,0 +1,9 @@
+// Rich Text — a live playground for the Text component's rich-text markup and the
+// TextInput widget. The field below the preview holds raw markup; every edit
+// (including IME composition for CJK) re-renders the preview through the same
+// `<b>/<i>/<color>/<font size>` pipeline. A static legend shows every tag.
+import { addStartupSystem } from 'esengine';
+
+import { buildSystem } from './systems/build';
+
+addStartupSystem(buildSystem);
diff --git a/examples/rich-text/src/state.ts b/examples/rich-text/src/state.ts
new file mode 100644
index 000000000..ed8bd2a82
--- /dev/null
+++ b/examples/rich-text/src/state.ts
@@ -0,0 +1,9 @@
+import type { Entity, TextInputHandle } from 'esengine';
+
+export const state = {
+ /** The editable markup source. */
+ input: null as TextInputHandle | null,
+ /** The rich Text whose content mirrors the input, re-rendered on every edit. */
+ preview: null as Entity | null,
+ built: false,
+};
diff --git a/examples/rich-text/src/systems/build.ts b/examples/rich-text/src/systems/build.ts
new file mode 100644
index 000000000..7d6a02595
--- /dev/null
+++ b/examples/rich-text/src/systems/build.ts
@@ -0,0 +1,100 @@
+import {
+ defineSystem, Res, GetWorld,
+ UIEvents,
+ UINode, Text,
+ createTextInput, createButton,
+ spawnUIEntity,
+ themeColors, px,
+ UIPositionType, TextAlign, TextVerticalAlign,
+} from 'esengine';
+import type { Entity, World, UIEventQueue, TextData } from 'esengine';
+
+import { SEED_MARKUP, SAMPLES } from '../config';
+import { state } from '../state';
+
+// The scene provides named layout slots (a Panel column with a preview card, a
+// composer row and a legend column); this system fills them once the scene tree
+// exists. Everything interactive is built in code so the wiring — input → live
+// preview — reads top-to-bottom.
+export const buildSystem = defineSystem(
+ [Res(UIEvents), GetWorld()],
+ (events: UIEventQueue, world: World) => {
+ if (state.built) return;
+ const previewSlot = world.findEntityByName('PreviewSlot');
+ const composerRow = world.findEntityByName('ComposerRow');
+ const showcaseSlot = world.findEntityByName('ShowcaseSlot');
+ if (previewSlot === null || composerRow === null || showcaseSlot === null) return;
+ state.built = true;
+
+ const c = themeColors();
+
+ // Live preview: a rich Text filling the preview card. Its content mirrors
+ // whatever markup is in the input, re-parsed + re-rendered on every edit.
+ const preview = spawnUIEntity({
+ world, parent: previewSlot,
+ node: {
+ position: UIPositionType.Absolute,
+ insetLeft: px(16), insetRight: px(16), insetTop: px(14), insetBottom: px(14),
+ },
+ text: {
+ content: SEED_MARKUP,
+ fontSize: 30,
+ richText: true,
+ wordWrap: true,
+ align: TextAlign.Left,
+ verticalAlign: TextVerticalAlign.Top,
+ color: { r: 1, g: 1, b: 1, a: 1 },
+ },
+ });
+ state.preview = preview;
+
+ // The editable markup source. Typing (incl. IME composition for CJK)
+ // fires `change`, which re-renders the preview above.
+ state.input = createTextInput({
+ world, events, parent: composerRow,
+ node: { width: px(580), height: px(36) },
+ value: SEED_MARKUP,
+ fontSize: 16,
+ onChange: (value) => setPreview(world, preview, value),
+ });
+
+ // Reset the markup back to the seed sample.
+ createButton({
+ world, events, parent: composerRow,
+ node: { width: px(110), height: px(36) },
+ states: { normal: { color: c.primary }, hover: { color: c.primary }, pressed: { color: c.primary } },
+ text: { content: 'Reset', color: c.onPrimary, fontSize: 14 },
+ onClick: () => {
+ state.input?.setValue(SEED_MARKUP);
+ setPreview(world, preview, SEED_MARKUP);
+ },
+ });
+
+ // Static legend: each supported tag rendered next to nothing but itself,
+ // so the panel doubles as a quick reference.
+ for (const line of SAMPLES) {
+ spawnUIEntity({
+ world, parent: showcaseSlot,
+ node: { height: px(32) },
+ text: {
+ content: line,
+ fontSize: 20,
+ richText: true,
+ align: TextAlign.Left,
+ verticalAlign: TextVerticalAlign.Middle,
+ color: { r: 0.9, g: 0.9, b: 0.92, a: 1 },
+ },
+ });
+ }
+ },
+ { name: 'BuildSystem' },
+);
+
+/** Point the preview Text at the current markup (skips a redundant write). */
+function setPreview(world: World, preview: Entity, markup: string): void {
+ if (!world.valid(preview) || !world.has(preview, Text)) return;
+ const t = world.get(preview, Text) as TextData;
+ if (t.content === markup) return;
+ t.content = markup;
+ world.insert(preview, Text, t);
+}
diff --git a/examples/rich-text/thumbnail.png b/examples/rich-text/thumbnail.png
new file mode 100644
index 000000000..30ac5a96e
Binary files /dev/null and b/examples/rich-text/thumbnail.png differ
diff --git a/examples/rich-text/thumbnail.png.meta b/examples/rich-text/thumbnail.png.meta
new file mode 100644
index 000000000..796becbd9
--- /dev/null
+++ b/examples/rich-text/thumbnail.png.meta
@@ -0,0 +1,17 @@
+{
+ "uuid": "c9a2e4b7-3f81-4d6a-8b05-2e7c1f94a30d",
+ "version": "2.0",
+ "type": "texture",
+ "importer": {
+ "maxSize": 2048,
+ "filterMode": "linear",
+ "wrapMode": "repeat",
+ "premultiplyAlpha": false,
+ "sliceBorder": {
+ "left": 0,
+ "right": 0,
+ "top": 0,
+ "bottom": 0
+ }
+ }
+}
diff --git a/examples/rich-text/tsconfig.json b/examples/rich-text/tsconfig.json
new file mode 100644
index 000000000..0a8528b29
--- /dev/null
+++ b/examples/rich-text/tsconfig.json
@@ -0,0 +1,22 @@
+{
+ "compilerOptions": {
+ "target": "ES2020",
+ "module": "ESNext",
+ "moduleResolution": "bundler",
+ "strict": true,
+ "esModuleInterop": true,
+ "skipLibCheck": true,
+ "forceConsistentCasingInFileNames": true,
+ "declaration": false,
+ "outDir": "./dist",
+ "rootDir": ".",
+ "baseUrl": ".",
+ "paths": {
+ "esengine": ["./.esengine/sdk/index.d.ts"],
+ "esengine/wasm": ["./.esengine/sdk/wasm.d.ts"],
+ "@esengine/editor": ["./.esengine/editor/index.d.ts"]
+ }
+ },
+ "include": ["src/**/*"],
+ "exclude": ["node_modules"]
+}
diff --git a/sdk/src/ui/ARCHITECTURE.md b/sdk/src/ui/ARCHITECTURE.md
index f5b37a925..28a55b61f 100644
--- a/sdk/src/ui/ARCHITECTURE.md
+++ b/sdk/src/ui/ARCHITECTURE.md
@@ -46,7 +46,7 @@ collection, or widgets.
| `behavior/` | Runtime systems: scroll/collection ticking, data-driven widget behavior, scrollbars, theme re-resolution | `plugin` (UIBehaviorPlugin), `dialog`, `slider`, `toggle`, `dropdown`, `scrollbar`, `theme-apply` |
| `render/` | UI-specific render concerns | `mask`, `render-order` |
| `collection/` | Data-driven collections + view recycling | `list-view`, `scroll-container`, `view-pool`, `data-source`, `layout-provider` |
-| `text/` | SDF glyph atlas, text layout, rich text, editable text | `glyph-atlas`, `text-renderer`, `layout`, `rich-text-*`, `text-input`, `image-resolver` |
+| `text/` | SDF glyph atlas, text layout, rich text, editable text | `glyph-atlas`, `text-renderer`, `layout`, `rich-text-parser`, `text-input`, `text-input-plugin`, `text-input-view` |
| `theme/` | Design tokens + per-entity role markers | `tokens`, `theme-style` |
| `util/` | Cross-cutting helpers (no engine state of their own) | `helpers`, `math`, `constants`, `property-path`, `ui-pick` |
| `widgets/` | Layer-4 widget **factory functions** + their prefab capture | `button`, `toggle`, `slider`, `progress`, `dialog`, `dropdown`, `text-input`, `list-view`, `scroll-view`, `helpers`, `toPrefab`, `prefabs/` |
diff --git a/sdk/src/ui/text/text-input-plugin.ts b/sdk/src/ui/text/text-input-plugin.ts
index e64bbf19f..6d16a0f26 100644
--- a/sdk/src/ui/text/text-input-plugin.ts
+++ b/sdk/src/ui/text/text-input-plugin.ts
@@ -20,6 +20,7 @@ import { spawnUIEntity } from '../core/compose';
import { px } from '../core/dimension';
import { SdfTextRenderer } from './text-renderer';
import { measureWidth } from './layout';
+import { textFieldDisplay, type TextFieldDisplay } from './text-input-view';
import { CURSOR_BLINK_INTERVAL } from '../util/constants';
import { SystemLabel, PluginName } from '../../systemLabels';
import { log } from '../../logger';
@@ -93,6 +94,19 @@ export class TextInputPlugin implements Plugin {
const onCompositionStart = () => {
composing = true;
+ resetCursorBlink();
+ };
+
+ // While composing, the browser holds the preedit inside the textarea
+ // value with the caret after it. The render loop reads that live (see
+ // below), so no state is copied here — this only keeps the caret solid
+ // and the field marked dirty as the preedit changes each keystroke.
+ const onCompositionUpdate = () => {
+ const focused = getFocusedTextInput();
+ if (focused !== null) {
+ (world.get(focused, TextInput) as TextInputData).dirty = true;
+ }
+ resetCursorBlink();
};
const onCompositionEnd = () => {
@@ -151,6 +165,7 @@ export class TextInputPlugin implements Plugin {
textarea.addEventListener('input', onInput);
textarea.addEventListener('compositionstart', onCompositionStart);
+ textarea.addEventListener('compositionupdate', onCompositionUpdate);
textarea.addEventListener('compositionend', onCompositionEnd);
textarea.addEventListener('keydown', onKeyDown);
textarea.addEventListener('blur', onBlur);
@@ -158,6 +173,7 @@ export class TextInputPlugin implements Plugin {
this.cleanupListeners_ = () => {
textarea.removeEventListener('input', onInput);
textarea.removeEventListener('compositionstart', onCompositionStart);
+ textarea.removeEventListener('compositionupdate', onCompositionUpdate);
textarea.removeEventListener('compositionend', onCompositionEnd);
textarea.removeEventListener('keydown', onKeyDown);
textarea.removeEventListener('blur', onBlur);
@@ -291,28 +307,28 @@ export class TextInputPlugin implements Plugin {
ensureBackground(entity, ti);
const ch = ensureChildren(entity, ti);
+ // Fold an active IME composition into the shown text: while
+ // composing, the hidden textarea holds the preedit at the caret,
+ // so a focused field renders that live instead of the (not-yet-
+ // committed) component value — otherwise the composed string is
+ // invisible until it commits.
+ const editing = composing && focused === entity;
+ const val = editing ? textarea.value : ti.value;
+ const caret = editing ? (textarea.selectionStart ?? val.length) : ti.cursorPos;
+ const disp = textFieldDisplay(val, caret, ti.password, ti.placeholder, PASSWORD_CHAR);
// Single-line fields scroll horizontally to keep the caret in view;
// multiline wraps within the box and clips (no h-scroll).
const innerW = Math.max(0, w - 2 * ti.padding);
- const caretText = ti.password
- ? PASSWORD_CHAR.repeat(ti.cursorPos)
- : ti.value.substring(0, ti.cursorPos);
- const caretRaw = measureWidth(caretText, ensureMeasure().atlas, ti.fontFamily, ti.fontSize, 0);
+ const caretRaw = measureWidth(disp.beforeCaret, ensureMeasure().atlas, ti.fontFamily, ti.fontSize, 0);
const scrollX = ti.multiline ? 0 : Math.max(0, caretRaw - innerW);
- syncTextChild(ch.text, ti, innerW, scrollX);
+ syncTextChild(ch.text, ti, disp, innerW, scrollX);
syncCaretChild(ch.caret, ti, h, ti.padding + caretRaw - scrollX);
}
},
{ name: 'TextInputRenderSystem' }
));
- /** Visible string: placeholder when empty, bullets when password. */
- const displayString = (ti: TextInputData): string =>
- ti.value.length === 0 ? ti.placeholder
- : ti.password ? PASSWORD_CHAR.repeat(ti.value.length)
- : ti.value;
-
function ensureBackground(entity: Entity, ti: TextInputData): void {
// Clip the editable text + caret to the field box: a long value scrolls
// horizontally past the edge and must not spill outside the input.
@@ -366,10 +382,10 @@ export class TextInputPlugin implements Plugin {
return ch;
}
- function syncTextChild(textEntity: Entity, ti: TextInputData, innerW: number, scrollX: number): void {
+ function syncTextChild(textEntity: Entity, ti: TextInputData, disp: TextFieldDisplay, innerW: number, scrollX: number): void {
const t = world.get(textEntity, Text) as TextData;
- const show = displayString(ti);
- const col = ti.value.length === 0 ? ti.placeholderColor : ti.color;
+ const show = disp.text;
+ const col = disp.isPlaceholder ? ti.placeholderColor : ti.color;
if (t.content !== show || t.fontFamily !== ti.fontFamily || t.fontSize !== ti.fontSize
|| t.wordWrap !== ti.multiline || t.renderMode !== ti.renderMode
|| t.color.r !== col.r || t.color.g !== col.g || t.color.b !== col.b || t.color.a !== col.a) {
diff --git a/sdk/src/ui/text/text-input-view.ts b/sdk/src/ui/text/text-input-view.ts
new file mode 100644
index 000000000..235e38750
--- /dev/null
+++ b/sdk/src/ui/text/text-input-view.ts
@@ -0,0 +1,47 @@
+// SPDX-License-Identifier: Apache-2.0
+// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team
+/**
+ * @file ui/text/text-input-view.ts
+ * @brief Pure derivation of *what a text field shows* — the glyph string,
+ * whether it is the placeholder, and the (already-masked) substring
+ * before the caret whose width positions the caret. Kept pure (no ECS,
+ * DOM or engine) so the placeholder / password / caret-offset rules are
+ * unit-testable; the input plugin feeds it the effective value + caret
+ * (which, while an IME composition is active, come straight from the
+ * hidden textarea so the preedit renders live).
+ */
+
+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. */
+ text: string;
+ /** True when {@link text} is the placeholder (drives placeholder color). */
+ isPlaceholder: boolean;
+ /** The substring up to the caret — already password-masked — whose measured
+ * width places the caret and drives horizontal scroll. Empty for the
+ * placeholder (an empty field parks the caret at the left edge). */
+ beforeCaret: string;
+}
+
+/**
+ * Resolve the shown text + caret prefix for a field with `value` and caret index
+ * `caret`. Empty ⇒ the placeholder (caret at the origin); password ⇒ every glyph
+ * is `bullet`, including the caret prefix, so the caret still lands between
+ * masked characters. Pure.
+ */
+export function textFieldDisplay(
+ value: string,
+ caret: number,
+ password: boolean,
+ placeholder: string,
+ bullet: string,
+): TextFieldDisplay {
+ if (value.length === 0) {
+ return { text: placeholder, isPlaceholder: true, beforeCaret: '' };
+ }
+ const clamped = Math.max(0, Math.min(caret, value.length));
+ if (password) {
+ return { text: bullet.repeat(value.length), isPlaceholder: false, beforeCaret: bullet.repeat(clamped) };
+ }
+ return { text: value, isPlaceholder: false, beforeCaret: value.slice(0, clamped) };
+}
diff --git a/sdk/tests/ui-text-input-view.test.ts b/sdk/tests/ui-text-input-view.test.ts
new file mode 100644
index 000000000..6cb09fb6b
--- /dev/null
+++ b/sdk/tests/ui-text-input-view.test.ts
@@ -0,0 +1,55 @@
+// SPDX-License-Identifier: Apache-2.0
+// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team
+/**
+ * @file Pure display derivation for the TextInput plugin: placeholder / password
+ * masking and the caret-prefix that positions the caret. The plugin feeds
+ * this the *effective* value + caret — which, mid-IME-composition, are the
+ * hidden textarea's live preedit — so covering the branches here covers
+ * the preedit render path too.
+ */
+import { describe, it, expect } from 'vitest';
+import { textFieldDisplay } from '../src/ui/text/text-input-view';
+
+const BULLET = '●';
+
+describe('textFieldDisplay', () => {
+ it('shows the placeholder for an empty value (caret parks at the origin)', () => {
+ expect(textFieldDisplay('', 0, false, 'Your name', BULLET)).toEqual({
+ text: 'Your name', isPlaceholder: true, beforeCaret: '',
+ });
+ });
+
+ it('an empty password field still shows the placeholder (empty wins over masking)', () => {
+ expect(textFieldDisplay('', 0, true, 'Password', BULLET)).toEqual({
+ text: 'Password', isPlaceholder: true, beforeCaret: '',
+ });
+ });
+
+ it('renders the value verbatim with the caret prefix up to the caret index', () => {
+ expect(textFieldDisplay('hello', 3, false, 'ph', BULLET)).toEqual({
+ text: 'hello', isPlaceholder: false, beforeCaret: 'hel',
+ });
+ });
+
+ it('clamps a caret past the end so the prefix is the whole value', () => {
+ expect(textFieldDisplay('hi', 99, false, 'ph', BULLET).beforeCaret).toBe('hi');
+ });
+
+ it('clamps a negative caret to the origin', () => {
+ expect(textFieldDisplay('hi', -5, false, 'ph', BULLET).beforeCaret).toBe('');
+ });
+
+ it('masks a password value AND its caret prefix bullet-for-bullet', () => {
+ const d = textFieldDisplay('secret', 4, true, 'ph', BULLET);
+ expect(d.text).toBe(BULLET.repeat(6));
+ expect(d.beforeCaret).toBe(BULLET.repeat(4));
+ expect(d.isPlaceholder).toBe(false);
+ });
+
+ it('treats a live IME preedit as ordinary text (the plugin passes the composed value + caret)', () => {
+ // Mid-composition the plugin passes textarea.value ("ab你好") + selectionStart (4).
+ expect(textFieldDisplay('ab你好', 4, false, 'ph', BULLET)).toEqual({
+ text: 'ab你好', isPlaceholder: false, beforeCaret: 'ab你好',
+ });
+ });
+});