{
  "$schema": "https://ui.shadcn.com/schema/registry-item.json",
  "name": "ribbon-flow-sankey-chart",
  "title": "Ribbon Flow Sankey Chart",
  "description": "A Sankey chart with flowing ribbon textures, animated period comparisons, linked node highlighting and a shared scale across views.",
  "dependencies": [],
  "files": [
    {
      "path": "registry/new-york/ribbon-flow-sankey-chart/ribbon-flow-sankey-chart.tsx",
      "content": "\"use client\";\n\nimport * as React from \"react\";\n\nexport interface FlowNode {\n  id: string;\n  label: string;\n  /** Column, counted from 0 on the left. */\n  column: number;\n}\n\nexport interface FlowLink {\n  source: string;\n  target: string;\n  value: number;\n}\n\nexport interface FlowView {\n  label: string;\n  links: FlowLink[];\n}\n\nexport interface RibbonFlowSankeyChartProps extends Omit<\n  React.ComponentPropsWithoutRef<\"section\">,\n  \"title\"\n> {\n  theme?: \"dark\" | \"light\";\n  title?: string;\n  subtitle?: string;\n  nodes?: FlowNode[];\n  /** Sets of flows to switch between. They should list the same links in the same order. */\n  views?: FlowView[];\n  /** Index of the view shown first. */\n  defaultView?: number;\n  /** The node that counts as success. Flows into it take the accent. */\n  goal?: string;\n  /** Colour of the flows into the goal. */\n  color?: string;\n  /** Height of the plot, in px. */\n  height?: number;\n  formatValue?: (value: number) => string;\n}\n\nconst PALETTES = {\n  dark: {\n    card: \"#08090A\",\n    surface: \"#0F1011\",\n    border: \"rgba(255,255,255,0.08)\",\n    grid: \"rgba(255,255,255,0.05)\",\n    text: \"#F7F8F8\",\n    soft: \"#D0D6E0\",\n    sub: \"#8A8F98\",\n    faint: \"#62666D\",\n    tip: \"#161718\",\n    tipShadow: \"0 4px 24px rgba(0,0,0,0.4)\",\n    chip: \"rgba(255,255,255,0.05)\",\n    chipOn: \"rgba(255,255,255,0.1)\",\n    accent: \"#5E6AD2\",\n    stripe: 0.16,\n  },\n  light: {\n    card: \"#FFFFFF\",\n    surface: \"#F7F8F8\",\n    border: \"rgba(8,9,10,0.08)\",\n    grid: \"rgba(8,9,10,0.06)\",\n    text: \"#08090A\",\n    soft: \"#3C3F44\",\n    sub: \"#62666D\",\n    faint: \"#8A8F98\",\n    tip: \"#FFFFFF\",\n    tipShadow: \"0 3px 12px rgba(8,9,10,0.09)\",\n    chip: \"rgba(8,9,10,0.04)\",\n    chipOn: \"#FFFFFF\",\n    accent: \"#5E6AD2\",\n    stripe: 0.4,\n  },\n};\n\ntype Palette = (typeof PALETTES)[\"dark\"];\n\nconst CARD_FONT =\n  '\"Inter Variable\", Inter, \"SF Pro Display\", -apple-system, BlinkMacSystemFont, sans-serif';\n\nfunction useReducedMotion() {\n  return React.useSyncExternalStore(\n    (callback) => {\n      const query = window.matchMedia(\"(prefers-reduced-motion: reduce)\");\n      query.addEventListener(\"change\", callback);\n      return () => query.removeEventListener(\"change\", callback);\n    },\n    () => window.matchMedia(\"(prefers-reduced-motion: reduce)\").matches,\n    () => false,\n  );\n}\n\n/** The chart is drawn at its real width, so its text stays the same size on a phone. */\nfunction useWidth(ref: React.RefObject<HTMLElement | null>) {\n  const [width, setWidth] = React.useState(700);\n  React.useEffect(() => {\n    const el = ref.current;\n    if (!el) return;\n    const ro = new ResizeObserver(([entry]) =>\n      setWidth(Math.max(240, Math.round(entry.contentRect.width))),\n    );\n    ro.observe(el);\n    return () => ro.disconnect();\n  }, [ref]);\n  return width;\n}\n\nfunction Stat({\n  value,\n  label,\n  pal,\n}: {\n  value: string;\n  label: string;\n  pal: Palette;\n}) {\n  return (\n    <div className=\"text-left sm:text-right\">\n      <p className=\"m-0 text-[18px] leading-[1.2] font-[510] tracking-[-0.018em] tabular-nums\">\n        {value}\n      </p>\n      <p\n        className=\"m-0 mt-0.5 text-[12px] tracking-[-0.011em]\"\n        style={{ color: pal.sub }}\n      >\n        {label}\n      </p>\n    </div>\n  );\n}\n\nfunction Pills({\n  label,\n  options,\n  value,\n  onChange,\n  pal,\n}: {\n  label: string;\n  options: string[];\n  value: number;\n  onChange: (index: number) => void;\n  pal: Palette;\n}) {\n  return (\n    <div\n      className=\"flex rounded-full p-0.5\"\n      style={{ background: pal.chip }}\n      role=\"radiogroup\"\n      aria-label={label}\n    >\n      {options.map((option, i) => (\n        <button\n          key={option}\n          type=\"button\"\n          role=\"radio\"\n          aria-checked={i === value}\n          tabIndex={i === value ? 0 : -1}\n          onKeyDown={(event) => {\n            if (![\"ArrowLeft\", \"ArrowRight\", \"Home\", \"End\"].includes(event.key))\n              return;\n            event.preventDefault();\n            const next =\n              event.key === \"Home\"\n                ? 0\n                : event.key === \"End\"\n                  ? options.length - 1\n                  : (i +\n                      (event.key === \"ArrowRight\" ? 1 : -1) +\n                      options.length) %\n                    options.length;\n            onChange(next);\n            event.currentTarget.parentElement\n              ?.querySelectorAll<HTMLButtonElement>(\"button\")\n              [next]?.focus();\n          }}\n          onClick={() => onChange(i)}\n          className=\"h-7 cursor-pointer rounded-full px-3 text-[13px] font-[510] tracking-[-0.011em] transition-colors outline-none focus-visible:ring-2\"\n          style={{\n            background: i === value ? pal.chipOn : \"transparent\",\n            color: i === value ? pal.text : pal.sub,\n          }}\n        >\n          {option}\n        </button>\n      ))}\n    </div>\n  );\n}\n\nfunction Tip({\n  x,\n  y,\n  width,\n  pal,\n  children,\n}: {\n  x: number;\n  y: number;\n  width: number;\n  pal: Palette;\n  children: React.ReactNode;\n}) {\n  return (\n    <div\n      aria-hidden=\"true\"\n      className=\"pointer-events-none absolute z-10 -translate-x-1/2 rounded-lg px-2.5 py-1.5 text-[12px] tracking-[-0.011em] whitespace-nowrap\"\n      style={{\n        left: Math.max(110, Math.min(width - 110, x)),\n        top: Math.max(0, y - 42),\n        background: pal.tip,\n        color: pal.sub,\n        boxShadow: `inset 0 0 0 1px ${pal.border}, ${pal.tipShadow}`,\n      }}\n    >\n      {children}\n    </div>\n  );\n}\n\nconst NODES: FlowNode[] = [\n  { id: \"search\", label: \"Search\", column: 0 },\n  { id: \"social\", label: \"Social\", column: 0 },\n  { id: \"referral\", label: \"Referral\", column: 0 },\n  { id: \"direct\", label: \"Direct\", column: 0 },\n  { id: \"pricing\", label: \"Pricing\", column: 1 },\n  { id: \"docs\", label: \"Docs\", column: 1 },\n  { id: \"blog\", label: \"Blog\", column: 1 },\n  { id: \"signed-up\", label: \"Signed up\", column: 2 },\n  { id: \"left\", label: \"Left\", column: 2 },\n];\n\nconst SHAPE: [string, string][] = [\n  [\"search\", \"pricing\"],\n  [\"search\", \"docs\"],\n  [\"search\", \"blog\"],\n  [\"social\", \"pricing\"],\n  [\"social\", \"blog\"],\n  [\"referral\", \"pricing\"],\n  [\"referral\", \"docs\"],\n  [\"direct\", \"pricing\"],\n  [\"direct\", \"docs\"],\n  [\"pricing\", \"signed-up\"],\n  [\"pricing\", \"left\"],\n  [\"docs\", \"signed-up\"],\n  [\"docs\", \"left\"],\n  [\"blog\", \"signed-up\"],\n  [\"blog\", \"left\"],\n];\n\nconst toLinks = (values: number[]): FlowLink[] =>\n  SHAPE.map(([source, target], i) => ({ source, target, value: values[i] }));\n\nconst VIEWS: FlowView[] = [\n  {\n    label: \"November\",\n    links: toLinks([\n      2400, 1500, 1100, 700, 900, 900, 400, 1300, 500, 2100, 3200, 800, 1600,\n      300, 1700,\n    ]),\n  },\n  {\n    label: \"December\",\n    links: toLinks([\n      3100, 1300, 800, 1500, 500, 1200, 300, 1700, 400, 3700, 3800, 900, 1100,\n      200, 1100,\n    ]),\n  },\n];\n\nconst FORMAT = (n: number) => Math.round(n).toLocaleString(\"en-US\");\nconst NODE = 8;\nconst GAP = 16;\n\nexport function RibbonFlowSankeyChart({\n  theme = \"dark\",\n  title = \"Visitor flow\",\n  subtitle = \"Where people come from, what they read and how it ends.\",\n  nodes: suppliedNodes = NODES,\n  views: suppliedViews = VIEWS,\n  defaultView = 1,\n  goal = \"signed-up\",\n  color,\n  height: requestedHeight = 300,\n  formatValue = FORMAT,\n  className,\n  style,\n  ...props\n}: RibbonFlowSankeyChartProps) {\n  const pal = PALETTES[theme];\n  const nodes = React.useMemo(\n    () =>\n      suppliedNodes.filter(\n        (n, i) =>\n          Number.isInteger(n.column) &&\n          n.column >= 0 &&\n          n.column < 12 &&\n          suppliedNodes.findIndex((other) => other.id === n.id) === i,\n      ),\n    [suppliedNodes],\n  );\n  const views = React.useMemo(\n    () =>\n      suppliedViews.map((view) => ({\n        ...view,\n        links: view.links.filter((link, i) => {\n          const source = nodes.find((n) => n.id === link.source);\n          const target = nodes.find((n) => n.id === link.target);\n          return (\n            source &&\n            target &&\n            source.column < target.column &&\n            Number.isFinite(link.value) &&\n            link.value > 0 &&\n            view.links.findIndex(\n              (other) =>\n                other.source === link.source && other.target === link.target,\n            ) === i\n          );\n        }),\n      })),\n    [suppliedViews, nodes],\n  );\n  const height = Math.max(\n    Number.isFinite(requestedHeight)\n      ? Math.max(180, Math.min(700, requestedHeight))\n      : 300,\n    ...nodes.map(\n      (n) => nodes.filter((other) => other.column === n.column).length * 20,\n    ),\n  );\n\n  const accent = color ?? pal.accent;\n  const reduce = useReducedMotion();\n  const boxRef = React.useRef<HTMLDivElement>(null);\n  const width = Math.max(560, useWidth(boxRef));\n  const stripeRefs = React.useRef<(SVGPathElement | null)[]>([]);\n  const [view, setView] = React.useState(defaultView);\n  const activeView = Number.isInteger(view)\n    ? Math.max(0, Math.min(views.length - 1, view))\n    : 0;\n  const [node, setNode] = React.useState<string | null>(null);\n  const [link, setLink] = React.useState<number | null>(null);\n  const links = React.useMemo(\n    () => (views[activeView] ?? views[0])?.links ?? [],\n    [views, activeView],\n  );\n  const [shown, setShown] = React.useState<number[]>(() =>\n    links.map((l) => l.value),\n  );\n  const liveRef = React.useRef(\n    new Map(links.map((l) => [`${l.source}:${l.target}`, l.value])),\n  );\n\n  // Keep the initial drawing visible, including inside an iframe. Ease only data changes.\n  React.useEffect(() => {\n    const from = liveRef.current;\n    let raf = 0;\n    let start = 0;\n    const frame = (now: number) => {\n      start = start || now;\n      const k = reduce ? 1 : Math.min(1, (now - start) / 800);\n      const e = 1 - Math.pow(1 - k, 3);\n      const next = links.map(\n        (l) =>\n          (from.get(`${l.source}:${l.target}`) ?? 0) +\n          (l.value - (from.get(`${l.source}:${l.target}`) ?? 0)) * e,\n      );\n      liveRef.current = new Map(\n        links.map((l, i) => [`${l.source}:${l.target}`, next[i]]),\n      );\n      setShown(next);\n      if (k < 1) raf = requestAnimationFrame(frame);\n    };\n    raf = requestAnimationFrame(frame);\n    return () => cancelAnimationFrame(raf);\n  }, [links, reduce]);\n\n  // Stripes run down every ribbon on their own animations, so the flow keeps moving with nothing re-rendering.\n  React.useEffect(() => {\n    if (reduce) return;\n    const runs = stripeRefs.current.slice(0, links.length).map((el) =>\n      el?.animate([{ strokeDashoffset: 0 }, { strokeDashoffset: -48 }], {\n        duration: 2000,\n        iterations: Infinity,\n      }),\n    );\n    return () => runs.forEach((run) => run?.cancel());\n  }, [reduce, links.length]);\n\n  // One scale from the busiest column of any view, so a thicker ribbon always means more people.\n  const columns = Math.max(1, ...nodes.map((n) => n.column)) + 1;\n  const through = (list: FlowLink[], id: string) =>\n    Math.max(\n      list.filter((l) => l.source === id).reduce((n, l) => n + l.value, 0),\n      list.filter((l) => l.target === id).reduce((n, l) => n + l.value, 0),\n    );\n  const scale = Math.min(\n    ...Array.from({ length: columns }, (_, c) => {\n      const members = nodes.filter((n) => n.column === c);\n      const space = height - GAP * Math.max(0, members.length - 1);\n      const busiest = Math.max(\n        1,\n        ...views.map((v) =>\n          members.reduce((n, m) => n + through(v.links, m.id), 0),\n        ),\n      );\n      return space / busiest;\n    }),\n  );\n\n  const live = links.map((l, i) => ({ ...l, value: shown[i] ?? 0 }));\n  const columnX = (c: number) =>\n    columns <= 1 ? 0 : (c / (columns - 1)) * (width - NODE);\n  const spot = new Map<\n    string,\n    { y: number; h: number; outY: number; inY: number }\n  >();\n  for (let c = 0; c < columns; c++) {\n    const members = nodes.filter((n) => n.column === c);\n    const heights = members.map((m) => through(live, m.id) * scale);\n    const used = heights.reduce((n, h) => n + h, 0);\n    let y = (height - used - GAP * Math.max(0, members.length - 1)) / 2;\n    members.forEach((m, i) => {\n      spot.set(m.id, { y, h: heights[i], outY: y, inY: y });\n      y += heights[i] + GAP;\n    });\n  }\n  const ribbons = live.map((l) => {\n    const a = spot.get(l.source);\n    const b = spot.get(l.target);\n    const thick = l.value * scale;\n    if (!a || !b) return { d: \"\", thick: 0, mid: { x: 0, y: 0 } };\n    const y1 = a.outY + thick / 2;\n    const y2 = b.inY + thick / 2;\n    a.outY += thick;\n    b.inY += thick;\n    const from = nodes.find((n) => n.id === l.source);\n    const to = nodes.find((n) => n.id === l.target);\n    const x1 = columnX(from?.column ?? 0) + NODE;\n    const x2 = columnX(to?.column ?? 1);\n    const bend = (x2 - x1) / 2;\n    return {\n      d: `M${x1.toFixed(1)} ${y1.toFixed(1)}C${(x1 + bend).toFixed(1)} ${y1.toFixed(1)} ${(x2 - bend).toFixed(1)} ${y2.toFixed(1)} ${x2.toFixed(1)} ${y2.toFixed(1)}`,\n      thick,\n      mid: { x: (x1 + x2) / 2, y: (y1 + y2) / 2 },\n    };\n  });\n\n  const related = (l: FlowLink, i: number) => {\n    if (link !== null) return link === i;\n    if (node !== null) return l.source === node || l.target === node;\n    return true;\n  };\n  const quiet = link !== null || node !== null;\n  const name = (id: string) => nodes.find((n) => n.id === id)?.label ?? id;\n  const firstColumn = nodes.filter((n) => n.column === 0).map((n) => n.id);\n  const visitors = links\n    .filter((l) => firstColumn.includes(l.source))\n    .reduce((n, l) => n + l.value, 0);\n  const won = links\n    .filter((l) => l.target === goal)\n    .reduce((n, l) => n + l.value, 0);\n  const picked = link === null ? null : links[link];\n\n  return (\n    <section\n      className={`w-full rounded-2xl p-5 sm:p-6 ${className ?? \"\"}`}\n      style={{\n        background: pal.card,\n        boxShadow: `inset 0 0 0 1px ${pal.border}`,\n        color: pal.text,\n        fontFamily: CARD_FONT,\n        ...style,\n      }}\n      {...props}\n    >\n      <div className=\"flex flex-wrap items-start justify-between gap-x-8 gap-y-3\">\n        <div>\n          <h3 className=\"m-0 text-[17px] leading-[1.33] font-[590] tracking-[-0.012em]\">\n            {title}\n          </h3>\n          <p\n            className=\"m-0 mt-0.5 text-[13px] tracking-[-0.011em]\"\n            style={{ color: pal.sub }}\n          >\n            {subtitle}\n          </p>\n        </div>\n        <div className=\"flex flex-wrap gap-x-7 gap-y-3\">\n          <Stat value={formatValue(visitors)} label=\"Visitors\" pal={pal} />\n          <Stat value={formatValue(won)} label={name(goal)} pal={pal} />\n          <Stat\n            value={`${visitors ? ((won / visitors) * 100).toFixed(1) : \"0.0\"}%`}\n            label=\"Conversion\"\n            pal={pal}\n          />\n        </div>\n      </div>\n\n      {!links.length ? (\n        <p className=\"py-16 text-center text-sm\" style={{ color: pal.sub }}>\n          No data available.\n        </p>\n      ) : (\n        <div\n          ref={boxRef}\n          className=\"relative mt-5 overflow-x-auto\"\n          onPointerLeave={() => {\n            setLink(null);\n            setNode(null);\n          }}\n        >\n          <svg\n            viewBox={`0 0 ${width} ${height}`}\n            className=\"block w-full\"\n            style={{ height, minWidth: width }}\n            role=\"group\"\n            aria-label={`${formatValue(visitors)} visitors, ${formatValue(won)} reached ${name(goal)}.`}\n          >\n            {live.map((l, i) => {\n              const r = ribbons[i];\n              const on = related(l, i);\n              const good = l.target === goal;\n              return (\n                <g\n                  key={`${l.source}-${l.target}`}\n                  role=\"button\"\n                  tabIndex={0}\n                  aria-label={`${name(l.source)} to ${name(l.target)}: ${formatValue(links[i].value)}`}\n                  onFocus={() => setLink(i)}\n                  onBlur={() => setLink(null)}\n                  onClick={() => setLink(i)}\n                  onKeyDown={(event) => {\n                    if (event.key === \"Escape\") setLink(null);\n                    if (event.key === \" \" || event.key === \"Enter\") {\n                      event.preventDefault();\n                      setLink(i);\n                    }\n                  }}\n                  onPointerEnter={() => setLink(i)}\n                  onPointerLeave={() => setLink(null)}\n                >\n                  <path\n                    d={r.d}\n                    fill=\"none\"\n                    stroke={good ? accent : pal.sub}\n                    strokeWidth={Math.max(0.5, r.thick)}\n                    strokeOpacity={!on ? 0.06 : quiet ? 0.6 : good ? 0.55 : 0.2}\n                    className=\"motion-safe:transition-[stroke-opacity] motion-safe:duration-200\"\n                  />\n                  <path\n                    ref={(el) => {\n                      stripeRefs.current[i] = el;\n                    }}\n                    d={r.d}\n                    fill=\"none\"\n                    stroke={pal.text}\n                    strokeWidth={Math.max(0.5, r.thick)}\n                    strokeOpacity={on ? pal.stripe : 0}\n                    strokeDasharray=\"3 45\"\n                    pointerEvents=\"none\"\n                  />\n                </g>\n              );\n            })}\n            {nodes.map((n) => {\n              const p = spot.get(n.id);\n              if (!p) return null;\n              const last = n.column === columns - 1;\n              const x = columnX(n.column);\n              const on = node === n.id;\n              const total = through(links, n.id);\n              return (\n                <g\n                  key={n.id}\n                  role=\"button\"\n                  tabIndex={0}\n                  aria-label={`${n.label}: ${formatValue(total)}`}\n                  onFocus={() => setNode(n.id)}\n                  onBlur={() => setNode(null)}\n                  onClick={() => setNode(n.id)}\n                  onKeyDown={(event) => {\n                    if (event.key === \"Escape\") setNode(null);\n                    if (event.key === \" \" || event.key === \"Enter\") {\n                      event.preventDefault();\n                      setNode(n.id);\n                    }\n                  }}\n                  onPointerEnter={() => setNode(n.id)}\n                  onPointerLeave={() => setNode(null)}\n                >\n                  <rect\n                    x={x - 6}\n                    y={p.y - 2}\n                    width={NODE + 12}\n                    height={Math.max(14, p.h + 4)}\n                    fill=\"transparent\"\n                  />\n                  <rect\n                    x={x}\n                    y={p.y}\n                    width={NODE}\n                    height={Math.max(1, p.h)}\n                    rx=\"2\"\n                    fill={n.id === goal ? accent : on ? pal.text : pal.soft}\n                  />\n                  <text\n                    x={last ? x - 6 : x + NODE + 6}\n                    y={p.y + Math.max(1, p.h) / 2 + 4}\n                    textAnchor={last ? \"end\" : \"start\"}\n                    fontSize=\"12\"\n                    fontWeight=\"510\"\n                    fill={pal.text}\n                    pointerEvents=\"none\"\n                    paintOrder=\"stroke\"\n                    stroke={pal.card}\n                    strokeWidth=\"3\"\n                    strokeOpacity=\"0.6\"\n                  >\n                    {n.label}{\" \"}\n                    <tspan fontWeight=\"400\" fill={pal.sub}>\n                      {formatValue(total)}\n                    </tspan>\n                  </text>\n                </g>\n              );\n            })}\n          </svg>\n\n          {picked && link !== null && (\n            <Tip\n              x={ribbons[link].mid.x}\n              y={ribbons[link].mid.y}\n              width={width}\n              pal={pal}\n            >\n              <span className=\"font-[510]\" style={{ color: pal.text }}>\n                {formatValue(picked.value)}\n              </span>{\" \"}\n              from {name(picked.source)} to {name(picked.target)}\n            </Tip>\n          )}\n        </div>\n      )}\n\n      <div className=\"mt-3 flex flex-wrap items-center justify-between gap-2\">\n        <Pills\n          label=\"Month\"\n          options={views.map((v) => v.label)}\n          value={activeView}\n          onChange={setView}\n          pal={pal}\n        />\n        <span\n          className=\"flex items-center gap-2 text-[12px]\"\n          style={{ color: pal.sub }}\n        >\n          <span\n            className=\"h-2.5 w-3.5 rounded-[3px]\"\n            style={{ background: accent }}\n          />\n          Flows into {name(goal)}\n        </span>\n      </div>\n    </section>\n  );\n}\n",
      "type": "registry:component"
    }
  ],
  "type": "registry:component"
}