dsh-memo-sync 0.0.0-stage → 2.74.6

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/client.js ADDED
@@ -0,0 +1,1512 @@
1
+ /**
2
+ * Client half of dsh-memo-sync: a 「星图」 tab in the conversation view.
3
+ * Data comes from the host route GET /api/memo-star/data (read-only, no model calls).
4
+ */
5
+ window.__ModuleLoader__.load({
6
+ id: 'dsh-memo-sync',
7
+ factory(require) {
8
+ const React = require('react');
9
+ const h = React.createElement;
10
+ const SHELL = { core: 1.0, insight: 1.28, fact: 1.55, skill: 2.1, daily: 2.65, emotion: 3.15 };
11
+ const LABELS = { core: '不常变', insight: '认识', fact: '事实', skill: '方法', daily: '当天', emotion: '情绪' };
12
+
13
+ // 右侧栏集成:优先把正文送进官方 sidebar 的 tab;拿不到服务就退回 tab 内面板
14
+ const sidebar = { open: null, ctx: null };
15
+ function resolveSidebar() {
16
+ const ctx = sidebar.ctx;
17
+ if (!ctx) return null;
18
+ const right = typeof ctx.get === 'function' ? ctx.get('sidebarRight') || ctx.sidebarRight : ctx.sidebarRight;
19
+ if (right && typeof right.openTab === 'function') {
20
+ sidebar.open = (kind) => {
21
+ try {
22
+ right.openTab(kind);
23
+ } catch (e) {
24
+ return false;
25
+ }
26
+ return true;
27
+ };
28
+ }
29
+ return sidebar.open;
30
+ }
31
+ const pending = { id: '', line: 0, frag: null, listeners: new Set() };
32
+ function setPending(id, line, frag) {
33
+ pending.id = id;
34
+ pending.line = Number(line) || 0;
35
+ pending.frag = frag || null;
36
+ pending.listeners.forEach((f) => f());
37
+ }
38
+ function subscribePending(f) {
39
+ pending.listeners.add(f);
40
+ return () => pending.listeners.delete(f);
41
+ }
42
+
43
+ function hash(s) {
44
+ let x = 2166136261;
45
+ for (let i = 0; i < s.length; i += 1) {
46
+ x ^= s.charCodeAt(i);
47
+ x = Math.imul(x, 16777619);
48
+ }
49
+ return ((x >>> 0) % 10000) / 10000;
50
+ }
51
+
52
+ function shellPos(i, total, r, seed) {
53
+ const phi = Math.acos(1 - 2 * ((i + 0.5) / Math.max(1, total)));
54
+ const theta = Math.PI * (1 + Math.sqrt(5)) * i + seed * 2.4;
55
+ const jr = r * (0.94 + hash('r' + i + seed) * 0.12);
56
+ return [jr * Math.sin(phi) * Math.cos(theta), jr * Math.cos(phi), jr * Math.sin(phi) * Math.sin(theta)];
57
+ }
58
+
59
+ function readTheme() {
60
+ const css = (name, fallback) => {
61
+ const v = getComputedStyle(document.documentElement).getPropertyValue(name).trim();
62
+ return v || fallback;
63
+ };
64
+ return {
65
+ text: css('--dsw-alias-label-primary', '#e6edf7'),
66
+ muted: css('--dsw-alias-label-secondary', '#8fa2c0'),
67
+ bg: css('--dsw-alias-bg-layer-1', '#0b1220'),
68
+ border: css('--dsw-alias-border-l2', '#22344f'),
69
+ brand: css('--dsw-alias-brand-primary', '#7fb2ff'),
70
+ };
71
+ }
72
+
73
+ function useTheme() {
74
+ const [theme, setTheme] = React.useState(readTheme);
75
+ React.useEffect(() => {
76
+ const update = () => setTheme(readTheme());
77
+ let mo = null;
78
+ try {
79
+ mo = new MutationObserver(update);
80
+ mo.observe(document.documentElement, { attributes: true, attributeFilter: ['class', 'style', 'data-theme'] });
81
+ } catch (e) {}
82
+ const mq = window.matchMedia ? window.matchMedia('(prefers-color-scheme: dark)') : null;
83
+ if (mq && mq.addEventListener) mq.addEventListener('change', update);
84
+ return () => {
85
+ if (mo) mo.disconnect();
86
+ if (mq && mq.removeEventListener) mq.removeEventListener('change', update);
87
+ };
88
+ }, []);
89
+ return theme;
90
+ }
91
+
92
+ function EntryPane() {
93
+ const theme = useTheme();
94
+ const [state, setState] = React.useState(null);
95
+ const [error, setError] = React.useState('');
96
+ const [copied, setCopied] = React.useState(false);
97
+
98
+ const load = React.useCallback(() => {
99
+ const id = pending.id;
100
+ if (!id) {
101
+ setState(null);
102
+ setError('');
103
+ return;
104
+ }
105
+ setState({ id, title: id, loading: true, line: pending.line });
106
+ setError('');
107
+ fetch('/api/memo-star/entry?id=' + encodeURIComponent(id) + (pending.line ? '&line=' + pending.line : ''), { cache: 'no-store' })
108
+ .then((r) => r.json())
109
+ .then((d) => {
110
+ if (d && d.ok) setState(d);
111
+ else setError((d && d.error) === 'private' ? '私密条目:界面上不显示正文' : (d && d.error) || '读不到这个文件');
112
+ })
113
+ .catch((e) => setError(String((e && e.message) || e)));
114
+ }, []);
115
+
116
+ React.useEffect(() => {
117
+ load();
118
+ return subscribePending(load);
119
+ }, [load]);
120
+
121
+ const preRef = React.useRef(null);
122
+ React.useEffect(() => {
123
+ const el = preRef.current;
124
+ const line = Number((state && state.line) || pending.line) || 0;
125
+ if (el && line > 0 && !pending.frag) {
126
+ const lh = 11.5 * 1.65;
127
+ el.scrollTop = Math.max(0, (line - 3) * lh);
128
+ }
129
+ }, [state]);
130
+
131
+ const copy = () => {
132
+ try {
133
+ navigator.clipboard.writeText((state && state.path) || pending.id);
134
+ setCopied(true);
135
+ setTimeout(() => setCopied(false), 1200);
136
+ } catch (e) {}
137
+ };
138
+
139
+ const btn = {
140
+ font: 'inherit',
141
+ fontSize: 11,
142
+ color: theme.muted,
143
+ background: 'transparent',
144
+ border: '1px solid ' + theme.border,
145
+ borderRadius: 6,
146
+ padding: '2px 8px',
147
+ cursor: 'pointer',
148
+ };
149
+
150
+ if (!state && !error) {
151
+ return h('div', { style: { padding: 14, fontSize: 12, color: theme.muted } }, '在星图里双击一颗星,这里显示它的正文。');
152
+ }
153
+ // 从卫星进来时只显示那一条片段(按行号切片),并给出片段索引
154
+ const frag = pending.frag;
155
+ const sliceFrag = () => {
156
+ const body = String((state && state.body) || '');
157
+ const line = Number((state && state.line) || pending.line) || 0;
158
+ if (!line) return body;
159
+ const lines = body.split('\n');
160
+ const i = Math.max(0, line - 1);
161
+ const next = Number(frag && frag.next) || 0;
162
+ // 有下一条片段就切到它前面(标题片段能带上后面的正文),否则切到下一个空行
163
+ let j = next > line ? next - 1 : i + 1;
164
+ if (next <= line) {
165
+ while (j < lines.length && lines[j].trim() !== '') j += 1;
166
+ }
167
+ return lines.slice(i, Math.min(j, lines.length)).join('\n').trim();
168
+ };
169
+ const shownBody = error ? error : frag ? sliceFrag() : ((state && state.body) || '读取中…');
170
+ return h(
171
+ 'div',
172
+ { style: { display: 'flex', flexDirection: 'column', gap: 8, height: '100%', padding: 10 } },
173
+ h(
174
+ 'div',
175
+ { style: { display: 'flex', alignItems: 'flex-start', gap: 6, flexShrink: 0 } },
176
+ h(
177
+ 'div',
178
+ { style: { flex: 1, minWidth: 0 } },
179
+ h(
180
+ 'div',
181
+ { style: { fontSize: 13, fontWeight: 600, color: theme.text, whiteSpace: 'nowrap', overflow: 'hidden', textOverflow: 'ellipsis' } },
182
+ (state && state.title) || pending.id,
183
+ ),
184
+ h(
185
+ 'div',
186
+ { style: { fontSize: 10.5, color: theme.muted, marginTop: 2 } },
187
+ frag
188
+ ? '片段 #' + (frag.k || '?') + (frag.total ? ' / 共 ' + frag.total + ' 条' : '') + ' · 主题「' + ((state && state.title) || pending.id) + '」'
189
+ : (state && state.line ? '第 ' + state.line + ' 行 · ' : '') + ((state && state.path) || ''),
190
+ ),
191
+ ),
192
+ frag
193
+ ? h('button', { onClick: () => setPending(pending.id, pending.line, null), style: btn }, '看整条')
194
+ : null,
195
+ h('button', { onClick: copy, style: btn }, copied ? '已复制' : '复制路径'),
196
+ ),
197
+ h(
198
+ 'pre',
199
+ {
200
+ ref: preRef,
201
+ style: {
202
+ flex: 1,
203
+ margin: 0,
204
+ overflow: 'auto',
205
+ whiteSpace: 'pre-wrap',
206
+ wordBreak: 'break-word',
207
+ fontSize: 11.5,
208
+ lineHeight: 1.65,
209
+ color: theme.text,
210
+ fontFamily: 'ui-monospace, Consolas, "Microsoft YaHei", monospace',
211
+ },
212
+ },
213
+ shownBody,
214
+ ),
215
+ );
216
+ }
217
+
218
+ function Star3D(props) {
219
+ const theme = useTheme();
220
+ const hideLabelsRef = React.useRef(Boolean(props && props.hideNames));
221
+ React.useEffect(() => { hideLabelsRef.current = Boolean(props && props.hideNames); }, [props && props.hideNames]);
222
+ const hideLabels = () => hideLabelsRef.current;
223
+ const canvasRef = React.useRef(null);
224
+ const focusRef = React.useRef(null); // 当前聚焦的主星 id;null = 全景
225
+ const wrapRef = React.useRef(null);
226
+ const [data, setData] = React.useState(null);
227
+ const [error, setError] = React.useState('');
228
+ const [tick, setTick] = React.useState(0);
229
+ const sigRef = React.useRef('');
230
+ const [entry, setEntry] = React.useState(null);
231
+ const [preview, setPreview] = React.useState(null);
232
+ const [hint, setHint] = React.useState('');
233
+ const [copied, setCopied] = React.useState(false);
234
+
235
+ React.useEffect(() => {
236
+ let alive = true;
237
+ fetch('/api/memo-star/data', { cache: 'no-store' })
238
+ .then((r) => {
239
+ if (!r.ok) throw new Error('HTTP ' + r.status);
240
+ return r.json();
241
+ })
242
+ .then((d) => {
243
+ if (!alive) return;
244
+ // 只有内容真的变了才换数据:否则每 60 秒重建一次场景,视角会被重置
245
+ const sig = JSON.stringify(d);
246
+ if (sig === sigRef.current) return;
247
+ sigRef.current = sig;
248
+ setData(d);
249
+ })
250
+ .catch((e) => alive && setError(String((e && e.message) || e)));
251
+ return () => {
252
+ alive = false;
253
+ };
254
+ }, [tick]);
255
+
256
+ React.useEffect(() => {
257
+ const id = setInterval(() => setTick((n) => n + 1), 60_000);
258
+ return () => clearInterval(id);
259
+ }, []);
260
+
261
+
262
+ React.useEffect(() => {
263
+ const canvas = canvasRef.current;
264
+ const wrap = wrapRef.current;
265
+ if (!canvas || !wrap || !data) return;
266
+ const ctx = canvas.getContext('2d');
267
+ const nodes = data.nodes || [];
268
+ const byLayer = {};
269
+ nodes.forEach((n) => {
270
+ (byLayer[n.layer] = byLayer[n.layer] || []).push(n);
271
+ });
272
+ const pts = [];
273
+ Object.keys(byLayer).forEach((layer) => {
274
+ const list = byLayer[layer];
275
+ const r = SHELL[layer] || 3.6;
276
+ list.sort((a, b) => String(a.id).localeCompare(String(b.id), 'zh'));
277
+ list.forEach((n, i) => {
278
+ n.pos = shellPos(i, list.length, r, n.seed || hash(String(n.id)));
279
+ n.color = (data.palette[layer] && data.palette[layer].color) || '#8b93a7';
280
+ pts.push(n);
281
+ });
282
+ });
283
+
284
+ // ---- 力导向布局:共享关键词互相吸引、彼此排斥,层只给一点向心偏置 ----
285
+ // 观感关键:不再是把点摆在球壳上,而是让它们自己「结团」。
286
+ (() => {
287
+ const list = pts;
288
+ const idx = new Map(list.map((p, i) => [p.id, i]));
289
+ const pos = list.map((p) => p.pos.slice());
290
+ const vel = list.map(() => [0, 0, 0]);
291
+ const N = list.length;
292
+ const shellOf = (p) => (SHELL[p.layer] || 3.6) / 3.15;
293
+ const edges = (data.edges || []).filter((e) => idx.has(e.a) && idx.has(e.b));
294
+ for (let it = 0; it < 240; it += 1) {
295
+ for (let i = 0; i < N; i += 1) {
296
+ for (let j = i + 1; j < N; j += 1) {
297
+ let dx = pos[i][0] - pos[j][0];
298
+ let dy = pos[i][1] - pos[j][1];
299
+ let dz = pos[i][2] - pos[j][2];
300
+ let d2 = dx * dx + dy * dy + dz * dz;
301
+ if (d2 < 1e-5) {
302
+ dx = 0.001 * (i - j); dy = 0.0007 * (i + j); dz = 0.0005;
303
+ d2 = dx * dx + dy * dy + dz * dz;
304
+ }
305
+ const d = Math.sqrt(d2);
306
+ const k = 0.05 / (d2 * d);
307
+ vel[i][0] += dx * k; vel[i][1] += dy * k; vel[i][2] += dz * k;
308
+ vel[j][0] -= dx * k; vel[j][1] -= dy * k; vel[j][2] -= dz * k;
309
+ }
310
+ }
311
+ for (const e of edges) {
312
+ const i = idx.get(e.a);
313
+ const j = idx.get(e.b);
314
+ let dx = pos[j][0] - pos[i][0];
315
+ let dy = pos[j][1] - pos[i][1];
316
+ let dz = pos[j][2] - pos[i][2];
317
+ const d = Math.sqrt(dx * dx + dy * dy + dz * dz) || 1e-3;
318
+ const want = 0.40 / (1 + Math.min(6, e.w || 1) * 0.55);
319
+ const k = ((d - want) * 0.30) / d;
320
+ vel[i][0] += dx * k; vel[i][1] += dy * k; vel[i][2] += dz * k;
321
+ vel[j][0] -= dx * k; vel[j][1] -= dy * k; vel[j][2] -= dz * k;
322
+ }
323
+ for (let i = 0; i < N; i += 1) {
324
+ const rr = Math.hypot(pos[i][0], pos[i][1], pos[i][2]) || 1e-3;
325
+ const g = (shellOf(list[i]) - rr) * 0.10;
326
+ vel[i][0] += (pos[i][0] / rr) * g;
327
+ vel[i][1] += (pos[i][1] / rr) * g;
328
+ vel[i][2] += (pos[i][2] / rr) * g;
329
+ }
330
+ for (let i = 0; i < N; i += 1) {
331
+ for (let k = 0; k < 3; k += 1) {
332
+ vel[i][k] *= 0.5;
333
+ let v = pos[i][k] + vel[i][k];
334
+ if (v > 1.35) v = 1.35;
335
+ if (v < -1.35) v = -1.35;
336
+ pos[i][k] = v;
337
+ }
338
+ }
339
+ }
340
+ // 归一化:最外层贴到 1.0,保证不出画面
341
+ let maxR = 0;
342
+ for (const p of pos) maxR = Math.max(maxR, Math.hypot(p[0], p[1], p[2]));
343
+ const scale = maxR > 1.15 ? 1.15 / maxR : 1;
344
+ list.forEach((p, i) => { p.pos = [pos[i][0] * scale, pos[i][1] * scale, pos[i][2] * scale]; });
345
+ })();
346
+
347
+ // ---- 粒子星云:每颗主题星自己就是一小团云(这才是视频里那种「结团」观感)----
348
+ const motes = [];
349
+ (() => {
350
+ const hex2rgb = (c) => {
351
+ const h = String(c || '').replace('#', '');
352
+ const s = h.length === 3 ? h[0] + h[0] + h[1] + h[1] + h[2] + h[2] : h;
353
+ const v = parseInt(s, 16) || 0x8899aa;
354
+ return ((v >> 16) & 255) + ',' + ((v >> 8) & 255) + ',' + (v & 255);
355
+ };
356
+ pts.forEach((host) => {
357
+ const tri = hex2rgb(host.color || '#8b93a7');
358
+ const spread = 0.055 + Math.min(0.05, (host.deg || 0) * 0.006);
359
+ const n = 80 + Math.min(40, Math.round((host.bytes || 0) / 700));
360
+ for (let i = 0; i < n; i += 1) {
361
+ const g1 = (hash(host.id + ':a' + i) + hash(host.id + ':b' + i) - 1) * spread;
362
+ const g2 = (hash(host.id + ':c' + i) + hash(host.id + ':d' + i) - 1) * spread;
363
+ const g3 = (hash(host.id + ':e' + i) + hash(host.id + ':f' + i) - 1) * spread;
364
+ motes.push({
365
+ tri,
366
+ size: 1.2 + hash(host.id + ':s' + i) * 1.4,
367
+ ph: hash(host.id + ':p' + i) * 6.283,
368
+ pos: [host.pos[0] + g1, host.pos[1] + g2, host.pos[2] + g3],
369
+ });
370
+ }
371
+ });
372
+ // 远处一点稀薄星尘,避免只有团没有「海」
373
+ Object.keys(byLayer).forEach((layer) => {
374
+ const list = byLayer[layer];
375
+ if (!list.length) return;
376
+ const tri = hex2rgb((data.palette[layer] && data.palette[layer].color) || '#8b93a7');
377
+ for (let i = 0; i < 90; i += 1) {
378
+ const host = list[i % list.length];
379
+ motes.push({
380
+ tri,
381
+ size: 0.7 + hash(layer + ':ds' + i) * 1.1,
382
+ ph: hash(layer + ':dp' + i) * 6.283,
383
+ pos: [
384
+ host.pos[0] + (hash(layer + ':dx' + i) - 0.5) * 0.75,
385
+ host.pos[1] + (hash(layer + ':dy' + i) - 0.5) * 0.75,
386
+ host.pos[2] + (hash(layer + ':dz' + i) - 0.5) * 0.75,
387
+ ],
388
+ });
389
+ }
390
+ });
391
+ })();
392
+ const byId = {};
393
+ pts.forEach((p) => {
394
+ byId[p.id] = p;
395
+ });
396
+ const links = (data.edges || []).filter((e) => byId[e.a] && byId[e.b]);
397
+ // 片段 = 绕主星的卫星:每个主题一圈,环上相邻的卫星彼此连成星链
398
+ const norm = (v) => { const l = Math.hypot(v[0], v[1], v[2]) || 1; return [v[0] / l, v[1] / l, v[2] / l]; };
399
+ const cross = (a, b) => [a[1] * b[2] - a[2] * b[1], a[2] * b[0] - a[0] * b[2], a[0] * b[1] - a[1] * b[0]];
400
+ const chains = [];
401
+ const byHub = new Map();
402
+ (data.fragments || []).forEach((f) => {
403
+ const hub = byId[f.entryId];
404
+ if (!hub) return;
405
+ if (!byHub.has(hub.id)) byHub.set(hub.id, { hub, items: [] });
406
+ byHub.get(hub.id).items.push(f);
407
+ });
408
+ for (const { hub, items } of byHub.values()) {
409
+ items.sort((a, b) => (Number(a.line) || 0) - (Number(b.line) || 0) || String(a.id).localeCompare(String(b.id)));
410
+ const n = items.length;
411
+ const radial = norm(hub.pos);
412
+ let u0 = cross(radial, [0, 1, 0]);
413
+ if (Math.hypot(u0[0], u0[1], u0[2]) < 1e-4) u0 = cross(radial, [1, 0, 0]);
414
+ u0 = norm(u0);
415
+ const v0 = norm(cross(radial, u0));
416
+ const seed = hash(hub.id + ':ring');
417
+ // 星环:片段按数量分成 1–3 圈,各自半径与倾角不同
418
+ const ringCount = n <= 9 ? 1 : n <= 22 ? 2 : 3;
419
+ const per = Math.ceil(n / ringCount);
420
+ for (let ri = 0; ri < ringCount; ri += 1) {
421
+ const chunk = items.slice(ri * per, (ri + 1) * per);
422
+ if (!chunk.length) continue;
423
+ const tilt = 0.55 + ri * 0.62;
424
+ const ct = Math.cos(tilt);
425
+ const st = Math.sin(tilt);
426
+ const vTilt = norm([v0[0] * ct + radial[0] * st, v0[1] * ct + radial[1] * st, v0[2] * ct + radial[2] * st]);
427
+ const r0 = (0.085 + ri * 0.055) * (0.92 + 0.08 * Math.min(1, chunk.length / 12));
428
+ const placed = chunk.map((f, i) => {
429
+ const t = (i / Math.max(1, chunk.length)) * Math.PI * 2 + seed * 6.2832 + ri * 1.1;
430
+ const wob = (hash(f.id + ':n') - 0.5) * 0.02;
431
+ const p = {
432
+ id: f.id, kind: 'frag', entryId: f.entryId, entryTitle: f.entryTitle,
433
+ label: f.label, line: f.line, layer: f.layer, frag: f,
434
+ color: (data.palette[f.layer] && data.palette[f.layer].color) || hub.color,
435
+ hubId: hub.id,
436
+ ring: { u: u0, v: vTilt, radial, r: r0 * (0.96 + 0.08 * hash(f.id + ':r')), wob, angle: t, phase: seed * 6.2832 },
437
+ pos: [
438
+ hub.pos[0] + (Math.cos(t) * u0[0] + Math.sin(t) * vTilt[0]) * r0 + radial[0] * wob,
439
+ hub.pos[1] + (Math.cos(t) * u0[1] + Math.sin(t) * vTilt[1]) * r0 + radial[1] * wob,
440
+ hub.pos[2] + (Math.cos(t) * u0[2] + Math.sin(t) * vTilt[2]) * r0 + radial[2] * wob,
441
+ ],
442
+ };
443
+ pts.push(p);
444
+ return p;
445
+ });
446
+ chains.push({ hub, items: placed, ring: { u: u0, v: vTilt, radial, r0 } });
447
+ }
448
+ }
449
+
450
+ let W = 0;
451
+ let H = 0;
452
+ let DPR = 1;
453
+ let R = 260;
454
+ let yaw = -0.6;
455
+ let pitch = 0.22;
456
+ let zoom = 1;
457
+ let hover = null;
458
+ let savedCam = null;
459
+ let focusCam = null; // 聚焦时锁定的视线,防止任何旋转把主星带离中心
460
+ let drag = null;
461
+ let spin = true;
462
+ let raf = 0;
463
+ let last = 0;
464
+ let dust = null;
465
+ let isVisible = () => true;
466
+ let orbitTarget = null; // 聚焦时相机绕这颗主题星转
467
+ let spikeGeo = null;
468
+ let polyGeo = null;
469
+ let rhomboGeo = null;
470
+
471
+ const resize = () => {
472
+ DPR = Math.min(2, window.devicePixelRatio || 1);
473
+ W = wrap.clientWidth || 600;
474
+ H = wrap.clientHeight || 420;
475
+ canvas.width = W * DPR;
476
+ canvas.height = H * DPR;
477
+ canvas.style.width = W + 'px';
478
+ canvas.style.height = H + 'px';
479
+ ctx.setTransform(DPR, 0, 0, DPR, 0, 0);
480
+ R = Math.min(W, H) * 0.42;
481
+ };
482
+ const obs = new ResizeObserver(resize);
483
+ obs.observe(wrap);
484
+ resize();
485
+
486
+ const project = (p) => {
487
+ // 聚焦时把主星当成原点:这样拖拽就是在绕着它转,它永远在画面中心
488
+ const px = orbitTarget ? p[0] - orbitTarget[0] : p[0];
489
+ const py = orbitTarget ? p[1] - orbitTarget[1] : p[1];
490
+ const pz = orbitTarget ? p[2] - orbitTarget[2] : p[2];
491
+ const cy = Math.cos(yaw), sy = Math.sin(yaw), cp = Math.cos(pitch), sp = Math.sin(pitch);
492
+ const x1 = px * cy - pz * sy;
493
+ const z1 = px * sy + pz * cy;
494
+ const y1 = py * cp - z1 * sp;
495
+ const z2 = py * sp + z1 * cp;
496
+ const d = 1 / (1 + (z2 + 4.2) / 8.6);
497
+ return { x: W / 2 + x1 * R * zoom * d, y: H / 2 + y1 * R * zoom * d, z: z2, d };
498
+ };
499
+
500
+ // 卫星沿环运动:frag 的 pos 每帧重算,拾取和星链也跟着走
501
+ const satPosAt = (p, ms) => {
502
+ const ring = p.ring;
503
+ const hub = byId[p.hubId];
504
+ if (!ring || !hub) return p.pos;
505
+ const a = ring.angle + ring.phase + ms * 0.00016;
506
+ return [
507
+ hub.pos[0] + (Math.cos(a) * ring.u[0] + Math.sin(a) * ring.v[0]) * ring.r + ring.radial[0] * ring.wob,
508
+ hub.pos[1] + (Math.cos(a) * ring.u[1] + Math.sin(a) * ring.v[1]) * ring.r + ring.radial[1] * ring.wob,
509
+ hub.pos[2] + (Math.cos(a) * ring.u[2] + Math.sin(a) * ring.v[2]) * ring.r + ring.radial[2] * ring.wob,
510
+ ];
511
+ };
512
+
513
+ const draw = () => {
514
+ const now = performance.now();
515
+ const dt = last ? Math.min(0.05, (now - last) / 1000) : 0.016;
516
+ last = now;
517
+ if (spin && !drag && !focusRef.current) yaw += dt * 0.16;
518
+
519
+ ctx.clearRect(0, 0, W, H);
520
+
521
+ // 深空底:画布保持透明,壁纸/面板底色从下面透上来。
522
+ // STAR_SCRIM = 0 全透;调到 0.4~0.6 会给一层很淡的暗雾(星点更清楚,但会挡壁纸)。
523
+ const STAR_SCRIM = 0;
524
+ const hexOf = (c) => String(c || '').replace('#', '');
525
+ const lumOf = (c) => { const h = hexOf(c); if (h.length < 6) return 255; const v = parseInt(h, 16); return ((v >> 16) & 255) * 0.299 + ((v >> 8) & 255) * 0.587 + (v & 255) * 0.114; };
526
+ const dark = lumOf(theme.bg) < 128;
527
+ if (dark) {
528
+ if (STAR_SCRIM > 0) {
529
+ const bgc = ctx.createRadialGradient(W * 0.5, H * 0.46, 0, W * 0.5, H * 0.5, Math.max(W, H) * 0.82);
530
+ const a = (v) => (v * STAR_SCRIM).toFixed(3);
531
+ bgc.addColorStop(0, 'rgba(11,21,36,' + a(0.9) + ')');
532
+ bgc.addColorStop(0.42, 'rgba(6,11,21,' + a(0.8) + ')');
533
+ bgc.addColorStop(1, 'rgba(1,3,10,' + a(0.7) + ')');
534
+ ctx.fillStyle = bgc;
535
+ ctx.fillRect(0, 0, W, H);
536
+ }
537
+ // 星云:按层染色的同心薄雾
538
+ const pal = (data && data.palette) || {};
539
+ ['core', 'fact', 'skill', 'daily', 'emotion'].forEach((k, i) => {
540
+ const st = pal[k];
541
+ if (!st || !st.color) return;
542
+ const rr = R * (0.42 + i * 0.22) * (1 + 0.02 * Math.sin(now / 4200 + i * 1.7));
543
+ const rgbs = hexOf(st.color);
544
+ const v = parseInt(rgbs.length === 3 ? rgbs[0] + rgbs[0] + rgbs[1] + rgbs[1] + rgbs[2] + rgbs[2] : rgbs, 16);
545
+ const tri = ((v >> 16) & 255) + ',' + ((v >> 8) & 255) + ',' + (v & 255);
546
+ const ng = ctx.createRadialGradient(W / 2, H / 2, rr * 0.08, W / 2, H / 2, rr);
547
+ ng.addColorStop(0, 'rgba(' + tri + ',0.12)');
548
+ ng.addColorStop(0.55, 'rgba(' + tri + ',0.04)');
549
+ ng.addColorStop(1, 'rgba(0,0,0,0)');
550
+ ctx.fillStyle = ng;
551
+ ctx.beginPath();
552
+ ctx.arc(W / 2, H / 2, rr, 0, Math.PI * 2);
553
+ ctx.fill();
554
+ });
555
+ // 尘埃:极轻的视差碎星
556
+ if (!dust) {
557
+ dust = [];
558
+ for (let i = 0; i < 260; i += 1) dust.push([Math.random(), Math.random(), 0.3 + Math.random(), Math.random() * 6.283]);
559
+ }
560
+ for (const d of dust) {
561
+ ctx.fillStyle = 'rgba(198,220,255,' + (0.04 + d[2] * 0.1).toFixed(3) + ')';
562
+ ctx.fillRect(d[0] * W + Math.sin(yaw * 0.35 + d[3]) * 8, d[1] * H + Math.cos(yaw * 0.25 + d[3]) * 5, d[2], d[2]);
563
+ }
564
+ }
565
+
566
+ for (const p of pts) if (p.kind === 'frag') p.pos = satPosAt(p, now);
567
+
568
+ isVisible = () => true;
569
+ const proj = pts.map((p) => {
570
+ const s = project(p.pos);
571
+ s.n = p;
572
+ return s;
573
+ });
574
+ proj.sort((a, b) => a.z - b.z);
575
+
576
+ // 星云光晕:枢纽星背后的大团柔光,先铺一层底子
577
+ for (const p of pts) {
578
+ if (p.kind === 'frag' || (p.deg || 0) < 3) continue;
579
+ const q = project(p.pos);
580
+ const rr = Math.max(30, R * 0.34 * q.d);
581
+ const gg = ctx.createRadialGradient(q.x, q.y, 0, q.x, q.y, rr);
582
+ gg.addColorStop(0, 'rgba(120,170,240,0.10)');
583
+ gg.addColorStop(0.45, 'rgba(90,140,220,0.05)');
584
+ gg.addColorStop(1, 'rgba(0,0,0,0)');
585
+ ctx.fillStyle = gg;
586
+ ctx.beginPath();
587
+ ctx.arc(q.x, q.y, rr, 0, Math.PI * 2);
588
+ ctx.fill();
589
+ }
590
+
591
+ // 粒子星云:主题星周围的微尘,随场景旋转、缓慢呼吸
592
+ for (const m of motes) {
593
+ const q = project(m.pos);
594
+ const a = (0.34 + 0.16 * Math.sin(now / 2400 + m.ph)) * Math.min(1, Math.max(0, q.d) * 1.3);
595
+ ctx.fillStyle = 'rgba(' + m.tri + ',' + a.toFixed(3) + ')';
596
+ ctx.fillRect(q.x, q.y, m.size, m.size);
597
+ }
598
+
599
+ // 中心恒星:代表 DSH,是整张记忆星图的锚点;聚焦某颗主题星时让位
600
+ if (!focusRef.current) {
601
+ const sun = project([0, 0, 0]);
602
+ const sunR = Math.max(24, Math.min(W, H) * 0.075);
603
+ const pulse = 0.86 + 0.14 * Math.sin(now / 750);
604
+ const glow = ctx.createRadialGradient(sun.x, sun.y, 0, sun.x, sun.y, sunR * 2.4);
605
+ glow.addColorStop(0, 'rgba(255,236,180,0.55)');
606
+ glow.addColorStop(0.35, 'rgba(255,200,95,0.22)');
607
+ glow.addColorStop(0.7, 'rgba(255,165,60,0.07)');
608
+ glow.addColorStop(1, 'rgba(255,150,40,0)');
609
+ ctx.fillStyle = glow;
610
+ ctx.beginPath();
611
+ ctx.arc(sun.x, sun.y, sunR * 2.4, 0, Math.PI * 2);
612
+ ctx.fill();
613
+ // 五复合正四面体:5 个正四面体共用一个正十二面体的 20 个顶点,
614
+ // 只看线框就是纸模那种「星刺球」——本质是 5 组互穿的三角面。
615
+ const cyw = Math.cos(yaw), syw = Math.sin(yaw);
616
+ const cpt = Math.cos(pitch), spt = Math.sin(pitch);
617
+ const spinT = -now / 3200; // 记忆恒星反向自转
618
+ const PHIQ = 1.6180339887;
619
+ if (!spikeGeo) {
620
+ const DV = [];
621
+ for (const sx of [-1, 1]) for (const sy of [-1, 1]) for (const sz of [-1, 1]) DV.push([sx, sy, sz]);
622
+ for (const sg of [-1, 1]) for (const tg of [-1, 1]) {
623
+ DV.push([0, sg / PHIQ, tg * PHIQ], [sg / PHIQ, tg * PHIQ, 0], [sg * PHIQ, 0, tg / PHIQ]);
624
+ }
625
+ const dist = (p, q) => Math.hypot(p[0] - q[0], p[1] - q[1], p[2] - q[2]);
626
+ const tets = [];
627
+ for (let i = 0; i < DV.length; i += 1) for (let j = i + 1; j < DV.length; j += 1) for (let k = j + 1; k < DV.length; k += 1) for (let m = k + 1; m < DV.length; m += 1) {
628
+ const L = dist(DV[i], DV[j]);
629
+ if (dist(DV[i], DV[k]) - L > 1e-6 || dist(DV[i], DV[m]) - L > 1e-6) continue;
630
+ if (dist(DV[j], DV[k]) - L > 1e-6 || dist(DV[j], DV[m]) - L > 1e-6) continue;
631
+ if (dist(DV[k], DV[m]) - L > 1e-6) continue;
632
+ if (Math.abs(dist(DV[i], DV[k]) - L) > 1e-6 || Math.abs(dist(DV[i], DV[m]) - L) > 1e-6) continue;
633
+ if (Math.abs(dist(DV[j], DV[k]) - L) > 1e-6 || Math.abs(dist(DV[j], DV[m]) - L) > 1e-6) continue;
634
+ if (Math.abs(dist(DV[k], DV[m]) - L) > 1e-6) continue;
635
+ tets.push([i, j, k, m]);
636
+ }
637
+ const canon = (t) => {
638
+ const pts = t.map((i) => DV[i]).slice().sort((p, q) => p[0] - q[0] || p[1] - q[1] || p[2] - q[2]);
639
+ const b = pts[0], c = pts[1], d = pts[2], e = pts[3];
640
+ const u = [c[0] - b[0], c[1] - b[1], c[2] - b[2]];
641
+ const v = [d[0] - b[0], d[1] - b[1], d[2] - b[2]];
642
+ const w = [e[0] - b[0], e[1] - b[1], e[2] - b[2]];
643
+ return Math.sign(u[0] * (v[1] * w[2] - v[2] * w[1]) - u[1] * (v[0] * w[2] - v[2] * w[0]) + u[2] * (v[0] * w[1] - v[1] * w[0]));
644
+ };
645
+ const g1 = tets.filter((t) => canon(t) > 0);
646
+ const g2 = tets.filter((t) => canon(t) < 0);
647
+ const pick5 = (g1.length >= g2.length ? g1 : g2).slice(0, 5);
648
+ const PAIRS = [[0, 1], [0, 2], [0, 3], [1, 2], [1, 3], [2, 3]];
649
+ spikeGeo = [];
650
+ for (const t of pick5) for (const pr2 of PAIRS) spikeGeo.push([DV[t[pr2[0]]], DV[t[pr2[1]]]]);
651
+ }
652
+ const RRAD = Math.hypot(1, 1, 1);
653
+ const SC = sunR / RRAD;
654
+ const prj = (v) => {
655
+ const r0 = v[0] * Math.cos(spinT) - v[2] * Math.sin(spinT);
656
+ const z0 = v[0] * Math.sin(spinT) + v[2] * Math.cos(spinT);
657
+ const x1 = r0 * cyw - z0 * syw;
658
+ const z1 = r0 * syw + z0 * cyw;
659
+ const y1 = v[1] * cpt - z1 * spt;
660
+ const z2 = v[1] * spt + z1 * cpt;
661
+ const dd = 1 / (1 + (z2 + 0.4) / 2.4);
662
+ return { x: sun.x + x1 * dd * SC, y: sun.y + y1 * dd * SC };
663
+ };
664
+ ctx.save();
665
+ ctx.lineJoin = 'round';
666
+ ctx.lineCap = 'round';
667
+ ctx.shadowColor = 'rgba(255,205,110,0.85)';
668
+ ctx.shadowBlur = 8 * pulse;
669
+ ctx.strokeStyle = 'rgba(255,241,202,' + (0.8 * pulse).toFixed(2) + ')';
670
+ ctx.lineWidth = 0.95;
671
+ for (const seg2 of spikeGeo) {
672
+ const q0 = prj(seg2[0]), q1 = prj(seg2[1]);
673
+ ctx.beginPath(); ctx.moveTo(q0.x, q0.y); ctx.lineTo(q1.x, q1.y); ctx.stroke();
674
+ }
675
+ ctx.restore();
676
+
677
+ }
678
+
679
+ chains.forEach(({ hub, items, ring }) => {
680
+ if (focusRef.current !== hub.id) return; // 全景不画,聚焦的主星才显示星环
681
+ if (!ring) return;
682
+ const ringPath = (rr) => {
683
+ ctx.beginPath();
684
+ for (let k = 0; k <= 72; k += 1) {
685
+ const ang = (k / 72) * Math.PI * 2;
686
+ const q = project([
687
+ hub.pos[0] + (Math.cos(ang) * ring.u[0] + Math.sin(ang) * ring.v[0]) * rr,
688
+ hub.pos[1] + (Math.cos(ang) * ring.u[1] + Math.sin(ang) * ring.v[1]) * rr,
689
+ hub.pos[2] + (Math.cos(ang) * ring.u[2] + Math.sin(ang) * ring.v[2]) * rr,
690
+ ]);
691
+ if (k === 0) ctx.moveTo(q.x, q.y);
692
+ else ctx.lineTo(q.x, q.y);
693
+ }
694
+ };
695
+ // 星环带:外宽内细两层,像土星环
696
+ ctx.save();
697
+ ctx.lineJoin = 'round';
698
+ ctx.strokeStyle = 'rgba(150,195,255,0.05)';
699
+ ctx.lineWidth = 16;
700
+ ringPath(ring.r0);
701
+ ctx.stroke();
702
+ ctx.strokeStyle = 'rgba(190,224,255,0.20)';
703
+ ctx.lineWidth = 1.3;
704
+ ringPath(ring.r0);
705
+ ctx.stroke();
706
+ ctx.restore();
707
+ });
708
+
709
+ if (!focusRef.current) {
710
+ links.forEach((e) => {
711
+ const a = proj.find((s) => s.n.id === e.a);
712
+ const b = proj.find((s) => s.n.id === e.b);
713
+ if (!a || !b) return;
714
+ const dep = Math.min(a.d, b.d);
715
+ const alpha = Math.min(0.42, 0.12 + e.w * 0.06) * dep;
716
+ ctx.strokeStyle = 'rgba(118,168,240,' + alpha.toFixed(3) + ')';
717
+ ctx.lineWidth = Math.max(0.5, e.w * 0.34 * dep);
718
+ ctx.beginPath();
719
+ ctx.moveTo(a.x, a.y);
720
+ ctx.lineTo(b.x, b.y);
721
+ ctx.stroke();
722
+ for (let k = 1; k <= 5; k += 1) {
723
+ const tt = k / 6;
724
+ ctx.fillStyle = 'rgba(150,195,255,' + (0.16 * dep).toFixed(3) + ')';
725
+ ctx.fillRect(a.x + (b.x - a.x) * tt, a.y + (b.y - a.y) * tt, 1.3, 1.3);
726
+ }
727
+ });
728
+ // 信号:沿主题连线游走的微光点
729
+ links.forEach((e, i) => {
730
+ const a = proj.find((s) => s.n.id === e.a);
731
+ const b = proj.find((s) => s.n.id === e.b);
732
+ if (!a || !b) return;
733
+ const t = (now * 0.00016 + i * 0.37) % 1;
734
+ const q = project([
735
+ a.n.pos[0] + (b.n.pos[0] - a.n.pos[0]) * t,
736
+ a.n.pos[1] + (b.n.pos[1] - a.n.pos[1]) * t,
737
+ a.n.pos[2] + (b.n.pos[2] - a.n.pos[2]) * t,
738
+ ]);
739
+ ctx.fillStyle = 'rgba(200,230,255,' + (0.34 * Math.min(a.d, b.d)).toFixed(3) + ')';
740
+ ctx.beginPath();
741
+ ctx.arc(q.x, q.y, 1.1, 0, Math.PI * 2);
742
+ ctx.fill();
743
+ });
744
+ }
745
+
746
+ proj.forEach((s) => {
747
+ const n = s.n;
748
+ if (n.kind === 'frag') {
749
+ if (n.hubId !== focusRef.current) return;
750
+ // 片段 = 星环上的小颗粒(星环本体由 chains 画)
751
+ const satScale = Math.min(2.4, Math.max(1, zoom / 2.2));
752
+ const dot = Math.max(1.2, (1.3 + 1.5 * s.d) * satScale * 0.72);
753
+ // 粒子沿环的短拖尾
754
+ for (let k = 1; k <= 2; k += 1) {
755
+ const tt = project(satPosAt(n, now - k * 150));
756
+ ctx.globalAlpha = 0.09 * (3 - k);
757
+ ctx.fillStyle = n.color;
758
+ ctx.beginPath();
759
+ ctx.arc(tt.x, tt.y, dot * (1 - k * 0.22), 0, Math.PI * 2);
760
+ ctx.fill();
761
+ }
762
+ ctx.save();
763
+ ctx.shadowColor = n.color;
764
+ ctx.shadowBlur = 6;
765
+ ctx.fillStyle = n.color;
766
+ ctx.globalAlpha = Math.min(0.98, 0.5 + s.d * 0.5);
767
+ ctx.beginPath();
768
+ ctx.arc(s.x, s.y, dot, 0, Math.PI * 2);
769
+ ctx.fill();
770
+ ctx.restore();
771
+ ctx.fillStyle = 'rgba(255,255,255,0.8)';
772
+ ctx.beginPath();
773
+ ctx.arc(s.x, s.y, Math.max(0.4, dot * 0.38), 0, Math.PI * 2);
774
+ ctx.fill();
775
+ if (hover === n.id) {
776
+ ctx.fillStyle = theme.text;
777
+ ctx.font = '11px "Segoe UI","Microsoft YaHei",sans-serif';
778
+ ctx.textAlign = 'center';
779
+ ctx.fillText(String(n.label || '').slice(0, 18), s.x, s.y - 8);
780
+ }
781
+ return;
782
+ }
783
+ if (focusRef.current && n.id !== focusRef.current) return;
784
+ const base = 1.6 + Math.sqrt(n.bytes) / 24 + Math.log1p(n.hits) * 1.6;
785
+ const rad = Math.max(1.5, base * (0.55 + s.d * 1.15));
786
+ // 主题星 = 小多面体线框(和小节点配对:普通八面体,枢纽二十面体)
787
+ if (!polyGeo) {
788
+ const octV = [[1, 0, 0], [-1, 0, 0], [0, 1, 0], [0, -1, 0], [0, 0, 1], [0, 0, -1]];
789
+ const octE = [];
790
+ for (let i = 0; i < 6; i += 1) for (let j = i + 1; j < 6; j += 1) if ((i ^ j) !== 1) octE.push([i, j]);
791
+ const icoV = [];
792
+ for (const sg of [-1, 1]) {
793
+ icoV.push([0, sg, 1.6180339887], [0, sg, -1.6180339887], [sg, 1.6180339887, 0], [sg, -1.6180339887, 0], [1.6180339887, 0, sg], [-1.6180339887, 0, sg]);
794
+ }
795
+ let el = Infinity;
796
+ const dd3 = (p, q) => Math.hypot(p[0] - q[0], p[1] - q[1], p[2] - q[2]);
797
+ for (let i = 0; i < icoV.length; i += 1) for (let j = i + 1; j < icoV.length; j += 1) el = Math.min(el, dd3(icoV[i], icoV[j]));
798
+ const icoE = [];
799
+ for (let i = 0; i < icoV.length; i += 1) for (let j = i + 1; j < icoV.length; j += 1) if (Math.abs(dd3(icoV[i], icoV[j]) - el) < 1e-6) icoE.push([i, j]);
800
+ const unit = (vs) => { const m = Math.max.apply(null, vs.map((v) => Math.hypot(v[0], v[1], v[2]))); return vs.map((v) => [v[0] / m, v[1] / m, v[2] / m]); };
801
+ polyGeo = { oct: { v: unit(octV), e: octE }, ico: { v: unit(icoV), e: icoE } };
802
+ }
803
+ const poly = n.deg >= 6 ? polyGeo.ico : polyGeo.oct;
804
+ const focused = focusRef.current === n.id;
805
+ if (focused) {
806
+ // 聚焦:这颗主题星放大成「主星」,加一圈暖光让它在星环里站得住
807
+ const hal = rad * 6.2;
808
+ const hg = ctx.createRadialGradient(s.x, s.y, 0, s.x, s.y, hal);
809
+ hg.addColorStop(0, 'rgba(255,246,214,0.30)');
810
+ hg.addColorStop(0.35, 'rgba(255,222,150,0.12)');
811
+ hg.addColorStop(1, 'rgba(255,190,90,0)');
812
+ ctx.fillStyle = hg;
813
+ ctx.beginPath(); ctx.arc(s.x, s.y, hal, 0, Math.PI * 2); ctx.fill();
814
+ }
815
+ const spin2 = (n.seed || 0) * 6.2832 + now / 5200;
816
+ const cs2 = Math.cos(spin2), sn2 = Math.sin(spin2);
817
+ const cy2 = Math.cos(yaw), sy2 = Math.sin(yaw), cp2 = Math.cos(pitch), sp2 = Math.sin(pitch);
818
+ const localRot = (v) => {
819
+ const x0 = v[0] * cs2 - v[2] * sn2;
820
+ const z0 = v[0] * sn2 + v[2] * cs2;
821
+ const x1 = x0 * cy2 - z0 * sy2;
822
+ const z1 = x0 * sy2 + z0 * cy2;
823
+ const y1 = v[1] * cp2 - z1 * sp2;
824
+ return [x1, y1];
825
+ };
826
+ const dimmed = hover && hover !== n.id ? 0.3 : 1;
827
+ const pr = poly.v.map(localRot);
828
+ ctx.save();
829
+ ctx.lineJoin = 'round';
830
+ ctx.shadowColor = n.color;
831
+ ctx.shadowBlur = 7;
832
+ ctx.strokeStyle = n.color;
833
+ ctx.globalAlpha = Math.min(0.95, 0.3 + s.d * 0.6) * dimmed;
834
+ ctx.lineWidth = poly.e.length > 20 ? 0.7 : 0.95;
835
+ const R2 = rad * 1.75 * (focused ? 2.3 : 1);
836
+ for (const [i2, j2] of poly.e) {
837
+ ctx.beginPath();
838
+ ctx.moveTo(s.x + pr[i2][0] * R2, s.y + pr[i2][1] * R2);
839
+ ctx.lineTo(s.x + pr[j2][0] * R2, s.y + pr[j2][1] * R2);
840
+ ctx.stroke();
841
+ }
842
+ ctx.restore();
843
+ // 中心一点白热核,保持「发光」
844
+ ctx.fillStyle = 'rgba(255,255,255,' + (Math.min(0.72, 0.2 + s.d * 0.5) * dimmed).toFixed(2) + ')';
845
+ ctx.beginPath();
846
+ ctx.arc(s.x, s.y, Math.max(0.7, rad * 0.3), 0, Math.PI * 2);
847
+ ctx.fill();
848
+ if (n.hits >= 2) {
849
+ const sl = rad * 3.2;
850
+ ctx.strokeStyle = 'rgba(222,238,255,' + (0.13 * Math.min(1, s.d)).toFixed(3) + ')';
851
+ ctx.lineWidth = 0.6;
852
+ ctx.beginPath();
853
+ ctx.moveTo(s.x - sl, s.y); ctx.lineTo(s.x + sl, s.y);
854
+ ctx.moveTo(s.x, s.y - sl); ctx.lineTo(s.x, s.y + sl);
855
+ ctx.stroke();
856
+ }
857
+ if (n.stale || n.solo) {
858
+ ctx.strokeStyle = n.stale ? n.color : '#8a93a8';
859
+ ctx.globalAlpha = 0.55;
860
+ ctx.setLineDash(n.solo ? [1, 4] : [2, 3]);
861
+ ctx.beginPath();
862
+ ctx.arc(s.x, s.y, rad + 4.5, 0, Math.PI * 2);
863
+ ctx.stroke();
864
+ ctx.setLineDash([]);
865
+ ctx.globalAlpha = 1;
866
+ }
867
+ if (focused && !hideLabels()) {
868
+ ctx.fillStyle = theme.text;
869
+ ctx.font = '600 13px "Segoe UI","Microsoft YaHei",sans-serif';
870
+ ctx.textAlign = 'center';
871
+ ctx.fillText(n.id, s.x, s.y + R2 * 1.25 + 14);
872
+ }
873
+ if (!hideLabels() && (s.d > 0.4 || hover === n.id)) {
874
+ ctx.globalAlpha = Math.min(0.95, 0.18 + s.d) + 0.15;
875
+ ctx.fillStyle = theme.text;
876
+ ctx.font = (hover === n.id ? '600 13px' : '11px') + ' "Segoe UI","Microsoft YaHei",sans-serif';
877
+ ctx.textAlign = 'center';
878
+ ctx.fillText(n.id, s.x, s.y + rad + 14);
879
+ ctx.globalAlpha = 1;
880
+ }
881
+ });
882
+
883
+ raf = requestAnimationFrame(draw);
884
+ };
885
+
886
+ const localPoint = (e) => {
887
+ const r = canvas.getBoundingClientRect();
888
+ return { x: e.clientX - r.left, y: e.clientY - r.top };
889
+ };
890
+ const pick = (mx, my) => {
891
+ let best = null;
892
+ let bd = 18;
893
+ pts.forEach((p) => {
894
+ if (!isVisible(p)) return;
895
+ if (p.kind === 'frag') {
896
+ if (!focusRef.current || p.hubId !== focusRef.current) return;
897
+ } else if (focusRef.current && p.id !== focusRef.current) return;
898
+ const s = project(p.pos);
899
+ const dd = Math.hypot(s.x - mx, s.y - my);
900
+ if (dd < bd) {
901
+ bd = dd;
902
+ best = p;
903
+ }
904
+ });
905
+ return best;
906
+ };
907
+
908
+ // 聚焦:把镜头转到该主星正面并拉近;取消时恢复原视角
909
+ const applyFocus = (id) => {
910
+ if (id) {
911
+ const hub = byId[id];
912
+ if (!hub) return;
913
+ savedCam = { yaw, pitch, zoom };
914
+ const hx = hub.pos[0];
915
+ const hy = hub.pos[1];
916
+ const hz = hub.pos[2];
917
+ const planar = Math.hypot(hx, hz) || 1e-4;
918
+ yaw = Math.atan2(hx, hz) + Math.PI;
919
+ pitch = Math.atan2(-hy, planar);
920
+ zoom = 5.0;
921
+ orbitTarget = [hx, hy, hz];
922
+ focusCam = null; // 不再锁视角:允许绕着主星转
923
+ } else if (savedCam) {
924
+ yaw = savedCam.yaw;
925
+ pitch = savedCam.pitch;
926
+ zoom = savedCam.zoom;
927
+ savedCam = null;
928
+ focusCam = null;
929
+ orbitTarget = null;
930
+ }
931
+ };
932
+
933
+ if (focusRef.current) applyFocus(focusRef.current);
934
+
935
+ const openEntry = (id, line, frag) => {
936
+ const open = sidebar.open || resolveSidebar();
937
+ if (open) {
938
+ setPending(id, line || 0, frag);
939
+ if (open('memo-entry') !== false) return;
940
+ }
941
+ setHint('侧栏服务没就绪,先用内嵌面板');
942
+ fetch('/api/memo-star/entry?id=' + encodeURIComponent(id) + (line ? '&line=' + line : ''), { cache: 'no-store' })
943
+ .then((r) => r.json())
944
+ .then((d) => {
945
+ if (d && d.ok) setEntry(d);
946
+ else setEntry({ id, title: id, error: (d && d.error) === 'private' ? '私密条目:界面上不显示正文' : (d && d.error) || '读不到这个文件' });
947
+ })
948
+ .catch((e) => setEntry({ id, title: id, error: String((e && e.message) || e) }));
949
+ };
950
+
951
+ let downAt = null;
952
+ let clickTimer = null;
953
+ const onDown = (e) => {
954
+ drag = { x: e.clientX, y: e.clientY };
955
+ downAt = { x: e.clientX, y: e.clientY };
956
+ canvas.setPointerCapture(e.pointerId);
957
+ };
958
+ const onUp = (e) => {
959
+ const clicked = downAt && Math.hypot(e.clientX - downAt.x, e.clientY - downAt.y) < 5;
960
+ drag = null;
961
+ downAt = null;
962
+ if (!clicked) return;
963
+ const lp = localPoint(e);
964
+ const n = pick(lp.x, lp.y);
965
+ if (!n) return;
966
+ if (clickTimer) {
967
+ clearTimeout(clickTimer);
968
+ clickTimer = null;
969
+ setPreview(null);
970
+ if (n.kind === 'frag') {
971
+ const k = Number(String(n.id).split('#')[1]) || 0;
972
+ const mine = (data.fragments || []).filter((f) => f.entryId === n.entryId)
973
+ .slice().sort((a, b) => (Number(a.line) || 0) - (Number(b.line) || 0));
974
+ const at = mine.findIndex((f) => f.id === n.id);
975
+ const next = at >= 0 && mine[at + 1] ? Number(mine[at + 1].line) || 0 : 0;
976
+ openEntry(n.entryId, n.line || 0, { k, total: mine.length, label: n.label, next });
977
+ } else {
978
+ openEntry(n.id, 0, null);
979
+ }
980
+ return;
981
+ }
982
+ clickTimer = setTimeout(() => {
983
+ clickTimer = null;
984
+ if (n.kind === 'frag') {
985
+ setPreview(n);
986
+ } else {
987
+ // 主星没有 kind,只有片段带 kind='frag':单击聚焦 / 再单击返回全景
988
+ focusRef.current = focusRef.current === n.id ? null : n.id;
989
+ applyFocus(focusRef.current);
990
+ setPreview(focusRef.current ? n : null);
991
+ setHint(focusRef.current ? '聚焦 ' + n.id + ' · 视角已锁定 · 再点返回' : '');
992
+ }
993
+ }, 220);
994
+ };
995
+ const onMove = (e) => {
996
+ if (drag) {
997
+ yaw += (e.clientX - drag.x) * 0.008;
998
+ pitch = Math.max(-1.2, Math.min(1.2, pitch + (e.clientY - drag.y) * 0.006));
999
+ drag.x = e.clientX;
1000
+ drag.y = e.clientY;
1001
+ return;
1002
+ }
1003
+ const lp = localPoint(e);
1004
+ const n = pick(lp.x, lp.y);
1005
+ hover = n ? n.id : null;
1006
+ canvas.style.cursor = n ? 'pointer' : 'grab';
1007
+ };
1008
+ const onWheel = (e) => {
1009
+ e.preventDefault();
1010
+ zoom = Math.max(0.5, Math.min(8.0, zoom * (e.deltaY > 0 ? 0.92 : 1.08)));
1011
+ };
1012
+ const onLeave = () => {
1013
+ hover = null;
1014
+ canvas.style.cursor = 'grab';
1015
+ };
1016
+ canvas.addEventListener('pointerdown', onDown);
1017
+ canvas.addEventListener('pointerup', onUp);
1018
+ canvas.addEventListener('pointermove', onMove);
1019
+ canvas.addEventListener('wheel', onWheel, { passive: false });
1020
+ canvas.addEventListener('pointerleave', onLeave);
1021
+ canvas.addEventListener('pointercancel', onLeave);
1022
+ raf = requestAnimationFrame(draw);
1023
+
1024
+ return () => {
1025
+ if (clickTimer) clearTimeout(clickTimer);
1026
+ cancelAnimationFrame(raf);
1027
+ obs.disconnect();
1028
+ canvas.removeEventListener('pointerdown', onDown);
1029
+ canvas.removeEventListener('pointerup', onUp);
1030
+ canvas.removeEventListener('pointermove', onMove);
1031
+ canvas.removeEventListener('wheel', onWheel);
1032
+ canvas.removeEventListener('pointerleave', onLeave);
1033
+ canvas.removeEventListener('pointercancel', onLeave);
1034
+ };
1035
+ }, [data, theme]);
1036
+
1037
+ const legend = Object.keys(SHELL).map((k) =>
1038
+ h(
1039
+ 'span',
1040
+ { key: k, style: { display: 'inline-flex', alignItems: 'center', gap: 4, marginRight: 10 } },
1041
+ h('span', {
1042
+ style: {
1043
+ width: 8,
1044
+ height: 8,
1045
+ borderRadius: 99,
1046
+ background: (data && data.palette[k] && data.palette[k].color) || '#888',
1047
+ display: 'inline-block',
1048
+ },
1049
+ }),
1050
+ LABELS[k],
1051
+ ),
1052
+ );
1053
+
1054
+ return h(
1055
+ 'div',
1056
+ { style: { display: 'flex', flexDirection: 'column', height: '100%', minHeight: 380, gap: 8 } },
1057
+ h(
1058
+ 'div',
1059
+ { style: { display: 'flex', flexWrap: 'wrap', gap: 12, fontSize: 11, color: theme.muted, padding: '2px 4px' } },
1060
+ h(
1061
+ 'span',
1062
+ { style: { color: theme.text, fontWeight: 600 } },
1063
+ data ? data.nodes.length + ' 颗星 · ' + (data.fragments || []).length + ' 片段 · ' + (data.edges.length + (data.fragmentEdges || []).length) + ' 条连线' : '星图',
1064
+ ),
1065
+ legend,
1066
+ data ? h('span', null, '热星 ' + data.hot + ' · 枢纽 ' + data.hubs) : null,
1067
+ h(
1068
+ 'button',
1069
+ {
1070
+ onClick: () => setTick((n) => n + 1),
1071
+ title: '重新拉取记忆',
1072
+ style: {
1073
+ font: 'inherit',
1074
+ fontSize: 11,
1075
+ color: theme.muted,
1076
+ background: 'transparent',
1077
+ border: '1px solid ' + theme.border,
1078
+ borderRadius: 6,
1079
+ padding: '1px 7px',
1080
+ cursor: 'pointer',
1081
+ },
1082
+ },
1083
+ '↻',
1084
+ ),
1085
+ h('span', { style: { marginLeft: 'auto' } }, hint || '拖拽旋转 · 滚轮缩放 · 单击主题星看卫星绕行 · 再点返回 · 双击打开'),
1086
+ ),
1087
+ h(
1088
+ 'div',
1089
+ {
1090
+ ref: wrapRef,
1091
+ style: {
1092
+ position: 'relative',
1093
+ flex: 1,
1094
+ minHeight: 340,
1095
+ borderRadius: 12,
1096
+ overflow: 'hidden',
1097
+ background: 'transparent',
1098
+ },
1099
+ },
1100
+ h('canvas', { ref: canvasRef, style: { display: 'block', width: '100%', height: '100%', cursor: 'grab' } }),
1101
+ entry
1102
+ ? h(
1103
+ 'div',
1104
+ {
1105
+ style: {
1106
+ position: 'absolute',
1107
+ inset: 8,
1108
+ display: 'flex',
1109
+ flexDirection: 'column',
1110
+ gap: 8,
1111
+ padding: 12,
1112
+ borderRadius: 10,
1113
+ border: '1px solid ' + theme.border,
1114
+ background: theme.bg,
1115
+ boxShadow: '0 12px 32px rgba(0,0,0,.35)',
1116
+ overflow: 'hidden',
1117
+ },
1118
+ },
1119
+ h(
1120
+ 'div',
1121
+ { style: { display: 'flex', alignItems: 'flex-start', gap: 8, flexShrink: 0 } },
1122
+ h(
1123
+ 'div',
1124
+ { style: { flex: 1, minWidth: 0 } },
1125
+ h(
1126
+ 'div',
1127
+ {
1128
+ style: {
1129
+ fontSize: 13,
1130
+ fontWeight: 600,
1131
+ color: theme.text,
1132
+ whiteSpace: 'nowrap',
1133
+ overflow: 'hidden',
1134
+ textOverflow: 'ellipsis',
1135
+ },
1136
+ },
1137
+ entry.title || entry.id,
1138
+ ),
1139
+ h('div', { style: { fontSize: 10.5, color: theme.muted, marginTop: 2 } }, entry.path || ''),
1140
+ ),
1141
+ h(
1142
+ 'button',
1143
+ {
1144
+ onClick: () => {
1145
+ try {
1146
+ navigator.clipboard.writeText(entry.path || entry.id);
1147
+ setCopied(true);
1148
+ setTimeout(() => setCopied(false), 1200);
1149
+ } catch (e) {}
1150
+ },
1151
+ style: {
1152
+ font: 'inherit',
1153
+ fontSize: 11,
1154
+ color: theme.muted,
1155
+ background: 'transparent',
1156
+ border: '1px solid ' + theme.border,
1157
+ borderRadius: 6,
1158
+ padding: '2px 8px',
1159
+ cursor: 'pointer',
1160
+ },
1161
+ },
1162
+ copied ? '已复制' : '复制路径',
1163
+ ),
1164
+ h(
1165
+ 'button',
1166
+ {
1167
+ onClick: () => setEntry(null),
1168
+ style: {
1169
+ font: 'inherit',
1170
+ fontSize: 11,
1171
+ color: theme.muted,
1172
+ background: 'transparent',
1173
+ border: '1px solid ' + theme.border,
1174
+ borderRadius: 6,
1175
+ padding: '2px 8px',
1176
+ cursor: 'pointer',
1177
+ },
1178
+ },
1179
+ '关闭',
1180
+ ),
1181
+ ),
1182
+ h(
1183
+ 'pre',
1184
+ {
1185
+ style: {
1186
+ flex: 1,
1187
+ margin: 0,
1188
+ overflow: 'auto',
1189
+ whiteSpace: 'pre-wrap',
1190
+ wordBreak: 'break-word',
1191
+ fontSize: 11.5,
1192
+ lineHeight: 1.65,
1193
+ color: theme.text,
1194
+ fontFamily: 'ui-monospace, Consolas, "Microsoft YaHei", monospace',
1195
+ },
1196
+ },
1197
+ entry.body || entry.error || '',
1198
+ ),
1199
+ )
1200
+ : null,
1201
+ error
1202
+ ? h(
1203
+ 'div',
1204
+ { style: { position: 'absolute', inset: 0, display: 'grid', placeItems: 'center', fontSize: 12, color: theme.muted } },
1205
+ '星图数据读不到:' + error,
1206
+ )
1207
+ : null,
1208
+ !data && !error
1209
+ ? h(
1210
+ 'div',
1211
+ { style: { position: 'absolute', inset: 0, display: 'grid', placeItems: 'center', fontSize: 12, color: theme.muted } },
1212
+ '正在读取记忆…',
1213
+ )
1214
+ : null,
1215
+ ),
1216
+ preview && !entry
1217
+ ? h(
1218
+ 'div',
1219
+ {
1220
+ style: {
1221
+ display: 'flex',
1222
+ gap: 8,
1223
+ alignItems: 'baseline',
1224
+ fontSize: 11,
1225
+ color: theme.muted,
1226
+ padding: '2px 4px',
1227
+ whiteSpace: 'nowrap',
1228
+ overflow: 'hidden',
1229
+ },
1230
+ },
1231
+ preview.kind === 'frag'
1232
+ ? [
1233
+ h('span', { key: 'l', style: { color: theme.text, fontWeight: 600 } }, preview.label),
1234
+ h('span', { key: 'e', style: { opacity: 0.8 } }, preview.entryTitle || preview.entryId),
1235
+ h('span', { key: 'n', style: { marginLeft: 'auto' } }, '双击打开 · 第 ' + (preview.line || 1) + ' 行'),
1236
+ ]
1237
+ : [
1238
+ h('span', { key: 'id', style: { color: theme.text, fontWeight: 600 } }, preview.id),
1239
+ h('span', { key: 'layer', style: { opacity: 0.8 } }, preview.layer || '未分层'),
1240
+ h('span', { key: 'kb' }, (preview.bytes / 1024).toFixed(1) + ' KB'),
1241
+ h('span', { key: 'tags' }, (preview.tags || []).slice(0, 4).join(' · ')),
1242
+ h('span', { key: 'hint', style: { marginLeft: 'auto' } }, '双击打开'),
1243
+ ],
1244
+ )
1245
+ : null,
1246
+ data
1247
+ ? h('div', { style: { fontSize: 10.5, color: theme.muted, textAlign: 'right' } }, data.generatedAt + ' 生成 · 打开前可跑 memo_star 刷新')
1248
+ : null,
1249
+ );
1250
+ }
1251
+
1252
+ const LAYER_ORDER = ['core', 'fact', 'skill', 'daily', 'emotion'];
1253
+ const TIER_LABEL = { core: '硬事实 · 不衰减', insight: '对人对事的理解', fact: '长期', skill: '长长期', daily: '一般', emotion: '短期' };
1254
+ function fmtKB(bytes) { return (Number(bytes || 0) / 1024).toFixed(1) + ' KB'; }
1255
+
1256
+ // ---------- 概览(v2.31 重构时被删掉了,这里补回;否则点「概览」会整块白屏) ----------
1257
+ function Overview(props) {
1258
+ const data = props.data; const theme = props.theme;
1259
+ const s = data.stats || {};
1260
+ const byLayer = s.byLayer || {};
1261
+ const tiers = s.tiers || [];
1262
+ const card = (label, value, hint) => h('div', { key: label, style: { border: '1px solid ' + theme.border, borderRadius: 10, padding: '8px 10px', flex: '1 1 96px', minWidth: 96 } },
1263
+ h('div', { style: { fontSize: 10.5, color: theme.muted } }, label),
1264
+ h('div', { style: { fontSize: 18, fontWeight: 600, color: theme.text, marginTop: 2 } }, String(value)),
1265
+ hint ? h('div', { style: { fontSize: 10, color: theme.muted, marginTop: 2 } }, hint) : null);
1266
+ const layerRow = (k) => h('tr', { key: k },
1267
+ h('td', { style: { padding: '4px 6px', color: theme.text } }, LABELS[k] || k),
1268
+ h('td', { style: { padding: '4px 6px', textAlign: 'right', color: theme.text } }, String(byLayer[k] || 0)),
1269
+ h('td', { style: { padding: '4px 6px', textAlign: 'right', color: theme.muted } }, TIER_LABEL[k] || ''),
1270
+ );
1271
+ return h('div', { style: { display: 'flex', flexDirection: 'column', gap: 12, height: '100%', minHeight: 380, overflow: 'auto', paddingRight: 4 } },
1272
+ h('div', { style: { display: 'flex', flexWrap: 'wrap', gap: 8 } },
1273
+ card('条目', s.entries != null ? s.entries : (data.nodes || []).length, '条明细'),
1274
+ card('片段', (data.fragments || []).length, '可点节点'),
1275
+ card('明细合计', fmtKB(s.bytes), 'Markdown'),
1276
+ card('活跃会话', s.sessions != null ? s.sessions : 0, '7 天触点'),
1277
+ ),
1278
+ h('table', { style: { width: '100%', borderCollapse: 'collapse', fontSize: 11.5 } },
1279
+ h('thead', null, h('tr', null,
1280
+ h('th', { style: { textAlign: 'left', color: theme.muted, fontWeight: 500, padding: '2px 6px' } }, '层'),
1281
+ h('th', { style: { textAlign: 'right', color: theme.muted, fontWeight: 500, padding: '2px 6px' } }, '条数'),
1282
+ h('th', { style: { textAlign: 'right', color: theme.muted, fontWeight: 500, padding: '2px 6px' } }, '分档'),
1283
+ )),
1284
+ h('tbody', null, LAYER_ORDER.map(layerRow)),
1285
+ ),
1286
+ h('div', { style: { fontSize: 10.5, color: theme.muted } }, '最后更新 ' + (s.lastUpdate ? new Date(s.lastUpdate).toLocaleString() : '-')),
1287
+ );
1288
+ }
1289
+
1290
+ // ---------- 错误边界:一个视图炸了不要整块黑屏 ----------
1291
+ class TabBoundary extends React.Component {
1292
+ constructor(props) { super(props); this.state = { err: null }; }
1293
+ static getDerivedStateFromError(err) { return { err: err }; }
1294
+ componentDidCatch(err) { try { console.error('[memo] tab crashed:', this.props.name, err); } catch (e) {} }
1295
+ render() {
1296
+ if (this.state.err) {
1297
+ const msg = String((this.state.err && this.state.err.message) || this.state.err);
1298
+ return h('div', { style: { padding: 12, fontSize: 12, color: '#ffb4b4', fontFamily: 'monospace', whiteSpace: 'pre-wrap', overflow: 'auto', height: '100%' } },
1299
+ '这个视图出错了(' + String(this.props.name) + '):\n' + msg);
1300
+ }
1301
+ return this.props.children;
1302
+ }
1303
+ }
1304
+
1305
+ // ---------- 记忆列表 ----------
1306
+ function MemoryList(props) {
1307
+ const data = props.data; const theme = props.theme; const onOpen = props.onOpen;
1308
+ const [q, setQ] = React.useState('');
1309
+ const rows = React.useMemo(() => {
1310
+ const list = (data.nodes || []).slice().sort((a, b) => (b.mtime || 0) - (a.mtime || 0));
1311
+ const s = q.trim().toLowerCase();
1312
+ if (!s) return list;
1313
+ return list.filter((n) => String(n.id).toLowerCase().indexOf(s) >= 0 || (n.tags || []).join(' ').toLowerCase().indexOf(s) >= 0);
1314
+ }, [data, q]);
1315
+ return h('div', { style: { display: 'flex', flexDirection: 'column', gap: 8, height: '100%', minHeight: 380 } },
1316
+ h('input', { value: q, onChange: (e) => setQ(e.target.value), placeholder: '搜 id / 标签', style: { font: 'inherit', fontSize: 12, color: theme.text, background: 'transparent', border: '1px solid ' + theme.border, borderRadius: 8, padding: '5px 9px', outline: 'none' } }),
1317
+ h('div', { style: { flex: 1, overflow: 'auto', border: '1px solid ' + theme.border, borderRadius: 10 } },
1318
+ rows.map((n) => h('div', { key: n.id, onClick: () => onOpen(n.id, 0), style: { display: 'flex', gap: 8, alignItems: 'baseline', padding: '6px 10px', borderBottom: '1px solid ' + theme.border, cursor: 'pointer', fontSize: 12 } },
1319
+ h('span', { style: { color: theme.text, fontWeight: 600, minWidth: 92 } }, String(n.id)),
1320
+ h('span', { style: { color: theme.muted, flex: 1, overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap' } }, (n.tags || []).join(' · ') || '—'),
1321
+ h('span', { style: { color: theme.muted, whiteSpace: 'nowrap' } }, fmtKB(n.bytes)),
1322
+ h('span', { style: { color: theme.muted, whiteSpace: 'nowrap' } }, '读 ' + (n.hits || 0)),
1323
+ )),
1324
+ ),
1325
+ );
1326
+ }
1327
+
1328
+ // ---------- 按天日记 / 时间线 ----------
1329
+ function DiaryView() {
1330
+ const theme = useTheme();
1331
+ const [days, setDays] = React.useState(null);
1332
+ const [error, setError] = React.useState('');
1333
+ const [sel, setSel] = React.useState('');
1334
+ const [text, setText] = React.useState('');
1335
+ const [loading, setLoading] = React.useState(false);
1336
+ React.useEffect(() => {
1337
+ let alive = true;
1338
+ fetch('/api/memo-star/diary', { cache: 'no-store' })
1339
+ .then((r) => { if (!r.ok) throw new Error('HTTP ' + r.status); return r.json(); })
1340
+ .then((d) => {
1341
+ if (!alive) return;
1342
+ if (!d.ok) throw new Error(d.error || '读取失败');
1343
+ setDays(d.days || []);
1344
+ if ((d.days || []).length) setSel((cur) => cur || d.days[0].date);
1345
+ })
1346
+ .catch((e) => { if (alive) setError(String((e && e.message) || e)); });
1347
+ return () => { alive = false; };
1348
+ }, []);
1349
+ React.useEffect(() => {
1350
+ if (!sel) return;
1351
+ let alive = true;
1352
+ setLoading(true);
1353
+ fetch('/api/memo-star/diary?date=' + encodeURIComponent(sel), { cache: 'no-store' })
1354
+ .then((r) => r.json())
1355
+ .then((d) => {
1356
+ if (!alive) return;
1357
+ if (d.ok) setText(d.text || '');
1358
+ else setError(d.error || '读不到这一天的日记');
1359
+ })
1360
+ .catch((e) => { if (alive) setError(String((e && e.message) || e)); })
1361
+ .finally(() => { if (alive) setLoading(false); });
1362
+ return () => { alive = false; };
1363
+ }, [sel]);
1364
+ if (error) return h('div', { style: { display: 'grid', placeItems: 'center', height: '100%', minHeight: 340, fontSize: 12, color: theme.muted } }, '日记读不到:' + error);
1365
+ if (!days) return h('div', { style: { display: 'grid', placeItems: 'center', height: '100%', minHeight: 340, fontSize: 12, color: theme.muted } }, '正在读取日记…');
1366
+ if (!days.length) return h('div', { style: { display: 'grid', placeItems: 'center', height: '100%', minHeight: 340, fontSize: 12, color: theme.muted } }, '还没有日记:归档会话自动摘要后,会按天汇总到这里');
1367
+ return h('div', { style: { display: 'flex', gap: 10, height: '100%', minHeight: 340 } },
1368
+ h('div', { style: { width: 150, flexShrink: 0, overflow: 'auto', borderRight: '1px solid ' + theme.border, paddingRight: 8 } },
1369
+ days.map((d) => h('button', {
1370
+ key: d.date,
1371
+ onClick: () => { setSel(d.date); setError(''); },
1372
+ style: {
1373
+ display: 'block', width: '100%', textAlign: 'left', font: 'inherit', fontSize: 11,
1374
+ cursor: 'pointer', border: 'none', borderRadius: 6, padding: '4px 6px', marginBottom: 2,
1375
+ color: sel === d.date ? theme.bg : theme.text,
1376
+ background: sel === d.date ? theme.text : 'transparent',
1377
+ },
1378
+ }, d.date + ' · ' + d.entries + ' 段'))),
1379
+ h('div', { style: { flex: 1, minWidth: 0, overflow: 'auto' } },
1380
+ loading
1381
+ ? h('div', { style: { display: 'grid', placeItems: 'center', height: '100%', fontSize: 12, color: theme.muted } }, '读取中…')
1382
+ : h('pre', { style: { margin: 0, whiteSpace: 'pre-wrap', wordBreak: 'break-word', fontSize: 11.5, lineHeight: 1.65, color: theme.text, fontFamily: 'ui-monospace, Consolas, "Microsoft YaHei", monospace' } }, text || '选一天看日记')),
1383
+ );
1384
+ }
1385
+
1386
+ function StarView() {
1387
+ const theme = useTheme();
1388
+ const [data, setData] = React.useState(null);
1389
+ const [error, setError] = React.useState('');
1390
+ const [tick, setTick] = React.useState(0);
1391
+ const [tab, setTab] = React.useState('graph');
1392
+ const [entry, setEntry] = React.useState(null);
1393
+ const [hint, setHint] = React.useState('');
1394
+ React.useEffect(() => {
1395
+ let alive = true;
1396
+ fetch('/api/memo-star/data', { cache: 'no-store' })
1397
+ .then((r) => { if (!r.ok) throw new Error('HTTP ' + r.status); return r.json(); })
1398
+ .then((d) => { if (alive) { setData(d); setError(''); } })
1399
+ .catch((e) => { if (alive) setError(String((e && e.message) || e)); });
1400
+ return () => { alive = false; };
1401
+ }, [tick]);
1402
+ React.useEffect(() => { const id = setInterval(() => setTick((n) => n + 1), 60000); return () => clearInterval(id); }, []);
1403
+ const openEntry = (id, line) => {
1404
+ const open = sidebar.open || resolveSidebar();
1405
+ if (open) { setPending(id, line); if (open('memo-entry') !== false) return; }
1406
+ setHint('侧栏服务没就绪,先用内嵌面板');
1407
+ fetch('/api/memo-star/entry?id=' + encodeURIComponent(id) + (line ? '&line=' + line : ''), { cache: 'no-store' })
1408
+ .then((r) => r.json())
1409
+ .then((d) => {
1410
+ if (d && d.ok) setEntry(d);
1411
+ else setEntry({ id: id, title: id, error: (d && d.error) === 'private' ? '私密条目:界面上不显示正文' : (d && d.error) || '读不到这个文件' });
1412
+ })
1413
+ .catch((e) => setEntry({ id: id, title: id, error: String((e && e.message) || e) }));
1414
+ };
1415
+ const tabs = [['graph', '星图'], ['diary', '日记'], ['overview', '概览'], ['memory', '记忆']];
1416
+ const [hideNames, setHideNames] = React.useState(false);
1417
+ const btnStyle = (on) => ({
1418
+ font: 'inherit', fontSize: 11, cursor: 'pointer', borderRadius: 99, padding: '2px 11px',
1419
+ color: on ? theme.bg : theme.muted,
1420
+ background: on ? theme.text : 'transparent',
1421
+ border: '1px solid ' + (on ? theme.text : theme.border),
1422
+ });
1423
+ let body = null;
1424
+ if (tab === 'diary') body = h(DiaryView);
1425
+ else if (!data && !error) body = h('div', { style: { display: 'grid', placeItems: 'center', height: '100%', minHeight: 340, fontSize: 12, color: theme.muted } }, '正在读取记忆…');
1426
+ else if (error) body = h('div', { style: { display: 'grid', placeItems: 'center', height: '100%', minHeight: 340, fontSize: 12, color: theme.muted } }, '星图数据读不到:' + error);
1427
+ else if (tab === 'overview') body = h(Overview, { data: data, theme: theme });
1428
+ else if (tab === 'graph') body = null;
1429
+ else body = h(MemoryList, { data: data, theme: theme, onOpen: openEntry });
1430
+ return h('div', { style: { display: 'flex', flexDirection: 'column', height: '100%', minHeight: 420, gap: 8 } },
1431
+ h('div', { style: { display: 'flex', alignItems: 'center', gap: 8, flexWrap: 'wrap', fontSize: 11, color: theme.muted } },
1432
+ tabs.map((t) => h('button', { key: t[0], onClick: () => setTab(t[0]), style: btnStyle(tab === t[0]) }, t[1])),
1433
+ h('button', {
1434
+ onClick: () => setHideNames((v) => !v),
1435
+ title: '隐藏 / 显示主题星与恒星的名字',
1436
+ style: btnStyle(hideNames),
1437
+ }, hideNames ? '显示名字' : '隐藏名字'),
1438
+ h('span', { style: { fontSize: 10, color: theme.muted, opacity: 0.75 } }, 'v2.63.0'),
1439
+ data ? h('span', { style: { color: theme.text, fontWeight: 600 } }, (data.nodes || []).length + ' 条 · ' + (data.fragments || []).length + ' 片段 · ' + ((data.edges || []).length + (data.fragmentEdges || []).length) + ' 连线') : null,
1440
+ h('button', { onClick: () => { try { window.open('http://127.0.0.1:8791/', '_blank', 'noopener'); } catch (e) {} }, title: '原文归档:新标签打开,列出所有已存会话(只读)', style: { font: 'inherit', fontSize: 11, color: theme.text, background: 'transparent', border: '1px solid ' + theme.border, borderRadius: 6, padding: '1px 8px', cursor: 'pointer' } }, '归档'),
1441
+ h('button', { onClick: () => setTick((n) => n + 1), title: '重新拉取', style: { font: 'inherit', fontSize: 11, color: theme.muted, background: 'transparent', border: '1px solid ' + theme.border, borderRadius: 6, padding: '1px 7px', cursor: 'pointer' } }, '↻'),
1442
+ h('span', { style: { marginLeft: 'auto' } }, hint || '单击主题星看卫星绕行 · 再点返回 · 双击打开'),
1443
+ ),
1444
+ h('div', { style: { flex: 1, minHeight: 360, position: 'relative' } },
1445
+ h('div', { style: { position: 'absolute', inset: 0, display: tab === 'graph' ? 'block' : 'none' } }, h(Star3D, { hideNames: hideNames })),
1446
+ body ? h(TabBoundary, { key: tab, name: tab }, h('div', { style: { position: 'absolute', inset: 0, overflow: 'auto' } }, body)) : null,
1447
+ entry ? h('div', { key: 'fallback', style: { position: 'absolute', inset: 8, display: 'flex', flexDirection: 'column', gap: 8, padding: 12, borderRadius: 10, border: '1px solid ' + theme.border, background: theme.bg, boxShadow: '0 12px 32px rgba(0,0,0,.35)', overflow: 'hidden' } },
1448
+ h('div', { style: { display: 'flex', alignItems: 'flex-start', gap: 8, flexShrink: 0 } },
1449
+ h('div', { style: { flex: 1, minWidth: 0 } },
1450
+ h('div', { style: { fontSize: 13, fontWeight: 600, color: theme.text, whiteSpace: 'nowrap', overflow: 'hidden', textOverflow: 'ellipsis' } }, entry.title || entry.id),
1451
+ h('div', { style: { fontSize: 10.5, color: theme.muted, marginTop: 2 } }, (entry.line ? '第 ' + entry.line + ' 行 · ' : '') + (entry.path || '')),
1452
+ ),
1453
+ h('button', { onClick: () => setEntry(null), style: { font: 'inherit', fontSize: 11, color: theme.muted, background: 'transparent', border: '1px solid ' + theme.border, borderRadius: 6, padding: '2px 8px', cursor: 'pointer' } }, '关闭'),
1454
+ ),
1455
+ h('pre', { style: { flex: 1, margin: 0, overflow: 'auto', whiteSpace: 'pre-wrap', wordBreak: 'break-word', fontSize: 11.5, lineHeight: 1.65, color: theme.text, fontFamily: 'ui-monospace, Consolas, "Microsoft YaHei", monospace' } }, entry.body || entry.error || ''),
1456
+ ) : null,
1457
+ ),
1458
+ h('div', { style: { fontSize: 10.5, color: theme.muted, textAlign: 'right' } }, data ? data.generatedAt + ' 生成 · 打开前可跑 memo_star 刷新' : ''),
1459
+ );
1460
+ }
1461
+ return {
1462
+ inject: ['slots', 'sidebarRightTabs', 'sidebarRight'],
1463
+ apply(ctx) {
1464
+ sidebar.ctx = ctx;
1465
+ if (!sidebar.open) resolveSidebar();
1466
+ ctx.slots.inject('conversation.view', () =>
1467
+ ctx.slots.register(
1468
+ { name: 'conversation.view', id: 'memo-star', order: 40, label: () => '星图' },
1469
+ StarView,
1470
+ ),
1471
+ );
1472
+
1473
+ // 右侧栏(官方 sidebar):注册一个「记忆」tab 类型 + 面板体
1474
+ try {
1475
+ const tabs = typeof ctx.get === 'function' ? ctx.get('sidebarRightTabs') : ctx.sidebarRightTabs;
1476
+ const right = typeof ctx.get === 'function' ? ctx.get('sidebarRight') : ctx.sidebarRight;
1477
+ sidebar.open =
1478
+ right && typeof right.openTab === 'function'
1479
+ ? (kind) => {
1480
+ try {
1481
+ right.openTab(kind);
1482
+ } catch (e) {
1483
+ sidebar.open = null;
1484
+ }
1485
+ }
1486
+ : null;
1487
+ if (tabs && typeof tabs.register === 'function') {
1488
+ ctx.effect(
1489
+ () =>
1490
+ tabs.register({
1491
+ id: 'memo-entry',
1492
+ kind: 'memo-entry',
1493
+ title: () => '记忆',
1494
+ // guide: 不注册 —— 「开始」面板里不再出现「记忆条目」胶囊;星图双击仍可打开本 tab
1495
+ }),
1496
+ 'memo: sidebar tab type',
1497
+ );
1498
+ ctx.slots.inject('sidebar.right.pane.tab', () =>
1499
+ ctx.slots.register({ name: 'sidebar.right.pane.tab', key: 'memo-entry' }, EntryPane),
1500
+ );
1501
+ ctx.slots.inject('sidebar.right.pane.tab.title', () =>
1502
+ ctx.slots.register(
1503
+ { name: 'sidebar.right.pane.tab.title', key: 'memo-entry' },
1504
+ () => h('span', { style: { fontSize: 12 } }, '记忆'),
1505
+ ),
1506
+ );
1507
+ }
1508
+ } catch (e) {}
1509
+ },
1510
+ };
1511
+ },
1512
+ });