{
  "$schema": "https://ui.shadcn.com/schema/registry-item.json",
  "name": "waterfall-chart",
  "type": "registry:component",
  "title": "Waterfall Chart",
  "description": "How a starting amount becomes an ending one, step by step: each rise or fall a bar floating from the running total, totals standing on the baseline, signs printed on every step so rises and falls never rest on colour.",
  "categories": [
    "viz"
  ],
  "dependencies": [
    "d3-scale"
  ],
  "devDependencies": [
    "@types/d3-scale"
  ],
  "registryDependencies": [
    "@rivier-ui/theme",
    "@rivier-ui/chart",
    "@rivier-ui/cn"
  ],
  "files": [
    {
      "path": "registry/viz/waterfall-chart.tsx",
      "type": "registry:component",
      "target": "components/viz/waterfall-chart.tsx",
      "content": "\"use client\";\n/**\n * @name waterfall-chart\n * @category viz\n * @description How a starting amount becomes an ending one, step by step: each rise or fall a bar floating from the running total, totals standing on the baseline, signs printed on every step so rises and falls never rest on colour.\n * @when Explaining a change between two totals: a budget's start to its end, revenue to profit, last year to this year by cause. For parts of one total use bar-chart stacked or treemap; for change over time use line-chart.\n * @example\n * <WaterfallChart\n *   label=\"From revenue to profit\"\n *   data={[\n *     { step: \"Revenue\", amount: 500, total: true },\n *     { step: \"Costs\", amount: -220 },\n *     { step: \"Marketing\", amount: -80 },\n *     { step: \"Other income\", amount: 30 },\n *     { step: \"Profit\", amount: 230, total: true },\n *   ]}\n *   x=\"step\"\n *   value=\"amount\"\n *   total=\"total\"\n * />\n */\nimport { scaleBand } from \"d3-scale\";\nimport { useMemo } from \"react\";\nimport { cn } from \"@/lib/cn\";\nimport {\n  axisNumberFormatter,\n  ChartAxis,\n  ChartContainer,\n  ChartEmpty,\n  ChartGrid,\n  chartLinear,\n  ChartSvg,\n  ChartTooltip,\n  fitText,\n  formatNumber,\n  readNumber,\n  useChartCursor,\n  widestText,\n  type ChartBaseProps,\n} from \"@/components/viz/chart\";\n\nexport type WaterfallChartLabels = { step: string; change: string; runningTotal: string; rise: string; fall: string; total: string };\n\nexport type WaterfallChartProps<T extends object> = ChartBaseProps & {\n  /** One object per step, in order. */\n  data: readonly T[];\n  /** The field naming each step. */\n  x: keyof T & string;\n  /** The field holding the step's change (or, on a total row, the total). */\n  value: keyof T & string;\n  /** A field that is true on rows that are totals: drawn from zero, and the running total is set to them. */\n  total?: keyof T & string;\n  /** Print each step's change above or below its bar where it fits. Default true. */\n  showValues?: boolean;\n  labels?: Partial<WaterfallChartLabels>;\n};\n\nconst LABELS: WaterfallChartLabels = { step: \"Step\", change: \"Change\", runningTotal: \"Running total\", rise: \"Rise\", fall: \"Fall\", total: \"Total\" };\nconst ROUND = \"[rx:min(var(--radius),3px)] [ry:min(var(--radius),3px)]\";\n\ntype Step = { name: string; change: number; from: number; to: number; kind: \"rise\" | \"fall\" | \"total\" };\n\nexport function WaterfallChart<T extends object>({\n  data,\n  x,\n  value,\n  total,\n  showValues = true,\n  labels: given,\n  label,\n  aspect,\n  height,\n  emptyLabel,\n  locale,\n  formatValue,\n  className,\n  ...props\n}: WaterfallChartProps<T>) {\n  const labels = { ...LABELS, ...given };\n  const steps = useMemo(() => {\n    let running = 0;\n    const out: Step[] = [];\n    for (const row of data) {\n      const amount = readNumber(row, value);\n      if (amount === null) continue;\n      const name = String((row as Record<string, unknown>)[x] ?? \"\");\n      if (total && (row as Record<string, unknown>)[total] === true) {\n        running = amount;\n        out.push({ name, change: amount, from: 0, to: amount, kind: \"total\" });\n      } else {\n        out.push({ name, change: amount, from: running, to: running + amount, kind: amount >= 0 ? \"rise\" : \"fall\" });\n        running += amount;\n      }\n    }\n    return out;\n  }, [data, x, value, total]);\n  const cursor = useChartCursor(steps.length);\n  const number = formatValue ?? ((amount: number) => formatNumber(amount, locale));\n  const signed = (amount: number, kind: Step[\"kind\"]): string =>\n    kind === \"total\" ? number(amount) : formatValue ? formatValue(amount) : formatNumber(amount, locale, { signDisplay: \"exceptZero\", maximumFractionDigits: 2 });\n  const kindWord = (kind: Step[\"kind\"]): string => labels[kind];\n  const table = {\n    caption: label,\n    columns: [labels.step, labels.change, labels.runningTotal],\n    rows: steps.map((step) => [step.name, `${signed(step.change, step.kind)} (${kindWord(step.kind)})`, number(step.to)]),\n  };\n  const current = cursor.active === null ? undefined : steps[cursor.active];\n\n  return (\n    <div data-slot=\"waterfall-chart\" className={cn(\"flex w-full min-w-0 flex-col gap-3\", className)} {...props}>\n      <ChartContainer\n        aspect={aspect}\n        height={height}\n        table={table}\n        announcement={cursor.keyboard && current ? `${current.name}: ${kindWord(current.kind)} ${signed(current.change, current.kind)}, ${labels.runningTotal} ${number(current.to)}` : \"\"}\n      >\n        {({ width, height: plotHeight }) => {\n          if (steps.length === 0) return <ChartEmpty>{emptyLabel}</ChartEmpty>;\n          const top = showValues ? 22 : 10;\n          const bottom = 28;\n          const ends = steps.flatMap((step) => [step.from, step.to]);\n          const sy = chartLinear(Math.min(0, ...ends), Math.max(0, ...ends), [plotHeight - bottom, top]);\n          const axisY = formatValue ?? axisNumberFormatter(Math.max(...ends.map(Math.abs)), locale);\n          const left = widestText(sy.ticks.map(axisY)) + 12;\n          const band = scaleBand<number>()\n            .domain(steps.map((_, i) => i))\n            .range([left, width - 4])\n            .paddingInner(0.25)\n            .paddingOuter(0.1);\n          const w = Math.min(48, band.bandwidth());\n          const xOf = (index: number): number => (band(index) ?? 0) + (band.bandwidth() - w) / 2;\n          const every = Math.max(1, Math.ceil((widestText(steps.map((s) => s.name)) + 8) / band.step()));\n          return (\n            <>\n              <ChartSvg label={label} width={width} height={plotHeight} interactive {...cursor.svgProps}>\n                <ChartGrid offsets={sy.ticks.map((tick) => sy.scale(tick))} from={left} to={width - 4} />\n                <ChartAxis side=\"left\" at={left - 8} ticks={sy.ticks.map((tick) => ({ offset: sy.scale(tick), label: axisY(tick) }))} />\n                <ChartAxis\n                  side=\"bottom\"\n                  at={plotHeight - bottom + 6}\n                  ticks={steps.flatMap((step, i) => (i % every === 0 ? [{ offset: (band(i) ?? 0) + band.bandwidth() / 2, label: fitText(step.name, band.step() * every - 4) }] : []))}\n                />\n                <g aria-hidden=\"true\">\n                  {steps.map((step, i) => {\n                    const y0 = sy.scale(step.from);\n                    const y1 = sy.scale(step.to);\n                    const next = steps[i + 1];\n                    const fill = step.kind === \"total\" ? \"fill-foreground\" : step.kind === \"rise\" ? \"fill-chart-3\" : \"fill-chart-2\";\n                    const labelY = step.change >= 0 ? Math.min(y0, y1) - 6 : Math.max(y0, y1) + 14;\n                    return (\n                      <g\n                        key={i}\n                        onPointerEnter={() => cursor.point(i)}\n                        className={cn(\"transition-opacity duration-instant motion-reduce:transition-none\", cursor.active !== null && cursor.active !== i && \"opacity-45\")}\n                      >\n                        <rect x={band(i) ?? 0} y={top} width={band.bandwidth()} height={plotHeight - bottom - top} fill=\"transparent\" />\n                        <rect x={xOf(i)} y={Math.min(y0, y1)} width={w} height={Math.max(1, Math.abs(y1 - y0))} className={cn(fill, ROUND)} fillOpacity={step.kind === \"total\" ? 0.8 : 1} />\n                        {next && next.kind !== \"total\" ? <line x1={xOf(i) + w} x2={xOf(i + 1)} y1={y1} y2={y1} className=\"stroke-muted-foreground\" strokeDasharray=\"2 2\" /> : null}\n                        {showValues && w >= 24 ? (\n                          <text x={xOf(i) + w / 2} y={labelY} textAnchor=\"middle\" className=\"fill-foreground text-xs tabular-nums\">\n                            {signed(step.change, step.kind)}\n                          </text>\n                        ) : null}\n                      </g>\n                    );\n                  })}\n                  <line x1={left} x2={width - 4} y1={sy.scale(0)} y2={sy.scale(0)} className=\"stroke-border-strong\" shapeRendering=\"crispEdges\" />\n                </g>\n              </ChartSvg>\n              {current && cursor.active !== null ? (\n                <ChartTooltip\n                  x={xOf(cursor.active) + w / 2}\n                  y={sy.scale(Math.max(current.from, current.to))}\n                  side={xOf(cursor.active) > width / 2 ? \"left\" : \"right\"}\n                  title={current.name}\n                  rows={[\n                    { label: kindWord(current.kind), value: signed(current.change, current.kind) },\n                    { label: labels.runningTotal, value: number(current.to) },\n                  ]}\n                />\n              ) : null}\n            </>\n          );\n        }}\n      </ChartContainer>\n    </div>\n  );\n}\n"
    }
  ],
  "meta": {
    "category": "viz",
    "when": "Explaining a change between two totals: a budget's start to its end, revenue to profit, last year to this year by cause. For parts of one total use bar-chart stacked or treemap; for change over time use line-chart.",
    "example": "<WaterfallChart\n  label=\"From revenue to profit\"\n  data={[\n    { step: \"Revenue\", amount: 500, total: true },\n    { step: \"Costs\", amount: -220 },\n    { step: \"Marketing\", amount: -80 },\n    { step: \"Other income\", amount: 30 },\n    { step: \"Profit\", amount: 230, total: true },\n  ]}\n  x=\"step\"\n  value=\"amount\"\n  total=\"total\"\n/>",
    "client": true
  }
}
