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): TextInput stands on a world rectangle as well as a UI node, and a Cocos EditBox becomes it: the importer folds the two labels into the field and the layer's EditBox is a view on it

yhhd182168991b5
diff --git a/pipeline/src/import/cocos/convert.ts b/pipeline/src/import/cocos/convert.ts
index c93cc8d38..024e23d4f 100644
--- a/pipeline/src/import/cocos/convert.ts
+++ b/pipeline/src/import/cocos/convert.ts
@@ -14,6 +14,7 @@
* `slot/localId`, a prefab's own entities are bare ids.
*/
import { convertNode, sameData, type ComponentContext, type ComponentData } from './components';
+import { foldEditBoxes } from './editBoxFold';
import { NODE_REF, type CocosDocument, type CocosNode, type CocosOverride } from './document';
import { ImportReport } from './report';
import { anchoredRect, type RectAnchorsData } from '../../../../sdk/src/ui/layout/rect-anchors';
@@ -436,7 +437,8 @@ export function convertPrefab(doc: CocosDocument, ctx: ConvertContext): PrefabFi
// A reference to a node of this prefab is that node's prefab-local id; a prefab's refs are strings the loader maps.
const own = new Set(entities.map((e) => e.prefabEntityId));
for (const e of entities) resolveRefs(e.components, (id) => (own.has(id) ? id : ''), '');
- return { version: '2', name: doc.name, rootEntityId: root.id, entities };
+ // an edit box is the engine's text field, with the style its two labels had; the labels are not written
+ return { version: '2', name: doc.name, rootEntityId: root.id, entities: foldEditBoxes(entities, (e) => e.prefabEntityId) };
}
/**
@@ -510,6 +512,12 @@ export function convertScene(doc: CocosDocument, ctx: ConvertContext): SceneFile
for (const r of doc.roots) walk(r, null);
// 0 is the engine's "no entity"; the loader maps the rest.
for (const e of entities) if ('components' in e) resolveRefs(e.components, (id) => ids.get(id) ?? 0, 0);
+ // an edit box is the engine's text field, with the style its two labels had; the labels are not written
+ const withComponents = entities.filter((e): e is SceneEntity => 'components' in e);
+ const surviving = new Set<SceneEntity | SceneInstanceEntry>(foldEditBoxes(withComponents, (e) => e.id));
+ const folded = entities.filter((e) => !('components' in e) || surviving.has(e));
+ entities.length = 0;
+ entities.push(...folded);
if (ctx.design) for (const e of entities) if ('components' in e && e.parent === null) placeInDesign(e.components, ctx.design);
return { version: 4, name: doc.name, entities };
}
diff --git a/pipeline/src/import/cocos/editBoxFold.ts b/pipeline/src/import/cocos/editBoxFold.ts
new file mode 100644
index 000000000..77100967b
--- /dev/null
+++ b/pipeline/src/import/cocos/editBoxFold.ts
@@ -0,0 +1,106 @@
+// SPDX-License-Identifier: Apache-2.0
+// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team
+/**
+ * @file editBoxFold.ts
+ * @brief A Cocos edit box becomes the engine's `TextInput`, and the two labels it was built from are folded into it.
+ *
+ * In Cocos an edit box is a node with a component and two children, a label for the typed text and one for the hint, which the
+ * component keeps in step. The engine's field draws its own text and hint, caret and selection, so what those two labels said — the
+ * font, the size, the colours, the alignment, where the text starts inside the box — is the field's own style, and the two nodes are not
+ * written: there is nothing for them to be.
+ *
+ * Done after the references between nodes are resolved, because the labels are named by the component as nodes of the document.
+ */
+import type { ComponentData } from './components';
+
+type Raw = Record<string, unknown>;
+
+/** The part of a converted entity this needs: what it carries and who it holds. */
+export interface FoldEntity {
+ components: ComponentData[];
+ children: Array<string | number>;
+}
+
+const COCOS_EDIT_BOX = 'Cocos.EditBox';
+
+/** Cocos's `InputMode`: ANY, EMAIL, NUMERIC, PHONE_NUMBER, URL, DECIMAL, SINGLE_LINE. */
+const NUMERIC = 2, PHONE_NUMBER = 3, DECIMAL = 5, ANY = 0;
+/** The engine's `TextInputFilter`. */
+const FILTER = { none: 0, digits: 1, decimal: 2, phone: 3 };
+const PASSWORD = 0;
+
+const isObj = (v: unknown): v is Raw => typeof v === 'object' && v !== null && !Array.isArray(v);
+const num = (v: unknown, fallback: number): number => (typeof v === 'number' && Number.isFinite(v) ? v : fallback);
+const part = (e: FoldEntity, type: string): Raw | null => (e.components.find((c) => c.type === type)?.data as Raw | undefined) ?? null;
+
+/** Where the label's text starts inside the box, measured from the box's left edge: the field's padding. */
+function paddingOf(box: FoldEntity, label: FoldEntity | null): number {
+ if (!label) return 0;
+ const boxRect = part(box, 'ContentRect');
+ const labelRect = part(label, 'ContentRect');
+ const labelAt = part(label, 'Transform');
+ if (!boxRect || !labelRect || !labelAt) return 0;
+ const size = (r: Raw): { x: number; y: number } => (isObj(r.size) ? { x: num(r.size.x, 0), y: num(r.size.y, 0) } : { x: 0, y: 0 });
+ const pivot = (r: Raw): { x: number; y: number } => (isObj(r.pivot) ? { x: num(r.pivot.x, 0.5), y: num(r.pivot.y, 0.5) } : { x: 0.5, y: 0.5 });
+ const position = isObj(labelAt.position) ? num(labelAt.position.x, 0) : 0;
+ const boxLeft = -pivot(boxRect).x * size(boxRect).x;
+ const labelLeft = position - pivot(labelRect).x * size(labelRect).x;
+ return Math.max(0, Math.round((labelLeft - boxLeft) * 100) / 100);
+}
+
+/**
+ * Replace each edit box component by a `TextInput` carrying the style of its labels, and drop the labels' entities (with whatever is
+ * under them) from @p entities. @p idOf names an entity the way the component's references do. Entities that are not edit boxes, and
+ * those a reference could not be resolved for, are left as they are.
+ */
+export function foldEditBoxes<E extends FoldEntity>(entities: E[], idOf: (e: E) => string | number): E[] {
+ const byId = new Map<string | number, E>(entities.map((e) => [idOf(e), e]));
+ const dropped = new Set<string | number>();
+ const dropWithDescendants = (id: string | number): void => {
+ if (dropped.has(id)) return;
+ dropped.add(id);
+ for (const child of byId.get(id)?.children ?? []) dropWithDescendants(child);
+ };
+
+ for (const entity of entities) {
+ const index = entity.components.findIndex((c) => c.type === COCOS_EDIT_BOX);
+ if (index < 0) continue;
+ const box = entity.components[index]!.data as Raw;
+ const textId = box.textLabel as string | number | undefined;
+ const hintId = box.placeholderLabel as string | number | undefined;
+ const textEntity = textId !== undefined && textId !== '' && textId !== 0 ? byId.get(textId) ?? null : null;
+ const hintEntity = hintId !== undefined && hintId !== '' && hintId !== 0 ? byId.get(hintId) ?? null : null;
+ const text = textEntity ? part(textEntity, 'Text') : null;
+ const hint = hintEntity ? part(hintEntity, 'Text') : null;
+ // the typed text's style leads; a box that has only the hint takes the size and the font from it
+ const style = text ?? hint ?? {};
+
+ const mode = num(box.inputMode, ANY);
+ const inputFilter = mode === NUMERIC ? FILTER.digits : mode === DECIMAL ? FILTER.decimal : mode === PHONE_NUMBER ? FILTER.phone : FILTER.none;
+ const data: Raw = {
+ value: typeof box.string_ === 'string' ? box.string_ : '',
+ placeholder: hint && typeof hint.content === 'string' ? hint.content : '',
+ maxLength: num(box.maxLength, 0) > 0 ? num(box.maxLength, 0) : 0,
+ inputFilter,
+ multiline: mode === ANY,
+ password: num(box.inputFlag, 5) === PASSWORD,
+ readOnly: box.enabled === false,
+ fontSize: num(style.fontSize, 16),
+ padding: paddingOf(entity, textEntity ?? hintEntity),
+ textAlign: num(style.align, 0),
+ renderMode: num(style.renderMode, 0),
+ };
+ if (isObj(text?.color)) data.color = text!.color;
+ if (isObj(hint?.color)) data.placeholderColor = hint!.color;
+ if (typeof style.fontFamily === 'string' && style.fontFamily !== '') data.fontFamily = style.fontFamily;
+ if (typeof style.font === 'string' || (typeof style.font === 'number' && style.font !== 0)) data.font = style.font;
+ entity.components[index] = { type: 'TextInput', data };
+
+ for (const labelId of [textId, hintId]) {
+ if (labelId === undefined || !byId.has(labelId)) continue;
+ dropWithDescendants(labelId);
+ entity.children = entity.children.filter((c) => c !== labelId);
+ }
+ }
+ return dropped.size === 0 ? entities : entities.filter((e) => !dropped.has(idOf(e)));
+}
diff --git a/pipeline/src/import/cocos/importProject.ts b/pipeline/src/import/cocos/importProject.ts
index 1ffd407ca..4cf1c4918 100644
--- a/pipeline/src/import/cocos/importProject.ts
+++ b/pipeline/src/import/cocos/importProject.ts
@@ -31,7 +31,7 @@ import { convertPass, isOutlinePass, type PassConversion } from './effectConvert
* importer that made less (or differently), and is brought up to date when it is opened. Raise it when the converted output changes in a
* way an existing project needs to pick up: a new generated file, a field a document or a manifest now carries.
*/
-export const COCOS_IMPORT_REVISION = 9;
+export const COCOS_IMPORT_REVISION = 10;
/** Whether the project at @p projectRoot was written by an importer of this revision. A project that was not converted has nothing to bring up. */
export function cocosImportIsCurrent(projectRoot: string): boolean {
diff --git a/pipeline/tests/cocos-editbox-fold.test.ts b/pipeline/tests/cocos-editbox-fold.test.ts
new file mode 100644
index 000000000..c9f52240e
--- /dev/null
+++ b/pipeline/tests/cocos-editbox-fold.test.ts
@@ -0,0 +1,64 @@
+// SPDX-License-Identifier: Apache-2.0
+// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team
+/**
+ * @file A Cocos edit box becomes the engine's text field with the style its two labels had, and the labels are not written.
+ */
+import { describe, expect, it } from 'vitest';
+import { foldEditBoxes, type FoldEntity } from '../src/import/cocos/editBoxFold';
+
+interface E extends FoldEntity { id: string }
+
+const rect = (w: number, h: number, px = 0.5, py = 0.5) => ({ type: 'ContentRect', data: { size: { x: w, y: h }, pivot: { x: px, y: py } } });
+const at = (x: number, y = 0) => ({ type: 'Transform', data: { position: { x, y, z: 0 } } });
+const color = (r: number, g: number, b: number) => ({ r, g, b, a: 1 });
+
+function field(over: Record<string, unknown> = {}): E[] {
+ return [
+ {
+ id: 'box', children: ['text', 'hint', 'other'],
+ components: [
+ at(0), rect(400, 80),
+ { type: 'Cocos.EditBox', data: { string_: '7930', maxLength: 20, inputMode: 6, inputFlag: 5, returnType: 0, tabIndex: 0, textLabel: 'text', placeholderLabel: 'hint', ...over } },
+ ],
+ },
+ { id: 'text', children: ['caretInside'], components: [at(-180), rect(380, 80, 0, 0.5), { type: 'Text', data: { content: '', fontSize: 36, color: color(1, 1, 1), align: 0, fontFamily: 'Arial', renderMode: 0 } }] },
+ { id: 'caretInside', children: [], components: [at(0), rect(2, 30)] },
+ { id: 'hint', children: [], components: [at(-180), rect(380, 80, 0, 0.5), { type: 'Text', data: { content: '输入账号', fontSize: 36, color: color(0.5, 0.5, 0.5), align: 0 } }] },
+ { id: 'other', children: [], components: [at(100), rect(40, 40)] },
+ ];
+}
+
+describe('folding an edit box into the engine field', () => {
+ it('becomes a TextInput with the style of its labels, and the labels are not kept', () => {
+ const out = foldEditBoxes(field(), (e) => e.id);
+ expect(out.map((e) => e.id)).toEqual(['box', 'other']);
+ const box = out[0]!;
+ expect(box.children).toEqual(['other']);
+ const input = box.components.find((c) => c.type === 'TextInput')!;
+ expect(box.components.some((c) => c.type === 'Cocos.EditBox')).toBe(false);
+ expect(input.data).toMatchObject({
+ value: '7930', placeholder: '输入账号', maxLength: 20, multiline: false, password: false, inputFilter: 0,
+ fontSize: 36, fontFamily: 'Arial', textAlign: 0,
+ color: color(1, 1, 1), placeholderColor: color(0.5, 0.5, 0.5),
+ });
+ // the text starts 20 units inside the box's left edge: that is the field's padding
+ expect(input.data.padding).toBe(20);
+ });
+
+ it('turns the input mode into the field\'s filter and line mode, and the flag into a password', () => {
+ const numeric = foldEditBoxes(field({ inputMode: 2 }), (e) => e.id)[0]!.components.find((c) => c.type === 'TextInput')!;
+ expect(numeric.data).toMatchObject({ inputFilter: 1, multiline: false });
+ const any = foldEditBoxes(field({ inputMode: 0 }), (e) => e.id)[0]!.components.find((c) => c.type === 'TextInput')!;
+ expect(any.data).toMatchObject({ inputFilter: 0, multiline: true });
+ const secret = foldEditBoxes(field({ inputFlag: 0 }), (e) => e.id)[0]!.components.find((c) => c.type === 'TextInput')!;
+ expect(secret.data.password).toBe(true);
+ // no limit in Cocos is a negative one; the field's is zero
+ const unlimited = foldEditBoxes(field({ maxLength: -1 }), (e) => e.id)[0]!.components.find((c) => c.type === 'TextInput')!;
+ expect(unlimited.data.maxLength).toBe(0);
+ });
+
+ it('leaves a scene with no edit box exactly as it is', () => {
+ const plain: E[] = [{ id: 'a', children: ['b'], components: [at(0)] }, { id: 'b', children: [], components: [at(1)] }];
+ expect(foldEditBoxes(plain, (e) => e.id)).toBe(plain);
+ });
+});
diff --git a/sdk/etc/index.api.md b/sdk/etc/index.api.md
index 74a3d7f9e..2f692fdf2 100644
--- a/sdk/etc/index.api.md
+++ b/sdk/etc/index.api.md
@@ -829,6 +829,7 @@ editorMode: boolean
pendingPlugins: unknown[]
pendingSystems: PendingSystemEntry[]
playMode: boolean
+queueEpoch: number
reset: () => void
wasmError: WasmErrorState
static new (): AppContext
diff --git a/sdk/etc/index.native.api.md b/sdk/etc/index.native.api.md
index 460136ef5..d8f8f83ce 100644
--- a/sdk/etc/index.native.api.md
+++ b/sdk/etc/index.native.api.md
@@ -829,6 +829,7 @@ editorMode: boolean
pendingPlugins: unknown[]
pendingSystems: PendingSystemEntry[]
playMode: boolean
+queueEpoch: number
reset: () => void
wasmError: WasmErrorState
static new (): AppContext
diff --git a/sdk/etc/index.node.api.md b/sdk/etc/index.node.api.md
index 4ffb03d50..ce5a1287a 100644
--- a/sdk/etc/index.node.api.md
+++ b/sdk/etc/index.node.api.md
@@ -824,6 +824,7 @@ editorMode: boolean
pendingPlugins: unknown[]
pendingSystems: PendingSystemEntry[]
playMode: boolean
+queueEpoch: number
reset: () => void
wasmError: WasmErrorState
static new (): AppContext
diff --git a/sdk/etc/minigame.api.md b/sdk/etc/minigame.api.md
index 43b95ef14..7714aa3a2 100644
--- a/sdk/etc/minigame.api.md
+++ b/sdk/etc/minigame.api.md
@@ -824,6 +824,7 @@ editorMode: boolean
pendingPlugins: unknown[]
pendingSystems: PendingSystemEntry[]
playMode: boolean
+queueEpoch: number
reset: () => void
wasmError: WasmErrorState
static new (): AppContext
diff --git a/sdk/etc/wechat.api.md b/sdk/etc/wechat.api.md
index c143e18fe..0a0ef7e55 100644
--- a/sdk/etc/wechat.api.md
+++ b/sdk/etc/wechat.api.md
@@ -824,6 +824,7 @@ editorMode: boolean
pendingPlugins: unknown[]
pendingSystems: PendingSystemEntry[]
playMode: boolean
+queueEpoch: number
reset: () => void
wasmError: WasmErrorState
static new (): AppContext
diff --git a/sdk/src/cocos/ui/editBox.ts b/sdk/src/cocos/ui/editBox.ts
index bf45e7916..eff4cfa7b 100644
--- a/sdk/src/cocos/ui/editBox.ts
+++ b/sdk/src/cocos/ui/editBox.ts
@@ -2,24 +2,29 @@
// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team
/**
* @file cocos/ui/editBox.ts
- * @brief `EditBox`: a text field whose box and labels are nodes of the scene, typed into through the platform's own text editor.
+ * @brief `EditBox`: a view on the engine's `TextInput`, as `Label` is a view on `Text`.
*
- * The engine's `TextInput` composes its own flex-laid-out children, and an imported scene is world-space nodes: an EditBox here is the box a
- * scene already drew, a `Label` that shows what was typed and one that shows the hint. A click on the box takes focus on the OS editing surface
- * (a hidden textarea on the web, the soft keyboard and its IME on a device), whose value the labels follow. A host with no such surface shows the
- * box and does not type, as the engine's own fields do.
+ * The engine's field does everything an edit box does — it takes focus on a press, holds the value and the selection on the platform's own
+ * text surface (a hidden textarea on the web, the soft keyboard and its IME on a device), draws the text, the hint, the caret and the
+ * selection, and scrolls to keep the caret in view. An imported scene's edit box is that field on the node that was the box, with the
+ * style its two labels carried; nothing here holds a second copy of any of it. What a script reaches through `textLabel` and
+ * `placeholderLabel` — a colour, a size, a string — is the field's own style, handed back as a label-shaped object.
*/
import { Component } from '../component';
import { Node } from '../node';
-import { declareClass } from '../host';
-import type { EventTouch } from '../input';
-import { Label } from './label';
-import { UITransform } from './uiTransform';
-import { EventHandler, joinHandlers } from './button';
-import { platformCreateTextEditor } from '../../platform';
-import type { PlatformTextEditor } from '../../platform/types';
-
-type Handlers = Array<{ component: string; handler: string; customEventData: string }>;
+import type { World } from '../../ecs/world';
+import type { Entity } from '../../types';
+import { TextInput, TextInputFilter, type TextInputData } from '../../ui/text/text-input';
+import { TextAlign } from '../../ui/core/text';
+import { FocusManager, Focusable, type FocusManagerState } from '../../ui/input/focusable';
+import { UIEventType } from '../../ui/core/events';
+import { EntityEvents, type EntityEventQueue } from '../../ecs/entityEvents';
+import { Schedule, defineSystem, addSystemToSchedule, GetWorld } from '../../ecs/system';
+import { Res } from '../../ecs/resource';
+import { SystemLabel } from '../../ecs/systemLabels';
+import { Color } from '../math';
+import { registerBuiltinComponent } from '../builtins';
+import { toCocosColor, toEngineColor, viewAdapter } from './view';
const InputMode = Object.freeze({ ANY: 0, EMAIL: 1, NUMERIC: 2, PHONE_NUMBER: 3, URL: 4, DECIMAL: 5, SINGLE_LINE: 6 });
const InputFlag = Object.freeze({ PASSWORD: 0, SENSITIVE: 1, INITIAL_CAPS_WORD: 2, INITIAL_CAPS_SENTENCE: 3, INITIAL_CAPS_ALL_CHARACTERS: 4, DEFAULT: 5 });
@@ -28,20 +33,64 @@ const EventType = Object.freeze({
EDITING_DID_BEGAN: 'editing-did-began', EDITING_DID_ENDED: 'editing-did-ended', TEXT_CHANGED: 'text-changed', EDITING_RETURN: 'editing-return',
});
-/** The characters a field of this input mode takes. */
-function allowed(mode: number, value: string): string {
+/** The filter and the line mode the engine's field has for a Cocos input mode. */
+function fieldMode(mode: number): { inputFilter: TextInputFilter; multiline: boolean } {
switch (mode) {
- case InputMode.NUMERIC: return value.replace(/[^0-9]/g, '');
- case InputMode.DECIMAL: return value.replace(/[^0-9.\-]/g, '');
- case InputMode.PHONE_NUMBER: return value.replace(/[^0-9+*#\-]/g, '');
+ case InputMode.NUMERIC: return { inputFilter: TextInputFilter.Digits, multiline: false };
+ case InputMode.DECIMAL: return { inputFilter: TextInputFilter.Decimal, multiline: false };
+ case InputMode.PHONE_NUMBER: return { inputFilter: TextInputFilter.Phone, multiline: false };
case InputMode.EMAIL:
case InputMode.URL:
- case InputMode.SINGLE_LINE: return value.replace(/[\r\n]/g, '');
- default: return value;
+ case InputMode.SINGLE_LINE: return { inputFilter: TextInputFilter.None, multiline: false };
+ default: return { inputFilter: TextInputFilter.None, multiline: true };
}
}
-const BULLET = '●';
+/** The Cocos input mode a field's settings say, as far as they can: the filter decides, then the line mode. */
+function modeOf(data: TextInputData): number {
+ if (data.inputFilter === TextInputFilter.Digits) return InputMode.NUMERIC;
+ if (data.inputFilter === TextInputFilter.Decimal) return InputMode.DECIMAL;
+ if (data.inputFilter === TextInputFilter.Phone) return InputMode.PHONE_NUMBER;
+ return data.multiline ? InputMode.ANY : InputMode.SINGLE_LINE;
+}
+
+/**
+ * What a script holds as an edit box's `textLabel` or `placeholderLabel`: the style of the field's text or of its hint, with a label's
+ * names. There is no node behind it — the engine draws the field's text itself — so the properties read and write the field.
+ */
+class FieldLabel {
+ constructor(private readonly box: EditBox, private readonly hint: boolean) {}
+
+ get node(): Node { return this.box.node; }
+ get enabled(): boolean { return true; }
+ set enabled(_v: boolean) {}
+
+ get string(): string { return this.hint ? this.box.placeholder : this.box.string; }
+ set string(v: string) { if (this.hint) this.box.placeholder = v; else this.box.string = v; }
+
+ get color(): Color { const d = this.box._data(); return toCocosColor(this.hint ? d.placeholderColor : d.color); }
+ set color(v: Color) { this.box._patch(this.hint ? { placeholderColor: toEngineColor(v) } : { color: toEngineColor(v) }); }
+
+ get fontSize(): number { return this.box._data().fontSize; }
+ set fontSize(v: number) { this.box._patch({ fontSize: v }); }
+ get actualFontSize(): number { return this.fontSize; }
+ get fontFamily(): string { return this.box._data().fontFamily; }
+ set fontFamily(v: string) { this.box._patch({ fontFamily: v }); }
+
+ /** The field lays its lines out at a fixed ratio of the size; a script that reads the pixel height gets that one back. */
+ lineHeight = 0;
+ horizontalAlign = 0;
+ verticalAlign = 1;
+ overflow = 0;
+ enableWrapText = false;
+ isBold = false;
+ isItalic = false;
+ isUnderline = false;
+ useSystemFont = true;
+ cacheMode = 0;
+ updateRenderData(_force = false): void {}
+ markForUpdateRenderData(_enable = true): void {}
+}
export class EditBox extends Component {
static readonly EventType = EventType;
@@ -49,151 +98,104 @@ export class EditBox extends Component {
static readonly InputFlag = InputFlag;
static readonly KeyboardReturnType = KeyboardReturnType;
- maxLength = 20;
- inputMode: number = InputMode.ANY;
- inputFlag: number = InputFlag.DEFAULT;
+ /** @internal */
+ _data(): TextInputData { return this._world.get(this._entity, TextInput); }
+ /** @internal */
+ _patch(patch: Partial<TextInputData>): void { this._world.set(this._entity, TextInput, { ...this._data(), ...patch }); }
+
returnType: number = KeyboardReturnType.DEFAULT;
- tabIndex = 0;
- textLabel: Label | null = null;
- placeholderLabel: Label | null = null;
-
- editingDidBeganTargets: Array<Node | null> = [];
- editingDidBeganHandlers: Handlers = [];
- textChangedTargets: Array<Node | null> = [];
- textChangedHandlers: Handlers = [];
- editingDidEndedTargets: Array<Node | null> = [];
- editingDidEndedHandlers: Handlers = [];
- editingReturnTargets: Array<Node | null> = [];
- editingReturnHandlers: Handlers = [];
- editingDidBegan: EventHandler[] = [];
- textChanged: EventHandler[] = [];
- editingDidEnded: EventHandler[] = [];
- editingReturn: EventHandler[] = [];
-
- private string_ = '';
- private editor_: PlatformTextEditor | null = null;
- private unsubscribe_: (() => void) | null = null;
-
- get string(): string { return this.string_; }
+ private readonly textLabel_ = new FieldLabel(this, false);
+ private readonly placeholderLabel_ = new FieldLabel(this, true);
+
+ get textLabel(): FieldLabel { return this.textLabel_; }
+ set textLabel(_v: unknown) {}
+ get placeholderLabel(): FieldLabel { return this.placeholderLabel_; }
+ set placeholderLabel(_v: unknown) {}
+
+ get string(): string { return this._data().value; }
set string(value: string) {
- this.string_ = this.fit_(value);
- this.refresh_();
+ const text = value === null || value === undefined ? '' : String(value);
+ // the field's own rules apply to what a script puts in as to what is typed: the caret follows to the end of it
+ this._patch({ value: text, cursorPos: text.length });
}
/** The hint shown while the field is empty. */
- get placeholder(): string { return this.placeholderLabel?.string ?? ''; }
- set placeholder(value: string) { if (this.placeholderLabel) this.placeholderLabel.string = value; }
+ get placeholder(): string { return this._data().placeholder; }
+ set placeholder(value: string) { this._patch({ placeholder: value }); }
- isFocused(): boolean { return this.editor_ !== null; }
+ get maxLength(): number { return this._data().maxLength || -1; }
+ set maxLength(value: number) { this._patch({ maxLength: value > 0 ? value : 0 }); }
- onLoad(): void {
- if (this.editingDidBegan.length === 0) this.editingDidBegan = joinHandlers(this.editingDidBeganTargets, this.editingDidBeganHandlers);
- if (this.textChanged.length === 0) this.textChanged = joinHandlers(this.textChangedTargets, this.textChangedHandlers);
- if (this.editingDidEnded.length === 0) this.editingDidEnded = joinHandlers(this.editingDidEndedTargets, this.editingDidEndedHandlers);
- if (this.editingReturn.length === 0) this.editingReturn = joinHandlers(this.editingReturnTargets, this.editingReturnHandlers);
- }
+ get inputMode(): number { return modeOf(this._data()); }
+ set inputMode(value: number) { this._patch(fieldMode(value)); }
- onEnable(): void {
- this.node.on(Node.EventType.TOUCH_END, this.onTouchEnd_, this);
- this.refresh_();
- }
+ get inputFlag(): number { return this._data().password ? InputFlag.PASSWORD : InputFlag.DEFAULT; }
+ set inputFlag(value: number) { this._patch({ password: value === InputFlag.PASSWORD }); }
- onDisable(): void {
- this.node.off(Node.EventType.TOUCH_END, this.onTouchEnd_, this);
- this.blur();
+ get tabIndex(): number { return this._world.tryGet(this._entity, Focusable)?.tabIndex ?? 0; }
+ set tabIndex(value: number) {
+ const focusable = this._world.tryGet(this._entity, Focusable);
+ if (focusable) this._world.set(this._entity, Focusable, { ...focusable, tabIndex: value });
}
- private onTouchEnd_(event: EventTouch): void {
- const inside = this.node.getComponent(UITransform)?.isHit(event.getUILocation()) ?? true;
- if (inside) this.focus();
- event.stopPropagation();
- }
+ get enabled(): boolean { return !this._data().readOnly; }
+ set enabled(value: boolean) { this._patch({ readOnly: !value }); }
+
+ isFocused(): boolean { return this._data().focused; }
- /** Take the keyboard, as a click on the box does. */
+ /** Take the keyboard, as a press on the box does. */
focus(): void {
- if (this.editor_ || !this.enabledInHierarchy) return;
- const editor = platformCreateTextEditor();
- if (!editor) return; // a host with no text surface shows the field and does not type
- this.editor_ = editor;
- const end = this.string_.length;
- editor.focus(
- { value: this.string_, selectionStart: end, selectionEnd: end, backward: false },
- { multiline: this.inputMode === InputMode.ANY, maxLength: this.maxLength > 0 ? this.maxLength : 0, password: this.inputFlag === InputFlag.PASSWORD },
- );
- this.unsubscribe_ = editor.subscribe((event) => {
- if (event.kind === 'change') this.onChange_();
- else if (event.kind === 'submit') { this.fire_(this.editingReturn, EventType.EDITING_RETURN); this.blur(); }
- else if (event.kind === 'cancel' || event.kind === 'blur') this.blur();
- });
- this.refresh_();
- this.fire_(this.editingDidBegan, EventType.EDITING_DID_BEGAN);
+ focusOf.get(this._world)?.focus(this._entity, false);
}
/** Give the keyboard back. */
blur(): void {
- const editor = this.editor_;
- if (!editor) return;
- this.editor_ = null;
- this.unsubscribe_?.();
- this.unsubscribe_ = null;
- editor.blur();
- editor.dispose();
- this.refresh_();
- this.fire_(this.editingDidEnded, EventType.EDITING_DID_ENDED);
+ const manager = focusOf.get(this._world);
+ if (manager?.focusedEntity === this._entity) manager.blur();
}
+}
- private onChange_(): void {
- const editor = this.editor_;
- if (!editor) return;
- const state = editor.read();
- const value = this.fit_(state.value);
- if (value !== state.value) editor.write({ ...state, value, selectionStart: Math.min(state.selectionStart, value.length), selectionEnd: Math.min(state.selectionEnd, value.length) });
- if (value === this.string_) return;
- this.string_ = value;
- this.refresh_();
- EventHandler.emitEvents(this.textChanged, value, this);
- this.node.emit(EventType.TEXT_CHANGED, this);
- }
+/** The focus manager of each world, learned from the frame loop that runs the systems below. */
+const focusOf = new WeakMap<World, FocusManagerState>();
- private fit_(value: string): string {
- const text = allowed(this.inputMode, value);
- return this.maxLength > 0 && text.length > this.maxLength ? text.slice(0, this.maxLength) : text;
- }
+const hasField = (world: World, entity: Entity): boolean => world.has(entity, TextInput);
+const addField = (world: World, entity: Entity): void => {
+ // a text surface that holds one line unless the script says otherwise, as a Cocos box's default mode is any text with a line limit of its own
+ world.insert(entity, TextInput, { ...fieldMode(InputMode.ANY), maxLength: 20 });
+};
- private fire_(handlers: EventHandler[], type: string): void {
- EventHandler.emitEvents(handlers, this);
- this.node.emit(type, this);
- }
+registerBuiltinComponent(EditBox, ['cc.EditBox', 'EditBox'], viewAdapter(EditBox, hasField, addField));
- /** What the labels show: the text (as bullets for a password), or the hint while there is none. */
- private refresh_(): void {
- const shown = this.inputFlag === InputFlag.PASSWORD ? BULLET.repeat(this.string_.length) : this.string_;
- if (this.textLabel) {
- this.textLabel.string = shown;
- // The text label is authored switched off (the field starts empty); it is on while there is text, which is when Cocos shows it.
- this.textLabel.node.active = shown !== '';
- }
- if (this.placeholderLabel) this.placeholderLabel.node.active = this.string_ === '';
- }
-}
+/** What the engine's field says happened, as the events a Cocos edit box emits on its node. */
+const ToCocos: Record<string, string> = {
+ [UIEventType.Focus]: EventType.EDITING_DID_BEGAN,
+ [UIEventType.Blur]: EventType.EDITING_DID_ENDED,
+ [UIEventType.Change]: EventType.TEXT_CHANGED,
+ [UIEventType.Submit]: EventType.EDITING_RETURN,
+};
+const subscribed = new WeakMap<object, WeakSet<object>>();
+/** Register the system that turns the field's events into the edit box's, for a script that listens on the node. */
export function declareEditBox(): void {
- declareClass(EditBox as never, 'EditBox', [
- { name: 'string_', kind: 'string' },
- { name: 'maxLength', kind: 'number' },
- { name: 'inputMode', kind: 'number' },
- { name: 'inputFlag', kind: 'number' },
- { name: 'returnType', kind: 'number' },
- { name: 'tabIndex', kind: 'number' },
- { name: 'textLabel', kind: 'component', type: Label },
- { name: 'placeholderLabel', kind: 'component', type: Label },
- { name: 'editingDidBeganTargets', kind: 'node', array: true },
- { name: 'editingDidBeganHandlers', kind: 'json' },
- { name: 'textChangedTargets', kind: 'node', array: true },
- { name: 'textChangedHandlers', kind: 'json' },
- { name: 'editingDidEndedTargets', kind: 'node', array: true },
- { name: 'editingDidEndedHandlers', kind: 'json' },
- { name: 'editingReturnTargets', kind: 'node', array: true },
- { name: 'editingReturnHandlers', kind: 'json' },
- ]);
+ addSystemToSchedule(Schedule.PreUpdate, defineSystem(
+ [Res(EntityEvents), Res(FocusManager), GetWorld()],
+ (events, focus, world) => {
+ if (focus) focusOf.set(world, focus as FocusManagerState);
+ if (!events) return;
+ const queue = events as EntityEventQueue;
+ let seen = subscribed.get(world);
+ if (!seen) subscribed.set(world, (seen = new WeakSet()));
+ if (seen.has(queue)) return;
+ seen.add(queue);
+ for (const [engineType, cocosType] of Object.entries(ToCocos)) {
+ queue.on(engineType, (e) => {
+ // an event bubbles to interactable ancestors as copies; the node tree does its own, from the original only
+ if (e.currentTarget !== e.target || !world.valid(e.target) || !world.has(e.target, TextInput)) return;
+ const node = Node.for(world, e.target);
+ node.emit(cocosType, node.getComponent(EditBox));
+ });
+ }
+ },
+ { name: 'Cocos:EditBoxEvents', touches: { opaque: true }, runAfter: [SystemLabel.UIInteraction] },
+ ));
}
diff --git a/sdk/src/ui/text/text-input-plugin.ts b/sdk/src/ui/text/text-input-plugin.ts
index 115bfbb5f..a8f458873 100644
--- a/sdk/src/ui/text/text-input-plugin.ts
+++ b/sdk/src/ui/text/text-input-plugin.ts
@@ -15,12 +15,13 @@ import { Focusable, FocusManager, FocusManagerState } from '../input/focusable';
import type { FocusableData } from '../input/focusable';
import { isFocusEligible } from '../input/focus-inspection';
import { UICameraInfo, type UICameraData } from '../core/ui-camera-info';
-import { Transform, type TransformData } from '../../ecs/component';
-import { UIEvents, UIEventQueue, type UIEvent } from '../core/events';
+import { Transform, Sprite, type TransformData, type SpriteData } from '../../ecs/component';
+import { ContentRect } from '../core/content-rect';
+import { UIEvents, UIEventQueue, UIEventType, type UIEvent } from '../core/events';
import { Res } from '../../ecs/resource';
import { playModeOnly } from '../../ecs/env';
import { ensureComponent, getUINodeWidth, getUINodeHeight } from '../util/helpers';
-import { spawnUIEntity } from '../core/compose';
+import { spawnUIEntity, identityTransform, buildText } from '../core/compose';
import { px } from '../core/dimension';
import { SdfTextRenderer } from './text-renderer';
import type { ESEngineModule } from '../../wasm';
@@ -104,6 +105,34 @@ export class TextInputPlugin implements Plugin {
return measureRenderer;
};
+ /**
+ * The rectangle a field occupies, whichever kind of node it is on. A field laid out by the UI tree has a `UINode` (a CSS box centred on
+ * its transform); one standing in the world — an imported scene's input, a hand-built HUD — has a `ContentRect`, a size and the point of
+ * it the transform sits on. Everything below is written against this, so the editing, the caret, the selection and the click-to-caret
+ * are one implementation for both.
+ */
+ interface FieldBox {
+ w: number;
+ h: number;
+ /** Where the transform sits in the box, as a fraction from its left and from its bottom. */
+ px: number;
+ py: number;
+ /** Laid out in world space (a `ContentRect`), not by the UI tree. */
+ world: boolean;
+ }
+ function boxOf(entity: Entity): FieldBox | null {
+ if (world.has(entity, UINode)) return { w: getUINodeWidth(entity), h: getUINodeHeight(entity), px: 0.5, py: 0.5, world: false };
+ const rect = world.tryGet(entity, ContentRect);
+ return rect ? { w: rect.size.x, h: rect.size.y, px: rect.pivot.x, py: rect.pivot.y, world: true } : null;
+ }
+ /** The box's left edge and top edge in the world, and the scale local units have there. */
+ function boxFrame(entity: Entity, box: FieldBox): { left: number; top: number; sx: number; sy: number } {
+ const tr = world.get(entity, Transform) as TransformData;
+ const sx = box.world ? (tr.worldScale?.x || 1) : 1;
+ const sy = box.world ? (tr.worldScale?.y || 1) : 1;
+ return { left: tr.worldPosition.x - box.px * box.w * sx, top: tr.worldPosition.y + (1 - box.py) * box.h * sy, sx, sy };
+ }
+
let composing = false;
let editingEntity: Entity | null = null;
let nativeEvents: UIEvent[] = [];
@@ -181,6 +210,7 @@ export class TextInputPlugin implements Plugin {
const f = world.get(focused, Focusable) as FocusableData;
f.isFocused = false;
world.insert(focused, Focusable, f);
+ (app.getResource(UIEvents) as UIEventQueue).emit(focused, UIEventType.Blur);
}
}
break;
@@ -252,17 +282,17 @@ export class TextInputPlugin implements Plugin {
const cam = app.getResource(UICameraInfo) as UICameraData | undefined;
const overlay = app.getResource(ScreenOverlay) as ScreenOverlayData | undefined;
if (!cam || !overlay || (!cam.valid && !overlay.active)) return null;
- if (!world.has(entity, Transform) || !world.has(entity, UINode)) return null;
+ const box = boxOf(entity);
+ if (!world.has(entity, Transform) || !box) return null;
// The pointer in the FIELD's domain: every subtraction below is a
// pointer minus a transform, and the two have to be in one space.
const pointer = uiPointerFor(world, entity, cam, overlay);
const ti = world.get(entity, TextInput) as TextInputData;
- const width = getUINodeWidth(entity);
+ const width = box.w;
if (width <= 0) return null;
- // The layout centers the box on its Transform (pivot 0.5): left edge is
- // 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;
+ // Left edge and top edge of the box in the world (y-up), and the scale between the world and the box's own units.
+ const frame = boxFrame(entity, box);
+ const fieldLeft = frame.left;
const val = editor!.read().value; // focused ⇒ the surface is the value source
const atlas = ensureMeasure().atlas;
// The family the child Text will actually rasterize with. The caret is
@@ -274,15 +304,13 @@ export class TextInputPlugin implements Plugin {
const innerW = Math.max(0, width - 2 * ti.padding);
if (ti.multiline) {
- const height = getUINodeHeight(entity);
const lineH = ti.fontSize * TEXT_INPUT_LINE_HEIGHT_RATIO;
- const fieldTop = tr.worldPosition.y + height / 2;
- const localY = fieldTop - pointer.y; // y-down from the box top
+ const localY = (frame.top - pointer.y) / frame.sy; // y-down from the box top
const lines = splitLines(val);
const li = Math.max(0, Math.min(Math.floor(localY / lineH), lines.length - 1));
const line = lines[li];
// Each line carries its own alignment offset, so undo THIS line's.
- const textX = pointer.x - fieldLeft - ti.padding
+ const textX = (pointer.x - fieldLeft) / frame.sx - ti.padding
- alignOffset(ti.textAlign, innerW, mw(line.text));
const prefixes = measurePrefixWidths(line.text, atlas, family, ti.fontSize, 0);
return line.start + nearestCaretIndex(prefixes, textX, line.text);
@@ -293,7 +321,7 @@ export class TextInputPlugin implements Plugin {
// a focused field's value can differ from what was last drawn, and a
// guess about the offset lands the caret on the wrong glyph.
const ao = alignOffsetOf.get(entity) ?? 0;
- const textX = pointer.x - fieldLeft - ti.padding - ao + scrollX;
+ const textX = (pointer.x - fieldLeft) / frame.sx - ti.padding - ao + scrollX;
const display = ti.password ? PASSWORD_CHAR.repeat(val.length) : val;
const prefixes = measurePrefixWidths(display, atlas, family, ti.fontSize, 0);
return nearestCaretIndex(prefixes, textX, val);
@@ -321,6 +349,13 @@ export class TextInputPlugin implements Plugin {
}
const fm = app.getResource(FocusManager) as FocusManagerState;
fm.blur();
+ // The field lost focus, so it says so, as a control does when a press elsewhere takes it.
+ if (focused !== null && world.valid(focused) && world.has(focused, Focusable)) {
+ const f = world.get(focused, Focusable) as FocusableData;
+ f.isFocused = false;
+ world.insert(focused, Focusable, f);
+ (app.getResource(UIEvents) as UIEventQueue).emit(focused, UIEventType.Blur);
+ }
editingEntity = null;
composing = false;
editor!.blur();
@@ -334,14 +369,12 @@ export class TextInputPlugin implements Plugin {
const cam = app.getResource(UICameraInfo) as UICameraData | undefined;
const overlay = app.getResource(ScreenOverlay) as ScreenOverlayData | undefined;
if (!cam || !overlay || (!cam.valid && !overlay.active)) return;
- if (!world.has(entity, Transform)) return;
+ const box = boxOf(entity);
+ if (!world.has(entity, Transform) || !box) return;
const screen = isScreenEntity(world, entity);
- const tr = world.get(entity, Transform) as TransformData;
- const w = getUINodeWidth(entity);
- const h = getUINodeHeight(entity);
- // Box is centered on its Transform (pivot 0.5): left/top edges from it.
- const worldX = (tr.worldPosition.x - w / 2) + caretX;
- const worldY = (tr.worldPosition.y + h / 2) - caretBottom; // world y-up
+ const frame = boxFrame(entity, box);
+ const worldX = frame.left + caretX * frame.sx;
+ const worldY = frame.top - caretBottom * frame.sy; // world y-up
// Forward through whichever projection actually drew the field.
const scr = screen
? uiLayoutToScreen(overlay, worldX, worldY)
@@ -470,14 +503,15 @@ export class TextInputPlugin implements Plugin {
}
}
- for (const entity of world.getEntitiesWithComponents([TextInput, UINode])) {
+ for (const entity of world.getEntitiesWithComponents([TextInput])) {
const ti = world.get(entity, TextInput) as TextInputData;
- const w = getUINodeWidth(entity);
- const h = getUINodeHeight(entity);
- if (w <= 0 || h <= 0) continue;
+ const box = boxOf(entity);
+ if (!box || box.w <= 0 || box.h <= 0) continue;
+ const w = box.w;
+ const h = box.h;
- ensureBackground(entity, ti);
- const ch = ensureChildren(entity, ti);
+ ensureBackground(entity, ti, box);
+ const ch = ensureChildren(entity, ti, box);
// 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
@@ -549,10 +583,10 @@ export class TextInputPlugin implements Plugin {
scrollXOf.set(entity, scrollX);
alignOffsetOf.set(entity, ao);
- syncSelChild(ch.sel, ti, sshow, sx, stop, sw);
- syncTextChild(ch.text, ti, disp, innerW, scrollX, ao);
+ syncSelChild(ch.sel, ti, box, sshow, sx, stop, sw);
+ syncTextChild(ch.text, ti, box, disp, innerW, scrollX, ao);
// The blinking caret hides while a highlight is drawn.
- syncCaretChild(ch.caret, ti, caretX, caretTop, editing && ti.focused && cursorVisible && !sshow);
+ syncCaretChild(ch.caret, ti, box, caretX, caretTop, editing && ti.focused && cursorVisible && !sshow);
// Anchor the IME at the caret. Not while composing — moving it
// mid-composition would yank an open candidate window.
@@ -564,12 +598,14 @@ export class TextInputPlugin implements Plugin {
{ name: 'TextInputRenderSystem' }
));
- function ensureBackground(entity: Entity, ti: TextInputData): void {
+ function ensureBackground(entity: Entity, ti: TextInputData, box: FieldBox): 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.
if (!world.has(entity, UIMask)) {
world.insert(entity, UIMask, { enabled: true, mode: MaskMode.Scissor });
}
+ // A field standing in the world is drawn by the sprite its scene gave it: there is no background of the field's own to keep.
+ if (box.world) return;
if (!world.has(entity, UIVisual)) {
world.insert(entity, UIVisual, {
visualType: UIVisualType.SolidColor, texture: 0,
@@ -596,57 +632,121 @@ export class TextInputPlugin implements Plugin {
}
}
- function ensureChildren(entity: Entity, ti: TextInputData): { sel: Entity; text: Entity; caret: Entity } {
+ /** The sorting layer a world field draws on, so what it adds sorts with it (a tree-ordered layer stacks the children in place). */
+ function layerOf(entity: Entity): number {
+ return world.tryGet(entity, Sprite)?.layer ?? world.tryGet(entity, Text)?.layer ?? 0;
+ }
+
+ /** A world entity under @p parent with a top-left-anchored rectangle, which is how the field's parts are placed from its top-left. */
+ function spawnWorldPart(parent: Entity): Entity {
+ const e = world.spawn();
+ world.insert(e, Transform, identityTransform());
+ world.insert(e, ContentRect, { size: { x: 0, y: 0 }, pivot: { x: 0, y: 1 } });
+ world.setParent(e, parent);
+ return e;
+ }
+
+ function ensureChildren(entity: Entity, ti: TextInputData, box: FieldBox): { sel: Entity; text: Entity; caret: Entity } {
const existing = childrenOf.get(entity);
if (existing && world.valid(existing.sel) && world.valid(existing.text) && world.valid(existing.caret)) return existing;
- const pad = px(ti.padding);
// Spawn order is the tree-DFS render order: highlight (behind) < text < caret.
- const sel = spawnUIEntity({
- world, parent: entity,
- node: { position: UIPositionType.Absolute, width: px(0), height: px(ti.fontSize), insetLeft: pad, insetTop: px(0) },
- visual: { visualType: UIVisualType.SolidColor, color: { ...SELECTION_COLOR }, enabled: false },
- });
- const text = spawnUIEntity({
- world, parent: entity,
- // Left-anchored by insetLeft (scrolled by the render loop) with an
- // explicit width — NOT insetRight — so a single-line value can slide
- // under the Scissor mask instead of being pinned to the box.
- node: { position: UIPositionType.Absolute, insetLeft: pad, insetTop: px(0), insetBottom: px(0), width: px(0) },
- text: {
+ let ch: { sel: Entity; text: Entity; caret: Entity };
+ if (box.world) {
+ const layer = layerOf(entity);
+ const sel = spawnWorldPart(entity);
+ world.insert(sel, Sprite, { layer, color: { ...SELECTION_COLOR }, enabled: false } as Partial<SpriteData> as SpriteData);
+ const text = spawnWorldPart(entity);
+ world.insert(text, Text, buildText({
content: '', font: ti.font, fontFamily: ti.fontFamily, fontSize: ti.fontSize,
align: TextAlign.Left, verticalAlign: TextVerticalAlign.Middle, wordWrap: ti.multiline,
- renderMode: ti.renderMode,
- },
- });
- const caret = spawnUIEntity({
- world, parent: entity,
- node: { position: UIPositionType.Absolute, width: px(2), height: px(ti.fontSize), insetLeft: px(ti.padding), insetTop: px(0) },
- visual: { visualType: UIVisualType.SolidColor, color: ti.color, enabled: false },
- });
- const ch = { sel, text, caret };
+ renderMode: ti.renderMode, layer,
+ }));
+ const caret = spawnWorldPart(entity);
+ world.insert(caret, Sprite, { layer, color: { ...ti.color }, enabled: false } as Partial<SpriteData> as SpriteData);
+ ch = { sel, text, caret };
+ } else {
+ const pad = px(ti.padding);
+ const sel = spawnUIEntity({
+ world, parent: entity,
+ node: { position: UIPositionType.Absolute, width: px(0), height: px(ti.fontSize), insetLeft: pad, insetTop: px(0) },
+ visual: { visualType: UIVisualType.SolidColor, color: { ...SELECTION_COLOR }, enabled: false },
+ });
+ const text = spawnUIEntity({
+ world, parent: entity,
+ // Left-anchored by insetLeft (scrolled by the render loop) with an
+ // explicit width — NOT insetRight — so a single-line value can slide
+ // under the Scissor mask instead of being pinned to the box.
+ node: { position: UIPositionType.Absolute, insetLeft: pad, insetTop: px(0), insetBottom: px(0), width: px(0) },
+ text: {
+ content: '', font: ti.font, fontFamily: ti.fontFamily, fontSize: ti.fontSize,
+ align: TextAlign.Left, verticalAlign: TextVerticalAlign.Middle, wordWrap: ti.multiline,
+ renderMode: ti.renderMode,
+ },
+ });
+ const caret = spawnUIEntity({
+ world, parent: entity,
+ node: { position: UIPositionType.Absolute, width: px(2), height: px(ti.fontSize), insetLeft: px(ti.padding), insetTop: px(0) },
+ visual: { visualType: UIVisualType.SolidColor, color: ti.color, enabled: false },
+ });
+ ch = { sel, text, caret };
+ }
childrenOf.set(entity, ch);
return ch;
}
- function syncSelChild(selEntity: Entity, ti: TextInputData, show: boolean, x: number, top: number, width: number): void {
- const w = Math.max(0, width);
- const node = world.get(selEntity, UINode) as UINodeData;
- if (node.insetLeft.value !== x || node.insetTop.value !== top || node.width.value !== w || node.height.value !== ti.fontSize) {
- node.insetLeft = px(x);
- node.insetTop = px(top);
- node.width = px(w);
- node.height = px(ti.fontSize);
- world.insert(selEntity, UINode, node);
+ /**
+ * Put a part of the field at (@p left, @p top) from the box's top-left, @p width by @p height. A UI field's parts are absolutely
+ * positioned UI nodes; a world field's are top-left-anchored rectangles placed by their transform from the field's own origin.
+ */
+ function placePart(part: Entity, box: FieldBox, left: number, top: number, width: number, height: number | null): void {
+ if (!box.world) {
+ const node = world.get(part, UINode) as UINodeData;
+ // `height` null: the node is sized by its insets (the text spans top to bottom) and keeps what it has.
+ if (node.insetLeft.value !== left || node.insetTop.value !== top || node.width.value !== width || (height !== null && node.height.value !== height)) {
+ node.insetLeft = px(left);
+ node.insetTop = px(top);
+ node.width = px(width);
+ if (height !== null) node.height = px(height);
+ world.insert(part, UINode, node);
+ }
+ return;
}
- const v = world.get(selEntity, UIVisual) as UIVisualData;
- const on = show && w > 0;
- if (v.enabled !== on) {
- v.enabled = on;
- world.insert(selEntity, UIVisual, v);
+ const worldHeight = height ?? box.h;
+ const x = -box.px * box.w + left;
+ const y = (1 - box.py) * box.h - top;
+ const tr = world.get(part, Transform) as TransformData;
+ if (tr.position.x !== x || tr.position.y !== y) {
+ tr.position = { x, y, z: 0 };
+ world.insert(part, Transform, tr);
}
+ const rect = world.get(part, ContentRect);
+ if (rect.size.x !== width || rect.size.y !== worldHeight) world.insert(part, ContentRect, { ...rect, size: { x: width, y: worldHeight } });
}
- function syncTextChild(textEntity: Entity, ti: TextInputData, disp: TextFieldDisplay, innerW: number, scrollX: number, ao: number): void {
+ /** Show or hide a solid-colour part (the highlight, the caret) and give it its colour. */
+ function paintPart(part: Entity, box: FieldBox, on: boolean, color: { r: number; g: number; b: number; a: number }, withColor: boolean): void {
+ if (!box.world) {
+ const v = world.get(part, UIVisual) as UIVisualData;
+ if (v.enabled !== on || (withColor && (v.color.r !== color.r || v.color.g !== color.g || v.color.b !== color.b))) {
+ v.enabled = on;
+ if (withColor) v.color = { ...color };
+ world.insert(part, UIVisual, v);
+ }
+ return;
+ }
+ const sp = world.get(part, Sprite) as SpriteData;
+ if (sp.enabled !== on || (withColor && (sp.color.r !== color.r || sp.color.g !== color.g || sp.color.b !== color.b))) {
+ world.insert(part, Sprite, { ...sp, enabled: on, ...(withColor ? { color: { ...color } } : {}) });
+ }
+ }
+
+ function syncSelChild(selEntity: Entity, ti: TextInputData, box: FieldBox, show: boolean, x: number, top: number, width: number): void {
+ const w = Math.max(0, width);
+ placePart(selEntity, box, x, top, w, ti.fontSize);
+ paintPart(selEntity, box, show && w > 0, SELECTION_COLOR, false);
+ }
+
+ function syncTextChild(textEntity: Entity, ti: TextInputData, box: FieldBox, disp: TextFieldDisplay, innerW: number, scrollX: number, ao: number): void {
const t = world.get(textEntity, Text) as TextData;
const show = disp.text;
const col = disp.isPlaceholder ? ti.placeholderColor : ti.color;
@@ -674,30 +774,13 @@ export class TextInputPlugin implements Plugin {
}
// Slide the text box by the alignment offset and the scroll; width = the
// inner box (a single line overflows it rightward and the Scissor mask
- // clips).
- const node = world.get(textEntity, UINode) as UINodeData;
- const left = ti.padding + ao - scrollX;
- if (node.insetLeft.value !== left || node.width.value !== innerW) {
- node.insetLeft = px(left);
- node.width = px(innerW);
- world.insert(textEntity, UINode, node);
- }
+ // clips). A UI node takes its height from its insets, a world rectangle needs it said.
+ placePart(textEntity, box, ti.padding + ao - scrollX, 0, innerW, null);
}
- function syncCaretChild(caretEntity: Entity, ti: TextInputData, caretX: number, caretTop: number, show: boolean): void {
- const node = world.get(caretEntity, UINode) as UINodeData;
- if (node.insetLeft.value !== caretX || node.insetTop.value !== caretTop || node.height.value !== ti.fontSize) {
- node.insetLeft = px(caretX);
- node.insetTop = px(caretTop);
- node.height = px(ti.fontSize);
- world.insert(caretEntity, UINode, node);
- }
- const v = world.get(caretEntity, UIVisual) as UIVisualData;
- if (v.enabled !== show || v.color.r !== ti.color.r || v.color.g !== ti.color.g || v.color.b !== ti.color.b) {
- v.enabled = show;
- v.color = { ...ti.color };
- world.insert(caretEntity, UIVisual, v);
- }
+ function syncCaretChild(caretEntity: Entity, ti: TextInputData, box: FieldBox, caretX: number, caretTop: number, show: boolean): void {
+ placePart(caretEntity, box, caretX, caretTop, 2, ti.fontSize);
+ paintPart(caretEntity, box, show, ti.color, true);
}
}
}
diff --git a/sdk/src/ui/text/text-input.ts b/sdk/src/ui/text/text-input.ts
index 63834c657..4aeb52c8a 100644
--- a/sdk/src/ui/text/text-input.ts
+++ b/sdk/src/ui/text/text-input.ts
@@ -13,12 +13,21 @@ export const TextInputFilter = {
None: 0,
/** Only 0-9, for a count or a price. */
Digits: 1,
+ /** 0-9, a point and a minus sign, for a number that may have a fraction or be negative. */
+ Decimal: 2,
+ /** 0-9 and the characters of a phone number: + * # and -. */
+ Phone: 3,
} as const;
export type TextInputFilter = typeof TextInputFilter[keyof typeof TextInputFilter];
/** `value` with the characters the filter does not allow taken out. */
export function applyTextInputFilter(value: string, filter: TextInputFilter | undefined): string {
- return filter === TextInputFilter.Digits ? value.replace(/[^0-9]/g, '') : value;
+ switch (filter) {
+ case TextInputFilter.Digits: return value.replace(/[^0-9]/g, '');
+ case TextInputFilter.Decimal: return value.replace(/[^0-9.\-]/g, '');
+ case TextInputFilter.Phone: return value.replace(/[^0-9+*#\-]/g, '');
+ default: return value;
+ }
}
export interface TextInputData {
diff --git a/sdk/tests/cocos/editbox-wasm.test.ts b/sdk/tests/cocos/editbox-wasm.test.ts
index 7ff16fed7..fa45cb1a8 100644
--- a/sdk/tests/cocos/editbox-wasm.test.ts
+++ b/sdk/tests/cocos/editbox-wasm.test.ts
@@ -1,12 +1,15 @@
// SPDX-License-Identifier: Apache-2.0
// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team
/**
- * @file EditBox: a click takes the platform's text editor, what is typed lands in the labels, and the field's rules (mode, length, hint) hold.
+ * @file EditBox is a view on the engine's TextInput: a press takes the platform's text editor, what is typed lands in the field, and the
+ * field's rules (mode, length, password, hint) hold. The field draws its own text and hint, so what is read back is the field's.
*/
import { afterEach, beforeAll, beforeEach, describe, expect, it, vi } from 'vitest';
import type { ESEngineModule } from '../../src/wasm';
-import { Transform, ensureBuiltinComponentsRegistered } from '../../src/ecs/component';
-import { EditBox, Label, Node, UITransform } from '../../src/cocos';
+import { Children, Transform, ensureBuiltinComponentsRegistered } from '../../src/ecs/component';
+import { Text } from '../../src/ui/core/text';
+import { TextInput } from '../../src/ui/text/text-input';
+import { Color, EditBox, Node, UITransform } from '../../src/cocos';
import type { PlatformTextEditor, TextEditorEvent, TextEditorState } from '../../src/platform/types';
import { HAS_WASM, loadWasmModule } from '../helpers/loadWasm';
import { pointerApp, type PointerApp } from './helpers/pointerApp';
@@ -28,6 +31,14 @@ class FakeEditor implements PlatformTextEditor {
emit(e: TextEditorEvent): void { for (const h of [...this.handlers]) h(e); }
}
+// the field measures its text through a glyph atlas; a fixed advance stands in for the platform's rasterizer, which a test has none of
+vi.mock('../../src/ui/text/text-renderer', () => ({
+ SdfTextRenderer: class {
+ atlas = { renderSize: 64, pixelSizeFor: () => 64, getGlyph: () => ({ advance: 16 }) };
+ dispose(): void {}
+ },
+}));
+
let editor: FakeEditor | null;
vi.mock('../../src/platform', async (importOriginal) => ({
...(await importOriginal<typeof import('../../src/platform')>()),
@@ -51,42 +62,53 @@ describe.skipIf(!HAS_WASM)('EditBox', () => {
return n;
}
- async function field(configure: (e: EditBox) => void = () => {}): Promise<{ node: Node; edit: EditBox; text: Label; hint: Label }> {
- P = pointerApp(module);
+ async function field(configure: (e: EditBox) => void = () => {}): Promise<{ node: Node; edit: EditBox }> {
+ P = pointerApp(module, { x: 0, y: 0 }, { fields: true });
const node = box('input', 200, 200, 160, 40);
- const text = box('text', 0, 0, 150, 30, node).addComponent(Label)!;
- const hint = box('hint', 0, 0, 150, 30, node).addComponent(Label)!;
- hint.string = 'type here';
const edit = node.addComponent<EditBox>('EditBox')!;
- edit.textLabel = text;
- edit.placeholderLabel = hint;
+ edit.placeholder = 'type here';
configure(edit);
- await P.frame(1);
- return { node, edit, text, hint };
+ await P.frame(2);
+ return { node, edit };
+ }
+
+ /** What the field is showing now: its text part, which holds the hint while the value is empty. */
+ function shown(node: Node): string {
+ const parts = P!.app.world.get(node._entity, Children).entities;
+ return P!.app.world.get(parts[1]!, Text).content;
}
- it('takes the text editor on a click, and tells the field\'s listeners', async () => {
+ it('is the engine field on its node: added if there is none, the same view each time', async () => {
+ const { node, edit } = await field();
+ expect(P!.app.world.has(node._entity, TextInput)).toBe(true);
+ expect(node.getComponent(EditBox)).toBe(edit);
+ expect(node.getComponent('cc.EditBox')).toBe(edit);
+ });
+
+ it("takes the text editor on a press, and tells the field's listeners", async () => {
const { node, edit } = await field();
const seen: string[] = [];
node.on(EditBox.EventType.EDITING_DID_BEGAN, () => seen.push('began'));
await P!.tap(200, 200);
+ await P!.frame(1);
expect(editor!.focused).toBe(true);
expect(edit.isFocused()).toBe(true);
expect(seen).toEqual(['began']);
});
- it('shows what is typed in its label and hides the hint, and brings the hint back when it is emptied', async () => {
- const { node, edit, text, hint } = await field();
+ it('shows the hint while empty, and what is typed after, with the field text-changed event', async () => {
+ const { node, edit } = await field();
const changed: string[] = [];
node.on(EditBox.EventType.TEXT_CHANGED, (e: EditBox) => changed.push(e.string));
- expect(hint.node.active).toBe(true);
+ expect(shown(node)).toBe('type here');
await P!.tap(200, 200);
editor!.type('hello');
+ await P!.frame(2);
expect(edit.string).toBe('hello');
- expect(text.string).toBe('hello');
- expect(hint.node.active).toBe(false);
+ expect(shown(node)).toBe('hello');
editor!.type('');
- expect(hint.node.active).toBe(true);
+ await P!.frame(2);
+ expect(shown(node)).toBe('type here');
expect(changed).toEqual(['hello', '']);
});
@@ -94,16 +116,18 @@ describe.skipIf(!HAS_WASM)('EditBox', () => {
const { edit } = await field((e) => { e.maxLength = 4; e.inputMode = EditBox.InputMode.NUMERIC; });
await P!.tap(200, 200);
editor!.type('12ab3456');
+ await P!.frame(1);
expect(edit.string).toBe('1234');
expect(editor!.state.value).toBe('1234');
});
it('shows bullets for a password and keeps the real text', async () => {
- const { edit, text } = await field((e) => { e.inputFlag = EditBox.InputFlag.PASSWORD; });
+ const { node, edit } = await field((e) => { e.inputFlag = EditBox.InputFlag.PASSWORD; });
await P!.tap(200, 200);
editor!.type('secret');
+ await P!.frame(2);
expect(edit.string).toBe('secret');
- expect(text.string).toBe('●●●●●●');
+ expect(shown(node)).toBe('●●●●●●');
expect((editor!.options as { password: boolean }).password).toBe(true);
});
@@ -113,33 +137,41 @@ describe.skipIf(!HAS_WASM)('EditBox', () => {
node.on(EditBox.EventType.EDITING_RETURN, () => seen.push('return'));
node.on(EditBox.EventType.EDITING_DID_ENDED, () => seen.push('ended'));
await P!.tap(200, 200);
+ await P!.frame(1);
editor!.emit({ kind: 'submit' });
+ await P!.frame(2);
expect(seen).toEqual(['return', 'ended']);
expect(edit.isFocused()).toBe(false);
expect(editor!.focused).toBe(false);
- expect(editor!.disposed).toBe(true);
});
- it('can be set from a script without an event, and shows the hint when empty', async () => {
- const { edit, text, hint } = await field();
+ it('can be set from a script, and shows it', async () => {
+ const { node, edit } = await field();
edit.string = 'preset';
- expect(text.string).toBe('preset');
- expect(hint.node.active).toBe(false);
+ await P!.frame(2);
+ expect(shown(node)).toBe('preset');
+ expect(P!.app.world.get(node._entity, TextInput).value).toBe('preset');
});
- it('switches its text label on while it holds text, even when the label was authored off', async () => {
- const { edit, text } = await field();
- text.node.active = false;
- edit.string = 'preset';
- expect(text.node.active).toBe(true);
- edit.string = '';
- expect(text.node.active).toBe(false);
+ it("hands a script the field's style as its text and hint labels", async () => {
+ const { node, edit } = await field();
+ edit.textLabel.color = new Color(255, 0, 0, 255);
+ edit.placeholderLabel.color = new Color(0, 255, 0, 255);
+ edit.textLabel.fontSize = 28;
+ const data = P!.app.world.get(node._entity, TextInput);
+ expect(data.color).toMatchObject({ r: 1, g: 0, b: 0 });
+ expect(data.placeholderColor).toMatchObject({ r: 0, g: 1, b: 0 });
+ expect(data.fontSize).toBe(28);
+ expect(edit.placeholderLabel.string).toBe('type here');
});
it('does nothing on a host with no text editor', async () => {
editor = null;
- const { edit } = await field();
+ const { node, edit } = await field();
+ const seen: string[] = [];
+ node.on(EditBox.EventType.EDITING_DID_BEGAN, () => seen.push('began'));
await P!.tap(200, 200);
- expect(edit.isFocused()).toBe(false);
+ expect(seen).toEqual([]);
+ expect(edit.string).toBe('');
});
});
diff --git a/sdk/tests/cocos/helpers/pointerApp.ts b/sdk/tests/cocos/helpers/pointerApp.ts
index ecfe91db9..57cbac144 100644
--- a/sdk/tests/cocos/helpers/pointerApp.ts
+++ b/sdk/tests/cocos/helpers/pointerApp.ts
@@ -14,6 +14,8 @@ import { Input, InputState } from '../../../src/input/input';
import { UICameraInfo } from '../../../src/ui/core/ui-camera-info';
import { UILayoutGeneration } from '../../../src/ui/layout/ui-layout-generation';
import { uiInteractionPlugin } from '../../../src/ui/input/interaction';
+import { focusPlugin } from '../../../src/ui/input/focus';
+import { textInputPlugin } from '../../../src/ui/text/text-input-plugin';
import { ensureBuiltinComponentsRegistered } from '../../../src/ecs/component';
import { resetClassRegistry } from '../../../src/cocos/registry';
import { declareBuiltinScripts } from '../../../src/cocos/builtinScripts';
@@ -36,7 +38,7 @@ export interface PointerApp {
}
/** @p origin: how far the world's origin sits from the surface's bottom-left corner, in pixels: a surface point is the world point plus it. */
-export function pointerApp(module: ESEngineModule, origin: { x: number; y: number } = { x: 0, y: 0 }): PointerApp {
+export function pointerApp(module: ESEngineModule, origin: { x: number; y: number } = { x: 0, y: 0 }, options: { fields?: boolean } = {}): PointerApp {
setDefaultContext(new AppContext());
ensureBuiltinComponentsRegistered();
resetClassRegistry();
@@ -53,6 +55,11 @@ export function pointerApp(module: ESEngineModule, origin: { x: number; y: numbe
});
app.insertResource(UILayoutGeneration, { generation: 0 });
uiInteractionPlugin.build(app);
+ // text fields: focus follows a press, and the field's plugin takes the text surface
+ if (options.fields) {
+ focusPlugin.build(app);
+ textInputPlugin.build(app);
+ }
flushPendingRegistrations(app);
setCurrentWorld(app.world);
@@ -90,6 +97,7 @@ export function pointerApp(module: ESEngineModule, origin: { x: number; y: numbe
},
dispose() {
uiInteractionPlugin.cleanup(app);
+ textInputPlugin.cleanup(app);
setCurrentWorld(null);
app.world.disconnectCpp();
registry.delete();
diff --git a/sdk/tests/text-input-plugin-lifecycle.test.ts b/sdk/tests/text-input-plugin-lifecycle.test.ts
index 3550cde74..ddf134c05 100644
--- a/sdk/tests/text-input-plugin-lifecycle.test.ts
+++ b/sdk/tests/text-input-plugin-lifecycle.test.ts
@@ -343,3 +343,39 @@ it('a field with no filter takes every character, and a digits field still honou
for (const listener of second.listeners) listener({ kind: 'change' });
expect(app.world.get(priced, TextInput).value).toBe('123');
});
+
+it('puts a field on a world rectangle together from world parts: text, selection and caret placed from the box top-left', async () => {
+ const { ContentRect } = await import('../src/ui/core/content-rect');
+ const { Sprite } = await import('../src/ecs/component');
+ const { Parent, Children } = await import('../src/ecs/component');
+ const app = build(new TextInputPlugin());
+ const field = app.world.spawn();
+ app.world.insert(field, Transform, { position: { x: 100, y: 50, z: 0 }, rotation: { w: 1, x: 0, y: 0, z: 0 }, scale: { x: 1, y: 1, z: 1 },
+ worldPosition: { x: 100, y: 50, z: 0 }, worldRotation: { w: 1, x: 0, y: 0, z: 0 }, worldScale: { x: 1, y: 1, z: 1 } });
+ // 200 by 60, the transform in the middle
+ app.world.insert(field, ContentRect, { size: { x: 200, y: 60 }, pivot: { x: 0.5, y: 0.5 } });
+ app.world.insert(field, TextInput, { value: 'typed', padding: 8, fontSize: 20 });
+ app.getResource(FocusManager).focus(field);
+ await app.tick(1 / 60);
+ await app.tick(1 / 60);
+
+ // a UI field would have grown UI nodes; this one grew world parts, three of them under it, none a UINode
+ const parts = app.world.get(field, Children).entities;
+ expect(parts).toHaveLength(3);
+ for (const part of parts) {
+ expect(app.world.has(part, UINode)).toBe(false);
+ expect(app.world.has(part, ContentRect)).toBe(true);
+ expect(app.world.get(part, Parent).entity).toBe(field);
+ }
+ const [selection, text, caret] = parts as [number, number, number];
+ expect(app.world.get(text, Text).content).toBe('typed');
+ // the text starts one padding in from the left edge (-100), and sits at the top (+30), from the field's own origin
+ expect(app.world.get(text, Transform).position.x).toBe(-100 + 8);
+ expect(app.world.get(text, Transform).position.y).toBe(30);
+ expect(app.world.get(text, ContentRect).size.x).toBe(200 - 16);
+ // the caret is a solid bar after the five typed characters (the measuring stub's glyph is 16 at 64, so 5 at this size), 2 wide and a line tall
+ expect(app.world.get(caret, ContentRect).size).toEqual({ x: 2, y: 20 });
+ expect(app.world.get(caret, Transform).position.x).toBeCloseTo(-100 + 8 + 5 * 5, 3);
+ expect(app.world.get(caret, Sprite).enabled).toBe(true);
+ expect(app.world.get(selection, Sprite).enabled).toBe(false);
+});