dsh-memu-memory 1.3.1 → 1.3.2

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.
Files changed (46) hide show
  1. package/CHANGELOG.md +27 -0
  2. package/README.md +3 -3
  3. package/README.zh.md +3 -1
  4. package/docs/contributing.md +2 -2
  5. package/docs/env-and-commands.md +12 -1
  6. package/docs/memory-semantics.md +8 -2
  7. package/docs/troubleshooting.md +9 -6
  8. package/lib/auto-link/apply.js +249 -0
  9. package/lib/auto-link/candidates.js +155 -0
  10. package/lib/auto-link/decide.js +304 -0
  11. package/lib/auto-link/normalize.js +99 -0
  12. package/lib/auto-link/policy.js +42 -0
  13. package/lib/auto-link/suppression.js +101 -0
  14. package/lib/auto-link/terminology.js +265 -0
  15. package/lib/binding-diagnostics.js +2 -2
  16. package/lib/client.js +1412 -69
  17. package/lib/graph.js +269 -18
  18. package/lib/memory.js +11 -0
  19. package/lib/memu.js +7 -6
  20. package/lib/private-links.js +105 -137
  21. package/lib/private.js +138 -38
  22. package/lib/rpc.js +67 -7
  23. package/lib/state.js +7 -2
  24. package/lib/tools.js +4 -2
  25. package/lib/webui/graph-LICENSE.txt +1 -62
  26. package/lib/webui/graph-view.bundle.js +1 -1
  27. package/lib/webui/graph-view.js +891 -124
  28. package/lib/webui/standalone.js +3 -3
  29. package/package.json +1 -2
  30. package/scripts/build-graph.mjs +3 -3
  31. package/scripts/check-graph-browser.mjs +106 -23
  32. package/scripts/rebuild-auto-links.mjs +252 -0
  33. package/tests/audit-regression.test.mjs +11 -8
  34. package/tests/auto-link-candidates.test.mjs +161 -0
  35. package/tests/auto-link-decide.test.mjs +512 -0
  36. package/tests/auto-link-migration.test.mjs +133 -0
  37. package/tests/client-render.test.mjs +7 -6
  38. package/tests/consolidation-fork.test.mjs +148 -0
  39. package/tests/cycle.test.mjs +1 -1
  40. package/tests/graph-view.test.mjs +163 -21
  41. package/tests/graph.test.mjs +5 -0
  42. package/tests/help-page.test.mjs +3 -3
  43. package/tests/memu-resident-route.test.mjs +130 -0
  44. package/tests/private-links.test.mjs +81 -45
  45. package/tests/stubs/child-process-spy.mjs +14 -0
  46. package/tests/tools.test.mjs +24 -18
@@ -1,24 +1,363 @@
1
- import { forceSimulation, forceLink, forceManyBody, forceCollide, forceX, forceY } from 'd3-force'
1
+ // 自研力导向关系图引擎:零第三方运行时依赖。
2
+ // 数据契约沿用 getGraph:{ nodes:[{id,title,kind,layer,strength,missing,status}], edges:[{from,to,...}] }。
3
+ // 物理:空间网格近程斥力 + 连线弹簧 + 可选向心力;fx/fy 非空 = 固定点(pin)。
4
+ // 拖动时只模拟「被拖节点的连通簇」,其他簇冻结但作为斥力障碍,避免重合。
2
5
 
3
- const LIMIT = 200
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
- // D3 owns mutable physics objects; never let it mutate an RPC snapshot.
8
- export function createLayout() {
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
- let nodes = [], edges = [], signature = ''
11
- let options = { ...DEFAULT_OPTIONS }
12
- const simulation = forceSimulation().stop().alphaDecay(.035).velocityDecay(.48)
13
- .force('charge', forceManyBody().strength(-options.repulsion).distanceMax(1400))
14
- .force('collision', forceCollide(node => node.radius + 12).iterations(2))
15
- .force('x', forceX(0).strength(.025))
16
- .force('y', forceY(0).strength(.025))
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, viewScale = 1
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.nodes || []).slice(0, LIMIT).map(node => [node.id, node])).values()]
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.edges || []).filter(edge => ids.has(edge.from) && ids.has(edge.to) && edge.from !== edge.to)
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
24
363
  const degree = new Map()
@@ -26,52 +365,237 @@ export function createLayout() {
26
365
  degree.set(edge.from, (degree.get(edge.from) || 0) + 1)
27
366
  degree.set(edge.to, (degree.get(edge.to) || 0) + 1)
28
367
  }
368
+ // 新节点按黄金角螺旋落在邻居质心附近(沿用旧播种逻辑)。
29
369
  const fresh = input.filter(node => !cache.has(node.id))
30
370
  for (let i = 0; i < fresh.length; i++) {
31
371
  const node = fresh[i]
32
372
  const neighbors = links.filter(edge => edge.from === node.id || edge.to === node.id)
33
373
  .map(edge => cache.get(edge.from === node.id ? edge.to : edge.from)).filter(Boolean)
34
- const angle = i * 2.399963229728653
374
+ const angle = i * GOLDEN_ANGLE
35
375
  const radius = neighbors.length ? 32 : 24 * Math.sqrt(i + .5)
36
376
  const x = neighbors.length ? neighbors.reduce((sum, n) => sum + n.x, 0) / neighbors.length : 0
37
377
  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, vx: 0, vy: 0 })
378
+ cache.set(node.id, { id: node.id, x: x + Math.cos(angle) * radius, y: y + Math.sin(angle) * radius,
379
+ vx: 0, vy: 0, fx: null, fy: null, locked: false })
39
380
  }
