moon-stage

    Type-safe HTML-in-Canvas scene graph for MoonBit: pure scheduler with camera, named groups, clipping, visibility and opacity; canvas and DOM-overlay runners

    html-in-canvas
    canvas
    scene-graph
    webgpu
    ui
    Download zip
    Version
    0.1.0
    License
    Apache-2.0
    Last updated
    4 hours ago
    Downloads
    4

    No dependencies

    #moon-stage

    Type-safe HTML-in-Canvas scene graph for MoonBit — the first MoonBit package wrapping the WICG HTML-in-Canvas API. Chrome 158 exposes it without flags (verified on macOS); older builds need chrome://flags/#canvas-draw-element or an origin-trial token.

    Real DOM stays real: text remains searchable (Ctrl+F), inputs focusable, content accessible — while the scene graph decides where and how every element is painted into <canvas content="drawable">.

    #What it looks like

    kanban board painted into a canvas with live inputs and draggable columns

    cmd/kanban: the cards are real DOM inside <canvas content="drawable"> — type in them, search with Ctrl+F, drag a card or a column header, right-drag to pan, wheel over empty space to zoom.

    camera demo: eight cards under a pan/zoom camera

    cmd/camera: one scene under a camera, plus a named column group and a clip group (?clip=1). Screenshots and the GIF are produced by e2e/shots.mjs and e2e/make_gif.py against a headless Chrome, not mocked up.

    whiteboard demo: notes, shapes and text as real DOM on an infinite canvas

    cmd/whiteboard: an infinite board where notes, shapes and text are real DOM inside the canvas — double-click to edit, drag a marquee, resize from any handle, rotate, undo, and reload with the board intact (localStorage).

    #Architecture

    geom Mat3/Vec2/Rect — pure 2D affine math, DOMMatrix-aligned core SceneNode ADT (Html / Group / Clip) + plan_paint — PURE scheduler driver extern "js" FFI shell (drawElementImage, updateElementGeometry, paint/pointer/wheel/resize bridges, feature detection) stage Stage facade — mount/set_scene/set_props(_many)/hit_test/set_camera, per-element layout observation, rotated draw path fallback OverlayStage — the SAME PaintPlan executed as DOM overlay (CSS transforms); `mount_any` picks canvas or overlay

    The scheduler is a pure function of its inputs, (Scene, Viewport) ->PaintPlan, and has no outside-world effects: the only per-frame mutation is consuming the dirty set, and node updates land in an override table rather than rebuilding the tree. Plans are plain data, which makes them property-testable without a browser, runnable by two backends (canvas snapshots / DOM overlay), and reviewable as a formal API via generated .mbti interfaces.

    #Quick start

    moon add allenli178/moon-stage

    #Build a scene and schedule a frame

    ///|
    test {
    let builder = @core.SceneBuilder::new()
    let card = builder.html(
    @core.HtmlProps::make(size={ width: 200.0, height: 80.0, }),
    )
    let scene = @core.Scene::new(
    root=@core.SceneBuilder::group(@geom.Mat3::translate(40.0, 30.0), [card]),
    )
    let plan = scene.plan_paint({
    size: { width: 800.0, height: 600.0, },
    dpr: 2.0,
    })
    debug_inspect(plan.ops.length(), content="1")
    match plan.ops[0] {
    @core.DrawElement(dest~, ..) =>
    debug_inspect(dest, content="{ x: 80, y: 60, width: 400, height: 160 }")
    _ => fail("expected DrawElement")
    }
    }

    Destination rects come out in canvas grid (device pixel) coordinates; the scheduler keeps canvasTransform values in canvas CSS pixel space per the spec. The 2D path lets the browser auto-sync geometry (hit testing + a11y), so a plain card needs only one DrawElement op.

    #Transforms compose child-first

    ///|
    test {
    let m = @geom.Mat3::translate(3.0, 4.0).mul(@geom.Mat3::scale(2.0, 2.0))
    let p = m.apply({ x: 1.0, y: 1.0, })
    assert_true(p.approx_eq({ x: 5.0, y: 6.0, }))
    }

    #Dragging: replace props, get geometry sync for free

    ///|
    test {
    let builder = @core.SceneBuilder::new()
    let card = builder.html(
    @core.HtmlProps::make(
    size={ width: 50.0, height: 30.0, },
    transform=@geom.Mat3::translate(10.0, 20.0),
    preserve_hit_order=true,
    ),
    )
    guard card.id() is Some(id) else { fail("html node has id") }
    let scene = @core.Scene::new(root=card)
    let viewport : @core.Viewport = {
    size: { width: 400.0, height: 300.0, },
    dpr: 2.0,
    }
    // Frame 1 marks everything dirty: preserve_hit_order nodes get an
    // explicit UpdateGeometry (canvasTransform in CSS px) + a draw with
    // preserveElementGeometry=true, so their hit-stack position survives.
    let plan1 = scene.plan_paint(viewport)
    debug_inspect(plan1.ops.length(), content="2")
    // Frame 2 is clean: draw only — hit-stack position preserved.
    debug_inspect(scene.plan_paint(viewport).ops.length(), content="1")
    // Moving the card re-dirties it:
    let _ = scene.replace_props(
    id,
    @core.HtmlProps::make(
    size={ width: 50.0, height: 30.0, },
    transform=@geom.Mat3::translate(30.0, 40.0),
    preserve_hit_order=true,
    ),
    )
    debug_inspect(scene.plan_paint(viewport).ops.length(), content="2")
    }

    #Layout follows the DOM

    Stage::bind tags each element and observes its border box, so a reflow (text wrap, responsive rules, an input that grows) updates props.size, the dest rect and the hit box without rebuilding the scene. A burst of observations is coalesced into one repaint (kanban/?sizes=1).

    #Rotation and skew

    An axis-aligned transform keeps the fast AABB draw path. Rotation/shear emits DrawElementTransformed: the snapshot is drawn in element space under the context transform, the browser records the rotated quad for hit testing/a11y, and Stage::hit_test inverse-maps the point into element space (kanban/?rotate=1 checks pixels, geometry and hits). dest_of still returns the AABB for rotated nodes — use hit_test for exactness.

    #Camera and named groups

    The scene has a camera (Stage::set_camera) applied before the root, so pan and zoom are one matrix update and dest_of/hit_test describe what is on screen. Mat3::around_point builds zoom-at-cursor transforms. Columns and panels built with SceneBuilder::group_named get an NodeId and can be moved later with Stage::set_group_transform, without touching each child's props (camera/?selftest=1, camera/?group=1).

    #Clip groups

    SceneBuilder::clip(m, rect, children) (or clip_named) clips a subtree to a rectangle in its local space; nested clips intersect. The scheduler emits balanced PushClip/PopClip ops, the canvas runner clips with ctx.clip(), and the overlay runner applies an element-local clip-path polygon. Clipped elements also get a canvasClip, so native hit testing and a11y geometry stop at the clip instead of only the painted pixels (camera/?clip=1, fallback/?backend=overlay&clip=1).

    #Visibility

    Named groups can be shown/hidden with set_group_visible. Hidden subtrees emit no draw ops, and elements that were drawn before get a ClearGeometry, so browser hit testing and a11y drop them too; showing the group re-adds everything on the next frame. The overlay runner maps this to CSS visibility (kanban/?hide=1, fallback/?backend=overlay&hide=1).

    #Opacity

    set_group_opacity(id, alpha) multiplies the drawing alpha for a group subtree; nested groups multiply. Hit testing and a11y are intentionally unchanged, matching CSS opacity. Canvas applies globalAlpha per element, so overlapping children are not composited as a single layer; the overlay maps the product to per-card CSS opacity (kanban/?opacity=1, fallback/?backend=overlay&opacity=1).

    #Group drags

    set_props writes into an O(1) props override table; set_props_many applies a whole selection with a single repaint. The kanban group drag uses the batched call instead of one repaint per selected card.

    #Choosing a backend

    @fallback.mount_any(canvas~, overlay~) mounts the canvas runner when the API exists and the overlay runner otherwise; Mounted forwards bind, set_scene, set_props(_many), hit_test, dest_of and unmount, so scene code never branches on the backend. The overlay host must be positioned exactly over the canvas, and pointer tracking goes through Element::track_pointer (down on the host, move/up on the document) because overlay cards are real DOM above the canvas.

    #Browser wiring (demo)

    let stage = @stage.Stage::mount(canvas) // feature detection + RO wiring
    stage.bind(id~, element=form) // NodeId -> drawable element
    stage.set_scene(root~) // marks dirty, paints, requestPaint
    stage.set_props(id~, props~) // drag/scale hot path (O(1))
    stage.set_props_many(updates) // group drag: one repaint
    stage.set_camera(m) // pan/zoom the whole scene
    stage.set_group_transform(gid, m) // move a named column/panel
    // fit/reset are demo-level math over Stage::dest_of + Stage::set_camera
    stage.hit_test({ x, y }) // local hit model (front-most first, quad-aware)
    stage.unmount() // disconnect observers + paint handler

    DOM mutations belong in input handlers, never inside paint (they apply on the NEXT rendering update per the spec) — set_props repaints synchronously and forces requestPaint because a transform change does not alter the element snapshot.

    Pointer and wheel bridges deliver coordinates in canvas CSS pixels derived from clientX/clientY minus the canvas border box. Do not switch them to offsetX/offsetY: once browser hit testing pierces into the drawable subtree, the event target is the card's own input, so offsetX is measured from that element while the event still bubbles to the canvas.

    #Demos (js target, served over http)

    democommandshows
    hellomoon build --target js cmd/helloform painted into canvas, input stays live
    dragmoon build --target js cmd/dragpointer drag + wheel scale, scripted selftest
    fallbackmoon build --target js cmd/fallbackmount_any canvas/overlay switch; ?backend=overlay forces the DOM runner, ?selftest=1 drags card0, ?clip=1 clip parity, ?hide=1 visibility parity, ?opacity=1 opacity parity
    cameramoon build --target js cmd/camerapan/zoom camera, zoom-at-cursor, named column group, clip group; ?selftest=1 ?group=1 ?clip=1
    kanbanmoon build --target js cmd/kanbanrubber-band multi-select, card/column drag, camera pan+zoom+fit, Ctrl+F; ?selftest=1 ?diff=1 ?hit=1 ?sizes=1 ?rotate=1 ?columns=1 ?cam=1 ?fit=1 ?hide=1 ?opacity=1
    whiteboardmoon build --target js cmd/whiteboardinfinite canvas: notes/shapes/text, marquee, handle resize+rotate, undo/redo, z-order, localStorage; ?selftest=1 (26 checks)
    benchmoon build --target js cmd/bench?n=1000 / ?n=5000 throughput; ?spread=1 spreads the cards over a wide board to separate draw cost from overdraw
    glassmoon build --target js cmd/glassWebGPU texture path, manual geometry sync (I5-3D)

    Chrome 158 runs these without flags (verified on macOS). On older Chrome, enable chrome://flags/#canvas-draw-element or register an origin-trial token (the trial covers Chrome ≤ 154). Serve over http.

    #Verification matrix

    #invariantwhere
    I1plan == hand derivation; deterministicpure MoonBit, 48 tests
    I2Mat3 associativity / identity / inverse roundtrip / affine interpolationpure MoonBit
    I3hit stack follows draw order; preserveHitTestOrder keeps an existing slot (pure model + tests)pure MoonBit
    I4browser getElementTransform == derived CSS transform (11/11 nodes: 8 cards + 3 column headers)headless Chrome 158 (kanban/?selftest=1)
    I5manual updateElementGeometry -> getBoundingClientRect match; also on the animated WebGPU path (I5-3D)headless Chrome 158 (kanban/?selftest=1), I5-3D on Edge
    I6trusted pointer events pierce into the drawable subtree, and the canvas-relative coords land inside the card (I6-COORD)headless Chrome 158, CDP Input — PASS
    I7element reflow (CSS-only width change) reaches props.size, the dest rect and the hit boxheadless Chrome 158 (?sizes=1) — PASS
    I8rotated node: geometry matrix rotated, pixels rotated (AABB corner empty), quad-accurate hit testheadless Chrome 158 (?rotate=1) — PASS
    I9auto backend selection plus trusted drag on both runnersheadless Chrome 158 (cmd/fallback, canvas + ?backend=overlay) — PASS
    I10camera pan/zoom: dests follow the matrix, zoom keeps the cursor hitheadless Chrome 158 (camera/?selftest=1) — PASS
    I11named group transform moves its subtree onlyheadless Chrome 158 (camera/?group=1) — PASS
    I12clip group: pixels clipped, local hits filtered, canvasClip bounds native hits/a11yheadless Chrome 158 (camera/?clip=1) — PASS
    I13overlay clip: element-local clip-path polygon and clipped hit testingheadless Chrome 158 (fallback/?backend=overlay&clip=1) — PASS
    I14column header drag moves its named group onlyheadless Chrome 158 (kanban/?columns=1) — PASS
    I15right-drag pan + cursor-anchored zoom in the real boardheadless Chrome 158 (kanban/?cam=1) — PASS
    I16fit frames every card inside the viewport; reset restores the originheadless Chrome 158 (kanban/?fit=1) — PASS
    I17hiding a named group drops dest/hit/pixels and restores on showheadless Chrome 158 (kanban/?hide=1) — PASS
    I18overlay group visibility: DOM visibility plus hit filteringheadless Chrome 158 (fallback/?backend=overlay&hide=1) — PASS
    I19group opacity dims pixels and keeps the hit targetheadless Chrome 158 (kanban/?opacity=1) — PASS
    I20overlay opacity maps to per-card CSS opacity, hits unchangedheadless Chrome 158 (fallback/?backend=overlay&opacity=1) — PASS
    I21whiteboard: hit/drag, handle geometry + resize, rotate, undo/redo, delete-restore, persistence, cursor-anchored zoom, DOM text editheadless Chrome 158 (whiteboard/?selftest=1, 26 checks) — PASS

    Differential test: the same scene runs through BOTH backends (canvas snapshots and DOM overlay); element positions agree 4/4, before and after a drag (kanban/?diff=1).

    e2e/accept.mjs runs the whole matrix against a headless Chrome over CDP (Node ≥ 22 for the built-in WebSocket; one command after serving the repo and opening a debugging port). It skips the canvas checks when drawElementImage is missing and always exercises the overlay runner, so the fallback stays covered on browsers without the API. .github/workflows/ci.yml runs moon check --deny-warn, moon test, the JS build and that suite on every push/PR.

    Benchmark (real-clock, CDP; initial headless-Edge run, then re-run on Chrome 158 / macOS): 1000 cards = 0.8 / 0.86 ms per frame (1000 drawElementImage + full replan), cold start 8.7 / 10.4 ms; 5000 cards = 20 / 4.5-5.0 ms per frame, cold start 17.4 / 21.5-27.2 ms. Platform difference is large at this scale; treat these as submission costs (plan plus draw calls inside the input handler). Raster/composite happens asynchronously and is not included, and fps_est is capped at 60 rather than measured. Artifact size: kanban demo 36.8 KB gzipped, no runtime dependencies.

    The default layout piles every card into a 5x4 spot grid, so above ~2k it mostly measures overdraw. ?spread=1 lays the same cards out as a wide board and tracks draw cost alone (Chrome 158 / macOS, M5): 10k = 13.4 ms, 20k = 29.9 ms, 50k = 87.6 ms per frame — linear in N, i.e. ~1.3-1.8 µs per element for replan + drawElementImage. hit_stack_next is linear too; the previous copy-per-move implementation made the 5k piled run 154 ms instead of 8 ms.

    #Known boundaries

    • extern "js" is js-backend-only in the current toolchain; geom/core are backend-agnostic and compile under wasm-gc/native.
    • Hit testing: Chrome 158 pierces trusted pointer events into the drawable subtree (I6 PASS). Browsers that stop events at the canvas still work through Stage::hit_test, but native focus/typing inside a card requires the pierce.
    • WebGPU: the element-texture path requires a paint record that a webgpu-context canvas cannot obtain yet (the glass demo degrades to geometry-sync-only and reports this precisely).
    • preserveHitTestOrder is modeled by hit_stack_next (pure, tested): auto geometry pushes, preserveHitTestOrder keeps an existing slot, and clearElementGeometry removes. The DOM-overlay runner hit-tests in visual paint order because the flag has no meaning there.
    • The local stack is reset by set_scene. With a stable element set it mirrors the browser; if a caller keeps browser geometry across a rebuild, it should clear/re-bind those elements.
    • Rotated nodes are painted through the context transform; the snapshot is not re-rastered at the rotated resolution, so extreme scales soften.
    • Clip groups clip rendering, local hit testing and native canvasClip on both backends. Rotated clips are exact for local hits; the browser-facing canvasClip is their AABB, so native piercing can still reach a corner just outside a rotated clip. Group opacity is not implemented, and viewport clipping still relies on the canvas bitmap bounds.

    #API stability

    0.1 freezes the surface the demos and the acceptance suite exercise:

    frozennotes
    SceneNodeHtml(id, props), Group(id?, transform, children), Clip(id?, transform, rect, children)
    HtmlPropssize, transform, z, clip, preserve_hit_order
    PaintPlanDrawElement, DrawElementTransformed, UpdateGeometry, ClearGeometry, preserve-aware hit_stack
    Scenecamera, replace_props(_many), replace_group, set_group_visible, set_group_opacity, hit-stack model
    runnersStage, OverlayStage, Mounted expose the same scene API
    hit testingfront-most first, quad-aware for rotation, preserve-aware on canvas

    Deferred to 0.2+ (additive unless noted):

    • true group compositing (offscreen layer) for opacity; the current implementation is per-element alpha;
    • viewport culling and batched FFI calls — internal performance work;
    • OffscreenCanvas/worker snapshots;
    • keyboard focus model and multi-pointer gestures.

    cmd/whiteboard is the showcase demo, built on this frozen surface: items, selection, handles, history and persistence exercise the scene API without changing it.

    See CHANGELOG.md for the 0.1.0 feature set.

    #License

    Apache-2.0

    Source Files