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(ui): an editable field talks to the platform's text-editing surface
esengine43fb045d95bb
diff --git a/sdk/etc/index.api.md b/sdk/etc/index.api.mdindex a3f45272a..fc246203b 100644--- a/sdk/etc/index.api.md+++ b/sdk/etc/index.api.md@@ -4623,6 +4623,7 @@ createAudioBackend: (() => PlatformAudioBackend) | undefinedcreateCanvas: (width: number, height: number) => PlatformCanvascreateImage: () => PlatformImagecreateSocket: ((options: PlatformSocketOptions) => PlatformSocket) | undefined+createTextEditor: (() => PlatformTextEditor | null) | undefinedcreateVideoBackend: ((ctx: VideoBackendContext) => PlatformVideoBackend) | undefineddevicePixelRatio: () => numberfamily: "minigame" | undefineddiff --git a/sdk/etc/index.native.api.md b/sdk/etc/index.native.api.mdindex 40eb9900b..b401324f3 100644--- a/sdk/etc/index.native.api.md+++ b/sdk/etc/index.native.api.md@@ -4771,6 +4771,7 @@ createAudioBackend: (() => PlatformAudioBackend) | undefinedcreateCanvas: (width: number, height: number) => PlatformCanvascreateImage: () => PlatformImagecreateSocket: ((options: PlatformSocketOptions) => PlatformSocket) | undefined+createTextEditor: (() => PlatformTextEditor | null) | undefinedcreateVideoBackend: ((ctx: VideoBackendContext) => PlatformVideoBackend) | undefineddevicePixelRatio: () => numberfamily: "minigame" | undefineddiff --git a/sdk/etc/index.node.api.md b/sdk/etc/index.node.api.mdindex 65622b3c2..7ffbe6d62 100644--- a/sdk/etc/index.node.api.md+++ b/sdk/etc/index.node.api.md@@ -4618,6 +4618,7 @@ createAudioBackend: (() => PlatformAudioBackend) | undefinedcreateCanvas: (width: number, height: number) => PlatformCanvascreateImage: () => PlatformImagecreateSocket: ((options: PlatformSocketOptions) => PlatformSocket) | undefined+createTextEditor: (() => PlatformTextEditor | null) | undefinedcreateVideoBackend: ((ctx: VideoBackendContext) => PlatformVideoBackend) | undefineddevicePixelRatio: () => numberfamily: "minigame" | undefineddiff --git a/sdk/etc/minigame.api.md b/sdk/etc/minigame.api.mdindex f28f9ed06..7ffea13de 100644--- a/sdk/etc/minigame.api.md+++ b/sdk/etc/minigame.api.md@@ -4833,6 +4833,7 @@ createAudioBackend: (() => PlatformAudioBackend) | undefinedcreateCanvas: (width: number, height: number) => PlatformCanvascreateImage: () => PlatformImagecreateSocket: ((options: PlatformSocketOptions) => PlatformSocket) | undefined+createTextEditor: (() => PlatformTextEditor | null) | undefinedcreateVideoBackend: ((ctx: VideoBackendContext) => PlatformVideoBackend) | undefineddevicePixelRatio: () => numberfamily: "minigame" | undefineddiff --git a/sdk/etc/wechat.api.md b/sdk/etc/wechat.api.mdindex e4742f163..a2d49e7d7 100644--- a/sdk/etc/wechat.api.md+++ b/sdk/etc/wechat.api.md@@ -4625,6 +4625,7 @@ createAudioBackend: (() => PlatformAudioBackend) | undefinedcreateCanvas: (width: number, height: number) => PlatformCanvascreateImage: () => PlatformImagecreateSocket: ((options: PlatformSocketOptions) => PlatformSocket) | undefined+createTextEditor: (() => PlatformTextEditor | null) | undefinedcreateVideoBackend: ((ctx: VideoBackendContext) => PlatformVideoBackend) | undefineddevicePixelRatio: () => numberfamily: "minigame" | undefineddiff --git a/sdk/src/platform/base.ts b/sdk/src/platform/base.tsindex bb2f2bbae..5f626fb56 100644--- a/sdk/src/platform/base.ts+++ b/sdk/src/platform/base.ts@@ -150,6 +150,14 @@ export function platformRasterizeGlyph(return getPlatform().rasterizeGlyph?.(request) ?? null;}+/** The platform's text-editing surface, or null where there is none (a headless+ * realm, the editor in edit mode) — fields then render but cannot be typed+ * into. Safe before a platform is set. */+export function platformCreateTextEditor(): import('./types').PlatformTextEditor | null {+ if (!isPlatformInitialized()) return null;+ return getPlatform().createTextEditor?.() ?? null;+}+export function platformNow(): number {return getPlatform().now();}diff --git a/sdk/src/platform/index.ts b/sdk/src/platform/index.tsindex eb4e8c1f2..a1f154c8a 100644--- a/sdk/src/platform/index.ts+++ b/sdk/src/platform/index.ts@@ -40,6 +40,7 @@ export {platformCreateImage,platformHasGlyphRasterizer,platformRasterizeGlyph,+ platformCreateTextEditor,platformNow,platformUnbindInputEvents,platformCreateAudioBackend,diff --git a/sdk/src/platform/types.ts b/sdk/src/platform/types.tsindex 46fcf31fa..ca6d6c5a5 100644--- a/sdk/src/platform/types.ts+++ b/sdk/src/platform/types.ts@@ -151,6 +151,78 @@ export interface PlatformTextMetrics {readonly actualBoundingBoxDescent?: number;}+// =============================================================================+// Text editing+// =============================================================================++/**+ * What an editing surface holds while a field has focus. Selection indices are+ * UTF-16 code units, as every platform's text field counts them.+ */+export interface TextEditorState {+ value: string;+ selectionStart: number;+ selectionEnd: number;+ /** The caret sits at `selectionStart` — a shift-left / shift-up selection. */+ backward: boolean;+}++/** What the surface needs to know about the field it is editing. */+export interface TextEditorOptions {+ /** Enter inserts a newline instead of submitting. */+ multiline: boolean;+ /** 0 = unlimited. The plugin enforces it too; a surface that can, should. */+ maxLength: number;+ /** The field renders its own bullets — this is for the keyboard's benefit+ * (no autocorrect / suggestion strip over a password). */+ password: boolean;+}++export type TextEditorEvent =+ /** The surface's value or selection changed — typing, paste, caret motion. */+ | { kind: 'change' }+ /** An IME composition began or ended; the preedit sits in `read().value`. */+ | { kind: 'composition'; composing: boolean }+ /** Enter on a single-line field, or the keyboard's done/go key. */+ | { kind: 'submit' }+ /** Escape, or the keyboard was dismissed without committing. */+ | { kind: 'cancel' }+ /** The surface gave up focus on its own. */+ | { kind: 'blur' };++/**+ * The OS text-editing surface behind an editable field: a hidden textarea on the+ * web, the soft keyboard and its IME on a device. It OWNS the value and the+ * selection while focused — caret motion, native shift/Ctrl-A selection and the+ * live IME preedit all land there — so the field renders what {@link read}+ * answers and pushes its own edits back through {@link write}.+ *+ * One contract for every platform, so the text-input plugin is the same code+ * everywhere; a host with no surface simply has none, and its fields render but+ * do not type.+ */+export interface PlatformTextEditor {+ /** Take focus with this state. On a device this opens the soft keyboard. */+ focus(state: TextEditorState, options: TextEditorOptions): void;+ /** Give up focus (and close the keyboard). */+ blur(): void;+ /** The surface's live state. */+ read(): TextEditorState;+ /** Push a state the app decided: a programmatic setValue, click-to-caret, a+ * maxLength truncation. */+ write(state: TextEditorState): void;+ /**+ * Put the caret at this point in CSS px (y down from the top-left of the+ * drawing surface), so an IME pops its candidate window there instead of in+ * a screen corner. Optional — a platform whose IME is a fixed system panel+ * has nowhere to put it.+ */+ setCaretAnchor?(left: number, top: number): void;+ /** Listen for what the surface did. Returns an unsubscribe. */+ subscribe(handler: (event: TextEditorEvent) => void): () => void;+ dispose(): void;+}+/** The `getContext('2d', …)` options actually used. */export interface PlatformCanvasContextAttributes {willReadFrequently?: boolean;@@ -326,6 +398,13 @@ export interface PlatformAdapter {*/rasterizeGlyph?(request: PlatformGlyphRequest): PlatformGlyph | null;+ /**+ * The OS text-editing surface for editable fields (see+ * {@link PlatformTextEditor}). Optional — a host without one (a headless+ * realm, the editor's edit mode) renders fields but cannot type into them.+ */+ createTextEditor?(): PlatformTextEditor | null;+now(): number;createImage(): PlatformImage;diff --git a/sdk/src/platform/web.ts b/sdk/src/platform/web.tsindex 5dcd70b3e..5eecefee6 100644--- a/sdk/src/platform/web.ts+++ b/sdk/src/platform/web.ts@@ -17,7 +17,9 @@ import type {PlatformImage,PlatformSocket,PlatformSocketOptions,+ PlatformTextEditor,} from './types';+import { createWebTextEditor } from './webTextEditor';import { WebAudioBackend } from '../audio/WebAudioBackend';import type { PlatformAudioBackend } from '../audio/PlatformAudioBackend';import { WebVideoBackend } from '../video/WebVideoBackend';@@ -123,6 +125,12 @@ class WebPlatformAdapter implements PlatformAdapter {return new Image();}+ /** A hidden textarea: the browser's own field, borrowed for its keyboard+ * layouts, IME and selection gestures (see platform/webTextEditor.ts). */+ createTextEditor(): PlatformTextEditor | null {+ return createWebTextEditor();+ }+createCanvas(width: number, height: number): PlatformCanvas {let canvas: HTMLCanvasElement | OffscreenCanvas;if (typeof OffscreenCanvas !== 'undefined') {diff --git a/sdk/src/platform/webTextEditor.ts b/sdk/src/platform/webTextEditor.tsnew file mode 100644index 000000000..1ee5fc2c7--- /dev/null+++ b/sdk/src/platform/webTextEditor.ts@@ -0,0 +1,149 @@+// SPDX-License-Identifier: Apache-2.0+// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team+/**+ * @file platform/webTextEditor.ts+ * @brief The web's editing surface: a hidden textarea, behind the platform's+ * {@link PlatformTextEditor} contract.+ *+ * A browser already has a text field that does everything an editable UI field+ * needs — keyboard layouts, IME composition with its candidate window, native+ * selection gestures, clipboard, undo — so the engine borrows one instead of+ * reimplementing it, keeps it invisible and click-through, and reads its value+ * and selection as the truth while a field is focused. Moving it to the caret is+ * what makes the IME candidate window pop under the text being typed.+ */+import type {+ PlatformTextEditor, TextEditorEvent, TextEditorOptions, TextEditorState,+} from './types';++const PARKED_PX = '-9999px';++function createHiddenTextarea(): HTMLTextAreaElement | null {+ if (typeof document === 'undefined' || !document.body) return null;+ const textarea = document.createElement('textarea');+ textarea.style.position = 'fixed';+ // Parked off-screen until a field focuses, then moved to the caret so the IME+ // candidate window anchors there. Invisible and click-through so the on-screen+ // textarea never shows or steals a pointer.+ textarea.style.left = PARKED_PX;+ textarea.style.top = PARKED_PX;+ textarea.style.width = '1px';+ textarea.style.height = '1px';+ textarea.style.opacity = '0';+ textarea.style.zIndex = '-1';+ textarea.style.pointerEvents = 'none';+ textarea.style.border = '0';+ textarea.style.padding = '0';+ textarea.autocomplete = 'off';+ textarea.setAttribute('autocorrect', 'off');+ textarea.setAttribute('autocapitalize', 'off');+ textarea.setAttribute('spellcheck', 'false');+ document.body.appendChild(textarea);+ return textarea;+}++export function createWebTextEditor(): PlatformTextEditor | null {+ const textarea = createHiddenTextarea();+ if (!textarea) return null;++ const handlers = new Set<(event: TextEditorEvent) => void>();+ const emit = (event: TextEditorEvent): void => {+ for (const handler of handlers) handler(event);+ };+ let composing = false;+ let multiline = false;++ const onInput = (): void => { if (!composing) emit({ kind: 'change' }); };+ const onCompositionStart = (): void => {+ composing = true;+ emit({ kind: 'composition', composing: true });+ };+ // The preedit lives in the textarea's value with the caret after it, and the+ // field reads that live — so an update carries no state, only the news that+ // the composition moved.+ const onCompositionUpdate = (): void => emit({ kind: 'composition', composing: true });+ const onCompositionEnd = (): void => {+ composing = false;+ emit({ kind: 'composition', composing: false });+ emit({ kind: 'change' });+ };+ const onKeyDown = (e: KeyboardEvent): void => {+ if (e.key === 'Escape') {+ emit({ kind: 'cancel' });+ return;+ }+ if (e.key === 'Enter' && !multiline) {+ e.preventDefault();+ emit({ kind: 'submit' });+ return;+ }+ // Arrows, Home/End, shift-select and Ctrl-A are the textarea's own; the+ // field mirrors its selection each frame. This only reports the motion.+ emit({ kind: 'change' });+ };+ const onBlur = (): void => emit({ kind: 'blur' });++ textarea.addEventListener('input', onInput);+ textarea.addEventListener('compositionstart', onCompositionStart);+ textarea.addEventListener('compositionupdate', onCompositionUpdate);+ textarea.addEventListener('compositionend', onCompositionEnd);+ textarea.addEventListener('keydown', onKeyDown);+ textarea.addEventListener('blur', onBlur);++ const park = (): void => {+ if (textarea.style.left !== PARKED_PX) {+ textarea.style.left = PARKED_PX;+ textarea.style.top = PARKED_PX;+ }+ };++ return {+ focus(state: TextEditorState, options: TextEditorOptions): void {+ multiline = options.multiline;+ // No limit is the ABSENCE of the attribute — assigning a negative+ // maxLength is an IndexSizeError, not "unlimited".+ if (options.maxLength > 0) textarea.maxLength = options.maxLength;+ else textarea.removeAttribute('maxlength');+ textarea.value = state.value;+ textarea.selectionStart = state.selectionStart;+ textarea.selectionEnd = state.selectionEnd;+ textarea.focus();+ },+ blur(): void {+ park();+ textarea.blur();+ },+ read(): TextEditorState {+ const value = textarea.value;+ return {+ value,+ selectionStart: textarea.selectionStart ?? value.length,+ selectionEnd: textarea.selectionEnd ?? value.length,+ backward: textarea.selectionDirection === 'backward',+ };+ },+ write(state: TextEditorState): void {+ if (textarea.value !== state.value) textarea.value = state.value;+ textarea.selectionStart = state.selectionStart;+ textarea.selectionEnd = state.selectionEnd;+ },+ setCaretAnchor(left: number, top: number): void {+ textarea.style.left = Math.round(left) + 'px';+ textarea.style.top = Math.round(top) + 'px';+ },+ subscribe(handler: (event: TextEditorEvent) => void): () => void {+ handlers.add(handler);+ return () => { handlers.delete(handler); };+ },+ dispose(): void {+ textarea.removeEventListener('input', onInput);+ textarea.removeEventListener('compositionstart', onCompositionStart);+ textarea.removeEventListener('compositionupdate', onCompositionUpdate);+ textarea.removeEventListener('compositionend', onCompositionEnd);+ textarea.removeEventListener('keydown', onKeyDown);+ textarea.removeEventListener('blur', onBlur);+ textarea.remove();+ handlers.clear();+ },+ };+}diff --git a/sdk/src/ui/text/text-input-plugin.ts b/sdk/src/ui/text/text-input-plugin.tsindex 234d5bc8f..466fadd4b 100644--- a/sdk/src/ui/text/text-input-plugin.ts+++ b/sdk/src/ui/text/text-input-plugin.ts@@ -21,13 +21,14 @@ import { ensureComponent, getUINodeWidth, getUINodeHeight } from '../util/helperimport { spawnUIEntity } from '../core/compose';import { px } from '../core/dimension';import { SdfTextRenderer } from './text-renderer';+import type { ESEngineModule } from '../../wasm';import { measureWidth } from './layout';import {textFieldDisplay, maskedPrefix, fieldSelection, nearestCaretIndex,splitLines, caretLineCol, lineSelections, imeAnchorCss, type TextFieldDisplay,} from './text-input-view';import { uiWorldToScreen } from '../util/ui-pick';-import { platformDevicePixelRatio } from '../../platform';+import { platformCreateTextEditor, platformDevicePixelRatio } from '../../platform';import { CURSOR_BLINK_INTERVAL, TEXT_INPUT_LINE_HEIGHT_RATIO } from '../util/constants';import { SystemLabel, PluginName } from '../../systemLabels';import { log } from '../../logger';@@ -56,18 +57,18 @@ export class TextInputPlugin implements Plugin {if (!playModeOnly()) return;- const moduleOrNull = app.wasmModule;- if (!moduleOrNull) {- // Editing needs two things this realm does not have: the module's glyph- // measurement and a DOM text field to take keystrokes and IME composition- // (a native app has neither — the OS supplies its own editing surface, and- // wiring that is its own piece of work). The component still renders through- // the shared SDF atlas, so a field shows its value; it just cannot be typed- // into. Stated as a fact about the realm, not as a missing dependency.+ // The OS surface that holds the value + selection while a field is focused:+ // a hidden textarea on the web, the soft keyboard and its IME on a device.+ // A realm without one (headless) renders fields but cannot type into them.+ const editor = platformCreateTextEditor();+ if (!editor) {log.info('ui', 'TextInput: this realm has no text-editing surface — fields render, typing is off');return;}- const module = moduleOrNull;++ // Null on the native core, whose glyphs come from the platform rasterizer+ // rather than the wasm heap — the measurement atlas takes either.+ const module = app.wasmModule as ESEngineModule | null;const world = app.world;@@ -92,12 +93,6 @@ export class TextInputPlugin implements Plugin {let cursorTimer = 0;let lastTime = 0;- const textareaOrNull = createHiddenTextarea();- if (!textareaOrNull) {- return;- }- const textarea = textareaOrNull;-function getFocusedTextInput(): Entity | null {const fm = app.getResource(FocusManager) as FocusManagerState | null;if (!fm || fm.focusedEntity === null) return null;@@ -106,84 +101,45 @@ export class TextInputPlugin implements Plugin {return entity;}- const onInput = () => {- if (composing || getFocusedTextInput() === null) return;- syncFromTextarea();- };-- 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 = () => {- composing = false;- syncFromTextarea();- };-- const onKeyDown = (e: KeyboardEvent) => {+ const unsubscribe = editor.subscribe((event) => {const focused = getFocusedTextInput();- if (focused === null) return;-- if (e.key === 'Escape') {- blurCurrent();- return;- }-- const ti = world.get(focused, TextInput) as TextInputData;- if (e.key === 'Enter' && !ti.multiline) {- e.preventDefault();- const events = app.getResource(UIEvents) as UIEventQueue;- events.emit(focused, 'submit');- blurCurrent();- return;- }-- // Caret movement + selection (arrows, Home/End, Shift-select, Ctrl-A)- // are handled natively by the focused textarea — the render loop- // mirrors its selection each frame — so nothing to intercept here.- // A keystroke that moves the caret should re-show it solid.- resetCursorBlink();- };-- const onBlur = () => {- const focused = getFocusedTextInput();- if (focused !== null) {- const ti = world.get(focused, TextInput) as TextInputData;- ti.focused = false;- ti.dirty = true;- const fm = app.getResource(FocusManager) as FocusManagerState;- fm.blur();+ switch (event.kind) {+ case 'change':+ if (!composing && focused !== null) syncFromEditor();+ break;+ case 'composition':+ // The preedit sits in the surface's value with the caret after+ // it, and the render loop reads that live — so nothing is copied+ // here. This keeps the caret solid and the field dirty while the+ // composition moves, and commits it when it ends.+ composing = event.composing;+ if (focused !== null) (world.get(focused, TextInput) as TextInputData).dirty = true;+ if (!event.composing && focused !== null) syncFromEditor();+ resetCursorBlink();+ break;+ case 'submit':+ if (focused !== null) {+ (app.getResource(UIEvents) as UIEventQueue).emit(focused, 'submit');+ blurCurrent();+ }+ break;+ case 'cancel':+ if (focused !== null) blurCurrent();+ break;+ case 'blur':+ if (focused !== null) {+ const ti = world.get(focused, TextInput) as TextInputData;+ ti.focused = false;+ ti.dirty = true;+ (app.getResource(FocusManager) as FocusManagerState).blur();+ }+ break;}- };-- textarea.addEventListener('input', onInput);- textarea.addEventListener('compositionstart', onCompositionStart);- textarea.addEventListener('compositionupdate', onCompositionUpdate);- textarea.addEventListener('compositionend', onCompositionEnd);- textarea.addEventListener('keydown', onKeyDown);- textarea.addEventListener('blur', onBlur);+ });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);- textarea.remove();+ unsubscribe();+ editor.dispose();for (const ch of childrenOf.values()) {if (world.valid(ch.sel)) world.despawn(ch.sel);if (world.valid(ch.text)) world.despawn(ch.text);@@ -192,16 +148,17 @@ export class TextInputPlugin implements Plugin {childrenOf.clear();};- function syncFromTextarea(): void {+ function syncFromEditor(): void {const focused = getFocusedTextInput();if (focused === null) return;const ti = world.get(focused, TextInput) as TextInputData;if (ti.readOnly) return;- let val = textarea.value;+ const state = editor!.read();+ let val = state.value;if (ti.maxLength > 0 && val.length > ti.maxLength) {val = val.substring(0, ti.maxLength);- textarea.value = val;+ editor!.write({ ...state, value: val, selectionStart: val.length, selectionEnd: val.length });}if (val !== ti.value) {@@ -209,7 +166,7 @@ export class TextInputPlugin implements Plugin {const events = app.getResource(UIEvents) as UIEventQueue;events.emit(focused, 'change');}- ti.cursorPos = textarea.selectionStart ?? val.length;+ ti.cursorPos = Math.min(state.selectionStart, val.length);ti.dirty = true;resetCursorBlink();}@@ -230,7 +187,7 @@ export class TextInputPlugin implements Plugin {// half a width to the left, top edge half a height above (world y-up).const tr = world.get(entity, Transform) as TransformData;const fieldLeft = tr.worldPosition.x - width / 2;- const val = textarea.value; // focused ⇒ the textarea is the value source+ const val = editor!.read().value; // focused ⇒ the surface is the value sourceconst atlas = ensureMeasure().atlas;const mw = (s: string): number => measureWidth(s, atlas, ti.fontFamily, ti.fontSize, 0);@@ -257,17 +214,17 @@ export class TextInputPlugin implements Plugin {return nearestCaretIndex(prefixes, textX);}- function activateTextarea(entity: Entity): void {+ function activateEditor(entity: Entity): void {const ti = world.get(entity, TextInput) as TextInputData;if (ti.readOnly) return;ti.focused = true;ti.dirty = true;- textarea.value = ti.value;- textarea.selectionStart = ti.cursorPos;- textarea.selectionEnd = ti.cursorPos;- textarea.focus();+ editor!.focus(+ { value: ti.value, selectionStart: ti.cursorPos, selectionEnd: ti.cursorPos, backward: false },+ { multiline: ti.multiline, maxLength: ti.maxLength, password: ti.password },+ );resetCursorBlink();}@@ -280,22 +237,14 @@ export class TextInputPlugin implements Plugin {}const fm = app.getResource(FocusManager) as FocusManagerState;fm.blur();- textarea.blur();+ editor!.blur();}- /** Park the hidden textarea off-screen (no field focused). */- function parkTextarea(): void {- if (textarea.style.left !== '-9999px') {- textarea.style.left = '-9999px';- textarea.style.top = '-9999px';- }- }-- /** Move the hidden textarea onto the caret's on-screen position so the OS- * IME candidate window pops just under the caret, not at the screen- * corner. `caretBottom` is the caret's bottom edge in field-local px- * (y-down from the box top). */- function positionTextareaAtCaret(entity: Entity, caretX: number, caretBottom: number): void {+ /** Put the surface's caret anchor at the caret's on-screen position, so the+ * OS IME pops its candidate window just under the text being typed rather+ * than in a screen corner. `caretBottom` is the caret's bottom edge in+ * field-local px (y-down from the box top). */+ function anchorCaret(entity: Entity, caretX: number, caretBottom: number): void {const cam = app.getResource(UICameraInfo) as UICameraData | undefined;if (!cam || !cam.valid || !world.has(entity, Transform)) return;const tr = world.get(entity, Transform) as TransformData;@@ -306,8 +255,7 @@ export class TextInputPlugin implements Plugin {const worldY = (tr.worldPosition.y + h / 2) - caretBottom; // world y-upconst scr = uiWorldToScreen(cam, worldX, worldY);const css = imeAnchorCss(scr.x, scr.y, cam.screenH, platformDevicePixelRatio());- textarea.style.left = Math.round(css.left) + 'px';- textarea.style.top = Math.round(css.top) + 'px';+ editor!.setCaretAnchor?.(css.left, css.top);}function resetCursorBlink(): void {@@ -333,11 +281,11 @@ export class TextInputPlugin implements Plugin {const ti = world.get(prevFocusedTextInput, TextInput) as TextInputData;ti.focused = false;ti.dirty = true;- textarea.blur();+ editor.blur();}if (currentFocused !== null) {- activateTextarea(currentFocused);+ activateEditor(currentFocused);}prevFocusedTextInput = currentFocused;@@ -352,8 +300,7 @@ export class TextInputPlugin implements Plugin {if (inter.justPressed) {const idx = caretIndexFromPointer(currentFocused);if (idx !== null) {- textarea.selectionStart = idx;- textarea.selectionEnd = idx;+ editor.write({ ...editor.read(), selectionStart: idx, selectionEnd: idx, backward: false });const ti = world.get(currentFocused, TextInput) as TextInputData;ti.cursorPos = idx;ti.dirty = true;@@ -384,8 +331,6 @@ export class TextInputPlugin implements Plugin {cursorTimer -= CURSOR_BLINK_INTERVAL;cursorVisible = !cursorVisible;}- } else {- parkTextarea();}// Reap the child entities of removed inputs.@@ -406,20 +351,17 @@ export class TextInputPlugin implements Plugin {ensureBackground(entity, ti);const ch = ensureChildren(entity, ti);- // While focused, the hidden textarea is the single source of- // truth for editing — caret moves, native Shift/Ctrl-A- // selection, and the live IME preedit all land there — so a- // focused field renders the textarea's value + selection; a- // blurred field renders its committed component value.+ // While focused, the editing surface is the single source of+ // truth — caret moves, native shift/Ctrl-A selection, and the+ // live IME preedit all land there — so a focused field renders+ // the surface's value + selection; a blurred field renders its+ // committed component value.const editing = focused === entity;- const val = editing ? textarea.value : ti.value;+ const state = editing ? editor.read() : null;+ const val = state ? state.value : ti.value;const len = val.length;- const sel = editing- ? fieldSelection(- textarea.selectionStart ?? len,- textarea.selectionEnd ?? len,- textarea.selectionDirection === 'backward',- len)+ const sel = state+ ? fieldSelection(state.selectionStart, state.selectionEnd, state.backward, len): { lo: 0, hi: 0, caret: Math.max(0, Math.min(ti.cursorPos, len)), hasRange: false };// Keep the component caret in step so a blur/refocus restores it.if (editing && ti.cursorPos !== sel.caret) ti.cursorPos = sel.caret;@@ -473,11 +415,10 @@ export class TextInputPlugin implements Plugin {// The blinking caret hides while a highlight is drawn.syncCaretChild(ch.caret, ti, caretX, caretTop, ti.focused && cursorVisible && !sshow);- // Anchor the hidden textarea at the caret so the IME candidate- // window pops there. Not while composing — moving it mid-- // composition would yank an open candidate window.+ // Anchor the IME at the caret. Not while composing — moving it+ // mid-composition would yank an open candidate window.if (editing && !composing) {- positionTextareaAtCaret(entity, caretX, caretTop + ti.fontSize);+ anchorCaret(entity, caretX, caretTop + ti.fontSize);}}},@@ -609,30 +550,4 @@ export class TextInputPlugin implements Plugin {}}-function createHiddenTextarea(): HTMLTextAreaElement | null {- if (typeof document === 'undefined' || !document.body) {- return null;- }- const textarea = document.createElement('textarea');- textarea.style.position = 'fixed';- // Parked off-screen until a field focuses, then moved to the caret so the IME- // candidate window anchors there (see positionTextareaAtCaret). Invisible and- // click-through so the on-screen textarea never shows or steals a pointer.- textarea.style.left = '-9999px';- textarea.style.top = '-9999px';- textarea.style.width = '1px';- textarea.style.height = '1px';- textarea.style.opacity = '0';- textarea.style.zIndex = '-1';- textarea.style.pointerEvents = 'none';- textarea.style.border = '0';- textarea.style.padding = '0';- textarea.autocomplete = 'off';- textarea.setAttribute('autocorrect', 'off');- textarea.setAttribute('autocapitalize', 'off');- textarea.setAttribute('spellcheck', 'false');- document.body.appendChild(textarea);- return textarea;-}-export const textInputPlugin = new TextInputPlugin();diff --git a/sdk/tests/ui-plugin-cleanup.test.ts b/sdk/tests/ui-plugin-cleanup.test.tsindex ef85407a4..eebcd11fd 100644--- a/sdk/tests/ui-plugin-cleanup.test.ts+++ b/sdk/tests/ui-plugin-cleanup.test.ts@@ -13,6 +13,8 @@ import { textInputPlugin, TextInputPlugin } from '../src/ui/text/text-input-plugimport { AppContext, setDefaultContext } from '../src/context';import { setEditorMode, setPlayMode } from '../src/env';import { createMockModule } from './mocks/wasm';+import { setPlatform } from '../src/platform/base';+import { webAdapter } from '../src/platform/web';describe('UIPlugin teardown', () => {it('forwards cleanup to sub-plugins in reverse build order', () => {@@ -53,6 +55,9 @@ describe('UIPlugin teardown', () => {setDefaultContext(new AppContext());setEditorMode(false);setPlayMode(false);+ // The field is edited through the platform's text-editing surface, which+ // on the web IS that hidden textarea (platform/webTextEditor.ts).+ setPlatform(webAdapter);const app = App.new();const module = createMockModule();app.connectCpp(module.getRegistry(), module);