Fragiola

API: primitives (@fragiola/flow-react, @fragiola/flow-vue, @fragiola/flow-svelte, @fragiola/flow-angular)

Hooks

The hooks read the root's model, engine, view, selection, nodes, edges and keys, select one value or node's data, and render nodes, edges and handles by hand.

Every hook reads the enclosing Flow.Root (outside one it throws, but useNodeId and useKeyPress). Three kinds:

  • Values: useFlow, useViewport, useConnection, useSelection, useNodes, useEdges. Each re-renders its component when its value changes, and only then.
  • Parts: useNode, useEdge, useHandle, each returning { state, props }: the part's state, and the props to spread on your own element (its attributes, the ref that registers it with the engine, its structural style). Flow.Node, Flow.Edge and Flow.Handle are built on them.
  • Selections: useFlowStore, useNodeId, useNodesData, useNodeConnections, useInternalNode, useKeyPress, useOnViewportChange. Each reads one thing and re-renders only when it changed (useOnViewportChange never: it calls you back).

From outside the root (a toolbar beside it, a test), use a flow ref.

In Vue they are composables of the same names, from @fragiola/flow-vue: the values are computed refs (useViewport().value.zoom, unwrapped in a template), and a part's state and props are computed refs too. Call them in setup. Vue components lists their types. In Svelte they are runes of the same names, from @fragiola/flow-svelte: the values are a { current } that follows the flow (useViewport().current.zoom), and a part's state and props are getters. Call them in a component's script, inside the root; Svelte components lists their types. In Angular they are injection functions (injectFlow, injectNode, injectViewport, …), from @fragiola/flow-angular: the values are signals, called in an injection context of a component inside the root; Angular directives lists their types.

useFlow

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

function DeleteSelected() {
    const { model } = useFlow<Types, typeof features>();
    return (
        <button type="button" onClick={() => model.run("selection.remove")}>
            Delete
        </button>
    );
}

useFlow<T, F>() returns UseFlowResult<T, F>, the model and the engine of the root. Pass the registry and the features as type arguments: a child cannot infer them through context.

fieldtypedescription
modelFlowModel<T, F>the flow's document and its rules: model.run, model.get, model.is (model)
engineFlowEngine<T, F>the flow on screen: engine.run("fit-view"), engine.get("viewport"), engine.subscribe (engine). There from the first render: before the root is mounted (and on the server) an action is refused and a read is empty

useViewport

useViewport() returns the root's Viewport ({ x, y, zoom }), re-rendering on every change: a zoom readout, a control's state. Change it with engine.run("set-viewport", …).

function ZoomLevel() {
    const { zoom } = useViewport();
    return <output>{Math.round(zoom * 100)}%</output>;
}

useConnection

useConnection() returns the Connection being drawn from a handle (connection()), or null: where it starts and ends, the handle it would end at (to) and whether the drop would be accepted (status). Flow.ConnectionLine uses it.

useSelection

useSelection<T>() returns FlowSelection<T>, the selected nodes and edges in drawing order (selection(); empty without it), re-rendering when they change.

fieldtypedescription
nodesreadonly FlowNode<T>[]the selected nodes
edgesreadonly FlowEdge<T>[]the selected edges

useNodes and useEdges

