Skip to content

Recipes

Four complete, runnable integrations. Each was executed against this package’s current src/ and the output shown is what it actually produced — see the individual notes for how.

Recipe 1: headless rendering in a CLI/CI job

Section titled “Recipe 1: headless rendering in a CLI/CI job”

Parse, lay out, and emit SVG in one call — no browser, no jsdom, DOM-free (though it does need react/react-dom installed; see Architecture for why).

import { renderC4DiagramToSVG } from '@liminis/diagrams/server';
const source = `
Person(user, "User", "End user")
System(app, "App", "Main app")
Rel(user, app, "Uses", "HTTPS")
`;
const { svg, errors } = renderC4DiagramToSVG(source, /* isDarkMode */ false);
if (errors.length > 0) {
console.error(errors);
process.exit(1);
}
console.log(svg);

Verified output (errors is []; svg is 1762 characters):

<svg width="320" height="394" viewBox="0 0 320 394" xmlns="http://www.w3.org/2000/svg" data-diagram="c4" style="font-family:system-ui, -apple-system, sans-serif"><g class="boundaries-layer"></g><g class="nodes-layer"><g><circle cx="160" cy="66" r="14" fill="#006b2d" stroke="#004b1e" stroke-width="1...

If parseC4 or validateC4 fail internally, renderC4DiagramToSVG returns { svg: '', errors } rather than throwing — always check errors before using svg.

Recipe 2: embedding C4InteractiveRenderer in a non-editor host

Section titled “Recipe 2: embedding C4InteractiveRenderer in a non-editor host”

C4InteractiveRenderer is a controlled component: it takes manualPositions in as a prop and calls onPositionChange out during/after a drag. It holds no persisted state of its own — the host owns manualPositions and decides what to do when the callback fires (nothing, useState, write to disk, debounce a network call, etc.).

import { useState } from 'react';
import { parseC4 } from '@liminis/diagrams/core';
import { C4InteractiveRenderer } from '@liminis/diagrams/react';
function DiagramHost({ source }: { source: string }) {
const { diagram } = parseC4(source);
const [positions, setPositions] = useState<Record<string, { x: number; y: number }>>({});
if (!diagram) return null;
return (
<C4InteractiveRenderer
diagram={diagram}
isDarkMode={false}
isEditMode={true}
manualPositions={positions}
onPositionChange={setPositions}
/>
);
}

With manualPositions={{}} (nothing set yet), the renderer lays the diagram out with dagre and lets you drag any node; each drag calls onPositionChange with the complete new positions map (not just the moved node — the first drag also seeds every other node’s current auto-layout position into the map, so manualPositions after any drag is enough on its own to reproduce the layout without dagre).

Verified: rendering DiagramHost with isEditMode={true} produces one draggable hit area (an SVGRectElement with data-node-id) per top-level and nested node — for a two-element diagram (user, app), container.querySelectorAll('[data-node-id]') returns exactly ['user', 'app']. Passing manualPositions={{ user: { x: 500, y: 500 }, app: { x: 900, y: 500 } }} and re-rendering places user’s hit area at exactly x="500" y="500" in the rendered SVG — confirming positions flow from the host’s state straight through to what’s drawn, with no intermediate transformation.

Recipe 3: position persistence — the host’s choice

Section titled “Recipe 3: position persistence — the host’s choice”

This package never writes anything to disk, a database, or anywhere else. manualPositions is a plain Record<string, { x: number; y: number }> — how you store it is entirely up to you. The simplest possible approach is to serialize it as JSON:

const positions = { user: { x: 10, y: 20 }, app: { x: 300, y: 20 } };
const stored = JSON.stringify(positions);
// stored: '{"user":{"x":10,"y":20},"app":{"x":300,"y":20}}'
// ...later, from wherever you stored `stored`...
const restored: Record<string, { x: number; y: number }> = JSON.parse(stored);
// restored deep-equals positions — verified round-trip

Pass restored back in as manualPositions (Recipe 2) or as the third argument to layoutC4Diagram (Recipe 1’s lower-level building block) to render with the saved layout instead of dagre’s auto-layout.

One worked example: how @liminis/editor does it

Section titled “One worked example: how @liminis/editor does it”

This is @liminis/editor’s own decision, not something @liminis/diagrams does or requires. It’s included here as one concrete answer to “where would I actually put this,” not as this package’s behavior.

