{
  "$schema": "https://ui.shadcn.com/schema/registry-item.json",
  "name": "graph",
  "title": "Graph",
  "description": "A canvas for nodes and wires: React Flow with the theme's colours, a grid drawn as dots, lines or crosses, snapping, groups that size themselves and keep apart, and nodes lined up in rows or columns inside them. Every React Flow prop passes through.",
  "dependencies": [
    "@xyflow/react@^12.12.1",
    "motion@^13.2.0"
  ],
  "registryDependencies": [
    "@pipecat/graph-tone"
  ],
  "files": [
    {
      "path": "src/components/graph/graph.tsx",
      "content": "\"use client\";\n\nimport {\n  Background,\n  BackgroundVariant,\n  type Edge,\n  type Node,\n  ReactFlow,\n  type ReactFlowInstance,\n  type ReactFlowProps,\n  type ReactFlowState,\n  type XYPosition,\n  useNodesInitialized,\n  useReactFlow,\n  useStore,\n} from \"@xyflow/react\";\nimport { animate } from \"motion/react\";\nimport { useEffect, useRef } from \"react\";\n\nimport {\n  boxGroups,\n  type GroupDirection,\n  lineUpGroups,\n  separateGroups,\n} from \"@/components/pipecat/graph/group-layout\";\nimport {\n  type GraphTone,\n  graphToneStyle,\n} from \"@/components/pipecat/graph/tone\";\nimport { cn } from \"@/lib/utils\";\n\nconst PATTERNS = {\n  dots: BackgroundVariant.Dots,\n  lines: BackgroundVariant.Lines,\n  cross: BackgroundVariant.Cross,\n} as const;\n\nexport type GraphPattern = keyof typeof PATTERNS | \"none\";\n\n/** How a graph is framed: all of it in view, never zoomed in past actual size. */\nexport const GRAPH_FIT = { padding: 0.08, maxZoom: 1 } as const;\n\n/** Groups pushed out of the way land on this spring. */\nconst GLIDE = {\n  type: \"spring\",\n  stiffness: 420,\n  damping: 22,\n  mass: 0.8,\n} as const;\n\ntype Glide = ReturnType<typeof animate>;\n\n/** How a group lays out its nodes: in a row, in a column, or wherever they are put. */\nexport type GraphGroupPacking = GroupDirection | \"off\";\n\nexport type ArrangeOptions = {\n  /** The grid's pitch in px. */\n  grid: number;\n  /** Line each group's nodes up in a row or a column. Off unless set. */\n  groups?: GraphGroupPacking;\n  /** Keep groups apart. On unless `false`. */\n  separate?: boolean;\n  /** The least room between two groups, in cells. Three unless set. */\n  gap?: number;\n  /** The groups that stay put: the ones just dragged. */\n  anchors?: readonly string[];\n};\n\n/**\n * Tidies the groups: lines their nodes up if asked, boxes each around its\n * nodes, and parts the ones that crowd each other. Sizes change at once and\n * whatever has to move glides there. Returns the glide, so it can be stopped.\n */\nexport function arrangeGroups<N extends Node, E extends Edge>(\n  flow: ReactFlowInstance<N, E>,\n  {\n    grid,\n    groups = \"off\",\n    separate = true,\n    gap = 3,\n    anchors = [],\n  }: ArrangeOptions,\n): Glide | null {\n  // React Flow's own measurements, in case the nodes' state has yet to catch up.\n  const start = flow.getNodes().map((node) => ({\n    ...node,\n    measured: flow.getInternalNode(node.id)?.measured ?? node.measured,\n  }));\n  const lined = groups === \"off\" ? start : lineUpGroups(start, grid, groups);\n  const boxed = boxGroups(lined, grid);\n  const end = separate ? separateGroups(boxed, anchors, grid, gap) : boxed;\n\n  const from = new Map(start.map((node) => [node.id, node.position]));\n  const to = new Map<string, XYPosition>();\n  for (const node of end) {\n    const was = from.get(node.id);\n    if (was && (was.x !== node.position.x || was.y !== node.position.y))\n      to.set(node.id, node.position);\n  }\n  const still = window.matchMedia(\"(prefers-reduced-motion: reduce)\").matches;\n  if (to.size === 0 || still) {\n    flow.setNodes(end);\n    return null;\n  }\n  // A group and its nodes move in step, so nothing drifts on the way.\n  const at = (id: string, progress: number) => {\n    const a = from.get(id);\n    const b = to.get(id);\n    return a && b\n      ? { x: a.x + (b.x - a.x) * progress, y: a.y + (b.y - a.y) * progress }\n      : undefined;\n  };\n  flow.setNodes(\n    end.map((node) => ({ ...node, position: at(node.id, 0) ?? node.position })),\n  );\n  return animate(0, 1, {\n    ...GLIDE,\n    onUpdate: (progress) =>\n      flow.setNodes((nodes) =>\n        nodes.map((node) => {\n          const position = at(node.id, progress);\n          return position ? { ...node, position } : node;\n        }),\n      ),\n  });\n}\n\ntype ArrangementProps = Required<\n  Pick<ArrangeOptions, \"grid\" | \"groups\" | \"separate\" | \"gap\">\n> & { glideRef: React.RefObject<Glide | null> };\n\ntype Sizes = Map<string, string>;\n\n/** The measured size of every node inside a group, by its id. */\nfunction childSizes({ nodeLookup }: ReactFlowState) {\n  const sizes: Sizes = new Map();\n  for (const [id, node] of nodeLookup)\n    if (node.parentId !== undefined)\n      sizes.set(id, `${node.measured.width}x${node.measured.height}`);\n  return sizes;\n}\n\nconst sameSizes = (a: Sizes, b: Sizes) =>\n  a.size === b.size && [...a].every(([id, size]) => b.get(id) === size);\n\n/**\n * Arranges the groups once the nodes are measured, and again when an option\n * changes or a node inside a group changes size.\n */\nfunction Arrangement({\n  glideRef,\n  grid,\n  groups,\n  separate,\n  gap,\n}: ArrangementProps) {\n  const flow = useReactFlow();\n  const measured = useNodesInitialized();\n  const sizes = useStore(childSizes, sameSizes);\n  const arranged = useRef<Sizes | null>(null);\n  // React Flow measures nodes outside React, so this has to wait for it.\n  useEffect(() => {\n    if (!measured) return;\n    const before = arranged.current;\n    arranged.current = sizes;\n    // A drag arranges the groups itself, when it ends.\n    if (flow.getNodes().some((node) => node.dragging)) return;\n    // The group of a node that changed size stays put, and the rest make room.\n    const anchors: string[] = [];\n    for (const [id, size] of before ? sizes : []) {\n      const group = flow.getNode(id)?.parentId;\n      if (group !== undefined && before?.get(id) !== size) anchors.push(group);\n    }\n    const glide = arrangeGroups(flow, { grid, groups, separate, gap, anchors });\n    glideRef.current = glide;\n    return () => glide?.stop();\n  }, [flow, glideRef, grid, groups, separate, gap, measured, sizes]);\n  return null;\n}\n\nexport interface GraphProps<\n  N extends Node = Node,\n  E extends Edge = Edge,\n> extends ReactFlowProps<N, E> {\n  /** The pitch of the grid in px: of its pattern, and of what nodes snap to. */\n  grid?: number;\n  /** How the grid is drawn. */\n  pattern?: GraphPattern;\n  /** Land nodes on the grid as they are dragged. */\n  snap?: boolean;\n  /** Box each group around its nodes, on the grid, and keep groups a gap apart. */\n  packGrid?: boolean;\n  /** The least room `packGrid` leaves between two groups, in grid cells. */\n  groupGap?: number;\n  /** Line each group's nodes up in a row or a column, and box the group around them. */\n  packGroups?: GraphGroupPacking;\n  /** The tone everything inside takes until a node, group or wire names its own. */\n  tone?: GraphTone;\n}\n\n/**\n * A canvas for nodes and wires: React Flow with the theme's colours, a grid\n * and a few defaults. Every React Flow prop passes through, and anything put\n * inside it can use React Flow's hooks.\n */\nexport function Graph<N extends Node = Node, E extends Edge = Edge>({\n  grid = 24,\n  pattern = \"dots\",\n  snap = false,\n  packGrid = false,\n  groupGap = 3,\n  packGroups = \"off\",\n  tone,\n  className,\n  style,\n  children,\n  onInit,\n  onNodeDragStart,\n  onNodeDragStop,\n  ...props\n}: GraphProps<N, E>) {\n  const flow = useRef<ReactFlowInstance<N, E> | null>(null);\n  const glide = useRef<Glide | null>(null);\n  const arrange = packGrid || packGroups !== \"off\";\n  const options = {\n    grid,\n    groups: packGroups,\n    separate: packGrid,\n    gap: groupGap,\n  };\n\n  return (\n    <ReactFlow<N, E>\n      data-slot=\"graph\"\n      data-tone={tone}\n      fitView\n      fitViewOptions={GRAPH_FIT}\n      minZoom={0.3}\n      maxZoom={1.6}\n      connectionRadius={38}\n      snapToGrid={snap}\n      snapGrid={[grid, grid]}\n      {...props}\n      className={cn(\n        // React Flow reads its colours from these. A node type that shares a\n        // name with one of its own (\"group\", \"default\") gets none of its chrome.\n        \"[--xy-node-border-selected:none] [--xy-node-border:none] [--xy-node-color:inherit]\",\n        \"[--xy-attribution-background-color:transparent] [--xy-background-color:var(--graph-canvas,var(--background))] [--xy-background-pattern-color:var(--graph-grid,color-mix(in_oklab,var(--foreground)_18%,var(--background)))] [--xy-selection-background-color:color-mix(in_oklab,var(--foreground)_6%,transparent)] [--xy-selection-border:1.5px_dashed_var(--muted-foreground)]\",\n        className,\n      )}\n      style={{ ...graphToneStyle(tone), ...style }}\n      onInit={(instance) => {\n        flow.current = instance;\n        onInit?.(instance);\n      }}\n      onNodeDragStart={(event, node, nodes) => {\n        // Whatever is still gliding stops, so the drag starts from where it is.\n        glide.current?.stop();\n        onNodeDragStart?.(event, node, nodes);\n      }}\n      onNodeDragStop={(event, node, nodes) => {\n        if (arrange && flow.current) {\n          const anchors = nodes.map(\n            (dragged) => dragged.parentId ?? dragged.id,\n          );\n          glide.current = arrangeGroups(flow.current, { ...options, anchors });\n        }\n        onNodeDragStop?.(event, node, nodes);\n      }}\n    >\n      {pattern === \"none\" ? null : (\n        <Background\n          variant={PATTERNS[pattern]}\n          gap={grid}\n          size={pattern === \"dots\" ? 1.7 : undefined}\n        />\n      )}\n      {arrange ? <Arrangement glideRef={glide} {...options} /> : null}\n      {children}\n    </ReactFlow>\n  );\n}\n",
      "type": "registry:component",
      "target": "components/pipecat/graph/graph.tsx"
    },
    {
      "path": "src/components/graph/group-layout.ts",
      "content": "import type { Node, XYPosition } from \"@xyflow/react\";\n\n/*\n * A group is a node with children: nodes whose `parentId` is its id. These\n * functions keep groups tidy. They only read and return nodes, so they work on\n * any graph, with or without the canvas.\n */\n\ntype Box = XYPosition & { width: number; height: number };\n\n/** A guard against a pathological chain of pushes. */\nconst MAX_PUSHES = 200;\n\n/** Room a group leaves around its nodes, in whole cells. The top is deeper, for its tag. */\nconst padding = (grid: number) => ({ x: grid, top: grid * 2, bottom: grid });\n\n/** A size a node was given comes first: React Flow's measurement of it lags a render behind. */\nfunction sizeOf(node: Node) {\n  return {\n    width: node.width ?? node.measured?.width ?? node.initialWidth ?? 0,\n    height: node.height ?? node.measured?.height ?? node.initialHeight ?? 0,\n  };\n}\n\nexport type GroupDirection = \"horizontal\" | \"vertical\";\n\n/** Room between two nodes lined up in a group: three cells in a row, for a wire, two in a column. */\nconst spacing = (grid: number, direction: GroupDirection) =>\n  grid * (direction === \"horizontal\" ? 3 : 2);\n\nfunction childrenOf<N extends Node>(nodes: N[]) {\n  const children = new Map<string, N[]>();\n  for (const node of nodes) {\n    if (node.parentId === undefined) continue;\n    children.set(node.parentId, [...(children.get(node.parentId) ?? []), node]);\n  }\n  return children;\n}\n\n/**\n * Lines each group's children up from its corner: in a row along their tops,\n * or in a column down their left edges. They keep the order they already have\n * along that line, so a node dropped past its neighbour changes places with it.\n */\nexport function lineUpGroups<N extends Node>(\n  nodes: N[],\n  grid: number,\n  direction: GroupDirection,\n): N[] {\n  const pad = padding(grid);\n  const row = direction === \"horizontal\";\n  const placed = new Map<string, XYPosition>();\n  for (const inside of childrenOf(nodes).values()) {\n    const ordered = [...inside].sort((a, b) =>\n      row\n        ? a.position.x - b.position.x || a.position.y - b.position.y\n        : a.position.y - b.position.y || a.position.x - b.position.x,\n    );\n    let at = row ? pad.x : pad.top;\n    for (const child of ordered) {\n      const { width, height } = sizeOf(child);\n      placed.set(child.id, row ? { x: at, y: pad.top } : { x: pad.x, y: at });\n      // The next one starts on the grid, clear of this one.\n      at =\n        Math.ceil((at + (row ? width : height)) / grid) * grid +\n        spacing(grid, direction);\n    }\n  }\n  return nodes.map((node) => {\n    const to = placed.get(node.id);\n    return to && (to.x !== node.position.x || to.y !== node.position.y)\n      ? { ...node, position: to }\n      : node;\n  });\n}\n\n/**\n * Boxes every group around its children, on the grid, a cell clear of them.\n * The group moves and resizes, and its children shift the other way, so\n * nothing moves on screen but the group's edges. A group with no children\n * keeps the size it has.\n */\nexport function boxGroups<N extends Node>(nodes: N[], grid: number): N[] {\n  const children = childrenOf(nodes);\n  const pad = padding(grid);\n  const shifts = new Map<string, XYPosition>();\n  const boxes = new Map<string, Box>();\n\n  for (const node of nodes) {\n    const inside = children.get(node.id);\n    if (!inside) continue;\n    let left = Infinity;\n    let top = Infinity;\n    let right = -Infinity;\n    let bottom = -Infinity;\n    for (const child of inside) {\n      const { width, height } = sizeOf(child);\n      left = Math.min(left, child.position.x);\n      top = Math.min(top, child.position.y);\n      right = Math.max(right, child.position.x + width);\n      bottom = Math.max(bottom, child.position.y + height);\n    }\n    // The corner is rounded to the grid and the size up to whole cells.\n    const x =\n      Math.round((node.position.x + left - pad.x) / grid) * grid -\n      node.position.x;\n    const y =\n      Math.round((node.position.y + top - pad.top) / grid) * grid -\n      node.position.y;\n    shifts.set(node.id, { x, y });\n    boxes.set(node.id, {\n      x: node.position.x + x,\n      y: node.position.y + y,\n      width: Math.ceil((right + pad.x - x) / grid) * grid,\n      height: Math.ceil((bottom + pad.bottom - y) / grid) * grid,\n    });\n  }\n\n  return nodes.map((node) => {\n    const box = boxes.get(node.id);\n    if (box) {\n      const same =\n        box.x === node.position.x &&\n        box.y === node.position.y &&\n        box.width === node.width &&\n        box.height === node.height;\n      return same\n        ? node\n        : {\n            ...node,\n            position: { x: box.x, y: box.y },\n            width: box.width,\n            height: box.height,\n          };\n    }\n    const shift =\n      node.parentId === undefined ? undefined : shifts.get(node.parentId);\n    return shift && (shift.x !== 0 || shift.y !== 0)\n      ? {\n          ...node,\n          position: {\n            x: node.position.x - shift.x,\n            y: node.position.y - shift.y,\n          },\n        }\n      : node;\n  });\n}\n\n/**\n * How far `b` has to move to clear `a` by the gap, the shortest way out, or\n * null if it already does.\n */\nfunction separation(a: Box, b: Box, room: number): XYPosition | null {\n  const clear =\n    b.x >= a.x + a.width + room ||\n    b.x + b.width + room <= a.x ||\n    b.y >= a.y + a.height + room ||\n    b.y + b.height + room <= a.y;\n  if (clear) return null;\n  const ways: XYPosition[] = [\n    { x: a.x + a.width + room - b.x, y: 0 },\n    { x: a.x - room - (b.x + b.width), y: 0 },\n    { x: 0, y: a.y + a.height + room - b.y },\n    { x: 0, y: a.y - room - (b.y + b.height) },\n  ];\n  return ways.reduce((best, way) =>\n    Math.abs(way.x) + Math.abs(way.y) < Math.abs(best.x) + Math.abs(best.y)\n      ? way\n      : best,\n  );\n}\n\n/**\n * Moves top-level groups apart until no two are closer than `gap` cells, edge\n * to edge: three unless told otherwise, and none at all lets them touch. Anchors\n * (the group just dragged, say) stay put and push the others; a pushed group\n * can push the next one along. With no anchors, groups hold their ground in\n * the order they come. A node outside any group is moved out of a group's way\n * but pushes nothing itself. Children ride along with their group.\n */\nexport function separateGroups<N extends Node>(\n  nodes: N[],\n  anchors: readonly string[],\n  grid: number,\n  gap = 3,\n): N[] {\n  const children = childrenOf(nodes);\n  const boxes = new Map<string, Box>();\n  const groups = new Set<string>();\n  for (const node of nodes) {\n    if (node.parentId !== undefined) continue;\n    boxes.set(node.id, { ...node.position, ...sizeOf(node) });\n    if (children.has(node.id) || node.type === \"group\") groups.add(node.id);\n  }\n\n  const room = grid * gap;\n  const fixed = new Set(anchors.filter((id) => boxes.has(id)));\n  const queue = [...fixed].filter((id) => groups.has(id));\n  // Every group gets a turn at pushing, so two that crowd each other far from\n  // an anchor are parted too.\n  const waiting = [...groups].filter((id) => !fixed.has(id));\n  for (let pushes = 0; pushes < MAX_PUSHES;) {\n    const pusherId = queue.shift() ?? waiting.shift();\n    if (pusherId === undefined) break;\n    const pusher = boxes.get(pusherId);\n    if (!pusher) continue;\n    for (const [id, box] of boxes) {\n      if (id === pusherId || fixed.has(id)) continue;\n      const push = separation(pusher, box, room);\n      if (!push) continue;\n      boxes.set(id, { ...box, x: box.x + push.x, y: box.y + push.y });\n      if (groups.has(id)) queue.push(id);\n      pushes += 1;\n    }\n  }\n\n  return nodes.map((node) => {\n    const box = boxes.get(node.id);\n    return box && (box.x !== node.position.x || box.y !== node.position.y)\n      ? { ...node, position: { x: box.x, y: box.y } }\n      : node;\n  });\n}\n",
      "type": "registry:lib",
      "target": "components/pipecat/graph/group-layout.ts"
    }
  ],
  "css": {
    "@import \"@xyflow/react/dist/base.css\" layer(base)": {}
  },
  "docs": "Graph takes React Flow's props (nodes, edges, nodeTypes, edgeTypes and so on) plus grid, pattern, snap, packGrid, groupGap, packGroups and tone. Give it a parent with a height. Colour the canvas with --graph-canvas and --graph-grid. React Flow's stylesheet is imported into the base layer, so utilities can restyle its nodes, edges and handles.",
  "categories": [
    "graph"
  ],
  "type": "registry:component"
}