Repository navigation
Expand file tree
/
Copy pathgraph.js
More file actions
1059 lines (945 loc) · 34.7 KB
/
Copy pathgraph.js
File metadata and controls
1059 lines (945 loc) · 34.7 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/**
* Smart Memory - SillyTavern Extension
* Copyright (C) 2026 Senjin the Dragon
* https://github.com/senjinthedragon/Smart-Memory
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as
* published by the Free Software Foundation, either version 3 of the
* License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
/**
* Memory graph visualization: force-directed canvas rendering of entities and memories.
*
* showMemoryGraph - opens the full-screen graph overlay for a given character
*/
import { loadCharacterMemories } from './longterm.js';
import { loadSessionMemories } from './session.js';
import {
loadCharacterEntityRegistry,
saveCharacterEntityRegistry,
loadSessionEntityRegistry,
saveSessionEntityRegistry,
reconcileEntityRegistry,
} from './graph-migration.js';
// ---- Visual constants -------------------------------------------------------
// Entity type colors (kept in sync with CSS badge definitions in style.css).
const ENTITY_COLORS = {
character: '#7ecfff',
place: '#a8d88f',
object: '#d4b97a',
faction: '#c49de8',
concept: '#f0a0a0',
unknown: '#999999',
};
// Memory type colors (kept in sync with CSS badge definitions in style.css).
const MEMORY_COLORS = {
fact: 'oklch(57% 0.10 252)',
relationship: 'oklch(57% 0.10 0)',
preference: 'oklch(57% 0.10 144)',
event: 'oklch(57% 0.10 36)',
scene: 'oklch(57% 0.10 180)',
revelation: 'oklch(57% 0.10 324)',
development: 'oklch(57% 0.10 108)',
detail: 'oklch(57% 0.10 216)',
};
const ENTITY_RADIUS = 32;
// Memory node radii by importance level (1/2/3).
// Wide ratio so tiers read clearly on large screens.
const MEMORY_RADII = [7, 13, 21];
// ---- Theme helpers ----------------------------------------------------------
/**
* Reads the active SillyTavern theme's CSS variables so the canvas renderer
* can match the surrounding UI. Called once per render frame so theme changes
* (e.g. the user switching themes while the graph is open) are reflected
* without needing to reopen the graph.
* @returns {{ bg: string, text: string, edgeLink: string, retiredStroke: string, selectGlow: string, hoverGlow: string }}
*/
function getGraphTheme() {
const style = getComputedStyle(document.documentElement);
const get = (v, fallback) => style.getPropertyValue(v).trim() || fallback;
const bg = get('--SmartThemeBlurTintColor', '#12121e');
const text = get('--SmartThemeBodyColor', '#dcdcd2');
const em = get('--SmartThemeEmColor', '#919191');
return {
bg,
text,
// Link edges use the theme's muted text color at low opacity.
edgeLink: em,
// Supersession arrows use the theme's quote/accent color when available,
// falling back to the original orange which reads well on most backgrounds.
edgeSupersedes: get('--SmartThemeQuoteColor', '#d4905b'),
// Retired node dashed border adapts to text color.
retiredStroke: text,
// Selection and hover glows are neutral so they work on any background.
selectGlow: 'rgba(255,255,200,0.18)',
hoverGlow: 'rgba(128,128,128,0.15)',
// Label shadow contrasts against both light and dark backgrounds.
labelShadow: 'rgba(0,0,0,0.85)',
};
}
// ---- Force simulation constants ---------------------------------------------
const REPULSION_K = 3500; // Coulomb-like repulsion strength
const SPRING_K = 0.05; // Hooke's law spring stiffness
const SPRING_REST_EM = 140; // entity-memory edge rest length
const SPRING_REST_MM = 55; // memory-memory (supersedes) rest length
const DAMPING = 0.9; // velocity multiplied by this each tick
const GRAVITY_K = 0.012; // pull toward world origin (0,0)
const ALPHA_DECAY = 0.992; // simulation cools by this factor each tick
const ALPHA_MIN = 0.004; // stop when alpha falls below this
const MAX_MEMORIES = 100; // max memory nodes rendered (top by importance)
// ---- Module state -----------------------------------------------------------
// All state lives here and is reset on close so there are no leaks.
let gs = null; // active graph state, null when closed
// ---- Public API -------------------------------------------------------------
/**
* Opens the memory graph overlay for a character.
* If the overlay is already open it is closed first.
* @param {string|null} characterName - Active character name for long-term lookups.
*/
export function showMemoryGraph(characterName) {
if (gs) closeGraph();
// Repair any entity-memory links that the model missed before rendering.
// Both registries are reconciled against the combined memory pool so that a
// session memory can link to an LT entity and vice versa.
const ltMems = characterName
? loadCharacterMemories(characterName).filter((m) => !m.superseded_by)
: [];
const sessionMems = loadSessionMemories().filter((m) => !m.superseded_by);
const allMems = [...ltMems, ...sessionMems];
if (characterName) {
const ltRegistry = loadCharacterEntityRegistry(characterName);
if (ltRegistry.length > 0) {
reconcileEntityRegistry(ltRegistry, allMems);
saveCharacterEntityRegistry(characterName, ltRegistry);
}
}
const sessionRegistry = loadSessionEntityRegistry();
if (sessionRegistry.length > 0) {
reconcileEntityRegistry(sessionRegistry, allMems);
saveSessionEntityRegistry(sessionRegistry).catch(console.error);
}
const opts = { showSession: true, showRetired: false };
const { nodes, edges } = buildGraph(characterName, opts);
if (nodes.length === 0) {
// Show a brief inline message rather than opening an empty graph.
const $panel = $('#sm_entity_panel');
const $msg = $(
'<div class="sm-muted" style="padding:6px 0">No entities or memories to display yet.</div>',
);
$panel.prepend($msg);
setTimeout(() => $msg.remove(), 3000);
return;
}
const $overlay = $(buildOverlayHTML(characterName));
document.body.appendChild($overlay[0]);
// Use showModal() so the overlay renders in the browser's top layer, immune
// to ST's transformed ancestors that trap position:fixed divs on mobile.
// Prevent the browser's default Escape handling - our keydown handler calls
// closeGraph() which does proper canvas/state cleanup before removing.
$overlay[0].addEventListener('cancel', (e) => e.preventDefault());
$overlay[0].showModal();
const canvas = document.getElementById('sm_graph_canvas');
const ctx = canvas.getContext('2d');
fitCanvas(canvas);
initPositions(nodes, edges);
gs = {
nodes,
edges,
nodeById: new Map(nodes.map((n) => [n.id, n])),
canvas,
ctx,
characterName,
opts,
// Camera: pan offset (world units) and zoom scale.
camera: { x: 0, y: 0, scale: 1 },
// Interaction state.
dragging: null, // { node, offsetX, offsetY }
hovered: null, // node or null
selected: null, // node or null
mouseWorld: { x: 0, y: 0 },
// Animation.
alpha: 1.0,
rafId: null,
// Pan state.
panning: false,
panStart: null,
cameraAtPanStart: null,
};
bindEvents(canvas, $overlay, characterName);
// Run the simulation to get an initial settled layout before showing the
// graph. 200 ticks brings alpha to ~0.20 (vs ~0.38 at 120), clearing the
// main turbulence phase where large entity nodes would otherwise visibly
// orbit each other before damping takes over.
for (let i = 0; i < 200; i++) tick();
fitCameraToNodes();
scheduleFrame();
}
// ---- Graph data builder -----------------------------------------------------
/**
* Builds the nodes and edges arrays from stored memory data.
* @param {string|null} characterName
* @param {{ showSession: boolean, showRetired: boolean }} opts
* @returns {{ nodes: object[], edges: object[] }}
*/
function buildGraph(characterName, opts) {
const nodes = [];
const edges = [];
const nodeById = new Map();
// ---- Entity nodes ----
const ltEntities = characterName ? loadCharacterEntityRegistry(characterName) : [];
const sessionEntities = opts.showSession ? loadSessionEntityRegistry() : [];
// Deduplicate by name|type. When the same entity appears in both LT and
// session registries, merge their memory_ids so edges to both LT and session
// memory nodes are drawn. Discarding the session entry's memory_ids would
// leave session memories linked only to the session entity as floating nodes.
const entityByKey = new Map();
for (const e of [...ltEntities, ...sessionEntities]) {
const key = `${e.name.toLowerCase().trim()}|${e.type ?? 'unknown'}`;
if (!entityByKey.has(key)) {
entityByKey.set(key, { ...e, memory_ids: [...(e.memory_ids ?? [])] });
} else {
const existing = entityByKey.get(key);
for (const id of e.memory_ids ?? []) {
if (!existing.memory_ids.includes(id)) existing.memory_ids.push(id);
}
}
}
for (const entity of entityByKey.values()) {
const node = {
id: entity.id,
nodeType: 'entity',
label: entity.name,
detail: `${entity.type}`,
subtype: entity.type ?? 'unknown',
color: ENTITY_COLORS[entity.type] ?? ENTITY_COLORS.unknown,
radius: ENTITY_RADIUS,
memoryIds: new Set(entity.memory_ids ?? []),
x: 0,
y: 0,
vx: 0,
vy: 0,
fixed: false,
};
nodes.push(node);
nodeById.set(entity.id, node);
}
// ---- Memory nodes ----
const ltMems = characterName ? loadCharacterMemories(characterName) : [];
const sessionMems = opts.showSession ? loadSessionMemories() : [];
const allMems = [...ltMems, ...sessionMems];
const filtered = opts.showRetired ? allMems : allMems.filter((m) => !m.superseded_by);
// Keep top MAX_MEMORIES by importance, then recency.
const sorted = [...filtered].sort(
(a, b) => (b.importance ?? 1) - (a.importance ?? 1) || (b.ts ?? 0) - (a.ts ?? 0),
);
const visible = sorted.slice(0, MAX_MEMORIES);
const visibleIds = new Set(visible.map((m) => m.id));
for (const mem of visible) {
const r = MEMORY_RADII[(mem.importance ?? 1) - 1] ?? MEMORY_RADII[0];
const node = {
id: mem.id,
nodeType: 'memory',
label: '',
// Truncate for tooltip.
detail: mem.content?.length > 200 ? mem.content.slice(0, 197) + '...' : (mem.content ?? ''),
subtype: mem.type ?? 'fact',
color: MEMORY_COLORS[mem.type] ?? '#666',
radius: r,
retired: Boolean(mem.superseded_by),
triggers: Array.isArray(mem.triggers) && mem.triggers.length > 0 ? mem.triggers : null,
x: 0,
y: 0,
vx: 0,
vy: 0,
fixed: false,
};
nodes.push(node);
nodeById.set(mem.id, node);
}
// ---- Edges ----
// Entity -> memory links.
for (const node of nodes) {
if (node.nodeType !== 'entity') continue;
for (const memId of node.memoryIds) {
if (visibleIds.has(memId) && nodeById.has(memId)) {
edges.push({ source: node.id, target: memId, edgeType: 'link' });
}
}
}
// Memory supersedes chains.
for (const mem of visible) {
if (!Array.isArray(mem.supersedes)) continue;
for (const oldId of mem.supersedes) {
if (visibleIds.has(oldId) && nodeById.has(oldId)) {
edges.push({ source: oldId, target: mem.id, edgeType: 'supersedes' });
}
}
}
return { nodes, edges };
}
/**
* Places nodes at reasonable starting positions so the simulation converges quickly.
* Entities are arranged in a circle; memories near their first linked entity.
* @param {object[]} nodes
* @param {object[]} edges
*/
function initPositions(nodes, edges) {
const entities = nodes.filter((n) => n.nodeType === 'entity');
const memories = nodes.filter((n) => n.nodeType === 'memory');
// Entities: evenly spaced on a circle. Radius scales with both count and
// node size so large entity nodes start far enough apart that the initial
// repulsion burst doesn't produce orbital energy before damping can absorb it.
const er = Math.max(ENTITY_RADIUS * 7, entities.length * 50);
entities.forEach((e, i) => {
const angle = (2 * Math.PI * i) / Math.max(entities.length, 1) - Math.PI / 2;
e.x = Math.cos(angle) * er;
e.y = Math.sin(angle) * er;
});
// Build a quick lookup: memId -> first entity that links to it.
const memAnchor = new Map();
for (const edge of edges) {
if (edge.edgeType !== 'link') continue;
if (!memAnchor.has(edge.target)) {
const entityNode = nodes.find((n) => n.id === edge.source);
if (entityNode) memAnchor.set(edge.target, entityNode);
}
}
// Memories: jitter near anchor entity, or random near origin if unlinked.
for (const mem of memories) {
const anchor = memAnchor.get(mem.id);
const cx = anchor ? anchor.x : 0;
const cy = anchor ? anchor.y : 0;
const spread = anchor ? 70 : 200;
mem.x = cx + (Math.random() - 0.5) * spread;
mem.y = cy + (Math.random() - 0.5) * spread;
}
}
// ---- Force simulation -------------------------------------------------------
/**
* Advances the simulation by one tick. Applies repulsion, spring forces,
* gravity, and integrates velocity. Cools alpha each tick.
*/
function tick() {
const { nodes, edges, alpha } = gs;
const n = nodes.length;
// Repulsion between all pairs (O(n²) - fine for n <= ~150).
// Effective distance is floored at the sum of both radii + padding so the
// repulsion force always separates circles regardless of their sizes.
const NODE_GAP = 14; // minimum gap between node edges in world units
for (let i = 0; i < n; i++) {
for (let j = i + 1; j < n; j++) {
const a = nodes[i];
const b = nodes[j];
const dx = a.x - b.x;
const dy = a.y - b.y;
const dist = Math.sqrt(dx * dx + dy * dy) || 1;
const minDist = a.radius + b.radius + NODE_GAP;
const effectiveDist = Math.max(dist, minDist * 0.5); // soft floor
const force = (REPULSION_K * alpha) / (effectiveDist * effectiveDist);
const fx = (dx / dist) * force;
const fy = (dy / dist) * force;
a.vx += fx;
a.vy += fy;
b.vx -= fx;
b.vy -= fy;
}
}
// Spring forces along edges.
const nodeById = gs.nodeById;
for (const edge of edges) {
const a = nodeById.get(edge.source);
const b = nodeById.get(edge.target);
if (!a || !b) continue;
const dx = b.x - a.x;
const dy = b.y - a.y;
const dist = Math.sqrt(dx * dx + dy * dy) || 1;
const rest = edge.edgeType === 'supersedes' ? SPRING_REST_MM : SPRING_REST_EM;
const force = SPRING_K * (dist - rest) * alpha;
const fx = (dx / dist) * force;
const fy = (dy / dist) * force;
a.vx += fx;
a.vy += fy;
b.vx -= fx;
b.vy -= fy;
}
// Gravity toward origin and velocity integration.
for (const node of nodes) {
if (node.fixed) continue;
node.vx += -GRAVITY_K * node.x * alpha;
node.vy += -GRAVITY_K * node.y * alpha;
node.vx *= DAMPING;
node.vy *= DAMPING;
node.x += node.vx;
node.y += node.vy;
}
// Hard collision resolution: push overlapping nodes apart so circles never
// intersect regardless of how strongly the springs pull them together.
for (let i = 0; i < n; i++) {
for (let j = i + 1; j < n; j++) {
const a = nodes[i];
const b = nodes[j];
const dx = a.x - b.x;
const dy = a.y - b.y;
const dist = Math.sqrt(dx * dx + dy * dy) || 1;
const minDist = a.radius + b.radius + NODE_GAP;
if (dist < minDist) {
const push = (minDist - dist) / 2;
const ux = dx / dist;
const uy = dy / dist;
if (!a.fixed) {
a.x += ux * push;
a.y += uy * push;
}
if (!b.fixed) {
b.x -= ux * push;
b.y -= uy * push;
}
}
}
}
gs.alpha *= ALPHA_DECAY;
}
// ---- Renderer ---------------------------------------------------------------
/**
* Draws the current graph state onto the canvas.
*/
function render() {
const { nodes, edges, canvas, ctx, camera, selected, hovered } = gs;
const { width, height } = canvas;
const theme = getGraphTheme();
ctx.clearRect(0, 0, width, height);
// Background - matches the card's panel background from the active ST theme.
ctx.fillStyle = theme.bg;
ctx.fillRect(0, 0, width, height);
// Camera transform: world origin maps to canvas center + pan offset.
ctx.save();
ctx.translate(width / 2 + camera.x, height / 2 + camera.y);
ctx.scale(camera.scale, camera.scale);
const nodeById = gs.nodeById;
// When a node is selected, dim everything not directly connected.
const highlightIds = buildHighlightSet(selected, edges);
// ---- Edges ----
for (const edge of edges) {
const a = nodeById.get(edge.source);
const b = nodeById.get(edge.target);
if (!a || !b) continue;
const dimmed = selected && !highlightIds.has(edge.source) && !highlightIds.has(edge.target);
const baseAlpha = edge.edgeType === 'supersedes' ? 0.75 : 0.22;
const alpha = dimmed ? 0.04 : baseAlpha;
if (edge.edgeType === 'supersedes') {
drawArrow(ctx, a.x, a.y, b.x, b.y, theme.edgeSupersedes, alpha, b.radius);
} else {
ctx.save();
ctx.globalAlpha = alpha;
ctx.strokeStyle = theme.edgeLink;
ctx.lineWidth = 1;
ctx.beginPath();
ctx.moveTo(a.x, a.y);
ctx.lineTo(b.x, b.y);
ctx.stroke();
ctx.restore();
}
}
// ---- Node circles (first pass) ----
for (const node of nodes) {
const dimmed = selected && !highlightIds.has(node.id);
const isSelected = selected && node.id === selected.id;
const isHovered = hovered && node.id === hovered.id;
ctx.save();
ctx.globalAlpha = dimmed ? 0.15 : 1.0;
// Glow ring for selected or hovered.
if (isSelected || isHovered) {
ctx.beginPath();
ctx.arc(node.x, node.y, node.radius + 5, 0, 2 * Math.PI);
ctx.fillStyle = isSelected ? theme.selectGlow : theme.hoverGlow;
ctx.fill();
}
// Node circle.
ctx.beginPath();
ctx.arc(node.x, node.y, node.radius, 0, 2 * Math.PI);
ctx.fillStyle = node.color;
ctx.fill();
// Retired memory: dashed border.
if (node.nodeType === 'memory' && node.retired) {
ctx.setLineDash([3, 3]);
ctx.strokeStyle = theme.retiredStroke;
ctx.globalAlpha = (ctx.globalAlpha ?? 1) * 0.3;
ctx.lineWidth = 1;
ctx.stroke();
ctx.setLineDash([]);
}
ctx.restore();
}
// ---- Entity labels (second pass, always on top of all circles) ----
for (const node of nodes) {
if (node.nodeType !== 'entity') continue;
const dimmed = selected && !highlightIds.has(node.id);
ctx.save();
ctx.globalAlpha = dimmed ? 0.15 : 1.0;
ctx.font = 'bold 11px sans-serif';
ctx.textAlign = 'center';
ctx.textBaseline = 'top';
ctx.shadowColor = theme.labelShadow;
ctx.shadowBlur = 3;
ctx.fillStyle = theme.text;
ctx.fillText(node.label, node.x, node.y + node.radius + 4);
ctx.shadowBlur = 0;
ctx.restore();
}
ctx.restore(); // undo camera transform
// ---- Tooltip (in screen space) ----
renderTooltip();
}
/**
* Returns the set of node ids that should be highlighted when a node is selected:
* the selected node itself plus all directly connected neighbours.
* @param {object|null} selected
* @param {object[]} edges
* @returns {Set<string>}
*/
function buildHighlightSet(selected, edges) {
if (!selected) return new Set();
const ids = new Set([selected.id]);
for (const edge of edges) {
if (edge.source === selected.id) ids.add(edge.target);
if (edge.target === selected.id) ids.add(edge.source);
}
return ids;
}
/**
* Draws a directed arrow between two points, stopping short of the target node centre.
* @param {CanvasRenderingContext2D} ctx
* @param {number} x1 - source x (world)
* @param {number} y1 - source y
* @param {number} x2 - target x
* @param {number} y2 - target y
* @param {string} color
* @param {number} alpha - global alpha
* @param {number} targetRadius - stop this many units from target centre
*/
function drawArrow(ctx, x1, y1, x2, y2, color, alpha, targetRadius = 10) {
const dx = x2 - x1;
const dy = y2 - y1;
const len = Math.sqrt(dx * dx + dy * dy);
if (len < 2) return;
const ux = dx / len;
const uy = dy / len;
// End point: stop just outside the target node's edge.
const tx = x2 - ux * (targetRadius + 4);
const ty = y2 - uy * (targetRadius + 4);
ctx.save();
ctx.globalAlpha = alpha;
ctx.strokeStyle = color;
ctx.lineWidth = 1.5;
ctx.beginPath();
ctx.moveTo(x1, y1);
ctx.lineTo(tx, ty);
ctx.stroke();
// Arrowhead.
const headLen = 8;
const angle = Math.atan2(ty - y1, tx - x1);
ctx.fillStyle = color;
ctx.beginPath();
ctx.moveTo(tx, ty);
ctx.lineTo(
tx - headLen * Math.cos(angle - Math.PI / 6),
ty - headLen * Math.sin(angle - Math.PI / 6),
);
ctx.lineTo(
tx - headLen * Math.cos(angle + Math.PI / 6),
ty - headLen * Math.sin(angle + Math.PI / 6),
);
ctx.closePath();
ctx.fill();
ctx.restore();
}
/**
* Updates the tooltip element position and content based on the hovered or selected node.
*/
function renderTooltip() {
const $tip = $('#sm_graph_tooltip');
const node = gs.hovered ?? gs.selected;
if (!node) {
$tip.hide();
return;
}
// Convert world coords to screen coords for positioning.
const { camera, canvas } = gs;
const sx = node.x * camera.scale + canvas.width / 2 + camera.x;
const sy = node.y * camera.scale + canvas.height / 2 + camera.y;
const esc = (s) => $('<div>').text(s).html();
const typeLabel = node.nodeType === 'entity' ? `Entity - ${node.subtype}` : node.subtype;
const triggersLine = node.triggers
? `<span class="sm_graph_tip_triggers">Triggers: ${esc(node.triggers.join(', '))}</span>`
: '';
const content = `<strong>${esc(node.nodeType === 'entity' ? node.label : node.subtype)}</strong>
<span class="sm_graph_tip_type">${esc(typeLabel)}</span>
<span class="sm_graph_tip_detail">${esc(node.detail)}</span>${triggersLine}`;
// Render off-screen first so outerWidth/Height return accurate dimensions.
// When the tooltip is hidden, jQuery returns 0 and the fallback value is
// used instead - causing bottom-clamp miscalculation for tall tooltips.
$tip.html(content).css({ left: -9999, top: -9999 }).show();
// Position tooltip: prefer above/right of node, clamp to canvas bounds.
const tipW = $tip.outerWidth(true) || 220;
const tipH = $tip.outerHeight(true) || 80;
const pad = 10;
let left = sx + node.radius * camera.scale + pad;
let top = sy - tipH / 2;
const canvasRect = canvas.getBoundingClientRect();
const overlayLeft =
canvasRect.left - document.getElementById('sm_graph_card').getBoundingClientRect().left;
const overlayTop =
canvasRect.top - document.getElementById('sm_graph_card').getBoundingClientRect().top;
left += overlayLeft;
top += overlayTop;
if (left + tipW > canvas.width + overlayLeft - 4)
left = sx - tipW - node.radius * camera.scale - pad + overlayLeft;
// Final clamp keeps tooltip inside canvas bounds on all sides, including
// after a left-flip that would push it off the left edge on small screens.
left = Math.max(overlayLeft + 4, Math.min(left, canvas.width + overlayLeft - tipW - 4));
top = Math.max(overlayTop + 4, Math.min(top, canvas.height + overlayTop - tipH - 4));
$tip.css({ left, top });
}
// ---- Animation loop ---------------------------------------------------------
/**
* Restarts the rAF loop if it has been paused due to idle state.
* Call this from any event handler that causes a visual change while the
* simulation is settled (hover, selection, zoom, filter toggle).
*/
function wakeGraph() {
if (gs && !gs.rafId) scheduleFrame();
}
function scheduleFrame() {
if (!gs) return;
gs.rafId = requestAnimationFrame(() => {
if (!gs) return;
// Tick only while the simulation is active or a node is being dragged.
// Panning also keeps the loop running so the canvas tracks the cursor.
const simActive = gs.alpha > ALPHA_MIN || gs.dragging || gs.panning;
if (simActive) tick();
render();
if (simActive) {
scheduleFrame();
} else {
// Simulation idle and no interaction in progress - stop burning frames.
// wakeGraph() restarts the loop whenever a visual change is needed.
gs.rafId = null;
}
});
}
// ---- Input handling ---------------------------------------------------------
/**
* Converts a mouse event's position to world coordinates.
* @param {MouseEvent} e
* @returns {{ x: number, y: number }}
*/
function mouseToWorld(e) {
const rect = gs.canvas.getBoundingClientRect();
const sx = e.clientX - rect.left;
const sy = e.clientY - rect.top;
return {
x: (sx - gs.canvas.width / 2 - gs.camera.x) / gs.camera.scale,
y: (sy - gs.canvas.height / 2 - gs.camera.y) / gs.camera.scale,
};
}
/**
* Returns the node at world position (wx, wy), or null if none.
* @param {number} wx
* @param {number} wy
* @returns {object|null}
*/
function nodeAtWorld(wx, wy) {
// Iterate in reverse so topmost-drawn nodes get hit first.
for (let i = gs.nodes.length - 1; i >= 0; i--) {
const n = gs.nodes[i];
const dx = n.x - wx;
const dy = n.y - wy;
if (dx * dx + dy * dy <= (n.radius + 4) * (n.radius + 4)) return n;
}
return null;
}
/**
* Binds all canvas and overlay event listeners, storing them for cleanup.
* @param {HTMLCanvasElement} canvas
* @param {jQuery} $overlay
* @param {string|null} characterName
*/
function bindEvents(canvas, $overlay, characterName) {
// ---- Mouse move: hover + drag + pan ----
// Bound on document so drag and pan continue when the cursor leaves the canvas.
const onMouseMove = (e) => {
if (!gs) return;
const world = mouseToWorld(e);
gs.mouseWorld = world;
if (gs.dragging) {
const node = gs.dragging;
node.x = world.x + gs.dragging.offsetX;
node.y = world.y + gs.dragging.offsetY;
node.vx = 0;
node.vy = 0;
gs.alpha = Math.max(gs.alpha, 0.1); // briefly reheat so graph settles
return;
}
if (gs.panning) {
const dx = e.clientX - gs.panStart.x;
const dy = e.clientY - gs.panStart.y;
gs.camera.x = gs.cameraAtPanStart.x + dx;
gs.camera.y = gs.cameraAtPanStart.y + dy;
return;
}
// Hover detection: only when cursor is actually over the canvas.
const rect = canvas.getBoundingClientRect();
const overCanvas =
e.clientX >= rect.left &&
e.clientX <= rect.right &&
e.clientY >= rect.top &&
e.clientY <= rect.bottom;
const node = overCanvas ? nodeAtWorld(world.x, world.y) : null;
if (node !== gs.hovered) {
gs.hovered = node;
canvas.style.cursor = node ? 'pointer' : 'grab';
// Hover changed while sim is idle - need one render to show highlight.
wakeGraph();
}
};
// ---- Mouse down: start drag or pan ----
const onMouseDown = (e) => {
if (!gs) return;
e.preventDefault();
const world = mouseToWorld(e);
const node = nodeAtWorld(world.x, world.y);
if (node && e.button === 0) {
// Drag node.
gs.dragging = node;
gs.dragging.offsetX = node.x - world.x;
gs.dragging.offsetY = node.y - world.y;
node.fixed = true;
canvas.style.cursor = 'grabbing';
wakeGraph();
} else if (!node && e.button === 0) {
// Pan.
gs.panning = true;
gs.panStart = { x: e.clientX, y: e.clientY };
gs.cameraAtPanStart = { ...gs.camera };
canvas.style.cursor = 'grabbing';
wakeGraph();
}
};
// ---- Mouse up: end drag or pan, handle click ----
// Bound on document so releasing outside the canvas still clears drag/pan state.
const onMouseUp = (e) => {
if (!gs) return;
if (gs.dragging) {
const node = gs.dragging;
node.fixed = false;
gs.dragging = null;
gs._endedDrag = true; // suppress the overlay click-outside handler this cycle
canvas.style.cursor = 'pointer';
return;
}
if (gs.panning) {
gs.panning = false;
gs._endedDrag = true;
canvas.style.cursor = 'grab';
return;
}
// Click: select/deselect - only when released over the canvas.
if (e.button === 0 && e.target === canvas) {
const world = mouseToWorld(e);
const node = nodeAtWorld(world.x, world.y);
gs.selected = node === gs.selected ? null : node;
wakeGraph();
}
};
// ---- Scroll: zoom ----
const onWheel = (e) => {
if (!gs) return;
e.preventDefault();
const factor = e.deltaY < 0 ? 1.1 : 0.91;
const newScale = Math.max(0.2, Math.min(4, gs.camera.scale * factor));
// Zoom toward the cursor position.
const rect = canvas.getBoundingClientRect();
const mx = e.clientX - rect.left - canvas.width / 2;
const my = e.clientY - rect.top - canvas.height / 2;
gs.camera.x = mx - (mx - gs.camera.x) * (newScale / gs.camera.scale);
gs.camera.y = my - (my - gs.camera.y) * (newScale / gs.camera.scale);
gs.camera.scale = newScale;
wakeGraph();
};
// ---- Keyboard: Escape to close ----
const onKeyDown = (e) => {
if (e.key === 'Escape') closeGraph();
};
document.addEventListener('mousemove', onMouseMove);
canvas.addEventListener('mousedown', onMouseDown);
document.addEventListener('mouseup', onMouseUp);
canvas.addEventListener('wheel', onWheel, { passive: false });
document.addEventListener('keydown', onKeyDown);
// Store for cleanup.
gs._cleanup = () => {
document.removeEventListener('mousemove', onMouseMove);
canvas.removeEventListener('mousedown', onMouseDown);
document.removeEventListener('mouseup', onMouseUp);
canvas.removeEventListener('wheel', onWheel);
document.removeEventListener('keydown', onKeyDown);
};
// ---- Overlay UI buttons ----
$overlay.find('#sm_graph_close').on('click', closeGraph);
$overlay.find('#sm_graph_reset').on('click', () => {
if (!gs) return;
initPositions(gs.nodes, gs.edges);
gs.camera = { x: 0, y: 0, scale: 1 };
gs.alpha = 1.0;
wakeGraph();
// Re-fit after the simulation has had a moment to settle.
setTimeout(() => {
if (gs) {
for (let i = 0; i < 120; i++) tick();
fitCameraToNodes();
}
}, 50);
});
$overlay.find('#sm_graph_show_session').on('change', function () {
if (!gs) return;
gs.opts.showSession = this.checked;
rebuildGraph(characterName);
});
$overlay.find('#sm_graph_show_retired').on('change', function () {
if (!gs) return;
gs.opts.showRetired = this.checked;
rebuildGraph(characterName);
});
// Click outside the card to close - but not if a drag just ended.
$overlay.on('click', (e) => {
if (gs?._endedDrag) {
gs._endedDrag = false;
return;
}
if (e.target === $overlay[0]) closeGraph();
});
}
/**
* Rebuilds the graph data in place (after toggling a filter) without closing the overlay.
* @param {string|null} characterName
*/
function rebuildGraph(characterName) {
const { nodes, edges } = buildGraph(characterName, gs.opts);
gs.nodes = nodes;
gs.edges = edges;
gs.nodeById = new Map(nodes.map((n) => [n.id, n]));
initPositions(nodes, edges);
gs.alpha = 1.0;
gs.selected = null;
gs.hovered = null;
wakeGraph();
}
// ---- Lifecycle helpers ------------------------------------------------------
/**
* Sets the camera scale and pan so all nodes fit within the canvas with padding.
* Called once after the initial layout pre-run so the graph is never tiny or
* clipped regardless of screen size.
*/
function fitCameraToNodes() {
const { nodes, canvas } = gs;
if (nodes.length === 0) return;
let minX = Infinity,
minY = Infinity,
maxX = -Infinity,
maxY = -Infinity;
for (const n of nodes) {
minX = Math.min(minX, n.x - n.radius);
minY = Math.min(minY, n.y - n.radius);
maxX = Math.max(maxX, n.x + n.radius);
maxY = Math.max(maxY, n.y + n.radius);
}
const pad = 60;
const contentW = maxX - minX + pad * 2;
const contentH = maxY - minY + pad * 2;
const scale = Math.min(
canvas.width / contentW,
canvas.height / contentH,
2, // don't over-zoom for very sparse graphs
);
const cx = (minX + maxX) / 2;
const cy = (minY + maxY) / 2;
gs.camera.scale = scale;
gs.camera.x = -cx * scale;
gs.camera.y = -cy * scale;
}
/**
* Closes and fully tears down the graph overlay.
*/
function closeGraph() {
if (!gs) return;
cancelAnimationFrame(gs.rafId);
gs._cleanup?.();
const overlay = document.getElementById('sm_graph_overlay');
if (overlay?.open) overlay.close();
overlay?.remove();
gs = null;
}
/**
* Sizes the canvas to match its wrapper element's actual pixel dimensions.