dsh-memu-memory 1.4.4 → 1.4.5

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 (180) hide show
  1. package/AGENTS.md +3 -1
  2. package/CHANGELOG.md +11 -0
  3. package/README.md +33 -14
  4. package/README.zh.md +34 -12
  5. package/assets/screenshots/drawer.jpg +0 -0
  6. package/assets/screenshots/libraries.jpg +0 -0
  7. package/assets/screenshots/mobile.jpg +0 -0
  8. package/assets/screenshots/relations.jpg +0 -0
  9. package/assets/screenshots/settings.jpg +0 -0
  10. package/assets/screenshots/webui-dark.jpg +0 -0
  11. package/assets/screenshots/webui-memory.jpg +0 -0
  12. package/docs/client-conventions.md +19 -3
  13. package/docs/contributing.md +4 -2
  14. package/docs/env-and-commands.md +9 -1
  15. package/docs/graph-scale.md +214 -0
  16. package/docs/lexicon-recall.md +100 -0
  17. package/docs/mcp-porting.md +8 -6
  18. package/docs/memory-semantics.md +35 -3
  19. package/docs/pending-work.md +3 -1
  20. package/docs/retention.md +83 -0
  21. package/docs/rt-index.md +452 -0
  22. package/docs/scale-performance.md +101 -0
  23. package/docs/token-budget.md +92 -0
  24. package/docs/troubleshooting.md +50 -11
  25. package/lib/auto-link/apply.js +7 -2
  26. package/lib/auto-link/candidates.js +32 -10
  27. package/lib/backup.js +67 -32
  28. package/lib/binding-diagnostics.js +1 -1
  29. package/lib/bounded-cache.js +80 -0
  30. package/lib/client.js +2096 -409
  31. package/lib/consolidation-ledger.js +21 -4
  32. package/lib/consolidation-worker.js +14 -1
  33. package/lib/cycle.js +16 -11
  34. package/lib/diagnostic-context.js +372 -0
  35. package/lib/diagnostics.js +147 -61
  36. package/lib/embedding-download.js +7 -8
  37. package/lib/engine-sources.js +286 -0
  38. package/lib/engine.js +23 -10
  39. package/lib/entity-repair.js +43 -13
  40. package/lib/entity-review.js +64 -0
  41. package/lib/environment-check.js +348 -36
  42. package/lib/feedback.js +25 -0
  43. package/lib/global-graph.js +46 -2
  44. package/lib/graph-adjacency-index.js +525 -0
  45. package/lib/graph-overview.js +293 -0
  46. package/lib/graph.js +658 -105
  47. package/lib/inbound.js +44 -15
  48. package/lib/index-pages.js +57 -0
  49. package/lib/index.js +44 -6
  50. package/lib/inject.js +119 -50
  51. package/lib/lexicon-rt-source.js +25 -0
  52. package/lib/lexicon-rt-worker.js +26 -0
  53. package/lib/lexicon-rt.js +224 -0
  54. package/lib/lexicon-scope.js +56 -5
  55. package/lib/lexicon.js +143 -54
  56. package/lib/local-vector-service.js +3 -0
  57. package/lib/maintenance-ledger.js +542 -12
  58. package/lib/managed-runtime.js +260 -80
  59. package/lib/media.js +1 -1
  60. package/lib/memory.js +564 -131
  61. package/lib/port-surface.js +96 -11
  62. package/lib/private.js +47 -21
  63. package/lib/recall-cache.js +20 -34
  64. package/lib/retention.js +173 -0
  65. package/lib/rpc.js +135 -52
  66. package/lib/rt-index/builder.js +209 -0
  67. package/lib/rt-index/format.js +231 -0
  68. package/lib/rt-index/manifest.js +105 -0
  69. package/lib/rt-index/reader.js +673 -0
  70. package/lib/rt-index-retention.js +151 -0
  71. package/lib/rt-index-service.js +283 -0
  72. package/lib/rt-index-worker.js +21 -0
  73. package/lib/salient-wake.js +55 -4
  74. package/lib/state.js +195 -24
  75. package/lib/temporal.js +39 -13
  76. package/lib/token-measurement.js +126 -0
  77. package/lib/tools.js +101 -6
  78. package/lib/turn-log.js +108 -3
  79. package/lib/webui/graph-layout-worker.js +68 -0
  80. package/lib/webui/graph-local-physics.js +390 -0
  81. package/lib/webui/graph-spatial-grid.js +64 -0
  82. package/lib/webui/graph-view.bundle.js +6 -1
  83. package/lib/webui/graph-view.js +478 -135
  84. package/lib/webui/graph-webgl-renderer.js +74 -0
  85. package/lib/webui/standalone.js +1 -1
  86. package/lib/worker-pool.js +30 -4
  87. package/package.json +3 -2
  88. package/scripts/acceptance-local.mjs +4 -10
  89. package/scripts/bench-all-libraries.mjs +47 -0
  90. package/scripts/check-classic-graph-browser.mjs +189 -0
  91. package/scripts/check-client-browser.mjs +929 -0
  92. package/scripts/check-graph-browser.mjs +6 -0
  93. package/scripts/check-graph-elastic-browser.mjs +139 -0
  94. package/scripts/check-memory-review-browser.mjs +124 -0
  95. package/scripts/entity-dedupe.mjs +19 -3
  96. package/scripts/graph-artifact-provenance.mjs +30 -0
  97. package/scripts/graph-freeze-manifest.mjs +129 -0
  98. package/scripts/graph-geometry-fixture.mjs +40 -0
  99. package/scripts/graph-physics-bench.mjs +218 -0
  100. package/scripts/graph-scale-bench.mjs +213 -0
  101. package/scripts/graph-scale-memory.mjs +48 -0
  102. package/scripts/graph-service-bench.mjs +72 -0
  103. package/scripts/make-readme-shots.mjs +17 -5
  104. package/scripts/preview.mjs +1 -0
  105. package/scripts/rebuild-rt.mjs +18 -0
  106. package/scripts/scale-bench.mjs +183 -0
  107. package/scripts/simulate-injection.mjs +47 -8
  108. package/scripts/verify-host-fixtures.mjs +108 -0
  109. package/scripts/verify-host-recovery.mjs +565 -0
  110. package/scripts/verify-vector-recovery.mjs +740 -0
  111. package/tests/auto-link-candidates.test.mjs +20 -0
  112. package/tests/browser.test.mjs +16 -2
  113. package/tests/client-export.test.mjs +16 -1
  114. package/tests/client-pagination.test.mjs +1495 -0
  115. package/tests/client-render.test.mjs +223 -28
  116. package/tests/consolidation-fork.test.mjs +93 -10
  117. package/tests/consolidation-ledger.test.mjs +17 -1
  118. package/tests/diagnostic-entity-candidates.test.mjs +54 -0
  119. package/tests/diagnostic-report.test.mjs +429 -0
  120. package/tests/diagnostic-wiring.test.mjs +88 -0
  121. package/tests/diagnostics.test.mjs +27 -0
  122. package/tests/embedding-download.test.mjs +44 -0
  123. package/tests/engine-source-settings.test.mjs +69 -0
  124. package/tests/engine-sources.test.mjs +145 -0
  125. package/tests/entity-dedupe.test.mjs +143 -0
  126. package/tests/entity-merge-review.test.mjs +363 -0
  127. package/tests/entity-merge.test.mjs +12 -4
  128. package/tests/entity-review.test.mjs +87 -0
  129. package/tests/environment-check.test.mjs +51 -1
  130. package/tests/feedback.test.mjs +95 -0
  131. package/tests/graph-adjacency-index.test.mjs +536 -0
  132. package/tests/graph-cascade.test.mjs +229 -0
  133. package/tests/graph-import-diagnostic.test.mjs +25 -0
  134. package/tests/graph-overview.test.mjs +709 -0
  135. package/tests/graph-session-authorization.test.mjs +419 -0
  136. package/tests/graph-view-geometry.test.mjs +426 -0
  137. package/tests/graph-view-scale.test.mjs +88 -0
  138. package/tests/graph-view.test.mjs +444 -5
  139. package/tests/graph.test.mjs +43 -0
  140. package/tests/help-page.test.mjs +128 -54
  141. package/tests/inbound.test.mjs +19 -0
  142. package/tests/index-pagination.test.mjs +113 -0
  143. package/tests/index-read-view.test.mjs +212 -0
  144. package/tests/inject-guide.test.mjs +9 -0
  145. package/tests/injection-dedupe.test.mjs +213 -0
  146. package/tests/lexicon-recall.test.mjs +641 -0
  147. package/tests/lexicon-rt-lifecycle.test.mjs +196 -0
  148. package/tests/lexicon-rt.test.mjs +468 -0
  149. package/tests/local-embedding-worker.test.mjs +38 -0
  150. package/tests/local-vector-service.test.mjs +32 -3
  151. package/tests/maintenance-compat.test.mjs +128 -0
  152. package/tests/maintenance-settlement.test.mjs +1003 -0
  153. package/tests/managed-memory.test.mjs +39 -11
  154. package/tests/managed-runtime.test.mjs +109 -0
  155. package/tests/memory-fields.test.mjs +24 -12
  156. package/tests/observed-evidence.test.mjs +52 -0
  157. package/tests/port-surface.test.mjs +93 -1
  158. package/tests/recall-cache.test.mjs +56 -3
  159. package/tests/recall-dedup.test.mjs +63 -2
  160. package/tests/retention.test.mjs +260 -0
  161. package/tests/rt-index-cross-library.test.mjs +230 -0
  162. package/tests/rt-index-integration.test.mjs +194 -0
  163. package/tests/rt-index-retention.test.mjs +552 -0
  164. package/tests/rt-index-scale.test.mjs +204 -0
  165. package/tests/rt-index.test.mjs +705 -0
  166. package/tests/salient-date-boundaries.test.mjs +121 -0
  167. package/tests/salient-wake.test.mjs +29 -0
  168. package/tests/scale-bench.test.mjs +53 -0
  169. package/tests/settings-plumbing.test.mjs +25 -0
  170. package/tests/simulate-injection.test.mjs +15 -1
  171. package/tests/standalone-navigation.test.mjs +44 -0
  172. package/tests/state.test.mjs +51 -0
  173. package/tests/temporal-precision.test.mjs +102 -0
  174. package/tests/temporal.test.mjs +10 -6
  175. package/tests/token-measurement.test.mjs +98 -0
  176. package/tests/tool-schema.test.mjs +41 -5
  177. package/tests/tools.test.mjs +6 -3
  178. package/tests/turn-token-budget.test.mjs +149 -0
  179. package/tests/webui-auth.test.mjs +57 -1
  180. package/tests/webui.test.mjs +40 -15
