Fragiola

API: core (@fragiola/flow)

Engine

createFlowEngine binds a model to the DOM. Its options, its actions, reads and questions, its events, and the contract adapters implement.

The engine is one flow on screen. It owns the viewport and writes its transform to the viewport element itself, measures nodes and handles with the root window's ResizeObserver, draws the edges' paths, and runs every gesture (pan, pinch, drag, connect, reconnect, box select, resize, the minimap) on Pointer Events with capture, plus the wheel and the keys. It changes the flow only by running the model's commands, so every middleware sees what a gesture does. It never touches the global document or window: everything goes through the root element.

Flow.Root creates and destroys it; in a React app you reach it with useFlow or a flow ref, and its surface is the same five verbs as the model's:

import { useFlow } from "@fragiola/flow-react";

function ZoomReadout() {
    const { engine } = useFlow<Types, typeof features>();
    return (
        <button type="button" onClick={() => engine.run("fit-view", { padding: 0.2 })}>
            Fit
        </button>
    );
}

createFlowEngine

createFlowEngine<T, F>(model, options?) returns a FlowEngine<T, F>. Give it the root element now (root) or attach it later (engine.adapter.attachRoot, what an adapter does); call destroy() when the flow leaves the screen. A model may have several engines (two views of one flow), each with its own viewport.

FlowEngineOptions (on Flow.Root, every one but root is a prop of the same name):