@liminis/editor stores positions in the meta string of the markdown code fence that holds the C4 source — the same place a fenced code block’s language tag lives, as the text following the language on the fence’s opening line (e.g. the part after c4 in an opening fence tagged c4). On write, if there are any manual positions, it serializes them as @layout followed by JSON:

// verveguy/liminis-editor, src/app/mapper/lexicalToMdast.ts — convertC4Node()
const manualLayout = node.getManualLayout(); // { positions: {...} } | undefined
const meta = manualLayout && Object.keys(manualLayout.positions).length > 0
? '@layout ' + JSON.stringify(manualLayout)
: undefined;

producing a fence meta string like:

@layout {"positions":{"user":{"x":10,"y":20},"app":{"x":300,"y":20}}}

On read, src/app/mapper/mdastToLexical.ts’s extractC4LayoutFromMeta looks for the @layout prefix, JSON.parses the rest, and validates every position has finite numeric x/y before trusting it — falling back to undefined (auto-layout) on anything malformed:

function extractC4LayoutFromMeta(meta: string | null | undefined): ManualLayout | undefined {
if (!meta?.startsWith('@layout ')) return undefined;
try {
const raw = JSON.parse(meta.slice('@layout '.length));
// ...validates raw.positions[key].x/.y are finite numbers...
return raw as ManualLayout;
} catch {
return undefined;
}
}

Verified: the round-trip '@layout ' + JSON.stringify({ positions }) → meta.slice('@layout '.length) → JSON.parse(...) reproduces the original positions object exactly, for the example above.

The advantage of this approach, specific to @liminis/editor’s context: it keeps a hand-arranged diagram’s positions in the same plain-text, line-diffable markdown file as the diagram source, with no sidecar file and no binary blob. If your host isn’t a markdown editor, this is not the right storage format for you — pick whatever fits your host (a database column, a separate JSON file next to the source, a CRDT document, whatever). The only contract this package cares about is the shape: Record<string, { x: number; y: number }>.

Recipe 4: adding elements and relationships — the host’s responsibilities

Section titled “Recipe 4: adding elements and relationships — the host’s responsibilities”

Available from 0.2.0. The docs-site playground and the demo are pinned to the published package, so they do not show this yet.

The renderer can add, rename and re-parent things; it never changes your source and never writes anywhere. It reports an edit, you apply it. This is the same controlled pattern as onPositionChange, and it means undo, persistence and conflict handling are whatever your host already has.

In edit mode, and only when you pass onEdit, C4InteractiveRenderer offers these things. (A host that passes isEditMode for dragging alone sees no change at all.)

  • Add an element. Right-click empty canvas — or inside a boundary to add it there — to open a menu of kinds (Person, System, Container, Component, and the Db variant of System, Container and Component). On touch, which has no right-click, press and hold for about half a second without moving: the same menu opens. Moving the finger further than a few pixels cancels the press, so a drag never opens a menu. Choosing a kind places the element at the point you opened the menu, then a label input appears over it. Enter confirms (an empty label falls back to a placeholder); Escape or losing focus cancels and reports nothing. The menu itself closes on Escape, a click outside it, or pointercancel of the pointer that opened it, and reports nothing. While editing is on the browser’s own context menu is suppressed over the diagram; a read-only render, and a host that passes isEditMode without onEdit, keep it. (A host that already has its own context menu passes onContextMenu instead, and the renderer draws no menu of its own: see “One menu, not two” below.)
  • Add a boundary. The same menu has a second group, set apart by a rule and a small heading, listing the boundary kinds: System boundary, Container boundary and Boundary (System_Boundary, Container_Boundary, Boundary). The label flow is the same as for an element. It adds an empty boundary where you opened the menu: at top level on empty canvas, or nested in the innermost boundary containing the point. An empty boundary is drawn as a visible, dashed box (at least 240×160), so you can right-click inside it and add an element, or another boundary, with the flow above. A boundary nested inside another is kept within its parent’s content area, so the parent does not move. Boundaries have no connect handle and cannot be relationship endpoints. Wrapping existing elements in a new boundary is not offered.
  • Add a relationship. Drag from the dot on an element’s right edge to another element. On release a label input appears near the midpoint of the new edge, pre-filled with “Uses”: Enter confirms (empty falls back to “Uses”), Escape or losing focus cancels and reports nothing, and the source is untouched until then. Releasing on empty canvas, on a boundary, or on the same element shows no input and reports nothing. Boundaries cannot start or end a relationship in this first cut. This labels the new Rel only.
  • Rename an element or a relationship. Double-click an element, or a relationship’s label, and the same label input opens over it, pre-filled with the current label (for a relationship, the label argument without its technology). On touch, tap an element to select it and choose Rename in the small bar beside it (a long-press on an element no longer renames: a pause before dragging must not turn the drag into a rename), or press and hold a relationship label for about half a second without moving. Enter confirms; Escape or losing focus cancels. Nothing is reported when the label is unchanged, and an empty label falls back to a placeholder (“Uses” for a relationship, the type’s name for an element). A relationship with no label can be renamed by double-clicking its line. Boundaries are not renamed from the diagram: a long-press on one still opens the add menu.
  • Move an element or boundary into or out of a boundary (re-parent). Release a dragged element, or a whole boundary, over another boundary and it becomes that boundary’s child (the innermost boundary under the pointer wins). While dragging, the boundary that would receive the drop is drawn with a dashed accent outline. Hold ⌥ (Alt) while dragging a child to lift it out of its boundary: released on empty canvas it goes to the top level, released on another boundary it goes into that one. ⌥ is read at the moment of release. A plain drag inside the current boundary only repositions, and the boundary grows, as before. Dropping a boundary on itself or its own descendants does nothing structural. pointercancel or Escape abandons the drag with no edit and no position change. On touch (no ⌥ key), tap an element to select it: a bar appears beside it with Rename and, if it has a parent boundary, Move out, which moves it to the top level where it is. A nested boundary offers Move out too. Tap empty canvas or press Escape to deselect. The bar is for touch and pen; a mouse keeps double-click and ⌥-drag. A re-parent drop reports through onEdit only, never onPositionChange.

