React bindings
@prnt/dagr-react is the package that joins the other three. A Graph goes in, a
canvas comes out, and the wiring in between (running the layout, converting it
into a scene, building the renderer, keeping the overlay in step, taking it all
back down on unmount) is the component rather than something every host writes
again.
import { Graph } from '@prnt/dagr-graph';
import { DagrCanvas, Html } from '@prnt/dagr-react';
const graph = new Graph();
graph.addNode({ id: 'plan' });
graph.addNode({ id: 'build' });
graph.addEdge({ source: 'plan', target: 'build' });
export function Board() {
return (
<DagrCanvas graph={graph} style={{ width: '100%', height: 480 }}>
<Html node="plan">Plan</Html>
<Html node="build">Build</Html>
</DagrCanvas>
);
}
This page describes the package as of M5.3a: the component, the hook under it, the animation an edit gets for free, the overlay sugar, and the conversions the renderer deliberately does not own.
The graph prop is controlled, and controlled here means watched
A Graph is mutable. Passing one as a prop and comparing it by identity, the
way React compares everything, would mean that graph.addNode(...) changed
nothing on screen until the caller also replaced the object, which is a rule
nobody remembers on the third edit.
So the hook under the component subscribes to the graph instead.
Graph.subscribe takes a listener and returns the function that stops
watching, which is exactly the shape React's useSyncExternalStore wants, and
an edit anywhere reaches the canvas:
// Both of these redraw.
graph.addNode({ id: 'ship' });
setGraph(rebuildFromScratch());
The one window this leaves open is worth knowing about, because it is narrow
and it is real. React subscribes in an effect, after the render that read the
store, and effects run child first. A child's mount effect that edits the
graph therefore runs before the canvas has subscribed, and that one edit is not
drawn until the next one arrives. Closing it properly needs an O(1) mutation
counter on Graph itself; the two ways of closing it from this side are a
second layout on every mount, or a listener that outlives every component and
makes the graph build a patch on every mutation forever. Both cost more than
the window does. use-dagr.ts carries the full argument.
It is one edit of latency rather than a disagreement that persists.
relayout re-runs the pipeline over the graph the engine holds and measures the
delta against the geometry it last reported, so the next edit reports both and
the drawing catches up. Any resubscribe (a new graph, a new config, React's
StrictMode remount) closes it outright, because a resubscribe rebuilds the
engine and lays the graph out cold.
An edit is a relayout, not a cold run
useDagr holds a createLayout engine for as long as it is watching one graph
with one config, and calls relayout(patch) with the patch the graph delivers.
So it returns four things rather than two:
const { result, error, delta, from } = useDagr(graph);
delta is a LayoutDelta: what appeared, what went away, what moved, and what
the box around the lot became. It is what <DagrCanvas animate> animates from,
and what a caller driving @prnt/dagr-render themselves wants. from is the drawing
that delta is a difference FROM, and it has a section of its own below.
delta is null on a cold run, and that is a statement rather than a missing
value. A delta is a difference from a drawing; the first run of a graph has no
drawing to differ from, and neither does the run after a config change or the
recovery from an engine that fell out of step with its graph. null is how those
runs say "reseat, do not retarget", and retarget (exported) is where that
decision is written down.
The engine runs in the graph listener, which is neither render nor an effect.
relayout does not apply its patch: the graph is already mutated, the patch
describes an edit already made, and a patch the graph disagrees with is refused.
A hook that kept those patches in a queue and drained it during render would be
doing a side effect in render, and concurrent rendering is entitled to discard
that render and run it again, which would consume a patch twice or not at all.
So there is no queue: Graph.subscribe hands over one patch per mutating call,
straight after it commits, and the relayout happens right there. Render only
reads the result.
One consequence worth stating: the relayout happens inside your own
graph.addNode(...) call. A layout that fails is reported through error
rather than thrown, because addNode is not a function anyone expects to raise
a layout error. And wrap a multi-step edit in graph.batch: it is one patch
and one relayout rather than three, which is the same advice relayout gives
for its own reasons. Unbatched, the intermediate layouts are computed and never
drawn, because React commits once, and the section below is about what the
component then has to do to stay correct.
The engine is disposed when the component stops watching, which is what
LayoutEngine.dispose is for: the graph, the previous run's pipeline state and
the reported-geometry snapshot are retained for the life of an engine, and on a
large graph they are larger than the result you can see.
A delta is only safe to apply to the drawing it was measured from
The state changes once per layout. An effect keyed on it runs once per commit. Those are different counts, because React renders the latest snapshot of an external store rather than every one, so two mutating calls in one task are two layouts and one commit holding the second. The delta you are handed is then a difference from a drawing you never drew, and applying it to the drawing you did draw leaves the two disagreeing from then on.
That is what from is for, and the check is one line:
// `drawn` is the result the motion is currently holding. `rosterOf` builds the
// whole scene from a result, which is what a reseat needs and a retarget does
// not: it has to be the CURRENT layout, not one hoisted earlier.
useEffect(() => {
if (state.result === null) return;
const continues = drawn.current !== null && drawn.current === state.from;
retarget(motion, continues ? state.delta : null, rosterOf(state.result));
drawn.current = state.result;
}, [state]);
Do not leave that check to the motion. SceneMotion.apply refuses a delta
naming an id whose presence it disagrees about, which catches some of these, and
a delta naming only ids it already holds applies cleanly and leaves the drawing
wrong in silence. Creating a node and then labelling it, in one handler, is
enough to produce one. <DagrCanvas animate> does this check for you, and
onLayout supplies from and a fourth argument, continues, for the same reason.
The other half of the answer is graph.batch: one patch, one layout, one delta,
nothing to miss.
Read change counts safely
onLayout(result, delta, from, continues) runs once per committed layout.
continues is true when from matches the last successful layout committed by
this canvas. It is false for initial/cold runs, after layout errors, and when
React skipped intermediate layouts. It works with animate on or off; it does
not report whether GPU drawing or a spring animation has finished.
<DagrCanvas
graph={graph}
onLayout={(result, delta, _from, continues) => {
setNodeCount(result.nodes.size);
setMovedCount(continues && delta ? delta.nodes.moved.length : null);
}}
/>
A null moved count means the last delta cannot describe the complete change
since the prior commit. Batch related mutations with graph.batch to produce
one layout per edit. Existing handlers taking fewer arguments still work.
When driving a renderer yourself, compare from against the scene you actually
hold; a canvas commit and your renderer's applied state may differ.
The layout still runs during render, synchronously
The first run for a graph is a useMemo, exactly as it was: synchronous, and
during render. The result is referentially stable, and so is the whole state
object: a render that changed neither the graph nor the config hands back the
same one, so an effect keyed on it does not run.
There is no worker here, and that is a decision rather than an omission. A
Worker has to be constructed by the host, because new Worker(new URL('./x.ts', import.meta.url)) is an expression a bundler reads statically and a new URL
inside this package would have to resolve, and emit its own chunk, under
everyone's bundler. @dagr/campaign-stage takes a createWorker factory for
exactly that reason. Inviting one here before M3.9b has built the worker-side
session that would make a per-edit round trip worth taking would be guessing at
a shape M3.9b is going to decide.
The config is compared by value
LayoutConfig is the one prop a caller writes as an object literal in JSX:
<DagrCanvas graph={graph} config={{ nodeSep: 80, rankSep: 120 }} />
Compared by identity, that would relayout the whole graph on every render of
the surrounding application. So useDagr compares the config field by field,
including one level into defaultNodeSize, and keeps the old object when they
agree.
nodeSize is the exception and it cannot be anything else: it is a function,
and two functions that agree on every node are indistinguishable without
calling them on every node, which is the work the comparison exists to avoid.
Memoise it, the way React asks for every callback prop. The same goes for
nodeAppearance and edgeColor.
A layout that fails is reported, not thrown
useDagr returns error rather than throwing. A graph a user is
editing passes through states the layout refuses, and throwing would unmount
the subtree to the nearest error boundary on the keystroke that made the graph
momentarily invalid. It does not hold the last good result either: a stale
picture presented as the current one is the failure mode that is hardest to
notice.
<DagrCanvas> is the one that decides. By default it throws the failure during
render, so a React error boundary catches it; an onError prop takes it
instead and suppresses the throw. Both beat the third option, which is to
render an empty box, because an empty box is indistinguishable from an empty
graph.
One class of failure is recovered from instead, and only one.
EngineStateError means the engine and the graph have fallen out of step, which
a cold run fixes, so the hook rebuilds and runs cold and reports the result with
no delta. Everything else a relayout raises is reported, exactly as the same
failure from a cold run already is. The alternative, recovering from all of
them, would make a failure reachable only under a warm start invisible: every
edit would come back cold, undelta'd and unanimated, with nothing saying why.
The cost of that choice, stated rather than buried: such a failure now reaches
your error boundary rather than quietly degrading to a correct but unanimated
drawing.
The flip, and why it lives here
@prnt/dagr-render refuses to name a LayoutResult. Naming one would make
@prnt/dagr-layout a dependency of the renderer, and the y-down to y-up conversion
belongs to whoever owns the layout. This package owns both, so the conversion
is here, and it is exported rather than hidden:
import { toSceneNodes, toSceneEdges, toWorldBounds } from '@prnt/dagr-react';
renderer.setNodes(toSceneNodes(result));
renderer.setEdges('my-edges', toSceneEdges(result));
renderer.camera.fitBounds(toWorldBounds(result.bounds));
A layout runs y-down, ranks increasing downwards, as dagre does. The renderer's world is y-up, because its camera is. Nodes, route points and bounds are three separate expressions and flipping two of the three draws a picture that is half upside down with every unit test on the flipped halves still green, which is why the suite runs a real layout through all three and asserts they agree.
The delta half is the same flip in three more expressions, and it is the worse
three: a target flipped the wrong way does not draw a node upside down, it
springs the node to the mirror of where it belongs and leaves it there. So
toMotionDelta is asserted against what toSceneNodes and toWorldBounds put
in the same place for the same run, rather than against numbers written by hand.
import { retarget, toMotionDelta, toMotionRoster } from '@prnt/dagr-react';
Appearance is a callback taking a node id:
<DagrCanvas
graph={graph}
nodeAppearance={useCallback(
(id) => (id === selected ? { fillColor: 0x2563eb, glowWorld: 6 } : undefined),
[selected],
)}
/>
Returning undefined takes the defaults, and a partial record is merged per
field, so recolouring one node does not mean restating its shape and both halo
fields. Geometry is not on the record: a node's centre and size are the
layout's answer, and overriding them here would draw a picture that disagrees
with the bounds, the routes and every stability guarantee the layout makes. Set
config.nodeSize instead, upstream, where the layout can account for it.
animate is one word, and it is the flagship
<DagrCanvas graph={graph} animate />
With it, an edit glides to its new layout instead of cutting to it: nodes spring to their new centres, edges follow their new routes, and the drawing's box moves with them. Without it, nothing tweens, which is what the component did before M5.3a and is still the default.
It is a prop rather than a hook because this component already owns all four
things a hook would have to hand back out: the coalesced frame, the renderer,
the scene conversions, and the delta. What keeps the prop from foreclosing the
other shape is that createMotionLoop takes its scheduler as an option. A
caller who owns their own frame leaves animate off, takes the renderer off
useDagrCanvas, takes the delta and its from off onLayout, and drives
createSceneMotion from their own loop, which is
the worked example
on the render page. toMotionDelta, toMotionRoster and retarget are
exported for exactly that caller, so the flip and the continuity check are not
theirs to rewrite. The component hands the loop its own requestDraw, so there
is one frame budget here rather than two, and a burst of edits in one task is
one frame.
The feel is the same prop:
<DagrCanvas graph={graph} animate={{ halfLifeSeconds: 0.3 }} />
halfLifeSeconds is how long a spring takes to close half the remaining gap
(default 0.12) and restEpsilon is how close, in world units, counts as arrived
(default 0.05). Both are @prnt/dagr-render's, one number each for the whole scene,
because one delta is one change and three arrival times would read as three. The
object is compared by value, like config.
Four things worth knowing:
- The first layout does not animate. A scene built from a result has no history to come from, so it is seeded at rest and drawn where the layout put it. Only an edit glides.
- Sizes do not spring. A node that changed size takes its new box on the frame the edit lands, and only its centre glides. A label that grew measures wider because the text that made it wider changed instantly, and a box lagging its own contents would clip them.
- A removed node leaves on the frame its spring settles, which for a node that was standing still is the next one: it is gone rather than faded. A node removed mid-glide finishes its move first, so it does not jump on the way out, unless that removal arrived in a burst that had to reseat, in which case it is gone at once: a reseat describes a whole state, and a node not in it has no departure to finish. Nothing fades, because a fade is an appearance and this component has no opinion about appearance.
- The loop stops itself. It asks for no frame after the one on which every spring has arrived, so an idle canvas is an idle canvas.
The living graph demo is this prop, onLayout, and a few
hundred lines of page. Its source is packages/living-stage, and the README
there is worth reading before writing your own: it is mostly a list of the
things that turned out to matter, including the two shapes of edit that looked
right and either moved the whole drawing or moved none of it.
The camera is fitted once, and the sprung box is yours
The first frame that has both a layout and a viewport frames the graph. Nothing
refits after that, and fit={false} skips even the first. Refitting on every
edit would be a camera that jumps whenever the graph changes, which is the
instability the whole incremental-layout milestone exists to keep out of the
layout, reintroduced one level up where no stability metric would see it. An
animated demo that refits every frame would look impressive and would hide the
thing it exists to show, because a drawing that stays put while the camera moves
is indistinguishable from a drawing that moves.
A caller who does want a following camera has the box on every frame, sprung along with everything else, and writes the one line themselves:
<DagrCanvas
graph={graph}
animate
onFrame={(frame, renderer) => {
if (following && frame.bounds !== null) renderer.camera.fitBounds(frame.bounds);
}}
/>
The types these props are spelled in are re-exported from this package, so a
caller whose only contact with the renderer is <DagrCanvas> does not take a
dependency on @prnt/dagr-render to write an annotation:
import type { SceneMotionFrame, SceneMotionOptions, Renderer } from '@prnt/dagr-react';
const feel: SceneMotionOptions = { halfLifeSeconds: 0.3 };
function follow(frame: SceneMotionFrame, renderer: Renderer): void {
if (frame.bounds !== null) renderer.camera.fitBounds(frame.bounds);
}
They are the same types, re-exported rather than restated, so one can still be
handed to @prnt/dagr-render directly. Anything that drives the renderer itself
still imports from @prnt/dagr-render, which stays a peer dependency.
onFrame runs after the renderer has been told what to draw and before it
draws, so a camera moved there moves on that frame rather than the next. The
renderer comes with the frame so that line needs no ref: reaching it through
useDagrCanvas would be a child component written to call fitBounds once. It
is not called when animate is off, because then there are no frames between
layouts to hand over.
The living graph demo takes the third option this decision leaves open, which is worth naming because it is the one an animated demo usually wants: it does not follow the box at all, and instead its graph is built so that no edit can make the drawing bigger, which makes one fit correct forever. A refit button is there for a visitor who has panned away, and a person pressing it is the whole difference between that and an automatic refit.
<Html> puts React content in world coordinates
createHtmlOverlay takes a create callback returning an HTMLElement, which
is the right shape for a caller building DOM by hand and the wrong one for
React. <Html> inverts it: the component owns one host element for its whole
life, create hands the overlay that same element every time, and the children
go into it through a portal. The overlay attaches and detaches an element whose
contents React has been maintaining all along.
<DagrCanvas graph={graph}>
<Html node="plan" minScreenWidth={120}>
<strong>Plan</strong>
</Html>
<Html placement={{ kind: 'point', at: { x: 0, y: 40 } }}>Legend</Html>
</DagrCanvas>
Exactly one of node and placement is given, and the type enforces it. The
node form sits over the box the layout gave that node and takes the overlay's
two screen-width gates; the placement form takes an OverlayPlacement
straight through, and carries its own gates inside it if it is a box.
<Html> is for the tens, not the thousands. The overlay's create is lazy
precisely so that a scene with 2,800 nodes builds DOM for the few dozen on
screen. A portal is not lazy: an <Html> that is culled still has its subtree
mounted. Ten labels and a card or two is nothing; one per node on a big graph
gives up the cap that makes the overlay work, and the thing to reach for there
is createRichNodes, which is pooled and imperative on purpose.
An <Html> naming a node the layout does not have registers nothing and
renders nothing, rather than throwing. A node can legitimately vanish while an
edit is in flight.
Reaching the renderer
Anything inside the canvas can have it:
function ZoomOut() {
const { renderer, requestDraw } = useDagrCanvas();
return (
<button
onClick={() => {
renderer.camera.setZoom(renderer.camera.zoom * 0.8);
requestDraw();
}}
>
Zoom out
</button>
);
}
The handle carries the renderer, the overlay, the layout currently on screen,
and requestDraw. Nothing calls renderer.render() directly: requestDraw
coalesces every reason to draw in one frame into a single callback, and the
overlay's own sync runs inside it, because a second animation loop is a
second frame budget and a frame of skew, which reads as the labels swimming
over the graph during a pan.
Children do not render at all until the renderer, the overlay and the layout all exist, so nothing on the handle is nullable. A caller who wants a spinner in the meantime renders it outside the canvas.
useDagrCanvas outside a <DagrCanvas> throws CanvasContextError, with code
OUTSIDE_CANVAS. A missing provider is the one mistake in a React package that
is otherwise completely silent, because useContext of an unprovided context
returns a default value and the failure surfaces several frames away from the
component that was in the wrong place.
Three props are read once
clearColor, sceneStyle and edgeStyle are taken when the renderer is
built. Edge groups are declared at construction in draw order, and rebuilding a
device context because a colour changed would drop every instance handle in the
scene to honour a prop nobody animates. A caller who does want to animate one
holds the renderer and calls setEdgeStyle on it.
Shared selection and click-versus-pan
useGraphInteraction owns the pointer sequence and leaves hit geometry,
selection, and the camera with you:
const surface = useRef<HTMLDivElement>(null);
const [selection, setSelection] = useState<GraphHitTarget | null>(null);
useGraphInteraction({
surfaceRef: surface,
displayedRevision: frame.revision,
devicePixelRatio: frame.devicePixelRatio,
screenToWorld: (point) => camera.screenToWorld(point),
hitTarget: (query) => index.hit(query),
selection,
onSelectionChange: setSelection,
onPanStart: () => camera.stop(),
onPanBy: (delta) => camera.panByScreen(delta),
});
The provider is synchronous. Every query carries four pieces of evidence:
| Field | Meaning |
|---|---|
css | CSS pixels from the surface's top-left border box, with positive y down |
world | That point converted through the camera displaying this scene |
devicePixelRatio | The caller-supplied CSS-to-device ratio used for this display |
displayedRevision | Opaque identity for displayed geometry, draw order, target membership, and the paired DPR |
Do not multiply css by DPR before screenToWorld. A provider reading a
device-pixel target multiplies at that boundary. A provider returns a stable
node identity (nodeId), port identity (nodeId plus portId), edge
identity (edgeId, the SceneEdge id), or null target and stamps every
hit or miss with the displayed revision it queried.
Renderer slots, array positions, and pick colors are not stable identities.
The stamp is load-bearing. The hook rejects a result whose stamp differs from
the query and rejects the whole click when displayedRevision changed between
press and release. Use the revision of what is on screen, not a graph model
revision that runs ahead of animation. Change it on every animated geometry
frame and whenever the displayed DPR changes. A graph edit that changes hit
geometry then cancels an in-flight click; a pan continues because it means
screen movement, not target identity.
Selection is controlled through selection and onSelectionChange. The hook
selects on release only when press and release hit the same target. A fresh
empty-to-empty click requests null. Crossing the default 5 CSS-pixel
threshold switches permanently to pan, reports the full first delta and
incremental later deltas, captures the pointer, and suppresses the generated
click and dblclick. Cancellation and lost capture never select.
Native controls are excluded by default. Add
data-dagr-interaction-target to a focusable graph target that should
participate. The closest control wins, so an input nested in a rich node keeps
its native behavior. Keyboard events are not intercepted: keep graph targets
focusable and process their keyboard-generated click, whose detail is 0,
in your component. Set touch-action: none on the surface for touch panning
and user-select: none if drag text selection would be misleading.
The 2026-10-01 Apple M4 CPU baseline scans 100, 1,000, and 10,000 synthetic rectangles in reverse draw order. Median pointer-down query time was 0.000125 ms, 0.000792 ms, and 0.008416 ms respectively. Each event makes one provider call and one displayed-revision check, then checks every rectangle. The 100-node value is recorded but not gated because it is only three clock ticks. These are CPU query medians, not browser frame time or GPU evidence.
The generic System Atlas uses this API with reverse draw-order rectangles. It
is proof that a consumer can supply geometry; it is not an exact
DagrCanvas adapter. DagrCanvas now supplies one, described in the next
section. Port geometry is M6.3a. Edges are answered through the same
contract (M4.8b), described below.
GPU picks behind the same contract
createPickedNodeHitProvider adapts an asynchronous pick, such as the
renderer's pickNode, to this synchronous contract:
const picked = createPickedNodeHitProvider<Revision>({
pick: (css) => renderer.pickNode(css),
// Query the resting pointer again, as the hover listener does.
onPicked: () => queryHover(),
});
useGraphInteraction({ /* as above */ hitTarget: picked.hitTarget });
A query is answered only from a pick that has settled for the same world point
and the same displayed revision. Any other query starts a pick and is answered
as stale, which the hook ignores rather than reading as a miss. So a press
selects only if its point was picked before the press: query the provider from
pointermove to prime it, with a world point converted exactly as the
screenToWorld you give the hook converts it (the key compares with ===), and
expect a touch tap with no hover before it to be
ignored. The release is its own query, so a mouse that moves a pixel between
press and release, under the pan threshold, is also ignored. A displayed revision
that changes every animated frame means no click is answered while nodes move.
At most one pick is in flight; a query arriving meanwhile is answered stale and
never picked later, since the camera may have moved by then, so re-query the
resting pointer from onPicked. The pick is exact to the device pixel under the
pointer and has none of the CPU index's touch tolerance. DagrCanvas wires
this provider in behind hitTesting="gpu" (next section). At 10,000 nodes a
pick took at most 0.2 ms of CPU at the median on AMD RDNA 2 and Apple M4,
on WebGPU in Chrome 156 (2026-10-28 and 2026-10-29) (see
bench/browser/README.md, "What a pick costs a frame").
Navigation, node events and camera control
DagrCanvas can host the whole interaction a large graph needs without you
wiring a camera: pan, zoom, click, hover and "fly to this node".
const api = useRef<DagrCanvasApi>(null);
<DagrCanvas
graph={graph}
navigation
label="Relationship graph"
apiRef={api}
onNodeClick={(id) => { openDrawer(id); api.current?.focusNode(id); }}
onNodeHover={(id) => setHovered(id)}
onBackgroundClick={() => closeDrawer()}
/>
navigation turns on wheel zoom (including trackpad pinch) anchored under
the cursor, two-finger touch pinch (zoom about the midpoint, panning with it),
drag to pan, and keyboard control while the canvas itself has
focus: Left/Right pan, Shift+Up/Down pan vertically, +/- and Up/Down zoom,
Page Up/Down zoom further, 0 or Home fits. A pinch never selects a node, and
single-finger pan is paused while two fingers are down. Content that handles the gesture itself keeps it: a textarea, a
contenteditable, anything that scrolls (overflow: auto with overflow), and
anything marked data-dagr-no-zoom, which is also excluded from pan, pinch and
selection starts.
Phones. touchNavigation="drag" (default) gives the canvas every touch
(touch-action: none): one finger pans, two pinch, and the page cannot scroll
from the canvas. For a canvas embedded in a scrolling page use
touchNavigation="two-finger" (touch-action: pan-x pan-y): a lone finger
scrolls the page and the camera moves only with two fingers. In that mode the
browser can still claim a two-finger gesture that starts as a scroll, so pinch
is dependable when both fingers land before either moves; test it on your
target devices, which nothing here has. A second finger never takes over an
active single-pointer gesture. maxPixelRatio (for example 2) caps the
render resolution and so the drawing buffer. Software WebGL2 drew slower at a
larger buffer and an RTX 4090 did not; no phone has been measured, so measure
on your target devices (bench/browser/README.md, "Mobile pixel-ratio
budget"). The canvas also
resizes when the browser's ratio changes.
Tolerance. A hit that lands inside no silhouette falls back to the nearest
node centre within 22 CSS pixels for touch and 4 for a mouse, so far-out dots
are tappable; an exact hit always wins. The pixel slack is converted at the
current zoom, and it applies to hover too. The
canvas becomes focusable (tabindex="0", role="group", named by label; pass one, or the focus stop is unnamed and a development
warning says so once). label names the region whenever it is set, with or
without navigation and
sets touch-action: none. It is off by default because a canvas that begins
capturing the wheel would trap page scroll under a caller who did not ask. All
of it stays inside the default camera limits, and
any input cancels a camera flight in progress. The arithmetic (wheelZoomFactor,
keyCommand, canvasPoint) is exported from @prnt/dagr-render if you drive your own camera
and want the same feel.
onNodeClick(nodeId), onNodeHover(nodeId | null) and
onBackgroundClick() report stable node ids. They work without
navigation: a drag then simply does not pan, and still does not click.
Clicks use the shared gesture contract
above, so a press that turns into a drag never selects, and a click whose
drawing changed between press and release (an animation frame, a relayout) is
refused rather than landing on a different node. Hover uses the same hit test
and sets cursor: pointer over a node when onNodeClick is set.
Hits are exact, on the CPU. The hit test (createNodeHitIndex, also
exported for hosts that run their own surface) evaluates the silhouette the
shader draws: a circle is a circle, so the empty corner of its box is a miss,
and a rounded rectangle's corners are cut. It tests the nodes as currently
drawn, which during animate means the sprung positions, not the layout's
final ones. Overlaps resolve by draw order (circles over rectangles, later over
earlier). A uniform grid keeps a query to a few shape tests; the index is rebuilt
when the drawn nodes change and not otherwise.
What is not a hit target on DagrCanvas: ports and glow halos. HTML
inside a tier (next section) is the DOM's to hit: native controls inside a
card keep their native behavior, and a click on a non-interactive part of a
card selects its node because the card sits on the node.
Edge hits, for a host with its own surface. createEdgeHitIndex(edges)
tests the centrelines the renderer was handed: the points after edgePath
shaping and, while edges glide, the frame's points, so build it from what was
drawn, not from the layout, and rebuild it when that changes (a removed edge
then misses and a rerouted one hits on its new route). hit(world, toleranceWorld) returns the id of the edge whose centreline is nearest the
point within the tolerance, or null. A centreline has no area, so pass half
the drawn width plus a pointer's slack in CSS pixels, divided by the zoom.
Where edges cross or fan into a node the nearer centreline wins, and an exact
tie goes to the later edge. Nodes are drawn over edges, so ask the node index
first and the edge index only on a node miss. Dashes are not gaps, and the
index tests straight segments, which is what a 'polyline' group (the one
DagrCanvas declares) draws. A provider answers an edge as
{ kind: 'edge', edgeId }, and the shared interaction selects it under the
same press-and-release rule as a node.
onEdgeClick(edgeId) and onEdgeHover(edgeId | null) make the
drawn edges hit targets on DagrCanvas through that index, rebuilt when the
drawn edges change, so while edges glide it tests the frame's points. The
tolerance is half the ribbon's width plus the same 4 or 22 CSS pixels of
slack a node gets. A node always wins, so a press on the end of an edge where
it meets its node is the node's, and hover reports null to onEdgeHover
when the pointer moves onto a node. Edges are tested on the CPU in both
hitTesting modes, after the node test misses: under 'gpu' that means after
a settled pick says no node. Without either handler an edge is not a target,
so a click on one stays a background click. With onEdgeHover and no
onEdgeClick, a click on an edge reports nothing rather than a background
click, as a click on a node does without onNodeClick. With onEdgeClick set, hover over
an edge sets cursor: pointer.
hitTesting="gpu" answers mouse hover and clicks from the
renderer's pickNode instead of the CPU index, through
createPickedNodeHitProvider (previous section), so it carries that provider's
limits: a press on a point that was not hovered first, a release that moved,
and a click while nodes glide are ignored, and hover holds its last answer
until the pick at a resting pointer settles. Each draw asks the resting pointer
again, so after a wheel zoom or a flight a click lands without moving the
mouse, and while nodes glide or the camera flies under it, picks run back to
back, one at a time, until the drawing rests. Hover primes the picks, so
onBackgroundClick or an edge handler alone is enough to start them. Touch and pen keep the CPU
index, touch with its fingertip tolerance, since a tap, or a pen that does not
report hover, has nothing picked before it. A renderer rebuilt after a lost
context starts with no picks rather than answering from the lost one's. The
default stays 'cpu' because of the ignored presses and clicks, not the pass's
cost.
Camera control. apiRef (and useDagrCanvas() inside the canvas) gives the
methods below. It is apiRef rather than ref on purpose: ref on a React
component reads as the DOM element, and this is an imperative API object; it
accepts a ref object or a callback, and is null until the canvas has mounted.
The flight is stepped from the component's own coalesced frame, so it shares
drawing's frame budget.
| Method | Does |
|---|---|
focusNode(id, { zoom?, durationMs? }) | Flies to centre the node. Default zoom makes the node fill about half the frame inset leaves. Returns false and moves nothing for an unknown id or an unsized canvas. |
fit({ durationMs? }) | Flies back to the whole graph, including group boundaries, with fitPadding. Returns false, moving nothing, before there is a layout and a size. |
Flights take 450 ms (zoom is interpolated geometrically, so it feels even) and
jump instantly under prefers-reduced-motion: reduce; pass durationMs: 0 to
jump. Every intermediate view passes through the camera's limits, so a target
outside them lands on the nearest legal view. The camera itself
(renderer.camera, a Camera2D) remains available from the handle for anything
else, such as reading camera.zoom to drive a zoom readout from onFrame.
Keyboard access to nodes. Canvas shortcuts are the keyboard story for the
camera. For the nodes, give your tier elements tabindex="0" (and an accessible
name): every element a tier creates is tagged with data-dagr-node-id, and
Enter or Space on a focused tagged element that is not already a native control
calls onNodeClick with that id (only when onNodeClick is set; otherwise the
keys are left alone). When onNodeClick is set, a tier element without its own
role or tabindex gets role="button" and tabindex="0", so it is reachable
and announced. Focus survives the overlay. Cards are removed or pooled when
they leave the view or their tier gives way to another; the canvas remembers the
node whose card held focus and, on the next frame, moves focus to that node's
new element, or to the canvas itself (preventScroll) if the node has none. It
stops as soon as you focus something outside the canvas. A native <button> inside a card activates
through its own click, as it should. Only nodes in view mount elements, so Tab
moves through what is on screen; the GPU shapes below the first tier are not in
the tab order, and a host that needs a complete keyboard path to every node
should offer a list or search beside the canvas and call focusNode.
Context loss and failure
If the GPU device (WebGPU) or context (WebGL 2) is lost after drawing began (a
driver reset, a GPU process crash, a mobile tab whose GPU memory was reclaimed),
onContextLost({ backend, reason }) fires and the canvas rebuilds its renderer
by itself, restarting from a fresh camera fit. More than three losses in ten
seconds stops the rebuilding and reports the failure through onError. If the
renderer cannot be built at all, the default is still to throw to the nearest
error boundary; pass fallback={<List />} to render a plain alternative in
place instead (onError still fires). React StrictMode is supported: the
renderer the dev double-mount abandons is aborted and disposed.
CPU cost of picking
Measured 2026-10-03 on the same Apple M4 and Node v25.6.1 as the M5.2a
baseline, on a grid of mixed circles and rounded rectangles: a query is about
0.00008 ms (the median is the clock's resolution here, so it is not gated) at
100, 1,000 and 10,000 nodes alike, because the grid makes it independent of
node count. Building the index for 10,000 nodes takes about 1.9 ms. It is built
lazily on the first pointer event after the drawn nodes change, so during an
animate glide a 10,000-node scene pays that 1.9 ms on the frame a click lands
and, with a moving pointer, at most once per 100 ms for hover; a static scene
pays it once per edit. That is CPU time for the query,
not browser frame time or GPU evidence, and the entries are recorded in
bench/README.md
without a gate; adding them to the baseline is the maintainer's call.
Level of detail: node tiers
nodeTiers makes a node's presentation depend on how big it is on screen,
which is how a graph of thousands of nodes stays cheap when zoomed out and rich
when zoomed in:
const nodeData = useCallback((id: string) => items.get(id) ?? EMPTY_ITEM, [items]);
const tiers = useMemo<RichNodeTier<Item>[]>(() => [
{ name: 'label', minScreenWidth: 28, maxScreenWidth: 300,
create: () => document.createElement('div'),
update: (el, { data }) => { el.textContent = data.title; } },
{ name: 'card', minScreenWidth: 300, interactive: true,
create: makeCardElement, update: fillCard },
], []);
<DagrCanvas graph={graph} navigation nodeTiers={tiers} nodeData={nodeData} />
The tiers are the same RichNodeTier the renderer's rich nodes
use, gated by the node's width in CSS pixels at the current zoom and disjoint
by construction (overlapping gates throw). Below the lowest minScreenWidth
there is no tier, so the node is just its instanced GPU shape: no DOM at all.
Between gates exactly one tier's element is mounted, and only for nodes
currently in view up to the overlay's cap; elements are pooled across a pan,
so update must fully overwrite what the previous node left. The two props are a typed pair: tiers over your own data type
(RichNodeTier<Item>) require nodeData, and the compiler rejects them without
it; tiers over RichNodeTier<string> may omit it and receive the node id.
nodeData maps a node id to the value each tier's update receives as
node.data, and an entry whose value is not the same reference as last
time is re-rendered. nodeTiers is compared by identity, so memoise it. Return the same object
from nodeData for an unchanged node: a fresh object each call re-renders every
visible tier on every animated frame. Hover is evaluated on pointer movement
only, so it can lag a node that moves under a still cursor (keyboard pan, a
flight, an animation).
Tiers follow the nodes as drawn, so with animate a card glides with its
node. Each animated frame feeds only the nodes whose box changed and calls
nodeData once per node (not per frame); the frame an animation settles on
replaces the whole set. A local run with 10,000 nodes and 100 in motion measured the incremental feed
about 7x faster than rebuilding all of it (taken on a loaded machine, so
indicative, not gated; CPU time only). A tier is plain DOM; to render React into one, create a root in create
and render from update, and unmount the roots you created when you drop the
tiers. A first-class React tier helper is not shipped yet.
Pair the tiers with navigation and the camera limits above: the maximum zoom
is the smallest node filling the viewport, so the richest tier is always
reachable.
Known limits of this slice
- Hover is evaluated on pointer movement and reuses a node or edge hit index up to 100 ms old while the drawing glides; clicks always use the index of what is drawn.
- Overlay tiers have a cap on mounted elements, but there is no per-frame budget
for how many mount at once when a pan reveals many nodes, and
onFrameis called only on animated frames, not on plain pans. - Camera flights use a fixed 450 ms ease-in-out with a straight centre path and
geometric zoom. A long flight across a large graph does not zoom out and in
(the van Wijk path); call
fit()thenfocusNode()if you want that. - Resizing the canvas can show a stale frame for one frame before the next draw.
cursoris written directly on the canvas element while a node is hovered.
When there is no GPU
createRenderer already prefers WebGPU and falls back to WebGL 2 on its own, so
most phones that lack WebGPU still draw, and renderer.backend reports what you
got. What nothing can fix is a device with neither, or a GPU process that
crashes. Handle it in two places:
import { detectBackendSupport } from '@prnt/dagr-render';
const support = await detectBackendSupport();
if (support.preferred === null) return <StaticFallback />; // list, table, image
detectBackendSupport() (memoised for the page) asks for a WebGPU adapter (not just navigator.gpu,
which many devices expose with no adapter behind it) and tries a throwaway
WebGL 2 context, and never throws. detectBackendSupport({ gpu, createCanvas, strict: true }) also refuses a
software-rendered WebGL 2 context (failIfMajorPerformanceCaveat), which
reports as available and draws a large graph at a few frames per second; pass
the real browser objects, or omit the environment to use the page's. It says what can start, not that your scene
will run well: a low-end phone on WebGL 2 draws the same graph more slowly, and
no benchmark here speaks for it. The other half is onError: a layout that fails or a device that never
arrives is reported there instead of thrown, so a host can swap in the same
fallback when the canvas dies late. Keep the fallback content-equivalent (a list
of the same items with the same details panel), since the graph is a view of the
data and not the only way to reach it.
What is not here yet
- Port hits (edges stay on the CPU). Exact CPU node hits ship with
DagrCanvas. Ports are M6.3a. GPU node picks are opt-in throughhitTesting="gpu"(M4.8b), priced on AMD RDNA 2 and Apple M4 at no more than 0.2 ms of CPU per pick at the median. Edge hits onDagrCanvasare CPU only. At 10,000 nodes a query takes 0.2 ms or less, but rebuilding the index while edges glide took 2 ms at one segment per edge and 12 to 14 ms at three, on one device. A cheaper build since takes 1.8 ms at one segment per edge and 4.8 to 4.9 ms at three on the same device. Paid every frame at three, it still misses ticks, butDagrCanvaspays it only on a click's frame and at most one hover frame in six while edges glide, so edges stay on the CPU (seebench/browser/README.md, "What an edge hit costs a frame"). - A React tier helper. Tiers are DOM elements. Rendering React into them is possible by hand and not wrapped.
- Tile-at-a-time layout. The campaign demo's worker layout is specific to its tile packer and is not exposed (see the roadmap's M7 for the generic version).
- A node ontology. What a node looks like is a callback and it stays one. Deciding that a node of kind X draws as a hexagon belongs to the visual-language toolkit, which is scoped precisely so that Dagr ships no ontology of its own.
Default navigation limits
DagrCanvas constrains its camera by default. The minimum zoom fits the complete
graph, including group labels and padding. The maximum fits a single node with
5% margin (or fitPadding); for mixed node sizes the smallest fitting node sets
the ceiling. Panning stays within the padded content bounds and keeps part of an actual node
visible, including in sparse graphs. An axis smaller
than the frame stays centered. Limits follow resizing, layout changes, and
animated bounds without resetting a valid close-up.
inset={{ right: 320 }} tells the canvas that something drawn over it covers
that much of a side, such as a details drawer or a toolbar. The first fit,
fit(), focusNode and these limits then frame the rest, so the graph is not
fitted under the drawer. An inset that would leave less than 160 CSS pixels of
width (120 of height), or less than a quarter of that axis, is ignored on that
axis. Keyboard zoom anchors at the frame's centre. Drawing and hit testing
still cover the whole canvas, and changing the inset keeps a camera at rest,
only re-clamping it. A fit() or focusNode flight still under way works its
target out again in the new frame and lands when it would have, so a handler
that opens a drawer, passes it as inset and calls focusNode ends with the
node in the middle of what the drawer leaves. One that lands at once
(durationMs: 0, or any flight under prefers-reduced-motion: reduce) has
nothing left to retarget, so calling it once the new inset has rendered, for
example from an effect, is the pattern that works for everyone. A flight under way retargets the same way when the canvas resizes.
The canvas also observes the visual viewport and leaves out what it hides of
the canvas beyond the layout viewport, such as the part of the page a software
keyboard covers without resizing it, taking the larger of that and inset on
each side. It too keeps the camera, and the page's own pinch-zoom takes
nothing off. See the mobile guide.
fit={false} only skips the initial fit. Use cameraLimits={false} to opt out
of content constraints when implementing a custom camera policy. Low-level
Camera2D instances remain unrestricted until setContentBounds is called.
Edge path styles
edgePath changes the visible route without rebuilding the renderer. It applies
on every animation frame, so orthogonal edges keep right-angle bends during edits.
<DagrCanvas graph={graph} edgePath={{ style: 'smooth' }} />
<DagrCanvas graph={graph} edgePath={{ style: 'orthogonal', direction: 'vertical' }} />
The default polyline preserves routed segments. smooth curves through route
anchors; two-anchor edges use a cubic with horizontal tangents by default.
orthogonal inserts axis-aligned doglegs between anchors. direction can be
horizontal or vertical; smoothing tolerance defaults to 0.5 world units.
These are visual transformations, not obstacle-aware routing, so either style
can introduce crossings or overlap nodes. Layout positions remain unchanged.
SVG or canvas consumers can use shapeEdgePath(points, options) from
@prnt/dagr/render (or @prnt/dagr-render) for the same geometry. Feed its
returned points to an SVG polyline/path or to renderer edges with curve: 'polyline'
to avoid smoothing them twice.
Shared mobile foundation
DagrCanvas and Explorer consume the same three.js-free pinch primitive.
The first two touches remain the active pair when an extra finger arrives;
cancellation ends the pair, and so does lost capture on the surface itself
(a child element such as the <canvas> losing a touch's implicit capture is a
handover, so the pinch continues). Coincident fingers pan without a zoom
spike. Existing touchNavigation modes and their browser-scroll tradeoffs
remain unchanged. See Mobile architecture for the public core
API, layer boundaries and remaining viewport/device validation work.