Editors / Flow

Flow

Steps as nodes, typed ports, edges that carry a run. Laid out for you, left to right.

Package
@forgeron/flow
Layers
core (no React) · /plugins · /react · /plugins/editor
Built on
@forgeron/canvas · @forgeron/ui automation blocks
Trigger:
Deal moved to WonCRM · deal.stage = won
Fetch the customerData hub · customers.get()
Over 5,000?If · amount > 5000
Tell #salesChat · postMessage()
Draft an invoiceInvoices · draft()
Send a thank-youMail · send()
Tell #sales
Deal moved to Won
Fetch the customer
Over 5,000?
Draft an invoice
Send a thank-you
The flow as JSON

dragfrom a port to connect⇧Lauto-layout⌫delete⌘Dduplicate⌘Zundo

/01 → Features come from plugins

core only: nodes, edges, ports as datadrag the invoice to the second payment: the rule says why nota kind no plugin draws stays in the graph, as a dashed box

/01 → A kind with its own port type and rule
import { definePlugin } from "@forgeron/flow";
import { FlowCanvas, defineEditorPlugin, useFlow } from "@forgeron/flow/react";
import { minimalEditorPlugins, typedEditorPlugins } from "@forgeron/flow/plugins/editor";

// A kind of node with a type of port of its own, and a rule that says why it refuses.
const money = defineEditorPlugin({
  core: definePlugin({
    id: "money",
    name: "Money",
    description: "Invoices and payments.",
    nodeKinds: {
      invoice: { label: "Invoice", outputs: [{ id: "bill", type: "invoice" }] },
      payment: { label: "Payment", inputs: [{ id: "due", type: "invoice" }] },
    },
    portTypes: { invoice: { label: "Invoice", color: "--accent" } },
    connectionRules: [
      {
        id: "paid-once",
        check: ({ source, target, graph }) =>
          source.type === "invoice" && target.type === "payment" &&
          graph.edges.some((e) => e.from.node === source.id)
            ? "already-paid"
            : null,
        messages: { "already-paid": "An invoice is paid once." },
      },
    ],
  }),
  nodeRenderers: { invoice: (n) => <Invoice node={n} />, payment: (n) => <Payment node={n} /> },
});

// A list at module scope: nodes and edges, the rules, and yours. A new list rebuilds the editor.
const plugins = [...typedEditorPlugins, money];
const flow = useFlow({ graph, plugins });
<FlowCanvas flow={flow} label="Billing" plugins={plugins} />;
/02 → What it covers
  • A graph document: nodes with typed ports, edges from an output to an input, groups; JSON with a version field.
  • Connection rules: matching types (or any), one edge per input unless it merges, no duplicate, no loop unless allowed.
  • Connect by dragging from a port; drop on a node to take its first free input, on the surface to add a step there.
  • Edges as curves or steps, with arrowheads; hover or select one for its “+” (insert a step) and its end (drag to reconnect, off to delete).
  • Auto-layout, layered left to right (Sugiyama): cycles broken, crossings reduced, edges straightened, on the grid. 500 nodes in about 2 ms.
  • Run state per node and edge (idle, running, success, error, skipped); items march along running edges, still under reduced motion.
  • Delete, duplicate, copy, cut and paste carry the edges between the nodes; every edit is one undo step of the canvas history.
  • The node body is yours (a render prop): here a StepCard with layout="node", the StepPicker to add and the StepInspector to edit.
/03 → Use it
/01 → A flow with steps as nodes
import "@forgeron/canvas/styles.css";
import "@forgeron/flow/styles.css";
import { FlowCanvas, FlowToolbar, useFlow } from "@forgeron/flow/react";
import { StepCard } from "@forgeron/ui";

export function Automation({ graph }) {
  const flow = useFlow({ graph });
  return (
    <FlowCanvas
      flow={flow}
      label="Automation editor"
      renderNode={(node, { selected, status }) => (
        <StepCard layout="node" {...node.data} selected={selected} status={status} />
      )}
      onConnectEnd={(from, point) => openPicker(from, point)}
      onInsert={(edge, point) => openPicker(edge, point)}
    >
      <FlowToolbar flow={flow} />
    </FlowCanvas>
  );
}
/02 → The graph without a view
import { applyLayout, connect, layoutGraph, planRun, serializeFlow } from "@forgeron/flow";

const r = connect(graph, { node: "if", port: "true" }, { node: "notify", port: "in" });
if (!r.ok) console.log(r.error); // "type", "occupied", "cycle"…
const laid = applyLayout(r.graph, layoutGraph(r.graph));
const frames = planRun(laid, (node) => ({ status: "success" }));
save(serializeFlow(laid));
/04 → Keys
Delete the selection (nodes and edges)⌫
Duplicate with inner edges⌘D
Copy as flow JSON⌘C
Paste⌘V
Auto-layout⇧L
Undo⌘Z
Select every node⌘A
Zoom to fit1
API → <FlowCanvas>
NameTypeDefaultDescription
flowFlowApi<D>—From useFlow: the canvas store, the graph and its edits.
renderNode(node, { selected, status }) => ReactNode—The body of a node inside its box; ports are drawn around it.
labelstring—Names the surface for assistive technology.
nodeLabel(node) => stringtype idNames a node for assistive technology; the run state is added.
runRunState—The state of each node and edge to show.
edgeStyle"bezier" | "orthogonal""bezier"Curves, or horizontal and vertical runs.
onConnectEnd(from, point) => void—A connection dropped on nothing.
onInsert(edge, point) => void—The “+” of an edge: shows it when given.
onNodeActivate(node) => void—Double click or Enter on a node.
controls / minimapbooleantrueThe zoom controls with undo, the minimap coloured by run state.
API → useFlow and the controller
NameTypeDefaultDescription
useFlow(options){ graph, connect, layout, grid, readOnly }—Creates the store once; later options are ignored.
currentFlowGraph<D>—The graph now, read back from the canvas items.
connect / connectEnds→ ConnectResult—Adds an edge when the rules allow it, or says why not.
addNode / insertOnEdge(node, from?) / (edgeId, node)—Adds a step, connected after a port or in the middle of an edge.
deleteSelection / duplicateSelection(edgeIds?) / ()—Nodes with their edges, as one undo step.
copySelection / paste() → json / (json?, at?)—Flow JSON of the selected nodes and the edges between them.
autoLayout(options?) → LayoutResult—Lays the flow out as one undo step.
load / toJSON(graph | json) / (space?)—Replaces the document; writes it.
API → Pure functions (@forgeron/flow)
NameTypeDefaultDescription
checkConnection(graph, from, to, options?) → ConnectError | null—missing-node, missing-port, same-node, type, duplicate, occupied, fan-out, cycle.
layoutGraph(graph, options?) → LayoutResult—Positions, layers, crossings left, edges reversed to break cycles.
planRun(graph, decide) → RunState[]—The frames of a run, wave by wave; untaken branches skipped.
parseFlow / serializeFlow(json) / (graph)—Version 1, checked; FlowFormatError otherwise.
insertOnEdge, extractSubgraph, pasteSubgraphgraph → graph—Edits that leave their input untouched.