The menu opens over empty canvas or a boundary, not over an element, a connect handle, a relationship label or the legend (the native menu is still suppressed there). With onContextMenu the host is still called on all of those, with no items.

Dragging a node still moves it; the connect handle is a separate target, and the two gestures are mutually exclusive. All of it uses pointer events and handles pointercancel. The handle sits on each node’s right edge with a touch target of about 16 SVG units, so the strip of a node just inside its right edge starts a connection rather than a move; grab the node anywhere else to move it.

onEdit(edit, { positions }) gives you two things, and you must do both in the same update:

  1. Apply edit to your source text with applyC4Edit from ./core. It is headless — no React — so the same call works from a test, a CLI or an agent.
  2. Store positions, replacing your own map. It is already the merge you want: your current manual positions (untouched), plus the current position of every node that had none, plus the new element at the spot the user placed it. Pinning every visible node is what stops the automatic layout reshuffling when a node is added. Merge, don’t clear. A host that resets its layout whenever the set of element ids changes (as @liminis/editor’s C4Component.tsx does today) throws away every arranged position the moment one box is added; that behaviour has to become a merge before this feature is usable there.

Apply both together. If the new text lands a frame before the new positions, the diagram renders the new element at the bottom of the stacked column and then jumps. In a plain useState host this is free (React batches two setters in one handler); in a host that updates asynchronously, make sure the two arrive in one update.

import { useState } from 'react';
import { parseC4, validateC4, applyC4Edit } from '@liminis/diagrams/core';
import { C4InteractiveRenderer } from '@liminis/diagrams/react';
import type { C4Edit } from '@liminis/diagrams/core';
import type { C4EditContext } from '@liminis/diagrams/react';
function EditableDiagram({ initial }: { initial: string }) {
const [text, setText] = useState(initial);
const [positions, setPositions] = useState<Record<string, { x: number; y: number }>>({});
const [error, setError] = useState<string | null>(null);
const parsed = parseC4(text);
const errors = parsed.diagram ? validateC4(parsed.diagram) : parsed.errors;
// Nothing to click while the text does not parse, so editing is unavailable.
if (!parsed.diagram || errors.length > 0) return <pre>{text}</pre>;
const onEdit = (edit: C4Edit, context: C4EditContext) => {
const result = applyC4Edit(text, edit);
if (!result.ok) {
setError(result.message); // e.g. a boundary that cannot take a new line
return;
}
setError(null);
setText(result.source); // 1. the new source text...
setPositions(context.positions); // 2. ...and the merged positions, in the same update
};
return (
<>
{error && <p role="alert">{error}</p>}
<C4InteractiveRenderer
diagram={parsed.diagram}
isDarkMode={false}
isEditMode
manualPositions={positions}
onPositionChange={setPositions}
onEdit={onEdit}
/>
</>
);
}

