dsh-macro-memory 0.0.0-stage → 0.4.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (132) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +506 -2
  3. package/cordis.patch.yml +6 -0
  4. package/lib/client.js +3623 -0
  5. package/lib/index.js +502 -0
  6. package/lib/macro/brand.js +82 -0
  7. package/lib/macro/bridge.js +158 -0
  8. package/lib/macro/chain.js +206 -0
  9. package/lib/macro/contract.js +471 -0
  10. package/lib/macro/cost.js +164 -0
  11. package/lib/macro/defs/admin.js +442 -0
  12. package/lib/macro/defs/dream.js +24 -0
  13. package/lib/macro/defs/link.js +257 -0
  14. package/lib/macro/defs/project.js +25 -0
  15. package/lib/macro/defs/read.js +160 -0
  16. package/lib/macro/defs/remember.js +411 -0
  17. package/lib/macro/defs/search.js +871 -0
  18. package/lib/macro/defs/update.js +161 -0
  19. package/lib/macro/dreamledger.js +1398 -0
  20. package/lib/macro/facade.js +135 -0
  21. package/lib/macro/fusion.js +182 -0
  22. package/lib/macro/linkflow.js +391 -0
  23. package/lib/macro/links.js +448 -0
  24. package/lib/macro/neighbor.js +209 -0
  25. package/lib/macro/panel.js +96 -0
  26. package/lib/macro/prompt.js +139 -0
  27. package/lib/macro/provenance.js +148 -0
  28. package/lib/macro/render.js +35 -0
  29. package/lib/macro/revisions.js +253 -0
  30. package/lib/macro/shared.js +113 -0
  31. package/lib/macro/store.js +103 -0
  32. package/lib/macro/supersede.js +197 -0
  33. package/lib/macro/tokencost.js +90 -0
  34. package/lib/macro/tools.js +67 -0
  35. package/package.json +54 -4
  36. package/vendor/VENDOR.json +23 -0
  37. package/vendor/dsh-memory-nebula/CONTRIBUTING.md +48 -0
  38. package/vendor/dsh-memory-nebula/LICENSE +21 -0
  39. package/vendor/dsh-memory-nebula/README.en.md +203 -0
  40. package/vendor/dsh-memory-nebula/README.md +253 -0
  41. package/vendor/dsh-memory-nebula/SECURITY.md +43 -0
  42. package/vendor/dsh-memory-nebula/SUPPORT.md +33 -0
  43. package/vendor/dsh-memory-nebula/cordis.patch.yml +4 -0
  44. package/vendor/dsh-memory-nebula/lib/client.js +105 -0
  45. package/vendor/dsh-memory-nebula/lib/host/adapters/index.js +279 -0
  46. package/vendor/dsh-memory-nebula/lib/host/adapters/ingest.js +230 -0
  47. package/vendor/dsh-memory-nebula/lib/host/adapters/meow.js +320 -0
  48. package/vendor/dsh-memory-nebula/lib/host/adapters/notes.js +305 -0
  49. package/vendor/dsh-memory-nebula/lib/host/adapters/sqlite.js +287 -0
  50. package/vendor/dsh-memory-nebula/lib/host/adapters/util.js +231 -0
  51. package/vendor/dsh-memory-nebula/lib/host/bridge.js +351 -0
  52. package/vendor/dsh-memory-nebula/lib/host/compress.js +97 -0
  53. package/vendor/dsh-memory-nebula/lib/host/demo.js +357 -0
  54. package/vendor/dsh-memory-nebula/lib/host/diagnostics.js +125 -0
  55. package/vendor/dsh-memory-nebula/lib/host/doctor.js +270 -0
  56. package/vendor/dsh-memory-nebula/lib/host/entities.js +230 -0
  57. package/vendor/dsh-memory-nebula/lib/host/graph.js +1762 -0
  58. package/vendor/dsh-memory-nebula/lib/host/graphcache.js +290 -0
  59. package/vendor/dsh-memory-nebula/lib/host/http.js +993 -0
  60. package/vendor/dsh-memory-nebula/lib/host/injectcfg.js +95 -0
  61. package/vendor/dsh-memory-nebula/lib/host/ledger.js +175 -0
  62. package/vendor/dsh-memory-nebula/lib/host/live.js +204 -0
  63. package/vendor/dsh-memory-nebula/lib/host/nebula.js +2105 -0
  64. package/vendor/dsh-memory-nebula/lib/host/page.js +75 -0
  65. package/vendor/dsh-memory-nebula/lib/host/path.js +83 -0
  66. package/vendor/dsh-memory-nebula/lib/host/recall.js +524 -0
  67. package/vendor/dsh-memory-nebula/lib/host/share.js +633 -0
  68. package/vendor/dsh-memory-nebula/lib/host/sources.js +266 -0
  69. package/vendor/dsh-memory-nebula/lib/host/store.js +333 -0
  70. package/vendor/dsh-memory-nebula/lib/host/text.js +410 -0
  71. package/vendor/dsh-memory-nebula/lib/host/transcripts.js +396 -0
  72. package/vendor/dsh-memory-nebula/lib/index.js +782 -0
  73. package/vendor/dsh-memory-nebula/lib/standalone.mjs +315 -0
  74. package/vendor/dsh-memory-nebula/lib/web/api.js +426 -0
  75. package/vendor/dsh-memory-nebula/lib/web/app.js +4172 -0
  76. package/vendor/dsh-memory-nebula/lib/web/i18n.js +580 -0
  77. package/vendor/dsh-memory-nebula/lib/web/index.html +174 -0
  78. package/vendor/dsh-memory-nebula/lib/web/nav.js +132 -0
  79. package/vendor/dsh-memory-nebula/lib/web/render.js +1890 -0
  80. package/vendor/dsh-memory-nebula/lib/web/space3d.js +1883 -0
  81. package/vendor/dsh-memory-nebula/lib/web/style.css +1402 -0
  82. package/vendor/dsh-memory-nebula/locale/en.json +7 -0
  83. package/vendor/dsh-memory-nebula/locale/zh.json +7 -0
  84. package/vendor/dsh-memory-nebula/market/assets/icon-180.png +0 -0
  85. package/vendor/dsh-memory-nebula/market/assets/icon.svg +40 -0
  86. package/vendor/dsh-memory-nebula/market/index.json +101 -0
  87. package/vendor/dsh-memory-nebula/package.json +87 -0
  88. package/vendor/dsh-memory-nebula/sidecar.ps1 +119 -0
  89. package/vendor/meow-memory/LICENSE +21 -0
  90. package/vendor/meow-memory/README.en.md +192 -0
  91. package/vendor/meow-memory/README.md +174 -0
  92. package/vendor/meow-memory/README.pt-br.md +180 -0
  93. package/vendor/meow-memory/cordis.patch.yml +7 -0
  94. package/vendor/meow-memory/lib/client.js +3344 -0
  95. package/vendor/meow-memory/lib/client.js.map +7 -0
  96. package/vendor/meow-memory/lib/index.js +9802 -0
  97. package/vendor/meow-memory/lib/index.js.map +7 -0
  98. package/vendor/meow-memory/lib/prompts/README.md +65 -0
  99. package/vendor/meow-memory/lib/prompts/en/dream-atomic.md +36 -0
  100. package/vendor/meow-memory/lib/prompts/en/dream-header.md +9 -0
  101. package/vendor/meow-memory/lib/prompts/en/dream-project-summary.md +12 -0
  102. package/vendor/meow-memory/lib/prompts/en/dream-topic.md +27 -0
  103. package/vendor/meow-memory/lib/prompts/en/external-memory-notice.md +8 -0
  104. package/vendor/meow-memory/lib/prompts/en/first-create-notice.md +8 -0
  105. package/vendor/meow-memory/lib/prompts/en/labels.md +98 -0
  106. package/vendor/meow-memory/lib/prompts/en/reflect.md +31 -0
  107. package/vendor/meow-memory/lib/prompts/en/system-guide.md +121 -0
  108. package/vendor/meow-memory/lib/prompts/en/tools.md +83 -0
  109. package/vendor/meow-memory/lib/prompts/en/welcome-guide.md +12 -0
  110. package/vendor/meow-memory/lib/prompts/pt-br/dream-atomic.md +36 -0
  111. package/vendor/meow-memory/lib/prompts/pt-br/dream-header.md +9 -0
  112. package/vendor/meow-memory/lib/prompts/pt-br/dream-project-summary.md +12 -0
  113. package/vendor/meow-memory/lib/prompts/pt-br/dream-topic.md +27 -0
  114. package/vendor/meow-memory/lib/prompts/pt-br/external-memory-notice.md +8 -0
  115. package/vendor/meow-memory/lib/prompts/pt-br/first-create-notice.md +8 -0
  116. package/vendor/meow-memory/lib/prompts/pt-br/labels.md +98 -0
  117. package/vendor/meow-memory/lib/prompts/pt-br/reflect.md +31 -0
  118. package/vendor/meow-memory/lib/prompts/pt-br/system-guide.md +121 -0
  119. package/vendor/meow-memory/lib/prompts/pt-br/tools.md +83 -0
  120. package/vendor/meow-memory/lib/prompts/pt-br/welcome-guide.md +12 -0
  121. package/vendor/meow-memory/lib/prompts/zh/dream-atomic.md +36 -0
  122. package/vendor/meow-memory/lib/prompts/zh/dream-header.md +9 -0
  123. package/vendor/meow-memory/lib/prompts/zh/dream-project-summary.md +19 -0
  124. package/vendor/meow-memory/lib/prompts/zh/dream-topic.md +27 -0
  125. package/vendor/meow-memory/lib/prompts/zh/external-memory-notice.md +8 -0
  126. package/vendor/meow-memory/lib/prompts/zh/first-create-notice.md +8 -0
  127. package/vendor/meow-memory/lib/prompts/zh/labels.md +98 -0
  128. package/vendor/meow-memory/lib/prompts/zh/reflect.md +30 -0
  129. package/vendor/meow-memory/lib/prompts/zh/system-guide.md +119 -0
  130. package/vendor/meow-memory/lib/prompts/zh/tools.md +83 -0
  131. package/vendor/meow-memory/lib/prompts/zh/welcome-guide.md +12 -0
  132. package/vendor/meow-memory/package.json +64 -0
