feat(wiki): improve graph layout, theme captions and group focus (#4147)
* feat(wiki): improve graph layout and exploration * feat(wiki): name graph themes and connect pages to their document summary - Rewrite selectGraphAnchors on deterministic Louvain communities with coverage, redundancy and readability rules; clean file-name captions. - Add group focus bar with switch menu, Esc/background exit, caption pills. - Count distinct neighbors for link_count from both link directions, and let ego BFS use the same adjacency so stale in_links do not hide pages. - Connect each page to its source document summary and leave the index page out of the graph; return edges as [] for an isolated ego center. - Keep graph search and type filters available after an empty render. * fix(wiki): use theme tokens in graph styles and satisfy Go lint * feat(wiki): label the page shared by a multi-document graph groupmain
parent
150d8cc605
commit
231a5c0b15
|
|
@ -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) {
|
||||
|
|
|
|||
|
|
@ -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)',
|
||||
|
|
|
|||
|
|
@ -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}個は概要の範囲外です。「展開」をクリックするとここを起点に表示できます)',
|
||||
|
|
|
|||
|
|
@ -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}개는 개요 범위 밖 — 확장을 클릭하여 이곳으로 전환)',
|
||||
|
|
|
|||
|
|
@ -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} вне обзора — нажмите «Развернуть», чтобы переключиться сюда)',
|
||||
|
|
|
|||
|
|
@ -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} 个不在概览范围,点"展开邻居"以此为中心查看)',
|
||||
|
|
|
|||
|
|
@ -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} 個不在概覽範圍,點"展開鄰居"以此為中心查看)',
|
||||
|
|
|
|||
File diff suppressed because it is too large
Load Diff
|
|
@ -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'])
|
||||
})
|
||||
|
|
@ -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'
|
||||
}
|
||||
|
|
@ -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
|
||||
}
|
||||
// Stable tiebreaker keeps the API deterministic between calls.
|
||||
return candidates[i].Slug < candidates[j].Slug
|
||||
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
|
||||
}
|
||||
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 {
|
||||
continue
|
||||
|
|
|
|||
|
|
@ -2,7 +2,9 @@ package service
|
|||
|
||||
import (
|
||||
"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|排班手册"}
|
||||
|
|
|
|||
Loading…
Reference in New Issue