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): public measureText for content-sized layout

yhhf93408aa86fd
diff --git a/examples/chat/src/config.ts b/examples/chat/src/config.ts
index c2bdeec78..8f8d70a79 100644
--- a/examples/chat/src/config.ts
+++ b/examples/chat/src/config.ts
@@ -1,4 +1,5 @@
import type { Color } from 'esengine';
+import { measureText } from 'esengine';
// The message log is a virtualized createListView; its viewport size must be
// known up front (scroll math), and the MessagesSlot box in the scene matches.
@@ -16,34 +17,17 @@ export const RIGHT_GUTTER = 24;
// Bubble text metrics.
export const LABEL_PAD = 12; // horizontal text inset inside a bubble
export const BUBBLE_VPAD = 10; // vertical padding above + below the text
-const FONT_SIZE = 14;
-const LINE_H = FONT_SIZE * 1.3; // matches Text.lineHeight (1.3 ratio)
-const AVG_CHAR_W = FONT_SIZE * 0.6; // deliberately wide → never under-count lines
+export const FONT_SIZE = 14;
/**
- * Estimated pixel height of a message bubble sized to its wrapped text. There is
- * no public text-measure API yet, so this word-wraps at an estimated
- * chars-per-line and errs TALL (a short estimate would overflow — the exact bug
- * this fixes). Fed to createListView as `itemHeight(index)`.
+ * Pixel height of a message bubble sized to its wrapped text — fed to
+ * createListView as `itemHeight(index)`. Uses the engine's `measureText` (the
+ * same Canvas2D metrics the renderer wraps by), so the row is exactly as tall as
+ * the text renders, no overflow. fontSize + the Text default 1.2 line-height ratio.
*/
export function bubbleHeight(msg: Message): number {
- const textW = BUBBLE_W - 2 * LABEL_PAD;
- const cpl = Math.max(1, Math.floor(textW / AVG_CHAR_W));
- return Math.max(1, wrapLines(msg.text, cpl)) * LINE_H + 2 * BUBBLE_VPAD;
-}
-
-/** Rough word-wrap line count at `cpl` chars per line (a word wider than a line
- * splits across lines). */
-function wrapLines(text: string, cpl: number): number {
- let lines = 1;
- let col = 0;
- for (const word of text.split(/\s+/)) {
- if (col === 0) col = word.length;
- else if (col + 1 + word.length <= cpl) col += 1 + word.length;
- else { lines++; col = word.length; }
- while (col > cpl) { lines++; col -= cpl; }
- }
- return lines;
+ const { height } = measureText(msg.text, { fontSize: FONT_SIZE, maxWidth: BUBBLE_W - 2 * LABEL_PAD });
+ return height + 2 * BUBBLE_VPAD;
}
export const COMPOSER_H = 40;
diff --git a/examples/chat/src/systems/build.ts b/examples/chat/src/systems/build.ts
index ccb8a0613..897581eb5 100644
--- a/examples/chat/src/systems/build.ts
+++ b/examples/chat/src/systems/build.ts
@@ -16,7 +16,7 @@ import type {
import {
CHAT_W, CHAT_H, ROW_SPACING, BUBBLE_W, RIGHT_GUTTER,
- LABEL_PAD, BUBBLE_VPAD, bubbleHeight,
+ LABEL_PAD, BUBBLE_VPAD, FONT_SIZE, bubbleHeight,
COMPOSER_H, SEND_W, INPUT_W,
ME_BUBBLE, BOT_BUBBLE, BUBBLE_TEXT,
botReply, SEED,
@@ -67,7 +67,7 @@ export const buildSystem = defineSystem(
insetTop: px(BUBBLE_VPAD), insetBottom: px(BUBBLE_VPAD),
},
text: {
- content: '', fontSize: 14, color: BUBBLE_TEXT,
+ content: '', fontSize: FONT_SIZE, color: BUBBLE_TEXT,
align: mine ? TextAlign.Right : TextAlign.Left,
verticalAlign: TextVerticalAlign.Middle, wordWrap: true,
},
diff --git a/sdk/etc/index.api.md b/sdk/etc/index.api.md
index d3a240764..a91528fc8 100644
--- a/sdk/etc/index.api.md
+++ b/sdk/etc/index.api.md
@@ -1,7 +1,7 @@
# API surface — esengine/index
<!-- Generated by tools/api-surface.mjs — do not edit. Run --update to accept changes. -->
-Symbols: 1225 stable · 17 beta · 1 deprecated
+Symbols: 1228 stable · 17 beta · 1 deprecated
## ABI_LAYOUT_HASH — const
```
@@ -3577,6 +3577,17 @@ switches: Record<string, boolean> | undefined
uniforms: Record<string, UniformValue> | undefined
```
+## MeasureTextOptions — interface
+```
+bold: boolean | undefined
+fontFamily: string | undefined
+fontSize: number
+italic: boolean | undefined
+letterSpacing: number | undefined
+lineHeight: number | undefined
+maxWidth: number | undefined
+```
+
## MeasuredLinearLayoutProvider — class
```
getContentSize: (count: number) => Vec2
@@ -6240,6 +6251,13 @@ static new (): TextInputPlugin
static prototype: TextInputPlugin
```
+## TextMetrics — interface
+```
+height: number
+lineCount: number
+width: number
+```
+
## TextOverflow — type
```
(typeof TextOverflow)[keyof typeof TextOverflow]
@@ -8665,6 +8683,11 @@ Logger
(type: BtNodeType): number
```
+## measureText — function
+```
+(text: string, opts: MeasureTextOptions): TextMetrics
+```
+
## mesh2dPlugin — const
```
Mesh2DPlugin
diff --git a/sdk/etc/index.node.api.md b/sdk/etc/index.node.api.md
index 15ab0f518..6b4a24a1d 100644
--- a/sdk/etc/index.node.api.md
+++ b/sdk/etc/index.node.api.md
@@ -1,7 +1,7 @@
# API surface — esengine/index.node
<!-- Generated by tools/api-surface.mjs — do not edit. Run --update to accept changes. -->
-Symbols: 1224 stable · 19 beta · 1 deprecated
+Symbols: 1227 stable · 19 beta · 1 deprecated
## ANCHOR_AXES — const
```
@@ -3572,6 +3572,17 @@ switches: Record<string, boolean> | undefined
uniforms: Record<string, UniformValue> | undefined
```
+## MeasureTextOptions — interface
+```
+bold: boolean | undefined
+fontFamily: string | undefined
+fontSize: number
+italic: boolean | undefined
+letterSpacing: number | undefined
+lineHeight: number | undefined
+maxWidth: number | undefined
+```
+
## MeasuredLinearLayoutProvider — class
```
getContentSize: (count: number) => Vec2
@@ -6235,6 +6246,13 @@ static new (): TextInputPlugin
static prototype: TextInputPlugin
```
+## TextMetrics — interface
+```
+height: number
+lineCount: number
+width: number
+```
+
## TextOverflow — type
```
(typeof TextOverflow)[keyof typeof TextOverflow]
@@ -8665,6 +8683,11 @@ Logger
(type: BtNodeType): number
```
+## measureText — function
+```
+(text: string, opts: MeasureTextOptions): TextMetrics
+```
+
## mesh2dPlugin — const
```
Mesh2DPlugin
diff --git a/sdk/src/core-ui.ts b/sdk/src/core-ui.ts
index d26b4cc62..4f644ccf6 100644
--- a/sdk/src/core-ui.ts
+++ b/sdk/src/core-ui.ts
@@ -27,6 +27,9 @@ export {
UILayoutGeneration,
UIMask,
textPlugin,
+ measureText,
+ type MeasureTextOptions,
+ type TextMetrics,
parseRichText,
type RichTextRun,
type TextSegment,
diff --git a/sdk/src/ui/index.ts b/sdk/src/ui/index.ts
index 5a6d8ee77..5f818ef58 100644
--- a/sdk/src/ui/index.ts
+++ b/sdk/src/ui/index.ts
@@ -318,6 +318,7 @@ export { BUILTIN_UI_PREFABS, BUILTIN_UI_WIDGET_NAMES } from './widgets/prefabs/g
// All text — display (Text) and editable (TextInput) — now renders through the
// SDF glyph atlas; the Canvas2D TextRenderer was retired.
export { TextPlugin, textPlugin, resolveTextRenderMode } from './text/plugin';
+export { measureText, type MeasureTextOptions, type TextMetrics } from './text/measure-text';
// UI Math Utilities
export {
diff --git a/sdk/src/ui/text/layout.ts b/sdk/src/ui/text/layout.ts
index 974dfa5bd..a1846b273 100644
--- a/sdk/src/ui/text/layout.ts
+++ b/sdk/src/ui/text/layout.ts
@@ -179,15 +179,13 @@ export function measureWidth(
}
/**
- * Greedy word-wrap a single line to `maxWidth` (display px). Breaks at spaces;
- * a single token wider than the line (long word, or CJK runs which have no
- * spaces) is broken character-by-character. Returns the wrapped sub-lines.
+ * Greedy word-wrap using an arbitrary width `measure` (display px). Breaks at
+ * spaces; a token wider than the line (long word, or CJK runs with no spaces) is
+ * broken character-by-character. The single source of wrap truth — the
+ * atlas-backed {@link wrapLine} and the Canvas2D-backed `measureText` both call
+ * it, so measured heights match rendered wraps.
*/
-export function wrapLine(
- text: string, atlas: GlyphAtlas, fontFamily: string, fontSizePx: number,
- style: number, maxWidth: number, letterSpacing = 0,
-): string[] {
- const measure = (s: string) => measureWidth(s, atlas, fontFamily, fontSizePx, style, letterSpacing);
+export function wrapByMeasure(text: string, measure: (s: string) => number, maxWidth: number): string[] {
const out: string[] = [];
let cur = '';
const flush = () => { const t = cur.replace(/\s+$/, ''); if (t) out.push(t); cur = ''; };
@@ -216,6 +214,17 @@ export function wrapLine(
return out.length ? out : [''];
}
+/**
+ * Greedy word-wrap a single line to `maxWidth` (display px) using the glyph
+ * atlas's advances. Thin wrapper over {@link wrapByMeasure}.
+ */
+export function wrapLine(
+ text: string, atlas: GlyphAtlas, fontFamily: string, fontSizePx: number,
+ style: number, maxWidth: number, letterSpacing = 0,
+): string[] {
+ return wrapByMeasure(text, (s) => measureWidth(s, atlas, fontFamily, fontSizePx, style, letterSpacing), maxWidth);
+}
+
/**
* Lay out multi-line text: splits on `\n`, lays each line out
* (rich or plain), stacks lines downward (y-up: line 0 on top) by `lineHeight`,
diff --git a/sdk/src/ui/text/measure-text.ts b/sdk/src/ui/text/measure-text.ts
new file mode 100644
index 000000000..e34da1b9a
--- /dev/null
+++ b/sdk/src/ui/text/measure-text.ts
@@ -0,0 +1,82 @@
+// SPDX-License-Identifier: Apache-2.0
+// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team
+/**
+ * @file ui/text/measure-text.ts — public text measurement.
+ *
+ * Answers "how wide/tall does this string render?" without spawning a Text
+ * entity, for layout that must size to content up front — e.g. a ListView row
+ * that grows with a wrapped chat bubble (`itemHeight(index)`).
+ *
+ * Metrics come from a hidden Canvas2D context, the SAME source the glyph atlas
+ * draws advances from, so a measured wrap matches the rendered one. Word-wrapping
+ * reuses {@link wrapByMeasure}, the one wrap algorithm the renderer uses. With no
+ * DOM (headless/logic-only host) it falls back to an average-glyph estimate.
+ */
+import { DEFAULT_FONT_FAMILY, DEFAULT_LINE_HEIGHT } from '../../defaults';
+import { wrapByMeasure } from './layout';
+
+export interface MeasureTextOptions {
+ /** Default: Arial. */
+ fontFamily?: string;
+ /** Display px. */
+ fontSize: number;
+ bold?: boolean;
+ italic?: boolean;
+ /** Extra px between glyphs (mirrors the renderer's letterSpacing). */
+ letterSpacing?: number;
+ /** Word-wrap width in display px. 0 / undefined ⇒ a single line (no wrap). */
+ maxWidth?: number;
+ /** Line height in display px. Default: `fontSize * 1.2` (the Text default ratio). */
+ lineHeight?: number;
+}
+
+export interface TextMetrics {
+ /** Width of the widest line, display px. */
+ width: number;
+ /** Number of lines after wrapping + explicit `\n`. */
+ lineCount: number;
+ /** `lineCount * lineHeight`, display px — the height to size a box to. */
+ height: number;
+}
+
+type Measurer = (s: string) => number;
+
+let ctx_: CanvasRenderingContext2D | null | undefined;
+
+/** A width measurer for `opts`: Canvas2D `measureText` where a DOM exists, else
+ * an average-advance estimate (headless). */
+function measurer(opts: MeasureTextOptions): Measurer {
+ const family = opts.fontFamily ?? DEFAULT_FONT_FAMILY;
+ const spacing = opts.letterSpacing ?? 0;
+ if (ctx_ === undefined) {
+ ctx_ = typeof document !== 'undefined' && document.createElement
+ ? document.createElement('canvas').getContext('2d')
+ : null;
+ }
+ if (ctx_) {
+ const ctx = ctx_;
+ ctx.font = `${opts.italic ? 'italic ' : ''}${opts.bold ? 'bold ' : ''}${opts.fontSize}px ${family}`;
+ return (s) => ctx.measureText(s).width + [...s].length * spacing;
+ }
+ // Headless fallback: a wide-ish average so wraps don't under-count.
+ const avg = opts.fontSize * 0.6 + spacing;
+ return (s) => [...s].length * avg;
+}
+
+/**
+ * Measure `text` at the given font, word-wrapped to `maxWidth`. Pure w.r.t. the
+ * inputs (a shared hidden canvas is the only state). Honours explicit `\n`.
+ */
+export function measureText(text: string, opts: MeasureTextOptions): TextMetrics {
+ const measure = measurer(opts);
+ const lineHeight = opts.lineHeight ?? opts.fontSize * DEFAULT_LINE_HEIGHT;
+ const wrap = opts.maxWidth && opts.maxWidth > 0;
+ const lines: string[] = [];
+ for (const para of text.split('\n')) {
+ if (wrap) lines.push(...wrapByMeasure(para, measure, opts.maxWidth!));
+ else lines.push(para);
+ }
+ let width = 0;
+ for (const line of lines) width = Math.max(width, measure(line));
+ return { width, lineCount: lines.length, height: lines.length * lineHeight };
+}
diff --git a/sdk/tests/ui-measure-text.test.ts b/sdk/tests/ui-measure-text.test.ts
new file mode 100644
index 000000000..e8fcdec41
--- /dev/null
+++ b/sdk/tests/ui-measure-text.test.ts
@@ -0,0 +1,35 @@
+// SPDX-License-Identifier: Apache-2.0
+// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team
+import { describe, it, expect } from 'vitest';
+import { measureText } from '../src/ui';
+
+// These hold whether measureText runs on real Canvas2D or the headless average
+// fallback — they assert structure (line counts, height = lines × lineHeight),
+// not exact pixel widths.
+describe('measureText', () => {
+ it('an unwrapped single line has lineCount 1 and height = fontSize × 1.2', () => {
+ const m = measureText('hello world', { fontSize: 16 });
+ expect(m.lineCount).toBe(1);
+ expect(m.height).toBeCloseTo(16 * 1.2);
+ expect(m.width).toBeGreaterThan(0);
+ });
+
+ it('counts explicit newlines as separate lines', () => {
+ expect(measureText('a\nb\nc', { fontSize: 10 }).lineCount).toBe(3);
+ });
+
+ it('wraps long text past maxWidth into multiple lines; height tracks the count', () => {
+ const long = 'word '.repeat(40).trim();
+ const m = measureText(long, { fontSize: 16, maxWidth: 100 });
+ expect(m.lineCount).toBeGreaterThan(1);
+ expect(m.height).toBeCloseTo(m.lineCount * 16 * 1.2);
+ });
+
+ it('a custom lineHeight overrides the default ratio', () => {
+ expect(measureText('x', { fontSize: 10, lineHeight: 30 }).height).toBe(30);
+ });
+
+ it('empty text is one (empty) line', () => {
+ expect(measureText('', { fontSize: 12 }).lineCount).toBe(1);
+ });
+});