import assert from 'node:assert/strict'; import { test } from 'node:test'; import { forceSimulation, forceManyBody, forceCollide, forceX, forceY } from 'd3-force'; import { graphGroup, forceClusters } from '../src/scripts/graph-clusters.ts'; const page = (id, kind = 'page') => ({ id, href: `/${id}/`, kind, title: id, excerpt: '' }); const node = (kind, x, y = 0) => ({ kind, x, y, vx: 0, vy: 0 }); const category = (node) => node.kind; const cluster = (nodes) => { const x = nodes.reduce((sum, node) => sum + node.x, 0) / nodes.length; const y = nodes.reduce((sum, node) => sum + node.y, 0) / nodes.length; return { x, y, radius: Math.max(...nodes.map((node) => Math.hypot(node.x - x, node.y - y))) }; }; test('the authors index and author profiles share a category', () => { assert.equal(graphGroup(page('authors')), 'author'); assert.equal(graphGroup(page('authors/ilta', 'author')), 'author'); assert.equal(graphGroup(page('latest')), 'page'); assert.equal(graphGroup(page('post', 'post')), 'post'); }); test('interleaved categories settle into compact, separated clusters', () => { const nodes = [ node('page', -90, -30), node('page', 90, 30), node('page', 0, 50), node('author', -70, 20), node('author', 70, -20), node('post', -50, 40), node('post', 50, -40), node('category', 0, 0), ]; const simulation = forceSimulation(nodes) .stop() .force( 'clusters', forceClusters(category, () => 13), ) .force('repel', forceManyBody().strength(-100)) .force('collision', forceCollide(20)) .force('x', forceX(0).strength(0.035)) .force('y', forceY(0).strength(0.045)); simulation.tick(250); const clusters = ['page', 'author', 'post', 'category'].map((kind) => cluster(nodes.filter((node) => node.kind === kind)), ); for (const [index, a] of clusters.entries()) { assert(a.radius < 60); for (const b of clusters.slice(index + 1)) assert(Math.hypot(a.x - b.x, a.y - b.y) > a.radius + b.radius + 8); } assert(nodes.every((node) => Number.isFinite(node.x) && Number.isFinite(node.y))); }); test('cluster forces follow node positions rather than fixed screen coordinates', () => { const fixture = [node('page', -20), node('page', 20), node('author', 0, 10)]; const shifted = fixture.map((node) => ({ ...node, x: node.x + 350, y: node.y - 200 })); for (const nodes of [fixture, shifted]) { const force = forceClusters(category, () => 13); force.initialize(nodes); force(1); } assert.deepEqual( fixture.map(({ vx, vy }) => [vx, vy]), shifted.map(({ vx, vy }) => [vx, vy]), ); const moving = [node('author', 0), node('author', 20)]; const force = forceClusters(category, () => 13); force.initialize(moving); moving[0].fx = 200; force(1); assert(moving[1].vx > 0, 'the other author follows the dragged member'); const empty = forceClusters(category, () => 13); empty.initialize([]); assert.doesNotThrow(() => empty(1)); });