# flow: the node canvas, and the workflow components

`flow` is an element the runtime builds (`runtime/page/flow.mote`, part `FL`): what
React Flow is to AI Elements' workflow components. `kit/flow.mote` is those
components over it, under their names. Gallery: `examples/kit/flow.mote`.
Test: `tests/kit_flow.real.mjs`.

    state nodes: Step[] = [{id: "a", x: 0, y: 0, title: "Start"}, {id: "b", x: 420, y: 80, title: "End"}]
    state edges: Wire[] = [{id: "e1", from: "a", to: "b", animated: true}]

    action changed(e: string)
      let ev: json = JSON.parse(e)
      match ev.type
        "move"
          for m in ev.nodes
            let hit = nodes.find(s => s.id == m.id)
            if hit
              hit.x = m.x
              hit.y = m.y
        "connect"
          edges.push({id: uid(), from: ev.from, to: ev.to, animated: false})
        "remove"
          nodes = nodes.filter(s => !ev.nodes.includes(s.id))
          edges = edges.filter(w => !ev.edges.includes(w.id) && !ev.nodes.includes(w.from) && !ev.nodes.includes(w.to))

    view height=560
      Canvas edges=edges change=changed
        for s in nodes key=s.id
          Node id=s.id x=s.x y=s.y target source
            NodeHeader
              NodeTitle s.title
              NodeDescription "What it does"
              NodeAction
                Button size="sm" variant="ghost" press=…
            NodeContent
              text "Anything"
            NodeFooter
              text "Status: ready"
          Toolbar for=s.id
            Button size="sm" variant="ghost" press=…
        Panel position="top-left"
          Button size="sm" press=add
        Controls

## The element

    flow edges=edges zoom=z x=vx y=vy locked=lk change=changed height=500
      view id="a" data-x=0 data-y=0 …        a node: any markup
      view data-panel="top-right" …           stays put over the canvas
      view data-toolbar-for="a" data-side="top" …   floats beside node a

**Children.** Every child is a node unless it is marked otherwise. A node
carries `id`, `data-x`, `data-y` (canvas coordinates of its top left corner;
0 if missing) and is whatever markup the page writes. `data-panel` (top-left
top-center top-right bottom-left bottom-center bottom-right) makes a child an
overlay that does not pan or zoom. `data-toolbar-for="nodeId"` makes it that
node's toolbar: it floats 8px off the node's `data-side` (top right bottom
left; bottom if missing), at its own size whatever the zoom, and shows while
the node is selected or under the pointer. Children come and go with `for`
and `if` as anywhere.

**Attributes.**

- `edges`: a list of `{id?, from, to, fromHandle?, toHandle?, kind?, animated?, dashed?, label?, color?, arrow?}`.
  `from` and `to` are node ids. `kind`: `"bezier"` (the default: a smooth
  cubic), `"smoothstep"` (right angles, rounded), `"step"` (right angles),
  `"straight"`. `animated`: a dot travels the edge on a 2 s loop and the
  stroke is a flowing dash. `dashed`: a still dashed stroke (the "temporary"
  look). `label`: text at the midpoint. `color`: any CSS colour. `arrow`:
  an arrowhead at the target. An edge with no `id` is named `from->to` in
  events. An edge whose node is not there is not drawn.
- `zoom`, `x`, `y`: the view (canvas point (0,0) is at `x`, `y` in the
  element; `zoom` is held between 0.2 and 2). Written back as the user pans
  and zooms when the page gave state. When none of the three has a value
  when the canvas first has a size and nodes, it fits everything in view
  (and writes that back): give `state vx: number? = none` to have both.
- `locked`: no dragging, no nudging, no connecting, no removing. Panning,
  zooming and selecting still work. Written back when a `data-flow="lock"`
  control is pressed.
- Styles on the element are honoured; it has `min-height: 160px` unless told.
  Give it a height (or a sized parent and `height=100%`).

**Marks it reads** (plain attributes, on the element or inside it):

- `data-handle="source"` / `"target"` on an element inside a node, with an
  optional `data-handle-id`: a connection point. An edge ends at the handle's
  centre and leaves by the side of the node the handle is nearest. With
  `fromHandle` / `toHandle` an edge picks a handle by id; otherwise the first
  of its kind. A node with no handle of the kind takes edges at the middle of
  its right (source) or left (target) side.
