{
  "$schema": "https://ui.shadcn.com/schema/registry-item.json",
  "name": "bar-chart",
  "title": "Bar Chart",
  "description": "One series as vertical or horizontal bars that grow in on first view, with a keyboard slider over the bars.",
  "registryDependencies": [
    "@corsair-ui/utils",
    "@corsair-ui/use-entrance"
  ],
  "files": [
    {
      "path": "registry/default/ui/bar-chart.tsx",
      "content": "\"use client\";\n\nimport {\n  useCallback,\n  useEffect,\n  useMemo,\n  useState,\n  type ComponentProps,\n  type CSSProperties,\n  type KeyboardEvent,\n  type PointerEvent,\n  type ReactNode,\n} from \"react\";\n\nimport { useEntrance } from \"@/registry/default/hooks/use-entrance\";\nimport { cn } from \"@/registry/default/lib/utils\";\n\n// Size of the drawing until the browser has measured the plot, in px.\nconst WIDTH = 600;\nconst HEIGHT = 200;\n// Height of one bar's row in the horizontal layout, in px.\nconst ROW = 32;\n// Room kept at the end of the bars for `showValues`, in px.\nconst VALUE_ROOM = { vertical: 20, horizontal: 56 };\nconst EASE = \"cubic-bezier(0.22, 0.9, 0.3, 1)\";\nconst GROW = \"cubic-bezier(0.22, 1, 0.36, 1)\";\n\ntype BarEnd = \"top\" | \"bottom\" | \"left\" | \"right\";\n\nconst n = (value: number) => Math.round(value * 100) / 100;\n\n/** A rectangle with its two corners at `end` rounded by `radius`. */\nfunction barPath(x: number, y: number, width: number, height: number, radius: number, end: BarEnd) {\n  if (width <= 0 || height <= 0) return \"\";\n  const along = end === \"top\" || end === \"bottom\";\n  const r = Math.max(0, Math.min(radius, along ? width / 2 : height / 2, along ? height : width));\n  const [x0, y0, x1, y1] = [n(x), n(y), n(x + width), n(y + height)];\n  const arc = (toX: number, toY: number) => `A${n(r)} ${n(r)} 0 0 1 ${n(toX)} ${n(toY)}`;\n  switch (end) {\n    case \"top\":\n      return `M${x0} ${y1} L${x0} ${n(y + r)} ${arc(x + r, y)} L${n(x + width - r)} ${y0} ${arc(x + width, y + r)} L${x1} ${y1} Z`;\n    case \"bottom\":\n      return `M${x1} ${y0} L${x1} ${n(y + height - r)} ${arc(x + width - r, y + height)} L${n(x + r)} ${y1} ${arc(x, y + height - r)} L${x0} ${y0} Z`;\n    case \"right\":\n      return `M${x0} ${y0} L${n(x + width - r)} ${y0} ${arc(x + width, y + r)} L${x1} ${n(y + height - r)} ${arc(x + width - r, y + height)} L${x0} ${y1} Z`;\n    case \"left\":\n      return `M${x1} ${y1} L${n(x + r)} ${y1} ${arc(x, y + height - r)} L${x0} ${n(y + r)} ${arc(x + r, y)} L${x1} ${y0} Z`;\n  }\n}\n\ninterface BarChartProps extends Omit<ComponentProps<\"div\">, \"children\"> {\n  /** The values to plot, in order. Negative values go below (or left of) a zero line. */\n  data: number[];\n  /** A label per value, shown in the tooltip and along the category axis. */\n  labels?: string[];\n  /** Name of the series, shown in the tooltip and used as the accessible name. */\n  name?: string;\n  /** Bar colour; any CSS colour. Defaults to the primary colour. */\n  color?: string;\n  /** \"vertical\" bars rise from the bottom; \"horizontal\" bars run from the left, one per row. */\n  orientation?: \"vertical\" | \"horizontal\";\n  /** Radius of the corners at the end of each bar, in px. */\n  radius?: number;\n  /** Write each value at the end of its bar. */\n  showValues?: boolean;\n  /**\n   * Locale and options for the numbers, as in `Intl.NumberFormat`. Both can\n   * be passed from a server component; a fixed default keeps the server and\n   * the browser in agreement.\n   */\n  locale?: string;\n  numberFormat?: Intl.NumberFormatOptions;\n  /** Formats the value in the tooltip and on the bars; overrides `locale` and `numberFormat`. */\n  formatValue?: (value: number, index: number) => ReactNode;\n  /** What screen readers hear for a bar. Defaults to its label and value. */\n  formatValueText?: (value: number, index: number) => string;\n  /** The bar selected at first. Defaults to the last one. */\n  defaultIndex?: number;\n  /** Called when the selected bar changes, by pointer or keyboard. */\n  onIndexChange?: (index: number) => void;\n  /** Show the labels along the category axis: under the bars, or beside them when horizontal. Needs `labels`. */\n  showXAxis?: boolean;\n  /**\n   * Vertical only: the most axis labels to show, evenly spaced and ending on\n   * the latest bar; narrow charts show fewer. Horizontal charts label every row.\n   */\n  tickCount?: number;\n  /** Grow the bars from the zero line the first time they come into view, and glide the tooltip. */\n  animated?: boolean;\n}\n\n/**\n * A bar chart for one series, vertical or horizontal. Hovering highlights\n * the nearest bar, dims the others and shows its value in a tooltip. It is a\n * slider over the bars for keyboards and screen readers: arrow keys, Page\n * Up / Page Down, Home and End move between bars and each one is announced\n * with its label and value, while the drawing itself is hidden from\n * assistive technology. Bars grow from the zero line the first time they\n * scroll into view; with `prefers-reduced-motion` they are simply shown. No\n * chart library: one SVG, sized to its container.\n *\n * @example\n * <BarChart\n *   name=\"Visitors\"\n *   data={[120, 180, 150, 240, 220, 300]}\n *   labels={[\"Mon\", \"Tue\", \"Wed\", \"Thu\", \"Fri\", \"Sat\"]}\n * />\n */\nfunction BarChart({\n  data,\n  labels,\n  name,\n  color = \"var(--primary)\",\n  orientation = \"vertical\",\n  radius = 4,\n  showValues = false,\n  locale = \"en-US\",\n  numberFormat,\n  formatValue,\n  formatValueText,\n  defaultIndex,\n  onIndexChange,\n  showXAxis = true,\n  tickCount = 12,\n  animated = true,\n  className,\n  style,\n  \"aria-label\": ariaLabel,\n  ...props\n}: BarChartProps) {\n  const vertical = orientation === \"vertical\";\n  const [plot, setPlot] = useState<HTMLDivElement | null>(null);\n  const [size, setSize] = useState<{ width: number; height: number } | null>(null);\n  const [active, setActive] = useState(() => defaultIndex ?? Math.max(0, data.length - 1));\n  const [engaged, setEngaged] = useState(false);\n  const [observe, phase] = useEntrance<HTMLDivElement>({ play: animated ? undefined : true });\n  const entrance = animated ? phase : \"static\";\n\n  const plotRef = useCallback(\n    (node: HTMLDivElement | null) => {\n      setPlot(node);\n      observe(node);\n    },\n    [observe]\n  );\n\n  useEffect(() => {\n    if (!plot || typeof ResizeObserver === \"undefined\") return;\n    const observer = new ResizeObserver(([entry]) => {\n      const box = entry?.contentRect;\n      if (box?.width && box.height) setSize({ width: box.width, height: box.height });\n    });\n    observer.observe(plot);\n    return () => observer.disconnect();\n  }, [plot]);\n\n  const width = size?.width ?? WIDTH;\n  const height = size?.height ?? (vertical ? HEIGHT : ROW * Math.max(1, data.length));\n\n  const bars = useMemo(() => {\n    if (data.length === 0) return [];\n    const min = Math.min(0, ...data);\n    const max = Math.max(0, ...data);\n    const range = max - min || 1;\n    const room = showValues ? VALUE_ROOM[orientation] : vertical ? 4 : 0;\n    const length = vertical ? height : width;\n    const high = max > 0 || min === 0 ? room : 0;\n    const low = min < 0 ? room : 0;\n    // Distance from the low end of the value axis.\n    const at = (value: number) => low + ((value - min) / range) * (length - low - high);\n    const band = (vertical ? width : height) / data.length;\n    const thickness = band * (vertical ? 0.7 : 0.66);\n    const zero = vertical ? height - at(0) : at(0);\n    return data.map((value, index) => {\n      const start = index * band + (band - thickness) / 2;\n      const end = vertical ? height - at(value) : at(value);\n      const negative = value < 0;\n      const from = Math.min(zero, end);\n      const span = Math.abs(end - zero);\n      return {\n        value,\n        negative,\n        zero,\n        // The centre of the bar across, and its tip along the value axis.\n        center: start + thickness / 2,\n        tip: end,\n        thickness,\n        d: vertical\n          ? barPath(start, from, thickness, span, radius, negative ? \"bottom\" : \"top\")\n          : barPath(from, start, span, thickness, radius, negative ? \"left\" : \"right\"),\n      };\n    });\n  }, [data, orientation, vertical, width, height, radius, showValues]);\n\n  const numbers = useMemo(\n    () => new Intl.NumberFormat(locale, numberFormat),\n    [locale, numberFormat]\n  );\n\n  const ticks = useMemo(() => {\n    if (!showXAxis || !labels?.length || bars.length === 0) return [];\n    if (!vertical) return Array.from({ length: bars.length }, (_, index) => index);\n    // At most one label per 56px, so they never run into each other.\n    const most = Math.min(tickCount, Math.max(2, Math.floor(width / 56)), bars.length);\n    if (most < 1) return [];\n    const last = bars.length - 1;\n    const step = Math.floor(last / most) + 1;\n    return Array.from(\n      { length: Math.floor(last / step) + 1 },\n      (_, tick) => (last % step) + tick * step\n    );\n  }, [showXAxis, labels, bars.length, vertical, tickCount, width]);\n\n  if (bars.length === 0) return null;\n\n  const index = Math.min(Math.max(active, 0), bars.length - 1);\n  const bar = bars[index]!;\n  const select = (next: number) => {\n    const clamped = Math.min(Math.max(next, 0), bars.length - 1);\n    if (clamped === index) return;\n    setActive(clamped);\n    onIndexChange?.(clamped);\n  };\n\n  const onPointer = (event: PointerEvent<HTMLDivElement>) => {\n    const box = event.currentTarget.getBoundingClientRect();\n    const across = vertical ? box.width : box.height;\n    if (across === 0) return;\n    const offset = vertical ? event.clientX - box.left : event.clientY - box.top;\n    setEngaged(true);\n    select(Math.floor((offset / across) * bars.length));\n  };\n\n  const onKeyDown = (event: KeyboardEvent<HTMLDivElement>) => {\n    const page = Math.max(1, Math.round(bars.length / 10));\n    // Horizontal charts list their bars top to bottom, so Down moves on.\n    const back = vertical ? [\"ArrowLeft\", \"ArrowDown\"] : [\"ArrowLeft\", \"ArrowUp\"];\n    const forward = vertical ? [\"ArrowRight\", \"ArrowUp\"] : [\"ArrowRight\", \"ArrowDown\"];\n    const moves: Record<string, number> = {\n      [back[0]!]: index - 1,\n      [back[1]!]: index - 1,\n      [forward[0]!]: index + 1,\n      [forward[1]!]: index + 1,\n      PageDown: index - page,\n      PageUp: index + page,\n      Home: 0,\n      End: bars.length - 1,\n    };\n    const next = moves[event.key];\n    if (next === undefined) return;\n    event.preventDefault();\n    setEngaged(true);\n    select(next);\n  };\n\n  const format = (value: number, at: number) =>\n    formatValue ? formatValue(value, at) : numbers.format(value);\n  const label = labels?.[index];\n  const valueText =\n    formatValueText?.(bar.value, index) ??\n    `${label ? `${label}: ` : \"\"}${numbers.format(bar.value)}`;\n\n  // The tooltip hangs off the side of the active bar's tip, flipping past halfway.\n  const tipX = vertical ? bar.center : bar.tip;\n  const tipY = vertical ? bar.tip : bar.center;\n  const flip = tipX > width / 2;\n  const anchorX = vertical ? tipX + (flip ? -1 : 1) * (bar.thickness / 2) : tipX;\n  // In container units of the plot (its width is 100cqw), so the anchor is\n  // right before the plot is measured too: the server render and the first\n  // paint place nothing past the plot's edge, which on a phone would widen\n  // the page. A horizontal chart's height is fixed in px, so its y stays in px.\n  const anchor = `${n((anchorX / width) * 100)}cqw, ${vertical ? `${n((tipY / width) * 100)}cqw` : `${n(tipY)}px`}`;\n  const glide = animated ? `transform 220ms ${EASE}` : undefined;\n  const stagger = Math.min(60, 480 / bars.length);\n\n  return (\n    <div\n      data-slot=\"bar-chart\"\n      data-orientation={orientation}\n      className={cn(\n        \"w-full select-none\",\n        !vertical && showXAxis && ticks.length > 0 && \"grid grid-cols-[auto_1fr] gap-x-3\",\n        className\n      )}\n      style={{ \"--bar-chart-color\": color, ...style } as CSSProperties}\n      {...props}\n    >\n      {!vertical && ticks.length > 0 ? (\n        <div aria-hidden=\"true\" data-slot=\"bar-chart-axis\" className=\"flex flex-col\">\n          {bars.map((_, at) => (\n            <span\n              key={at}\n              className=\"text-muted-foreground flex flex-1 items-center justify-end text-xs whitespace-nowrap\"\n            >\n              {labels?.[at]}\n            </span>\n          ))}\n        </div>\n      ) : null}\n\n      <div\n        ref={plotRef}\n        role=\"slider\"\n        tabIndex={0}\n        aria-label={ariaLabel ?? name ?? \"Chart\"}\n        aria-valuemin={1}\n        aria-valuemax={bars.length}\n        aria-valuenow={index + 1}\n        aria-valuetext={valueText}\n        aria-orientation={vertical ? \"horizontal\" : \"vertical\"}\n        data-slot=\"bar-chart-plot\"\n        data-state={entrance}\n        data-engaged={engaged ? \"\" : undefined}\n        // A size container: the tooltip is placed in its cqw.\n        className={cn(\n          \"focus-visible:ring-ring/50 [container-type:inline-size] relative w-full rounded-md outline-none focus-visible:ring-[3px]\",\n          vertical ? \"aspect-[3/1] touch-pan-y\" : \"touch-pan-x\"\n        )}\n        style={vertical ? undefined : { height: ROW * bars.length }}\n        onPointerMove={onPointer}\n        onPointerDown={onPointer}\n        onPointerLeave={() => setEngaged(false)}\n        onFocus={() => setEngaged(true)}\n        onBlur={() => setEngaged(false)}\n        onKeyDown={onKeyDown}\n      >\n        <svg\n          aria-hidden=\"true\"\n          viewBox={`0 0 ${n(width)} ${n(height)}`}\n          preserveAspectRatio=\"none\"\n          className=\"absolute inset-0 size-full overflow-visible\"\n        >\n          {bars.map((item, at) => (\n            <path\n              key={at}\n              data-slot=\"bar-chart-bar\"\n              data-active={at === index ? \"\" : undefined}\n              data-dimmed={engaged && at !== index ? \"\" : undefined}\n              data-negative={item.negative ? \"\" : undefined}\n              d={item.d}\n              fill=\"var(--bar-chart-color)\"\n              className=\"transition-opacity data-[dimmed]:opacity-40 motion-reduce:![transform:none] motion-reduce:!transition-none\"\n              style={{\n                transformBox: \"view-box\",\n                transformOrigin: vertical ? `0 ${n(item.zero)}px` : `${n(item.zero)}px 0`,\n                transform:\n                  entrance === \"armed\" ? (vertical ? \"scale(1, 0)\" : \"scale(0, 1)\") : undefined,\n                transition:\n                  entrance === \"play\"\n                    ? `transform 600ms ${GROW} ${n(at * stagger)}ms, opacity 150ms ease`\n                    : undefined,\n              }}\n            />\n          ))}\n          <line\n            data-slot=\"bar-chart-zero\"\n            x1={vertical ? 0 : n(bar.zero)}\n            x2={vertical ? n(width) : n(bar.zero)}\n            y1={vertical ? n(bar.zero) : 0}\n            y2={vertical ? n(bar.zero) : n(height)}\n            stroke=\"var(--border)\"\n            strokeWidth=\"1\"\n            vectorEffect=\"non-scaling-stroke\"\n          />\n        </svg>\n\n        {showValues\n          ? bars.map((item, at) => (\n              <span\n                key={at}\n                aria-hidden=\"true\"\n                data-slot=\"bar-chart-value\"\n                className={cn(\n                  \"text-muted-foreground pointer-events-none absolute font-mono text-[11px] leading-none whitespace-nowrap tabular-nums transition-opacity motion-reduce:!opacity-100 motion-reduce:!transition-none\",\n                  entrance === \"armed\" && \"opacity-0\"\n                )}\n                style={{\n                  left: `${((vertical ? item.center : item.tip) / width) * 100}%`,\n                  top: `${((vertical ? item.tip : item.center) / height) * 100}%`,\n                  transform: vertical\n                    ? `translate(-50%, ${item.negative ? \"4px\" : \"calc(-100% - 4px)\"})`\n                    : `translate(${item.negative ? \"calc(-100% - 4px)\" : \"4px\"}, -50%)`,\n                  transitionDuration: entrance === \"play\" ? \"300ms\" : undefined,\n                  transitionDelay: entrance === \"play\" ? `${n(400 + at * stagger)}ms` : undefined,\n                }}\n              >\n                {format(item.value, at)}\n              </span>\n            ))\n          : null}\n\n        {/* A zero-size anchor rides on the bar's tip; the card hangs off its side. */}\n        <div\n          aria-hidden=\"true\"\n          data-slot=\"bar-chart-tooltip-anchor\"\n          className=\"pointer-events-none absolute top-0 left-0 z-10 size-0 motion-reduce:!transition-none\"\n          style={{ transform: `translate3d(${anchor}, 0)`, transition: glide }}\n        >\n          <div\n            data-slot=\"bar-chart-tooltip\"\n            data-state={engaged ? \"open\" : \"closed\"}\n            className={cn(\n              \"bg-popover text-popover-foreground absolute top-0 grid w-max min-w-32 -translate-y-1/2 gap-1.5 rounded-md border px-2.5 py-1.5 text-xs shadow-md transition-opacity data-[state=closed]:opacity-0 motion-reduce:transition-none\",\n              flip ? \"right-2\" : \"left-2\"\n            )}\n          >\n            {label ? <div className=\"font-medium\">{label}</div> : null}\n            <div className=\"flex items-center gap-2\">\n              <span className=\"size-2.5 shrink-0 rounded-[3px] bg-[color:var(--bar-chart-color)]\" />\n              {name ? <span className=\"text-muted-foreground\">{name}</span> : null}\n              <span className=\"ml-auto font-mono font-medium tabular-nums\">\n                {format(bar.value, index)}\n              </span>\n            </div>\n          </div>\n        </div>\n      </div>\n\n      {vertical && ticks.length > 0 ? (\n        <div aria-hidden=\"true\" data-slot=\"bar-chart-axis\" className=\"relative mt-2 h-5\">\n          {ticks.map((tick) => (\n            <span\n              key={tick}\n              className=\"text-muted-foreground absolute top-0 -translate-x-1/2 text-[11px] leading-none whitespace-nowrap tabular-nums\"\n              style={{ left: `${(bars[tick]!.center / width) * 100}%` }}\n            >\n              {labels?.[tick]}\n            </span>\n          ))}\n        </div>\n      ) : null}\n    </div>\n  );\n}\n\nexport { BarChart, type BarChartProps };\n",
      "type": "registry:ui"
    }
  ],
  "type": "registry:ui"
}