{
  "$schema": "https://ui.shadcn.com/schema/registry-item.json",
  "name": "flow",
  "title": "Flow",
  "description": "Primitives for flows: a recharts Sankey chart that keeps each flow's colour downstream, draws drop-offs muted and highlights what a hovered node or band connects, with a tooltip, plus path steps joined by arrows.",
  "dependencies": [
    "recharts"
  ],
  "registryDependencies": [
    "https://www.dashboardblocks.com/r/radix/chart.json",
    "https://www.dashboardblocks.com/r/radix/format.json"
  ],
  "files": [
    {
      "path": "registry/components/dashboardblocks/flow.tsx",
      "content": "'use client'\n\nimport { useBlockState } from '@/registry/components/dashboardblocks/block-state'\nimport {\n  ChartPlaceholder,\n  ChartTooltipFrame,\n  ChartTooltipItem,\n} from '@/registry/components/dashboardblocks/chart'\nimport { formatNumber, formatPercent } from '@/registry/lib/dashboardblocks/format'\nimport { type KeyboardEvent, useEffect, useRef, useState } from 'react'\nimport {\n  ResponsiveContainer,\n  Sankey,\n  type SankeyLinkProps,\n  type SankeyNodeProps,\n  Tooltip,\n} from 'recharts'\n\nimport { cn } from '@/lib/utils'\n\ninterface FlowNode {\n  color?: string\n  id: string\n  /** `exit` draws grey, for people who left. `gap` draws nothing and holds its place, so a node after it keeps its column. */\n  kind?: 'default' | 'exit' | 'gap'\n  label: string\n}\n\ninterface FlowLink {\n  source: string\n  target: string\n  value: number\n}\n\ninterface FlowLayoutNode extends FlowNode {\n  color: string\n  column: number\n  value: number\n}\n\nconst flowPalette = [\n  'var(--color-chart-2)',\n  'var(--color-chart-3)',\n  'var(--color-chart-4)',\n  'var(--color-chart-5)',\n  'var(--color-chart-1)',\n]\nconst exitColor = 'var(--color-muted-foreground)'\n\n/** A path through the flow, drawn as its own band over the rest. */\ninterface FlowHighlight {\n  /** Node ids in order, one per column. */\n  nodes: string[]\n  /** How many took the whole path: the band's width. */\n  value: number\n}\n\nconst NODE_WIDTH = 8\n/** How long after the column before each column starts to draw, in milliseconds. */\nconst COLUMN_DELAY = 220\n\nconst flowStyles = `\n  @keyframes dashboardblocks-flow-draw {\n    from { stroke-dashoffset: 1; }\n    to { stroke-dashoffset: 0; }\n  }\n  @keyframes dashboardblocks-flow-fade {\n    from { opacity: 0; }\n  }\n  @media (prefers-reduced-motion: no-preference) {\n    [data-flow-drawing] [data-flow-draw], [data-flow-draw='band'] {\n      stroke-dasharray: 1;\n      animation: dashboardblocks-flow-draw 700ms cubic-bezier(0.2, 0, 0, 1) both;\n    }\n    [data-flow-draw='band'] { animation-duration: 450ms; }\n    [data-flow-drawing] [data-flow-fade] { animation: dashboardblocks-flow-fade 500ms cubic-bezier(0.2, 0, 0, 1) both; }\n  }\n`\nconst LABEL_GAP = 6\nconst TWO_LINE_LABEL_HEIGHT = 22\n/** About how tall a node's tooltip is, to keep it clear of the node's label and inside the chart. */\nconst TOOLTIP_HEIGHT = 56\n\nfunction getFlowTotals(nodes: FlowNode[], links: FlowLink[]) {\n  const totals = new Map(nodes.map((node) => [node.id, { in: 0, out: 0 }]))\n  for (const link of links) {\n    const source = totals.get(link.source)\n    const target = totals.get(link.target)\n    if (source) source.out += link.value\n    if (target) target.in += link.value\n  }\n  return totals\n}\n\nfunction getFlowColumns(nodes: FlowNode[], links: FlowLink[]) {\n  const columns = new Map<string, number>()\n  const visit = (id: string, seen: Set<string>): number => {\n    const known = columns.get(id)\n    if (known !== undefined) return known\n    const parents = links.filter((link) => link.target === id && !seen.has(link.source))\n    const column = parents.length\n      ? Math.max(...parents.map((link) => visit(link.source, new Set([...seen, id])) + 1))\n      : 0\n    columns.set(id, column)\n    return column\n  }\n  for (const node of nodes) visit(node.id, new Set())\n  return columns\n}\n\nfunction getFlowNodes(\n  nodes: FlowNode[],\n  links: FlowLink[],\n  colorBy: 'source' | 'target' = 'source',\n): FlowLayoutNode[] {\n  const totals = getFlowTotals(nodes, links)\n  const columns = getFlowColumns(nodes, links)\n  const lastColumn = Math.max(0, ...columns.values())\n  const placed = new Map<string, FlowLayoutNode>()\n  for (let column = 0; column <= lastColumn; column++) {\n    nodes\n      .filter((node) => columns.get(node.id) === column)\n      .forEach((node, index) => {\n        const total = totals.get(node.id)\n        placed.set(node.id, {\n          ...node,\n          color:\n            node.color ??\n            (node.kind === 'exit' ? exitColor : flowPalette[index % flowPalette.length]),\n          column,\n          value: total ? Math.max(total.in, total.out) : 0,\n        })\n      })\n  }\n  for (let column = 1; colorBy === 'source' && column <= lastColumn; column++) {\n    for (const original of nodes) {\n      const node = placed.get(original.id)\n      if (!node || node.column !== column || original.color || original.kind === 'exit') {\n        continue\n      }\n      const largest = links\n        .filter((link) => link.target === node.id)\n        .sort((a, b) => b.value - a.value)[0]\n      if (largest) node.color = placed.get(largest.source)?.color ?? node.color\n    }\n  }\n  return nodes.flatMap((node) => {\n    const laidOut = placed.get(node.id)\n    return laidOut ? [laidOut] : []\n  })\n}\n\n/** What the pointer is on; a node keeps the y its tooltip goes at, clear of its label. */\ntype FlowActive = { link: number } | { node: string; tooltipY: number } | null\n\ninterface FlowChartProps {\n  className?: string\n  /** @default 'source' */\n  colorBy?: 'source' | 'target'\n  /** The muted text beside a hovered band's value. @default its share of the source */\n  describeLink?: (\n    link: FlowLink,\n    source: FlowLayoutNode,\n    target: FlowLayoutNode,\n  ) => string\n  /** The muted text beside a hovered node's value. */\n  describeNode?: (node: FlowLayoutNode) => string\n  /** Draws the bands into and out of this node id stronger than the rest. */\n  emphasis?: string\n  format?: (value: number) => string\n  /** @default 280 */\n  height?: number\n  /** Lights one path and fades the rest. */\n  highlight?: FlowHighlight\n  /** Names the chart, and the sideways scroll region `minWidth` adds. @default 'Flow' */\n  label?: string\n  /**\n   * `inside` puts the last column's labels left of its bars, at the chart's right edge. `outside`\n   * puts them right of the bars, like every other column's, and spaces the columns evenly, so\n   * column `c` of `n` starts at `c / n` of the width.\n   * @default 'inside'\n   */\n  lastLabels?: 'inside' | 'outside'\n  links: FlowLink[]\n  /** Keeps labels legible in narrow cards: below this width the chart scrolls sideways. */\n  minWidth?: string\n  nodes: FlowNode[]\n  /** Makes each node a button that calls this. The chart is one tab stop, and the arrow keys move between nodes. */\n  onNodeSelect?: (node: FlowLayoutNode) => void\n}\n\nfunction FlowChart({\n  className,\n  colorBy = 'source',\n  describeLink,\n  describeNode,\n  emphasis,\n  format = (value) => formatNumber(value),\n  height = 280,\n  highlight,\n  label = 'Flow',\n  lastLabels = 'inside',\n  links,\n  minWidth,\n  nodes,\n  onNodeSelect,\n}: FlowChartProps) {\n  const [active, setActive] = useState<FlowActive>(null)\n  const [cursor, setCursor] = useState<string | null>(null)\n  const chart = useRef<HTMLDivElement>(null)\n  const state = useBlockState()\n  const laidOut = getFlowNodes(nodes, links, colorBy)\n  const byId = new Map(laidOut.map((node) => [node.id, node]))\n  const indexOf = new Map(laidOut.map((node, index) => [node.id, index]))\n  const lastColumn = Math.max(0, ...laidOut.map((node) => node.column))\n  const isGap = (id: string) => byId.get(id)?.kind === 'gap'\n  const lit = new Set(highlight?.nodes)\n  const highlightKey = highlight?.nodes.join('>')\n  const reachable = laidOut.filter((node) => node.kind !== 'gap')\n  const roving =\n    reachable.find((node) => node.id === cursor) ??\n    reachable.find((node) => lit.has(node.id)) ??\n    reachable[0]\n\n  const moveFocus = (from: FlowLayoutNode, key: string) => {\n    const column = reachable.filter((node) => node.column === from.column)\n    const at = column.indexOf(from)\n    let next: FlowLayoutNode | undefined\n    if (key === 'ArrowUp') next = column[at - 1]\n    else if (key === 'ArrowDown') next = column[at + 1]\n    else {\n      const side = reachable.filter(\n        (node) => node.column === from.column + (key === 'ArrowRight' ? 1 : -1),\n      )\n      next = side.find((node) => lit.has(node.id)) ?? side[Math.min(at, side.length - 1)]\n    }\n    if (!next) return\n    setCursor(next.id)\n    chart.current\n      ?.querySelector<SVGGElement>(`[data-flow-node=\"${CSS.escape(next.id)}\"]`)\n      ?.focus()\n  }\n  /** Where a link sits on the highlighted path, or -1 when it's off it. */\n  const segmentOf = (link: FlowLink) => {\n    const at = highlight ? highlight.nodes.indexOf(link.source) : -1\n    return at >= 0 && highlight?.nodes[at + 1] === link.target ? at : -1\n  }\n  // Drawing again when the data changes, so a new query draws in like the first.\n  const drawKey = links\n    .map((link) => `${link.source}>${link.target}:${link.value}`)\n    .join()\n  // Recharts keys each node by its position, so a resize mounts the nodes again: they only\n  // draw in until the data's first draw has ended.\n  const [drawnKey, setDrawnKey] = useState<string | null>(null)\n  useEffect(() => {\n    if (drawnKey === drawKey) return\n    const timer = setTimeout(() => setDrawnKey(drawKey), lastColumn * COLUMN_DELAY + 700)\n    return () => clearTimeout(timer)\n  }, [drawKey, drawnKey, lastColumn])\n  const data = {\n    links: links.flatMap((link) => {\n      const source = indexOf.get(link.source)\n      const target = indexOf.get(link.target)\n      return source === undefined || target === undefined\n        ? []\n        : [{ source, target, value: link.value }]\n    }),\n    nodes: laidOut.map((node) => ({ ...node, name: node.label })),\n  }\n\n  const isLinkActive = (link: FlowLink, index: number) => {\n    if (!active) return false\n    if ('link' in active) return active.link === index\n    return link.source === active.node || link.target === active.node\n  }\n  const isNodeActive = (node: FlowLayoutNode) => {\n    if (!active) return false\n    if ('node' in active) return active.node === node.id\n    const link = links[active.link]\n    return link?.source === node.id || link?.target === node.id\n  }\n\n  const tooltip = () => {\n    if (!active) return null\n    if ('link' in active) {\n      const link = links[active.link]\n      const source = link && byId.get(link.source)\n      const target = link && byId.get(link.target)\n      if (!link || !source || !target) return null\n      const share = formatPercent(source.value > 0 ? link.value / source.value : 0, {\n        maximumFractionDigits: 0,\n      })\n      return {\n        color: target.kind === 'exit' ? exitColor : source.color,\n        heading: `${source.label} → ${target.label}`,\n        name: describeLink\n          ? describeLink(link, source, target)\n          : `${share} of ${source.label}`,\n        value: link.value,\n      }\n    }\n    const node = byId.get(active.node)\n    if (!node) return null\n    return {\n      color: node.color,\n      heading: node.label,\n      name: describeNode?.(node),\n      value: node.value,\n    }\n  }\n\n  const renderLink = (shape: SankeyLinkProps) => {\n    const link = links[shape.index]\n    const source = link && byId.get(link.source)\n    const target = link && byId.get(link.target)\n    if (!link || !source || !target || source.kind === 'gap' || target.kind === 'gap') {\n      return <path />\n    }\n    const segment = segmentOf(link)\n    const emphasised =\n      emphasis !== undefined && (link.source === emphasis || link.target === emphasis)\n    const opacity = active\n      ? isLinkActive(link, shape.index)\n        ? 0.6\n        : 0.12\n      : highlight\n        ? segment >= 0\n          ? 0.24\n          : 0.12\n        : emphasis === undefined\n          ? 0.32\n          : emphasised\n            ? 0.5\n            : 0.2\n    const stroke =\n      target.kind === 'exit'\n        ? exitColor\n        : colorBy === 'target'\n          ? target.color\n          : source.color\n    const width = Math.max(1, shape.linkWidth)\n    const curve = (offset: number) =>\n      `M${shape.sourceX},${shape.sourceY + offset} C${shape.sourceControlX},${shape.sourceY + offset} ${shape.targetControlX},${shape.targetY + offset} ${shape.targetX},${shape.targetY + offset}`\n    const bandWidth =\n      highlight && segment >= 0 && link.value > 0\n        ? Math.min(width, Math.max(2, (width * highlight.value) / link.value))\n        : 0\n    return (\n      <g>\n        <path\n          data-flow-draw=''\n          d={curve(0)}\n          fill='none'\n          pathLength={1}\n          stroke={stroke}\n          strokeOpacity={target.kind === 'exit' ? opacity * 0.6 : opacity}\n          strokeWidth={width}\n          className='transition-[stroke-opacity] duration-200'\n          style={{ animationDelay: `${source.column * COLUMN_DELAY}ms` }}\n        />\n        {bandWidth > 0 && (\n          <path\n            key={highlightKey}\n            data-flow-draw='band'\n            d={curve((bandWidth - width) / 2)}\n            fill='none'\n            pathLength={1}\n            stroke={stroke}\n            strokeOpacity={target.kind === 'exit' ? 0.5 : 0.8}\n            strokeWidth={bandWidth}\n            className='pointer-events-none'\n            style={{ animationDelay: `${segment * COLUMN_DELAY}ms` }}\n          />\n        )}\n      </g>\n    )\n  }\n\n  const renderNode = (shape: SankeyNodeProps) => {\n    const node = byId.get(String((shape.payload as { id?: string }).id))\n    if (!node || node.kind === 'gap') return <g />\n    const last = lastLabels === 'inside' && node.column === lastColumn && lastColumn > 0\n    const dimmed = active !== null && !isNodeActive(node)\n    // Off the highlighted path the bar fades but its label stays readable.\n    const faded = !dimmed && highlight !== undefined && !lit.has(node.id)\n    const textX = last ? shape.x - LABEL_GAP : shape.x + shape.width + LABEL_GAP\n    const centre = shape.y + shape.height / 2\n    const twoLines = shape.height > TWO_LINE_LABEL_HEIGHT\n    const select = onNodeSelect\n      ? {\n          'aria-label': `${node.label} ${format(node.value)}`,\n          'aria-pressed': lit.has(node.id),\n          'data-flow-node': node.id,\n          onClick: () => {\n            setCursor(node.id)\n            onNodeSelect(node)\n          },\n          onFocus: () => setCursor(node.id),\n          onKeyDown: (event: KeyboardEvent) => {\n            if (event.key.startsWith('Arrow')) {\n              event.preventDefault()\n              moveFocus(node, event.key)\n              return\n            }\n            if (event.key !== 'Enter' && event.key !== ' ') return\n            event.preventDefault()\n            onNodeSelect(node)\n          },\n          role: 'button',\n          tabIndex: node.id === roving?.id ? 0 : -1,\n        }\n      : {}\n    return (\n      <g\n        {...select}\n        data-flow-fade=''\n        className={cn(\n          'group/flow-node focus-visible:outline-ring transition-opacity duration-200 outline-none focus-visible:outline-2 focus-visible:outline-offset-2',\n          onNodeSelect && 'cursor-pointer',\n        )}\n        opacity={dimmed ? 0.45 : 1}\n        style={{ animationDelay: `${node.column * COLUMN_DELAY}ms` }}\n      >\n        <rect\n          x={shape.x}\n          y={shape.y}\n          width={shape.width}\n          height={Math.max(1, shape.height)}\n          rx={2}\n          fill={node.color}\n          opacity={faded ? 0.35 : 1}\n          className='transition-opacity duration-200'\n        />\n        <foreignObject x={textX} y={centre} width={1} height={1} overflow='visible'>\n          <span\n            className={cn(\n              'bg-background absolute top-0 -translate-y-1/2 rounded-sm px-1 text-xs leading-tight whitespace-nowrap',\n              last ? 'right-0 -mr-1 text-end' : 'left-0 -ml-1',\n              onNodeSelect &&\n                'group-focus-visible/flow-node:ring-ring group-focus-visible/flow-node:ring-2',\n            )}\n          >\n            <span\n              className={faded ? 'text-muted-foreground' : 'text-foreground font-medium'}\n            >\n              {node.label}\n            </span>{' '}\n            <span\n              className={cn('text-muted-foreground tabular-nums', twoLines && 'block')}\n            >\n              {format(node.value)}\n            </span>\n          </span>\n        </foreignObject>\n      </g>\n    )\n  }\n\n  if (state) return <ChartPlaceholder className={className} height={height} />\n\n  return (\n    <div\n      role={minWidth ? 'region' : undefined}\n      aria-label={minWidth ? label : undefined}\n      // oxlint-disable-next-line jsx-a11y/no-noninteractive-tabindex -- a scrolling region must be focusable so keyboard users can reach the columns that don't fit\n      tabIndex={minWidth ? 0 : undefined}\n      className={cn(\n        minWidth &&\n          'focus-visible:ring-ring/50 -my-1 overflow-x-auto rounded-sm py-1 outline-none [scrollbar-width:thin] focus-visible:ring-3',\n        className,\n      )}\n    >\n      <style href='dashboardblocks-flow' precedence='default'>\n        {flowStyles}\n      </style>\n      <div\n        ref={chart}\n        role={onNodeSelect ? 'group' : 'img'}\n        aria-label={\n          onNodeSelect ? `${label}. Use the arrow keys to move between steps.` : label\n        }\n        style={{ height, minWidth }}\n      >\n        <div\n          key={drawKey}\n          data-flow-drawing={drawnKey === drawKey ? undefined : ''}\n          className='h-full [&_.recharts-surface]:overflow-visible'\n          onPointerLeave={() => setActive(null)}\n          style={{\n            width:\n              lastLabels === 'outside' && lastColumn > 0\n                ? `calc(100% * ${lastColumn} / ${lastColumn + 1} + ${NODE_WIDTH}px)`\n                : undefined,\n          }}\n        >\n          <ResponsiveContainer width='100%' height='100%'>\n            <Sankey\n              accessibilityLayer={false}\n              align='left'\n              data={data}\n              iterations={32}\n              link={renderLink}\n              margin={{ top: 0, right: 0, bottom: 0, left: 0 }}\n              node={renderNode}\n              nodePadding={12}\n              nodeWidth={NODE_WIDTH}\n              onMouseEnter={(item, type) => {\n                if (type === 'link' && 'linkWidth' in item) {\n                  const link = links[item.index]\n                  if (link && !isGap(link.source) && !isGap(link.target)) {\n                    setActive({ link: item.index })\n                  }\n                }\n                if (type === 'node' && 'payload' in item && 'id' in item.payload) {\n                  const id = String(item.payload.id)\n                  const { payload } = item\n                  const centre =\n                    'y' in payload && 'dy' in payload ? payload.y + payload.dy / 2 : 0\n                  const clear = TWO_LINE_LABEL_HEIGHT / 2 + LABEL_GAP * 2\n                  const tooltipY =\n                    centre + clear + TOOLTIP_HEIGHT <= height\n                      ? centre + clear\n                      : centre - clear - TOOLTIP_HEIGHT\n                  if (!isGap(id)) setActive({ node: id, tooltipY })\n                }\n              }}\n              sort={false}\n            >\n              <Tooltip\n                active={active !== null}\n                position={active && 'node' in active ? { y: active.tooltipY } : undefined}\n                content={() => {\n                  const item = tooltip()\n                  if (!item) return null\n                  return (\n                    <ChartTooltipFrame>\n                      <span className='font-medium'>{item.heading}</span>\n                      <ChartTooltipItem\n                        color={item.color}\n                        name={item.name}\n                        value={format(item.value)}\n                      />\n                    </ChartTooltipFrame>\n                  )\n                }}\n              />\n            </Sankey>\n          </ResponsiveContainer>\n        </div>\n      </div>\n    </div>\n  )\n}\n\ninterface FlowPathStep {\n  label: string\n}\n\nfunction FlowPathSteps({\n  className,\n  steps,\n}: {\n  className?: string\n  steps: FlowPathStep[]\n}) {\n  return (\n    <ol className={cn('flex flex-wrap items-center gap-x-1.5 text-sm', className)}>\n      {steps.map((step, index) => (\n        <li key={`${step.label}-${index}`} className='flex items-center gap-1.5'>\n          {index > 0 && (\n            <span aria-hidden className='text-muted-foreground'>\n              →\n            </span>\n          )}\n          <span className='font-medium whitespace-nowrap'>{step.label}</span>\n        </li>\n      ))}\n    </ol>\n  )\n}\n\nexport {\n  FlowChart,\n  FlowPathSteps,\n  flowPalette,\n  getFlowColumns,\n  getFlowNodes,\n  getFlowTotals,\n}\n\nexport type {\n  FlowChartProps,\n  FlowHighlight,\n  FlowLayoutNode,\n  FlowLink,\n  FlowNode,\n  FlowPathStep,\n}\n",
      "type": "registry:component",
      "target": "@components/dashboardblocks/flow.tsx"
    }
  ],
  "type": "registry:component"
}
