cortico-world-memory-core 0.26.1 → 0.27.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.
package/webui/app.js CHANGED
@@ -63,6 +63,11 @@ const el = {
63
63
  menu: $('#menu'),
64
64
  };
65
65
 
66
+ const narrowFilters = matchMedia('(max-width: 980px)');
67
+ const narrowInspector = matchMedia('(max-width: 899px)');
68
+ const atlasPage = document.body.classList.contains('atlas-app');
69
+ if (atlasPage) S.inspCollapsed = narrowInspector.matches;
70
+
66
71
  /* ── 小工具 ─────────────────────────────────────────── */
67
72
 
68
73
  const pad = (n) => String(n).padStart(2, '0');
@@ -158,6 +163,8 @@ function highlight(text, q) {
158
163
  function toast(msg, isErr = false) {
159
164
  el.toast.textContent = msg;
160
165
  el.toast.classList.toggle('err', isErr);
166
+ el.toast.setAttribute('role', isErr ? 'alert' : 'status');
167
+ el.toast.setAttribute('aria-live', isErr ? 'assertive' : 'polite');
161
168
  el.toast.hidden = false;
162
169
  clearTimeout(toast._t);
163
170
  toast._t = setTimeout(() => {
@@ -169,6 +176,8 @@ function toast(msg, isErr = false) {
169
176
  function toastUndo(msg, onUndo, ms = 10000) {
170
177
  el.toast.innerHTML = `<span>${esc(msg)}</span><button type="button" class="toast-undo">撤销</button>`;
171
178
  el.toast.classList.remove('err');
179
+ el.toast.setAttribute('role', 'status');
180
+ el.toast.setAttribute('aria-live', 'polite');
172
181
  el.toast.hidden = false;
173
182
  clearTimeout(toast._t);
174
183
  el.toast.querySelector('.toast-undo')?.addEventListener('click', async () => {
@@ -288,10 +297,16 @@ $('#btn-theme').addEventListener('click', () => {
288
297
  /* ── 数据与筛选 ─────────────────────────────────────── */
289
298
 
290
299
  async function load({ quiet = false } = {}) {
300
+ const busy = () => S.editing || !el.modal.hidden || (immersiveAtlas() && el.inspector.contains(document.activeElement));
301
+ if (quiet && busy()) return;
291
302
  try {
292
303
  const snap = await api('/api/snapshot');
304
+ if (quiet && busy()) return;
293
305
  S.snap = snap;
294
306
  render();
307
+ if (typeof window !== 'undefined' && typeof CustomEvent === 'function') {
308
+ window.dispatchEvent(new CustomEvent('mcore:snapshot', { detail: snap }));
309
+ }
295
310
  } catch (err) {
296
311
  toast(`读不到数据:${err.message}`, true);
297
312
  }
@@ -333,24 +348,56 @@ function selectedCard() {
333
348
  /* ── 右栏折叠 ───────────────────────────────────────── */
334
349
 
335
350
  function applyInspState() {
336
- document.body.dataset.insp = S.inspCollapsed ? 'off' : 'on';
351
+ const off = inspectorCollapsed();
352
+ document.body.dataset.insp = off ? 'off' : 'on';
337
353
  const badge = $('#stub-count');
338
354
  if (badge) badge.textContent = String(filtered().length);
355
+ const details = $('#btn-details');
356
+ if (details) {
357
+ const story = immersiveAtlas();
358
+ const name = story ? (atlasFiltered() ? '筛选结果' : '观察记录') : '详情';
359
+ if (story) $('#story-inspector-name').textContent = name;
360
+ details.setAttribute('aria-expanded', String(!off));
361
+ details.title = off ? name : story ? '关闭浮层' : '关闭详情';
362
+ details.setAttribute('aria-label', off ? `打开${name}` : details.title);
363
+ }
339
364
  }
340
365
 
341
366
  function setInspCollapsed(off) {
342
- S.inspCollapsed = Boolean(off);
343
- localStorage.setItem('mcore-insp', S.inspCollapsed ? 'off' : 'on');
367
+ if (immersiveAtlas()) storyInspCollapsed = off;
368
+ else {
369
+ S.inspCollapsed = off;
370
+ localStorage.setItem('mcore-insp', off ? 'off' : 'on');
371
+ }
372
+ if (!off && narrowFilters.matches) setFiltersOpen(false);
344
373
  applyInspState();
345
374
  }
346
375
 
347
- function selectCard(id, { scroll = false } = {}) {
376
+ function setFiltersOpen(open) {
377
+ const next = Boolean(open) && (atlasPage || narrowFilters.matches);
378
+ if (next && narrowInspector.matches) setInspCollapsed(true);
379
+ $('#atlas-filter')?.setAttribute('aria-expanded', String(next));
380
+ document.body.dataset.filters = next ? 'open' : 'closed';
381
+ const btn = $('#btn-filters');
382
+ if (btn) {
383
+ btn.setAttribute('aria-expanded', String(next));
384
+ btn.setAttribute('aria-label', next ? '关闭筛选' : '打开筛选');
385
+ btn.title = next ? '关闭筛选' : '筛选';
386
+ }
387
+ }
388
+
389
+ function selectCard(id, { scroll = false, trigger = document.activeElement } = {}) {
390
+ if (immersiveAtlas() && !el.inspector.contains(trigger)) storyReturnFocus = trigger;
391
+ if (atlasPage && !S.selected && id) atlasResultsScroll = el.inspBody.scrollTop;
348
392
  S.selected = id ?? null;
349
393
  S.editing = false;
350
- setInspCollapsed(!id); // 选中就展开详情,取消就收回去
394
+ if (id && narrowFilters.matches) setFiltersOpen(false);
395
+ setInspCollapsed(!id && !atlasPage);
351
396
  renderStage();
352
397
  renderInspector();
353
398
  renderStatus();
399
+ if (atlasPage) el.inspBody.scrollTop = id ? 0 : atlasResultsScroll;
400
+ if (immersiveAtlas()) $('#story-inspector-close').focus({ preventScroll: true });
354
401
  if (scroll && id) {
355
402
  document.querySelector(`.tl-item[data-id="${id}"], tr[data-id="${id}"]`)?.scrollIntoView({ block: 'nearest' });
356
403
  }
@@ -361,6 +408,28 @@ function bindInspCollapse() {
361
408
  if (btn) btn.addEventListener('click', () => setInspCollapsed(true));
362
409
  }
363
410
 
411
+ function closeStoryInspector() {
412
+ S.selected = null;
413
+ S.editing = false;
414
+ setInspCollapsed(true);
415
+ orbitAtlas?.update(null, Boolean(S.query));
416
+ const target = storyReturnFocus;
417
+ (target?.getClientRects().length ? target : $('#btn-details')).focus({ preventScroll: true });
418
+ storyReturnFocus = null;
419
+ }
420
+
421
+ function toggleInspector() {
422
+ if (immersiveAtlas() && !inspectorCollapsed()) return closeStoryInspector();
423
+ setInspCollapsed(!inspectorCollapsed());
424
+ if (!inspectorCollapsed()) {
425
+ renderInspector();
426
+ if (immersiveAtlas()) {
427
+ storyReturnFocus = $('#btn-details');
428
+ $('#story-inspector-close').focus({ preventScroll: true });
429
+ }
430
+ }
431
+ }
432
+
364
433
  /* ── 顶栏指标 ───────────────────────────────────────── */
365
434
 
366
435
  function renderMetrics() {
@@ -519,42 +588,46 @@ function renderRail() {
519
588
  }
520
589
 
521
590
  el.rail.addEventListener('click', (event) => {
591
+ const done = () => {
592
+ render();
593
+ setFiltersOpen(false);
594
+ };
522
595
  const kindBtn = event.target.closest('[data-kind]');
523
596
  if (kindBtn) {
524
597
  const id = kindBtn.dataset.kind;
525
598
  if (S.kinds.has(id)) S.kinds.delete(id);
526
599
  else S.kinds.add(id);
527
- render();
600
+ done();
528
601
  return;
529
602
  }
530
603
  const tagBtn = event.target.closest('[data-tag]');
531
604
  if (tagBtn) {
532
605
  const t = tagBtn.dataset.tag;
533
606
  S.tag = S.tag === t ? null : t;
534
- render();
607
+ done();
535
608
  return;
536
609
  }
537
610
  if (event.target.id === 'tag-clear') {
538
611
  S.tag = null;
539
- render();
612
+ done();
540
613
  return;
541
614
  }
542
615
  const rangeBtn = event.target.closest('[data-range]');
543
616
  if (rangeBtn) {
544
617
  S.range = rangeBtn.dataset.range;
545
- render();
618
+ done();
546
619
  return;
547
620
  }
548
621
  const statusBtn = event.target.closest('[data-status]');
549
622
  if (statusBtn) {
550
623
  S.status = statusBtn.dataset.status;
551
- render();
624
+ done();
552
625
  return;
553
626
  }
554
627
  const scopeBtn = event.target.closest('[data-scope]');
555
628
  if (scopeBtn) {
556
629
  S.scope = S.scope === scopeBtn.dataset.scope ? null : scopeBtn.dataset.scope;
557
- render();
630
+ done();
558
631
  }
559
632
  });
560
633
 
@@ -992,894 +1065,55 @@ class Graph {
992
1065
  }
993
1066
  }
994
1067
 
995
- /* ── 记忆星图(3D) ─────────────────────────────────── */
996
-
997
- const GALAXY_KIND = { fact: '事实', self: '自己', episode: '经历', promise: '承诺', note: '临时' };
998
- const GALAXY_COLOR = { fact: '#72f4dc', self: '#a997ff', episode: '#ffd18a', promise: '#ff9fc9', note: '#b9d3e8' };
999
- /** 攒够 3 张就独立成团的标签,可以有自己的颜色。色相要和它的 kind 拉开,一眼能分。 */
1000
- const GALAXY_TAG_COLOR = { 独处: '#c9a2ff' };
1001
- const GALAXY_CAM = 1900;
1002
- /** 旋臂薄雾的色号:必须覆盖 buildScene 里所有 arm.tone,否则那一层会被跳过。 */
1003
- const HAZE_TONES = [
1004
- '255,236,198',
1005
- '255,238,205',
1006
- '34,230,255',
1007
- '255,64,128',
1008
- '255,120,170',
1009
- '150,120,255',
1010
- ];
1011
-
1012
- /** 固定种子:同一批卡片每次布出来的星系一样。 */
1013
- function seeded(seed) {
1014
- let s = seed >>> 0 || 1;
1015
- return () => {
1016
- s = (s * 1664525 + 1013904223) >>> 0;
1017
- return s / 4294967296;
1018
- };
1019
- }
1068
+ let atlasResultsScroll = 0;
1069
+ let orbitAtlas, orbitLoading = false, orbitFailed = false, orbitSignature = '';
1070
+ let storyInspCollapsed = true, storyReturnFocus;
1071
+ const immersiveAtlas = () => atlasPage && S.view === 'galaxy';
1072
+ const inspectorCollapsed = () => immersiveAtlas() ? storyInspCollapsed : S.inspCollapsed;
1073
+ const libraryView = () => ['galaxy','table','graph','timeline'].includes(S.view);
1020
1074
 
1021
- const clampNum = (v, lo, hi) => Math.max(lo, Math.min(hi, v));
1022
-
1023
- /** 圆角矩形:不用 ctx.roundRect,老一点的宿主内核没有这个 API。 */
1024
- function roundRect(ctx, x, y, w, h, r) {
1025
- const rr = Math.min(r, h / 2, w / 2);
1026
- ctx.beginPath();
1027
- ctx.moveTo(x + rr, y);
1028
- ctx.arcTo(x + w, y, x + w, y + h, rr);
1029
- ctx.arcTo(x + w, y + h, x, y + h, rr);
1030
- ctx.arcTo(x, y + h, x, y, rr);
1031
- ctx.arcTo(x, y, x + w, y, rr);
1032
- ctx.closePath();
1075
+ function chooseAtlasKind(kind) {
1076
+ const clear = !kind || (S.kinds.size === 1 && S.kinds.has(kind));
1077
+ S.kinds.clear();
1078
+ if (!clear) S.kinds.add(kind);
1079
+ S.selected = null; S.editing = false;
1080
+ render();
1033
1081
  }
1034
1082
 
1035
-
1036
- class Galaxy {
1037
- constructor(canvas) {
1038
- this.canvas = canvas;
1039
- this.ctx = canvas.getContext('2d');
1040
- this.cards = [];
1041
- this.nodes = [];
1042
- this.links = [];
1043
- this.regions = [];
1044
- this.dust = [];
1045
- this.armTrails = [];
1046
- this.clusters = [];
1047
- this.far = [];
1048
- this.glow = new Map();
1049
- this.hover = null;
1050
- this.selected = null;
1051
- this.signature = null;
1052
- this.onSelect = null;
1053
-
1054
- this.yaw = 0.55;
1055
- this.pitch = 0.46;
1056
- this.zoom = 1;
1057
- this.panX = 0;
1058
- this.panY = 0;
1059
- const gx = new URLSearchParams(location.search).get('gx');
1060
- if (gx) {
1061
- const [a, b, c] = gx.split(',').map(Number);
1062
- if (Number.isFinite(a)) this.yaw = a;
1063
- if (Number.isFinite(b)) this.pitch = clampNum(b, -1.35, 1.35);
1064
- if (Number.isFinite(c)) this.zoom = clampNum(c, 0.45, 3.2);
1065
- }
1066
- this.vy = 0;
1067
- this.vp = 0;
1068
- this.dragging = false;
1069
- this.lastInteract = 0;
1070
- this.frame = 0;
1071
- this.running = false;
1072
- this.tickCount = 0;
1073
-
1074
- this.w = 0;
1075
- this.h = 0;
1076
- this.dpr = 1;
1077
- this.buildSprites();
1078
- this.bind();
1079
- new ResizeObserver(() => this.resize()).observe(canvas.parentElement);
1080
- this.resize();
1081
- }
1082
-
1083
- bind() {
1084
- const c = this.canvas;
1085
- let last = null;
1086
- let down = null;
1087
-
1088
- c.addEventListener('pointerdown', (e) => {
1089
- this.dragging = true;
1090
- this.vy = 0;
1091
- this.vp = 0;
1092
- last = { x: e.clientX, y: e.clientY };
1093
- down = { x: e.clientX, y: e.clientY };
1094
- this.lastInteract = performance.now();
1095
- c.setPointerCapture(e.pointerId);
1096
- c.classList.add('grabbing');
1097
- });
1098
-
1099
- c.addEventListener('pointermove', (e) => {
1100
- if (this.dragging && last) {
1101
- const dx = e.clientX - last.x;
1102
- const dy = e.clientY - last.y;
1103
- last = { x: e.clientX, y: e.clientY };
1104
- this.yaw += dx * 0.0062;
1105
- this.pitch = clampNum(this.pitch + dy * 0.0062, -1.35, 1.35);
1106
- this.vy = dx * 0.0062;
1107
- this.vp = dy * 0.0062;
1108
- this.lastInteract = performance.now();
1109
- return;
1110
- }
1111
- const hit = this.pick(e.clientX, e.clientY);
1112
- const id = hit ? hit.card.id : null;
1113
- if (id === this.hover) return;
1114
- this.hover = id;
1115
- c.style.cursor = hit ? 'pointer' : 'grab';
1116
- });
1117
-
1118
- const end = () => {
1119
- this.dragging = false;
1120
- last = null;
1121
- this.lastInteract = performance.now();
1122
- c.classList.remove('grabbing');
1123
- };
1124
- c.addEventListener('pointerup', end);
1125
- c.addEventListener('pointercancel', end);
1126
- c.addEventListener('pointerleave', () => {
1127
- this.hover = null;
1128
- });
1129
-
1130
- c.addEventListener(
1131
- 'wheel',
1132
- (e) => {
1133
- e.preventDefault();
1134
- const box = c.getBoundingClientRect();
1135
- const dx = e.clientX - box.left - this.CX;
1136
- const dy = e.clientY - box.top - this.CY;
1137
- const old = this.zoom;
1138
- const next = clampNum(old * Math.exp(-e.deltaY * 0.0013), 0.45, 3.2);
1139
- if (next === old) return;
1140
- // 让光标指着的那颗星别跑:按比例反推平移量
1141
- const ratio = next / old;
1142
- this.panX = clampNum(dx - (dx - this.panX) * ratio, -this.w * 0.5, this.w * 0.5);
1143
- this.panY = clampNum(dy - (dy - this.panY) * ratio, -this.h * 0.5, this.h * 0.5);
1144
- this.zoom = next;
1145
- this.lastInteract = performance.now();
1146
- },
1147
- { passive: false },
1148
- );
1149
-
1150
- c.addEventListener('dblclick', () => {
1151
- this.yaw = 0.55;
1152
- this.pitch = 0.46;
1153
- this.zoom = 1;
1154
- this.panX = 0;
1155
- this.panY = 0;
1156
- this.vy = 0;
1157
- this.vp = 0;
1158
- this.lastInteract = performance.now();
1159
- });
1160
-
1161
- c.addEventListener('click', (e) => {
1162
- if (!down) return;
1163
- const moved = Math.hypot(e.clientX - down.x, e.clientY - down.y);
1164
- down = null;
1165
- if (moved > 5) return;
1166
- const hit = this.pick(e.clientX, e.clientY);
1167
- if (this.onSelect) this.onSelect(hit ? hit.card.id : null);
1168
- });
1169
- }
1170
-
1171
- resize() {
1172
- const box = this.canvas.parentElement.getBoundingClientRect();
1173
- const w = Math.max(360, Math.round(box.width));
1174
- const h = Math.max(320, Math.round(box.height));
1175
- this.dpr = Math.min(2, window.devicePixelRatio || 1);
1176
- this.w = w;
1177
- this.h = h;
1178
- this.canvas.width = Math.round(w * this.dpr);
1179
- this.canvas.height = Math.round(h * this.dpr);
1180
- this.ctx.setTransform(this.dpr, 0, 0, this.dpr, 0, 0);
1181
- // 空数据也要重排:不然空态会拿构造时那个 360×320 的小尺寸画
1182
- this.buildScene();
1183
- }
1184
-
1185
- start() {
1186
- if (this.running) return;
1187
- this.running = true;
1188
- const loop = () => {
1189
- if (!this.running) return;
1190
- this.step();
1191
- this.frame = requestAnimationFrame(loop);
1192
- };
1193
- this.frame = requestAnimationFrame(loop);
1194
- }
1195
-
1196
- stop() {
1197
- this.running = false;
1198
- if (this.frame) cancelAnimationFrame(this.frame);
1199
- this.frame = 0;
1200
- }
1201
-
1202
- setData(cards) {
1203
- this.cards = cards.slice();
1204
- this.buildScene();
1205
- }
1206
-
1207
- /**
1208
- * 柔光贴图:节点 5 种类型各一张,旋臂薄雾再各一张。
1209
- * 薄雾的色号必须和 buildScene 里 arms 的 tone 一一对上——对不上就取不到贴图,
1210
- * 整层薄雾会被静默跳过(看起来就像旋臂只剩下一圈圈散点)。
1211
- */
1212
- buildSprites() {
1213
- this.glow.clear();
1214
- this.hazeSprites = new Map();
1215
- for (const tone of HAZE_TONES) {
1216
- const size = 128;
1217
- const cv = document.createElement('canvas');
1218
- cv.width = size;
1219
- cv.height = size;
1220
- const g = cv.getContext('2d');
1221
- const grad = g.createRadialGradient(size / 2, size / 2, 0, size / 2, size / 2, size / 2);
1222
- grad.addColorStop(0, `rgba(${tone},1)`);
1223
- grad.addColorStop(0.35, `rgba(${tone},0.45)`);
1224
- grad.addColorStop(1, `rgba(${tone},0)`);
1225
- g.fillStyle = grad;
1226
- g.fillRect(0, 0, size, size);
1227
- this.hazeSprites.set(tone, cv);
1228
- }
1229
- for (const [kind, color] of Object.entries(GALAXY_COLOR)) {
1230
- const size = 128;
1231
- const cv = document.createElement('canvas');
1232
- cv.width = size;
1233
- cv.height = size;
1234
- const g = cv.getContext('2d');
1235
- const grad = g.createRadialGradient(size / 2, size / 2, 0, size / 2, size / 2, size / 2);
1236
- grad.addColorStop(0, color);
1237
- grad.addColorStop(0.1, color);
1238
- grad.addColorStop(0.45, `${color}55`);
1239
- grad.addColorStop(1, 'rgba(0,0,0,0)');
1240
- g.fillStyle = grad;
1241
- g.fillRect(0, 0, size, size);
1242
- this.glow.set(kind, cv);
1243
- }
1244
- }
1245
-
1246
- /** 场景:星系尘埃、远景星、记忆星、星座连线,全部在世界坐标里。 */
1247
- buildScene() {
1248
- const W = this.w;
1249
- const H = this.h;
1250
- this.CX = W * 0.5;
1251
- this.CY = H * 0.52;
1252
- this.RCORE = Math.min(W, H) * 0.125;
1253
- this.RMAX = Math.min(W, H) * 0.46;
1254
- const RMAX = this.RMAX;
1255
- const RCORE = this.RCORE;
1256
- const rnd = seeded(20261105);
1257
- const gauss = () => (rnd() + rnd() + rnd() - 1.5) / 1.5;
1258
- const GOLD = Math.PI * (3 - Math.sqrt(5));
1259
-
1260
- // 分区
1261
- const tagCount = new Map();
1262
- for (const c of this.cards) for (const t of c.tags ?? []) tagCount.set(t, (tagCount.get(t) ?? 0) + 1);
1263
- const groups = new Map();
1264
- for (const c of this.cards) {
1265
- const strong = (c.tags ?? []).find((t) => (tagCount.get(t) ?? 0) >= 3);
1266
- const key = strong || GALAXY_KIND[c.kind] || '其他';
1267
- if (!groups.has(key)) groups.set(key, { name: key, cards: [] });
1268
- groups.get(key).cards.push(c);
1269
- }
1270
- const regions = [...groups.values()].sort((a, b) => b.cards.length - a.cards.length);
1271
- const RIN = RCORE * 2;
1272
-
1273
- regions.forEach((g, i) => {
1274
- const f = (i + 0.5) / regions.length;
1275
- const rc = RIN + (RMAX - RIN) * Math.pow(f, 0.92);
1276
- const tc = -Math.PI * 0.5 + f * Math.PI * 2 * 1.55 + 0.55 * Math.log(rc / RCORE);
1277
- g.x = Math.cos(tc) * rc;
1278
- g.y = Math.sin(tc) * rc;
1279
- g.br = 24 + Math.sqrt(g.cards.length) * 6.8;
1280
- });
1281
-
1282
- // 团间排斥(在盘面上)
1283
- for (let iter = 0; iter < 80; iter += 1) {
1284
- for (let i = 0; i < regions.length; i += 1) {
1285
- for (let j = i + 1; j < regions.length; j += 1) {
1286
- const a = regions[i];
1287
- const b = regions[j];
1288
- let dx = b.x - a.x;
1289
- let dy = b.y - a.y;
1290
- const d = Math.hypot(dx, dy) || 1;
1291
- const need = (a.br + b.br) * 1.16;
1292
- if (d < need) {
1293
- const push = (need - d) / 2;
1294
- dx /= d;
1295
- dy /= d;
1296
- a.x -= dx * push;
1297
- a.y -= dy * push;
1298
- b.x += dx * push;
1299
- b.y += dy * push;
1300
- }
1301
- }
1302
- }
1303
- for (const g of regions) {
1304
- const d = Math.hypot(g.x, g.y) || 1;
1305
- const lim = RMAX * 0.9;
1306
- if (d > lim) {
1307
- g.x = (g.x / d) * lim;
1308
- g.y = (g.y / d) * lim;
1309
- }
1310
- }
1311
- }
1312
-
1313
- // 记忆星
1314
- const now = Date.now();
1315
- this.nodes = [];
1316
- for (const g of regions) {
1317
- g.nodes = [];
1318
- g.cards.forEach((card, k) => {
1319
- const u = (k + 0.55) / g.cards.length;
1320
- const rr = g.br * Math.sqrt(u) * (0.9 + rnd() * 0.2);
1321
- const aa = k * GOLD + g.name.length * 1.3 + (rnd() - 0.5) * 0.45;
1322
- const weight = Number(card.weight) || 0.5;
1323
- const uses = (card.uses ?? 0) + (card.primedCount ?? 0);
1324
- const last = Date.parse(card.lastUsedAt ?? card.createdAt ?? '') || now;
1325
- const quiet = Math.max(0, (now - last) / 86_400_000);
1326
- const sizeBoost = 0.72 + 0.4 * Math.min(1, g.cards.length / 14);
1327
- const bright = (0.4 + 0.6 * Math.exp(-quiet / 45)) * (card.coldAt ? 0.42 : 1) * sizeBoost;
1328
- const node = {
1329
- card,
1330
- x: g.x + Math.cos(aa) * rr,
1331
- y: g.y + Math.sin(aa) * rr,
1332
- z: gauss() * RMAX * 0.05,
1333
- r: 1.6 + weight * 3.6 + Math.min(2.4, Math.sqrt(uses) * 0.7),
1334
- bright,
1335
- region: g,
1336
- };
1337
- g.nodes.push(node);
1338
- this.nodes.push(node);
1339
- });
1340
- g.hub = g.nodes.reduce((b, n) => (Number(n.card.weight) > Number(b.card.weight) ? n : b), g.nodes[0]);
1341
- g.color = GALAXY_TAG_COLOR[g.name] ?? GALAXY_COLOR[g.hub.card.kind] ?? '#c3ccd8';
1342
- g.rz = gauss() * RMAX * 0.04;
1343
- }
1344
-
1345
- // 星座连线:每个团连最近的两颗
1346
- this.links = [];
1347
- for (const g of regions) {
1348
- for (let i = 0; i < g.nodes.length; i += 1) {
1349
- const a = g.nodes[i];
1350
- g.nodes
1351
- .map((b, j) => ({ b, j, d: Math.hypot(b.x - a.x, b.y - a.y) }))
1352
- .filter((o) => o.j !== i)
1353
- .sort((x, y) => x.d - y.d)
1354
- .slice(0, 2)
1355
- .forEach(({ b, d }) => {
1356
- if (d <= g.br * 2.5) this.links.push([a, b, g.color]);
1357
- });
1358
- }
1359
- }
1360
-
1361
- // 超空间航道:不同星系之间、但共享标签的记忆连一条淡线
1362
- this.lanes = [];
1363
- const byTag = new Map();
1364
- for (const c of this.cards) for (const t of c.tags ?? []) {
1365
- if (!byTag.has(t)) byTag.set(t, []);
1366
- byTag.get(t).push(c);
1367
- }
1368
- const byId = new Map(this.nodes.map((n) => [n.card.id, n]));
1369
- for (const list of byTag.values()) {
1370
- if (list.length < 2 || list.length > 6) continue;
1371
- const head = byId.get(list[0].id);
1372
- if (!head) continue;
1373
- for (let i = 1; i < list.length; i += 1) {
1374
- const other = byId.get(list[i].id);
1375
- if (other && other.region !== head.region) this.lanes.push([head, other]);
1376
- }
1377
- }
1378
-
1379
- // 星系尘埃:散点按密度自然堆出旋臂,不画「虚线螺旋」
1380
- this.dust = [];
1381
- const arms = [
1382
- { base: -0.18, tone: '255,64,128', n: 1850, twist: Math.PI * 2.42 },
1383
- { base: Math.PI * 0.5 - 0.18, tone: '34,230,255', n: 1850, twist: Math.PI * 2.42 },
1384
- { base: Math.PI - 0.18, tone: '255,120,170', n: 1850, twist: Math.PI * 2.42 },
1385
- { base: Math.PI * 1.5 - 0.18, tone: '150,120,255', n: 1850, twist: Math.PI * 2.42 },
1386
- ];
1387
- for (const arm of arms) {
1388
- for (let i = 0; i < arm.n; i += 1) {
1389
- const s = Math.pow(rnd(), 0.75);
1390
- const r = RCORE * 0.55 + s * RMAX * 1.1;
1391
- const t = arm.base + arm.twist * s + gauss() * (0.03 + 0.085 * s);
1392
- const rr = r + gauss() * (9 + 38 * s);
1393
- // 沿弧长做亮度起伏,看起来有「结」和「空洞」
1394
- const knot = 0.5 + 0.5 * Math.sin(s * 19 + arm.base * 3);
1395
- const faint = arm.n === 800 ? 0.55 : 1;
1396
- this.dust.push({
1397
- x: Math.cos(t) * rr,
1398
- y: Math.sin(t) * rr,
1399
- z: gauss() * RMAX * 0.05,
1400
- size: 0.5 + Math.pow(rnd(), 2) * 1.7,
1401
- alpha: (0.12 + rnd() * 0.24) * knot * (1 - s * 0.3) * faint,
1402
- color: s < 0.2 ? '255,238,205' : arm.tone,
1403
- });
1404
- }
1405
- }
1406
-
1407
- // 清晰但很淡的旋臂骨架:让星尘形成真正的银河结构,而不是一团竖直光柱。
1408
- this.armTrails = arms.map((arm) => {
1409
- const points = [];
1410
- for (let i = 0; i <= 96; i += 1) {
1411
- const s = i / 96;
1412
- const r = RCORE * 0.62 + s * RMAX * 1.1;
1413
- const t = arm.base + arm.twist * s;
1414
- points.push({ x: Math.cos(t) * r, y: Math.sin(t) * r, z: gauss() * RMAX * 0.018 });
1415
- }
1416
- return { points, tone: arm.tone };
1417
- });
1418
-
1419
- // 亮星团:沿旋臂布置少量高亮节点,形成照片般的“恒星育婴室”。
1420
- this.clusters = [];
1421
- for (const arm of arms) {
1422
- for (let i = 0; i < 42; i += 1) {
1423
- const s = 0.08 + rnd() * 0.9;
1424
- const r = RCORE * 0.7 + s * RMAX * 1.08 + gauss() * (4 + s * 12);
1425
- const t = arm.base + arm.twist * s + gauss() * 0.035;
1426
- this.clusters.push({ x: Math.cos(t) * r, y: Math.sin(t) * r, z: gauss() * RMAX * 0.035, tone: arm.tone, size: 0.7 + rnd() * 1.6, alpha: 0.35 + rnd() * 0.5, phase: rnd() * Math.PI * 2 });
1427
- }
1428
- }
1429
-
1430
- // 旋臂薄雾:沿臂铺很淡的柔光,把散点连成气态盘面。
1431
- // 少了这一层,旋臂就只剩一串点,看起来像同心圆而不是银河。
1432
- this.haze = [];
1433
- for (const arm of arms) {
1434
- const steps = 44;
1435
- for (let i = 0; i < steps; i += 1) {
1436
- const s0 = (i + 0.5) / steps;
1437
- const r = RCORE * 0.5 + s0 * RMAX * 1.12;
1438
- const t = arm.base + arm.twist * s0;
1439
- this.haze.push({
1440
- x: Math.cos(t) * r + gauss() * 4,
1441
- y: Math.sin(t) * r + gauss() * 4,
1442
- z: gauss() * RMAX * 0.02,
1443
- radius: RMAX * (0.055 + 0.08 * s0),
1444
- color: s0 < 0.3 ? '255,236,198' : arm.tone,
1445
- alpha: (0.05 + 0.025 * Math.sin(s0 * 11)) * (1 - s0 * 0.22),
1446
- });
1447
- }
1448
- }
1449
-
1450
- // 远景星
1451
- this.far = [];
1452
- for (let i = 0; i < 420; i += 1) {
1453
- const a = rnd() * Math.PI * 2;
1454
- const rr = RMAX * (1.15 + rnd() * 1.1);
1455
- this.far.push({
1456
- x: Math.cos(a) * rr,
1457
- y: Math.sin(a) * rr,
1458
- z: (rnd() - 0.5) * RMAX * 1.4,
1459
- size: 0.4 + rnd() * 1.1,
1460
- alpha: 0.2 + rnd() * 0.5,
1083
+ function renderAtlas() {
1084
+ const list = filtered();
1085
+ const canvas = $('#orbit-galaxy');
1086
+ const empty = $('#galaxy-empty');
1087
+ canvas.hidden = orbitFailed;
1088
+ orbitAtlas?.setActive(!orbitFailed);
1089
+ if (!orbitAtlas && !orbitLoading && !orbitFailed) {
1090
+ orbitLoading = true;
1091
+ import('./starfield/atlas.js').then(({ createOrbitAtlas }) => {
1092
+ orbitAtlas = createOrbitAtlas(canvas, $('#orbit-label'), {
1093
+ kinds: KINDS,
1094
+ onSelect: id => selectCard(id, { trigger: canvas }),
1095
+ onZoom: scale => { $('#atlas-scale').textContent = `${scale.toFixed(2)}×`; },
1096
+ onLost: () => { orbitFailed = true; renderStage(); },
1461
1097
  });
1098
+ renderStage();
1099
+ }).catch(() => { orbitFailed = true; renderStage(); });
1100
+ }
1101
+ const nodes = [];
1102
+ for (const kind of KINDS) {
1103
+ const group = list.filter(card => card.kind === kind.id).sort((left,right) => left.createdAt.localeCompare(right.createdAt) || left.id.localeCompare(right.id));
1104
+ for (const card of group) {
1105
+ const last = Math.max(Date.parse(card.lastUsedAt) || 0, Date.parse(card.lastPrimedAt) || 0);
1106
+ nodes.push({ id: card.id, cluster: card.kind, title: card.text, tags: card.tags, weight: card.weight,
1107
+ days: last ? Math.max(0, Math.floor((Date.now()-last)/86400000)) : 3650, related: [...(card.supersedes ?? []), ...(card.summaryOf ?? [])] });
1462
1108
  }
1463
-
1464
- this.regions = regions;
1465
- this.kindCounts = {};
1466
- for (const c of this.cards) this.kindCounts[c.kind] = (this.kindCounts[c.kind] ?? 0) + 1;
1467
- this.projected = new Map();
1468
- this.step(true);
1469
- }
1470
-
1471
- /** 世界坐标 → 屏幕。先绕 Y 转,再绕 X 抬,最后做一点透视。 */
1472
- project(x, y, z) {
1473
- const cy = Math.cos(this.yaw);
1474
- const sy = Math.sin(this.yaw);
1475
- const X = x * cy + z * sy;
1476
- const Z1 = -x * sy + z * cy;
1477
- const cp = Math.cos(this.pitch);
1478
- const sp = Math.sin(this.pitch);
1479
- const Y = y * cp - Z1 * sp;
1480
- const Z = y * sp + Z1 * cp;
1481
- const depth = Z + GALAXY_CAM;
1482
- if (depth < 120) return null;
1483
- const k = (GALAXY_CAM / depth) * this.zoom;
1484
- return { x: this.CX + this.panX + X * k, y: this.CY + this.panY + Y * k, k, depth };
1485
- }
1486
-
1487
- step(once = false) {
1488
- const now = performance.now();
1489
- if (!this.dragging) {
1490
- // 惯性
1491
- if (Math.abs(this.vy) > 0.00002 || Math.abs(this.vp) > 0.00002) {
1492
- this.yaw += this.vy;
1493
- this.pitch = clampNum(this.pitch + this.vp, -1.35, 1.35);
1494
- this.vy *= 0.94;
1495
- this.vp *= 0.94;
1496
- } else if (now - this.lastInteract > 2600) {
1497
- // 静置时慢慢自转,像在轨观测
1498
- this.yaw += 0.0016;
1499
- }
1500
- }
1501
- this.draw();
1502
- this.tickCount += 1;
1503
- if (this.tickCount % 6 === 0) this.updateTelemetry();
1504
- if (!once) return;
1505
- }
1506
-
1507
- draw() {
1508
- const ctx = this.ctx;
1509
- const W = this.w;
1510
- const H = this.h;
1511
- if (!ctx) return;
1512
- ctx.clearRect(0, 0, W, H);
1513
-
1514
- // 深空底:中心银白、外围靛蓝,先铺一个很克制的宇宙底色。
1515
- const bg = ctx.createRadialGradient(this.CX, this.CY, 0, this.CX, this.CY, Math.max(W, H) * 0.78);
1516
- bg.addColorStop(0, '#15182a');
1517
- bg.addColorStop(0.18, '#0b1221');
1518
- bg.addColorStop(0.62, '#050914');
1519
- bg.addColorStop(1, '#010207');
1520
- ctx.fillStyle = bg;
1521
- ctx.fillRect(0, 0, W, H);
1522
-
1523
- // 倾斜的银河盘:细微的椭圆雾带,帮助眼睛感受到盘面方向。
1524
- ctx.save();
1525
- ctx.translate(this.CX + this.panX, this.CY + this.panY);
1526
- ctx.rotate(-0.16);
1527
- ctx.globalCompositeOperation = 'lighter';
1528
- const disk = ctx.createRadialGradient(0, 0, this.RCORE * 0.2, 0, 0, this.RMAX * 1.4);
1529
- disk.addColorStop(0, 'rgba(255,246,220,.18)');
1530
- disk.addColorStop(.22, 'rgba(140,190,255,.065)');
1531
- disk.addColorStop(.62, 'rgba(90,110,220,.026)');
1532
- disk.addColorStop(1, 'rgba(0,0,0,0)');
1533
- ctx.fillStyle = disk;
1534
- ctx.scale(1, .25);
1535
- ctx.beginPath();
1536
- ctx.arc(0, 0, this.RMAX * 1.35, 0, Math.PI * 2);
1537
- ctx.fill();
1538
- ctx.restore();
1539
- ctx.globalCompositeOperation = 'source-over';
1540
-
1541
- // 没有记忆时也要有星空底:尘埃和远景星照画,只是没有星点和标签
1542
-
1543
- // 每个区一团淡淡的星云
1544
- ctx.globalCompositeOperation = 'lighter';
1545
- for (const g of this.regions) {
1546
- const p = this.project(g.x, g.y, g.rz ?? 0);
1547
- if (!p) continue;
1548
- const radius = g.br * 1.9 * p.k;
1549
- const grd = ctx.createRadialGradient(p.x, p.y, 0, p.x, p.y, radius);
1550
- const hex = g.color;
1551
- grd.addColorStop(0, `${hex}16`);
1552
- grd.addColorStop(0.5, `${hex}08`);
1553
- grd.addColorStop(1, 'rgba(0,0,0,0)');
1554
- ctx.fillStyle = grd;
1555
- ctx.beginPath();
1556
- ctx.arc(p.x, p.y, radius, 0, Math.PI * 2);
1557
- ctx.fill();
1558
- }
1559
- ctx.globalCompositeOperation = 'source-over';
1560
-
1561
- // 旋臂骨架线:比单纯星点更能读出银河的盘面和旋转方向。
1562
- ctx.save();
1563
- ctx.globalCompositeOperation = 'lighter';
1564
- ctx.lineCap = 'round';
1565
- for (const arm of this.armTrails ?? []) {
1566
- let started = false;
1567
- for (const q of arm.points) {
1568
- const p = this.project(q.x, q.y, q.z);
1569
- if (!p) { started = false; continue; }
1570
- if (!started) { ctx.beginPath(); ctx.moveTo(p.x, p.y); started = true; }
1571
- else ctx.lineTo(p.x, p.y);
1572
- }
1573
- ctx.strokeStyle = `rgba(${arm.tone},.13)`;
1574
- ctx.lineWidth = Math.max(1, this.zoom * 1.3);
1575
- ctx.stroke();
1576
- }
1577
- ctx.restore();
1578
-
1579
- // 星系核心
1580
- const core = this.project(0, 0, 0);
1581
- if (core) {
1582
- ctx.globalCompositeOperation = 'lighter';
1583
- for (const [mul, alpha] of [
1584
- [3.2, 0.1],
1585
- [1.8, 0.22],
1586
- [0.9, 0.5],
1587
- ]) {
1588
- const rr = this.RCORE * mul * core.k;
1589
- const grd = ctx.createRadialGradient(core.x, core.y, 0, core.x, core.y, rr);
1590
- grd.addColorStop(0, `rgba(255,246,220,${alpha})`);
1591
- grd.addColorStop(0.45, `rgba(255,232,190,${alpha * 0.45})`);
1592
- grd.addColorStop(1, 'rgba(255,220,170,0)');
1593
- ctx.fillStyle = grd;
1594
- ctx.beginPath();
1595
- ctx.arc(core.x, core.y, rr, 0, Math.PI * 2);
1596
- ctx.fill();
1597
- }
1598
- ctx.globalAlpha = 0.9;
1599
- ctx.fillStyle = '#fffaf0';
1600
- ctx.beginPath();
1601
- ctx.arc(core.x, core.y, Math.max(2.5, this.RCORE * 0.12 * core.k), 0, Math.PI * 2);
1602
- ctx.fill();
1603
- ctx.globalAlpha = 1;
1604
- ctx.globalCompositeOperation = 'source-over';
1605
- }
1606
-
1607
- // 旋臂薄雾:柔光贴图叠出来的连续感,不是一个个硬圆
1608
- if (this.haze?.length) {
1609
- ctx.globalCompositeOperation = 'lighter';
1610
- for (const h of this.haze) {
1611
- const p = this.project(h.x, h.y, h.z);
1612
- if (!p) continue;
1613
- const sprite = this.hazeSprites?.get(h.color);
1614
- if (!sprite) continue;
1615
- const r = h.radius * p.k * 2.2;
1616
- ctx.globalAlpha = h.alpha * 2.4;
1617
- ctx.drawImage(sprite, p.x - r, p.y - r, r * 2, r * 2);
1618
- }
1619
- ctx.globalAlpha = 1;
1620
- ctx.globalCompositeOperation = 'source-over';
1621
- }
1622
-
1623
- // 沿旋臂的亮星团,亮度随时间轻微呼吸。
1624
- ctx.save();
1625
- ctx.globalCompositeOperation = 'lighter';
1626
- const pulseTime = performance.now() * 0.001;
1627
- for (const c of this.clusters ?? []) {
1628
- const p = this.project(c.x, c.y, c.z);
1629
- if (!p) continue;
1630
- const pulse = 0.82 + Math.sin(pulseTime * 0.7 + c.phase) * 0.18;
1631
- const r = Math.max(.8, c.size * p.k * 1.8);
1632
- ctx.globalAlpha = c.alpha * pulse;
1633
- ctx.fillStyle = `rgb(${c.tone})`;
1634
- ctx.beginPath(); ctx.arc(p.x, p.y, r, 0, Math.PI * 2); ctx.fill();
1635
- if (r > 1.5) {
1636
- ctx.globalAlpha = c.alpha * pulse * .2;
1637
- ctx.strokeStyle = `rgb(${c.tone})`;
1638
- ctx.beginPath(); ctx.moveTo(p.x - r * 4, p.y); ctx.lineTo(p.x + r * 4, p.y); ctx.moveTo(p.x, p.y - r * 4); ctx.lineTo(p.x, p.y + r * 4); ctx.stroke();
1639
- }
1640
- }
1641
- ctx.restore();
1642
-
1643
- // 收集并按深度排序(远的先画)
1644
- const items = [];
1645
- for (const d of this.dust) items.push({ z: d.z, kind: 'dust', d });
1646
- for (const s of this.far) items.push({ z: s.z, kind: 'far', d: s });
1647
- for (const n of this.nodes) items.push({ z: n.z, kind: 'node', d: n });
1648
- items.sort((a, b) => b.z - a.z);
1649
-
1650
- ctx.globalCompositeOperation = 'lighter';
1651
- let linkDrawn = false;
1652
- for (const it of items) {
1653
- const d = it.d;
1654
- if (it.kind === 'dust') {
1655
- const p = this.project(d.x, d.y, d.z);
1656
- if (!p) continue;
1657
- ctx.globalAlpha = d.alpha * Math.min(1.4, p.k);
1658
- ctx.fillStyle = `rgba(${d.color},1)`;
1659
- const sz = Math.max(0.5, d.size * p.k);
1660
- ctx.fillRect(p.x - sz / 2, p.y - sz / 2, sz, sz);
1661
- continue;
1662
- }
1663
- if (it.kind === 'far') {
1664
- const p = this.project(d.x, d.y, d.z);
1665
- if (!p) continue;
1666
- ctx.globalAlpha = d.alpha * 0.7;
1667
- ctx.fillStyle = '#d6e6ff';
1668
- const sz = Math.max(0.4, d.size * p.k * 0.9);
1669
- ctx.fillRect(p.x, p.y, sz, sz);
1670
- continue;
1671
- }
1672
- // 连线先于节点画(同一层里节点压线)
1673
- if (!linkDrawn) {
1674
- linkDrawn = true;
1675
- this.drawLinks();
1676
- }
1677
- const n = d;
1678
- const p = this.project(n.x, n.y, n.z);
1679
- if (!p) continue;
1680
- this.projected.set(n.card.id, { x: p.x, y: p.y, k: p.k });
1681
- const tone = GALAXY_COLOR[n.card.kind] ?? '#c3ccd8';
1682
- const core = Math.max(0.7, (0.8 + n.r * 0.32) * p.k);
1683
- // 光晕压到 3 倍核径以内、透明度很低:放大不会糊成一团
1684
- const halo = core * 3;
1685
- ctx.globalAlpha = 0.24 * n.bright;
1686
- const sprite = this.glow.get(n.card.kind) ?? this.glow.get('note');
1687
- ctx.drawImage(sprite, p.x - halo, p.y - halo, halo * 2, halo * 2);
1688
- // 锐利的星核
1689
- ctx.globalAlpha = Math.min(1, 0.72 + n.bright * 0.4);
1690
- ctx.fillStyle = '#fff';
1691
- ctx.beginPath();
1692
- ctx.arc(p.x, p.y, core * 0.5, 0, Math.PI * 2);
1693
- ctx.fill();
1694
- // 十字星芒,只给够亮的
1695
- if (core > 1.5) {
1696
- const arm = core * (3.6 + n.bright * 3);
1697
- ctx.globalAlpha = 0.2 * n.bright;
1698
- ctx.strokeStyle = tone;
1699
- ctx.lineWidth = 0.6;
1700
- ctx.beginPath();
1701
- ctx.moveTo(p.x - arm, p.y);
1702
- ctx.lineTo(p.x + arm, p.y);
1703
- ctx.moveTo(p.x, p.y - arm);
1704
- ctx.lineTo(p.x, p.y + arm);
1705
- ctx.stroke();
1706
- }
1707
- }
1708
- ctx.globalAlpha = 1;
1709
- ctx.globalCompositeOperation = 'source-over';
1710
-
1711
- // 选中 / 悬停
1712
- const mark = (n, alpha) => {
1713
- const p = this.projected.get(n.card.id);
1714
- if (!p) return;
1715
- ctx.strokeStyle = '#fff';
1716
- ctx.globalAlpha = alpha;
1717
- ctx.lineWidth = 1.4;
1718
- ctx.beginPath();
1719
- ctx.arc(p.x, p.y, Math.max(6, n.r * p.k) + 7, 0, Math.PI * 2);
1720
- ctx.stroke();
1721
- ctx.globalAlpha = 1;
1722
- };
1723
- const sel = this.nodes.find((n) => n.card.id === this.selected);
1724
- if (sel) mark(sel, 0.7);
1725
- const hov = this.nodes.find((n) => n.card.id === this.hover);
1726
- if (hov && hov !== sel) mark(hov, 0.45);
1727
-
1728
- this.drawLabels();
1729
- if (hov) this.drawTip(hov);
1730
- }
1731
-
1732
- drawLinks() {
1733
- const ctx = this.ctx;
1734
- ctx.lineWidth = 0.6;
1735
- for (const [a, b, color] of this.links) {
1736
- const pa = this.project(a.x, a.y, a.z);
1737
- const pb = this.project(b.x, b.y, b.z);
1738
- if (!pa || !pb) continue;
1739
- ctx.strokeStyle = color;
1740
- ctx.globalAlpha = 0.18 * Math.min(1, (pa.k + pb.k) / 2);
1741
- ctx.beginPath();
1742
- ctx.moveTo(pa.x, pa.y);
1743
- ctx.lineTo(pb.x, pb.y);
1744
- ctx.stroke();
1745
- }
1746
- ctx.globalAlpha = 1;
1747
- }
1748
-
1749
- /** 标签贴着自己那团的外缘;两个撞上了就往下错开,别叠字。 */
1750
- drawLabels() {
1751
- const ctx = this.ctx;
1752
- const placed = [];
1753
- ctx.textBaseline = 'middle';
1754
- ctx.font = '600 12px -apple-system, "PingFang SC", sans-serif';
1755
- const detail = this.zoom >= 0.9;
1756
- for (const g of this.regions) {
1757
- if (!detail && g.cards.length < 2) continue;
1758
- const p = this.project(g.x, g.y, g.rz ?? 0);
1759
- if (!p) continue;
1760
- const pts = g.nodes.map((n) => this.projected.get(n.card.id)).filter(Boolean);
1761
- if (!pts.length) continue;
1762
-
1763
- const far = Math.max(...pts.map((q) => Math.hypot(q.x - p.x, q.y - p.y)));
1764
- let dir = Math.atan2(p.y - this.CY, p.x - this.CX);
1765
- // 团就在正中间时方向没有意义,直接往右上放
1766
- if (far < 4 || Math.hypot(p.x - this.CX, p.y - this.CY) < 30) dir = -Math.PI / 3;
1767
- const text = `${g.name} · ${g.cards.length}`;
1768
- const w = ctx.measureText(text).width;
1769
-
1770
- let lx = p.x + Math.cos(dir) * (far + 20);
1771
- let ly = p.y + Math.sin(dir) * (far + 18);
1772
- lx = clampNum(lx, 20 + w / 2, this.w - 20 - w / 2);
1773
- ly = clampNum(ly, 74, this.h - 46);
1774
-
1775
- const box = { x: lx - w / 2 - 5, y: ly - 10, w: w + 10, h: 20 };
1776
- for (let pass = 0; pass < 16; pass += 1) {
1777
- const hit = placed.find(
1778
- (b) => box.x < b.x + b.w && box.x + box.w > b.x && box.y < b.y + b.h && box.y + box.h > b.y,
1779
- );
1780
- if (!hit) break;
1781
- box.y += 18;
1782
- if (box.y > this.h - 40) box.y = 66;
1783
- }
1784
- placed.push(box);
1785
- ly = box.y + 10;
1786
-
1787
- ctx.fillStyle = 'rgba(4,7,14,0.72)'
1788
- roundRect(ctx, box.x, box.y, box.w, box.h, 6);
1789
- ctx.fill();
1790
- ctx.textAlign = 'center';
1791
- ctx.globalAlpha = 0.96;
1792
- ctx.fillStyle = g.color;
1793
- ctx.shadowColor = g.color;
1794
- ctx.shadowBlur = 12;
1795
- ctx.fillText(text, lx, ly);
1796
- ctx.shadowBlur = 0;
1797
- ctx.globalAlpha = 1;
1798
- }
1799
- }
1800
-
1801
- drawTip(hov) {
1802
- const ctx = this.ctx;
1803
- const p = this.projected.get(hov.card.id);
1804
- if (!p) return;
1805
- const text = hov.card.text.length > 30 ? `${hov.card.text.slice(0, 30)}…` : hov.card.text;
1806
- ctx.font = '12px -apple-system, "PingFang SC", sans-serif';
1807
- const w = ctx.measureText(text).width;
1808
- const bx = clampNum(p.x - w / 2 - 10, 12, this.w - w - 34);
1809
- const by = clampNum(p.y - 46, 12, this.h - 44);
1810
- roundRect(ctx, bx, by, w + 20, 26, 8);
1811
- ctx.fillStyle = 'rgba(6,10,20,0.9)';
1812
- ctx.fill();
1813
- ctx.strokeStyle = 'rgba(140,255,240,0.35)';
1814
- ctx.lineWidth = 1;
1815
- ctx.stroke();
1816
- ctx.fillStyle = 'rgba(232,246,255,0.96)';
1817
- ctx.textAlign = 'left';
1818
- ctx.textBaseline = 'middle';
1819
- ctx.fillText(text, bx + 10, by + 13);
1820
- }
1821
-
1822
- updateTelemetry() {
1823
- const box = $('#galaxy-telemetry');
1824
- if (!box) return;
1825
- const deg = ((this.yaw * 180) / Math.PI) % 360;
1826
- box.textContent = `ROT ${((deg < 0 ? deg + 360 : deg) | 0).toString().padStart(3, '0')}° · PITCH ${((this.pitch * 180) / Math.PI).toFixed(0)}° · ZOOM ${this.zoom.toFixed(2)}×`;
1827
- }
1828
-
1829
- pick(cx, cy) {
1830
- const box = this.canvas.getBoundingClientRect();
1831
- const x = cx - box.left;
1832
- const y = cy - box.top;
1833
- let best = null;
1834
- let bestD = Infinity;
1835
- for (const n of this.nodes) {
1836
- const p = this.projected.get(n.card.id);
1837
- if (!p) continue;
1838
- const d = Math.hypot(p.x - x, p.y - y);
1839
- if (d < Math.max(11, n.r * p.k + 6) && d < bestD) {
1840
- best = n;
1841
- bestD = d;
1842
- }
1843
- }
1844
- return best;
1845
1109
  }
1846
- }
1847
-
1848
- let galaxy = null;
1849
-
1850
- function renderGalaxy() {
1851
- const canvas = $('#galaxy');
1852
- if (!canvas) return;
1853
- if (!galaxy) galaxy = new Galaxy(canvas);
1854
- galaxy.onSelect = (id) => selectCard(id);
1855
- galaxy.selected = S.selected;
1856
- const list = filtered();
1857
- $('#galaxy-empty').hidden = list.length > 0;
1858
- const signature = list.map((c) => c.id).join(',');
1859
- if (signature !== galaxy.signature) {
1860
- galaxy.signature = signature;
1861
- galaxy.setData(list);
1862
- }
1863
- galaxy.start();
1864
- renderGalaxyLegend();
1865
- }
1866
-
1867
- function renderGalaxyLegend() {
1868
- const host = $('#galaxy-legend');
1869
- if (!host || !galaxy) return;
1870
- const counts = galaxy.kindCounts ?? {};
1871
- const parts = Object.keys(GALAXY_KIND)
1872
- .filter((k) => counts[k])
1873
- .map(
1874
- (k) =>
1875
- `<span style="color:${GALAXY_COLOR[k]}"><i style="background:${GALAXY_COLOR[k]}"></i>${GALAXY_KIND[k]} ${counts[k]}</span>`,
1876
- );
1877
- // 独立成团的标签单独列一行:它已经从「自己」里分出去了,混在一起会让人数不上
1878
- for (const [tag, color] of Object.entries(GALAXY_TAG_COLOR)) {
1879
- const n = cards().filter((c) => (c.tags ?? []).includes(tag)).length;
1880
- if (n >= 3) parts.push(`<span style="color:${color}"><i style="background:${color}"></i>${tag} ${n}</span>`);
1881
- }
1882
- host.innerHTML = parts.join('');
1110
+ const signature = JSON.stringify(nodes);
1111
+ if (orbitAtlas && signature !== orbitSignature) { orbitAtlas.setCards(nodes); orbitSignature = signature; }
1112
+ orbitAtlas?.update(S.selected, Boolean(S.query));
1113
+ const ready = orbitAtlas && !orbitFailed;
1114
+ empty.hidden = Boolean(nodes.length && ready);
1115
+ empty.textContent = !ready ? (orbitFailed ? '此设备无法绘制星图,请切换「列表」。' : '正在加载记忆星河…') : nodes.length ? '' : '这里没有匹配的记忆,可清除筛选或新建记忆。';
1116
+ $('#atlas-count').textContent = `符合条件 ${list.length} 条 · 图上展示 ${ready ? nodes.length : 0} 条`;
1883
1117
  }
1884
1118
 
1885
1119
  let graph = null;
@@ -2096,51 +1330,39 @@ function renderTable() {
2096
1330
 
2097
1331
  /* ── 对话原文 ───────────────────────────────────────── */
2098
1332
 
2099
- function archiveBar() {
2100
- const retention = S.snap?.archive?.retention ?? 90;
2101
- const hint = S.withArchive
2102
- ? `连${retention ? ` ${retention} 天内` : '全部'}的归档一起搜`
2103
- : '只搜最近 7 天;更早的句子在归档里,勾上就能搜到';
2104
- return `<div class="turns-bar">
2105
- <label class="switch"><input type="checkbox" id="turns-archive" ${S.withArchive ? 'checked' : ''} /><span>含归档</span></label>
2106
- <span class="dim">${hint}</span>
2107
- </div>`;
2108
- }
1333
+ const chat = { owner: true, fish: false, rows: new Map(), before: undefined, fetching: false, revision: 0, error: '', selected: new Set(), removing: false };
2109
1334
 
2110
- function turnRow(t) {
2111
- return `<div class="turn">
2112
- <div><time>${fmtTime(t.ts).slice(6)}</time><div class="who">${esc(shortSender(t.sender))}</div></div>
2113
- <div class="msg">${highlight(t.text.slice(0, 600), S.query)}</div>
2114
- <button class="turn-del" data-cursor="${t.cursor}" title="删掉这条原文" aria-label="删掉这条原文">×</button>
2115
- </div>`;
1335
+ async function loadFish(older = false) {
1336
+ if (chat.fetching || !chat.fish || (older && !chat.before)) return;
1337
+ chat.fetching = true;
1338
+ const revision = chat.revision;
1339
+ chat.error = '';
1340
+ try {
1341
+ const page = await api('/api/turns/fish' + (older ? `?before=${chat.before}` : ''));
1342
+ if (revision !== chat.revision) return;
1343
+ if (older || chat.before === undefined) chat.before = page.before;
1344
+ for (const row of page.rows) chat.rows.set(row.cursor, { ...row, fish: true });
1345
+ } catch (err) { chat.error = `读取鱼的回复失败:${err.message}`; }
1346
+ finally { chat.fetching = false; if (S.view === 'turns') renderTurns(); }
2116
1347
  }
2117
1348
 
2118
- function bindArchiveToggle() {
2119
- const box = $('#turns-archive');
2120
- if (!box) return;
2121
- box.addEventListener('change', () => {
2122
- S.withArchive = box.checked;
2123
- localStorage.setItem('mcore-archive', S.withArchive ? '1' : '0');
2124
- S.archive = null;
2125
- S.archiveQ = '';
2126
- renderTurns();
2127
- if (S.withArchive && S.query) void ensureArchive(S.query);
2128
- });
1349
+ function turnRow(turn) {
1350
+ const role = turn.fish ? 'fish' : 'owner';
1351
+ const speaker = turn.fish ? '鱼' : '主人';
1352
+ const key = `${role}:${turn.cursor}`;
1353
+ const time = fmtTime(turn.ts).slice(6);
1354
+ return `<div class="chat-line ${role}"><label class="chat-check"><input type="checkbox" data-turn="${key}" aria-label="选择${speaker} ${time} 的发言" ${chat.selected.has(key) ? 'checked' : ''}></label><div class="chat-bubble"><header><b>${speaker}</b><time>${time}</time>${turn.fish ? '' : `<span>${esc(shortSender(turn.sender))}${turn.archive ? ' · 归档' : ''}</span>`}</header><p>${highlight(turn.text, S.query)}</p></div></div>`;
2129
1355
  }
2130
1356
 
2131
- /** 归档不进快照,勾了「含归档」且有搜索词时才按需拉一次。 */
2132
1357
  async function ensureArchive(query) {
2133
- if (!S.withArchive || !query) return;
2134
- if (S.archiveQ === query && S.archive) return;
1358
+ if (!chat.owner || !S.withArchive || !query || S.archiveQ === query) return;
2135
1359
  S.archiveQ = query;
2136
- S.archive = null;
2137
- const days = S.snap?.archive?.retention || 3650;
2138
1360
  try {
2139
- const rows = await api(`/api/archive?q=${encodeURIComponent(query)}&days=${days}&limit=40`);
2140
- if (S.query !== query) return;
2141
- S.archive = Array.isArray(rows) ? rows : [];
1361
+ const rows = await api(`/api/archive?q=${encodeURIComponent(query)}&days=${S.snap?.archive?.retention || 3650}&limit=40`);
1362
+ if (S.archiveQ !== query) return;
1363
+ S.archive = rows;
2142
1364
  } catch (err) {
2143
- if (S.query !== query) return;
1365
+ if (S.archiveQ !== query) return;
2144
1366
  S.archive = [];
2145
1367
  toast(`翻归档失败:${err.message}`, true);
2146
1368
  }
@@ -2149,85 +1371,63 @@ async function ensureArchive(query) {
2149
1371
 
2150
1372
  function renderTurns() {
2151
1373
  const host = $('#view-turns');
2152
- const toks = tokens(S.query);
2153
- const matched = (S.snap?.turns ?? []).filter((t) => matches(t.text, toks)).slice().reverse();
2154
- const wantArchive = S.withArchive && Boolean(S.query);
2155
- const archiving = wantArchive && (S.archiveQ !== S.query || S.archive === null);
2156
- const archived = wantArchive && S.archiveQ === S.query ? (S.archive ?? []) : [];
2157
-
2158
- if (!matched.length && !archived.length && !archiving) {
2159
- const dbg = S.snap?.state?.captureDebug;
2160
- let hint = '在插件设置里确认「存对话原文」是开的,聊几句就会出现在这里。';
2161
- if (dbg && dbg.scanned && !dbg.kept) {
2162
- const keys = (dbg.keys ?? []).map((k) => esc(k)).join('、') || '无';
2163
- hint = `上次扫了 ${dbg.scanned} 条外部事件,一条都没留下——被「算作对话的来源」白名单挡掉了(样例:${keys}),把这几个 key 加进设置里的正则就行。`;
2164
- }
2165
- const sub = S.query
2166
- ? S.withArchive
2167
- ? '归档里也没有。'
2168
- : '最近 7 天里没有。更早的句子在归档里,勾上「含归档」再搜一次。'
2169
- : hint;
2170
- host.innerHTML = `<div class="turns-wrap">${archiveBar()}<div class="empty"><p>${
2171
- S.query ? '没有匹配的对话。' : '还没有存下对话原文。'
2172
- }</p><p class="dim">${sub}</p></div></div>`;
2173
- bindArchiveToggle();
2174
- return;
2175
- }
2176
- // 全量拼 DOM 在 1000 条时会明显卡:先渲染最近 200 条,要更多再点。
2177
- // 分组按匹配总数算,组头显示「已显示/该天总数」,不让人误以为那天只有这么几句。
1374
+ const query = tokens(S.query);
1375
+ const archive = chat.owner && S.withArchive && Boolean(S.query);
1376
+ const ownerRows = chat.owner ? (S.snap?.turns ?? []).filter(turn => matches(turn.text, query)) : [];
1377
+ const combined = new Map(ownerRows.map(turn => [`owner:${turn.cursor}`, turn]));
1378
+ if (archive && S.archiveQ === S.query) for (const turn of S.archive ?? []) if (!combined.has(`owner:${turn.cursor}`)) combined.set(`owner:${turn.cursor}`, { ...turn, archive: true });
1379
+ if (chat.fish) for (const turn of chat.rows.values()) if (matches(turn.text, query)) combined.set(`fish:${turn.cursor}`, turn);
1380
+ const rows = [...combined.values()].sort((a,b) => Date.parse(b.ts) - Date.parse(a.ts) || b.cursor - a.cursor);
2178
1381
  const groups = new Map();
2179
- for (const t of matched) {
2180
- const key = dayKey(t.ts);
2181
- if (!groups.has(key)) groups.set(key, []);
2182
- groups.get(key).push(t);
2183
- }
2184
- const limit = Math.max(TURNS_PAGE, Math.min(S.turnsLimit ?? TURNS_PAGE, matched.length));
2185
- let remain = limit;
2186
- const parts = [];
2187
- for (const [key, items] of groups) {
2188
- if (remain <= 0) break;
2189
- const take = items.slice(0, remain);
2190
- remain -= take.length;
2191
- parts.push(`
2192
- <div class="day-group">
2193
- <div class="day-head"><b>${dayLabel(key)}</b><span>${
2194
- take.length === items.length ? `${items.length} 条` : `${take.length} / ${items.length} 条`
2195
- }</span></div>
2196
- ${take.map(turnRow).join('')}
2197
- </div>`);
2198
- }
2199
- // 归档命中按天分组:行里只显示时分,日期靠组头,避免窄列里塞不下「09-28 08:22」
2200
- const archGroups = new Map();
2201
- for (const t of archived) {
2202
- const key = dayKey(t.ts);
2203
- if (!archGroups.has(key)) archGroups.set(key, []);
2204
- archGroups.get(key).push(t);
2205
- }
2206
- const archiveBlock = archiving
2207
- ? '<div class="day-group archive"><div class="day-head"><b>更早 · 归档</b><span>搜索中…</span></div></div>'
2208
- : archGroups.size
2209
- ? `<div class="archive-head">更早 · 归档<span>${archived.length} 条</span></div>${[...archGroups.entries()]
2210
- .map(
2211
- ([key, items]) => `<div class="day-group archive">
2212
- <div class="day-head"><b>${dayLabel(key)}</b><span>${items.length} 条</span></div>
2213
- ${items.map((t) => turnRow(t)).join('')}
2214
- </div>`,
2215
- )
2216
- .join('')}`
2217
- : wantArchive
2218
- ? '<p class="turns-none dim">归档里没有匹配的句子。</p>'
2219
- : '';
2220
- const more =
2221
- matched.length > limit
2222
- ? `<button class="btn turns-more" id="turns-more">还有 ${matched.length - limit} 条 · 继续加载</button>`
2223
- : '';
2224
- host.innerHTML = `<div class="turns-wrap">${archiveBar()}${parts.join('')}${archiveBlock}${more}</div>`;
2225
- bindArchiveToggle();
2226
- $('#turns-more')?.addEventListener('click', () => {
2227
- S.turnsLimit = limit + TURNS_PAGE;
2228
- renderTurns();
2229
- });
2230
- if (archiving) void ensureArchive(S.query);
1382
+ for (const turn of rows.slice(0, S.turnsLimit)) {
1383
+ const day = dayKey(turn.ts);
1384
+ if (!groups.has(day)) groups.set(day, []);
1385
+ groups.get(day).push(turn);
1386
+ }
1387
+ const fetching = chat.fish && chat.fetching || archive && (S.archiveQ !== S.query || !S.archive);
1388
+ const empty = !chat.owner && !chat.fish ? '请选择要查看的说话人。' : fetching ? '正在读取对话…' : S.query ? '已加载的记录中没有匹配的对话。' : '还没有可回看的发言。';
1389
+ host.innerHTML = `<div class="turns-wrap"><div class="chat-tools">
1390
+ <label><input type="checkbox" id="turn-owner" ${chat.owner ? 'checked' : ''}>主人说的</label>
1391
+ <label><input type="checkbox" id="turn-fish" ${chat.fish ? 'checked' : ''}>鱼说的</label>
1392
+ <label><input type="checkbox" id="turns-archive" ${chat.owner && S.withArchive ? 'checked' : ''}>含主人归档</label>
1393
+ <button class="btn" id="turn-remove" ${!chat.selected.size || chat.removing ? 'disabled' : ''}>删除所选(${chat.selected.size})</button>
1394
+ <p class="chat-note">最近发言在上:鱼在左,主人在右。主人一侧显示已保存的原文;搜索时可勾选归档。鱼的回复只供回看。</p></div>
1395
+ ${[...groups].map(([day, items]) => {
1396
+ const fishCount = items.filter(turn => turn.fish).length;
1397
+ return `<section class="day-group"><div class="day-head"><b>${dayLabel(day)}</b><span>当前显示:${[chat.owner && `主人 ${items.length - fishCount} 条`, chat.fish && `鱼 ${fishCount} 条`].filter(Boolean).join(' · ')}</span></div>${items.map(turnRow).join('')}</section>`;
1398
+ }).join('') || `<p class="chat-empty" role="status">${empty}</p>`}
1399
+ ${rows.length > S.turnsLimit ? '<button class="btn" id="turns-more">显示更多对话</button>' : ''}
1400
+ ${chat.fish && chat.error ? `<p role="status">${esc(chat.error)}</p><button class="btn" id="fish-retry">重试读取</button>` : ''}
1401
+ ${chat.fish && chat.before ? `<button class="btn" id="fish-older" ${chat.fetching ? 'disabled' : ''}>加载更早的鱼回复</button>` : ''}</div>`;
1402
+ if (archive && S.archiveQ !== S.query) void ensureArchive(S.query);
1403
+ if (chat.fish && chat.before === undefined && !chat.fetching && !chat.error) void loadFish();
1404
+ }
1405
+
1406
+ async function removeSelectedTurns() {
1407
+ if (!chat.selected.size || chat.removing) return;
1408
+ const owner = [], fish = [];
1409
+ for (const key of chat.selected) { const [role, id] = key.split(':'); (role === 'fish' ? fish : owner).push(Number(id)); }
1410
+ const dialog = document.createElement('dialog');
1411
+ dialog.className = 'turn-dialog';
1412
+ dialog.setAttribute('aria-labelledby', 'turn-dialog-title');
1413
+ dialog.innerHTML = `<form method="dialog"><h2 id="turn-dialog-title">处理所选记录?</h2><p>从记忆核心删除 <b>${owner.length}</b> 条主人原文;从本页隐藏 <b>${fish.length}</b> 条鱼回复。</p><p>不删除宿主聊天记录,也不更改已生成的记忆卡。主人原文删除后不能在本页撤销。</p><footer><button class="btn" value="cancel" autofocus>取消</button><button class="btn" value="confirm">确认${owner.length ? '删除' : '隐藏'}</button></footer></form>`;
1414
+ document.body.append(dialog);
1415
+ dialog.showModal();
1416
+ await new Promise(resolve => dialog.addEventListener('close', resolve, { once: true }));
1417
+ const confirmed = dialog.returnValue === 'confirm';
1418
+ dialog.remove();
1419
+ if (!confirmed) { $('#turn-remove')?.focus(); return; }
1420
+ chat.removing = true;
1421
+ try {
1422
+ const result = await api('/api/turns/remove', { method: 'POST', body: JSON.stringify({ owner, fish }) });
1423
+ chat.revision++;
1424
+ chat.selected.clear();
1425
+ for (const id of fish) chat.rows.delete(id);
1426
+ S.archiveQ = ''; S.archive = null;
1427
+ await load();
1428
+ toast(`已删除 ${result.removed} 条主人原文,隐藏 ${result.hidden} 条鱼回复。`);
1429
+ } catch (err) { toast(`处理失败:${err.message}`, true); }
1430
+ finally { chat.removing = false; if (S.view === 'turns') renderTurns(); }
2231
1431
  }
2232
1432
 
2233
1433
  function shortSender(key) {
@@ -2314,16 +1514,17 @@ async function openDoc(path) {
2314
1514
  function renderInspector() {
2315
1515
  if (S.view === 'docs' && S.docSel) return renderDocInspector();
2316
1516
  const card = selectedCard();
2317
- if (!card) return renderOverview();
1517
+ if (!card) return atlasPage && libraryView() ? renderAtlasOverview() : renderOverview();
2318
1518
  const k = kindOf(card.kind);
2319
1519
  const related = relatedTo(card);
2320
1520
  el.inspBody.innerHTML = `
1521
+ ${atlasPage ? `<button class="atlas-return" id="atlas-return">← 返回${atlasFiltered() ? '搜索与筛选结果' : '观察记录'}</button>` : ''}
2321
1522
  <div class="insp-head">
2322
1523
  <span class="card-kind"><i style="background:var(${k.css})"></i>${k.label}</span>
2323
1524
  ${isRetired(card) ? '<span class="card-kind retired">已退休</span>' : ''}
2324
1525
  <div style="display:flex;gap:4px">
2325
1526
  ${isRetired(card) ? '' : `<button class="btn tiny ghost" id="btn-edit">${S.editing ? '取消' : '编辑'}</button>`}
2326
- <button class="icon-btn tiny" id="btn-copy" title="复制内容">⧉</button>
1527
+ <button class="icon-btn tiny" id="btn-copy" title="复制内容" aria-label="复制内容">⧉</button>
2327
1528
  <button class="icon-btn tiny" id="btn-insp-collapse" title="收起右栏 (I)" aria-label="收起右栏">›</button>
2328
1529
  </div>
2329
1530
  </div>
@@ -2348,9 +1549,11 @@ function renderInspector() {
2348
1549
  </div>`
2349
1550
  : `<div class="card-text">${highlight(card.text, S.query)}</div>`
2350
1551
  }
1552
+ ${atlasPage && !S.editing ? `<section class="atlas-source"><small>记录时附近的主人原话</small>${card.src?.text ? `<blockquote>${esc(card.src.text)}</blockquote>` : `<p>${card.src ? '未保存原话摘录。' : '这条记忆没有可核对的原文。'}</p>`}${card.src ? '<button class="btn tiny" id="atlas-context">核对原文上下文</button>' : ''}</section>` : ''}
2351
1553
  <div class="card-meta">
2352
1554
  <div class="kv"><span>记于</span><b>${fmtTime(card.createdAt)} · ${relative(card.createdAt)}</b></div>
2353
1555
  <div class="kv"><span>权重</span><b>${card.weight.toFixed(2)}</b></div>
1556
+ ${card.keepLongTerm === true ? '<div class="kv"><span>保留策略</span><b>长期保留 · 不进冷层</b></div>' : ''}
2354
1557
  <div class="kv"><span>来源</span><b>${esc(sourceLabel(card.source))}</b></div>
2355
1558
  <div class="kv"><span>被想起</span><b>${card.uses || 0} 次${card.lastUsedAt ? ` · 最近 ${relative(card.lastUsedAt)}` : ''}</b></div>
2356
1559
  ${card.dueAt ? `<div class="kv"><span>${card.done ? '已完成' : '截止'}</span><b>${fmtTime(card.dueAt)}</b></div>` : ''}
@@ -2358,13 +1561,16 @@ function renderInspector() {
2358
1561
  </div>
2359
1562
  <div class="card-actions">
2360
1563
  <button class="btn tiny" id="btn-ask">相关记忆</button>
1564
+ ${isRetired(card) ? '' : `<button class="btn tiny" id="btn-keep">${card.keepLongTerm === true ? '取消长期保留' : '长期保留'}</button>`}
1565
+ <details class="atlas-more"><summary>更多操作</summary>
2361
1566
  ${
2362
1567
  isRetired(card)
2363
1568
  ? `<button class="btn tiny" id="btn-restore">恢复这条</button>`
2364
1569
  : `<button class="btn tiny" id="btn-retire">退休</button>`
2365
1570
  }
2366
- <button class="btn tiny danger" id="btn-purge">彻底删除</button>
1571
+ <button class="btn tiny danger" id="btn-purge">彻底删除</button></details>
2367
1572
  </div>
1573
+ ${summarySourcesHtml(card)}
2368
1574
  ${lineageHtml(card)}
2369
1575
  ${
2370
1576
  related.length
@@ -2379,6 +1585,8 @@ function renderInspector() {
2379
1585
  }
2380
1586
  `;
2381
1587
 
1588
+ $('#atlas-return')?.addEventListener('click', () => selectCard(null));
1589
+ $('#atlas-context')?.addEventListener('click', () => openSourceContext(card));
2382
1590
  if (S.editing) {
2383
1591
  $('#edit-text').value = card.text;
2384
1592
  $('#edit-weight').addEventListener('input', (e) => {
@@ -2392,6 +1600,10 @@ function renderInspector() {
2392
1600
  S.editing = !S.editing;
2393
1601
  renderInspector();
2394
1602
  });
1603
+ $('#btn-keep')?.addEventListener('click', () => {
1604
+ const keepLongTerm = card.keepLongTerm !== true;
1605
+ void patchCard(card.id, { keepLongTerm }, keepLongTerm ? '已设为长期保留,不再沉到冷层' : '已取消长期保留,不会删除这条记忆');
1606
+ });
2395
1607
  $('#btn-copy').addEventListener('click', async () => {
2396
1608
  try {
2397
1609
  await navigator.clipboard.writeText(card.text);
@@ -2452,7 +1664,7 @@ function renderDocInspector() {
2452
1664
  <span class="card-kind">文件</span>
2453
1665
  <div style="display:flex;gap:4px">
2454
1666
  <button class="icon-btn tiny" id="btn-insp-collapse" title="收起右栏 (I)" aria-label="收起右栏">›</button>
2455
- <button class="icon-btn tiny" id="doc-close" title="关闭">×</button>
1667
+ <button class="icon-btn tiny" id="doc-close" title="关闭" aria-label="关闭文件详情">×</button>
2456
1668
  </div>
2457
1669
  </div>
2458
1670
  ${doc ? `<div class="card-text" style="max-height:60vh;overflow:auto;font-size:12.5px">${esc(doc.text)}</div>
@@ -2468,6 +1680,38 @@ function renderDocInspector() {
2468
1680
  });
2469
1681
  }
2470
1682
 
1683
+ async function openSourceContext(card) {
1684
+ openModal('记录时附近的主人原文', '<p role="status" id="source-reading">正在核对对应记录…</p>', '<button class="btn" id="source-return">返回记忆档案</button>');
1685
+ $('#source-return').onclick = closeModal;
1686
+ const pending = $('#source-reading');
1687
+ try {
1688
+ const rows = await api(`/api/source-context?card=${encodeURIComponent(card.id)}`);
1689
+ if (!pending.isConnected) return;
1690
+ el.modalBody.innerHTML = rows.length ? `<p class="dim">同一来源、同一天、前后半小时内已保存的主人发言。高亮的是写卡时附近的那句,并非整张卡的证明。</p>${rows.map(row => `<div class="atlas-quote ${row.cursor === card.src.cursor ? 'anchor' : ''}"><small>${fmtTime(row.ts)}${row.cursor === card.src.cursor ? ' · 对应原文' : ''}</small><p>${esc(row.text)}</p></div>`).join('')}` : '<p>对应原文已删除或不可用。没有用相似的聊天代替。</p>';
1691
+ } catch { if (pending.isConnected) pending.textContent = '暂时无法读取原文,请稍后重试。'; }
1692
+ }
1693
+
1694
+ function atlasFiltered() {
1695
+ return Boolean(S.query.trim() || S.kinds.size || S.scope || S.tag || S.minWeight || S.range !== 'all' || S.status !== 'active');
1696
+ }
1697
+
1698
+ function renderAtlasOverview() {
1699
+ const list = filtered();
1700
+ const searching = atlasFiltered();
1701
+ const section = (title, rows) => rows.length ? `<section class="atlas-group"><h3>${title}</h3>${rows.map(card => `<button data-atlas-card="${esc(card.id)}"><small>${kindOf(card.kind).label} · ${fmtTime(card.createdAt)}</small><span>${highlight(card.text, S.query)}</span></button>`).join('')}</section>` : '';
1702
+ const recent = [...list].sort((a,b) => b.createdAt.localeCompare(a.createdAt));
1703
+ const recallTime = card => Math.max(Date.parse(card.lastUsedAt) || 0, Date.parse(card.lastPrimedAt) || 0);
1704
+ const groups = searching ? section(`符合条件 · ${list.length} 条`, recent) : [
1705
+ section('长期保留', recent.filter(card => card.keepLongTerm).slice(0,1)),
1706
+ section('最近被想起', list.filter(recallTime).sort((a,b) => recallTime(b)-recallTime(a)).slice(0,2)),
1707
+ section('待完成的承诺', list.filter(card => card.kind === 'promise' && !card.done).sort((a,b) => (a.dueAt || '9999').localeCompare(b.dueAt || '9999')).slice(0,1)),
1708
+ section('最近记下', recent.slice(0,3)),
1709
+ ].join('');
1710
+ el.inspBody.innerHTML = `<div class="atlas-read-head"><small>FIELD JOURNAL</small><h2>${searching ? '搜索与筛选结果' : '观察记录'}</h2><button class="icon-btn" id="btn-insp-collapse" aria-label="收起阅读栏">›</button></div>${groups || '<p class="dim">暂无记录。可以换个关键词,或点「新记忆」。</p>'}`;
1711
+ bindInspCollapse();
1712
+ el.inspBody.querySelectorAll('[data-atlas-card]').forEach(button => button.onclick = () => selectCard(button.dataset.atlasCard));
1713
+ }
1714
+
2471
1715
  function renderOverview() {
2472
1716
  const st = S.snap?.stats;
2473
1717
  const list = filtered();
@@ -2538,14 +1782,14 @@ function renderOverview() {
2538
1782
  }
2539
1783
 
2540
1784
  function sourceLabel(src) {
2541
- return { tool: '聊天时写下', map: '记忆地图里手填', import: '旧插件导入', script: '系统' }[src] ?? src ?? '—';
1785
+ return { tool: '聊天时写下', map: '记忆地图里手填', import: '旧插件导入', script: '系统', review: '整理建议提炼' }[src] ?? src ?? '—';
2542
1786
  }
2543
1787
 
2544
1788
  /* 表格里只放得下短名,完整语义留给 title */
2545
1789
  function sourceShort(src) {
2546
1790
  if (!src) return '—';
2547
1791
  if (src.startsWith('import:')) return `导入·${src.slice(7).replace(/^(private-|memory-)/, '')}`;
2548
- return { tool: '聊天', map: '手填', script: '系统' }[src] ?? src;
1792
+ return { tool: '聊天', map: '手填', script: '系统', review: '提炼' }[src] ?? src;
2549
1793
  }
2550
1794
 
2551
1795
  function toLocalInput(iso) {
@@ -2581,6 +1825,17 @@ function relatedTo(card) {
2581
1825
  return scored.sort((a, b) => b.score - a.score).slice(0, 4);
2582
1826
  }
2583
1827
 
1828
+ function summarySourcesHtml(card) {
1829
+ if (!Array.isArray(card.summaryOf) || !card.summaryOf.length) return '';
1830
+ const byId = new Map(cards().map((item) => [item.id, item]));
1831
+ return `<div class="lineage"><h3>提炼所依据的原卡</h3>${card.summaryOf.map((id) => {
1832
+ const item = byId.get(id);
1833
+ return item
1834
+ ? `<button class="related-item" data-goto="${esc(id)}">${esc(item.text.slice(0, 70))}${item.text.length > 70 ? '…' : ''}</button>`
1835
+ : `<p class="lineage-note">原卡不可用 · ${esc(id.slice(0, 8))}</p>`;
1836
+ }).join('')}</div>`;
1837
+ }
1838
+
2584
1839
  function lineageHtml(card) {
2585
1840
  const before = (card.supersedes ?? [])
2586
1841
  .map((id) => cards().find((c) => c.id === id))
@@ -2628,6 +1883,7 @@ async function saveCard(card) {
2628
1883
  async function patchCard(id, patch, msg) {
2629
1884
  try {
2630
1885
  await api(`/api/cards/${id}`, { method: 'PATCH', body: JSON.stringify(patch) });
1886
+ if (typeof patch.keepLongTerm === 'boolean') S.health = null;
2631
1887
  toast(msg);
2632
1888
  await load();
2633
1889
  } catch (err) {
@@ -2637,6 +1893,143 @@ async function patchCard(id, patch, msg) {
2637
1893
 
2638
1894
  /* ── 体检 ───────────────────────────────────────────── */
2639
1895
 
1896
+ async function openChillPreview(trigger) {
1897
+ const limit = S.health?.chill.reviewLimit || 0;
1898
+ trigger.disabled = true;
1899
+ try {
1900
+ const rows = await api('/api/chill');
1901
+ if (S.view !== 'health' || !el.modal.hidden) return;
1902
+ if (!rows.length) {
1903
+ S.health = null;
1904
+ await ensureHealth();
1905
+ return toast('现在没有符合冷层条件的记忆');
1906
+ }
1907
+ openModal('冷层整理预览', `
1908
+ <p class="maint-note">这里列出活动少、权重低且久未被想起的记忆。勾选后才会移入冷层,不删除,搜索仍可找到。</p>
1909
+ <p class="maint-note" id="chill-review-status" role="status">${limit ? `可选最多 ${limit} 张交给本机模型评估。只发送勾选卡片的正文、类型、权重和未活动天数,不发送对话原文。` : '如需模型建议,请先在设置里填写本机 Ollama 模型。'}</p>
1910
+ <div class="maint-group">${rows.map((card) => `<label class="maint-row">
1911
+ <span><b>${esc(kindOf(card.kind).label)}</b> · ${esc(card.text)}<br>
1912
+ <span class="maint-meta">权重 ${card.weight.toFixed(2)} · ${card.idleDays} 天未活动 · 最近活动 ${fmtTime(card.lastActivityAt)}</span></span>
1913
+ <input type="checkbox" name="chill-id" value="${esc(card.id)}">
1914
+ </label>`).join('')}</div>`,
1915
+ `<button class="btn" id="chill-cancel">取消</button>${limit ? '<button class="btn" id="chill-review" disabled>本机评估</button>' : ''}<button class="btn" id="chill-confirm" disabled>移入冷层(0)</button>`);
1916
+ const selected = () => [...el.modalBody.querySelectorAll('input[name="chill-id"]:checked')].map((input) => input.value);
1917
+ const submit = $('#chill-confirm');
1918
+ const review = $('#chill-review');
1919
+ const status = $('#chill-review-status');
1920
+ let busy = false;
1921
+ const sync = () => {
1922
+ const n = selected().length;
1923
+ submit.disabled = busy || !n;
1924
+ submit.textContent = `移入冷层(${n})`;
1925
+ if (review) review.disabled = busy || !n || n > limit;
1926
+ };
1927
+ el.modalBody.querySelector('.maint-group').addEventListener('change', sync);
1928
+ $('#chill-cancel').addEventListener('click', closeModal);
1929
+ review?.addEventListener('click', async () => {
1930
+ const ids = selected();
1931
+ const submitted = ids.map((id) => rows.find((row) => row.id === id));
1932
+ busy = true;
1933
+ sync();
1934
+ status.textContent = `正在用本机模型评估 ${ids.length} 张记忆…此操作不修改卡片。`;
1935
+ try {
1936
+ const draft = await api('/api/chill/review', { method: 'POST', body: JSON.stringify({ refs: submitted.map(({ id, stamp }) => ({ id, stamp })) }) });
1937
+ if (!el.modal.hidden && status.isConnected) openChillSuggestions(draft, submitted);
1938
+ } catch (err) {
1939
+ status.textContent = err.message;
1940
+ } finally {
1941
+ busy = false;
1942
+ if (!el.modal.hidden && status.isConnected) sync();
1943
+ }
1944
+ });
1945
+ submit.addEventListener('click', async () => {
1946
+ const ids = selected();
1947
+ if (!ids.length) return;
1948
+ closeModal();
1949
+ try {
1950
+ const { changed } = await api('/api/chill', { method: 'POST', body: JSON.stringify({ ids }) });
1951
+ S.health = null;
1952
+ await load();
1953
+ toast(`${changed} 张已沉到冷层${changed < ids.length ? `,${ids.length - changed} 张已不符合条件,未移动` : ''}`);
1954
+ } catch (err) {
1955
+ toast(`整理失败:${err.message}`, true);
1956
+ }
1957
+ });
1958
+ } catch (err) {
1959
+ toast(`预览读不出来:${err.message}`, true);
1960
+ } finally {
1961
+ trigger.disabled = false;
1962
+ }
1963
+ }
1964
+
1965
+ function openChillSuggestions(draft, rows) {
1966
+ const labels = { keep: '长期保留', summarize: '新建摘要', chill: '移入冷层', unsure: '拿不准 · 不操作' };
1967
+ openModal('整理建议', `
1968
+ <p class="maint-note">建议尚未应用。请核对理由和原卡,仅勾选你认可的操作。新建摘要不会覆盖、退休或移动原卡。</p>
1969
+ <p id="review-apply-status" class="maint-note" role="status"></p>
1970
+ <div class="maint-group">${draft.suggestions.map((item, index) => `<label class="maint-row">
1971
+ <span><b>${esc(labels[item.action])}</b> · ${esc(item.reason)}
1972
+ ${item.sources.map((number) => `<br><span class="maint-meta">原卡 ${number}:</span>${esc(rows[number - 1].text)}`).join('')}
1973
+ ${item.summary ? `<br><b>摘要:</b>${esc(item.summary)}` : ''}</span>
1974
+ ${item.action === 'unsure' ? '' : `<input type="checkbox" name="review-action" value="${index}">`}
1975
+ </label>`).join('')}</div>`,
1976
+ '<button class="btn" id="review-dismiss">关闭</button><button class="btn primary" id="review-apply" disabled>应用所选(0)</button>');
1977
+ const selected = () => [...el.modalBody.querySelectorAll('input[name="review-action"]:checked')].map((input) => Number(input.value));
1978
+ const apply = $('#review-apply');
1979
+ const status = $('#review-apply-status');
1980
+ let busy = false;
1981
+ const sync = () => {
1982
+ const count = selected().length;
1983
+ apply.disabled = busy || !count;
1984
+ apply.textContent = `应用所选(${count})`;
1985
+ };
1986
+ el.modalBody.querySelector('.maint-group').addEventListener('change', sync);
1987
+ $('#review-dismiss').addEventListener('click', closeModal);
1988
+ apply.addEventListener('click', async () => {
1989
+ busy = true;
1990
+ sync();
1991
+ try {
1992
+ const result = await api('/api/chill/review/apply', { method: 'POST', body: JSON.stringify({ id: draft.id, selected: selected() }) });
1993
+ if (status.isConnected) closeModal();
1994
+ S.health = null;
1995
+ await load();
1996
+ toast(`长期保留 ${result.kept} 张,归冷 ${result.chilled} 张,新建 ${result.summarized} 张摘要${result.duplicate ? `,跳过 ${result.duplicate} 条重复摘要` : ''}`);
1997
+ } catch (err) {
1998
+ status.textContent = err.message;
1999
+ } finally {
2000
+ busy = false;
2001
+ if (!el.modal.hidden && status.isConnected) sync();
2002
+ }
2003
+ });
2004
+ }
2005
+
2006
+ async function openKeepSuggestions(trigger) {
2007
+ trigger.disabled = true;
2008
+ try {
2009
+ const rows = await api('/api/keep-suggestions');
2010
+ if (S.view !== 'health' || !el.modal.hidden) return;
2011
+ trigger.disabled = false;
2012
+ trigger.focus();
2013
+ renderKeepSuggestions(rows);
2014
+ } catch (err) {
2015
+ toast(`建议读不出来:${err.message}`, true);
2016
+ } finally {
2017
+ trigger.disabled = false;
2018
+ }
2019
+ }
2020
+
2021
+ function renderKeepSuggestions(rows) {
2022
+ const empty = '<p>还没有。她在自我意识里想到重要的事,才会记一笔。</p>';
2023
+ openModal('她自己保留的记忆', `
2024
+ <p class="maint-note">她独处时觉得重要的经历,已经自己标成长期保留。不改变权重,也不删卡;要撤销就到卡片详情里取消「长期保留」。</p>
2025
+ ${rows.length ? `<div class="maint-group">${rows.map((row, index) => `<div class="maint-row keep-suggestion">
2026
+ <div class="keep-suggestion-copy"><b>记忆 ${index + 1}</b> · ${esc(fmtTime(row.ts))}<br>
2027
+ ${esc(row.text)}<br><b>她的理由:</b>${esc(row.reason)}</div>
2028
+ </div>`).join('')}</div>` : empty}`,
2029
+ '<button class="btn" id="keep-close" type="button">关闭</button>');
2030
+ $('#keep-close').addEventListener('click', closeModal);
2031
+ }
2032
+
2640
2033
  async function ensureHealth() {
2641
2034
  if (S.health) return;
2642
2035
  try {
@@ -2747,19 +2140,24 @@ function renderHealth() {
2747
2140
 
2748
2141
  <section class="h-block">
2749
2142
  <h3>冷层
2750
- ${h.chill.eligible ? `<button class="btn tiny" id="h-chill">沉下去(${h.chill.eligible})</button>` : ''}
2143
+ ${h.chill.eligible ? `<button class="btn tiny" id="h-chill">预览整理(${h.chill.eligible})</button>` : ''}
2751
2144
  ${h.chill.cold ? `<button class="btn tiny" id="h-warm">全部回暖(${h.chill.cold})</button>` : ''}
2752
2145
  </h3>
2753
2146
  <div class="h-line">
2754
2147
  <span>冷层里 <b>${h.chill.cold}</b> 条</span>
2755
2148
  <span class="dim">${
2756
2149
  h.chill.afterDays
2757
- ? `超过 ${h.chill.afterDays} 天没被想起的低权重记忆会沉下去;搜索仍然找得到,不删除`
2150
+ ? `超过 ${h.chill.afterDays} 天没被想起的低权重记忆可沉到冷层;长期保留的不沉,搜索仍找得到,不删除`
2758
2151
  : '自动分层已关闭(chillAfterDays = 0)'
2759
2152
  }</span>
2760
2153
  </div>
2761
2154
  </section>
2762
2155
 
2156
+ <section class="h-block">
2157
+ <h3>她自己保留的记忆 <button class="btn tiny" id="h-keep-suggestions">查看记录</button></h3>
2158
+ <p class="maint-note">独处时她觉得某段经历重要,就直接标成长期保留,不再等你确认。</p>
2159
+ </section>
2160
+
2763
2161
  <section class="h-block">
2764
2162
  <h3>从没被想起的卡 ${h.cards.dead ? `<button class="btn tiny" id="h-retire-dead">全部退休(${h.cards.dead})</button>` : ''}</h3>
2765
2163
  ${
@@ -2773,19 +2171,9 @@ function renderHealth() {
2773
2171
  const fix = $('#h-fix-promises');
2774
2172
  if (fix) fix.addEventListener('click', () => void openMaintenance('promises'));
2775
2173
  const chillBtn = $('#h-chill');
2776
- if (chillBtn) {
2777
- chillBtn.addEventListener('click', async () => {
2778
- if (!confirm(`把 ${h.chill.eligible} 张很久没被想起的低权重记忆沉到冷层?不删除,随时能回暖。`)) return;
2779
- try {
2780
- const res = await api('/api/chill', { method: 'POST', body: '{}' });
2781
- S.health = null;
2782
- await load();
2783
- toast(`${res?.changed ?? 0} 张已沉到冷层`);
2784
- } catch (err) {
2785
- toast(`失败:${err.message}`, true);
2786
- }
2787
- });
2788
- }
2174
+ if (chillBtn) chillBtn.addEventListener('click', () => void openChillPreview(chillBtn));
2175
+ const keepBtn = $('#h-keep-suggestions');
2176
+ keepBtn.addEventListener('click', () => void openKeepSuggestions(keepBtn));
2789
2177
  const warmBtn = $('#h-warm');
2790
2178
  if (warmBtn) {
2791
2179
  warmBtn.addEventListener('click', async () => {
@@ -2821,19 +2209,34 @@ function renderHealth() {
2821
2209
  /* ── 视图切换与渲染 ─────────────────────────────────── */
2822
2210
 
2823
2211
  function renderStage() {
2824
- localStorage.setItem('mcore-view2', S.view);
2825
- if (S.view !== 'galaxy') galaxy?.stop();
2212
+ if (atlasPage) {
2213
+ if (S.view !== 'galaxy') orbitAtlas?.setActive(false);
2214
+ document.body.toggleAttribute('data-immersive', immersiveAtlas());
2215
+ document.body.dataset.area = libraryView() ? 'library' : S.view;
2216
+ el.search.placeholder = S.view === 'turns' ? '搜索对话原文…' : S.view === 'docs' ? '搜索文件名…' : '搜索记忆或标签…';
2217
+ el.search.setAttribute('aria-label', el.search.placeholder);
2218
+ if (libraryView()) {
2219
+ $('#atlas-mode').value = S.view;
2220
+ $('#atlas-kinds').innerHTML = [{id:'',label:'全部'}, ...KINDS].map(kind => `<button type="button" data-atlas-kind="${kind.id}" aria-pressed="${kind.id ? S.kinds.has(kind.id) : !S.kinds.size}">${kind.id ? `<i style="--dot:var(${kind.css})"></i>` : ''}${kind.label}</button>`).join('');
2221
+ }
2222
+ }
2826
2223
  for (const v of VIEWS) {
2827
2224
  const el = $(`#view-${v}`);
2828
2225
  if (el) el.hidden = S.view !== v;
2829
2226
  }
2830
- document.querySelectorAll('#tabs .tab').forEach((t) => t.classList.toggle('active', t.dataset.view === S.view));
2227
+ document.querySelectorAll('#tabs .tab').forEach((t) => {
2228
+ const active = t.dataset.view === (atlasPage && libraryView() ? 'galaxy' : S.view);
2229
+ t.classList.toggle('active', active);
2230
+ t.setAttribute('aria-selected', String(active));
2231
+ if (t.dataset.view === 'galaxy') t.setAttribute('aria-controls', `view-${libraryView() ? S.view : 'galaxy'}`);
2232
+ t.tabIndex = active ? 0 : -1;
2233
+ });
2831
2234
 
2832
2235
  if (S.view === 'graph') renderGraph();
2833
2236
  if (S.view === 'timeline') renderTimeline();
2834
2237
  if (S.view === 'table') renderTable();
2835
2238
  if (S.view === 'turns') renderTurns();
2836
- if (S.view === 'galaxy') renderGalaxy();
2239
+ if (immersiveAtlas()) renderAtlas();
2837
2240
  if (S.view === 'docs') {
2838
2241
  renderDocs();
2839
2242
  ensureDocs();
@@ -2881,9 +2284,32 @@ function move(delta) {
2881
2284
  }
2882
2285
 
2883
2286
  document.addEventListener('keydown', (event) => {
2287
+ if (!el.modal.hidden) {
2288
+ if (event.key === 'Escape') {
2289
+ event.preventDefault();
2290
+ closeModal();
2291
+ } else if (event.key === 'Tab') {
2292
+ trapModalFocus(event);
2293
+ }
2294
+ return;
2295
+ }
2884
2296
  const typing = /^(INPUT|TEXTAREA|SELECT)$/.test(document.activeElement?.tagName ?? '');
2885
2297
  if (event.key === 'Escape') {
2886
- if (!el.modal.hidden) return closeModal();
2298
+ if (document.body.dataset.filters === 'open') {
2299
+ event.preventDefault();
2300
+ setFiltersOpen(false);
2301
+ return;
2302
+ }
2303
+ if (immersiveAtlas() && !inspectorCollapsed()) {
2304
+ event.preventDefault();
2305
+ closeStoryInspector();
2306
+ return;
2307
+ }
2308
+ if (narrowInspector.matches && document.body.dataset.insp === 'on') {
2309
+ event.preventDefault();
2310
+ setInspCollapsed(true);
2311
+ return;
2312
+ }
2887
2313
  if (typing) {
2888
2314
  document.activeElement.blur();
2889
2315
  return;
@@ -2901,6 +2327,8 @@ document.addEventListener('keydown', (event) => {
2901
2327
  return;
2902
2328
  }
2903
2329
  if (typing) return;
2330
+ if (immersiveAtlas() && el.inspector.contains(event.target) && (event.key.startsWith('Arrow') || event.key === 'Enter')) return;
2331
+ if (immersiveAtlas() && event.key === 'Enter' && event.target.closest('button')) return;
2904
2332
  if (event.key === '/' || (event.key === 'k' && (event.metaKey || event.ctrlKey))) {
2905
2333
  event.preventDefault();
2906
2334
  el.search.focus();
@@ -2934,9 +2362,7 @@ document.addEventListener('keydown', (event) => {
2934
2362
  }
2935
2363
  if (event.key === 'r') return load();
2936
2364
  if (event.key === 'i') {
2937
- setInspCollapsed(!S.inspCollapsed);
2938
- if (!S.inspCollapsed) renderInspector();
2939
- return;
2365
+ return toggleInspector();
2940
2366
  }
2941
2367
  if (VIEWS.map((_, i) => String(i + 1)).includes(event.key)) {
2942
2368
  const views = VIEWS;
@@ -2949,6 +2375,12 @@ document.addEventListener('keydown', (event) => {
2949
2375
  // 输入框状态立刻更新(清除按钮要跟手),重绘压到 150ms 后。
2950
2376
  let searchTimer = 0;
2951
2377
  el.search.addEventListener('input', () => {
2378
+ if (atlasPage && libraryView()) {
2379
+ S.selected = null;
2380
+ S.editing = false;
2381
+ if (!immersiveAtlas() && (el.search.value.trim() || !narrowInspector.matches)) setInspCollapsed(false);
2382
+ }
2383
+ chat.selected.clear();
2952
2384
  S.query = el.search.value;
2953
2385
  el.searchClear.hidden = !S.query;
2954
2386
  S.turnsLimit = TURNS_PAGE;
@@ -2958,6 +2390,7 @@ el.search.addEventListener('input', () => {
2958
2390
  searchTimer = setTimeout(() => render(), 150);
2959
2391
  });
2960
2392
  el.searchClear.addEventListener('click', () => {
2393
+ chat.selected.clear();
2961
2394
  S.query = '';
2962
2395
  el.search.value = '';
2963
2396
  el.searchClear.hidden = true;
@@ -2968,11 +2401,36 @@ el.searchClear.addEventListener('click', () => {
2968
2401
  render();
2969
2402
  });
2970
2403
 
2971
- document.querySelectorAll('#tabs .tab').forEach((tab) => {
2404
+ const areaQueries = new Map();
2405
+ const tabs = [...document.querySelectorAll('#tabs .tab')];
2406
+ tabs.forEach((tab) => {
2972
2407
  tab.addEventListener('click', () => {
2408
+ const previous = libraryView() ? 'library' : S.view;
2409
+ areaQueries.set(previous, S.query);
2973
2410
  S.view = tab.dataset.view;
2411
+ const area = libraryView() ? 'library' : S.view;
2412
+ if (area !== previous) {
2413
+ S.query = areaQueries.get(area) ?? '';
2414
+ el.search.value = S.query;
2415
+ el.searchClear.hidden = !S.query;
2416
+ S.selected = null;
2417
+ S.editing = false;
2418
+ chat.selected.clear();
2419
+ }
2420
+ if (atlasPage) { setFiltersOpen(false); if (narrowInspector.matches) setInspCollapsed(true); }
2974
2421
  render();
2975
2422
  });
2423
+ tab.addEventListener('keydown', (event) => {
2424
+ const keys = ['ArrowLeft', 'ArrowRight', 'Home', 'End'];
2425
+ if (!keys.includes(event.key)) return;
2426
+ event.preventDefault();
2427
+ const visibleTabs = tabs.filter(button => button.getClientRects().length);
2428
+ const index = visibleTabs.indexOf(tab);
2429
+ const nextIndex =
2430
+ event.key === 'Home' ? 0 : event.key === 'End' ? visibleTabs.length - 1 : (index + (event.key === 'ArrowRight' ? 1 : -1) + visibleTabs.length) % visibleTabs.length;
2431
+ visibleTabs[nextIndex].focus();
2432
+ visibleTabs[nextIndex].click();
2433
+ });
2976
2434
  });
2977
2435
 
2978
2436
  $('#view-timeline').addEventListener('click', (event) => {
@@ -2981,23 +2439,31 @@ $('#view-timeline').addEventListener('click', (event) => {
2981
2439
  selectCard(item.dataset.id);
2982
2440
  });
2983
2441
 
2984
- // 原文单条删除:按钮随行渲染,用事件委托,重绘后不用重新绑定
2985
- $('#view-turns').addEventListener('click', async (event) => {
2986
- const btn = event.target.closest('.turn-del');
2987
- if (!btn) return;
2988
- const cursor = Number(btn.dataset.cursor);
2989
- if (!Number.isFinite(cursor)) return;
2990
- if (!confirm('删掉这条原文?只删本地这一行,对方那边不受影响。删了补不回来。')) return;
2991
- try {
2992
- const res = await api(`/api/turns/${cursor}`, { method: 'DELETE', body: '{}' });
2993
- if (!res?.removed) return toast('没找到这条', true);
2994
- S.archiveQ = '';
2995
- S.archive = null;
2996
- await load();
2997
- toast('已删掉');
2998
- } catch (err) {
2999
- toast(`删除失败:${err.message}`, true);
2442
+ $('#view-turns').addEventListener('change', event => {
2443
+ const input = event.target;
2444
+ if (input.dataset.turn) {
2445
+ if (input.checked) chat.selected.add(input.dataset.turn); else chat.selected.delete(input.dataset.turn);
2446
+ const button = $('#turn-remove');
2447
+ button.textContent = `删除所选(${chat.selected.size})`;
2448
+ button.disabled = !chat.selected.size || chat.removing;
2449
+ return;
3000
2450
  }
2451
+ if (input.id === 'turn-owner') chat.owner = input.checked;
2452
+ else if (input.id === 'turn-fish') chat.fish = input.checked;
2453
+ else if (input.id === 'turns-archive') {
2454
+ S.withArchive = input.checked;
2455
+ if (input.checked) chat.owner = true;
2456
+ localStorage.setItem('mcore-archive', S.withArchive ? '1' : '0');
2457
+ S.archiveQ = ''; S.archive = null;
2458
+ } else return;
2459
+ chat.selected.clear(); S.turnsLimit = TURNS_PAGE;
2460
+ renderTurns(); document.getElementById(input.id)?.focus();
2461
+ });
2462
+ $('#view-turns').addEventListener('click', event => {
2463
+ const id = event.target.closest('button')?.id;
2464
+ if (id === 'turn-remove') void removeSelectedTurns();
2465
+ if (id === 'turns-more') { S.turnsLimit += TURNS_PAGE; renderTurns(); }
2466
+ if (id === 'fish-older' || id === 'fish-retry') void loadFish(Boolean(chat.before));
3001
2467
  });
3002
2468
 
3003
2469
  $('#view-table').addEventListener('click', (event) => {
@@ -3250,15 +2716,54 @@ function renderMaintenance(tab) {
3250
2716
  }
3251
2717
  }
3252
2718
 
2719
+ let modalReturnFocus = null;
2720
+
2721
+ function modalFocusables() {
2722
+ return [...el.modal.querySelectorAll(
2723
+ 'a[href], button:not([disabled]), input:not([disabled]), select:not([disabled]), textarea:not([disabled]), [tabindex]:not([tabindex="-1"])',
2724
+ )].filter((node) => !node.hidden && node.getClientRects().length > 0);
2725
+ }
2726
+
2727
+ function trapModalFocus(event) {
2728
+ const items = modalFocusables();
2729
+ if (!items.length) {
2730
+ event.preventDefault();
2731
+ return;
2732
+ }
2733
+ const first = items[0];
2734
+ const last = items[items.length - 1];
2735
+ if (!el.modal.contains(document.activeElement)) {
2736
+ event.preventDefault();
2737
+ first.focus();
2738
+ return;
2739
+ }
2740
+ if (event.shiftKey && document.activeElement === first) {
2741
+ event.preventDefault();
2742
+ last.focus();
2743
+ } else if (!event.shiftKey && document.activeElement === last) {
2744
+ event.preventDefault();
2745
+ first.focus();
2746
+ }
2747
+ }
2748
+
3253
2749
  function openModal(title, bodyHtml, footHtml) {
2750
+ if (el.modal.hidden) modalReturnFocus = document.activeElement;
3254
2751
  el.modalTitle.textContent = title;
3255
2752
  el.modalBody.innerHTML = bodyHtml;
3256
2753
  el.modalFoot.innerHTML = footHtml;
3257
2754
  el.modal.hidden = false;
2755
+ const first =
2756
+ el.modalBody.querySelector('textarea, input, select, button:not([disabled])') ??
2757
+ el.modalFoot.querySelector('button:not([disabled])') ??
2758
+ $('#modal-close');
2759
+ first?.focus();
3258
2760
  }
3259
2761
 
3260
2762
  function closeModal() {
2763
+ if (el.modal.hidden) return;
3261
2764
  el.modal.hidden = true;
2765
+ if (modalReturnFocus?.isConnected) modalReturnFocus.focus();
2766
+ modalReturnFocus = null;
3262
2767
  }
3263
2768
 
3264
2769
  $('#modal-close').addEventListener('click', closeModal);
@@ -3266,6 +2771,34 @@ el.modal.addEventListener('click', (e) => {
3266
2771
  if (e.target === el.modal) closeModal();
3267
2772
  });
3268
2773
 
2774
+ $('#btn-filters')?.addEventListener('click', () => {
2775
+ setFiltersOpen(document.body.dataset.filters !== 'open');
2776
+ });
2777
+ $('#atlas-filter')?.addEventListener('click', () => setFiltersOpen(document.body.dataset.filters !== 'open'));
2778
+ $('#atlas-mode')?.addEventListener('change', event => { S.view = event.target.value; render(); });
2779
+ $('#atlas-kinds')?.addEventListener('click', event => { const button = event.target.closest('[data-atlas-kind]'); if (button) chooseAtlasKind(button.dataset.atlasKind); });
2780
+ document.querySelector('.atlas-zoom')?.addEventListener('click', event => {
2781
+ const action = event.target.closest('button')?.dataset.zoom;
2782
+ const map = orbitFailed ? null : orbitAtlas;
2783
+ if (action === 'reset') map?.reset();
2784
+ else if (action) map?.zoomBy(action === 'in' ? 1.25 : .8);
2785
+ });
2786
+
2787
+ $('#btn-details')?.addEventListener('click', toggleInspector);
2788
+ $('#story-inspector-close')?.addEventListener('click', closeStoryInspector);
2789
+
2790
+ $('#drawer-backdrop')?.addEventListener('click', () => {
2791
+ if (document.body.dataset.filters === 'open') setFiltersOpen(false);
2792
+ else setInspCollapsed(true);
2793
+ });
2794
+
2795
+ const syncDrawers = () => {
2796
+ if (!narrowFilters.matches) setFiltersOpen(false);
2797
+ applyInspState();
2798
+ };
2799
+ narrowFilters.addEventListener?.('change', syncDrawers);
2800
+ narrowInspector.addEventListener?.('change', syncDrawers);
2801
+
3269
2802
  function openCompose() {
3270
2803
  openModal(
3271
2804
  '新建记忆',
@@ -3386,7 +2919,7 @@ el.inspStub.addEventListener('click', () => {
3386
2919
  renderInspector();
3387
2920
  });
3388
2921
  const bootParams = new URLSearchParams(location.search);
3389
- const bootView = bootParams.get('view') ?? localStorage.getItem('mcore-view2') ?? 'galaxy';
2922
+ const bootView = bootParams.get('view') ?? 'galaxy';
3390
2923
  if (VIEWS.includes(bootView)) S.view = bootView;
3391
2924
  const bootQuery = bootParams.get('q');
3392
2925
  if (bootQuery) {
@@ -3410,5 +2943,7 @@ if (bootCard && cards().some((c) => c.id === bootCard)) {
3410
2943
  render();
3411
2944
  }
3412
2945
  setInterval(() => {
3413
- if (!document.hidden) load({ quiet: true });
2946
+ if (document.hidden || chat.removing || document.querySelector('.turn-dialog')) return;
2947
+ load({ quiet: true });
2948
+ if (S.view === 'turns' && chat.fish) void loadFish();
3414
2949
  }, 20_000);