dsh-memu-memory 1.3.1 → 1.3.3
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/AGENTS.md +6 -3
- package/CHANGELOG.md +57 -0
- package/README.md +8 -7
- package/README.zh.md +8 -5
- package/assets/screenshots/drawer.jpg +0 -0
- package/assets/screenshots/mobile.jpg +0 -0
- package/assets/screenshots/relations.jpg +0 -0
- package/assets/screenshots/settings.jpg +0 -0
- package/assets/screenshots/stats.jpg +0 -0
- package/assets/screenshots/webui-dark.jpg +0 -0
- package/assets/screenshots/webui-memory.jpg +0 -0
- package/docs/client-conventions.md +11 -0
- package/docs/contributing.md +6 -4
- package/docs/env-and-commands.md +12 -1
- package/docs/memory-semantics.md +8 -2
- package/docs/troubleshooting.md +24 -6
- package/lib/auto-link/apply.js +249 -0
- package/lib/auto-link/candidates.js +155 -0
- package/lib/auto-link/decide.js +304 -0
- package/lib/auto-link/normalize.js +99 -0
- package/lib/auto-link/policy.js +42 -0
- package/lib/auto-link/suppression.js +101 -0
- package/lib/auto-link/terminology.js +265 -0
- package/lib/binding-diagnostics.js +2 -2
- package/lib/client.js +1509 -72
- package/lib/graph.js +269 -18
- package/lib/memory.js +11 -0
- package/lib/memu.js +7 -6
- package/lib/private-links.js +105 -137
- package/lib/private.js +138 -38
- package/lib/rpc.js +73 -8
- package/lib/state.js +7 -2
- package/lib/tools.js +4 -2
- package/lib/webui/graph-LICENSE.txt +1 -62
- package/lib/webui/graph-view.bundle.js +1 -1
- package/lib/webui/graph-view.js +921 -126
- package/lib/webui/standalone.js +3 -3
- package/package.json +1 -2
- package/scripts/build-graph.mjs +35 -7
- package/scripts/check-all.mjs +2 -0
- package/scripts/check-graph-browser.mjs +106 -23
- package/scripts/make-readme-shots.mjs +59 -0
- package/scripts/rebuild-auto-links.mjs +252 -0
- package/tests/audit-regression.test.mjs +11 -8
- package/tests/auto-link-candidates.test.mjs +161 -0
- package/tests/auto-link-decide.test.mjs +512 -0
- package/tests/auto-link-migration.test.mjs +133 -0
- package/tests/browser.test.mjs +27 -0
- package/tests/client-render.test.mjs +178 -6
- package/tests/consolidation-fork.test.mjs +148 -0
- package/tests/cycle.test.mjs +1 -1
- package/tests/graph-view.test.mjs +221 -22
- package/tests/graph.test.mjs +5 -0
- package/tests/help-page.test.mjs +3 -3
- package/tests/memu-resident-route.test.mjs +130 -0
- package/tests/private-links.test.mjs +81 -45
- package/tests/stubs/child-process-spy.mjs +14 -0
- package/tests/tools.test.mjs +24 -18
package/lib/webui/graph-view.js
CHANGED
|
@@ -1,77 +1,620 @@
|
|
|
1
|
-
|
|
1
|
+
// 自研力导向关系图引擎:零第三方运行时依赖。
|
|
2
|
+
// 数据契约沿用 getGraph:{ nodes:[{id,title,kind,layer,strength,missing,status}], edges:[{from,to,...}] }。
|
|
3
|
+
// 物理:空间网格近程斥力 + 连线弹簧 + 可选向心力;fx/fy 非空 = 固定点(pin)。
|
|
4
|
+
// 拖动时只模拟「被拖节点的连通簇」,其他簇冻结但作为斥力障碍,避免重合。
|
|
2
5
|
|
|
3
|
-
const
|
|
6
|
+
const TAU = Math.PI * 2
|
|
7
|
+
const GOLDEN_ANGLE = 2.399963229728653
|
|
8
|
+
const INPUT_LIMIT = 200 // 与 getGraph 的 limit 对齐
|
|
9
|
+
const CACHE_LIMIT = 800
|
|
10
|
+
const PHYSICS_KEYS = new Set(['x', 'y', 'vx', 'vy', 'fx', 'fy'])
|
|
4
11
|
const clamp = (value, min, max) => Math.max(min, Math.min(max, value))
|
|
5
|
-
export const DEFAULT_OPTIONS = Object.freeze({ repulsion: 120, distance: 100, labels: true, motion: true })
|
|
6
12
|
|
|
7
|
-
|
|
8
|
-
|
|
13
|
+
export const DEFAULT_OPTIONS = Object.freeze({
|
|
14
|
+
repulsion: 120, // 斥力滑杆 30..350 -> SIM.repel * repulsion/120
|
|
15
|
+
distance: 100, // 连线距离滑杆 40..220 -> baseLen * distance/100
|
|
16
|
+
center: 0, // 向心力滑杆 0..3,默认关闭(避免小簇被吸到质心)
|
|
17
|
+
labels: true,
|
|
18
|
+
motion: true,
|
|
19
|
+
grid: true, // 画布背景网格点(Graph Studio 侧栏开关)
|
|
20
|
+
clusterScope: true, // 拖动只模拟连通簇,UI 不暴露
|
|
21
|
+
})
|
|
22
|
+
|
|
23
|
+
const SIM = Object.freeze({
|
|
24
|
+
cell: 120, range: 150, repel: 900, link: .9, centerForce: .012,
|
|
25
|
+
vDecay: .6, alphaDecay: .025, alphaTarget: .02,
|
|
26
|
+
})
|
|
27
|
+
|
|
28
|
+
// 明暗主题下均可读的固定色板;激活色另取宿主 token。
|
|
29
|
+
const NODE_COLORS = Object.freeze({
|
|
30
|
+
memory: '#618fcd', must: '#d97768', short: '#8a93a6', entity: '#36a582',
|
|
31
|
+
provisional: '#b9963f', global: '#8b7bd8', missing: '#92959c',
|
|
32
|
+
})
|
|
33
|
+
// evidence.rule 的固定色板(明暗都可读),与 graph-studio 的 paper 主题一致。
|
|
34
|
+
const EDGE_RULES = Object.freeze({
|
|
35
|
+
'entity-mention': '#4f6bdb', conflict: '#d9705f', supersede: '#c08a49',
|
|
36
|
+
'fact-key': '#7a8fbc', 'worker-quote': '#8a7cc0',
|
|
37
|
+
})
|
|
38
|
+
const edgeColor = (edge, foreground, accent) =>
|
|
39
|
+
edge.rule && EDGE_RULES[edge.rule] ? EDGE_RULES[edge.rule] : edge.manual ? accent : foreground
|
|
40
|
+
|
|
41
|
+
const nodeColor = node => node.missing ? NODE_COLORS.missing
|
|
42
|
+
: node.kind === 'global' ? NODE_COLORS.global
|
|
43
|
+
: node.kind !== 'memory' ? (node.status === 'provisional' ? NODE_COLORS.provisional : NODE_COLORS.entity)
|
|
44
|
+
: node.layer === 'must_remember' ? NODE_COLORS.must
|
|
45
|
+
: node.layer === 'short_term' ? NODE_COLORS.short : NODE_COLORS.memory
|
|
46
|
+
|
|
47
|
+
const hashId = value => {
|
|
48
|
+
let hash = 2166136261
|
|
49
|
+
const text = String(value)
|
|
50
|
+
for (let i = 0; i < text.length; i++) { hash ^= text.charCodeAt(i); hash = Math.imul(hash, 16777619) }
|
|
51
|
+
return hash >>> 0
|
|
52
|
+
}
|
|
53
|
+
const cellKey = (x, y) => `${Math.floor(x / SIM.cell)},${Math.floor(y / SIM.cell)}`
|
|
54
|
+
|
|
55
|
+
// ---- 纯布局:不碰 DOM,供单测直接驱动 ------------------------------------
|
|
56
|
+
export function createForceLayout(initialOptions = {}) {
|
|
9
57
|
const cache = new Map()
|
|
10
|
-
|
|
11
|
-
let
|
|
12
|
-
|
|
13
|
-
|
|
14
|
-
|
|
15
|
-
|
|
16
|
-
|
|
58
|
+
const edgeLengths = new Map()
|
|
59
|
+
let nodes = [], edges = [], adjacency = new Map(), components = null
|
|
60
|
+
let signature = '', alpha = 1, options = { ...DEFAULT_OPTIONS, ...initialOptions }
|
|
61
|
+
let dragComp = null, dragging = false, settling = false
|
|
62
|
+
let layoutInitialized = false
|
|
63
|
+
|
|
64
|
+
const factors = () => ({
|
|
65
|
+
repel: clamp(options.repulsion, 1, 1000) / 120,
|
|
66
|
+
linkDist: clamp(options.distance, 1, 1000) / 100,
|
|
67
|
+
center: clamp(options.center, 0, 20),
|
|
68
|
+
})
|
|
69
|
+
const baseLenOf = (source, target) => clamp(Math.hypot(source.x - target.x, source.y - target.y) || 56, 48, 160)
|
|
70
|
+
|
|
71
|
+
const buildAdjacency = () => {
|
|
72
|
+
const map = new Map()
|
|
73
|
+
for (const edge of edges) {
|
|
74
|
+
if (!map.has(edge.from)) map.set(edge.from, new Set())
|
|
75
|
+
if (!map.has(edge.to)) map.set(edge.to, new Set())
|
|
76
|
+
map.get(edge.from).add(edge.to)
|
|
77
|
+
map.get(edge.to).add(edge.from)
|
|
78
|
+
}
|
|
79
|
+
return map
|
|
80
|
+
}
|
|
81
|
+
// 连通分量按 id 建表,成员引用 cache 里的物理对象;对象身份跨 update 不变。
|
|
82
|
+
const buildComponents = () => {
|
|
83
|
+
const map = new Map()
|
|
84
|
+
for (const node of nodes) {
|
|
85
|
+
if (map.has(node.id)) continue
|
|
86
|
+
const ids = new Set([node.id]), queue = [node.id], members = []
|
|
87
|
+
for (let i = 0; i < queue.length; i++) {
|
|
88
|
+
const id = queue[i], state = cache.get(id)
|
|
89
|
+
if (state) members.push(state)
|
|
90
|
+
for (const next of adjacency.get(id) || []) if (!ids.has(next)) { ids.add(next); queue.push(next) }
|
|
91
|
+
}
|
|
92
|
+
const comp = { ids, members }
|
|
93
|
+
for (const id of ids) map.set(id, comp)
|
|
94
|
+
}
|
|
95
|
+
return map
|
|
96
|
+
}
|
|
97
|
+
|
|
98
|
+
const reheat = value => { alpha = Math.max(alpha, value) }
|
|
99
|
+
const componentOf = id => options.clusterScope && components ? components.get(id) : null
|
|
100
|
+
|
|
101
|
+
// ---- 花瓣向心布局:从 graph-studio 的 layoutFlower / packDisc / wrapRim 移植 ----
|
|
102
|
+
// 最大簇居中、其余同心环贴着外沿铺开;簇少时把外围簇的节点摊到外圆周上,
|
|
103
|
+
// 所以整体轮廓收成一个圆,而不是散开的螺旋。力模拟只在这个形状上做微调。
|
|
104
|
+
const RING_GAP = 18
|
|
105
|
+
const densityScale = count => clamp(Math.sqrt(900 / Math.max(900, count)), .56, 1)
|
|
106
|
+
|
|
107
|
+
const buildGroups = () => {
|
|
108
|
+
const groups = [], seen = new Set()
|
|
109
|
+
for (const node of nodes) {
|
|
110
|
+
if (seen.has(node.id)) continue
|
|
111
|
+
const comp = components?.get(node.id)
|
|
112
|
+
const ids = comp ? [...comp.ids] : [node.id]
|
|
113
|
+
for (const id of ids) seen.add(id)
|
|
114
|
+
const adj = new Map(ids.map(id => [id, []]))
|
|
115
|
+
for (const edge of edges) {
|
|
116
|
+
if (!adj.has(edge.from) || !adj.has(edge.to)) continue
|
|
117
|
+
adj.get(edge.from).push(edge.to)
|
|
118
|
+
adj.get(edge.to).push(edge.from)
|
|
119
|
+
}
|
|
120
|
+
// 根:度数最大;同度时实体优先,再按 id 稳定排序。
|
|
121
|
+
let root = ids[0], bestScore = -1
|
|
122
|
+
for (const id of ids) {
|
|
123
|
+
const nd = cache.get(id)
|
|
124
|
+
const score = (adj.get(id)?.length || 0) * 10 + (nd?.kind === 'memory' ? 0 : 3)
|
|
125
|
+
if (score > bestScore || (score === bestScore && id < root)) { root = id; bestScore = score }
|
|
126
|
+
}
|
|
127
|
+
const parent = new Map([[root, null]])
|
|
128
|
+
const kids = new Map([[root, []]])
|
|
129
|
+
const level = new Map([[root, 0]])
|
|
130
|
+
const order = [root]
|
|
131
|
+
for (let i = 0; i < order.length; i++) {
|
|
132
|
+
const id = order[i]
|
|
133
|
+
for (const next of adj.get(id) || []) {
|
|
134
|
+
if (parent.has(next)) continue
|
|
135
|
+
parent.set(next, id); kids.set(next, []); level.set(next, level.get(id) + 1)
|
|
136
|
+
kids.get(id).push(next); order.push(next)
|
|
137
|
+
}
|
|
138
|
+
}
|
|
139
|
+
// 子树体量:重枝分到更宽的扇区,兄弟之间才不会挤在一起。
|
|
140
|
+
const weight = new Map()
|
|
141
|
+
for (let i = order.length - 1; i >= 0; i--) {
|
|
142
|
+
const id = order[i]
|
|
143
|
+
let w = 0
|
|
144
|
+
for (const k of kids.get(id) || []) w += weight.get(k)
|
|
145
|
+
weight.set(id, w || 1)
|
|
146
|
+
}
|
|
147
|
+
groups.push({ ids, root, kids, weight })
|
|
148
|
+
}
|
|
149
|
+
groups.sort((a, b) => b.ids.length - a.ids.length)
|
|
150
|
+
return groups
|
|
151
|
+
}
|
|
152
|
+
|
|
153
|
+
const placeFlower = (group, ring, minChord, maxRing) => {
|
|
154
|
+
const rootNode = cache.get(group.root)
|
|
155
|
+
if (!rootNode) return
|
|
156
|
+
rootNode.x = 0; rootNode.y = 0
|
|
157
|
+
const stack = [{ id: group.root, x: 0, y: 0, dir: -Math.PI / 2, span: Math.PI * 2 }]
|
|
158
|
+
while (stack.length) {
|
|
159
|
+
const cur = stack.pop()
|
|
160
|
+
const list = group.kids.get(cur.id)
|
|
161
|
+
if (!list || !list.length) continue
|
|
162
|
+
const arr = list.length > 1 ? list.slice().sort((a, b) => group.weight.get(b) - group.weight.get(a)) : list
|
|
163
|
+
let total = 0
|
|
164
|
+
for (const k of arr) total += group.weight.get(k)
|
|
165
|
+
let minShare = Infinity
|
|
166
|
+
for (const k of arr) minShare = Math.min(minShare, cur.span * group.weight.get(k) / total)
|
|
167
|
+
let radius = ring
|
|
168
|
+
if (arr.length > 1 && minShare > 1e-6) {
|
|
169
|
+
radius = Math.max(ring, minChord / (2 * Math.sin(Math.min(Math.PI, minShare) / 2)))
|
|
170
|
+
}
|
|
171
|
+
if (radius > maxRing) radius = maxRing
|
|
172
|
+
// 只有一个孩子时方向轻微偏转:一串记忆会卷成弧形,而不是一条直线。
|
|
173
|
+
const curl = arr.length === 1 ? .62 : 0
|
|
174
|
+
let cursor = cur.dir - cur.span / 2
|
|
175
|
+
for (const k of arr) {
|
|
176
|
+
const share = cur.span * group.weight.get(k) / total
|
|
177
|
+
const a = cursor + share / 2 + curl
|
|
178
|
+
const kn = cache.get(k)
|
|
179
|
+
if (kn) { kn.x = cur.x + Math.cos(a) * radius; kn.y = cur.y + Math.sin(a) * radius }
|
|
180
|
+
stack.push({ id: k, x: kn ? kn.x : cur.x, y: kn ? kn.y : cur.y, dir: a, span: share })
|
|
181
|
+
cursor += share
|
|
182
|
+
}
|
|
183
|
+
}
|
|
184
|
+
}
|
|
185
|
+
|
|
186
|
+
// 用「分角度的最大半径」的方差当圆度评分,找方差最小的整体旋转角。
|
|
187
|
+
const chooseRoundestRotation = list => {
|
|
188
|
+
const BINS = 36
|
|
189
|
+
const base = new Float64Array(BINS)
|
|
190
|
+
const head = list[0]
|
|
191
|
+
const binOf = a => Math.min(BINS - 1, Math.floor((a + Math.PI) / (Math.PI * 2) * BINS))
|
|
192
|
+
for (const id of head.ids) {
|
|
193
|
+
const node = cache.get(id)
|
|
194
|
+
if (!node) continue
|
|
195
|
+
const r = Math.hypot(node.x - (head.cx || 0), node.y - (head.cy || 0))
|
|
196
|
+
const b = binOf(Math.atan2(node.y - (head.cy || 0), node.x - (head.cx || 0)))
|
|
197
|
+
if (r > base[b]) base[b] = r
|
|
198
|
+
}
|
|
199
|
+
let bestDelta = 0, bestScore = Infinity
|
|
200
|
+
for (let t = 0; t < 36; t++) {
|
|
201
|
+
const delta = t / 36 * Math.PI * 2
|
|
202
|
+
const prof = Float64Array.from(base)
|
|
203
|
+
for (let i = 1; i < list.length; i++) {
|
|
204
|
+
const g = list[i]
|
|
205
|
+
const d = Math.hypot(g.ax, g.ay)
|
|
206
|
+
const ang = Math.atan2(g.ay, g.ax) + delta
|
|
207
|
+
const r = g.radius
|
|
208
|
+
for (let b = 0; b < BINS; b++) {
|
|
209
|
+
const a = -Math.PI + (b + .5) / BINS * Math.PI * 2
|
|
210
|
+
let diff = a - ang
|
|
211
|
+
while (diff > Math.PI) diff -= Math.PI * 2
|
|
212
|
+
while (diff < -Math.PI) diff += Math.PI * 2
|
|
213
|
+
const perp = d * Math.sin(diff)
|
|
214
|
+
if (Math.abs(perp) >= r || Math.abs(diff) >= Math.PI / 2) continue
|
|
215
|
+
const reach = d * Math.cos(diff) + Math.sqrt(r * r - perp * perp)
|
|
216
|
+
if (reach > prof[b]) prof[b] = reach
|
|
217
|
+
}
|
|
218
|
+
}
|
|
219
|
+
let mean = 0
|
|
220
|
+
for (let b = 0; b < BINS; b++) mean += prof[b]
|
|
221
|
+
mean /= BINS
|
|
222
|
+
let score = 0
|
|
223
|
+
for (let b = 0; b < BINS; b++) score += (prof[b] - mean) * (prof[b] - mean)
|
|
224
|
+
if (score < bestScore) { bestScore = score; bestDelta = delta }
|
|
225
|
+
}
|
|
226
|
+
if (!bestDelta) return
|
|
227
|
+
const cos = Math.cos(bestDelta), sin = Math.sin(bestDelta)
|
|
228
|
+
for (let i = 1; i < list.length; i++) {
|
|
229
|
+
const g = list[i]
|
|
230
|
+
const x = g.ax, y = g.ay
|
|
231
|
+
g.ax = x * cos - y * sin; g.ay = x * sin + y * cos
|
|
232
|
+
}
|
|
233
|
+
}
|
|
234
|
+
|
|
235
|
+
// 圆盘排布:最大的一团居中,其余一圈圈贴着它往外铺,整环外沿落在同一个圆上。
|
|
236
|
+
const packDisc = groups => {
|
|
237
|
+
const list = groups.slice().sort((a, b) => b.radius - a.radius)
|
|
238
|
+
if (!list.length) return
|
|
239
|
+
list[0].ax = 0; list[0].ay = 0
|
|
240
|
+
let cursor = list[0].radius + RING_GAP
|
|
241
|
+
let i = 1, ringIdx = 1
|
|
242
|
+
while (i < list.length) {
|
|
243
|
+
const ring = []
|
|
244
|
+
let used = 0, j = i
|
|
245
|
+
while (j < list.length) {
|
|
246
|
+
const c = list[j], d = cursor + c.radius
|
|
247
|
+
const need = (2 * c.radius + RING_GAP) / Math.max(1, d)
|
|
248
|
+
if (ring.length && used + need > Math.PI * 2) break
|
|
249
|
+
ring.push({ c, d, need }); used += need; j++
|
|
250
|
+
}
|
|
251
|
+
let total = 0, outer = cursor
|
|
252
|
+
for (const item of ring) { total += item.need; outer = Math.max(outer, item.d + item.c.radius) }
|
|
253
|
+
const start = -Math.PI / 2 + ringIdx * 0.9
|
|
254
|
+
let acc = 0
|
|
255
|
+
for (const item of ring) {
|
|
256
|
+
const need = (2 * item.c.radius + RING_GAP) / Math.max(1, item.d)
|
|
257
|
+
const mid = start + ((acc + need / 2) / Math.max(1e-6, total)) * Math.PI * 2
|
|
258
|
+
item.c.ax = Math.cos(mid) * item.d; item.c.ay = Math.sin(mid) * item.d
|
|
259
|
+
acc += need
|
|
260
|
+
}
|
|
261
|
+
cursor = outer + RING_GAP; i = j; ringIdx++
|
|
262
|
+
}
|
|
263
|
+
if (list.length <= 12) chooseRoundestRotation(list)
|
|
264
|
+
}
|
|
265
|
+
|
|
266
|
+
// 簇少时把外围簇的节点沿外圆周摊开:局部 x 映射成角度,圆周真的被节点填满。
|
|
267
|
+
// 关键约束:摊开的角跨度按「每个节点约一个 RING 弧长」反推,绝不把小簇
|
|
268
|
+
// 仅有的几个节点摊满整个扇区 —— 否则同一簇里的一二级节点会被拉到几百像素外。
|
|
269
|
+
const wrapRim = (groups, ring) => {
|
|
270
|
+
const sats = groups.filter(g => Math.hypot(g.ax, g.ay) > 1)
|
|
271
|
+
if (!sats.length) return
|
|
272
|
+
let R = 0
|
|
273
|
+
for (const g of sats) R = Math.max(R, Math.hypot(g.ax, g.ay) + g.radius * .5)
|
|
274
|
+
const sector = Math.PI * 2 / sats.length
|
|
275
|
+
sats.sort((a, b) => Math.atan2(a.ay, a.ax) - Math.atan2(b.ay, b.ax))
|
|
276
|
+
for (let i = 0; i < sats.length; i++) {
|
|
277
|
+
const g = sats[i]
|
|
278
|
+
const list = g.ids.map(id => cache.get(id)).filter(Boolean)
|
|
279
|
+
if (!list.length) continue
|
|
280
|
+
let minX = Infinity, maxX = -Infinity
|
|
281
|
+
for (const node of list) {
|
|
282
|
+
const lx = node.x - g.ax
|
|
283
|
+
if (lx < minX) minX = lx
|
|
284
|
+
if (lx > maxX) maxX = lx
|
|
285
|
+
}
|
|
286
|
+
const span = Math.max(1, maxX - minX)
|
|
287
|
+
const base = -Math.PI / 2 + (i + .5) * sector
|
|
288
|
+
// 每个节点至少占 ring 的弧长;簇小的时候只占扇区的一小段。
|
|
289
|
+
const spread = Math.min(sector * .94, Math.max(1, list.length) * (ring / Math.max(R, ring)))
|
|
290
|
+
for (const node of list) {
|
|
291
|
+
const lx = node.x - g.ax, ly = node.y - g.ay
|
|
292
|
+
const t = (lx - minX) / span - .5
|
|
293
|
+
const ang = base + t * spread
|
|
294
|
+
// 径向只用有限的抖动,避免把簇沿半径方向拉散。
|
|
295
|
+
const rr = R + clamp(ly, -ring, ring) * .28
|
|
296
|
+
node.x = Math.cos(ang) * rr; node.y = Math.sin(ang) * rr
|
|
297
|
+
}
|
|
298
|
+
}
|
|
299
|
+
}
|
|
300
|
+
|
|
301
|
+
const layoutFlower = () => {
|
|
302
|
+
if (!nodes.length) return
|
|
303
|
+
const scale = densityScale(nodes.length)
|
|
304
|
+
const ring = 56 * scale
|
|
305
|
+
const minChord = Math.max(22, 44 * scale)
|
|
306
|
+
const maxRing = ring * 2.8
|
|
307
|
+
const groups = buildGroups()
|
|
308
|
+
for (const group of groups) {
|
|
309
|
+
placeFlower(group, ring, minChord, maxRing)
|
|
310
|
+
let l = Infinity, r = -Infinity, t = Infinity, b = -Infinity
|
|
311
|
+
for (const id of group.ids) {
|
|
312
|
+
const node = cache.get(id)
|
|
313
|
+
if (!node) continue
|
|
314
|
+
if (node.x < l) l = node.x
|
|
315
|
+
if (node.x > r) r = node.x
|
|
316
|
+
if (node.y < t) t = node.y
|
|
317
|
+
if (node.y > b) b = node.y
|
|
318
|
+
}
|
|
319
|
+
// 用包围盒中心当簇心:根往往在主枝上,按根对齐会让同心环歪掉。
|
|
320
|
+
group.cx = (l + r) / 2; group.cy = (t + b) / 2
|
|
321
|
+
const dists = []
|
|
322
|
+
for (const id of group.ids) {
|
|
323
|
+
const node = cache.get(id)
|
|
324
|
+
if (node) dists.push(Math.hypot(node.x - group.cx, node.y - group.cy))
|
|
325
|
+
}
|
|
326
|
+
dists.sort((a, b) => a - b)
|
|
327
|
+
const q = dists.length ? dists[Math.min(dists.length - 1, Math.floor(dists.length * .88))] : 0
|
|
328
|
+
group.radius = q + 26
|
|
329
|
+
if (group.cx || group.cy) {
|
|
330
|
+
for (const id of group.ids) {
|
|
331
|
+
const node = cache.get(id)
|
|
332
|
+
if (node) { node.x -= group.cx; node.y -= group.cy }
|
|
333
|
+
}
|
|
334
|
+
group.cx = 0; group.cy = 0
|
|
335
|
+
}
|
|
336
|
+
}
|
|
337
|
+
packDisc(groups)
|
|
338
|
+
for (const group of groups) {
|
|
339
|
+
for (const id of group.ids) {
|
|
340
|
+
const node = cache.get(id)
|
|
341
|
+
if (node) { node.x += group.ax; node.y += group.ay }
|
|
342
|
+
}
|
|
343
|
+
}
|
|
344
|
+
if (groups.length <= 12) wrapRim(groups, ring)
|
|
345
|
+
for (const node of cache.values()) {
|
|
346
|
+
node.vx = 0; node.vy = 0; node.fx = null; node.fy = null; node.locked = false
|
|
347
|
+
}
|
|
348
|
+
// 记下每条边的自然长度当弹簧原长,力模拟只做微调。
|
|
349
|
+
for (const edge of edges) {
|
|
350
|
+
const a = edge.source, b = edge.target
|
|
351
|
+
edge.baseLen = a && b ? Math.max(1, Math.hypot(a.x - b.x, a.y - b.y)) : 56
|
|
352
|
+
edgeLengths.set(JSON.stringify([edge.from, edge.to, edge.kind || '']), edge.baseLen)
|
|
353
|
+
}
|
|
354
|
+
}
|
|
355
|
+
|
|
17
356
|
const update = graph => {
|
|
18
|
-
const input = [...new Map((graph
|
|
357
|
+
const input = [...new Map((graph?.nodes || []).slice(0, INPUT_LIMIT).map(node => [node.id, node])).values()]
|
|
19
358
|
.sort((a, b) => String(a.id).localeCompare(String(b.id)))
|
|
20
359
|
const ids = new Set(input.map(node => node.id))
|
|
21
|
-
const links = (graph
|
|
360
|
+
const links = (graph?.edges || []).filter(edge => ids.has(edge.from) && ids.has(edge.to) && edge.from !== edge.to)
|
|
22
361
|
const nextSignature = JSON.stringify([input.map(node => node.id), links.map(edge => [edge.from, edge.to]).sort()])
|
|
23
362
|
const changed = signature !== nextSignature
|
|
363
|
+
// 重排判定要用「上一帧的节点数」:nodes 马上就被新数据覆盖了
|
|
364
|
+
const previousCount = nodes.length
|
|
24
365
|
const degree = new Map()
|
|
25
366
|
for (const edge of links) {
|
|
26
367
|
degree.set(edge.from, (degree.get(edge.from) || 0) + 1)
|
|
27
368
|
degree.set(edge.to, (degree.get(edge.to) || 0) + 1)
|
|
28
369
|
}
|
|
370
|
+
// 新节点按黄金角螺旋落在邻居质心附近(沿用旧播种逻辑)。
|
|
29
371
|
const fresh = input.filter(node => !cache.has(node.id))
|
|
30
372
|
for (let i = 0; i < fresh.length; i++) {
|
|
31
373
|
const node = fresh[i]
|
|
32
374
|
const neighbors = links.filter(edge => edge.from === node.id || edge.to === node.id)
|
|
33
375
|
.map(edge => cache.get(edge.from === node.id ? edge.to : edge.from)).filter(Boolean)
|
|
34
|
-
const angle = i *
|
|
376
|
+
const angle = i * GOLDEN_ANGLE
|
|
35
377
|
const radius = neighbors.length ? 32 : 24 * Math.sqrt(i + .5)
|
|
36
378
|
const x = neighbors.length ? neighbors.reduce((sum, n) => sum + n.x, 0) / neighbors.length : 0
|
|
37
379
|
const y = neighbors.length ? neighbors.reduce((sum, n) => sum + n.y, 0) / neighbors.length : 0
|
|
38
|
-
cache.set(node.id, { id: node.id, x: x + Math.cos(angle) * radius, y: y + Math.sin(angle) * radius,
|
|
380
|
+
cache.set(node.id, { id: node.id, x: x + Math.cos(angle) * radius, y: y + Math.sin(angle) * radius,
|
|
381
|
+
vx: 0, vy: 0, fx: null, fy: null, locked: false })
|
|
39
382
|
}
|
|
40
|
-
|
|
41
|
-
|
|
42
|
-
|
|
43
|
-
|
|
44
|
-
|
|
45
|
-
|
|
46
|
-
|
|
47
|
-
|
|
383
|
+
// 只合并数据字段,物理字段(含 pin)永远以缓存为准:心跳刷新不会冲掉摆位。
|
|
384
|
+
nodes = input.map(data => {
|
|
385
|
+
const state = cache.get(data.id)
|
|
386
|
+
for (const [key, value] of Object.entries(data)) if (!PHYSICS_KEYS.has(key)) state[key] = value
|
|
387
|
+
state.degree = degree.get(data.id) || 0
|
|
388
|
+
state.radius = 4 + Math.min(3, Math.log2(1 + state.degree)) + clamp(Number(data.strength) || 0, 0, 1) * 2
|
|
389
|
+
return state
|
|
390
|
+
})
|
|
391
|
+
edges = links.map(edge => {
|
|
392
|
+
const source = cache.get(edge.from), target = cache.get(edge.to)
|
|
393
|
+
const key = JSON.stringify([edge.from, edge.to, edge.kind || ''])
|
|
394
|
+
let baseLen = edgeLengths.get(key)
|
|
395
|
+
// 首次见到该边时按当时两端距离记录;自定义摆位后不重算。
|
|
396
|
+
if (baseLen === undefined) { baseLen = baseLenOf(source, target); edgeLengths.set(key, baseLen) }
|
|
397
|
+
// source/target 必须留给物理引擎当节点引用,原始来源记在 manual 上,
|
|
398
|
+
// 否则 edge.source === 'auto' 永远为假(所有边都会被画成手动虚线)。
|
|
399
|
+
return { ...edge, source, target, manual: edge.source !== 'auto', baseLen }
|
|
400
|
+
})
|
|
401
|
+
adjacency = buildAdjacency()
|
|
402
|
+
if (changed) components = buildComponents()
|
|
403
|
+
// 首次拿到真实图(或从空图切到有数据)时用花瓣向心布局铺开:
|
|
404
|
+
// 最大簇居中、外围收成圆。之前只看 signature 是否为空会漏掉「空图先到、
|
|
405
|
+
// 数据后到」的场景,导致新节点按螺旋挤在中心,必须手动点一次重新布局。
|
|
406
|
+
// 但心跳里 200 条上限的截断集合换了一批节点时不能重排:那会让整图跳一下,
|
|
407
|
+
// 极小缩放下就是「所有节点互相打架闪现」。只有上一帧几乎空着才重铺。
|
|
408
|
+
const mostlyFresh = nodes.length > 0 && fresh.length >= Math.ceil(nodes.length * .6)
|
|
409
|
+
&& previousCount <= Math.max(8, nodes.length * .2)
|
|
410
|
+
if (changed && nodes.length && (!layoutInitialized || mostlyFresh)) {
|
|
411
|
+
layoutFlower()
|
|
412
|
+
layoutInitialized = true
|
|
48
413
|
}
|
|
414
|
+
if (changed) reheat(signature ? .25 : 1)
|
|
49
415
|
signature = nextSignature
|
|
50
|
-
|
|
51
|
-
|
|
416
|
+
for (const id of cache.keys()) if (cache.size > CACHE_LIMIT && !ids.has(id)) cache.delete(id)
|
|
417
|
+
if (edgeLengths.size > 4000) edgeLengths.clear()
|
|
52
418
|
return changed
|
|
53
419
|
}
|
|
420
|
+
|
|
421
|
+
const tick = () => {
|
|
422
|
+
if (!nodes.length) return
|
|
423
|
+
alpha += (SIM.alphaTarget - alpha) * SIM.alphaDecay
|
|
424
|
+
if (alpha < SIM.alphaTarget) alpha = SIM.alphaTarget
|
|
425
|
+
const F = factors()
|
|
426
|
+
// settle() 是同步收敛:期间保持作用域,否则松手那一刻会把全图轻推一遍。
|
|
427
|
+
if (dragComp && !dragging && !settling && alpha < .05) dragComp = null
|
|
428
|
+
const active = dragComp ? dragComp.members : nodes
|
|
429
|
+
const activeIds = dragComp ? dragComp.ids : null
|
|
430
|
+
// 网格装全节点:冻结簇只当障碍施力、自身不被积分,活动簇因此不会与其重合。
|
|
431
|
+
const grid = new Map()
|
|
432
|
+
for (const node of nodes) {
|
|
433
|
+
const key = cellKey(node.x, node.y)
|
|
434
|
+
let list = grid.get(key)
|
|
435
|
+
if (!list) grid.set(key, list = [])
|
|
436
|
+
list.push(node)
|
|
437
|
+
}
|
|
438
|
+
const range2 = SIM.range * SIM.range
|
|
439
|
+
const rep = SIM.repel * F.repel * alpha
|
|
440
|
+
for (const node of active) {
|
|
441
|
+
const gx = Math.floor(node.x / SIM.cell), gy = Math.floor(node.y / SIM.cell)
|
|
442
|
+
for (let ox = -1; ox <= 1; ox++) for (let oy = -1; oy <= 1; oy++) {
|
|
443
|
+
const list = grid.get(`${gx + ox},${gy + oy}`)
|
|
444
|
+
if (!list) continue
|
|
445
|
+
for (const other of list) {
|
|
446
|
+
if (other === node) continue
|
|
447
|
+
let dx = node.x - other.x, dy = node.y - other.y, d2 = dx * dx + dy * dy
|
|
448
|
+
if (d2 > range2) continue
|
|
449
|
+
if (d2 < 1) {
|
|
450
|
+
// 确定性抖动:重合时分开,但不引入随机数导致位置不可复现。
|
|
451
|
+
const jitter = hashId(node.id) ^ hashId(other.id)
|
|
452
|
+
dx = ((jitter & 1023) / 1023 - .5) || .25
|
|
453
|
+
dy = ((jitter >>> 10 & 1023) / 1023 - .5) || .25
|
|
454
|
+
d2 = dx * dx + dy * dy + 1
|
|
455
|
+
}
|
|
456
|
+
const d = Math.sqrt(d2), f = rep / (d2 + 60)
|
|
457
|
+
node.vx += dx / d * f; node.vy += dy / d * f
|
|
458
|
+
}
|
|
459
|
+
}
|
|
460
|
+
}
|
|
461
|
+
const lk = SIM.link * alpha
|
|
462
|
+
for (const edge of edges) {
|
|
463
|
+
if (activeIds && (!activeIds.has(edge.from) || !activeIds.has(edge.to))) continue
|
|
464
|
+
const p = edge.source, q = edge.target
|
|
465
|
+
if (!p || !q) continue
|
|
466
|
+
const dx = q.x - p.x, dy = q.y - p.y, dist = Math.hypot(dx, dy) || .01
|
|
467
|
+
const f = (dist - edge.baseLen * F.linkDist) / dist * lk
|
|
468
|
+
const fx = dx * f, fy = dy * f
|
|
469
|
+
p.vx += fx; p.vy += fy; q.vx -= fx; q.vy -= fy
|
|
470
|
+
}
|
|
471
|
+
if (F.center > 0 && active.length) {
|
|
472
|
+
let cx = 0, cy = 0
|
|
473
|
+
for (const node of active) { cx += node.x; cy += node.y }
|
|
474
|
+
cx /= active.length; cy /= active.length
|
|
475
|
+
const cf = SIM.centerForce * F.center * alpha
|
|
476
|
+
for (const node of active) { node.vx += (cx - node.x) * cf; node.vy += (cy - node.y) * cf }
|
|
477
|
+
}
|
|
478
|
+
for (const node of active) {
|
|
479
|
+
node.vx = clamp(node.vx, -24, 24); node.vy = clamp(node.vy, -24, 24)
|
|
480
|
+
if (node.fx != null) { node.x = node.fx; node.vx = 0 } else { node.vx *= SIM.vDecay; node.x += node.vx }
|
|
481
|
+
if (node.fy != null) { node.y = node.fy; node.vy = 0 } else { node.vy *= SIM.vDecay; node.y += node.vy }
|
|
482
|
+
if (!Number.isFinite(node.x) || !Number.isFinite(node.y)) { node.x = 0; node.y = 0; node.vx = 0; node.vy = 0 }
|
|
483
|
+
// 硬分离:弹簧链会把节点拉回彼此身上,而斥力在 alpha 落到地板后就没了,
|
|
484
|
+
// 两颗粒一旦停在重叠位置就会永远贴着(用户看到的「打架 / 重合」)。
|
|
485
|
+
// 阈值只看世界坐标与节点半径,绝不跟缩放挂钩:之前写成 24 / viewScale,
|
|
486
|
+
// 缩到最小(k≈.06)时等于要求 400 世界像素间距,每帧互相猛推,整图就是打架。
|
|
487
|
+
// 拖动中只做「别完全重合」的软约束,否则整簇会被锁成刚性块、弹簧拉不动邻居;
|
|
488
|
+
// 松手后才用完整间距。冻结节点与右键锁定节点不被推。
|
|
489
|
+
if (node.fx == null || (!dragging && !node.locked)) {
|
|
490
|
+
const own = (Number(node.radius) || 4) + (dragging ? 2 : 8)
|
|
491
|
+
const gx = Math.floor(node.x / SIM.cell), gy = Math.floor(node.y / SIM.cell)
|
|
492
|
+
for (let ox = -1; ox <= 1; ox++) for (let oy = -1; oy <= 1; oy++) {
|
|
493
|
+
const list = grid.get(`${gx + ox},${gy + oy}`)
|
|
494
|
+
if (!list) continue
|
|
495
|
+
for (const other of list) {
|
|
496
|
+
if (other === node) continue
|
|
497
|
+
let dx = node.x - other.x, dy = node.y - other.y, d2 = dx * dx + dy * dy
|
|
498
|
+
const minSep = own + (Number(other.radius) || 4), minSep2 = minSep * minSep
|
|
499
|
+
if (d2 >= minSep2) continue
|
|
500
|
+
let d = Math.sqrt(d2)
|
|
501
|
+
if (d < .01) {
|
|
502
|
+
// 完全重合:按 id 哈希给一个确定方向分开,避免随机数让位置不可复现。
|
|
503
|
+
const jitter = hashId(node.id) ^ hashId(other.id)
|
|
504
|
+
dx = ((jitter & 1023) / 1023 - .5) || .25
|
|
505
|
+
dy = ((jitter >>> 10 & 1023) / 1023 - .5) || .25
|
|
506
|
+
d = Math.hypot(dx, dy) || 1
|
|
507
|
+
}
|
|
508
|
+
const push = minSep - d
|
|
509
|
+
node.x += dx / d * push; node.y += dy / d * push
|
|
510
|
+
}
|
|
511
|
+
}
|
|
512
|
+
node.vx *= .3; node.vy *= .3
|
|
513
|
+
// 固定点被推开后要把锁定坐标一起搬走,否则下一帧又被拉回旧位置。
|
|
514
|
+
if (node.fx != null) { node.fx = node.x; node.fy = node.y }
|
|
515
|
+
}
|
|
516
|
+
}
|
|
517
|
+
}
|
|
518
|
+
|
|
54
519
|
return {
|
|
55
|
-
simulation, update,
|
|
56
520
|
get nodes() { return nodes },
|
|
57
521
|
get edges() { return edges },
|
|
522
|
+
get alpha() { return alpha },
|
|
523
|
+
// 空闲时 alpha 落在地板即停止积分:心跳重绘不会让已收敛的布局漂移。
|
|
524
|
+
get active() { return alpha > SIM.alphaTarget + 1e-4 || dragging },
|
|
525
|
+
update,
|
|
526
|
+
tick,
|
|
527
|
+
settle(ticks = 200) {
|
|
528
|
+
settling = true
|
|
529
|
+
try { for (let i = 0; i < ticks; i++) tick() } finally { settling = false }
|
|
530
|
+
alpha = SIM.alphaTarget
|
|
531
|
+
},
|
|
58
532
|
configure(next) {
|
|
533
|
+
const distanceChanged = next?.distance !== undefined && next.distance !== options.distance
|
|
59
534
|
options = { ...options, ...next }
|
|
60
|
-
|
|
61
|
-
|
|
62
|
-
|
|
535
|
+
if (distanceChanged) {
|
|
536
|
+
edgeLengths.clear()
|
|
537
|
+
for (const edge of edges) {
|
|
538
|
+
edge.baseLen = baseLenOf(edge.source, edge.target)
|
|
539
|
+
edgeLengths.set(JSON.stringify([edge.from, edge.to, edge.kind || '']), edge.baseLen)
|
|
540
|
+
}
|
|
541
|
+
}
|
|
542
|
+
reheat(.25)
|
|
543
|
+
},
|
|
544
|
+
reheat,
|
|
545
|
+
// pin = 用户右键锁定(计数、画标记);hold = 拖动落点(留在原地但不计为锁定)。
|
|
546
|
+
pin(id, x, y) {
|
|
547
|
+
const state = cache.get(id)
|
|
548
|
+
if (!state) return
|
|
549
|
+
state.fx = x; state.fy = y; state.x = x; state.y = y; state.vx = 0; state.vy = 0; state.locked = true
|
|
550
|
+
reheat(.3)
|
|
551
|
+
},
|
|
552
|
+
hold(id, x, y) {
|
|
553
|
+
const state = cache.get(id)
|
|
554
|
+
if (!state) return
|
|
555
|
+
state.fx = x; state.fy = y; state.x = x; state.y = y; state.vx = 0; state.vy = 0
|
|
556
|
+
reheat(.55)
|
|
557
|
+
},
|
|
558
|
+
// 松手:解除临时固定,但把相连边的自然长度改成当前距离 —— 节点留在原地不被
|
|
559
|
+
// 拉回,同时仍是自由节点,之后拖别的节点还能带动它。
|
|
560
|
+
release(id) {
|
|
561
|
+
const state = cache.get(id)
|
|
562
|
+
if (!state) return
|
|
563
|
+
state.fx = null; state.fy = null; state.vx = 0; state.vy = 0
|
|
564
|
+
for (const edge of edges) {
|
|
565
|
+
if (edge.from !== id && edge.to !== id) continue
|
|
566
|
+
edge.baseLen = Math.max(24, Math.hypot(edge.source.x - edge.target.x, edge.source.y - edge.target.y))
|
|
567
|
+
edgeLengths.set(JSON.stringify([edge.from, edge.to, edge.kind || '']), edge.baseLen)
|
|
568
|
+
}
|
|
569
|
+
reheat(.2)
|
|
570
|
+
},
|
|
571
|
+
unpin(id) {
|
|
572
|
+
const state = cache.get(id)
|
|
573
|
+
if (!state) return
|
|
574
|
+
state.fx = null; state.fy = null; state.vx = 0; state.vy = 0; state.locked = false
|
|
575
|
+
reheat(.3)
|
|
576
|
+
},
|
|
577
|
+
unpinAll() {
|
|
578
|
+
for (const state of cache.values()) {
|
|
579
|
+
state.fx = null; state.fy = null; state.vx = 0; state.vy = 0; state.locked = false
|
|
580
|
+
}
|
|
581
|
+
reheat(.35)
|
|
582
|
+
},
|
|
583
|
+
relayout() {
|
|
584
|
+
layoutFlower()
|
|
585
|
+
// 重排后必须按新几何重记弹簧原长:否则沿用旧的 baseLen(可能来自上一次拖动
|
|
586
|
+
// 或上一版布局)会把刚铺开的节点硬拽回旧间距,弹簧与斥力互相拉扯,
|
|
587
|
+
// 极小缩放下就是成对节点「打架 / 闪现」。与 configure 改距离时同一套口径。
|
|
588
|
+
edgeLengths.clear()
|
|
589
|
+
for (const edge of edges) {
|
|
590
|
+
edge.baseLen = baseLenOf(edge.source, edge.target)
|
|
591
|
+
edgeLengths.set(JSON.stringify([edge.from, edge.to, edge.kind || '']), edge.baseLen)
|
|
592
|
+
}
|
|
593
|
+
dragComp = null; dragging = false; alpha = 1
|
|
594
|
+
},
|
|
595
|
+
componentOf,
|
|
596
|
+
startDragScope(id) {
|
|
597
|
+
dragging = true
|
|
598
|
+
const comp = componentOf(id)
|
|
599
|
+
dragComp = comp ? { ids: comp.ids, members: comp.members } : null
|
|
600
|
+
reheat(.35)
|
|
601
|
+
return dragComp
|
|
63
602
|
},
|
|
64
|
-
|
|
65
|
-
|
|
603
|
+
setDragging(value) { dragging = value },
|
|
604
|
+
clearDragScope() { dragComp = null; dragging = false },
|
|
605
|
+
nodeById: id => cache.get(id),
|
|
606
|
+
dispose() { cache.clear(); edgeLengths.clear(); nodes = []; edges = []; components = null; adjacency = new Map() },
|
|
66
607
|
}
|
|
67
608
|
}
|
|
68
609
|
|
|
69
610
|
export function fitCamera(nodes, width, height) {
|
|
70
611
|
if (!nodes.length) return { x: width / 2, y: height / 2, k: 1 }
|
|
71
|
-
|
|
72
|
-
|
|
73
|
-
|
|
74
|
-
|
|
612
|
+
let left = Infinity, right = -Infinity, top = Infinity, bottom = -Infinity
|
|
613
|
+
for (const node of nodes) {
|
|
614
|
+
const r = Number(node.radius) || 4
|
|
615
|
+
left = Math.min(left, node.x - r); right = Math.max(right, node.x + r)
|
|
616
|
+
top = Math.min(top, node.y - r); bottom = Math.max(bottom, node.y + r)
|
|
617
|
+
}
|
|
75
618
|
const k = clamp(Math.min(Math.max(32, width - 100) / Math.max(120, right - left),
|
|
76
619
|
Math.max(32, height - 96) / Math.max(120, bottom - top)), .06, 1.6)
|
|
77
620
|
return { x: width / 2 - (left + right) * k / 2, y: height / 2 - (top + bottom) * k / 2, k }
|
|
@@ -110,28 +653,52 @@ export function placeLabels(candidates, obstacles, width, height) {
|
|
|
110
653
|
return labels
|
|
111
654
|
}
|
|
112
655
|
|
|
113
|
-
|
|
656
|
+
// ---- 画布控制器:相机、渲染、指针与键盘 ------------------------------------
|
|
657
|
+
export function createGraphView(canvas, { onFocus = () => {}, onZoom = () => {}, onPaint = () => {}, tooltip,
|
|
658
|
+
reducedMotion = false, emptyLabel = '' } = {}) {
|
|
114
659
|
const context = canvas.getContext('2d')
|
|
115
660
|
if (!context) throw new Error('Canvas 2D is unavailable')
|
|
116
|
-
const layout =
|
|
661
|
+
const layout = createForceLayout()
|
|
117
662
|
let width = 1, height = 1, ratio = 1, camera = { x: 0, y: 0, k: 1 }
|
|
118
663
|
let options = { ...DEFAULT_OPTIONS }, focused = '', hovered = null, gesture = null
|
|
119
664
|
let initialized = false, disposed = false, frame = null, lastTime = 0, accumulator = 0
|
|
120
665
|
const pointers = new Map(), cleanup = []
|
|
121
666
|
const win = canvas.ownerDocument.defaultView
|
|
122
667
|
const world = point => ({ x: (point.x - camera.x) / camera.k, y: (point.y - camera.y) / camera.k })
|
|
123
|
-
const
|
|
124
|
-
const radius = node => clamp(node.radius * Math.sqrt(camera.k), 2.5, 22)
|
|
668
|
+
const radius = node => clamp((Number(node.radius) || 4) * Math.sqrt(camera.k), 2.5, 22)
|
|
125
669
|
const point = event => {
|
|
126
670
|
const rect = canvas.getBoundingClientRect()
|
|
127
671
|
return { x: (event.clientX - rect.left) * width / rect.width, y: (event.clientY - rect.top) * height / rect.height }
|
|
128
672
|
}
|
|
129
|
-
|
|
130
|
-
|
|
131
|
-
|
|
132
|
-
|
|
133
|
-
|
|
673
|
+
// 命中测试走世界网格;千级节点时避免每次 pointermove 全量扫描。
|
|
674
|
+
// prefer = 当前 hover:极小缩放下几十个节点会挤进同一个像素邻域,纯最近邻会每帧换人,
|
|
675
|
+
// 看起来就是节点之间"打架闪现"。所以只有明显更近(>25%)才换目标。
|
|
676
|
+
const hit = (p, prefer) => {
|
|
677
|
+
const nodes = layout.nodes
|
|
678
|
+
if (!nodes.length) return null
|
|
679
|
+
const target = world(p), reach = clamp(Math.ceil(40 / Math.max(camera.k, .06) / SIM.cell), 1, 8)
|
|
680
|
+
const gx = Math.floor(target.x / SIM.cell), gy = Math.floor(target.y / SIM.cell), grid = new Map()
|
|
681
|
+
for (const node of nodes) {
|
|
682
|
+
const key = cellKey(node.x, node.y)
|
|
683
|
+
let list = grid.get(key)
|
|
684
|
+
if (!list) grid.set(key, list = [])
|
|
685
|
+
list.push(node)
|
|
686
|
+
}
|
|
687
|
+
const near = node => Math.max(6, radius(node) + 4)
|
|
688
|
+
let closest = null, distance = Infinity, preferDistance = Infinity
|
|
689
|
+
for (let ox = -reach; ox <= reach; ox++) for (let oy = -reach; oy <= reach; oy++) {
|
|
690
|
+
const list = grid.get(`${gx + ox},${gy + oy}`)
|
|
691
|
+
if (!list) continue
|
|
692
|
+
for (const node of list) {
|
|
693
|
+
const sx = node.x * camera.k + camera.x, sy = node.y * camera.k + camera.y
|
|
694
|
+
const d = Math.hypot(sx - p.x, sy - p.y)
|
|
695
|
+
if (node === prefer) preferDistance = d
|
|
696
|
+
if (d <= near(node) && d < distance) { closest = node; distance = d }
|
|
697
|
+
}
|
|
134
698
|
}
|
|
699
|
+
// 磁滞:只有新候选确实更近(≥2px)才换目标。极小缩放下两颗点可能只差 2-3px,
|
|
700
|
+
// 纯最近邻会随鼠标 1px 抖动来回换人 —— 高亮反复切换就是「打架闪现」。
|
|
701
|
+
if (prefer && preferDistance <= near(prefer) && (!closest || distance > preferDistance - 2)) return prefer
|
|
135
702
|
return closest
|
|
136
703
|
}
|
|
137
704
|
const hideTooltip = () => { if (tooltip) tooltip.hidden = true }
|
|
@@ -145,12 +712,33 @@ export function createGraphView(canvas, { onFocus = () => {}, onZoom = () => {},
|
|
|
145
712
|
tooltip.style.left = `${clamp(p.x + 14, 6, Math.max(6, width - Math.min(260, width - 12)))}px`
|
|
146
713
|
tooltip.style.top = `${(canvas.offsetTop || 0) + clamp(p.y + 16, 6, height - 60)}px`
|
|
147
714
|
}
|
|
715
|
+
const restoreGesture = current => {
|
|
716
|
+
if (!current?.snapshot) return
|
|
717
|
+
for (const saved of current.snapshot) {
|
|
718
|
+
const state = layout.nodeById(saved.id)
|
|
719
|
+
if (!state) continue
|
|
720
|
+
state.fx = saved.fx; state.fy = saved.fy; state.locked = saved.locked === true
|
|
721
|
+
state.x = saved.x; state.y = saved.y; state.vx = 0; state.vy = 0
|
|
722
|
+
}
|
|
723
|
+
layout.clearDragScope()
|
|
724
|
+
}
|
|
725
|
+
const drawGrid = alpha => {
|
|
726
|
+
const step = 34 * camera.k
|
|
727
|
+
if (step < 12) return
|
|
728
|
+
const ox = ((camera.x % step) + step) % step, oy = ((camera.y % step) + step) % step
|
|
729
|
+
context.fillStyle = context.strokeStyle
|
|
730
|
+
context.globalAlpha = alpha
|
|
731
|
+
context.beginPath()
|
|
732
|
+
for (let x = ox; x < width; x += step) for (let y = oy; y < height; y += step) context.rect(x, y, 1.2, 1.2)
|
|
733
|
+
context.fill()
|
|
734
|
+
}
|
|
148
735
|
const draw = () => {
|
|
149
736
|
context.setTransform(ratio, 0, 0, ratio, 0, 0)
|
|
150
737
|
context.clearRect(0, 0, width, height)
|
|
151
738
|
const style = win.getComputedStyle(canvas)
|
|
152
|
-
const foreground = style.color
|
|
739
|
+
const foreground = style.color || '#202020'
|
|
153
740
|
const background = style.getPropertyValue('--dsw-alias-bg-layer-1').trim() || '#ffffff'
|
|
741
|
+
const accent = style.getPropertyValue('--dsw-alias-brand-primary').trim() || '#3b5bdb'
|
|
154
742
|
const active = hovered?.id || focused
|
|
155
743
|
const neighbors = new Set(active ? [active] : [])
|
|
156
744
|
for (const edge of layout.edges) {
|
|
@@ -158,79 +746,220 @@ export function createGraphView(canvas, { onFocus = () => {}, onZoom = () => {},
|
|
|
158
746
|
if (edge.to === active) neighbors.add(edge.from)
|
|
159
747
|
}
|
|
160
748
|
context.strokeStyle = foreground
|
|
749
|
+
// 呼吸只在模拟活跃时出现:冷却后不再为了透明度自续帧(空闲 = 零帧、零 GPU)。
|
|
750
|
+
const breath = options.motion && !reducedMotion && layout.active ? .06 + .025 * Math.sin(Date.now() / 900) : .07
|
|
751
|
+
if (options.grid !== false) drawGrid(breath)
|
|
752
|
+
// 边:自动边实线、手动/worker 边虚线并按「主语 → 宾语」画箭头,两批各自一次 stroke。
|
|
753
|
+
const k = camera.k, ox = camera.x, oy = camera.y
|
|
754
|
+
// 按「rule 颜色 + 实/虚 + 是否簇间骨架」分组,每组一次 stroke;最多 6 色,开销可控。
|
|
755
|
+
const batches = new Map()
|
|
161
756
|
for (const edge of layout.edges) {
|
|
162
|
-
const a =
|
|
163
|
-
const
|
|
164
|
-
|
|
165
|
-
|
|
166
|
-
|
|
167
|
-
|
|
168
|
-
|
|
169
|
-
|
|
170
|
-
|
|
171
|
-
|
|
172
|
-
|
|
173
|
-
|
|
174
|
-
|
|
175
|
-
|
|
176
|
-
context.globalAlpha = active
|
|
177
|
-
context.
|
|
178
|
-
context.beginPath()
|
|
179
|
-
|
|
180
|
-
|
|
181
|
-
|
|
757
|
+
const a = { x: edge.source.x * k + ox, y: edge.source.y * k + oy }
|
|
758
|
+
const b = { x: edge.target.x * k + ox, y: edge.target.y * k + oy }
|
|
759
|
+
if ((a.x < -40 && b.x < -40) || (a.x > width + 40 && b.x > width + 40)) continue
|
|
760
|
+
if ((a.y < -40 && b.y < -40) || (a.y > height + 40 && b.y > height + 40)) continue
|
|
761
|
+
const color = edgeColor(edge, foreground, accent)
|
|
762
|
+
const skeleton = edge.source.kind !== 'memory' && edge.target.kind !== 'memory'
|
|
763
|
+
const key = `${color}|${edge.manual ? 'd' : 's'}|${skeleton ? 'k' : 'n'}`
|
|
764
|
+
let batch = batches.get(key)
|
|
765
|
+
if (!batch) batches.set(key, batch = { color, manual: edge.manual, skeleton, list: [] })
|
|
766
|
+
batch.list.push({ edge, a, b })
|
|
767
|
+
}
|
|
768
|
+
context.lineWidth = .8
|
|
769
|
+
for (const batch of batches.values()) {
|
|
770
|
+
context.strokeStyle = batch.color
|
|
771
|
+
context.globalAlpha = active ? .055 : (batch.skeleton ? .1 : batch.manual ? .24 : .16)
|
|
772
|
+
context.setLineDash(batch.manual ? [5, 4] : [])
|
|
773
|
+
context.beginPath()
|
|
774
|
+
for (const item of batch.list) { context.moveTo(item.a.x, item.a.y); context.lineTo(item.b.x, item.b.y) }
|
|
775
|
+
context.stroke()
|
|
776
|
+
context.setLineDash([])
|
|
777
|
+
// 箭头只表示有向断言:提及/冲突是关系型证据,不画箭头(与 HTML 一致)。
|
|
778
|
+
if (batch.manual && camera.k >= .3) {
|
|
779
|
+
context.fillStyle = batch.color
|
|
780
|
+
context.globalAlpha = active ? .22 : .4
|
|
781
|
+
for (const item of batch.list) {
|
|
782
|
+
if (item.edge.rule === 'entity-mention' || item.edge.rule === 'conflict') continue
|
|
783
|
+
const dx = item.b.x - item.a.x, dy = item.b.y - item.a.y, d = Math.hypot(dx, dy)
|
|
784
|
+
if (d <= 22) continue
|
|
785
|
+
const ux = dx / d, uy = dy / d, rr = radius(item.edge.target) + 3
|
|
786
|
+
const hx = item.b.x - ux * rr, hy = item.b.y - uy * rr
|
|
787
|
+
context.beginPath()
|
|
788
|
+
context.moveTo(hx, hy)
|
|
789
|
+
context.lineTo(hx - ux * 7 - uy * 3.4, hy - uy * 7 + ux * 3.4)
|
|
790
|
+
context.lineTo(hx - ux * 7 + uy * 3.4, hy - uy * 7 - ux * 3.4)
|
|
791
|
+
context.closePath(); context.fill()
|
|
792
|
+
}
|
|
793
|
+
}
|
|
794
|
+
}
|
|
795
|
+
if (active) {
|
|
796
|
+
context.globalAlpha = .6; context.lineWidth = 1.5; context.strokeStyle = accent
|
|
797
|
+
context.beginPath()
|
|
798
|
+
for (const edge of layout.edges) {
|
|
799
|
+
if (edge.from !== active && edge.to !== active) continue
|
|
800
|
+
context.moveTo(edge.source.x * k + ox, edge.source.y * k + oy)
|
|
801
|
+
context.lineTo(edge.target.x * k + ox, edge.target.y * k + oy)
|
|
182
802
|
}
|
|
803
|
+
context.stroke()
|
|
183
804
|
}
|
|
184
805
|
context.globalAlpha = 1
|
|
185
|
-
|
|
186
|
-
|
|
187
|
-
|
|
188
|
-
|
|
189
|
-
|
|
190
|
-
|
|
191
|
-
|
|
192
|
-
|
|
193
|
-
|
|
194
|
-
|
|
195
|
-
|
|
196
|
-
|
|
197
|
-
|
|
198
|
-
|
|
199
|
-
|
|
200
|
-
|
|
201
|
-
|
|
202
|
-
|
|
203
|
-
|
|
204
|
-
|
|
205
|
-
|
|
206
|
-
|
|
207
|
-
|
|
806
|
+
context.strokeStyle = foreground
|
|
807
|
+
const visible = []
|
|
808
|
+
for (const node of layout.nodes) {
|
|
809
|
+
const x = node.x * k + ox, y = node.y * k + oy
|
|
810
|
+
// 留足裁剪余量:拖动时硬分离会把邻簇推开,小视口下也不该让节点突然消失
|
|
811
|
+
// (可见性仍由下面的点层 LOD 与标签视口裁剪兜底)。
|
|
812
|
+
if (x >= -120 && x <= width + 120 && y >= -120 && y <= height + 120) visible.push({ node, x, y, r: radius(node) })
|
|
813
|
+
}
|
|
814
|
+
const dots = layout.nodes.length > 2400 && camera.k < .3
|
|
815
|
+
if (dots) {
|
|
816
|
+
// 点层 LOD:按颜色批量 2px 方点,不建每节点对象、不逐颗 arc。
|
|
817
|
+
const groups = new Map()
|
|
818
|
+
for (const node of layout.nodes) {
|
|
819
|
+
const x = node.x * k + ox, y = node.y * k + oy
|
|
820
|
+
if (x < 0 || x > width || y < 0 || y > height) continue
|
|
821
|
+
const color = nodeColor(node)
|
|
822
|
+
let list = groups.get(color)
|
|
823
|
+
if (!list) groups.set(color, list = [])
|
|
824
|
+
list.push(x, y)
|
|
825
|
+
}
|
|
826
|
+
context.globalAlpha = 1
|
|
827
|
+
for (const [color, list] of groups) {
|
|
828
|
+
context.fillStyle = color
|
|
829
|
+
context.beginPath()
|
|
830
|
+
for (let i = 0; i < list.length; i += 2) context.rect(list[i] - 1, list[i + 1] - 1, 2, 2)
|
|
831
|
+
context.fill()
|
|
832
|
+
}
|
|
833
|
+
} else {
|
|
834
|
+
// 详细层:按「颜色 + 是否淡出」分组,每节点仍恰好一次 ctx.arc。
|
|
835
|
+
const groups = new Map()
|
|
836
|
+
for (const p of visible) {
|
|
837
|
+
const faded = !!active && !neighbors.has(p.node.id)
|
|
838
|
+
const key = nodeColor(p.node) + (faded ? '|d' : '|n')
|
|
839
|
+
let list = groups.get(key)
|
|
840
|
+
if (!list) groups.set(key, list = [])
|
|
841
|
+
list.push(p)
|
|
842
|
+
}
|
|
843
|
+
for (const [key, list] of groups) {
|
|
844
|
+
const [color, mode] = key.split('|')
|
|
845
|
+
context.globalAlpha = mode === 'd' ? .22 : 1
|
|
846
|
+
context.fillStyle = color
|
|
847
|
+
context.beginPath()
|
|
848
|
+
for (const p of list) { context.moveTo(p.x + p.r, p.y); context.arc(p.x, p.y, p.r, 0, TAU) }
|
|
849
|
+
context.fill()
|
|
850
|
+
}
|
|
851
|
+
context.globalAlpha = 1
|
|
852
|
+
const queryHighlight = String(options.query || '').trim().toLowerCase()
|
|
853
|
+
// 实体用圆角方覆盖圆点;arcTo 不增加 arc 计数。
|
|
854
|
+
for (const p of visible) {
|
|
855
|
+
if (p.node.kind === 'memory' || p.node.missing) continue
|
|
856
|
+
const size = p.r * 1.75, rad = Math.min(5, size / 3), x = p.x - size / 2, y = p.y - size / 2
|
|
857
|
+
context.fillStyle = nodeColor(p.node)
|
|
858
|
+
context.beginPath()
|
|
859
|
+
context.moveTo(x + rad, y)
|
|
860
|
+
context.arcTo(x + size, y, x + size, y + size, rad)
|
|
861
|
+
context.arcTo(x + size, y + size, x, y + size, rad)
|
|
862
|
+
context.arcTo(x, y + size, x, y, rad)
|
|
863
|
+
context.arcTo(x, y, x + size, y, rad)
|
|
864
|
+
context.closePath(); context.fill()
|
|
865
|
+
}
|
|
866
|
+
// 临时实体虚线环 / 固定标记:环用 ellipse、标记用 rect,均不污染 arc 计数。
|
|
867
|
+
for (const p of visible) {
|
|
868
|
+
const node = p.node
|
|
869
|
+
if (node.status === 'provisional') {
|
|
870
|
+
context.strokeStyle = nodeColor(node); context.lineWidth = 1.2; context.setLineDash([3, 3])
|
|
871
|
+
context.beginPath(); context.ellipse(p.x, p.y, p.r + 5, p.r + 5, 0, 0, TAU); context.stroke()
|
|
872
|
+
context.setLineDash([])
|
|
873
|
+
}
|
|
874
|
+
if (node.locked) {
|
|
875
|
+
context.fillStyle = background; context.globalAlpha = .95
|
|
876
|
+
context.fillRect(p.x - 1.5, p.y - 1.5, 3, 3); context.globalAlpha = 1
|
|
877
|
+
}
|
|
878
|
+
if (node.id === active || node.id === hovered?.id) {
|
|
879
|
+
context.strokeStyle = node.id === active ? accent : nodeColor(node); context.lineWidth = 1.5
|
|
880
|
+
context.beginPath(); context.ellipse(p.x, p.y, p.r + 4, p.r + 4, 0, 0, TAU); context.stroke()
|
|
208
881
|
}
|
|
209
|
-
|
|
210
|
-
|
|
211
|
-
|
|
212
|
-
|
|
882
|
+
// 工作台搜索命中:与 HTML 的 query 高亮一致,不增加 arc 计数。
|
|
883
|
+
if (queryHighlight && String(node.title || node.id).toLowerCase().includes(queryHighlight)) {
|
|
884
|
+
context.strokeStyle = accent; context.lineWidth = 2
|
|
885
|
+
context.beginPath(); context.ellipse(p.x, p.y, p.r + 4, p.r + 4, 0, 0, TAU); context.stroke()
|
|
886
|
+
}
|
|
887
|
+
}
|
|
888
|
+
}
|
|
889
|
+
context.globalAlpha = 1
|
|
890
|
+
context.strokeStyle = foreground
|
|
891
|
+
if (options.labels && !dots) {
|
|
892
|
+
// 原版标签逻辑:按缩放决定铺多少、缩得越小字越淡、拖动/平移时只画焦点,
|
|
893
|
+
// 冲突时下移一行、仍冲突就跳过;文字用背景色描边当 halo。
|
|
894
|
+
context.font = '11.5px -apple-system,"PingFang SC","Microsoft YaHei",sans-serif'
|
|
895
|
+
const inView = visible.filter(p => p.x > -60 && p.x < width + 60 && p.y > -60 && p.y < height + 60)
|
|
896
|
+
const showAll = (camera.k >= .55 || visible.length < 34) && inView.length <= 260
|
|
897
|
+
const minDeg = inView.length > 260 ? 9999 : 3
|
|
898
|
+
const zoomFade = clamp((camera.k - .3) / .35, 0, 1)
|
|
899
|
+
const panning = gesture?.type === 'pan' && gesture.moved
|
|
900
|
+
const draggingNode = gesture?.type === 'node' && gesture.moved
|
|
901
|
+
const interactive = (draggingNode || panning) && layout.nodes.length > 400
|
|
902
|
+
const candidates = interactive
|
|
903
|
+
? inView.filter(p => p.node.id === active)
|
|
904
|
+
: showAll ? inView : inView.filter(p => p.node.id === active || p.node.degree >= minDeg)
|
|
905
|
+
const ordered = candidates.length > 260 ? candidates.slice(0, 260) : candidates
|
|
906
|
+
ordered.sort((a, b) => Number(b.node.id === active) - Number(a.node.id === active) || b.node.degree - a.node.degree)
|
|
907
|
+
const placed = []
|
|
908
|
+
context.textAlign = 'center'; context.textBaseline = 'top'
|
|
909
|
+
for (const p of ordered) {
|
|
910
|
+
if (active && !neighbors.has(p.node.id)) continue
|
|
911
|
+
const must = p.node.id === active
|
|
912
|
+
if (!must) {
|
|
913
|
+
if (!showAll && p.node.degree < minDeg) continue
|
|
914
|
+
if (zoomFade < .02) continue
|
|
915
|
+
}
|
|
916
|
+
const label = String(p.node.title || p.node.id)
|
|
917
|
+
const w = context.measureText(label).width
|
|
918
|
+
const boxOf = yy => ({ l: p.x - w / 2 - 3, t: yy - 1, r: p.x + w / 2 + 3, b: yy + 14 })
|
|
919
|
+
const clash = r => placed.some(q => r.l < q.r && r.r > q.l && r.t < q.b && r.b > q.t)
|
|
920
|
+
let yy = p.y + p.r + 4
|
|
921
|
+
let box = boxOf(yy)
|
|
922
|
+
if (clash(box)) { yy += 16; box = boxOf(yy); if (clash(box)) continue }
|
|
923
|
+
if (box.l < 2 || box.r > width - 2 || box.b > height - 2) continue
|
|
924
|
+
placed.push(box)
|
|
925
|
+
context.globalAlpha = must ? 1 : .78 * Math.max(.35, zoomFade)
|
|
926
|
+
context.lineWidth = 3.5; context.strokeStyle = background; context.lineJoin = 'round'
|
|
927
|
+
context.strokeText(label, p.x, yy)
|
|
213
928
|
context.fillStyle = foreground
|
|
214
|
-
context.fillText(label
|
|
929
|
+
context.fillText(label, p.x, yy)
|
|
215
930
|
}
|
|
216
931
|
context.globalAlpha = 1
|
|
932
|
+
} else if (options.labels && dots && active) {
|
|
933
|
+
const focus = layout.nodes.find(node => node.id === active)
|
|
934
|
+
if (focus) {
|
|
935
|
+
context.font = '12px system-ui, sans-serif'; context.textAlign = 'center'; context.textBaseline = 'top'
|
|
936
|
+
context.fillStyle = foreground
|
|
937
|
+
context.fillText(String(focus.title || focus.id), focus.x * k + ox, focus.y * k + oy + 10)
|
|
938
|
+
}
|
|
217
939
|
}
|
|
218
940
|
if (!layout.nodes.length && emptyLabel) {
|
|
219
941
|
context.font = '13px system-ui, sans-serif'; context.textAlign = 'center'; context.textBaseline = 'middle'
|
|
220
942
|
context.fillStyle = foreground; context.globalAlpha = .55
|
|
221
943
|
context.fillText(emptyLabel, width / 2, height / 2); context.globalAlpha = 1
|
|
222
944
|
}
|
|
945
|
+
// 每真正重绘一次计数一次:缩略图据此决定要不要拷贝,空闲期不再白拷纹理。
|
|
946
|
+
onPaint()
|
|
223
947
|
}
|
|
224
948
|
const animate = time => {
|
|
225
949
|
frame = null
|
|
226
950
|
if (disposed) return
|
|
227
|
-
|
|
951
|
+
const stepping = options.motion && !reducedMotion && layout.active
|
|
952
|
+
if (stepping) {
|
|
228
953
|
accumulator += lastTime ? Math.min(64, time - lastTime) : 17
|
|
229
|
-
|
|
954
|
+
let steps = 0
|
|
955
|
+
for (; accumulator >= 1000 / 60 && steps < 4; accumulator -= 1000 / 60, steps++) layout.tick()
|
|
230
956
|
lastTime = time
|
|
231
|
-
requestDraw()
|
|
232
957
|
} else { lastTime = 0; accumulator = 0 }
|
|
233
958
|
draw()
|
|
959
|
+
// 只有物理仍在跑(模拟活跃 / 拖动 / 收敛)才自续帧。
|
|
960
|
+
// 冷却后不再空转重绘:GPU 占用会随布局收敛回落,而不是长期占住一档。
|
|
961
|
+
// 悬停、相机、数据变化、缩放等路径各自 requestDraw 一帧,画面依旧即时更新。
|
|
962
|
+
if (stepping) requestDraw()
|
|
234
963
|
}
|
|
235
964
|
function requestDraw() {
|
|
236
965
|
if (!disposed && frame === null) frame = win.requestAnimationFrame(animate)
|
|
@@ -247,14 +976,8 @@ export function createGraphView(canvas, { onFocus = () => {}, onZoom = () => {},
|
|
|
247
976
|
canvas.width = Math.round(width * ratio); canvas.height = Math.round(height * ratio)
|
|
248
977
|
requestDraw()
|
|
249
978
|
}
|
|
250
|
-
const releaseNode = () => {
|
|
251
|
-
if (gesture?.node) {
|
|
252
|
-
gesture.node.fx = null; gesture.node.fy = null
|
|
253
|
-
gesture.node.vx = 0; gesture.node.vy = 0
|
|
254
|
-
}
|
|
255
|
-
}
|
|
256
979
|
const startPinch = () => {
|
|
257
|
-
|
|
980
|
+
restoreGesture(gesture)
|
|
258
981
|
const [a, b] = [...pointers.values()]
|
|
259
982
|
gesture = { type: 'pinch', distance: Math.max(1, Math.hypot(b.x - a.x, b.y - a.y)), camera: { ...camera },
|
|
260
983
|
center: { x: (a.x + b.x) / 2, y: (a.y + b.y) / 2 }, moved: true }
|
|
@@ -268,15 +991,25 @@ export function createGraphView(canvas, { onFocus = () => {}, onZoom = () => {},
|
|
|
268
991
|
canvas.setPointerCapture?.(event.pointerId)
|
|
269
992
|
if (pointers.size >= 2) { startPinch(); hideTooltip(); return }
|
|
270
993
|
const node = hit(p)
|
|
271
|
-
|
|
272
|
-
|
|
273
|
-
|
|
994
|
+
const w = world(p)
|
|
995
|
+
const component = node ? layout.componentOf(node.id) : null
|
|
996
|
+
const mode = node && event.shiftKey && component ? 'rigid' : 'node'
|
|
997
|
+
const members = mode === 'rigid' ? component.members : (node ? [node] : [])
|
|
998
|
+
gesture = { type: node ? 'node' : 'pan', node, mode, members, start: p, camera: { ...camera }, moved: false,
|
|
999
|
+
offset: node ? { x: node.x - w.x, y: node.y - w.y } : null,
|
|
1000
|
+
snapshot: members.map(m => ({ id: m.id, x: m.x, y: m.y, fx: m.fx, fy: m.fy, locked: m.locked })) }
|
|
1001
|
+
if (node) {
|
|
1002
|
+
// 拖动期间只临时钉住,不算"锁定";锁定只由右键产生。
|
|
1003
|
+
for (const m of members) layout.hold(m.id, m.x, m.y)
|
|
1004
|
+
layout.startDragScope(node.id)
|
|
1005
|
+
layout.setDragging(true)
|
|
1006
|
+
}
|
|
274
1007
|
hideTooltip()
|
|
275
1008
|
canvas.style.cursor = 'grabbing'
|
|
276
1009
|
}
|
|
277
1010
|
const move = event => {
|
|
278
1011
|
const p = point(event)
|
|
279
|
-
if (!pointers.has(event.pointerId) || !gesture) { setHover(hit(p), p); return }
|
|
1012
|
+
if (!pointers.has(event.pointerId) || !gesture) { setHover(hit(p, hovered), p); return }
|
|
280
1013
|
pointers.set(event.pointerId, p)
|
|
281
1014
|
if (gesture.type === 'pinch') {
|
|
282
1015
|
if (pointers.size < 2) return
|
|
@@ -290,9 +1023,14 @@ export function createGraphView(canvas, { onFocus = () => {}, onZoom = () => {},
|
|
|
290
1023
|
if (!gesture.moved) return
|
|
291
1024
|
if (gesture.node) {
|
|
292
1025
|
const w = world(p), node = gesture.node
|
|
293
|
-
|
|
294
|
-
|
|
295
|
-
|
|
1026
|
+
if (gesture.mode === 'rigid') {
|
|
1027
|
+
const nx = w.x + gesture.offset.x, ny = w.y + gesture.offset.y
|
|
1028
|
+
const dx = nx - node.fx, dy = ny - node.fy
|
|
1029
|
+
for (const m of gesture.members) layout.hold(m.id, m.fx + dx, m.fy + dy)
|
|
1030
|
+
} else layout.hold(node.id, w.x + gesture.offset.x, w.y + gesture.offset.y)
|
|
1031
|
+
// 每次指针移动都同步推进两帧:邻居像珠子链一样立刻跟过来,
|
|
1032
|
+
// 不会等 rAF(小图缩放时 rAF 一帧的位移远小于指针)。
|
|
1033
|
+
layout.settle(2)
|
|
296
1034
|
} else {
|
|
297
1035
|
camera.x = gesture.camera.x + p.x - gesture.start.x; camera.y = gesture.camera.y + p.y - gesture.start.y
|
|
298
1036
|
}
|
|
@@ -303,11 +1041,30 @@ export function createGraphView(canvas, { onFocus = () => {}, onZoom = () => {},
|
|
|
303
1041
|
if (!pointers.has(event.pointerId)) return
|
|
304
1042
|
const cancelled = event.type !== 'pointerup'
|
|
305
1043
|
const selected = gesture?.node
|
|
306
|
-
const click = !cancelled && !gesture?.moved && gesture?.type !== 'pinch'
|
|
307
|
-
|
|
1044
|
+
const click = !cancelled && !gesture?.moved && gesture?.type !== 'pinch' && (event.detail ?? 1) < 2
|
|
1045
|
+
if (click || cancelled) {
|
|
1046
|
+
// 单击不留下临时 pin;取消/Esc 恢复按下前的摆位。
|
|
1047
|
+
restoreGesture(gesture)
|
|
1048
|
+
} else if (selected) {
|
|
1049
|
+
// 松手:原本锁定的节点把锁定点更新到落点;自由节点则 release —— 留在原地
|
|
1050
|
+
// 但不再固定,后续拖别的节点能带动它,右键一次即可(它本来就没被锁)。
|
|
1051
|
+
for (const saved of gesture.snapshot) {
|
|
1052
|
+
const state = layout.nodeById(saved.id)
|
|
1053
|
+
if (!state) continue
|
|
1054
|
+
if (saved.locked || saved.fx != null) {
|
|
1055
|
+
state.fx = state.x; state.fy = state.y; state.locked = true
|
|
1056
|
+
state.vx = 0; state.vy = 0
|
|
1057
|
+
} else {
|
|
1058
|
+
layout.release(saved.id)
|
|
1059
|
+
}
|
|
1060
|
+
}
|
|
1061
|
+
layout.setDragging(false)
|
|
1062
|
+
// 多收敛几帧,让「松手落点」也被安全间距推开,不会停在别的节点身上。
|
|
1063
|
+
if (reducedMotion || !options.motion) { layout.settle(120); layout.clearDragScope() }
|
|
1064
|
+
else layout.reheat(.3)
|
|
1065
|
+
}
|
|
308
1066
|
pointers.delete(event.pointerId)
|
|
309
1067
|
gesture = null
|
|
310
|
-
// A remaining finger may pan, but must never turn a pinch into a node click.
|
|
311
1068
|
if (pointers.size) {
|
|
312
1069
|
const p = [...pointers.values()][0]
|
|
313
1070
|
gesture = { type: 'pan', start: p, camera: { ...camera }, moved: true }
|
|
@@ -324,13 +1081,30 @@ export function createGraphView(canvas, { onFocus = () => {}, onZoom = () => {},
|
|
|
324
1081
|
listen(canvas, 'pointermove', move)
|
|
325
1082
|
for (const type of ['pointerup', 'pointercancel', 'lostpointercapture']) listen(canvas, type, up)
|
|
326
1083
|
listen(canvas, 'pointerleave', () => { if (!gesture) { hovered = null; hideTooltip(); requestDraw() } })
|
|
1084
|
+
// 右键 = 锁定 / 解除:左键只负责显示单链与拖动,不再产生固定点。
|
|
1085
|
+
listen(canvas, 'contextmenu', event => {
|
|
1086
|
+
event.preventDefault()
|
|
1087
|
+
const node = hit(point(event))
|
|
1088
|
+
if (!node) return
|
|
1089
|
+
const state = layout.nodeById(node.id)
|
|
1090
|
+
if (!state) return
|
|
1091
|
+
// 有任何固定点(含拖动残留)就先解开,再点一次才锁定 —— 不会出现要点两次。
|
|
1092
|
+
if (state.fx != null) layout.unpin(node.id)
|
|
1093
|
+
else layout.pin(node.id, state.x, state.y)
|
|
1094
|
+
layout.setDragging(false)
|
|
1095
|
+
if (reducedMotion || !options.motion) layout.settle(20)
|
|
1096
|
+
requestDraw()
|
|
1097
|
+
})
|
|
1098
|
+
// 双击聚焦:第二次 pointerup 的 detail>=2 已在 up 里跳过,避免重复取数。
|
|
1099
|
+
listen(canvas, 'dblclick', event => { onFocus(hit(point(event))?.id || '') })
|
|
327
1100
|
listen(canvas, 'wheel', event => { event.preventDefault(); zoom(Math.exp(-clamp(event.deltaY, -160, 160) * .0025), point(event)) }, { passive: false })
|
|
328
1101
|
listen(canvas, 'keydown', event => {
|
|
329
1102
|
if (event.key === '+' || event.key === '=') zoom(1.25)
|
|
330
1103
|
else if (event.key === '-') zoom(.8)
|
|
331
1104
|
else if (event.key === '0' || event.key === 'Home') fit()
|
|
332
|
-
else if (event.key === 'Escape') {
|
|
333
|
-
|
|
1105
|
+
else if (event.key === 'Escape') {
|
|
1106
|
+
restoreGesture(gesture); gesture = null; pointers.clear(); onFocus(''); hideTooltip(); requestDraw()
|
|
1107
|
+
} else if (['ArrowLeft', 'ArrowRight', 'ArrowUp', 'ArrowDown'].includes(event.key)) {
|
|
334
1108
|
const step = event.shiftKey ? 90 : 30
|
|
335
1109
|
camera.x += event.key === 'ArrowLeft' ? step : event.key === 'ArrowRight' ? -step : 0
|
|
336
1110
|
camera.y += event.key === 'ArrowUp' ? step : event.key === 'ArrowDown' ? -step : 0
|
|
@@ -338,7 +1112,9 @@ export function createGraphView(canvas, { onFocus = () => {}, onZoom = () => {},
|
|
|
338
1112
|
} else return
|
|
339
1113
|
event.preventDefault()
|
|
340
1114
|
})
|
|
341
|
-
listen(win, 'blur', () => {
|
|
1115
|
+
listen(win, 'blur', () => {
|
|
1116
|
+
restoreGesture(gesture); gesture = null; pointers.clear(); hovered = null; hideTooltip(); requestDraw()
|
|
1117
|
+
})
|
|
342
1118
|
const observer = win.ResizeObserver ? new win.ResizeObserver(resize) : null
|
|
343
1119
|
observer?.observe(canvas)
|
|
344
1120
|
listen(win, 'resize', resize)
|
|
@@ -348,31 +1124,50 @@ export function createGraphView(canvas, { onFocus = () => {}, onZoom = () => {},
|
|
|
348
1124
|
resize()
|
|
349
1125
|
return {
|
|
350
1126
|
update(graph, focus = '') {
|
|
351
|
-
// A response may arrive mid-drag. End only gestures whose node disappeared.
|
|
352
1127
|
if (gesture?.node && !graph.nodes.some(node => node.id === gesture.node.id)) {
|
|
353
|
-
|
|
1128
|
+
restoreGesture(gesture); gesture = null; pointers.clear()
|
|
354
1129
|
}
|
|
355
1130
|
const changed = layout.update(graph)
|
|
356
1131
|
focused = focus
|
|
357
1132
|
if (hovered && !layout.nodes.includes(hovered)) { hovered = null; hideTooltip() }
|
|
358
1133
|
if (!initialized && layout.nodes.length) {
|
|
359
1134
|
layout.settle(220); initialized = true; fit()
|
|
360
|
-
} else if (changed && reducedMotion) layout.settle(180)
|
|
1135
|
+
} else if (changed && (reducedMotion || !options.motion)) layout.settle(180)
|
|
361
1136
|
requestDraw()
|
|
362
1137
|
},
|
|
363
1138
|
configure(next) {
|
|
364
|
-
const
|
|
365
|
-
next.distance !== undefined && next.distance !== options.distance
|
|
1139
|
+
const forceChanged = ['repulsion', 'distance', 'center'].some(key => next[key] !== undefined && next[key] !== options[key])
|
|
366
1140
|
options = { ...options, ...next }
|
|
367
|
-
if (
|
|
368
|
-
layout.configure(
|
|
369
|
-
if (reducedMotion) layout.settle(
|
|
1141
|
+
if (forceChanged) {
|
|
1142
|
+
layout.configure(next)
|
|
1143
|
+
if (reducedMotion || !options.motion) layout.settle(160)
|
|
370
1144
|
}
|
|
371
1145
|
requestDraw()
|
|
372
1146
|
},
|
|
373
1147
|
fit, zoom,
|
|
1148
|
+
isPinned(id) { return layout.nodeById(id)?.locked === true },
|
|
1149
|
+
pinnedCount() { return layout.nodes.reduce((count, node) => count + (node.locked ? 1 : 0), 0) },
|
|
1150
|
+
// 只读快照(屏幕坐标 + id):验收按 id 追节点,不依赖绘制顺序。
|
|
1151
|
+
snapshot() {
|
|
1152
|
+
return layout.nodes.map(node => ({
|
|
1153
|
+
id: node.id, x: node.x * camera.k + camera.x, y: node.y * camera.k + camera.y,
|
|
1154
|
+
r: radius(node), pinned: node.locked === true, degree: node.degree || 0,
|
|
1155
|
+
}))
|
|
1156
|
+
},
|
|
1157
|
+
unpinAll() {
|
|
1158
|
+
layout.unpinAll(); layout.clearDragScope()
|
|
1159
|
+
if (reducedMotion || !options.motion) layout.settle(120)
|
|
1160
|
+
requestDraw()
|
|
1161
|
+
},
|
|
1162
|
+
relayout() {
|
|
1163
|
+
restoreGesture(gesture); gesture = null; pointers.clear()
|
|
1164
|
+
layout.relayout()
|
|
1165
|
+
if (reducedMotion || !options.motion) layout.settle(220)
|
|
1166
|
+
requestDraw()
|
|
1167
|
+
},
|
|
374
1168
|
dispose() {
|
|
375
|
-
disposed = true
|
|
1169
|
+
disposed = true
|
|
1170
|
+
restoreGesture(gesture); gesture = null; pointers.clear()
|
|
376
1171
|
if (frame !== null) win.cancelAnimationFrame(frame)
|
|
377
1172
|
for (const remove of cleanup) remove()
|
|
378
1173
|
observer?.disconnect(); themeObserver?.disconnect(); layout.dispose(); hideTooltip()
|