Fragiola

API: core (@fragiola/flow)

The JSON document

The version 1 flow document of nodes and edges, every field and flag, its JSON Schemas, and how to validate a document before loading it.

A flow is one JSON document: { version: 1, nodes, edges }. It is the model's whole state, the selection and the sub-flow hierarchy included (when their features are installed); the viewport is not in it (it is view state, the engine's). model.get("flow-json") returns it as a writable copy with every id present, and createFlowModel(json) loads it back, so saving a flow is JSON.stringify and restoring it is one call.

flow.json
{
    "version": 1,
    "nodes": [
        { "id": "start", "type": "trigger", "position": { "x": 0, "y": 0 }, "data": { "event": "push" } },
        { "id": "build", "type": "task", "position": { "x": 0, "y": 140 }, "data": { "title": "Build" }, "deletable": false }
    ],
    "edges": [
        { "id": "start-build", "source": "start", "target": "build", "type": "smoothstep" }
    ]
}

The document is frozen once loaded, ids are explicit (generated by createId when a node or edge comes without one), and a field of a feature that is not installed is a validation issue, never dropped silently.

The registry

FlowTypes is the app's registry of node and edge types and their data, the type argument T of every typed API (see Typed data):

fieldtypedescription
nodesobjecteach node type and the shape of its data: { task: { title: string } }
edgesobjecteach app edge type and the shape of its data (the built-in types may be given too)
import type { FlowNode, FlowTypes } from "@fragiola/flow-react";

interface Types extends FlowTypes {
    readonly nodes: { trigger: { event: string }; task: { title: string } };
    readonly edges: { dependency: { weight: number } };
}

declare const node: FlowNode<Types>;
if (node.type === "task") node.data.title; // string: the type narrows the data

