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.EdgeandFlow.Handleare built on them. - Selections:
useFlowStore,useNodeId,useNodesData,useNodeConnections,useInternalNode,useKeyPress,useOnViewportChange. Each reads one thing and re-renders only when it changed (useOnViewportChangenever: 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.
| field | type | description |
|---|---|---|
model | FlowModel<T, F> | the flow's document and its rules: model.run, model.get, model.is (model) |
engine | FlowEngine<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.
| field | type | description |
|---|---|---|
nodes | readonly FlowNode<T>[] | the selected nodes |
edges | readonly 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):
| field | type | description |
|---|---|---|
nodeId | string | its id |
node | FlowNode<T> | the node, as the model holds it |
x, y | number | its top-left corner in absolute flow coordinates |
selected | boolean | data-selected (selection()) |
dragging | boolean | data-dragging (drag()) |
resizing | boolean | data-resizing (resize()) |
measured | boolean | its size is known: data-measured |
focusable | boolean | it takes DOM focus (keyboard()) |
attributes | PartAttributes | data-flow-part, data-flow-id and its state |
UseNodeResult<T>:
| field | type | description |
|---|---|---|
state | NodeState<T> | its state |
props | { ref, tabIndex, style } & DataAttributes | its 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):
| field | type | description |
|---|---|---|
edgeId | string | its id |
edge | FlowEdge<T> | the edge, as the model holds it |
path | EdgePath | undefined | its path, label point and ends, once both nodes have a size |
selected | boolean | data-selected (selection()) |
reconnecting | boolean | one of its ends is being moved (reconnection()) |
focusable | boolean | it takes DOM focus (keyboard()) |
attributes | PartAttributes | its attributes |
UseEdgeResult<T>:
| field | type | description |
|---|---|---|
state | EdgeState<T> | its state |
props | { tabIndex } & DataAttributes | its attributes and tabIndex |
useHandle
useHandle(options) returns UseHandleResult for a handle rendered by hand: spread props on its
element, inside a node.
UseHandleOptions:
| option | type | default | description |
|---|---|---|---|
type | HandleType | required | edges start ("source") or end ("target") here |
side | HandleSide | required | the side of the node it sits on |
handleId | string | none | its id among the node's handles of its type |
connectable | boolean | true | a connection may start or end here |
connectableStart | boolean | true | a connection may start here |
connectableEnd | boolean | true | a connection may end here |
nodeId | string | the enclosing Flow.Node's | its node |
state is HandleState (see Flow.Handle):
| field | type | description |
|---|---|---|
nodeId | string | its node |
handleId | string | undefined | its id |
type | HandleType | its type |
side | HandleSide | its side |
connectable | boolean | a connection may start or end here: data-connectable |
connectableStart | boolean | a connection may start here: data-connectable-start |
connectableEnd | boolean | a connection may end here: data-connectable-end |
connecting | boolean | the connection under way starts here: data-connecting |
valid | boolean | the connection under way would end here, accepted: data-valid |
invalid | boolean | the connection under way would end here, refused: data-invalid |
attributes | PartAttributes | its attributes |
UseHandleResult:
| field | type | description |
|---|---|---|
state | HandleState | its state |
props | { ref } & DataAttributes | its 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:
| React | Vue (composable) | Svelte (rune) | Angular (injection function) |
|---|---|---|---|
useFlowStore | useFlowStore: a ComputedRef | useFlowStore: a FlowValue | injectFlowStore: a Signal |
useNodeId | useNodeId: a ComputedRef | useNodeId: the id itself | injectNodeId: a Signal |
useNodesData | useNodesData: a ComputedRef | useNodesData: a FlowValue | injectNodesData: a Signal |
useNodeConnections | useNodeConnections: a ComputedRef | useNodeConnections: a FlowValue | injectNodeConnections: a Signal |
useInternalNode | useInternalNode: a ComputedRef | useInternalNode: a FlowValue | injectInternalNode: a Signal |
useKeyPress | useKeyPress: a read-only Ref<boolean> | useKeyPress: a FlowValue<boolean> | injectKeyPress: a Signal<boolean> |
useOnViewportChange | useOnViewportChange | useOnViewportChange (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>(…)).
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.
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):
| option | type | default | description |
|---|---|---|---|
id | string | the enclosing Flow.Node's | the node |
handleId | string | any | only the connections at this handle of it |
type | HandleType | both | only 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.
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.
| field | type | description |
|---|---|---|
id | string | its id |
node | FlowNode<T> | the node, as the model holds it |
absolutePosition | XY | its position in absolute flow coordinates (a child's added to its parents') |
rect | Rect | its box in absolute flow coordinates, nodeOrigin applied (size 0 until measured) |
measured | boolean | its size is known: measured, or given by the document |
zIndex | number | its structural z-index |
handles | readonly FlowHandle[] | its registered handles, with their centres and bounds (handles-by) |
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 aKeyboardEvent.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):
| option | type | default | description |
|---|---|---|---|
target | KeyPressTarget | null | the root's window | where the keys are read: a window, a document or an element; null: nowhere |
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):
| option | type | description |
|---|---|---|
onStart | (viewport: Viewport, gesture: boolean) => void | the viewport starts changing: a pan, a zoom, an animation |
onChange | (viewport: Viewport, gesture: boolean) => void | each change of the viewport |
onEnd | (viewport: Viewport, gesture: boolean) => void | the viewport stopped changing (a wheel's 150 ms after its last event) |
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.