# The in-memory renderer

`@swiftbrowser/raster` ([`packages/raster`](https://swiftbrowser-docs.pages.dev/raster))
draws a SwiftBrowser app's render ops to a PNG with no browser: the web
renderer's own layout engine lays the element tree out, a painter turns the
result into a flat display list, and a Rust rasterizer compiled to
WebAssembly draws it. It runs wherever WebAssembly does: Node (an agent's
sandbox, CI, the CLI), Cloudflare Workers, and a page that wants a picture of
an app without mounting it. This page is the exploration behind it: what it
is for, the shape chosen and the ones not chosen, how close it gets to the
browser, and what is left.

```
app.wasm (headless, Node WASI)  ─┐
@swiftbrowser/react (Node)      ─┼─▶ ops ─▶ element tree ─▶ layout engine ─▶ display list ─▶ raster.wasm ─▶ PNG
a snapshot (.jsonl)             ─┘            (tree.ts)      (Web/src/layout)    (paint.ts)     (tiny-skia)
```

## Why

Screenshots are how an agent sees an app, and how a test says what a screen
looked like. Until now both needed a browser: Playwright's Chromium in CI, or
a real one. A browser is a large dependency where an agent runs (a sandbox
without a display, a Cloudflare Worker, a serverless function), slow to start,
and not deterministic to the pixel across versions. The headless op stream
(`SB_HEADLESS=1`, docs/ops-protocol.md "Headless mode") already describes a
screen completely without a browser; what was missing was something to draw
it.

The goal is a renderer that is a plain function from ops to pixels: no DOM,
no fonts from the system, the same output on every machine, fast enough to
draw a screen per event, and close enough to the browser that a screenshot
from it means what a screenshot from the browser means.

## The shape

The decisive fact is that **layout already lives outside the DOM**
(docs/architecture.md, "Phase 3 notes"): `Web/src/layout` is a pure
TypeScript engine, 5,600 lines of SwiftUI's propose-and-report protocol per
element kind, with a pluggable `TextMeasurer` and a vitest suite that runs in
Node. The DOM renderer only *positions* elements from its result and paints
them with CSS. So the renderer here reuses the engine as it is and replaces
the DOM with a display list: one source of truth for where everything goes,
shared with the web renderer, and the Rust side stays generic.

Two other shapes were considered:

- **Everything in Rust**: port the layout engine too, so the ops go into the
  module and pixels come out. It would be the leanest artifact and the
  fastest, but a second 5,600-line layout engine to keep in step with the
  first, or a migration of the web renderer onto the Rust one (possible: wasm
  calls are synchronous, and the web renderer already calls its engine
  synchronously on every commit). The display list is the seam that keeps
  this open: the Rust side knows nothing of SwiftUI, only rectangles, paths
  and text, so layout can move later without touching it.
- **A DOM in Node** (jsdom, linkedom, or a headless Chromium): the web
  renderer unchanged. jsdom does no layout or painting; a headless Chromium is
  the dependency this avoids.

The text measurer is the one place the two sides meet before painting: the
engine wraps and truncates text by widths, and the browser measures them with
its canvas. Here the Rust side measures them with the same shaper that draws
them (`WasmTextMeasurer`), so layout and glyphs agree to the pixel, and no
canvas is needed.

### The Rust side

`packages/raster/crate` is a small `cdylib` with a plain C ABI (no
wasm-bindgen: the host allocates a buffer, writes its input, calls, reads
the result), 1.37 MB as `raster.wasm` after wasm-opt (540 KB gzipped). It is
built with WebAssembly SIMD (`simd128`, which Node, the browsers and
Cloudflare Workers all run; `packages/raster/.cargo/config.toml`), so
tiny-skia's pipeline, the PNG encoder's checksum and deflate, and the
blend loops work on vectors. It is built on:

- [tiny-skia](https://github.com/linebender/tiny-skia): a CPU port of Skia's
  rasterizer in pure Rust. Paths, anti-aliasing, strokes with dashes, clip
  masks, linear and radial gradients, PNG in and out. Small, proven (resvg
  draws SVG with it), and it compiles to `wasm32-unknown-unknown` with no
  system dependencies.
- [rustybuzz](https://github.com/harfbuzz/rustybuzz): HarfBuzz ported to
  Rust, so text is shaped (kerning, ligatures, tabular figures) as Chromium
  shapes it. Glyph outlines come from ttf-parser and are filled as paths.
- svgtypes for path data. Nothing parses JSON: the display list crosses the
  boundary in a binary encoding of its own (below).

What the display list has (`crate/src/dl.rs`): rounded rectangles with
per-corner radii, SVG paths under a matrix, text at a baseline, clips to a
rounded rectangle or to an SVG path, opacity
layers, fills with colors and linear, radial and conic gradients (the conic
one is drawn by hand, tiny-skia has no sweep shader), box shadows (a gaussian
blur of the shape's alpha, three box blurs) and a layer's drop-shadows (CSS
`filter: drop-shadow()`, of the layer's alpha: a `.shadow` around a box that
clips, masks or composites falls under that box whole, as the page casts it,
rather than on each view inside), strokes inside or centered,
dashes, and `backdrop-filter`-style blurs of what is under a shape (for
Liquid Glass). It also compares two PNGs (`sb_diff`), so a fidelity check
needs no browser either.

A layer can carry effects (`crate/src/effects.rs`): a CSS `mix-blend-mode`
(the W3C Compositing formulas, separable and not, on premultiplied colour,
plus `plus-lighter` and WebKit's `plus-darker`), a `filter: blur()`, colour
filters as feColorMatrix matrices on unpremultiplied colour (what CSS's
`grayscale()`, `sepia()`, `hue-rotate()` and the rest reduce to), a
`mask-image` (a paint's alpha over a rectangle) and a projective warp (a
CSS 3D rotation flattened to the screen, resampled bilinearly). Its content
is drawn with no clip, so it is whole before the effects; at its `restore`
it is blurred, filtered, masked and warped, in that order, over the region
it covers by then (grown by three standard deviations for the blur, mapped
for the warp), and composited through the clip it opened under. The mask
and the warp are in the CSS px of the transform the layer opened under. A
plain opacity layer is drawn as before.

Alternatives weighed for drawing: **vello_cpu** (Linebender's newer CPU
renderer with sparse strips: faster on large canvases, with a GPU sibling,
but young and its text story is parley, a bigger dependency); **resvg**
(render an SVG document instead of a display list: it draws everything above
and more, but text needs fontdb and the painter would be building SVG strings
to parse again); **skia-safe** (real Skia: a C++ build and no easy wasm). For
text, **cosmic-text** or **parley + swash** do font fallback, bidi and emoji;
rustybuzz alone is enough for the Latin UI text the examples have, with a
per-character fallback to a second face for what the first lacks. The next
script or emoji that matters is the point to move up.

### Fonts

Nothing comes from the system: the host hands fonts in by role (`system`,
`rounded`, `monospaced`, `serif`, `fallback`). The package ships Inter (every
weight from Thin to Black, the italics from Regular to Bold; OFL), Liberation
Serif (four styles; OFL) and DejaVu Sans Mono and Sans (`fonts/LICENSE.md`),
about 11 MB. Inter is not an accident: the web renderer's font stack falls back to
Inter where SF Pro is absent, which is what Playwright's Chromium on Linux
draws, so a screenshot from this renderer and one from CI's browser use the
same face and can be compared pixel for pixel. Liberation Serif is the same
reasoning for `.fontDesign(.serif)`: the stack ends in "Times New Roman", and
Chromium on Linux accepts only metric-compatible aliases for a named family,
so it draws Liberation Serif (not the system's default serif). A host that has
SF Pro (a Mac) can load it instead and get the iOS look.

A face is chosen by role, weight and slant: the text op's role byte carries
italic in its high bit (a rich run's `italic`, a view's `.italic()`), which
picks the role's italic faces and falls back to its upright ones. The layout
engine measures an italic run in the italic face, as the browser does.

### The painter

`paint.ts` walks the tree in DOM order and mirrors `Web/src/layoutDom.ts` and
`styles.css` rule by rule, each with the rule it mirrors named in a comment:
list cards, separators from the row's first text, the 63 × 28 switch and its
37 × 24 knob, iOS 26's glass capsules under bar items, the tab bar's 31-radius
glass and its 27-radius selected item, segmented pickers, steppers, sliders,
sheets, alerts, edit-mode controls. Symbols are the web renderer's icons
(`Web/src/symbols.ts`: open-symbols, one filled path each), drawn as path
data; the Node entry registers the whole set, `dist/session.js` carries it
(9.6 MB of its 10, for the CLI and the window, which run any app),
`scripts/session.mjs --content <dir>` writes a session with only the icons
an app's sources name (the plugin's, 761 KB for Codon), and `dist/index.js`
draws what its host registers (`registerSymbols`).

The rest of the vocabulary reuses the web renderer's DOM-free pieces where it
has them: charts are drawn from `Web/src/layout/chart.ts`'s geometry (the
marks, grid, ticks, axis labels and legend that `chartDom.ts` builds as SVG),
custom shapes from their path data (`affinePathData` for a path for any size),
a Canvas from its recorded commands (each command's opacity, blend mode,
filters and path clips around it, in the canvas's own coordinates), circular
gauges as `gaugeRing.ts`'s arcs. Every glass surface gets the 1 pt rim (an
even-odd ring filled with the conic `--sb-glass-rim`), and its backdrop the
`saturate(180%)` after the blur. The search field (the bottom glass capsule or
the gray one under a tab view's title), the text editor, a vertical text field,
the compact date picker, the disclosure chevron, pinned section headers and
footers (`pinnedViews.ts`'s offsets), the top and bottom scroll edge effects
(their fade times their mask, folded into one gradient), and rich text (each
run's color, link tint, background, kerning, baseline offset, underline and
strikethrough, inline symbols) follow their stylesheet rules the same way.

A style's effects are one layer (`effectsLayer`), as the page composites
them: `.blur`, the colour filters (`filters.ts`: the Filter Effects spec's
matrices for brightness, contrast, saturation, grayscale, hue rotation and
invert, after `.colorMultiply`), `.mask` (the style's gradient or alpha),
`.blendMode` and `.rotation3DEffect`, whose CSS transform
(`translate rotate perspective rotate3d scale` about the anchor) is flattened
onto the z = 0 plane as a homography the rasterizer warps the layer by
(`styleWarp`). A shape's `.trim` is a conic mask on its layer.

Text placement was measured against Chromium rather than assumed, and the
rules are small but easy to get wrong:

- a `text` element's first line is trimmed to its cap height and the
  capitals put 0.2476 em below the top (`text-box: trim-start cap alphabetic`
  with `--sb-cap-inset`, the stylesheet's way of landing text where SwiftUI
  does whatever the font); the baseline is therefore top + 0.2476 em + the
  font's cap height, exactly, no rounding;
- a line box (a title, a tab's label, a segment) puts the baseline at the
  ascent floored to whole CSS px plus the half-leading floored, with the
  descent ceiled when computing that leading;
- every baseline is then snapped to a whole CSS px, a half rounding down.

With those, the body text of the typography screen lands on the same device
pixel as the browser's, and the remaining differences are anti-aliasing at
glyph edges.

## How close it is

`scripts/raster-compare.mjs` draws each screen of the React Fidelity app
(`packages/react/demo/fidelity`, the same screens `Examples/Fidelity` has in
Swift) twice: in Playwright's Chromium through the web renderer, in the
page's iPhone frame at 3× with the status bar and home indicator hidden, and
in this renderer from the ops the same React tree emits in Node. The share
of pixels differing by more than 32/255 in a channel (the iOS comparison's
measure, CONTRIBUTING.md "Comparing with iOS"):

| Screen | Light | Dark |
|--------|-------|------|
| list | 0.13% | 0.17% |
| detail | 0.21% | 0.21% |
| form | 0.05% | 0.29% |
| controls | 0.11% | 0.14% |
| typography | 0.03% | 0.08% |
| shapes | 0.19% | 0.21% |
| layout | 0.07% | 0.10% |
| tabs | 0.43% | 0.48% |
| sheet | 0.12% | 0.13% |
| alert | 0.27% | 0.25% |
| search | 0.27% | 0.29% |
| post | 0.23% | 0.28% |
| settings | 0.05% | 0.08% |
| reorder | 0.19% | 0.22% |
| backswipe | 0.03% | 0.09% |
| topbarsegmented | 0.07% | 0.09% |
| more | 0.20% | 0.23% |
| extras | 0.34% | 0.38% |
| splitback | 0.85% | 0.85% |

`more` and `extras` are React-only screens (not in `Examples/Fidelity/screens.txt`, so name them with `--screens`):
custom shapes, circular gauges, blur, grayscale, a 3D rotation, a Canvas clock, compact date pickers, a text editor
and, below the first screen, an `AsyncImage` and two charts (`--script` with `scroll 1300` shows them: 0.16% and
0.19% scrolled there, from 13% before images were drawn). The photo is an SVG `data:` URL, which the rasterizer does
not decode; the comparison has the browser draw it at 3× into a PNG for the session (`loadImages`' `load` option).

`rowbackgrounds` is a third React-only screen: list rows with a `listRowBackground` of their own, a clear one among
them, which is how an app draws a search field of its own at the top of a list (a rounded field in a clear row). The
painter used to paint the card under every row and clip to its corners whatever the rows said, so such a field sat in
a white capsule that cut its corners; it now follows the stylesheet's two rules (a card with such a row leaves the
cell paint to its rows, and a card of clear rows alone clips nothing). The measure above could not have said so: the
card on the grouped background is 13/255 away in the light appearance and 30/255 in the dark one, under the 32/255 a
pixel must differ by to count, so the screen read the same before the fix as after. What it did show there (0.6%) was
the browser's own, and is mended on the page: a `Text` that is itself a list row was drawn 4.2 px (the cap inset,
0.2476 em) higher than one inside a styled row, because the row's inline padding (`layoutDom.ts` `padIntoFrame`)
replaced the stylesheet's `padding-top: var(--sb-cap-inset)` on the text; the padding now has the inset on top of it
(`--sb-cap-pad`), and the screen compares at 0.02% (0.04% dark). The comparison's own session was not handed the
app's custom `Layout`s (`layoutRules`), so `extras`, whose flow layout is one, read 7% for a while; with them it is
0.20% (0.24% dark).

What remains is glyph edges and the soft edges of shadows, and three places where the browser is the one that is
off: the page sets its font family on the renderer's own elements only, so an `<input>`'s text (a search field's, a
date picker's) and a Canvas's SVG text fall back to the browser's serif, where this renderer draws the system face;
and the stylesheet's rule hiding the separators beside a selected list row (`[data-sb-selected]`) also matches a
picker, which carries its selected index in the same attribute, so the browser drops the separators around picker
rows (the dark form's 0.29%: invisible in the light one, where a separator is within the comparison's threshold).
Two rules were learnt from the numbers: a glyph's subpixel position is rounded to the nearest quarter pixel
(Skia's positioning; flooring it doubled the text screens' difference), and a `backdrop-filter` blur samples only
the pixels under the element, with its edges continued outward, not the surroundings (the floating sheet's glass
card was 9% off while the dimmed list around it bled into the blur). Underlines were measured too: Chromium puts the
line's top half its thickness (at least a point) below the snapped baseline, not where the font's `post` table says,
and strikes it through a third of the ascent up.
All thirteen Swift examples' headless
snapshots (`Examples/*/__snapshots__/*.jsonl`) draw without error in both
appearances; nothing compares those with a browser yet, as that needs the
Swift modules built.

### The display list's encoding, and where the time goes

The first version sent the display list as JSON and parsed it with serde.
Replacing that with a binary encoding (`src/encode.ts` writes it,
`crate/src/bin.rs` reads it: little-endian, a tag byte per op, a presence
byte before every optional part, a count before every list, strings as a
length and UTF-8) took serde and serde_json out of the module, which went
from 1.52 to 1.38 MB before wasm-opt. The header is `SBDL`, a version byte
(4: layers grew drop-shadows; 3: images; 2: layers grew effects and clips grew paths), the size, scale,
background and op count; then the ops:

| Tag | Op | Fields |
| --- | --- | --- |
| 1 | rect | x, y, w, h f32; radius; fill paint; stroke; shadows; backdrop blur f32 |
| 2 | path | d string; matrix (presence + 6 f32); fill paint; stroke; even-odd bool; shadows |
| 3 | text | x, y, size f32; weight u16; role u8; fill paint; spacing f32; tabular bool; text string |
| 4 | clip | x, y, w, h f32; radius |
| 5 | layer | opacity f32; flags u8 (1 blend, 2 blur, 4 filters, 8 mask, 16 warp, 32 drop-shadows), then the flagged fields in that order: blend index u8; blur f32; filters (count u8, 20 f32 each); mask (paint, then x, y, w, h f32); warp (9 f32); drop-shadows (as a rect's shadows) |
| 6 | restore | |
| 7 | transform | 6 f32 |
| 8 | clip path | d string; matrix (presence + 6 f32); even-odd bool |
| 9 | image | key string; x, y, w, h f32; opacity f32; flags u8 (1 source rectangle, 2 nearest neighbour, 4 tint), then the flagged fields: source x, y, w, h f32; tint rgba |

A paint is a tag byte (0 none, 1 color, 2 linear, 3 radial, 4 conic) and
its fields. A screen's list is 10 to 16 KB either
way, and parsing it was never where the time went: drawing a screen took
80 to 160 ms, and a profile (Node's `--cpu-prof` on an unstripped build)
put it in the canvas, not the list. At 3× the canvas is three million
pixels, and the first drawing code touched all of them too often:

- a clip built its mask by intersecting a full-size mask, pixel by pixel,
  and a fill under a clip walked the whole shape through the mask: a
  background under a scroll view's clip cost 10 ms. Now a clip's mask is
  rasterized over the clipped shape's bounds, a run of plain rectangular
  clips keeps no mask at all (its bounds are the clip), and a rectangle in
  one color on whole pixels is written row by row;
- an opacity layer composited a full-size pixmap through tiny-skia's
  pipeline, 100 ms each; now it composites what was drawn into it;
- a shadow or a glass backdrop blurred its region at full resolution in
  floating point; now a wide blur runs on the region averaged down by up to
  8× and sampled back up, in fixed point, and a backdrop blur samples back
  only the pixels inside the shape;
- every glyph was filled as a path on every screen; now a glyph is
  rasterized once per size and quarter-pixel offset into a small alpha
  bitmap kept with the fonts, and blended from there, and a shaped line is
  kept too (the layout engine measures it, then the painter draws it).

With those, the list screen drew in 30 ms and the tab view in 41 ms (from
86 and 163), layout and PNG included, after the module and fonts are loaded
once (25 ms). WebAssembly SIMD took a further third off: 19 ms and 32 ms,
with the PNG encoding (the fast deflate level over 12 MB of pixels) down
from 12 to 4 ms, a glass capsule's shadow and backdrop blur halved, and
text a third faster. What remains is spread over blends, blurs and
tiny-skia's rasterizing; the one full-canvas cost left is an opacity
layer (27 ms, an allocation and a composite of three million pixels).

### Painting only what changed

A screenshot is one frame; a live editor (docs/notes/plugins.md, "Measured: a knob dragged") wants one every 16 ms,
and a knob drag changes a few thousand pixels of four million. The rasterizer now keeps a **frame** between
renders (`crate/src/frame.rs`): the last display list's pixels, and for each of its ops a token and its device
bounds. A new list is compared with the last op by op, as bytes (the ops' records in the binary encoding, which
the painter rebuilds every frame anyway): an op's token is the hash of its bytes mixed with the hash of every
`transform`, `clip` and `layer` open around it, so an op that moved with its transform or whose clip changed
counts as changed although its own bytes did not; inside an effects layer every op also carries the hash of the
whole layer, since its blur or warp mixes them; an `image` op carries the generation of the picture under its
key, so a shader redrawn under the same key is a change. Myers's diff of the two token sequences (after the common
prefix and suffix; a list more than a thousand edits away is painted whole) says which ops went and which came,
and the **damage** is the union of their bounds, merged into at most eight rectangles. The bounds are estimated
before anything is drawn, conservatively and the same way for both lists: a rectangle's with its stroke and the
reach of each shadow (three standard deviations of its blur), a path's, a text's line box, an image's, all under
the transform and inside the clips in force; an effects layer's content takes the region its composite covers
(the content grown by the blur, the whole canvas under a warp). A glass surface reads the pixels under it, so a
damaged area under a `backdrop` blur damages the surface whole, to a fixed point.

The repaint then draws the new list's ops that meet the damage, skipping a `clip`, `layer` or `transform` block
whole when nothing in it does, into a scratch pixmap whose damaged rectangles were reset to the background, and
copies those rectangles into the kept frame. Two rules make a repainted pixel the same, to the bit, as a whole
paint's. Every pixel write of the rasterizer's own loops (the local blends, glyphs, conic fills, the plain layer
and effects composites, a backdrop's write) is held to the damage, but nothing that is read is: a backdrop reads
its whole region (inside the damage by the fixed point), an effects layer's content is drawn whole and unheld so
its blur and warp see all of it, and tiny-skia's fills run as they would for the whole frame. And shapes are not
rasterized over their own bounds any more but over a grid of 256-pixel **tiles** fixed to the canvas (a shape
small enough to lie in one tile and clipped by nothing is still filled in place), the same tiles in a whole paint
and a repaint, so a repaint can leave out the tiles outside the damage and the others are the same calls, with
the same translation, on pixmaps of the same geometry; a clip's coverage mask is built the same way, only over
the tiles the damage meets, since nothing reads it elsewhere. Layer pixmaps, clip masks and the tile buffer are
pooled across frames and zeroed only where they were written, which also takes the "one full-canvas cost left",
the opacity layer's allocation, out of the whole paint. `test/damage.test.tsx` draws the Fidelity screens both
ways through a slider drag, a scroll under the glass bar, a tap, a pop, dark mode and the effects screens and
requires the PNGs to be identical; the crate's tests do the same for shadows, transforms, clips, opacity and blur
layers, and a change under glass.

A host gets it through `session.render({ mode: 'frame' })` (`Raster.renderFrame`, `sb_frame_render`): the
damaged rectangles in device pixels and the frame's premultiplied pixels, a view into the module's memory, for
a window to blit; `render()` keeps drawing a whole PNG. `swiftbrowser-shot` paints each `shot` into the frame and
says what it repainted (`--full-paint` for the old behaviour; `SB_PAINT_TRACE=1`, `2` or `3` prints the stages,
every op drawn, and the phases of the slow ones). Measured with `scripts/knob-bench.sh` (Codon's bundle at
1194 × 834 points, 2×, the OSC A level knob dragged ten steps; the shared Xeon VM, best and worst of five):

| Per shot, native CLI | Display list (QuickJS) | Paint | PNG |
|---|---|---|---|
| The screen, whole | 230–260 ms | 136–171 ms | 17–26 ms |
| A knob frame, whole (`--full-paint`) | 30–53 ms | 134–250 ms | 17–24 ms |
| A knob frame, what changed (1 rectangle, 24,552 px, 0.62% of the frame) | 29–36 ms | **8.2–9.3 ms** | 18–24 ms |
| The knob dragged back to where it was (nothing changed) | 29–43 ms | 0.4–0.6 ms | 17–24 ms |

The paint of a knob frame is under the budget; of its 8 to 9 ms, about two are the OSC panel's gradient fill and
inside stroke on the tiles the damage touches, and the rest the knobs around the dragged one, whose blurred
shadows and masked layers overlap its bounds and are drawn again. What stood between a knob and a 16 ms frame
then was the display list (the painter walked the whole tree in QuickJS; now incremental, below) and the PNG, which
a window does not need. Found on the way: the
session's hit test tried a `.background { }` decoration before the content over it (the painter draws them the
other way), so every point of Codon hit its full-window background Color and a drag moved nothing; the
shared `paintOrder` now puts the decoration first for both.

### An incremental display list

The display list was built whole every frame: the painter walked all 2,905 of Codon's nodes to emit 890 ops,
22 to 34 ms in QuickJS, and the encoder wrote the 40 KB of their bytes field by field through a `DataView`, another
6 to 11 ms, together more than the paint of what changed. The painter now keeps each node's ops across frames
(`DisplayCache`, owned by the session): when a node is walked, the ops its walk emitted are kept as a slice of their
own with the context (the colors, list and bar state an ancestor set), the scroll shift and, for a scroll view, its
own offset they were drawn under; the next frame reuses the slice when nothing under the node changed and it is
drawn under the same context, shift and offset, and walks the node afresh otherwise. What counts as a change the
session says, since it already knows: an op that updates, inserts or removes a node marks it and its ancestors
stale (the tree's observer, which tells the layout pass the same), a layout run marks the nodes it placed or hid
(`LayoutResult.changed`), and a scroll offset, the focused field or the swiped row that moved since the last frame
marks the scroll view, the field or the row; an image that loads or an environment change clears the cache, since
any node may draw differently. A search field reads its sibling's scroll offset and is never reused. The encoder
keeps each op's bytes with the op (ops are never changed once emitted), so a reused op is a copy of its record, and
a drawn shader is kept by its content as well as by its props object, so a page shown again does not run its
wavetable shaders again. A context that changes under a reused node (a foreground set above it) is caught by the
comparison, as a changed shift is; and a `styled` box with hierarchical foreground levels no longer writes them into
its parent's hierarchy, which is what CSS variables do too.

The ops are the same: `test/incremental.test.tsx` compares the incremental list with a fresh walk of the whole tree,
op for op and byte for byte, through a slider drag, scrolls (a large title collapsing and coming back), tab
changes, a push and a pop, a field focused and typed into, a swipe open and closed, sheets, alerts and dark mode;
the pixel comparisons with Chromium (at rest, scrolled 200 points, tapped into a detail) and the damage painter's
identity tests are unchanged, and Codon's screenshots through the knob drags and page changes are byte for byte
what they were. `session.displayList({ incremental: false })` walks everything (`incrementalPaint: false` for every
frame), `paintStats` says what a frame reused, and `swiftbrowser-shot --verbose` prints the painter's walk and the
encoding apart, with the subtrees reused and nodes walked.

Measured on the shared Xeon VM (Codon at 1194 × 834 points, 2×; the native CLI; three runs):

| Per shot, QuickJS | Display list, before | After | Paint |
|---|---|---|---|
| A knob frame (4 ops, 47 nodes placed) | 28–45 ms (890 ops walked whole, 6–11 of it encoding) | **2.2–3.2 ms** (45 nodes walked, 26 subtrees reused; 0.8–1.3 encoding) | 7.5–12.3 ms (1 rectangle, 0.62%) |
| A page changed (FX: a new subtree of 1,872 nodes) | 33–52 ms | 39–55 ms (10 subtrees reused) | 163–252 ms, whole |
| Back to the OSC page (two wavetable shaders) | 243–308 ms (the shaders drawn again) | 32–50 ms (their pictures kept by content) | 124–200 ms, whole |
| The panel scrolled 120 points (1194 × 640, where it overflows) | 30–46 ms | 34–47 ms (the scrolled content's shift changed under all of it) | 113–224 ms, whole |

A scroll still walks what scrolled, since every op under the scroll view moves; shifting the kept ops by the delta
instead would make it a few milliseconds, and the paint of a scrolled frame is the whole viewport either way until
the rasterizer blits what moved. A page change is a new subtree, and costs what it costs to walk; its layout
(645–861 ms in QuickJS for the FX page) and whole-frame paint are the larger parts of it.
### A desktop window

The frame mode above is what a window blits. `swiftbrowser-window`
(`packages/raster/window`) is the same host and session as the screenshot
CLI, a library they now share, run in a native window: the bundle in
QuickJS on the wall clock, the session's frame blitted to the window with
only its damaged rectangles touched, and the OS's mouse and keyboard fed
to the session one event at a time. It is the in-memory renderer as a
desktop UI, which is the editor a CLAP or VST3 plugin draws
(docs/notes/plugins.md): a window a plugin host hands over through CLAP's
`gui` extension (an HWND, an NSView or an X11 window) takes the same code
as a standalone window, `Window::embedded(parent)` beside
`Window::standalone()`, and `examples/embed.rs` embeds it in a plain
parent window on each platform.

The engine runs on a thread of its own, because QuickJS values must stay
on one thread and React and the layout engine recurse deeper than a main
thread's stack allows; the window thread only translates events and
blits. Each turn the engine waits for an input, the next timer or a
network answer, takes every command queued (pointer moves coalesced to
the last, as a browser coalesces them), hands each to the session, settles
the engine, and, when the session's revision moved, paints: the display
list, the kept frame repainted where it changed, the damaged rectangles
copied into the pixels the window shares, which it then blits with
`present_with_damage`. The window asks the session for a frame only when
something changed, so a still screen costs nothing.

The input is the session's own, as a script's taps and drags are
(`src/pointer.ts`): a press that lifts within the slop is a tap at the
pressed point, one that moves past it is the drag the session's `drag`
would make of the same two points, by the same priorities (a grip
reorders, a drag gesture gets `began`, `changed` per move and `ended`
with a measured velocity, a slider or a knob follows the pointer, a
swipeable row follows and settles, a sheet or the back edge settles at
the release, else the scroll view under the press pans); a move with
nothing pressed hovers where the app asks (`.onHover`,
`.onContinuousHover`) and sets the window's cursor (`.pointerStyle`, the
I-beam over a text field); the wheel and trackpad scroll what is under
the pointer; keys and typed text, Escape, Return, Backspace, select-all
and the clipboard reach the focused field; resizing the window relays out
the tree (the session's environment-change path). A `ScopeView` draws a
flat trace as the CLI does, with the hook where a plugin host hands it
the engine's frames.

Measured with a synthesized knob drag (`--drag`, which plays pointer
events in as the OS would, and `--stats`, a line a frame): Codon's
bundle in a 1194 × 834-point window at 2×, the OSC A level knob held and
wiggled so every move turns it, on the shared Xeon VM (Linux, software
rendering under Xvfb), with the incremental display list and the React
host's partial flush of the renderer-speed stream merged. A frame only
repaints the knob (one rectangle, 24,552 pixels):

| Per frame (median / p90) | Damage repaint | Whole frame (`--full-paint`) |
|---|---|---|
| The app's JavaScript (a knob event, React's render and commit) | 2.9 / 4.0 ms | 3.6 / 4.9 ms |
| Layout (what the commit changed) | 5.9 / 8.8 ms | 6.1 / 8.4 ms |
| The display list (the painter, incremental) | 2.1 / 3.3 ms | 2.3 / 3.2 ms |
| Paint (the rasterizer) | 6.9 / 9.9 ms | 141 / 163 ms |
| Copy and blit | under 0.1 ms | 7 ms |
| The engine's turn | 19.7 / 26.8 ms | 159 / 190 ms |
| From the pointer move to the blit | **20.5 / 35.2 ms** | 318 / 386 ms |
| Frames a second | **41** | 6.1 |

A knob frame is at the budget: a pointer move reaches the screen in about
20 ms, 41 frames a second against the 60 the events arrive at, and the
pixels on screen are the frame mode's, so they are the screenshot's to
the bit. On the CI runner (`ubuntu-latest`, a faster machine than the
shared VM; the job writes its run to the step summary) the same drag runs
at the input's own rate, 67 frames a second with a 12 ms median from the
move to the blit (engine turn 11 ms: app 2, layout 3.5, display list
1.4, paint 4). Painting only the damage is what makes it possible, 7 ms against
141 for the whole frame; with the display list and the app's own work
down to a few ms each (the renderer-speed stream's incremental display
list and the host's partial flush, measured before they merged at 25 and
23 ms), the two largest pieces left are the rasterizer's repaint of the
knob (7 ms: the knobs beside it whose shadows and masked layers overlap
its bounds, docs above) and the layout of what the commit changed (6 ms),
which are now the window's own to shorten. Before the merge the same
drag ran at 15 frames a second with a 130 ms input-to-blit median, the
engine's 60 ms turn queueing several inputs behind each frame; the
coalescing is still there for when a frame runs long.

## Images

Remote images (`AsyncImage`, a Swift `image` request), catalog images and
bitmaps (`Image(uiImage:)` recipes over `imagedata` sources) are drawn by
the display list's `image` op (tag 9 below): an image registered with the
rasterizer once by key (`sb_add_image` decodes a PNG, a JPEG with its EXIF
orientation applied, a GIF's first frame, WebP where the build has it;
`sb_add_image_rgba` takes pixels), drawn into a rectangle under the
transform and clip, optionally from a source rectangle, at an opacity,
tinted (a template), and sampled by the nearest pixel
(`.interpolation(.none)`) or bilinearly from the full image or, drawn at
half its size or less, from a box-filtered halving (as browsers use
mipmaps). The decoders add 110 KB to the module (JPEG 78 KB, GIF 32 KB).

Loading is the host's and the session stays synchronous
(`src/images.ts`). The session collects what the app needs (a URL in an
`image` element, a rich text run or a Canvas command; a catalog image's
file from the manifest given as `assets`; a Swift `image` request op) and
lists it (`session.pendingImages()`); the host loads it and hands the bytes
back (`session.provideImage(key, bytes | { error }, { scale })`), which
answers the request with the page's `response` (the pixel size, or the
error) and fires the `load` of the `Image` a React `AsyncImage` made, so it
re-renders with the picture. Until then an image draws nothing, as the page
shows nothing until loaded. `imagedata` sources come with their bytes and
are decoded when first drawn. In Node, `installImage(session)` gives React
an `Image` over the session and `loadImages(session, { assets })` loads
URLs with `fetch`, `data:` and `file:` URLs and catalog files from disk.
The CLI loads remote images through the app's own network (fixtures win,
`--offline` fails the rest, `wait` waits for them), implements the native
bridge's `probeImage` so `AsyncImage` behaves as on the page, and reads a
built catalog with `--assets catalog/<App>` (the manifest is
`catalog/<App>.json` beside it).

The painter follows `applyImage` and styles.css: the picture fills the
element's frame (`object-fit: fill`; fitting is the layout engine's), a
catalog name the manifest lacks is the dashed box, an inline bitmap or
remote image in rich text stands on the baseline (a catalog one on the
text's bottom). A recipe of geometry and tints is drawn as
`Web/src/bitmapPlan.ts` plans it (the source in one drawing, clipped to the
output and its rounded rectangles, tinted); one with filters runs
`Web/src/imageOps.ts` at the page's working scale and is kept as an image
of its own.

## Registered views

A `registered` element (`RegisteredView` in React, a package's view that the page draws with a builder from
`ViewRegistry`) is drawn here by a **drawer** registered under the same name (`src/registered.ts`,
`registerDrawer`): the element's props and box in, display ops out, clipped to the box. Two ship:

- **`ShaderView`** (@swiftbrowser/shader). Its box, in device pixels, is drawn by the first **shader backend**
  that can (`src/shaders.ts`); the result is an image (`addImagePixels`) drawn 1:1, kept until the props or the
  size change. Every backend draws what the page draws, each pixel at its center in points from the top left
  (`drawJS`'s rule), and is held to the shader package's render fixtures. A host installs the GPU it has in front
  (`installShaderBackend`): `createWebGLShaderBackend()` draws the shader's GLSL with WebGL2 in a page or a worker
  (an `OffscreenCanvas`) as the page's own view does, and `swiftbrowser-shot` built with its `gpu` feature
  installs wgpu, drawing the shader's WGSL on whatever adapter there is (Metal, Vulkan, DX12, GL; lavapipe where
  there is no GPU), or declining without one (`--no-gpu` turns it off). Behind those come the built-in ones: the
  rasterizer's interpreter of the shader's **bytecode** (`crate/src/shader.rs`; the compiler's fourth output,
  `packages/shader/src/bytecode.ts`), sixteen pixels at once under execution masks, in f32 as a GPU computes,
  across the cores natively and SIMD in wasm; and last the shader's JavaScript, the page's fallback without WebGL2.
  A native host's `ShaderView` sends only Metal; the CLI sets `__sbHeadless` before the app runs, which makes it
  send what the headless backends run instead (JavaScript, bytecode, WGSL). Time stands at 0, so an animated view
  shows its first frame.
- **`ScopeView`** (@swiftbrowser/dsp) draws what the audio thread produces; there is none here, so it is the flat
  1.5 pt trace a silent node shows, in its color or the app's accent.

Codon's wavetable display is a heavy shader (it marches 128 steps a pixel). One display at 2× (744 × 204
pixels), and the CLI's whole Codon screen (1194 × 834 at 2×, two displays):

| Backend | One display | Codon's screen in the CLI |
|---------|-------------|--------------------------------|
| JavaScript, Node (V8) | 1.8–2 s | |
| JavaScript, QuickJS (the CLI) | about 75 s | 152 s |
| Bytecode, wasm in Node | 295 ms | |
| Bytecode, native (the CLI, 4 cores) | 61–64 ms | 1.4 s |
| WebGL2, Chromium on SwiftShader (software) | 355 ms | |
| wgpu, the CLI on lavapipe (software Vulkan) | 69 ms warm, 167 ms first | 1.4 s |

The bytecode draws the render fixtures exactly as the JavaScript does (every channel), and the GPUs within the
page's WebGL2 tolerance; the CLI's Codon screen drawn by wgpu and by the bytecode differs by at most one
step a channel. A real GPU is faster still; on a machine without one, the bytecode is the fast path, and it is
the only one where `new Function` is forbidden (Cloudflare Workers). The bytecode adds 52 KB to the module; the
`gpu` feature adds about 5 MB to the CLI and is off by default.

## Driving an app

A screenshot of a first screen is half of what an agent needs; the other
half is using the app: tapping a row, typing into a field, scrolling a
list, dragging a slider, and seeing the result. The web renderer does all
of that with the DOM (hit-testing by `pointer-events`, scrolling by
`scrollTop`, focus by the browser) and its scripts. A **session**
(`packages/raster/src/session.ts`) does it over the element tree and the
layout result instead, so it needs no browser either.

- **The state the page keeps.** Every scroll view's offset, clamped to its
  content plus the bottom inset (the same rule as `layoutDom.ts`); the
  focused text input; and the commands Swift and React send at commit,
  carried out once per serial as the renderer does: `scrollTo`,
  `scrollOffset`, `defaultScrollAnchor`, `focused` props. After each pass
  the session reports `geometry`, `layout` and `scrollgeometry` events, and
  after a scroll `scrollposition`, `scrollvisibility` and `lazy`, through
  the renderer's own pure helpers (`Web/src/scroll*.ts`).
- **Hit-testing** (`hit.ts`) follows the stylesheet's `pointer-events`
  rules: content and controls are hit, the empty space of stacks and
  boxes is not; hidden, disabled and `hitTesting: false` subtrees take
  nothing; clips and scroll offsets apply; a transformed box is hit where
  it is drawn (the point is taken through the inverse matrix). A hit
  becomes the event the page would send: a button or link tap, a toggle
  at its switch, a stepper half, a segment, a tab, a slider value, the
  back circle, a sheet's scrim, an alert's OK, a list row's single button.
- **Selectors** (`selectors.ts`) are the headless Swift replay's: `"text"`,
  `[kind]`, `@id`, `#n` among several, searched only on screen (the top
  sheet or alert, else each stack's top screen and the selected tab), the
  event going to the nearest ancestor of the match that takes it. A
  selector that matches nothing, or several without `#n`, is an error.
- **Drags** follow the page's priorities: a movable row's grip reorders
  (`move`), a `gesture` gets `drag` events past its minimum distance, a
  slider slides, a sheet dragged down 100 points dismisses, a drag from
  the left edge past a third of the width goes back, and anything else
  scrolls the view under it, snapping for paging views.
- **Popover menus** (`menus.ts`): a tap on a `Menu` or a menu-style
  `Picker` opens its popover as the renderer builds it (a picker's options
  as checked rows; a menu's buttons, toggles, pickers, sections and
  dividers as rows, captions and hairlines; a nested menu as a submenu row
  with a chevron; a lazy menu asking for its items first) and places it the
  same way: trailing edges aligned with the control's box (a list row's
  whole row), 4 below it or above it, inside the screen. A tap on a row
  chooses it (`tap`, `toggle` or `select`); a tap on a submenu row opens
  its panel over the menu's, its header row over the submenu row, the
  menu's panel pushed back behind it (scaled, dimmed), and a tap on the
  header or on that panel brings it back; a tap anywhere else only closes
  the popover, as the page swallows it.
- **Swipe actions** (`swipes.ts`, over the renderer's `swipe.ts`): a
  horizontal drag on a list row with `swipeActions` (or a deletable row,
  whose one action is Delete) slides its content over the action buttons
  and settles open, closed, or past the full-swipe point performs the first
  action; a tap on a shown action performs it, a tap elsewhere or a scroll
  closes the row. `swipe "row" left` is the script's shorthand.
- **The painter** draws a scrolled view's content moved by its offset, the
  large title moving with the root scroller and collapsing into the bar
  past 44 points (the inline title then shows), the bar's scroll edge
  effect fading in over the first 40 points, and a caret in the focused
  field.

`scripts/raster-compare.mjs --script steps.txt` drives Playwright and a
session through the same steps (`scroll dy`, `tap "text"`, `wait ms`)
before comparing them. Scrolled 200 points, the Fidelity screens are
within 0.4% to 1% of Chromium (typography 0.83%, shapes 0.72%, layout
1.04%, controls 0.54%, form 0.39%); tapped into a book's detail screen,
0.2%. What differs more than at rest is the bar's edge effect, whose
blur and gradient approximate the page's.

### Transforms

`.offset`, `.rotationEffect` and `.scaleEffect` never reach the layout
engine (as in SwiftUI, they move what is drawn, not the frame). The
painter composes them as the page's CSS does (translate, rotate, scale,
about the rotation anchor, else the scale anchor, else the box's centre)
and emits a `transform` op; the rasterizer keeps a current matrix, under
which clips, coverage masks, shadows, backdrop blurs and conic gradients
are drawn, glyphs come from the bitmap cache only under a uniform scale
(rotated or stretched text is filled as outlines), and the rectangle fast
paths apply only while rectangles stay axis-aligned. A stack's children
are drawn in `zIndex` order. Blur, the colour filters and 3D rotations
are still not drawn.

### Incremental layout

The web renderer gets incremental layout from its own `LayoutPass`
(Web/src/layout, Phase 9): the pass lives across commits, the renderer tells
it which nodes its ops touched, and `place` returns at once for a subtree
placed before with the same proposal at the same origin and nothing
invalidated under it. The session laid the whole tree out at every commit
instead, which for a plugin-sized app is most of a frame: Codon's 2,905
nodes take about 360 ms in QuickJS. The session now keeps one pass too, told
by the tree (`OpsTree.observer`, what the web renderer's DOM pass tells its
engine): an `update` invalidates the node, its ancestors (their sizes may
change) and its descendants (their context may), by what changed
(`LayoutPass.invalidateProps`): props set to what they were invalidate
nothing, a scroll view's `scrollOffset` alone nothing (the session scrolls
after layout), and a `styled` node's style changed only in keys no child
inherits (a frame, a padding, a background; not the font, the line limit,
the text alignment, the image scale, the safe area, the list row height or
whether scrolling is off) the node and its ancestors, the children placed
again only where their proposal changes; an `insert` invalidates the
parents on both sides and the moved subtree; a `remove` drops the subtree's
output and invalidates its parent. The pass is exact: a changed child is
measured again, and so is every ancestor up to the root, since SwiftUI's
protocol lets a child's reported size change its parent's; a sibling subtree
whose proposal and origin come out the same is kept, frames, chrome and text
alike. A change to the environment (the appearance, the text size, the
focused field and its keyboard) starts a fresh pass, so is a full layout,
and `incrementalLayout: false` (the CLI's `--full-layout`) makes every
commit one, for measuring against. The tests drive a slider by drag and
structural changes (a push, a pop, a toggle, a scroll) and check the live
result against a fresh `layoutTree` of the same tree, map by map, and that
the drawn pixels agree.

A plan is kept by the part of the proposal it reads: a text's by its width alone (it wraps at the width and reads
nothing of the height), a stack's and a `styled` box's by the axes their subtree reads (`axisReadsOf`: a box's fixed
length, its child's rule, a stack's children's; a spacer, a colour or a flexible frame below makes them read the
height), and a node's placement the same way. A panel giving a band its height offers everything in it a new height;
its texts are then not wrapped again (Codon's settling commit computed 23,782 plans, 2,781 of them texts measured
through the host; now 16,665, 48 texts), nor its rigid rows planned or placed again (the open's first layout 22,694
plans → 16,466; docs/notes/memory.md, "Stream Q"). A plan's key is found by its four numbers (the
proposal's and the container's) without making its string again, which was a tenth of a layout's time under V8.

The steps after a layout (focus, scroll commands, the geometry and scroll
geometry reports) each walked the whole tree to find a handful of nodes,
about 1 ms a walk in QuickJS; the session keeps an index of the nodes they
look for (text inputs, scroll views, geometry reporters, `scrollTo`
commands) as the ops arrive, and collects the images of the nodes a commit
created or changed rather than every node's.

(Since Codon ships no program, `bench/knob.mjs` draws its sign-in and says so rather than measure; a drag on a
sound is timed under V8 by `Native/Examples/Codon/scripts/editor-memory.mjs --time`, and in the plugin by
`CODON_EDITOR_VERBOSE=1` with `examples/memory.rs --editor`: docs/notes/memory.md, "Stream E".) Measured with
`bench/knob.mjs` (`swiftbrowser-shot --verbose`, which times
each command and each commit): Codon's bundle at 1194 × 834 points at
2×, the OSC A level knob dragged ten steps up and ten down, five times, on
the shared Xeon VM. The knob's commit is four ops (the knob's own `update`
and the commit):

| A knob commit, QuickJS | Full layout (before) | Incremental (after) |
|---|---|---|
| Ops applied | 1.0 ms | 1.0 ms |
| Layout | 359 ms (2,119 nodes placed) | 5.9 ms (47 placed, 26 subtrees kept) |
| Steps after | 5.1 ms (four walks of the tree); 1.9 with the index | 1.9 ms |
| The commit | 362 ms | 9.0 ms |

A ten-step drag went from about 4.2 s to 1.4 s; what remains is the app's
own JavaScript, which re-renders its whole tree on every knob event
(docs/notes/plugins.md, "Measured: a knob dragged"), and the paint, which is
the whole frame. Both are work of their own.

### swiftbrowser-shot: a standalone CLI with a small engine

An agent's sandbox, a CI job or a worker may have no Node, and an agent
wants one call that runs an app, drives it and writes screenshots. The
layout engine and the painter are TypeScript, so any such tool needs a
JavaScript engine; the question was which. The candidates in Rust were
**Boa** (pure Rust, no C compiler, easy to cross-compile, but no JIT and
several times slower than QuickJS, still filling in the standard) and
**QuickJS** through rquickjs (QuickJS-NG: ES2020 and beyond, a megabyte,
fast to start, a C compiler at build time). React and the layout engine
are a lot of JavaScript to run per screen, so QuickJS it is
(`packages/raster/cli`, a separate crate so the engine and the HTTP
client never enter the WebAssembly build).

The QuickJS is **quickerjs** now (`github.com/noya-app/quickerjs`, v0.2.0
from its tag): QuickJS 2026 ported to Rust, with a tail-call interpreter, a
baseline JIT and an optimizing tier, and a tracing collector, embedded
through `quickerjs::embed`, rquickjs's shape without its lifetimes. It needs
the nightly that the CLI's and the window's `rust-toolchain.toml` pin (the
renderer's crate and its WebAssembly build stay on stable). The binaries
register its small block allocator (`quickerjs::alloc::SmallAlloc`) as
theirs; a plugin keeps its host's (docs/notes/plugins.md, "The engine is
quickerjs"). Codon's knob drag in the CLI (`bench/knob.mjs`) went from 57 to
61 ms a ten-step drag under QuickJS-NG through rquickjs to 10 to 12, a knob
commit from about 310 ms to 67 to 82, and start-up from 7.6 to 7.9 s to 2.4
to 2.8 (docs/history.md, "The editor's JavaScript engine is quickerjs").

The binary runs **React apps only**, bundled as SwiftBrowser Native bundles
(`swiftbrowser-native build`): the app's script starts with the runtime
that builds the web globals (timers, fetch, storage, `URL`,
`TextEncoder`…) over a host bridge, `__sbNative`. The iOS host implements
that bridge over JavaScriptCore; the CLI implements the same one over
QuickJS, so an app bundle runs unchanged. Beside it, the session script
(`dist/session.js`, an ES2020 classic script from `src/sessionEntry.ts`)
gets the rasterizer natively as `__sbRaster`. The app's ops go from
`__sbNative.applyOps` to the session; the session's events go to the
app's `__sbDispatch`, synchronously, as on iOS.

Two differences from JavaScriptCore needed care. QuickJS runs promise
jobs only when asked, so after every call into JavaScript the host
settles: it runs jobs, hands over network answers, and fires timers due
now, until nothing is left. And QuickJS has no `Intl`, which apps reach
for to format numbers and dates, so a small prelude provides US English
`NumberFormat`, `DateTimeFormat` and the `toLocale*String` methods over
them.

Time is **virtual** by default: the app's timers fire only as the script's
`wait` advances the clock, so a run is the same every time. `--real-time`
uses the wall clock. `fetch` goes out over **real HTTP** (reqwest with
rustls; the proxy and CA bundle from the environment), and a
`--responses` fixtures file wins where it matches, optionally delayed on
the app's clock so a loading state can be screenshotted; `--offline`
fails what no fixture answers. In virtual time, `wait` also waits (in
real time, up to `--net-timeout`) for requests under way, so `wait`
means "let everything finish".

Starting the Fidelity app takes about 100 ms; a screenshot takes 20 to 30
ms; and the PNG is pixel for pixel what the Node session draws for the
same tree (`test/shot.test.ts` checks it).

```sh
npx swiftbrowser-native build src/index.tsx --out app.js
cat > steps.txt <<'STEPS'
shot home
tap "Design Patterns"        # a selector, or tap 120,340
wait 600
shot detail
back
scroll 0,300
toggle "Notifications" on
env dark
shot dark
STEPS
swiftbrowser-shot app.js steps.txt --out shots --session packages/raster/dist/session.js
```

## Using it

From an agent or a script, with the examples' modules built
(`scripts/build-wasm.sh`):

```sh
# The ops of a screen, from the real app under Node's WASI, after some events.
SB_HEADLESS=1 SB_EVENTS='tap:"Add"' node scripts/run-wasi.mjs Web/public/Todos.wasm > todos.jsonl
# Drawn.
npx swiftbrowser-raster todos.jsonl --out todos.png            # --dark, --commit N, --width/--height/--scale
```

From Node:

```ts
import { createRenderer } from '@swiftbrowser/raster/node';

const renderer = await createRenderer();                        // the packaged module and fonts
const png = renderer.renderOps(ops, { colorScheme: 'dark' });   // Uint8Array
const { ratio, png: sideBySide } = renderer.raster.diff(expected, png);
```

In a browser or a Worker, where there is no file system, load the module and
the fonts yourself: `Raster.load(fetch('/raster.wasm'))`, then
`raster.addFont(bytes, 'system')` for each face, then `new Renderer(raster)`.
A `@swiftbrowser/react` app gives its ops to a `createSwiftUIRoot` sink
instead of a renderer, as `packages/react/test` does, so a React app can be
drawn headless too.

### A screenshot Worker

A host that runs an app and takes its picture (a Cloudflare Worker, a script)
has one thing to decide that a page never does: when the app is done drawing.
`@swiftbrowser/raster/headless` is that, taken out of Codon's screenshot Worker
(`codon-site/apps/shots`) so the next host does not write it again. It is the
entry's first import, before the app's modules and React's: it counts what is
asked of the event loop (timers due within two seconds, and immediates, which
is how React schedules its work outside a page), says the realm is a headless
one (`__sbHeadless`: a shader hands over its bytecode, since a Worker runs no
`new Function`) and gives it an in-memory `localStorage` where there is none.
`settle(session)` then waits until the app has drawn something, has changed
nothing since it was last looked at, and either has nothing outstanding or has
rested half a second whatever is left (a timer that sets itself again never is
done); `least` says how many nodes a drawn screen has, `until` what else must
show, `longest` when to take the screen as it stands. The app need not be in
the host's realm: a sandbox whose host runs its timers on the realm's
`setTimeout` is counted the same.

```ts
import { drain, forget, settle } from '@swiftbrowser/raster/headless';   // first
import { Raster, Session, registerSymbols } from '@swiftbrowser/raster';
import wasm from '@swiftbrowser/raster/raster.wasm';                     // a CompiledWasm rule
import inter from '@swiftbrowser/raster/fonts/Inter-Regular.otf';         // a Data rule

const raster = await Raster.load(wasm);
raster.addFont(new Uint8Array(inter), 'system');
registerSymbols(icons);                       // the icons the app names: the main entry carries none
forget();                                     // what an earlier request left asked for
const session = new Session(raster, { dispatch: (event) => app.dispatch(event) }, { screen, scale: 2 });
const app = start((ops) => session.applyOps(ops));   // the host's own way of running the app
session.start();
const { drawn } = await settle(session, { least: 50 });
const png = drawn ? session.render() : null;
app.unmount();
await drain();                                // what unmounting asked for, before the request answers
```

The package's `exports` name the module (`./raster.wasm`) and each font
(`./fonts/*`), so a bundler takes only the faces a host draws with: all of
them are 10 MB, Codon's eight are 1.4. The whole icon set is
`@swiftbrowser/web/symbols/open-symbols.json` (9.4 MB, 2 MB compressed); a
host that knows its app cuts it to the names the app's sources spell, as
Codon's build does.

## Not yet

- Host elements (the page's own DOM) draw nothing, nor does a registered view without a drawer. An animated
  shader shows its first frame; a scope shows no sound. SVG images (a remote SVG, a catalog `.symbolset`) are not
  decoded, so they draw nothing (an `AsyncImage` of one shows its failure view); WebP decodes in the CLI only (its
  decoder would add 163 KB to the module; the crate's `webp` feature); HEIC never. A Canvas draws remote and catalog
  images but not bitmaps, as the page does. Animated GIFs show their first frame (a recipe's `frame` composes others).
- A 3D rotation is drawn, but hit-testing uses only the style's 2D transform (offset, rotation, scale), not its
  perspective.
- Context menus (a long press) are not driven, nor are pinch and multi-touch. A popover menu that scrolls (taller
  than the screen) shows the part around its checked row and is not scrolled further.
- The CLI runs React apps (Native bundles) only, not Swift app modules; its
  `Intl` is US English only.
- `.rounded` text draws in Inter (as a browser without SF Pro Rounded does); a serif or monospaced italic falls back
  to the upright face where the packaged fonts have no italic (DejaVu Sans Mono), where a browser slants it.
- Font fallback is one face deep (DejaVu Sans), so emoji and non-Latin
  scripts beyond it show as missing glyphs; `monospacedDigit` is honoured,
  other OpenType features are not.
- Dynamic Type sizes and other screen sizes are options, uncompared with the browser.
- Here the Rust module is built by hand (`npm run build:wasm`, a Rust toolchain
  with the `wasm32-unknown-unknown` target; wasm-opt when Binaryen is
  installed). A release builds it and publishes the package with it
  (`.github/workflows/publish.yml`); `swiftbrowser-shot` and
  `swiftbrowser-window` are Rust binaries no release builds, so the package
  leaves out the session script they load (`dist/session.js`).
- The published package carries the code of @swiftbrowser/shader it draws a
  `ShaderView` with, and the declaration of the one module of it the
  renderer's types name (`scripts/declarations.mjs`), rather than depend on
  that package, which is a React app's (it wants @swiftbrowser/react beside
  it): a host that only draws installs @swiftbrowser/web and no more. Its
  declarations name @swiftbrowser/web's types by that package's source paths.
