Open-source LLM knowledge platform: turn raw documents into a queryable RAG, an autonomous reasoning agent, and a self-maintaining Wiki.
Go agentagenticaichatbotdsh-pluginembeddingsevaluationgenerative-aigolangknowledge-basellmmulti-tenantollamaopenaiquestion-answeringragrerankingsemantic-searchvector-searchwiki
feat(wiki): improve graph layout, theme captions and group focus (#4147)
lyingbug231a5c0b15b8
diff --git a/frontend/src/api/wiki/index.ts b/frontend/src/api/wiki/index.tsindex 028558983..dd21e84dd 100644--- a/frontend/src/api/wiki/index.ts+++ b/frontend/src/api/wiki/index.ts@@ -326,7 +326,15 @@ export function getWikiGraph(kbId: string, params?: WikiGraphQueryParams) {}}const qs = query.toString();- return get(`/api/v1/knowledgebase/${kbId}/wiki/graph${qs ? '?' + qs : ''}`);+ return get(`/api/v1/knowledgebase/${kbId}/wiki/graph${qs ? '?' + qs : ''}`).then((res: any) => {+ // Older backends serialize an edgeless subgraph as `"edges": null`.+ const graph = res?.data || res;+ if (graph && typeof graph === 'object') {+ graph.nodes ??= [];+ graph.edges ??= [];+ }+ return res;+ });}export function getWikiStats(kbId: string) {diff --git a/frontend/src/i18n/locales/en-US.ts b/frontend/src/i18n/locales/en-US.tsindex a7c213256..3fbd87028 100755--- a/frontend/src/i18n/locales/en-US.ts+++ b/frontend/src/i18n/locales/en-US.ts@@ -3626,6 +3626,16 @@ export default {helpZoomDesc: 'Zoom the canvas',neighborsProgress: 'Showing {visible} of {total} neighbors ({hidden} not loaded)',neighborsAllShown: 'All {total} neighbors are already on the canvas (click Expand to focus on this node’s subgraph)',+ graphNavigationHint: 'Drag the canvas to pan · Scroll to zoom',+ focusGroup: 'Focus this group',+ focusGroupViewing: 'Viewing: {name}',+ focusGroupBack: 'Back to full graph',+ focusGroupSwitch: 'Switch to another group',+ unlinkedHidden: '{count} unlinked pages hidden',+ unlinkedSection: 'Unlinked pages · {count}',+ offscreenSection: 'No visible connections (links exist) · {count}',+ hideUnlinked: 'Hide unlinked pages ({count})',+ showUnlinked: 'Show unlinked pages ({count})',neighborsNone: 'This page has no linked neighbors',neighborsCenterUnreachable: 'Showing {visible} of {total} neighbors ({hidden} unreachable: dead links, filtered, or deleted)',neighborsOverviewHidden: 'Showing {visible} of {total} neighbors ({hidden} outside the overview — click Expand to pivot here)',diff --git a/frontend/src/i18n/locales/ja-JP.ts b/frontend/src/i18n/locales/ja-JP.tsindex 025fa3412..da5a17a97 100644--- a/frontend/src/i18n/locales/ja-JP.ts+++ b/frontend/src/i18n/locales/ja-JP.ts@@ -3626,6 +3626,16 @@ export default {helpZoomDesc: 'キャンバスを拡大・縮小',neighborsProgress: '{total}個の隣接ノードのうち{visible}個を表示中({hidden}個は未読み込み)',neighborsAllShown: '{total}個の隣接ノードはすべてキャンバス上にあります(「隣接ノードを展開」でこのノードのサブグラフに焦点を当てられます)',+ graphNavigationHint: '背景をドラッグして移動 · スクロールでズーム',+ focusGroup: 'このグループを表示',+ focusGroupViewing: '表示中:{name}',+ focusGroupBack: '全体に戻る',+ focusGroupSwitch: '別のグループに切り替え',+ unlinkedHidden: 'リンクのないページを {count} 件非表示',+ unlinkedSection: 'リンクのないページ · {count}',+ offscreenSection: '現在の表示内に接続なし(リンクあり)· {count}',+ hideUnlinked: 'リンクのないページを非表示({count})',+ showUnlinked: 'リンクのないページを表示({count})',neighborsNone: 'このページにリンクされた隣接ノードはありません',neighborsCenterUnreachable: '{total}個の隣接ノードのうち{visible}個を表示中({hidden}個は到達不可: リンク切れ、フィルタ対象外、または削除済み)',neighborsOverviewHidden: '{total}個の隣接ノードのうち{visible}個を表示中({hidden}個は概要の範囲外です。「展開」をクリックするとここを起点に表示できます)',diff --git a/frontend/src/i18n/locales/ko-KR.ts b/frontend/src/i18n/locales/ko-KR.tsindex 504d289ff..5f8e2d4d0 100755--- a/frontend/src/i18n/locales/ko-KR.ts+++ b/frontend/src/i18n/locales/ko-KR.ts@@ -4661,6 +4661,16 @@ export default {helpZoomDesc: '캔버스 확대/축소',neighborsProgress: '이웃 {visible}/{total} 표시됨 ({hidden}개 미로딩)',neighborsAllShown: '모든 {total}개 이웃이 이미 캔버스에 있습니다 (확장을 클릭하여 이 노드의 서브그래프에 집중)',+ graphNavigationHint: '빈 공간을 드래그하여 이동 · 스크롤하여 확대/축소',+ focusGroup: '이 그룹에 초점 맞추기',+ focusGroupViewing: '보는 중: {name}',+ focusGroupBack: '전체 그래프로 돌아가기',+ focusGroupSwitch: '다른 그룹으로 전환',+ unlinkedHidden: '연결 없는 페이지 {count}개 숨김',+ unlinkedSection: '연결 없는 페이지 · {count}',+ offscreenSection: '현재 화면에 연결 없음 (링크 있음) · {count}',+ hideUnlinked: '연결 없는 페이지 숨기기 ({count})',+ showUnlinked: '연결 없는 페이지 표시 ({count})',neighborsNone: '이 페이지에는 연결된 이웃이 없습니다',neighborsCenterUnreachable: '이웃 {visible}/{total} 표시됨 ({hidden}개 연결 불가: 끊긴 링크, 필터됨 또는 삭제됨)',neighborsOverviewHidden: '이웃 {visible}/{total} 표시됨 ({hidden}개는 개요 범위 밖 — 확장을 클릭하여 이곳으로 전환)',diff --git a/frontend/src/i18n/locales/ru-RU.ts b/frontend/src/i18n/locales/ru-RU.tsindex a883c7d23..c00d7bbe6 100755--- a/frontend/src/i18n/locales/ru-RU.ts+++ b/frontend/src/i18n/locales/ru-RU.ts@@ -4661,6 +4661,16 @@ export default {helpZoomDesc: 'Масштабировать холст',neighborsProgress: 'Показано {visible} из {total} соседей (еще {hidden} не загружено)',neighborsAllShown: 'Все {total} соседей уже на холсте (нажмите «Развернуть», чтобы сфокусироваться на подграфе этого узла)',+ graphNavigationHint: 'Перетаскивайте фон для перемещения · Прокручивайте для масштаба',+ focusGroup: 'Показать эту группу',+ focusGroupViewing: 'Просмотр: {name}',+ focusGroupBack: 'Вернуться ко всему графу',+ focusGroupSwitch: 'Перейти к другой группе',+ unlinkedHidden: 'Скрыто страниц без связей: {count}',+ unlinkedSection: 'Страницы без связей · {count}',+ offscreenSection: 'Нет видимых связей (ссылки есть) · {count}',+ hideUnlinked: 'Скрыть страницы без связей ({count})',+ showUnlinked: 'Показать страницы без связей ({count})',neighborsNone: 'У этой страницы нет связанных соседей',neighborsCenterUnreachable: 'Показано {visible} из {total} соседей ({hidden} недоступны: мёртвые ссылки, отфильтрованы или удалены)',neighborsOverviewHidden: 'Показано {visible} из {total} соседей ({hidden} вне обзора — нажмите «Развернуть», чтобы переключиться сюда)',diff --git a/frontend/src/i18n/locales/zh-CN.ts b/frontend/src/i18n/locales/zh-CN.tsindex c9b3fb52f..ebcaff95b 100755--- a/frontend/src/i18n/locales/zh-CN.ts+++ b/frontend/src/i18n/locales/zh-CN.ts@@ -4663,6 +4663,16 @@ export default {helpZoomDesc: '缩放画布',neighborsProgress: '已显示邻居 {visible}/{total}(还有 {hidden} 个未加载)',neighborsAllShown: '全部 {total} 个邻居已在图中(可点"展开邻居"聚焦到该节点子图)',+ graphNavigationHint: '拖拽空白处移动 · 滚轮缩放',+ focusGroup: '聚焦这组页面',+ focusGroupViewing: '正在查看:{name}',+ focusGroupBack: '返回全图',+ focusGroupSwitch: '切换到其他分组',+ unlinkedHidden: '已隐藏 {count} 个无关联页面',+ unlinkedSection: '无关联页面 · {count}',+ offscreenSection: '当前视图无连线(存在链接)· {count}',+ hideUnlinked: '隐藏无关联页面({count})',+ showUnlinked: '显示无关联页面({count})',neighborsNone: '该节点没有链接邻居',neighborsCenterUnreachable: '已显示邻居 {visible}/{total}(还有 {hidden} 个无法连通:可能是死链、被过滤或已删除)',neighborsOverviewHidden: '已显示邻居 {visible}/{total}({hidden} 个不在概览范围,点"展开邻居"以此为中心查看)',diff --git a/frontend/src/i18n/locales/zh-TW.ts b/frontend/src/i18n/locales/zh-TW.tsindex 8eff52934..276db5982 100644--- a/frontend/src/i18n/locales/zh-TW.ts+++ b/frontend/src/i18n/locales/zh-TW.ts@@ -4663,6 +4663,16 @@ export default {helpZoomDesc: '縮放畫布',neighborsProgress: '已顯示鄰居 {visible}/{total}(還有 {hidden} 個未載入)',neighborsAllShown: '全部 {total} 個鄰居已在圖中(可點"展開鄰居"聚焦到該節點子圖)',+ graphNavigationHint: '拖曳空白處移動 · 滾輪縮放',+ focusGroup: '聚焦這組頁面',+ focusGroupViewing: '正在查看:{name}',+ focusGroupBack: '返回全圖',+ focusGroupSwitch: '切換到其他分組',+ unlinkedHidden: '已隱藏 {count} 個無關聯頁面',+ unlinkedSection: '無關聯頁面 · {count}',+ offscreenSection: '目前視圖無連線(存在連結)· {count}',+ hideUnlinked: '隱藏無關聯頁面({count})',+ showUnlinked: '顯示無關聯頁面({count})',neighborsNone: '該節點沒有連結鄰居',neighborsCenterUnreachable: '已顯示鄰居 {visible}/{total}(還有 {hidden} 個無法連通:可能是死鏈、被篩選或已刪除)',neighborsOverviewHidden: '已顯示鄰居 {visible}/{total}({hidden} 個不在概覽範圍,點"展開鄰居"以此為中心查看)',diff --git a/frontend/src/views/knowledge/wiki/WikiBrowser.vue b/frontend/src/views/knowledge/wiki/WikiBrowser.vueindex 1d0f65b7c..9b0bdc769 100644--- a/frontend/src/views/knowledge/wiki/WikiBrowser.vue+++ b/frontend/src/views/knowledge/wiki/WikiBrowser.vue@@ -5,8 +5,31 @@<div class="wiki-graph"><div ref="graphRef" class="wiki-graph-canvas"></div>+ <div v-if="graphReady" class="graph-navigation-hint">+ {{ $t('knowledgeEditor.wikiBrowser.graphNavigationHint') }}+ </div>++ <div v-if="graphReady && graphFocusGroup" class="graph-focus-bar"+ :class="{ 'focus-bar-shifted': graphDrawerVisible }">+ <t-dropdown v-if="graphGroupMenu.length" :options="graphGroupMenu" trigger="click" placement="top"+ attach="body" :max-height="320" @click="(item: any) => focusGraphGroup(String(item.value))">+ <button type="button" class="graph-focus-name" :title="$t('knowledgeEditor.wikiBrowser.focusGroupSwitch')">+ <span>{{ $t('knowledgeEditor.wikiBrowser.focusGroupViewing', { name: graphFocusGroup.name }) }}</span>+ <t-icon name="chevron-up" />+ </button>+ </t-dropdown>+ <span v-else class="graph-focus-name" :title="graphFocusGroup.name">+ {{ $t('knowledgeEditor.wikiBrowser.focusGroupViewing', { name: graphFocusGroup.name }) }}+ </span>+ <button type="button" class="graph-focus-back" @click="exitGraphFocus">+ <t-icon name="rollback" />+ <span>{{ $t('knowledgeEditor.wikiBrowser.focusGroupBack') }}</span>+ <kbd>Esc</kbd>+ </button>+ </div>+<!-- Graph Search Overlay -->- <div v-if="graphReady" class="wiki-graph-search-container">+ <div v-if="graphControlsVisible" class="wiki-graph-search-container"><div class="wiki-graph-search-row"><div class="wiki-graph-search"><t-select v-model="graphSearchValue" filterable :options="graphSearchEffectiveOptions"@@ -47,7 +70,7 @@</div><!-- Legend Overlay -->- <div v-if="graphReady" class="wiki-graph-legend" :class="{ 'legend-shifted': graphDrawerVisible }">+ <div v-if="graphControlsVisible" class="wiki-graph-legend" :class="{ 'legend-shifted': graphDrawerVisible }"><div class="legend-items"><div class="legend-item clickable" :class="{ disabled: !graphFilterTypes.has('summary') }"@click="toggleGraphFilterType('summary')">@@ -81,6 +104,11 @@</div><div class="legend-divider"></div><div class="legend-actions">+ <button v-if="graphUnlinkedSlugs.size > 0" type="button" class="legend-action graph-unlinked-toggle"+ :aria-pressed="showUnlinkedNodes" @click="toggleUnlinkedNodes">+ <span class="legend-action-icon"><t-icon :name="showUnlinkedNodes ? 'browse-off' : 'browse'" /></span>+ <span>{{ $t(showUnlinkedNodes ? 'knowledgeEditor.wikiBrowser.hideUnlinked' : 'knowledgeEditor.wikiBrowser.showUnlinked', { count: graphUnlinkedSlugs.size }) }}</span>+ </button><div class="legend-action" @click="fitGraphToView" title="Fit to View"><span class="legend-action-icon"><t-icon name="focus" /></span><span>{{ $t('knowledgeEditor.wikiBrowser.fitView') || '适应屏幕' }}</span>@@ -810,6 +838,7 @@ import {expandWikiDirectoryPath,} from './wikiDirectoryState'import { resolveWikiBacklinkTitle } from './wikiBacklinkTitles'+import { buildGraphLayout, graphNodeRadius, stepGraphLayout, visibleGraphLabels, graphPointBounds, initialGraphViewport, graphClusterOutline, graphLandmarkTitle, type GraphBounds, type GraphCluster } from './wikiGraphLayout'import { getKnowledgeDetails } from '@/api/knowledge-base'import { createSessions } from '@/api/chat'import ChatView from '@/views/chat/index.vue'@@ -996,7 +1025,25 @@ const drawerBodyRef = ref<HTMLElement | null>(null)const loading = ref(false)const graphLoading = ref(false)const graphReady = ref(false)+// Search and type filters must survive an empty or failed render, otherwise+// the user has no way to leave that state.+const graphControlsVisible = computed(() => graphReady.value || (!graphLoading.value && graphData.value !== null))const showArrows = ref(true)+const showUnlinkedNodes = ref(true)+const graphUnlinkedSlugs = computed(() => {+ const data = graphData.value+ const endpoints = new Set((data?.edges ?? []).flatMap(e => [e.source, e.target]))+ return new Set((data?.nodes ?? []).filter(n => n.link_count === 0 && !endpoints.has(n.slug)).map(n => n.slug))+})+function toggleUnlinkedNodes() {+ showUnlinkedNodes.value = !showUnlinkedNodes.value+ if (!showUnlinkedNodes.value && graphSelectedSlug.value && graphUnlinkedSlugs.value.has(graphSelectedSlug.value)) {+ graphSelectedSlug.value = null+ graphHighlightSlug.value = null+ graphDrawerVisible.value = false+ }+ renderGraph()+}// Graph filteringconst graphFilterTypes = ref<Set<string>>(new Set(['summary', 'entity', 'concept', 'synthesis', 'comparison', 'index']))@@ -1092,9 +1139,38 @@ function applyGraphFilters() {// node/edge membership when the allow-list changes.}+// Group focus is entered from a landmark caption. Leaving it restores the+// viewport the user had before the first focus, not a fit-to-view.+const graphFocusGroup = ref<{ key: string; name: string } | null>(null)+let graphFocusReturnViewport: { scale: number; x: number; y: number } | null = null+// Every focusable group, so the focus bar can switch to groups off screen.+const graphGroups = ref<{ key: string; name: string; count: number }[]>([])+let graphGroupFocusers = new Map<string, () => void>()+const graphGroupMenu = computed(() => graphGroups.value+ .filter(group => group.key !== graphFocusGroup.value?.key)+ .map(group => ({ value: group.key, content: `${group.name} · ${group.count}` })))++function focusGraphGroup(key: string) {+ graphGroupFocusers.get(key)?.()+}++function exitGraphFocus() {+ if (!graphFocusGroup.value) return+ graphFocusedSlugs.clear()+ graphFocusGroup.value = null+ const back = graphFocusReturnViewport+ graphFocusReturnViewport = null+ clearHighlight(graphNodeElsRef, graphEdgeElsRef)+ if (back && graphPanZoomRef) graphPanZoomRef.flyTo(back.x, back.y, back.scale, 500)+}+// Fit graph to viewfunction fitGraphToView() {+ graphFocusedSlugs.clear()+ graphFocusGroup.value = null+ graphFocusReturnViewport = nullif (!graphReady.value || !graphPanZoomRef || !graphRef.value || graphNodes.length === 0) return+ clearHighlight(graphNodeElsRef, graphEdgeElsRef)const container = graphRef.valueconst width = container.clientWidth@@ -1116,21 +1192,33 @@ function fitGraphToView() {if (visibleCount === 0) return // No visible nodes+ // Include the separate shelves as well as the live node coordinates.+ if (graphLayoutBounds) {+ minX = Math.min(minX, graphLayoutBounds.left)+ minY = Math.min(minY, graphLayoutBounds.top)+ maxX = Math.max(maxX, graphLayoutBounds.right)+ maxY = Math.max(maxY, graphLayoutBounds.bottom)+ }+// Calculate center of the bounding boxconst cx = (minX + maxX) / 2const cy = (minY + maxY) / 2// Calculate scale to fit the bounding box (with some padding)- const padding = 60- const boxWidth = Math.max(maxX - minX, 100) + padding * 2- const boxHeight = Math.max(maxY - minY, 100) + padding * 2-- const scaleX = width / boxWidth- const scaleY = height / boxHeight- const targetScale = Math.max(0.2, Math.min(2, Math.min(scaleX, scaleY))) // Limit scale between 0.2 and 2+ const padding = 100+ const boxWidth = Math.max(maxX - minX, 100)+ const boxHeight = Math.max(maxY - minY, 100)++ // Reserve room for the legend or page drawer instead of fitting nodes+ // underneath them. The canvas still pans freely into the reserved space.+ const sidebarWidth = graphDrawerVisible.value ? 480 : Math.min(240, width * 0.25)+ const availableWidth = Math.max(160, width - sidebarWidth)+ const scaleX = Math.max(100, availableWidth - padding * 2) / boxWidth+ const scaleY = Math.max(100, height - padding * 2) / boxHeight+ const targetScale = Math.max(0.005, Math.min(2, Math.min(scaleX, scaleY)))// Offset center if drawer is open- const targetCx = width / 2 - (graphDrawerVisible.value ? 240 : 0)+ const targetCx = availableWidth / 2const targetCy = height / 2// Target translation@@ -1495,14 +1583,17 @@ const graphStatusCard = computed((): { icon: string; title: string; primary: str}}if (meta.mode === 'overview') {- const secondary = meta.truncated+ const hiddenCount = showUnlinkedNodes.value ? 0 : graphUnlinkedSlugs.value.size+ const secondary = hiddenCount > 0+ ? t('knowledgeEditor.wikiBrowser.unlinkedHidden', { count: hiddenCount })+ : meta.truncated? t('knowledgeEditor.wikiBrowser.cardOverviewHintTruncated'): t('knowledgeEditor.wikiBrowser.cardOverviewHintFull')return {icon: 'chart-bubble',title: t('knowledgeEditor.wikiBrowser.cardOverviewTitle'),primary: t('knowledgeEditor.wikiBrowser.cardOverviewPrimary', {- returned: meta.returned,+ returned: data.nodes.length - hiddenCount,total: meta.total,}),secondary,@@ -3209,6 +3300,7 @@ async function loadGraph() {// loadGraph() again.async function loadEgoGraph(slug: string, depth = GRAPH_EGO_DEFAULT_DEPTH) {if (!slug) return+ showUnlinkedNodes.value = truegraphLoading.value = truegraphReady.value = falseif (graphFilterSelectsNothing()) {@@ -3236,13 +3328,16 @@ async function loadEgoGraph(slug: string, depth = GRAPH_EGO_DEFAULT_DEPTH) {// generation counter — we're no longer accumulating on top of the// previous canvas, so every node belongs to generation 0.resetBloomGenerations(graphData.value?.nodes)+ // Select before rendering so the new center also receives its highlight.+ graphSelectedSlug.value = slug+ graphHighlightSlug.value = nullawait nextTick()renderGraph()- // After a fresh ego render, preselect the center so the highlight /- // drawer context matches what the user just asked for.- graphSelectedSlug.value = slug} catch (e) {console.error(`Failed to load ego graph for ${slug}:`, e)+ // Keep showing the previous graph; the caller still opens the page.+ await nextTick()+ renderGraph()} finally {graphLoading.value = false}@@ -3316,7 +3411,7 @@ async function loadBloomNeighbors(anchorSlug: string, depth = GRAPH_EGO_DEFAULT_graphData.value = mergedawait nextTick()- renderGraph({ preserveLayout: true, anchorSlug })+ renderGraph({ preserveLayout: true })} catch (e) {console.error(`Failed to bloom neighbors for ${anchorSlug}:`, e)} finally {@@ -3519,9 +3614,7 @@ async function growFrontier() {graphData.value = mergedawait nextTick()- // anchorSlug intentionally omitted — new nodes have no single natural- // landing point, so we fall back to random canvas-center placement- // and let the force simulation untangle them.+ // Place each new node near an existing neighbor, retaining the old layout.renderGraph({ preserveLayout: true })} finally {graphLoading.value = false@@ -3690,6 +3783,7 @@ function toggleArrows() {e.line.removeAttribute('marker-start')}}+ refreshGraphLabels()}function formatDate(dateStr: string) {@@ -3712,12 +3806,23 @@ interface GNode {slug: string; title: string; type: stringlinkCount: number; pinned: booleanfamiliar: boolean+ labelWidth: number}// Persistent graph state so it survives re-renderslet graphNodes: GNode[] = []+let graphLayoutBounds: GraphBounds | null = null+let graphClusterEls: { group: SVGGElement; cluster: GraphCluster; anchorSlug: string; labelWidth: number; priority: number }[] = []+let graphContourEls: { path: SVGPathElement; cluster: GraphCluster; scale?: number; positions?: number[] }[] = []+let graphSectionEls: { text: SVGTextElement; top: number }[] = []+let graphImportantSlugs = new Set<string>()+let graphFocusedSlugs = new Set<string>()+let graphHoverSuppressedUntil = 0let graphSvg: SVGSVGElement | null = nulllet graphAnimFrame = 0+let refreshGraphLabels = () => {}+let graphEdgeMarkersVisible = true+let disposeGraphPanZoom = () => {}// Shared timer for debouncing node mouseleave -> mouseenter transitions.// Prevents flickering when the pointer quickly moves between adjacent nodes.let graphHoverLeaveTimer: ReturnType<typeof setTimeout> | null = null@@ -3728,7 +3833,8 @@ let graphPanZoomRef: {setTranslate: (x: number, y: number) => void,apply: () => void,flyTo: (x: number, y: number, s?: number, duration?: number) => void,- getScale: () => number+ getScale: () => number,+ getTranslate: () => { x: number; y: number }} | null = nullconst graphHighlightSlug = ref<string | null>(null)@@ -3739,36 +3845,48 @@ const nodeColorMap: Record<string, string> = {summary: '#0052d9', entity: '#2ba471', concept: '#e37318',synthesis: '#0594fa', comparison: '#d54941', index: '#8c8c8c',}+const graphEdgeColor = '#aeb5c0'+const graphEdgeWidth = '0.8'+const graphEdgeOpacity = '0.42'-// RenderGraphOpts tweaks how renderGraph initializes node positions when-// repainting the canvas. The default (no opts) does a full layout reset —-// every node gets a fresh circular starting position and the force-// simulation runs from scratch. With `preserveLayout: true` we reuse the-// x/y/vx/vy of any node that already existed in the previous graphNodes-// list, and only new nodes get initial positions. This is what the-// "bloom neighbors" interaction needs: when the user expands a second-// ego around a neighbor, the nodes they already see don't jump to new-// positions — only the newly arrived neighbors fly in.+// Incremental expansion preserves existing positions and the viewport.interface RenderGraphOpts {preserveLayout?: boolean- // anchorSlug: if set and the node is new, it is placed near the anchor- // with a small random jitter so related nodes visually land together.- anchorSlug?: string}function renderGraph(opts: RenderGraphOpts = {}) {const container = graphRef.valueconst data = graphData.valueif (!container) return+ if (graphAnimFrame) { cancelAnimationFrame(graphAnimFrame); graphAnimFrame = 0 }+ if (graphHoverLeaveTimer) { clearTimeout(graphHoverLeaveTimer); graphHoverLeaveTimer = null }+ const previousViewport = opts.preserveLayout && graphPanZoomRef+ ? { scale: graphPanZoomRef.getScale(), ...graphPanZoomRef.getTranslate() } : undefined+ disposeGraphPanZoom()+ refreshGraphLabels = () => {}+ graphPanZoomRef = null+ graphSvg = null+ graphLayoutBounds = null+ graphClusterEls = []+ graphContourEls = []+ graphSectionEls = []+ graphFocusedSlugs.clear()+ graphFocusGroup.value = null+ graphFocusReturnViewport = null+ graphGroups.value = []+ graphGroupFocusers = new Map()+ graphReady.value = falseif (!data || !data.nodes?.length) {container.innerHTML = ''+ graphNodes = []+ graphNodeElsRef = []+ graphEdgeElsRef = []+ graphAdjacencyRef = new Map()return}- const graph = data-- // Stop any previous animation- if (graphAnimFrame) { cancelAnimationFrame(graphAnimFrame); graphAnimFrame = 0 }- if (graphHoverLeaveTimer) { clearTimeout(graphHoverLeaveTimer); graphHoverLeaveTimer = null }+ const graph = showUnlinkedNodes.value ? data : {+ ...data, nodes: data.nodes.filter(n => !graphUnlinkedSlugs.value.has(n.slug)),+ }const width = container.clientWidth || 800const height = container.clientHeight || 600@@ -3776,10 +3894,10 @@ function renderGraph(opts: RenderGraphOpts = {}) {// Snapshot prior node coordinates before we rebuild graphNodes. Used// when preserveLayout is true to avoid the whole canvas jumping during// an incremental bloom.- const priorCoords = new Map<string, { x: number; y: number; vx: number; vy: number; pinned: boolean }>()+ const priorCoords = new Map<string, { x: number; y: number; pinned: boolean }>()if (opts.preserveLayout) {for (const n of graphNodes) {- priorCoords.set(n.slug, { x: n.x, y: n.y, vx: n.vx, vy: n.vy, pinned: n.pinned })+ priorCoords.set(n.slug, { x: n.x, y: n.y, pinned: n.pinned })}}@@ -3788,6 +3906,8 @@ function renderGraph(opts: RenderGraphOpts = {}) {svg.setAttribute('viewBox', `0 0 ${width} ${height}`)svg.style.width = '100%'svg.style.height = '100%'+ svg.style.cursor = 'grab'+ svg.style.userSelect = 'none'container.innerHTML = ''container.appendChild(svg)graphSvg = svg@@ -3799,6 +3919,7 @@ function renderGraph(opts: RenderGraphOpts = {}) {// Edge group (below nodes)const edgeG = document.createElementNS('http://www.w3.org/2000/svg', 'g')+ edgeG.setAttribute('pointer-events', 'none')rootG.appendChild(edgeG)// Node group (above edges)@@ -3814,65 +3935,146 @@ function renderGraph(opts: RenderGraphOpts = {}) {adjacency.get(edge.target)!.add(edge.source)}- // Locate the anchor's prior coordinates so new nodes land near it in- // bloom mode. Falls back to canvas center if the anchor is itself new- // (e.g. ego was pivoted rather than bloomed).- const anchorCoord = opts.anchorSlug ? priorCoords.get(opts.anchorSlug) : undefined- const anchorX = anchorCoord?.x ?? width / 2- const anchorY = anchorCoord?.y ?? height / 2+ const layout = buildGraphLayout(graph.nodes, graph.edges, width, height, priorCoords)+ const regions = layout.sections+ if (regions.length) graphLayoutBounds = {+ left: Math.min(...regions.map(r => r.left)), top: Math.min(...regions.map(r => r.top)),+ right: Math.max(...regions.map(r => r.right)), bottom: Math.max(...regions.map(r => r.bottom)),+ }+ graphImportantSlugs = new Set([...graph.nodes]+ .sort((a, b) => b.link_count - a.link_count)+ .slice(0, Math.max(1, Math.min(12, Math.ceil(graph.nodes.length / 30))))+ .map(n => n.slug))+ // Outlines separate groups in the overview. Ego exploration shows only+ // nodes and links, including after pivoting or expanding a neighborhood.+ const overviewClusters = graphMode.value === 'overview' ? layout.clusters : []+ for (const cluster of overviewClusters) {+ const path = document.createElementNS('http://www.w3.org/2000/svg', 'path')+ path.classList.add('graph-cluster-outline')+ path.setAttribute('fill', 'var(--td-bg-color-secondarycontainer)')+ path.setAttribute('data-cluster', cluster.representative)+ path.setAttribute('stroke', 'var(--td-component-border)')+ path.setAttribute('stroke-width', '1')+ path.setAttribute('vector-effect', 'non-scaling-stroke')+ path.setAttribute('pointer-events', 'visiblePainted')+ rootG.insertBefore(path, edgeG)+ graphContourEls.push({ path, cluster })+ }+ if (overviewClusters.length) {+ const clusterBySlug = new Map(overviewClusters.flatMap(c => c.slugs.map(slug => [slug, c.representative] as const)))+ let hoveredCluster: string | null = null+ const highlightCluster = (cluster: string | null) => {+ if (cluster === hoveredCluster) return+ hoveredCluster = cluster+ for (const { path, cluster: group } of graphContourEls) path.classList.toggle('is-hovered', group.representative === cluster)+ }+ // Delegation keeps the region highlighted while moving between its+ // background, nodes and labels. The background still accepts canvas pan.+ svg.addEventListener('mousemove', e => {+ const target = e.target as Element+ const slug = target.closest('[data-graph-node]')?.getAttribute('data-graph-node')+ ?? target.closest('[data-representative]')?.getAttribute('data-representative')+ highlightCluster(slug ? clusterBySlug.get(slug) ?? null+ : target.closest('[data-cluster]')?.getAttribute('data-cluster') ?? null)+ })+ svg.addEventListener('mouseleave', () => highlightCluster(null))+ }+ // Each landmark names its own page; no individual page is presented as+ // the title of the entire connected component.+ if (graphMode.value === 'overview') {+ const pageBySlug = new Map(graph.nodes.map(n => [n.slug, n]))+ for (const cluster of layout.clusters) {+ if (cluster.slugs.length < 5) continue+ const focus = () => {+ if (!graphPanZoomRef) return+ if (graphFocusGroup.value?.key === cluster.representative) { exitGraphFocus(); return }+ if (!graphFocusGroup.value) graphFocusReturnViewport = { scale: graphPanZoomRef.getScale(), ...graphPanZoomRef.getTranslate() }+ graphFocusGroup.value = { key: cluster.representative,+ name: graphLandmarkTitle(pageBySlug.get(cluster.anchors[0]!)!.title) }+ graphFocusedSlugs = new Set(cluster.slugs)+ graphSelectedSlug.value = null+ graphHighlightSlug.value = null+ graphDrawerVisible.value = false+ graphHoverSuppressedUntil = performance.now() + 500+ clearHighlight(graphNodeElsRef, graphEdgeElsRef)+ const availableWidth = Math.max(160, width - Math.min(240, width * 0.25))+ const members = new Set(cluster.slugs)+ const bounds = graphPointBounds(graphNodes.filter(n => members.has(n.slug)))+ const scale = Math.min(1.75, Math.max(0.4, Math.min(+ (availableWidth - 160) / Math.max(100, bounds.right - bounds.left),+ (height - 180) / Math.max(100, bounds.bottom - bounds.top))))+ graphPanZoomRef.flyTo(availableWidth / 2 - (bounds.left + bounds.right) / 2 * scale,+ height / 2 - (bounds.top + bounds.bottom) / 2 * scale, scale)+ }+ const addCaption = (anchorSlug: string, rank: number) => {+ const label = graphLandmarkTitle(pageBySlug.get(anchorSlug)!.title)+ const caption = document.createElementNS('http://www.w3.org/2000/svg', 'g')+ caption.classList.add('graph-cluster-caption')+ caption.setAttribute('data-representative', anchorSlug)+ caption.setAttribute('role', 'button')+ caption.setAttribute('tabindex', '0')+ caption.setAttribute('aria-label', `${label} · ${t('knowledgeEditor.wikiBrowser.focusGroup')}`)+ const title = document.createElementNS('http://www.w3.org/2000/svg', 'text')+ title.textContent = label.length > 20 ? label.slice(0, 20) + '…' : label+ title.setAttribute('text-anchor', 'middle')+ title.setAttribute('font-size', '13')+ title.setAttribute('font-weight', '600')+ title.setAttribute('fill', 'var(--td-text-color-primary)')+ // Pill shown while another group is focused, so names read as targets.+ const pill = document.createElementNS('http://www.w3.org/2000/svg', 'rect')+ pill.classList.add('graph-caption-pill')+ caption.append(pill, title)+ rootG.appendChild(caption)+ const textWidth = title.getComputedTextLength() || title.textContent.length * 13+ pill.setAttribute('x', String(-textWidth / 2 - 12))+ pill.setAttribute('y', '-17')+ pill.setAttribute('width', String(textWidth + 24))+ pill.setAttribute('height', '24')+ pill.setAttribute('rx', '12')+ graphClusterEls.push({ group: caption, cluster, anchorSlug,+ labelWidth: textWidth + 24,+ priority: 100000 + cluster.slugs.length - rank })+ caption.addEventListener('click', e => { e.stopPropagation(); focus() })+ caption.addEventListener('keydown', e => {+ if (e.key === 'Enter' || e.key === ' ') { e.preventDefault(); e.stopPropagation(); focus() }+ })+ }+ cluster.anchors.forEach((slug, rank) => addCaption(slug, rank))+ graphGroupFocusers.set(cluster.representative, focus)+ graphGroups.value.push({ key: cluster.representative, count: cluster.slugs.length,+ name: graphLandmarkTitle(pageBySlug.get(cluster.anchors[0]!)!.title) })+ }+ }+ // Section captions describe why these pages have no visible neighbors.+ for (const section of layout.sections) {+ const caption = document.createElementNS('http://www.w3.org/2000/svg', 'text')+ caption.setAttribute('x', String(section.left + 16))+ caption.setAttribute('y', String(section.top + 20))+ caption.setAttribute('font-size', '13')+ caption.setAttribute('fill', 'var(--td-text-color-secondary)')+ caption.setAttribute('pointer-events', 'none')+ caption.textContent = t(section.kind === 'unlinked'+ ? 'knowledgeEditor.wikiBrowser.unlinkedSection'+ : 'knowledgeEditor.wikiBrowser.offscreenSection', { count: section.count })+ rootG.insertBefore(caption, edgeG)+ graphSectionEls.push({ text: caption, top: section.top })+ }- // Build nodesconst nodeMap = new Map<string, GNode>()- graphNodes = graph.nodes.map((n, i) => {- const prior = opts.preserveLayout ? priorCoords.get(n.slug) : undefined- let x: number- let y: number- let vx: number- let vy: number- let pinned: boolean- if (prior) {- // Reuse the node's existing position so the user's mental map of- // the canvas stays stable across bloom iterations.- x = prior.x- y = prior.y- vx = prior.vx- vy = prior.vy- pinned = prior.pinned- } else if (opts.preserveLayout && opts.anchorSlug) {- // New node arriving during a bloom — spawn it right next to the- // anchor with a small random kick so the force simulation pushes- // it into place alongside its siblings.- const jitterR = 40- const angle = Math.random() * Math.PI * 2- x = anchorX + jitterR * Math.cos(angle)- y = anchorY + jitterR * Math.sin(angle)- vx = 0- vy = 0- pinned = false- } else {- // Full repaint — classic circular layout.- const angle = (2 * Math.PI * i) / graph.nodes.length- const r = Math.min(width, height) * 0.35- x = width / 2 + r * Math.cos(angle) + (Math.random() - 0.5) * 50- y = height / 2 + r * Math.sin(angle) + (Math.random() - 0.5) * 50- vx = 0- vy = 0- pinned = false- }+ graphNodes = graph.nodes.map(n => {+ const prior = priorCoords.get(n.slug)+ const placement = layout.placements.get(n.slug)!const node: GNode = {- x, y, vx, vy,+ x: placement.x, y: placement.y, vx: 0, vy: 0,slug: n.slug, title: n.title, type: n.page_type,- linkCount: n.link_count || 0, pinned,+ linkCount: n.link_count || 0, pinned: prior?.pinned ?? false,familiar: !!n.familiar,+ labelWidth: Math.min(n.title.length, 15) * 11,}nodeMap.set(n.slug, node)return node})-- // Node radius based on link count (logarithmic scale to prevent overly large nodes)- function nodeRadius(n: GNode) {- return Math.max(8, Math.min(24, 8 + Math.log(n.linkCount + 1) * 4))- }+ const nodeRadius = (n: GNode) => graphNodeRadius(n.linkCount)// Define arrow markers in SVG <defs>const defs = document.createElementNS('http://www.w3.org/2000/svg', 'defs')@@ -3888,7 +4090,7 @@ function renderGraph(opts: RenderGraphOpts = {}) {markerEnd.setAttribute('orient', 'auto')const arrowPath = document.createElementNS('http://www.w3.org/2000/svg', 'path')arrowPath.setAttribute('d', 'M0,0 L10,3 L0,6 L2,3 Z')- arrowPath.setAttribute('fill', '#c0c4cc')+ arrowPath.setAttribute('fill', graphEdgeColor)markerEnd.appendChild(arrowPath)defs.appendChild(markerEnd)@@ -3903,7 +4105,7 @@ function renderGraph(opts: RenderGraphOpts = {}) {markerStart.setAttribute('orient', 'auto')const arrowPathStart = document.createElementNS('http://www.w3.org/2000/svg', 'path')arrowPathStart.setAttribute('d', 'M10,0 L0,3 L10,6 L8,3 Z')- arrowPathStart.setAttribute('fill', '#c0c4cc')+ arrowPathStart.setAttribute('fill', graphEdgeColor)markerStart.appendChild(arrowPathStart)defs.appendChild(markerStart)@@ -3955,12 +4157,13 @@ function renderGraph(opts: RenderGraphOpts = {}) {const bidir = edgePairSet.has(`${edge.target}→${edge.source}`)const line = document.createElementNS('http://www.w3.org/2000/svg', 'line')- line.setAttribute('stroke', '#c0c4cc')- line.setAttribute('stroke-width', '1.2')- line.setAttribute('stroke-opacity', '0.4')- line.setAttribute('marker-end', 'url(#arrow-end)')+ line.setAttribute('stroke', graphEdgeColor)+ line.setAttribute('stroke-width', graphEdgeWidth)+ line.setAttribute('stroke-opacity', graphEdgeOpacity)+ line.setAttribute('stroke-linecap', 'round')+ if (showArrows.value) line.setAttribute('marker-end', 'url(#arrow-end)')line.style.transition = 'stroke 0.2s, stroke-width 0.2s, stroke-opacity 0.2s'- if (bidir) {+ if (bidir && showArrows.value) {line.setAttribute('marker-start', 'url(#arrow-start)')}edgeG.appendChild(line)@@ -3972,6 +4175,7 @@ function renderGraph(opts: RenderGraphOpts = {}) {for (const n of graphNodes) {const g = document.createElementNS('http://www.w3.org/2000/svg', 'g')g.style.cursor = 'pointer'+ g.setAttribute('data-graph-node', n.slug)const r = nodeRadius(n)@@ -3993,7 +4197,9 @@ function renderGraph(opts: RenderGraphOpts = {}) {const visibleNeighbors = adjacency.get(n.slug)?.size ?? 0const hiddenNeighbors = Math.max(0, n.linkCount - visibleNeighbors)const isEgoCenter = graph.meta?.mode === 'ego' && graph.meta.center === n.slug- const showExpansionRing = hiddenNeighbors > 0 && !isEgoCenter+ // In the overview nearly every page has neighbors beyond the top-N+ // slice, so the ring would only add noise; it guides ego exploration.+ const showExpansionRing = graph.meta?.mode === 'ego' && hiddenNeighbors > 0 && !isEgoCenterconst expansionRing = document.createElementNS('http://www.w3.org/2000/svg', 'circle')expansionRing.setAttribute('r', String(r + 3))expansionRing.setAttribute('fill', 'none')@@ -4036,7 +4242,8 @@ function renderGraph(opts: RenderGraphOpts = {}) {circle.setAttribute('r', String(r))circle.setAttribute('fill', nodeColorMap[n.type] || '#8c8c8c')circle.setAttribute('stroke', '#fff')- circle.setAttribute('stroke-width', '2')+ circle.setAttribute('stroke-width', '1.5')+ circle.classList.add('node-circle')// circle.setAttribute('filter', 'url(#node-shadow)')circle.style.transition = 'r 0.2s, stroke-width 0.2s, opacity 0.2s'g.appendChild(circle)@@ -4122,6 +4329,7 @@ function renderGraph(opts: RenderGraphOpts = {}) {// one node to the next doesn't flash through the fully-unhighlighted state// (which is what caused the whole-graph flickering).g.addEventListener('mouseenter', () => {+ if (performance.now() < graphHoverSuppressedUntil) returnif (graphHoverLeaveTimer) {clearTimeout(graphHoverLeaveTimer)graphHoverLeaveTimer = null@@ -4230,86 +4438,24 @@ function renderGraph(opts: RenderGraphOpts = {}) {nodeEls.push({ g, circle, text, activeRing, node: n })}- // Pan & zoom on SVG background- setupPanZoom(svg, rootG)+ // Measure after all DOM writes to avoid forcing a layout for every node.+ for (const { text, node } of nodeEls) node.labelWidth = text.getComputedTextLength() || node.labelWidth- // Animated force simulation+ // Pan & zoom on SVG background+ const centerNode = nodeMap.get(graphCenter.value)+ const initialFocus = centerNode ?? layout.clusters[0] ?? graphNodes[0]+ const availableWidth = Math.max(160, width - (graphDrawerVisible.value ? 480 : Math.min(240, width * 0.25)))+ setupPanZoom(svg, rootG, previousViewport ?? initialGraphViewport(graphNodes, availableWidth, height, initialFocus))++ // Links and repulsion determine the shape without a circular boundary.+ // Existing nodes stay still during incremental expansion, including pins.+ const retained = new Set(priorCoords.keys())let alpha = 1.0+ let frame = 0function tick() {alpha *= 0.985- if (alpha < 0.02) { graphAnimFrame = 0; return }-- // Repulsion: Optimized using 1D spatial sorting (X-axis) to reduce O(n²) to O(n log n)- // This allows smooth rendering even for > 1000 nodes- const sortedNodes = [...graphNodes].sort((a, b) => a.x - b.x)- const MAX_REPULSION_DIST = 300 // Only calculate repulsion for nodes within 300px- const MAX_REPULSION_DIST_SQ = MAX_REPULSION_DIST * MAX_REPULSION_DIST-- for (let i = 0; i < sortedNodes.length; i++) {- const n1 = sortedNodes[i]- for (let j = i + 1; j < sortedNodes.length; j++) {- const n2 = sortedNodes[j]- const dx = n2.x - n1.x-- // Because nodes are sorted by X, if dx > MAX_REPULSION_DIST,- // all subsequent n2 nodes will also be too far on the X axis, so we can break early- if (dx > MAX_REPULSION_DIST) break-- const dy = n2.y - n1.y- if (Math.abs(dy) > MAX_REPULSION_DIST) continue // Too far on Y axis-- const distSq = dx * dx + dy * dy- if (distSq > MAX_REPULSION_DIST_SQ) continue-- const dist = Math.sqrt(distSq) || 1- // Prevent extremely high repulsion when nodes are very close- const force = (200 * alpha) / Math.max(distSq, 100) * 60- const fx = (dx / dist) * force- const fy = (dy / dist) * force-- if (!n1.pinned) { n1.vx -= fx; n1.vy -= fy }- if (!n2.pinned) { n2.vx += fx; n2.vy += fy }- }- }-- // Attraction along edges- for (const edge of graph.edges) {- const s = nodeMap.get(edge.source)- const t = nodeMap.get(edge.target)- if (!s || !t) continue- const dx = t.x - s.x- const dy = t.y - s.y- const dist = Math.sqrt(dx * dx + dy * dy) || 1- const force = (dist - 120) * 0.005 * alpha- const fx = (dx / dist) * force- const fy = (dy / dist) * force- if (!s.pinned) { s.vx += fx; s.vy += fy }- if (!t.pinned) { t.vx -= fx; t.vy -= fy }- }-- // Center gravity- // Increase gravity slightly when there are more nodes to prevent the graph from expanding too much- const gravityStrength = Math.min(0.01, 0.001 + graphNodes.length * 0.00002)- for (const n of graphNodes) {- if (n.pinned) continue- n.vx += (width / 2 - n.x) * gravityStrength * alpha- n.vy += (height / 2 - n.y) * gravityStrength * alpha- }-- // Apply velocity- for (const n of graphNodes) {- if (n.pinned) continue- n.vx *= 0.6- n.vy *= 0.6- // Cap velocity to prevent nodes from flying off screen during initial explosive layout- const v = Math.sqrt(n.vx * n.vx + n.vy * n.vy)- if (v > 20) {- n.vx = (n.vx / v) * 20- n.vy = (n.vy / v) * 20- }- n.x += n.vx- n.y += n.vy- }+ if (alpha < 0.02) { refreshGraphLabels(); graphAnimFrame = 0; return }+ stepGraphLayout(graphNodes, graph.edges, layout.placements, alpha, retained)// Update SVG positionsfor (const { g, node } of nodeEls) {@@ -4323,6 +4469,7 @@ function renderGraph(opts: RenderGraphOpts = {}) {}}+ if (++frame % 6 === 0) refreshGraphLabels()graphAnimFrame = requestAnimationFrame(tick)}@@ -4345,8 +4492,12 @@ function renderGraph(opts: RenderGraphOpts = {}) {applyGraphFilters()- graphAnimFrame = requestAnimationFrame(tick)+ if (graphNodes.length) graphAnimFrame = requestAnimationFrame(tick)graphReady.value = true+ if (graphSelectedSlug.value && nodeMap.has(graphSelectedSlug.value)) {+ applyHighlight(graphSelectedSlug.value, adjacency, nodeEls, edgeEls)+ }+ refreshGraphLabels()}// Set edge line positions, shortened to stop at node circle boundary so arrows are visible@@ -4357,9 +4508,11 @@ function setEdgePositions(line: SVGLineElement, s: GNode, t: GNode, nodeRadius:const ux = dx / distconst uy = dy / dist- // Shorten each end by the node radius + arrow margin- const rS = nodeRadius(s) + 4- const rT = nodeRadius(t) + 4+ // Shorten each end by the node radius, plus a margin only while arrowheads+ // are drawn; otherwise the gaps form a ring of line ends around every node.+ const margin = graphEdgeMarkersVisible ? 4 : 0+ const rS = nodeRadius(s) + margin+ const rT = nodeRadius(t) + marginline.setAttribute('x1', String(s.x + ux * rS))line.setAttribute('y1', String(s.y + uy * rS))@@ -4377,6 +4530,7 @@ function setupDrag() {let dragging = falselet startX = 0, startY = 0+ let pointerStartX = 0, pointerStartY = 0, moved = falsefunction getPoint(e: MouseEvent | Touch) {const svg = graphSvg@@ -4396,23 +4550,27 @@ function setupDrag(if (e.button !== 0) returne.stopPropagation()dragging = true+ moved = false+ pointerStartX = e.clientX; pointerStartY = e.clientYnode.pinned = trueconst p = getPoint(e)startX = p.x - node.xstartY = p.y - node.y- g.querySelector('circle')?.setAttribute('stroke', nodeColorMap[node.type] || '#8c8c8c')- g.querySelector('circle')?.setAttribute('stroke-width', '3')+ g.querySelector('.node-circle')?.setAttribute('stroke', nodeColorMap[node.type] || '#8c8c8c')+ g.querySelector('.node-circle')?.setAttribute('stroke-width', '2.5')window.addEventListener('mousemove', onMove)window.addEventListener('mouseup', onEnd)}function onMove(e: MouseEvent) {if (!dragging) return+ if (Math.hypot(e.clientX - pointerStartX, e.clientY - pointerStartY) > 4) moved = trueconst p = getPoint(e)node.x = p.x - startXnode.y = p.y - startYnode.vx = 0; node.vy = 0g.setAttribute('transform', `translate(${node.x},${node.y})`)+ refreshGraphLabels()// Update connected edges immediatelyfor (const edge of edgeEls) {if (edge.source === node.slug || edge.target === node.slug) {@@ -4426,19 +4584,22 @@ function setupDrag(function onEnd() {dragging = false// Keep pinned after drag so the node stays where user placed it- g.querySelector('circle')?.setAttribute('stroke', '#fff')- g.querySelector('circle')?.setAttribute('stroke-width', '2')+ g.querySelector('.node-circle')?.setAttribute('stroke', '#fff')+ g.querySelector('.node-circle')?.setAttribute('stroke-width', '1.5')window.removeEventListener('mousemove', onMove)window.removeEventListener('mouseup', onEnd)}g.addEventListener('mousedown', onStart)+ g.addEventListener('click', e => {+ if (moved) { e.preventDefault(); e.stopImmediatePropagation(); moved = false }+ }, true)}// ─── Pan & Zoom ───-function setupPanZoom(svg: SVGSVGElement, rootG: SVGGElement) {- let scale = 1- let translateX = 0, translateY = 0+function setupPanZoom(svg: SVGSVGElement, rootG: SVGGElement, viewport?: { scale: number; x: number; y: number }) {+ let scale = viewport?.scale ?? 1+ let translateX = viewport?.x ?? 0, translateY = viewport?.y ?? 0let panning = falselet panStartX = 0, panStartY = 0let dragStartX = 0, dragStartY = 0@@ -4449,28 +4610,85 @@ function setupPanZoom(svg: SVGSVGElement, rootG: SVGGElement) {}function updateLabelsVisibility() {+ // Arrowheads shrink to specks around every node when zoomed out.+ rootG.classList.toggle('hide-edge-markers', scale < 0.8)+ const markersVisible = showArrows.value && scale >= 0.8+ if (markersVisible !== graphEdgeMarkersVisible) {+ graphEdgeMarkersVisible = markersVisible+ const bySlug = new Map(graphNodes.map(n => [n.slug, n]))+ for (const e of graphEdgeElsRef) {+ const s = bySlug.get(e.source), t = bySlug.get(e.target)+ if (s && t) setEdgePositions(e.line, s, t, n => graphNodeRadius(n.linkCount))+ }+ }// Hide labels when zoomed out too much or hide less important labels// We only want to show labels for important nodes (high link count) when zoomed out- for (const { text, node } of graphNodeElsRef) {- if (node.slug === graphSelectedSlug.value || node.slug === graphHighlightSlug.value) {- text.style.opacity = '1' // Always show selected/highlighted- continue- }-- let visibilityThreshold = 0.5 // Default: need to zoom in to at least 0.5 to see all labels-- // Highly connected nodes get their labels shown earlier- if (node.linkCount > 10) visibilityThreshold = 0.2- else if (node.linkCount > 5) visibilityThreshold = 0.35- else if (node.linkCount > 2) visibilityThreshold = 0.45-- if (scale < visibilityThreshold) {- text.style.opacity = '0'- } else {- text.style.opacity = '1'+ for (const { text, top } of graphSectionEls) {+ text.setAttribute('font-size', String(13 / scale))+ text.setAttribute('y', String(top - 12 / scale))+ }+ const positionsBySlug = new Map(graphNodes.map(n => [n.slug, n]))+ for (const contour of graphContourEls) {+ const { path, cluster } = contour+ const members = cluster.slugs.flatMap(slug => positionsBySlug.has(slug) ? [positionsBySlug.get(slug)!] : [])+ // Panning and hover do not change geometry. Rebuild only after zoom or+ // node movement, keeping the more detailed contour cheap to interact with.+ if (contour.scale !== scale || contour.positions?.length !== members.length * 2+ || members.some((n, i) => contour.positions![i * 2] !== n.x || contour.positions![i * 2 + 1] !== n.y)) {+ path.setAttribute('d', graphClusterOutline(members.map(n => ({ ...n, radius: graphNodeRadius(n.linkCount) })), scale))+ contour.scale = scale+ contour.positions = members.flatMap(n => [n.x, n.y])}+ path.classList.toggle('is-dimmed', graphFocusedSlugs.size > 0 && !graphFocusedSlugs.has(cluster.representative))+ }+ const groupLabels = graphClusterEls.flatMap(({ group, cluster, anchorSlug, labelWidth, priority }) => {+ const anchor = positionsBySlug.get(anchorSlug)+ // While a group is focused, every other group keeps exactly its name,+ // at any zoom, as the way to switch to it.+ const outside = graphFocusedSlugs.size > 0 && !graphFocusedSlugs.has(cluster.representative)+ group.classList.toggle('is-outside-focus', outside)+ const shown = !!anchor && (outside ? anchorSlug === cluster.anchors[0] : scale < 1.2)+ group.style.display = shown ? '' : 'none'+ if (!shown || !anchor) return []+ const labelX = anchor.x+ const labelY = anchor.y + graphNodeRadius(anchor.linkCount) + 18 / scale+ const x = labelX * scale, y = labelY * scale+ group.setAttribute('transform', `translate(${labelX},${labelY}) scale(${1 / scale})`)+ return [{ slug: `anchor:${anchorSlug}`, priority,+ required: outside || anchor.slug === graphSelectedSlug.value || anchor.slug === graphHighlightSlug.value,+ left: x - labelWidth / 2 - 8, right: x + labelWidth / 2 + 8, top: y - 16, bottom: y + 5 }]+ })+ const captionedSlugs = new Set(groupLabels.map(label => label.slug.slice('anchor:'.length)))+ const candidates = graphNodeElsRef.flatMap(({ text, node }) => {+ const required = node.slug === graphSelectedSlug.value || node.slug === graphHighlightSlug.value+ // Keep text legible in screen pixels. At overview scale show a few+ // landmarks; zooming in reveals the individual page labels.+ text.setAttribute('font-size', String(12 / scale))+ text.setAttribute('dy', String(graphNodeRadius(node.linkCount) + 16 / scale))+ // The representative caption replaces its ordinary label at overview+ // scales, including hover/selection, so the page name appears only once.+ if (captionedSlugs.has(node.slug)) return []+ // Reveal names after a modest zoom from the overview. Screen-space+ // collision filtering below controls clutter, regardless of graph size.+ const showDetail = scale >= 0.5 || (graphFocusedSlugs.has(node.slug) && scale >= 0.4)+ const landmark = graphImportantSlugs.has(node.slug) && (groupLabels.length === 0 || scale >= 0.4)+ if (!required && !showDetail && !landmark) return []+ const halfWidth = node.labelWidth * 12 / 11 / 2 + 5+ const baseline = (node.y + graphNodeRadius(node.linkCount)) * scale + 16+ return [{ slug: node.slug, priority: node.linkCount, required,+ left: node.x * scale - halfWidth, right: node.x * scale + halfWidth,+ top: baseline - 15, bottom: baseline + 4 }]+ })+ const visible = visibleGraphLabels([...groupLabels, ...candidates])+ for (const { group, anchorSlug } of graphClusterEls) {+ const shown = visible.has(`anchor:${anchorSlug}`)+ group.style.visibility = shown ? 'visible' : 'hidden'+ group.setAttribute('tabindex', shown ? '0' : '-1')}+ for (const { text, node } of graphNodeElsRef) text.style.opacity = visible.has(node.slug) ? '1' : '0'+}+ refreshGraphLabels = updateLabelsVisibility// Export methods for programmatic pan/zoomlet animId = 0@@ -4479,6 +4697,7 @@ function setupPanZoom(svg: SVGSVGElement, rootG: SVGGElement) {setTranslate: (x: number, y: number) => { translateX = x; translateY = y },apply: applyTransform,getScale: () => scale,+ getTranslate: () => ({ x: translateX, y: translateY }),flyTo: (tx: number, ty: number, s?: number, duration = 400) => {cancelAnimationFrame(animId)const startX = translateX, startY = translateY, startScale = scale@@ -4501,8 +4720,9 @@ function setupPanZoom(svg: SVGSVGElement, rootG: SVGGElement) {// Zoom with mouse wheelsvg.addEventListener('wheel', (e) => {e.preventDefault()+ cancelAnimationFrame(animId)const zoomFactor = e.deltaY > 0 ? 0.92 : 1.08- const newScale = Math.max(0.2, Math.min(5, scale * zoomFactor))+ const newScale = Math.max(0.005, Math.min(5, scale * zoomFactor))// Zoom towards cursorconst rect = svg.getBoundingClientRect()@@ -4518,7 +4738,8 @@ function setupPanZoom(svg: SVGSVGElement, rootG: SVGGElement) {svg.addEventListener('mousedown', (e) => {if (e.button !== 0) return// Only pan if clicking the SVG background, not a node- if ((e.target as Element).tagName === 'svg' || (e.target as Element).tagName === 'SVG') {+ if (!(e.target as Element).closest('[data-graph-node], .graph-cluster-caption')) {+ cancelAnimationFrame(animId)panning = truepanStartX = e.clientX - translateXpanStartY = e.clientY - translateY@@ -4528,30 +4749,48 @@ function setupPanZoom(svg: SVGSVGElement, rootG: SVGGElement) {}})- window.addEventListener('mousemove', (e) => {+ const onMouseMove = (e: MouseEvent) => {if (!panning) returntranslateX = e.clientX - panStartXtranslateY = e.clientY - panStartYapplyTransform()- })+ }- window.addEventListener('mouseup', (e) => {+ const onMouseUp = (e: MouseEvent) => {if (panning) {panning = false- svg.style.cursor = 'default'+ svg.style.cursor = 'grab'// If we barely moved, consider it a click to clear selectionconst dx = e.clientX - dragStartXconst dy = e.clientY - dragStartYif (Math.abs(dx) < 5 && Math.abs(dy) < 5) {- if ((e.target as Element).tagName === 'svg' || (e.target as Element).tagName === 'SVG') {- graphSelectedSlug.value = null- graphDrawerVisible.value = false- clearHighlight(graphNodeElsRef, graphEdgeElsRef)+ if (!(e.target as Element).closest('[data-graph-node], .graph-cluster-caption')) {+ // Clear the innermost state first: a selection, then the group focus.+ if (graphSelectedSlug.value || graphDrawerVisible.value) {+ graphSelectedSlug.value = null+ graphDrawerVisible.value = false+ clearHighlight(graphNodeElsRef, graphEdgeElsRef)+ } else exitGraphFocus()}}}- })+ }+ const onKeyDown = (e: KeyboardEvent) => {+ if (e.key !== 'Escape' || !graphFocusGroup.value || graphDrawerVisible.value) return+ if (e.target instanceof Element && e.target.closest('input, textarea, [contenteditable="true"]')) return+ exitGraphFocus()+ }+ window.addEventListener('mousemove', onMouseMove)+ window.addEventListener('mouseup', onMouseUp)+ window.addEventListener('keydown', onKeyDown)+ disposeGraphPanZoom = () => {+ cancelAnimationFrame(animId)+ window.removeEventListener('mousemove', onMouseMove)+ window.removeEventListener('mouseup', onMouseUp)+ window.removeEventListener('keydown', onKeyDown)+ }+ applyTransform()}// ─── Hover Highlight ───@@ -4562,29 +4801,30 @@ function applyHighlight(edgeEls: { line: SVGLineElement; source: string; target: string; bidir: boolean }[],hoverSlug?: string) {+ refreshGraphLabels()const neighbors = adjacency.get(slug) || new Set()const hoverNeighbors = hoverSlug ? (adjacency.get(hoverSlug) || new Set()) : new Set()// Helper to get consistent radius- const getRadius = (n: GNode) => Math.max(8, Math.min(24, 8 + Math.log(n.linkCount + 1) * 4))+ const getRadius = (n: GNode) => graphNodeRadius(n.linkCount)for (const { g, circle, activeRing, node } of nodeEls) {const r = getRadius(node)if (node.slug === slug) {circle.setAttribute('r', String(r + 3))- circle.setAttribute('stroke-width', '3')+ circle.setAttribute('stroke-width', '2.5')g.style.opacity = '1'} else if (hoverSlug && node.slug === hoverSlug) {circle.setAttribute('r', String(r + 3))- circle.setAttribute('stroke-width', '3')+ circle.setAttribute('stroke-width', '2.5')g.style.opacity = '1'} else if (neighbors.has(node.slug) || (hoverSlug && hoverNeighbors.has(node.slug))) {circle.setAttribute('r', String(r))- circle.setAttribute('stroke-width', '2')+ circle.setAttribute('stroke-width', '1.5')g.style.opacity = '1'} else {circle.setAttribute('r', String(r))- circle.setAttribute('stroke-width', '2')+ circle.setAttribute('stroke-width', '1.5')g.style.opacity = '0.2'}@@ -4596,8 +4836,8 @@ function applyHighlight(}for (const e of edgeEls) {if (e.source === slug || e.target === slug || (hoverSlug && (e.source === hoverSlug || e.target === hoverSlug))) {- e.line.setAttribute('stroke-opacity', '0.9')- e.line.setAttribute('stroke-width', '2')+ e.line.setAttribute('stroke-opacity', '0.85')+ e.line.setAttribute('stroke-width', '1.5')// Determine which node is driving the highlight colorconst focusSlug = (hoverSlug && (e.source === hoverSlug || e.target === hoverSlug)) ? hoverSlug : slug@@ -4606,18 +4846,27 @@ function applyHighlight(] || '#0052d9'e.line.setAttribute('stroke', hlColor)- e.line.setAttribute('marker-end', 'url(#arrow-end-hl)')- if (e.bidir) e.line.setAttribute('marker-start', 'url(#arrow-start-hl)')+ setEdgeMarkers(e, '-hl')} else {+ e.line.setAttribute('stroke', graphEdgeColor)e.line.setAttribute('stroke-opacity', '0.08')- e.line.setAttribute('stroke-width', '1')- e.line.setAttribute('marker-end', 'url(#arrow-end)')- if (e.bidir) e.line.setAttribute('marker-start', 'url(#arrow-start)')- else e.line.removeAttribute('marker-start')+ e.line.setAttribute('stroke-width', graphEdgeWidth)+ setEdgeMarkers(e)}}}+function setEdgeMarkers(e: { line: SVGLineElement; bidir: boolean }, suffix = '') {+ if (!showArrows.value) {+ e.line.removeAttribute('marker-end')+ e.line.removeAttribute('marker-start')+ return+ }+ e.line.setAttribute('marker-end', `url(#arrow-end${suffix})`)+ if (e.bidir) e.line.setAttribute('marker-start', `url(#arrow-start${suffix})`)+ else e.line.removeAttribute('marker-start')+}+function clearHighlight(nodeEls: { g: SVGGElement; circle: SVGCircleElement; text: SVGTextElement; activeRing: SVGCircleElement; node: GNode }[],edgeEls: { line: SVGLineElement; source: string; target: string; bidir: boolean }[],@@ -4627,21 +4876,21 @@ function clearHighlight(return}- const getRadius = (n: GNode) => Math.max(8, Math.min(24, 8 + Math.log(n.linkCount + 1) * 4))+ refreshGraphLabels()+ const getRadius = (n: GNode) => graphNodeRadius(n.linkCount)for (const { g, circle, activeRing, node } of nodeEls) {circle.setAttribute('r', String(getRadius(node)))- circle.setAttribute('stroke-width', '2')- g.style.opacity = '1'+ circle.setAttribute('stroke-width', '1.5')+ g.style.opacity = graphFocusedSlugs.size && !graphFocusedSlugs.has(node.slug) ? '0.12' : '1'activeRing.style.opacity = '0'}for (const e of edgeEls) {- e.line.setAttribute('stroke', '#c0c4cc')- e.line.setAttribute('stroke-width', '1.2')- e.line.setAttribute('stroke-opacity', '0.4')- e.line.setAttribute('marker-end', 'url(#arrow-end)')- if (e.bidir) e.line.setAttribute('marker-start', 'url(#arrow-start)')- else e.line.removeAttribute('marker-start')+ e.line.setAttribute('stroke', graphEdgeColor)+ e.line.setAttribute('stroke-width', graphEdgeWidth)+ const outsideFocus = graphFocusedSlugs.size && (!graphFocusedSlugs.has(e.source) || !graphFocusedSlugs.has(e.target))+ e.line.setAttribute('stroke-opacity', outsideFocus ? '0.05' : graphEdgeOpacity)+ setEdgeMarkers(e)}}@@ -4727,6 +4976,11 @@ let graphAdjacencyRef = new Map<string, Set<string>>()// the target sits in the link_count ranking.async function handleGraphSearchSelect(value: string) {if (!value) return+ // A search result must remain reachable even when its shelf was collapsed.+ if (!showUnlinkedNodes.value && graphUnlinkedSlugs.value.has(value)) {+ showUnlinkedNodes.value = true+ renderGraph()+ }let node = graphNodes.find(n => n.slug === value)if (!node) {@@ -4854,6 +5108,7 @@ onMounted(() => {})onUnmounted(() => {+ disposeGraphPanZoom()if (statsTimer) {clearInterval(statsTimer)}@@ -6071,6 +6326,207 @@ onUnmounted(() => {}// ── Graph ──+.graph-navigation-hint {+ position: absolute;+ left: 20px;+ bottom: 16px;+ pointer-events: none;+ color: var(--td-text-color-placeholder);+ font-size: var(--app-text-sm);+ padding: 5px 9px;+ background: var(--td-bg-color-container);+ border-radius: var(--app-radius-xs);+ z-index: 1;+}++.graph-focus-bar {+ position: absolute;+ left: 50%;+ bottom: 16px;+ transform: translateX(-50%);+ display: flex;+ align-items: center;+ gap: 12px;+ max-width: calc(100% - 360px);+ padding: 6px 6px 6px 14px;+ background: var(--td-bg-color-container);+ border: 1px solid var(--td-component-stroke);+ border-radius: var(--app-radius-pill);+ box-shadow: var(--td-shadow-1);+ font-size: var(--app-text-md);+ color: var(--td-text-color-primary);+ z-index: 2;+ transition: left var(--app-motion-base) ease;++ &.focus-bar-shifted {+ left: calc(50% - 240px);+ }+}++.graph-focus-name {+ display: inline-flex;+ align-items: center;+ gap: 4px;+ min-width: 0;+ max-width: 100%;+ padding: 2px 6px;+ border: 0;+ border-radius: var(--app-radius-sm);+ background: transparent;+ color: inherit;+ font: inherit;+ cursor: pointer;++ span {+ overflow: hidden;+ text-overflow: ellipsis;+ white-space: nowrap;+ }++ &:hover {+ background: var(--td-bg-color-container-hover);+ }++ &:focus-visible {+ outline: 2px solid var(--td-brand-color);+ outline-offset: 1px;+ }+}++span.graph-focus-name {+ display: block;+ overflow: hidden;+ text-overflow: ellipsis;+ white-space: nowrap;+ cursor: default;++ &:hover {+ background: transparent;+ }+}++.graph-focus-back {+ display: inline-flex;+ flex-shrink: 0;+ align-items: center;+ gap: 6px;+ padding: 4px 10px;+ border: 0;+ border-radius: var(--app-radius-pill);+ background: var(--td-brand-color-light);+ color: var(--td-brand-color);+ font: inherit;+ cursor: pointer;++ &:hover {+ background: var(--td-brand-color-focus);+ }++ &:focus-visible {+ outline: 2px solid var(--td-brand-color);+ outline-offset: 1px;+ }++ kbd {+ padding: 0 4px;+ border: 1px solid currentColor;+ border-radius: var(--app-radius-xs);+ font: inherit;+ font-size: var(--app-text-xs);+ line-height: 16px;+ opacity: 0.7;+ }+}++.wiki-graph-canvas :deep(.graph-cluster-outline) {+ fill-opacity: 0.45;+ stroke-opacity: 0;+ transition: fill-opacity var(--app-motion-fast) ease, stroke-opacity var(--app-motion-fast) ease, opacity var(--app-motion-fast) ease;++ &.is-hovered {+ fill-opacity: 0.8;+ stroke-opacity: 0.8;+ }++ &.is-dimmed {+ opacity: 0.3;+ }++ // Previews the group a switch target leads to.+ &.is-dimmed.is-hovered {+ opacity: 1;+ }++ @media (prefers-reduced-motion: reduce) {+ transition: none;+ }+}++.wiki-graph-canvas :deep(.hide-edge-markers line) {+ marker-start: none;+ marker-end: none;+}++.wiki-graph-canvas :deep(.graph-cluster-caption) {+ cursor: zoom-in;+ outline: none;++ text {+ paint-order: stroke;+ stroke: var(--td-bg-color-container);+ stroke-width: 4px;+ stroke-linejoin: round;+ }++ .graph-caption-pill {+ display: none;+ }++ &:hover text,+ &:focus-visible text {+ fill: var(--td-brand-color);+ text-decoration: underline;+ }++ &.is-outside-focus {+ cursor: pointer;++ .graph-caption-pill {+ display: inline;+ fill: var(--td-bg-color-container);+ stroke: var(--td-component-border);+ stroke-width: 1px;+ transition: stroke var(--app-motion-instant) ease;+ }++ text {+ fill: var(--td-text-color-secondary);+ font-weight: 500;+ stroke: none;+ }++ &:hover,+ &:focus-visible {+ .graph-caption-pill {+ stroke: var(--td-brand-color);+ }++ text {+ fill: var(--td-brand-color);+ text-decoration: none;+ }+ }+ }+}++.graph-unlinked-toggle {+ border: 0;+ background: transparent;+ font: inherit;+ color: inherit;+ text-align: left;+}+.wiki-graph {flex: 1;position: relative;diff --git a/frontend/src/views/knowledge/wiki/wikiGraphLayout.test.ts b/frontend/src/views/knowledge/wiki/wikiGraphLayout.test.tsnew file mode 100644index 000000000..3b6a73ac8--- /dev/null+++ b/frontend/src/views/knowledge/wiki/wikiGraphLayout.test.ts@@ -0,0 +1,342 @@+import assert from 'node:assert/strict'+import test from 'node:test'+import {+ selectGraphAnchors, buildGraphLayout, graphNodeRadius, stepGraphLayout, visibleGraphLabels, initialGraphViewport, graphPointBounds, graphClusterOutline,+ type ForceNode, type GraphLink, type LayoutInput,+} from './wikiGraphLayout.ts'++function simulate(inputs: LayoutInput[], edges: GraphLink[], prior = new Map<string, { x: number; y: number }>()) {+ const layout = buildGraphLayout(inputs, edges, 1200, 800, prior)+ const nodes: ForceNode[] = inputs.map(n => ({+ slug: n.slug, linkCount: n.link_count, ...layout.placements.get(n.slug)!,+ vx: 0, vy: 0, pinned: false,+ }))+ const retained = new Set(prior.keys())+ for (let alpha = 1; alpha >= 0.02; alpha *= 0.985) stepGraphLayout(nodes, edges, layout.placements, alpha, retained)+ return { nodes, layout }+}++test('disconnected groups stay apart and isolated pages distinguish missing visible links', () => {+ const inputs = [+ { slug: 'a', link_count: 1 }, { slug: 'b', link_count: 1 },+ { slug: 'c', link_count: 1 }, { slug: 'd', link_count: 1 },+ { slug: 'orphan', link_count: 0 }, { slug: 'outside', link_count: 3 },+ ]+ const edges = [{ source: 'a', target: 'b' }, { source: 'd', target: 'c' }, { source: 'outside', target: 'not-loaded' }]+ const { nodes, layout } = simulate(inputs, edges)+ assert.deepEqual(layout.sections.map(s => [s.kind, s.count]), [['offscreen', 1], ['unlinked', 1]])+ const a = nodes.find(n => n.slug === 'a')!, b = nodes.find(n => n.slug === 'b')!+ const c = nodes.find(n => n.slug === 'c')!, d = nodes.find(n => n.slug === 'd')!+ const within = Math.max(Math.hypot(a.x - b.x, a.y - b.y), Math.hypot(c.x - d.x, c.y - d.y))+ for (const first of [a, b]) for (const second of [c, d]) {+ assert.ok(Math.hypot(first.x - second.x, first.y - second.y) > within)+ }+ for (const section of layout.sections) {+ const node = nodes.find(n => n.slug === (section.kind === 'unlinked' ? 'orphan' : 'outside'))!+ assert.ok(node.x > section.left && node.x < section.right && node.y > section.top && node.y < section.bottom)+ }+})++test('initial positions are stable across API ordering and reverse links', () => {+ const inputs = Array.from({ length: 20 }, (_, i) => ({ slug: `p${i}`, link_count: 2 }))+ const edges = inputs.slice(1).map(n => ({ source: 'p0', target: n.slug }))+ const a = buildGraphLayout(inputs, edges, 900, 600)+ const b = buildGraphLayout([...inputs].reverse(), [...edges].reverse().map(e => ({ source: e.target, target: e.source })), 900, 600)+ for (const n of inputs) assert.deepEqual(a.placements.get(n.slug), b.placements.get(n.slug))+})++test('many small components pack without overlap or forming rows', t => {+ const inputs = Array.from({ length: 500 }, (_, i) => ({ slug: `pair${i}`, link_count: 1 }))+ const edges = inputs.flatMap((n, i) => i % 2 ? [{ source: `pair${i - 1}`, target: n.slug }] : [])+ const start = performance.now()+ const { clusters } = buildGraphLayout(inputs, edges, 1400, 900)+ t.diagnostic(`250 components packed in ${Math.round(performance.now() - start)} ms`)+ assert.equal(clusters.length, 250)+ assert.ok(new Set(clusters.map(c => Math.round(c.y))).size > 100)+ for (let i = 0; i < clusters.length; i++) for (let j = i + 1; j < clusters.length; j++) {+ const a = clusters[i]!, b = clusters[j]!+ assert.ok(a.right <= b.left || a.left >= b.right || a.bottom <= b.top || a.top >= b.bottom)+ }+})++test('empty and entirely unlinked graphs have finite, nonoverlapping positions', () => {+ assert.equal(buildGraphLayout([], [], 800, 600).placements.size, 0)+ const inputs = Array.from({ length: 500 }, (_, i) => ({ slug: `orphan${i}`, link_count: 0 }))+ const { nodes, layout } = simulate(inputs, [])+ assert.deepEqual(layout.sections.map(s => [s.kind, s.count]), [['unlinked', 500]])+ for (let i = 0; i < nodes.length; i++) for (let j = i + 1; j < nodes.length; j++) {+ assert.ok(Math.hypot(nodes[i]!.x - nodes[j]!.x, nodes[i]!.y - nodes[j]!.y) > 50)+ }+})++test('500 and 1500 node graphs settle with finite positions and node clearance', t => {+ for (const count of [500, 1500]) {+ const inputs = Array.from({ length: count }, (_, i) => ({ slug: `p${i}`, link_count: i % 50 === 0 ? 49 : 1 }))+ const edges = inputs.flatMap((n, i) => i % 50 ? [{ source: `p${i - i % 50}`, target: n.slug }] : [])+ const start = performance.now()+ const { nodes } = simulate(inputs, edges)+ t.diagnostic(`${count} nodes settled in ${Math.round(performance.now() - start)} ms (pure layout, no DOM)`)+ for (const n of nodes) {+ assert.ok(Number.isFinite(n.x) && Number.isFinite(n.y))+ }+ for (let i = 0; i < nodes.length; i++) for (let j = i + 1; j < nodes.length; j++) {+ const a = nodes[i]!, b = nodes[j]!+ assert.ok(Math.hypot(a.x - b.x, a.y - b.y) >= graphNodeRadius(a.linkCount) + graphNodeRadius(b.linkCount) + 15,+ `${count}: ${a.slug} overlaps ${b.slug}`)+ }+ }+})++test('incremental expansion holds existing nodes and settles new neighbors', () => {+ const prior = new Map([['a', { x: 111, y: 222 }], ['b', { x: 260, y: 222 }]])+ const inputs = Array.from({ length: 30 }, (_, i) => ({ slug: i === 0 ? 'a' : i === 1 ? 'b' : `new${i}`, link_count: 1 }))+ const edges = inputs.slice(1).map(n => ({ source: 'a', target: n.slug }))+ const { nodes } = simulate(inputs, edges, prior)+ for (const [slug, point] of prior) {+ const n = nodes.find(n => n.slug === slug)!+ assert.deepEqual({ x: n.x, y: n.y }, point)+ }+ for (const n of nodes.slice(2)) {+ assert.ok(Number.isFinite(n.x) && Number.isFinite(n.y))+ assert.ok(Math.hypot(n.x - 111, n.y - 222) > 32)+ }+})++test('a large hub with 1499 neighbors settles with node clearance', t => {+ const inputs = Array.from({ length: 1500 }, (_, i) => ({ slug: `hub${i}`, link_count: i ? 1 : 1499 }))+ const edges = inputs.slice(1).map(n => ({ source: 'hub0', target: n.slug }))+ const start = performance.now()+ const { nodes } = simulate(inputs, edges)+ t.diagnostic(`1500 nodes in one component settled in ${Math.round(performance.now() - start)} ms (no DOM)`)+ for (let i = 0; i < nodes.length; i++) for (let j = i + 1; j < nodes.length; j++) {+ const a = nodes[i]!, b = nodes[j]!+ assert.ok(Math.hypot(a.x - b.x, a.y - b.y) >= graphNodeRadius(a.linkCount) + graphNodeRadius(b.linkCount) + 14,+ `${a.slug} overlaps ${b.slug}`)+ }+})++test('collision separates coincident nodes while respecting a dragged pin', () => {+ const inputs = [{ slug: 'a', link_count: 10 }, { slug: 'b', link_count: 10 }]+ const layout = buildGraphLayout(inputs, [{ source: 'a', target: 'b' }], 800, 600)+ const nodes: ForceNode[] = inputs.map(n => ({ slug: n.slug, linkCount: n.link_count, x: 400, y: 300, vx: 0, vy: 0, pinned: n.slug === 'a' }))+ for (let i = 0; i < 10; i++) stepGraphLayout(nodes, [], layout.placements, 0.02)+ assert.equal(nodes[0]!.x, 400)+ assert.equal(nodes[0]!.y, 300)+ assert.ok(Math.hypot(nodes[0]!.x - nodes[1]!.x, nodes[0]!.y - nodes[1]!.y) >= graphNodeRadius(10) * 2 + 15)+})++test('overlapping labels favor important nodes, but focused labels always stay readable', () => {+ const box = { left: 0, right: 100, top: 0, bottom: 20 }+ const labels = [+ { ...box, slug: 'low', priority: 1 }, { ...box, slug: 'high', priority: 20 },+ { ...box, left: 200, right: 300, slug: 'separate', priority: 0 },+ ]+ assert.deepEqual([...visibleGraphLabels(labels)], ['high', 'separate'])+ assert.deepEqual([...visibleGraphLabels([...labels, { ...box, slug: 'selected', priority: 0, required: true }])], ['selected', 'separate'])+})+++test('long chains keep their elongated topology and reserve space away from other groups', () => {+ const inputs = Array.from({ length: 40 }, (_, i) => ({ slug: `chain${String(i).padStart(2, '0')}`, link_count: 2 }))+ const edges = inputs.flatMap((n, i) => i % 20 ? [{ source: inputs[i - 1]!.slug, target: n.slug }] : [])+ const { nodes, layout } = simulate(inputs, edges)+ for (const cluster of layout.clusters) {+ const members = nodes.filter(n => cluster.slugs.includes(n.slug))+ const bounds = graphPointBounds(members)+ const mean = { x: members.reduce((s, n) => s + n.x, 0) / members.length, y: members.reduce((s, n) => s + n.y, 0) / members.length }+ const xx = members.reduce((s, n) => s + (n.x - mean.x) ** 2, 0)+ const yy = members.reduce((s, n) => s + (n.y - mean.y) ** 2, 0)+ const xy = members.reduce((s, n) => s + (n.x - mean.x) * (n.y - mean.y), 0)+ const delta = Math.hypot(xx - yy, 2 * xy)+ // Principal axes make this invariant to the chain's heading.+ assert.ok((xx + yy + delta) / Math.max(1, xx + yy - delta) > 9)+ assert.ok(Math.hypot(bounds.right - bounds.left, bounds.bottom - bounds.top) > 1500)+ }+ const first = nodes.slice(0, 20), second = nodes.slice(20)+ for (const a of first) for (const b of second) assert.ok(Math.hypot(a.x - b.x, a.y - b.y) > 250)+})++test('large canvases start readable around the focus instead of fitting every node', () => {+ const points = [{ x: -4000, y: -2000 }, { x: 5000, y: 3000 }]+ const focus = { x: 300, y: 400 }+ const view = initialGraphViewport(points, 1200, 800, focus)+ assert.equal(view.scale, 0.4)+ assert.equal(focus.x * view.scale + view.x, 600)+ assert.equal(focus.y * view.scale + view.y, 400)+ assert.ok(points[1]!.x * view.scale + view.x > 1200)+ assert.equal(initialGraphViewport([{ x: 0, y: 0 }, { x: 100, y: 100 }], 1200, 800).scale, 0.85)+ assert.ok(Object.values(initialGraphViewport([], 1200, 800)).every(Number.isFinite))+})+++test('group outlines follow displaced nodes and handle empty or coincident input', () => {+ assert.equal(graphClusterOutline([]), '')+ for (const points of [[{ x: 0, y: 0 }], [{ x: 0, y: 0 }, { x: 0, y: 0 }], [{ x: 0, y: 0 }, { x: 200, y: 10 }, { x: 800, y: 400 }]]) {+ const path = graphClusterOutline(points)+ assert.ok(path.startsWith('M') && path.endsWith('Z'))+ assert.ok(!path.includes('NaN') && !path.includes('Infinity'))+ assert.equal(graphClusterOutline([...points].reverse()), path)+ }+ assert.notEqual(graphClusterOutline([{ x: 0, y: 0 }, { x: 200, y: 0 }]), graphClusterOutline([{ x: 0, y: 0 }, { x: 400, y: 0 }]))+})+++test('landmarks cover separate dense neighborhoods instead of only the largest one', () => {+ const sizes = [40, 30, 20]+ const slugs = sizes.flatMap((size, group) => Array.from({ length: size }, (_, i) => `region${group}-${i}`))+ const adjacency = new Map(slugs.map(slug => [slug, new Set<string>()]))+ const link = (a: string, b: string) => { adjacency.get(a)!.add(b); adjacency.get(b)!.add(a) }+ sizes.forEach((size, group) => {+ for (let i = 0; i < size; i++) for (let j = i + 1; j < size; j++) link(`region${group}-${i}`, `region${group}-${j}`)+ })+ link('region0-0', 'region1-0'); link('region1-0', 'region2-0')+ const anchors = selectGraphAnchors(slugs, adjacency)+ assert.equal(anchors.length, 3)+ assert.equal(new Set(anchors.map(slug => slug.split('-')[0])).size, 3)+ const reversed = new Map([...adjacency].reverse().map(([slug, neighbors]) => [slug, new Set([...neighbors].reverse())]))+ assert.deepEqual(selectGraphAnchors([...slugs].reverse(), reversed), anchors)+})++test('one hub does not create artificial extra themes and external neighbors do not affect landmarks', () => {+ const slugs = Array.from({ length: 200 }, (_, i) => `page${i}`)+ const adjacency = new Map(slugs.map(slug => [slug, new Set<string>()]))+ for (const slug of slugs.slice(1)) { adjacency.get('page0')!.add(slug); adjacency.get(slug)!.add('page0') }+ adjacency.get('page199')!.add('outside-the-component')+ assert.deepEqual(selectGraphAnchors(slugs, adjacency), ['page0'])+ assert.deepEqual(selectGraphAnchors([], adjacency), [])+})++test('landmark budgets scale from small to large components with a maximum of five', () => {+ for (const [size, expected] of [[10, 1], [30, 2], [75, 3], [150, 4], [500, 5]]) {+ const slugs = Array.from({ length: size! }, (_, i) => `p${i}`)+ const adjacency = new Map(slugs.map((slug, i) => [slug, new Set([slugs[i - 1], slugs[i + 1]].filter((s): s is string => !!s))]))+ const anchors = selectGraphAnchors(slugs, adjacency)+ assert.equal(anchors.length, expected)+ assert.equal(new Set(anchors).size, expected)+ if (size! >= 30) {+ const indices = anchors.map(slug => Number(slug.slice(1)))+ assert.ok(Math.max(...indices) - Math.min(...indices) > size! * 0.7)+ }+ const inputs = slugs.map(slug => ({ slug, link_count: adjacency.get(slug)!.size }))+ const edges = slugs.slice(1).map((slug, i) => ({ source: slugs[i]!, target: slug }))+ assert.deepEqual(buildGraphLayout(inputs, edges, 1200, 800).clusters[0]!.anchors, anchors)+ }+})++test('the main subject leads, and a separate configuration theme is named instead of a second name for the same theme', () => {+ const names = ['platform', 'enterprise', 'configuration',+ ...Array.from({ length: 12 }, (_, i) => `shared${i}`),+ ...Array.from({ length: 10 }, (_, i) => `platformDetail${i}`),+ ...Array.from({ length: 4 }, (_, i) => `enterpriseDetail${i}`),+ ...Array.from({ length: 6 }, (_, i) => `configurationDetail${i}`)]+ const adjacency = new Map(names.map(slug => [slug, new Set<string>()]))+ const edges: GraphLink[] = []+ const link = (a: string, b: string) => { adjacency.get(a)!.add(b); adjacency.get(b)!.add(a); edges.push({ source: a, target: b }) }+ for (let i = 0; i < 12; i++) { link('platform', `shared${i}`); link('enterprise', `shared${i}`) }+ for (let i = 0; i < 10; i++) link('platform', `platformDetail${i}`)+ for (let i = 0; i < 4; i++) link('enterprise', `enterpriseDetail${i}`)+ for (let i = 0; i < 6; i++) link('configuration', `configurationDetail${i}`)+ for (let i = 0; i < 3; i++) link('configuration', `shared${i}`)+ link('platform', 'enterprise'); link('enterprise', 'configuration')+ const nodes = names.map(slug => ({ slug, link_count: adjacency.get(slug)!.size,+ page_type: ['platform', 'enterprise'].includes(slug) ? 'entity' : 'concept' }))+ const layout = buildGraphLayout(nodes, edges, 1200, 800)+ // enterprise shares twelve neighbors with platform: one theme, one name.+ assert.deepEqual(layout.clusters[0]!.anchors, ['platform', 'configuration'])+ assert.deepEqual(buildGraphLayout([...nodes].reverse(), [...edges].reverse(), 1200, 800).clusters[0]!.anchors, layout.clusters[0]!.anchors)+})++test('a subject linked to most pages of every theme names the component alone', () => {+ const slugs = ['hub', ...Array.from({ length: 3 }, (_, g) => Array.from({ length: 10 }, (_, i) => `t${g}-${i}`)).flat()]+ const adjacency = new Map(slugs.map(slug => [slug, new Set<string>()]))+ const link = (a: string, b: string) => { adjacency.get(a)!.add(b); adjacency.get(b)!.add(a) }+ for (let g = 0; g < 3; g++) {+ for (let i = 0; i < 10; i++) for (let j = i + 1; j < 10; j++) link(`t${g}-${i}`, `t${g}-${j}`)+ // One document: its subject links to nearly every page in each section.+ for (let i = 0; i < 8; i++) link('hub', `t${g}-${i}`)+ }+ assert.deepEqual(selectGraphAnchors(slugs, adjacency), ['hub'])+})++test('a theme is not named again by a page whose title repeats an existing label', () => {+ const sizes = [30, 20]+ const slugs = sizes.flatMap((size, g) => Array.from({ length: size }, (_, i) => `r${g}-${i}`))+ const adjacency = new Map(slugs.map(slug => [slug, new Set<string>()]))+ const link = (a: string, b: string) => { adjacency.get(a)!.add(b); adjacency.get(b)!.add(a) }+ sizes.forEach((size, g) => {+ for (let i = 0; i < size; i++) for (let j = i + 1; j < size; j++) link(`r${g}-${i}`, `r${g}-${j}`)+ })+ link('r0-0', 'r1-0')+ const pages = new Map([+ ['r0-0', { page_type: 'concept', title: '第三代社保卡' }],+ ['r1-0', { page_type: 'entity', title: '北京市第三代社保卡' }],+ ['r1-1', { page_type: 'concept', title: '线上申领' }],+ ])+ assert.deepEqual(selectGraphAnchors(slugs, adjacency, pages), ['r0-0', 'r1-1'])+})++test('a summary names the document it dominates, but a nearly as central entity still wins', () => {+ const pages = new Map([+ ['summary', { page_type: 'summary', title: '初中63组语文古诗词高频考点(2).pdf - Summary' }],+ ['subject', { page_type: 'entity', title: '范仲淹' }],+ ])+ const anchorsWhenSubjectLinks = (details: number) => {+ const slugs = ['summary', 'subject', ...Array.from({ length: 10 }, (_, i) => `detail${i}`)]+ const adjacency = new Map(slugs.map(slug => [slug, new Set<string>()]))+ const link = (a: string, b: string) => { adjacency.get(a)!.add(b); adjacency.get(b)!.add(a) }+ for (const slug of slugs.slice(1)) link('summary', slug)+ for (let i = 0; i < details; i++) link('subject', `detail${i}`)+ return selectGraphAnchors(slugs, adjacency, pages)+ }+ assert.deepEqual(anchorsWhenSubjectLinks(5), ['summary'])+ assert.deepEqual(anchorsWhenSubjectLinks(9), ['subject'])+})++test('a component of several documents also names the page they share', () => {+ const anchorsWithBridgeDetails = (details: number) => {+ const slugs: string[] = ['bridge']+ const adjacency = new Map<string, Set<string>>([['bridge', new Set()]])+ const link = (a: string, b: string) => {+ for (const s of [a, b]) if (!adjacency.has(s)) { adjacency.set(s, new Set()); slugs.push(s) }+ adjacency.get(a)!.add(b); adjacency.get(b)!.add(a)+ }+ const pages = new Map<string, { page_type: string; title: string }>([['bridge', { page_type: 'concept', title: '强化学习' }]])+ for (let d = 0; d < 3; d++) {+ pages.set(`doc${d}`, { page_type: 'summary', title: `论文${d}.pdf - Summary` })+ for (let i = 0; i < 8; i++) {+ link(`doc${d}`, `d${d}-${i}`)+ if (i > 0) link(`d${d}-${i}`, `d${d}-${i - 1}`)+ }+ link('bridge', `doc${d}`)+ for (let i = 0; i < details; i++) link('bridge', `d${d}-${i}`)+ }+ return selectGraphAnchors(slugs, adjacency, pages)+ }+ const named = anchorsWithBridgeDetails(1)+ assert.equal(named.at(-1), 'bridge')+ assert.ok(named.slice(0, -1).every(slug => slug.startsWith('doc')), named.join())+ // Shared by every document but barely linked: a detail, not what ties them.+ assert.ok(!anchorsWithBridgeDetails(0).includes('bridge'))+})++test('an identifier-like file name does not name a theme over a readable page', () => {+ const slugs = ['summary', 'subject', ...Array.from({ length: 10 }, (_, i) => `detail${i}`)]+ const adjacency = new Map(slugs.map(slug => [slug, new Set<string>()]))+ const link = (a: string, b: string) => { adjacency.get(a)!.add(b); adjacency.get(b)!.add(a) }+ for (const slug of slugs.slice(1)) link('summary', slug)+ for (let i = 0; i < 5; i++) link('subject', `detail${i}`)+ const pages = new Map([+ ['summary', { page_type: 'summary', title: '2412.18925v1.pdf - Summary' }],+ ['subject', { page_type: 'entity', title: '香港中文大学(深圳)' }],+ ])+ assert.deepEqual(selectGraphAnchors(slugs, adjacency, pages), ['subject'])+})++test('entity preference breaks a close ranking without displacing a substantially stronger concept', () => {+ const inputs = Array.from({ length: 12 }, (_, i) => ({ slug: `page${i}`, link_count: 0, page_type: i === 1 ? 'entity' : 'concept' }))+ const edges = inputs.slice(1).map(n => ({ source: 'page0', target: n.slug }))+ assert.deepEqual(buildGraphLayout(inputs, edges, 1200, 800).clusters[0]!.anchors, ['page0'])+ // Two equally connected pages: the entity is the more useful overview anchor.+ const pair = [{ slug: 'a-concept', link_count: 1, page_type: 'concept' }, { slug: 'z-entity', link_count: 1, page_type: 'entity' }]+ assert.deepEqual(buildGraphLayout(pair, [{ source: pair[0]!.slug, target: pair[1]!.slug }], 1200, 800).clusters[0]!.anchors, ['z-entity'])+})diff --git a/frontend/src/views/knowledge/wiki/wikiGraphLayout.ts b/frontend/src/views/knowledge/wiki/wikiGraphLayout.tsnew file mode 100644index 000000000..3031577c8--- /dev/null+++ b/frontend/src/views/knowledge/wiki/wikiGraphLayout.ts@@ -0,0 +1,579 @@+// Geometry is independent of SVG so dense and disconnected graphs can be+// exercised without a browser. Coordinates are world units, not screen pixels.+export interface GraphPoint { x: number; y: number }+export interface GraphLink { source: string; target: string }+export interface LayoutInput { slug: string; link_count: number; page_type?: string; title?: string }+export interface GraphBounds { left: number; top: number; right: number; bottom: number }+export interface LayoutPlacement extends GraphPoint {+ center: GraphPoint+ stationary?: boolean+ degree?: number+}+export interface GraphCluster extends GraphPoint, GraphBounds {+ slugs: string[]+ representative: string+ anchors: string[]+}+export interface GraphSection extends GraphBounds {+ kind: 'unlinked' | 'offscreen'+ count: number+}++export function graphNodeRadius(linkCount: number): number {+ // Square-root scaling keeps leaves small so hubs read as landmarks.+ return Math.max(5, Math.min(20, 4 + Math.sqrt(Math.max(0, linkCount)) * 1.8))+}++/** Deterministic multi-level Louvain over an undirected, unweighted graph.+ * Returns a community index per node; callers must pass nodes in a stable+ * order because ties are resolved by index.+ */+export function graphCommunities(neighbors: readonly (readonly number[])[]): number[] {+ const n = neighbors.length+ let membership = Array.from({ length: n }, (_, i) => i)+ // Level graph: weighted adjacency between super-nodes plus the weight of+ // edges already collapsed inside each super-node.+ let weights: Map<number, number>[] = neighbors.map(list => {+ const row = new Map<number, number>()+ for (const j of list) row.set(j, (row.get(j) ?? 0) + 1)+ return row+ })+ let inner = new Array<number>(n).fill(0)+ for (;;) {+ const size = weights.length+ const degree = weights.map((row, i) => [...row.values()].reduce((sum, w) => sum + w, 0) + 2 * inner[i]!)+ const total = degree.reduce((sum, d) => sum + d, 0)+ if (!total) break+ const community = Array.from({ length: size }, (_, i) => i)+ const tot = [...degree]+ let movedAny = false+ for (let pass = 0; pass < 32; pass++) {+ let moved = false+ for (let i = 0; i < size; i++) {+ const own = community[i]!+ const links = new Map<number, number>()+ for (const [j, w] of weights[i]!) links.set(community[j]!, (links.get(community[j]!) ?? 0) + w)+ tot[own] -= degree[i]!+ let best = own, bestGain = (links.get(own) ?? 0) - tot[own]! * degree[i]! / total+ for (const c of [...links.keys()].sort((a, b) => a - b)) {+ const gain = links.get(c)! - tot[c]! * degree[i]! / total+ if (gain > bestGain + 1e-9) { best = c; bestGain = gain }+ }+ tot[best] += degree[i]!+ if (best !== own) { community[i] = best; moved = true; movedAny = true }+ }+ if (!moved) break+ }+ if (!movedAny) break+ const renumber = new Map<number, number>()+ for (const c of community) if (!renumber.has(c)) renumber.set(c, renumber.size)+ const next = Array.from({ length: renumber.size }, () => new Map<number, number>())+ const nextInner = new Array<number>(renumber.size).fill(0)+ for (let i = 0; i < size; i++) {+ const ci = renumber.get(community[i]!)!+ nextInner[ci] += inner[i]!+ for (const [j, w] of weights[i]!) {+ const cj = renumber.get(community[j]!)!+ // Each undirected edge appears in both rows; count it once inside.+ if (ci === cj) nextInner[ci] += w / 2+ else next[ci]!.set(cj, (next[ci]!.get(cj) ?? 0) + w)+ }+ }+ membership = membership.map(c => renumber.get(community[c]!)!)+ weights = next; inner = nextInner+ if (renumber.size === size) break+ }+ return membership+}++/** Landmark caption text: summary pages carry their source file name. */+export function graphLandmarkTitle(title: string): string {+ const name = title.replace(/\s*-\s*Summary$/i, '')+ .replace(/\.(pdf|docx?|pptx?|xlsx?|csv|md|txt|html?|json|ya?ml|xml|png|jpe?g)$/i, '')+ .replace(/\s*[((]\d+[))]$/, '').trim()+ return name || title+}++// A summary is named after its source file, which usually names the document+// well, so it only yields near-ties to entities and concepts. Index pages are+// navigation and a poor name for a region even when they link to all of it.+const anchorTypeQuality: Record<string, number> = {+ entity: 1.15, concept: 1, synthesis: 0.8, comparison: 0.8, summary: 0.9, index: 0.2,+}++/** Name a connected component and its distinct themes.+ * The first landmark is the component's most prominent readable page, even+ * when it bridges every theme. Communities are the themes; each contributes+ * at most one landmark, chosen by its links inside the theme and how well its+ * title reads as a name. Themes mostly linked to an existing landmark, and+ * pages that repeat one, get no extra name. Later picks favor larger themes+ * far from earlier labels so names spread instead of stacking up. A component+ * built from several documents also names the page most of them share.+ */+export function selectGraphAnchors(+ slugs: string[], adjacency: ReadonlyMap<string, ReadonlySet<string>>,+ pages: ReadonlyMap<string, Pick<LayoutInput, 'page_type' | 'title'>> = new Map(),+): string[] {+ if (!slugs.length) return []+ const order = [...new Set(slugs)].sort()+ const index = new Map(order.map((slug, i) => [slug, i]))+ const neighbors = order.map(slug => [...(adjacency.get(slug) ?? [])]+ .flatMap(n => index.has(n) && n !== slug ? [index.get(n)!] : []).sort((a, b) => a - b))+ const membership = graphCommunities(neighbors)+ const groups = new Map<number, number[]>()+ membership.forEach((c, i) => { const group = groups.get(c) ?? []; group.push(i); groups.set(c, group) })++ const quality = (i: number) => {+ const page = pages.get(order[i]!)+ const title = graphLandmarkTitle(page?.title ?? '')+ // An identifier such as an arXiv file name ("2412.18925v1") has no word to read.+ const readable = /[\u4e00-\u9fff]{2}|[a-z]{3}/i.test(title) ? 1 : 0.3+ return (anchorTypeQuality[page?.page_type ?? ''] ?? 1) * (title.length > 18 ? 0.6 : 1) * readable+ }+ const best = (group: number[], score: (i: number) => number) => group.reduce((top, i) => {+ const a = score(i), b = score(top)+ return a > b + 1e-9 || (Math.abs(a - b) <= 1e-9 && neighbors[i]!.length > neighbors[top]!.length) ? i : top+ })+ // A theme is named by a page that lives in it; links elsewhere still count+ // for some prominence.+ const themes = [...groups.values()].map(group => {+ const inside = new Set(group)+ const score = (i: number) => {+ const internal = neighbors[i]!.filter(j => inside.has(j)).length+ return (internal + 0.5 * (neighbors[i]!.length - internal) + 1) * quality(i)+ }+ const ranked = [...group].sort((a, b) => score(b) - score(a) || neighbors[b]!.length - neighbors[a]!.length || a - b)+ return { size: group.length, ranked, members: inside }+ }).sort((a, b) => b.size - a.size || a.ranked[0]! - b.ranked[0]!)++ const name = best(order.map((_, i) => i), i => (neighbors[i]!.length + 1) * quality(i))+ const home = themes.find(theme => theme.members.has(name))!+ // Fragments of a theme are not themes of their own.+ const minimum = Math.max(3, themes[0]!.size * 0.3)+ const candidates = themes.filter(theme => theme !== home && theme.size >= minimum)+ // A second name for something already labeled: nearly the same+ // neighborhood (an author next to their paper) or a title that contains+ // the other ("北京市第三代社保卡" next to "第三代社保卡").+ const closed = (i: number) => new Set([i, ...neighbors[i]!])+ const normalized = (i: number) => graphLandmarkTitle(pages.get(order[i]!)?.title ?? '')+ .toLowerCase().replace(/[\s《》“”"'‘’()()·・]/g, '')+ const redundant = (i: number, chosen: number[]) => chosen.some(s => {+ const a = closed(i), b = closed(s)+ const shared = [...a].filter(x => b.has(x)).length+ if (shared / (a.size + b.size - shared) >= 0.5) return true+ const x = normalized(i), y = normalized(s)+ return !!x && !!y && (x.includes(y) || y.includes(x))+ })+ const budget = order.length < 16 ? 1 : order.length < 50 ? 2 : order.length < 100 ? 3 : order.length < 200 ? 4 : 5+ const bfs = (start: number) => {+ const distance = new Array<number>(order.length).fill(Infinity)+ distance[start] = 0+ const queue = [start]+ for (let q = 0; q < queue.length; q++) {+ for (const j of neighbors[queue[q]!]!) {+ if (distance[j] !== Infinity) continue+ distance[j] = distance[queue[q]!]! + 1; queue.push(j)+ }+ }+ return distance+ }+ // Labels count as fully separated once they are a fair share of the+ // component's diameter apart; closer than that, a larger theme still wins.+ const nearest = bfs(name)+ const far = nearest.reduce((top, d, i) => d !== Infinity && d > nearest[top]! ? i : top, name)+ const diameter = Math.max(...bfs(far).filter(Number.isFinite))+ const reach = Math.max(2, diameter / budget)+ const selected = [name]+ const open = new Set(candidates)+ while (selected.length < budget && open.size) {+ let pick: { theme: typeof candidates[number]; label: number } | undefined, bestScore = -1+ for (const theme of open) {+ // Most of the theme already hangs off an existing label (one document+ // around its subject): another name would only be a detail page.+ const covered = selected.some(s => neighbors[s]!.filter(j => theme.members.has(j)).length * 2 >= theme.size)+ const label = covered ? undefined : theme.ranked.find(i => !redundant(i, selected))+ if (label === undefined) { open.delete(theme); continue }+ const score = Math.sqrt(theme.size) * Math.min(nearest[label]!, reach) / reach+ if (score > bestScore + 1e-9 || (Math.abs(score - bestScore) <= 1e-9 && pick && nearest[label]! > nearest[pick.label]!)) {+ pick = { theme, label }; bestScore = score+ }+ }+ if (!pick) break+ open.delete(pick.theme)+ selected.push(pick.label)+ bfs(pick.label).forEach((d, i) => { nearest[i] = Math.min(nearest[i]!, d) })+ }++ // Themes mostly follow documents, so their names say which documents are+ // here but not why they belong together. A page shared by most of them+ // says that; it is added unless a label already is one.+ const documents = new Set(order.flatMap((slug, i) => pages.get(slug)?.page_type === 'summary' ? [i] : []))+ if (documents.size >= 2) {+ const spans = (i: number) => documents.has(i) ? 0 : neighbors[i]!.filter(j => documents.has(j)).length+ const needed = Math.max(2, Math.ceil(documents.size * 2 / 3))+ if (!selected.some(s => spans(s) >= needed)) {+ const weakest = Math.min(...selected.map(s => neighbors[s]!.length))+ const prominence = (i: number) => (neighbors[i]!.length + 1) * quality(i)+ const bridge = order.map((_, i) => i)+ .filter(i => spans(i) >= needed && neighbors[i]!.length >= weakest * 0.6 && !redundant(i, selected))+ .reduce<number | undefined>((top, i) => top === undefined || spans(i) > spans(top)+ || (spans(i) === spans(top) && prominence(i) > prominence(top) + 1e-9) ? i : top, undefined)+ if (bridge !== undefined) selected.push(bridge)+ }+ }+ return selected.map(i => order[i]!)+}++/** Pack connected components separately; singletons get two explicit shelves.+ * A missing visible edge is not evidence that the page has no links in the KB.+ */+export function buildGraphLayout(+ nodes: LayoutInput[], edges: GraphLink[], width: number, height: number,+ prior: ReadonlyMap<string, GraphPoint> = new Map(),+) {+ const nodeBySlug = new Map(nodes.map(n => [n.slug, n]))+ const adjacency = new Map(nodes.map(n => [n.slug, new Set<string>()]))+ for (const e of edges) {+ if (e.source === e.target || !nodeBySlug.has(e.source) || !nodeBySlug.has(e.target)) continue+ adjacency.get(e.source)!.add(e.target)+ adjacency.get(e.target)!.add(e.source)+ }+ const components: string[][] = []+ const unlinked: string[] = []+ const offscreen: string[] = []+ const visited = new Set<string>()+ for (const slug of [...nodeBySlug.keys()].sort()) {+ if (visited.has(slug)) continue+ visited.add(slug)+ if (!adjacency.get(slug)!.size) {+ ;(nodeBySlug.get(slug)!.link_count > 0 ? offscreen : unlinked).push(slug)+ continue+ }+ const component = [slug]+ for (let i = 0; i < component.length; i++) {+ for (const neighbor of adjacency.get(component[i]!)!) {+ if (visited.has(neighbor)) continue+ visited.add(neighbor)+ component.push(neighbor)+ }+ }+ components.push(component.sort())+ }+ components.sort((a, b) => b.length - a.length || (a[0]! < b[0]! ? -1 : 1))++ // Reserve space from each component's topology, not a circular boundary.+ // These envelopes only place groups initially; the simulation never clips+ // nodes to them or pulls individual nodes towards a common center.+ const aspect = Math.min(1.8, Math.max(0.8, width / Math.max(height, 1)))+ const stretch = Math.sqrt(aspect)+ const goldenAngle = Math.PI * (3 - Math.sqrt(5))+ const clusters: GraphCluster[] = []+ const seeds = new Map<string, GraphPoint>()+ const cellSize = 500+ const cells = new Map<string, GraphCluster[]>()+ const keysFor = (bounds: GraphBounds) => {+ const keys: string[] = []+ for (let gx = Math.floor(bounds.left / cellSize); gx <= Math.floor(bounds.right / cellSize); gx++) {+ for (let gy = Math.floor(bounds.top / cellSize); gy <= Math.floor(bounds.bottom / cellSize); gy++) keys.push(`${gx},${gy}`)+ }+ return keys+ }+ for (const slugs of components) {+ const representative = [...slugs].sort((a, b) => adjacency.get(b)!.size - adjacency.get(a)!.size || (a < b ? -1 : 1))[0]!+ // Seed a spanning tree from the best-connected page. Branches follow+ // their parent direction, so chains and trees are not born as disks.+ const local = new Map<string, GraphPoint & { heading: number }>()+ local.set(representative, { x: 0, y: 0, heading: 0 })+ const queue = [representative]+ for (let cursor = 0; cursor < queue.length; cursor++) {+ const parentSlug = queue[cursor]!+ const parent = local.get(parentSlug)!+ const children = [...adjacency.get(parentSlug)!].filter(slug => !local.has(slug)).sort()+ children.forEach((slug, i) => {+ const heading = parent.heading + (cursor === 0 ? i * goldenAngle : ((i + 0.5) / children.length - 0.5) * Math.PI * 0.8)+ const distance = 150 + (children.length > 6 ? Math.sqrt(i) * 30 : (i % 3) * 12)+ local.set(slug, { x: parent.x + Math.cos(heading) * distance, y: parent.y + Math.sin(heading) * distance, heading })+ queue.push(slug)+ })+ }+ const mean = { x: 0, y: 0 }+ for (const point of local.values()) { mean.x += point.x / local.size; mean.y += point.y / local.size }+ for (const [slug, point] of local) seeds.set(slug, { x: point.x - mean.x, y: point.y - mean.y })+ const extent = graphPointBounds(slugs.map(slug => seeds.get(slug)!))+ // Room for repulsion and the caption; this is spacing, not a force limit.+ const padding = 160+ let x = 0, y = 0, bounds: GraphBounds+ for (let attempt = 0; ; attempt++) {+ const distance = Math.sqrt(attempt) * 48+ x = Math.cos(attempt * goldenAngle) * distance * stretch+ y = Math.sin(attempt * goldenAngle) * distance / stretch+ bounds = { left: x + extent.left - padding, right: x + extent.right + padding,+ top: y + extent.top - padding, bottom: y + extent.bottom + padding }+ const neighbors = new Set(keysFor(bounds).flatMap(key => cells.get(key) ?? []))+ if ([...neighbors].every(c => bounds.right <= c.left || bounds.left >= c.right || bounds.bottom <= c.top || bounds.top >= c.bottom)) break+ }+ const cluster = { x, y, ...bounds, slugs, representative, anchors: selectGraphAnchors(slugs, adjacency, nodeBySlug) }+ clusters.push(cluster)+ for (const key of keysFor(bounds)) {+ const bucket = cells.get(key) ?? []+ bucket.push(cluster); cells.set(key, bucket)+ }+ }+ const left = Math.min(0, ...clusters.map(c => c.left))+ const top = Math.min(0, ...clusters.map(c => c.top))+ const placements = new Map<string, LayoutPlacement>()+ const sections: GraphSection[] = []+ let right = 0, bottom = 0+ for (const cluster of clusters) {+ cluster.x -= left; cluster.y -= top+ cluster.left -= left; cluster.right -= left; cluster.top -= top; cluster.bottom -= top+ const center = { x: cluster.x, y: cluster.y }+ for (const slug of cluster.slugs) {+ const point = seeds.get(slug)!+ placements.set(slug, { x: center.x + point.x, y: center.y + point.y,+ center, degree: adjacency.get(slug)!.size })+ }+ right = Math.max(right, cluster.right)+ bottom = Math.max(bottom, cluster.bottom)+ }+ const gap = 80+ // Independent pages stay on a readable grid rather than accumulating at a+ // shared force center. The shelves are not semantic clusters.+ for (const [kind, slugs] of [['offscreen', offscreen], ['unlinked', unlinked]] as const) {+ if (!slugs.length) continue+ const shelfWidth = right || Math.sqrt(slugs.length * 180 * 100 * aspect)+ const columns = Math.min(slugs.length, Math.max(3, Math.floor(shelfWidth / 180)))+ const top = bottom ? bottom + gap : 0+ const sectionWidth = columns * 180+ const sectionHeight = Math.ceil(slugs.length / columns) * 100 + 50+ const left = Math.max(0, (right - sectionWidth) / 2)+ slugs.forEach((slug, i) => {+ const point = { x: left + (i % columns) * 180 + 90, y: top + 70 + Math.floor(i / columns) * 100 }+ placements.set(slug, { ...point, center: point, stationary: true })+ })+ sections.push({ kind, count: slugs.length, left, top, right: left + sectionWidth, bottom: top + sectionHeight })+ bottom = top + sectionHeight+ right = Math.max(right, left + sectionWidth)+ }++ const dx = (width - right) / 2, dy = (height - bottom) / 2+ for (const placement of placements.values()) {+ placement.x += dx; placement.y += dy+ // Centers are shared by a component; translate them only once below.+ }+ for (const center of new Set([...placements.values()].map(p => p.center))) { center.x += dx; center.y += dy }+ for (const cluster of clusters) {+ cluster.x += dx; cluster.y += dy+ cluster.left += dx; cluster.right += dx; cluster.top += dy; cluster.bottom += dy+ }+ for (const section of sections) {+ section.left += dx; section.right += dx; section.top += dy; section.bottom += dy+ }++ // During expansion, keep the existing mental map. New nodes start near an+ // already visible neighbor; old nodes are held still by the simulation.+ if (prior.size) {+ for (const slugs of components) {+ const existing = slugs.flatMap(slug => prior.has(slug) ? [prior.get(slug)!] : [])+ if (!existing.length) continue+ const center = { x: existing.reduce((sum, p) => sum + p.x, 0) / existing.length, y: existing.reduce((sum, p) => sum + p.y, 0) / existing.length }+ slugs.forEach((slug, i) => {+ const neighbor = [...adjacency.get(slug)!].find(nb => prior.has(nb))+ const anchor = prior.get(slug) ?? (neighbor ? prior.get(neighbor)! : center)+ const angle = i * Math.PI * (3 - Math.sqrt(5))+ const point = prior.has(slug) ? anchor : { x: anchor.x + Math.cos(angle) * 90, y: anchor.y + Math.sin(angle) * 90 }+ placements.set(slug, { ...point, center, degree: adjacency.get(slug)!.size })+ })+ }+ for (const [slug, point] of prior) {+ const placement = placements.get(slug)+ if (placement) { placement.x = point.x; placement.y = point.y }+ }+ }+ return { placements, sections: prior.size ? [] : sections, clusters: prior.size ? [] : clusters }+}++export interface ForceNode extends GraphPoint {+ slug: string; vx: number; vy: number; linkCount: number; pinned: boolean+}++/** Local repulsion uses a 2D spatial grid; collision includes outer rings. */+export function stepGraphLayout(+ nodes: ForceNode[], edges: GraphLink[], placements: ReadonlyMap<string, LayoutPlacement>,+ alpha: number, retained: ReadonlySet<string> = new Set(),+) {+ const fixed = (n: ForceNode) => n.pinned || retained.has(n.slug) || !!placements.get(n.slug)?.stationary+ if (nodes.every(fixed)) return+ const reach = 300+ const buckets = new Map<string, ForceNode[]>()+ const nodeMap = new Map(nodes.map(n => [n.slug, n]))+ for (const n of nodes) {+ const cx = Math.floor(n.x / reach), cy = Math.floor(n.y / reach)+ for (let gx = cx - 1; gx <= cx + 1; gx++) for (let gy = cy - 1; gy <= cy + 1; gy++) {+ for (const other of buckets.get(`${gx},${gy}`) ?? []) {+ let dx = n.x - other.x, dy = n.y - other.y+ let distance = Math.hypot(dx, dy)+ if (distance > reach) continue+ if (distance < 0.001) { dx = 1; dy = 0; distance = 1 }+ const force = 12000 * alpha / Math.max(distance * distance, 100)+ const fx = dx / distance * force, fy = dy / distance * force+ if (!fixed(n)) { n.vx += fx; n.vy += fy }+ if (!fixed(other)) { other.vx -= fx; other.vy -= fy }+ }+ }+ const key = `${cx},${cy}`+ const bucket = buckets.get(key) ?? []+ bucket.push(n); buckets.set(key, bucket)+ }+ // A reciprocal Wiki link is one visual spring, not double attraction.+ const pairs = new Set<string>()+ for (const edge of edges) {+ const s = nodeMap.get(edge.source), t = nodeMap.get(edge.target)+ if (!s || !t || s === t) continue+ const key = JSON.stringify([s.slug, t.slug].sort())+ if (pairs.has(key)) continue+ pairs.add(key)+ const dx = t.x - s.x, dy = t.y - s.y, distance = Math.hypot(dx, dy) || 1+ // Dense pages should not pull a whole group into a solid ball. Normalize+ // attraction by the visible degrees rather than the KB-wide link count.+ const degree = Math.min(placements.get(s.slug)?.degree ?? 1, placements.get(t.slug)?.degree ?? 1)+ const force = (distance - 140) * 0.003 * alpha / Math.sqrt(Math.max(1, degree))+ if (!fixed(s)) { s.vx += dx / distance * force; s.vy += dy / distance * force }+ if (!fixed(t)) { t.vx -= dx / distance * force; t.vy -= dy / distance * force }+ }+ for (const n of nodes) {+ if (fixed(n)) continue+ n.vx *= 0.6+ n.vy *= 0.6+ const speed = Math.hypot(n.vx, n.vy)+ if (speed > 20) { n.vx *= 20 / speed; n.vy *= 20 / speed }+ n.x += n.vx; n.y += n.vy+ }+ // Resolve overlaps after integration, even when the force has cooled. Use+ // X pruning here since the collision radius is small (at most 64 units).+ for (let pass = 0; pass < 3; pass++) {+ const sorted = [...nodes].sort((a, b) => a.x - b.x)+ for (let i = 0; i < sorted.length; i++) {+ const a = sorted[i]!+ for (let j = i + 1; j < sorted.length; j++) {+ const b = sorted[j]!+ if (b.x - a.x > 64) break+ let dx = b.x - a.x, dy = b.y - a.y+ let distance = Math.hypot(dx, dy)+ const minimum = graphNodeRadius(a.linkCount) + graphNodeRadius(b.linkCount) + 16+ if (distance >= minimum || (fixed(a) && fixed(b))) continue+ if (distance < 0.001) { dx = 1; dy = 0; distance = 1 }+ const shift = (minimum - distance) / (fixed(a) || fixed(b) ? 1 : 2)+ if (!fixed(a)) { a.x -= dx / distance * shift; a.y -= dy / distance * shift }+ if (!fixed(b)) { b.x += dx / distance * shift; b.y += dy / distance * shift }+ }+ }+ }+ // Correct only whole-component drift. The same translation is applied to+ // every member; no node is attracted to a shared center or clipped to a+ // circle. Pinned/retained components keep their user's coordinates intact.+ const groups = new Map<GraphPoint, ForceNode[]>()+ for (const node of nodes) {+ const center = placements.get(node.slug)?.center+ if (!center) continue+ const group = groups.get(center) ?? []+ group.push(node); groups.set(center, group)+ }+ for (const [center, group] of groups) {+ if (group.some(fixed)) continue+ const dx = (center.x - group.reduce((sum, n) => sum + n.x, 0) / group.length) * 0.03 * alpha+ const dy = (center.y - group.reduce((sum, n) => sum + n.y, 0) / group.length) * 0.03 * alpha+ for (const n of group) { n.x += dx; n.y += dy }+ }+}++export interface GraphLabel extends GraphBounds { slug: string; priority: number; required?: boolean }+/** Greedy screen-space label placement. Focused labels are never suppressed. */+export function visibleGraphLabels(labels: GraphLabel[]): Set<string> {+ const visible = new Set<string>()+ const occupied = new Map<string, GraphLabel[]>()+ const cells = (label: GraphLabel) => {+ const keys: string[] = []+ for (let x = Math.floor(label.left / 160); x <= Math.floor(label.right / 160); x++) {+ for (let y = Math.floor(label.top / 32); y <= Math.floor(label.bottom / 32); y++) keys.push(`${x},${y}`)+ }+ return keys+ }+ for (const label of [...labels].sort((a, b) => Number(!!b.required) - Number(!!a.required) || b.priority - a.priority)) {+ const keys = cells(label)+ const overlaps = keys.some(key => (occupied.get(key) ?? []).some(other => label.left < other.right && label.right > other.left && label.top < other.bottom && label.bottom > other.top))+ if (overlaps && !label.required) continue+ visible.add(label.slug)+ for (const key of keys) {+ const bucket = occupied.get(key) ?? []+ bucket.push(label); occupied.set(key, bucket)+ }+ }+ return visible+}+++export function graphPointBounds(points: GraphPoint[]): GraphBounds {+ if (!points.length) return { left: 0, top: 0, right: 0, bottom: 0 }+ return {+ left: Math.min(...points.map(p => p.x)), right: Math.max(...points.map(p => p.x)),+ top: Math.min(...points.map(p => p.y)), bottom: Math.max(...points.map(p => p.y)),+ }+}++/** Start at a readable scale. Fitting the entire graph is an explicit action. */+export function initialGraphViewport(points: GraphPoint[], width: number, height: number, focus?: GraphPoint) {+ const bounds = graphPointBounds(points)+ const fit = Math.min(Math.max(100, width - 120) / Math.max(100, bounds.right - bounds.left),+ Math.max(100, height - 120) / Math.max(100, bounds.bottom - bounds.top))+ const scale = Math.max(0.4, Math.min(0.85, fit))+ const center = fit < 0.4 && focus ? focus : { x: (bounds.left + bounds.right) / 2, y: (bounds.top + bounds.bottom) / 2 }+ return { scale, x: width / 2 - center.x * scale, y: height / 2 - center.y * scale }+}+++/** Smooth envelope of the node disks with a stable screen-space gutter.+ * The hull is taken over disks already grown by the gutter, then traced with+ * a closed spline whose tangents are limited by the adjacent segment length,+ * so it bows outwards from the hull without loops or cusps.+ */+export function graphClusterOutline(points: (GraphPoint & { radius?: number })[], scale = 1): string {+ if (!points.length) return ''+ const zoom = Number.isFinite(scale) && scale > 0 ? scale : 1+ // Capped in world units so far-out zoom levels do not merge separate groups.+ const padding = Math.min(22 / zoom, 60)+ const samples = 24+ const expanded = points.flatMap(p => {+ const radius = Math.max(0, p.radius ?? 0) + padding+ return Array.from({ length: samples }, (_, i) => ({+ x: p.x + Math.cos(i * 2 * Math.PI / samples) * radius,+ y: p.y + Math.sin(i * 2 * Math.PI / samples) * radius,+ }))+ }).sort((a, b) => a.x - b.x || a.y - b.y)+ const unique = expanded.filter((p, i) => !i || p.x !== expanded[i - 1]!.x || p.y !== expanded[i - 1]!.y)+ const cross = (o: GraphPoint, a: GraphPoint, b: GraphPoint) => (a.x - o.x) * (b.y - o.y) - (a.y - o.y) * (b.x - o.x)+ const half = (list: GraphPoint[]) => {+ const hull: GraphPoint[] = []+ for (const point of list) {+ while (hull.length > 1 && cross(hull[hull.length - 2]!, hull[hull.length - 1]!, point) <= 0) hull.pop()+ hull.push(point)+ }+ hull.pop()+ return hull+ }+ const hull = [...half(unique), ...half([...unique].reverse())]+ const at = (i: number) => hull[(i + hull.length) % hull.length]!+ const fmt = (p: GraphPoint) => `${Math.round(p.x * 10) / 10},${Math.round(p.y * 10) / 10}`+ const tangent = (from: GraphPoint, to: GraphPoint, length: number) => {+ const dx = to.x - from.x, dy = to.y - from.y, norm = Math.hypot(dx, dy) || 1+ return { x: dx / norm * length, y: dy / norm * length }+ }+ const path = [`M${fmt(hull[0]!)}`]+ hull.forEach((p, i) => {+ const next = at(i + 1)+ const reach = Math.hypot(next.x - p.x, next.y - p.y) * 0.36+ const out = tangent(at(i - 1), next, reach), into = tangent(p, at(i + 2), reach)+ path.push(`C${fmt({ x: p.x + out.x, y: p.y + out.y })} ${fmt({ x: next.x - into.x, y: next.y - into.y })} ${fmt(next)}`)+ })+ return path.join(' ') + ' Z'+}diff --git a/internal/application/service/wiki_page.go b/internal/application/service/wiki_page.goindex 3755f211f..0af0bda26 100644--- a/internal/application/service/wiki_page.go+++ b/internal/application/service/wiki_page.go@@ -699,6 +699,18 @@ func computeGraphSubset(pages []*types.WikiPage, req *types.WikiGraphRequest) (*}}hasTypeFilter := len(typeAllow) > 0+ // The index page is navigation over the whole wiki, not a subject. Its+ // directory is assembled on read, so it never carries links and would+ // only ever sit on the canvas as a lone node.+ if !typeAllow[types.WikiPageTypeIndex] {+ subjects := make([]*types.WikiPage, 0, len(pages))+ for _, p := range pages {+ if p.PageType != types.WikiPageTypeIndex {+ subjects = append(subjects, p)+ }+ }+ pages = subjects+ }familiarSet := make(map[string]struct{}, len(req.FamiliarKnowledgeIDs))for _, id := range req.FamiliarKnowledgeIDs {@@ -708,10 +720,74 @@ func computeGraphSubset(pages []*types.WikiPage, req *types.WikiGraphRequest) (*}pageBySlug := make(map[string]*types.WikiPage, len(pages))- linkCount := make(map[string]int, len(pages))for _, p := range pages {pageBySlug[p.Slug] = p- linkCount[p.Slug] = len(p.InLinks) + len(p.OutLinks)+ }+ // link_count is the number of distinct pages this page can be connected+ // to on the canvas: reciprocal links count once, and links to deleted or+ // type-filtered pages are excluded. The frontend compares it with the+ // visible degree to decide whether a page still has neighbors to load.+ // in_links can lag behind other pages' out_links, so links are collected+ // from both ends: edges are drawn from out_links, and a page someone links+ // to must not report zero links.+ neighbors := make(map[string]map[string]struct{}, len(pages))+ connect := func(a, b string) bool {+ pa, okA := pageBySlug[a]+ pb, okB := pageBySlug[b]+ if !okA || !okB || a == b {+ return false+ }+ if hasTypeFilter && (!typeAllow[pa.PageType] || !typeAllow[pb.PageType]) {+ return false+ }+ for _, pair := range [2][2]string{{a, b}, {b, a}} {+ set := neighbors[pair[0]]+ if set == nil {+ set = make(map[string]struct{})+ neighbors[pair[0]] = set+ }+ set[pair[1]] = struct{}{}+ }+ return true+ }+ for _, p := range pages {+ for _, target := range p.OutLinks {+ connect(p.Slug, target)+ }+ for _, source := range p.InLinks {+ connect(source, p.Slug)+ }+ }+ // A page extracted from a document belongs next to that document's+ // summary even when the summary text never links it, e.g. a name the+ // summary only writes as inline code, or a concept it never mentions by+ // title. Summary slugs are not always derived from the document ID, so+ // documents are matched through the summaries' own source_refs.+ summaryOf := make(map[string]string)+ for _, p := range pages {+ if p.PageType != types.WikiPageTypeSummary {+ continue+ }+ for _, id := range p.SourceKnowledgeIDs() {+ if prev, ok := summaryOf[id]; !ok || p.Slug < prev {+ summaryOf[id] = p.Slug+ }+ }+ }+ var sourceEdges [][2]string+ for _, p := range pages {+ if p.PageType == types.WikiPageTypeSummary {+ continue+ }+ for _, id := range p.SourceKnowledgeIDs() {+ if summary, ok := summaryOf[id]; ok && connect(summary, p.Slug) {+ sourceEdges = append(sourceEdges, [2]string{summary, p.Slug})+ }+ }+ }+ linkCount := make(map[string]int, len(pages))+ for slug, set := range neighbors {+ linkCount[slug] = len(set)}// Select the node slug set for the requested slice.@@ -728,7 +804,7 @@ func computeGraphSubset(pages []*types.WikiPage, req *types.WikiGraphRequest) (*if depth < 1 {depth = 1}- selected = bfsEgoSlugs(pageBySlug, req.Center, depth, typeAllow, req.Limit)+ selected = bfsEgoSlugs(pageBySlug, neighbors, req.Center, depth, typeAllow, req.Limit)default:// overview: keep only type-allowed candidates, sort by link_count desc, cap.candidates := make([]*types.WikiPage, 0, len(pages))@@ -738,14 +814,28 @@ func computeGraphSubset(pages []*types.WikiPage, req *types.WikiGraphRequest) (*}candidates = append(candidates, p)}+ // Many low-degree pages tie at the truncation boundary. Prefer pages+ // this person relies on, then subject pages over navigation pages,+ // then recently updated ones; slug keeps the API deterministic.+ familiar := make(map[string]bool, len(candidates))+ for _, p := range candidates {+ familiar[p.Slug] = p.BuiltFrom(familiarSet)+ }sort.SliceStable(candidates, func(i, j int) bool {- li := linkCount[candidates[i].Slug]- lj := linkCount[candidates[j].Slug]- if li != lj {- return li > lj+ a, b := candidates[i], candidates[j]+ if la, lb := linkCount[a.Slug], linkCount[b.Slug]; la != lb {+ return la > lb+ }+ if familiar[a.Slug] != familiar[b.Slug] {+ return familiar[a.Slug]+ }+ if ra, rb := graphOverviewTypeRank(a.PageType), graphOverviewTypeRank(b.PageType); ra != rb {+ return ra < rb}- // Stable tiebreaker keeps the API deterministic between calls.- return candidates[i].Slug < candidates[j].Slug+ if !a.UpdatedAt.Equal(b.UpdatedAt) {+ return a.UpdatedAt.After(b.UpdatedAt)+ }+ return a.Slug < b.Slug})if req.Limit > 0 && len(candidates) > req.Limit {candidates = candidates[:req.Limit]@@ -777,21 +867,41 @@ func computeGraphSubset(pages []*types.WikiPage, req *types.WikiGraphRequest) (*})// Build edges, keeping only edges whose endpoints both survived selection.- var edges []types.WikiGraphEdge+ // An isolated ego center still needs "edges": [], not null.+ edges := []types.WikiGraphEdge{}+ drawn := make(map[[2]string]struct{})for _, p := range pages {if _, ok := selected[p.Slug]; !ok {continue}for _, target := range p.OutLinks {- if _, ok := selected[target]; !ok {+ if _, ok := selected[target]; !ok || target == p.Slug {+ continue+ }+ if _, dup := drawn[[2]string{p.Slug, target}]; dup {continue}+ drawn[[2]string{p.Slug, target}] = struct{}{}edges = append(edges, types.WikiGraphEdge{Source: p.Slug,Target: target,})}}+ for _, e := range sourceEdges {+ _, okS := selected[e[0]]+ _, okT := selected[e[1]]+ if !okS || !okT {+ continue+ }+ _, forward := drawn[e]+ _, backward := drawn[[2]string{e[1], e[0]}]+ if forward || backward {+ continue+ }+ drawn[e] = struct{}{}+ edges = append(edges, types.WikiGraphEdge{Source: e[0], Target: e[1]})+ }// total is the count of candidate nodes before truncation — i.e. the// population the frontend would need to fetch if it asked for the@@ -834,6 +944,21 @@ func computeGraphSubset(pages []*types.WikiPage, req *types.WikiGraphRequest) (*}, nil}+// graphOverviewTypeRank orders page types for overview tie-breaks: subject+// pages first, generated summaries next, navigation pages last.+func graphOverviewTypeRank(pageType string) int {+ switch pageType {+ case types.WikiPageTypeEntity, types.WikiPageTypeConcept:+ return 0+ case types.WikiPageTypeSynthesis, types.WikiPageTypeComparison:+ return 1+ case types.WikiPageTypeSummary:+ return 2+ default:+ return 3+ }+}+// bfsEgoSlugs computes the undirected BFS neighborhood of `center` up to// `depth` hops using both inbound and outbound links. Type-filtered pages// are excluded from the result but are also NOT traversed through — so a@@ -841,6 +966,7 @@ func computeGraphSubset(pages []*types.WikiPage, req *types.WikiGraphRequest) (*// index. The caller guarantees center exists in pageBySlug.func bfsEgoSlugs(pageBySlug map[string]*types.WikiPage,+ adjacency map[string]map[string]struct{},center string,depth int,typeAllow map[string]bool,@@ -866,13 +992,13 @@ func bfsEgoSlugs(}next := make([]string, 0, len(frontier))for _, slug := range frontier {- p, ok := pageBySlug[slug]- if !ok {- continue+ // Undirected adjacency built from every page's links, so a page+ // with stale in_links still reaches the pages that link to it.+ neighbors := make([]string, 0, len(adjacency[slug]))+ for nb := range adjacency[slug] {+ neighbors = append(neighbors, nb)}- neighbors := make([]string, 0, len(p.OutLinks)+len(p.InLinks))- neighbors = append(neighbors, p.OutLinks...)- neighbors = append(neighbors, p.InLinks...)+ sort.Strings(neighbors)for _, nb := range neighbors {if _, seen := visited[nb]; seen {continuediff --git a/internal/application/service/wiki_page_test.go b/internal/application/service/wiki_page_test.goindex dd4a55211..38347e111 100644--- a/internal/application/service/wiki_page_test.go+++ b/internal/application/service/wiki_page_test.go@@ -2,7 +2,9 @@ package serviceimport ("context"+ "encoding/json""fmt"+ "strings""testing""time"@@ -421,7 +423,7 @@ func TestComputeGraphSubset_OverviewTruncatesByLinkCount(t *testing.T) {t.Errorf("want 3 nodes, got %d (%v)", len(got.Nodes), nodeSlugs(got))}slugs := nodeSlugs(got)- // hub has link_count 6 (4 out + 2 in), must survive the cap.+ // hub links to four distinct pages, more than any other; it must survive the cap.if !slugs["hub"] {t.Errorf("expected hub to survive the top-3 cap, got %v", slugs)}@@ -443,6 +445,163 @@ func TestComputeGraphSubset_OverviewTruncatesByLinkCount(t *testing.T) {}}+func TestComputeGraphSubset_LinkCountCountsDistinctReachablePages(t *testing.T) {+ pages := []*types.WikiPage{+ {+ Slug: "p", PageType: types.WikiPageTypeEntity,+ OutLinks: types.StringArray{"q", "q", "gone", "p", "idx"}, InLinks: types.StringArray{"q"},+ },+ {+ Slug: "q", PageType: types.WikiPageTypeEntity,+ OutLinks: types.StringArray{"p"}, InLinks: types.StringArray{"p"},+ },+ {Slug: "idx", PageType: types.WikiPageTypeIndex, InLinks: types.StringArray{"p"}},+ }+ got, err := computeGraphSubset(pages, &types.WikiGraphRequest{+ Mode: types.WikiGraphModeOverview, Types: []string{types.WikiPageTypeEntity},+ })+ if err != nil {+ t.Fatalf("computeGraphSubset: %v", err)+ }+ for _, n := range got.Nodes {+ if n.LinkCount != 1 {+ t.Errorf("%s link_count = %d, want 1 (reciprocal, duplicate, self, dead and filtered links excluded)",+ n.Slug, n.LinkCount)+ }+ }+ if len(got.Edges) != 2 {+ t.Errorf("want one edge per direction between p and q, got %v", got.Edges)+ }+}++func TestComputeGraphSubset_LinkCountSurvivesStaleInLinks(t *testing.T) {+ pages := []*types.WikiPage{+ {Slug: "summary", PageType: types.WikiPageTypeSummary, OutLinks: types.StringArray{"topic"}},+ {Slug: "topic", PageType: types.WikiPageTypeConcept},+ }+ got, err := computeGraphSubset(pages, &types.WikiGraphRequest{Mode: types.WikiGraphModeOverview})+ if err != nil {+ t.Fatalf("computeGraphSubset: %v", err)+ }+ for _, n := range got.Nodes {+ if n.LinkCount != 1 {+ t.Errorf("%s link_count = %d, want 1 even though topic.in_links was never updated", n.Slug, n.LinkCount)+ }+ }++ ego, err := computeGraphSubset(pages, &types.WikiGraphRequest{+ Mode: types.WikiGraphModeEgo, Center: "topic", Depth: 1,+ })+ if err != nil {+ t.Fatalf("ego: %v", err)+ }+ if !nodeSlugs(ego)["summary"] || len(ego.Edges) != 1 {+ t.Errorf("ego of topic must reach the page linking to it, got nodes %v edges %v", nodeSlugs(ego), ego.Edges)+ }+}++func TestComputeGraphSubset_ConnectsPagesToTheirDocumentSummary(t *testing.T) {+ pages := []*types.WikiPage{+ {+ Slug: "summary/ollama-tags", PageType: types.WikiPageTypeSummary,+ SourceRefs: types.StringArray{"doc-1|Ollama标签.md"},+ },+ {Slug: "entity/qwen", PageType: types.WikiPageTypeEntity, SourceRefs: types.StringArray{"doc-1"}},+ {Slug: "concept/linked", PageType: types.WikiPageTypeConcept, SourceRefs: types.StringArray{"doc-1"}},+ {+ Slug: "concept/other-doc", PageType: types.WikiPageTypeConcept,+ SourceRefs: types.StringArray{"doc-2"},+ },+ }+ pages[0].OutLinks = types.StringArray{"concept/linked"}++ got, err := computeGraphSubset(pages, &types.WikiGraphRequest{Mode: types.WikiGraphModeOverview})+ if err != nil {+ t.Fatalf("computeGraphSubset: %v", err)+ }+ edges := map[string]bool{}+ for _, e := range got.Edges {+ edges[e.Source+"->"+e.Target] = true+ }+ want := []string{"summary/ollama-tags->concept/linked", "summary/ollama-tags->entity/qwen"}+ if len(edges) != len(want) || !edges[want[0]] || !edges[want[1]] {+ t.Errorf("edges = %v, want %v (one edge per pair, none for a document without summary)", edges, want)+ }+ counts := map[string]int{}+ for _, n := range got.Nodes {+ counts[n.Slug] = n.LinkCount+ }+ if counts["summary/ollama-tags"] != 2 || counts["entity/qwen"] != 1 || counts["concept/other-doc"] != 0 {+ t.Errorf("link counts = %v", counts)+ }+}++func TestComputeGraphSubset_LeavesOutIndexUnlessRequested(t *testing.T) {+ pages := []*types.WikiPage{+ {Slug: "index", PageType: types.WikiPageTypeIndex},+ {Slug: "entity/a", PageType: types.WikiPageTypeEntity},+ }+ got, err := computeGraphSubset(pages, &types.WikiGraphRequest{Mode: types.WikiGraphModeOverview})+ if err != nil {+ t.Fatalf("computeGraphSubset: %v", err)+ }+ if nodeSlugs(got)["index"] || got.Meta.Total != 1 {+ t.Errorf("overview must leave out the index page, got nodes %v total %d", nodeSlugs(got), got.Meta.Total)+ }+ got, err = computeGraphSubset(pages, &types.WikiGraphRequest{+ Mode: types.WikiGraphModeOverview, Types: []string{types.WikiPageTypeIndex},+ })+ if err != nil {+ t.Fatalf("computeGraphSubset: %v", err)+ }+ if !nodeSlugs(got)["index"] {+ t.Errorf("an explicit index type filter must still return it, got %v", nodeSlugs(got))+ }+}++func TestComputeGraphSubset_IsolatedEgoCenterHasEmptyEdgeList(t *testing.T) {+ pages := []*types.WikiPage{{Slug: "alone", PageType: types.WikiPageTypeEntity}}+ got, err := computeGraphSubset(pages, &types.WikiGraphRequest{+ Mode: types.WikiGraphModeEgo, Center: "alone", Depth: 1,+ })+ if err != nil {+ t.Fatalf("computeGraphSubset: %v", err)+ }+ body, err := json.Marshal(got)+ if err != nil {+ t.Fatalf("marshal: %v", err)+ }+ if !strings.Contains(string(body), `"edges":[]`) {+ t.Errorf("isolated center must serialize edges as [], got %s", body)+ }+}++func TestComputeGraphSubset_OverviewBreaksTiesBySignificance(t *testing.T) {+ now := time.Now()+ pages := []*types.WikiPage{+ {Slug: "a-index", PageType: types.WikiPageTypeIndex, UpdatedAt: now},+ {Slug: "b-summary", PageType: types.WikiPageTypeSummary, UpdatedAt: now},+ {Slug: "c-old", PageType: types.WikiPageTypeEntity, UpdatedAt: now.Add(-time.Hour)},+ {Slug: "d-new", PageType: types.WikiPageTypeConcept, UpdatedAt: now},+ {+ Slug: "e-familiar", PageType: types.WikiPageTypeSummary, UpdatedAt: now.Add(-2 * time.Hour),+ SourceRefs: types.StringArray{"doc-1"},+ },+ }+ got, err := computeGraphSubset(pages, &types.WikiGraphRequest{+ Mode: types.WikiGraphModeOverview, Limit: 3, FamiliarKnowledgeIDs: []string{"doc-1"},+ })+ if err != nil {+ t.Fatalf("computeGraphSubset: %v", err)+ }+ slugs := nodeSlugs(got)+ for _, want := range []string{"e-familiar", "d-new", "c-old"} {+ if !slugs[want] {+ t.Errorf("expected %q among tied pages, got %v", want, slugs)+ }+ }+}+func TestComputeGraphSubset_MarksFamiliarSourcePages(t *testing.T) {pages := makeGraphFixture()pages[0].SourceRefs = types.StringArray{"doc-1|排班手册"}