Skip to content

Commit b5baf57

Browse files
authored
✨Element replay
1 parent 0317a14 commit b5baf57

18 files changed

Lines changed: 832 additions & 275 deletions

‎.changeset/css-color-strings.md‎

Lines changed: 18 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -1,24 +1,35 @@
11
---
2-
'@bomb.sh/tty': minor
2+
"@bomb.sh/tty": minor
33
---
44

55
Adds CSS color string support to every color field in `@bomb.sh/tty`.
66

7-
`open({ bg })`, `border.color`, `border.bg`, per-side `color`/`bg`, and `text({ color, bg })` now accept CSS Color 4 strings in addition to packed ARGB numbers from `rgba()`.
7+
`open(id, { bg })`, `border.color`, `border.bg`, per-side `color`/`bg`, and
8+
`text(content, { color, bg })` now accept CSS Color 4 strings in addition to
9+
packed ARGB numbers from `rgba()`.
810

911
#### Accepted forms
1012

1113
- **Hex** — `#rgb`, `#rgba`, `#rrggbb`, `#rrggbbaa`
12-
- **Named colors** — `rebeccapurple`, `transparent`, all CSS named color keywords
13-
- **Functions** — `rgb()`, `rgba()`, `hsl()`, `hsla()`, `hwb()`, `lab()`, `lch()`, `oklab()`, `oklch()`
14+
- **Named colors** — `rebeccapurple`, `transparent`, all CSS named color
15+
keywords
16+
- **Functions** — `rgb()`, `rgba()`, `hsl()`, `hsla()`, `hwb()`, `lab()`,
17+
`lch()`, `oklab()`, `oklch()`
1418

15-
Colors are resolved to sRGB at the transfer-encoding boundary; the wire format, snapshot encoding, and renderer are unchanged. Out-of-gamut colors (common with `lab()`/`oklch()`) clip per channel. Invalid strings are rejected by `validate()` and throw a `TypeError` from the packer before any bytes are produced.
19+
Colors are resolved to packed sRGB ARGB values when directives are encoded for
20+
the renderer. Out-of-gamut colors (common with `lab()`/`oklch()`) clip per
21+
channel. Invalid strings are rejected by `validate()` and cause `render()` to
22+
throw a `TypeError` before returning output.
1623

17-
String literals assigned to color fields are also checked at compile time in TypeScript: invalid hex digit counts, misspelled named colors, and unsupported function names are type errors.
24+
String literals assigned to color fields are also checked at compile time in
25+
TypeScript: invalid hex digit counts, misspelled named colors, and unsupported
26+
function names are type errors.
1827

1928
#### Migration
2029

21-
Color fields were previously typed `number`; they are now typed `number | string`. Existing `rgba()` calls and numeric color values are unaffected.
30+
Color fields were previously typed `number`; they are now typed
31+
`number | string`. Existing `rgba()` calls and numeric color values are
32+
unaffected.
2233

