dsh-memu-memory 1.4.2 → 1.4.4

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