{
  "$schema": "https://ui.shadcn.com/schema/registry-item.json",
  "name": "chart",
  "type": "registry:component",
  "title": "Chart",
  "description": "The shared parts every chart is built from: a container that measures itself and carries the text alternative, an SVG root, a tooltip, a legend, series styles, and axis and format helpers.",
  "categories": [
    "viz"
  ],
  "dependencies": [
    "d3-shape"
  ],
  "devDependencies": [
    "@types/d3-shape"
  ],
  "registryDependencies": [
    "@rivier-ui/theme",
    "@rivier-ui/cn",
    "@rivier-ui/use-size"
  ],
  "files": [
    {
      "path": "registry/viz/chart.tsx",
      "type": "registry:component",
      "target": "components/viz/chart.tsx",
      "content": "\"use client\";\n/**\n * @name chart\n * @category viz\n * @description The shared parts every chart is built from: a container that measures itself and carries the text alternative, an SVG root, a tooltip, a legend, series styles, and axis and format helpers.\n * @when Building a chart of your own that should match the others. For the common forms use line-chart, area-chart, bar-chart, donut-chart, sparkline, heatmap or radial-progress directly.\n * @example\n * <ChartContainer aspect={2} table={{ caption: \"Signups\", columns: [\"Day\", \"Signups\"], rows: [[\"Mon\", 4], [\"Tue\", 9]] }}>\n *   {({ width, height }) => (\n *     <ChartSvg label=\"Signups by day\" width={width} height={height}>\n *       <rect x={0} y={height - 40} width={width / 3} height={40} className={chartSeries(0).fill} />\n *       <rect x={width / 2} y={height - 90} width={width / 3} height={90} className={chartSeries(0).fill} />\n *     </ChartSvg>\n *   )}\n * </ChartContainer>\n * <ChartLegend items={[{ label: \"Signups\", index: 0 }]} mark=\"rect\" />\n */\nimport { symbol, symbolCircle, symbolCross, symbolDiamond, symbolSquare, symbolStar, symbolTriangle, type SymbolType } from \"d3-shape\";\nimport type { ComponentProps, ReactNode } from \"react\";\nimport { cn } from \"@/lib/cn\";\nimport { useSize, type Size } from \"@/lib/use-size\";\n\n/* Series: colour, plus a shape and (past five) a dash, so identity never rests on colour alone. */\n\nexport type ChartSeries<T> = {\n  /** The field of a data row that holds this series' number. */\n  key: keyof T & string;\n  /** Its name in the legend, the tooltip and the table. */\n  label: string;\n};\n\nexport type ChartSeriesStyle = {\n  /** Tailwind classes for the series colour. Literal strings, so Tailwind finds them. */\n  fill: string;\n  stroke: string;\n  background: string;\n  /** A stroke-dasharray for lines, set only past the fifth series. */\n  dash: string | undefined;\n  symbol: SymbolType;\n};\n\nconst PALETTE = [\n  { fill: \"fill-chart-1\", stroke: \"stroke-chart-1\", background: \"bg-chart-1\", symbol: symbolCircle },\n  { fill: \"fill-chart-2\", stroke: \"stroke-chart-2\", background: \"bg-chart-2\", symbol: symbolSquare },\n  { fill: \"fill-chart-3\", stroke: \"stroke-chart-3\", background: \"bg-chart-3\", symbol: symbolDiamond },\n  { fill: \"fill-chart-4\", stroke: \"stroke-chart-4\", background: \"bg-chart-4\", symbol: symbolTriangle },\n  { fill: \"fill-chart-5\", stroke: \"stroke-chart-5\", background: \"bg-chart-5\", symbol: symbolCross },\n] as const;\nconst NEUTRAL: ChartSeriesStyle = { fill: \"fill-muted-foreground\", stroke: \"stroke-muted-foreground\", background: \"bg-muted-foreground\", dash: undefined, symbol: symbolStar };\nconst DASHES = [undefined, \"6 4\", \"2 4\"] as const;\n\n/**\n * The style of series `index` (0-based), in fixed order: the colour follows the series, never its rank.\n * There are five colours. A sixth to fifteenth series reuses them with a dash; prefer folding a long tail\n * into \"Other\" or splitting the chart. A negative index is the neutral \"Other\".\n */\nexport function chartSeries(index: number): ChartSeriesStyle {\n  if (index < 0) return NEUTRAL;\n  const slot = PALETTE[index % PALETTE.length] ?? PALETTE[0];\n  return { ...slot, dash: DASHES[Math.floor(index / PALETTE.length) % DASHES.length] };\n}\n\n/** The path of a series' marker, centred on 0,0, about `radius` in reach. */\nexport function chartMarkPath(index: number, radius: number): string {\n  return symbol(chartSeries(index).symbol, radius * radius * 3.2)() ?? \"\";\n}\n\nexport type ChartMarkProps = Omit<ComponentProps<\"path\">, \"d\" | \"transform\"> & {\n  index: number;\n  x: number;\n  y: number;\n  radius?: number;\n  /** A 2px ring in the surface colour, so the mark stays legible where it crosses a line or another mark. */\n  ring?: boolean;\n};\n\n/** A series marker inside an SVG: the series' colour and its own shape. */\nexport function ChartMark({ index, x, y, radius = 4, ring = true, className, ...props }: ChartMarkProps) {\n  return (\n    <path\n      data-slot=\"chart-mark\"\n      d={chartMarkPath(index, radius)}\n      transform={`translate(${x},${y})`}\n      className={cn(chartSeries(index).fill, ring && \"stroke-background\", className)}\n      strokeWidth={ring ? 2 : undefined}\n      paintOrder=\"stroke\"\n      strokeLinejoin=\"round\"\n      {...props}\n    />\n  );\n}\n\n/* Formatting. The locale defaults to a fixed one so the server and the browser print the same text. */\n\nexport type ChartFormat = {\n  /** A BCP 47 locale for numbers and dates. Default \"en-US\". */\n  locale?: string;\n  /** The time zone dates are printed in. Default \"UTC\", so the server and the browser agree. */\n  timeZone?: string;\n  /** Replaces the number format everywhere: axis, labels, tooltip, table. */\n  formatValue?: (value: number) => string;\n};\n\nconst DEFAULT_LOCALE = \"en-US\";\nconst numberFormats = new Map<string, Intl.NumberFormat>();\nconst dateFormats = new Map<string, Intl.DateTimeFormat>();\n\nfunction numberFormat(locale: string, options: Intl.NumberFormatOptions): Intl.NumberFormat {\n  const key = `${locale}:${JSON.stringify(options)}`;\n  let format = numberFormats.get(key);\n  if (!format) {\n    format = new Intl.NumberFormat(locale, options);\n    numberFormats.set(key, format);\n  }\n  return format;\n}\n\n/** A number in full, for tooltips, labels and tables. */\nexport function formatNumber(value: number, locale: string = DEFAULT_LOCALE, options: Intl.NumberFormatOptions = { maximumFractionDigits: 2 }): string {\n  return numberFormat(locale, options).format(value);\n}\n\n/** The format for an axis: in full below 10,000, compact (10K, 1.2M) on an axis that reaches it. One style per axis. */\nexport function axisNumberFormatter(extent: number, locale: string = DEFAULT_LOCALE): (value: number) => string {\n  const format = numberFormat(locale, Math.abs(extent) >= 10000 ? { notation: \"compact\", maximumFractionDigits: 1 } : { maximumFractionDigits: 2 });\n  return (value) => format.format(value);\n}\n\n/** The format for dates on an axis (\"axis\") or in a tooltip and table (\"full\"), chosen by how much time the data spans. */\nexport function dateFormatter(spanMs: number, detail: \"axis\" | \"full\" = \"axis\", locale: string = DEFAULT_LOCALE, timeZone: string = \"UTC\"): (value: number | Date) => string {\n  const day = 86400000;\n  let options: Intl.DateTimeFormatOptions;\n  if (spanMs <= 2 * day) options = detail === \"axis\" ? { hour: \"numeric\", minute: \"2-digit\" } : { month: \"short\", day: \"numeric\", hour: \"numeric\", minute: \"2-digit\" };\n  else if (spanMs <= 366 * day) options = detail === \"axis\" ? { month: \"short\", day: \"numeric\" } : { year: \"numeric\", month: \"short\", day: \"numeric\" };\n  else if (spanMs <= 4 * 366 * day) options = detail === \"axis\" ? { month: \"short\", year: \"2-digit\" } : { year: \"numeric\", month: \"short\", day: \"numeric\" };\n  else options = detail === \"axis\" ? { year: \"numeric\" } : { year: \"numeric\", month: \"short\" };\n  const key = `${locale}:${timeZone}:${JSON.stringify(options)}`;\n  let format = dateFormats.get(key);\n  if (!format) {\n    format = new Intl.DateTimeFormat(locale, { ...options, timeZone });\n    dateFormats.set(key, format);\n  }\n  const resolved = format;\n  return (value) => resolved.format(value);\n}\n\n/** A close enough width for a short label at the axis text size, used to make room before drawing. */\nexport function estimateTextWidth(text: string, fontSize = 12): number {\n  return text.length * fontSize * 0.58;\n}\n\n/** A number from a data row, or null when the field is missing or not a finite number: a gap, not a zero. */\nexport function readNumber(row: object, key: string): number | null {\n  const value = (row as Record<string, unknown>)[key];\n  return typeof value === \"number\" && Number.isFinite(value) ? value : null;\n}\n\n/* Container, SVG root and the text alternative. */\n\nexport type ChartTable = {\n  caption?: string;\n  columns: readonly string[];\n  rows: readonly (readonly (string | number)[])[];\n};\n\n/** The data as a table for assistive technology. It is in the server markup, so it is there before the chart draws. */\nexport function ChartDataTable({ caption, columns, rows }: ChartTable) {\n  return (\n    <table data-slot=\"chart-table\" className=\"sr-only\">\n      {caption ? <caption>{caption}</caption> : null}\n      <thead>\n        <tr>\n          {columns.map((column, index) => (\n            <th key={index} scope=\"col\">\n              {column}\n            </th>\n          ))}\n        </tr>\n      </thead>\n      <tbody>\n        {rows.map((row, rowIndex) => (\n          <tr key={rowIndex}>\n            {row.map((cell, index) =>\n              index === 0 ? (\n                <th key={index} scope=\"row\">\n                  {cell}\n                </th>\n              ) : (\n                <td key={index}>{cell}</td>\n              ),\n            )}\n          </tr>\n        ))}\n      </tbody>\n    </table>\n  );\n}\n\nexport type ChartContainerProps = Omit<ComponentProps<\"div\">, \"children\"> & {\n  /** Width / height of the plot. The box keeps this ratio before the chart draws, so the layout never shifts. */\n  aspect?: number;\n  /** A fixed height in pixels instead of a ratio. */\n  height?: number;\n  /** The data as a visually hidden table: the chart's text alternative. */\n  table?: ChartTable;\n  /** Read out politely when it changes: the values under keyboard focus. */\n  announcement?: string;\n  /** Draws the chart at the measured size. Not called on the server or before the first measurement. */\n  children: (size: Size) => ReactNode;\n};\n\nexport function ChartContainer({ aspect = 16 / 9, height, table, announcement, className, style, children, ...props }: ChartContainerProps) {\n  const { ref, width, height: measuredHeight } = useSize<HTMLDivElement>();\n  return (\n    <div\n      ref={ref}\n      data-slot=\"chart\"\n      className={cn(\"relative w-full min-w-0\", className)}\n      style={{ ...(height === undefined ? { aspectRatio: String(aspect) } : { height }), ...style }}\n      {...props}\n    >\n      {/*\n        The drawing sits in a layer that takes no part in layout. If it were in the flow, a drawing one pixel\n        taller than the box (rounding) would stretch the box, which would be measured again and drawn taller:\n        a loop that grows the page without end.\n      */}\n      {width > 0 && measuredHeight > 0 ? (\n        <div data-slot=\"chart-layer\" className=\"absolute inset-0\">\n          {children({ width, height: measuredHeight })}\n        </div>\n      ) : null}\n      {table ? <ChartDataTable {...table} /> : null}\n      <span className=\"sr-only\" aria-live=\"polite\">\n        {announcement}\n      </span>\n    </div>\n  );\n}\n\nexport type ChartSvgProps = ComponentProps<\"svg\"> & {\n  /** What the chart shows, for assistive technology. */\n  label: string;\n  width: number;\n  height: number;\n  /** Focusable and driven by arrow keys. The chart supplies `onKeyDown`. */\n  interactive?: boolean;\n};\n\n/** The SVG root. It fades in once when it first draws, and not at all under reduced motion. */\nexport function ChartSvg({ label, width, height, interactive = false, className, children, ...props }: ChartSvgProps) {\n  return (\n    <svg\n      data-slot=\"chart-svg\"\n      role={interactive ? \"application\" : \"img\"}\n      aria-roledescription={interactive ? \"chart\" : undefined}\n      aria-label={label}\n      tabIndex={interactive ? 0 : undefined}\n      width={width}\n      height={height}\n      viewBox={`0 0 ${width} ${height}`}\n      className={cn(\"block overflow-visible text-xs animate-in fade-in-0 motion-reduce:animate-none\", interactive && \"touch-pan-y select-none\", className)}\n      {...props}\n    >\n      {children}\n    </svg>\n  );\n}\n\n/* Axes and grid. Recessive: hairlines one step off the surface, muted text. */\n\nexport type ChartTick = { offset: number; label: string };\n\n/** Hairlines across the plot at each offset: horizontal by default, vertical with `vertical`. */\nexport function ChartGrid({ offsets, from, to, vertical = false }: { offsets: readonly number[]; from: number; to: number; vertical?: boolean }) {\n  return (\n    <g data-slot=\"chart-grid\" aria-hidden=\"true\" className=\"stroke-border\" strokeWidth={1} shapeRendering=\"crispEdges\">\n      {offsets.map((offset, index) => (vertical ? <line key={index} x1={offset} x2={offset} y1={from} y2={to} /> : <line key={index} x1={from} x2={to} y1={offset} y2={offset} />))}\n    </g>\n  );\n}\n\n/** Tick labels under the plot (`side=\"bottom\"`, at height `at`) or to its left (`side=\"left\"`, ending at x `at`). */\nexport function ChartAxis({ side, ticks, at }: { side: \"bottom\" | \"left\"; ticks: readonly ChartTick[]; at: number }) {\n  return (\n    <g data-slot=\"chart-axis\" aria-hidden=\"true\" className=\"fill-muted-foreground tabular-nums\">\n      {ticks.map((tick, index) =>\n        side === \"bottom\" ? (\n          <text key={index} x={tick.offset} y={at} dy=\"1em\" textAnchor=\"middle\">\n            {tick.label}\n          </text>\n        ) : (\n          <text key={index} x={at} y={tick.offset} dy=\"0.32em\" textAnchor=\"end\">\n            {tick.label}\n          </text>\n        ),\n      )}\n    </g>\n  );\n}\n\n/* Tooltip and legend. */\n\nexport type ChartTooltipRow = { label: string; value: string; index?: number; mark?: \"line\" | \"rect\" };\n\nexport type ChartTooltipProps = Omit<ComponentProps<\"div\">, \"title\"> & {\n  /** The point it describes, in pixels from the container's top left. */\n  x: number;\n  y: number;\n  /** Which side of the point it sits on. Flip it past the middle so it stays inside the chart. */\n  side?: \"left\" | \"right\";\n  /** Where it sits against the point vertically. */\n  align?: \"top\" | \"center\";\n  title?: ReactNode;\n  rows?: readonly ChartTooltipRow[];\n};\n\n/** A small flat box that follows the active point. It repeats what the table says, so it is hidden from assistive technology. */\nexport function ChartTooltip({ x, y, side = \"right\", align = \"center\", title, rows, className, style, children, ...props }: ChartTooltipProps) {\n  const shift = `translate(${side === \"left\" ? \"calc(-100% - 12px)\" : \"12px\"}, ${align === \"center\" ? \"-50%\" : \"0px\"})`;\n  return (\n    <div\n      data-slot=\"chart-tooltip\"\n      aria-hidden=\"true\"\n      className={cn(\"pointer-events-none absolute left-0 top-0 z-10 w-max max-w-60 rounded-surface border bg-popover px-2.5 py-2 text-xs text-popover-foreground\", className)}\n      style={{ transform: `translate(${Math.round(x)}px, ${Math.round(y)}px) ${shift}`, ...style }}\n      {...props}\n    >\n      {title ? <div className=\"mb-1 text-muted-foreground\">{title}</div> : null}\n      {rows?.map((row, index) => (\n        <div key={index} className=\"flex items-center gap-2\">\n          {row.index === undefined ? null : <ChartKey index={row.index} mark={row.mark ?? \"line\"} />}\n          <span className=\"font-medium tabular-nums text-foreground\">{row.value}</span>\n          <span className=\"text-muted-foreground\">{row.label}</span>\n        </div>\n      ))}\n      {children}\n    </div>\n  );\n}\n\n/** The key of one series: its colour and its shape, on a short stroke for lines. */\nexport function ChartKey({ index, mark = \"line\" }: { index: number; mark?: \"line\" | \"rect\" }) {\n  const style = chartSeries(index);\n  return (\n    <svg data-slot=\"chart-key\" aria-hidden=\"true\" width={mark === \"line\" ? 20 : 12} height={12} className=\"shrink-0 overflow-visible\">\n      {mark === \"line\" ? (\n        <>\n          <line x1={1} x2={19} y1={6} y2={6} className={style.stroke} strokeWidth={2} strokeLinecap=\"round\" strokeDasharray={style.dash} />\n          <ChartMark index={index} x={10} y={6} radius={3.5} />\n        </>\n      ) : (\n        <ChartMark index={index} x={6} y={6} radius={5} ring={false} />\n      )}\n    </svg>\n  );\n}\n\nexport type ChartLegendItem = { label: string; index: number; value?: string };\n\nexport type ChartLegendProps = ComponentProps<\"ul\"> & {\n  items: readonly ChartLegendItem[];\n  /** \"line\" for lines; \"rect\" for bars, areas and slices. */\n  mark?: \"line\" | \"rect\";\n  /** A wrapping row, or one item per line with values at the end. */\n  orientation?: \"horizontal\" | \"vertical\";\n};\n\n/** Names every series beside its colour and its shape. Labels wear text colours, never the series colour. */\nexport function ChartLegend({ items, mark = \"line\", orientation = \"horizontal\", className, ...props }: ChartLegendProps) {\n  return (\n    <ul data-slot=\"chart-legend\" className={cn(\"flex text-xs text-muted-foreground\", orientation === \"horizontal\" ? \"flex-wrap gap-x-4 gap-y-1\" : \"flex-col gap-1.5\", className)} {...props}>\n      {items.map((item, index) => (\n        <li key={index} className=\"flex min-w-0 items-center gap-1.5\">\n          <ChartKey index={item.index} mark={mark} />\n          <span className=\"truncate\">{item.label}</span>\n          {item.value === undefined ? null : <span className=\"ms-auto ps-3 font-medium tabular-nums text-foreground\">{item.value}</span>}\n        </li>\n      ))}\n    </ul>\n  );\n}\n"
    }
  ],
  "meta": {
    "category": "viz",
    "when": "Building a chart of your own that should match the others. For the common forms use line-chart, area-chart, bar-chart, donut-chart, sparkline, heatmap or radial-progress directly.",
    "example": "<ChartContainer aspect={2} table={{ caption: \"Signups\", columns: [\"Day\", \"Signups\"], rows: [[\"Mon\", 4], [\"Tue\", 9]] }}>\n  {({ width, height }) => (\n    <ChartSvg label=\"Signups by day\" width={width} height={height}>\n      <rect x={0} y={height - 40} width={width / 3} height={40} className={chartSeries(0).fill} />\n      <rect x={width / 2} y={height - 90} width={width / 3} height={90} className={chartSeries(0).fill} />\n    </ChartSvg>\n  )}\n</ChartContainer>\n<ChartLegend items={[{ label: \"Signups\", index: 0 }]} mark=\"rect\" />",
    "client": true
  }
}