2334
```diff
2435
-open("box", { bg: rgba(255, 136, 0) });

‎.changeset/element-replay.md‎

Lines changed: 30 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,30 @@
1+
---
2+
"@bomb.sh/tty": minor
3+
---
4+
5+
Adds `result.info.get(id).replay` to reuse an entire rendered element, including
6+
its descendants, in the next `render()` call without rebuilding or repacking its
7+
directives. Layout, pointer handling, caret placement, and transitions use the
8+
new render's context and options.
9+
10+
**Breaking:** removes `snapshot()`. Give the reusable subtree a named root,
11+
render its directives once, then obtain its replay from the result:
12+
13+
```ts
14+
let result = term.render([
15+
open("sidebar"),
16+
text("Navigation"),
17+
close(),
18+
]);
19+
20+
result = term.render([result.info.get("sidebar")!.replay]);
21+
```
22+
23+
Each completed render expires previous replays, even if it emits no output.
24+
Obtain a fresh replay from each new result. `update()` calls, including resizes
25+
and capability changes, and renders that throw preserve existing replays. An
26+
older result's `info.get()` returns `undefined` after another render completes.
27+
28+
`validate()` and `assert()` now reject unbalanced `open()`/`close()` directives.
29+
The optional `validated(term)` wrapper also rejects expired replays obtained
30+
through the wrapper.

‎AGENTS.md‎

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -49,7 +49,8 @@ Do not include any agent marketing material (e.g. "Generated with...",
4949
renderer-spec.md §7.10).
5050

5151
- Each frame is a complete snapshot. The renderer carries no UI tree state
52-
between frames — only cell buffers for diffing.
52+
between frames. Retained directives support element replay; cell buffers
53+
support diffing.
5354

5455
- Public API values are string literals (`"center-center"`), not numeric
5556
constants or enums. Use functions when a value is parameterized.

‎Makefile‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -23,7 +23,7 @@ EXPORTS = \
2323
-Wl,--export=pointer_over_count \
2424
-Wl,--export=pointer_over_id_string_length \
2525
-Wl,--export=pointer_over_id_string_ptr \
26-
-Wl,--export=get_element_bounds \
26+
-Wl,--export=get_element_info \
2727
-Wl,--export=animating \
2828
-Wl,--export=error_count \
2929
-Wl,--export=error_type \

‎bench/render.bench.ts‎

Lines changed: 12 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -101,6 +101,8 @@ let uiOps: Op[] = [
101101
];
102102

103103
let bench = withCodSpeed(new Bench({ name: "render" }));
104+
let replayTerm = await createTerm({ width: 80, height: 24 });
105+
let replayResult = replayTerm.render(dashboardOps);
104106

105107
bench
106108
.add(
@@ -118,6 +120,16 @@ bench
118120
term.render(dashboardOps);
119121
}
120122
}),
123+
)
124+
.add(
125+
"render steady replay",
126+
sync(() => {
127+
for (let i = 0; i < 250; i++) {
128+
replayResult = replayTerm.render([
129+
replayResult.info.get("root")!.replay,
130+
]);
131+
}
132+
}),
121133
);
122134

123135
await bench.run();

‎ops.ts‎

Lines changed: 11 additions & 50 deletions
Original file line numberDiff line numberDiff line change
@@ -30,7 +30,7 @@ export interface Transition {
3030
const OP_OPEN_ELEMENT = 0x02;
3131
const OP_TEXT = 0x03;
3232
const OP_CLOSE_ELEMENT = 0x04;
33-
const OP_SNAPSHOT = 0x05;
33+
const OP_REPLAY = 0x05;
3434

3535
/* Property group masks for OPEN_ELEMENT */
3636
const PROP_LAYOUT = 0x01;
@@ -296,9 +296,11 @@ export function pack(
296296
break;
297297
}
298298

299-
case OP_SNAPSHOT: {
300-
new Uint8Array(mem).set(op.data, o);
301-
o += op.data.length;
299+
case OP_REPLAY: {
300+
view.setUint32(o, OP_REPLAY, true);
301+
view.setUint32(o + 4, op.offset, true);
302+
view.setUint32(o + 8, op.length, true);
303+
o += 12;
302304
break;
303305
}
304306

@@ -528,12 +530,13 @@ export interface Text {
528530
caret?: number;
529531
}
530532

531-
interface Snapshot {
532-
directive: typeof OP_SNAPSHOT;
533-
data: Uint8Array;
533+
interface Replay {
534+
directive: typeof OP_REPLAY;
535+
offset: number;
536+
length: number;
534537
}
535538

536-
export type Op = OpenElement | Text | CloseElement | Snapshot;
539+
export type Op = OpenElement | Text | CloseElement | Replay;
537540

538541
/*
539542
* Compile-time color checking (§8.5). A string literal assigned to a color
@@ -633,48 +636,6 @@ export function close(): CloseElement {
633636
return { directive: OP_CLOSE_ELEMENT };
634637
}
635638

636-
function packSize(ops: Op[]): number {
637-
let n = 0;
638-
for (let op of ops) {
639-
switch (op.directive) {
640-
case OP_CLOSE_ELEMENT:
641-
n += 4;
642-
break;
643-
case OP_SNAPSHOT:
644-
n += op.data.length;
645-
break;
646-
case OP_OPEN_ELEMENT: {
647-
n += 4; // opcode
648-
n += 4 + Math.ceil(encoder.encode(op.id).length / 4) * 4; // id string
649-
n += 4; // mask
650-
if (op.layout) n += 6 * 4 + 4 + 4 + 4; // 2 axes (3 words each) + pad + gap + align
651-
if (op.bg !== undefined) n += 4;
652-
if (op.cornerRadius) n += 4;
653-
if (op.border) n += 36; // widths word + 4 sides × (fg + bg)
654-
if (op.clip) n += 4;
655-
// x, y, expand width/height, parent, attach/pointer, clip/z
656-
if (op.floating) n += 7 * 4;
657-
if (op.transition) n += 8;
658-
if (pointerShapeIndex(op.cursor) !== undefined) n += 4;
659-
break;
660-
}
661-
case OP_TEXT: {
662-
n += 4 + 4 + 4 + 4 + 4; // opcode + color + bg + cfg + caret
663-
n += 4 + Math.ceil(encoder.encode(op.content).length / 4) * 4; // string
664-
break;
665-
}
666-
}
667-
}
668-
return n;
669-
}
670-
671-
export function snapshot(ops: Op[]): Op {
672-
let size = packSize(ops);
673-
let buf = new ArrayBuffer(size);
674-
let words = pack(ops, buf, 0, size);
675-
return { directive: OP_SNAPSHOT, data: new Uint8Array(buf, 0, words * 4) };
676-
}
677-
678639
const TP_X = 1;
679640
const TP_Y = 2;
680641
const TP_WIDTH = 4;

‎specs/renderer-spec.md‎

Lines changed: 52 additions & 34 deletions
Original file line numberDiff line numberDiff line change
@@ -149,19 +149,18 @@ yields, or partial results.
149149

150150
Each render transaction operates on a complete, self-contained snapshot of the
151151
UI. The renderer MUST NOT maintain an internal component tree or UI state across
152-
frames. The only state the renderer retains between frames is the cell buffer
153-
used for diffing, which is an implementation detail of output minimization and
154-
not observable to the caller except through reduced output size.
152+
frames. Elements from the previous render MAY be supplied through their replay
153+
directives (§8.3.4). The caller still supplies the complete frame on every
154+
render.
155155

156156
### 4.4 Double-buffered diffing
157157

158158
The renderer maintains two cell buffers: a front buffer (the previously rendered
159159
frame) and a back buffer (the frame being rendered). After populating the back
160160
buffer from the current frame's render commands, the renderer compares it
161-
against the front buffer and emits ANSI bytes only for cells that differ.
162-
Changed cells are then copied from the back buffer to the front buffer so that
163-
both buffers are identical at the end of the transaction. This mechanism is
164-
internal to the renderer and not directly observable to the caller.
161+
against the front buffer and emits ANSI bytes only for cells that differ. The
162+
completed frame becomes the comparison baseline for the next render. This
163+
mechanism is internal to the renderer and not directly observable to the caller.
165164

166165
---
167166

@@ -218,7 +217,8 @@ complete frame as a directive array and receives ANSI bytes in return.
218217

219218
**INV-3. Frame-snapshot independence.** The renderer MUST NOT require the caller
220219
to maintain or provide state across frames beyond calling `render()` on the same
221-
Term instance. Each directive array fully describes its frame.
220+
Term instance. Each directive array fully describes its frame, directly or
221+
through valid element replay directives.
222222

223223
**INV-4. ANSI byte output.** The output of a render transaction MUST be a byte
224224
sequence of valid UTF-8–encoded ANSI escape codes that is directly writable to a
@@ -549,8 +549,8 @@ shape:
549549
element in `"capture"` mode hides the elements beneath it; one in
550550
`"passthrough"` mode lets them decide.
551551

552-
Elements inside a `snapshot()` participate as direct directives would.
553-
Resolution and output are identical in line mode (§8.2.2).
552+
Replayed elements participate as direct directives would. Resolution and output
553+
are identical in line mode (§8.2.2).
554554

555555
**Output.** The Term tracks the shape it last emitted, starting at `default`.
556556
When the resolved shape differs, the render MUST append `ESC ] 22 ; <shape> ST`
@@ -704,25 +704,31 @@ occupied by a grapheme cluster with combining marks MUST be treated as changed
704704
The set of styling properties accepted by `props` is part of the current
705705
implementation surface and may be extended.
706706

707-
#### 8.3.4 snapshot
707+
#### 8.3.4 Element replay
708708

709-
```
710-
snapshot(ops: Op[]): Op
709+
```ts
710+
let sidebar = previous.info.get("sidebar")!;
711+
let next = term.render([
712+
open("root", rootProps),
713+
sidebar.replay,
714+
close(),
715+
]);
711716
```
712717

