Fragiola

Concepts

Nodes and edges

A flow is one JSON document of nodes and edges, with ids, positions, data and permission flags, which the model keeps valid through every command.

A flow's whole state is one document, { version: 1, nodes, edges }: plain JSON, frozen, checked against its JSON Schema when the model loads it. A node is a box at a position, of a type of yours, holding your data. An edge joins a source node to a target node, optionally at given handles, and is drawn as a path of its type. The viewport is not in the document: it is view state (The viewport).

A node

const node: FlowNodeInput<Types> = {
    id: "fetch",                    // optional on input: generated when missing
    type: "task",                   // a node type of your registry
    position: { x: 120, y: 80 },    // its top-left corner (its origin, else the root's nodeOrigin), in flow coordinates
    data: { title: "Fetch orders", done: false },
    width: 180,                     // optional: a fixed size, over the measured one
    height: 64,
    // initialWidth, initialHeight: a size until it is measured; handles, sourcePosition,
    // targetPosition: where its edges end before then; origin: its own anchor (below)
    zIndex: 1,                      // optional: drawn above the nodes with less (default 0)
    draggable: true,                // flags, each with its default
    selectable: true,
    connectable: true,
    deletable: true,
    hidden: false,
};

Flow coordinates have x growing to the right and y growing down. A node without width and height takes the size of what you render in it, measured by the engine. With subflows(), a node may live in a parentId, its position then relative to its parent (Sub-flows); with selection(), it may be selected.

An edge

const edge: FlowEdgeInput<Types> = {
    id: "fetch-parse",              // optional on input
    source: "fetch",                // the node it starts at
    target: "parse",                // the node it ends at
    sourceHandle: "out",            // optional: the source node's handle
    targetHandle: "in",             // optional: the target node's handle
    type: "smoothstep",             // bezier (default), simplebezier, smoothstep, step, straight, or yours
    data: { weight: 1 },            // optional
    zIndex: 1,                      // optional: drawn above the edges with less (default 0)
    selectable: true,
    deletable: true,
    hidden: false,
    reconnectable: true,
};

An edge without a handle uses its node's first handle of that type (a source handle at its source, a target handle at its target), or, when the node has none, leaves the source by its bottom and enters the target by its top (a node's sourcePosition and targetPosition change those sides). An edge of a type of yours gets the bezier path, and its ends to draw your own (Custom edges).

Sizes and handles before measuring

The engine measures what you render, so by default a node's edges are drawn once it is on screen and measured. A node can declare enough for its edges to be drawn before that: on the server and in the first client render (Server rendering), and in fitView on init.

fieldwhat it gives
width, heighta fixed size: it wins over the measured one, always
initialWidth, initialHeighta size until the node is measured; then the measured one
handlesDeclaredHandle[]: { id?, type, position, x, y, width?, height? }, each handle's box relative to the node's top-left corner; an edge ends at the box's centre, the point the engine measures for a rendered handle; a measured handle of the same type and id always wins
sourcePosition, targetPositionthe side an edge leaves or enters by when no handle (rendered or declared) gives one; default "bottom" and "top"
const nodes: FlowNodeInput<Types>[] = [
    {
        id: "fetch",
        type: "task",
        position: { x: 0, y: 0 },
        data: { title: "Fetch orders", done: false },
        initialWidth: 180,
        initialHeight: 64,
        handles: [{ type: "source", position: "right", x: 176, y: 28, width: 8, height: 8 }],
    },
    {
        id: "parse",
        type: "task",
        position: { x: 260, y: 0 },
        data: { title: "Parse", done: false },
        initialWidth: 180,
        initialHeight: 64,
        targetPosition: "left", // no handle declared: the edge enters by the left side's middle
    },
];

Declare what you render: a handle at x: 176, width: 8 on a 180-wide node is centred on its right edge, where a Flow.Handle with side="right" and an 8 px box sits. When the measured geometry equals the declared one, nothing moves when the engine takes over.

A node's own origin

