{
  "$schema": "https://ui.shadcn.com/schema/registry-item.json",
  "name": "chord-diagram",
  "type": "registry:component",
  "title": "Chord Diagram",
  "description": "Flows between the members of one group, both ways, around a circle: each member an arc sized by all it sends, each ribbon joining two members with ends as wide as what goes each way, lit with its member on hover or focus.",
  "categories": [
    "viz"
  ],
  "dependencies": [
    "d3-shape"
  ],
  "devDependencies": [
    "@types/d3-shape"
  ],
  "registryDependencies": [
    "@rivier-ui/theme",
    "@rivier-ui/chart",
    "@rivier-ui/cn"
  ],
  "files": [
    {
      "path": "registry/viz/chord-diagram.tsx",
      "type": "registry:component",
      "target": "components/viz/chord-diagram.tsx",
      "content": "\"use client\";\n/**\n * @name chord-diagram\n * @category viz\n * @description Flows between the members of one group, both ways, around a circle: each member an arc sized by all it sends, each ribbon joining two members with ends as wide as what goes each way, lit with its member on hover or focus.\n * @when Showing exchanges within a set where both directions matter: moves between regions, trade between countries, messages between teams. Keep it to about a dozen members. For flows in one direction through stages use sankey-chart; for links without amounts use network-graph.\n * @example\n * <ChordDiagram\n *   label=\"Moves between neighbourhoods\"\n *   names={[\"North\", \"South\", \"East\"]}\n *   matrix={[\n *     [0, 120, 40],\n *     [80, 0, 60],\n *     [30, 90, 0],\n *   ]}\n * />\n */\nimport { arc } from \"d3-shape\";\nimport { useMemo } from \"react\";\nimport { cn } from \"@/lib/cn\";\nimport { ChartContainer, ChartEmpty, chartSeries, ChartSvg, ChartTooltip, fitText, formatNumber, useChartCursor, type ChartBaseProps } from \"@/components/viz/chart\";\n\nexport type ChordDiagramLabels = { from: string; to: string; value: string; sends: string; receives: string };\n\nexport type ChordDiagramProps = ChartBaseProps & {\n  /** The members, in order round the circle. */\n  names: readonly string[];\n  /** matrix[i][j]: how much member i sends to member j. Square, one row and one column per name. */\n  matrix: readonly (readonly number[])[];\n  labels?: Partial<ChordDiagramLabels>;\n};\n\nconst LABELS: ChordDiagramLabels = { from: \"From\", to: \"To\", value: \"Amount\", sends: \"Sends\", receives: \"Receives\" };\nconst PAD = 0.04;\n\ntype Span = { start: number; end: number };\ntype Group = Span & { index: number; total: number };\ntype Chord = { a: number; b: number; ab: number; ba: number; sourceSpan: Span; targetSpan: Span };\n\nexport function ChordDiagram({ names, matrix, labels: given, label, aspect = 1, height, emptyLabel, locale, formatValue, className, ...props }: ChordDiagramProps) {\n  const labels = { ...LABELS, ...given };\n  const layout = useMemo(() => {\n    const n = names.length;\n    const at = (i: number, j: number): number => Math.max(0, matrix[i]?.[j] ?? 0);\n    const totals = names.map((_, i) => names.reduce((sum, __, j) => sum + at(i, j), 0));\n    const sum = totals.reduce((a, b) => a + b, 0);\n    const k = sum > 0 ? (2 * Math.PI - PAD * n) / sum : 0;\n    const groups: Group[] = [];\n    // Within each member's arc, the slices for each partner in order: subgroup[i][j] is i's share sent to j.\n    const slices: Span[][] = [];\n    let angle = 0;\n    for (let i = 0; i < n; i++) {\n      const start = angle;\n      const row: Span[] = [];\n      for (let j = 0; j < n; j++) {\n        const width = at(i, j) * k;\n        row.push({ start: angle, end: angle + width });\n        angle += width;\n      }\n      slices.push(row);\n      groups.push({ index: i, start, end: angle, total: totals[i] ?? 0 });\n      angle += PAD;\n    }\n    const chords: Chord[] = [];\n    for (let i = 0; i < n; i++) {\n      for (let j = i; j < n; j++) {\n        if (at(i, j) + at(j, i) <= 0) continue;\n        chords.push({ a: i, b: j, ab: at(i, j), ba: at(j, i), sourceSpan: slices[i]?.[j] ?? { start: 0, end: 0 }, targetSpan: slices[j]?.[i] ?? { start: 0, end: 0 } });\n      }\n    }\n    const receives = names.map((_, j) => names.reduce((s, __, i) => s + at(i, j), 0));\n    return { groups, chords, sum, receives };\n  }, [names, matrix]);\n  const { groups, chords, sum, receives } = layout;\n  const cursor = useChartCursor(groups.length + chords.length);\n  const number = formatValue ?? ((value: number) => formatNumber(value, locale));\n  const table = {\n    caption: label,\n    columns: [labels.from, labels.to, labels.value],\n    rows: names.flatMap((from, i) => names.flatMap((to, j) => ((matrix[i]?.[j] ?? 0) > 0 ? [[from, to, number(matrix[i]?.[j] ?? 0)]] : []))),\n  };\n  const colour = (i: number): number => (i < 5 ? i : -1);\n  const reading = (index: number): { title: string; rows: { label: string; value: string }[] } => {\n    const group = groups[index];\n    if (group)\n      return {\n        title: names[group.index] ?? \"\",\n        rows: [\n          { label: labels.sends, value: number(group.total) },\n          { label: labels.receives, value: number(receives[group.index] ?? 0) },\n        ],\n      };\n    const chord = chords[index - groups.length];\n    if (!chord) return { title: \"\", rows: [] };\n    const a = names[chord.a] ?? \"\";\n    const b = names[chord.b] ?? \"\";\n    return {\n      title: chord.a === chord.b ? a : `${a} ↔ ${b}`,\n      rows: [{ label: `${a} → ${b}`, value: number(chord.ab) }, ...(chord.a === chord.b ? [] : [{ label: `${b} → ${a}`, value: number(chord.ba) }])],\n    };\n  };\n  const current = cursor.active === null ? undefined : reading(cursor.active);\n\n  return (\n    <div data-slot=\"chord-diagram\" className={cn(\"flex w-full min-w-0 flex-col gap-3\", className)} {...props}>\n      <ChartContainer\n        aspect={aspect}\n        height={height}\n        table={table}\n        announcement={cursor.keyboard && current ? `${current.title}: ${current.rows.map((row) => `${row.label} ${row.value}`).join(\", \")}` : \"\"}\n      >\n        {({ width, height: plotHeight }) => {\n          if (sum <= 0) return <ChartEmpty>{emptyLabel}</ChartEmpty>;\n          const outer = Math.max(20, Math.min(width, plotHeight) / 2 - 56);\n          const inner = outer - 12;\n          const cx = width / 2;\n          const cy = plotHeight / 2;\n          const ring = arc<Span>()\n            .innerRadius(inner)\n            .outerRadius(outer)\n            .startAngle((s) => s.start)\n            .endAngle((s) => s.end)\n            .cornerRadius(2);\n          const point = (angle: number, r: number): string => `${Math.sin(angle) * r},${-Math.cos(angle) * r}`;\n          const ribbon = (c: Chord): string => {\n            const s = c.sourceSpan;\n            const t = c.targetSpan;\n            const r = inner - 1;\n            const large = (span: Span): number => (span.end - span.start > Math.PI ? 1 : 0);\n            return `M${point(s.start, r)}A${r},${r} 0 ${large(s)} 1 ${point(s.end, r)}Q0,0 ${point(t.start, r)}A${r},${r} 0 ${large(t)} 1 ${point(t.end, r)}Q0,0 ${point(s.start, r)}Z`;\n          };\n          const activeGroup = cursor.active !== null && cursor.active < groups.length ? cursor.active : null;\n          const activeChord = cursor.active !== null && cursor.active >= groups.length ? chords[cursor.active - groups.length] : undefined;\n          const lit = (c: Chord): boolean => c === activeChord || (activeGroup !== null && (c.a === activeGroup || c.b === activeGroup));\n          const anchorAngle =\n            activeGroup !== null ? ((groups[activeGroup]?.start ?? 0) + (groups[activeGroup]?.end ?? 0)) / 2 : activeChord ? (activeChord.sourceSpan.start + activeChord.sourceSpan.end) / 2 : 0;\n          const anchor = { x: cx + Math.sin(anchorAngle) * (activeGroup !== null ? outer : inner * 0.6), y: cy - Math.cos(anchorAngle) * (activeGroup !== null ? outer : inner * 0.6) };\n          return (\n            <>\n              <ChartSvg label={label} width={width} height={plotHeight} interactive {...cursor.svgProps}>\n                <g transform={`translate(${cx},${cy})`} aria-hidden=\"true\">\n                  {chords.map((c, i) => (\n                    <path\n                      key={i}\n                      d={ribbon(c)}\n                      className={cn(chartSeries(colour(c.ab >= c.ba ? c.a : c.b)).fill, \"stroke-background transition-opacity duration-instant motion-reduce:transition-none\")}\n                      fillOpacity={cursor.active === null ? 0.45 : lit(c) ? 0.7 : 0.08}\n                      strokeWidth={0.75}\n                      onPointerEnter={() => cursor.point(groups.length + i)}\n                    />\n                  ))}\n                  {groups.map((g) => {\n                    const mid = (g.start + g.end) / 2;\n                    const right = Math.sin(mid) >= 0;\n                    return (\n                      <g key={g.index} onPointerEnter={() => cursor.point(g.index)}>\n                        <path d={ring(g) ?? \"\"} className={chartSeries(colour(g.index)).fill} />\n                        <text\n                          transform={`translate(${Math.sin(mid) * (outer + 8)},${-Math.cos(mid) * (outer + 8)})`}\n                          dy=\"0.32em\"\n                          textAnchor={right ? \"start\" : \"end\"}\n                          className={cn(\"text-xs\", activeGroup === g.index ? \"fill-foreground font-medium\" : \"fill-muted-foreground\")}\n                        >\n                          {fitText(names[g.index] ?? \"\", 52)}\n                        </text>\n                      </g>\n                    );\n                  })}\n                  {activeGroup !== null && groups[activeGroup] ? <path d={ring(groups[activeGroup]) ?? \"\"} fill=\"none\" className=\"stroke-foreground\" strokeWidth={2} /> : null}\n                  {activeChord ? <path d={ribbon(activeChord)} fill=\"none\" className=\"stroke-foreground\" strokeWidth={1.5} /> : null}\n                </g>\n              </ChartSvg>\n              {current ? <ChartTooltip x={anchor.x} y={anchor.y} side={anchor.x > cx ? \"left\" : \"right\"} title={current.title} rows={current.rows} /> : null}\n            </>\n          );\n        }}\n      </ChartContainer>\n    </div>\n  );\n}\n"
    }
  ],
  "meta": {
    "category": "viz",
    "when": "Showing exchanges within a set where both directions matter: moves between regions, trade between countries, messages between teams. Keep it to about a dozen members. For flows in one direction through stages use sankey-chart; for links without amounts use network-graph.",
    "example": "<ChordDiagram\n  label=\"Moves between neighbourhoods\"\n  names={[\"North\", \"South\", \"East\"]}\n  matrix={[\n    [0, 120, 40],\n    [80, 0, 60],\n    [30, 90, 0],\n  ]}\n/>",
    "client": true
  }
}