optiontypedefaultdescription
rootHTMLElementnonethe root element; an adapter may attach it later
defaultViewportViewport{ x: 0, y: 0, zoom: 1 }the viewport it starts at
minZoomnumber0.5the least zoom
maxZoomnumber2the greatest zoom
translateExtentRectnonethe flow rectangle the view stays inside
panOnDragboolean | number[]truea drag on the pane pans: true with the primary button (a touch, a pen), or the mouse buttons listed (0 primary, 1 middle, 2 right; a middle or right pan that moved keeps the context menu out)
panActivationKeystring | null" " (Space)held, a primary drag pans from anywhere, nodes included, and starts no other gesture (a KeyboardEvent.key or .code; not while typing in a field); null for none
panOnScrollbooleanfalsethe wheel pans (Ctrl + wheel zooms); otherwise the wheel zooms
panOnScrollMode"free" | "horizontal" | "vertical""free"which way the wheel pans with panOnScroll (PanOnScrollMode)
panOnScrollSpeednumber1the factor of the wheel's pixels when it pans
zoomActivationKeystring | nullMeta on Apple platforms, Control elsewhereheld, the wheel zooms while panOnScroll is on; null for none
zoomOnScrollbooleantruethe wheel zooms around the pointer
zoomOnPinchbooleantruea two-finger pinch (and a trackpad's) zooms
zoomOnDoubleClickbooleantruea double click on the pane zooms in
zoomStepnumber1.2the factor of zoom-in and zoom-out
fitViewboolean | FitViewPayloadfalsefits the nodes once the root and every visible node have a size: measured, given (width, height) or initial (initialWidth, initialHeight, counted until the node is measured); a fit on initial sizes runs once more when every node is measured, unless the viewport moved in between
interactivebooleantruewhether gestures and keys may change the flow (pan and zoom stay)
onlyRenderVisiblebooleanfalseadapters render only the nodes and edges in view
pathOptionsPathOptionssee Path helpersthe shape of the built-in edge paths
autoPanboolean | AutoPanOptionstruethe viewport pans while a node drag, a connection, a reconnection, a selection box or a resize has its pointer near the root's edge, and the gesture follows the pointer; AutoPanOptions { speed, margin, node, connect, selection, resize }: the pixels a frame at the edge (default 10), how near it starts (default 30 pixels), and each gesture's own switch ({ connect: false } keeps the view still while drawing an edge; each one left out pans; AutoPanGesture names them)
paneClickDistancenumber3how far (in pixels) a press on the pane may move and still be a tap (a click: it clears the selection, pane-click); React Flow's is 0, ours stays 3 so a jittery click still counts
nodeClickDistancenumber3how far a press on a node, an edge or a handle may move and still be a tap (it selects, node-click); with connection({ clickToConnect }) a handle's drag starts only past it
preventScrollingbooleantruethe wheel over the flow never scrolls the page, even when neither zoomOnScroll nor panOnScroll uses it; a data-flow-no-wheel element and the controls keep their wheel
nodesFocusablebooleantruenodes take DOM focus (with keyboard()); a node's own focusable: false still wins
edgesFocusablebooleantrueedges take DOM focus (with keyboard()); an edge's own focusable: false still wins
easing(t: number) => numbera smooth ease in and outhow an animated viewport action (duration) eases (ViewportEasing)
nodeOriginXY{ x: 0, y: 0 }the point of a node's box its position stands at, as shares of its size ({ x: 0.5, y: 0.5 }: its centre); every box the engine derives uses it (rects, handles, edge ends, bounds, fit-view, visible-nodes, the minimap, toolbars, the selection box, drag and resize); a child's position stays its box's top-left corner inside its parent's
nodeExtentRectnonethe flow rectangle every node's box stays inside when dragged, moved by the arrows or resized
elevateNodesOnSelectbooleantruea selected node, and its descendants with it, is drawn above the other nodes (node-z-index-by)
elevateEdgesOnSelectbooleantrue in "auto", false in "basic"a selected edge is drawn above the other edges (drawn-edges); in "auto", above the nodes too (render-layers); an explicit value is honoured; ignored in "manual"
zIndexModeZIndexMode"auto"how nodes and edges stack: "basic" (each by its zIndex, a selected one raised, a child above its parent; the edges always below the nodes), "auto" (the same for nodes; an edge stands at least as high as its ends when one of them is a child, and a selected one is raised, so it may be drawn above nodes), "manual" (only the zIndex values count); see Z-order

The roots of the four adapters take every option but root as a prop of the same name (Vue: kebab-case in a template; Angular: an input of flowRoot) and send a change through engine.adapter.setOptions (Root).

The members

memberdoes
run(action, payload?)runs a screen action; returns a CommandResult (refused, never thrown)
can(action, payload?)whether run would succeed now (a Controls button's disabled state is !engine.can("zoom-in"))
check(action, payload?)what run would return, without doing it
get(key, payload?)reads a fact of the flow on screen
is(key, payload?)asks a yes/no question about it
subscribe(listener)listens to the engine's events; returns its remover
destroy()releases every listener and element; nothing runs afterwards
adapterwhat only an adapter calls (below)

An action's key never has a dot (fit-view), a command's always does (node.move): commands change the document through the model, actions do what only the screen can. The installed features add keys: EngineActionKeyOf<F>, EngineGetKeyOf<F> and EngineIsKeyOf<F> are those of an engine whose model has the features F. EngineActionMap, EngineGetMap<T> and EngineIsMap map each key to its payload and result; EngineActionKey, EngineActionPayload<K>, EngineActionResult<K>, EngineGetKey, EngineGetPayload<K>, EngineGetResult<T, K>, EngineIsKey and EngineIsPayload<K> read them.

Actions

around and the selection box are root-relative pixels; screen-to-flow and flow-to-screen take and give client points (a pointer's clientX / clientY, a drop's).

actionpayloaddoes
"set-viewport"{ x?, y?, zoom?, duration? }sets the viewport (what it leaves out stays), zoom limits and extent kept
"pan-by"{ x, y }pans by a screen offset, in pixels
"zoom-in"ZoomStepPayloadzooms in by a step around a point; refused at the greatest zoom
"zoom-out"ZoomStepPayloadzooms out by a step; refused at the least zoom
"zoom-to"{ zoom, around?, duration? }zooms to a level around a point (default the root's centre)
"fit-view"FitViewPayloadfits the nodes (or some) in the root; refused while none is measured or the root has no size
"center-on"{ x, y, zoom?, duration? }centres a flow point in the root
"focus-node"{ nodeId }gives DOM focus to a node's element, panning it into view
"set-interactive"InteractivityPayloadlets gestures and keys change the flow, or not: all of them (interactive) or one kind (drag, connect, select, reconnect), the switches left out kept (Flow.ToggleInteractive switches drag, connect and select); pan and zoom stay; a switch turned off cancels the gesture under way; returns every switch (Interactivity)
"cancel-gesture"nonecancels the gesture under way (what Escape does) and stops a viewport animation where it is; refused when there is neither

duration (milliseconds, default 0: at once) animates set-viewport, zoom-in, zoom-out, zoom-to, fit-view and center-on on the root window's frames, eased by the easing option: the result is the viewport it ends at (zoom limits and extent kept), and every frame tells a viewport-change with gesture: false. Another viewport action, a pan, the wheel, a pinch, cancel-gesture or destroy stops it where it is.

InteractivityPayload is a part of Interactivity, the switches (at least one given; a missing one stays as it is):

switchstops (when false)
interactiveevery gesture and key that changes the flow (each kind below, a resize, a delete key)
dragdragging nodes, and moving them with the arrows (drag(), keyboard())
connectdrawing edges from handles: a drag, a tap (click-to-connect), Enter on a handle (whose tabindex goes)
selecta tap's selection, the selection box, Enter and Space; a drag does not select the node it drags
reconnectmoving an edge's ends (reconnection()); connect: false stops it too (moving an end connects it anew)

InteractionKind names the four kinds. The switches are the engine's state, read by every feature at the moment it would act: no feature is installed again.

FitViewPayload (also the fitView option's object form):

fieldtypedescription
paddingFitPaddingthe room kept free on every side: a number is a share of the root's size, a "<n>px" string pixels, { top, right, bottom, left } each side's (a side left out keeps none); default 0.1
nodeIdsstring[]only these nodes; default every node that is not hidden
includeHiddenbooleanwithout nodeIds, the hidden nodes of known size too; default false
minZoomnumberthe least zoom it may pick, within the engine's limits (it narrows them, never widens)
maxZoomnumberthe greatest zoom it may pick, within the engine's limits
durationnumberhow long it animates, in milliseconds; default 0: at once

ZoomStepPayload:

fieldtypedescription
stepnumberthe factor; default the engine's zoomStep
aroundXYthe root-relative point that stays put; default the root's centre
durationnumberhow long it animates, in milliseconds; default 0: at once

Reads

keypayloadreturns
"viewport"nonethe Viewport
"root-size"nonethe root's { width, height }, in pixels
"edge-path-by"{ edgeId }its EdgePath (path, label point, ends and sides), undefined until both nodes have a size; an app type gets the bezier
"node-rect-by"{ nodeId }its absolute box (size 0 until measured or given)
"nodes-bounds"{ nodeIds? }the box of the nodes (or some); none without a node
"intersecting-nodes"IntersectingNodesPayloadthe nodes whose box (measured or given) shares some area with a node's box or a flow rectangle (partial: false: lies wholly inside it), in the document's order; hidden nodes, nodes of unknown size and the node itself are left out
"viewport-for-bounds"ViewportForBoundsPayloadthe viewport that frames a flow rectangle in the root, as fit-view would set it (padding, zoom limits and translate extent kept); undefined while the root has no size
"screen-to-flow"XYa client point as a flow point (a drop's position)
"flow-to-screen"XYa flow point as a client point
"visible-nodes"nonethe nodes in view, plus those of unknown size; with onlyRenderVisible, none while the root has no size (nothing mounts before the view is known). The same array while its content is unchanged
"visible-edges"nonethe edges whose ends' box is in view; with onlyRenderVisible, none while the root has no size. The same array while its content is unchanged
"drawn-edges"nonethe edges to draw, in drawing order: those shown whose nodes have a size (with onlyRenderVisible, those in view), by their stack value (zIndexMode: zIndex, a selected one raised with elevateEdgesOnSelect, in "auto" at least its ends' when one is a child), the document's order among equals
"render-layers"nonethe levels to draw, lowest first (RenderLayer[], below): one level, the edges below the nodes, unless an edge's stack value is above the lowest shown node's; then each level's edges go in their own layer at its zIndex, between the nodes below and above them
"node-z-index-by"{ nodeId }a node's structural z-index: with one render level, its stack value (its zIndex, a selected node and its descendants raised with elevateNodesOnSelect, always above its parent's; "manual": its zIndex); with several, its rank among the layers (a negative number), so what the app renders after the layers (the connection line, the selection box, the selection's rectangle) stays above
"internal-node-by"{ nodeId }a node on screen, an InternalNode (id, node, absolutePosition, rect, measured, zIndex, handles), undefined for an unknown node: what useInternalNode reads
"handles-by"{ nodeId }a node's registered handles (FlowHandle[]), with their centres
"background-pattern"BackgroundPatternPayloadone tile of a background pattern at the current viewport
"node-toolbar-by"NodeToolbarPayloadwhere a node's toolbar goes, outside the zoom: beside a node, or beside several nodes' bounds (nodeIds); undefined until one of them has a size
"edge-toolbar-by"EdgeToolbarPayloadwhere an edge's toolbar goes, outside the zoom (an EdgeToolbarPosition): at its label point, one of its ends or a flow point; undefined until the edge is drawn
"selection-box"nonethe box being drawn (a root-relative SelectionBox), or null (selection(); undefined without it)
"selection-rect"nonethe flow-space bounds (a Rect) of the selected nodes, for the rectangle around them (the nodes-selection part, in the viewport): while two or more are selected by a box (selection({ rect: "always" }): by anything), until the selection changes otherwise; null otherwise and while a box is drawn (selection())
"dragging-node-ids"nonethe nodes being dragged (drag())
"connection"nonethe Connection being drawn, or null (connection(); undefined without it)
"minimap-view"{ width, height }what a minimap of that many pixels draws (minimap())
"minimap-point-to-flow"{ client }a client point on the minimap (the one under it, else the first) as a flow point, for a click on it; undefined while no minimap has a size (minimap())

IntersectingNodesPayload:

fieldtypedescription
nodeIdstringthe node whose box the others are compared with (it is left out); wins over rect
rectRecta rectangle in absolute flow coordinates, without nodeId
partialbooleanany shared area counts (default true); false: only a node wholly inside

ViewportForBoundsPayload:

fieldtypedescription
boundsRectthe flow rectangle to frame
paddingFitPaddingthe room kept free on every side, or each side's, as fit-view's; default 0.1
minZoomnumberthe least zoom it may pick (within the engine's limits); default the engine's minZoom
maxZoomnumberthe greatest zoom it may pick (within the engine's limits); default the engine's maxZoom

The same framing is a pure function, viewportForBounds(bounds, width, height, options?): the viewport that shows bounds whole and centred in a root of width × height pixels (a server render, a thumbnail, a saved view), with no engine. Its ViewportForBoundsOptions:

optiontypedescription
paddingFitPaddingthe room kept free on every side, or each side's (the bounds centred in what is left); default 0.1
minZoomnumberthe least zoom it may pick; default 0.5

FitPadding is a PaddingValue for every side, or { top?, right?, bottom?, left? } of them; a PaddingValue is a number (a share of the root's width for the left and right, of its height for the top and bottom) or a `${number}px` string (pixels). A plain number frames exactly as before per-side padding existed. | maxZoom | number | the greatest zoom it may pick; default 2 |

BackgroundPatternPayload:

fieldtypedescription
variantBackgroundVariant"dots" (default), "lines" or "cross"
gapnumber | [number, number]the distance between two marks, in flow units; default 20
sizenumberdots: a dot's diameter, in flow units, default 1; lines: the stroke width in screen pixels (not scaled by the zoom), default 1; cross: each bar's length (an arm is half of it), in flow units, default 6
offsetnumber | [number, number]the pattern's shift from the flow's origin, in flow units; default 0

BackgroundPattern, one tile for an SVG pattern with patternUnits="userSpaceOnUse":

fieldtypedescription
variantBackgroundVariantthe marks
xnumberthe tile's left, on the screen
ynumberthe tile's top
widthnumberthe tile's width, in pixels
heightnumberthe tile's height
dot{ cx, cy, r } | undefinedthe dot, for dots
pathstring | undefinedthe lines' or the cross's path data
strokeWidthnumberthe stroke width of path, in pixels

NodeToolbarPayload:

fieldtypedescription
nodeIdstringthe node it stands beside (without nodeIds)
nodeIdsstring[]the nodes whose bounds it stands beside (their measured boxes); wins over nodeId when not empty
sideHandleSidethe side it stands on; default "top"
align"start" | "center" | "end"where along that side; default "center"
offsetnumberthe gap to the node, in pixels; default 10

NodeToolbarPosition, a root-relative anchor outside the zoom:

fieldtypedescription
xnumberthe anchor's left, in pixels
ynumberthe anchor's top
anchorXnumberwhich point of the toolbar goes there, as a share of its width (0.5: its centre)
anchorYnumberthe same along its height (1: its bottom)

EdgeToolbarPayload:

fieldtypedescription
edgeIdstringthe edge
position"label" | "source" | "target"the point of the edge it stands at: its label point (default) or one of its ends
pointXYa flow point it stands at instead (absolute flow coordinates); wins over position
offsetXYa screen offset from that point, in pixels; default { x: 0, y: 0 }
alignX"start" | "center" | "end"which of the toolbar's edges goes at the point across: its left, its centre (default) or its right
alignY"start" | "center" | "end"the same down: its top, its centre (default) or its bottom

EdgeToolbarPosition is a NodeToolbarPosition whose anchorX and anchorY follow alignX and alignY (0, 0.5 or 1; 0.5 by default: the toolbar's centre goes to the point). The toolbar part's attributes take { edgeId } for an edge's toolbar (its data-flow-id), { nodeId } for a node's, nothing for several nodes'.

Connection, the connection being drawn:

fieldtypedescription
fromFlowHandlethe handle it started from
fromPointXYwhere it starts, in flow coordinates (the handle's centre)
toPointXYthe pointer, or the centre of the handle it snapped to
toSideHandleSidethe side it enters by
toFlowHandle | undefinedthe handle within the radius it would end at
status"valid" | "invalid" | nullvalid: the drop adds an edge; invalid: model.can refuses it; null: no handle near
pathstringthe connection line's path, as connection({ lineType }) draws it (a bezier by default)
reconnecting{ edgeId, end } | undefinedthe edge whose end is moved (reconnection())

MinimapView, in flow coordinates:

fieldtypedescription
viewBoxRectthe SVG viewBox: the nodes and the view, fitted to the minimap's aspect
viewBoxAttributestringviewBox as the attribute writes it
scalenumberthe flow units one minimap pixel stands for
nodes{ nodeId, x, y, width, height }[]the box of every node shown (not hidden) and measured, in view or not
viewRectwhat the root shows
maskPathstringthe view box with the view cut out, for fill-rule="evenodd"

RenderLayer, one level of render-layers (the same as staticGeometry's layers):

fieldtypedescription
levelnumberits place, 0 the lowest (the data-level of its edges-layer)
zIndexnumber | undefinedthe structural z-index of its edges' layer in the viewport's stacking context; none with a single level
nodeIdsstring[]the shown nodes of this level, in the document's order
edgeIdsstring[]its edges, in drawing order

With one level (zIndex undefined) an adapter renders one edges SVG below the nodes. With several, the levels' z-indexes are negative ranks in one order (level 0's edges, level 0's nodes, level 1's edges, level 1's nodes, …); an edge at the same value as a node stays below it. Nodes never change wrapper: each adapter keeps them all in the one nodes layer and interleaves them with the edges' layers by stacking order.

Questions

keypayloadanswers
"interactive"nonegestures and keys may change the flow
"interactive-by"{ kind }gestures and keys of an InteractionKind may (interactive and that kind's switch)
"ready"nonethe root has a size and the fit on init is done (the ready event came)
"panning"nonethe viewport is being panned by a drag or a pinch
"node-measured"{ nodeId }its size is known (measured, or given by the document)
"box-selecting"nonea box selection is being drawn (selection())
"dragging"nonenodes are being dragged (drag())
"node-dragging"{ nodeId }this node is being dragged (drag())
"resizing"nonea node is being resized (resize())
"node-resizing"{ nodeId }this node is being resized (resize())
"connecting"nonea connection is being drawn (connection())
"edge-reconnecting"{ edgeId }one of its ends is being moved (reconnection())
"node-focusable"{ nodeId }it takes DOM focus, tabindex="0" (keyboard()): shown, its focusable not false, nodesFocusable on
"edge-focusable"{ edgeId }it takes DOM focus (keyboard()): shown, its focusable not false, edgesFocusable on

The engine measures every node and its handles with a ResizeObserver, so there is nothing to refresh by hand: engine.is("node-measured", { nodeId }) answers whether a node is measured.

Events

engine.subscribe(listener) hears what happens on screen, a FlowEngineEvent (its type is a FlowEngineEventType). No text is built in: turn an event into your own words for your own live region (see Accessible names), or sync a controlled viewport from it.

eventfieldswhen
"viewport-change"viewport, gesturethe viewport changed; gesture: by a pan, a zoom or a pinch, not an action
"viewport-change-start"viewport, gesturethe viewport starts a move: the first change of a pan, a wheel, a pinch, an animation or an action (viewport is where it starts)
"viewport-change-end"viewport, gesturethe move ended: the pan or pinch released, the animation done or stopped, the wheel at rest for 150 ms; an action that does not animate starts and ends at once
"ready"nonethe root has a size and the fit on init (fitView) is done, once per engine; the root's size is observed, so a root sized after mount makes it come
"node-click", "edge-click", "pane-click"nodeId / edgeId, point, client, eventa tap: a primary press released within the tap distance (paneClickDistance, nodeClickDistance) that started no gesture; a press that dragged or panned is none. Told after the selection changed, and while the flow is not interactive too
"node-double-click", "edge-double-click", "pane-double-click"the samea double click whose two presses were taps; on the pane it also zooms in (zoomOnDoubleClick)
"node-context-menu", "edge-context-menu", "pane-context-menu"the samea context menu (a right click, the menu key); the app calls event.preventDefault() to show its own. One a right-button pan keeps out is none
"selection-context-menu"nodeIds, edgeIds, point, client, eventa context menu on a selected node while several nodes are selected (instead of node-context-menu), or on the rectangle around the selection (nodes-selection)
"drag-start"nodeIdsa drag of these nodes started (drag())
"nodes-move"nodeIds, sourcenodes were dropped after a drag, or moved by the arrows; source is a MoveSource, "pointer" or "keyboard"
"drag-cancel"nodeIdsa drag was cancelled: its nodes went back (also the cancel of a drag of the selection rectangle, which has no event of its own)
"minimap-click"element, point, client, event (a FlowPointerInfo)a tap on a minimap (minimap()), element the tapped minimap, point the flow point under it on that minimap; not a root callback (the MiniMap's onClick)
"selection-drag-start", "selection-drag", "selection-drag-end"nodeIds, client, point (a SelectionDragStep)a press on the rectangle around the selection (nodes-selection, drag()) dragged the selection, as a node drag (threshold, snap, extent, auto-pan): it started (instead of drag-start), moved its nodes (each step), dropped them (after their nodes-move); a cancel is drag-cancel
"connect-start"nodeId, handleId, handleType, inputa connection started from a handle (connection()); input (a MoveSource): "pointer" (a drag or a tap) or "keyboard" (Enter on a focused handle, with keyboard())
"connect-target"nodeId, handleId, handleType, index, counta keyboard connection points at another target: the index-th of the count handles the model accepts, nearest first (index -1 and no handle when it accepts none), for your live region
"connect"edgeId, source, target, inputa connection was dropped on a handle (or Enter chose it): an edge was added
"connect-cancel"refused, input, dropped, from, to, client, pointa connection ended without an edge; refused: on a handle model.can("edge.add") refused; dropped: released (or confirmed), not cancelled by Escape, the lock or a pointercancel; where it ended (ConnectionDrop)
"reconnect-start"edgeId, endan edge's end was grabbed (reconnection())
"reconnect"edgeId, source, targetan edge was reconnected
"reconnect-cancel"edgeId, end, refused, dropped, from, to, client, pointa reconnection ended with the edge as it was (dropped as for connect-cancel); from is the edge's fixed end
"resize-start"nodeId, width, heighta resize started (resize()), at the node's size then; its steps are node.resize commands run as transient (model.subscribe, onNodesChange)
"resize-cancel"nodeIda resize was cancelled: the node is back at its size
"resize"nodeId, width, height, sourcea node was resized (resize()): by a drag (source: "pointer"), or by the arrows on a focused resize handle ("keyboard", with keyboard())
"box-select-start"client, pointa selection box started (selection()): where, as a client and a flow point
"box-select"nodeIds, edgeIdsa box selection ended with these selected (selection())
"remove"nodeIds, edgeIdsa delete key (deleteKeys: Delete or Backspace by default) removed these (keyboard()), after its beforeDelete

ConnectionDrop, where a connection or a reconnection ended without an edge:

fieldtypedescription
fromConnectionEndthe handle it came from (a reconnection: the edge's fixed end), { nodeId, handleId, type }
toConnectionEnd | undefinedthe handle it was over, none over nothing
clientXYthe drop as a client point (clientX, clientY): where a node made from it goes on screen
pointXYthe drop as a flow point (screen-to-flow of client); a keyboard connection's is its target's centre (or its start's)

FlowPointerInfo (point, client, event) is what the tap, double-click and context-menu events share; FlowEngineEventOf<K> is the event of one type. ENGINE_EVENT_CALLBACKS maps each event but viewport-change (a CallbackEventType) to the name of its root callback in every adapter (an EventCallbackName: NodeClick is React's onNodeClick, Vue's nodeClick (@node-click), Svelte's onnodeclick, Angular's (nodeClick); see Root).

The engine tells taps from its own gestures: the pointer is captured on the root at every press, so a browser's click and dblclick target the root. A click that ended a drag or a pan is never a tap.

const stop = engine.subscribe((event) => {
    if (event.type === "connect") announce(`Connected ${event.source} to ${event.target}.`);
    if (event.type === "connect-cancel" && event.refused) announce("That connection is not allowed.");
});

The adapter contract

engine.adapter is a FlowEngineAdapter: what a framework adapter (@fragiola/flow-react, @fragiola/flow-vue, @fragiola/flow-svelte, @fragiola/flow-angular) calls. An app never needs it. The adapter renders and attaches; the engine listens to the root itself and resolves every press, key and wheel from the part attributes, so every adapter behaves the same.

memberdoes
modelthe model this engine draws
settingsthe rendering settings from the options: onlyRenderVisible
setOptions(options)options changed (a root prop): they apply from now on, a gesture under way included; root, defaultViewport and fitView are creation options
attachRoot(element)attaches the root: the engine listens to its pointer, wheel, key and focus events and sets its touch-action: none
detachRoot()detaches it, cancelling a gesture under way
attachViewport(element)attaches (or, with null, detaches) the viewport element: the engine writes its transform and transform-origin, the framework never does
registerNode(nodeId, element)registers (or unregisters) a node's element: the engine measures it
registerHandle(handle, element)registers (or unregisters) a handle: the engine measures its centre relative to its node
refocus(element)gives focus back to a part that was remounted (an edge that moved to another render level's layer): when element is the part (data-flow-part and data-flow-id) that last had focus in the flow and focus was lost (the active element is the body, or none), it is focused again, without scrolling; each adapter's Flow.Edge calls it when it mounts
setPartOptions(part, id, options)options a part's primitive takes (a resizer's minWidth, …, direction; the minimaps' inversePan and zoomStep under the id "", over minimap()'s); null drops them
attributes(part, payload?)the record to spread on a part: data-flow-part, data-flow-id and its state
subscribe(listener)the view changed (a ViewChange); returns its remover
getSnapshot()a number that changes whenever the view changes

HandleRegistration, what a handle registers:

fieldtypedescription
nodeIdstringthe node it belongs to
handleIdstringits id among the node's handles of its type; none: the default handle
typeHandleType"source" or "target"
sideHandleSidethe side it sits on: the direction its edges leave or enter by
connectablebooleana connection may start or end at it; default true
connectableStartbooleana connection may start at it (a drag, a tap, a key); default true
connectableEndbooleana connection may end at it (be its target); default true

FlowHandle, a registered handle (handles-by, a connection's ends):

fieldtypedescription
nodeIdstringits node
handleIdstring | undefinedits id
typeHandleTypesource or target
sideHandleSideits side
connectablebooleanits flag and its node's
connectableStartbooleanit may start a connection (and is connectable)
connectableEndbooleanit may end one (and is connectable)
centerXY | undefinedits centre in absolute flow coordinates, once measured
boundsRect | undefinedits box relative to its node, in flow units, once measured

ViewChange, what changed in the view, so an adapter re-renders only what depends on it:

fieldtypedescription
viewportbooleanthe viewport moved or zoomed (the background, the minimap, toolbars)
measuredbooleana node or handle was measured (edges, the minimap, toolbars)
gesturebooleana gesture's state changed (the connection line, the selection box, state attributes)

PartPayloadMap types the payload of each part's attributes (node takes { nodeId }, handle a HandleRegistration, reconnect-anchor { edgeId, end }, resize-handle { nodeId, position, direction?, variant? } (its own direction and how it is drawn: data-direction, data-variant), edges-layer { level } (data-level), …). With keyboard() the record of nodes-selection (the rectangle around the selection) has tabindex="0", as a resize handle's does with resize(). PressTarget is what the engine resolved a press to (kind: pane, node, edge, handle, resize-handle, minimap, nodes-selection or other, with the ids; a press on an edges-layer is a pane press; outsideDragHandle on a press on a node that holds a drag handle, outside it), handed to the features' hooks.

Part attributes

The attribute names are constants, and the helpers give the static attributes without an engine (a server render, a part with no state):

exportvalue
PART_ATTRIBUTE"data-flow-part": every element's part name (FlowPart: root, node, edge, handle, …)
ID_ATTRIBUTE"data-flow-id": the id of the node, edge or handle a part stands for
POSITION_ATTRIBUTE"data-position": a resize handle's corner or side
END_ATTRIBUTE"data-end": a reconnect anchor's end of its edge
DIRECTION_ATTRIBUTE"data-direction": a resize handle's own direction (horizontal, vertical), over its resizer's, read when a press or a key on it starts
VARIANT_ATTRIBUTE"data-variant": how a resize handle is drawn (handle, line), for the app's styles
LEVEL_ATTRIBUTE"data-level": an edges-layer's render level, 0 the lowest
NO_GESTURE_ATTRIBUTE"data-flow-no-gesture": a subtree inside a node that starts no gesture (a slider, a field)
NO_WHEEL_ATTRIBUTE"data-flow-no-wheel": a subtree where the wheel scrolls its content instead of zooming
DRAG_HANDLE_ATTRIBUTE"data-flow-drag-handle": an element inside a node that is its drag handle; a node holding one drags only from it (a press elsewhere on it still selects it)
partAttributes(part, id?){ "data-flow-part": part, "data-flow-id": id }
edgesLayerAttributes(level){ "data-flow-part": "edges-layer", "data-level": level }: one render level's edges layer, the same with or without an engine
resizeHandleAttributes(position, options?)a resize handle's static attributes: its part, data-position, data-variant (line only on a side, else handle) and data-direction when it has a valid one; options is a ResizeHandleAttributeOptions { direction?, variant? } (ResizeHandleDirection "horizontal" | "vertical", ResizeHandleVariant "handle" | "line")
flag(on)a boolean state attribute's value: "" when on, undefined when off

PartAttributes is a read-only record of them, MutablePartAttributes the writable one the engine and its features fill. The state attributes each part carries: State attributes.

Static geometry

staticGeometry(flow, options?) is a flow's geometry from its document alone, without an engine and without a DOM: what each adapter renders on the server and in its first client render, before the engine exists. It runs the very functions the engine runs before a node is measured, so the first render and the engine agree (no hydration mismatch, no jump). A node's size is its width / height, else its initialWidth / initialHeight; an edge's ends are its nodes' declared handles (else the sourcePosition / targetPosition side). An app that renders a flow itself (an SVG thumbnail, an image on the server) can call it too:

import { staticGeometry } from "@fragiola/flow";

const geometry = staticGeometry(
    { nodes, edges },
    { nodeOrigin: { x: 0, y: 0 }, zIndexMode: "auto" },
);
const paths = geometry.drawnEdges.map((edgeId) => geometry.edgePaths[edgeId]?.path);

StaticGeometryOptions, the engine options it follows (give it the root's, so both agree):

fieldtypedescription
nodeOriginXYthe point of a node's box its position stands at; default top-left
pathOptionsPathOptionsthe shape of the built-in edge paths (an edge's own go over them)
zIndexModeZIndexModehow stack values are worked out; default "auto"
elevateNodesOnSelectbooleana selected node is raised; default true
elevateEdgesOnSelectbooleana selected edge is raised; default false in "basic", true in "auto"

StaticGeometry, the result (frozen plain data, keyed by id):

fieldtypedescription
nodeRectsRecord<string, Rect>every node's box in absolute flow coordinates, its origin applied, its size 0 when unknown (node-rect-by)
nodeZIndexesRecord<string, number>every node's structural z-index (node-z-index-by)
edgePathsRecord<string, EdgePath>the path of each edge whose two nodes have a size (edge-path-by); the others are absent
drawnEdgesstring[]the ids of the edges to draw, in drawing order (drawn-edges, without onlyRenderVisible)
layersRenderLayer[]the levels to draw (render-layers)

The module (src/geometry/) imports nothing of the DOM and nothing of the engine; a guard test keeps it so. See Server rendering.

Helpers for the hooks

What every adapter's hooks share, so they agree: watchKeyPress(target, keys, onChange) calls onChange(pressed) whenever a combo of keys (a KeyPressKeys: key names joined by +, held at once, "Meta+s", or a list of combos, any of them; a name is a KeyboardEvent.key or .code without case) starts or stops being held on target (a KeyPressTarget: a window, a document or an element), forgetting the keys on its window's blur and on Meta's release, and returns its stop. sameFlowValue(a, b) tells two reads apart: arrays and plain records compared all the way down, anything else by identity.