
Force-directed graph layout visualizing nodes and physics spring link connections.
components/tanstack-charts/line/force-directed-network.tsx
import { type ChartPoint, defineChart, dot, link, text } from "@tanstack/charts";
import { motion } from "@tanstack/charts/motion";
import { forceLayout } from "@tanstack/charts/network/force";
import { tooltip } from "@tanstack/charts/tooltip";
import { Chart } from "@tanstack/react-charts/core";
import { useMemo } from "react";
import { scaleLinear } from "d3-scale";
import { Share2 } from "lucide-react";
import { Card, CardContent, CardDescription, CardFooter, CardHeader, CardTitle } from "@/components/ui/card";
interface NodeDatum {
id: string;
group: number;
}
interface LinkDatum {
source: string;
target: string;
value: number;
}
const motionRenderer = motion({
initial: "always",
transition: { type: "spring", stiffness: 170, damping: 18, mass: 1 },
});
function generateDemoData(): { nodes: NodeDatum[]; links: LinkDatum[] } {
const nodes: NodeDatum[] = [
{ id: "Valjean", group: 1 },
{ id: "Javert", group: 1 },
{ id: "Fantine", group: 1 },
{ id: "Cosette", group: 2 },
{ id: "Marius", group: 2 },
{ id: "Eponine", group: 2 },
{ id: "Thenardier", group: 2 },
{ id: "Mme.Thenardier", group: 2 },
{ id: "Enjolras", group: 3 },
{ id: "Gavroche", group: 3 },
{ id: "Courfeyrac", group: 3 },
{ id: "Combeferre", group: 3 },
];
const links: LinkDatum[] = [
{ source: "Valjean", target: "Javert", value: 8 },
{ source: "Valjean", target: "Fantine", value: 6 },
{ source: "Valjean", target: "Cosette", value: 9 },
{ source: "Valjean", target: "Marius", value: 5 },
{ source: "Javert", target: "Fantine", value: 3 },
{ source: "Cosette", target: "Marius", value: 10 },
{ source: "Marius", target: "Eponine", value: 7 },
{ source: "Thenardier", target: "Mme.Thenardier", value: 9 },
{ source: "Thenardier", target: "Valjean", value: 4 },
{ source: "Enjolras", target: "Gavroche", value: 8 },
{ source: "Enjolras", target: "Courfeyrac", value: 7 },
{ source: "Enjolras", target: "Combeferre", value: 7 },
{ source: "Courfeyrac", target: "Combeferre", value: 6 },
{ source: "Marius", target: "Enjolras", value: 5 },
];
return { nodes, links };
}
function shadcnTooltipContent<TDatum>(points: readonly ChartPoint<TDatum>[]) {
if (points.length === 0) return { title: "", rows: [] };
const p = points[0];
const d = p.datum as any;
if (!d) return { title: "", rows: [] };
if ("group" in d) {
return {
title: d.id,
rows: [{ label: "Group", value: `Cluster ${d.group}`, color: "var(--chart-1)" }],
};
}
return {
title: "Connection Link",
rows: [
{ label: "Link Path", value: `${d.source} → ${d.target}`, color: "var(--foreground)" },
{ label: "Interaction Weight", value: `${d.value}`, color: "var(--chart-2)" },
],
};
}
export function ForceDirectedNetwork() {
const { nodes, links } = useMemo(() => generateDemoData(), []);
const graph = useMemo(() => {
return forceLayout(nodes, links, {
nodeKey: "id",
source: "source",
target: "target",
iterations: 300,
domainPadding: 0.2,
forces: [
{
type: "link",
distance: (datum: LinkDatum) => 54 - Math.min(datum.value, 10) * 1.8,
strength: (datum: LinkDatum) => 0.2 + Math.min(datum.value, 10) * 0.045,
},
{ type: "manyBody", strength: -165 },
{ type: "center", x: 0, y: 0 },
{ type: "collide", radius: 15, strength: 0.9 },
{ type: "x", x: 0, strength: 0.035 },
{ type: "y", y: 0, strength: 0.035 },
],
});
}, [nodes, links]);
const definition = useMemo(
() =>
defineChart(
{
renderer: motionRenderer,
marks: [
link(graph.links, {
id: "network-links",
x1: "x1",
y1: "y1",
x2: "x2",
y2: "y2",
key: ({ source, target }: any) => `${source}->${target}`,
stroke: "var(--border)",
strokeOpacity: 0.7,
strokeWidth: 1.5,
}),
dot(graph.nodes, {
id: "network-nodes",
x: "x",
y: "y",
color: (d: any) =>
d.group === 1 ? "var(--chart-1)" : d.group === 2 ? "var(--chart-2)" : "var(--chart-3)",
key: "id",
r: 7,
stroke: "var(--background)",
strokeWidth: 1.5,
}),
text(graph.nodes, {
id: "network-labels",
x: "x",
y: "y",
text: "id",
key: "id",
dy: -12,
fontSize: 10,
fontWeight: 600,
fill: "var(--foreground)",
}),
],
scales: {
x: {
scale: scaleLinear().domain(graph.xDomain),
},
y: {
scale: scaleLinear().domain(graph.yDomain),
},
},
guides: false,
theme: {
foreground: "var(--muted-foreground)",
grid: "transparent",
background: "transparent",
},
},
{
keyboard: true,
tooltip: {
use: tooltip,
className:
"font-sans shadow-none rounded-md bg-popover text-popover-foreground border p-2 text-xs",
anchor: "group-center",
placement: "auto",
content: (points) => shadcnTooltipContent(points),
},
},
),
[graph],
);
return (
<Card className="w-full max-w-xl">
<CardHeader>
<CardTitle>Force-Directed Network</CardTitle>
<CardDescription>
Physics-based force layout displaying node relationships and entity interaction clusters
</CardDescription>
</CardHeader>
<CardContent>
<div className="h-[280px] w-full">
<Chart
definition={definition}
renderer={motionRenderer}
height={280}
ariaLabel="Force-Directed Network Chart"
/>
</div>
</CardContent>
<CardFooter className="flex-col items-start gap-2 text-sm">
<div className="flex items-center gap-2 leading-none font-medium">
Nodes positioned via spring-embedder force simulation <Share2 className="text-primary h-4 w-4" />
</div>
<div className="text-muted-foreground leading-none">
Repulsive many-body forces separate clusters while link tension pulls connected entities
</div>
</CardFooter>
</Card>
);
}
export default ForceDirectedNetwork;