import type { Force, SimulationNodeDatum } from 'd3-force'; import type { PageKind, PageLink } from '../lib/layouts'; export const graphGroup = (page: PageLink): PageKind => page.href.startsWith('/authors/') ? 'author' : page.kind; export const graphGroups = [ { kind: 'page', title: 'Pages' }, { kind: 'post', title: 'Posts' }, { kind: 'author', title: 'Authors' }, { kind: 'category', title: 'Categories' }, ] as const; /** Cohesion follows each group's moving centroid; separation keeps the clusters apart. */ export function forceClusters( group: (node: N) => PageKind, radius: (node: N) => number, ): Force { let groups: N[][] = []; const force = (alpha: number) => { const clusters = groups.map((nodes) => { const x = nodes.reduce((sum, node) => sum + (node.fx ?? node.x!), 0) / nodes.length; const y = nodes.reduce((sum, node) => sum + (node.fy ?? node.y!), 0) / nodes.length; return { nodes, x, y, fixed: nodes.some((node) => node.fx != null || node.fy != null), radius: Math.max( ...nodes.map( (node) => Math.hypot((node.fx ?? node.x!) - x, (node.fy ?? node.y!) - y) + radius(node), ), ), }; }); for (const cluster of clusters) for (const node of cluster.nodes) { node.vx! += (cluster.x - node.x!) * 0.16 * alpha; node.vy! += (cluster.y - node.y!) * 0.16 * alpha; } for (let i = 0; i < clusters.length; i++) for (let j = i + 1; j < clusters.length; j++) { const a = clusters[i], b = clusters[j]; let dx = b.x - a.x, dy = b.y - a.y; let distance = Math.hypot(dx, dy); if (distance < 0.001) { const angle = (i + j + 1) * Math.PI * (3 - Math.sqrt(5)); dx = Math.cos(angle); dy = Math.sin(angle); distance = 1; } const overlap = a.radius + b.radius + 24 - distance; if (overlap <= 0) continue; const push = (overlap / distance) * 0.4 * alpha; const mass = a.nodes.length + b.nodes.length; const share = a.fixed && !b.fixed ? 0 : b.fixed && !a.fixed ? 1 : b.nodes.length / mass; for (const node of a.nodes) { node.vx! -= dx * push * share; node.vy! -= dy * push * share; } for (const node of b.nodes) { node.vx! += dx * push * (1 - share); node.vy! += dy * push * (1 - share); } } }; force.initialize = (nodes: N[]) => { const byGroup = new Map(); for (const node of nodes) { const kind = group(node); const members = byGroup.get(kind); if (members) members.push(node); else byGroup.set(kind, [node]); } groups = [...byGroup.values()]; }; return force; }