Something went wrong. Try again.
doll.systems community website
Something went wrong. Try again.
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473import { clamp } from '../lib/math';import type { PageScope } from './page-scope';import { select, pointer } from 'd3-selection';import { forceSimulation, forceLink, forceManyBody, forceCollide, forceX, forceY } from 'd3-force';import type { SimulationNodeDatum } from 'd3-force';import { drag } from 'd3-drag';import { motionPaused } from './motion';import type { LinkGraphData, PageLink } from '../lib/layouts';import { snapPixel, alignToPixelGrid, labelGrid } from './pixel-grid';import { graphBitmap, graphLabel, type BitmapNode, type BitmapLink } from './graph-bitmap';import { previewTransition } from './preview-transition';import { graphGroup, graphGroups, forceClusters } from './graph-clusters';
const inset = { x: 32, y: 38 };const nodeSize = { primary: 5, normal: 3, hit: 15 };const keyboardStep = { normal: 8, shifted: 24 };const goldenAngle = Math.PI * (3 - Math.sqrt(5));const force = { linkDistance: 0.2, linkStrength: 0.2, charge: 0.0006, collision: 20, labelSpacing: 0.03, x: 0.035, y: 0.045, returnEase: 0.16, returnSnap: 0.25, decay: 0.045, reheat: 0.45, dragging: 0.12, warmup: 40, settle: 160, release: 30,};const directions: Record<string, [number, number]> = { ArrowLeft: [-1, 0], ArrowRight: [1, 0], ArrowUp: [0, -1], ArrowDown: [0, 1],};
type Node = PageLink & BitmapNode & SimulationNodeDatum;type Edge = BitmapLink & { source: Node; target: Node };
export function mountGraphs(scope: PageScope) { document.querySelectorAll<HTMLElement>('.link-graph').forEach((element) => { let width = element.clientWidth, height = element.clientHeight; const center = [width / 2, height / 2]; const constrain = (x: number, y: number): [number, number] => [ clamp(x, inset.x, width - inset.x), clamp(y, inset.x, height - inset.y), ]; const overview = element.hasAttribute('data-overview'); const data: LinkGraphData = JSON.parse( element.querySelector('[data-graph-data]')!.textContent!, ); const current = element.dataset.current; const pages = [...data.nodes].sort( (a, b) => Number(b.id === current) - Number(a.id === current), ); const nodes = pages.map((page) => ({ ...page, primary: page.id === current, radius: page.id === current ? nodeSize.primary : nodeSize.normal, })) as Node[]; const nodeById = new Map(nodes.map((node) => [node.id, node])); const primary = current ? nodeById.get(current) : undefined; let homeState: 'centered' | 'dragging' | 'returning' = 'centered'; function pinCurrent() { if (!primary) return; homeState = 'centered'; [primary.x, primary.y] = center; primary.fx = primary.x; primary.fy = primary.y; } const outgoing = new Map(nodes.map((node) => [node.id, new Set<string>()])); for (const [from, to] of data.edges) outgoing.get(from)!.add(to); const primaryTargets = primary && outgoing.get(primary.id); nodes.forEach((node) => (node.related = !!primaryTargets?.has(node.id))); const crowded = nodes.length > 20 || (width * height) / nodes.length < 10000; const outgoingFrom = (from: Node | undefined, edge: Edge) => { if (!from) return false; const targets = outgoing.get(from.id)!; return edge.source === from ? targets.has(edge.target.id) : edge.target === from && targets.has(edge.source.id); }; const uniqueEdges = new Map( data.edges.map(([a, b]) => [ [a, b].sort().join('\0'), { source: nodeById.get(a)!, target: nodeById.get(b)! }, ]), ); const edges = [...uniqueEdges.values()] as Edge[]; edges.forEach((edge) => (edge.related = outgoingFrom(primary, edge))); const svgElement = element.querySelector('svg')!; alignToPixelGrid(element); const fontsReady = nodes.every((d) => document.fonts.check(labelGrid(d.title).font, d.title)); const bitmap = graphBitmap(element.querySelector('canvas')!, fontsReady); bitmap.resize(width, height); element.classList.add('bitmap-ready'); const svg = select(svgElement).attr('viewBox', `0 0 ${width} ${height}`); const group = svg.append('g'); const groups = graphGroups .map((group) => ({ ...group, nodes: nodes.filter((node) => graphGroup(node) === group.kind), })) .filter((group) => group.nodes.length); const subgraphs = group .selectAll<SVGGElement, (typeof groups)[number]>('g.graph-subgraph') .data(groups, (group) => group.kind) .join('g') .attr('class', 'graph-subgraph') .attr('data-group', (group) => group.kind) .attr('role', 'group') .attr( 'aria-label', (group) => `${group.title}: ${group.nodes.length} ${group.nodes.length === 1 ? 'page' : 'pages'}`, ); const node = subgraphs .selectAll<SVGAElement, Node>('a') .data((group) => group.nodes) .join((enter) => enter.append<SVGAElement>('a')) .attr('class', (d) => `graph-node${d.primary ? ' primary' : ''}`) .attr('tabindex', 0) .attr('role', 'link') .attr('aria-label', (d) => `Open ${d.title}`) .attr('aria-description', (d) => d.kind) .attr('data-kind', (d) => d.kind) .attr('data-current-outgoing', (d) => (d.related ? '' : null)) .attr('data-preview', (d) => (overview ? null : d.id)) .attr('href', (d) => d.href); node.append('circle').attr('class', 'node-hit-area').attr('r', nodeSize.hit); const labels = node.append('image').attr('class', 'node-label').attr('aria-hidden', 'true'); const labelMetrics = new Map<string, ReturnType<typeof bitmap.label>>(); const labelLimit = () => Math.min(graphLabel.width, Math.max(24, width - 16)); function measureLabels() { nodes.forEach((d) => labelMetrics.set(d.id, bitmap.label(d.title, 'normal', labelLimit()))); labels .attr('width', (d) => labelMetrics.get(d.id)!.width) .attr('height', (d) => labelMetrics.get(d.id)!.height); } measureLabels(); let radarPoint: readonly number[] | null = null; let highlighted: Node | undefined; let frame = 0, geometryDirty = true, selectionDirty = true; const inspector = overview ? document.querySelector<HTMLElement>('[data-graph-inspector]') : null; const inspect = inspector ? previewTransition(inspector, scope) : () => {}; const labelWidth = (d: Node) => labelMetrics.get(d.id)!.width - 2 * graphLabel.padding; const labelX = (d: Node) => { const half = labelWidth(d) / 2; const left = 6; const right = width - 6; const x = right - left < half * 2 ? left : clamp(d.x - half, left, right - half * 2); return snapPixel(x) - snapPixel(d.x); }; const labelY = (d: Node) => { const label = labelMetrics.get(d.id)!; const offset = d.primary || d.y >= center[1] ? 22 - label.baseline : -10 - label.height; return Math.max( 2 - snapPixel(d.y), Math.min(height - snapPixel(d.y) - label.height - 2, offset), ); };
function paint(moved = false) { geometryDirty ||= moved; if (frame || scope.signal.aborted) return; frame = requestAnimationFrame(() => { frame = 0; if (geometryDirty) { nodes.forEach((d) => { [d.x, d.y] = constrain(d.x, d.y); }); node.attr('transform', (d) => `translate(${snapPixel(d.x)},${snapPixel(d.y)})`); labels.attr('x', (d) => labelX(d) - graphLabel.padding).attr('y', labelY); geometryDirty = false; } const targets = highlighted && outgoing.get(highlighted.id); for (const d of nodes) { d.focused = d === highlighted; d.linked = !!targets?.has(d.id); } if (selectionDirty) { labels.attr( 'href', (d) => bitmap.label( d.title, d.focused || d.linked ? 'focused' : d.related ? 'related' : 'normal', labelLimit(), ).href, ); node.attr('data-outgoing', (d) => (targets?.has(d.id) ? '' : null)); selectionDirty = false; } const occupied: { left: number; right: number; top: number; bottom: number }[] = []; const visibleLabels = new Set<Node>(); const priority = (d: Node) => Number(d.focused) * 8 + Number(d.primary) * 4 + Number(d.linked) * 2 + Number(d.related); for (const d of [...nodes].sort((a, b) => priority(b) - priority(a))) { if ( crowded && !d.primary && !d.focused && !d.linked && !(d.related && (primaryTargets?.size ?? 0) <= 6) ) continue; const metrics = labelMetrics.get(d.id)!; const box = { left: snapPixel(d.x) + labelX(d) - graphLabel.padding - 3, right: snapPixel(d.x) + labelX(d) + metrics.width - graphLabel.padding + 3, top: snapPixel(d.y) + labelY(d) - 3, bottom: snapPixel(d.y) + labelY(d) + metrics.height + 3, }; if ( !d.focused && occupied.some( (other) => box.left < other.right && box.right > other.left && box.top < other.bottom && box.bottom > other.top, ) ) continue; occupied.push(box); visibleLabels.add(d); } labels.style('opacity', (d) => (visibleLabels.has(d) ? 1 : 0)); for (const edge of edges) edge.highlighted = outgoingFrom(highlighted, edge); bitmap.draw( nodes, edges, radarPoint && !motionPaused() ? { x: radarPoint[0], y: radarPoint[1] } : undefined, ); }); } const linkDistance = (edge: Edge) => { const span = Math.min(width, height); return graphGroup(edge.source) === graphGroup(edge.target) ? Math.min(84, span * force.linkDistance) : Math.min(180, span * 0.42); }; const linkForce = forceLink<Node, Edge>(edges) .distance(linkDistance) .strength((edge) => graphGroup(edge.source) === graphGroup(edge.target) ? force.linkStrength : 0.025, ); const simulation = forceSimulation(nodes).stop(); const chargeStrength = () => -Math.min(240, Math.min(width, height) ** 2 * force.charge); const repulsion = forceManyBody<Node>().strength(chargeStrength); const horizontal = forceX<Node>(center[0]).strength(force.x); const vertical = forceY<Node>(center[1]).strength(force.y); const collision = forceCollide<Node>( (d) => force.collision + labelWidth(d) * force.labelSpacing, ).strength(0.8); simulation .force('links', linkForce) .force('repel', repulsion) .force( 'clusters', forceClusters(graphGroup, (node: Node) => node.radius + 10), ) .force('collision', collision) .force('x', horizontal) .force('y', vertical) .force('home', () => { if (!primary || homeState !== 'returning') return; const [x, y] = center; const dx = x - primary.fx!, dy = y - primary.fy!; if (Math.hypot(dx, dy) < force.returnSnap) pinCurrent(); else { primary.fx! += dx * force.returnEase; primary.fy! += dy * force.returnEase; } }) .alphaDecay(force.decay) .on('tick', () => paint(true)) .stop(); // Initial positions only: category centers are free to move throughout the simulation. const primaryGroup = primary && graphGroup(primary); const clusterSeed = Math.min(90, Math.min(width, height) * 0.22); groups.sort((a, b) => Number(b.kind === primaryGroup) - Number(a.kind === primaryGroup)); groups.forEach((group, groupIndex) => { const angle = groupIndex * goldenAngle; const radius = group.kind === primaryGroup || groups.length === 1 ? 0 : clusterSeed; const x = center[0] + Math.cos(angle) * radius; const y = center[1] + Math.sin(angle) * radius; group.nodes.forEach((node, index) => { const angle = index * goldenAngle; const radius = 14 * Math.sqrt(index + 0.5); node.x = x + Math.cos(angle) * radius; node.y = y + Math.sin(angle) * radius; }); }); pinCurrent(); let visible = false; function resume() { if (motionPaused()) { if (homeState === 'returning') pinCurrent(); simulation.stop().tick(force.settle); paint(true); } else if (visible && !document.hidden && simulation.alpha() > simulation.alphaMin()) { simulation.restart(); } else simulation.stop(); } function returnHome() { if (!primary || homeState === 'centered') return; homeState = 'returning'; simulation.alpha(Math.max(simulation.alpha(), force.reheat)); resume(); } // Start near equilibrium; animate only the remaining settling and user interactions. simulation.tick(force.warmup); paint(true); scope.defer(() => { simulation.stop(); cancelAnimationFrame(frame); group.remove(); }); scope .observe( new ResizeObserver(() => { const nextWidth = element.clientWidth, nextHeight = element.clientHeight; if (!nextWidth || !nextHeight || (nextWidth === width && nextHeight === height)) return; const scaleX = nextWidth / width, scaleY = nextHeight / height; width = nextWidth; height = nextHeight; center[0] = width / 2; center[1] = height / 2; svg.attr('viewBox', `0 0 ${width} ${height}`); bitmap.resize(width, height); measureLabels(); selectionDirty = true; nodes.forEach((node) => { node.x *= scaleX; node.y *= scaleY; if (node.fx != null) node.fx *= scaleX; if (node.fy != null) node.fy *= scaleY; [node.x, node.y] = constrain(node.x, node.y); if (node.fx != null && node.fy != null) [node.fx, node.fy] = constrain(node.fx, node.fy); }); if (homeState === 'centered') pinCurrent(); radarPoint = null; linkForce.distance(linkDistance); repulsion.strength(chargeStrength); collision.radius(collision.radius()); horizontal.x(center[0]); vertical.y(center[1]); simulation.alpha(force.reheat); resume(); paint(true); }), ) .observe(element); if (!fontsReady) Promise.all(nodes.map((d) => document.fonts.load(labelGrid(d.title).font, d.title))).then( () => { if (!scope.signal.aborted) { bitmap.refreshFonts(); measureLabels(); collision.radius(collision.radius()); selectionDirty = true; paint(true); } }, ); function highlight(selected?: Node) { highlighted = selected; selectionDirty = true; if (selected) inspect(selected); paint(); } svg .on('pointermove', (event) => { const point = pointer(event, svgElement).map(snapPixel); if (point[0] === radarPoint?.[0] && point[1] === radarPoint?.[1]) return; radarPoint = point; paint(); }) .on('pointerleave', () => { radarPoint = null; highlight(); }); node .on('pointerenter', (_, d) => highlight(d)) .on('pointerleave', () => highlight()) .on('focus', (_, d) => { radarPoint = null; highlight(d); }) .on('blur', (_, d) => { if (d === primary) returnHome(); highlight(); }); node.on('keydown', (event: KeyboardEvent, d) => { const direction = directions[event.key]; if (!direction || event.altKey || event.metaKey || event.ctrlKey) return; event.preventDefault(); event.stopPropagation(); if (d === primary) homeState = 'dragging'; simulation.stop(); const step = event.shiftKey ? keyboardStep.shifted : keyboardStep.normal; [d.x, d.y] = constrain( snapPixel(d.x + direction[0] * step), snapPixel(d.y + direction[1] * step), ); d.fx = d.x; d.fy = d.y; paint(true); }); node.on('keyup', (event: KeyboardEvent, d) => { if (!event.key.startsWith('Arrow')) return; if (d === primary) returnHome(); else { d.fx = d.fy = null; simulation.alpha(Math.max(simulation.alpha(), force.reheat)); resume(); } }); node.call( drag<SVGAElement, Node>() .on('start', (event, d) => { if (d === primary) homeState = 'dragging'; if (!event.active && !motionPaused()) simulation.alphaTarget(force.dragging).restart(); d.fx = d.x; d.fy = d.y; document.dispatchEvent(new Event('preview:hide')); }) .on('drag', (event, d) => { [d.fx, d.fy] = constrain(event.x, event.y); if (motionPaused()) { d.x = d.fx; d.y = d.fy; paint(true); } }) .on('end', (event, d) => { if (!event.active) simulation.alphaTarget(0); if (d === primary) returnHome(); else { d.fx = null; d.fy = null; } if (motionPaused()) { simulation.tick(force.release); paint(true); simulation.stop(); } }), ); scope.on(document, 'motion:change', resume); scope.on(document, 'visibilitychange', resume); scope.intersect([element], (entry) => { visible = entry.isIntersecting; resume(); }); });}