LLM Wiki is a cross-platform desktop application that turns your documents into an organized, interlinked knowledge base — automatically. Instead of traditional RAG (retrieve-and-answer from scratch every time), the LLM incrementally builds and maintains a persistent wiki from your sources。
TypeScript
perf: optimize graph rendering
nash_su836eb8bfdf1b
diff --git a/src/components/graph/graph-layout-worker.ts b/src/components/graph/graph-layout-worker.tsnew file mode 100644index 00000000..79bd92a3--- /dev/null+++ b/src/components/graph/graph-layout-worker.ts@@ -0,0 +1,45 @@+import Graph from "graphology"+import forceAtlas2 from "graphology-layout-forceatlas2"++interface LayoutRequest {+ key: string+ nodes: Array<{ id: string; x: number; y: number }>+ edges: Array<{ source: string; target: string; weight: number }>+ iterations: number+ scalingRatio: number+}++self.onmessage = (event: MessageEvent<LayoutRequest>) => {+ const { key, nodes, edges, iterations, scalingRatio } = event.data+ const graph = new Graph()++ for (const node of nodes) {+ graph.addNode(node.id, { x: node.x, y: node.y })+ }++ for (const edge of edges) {+ if (!graph.hasNode(edge.source) || !graph.hasNode(edge.target)) continue+ const edgeKey = `${edge.source}->${edge.target}`+ if (graph.hasEdge(edgeKey) || graph.hasEdge(`${edge.target}->${edge.source}`)) continue+ graph.addEdgeWithKey(edgeKey, edge.source, edge.target, { weight: edge.weight })+ }++ const settings = forceAtlas2.inferSettings(graph)+ forceAtlas2.assign(graph, {+ iterations,+ settings: {+ ...settings,+ gravity: 1,+ scalingRatio,+ strongGravityMode: true,+ barnesHutOptimize: nodes.length > 50,+ },+ })++ const positions: Array<{ id: string; x: number; y: number }> = []+ graph.forEachNode((id, attrs) => {+ positions.push({ id, x: attrs.x, y: attrs.y })+ })++ self.postMessage({ key, positions })+}diff --git a/src/components/graph/graph-view.tsx b/src/components/graph/graph-view.tsxindex 74ae9407..82c7db4a 100644--- a/src/components/graph/graph-view.tsx+++ b/src/components/graph/graph-view.tsx@@ -1,6 +1,6 @@import { useEffect, useCallback, useMemo, useState, useRef, type ChangeEvent } from "react"import Graph from "graphology"-import { SigmaContainer, useLoadGraph, useRegisterEvents, useSigma } from "@react-sigma/core"+import { SigmaContainer, useLoadGraph, useRegisterEvents, useSetSettings, useSigma } from "@react-sigma/core"import "@react-sigma/core/lib/style.css"import type { SigmaNodeEventPayload } from "sigma/types"import forceAtlas2 from "graphology-layout-forceatlas2"@@ -67,6 +67,9 @@ const MAX_NODE_SIZE = 28const DEFAULT_NODE_SCALE = 1const DEFAULT_GRAPH_SPACING = 1const GRAPH_SPACING_DEBOUNCE_MS = 180+const WORKER_LAYOUT_NODE_THRESHOLD = 220++type HoverState = { node: string; neighbors: Set<string> } | nullfunction nodeColor(type: string): string {if (NODE_TYPE_COLORS[type]) return NODE_TYPE_COLORS[type]@@ -104,11 +107,71 @@ function nodeSize(linkCount: number, maxLinks: number, nodeCount: number, userScreturn size * graphDensityScale(nodeCount) * userScale}+function layoutIterations(nodeCount: number): number {+ if (nodeCount > 2500) return 28+ if (nodeCount > 1200) return 40+ if (nodeCount > 600) return 65+ if (nodeCount > 250) return 90+ return 140+}++function edgeVisibilityThreshold(nodeCount: number): number {+ if (nodeCount > 2500) return 0.16+ if (nodeCount > 1200) return 0.1+ if (nodeCount > 700) return 0.05+ return 0+}++function labelSizeThreshold(nodeCount: number): number {+ if (nodeCount > 2500) return 18+ if (nodeCount > 1200) return 14+ if (nodeCount > 600) return 10+ return 6+}++function labelDensity(nodeCount: number): number {+ if (nodeCount > 2500) return 0.08+ if (nodeCount > 1200) return 0.14+ if (nodeCount > 600) return 0.24+ return 0.4+}++function graphDataKey(nodes: readonly GraphNode[], edges: readonly GraphEdge[], graphSpacing: number): string {+ const nodeIds = nodes.map((n) => n.id).sort()+ const edgeIds = edges+ .map((e) => `${e.source}->${e.target}:${Math.round(e.weight * 1000)}`)+ .sort()+ return `${hashParts(nodeIds)}:${hashParts(edgeIds)}:${nodes.length}:${edges.length}:${graphSpacing.toFixed(2)}`+}++function hashParts(parts: readonly string[]): string {+ let hash = 2166136261+ for (const part of parts) {+ for (let i = 0; i < part.length; i++) {+ hash ^= part.charCodeAt(i)+ hash = Math.imul(hash, 16777619)+ }+ hash ^= 0xff+ hash = Math.imul(hash, 16777619)+ }+ return (hash >>> 0).toString(36)+}++function makeLayoutWorker(): Worker | null {+ try {+ return new Worker(new URL("./graph-layout-worker.ts", import.meta.url), { type: "module" })+ } catch (err) {+ console.warn("[Graph] failed to start layout worker; falling back to main-thread layout:", err)+ return null+ }+}+// --- Inner components ---// Cache computed node positions so re-renders don't re-layoutconst positionCache = new Map<string, { x: number; y: number }>()let lastLayoutDataKey = ""+let pendingLayoutDataKey = ""function GraphLoader({nodes,@@ -124,13 +187,17 @@ function GraphLoader({graphSpacing: number}) {const loadGraph = useLoadGraph()+ const sigma = useSigma()useEffect(() => {- const dataKey = nodes.map((n) => n.id).sort().join(",") + "|" + edges.length + `|spacing:${graphSpacing.toFixed(2)}`- const needsLayout = dataKey !== lastLayoutDataKey+ const dataKey = graphDataKey(nodes, edges, graphSpacing)+ const needsLayout = dataKey !== lastLayoutDataKey && dataKey !== pendingLayoutDataKey+ let cancelled = false+ let worker: Worker | null = nullconst graph = new Graph()const maxLinks = Math.max(...nodes.map((n) => n.linkCount), 1)+ const weakEdgeThreshold = edgeVisibilityThreshold(nodes.length)for (const node of nodes) {const cached = positionCache.get(node.id)@@ -165,16 +232,19 @@ function GraphLoader({color,size,weight: edge.weight,+ normalizedWeight,+ sourceNode: edge.source,+ targetNode: edge.target,+ lowPriority: weakEdgeThreshold > 0 && normalizedWeight < weakEdgeThreshold,})}}}- // Only run expensive ForceAtlas2 layout when data actually changed- if (needsLayout && nodes.length > 1) {+ const runMainThreadLayout = () => {const settings = forceAtlas2.inferSettings(graph)forceAtlas2.assign(graph, {- iterations: 150,+ iterations: layoutIterations(nodes.length),settings: {...settings,gravity: 1,@@ -191,48 +261,139 @@ function GraphLoader({})}+ // Only run expensive ForceAtlas2 layout when data actually changed.+ // Large graphs are laid out in a Web Worker so the UI remains+ // responsive while coordinates settle.+ if (needsLayout && nodes.length > 1 && nodes.length < WORKER_LAYOUT_NODE_THRESHOLD) {+ runMainThreadLayout()+ }+loadGraph(graph)- }, [loadGraph, nodes, edges, colorMode, nodeScale, graphSpacing])++ if (needsLayout && nodes.length >= WORKER_LAYOUT_NODE_THRESHOLD) {+ worker = makeLayoutWorker()+ if (!worker) {+ runMainThreadLayout()+ loadGraph(graph)+ return undefined+ }+ pendingLayoutDataKey = dataKey++ worker.onmessage = (event: MessageEvent<{ key: string; positions: Array<{ id: string; x: number; y: number }> }>) => {+ if (cancelled || event.data.key !== dataKey) return+ for (const { id, x, y } of event.data.positions) {+ if (!graph.hasNode(id)) continue+ graph.setNodeAttribute(id, "x", x)+ graph.setNodeAttribute(id, "y", y)+ positionCache.set(id, { x, y })+ }+ lastLayoutDataKey = dataKey+ if (pendingLayoutDataKey === dataKey) pendingLayoutDataKey = ""+ sigma.refresh()+ }+ worker.onerror = (event) => {+ if (cancelled) return+ console.warn("[Graph] layout worker failed; falling back to main-thread layout:", event.message)+ if (pendingLayoutDataKey === dataKey) pendingLayoutDataKey = ""+ runMainThreadLayout()+ loadGraph(graph)+ }+ worker.postMessage({+ key: dataKey,+ nodes: nodes.map((node) => {+ const cached = positionCache.get(node.id)+ return {+ id: node.id,+ x: cached?.x ?? graph.getNodeAttribute(node.id, "x"),+ y: cached?.y ?? graph.getNodeAttribute(node.id, "y"),+ }+ }),+ edges: edges.map((edge) => ({ source: edge.source, target: edge.target, weight: edge.weight })),+ iterations: layoutIterations(nodes.length),+ scalingRatio: graphSpacing * (nodes.length > 400 ? 3 : 2),+ })+ }++ return () => {+ cancelled = true+ if (pendingLayoutDataKey === dataKey) pendingLayoutDataKey = ""+ worker?.terminate()+ }+ }, [loadGraph, sigma, nodes, edges, colorMode, nodeScale, graphSpacing])return null}-function HighlightManager({ highlightedNodes }: { highlightedNodes: Set<string> }) {+function GraphRenderSettings({+ hoverState,+ highlightedNodes,+ nodeCount,+}: {+ hoverState: HoverState+ highlightedNodes: Set<string>+ nodeCount: number+}) {const sigma = useSigma()+ const setSettings = useSetSettings()useEffect(() => {- const graph = sigma.getGraph()- if (highlightedNodes.size === 0) {- graph.forEachNode((n) => {- graph.removeNodeAttribute(n, "insightHighlight")- graph.removeNodeAttribute(n, "dimmed")- })- graph.forEachEdge((e) => {- graph.removeEdgeAttribute(e, "dimmed")- graph.removeEdgeAttribute(e, "highlighted")- })- } else {- graph.forEachNode((n) => {- if (highlightedNodes.has(n)) {- graph.setNodeAttribute(n, "insightHighlight", true)- graph.removeNodeAttribute(n, "dimmed")- } else {- graph.setNodeAttribute(n, "dimmed", true)- graph.removeNodeAttribute(n, "insightHighlight")+ setSettings({+ hideEdgesOnMove: true,+ hideLabelsOnMove: true,+ labelDensity: labelDensity(nodeCount),+ labelRenderedSizeThreshold: labelSizeThreshold(nodeCount),+ renderEdgeLabels: false,+ nodeReducer: (node, attrs) => {+ const result = { ...attrs }+ const hasHover = !!hoverState+ const hasHighlight = highlightedNodes.size > 0+ const isHoverNode = hoverState?.node === node+ const isHoverNeighbor = hoverState?.neighbors.has(node) ?? false+ const isHighlighted = highlightedNodes.has(node)++ if (isHighlighted) {+ result.size = (attrs.size ?? BASE_NODE_SIZE) * 1.5+ result.zIndex = 10+ result.forceLabel = true}- })- graph.forEachEdge((e, _attrs, source, target) => {- if (highlightedNodes.has(source) && highlightedNodes.has(target)) {- graph.setEdgeAttribute(e, "highlighted", true)- graph.removeEdgeAttribute(e, "dimmed")- } else {- graph.setEdgeAttribute(e, "dimmed", true)- graph.removeEdgeAttribute(e, "highlighted")+ if (isHoverNode) {+ result.size = (attrs.size ?? BASE_NODE_SIZE) * 1.4+ result.zIndex = 10+ result.forceLabel = true}- })- }+ if ((hasHover && !isHoverNode && !isHoverNeighbor) || (hasHighlight && !isHighlighted)) {+ result.color = mixColor(attrs.color ?? "#94a3b8", "#e2e8f0", 0.75)+ result.label = ""+ result.size = (attrs.size ?? BASE_NODE_SIZE) * 0.6+ }+ return result+ },+ edgeReducer: (_edge, attrs) => {+ const result = { ...attrs }+ const source = String(attrs.sourceNode ?? "")+ const target = String(attrs.targetNode ?? "")+ const hasHover = !!hoverState+ const hasHighlight = highlightedNodes.size > 0+ const hoverEdge = hasHover && (source === hoverState?.node || target === hoverState?.node)+ const highlightedEdge = hasHighlight && highlightedNodes.has(source) && highlightedNodes.has(target)++ if (attrs.lowPriority && !hoverEdge && !highlightedEdge) {+ result.hidden = true+ return result+ }+ if ((hasHover && !hoverEdge) || (hasHighlight && !highlightedEdge)) {+ result.color = "#f1f5f9"+ result.size = 0.3+ }+ if (hoverEdge || highlightedEdge) {+ result.color = "#1e293b"+ result.size = Math.max(2, (attrs.size ?? 1) * 1.5)+ }+ return result+ },+ })sigma.refresh()- }, [sigma, highlightedNodes])+ }, [setSettings, sigma, hoverState, highlightedNodes, nodeCount])return null}@@ -240,9 +401,11 @@ function HighlightManager({ highlightedNodes }: { highlightedNodes: Set<string>function EventHandler({onNodeClick,onNodeContextMenu,+ onHoverChange,}: {onNodeClick: (nodeId: string) => voidonNodeContextMenu: (nodeId: string, x: number, y: number) => void+ onHoverChange: (state: HoverState) => void}) {const registerEvents = useRegisterEvents()const sigma = useSigma()@@ -261,37 +424,15 @@ function EventHandler({const container = sigma.getContainer()container.style.cursor = "pointer"const graph = sigma.getGraph()- graph.setNodeAttribute(node, "hovering", true)- const neighbors = new Set(graph.neighbors(node))- neighbors.add(node)- graph.forEachNode((n) => {- if (!neighbors.has(n)) graph.setNodeAttribute(n, "dimmed", true)- })- graph.forEachEdge((e, _attrs, source, target) => {- if (source !== node && target !== node) {- graph.setEdgeAttribute(e, "dimmed", true)- } else {- graph.setEdgeAttribute(e, "highlighted", true)- }- })- sigma.refresh()+ onHoverChange({ node, neighbors: new Set(graph.neighbors(node)) })},leaveNode: () => {const container = sigma.getContainer()container.style.cursor = "default"- const graph = sigma.getGraph()- graph.forEachNode((n) => {- graph.removeNodeAttribute(n, "hovering")- graph.removeNodeAttribute(n, "dimmed")- })- graph.forEachEdge((e) => {- graph.removeEdgeAttribute(e, "dimmed")- graph.removeEdgeAttribute(e, "highlighted")- })- sigma.refresh()+ onHoverChange(null)},})- }, [registerEvents, sigma, onNodeClick, onNodeContextMenu])+ }, [registerEvents, sigma, onNodeClick, onNodeContextMenu, onHoverChange])return null}@@ -368,6 +509,7 @@ export function GraphView() {const [colorMode, setColorMode] = useState<ColorMode>("type")const [showInsights, setShowInsights] = useState(false)const [highlightedNodes, setHighlightedNodes] = useState<Set<string>>(new Set())+ const [hoverState, setHoverState] = useState<HoverState>(null)const [dismissedInsights, setDismissedInsights] = useState<Set<string>>(new Set())const [sigmaKey, setSigmaKey] = useState(0)const [isResizing, setIsResizing] = useState(false)@@ -826,49 +968,17 @@ export function GraphView() {key={sigmaKey}style={{ width: "100%", height: "100%", background: "transparent" }}settings={{- renderEdgeLabels: true,+ renderEdgeLabels: false,+ hideEdgesOnMove: true,+ hideLabelsOnMove: true,defaultEdgeColor: "#cbd5e1",defaultNodeColor: "#94a3b8",labelSize: 13,labelWeight: "bold",labelColor: { color: "#1e293b" },- labelDensity: 0.4,- labelRenderedSizeThreshold: 6,+ labelDensity: labelDensity(searchedGraph.nodes.length),+ labelRenderedSizeThreshold: labelSizeThreshold(searchedGraph.nodes.length),stagePadding: 30,- nodeReducer: (_node, attrs) => {- const result = { ...attrs }- if (attrs.insightHighlight) {- result.size = (attrs.size ?? BASE_NODE_SIZE) * 1.5- result.zIndex = 10- result.forceLabel = true- }- if (attrs.hovering) {- result.size = (attrs.size ?? BASE_NODE_SIZE) * 1.4- result.zIndex = 10- result.forceLabel = true- }- if (attrs.dimmed) {- result.color = mixColor(attrs.color ?? "#94a3b8", "#e2e8f0", 0.75)- result.label = ""- result.size = (attrs.size ?? BASE_NODE_SIZE) * 0.6- }- return result- },- edgeReducer: (_edge, attrs) => {- const result = { ...attrs }- if (attrs.dimmed) {- result.color = "#f1f5f9"- result.size = 0.3- }- if (attrs.highlighted) {- const w = attrs.weight ?? 1- result.color = "#1e293b"- result.size = Math.max(2, (attrs.size ?? 1) * 1.5)- result.label = `relevance: ${w.toFixed(1)}`- result.forceLabel = true- }- return result- },}}><GraphLoader@@ -878,8 +988,16 @@ export function GraphView() {nodeScale={nodeScale}graphSpacing={graphSpacing}/>- <EventHandler onNodeClick={handleNodeClick} onNodeContextMenu={handleNodeContextMenu} />- <HighlightManager highlightedNodes={searchActive ? searchedGraph.matchedNodeIds : highlightedNodes} />+ <EventHandler+ onNodeClick={handleNodeClick}+ onNodeContextMenu={handleNodeContextMenu}+ onHoverChange={setHoverState}+ />+ <GraphRenderSettings+ hoverState={hoverState}+ highlightedNodes={searchActive ? searchedGraph.matchedNodeIds : highlightedNodes}+ nodeCount={searchedGraph.nodes.length}+ /><ZoomControls /></SigmaContainer></ErrorBoundary>