@@ -3,10 +3,15 @@
3
3
  // 物理:空间网格近程斥力 + 连线弹簧 + 可选向心力;fx/fy 非空 = 固定点(pin)。
4
4
  // 拖动时只模拟「被拖节点的连通簇」,其他簇冻结但作为斥力障碍,避免重合。
5
5
 
6
+ import { createSpatialGrid } from './graph-spatial-grid.js'
7
+ import { prelayoutGraph, createLayoutWorker } from './graph-layout-worker.js'
8
+ import { createWebGLRenderer } from './graph-webgl-renderer.js'
9
+ import { createLocalPhysics } from './graph-local-physics.js'
10
+
6
11
  const TAU = Math.PI * 2
7
12
  const GOLDEN_ANGLE = 2.399963229728653
8
13
  const CACHE_LIMIT = 800
9
- const PHYSICS_KEYS = new Set(['x', 'y', 'vx', 'vy', 'fx', 'fy'])
14
+ const PHYSICS_KEYS = new Set(['x', 'y', 'vx', 'vy', 'fx', 'fy', 'locked', 'anchored'])
10
15
  const clamp = (value, min, max) => Math.max(min, Math.min(max, value))
11
16
 
12
17
  export const DEFAULT_OPTIONS = Object.freeze({
@@ -17,6 +22,7 @@ export const DEFAULT_OPTIONS = Object.freeze({
17
22
  motion: true,
18
23
  grid: true, // 画布背景网格点(Graph Studio 侧栏开关)
19
24
  clusterScope: true, // 拖动只模拟连通簇,UI 不暴露
25
+ workerThreshold: 500,
20
26
  })
21
27
 
22
28
  const SIM = Object.freeze({
@@ -49,12 +55,15 @@ const hashId = value => {
49
55
  for (let i = 0; i < text.length; i++) { hash ^= text.charCodeAt(i); hash = Math.imul(hash, 16777619) }
50
56
  return hash >>> 0
51
57
  }
52
- const cellKey = (x, y) => `${Math.floor(x / SIM.cell)},${Math.floor(y / SIM.cell)}`
53
58
 
54
59
  // ---- 纯布局:不碰 DOM,供单测直接驱动 ------------------------------------
55
60
  export function createForceLayout(initialOptions = {}) {
56
61
  const cache = new Map()
57
62
  const edgeLengths = new Map()
63
+ const grid = createSpatialGrid(SIM.cell)
64
+ const local = createLocalPhysics()
65
+ const fixedPositions = new Map()
66
+ let positionScope = null, fixedPositionEvictions = 0
58
67
  let nodes = [], edges = [], adjacency = new Map(), components = null
59
68
  let signature = '', alpha = 1, options = { ...DEFAULT_OPTIONS, ...initialOptions }
60
69
  let dragComp = null, dragging = false, settling = false
@@ -111,11 +120,7 @@ export function createForceLayout(initialOptions = {}) {
111
120
  const ids = comp ? [...comp.ids] : [node.id]
112
121
  for (const id of ids) seen.add(id)
113
122
  const adj = new Map(ids.map(id => [id, []]))
114
- for (const edge of edges) {
115
- if (!adj.has(edge.from) || !adj.has(edge.to)) continue
116
- adj.get(edge.from).push(edge.to)
117
- adj.get(edge.to).push(edge.from)
118
- }
123
+ for (const id of ids) for (const next of adjacency.get(id) || []) if (adj.has(next)) adj.get(id).push(next)
119
124
  // 根:度数最大;同度时实体优先,再按 id 稳定排序。
120
125
  let root = ids[0], bestScore = -1
121
126
  for (const id of ids) {
@@ -342,7 +347,7 @@ export function createForceLayout(initialOptions = {}) {
342
347
  }
343
348
  if (groups.length <= 12) wrapRim(groups, ring)
344
349
  for (const node of cache.values()) {
345
- node.vx = 0; node.vy = 0; node.fx = null; node.fy = null; node.locked = false
350
+ node.vx = 0; node.vy = 0; node.fx = null; node.fy = null; node.locked = false; node.anchored = false
346
351
  }
347
352
  // 记下每条边的自然长度当弹簧原长,力模拟只做微调。
348
353
  for (const edge of edges) {
@@ -353,8 +358,15 @@ export function createForceLayout(initialOptions = {}) {
353
358
  }
354
359
 
355
360
  const update = graph => {
361
+ const nextScope = graph.positionScope ?? graph.scope ?? 'default'
362
+ if (positionScope !== null && positionScope !== nextScope) {
363
+ local.cancel(); cache.clear(); edgeLengths.clear(); fixedPositions.clear()
364
+ nodes = []; signature = ''; layoutInitialized = false
365
+ }
366
+ positionScope = nextScope
356
367
  const input = [...new Map((graph?.nodes || []).map(node => [node.id, node])).values()]
357
368
  .sort((a, b) => String(a.id).localeCompare(String(b.id)))
369
+ const prepositioned = input.every(node => Number.isFinite(node.x) && Number.isFinite(node.y))
358
370
  const ids = new Set(input.map(node => node.id))
359
371
  const links = (graph?.edges || []).filter(edge => ids.has(edge.from) && ids.has(edge.to) && edge.from !== edge.to)
360
372
  const nextSignature = JSON.stringify([input.map(node => node.id), links.map(edge => [edge.from, edge.to]).sort()])
@@ -368,23 +380,35 @@ export function createForceLayout(initialOptions = {}) {
368
380
  }
369
381
  // 新节点按黄金角螺旋落在邻居质心附近(沿用旧播种逻辑)。
370
382
  const fresh = input.filter(node => !cache.has(node.id))
383
+ const neighborStates = new Map()
384
+ for (const edge of links) {
385
+ for (const [id, other] of [[edge.from, edge.to], [edge.to, edge.from]]) {
386
+ if (!neighborStates.has(id)) neighborStates.set(id, [])
387
+ neighborStates.get(id).push(other)
388
+ }
389
+ }
371
390
  for (let i = 0; i < fresh.length; i++) {
372
391
  const node = fresh[i]
373
- const neighbors = links.filter(edge => edge.from === node.id || edge.to === node.id)
374
- .map(edge => cache.get(edge.from === node.id ? edge.to : edge.from)).filter(Boolean)
392
+ const neighbors = input.length >= options.workerThreshold ? [] : (neighborStates.get(node.id) || []).map(id => cache.get(id)).filter(Boolean)
375
393
  const angle = i * GOLDEN_ANGLE
376
394
  const radius = neighbors.length ? 32 : 24 * Math.sqrt(i + .5)
377
395
  const x = neighbors.length ? neighbors.reduce((sum, n) => sum + n.x, 0) / neighbors.length : 0
378
396
  const y = neighbors.length ? neighbors.reduce((sum, n) => sum + n.y, 0) / neighbors.length : 0
379
- cache.set(node.id, { id: node.id, x: x + Math.cos(angle) * radius, y: y + Math.sin(angle) * radius,
380
- vx: 0, vy: 0, fx: null, fy: null, locked: false })
397
+ const cols = Math.ceil(Math.sqrt(input.length))
398
+ const large = input.length >= options.workerThreshold
399
+ const saved = fixedPositions.get(node.id)
400
+ cache.set(node.id, { id: node.id,
401
+ x: Number.isFinite(node.x) ? node.x : large ? i % cols * 28 : x + Math.cos(angle) * radius,
402
+ y: Number.isFinite(node.y) ? node.y : large ? Math.floor(i / cols) * 28 : y + Math.sin(angle) * radius,
403
+ vx: 0, vy: 0, fx: null, fy: null, locked: false, anchored: false, ...saved })
381
404
  }
382
405
  // 只合并数据字段,物理字段(含 pin)永远以缓存为准:心跳刷新不会冲掉摆位。
383
406
  nodes = input.map(data => {
384
407
  const state = cache.get(data.id)
385
408
  for (const [key, value] of Object.entries(data)) if (!PHYSICS_KEYS.has(key)) state[key] = value
386
409
  state.degree = degree.get(data.id) || 0
387
- state.radius = 4 + Math.min(3, Math.log2(1 + state.degree)) + clamp(Number(data.strength) || 0, 0, 1) * 2
410
+ state.radius = data.kind === 'cluster' ? 10 + Math.min(14, Math.log2(1 + Number(data.count || 1)) * 1.4)
411
+ : 4 + Math.min(3, Math.log2(1 + state.degree)) + clamp(Number(data.strength) || 0, 0, 1) * 2
388
412
  return state
389
413
  })
390
414
  edges = links.map(edge => {
@@ -392,7 +416,10 @@ export function createForceLayout(initialOptions = {}) {
392
416
  const key = JSON.stringify([edge.from, edge.to, edge.kind || ''])
393
417
  let baseLen = edgeLengths.get(key)
394
418
  // 首次见到该边时按当时两端距离记录;自定义摆位后不重算。
395
- if (baseLen === undefined) { baseLen = baseLenOf(source, target); edgeLengths.set(key, baseLen) }
419
+ if (baseLen === undefined) {
420
+ baseLen = prepositioned ? Math.max(24, Math.hypot(source.x - target.x, source.y - target.y)) : baseLenOf(source, target)
421
+ edgeLengths.set(key, baseLen)
422
+ }
396
423
  // source/target 必须留给物理引擎当节点引用,原始来源记在 manual 上,
397
424
  // 否则 edge.source === 'auto' 永远为假(所有边都会被画成手动虚线)。
398
425
  return { ...edge, source, target, manual: edge.source !== 'auto', baseLen }
@@ -404,18 +431,35 @@ export function createForceLayout(initialOptions = {}) {
404
431
  const mostlyFresh = nodes.length > 0 && fresh.length >= Math.ceil(nodes.length * .6)
405
432
  && previousCount <= Math.max(8, nodes.length * .2)
406
433
  if (changed && nodes.length && (!layoutInitialized || mostlyFresh)) {
407
- layoutFlower()
434
+ // A heartbeat can arrive while a pointer drag is still live. Re-running
435
+ // the flower layout here clears fx/fy and would make the held node jump
436
+ // back to its seed position. Let the active local/rigid session finish;
437
+ // the next ordinary refresh can reflow if it still needs to.
438
+ const dragInProgress = !!local.session || !!dragComp || dragging
439
+ if (!dragInProgress && (graph.mode === 'classic' || nodes.length < options.workerThreshold) && !prepositioned) layoutFlower()
408
440
  layoutInitialized = true
409
441
  }
410
- if (changed) reheat(signature ? .25 : 1)
442
+ if (changed) {
443
+ if (nodes.length >= options.workerThreshold || input.every(node => Number.isFinite(node.x) && Number.isFinite(node.y))) alpha = SIM.alphaTarget
444
+ else reheat(signature ? .25 : 1)
445
+ }
411
446
  signature = nextSignature
412
- for (const id of cache.keys()) if (cache.size > CACHE_LIMIT && !ids.has(id)) cache.delete(id)
447
+ for (const [id, node] of cache) if (cache.size > CACHE_LIMIT && !ids.has(id)) {
448
+ if (node.fx != null || node.fy != null) {
449
+ fixedPositions.delete(id)
450
+ fixedPositions.set(id, { x: node.x, y: node.y, fx: node.fx, fy: node.fy, locked: node.locked, anchored: node.anchored })
451
+ }
452
+ cache.delete(id)
453
+ }
454
+ while (fixedPositions.size > 4096) { fixedPositions.delete(fixedPositions.keys().next().value); fixedPositionEvictions++ }
413
455
  if (edgeLengths.size > 4000) edgeLengths.clear()
456
+ local.update(nodes, edges)
414
457
  return changed
415
458
  }
416
459
 
417
460
  const tick = () => {
418
461
  if (!nodes.length) return
462
+ local.invalidate()
419
463
  alpha += (SIM.alphaTarget - alpha) * SIM.alphaDecay
420
464
  if (alpha < SIM.alphaTarget) alpha = SIM.alphaTarget
421
465
  const F = factors()
@@ -424,19 +468,14 @@ export function createForceLayout(initialOptions = {}) {
424
468
  const active = dragComp ? dragComp.members : nodes
425
469
  const activeIds = dragComp ? dragComp.ids : null
426
470
  // 网格装全节点:冻结簇只当障碍施力、自身不被积分,活动簇因此不会与其重合。
427
- const grid = new Map()
428
- for (const node of nodes) {
429
- const key = cellKey(node.x, node.y)
430
- let list = grid.get(key)
431
- if (!list) grid.set(key, list = [])
432
- list.push(node)
433
- }
471
+ grid.reset()
472
+ for (const node of nodes) grid.insert(node)
434
473
  const range2 = SIM.range * SIM.range
435
474
  const rep = SIM.repel * F.repel * alpha
436
475
  for (const node of active) {
437
476
  const gx = Math.floor(node.x / SIM.cell), gy = Math.floor(node.y / SIM.cell)
438
477
  for (let ox = -1; ox <= 1; ox++) for (let oy = -1; oy <= 1; oy++) {
439
- const list = grid.get(`${gx + ox},${gy + oy}`)
478
+ const list = grid.get(gx + ox, gy + oy)
440
479
  if (!list) continue
441
480
  for (const other of list) {
442
481
  if (other === node) continue
@@ -482,11 +521,11 @@ export function createForceLayout(initialOptions = {}) {
482
521
  // 缩到最小(k≈.06)时等于要求 400 世界像素间距,每帧互相猛推,整图就是打架。
483
522
  // 拖动中只做「别完全重合」的软约束,否则整簇会被锁成刚性块、弹簧拉不动邻居;
484
523
  // 松手后才用完整间距。冻结节点与右键锁定节点不被推。
485
- if (node.fx == null || (!dragging && !node.locked)) {
524
+ if (node.fx == null && node.fy == null) {
486
525
  const own = (Number(node.radius) || 4) + (dragging ? 2 : 8)
487
526
  const gx = Math.floor(node.x / SIM.cell), gy = Math.floor(node.y / SIM.cell)
488
527
  for (let ox = -1; ox <= 1; ox++) for (let oy = -1; oy <= 1; oy++) {
489
- const list = grid.get(`${gx + ox},${gy + oy}`)
528
+ const list = grid.get(gx + ox, gy + oy)
490
529
  if (!list) continue
491
530
  for (const other of list) {
492
531
  if (other === node) continue
@@ -506,8 +545,6 @@ export function createForceLayout(initialOptions = {}) {
506
545
  }
507
546
  }
508
547
  node.vx *= .3; node.vy *= .3
509
- // 固定点被推开后要把锁定坐标一起搬走,否则下一帧又被拉回旧位置。
510
- if (node.fx != null) { node.fx = node.x; node.fy = node.y }
511
548
  }
512
549
  }
513
550
  }
@@ -515,11 +552,24 @@ export function createForceLayout(initialOptions = {}) {
515
552
  return {
516
553
  get nodes() { return nodes },
517
554
  get edges() { return edges },
555
+ edgesFor: id => local.edgesFor(id),
518
556
  get alpha() { return alpha },
519
557
  // 空闲时 alpha 落在地板即停止积分:心跳重绘不会让已收敛的布局漂移。
520
- get active() { return alpha > SIM.alphaTarget + 1e-4 || dragging },
558
+ get active() { return alpha > SIM.alphaTarget + 1e-4 },
521
559
  update,
522
560
  tick,
561
+ beginLocalDrag(id) {
562
+ const session = local.begin(id)
563
+ for (const node of session?.members || []) if (node.fx == null && node.fy == null) fixedPositions.delete(node.id)
564
+ return session
565
+ },
566
+ moveLocalDrag: (x, y) => local.move(x, y),
567
+ stepLocal: () => local.step(options),
568
+ releaseLocalDrag: immediate => local.release(immediate),
569
+ cancelLocalDrag: () => local.cancel(),
570
+ get localSession() { return local.session },
571
+ get localActive() { return local.active },
572
+ localDiagnostics: () => ({ ...local.diagnostics(), fixedPositionCache: fixedPositions.size, fixedPositionEvictions, positionScope }),
523
573
  settle(ticks = 200) {
524
574
  settling = true
525
575
  try { for (let i = 0; i < ticks; i++) tick() } finally { settling = false }
@@ -538,17 +588,35 @@ export function createForceLayout(initialOptions = {}) {
538
588
  reheat(.25)
539
589
  },
540
590
  reheat,
591
+ cool() { alpha = SIM.alphaTarget; dragComp = null; dragging = false },
592
+ applyPositions(positions) {
593
+ if (!(positions instanceof Float64Array) || positions.length !== nodes.length * 2) return false
594
+ if (!positions.every(Number.isFinite)) return false
595
+ nodes.forEach((node, i) => {
596
+ if (node.fx != null || node.fy != null) return
597
+ node.x = positions[i * 2]; node.y = positions[i * 2 + 1]; node.vx = 0; node.vy = 0
598
+ })
599
+ for (const edge of edges) {
600
+ edge.baseLen = Math.max(1, Math.hypot(edge.source.x - edge.target.x, edge.source.y - edge.target.y))
601
+ edgeLengths.set(JSON.stringify([edge.from, edge.to, edge.kind || '']), edge.baseLen)
602
+ }
603
+ alpha = SIM.alphaTarget
604
+ local.invalidate()
605
+ return true
606
+ },
541
607
  // pin = 用户右键锁定(计数、画标记);hold = 拖动落点(留在原地但不计为锁定)。
542
608
  pin(id, x, y) {
543
609
  const state = cache.get(id)
544
610
  if (!state) return
545
611
  state.fx = x; state.fy = y; state.x = x; state.y = y; state.vx = 0; state.vy = 0; state.locked = true
612
+ local.updatePosition(state)
546
613
  reheat(.3)
547
614
  },
548
615
  hold(id, x, y) {
549
616
  const state = cache.get(id)
550
617
  if (!state) return
551
618
  state.fx = x; state.fy = y; state.x = x; state.y = y; state.vx = 0; state.vy = 0
619
+ local.updatePosition(state)
552
620
  reheat(.55)
553
621
  },
554
622
  // 松手:解除临时固定,但把相连边的自然长度改成当前距离 —— 节点留在原地不被
@@ -567,17 +635,21 @@ export function createForceLayout(initialOptions = {}) {
567
635
  unpin(id) {
568
636
  const state = cache.get(id)
569
637
  if (!state) return
570
- state.fx = null; state.fy = null; state.vx = 0; state.vy = 0; state.locked = false
638
+ state.fx = null; state.fy = null; state.vx = 0; state.vy = 0; state.locked = false; state.anchored = false
639
+ fixedPositions.delete(id)
571
640
  reheat(.3)
572
641
  },
573
642
  unpinAll() {
643
+ local.cancel(); fixedPositions.clear()
574
644
  for (const state of cache.values()) {
575
- state.fx = null; state.fy = null; state.vx = 0; state.vy = 0; state.locked = false
645
+ state.fx = null; state.fy = null; state.vx = 0; state.vy = 0; state.locked = false; state.anchored = false
576
646
  }
577
647
  reheat(.35)
578
648
  },
579
649
  relayout() {
650
+ local.cancel(); fixedPositions.clear()
580
651
  layoutFlower()
652
+ local.invalidate()
581
653
  // 重排后按新几何重记弹簧原长,避免旧 baseLen 将节点拉回旧间距并引起振荡。
582
654
  // 与 configure 调整距离时使用相同规则。
583
655
  edgeLengths.clear()
@@ -598,11 +670,11 @@ export function createForceLayout(initialOptions = {}) {
598
670
  setDragging(value) { dragging = value },
599
671
  clearDragScope() { dragComp = null; dragging = false },
600
672
  nodeById: id => cache.get(id),
601
- dispose() { cache.clear(); edgeLengths.clear(); nodes = []; edges = []; components = null; adjacency = new Map() },
673
+ dispose() { local.dispose(); grid.dispose(); cache.clear(); fixedPositions.clear(); edgeLengths.clear(); nodes = []; edges = []; components = null; adjacency = new Map() },
602
674
  }
603
675
  }
604
676
 
605
- export function fitCamera(nodes, width, height) {
677
+ export function fitCamera(nodes, width, height, minZoom = .06) {
606
678
  if (!nodes.length) return { x: width / 2, y: height / 2, k: 1 }
607
679
  let left = Infinity, right = -Infinity, top = Infinity, bottom = -Infinity
608
680
  for (const node of nodes) {
@@ -611,12 +683,12 @@ export function fitCamera(nodes, width, height) {
611
683
  top = Math.min(top, node.y - r); bottom = Math.max(bottom, node.y + r)
612
684
  }
613
685
  const k = clamp(Math.min(Math.max(32, width - 100) / Math.max(120, right - left),
614
- Math.max(32, height - 96) / Math.max(120, bottom - top)), .06, 1.6)
686
+ Math.max(32, height - 96) / Math.max(120, bottom - top)), minZoom, 1.6)
615
687
  return { x: width / 2 - (left + right) * k / 2, y: height / 2 - (top + bottom) * k / 2, k }
616
688
  }
617
689
 
618
- export function zoomCamera(camera, factor, point) {
619
- const k = clamp(camera.k * factor, .06, 5)
690
+ export function zoomCamera(camera, factor, point, minZoom = .06) {
691
+ const k = clamp(camera.k * factor, minZoom, 5)
620
692
  return { k, x: point.x - (point.x - camera.x) * k / camera.k, y: point.y - (point.y - camera.y) * k / camera.k }
621
693
  }
622
694
 
@@ -649,18 +721,39 @@ export function placeLabels(candidates, obstacles, width, height) {
649
721
  }
650
722
 
651
723
  // ---- 画布控制器:相机、渲染、指针与键盘 ------------------------------------
652
- export function createGraphView(canvas, { onFocus = () => {}, onZoom = () => {}, onPaint = () => {}, tooltip,
653
- reducedMotion = false, emptyLabel = '' } = {}) {
724
+ export function createGraphView(canvas, { onFocus = () => {}, onZoom = () => {}, onPaint = () => {}, onViewport = () => {},
725
+ onDiagnostic = () => {}, tooltip, reducedMotion = false, emptyLabel = '' } = {}) {
654
726
  const context = canvas.getContext('2d')
655
727
  if (!context) throw new Error('Canvas 2D is unavailable')
656
728
  const layout = createForceLayout()
657
729
  let width = 1, height = 1, ratio = 1, camera = { x: 0, y: 0, k: 1 }
658
730
  let options = { ...DEFAULT_OPTIONS }, focused = '', hovered = null, gesture = null
659
- let initialized = false, disposed = false, frame = null, lastTime = 0, accumulator = 0
660
- const pointers = new Map(), cleanup = []
731
+ let positionScope = null
732
+ let initialized = false, disposed = false, frame = null, lastTime = 0, accumulator = 0, classicView = false
733
+ const pointers = new Map(), cleanup = [], handledPointerEvents = new WeakSet()
661
734
  const win = canvas.ownerDocument.defaultView
735
+ const hitGrid = createSpatialGrid(SIM.cell)
736
+ let hitDirty = true, workerPending = false, workerUsed = false, workerFallback = null, pendingLayoutGraph = null
737
+ let webgl = null, webglAttempted = false, renderer = 'canvas2d'
738
+ let fixedLargeLayout = false
739
+ let dragCachedFrames = 0, dragCachePeakBytes = 0
740
+ let localLayer = null
741
+ const applyPrelayout = positions => {
742
+ workerPending = false
743
+ pendingLayoutGraph = null
744
+ if (disposed || gesture || !layout.applyPositions(positions)) return
745
+ fixedLargeLayout = layout.nodes.length >= options.workerThreshold
746
+ hitDirty = true; fit()
747
+ }
748
+ const worker = createLayoutWorker(win, { onResult: positions => { workerUsed = true; applyPrelayout(positions) },
749
+ onFallback: reason => {
750
+ workerFallback = reason
751
+ onDiagnostic({ code: 'GRAPH_LAYOUT_FALLBACK', reason })
752
+ if (workerPending && pendingLayoutGraph) applyPrelayout(prelayoutGraph(pendingLayoutGraph))
753
+ } })
662
754
  const world = point => ({ x: (point.x - camera.x) / camera.k, y: (point.y - camera.y) / camera.k })
663
- const radius = node => clamp((Number(node.radius) || 4) * Math.sqrt(camera.k), 2.5, 22)
755
+ const radius = node => node.kind === 'cluster' ? clamp((Number(node.radius) || 10) * Math.sqrt(camera.k), 11 + Math.floor(Math.log10(Math.max(1, node.count || 1))) * 2, 26)
756
+ : clamp((Number(node.radius) || 4) * Math.sqrt(camera.k), 2.5, 22)
664
757
  const point = event => {
665
758
  const rect = canvas.getBoundingClientRect()
666
759
  return { x: (event.clientX - rect.left) * width / rect.width, y: (event.clientY - rect.top) * height / rect.height }
@@ -671,25 +764,21 @@ export function createGraphView(canvas, { onFocus = () => {}, onZoom = () => {},
671
764
  const hit = (p, prefer) => {
672
765
  const nodes = layout.nodes
673
766
  if (!nodes.length) return null
674
- const target = world(p), reach = clamp(Math.ceil(40 / Math.max(camera.k, .06) / SIM.cell), 1, 8)
675
- const gx = Math.floor(target.x / SIM.cell), gy = Math.floor(target.y / SIM.cell), grid = new Map()
676
- for (const node of nodes) {
677
- const key = cellKey(node.x, node.y)
678
- let list = grid.get(key)
679
- if (!list) grid.set(key, list = [])
680
- list.push(node)
681
- }
767
+ const target = world(p), reach = Math.max(1, Math.ceil(40 / camera.k / SIM.cell))
768
+ const gx = Math.floor(target.x / SIM.cell), gy = Math.floor(target.y / SIM.cell)
769
+ if (hitDirty) { hitGrid.reset(); for (const node of nodes) hitGrid.insert(node); hitDirty = false }
682
770
  const near = node => Math.max(6, radius(node) + 4)
683
771
  let closest = null, distance = Infinity, preferDistance = Infinity
684
- for (let ox = -reach; ox <= reach; ox++) for (let oy = -reach; oy <= reach; oy++) {
685
- const list = grid.get(`${gx + ox},${gy + oy}`)
686
- if (!list) continue
687
- for (const node of list) {
688
- const sx = node.x * camera.k + camera.x, sy = node.y * camera.k + camera.y
689
- const d = Math.hypot(sx - p.x, sy - p.y)
690
- if (node === prefer) preferDistance = d
691
- if (d <= near(node) && d < distance) { closest = node; distance = d }
692
- }
772
+ const consider = node => {
773
+ const sx = node.x * camera.k + camera.x, sy = node.y * camera.k + camera.y
774
+ const d = Math.hypot(sx - p.x, sy - p.y)
775
+ if (node === prefer) preferDistance = d
776
+ if (d <= near(node) && d < distance) { closest = node; distance = d }
777
+ }
778
+ // At very small scales a screen target spans too many world-grid cells.
779
+ if (reach > 8) for (const node of nodes) consider(node)
780
+ else for (let ox = -reach; ox <= reach; ox++) for (let oy = -reach; oy <= reach; oy++) {
781
+ for (const node of hitGrid.get(gx + ox, gy + oy) || []) consider(node)
693
782
  }
694
783
  // 磁滞:只有新候选确实更近(≥2px)才换目标。极小缩放下两颗点可能只差 2-3px,
695
784
  // 纯最近邻会随鼠标 1px 抖动来回换人 —— 高亮反复切换就是「打架闪现」。
@@ -703,16 +792,18 @@ export function createGraphView(canvas, { onFocus = () => {}, onZoom = () => {},
703
792
  if (!tooltip) return
704
793
  tooltip.hidden = !node || !!gesture
705
794
  if (!node || gesture) return
706
- tooltip.textContent = String(node.title || node.id)
795
+ tooltip.textContent = node.kind === 'cluster' ? `${node.title || node.id} (${node.count})` : String(node.title || node.id)
707
796
  tooltip.style.left = `${clamp(p.x + 14, 6, Math.max(6, width - Math.min(260, width - 12)))}px`
708
797
  tooltip.style.top = `${(canvas.offsetTop || 0) + clamp(p.y + 16, 6, height - 60)}px`
709
798
  }
710
799
  const restoreGesture = current => {
711
800
  if (!current?.snapshot) return
801
+ if (current.localPhysics) layout.cancelLocalDrag()
802
+ hitDirty = true
712
803
  for (const saved of current.snapshot) {
713
804
  const state = layout.nodeById(saved.id)
714
805
  if (!state) continue
715
- state.fx = saved.fx; state.fy = saved.fy; state.locked = saved.locked === true
806
+ state.fx = saved.fx; state.fy = saved.fy; state.locked = saved.locked === true; state.anchored = saved.anchored === true
716
807
  state.x = saved.x; state.y = saved.y; state.vx = 0; state.vy = 0
717
808
  }
718
809
  layout.clearDragScope()
@@ -727,6 +818,78 @@ export function createGraphView(canvas, { onFocus = () => {}, onZoom = () => {},
727
818
  for (let x = ox; x < width; x += step) for (let y = oy; y < height; y += step) context.rect(x, y, 1.2, 1.2)
728
819
  context.fill()
729
820
  }
821
+ const invalidateDragLayer = () => { localLayer = null }
822
+ const drawDraggedNode = (node, foreground, background, accent, emphasis = true) => {
823
+ const x = node.x * camera.k + camera.x, y = node.y * camera.k + camera.y, r = radius(node)
824
+ if (x < -50 || y < -50 || x > width + 50 || y > height + 50) return
825
+ context.globalAlpha = 1; context.setLineDash([])
826
+ if (!emphasis && layout.nodes.length > 2400 && camera.k < .3) {
827
+ context.fillStyle = nodeColor(node); context.beginPath(); context.arc(x, y, 1, 0, TAU); context.fill()
828
+ return
829
+ }
830
+ context.fillStyle = nodeColor(node); context.beginPath(); context.arc(x, y, r, 0, TAU); context.fill()
831
+ if (node.kind === 'cluster') {
832
+ context.font = '10px system-ui, sans-serif'; context.textAlign = 'center'; context.textBaseline = 'middle'
833
+ context.fillStyle = background; context.fillText(String(node.count), x, y)
834
+ }
835
+ if (node.locked) { context.fillStyle = background; context.fillRect(x - 1.5, y - 1.5, 3, 3) }
836
+ if (node.status === 'provisional') {
837
+ context.strokeStyle = nodeColor(node); context.setLineDash([3, 3])
838
+ context.beginPath(); context.ellipse(x, y, r + 5, r + 5, 0, 0, TAU); context.stroke(); context.setLineDash([])
839
+ }
840
+ if (emphasis) {
841
+ context.strokeStyle = accent; context.lineWidth = 1.5
842
+ context.beginPath(); context.ellipse(x, y, r + 4, r + 4, 0, 0, TAU); context.stroke()
843
+ }
844
+ if (options.labels && emphasis) {
845
+ context.font = '12px system-ui, sans-serif'; context.textAlign = 'center'; context.textBaseline = 'top'
846
+ context.strokeStyle = background; context.lineWidth = 3.5
847
+ const label = String(node.title || node.id)
848
+ context.strokeText(label, x, y + r + 4); context.fillStyle = foreground; context.fillText(label, x, y + r + 4)
849
+ }
850
+ context.globalAlpha = 1
851
+ }
852
+ const drawLocal = (session, foreground, background, accent) => {
853
+ const batches = new Map()
854
+ for (const edge of session.edgeSet) {
855
+ const a = { x: edge.source.x * camera.k + camera.x, y: edge.source.y * camera.k + camera.y }
856
+ const b = { x: edge.target.x * camera.k + camera.x, y: edge.target.y * camera.k + camera.y }
857
+ if (Math.max(a.x, b.x) < -40 || Math.min(a.x, b.x) > width + 40
858
+ || Math.max(a.y, b.y) < -40 || Math.min(a.y, b.y) > height + 40) continue
859
+ const primary = edge.from === session.root.id || edge.to === session.root.id
860
+ if (!primary && layout.nodes.length > 2400 && camera.k < .3) continue
861
+ const color = edgeColor(edge, foreground, accent), key = JSON.stringify([primary, color, edge.manual])
862
+ let batch = batches.get(key)
863
+ if (!batch) batches.set(key, batch = { primary, color, manual: edge.manual, list: [] })
864
+ batch.list.push({ edge, a, b })
865
+ }
866
+ for (const batch of [...batches.values()].sort((a, b) => Number(a.primary) - Number(b.primary))) {
867
+ context.strokeStyle = batch.color
868
+ context.globalAlpha = batch.primary ? .65 : .15; context.lineWidth = batch.primary ? 1.5 : .8
869
+ context.setLineDash(batch.manual ? [5, 4] : [])
870
+ context.beginPath()
871
+ for (const { a, b } of batch.list) { context.moveTo(a.x, a.y); context.lineTo(b.x, b.y) }
872
+ context.stroke(); context.setLineDash([])
873
+ if (!batch.manual || camera.k < .3) continue
874
+ context.fillStyle = batch.color
875
+ context.beginPath()
876
+ for (const { edge, a, b } of batch.list) {
877
+ if (edge.rule === 'entity-mention' || edge.rule === 'conflict') continue
878
+ const dx = b.x - a.x, dy = b.y - a.y, d = Math.hypot(dx, dy)
879
+ if (d <= 22) continue
880
+ const ux = dx / d, uy = dy / d, rr = radius(edge.target) + 3
881
+ const hx = b.x - ux * rr, hy = b.y - uy * rr
882
+ if (hx < -10 || hy < -10 || hx > width + 10 || hy > height + 10) continue
883
+ context.moveTo(hx, hy)
884
+ context.lineTo(hx - ux * 7 - uy * 3.4, hy - uy * 7 + ux * 3.4)
885
+ context.lineTo(hx - ux * 7 + uy * 3.4, hy - uy * 7 - ux * 3.4)
886
+ context.closePath()
887
+ }
888
+ context.fill()
889
+ }
890
+ for (const node of session.members) drawDraggedNode(node, foreground, background, accent, node === session.root)
891
+ context.globalAlpha = 1
892
+ }
730
893
  const draw = () => {
731
894
  context.setTransform(ratio, 0, 0, ratio, 0, 0)
732
895
  context.clearRect(0, 0, width, height)
@@ -734,9 +897,17 @@ export function createGraphView(canvas, { onFocus = () => {}, onZoom = () => {},
734
897
  const foreground = style.color || '#202020'
735
898
  const background = style.getPropertyValue('--dsw-alias-bg-layer-1').trim() || '#ffffff'
736
899
  const accent = style.getPropertyValue('--dsw-alias-brand-primary').trim() || '#3b5bdb'
737
- const active = hovered?.id || focused
900
+ const dynamic = layout.localSession
901
+ if (!dynamic) localLayer = null
902
+ if (dynamic && localLayer?.session === dynamic && localLayer.version === dynamic.version) {
903
+ context.drawImage(localLayer.canvas, 0, 0, width, height)
904
+ drawLocal(dynamic, foreground, background, accent)
905
+ dragCachedFrames++; onPaint(); return
906
+ }
907
+ const active = dynamic?.root.id || (gesture?.type === 'node' ? gesture.node?.id : null) || hovered?.id || focused
738
908
  const neighbors = new Set(active ? [active] : [])
739
- for (const edge of layout.edges) {
909
+ const far = layout.nodes.length > 2400 && camera.k < .3
910
+ for (const edge of active ? layout.edgesFor(active) : []) {
740
911
  if (edge.from === active) neighbors.add(edge.to)
741
912
  if (edge.to === active) neighbors.add(edge.from)
742
913
  }
@@ -748,7 +919,8 @@ export function createGraphView(canvas, { onFocus = () => {}, onZoom = () => {},
748
919
  const k = camera.k, ox = camera.x, oy = camera.y
749
920
  // 按「rule 颜色 + 实/虚 + 是否簇间骨架」分组,每组一次 stroke;最多 6 色,开销可控。
750
921
  const batches = new Map()
751
- for (const edge of layout.edges) {
922
+ for (const edge of far ? [] : layout.edges) {
923
+ if (dynamic && (dynamic.ids.has(edge.from) || dynamic.ids.has(edge.to))) continue
752
924
  const a = { x: edge.source.x * k + ox, y: edge.source.y * k + oy }
753
925
  const b = { x: edge.target.x * k + ox, y: edge.target.y * k + oy }
754
926
  if ((a.x < -40 && b.x < -40) || (a.x > width + 40 && b.x > width + 40)) continue
@@ -773,18 +945,20 @@ export function createGraphView(canvas, { onFocus = () => {}, onZoom = () => {},
773
945
  if (batch.manual && camera.k >= .3) {
774
946
  context.fillStyle = batch.color
775
947
  context.globalAlpha = active ? .22 : .4
948
+ context.beginPath()
776
949
  for (const item of batch.list) {
777
950
  if (item.edge.rule === 'entity-mention' || item.edge.rule === 'conflict') continue
778
951
  const dx = item.b.x - item.a.x, dy = item.b.y - item.a.y, d = Math.hypot(dx, dy)
779
952
  if (d <= 22) continue
780
953
  const ux = dx / d, uy = dy / d, rr = radius(item.edge.target) + 3
781
954
  const hx = item.b.x - ux * rr, hy = item.b.y - uy * rr
782
- context.beginPath()
955
+ if (hx < -10 || hy < -10 || hx > width + 10 || hy > height + 10) continue
783
956
  context.moveTo(hx, hy)
784
957
  context.lineTo(hx - ux * 7 - uy * 3.4, hy - uy * 7 + ux * 3.4)
785
958
  context.lineTo(hx - ux * 7 + uy * 3.4, hy - uy * 7 - ux * 3.4)
786
- context.closePath(); context.fill()
959
+ context.closePath()
787
960
  }
961
+ context.fill()
788
962
  }
789
963
  }
790
964
  if (active) {
@@ -792,6 +966,7 @@ export function createGraphView(canvas, { onFocus = () => {}, onZoom = () => {},
792
966
  context.beginPath()
793
967
  for (const edge of layout.edges) {
794
968
  if (edge.from !== active && edge.to !== active) continue
969
+ if (dynamic) continue
795
970
  context.moveTo(edge.source.x * k + ox, edge.source.y * k + oy)
796
971
  context.lineTo(edge.target.x * k + ox, edge.target.y * k + oy)
797
972
  }
@@ -799,20 +974,39 @@ export function createGraphView(canvas, { onFocus = () => {}, onZoom = () => {},
799
974
  }
800
975
  context.globalAlpha = 1
801
976
  context.strokeStyle = foreground
802
- const visible = []
977
+ let visible = []
803
978
  for (const node of layout.nodes) {
979
+ if (dynamic?.ids.has(node.id)) continue
804
980
  const x = node.x * k + ox, y = node.y * k + oy
805
981
  // 留足裁剪余量:拖动时硬分离会把邻簇推开,小视口下也不该让节点突然消失
806
982
  // (可见性仍由下面的点层 LOD 与标签视口裁剪兜底)。
807
983
  if (x >= -120 && x <= width + 120 && y >= -120 && y <= height + 120) visible.push({ node, x, y, r: radius(node) })
808
984
  }
809
- const dots = layout.nodes.length > 2400 && camera.k < .3
810
- if (dots) {
811
- // 点层 LOD:按颜色批量 2px 方点,不建每节点对象、不逐颗 arc。
985
+ const dots = far
986
+ let gpuCanvas = null
987
+ if (layout.nodes.length > 20000 && options.webgl !== false) {
988
+ if (!webglAttempted) {
989
+ webglAttempted = true
990
+ webgl = createWebGLRenderer(canvas.ownerDocument, () => {
991
+ renderer = 'canvas2d'; onDiagnostic({ code: 'GRAPH_WEBGL_FALLBACK', reason: 'context-lost' }); requestDraw()
992
+ })
993
+ if (!webgl) onDiagnostic({ code: 'GRAPH_WEBGL_FALLBACK', reason: 'webgl2-unavailable' })
994
+ }
995
+ if (dots) for (const point of visible) point.r = 1
996
+ gpuCanvas = webgl?.draw(visible, width, height, ratio, nodeColor, node => !dots && !!active && !neighbors.has(node.id))
997
+ if (gpuCanvas) context.drawImage(gpuCanvas, 0, 0, width, height)
998
+ }
999
+ renderer = gpuCanvas ? 'webgl2' : 'canvas2d'
1000
+ if (!gpuCanvas && layout.nodes.length > 20000 && visible.length > 8000) {
1001
+ const stride = Math.ceil(visible.length / 8000)
1002
+ visible = visible.filter((point, i) => i % stride === 0 || neighbors.has(point.node.id))
1003
+ }
1004
+ if (gpuCanvas) {
1005
+ // Labels, focus and tooltip still use the 2D/accessibility controller.
1006
+ } else if (dots) {
1007
+ // Keep the classic circular node shape in the distant layer too.
812
1008
  const groups = new Map()
813
- for (const node of layout.nodes) {
814
- const x = node.x * k + ox, y = node.y * k + oy
815
- if (x < 0 || x > width || y < 0 || y > height) continue
1009
+ for (const { node, x, y } of visible) {
816
1010
  const color = nodeColor(node)
817
1011
  let list = groups.get(color)
818
1012
  if (!list) groups.set(color, list = [])
@@ -822,7 +1016,9 @@ export function createGraphView(canvas, { onFocus = () => {}, onZoom = () => {},
822
1016
  for (const [color, list] of groups) {
823
1017
  context.fillStyle = color
824
1018
  context.beginPath()
825
- for (let i = 0; i < list.length; i += 2) context.rect(list[i] - 1, list[i + 1] - 1, 2, 2)
1019
+ for (let i = 0; i < list.length; i += 2) {
1020
+ context.moveTo(list[i] + 1, list[i + 1]); context.arc(list[i], list[i + 1], 1, 0, TAU)
1021
+ }
826
1022
  context.fill()
827
1023
  }
828
1024
  } else {
@@ -845,22 +1041,13 @@ export function createGraphView(canvas, { onFocus = () => {}, onZoom = () => {},
845
1041
  }
846
1042
  context.globalAlpha = 1
847
1043
  const queryHighlight = String(options.query || '').trim().toLowerCase()
848
- // 实体用圆角方覆盖圆点;arcTo 不增加 arc 计数。
849
- for (const p of visible) {
850
- if (p.node.kind === 'memory' || p.node.missing) continue
851
- const size = p.r * 1.75, rad = Math.min(5, size / 3), x = p.x - size / 2, y = p.y - size / 2
852
- context.fillStyle = nodeColor(p.node)
853
- context.beginPath()
854
- context.moveTo(x + rad, y)
855
- context.arcTo(x + size, y, x + size, y + size, rad)
856
- context.arcTo(x + size, y + size, x, y + size, rad)
857
- context.arcTo(x, y + size, x, y, rad)
858
- context.arcTo(x, y, x + size, y, rad)
859
- context.closePath(); context.fill()
860
- }
861
1044
  // 临时实体虚线环 / 固定标记:环用 ellipse、标记用 rect,均不污染 arc 计数。
862
1045
  for (const p of visible) {
863
1046
  const node = p.node
1047
+ if (node.kind === 'cluster') {
1048
+ context.font = '10px system-ui, sans-serif'; context.textAlign = 'center'; context.textBaseline = 'middle'
1049
+ context.fillStyle = background; context.fillText(String(node.count), p.x, p.y)
1050
+ }
864
1051
  if (node.status === 'provisional') {
865
1052
  context.strokeStyle = nodeColor(node); context.lineWidth = 1.2; context.setLineDash([3, 3])
866
1053
  context.beginPath(); context.ellipse(p.x, p.y, p.r + 5, p.r + 5, 0, 0, TAU); context.stroke()
@@ -908,7 +1095,7 @@ export function createGraphView(canvas, { onFocus = () => {}, onZoom = () => {},
908
1095
  if (!showAll && p.node.degree < minDeg) continue
909
1096
  if (zoomFade < .02) continue
910
1097
  }
911
- const label = String(p.node.title || p.node.id)
1098
+ const label = p.node.kind === 'cluster' ? `${p.node.title || p.node.id} (${p.node.count})` : String(p.node.title || p.node.id)
912
1099
  const w = context.measureText(label).width
913
1100
  const boxOf = yy => ({ l: p.x - w / 2 - 3, t: yy - 1, r: p.x + w / 2 + 3, b: yy + 14 })
914
1101
  const clash = r => placed.some(q => r.l < q.r && r.r > q.l && r.t < q.b && r.b > q.t)
@@ -924,7 +1111,7 @@ export function createGraphView(canvas, { onFocus = () => {}, onZoom = () => {},
924
1111
  context.fillText(label, p.x, yy)
925
1112
  }
926
1113
  context.globalAlpha = 1
927
- } else if (options.labels && dots && active) {
1114
+ } else if (options.labels && dots && active && !dynamic) {
928
1115
  const focus = layout.nodes.find(node => node.id === active)
929
1116
  if (focus) {
930
1117
  context.font = '12px system-ui, sans-serif'; context.textAlign = 'center'; context.textBaseline = 'top'
@@ -937,31 +1124,105 @@ export function createGraphView(canvas, { onFocus = () => {}, onZoom = () => {},
937
1124
  context.fillStyle = foreground; context.globalAlpha = .55
938
1125
  context.fillText(emptyLabel, width / 2, height / 2); context.globalAlpha = 1
939
1126
  }
1127
+ if (dynamic) {
1128
+ // Only the untouched background is cached. Every member of the actual
1129
+ // spring/collision solve and every incident edge is redrawn each frame.
1130
+ try {
1131
+ const layer = canvas.ownerDocument.createElement('canvas')
1132
+ const scale = Math.min(1, Math.sqrt(16 * 1024 * 1024 / (4 * canvas.width * canvas.height)))
1133
+ layer.width = Math.max(1, Math.floor(canvas.width * scale)); layer.height = Math.max(1, Math.floor(canvas.height * scale))
1134
+ const target = layer.getContext('2d')
1135
+ if (!target) throw new Error('canvas snapshot unavailable')
1136
+ target.drawImage(canvas, 0, 0, layer.width, layer.height)
1137
+ localLayer = { session: dynamic, version: dynamic.version, canvas: layer }
1138
+ dragCachePeakBytes = Math.max(dragCachePeakBytes, layer.width * layer.height * 4)
1139
+ } catch { localLayer = null }
1140
+ drawLocal(dynamic, foreground, background, accent)
1141
+ }
940
1142
  // 每真正重绘一次计数一次:缩略图据此决定要不要拷贝,空闲期不再白拷纹理。
941
1143
  onPaint()
942
1144
  }
943
1145
  const animate = time => {
944
1146
  frame = null
945
1147
  if (disposed) return
946
- const stepping = options.motion && !reducedMotion && layout.active
947
- if (stepping) {
1148
+ // A press that has not moved yet must not run the local solve. Otherwise the
1149
+ // edge springs drag the stragglers toward the held node, and the click path
1150
+ // (no movement = click) restores every saved position — which reads as
1151
+ // "pulled over, then snapped back the moment you let go".
1152
+ const heldStill = gesture?.localPhysics === true && gesture.moved !== true
1153
+ const localStepping = layout.localActive && options.motion && !reducedMotion && !heldStill
1154
+ const stepping = !layout.localSession && options.motion && !reducedMotion && layout.active
1155
+ if (localStepping || stepping) {
948
1156
  accumulator += lastTime ? Math.min(64, time - lastTime) : 17
949
1157
  let steps = 0
950
- for (; accumulator >= 1000 / 60 && steps < 4; accumulator -= 1000 / 60, steps++) layout.tick()
1158
+ const maxSteps = localStepping ? 3 : layout.nodes.length >= options.workerThreshold ? 1 : 4
1159
+ for (; accumulator >= 1000 / 60 && steps < maxSteps; accumulator -= 1000 / 60, steps++) {
1160
+ if (localStepping) { if (layout.localActive) layout.stepLocal() }
1161
+ else layout.tick()
1162
+ }
1163
+ if (steps) hitDirty = true
1164
+ if (steps === maxSteps) accumulator = Math.min(accumulator, 1000 / 60)
951
1165
  lastTime = time
952
1166
  } else { lastTime = 0; accumulator = 0 }
953
1167
  draw()
954
1168
  // 只有物理仍在跑(模拟活跃 / 拖动 / 收敛)才自续帧。
955
1169
  // 冷却后不再空转重绘:GPU 占用会随布局收敛回落,而不是长期占住一档。
956
1170
  // 悬停、相机、数据变化、缩放等路径各自 requestDraw 一帧,画面依旧即时更新。
957
- if (stepping) requestDraw()
1171
+ const continueLocal = layout.localActive && options.motion && !reducedMotion && !heldStill
1172
+ const continueLayout = !layout.localSession && options.motion && !reducedMotion && layout.active
1173
+ if (continueLayout || continueLocal) requestDraw()
958
1174
  }
959
1175
  function requestDraw() {
960
1176
  if (!disposed && frame === null) frame = win.requestAnimationFrame(animate)
961
1177
  }
962
- const notifyCamera = () => { onZoom(camera.k); requestDraw() }
963
- const fit = () => { camera = fitCamera(layout.nodes, width, height); hideTooltip(); notifyCamera() }
964
- const zoom = (factor, p = { x: width / 2, y: height / 2 }) => { camera = zoomCamera(camera, factor, p); hideTooltip(); notifyCamera() }
1178
+ const viewport = () => ({ zoom: camera.k, bbox: { minX: -camera.x / camera.k, minY: -camera.y / camera.k,
1179
+ maxX: (width - camera.x) / camera.k, maxY: (height - camera.y) / camera.k } })
1180
+ const notifyCamera = () => { invalidateDragLayer(); onZoom(camera.k); onViewport(viewport()); requestDraw() }
1181
+ const minimumZoom = () => classicView ? Math.min(.06, fitCamera(layout.nodes, width, height, 1e-6).k * .5) : .06
1182
+ const fit = () => { camera = fitCamera(layout.nodes, width, height, classicView ? 1e-6 : .06); hideTooltip(); notifyCamera() }
1183
+ const zoom = (factor, p = { x: width / 2, y: height / 2 }) => {
1184
+ worker.cancel(); workerPending = false; pendingLayoutGraph = null
1185
+ camera = zoomCamera(camera, factor, p, minimumZoom()); hideTooltip(); notifyCamera()
1186
+ }
1187
+ const setViewport = value => {
1188
+ if (disposed || !value || typeof value !== 'object' || Array.isArray(value)
1189
+ || !Number.isFinite(value.zoom) || value.zoom < minimumZoom() || value.zoom > 5) return false
1190
+ const k = value.zoom, bbox = value.bbox
1191
+ let x, y
1192
+ if (bbox !== undefined) {
1193
+ if (!bbox || typeof bbox !== 'object' || Array.isArray(bbox) || value.x !== undefined || value.y !== undefined
1194
+ || ![bbox.minX, bbox.minY, bbox.maxX, bbox.maxY].every(Number.isFinite)
1195
+ || bbox.minX >= bbox.maxX || bbox.minY >= bbox.maxY) return false
1196
+ // Preserve the saved world origin and zoom across canvas resizes.
1197
+ x = k === camera.k && bbox.minX === -camera.x / k ? camera.x : -bbox.minX * k
1198
+ y = k === camera.k && bbox.minY === -camera.y / k ? camera.y : -bbox.minY * k
1199
+ } else { x = value.x; y = value.y }
1200
+ if (![x, y].every(Number.isFinite)) return false
1201
+ const minX = -x / k, minY = -y / k, maxX = (width - x) / k, maxY = (height - y) / k
1202
+ if (![minX, minY, maxX, maxY].every(Number.isFinite) || minX >= maxX || minY >= maxY) return false
1203
+ // A stale prelayout must not fit the camera after a programmatic restore.
1204
+ worker.cancel(); workerPending = false; pendingLayoutGraph = null
1205
+ if (camera.x === x && camera.y === y && camera.k === k) return true
1206
+ const zoomChanged = camera.k !== k
1207
+ camera = { x, y, k }
1208
+ if (gesture?.type === 'pinch' && pointers.size >= 2) {
1209
+ const [a, b] = [...pointers.values()]
1210
+ gesture.camera = { ...camera }
1211
+ gesture.distance = Math.max(1, Math.hypot(b.x - a.x, b.y - a.y))
1212
+ gesture.center = { x: (a.x + b.x) / 2, y: (a.y + b.y) / 2 }
1213
+ } else if (gesture && pointers.size) {
1214
+ const p = pointers.values().next().value
1215
+ if (gesture.node) {
1216
+ const w = world(p)
1217
+ gesture.offset = { x: gesture.node.x - w.x, y: gesture.node.y - w.y }
1218
+ } else { gesture.start = p; gesture.camera = { ...camera } }
1219
+ }
1220
+ invalidateDragLayer(); hideTooltip()
1221
+ if (zoomChanged) onZoom(k)
1222
+ // Restoring an RPC/search snapshot is not a new viewport-fetch request.
1223
+ requestDraw()
1224
+ return true
1225
+ }
965
1226
  const resize = () => {
966
1227
  const rect = canvas.getBoundingClientRect()
967
1228
  if (!rect.width || !rect.height) return
@@ -969,6 +1230,7 @@ export function createGraphView(canvas, { onFocus = () => {}, onZoom = () => {},
969
1230
  camera.x += (nextWidth - width) / 2; camera.y += (nextHeight - height) / 2
970
1231
  width = nextWidth; height = nextHeight; ratio = Math.min(2, win.devicePixelRatio || 1)
971
1232
  canvas.width = Math.round(width * ratio); canvas.height = Math.round(height * ratio)
1233
+ invalidateDragLayer()
972
1234
  requestDraw()
973
1235
  }
974
1236
  const startPinch = () => {
@@ -980,6 +1242,7 @@ export function createGraphView(canvas, { onFocus = () => {}, onZoom = () => {},
980
1242
  const down = event => {
981
1243
  if (event.button !== 0 && event.pointerType !== 'touch') return
982
1244
  event.preventDefault()
1245
+ worker.cancel(); workerPending = false
983
1246
  canvas.focus({ preventScroll: true })
984
1247
  const p = point(event)
985
1248
  pointers.set(event.pointerId, p)
@@ -988,21 +1251,33 @@ export function createGraphView(canvas, { onFocus = () => {}, onZoom = () => {},
988
1251
  const node = hit(p)
989
1252
  const w = world(p)
990
1253
  const component = node ? layout.componentOf(node.id) : null
991
- const mode = node && event.shiftKey && component ? 'rigid' : 'node'
1254
+ // Use the same rooted elastic solve at every scale. Shift remains the
1255
+ // explicit rigid translation gesture.
1256
+ const localPhysics = !!node && !event.shiftKey
1257
+ const mode = localPhysics ? 'node' : (node && component && event.shiftKey ? 'rigid' : 'component')
992
1258
  const members = mode === 'rigid' ? component.members : (node ? [node] : [])
993
1259
  gesture = { type: node ? 'node' : 'pan', node, mode, members, start: p, camera: { ...camera }, moved: false,
1260
+ localPhysics,
994
1261
  offset: node ? { x: node.x - w.x, y: node.y - w.y } : null,
995
- snapshot: members.map(m => ({ id: m.id, x: m.x, y: m.y, fx: m.fx, fy: m.fy, locked: m.locked })) }
1262
+ snapshot: (localPhysics ? members : (component?.members || members)).map(m =>
1263
+ ({ id: m.id, x: m.x, y: m.y, fx: m.fx, fy: m.fy, locked: m.locked, anchored: m.anchored })) }
996
1264
  if (node) {
997
- // 拖动期间只临时钉住,不算"锁定";锁定只由右键产生。
998
- for (const m of members) layout.hold(m.id, m.x, m.y)
999
- layout.startDragScope(node.id)
1000
- layout.setDragging(true)
1265
+ if (gesture.localPhysics) { layout.beginLocalDrag(node.id); layout.cool() }
1266
+ else {
1267
+ layout.startDragScope(node.id)
1268
+ // A normal drag is elastic; only the root is temporarily fixed.
1269
+ if (gesture.mode === 'rigid') for (const m of members) layout.hold(m.id, m.x, m.y)
1270
+ else layout.hold(node.id, node.x, node.y)
1271
+ layout.setDragging(true)
1272
+ }
1001
1273
  }
1002
1274
  hideTooltip()
1003
1275
  canvas.style.cursor = 'grabbing'
1276
+ requestDraw()
1004
1277
  }
1005
1278
  const move = event => {
1279
+ if (handledPointerEvents.has(event)) return
1280
+ handledPointerEvents.add(event)
1006
1281
  const p = point(event)
1007
1282
  if (!pointers.has(event.pointerId) || !gesture) { setHover(hit(p, hovered), p); return }
1008
1283
  pointers.set(event.pointerId, p)
@@ -1010,7 +1285,7 @@ export function createGraphView(canvas, { onFocus = () => {}, onZoom = () => {},
1010
1285
  if (pointers.size < 2) return
1011
1286
  const [a, b] = [...pointers.values()]
1012
1287
  const center = { x: (a.x + b.x) / 2, y: (a.y + b.y) / 2 }
1013
- camera = zoomCamera(gesture.camera, Math.hypot(b.x - a.x, b.y - a.y) / gesture.distance, gesture.center)
1288
+ camera = zoomCamera(gesture.camera, Math.hypot(b.x - a.x, b.y - a.y) / gesture.distance, gesture.center, minimumZoom())
1014
1289
  camera.x += center.x - gesture.center.x; camera.y += center.y - gesture.center.y
1015
1290
  notifyCamera()
1016
1291
  } else {
@@ -1022,41 +1297,61 @@ export function createGraphView(canvas, { onFocus = () => {}, onZoom = () => {},
1022
1297
  const nx = w.x + gesture.offset.x, ny = w.y + gesture.offset.y
1023
1298
  const dx = nx - node.fx, dy = ny - node.fy
1024
1299
  for (const m of gesture.members) layout.hold(m.id, m.fx + dx, m.fy + dy)
1025
- } else layout.hold(node.id, w.x + gesture.offset.x, w.y + gesture.offset.y)
1026
- // 每次指针移动都同步推进两帧:邻居像珠子链一样立刻跟过来,
1027
- // 不会等 rAF(小图缩放时 rAF 一帧的位移远小于指针)。
1028
- layout.settle(2)
1300
+ } else if (gesture.localPhysics) layout.moveLocalDrag(w.x + gesture.offset.x, w.y + gesture.offset.y)
1301
+ else layout.hold(node.id, w.x + gesture.offset.x, w.y + gesture.offset.y)
1302
+ if (!gesture.localPhysics) {
1303
+ if (reducedMotion || !options.motion) layout.settle(2)
1304
+ else layout.tick()
1305
+ } else {
1306
+ layout.cool()
1307
+ if (reducedMotion || !options.motion) { layout.stepLocal(); layout.stepLocal() }
1308
+ }
1309
+ hitDirty = true
1029
1310
  } else {
1030
1311
  camera.x = gesture.camera.x + p.x - gesture.start.x; camera.y = gesture.camera.y + p.y - gesture.start.y
1031
1312
  }
1032
- requestDraw()
1313
+ if (gesture.node) requestDraw()
1314
+ else notifyCamera()
1033
1315
  }
1034
1316
  }
1035
1317
  const up = event => {
1318
+ if (handledPointerEvents.has(event)) return
1319
+ handledPointerEvents.add(event)
1036
1320
  if (!pointers.has(event.pointerId)) return
1037
- const cancelled = event.type !== 'pointerup'
1321
+ const cancelled = event.type === 'pointercancel'
1038
1322
  const selected = gesture?.node
1039
1323
  const click = !cancelled && !gesture?.moved && gesture?.type !== 'pinch' && (event.detail ?? 1) < 2
1040
1324
  if (click || cancelled) {
1041
1325
  // 单击不留下临时 pin;取消/Esc 恢复按下前的摆位。
1042
1326
  restoreGesture(gesture)
1043
- } else if (selected) {
1044
- // 松手:原本锁定的节点把锁定点更新到落点;自由节点则 release —— 留在原地
1045
- // 但不再固定,后续拖别的节点能带动它,右键一次即可(它本来就没被锁)。
1046
- for (const saved of gesture.snapshot) {
1047
- const state = layout.nodeById(saved.id)
1048
- if (!state) continue
1049
- if (saved.locked || saved.fx != null) {
1050
- state.fx = state.x; state.fy = state.y; state.locked = true
1327
+ } else if (selected && gesture.localPhysics) {
1328
+ layout.releaseLocalDrag(reducedMotion || !options.motion)
1329
+ if (reducedMotion || !options.motion) for (let i = 0; i < 240 && layout.localActive; i++) layout.stepLocal()
1330
+ } else if (selected && gesture.mode === 'component') {
1331
+ const saved = gesture.snapshot.find(item => item.id === selected.id)
1332
+ const state = layout.nodeById(selected.id)
1333
+ if (state) {
1334
+ if (saved?.locked || saved?.fx != null) {
1335
+ state.fx = state.x; state.fy = state.y; state.locked = saved.locked === true
1051
1336
  state.vx = 0; state.vy = 0
1052
1337
  } else {
1053
- layout.release(saved.id)
1338
+ state.fx = state.x; state.fy = state.y
1339
+ state.anchored = true
1340
+ state.vx = 0; state.vy = 0
1054
1341
  }
1055
1342
  }
1056
1343
  layout.setDragging(false)
1057
- // 多收敛几帧,让「松手落点」也被安全间距推开,不会停在别的节点身上。
1058
1344
  if (reducedMotion || !options.motion) { layout.settle(120); layout.clearDragScope() }
1059
1345
  else layout.reheat(.3)
1346
+ } else if (selected) {
1347
+ // Shift-drag keeps the whole translated component at its new coordinates.
1348
+ for (const saved of gesture.snapshot) {
1349
+ const state = layout.nodeById(saved.id)
1350
+ if (!state) continue
1351
+ state.fx = state.x; state.fy = state.y; state.locked = saved.locked === true; state.anchored = true
1352
+ state.vx = 0; state.vy = 0
1353
+ }
1354
+ layout.cool()
1060
1355
  }
1061
1356
  pointers.delete(event.pointerId)
1062
1357
  gesture = null
@@ -1066,7 +1361,7 @@ export function createGraphView(canvas, { onFocus = () => {}, onZoom = () => {},
1066
1361
  }
1067
1362
  if (canvas.hasPointerCapture?.(event.pointerId)) canvas.releasePointerCapture(event.pointerId)
1068
1363
  if (click) onFocus(selected?.id || '')
1069
- hovered = null; canvas.style.cursor = 'grab'; hideTooltip(); requestDraw()
1364
+ hitDirty = true; hovered = null; canvas.style.cursor = 'grab'; hideTooltip(); requestDraw()
1070
1365
  }
1071
1366
  const listen = (target, type, fn, opts) => {
1072
1367
  target.addEventListener(type, fn, opts)
@@ -1074,20 +1369,36 @@ export function createGraphView(canvas, { onFocus = () => {}, onZoom = () => {},
1074
1369
  }
1075
1370
  listen(canvas, 'pointerdown', down)
1076
1371
  listen(canvas, 'pointermove', move)
1077
- for (const type of ['pointerup', 'pointercancel', 'lostpointercapture']) listen(canvas, type, up)
1372
+ listen(canvas, 'pointerup', up)
1373
+ listen(canvas, 'pointercancel', up)
1374
+ listen(canvas, 'lostpointercapture', event => {
1375
+ // Capture loss can happen during a live drag. Keep the gesture alive and
1376
+ // try to reacquire capture while the primary button is still held; the
1377
+ // real pointerup/pointercancel handlers own the final transition.
1378
+ if (!pointers.has(event.pointerId)) return
1379
+ if (gesture) gesture.captureLost = true
1380
+ if (event.buttons !== 0 || event.pressure > 0) {
1381
+ try { canvas.setPointerCapture?.(event.pointerId) } catch {}
1382
+ if (canvas.hasPointerCapture?.(event.pointerId) && gesture) gesture.captureLost = false
1383
+ }
1384
+ })
1385
+ listen(win, 'pointermove', event => { if (gesture?.captureLost) move(event) })
1386
+ listen(win, 'pointerup', event => { if (gesture?.captureLost) up(event) })
1387
+ listen(win, 'pointercancel', event => { if (gesture?.captureLost) up(event) })
1078
1388
  listen(canvas, 'pointerleave', () => { if (!gesture) { hovered = null; hideTooltip(); requestDraw() } })
1079
- // 右键 = 锁定 / 解除:左键只负责显示单链与拖动,不再产生固定点。
1389
+ // Right-click marks an explicit pin; left-drag anchors do not count as pins.
1080
1390
  listen(canvas, 'contextmenu', event => {
1081
1391
  event.preventDefault()
1082
1392
  const node = hit(point(event))
1083
1393
  if (!node) return
1084
1394
  const state = layout.nodeById(node.id)
1085
1395
  if (!state) return
1086
- // 有任何固定点(含拖动残留)就先解开,再点一次才锁定 —— 不会出现要点两次。
1087
- if (state.fx != null) layout.unpin(node.id)
1396
+ if (state.locked) layout.unpin(node.id)
1088
1397
  else layout.pin(node.id, state.x, state.y)
1089
1398
  layout.setDragging(false)
1090
- if (reducedMotion || !options.motion) layout.settle(20)
1399
+ if (fixedLargeLayout) layout.cool()
1400
+ else if (reducedMotion || !options.motion) layout.settle(20)
1401
+ hitDirty = true
1091
1402
  requestDraw()
1092
1403
  })
1093
1404
  // 双击聚焦:第二次 pointerup 的 detail>=2 已在 up 里跳过,避免重复取数。
@@ -1098,66 +1409,97 @@ export function createGraphView(canvas, { onFocus = () => {}, onZoom = () => {},
1098
1409
  else if (event.key === '-') zoom(.8)
1099
1410
  else if (event.key === '0' || event.key === 'Home') fit()
1100
1411
  else if (event.key === 'Escape') {
1101
- restoreGesture(gesture); gesture = null; pointers.clear(); onFocus(''); hideTooltip(); requestDraw()
1412
+ restoreGesture(gesture); hitDirty = true; gesture = null; pointers.clear(); onFocus(''); hideTooltip(); requestDraw()
1102
1413
  } else if (['ArrowLeft', 'ArrowRight', 'ArrowUp', 'ArrowDown'].includes(event.key)) {
1103
1414
  const step = event.shiftKey ? 90 : 30
1104
1415
  camera.x += event.key === 'ArrowLeft' ? step : event.key === 'ArrowRight' ? -step : 0
1105
1416
  camera.y += event.key === 'ArrowUp' ? step : event.key === 'ArrowDown' ? -step : 0
1106
- requestDraw()
1417
+ notifyCamera()
1107
1418
  } else return
1108
1419
  event.preventDefault()
1109
1420
  })
1110
1421
  listen(win, 'blur', () => {
1111
- restoreGesture(gesture); gesture = null; pointers.clear(); hovered = null; hideTooltip(); requestDraw()
1422
+ restoreGesture(gesture); hitDirty = true; gesture = null; pointers.clear(); hovered = null; hideTooltip(); requestDraw()
1112
1423
  })
1113
1424
  const observer = win.ResizeObserver ? new win.ResizeObserver(resize) : null
1114
1425
  observer?.observe(canvas)
1115
1426
  listen(win, 'resize', resize)
1116
- const themeObserver = win.MutationObserver ? new win.MutationObserver(requestDraw) : null
1427
+ const themeObserver = win.MutationObserver ? new win.MutationObserver(() => { invalidateDragLayer(); requestDraw() }) : null
1117
1428
  themeObserver?.observe(canvas.ownerDocument.documentElement, { attributes: true, attributeFilter: ['class', 'data-theme', 'style'] })
1118
1429
  if (canvas.ownerDocument.body) themeObserver?.observe(canvas.ownerDocument.body, { attributes: true, attributeFilter: ['class', 'data-theme', 'style'] })
1119
1430
  resize()
1120
1431
  return {
1121
1432
  update(graph, focus = '') {
1122
- if (gesture?.node && !graph.nodes.some(node => node.id === gesture.node.id)) {
1433
+ invalidateDragLayer()
1434
+ const nextPositionScope = graph.positionScope ?? graph.scope ?? 'default'
1435
+ if (positionScope !== null && positionScope !== nextPositionScope && gesture) {
1436
+ restoreGesture(gesture); gesture = null; pointers.clear()
1437
+ } else if (gesture?.node && !graph.nodes.some(node => node.id === gesture.node.id)) {
1123
1438
  restoreGesture(gesture); gesture = null; pointers.clear()
1124
1439
  }
1440
+ positionScope = nextPositionScope
1441
+ const previousIds = new Set(layout.nodes.map(node => node.id))
1442
+ const classic = graph.mode === 'classic'
1443
+ classicView = classic
1444
+ const prepositioned = !classic && graph.overview || (graph.nodes.length > 0 && graph.nodes.every(node => Number.isFinite(node.x) && Number.isFinite(node.y)))
1125
1445
  const changed = layout.update(graph)
1446
+ fixedLargeLayout = layout.nodes.length >= options.workerThreshold && (classic || prepositioned || (!changed && fixedLargeLayout))
1447
+ if (changed) { worker.cancel(); workerPending = false; hitDirty = true }
1126
1448
  focused = focus
1127
1449
  if (hovered && !layout.nodes.includes(hovered)) { hovered = null; hideTooltip() }
1128
1450
  if (!initialized && layout.nodes.length) {
1129
- layout.settle(220); initialized = true; fit()
1130
- } else if (changed && (reducedMotion || !options.motion)) layout.settle(180)
1451
+ if (layout.nodes.length < options.workerThreshold && !prepositioned) layout.settle(220)
1452
+ initialized = true; fit()
1453
+ } else if (changed && layout.nodes.length < options.workerThreshold && !prepositioned && (reducedMotion || !options.motion)) layout.settle(180)
1454
+ if (changed && layout.nodes.length >= options.workerThreshold && !prepositioned && !classic) {
1455
+ const inputById = new Map(graph.nodes.map(node => [node.id, node]))
1456
+ pendingLayoutGraph = { nodes: layout.nodes.map(node => {
1457
+ const previous = previousIds.has(node.id) ? node : inputById.get(node.id)
1458
+ return { id: node.id, x: previous?.x, y: previous?.y }
1459
+ }), edges: (graph.edges || []).map(({ from, to }) => ({ from, to })) }
1460
+ workerPending = true
1461
+ if (!worker.request(pendingLayoutGraph) && workerPending) applyPrelayout(prelayoutGraph(pendingLayoutGraph))
1462
+ }
1131
1463
  requestDraw()
1132
1464
  },
1133
1465
  configure(next) {
1466
+ invalidateDragLayer()
1134
1467
  const forceChanged = ['repulsion', 'distance', 'center'].some(key => next[key] !== undefined && next[key] !== options[key])
1135
1468
  options = { ...options, ...next }
1136
1469
  if (forceChanged) {
1137
1470
  layout.configure(next)
1138
1471
  if (reducedMotion || !options.motion) layout.settle(160)
1472
+ hitDirty = true
1139
1473
  }
1140
1474
  requestDraw()
1141
1475
  },
1142
- fit, zoom,
1476
+ fit, zoom, viewport, setViewport,
1477
+ diagnostics() { return { workerPending, workerUsed, workerFallback, renderer, nodes: layout.nodes.length, fixedNodeDrag: false,
1478
+ localPhysics: layout.localDiagnostics(),
1479
+ dragCachedFrames, dragCachePeakBytes, dragCacheBytes: localLayer ? localLayer.canvas.width * localLayer.canvas.height * 4 : 0 } },
1143
1480
  isPinned(id) { return layout.nodeById(id)?.locked === true },
1144
1481
  pinnedCount() { return layout.nodes.reduce((count, node) => count + (node.locked ? 1 : 0), 0) },
1145
1482
  // 只读快照(屏幕坐标 + id):验收按 id 追节点,不依赖绘制顺序。
1146
1483
  snapshot() {
1147
1484
  return layout.nodes.map(node => ({
1148
1485
  id: node.id, x: node.x * camera.k + camera.x, y: node.y * camera.k + camera.y,
1149
- r: radius(node), pinned: node.locked === true, degree: node.degree || 0,
1486
+ r: radius(node), worldX: node.x, worldY: node.y, worldRadius: node.radius,
1487
+ positionFixed: node.fx != null || node.fy != null, anchored: node.anchored === true,
1488
+ pinned: node.locked === true, degree: node.degree || 0,
1150
1489
  }))
1151
1490
  },
1152
1491
  unpinAll() {
1153
1492
  layout.unpinAll(); layout.clearDragScope()
1154
- if (reducedMotion || !options.motion) layout.settle(120)
1493
+ if (fixedLargeLayout) layout.cool()
1494
+ else if (reducedMotion || !options.motion) layout.settle(120)
1495
+ hitDirty = true
1155
1496
  requestDraw()
1156
1497
  },
1157
1498
  relayout() {
1158
1499
  restoreGesture(gesture); gesture = null; pointers.clear()
1159
1500
  layout.relayout()
1160
1501
  if (reducedMotion || !options.motion) layout.settle(220)
1502
+ hitDirty = true
1161
1503
  requestDraw()
1162
1504
  },
1163
1505
  dispose() {
@@ -1165,6 +1507,7 @@ export function createGraphView(canvas, { onFocus = () => {}, onZoom = () => {},
1165
1507
  restoreGesture(gesture); gesture = null; pointers.clear()
1166
1508
  if (frame !== null) win.cancelAnimationFrame(frame)
1167
1509
  for (const remove of cleanup) remove()
1510
+ worker.dispose(); webgl?.dispose(); hitGrid.dispose()
1168
1511
  observer?.disconnect(); themeObserver?.disconnect(); layout.dispose(); hideTooltip()
1169
1512
  },
1170
1513
  }