40
- nodes = input.map(data => Object.assign(cache.get(data.id), data, {
41
- degree: degree.get(data.id) || 0,
42
- radius: 4 + Math.min(3, Math.log2(1 + (degree.get(data.id) || 0))) + clamp(Number(data.strength) || 0, 0, 1) * 2,
43
- }))
44
- edges = links.map(edge => ({ ...edge, source: cache.get(edge.from), target: cache.get(edge.to) }))
45
- if (changed) {
46
- simulation.nodes(nodes).force('link', forceLink(edges).id(node => node.id).distance(options.distance).strength(.18))
47
- simulation.alpha(signature ? .25 : 1)
381
+ // 只合并数据字段,物理字段(含 pin)永远以缓存为准:心跳刷新不会冲掉摆位。
382
+ nodes = input.map(data => {
383
+ const state = cache.get(data.id)
384
+ for (const [key, value] of Object.entries(data)) if (!PHYSICS_KEYS.has(key)) state[key] = value
385
+ state.degree = degree.get(data.id) || 0
386
+ state.radius = 4 + Math.min(3, Math.log2(1 + state.degree)) + clamp(Number(data.strength) || 0, 0, 1) * 2
387
+ return state
388
+ })
389
+ edges = links.map(edge => {
390
+ const source = cache.get(edge.from), target = cache.get(edge.to)
391
+ const key = JSON.stringify([edge.from, edge.to, edge.kind || ''])
392
+ let baseLen = edgeLengths.get(key)
393
+ // 首次见到该边时按当时两端距离记录;自定义摆位后不重算。
394
+ if (baseLen === undefined) { baseLen = baseLenOf(source, target); edgeLengths.set(key, baseLen) }
395
+ // source/target 必须留给物理引擎当节点引用,原始来源记在 manual 上,
396
+ // 否则 edge.source === 'auto' 永远为假(所有边都会被画成手动虚线)。
397
+ return { ...edge, source, target, manual: edge.source !== 'auto', baseLen }
398
+ })
399
+ adjacency = buildAdjacency()
400
+ if (changed) components = buildComponents()
401
+ // 首次拿到真实图(或切库后大部分节点都换了)时用花瓣向心布局铺开:
402
+ // 最大簇居中、外围收成圆。之前只看 signature 是否为空会漏掉「空图先到、
403
+ // 数据后到」的场景,导致新节点按螺旋挤在中心,必须手动点一次重新布局。
404
+ const mostlyFresh = nodes.length > 0 && fresh.length >= Math.ceil(nodes.length * .6)
405
+ if (changed && nodes.length && (!layoutInitialized || mostlyFresh)) {
406
+ layoutFlower()
407
+ layoutInitialized = true
48
408
  }
409
+ if (changed) reheat(signature ? .25 : 1)
49
410
  signature = nextSignature
50
- // Keep positions across local-focus changes, but bound the cache for long-lived panes.
51
- for (const id of cache.keys()) if (cache.size > 800 && !ids.has(id)) cache.delete(id)
411
+ for (const id of cache.keys()) if (cache.size > CACHE_LIMIT && !ids.has(id)) cache.delete(id)
412
+ if (edgeLengths.size > 4000) edgeLengths.clear()
52
413
  return changed
53
414
  }
415
+
416
+ const tick = () => {
417
+ if (!nodes.length) return
418
+ alpha += (SIM.alphaTarget - alpha) * SIM.alphaDecay
419
+ if (alpha < SIM.alphaTarget) alpha = SIM.alphaTarget
420
+ const F = factors()
421
+ // settle() 是同步收敛:期间保持作用域,否则松手那一刻会把全图轻推一遍。
422
+ if (dragComp && !dragging && !settling && alpha < .05) dragComp = null
423
+ const active = dragComp ? dragComp.members : nodes
424
+ const activeIds = dragComp ? dragComp.ids : null
425
+ // 网格装全节点:冻结簇只当障碍施力、自身不被积分,活动簇因此不会与其重合。
426
+ const grid = new Map()
427
+ for (const node of nodes) {
428
+ const key = cellKey(node.x, node.y)
429
+ let list = grid.get(key)
430
+ if (!list) grid.set(key, list = [])
431
+ list.push(node)
432
+ }
433
+ const range2 = SIM.range * SIM.range
434
+ const rep = SIM.repel * F.repel * alpha
435
+ for (const node of active) {
436
+ const gx = Math.floor(node.x / SIM.cell), gy = Math.floor(node.y / SIM.cell)
437
+ for (let ox = -1; ox <= 1; ox++) for (let oy = -1; oy <= 1; oy++) {
438
+ const list = grid.get(`${gx + ox},${gy + oy}`)
439
+ if (!list) continue
440
+ for (const other of list) {
441
+ if (other === node) continue
442
+ let dx = node.x - other.x, dy = node.y - other.y, d2 = dx * dx + dy * dy
443
+ if (d2 > range2) continue
444
+ if (d2 < 1) {
445
+ // 确定性抖动:重合时分开,但不引入随机数导致位置不可复现。
446
+ const jitter = hashId(node.id) ^ hashId(other.id)
447
+ dx = ((jitter & 1023) / 1023 - .5) || .25
448
+ dy = ((jitter >>> 10 & 1023) / 1023 - .5) || .25
449
+ d2 = dx * dx + dy * dy + 1
450
+ }
451
+ const d = Math.sqrt(d2), f = rep / (d2 + 60)
452
+ node.vx += dx / d * f; node.vy += dy / d * f
453
+ }
454
+ }
455
+ }
456
+ const lk = SIM.link * alpha
457
+ for (const edge of edges) {
458
+ if (activeIds && (!activeIds.has(edge.from) || !activeIds.has(edge.to))) continue
459
+ const p = edge.source, q = edge.target
460
+ if (!p || !q) continue
461
+ const dx = q.x - p.x, dy = q.y - p.y, dist = Math.hypot(dx, dy) || .01
462
+ const f = (dist - edge.baseLen * F.linkDist) / dist * lk
463
+ const fx = dx * f, fy = dy * f
464
+ p.vx += fx; p.vy += fy; q.vx -= fx; q.vy -= fy
465
+ }
466
+ if (F.center > 0 && active.length) {
467
+ let cx = 0, cy = 0
468
+ for (const node of active) { cx += node.x; cy += node.y }
469
+ cx /= active.length; cy /= active.length
470
+ const cf = SIM.centerForce * F.center * alpha
471
+ for (const node of active) { node.vx += (cx - node.x) * cf; node.vy += (cy - node.y) * cf }
472
+ }
473
+ for (const node of active) {
474
+ node.vx = clamp(node.vx, -24, 24); node.vy = clamp(node.vy, -24, 24)
475
+ if (node.fx != null) { node.x = node.fx; node.vx = 0 } else { node.vx *= SIM.vDecay; node.x += node.vx }
476
+ if (node.fy != null) { node.y = node.fy; node.vy = 0 } else { node.vy *= SIM.vDecay; node.y += node.vy }
477
+ if (!Number.isFinite(node.x) || !Number.isFinite(node.y)) { node.x = 0; node.y = 0; node.vx = 0; node.vy = 0 }
478
+ // 单向硬分离:弹簧链会把节点拉回彼此身上,纯斥力来不及挡住。只把活动节点
479
+ // 推到最小间距外,冻结节点与 pin 节点都不动,所以拖动时跨簇永不重合。
480
+ // 阈值按相机缩放换算:无论缩到多小,屏幕上都至少留出 18px 间距。
481
+ // 拖动中只推自由节点(跟手优先);松手后连「拖动落点」一起推,
482
+ // 免得它停在别的节点身上。右键锁定的节点永远不动。
483
+ if (node.fx == null || (!dragging && !node.locked)) {
484
+ // 拖动中只做「别完全重合」的软约束(世界 12px),否则整簇会被锁成刚性块、
485
+ // 弹簧拉不动邻居,拖动就只剩一条越拉越长的边。松手后才用 24px 屏幕间距。
486
+ const minSep = dragging ? 12 : 24 / clamp(viewScale, .06, 5), minSep2 = minSep * minSep
487
+ const gx = Math.floor(node.x / SIM.cell), gy = Math.floor(node.y / SIM.cell)
488
+ for (let ox = -1; ox <= 1; ox++) for (let oy = -1; oy <= 1; oy++) {
489
+ const list = grid.get(`${gx + ox},${gy + oy}`)
490
+ if (!list) continue
491
+ for (const other of list) {
492
+ if (other === node) continue
493
+ let dx = node.x - other.x, dy = node.y - other.y, d2 = dx * dx + dy * dy
494
+ if (d2 >= minSep2) continue
495
+ if (d2 < .0001) { dx = 1; dy = 0; d2 = 1 }
496
+ const d = Math.sqrt(d2), push = minSep - d
497
+ node.x += dx / d * push; node.y += dy / d * push
498
+ }
499
+ }
500
+ node.vx *= .3; node.vy *= .3
501
+ // 固定点被推开后要把锁定坐标一起搬走,否则下一帧又被拉回旧位置。
502
+ if (node.fx != null) { node.fx = node.x; node.fy = node.y }
503
+ }
504
+ }
505
+ }
506
+
54
507
  return {
55
- simulation, update,
56
508
  get nodes() { return nodes },
57
509
  get edges() { return edges },
510
+ get alpha() { return alpha },
511
+ // 空闲时 alpha 落在地板即停止积分:心跳重绘不会让已收敛的布局漂移。
512
+ get active() { return alpha > SIM.alphaTarget + 1e-4 || dragging },
513
+ update,
514
+ tick,
515
+ settle(ticks = 200) {
516
+ settling = true
517
+ try { for (let i = 0; i < ticks; i++) tick() } finally { settling = false }
518
+ alpha = SIM.alphaTarget
519
+ },
58
520
  configure(next) {
521
+ const distanceChanged = next?.distance !== undefined && next.distance !== options.distance
59
522
  options = { ...options, ...next }
60
- simulation.force('charge').strength(-options.repulsion)
61
- simulation.force('link')?.distance(options.distance)
62
- simulation.alpha(Math.max(.25, simulation.alpha()))
523
+ if (distanceChanged) {
524
+ edgeLengths.clear()
525
+ for (const edge of edges) {
526
+ edge.baseLen = baseLenOf(edge.source, edge.target)
527
+ edgeLengths.set(JSON.stringify([edge.from, edge.to, edge.kind || '']), edge.baseLen)
528
+ }
529
+ }
530
+ reheat(.25)
531
+ },
532
+ reheat,
533
+ setScale(value) { viewScale = Number(value) > 0 ? Number(value) : 1 },
534
+ // pin = 用户右键锁定(计数、画标记);hold = 拖动落点(留在原地但不计为锁定)。
535
+ pin(id, x, y) {
536
+ const state = cache.get(id)
537
+ if (!state) return
538
+ state.fx = x; state.fy = y; state.x = x; state.y = y; state.vx = 0; state.vy = 0; state.locked = true
539
+ reheat(.3)
540
+ },
541
+ hold(id, x, y) {
542
+ const state = cache.get(id)
543
+ if (!state) return
544
+ state.fx = x; state.fy = y; state.x = x; state.y = y; state.vx = 0; state.vy = 0
545
+ reheat(.55)
546
+ },
547
+ // 松手:解除临时固定,但把相连边的自然长度改成当前距离 —— 节点留在原地不被
548
+ // 拉回,同时仍是自由节点,之后拖别的节点还能带动它。
549
+ release(id) {
550
+ const state = cache.get(id)
551
+ if (!state) return
552
+ state.fx = null; state.fy = null; state.vx = 0; state.vy = 0
553
+ for (const edge of edges) {
554
+ if (edge.from !== id && edge.to !== id) continue
555
+ edge.baseLen = Math.max(24, Math.hypot(edge.source.x - edge.target.x, edge.source.y - edge.target.y))
556
+ edgeLengths.set(JSON.stringify([edge.from, edge.to, edge.kind || '']), edge.baseLen)
557
+ }
558
+ reheat(.2)
559
+ },
560
+ unpin(id) {
561
+ const state = cache.get(id)
562
+ if (!state) return
563
+ state.fx = null; state.fy = null; state.vx = 0; state.vy = 0; state.locked = false
564
+ reheat(.3)
565
+ },
566
+ unpinAll() {
567
+ for (const state of cache.values()) {
568
+ state.fx = null; state.fy = null; state.vx = 0; state.vy = 0; state.locked = false
569
+ }
570
+ reheat(.35)
571
+ },
572
+ relayout() {
573
+ layoutFlower()
574
+ dragComp = null; dragging = false; alpha = 1
575
+ },
576
+ componentOf,
577
+ startDragScope(id) {
578
+ dragging = true
579
+ const comp = componentOf(id)
580
+ dragComp = comp ? { ids: comp.ids, members: comp.members } : null
581
+ reheat(.35)
582
+ return dragComp
63
583
  },
64
- settle(ticks = 200) { simulation.tick(ticks) },
65
- dispose() { simulation.stop(); cache.clear() },
584
+ setDragging(value) { dragging = value },
585
+ clearDragScope() { dragComp = null; dragging = false },
586
+ nodeById: id => cache.get(id),
587
+ dispose() { cache.clear(); edgeLengths.clear(); nodes = []; edges = []; components = null; adjacency = new Map() },
66
588
  }
