{
  "$schema": "https://ui.shadcn.com/schema/registry-item.json",
  "name": "flow-diagram",
  "type": "registry:ui",
  "title": "Flow Diagram",
  "description": "A diagram of boxes joined by arrows that the person edits: nodes dragged or moved with the arrow keys, joined by pressing C and choosing the next node (or by pointer), removed with Delete, zoomed and panned; every change said aloud and the whole diagram also given as a list of steps and links.",
  "categories": [
    "ui"
  ],
  "dependencies": [
    "lucide-react"
  ],
  "registryDependencies": [
    "@rivier-ui/theme",
    "@rivier-ui/announce",
    "@rivier-ui/cn",
    "@rivier-ui/use-controllable-state"
  ],
  "files": [
    {
      "path": "registry/ui/flow-diagram.tsx",
      "type": "registry:ui",
      "target": "components/ui/flow-diagram.tsx",
      "content": "\"use client\";\n/**\n * @name flow-diagram\n * @category ui\n * @description A diagram of boxes joined by arrows that the person edits: nodes dragged or moved with the arrow keys, joined by pressing C and choosing the next node (or by pointer), removed with Delete, zoomed and panned; every change said aloud and the whole diagram also given as a list of steps and links.\n * @when Processes, pipelines and simple node graphs the person builds or rearranges: an approval flow, a data pipeline, a decision tree. For a graph to look at, laid out automatically, use network-graph; for stages with amounts use sankey-chart; for work moving between columns use kanban.\n * @example\n * const [nodes, setNodes] = useState([{ id: \"a\", label: \"Order placed\", x: 40, y: 60 }, { id: \"b\", label: \"Paid\", x: 260, y: 60 }]);\n * const [edges, setEdges] = useState([{ id: \"a-b\", source: \"a\", target: \"b\" }]);\n * <FlowDiagram aria-label=\"Order flow\" nodes={nodes} edges={edges} onNodesChange={setNodes} onEdgesChange={setEdges} />\n */\nimport { Minus, Plus, RotateCcw } from \"lucide-react\";\nimport { useId, useRef, useState, type ComponentProps, type KeyboardEvent, type PointerEvent } from \"react\";\nimport { announce } from \"@/lib/announce\";\nimport { cn } from \"@/lib/cn\";\nimport { useControllableState } from \"@/lib/use-controllable-state\";\n\nexport type FlowNode = {\n  id: string;\n  label: string;\n  x: number;\n  y: number /** A short line under the label. */;\n  note?: string /** \"start\" and \"end\" are drawn round. */;\n  kind?: \"step\" | \"start\" | \"end\" | \"decision\";\n};\nexport type FlowEdge = { id: string; source: string; target: string; label?: string };\n\nexport type FlowDiagramLabels = {\n  diagram: string;\n  node: string;\n  help: string;\n  connecting: (from: string) => string;\n  connected: (from: string, to: string) => string;\n  removed: (what: string) => string;\n  moved: (node: string, x: number, y: number) => string;\n  links: string;\n  noLinks: string;\n  linksFrom: (node: string, targets: string) => string;\n  zoomIn: string;\n  zoomOut: string;\n  reset: string;\n  cancelled: string;\n};\n\nconst LABELS: FlowDiagramLabels = {\n  diagram: \"diagram\",\n  node: \"step\",\n  help: \"Tab moves between steps. Arrow keys move a step, with Shift further. C starts a link from the step; then Enter on another step ends it, Escape cancels. Delete removes a step and its links.\",\n  connecting: (from) => `Linking from ${from}: go to another step and press Enter, or Escape to cancel.`,\n  connected: (from, to) => `${from} now leads to ${to}`,\n  removed: (what) => `${what} removed`,\n  moved: (node, x, y) => `${node} moved to ${x}, ${y}`,\n  links: \"Steps and links\",\n  noLinks: \"leads nowhere\",\n  linksFrom: (node, targets) => `${node} leads to ${targets}`,\n  zoomIn: \"Zoom in\",\n  zoomOut: \"Zoom out\",\n  reset: \"Reset the view\",\n  cancelled: \"Link cancelled\",\n};\n\nexport type FlowDiagramProps = Omit<ComponentProps<\"div\">, \"defaultValue\"> & {\n  nodes?: readonly FlowNode[];\n  defaultNodes?: readonly FlowNode[];\n  onNodesChange?: (nodes: readonly FlowNode[]) => void;\n  edges?: readonly FlowEdge[];\n  defaultEdges?: readonly FlowEdge[];\n  onEdgesChange?: (edges: readonly FlowEdge[]) => void;\n  /** Nothing can be changed; the diagram can still be read, zoomed and panned. */\n  readOnly?: boolean;\n  /** The grid nodes snap to, in diagram units. Default 10. */\n  grid?: number;\n  /** Height in pixels. Default 360. */\n  height?: number;\n  labels?: Partial<FlowDiagramLabels>;\n};\n\nconst NODE_W = 160;\nconst NODE_H = 56;\nconst EMPTY_NODES: readonly FlowNode[] = [];\nconst EMPTY_EDGES: readonly FlowEdge[] = [];\n\nexport function FlowDiagram({\n  nodes: nodesProp,\n  defaultNodes = EMPTY_NODES,\n  onNodesChange,\n  edges: edgesProp,\n  defaultEdges = EMPTY_EDGES,\n  onEdgesChange,\n  readOnly = false,\n  grid = 10,\n  height = 360,\n  labels: given,\n  className,\n  \"aria-label\": ariaLabel,\n  ...props\n}: FlowDiagramProps) {\n  const labels = { ...LABELS, ...given };\n  const [nodes, setNodes] = useControllableState<readonly FlowNode[]>({ value: nodesProp, defaultValue: defaultNodes, onChange: onNodesChange });\n  const [edges, setEdges] = useControllableState<readonly FlowEdge[]>({ value: edgesProp, defaultValue: defaultEdges, onChange: onEdgesChange });\n  const [view, setView] = useState({ k: 1, x: 0, y: 0 });\n  const [selected, setSelected] = useState<string | null>(null);\n  const [linkFrom, setLinkFrom] = useState<string | null>(null);\n  const drag = useRef<{ id: string; dx: number; dy: number; moved: boolean } | null>(null);\n  const pan = useRef<{ x: number; y: number; vx: number; vy: number } | null>(null);\n  const helpId = useId();\n  const nameOf = (id: string): string => nodes.find((n) => n.id === id)?.label ?? id;\n  const snap = (v: number): number => Math.round(v / grid) * grid;\n\n  const moveNode = (id: string, x: number, y: number): void => setNodes(nodes.map((n) => (n.id === id ? { ...n, x: snap(x), y: snap(y) } : n)));\n  const connect = (from: string, to: string): void => {\n    setLinkFrom(null);\n    if (from === to || edges.some((e) => e.source === from && e.target === to)) return;\n    setEdges([...edges, { id: `${from}-${to}`, source: from, target: to }]);\n    announce(labels.connected(nameOf(from), nameOf(to)));\n  };\n  const removeNode = (id: string): void => {\n    const name = nameOf(id);\n    setNodes(nodes.filter((n) => n.id !== id));\n    setEdges(edges.filter((e) => e.source !== id && e.target !== id));\n    announce(labels.removed(name));\n    setSelected(null);\n  };\n\n  const onNodeKeyDown = (node: FlowNode, event: KeyboardEvent<SVGGElement>): void => {\n    const step = (event.shiftKey ? 5 : 1) * grid;\n    const moves: Record<string, [number, number]> = { ArrowLeft: [-step, 0], ArrowRight: [step, 0], ArrowUp: [0, -step], ArrowDown: [0, step] };\n    const move = moves[event.key];\n    if (move && !readOnly) {\n      event.preventDefault();\n      // The canvas is not mirrored in a right-to-left page: Right is always further right.\n      const x = snap(node.x + move[0]);\n      const y = snap(node.y + move[1]);\n      moveNode(node.id, x, y);\n      announce(labels.moved(node.label, x, y));\n    } else if ((event.key === \"c\" || event.key === \"C\") && !readOnly) {\n      event.preventDefault();\n      setLinkFrom(node.id);\n      announce(labels.connecting(node.label));\n    } else if (event.key === \"Enter\" || event.key === \" \") {\n      event.preventDefault();\n      if (linkFrom && linkFrom !== node.id) connect(linkFrom, node.id);\n      else setSelected(node.id);\n    } else if (event.key === \"Escape\" && linkFrom) {\n      event.preventDefault();\n      setLinkFrom(null);\n      announce(labels.cancelled);\n    } else if ((event.key === \"Delete\" || event.key === \"Backspace\") && !readOnly) {\n      event.preventDefault();\n      removeNode(node.id);\n    }\n  };\n  const local = (event: PointerEvent<Element>, svg: SVGSVGElement): { x: number; y: number } => {\n    const box = svg.getBoundingClientRect();\n    return { x: (event.clientX - box.left - view.x) / view.k, y: (event.clientY - box.top - view.y) / view.k };\n  };\n  const zoom = (factor: number): void => setView((v) => ({ ...v, k: Math.max(0.4, Math.min(2.5, v.k * factor)) }));\n\n  const centre = (n: FlowNode): { x: number; y: number } => ({ x: n.x + NODE_W / 2, y: n.y + NODE_H / 2 });\n  // A link leaves the side of the box facing its target and arrives at the side facing its source.\n  const anchor = (from: FlowNode, to: FlowNode): { x: number; y: number } => {\n    const a = centre(from);\n    const b = centre(to);\n    const dx = b.x - a.x;\n    const dy = b.y - a.y;\n    if (Math.abs(dx) * NODE_H > Math.abs(dy) * NODE_W) return { x: a.x + (Math.sign(dx) * NODE_W) / 2, y: a.y };\n    return { x: a.x, y: a.y + (Math.sign(dy) * NODE_H) / 2 };\n  };\n\n  return (\n    <div data-slot=\"flow-diagram\" className={cn(\"relative w-full min-w-0 overflow-hidden rounded-surface border bg-card\", className)} style={{ height }} {...props}>\n      <svg\n        role=\"application\"\n        aria-roledescription={labels.diagram}\n        aria-label={ariaLabel}\n        aria-describedby={helpId}\n        direction=\"ltr\"\n        className=\"block size-full touch-none select-none\"\n        onPointerDown={(event) => {\n          if (event.target !== event.currentTarget) return;\n          setSelected(null);\n          pan.current = { x: event.clientX, y: event.clientY, vx: view.x, vy: view.y };\n          event.currentTarget.setPointerCapture(event.pointerId);\n        }}\n        onPointerMove={(event) => {\n          const svg = event.currentTarget;\n          if (drag.current) {\n            const p = local(event, svg);\n            drag.current.moved = true;\n            moveNode(drag.current.id, p.x - drag.current.dx, p.y - drag.current.dy);\n          } else if (pan.current) {\n            const start = pan.current;\n            setView((v) => ({ ...v, x: start.vx + event.clientX - start.x, y: start.vy + event.clientY - start.y }));\n          }\n        }}\n        onPointerUp={() => {\n          drag.current = null;\n          pan.current = null;\n        }}\n      >\n        <defs>\n          <marker id={`${helpId}-arrow`} viewBox=\"0 0 10 10\" refX=\"9\" refY=\"5\" markerWidth=\"7\" markerHeight=\"7\" orient=\"auto-start-reverse\">\n            <path d=\"M0,0 L10,5 L0,10 z\" className=\"fill-muted-foreground\" />\n          </marker>\n          <pattern id={`${helpId}-dots`} width={grid * 2} height={grid * 2} patternUnits=\"userSpaceOnUse\">\n            <circle cx={1} cy={1} r={1} className=\"fill-border\" />\n          </pattern>\n        </defs>\n        <g transform={`translate(${view.x},${view.y}) scale(${view.k})`}>\n          <rect x={-5000} y={-5000} width={10000} height={10000} fill={`url(#${helpId}-dots)`} pointerEvents=\"none\" />\n          <g aria-hidden=\"true\">\n            {edges.map((edge) => {\n              const from = nodes.find((n) => n.id === edge.source);\n              const to = nodes.find((n) => n.id === edge.target);\n              if (!from || !to) return null;\n              const a = anchor(from, to);\n              const b = anchor(to, from);\n              const mx = (a.x + b.x) / 2;\n              const horizontal = Math.abs(b.x - a.x) > Math.abs(b.y - a.y);\n              const d = horizontal ? `M${a.x},${a.y} C${mx},${a.y} ${mx},${b.y} ${b.x},${b.y}` : `M${a.x},${a.y} C${a.x},${(a.y + b.y) / 2} ${b.x},${(a.y + b.y) / 2} ${b.x},${b.y}`;\n              const lit = selected === edge.source || selected === edge.target;\n              return (\n                <g key={edge.id}>\n                  <path d={d} fill=\"none\" className={lit ? \"stroke-foreground\" : \"stroke-muted-foreground\"} strokeWidth={lit ? 2 : 1.5} markerEnd={`url(#${helpId}-arrow)`} />\n                  {edge.label ? (\n                    <text x={mx} y={(a.y + b.y) / 2 - 6} textAnchor=\"middle\" className=\"fill-muted-foreground stroke-card text-xs\" paintOrder=\"stroke\" strokeWidth={4}>\n                      {edge.label}\n                    </text>\n                  ) : null}\n                </g>\n              );\n            })}\n          </g>\n          {nodes.map((node) => {\n            const isSelected = selected === node.id;\n            const isSource = linkFrom === node.id;\n            const round = node.kind === \"start\" || node.kind === \"end\";\n            return (\n              <g\n                key={node.id}\n                data-slot=\"flow-diagram-node\"\n                role=\"group\"\n                aria-roledescription={labels.node}\n                aria-label={`${node.label}${node.note ? `, ${node.note}` : \"\"}`}\n                tabIndex={0}\n                transform={`translate(${node.x},${node.y})`}\n                className=\"cursor-grab outline-none focus-visible:[&>rect:first-of-type]:stroke-ring focus-visible:[&>rect:first-of-type]:[stroke-width:3]\"\n                onKeyDown={(event) => onNodeKeyDown(node, event)}\n                onFocus={() => setSelected(node.id)}\n                onPointerDown={(event) => {\n                  event.stopPropagation();\n                  const svg = event.currentTarget.ownerSVGElement;\n                  if (!svg) return;\n                  if (linkFrom && linkFrom !== node.id) {\n                    connect(linkFrom, node.id);\n                    return;\n                  }\n                  setSelected(node.id);\n                  if (readOnly) return;\n                  const p = local(event, svg);\n                  drag.current = { id: node.id, dx: p.x - node.x, dy: p.y - node.y, moved: false };\n                  svg.setPointerCapture(event.pointerId);\n                }}\n              >\n                <rect\n                  width={NODE_W}\n                  height={NODE_H}\n                  className={cn(\n                    isSelected ? \"fill-highlight-soft stroke-foreground\" : \"fill-card stroke-border-strong\",\n                    round ? \"[rx:28px]\" : node.kind === \"decision\" ? \"[rx:0]\" : \"[rx:min(var(--radius),10px)]\",\n                  )}\n                  strokeWidth={isSelected ? 2 : 1}\n                  strokeDasharray={isSource ? \"4 3\" : undefined}\n                />\n                <text x={NODE_W / 2} y={node.note ? NODE_H / 2 - 6 : NODE_H / 2} dy=\"0.32em\" textAnchor=\"middle\" className=\"fill-foreground text-sm font-medium\" pointerEvents=\"none\">\n                  {node.label.length > 20 ? `${node.label.slice(0, 19)}…` : node.label}\n                </text>\n                {node.note ? (\n                  <text x={NODE_W / 2} y={NODE_H / 2 + 12} dy=\"0.32em\" textAnchor=\"middle\" className=\"fill-muted-foreground text-xs\" pointerEvents=\"none\">\n                    {node.note.length > 26 ? `${node.note.slice(0, 25)}…` : node.note}\n                  </text>\n                ) : null}\n                {!readOnly ? (\n                  <circle\n                    cx={NODE_W}\n                    cy={NODE_H / 2}\n                    r={6}\n                    className=\"fill-background stroke-foreground\"\n                    onPointerDown={(event) => {\n                      // The handle starts a link: the next node pressed is its end.\n                      event.stopPropagation();\n                      setLinkFrom(node.id);\n                      announce(labels.connecting(node.label));\n                    }}\n                  />\n                ) : null}\n              </g>\n            );\n          })}\n        </g>\n      </svg>\n      <span id={helpId} className=\"sr-only\">\n        {readOnly ? \"\" : labels.help}\n      </span>\n      <div className=\"absolute end-2 top-2 flex flex-col overflow-hidden rounded-control border bg-background\">\n        <button type=\"button\" aria-label={labels.zoomIn} onClick={() => zoom(1.25)} className=\"flex size-9 items-center justify-center hover:bg-accent pointer-coarse:size-11\">\n          <Plus aria-hidden=\"true\" className=\"size-4\" />\n        </button>\n        <button type=\"button\" aria-label={labels.zoomOut} onClick={() => zoom(0.8)} className=\"flex size-9 items-center justify-center border-y hover:bg-accent pointer-coarse:size-11\">\n          <Minus aria-hidden=\"true\" className=\"size-4\" />\n        </button>\n        <button type=\"button\" aria-label={labels.reset} onClick={() => setView({ k: 1, x: 0, y: 0 })} className=\"flex size-9 items-center justify-center hover:bg-accent pointer-coarse:size-11\">\n          <RotateCcw aria-hidden=\"true\" className=\"size-4\" />\n        </button>\n      </div>\n      <div className=\"sr-only\">\n        <h4>{labels.links}</h4>\n        <ul data-slot=\"flow-diagram-list\">\n          {nodes.map((node) => {\n            const targets = edges.filter((e) => e.source === node.id).map((e) => nameOf(e.target));\n            return <li key={node.id}>{targets.length > 0 ? labels.linksFrom(node.label, targets.join(\", \")) : `${node.label}: ${labels.noLinks}`}</li>;\n          })}\n        </ul>\n      </div>\n    </div>\n  );\n}\n"
    }
  ],
  "meta": {
    "category": "ui",
    "when": "Processes, pipelines and simple node graphs the person builds or rearranges: an approval flow, a data pipeline, a decision tree. For a graph to look at, laid out automatically, use network-graph; for stages with amounts use sankey-chart; for work moving between columns use kanban.",
    "example": "const [nodes, setNodes] = useState([{ id: \"a\", label: \"Order placed\", x: 40, y: 60 }, { id: \"b\", label: \"Paid\", x: 260, y: 60 }]);\nconst [edges, setEdges] = useState([{ id: \"a-b\", source: \"a\", target: \"b\" }]);\n<FlowDiagram aria-label=\"Order flow\" nodes={nodes} edges={edges} onNodesChange={setNodes} onEdgesChange={setEdges} />",
    "client": true
  }
}
