import type { WikiPage, WikiRawSource } from "@/types/wiki"; export interface WikiGraphNode { id: string; path: string; label: string; kind: "page" | "source" | "artifact"; description?: string; sourcePath?: string; } export interface WikiGraphEdge { id: string; from: string; to: string; kind: "link" | "source"; } export interface WikiGraph { nodes: WikiGraphNode[]; edges: WikiGraphEdge[]; unresolvedLinks: { page: string; target: string }[]; } export interface GraphPoint { x: number; y: number; } export interface GraphCamera extends GraphPoint { zoom: number; } export const GRAPH_NODE_WIDTH = 184; export const GRAPH_NODE_HEIGHT = 68; export const MIN_GRAPH_ZOOM = 0.1; export const MAX_GRAPH_ZOOM = 8; export const MAX_GRAPH_NODES = 240; function normalizedPath(ref: string): string | undefined { if (/^(?:[a-z][a-z\d+.-]*:|\/\/)/i.test(ref.trim())) return undefined; const value = ref.trim().split(/[?#]/)[0]; if (!value) return undefined; let decoded = value; try { decoded = decodeURIComponent(value); } catch { /* Preserve literal malformed escapes. */ } const parts: string[] = []; for (const part of decoded.split("/")) { if (part === "..") parts.pop(); else if (part && part !== ".") parts.push(part); } return parts.join("/"); } /** Only aliases of observed source paths resolve; a basename match is unsafe. */ export function resolveWikiSourcePath( ref: string, sources: readonly Pick[], ): string | undefined { const key = normalizedPath(ref); if (!key) return undefined; const candidates = [key]; for (const prefix of [".wiki/raw/", "wiki/raw/", "raw/", "wiki/"]) { if (key.startsWith(prefix)) candidates.push(key.slice(prefix.length)); } for (const candidate of candidates) { const match = sources.find( (source) => normalizedPath(source.path) === candidate, ); if (match) return match.path; } return undefined; } export function buildWikiGraph( pages: readonly WikiPage[], sources: readonly Pick[] = [], ): WikiGraph { const nodes = new Map(); const edges = new Map(); const unresolved = new Map(); const pagePaths = new Map( pages.map((page) => [normalizedPath(page.path), page.path]), ); const addEdge = (from: string, to: string, kind: WikiGraphEdge["kind"]) => { if (from === to) return; const id = JSON.stringify([kind, from, to]); edges.set(id, { id, from, to, kind }); }; const ensureSource = (ref: string, sourcePath?: string) => { const path = sourcePath ?? normalizedPath(ref) ?? ref; const id = `source:${path}`; if (!nodes.has(id)) nodes.set(id, { id, path, sourcePath, label: path.split("/").at(-1) || path, kind: path.startsWith("artifacts/dream/") ? "artifact" : "source", }); return id; }; for (const page of pages) nodes.set(`page:${page.path}`, { id: `page:${page.path}`, path: page.path, label: page.title || page.path.split("/").at(-1) || page.path, kind: "page", description: page.description, }); // Include uploaded but uncited documents too, without inventing an edge. for (const source of sources) ensureSource(source.path, source.path); for (const page of pages) { const id = `page:${page.path}`; const citations = page.sources ?? []; for (const ref of citations) addEdge( ensureSource(ref, resolveWikiSourcePath(ref, sources)), id, "source", ); const connect = (ref: string, incoming: boolean) => { if (!normalizedPath(ref)) return; const directory = page.path.slice(0, page.path.lastIndexOf("/") + 1); const candidates = ref.startsWith("/") ? [ref] : [directory + ref, ref]; // A loaded compiled page always wins over a similarly named raw source. for (const candidate of candidates) { const target = pagePaths.get(normalizedPath(candidate)); if (target) { addEdge( incoming ? `page:${target}` : id, incoming ? id : `page:${target}`, "link", ); return; } } for (const candidate of candidates) { // Only this page's citations establish provenance. A globally known // filename alone may also name a compiled page that is not loaded. // The source listing may be loading or paginated. Citation metadata is // still evidence of a source identity, never an unloaded Wiki page. const cited = resolveWikiSourcePath( candidate, citations.map((path) => ({ path: path.replace(/^raw\//, "") })), ); if (cited) { const ref = citations.find( (path) => path.replace(/^raw\//, "") === cited, )!; addEdge( ensureSource(ref, resolveWikiSourcePath(ref, sources)), id, "source", ); return; } } unresolved.set(JSON.stringify([page.path, ref]), { page: page.path, target: ref, }); }; for (const ref of page.outgoingLinks ?? []) connect(ref, false); for (const ref of page.incomingLinks ?? []) connect(ref, true); } return { nodes: [...nodes.values()], edges: [...edges.values()], unresolvedLinks: [...unresolved.values()], }; } /** Deterministic spring layout. Resolve card collisions before showing it so * selecting/dragging never restarts a moving simulation under the pointer. */ export function layoutWikiGraph(graph: WikiGraph, showSources: boolean) { const visibleNodes = graph.nodes.filter( (node) => showSources || node.kind === "page", ); const nodes = visibleNodes.slice(0, MAX_GRAPH_NODES); const ids = new Set(nodes.map((node) => node.id)); const edges = graph.edges.filter( (edge) => ids.has(edge.from) && ids.has(edge.to), ); const degree = new Map(); for (const edge of edges) for (const id of [edge.from, edge.to]) degree.set(id, (degree.get(id) ?? 0) + 1); const ordered = [...nodes].sort( (a, b) => (degree.get(b.id) ?? 0) - (degree.get(a.id) ?? 0) || a.id.localeCompare(b.id), ); const hubId = ordered[0]?.id; const star = nodes.length > 2 && edges.every((edge) => edge.from === hubId || edge.to === hubId) && new Set(edges.map((edge) => (edge.from === hubId ? edge.to : edge.from))) .size === nodes.length - 1; const radius = Math.max(260, (nodes.length - 1) * 38); const points = ordered.map((node, i) => ({ id: node.id, x: i ? star ? Math.cos(((i - 1) * Math.PI * 2) / (nodes.length - 1) - Math.PI / 2) * radius : Math.cos(i * 2.399963) * Math.sqrt(i) * 125 : 0, y: i ? star ? Math.sin(((i - 1) * Math.PI * 2) / (nodes.length - 1) - Math.PI / 2) * radius : Math.sin(i * 2.399963) * Math.sqrt(i) * 100 : 0, vx: 0, vy: 0, })); const index = new Map(points.map((point, i) => [point.id, i])); const springs = edges.map((edge) => ({ a: index.get(edge.from)!, b: index.get(edge.to)!, length: edge.kind === "link" ? 260 : 225, })); const separate = () => { for (let i = 0; i < points.length; i++) for (let j = i + 1; j < points.length; j++) { const a = points[i], b = points[j]; const dx = b.x - a.x, dy = b.y - a.y; const overlapX = GRAPH_NODE_WIDTH + 28 - Math.abs(dx); const overlapY = GRAPH_NODE_HEIGHT + 34 - Math.abs(dy); if (overlapX > 0 && overlapY > 0) { if (overlapX < overlapY) { const push = (overlapX / 2 + 0.1) * (dx >= 0 ? 1 : -1); a.x -= push; b.x += push; } else { const push = (overlapY / 2 + 0.1) * (dy >= 0 ? 1 : -1); a.y -= push; b.y += push; } } } }; const iterations = Math.max( 80, Math.min(320, Math.floor(32000 / Math.max(1, nodes.length))), ); for (let step = 0; step < iterations; step++) { const forces = points.map((p) => ({ x: -p.x * 0.002, y: -p.y * 0.002 })); for (let i = 0; i < points.length; i++) for (let j = i + 1; j < points.length; j++) { const dx = points[j].x - points[i].x, dy = points[j].y - points[i].y; const distance = Math.max(1, Math.hypot(dx, dy)); const force = 13000 / (distance * distance); const fx = (dx / distance) * force, fy = (dy / distance) * force; forces[i].x -= fx; forces[i].y -= fy; forces[j].x += fx; forces[j].y += fy; } for (const spring of springs) { const a = points[spring.a], b = points[spring.b]; const dx = b.x - a.x, dy = b.y - a.y, distance = Math.max(1, Math.hypot(dx, dy)); const force = (distance - spring.length) * 0.025; const fx = (dx / distance) * force, fy = (dy / distance) * force; forces[spring.a].x += fx; forces[spring.a].y += fy; forces[spring.b].x -= fx; forces[spring.b].y -= fy; } const speed = 8 * (1 - step / iterations) + 0.3; points.forEach((p, i) => { p.vx = (p.vx + forces[i].x) * 0.65; p.vy = (p.vy + forces[i].y) * 0.65; const ratio = Math.min(1, speed / Math.max(1, Math.hypot(p.vx, p.vy))); p.x += p.vx * ratio; p.y += p.vy * ratio; }); separate(); } for (let i = 0; i < 50; i++) separate(); const positions = new Map(points.map((p) => [p.id, { x: p.x, y: p.y }])); return { nodes, edges, positions, hiddenNodeCount: visibleNodes.length - nodes.length, }; } export function fitGraphCamera( positions: ReadonlyMap, width: number, height: number, ): GraphCamera { if (!positions.size || width <= 0 || height <= 0) return { x: width / 2, y: height / 2, zoom: 1 }; const points = [...positions.values()]; const minX = Math.min(...points.map((p) => p.x)) - GRAPH_NODE_WIDTH / 2; const maxX = Math.max(...points.map((p) => p.x)) + GRAPH_NODE_WIDTH / 2; const minY = Math.min(...points.map((p) => p.y)) - GRAPH_NODE_HEIGHT / 2; const maxY = Math.max(...points.map((p) => p.y)) + GRAPH_NODE_HEIGHT / 2; const zoom = Math.max( MIN_GRAPH_ZOOM, Math.min(1, (width - 100) / (maxX - minX), (height - 130) / (maxY - minY)), ); return { x: width / 2 - ((minX + maxX) / 2) * zoom, y: height / 2 - ((minY + maxY) / 2) * zoom, zoom, }; } /** Preserve the world point under the pointer, including at zoom limits. */ export function zoomGraphCamera( camera: GraphCamera, zoom: number, anchor: GraphPoint, ): GraphCamera { const next = Math.max(MIN_GRAPH_ZOOM, Math.min(MAX_GRAPH_ZOOM, zoom)); const ratio = next / camera.zoom; return { x: anchor.x - (anchor.x - camera.x) * ratio, y: anchor.y - (anchor.y - camera.y) * ratio, zoom: next, }; } /** Clip links to card boundaries. Reciprocal references bend to opposite sides. */ export function graphEdgePath( from: GraphPoint, to: GraphPoint, reciprocal = false, ): string { const dx = to.x - from.x, dy = to.y - from.y; const length = Math.hypot(dx, dy); if (length < 1) return ""; const offset = reciprocal ? 32 : 0; const control = { x: (from.x + to.x) / 2 - (dy / length) * offset, y: (from.y + to.y) / 2 + (dx / length) * offset, }; const boundary = ( center: GraphPoint, toward: GraphPoint, padding: number, ) => { const dx = toward.x - center.x, dy = toward.y - center.y; const scale = Math.min( (GRAPH_NODE_WIDTH / 2 + padding) / Math.max(0.001, Math.abs(dx)), (GRAPH_NODE_HEIGHT / 2 + padding) / Math.max(0.001, Math.abs(dy)), ); return { x: center.x + dx * scale, y: center.y + dy * scale }; }; const start = boundary(from, control, 2), end = boundary(to, control, 7); return `M${start.x},${start.y} Q${control.x},${control.y} ${end.x},${end.y}`; }