{
  "$schema": "https://ui.shadcn.com/schema/registry-item.json",
  "name": "streamgraph",
  "title": "Streamgraph",
  "description": "A streamgraph of how a mix shifts over time: smooth streams flowing around a moving centre line, each swelling and thinning with its share, named inside where they're thick, with hover highlighting and a sorted weekly breakdown.",
  "dependencies": [
    "clsx",
    "tailwind-merge"
  ],
  "files": [
    {
      "path": "registry/new-york/streamgraph/streamgraph.tsx",
      "content": "\"use client\";\n\nimport * as React from \"react\";\nimport { clsx, type ClassValue } from \"clsx\";\nimport { twMerge } from \"tailwind-merge\";\n\nfunction cn(...inputs: ClassValue[]) {\n  return twMerge(clsx(inputs));\n}\n\nexport type ChartTheme = \"dark\" | \"light\";\n\nexport interface StreamSeries {\n  label: string;\n  /** One value per x position. */\n  values: number[];\n  color?: string;\n}\n\nexport interface StreamgraphProps extends Omit<\n  React.ComponentPropsWithoutRef<\"div\">,\n  \"title\"\n> {\n  theme?: ChartTheme;\n  title?: string;\n  subtitle?: string;\n  series?: StreamSeries[];\n  /** Label for each x position. */\n  labels?: string[];\n  /** \"silhouette\" centres the streams; \"wiggle\" also minimises how much they slope (less jitter). */\n  offset?: \"silhouette\" | \"wiggle\";\n  /** Write each stream's name inside it where it's thick enough. */\n  inlineLabels?: boolean;\n  /** Height of the plot, in px. */\n  height?: number;\n  formatValue?: (value: number) => string;\n}\n\nconst PALETTES = {\n  dark: {\n    card: \"#0E0E0E\",\n    border: \"rgba(255,255,255,0.08)\",\n    text: \"#F4F5F7\",\n    sub: \"rgba(255,255,255,0.55)\",\n    grid: \"rgba(255,255,255,0.06)\",\n    axis: \"rgba(255,255,255,0.45)\",\n    tip: \"rgba(20,20,20,0.96)\",\n    tipBorder: \"rgba(255,255,255,0.12)\",\n    ink: \"#0E0E0E\",\n    series: [\"#87FFE3\", \"#8FB8FF\", \"#B69CFF\", \"#FFB3D9\", \"#F2A841\", \"#FF7A6B\"],\n  },\n  light: {\n    card: \"#FFFFFF\",\n    border: \"rgba(0,0,0,0.07)\",\n    text: \"#111317\",\n    sub: \"rgba(17,19,23,0.55)\",\n    grid: \"rgba(17,19,23,0.06)\",\n    axis: \"rgba(17,19,23,0.5)\",\n    tip: \"rgba(255,255,255,0.98)\",\n    tipBorder: \"rgba(0,0,0,0.08)\",\n    ink: \"#FFFFFF\",\n    series: [\"#0E9F80\", \"#3B6FD8\", \"#7B5CE0\", \"#DB2777\", \"#D9822B\", \"#E5484D\"],\n  },\n};\n\nconst MONTHS = [\n  \"Jan\",\n  \"Feb\",\n  \"Mar\",\n  \"Apr\",\n  \"May\",\n  \"Jun\",\n  \"Jul\",\n  \"Aug\",\n  \"Sep\",\n  \"Oct\",\n  \"Nov\",\n  \"Dec\",\n];\n\n// Deterministic sample: weekly mentions for six topics, each swelling and fading at its own time.\nfunction sampleSeries(): { series: StreamSeries[]; labels: string[] } {\n  const weeks = 36;\n  const topics: [string, number, number, number, number][] = [\n    [\"Pricing\", 120, 9, 6, 60],\n    [\"Integrations\", 160, 20, 8, 70],\n    [\"Performance\", 90, 28, 5, 40],\n    [\"Mobile app\", 140, 14, 7, 45],\n    [\"AI features\", 210, 31, 6, 20],\n    [\"Onboarding\", 80, 4, 9, 55],\n  ];\n  const series = topics.map(([label, peak, at, spread, floor], k) => ({\n    label,\n    values: Array.from({ length: weeks }, (_, i) =>\n      Math.round(\n        floor +\n          peak * Math.exp(-((i - at) ** 2) / (2 * spread * spread)) +\n          14 * Math.sin(i * 0.9 + k * 1.7) +\n          14,\n      ),\n    ),\n  }));\n  const labels = Array.from({ length: weeks }, (_, i) => {\n    const d = new Date(Date.UTC(2025, 0, 6 + i * 7));\n    return `${MONTHS[d.getUTCMonth()]} ${d.getUTCDate()}`;\n  });\n  return { series, labels };\n}\n\nconst SAMPLE = sampleSeries();\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\nfunction useWidth(ref: React.RefObject<HTMLElement | null>) {\n  const [width, setWidth] = React.useState(0);\n  React.useEffect(() => {\n    const el = ref.current;\n    if (!el) return;\n    const ro = new ResizeObserver(([entry]) =>\n      setWidth(entry.contentRect.width),\n    );\n    ro.observe(el);\n    return () => ro.disconnect();\n  }, [ref]);\n  return width;\n}\n\n/** 0 → 1 (linear) once the element scrolls into view; 1 straight away with reduced motion. */\nfunction useReveal(\n  ref: React.RefObject<HTMLElement | null>,\n  reduce: boolean,\n  duration = 1500,\n) {\n  const [t, setT] = React.useState(0);\n  React.useEffect(() => {\n    const el = ref.current;\n    if (!el || reduce) return;\n    let raf = 0;\n    const io = new IntersectionObserver(\n      ([entry]) => {\n        if (!entry.isIntersecting) return;\n        io.disconnect();\n        const start = performance.now();\n        const tick = (now: number) => {\n          const k = Math.min(1, (now - start) / duration);\n          setT(k);\n          if (k < 1) raf = requestAnimationFrame(tick);\n        };\n        raf = requestAnimationFrame(tick);\n      },\n      { threshold: 0.2 },\n    );\n    io.observe(el);\n    return () => {\n      io.disconnect();\n      cancelAnimationFrame(raf);\n    };\n  }, [ref, reduce, duration]);\n  return reduce ? 1 : t;\n}\n\n/** Catmull-Rom spline through points, as cubic Bézier segments (continues an existing path). */\nfunction spline(pts: [number, number][], move: boolean) {\n  if (!pts.length) return \"\";\n  let d = `${move ? \"M\" : \"L\"}${pts[0][0]},${pts[0][1]}`;\n  for (let i = 0; i < pts.length - 1; i++) {\n    const p0 = pts[i - 1] ?? pts[i];\n    const p1 = pts[i];\n    const p2 = pts[i + 1];\n    const p3 = pts[i + 2] ?? p2;\n    d += `C${p1[0] + (p2[0] - p0[0]) / 6},${p1[1] + (p2[1] - p0[1]) / 6} ${p2[0] - (p3[0] - p1[0]) / 6},${p2[1] - (p3[1] - p1[1]) / 6} ${p2[0]},${p2[1]}`;\n  }\n  return d;\n}\n\nconst M = { top: 8, right: 8, bottom: 28, left: 8 };\n\nexport function Streamgraph({\n  theme = \"dark\",\n  title = \"Feedback by topic\",\n  subtitle = \"Weekly mentions in support tickets and reviews, 2025\",\n  series = SAMPLE.series,\n  labels = SAMPLE.labels,\n  offset = \"wiggle\",\n  inlineLabels = true,\n  height = 300,\n  formatValue = (v) => Math.round(v).toLocaleString(\"en-US\"),\n  className,\n  style,\n  ...props\n}: StreamgraphProps) {\n  const pal = PALETTES[theme];\n  const reduce = useReducedMotion();\n  const plotRef = React.useRef<HTMLDivElement>(null);\n  const width = useWidth(plotRef);\n  const reveal = useReveal(plotRef, reduce);\n  const [active, setActive] = React.useState<number | null>(null);\n  const [hot, setHot] = React.useState<number | null>(null);\n  const id = React.useId();\n  const colors = series.map(\n    (s, i) => s.color ?? pal.series[i % pal.series.length],\n  );\n\n  const n = Math.max(0, ...series.map((s) => s.values.length));\n  const plotW = Math.max(0, width - M.left - M.right);\n  const xAt = (i: number) =>\n    M.left + (n > 1 ? (i / (n - 1)) * plotW : plotW / 2);\n\n  // Stack with a moving baseline: silhouette centres each column; wiggle (Byron & Wattenberg) also\n  // shifts it to minimise the weighted slope of the streams, which reads calmer.\n  const layers = React.useMemo(() => {\n    const m = series.length;\n    const v = (s: number, i: number) => Math.max(0, series[s].values[i] ?? 0);\n    const base: number[] = [];\n    for (let i = 0; i < n; i++) {\n      const total = series.reduce((sum, _, s) => sum + v(s, i), 0);\n      if (offset === \"silhouette\" || i === 0) base.push(-total / 2);\n      else {\n        // Each layer's slope at its own middle, weighted by its thickness.\n        let num = 0;\n        for (let s = 0; s < m; s++) {\n          let mid = (v(s, i) - v(s, i - 1)) / 2;\n          for (let k = 0; k < s; k++) mid += v(k, i) - v(k, i - 1);\n          num += mid * v(s, i);\n        }\n        base.push(base[i - 1] - (total ? num / total : 0));\n      }\n    }\n    // Recentre so the whole graph sits in the middle of the plot.\n    const lows = base;\n    const highs = base.map(\n      (b, i) => b + series.reduce((sum, _, s) => sum + v(s, i), 0),\n    );\n    const mid = (Math.min(...lows) + Math.max(...highs)) / 2;\n    return series.map((_, s) =>\n      Array.from({ length: n }, (_, i) => {\n        let lo = base[i] - mid;\n        for (let k = 0; k < s; k++) lo += v(k, i);\n        return [lo, lo + v(s, i)] as [number, number];\n      }),\n    );\n  }, [series, n, offset]);\n\n  const extent = Math.max(\n    1,\n    ...layers.flatMap((l) =>\n      l.map(([a, b]) => Math.max(Math.abs(a), Math.abs(b))),\n    ),\n  );\n  const grow = reduce\n    ? 1\n    : 0.25 + 0.75 * (1 - Math.pow(1 - Math.min(1, reveal * 1.3), 3));\n  const yAt = (v: number) =>\n    M.top + height / 2 - (v / extent) * (height / 2) * grow;\n  const paths = layers.map((l) => {\n    const top = l.map(([, b], i) => [xAt(i), yAt(b)] as [number, number]);\n    const bot = l\n      .map(([a], i) => [xAt(i), yAt(a)] as [number, number])\n      .reverse();\n    return `${spline(top, true)}${spline(bot, false)}Z`;\n  });\n  // Inline label spot: where each stream is thickest (away from the edges).\n  const spots = layers.map((l) => {\n    let best = 1;\n    for (let i = 1; i < n - 1; i++)\n      if (l[i][1] - l[i][0] > l[best][1] - l[best][0]) best = i;\n    return {\n      i: best,\n      thick: ((l[best][1] - l[best][0]) / extent) * (height / 2),\n    };\n  });\n  const every = Math.max(1, Math.ceil((n * 64) / Math.max(1, plotW)));\n\n  const pick = (clientX: number, clientY: number) => {\n    const r = plotRef.current?.getBoundingClientRect();\n    if (!r || !n) return;\n    const i = Math.max(\n      0,\n      Math.min(\n        n - 1,\n        Math.round(\n          ((clientX - r.left - M.left) / Math.max(1, plotW)) * (n - 1),\n        ),\n      ),\n    );\n    setActive(i);\n    const y = clientY - r.top;\n    const s = layers.findIndex((l) => y <= yAt(l[i][0]) && y >= yAt(l[i][1]));\n    setHot(s >= 0 ? s : null);\n  };\n  const onKey = (event: React.KeyboardEvent) => {\n    if (!n) return;\n    const k = event.key;\n    if (k === \"ArrowRight\" || k === \"ArrowLeft\") {\n      event.preventDefault();\n      setActive((a) =>\n        Math.max(\n          0,\n          Math.min(\n            n - 1,\n            a === null\n              ? k === \"ArrowRight\"\n                ? 0\n                : n - 1\n              : a + (k === \"ArrowRight\" ? 1 : -1),\n          ),\n        ),\n      );\n    } else if (k === \"ArrowUp\" || k === \"ArrowDown\") {\n      event.preventDefault();\n      setHot(\n        (h) =>\n          ((h ?? (k === \"ArrowDown\" ? -1 : series.length)) +\n            (k === \"ArrowDown\" ? 1 : -1) +\n            series.length) %\n          series.length,\n      );\n      setActive((a) => a ?? n - 1);\n    } else if (k === \"Escape\") {\n      setActive(null);\n      setHot(null);\n    }\n  };\n\n  const totals = series.map((s) => s.values.reduce((a, b) => a + b, 0));\n  const leader = totals.indexOf(Math.max(...totals));\n  const tipX = active !== null ? xAt(active) : 0;\n  const tipFlip = tipX > width - 210;\n  const atTotal =\n    active !== null\n      ? series.reduce((s, sr) => s + (sr.values[active] ?? 0), 0)\n      : 0;\n  const summary = `${title}. ${series.map((s, i) => `${s.label}: ${formatValue(totals[i])} in total, peaking around ${labels[spots[i].i] ?? \"\"}`).join(\"; \")}.`;\n\n  return (\n    <div\n      className={cn(\n        \"w-full overflow-hidden rounded-[20px] p-5 sm:p-7\",\n        className,\n      )}\n      style={{\n        background: pal.card,\n        border: `1px solid ${pal.border}`,\n        color: pal.text,\n        fontFamily: \"Inter, -apple-system, BlinkMacSystemFont, sans-serif\",\n        ...style,\n      }}\n      {...props}\n    >\n      <div className=\"flex flex-wrap items-start justify-between gap-4\">\n        <div className=\"min-w-0\">\n          <p className=\"text-[15px] font-semibold tracking-[-0.01em]\">\n            {title}\n          </p>\n          {subtitle && (\n            <p className=\"mt-1 text-[12.5px]\" style={{ color: pal.sub }}>\n              {subtitle}\n            </p>\n          )}\n        </div>\n        <div className=\"text-right\">\n          <p className=\"text-[22px] leading-none font-semibold tracking-[-0.02em] tabular-nums\">\n            {formatValue(totals.reduce((a, b) => a + b, 0))}\n          </p>\n          <p className=\"mt-1 text-[11.5px]\" style={{ color: pal.sub }}>\n            Most mentioned:{\" \"}\n            <span style={{ color: colors[leader] }}>\n              {series[leader]?.label}\n            </span>\n          </p>\n        </div>\n      </div>\n\n      <div className=\"mt-4 flex flex-wrap gap-x-4 gap-y-2\">\n        {series.map((s, i) => (\n          <button\n            key={s.label}\n            type=\"button\"\n            onMouseEnter={() => setHot(i)}\n            onMouseLeave={() => setHot(null)}\n            onFocus={() => setHot(i)}\n            onBlur={() => setHot(null)}\n            className=\"flex cursor-default items-center gap-1.5 text-[12px] font-medium transition-opacity\"\n            style={{ opacity: hot === null || hot === i ? 1 : 0.45 }}\n          >\n            <span\n              className=\"size-2.5 rounded-full\"\n              style={{ background: colors[i] }}\n            />\n            {s.label}\n          </button>\n        ))}\n      </div>\n\n      <div\n        ref={plotRef}\n        role=\"img\"\n        aria-label={summary}\n        tabIndex={0}\n        onKeyDown={onKey}\n        onPointerMove={(e) => pick(e.clientX, e.clientY)}\n        onPointerDown={(e) => pick(e.clientX, e.clientY)}\n        onPointerLeave={(e) => {\n          if (e.pointerType !== \"mouse\") return;\n          setActive(null);\n          setHot(null);\n        }}\n        onBlur={() => {\n          setActive(null);\n          setHot(null);\n        }}\n        className=\"relative mt-3 w-full rounded-lg outline-none focus-visible:ring-2\"\n        style={{ height: height + M.top + M.bottom }}\n      >\n        {width > 0 && (\n          <svg\n            width={width}\n            height={height + M.top + M.bottom}\n            className=\"block\"\n            aria-hidden=\"true\"\n          >\n            <defs>\n              <clipPath id={`${id}-clip`}>\n                <rect\n                  x={0}\n                  y={0}\n                  width={M.left + plotW * Math.min(1, reveal * 1.15) + 1}\n                  height={height + M.top}\n                />\n              </clipPath>\n            </defs>\n            {labels.map((l, i) =>\n              i % every === 0 ? (\n                <g key={l + i}>\n                  <line\n                    x1={xAt(i)}\n                    x2={xAt(i)}\n                    y1={M.top}\n                    y2={M.top + height}\n                    stroke={pal.grid}\n                  />\n                  <text\n                    x={xAt(i)}\n                    y={M.top + height + 20}\n                    textAnchor={i === 0 ? \"start\" : \"middle\"}\n                    fontSize={11}\n                    fill={pal.axis}\n                  >\n                    {l}\n                  </text>\n                </g>\n              ) : null,\n            )}\n            <g clipPath={`url(#${id}-clip)`}>\n              {paths.map((d, s) => (\n                <path\n                  key={series[s].label}\n                  d={d}\n                  fill={colors[s]}\n                  fillOpacity={\n                    hot === null\n                      ? theme === \"dark\"\n                        ? 0.82\n                        : 0.78\n                      : hot === s\n                        ? 0.95\n                        : 0.18\n                  }\n                  stroke={pal.card}\n                  strokeWidth={0.8}\n                  style={{ transition: \"fill-opacity 180ms\" }}\n                />\n              ))}\n              {inlineLabels &&\n                series.map((s, i) =>\n                  spots[i].thick * grow > 22 ? (\n                    <text\n                      key={`t${s.label}`}\n                      x={Math.min(\n                        Math.max(xAt(spots[i].i), M.left + 50),\n                        M.left + plotW - 50,\n                      )}\n                      y={\n                        yAt(\n                          (layers[i][spots[i].i][0] +\n                            layers[i][spots[i].i][1]) /\n                            2,\n                        ) + 4\n                      }\n                      textAnchor=\"middle\"\n                      fontSize={12}\n                      fontWeight={600}\n                      fill={pal.ink}\n                      opacity={\n                        (hot === null || hot === i ? 0.85 : 0.2) *\n                        Math.min(1, Math.max(0, reveal * 2 - 1))\n                      }\n                      style={{\n                        pointerEvents: \"none\",\n                        transition: \"opacity 180ms\",\n                      }}\n                    >\n                      {s.label}\n                    </text>\n                  ) : null,\n                )}\n            </g>\n            {active !== null && (\n              <line\n                x1={tipX}\n                x2={tipX}\n                y1={M.top}\n                y2={M.top + height}\n                stroke={pal.text}\n                strokeOpacity={0.6}\n                strokeDasharray=\"2 3\"\n              />\n            )}\n          </svg>\n        )}\n        {active !== null && width > 0 && (\n          <div\n            className=\"pointer-events-none absolute top-1 z-10 min-w-[180px] rounded-xl px-3 py-2.5 text-[12px] shadow-xl\"\n            style={{\n              left: tipFlip ? undefined : tipX + 12,\n              right: tipFlip ? width - tipX + 12 : undefined,\n              background: pal.tip,\n              border: `1px solid ${pal.tipBorder}`,\n              backdropFilter: \"blur(8px)\",\n            }}\n          >\n            <p className=\"mb-1.5 font-semibold\">Week of {labels[active]}</p>\n            {series\n              .map((s, i) => ({ s, i, v: s.values[active] ?? 0 }))\n              .sort((a, b) => b.v - a.v)\n              .map(({ s, i, v }) => (\n                <div\n                  key={s.label}\n                  className=\"mt-1 flex items-center justify-between gap-4\"\n                  style={{ opacity: hot === null || hot === i ? 1 : 0.45 }}\n                >\n                  <span\n                    className=\"flex items-center gap-1.5\"\n                    style={{\n                      color: hot === i ? pal.text : pal.sub,\n                      fontWeight: hot === i ? 600 : 400,\n                    }}\n                  >\n                    <span\n                      className=\"size-2 rounded-full\"\n                      style={{ background: colors[i] }}\n                    />\n                    {s.label}\n                  </span>\n                  <span className=\"font-semibold tabular-nums\">\n                    {formatValue(v)}\n                  </span>\n                </div>\n              ))}\n            <div\n              className=\"mt-2 flex justify-between border-t pt-1.5\"\n              style={{ borderColor: pal.tipBorder }}\n            >\n              <span style={{ color: pal.sub }}>Total</span>\n              <span className=\"font-semibold tabular-nums\">\n                {formatValue(atTotal)}\n              </span>\n            </div>\n          </div>\n        )}\n      </div>\n    </div>\n  );\n}\n",
      "type": "registry:component"
    }
  ],
  "type": "registry:component"
}