AnyTypes types nothing (any type, any JSON object as data): the default. NodeTypeOf<T>, NodeDataOf<T, K>, EdgeTypeOf<T> (the built-in types and the app's) and EdgeDataOf<T, K> read a registry. BuiltInEdgeType is "bezier" | "simplebezier" | "smoothstep" | "step" | "straight".

The document

FlowJson<T> is a document as createFlowModel and validateFlow take it:

fieldtypedescription
version1the format's version
nodesFlowNodeInput<T>[]the nodes, in drawing order
edgesFlowEdgeInput<T>[]the edges, in drawing order

FlowNodeInput<T> and FlowEdgeInput<T> are a node and an edge whose id may be left out (what node.add and edge.add take too). FlowDocument<T> is the document as the model holds it (readonly, every id present: event.before, ctx.state), FlowDocumentJson<T> the writable copy get("flow-json") returns. XY is a point, { x, y }: x grows to the right, y grows down.

Nodes

FlowNode<T> is a union over the registry's node types, so checking type narrows data. A node of one type is a NodeOf<K, D>:

fieldtypedescription
idstringits id, unique among the nodes
typeKits type, a key of the registry's nodes
dataDthe app's data, a JSON object (required)

What every node has, whatever its type (NodeFields):

fieldtypedescription
positionXYwhere it stands, in flow coordinates (relative to its parent's top-left corner with sub-flows): its box's top-left corner, or the point origin (else the engine's nodeOrigin) names
widthnumberits fixed width: it wins over the measured one, and draws its edges before it is measured (a server render)
heightnumberits fixed height
initialWidthnumber (>= 0)its width until it is measured (a server render, the first client render, fitView on init); width wins
initialHeightnumber (>= 0)its height until it is measured; height wins
handlesDeclaredHandle[]its handles, declared so its edges are drawn before it is rendered and measured (below); a measured handle of the same type and id always wins
sourcePositionHandleSidethe side its edges leave by when no handle (rendered or declared) gives one; default "bottom"
targetPositionHandleSidethe side its edges enter by when no handle gives one; default "top"
originXYthe point of its box its position stands at, as shares of its size ({ x: 0.5, y: 0.5 }: its centre), over the engine's nodeOrigin for this node; a child keeps its top-left corner in its parent, as with nodeOrigin
zIndexnumber (an integer)its place in the stacking order: a greater one is drawn above (a child always above its parent, except in zIndexMode: "manual"); default 0

DeclaredHandle, a handle the node declares in the document ({ id?, type, position, x, y, width?, height? }). Its point, where an edge ends, is the centre of its box: the same point the engine measures for a rendered handle, so the server's edges and the measured ones meet at the same place (React Flow ends an edge on the box's side instead). It is matched to an edge's sourceHandle / targetHandle as a rendered handle is: with an id, the one of that type and id; without, the first of that type with no id, else the first of that type.

fieldtypedescription
idstringits id among the node's handles of its type; none: the node's default handle
type"source" | "target"whether edges start or end at it
positionHandleSidethe side of the node it sits on: the direction an edge leaves or enters by
xnumberits box's left edge, relative to the node box's left edge, in flow units
ynumberits box's top edge, relative to the node box's top edge
widthnumberits box's width; default 0
heightnumberits box's height; default 0
flow.json (a node that draws its edges on the server)
{
    "id": "order",
    "type": "card",
    "position": { "x": 0, "y": 0 },
    "data": { "label": "Order" },
    "width": 160,
    "height": 60,
    "handles": [
        { "type": "target", "position": "left", "x": -4, "y": 26, "width": 8, "height": 8 },
        { "type": "source", "position": "right", "x": 156, "y": 26, "width": 8, "height": 8 }
    ]
}

Its permission flags (NodeFlags); an absent flag is its default, and the commands enforce them, for the user's gestures and for your code alike:

flagdefaultdescription
draggabletrueit may be moved (node.move)
selectabletrueit may be selected (selection.set)
connectabletrueedges may start or end at it (edge.add, edge.reconnect)
deletabletrueit may be removed (node.remove, selection.remove)
hiddenfalseit is not shown (its edges neither)
focusabletrueit takes DOM focus with keyboard() (node-focusable; the engine's nodesFocusable turns every node's off)

The fields of selection() (SelectionFields, on nodes and edges alike):

fieldtypedescription
selectedbooleanit is selected; absent when not

The fields of subflows() (SubflowFields):

fieldtypedescription
parentIdstringthe node it lives in: its position is relative to it
extent"parent" | Rect"parent": it stays inside its parent's box; a Rect ({ x, y, width, height }): inside that rectangle, in the coordinates of its position (relative to its parent for a child); the engine keeps it during drags, arrows and resizes
expandParentbooleanits parent grows to keep it inside when it moves or grows past it

Edges

FlowEdge<T> is a union over the edge types. An edge of one type is an EdgeOf<K, D>:

fieldtypedescription
idstringits id, unique among the edges
typeKhow it is drawn: a BuiltInEdgeType or the app's type; none is "bezier"
dataDthe app's data, optional

What every edge has (EdgeFields):

fieldtypedescription
sourcestringthe node it starts at
targetstringthe node it ends at
sourceHandlestringthe source node's handle it starts at; none: the node's default source handle
targetHandlestringthe target node's handle it ends at; none: the node's default target handle
zIndexnumber (an integer)its place in the edges' drawing order: a greater one is drawn above; with zIndexMode "basic" edges stay under the nodes, with "auto" and "manual" one above a node's value is drawn above it (z-order); default 0
pathOptionsEdgePathOptionsthe shape of its path, over the engine's pathOptions key by key (below); a controlled sync that changes them replaces the edge

EdgePathOptions, each built-in type reading its own keys (the others are ignored):

optiontypedescription
curvaturenumberbezier: the share of the distance a control point stands out by
borderRadiusnumbersmooth step: the corners' radius, in flow units
offsetnumbersmooth step and step: how far an end stands out before turning
stepPositionnumbersmooth step and step: where the turn sits between the source (0) and the target (1)
centerXnumbersmooth step and step: the x of a vertical turn, in flow coordinates
centerYnumbersmooth step and step: the y of a horizontal turn, in flow coordinates

Its flags (EdgeFlags):

flagdefaultdescription
selectabletrueit may be selected
deletabletrueit may be removed (edge.remove, selection.remove); removing a node removes its edges whatever their flag
hiddenfalseit is not drawn
reconnectabletrueits ends may be moved (edge.reconnect): both (true), none (false), or only its "source" or its "target" end (the reconnect anchor of the other end draws nothing, and a press near it grabs nothing)
focusabletrueit takes DOM focus with keyboard() (edge-focusable; the engine's edgesFocusable turns every edge's off)
animatedfalseit is drawn animated: its parts carry data-animated, which the app's CSS animates (edge.set-flags toggles it)

The rules beyond the fields: one edge per pair of handles and direction (a second is refused), a self loop is allowed (forbid it in a middleware), and every source, target and parentId names a node of the document. With sub-flows, children may come before their parent and a parent cycle is an issue.

isNode(value) and isEdge(value) tell a node from an edge by its shape (a node: a string id and a position, no source or target; an edge: a string id, source and target), as type guards for a mixed list. They are not a validation: validateFlow is.

The schemas

flowDocumentSchema, nodeSchema and edgeSchema are the document's JSON Schemas (a JsonSchema: the subset of JSON Schema 2020-12 the core's validator checks), with a description on every field: give them to a back-end, a form, or an assistant that writes flows. FromSchema<S> is the TypeScript type a schema of that subset describes (the core's own type tests use it to keep each command's schema and payload type in step). JsonValue is a JSON value, JsonSchemaType the types a schema names.

Validating

validateFlow(json, options?) returns every problem of a document as a ValidationIssue, or none; it never throws for a document. createFlowModel throws a FlowValidationError with the same issues. Validate what comes back from storage or from a network before you load it:

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

function restore(raw: string | null) {
    let json: unknown = null;
    try {
        json = JSON.parse(raw ?? "null");
    } catch {
        // not JSON: start empty
    }
    const valid = json !== null && validateFlow(json, { features }).length === 0;
    return createFlowModel<Types, typeof features>(valid ? (json as FlowJson<Types>) : undefined, { features });
}

ValidateFlowOptions:

optiontypedescription
featuresFlowFeaturesthe features installed: a field of one not given is an issue; default none

ValidationIssue:

fieldtypedescription
pathstringwhere: a JSON pointer (RFC 6901), /nodes/2/position/x
messagestringwhat is wrong

Saving and restoring in an app: Saving and restoring flows.