{
  "$schema": "https://ui.shadcn.com/schema/registry-item.json",
  "name": "waterfall-chart",
  "title": "Waterfall chart",
  "description": "Running totals as floating bars that step in one after another in success and danger tones, with neutral total bars, connectors, signed value labels and a tooltip with the running total.",
  "dependencies": [
    "motion"
  ],
  "registryDependencies": [
    "https://goodui.dev/r/goodui-motion.json",
    "https://goodui.dev/r/locale.json"
  ],
  "files": [
    {
      "path": "registry/components/charts/waterfall-chart.tsx",
      "content": "\"use client\"\n\nimport * as React from \"react\"\nimport { motion, useReducedMotion } from \"motion/react\"\nimport { cn } from \"@/lib/utils\"\nimport { useLabels } from \"@/lib/goodui-locale\"\nimport { GooduiTokens, spring as springs } from \"@/lib/goodui-motion\"\n\nexport type WaterfallStep = {\n  /** Defaults to the label. */\n  key?: string\n  label: string\n  /** Change from the previous step (ignored for totals). */\n  value: number\n  /** Draws the running total so far as a full bar from zero. */\n  total?: boolean\n}\n\nexport type WaterfallChartLabels = {\n  summary: (name: string, start: string, end: string) => string\n  /** Announced for the active step. */\n  step: (label: string, change: string | null, runningTotal: string) => string\n  runningTotal: string\n  columnStep: string\n  columnChange: string\n  columnTotal: string\n  noData: string\n}\nconst DEFAULT_LABELS: WaterfallChartLabels = {\n  summary: (name, start, end) => `${name ? name + \": \" : \"\"}from ${start} to ${end}`,\n  step: (label, change, total) => `${label}: ${change ? `${change}, ` : \"\"}total ${total}`,\n  runningTotal: \"Running total\",\n  columnStep: \"Step\",\n  columnChange: \"Change\",\n  columnTotal: \"Running total\",\n  noData: \"No data\",\n}\n\nexport type WaterfallChartProps = Omit<React.ComponentProps<\"div\">, \"title\"> & {\n  steps: WaterfallStep[]\n  /** Running total before the first step, e.g. an opening balance that a leading total step then draws. */\n  start?: number\n  /** Chart name for screen readers and the table caption. */\n  title?: React.ReactNode\n  /** Plot height in px, axes included. */\n  height?: number\n  /** Maximum bar thickness in px. */\n  barSize?: number\n  radius?: number\n  /** Hairlines joining each bar's end to the next bar's start. */\n  connectors?: boolean\n  /** Signed change above each bar (the total on total bars). */\n  valueLabels?: boolean\n  /** Colors for increases, decreases and totals. Default to the kit's success, danger and neutral tones. */\n  colors?: { positive?: string; negative?: string; total?: string }\n  grid?: boolean\n  axis?: boolean\n  axisWidth?: number\n  format?: Intl.NumberFormatOptions\n  locale?: string\n  formatValue?: (value: number) => string\n  formatTick?: (value: number) => string\n  /** Seconds a bar takes to grow; bars run one after another at 80 ms. */\n  duration?: number\n  /** Text for built-in controls and screen readers; pass translations here. */\n  labels?: Partial<WaterfallChartLabels>\n}\n\nconst CSS = `\n.pc-waterfall-chart{--pc-wf-pos:oklch(0.53 0.13 155);--pc-wf-neg:oklch(0.56 0.21 27);--pc-wf-total:color-mix(in oklab,var(--foreground) 72%,transparent)}\n.dark .pc-waterfall-chart{--pc-wf-pos:oklch(0.7 0.16 155);--pc-wf-neg:oklch(0.68 0.2 25)}\n`\n\nfunction useReduce() {\n  const prefers = useReducedMotion()\n  const [mounted, setMounted] = React.useState(false)\n  React.useEffect(() => setMounted(true), [])\n  return mounted && !!prefers\n}\n\nfunction useInView(ref: React.RefObject<Element | null>, threshold = 0.2) {\n  const [inView, setInView] = React.useState(false)\n  React.useEffect(() => {\n    const el = ref.current\n    if (!el || inView) return\n    if (typeof IntersectionObserver === \"undefined\") {\n      setInView(true)\n      return\n    }\n    const io = new IntersectionObserver(\n      ([e]) => {\n        if (e?.isIntersecting) {\n          setInView(true)\n          io.disconnect()\n        }\n      },\n      { threshold },\n    )\n    io.observe(el)\n    return () => io.disconnect()\n  }, [ref, inView, threshold])\n  return inView\n}\n\nfunction useWidth(ref: React.RefObject<HTMLElement | null>) {\n  const [width, setWidth] = React.useState<number | null>(null)\n  React.useLayoutEffect(() => {\n    const el = ref.current\n    if (!el) return\n    // A hidden parent (display:none) measures 0: keep the last real width instead of collapsing the chart.\n    const measure = () => {\n      const w = Math.round(el.clientWidth)\n      if (w > 0) setWidth(Math.max(120, w))\n    }\n    measure()\n    const ro = new ResizeObserver(measure)\n    ro.observe(el)\n    return () => ro.disconnect()\n  }, [ref])\n  return width\n}\n\nfunction niceTicks(lo: number, hi: number, count = 4): number[] {\n  if (hi <= lo) hi = lo + 1\n  const raw = (hi - lo) / count\n  const mag = 10 ** Math.floor(Math.log10(raw))\n  const norm = raw / mag\n  const step = (norm <= 1 ? 1 : norm <= 2 ? 2 : norm <= 2.5 ? 2.5 : norm <= 5 ? 5 : 10) * mag\n  const start = Math.floor(lo / step) * step\n  const end = Math.ceil(hi / step) * step\n  const ticks: number[] = []\n  for (let v = start; v <= end + step / 2; v += step) ticks.push(Number(v.toFixed(10)))\n  return ticks\n}\n\nfunction rrect(x: number, y: number, w: number, h: number, tl: number, tr: number, br: number, bl: number) {\n  const m = Math.max(0, Math.min(w / 2, h / 2))\n  const a = Math.min(tl, m)\n  const b = Math.min(tr, m)\n  const c = Math.min(br, m)\n  const d = Math.min(bl, m)\n  const f = (v: number) => v.toFixed(1)\n  return `M${f(x + a)},${f(y)}H${f(x + w - b)}Q${f(x + w)},${f(y)} ${f(x + w)},${f(y + b)}V${f(y + h - c)}Q${f(x + w)},${f(y + h)} ${f(x + w - c)},${f(y + h)}H${f(x + d)}Q${f(x)},${f(y + h)} ${f(x)},${f(y + h - d)}V${f(y + a)}Q${f(x)},${f(y)} ${f(x + a)},${f(y)}Z`\n}\n\n/** Waterfall of running totals: floating bars step up in green and down in red one after another, totals anchor to zero, connectors join the steps. */\nexport function WaterfallChart({\n  steps,\n  start = 0,\n  title,\n  height = 240,\n  barSize = 28,\n  radius = 4,\n  connectors = true,\n  valueLabels = true,\n  colors,\n  grid = true,\n  axis = true,\n  axisWidth = 44,\n  format,\n  locale = \"en-US\",\n  formatValue,\n  formatTick,\n  duration = 0.5,\n  labels,\n  className,\n  \"aria-label\": ariaLabel,\n  ...props\n}: WaterfallChartProps) {\n  const l = useLabels(\"waterfall-chart\", DEFAULT_LABELS, labels)\n  const reduce = useReduce()\n  const rootRef = React.useRef<HTMLDivElement>(null)\n  const plotRef = React.useRef<HTMLDivElement>(null)\n  const inView = useInView(rootRef)\n  const width = useWidth(plotRef)\n  const [active, setActive] = React.useState<number | null>(null)\n  const fmt = React.useMemo(() => formatValue ?? ((v: number) => new Intl.NumberFormat(locale, format).format(v)), [formatValue, locale, format])\n  const signed = React.useMemo(() => new Intl.NumberFormat(locale, { ...format, signDisplay: \"exceptZero\" }), [locale, format])\n\n  // Running totals: each step floats from the previous total; total steps draw the running total from zero.\n  let run = start\n  const items = steps.map((s, i) => {\n    const key = s.key ?? s.label\n    if (s.total) return { ...s, key, index: i, from: 0, to: run, change: null as number | null, total: true, running: run }\n    const from = run\n    run += s.value\n    return { ...s, key, index: i, from, to: run, change: s.value, total: false, running: run }\n  })\n  const n = items.length\n  const all = items.flatMap((s) => [s.from, s.to])\n  const lo0 = Math.min(0, ...(all.length ? all : [0]))\n  const hi0 = Math.max(0, ...(all.length ? all : [0]))\n  const ticks = niceTicks(lo0, hi0, 4)\n  const lo = ticks[0] ?? 0\n  const hi = ticks[ticks.length - 1] ?? 1\n  const tick = React.useMemo(() => {\n    if (formatTick) return formatTick\n    const compact = Math.max(Math.abs(hi), Math.abs(lo)) >= 10000\n    const f = new Intl.NumberFormat(locale, compact ? { ...format, notation: \"compact\", maximumFractionDigits: Math.max(1, format?.minimumFractionDigits ?? 0) } : format)\n    return (v: number) => f.format(v)\n  }, [formatTick, locale, format, hi, lo])\n\n  const W = width ?? 0\n  const padL = axis ? axisWidth : 6\n  const padR = 10\n  const padT = valueLabels ? 22 : 12\n  const padB = 24\n  const plotW = Math.max(10, W - padL - padR)\n  const plotH = Math.max(10, height - padT - padB)\n  const vy = (v: number) => padT + (1 - (v - lo) / (hi - lo || 1)) * plotH\n  const slot = plotW / Math.max(1, n)\n  const thick = Math.min(barSize, slot * 0.72)\n  const xOf = (i: number) => padL + i * slot + (slot - thick) / 2\n  const colorOf = (s: (typeof items)[number]) => (s.total ? (colors?.total ?? \"var(--pc-wf-total)\") : (s.change ?? 0) >= 0 ? (colors?.positive ?? \"var(--pc-wf-pos)\") : (colors?.negative ?? \"var(--pc-wf-neg)\"))\n\n  const bars = items.map((s, i) => {\n    const yTop = vy(Math.max(s.from, s.to))\n    const yBot = vy(Math.min(s.from, s.to))\n    const up = s.to >= s.from\n    const x = xOf(i)\n    const h = Math.max(0, yBot - yTop)\n    const r = radius\n    return { ...s, x, yTop, yBot, h, color: colorOf(s), from: s.from, to: s.to, fromPath: rrect(x, vy(s.from), thick, 0, 0, 0, 0, 0), toPath: s.total ? rrect(x, yTop, thick, h, r, r, 0, 0) : up ? rrect(x, yTop, thick, h, r, r, 0, 0) : rrect(x, yTop, thick, h, 0, 0, r, r), up }\n  })\n\n  // Dense charts keep the value labels on the totals only, and thin the step labels so neighbours never touch.\n  const denseValues = slot < 54\n  const labelStep = Math.max(1, Math.ceil(64 / Math.max(1, slot)))\n  const showStepLabel = (i: number) => i === n - 1 || (i % labelStep === 0 && (n - 1 - i) * slot >= 56)\n  const name = typeof title === \"string\" ? title : \"\"\n  const first = items[0]\n  const last = items[n - 1]\n  const summary = ariaLabel ?? (n && first && last ? l.summary(name, fmt(first.from), fmt(last.to)) : l.noData)\n  const act = active !== null ? bars[active] : undefined\n  const announce = act ? l.step(act.label, act.change === null ? null : signed.format(act.change), fmt(act.running)) : \"\"\n\n  const indexAt = (clientX: number) => {\n    const rect = plotRef.current?.getBoundingClientRect()\n    if (!rect || n === 0) return null\n    return Math.min(n - 1, Math.max(0, Math.floor((clientX - rect.left - padL) / slot)))\n  }\n  const onKeyDown = (e: React.KeyboardEvent) => {\n    if (n === 0) return\n    if (e.key === \"ArrowLeft\" || e.key === \"ArrowRight\") {\n      e.preventDefault()\n      const dir = e.key === \"ArrowLeft\" ? -1 : 1\n      setActive((i) => Math.min(n - 1, Math.max(0, (i ?? (dir > 0 ? -1 : n)) + dir)))\n    } else if (e.key === \"Home\" || e.key === \"End\") {\n      e.preventDefault()\n      setActive(e.key === \"Home\" ? 0 : n - 1)\n    } else if (e.key === \"Escape\") setActive(null)\n  }\n\n  const ready = inView || reduce\n  // A container resize reshapes the bars at once; only data changes morph.\n  const widthRef = React.useRef(W)\n  const resized = widthRef.current !== W\n  widthRef.current = W\n  const spring = reduce || resized ? { duration: 0 } : springs.morph\n  const delayOf = (i: number) => (reduce ? 0 : i * 0.08)\n  const tipX = act ? act.x + thick / 2 : 0\n  const tipRight = tipX > W * 0.55\n\n  return (\n    <div ref={rootRef} className={cn(\"pc-waterfall-chart flex w-full min-w-0 flex-col gap-2\", className)} {...props}>\n      <GooduiTokens />\n      <style href=\"pc-waterfall-chart\" precedence=\"default\">\n        {CSS}\n      </style>\n      <div\n        ref={plotRef}\n        role=\"group\"\n        aria-roledescription=\"waterfall chart\"\n        aria-label={summary}\n        tabIndex={0}\n        onPointerMove={(e) => setActive(indexAt(e.clientX))}\n        onPointerLeave={() => setActive(null)}\n        onFocus={() => setActive((i) => i ?? (n ? 0 : null))}\n        onBlur={() => setActive(null)}\n        onKeyDown={onKeyDown}\n        className=\"relative w-full touch-pan-y rounded-md outline-none focus-visible:ring-3 focus-visible:ring-ring/50\"\n        style={{ height }}\n      >\n        {width !== null && n > 0 && (\n          <svg width={W} height={height} viewBox={`0 0 ${W} ${height}`} className=\"absolute inset-0 overflow-visible\" aria-hidden=\"true\">\n            {active !== null && <rect x={padL + active * slot} y={padT - 4} width={slot} height={plotH + 8} rx={6} className=\"fill-foreground\" style={{ opacity: 0.045 }} />}\n            {ticks.map((t) => (\n              <g key={t}>\n                {grid && <line x1={padL} x2={padL + plotW} y1={vy(t)} y2={vy(t)} className={cn(t === 0 ? \"stroke-foreground/30\" : \"stroke-border\")} strokeWidth={1} />}\n                {axis && (\n                  <text x={padL - 8} y={vy(t)} dy=\".35em\" textAnchor=\"end\" className=\"fill-muted-foreground text-[11px] tabular-nums\">\n                    {tick(t)}\n                  </text>\n                )}\n              </g>\n            ))}\n            {bars.map((b, i) => (\n              <g key={b.key}>\n                <motion.path\n                  d={ready ? b.toPath : b.fromPath}\n                  style={{ fill: b.color }}\n                  initial={false}\n                  animate={{ d: ready ? b.toPath : b.fromPath, opacity: !ready ? 0 : active !== null && active !== i ? 0.7 : 1 }}\n                  transition={{ d: reduce ? { duration: 0 } : { ...spring, delay: delayOf(i) }, opacity: { duration: reduce ? 0 : 0.2 } }}\n                />\n                {connectors && i < n - 1 && (\n                  <motion.line\n                    x1={b.x + thick}\n                    x2={xOf(i + 1)}\n                    y1={vy(b.to)}\n                    y2={vy(b.to)}\n                    className=\"stroke-foreground/30\"\n                    strokeWidth={1}\n                    initial={false}\n                    animate={{ pathLength: ready ? 1 : 0, opacity: ready ? 1 : 0 }}\n                    transition={reduce ? { duration: 0 } : { duration: 0.25, delay: delayOf(i) + duration * 0.6 }}\n                  />\n                )}\n                {valueLabels && (!denseValues || b.total) && (\n                  <motion.text\n                    x={b.x + thick / 2}\n                    y={b.up || b.total ? b.yTop - 6 : b.yBot + 13}\n                    textAnchor=\"middle\"\n                    className={cn(\"text-[11px] font-medium tabular-nums\", b.total ? \"fill-foreground\" : \"fill-muted-foreground\")}\n                    initial={false}\n                    animate={{ opacity: ready ? 1 : 0 }}\n                    transition={reduce ? { duration: 0 } : { duration: 0.3, delay: delayOf(i) + duration * 0.5 }}\n                  >\n                    {b.total ? fmt(b.to) : signed.format(b.change ?? 0)}\n                  </motion.text>\n                )}\n              </g>\n            ))}\n            {axis &&\n              items.map((s, i) =>\n                showStepLabel(i) ? (\n                  <text key={s.key} x={xOf(i) + thick / 2} y={height - 6} textAnchor=\"middle\" className={cn(\"text-[11px]\", s.total ? \"fill-foreground font-medium\" : \"fill-muted-foreground\")}>\n                    {s.label}\n                  </text>\n                ) : null,\n              )}\n          </svg>\n        )}\n        {width !== null && n === 0 && <div className=\"absolute inset-0 grid place-items-center text-sm text-muted-foreground\">{l.noData}</div>}\n        {act && (\n          <div\n            className=\"pointer-events-none absolute z-10 flex min-w-32 flex-col gap-0.5 rounded-md border bg-popover px-2.5 py-1.5 text-xs whitespace-nowrap text-popover-foreground shadow-[var(--pc-e2)]\"\n            style={{ left: tipX, top: padT, transform: `translateX(${tipRight ? \"calc(-100% - 12px)\" : \"12px\"})` }}\n          >\n            <span className=\"text-muted-foreground\">{act.label}</span>\n            {act.change !== null && (\n              <span className=\"flex items-center gap-1.5 font-semibold tabular-nums\">\n                <span className=\"inline-block size-2 rounded-[2px]\" style={{ background: act.color }} />\n                {signed.format(act.change)}\n              </span>\n            )}\n            <span className=\"flex items-center justify-between gap-3 tabular-nums\">\n              <span className=\"text-muted-foreground\">{l.runningTotal}</span>\n              <span className=\"font-semibold\">{fmt(act.running)}</span>\n            </span>\n          </div>\n        )}\n        <span className=\"sr-only\" aria-live=\"polite\">\n          {announce}\n        </span>\n      </div>\n      {n > 0 && (\n        <div className=\"sr-only\">\n          <table>\n          <caption>{summary}</caption>\n          <thead>\n            <tr>\n              <th scope=\"col\">{l.columnStep}</th>\n              <th scope=\"col\">{l.columnChange}</th>\n              <th scope=\"col\">{l.columnTotal}</th>\n            </tr>\n          </thead>\n          <tbody>\n            {items.map((s) => (\n              <tr key={s.key}>\n                <th scope=\"row\">{s.label}</th>\n                <td>{s.change === null ? \"\" : signed.format(s.change)}</td>\n                <td>{fmt(s.running)}</td>\n              </tr>\n            ))}\n          </tbody>\n        </table>\n        </div>\n      )}\n    </div>\n  )\n}\n",
      "type": "registry:component",
      "target": "components/goodui/waterfall-chart.tsx"
    }
  ],
  "categories": [
    "components",
    "charts"
  ],
  "type": "registry:component"
}