{
  "$schema": "https://ui.shadcn.com/schema/registry-item.json",
  "name": "dot-plot",
  "type": "registry:component",
  "title": "Dot Plot",
  "description": "Values as dots along a shared axis, one row per category: plain dots for one or more series, a lollipop (a stick to the dot), a dumbbell (two values joined, for a before and after), or a beeswarm (every single value as its own dot, packed so none overlap).",
  "categories": [
    "viz"
  ],
  "dependencies": [
    "d3-scale"
  ],
  "devDependencies": [
    "@types/d3-scale"
  ],
  "registryDependencies": [
    "@rivier-ui/theme",
    "@rivier-ui/chart",
    "@rivier-ui/cn"
  ],
  "files": [
    {
      "path": "registry/viz/dot-plot.tsx",
      "type": "registry:component",
      "target": "components/viz/dot-plot.tsx",
      "content": "\"use client\";\n/**\n * @name dot-plot\n * @category viz\n * @description Values as dots along a shared axis, one row per category: plain dots for one or more series, a lollipop (a stick to the dot), a dumbbell (two values joined, for a before and after), or a beeswarm (every single value as its own dot, packed so none overlap).\n * @when Comparing values across categories with less ink than bars, especially when zero is not meaningful (dot, dumbbell), showing a change between two moments per category (dumbbell), or showing every observation in a few groups (beeswarm). For totals from zero use bar-chart; for a summary of spread use box-plot.\n * @example\n * <DotPlot\n *   label=\"Satisfaction before and after\"\n *   data={[\n *     { team: \"Support\", before: 62, after: 78 },\n *     { team: \"Sales\", before: 70, after: 74 },\n *     { team: \"Product\", before: 55, after: 71 },\n *   ]}\n *   y=\"team\"\n *   series={[{ key: \"before\", label: \"Before\" }, { key: \"after\", label: \"After\" }]}\n *   variant=\"dumbbell\"\n * />\n */\nimport { scaleBand } from \"d3-scale\";\nimport { useMemo } from \"react\";\nimport { cn } from \"@/lib/cn\";\nimport {\n  axisNumberFormatter,\n  ChartAxis,\n  ChartContainer,\n  ChartEmpty,\n  ChartGrid,\n  ChartLegend,\n  ChartMark,\n  chartLinear,\n  chartSeries,\n  ChartSvg,\n  ChartTooltip,\n  fitText,\n  formatNumber,\n  readNumber,\n  useChartCursor,\n  widestText,\n  type ChartBaseProps,\n  type ChartSeries,\n} from \"@/components/viz/chart\";\n\nexport type DotPlotProps<T extends object> = ChartBaseProps & {\n  data: readonly T[];\n  /** The field naming each row: a category, or a group in a beeswarm. */\n  y: keyof T & string;\n  /** The values. A lollipop and a beeswarm use the first; a dumbbell joins the first two. */\n  series: readonly ChartSeries<T>[];\n  variant?: \"dot\" | \"lollipop\" | \"dumbbell\" | \"beeswarm\";\n  /** Start the axis at zero. Default: true for a lollipop, false otherwise. */\n  zero?: boolean;\n  /** A field naming each dot in a beeswarm, for the tooltip and the table. */\n  name?: keyof T & string;\n  showGrid?: boolean;\n  showLegend?: boolean;\n};\n\ntype Row = { name: string; values: (number | null)[] };\ntype Swarm = { group: number; value: number; name: string; offset: number };\n\n/** Packs dots of radius r along x so none overlap, each as close to its row's centre line as it can be. */\nfunction dodge(values: { value: number; px: number; index: number }[], r: number): Map<number, number> {\n  const placed: { px: number; offset: number }[] = [];\n  const offsets = new Map<number, number>();\n  for (const item of [...values].sort((a, b) => a.px - b.px)) {\n    let offset = 0;\n    for (let step = 0; step < 400; step++) {\n      const candidate = step === 0 ? 0 : Math.ceil(step / 2) * (step % 2 ? 1 : -1) * r * 0.5;\n      if (placed.every((p) => Math.hypot(p.px - item.px, p.offset - candidate) >= r * 2)) {\n        offset = candidate;\n        break;\n      }\n    }\n    placed.push({ px: item.px, offset });\n    offsets.set(item.index, offset);\n  }\n  return offsets;\n}\n\nexport function DotPlot<T extends object>({\n  data,\n  y,\n  series,\n  variant = \"dot\",\n  zero,\n  name,\n  showGrid = true,\n  showLegend,\n  label,\n  aspect,\n  height,\n  emptyLabel,\n  locale,\n  formatValue,\n  className,\n  ...props\n}: DotPlotProps<T>) {\n  const swarm = variant === \"beeswarm\";\n  const used = variant === \"lollipop\" || swarm ? series.slice(0, 1) : variant === \"dumbbell\" ? series.slice(0, 2) : series;\n  const model = useMemo(() => {\n    const read = (row: T, key: string): string => String((row as Record<string, unknown>)[key] ?? \"\");\n    if (swarm) {\n      const groups = [...new Set(data.map((row) => read(row, y)))];\n      const first = used[0];\n      const dots: Swarm[] = first\n        ? data.flatMap((row, index) => {\n            const value = readNumber(row, first.key);\n            return value === null ? [] : [{ group: groups.indexOf(read(row, y)), value, name: name ? read(row, name) : String(index + 1), offset: 0 }];\n          })\n        : [];\n      dots.sort((a, b) => a.group - b.group || a.value - b.value);\n      return { rows: groups.map((g): Row => ({ name: g, values: [] })), dots };\n    }\n    return { rows: data.map((row): Row => ({ name: read(row, y), values: used.map((s) => readNumber(row, s.key)) })), dots: [] as Swarm[] };\n  }, [data, y, used, swarm, name]);\n  const { rows, dots } = model;\n  const cursor = useChartCursor(swarm ? dots.length : rows.length);\n  const number = formatValue ?? ((value: number) => formatNumber(value, locale));\n  const table = swarm\n    ? { caption: label, columns: [name ?? \"#\", y, used[0]?.label ?? \"\"], rows: dots.map((d) => [d.name, rows[d.group]?.name ?? \"\", number(d.value)]) }\n    : { caption: label, columns: [y, ...used.map((s) => s.label)], rows: rows.map((row) => [row.name, ...row.values.map((v) => (v === null ? \"\" : number(v)))]) };\n  const rowReading = (row: Row): { label: string; value: string; index: number }[] =>\n    used.flatMap((s, i) => (row.values[i] === null || row.values[i] === undefined ? [] : [{ label: s.label, value: number(row.values[i] as number), index: i }]));\n  const currentRow = !swarm && cursor.active !== null ? rows[cursor.active] : undefined;\n  const currentDot = swarm && cursor.active !== null ? dots[cursor.active] : undefined;\n  const announcement = !cursor.keyboard\n    ? \"\"\n    : currentRow\n      ? `${currentRow.name}: ${rowReading(currentRow)\n          .map((r) => `${r.label} ${r.value}`)\n          .join(\", \")}`\n      : currentDot\n        ? `${currentDot.name}, ${rows[currentDot.group]?.name ?? \"\"}: ${number(currentDot.value)}`\n        : \"\";\n  const legend = showLegend ?? (!swarm && used.length > 1);\n  const fromZero = zero ?? variant === \"lollipop\";\n\n  return (\n    <div data-slot=\"dot-plot\" className={cn(\"flex w-full min-w-0 flex-col gap-3\", className)} {...props}>\n      {legend ? <ChartLegend items={used.map((s, i) => ({ label: s.label, index: i }))} mark=\"rect\" /> : null}\n      <ChartContainer aspect={aspect} height={height ?? Math.max(120, rows.length * (swarm ? 72 : 36) + 36)} table={table} announcement={announcement}>\n        {({ width, height: plotHeight }) => {\n          const values = swarm ? dots.map((d) => d.value) : rows.flatMap((row) => row.values.filter((v): v is number => v !== null));\n          if (values.length === 0) return <ChartEmpty>{emptyLabel}</ChartEmpty>;\n          const bottom = 26;\n          const nameRoom = Math.min(Math.round(width * 0.3), widestText(rows.map((r) => r.name)) + 12);\n          const sx = chartLinear(Math.min(...values, ...(fromZero ? [0] : [])), Math.max(...values, ...(fromZero ? [0] : [])), [nameRoom, width - 12], 80);\n          const axis = formatValue ?? axisNumberFormatter(Math.max(...values.map(Math.abs)), locale);\n          const band = scaleBand<number>()\n            .domain(rows.map((_, i) => i))\n            .range([4, plotHeight - bottom])\n            .paddingInner(0.1);\n          const mid = (i: number): number => (band(i) ?? 0) + band.bandwidth() / 2;\n          const r = swarm ? Math.max(2.5, Math.min(5, band.bandwidth() / 10)) : 5;\n          // Each row is packed on its own, so dots of one group never push those of another.\n          const offsets = new Map<number, number>();\n          if (swarm) {\n            rows.forEach((_, g) => {\n              const mine = dots.flatMap((d, index) => (d.group === g ? [{ value: d.value, px: sx.scale(d.value), index }] : []));\n              for (const [index, offset] of dodge(mine, r)) offsets.set(index, offset);\n            });\n          }\n          const offsetOf = (index: number): number => Math.max(-band.bandwidth() / 2 + r, Math.min(band.bandwidth() / 2 - r, offsets.get(index) ?? 0));\n          const tip =\n            currentRow && cursor.active !== null\n              ? { x: sx.scale(Math.max(...currentRow.values.filter((v): v is number => v !== null))), y: mid(cursor.active) }\n              : currentDot && cursor.active !== null\n                ? { x: sx.scale(currentDot.value), y: mid(currentDot.group) + offsetOf(cursor.active) }\n                : undefined;\n          return (\n            <>\n              <ChartSvg label={label} width={width} height={plotHeight} interactive {...cursor.svgProps}>\n                {showGrid ? <ChartGrid offsets={sx.ticks.map((t) => sx.scale(t))} from={4} to={plotHeight - bottom} vertical /> : null}\n                <ChartAxis side=\"bottom\" at={plotHeight - bottom + 6} ticks={sx.ticks.map((t) => ({ offset: sx.scale(t), label: axis(t) }))} />\n                <ChartAxis side=\"left\" at={nameRoom - 8} ticks={rows.map((row, i) => ({ offset: mid(i), label: fitText(row.name, nameRoom - 12) }))} />\n                <g aria-hidden=\"true\">\n                  {!swarm\n                    ? rows.map((row, i) => {\n                        const present = row.values.map((v, s) => ({ v, s })).filter((item): item is { v: number; s: number } => item.v !== null);\n                        const dim = cursor.active !== null && cursor.active !== i;\n                        return (\n                          <g key={i} onPointerEnter={() => cursor.point(i)} className={cn(\"transition-opacity duration-instant motion-reduce:transition-none\", dim && \"opacity-40\")}>\n                            <rect x={0} y={band(i) ?? 0} width={width} height={band.bandwidth()} fill=\"transparent\" />\n                            <line x1={nameRoom} x2={width - 12} y1={mid(i)} y2={mid(i)} className=\"stroke-border\" strokeDasharray=\"1 3\" />\n                            {variant === \"lollipop\" && present[0] ? (\n                              <line x1={sx.scale(0)} x2={sx.scale(present[0].v)} y1={mid(i)} y2={mid(i)} className={chartSeries(0).stroke} strokeWidth={2} />\n                            ) : null}\n                            {variant === \"dumbbell\" && present.length === 2 ? (\n                              <line x1={sx.scale(present[0]?.v ?? 0)} x2={sx.scale(present[1]?.v ?? 0)} y1={mid(i)} y2={mid(i)} className=\"stroke-muted-foreground\" strokeWidth={2.5} />\n                            ) : null}\n                            {present.map((item) => (\n                              <ChartMark key={item.s} index={item.s} x={sx.scale(item.v)} y={mid(i)} radius={r} />\n                            ))}\n                          </g>\n                        );\n                      })\n                    : dots.map((d, i) => (\n                        <circle\n                          key={i}\n                          cx={sx.scale(d.value)}\n                          cy={mid(d.group) + offsetOf(i)}\n                          r={r}\n                          className={cn(\n                            chartSeries(0).fill,\n                            \"stroke-background transition-opacity duration-instant motion-reduce:transition-none\",\n                            cursor.active !== null && cursor.active !== i && \"opacity-50\",\n                          )}\n                          strokeWidth={1}\n                          onPointerEnter={() => cursor.point(i)}\n                        />\n                      ))}\n                  {tip ? <circle cx={tip.x} cy={tip.y} r={r + 3} fill=\"none\" className=\"stroke-foreground\" strokeWidth={2} /> : null}\n                </g>\n              </ChartSvg>\n              {tip && currentRow ? (\n                <ChartTooltip x={tip.x} y={tip.y} side={tip.x > width / 2 ? \"left\" : \"right\"} title={currentRow.name} rows={rowReading(currentRow).map((row) => ({ ...row, mark: \"rect\" as const }))} />\n              ) : null}\n              {tip && currentDot ? (\n                <ChartTooltip\n                  x={tip.x}\n                  y={tip.y}\n                  side={tip.x > width / 2 ? \"left\" : \"right\"}\n                  title={currentDot.name}\n                  rows={[{ label: rows[currentDot.group]?.name ?? \"\", value: number(currentDot.value) }]}\n                />\n              ) : null}\n            </>\n          );\n        }}\n      </ChartContainer>\n    </div>\n  );\n}\n"
    }
  ],
  "meta": {
    "category": "viz",
    "when": "Comparing values across categories with less ink than bars, especially when zero is not meaningful (dot, dumbbell), showing a change between two moments per category (dumbbell), or showing every observation in a few groups (beeswarm). For totals from zero use bar-chart; for a summary of spread use box-plot.",
    "example": "<DotPlot\n  label=\"Satisfaction before and after\"\n  data={[\n    { team: \"Support\", before: 62, after: 78 },\n    { team: \"Sales\", before: 70, after: 74 },\n    { team: \"Product\", before: 55, after: 71 },\n  ]}\n  y=\"team\"\n  series={[{ key: \"before\", label: \"Before\" }, { key: \"after\", label: \"After\" }]}\n  variant=\"dumbbell\"\n/>",
    "client": true
  }
}