This is C4Playground’s own wiring, and the playground’s end-to-end test (src/playground/C4Playground.test.tsx) drives exactly this: add a top-level element, add an element inside a boundary, add a boundary and then an element inside it, connect two elements, diffing the source each time.

Verified by that test: each action inserts exactly one contiguous block (one line, or two for a boundary) and no other line changes; previously positioned elements keep their positions; the first edit on a diagram with no manual positions moves no element.

If your host already has a context menu on the diagram, the renderer’s own menu would open beside it. Pass onContextMenu and the renderer draws no menu: it hands you the click position and the diagram’s actions, and you show one menu with your items and its together.

Available from 0.2.1. The docs-site playground is pinned to the published package and has no host menu of its own to merge into, so it does not demo this; the snippet below is the whole recipe.

import { useState } from 'react';
import { C4InteractiveRenderer } from '@liminis/diagrams/react';
import type { C4ContextMenuRequest } from '@liminis/diagrams/react';
function DiagramWithMenu(props: React.ComponentProps<typeof C4InteractiveRenderer>) {
const [menu, setMenu] = useState<C4ContextMenuRequest | null>(null);
return (
<div onContextMenu={(e) => e.preventDefault() /* never reached over the diagram: the renderer stops it */}>
<C4InteractiveRenderer {...props} onContextMenu={setMenu} />
{menu && (
<div role="menu" style={{ position: 'fixed', left: menu.clientX, top: menu.clientY }}>
<button role="menuitem" onClick={() => { copyImage(); setMenu(null); }}>
Copy image to clipboard
</button>
{(['element', 'boundary'] as const).map((group) => {
const items = menu.items.filter((i) => i.group === group);
return items.length > 0 && (
<div role="group" aria-label={group === 'element' ? 'Add element' : 'Add boundary'} key={group}>
{items.map((item) => (
<button
role="menuitem"
key={item.id}
onClick={() => {
setMenu(null); // close first: the label prompt takes focus
item.select();
}}
>
{item.label}
</button>
))}
</div>
);
})}
</div>
)}
</div>
);
}

What to know:

  • items is [] where the diagram has nothing to add: over a node, a relationship label, a connect handle or the legend, outside edit mode, and in edit mode without onEdit. The hook is still called there, so your own items are reachable everywhere. Show your menu with whatever items holds.
  • Each item has a stable id (add:element:person, add:boundary:systemBoundary, …), the same label as the built-in menu, and a group (element or boundary; elements come first). select() does what choosing it in the built-in menu does: places the new element centred on the point you were called for (inside the enclosing boundary if there is one), then shows the label prompt and, on Enter, reports the edit through onEdit.
  • Long-press (touch and pen, edit mode only) calls the same hook with pointerId set. Outside edit mode there is no long-press: use your own gesture for a touch menu.
  • Close your menu, and return focus, when an item is picked. The label prompt the renderer shows cancels when it loses focus, so a menu that keeps focus after select() would cancel it at once. You own closing it, too: the renderer keeps nothing between the call and select(), so a menu you dismiss without choosing leaves nothing behind.
  • The renderer stops the event. It calls preventDefault() and stopPropagation(), so a React onContextMenu on an ancestor does not fire a second menu. React listens at the root, so a native addEventListener('contextmenu') on a non-root ancestor element still sees it. A right-click during a drag or a connect is swallowed without a call.
  • Without onContextMenu nothing changes.
import { applyC4Edit } from '@liminis/diagrams/core';
const source = `@startuml
Person(user, "User")
System(app, "App")
Rel_D(user, app, "Uses", "HTTPS")
@enduml`;
const r = applyC4Edit(source, { kind: 'add-element', elementKind: 'system', label: 'Billing' });
// r = { ok: true, source: <...>, insertedLine: 'System(billing, "Billing")', label: 'Billing', alias: 'billing' }

The result source is the input with one line (or, for add-boundary, one two-line block) inserted after the last top-level element or boundary (wherever that sits relative to any Rel lines, and always before @enduml). An element with parent set to a boundary id goes inside that boundary’s { ... } block, indented like its siblings. A add-relationship edit inserts one Rel(source, target, "label") line after the last top-level Rel.

add-boundary adds an empty boundary, the one edit that inserts more than a single line: an opening line and a closing }, together at one point. “Exactly one line” is therefore “exactly one contiguous block” for this kind only; no existing line changes.

