"use client"; import { useCallback, useEffect, useId, useMemo, useRef, useState, type PointerEvent, } from "react"; import { ArrowUpRight, BookOpen, FileText, Focus, GitBranch, Maximize2, Minimize2, Minus, Plus, RotateCcw, Search, Sparkles, X, } from "lucide-react"; import { Button } from "@/components/ui/button"; import { Input } from "@/components/ui/input"; import { useI18n } from "@/i18n/i18n-context"; import { buildWikiGraph, layoutWikiGraph, fitGraphCamera, zoomGraphCamera, graphEdgePath, GRAPH_NODE_WIDTH, GRAPH_NODE_HEIGHT, MIN_GRAPH_ZOOM, MAX_GRAPH_ZOOM, type GraphCamera, type GraphPoint, type WikiGraphNode, } from "@/lib/wiki-graph"; import { cn } from "@/lib/utils"; import { toast } from "sonner"; import type { WikiPage, WikiRawSource } from "@/types/wiki"; type Drag = { pointerId: number; nodeId?: string; start: GraphPoint; origin: GraphPoint; zoom: number; moved: boolean; }; export function WikiGraphView({ pages, sources, selectedPath, onOpenPage, onOpenSource, }: { pages: WikiPage[]; sources: WikiRawSource[]; selectedPath?: string; onOpenPage: (path: string) => void; onOpenSource: (path: string) => void; }) { const { t } = useI18n(); const graph = useMemo(() => buildWikiGraph(pages, sources), [pages, sources]); const [showSources, setShowSources] = useState(false); const layout = useMemo( () => layoutWikiGraph(graph, showSources), [graph, showSources], ); const [positions, setPositions] = useState(layout.positions); const positionsRef = useRef(positions); const positionedView = useRef(null); const [selectedId, setSelectedId] = useState( selectedPath ? `page:${selectedPath}` : undefined, ); const [search, setSearch] = useState(""); const [camera, setCamera] = useState({ x: 0, y: 0, zoom: 1 }); const cameraRef = useRef(camera); const viewport = useRef({ width: 900, height: 600 }); const [dragging, setDragging] = useState(false); const drag = useRef(null); const pointers = useRef(new Map()); const pinch = useRef<{ camera: GraphCamera; center: GraphPoint; distance: number; } | null>(null); const lastClick = useRef<{ id: string; at: number } | null>(null); const svg = useRef(null); const container = useRef(null); const [fullscreen, setFullscreen] = useState(false); const uid = useId().replace(/:/g, ""); const commitCamera = useCallback((value: GraphCamera) => { cameraRef.current = value; setCamera(value); }, []); const fit = useCallback( () => commitCamera( fitGraphCamera( positionsRef.current, viewport.current.width, viewport.current.height, ), ), [commitCamera], ); useEffect(() => { const reset = positionedView.current === null || positionedView.current !== showSources || positionsRef.current.size === 0; const next = new Map( layout.nodes.map((node) => [ node.id, (!reset && positionsRef.current.get(node.id)) || layout.positions.get(node.id)!, ]), ); positionsRef.current = next; setPositions(next); positionedView.current = showSources; if (drag.current?.nodeId && !next.has(drag.current.nodeId)) drag.current = null; if (reset) fit(); }, [layout, showSources, fit]); useEffect(() => { const element = svg.current; if (!element) return; const measure = () => { const bounds = element.getBoundingClientRect(); if (bounds.width && bounds.height) { viewport.current = { width: bounds.width, height: bounds.height }; fit(); } }; measure(); const observer = new ResizeObserver(measure); observer.observe(element); return () => observer.disconnect(); }, [fit]); useEffect(() => { const element = svg.current; if (!element) return; const wheel = (event: WheelEvent) => { event.preventDefault(); if (drag.current || pinch.current) return; const box = element.getBoundingClientRect(); const delta = event.deltaY * (event.deltaMode === 1 ? 16 : event.deltaMode === 2 ? box.height : 1); const factor = Math.exp(-Math.max(-240, Math.min(240, delta)) * 0.003); commitCamera( zoomGraphCamera(cameraRef.current, cameraRef.current.zoom * factor, { x: event.clientX - box.left, y: event.clientY - box.top, }), ); }; element.addEventListener("wheel", wheel, { passive: false }); return () => element.removeEventListener("wheel", wheel); }, [commitCamera]); useEffect(() => { const update = () => setFullscreen(document.fullscreenElement === container.current); document.addEventListener("fullscreenchange", update); return () => document.removeEventListener("fullscreenchange", update); }, []); useEffect( () => setSelectedId(selectedPath ? `page:${selectedPath}` : undefined), [selectedPath], ); const selected = useMemo( () => layout.nodes.find((node) => node.id === selectedId), [layout.nodes, selectedId], ); const connected = useMemo(() => { const nodeIds = new Set(selected ? [selected.id] : []); for (const edge of layout.edges) if (edge.from === selected?.id || edge.to === selected?.id) { nodeIds.add(edge.from); nodeIds.add(edge.to); } return nodeIds; }, [layout.edges, selected]); const { matching, matchedIds } = useMemo(() => { const query = search.trim().toLowerCase(); const nodes = layout.nodes.filter((node) => `${node.label} ${node.path}`.toLowerCase().includes(query), ); return { matching: nodes, matchedIds: new Set(nodes.map((node) => node.id)), }; }, [layout.nodes, search]); const { sourceCount, reciprocalLinkIds } = useMemo(() => { const linkKeys = new Set( layout.edges .filter((edge) => edge.kind === "link") .map((edge) => `${edge.from}\0${edge.to}`), ); return { sourceCount: layout.nodes.filter((node) => node.kind !== "page").length, reciprocalLinkIds: new Set( layout.edges .filter( (edge) => edge.kind === "link" && linkKeys.has(`${edge.to}\0${edge.from}`), ) .map((edge) => edge.id), ), }; }, [layout.edges, layout.nodes]); const kindLabel = (node: WikiGraphNode) => t( node.kind === "page" ? "wiki.graph.page" : node.kind === "artifact" ? "wiki.graph.artifact" : "wiki.graph.source", ); const openNode = async (node: WikiGraphNode) => { // Document previews render outside the fullscreen element through a portal. if (document.fullscreenElement === container.current) { try { await document.exitFullscreen(); } catch { toast.error(t("wiki.graph.fullscreenFailed")); return; } } if (node.kind === "page") onOpenPage(node.path); else if (node.sourcePath) onOpenSource(node.sourcePath); }; const pointInCanvas = (event: { clientX: number; clientY: number }) => { const bounds = svg.current!.getBoundingClientRect(); return { x: event.clientX - bounds.left, y: event.clientY - bounds.top }; }; function pointerDown(event: PointerEvent, nodeId?: string) { if (event.button !== 0) return; event.stopPropagation(); const point = pointInCanvas(event); pointers.current.set(event.pointerId, point); svg.current!.setPointerCapture(event.pointerId); setDragging(true); if (pointers.current.size === 2) { const [a, b] = [...pointers.current.values()]; pinch.current = { camera: cameraRef.current, center: { x: (a.x + b.x) / 2, y: (a.y + b.y) / 2 }, distance: Math.max(1, Math.hypot(a.x - b.x, a.y - b.y)), }; drag.current = null; } else if (pointers.current.size === 1) { drag.current = { pointerId: event.pointerId, nodeId, start: point, origin: nodeId ? positionsRef.current.get(nodeId)! : cameraRef.current, zoom: cameraRef.current.zoom, moved: false, }; } } function pointerMove(event: PointerEvent) { if (!pointers.current.has(event.pointerId)) return; const point = pointInCanvas(event); pointers.current.set(event.pointerId, point); if (pinch.current && pointers.current.size >= 2) { const [a, b] = [...pointers.current.values()], start = pinch.current; const center = { x: (a.x + b.x) / 2, y: (a.y + b.y) / 2 }; const next = zoomGraphCamera( start.camera, (start.camera.zoom * Math.hypot(a.x - b.x, a.y - b.y)) / start.distance, start.center, ); commitCamera({ ...next, x: next.x + center.x - start.center.x, y: next.y + center.y - start.center.y, }); return; } const current = drag.current; if (!current || current.pointerId !== event.pointerId) return; const dx = point.x - current.start.x, dy = point.y - current.start.y; if (!current.moved && Math.hypot(dx, dy) < 4) return; current.moved = true; if (current.nodeId) { const next = new Map(positionsRef.current); next.set(current.nodeId, { x: current.origin.x + dx / current.zoom, y: current.origin.y + dy / current.zoom, }); positionsRef.current = next; setPositions(next); } else commitCamera({ ...cameraRef.current, x: current.origin.x + dx, y: current.origin.y + dy, }); } function pointerEnd(event: PointerEvent, cancelled = false) { const current = drag.current; if ( !cancelled && current?.pointerId === event.pointerId && !current.moved ) { if (current.nodeId) { const node = layout.nodes.find((node) => node.id === current.nodeId)!; if ( lastClick.current?.id === node.id && Date.now() - lastClick.current.at < 350 ) { openNode(node); lastClick.current = null; } else { setSelectedId((value) => (value === node.id ? undefined : node.id)); lastClick.current = { id: node.id, at: Date.now() }; } } else { setSelectedId(undefined); lastClick.current = null; } } pointers.current.delete(event.pointerId); if (svg.current?.hasPointerCapture(event.pointerId)) svg.current.releasePointerCapture(event.pointerId); pinch.current = null; const remaining = [...pointers.current.entries()][0]; drag.current = remaining ? { pointerId: remaining[0], start: remaining[1], origin: cameraRef.current, zoom: cameraRef.current.zoom, moved: true, } : null; setDragging(!!remaining); } const zoom = (factor: number) => commitCamera( zoomGraphCamera(cameraRef.current, cameraRef.current.zoom * factor, { x: viewport.current.width / 2, y: viewport.current.height / 2, }), ); const focusNode = (node: WikiGraphNode) => { const point = positionsRef.current.get(node.id)!; const scale = Math.max(1, cameraRef.current.zoom); setSelectedId(node.id); setSearch(""); commitCamera({ x: viewport.current.width / 2 - point.x * scale, y: viewport.current.height / 2 - point.y * scale, zoom: scale, }); }; async function toggleFullscreen() { try { if (document.fullscreenElement) await document.exitFullscreen(); else await container.current?.requestFullscreen(); } catch { toast.error(t("wiki.graph.fullscreenFailed")); } } return (

{t("wiki.graph.title")}

{t( showSources ? "wiki.graph.subtitle" : "wiki.graph.wikiSubtitle", { pages: layout.nodes.length - sourceCount, sources: sourceCount, edges: layout.edges.length, }, )}

{[false, true].map((value) => ( ))}
{layout.hiddenNodeCount > 0 && (

{t("wiki.graph.nodeLimit", { count: layout.nodes.length })}

)}
setSearch(event.target.value)} onKeyDown={(event) => { if (event.key === "Enter" && matching[0]) focusNode(matching[0]); if (event.key === "Escape") setSearch(""); }} className="h-9 rounded-xl bg-background pl-9 pr-8 text-xs" /> {search && ( )} {search.trim() && (
{matching.length ? ( matching.slice(0, 12).map((node) => ( )) ) : (

{t("wiki.graph.noMatch")}

)}
)}
{t("wiki.graph.link")} {showSources && ( {t("wiki.graph.citation")} )}
pointerDown(event)} onPointerMove={pointerMove} onPointerUp={(event) => pointerEnd(event)} onPointerCancel={(event) => pointerEnd(event, true)} onLostPointerCapture={(event) => { if (pointers.current.has(event.pointerId)) pointerEnd(event, true); }} > {layout.edges.map((edge) => { const from = positions.get(edge.from), to = positions.get(edge.to); if (!from || !to) return null; const active = selected && (edge.from === selected.id || edge.to === selected.id); return ( ); })} {layout.nodes.map((node) => { const point = positions.get(node.id); if (!point) return null; const active = (!selected || connected.has(node.id)) && (!search.trim() || matchedIds.has(node.id)); const Icon = node.kind === "page" ? BookOpen : node.kind === "artifact" ? Sparkles : FileText; return ( ); })} {!pages.length && (
{t("wiki.graph.empty")}
)}
{t("wiki.graph.gestures")}
{selected ? ( <>

{selected.label} {t("wiki.graph.connections", { count: connected.size - 1 })}

{selected.description || selected.path}

{(selected.kind === "page" || selected.sourcePath) && ( )} ) : (

{t("wiki.graph.hint")} {graph.unresolvedLinks.length > 0 && ( {t("wiki.graph.unresolved", { count: graph.unresolvedLinks.length, })} )}

)}
); }