{
  "$schema": "https://ui.shadcn.com/schema/registry-item.json",
  "name": "chart-sankey-flow",
  "type": "registry:component",
  "title": "Sankey Flow",
  "description": "A multi-stage flow diagram laid out from plain nodes and links: gradient ribbons draw left to right stage by stage. Hovering or focusing a node lights its whole upstream and downstream path, and each ribbon shows its share in a tooltip.",
  "author": "Hyperblur <hello@hyperblur.dev>",
  "dependencies": [],
  "registryDependencies": [],
  "categories": [
    "charts",
    "chart",
    "sankey",
    "flow",
    "funnel",
    "svg",
    "journey"
  ],
  "docs": "https://hyperblur.dev/effects/chart-sankey-flow",
  "files": [
    {
      "path": "registry/hyperblur/chart-sankey-flow.tsx",
      "type": "registry:component",
      "target": "components/hyperblur/chart-sankey-flow.tsx",
      "content": "\"use client\";\n\nimport * as React from \"react\";\n\nexport interface SankeyNode {\n  id: string;\n  label: string;\n  color?: string;\n}\n\nexport interface SankeyLink {\n  source: string;\n  target: string;\n  value: number;\n}\n\nexport interface ChartSankeyFlowProps extends Omit<React.HTMLAttributes<HTMLDivElement>, \"children\" | \"title\"> {\n  nodes?: SankeyNode[];\n  links?: SankeyLink[];\n  height?: number;\n  title?: string;\n  summary?: string;\n  format?: (value: number) => string;\n  nodeGap?: number;\n  accent?: string;\n  onNodeSelect?: (node: SankeyNode | null) => void;\n}\n\nconst defaultNodes: SankeyNode[] = [\n  { id: \"search\", label: \"Search\", color: \"#2f7bff\" },\n  { id: \"referral\", label: \"Referral\", color: \"#22c3a6\" },\n  { id: \"partners\", label: \"Partners\", color: \"#a78bfa\" },\n  { id: \"direct\", label: \"Direct\", color: \"#7fb3ff\" },\n  { id: \"self\", label: \"Self-serve trial\", color: \"#5b9dff\" },\n  { id: \"demo\", label: \"Sales demo\", color: \"#c084fc\" },\n  { id: \"annual\", label: \"Paid annual\", color: \"#34d399\" },\n  { id: \"monthly\", label: \"Paid monthly\", color: \"#86efac\" },\n  { id: \"eval\", label: \"Evaluating\", color: \"#f5b544\" },\n  { id: \"churn\", label: \"Churned\", color: \"#6b6b6b\" },\n];\n\nconst defaultLinks: SankeyLink[] = [\n  { source: \"search\", target: \"self\", value: 3900 },\n  { source: \"search\", target: \"demo\", value: 920 },\n  { source: \"referral\", target: \"self\", value: 1640 },\n  { source: \"referral\", target: \"demo\", value: 500 },\n  { source: \"partners\", target: \"self\", value: 380 },\n  { source: \"partners\", target: \"demo\", value: 980 },\n  { source: \"direct\", target: \"self\", value: 1700 },\n  { source: \"direct\", target: \"demo\", value: 280 },\n  { source: \"self\", target: \"monthly\", value: 1480 },\n  { source: \"self\", target: \"annual\", value: 620 },\n  { source: \"self\", target: \"eval\", value: 1320 },\n  { source: \"self\", target: \"churn\", value: 4200 },\n  { source: \"demo\", target: \"annual\", value: 1140 },\n  { source: \"demo\", target: \"monthly\", value: 260 },\n  { source: \"demo\", target: \"eval\", value: 690 },\n  { source: \"demo\", target: \"churn\", value: 590 },\n];\n\nconst W = 640;\nconst H = 260;\nconst NW = 10;\n\ninterface LaidNode extends SankeyNode {\n  depth: number;\n  x: number;\n  y: number;\n  h: number;\n  value: number;\n  color: string;\n}\n\ninterface LaidLink extends SankeyLink {\n  i: number;\n  sy: number;\n  ty: number;\n  t: number;\n  d: string;\n}\n\nfunction layout(nodes: SankeyNode[], links: SankeyLink[], gap: number, fallback: string) {\n  const depth = new Map<string, number>(nodes.map((n) => [n.id, 0]));\n  for (let pass = 0; pass < nodes.length; pass++) {\n    let changed = false;\n    for (const l of links) {\n      const next = (depth.get(l.source) ?? 0) + 1;\n      if (next > (depth.get(l.target) ?? 0)) {\n        depth.set(l.target, next);\n        changed = true;\n      }\n    }\n    if (!changed) break;\n  }\n  const cols = Math.max(1, ...depth.values()) + 1;\n  const valueOf = (id: string) =>\n    Math.max(\n      links.filter((l) => l.source === id).reduce((a, l) => a + l.value, 0),\n      links.filter((l) => l.target === id).reduce((a, l) => a + l.value, 0),\n    );\n  const columns: SankeyNode[][] = Array.from({ length: cols }, () => []);\n  nodes.forEach((n) => columns[depth.get(n.id) ?? 0].push(n));\n  let ky = Infinity;\n  columns.forEach((c) => {\n    const total = c.reduce((a, n) => a + valueOf(n.id), 0);\n    if (total > 0) ky = Math.min(ky, (H - gap * Math.max(0, c.length - 1)) / total);\n  });\n  if (!Number.isFinite(ky)) ky = 1;\n  const laid = new Map<string, LaidNode>();\n  columns.forEach((c, ci) => {\n    const used = c.reduce((a, n) => a + valueOf(n.id) * ky, 0) + gap * Math.max(0, c.length - 1);\n    let y = (H - used) / 2;\n    c.forEach((n) => {\n      const v = valueOf(n.id);\n      const h = Math.max(2, v * ky);\n      laid.set(n.id, { ...n, depth: ci, x: cols === 1 ? 0 : (ci / (cols - 1)) * (W - NW), y, h, value: v, color: n.color ?? fallback });\n      y += h + gap;\n    });\n  });\n  const outOff = new Map<string, number>();\n  const inOff = new Map<string, number>();\n  const order = links.map((l, i) => ({ l, i }));\n  const sortedOut = [...order].sort((a, b) => (laid.get(a.l.target)?.y ?? 0) - (laid.get(b.l.target)?.y ?? 0));\n  const sortedIn = [...order].sort((a, b) => (laid.get(a.l.source)?.y ?? 0) - (laid.get(b.l.source)?.y ?? 0));\n  const sy = new Map<number, number>();\n  const ty = new Map<number, number>();\n  sortedOut.forEach(({ l, i }) => {\n    const s = laid.get(l.source);\n    if (!s) return;\n    const o = outOff.get(l.source) ?? 0;\n    sy.set(i, s.y + o);\n    outOff.set(l.source, o + l.value * ky);\n  });\n  sortedIn.forEach(({ l, i }) => {\n    const t = laid.get(l.target);\n    if (!t) return;\n    const o = inOff.get(l.target) ?? 0;\n    ty.set(i, t.y + o);\n    inOff.set(l.target, o + l.value * ky);\n  });\n  const f = (n: number) => n.toFixed(2);\n  const laidLinks: LaidLink[] = order\n    .filter(({ l }) => laid.has(l.source) && laid.has(l.target))\n    .map(({ l, i }) => {\n      const s = laid.get(l.source) as LaidNode;\n      const tg = laid.get(l.target) as LaidNode;\n      const t = l.value * ky;\n      const x0 = s.x + NW;\n      const x1 = tg.x;\n      const xm = (x0 + x1) / 2;\n      const a = sy.get(i) ?? 0;\n      const b = ty.get(i) ?? 0;\n      const d = `M${f(x0)} ${f(a)} C${f(xm)} ${f(a)} ${f(xm)} ${f(b)} ${f(x1)} ${f(b)} L${f(x1)} ${f(b + t)} C${f(xm)} ${f(b + t)} ${f(xm)} ${f(a + t)} ${f(x0)} ${f(a + t)} Z`;\n      return { ...l, i, sy: a, ty: b, t, d };\n    });\n  return { nodes: [...laid.values()], links: laidLinks, cols };\n}\n\nconst css = `\n.hb-wi2 {\n  --hb-wi2-a: #2f7bff;\n  position: relative;\n  width: 100%;\n  box-sizing: border-box;\n  color: #ededed;\n  font-family: inherit;\n  font-size: 12px;\n}\n.hb-wi2 *, .hb-wi2 *::before, .hb-wi2 *::after { box-sizing: border-box; }\n.hb-wi2-plot { position: relative; width: 100%; height: var(--hb-wi2-h, 260px); }\n.hb-wi2-svg { position: absolute; inset: 0; width: 100%; height: 100%; display: block; overflow: visible; }\n.hb-wi2-link {\n  opacity: 0.38;\n  clip-path: inset(0 100% 0 0);\n  transition: opacity 0.25s ease;\n  cursor: pointer;\n  mix-blend-mode: screen;\n}\n.hb-wi2[data-in=\"true\"] .hb-wi2-link {\n  clip-path: inset(0 0 0 0);\n  transition: clip-path 1.2s cubic-bezier(0.65, 0, 0.25, 1) var(--hb-wi2-d, 0ms), opacity 0.25s ease;\n}\n.hb-wi2[data-active=\"true\"] .hb-wi2-link { opacity: 0.08; }\n.hb-wi2[data-active=\"true\"] .hb-wi2-link[data-on=\"true\"] { opacity: 0.78; }\n.hb-wi2-node {\n  transform-box: fill-box;\n  transform-origin: center;\n  transform: scaleY(0);\n  rx: 2px;\n  transition: transform 0.7s cubic-bezier(0.34, 1.4, 0.64, 1) var(--hb-wi2-d, 0ms), opacity 0.25s ease;\n}\n.hb-wi2[data-in=\"true\"] .hb-wi2-node { transform: scaleY(1); }\n.hb-wi2[data-active=\"true\"] .hb-wi2-node { opacity: 0.35; }\n.hb-wi2[data-active=\"true\"] .hb-wi2-node[data-on=\"true\"] { opacity: 1; }\n.hb-wi2-hit { fill: transparent; cursor: pointer; outline: none; }\n.hb-wi2-hit:focus-visible { stroke: #ededed; stroke-width: 1.5; vector-effect: non-scaling-stroke; }\n.hb-wi2-lab {\n  position: absolute;\n  transform: translateY(-50%);\n  display: flex;\n  flex-direction: column;\n  gap: 1px;\n  padding: 2px 6px;\n  border-radius: 6px;\n  white-space: nowrap;\n  pointer-events: none;\n  line-height: 1.15;\n  opacity: 0;\n  transition: opacity 0.5s ease var(--hb-wi2-d, 0ms), color 0.2s ease;\n}\n.hb-wi2[data-in=\"true\"] .hb-wi2-lab { opacity: 1; }\n.hb-wi2[data-active=\"true\"] .hb-wi2-lab { opacity: 0.4; }\n.hb-wi2[data-active=\"true\"] .hb-wi2-lab[data-on=\"true\"] { opacity: 1; }\n.hb-wi2-lab[data-mid=\"true\"] { background: rgba(10, 10, 10, 0.72); backdrop-filter: blur(4px); }\n.hb-wi2-lab b { font-size: 11.5px; font-weight: 550; color: #ededed; }\n.hb-wi2-lab span { font-size: 10.5px; color: #8f8f8f; font-variant-numeric: tabular-nums; }\n.hb-wi2-tip {\n  position: absolute;\n  z-index: 3;\n  padding: 8px 10px;\n  border-radius: 10px;\n  background: rgba(17, 17, 17, 0.95);\n  border: 1px solid #262626;\n  box-shadow: 0 14px 30px rgba(0, 0, 0, 0.5), inset 0 1px 0 rgba(255, 255, 255, 0.05);\n  pointer-events: none;\n  white-space: nowrap;\n  transform: translate(-50%, calc(-100% - 12px));\n}\n.hb-wi2-tip-p { display: flex; align-items: center; gap: 6px; font-size: 11px; color: #a1a1a1; }\n.hb-wi2-tip-p i { width: 6px; height: 6px; border-radius: 50%; }\n.hb-wi2-tip-p svg { opacity: 0.5; }\n.hb-wi2-tip-v { margin-top: 4px; font-size: 13px; font-weight: 600; font-variant-numeric: tabular-nums; }\n.hb-wi2-tip-v span { margin-left: 6px; font-size: 11px; font-weight: 500; color: #7fb3ff; }\n.hb-wi2-sr { position: absolute; width: 1px; height: 1px; overflow: hidden; clip: rect(0 0 0 0); white-space: nowrap; }\n@media (prefers-reduced-motion: reduce) {\n  .hb-wi2-link, .hb-wi2[data-in=\"true\"] .hb-wi2-link { clip-path: none; transition: none; }\n  .hb-wi2-node, .hb-wi2[data-in=\"true\"] .hb-wi2-node { transform: none; transition: none; }\n  .hb-wi2-lab { opacity: 1; transition: none; }\n}\n`;\n\nexport function ChartSankeyFlow({\n  nodes = defaultNodes,\n  links = defaultLinks,\n  height = 260,\n  title = \"Trial journeys, Q3\",\n  summary,\n  format,\n  nodeGap = 10,\n  accent = \"#2f7bff\",\n  onNodeSelect,\n  className,\n  style,\n  ...rest\n}: ChartSankeyFlowProps) {\n  const id = React.useId().replace(/:/g, \"\");\n  const [inView, setInView] = React.useState(false);\n  const [hoverNode, setHoverNode] = React.useState<string | null>(null);\n  const [pinned, setPinned] = React.useState<string | null>(null);\n  const [hoverLink, setHoverLink] = React.useState<{ i: number; x: number; y: number } | null>(null);\n  const plotRef = React.useRef<HTMLDivElement>(null);\n  const fmt = format ?? ((v: number) => v.toLocaleString(\"en-US\"));\n\n  React.useEffect(() => {\n    const t = window.setTimeout(() => setInView(true), 60);\n    return () => window.clearTimeout(t);\n  }, []);\n\n  const g = React.useMemo(() => layout(nodes, links, nodeGap, accent), [nodes, links, nodeGap, accent]);\n  const focusNode = hoverNode ?? pinned;\n\n  const connected = React.useMemo(() => {\n    if (!focusNode) return null;\n    const set = new Set<number>();\n    const nodeSet = new Set<string>([focusNode]);\n    const walk = (nid: string, dir: \"up\" | \"down\") => {\n      g.links.forEach((l) => {\n        const from = dir === \"down\" ? l.source : l.target;\n        const to = dir === \"down\" ? l.target : l.source;\n        if (from === nid && !set.has(l.i)) {\n          set.add(l.i);\n          nodeSet.add(to);\n          walk(to, dir);\n        }\n      });\n    };\n    walk(focusNode, \"down\");\n    walk(focusNode, \"up\");\n    return { links: set, nodes: nodeSet };\n  }, [focusNode, g.links]);\n\n  const linkOn = (l: LaidLink) => (hoverLink ? hoverLink.i === l.i : connected ? connected.links.has(l.i) : false);\n  const nodeOn = (n: LaidNode) => {\n    if (hoverLink) {\n      const l = g.links.find((k) => k.i === hoverLink.i);\n      return l ? l.source === n.id || l.target === n.id : false;\n    }\n    return connected ? connected.nodes.has(n.id) : false;\n  };\n  const active = hoverLink !== null || connected !== null;\n\n  const select = (n: LaidNode) => {\n    const next = pinned === n.id ? null : n.id;\n    setPinned(next);\n    onNodeSelect?.(next ? n : null);\n  };\n\n  const sources = g.nodes.filter((n) => n.depth === 0);\n  const totalIn = sources.reduce((a, n) => a + n.value, 0);\n  const tipLink = hoverLink ? g.links.find((l) => l.i === hoverLink.i) : null;\n  const tipSrc = tipLink ? g.nodes.find((n) => n.id === tipLink.source) : null;\n  const tipTgt = tipLink ? g.nodes.find((n) => n.id === tipLink.target) : null;\n  const desc =\n    summary ??\n    `Flow diagram across ${g.cols} stages. ${fmt(totalIn)} entries from ${sources.map((s) => s.label).join(\", \")}. ` +\n      g.nodes\n        .filter((n) => n.depth === g.cols - 1)\n        .map((n) => `${n.label} ${fmt(n.value)}`)\n        .join(\", \") +\n      \".\";\n\n  const announce = focusNode ? g.nodes.find((n) => n.id === focusNode) : null;\n\n  return (\n    <div\n      {...rest}\n      className={[\"hb-wi2\", className].filter(Boolean).join(\" \")}\n      style={{ ...style, [\"--hb-wi2-a\" as string]: accent, [\"--hb-wi2-h\" as string]: `${height}px` } as React.CSSProperties}\n      data-in={inView}\n      data-active={active}\n    >\n      <style href=\"hb-chart-sankey-flow\" precedence=\"default\">{css}</style>\n      <div ref={plotRef} className=\"hb-wi2-plot\" onPointerLeave={() => { setHoverLink(null); setHoverNode(null); }}>\n        <svg className=\"hb-wi2-svg\" viewBox={`0 0 ${W} ${H}`} preserveAspectRatio=\"none\" role=\"img\" aria-labelledby={`${id}-t ${id}-d`}>\n          <title id={`${id}-t`}>{title}</title>\n          <desc id={`${id}-d`}>{desc}</desc>\n          <defs>\n            {g.links.map((l) => {\n              const s = g.nodes.find((n) => n.id === l.source) as LaidNode;\n              const t = g.nodes.find((n) => n.id === l.target) as LaidNode;\n              return (\n                <linearGradient key={l.i} id={`${id}-g${l.i}`} gradientUnits=\"userSpaceOnUse\" x1={(s.x + NW).toFixed(2)} x2={t.x.toFixed(2)} y1=\"0\" y2=\"0\">\n                  <stop offset=\"0\" stopColor={s.color} />\n                  <stop offset=\"1\" stopColor={t.color} />\n                </linearGradient>\n              );\n            })}\n          </defs>\n          {g.links.map((l) => {\n            const s = g.nodes.find((n) => n.id === l.source) as LaidNode;\n            return (\n              <path\n                key={l.i}\n                className=\"hb-wi2-link\"\n                d={l.d}\n                fill={`url(#${id}-g${l.i})`}\n                data-on={linkOn(l)}\n                style={{ [\"--hb-wi2-d\" as string]: `${200 + s.depth * 380}ms` } as React.CSSProperties}\n                onPointerMove={(e) => {\n                  const r = plotRef.current?.getBoundingClientRect();\n                  if (r) setHoverLink({ i: l.i, x: e.clientX - r.left, y: e.clientY - r.top });\n                }}\n                onPointerLeave={() => setHoverLink(null)}\n              />\n            );\n          })}\n          {g.nodes.map((n) => (\n            <g key={n.id}>\n              <rect className=\"hb-wi2-node\" x={n.x.toFixed(2)} y={n.y.toFixed(2)} width={NW} height={n.h.toFixed(2)} fill={n.color} data-on={nodeOn(n)} style={{ [\"--hb-wi2-d\" as string]: `${n.depth * 380}ms` } as React.CSSProperties} />\n              <rect\n                className=\"hb-wi2-hit\"\n                x={(n.x - 6).toFixed(2)}\n                y={n.y.toFixed(2)}\n                width={NW + 12}\n                height={n.h.toFixed(2)}\n                tabIndex={0}\n                role=\"button\"\n                aria-pressed={pinned === n.id}\n                aria-label={`${n.label}, ${fmt(n.value)}`}\n                onPointerEnter={() => setHoverNode(n.id)}\n                onPointerLeave={() => setHoverNode(null)}\n                onFocus={() => setHoverNode(n.id)}\n                onBlur={() => setHoverNode(null)}\n                onClick={() => select(n)}\n                onKeyDown={(e) => {\n                  if (e.key === \"Enter\" || e.key === \" \") {\n                    e.preventDefault();\n                    select(n);\n                  } else if (e.key === \"Escape\") {\n                    setPinned(null);\n                    onNodeSelect?.(null);\n                  }\n                }}\n              />\n            </g>\n          ))}\n        </svg>\n        {g.nodes.map((n) => {\n          const last = n.depth === g.cols - 1;\n          const mid = n.depth > 0 && !last;\n          const share = totalIn > 0 ? Math.round((n.value / totalIn) * 100) : 0;\n          return (\n            <div\n              key={n.id}\n              className=\"hb-wi2-lab\"\n              data-on={nodeOn(n)}\n              data-mid={mid}\n              style={{\n                top: `${(((n.y + n.h / 2) / H) * 100).toFixed(2)}%`,\n                left: last ? undefined : `calc(${(((n.x + NW) / W) * 100).toFixed(2)}% + 4px)`,\n                right: last ? `calc(${((1 - n.x / W) * 100).toFixed(2)}% + 4px)` : undefined,\n                textAlign: last ? \"right\" : \"left\",\n                [\"--hb-wi2-d\" as string]: `${300 + n.depth * 380}ms`,\n              } as React.CSSProperties}\n            >\n              <b>{n.label}</b>\n              <span>\n                {fmt(n.value)}\n                {n.depth > 0 ? ` · ${share}%` : \"\"}\n              </span>\n            </div>\n          );\n        })}\n        {tipLink && tipSrc && tipTgt && hoverLink ? (\n          <div className=\"hb-wi2-tip\" style={{ left: hoverLink.x, top: hoverLink.y }}>\n            <div className=\"hb-wi2-tip-p\">\n              <i style={{ background: tipSrc.color }} />\n              {tipSrc.label}\n              <svg width=\"10\" height=\"10\" viewBox=\"0 0 10 10\" aria-hidden=\"true\">\n                <path d=\"M1 5h7M5.5 2 8.5 5l-3 3\" fill=\"none\" stroke=\"currentColor\" strokeWidth=\"1.4\" strokeLinecap=\"round\" strokeLinejoin=\"round\" />\n              </svg>\n              <i style={{ background: tipTgt.color }} />\n              {tipTgt.label}\n            </div>\n            <div className=\"hb-wi2-tip-v\">\n              {fmt(tipLink.value)}\n              <span>{tipSrc.value > 0 ? Math.round((tipLink.value / tipSrc.value) * 100) : 0}% of {tipSrc.label}</span>\n            </div>\n          </div>\n        ) : null}\n        <div className=\"hb-wi2-sr\" aria-live=\"polite\">\n          {announce ? `${announce.label}: ${fmt(announce.value)}` : \"\"}\n        </div>\n      </div>\n    </div>\n  );\n}\n"
    }
  ]
}