useNodes<T>() and useEdges<T>() return every node, or every edge, in drawing order (the model's own frozen list), re-rendering on every change of one: a list beside the flow, a counter. A drag re-renders them at every step; read model.get("node-by", { id }) for one entity.

useNode

useNode<T>(node) returns UseNodeResult<T> for a node rendered by hand: spread props on its element (the engine resolves presses from its attributes).

function PlainNode({ node }: { node: FlowNode<Types> }) {
    const { state, props } = useNode(node);
    return (
        <section {...props} aria-label={node.data.label} className={state.selected ? "ring-2" : undefined}>
            {node.data.label}
        </section>
    );
}

state is NodeState<T> (see Flow.Node):

fieldtypedescription
nodeIdstringits id
nodeFlowNode<T>the node, as the model holds it
x, ynumberits top-left corner in absolute flow coordinates
selectedbooleandata-selected (selection())
draggingbooleandata-dragging (drag())
resizingbooleandata-resizing (resize())
measuredbooleanits size is known: data-measured
focusablebooleanit takes DOM focus (keyboard())
attributesPartAttributesdata-flow-part, data-flow-id and its state

UseNodeResult<T>:

fieldtypedescription
stateNodeState<T>its state
props{ ref, tabIndex, style } & DataAttributesits attributes, tabIndex (0 with keyboard()), its structural style (absolute, at its position, with the document's size) and the ref that registers it

useEdge

useEdge<T>(edge) returns UseEdgeResult<T> for an edge drawn by hand: spread props on an SVG g.

state is EdgeState<T> (see Flow.Edge):

fieldtypedescription
edgeIdstringits id
edgeFlowEdge<T>the edge, as the model holds it
pathEdgePath | undefinedits path, label point and ends, once both nodes have a size
selectedbooleandata-selected (selection())
reconnectingbooleanone of its ends is being moved (reconnection())
focusablebooleanit takes DOM focus (keyboard())
attributesPartAttributesits attributes

UseEdgeResult<T>:

fieldtypedescription
stateEdgeState<T>its state
props{ tabIndex } & DataAttributesits attributes and tabIndex

useHandle

useHandle(options) returns UseHandleResult for a handle rendered by hand: spread props on its element, inside a node.

UseHandleOptions:

optiontypedefaultdescription
typeHandleTyperequirededges start ("source") or end ("target") here
sideHandleSiderequiredthe side of the node it sits on
handleIdstringnoneits id among the node's handles of its type
connectablebooleantruea connection may start or end here
connectableStartbooleantruea connection may start here
connectableEndbooleantruea connection may end here
nodeIdstringthe enclosing Flow.Node'sits node

state is HandleState (see Flow.Handle):

fieldtypedescription
nodeIdstringits node
handleIdstring | undefinedits id
typeHandleTypeits type
sideHandleSideits side
connectablebooleana connection may start or end here: data-connectable
connectableStartbooleana connection may start here: data-connectable-start
connectableEndbooleana connection may end here: data-connectable-end
connectingbooleanthe connection under way starts here: data-connecting
validbooleanthe connection under way would end here, accepted: data-valid
invalidbooleanthe connection under way would end here, refused: data-invalid
attributesPartAttributesits attributes

UseHandleResult:

fieldtypedescription
stateHandleStateits state
props{ ref } & DataAttributesits attributes and the ref that registers it (its centre is measured)

Selecting hooks

The hooks below read one thing and change only when it does: a component built on them is not rendered again when a node moves or the viewport pans, unless what it reads changed. The same seven are in every adapter:

ReactVue (composable)Svelte (rune)Angular (injection function)
useFlowStoreuseFlowStore: a ComputedRefuseFlowStore: a FlowValueinjectFlowStore: a Signal
useNodeIduseNodeId: a ComputedRefuseNodeId: the id itselfinjectNodeId: a Signal
useNodesDatauseNodesData: a ComputedRefuseNodesData: a FlowValueinjectNodesData: a Signal
useNodeConnectionsuseNodeConnections: a ComputedRefuseNodeConnections: a FlowValueinjectNodeConnections: a Signal
useInternalNodeuseInternalNode: a ComputedRefuseInternalNode: a FlowValueinjectInternalNode: a Signal
useKeyPressuseKeyPress: a read-only Ref<boolean>useKeyPress: a FlowValue<boolean>injectKeyPress: a Signal<boolean>
useOnViewportChangeuseOnViewportChangeuseOnViewportChange (onstart, onchange, onend)injectOnViewportChange

Their arguments follow each framework: in Vue a value, a ref or a getter (() => props.nodeId); in Svelte a value or a getter; in Angular a value, a signal or a getter. A getter is read again when what it reads changes, so the hook follows a prop.

useFlowStore

useFlowStore<S, T, F>(selector, equal?) returns selector({ model, engine }), the model and the engine of the root (useFlow()'s), and renders its component again only when the selected value changed: equal(previous, next), by default Object.is. The selector runs again on every change of the model, on every view change of the engine (a measurement, the viewport, a gesture) and on every render. Pass the registry and the features after the selected value's type (useFlowStore<number, Types, typeof features>(…)).

selected-count.tsx
import { useFlowStore } from "@fragiola/flow-react";

export function SelectedCount() {
    const count = useFlowStore<number, Types, typeof features>(
        ({ model }) => model.get("selected-nodes").length,
    );
    return <output>{count} selected</output>;
}

A selector that builds an object or an array builds a new one at each change: give it an equal that compares by value, sameFlowValue (from the package: arrays and plain records compared all the way down), or it renders again every time.

const ids = useFlowStore(
    ({ model }) => model.get("selected-nodes").map((node) => node.id),
    sameFlowValue,
);

useNodeId

useNodeId() returns the id of the node the component renders inside (Flow.Node), or null outside one: a piece of a custom node (a badge, a menu, a handle of yours) reads its node without being given its id.

node-badge.tsx
import { useNodeId } from "@fragiola/flow-react";

export function NodeBadge() {
    const nodeId = useNodeId();
    return <span className="text-xs opacity-60">{nodeId}</span>;
}

useNodesData and useNodeConnections

useNodesData<T>(nodeId) returns a node's NodeData<T> ({ id, type, data }, the model's nodes-data-by), or null while it does not exist. Given a list of ids, useNodesData<T>(nodeIds) returns each existing node's, in the order given (an unknown id is left out). It changes only when one of them changes its type or its data (compared by value), not when a node moves or another node changes. type narrows data: check it before reading a type's fields.

useNodeConnections(options?) returns the connections at a node, NodeConnection[] (the model's node-connections-by): one per edge that starts or ends there, as its edgeId, source, sourceHandle, target and targetHandle, in the document's order. It changes only when they do (an edge added, removed or reconnected there), not when a node moves or an edge's data changes. By default it reads the enclosing node; outside a node, give an id (without one it throws).

UseNodeConnectionsOptions (Angular: InjectNodeConnectionsOptions):

optiontypedefaultdescription
idstringthe enclosing Flow.Node'sthe node
handleIdstringanyonly the connections at this handle of it
typeHandleTypebothonly those that end ("target") or start ("source") at it

Together they make a node that follows its inputs: the sum of the nodes connected into it, updated when an input's value changes or an edge is drawn or removed.

Data from connections
Gallery
sum-body.tsx
import { useNodeConnections, useNodesData } from "@fragiola/flow-react";

/** Inside the sum node's Flow.Node: the values of the nodes connected into it. */
export function SumBody() {
    const connections = useNodeConnections({ type: "target" });
    const inputs = useNodesData<Types>(connections.map((connection) => connection.source));
    let total = 0;
    for (const input of inputs) if (input.type === "number") total += input.data.value;
    return <output>{total}</output>;
}

useInternalNode

useInternalNode<T>(nodeId) returns the node as the engine knows it on screen, an InternalNode<T> (the engine's internal-node-by), or undefined while the node does not exist or before the root is mounted. It changes only when one of its fields does (compared by value): a pan or a zoom does not change it, a drag does.

fieldtypedescription
idstringits id
nodeFlowNode<T>the node, as the model holds it
absolutePositionXYits position in absolute flow coordinates (a child's added to its parents')
rectRectits box in absolute flow coordinates, nodeOrigin applied (size 0 until measured)
measuredbooleanits size is known: measured, or given by the document
zIndexnumberits structural z-index
handlesreadonly FlowHandle[]its registered handles, with their centres and bounds (handles-by)
node-position.tsx
import { useInternalNode } from "@fragiola/flow-react";

export function NodePosition({ nodeId }: { nodeId: string }) {
    const internal = useInternalNode(nodeId);
    if (!internal) return null;
    const { x, y } = internal.absolutePosition;
    return <output>{`${Math.round(x)}, ${Math.round(y)}`}</output>;
}

useKeyPress

useKeyPress(keys, options?) returns whether a key, or a combo of keys, is held, and changes when that does. keys is a combo or a list of combos (any of them):

  • a combo is key names joined by +, all held at once: "Shift", "Meta+s", "Control+Shift+z" (other keys held too do not matter);
  • a name is a KeyboardEvent.key ("a", "Shift", "Delete", " " for Space) or a KeyboardEvent.code ("KeyA", "Space"), compared without case;
  • a list is any of its combos: ["Meta+z", "Control+z"].

The keys are read on target, by default the window of the root's element (its ownerDocument.defaultView: the right one in an iframe or a pop-up window), never the global window. Before the root is mounted, or outside a root with no target, it is false. The keys held are forgotten when that window loses focus, and when Meta is released. It reads the keys only: it prevents no default, and it does not tell a key typed in a field from another (check document.activeElement yourself when that matters).

UseKeyPressOptions (Angular: InjectKeyPressOptions, whose target may be a signal):

optiontypedefaultdescription
targetKeyPressTarget | nullthe root's windowwhere the keys are read: a window, a document or an element; null: nowhere
box-hint.tsx
import { useKeyPress } from "@fragiola/flow-react";

export function BoxHint() {
    const held = useKeyPress("Shift");
    return held ? <p role="status">Drag on the canvas to draw a box</p> : null;
}

The same matcher without a component is the core's watchKeyPress(target, keys, onChange) (engine).

useOnViewportChange

useOnViewportChange(options) calls back on the viewport's changes (the engine's viewport-change-start, viewport-change and viewport-change-end) and renders nothing again: save the view when it settles, hide a popover while the flow moves. gesture is true for a pan, the wheel, a pinch or auto-pan, false for an action (fit-view, a control button). The latest callbacks are called.

UseOnViewportChangeOptions (Svelte: lowercase onstart, onchange, onend; Angular: InjectOnViewportChangeOptions):

optiontypedescription
onStart(viewport: Viewport, gesture: boolean) => voidthe viewport starts changing: a pan, a zoom, an animation
onChange(viewport: Viewport, gesture: boolean) => voideach change of the viewport
onEnd(viewport: Viewport, gesture: boolean) => voidthe viewport stopped changing (a wheel's 150 ms after its last event)
save-view.tsx
import { useOnViewportChange } from "@fragiola/flow-react";

export function SaveView({ onMoving }: { onMoving: (moving: boolean) => void }) {
    useOnViewportChange({
        onStart: () => onMoving(true),
        onEnd: (viewport) => {
            onMoving(false);
            localStorage.setItem("flow-view", JSON.stringify(viewport));
        },
    });
    return null;
}

For every event of the engine, subscribe to it: engine.subscribe(listener) (engine), or the root's callbacks.