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): multiline caret, selection and click across \n-broken lines
yhh503e0ae51577
diff --git a/docs/astro/src/content/docs/guides/ui-components.mdx b/docs/astro/src/content/docs/guides/ui-components.mdxindex 028b911be..6abf1f65a 100644--- a/docs/astro/src/content/docs/guides/ui-components.mdx+++ b/docs/astro/src/content/docs/guides/ui-components.mdx@@ -352,6 +352,11 @@ Chinese/Japanese/Korean composition renders **live in the field** (the preeditstring shows at the caret as you type) and only fires `change` once thecomposition commits — the same behavior as a native input.+A **`multiline`** field (Enter inserts a newline) stacks its lines from the top;+the caret position, click-to-place and within-line selection track the+`\n`-broken lines (soft word-wrap is not modeled — lines break on explicit+newlines).+<Aside type="note">Text input runs in **play mode only** and needs a browser DOM (the hiddennative textarea) — it's inert in the editor's edit view.diff --git a/examples/rich-text/assets/scenes/main.esscene b/examples/rich-text/assets/scenes/main.essceneindex f8ce5f9ed..6942d7e71 100644--- a/examples/rich-text/assets/scenes/main.esscene+++ b/examples/rich-text/assets/scenes/main.esscene@@ -29,7 +29,7 @@"id": 2,"name": "Panel","parent": 1,- "children": [3, 4, 5, 6, 7, 8],+ "children": [3, 4, 5, 6, 9, 10, 7, 8],"components": [{ "type": "Transform", "data": {} },{@@ -48,7 +48,7 @@"direction": 1,"justifyContent": 0,"alignItems": 3,- "gap": { "x": 0, "y": 12 },+ "gap": { "x": 0, "y": 8 },"padding": { "left": 20, "top": 20, "right": 20, "bottom": 20 }}},@@ -66,17 +66,10 @@"children": [],"components": [{ "type": "Transform", "data": {} },- { "type": "UINode", "data": { "height": { "value": 30, "unit": 0 } } },+ { "type": "UINode", "data": { "height": { "value": 28, "unit": 0 } } },{"type": "Text",- "data": {- "content": "Rich Text + Input Playground",- "fontSize": 22,- "bold": true,- "color": { "r": 1, "g": 1, "b": 1, "a": 1 },- "align": 0,- "verticalAlign": 1- }+ "data": { "content": "Rich Text + Input Playground", "fontSize": 22, "bold": true, "color": { "r": 1, "g": 1, "b": 1, "a": 1 }, "align": 0, "verticalAlign": 1 }}],"visible": true@@ -88,11 +81,8 @@"children": [],"components": [{ "type": "Transform", "data": {} },- { "type": "UINode", "data": { "height": { "value": 180, "unit": 0 } } },- {- "type": "UIVisual",- "data": { "visualType": 1, "color": { "r": 0.08, "g": 0.09, "b": 0.12, "a": 1 }, "enabled": true }- }+ { "type": "UINode", "data": { "height": { "value": 148, "unit": 0 } } },+ { "type": "UIVisual", "data": { "visualType": 1, "color": { "r": 0.08, "g": 0.09, "b": 0.12, "a": 1 }, "enabled": true } }],"visible": true},@@ -103,16 +93,10 @@"children": [],"components": [{ "type": "Transform", "data": {} },- { "type": "UINode", "data": { "height": { "value": 22, "unit": 0 } } },+ { "type": "UINode", "data": { "height": { "value": 20, "unit": 0 } } },{"type": "Text",- "data": {- "content": "Edit the markup below — the preview updates live. Type 中文 to test IME.",- "fontSize": 14,- "color": { "r": 0.65, "g": 0.66, "b": 0.7, "a": 1 },- "align": 0,- "verticalAlign": 1- }+ "data": { "content": "Edit the markup below — the preview updates live. Type 中文 to test IME.", "fontSize": 14, "color": { "r": 0.65, "g": 0.66, "b": 0.7, "a": 1 }, "align": 0, "verticalAlign": 1 }}],"visible": true@@ -124,14 +108,37 @@"children": [],"components": [{ "type": "Transform", "data": {} },- { "type": "UINode", "data": { "height": { "value": 38, "unit": 0 } } },+ { "type": "UINode", "data": { "height": { "value": 36, "unit": 0 } } },+ { "type": "FlexContainer", "data": { "direction": 0, "justifyContent": 0, "alignItems": 1, "gap": { "x": 10, "y": 0 } } }+ ],+ "visible": true+ },+ {+ "id": 9,+ "name": "MultilineLabel",+ "parent": 2,+ "children": [],+ "components": [+ { "type": "Transform", "data": {} },+ { "type": "UINode", "data": { "height": { "value": 20, "unit": 0 } } },{- "type": "FlexContainer",- "data": { "direction": 0, "justifyContent": 0, "alignItems": 1, "gap": { "x": 10, "y": 0 } }+ "type": "Text",+ "data": { "content": "Multiline field — Enter inserts a newline; click or arrow across lines:", "fontSize": 14, "color": { "r": 0.65, "g": 0.66, "b": 0.7, "a": 1 }, "align": 0, "verticalAlign": 1 }}],"visible": true},+ {+ "id": 10,+ "name": "MultilineSlot",+ "parent": 2,+ "children": [],+ "components": [+ { "type": "Transform", "data": {} },+ { "type": "UINode", "data": { "height": { "value": 76, "unit": 0 } } }+ ],+ "visible": true+ },{"id": 7,"name": "ShowcaseTitle",@@ -139,17 +146,10 @@"children": [],"components": [{ "type": "Transform", "data": {} },- { "type": "UINode", "data": { "height": { "value": 26, "unit": 0 } } },+ { "type": "UINode", "data": { "height": { "value": 24, "unit": 0 } } },{"type": "Text",- "data": {- "content": "Supported tags",- "fontSize": 16,- "bold": true,- "color": { "r": 0.85, "g": 0.86, "b": 0.9, "a": 1 },- "align": 0,- "verticalAlign": 1- }+ "data": { "content": "Supported tags", "fontSize": 16, "bold": true, "color": { "r": 0.85, "g": 0.86, "b": 0.9, "a": 1 }, "align": 0, "verticalAlign": 1 }}],"visible": true@@ -161,11 +161,8 @@"children": [],"components": [{ "type": "Transform", "data": {} },- { "type": "UINode", "data": { "height": { "value": 170, "unit": 0 } } },- {- "type": "FlexContainer",- "data": { "direction": 1, "justifyContent": 0, "alignItems": 3, "gap": { "x": 0, "y": 6 } }- }+ { "type": "UINode", "data": { "height": { "value": 104, "unit": 0 } } },+ { "type": "FlexContainer", "data": { "direction": 1, "justifyContent": 0, "alignItems": 3, "gap": { "x": 0, "y": 6 } } }],"visible": true}diff --git a/examples/rich-text/src/systems/build.ts b/examples/rich-text/src/systems/build.tsindex 8b075fa21..8dc3b1e0f 100644--- a/examples/rich-text/src/systems/build.ts+++ b/examples/rich-text/src/systems/build.ts@@ -23,7 +23,8 @@ export const buildSystem = defineSystem(const previewSlot = world.findEntityByName('PreviewSlot');const composerRow = world.findEntityByName('ComposerRow');const showcaseSlot = world.findEntityByName('ShowcaseSlot');- if (previewSlot === null || composerRow === null || showcaseSlot === null) return;+ const multilineSlot = world.findEntityByName('MultilineSlot');+ if (previewSlot === null || composerRow === null || showcaseSlot === null || multilineSlot === null) return;state.built = true;const c = themeColors();@@ -70,6 +71,16 @@ export const buildSystem = defineSystem(},});+ // A multiline field: Enter inserts a newline, and the caret / click /+ // selection track across the \n-broken lines.+ createTextInput({+ world, events, parent: multilineSlot,+ node: { position: UIPositionType.Absolute, insetLeft: px(0), insetRight: px(0), insetTop: px(0), insetBottom: px(0) },+ value: 'first line\nsecond line — click here\nthird line',+ multiline: true,+ fontSize: 15,+ });+// Static legend: each supported tag rendered next to nothing but itself,// so the panel doubles as a quick reference.for (const line of SAMPLES) {diff --git a/sdk/src/ui/text/text-input-plugin.ts b/sdk/src/ui/text/text-input-plugin.tsindex d58e3a6e3..6feec7cd9 100644--- a/sdk/src/ui/text/text-input-plugin.ts+++ b/sdk/src/ui/text/text-input-plugin.ts@@ -22,8 +22,11 @@ import { spawnUIEntity } from '../core/compose';import { px } from '../core/dimension';import { SdfTextRenderer } from './text-renderer';import { measureWidth } from './layout';-import { textFieldDisplay, maskedPrefix, fieldSelection, nearestCaretIndex, type TextFieldDisplay } from './text-input-view';-import { CURSOR_BLINK_INTERVAL } from '../util/constants';+import {+ textFieldDisplay, maskedPrefix, fieldSelection, nearestCaretIndex,+ splitLines, caretLineCol, lineSelections, type TextFieldDisplay,+} from './text-input-view';+import { CURSOR_BLINK_INTERVAL, TEXT_INPUT_LINE_HEIGHT_RATIO } from '../util/constants';import { SystemLabel, PluginName } from '../../systemLabels';import { log } from '../../logger';@@ -203,30 +206,45 @@ export class TextInputPlugin implements Plugin {resetCursorBlink();}- // Map the current pointer to a caret index inside `entity` (single-line):- // pointer world-x → the field's local text space (undo the box center,- // padding and horizontal scroll) → nearest character boundary. null when- // it can't be resolved (no camera / multiline / zero-width).+ // Map the current pointer to a caret index inside `entity`: pointer+ // world-x → the field's local text space (undo the box center, padding and+ // horizontal scroll) → nearest character boundary. Multiline also maps the+ // pointer world-y to a \n-broken line first. null when it can't be resolved+ // (no camera / no box).function caretIndexFromPointer(entity: Entity): number | null {const cam = app.getResource(UICameraInfo) as UICameraData | undefined;if (!cam || !cam.valid) return null;if (!world.has(entity, Transform) || !world.has(entity, UINode)) return null;const ti = world.get(entity, TextInput) as TextInputData;- if (ti.multiline) return null;const width = getUINodeWidth(entity);if (width <= 0) return null;- // The layout centers the box on its Transform (pivot 0.5), so the left- // edge is half a width to the left; text starts `padding` in, scrolled.+ // 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;+ const val = textarea.value; // focused ⇒ the textarea is the value source+ const atlas = ensureMeasure().atlas;+ const mw = (s: string): number => measureWidth(s, atlas, ti.fontFamily, ti.fontSize, 0);++ 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 - cam.worldMouseY; // 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];+ const textX = cam.worldMouseX - fieldLeft - ti.padding;+ const prefixes: number[] = [];+ for (let i = 0; i <= line.text.length; i++) prefixes.push(mw(line.text.slice(0, i)));+ return line.start + nearestCaretIndex(prefixes, textX);+ }+const scrollX = scrollXOf.get(entity) ?? 0;const textX = cam.worldMouseX - fieldLeft - ti.padding + scrollX;- // Focused ⇒ the textarea is the source of truth for the value.- const val = textarea.value;- const atlas = ensureMeasure().atlas;const prefixes: number[] = [];for (let i = 0; i <= val.length; i++) {- prefixes.push(measureWidth(maskedPrefix(val, i, ti.password, PASSWORD_CHAR), atlas, ti.fontFamily, ti.fontSize, 0));+ prefixes.push(mw(maskedPrefix(val, i, ti.password, PASSWORD_CHAR)));}return nearestCaretIndex(prefixes, textX);}@@ -371,28 +389,52 @@ export class TextInputPlugin implements Plugin {const disp = textFieldDisplay(val, ti.password, ti.placeholder, PASSWORD_CHAR);const atlas = ensureMeasure().atlas;- const measure = (i: number): number =>- measureWidth(maskedPrefix(val, i, ti.password, PASSWORD_CHAR), atlas, ti.fontFamily, ti.fontSize, 0);- const caretRaw = measure(sel.caret);- // Single-line fields scroll horizontally to keep the caret in view;- // multiline wraps within the box and clips (no h-scroll).+ const mw = (s: string): number => measureWidth(s, atlas, ti.fontFamily, ti.fontSize, 0);const innerW = Math.max(0, w - 2 * ti.padding);- const scrollX = ti.multiline ? 0 : Math.max(0, caretRaw - innerW);+ const vCenter = Math.max(0, (h - ti.fontSize) / 2);++ // caret + a single highlight rect, placed the same way for both+ // field kinds: single-line scrolls horizontally and centers+ // vertically; multiline stacks lines from the top (no h-scroll)+ // and positions the caret on its \n-broken line. A selection that+ // spans multiple visual lines shows the caret only for now.+ let caretX: number, caretTop: number, scrollX: number;+ let sshow = false, sx = 0, stop = 0, sw = 0;+ if (ti.multiline) {+ const lineH = ti.fontSize * TEXT_INPUT_LINE_HEIGHT_RATIO;+ scrollX = 0;+ const lc = caretLineCol(val, sel.caret);+ caretX = ti.padding + mw(val.slice(lc.lineStart, sel.caret));+ caretTop = lc.line * lineH;+ // Highlight a selection that stays on one visual line; a+ // multi-line range shows the caret only for now.+ const rows = sel.hasRange ? lineSelections(val, sel.lo, sel.hi) : [];+ if (rows.length === 1) {+ const line = splitLines(val)[rows[0].line];+ sx = ti.padding + mw(line.text.slice(0, rows[0].from));+ sw = mw(line.text.slice(rows[0].from, rows[0].to));+ stop = rows[0].line * lineH;+ sshow = true;+ }+ } else {+ const caretRaw = mw(maskedPrefix(val, sel.caret, ti.password, PASSWORD_CHAR));+ scrollX = Math.max(0, caretRaw - innerW);+ caretX = ti.padding + caretRaw - scrollX;+ caretTop = vCenter;+ if (sel.hasRange) {+ const lo = mw(maskedPrefix(val, sel.lo, ti.password, PASSWORD_CHAR));+ sx = ti.padding + lo - scrollX;+ sw = mw(maskedPrefix(val, sel.hi, ti.password, PASSWORD_CHAR)) - lo;+ stop = vCenter;+ sshow = true;+ }+ }scrollXOf.set(entity, scrollX);- // Selection highlight (single-line only): a quad spanning the- // masked range, drawn behind the text. A multiline selection- // spans lines and is left to a later pass.- const showSel = sel.hasRange && !ti.multiline;- const selLo = showSel ? measure(sel.lo) : 0;- const selHi = showSel ? measure(sel.hi) : 0;- syncSelChild(ch.sel, ti, h, showSel, ti.padding + selLo - scrollX, selHi - selLo);-+ syncSelChild(ch.sel, ti, sshow, sx, stop, sw);syncTextChild(ch.text, ti, disp, innerW, scrollX);- // The blinking caret hides while a range is selected (the- // highlight stands in), matching a native field.- syncCaretChild(ch.caret, ti, h, ti.padding + caretRaw - scrollX,- ti.focused && cursorVisible && !sel.hasRange);+ // The blinking caret hides while a highlight is drawn.+ syncCaretChild(ch.caret, ti, caretX, caretTop, ti.focused && cursorVisible && !sshow);}},{ name: 'TextInputRenderSystem' }@@ -457,9 +499,8 @@ export class TextInputPlugin implements Plugin {return ch;}- function syncSelChild(selEntity: Entity, ti: TextInputData, boxH: number, show: boolean, x: number, width: number): void {+ function syncSelChild(selEntity: Entity, ti: TextInputData, show: boolean, x: number, top: number, width: number): void {const w = Math.max(0, width);- const top = Math.max(0, (boxH - ti.fontSize) / 2);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);@@ -480,13 +521,17 @@ export class TextInputPlugin implements Plugin {const t = world.get(textEntity, Text) as TextData;const show = disp.text;const col = disp.isPlaceholder ? ti.placeholderColor : ti.color;+ // Multiline stacks lines from the top so caret line math lines up;+ // single-line centers the one line in the box.+ const vAlign = ti.multiline ? TextVerticalAlign.Top : TextVerticalAlign.Middle;if (t.content !== show || t.fontFamily !== ti.fontFamily || t.fontSize !== ti.fontSize- || t.wordWrap !== ti.multiline || t.renderMode !== ti.renderMode+ || t.wordWrap !== ti.multiline || t.renderMode !== ti.renderMode || t.verticalAlign !== vAlign|| t.color.r !== col.r || t.color.g !== col.g || t.color.b !== col.b || t.color.a !== col.a) {t.content = show;t.fontFamily = ti.fontFamily;t.fontSize = ti.fontSize;t.wordWrap = ti.multiline;+ t.verticalAlign = vAlign;t.renderMode = ti.renderMode;t.color = { ...col };world.insert(textEntity, Text, t);@@ -502,8 +547,7 @@ export class TextInputPlugin implements Plugin {}}- function syncCaretChild(caretEntity: Entity, ti: TextInputData, boxH: number, caretX: number, show: boolean): void {- const caretTop = Math.max(0, (boxH - ti.fontSize) / 2);+ 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);diff --git a/sdk/src/ui/text/text-input-view.ts b/sdk/src/ui/text/text-input-view.tsindex bda86d295..0c8a35a38 100644--- a/sdk/src/ui/text/text-input-view.ts+++ b/sdk/src/ui/text/text-input-view.ts@@ -87,3 +87,58 @@ export function nearestCaretIndex(prefixWidths: readonly number[], x: number): n}return best;}++/** A visual line of a multiline value: its text (no trailing `\n`) and the+ * index in the full value where it starts. */+export interface VisualLine {+ text: string;+ start: number;+}++/** Split a value into its hard-broken (`\n`) visual lines with their start+ * indices. Always at least one line. Pure. (Soft word-wrap is not modeled —+ * the multiline field breaks on explicit newlines.) */+export function splitLines(value: string): VisualLine[] {+ const lines: VisualLine[] = [];+ let start = 0;+ for (;;) {+ const nl = value.indexOf('\n', start);+ if (nl < 0) { lines.push({ text: value.slice(start), start }); break; }+ lines.push({ text: value.slice(start, nl), start });+ start = nl + 1;+ }+ return lines;+}++/** Locate a caret index as a (line, column) in the `\n`-broken value. `column`+ * is the offset within the line's text; `lineStart` is the line's start index+ * so `value.slice(lineStart, caret)` is the prefix whose width places the+ * caret on that line. Pure. */+export function caretLineCol(value: string, caret: number): { line: number; col: number; lineStart: number } {+ const c = Math.max(0, Math.min(caret, value.length));+ const lines = splitLines(value);+ for (let i = 0; i < lines.length; i++) {+ const end = lines[i].start + lines[i].text.length;+ if (c <= end) return { line: i, col: c - lines[i].start, lineStart: lines[i].start };+ }+ const last = lines[lines.length - 1];+ return { line: lines.length - 1, col: last.text.length, lineStart: last.start };+}++/** Per-line column span of a selection `[lo, hi]` over the `\n`-broken value:+ * one entry per visual line that has selected text, giving the column range to+ * highlight on that line. Used to draw one highlight rect per line. Pure. */+export function lineSelections(value: string, lo: number, hi: number): Array<{ line: number; from: number; to: number }> {+ const a = Math.max(0, Math.min(Math.min(lo, hi), value.length));+ const b = Math.max(0, Math.min(Math.max(lo, hi), value.length));+ const out: Array<{ line: number; from: number; to: number }> = [];+ const lines = splitLines(value);+ for (let i = 0; i < lines.length; i++) {+ const ls = lines[i].start;+ const le = ls + lines[i].text.length;+ const from = Math.max(a, ls);+ const to = Math.min(b, le);+ if (to > from) out.push({ line: i, from: from - ls, to: to - ls });+ }+ return out;+}diff --git a/sdk/tests/ui-text-input-view.test.ts b/sdk/tests/ui-text-input-view.test.tsindex 653dffe49..0cbb31264 100644--- a/sdk/tests/ui-text-input-view.test.ts+++ b/sdk/tests/ui-text-input-view.test.ts@@ -10,7 +10,10 @@* the caret / preedit / selection render paths.*/import { describe, it, expect } from 'vitest';-import { textFieldDisplay, maskedPrefix, fieldSelection, nearestCaretIndex } from '../src/ui/text/text-input-view';+import {+ textFieldDisplay, maskedPrefix, fieldSelection, nearestCaretIndex,+ splitLines, caretLineCol, lineSelections,+} from '../src/ui/text/text-input-view';const BULLET = '●';@@ -102,3 +105,65 @@ describe('nearestCaretIndex', () => {expect(nearestCaretIndex([0], 25)).toBe(0);});});++describe('splitLines', () => {+ it('returns one line for a value with no newline', () => {+ expect(splitLines('hello')).toEqual([{ text: 'hello', start: 0 }]);+ });++ it('splits on \\n and records start indices', () => {+ expect(splitLines('ab\ncd\ne')).toEqual([+ { text: 'ab', start: 0 },+ { text: 'cd', start: 3 },+ { text: 'e', start: 6 },+ ]);+ });++ it('keeps empty lines (a trailing newline yields a trailing empty line)', () => {+ expect(splitLines('a\n')).toEqual([+ { text: 'a', start: 0 },+ { text: '', start: 2 },+ ]);+ });+});++describe('caretLineCol', () => {+ it('locates the caret on a single line', () => {+ expect(caretLineCol('hello', 3)).toEqual({ line: 0, col: 3, lineStart: 0 });+ });++ it('locates the caret on the second line', () => {+ expect(caretLineCol('ab\ncd', 4)).toEqual({ line: 1, col: 1, lineStart: 3 });+ });++ it('the end of a line (before its newline) stays on that line', () => {+ expect(caretLineCol('ab\ncd', 2)).toEqual({ line: 0, col: 2, lineStart: 0 });+ });++ it('the start of the next line (after the newline) is column 0 there', () => {+ expect(caretLineCol('ab\ncd', 3)).toEqual({ line: 1, col: 0, lineStart: 3 });+ });+});++describe('lineSelections', () => {+ it('a within-line selection is one span', () => {+ expect(lineSelections('hello', 1, 4)).toEqual([{ line: 0, from: 1, to: 4 }]);+ });++ it('a multi-line selection spans each line it covers', () => {+ // "ab\ncd\nef", select from index 1 ('b') through index 7 ('f').+ expect(lineSelections('ab\ncd\nef', 1, 7)).toEqual([+ { line: 0, from: 1, to: 2 }, // "b"+ { line: 1, from: 0, to: 2 }, // "cd"+ { line: 2, from: 0, to: 1 }, // "e"+ ]);+ });++ it('orders the endpoints and clamps', () => {+ expect(lineSelections('abc', 5, -2)).toEqual([{ line: 0, from: 0, to: 3 }]);+ });++ it('an empty selection yields no spans', () => {+ expect(lineSelections('abc', 2, 2)).toEqual([]);+ });+});