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.
- package/AGENTS.md +108 -110
- package/CHANGELOG.md +173 -868
- package/LICENSE +21 -21
- package/README.md +368 -374
- package/README.zh.md +354 -360
- package/assets/icon.svg +7 -7
- package/cordis.patch.yml +8 -8
- package/docs/active-memory-ab.md +279 -385
- package/docs/binding-lifecycle.md +99 -99
- package/docs/client-conventions.md +75 -75
- package/docs/contributing.md +217 -217
- package/docs/emotion-model-spec.md +247 -281
- package/docs/env-and-commands.md +149 -152
- package/docs/host-adaptation.md +339 -360
- package/docs/host-api.md +131 -137
- package/docs/host-versions.md +117 -120
- package/docs/mcp-porting.md +146 -146
- package/docs/memory-semantics.md +271 -259
- package/docs/pending-work.md +44 -51
- package/docs/troubleshooting.md +909 -854
- package/lib/active-memory.js +160 -165
- package/lib/activity-log.js +207 -207
- package/lib/auto-link/apply.js +248 -249
- package/lib/auto-link/candidates.js +163 -163
- package/lib/auto-link/decide.js +300 -300
- package/lib/auto-link/normalize.js +99 -99
- package/lib/auto-link/policy.js +42 -42
- package/lib/auto-link/suppression.js +101 -101
- package/lib/auto-link/terminology.js +311 -311
- package/lib/backup.js +1254 -1254
- package/lib/binding-diagnostics.js +634 -634
- package/lib/budget.js +118 -118
- package/lib/client.js +9820 -9751
- package/lib/commitment.js +178 -138
- package/lib/consolidation-ledger.js +434 -438
- package/lib/consolidation-receipt.js +386 -387
- package/lib/consolidation-snapshot.js +420 -405
- package/lib/consolidation-worker.js +240 -241
- package/lib/context.js +33 -33
- package/lib/curator-evidence.js +131 -131
- package/lib/curator-policy.js +198 -202
- package/lib/curator.js +1813 -1811
- package/lib/cycle.js +524 -513
- package/lib/diagnostics.js +524 -524
- package/lib/embedding-catalog.js +1051 -1055
- package/lib/embedding-download.js +637 -607
- package/lib/embedding-runtime.js +946 -946
- package/lib/engine.js +1103 -1103
- package/lib/entity-repair.js +285 -285
- package/lib/environment-check.js +394 -394
- package/lib/fork-model.js +312 -312
- package/lib/freshness.js +128 -121
- package/lib/global-graph.js +389 -389
- package/lib/graph.js +1193 -1193
- package/lib/host-surface.js +30 -30
- package/lib/inbound.js +284 -281
- package/lib/index.js +506 -511
- package/lib/inject.js +2639 -2619
- package/lib/lexicon-scope.js +143 -143
- package/lib/lexicon.js +1183 -1192
- package/lib/lifecycle-audit.js +37 -0
- package/lib/local-embedding-entry.js +145 -145
- package/lib/local-embedding-manager.js +306 -306
- package/lib/local-embedding-protocol.js +210 -210
- package/lib/local-embedding-worker.js +682 -682
- package/lib/local-vector-service.js +506 -453
- package/lib/maintenance-ledger.js +138 -0
- package/lib/maintenance-review.js +103 -0
- package/lib/maintenance-runner.js +267 -0
- package/lib/managed-runtime.js +118 -118
- package/lib/media.js +607 -513
- package/lib/memory.js +5035 -4941
- package/lib/memu-config.js +213 -213
- package/lib/memu.js +565 -565
- package/lib/migrate.js +200 -200
- package/lib/mood.js +300 -300
- package/lib/paths.js +453 -457
- package/lib/port-surface.js +82 -82
- package/lib/preset-mount.js +85 -0
- package/lib/preset-scope.js +126 -126
- package/lib/private-links.js +567 -567
- package/lib/private.js +2198 -2209
- package/lib/prompts/global-curator.md +135 -135
- package/lib/prompts/image-caption.md +1 -1
- package/lib/prompts/private-consolidation.coding.md +39 -39
- package/lib/prompts/private-consolidation.md +32 -32
- package/lib/prompts/private-consolidation.mixed.md +37 -37
- package/lib/prompts/private-consolidation.rp.md +47 -47
- package/lib/prompts/private-policy.coding.md +35 -35
- package/lib/prompts/private-policy.md +36 -36
- package/lib/prompts/private-policy.mixed.md +29 -29
- package/lib/prompts/private-policy.rp.md +43 -43
- package/lib/prompts/system-guide.coding.md +20 -20
- package/lib/prompts/system-guide.md +25 -25
- package/lib/prompts/system-guide.mixed.md +22 -22
- package/lib/prompts/system-guide.rp.md +23 -23
- package/lib/prompts.js +331 -331
- package/lib/recall-cache.js +212 -212
- package/lib/remote-summary.js +123 -123
- package/lib/rpc.js +2531 -2532
- package/lib/salient-wake.js +438 -438
- package/lib/snippet.js +125 -125
- package/lib/state.js +1948 -1928
- package/lib/stats.js +236 -236
- package/lib/temporal.js +345 -348
- package/lib/text-retrieval.js +992 -1001
- package/lib/text-similarity.js +305 -305
- package/lib/tokenizer-v2.js +271 -271
- package/lib/tools.js +1098 -1091
- package/lib/turn-log.js +545 -545
- package/lib/vector-migration.js +928 -930
- package/lib/vector-profile.js +1353 -1359
- package/lib/visibility.js +59 -59
- package/lib/webui/graph-LICENSE.txt +1 -1
- package/lib/webui/graph-view.bundle.js +2 -2
- package/lib/webui/graph-view.js +1171 -1175
- package/lib/webui/mark.svg +7 -7
- package/lib/webui/standalone.css +1178 -1178
- package/lib/webui/standalone.js +238 -238
- package/lib/webui.js +136 -136
- package/lib/worker-pool.js +1020 -979
- package/package.json +153 -153
- package/requirements.lock +34 -34
- package/scripts/acceptance-local.mjs +946 -946
- package/scripts/active-memory-ab-live.mjs +653 -655
- package/scripts/active-memory-ab.mjs +1302 -1302
- package/scripts/audit-memory-lifecycle.mjs +55 -0
- package/scripts/bench-recall.mjs +142 -142
- package/scripts/build-graph.mjs +44 -45
- package/scripts/chain-matrix.mjs +541 -541
- package/scripts/check-all.mjs +68 -74
- package/scripts/check-doc-drift.mjs +547 -547
- package/scripts/check-graph-browser.mjs +261 -261
- package/scripts/check-i18n.mjs +81 -83
- package/scripts/check-idle-compositing.mjs +61 -61
- package/scripts/check-seed-compat.mjs +115 -118
- package/scripts/check-text-format.mjs +55 -0
- package/scripts/curator-pair-calibrate.mjs +259 -259
- package/scripts/diagnose-bindings.mjs +176 -176
- package/scripts/drive-session.mjs +863 -864
- package/scripts/engine-smoke.mjs +69 -69
- package/scripts/entity-dedupe.mjs +110 -110
- package/scripts/lexicon-calibrate.mjs +230 -230
- package/scripts/lexicon-dedupe.mjs +318 -318
- package/scripts/local-runtime-install.mjs +142 -142
- package/scripts/local-runtime-verify.mjs +56 -56
- package/scripts/local-vector-verify.mjs +93 -93
- package/scripts/make-readme-shots.mjs +59 -59
- package/scripts/migrate-visibility.mjs +94 -94
- package/scripts/mock-llm.mjs +938 -903
- package/scripts/preview.mjs +58 -58
- package/scripts/prune-sessions.mjs +31 -34
- package/scripts/prune-turnlogs.mjs +29 -30
- package/scripts/prune-vectors.mjs +24 -24
- package/scripts/rebuild-auto-links.mjs +252 -252
- package/scripts/recall-bench.mjs +820 -820
- package/scripts/repetition-ab-scenarios.mjs +93 -93
- package/scripts/repetition-detector-snapshot.mjs +314 -314
- package/scripts/repetition-eval-live.mjs +360 -360
- package/scripts/repetition-eval.mjs +702 -702
- package/scripts/replay.mjs +705 -575
- package/scripts/setup.mjs +46 -46
- package/scripts/simulate-injection.mjs +299 -301
- package/tests/absorb-review.test.mjs +354 -354
- package/tests/activation.test.mjs +89 -89
- package/tests/active-memory-ab.test.mjs +745 -745
- package/tests/active-memory.test.mjs +129 -129
- package/tests/activity-log.test.mjs +126 -126
- package/tests/activity-wiring.test.mjs +155 -155
- package/tests/appendix-b.test.mjs +217 -217
- package/tests/appendix-b2.test.mjs +166 -166
- package/tests/audit-batch3.test.mjs +247 -247
- package/tests/audit-regression.test.mjs +275 -275
- package/tests/audit-safety.test.mjs +227 -227
- package/tests/auto-link-candidates.test.mjs +245 -245
- package/tests/auto-link-decide.test.mjs +512 -512
- package/tests/auto-link-migration.test.mjs +133 -133
- package/tests/backend-compensation.test.mjs +272 -272
- package/tests/backup.test.mjs +793 -793
- package/tests/binding-diagnostics.test.mjs +720 -720
- package/tests/browser.test.mjs +476 -476
- package/tests/client-export.test.mjs +521 -521
- package/tests/client-render.test.mjs +2008 -1728
- package/tests/coalesce.test.mjs +113 -113
- package/tests/commitment.test.mjs +243 -144
- package/tests/config.test.mjs +159 -159
- package/tests/consolidation-credential.test.mjs +330 -330
- package/tests/consolidation-feed.test.mjs +122 -122
- package/tests/consolidation-fork.test.mjs +1587 -1539
- package/tests/consolidation-ledger.test.mjs +389 -389
- package/tests/consolidation-snapshot.test.mjs +567 -505
- package/tests/consolidation-value.test.mjs +89 -89
- package/tests/context-scope.test.mjs +40 -40
- package/tests/cross-library-recall.test.mjs +269 -269
- package/tests/cue.test.mjs +58 -58
- package/tests/curator-absorb.test.mjs +444 -444
- package/tests/curator-calibrate.test.mjs +173 -173
- package/tests/curator-clusters.test.mjs +306 -306
- package/tests/curator-commit.test.mjs +325 -325
- package/tests/curator-contract.test.mjs +191 -191
- package/tests/curator-evidence.test.mjs +102 -102
- package/tests/curator-link.test.mjs +317 -317
- package/tests/curator-pairing.test.mjs +339 -339
- package/tests/curator-probe.test.mjs +490 -490
- package/tests/curator-review-mode.test.mjs +315 -315
- package/tests/curator.test.mjs +152 -152
- package/tests/cycle.test.mjs +567 -568
- package/tests/diagnostics.test.mjs +278 -278
- package/tests/disclosure.test.mjs +249 -249
- package/tests/doc-drift.test.mjs +342 -342
- package/tests/drive-session.test.mjs +152 -152
- package/tests/dynamic-rrf.test.mjs +182 -182
- package/tests/dynamic-threshold.test.mjs +52 -52
- package/tests/embedding-catalog.test.mjs +374 -374
- package/tests/embedding-download.test.mjs +529 -486
- package/tests/embedding-runtime.test.mjs +449 -449
- package/tests/emotion-chain.test.mjs +84 -84
- package/tests/emotion-contract.test.mjs +445 -445
- package/tests/engine.test.mjs +108 -108
- package/tests/entity-merge.test.mjs +278 -278
- package/tests/environment-check.test.mjs +187 -187
- package/tests/fact-version.test.mjs +146 -146
- package/tests/fixtures/active-memory-ab/README.md +56 -56
- package/tests/fixtures/active-memory-ab/cases/01-clean-dense-turn.json +351 -351
- package/tests/fixtures/active-memory-ab/cases/02-clean-thin-turn.json +122 -122
- package/tests/fixtures/active-memory-ab/cases/03-clean-starved-small.json +125 -125
- package/tests/fixtures/active-memory-ab/cases/04-clean-large-thin.json +137 -137
- package/tests/fixtures/active-memory-ab/cases/05-clean-half-step.json +166 -166
- package/tests/fixtures/active-memory-ab/cases/06-clean-duplicate-reread.json +197 -197
- package/tests/fixtures/active-memory-ab/cases/07-clean-recent-recall.json +125 -125
- package/tests/fixtures/active-memory-ab/cases/08-global-relevant.json +111 -111
- package/tests/fixtures/active-memory-ab/cases/09-global-irrelevant-conflict.json +158 -158
- package/tests/fixtures/active-memory-ab/cases/10-no-human-turn.json +97 -97
- package/tests/fixtures/active-memory-ab/cases/11-clean-scale-100.json +137 -137
- package/tests/fixtures/active-memory-ab/cases/12-clean-scale-1000.json +137 -137
- package/tests/fixtures/active-memory-ab/cases/13-clean-scale-5000.json +137 -137
- package/tests/fixtures/active-memory-ab/cases/14-clean-scale-20000.json +137 -137
- package/tests/fixtures/active-memory-ab/lead-ai-reviewed-reference.json +191 -191
- package/tests/fixtures/active-memory-ab/manifest.json +199 -199
- package/tests/fixtures/curator-pairs/labeled.v1.jsonl +90 -90
- package/tests/fixtures/lexicon-stub-hooks.mjs +15 -15
- package/tests/fixtures/lexicon-stub.mjs +284 -284
- package/tests/fixtures/mock-llm/reply.txt +1 -1
- package/tests/fixtures/recall-bench/01-paraphrase.json +183 -183
- package/tests/fixtures/recall-bench/02-exact.json +152 -152
- package/tests/fixtures/recall-bench/03-negation.json +172 -172
- package/tests/fixtures/recall-bench/04-no-answer.json +161 -161
- package/tests/fixtures/recall-bench/05-conflict.json +193 -193
- package/tests/fixtures/recall-bench/06-boundary.json +272 -272
- package/tests/fixtures/recall-bench/07-secret.json +190 -190
- package/tests/fixtures/recall-bench/08-coding.json +163 -163
- package/tests/fixtures/recall-bench-gold-candidates/01-paraphrase.json +193 -193
- package/tests/fixtures/recall-bench-gold-candidates/02-exact.json +197 -197
- package/tests/fixtures/recall-bench-gold-candidates/03-negation.json +244 -244
- package/tests/fixtures/recall-bench-gold-candidates/04-no-answer.json +189 -189
- package/tests/fixtures/recall-bench-gold-candidates/05-conflict.json +245 -245
- package/tests/fixtures/recall-bench-gold-candidates/06-boundary.json +279 -279
- package/tests/fixtures/recall-bench-gold-candidates/07-secret.json +224 -224
- package/tests/fixtures/recall-bench-gold-candidates/08-coding.json +218 -218
- package/tests/fixtures/repetition-eval/01-zh-rp.json +92 -92
- package/tests/fixtures/repetition-eval/02-en.json +96 -96
- package/tests/fixtures/repetition-eval/03-code.json +90 -90
- package/tests/fixtures/repetition-eval/04-names.json +115 -115
- package/tests/fixtures/repetition-eval/05-user-quote.json +95 -95
- package/tests/fixtures/repetition-eval/06-agreement.json +85 -85
- package/tests/fixtures/tokenizer-cases.mjs +27 -27
- package/tests/fork-model.test.mjs +345 -345
- package/tests/freshness.test.mjs +140 -140
- package/tests/global-graph.test.mjs +106 -106
- package/tests/global-lifecycle.test.mjs +149 -149
- package/tests/graph-cascade.test.mjs +363 -363
- package/tests/graph-view.test.mjs +414 -414
- package/tests/graph.test.mjs +371 -371
- package/tests/help-page.test.mjs +416 -416
- package/tests/hook-order.test.mjs +72 -72
- package/tests/humanlike.test.mjs +232 -232
- package/tests/hybrid-recall.test.mjs +610 -610
- package/tests/inbound.test.mjs +441 -441
- package/tests/inject-conflict.test.mjs +173 -173
- package/tests/inject-guide.test.mjs +513 -513
- package/tests/inject.test.mjs +384 -384
- package/tests/injection-budget-settings.test.mjs +35 -35
- package/tests/injection-budget.test.mjs +165 -165
- package/tests/injection-chain.test.mjs +442 -442
- package/tests/injection-intent-budget.test.mjs +92 -92
- package/tests/injection-rollback.test.mjs +428 -428
- package/tests/issue2-chain.test.mjs +169 -169
- package/tests/lexical-bm25.test.mjs +171 -171
- package/tests/lexicon-calibrate.test.mjs +48 -48
- package/tests/lexicon-dedupe.test.mjs +171 -171
- package/tests/lexicon-frequency.test.mjs +195 -195
- package/tests/lexicon-inject.test.mjs +459 -459
- package/tests/lexicon-perf.test.mjs +464 -464
- package/tests/lexicon-scope.test.mjs +256 -256
- package/tests/lexicon-ui.test.mjs +667 -667
- package/tests/lexicon.test.mjs +922 -922
- package/tests/lifecycle-audit.test.mjs +56 -0
- package/tests/loader-register.mjs +3 -3
- package/tests/loader.mjs +17 -17
- package/tests/local-embedding-entry.test.mjs +95 -95
- package/tests/local-embedding-env.test.mjs +51 -51
- package/tests/local-embedding-manager.test.mjs +494 -494
- package/tests/local-embedding-protocol.test.mjs +121 -121
- package/tests/local-embedding-worker.test.mjs +440 -440
- package/tests/local-vector-service.test.mjs +41 -0
- package/tests/maintenance-status.test.mjs +77 -0
- package/tests/maintenance.test.mjs +438 -0
- package/tests/managed-memory.test.mjs +1234 -1234
- package/tests/managed-runtime.test.mjs +72 -72
- package/tests/media-injection.test.mjs +225 -0
- package/tests/media.test.mjs +135 -135
- package/tests/memory-chain.test.mjs +169 -169
- package/tests/memory-fields.test.mjs +134 -134
- package/tests/memu-resident-route.test.mjs +130 -130
- package/tests/memu-resident.test.mjs +33 -33
- package/tests/migration-payload.test.mjs +40 -42
- package/tests/mock-llm.test.mjs +263 -225
- package/tests/mood.test.mjs +109 -109
- package/tests/multiprocess.test.mjs +29 -29
- package/tests/negation-polarity.test.mjs +135 -135
- package/tests/new-session-gate.test.mjs +617 -617
- package/tests/open-loop-date.test.mjs +416 -416
- package/tests/ops-hardening.test.mjs +209 -209
- package/tests/package-shipping.test.mjs +88 -88
- package/tests/pending-injection.test.mjs +107 -107
- package/tests/port-surface.test.mjs +138 -138
- package/tests/preset-mount.test.mjs +132 -0
- package/tests/preset-scope.test.mjs +212 -212
- package/tests/private-links.test.mjs +493 -493
- package/tests/prompt-semantics.test.mjs +51 -51
- package/tests/prompts.test.mjs +315 -315
- package/tests/query-decompose.test.mjs +62 -62
- package/tests/react-snapshot.test.mjs +24 -24
- package/tests/recall-bench.test.mjs +317 -317
- package/tests/recall-cache.test.mjs +292 -292
- package/tests/recall-corpus-eligibility.test.mjs +51 -51
- package/tests/recall-dedup.test.mjs +446 -446
- package/tests/recall-intent.test.mjs +172 -172
- package/tests/regression-sweep.test.mjs +311 -311
- package/tests/reminder-fairness.test.mjs +55 -0
- package/tests/remote.test.mjs +140 -140
- package/tests/rename.test.mjs +30 -30
- package/tests/repetition-detector-snapshot.test.mjs +231 -231
- package/tests/repetition-eval-live.test.mjs +177 -177
- package/tests/repetition-eval.test.mjs +373 -373
- package/tests/salience-domain.test.mjs +173 -173
- package/tests/salient-date.test.mjs +142 -142
- package/tests/salient-wake.test.mjs +389 -389
- package/tests/settings-beat.test.mjs +222 -222
- package/tests/settings-coverage.test.mjs +97 -97
- package/tests/settings-plumbing.test.mjs +79 -79
- package/tests/short-term.test.mjs +182 -166
- package/tests/sidebar-beat.test.mjs +213 -213
- package/tests/sidebar-refresh.test.mjs +123 -123
- package/tests/sidebar.test.mjs +102 -74
- package/tests/simulate-injection.test.mjs +76 -76
- package/tests/slot-similarity.test.mjs +153 -153
- package/tests/snippet.test.mjs +79 -79
- package/tests/source-kind.test.mjs +52 -52
- package/tests/speaker-provenance.test.mjs +120 -120
- package/tests/stale-maintenance.test.mjs +206 -131
- package/tests/state-gc.test.mjs +34 -34
- package/tests/state.test.mjs +155 -155
- package/tests/stats.test.mjs +112 -112
- package/tests/storage.test.mjs +125 -125
- package/tests/stubs/child-process-spy.mjs +14 -14
- package/tests/stubs/dsh-llm-pi-ai.js +13 -13
- package/tests/stubs/dsh-llm.js +5 -5
- package/tests/stubs/dsh-schedule.js +140 -140
- package/tests/stubs/dsh-session-query.js +26 -26
- package/tests/stubs/dsh-session.js +7 -7
- package/tests/stubs/dsh-tools.js +101 -101
- package/tests/temporal-repair.test.mjs +78 -0
- package/tests/temporal.test.mjs +124 -124
- package/tests/text-format.test.mjs +24 -0
- package/tests/tokenizer-v2.test.mjs +142 -142
- package/tests/tool-schema.test.mjs +126 -126
- package/tests/tools.test.mjs +810 -810
- package/tests/turn-log.test.mjs +487 -487
- package/tests/ui-defaults.test.mjs +57 -57
- package/tests/update-fields.test.mjs +138 -138
- package/tests/vector-gc.test.mjs +37 -37
- package/tests/vector-migration.test.mjs +810 -810
- package/tests/vector-profile.test.mjs +449 -449
- package/tests/visibility-migration.test.mjs +152 -152
- package/tests/webui-auth.test.mjs +963 -963
- package/tests/webui.test.mjs +421 -421
- package/tests/windows-env.test.mjs +89 -89
- package/tests/worker-lifecycle.test.mjs +1522 -1429
package/lib/webui/graph-view.js
CHANGED
|
@@ -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
|
-
//
|
|
404
|
-
|
|
405
|
-
|
|
406
|
-
|
|
407
|
-
|
|
408
|
-
|
|
409
|
-
|
|
410
|
-
|
|
411
|
-
|
|
412
|
-
|
|
413
|
-
if (
|
|
414
|
-
|
|
415
|
-
|
|
416
|
-
|
|
417
|
-
|
|
418
|
-
|
|
419
|
-
|
|
420
|
-
|
|
421
|
-
|
|
422
|
-
|
|
423
|
-
if (alpha <
|
|
424
|
-
const
|
|
425
|
-
|
|
426
|
-
|
|
427
|
-
const
|
|
428
|
-
const
|
|
429
|
-
|
|
430
|
-
|
|
431
|
-
|
|
432
|
-
|
|
433
|
-
|
|
434
|
-
|
|
435
|
-
|
|
436
|
-
|
|
437
|
-
|
|
438
|
-
|
|
439
|
-
|
|
440
|
-
|
|
441
|
-
|
|
442
|
-
|
|
443
|
-
|
|
444
|
-
|
|
445
|
-
if (
|
|
446
|
-
|
|
447
|
-
|
|
448
|
-
|
|
449
|
-
|
|
450
|
-
|
|
451
|
-
|
|
452
|
-
|
|
453
|
-
|
|
454
|
-
|
|
455
|
-
|
|
456
|
-
|
|
457
|
-
|
|
458
|
-
|
|
459
|
-
|
|
460
|
-
|
|
461
|
-
|
|
462
|
-
|
|
463
|
-
const
|
|
464
|
-
|
|
465
|
-
|
|
466
|
-
|
|
467
|
-
|
|
468
|
-
|
|
469
|
-
|
|
470
|
-
|
|
471
|
-
|
|
472
|
-
for (const node of active) {
|
|
473
|
-
|
|
474
|
-
|
|
475
|
-
|
|
476
|
-
|
|
477
|
-
|
|
478
|
-
node.
|
|
479
|
-
|
|
480
|
-
|
|
481
|
-
|
|
482
|
-
//
|
|
483
|
-
//
|
|
484
|
-
//
|
|
485
|
-
|
|
486
|
-
|
|
487
|
-
|
|
488
|
-
|
|
489
|
-
|
|
490
|
-
|
|
491
|
-
|
|
492
|
-
|
|
493
|
-
|
|
494
|
-
|
|
495
|
-
if (
|
|
496
|
-
let
|
|
497
|
-
|
|
498
|
-
|
|
499
|
-
|
|
500
|
-
|
|
501
|
-
|
|
502
|
-
|
|
503
|
-
|
|
504
|
-
|
|
505
|
-
|
|
506
|
-
|
|
507
|
-
|
|
508
|
-
|
|
509
|
-
|
|
510
|
-
}
|
|
511
|
-
|
|
512
|
-
|
|
513
|
-
|
|
514
|
-
|
|
515
|
-
|
|
516
|
-
|
|
517
|
-
|
|
518
|
-
|
|
519
|
-
|
|
520
|
-
get
|
|
521
|
-
|
|
522
|
-
|
|
523
|
-
|
|
524
|
-
|
|
525
|
-
|
|
526
|
-
|
|
527
|
-
|
|
528
|
-
|
|
529
|
-
|
|
530
|
-
|
|
531
|
-
|
|
532
|
-
|
|
533
|
-
|
|
534
|
-
|
|
535
|
-
|
|
536
|
-
|
|
537
|
-
|
|
538
|
-
|
|
539
|
-
|
|
540
|
-
|
|
541
|
-
|
|
542
|
-
|
|
543
|
-
|
|
544
|
-
|
|
545
|
-
|
|
546
|
-
|
|
547
|
-
|
|
548
|
-
|
|
549
|
-
|
|
550
|
-
|
|
551
|
-
|
|
552
|
-
|
|
553
|
-
|
|
554
|
-
|
|
555
|
-
|
|
556
|
-
|
|
557
|
-
|
|
558
|
-
|
|
559
|
-
|
|
560
|
-
const
|
|
561
|
-
|
|
562
|
-
|
|
563
|
-
|
|
564
|
-
|
|
565
|
-
|
|
566
|
-
|
|
567
|
-
|
|
568
|
-
|
|
569
|
-
|
|
570
|
-
|
|
571
|
-
|
|
572
|
-
|
|
573
|
-
|
|
574
|
-
|
|
575
|
-
|
|
576
|
-
|
|
577
|
-
|
|
578
|
-
|
|
579
|
-
|
|
580
|
-
|
|
581
|
-
|
|
582
|
-
|
|
583
|
-
|
|
584
|
-
|
|
585
|
-
|
|
586
|
-
|
|
587
|
-
|
|
588
|
-
|
|
589
|
-
|
|
590
|
-
|
|
591
|
-
|
|
592
|
-
|
|
593
|
-
|
|
594
|
-
|
|
595
|
-
|
|
596
|
-
|
|
597
|
-
|
|
598
|
-
|
|
599
|
-
|
|
600
|
-
|
|
601
|
-
},
|
|
602
|
-
|
|
603
|
-
|
|
604
|
-
|
|
605
|
-
|
|
606
|
-
}
|
|
607
|
-
|
|
608
|
-
|
|
609
|
-
|
|
610
|
-
|
|
611
|
-
|
|
612
|
-
|
|
613
|
-
|
|
614
|
-
|
|
615
|
-
|
|
616
|
-
|
|
617
|
-
|
|
618
|
-
|
|
619
|
-
|
|
620
|
-
}
|
|
621
|
-
|
|
622
|
-
|
|
623
|
-
|
|
624
|
-
|
|
625
|
-
|
|
626
|
-
|
|
627
|
-
const
|
|
628
|
-
|
|
629
|
-
|
|
630
|
-
|
|
631
|
-
|
|
632
|
-
|
|
633
|
-
|
|
634
|
-
|
|
635
|
-
|
|
636
|
-
{ x: x
|
|
637
|
-
{ x: x -
|
|
638
|
-
|
|
639
|
-
|
|
640
|
-
|
|
641
|
-
|
|
642
|
-
|
|
643
|
-
|
|
644
|
-
)
|
|
645
|
-
|
|
646
|
-
|
|
647
|
-
|
|
648
|
-
|
|
649
|
-
|
|
650
|
-
|
|
651
|
-
|
|
652
|
-
|
|
653
|
-
}
|
|
654
|
-
|
|
655
|
-
|
|
656
|
-
|
|
657
|
-
|
|
658
|
-
|
|
659
|
-
|
|
660
|
-
const
|
|
661
|
-
|
|
662
|
-
|
|
663
|
-
|
|
664
|
-
const
|
|
665
|
-
|
|
666
|
-
|
|
667
|
-
|
|
668
|
-
|
|
669
|
-
|
|
670
|
-
|
|
671
|
-
|
|
672
|
-
|
|
673
|
-
|
|
674
|
-
|
|
675
|
-
|
|
676
|
-
const
|
|
677
|
-
|
|
678
|
-
|
|
679
|
-
|
|
680
|
-
|
|
681
|
-
|
|
682
|
-
|
|
683
|
-
|
|
684
|
-
|
|
685
|
-
|
|
686
|
-
|
|
687
|
-
|
|
688
|
-
|
|
689
|
-
|
|
690
|
-
|
|
691
|
-
|
|
692
|
-
|
|
693
|
-
|
|
694
|
-
|
|
695
|
-
|
|
696
|
-
|
|
697
|
-
|
|
698
|
-
|
|
699
|
-
|
|
700
|
-
|
|
701
|
-
|
|
702
|
-
|
|
703
|
-
|
|
704
|
-
|
|
705
|
-
if (
|
|
706
|
-
|
|
707
|
-
|
|
708
|
-
tooltip.
|
|
709
|
-
|
|
710
|
-
|
|
711
|
-
|
|
712
|
-
|
|
713
|
-
|
|
714
|
-
|
|
715
|
-
|
|
716
|
-
|
|
717
|
-
|
|
718
|
-
|
|
719
|
-
|
|
720
|
-
|
|
721
|
-
|
|
722
|
-
|
|
723
|
-
|
|
724
|
-
|
|
725
|
-
|
|
726
|
-
|
|
727
|
-
|
|
728
|
-
context.
|
|
729
|
-
|
|
730
|
-
|
|
731
|
-
|
|
732
|
-
context.
|
|
733
|
-
|
|
734
|
-
|
|
735
|
-
|
|
736
|
-
|
|
737
|
-
const
|
|
738
|
-
const
|
|
739
|
-
const
|
|
740
|
-
|
|
741
|
-
|
|
742
|
-
|
|
743
|
-
|
|
744
|
-
|
|
745
|
-
|
|
746
|
-
|
|
747
|
-
|
|
748
|
-
|
|
749
|
-
|
|
750
|
-
|
|
751
|
-
|
|
752
|
-
|
|
753
|
-
|
|
754
|
-
|
|
755
|
-
|
|
756
|
-
const
|
|
757
|
-
const
|
|
758
|
-
|
|
759
|
-
|
|
760
|
-
|
|
761
|
-
|
|
762
|
-
|
|
763
|
-
|
|
764
|
-
|
|
765
|
-
|
|
766
|
-
|
|
767
|
-
|
|
768
|
-
|
|
769
|
-
context.
|
|
770
|
-
context.
|
|
771
|
-
context.setLineDash(
|
|
772
|
-
|
|
773
|
-
|
|
774
|
-
|
|
775
|
-
|
|
776
|
-
|
|
777
|
-
|
|
778
|
-
|
|
779
|
-
|
|
780
|
-
|
|
781
|
-
|
|
782
|
-
|
|
783
|
-
|
|
784
|
-
|
|
785
|
-
|
|
786
|
-
context.
|
|
787
|
-
|
|
788
|
-
|
|
789
|
-
|
|
790
|
-
|
|
791
|
-
|
|
792
|
-
|
|
793
|
-
|
|
794
|
-
|
|
795
|
-
|
|
796
|
-
|
|
797
|
-
|
|
798
|
-
|
|
799
|
-
|
|
800
|
-
|
|
801
|
-
|
|
802
|
-
|
|
803
|
-
|
|
804
|
-
|
|
805
|
-
|
|
806
|
-
|
|
807
|
-
|
|
808
|
-
|
|
809
|
-
|
|
810
|
-
|
|
811
|
-
|
|
812
|
-
|
|
813
|
-
|
|
814
|
-
|
|
815
|
-
|
|
816
|
-
|
|
817
|
-
|
|
818
|
-
|
|
819
|
-
|
|
820
|
-
|
|
821
|
-
|
|
822
|
-
|
|
823
|
-
|
|
824
|
-
|
|
825
|
-
|
|
826
|
-
|
|
827
|
-
|
|
828
|
-
|
|
829
|
-
|
|
830
|
-
|
|
831
|
-
|
|
832
|
-
|
|
833
|
-
|
|
834
|
-
|
|
835
|
-
|
|
836
|
-
|
|
837
|
-
|
|
838
|
-
|
|
839
|
-
|
|
840
|
-
|
|
841
|
-
|
|
842
|
-
|
|
843
|
-
const
|
|
844
|
-
context.
|
|
845
|
-
|
|
846
|
-
|
|
847
|
-
|
|
848
|
-
|
|
849
|
-
|
|
850
|
-
|
|
851
|
-
|
|
852
|
-
|
|
853
|
-
|
|
854
|
-
|
|
855
|
-
|
|
856
|
-
context.
|
|
857
|
-
context.
|
|
858
|
-
context.
|
|
859
|
-
context.
|
|
860
|
-
|
|
861
|
-
|
|
862
|
-
|
|
863
|
-
|
|
864
|
-
|
|
865
|
-
|
|
866
|
-
|
|
867
|
-
|
|
868
|
-
|
|
869
|
-
|
|
870
|
-
context.
|
|
871
|
-
context.
|
|
872
|
-
}
|
|
873
|
-
if (node.
|
|
874
|
-
context.
|
|
875
|
-
context.
|
|
876
|
-
}
|
|
877
|
-
|
|
878
|
-
|
|
879
|
-
context.
|
|
880
|
-
|
|
881
|
-
|
|
882
|
-
|
|
883
|
-
|
|
884
|
-
|
|
885
|
-
|
|
886
|
-
|
|
887
|
-
|
|
888
|
-
|
|
889
|
-
|
|
890
|
-
|
|
891
|
-
|
|
892
|
-
|
|
893
|
-
|
|
894
|
-
const
|
|
895
|
-
const
|
|
896
|
-
const
|
|
897
|
-
const
|
|
898
|
-
|
|
899
|
-
|
|
900
|
-
const
|
|
901
|
-
|
|
902
|
-
|
|
903
|
-
|
|
904
|
-
const
|
|
905
|
-
|
|
906
|
-
|
|
907
|
-
|
|
908
|
-
|
|
909
|
-
|
|
910
|
-
|
|
911
|
-
|
|
912
|
-
|
|
913
|
-
|
|
914
|
-
|
|
915
|
-
|
|
916
|
-
|
|
917
|
-
|
|
918
|
-
|
|
919
|
-
|
|
920
|
-
|
|
921
|
-
|
|
922
|
-
|
|
923
|
-
|
|
924
|
-
context.
|
|
925
|
-
|
|
926
|
-
|
|
927
|
-
|
|
928
|
-
|
|
929
|
-
|
|
930
|
-
|
|
931
|
-
|
|
932
|
-
|
|
933
|
-
|
|
934
|
-
|
|
935
|
-
|
|
936
|
-
|
|
937
|
-
|
|
938
|
-
|
|
939
|
-
|
|
940
|
-
|
|
941
|
-
|
|
942
|
-
|
|
943
|
-
|
|
944
|
-
|
|
945
|
-
|
|
946
|
-
|
|
947
|
-
|
|
948
|
-
|
|
949
|
-
|
|
950
|
-
|
|
951
|
-
|
|
952
|
-
|
|
953
|
-
|
|
954
|
-
|
|
955
|
-
|
|
956
|
-
|
|
957
|
-
|
|
958
|
-
|
|
959
|
-
|
|
960
|
-
|
|
961
|
-
|
|
962
|
-
}
|
|
963
|
-
|
|
964
|
-
|
|
965
|
-
|
|
966
|
-
|
|
967
|
-
|
|
968
|
-
|
|
969
|
-
|
|
970
|
-
|
|
971
|
-
|
|
972
|
-
|
|
973
|
-
|
|
974
|
-
|
|
975
|
-
|
|
976
|
-
|
|
977
|
-
|
|
978
|
-
|
|
979
|
-
|
|
980
|
-
|
|
981
|
-
|
|
982
|
-
|
|
983
|
-
|
|
984
|
-
|
|
985
|
-
|
|
986
|
-
event.
|
|
987
|
-
|
|
988
|
-
const
|
|
989
|
-
|
|
990
|
-
|
|
991
|
-
|
|
992
|
-
const
|
|
993
|
-
|
|
994
|
-
|
|
995
|
-
|
|
996
|
-
|
|
997
|
-
|
|
998
|
-
|
|
999
|
-
|
|
1000
|
-
|
|
1001
|
-
|
|
1002
|
-
|
|
1003
|
-
|
|
1004
|
-
|
|
1005
|
-
|
|
1006
|
-
|
|
1007
|
-
|
|
1008
|
-
|
|
1009
|
-
|
|
1010
|
-
|
|
1011
|
-
|
|
1012
|
-
|
|
1013
|
-
|
|
1014
|
-
|
|
1015
|
-
|
|
1016
|
-
|
|
1017
|
-
|
|
1018
|
-
|
|
1019
|
-
|
|
1020
|
-
|
|
1021
|
-
|
|
1022
|
-
|
|
1023
|
-
|
|
1024
|
-
|
|
1025
|
-
|
|
1026
|
-
|
|
1027
|
-
|
|
1028
|
-
|
|
1029
|
-
|
|
1030
|
-
|
|
1031
|
-
|
|
1032
|
-
|
|
1033
|
-
|
|
1034
|
-
|
|
1035
|
-
|
|
1036
|
-
|
|
1037
|
-
|
|
1038
|
-
|
|
1039
|
-
|
|
1040
|
-
if (
|
|
1041
|
-
|
|
1042
|
-
|
|
1043
|
-
|
|
1044
|
-
|
|
1045
|
-
//
|
|
1046
|
-
|
|
1047
|
-
|
|
1048
|
-
|
|
1049
|
-
|
|
1050
|
-
|
|
1051
|
-
|
|
1052
|
-
|
|
1053
|
-
|
|
1054
|
-
|
|
1055
|
-
|
|
1056
|
-
|
|
1057
|
-
|
|
1058
|
-
|
|
1059
|
-
|
|
1060
|
-
|
|
1061
|
-
|
|
1062
|
-
|
|
1063
|
-
|
|
1064
|
-
|
|
1065
|
-
|
|
1066
|
-
|
|
1067
|
-
if (
|
|
1068
|
-
|
|
1069
|
-
|
|
1070
|
-
|
|
1071
|
-
|
|
1072
|
-
|
|
1073
|
-
|
|
1074
|
-
}
|
|
1075
|
-
|
|
1076
|
-
|
|
1077
|
-
|
|
1078
|
-
}
|
|
1079
|
-
|
|
1080
|
-
listen(canvas, '
|
|
1081
|
-
|
|
1082
|
-
|
|
1083
|
-
|
|
1084
|
-
|
|
1085
|
-
|
|
1086
|
-
|
|
1087
|
-
if (
|
|
1088
|
-
|
|
1089
|
-
|
|
1090
|
-
|
|
1091
|
-
|
|
1092
|
-
|
|
1093
|
-
|
|
1094
|
-
|
|
1095
|
-
|
|
1096
|
-
|
|
1097
|
-
|
|
1098
|
-
|
|
1099
|
-
|
|
1100
|
-
|
|
1101
|
-
|
|
1102
|
-
else if (
|
|
1103
|
-
|
|
1104
|
-
|
|
1105
|
-
|
|
1106
|
-
|
|
1107
|
-
|
|
1108
|
-
|
|
1109
|
-
|
|
1110
|
-
|
|
1111
|
-
|
|
1112
|
-
|
|
1113
|
-
|
|
1114
|
-
|
|
1115
|
-
|
|
1116
|
-
|
|
1117
|
-
|
|
1118
|
-
|
|
1119
|
-
|
|
1120
|
-
|
|
1121
|
-
|
|
1122
|
-
|
|
1123
|
-
|
|
1124
|
-
|
|
1125
|
-
|
|
1126
|
-
|
|
1127
|
-
|
|
1128
|
-
|
|
1129
|
-
|
|
1130
|
-
|
|
1131
|
-
|
|
1132
|
-
|
|
1133
|
-
|
|
1134
|
-
|
|
1135
|
-
|
|
1136
|
-
|
|
1137
|
-
|
|
1138
|
-
|
|
1139
|
-
|
|
1140
|
-
|
|
1141
|
-
|
|
1142
|
-
|
|
1143
|
-
|
|
1144
|
-
|
|
1145
|
-
|
|
1146
|
-
|
|
1147
|
-
|
|
1148
|
-
|
|
1149
|
-
|
|
1150
|
-
|
|
1151
|
-
|
|
1152
|
-
|
|
1153
|
-
|
|
1154
|
-
|
|
1155
|
-
|
|
1156
|
-
|
|
1157
|
-
|
|
1158
|
-
|
|
1159
|
-
|
|
1160
|
-
|
|
1161
|
-
|
|
1162
|
-
|
|
1163
|
-
|
|
1164
|
-
|
|
1165
|
-
|
|
1166
|
-
|
|
1167
|
-
|
|
1168
|
-
|
|
1169
|
-
|
|
1170
|
-
|
|
1171
|
-
|
|
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
|
+
}
|