{
  "$schema": "https://ui.shadcn.com/schema/registry-item.json",
  "name": "bar-chart",
  "type": "registry:component",
  "title": "Bar Chart",
  "description": "A bar chart, vertical or horizontal, grouped or stacked, always measured from zero, with a tooltip on hover and arrow-key reading.",
  "categories": [
    "viz"
  ],
  "dependencies": [
    "d3-scale"
  ],
  "devDependencies": [
    "@types/d3-scale"
  ],
  "registryDependencies": [
    "@rivier-ui/theme",
    "@rivier-ui/chart",
    "@rivier-ui/cn"
  ],
  "files": [
    {
      "path": "registry/viz/bar-chart.tsx",
      "type": "registry:component",
      "target": "components/viz/bar-chart.tsx",
      "content": "\"use client\";\n/**\n * @name bar-chart\n * @category viz\n * @description A bar chart, vertical or horizontal, grouped or stacked, always measured from zero, with a tooltip on hover and arrow-key reading.\n * @when Comparing amounts across categories. Use `orientation=\"horizontal\"` for long names or a ranking, `stacked` when the series add up to a total. For change over many points in time use line-chart; for a single number use a stat, not one bar.\n * @example\n * <BarChart\n *   label=\"Orders by channel per quarter\"\n *   data={[\n *     { quarter: \"Q1\", web: 320, app: 210 },\n *     { quarter: \"Q2\", web: 410, app: 290 },\n *     { quarter: \"Q3\", web: 380, app: 350 },\n *   ]}\n *   x=\"quarter\"\n *   series={[\n *     { key: \"web\", label: \"Web\" },\n *     { key: \"app\", label: \"App\" },\n *   ]}\n *   showValues\n * />\n */\nimport { scaleBand, scaleLinear } from \"d3-scale\";\nimport { useMemo, useState, type ComponentProps, type KeyboardEvent } from \"react\";\nimport { cn } from \"@/lib/cn\";\nimport {\n  axisNumberFormatter,\n  ChartAxis,\n  ChartContainer,\n  ChartGrid,\n  ChartLegend,\n  chartSeries,\n  ChartSvg,\n  ChartTooltip,\n  estimateTextWidth,\n  formatNumber,\n  readNumber,\n  type ChartFormat,\n  type ChartSeries,\n} from \"@/components/viz/chart\";\n\nexport type BarChartProps<T extends object> = Omit<ComponentProps<\"div\">, \"children\"> &\n  Omit<ChartFormat, \"timeZone\"> & {\n    /** One object per category. */\n    data: readonly T[];\n    /** The field that names the category. */\n    x: keyof T & string;\n    /** The bars per category, in a fixed order: the first takes the highlight colour. */\n    series: readonly ChartSeries<T>[];\n    /** What the chart shows, for assistive technology. */\n    label: string;\n    /** Bars standing up (\"vertical\") or lying along the row (\"horizontal\"). */\n    orientation?: \"vertical\" | \"horizontal\";\n    /** Stack the series in one bar per category instead of side by side. */\n    stacked?: boolean;\n    /** Print each bar's value at its end (the total, when stacked), where it fits. */\n    showValues?: boolean;\n    showGrid?: boolean;\n    /** Default: shown for two or more series. */\n    showLegend?: boolean;\n    /** The name of the category column in the table alternative. Default: the `x` field name. */\n    xLabel?: string;\n    /** Width / height of the plot. */\n    aspect?: number;\n    /** A fixed plot height in pixels instead of a ratio. */\n    height?: number;\n  };\n\ntype Bar = { category: number; series: number; value: number; from: number; to: number; outer: boolean };\n\n/** Bars are thin; what the band has left over is air. */\nconst MAX_THICKNESS = 24;\n/** The space in the surface colour between touching bars and between stacked segments. */\nconst GAP = 2;\n/** Rounded bar ends follow the theme's roundness up to 4px, and are square when it is \"none\". */\nconst ROUND = \"[rx:min(var(--radius),4px)] [ry:min(var(--radius),4px)]\";\n\nexport function BarChart<T extends object>({\n  data,\n  x,\n  series,\n  label,\n  orientation = \"vertical\",\n  stacked = false,\n  showValues = false,\n  showGrid = true,\n  showLegend,\n  xLabel,\n  aspect,\n  height,\n  locale,\n  formatValue,\n  className,\n  ...props\n}: BarChartProps<T>) {\n  const [active, setActive] = useState<number | null>(null);\n  const [keyboard, setKeyboard] = useState(false);\n  const vertical = orientation === \"vertical\";\n\n  const model = useMemo(() => {\n    const categories = data.map((row) => String((row as Record<string, unknown>)[x] ?? \"\"));\n    const bars: Bar[] = [];\n    const totals: { high: number; low: number }[] = [];\n    data.forEach((row, category) => {\n      let high = 0;\n      let low = 0;\n      const start = bars.length;\n      series.forEach((item, index) => {\n        const value = readNumber(row, item.key);\n        if (value === null) return;\n        if (!stacked) {\n          bars.push({ category, series: index, value, from: 0, to: value, outer: true });\n          high = Math.max(high, value);\n          low = Math.min(low, value);\n        } else if (value >= 0) {\n          bars.push({ category, series: index, value, from: high, to: high + value, outer: false });\n          high += value;\n        } else {\n          bars.push({ category, series: index, value, from: low, to: low + value, outer: false });\n          low += value;\n        }\n      });\n      if (stacked) {\n        // Only the segment at the far end of a stack gets the rounded end.\n        const mine = bars.slice(start);\n        const top = mine.findLast((bar) => bar.value > 0);\n        const bottom = mine.findLast((bar) => bar.value < 0);\n        if (top) top.outer = true;\n        if (bottom) bottom.outer = true;\n      }\n      totals.push({ high, low });\n    });\n    // The baseline is zero, always: a bar is read by its length.\n    const high = Math.max(0, ...totals.map((total) => total.high));\n    const low = Math.min(0, ...totals.map((total) => total.low));\n    return { categories, bars, totals, high, low };\n  }, [data, x, series, stacked]);\n\n  const { categories, bars, totals } = model;\n  const value = formatValue ?? ((number: number) => formatNumber(number, locale));\n  const table = {\n    caption: label,\n    columns: [xLabel ?? x, ...series.map((item) => item.label)],\n    rows: data.map((row, index) => [\n      categories[index] ?? \"\",\n      ...series.map((item) => {\n        const number = readNumber(row, item.key);\n        return number === null ? \"\" : value(number);\n      }),\n    ]),\n  };\n\n  const current = active === null ? undefined : bars[active];\n  const currentLabel = current ? (series[current.series]?.label ?? \"\") : \"\";\n  const announcement = keyboard && current ? `${categories[current.category] ?? \"\"}, ${currentLabel}: ${value(current.value)}` : \"\";\n\n  const move = (step: number | \"first\" | \"last\"): void => {\n    if (bars.length === 0) return;\n    setKeyboard(true);\n    setActive((index) => {\n      if (step === \"first\") return 0;\n      if (step === \"last\") return bars.length - 1;\n      if (index === null) return step > 0 ? 0 : bars.length - 1;\n      return Math.max(0, Math.min(bars.length - 1, index + step));\n    });\n  };\n  const onKeyDown = (event: KeyboardEvent<SVGSVGElement>): void => {\n    if (event.key === \"ArrowRight\" || event.key === \"ArrowDown\") move(1);\n    else if (event.key === \"ArrowLeft\" || event.key === \"ArrowUp\") move(-1);\n    else if (event.key === \"Home\") move(\"first\");\n    else if (event.key === \"End\") move(\"last\");\n    else if (event.key === \"Escape\") setActive(null);\n    else return;\n    event.preventDefault();\n  };\n\n  const legend = showLegend ?? series.length > 1;\n\n  return (\n    <div data-slot=\"bar-chart\" className={cn(\"flex w-full min-w-0 flex-col gap-3\", className)} {...props}>\n      {legend ? <ChartLegend items={series.map((item, index) => ({ label: item.label, index }))} mark=\"rect\" /> : null}\n      <ChartContainer aspect={aspect} height={height} table={table} announcement={announcement}>\n        {(size) => {\n          if (bars.length === 0) {\n            return <p className=\"absolute inset-0 flex items-center justify-center text-sm text-muted-foreground\">No data</p>;\n          }\n          const ticksWanted = Math.max(2, Math.floor((vertical ? size.height : size.width) / (vertical ? 56 : 90)));\n          const scale = scaleLinear()\n            .domain(model.low === model.high ? [0, 1] : [model.low, model.high])\n            .nice(ticksWanted);\n          const ticks = scale.ticks(ticksWanted);\n          const axisValue = formatValue ?? axisNumberFormatter(Math.max(Math.abs(scale.domain()[0] ?? 0), Math.abs(scale.domain()[1] ?? 0)), locale);\n          const widest = (texts: readonly string[]): number => Math.ceil(Math.max(0, ...texts.map((text) => estimateTextWidth(text))));\n          const valueRoom = showValues ? widest(bars.map((bar) => value(bar.value))) + 8 : 0;\n          const hasNegative = model.low < 0;\n\n          const left = vertical ? widest(ticks.map(axisValue)) + 10 : Math.min(Math.round(size.width * 0.35), widest(categories) + 10) + (showValues && hasNegative ? valueRoom : 0);\n          const right = vertical ? 4 : Math.max(12, valueRoom);\n          const top = vertical ? (showValues ? 22 : 10) : 4;\n          const bottom = 26;\n          const nameRoom = vertical ? 0 : Math.min(Math.round(size.width * 0.35), widest(categories) + 10) - 10;\n          scale.range(vertical ? [size.height - bottom, top] : [left, size.width - right]);\n\n          const band = scaleBand<number>()\n            .domain(categories.map((_, index) => index))\n            .range(vertical ? [left, size.width - right] : [top, size.height - bottom])\n            .paddingInner(0.3)\n            .paddingOuter(0.15);\n          const slots = stacked ? 1 : series.length;\n          const thickness = Math.max(1, Math.min(MAX_THICKNESS, (band.bandwidth() - GAP * (slots - 1)) / slots));\n          const groupStart = (category: number): number => (band(category) ?? 0) + (band.bandwidth() - (slots * thickness + (slots - 1) * GAP)) / 2;\n          const zero = scale(0);\n\n          const shapes = bars.map((bar) => {\n            const across = groupStart(bar.category) + (stacked ? 0 : bar.series * (thickness + GAP));\n            let a = scale(bar.from);\n            const b = scale(bar.to);\n            // Stacked segments keep a gap in the surface colour between them, taken from the end nearer the baseline.\n            if (bar.from !== 0 && Math.abs(b - a) > GAP + 1) a += Math.sign(b - a) * GAP;\n            return { bar, across, a, b, tip: b, middle: across + thickness / 2 };\n          });\n          const rect = (across: number, a: number, b: number): { x: number; y: number; width: number; height: number } =>\n            vertical ? { x: across, y: Math.min(a, b), width: thickness, height: Math.abs(b - a) } : { x: Math.min(a, b), y: across, width: Math.abs(b - a), height: thickness };\n          const plotFrom = vertical ? top : left;\n          const plotTo = vertical ? size.height - bottom : size.width - right;\n\n          const names = categories.map((name) => {\n            if (vertical) return name;\n            const fits = Math.max(3, Math.floor(nameRoom / (12 * 0.58)));\n            return name.length > fits ? `${name.slice(0, fits - 1)}…` : name;\n          });\n          // Category names that would run into each other are thinned out; every name stays in the table.\n          const every = vertical ? Math.max(1, Math.ceil((widest(categories) + 8) / band.step())) : 1;\n\n          const labels = !showValues\n            ? []\n            : stacked\n              ? totals.flatMap((total, category) => {\n                  const middle = groupStart(category) + thickness / 2;\n                  const out: { key: string; text: string; at: number; middle: number; positive: boolean }[] = [];\n                  if (total.high > 0 || total.low === 0) out.push({ key: `${category}:high`, text: value(total.high), at: scale(total.high), middle, positive: true });\n                  if (total.low < 0) out.push({ key: `${category}:low`, text: value(total.low), at: scale(total.low), middle, positive: false });\n                  return out;\n                })\n              : shapes.map((shape) => ({ key: `${shape.bar.category}:${shape.bar.series}`, text: value(shape.bar.value), at: shape.tip, middle: shape.middle, positive: shape.bar.value >= 0 }));\n          // A value that does not fit over its bar is not printed: the tooltip and the table carry it.\n          const labelFits = (text: string): boolean => !vertical || estimateTextWidth(text) <= (stacked ? band.bandwidth() : thickness + GAP) + 6;\n\n          const shape = active === null ? undefined : shapes[active];\n          const tooltipX = shape ? (vertical ? shape.middle : shape.tip) : 0;\n          const tooltipY = shape ? (vertical ? Math.min(shape.tip, zero) : shape.middle) : 0;\n\n          return (\n            <>\n              <ChartSvg\n                label={label}\n                width={size.width}\n                height={size.height}\n                interactive\n                onKeyDown={onKeyDown}\n                onPointerLeave={() => setActive(null)}\n                onFocus={(event) => {\n                  if (event.currentTarget.matches(\":focus-visible\")) move(\"first\");\n                }}\n                onBlur={() => setActive(null)}\n              >\n                {showGrid ? <ChartGrid offsets={ticks.map((tick) => scale(tick))} from={vertical ? left : top} to={vertical ? size.width - right : size.height - bottom} vertical={!vertical} /> : null}\n                {vertical ? (\n                  <>\n                    <ChartAxis side=\"left\" at={left - 8} ticks={ticks.map((tick) => ({ offset: scale(tick), label: axisValue(tick) }))} />\n                    <ChartAxis side=\"bottom\" at={size.height - bottom + 8} ticks={names.flatMap((name, index) => (index % every === 0 ? [{ offset: (band(index) ?? 0) + band.bandwidth() / 2, label: name }] : []))} />\n                  </>\n                ) : (\n                  <>\n                    <ChartAxis side=\"bottom\" at={size.height - bottom + 8} ticks={ticks.map((tick) => ({ offset: scale(tick), label: axisValue(tick) }))} />\n                    <ChartAxis side=\"left\" at={left - 8 - (showValues && hasNegative ? valueRoom : 0)} ticks={names.map((name, index) => ({ offset: (band(index) ?? 0) + band.bandwidth() / 2, label: name }))} />\n                  </>\n                )}\n                <g aria-hidden=\"true\">\n                  {shapes.map((item, index) => {\n                    const full = rect(item.across, item.a, item.b);\n                    if (full.width <= 0 || full.height <= 0) return null;\n                    const fill = chartSeries(item.bar.series).fill;\n                    return (\n                      <g key={index} className={cn(\"transition-opacity duration-instant motion-reduce:transition-none\", active !== null && active !== index && \"opacity-45\")}>\n                        {item.bar.outer ? (\n                          <>\n                            {/* Rounded at the data end, square at the baseline: a rounded bar, with its baseline half squared off. */}\n                            <rect {...full} className={cn(fill, ROUND)} />\n                            <rect {...rect(item.across, item.a, (item.a + item.b) / 2)} className={fill} />\n                          </>\n                        ) : (\n                          <rect {...full} className={fill} />\n                        )}\n                      </g>\n                    );\n                  })}\n                  <line\n                    x1={vertical ? left : zero}\n                    x2={vertical ? size.width - right : zero}\n                    y1={vertical ? zero : top}\n                    y2={vertical ? zero : size.height - bottom}\n                    className=\"stroke-border-strong\"\n                    strokeWidth={1}\n                    shapeRendering=\"crispEdges\"\n                  />\n                  {labels.map((item) =>\n                    labelFits(item.text) ? (\n                      vertical ? (\n                        <text key={item.key} x={item.middle} y={item.at + (item.positive ? -6 : 6)} dy={item.positive ? 0 : \"0.7em\"} textAnchor=\"middle\" className=\"fill-foreground tabular-nums\">\n                          {item.text}\n                        </text>\n                      ) : (\n                        <text key={item.key} x={item.at + (item.positive ? 6 : -6)} y={item.middle} dy=\"0.32em\" textAnchor={item.positive ? \"start\" : \"end\"} className=\"fill-foreground tabular-nums\">\n                          {item.text}\n                        </text>\n                      )\n                    ) : null,\n                  )}\n                  {/* Hit areas are larger than the bars: the whole column of a grouped bar, the whole band of a stacked segment. */}\n                  {shapes.map((item, index) => {\n                    const along = stacked ? { a: item.a, b: item.b } : { a: plotFrom, b: plotTo };\n                    const start = stacked ? (band(item.bar.category) ?? 0) : item.across - GAP / 2;\n                    const breadth = stacked ? band.bandwidth() : thickness + GAP;\n                    const area = vertical\n                      ? { x: start, y: Math.min(along.a, along.b), width: breadth, height: Math.abs(along.b - along.a) }\n                      : { x: Math.min(along.a, along.b), y: start, width: Math.abs(along.b - along.a), height: breadth };\n                    return (\n                      <rect\n                        key={index}\n                        {...area}\n                        fill=\"transparent\"\n                        onPointerEnter={() => {\n                          setKeyboard(false);\n                          setActive(index);\n                        }}\n                      />\n                    );\n                  })}\n                </g>\n              </ChartSvg>\n              {shape && current ? (\n                <ChartTooltip\n                  x={tooltipX}\n                  y={tooltipY}\n                  side={tooltipX > size.width / 2 ? \"left\" : \"right\"}\n                  title={categories[current.category]}\n                  rows={[{ label: currentLabel, value: value(current.value), index: current.series, mark: \"rect\" }]}\n                />\n              ) : null}\n            </>\n          );\n        }}\n      </ChartContainer>\n    </div>\n  );\n}\n"
    }
  ],
  "meta": {
    "category": "viz",
    "when": "Comparing amounts across categories. Use `orientation=\"horizontal\"` for long names or a ranking, `stacked` when the series add up to a total. For change over many points in time use line-chart; for a single number use a stat, not one bar.",
    "example": "<BarChart\n  label=\"Orders by channel per quarter\"\n  data={[\n    { quarter: \"Q1\", web: 320, app: 210 },\n    { quarter: \"Q2\", web: 410, app: 290 },\n    { quarter: \"Q3\", web: 380, app: 350 },\n  ]}\n  x=\"quarter\"\n  series={[\n    { key: \"web\", label: \"Web\" },\n    { key: \"app\", label: \"App\" },\n  ]}\n  showValues\n/>",
    "client": true
  }
}
