@swiftbrowser/raster#
SwiftBrowser's in-memory renderer: an app's render ops drawn to a PNG with no browser, by the web renderer's own layout engine and a Rust rasterizer (tiny-skia, text shaped by rustybuzz) compiled to WebAssembly. For screenshots in agents, workers, tests and anywhere else WebAssembly runs (experimental). The design, and how close it gets to the browser, is in docs/raster.md.
npm run build:wasm # crate/ → dist/raster.wasm (cargo with `rustup target add wasm32-unknown-unknown`; wasm-opt when scripts/install-binaryen.sh has run)
# built with WebAssembly SIMD (.cargo/config.toml): every current runtime has it
npm run build # dist/index.js, dist/node.js and the declarations
npm run test:unit # the examples' snapshots drawn, the Counter's geometry, the PNG comparison
From npm#
npm install @swiftbrowser/raster
Three entries: @swiftbrowser/raster (any runtime with WebAssembly: the host
loads the module, the fonts and the icons it draws), @swiftbrowser/raster/node
(Node and Bun: loadRaster() and createRenderer() over the packaged module,
fonts and every icon) and @swiftbrowser/raster/headless (a host that runs an
app and takes its picture: what it has asked the event loop for, counted, and
settle(session), which waits for the app to be done drawing; imported first).
The module is @swiftbrowser/raster/raster.wasm and each font
@swiftbrowser/raster/fonts/<file>, for a bundler to take what a host needs.
docs/raster.md, "A screenshot Worker", has the whole of
one; codon-site/apps/shots in this repository is one that runs.
Command line#
swiftbrowser-raster <ops.jsonl | -> [--out screen.png] [--dark] [--commit N] [--width 393] [--height 852] [--scale 3]
The input is an op stream as JSON Lines: a headless snapshot
(Examples/<App>/__snapshots__/<app>.jsonl), or what an app prints under
SB_HEADLESS=1 (scripts/run-wasi.mjs, after the events in SB_EVENTS).
--commit N draws the tree as it stood after the N-th commit; without it
every op is applied. - reads stdin, --out - writes the PNG to stdout.
swiftbrowser-shot#
A standalone binary (cli/, Rust) that runs a @swiftbrowser/react app
headless in QuickJS, drives it from a script and writes screenshots: no
Node and no browser where it runs. The app is a SwiftBrowser Native
bundle, the same one an iOS app ships:
npm run build:cli # cli/target/release/swiftbrowser-shot (cargo; a C compiler for QuickJS)
npm run build # dist/session.js, the session the binary loads
npx swiftbrowser-native build src/index.tsx --out app.js
swiftbrowser-shot app.js steps.txt --out shots/ # or the steps on stdin
One command a line, # comments, words quoted as in a shell. The whole
script is checked before anything runs; a command that fails stops the
run with exit status 1 and steps.txt:<line>: <command>: <why>.
| Command | What it does |
|---|---|
shot name |
writes name.png |
tap "text", tap [kind]#2, tap @12, tap 120,340 |
taps what a selector names, or what is at a point; a menu or a menu picker opens its popover, whose rows tap "Author" then chooses (a tap anywhere else closes it) |
type "text", clear, submit |
types into, empties or submits the focused field (\n in type submits) |
focus "Email" |
focuses a text field |
toggle "Wi-Fi" on, select "Sort" "Rating", step [stepper] up, slide [slider] 0.4 |
sets a control |
scroll 0,300, scroll "Recent" 0,300, scroll 200,500 0,-100 |
scrolls the screen's scroller, the one a selector or a point is in |
drag 200,600 200,300 [steps] |
drags: reorders by a grip, drives a gesture or a slider, slides a row's swipe actions open, swipes back or a sheet away, or scrolls |
swipe "Milk" left, swipe "Milk" left full |
shows a list row's trailing (left) or leading (right) swipe actions, which tap "Pin" performs; full performs the first at once |
back, dismiss |
pops the visible pushed screen; dismisses the top sheet or alert |
wait 500 |
advances the clock 500 ms, firing timers on the way, and waits for requests under way |
env dark, size xLarge |
changes the appearance or the Dynamic Type size |
hit 120,340, log "text" |
prints what is at a point; prints a line |
Selectors are the headless Swift replay's (docs/ops-protocol.md, "Event
scripts"): "text" matches what an element shows, [kind] a kind, @12
an id, and #n picks among several matches.
Options: --width 393 --height 852 --scale 3 --safe-area 59,34, --dark,
--type <size>, --keyboard <height> (a keyboard while a field is
focused), --arg <value> (the app's launch arguments, repeatable),
--responses fixtures.json, --offline, --net-timeout <ms>,
--assets catalog/<App> (a built asset catalog: its files, with the
manifest catalog/<App>.json beside them), --real-time (the wall clock; virtual time otherwise), --seed <n>,
--locale, --font role=path, --no-default-fonts,
--fail-on-error-log, --verbose, --session <session.js> (else
$SB_SESSION_JS, else this checkout's dist/session.js, which carries every
SF Symbol icon; node scripts/session.mjs --out <file> --content <app's sources>
writes one with only the icons an app names), --no-gpu,
--full-paint (every shot paints the whole screen; without it a shot
repaints only what changed since the last one, and its line says how much:
paint 8.5 ms (1 rect, 24552 px, 0.62% of the frame); SB_PAINT_TRACE=1
in the environment prints the paint's stages and the ops over 0.05 ms, 2
every op drawn, 3 the phases inside the slow ones),
--full-layout (the whole tree laid out at every commit rather than what
changed, to measure against).
--verbose says what each command did and how long it took, split into
the app's share (its handlers, React's render and the host's flush) and the
session's (the ops applied, laid out and committed), with the events sent
and the passes they caused; prints each commit's cost: the ops applied, the
layout (the nodes placed and the subtrees kept from the last result) and
the steps after it (focus, scroll commands, the geometry reports); and for
each shot the painter's walk (the ops, the subtrees reused and the nodes
walked) apart from the encoding, then the paint and the PNG. The session
lays out and paints incrementally (docs/raster.md, "Incremental layout",
"An incremental display list"): bench/knob.mjs measures it on Codon,
a knob dragged in the plugin window's size, and prints the median drag and
the median commit's split; bench/knob-v8.mjs takes the same knob, page
changes and a scroll under V8, the engine taken out.
Images: PNG always; JPEG, GIF and WebP with the image-decoders feature of
the CLI (swiftbrowser-shot) and the window (swiftbrowser-window), on by
default; a host whose app draws no such image turns it off
(default-features = false), as the Codon plugin does. The window has
X11 and no Wayland on Linux: a plugin host hands over an X11 window, and a
window of its own runs on XWayland where the desktop is Wayland's.
Shaders (ShaderView) draw on the CPU unless the binary is built with the
gpu feature (cargo build --release --manifest-path cli/Cargo.toml --features gpu; off by default here and on in Codon's plugin, it adds
wgpu, 3 to 4 MB). It is each platform's own API and no other: Metal on a
Mac, DX12 on Windows, Vulkan elsewhere. --features gpu-gl adds GL on
Linux and Windows, for a machine whose only adapter is GL's (a container
with Mesa and no Vulkan driver, which is where the GPU tests run here).
Then the first shader looks for an adapter (WGPU_BACKEND=gl picks a
backend among those built) and draws the shader's WGSL there,
falling back to the CPU without one, for a shader compiled before it had
WGSL, or with --no-gpu. A machine whose only adapter is a software one
(Mesa's llvmpipe or lavapipe, Windows' WARP) draws on the CPU too: the
rasterizer's own interpreter is about twice as fast as llvmpipe at
Codon's wavetable display (SB_GPU_SOFTWARE=1 uses the adapter all the
same, to try the path). --verbose
names the adapter and says which shaders wgpu drew and how fast.
cargo test --release --features gpu (or gpu-gl) validates the repository's compiled
WGSL with naga and, given an adapter, holds the render fixtures' pixels
to the GPU tests' tolerance (it skips them without one).
A fixtures file is a JSON array of answers, the first match winning:
[{ "match": { "url": "https://api.example.com/items", "method": "GET" }, "status": 200, "json": { "items": ["Apples"] }, "delay": 300 },
{ "match": { "urlPrefix": "https://cdn.example.com/" }, "bodyFile": "image.png", "headers": { "content-type": "image/png" } },
{ "match": { "urlPrefix": "https://down.example.com/" }, "error": "network: unreachable" }]
body (text), json, bodyBase64 and bodyFile (relative to the
fixtures file) give the body; delay holds the answer that many ms on the
app's clock. Without a match the request goes out over HTTP, honouring
HTTPS_PROXY and SSL_CERT_FILE, unless --offline. Images load the
same way (an AsyncImage's URL, fixtures first), so wait lets them
arrive; a data: URL answers by itself.
swiftbrowser-window#
The same host and session in a live desktop window (window/, Rust),
drawn by the in-memory renderer with no browser: the bundle runs in
QuickJS on the wall clock, the session's frame is blitted to a native
window (winit, softbuffer) repainting only what changed, and the mouse
and keyboard are the session's gestures. It is the in-memory renderer as
a desktop UI, and the editor a CLAP or VST3 plugin shows (docs/notes/plugins.md).
npm run build --workspace packages/raster # dist/session.js
cargo build --release --manifest-path window/Cargo.toml # window/target/release/swiftbrowser-window
npx swiftbrowser-native build src/index.tsx --out app.js
swiftbrowser-window app.js --width 1194 --height 834
The window is sized in points at the display's scale (--scale fixes
it). A press that lifts where it went down is a tap; one that moves past
the slop is a drag, by the session's priorities (a grip reorders, a drag
gesture gets its phases, a slider or a knob follows the pointer, a row's
swipe opens, a sheet or the back edge settles at the release, else the
scroll view under the press pans); the wheel and trackpad scroll what is
under the pointer; hover, the text cursor and the page's .pointerStyle
set the window's cursor; keys and typed text, Escape, Return, Backspace,
select-all and the clipboard reach the focused field. The app starts in
the size class the window's width gives (700 points and up is regular), and
resizing the window relays out the tree, telling the app its new size
class as the width crosses 700 points. Pointer moves that arrive faster than the engine
paints are coalesced, as a browser coalesces them, so the frame rate is
the one the engine sustains.
Options: --session, --scale, --dark, --type <size>, --arg,
--locale, --assets, --responses, --offline, --net-timeout,
--title, --no-gpu, --full-paint, --verbose (the same meaning as
swiftbrowser-shot's), and, for measuring without a hand on the mouse:
--screenshot <file.png> (the first frame, then keep running),
--exit-after <ms>, --drag x1,y1 x2,y2 (a held press from the first
point that wiggles to the second and back --repeat times, --steps a
leg, --interval ms a move) and --stats (a line a frame and a summary:
the frame rate, the input-to-blit latency, and each frame split into the
app's JavaScript, layout, the display list, paint, copy and blit). The
knob-drag measurement of docs/raster.md ("A desktop window") is
swiftbrowser-window app.js --width 1194 --height 834 --scale 2 \
--drag 100,305 100,370 --steps 6 --repeat 20 --stats
The window is a library too (swiftbrowser_window::Window):
Window::standalone(options)?.run() opens its own window, and
Window::embedded(parent, options) makes a child of a window a plugin
host hands over (CLAP's gui extension: an HWND, an NSView or an X11
window), driven from the host's own loop with pump, set_size, show
and hide. examples/embed.rs embeds it in a plain parent window made
with the platform's own API on Linux, Windows and macOS:
cargo run --release --manifest-path window/Cargo.toml --example embed -- app.js
Driving an app from Node#
import { createSwiftUIRoot } from '@swiftbrowser/react';
import { loadRaster, Session } from '@swiftbrowser/raster/node';
let session: Session;
const root = createSwiftUIRoot((ops) => session.applyOps(ops));
session = new Session(await loadRaster(), { dispatch: (event) => root.dispatch(event), setEnvironment: (env) => root.setEnvironment(env) });
root.render(<App />);
session.tap('"Design Patterns"'); // or session.tap(120, 340)
session.scroll(null, 0, 300);
session.drag({ x: 200, y: 600 }, { x: 200, y: 300 });
const png = session.render();
const frame = session.render({ mode: 'frame' }); // { width, height, damage: [{ x, y, width, height }], pixels, full }
render() draws the whole screen afresh as a PNG. render({ mode: 'frame' })
draws into a frame the rasterizer keeps between calls, repainting only what
changed since the last one (docs/raster.md, "Painting only what changed"),
and returns the device-pixel rectangles it repainted with the frame's pixels
(premultiplied RGBA, a view into the module's memory until the next call):
what a window blits. The two draw the same pixels, exactly; raster.framePng()
is the kept frame as a PNG and raster.resetFrame() forgets it.
hitTest(x, y) says what is under a point and what a tap there sends;
focus, type, submit, toggle, select, step, slide, back,
dismiss and environment are the script's commands as methods; start()
tells the app (once it runs) its appearance, text size and the size class the
screen's width gives, as the CLI and the window do after loading it, and
resize() tells it a new size class when that changes. The
options take incrementalLayout: false (every commit lays the whole tree
out; the default keeps one layout pass across commits and lays out what
changed), incrementalPaint: false (every frame walks the whole tree for
its display list; the default reuses last frame's ops for the subtrees
nothing touched, docs/raster.md "An incremental display list") and
profile, a function told each commit's cost (CommitProfile: the ops
applied, the layout's time and its nodes placed and kept, the steps after);
layoutStats holds the last layout's counts and paintStats the last
display list's (subtrees reused, nodes walked); displayList({ incremental: false }) is a fresh walk to compare with.
Images load on the host (docs/raster.md, "Images"): installImage(session)
before rendering gives a React AsyncImage an Image to load with, and
await loadImages(session, { assets: 'catalog/App' }) loads what the
session lists in pendingImages() (fetch for URLs, data: and file:
URLs and catalog files from disk) and hands it to provideImage. An image
draws once it is provided.
Node#
import { createRenderer } from '@swiftbrowser/raster/node';
const renderer = await createRenderer(); // dist/raster.wasm and the packaged fonts
const png = renderer.renderSnapshot(jsonl, { colorScheme: 'dark', commit: 2 });
const png2 = renderer.renderOps(ops); // Op[] from @swiftbrowser/react, or parsed lines
Options: colorScheme, screen (393 × 852), safeArea (59 / 34),
scale (3), dynamicTypeSize (large). The steps are available one by one
for a page that wants the display list rather than pixels: OpsTree (the
tree from ops), renderer.layout(tree, env) (the web renderer's
LayoutResult), renderer.displayList(tree, env), raster.render(list).
renderer.raster.diff(reference, candidate, threshold) compares two PNGs:
the share of pixels whose channels differ by more than threshold (32), and
a side-by-side PNG with the differing pixels in red over the faded reference.
Browsers and workers#
Without a file system, load the module and fonts yourself:
import { Raster, Renderer } from '@swiftbrowser/raster';
const raster = await Raster.load(fetch('/raster.wasm'));
raster.addFont(await (await fetch('/fonts/Inter-Regular.otf')).bytes(), 'system');
const renderer = new Renderer(raster);
Roles: system, rounded (falls back to system), monospaced, serif,
and fallback, tried for characters the role's face lacks. Weights resolve
as CSS does from the faces loaded. The packaged faces are in
fonts/: Inter, which Playwright's Chromium on Linux
draws the web renderer with too, and DejaVu.
Comparing with the browser#
With the React demo running (cd packages/react && npm run dev):
node scripts/raster-compare.mjs --out .build/raster-fidelity [--screens list,controls] [--themes light,dark]
draws each Fidelity screen in Playwright's Chromium and here, compares them,
and writes browser/, raster/, compare/, a summary.md and an
index.html to page through.
Layout#
crate/ the Rust rasterizer: lib.rs (the C ABI), dl.rs (the display list), draw.rs, frame.rs (a kept frame, repainting what changed), fonts.rs, path.rs, blur.rs, diff.rs
src/wasm.ts the module behind a typed API (load, addFont, metrics, measure, render, diff)
src/encode.ts the binary encoding of a display list and a measure call the module reads (crate/src/bin.rs)
src/tree.ts ops → LayoutNode tree
src/text.ts the TextMeasurer over the shaper; where baselines fall, as Chromium places them
src/paint.ts tree + LayoutResult → display list, mirroring Web/src/layoutDom.ts and styles.css
src/color.ts ShapeStyles → paints (Web/src/styles.ts without CSS)
src/palette.ts the stylesheet's color tokens, light and dark
src/symbols.ts SF Symbols as the web renderer draws them, as paths
src/index.ts Renderer, renderOps, renderSnapshot; src/node.ts: the packaged module and fonts
src/session.ts a live tree: scroll offsets, focus, the commit's commands, the gestures that drive it
src/hit.ts what is under a point, and what a tap there sends
src/selectors.ts "text", [kind], @id, #n, as the headless Swift replay resolves them
src/transform.ts offset, rotation and scale as matrices; zIndex order
src/sessionEntry.ts the session as a script for the CLI (dist/session.js)
bin/raster.mjs the command line for op streams
cli/ swiftbrowser-shot: QuickJS (quickerjs, on a pinned nightly), the Native bridge, the clock, fetch, the script runner (a library the window shares)
window/ swiftbrowser-window: the host and session in a native window (winit, softbuffer), the mouse and keyboard, standalone or embedded
scripts/knob-bench.sh the frame-time measurement: Codon at a plugin window's size, a knob dragged, each shot timed
bench/knob.mjs the knob drag's commits under QuickJS, medians; bench/knob-v8.mjs the same frames under V8
test/apps/ small apps for the CLI's tests