67
589
  }
68
590
 
69
591
  export function fitCamera(nodes, width, height) {
70
592
  if (!nodes.length) return { x: width / 2, y: height / 2, k: 1 }
71
- const left = Math.min(...nodes.map(node => node.x - node.radius))
72
- const right = Math.max(...nodes.map(node => node.x + node.radius))
73
- const top = Math.min(...nodes.map(node => node.y - node.radius))
74
- const bottom = Math.max(...nodes.map(node => node.y + node.radius))
593
+ let left = Infinity, right = -Infinity, top = Infinity, bottom = -Infinity
594
+ for (const node of nodes) {
595
+ const r = Number(node.radius) || 4
596
+ left = Math.min(left, node.x - r); right = Math.max(right, node.x + r)
597
+ top = Math.min(top, node.y - r); bottom = Math.max(bottom, node.y + r)
598
+ }
75
599
  const k = clamp(Math.min(Math.max(32, width - 100) / Math.max(120, right - left),
76
600
  Math.max(32, height - 96) / Math.max(120, bottom - top)), .06, 1.6)
77
601
  return { x: width / 2 - (left + right) * k / 2, y: height / 2 - (top + bottom) * k / 2, k }
@@ -110,27 +634,44 @@ export function placeLabels(candidates, obstacles, width, height) {
110
634
  return labels
111
635
  }
112
636
 
113
- export function createGraphView(canvas, { onFocus = () => {}, onZoom = () => {}, tooltip, reducedMotion = false, emptyLabel = '' } = {}) {
637
+ // ---- 画布控制器:相机、渲染、指针与键盘 ------------------------------------
638
+ export function createGraphView(canvas, { onFocus = () => {}, onZoom = () => {}, tooltip,
639
+ reducedMotion = false, emptyLabel = '' } = {}) {
114
640
  const context = canvas.getContext('2d')
115
641
  if (!context) throw new Error('Canvas 2D is unavailable')
116
- const layout = createLayout()
642
+ const layout = createForceLayout()
117
643
  let width = 1, height = 1, ratio = 1, camera = { x: 0, y: 0, k: 1 }
118
644
  let options = { ...DEFAULT_OPTIONS }, focused = '', hovered = null, gesture = null
119
- let initialized = false, disposed = false, frame = null, lastTime = 0, accumulator = 0
645
+ let initialized = false, disposed = false, frame = null, lastTime = 0, accumulator = 0, idleFrame = 0
120
646
  const pointers = new Map(), cleanup = []
121
647
  const win = canvas.ownerDocument.defaultView
122
648
  const world = point => ({ x: (point.x - camera.x) / camera.k, y: (point.y - camera.y) / camera.k })
123
- const screen = node => ({ x: node.x * camera.k + camera.x, y: node.y * camera.k + camera.y })
124
- const radius = node => clamp(node.radius * Math.sqrt(camera.k), 2.5, 22)
649
+ const radius = node => clamp((Number(node.radius) || 4) * Math.sqrt(camera.k), 2.5, 22)
125
650
  const point = event => {
126
651
  const rect = canvas.getBoundingClientRect()
127
652
  return { x: (event.clientX - rect.left) * width / rect.width, y: (event.clientY - rect.top) * height / rect.height }
128
653
  }
654
+ // 命中测试走世界网格;千级节点时避免每次 pointermove 全量扫描。
129
655
  const hit = p => {
656
+ const nodes = layout.nodes
657
+ if (!nodes.length) return null
658
+ const target = world(p), reach = clamp(Math.ceil(40 / Math.max(camera.k, .06) / SIM.cell), 1, 8)
659
+ const gx = Math.floor(target.x / SIM.cell), gy = Math.floor(target.y / SIM.cell), grid = new Map()
660
+ for (const node of nodes) {
661
+ const key = cellKey(node.x, node.y)
662
+ let list = grid.get(key)
663
+ if (!list) grid.set(key, list = [])
664
+ list.push(node)
665
+ }
130
666
  let closest = null, distance = Infinity
131
- for (const node of layout.nodes) {
132
- const s = screen(node), d = Math.hypot(s.x - p.x, s.y - p.y)
133
- if (d <= Math.max(10, radius(node) + 4) && d < distance) { closest = node; distance = d }
667
+ for (let ox = -reach; ox <= reach; ox++) for (let oy = -reach; oy <= reach; oy++) {
668
+ const list = grid.get(`${gx + ox},${gy + oy}`)
669
+ if (!list) continue
670
+ for (const node of list) {
671
+ const sx = node.x * camera.k + camera.x, sy = node.y * camera.k + camera.y
672
+ const d = Math.hypot(sx - p.x, sy - p.y)
673
+ if (d <= Math.max(10, radius(node) + 4) && d < distance) { closest = node; distance = d }
674
+ }
134
675
  }
135
676
  return closest
136
677
  }
@@ -145,12 +686,34 @@ export function createGraphView(canvas, { onFocus = () => {}, onZoom = () => {},
145
686
  tooltip.style.left = `${clamp(p.x + 14, 6, Math.max(6, width - Math.min(260, width - 12)))}px`
146
687
  tooltip.style.top = `${(canvas.offsetTop || 0) + clamp(p.y + 16, 6, height - 60)}px`
147
688
  }
689
+ const restoreGesture = current => {
690
+ if (!current?.snapshot) return
691
+ for (const saved of current.snapshot) {
692
+ const state = layout.nodeById(saved.id)
693
+ if (!state) continue
694
+ state.fx = saved.fx; state.fy = saved.fy; state.locked = saved.locked === true
695
+ state.x = saved.x; state.y = saved.y; state.vx = 0; state.vy = 0
696
+ }
697
+ layout.clearDragScope()
698
+ }
699
+ const drawGrid = alpha => {
700
+ const step = 34 * camera.k
701
+ if (step < 12) return
702
+ const ox = ((camera.x % step) + step) % step, oy = ((camera.y % step) + step) % step
703
+ context.fillStyle = context.strokeStyle
704
+ context.globalAlpha = alpha
705
+ context.beginPath()
706
+ for (let x = ox; x < width; x += step) for (let y = oy; y < height; y += step) context.rect(x, y, 1.2, 1.2)
707
+ context.fill()
708
+ }
148
709
  const draw = () => {
710
+ layout.setScale(camera.k)
149
711
  context.setTransform(ratio, 0, 0, ratio, 0, 0)
150
712
  context.clearRect(0, 0, width, height)
151
713
  const style = win.getComputedStyle(canvas)
152
- const foreground = style.color
714
+ const foreground = style.color || '#202020'
153
715
  const background = style.getPropertyValue('--dsw-alias-bg-layer-1').trim() || '#ffffff'
716
+ const accent = style.getPropertyValue('--dsw-alias-brand-primary').trim() || '#3b5bdb'
154
717
  const active = hovered?.id || focused
155
718
  const neighbors = new Set(active ? [active] : [])
156
719
  for (const edge of layout.edges) {
@@ -158,62 +721,196 @@ export function createGraphView(canvas, { onFocus = () => {}, onZoom = () => {},
158
721
  if (edge.to === active) neighbors.add(edge.from)
159
722
  }
160
723
  context.strokeStyle = foreground
724
+ // 空闲呼吸只改网格点的透明度,不碰任何坐标:心跳重绘不会让验收截图漂移。
725
+ const breath = options.motion && !reducedMotion ? .06 + .025 * Math.sin(Date.now() / 900) : .07
726
+ if (options.grid !== false) drawGrid(breath)
727
+ // 边:自动边实线、手动/worker 边虚线并按「主语 → 宾语」画箭头,两批各自一次 stroke。
728
+ const k = camera.k, ox = camera.x, oy = camera.y
729
+ // 按「rule 颜色 + 实/虚 + 是否簇间骨架」分组,每组一次 stroke;最多 6 色,开销可控。
730
+ const batches = new Map()
161
731
  for (const edge of layout.edges) {
162
- const a = screen(edge.source), b = screen(edge.target)
163
- const highlighted = active && (edge.from === active || edge.to === active)
164
- context.globalAlpha = highlighted ? .6 : active ? .055 : .16
165
- context.lineWidth = highlighted ? 1.5 : .8
166
- context.beginPath(); context.moveTo(a.x, a.y); context.lineTo(b.x, b.y); context.stroke()
167
- }
168
- const visible = layout.nodes.map(node => ({ node, ...screen(node), radius: radius(node) }))
169
- .filter(p => p.x >= -30 && p.x <= width + 30 && p.y >= -30 && p.y <= height + 30)
170
- for (const p of visible) {
171
- const node = p.node
172
- const color = node.missing ? '#92959c'
173
- : node.kind === 'global' ? '#8b7bd8'
174
- : node.kind !== 'memory' ? '#36a582'
175
- : node.layer === 'must_remember' ? '#d97768' : '#618fcd'
176
- context.globalAlpha = active && !neighbors.has(node.id) ? .22 : 1
177
- context.fillStyle = color
178
- context.beginPath(); context.arc(p.x, p.y, p.radius, 0, Math.PI * 2); context.fill()
179
- if (node.id === active) {
180
- context.strokeStyle = color; context.lineWidth = 1.5
181
- context.beginPath(); context.arc(p.x, p.y, p.radius + 4, 0, Math.PI * 2); context.stroke()
732
+ const a = { x: edge.source.x * k + ox, y: edge.source.y * k + oy }
733
+ const b = { x: edge.target.x * k + ox, y: edge.target.y * k + oy }
734
+ if ((a.x < -40 && b.x < -40) || (a.x > width + 40 && b.x > width + 40)) continue
735
+ if ((a.y < -40 && b.y < -40) || (a.y > height + 40 && b.y > height + 40)) continue
736
+ const color = edgeColor(edge, foreground, accent)
737
+ const skeleton = edge.source.kind !== 'memory' && edge.target.kind !== 'memory'
738
+ const key = `${color}|${edge.manual ? 'd' : 's'}|${skeleton ? 'k' : 'n'}`
739
+ let batch = batches.get(key)
740
+ if (!batch) batches.set(key, batch = { color, manual: edge.manual, skeleton, list: [] })
741
+ batch.list.push({ edge, a, b })
742
+ }
743
+ context.lineWidth = .8
744
+ for (const batch of batches.values()) {
745
+ context.strokeStyle = batch.color
746
+ context.globalAlpha = active ? .055 : (batch.skeleton ? .1 : batch.manual ? .24 : .16)
747
+ context.setLineDash(batch.manual ? [5, 4] : [])
748
+ context.beginPath()
749
+ for (const item of batch.list) { context.moveTo(item.a.x, item.a.y); context.lineTo(item.b.x, item.b.y) }
750
+ context.stroke()
751
+ context.setLineDash([])
752
+ // 箭头只表示有向断言:提及/冲突是关系型证据,不画箭头(与 HTML 一致)。
753
+ if (batch.manual && camera.k >= .3) {
754
+ context.fillStyle = batch.color
755
+ context.globalAlpha = active ? .22 : .4
756
+ for (const item of batch.list) {
757
+ if (item.edge.rule === 'entity-mention' || item.edge.rule === 'conflict') continue
758
+ const dx = item.b.x - item.a.x, dy = item.b.y - item.a.y, d = Math.hypot(dx, dy)
759
+ if (d <= 22) continue
760
+ const ux = dx / d, uy = dy / d, rr = radius(item.edge.target) + 3
761
+ const hx = item.b.x - ux * rr, hy = item.b.y - uy * rr
762
+ context.beginPath()
763
+ context.moveTo(hx, hy)
764
+ context.lineTo(hx - ux * 7 - uy * 3.4, hy - uy * 7 + ux * 3.4)
765
+ context.lineTo(hx - ux * 7 + uy * 3.4, hy - uy * 7 - ux * 3.4)
766
+ context.closePath(); context.fill()
767
+ }
768
+ }
769
+ }
770
+ if (active) {
771
+ context.globalAlpha = .6; context.lineWidth = 1.5; context.strokeStyle = accent
772
+ context.beginPath()
773
+ for (const edge of layout.edges) {
774
+ if (edge.from !== active && edge.to !== active) continue
775
+ context.moveTo(edge.source.x * k + ox, edge.source.y * k + oy)
776
+ context.lineTo(edge.target.x * k + ox, edge.target.y * k + oy)
182
777
  }
778
+ context.stroke()
183
779
  }
184
780
  context.globalAlpha = 1
185
- if (options.labels) {
186
- context.font = '12px system-ui, sans-serif'
187
- const candidates = visible.filter(p => !active || neighbors.has(p.node.id))
188
- .filter(p => camera.k >= .45 || p.node.id === active || p.node.degree >= 3 || layout.nodes.length < 30)
189
- .sort((a, b) => Number(b.node.id === active) - Number(a.node.id === active) || b.node.degree - a.node.degree ||
190
- String(a.node.id).localeCompare(String(b.node.id)))
191
- .map(p => {
192
- const title = String(p.node.title || p.node.id)
193
- let text = title
194
- while (text.length > 1 && context.measureText(text).width > Math.min(136, width - 24)) text = text.slice(0, -1)
195
- if (text !== title) text = text.slice(0, -2) + '...'
196
- return { ...p, text, textWidth: context.measureText(text).width + 4, priority: p.node.degree >= 3 || p.node.id === active }
197
- })
198
- const labels = placeLabels(candidates, visible.map(p => ({
199
- x: p.x - p.radius - 2, y: p.y - p.radius - 2, width: p.radius * 2 + 4, height: p.radius * 2 + 4,
200
- })), width, height)
201
- context.textAlign = 'left'; context.textBaseline = 'top'
202
- for (const label of labels) {
203
- const anchor = { x: clamp(label.x, label.box.x, label.box.x + label.box.width),
204
- y: clamp(label.y, label.box.y, label.box.y + label.box.height) }
205
- if (Math.hypot(anchor.x - label.x, anchor.y - label.y) > label.radius + 18) {
206
- context.globalAlpha = .25; context.strokeStyle = foreground; context.lineWidth = .7
207
- context.beginPath(); context.moveTo(label.x, label.y); context.lineTo(anchor.x, anchor.y); context.stroke()
781
+ context.strokeStyle = foreground
782
+ const visible = []
783
+ for (const node of layout.nodes) {
784
+ const x = node.x * k + ox, y = node.y * k + oy
785
+ // 留足裁剪余量:拖动时硬分离会把邻簇推开,小视口下也不该让节点突然消失
786
+ // (可见性仍由下面的点层 LOD 与标签视口裁剪兜底)。
787
+ if (x >= -120 && x <= width + 120 && y >= -120 && y <= height + 120) visible.push({ node, x, y, r: radius(node) })
788
+ }
789
+ const dots = layout.nodes.length > 2400 && camera.k < .3
790
+ if (dots) {
791
+ // 点层 LOD:按颜色批量 2px 方点,不建每节点对象、不逐颗 arc。
792
+ const groups = new Map()
793
+ for (const node of layout.nodes) {
794
+ const x = node.x * k + ox, y = node.y * k + oy
795
+ if (x < 0 || x > width || y < 0 || y > height) continue
796
+ const color = nodeColor(node)
797
+ let list = groups.get(color)
798
+ if (!list) groups.set(color, list = [])
799
+ list.push(x, y)
800
+ }
801
+ context.globalAlpha = 1
802
+ for (const [color, list] of groups) {
803
+ context.fillStyle = color
804
+ context.beginPath()
805
+ for (let i = 0; i < list.length; i += 2) context.rect(list[i] - 1, list[i + 1] - 1, 2, 2)
806
+ context.fill()
807
+ }
808
+ } else {
809
+ // 详细层:按「颜色 + 是否淡出」分组,每节点仍恰好一次 ctx.arc。
810
+ const groups = new Map()
811
+ for (const p of visible) {
812
+ const faded = !!active && !neighbors.has(p.node.id)
813
+ const key = nodeColor(p.node) + (faded ? '|d' : '|n')
814
+ let list = groups.get(key)
815
+ if (!list) groups.set(key, list = [])
816
+ list.push(p)
817
+ }
818
+ for (const [key, list] of groups) {
819
+ const [color, mode] = key.split('|')
820
+ context.globalAlpha = mode === 'd' ? .22 : 1
821
+ context.fillStyle = color
822
+ context.beginPath()
823
+ for (const p of list) { context.moveTo(p.x + p.r, p.y); context.arc(p.x, p.y, p.r, 0, TAU) }
824
+ context.fill()
825
+ }
826
+ context.globalAlpha = 1
827
+ const queryHighlight = String(options.query || '').trim().toLowerCase()
828
+ // 实体用圆角方覆盖圆点;arcTo 不增加 arc 计数。
829
+ for (const p of visible) {
830
+ if (p.node.kind === 'memory' || p.node.missing) continue
831
+ const size = p.r * 1.75, rad = Math.min(5, size / 3), x = p.x - size / 2, y = p.y - size / 2
832
+ context.fillStyle = nodeColor(p.node)
833
+ context.beginPath()
834
+ context.moveTo(x + rad, y)
835
+ context.arcTo(x + size, y, x + size, y + size, rad)
836
+ context.arcTo(x + size, y + size, x, y + size, rad)
837
+ context.arcTo(x, y + size, x, y, rad)
838
+ context.arcTo(x, y, x + size, y, rad)
839
+ context.closePath(); context.fill()
840
+ }
841
+ // 临时实体虚线环 / 固定标记:环用 ellipse、标记用 rect,均不污染 arc 计数。
842
+ for (const p of visible) {
843
+ const node = p.node
844
+ if (node.status === 'provisional') {
845
+ context.strokeStyle = nodeColor(node); context.lineWidth = 1.2; context.setLineDash([3, 3])
846
+ context.beginPath(); context.ellipse(p.x, p.y, p.r + 5, p.r + 5, 0, 0, TAU); context.stroke()
847
+ context.setLineDash([])
848
+ }
849
+ if (node.locked) {
850
+ context.fillStyle = background; context.globalAlpha = .95
851
+ context.fillRect(p.x - 1.5, p.y - 1.5, 3, 3); context.globalAlpha = 1
852
+ }
853
+ if (node.id === active || node.id === hovered?.id) {
854
+ context.strokeStyle = node.id === active ? accent : nodeColor(node); context.lineWidth = 1.5
855
+ context.beginPath(); context.ellipse(p.x, p.y, p.r + 4, p.r + 4, 0, 0, TAU); context.stroke()
208
856
  }
209
- context.fillStyle = background
210
- context.globalAlpha = .88
211
- context.fillRect(label.box.x - 1, label.box.y, label.box.width + 2, label.box.height)
212
- context.globalAlpha = label.node.id === active ? 1 : .78
857
+ // 工作台搜索命中:与 HTML 的 query 高亮一致,不增加 arc 计数。
858
+ if (queryHighlight && String(node.title || node.id).toLowerCase().includes(queryHighlight)) {
859
+ context.strokeStyle = accent; context.lineWidth = 2
860
+ context.beginPath(); context.ellipse(p.x, p.y, p.r + 4, p.r + 4, 0, 0, TAU); context.stroke()
861
+ }
862
+ }
863
+ }
864
+ context.globalAlpha = 1
865
+ context.strokeStyle = foreground
866
+ if (options.labels && !dots) {
867
+ // 原版标签逻辑:按缩放决定铺多少、缩得越小字越淡、拖动/平移时只画焦点,
868
+ // 冲突时下移一行、仍冲突就跳过;文字用背景色描边当 halo。
869
+ context.font = '11.5px -apple-system,"PingFang SC","Microsoft YaHei",sans-serif'
870
+ const inView = visible.filter(p => p.x > -60 && p.x < width + 60 && p.y > -60 && p.y < height + 60)
871
+ const showAll = (camera.k >= .55 || visible.length < 34) && inView.length <= 260
872
+ const minDeg = inView.length > 260 ? 9999 : 3
873
+ const zoomFade = clamp((camera.k - .3) / .35, 0, 1)
874
+ const panning = gesture?.type === 'pan' && gesture.moved
875
+ const draggingNode = gesture?.type === 'node' && gesture.moved
876
+ const interactive = (draggingNode || panning) && layout.nodes.length > 400
877
+ const candidates = interactive
878
+ ? inView.filter(p => p.node.id === active)
879
+ : showAll ? inView : inView.filter(p => p.node.id === active || p.node.degree >= minDeg)
880
+ const ordered = candidates.length > 260 ? candidates.slice(0, 260) : candidates
881
+ ordered.sort((a, b) => Number(b.node.id === active) - Number(a.node.id === active) || b.node.degree - a.node.degree)
882
+ const placed = []
883
+ context.textAlign = 'center'; context.textBaseline = 'top'
884
+ for (const p of ordered) {
885
+ if (active && !neighbors.has(p.node.id)) continue
886
+ const must = p.node.id === active
887
+ if (!must) {
888
+ if (!showAll && p.node.degree < minDeg) continue
889
+ if (zoomFade < .02) continue
890
+ }
891
+ const label = String(p.node.title || p.node.id)
892
+ const w = context.measureText(label).width
893
+ const boxOf = yy => ({ l: p.x - w / 2 - 3, t: yy - 1, r: p.x + w / 2 + 3, b: yy + 14 })
894
+ const clash = r => placed.some(q => r.l < q.r && r.r > q.l && r.t < q.b && r.b > q.t)
895
+ let yy = p.y + p.r + 4
896
+ let box = boxOf(yy)
897
+ if (clash(box)) { yy += 16; box = boxOf(yy); if (clash(box)) continue }
898
+ if (box.l < 2 || box.r > width - 2 || box.b > height - 2) continue
899
+ placed.push(box)
900
+ context.globalAlpha = must ? 1 : .78 * Math.max(.35, zoomFade)
901
+ context.lineWidth = 3.5; context.strokeStyle = background; context.lineJoin = 'round'
902
+ context.strokeText(label, p.x, yy)
213
903
  context.fillStyle = foreground
214
- context.fillText(label.text, label.box.x + 2, label.box.y + 1)
904
+ context.fillText(label, p.x, yy)
215
905
  }
216
906
  context.globalAlpha = 1
907
+ } else if (options.labels && dots && active) {
908
+ const focus = layout.nodes.find(node => node.id === active)
909
+ if (focus) {
910
+ context.font = '12px system-ui, sans-serif'; context.textAlign = 'center'; context.textBaseline = 'top'
911
+ context.fillStyle = foreground
912
+ context.fillText(String(focus.title || focus.id), focus.x * k + ox, focus.y * k + oy + 10)
913
+ }
217
914
  }
218
915
  if (!layout.nodes.length && emptyLabel) {
219
916
  context.font = '13px system-ui, sans-serif'; context.textAlign = 'center'; context.textBaseline = 'middle'
@@ -224,13 +921,17 @@ export function createGraphView(canvas, { onFocus = () => {}, onZoom = () => {},
224
921
  const animate = time => {
225
922
  frame = null
226
923
  if (disposed) return
227
- if (options.motion && !reducedMotion && layout.simulation.alpha() > layout.simulation.alphaMin()) {
924
+ const stepping = options.motion && !reducedMotion && layout.active
925
+ if (stepping) {
228
926
  accumulator += lastTime ? Math.min(64, time - lastTime) : 17
229
- for (; accumulator >= 1000 / 60; accumulator -= 1000 / 60) layout.simulation.tick()
927
+ let steps = 0
928
+ for (; accumulator >= 1000 / 60 && steps < 4; accumulator -= 1000 / 60, steps++) layout.tick()
230
929
  lastTime = time
231
- requestDraw()
232
930
  } else { lastTime = 0; accumulator = 0 }
931
+ // 空闲降到 ~30fps:只重绘不改坐标(呼吸在 drawGrid 里)。
932
+ if (!stepping && options.motion && !reducedMotion && (idleFrame++ % 2)) { requestDraw(); return }
233
933
  draw()
934
+ if (stepping || (options.motion && !reducedMotion)) requestDraw()
234
935
  }
235
936
  function requestDraw() {
236
937
  if (!disposed && frame === null) frame = win.requestAnimationFrame(animate)
@@ -247,14 +948,8 @@ export function createGraphView(canvas, { onFocus = () => {}, onZoom = () => {},
247
948
  canvas.width = Math.round(width * ratio); canvas.height = Math.round(height * ratio)
248
949
  requestDraw()
249
950
  }
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
951
  const startPinch = () => {
257
- releaseNode()
952
+ restoreGesture(gesture)
258
953
  const [a, b] = [...pointers.values()]
259
954
  gesture = { type: 'pinch', distance: Math.max(1, Math.hypot(b.x - a.x, b.y - a.y)), camera: { ...camera },
260
955
  center: { x: (a.x + b.x) / 2, y: (a.y + b.y) / 2 }, moved: true }
@@ -268,9 +963,19 @@ export function createGraphView(canvas, { onFocus = () => {}, onZoom = () => {},
268
963
  canvas.setPointerCapture?.(event.pointerId)
269
964
  if (pointers.size >= 2) { startPinch(); hideTooltip(); return }
270
965
  const node = hit(p)
271
- gesture = { type: node ? 'node' : 'pan', node, start: p, camera: { ...camera }, moved: false,
272
- offset: node ? { x: node.x - world(p).x, y: node.y - world(p).y } : null }
273
- if (node) { node.fx = node.x; node.fy = node.y; node.vx = 0; node.vy = 0 }
966
+ const w = world(p)
967
+ const component = node ? layout.componentOf(node.id) : null
968
+ const mode = node && event.shiftKey && component ? 'rigid' : 'node'
969
+ const members = mode === 'rigid' ? component.members : (node ? [node] : [])
970
+ gesture = { type: node ? 'node' : 'pan', node, mode, members, start: p, camera: { ...camera }, moved: false,
971
+ offset: node ? { x: node.x - w.x, y: node.y - w.y } : null,
972
+ snapshot: members.map(m => ({ id: m.id, x: m.x, y: m.y, fx: m.fx, fy: m.fy, locked: m.locked })) }
973
+ if (node) {
974
+ // 拖动期间只临时钉住,不算"锁定";锁定只由右键产生。
975
+ for (const m of members) layout.hold(m.id, m.x, m.y)
976
+ layout.startDragScope(node.id)
977
+ layout.setDragging(true)
978
+ }
274
979
  hideTooltip()
275
980
  canvas.style.cursor = 'grabbing'
276
981
  }
@@ -290,9 +995,14 @@ export function createGraphView(canvas, { onFocus = () => {}, onZoom = () => {},
290
995
  if (!gesture.moved) return
291
996
  if (gesture.node) {
292
997
  const w = world(p), node = gesture.node
293
- node.x = node.fx = w.x + gesture.offset.x; node.y = node.fy = w.y + gesture.offset.y
294
- node.vx = 0; node.vy = 0
295
- layout.simulation.alpha(Math.max(.08, layout.simulation.alpha()))
998
+ if (gesture.mode === 'rigid') {
999
+ const nx = w.x + gesture.offset.x, ny = w.y + gesture.offset.y
1000
+ const dx = nx - node.fx, dy = ny - node.fy
1001
+ for (const m of gesture.members) layout.hold(m.id, m.fx + dx, m.fy + dy)
1002
+ } else layout.hold(node.id, w.x + gesture.offset.x, w.y + gesture.offset.y)
1003
+ // 每次指针移动都同步推进两帧:邻居像珠子链一样立刻跟过来,
1004
+ // 不会等 rAF(小图缩放时 rAF 一帧的位移远小于指针)。
1005
+ layout.settle(2)
296
1006
  } else {
297
1007
  camera.x = gesture.camera.x + p.x - gesture.start.x; camera.y = gesture.camera.y + p.y - gesture.start.y
298
1008
  }
@@ -303,11 +1013,30 @@ export function createGraphView(canvas, { onFocus = () => {}, onZoom = () => {},
303
1013
  if (!pointers.has(event.pointerId)) return
304
1014
  const cancelled = event.type !== 'pointerup'
305
1015
  const selected = gesture?.node
306
- const click = !cancelled && !gesture?.moved && gesture?.type !== 'pinch'
307
- releaseNode()
1016
+ const click = !cancelled && !gesture?.moved && gesture?.type !== 'pinch' && (event.detail ?? 1) < 2
1017
+ if (click || cancelled) {
1018
+ // 单击不留下临时 pin;取消/Esc 恢复按下前的摆位。
1019
+ restoreGesture(gesture)
1020
+ } else if (selected) {
1021
+ // 松手:原本锁定的节点把锁定点更新到落点;自由节点则 release —— 留在原地
1022
+ // 但不再固定,后续拖别的节点能带动它,右键一次即可(它本来就没被锁)。
1023
+ for (const saved of gesture.snapshot) {
1024
+ const state = layout.nodeById(saved.id)
1025
+ if (!state) continue
1026
+ if (saved.locked || saved.fx != null) {
1027
+ state.fx = state.x; state.fy = state.y; state.locked = true
1028
+ state.vx = 0; state.vy = 0
1029
+ } else {
1030
+ layout.release(saved.id)
1031
+ }
1032
+ }
1033
+ layout.setDragging(false)
1034
+ // 多收敛几帧,让「松手落点」也被安全间距推开,不会停在别的节点身上。
1035
+ if (reducedMotion || !options.motion) { layout.settle(120); layout.clearDragScope() }
1036
+ else layout.reheat(.3)
1037
+ }
308
1038
  pointers.delete(event.pointerId)
309
1039
  gesture = null
310
- // A remaining finger may pan, but must never turn a pinch into a node click.
311
1040
  if (pointers.size) {
312
1041
  const p = [...pointers.values()][0]
313
1042
  gesture = { type: 'pan', start: p, camera: { ...camera }, moved: true }
@@ -324,13 +1053,30 @@ export function createGraphView(canvas, { onFocus = () => {}, onZoom = () => {},
324
1053
  listen(canvas, 'pointermove', move)
325
1054
  for (const type of ['pointerup', 'pointercancel', 'lostpointercapture']) listen(canvas, type, up)
326
1055
  listen(canvas, 'pointerleave', () => { if (!gesture) { hovered = null; hideTooltip(); requestDraw() } })
1056
+ // 右键 = 锁定 / 解除:左键只负责显示单链与拖动,不再产生固定点。
1057
+ listen(canvas, 'contextmenu', event => {
1058
+ event.preventDefault()
1059
+ const node = hit(point(event))
1060
+ if (!node) return
1061
+ const state = layout.nodeById(node.id)
1062
+ if (!state) return
1063
+ // 有任何固定点(含拖动残留)就先解开,再点一次才锁定 —— 不会出现要点两次。
1064
+ if (state.fx != null) layout.unpin(node.id)
1065
+ else layout.pin(node.id, state.x, state.y)
1066
+ layout.setDragging(false)
1067
+ if (reducedMotion || !options.motion) layout.settle(20)
1068
+ requestDraw()
1069
+ })
1070
+ // 双击聚焦:第二次 pointerup 的 detail>=2 已在 up 里跳过,避免重复取数。
1071
+ listen(canvas, 'dblclick', event => { onFocus(hit(point(event))?.id || '') })
327
1072
  listen(canvas, 'wheel', event => { event.preventDefault(); zoom(Math.exp(-clamp(event.deltaY, -160, 160) * .0025), point(event)) }, { passive: false })
328
1073
  listen(canvas, 'keydown', event => {
329
1074
  if (event.key === '+' || event.key === '=') zoom(1.25)
330
1075
  else if (event.key === '-') zoom(.8)
331
1076
  else if (event.key === '0' || event.key === 'Home') fit()
332
- else if (event.key === 'Escape') { releaseNode(); gesture = null; pointers.clear(); onFocus(''); hideTooltip(); requestDraw() }
333
- else if (['ArrowLeft', 'ArrowRight', 'ArrowUp', 'ArrowDown'].includes(event.key)) {
1077
+ else if (event.key === 'Escape') {
1078
+ restoreGesture(gesture); gesture = null; pointers.clear(); onFocus(''); hideTooltip(); requestDraw()
1079
+ } else if (['ArrowLeft', 'ArrowRight', 'ArrowUp', 'ArrowDown'].includes(event.key)) {
334
1080
  const step = event.shiftKey ? 90 : 30
335
1081
  camera.x += event.key === 'ArrowLeft' ? step : event.key === 'ArrowRight' ? -step : 0
336
1082
  camera.y += event.key === 'ArrowUp' ? step : event.key === 'ArrowDown' ? -step : 0
@@ -338,7 +1084,9 @@ export function createGraphView(canvas, { onFocus = () => {}, onZoom = () => {},
338
1084
  } else return
339
1085
  event.preventDefault()
340
1086
  })
341
- listen(win, 'blur', () => { releaseNode(); gesture = null; pointers.clear(); hovered = null; hideTooltip(); requestDraw() })
1087
+ listen(win, 'blur', () => {
1088
+ restoreGesture(gesture); gesture = null; pointers.clear(); hovered = null; hideTooltip(); requestDraw()
1089
+ })
342
1090
  const observer = win.ResizeObserver ? new win.ResizeObserver(resize) : null
343
1091
  observer?.observe(canvas)
344
1092
  listen(win, 'resize', resize)
@@ -348,31 +1096,50 @@ export function createGraphView(canvas, { onFocus = () => {}, onZoom = () => {},
348
1096
  resize()
349
1097
  return {
350
1098
  update(graph, focus = '') {
351
- // A response may arrive mid-drag. End only gestures whose node disappeared.
352
1099
  if (gesture?.node && !graph.nodes.some(node => node.id === gesture.node.id)) {
353
- releaseNode(); gesture = null; pointers.clear()
1100
+ restoreGesture(gesture); gesture = null; pointers.clear()
354
1101
  }
355
1102
  const changed = layout.update(graph)
356
1103
  focused = focus
357
1104
  if (hovered && !layout.nodes.includes(hovered)) { hovered = null; hideTooltip() }
358
1105
  if (!initialized && layout.nodes.length) {
359
1106
  layout.settle(220); initialized = true; fit()
360
- } else if (changed && reducedMotion) layout.settle(180)
1107
+ } else if (changed && (reducedMotion || !options.motion)) layout.settle(180)
361
1108
  requestDraw()
362
1109
  },
363
1110
  configure(next) {
364
- const forcesChanged = next.repulsion !== undefined && next.repulsion !== options.repulsion ||
365
- next.distance !== undefined && next.distance !== options.distance
1111
+ const forceChanged = ['repulsion', 'distance', 'center'].some(key => next[key] !== undefined && next[key] !== options[key])
366
1112
  options = { ...options, ...next }
367
- if (forcesChanged) {
368
- layout.configure(options)
369
- if (reducedMotion) layout.settle(180)
1113
+ if (forceChanged) {
1114
+ layout.configure(next)
1115
+ if (reducedMotion || !options.motion) layout.settle(160)
370
1116
  }
371
1117
  requestDraw()
372
1118
  },
373
1119
  fit, zoom,
1120
+ isPinned(id) { return layout.nodeById(id)?.locked === true },
1121
+ pinnedCount() { return layout.nodes.reduce((count, node) => count + (node.locked ? 1 : 0), 0) },
1122
+ // 只读快照(屏幕坐标 + id):验收按 id 追节点,不依赖绘制顺序。
1123
+ snapshot() {
1124
+ return layout.nodes.map(node => ({
1125
+ id: node.id, x: node.x * camera.k + camera.x, y: node.y * camera.k + camera.y,
1126
+ r: radius(node), pinned: node.locked === true, degree: node.degree || 0,
1127
+ }))
1128
+ },
1129
+ unpinAll() {
1130
+ layout.unpinAll(); layout.clearDragScope()
1131
+ if (reducedMotion || !options.motion) layout.settle(120)
1132
+ requestDraw()
1133
+ },
1134
+ relayout() {
1135
+ restoreGesture(gesture); gesture = null; pointers.clear()
1136
+ layout.relayout()
1137
+ if (reducedMotion || !options.motion) layout.settle(220)
1138
+ requestDraw()
1139
+ },
374
1140
  dispose() {
375
- disposed = true; releaseNode()
1141
+ disposed = true
1142
+ restoreGesture(gesture); gesture = null; pointers.clear()
376
1143
  if (frame !== null) win.cancelAnimationFrame(frame)
377
1144
  for (const remove of cleanup) remove()
378
1145
  observer?.disconnect(); themeObserver?.disconnect(); layout.dispose(); hideTooltip()