- `data-flow="zoom-in" | "zoom-out" | "fit" | "lock"` on anything inside: a
  press on it does that. `data-flow-when="locked"` / `"unlocked"` inside:
  shown only then (the lock button's two icons); the lock control gets
  `aria-pressed`.
- `data-nodrag` inside a node: a press starting there does not drag the node
  (inputs, textareas, selects, buttons and links are so already).
  `data-nowheel`: the wheel over it is left to it (a scrolling list in a node).
- `data-select="drag"` on the element: a mouse drag on the background draws a
  selection box instead of panning (the wheel still pans, the middle button
  drags the view, a finger pans). Canvas sets it.
- It sets `data-selected` on selected nodes, `data-open` on shown toolbars,
  `data-locked` and `data-connecting` on itself.

**What the user can do.**

- Pan: drag the background, two-finger scroll (the wheel), middle-button
  drag, or two fingers on a touch screen. Zoom: pinch, or ctrl/cmd + wheel,
  about the pointer. Keys `+` `-` zoom, `0` fits.
- Select: click a node or press near an edge; shift-click adds or removes;
  shift-drag on the background (any drag there under `data-select="drag"`)
  draws a box; ctrl/cmd+A takes all nodes; a press on the background or
  Escape lets go. A focused node is selected with Enter or Space.
- Move: drag a node by its body: all selected nodes go with it. Arrow keys
  nudge the selection by 1 (10 with shift).
- Connect: drag from a source handle. A bezier with a circle at the pointer
  follows it (this is AI Elements' Connection) and takes hold of a target
  handle within 28px, or of the node under the pointer. Let go on one and
  the page is told; let go elsewhere and nothing happens.
- Remove: Delete or Backspace asks the page to remove what is selected.

**Events.** One event, `change`, handed a JSON string:

    {type: "move", nodes: [{id, x, y}]}          at the end of a drag or a nudge (whole numbers)
    {type: "select", nodes: [ids], edges: [ids]} whenever the selection changes
    {type: "connect", from, to, fromHandle, toHandle}   handle ids, or null
    {type: "remove", nodes: [ids], edges: [ids]} Delete / Backspace: the page decides
    {type: "view", x, y, zoom}                   150 ms after the view last changed

Positions are the page's data. During a drag the element moves the node
itself; when the drag ends it says `move`, and from then on the node is
wherever the page's `data-x` / `data-y` say. A page that does not write the
move down gets the node back where it was. The same for `remove` and
`connect`: nothing changes until the page changes its lists.

Between events the element's `value` is `{}`: a field inside a node whose own
`change` bubbles up to the page's handler arrives as `{}`, with no `type`.

**From script.** `node.hkFit()` fits everything in view; `node.hkZoom(by)`
multiplies the zoom about the middle (both glide for 180 ms).

**Size.** One container is transformed for pan and zoom; a moved node updates
only its own edges; handles are measured when a node appears, changes inside
or changes size (ResizeObserver). Dragging in a graph of 200 nodes and 300
edges stays under 20 ms a frame in the test.

## The components

| AI Elements | Mote | |
|---|---|---|
| `<Canvas>` | `Canvas edges=edges change=changed` | props: `edges`, `zoom`, `x`, `y`, `locked`, `change`. The `flow` with the AI defaults: fits on open, the wheel pans, a drag on the background selects. Fills its parent (`width=100% height=100%`, at least 240 tall). |
| `<Node handles={{target, source}}>` | `Node id="a" x=0 y=0 target source` | props: `id`, `x`, `y`, and the handles as two bools: `target` on the left edge, `source` on the right. A card 320 wide (`Node width=240` to change). |
| `<NodeHeader>` | `NodeHeader` | the tinted top band; lays out title, description and action |
| `<NodeTitle>` | `NodeTitle "Start"` | |
| `<NodeDescription>` | `NodeDescription "Initialize workflow"` | |
| `<NodeAction>` | `NodeAction` | children at the header's top right |
| `<NodeContent>` | `NodeContent` | |
| `<NodeFooter>` | `NodeFooter` | the tinted bottom band |
| `<Edge.Animated>` | `{from, to, animated: true}` in `edges` | an edge is data, not a component |
| `<Edge.Temporary>` | `{from, to, dashed: true}` in `edges` | |
| `<Connection>` | built into `flow` | the live line while a new edge is dragged from a handle |
| `<Controls>` | `Controls position="bottom-left"` | zoom in, zoom out, fit view, lock. `position`: Panel's six words (bottom-left if missing) |
| `<Panel position>` | `Panel position="top-left"` | `position`: top-left top-center top-right bottom-left bottom-center bottom-right (top-left if missing) |
| `<Toolbar>` | `Toolbar for="a" side="bottom"` | a node's toolbar. `for`: the node's id. `side`: top right bottom left (bottom if missing) |

`FlowControlButton does="fit" label="Fit view"` is the button Controls is
made of (`does`: zoom-in zoom-out fit lock), there for a page that builds its
own controls.

## What differs from the original

- Nodes and edges are not typed registries (`nodeTypes`, `edgeTypes`): a node
  is the markup written under Canvas, an edge is a record with `kind`,
  `animated`, `dashed`. There is no way to draw a custom edge.
- No context: Toolbar is a sibling of its Node, not a child, and names it
  with `for`. (Inside the node it would scale with the zoom and be clipped by
  it.) Node takes `id`, `x`, `y` itself, where React Flow keeps them in the
  `nodes` array.
- State is the page's only (React Flow's "controlled" way): there is no
  `defaultNodes` / uncontrolled mode, and no `onNodesChange` /
  `applyNodeChanges` helpers: one `change` event, five types.
- `handles` is two bool props; their places are fixed (target left, source
  right). For handles elsewhere, write the element with `data-handle` in a
  node of your own.
- Canvas's view props are typed `json`, not `number?`: the `flow` element
  refuses a value that may be none, and "no view given" is how it knows to
  fit. Pass numbers, or state of type `number?`.
- Controls' lock locks dragging and connecting, not selection.
- A handle only starts a connection if it is a source; a connection is valid
  when it ends on a target handle (or a node with none) of another node. No
  `isValidConnection`: the page refuses by not adding the edge.
- Not there: minimap, node resizer, edge reconnection by dragging an end,
  snap-to-grid, `deleteKeyCode` and the other key options, viewport extent
  limits. Fit view does not zoom in past 1.
- React-only: `asChild`, `className`, refs, `useReactFlow` and the other
  hooks (`hkFit` / `hkZoom` and the `data-flow` marks stand in for the two
  the Controls need).
