{
  "$schema": "https://ui.shadcn.com/schema/registry-item.json",
  "name": "network-graph",
  "type": "registry:component",
  "title": "Network Graph",
  "description": "Things and the links between them, placed by a force layout that is run to rest before it is drawn (so it is the same every time and never moves on its own), with each node's links lit on hover or focus and every node reachable by arrow keys.",
  "categories": [
    "viz"
  ],
  "dependencies": [
    "d3-force"
  ],
  "devDependencies": [
    "@types/d3-force"
  ],
  "registryDependencies": [
    "@rivier-ui/theme",
    "@rivier-ui/chart",
    "@rivier-ui/cn"
  ],
  "files": [
    {
      "path": "registry/viz/network-graph.tsx",
      "type": "registry:component",
      "target": "components/viz/network-graph.tsx",
      "content": "\"use client\";\n/**\n * @name network-graph\n * @category viz\n * @description Things and the links between them, placed by a force layout that is run to rest before it is drawn (so it is the same every time and never moves on its own), with each node's links lit on hover or focus and every node reachable by arrow keys.\n * @when Showing who or what is connected to what: clusters, bridges between groups, the most linked items. Keep it to a few hundred nodes. For amounts flowing in one direction use sankey-chart; for a hierarchy use treemap or tree-view; for a process the person edits use flow-diagram.\n * @example\n * <NetworkGraph\n *   label=\"Libraries and what they use\"\n *   nodes={[{ id: \"app\", group: \"Apps\" }, { id: \"ui\", group: \"Libraries\" }, { id: \"charts\", group: \"Libraries\" }, { id: \"maths\", group: \"Libraries\" }]}\n *   links={[{ source: \"app\", target: \"ui\" }, { source: \"app\", target: \"charts\" }, { source: \"charts\", target: \"maths\" }]}\n * />\n */\nimport { forceCollide, forceLink, forceManyBody, forceSimulation, forceX, forceY, type SimulationLinkDatum, type SimulationNodeDatum } from \"d3-force\";\nimport { useMemo } from \"react\";\nimport { cn } from \"@/lib/cn\";\nimport { ChartContainer, ChartEmpty, ChartLegend, ChartMark, ChartSvg, ChartTooltip, fitText, formatNumber, useChartCursor, type ChartBaseProps } from \"@/components/viz/chart\";\n\nexport type NetworkNode = {\n  id: string;\n  /** Its name. Default: the id. */\n  label?: string;\n  /** Its group: one colour and shape per group, in order of first appearance (or `groups`). */\n  group?: string;\n  /** A number that sets the node's size, such as its weight. Default: its number of links. */\n  size?: number;\n};\n\nexport type NetworkLink = { source: string; target: string /** The strength of the link; thicker when larger. */; value?: number };\n\nexport type NetworkGraphLabels = { node: string; group: string; links: string; linkCount: (count: number, formatted: string) => string };\n\nexport type NetworkGraphProps = ChartBaseProps & {\n  nodes: readonly NetworkNode[];\n  links: readonly NetworkLink[];\n  /** The groups in a fixed order, so a group keeps its colour. */\n  groups?: readonly string[];\n  /** Write each node's name beside it. Default: when there are 40 nodes or fewer. */\n  showLabels?: boolean;\n  /** Default: shown when there are two or more groups. */\n  showLegend?: boolean;\n  labels?: Partial<NetworkGraphLabels>;\n};\n\nconst LABELS: NetworkGraphLabels = { node: \"Node\", group: \"Group\", links: \"Linked to\", linkCount: (count, formatted) => `${formatted} ${count === 1 ? \"link\" : \"links\"}` };\n\ntype SimNode = SimulationNodeDatum & { id: string; name: string; group: number; groupName: string; weight: number };\ntype SimLink = SimulationLinkDatum<SimNode> & { value: number };\n\nexport function NetworkGraph({ nodes, links, groups, showLabels, showLegend, labels: given, label, aspect = 4 / 3, height, emptyLabel, locale, className, ...props }: NetworkGraphProps) {\n  const labels = { ...LABELS, ...given };\n  const model = useMemo(() => {\n    const order = groups ? [...groups] : [...new Set(nodes.map((node) => node.group ?? \"\"))];\n    const ids = new Set(nodes.map((node) => node.id));\n    const kept = links.filter((link) => ids.has(link.source) && ids.has(link.target) && link.source !== link.target);\n    const degree = new Map<string, number>();\n    for (const link of kept) {\n      degree.set(link.source, (degree.get(link.source) ?? 0) + 1);\n      degree.set(link.target, (degree.get(link.target) ?? 0) + 1);\n    }\n    const simNodes: SimNode[] = nodes.map((node) => ({\n      id: node.id,\n      name: node.label ?? node.id,\n      group: Math.max(0, order.indexOf(node.group ?? \"\")),\n      groupName: node.group ?? \"\",\n      weight: node.size ?? degree.get(node.id) ?? 0,\n    }));\n    const simLinks: SimLink[] = kept.map((link) => ({ source: link.source, target: link.target, value: link.value ?? 1 }));\n    // Run to rest here, once: the starting positions of d3-force are fixed, so the same data gives the same picture.\n    const simulation = forceSimulation<SimNode>(simNodes)\n      .force(\n        \"link\",\n        forceLink<SimNode, SimLink>(simLinks)\n          .id((node) => node.id)\n          .distance(40),\n      )\n      .force(\"charge\", forceManyBody<SimNode>().strength(-120))\n      .force(\"x\", forceX<SimNode>(0).strength(0.06))\n      .force(\"y\", forceY<SimNode>(0).strength(0.06))\n      .force(\"collide\", forceCollide<SimNode>(14))\n      .stop();\n    simulation.tick(Math.ceil(Math.log(simulation.alphaMin()) / Math.log(1 - simulation.alphaDecay())));\n    const neighbours = new Map<string, string[]>();\n    for (const link of simLinks) {\n      const a = (link.source as SimNode).id;\n      const b = (link.target as SimNode).id;\n      neighbours.set(a, [...(neighbours.get(a) ?? []), b]);\n      neighbours.set(b, [...(neighbours.get(b) ?? []), a]);\n    }\n    return { simNodes, simLinks, order, neighbours };\n  }, [nodes, links, groups]);\n\n  const { simNodes, simLinks, order, neighbours } = model;\n  const cursor = useChartCursor(simNodes.length);\n  const nameOf = (id: string): string => simNodes.find((node) => node.id === id)?.name ?? id;\n  const grouped = order.length > 1 || (order.length === 1 && order[0] !== \"\");\n  const countText = (id: string): string => {\n    const count = (neighbours.get(id) ?? []).length;\n    return labels.linkCount(count, formatNumber(count, locale));\n  };\n  const linkedNames = (id: string): string[] => (neighbours.get(id) ?? []).map(nameOf);\n  const table = {\n    caption: label,\n    columns: [labels.node, ...(grouped ? [labels.group] : []), labels.links],\n    rows: simNodes.map((node) => [node.name, ...(grouped ? [node.groupName] : []), linkedNames(node.id).join(\", \")]),\n  };\n  const current = cursor.active === null ? undefined : simNodes[cursor.active];\n  const describe = (node: SimNode): string => `${node.name}${grouped ? `, ${node.groupName}` : \"\"}, ${countText(node.id)}: ${linkedNames(node.id).join(\", \")}`;\n  const labelled = showLabels ?? simNodes.length <= 40;\n  const legend = showLegend ?? order.length > 1;\n  const maxWeight = Math.max(1, ...simNodes.map((node) => node.weight));\n\n  return (\n    <div data-slot=\"network-graph\" className={cn(\"flex w-full min-w-0 flex-col gap-3\", className)} {...props}>\n      {legend ? <ChartLegend items={order.map((name, index) => ({ label: name, index }))} mark=\"rect\" /> : null}\n      <ChartContainer aspect={aspect} height={height} table={table} announcement={cursor.keyboard && current ? describe(current) : \"\"}>\n        {({ width, height: plotHeight }) => {\n          if (simNodes.length === 0) return <ChartEmpty>{emptyLabel}</ChartEmpty>;\n          const xs = simNodes.map((node) => node.x ?? 0);\n          const ys = simNodes.map((node) => node.y ?? 0);\n          const pad = labelled ? 48 : 16;\n          const spanX = Math.max(1, Math.max(...xs) - Math.min(...xs));\n          const spanY = Math.max(1, Math.max(...ys) - Math.min(...ys));\n          const k = Math.min((width - pad * 2) / spanX, (plotHeight - 32) / spanY, 3);\n          const cx = (Math.max(...xs) + Math.min(...xs)) / 2;\n          const cy = (Math.max(...ys) + Math.min(...ys)) / 2;\n          const px = (node: SimNode): number => width / 2 + ((node.x ?? 0) - cx) * k;\n          const py = (node: SimNode): number => plotHeight / 2 + ((node.y ?? 0) - cy) * k;\n          const radius = (node: SimNode): number => 4 + 6 * Math.sqrt(node.weight / maxWeight);\n          const near = current ? new Set([current.id, ...(neighbours.get(current.id) ?? [])]) : undefined;\n          return (\n            <>\n              <ChartSvg label={label} width={width} height={plotHeight} interactive {...cursor.svgProps}>\n                <g aria-hidden=\"true\">\n                  {simLinks.map((link, index) => {\n                    const a = link.source as SimNode;\n                    const b = link.target as SimNode;\n                    const lit = current !== undefined && (a === current || b === current);\n                    return (\n                      <line\n                        key={index}\n                        x1={px(a)}\n                        y1={py(a)}\n                        x2={px(b)}\n                        y2={py(b)}\n                        className={lit ? \"stroke-foreground\" : \"stroke-border-strong\"}\n                        strokeOpacity={current && !lit ? 0.35 : 1}\n                        strokeWidth={Math.min(4, 1 + Math.log1p(link.value) * 0.6)}\n                      />\n                    );\n                  })}\n                  {simNodes.map((node, index) => {\n                    const dim = near !== undefined && !near.has(node.id);\n                    return (\n                      <g key={node.id} className={cn(\"transition-opacity duration-instant motion-reduce:transition-none\", dim && \"opacity-35\")} onPointerEnter={() => cursor.point(index)}>\n                        <circle cx={px(node)} cy={py(node)} r={Math.max(12, radius(node) + 4)} fill=\"transparent\" />\n                        <ChartMark index={grouped ? node.group : 0} x={px(node)} y={py(node)} radius={radius(node)} />\n                        {labelled ? (\n                          <text\n                            x={px(node)}\n                            y={py(node) + radius(node) + 4}\n                            dy=\"0.8em\"\n                            textAnchor=\"middle\"\n                            className={cn(\"pointer-events-none text-xs\", current === node ? \"fill-foreground font-medium\" : \"fill-muted-foreground\")}\n                          >\n                            {fitText(node.name, 96)}\n                          </text>\n                        ) : null}\n                      </g>\n                    );\n                  })}\n                  {current ? <circle cx={px(current)} cy={py(current)} r={radius(current) + 4} fill=\"none\" className=\"stroke-foreground\" strokeWidth={2} /> : null}\n                </g>\n              </ChartSvg>\n              {current ? (\n                <ChartTooltip\n                  x={px(current)}\n                  y={py(current)}\n                  side={px(current) > width / 2 ? \"left\" : \"right\"}\n                  title={current.name}\n                  rows={[\n                    ...(grouped ? [{ label: \"\", value: current.groupName, index: current.group, mark: \"rect\" as const }] : []),\n                    {\n                      label: linkedNames(current.id).slice(0, 6).join(\", \") + ((neighbours.get(current.id)?.length ?? 0) > 6 ? \"…\" : \"\"),\n                      value: countText(current.id),\n                    },\n                  ]}\n                />\n              ) : null}\n            </>\n          );\n        }}\n      </ChartContainer>\n    </div>\n  );\n}\n\n"
    }
  ],
  "meta": {
    "category": "viz",
    "when": "Showing who or what is connected to what: clusters, bridges between groups, the most linked items. Keep it to a few hundred nodes. For amounts flowing in one direction use sankey-chart; for a hierarchy use treemap or tree-view; for a process the person edits use flow-diagram.",
    "example": "<NetworkGraph\n  label=\"Libraries and what they use\"\n  nodes={[{ id: \"app\", group: \"Apps\" }, { id: \"ui\", group: \"Libraries\" }, { id: \"charts\", group: \"Libraries\" }, { id: \"maths\", group: \"Libraries\" }]}\n  links={[{ source: \"app\", target: \"ui\" }, { source: \"app\", target: \"charts\" }, { source: \"charts\", target: \"maths\" }]}\n/>",
    "client": true
  }
}