const b = applyC4Edit(source, { kind: 'add-boundary', boundaryKind: 'containerBoundary', label: 'API Application' });
// b = { ok: true, source: <...>, label: 'API Application', alias: 'api_application',
// insertedLine: 'Container_Boundary(api_application, "API Application") {',
// insertedLines: ['Container_Boundary(api_application, "API Application") {', '}'] }
// The new boundary can take children straight away:
applyC4Edit(b.source, { kind: 'add-element', elementKind: 'component', label: 'Controller', parent: 'api_application' });

boundaryKind is systemBoundary, containerBoundary or boundary; parent nests it in an existing boundary. Alias, label, indentation and the error codes behave exactly as for add-element, and the closing } is aligned with the opening line. Every successful result carries insertedLines (one element for the other kinds); insertedLine is the first of them.

Failures are returned, not thrown: { ok: false, code, message }, where code is one of parse-error, unknown-parent, unknown-endpoint, boundary-cannot-take-children (a boundary with no braces, a single-line { }, or an unterminated block: adding a child would mean rewriting an existing line), alias-collision, invalid-alias, self-relationship, invalid-result.

// An element into a boundary:
applyC4Edit(source, { kind: 'reparent', id: 'worker', parent: 'backend' });
// A boundary (with every child) or an element out to the top level:
applyC4Edit(source, { kind: 'reparent', id: 'worker' });

The element’s line, or a boundary’s whole block from its opening line to its closing }, is removed and re-inserted at the end of the destination: immediately before the new parent’s closing }, or for the top level after the last top-level element or block (the same rule as adding). Every moved line is re-indented by one uniform amount to the destination’s sibling indent (the last sibling’s, else the parent’s plus one unit; blank lines stay blank), so a block keeps its internal structure. Nothing else changes: comments (including ones directly above the moved line, which stay where they are), Rel arguments, direction variants, CRLF and every untouched line are byte-identical, and no alias changes, so relationships and manual positions keyed by alias survive. Rel lines written inside a moved boundary’s block move with it. Moving an element to the parent it already has returns the source unchanged.

The result reports the moved lines as they now read in insertedLines (insertedLine is the first), with alias set to the moved id and label to its name.

Failures are returned, not thrown, with the source untouched: unknown-element (no such id), unknown-parent (the parent does not exist or is not a boundary), boundary-cannot-take-children (the parent has no multi-line { ... } block), move-into-self (a boundary moved into itself or one of its descendants) and invalid-result: the result is re-parsed and must have the same elements, relationships and parents, with only the moved id under its new parent. A block whose shape does not survive a move, such as an unterminated boundary, fails here instead of mis-nesting its children.

The host’s duties are those of any edit: apply edit to your source and store context.positions in one update, and show message when ok is false (a rejected edit leaves the diagram showing the dropped position until the next drag).

// An element, by alias:
applyC4Edit(source, { kind: 'rename', target: { element: 'app' }, label: 'Billing' });
// A relationship, by index into `diagram.relationships`, plus what you saw there:
applyC4Edit(source, {
kind: 'rename',
target: { relationship: { index: 0, sourceId: 'user', targetId: 'app', label: 'Uses [HTTPS]' } },
label: 'Calls',
});
// r.source = ... Rel_D(user, app, "Calls", "HTTPS") ...

A rename replaces only the characters of the label argument on one line, written quoted. The alias, description, technology, tags, macro variant (Rel_D, ContainerDb, _Ext), spacing, trailing comment and every other line are byte-identical, so manual positions (keyed by alias) never move. An empty or whitespace-only label falls back to the placeholder; renaming to the current label returns the source unchanged. A boundary’s alias is accepted too, since its label is the same argument.

Relationships have no alias, so the target is their position in the parsed list plus the sourceId, targetId and label (the combined label [technology] string, exactly C4Relationship.label) that you saw there. applyC4Edit re-parses your text and only proceeds if the relationship at that index still matches, so a stale edit fails rather than patching a different line. The renderer reports exactly this target. If you build one yourself, take it from the same text you pass to applyC4Edit.

Rename’s failures are unknown-element (no such alias), stale-target (the relationship at that index no longer matches), no-label-argument (the line has no plain label argument to replace: for example Person(a), or a $label=… named argument — rewriting it would drop the keyword) and invalid-result, besides parse-error. A Rel with fewer than three arguments does not parse at all, so it is a parse-error. The host’s duties are the same as for any edit: apply edit to your source and store context.positions, in one update.

