{
  "$schema": "https://ui.shadcn.com/schema/registry-item.json",
  "name": "small-multiples",
  "type": "registry:component",
  "title": "Small Multiples",
  "description": "The same small chart repeated for each group (a region, a product) in a grid that fits its width, every panel on one shared scale so they can be compared at a glance, each read by arrow keys.",
  "categories": [
    "viz"
  ],
  "dependencies": [
    "d3-scale",
    "d3-shape"
  ],
  "devDependencies": [
    "@types/d3-scale",
    "@types/d3-shape"
  ],
  "registryDependencies": [
    "@rivier-ui/theme",
    "@rivier-ui/chart",
    "@rivier-ui/cn"
  ],
  "files": [
    {
      "path": "registry/viz/small-multiples.tsx",
      "type": "registry:component",
      "target": "components/viz/small-multiples.tsx",
      "content": "\"use client\";\n/**\n * @name small-multiples\n * @category viz\n * @description The same small chart repeated for each group (a region, a product) in a grid that fits its width, every panel on one shared scale so they can be compared at a glance, each read by arrow keys.\n * @when Comparing the shape of one measure across many groups, where one chart with many lines would tangle: more than five series, or groups of very different sizes. For up to five series on one chart use line-chart; for one value per group use bar-chart.\n * @example\n * <SmallMultiples\n *   label=\"Monthly visits by region\"\n *   data={[\n *     { region: \"North\", month: 1, visits: 40 }, { region: \"North\", month: 2, visits: 52 }, { region: \"North\", month: 3, visits: 61 },\n *     { region: \"South\", month: 1, visits: 30 }, { region: \"South\", month: 2, visits: 28 }, { region: \"South\", month: 3, visits: 35 },\n *   ]}\n *   facet=\"region\"\n *   x=\"month\"\n *   y=\"visits\"\n *   kind=\"area\"\n * />\n */\nimport { scaleBand, scaleLinear, scaleUtc } from \"d3-scale\";\nimport { area, line } from \"d3-shape\";\nimport { useId, useMemo, type ComponentProps, type PointerEvent } from \"react\";\nimport { cn } from \"@/lib/cn\";\nimport {\n  axisNumberFormatter,\n  ChartContainer,\n  ChartDataTable,\n  ChartEmpty,\n  chartSeries,\n  ChartSvg,\n  ChartTooltip,\n  dateFormatter,\n  formatNumber,\n  readNumber,\n  useChartCursor,\n  type ChartBaseProps,\n} from \"@/components/viz/chart\";\n\nexport type SmallMultiplesProps<T extends object> = ChartBaseProps & {\n  /** One object per point, every group's rows together. */\n  data: readonly T[];\n  /** The field naming each row's panel. */\n  facet: keyof T & string;\n  /** The field holding x: a number or Date (lines, areas) or a category name (bars). */\n  x: keyof T & string;\n  /** The field holding the value. */\n  y: keyof T & string;\n  /** The panels in order. Default: in order of first appearance. */\n  facets?: readonly string[];\n  /** The form of each panel. */\n  kind?: \"line\" | \"area\" | \"bar\";\n  /** Each panel on its own y scale. Default false: shared, so the panels can be compared. Say so in the label when it is true. */\n  independent?: boolean;\n  /** The narrowest a panel may be, in pixels, before the grid has fewer columns. Default 180. */\n  minPanelWidth?: number;\n  /** The names of x and y in the tooltip and the table. Default: the field names. */\n  xLabel?: string;\n  yLabel?: string;\n  /** Replaces the x format. */\n  formatX?: (value: number | Date | string) => string;\n  timeZone?: string;\n};\n\ntype Point = { x: number | string; y: number };\ntype Panel = { name: string; points: Point[] };\n\nexport function SmallMultiples<T extends object>({\n  data,\n  facet,\n  x,\n  y,\n  facets,\n  kind = \"line\",\n  independent = false,\n  minPanelWidth = 180,\n  xLabel,\n  yLabel,\n  formatX,\n  timeZone,\n  label,\n  aspect = 1.6,\n  height,\n  emptyLabel,\n  locale,\n  formatValue,\n  className,\n  style,\n  ...props\n}: SmallMultiplesProps<T>) {\n  const model = useMemo(() => {\n    const isTime = data.some((row) => (row as Record<string, unknown>)[x] instanceof Date);\n    const map = new Map<string, Point[]>();\n    for (const name of facets ?? []) map.set(name, []);\n    const categories: string[] = [];\n    for (const row of data) {\n      const value = readNumber(row, y);\n      if (value === null) continue;\n      const name = String((row as Record<string, unknown>)[facet] ?? \"\");\n      if (facets && !map.has(name)) continue;\n      const raw = (row as Record<string, unknown>)[x];\n      const at = kind === \"bar\" ? String(raw ?? \"\") : raw instanceof Date ? raw.getTime() : typeof raw === \"number\" ? raw : NaN;\n      if (typeof at === \"number\" && !Number.isFinite(at)) continue;\n      if (typeof at === \"string\" && !categories.includes(at)) categories.push(at);\n      const list = map.get(name) ?? [];\n      list.push({ x: at, y: value });\n      map.set(name, list);\n    }\n    const panels: Panel[] = [...map].map(([name, points]) => ({ name, points: kind === \"bar\" ? points : [...points].sort((a, b) => Number(a.x) - Number(b.x)) }));\n    const all = panels.flatMap((panel) => panel.points);\n    const ys = all.map((point) => point.y);\n    const xs = all.map((point) => Number(point.x)).filter(Number.isFinite);\n    return { panels, isTime, categories, yLow: Math.min(0, ...ys), yHigh: Math.max(0, ...ys), xLow: Math.min(...xs), xHigh: Math.max(...xs) };\n  }, [data, facet, x, y, facets, kind]);\n\n  const { panels, isTime } = model;\n  const number = formatValue ?? ((amount: number) => formatNumber(amount, locale));\n  const span = model.xHigh - model.xLow;\n  const fullX = (value: number | string): string =>\n    formatX\n      ? formatX(isTime && typeof value === \"number\" ? new Date(value) : value)\n      : typeof value === \"string\"\n        ? value\n        : isTime\n          ? dateFormatter(span, \"full\", locale, timeZone)(value)\n          : formatNumber(value, locale);\n  const table = {\n    caption: label,\n    columns: [facet, xLabel ?? x, yLabel ?? y],\n    rows: panels.flatMap((panel) => panel.points.map((point) => [panel.name, fullX(point.x), number(point.y)])),\n  };\n\n  return (\n    <figure data-slot=\"small-multiples\" aria-label={label} className={cn(\"m-0 w-full min-w-0\", className)} style={style} {...props}>\n      {panels.length === 0 ? (\n        <div className=\"relative h-32\">\n          <ChartEmpty>{emptyLabel}</ChartEmpty>\n        </div>\n      ) : (\n        <ul className=\"grid gap-4\" style={{ gridTemplateColumns: `repeat(auto-fill, minmax(min(100%, ${minPanelWidth}px), 1fr))` }}>\n          {panels.map((panel) => (\n            <SmallMultiplesPanel\n              key={panel.name}\n              panel={panel}\n              kind={kind}\n              isTime={isTime}\n              categories={model.categories}\n              xDomain={[model.xLow, model.xHigh]}\n              yDomain={independent ? [Math.min(0, ...panel.points.map((p) => p.y)), Math.max(0, ...panel.points.map((p) => p.y))] : [model.yLow, model.yHigh]}\n              aspect={aspect}\n              height={height}\n              number={number}\n              fullX={fullX}\n              yName={yLabel ?? y}\n              locale={locale}\n              formatValue={formatValue}\n            />\n          ))}\n        </ul>\n      )}\n      <ChartDataTable {...table} />\n    </figure>\n  );\n}\n\ntype PanelProps = {\n  panel: Panel;\n  kind: \"line\" | \"area\" | \"bar\";\n  isTime: boolean;\n  categories: string[];\n  xDomain: [number, number];\n  yDomain: [number, number];\n  aspect: number;\n  height: number | undefined;\n  number: (value: number) => string;\n  fullX: (value: number | string) => string;\n  yName: string;\n  locale: string | undefined;\n  formatValue: ((value: number) => string) | undefined;\n};\n\n/** One panel. Exported for a project that lays panels out itself; most use SmallMultiples. */\nexport function SmallMultiplesPanel({\n  panel,\n  kind,\n  isTime,\n  categories,\n  xDomain,\n  yDomain,\n  aspect,\n  height,\n  number,\n  fullX,\n  yName,\n  locale,\n  formatValue,\n  className,\n  ...props\n}: PanelProps & Omit<ComponentProps<\"li\">, \"children\">) {\n  const id = useId();\n  const cursor = useChartCursor(panel.points.length);\n  const current = cursor.active === null ? undefined : panel.points[cursor.active];\n  const axisY = formatValue ?? axisNumberFormatter(Math.max(Math.abs(yDomain[0]), Math.abs(yDomain[1])), locale);\n  return (\n    <li data-slot=\"small-multiples-panel\" className={cn(\"flex min-w-0 flex-col gap-1\", className)} {...props}>\n      <span id={id} className=\"truncate text-sm font-medium\">\n        {panel.name}\n      </span>\n      <ChartContainer aspect={aspect} height={height} announcement={cursor.keyboard && current ? `${panel.name}, ${fullX(current.x)}: ${number(current.y)}` : \"\"}>\n        {({ width, height: plotHeight }) => {\n          const top = 14;\n          const bottom = 4;\n          const sy = scaleLinear()\n            .domain(yDomain[0] === yDomain[1] ? [0, 1] : yDomain)\n            .nice(3)\n            .range([plotHeight - bottom, top]);\n          const [, highTick = 0] = sy.domain();\n          const bars = scaleBand<string>().domain(categories).range([0, width]).paddingInner(0.2);\n          const domain: [number, number] = xDomain[0] === xDomain[1] ? [xDomain[0], xDomain[0] + 1] : xDomain;\n          const timeScale = scaleUtc().domain(domain).range([2, width - 2]);\n          const numberScale = scaleLinear().domain(domain).range([2, width - 2]);\n          const linear = (value: number): number => (isTime ? timeScale(value) : numberScale(value));\n          const sx = (value: number | string): number => (kind === \"bar\" ? (bars(String(value)) ?? 0) + bars.bandwidth() / 2 : linear(Number(value)));\n          const linePath = line<Point>()\n            .x((p) => sx(p.x))\n            .y((p) => sy(p.y))(panel.points);\n          const areaPath =\n            kind === \"area\"\n              ? area<Point>()\n                  .x((p) => sx(p.x))\n                  .y0(sy(0))\n                  .y1((p) => sy(p.y))(panel.points)\n              : null;\n          const onPointerMove = (event: PointerEvent<SVGSVGElement>): void => {\n            const px = event.clientX - event.currentTarget.getBoundingClientRect().left;\n            let best = 0;\n            panel.points.forEach((point, index) => {\n              if (Math.abs(sx(point.x) - px) < Math.abs(sx(panel.points[best]?.x ?? 0) - px)) best = index;\n            });\n            cursor.point(best);\n          };\n          const style = chartSeries(0);\n          const shown = current ? { x: sx(current.x), y: sy(current.y) } : undefined;\n          return (\n            <>\n              <ChartSvg label={panel.name} aria-labelledby={id} width={width} height={plotHeight} interactive {...cursor.svgProps} onPointerMove={onPointerMove}>\n                <g aria-hidden=\"true\">\n                  <line x1={0} x2={width} y1={sy(highTick)} y2={sy(highTick)} className=\"stroke-border\" shapeRendering=\"crispEdges\" />\n                  <text x={0} y={sy(highTick) - 3} className=\"fill-muted-foreground tabular-nums\">\n                    {axisY(highTick)}\n                  </text>\n                  <line x1={0} x2={width} y1={sy(0)} y2={sy(0)} className=\"stroke-border-strong\" shapeRendering=\"crispEdges\" />\n                  {areaPath ? <path d={areaPath} className={style.fill} fillOpacity={0.25} /> : null}\n                  {kind !== \"bar\" && linePath ? <path d={linePath} fill=\"none\" className={style.stroke} strokeWidth={2} strokeLinejoin=\"round\" /> : null}\n                  {kind === \"bar\"\n                    ? panel.points.map((point, index) => {\n                        const w = Math.max(1, Math.min(16, bars.bandwidth()));\n                        const y0 = sy(0);\n                        const y1 = sy(point.y);\n                        return (\n                          <rect\n                            key={index}\n                            x={sx(point.x) - w / 2}\n                            y={Math.min(y0, y1)}\n                            width={w}\n                            height={Math.abs(y0 - y1)}\n                            className={cn(style.fill, cursor.active !== null && cursor.active !== index && \"opacity-45\")}\n                          />\n                        );\n                      })\n                    : null}\n                  {shown ? <circle cx={shown.x} cy={shown.y} r={4} className={cn(style.fill, \"stroke-background\")} strokeWidth={2} /> : null}\n                </g>\n              </ChartSvg>\n              {shown && current ? (\n                <ChartTooltip x={shown.x} y={shown.y} side={shown.x > width / 2 ? \"left\" : \"right\"} title={fullX(current.x)} rows={[{ label: yName, value: number(current.y) }]} />\n              ) : null}\n            </>\n          );\n        }}\n      </ChartContainer>\n    </li>\n  );\n}\n"
    }
  ],
  "meta": {
    "category": "viz",
    "when": "Comparing the shape of one measure across many groups, where one chart with many lines would tangle: more than five series, or groups of very different sizes. For up to five series on one chart use line-chart; for one value per group use bar-chart.",
    "example": "<SmallMultiples\n  label=\"Monthly visits by region\"\n  data={[\n    { region: \"North\", month: 1, visits: 40 }, { region: \"North\", month: 2, visits: 52 }, { region: \"North\", month: 3, visits: 61 },\n    { region: \"South\", month: 1, visits: 30 }, { region: \"South\", month: 2, visits: 28 }, { region: \"South\", month: 3, visits: 35 },\n  ]}\n  facet=\"region\"\n  x=\"month\"\n  y=\"visits\"\n  kind=\"area\"\n/>",
    "client": true
  }
}
