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): ListView supports auto-height items via a measured layout

yhh3f36062e123a
diff --git a/examples/chat/src/config.ts b/examples/chat/src/config.ts
index f07e78bc2..c2bdeec78 100644
--- a/examples/chat/src/config.ts
+++ b/examples/chat/src/config.ts
@@ -5,14 +5,47 @@ import type { Color } from 'esengine';
export const CHAT_W = 720;
export const CHAT_H = 424;
-// Fixed-height rows (the list recycles a handful of entities): a bubble plus an
-// 8px gap. Bubbles are pinned left (them) or right (you) at a fixed max width.
-export const ROW_H = 60;
+// Rows auto-size to their wrapped text (createListView's measured layout). Bubbles
+// are pinned left (them) or right (you) at a fixed max width, and grow taller as
+// the message wraps.
export const ROW_SPACING = 8;
export const BUBBLE_W = 460;
// Right-side bubbles leave a gutter so they clear the scroll edge.
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
+
+/**
+ * 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)`.
+ */
+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;
+}
+
export const COMPOSER_H = 40;
export const SEND_W = 84;
export const INPUT_W = CHAT_W - SEND_W - 10; // + the row's 10px gap = CHAT_W
diff --git a/examples/chat/src/systems/build.ts b/examples/chat/src/systems/build.ts
index b97e673b9..ccb8a0613 100644
--- a/examples/chat/src/systems/build.ts
+++ b/examples/chat/src/systems/build.ts
@@ -15,7 +15,8 @@ import type {
} from 'esengine';
import {
- CHAT_W, CHAT_H, ROW_H, ROW_SPACING, BUBBLE_W, RIGHT_GUTTER,
+ CHAT_W, CHAT_H, ROW_SPACING, BUBBLE_W, RIGHT_GUTTER,
+ LABEL_PAD, BUBBLE_VPAD, bubbleHeight,
COMPOSER_H, SEND_W, INPUT_W,
ME_BUBBLE, BOT_BUBBLE, BUBBLE_TEXT,
botReply, SEED,
@@ -48,12 +49,13 @@ export const buildSystem = defineSystem(
const makeSide = (w: World, row: Entity, mine: boolean): Side => {
const bubble = spawnUIEntity({
world: w, parent: row,
+ // Fills the row's (measured) height; width fixed, pinned to a side.
node: {
position: UIPositionType.Absolute,
insetLeft: px(mine ? CHAT_W - BUBBLE_W - RIGHT_GUTTER : 12),
insetTop: px(0),
+ insetBottom: px(0),
width: px(BUBBLE_W),
- height: px(ROW_H - ROW_SPACING),
},
visual: { color: mine ? ME_BUBBLE : BOT_BUBBLE, enabled: false },
});
@@ -61,7 +63,8 @@ export const buildSystem = defineSystem(
world: w, parent: bubble,
node: {
position: UIPositionType.Absolute,
- insetLeft: px(12), insetRight: px(12), insetTop: px(0), insetBottom: px(0),
+ insetLeft: px(LABEL_PAD), insetRight: px(LABEL_PAD),
+ insetTop: px(BUBBLE_VPAD), insetBottom: px(BUBBLE_VPAD),
},
text: {
content: '', fontSize: 14, color: BUBBLE_TEXT,
@@ -96,7 +99,8 @@ export const buildSystem = defineSystem(
viewportSize: { x: CHAT_W, y: CHAT_H },
background: { color: LIST_BG },
data: messages,
- layout: { itemHeight: ROW_H, spacing: ROW_SPACING },
+ // Rows auto-size to each message's wrapped text (measured layout).
+ layout: { itemHeight: (i) => bubbleHeight(messages.getItem(i)), spacing: ROW_SPACING },
item: rowTemplate,
});
diff --git a/sdk/etc/index.api.md b/sdk/etc/index.api.md
index 273369192..d3a240764 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: 1224 stable · 17 beta · 1 deprecated
+Symbols: 1225 stable · 17 beta · 1 deprecated
## ABI_LAYOUT_HASH — const
```
@@ -3277,7 +3277,7 @@ create: (world: World, parent: Entity) => Entity
## ListLayoutSpec — type
```
-| { itemHeight: number; spacing?: number; direction?: 'column' }
+| { itemHeight: number | ((index: number) => number); spacing?: number; direction?: 'column' }
| { itemWidth: number; spacing?: number; direction: 'row' }
| { columns: number; itemSize: Vec2; spacing?: Vec2 }
```
@@ -3577,6 +3577,16 @@ switches: Record<string, boolean> | undefined
uniforms: Record<string, UniformValue> | undefined
```
+## MeasuredLinearLayoutProvider — class
+```
+getContentSize: (count: number) => Vec2
+getItemRect: (index: number) => Rect
+getVisibleRange: (viewport: Rect, count: number) => [number, number]
+invalidate: () => void
+static new (opts: MeasuredLinearLayoutOptions): MeasuredLinearLayoutProvider
+static prototype: MeasuredLinearLayoutProvider
+```
+
## MemoryTransport — class
```
dropPending: () => void
diff --git a/sdk/etc/index.node.api.md b/sdk/etc/index.node.api.md
index 78ccb84a7..15ab0f518 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: 1223 stable · 19 beta · 1 deprecated
+Symbols: 1224 stable · 19 beta · 1 deprecated
## ANCHOR_AXES — const
```
@@ -3272,7 +3272,7 @@ create: (world: World, parent: Entity) => Entity
## ListLayoutSpec — type
```
-| { itemHeight: number; spacing?: number; direction?: 'column' }
+| { itemHeight: number | ((index: number) => number); spacing?: number; direction?: 'column' }
| { itemWidth: number; spacing?: number; direction: 'row' }
| { columns: number; itemSize: Vec2; spacing?: Vec2 }
```
@@ -3572,6 +3572,16 @@ switches: Record<string, boolean> | undefined
uniforms: Record<string, UniformValue> | undefined
```
+## MeasuredLinearLayoutProvider — class
+```
+getContentSize: (count: number) => Vec2
+getItemRect: (index: number) => Rect
+getVisibleRange: (viewport: Rect, count: number) => [number, number]
+invalidate: () => void
+static new (opts: MeasuredLinearLayoutOptions): MeasuredLinearLayoutProvider
+static prototype: MeasuredLinearLayoutProvider
+```
+
## MemoryTransport — class
```
dropPending: () => void
diff --git a/sdk/src/core-ui.ts b/sdk/src/core-ui.ts
index 6b820a1f8..d26b4cc62 100644
--- a/sdk/src/core-ui.ts
+++ b/sdk/src/core-ui.ts
@@ -228,6 +228,7 @@ export {
arrayDataSource,
type DataSource,
LinearLayoutProvider,
+ MeasuredLinearLayoutProvider,
GridLayoutProvider,
type LayoutProvider,
widgetToPrefab,
diff --git a/sdk/src/ui/collection/layout-provider.ts b/sdk/src/ui/collection/layout-provider.ts
index fad82c0c2..b99cc7015 100644
--- a/sdk/src/ui/collection/layout-provider.ts
+++ b/sdk/src/ui/collection/layout-provider.ts
@@ -88,6 +88,90 @@ export class LinearLayoutProvider implements LayoutProvider {
}
}
+// -- Measured linear (variable main-axis size) --------------------------------
+
+export interface MeasuredLinearLayoutOptions {
+ direction?: 'row' | 'column';
+ spacing?: number;
+ /** Fixed cross-axis size (width for a column list, height for a row). */
+ crossSize: number;
+ /** Main-axis size (height for a column, width for a row) of item `index`. */
+ mainSizeOf: (index: number) => number;
+}
+
+/**
+ * A linear list whose items vary along the main axis (e.g. chat bubbles that grow
+ * with their wrapped text). Item offsets are prefix-summed and cached; the cache
+ * rebuilds when the item count changes or {@link invalidate} is called (a data or
+ * measurement change — the ListView invalidates on both). `mainSizeOf` is the
+ * app's measure hook, so the list stays measurement-agnostic.
+ */
+export class MeasuredLinearLayoutProvider implements LayoutProvider {
+ private readonly dir_: 'row' | 'column';
+ private readonly spacing_: number;
+ private readonly crossSize_: number;
+ private readonly mainSizeOf_: (index: number) => number;
+ /** Prefix offsets: `offsets_[i]` = main-axis start of item `i`; length count+1. */
+ private offsets_: number[] = [0];
+ private total_ = 0;
+ private builtFor_ = -1; // item count the offsets were built for; -1 forces rebuild
+
+ constructor(opts: MeasuredLinearLayoutOptions) {
+ this.dir_ = opts.direction ?? 'column';
+ this.spacing_ = opts.spacing ?? 0;
+ this.crossSize_ = opts.crossSize;
+ this.mainSizeOf_ = opts.mainSizeOf;
+ }
+
+ /** Re-measure on the next query (an item's data/size changed, not just the count). */
+ invalidate(): void {
+ this.builtFor_ = -1;
+ }
+
+ private ensure_(count: number): void {
+ if (this.builtFor_ === count) return;
+ this.builtFor_ = count;
+ const offsets = new Array<number>(count + 1);
+ offsets[0] = 0;
+ for (let i = 0; i < count; i++) {
+ offsets[i + 1] = offsets[i] + Math.max(0, this.mainSizeOf_(i)) + this.spacing_;
+ }
+ this.offsets_ = offsets;
+ // Drop the trailing gap after the last item.
+ this.total_ = count > 0 ? offsets[count] - this.spacing_ : 0;
+ }
+
+ getContentSize(count: number): Vec2 {
+ this.ensure_(count);
+ return this.dir_ === 'column'
+ ? { x: this.crossSize_, y: this.total_ }
+ : { x: this.total_, y: this.crossSize_ };
+ }
+
+ getItemRect(index: number): Rect {
+ // getVisibleRange / getContentSize run first each update() and prime the cache.
+ const start = this.offsets_[index] ?? 0;
+ const size = Math.max(0, (this.offsets_[index + 1] ?? start) - start - this.spacing_);
+ return this.dir_ === 'column'
+ ? { x: 0, y: start, width: this.crossSize_, height: size }
+ : { x: start, y: 0, width: size, height: this.crossSize_ };
+ }
+
+ getVisibleRange(viewport: Rect, count: number): [number, number] {
+ this.ensure_(count);
+ if (count <= 0) return [0, 0];
+ const vStart = this.dir_ === 'column' ? viewport.y : viewport.x;
+ const vEnd = vStart + (this.dir_ === 'column' ? viewport.height : viewport.width);
+ // offsets_ is sorted, so scan for the first item whose end clears vStart and
+ // the last whose start is before vEnd (linear — visible spans are short).
+ let start = 0;
+ while (start < count && this.offsets_[start + 1] - this.spacing_ <= vStart) start++;
+ let end = start;
+ while (end < count && this.offsets_[end] < vEnd) end++;
+ return start < end ? [start, end] : [0, 0];
+ }
+}
+
// -- Grid ---------------------------------------------------------------------
export interface GridLayoutOptions {
diff --git a/sdk/src/ui/collection/list-view.ts b/sdk/src/ui/collection/list-view.ts
index a00cc318c..91387a173 100644
--- a/sdk/src/ui/collection/list-view.ts
+++ b/sdk/src/ui/collection/list-view.ts
@@ -105,10 +105,18 @@ export class ListView<T = unknown> {
if (this.dataSource_.subscribe) {
this.unsubscribeDataSource_ = this.dataSource_.subscribe(() => {
this.dirty_ = true;
+ this.invalidateLayout_();
});
}
}
+ /** A measured layout caches per-item offsets; drop them when the data (or, for
+ * width-dependent measures like wrapped text, the viewport) changes. No-op for
+ * fixed-size providers. */
+ private invalidateLayout_(): void {
+ (this.layout_ as { invalidate?: () => void }).invalidate?.();
+ }
+
/** Current visible window within the content, in content-local coords. */
getViewport(): Rect {
return {
@@ -144,6 +152,7 @@ export class ListView<T = unknown> {
if (size.x === this.viewportSize_.x && size.y === this.viewportSize_.y) return;
this.viewportSize_ = { x: size.x, y: size.y };
this.dirty_ = true;
+ this.invalidateLayout_(); // width-dependent measures (wrapped text) re-flow
}
/** Mark the mount set dirty — the next `update()` will re-sync. */
diff --git a/sdk/src/ui/index.ts b/sdk/src/ui/index.ts
index 803834bf7..5a6d8ee77 100644
--- a/sdk/src/ui/index.ts
+++ b/sdk/src/ui/index.ts
@@ -203,8 +203,10 @@ export {
type LayoutProvider,
type Rect,
type LinearLayoutOptions,
+ type MeasuredLinearLayoutOptions,
type GridLayoutOptions,
LinearLayoutProvider,
+ MeasuredLinearLayoutProvider,
GridLayoutProvider,
} from './collection/layout-provider';
diff --git a/sdk/src/ui/widgets/list-view.ts b/sdk/src/ui/widgets/list-view.ts
index 811737f34..66bfbd54d 100644
--- a/sdk/src/ui/widgets/list-view.ts
+++ b/sdk/src/ui/widgets/list-view.ts
@@ -32,6 +32,7 @@ import {
type LayoutProvider,
type Rect,
LinearLayoutProvider,
+ MeasuredLinearLayoutProvider,
GridLayoutProvider,
} from '../collection/layout-provider';
import { ListView } from '../collection/list-view';
@@ -61,7 +62,7 @@ export interface ListItemTemplate<T> {
/** Layout sugar. A column list, a row list, or a grid (`columns`). */
export type ListLayoutSpec =
- | { itemHeight: number; spacing?: number; direction?: 'column' }
+ | { itemHeight: number | ((index: number) => number); spacing?: number; direction?: 'column' }
| { itemWidth: number; spacing?: number; direction: 'row' }
| { columns: number; itemSize: Vec2; spacing?: Vec2 };
@@ -138,6 +139,13 @@ function buildLayout(spec: ListLayoutSpec, viewport: Vec2): { layout: LayoutProv
axis: 'horizontal',
};
}
+ if (typeof spec.itemHeight === 'function') {
+ const mainSizeOf = spec.itemHeight;
+ return {
+ layout: new MeasuredLinearLayoutProvider({ direction: 'column', crossSize: viewport.x, mainSizeOf, spacing: spec.spacing }),
+ axis: 'vertical',
+ };
+ }
return {
layout: new LinearLayoutProvider({ direction: 'column', itemSize: { x: viewport.x, y: spec.itemHeight }, spacing: spec.spacing }),
axis: 'vertical',
diff --git a/sdk/tests/ui-layout-provider.test.ts b/sdk/tests/ui-layout-provider.test.ts
index 0d4e0d66f..7ea54f03c 100644
--- a/sdk/tests/ui-layout-provider.test.ts
+++ b/sdk/tests/ui-layout-provider.test.ts
@@ -1,11 +1,54 @@
// SPDX-License-Identifier: Apache-2.0
// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team
import { describe, it, expect } from 'vitest';
-import { LinearLayoutProvider, GridLayoutProvider, type Rect } from '../src/ui';
+import { LinearLayoutProvider, MeasuredLinearLayoutProvider, GridLayoutProvider, type Rect } from '../src/ui';
const VIEWPORT = (x: number, y: number, w: number, h: number): Rect =>
({ x, y, width: w, height: h });
+describe('MeasuredLinearLayoutProvider (variable height)', () => {
+ // Heights are mutable so the invalidate() case can re-measure.
+ const heights = [20, 40, 60, 30];
+ const p = new MeasuredLinearLayoutProvider({
+ direction: 'column',
+ crossSize: 200,
+ spacing: 4,
+ mainSizeOf: (i) => heights[i],
+ });
+
+ it('content height sums measured items plus inter-item spacing', () => {
+ // 20+40+60+30 = 150 + 3 gaps * 4 = 162
+ expect(p.getContentSize(4)).toEqual({ x: 200, y: 162 });
+ });
+
+ it('empty content has zero size', () => {
+ expect(p.getContentSize(0)).toEqual({ x: 200, y: 0 });
+ });
+
+ it('item rects offset by the running measured heights', () => {
+ p.getContentSize(4); // prime the cache
+ expect(p.getItemRect(0)).toEqual({ x: 0, y: 0, width: 200, height: 20 });
+ expect(p.getItemRect(1)).toEqual({ x: 0, y: 24, width: 200, height: 40 });
+ expect(p.getItemRect(2)).toEqual({ x: 0, y: 68, width: 200, height: 60 });
+ expect(p.getItemRect(3)).toEqual({ x: 0, y: 132, width: 200, height: 30 });
+ });
+
+ it('visible range spans items that overlap the window', () => {
+ // window 0..50 covers item0 (0..20) and item1 (24..64); item2 starts at 68
+ expect(p.getVisibleRange(VIEWPORT(0, 0, 200, 50), 4)).toEqual([0, 2]);
+ // scrolled to y=70 covers item2 (68..128) and item3 (132..162)
+ expect(p.getVisibleRange(VIEWPORT(0, 70, 200, 80), 4)).toEqual([2, 4]);
+ });
+
+ it('invalidate() re-measures after a height changes', () => {
+ heights[0] = 100; // item 0 grew
+ // Stale until invalidate: the cache still reports the old total.
+ expect(p.getContentSize(4).y).toBe(162);
+ p.invalidate();
+ expect(p.getContentSize(4).y).toBe(242); // 100+40+60+30 + 12
+ });
+});
+
describe('LinearLayoutProvider (column)', () => {
const p = new LinearLayoutProvider({
direction: 'column',