Four guarantees worth relying on:

  • The source stays canonical. An add is an insertion (one line, or one two-line block for a boundary) at a character offset, a rename splices one label argument, and a re-parent moves one block (re-indented, nothing else touched). No other byte changes: comments, Rel technology arguments, Rel_D-style variants, !include, title, SHOW_LEGEND() and LAYOUT_* all survive, and CRLF files get CRLF. The parsed model is lossy and is never re-serialised.
  • The result parses. Every returned source is re-parsed before it is returned. For a rename that also means the same elements, aliases and relationships, with only the target’s label changed, and for a re-parent the same elements and relationships with only the moved id under a new parent.
  • Aliases are unique and valid. Without alias one is generated from the label (Cache → cache, then cache_2, …), avoiding every existing id, macro names and the reserved __legend__. The renderer decides the alias itself because positions are keyed by it; if you pass one and it collides with your current text, you get alias-collision rather than a silent rename (which would orphan the position).
  • Labels are made safe, not rejected. The parser does not un-escape and PlantUML has no escape for ", so inside a quoted argument " becomes ', \ becomes /, and control characters become spaces. The result reports the label as written.

The add menu is the package’s only built-in control. It uses inline styles and reads --c4-accent, --c4-border and --c4-bg, and it carries data-c4-menu for targeting. It has two role="group"s: element items carry data-kind, boundary items carry data-boundary-kind. It replaces the toolbar palette (data-c4-palette) of earlier drafts, which no longer exists. The inline label inputs — for an element and for a relationship, and for a boundary — carry data-c4-label-input.

Recipe 5: a scrolling host absorbs the origin shift

Section titled “Recipe 5: a scrolling host absorbs the origin shift”

While a node is dragged past the top or left edge the frame grows and the diagram origin moves inside the <svg>’s box. By default the renderer cancels that with a temporary CSS transform on the <svg>. A transform paints outside the element’s layout box, so a host whose container clips (any overflow other than visible) cuts off the grown strip, including the node being dragged, until release. Down and right never have this problem, because the box simply grows.

To make all four edges behave alike, opt out of the transform and scroll by the amount the origin moved:

Available from 0.2.2.

import { useRef, useState } from 'react';
import { parseC4 } from '@liminis/diagrams/core';
import { C4InteractiveRenderer } from '@liminis/diagrams/react';
function ScrollingHost({ source }: { source: string }) {
const { diagram } = parseC4(source);
const [positions, setPositions] = useState<Record<string, { x: number; y: number }>>({});
const scroller = useRef<HTMLDivElement>(null);
if (!diagram) return null;
return (
<div ref={scroller} style={{ overflow: 'auto', height: 600 }}>
<C4InteractiveRenderer
diagram={diagram}
isDarkMode={false}
isEditMode={true}
manualPositions={positions}
onPositionChange={setPositions}
holdOrigin={false}
onOriginShift={({ dx, dy }) => {
scroller.current!.scrollLeft += dx;
scroller.current!.scrollTop += dy;
}}
/>
</div>
);
}

How it behaves:

  • holdOrigin={false}: the renderer never sets a transform on the <svg>, at any edge, during or after a drag. The svg’s box is always the whole drawing, so the container’s scroll extent grows and nothing is clipped or spilled.
  • onOriginShift is called from a layout effect in the same commit as the frame change, so before paint. Scrolling inside it produces no visible jump.
  • dx and dy are rendered CSS px (user-space shift times the rendered scale, so correct when your CSS or zoom shrinks the svg), and are the displacement since the previous commit, not a running total. Positive means the origin moved right/down, so adding them to the scroll offsets keeps it still.
  • It is only called while a node is being dragged, never for growth at the bottom or right only, and never for a zero shift. Shrinking at the top/left, including a cancel (pointercancel, Escape) that returns to the pre-drag frame, reports the opposite sign, so the same code restores your scroll.
  • It is only called with holdOrigin={false}. In the default mode the renderer’s own transform already compensates, so scrolling as well would compensate twice.
  • Pointer mapping uses the live geometry in this mode, so a scroll that is not exactly the reported amount (browsers round scroll positions, and clamp them) does not leave the node drifting from the pointer.
  • Release causes no extra shift: there is no transform to drop.

If you set holdOrigin={false} and do not compensate (no callback, or nothing to scroll), the drawing shifts on screen as the frame grows. The renderer neither prevents nor works around that.