713-
Creates a snapshot by pre-packing the given directive array into its transfer
714-
encoding. The returned value is an `Op` and can appear anywhere in a directive
715-
array where the original ops would have appeared. The internal representation is
716-
opaque.
718+
Each `ElementInfo` MUST contain a `replay` field whose value is an `Op`. It can
719+
be placed directly in a directive array as a substitute for that entire element,
720+
from its `open()` through its matching `close()`, including all descendants. Its
721+
representation is opaque. Callers can reuse unchanged elements without
722+
rebuilding their directives or packing their contents into the transfer buffer.
717723

718-
When the renderer encounters a snapshot during transfer, it copies the
719-
pre-packed bytes directly into the command buffer without re-encoding. The
720-
snapshot's ops MUST be structurally balanced (every `open` matched by a
721-
`close`).
724+
A replay is equivalent to supplying the element's original directives in that
725+
position. Layout, pointer handling, caret placement, and transitions use the new
726+
render's context and options. Replayed elements and their descendants provide
727+
fresh `ElementInfo` in the result.
722728

723-
Snapshots enable higher-level frameworks to implement dirty tracking: a
724-
component whose inputs have not changed can reuse a previously created snapshot,
725-
avoiding the cost of re-packing its subtree each frame.
729+
A replay is valid until the next render completes. `update()` and renders that
730+
throw do not expire it. To reuse the element again, obtain its replay from the
731+
new result. Using an expired replay is invalid input (§9.1).
726732