@@ -0,0 +1,1890 @@
1
+ /* REV_20261107_A */
2
+ /* 宏记忆 · 星图 —— 渲染层
3
+ 一个 canvas 干完所有事:力导向布局、发光节点、曲线连边、脉冲扩散。
4
+ 没有依赖,没有构建步骤。 */
5
+ (function () {
6
+ 'use strict'
7
+ /** 中文即源文:英文模式查 i18n.js 的表,查不到就原样返回中文。 */
8
+ const T = (zh, vars) => (window.NebulaI18n ? window.NebulaI18n.t(zh, vars) : zh)
9
+ const N = (window.Nebula = window.Nebula || {})
10
+
11
+ /** 每层记忆的颜色(与 CSS 强调色一致)。 */
12
+ const LEVEL_COLOR = {
13
+ soul: '#ffd88a',
14
+ user: '#7ff0c8',
15
+ project: '#6cc8ff',
16
+ lesson: '#ff9f7a',
17
+ topic: '#c39bff',
18
+ fact: '#9fb6cc',
19
+ rules: '#ff8fb0',
20
+ source: '#8ce0ff',
21
+ }
22
+
23
+ const TYPE_COLOR = {
24
+ explicit: '#ffd88a',
25
+ project: '#6cc8ff',
26
+ entity: '#7ff0c8',
27
+ keyword: '#c39bff',
28
+ semantic: '#79e0b6',
29
+ hebbian: '#ffa26b',
30
+ mentions: '#8ce0ff',
31
+ }
32
+
33
+ function hexToRgb(hex) {
34
+ const h = String(hex || '#ffffff').replace('#', '')
35
+ const v = h.length === 3 ? h.split('').map((c) => c + c).join('') : h
36
+ const n = parseInt(v, 16)
37
+ return [(n >> 16) & 255, (n >> 8) & 255, n & 255]
38
+ }
39
+ function rgba(hex, a) {
40
+ const [r, g, b] = hexToRgb(hex)
41
+ return `rgba(${r},${g},${b},${a})`
42
+ }
43
+
44
+ // 光点贴图缓存:同一个层级色只渲染一次发光球,之后靠 drawImage 缩放复用。
45
+ // 900+ 节点每帧各建两个径向渐变太贵,这是缩放卡顿的主因。
46
+ const SPRITE_CACHE = new Map()
47
+ const SPRITE_SIZE = 128
48
+ // 交互期用的整帧快照按半分辨率抓,贴回去时放大 —— 软件渲染下省一半像素填充
49
+ const NODE_MIN_R = 1.3
50
+ function nodeSprite(color) {
51
+ const key = color || '#9fb6cc'
52
+ const hit = SPRITE_CACHE.get(key)
53
+ if (hit) return hit
54
+ const cv = document.createElement('canvas')
55
+ cv.width = SPRITE_SIZE
56
+ cv.height = SPRITE_SIZE
57
+ const g2 = cv.getContext('2d')
58
+ const [r, g, b] = hexToRgb(key)
59
+ const mid = SPRITE_SIZE / 2
60
+ // 外发光(占满整张图)
61
+ const gr = g2.createRadialGradient(mid, mid, 0, mid, mid, mid)
62
+ gr.addColorStop(0, `rgba(${r},${g},${b},0.5)`)
63
+ gr.addColorStop(0.22, `rgba(${r},${g},${b},0.2)`)
64
+ gr.addColorStop(0.6, `rgba(${r},${g},${b},0.045)`)
65
+ gr.addColorStop(1, `rgba(${r},${g},${b},0)`)
66
+ g2.fillStyle = gr
67
+ g2.beginPath()
68
+ g2.arc(mid, mid, mid, 0, 6.2832)
69
+ g2.fill()
70
+ // 核心用「本色」不加白:一堆光点叠在一起时才不会被叠成一片白
71
+ const core = mid * 0.2
72
+ const gc = g2.createRadialGradient(mid, mid, 0, mid, mid, core)
73
+ gc.addColorStop(0, `rgba(${r},${g},${b},0.98)`)
74
+ gc.addColorStop(0.6, `rgba(${r},${g},${b},0.7)`)
75
+ gc.addColorStop(1, `rgba(${r},${g},${b},0)`)
76
+ g2.fillStyle = gc
77
+ g2.beginPath()
78
+ g2.arc(mid, mid, core, 0, 6.2832)
79
+ g2.fill()
80
+ SPRITE_CACHE.set(key, cv)
81
+ return cv
82
+ }
83
+
84
+ /** 32 位整数哈希,用来做确定性抖动。 */
85
+ function h32(str) {
86
+ let h = 2166136261 >>> 0
87
+ const s = String(str)
88
+ for (let i = 0; i < s.length; i++) {
89
+ h ^= s.charCodeAt(i)
90
+ h = Math.imul(h, 16777619) >>> 0
91
+ }
92
+ return h >>> 0
93
+ }
94
+
95
+ N.stage = function createStage(canvas, opts) {
96
+ const state = {
97
+ graph: null,
98
+ nodes: [],
99
+ edges: [],
100
+ byId: new Map(),
101
+ clusters: [],
102
+ cam: { x: 0, y: 0, k: 1 },
103
+ target: null,
104
+ hover: null,
105
+ selected: null,
106
+ highlight: null,
107
+ pathSeq: null,
108
+ pathIds: null,
109
+ pathEdges: null,
110
+ filter: null,
111
+ mode: 'nebula',
112
+ pulses: [],
113
+ labels: true,
114
+ dpr: 1,
115
+ w: 0,
116
+ h: 0,
117
+ listeners: {},
118
+ moving: false,
119
+ alpha: 1,
120
+ drag: null,
121
+ pointer: { x: 0, y: 0 },
122
+ stars: [],
123
+ lastFrame: 0,
124
+ fps: 0,
125
+ }
126
+
127
+ const ctx = canvas.getContext('2d')
128
+ const emit = (name, arg) => {
129
+ const fn = state.listeners[name]
130
+ if (fn) fn(arg)
131
+ }
132
+ const api = { on: (n, f) => ((state.listeners[n] = f), api), get state() { return state } }
133
+
134
+ // ---------------- 尺寸 ----------------
135
+ function resize() {
136
+ const rect = canvas.getBoundingClientRect()
137
+ // 画布被 display:none(切到 3D)时 rect 是 0×0。这时如果照常写后备缓冲,
138
+ // 会把它改成 1×1;等切回 2D 就只剩一张空画布。隐藏时直接跳过,可见时再量。
139
+ if (rect.width < 2 || rect.height < 2) return false
140
+ state.dpr = Math.min(2, window.devicePixelRatio || 1)
141
+ state.w = rect.width
142
+ state.h = rect.height
143
+ canvas.width = Math.round(state.w * state.dpr)
144
+ canvas.height = Math.round(state.h * state.dpr)
145
+ ctx.setTransform(state.dpr, 0, 0, state.dpr, 0, 0)
146
+ buildStars()
147
+ draw()
148
+ return true
149
+ }
150
+
151
+ /** 背景星尘:屏幕坐标,跟着镜头做极慢视差。 */
152
+ function buildStars() {
153
+ const count = Math.round((state.w * state.h) / 9000)
154
+ const out = []
155
+ for (let i = 0; i < count; i++) {
156
+ const r = Math.random()
157
+ out.push({
158
+ x: Math.random() * state.w,
159
+ y: Math.random() * state.h,
160
+ r: r < 0.86 ? 0.6 : r < 0.97 ? 1.1 : 1.7,
161
+ a: 0.12 + Math.random() * 0.5,
162
+ p: 0.15 + Math.random() * 0.85,
163
+ tw: Math.random() * Math.PI * 2,
164
+ })
165
+ }
166
+ state.stars = out
167
+ }
168
+
169
+ // ---------------- 布局 ----------------
170
+ function initLayout() {
171
+ const nodes = state.nodes
172
+ const clusters = state.clusters
173
+ if (!clusters.length) return
174
+ // 每个簇按记忆条数估半径(面积 ∝ 条数);最大的簇坐中心,其余围一圈,
175
+ // 圈半径 = 中心簇半径 ×0.9 + 自己半径 + 间距,保证互不吞并。
176
+ const counts = new Map()
177
+ for (const n of nodes) counts.set(n.cluster, (counts.get(n.cluster) || 0) + 1)
178
+ for (const c of clusters) c._n = counts.get(c.id) || 1
179
+ const radiusOf = (c) => 50 + Math.sqrt(c._n) * 19
180
+ for (const c of clusters) c._rad = radiusOf(c)
181
+ const order = clusters.slice().sort((a, b) => b._n - a._n)
182
+ const hub = order[0]
183
+ const satellites = order.slice(1)
184
+ hub._cx = 0
185
+ hub._cy = 0
186
+ satellites.forEach((c, i) => {
187
+ const ang = (i / Math.max(1, satellites.length)) * Math.PI * 2 - Math.PI / 2
188
+ // 圆心距 = 两团半径之和 + 间距,保证边缘不打架
189
+ const r = hub._rad + c._rad + 200
190
+ c._cx = Math.cos(ang) * r * 1.06
191
+ c._cy = Math.sin(ang) * r
192
+ })
193
+ const cIndex = new Map(clusters.map((c, i) => [c.id, i]))
194
+ for (const node of nodes) {
195
+ const ci = cIndex.get(node.cluster) || 0
196
+ const c = clusters[ci] || { _cx: 0, _cy: 0, _rad: 120 }
197
+ const rnd = h32(node.id) >>> 0
198
+ const a = ((rnd % 1000) / 1000) * Math.PI * 2
199
+ // 注意:h32 是无符号 32 位,右移必须用 >>>,用 >> 会移出负数 → sqrt(负) = NaN
200
+ // (曾因此让一半节点成为 NaN 坐标,抽取时整屏只剩一团)
201
+ let rad = Math.sqrt(((rnd >>> 10) % 1000) / 1000) * (c._rad || 120)
202
+ if (!isFinite(rad)) rad = (c._rad || 120) * 0.5
203
+ node.x = c._cx + Math.cos(a) * rad
204
+ node.y = c._cy + Math.sin(a) * rad
205
+ if (!isFinite(node.x) || !isFinite(node.y)) {
206
+ node.x = c._cx || 0
207
+ node.y = c._cy || 0
208
+ }
209
+ node.vx = 0
210
+ node.vy = 0
211
+ node.r = nodeRadius(node)
212
+ node.color = LEVEL_COLOR[node.level] || '#9fb6cc'
213
+ node.rgb = hexToRgb(node.color)
214
+ }
215
+ }
216
+
217
+ function nodeRadius(node) {
218
+ const base = 1.35 + (node.heat || 0.4) * 3.4 + (node.importance || 1) * 0.5
219
+ return Math.min(7.2, base)
220
+ }
221
+
222
+ /** 力导向:网格加速的斥力 + 弹簧 + 簇心引力。 */
223
+ function simulate(ticks, decay) {
224
+ const nodes = state.nodes
225
+ if (!nodes.length) return
226
+ const edges = state.edges
227
+ const clusters = state.clusters
228
+ const cMap = new Map()
229
+ for (const c of clusters) cMap.set(c.id, c)
230
+ const degree = new Map()
231
+ const pairW = new Map()
232
+ for (const e of edges) {
233
+ degree.set(e.a, (degree.get(e.a) || 0) + 1)
234
+ degree.set(e.b, (degree.get(e.b) || 0) + 1)
235
+ // 记住每对节点之间最强的证据权重:关系越铁,两个点就该挨得越近
236
+ const key = e.a < e.b ? e.a + '|' + e.b : e.b + '|' + e.a
237
+ const w = e.w || 0.3
238
+ if (!pairW.has(key) || pairW.get(key) < w) pairW.set(key, w)
239
+ }
240
+
241
+ for (let t = 0; t < ticks; t++) {
242
+ const alpha = state.alpha
243
+ // 1) 斥力(网格)
244
+ const cell = 110
245
+ const grid = new Map()
246
+ for (const n of nodes) {
247
+ const gx = Math.floor(n.x / cell)
248
+ const gy = Math.floor(n.y / cell)
249
+ const key = gx + ',' + gy
250
+ let bucket = grid.get(key)
251
+ if (!bucket) grid.set(key, (bucket = []))
252
+ bucket.push(n)
253
+ }
254
+ for (const n of nodes) {
255
+ const gx = Math.floor(n.x / cell)
256
+ const gy = Math.floor(n.y / cell)
257
+ for (let dx = -1; dx <= 1; dx++) {
258
+ for (let dy = -1; dy <= 1; dy++) {
259
+ const bucket = grid.get(gx + dx + ',' + (gy + dy))
260
+ if (!bucket) continue
261
+ for (const m of bucket) {
262
+ if (m === n) continue
263
+ let ddx = n.x - m.x
264
+ let ddy = n.y - m.y
265
+ let d2 = ddx * ddx + ddy * ddy
266
+ if (d2 > 40000 || d2 <= 0.0001) continue
267
+ const d = Math.sqrt(d2)
268
+ const rep = (900 * alpha) / d2
269
+ const f = Math.min(4.2, rep)
270
+ n.vx += (ddx / d) * f
271
+ n.vy += (ddy / d) * f
272
+ }
273
+ }
274
+ }
275
+ }
276
+ // 2) 弹簧(跨簇的拉得更软,避免把两个簇拽到一起)
277
+ for (const e of edges) {
278
+ const a = e._a
279
+ const b = e._b
280
+ if (!a || !b) continue
281
+ const cross = a.cluster !== b.cluster
282
+ let ddx = b.x - a.x
283
+ let ddy = b.y - a.y
284
+ const d = Math.sqrt(ddx * ddx + ddy * ddy) || 0.001
285
+ // 静止长度也按权重来:证据越强,弹簧越短(关系越近)
286
+ const ww = e.w || 0.4
287
+ const target = (cross ? 46 : 26) + (cross ? 130 : 96) * Math.pow(1 - ww, 1.35)
288
+ const k = ((cross ? 0.004 : 0.012) + 0.05 * ww) * alpha
289
+ const f = (d - target) * k
290
+ ddx /= d
291
+ ddy /= d
292
+ a.vx += ddx * f
293
+ a.vy += ddy * f
294
+ b.vx -= ddx * f
295
+ b.vy -= ddy * f
296
+ }
297
+ // 3) 簇锚点引力 + 越界回拉 + 阻尼
298
+ for (const n of nodes) {
299
+ const c = cMap.get(n.cluster)
300
+ if (c) {
301
+ const ax = c._cx || 0
302
+ const ay = c._cy || 0
303
+ n.vx += (ax - n.x) * 0.034 * alpha
304
+ n.vy += (ay - n.y) * 0.034 * alpha
305
+ const dist = Math.hypot(n.x - ax, n.y - ay)
306
+ const limit = (c._rad || 140) * 1.0
307
+ if (isFinite(dist) && dist > limit) {
308
+ // 硬边界:超出簇半径就把节点往回按(^1.6 的力,越界越多越强)
309
+ const over = dist - limit
310
+ const pull = Math.min(58, over * 0.16 + over * over * 0.0009) * alpha
311
+ n.vx -= ((n.x - ax) / dist) * pull
312
+ n.vy -= ((n.y - ay) / dist) * pull
313
+ }
314
+ }
315
+ const damp = 0.86
316
+ n.vx *= damp
317
+ n.vy *= damp
318
+ const max = 14
319
+ if (!isFinite(n.vx)) n.vx = 0
320
+ if (!isFinite(n.vy)) n.vy = 0
321
+ if (n.vx > max) n.vx = max
322
+ if (n.vx < -max) n.vx = -max
323
+ if (n.vy > max) n.vy = max
324
+ if (n.vy < -max) n.vy = -max
325
+ if (n.pinned) continue
326
+ n.x += n.vx + (Math.random() - 0.5) * 0.6
327
+ n.y += n.vy + (Math.random() - 0.5) * 0.6
328
+ if (!isFinite(n.x) || !isFinite(n.y)) {
329
+ const bx = (c && c._cx) || 0
330
+ const by = (c && c._cy) || 0
331
+ const rr = (c && c._rad ? c._rad : 120) * 0.6
332
+ n.x = bx + (Math.random() - 0.5) * rr
333
+ n.y = by + (Math.random() - 0.5) * rr
334
+ n.vx = 0
335
+ n.vy = 0
336
+ }
337
+ }
338
+ // 4) 硬分离:每对节点留一个最小间距,别挤成密密麻麻一坨
339
+ for (let pass = 0; pass < 2; pass++) {
340
+ const cell2 = 42
341
+ const grid2 = new Map()
342
+ for (const n of nodes) {
343
+ const gx = Math.floor(n.x / cell2)
344
+ const gy = Math.floor(n.y / cell2)
345
+ const key = gx + ',' + gy
346
+ let bucket = grid2.get(key)
347
+ if (!bucket) grid2.set(key, (bucket = []))
348
+ bucket.push(n)
349
+ }
350
+ for (const n of nodes) {
351
+ if (n.pinned) continue
352
+ const gx = Math.floor(n.x / cell2)
353
+ const gy = Math.floor(n.y / cell2)
354
+ for (let dx = -1; dx <= 1; dx++) {
355
+ for (let dy = -1; dy <= 1; dy++) {
356
+ const bucket = grid2.get(gx + dx + ',' + (gy + dy))
357
+ if (!bucket) continue
358
+ for (const m of bucket) {
359
+ if (m === n) continue
360
+ let ddx = n.x - m.x
361
+ let ddy = n.y - m.y
362
+ let d2 = ddx * ddx + ddy * ddy
363
+ // 间距由「关系有多紧」决定:铁关系挨着,没关系的才疏开
364
+ const pk = n.id < m.id ? n.id + '|' + m.id : m.id + '|' + n.id
365
+ const pw = pairW.get(pk)
366
+ const minSep = (pw == null ? 52 : 26 + 44 * (1 - pw)) + (n.r || 2) + (m.r || 2)
367
+ if (d2 >= minSep * minSep) continue
368
+ if (d2 <= 0.0001) {
369
+ ddx = Math.random() - 0.5
370
+ ddy = Math.random() - 0.5
371
+ d2 = ddx * ddx + ddy * ddy || 0.01
372
+ }
373
+ const d = Math.sqrt(d2)
374
+ const push = (minSep - d) * 0.5
375
+ const ux = ddx / d
376
+ const uy = ddy / d
377
+ n.x += ux * push
378
+ n.y += uy * push
379
+ if (!m.pinned) {
380
+ m.x -= ux * push
381
+ m.y -= uy * push
382
+ }
383
+ }
384
+ }
385
+ }
386
+ }
387
+ }
388
+ state.alpha = Math.max(0.02, state.alpha * decay)
389
+ }
390
+ // 坐标变了:告诉绘制层「上一帧的边路径缓存失效了」。
391
+ // 静止时(绝大多数时间)这份缓存让每帧省掉几千条曲线的重建。
392
+ state.geoVersion = (state.geoVersion || 0) + 1
393
+ }
394
+
395
+ /** 时间轴布局:横轴=记忆时间,纵轴=工作区。 */
396
+ function layoutTime() {
397
+ const nodes = state.nodes
398
+ if (!nodes.length) return
399
+ const times = nodes.map((n) => n.createdAt || 0).filter((x) => x > 0)
400
+ const min = Math.min(...times)
401
+ const maxs = Math.max(...times)
402
+ const span = Math.max(1, maxs - min)
403
+ const clusters = state.clusters
404
+ const idx = new Map(clusters.map((c, i) => [c.id, i]))
405
+ const rowH = Math.min(120, (state.h * 0.62) / Math.max(1, clusters.length))
406
+ state.timeRange = { min, max: maxs }
407
+ state.timeRows = clusters.map((c, i) => ({ id: c.id, title: c.title || c.label || '', y: -state.h * 0.3 + i * rowH, color: c.color }))
408
+ for (const n of nodes) {
409
+ const t = n.createdAt || min
410
+ n.tx = state.w * 0.12 + ((t - min) / span) * state.w * 0.76 - state.w / 2
411
+ n.ty = -state.h * 0.3 + (idx.get(n.cluster) || 0) * rowH
412
+ }
413
+ }
414
+
415
+ // ---------------- 数据 ----------------
416
+ /**
417
+ * 区块加载(MC 那一套的骨架):把世界切成格子,按「离视口中心远近」排队,
418
+ * 每帧只点亮一点点,同时把力导向按帧推进——星云是长出来的,不是蹦出来的。
419
+ */
420
+ function startReveal() {
421
+ // 系统里选了「减少动态效果」的人,不要看二十秒的生长动画:直接全亮。
422
+ if (window.matchMedia && window.matchMedia('(prefers-reduced-motion: reduce)').matches) {
423
+ for (const n of state.nodes) n.reveal = 1
424
+ state.pump = null
425
+ state.alpha = 1
426
+ return
427
+ }
428
+ const CELL = 900
429
+ const cells = new Map()
430
+ for (const n of state.nodes) {
431
+ const k = Math.floor(n.x / CELL) + ',' + Math.floor(n.y / CELL)
432
+ let arr = cells.get(k)
433
+ if (!arr) cells.set(k, (arr = []))
434
+ arr.push(n)
435
+ }
436
+ const cx = state.cam.x
437
+ const cy = state.cam.y
438
+ const dist = (arr) => {
439
+ let sx = 0, sy = 0
440
+ for (const n of arr) { sx += n.x; sy += n.y }
441
+ return Math.hypot(sx / arr.length - cx, sy / arr.length - cy)
442
+ }
443
+ const order = [...cells.values()].sort((A, B) => dist(A) - dist(B))
444
+ const t0 = performance.now()
445
+ let t = 0
446
+ for (const arr of order) {
447
+ // 同一格里重要度高的先长出来(主人打开页面通常在找重要的东西)
448
+ arr.sort((a, b) => (b.importance || 0) - (a.importance || 0))
449
+ for (let i = 0; i < arr.length; i++) {
450
+ arr[i].reveal = 0
451
+ arr[i].delay = t + Math.min(220, i * 8)
452
+ }
453
+ t += 62 // 每格错开一点,形成"扫过去"的波
454
+ }
455
+ // 万条图:420 轮力导向要十几秒,首屏等不起。格子初始位置已经分好簇,
456
+ // 少量轮次足以把同一格的节点拉开;细节交给用户缩放/拖动后的按需推进。
457
+ const ticksTarget = state.nodes.length > 3000 ? 48 : state.nodes.length > 1000 ? 180 : 420
458
+ state.pump = { t0, done: false, total: state.nodes.length, ticks: 0, ticksTarget }
459
+ state.alpha = 1
460
+ }
461
+
462
+ /** 加载进度(给界面显示"正在生长 42%")。 */
463
+ api.progress = function progress() {
464
+ if (!state.pump) return { done: true, shown: state.nodes.length, total: state.nodes.length }
465
+ let shown = 0
466
+ for (const n of state.nodes) if ((n.reveal || 0) >= 0.98) shown++
467
+ return { done: state.pump.done, shown, total: state.nodes.length }
468
+ }
469
+
470
+ function pumpReveal(now) {
471
+ const p = state.pump
472
+ if (!p) return false
473
+ const t = now - p.t0
474
+ let shown = 0
475
+ for (const n of state.nodes) {
476
+ if ((n.reveal || 0) >= 1) { shown++; continue }
477
+ const el = t - (n.delay || 0)
478
+ n.reveal = el <= 0 ? 0 : Math.min(1, el / 240)
479
+ }
480
+ // 边生根之后力导向还在找位置:每帧按 8ms 预算推进,直到走完目标轮次
481
+ // (注意:不能"点全亮就停",否则布局只跑了几十轮,星团会挤成一坨)
482
+ const ticksTarget = p.ticksTarget || 420
483
+ if (p.ticks < ticksTarget) {
484
+ const budget = 8
485
+ const s0 = performance.now()
486
+ while (performance.now() - s0 < budget && p.ticks < ticksTarget) {
487
+ simulate(1, 0.994)
488
+ p.ticks++
489
+ }
490
+ if (shown < p.total) return true
491
+ }
492
+ p.done = true
493
+ state.pump = null
494
+ return false
495
+ }
496
+
497
+ api.load = function load(graph, keepView) {
498
+ const loadT0 = performance.now()
499
+ const first = !state.graph
500
+ state.graph = graph
501
+ state.edgeCache = null // 换了一批数据,上一帧的边路径一律作废
502
+ state.boxesDirty = true
503
+ state.nodes = graph.nodes.map((n) => ({ ...n }))
504
+ state.byId = new Map(state.nodes.map((n) => [n.id, n]))
505
+ state.edges = graph.edges
506
+ .map((e) => ({ ...e, _a: state.byId.get(e.a), _b: state.byId.get(e.b) }))
507
+ .filter((e) => e._a && e._b)
508
+ state.clusters = (graph.clusters || []).map((c) => ({ ...c }))
509
+ initLayout()
510
+ if (!keepView || first) api.fit(true)
511
+ if (graph.v >= 2) {
512
+ if (state.nodes.length > 3000 || window.__NEBULA_SNAPSHOT__) {
513
+ // 快照没有后端、也没有第二次机会:直接出图,不依赖 rAF 的生长动画。
514
+ // 万条图更是如此:生长动画 + 每帧重绘会把首屏拖到十几秒。
515
+ // 先同步走少量轮次把格子里的点拉开,一次画完;细节交给缩放后的重绘。
516
+ state.alpha = 1
517
+ // 初始位置已经按簇排好;万条图不再跑力导向,直接出图。
518
+ for (const n of state.nodes) n.reveal = 1
519
+ state.pump = null
520
+ } else {
521
+ // 精简图:先按格子排队做"区块加载",布局靠后续每帧推进
522
+ for (const n of state.nodes) n.reveal = 0
523
+ startReveal()
524
+ }
525
+ } else {
526
+ state.alpha = 1
527
+ simulate(420, 0.988)
528
+ for (const n of state.nodes) n.reveal = 1
529
+ }
530
+ draw()
531
+ api.timings = { loadMs: Math.round(performance.now() - loadT0), nodes: state.nodes.length, edges: state.edges.length, pump: state.pump ? state.pump.ticksTarget : 0 }
532
+ }
533
+
534
+ /**
535
+ * 追加一页(1.9.0):只把新节点摆进各自簇里,**不动相机、不重排已有节点**。
536
+ * 新节点直接 reveal=1(用户已经在看这张图了,再放生长动画反而像卡住)。
537
+ * @returns {{added:number, edges:number, ms:number}}
538
+ */
539
+ api.append = function append(addNodes, addEdges) {
540
+ const t0 = performance.now()
541
+ if (!state.graph || !Array.isArray(addNodes)) return { added: 0, edges: 0, ms: 0 }
542
+ const cMap = new Map(state.clusters.map((c) => [c.id, c]))
543
+ let extra = 0
544
+ let added = 0
545
+ for (const raw of addNodes) {
546
+ if (!raw || state.byId.has(raw.id)) continue
547
+ const node = { ...raw }
548
+ let c = cMap.get(node.cluster)
549
+ if (!c) {
550
+ // 第一页里没出现过的簇:在外圈按序号找个位子,免得全堆在原点
551
+ const ang = extra * 2.399963 // 黄金角,散得均匀又不规则
552
+ const r = 320 + extra * 140
553
+ extra++
554
+ c = { id: node.cluster, _cx: Math.cos(ang) * r, _cy: Math.sin(ang) * r, _rad: 150 }
555
+ cMap.set(node.cluster, c)
556
+ }
557
+ const rnd = h32(node.id) >>> 0
558
+ const ang = ((rnd % 1000) / 1000) * Math.PI * 2
559
+ let rad = Math.sqrt(((rnd >>> 10) % 1000) / 1000) * (c._rad || 120)
560
+ if (!isFinite(rad)) rad = (c._rad || 120) * 0.5
561
+ node.x = (c._cx || 0) + Math.cos(ang) * rad
562
+ node.y = (c._cy || 0) + Math.sin(ang) * rad
563
+ if (!isFinite(node.x) || !isFinite(node.y)) {
564
+ node.x = c._cx || 0
565
+ node.y = c._cy || 0
566
+ }
567
+ node.vx = 0
568
+ node.vy = 0
569
+ node.r = nodeRadius(node)
570
+ node.color = LEVEL_COLOR[node.level] || '#9fb6cc'
571
+ node.rgb = hexToRgb(node.color)
572
+ node.reveal = 1
573
+ state.nodes.push(node)
574
+ state.byId.set(node.id, node)
575
+ added++
576
+ }
577
+ let edges = 0
578
+ for (const e of addEdges || []) {
579
+ const ea = state.byId.get(e.a)
580
+ const eb = state.byId.get(e.b)
581
+ if (!ea || !eb) continue
582
+ state.edges.push({ ...e, _a: ea, _b: eb })
583
+ edges++
584
+ }
585
+ if (added) {
586
+ state.edgeCache = null // 边集合变了,上一帧缓存的两端位置作废
587
+ state.boxesDirty = true
588
+ state.geoVersion = (state.geoVersion || 0) + 1 // 空间网格跟着重建
589
+ draw()
590
+ }
591
+ return { added, edges, ms: Math.round(performance.now() - t0) }
592
+ }
593
+
594
+ api.fit = function fit(instant) {
595
+ const nodes = api.visibleNodes()
596
+ if (!nodes.length) return
597
+ let minX = Infinity, minY = Infinity, maxX = -Infinity, maxY = -Infinity
598
+ for (const n of nodes) {
599
+ if (n.x < minX) minX = n.x
600
+ if (n.x > maxX) maxX = n.x
601
+ if (n.y < minY) minY = n.y
602
+ if (n.y > maxY) maxY = n.y
603
+ }
604
+ const pad = 62
605
+ const P = state.pad || { left: 0, right: 0, top: 0, bottom: 0 }
606
+ const availW = Math.max(220, state.w - P.left - P.right)
607
+ const availH = Math.max(220, state.h - P.top - P.bottom)
608
+ const bw = maxX - minX + pad * 2
609
+ const bh = maxY - minY + pad * 2
610
+ const k = Math.min(availW / bw, availH / bh, 1.35)
611
+ // 让内容落在「可用区域」的中心,而不是画布中心(左侧有筛选面板时要往右挪)
612
+ const cx = P.left + availW / 2 - state.w / 2
613
+ const cy = P.top + availH / 2 - state.h / 2
614
+ state.target = {
615
+ k,
616
+ x: (minX + maxX) / 2 - cx / k,
617
+ y: (minY + maxY) / 2 - cy / k,
618
+ }
619
+ if (instant) {
620
+ state.cam.k = k
621
+ state.cam.x = state.target.x
622
+ state.cam.y = state.target.y
623
+ state.target = null
624
+ }
625
+ }
626
+
627
+ /** 给界面留出面板位置。 */
628
+ api.setPadding = function setPadding(p) {
629
+ state.pad = { left: 0, right: 0, top: 0, bottom: 0, ...(p || {}) }
630
+ }
631
+
632
+ /** 拉远时点的聚合光斑:返回那个工作区 id(不是个体节点,所以没点到就退化成 null)。 */
633
+ api.lodAt = function lodAt(sx, sy) {
634
+ const agg = state.lodAgg
635
+ if (!agg || !agg.size) return null
636
+ let best = null
637
+ let bestD = Infinity
638
+ for (const [ws, a] of agg) {
639
+ const d = Math.hypot(sx - a.cx, sy - a.cy)
640
+ if (d <= a.rad * 0.95 && d < bestD) {
641
+ bestD = d
642
+ best = ws
643
+ }
644
+ }
645
+ return best
646
+ }
647
+
648
+ /** LOD 当前状态(调试/自动化用):哪些簇被聚合成光斑、缩放多少。 */
649
+ api.lodInfo = function lodInfo() {
650
+ const agg = state.lodAgg || new Map()
651
+ return {
652
+ k: Number(state.cam.k.toFixed(3)),
653
+ clusters: [...agg.entries()].map(([ws, a]) => ({ ws, n: a.n, r: Math.round(a.rad), x: Math.round(a.cx), y: Math.round(a.cy) })),
654
+ }
655
+ }
656
+
657
+ /** 下钻一个项目:把镜头推到这一簇的范围(不筛掉别人,保留上下文)。 */ api.focusCluster = function focusCluster(ws) {
658
+ const list = state.nodes.filter((n) => !n.hidden && n.cluster === ws)
659
+ if (!list.length) return
660
+ let minX = Infinity, minY = Infinity, maxX = -Infinity, maxY = -Infinity
661
+ for (const n of list) {
662
+ if (n.x < minX) minX = n.x
663
+ if (n.x > maxX) maxX = n.x
664
+ if (n.y < minY) minY = n.y
665
+ if (n.y > maxY) maxY = n.y
666
+ }
667
+ const pad = 90
668
+ const P = state.pad || { left: 0, right: 0, top: 0, bottom: 0 }
669
+ const availW = Math.max(220, state.w - P.left - P.right)
670
+ const availH = Math.max(220, state.h - P.top - P.bottom)
671
+ const k = Math.min(availW / (maxX - minX + pad * 2), availH / (maxY - minY + pad * 2), 3.2)
672
+ const cx = P.left + availW / 2 - state.w / 2
673
+ const cy = P.top + availH / 2 - state.h / 2
674
+ state.target = { k, x: (minX + maxX) / 2 - cx / k, y: (minY + maxY) / 2 - cy / k }
675
+ }
676
+
677
+ /** 世界坐标 → 屏幕坐标。 */
678
+ function toScreen(x, y) {
679
+ return [
680
+ (x - state.cam.x) * state.cam.k + state.w / 2,
681
+ (y - state.cam.y) * state.cam.k + state.h / 2,
682
+ ]
683
+ }
684
+ function toWorld(sx, sy) {
685
+ return [
686
+ (sx - state.w / 2) / state.cam.k + state.cam.x,
687
+ (sy - state.h / 2) / state.cam.k + state.cam.y,
688
+ ]
689
+ }
690
+ api.toScreen = toScreen
691
+ api.toWorld = toWorld
692
+
693
+ // ---------------- 视口裁剪 ----------------
694
+ // 5 万条记忆时图上有十几万条边。整帧重建路径会让每次拖动/缩放都卡一下,
695
+ // 所以把节点与边都登记到世界坐标网格里:
696
+ // nodeGrid —— pick() 只查指针附近的格子,不再线性扫 5 万个点;
697
+ // edgeGrid —— draw() 只把「与视口相交的格子」里的边拿去建路径,放大后只剩几个百分点。
698
+ // 网格版本跟着 geoVersion 与 hiddenVersion 走:位置或显隐一变就重建。
699
+ const NODE_CELL = 96
700
+ const EDGE_CELL = 384
701
+ // 超过这个规模、又拉得这么远时,逐条画边没有意义:改画簇级网络
702
+ const BIG_EDGE_LOD = 20000
703
+ const EDGE_LOD_K = 1
704
+
705
+ function gridSignature() {
706
+ return (state.geoVersion || 0) + '|' + (state.hiddenVersion || 0) + '|' + state.nodes.length + '|' + state.edges.length
707
+ }
708
+
709
+ function ensureGrids() {
710
+ const sig = gridSignature()
711
+ if (state.grids && state.gridSig === sig) return
712
+ const nodeGrid = new Map()
713
+ for (let i = 0; i < state.nodes.length; i++) {
714
+ const n = state.nodes[i]
715
+ if (n.hidden) continue
716
+ const key = Math.floor(n.x / NODE_CELL) + ',' + Math.floor(n.y / NODE_CELL)
717
+ let arr = nodeGrid.get(key)
718
+ if (!arr) nodeGrid.set(key, (arr = []))
719
+ arr.push(i)
720
+ }
721
+ const edgeGrid = new Map()
722
+ for (let i = 0; i < state.edges.length; i++) {
723
+ const e = state.edges[i]
724
+ const a = e._a
725
+ const b = e._b
726
+ if (!a || !b) continue
727
+ const c0 = Math.floor(Math.min(a.x, b.x) / EDGE_CELL)
728
+ const c1 = Math.floor(Math.max(a.x, b.x) / EDGE_CELL)
729
+ const r0 = Math.floor(Math.min(a.y, b.y) / EDGE_CELL)
730
+ const r1 = Math.floor(Math.max(a.y, b.y) / EDGE_CELL)
731
+ for (let cy = r0; cy <= r1; cy++) {
732
+ for (let cx = c0; cx <= c1; cx++) {
733
+ const key = cx + ',' + cy
734
+ let arr = edgeGrid.get(key)
735
+ if (!arr) edgeGrid.set(key, (arr = []))
736
+ arr.push(i)
737
+ }
738
+ }
739
+ }
740
+ // 大图远景:把边按「簇到簇」压成一张几十条的网络。
741
+ // 5 万条时十几万条曲线在 1 像素尺度上没有信息量,只会把整帧时间烧在路径上。
742
+ const links = new Map()
743
+ if (state.nodes.length >= BIG_EDGE_LOD) {
744
+ for (const e of state.edges) {
745
+ const a = e._a
746
+ const b = e._b
747
+ if (!a || !b || a.cluster === b.cluster) continue
748
+ const key = a.cluster < b.cluster ? a.cluster + '\u0000' + b.cluster : b.cluster + '\u0000' + a.cluster
749
+ let link = links.get(key)
750
+ if (!link) links.set(key, (link = { ca: a.cluster, cb: b.cluster, n: 0, w: 0, t: e.t }))
751
+ link.n++
752
+ link.w += e.w || 0.4
753
+ }
754
+ }
755
+ state.grids = { nodeGrid, edgeGrid, links }
756
+ state.gridSig = sig
757
+ state.edgeMark = new Uint32Array(state.edges.length)
758
+ state.edgeGen = 0
759
+ }
760
+
761
+ /** 视口对应的世界矩形(带一点余量,免得屏幕边缘的曲线被切掉半截)。 */
762
+ function viewRect(marginPx) {
763
+ const k = state.cam.k || 1
764
+ const mx = (marginPx || 0) / k
765
+ const hw = state.w / 2 / k + mx
766
+ const hh = state.h / 2 / k + mx
767
+ return { x0: state.cam.x - hw, y0: state.cam.y - hh, x1: state.cam.x + hw, y1: state.cam.y + hh }
768
+ }
769
+
770
+ /** 与视口相交的边下标(去重)。整图可见时就是全部边,量级与裁剪前相同。 */
771
+ function visibleEdgeIndices(rect) {
772
+ ensureGrids()
773
+ const grid = state.grids.edgeGrid
774
+ const mark = state.edgeMark
775
+ const gen = (state.edgeGen = (state.edgeGen || 0) + 1)
776
+ const out = []
777
+ const c0 = Math.floor(rect.x0 / EDGE_CELL)
778
+ const c1 = Math.floor(rect.x1 / EDGE_CELL)
779
+ const r0 = Math.floor(rect.y0 / EDGE_CELL)
780
+ const r1 = Math.floor(rect.y1 / EDGE_CELL)
781
+ for (let cy = r0; cy <= r1; cy++) {
782
+ for (let cx = c0; cx <= c1; cx++) {
783
+ const arr = grid.get(cx + ',' + cy)
784
+ if (!arr) continue
785
+ for (let j = 0; j < arr.length; j++) {
786
+ const idx = arr[j]
787
+ if (mark[idx] === gen) continue
788
+ mark[idx] = gen
789
+ out.push(idx)
790
+ }
791
+ }
792
+ }
793
+ if (gen >= 4294967295) {
794
+ state.edgeMark = new Uint32Array(state.edges.length)
795
+ state.edgeGen = 0
796
+ }
797
+ return out
798
+ }
799
+
800
+ // ---------------- 绘制 ----------------
801
+ function drawStars() {
802
+ const t = performance.now() / 1000
803
+ for (const s of state.stars) {
804
+ const px = (s.x + state.cam.x * -0.012 * s.p) % state.w
805
+ const py = (s.y + state.cam.y * -0.012 * s.p) % state.h
806
+ const a = s.a * (0.72 + 0.28 * Math.sin(t * 0.7 + s.tw))
807
+ ctx.fillStyle = `rgba(190,215,245,${a})`
808
+ ctx.beginPath()
809
+ ctx.arc(px < 0 ? px + state.w : px, py < 0 ? py + state.h : py, s.r, 0, 6.2832)
810
+ ctx.fill()
811
+ }
812
+ }
813
+
814
+ function visibleEdge(e) {
815
+ const f = state.filter
816
+ if (!f) return true
817
+ if (f.types && !f.types.has(e.t)) return false
818
+ if (f.minW && e.w < f.minW) return false
819
+ if (f.ws && e._a && !f.ws.has(e._a.ws)) return false
820
+ return true
821
+ }
822
+
823
+ /** 簇级网络:大图拉远时代替逐条边(几十条线,一帧画完)。 */
824
+ function drawClusterLinks(links) {
825
+ const center = (id) => {
826
+ const b = state.boxes && state.boxes.get(id)
827
+ return b ? [(b.minX + b.maxX) / 2, (b.minY + b.maxY) / 2] : null
828
+ }
829
+ let maxN = 1
830
+ for (const [, l] of links) if (l.n > maxN) maxN = l.n
831
+ ctx.save()
832
+ ctx.lineCap = 'round'
833
+ for (const [, l] of links) {
834
+ const a = center(l.ca)
835
+ const b = center(l.cb)
836
+ if (!a || !b) continue
837
+ const [ax, ay] = toScreen(a[0], a[1])
838
+ const [bx, by] = toScreen(b[0], b[1])
839
+ const t = Math.sqrt(l.n / maxN)
840
+ ctx.strokeStyle = rgba(TYPE_COLOR[l.t] || '#8fb8d8', 0.05 + 0.15 * t)
841
+ ctx.lineWidth = Math.max(0.6, 0.8 + 2.6 * t)
842
+ ctx.beginPath()
843
+ ctx.moveTo(ax, ay)
844
+ ctx.lineTo(bx, by)
845
+ ctx.stroke()
846
+ }
847
+ ctx.restore()
848
+ }
849
+
850
+ /** 每帧耗时的观测值(自动化验收与「为什么拖动会卡」的排查都靠它)。 */
851
+ function draw() {
852
+ const t0 = performance.now()
853
+ drawInner()
854
+ state.lastDrawMs = Math.round((performance.now() - t0) * 10) / 10
855
+ }
856
+
857
+ function drawInner() {
858
+ const k = state.cam.k
859
+ ctx.clearRect(0, 0, state.w, state.h)
860
+ ctx.fillStyle = '#04060c'
861
+ ctx.fillRect(0, 0, state.w, state.h)
862
+
863
+ drawStars()
864
+
865
+ // 世界坐标包围盒只算一次:平移/缩放下每帧只把 4 个角投到屏幕
866
+ // (原来每帧遍历 1400+ 个节点算簇包围盒,拖动时白烧 CPU;顺带让"拖到哪都不断帧")
867
+ if (state.boxesDirty !== false || !state.boxes) {
868
+ const boxes = new Map()
869
+ for (const n of state.nodes) {
870
+ if (n.hidden) continue
871
+ let b = boxes.get(n.cluster)
872
+ if (!b) {
873
+ b = { minX: n.x, maxX: n.x, minY: n.y, maxY: n.y, n: 0 }
874
+ boxes.set(n.cluster, b)
875
+ }
876
+ if (n.x < b.minX) b.minX = n.x
877
+ if (n.x > b.maxX) b.maxX = n.x
878
+ if (n.y < b.minY) b.minY = n.y
879
+ if (n.y > b.maxY) b.maxY = n.y
880
+ b.n++
881
+ }
882
+ state.boxes = boxes
883
+ state.boxesDirty = false
884
+ // 包围盒变了 → LOD 聚合范围可能变 → 边路径缓存跟着失效
885
+ state.boxVersion = (state.boxVersion || 0) + 1
886
+ }
887
+ const clusterLabels = []
888
+ // LOD:拉远时,屏幕半径过小的簇整团并成一个聚合光斑(旁边写条数),点它可下钻。
889
+ // 判据是"这团在屏幕上有多大",不是写死的缩放级别——所以和窗口大小、缩放都自洽。
890
+ const agg = new Map()
891
+ const LOD_MIN_R = 96
892
+ state.lodAgg = agg
893
+ // 每个簇里「还被筛选留下」的节点数。全被筛掉的簇不该再画光斑——
894
+ // 否则画面说「这一屏没有记忆」,旁边还挂着 131 个光斑,人只会以为界面在骗他。
895
+ const visByCluster = new Map()
896
+ for (const n of state.nodes) if (!n.hidden) visByCluster.set(n.cluster, (visByCluster.get(n.cluster) || 0) + 1)
897
+ if (state.mode === 'nebula') {
898
+ for (const c of state.clusters) {
899
+ const wb = state.boxes.get(c.id)
900
+ if (!wb || wb.n < 3) continue
901
+ const visN = visByCluster.get(c.id) || 0
902
+ if (!visN) continue
903
+ // 世界包围盒 → 屏幕(只投 4 个角,恒定的 4 次乘法)
904
+ let minX = Infinity, maxX = -Infinity, minY = Infinity, maxY = -Infinity
905
+ for (const [wx, wy] of [
906
+ [wb.minX, wb.minY],
907
+ [wb.maxX, wb.minY],
908
+ [wb.minX, wb.maxY],
909
+ [wb.maxX, wb.maxY],
910
+ ]) {
911
+ const sx = (wx - state.cam.x) * state.cam.k + state.w / 2
912
+ const sy = (wy - state.cam.y) * state.cam.k + state.h / 2
913
+ if (sx < minX) minX = sx
914
+ if (sx > maxX) maxX = sx
915
+ if (sy < minY) minY = sy
916
+ if (sy > maxY) maxY = sy
917
+ }
918
+ const cx = (minX + maxX) / 2
919
+ const cy = (minY + maxY) / 2
920
+ const rad = Math.max(52, Math.max(maxX - minX, maxY - minY) * 0.66)
921
+ if (rad < 26) continue
922
+ if (rad < LOD_MIN_R) {
923
+ agg.set(c.id, { cx, cy, rad: Math.max(24, rad * 1.15), n: visN, color: c.color || '#6cc8ff', title: c.title })
924
+ continue
925
+ }
926
+ const g = ctx.createRadialGradient(cx, cy, 0, cx, cy, rad)
927
+ const col = c.color || '#6cc8ff'
928
+ g.addColorStop(0, rgba(col, 0.06))
929
+ g.addColorStop(0.55, rgba(col, 0.024))
930
+ g.addColorStop(1, rgba(col, 0))
931
+ ctx.fillStyle = g
932
+ ctx.beginPath()
933
+ ctx.arc(cx, cy, rad, 0, 6.2832)
934
+ ctx.fill()
935
+ // 早先 k<0.18 就不画簇名,于是「再缩小一点」会把还没并成光斑的大簇名字弄丢;
936
+ // 真正的门槛应该是「这团还画得出轮廓」(rad≥LOD_MIN_R),不是写死一个缩放级别。
937
+ if (k > 0.10) {
938
+ clusterLabels.push({
939
+ x: cx,
940
+ y: minY - 14,
941
+ ax: cx,
942
+ ay: cy,
943
+ rad,
944
+ text: String(c.title || c.id).toUpperCase(),
945
+ col,
946
+ })
947
+ }
948
+ }
949
+ }
950
+
951
+ const hl = state.highlight
952
+ const hset = state.highlightSet
953
+ const sel = state.selected
954
+
955
+ // 连边:按「颜色 + 透明度档」归并成少量路径,一次 stroke 一批
956
+ // (原来是每条边一个 beginPath/stroke,3000+ 边时光栅化开销全在这上面)
957
+ //
958
+ // 再加一层:静止时路径根本不用重建。镜头、坐标版本、聚类包围盒、筛选、高亮
959
+ // 都没变,就直接复用上一帧那几批 Path2D —— 绝大多数时间画面是静的。
960
+ const f = state.filter || {}
961
+ const edgeKey = [
962
+ state.cam.x,
963
+ state.cam.y,
964
+ state.cam.k,
965
+ state.geoVersion || 0,
966
+ state.boxVersion || 0,
967
+ state.pump ? 'p' + state.pump.ticks : 'idle',
968
+ hl || '',
969
+ hset ? hset.size + ':' + (hset.size ? Array.from(hset).slice(0, 3).join(',') : '') : '',
970
+ sel || '',
971
+ f.minW || 0,
972
+ f.minImp || 0,
973
+ f.ws ? 'w' + f.ws.size : 'wa',
974
+ f.levels ? 'l' + f.levels.size : 'la',
975
+ f.types ? 't' + f.types.size : 'ta',
976
+ // 换一组同数量的工作区时 size 不变,但藏起来的节点变了——必须有版本号,
977
+ // 否则边会沿用上一次筛选的路径,看着像筛选没生效。
978
+ state.hiddenVersion || 0,
979
+ state.w,
980
+ state.h,
981
+ ].join('|')
982
+
983
+ let edgeBuckets
984
+ // 远景大图:十几万条边在屏幕上只有一两像素长,逐条建路径纯属浪费。
985
+ // 这种时候边要表达的信息只剩「哪几团之间连着」——直接画簇级网络。
986
+ if (state.nodes.length >= BIG_EDGE_LOD) ensureGrids()
987
+ const bigLod = state.nodes.length >= BIG_EDGE_LOD && k < EDGE_LOD_K && state.grids && state.grids.links.size > 0
988
+ if (bigLod) {
989
+ edgeBuckets = new Map()
990
+ state.edgeCache = null
991
+ state.cull = { edges: state.edges.length, considered: 0, mode: 'cluster', links: state.grids.links.size }
992
+ drawClusterLinks(state.grids.links)
993
+ } else if (state.edgeCache && state.edgeCache.key === edgeKey) {
994
+ edgeBuckets = state.edgeCache.buckets
995
+ } else {
996
+ edgeBuckets = new Map()
997
+ const edgePath = (bucket, ax, ay, bx, by) => {
998
+ let p = edgeBuckets.get(bucket)
999
+ if (!p) edgeBuckets.set(bucket, (p = new Path2D()))
1000
+ const mx = (ax + bx) / 2
1001
+ const my = (ay + by) / 2
1002
+ const dl = Math.hypot(bx - ax, by - ay) || 1
1003
+ const nx = -(by - ay) / dl
1004
+ const ny = (bx - ax) / dl
1005
+ const bend = Math.min(26, dl * 0.16)
1006
+ p.moveTo(ax, ay)
1007
+ p.quadraticCurveTo(mx + nx * bend, my + ny * bend, bx, by)
1008
+ }
1009
+ // 只处理视口里的边:放大之后这一步能把十几万条砍到几千条。
1010
+ // 拖动单个节点时退回全量:那条节点的边可能刚好被网格判在视口外,
1011
+ // 拖到一半线消失比慢一点更难受(而且拖动本身只有一条边在动)。
1012
+ const cand = state.drag && state.drag.type === 'node' ? null : visibleEdgeIndices(viewRect(220))
1013
+ const candN = cand ? cand.length : state.edges.length
1014
+ state.cull = { edges: state.edges.length, considered: candN, mode: 'edges', full: !cand }
1015
+ for (let ci = 0; ci < candN; ci++) {
1016
+ const e = cand ? state.edges[cand[ci]] : state.edges[ci]
1017
+ if (!visibleEdge(e)) continue
1018
+ const a = e._a
1019
+ const b = e._b
1020
+ // 端点被筛掉了,这条线就没有归属:留着会变成画面中央的「孤儿细线」
1021
+ if (a.hidden || b.hidden) continue
1022
+ // 区块加载:两端都点亮到 85% 才画这条边,否则会先有线后有点
1023
+ const ra = a.reveal == null ? 1 : a.reveal
1024
+ const rb = b.reveal == null ? 1 : b.reveal
1025
+ const rMin = ra < rb ? ra : rb
1026
+ if (rMin < 0.85) continue
1027
+ // LOD:两端都被聚合成光斑时,这条边没有个体可连,跳过
1028
+ if (agg.size && agg.has(a.cluster) && agg.has(b.cluster)) continue
1029
+ const [ax, ay] = toScreen(a.x, a.y)
1030
+ const [bx, by] = toScreen(b.x, b.y)
1031
+ if (ax < -200 || ay < -200 || bx < -200 || by < -200) continue
1032
+ if (ax > state.w + 200 || bx > state.w + 200) continue
1033
+ let alpha = 0.1 + 0.32 * (e.w || 0.4)
1034
+ if (hset) alpha = hset.has(e.a) && hset.has(e.b) ? 0.12 + 0.5 * (e.w || 0.4) : 0.28
1035
+ if (e.dim) alpha *= 0.4
1036
+ // 万条图的边是主要亮度来源:几万条半透明线叠在一起会变成一整片白。
1037
+ if (state.nodes.length > 3000) alpha *= 0.16
1038
+ alpha *= Math.min(1, (rMin - 0.85) / 0.15)
1039
+ const col = TYPE_COLOR[e.t] || '#8fb8d8'
1040
+ const q = Math.round(Math.min(0.72, alpha) * 50) / 50
1041
+ edgePath(col + '|' + q, ax, ay, bx, by)
1042
+ }
1043
+ state.edgeCache = { key: edgeKey, buckets: edgeBuckets }
1044
+ }
1045
+ ctx.lineWidth = Math.max(0.5, k)
1046
+ for (const [bucket, p] of edgeBuckets) {
1047
+ const cut = bucket.lastIndexOf('|')
1048
+ const col = bucket.slice(0, cut)
1049
+ const a = Number(bucket.slice(cut + 1))
1050
+ ctx.strokeStyle = rgba(col, a)
1051
+ ctx.stroke(p)
1052
+ }
1053
+
1054
+ // LOD 聚合光斑:一团一个,亮度和大小按条数走,旁边写条数
1055
+ if (agg.size) {
1056
+ for (const [, a] of agg) {
1057
+ const g = ctx.createRadialGradient(a.cx, a.cy, 0, a.cx, a.cy, a.rad)
1058
+ g.addColorStop(0, rgba(a.color, 0.5))
1059
+ g.addColorStop(0.35, rgba(a.color, 0.16))
1060
+ g.addColorStop(1, rgba(a.color, 0))
1061
+ ctx.fillStyle = g
1062
+ ctx.beginPath()
1063
+ ctx.arc(a.cx, a.cy, a.rad, 0, 6.2832)
1064
+ ctx.fill()
1065
+ ctx.strokeStyle = rgba(a.color, 0.34)
1066
+ ctx.lineWidth = 1
1067
+ ctx.beginPath()
1068
+ ctx.arc(a.cx, a.cy, a.rad * 0.62, 0, 6.2832)
1069
+ ctx.stroke()
1070
+ const fs = Math.max(10, Math.min(13, a.rad * 0.34))
1071
+ ctx.font = `600 ${Math.round(fs)}px ui-monospace, Menlo, Consolas, monospace`
1072
+ ctx.textAlign = 'center'
1073
+ ctx.fillStyle = rgba(a.color, 0.95)
1074
+ ctx.fillText(String(a.n), a.cx, a.cy + fs * 0.36)
1075
+ ctx.font = `500 ${Math.round(fs * 0.82)}px system-ui, "Noto Sans SC", sans-serif`
1076
+ ctx.fillStyle = 'rgba(214, 232, 248, 0.82)'
1077
+ ctx.fillText(String(a.title || '').slice(0, 18), a.cx, a.cy + a.rad * 0.62 + fs + 4)
1078
+ ctx.textAlign = 'left'
1079
+ }
1080
+ }
1081
+
1082
+ // 证据链:压在普通边上面重画一次,用暖金色,一眼能顺着走
1083
+ if (state.pathEdges && state.pathEdges.size) {
1084
+ ctx.save()
1085
+ ctx.lineCap = 'round'
1086
+ ctx.strokeStyle = 'rgba(255, 216, 138, 0.92)'
1087
+ ctx.lineWidth = Math.max(1.6, 2.6 * k)
1088
+ ctx.shadowColor = 'rgba(255, 200, 62, 0.55)'
1089
+ ctx.shadowBlur = 10 * Math.min(1.4, k)
1090
+ for (const e of state.edges) {
1091
+ const key = e.a < e.b ? e.a + '|' + e.b : e.b + '|' + e.a
1092
+ if (!state.pathEdges.has(key)) continue
1093
+ const a = e._a
1094
+ const b = e._b
1095
+ if (!a || !b) continue
1096
+ const [ax, ay] = toScreen(a.x, a.y)
1097
+ const [bx, by] = toScreen(b.x, b.y)
1098
+ const mx = (ax + bx) / 2
1099
+ const my = (ay + by) / 2
1100
+ const dl = Math.hypot(bx - ax, by - ay) || 1
1101
+ const nx = -(by - ay) / dl
1102
+ const ny = (bx - ax) / dl
1103
+ const bend = Math.min(26, dl * 0.16)
1104
+ ctx.beginPath()
1105
+ ctx.moveTo(ax, ay)
1106
+ ctx.quadraticCurveTo(mx + nx * bend, my + ny * bend, bx, by)
1107
+ ctx.stroke()
1108
+ }
1109
+ ctx.restore()
1110
+ }
1111
+
1112
+ // 节点
1113
+ const labelQueue = []
1114
+ for (const n of state.nodes) {
1115
+ if (n.hidden) continue
1116
+ // LOD 聚合掉的簇,个体不再画(整团由一个光斑代表)
1117
+ if (agg.size && agg.has(n.cluster)) continue
1118
+ const [px, py] = toScreen(n.x, n.y)
1119
+ if (px < -60 || py < -60 || px > state.w + 60 || py > state.h + 60) continue
1120
+ const isSel = sel === n.id
1121
+ const isHl = hl === n.id
1122
+ const nearHl = hset ? hset.has(n.id) : false
1123
+ const dim = hset && !nearHl
1124
+ // 区块加载:还没点亮的节点不画;正在点亮的按 reveal 淡入 + 从 0.55 倍大小长到 1 倍
1125
+ const rev = n.reveal == null ? 1 : n.reveal
1126
+ if (rev <= 0.02) continue
1127
+ const grow = 0.55 + 0.45 * rev
1128
+ const r = Math.max(1.4, (n.r || nodeRadius(n)) * Math.min(1.6, 0.55 + k * 0.75) * grow)
1129
+ const colKey = n.color || LEVEL_COLOR[n.level] || '#9fb6cc'
1130
+ // 万条图:一万个光点叠在一起会把整片烧成白色。按密度压低单点亮度,
1131
+ // 让「一团」看起来是颗粒,而不是一块发光的墙。
1132
+ const dense = state.nodes.length > 3000 ? 0.085 : 1
1133
+ const intensity = (dim ? 0.62 : isSel || isHl ? 1 : nearHl ? 0.9 : 0.82) * rev * (0.72 + 0.28 * Math.min(1, k)) * dense
1134
+ // 光晕别随 k 无限放大:拉远时一堆光晕叠起来会把整片烧成白的
1135
+ const glow = r * (1.35 + 1.65 * Math.min(1, k)) * (isSel || isHl ? 1.5 : nearHl ? 1.25 : 1) * (state.nodes.length > 3000 ? 0.62 : 1)
1136
+ // 光点贴图缓存:同一层级色的发光小球只画一次,之后全是 drawImage
1137
+ // (原来每帧给 900+ 个节点各建两个径向渐变,缩放时明显卡)
1138
+ const bigGraph = state.nodes.length > 3000
1139
+ const prevAlpha = ctx.globalAlpha
1140
+ if (bigGraph && n.level !== 'source' && !isSel && !isHl) {
1141
+ // 一万条时不要一万个发光贴图:它们叠起来是一堵白墙。
1142
+ // 画成小颗粒,颜色还在,密度也还在,但不会把整片烧掉。
1143
+ ctx.globalAlpha = dim ? 0.16 : 0.62
1144
+ ctx.fillStyle = colKey
1145
+ ctx.beginPath()
1146
+ ctx.arc(px, py, Math.max(0.9, r * 0.3), 0, Math.PI * 2)
1147
+ ctx.fill()
1148
+ } else {
1149
+ const sprite = nodeSprite(colKey)
1150
+ ctx.globalAlpha = intensity
1151
+ ctx.drawImage(sprite, px - glow, py - glow, glow * 2, glow * 2)
1152
+ }
1153
+ ctx.globalAlpha = prevAlpha
1154
+ // 来源节点(技能 / MCP / 插件)用空心小菱标记,和记忆光点区分开
1155
+ if (n.level === 'source') {
1156
+ const s2 = Math.max(3.2, r + 1.6)
1157
+ ctx.strokeStyle = rgba(colKey, dim ? 0.3 : 0.95)
1158
+ ctx.lineWidth = 1.2
1159
+ ctx.beginPath()
1160
+ ctx.moveTo(px, py - s2)
1161
+ ctx.lineTo(px + s2, py)
1162
+ ctx.lineTo(px, py + s2)
1163
+ ctx.lineTo(px - s2, py)
1164
+ ctx.closePath()
1165
+ ctx.stroke()
1166
+ ctx.lineWidth = Math.max(0.5, k)
1167
+ }
1168
+ // 高重要性的环
1169
+ if ((n.importance || 0) >= 4 && !dim && k > 0.55) {
1170
+ ctx.strokeStyle = rgba('#ffd88a', 0.55)
1171
+ ctx.lineWidth = 1
1172
+ ctx.beginPath()
1173
+ ctx.arc(px, py, r + 3.2, 0, 6.2832)
1174
+ ctx.stroke()
1175
+ ctx.lineWidth = Math.max(0.5, k)
1176
+ }
1177
+ // 证据链上的节点:编号 + 金环,方便和右侧的步骤一一对上
1178
+ if (state.pathIds && state.pathIds.has(n.id)) {
1179
+ const step = state.pathSeq ? state.pathSeq.indexOf(n.id) + 1 : 0
1180
+ ctx.strokeStyle = 'rgba(255, 216, 138, 0.95)'
1181
+ ctx.lineWidth = 1.6
1182
+ ctx.beginPath()
1183
+ ctx.arc(px, py, r + 5.4, 0, 6.2832)
1184
+ ctx.stroke()
1185
+ if (step) {
1186
+ const fs = Math.round(10 + Math.min(4, k))
1187
+ ctx.font = `600 ${fs}px "JetBrains Mono", ui-monospace, monospace`
1188
+ ctx.textAlign = 'center'
1189
+ const tx = px
1190
+ const ty = py - r - 9
1191
+ const txt = String(step)
1192
+ const w2 = ctx.measureText(txt).width + 8
1193
+ ctx.fillStyle = 'rgba(255, 216, 138, 0.92)'
1194
+ ctx.beginPath()
1195
+ ctx.roundRect ? ctx.roundRect(tx - w2 / 2, ty - fs, w2, fs + 5, 3) : ctx.rect(tx - w2 / 2, ty - fs, w2, fs + 5)
1196
+ ctx.fill()
1197
+ ctx.fillStyle = '#1a1206'
1198
+ ctx.fillText(txt, tx, ty - 3)
1199
+ ctx.textAlign = 'left'
1200
+ }
1201
+ ctx.lineWidth = Math.max(0.5, k)
1202
+ }
1203
+ if (isSel) {
1204
+ ctx.strokeStyle = rgba('#ffffff', 0.85)
1205
+ ctx.lineWidth = 1.4
1206
+ ctx.beginPath()
1207
+ ctx.arc(px, py, r + 6.5 + 2 * Math.sin(performance.now() / 320), 0, 6.2832)
1208
+ ctx.stroke()
1209
+ ctx.lineWidth = Math.max(0.5, k)
1210
+ }
1211
+ const wantLabel =
1212
+ rev > 0.7 &&
1213
+ (isSel || isHl || nearHl || (k > 1.05 && (n.importance || 0) >= 3) || (k > 1.6 && (n.degree || 0) >= 8))
1214
+ if (wantLabel && state.labels) labelQueue.push({ n, px, py, r, dim, strong: isSel || isHl })
1215
+ }
1216
+
1217
+ // 标签(后画,避免被节点盖住)。按「选中 > 悬停 > 重要度 > 度数」排序后限量,
1218
+ // 否则放大时几百个标签一起铺满画面,什么都看不清。
1219
+ ctx.textAlign = 'left'
1220
+ labelQueue.sort(
1221
+ (p, q) =>
1222
+ (q.strong ? 1 : 0) - (p.strong ? 1 : 0) ||
1223
+ (q.n.importance || 0) - (p.n.importance || 0) ||
1224
+ (q.n.degree || 0) - (p.n.degree || 0),
1225
+ )
1226
+ const labelTaken = []
1227
+ for (const item of labelQueue.slice(0, 64)) {
1228
+ const { n, px, py, r, dim } = item
1229
+ const text = String(n.label || n.title || '')
1230
+ if (!text) continue
1231
+ const fs = Math.min(13, 10.5 + k * 0.6)
1232
+ ctx.font = `${item.strong ? 600 : 400} ${fs}px Inter, "PingFang SC", "Microsoft YaHei", sans-serif`
1233
+ const tw = ctx.measureText(text).width
1234
+ const maxW = 190
1235
+ const shown = tw > maxW ? text.slice(0, Math.max(4, Math.floor((maxW / tw) * text.length))) + '…' : text
1236
+ const w2 = ctx.measureText(shown).width
1237
+ const box = { x: px + r + 5, y: py - fs * 0.72, w: w2 + 8, h: fs * 1.42 }
1238
+ if (labelTaken.some((b) => Math.abs(b.x - box.x) < (b.w + box.w) / 2 + 4 && Math.abs(b.y - box.y) < (b.h + box.h) / 2 + 2)) continue
1239
+ labelTaken.push(box)
1240
+ ctx.fillStyle = `rgba(4,6,12,${dim ? 0.5 : 0.66})`
1241
+ ctx.fillRect(box.x, box.y, box.w, box.h)
1242
+ ctx.fillStyle = dim ? 'rgba(150,175,200,0.35)' : item.strong ? '#f2fbff' : 'rgba(200,220,240,0.82)'
1243
+ ctx.fillText(shown, px + r + 9, py + fs * 0.36)
1244
+ }
1245
+
1246
+ // 簇名最后画:不压在星团里——从画面中心朝星团方向推到簇外,用细引导线牵回去
1247
+ const taken = []
1248
+ const midX = state.w / 2
1249
+ const midY = state.h / 2
1250
+ for (const label of clusterLabels) {
1251
+ const fs = Math.min(15, 10 + 3 * k)
1252
+ ctx.save()
1253
+ ctx.font = `500 ${fs}px Inter, "PingFang SC", "Microsoft YaHei", sans-serif`
1254
+ ctx.textAlign = 'center'
1255
+ const w = ctx.measureText(label.text).width
1256
+ let dx = label.ax - midX
1257
+ let dy = label.ay - midY
1258
+ const len = Math.hypot(dx, dy) || 1
1259
+ dx /= len
1260
+ dy /= len
1261
+ const push = Math.min(len + label.rad * 0.55 + 26, Math.min(state.w, state.h) * 0.5)
1262
+ let lx = label.ax + dx * (label.rad * 0.9 + 30)
1263
+ let ly = label.ay + dy * (label.rad * 0.9 + 30)
1264
+ lx = Math.min(Math.max(lx, w / 2 + 16), state.w - w / 2 - 16)
1265
+ ly = Math.min(Math.max(ly, fs + 52), state.h - 32)
1266
+ // 撞了别直接丢:先上下让一让(最多三次),让不开才放弃。
1267
+ // 以前一撞就 continue,缩小时总有一两个簇名静默消失,看着像漏渲染。
1268
+ const hitAt = (tx, ty) => taken.some((t) => Math.abs(t.x - tx) < (t.w + w) / 2 + 12 && Math.abs(t.y - ty) < 26)
1269
+ const minY = fs + 52
1270
+ const maxY = state.h - 32
1271
+ let placed = false
1272
+ for (const dy2 of [0, -(fs + 16), fs + 16, -(fs * 2 + 26), fs * 2 + 26]) {
1273
+ const ty = Math.min(Math.max(ly + dy2, minY), maxY)
1274
+ if (!hitAt(lx, ty)) {
1275
+ ly = ty
1276
+ placed = true
1277
+ break
1278
+ }
1279
+ }
1280
+ if (!placed) {
1281
+ ctx.restore()
1282
+ continue
1283
+ }
1284
+ taken.push({ x: lx, y: ly, w })
1285
+ // 引导线:从簇边到标签
1286
+ ctx.strokeStyle = rgba(label.col, 0.16)
1287
+ ctx.lineWidth = 1
1288
+ ctx.beginPath()
1289
+ ctx.moveTo(label.ax + dx * label.rad * 0.35, label.ay + dy * label.rad * 0.35)
1290
+ ctx.lineTo(lx, ly)
1291
+ ctx.stroke()
1292
+ ctx.fillStyle = 'rgba(4,6,12,0.55)'
1293
+ ctx.beginPath()
1294
+ const rx = lx - w / 2 - 9
1295
+ const ry = ly - fs * 1.05
1296
+ const rw = w + 18
1297
+ const rh = fs * 1.5
1298
+ const rr = rh / 2
1299
+ ctx.moveTo(rx + rr, ry)
1300
+ ctx.arcTo(rx + rw, ry, rx + rw, ry + rh, rr)
1301
+ ctx.arcTo(rx + rw, ry + rh, rx, ry + rh, rr)
1302
+ ctx.arcTo(rx, ry + rh, rx, ry, rr)
1303
+ ctx.arcTo(rx, ry, rx + rw, ry, rr)
1304
+ ctx.fill()
1305
+ if (ctx.letterSpacing !== undefined) ctx.letterSpacing = '1.5px'
1306
+ ctx.fillStyle = rgba(label.col, 0.86)
1307
+ ctx.fillText(label.text, lx, ly)
1308
+ ctx.restore()
1309
+ }
1310
+
1311
+ // 时间模式:左侧行名 + 底部时间刻度
1312
+ if (state.mode === 'time' && state.timeRange && state.timeRows) {
1313
+ const { min, max } = state.timeRange
1314
+ const leftX = Math.max(300, toScreen(-0.38 * state.w, 0)[0])
1315
+ const rightX = toScreen(0.38 * state.w, 0)[0]
1316
+ const avail = Math.max(46, leftX - 14 - 272)
1317
+ ctx.save()
1318
+ ctx.font = '500 11px Inter, "PingFang SC", "Microsoft YaHei", sans-serif'
1319
+ ctx.textAlign = 'right'
1320
+ for (const row of state.timeRows) {
1321
+ const sy = toScreen(0, row.y)[1]
1322
+ if (sy < 40 || sy > state.h - 6) continue
1323
+ ctx.fillStyle = rgba(row.color || '#6cc8ff', 0.92)
1324
+ let label = String(row.title).toUpperCase()
1325
+ while (label.length > 3 && ctx.measureText(label).width > avail) label = label.slice(0, -1)
1326
+ if (label !== String(row.title).toUpperCase()) {
1327
+ while (label.length > 3 && ctx.measureText(label + '…').width > avail) label = label.slice(0, -1)
1328
+ label += '…'
1329
+ }
1330
+ ctx.fillText(label, leftX - 12, sy + 4)
1331
+ ctx.strokeStyle = rgba(row.color || '#6cc8ff', 0.12)
1332
+ ctx.lineWidth = 1
1333
+ ctx.beginPath()
1334
+ ctx.moveTo(leftX - 6, sy)
1335
+ ctx.lineTo(rightX, sy)
1336
+ ctx.stroke()
1337
+ }
1338
+ // 时间刻度:按跨度自适应(小时/天/月)
1339
+ const HOUR = 3600000
1340
+ const DAY = 86400000
1341
+ const span = Math.max(1, max - min)
1342
+ const steps = [HOUR, 3 * HOUR, 6 * HOUR, 12 * HOUR, DAY, 2 * DAY, 7 * DAY, 14 * DAY, 30 * DAY, 90 * DAY, 365 * DAY]
1343
+ const stepMs = steps.find((s) => span / s <= 8) || 365 * DAY
1344
+ const shortSpan = span <= 3 * DAY
1345
+ const fmt = (d) => {
1346
+ const p = (v) => String(v).padStart(2, '0')
1347
+ if (stepMs < DAY) return `${d.getMonth() + 1}/${d.getDate()} ${p(d.getHours())}:${p(d.getMinutes())}`
1348
+ return `${d.getMonth() + 1}/${d.getDate()}`
1349
+ }
1350
+ const start = new Date(min)
1351
+ if (stepMs >= DAY) {
1352
+ start.setHours(0, 0, 0, 0)
1353
+ if (stepMs >= 30 * DAY) start.setDate(1)
1354
+ } else {
1355
+ start.setMinutes(0, 0, 0)
1356
+ start.setHours(Math.floor(start.getHours() / (stepMs / HOUR)) * (stepMs / HOUR))
1357
+ }
1358
+ const t = new Date(start.getTime() + stepMs)
1359
+ ctx.textAlign = 'center'
1360
+ ctx.font = '500 10.5px Inter, "PingFang SC", "Microsoft YaHei", sans-serif'
1361
+ ctx.fillStyle = 'rgba(170,200,230,0.82)'
1362
+ while (t.getTime() < max) {
1363
+ const worldX = state.w * 0.12 + ((t.getTime() - min) / Math.max(1, max - min)) * state.w * 0.76 - state.w / 2
1364
+ const x = toScreen(worldX, 0)[0]
1365
+ if (x > leftX && x < rightX + 40) {
1366
+ ctx.fillText(fmt(t), x, state.h - 34)
1367
+ ctx.strokeStyle = 'rgba(150,180,210,0.12)'
1368
+ ctx.beginPath()
1369
+ ctx.moveTo(x, 46)
1370
+ ctx.lineTo(x, state.h - 44)
1371
+ ctx.stroke()
1372
+ }
1373
+ t.setTime(t.getTime() + stepMs)
1374
+ }
1375
+ if (shortSpan) {
1376
+ ctx.textAlign = 'left'
1377
+ ctx.fillStyle = 'rgba(150,180,210,0.55)'
1378
+ ctx.fillText(T('最近 ') + Math.round(span / HOUR) + T(' 小时'), leftX, state.h - 16)
1379
+ }
1380
+ ctx.restore()
1381
+ }
1382
+
1383
+ // 脉冲:沿边的激活传播
1384
+ const now = performance.now()
1385
+ state.pulses = state.pulses.filter((p) => now - p.t0 < p.life)
1386
+ for (const p of state.pulses) {
1387
+ const prog = (now - p.t0) / p.life
1388
+ const ease = 1 - Math.pow(1 - prog, 2.2)
1389
+ const a = p._a
1390
+ const b = p._b
1391
+ if (!a || !b) continue
1392
+ const [ax, ay] = toScreen(a.x, a.y)
1393
+ const [bx, by] = toScreen(b.x, b.y)
1394
+ const x = ax + (bx - ax) * ease
1395
+ const y = ay + (by - ay) * ease
1396
+ const rad = 6 + 4 * Math.sin(prog * Math.PI)
1397
+ const g = ctx.createRadialGradient(x, y, 0, x, y, rad * 2.4)
1398
+ g.addColorStop(0, `rgba(150,240,255,${0.85 * (1 - prog * 0.6)})`)
1399
+ g.addColorStop(1, 'rgba(150,240,255,0)')
1400
+ ctx.fillStyle = g
1401
+ ctx.beginPath()
1402
+ ctx.arc(x, y, rad * 2.4, 0, 6.2832)
1403
+ ctx.fill()
1404
+ }
1405
+
1406
+ // 正在被「点亮」的节点呼吸圈
1407
+ for (const id of state.pulseNodes || []) {
1408
+ const n = state.byId.get(id)
1409
+ if (!n) continue
1410
+ const [px, py] = toScreen(n.x, n.y)
1411
+ const tt = (now % 1600) / 1600
1412
+ ctx.strokeStyle = `rgba(150,240,255,${0.55 * (1 - tt)})`
1413
+ ctx.lineWidth = 1.2
1414
+ ctx.beginPath()
1415
+ ctx.arc(px, py, n.r + 6 + tt * 26, 0, 6.2832)
1416
+ ctx.stroke()
1417
+ }
1418
+ ctx.lineWidth = Math.max(0.5, k)
1419
+ }
1420
+
1421
+ function frame(ts) {
1422
+ if (state.pump) {
1423
+ pumpReveal(ts || performance.now())
1424
+ draw()
1425
+ }
1426
+ if (state.moving) {
1427
+ simulate(1, 0.994)
1428
+ draw()
1429
+ state.moving = false
1430
+ }
1431
+ if (state.target) {
1432
+ const t = state.target
1433
+ const s = 0.14
1434
+ state.cam.k += (t.k - state.cam.k) * s
1435
+ state.cam.x += (t.x - state.cam.x) * s
1436
+ state.cam.y += (t.y - state.cam.y) * s
1437
+ if (Math.abs(t.k - state.cam.k) < 0.002 && Math.abs(t.x - state.cam.x) < 0.6 && Math.abs(t.y - state.cam.y) < 0.6) {
1438
+ state.cam.k = t.k
1439
+ state.cam.x = t.x
1440
+ state.cam.y = t.y
1441
+ state.target = null
1442
+ }
1443
+ draw()
1444
+ }
1445
+ if (state.pulses.length || (state.pulseNodes && state.pulseNodes.length)) draw()
1446
+ requestAnimationFrame(frame)
1447
+ }
1448
+
1449
+ // ---------------- 交互 ----------------
1450
+ let rafId = 0
1451
+ api.redraw = () => {
1452
+ if (rafId) return
1453
+ rafId = requestAnimationFrame(() => {
1454
+ rafId = 0
1455
+ draw()
1456
+ })
1457
+ }
1458
+ // 调试用:同步画一帧并返回耗时
1459
+ api.drawNow = () => {
1460
+ const t0 = performance.now()
1461
+ draw()
1462
+ return performance.now() - t0
1463
+ }
1464
+ // 调试用:看一眼内部状态(NaN 排查 + 「边到底去哪了」三段闸门)
1465
+ api.debugState = () => {
1466
+ let passFilter = 0
1467
+ let passReveal = 0
1468
+ for (const e of state.edges) {
1469
+ if (!visibleEdge(e)) continue
1470
+ passFilter++
1471
+ const ra = e._a && e._a.reveal != null ? e._a.reveal : 1
1472
+ const rb = e._b && e._b.reveal != null ? e._b.reveal : 1
1473
+ if ((ra < rb ? ra : rb) >= 0.85) passReveal++
1474
+ }
1475
+ let minX = Infinity, minY = Infinity, maxX = -Infinity, maxY = -Infinity
1476
+ for (const n of state.nodes) {
1477
+ if (!isFinite(n.x) || !isFinite(n.y)) continue
1478
+ if (n.x < minX) minX = n.x; if (n.x > maxX) maxX = n.x
1479
+ if (n.y < minY) minY = n.y; if (n.y > maxY) maxY = n.y
1480
+ }
1481
+ return {
1482
+ cam: { ...state.cam },
1483
+ bounds: { minX, minY, maxX, maxY, w: maxX - minX, h: maxY - minY },
1484
+ farNodes: state.nodes.filter((n) => Math.abs(n.x) > 3000 || Math.abs(n.y) > 3000).length,
1485
+ size: { w: state.w, h: state.h },
1486
+ clusters: state.clusters.length,
1487
+ sample: state.nodes.slice(0, 3).map((n) => ({ id: n.id, x: n.x, y: n.y, r: n.r, cluster: n.cluster })),
1488
+ bad: state.nodes.filter((n) => !isFinite(n.x) || !isFinite(n.y)).length,
1489
+ // 「连接消失」排查三件套
1490
+ edges: state.edges.length,
1491
+ edgesPassFilter: passFilter,
1492
+ edgesPassReveal: passReveal,
1493
+ nodesRevealed: state.nodes.filter((n) => (n.reveal == null ? 1 : n.reveal) >= 0.85).length,
1494
+ pump: state.pump ? { done: state.pump.done, ticks: state.pump.ticks } : null,
1495
+ alpha: state.alpha,
1496
+ mode: state.mode,
1497
+ // 边路径缓存是否命中:perf 探针靠这两个数判断「每帧重建 6382 条曲线」有没有发生
1498
+ edgeCache: state.edgeCache ? state.edgeCache.buckets.size : 0,
1499
+ geoVersion: state.geoVersion || 0,
1500
+ filter: state.filter
1501
+ ? {
1502
+ ws: state.filter.ws ? state.filter.ws.size : null,
1503
+ levels: state.filter.levels ? state.filter.levels.size : null,
1504
+ types: state.filter.types ? state.filter.types.size : null,
1505
+ providers: state.filter.providers ? state.filter.providers.size : null,
1506
+ minW: state.filter.minW || 0,
1507
+ minImp: state.filter.minImp || 0,
1508
+ }
1509
+ : null,
1510
+ }
1511
+ }
1512
+ // 切回 2D 时补量一次:canvas 在 3D 模式下是隐藏的,window.resize 不会因切模式而触发
1513
+ api.resize = resize
1514
+
1515
+ // 导出前把「还在长」的那一屏直接点亮:否则刚点完重建就导出,会拿到一张只长了一半的图
1516
+ api.finishReveal = () => {
1517
+ if (state.pump) {
1518
+ for (const n of state.nodes) n.reveal = 1
1519
+ state.pump = null
1520
+ state.alpha = 1
1521
+ draw()
1522
+ return true
1523
+ }
1524
+ return false
1525
+ }
1526
+
1527
+ api.wake = (ticks) => {
1528
+ state.alpha = Math.max(state.alpha, 0.55)
1529
+ simulate(ticks || 40, 0.985)
1530
+ api.redraw()
1531
+ }
1532
+
1533
+ api.visibleNodes = function visibleNodes() {
1534
+ const f = state.filter
1535
+ if (!f) return state.nodes
1536
+ return state.nodes.filter((n) => n.visible !== false)
1537
+ }
1538
+
1539
+ api.setFilter = function setFilter(filter) {
1540
+ state.filter = filter
1541
+ const f = filter
1542
+ for (const n of state.nodes) {
1543
+ let vis = true
1544
+ if (f.ws && !f.ws.has(n.ws)) vis = false
1545
+ if (f.levels && !f.levels.has(n.level)) vis = false
1546
+ if (f.providers && !f.providers.has(n.provider || 'meow-memory')) vis = false
1547
+ if (f.minImp && (n.importance || 0) < f.minImp) vis = false
1548
+ n.hidden = !vis
1549
+ n.visible = vis
1550
+ }
1551
+ state.hiddenVersion = (state.hiddenVersion || 0) + 1
1552
+ api.redraw()
1553
+ }
1554
+
1555
+ api.highlight = function highlight(id) {
1556
+ state.highlight = id
1557
+ if (!id) {
1558
+ state.highlightSet = null
1559
+ } else {
1560
+ const set = new Set([id])
1561
+ for (const e of state.edges) {
1562
+ if (e.a === id) set.add(e.b)
1563
+ else if (e.b === id) set.add(e.a)
1564
+ }
1565
+ state.highlightSet = set
1566
+ }
1567
+ api.redraw()
1568
+ }
1569
+
1570
+ api.select = function select(id) {
1571
+ state.selected = id
1572
+ api.redraw()
1573
+ }
1574
+
1575
+ /** 高亮一条证据链(按顺序的节点 id);传 null 清掉。 */
1576
+ api.setPath = function setPath(ids) {
1577
+ if (!ids || ids.length < 2) {
1578
+ state.pathSeq = null
1579
+ state.pathIds = null
1580
+ state.pathEdges = null
1581
+ api.redraw()
1582
+ return
1583
+ }
1584
+ state.pathSeq = ids.slice()
1585
+ state.pathIds = new Set(ids)
1586
+ const edges = new Set()
1587
+ for (let i = 0; i + 1 < ids.length; i += 1) {
1588
+ const a = ids[i]
1589
+ const b = ids[i + 1]
1590
+ edges.add(a < b ? a + '|' + b : b + '|' + a)
1591
+ }
1592
+ state.pathEdges = edges
1593
+ api.redraw()
1594
+ }
1595
+
1596
+ /** 程序化打开某条记忆(调试与「从搜索直接定位」共用)。 */
1597
+ api.open = function open(id) {
1598
+ api.select(id)
1599
+ emit('select', id)
1600
+ }
1601
+
1602
+ /** 某条记忆在屏幕上的坐标(调试、自动化测试用)。 */
1603
+ api.screenOf = function screenOf(id) {
1604
+ const n = state.byId.get(id)
1605
+ if (!n || n.hidden) return null
1606
+ const [x, y] = toScreen(n.x, n.y)
1607
+ return { x, y, r: (n.r || nodeRadius(n)) * state.cam.k }
1608
+ }
1609
+
1610
+ api.focusNode = function focusNode(id, zoom) {
1611
+ const n = state.byId.get(id)
1612
+ if (!n) return
1613
+ const k = zoom || Math.max(1.5, state.cam.k)
1614
+ // 让节点落在「可用区域」的正中(左侧筛选栏、右侧详情栏都是空的),
1615
+ // 不然打开详情后焦点会被面板压住半边。
1616
+ const P = state.pad || { left: 0, right: 0, top: 0, bottom: 0 }
1617
+ const availW = Math.max(220, state.w - P.left - P.right)
1618
+ const availH = Math.max(220, state.h - P.top - P.bottom)
1619
+ const cx = P.left + availW / 2 - state.w / 2
1620
+ const cy = P.top + availH / 2 - state.h / 2
1621
+ state.target = { k, x: n.x - cx / k, y: n.y - cy / k }
1622
+ }
1623
+
1624
+ /**
1625
+ * 键盘行走用:只把镜头平移到这颗星,缩放不动。
1626
+ * 方向键是「走过去看」,不是每次重新构图——每按一下都变焦会晕。
1627
+ */
1628
+ api.centerOn = function centerOn(id) {
1629
+ const n = state.byId.get(id)
1630
+ if (!n) return
1631
+ const P = state.pad || { left: 0, right: 0, top: 0, bottom: 0 }
1632
+ const availW = Math.max(220, state.w - P.left - P.right)
1633
+ const availH = Math.max(220, state.h - P.top - P.bottom)
1634
+ const cx = P.left + availW / 2 - state.w / 2
1635
+ const cy = P.top + availH / 2 - state.h / 2
1636
+ state.target = { k: state.cam.k, x: n.x - cx / state.cam.k, y: n.y - cy / state.cam.k }
1637
+ }
1638
+
1639
+ /**
1640
+ * 键盘加号/减号用:以当前视口中心为轴缩一档。
1641
+ * 上下限和滚轮完全一致(0.18–5.5),否则键盘能把视图推进滚轮到不了的死角。
1642
+ */
1643
+ api.zoomBy = function zoomBy(factor) {
1644
+ const f = Number(factor)
1645
+ if (!f || !isFinite(f) || f <= 0) return state.cam.k
1646
+ const k = Math.min(5.5, Math.max(0.18, state.cam.k * f))
1647
+ if (k === state.cam.k) return k
1648
+ state.target = null
1649
+ state.cam.k = k
1650
+ api.redraw()
1651
+ return k
1652
+ }
1653
+
1654
+ /** 从一组种子沿边打出脉冲。 */
1655
+ api.pulseFrom = function pulseFrom(ids, spread) {
1656
+ const now = performance.now()
1657
+ const set = new Set(ids || [])
1658
+ const out = []
1659
+ let budget = 220
1660
+ for (const e of state.edges) {
1661
+ if (budget <= 0) break
1662
+ if (!set.has(e.a) && !set.has(e.b)) continue
1663
+ if (e.w < (spread ? 0.25 : 0.4)) continue
1664
+ out.push({ ...e, t0: now + Math.random() * 260, life: 900 + Math.random() * 700 })
1665
+ budget--
1666
+ }
1667
+ state.pulses.push(...out)
1668
+ state.pulseNodes = ids || []
1669
+ setTimeout(() => {
1670
+ state.pulseNodes = []
1671
+ api.redraw()
1672
+ }, 2400)
1673
+ api.redraw()
1674
+ }
1675
+
1676
+ // 供交互层与自动化验证调用:屏幕坐标 → 命中的节点(走空间网格)
1677
+ api.pick = pick
1678
+
1679
+ api.debug = function debug() { return {
1680
+ mode: state.mode,
1681
+ timeRange: state.timeRange,
1682
+ rows: (state.timeRows || []).length,
1683
+ w: state.w, h: state.h, k: state.k,
1684
+ // 相机快照:分页合并之后不该动它(动了就是「加载下一页把我视角甩走了」)
1685
+ cam: { k: state.cam.k, x: state.cam.x, y: state.cam.y },
1686
+ // 视口裁剪的现场数据:edges=总边数,considered=这一帧真正拿去建路径的边数
1687
+ cull: state.cull || null,
1688
+ grid: state.grids
1689
+ ? { sig: state.gridSig, nodeCells: state.grids.nodeGrid.size, edgeCells: state.grids.edgeGrid.size, ver: state.geoVersion || 0 }
1690
+ : null,
1691
+ drawMs: state.lastDrawMs == null ? null : state.lastDrawMs,
1692
+ }
1693
+ }
1694
+
1695
+ api.setMode = function setMode(mode) {
1696
+ if (mode === state.mode) return
1697
+ state.mode = mode
1698
+ if (mode === 'time') {
1699
+ layoutTime()
1700
+ for (const n of state.nodes) {
1701
+ n.x = n.tx
1702
+ n.y = n.ty
1703
+ n.vx = 0
1704
+ n.vy = 0
1705
+ }
1706
+ api.fit()
1707
+ api.redraw()
1708
+ } else {
1709
+ state.alpha = 0.9
1710
+ simulate(120, 0.985)
1711
+ api.fit()
1712
+ api.redraw()
1713
+ }
1714
+ }
1715
+
1716
+ // 指针
1717
+ function pos(ev) {
1718
+ const rect = canvas.getBoundingClientRect()
1719
+ return [ev.clientX - rect.left, ev.clientY - rect.top]
1720
+ }
1721
+ function pick(sx, sy) {
1722
+ const [wx, wy] = toWorld(sx, sy)
1723
+ const tol = Math.max(10, 14 / state.cam.k)
1724
+ // 网格查询:5 万条时命中通常只有个位数候选,不再线性扫全表
1725
+ ensureGrids()
1726
+ const grid = state.grids.nodeGrid
1727
+ const c0 = Math.floor((wx - tol) / NODE_CELL)
1728
+ const c1 = Math.floor((wx + tol) / NODE_CELL)
1729
+ const r0 = Math.floor((wy - tol) / NODE_CELL)
1730
+ const r1 = Math.floor((wy + tol) / NODE_CELL)
1731
+ let best = null
1732
+ let bestD = Infinity
1733
+ for (let cy = r0; cy <= r1; cy++) {
1734
+ for (let cx = c0; cx <= c1; cx++) {
1735
+ const arr = grid.get(cx + ',' + cy)
1736
+ if (!arr) continue
1737
+ for (let j = 0; j < arr.length; j++) {
1738
+ const n = state.nodes[arr[j]]
1739
+ if (n.hidden) continue
1740
+ const d = Math.hypot(n.x - wx, n.y - wy)
1741
+ if (d < tol && d < bestD) {
1742
+ bestD = d
1743
+ best = n
1744
+ }
1745
+ }
1746
+ }
1747
+ }
1748
+ return best
1749
+ }
1750
+
1751
+ // 双击空白 = 回全视图(双击节点=聚焦它,别抢)
1752
+ canvas.addEventListener('dblclick', (ev) => {
1753
+ if (pick(ev.offsetX, ev.offsetY)) return
1754
+ api.fit()
1755
+ })
1756
+
1757
+ canvas.addEventListener('pointerdown', (ev) => {
1758
+ // 中键/右键只负责拖视角,永远不选中节点;左键才点选与拖节点。
1759
+ const [sx, sy] = pos(ev)
1760
+ const panOnly = ev.button !== 0
1761
+ if (panOnly) ev.preventDefault()
1762
+ canvas.setPointerCapture(ev.pointerId)
1763
+ const n = panOnly ? null : pick(sx, sy)
1764
+ if (n) {
1765
+ state.drag = { type: 'node', node: n, sx, sy, button: ev.button, moved: false }
1766
+ n.pinned = true
1767
+ } else {
1768
+ state.drag = { type: 'pan', sx, sy, camX: state.cam.x, camY: state.cam.y, button: ev.button }
1769
+ canvas.classList.add('dragging')
1770
+ }
1771
+ })
1772
+
1773
+ canvas.addEventListener('auxclick', (ev) => { if (ev.button === 1) ev.preventDefault() })
1774
+ canvas.addEventListener('contextmenu', (ev) => ev.preventDefault())
1775
+
1776
+ canvas.addEventListener('pointermove', (ev) => {
1777
+ const [sx, sy] = pos(ev)
1778
+ state.pointer.x = sx
1779
+ state.pointer.y = sy
1780
+ if (state.drag) {
1781
+ if (state.drag.type === 'pan') {
1782
+ state.cam.x = state.drag.camX - (sx - state.drag.sx) / state.cam.k
1783
+ state.cam.y = state.drag.camY - (sy - state.drag.sy) / state.cam.k
1784
+ state.target = null
1785
+ if (!state.drag.moved && Math.hypot(sx - state.drag.sx, sy - state.drag.sy) > 4) state.drag.moved = true
1786
+ } else {
1787
+ const [wx, wy] = toWorld(sx, sy)
1788
+ const n = state.drag.node
1789
+ n.x = wx
1790
+ n.y = wy
1791
+ n.vx = 0
1792
+ n.vy = 0
1793
+ // 位置变了:边路径与空间网格都要重算,否则被拖的节点会「甩开」自己的线
1794
+ state.geoVersion = (state.geoVersion || 0) + 1
1795
+ if (!state.drag.moved && Math.hypot(sx - state.drag.sx, sy - state.drag.sy) > 4) state.drag.moved = true
1796
+ state.moving = true
1797
+ }
1798
+ api.redraw()
1799
+ return
1800
+ }
1801
+ const n = pick(sx, sy)
1802
+ canvas.classList.toggle('pointing', !!n)
1803
+ if ((n && n.id) !== state.hover) {
1804
+ state.hover = n ? n.id : null
1805
+ api.highlight(state.hover)
1806
+ emit('hover', n ? { id: n.id, x: sx, y: sy } : null)
1807
+ }
1808
+ })
1809
+
1810
+ function endDrag(ev) {
1811
+ if (state.drag) {
1812
+ if (state.drag.type === 'node') {
1813
+ state.drag.node.pinned = false
1814
+ state.moving = true
1815
+ }
1816
+ if (state.drag.type === 'pan') canvas.classList.remove('dragging')
1817
+ state.drag = null
1818
+ }
1819
+ }
1820
+ canvas.addEventListener('pointerup', (ev) => {
1821
+ const drag = state.drag
1822
+ const [sx, sy] = pos(ev)
1823
+ const moved = drag && (drag.moved || Math.hypot(sx - drag.sx, sy - drag.sy) > 4)
1824
+ endDrag(ev)
1825
+ // 只有「左键 + 没拖动」才算一次点选
1826
+ if (!drag || drag.button !== 0 || moved) return
1827
+ // 拉远到「光斑」这一档时,人在光斑上点的意思几乎总是「进去看看」,
1828
+ // 而不是「选中光斑底下恰好压着的那一个点」——所以先判 LOD,再判单点。
1829
+ const wsAt = api.lodAt(sx, sy)
1830
+ if (wsAt) {
1831
+ api.focusCluster(wsAt)
1832
+ emit('lod', wsAt)
1833
+ return
1834
+ }
1835
+ const n = pick(sx, sy)
1836
+ if (n && ev.shiftKey && state.selected && state.selected !== n.id) {
1837
+ // Shift + 点:不是换选中,而是问「选中的那条和这条,中间怎么连上的」
1838
+ emit('path', { from: state.selected, to: n.id })
1839
+ return
1840
+ }
1841
+ if (n) {
1842
+ api.select(n.id)
1843
+ emit('select', n.id)
1844
+ } else {
1845
+ // 点空处:如果落在 LOD 聚合光斑上,等于「下钻进这个项目」
1846
+ const ws = api.lodAt(sx, sy)
1847
+ if (ws) {
1848
+ api.focusCluster(ws)
1849
+ emit('lod', ws)
1850
+ return
1851
+ }
1852
+ api.select(null)
1853
+ emit('select', null)
1854
+ }
1855
+ })
1856
+ canvas.addEventListener('pointerleave', () => {
1857
+ if (!state.drag) api.highlight(null)
1858
+ })
1859
+
1860
+ canvas.addEventListener(
1861
+ 'wheel',
1862
+ (ev) => {
1863
+ ev.preventDefault()
1864
+ const [sx, sy] = pos(ev)
1865
+ const [wx, wy] = toWorld(sx, sy)
1866
+ const factor = Math.exp(-ev.deltaY * 0.0016)
1867
+ const k = Math.min(5.5, Math.max(0.18, state.cam.k * factor))
1868
+ state.cam.k = k
1869
+ // 保持鼠标下的世界点不动
1870
+ state.cam.x = wx - (sx - state.w / 2) / k
1871
+ state.cam.y = wy - (sy - state.h / 2) / k
1872
+ state.target = null
1873
+ api.redraw()
1874
+ },
1875
+ { passive: false },
1876
+ )
1877
+
1878
+ window.addEventListener('resize', resize)
1879
+ resize()
1880
+ requestAnimationFrame(frame)
1881
+ window.__nebulaStage = api
1882
+ return api
1883
+ }
1884
+
1885
+ N.LEVEL_COLOR = LEVEL_COLOR
1886
+ N.TYPE_COLOR = TYPE_COLOR
1887
+ N.rgba = rgba
1888
+ })()
1889
+
1890
+ /* 顶部导航的悬停提示 */