A node's position is its box's top-left corner, or the point the root's nodeOrigin names, as shares of its size. A node's own origin overrides nodeOrigin for that node, everywhere the engine computes a box (its edges and handles, bounds, fit-view, the minimap, toolbars, the selection box, drags and resizes):

const nodes: FlowNodeInput<Types>[] = [
    // stands on its top-left corner, as every node by default
    { id: "start", type: "task", position: { x: 0, y: 0 }, data: { title: "Start", done: false } },
    // stands on its centre: a circle a layout placed by its centre
    { id: "hub", type: "task", position: { x: 300, y: 40 }, origin: { x: 0.5, y: 0.5 }, data: { title: "Hub", done: false } },
];
<Flow.Root defaultNodes={nodes} nodeOrigin={{ x: 0, y: 0 }} className="h-96">
    …
</Flow.Root>

As with nodeOrigin, a child of a sub-flow keeps its top-left corner in its parent: its own origin does not move it, so the model's sub-flow rules hold as they are. A parent's origin moves its box, and its children with it. The model's own sub-flow rules count a node's position as its corner, whatever its origin: absolute-position-by, expandParent (a parent grows around its origin), the model's extent: "parent" clamp and node.set-parent (which keeps a node's place as if it were the corner). The engine's boxes apply the origin.

Where a node may go

With subflows(), a node's extent bounds it: "parent" keeps it inside its parent, a flow rectangle { x, y, width, height } inside that rectangle (in its position's coordinates, so relative to its parent's top-left corner for a child). The root's nodeExtent bounds every node at once. Drags, the arrow keys and resizes keep a node's whole box inside every bound it has; a node larger than its bounds keeps to their top-left corner.

const nodes: FlowNodeInput<Types>[] = [
    // with subflows(): this node stays inside a 400 × 300 area
    { id: "note", type: "note", position: { x: 20, y: 20 }, extent: { x: 0, y: 0, width: 400, height: 300 }, data: { text: "" } },
];
<Flow.Root defaultNodes={nodes} nodeExtent={{ x: -500, y: -500, width: 1000, height: 1000 }} className="h-96">
    …
</Flow.Root>

The model itself keeps only "parent" (with the sizes the document gives): a rectangle is kept by the gestures, so node.move from your code may place a node outside it.

Z-order

Nodes are drawn in the order of their zIndex (default 0), then of the document; a child is always above its parent. A selected node rises above the others, its children with it, while the root's elevateNodesOnSelect is on (the default). Edges are ordered by their zIndex the same way. Change an order from code with two commands, null putting the default back:

model.run("node.set-z-index", { nodeId: "note", zIndex: 10 });
model.run("edge.set-z-index", { edgeId: "fetch-parse", zIndex: null });

Whether an edge may stand above nodes is the root's zIndexMode:

zIndexModenodesedges
"basic"by zIndex, a selected one raised (elevateNodesOnSelect), a child above its parentby zIndex, a selected one raised among the edges (elevateEdgesOnSelect, off by default); every edge below every node
"auto" (the default)as in "basic"as high as its zIndex, and at least as high as its ends when one of them is a child (an edge between a group's children stands above the group); a selected one is raised above the nodes (elevateEdgesOnSelect defaults to true here)
"manual"only their zIndexonly their zIndex: one above a node's is drawn above it
<Flow.Root defaultNodes={nodes} defaultEdges={edges} zIndexMode="basic" elevateNodesOnSelect={false} elevateEdgesOnSelect>
    …
</Flow.Root>

These are this package's own choices, not React Flow's defaults: React Flow defaults to "basic", and its "basic" already lifts an edge to the z of an end that is a child or selected. Here "basic" keeps every edge below every node, which is what you want when a selected edge must never cover a node. "auto" is the default because it keeps a sub-flow's edges visible above their group and a selected edge visible above the nodes it crosses. Turn elevateEdgesOnSelect off to keep "auto"'s sub-flow order without raising the selected edge. The same two props, zIndexMode and elevateEdgesOnSelect, are the root's in React, Vue, Svelte and Angular.

How it is drawn

The engine splits the flow into ordered levels (engine.get("render-layers")): one, the edges below the nodes, unless an edge stands above some node. With one level the DOM is exactly the usual one: an edges SVG in Flow.Edges, then the nodes in Flow.Nodes. With several, Flow.Edges holds one wrapper per level, data-flow-part="edges-layer" with data-level (0 the lowest) and the level's z-index, each with its SVG (data-flow-part="edges") and its edges' labels; the nodes stay in their one nodes layer, which drops its isolation then, and their z-indexes interleave with the levels' in the viewport. A node never changes wrapper, so it keeps its state, focus and measurement; an edge that changes level is remounted (in Angular, moved) and gets its focus back.

flow.css
/* the wrappers only appear while an edge stands above a node */
[data-flow-part="edges-layer"][data-level="1"] [data-flow-part="edge-path"] {
    stroke-width: 2;
}

For the layering to work, your CSS must not make Flow.Nodes or Flow.Edges a stacking context: no opacity below 1, transform, filter, isolation or z-index on them (style a wrapper of yours around Flow.Viewport, or the nodes themselves, instead). The adapters put a node's order in its structural z-index (a selected node's is raised by 10 000; a negative rank while there are several levels), so a z-index of yours on a node is overridden; the first render takes the same value from the document's static geometry.