727733
### 8.4 Sizing helpers
728734

@@ -764,9 +770,9 @@ wherever the directive model expects a color.
764770
structured border sides, and `text({ color, bg })` — accepts both forms. Each
765771
color string is resolved to a packed ARGB value at the transfer-encoding
766772
boundary (§9.2), so color strings MUST NOT appear in the transfer encoding. The
767-
wire format, snapshot encoding, and cell representation are unchanged by this
768-
acceptance: packed sRGB ARGB remains the only color representation the renderer
769-
sees.
773+
wire format, retained directive encoding, and cell representation are unchanged
774+
by this acceptance: packed sRGB ARGB remains the only color representation the
775+
renderer sees.
770776

771777
**Color string grammar.** A color string is one of the following CSS Color
772778
Module Level 4 forms. Function names and keywords are case-insensitive. Leading
@@ -866,10 +872,10 @@ _This section is normative._
866872
### 9.1 Directive-array pattern
867873

868874
The rendering input is an ordered array of directive objects. Each directive is
869-
a plain JavaScript/TypeScript object created by a constructor function (Section
870-
8.3). Directives are not classes, do not carry methods, and do not participate
871-
in a prototype chain. They MAY be spread, composed, stored, or inspected as
872-
ordinary objects.
875+
a plain JavaScript/TypeScript object created by a constructor function or
876+
returned as an element's replay (Section 8.3). Directives are not classes, do
877+
not carry methods, and do not participate in a prototype chain. They MAY be
878+
spread, composed, stored, or inspected as ordinary objects.
873879

874880
The array is processed in order. Open and close directives form an implicit
875881
tree. The renderer processes them sequentially.
@@ -879,9 +885,10 @@ that do not match a preceding open, is invalid input. Callers SHOULD validate
879885
directive arrays before rendering. The renderer's behavior when given an invalid
880886
directive array is unspecified by this specification.
881887

882-
A snapshot is semantically equivalent to splicing its source ops into the array
883-
at the snapshot's position. The renderer MUST produce identical layout and
884-
output regardless of whether ops are provided directly or via a snapshot.
888+
A replay is semantically equivalent to splicing the referenced element's
889+
directives into the array at the replay's position. The renderer MUST produce
890+
identical layout and output for direct and replayed directives given the same
891+
rendering history and options.
885892

886893
### 9.2 Transfer to the WASM module
887894

@@ -897,6 +904,9 @@ expose only the raw host-level TypedArray message `"offset is out of bounds"`
897904
for this condition. The error message SHOULD direct callers to render a smaller
898905
visible slice or reduce frame content.
899906

907+
The same capacity policy applies when replayed content makes the frame exceed
908+
renderer capacity, even if its transfer data fits.
909+
900910
### 9.3 Directive identity
901911

902912
Each element directive carries an `id` provided by the caller via `open()`.
@@ -1201,6 +1211,7 @@ interface RenderInfo {
12011211
12021212
interface ElementInfo {
12031213
bounds: BoundingBox;
1214+
replay: Op;
12041215
}
12051216
12061217
interface BoundingBox {
@@ -1216,6 +1227,9 @@ element's computed bounding box in character cells, as determined by the layout
12161227
engine after the render transaction completes. `x` and `y` are zero-indexed from
12171228
the top-left corner of the layout root.
12181229

1230+
The `replay` field substitutes for the entire element as defined in §8.3.4. A
1231+
result's `info` MUST NOT return metadata belonging to a later render.
1232+
12191233
Querying an element with an empty-string id or an id not present in the frame
12201234
returns `undefined`.
12211235

@@ -1278,6 +1292,10 @@ structural errors (unbalanced open/close pairs, invalid field types — includin
12781292
color fields, which must be a packed ARGB number or a §8.5 CSS color string).
12791293
Exported and used in tests.
12801294

1295+
**`validated(term)`** — An optional wrapper that validates directives before
1296+
rendering, including rejecting expired replay directives. These diagnostics are
1297+
not required when calling the unwrapped Term.
1298+
12811299
**`pack(ops, mem, offset)`** — An internal function that serializes a directive
12821300
array into the transfer encoding described in Section 12.1. Currently exported
12831301
but not public API; its exposure is incidental to the module structure.

0 commit comments

Comments
 (0)