{
  "$schema": "https://ui.shadcn.com/schema/registry-item.json",
  "name": "waterfall-chart",
  "type": "registry:component",
  "title": "Waterfall chart",
  "description": "A bridge chart that walks from an opening total through each increase and decrease to the closing total, with a crosshair readout per step.",
  "categories": [
    "charts"
  ],
  "dependencies": [],
  "registryDependencies": [],
  "files": [
    {
      "path": "src/registry/overtrue/waterfall-chart.tsx",
      "type": "registry:component",
      "target": "components/overtrue/waterfall-chart.tsx",
      "content": "\"use client\";\n\nimport * as React from \"react\";\n\nimport { cn } from \"@/lib/utils\";\n\n/**\n * start sets the running total, delta moves it, subtotal and end show it.\n * Defaults to \"delta\".\n */\nexport type WaterfallStepKind = \"start\" | \"delta\" | \"subtotal\" | \"end\";\n\nexport interface WaterfallStep {\n  id: string;\n  label: string;\n  /**\n   * The opening amount for a start step, or the signed change for a delta.\n   * Subtotal and end steps always show the running total, so the bridge balances.\n   */\n  value: number;\n  kind?: WaterfallStepKind;\n}\n\nexport type WaterfallDirection = \"increase\" | \"decrease\" | \"total\";\n\n/** Where a value is shown: bar labels, axis ticks, or the tooltip and table. */\nexport type WaterfallFormatContext = \"label\" | \"axis\" | \"detail\";\n\nexport interface WaterfallStepInfo {\n  index: number;\n  kind: WaterfallStepKind;\n  direction: WaterfallDirection;\n  /** Signed change for a delta; the total for start, subtotal and end. */\n  change: number;\n  /** Running total before and after the step. Totals run from 0. */\n  from: number;\n  to: number;\n  /** The change with its sign, or the total, formatted for the tooltip. */\n  formattedChange: string;\n  /** The running total after the step, formatted for the tooltip. */\n  formattedTotal: string;\n  /** Change relative to the opening total, when there is one. */\n  shareOfStart: number | null;\n  /** The bar color. */\n  color: string;\n}\n\nexport interface WaterfallChartColors {\n  /** Any CSS color. Defaults to emerald. */\n  increase?: string;\n  /** Any CSS color. Defaults to the destructive color. */\n  decrease?: string;\n  /** Any CSS color for start, subtotal and end bars. Defaults to the primary color. */\n  total?: string;\n}\n\nexport type WaterfallOrientation = \"vertical\" | \"horizontal\" | \"auto\";\n\n/** The figures behind the summary line, passed to `renderSummary`. */\nexport interface WaterfallTotals {\n  /** The first start step's value, or null when the bridge has no start. */\n  opening: number | null;\n  /** The running total after the last step. */\n  closing: number;\n  /** closing − opening, or null without an opening total. */\n  net: number | null;\n  /** net as a share of the opening total, or null. */\n  netShare: number | null;\n  /** The chart's formatter, with a leading − for negative values. */\n  format: (value: number, context: WaterfallFormatContext) => string;\n}\n\nexport interface WaterfallChartProps extends Omit<\n  React.ComponentProps<\"div\">,\n  \"title\" | \"onSelect\" | \"children\"\n> {\n  steps: WaterfallStep[];\n  /**\n   * Columns, rows, or \"auto\": columns when the card is wide enough for every step\n   * and rows below that, switched with a container query. Defaults to \"auto\".\n   */\n  orientation?: WaterfallOrientation;\n  /**\n   * Formats an amount. It always receives a non-negative number; the chart adds\n   * + and − itself. Defaults to compact numbers, and grouped digits in the tooltip.\n   */\n  valueFormatter?: (value: number, context: WaterfallFormatContext) => string;\n  title?: React.ReactNode;\n  description?: React.ReactNode;\n  /** Controls placed at the top right. */\n  actions?: React.ReactNode;\n  /** Plot height in pixels for columns. Rows size themselves. Defaults to 280. */\n  height?: number;\n  colors?: WaterfallChartColors;\n  /**\n   * \"auto\" starts the value axis just below the lowest running total when every\n   * total is far from zero, and marks the cut on total bars. \"zero\" always starts at 0.\n   */\n  baseline?: \"auto\" | \"zero\";\n  /** Show the closing total and net change under the title. Defaults to true. */\n  showSummary?: boolean;\n  /** Replace the summary line, e.g. to show a margin instead of the net change. */\n  renderSummary?: (totals: WaterfallTotals) => React.ReactNode;\n  /** Show the increase, decrease and total key. Defaults to true. */\n  showLegend?: boolean;\n  /** Replace the tooltip content for a hovered or focused step. */\n  renderTooltip?: (\n    step: WaterfallStep,\n    info: WaterfallStepInfo,\n  ) => React.ReactNode;\n  /** Called when a step is clicked or activated with Enter. */\n  onSelect?: (step: WaterfallStep, info: WaterfallStepInfo) => void;\n}\n\ninterface Row {\n  step: WaterfallStep;\n  info: WaterfallStepInfo;\n  /** Ends of the bar in data units, low to high. */\n  low: number;\n  high: number;\n  /** Whether the bar is cut by a raised baseline. */\n  cut: boolean;\n  /** Whether a connector runs from this bar to the next one. */\n  connects: boolean;\n}\n\nconst MINUS = \"−\";\nconst compactNumber = new Intl.NumberFormat(\"en-US\", {\n  notation: \"compact\",\n  maximumFractionDigits: 1,\n});\nconst exactNumber = new Intl.NumberFormat(\"en-US\", {\n  maximumFractionDigits: 2,\n});\nconst sharePercent = new Intl.NumberFormat(\"en-US\", {\n  style: \"percent\",\n  maximumFractionDigits: 1,\n  signDisplay: \"exceptZero\",\n});\n\nfunction defaultFormatter(value: number, context: WaterfallFormatContext) {\n  return context === \"detail\"\n    ? exactNumber.format(value)\n    : compactNumber.format(value);\n}\n\nconst DEFAULT_INCREASE = \"var(--color-emerald-500, oklch(69.6% 0.17 162.48))\";\nconst DEFAULT_DECREASE = \"var(--color-destructive)\";\nconst DEFAULT_TOTAL = \"var(--color-primary)\";\n\n/** Container widths where columns take over from rows, by step count. */\nconst AUTO_SWITCH = [\n  {\n    upTo: 4,\n    columns: \"hidden @min-[20rem]/waterfall:block\",\n    rows: \"@min-[20rem]/waterfall:hidden\",\n  },\n  {\n    upTo: 5,\n    columns: \"hidden @min-[24rem]/waterfall:block\",\n    rows: \"@min-[24rem]/waterfall:hidden\",\n  },\n  {\n    upTo: 6,\n    columns: \"hidden @min-[28rem]/waterfall:block\",\n    rows: \"@min-[28rem]/waterfall:hidden\",\n  },\n  {\n    upTo: 7,\n    columns: \"hidden @min-[32rem]/waterfall:block\",\n    rows: \"@min-[32rem]/waterfall:hidden\",\n  },\n  {\n    upTo: 8,\n    columns: \"hidden @min-[36rem]/waterfall:block\",\n    rows: \"@min-[36rem]/waterfall:hidden\",\n  },\n  {\n    upTo: 10,\n    columns: \"hidden @min-[44rem]/waterfall:block\",\n    rows: \"@min-[44rem]/waterfall:hidden\",\n  },\n  {\n    upTo: Infinity,\n    columns: \"hidden @min-[54rem]/waterfall:block\",\n    rows: \"@min-[54rem]/waterfall:hidden\",\n  },\n];\n\nconst kindLabel: Record<WaterfallStepKind, string> = {\n  start: \"Opening total\",\n  delta: \"Change\",\n  subtotal: \"Subtotal\",\n  end: \"Closing total\",\n};\n\nconst finite = (value: number) => (Number.isFinite(value) ? value : 0);\n\nfunction niceStep(span: number, count: number) {\n  const raw = span / Math.max(1, count);\n  if (!(raw > 0)) return 1;\n  const magnitude = 10 ** Math.floor(Math.log10(raw));\n  const step = [1, 2, 2.5, 5, 10].find((n) => raw <= n * magnitude) ?? 10;\n  return step * magnitude;\n}\n\n/**\n * The visible range and its ticks. With a raised baseline the range starts a little\n * below the lowest running total so the changes, not the totals, fill the plot.\n */\nfunction scaleFor(\n  rows: Omit<Row, \"cut\" | \"connects\">[],\n  baseline: \"auto\" | \"zero\",\n) {\n  let low = Infinity;\n  let high = -Infinity;\n  let totalLow = Infinity;\n  for (const row of rows) {\n    if (row.info.direction === \"total\") {\n      totalLow = Math.min(totalLow, row.info.to);\n      low = Math.min(low, row.info.to);\n      high = Math.max(high, row.info.to);\n    } else {\n      low = Math.min(low, row.low);\n      high = Math.max(high, row.high);\n    }\n  }\n  if (!Number.isFinite(low))\n    return { min: 0, max: 1, ticks: [0, 1], raised: false };\n  let min = Math.min(0, low);\n  let max = Math.max(0, high);\n  let raised = false;\n  if (baseline === \"auto\" && low > 0 && totalLow > 0 && low / high > 0.35) {\n    // Leave room under the lowest total so short bars still read as bars.\n    min = Math.max(0, low - (high - low) * 0.55);\n    raised = true;\n  }\n  const step = niceStep(max - min, 4);\n  const start = Math.floor(min / step) * step;\n  const end = Math.ceil(max / step) * step || step;\n  const ticks: number[] = [];\n  for (let tick = start; tick <= end + step / 2; tick += step)\n    ticks.push(Math.round(tick / step) * step);\n  return { min: start, max: end, ticks, raised: raised && start > 0 };\n}\n\nconst reveal =\n  \"motion-safe:animate-[waterfall-rise_620ms_cubic-bezier(0.22,1,0.36,1)_backwards]\";\nconst fadeUp =\n  \"motion-safe:animate-[waterfall-fade_420ms_cubic-bezier(0.22,1,0.36,1)_backwards]\";\nconst draw =\n  \"motion-safe:animate-[waterfall-draw_360ms_cubic-bezier(0.22,1,0.36,1)_backwards]\";\n\n/** Two short card-colored strokes across a bar whose bottom is cut by a raised axis. */\nfunction CutMark({ horizontal }: { horizontal?: boolean }) {\n  return (\n    <svg\n      aria-hidden=\"true\"\n      viewBox=\"0 0 10 10\"\n      preserveAspectRatio=\"none\"\n      className={cn(\n        \"pointer-events-none absolute\",\n        horizontal\n          ? \"inset-y-0 left-1.5 h-full w-2\"\n          : \"inset-x-0 bottom-1.5 h-2 w-full\",\n      )}\n    >\n      {horizontal ? (\n        <>\n          <path\n            d=\"M3 0 L1 10\"\n            stroke=\"var(--color-card)\"\n            strokeWidth=\"1.5\"\n            vectorEffect=\"non-scaling-stroke\"\n          />\n          <path\n            d=\"M8 0 L6 10\"\n            stroke=\"var(--color-card)\"\n            strokeWidth=\"1.5\"\n            vectorEffect=\"non-scaling-stroke\"\n          />\n        </>\n      ) : (\n        <>\n          <path\n            d=\"M0 4 L10 2\"\n            stroke=\"var(--color-card)\"\n            strokeWidth=\"1.5\"\n            vectorEffect=\"non-scaling-stroke\"\n          />\n          <path\n            d=\"M0 9 L10 7\"\n            stroke=\"var(--color-card)\"\n            strokeWidth=\"1.5\"\n            vectorEffect=\"non-scaling-stroke\"\n          />\n        </>\n      )}\n    </svg>\n  );\n}\n\n/**\n * A waterfall (bridge) chart: an opening total, the changes that move it, optional\n * subtotals, and the closing total. Bars rise in sequence on mount; hover or focus a\n * step for a crosshair at its running total and a readout of the change.\n */\nfunction WaterfallChart({\n  steps,\n  orientation = \"auto\",\n  valueFormatter = defaultFormatter,\n  title,\n  description,\n  actions,\n  height = 280,\n  colors,\n  baseline = \"auto\",\n  showSummary = true,\n  showLegend = true,\n  renderSummary,\n  renderTooltip,\n  onSelect,\n  className,\n  ...props\n}: WaterfallChartProps) {\n  const [hovered, setHovered] = React.useState<number | null>(null);\n  const [focused, setFocused] = React.useState<number | null>(null);\n  const [cursor, setCursor] = React.useState(0);\n\n  const increase = colors?.increase ?? DEFAULT_INCREASE;\n  const decrease = colors?.decrease ?? DEFAULT_DECREASE;\n  const total = colors?.total ?? DEFAULT_TOTAL;\n  const subtotalFill = `color-mix(in oklab, ${total} 52%, var(--color-card))`;\n\n  const format = React.useCallback(\n    (value: number, context: WaterfallFormatContext) =>\n      `${value < 0 ? MINUS : \"\"}${valueFormatter(Math.abs(value), context)}`,\n    [valueFormatter],\n  );\n  const signed = React.useCallback(\n    (value: number, context: WaterfallFormatContext) =>\n      `${value < 0 ? MINUS : \"+\"}${valueFormatter(Math.abs(value), context)}`,\n    [valueFormatter],\n  );\n\n  const { rows, scale, opening, closing } = React.useMemo(() => {\n    let running = 0;\n    let opening: number | null = null;\n    const base = steps.map((step, index) => {\n      const kind = step.kind ?? \"delta\";\n      const value = finite(step.value);\n      let from = 0;\n      let to = 0;\n      if (kind === \"start\") {\n        to = value;\n        running = value;\n        if (opening == null) opening = value;\n      } else if (kind === \"delta\") {\n        from = running;\n        to = running + value;\n        running = to;\n      } else {\n        to = running;\n      }\n      const direction: WaterfallDirection =\n        kind === \"delta\" ? (value < 0 ? \"decrease\" : \"increase\") : \"total\";\n      const change = kind === \"delta\" ? value : to;\n      const color =\n        direction === \"increase\"\n          ? increase\n          : direction === \"decrease\"\n            ? decrease\n            : kind === \"subtotal\"\n              ? subtotalFill\n              : total;\n      const info: WaterfallStepInfo = {\n        index,\n        kind,\n        direction,\n        change,\n        from,\n        to,\n        formattedChange:\n          kind === \"delta\"\n            ? signed(change, \"detail\")\n            : format(change, \"detail\"),\n        formattedTotal: format(to, \"detail\"),\n        shareOfStart:\n          opening && kind === \"delta\"\n            ? change / opening\n            : opening && kind !== \"start\"\n              ? (to - opening) / opening\n              : null,\n        color,\n      };\n      return {\n        step,\n        info,\n        low: Math.min(from, to),\n        high: Math.max(from, to),\n      };\n    });\n    const scale = scaleFor(base, baseline);\n    const rows: Row[] = base.map((row, index) => {\n      const next = base[index + 1];\n      return {\n        ...row,\n        cut: row.info.direction === \"total\" && scale.raised,\n        connects: next != null && next.info.kind !== \"start\",\n      };\n    });\n    const closing = base.length ? base[base.length - 1].info.to : 0;\n    return { rows, scale, opening, closing };\n  }, [\n    steps,\n    baseline,\n    increase,\n    decrease,\n    total,\n    subtotalFill,\n    format,\n    signed,\n  ]);\n\n  const span = scale.max - scale.min || 1;\n  /** Distance from the low end of the axis, as a percentage. */\n  const position = (value: number) =>\n    ((Math.min(scale.max, Math.max(scale.min, value)) - scale.min) / span) *\n    100;\n\n  const active = hovered ?? focused;\n  const activeRow = active != null ? rows[active] : null;\n  const count = rows.length;\n  const auto = AUTO_SWITCH.find((entry) => count <= entry.upTo)!;\n  const net = opening != null ? closing - opening : null;\n\n  const largest = (direction: WaterfallDirection) =>\n    rows\n      .filter((row) => row.info.direction === direction)\n      .sort((a, b) => Math.abs(b.info.change) - Math.abs(a.info.change))[0];\n  const topIncrease = largest(\"increase\");\n  const topDecrease = largest(\"decrease\");\n  const titleText = typeof title === \"string\" ? title : \"Waterfall chart\";\n  const summary = [\n    `${titleText}.`,\n    opening != null ? `Starts at ${format(opening, \"detail\")}` : null,\n    count ? `ends at ${format(closing, \"detail\")}` : null,\n    net != null && opening\n      ? `(${signed(net, \"detail\")}, ${sharePercent.format(net / opening)}).`\n      : null,\n    topIncrease\n      ? `Largest increase: ${topIncrease.step.label}, ${topIncrease.info.formattedChange}.`\n      : null,\n    topDecrease\n      ? `Largest decrease: ${topDecrease.step.label}, ${topDecrease.info.formattedChange}.`\n      : null,\n  ]\n    .filter(Boolean)\n    .join(\" \");\n\n  const select = (index: number) => {\n    const row = rows[index];\n    if (row && onSelect) onSelect(row.step, row.info);\n  };\n\n  const onKeyDown = (event: React.KeyboardEvent<HTMLDivElement>) => {\n    const keys: Record<string, number> = {\n      ArrowRight: 1,\n      ArrowDown: 1,\n      ArrowLeft: -1,\n      ArrowUp: -1,\n    };\n    let next: number | null = null;\n    if (event.key in keys) next = (focused ?? cursor) + keys[event.key];\n    else if (event.key === \"Home\") next = 0;\n    else if (event.key === \"End\") next = count - 1;\n    else if ((event.key === \"Enter\" || event.key === \" \") && focused != null) {\n      event.preventDefault();\n      select(focused);\n      return;\n    } else if (event.key === \"Escape\") {\n      setFocused(null);\n      return;\n    }\n    if (next == null || !count) return;\n    event.preventDefault();\n    const clamped = Math.min(count - 1, Math.max(0, next));\n    setCursor(clamped);\n    setFocused(clamped);\n    setHovered(null);\n  };\n\n  const plotProps = (label: string) => ({\n    role: \"img\" as const,\n    tabIndex: count ? 0 : -1,\n    \"aria-label\": `${label} Use the arrow keys to read each step.`,\n    \"aria-roledescription\": \"waterfall chart\",\n    onKeyDown,\n    onFocus: (event: React.FocusEvent<HTMLDivElement>) => {\n      if (\n        event.target === event.currentTarget &&\n        event.currentTarget.matches(\":focus-visible\")\n      )\n        setFocused(cursor);\n    },\n    onBlur: () => setFocused(null),\n    onPointerLeave: () => setHovered(null),\n  });\n\n  const valueText = (row: Row) =>\n    row.info.kind === \"delta\"\n      ? signed(row.info.change, \"label\")\n      : format(row.info.to, \"label\");\n\n  const valueTone = (row: Row) => {\n    if (row.info.direction === \"total\") return \"text-foreground font-semibold\";\n    if (row.info.direction === \"increase\")\n      return colors?.increase ? \"\" : \"text-emerald-700 dark:text-emerald-400\";\n    return colors?.decrease ? \"\" : \"text-rose-600 dark:text-rose-400\";\n  };\n  const valueStyle = (row: Row): React.CSSProperties | undefined =>\n    row.info.direction === \"increase\" && colors?.increase\n      ? { color: colors.increase }\n      : row.info.direction === \"decrease\" && colors?.decrease\n        ? { color: colors.decrease }\n        : undefined;\n\n  const tooltip = (row: Row) =>\n    renderTooltip ? (\n      renderTooltip(row.step, row.info)\n    ) : (\n      <div className=\"flex min-w-36 flex-col gap-1.5\">\n        <div className=\"flex items-center gap-1.5 text-muted-foreground\">\n          <span\n            className=\"h-2.5 w-[3px] shrink-0 rounded-full\"\n            style={{ backgroundColor: row.info.color }}\n          />\n          <span className=\"truncate\">{row.step.label}</span>\n        </div>\n        <div className=\"text-sm leading-none font-semibold tracking-tight whitespace-nowrap tabular-nums\">\n          {row.info.formattedChange}\n          {row.info.shareOfStart != null ? (\n            <span className=\"ml-1.5 font-mono text-[10.5px] font-normal text-muted-foreground\">\n              {sharePercent.format(row.info.shareOfStart)}\n            </span>\n          ) : null}\n        </div>\n        {row.info.kind === \"delta\" ? (\n          <div className=\"flex items-baseline justify-between gap-4 border-t pt-1.5 whitespace-nowrap text-muted-foreground tabular-nums\">\n            <span>Running total</span>\n            <span className=\"font-medium text-foreground\">\n              {row.info.formattedTotal}\n            </span>\n          </div>\n        ) : null}\n      </div>\n    );\n\n  const crosshairValue = activeRow ? activeRow.info.to : null;\n\n  const columns = (\n    <div\n      data-slot=\"waterfall-chart-columns\"\n      className={cn(\n        \"px-4 pt-3 pb-3\",\n        orientation === \"auto\"\n          ? auto.columns\n          : orientation === \"vertical\"\n            ? \"block\"\n            : \"hidden\",\n      )}\n    >\n      <div\n        {...plotProps(summary)}\n        data-slot=\"waterfall-chart-plot\"\n        className=\"group/plot relative rounded-md outline-none focus-visible:ring-2 focus-visible:ring-ring/50 focus-visible:ring-offset-4 focus-visible:ring-offset-card\"\n      >\n        <div className=\"relative\" style={{ height }}>\n          {/* Axis and gridlines. */}\n          <div\n            aria-hidden=\"true\"\n            data-slot=\"waterfall-chart-axis\"\n            className=\"absolute inset-x-0 top-6 bottom-6\"\n          >\n            {scale.ticks.map((tick) => (\n              <div\n                key={tick}\n                className=\"absolute inset-x-0 flex items-center\"\n                style={{\n                  bottom: `${position(tick)}%`,\n                  transform: \"translateY(50%)\",\n                }}\n              >\n                <span className=\"w-11 shrink-0 pr-2 text-right font-mono text-[10.5px] leading-none text-muted-foreground tabular-nums\">\n                  {format(tick, \"axis\")}\n                </span>\n                <span\n                  className={cn(\n                    \"h-px flex-1\",\n                    tick === 0 ? \"bg-foreground/25\" : \"bg-border\",\n                  )}\n                />\n              </div>\n            ))}\n            {crosshairValue != null ? (\n              <div\n                data-slot=\"waterfall-chart-crosshair\"\n                className=\"pointer-events-none absolute inset-x-0 z-10 flex items-center\"\n                style={{\n                  bottom: `${position(crosshairValue)}%`,\n                  transform: \"translateY(50%)\",\n                }}\n              >\n                <span className=\"flex w-11 shrink-0 justify-end pr-1\">\n                  <span className=\"rounded-[4px] bg-foreground px-1 py-0.5 font-mono text-[10px] leading-none text-background tabular-nums\">\n                    {format(crosshairValue, \"axis\")}\n                  </span>\n                </span>\n                <span className=\"h-px flex-1 bg-foreground/45\" />\n              </div>\n            ) : null}\n          </div>\n\n          {/* Bars. */}\n          <div\n            className=\"absolute inset-y-0 right-0 left-11 grid\"\n            style={{\n              gridTemplateColumns: `repeat(${Math.max(1, count)}, minmax(0, 1fr))`,\n            }}\n          >\n            {rows.map((row, index) => {\n              const isActive = active === index;\n              const dimmed = active != null && !isActive;\n              const bottom = position(row.low);\n              const top = position(row.high);\n              const delay = 120 + index * 85;\n              // Decreases and negative totals hang from their top edge.\n              const falling =\n                row.info.direction === \"decrease\" ||\n                (row.info.direction === \"total\" && row.info.to < 0);\n              return (\n                <div\n                  key={row.step.id}\n                  data-slot=\"waterfall-chart-step\"\n                  data-direction={row.info.direction}\n                  data-active={isActive || undefined}\n                  className={cn(\"relative\", onSelect && \"cursor-pointer\")}\n                  onPointerEnter={() => setHovered(index)}\n                  onClick={onSelect ? () => select(index) : undefined}\n                >\n                  <div\n                    aria-hidden=\"true\"\n                    className={cn(\n                      \"absolute inset-x-[8%] inset-y-0 rounded-md bg-foreground/[0.045] opacity-0 transition-opacity duration-150 motion-reduce:transition-none\",\n                      isActive && \"opacity-100\",\n                    )}\n                  />\n                  <div className=\"absolute inset-x-0 top-6 bottom-6\">\n                    <div\n                      data-slot=\"waterfall-chart-bar\"\n                      className={cn(\n                        \"absolute left-1/2 w-[min(34px,58%)] -translate-x-1/2 transition-[opacity,bottom,height] duration-300 motion-reduce:transition-none\",\n                        row.info.direction === \"total\"\n                          ? \"rounded-t-[4px]\"\n                          : \"rounded-[3px]\",\n                        row.info.direction === \"total\" &&\n                          row.low < 0 &&\n                          \"rounded-t-none rounded-b-[4px]\",\n                        dimmed && \"opacity-45\",\n                      )}\n                      style={{\n                        bottom: `${bottom}%`,\n                        height: `max(2px, ${top - bottom}%)`,\n                      }}\n                    >\n                      <div\n                        className={cn(\n                          \"absolute inset-0 rounded-[inherit]\",\n                          reveal,\n                        )}\n                        style={{\n                          backgroundColor: row.info.color,\n                          transformOrigin: falling ? \"top\" : \"bottom\",\n                          animationDelay: `${delay}ms`,\n                        }}\n                      />\n                      {row.cut ? <CutMark /> : null}\n                    </div>\n                    <span\n                      data-slot=\"waterfall-chart-value\"\n                      className={cn(\n                        \"absolute inset-x-0 text-center text-[11px] leading-none whitespace-nowrap tabular-nums transition-opacity duration-150 motion-reduce:transition-none\",\n                        valueTone(row),\n                        fadeUp,\n                        dimmed && \"opacity-50\",\n                      )}\n                      style={{\n                        ...valueStyle(row),\n                        ...(falling\n                          ? { top: `calc(${100 - bottom}% + 6px)` }\n                          : { bottom: `calc(${top}% + 6px)` }),\n                        animationDelay: `${delay + 300}ms`,\n                      }}\n                    >\n                      {valueText(row)}\n                    </span>\n                    {row.connects ? (\n                      <span\n                        aria-hidden=\"true\"\n                        data-slot=\"waterfall-chart-connector\"\n                        className={cn(\n                          \"absolute left-[calc(50%+min(17px,29%))] h-px w-[calc(100%-min(34px,58%))] origin-left bg-foreground/35\",\n                          draw,\n                        )}\n                        style={{\n                          bottom: `${position(row.info.to)}%`,\n                          animationDelay: `${delay + 380}ms`,\n                        }}\n                      />\n                    ) : null}\n                  </div>\n                  {isActive ? (\n                    <div\n                      data-slot=\"waterfall-chart-tooltip\"\n                      className=\"pointer-events-none absolute z-30 rounded-lg border bg-popover px-3 py-2 text-xs whitespace-nowrap text-popover-foreground shadow-lg shadow-black/5\"\n                      style={{\n                        // Beside the bar, level with its top, kept inside the plot.\n                        top: Math.max(\n                          0,\n                          Math.min(\n                            24 + ((100 - top) / 100) * (height - 48) - 6,\n                            height - 88,\n                          ),\n                        ),\n                        [index < count / 2 ? \"left\" : \"right\"]:\n                          \"calc(50% + min(17px, 29%) + 10px)\",\n                      }}\n                    >\n                      {tooltip(row)}\n                    </div>\n                  ) : null}\n                </div>\n              );\n            })}\n          </div>\n        </div>\n\n        {/* Step labels. */}\n        <div\n          aria-hidden=\"true\"\n          className=\"grid pl-11\"\n          style={{\n            gridTemplateColumns: `repeat(${Math.max(1, count)}, minmax(0, 1fr))`,\n          }}\n        >\n          {rows.map((row, index) => (\n            <span\n              key={row.step.id}\n              data-slot=\"waterfall-chart-label\"\n              className={cn(\n                \"line-clamp-2 px-0.5 pt-1 text-center text-[11px] leading-[14px] transition-colors motion-reduce:transition-none\",\n                row.info.direction === \"total\"\n                  ? \"font-medium text-foreground\"\n                  : \"text-muted-foreground\",\n                active === index && \"text-foreground\",\n              )}\n            >\n              {row.step.label}\n            </span>\n          ))}\n        </div>\n      </div>\n    </div>\n  );\n\n  // Below 26rem the value moves under its label so the track keeps most of the width.\n  const rowsView = (\n    <div\n      data-slot=\"waterfall-chart-rows\"\n      className={cn(\n        \"px-4 pt-3 pb-3\",\n        \"[--wf-label:6.25rem] [--wf-value:0px] @min-[26rem]/waterfall:[--wf-label:6.5rem] @min-[26rem]/waterfall:[--wf-value:calc(4.75rem+0.75rem)] @md/waterfall:[--wf-label:9rem]\",\n        orientation === \"auto\"\n          ? auto.rows\n          : orientation === \"horizontal\"\n            ? \"block\"\n            : \"hidden\",\n      )}\n    >\n      <div\n        {...plotProps(summary)}\n        data-slot=\"waterfall-chart-plot\"\n        className=\"group/plot relative rounded-md outline-none focus-visible:ring-2 focus-visible:ring-ring/50 focus-visible:ring-offset-4 focus-visible:ring-offset-card\"\n      >\n        <div className=\"relative\">\n          {/* Gridlines span the track column only. */}\n          <div\n            aria-hidden=\"true\"\n            data-slot=\"waterfall-chart-axis\"\n            className=\"pointer-events-none absolute inset-y-0 right-(--wf-value) left-[calc(var(--wf-label)+0.75rem)]\"\n          >\n            {scale.ticks.map((tick) => (\n              <span\n                key={tick}\n                className={cn(\n                  \"absolute inset-y-0 w-px\",\n                  tick === 0 ? \"bg-foreground/25\" : \"bg-border\",\n                )}\n                style={{ left: `${position(tick)}%` }}\n              />\n            ))}\n            {crosshairValue != null ? (\n              <span\n                data-slot=\"waterfall-chart-crosshair\"\n                className=\"absolute inset-y-0 z-10 w-px bg-foreground/45\"\n                style={{ left: `${position(crosshairValue)}%` }}\n              />\n            ) : null}\n          </div>\n\n          <ul role=\"presentation\" className=\"relative\">\n            {rows.map((row, index) => {\n              const isActive = active === index;\n              const dimmed = active != null && !isActive;\n              const left = position(row.low);\n              const right = position(row.high);\n              const delay = 120 + index * 85;\n              // Decreases and negative totals hang from their top edge.\n              const falling =\n                row.info.direction === \"decrease\" ||\n                (row.info.direction === \"total\" && row.info.to < 0);\n              const center = (left + right) / 2;\n              return (\n                <li\n                  key={row.step.id}\n                  role=\"presentation\"\n                  data-slot=\"waterfall-chart-step\"\n                  data-direction={row.info.direction}\n                  data-active={isActive || undefined}\n                  onPointerEnter={() => setHovered(index)}\n                  onClick={onSelect ? () => select(index) : undefined}\n                  className={cn(\n                    \"relative grid h-10 grid-cols-[var(--wf-label)_minmax(0,1fr)] items-center gap-x-3\",\n                    \"@min-[26rem]/waterfall:h-9 @min-[26rem]/waterfall:grid-cols-[var(--wf-label)_minmax(0,1fr)_4.75rem]\",\n                    onSelect && \"cursor-pointer\",\n                    row.info.kind === \"subtotal\" || row.info.kind === \"end\"\n                      ? \"border-t border-dashed border-border\"\n                      : \"\",\n                  )}\n                >\n                  <span\n                    aria-hidden=\"true\"\n                    className={cn(\n                      \"absolute -inset-x-2 inset-y-0.5 rounded-md bg-foreground/[0.045] opacity-0 transition-opacity duration-150 motion-reduce:transition-none\",\n                      isActive && \"opacity-100\",\n                    )}\n                  />\n                  <span className=\"relative min-w-0\">\n                    <span\n                      data-slot=\"waterfall-chart-label\"\n                      className={cn(\n                        \"block truncate text-xs leading-4\",\n                        row.info.direction === \"total\"\n                          ? \"font-medium text-foreground\"\n                          : \"text-muted-foreground\",\n                        isActive && \"text-foreground\",\n                      )}\n                    >\n                      {row.step.label}\n                    </span>\n                    <span\n                      className={cn(\n                        \"block text-[11px] leading-4 whitespace-nowrap tabular-nums @min-[26rem]/waterfall:hidden\",\n                        valueTone(row),\n                        dimmed && \"opacity-50\",\n                      )}\n                      style={valueStyle(row)}\n                    >\n                      {valueText(row)}\n                    </span>\n                  </span>\n                  <span className=\"relative h-full\">\n                    <span\n                      data-slot=\"waterfall-chart-bar\"\n                      className={cn(\n                        \"absolute top-1/2 h-3.5 -translate-y-1/2 transition-[opacity,left,width] duration-300 motion-reduce:transition-none\",\n                        row.info.direction === \"total\"\n                          ? row.info.to < 0\n                            ? \"rounded-l-[4px]\"\n                            : \"rounded-r-[4px]\"\n                          : \"rounded-[3px]\",\n                        dimmed && \"opacity-45\",\n                      )}\n                      style={{\n                        left: `${left}%`,\n                        width: `max(2px, ${right - left}%)`,\n                      }}\n                    >\n                      <span\n                        className=\"absolute inset-0 rounded-[inherit] motion-safe:animate-[waterfall-grow_620ms_cubic-bezier(0.22,1,0.36,1)_backwards]\"\n                        style={{\n                          backgroundColor: row.info.color,\n                          transformOrigin: falling ? \"right\" : \"left\",\n                          animationDelay: `${delay}ms`,\n                        }}\n                      />\n                      {row.cut ? <CutMark horizontal /> : null}\n                    </span>\n                    {row.connects ? (\n                      <span\n                        aria-hidden=\"true\"\n                        data-slot=\"waterfall-chart-connector\"\n                        className=\"absolute top-[calc(50%+7px)] h-[calc(100%-14px)] w-px origin-top bg-foreground/35 motion-safe:animate-[waterfall-drop_300ms_cubic-bezier(0.22,1,0.36,1)_backwards]\"\n                        style={{\n                          left: `${position(row.info.to)}%`,\n                          animationDelay: `${delay + 380}ms`,\n                        }}\n                      />\n                    ) : null}\n                    {isActive ? (\n                      <span\n                        data-slot=\"waterfall-chart-tooltip\"\n                        className=\"pointer-events-none absolute bottom-[calc(50%+14px)] z-30 rounded-lg border bg-popover px-3 py-2 text-xs whitespace-nowrap text-popover-foreground shadow-lg shadow-black/5\"\n                        style={{\n                          left: `${center}%`,\n                          transform: `translateX(-${Math.min(100, Math.max(0, center))}%)`,\n                        }}\n                      >\n                        {tooltip(row)}\n                      </span>\n                    ) : null}\n                  </span>\n                  <span\n                    data-slot=\"waterfall-chart-value\"\n                    className={cn(\n                      \"relative hidden text-right text-xs whitespace-nowrap tabular-nums transition-opacity duration-150 motion-reduce:transition-none @min-[26rem]/waterfall:block\",\n                      valueTone(row),\n                      fadeUp,\n                      dimmed && \"opacity-50\",\n                    )}\n                    style={{\n                      ...valueStyle(row),\n                      animationDelay: `${delay + 260}ms`,\n                    }}\n                  >\n                    {valueText(row)}\n                  </span>\n                </li>\n              );\n            })}\n          </ul>\n        </div>\n        <div\n          aria-hidden=\"true\"\n          className=\"relative mt-1 mr-(--wf-value) ml-[calc(var(--wf-label)+0.75rem)] h-4\"\n        >\n          {scale.ticks.map((tick, index) => {\n            const first = index === 0;\n            const last = index === scale.ticks.length - 1;\n            return (\n              <span\n                key={tick}\n                className={cn(\n                  \"absolute top-0 font-mono text-[10.5px] leading-4 text-muted-foreground tabular-nums\",\n                  first ? \"\" : last ? \"-translate-x-full\" : \"-translate-x-1/2\",\n                  // Narrow tracks only label the ends of the axis.\n                  !first && !last && \"hidden @min-[26rem]/waterfall:block\",\n                )}\n                style={{ left: `${position(tick)}%` }}\n              >\n                {format(tick, \"axis\")}\n              </span>\n            );\n          })}\n        </div>\n      </div>\n    </div>\n  );\n\n  const legend = (className: string) => (\n    <ul\n      data-slot=\"waterfall-chart-legend\"\n      aria-hidden=\"true\"\n      className={cn(\n        \"flex flex-wrap items-center gap-x-3.5 gap-y-1 text-[11px] text-muted-foreground\",\n        className,\n      )}\n    >\n      {(\n        [\n          [\"Increase\", increase],\n          [\"Decrease\", decrease],\n          [\"Total\", total],\n          ...(hasSubtotal ? [[\"Subtotal\", subtotalFill]] : []),\n        ] as [string, string][]\n      ).map(([label, color]) => (\n        <li key={label} className=\"flex items-center gap-1.5\">\n          <span\n            className=\"size-2.5 rounded-[3px]\"\n            style={{ backgroundColor: color }}\n          />\n          {label}\n        </li>\n      ))}\n    </ul>\n  );\n\n  const hasHeader =\n    title != null ||\n    description != null ||\n    actions != null ||\n    showSummary ||\n    showLegend;\n  const hasSubtotal = rows.some((row) => row.info.kind === \"subtotal\");\n\n  return (\n    <div\n      data-slot=\"waterfall-chart\"\n      data-orientation={orientation}\n      className={cn(\n        \"@container/waterfall flex min-w-0 flex-col rounded-xl border bg-card text-card-foreground shadow-xs\",\n        className,\n      )}\n      {...props}\n    >\n      <style href=\"overtrue-waterfall-chart\" precedence=\"default\">\n        {`@keyframes waterfall-rise{from{transform:scaleY(0)}}@keyframes waterfall-grow{from{transform:scaleX(0)}}@keyframes waterfall-drop{from{transform:scaleY(0)}}@keyframes waterfall-draw{from{transform:scaleX(0)}}@keyframes waterfall-fade{from{opacity:0;transform:translateY(3px)}}`}\n      </style>\n\n      {hasHeader ? (\n        <div className=\"flex flex-col gap-3 px-4 pt-4\">\n          {title != null || description != null || actions != null ? (\n            <div className=\"flex flex-wrap items-start justify-between gap-x-6 gap-y-3\">\n              <div className=\"min-w-0 space-y-1\">\n                {title != null ? (\n                  <h3 className=\"text-sm leading-5 font-semibold tracking-tight\">\n                    {title}\n                  </h3>\n                ) : null}\n                {description != null ? (\n                  <p className=\"text-xs text-muted-foreground\">{description}</p>\n                ) : null}\n              </div>\n              {actions != null ? (\n                <div className=\"flex shrink-0 items-center gap-2\">\n                  {actions}\n                </div>\n              ) : null}\n            </div>\n          ) : null}\n          {showSummary || showLegend ? (\n            <div className=\"flex flex-wrap items-end justify-between gap-x-6 gap-y-2\">\n              {showSummary && count ? (\n                renderSummary ? (\n                  <div data-slot=\"waterfall-chart-summary\" className=\"min-w-0\">\n                    {renderSummary({\n                      opening,\n                      closing,\n                      net,\n                      netShare: net != null && opening ? net / opening : null,\n                      format,\n                    })}\n                  </div>\n                ) : (\n                  <p\n                    data-slot=\"waterfall-chart-summary\"\n                    className=\"flex flex-wrap items-baseline gap-x-2 gap-y-1\"\n                  >\n                    <span className=\"text-2xl leading-none font-semibold tracking-tight\">\n                      {format(closing, \"detail\")}\n                    </span>\n                    {net != null && opening ? (\n                      <span\n                        className={cn(\n                          \"text-xs font-medium tabular-nums\",\n                          net > 0\n                            ? \"text-emerald-700 dark:text-emerald-400\"\n                            : net < 0\n                              ? \"text-rose-600 dark:text-rose-400\"\n                              : \"text-muted-foreground\",\n                        )}\n                      >\n                        {signed(net, \"label\")}\n                        <span className=\"ml-1 font-mono text-[10.5px] font-normal\">\n                          {sharePercent.format(net / opening)}\n                        </span>\n                      </span>\n                    ) : null}\n                    {opening != null ? (\n                      <span className=\"text-xs text-muted-foreground\">\n                        from {format(opening, \"label\")}\n                      </span>\n                    ) : null}\n                  </p>\n                )\n              ) : (\n                <span />\n              )}\n              {showLegend && count ? legend(\"hidden @md/waterfall:flex\") : null}\n            </div>\n          ) : null}\n        </div>\n      ) : null}\n\n      {count === 0 ? (\n        <p className=\"m-4 grid h-32 place-items-center rounded-md border border-dashed text-xs text-muted-foreground\">\n          No steps to show.\n        </p>\n      ) : (\n        <>\n          {orientation !== \"horizontal\" ? columns : null}\n          {orientation !== \"vertical\" ? rowsView : null}\n          {showLegend && count\n            ? legend(\"border-t px-4 py-2.5 @md/waterfall:hidden\")\n            : null}\n        </>\n      )}\n\n      <p className=\"sr-only\" aria-live=\"polite\">\n        {focused != null && rows[focused]\n          ? `${rows[focused].step.label}: ${rows[focused].info.formattedChange}${\n              rows[focused].info.kind === \"delta\"\n                ? `, running total ${rows[focused].info.formattedTotal}`\n                : \"\"\n            }`\n          : \"\"}\n      </p>\n\n      <div className=\"sr-only\">\n        <table>\n          <caption>{titleText}</caption>\n          <thead>\n            <tr>\n              <th scope=\"col\">Step</th>\n              <th scope=\"col\">Change</th>\n              <th scope=\"col\">Running total</th>\n            </tr>\n          </thead>\n          <tbody>\n            {rows.map((row) => (\n              <tr key={row.step.id}>\n                <th scope=\"row\">{row.step.label}</th>\n                <td>\n                  {row.info.kind === \"delta\"\n                    ? row.info.formattedChange\n                    : kindLabel[row.info.kind]}\n                </td>\n                <td>{row.info.formattedTotal}</td>\n              </tr>\n            ))}\n          </tbody>\n        </table>\n      </div>\n    </div>\n  );\n}\n\nexport { WaterfallChart };\n"
    }
  ],
  "docs": "Documentation: https://ui.overtrue.xyz/components/waterfall-chart. Requires an initialized shadcn/ui project with Tailwind CSS v4."
}