The rules the model keeps

  • Ids are unique, among nodes and among edges. A node or an edge added without an id gets one from createId(kind) (an option of createFlowModel and of the root), by default node-1, edge-1, … The model never uses a global crypto.
  • Edges join existing, connectable nodes. edge.add refuses a missing node, a node with connectable: false, and a second edge joining the same handles in the same direction. A self loop is allowed; forbid it in a middleware if your flow does not want it (Connection rules).
  • An edge never dangles. Removing a node removes its edges in the same step (and, with subflows(), its children), whatever the edges' own deletable.
  • Flags hold for code too. draggable: false refuses node.move from a drag and from your code; deletable: false refuses node.remove; selectable: false refuses selection.set. Change a flag with node.set-flags or edge.set-flags.
  • A feature's field needs its feature. selected needs selection(); parentId, extent and expandParent need subflows(). A document carrying one without it is refused, with the path of each problem.

Loading and validating

import { createFlowModel, FlowValidationError, validateFlow } from "@fragiola/flow-react";

try {
    const model = createFlowModel<Types, typeof features>(json, { features });
} catch (error) {
    if (error instanceof FlowValidationError) {
        for (const issue of error.issues) console.warn(issue.path, issue.message);
    }
}

// or, without throwing: every problem with its JSON path, none for a valid document
const issues = validateFlow(json, { features });

model.get("flow-json") gives the document back as a writable copy, every id present: it loads again into createFlowModel unchanged. See Flow JSON.

Reading nodes and edges

model.get("node-by", { id: "fetch" });                              // a node, or undefined
model.get("all-nodes");                                             // every node, in drawing order
model.get("node-edges-by", { nodeId: "fetch", handleType: "source" }); // the edges that start there
model.get("connected-edges-by", { nodeIds: ["fetch", "parse"] });   // the edges touching either
model.get("absolute-position-by", { nodeId: "fetch" });             // with its parents' positions added
model.is("node-deletable", { nodeId: "fetch" });

In a component under the root, useNodes() and useEdges() re-render on every change, and useSelection() when the selection changes (in Vue, computed refs that change then; in Svelte, their current; in Angular, signals) (Hooks).

Controlled or not

The root creates its model from defaultNodes and defaultEdges, read once. Or control them: give nodes and edges with onNodesChange and onEdgesChange, and the root brings the model to your lists with the commands a user would have run, so middleware and listeners still see every change. There are no change objects to apply: onNodesChange receives the nodes themselves, and a middleware or model.subscribe sees every command with its payload.

const [nodes, setNodes] = useState<readonly FlowNode<Types>[]>(initialNodes);

<Flow.Root<Types, typeof features>
    features={features}
    nodes={nodes}
    onNodesChange={setNodes}
    defaultEdges={edges}
>
    …
</Flow.Root>;

Controlled nodes need every id. In React, keep the children functions stable when the app re-renders on each change (a module function, useCallback), or every node re-renders.