{
  "$schema": "https://ui.shadcn.com/schema/registry-item.json",
  "name": "waterfall-chart",
  "title": "Waterfall Chart",
  "description": "A waterfall (bridge) chart that explains how a number got from A to B: floating bars for each increase and decrease, totals anchored to zero, dashed connectors, signed value labels, a net change in the header and a running-total tooltip.",
  "dependencies": [
    "clsx",
    "tailwind-merge"
  ],
  "files": [
    {
      "path": "registry/new-york/waterfall-chart/waterfall-chart.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 WaterfallStep {\n  label: string;\n  /** For \"start\": the opening amount. For \"delta\": the change (negative to subtract). Ignored for \"total\". */\n  value?: number;\n  /** \"start\" opens the bridge, \"delta\" adds or subtracts, \"total\" shows the running total so far. */\n  kind?: \"start\" | \"delta\" | \"total\";\n}\n\nexport interface WaterfallChartProps extends Omit<\n  React.ComponentPropsWithoutRef<\"div\">,\n  \"title\"\n> {\n  theme?: ChartTheme;\n  title?: string;\n  subtitle?: string;\n  steps?: WaterfallStep[];\n  upColor?: string;\n  downColor?: string;\n  totalColor?: string;\n  /** Height of the plot area, 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.07)\",\n    axis: \"rgba(255,255,255,0.45)\",\n    link: \"rgba(255,255,255,0.3)\",\n    tip: \"rgba(20,20,20,0.96)\",\n    tipBorder: \"rgba(255,255,255,0.12)\",\n    band: \"rgba(255,255,255,0.04)\",\n    up: \"#2EE6A8\",\n    down: \"#FF6B78\",\n    total: \"#8FB8FF\",\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.08)\",\n    axis: \"rgba(17,19,23,0.5)\",\n    link: \"rgba(17,19,23,0.3)\",\n    tip: \"rgba(255,255,255,0.98)\",\n    tipBorder: \"rgba(0,0,0,0.08)\",\n    band: \"rgba(17,19,23,0.04)\",\n    up: \"#0E9F6E\",\n    down: \"#E5484D\",\n    total: \"#3B6FD8\",\n  },\n};\n\nconst DEFAULT_STEPS: WaterfallStep[] = [\n  { label: \"Q1 ARR\", value: 1240000, kind: \"start\" },\n  { label: \"New\", value: 312000 },\n  { label: \"Expansion\", value: 148000 },\n  { label: \"Reactivation\", value: 36000 },\n  { label: \"Contraction\", value: -64000 },\n  { label: \"Churn\", value: -182000 },\n  { label: \"Q2 ARR\", kind: \"total\" },\n];\n\nconst money = new Intl.NumberFormat(\"en-US\", {\n  style: \"currency\",\n  currency: \"USD\",\n  notation: \"compact\",\n  maximumFractionDigits: 1,\n});\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 = 1600,\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\nfunction niceScale(min: number, max: number, count = 5) {\n  const span = Math.max(1e-9, max - min);\n  const raw = span / count;\n  const mag = Math.pow(10, Math.floor(Math.log10(raw)));\n  const step =\n    [1, 2, 2.5, 5, 10].map((m) => m * mag).find((s) => s >= raw) ?? 10 * mag;\n  const lo = Math.floor(min / step) * step;\n  const hi = Math.ceil(max / step) * step;\n  return {\n    min: lo,\n    max: hi,\n    ticks: Array.from(\n      { length: Math.round((hi - lo) / step) + 1 },\n      (_, i) => lo + i * step,\n    ),\n  };\n}\n\nconst easeOut = (t: number) => 1 - Math.pow(1 - Math.min(1, Math.max(0, t)), 3);\n\nconst M = { top: 26, right: 12, bottom: 34, left: 56 };\n\nexport function WaterfallChart({\n  theme = \"dark\",\n  title = \"ARR bridge\",\n  subtitle = \"What moved annual recurring revenue from Q1 to Q2\",\n  steps = DEFAULT_STEPS,\n  upColor,\n  downColor,\n  totalColor,\n  height = 300,\n  formatValue = (v) => money.format(v),\n  className,\n  style,\n  ...props\n}: WaterfallChartProps) {\n  const pal = PALETTES[theme];\n  const colors = {\n    up: upColor ?? pal.up,\n    down: downColor ?? pal.down,\n    total: totalColor ?? pal.total,\n  };\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\n  // Each bar's span [from, to] and running total after it.\n  const bars = React.useMemo(() => {\n    const out: { kind: \"start\" | \"delta\" | \"total\"; from: number; to: number; delta: number; run: number }[] = [];\n    for (let i = 0; i < steps.length; i++) {\n      const s = steps[i];\n      const kind = s.kind ?? (i === 0 ? \"start\" : \"delta\");\n      const prev = out[i - 1]?.run ?? 0;\n      if (kind === \"start\") out.push({ kind, from: 0, to: s.value ?? 0, delta: s.value ?? 0, run: s.value ?? 0 });\n      else if (kind === \"total\") out.push({ kind, from: 0, to: prev, delta: prev, run: prev });\n      else out.push({ kind, from: prev, to: prev + (s.value ?? 0), delta: s.value ?? 0, run: prev + (s.value ?? 0) });\n    }\n    return out;\n  }, [steps]);\n\n  const n = steps.length;\n  const plotW = Math.max(0, width - M.left - M.right);\n  const slot = n ? plotW / n : 0;\n  const barW = Math.max(10, Math.min(64, slot * 0.62));\n  const xAt = (i: number) => M.left + slot * (i + 0.5);\n  const lo = Math.min(0, ...bars.map((b) => Math.min(b.from, b.to)));\n  const hi = Math.max(...bars.map((b) => Math.max(b.from, b.to)));\n  // Zoom the axis in on where the action is unless totals need to start at zero to stay honest.\n  const sc = niceScale(lo, hi * 1.06, 5);\n  const yAt = (v: number) =>\n    M.top + height - ((v - sc.min) / (sc.max - sc.min)) * height;\n  const colorOf = (b: (typeof bars)[number]) =>\n    b.kind === \"delta\"\n      ? b.delta >= 0\n        ? colors.up\n        : colors.down\n      : colors.total;\n  const start = bars[0]?.run ?? 0;\n  const end = bars[n - 1]?.run ?? 0;\n  const net = end - start;\n  const compactLabels = slot < 64;\n\n  const pick = (clientX: number) => {\n    const r = plotRef.current?.getBoundingClientRect();\n    if (!r || !n) return;\n    const i = Math.floor((clientX - r.left - M.left) / Math.max(1, slot));\n    setActive(i >= 0 && i < n ? i : null);\n  };\n  const onKey = (event: React.KeyboardEvent) => {\n    if (!n) return;\n    if (event.key === \"ArrowRight\" || event.key === \"ArrowLeft\") {\n      event.preventDefault();\n      const dir = event.key === \"ArrowRight\" ? 1 : -1;\n      setActive((a) =>\n        Math.max(\n          0,\n          Math.min(n - 1, a === null ? (dir > 0 ? 0 : n - 1) : a + dir),\n        ),\n      );\n    } else if (event.key === \"Home\") setActive(0);\n    else if (event.key === \"End\") setActive(n - 1);\n    else if (event.key === \"Escape\") setActive(null);\n  };\n\n  const ab = active !== null ? bars[active] : null;\n  const tipX = active !== null ? xAt(active) : 0;\n  // Floating bars have room underneath them; totals stand on zero, so their tooltip goes above.\n  const tipTop = ab\n    ? ab.kind === \"delta\"\n      ? yAt(Math.min(ab.from, ab.to)) + 12\n      : Math.max(0, yAt(Math.max(ab.from, ab.to)) - 112)\n    : 0;\n  const tipLeft = Math.max(0, Math.min(width - 186, tipX - 90));\n  const signed = (v: number) =>\n    `${v >= 0 ? \"+\" : \"−\"}${formatValue(Math.abs(v))}`;\n  const summary = `${title}. ${steps.map((s, i) => `${s.label}: ${bars[i].kind === \"delta\" ? signed(bars[i].delta) : formatValue(bars[i].run)}`).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(end)}\n          </p>\n          <p\n            className=\"mt-1 text-[11.5px] tabular-nums\"\n            style={{ color: net >= 0 ? colors.up : colors.down }}\n          >\n            {signed(net)} ({net >= 0 ? \"+\" : \"−\"}\n            {Math.abs(start ? (net / start) * 100 : 0).toFixed(1)}%) net\n          </p>\n        </div>\n      </div>\n\n      <div className=\"mt-4 flex flex-wrap gap-x-4 gap-y-1.5 text-[12px] font-medium\">\n        {(\n          [\n            [\"Increase\", colors.up],\n            [\"Decrease\", colors.down],\n            [\"Total\", colors.total],\n          ] as const\n        ).map(([label, c]) => (\n          <span key={label} className=\"flex items-center gap-1.5\">\n            <span\n              className=\"size-2.5 rounded-[3px]\"\n              style={{ background: c }}\n            />\n            {label}\n          </span>\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)}\n        onPointerDown={(e) => pick(e.clientX)}\n        onPointerLeave={(e) => e.pointerType === \"mouse\" && setActive(null)}\n        onBlur={() => setActive(null)}\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 overflow-visible\"\n            aria-hidden=\"true\"\n          >\n            {sc.ticks.map((t) => (\n              <g key={t}>\n                <line\n                  x1={M.left}\n                  x2={M.left + plotW}\n                  y1={yAt(t)}\n                  y2={yAt(t)}\n                  stroke={pal.grid}\n                  strokeDasharray={t === 0 ? undefined : \"3 4\"}\n                />\n                <text\n                  x={M.left - 10}\n                  y={yAt(t) + 4}\n                  textAnchor=\"end\"\n                  fontSize={11}\n                  fill={pal.axis}\n                  className=\"tabular-nums\"\n                >\n                  {formatValue(t)}\n                </text>\n              </g>\n            ))}\n            {active !== null && (\n              <rect\n                x={xAt(active) - slot / 2}\n                y={M.top - 20}\n                width={slot}\n                height={height + 20}\n                rx={8}\n                fill={pal.band}\n              />\n            )}\n            {bars.map((b, i) => {\n              // Bars fall into place one after another, each growing from where the previous one ended.\n              const t = easeOut(reveal * 1.5 - (i / Math.max(1, n)) * 0.5);\n              const grownTo = b.from + (b.to - b.from) * t;\n              const y0 = yAt(Math.max(b.from, grownTo));\n              const y1 = yAt(Math.min(b.from, grownTo));\n              const x = xAt(i) - barW / 2;\n              const c = colorOf(b);\n              const next = bars[i + 1];\n              const label =\n                b.kind === \"delta\" ? signed(b.delta) : formatValue(b.run);\n              return (\n                <g\n                  key={steps[i].label + i}\n                  opacity={active === null || active === i ? 1 : 0.45}\n                  style={{ transition: \"opacity 160ms\" }}\n                >\n                  <rect\n                    x={x}\n                    y={y0}\n                    width={barW}\n                    height={Math.max(1, y1 - y0)}\n                    rx={Math.min(5, barW / 5)}\n                    fill={c}\n                    fillOpacity={b.kind === \"delta\" ? 0.9 : 1}\n                  />\n                  {next && t > 0.98 && (\n                    <line\n                      x1={x + barW}\n                      x2={xAt(i + 1) - barW / 2}\n                      y1={yAt(b.run)}\n                      y2={yAt(b.run)}\n                      stroke={pal.link}\n                      strokeDasharray=\"3 3\"\n                    />\n                  )}\n                  {!compactLabels && (\n                    <text\n                      x={xAt(i)}\n                      y={y0 - 8}\n                      textAnchor=\"middle\"\n                      fontSize={11.5}\n                      fontWeight={600}\n                      fill={b.kind === \"delta\" ? c : pal.text}\n                      opacity={t}\n                      className=\"tabular-nums\"\n                    >\n                      {label}\n                    </text>\n                  )}\n                  <text\n                    x={xAt(i)}\n                    y={M.top + height + 20}\n                    textAnchor=\"middle\"\n                    fontSize={compactLabels ? 10 : 11}\n                    fill={active === i ? pal.text : pal.axis}\n                  >\n                    {compactLabels && steps[i].label.length > 7\n                      ? `${steps[i].label.slice(0, 6)}…`\n                      : steps[i].label}\n                  </text>\n                </g>\n              );\n            })}\n          </svg>\n        )}\n        {ab && active !== null && width > 0 && (\n          <div\n            className=\"pointer-events-none absolute z-10 w-[180px] rounded-xl px-3 py-2.5 text-[12px] shadow-xl\"\n            style={{\n              left: tipLeft,\n              top: tipTop,\n              background: pal.tip,\n              border: `1px solid ${pal.tipBorder}`,\n              backdropFilter: \"blur(8px)\",\n            }}\n          >\n            <p className=\"flex items-center gap-1.5 font-semibold\">\n              <span\n                className=\"size-2 rounded-[2px]\"\n                style={{ background: colorOf(ab) }}\n              />\n              {steps[active].label}\n            </p>\n            {ab.kind === \"delta\" ? (\n              <>\n                <div className=\"mt-1.5 flex justify-between gap-4\">\n                  <span style={{ color: pal.sub }}>Change</span>\n                  <span\n                    className=\"font-semibold tabular-nums\"\n                    style={{ color: colorOf(ab) }}\n                  >\n                    {signed(ab.delta)}\n                  </span>\n                </div>\n                <div className=\"mt-1 flex justify-between gap-4\">\n                  <span style={{ color: pal.sub }}>Share of start</span>\n                  <span className=\"font-semibold tabular-nums\">\n                    {start ? `${((ab.delta / start) * 100).toFixed(1)}%` : \"–\"}\n                  </span>\n                </div>\n                <div className=\"mt-1 flex justify-between gap-4\">\n                  <span style={{ color: pal.sub }}>Running total</span>\n                  <span className=\"font-semibold tabular-nums\">\n                    {formatValue(ab.run)}\n                  </span>\n                </div>\n              </>\n            ) : (\n              <div className=\"mt-1.5 flex justify-between gap-4\">\n                <span style={{ color: pal.sub }}>\n                  {ab.kind === \"start\" ? \"Opening\" : \"Total\"}\n                </span>\n                <span className=\"font-semibold tabular-nums\">\n                  {formatValue(ab.run)}\n                </span>\n              </div>\n            )}\n          </div>\n        )}\n      </div>\n    </div>\n  );\n}\n",
      "type": "registry:component"
    }
  ],
  "type": "registry:component"
}