Repository navigation
Expand file tree
/
Copy pathapp.js
More file actions
804 lines (705 loc) · 24.5 KB
/
Copy pathapp.js
File metadata and controls
804 lines (705 loc) · 24.5 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
const starterNodes = [
{
id: 1,
title: "Import Context",
x: 50,
y: 35,
cluster: "imported",
summary:
"Start by importing a shared AI conversation link, a text file, JSON memory data, or copied conversation text.",
transferableContext:
"This public template does not include the creator's private context. Import your own conversations to build a personal memory map.",
related: ["Local Browser Storage", "Export Memory"],
importance: 72,
},
{
id: 2,
title: "Local Browser Storage",
x: 30,
y: 62,
cluster: "workflow",
summary: "Imported memories are stored locally in the current browser using localStorage.",
transferableContext:
"Each visitor gets their own private browser-local memory map. Public hosting does not include anyone else's imported conversations.",
related: ["Import Context", "Export Memory"],
importance: 68,
},
{
id: 3,
title: "Export Memory",
x: 70,
y: 62,
cluster: "projects",
summary: "Export your generated memory map as JSON whenever you want a portable backup.",
transferableContext:
"Use exported JSON to move a memory map between browsers or keep a backup outside the app.",
related: ["Import Context", "Local Browser Storage"],
importance: 64,
},
];
const colors = {
career: "#55f0dc",
learning: "#7df5a8",
projects: "#ffd166",
workflow: "#b79cff",
imported: "#ff6b8a",
};
const storageKey = "neural-context-memory-map-v2";
const state = {
nodes: loadNodes(),
selectedId: 1,
mode: "network",
search: "",
minImportance: 0,
nodeElements: new Map(),
connectionElements: [],
animationFrame: null,
};
const els = {
stage: document.querySelector(".map-stage"),
nodeLayer: document.querySelector("#node-layer"),
connectionLayer: document.querySelector("#connection-layer"),
search: document.querySelector("#search"),
importanceFilter: document.querySelector("#importance-filter"),
importanceValue: document.querySelector("#importance-value"),
importFile: document.querySelector("#import-file"),
sourceUrl: document.querySelector("#source-url"),
sourceText: document.querySelector("#source-text"),
importSource: document.querySelector("#import-source"),
sourceStatus: document.querySelector("#source-status"),
exportJson: document.querySelector("#export-json"),
resetMap: document.querySelector("#reset-map"),
addNode: document.querySelector("#add-node"),
modeButtons: [...document.querySelectorAll(".segmented button")],
activeTitle: document.querySelector("#active-title"),
title: document.querySelector("#node-title"),
summary: document.querySelector("#node-summary"),
context: document.querySelector("#node-context"),
related: document.querySelector("#node-related"),
importance: document.querySelector("#node-importance"),
importanceText: document.querySelector("#node-importance-value"),
form: document.querySelector("#memory-form"),
copyContext: document.querySelector("#copy-context"),
deleteNode: document.querySelector("#delete-node"),
preview: document.querySelector("#import-preview"),
importedText: document.querySelector("#imported-text"),
total: document.querySelector("#metric-total"),
average: document.querySelector("#metric-average"),
cluster: document.querySelector("#metric-cluster"),
};
function loadNodes() {
try {
const saved = JSON.parse(localStorage.getItem(storageKey));
return Array.isArray(saved) && saved.length ? saved : structuredClone(starterNodes);
} catch {
return structuredClone(starterNodes);
}
}
function saveNodes() {
localStorage.setItem(storageKey, JSON.stringify(state.nodes));
}
function selectedNode() {
return state.nodes.find((node) => node.id === state.selectedId) || state.nodes[0];
}
function relationPairs() {
const pairs = new Set();
state.nodes.forEach((node) => {
node.related.forEach((title) => {
const target = state.nodes.find((candidate) => sameTitle(candidate.title, title));
if (!target) return;
pairs.add([node.id, target.id].sort((a, b) => a - b).join(":"));
});
});
return [...pairs].map((pair) => pair.split(":").map(Number));
}
function sameTitle(a, b) {
return a.trim().toLowerCase() === b.trim().toLowerCase();
}
function visibleNodes() {
const query = state.search.trim().toLowerCase();
return state.nodes.filter((node) => {
const haystack = [node.title, node.summary, node.transferableContext, node.related.join(" ")]
.join(" ")
.toLowerCase();
return node.importance >= state.minImportance && (!query || haystack.includes(query));
});
}
function isFocusVisible(node, visibleIds) {
const active = selectedNode();
return (
state.mode !== "focus" ||
node.id === active.id ||
active.related.some((item) => sameTitle(item, node.title)) ||
node.related.some((item) => sameTitle(item, active.title))
) && visibleIds.has(node.id);
}
function nodeSize(node) {
return Math.round(74 + node.importance * 0.58);
}
function render() {
if (!state.nodes.length) {
state.nodes = structuredClone(starterNodes);
state.selectedId = 1;
}
const visible = visibleNodes();
const visibleIds = new Set(visible.map((node) => node.id));
renderConnections(visibleIds);
renderNodes(visibleIds);
renderDetails();
renderMetrics();
saveNodes();
}
function renderConnections(visibleIds) {
els.connectionLayer.innerHTML = "";
state.connectionElements = [];
relationPairs().forEach(([fromId, toId]) => {
const from = state.nodes.find((node) => node.id === fromId);
const to = state.nodes.find((node) => node.id === toId);
if (!from || !to) return;
const line = document.createElementNS("http://www.w3.org/2000/svg", "line");
line.classList.add("connection");
if (!visibleIds.has(from.id) || !visibleIds.has(to.id)) {
line.classList.add("is-muted");
}
els.connectionLayer.appendChild(line);
state.connectionElements.push({ line, fromId, toId });
});
updateAnimatedPositions(performance.now());
}
function renderNodes(visibleIds) {
els.nodeLayer.innerHTML = "";
state.nodeElements.clear();
state.nodes.forEach((node) => {
const button = document.createElement("button");
button.className = "node";
button.type = "button";
button.style.left = `${node.x}%`;
button.style.top = `${node.y}%`;
button.style.setProperty("--float-x", "0px");
button.style.setProperty("--float-y", "0px");
button.style.setProperty("--node-size", `${nodeSize(node)}px`);
button.style.setProperty("--node-color", colors[node.cluster] || colors.imported);
button.innerHTML = `<strong>${escapeHtml(node.title)}</strong><small>${node.importance}</small>`;
button.setAttribute("aria-label", `Open ${node.title}`);
if (node.id === state.selectedId) button.classList.add("is-active");
if (!isFocusVisible(node, visibleIds)) button.classList.add("is-dimmed");
button.addEventListener("click", () => {
state.selectedId = node.id;
render();
});
button.addEventListener("pointerdown", (event) => beginDrag(event, node));
els.nodeLayer.appendChild(button);
state.nodeElements.set(node.id, button);
});
updateAnimatedPositions(performance.now());
}
function beginDrag(event, node) {
if (event.button !== 0) return;
const target = event.currentTarget;
target.setPointerCapture(event.pointerId);
const move = (moveEvent) => {
const rect = els.stage.getBoundingClientRect();
node.x = clamp(((moveEvent.clientX - rect.left) / rect.width) * 100, 7, 93);
node.y = clamp(((moveEvent.clientY - rect.top) / rect.height) * 100, 9, 91);
target.style.left = `${node.x}%`;
target.style.top = `${node.y}%`;
updateAnimatedPositions(performance.now());
};
const end = () => {
target.removeEventListener("pointermove", move);
target.removeEventListener("pointerup", end);
saveNodes();
};
target.addEventListener("pointermove", move);
target.addEventListener("pointerup", end);
}
function renderDetails() {
const node = selectedNode();
if (!node) return;
els.activeTitle.textContent = node.title;
els.title.value = node.title;
els.summary.value = node.summary;
els.context.value = node.transferableContext;
els.related.value = node.related.join(", ");
els.importance.value = node.importance;
els.importanceText.textContent = node.importance;
}
function renderMetrics() {
const nodes = state.nodes;
const average = nodes.length
? Math.round(nodes.reduce((total, node) => total + Number(node.importance), 0) / nodes.length)
: 0;
const clusterScores = nodes.reduce((scores, node) => {
scores[node.cluster] = (scores[node.cluster] || 0) + node.importance;
return scores;
}, {});
const strongest = Object.entries(clusterScores).sort((a, b) => b[1] - a[1])[0]?.[0] || "-";
els.total.textContent = nodes.length;
els.average.textContent = average;
els.cluster.textContent = titleCase(strongest);
}
function upsertNodeFromForm(event) {
event.preventDefault();
const node = selectedNode();
if (!node) return;
node.title = els.title.value.trim() || "Untitled Memory";
node.summary = els.summary.value.trim();
node.transferableContext = els.context.value.trim();
node.related = parseRelated(els.related.value);
node.importance = Number(els.importance.value);
render();
}
function addNode() {
const nextId = Math.max(0, ...state.nodes.map((node) => node.id)) + 1;
const position = findOpenPosition();
const node = {
id: nextId,
title: "New Memory",
x: position.x,
y: position.y,
cluster: "imported",
summary: "Describe the memory, preference, project, or useful context here.",
transferableContext: "This is the concise context to carry into a new AI chat.",
related: selectedNode() ? [selectedNode().title] : [],
importance: 60,
};
state.nodes.push(node);
state.selectedId = node.id;
settleNodeLayout();
render();
}
function deleteSelectedNode() {
if (state.nodes.length <= 1) return;
const deleted = selectedNode();
state.nodes = state.nodes
.filter((node) => node.id !== deleted.id)
.map((node) => ({
...node,
related: node.related.filter((item) => !sameTitle(item, deleted.title)),
}));
state.selectedId = state.nodes[0].id;
render();
}
async function copyContext() {
const node = selectedNode();
if (navigator.clipboard?.writeText) {
await navigator.clipboard.writeText(node.transferableContext);
} else {
els.context.focus();
els.context.select();
document.execCommand("copy");
}
els.copyContext.textContent = "Copied";
window.setTimeout(() => {
els.copyContext.textContent = "Copy Context";
}, 1200);
}
function exportJson() {
const blob = new Blob([JSON.stringify(state.nodes, null, 2)], {
type: "application/json",
});
const url = URL.createObjectURL(blob);
const link = document.createElement("a");
link.href = url;
link.download = "neural-context-memory-map.json";
link.click();
URL.revokeObjectURL(url);
}
function resetMap() {
state.nodes = structuredClone(starterNodes);
state.selectedId = 1;
localStorage.removeItem(storageKey);
render();
}
function handleImport(event) {
const file = event.target.files?.[0];
if (!file) return;
const reader = new FileReader();
reader.onload = () => {
const text = String(reader.result || "");
els.preview.hidden = false;
els.importedText.textContent = text.slice(0, 1400) + (text.length > 1400 ? "..." : "");
try {
const parsed = JSON.parse(text);
if (Array.isArray(parsed)) {
state.nodes = normalizeImportedNodes(parsed);
state.selectedId = state.nodes[0]?.id || 1;
settleNodeLayout();
render();
return;
}
} catch {
// Plain text import falls through to local topic extraction.
}
const generated = extractMemories(text);
if (generated.length) {
state.nodes.push(...generated);
state.selectedId = generated[0].id;
settleNodeLayout();
render();
}
};
reader.readAsText(file);
event.target.value = "";
}
async function importSourceContext() {
const sourceUrl = normalizeUrl(els.sourceUrl.value.trim());
const pastedText = els.sourceText.value.trim();
if (!sourceUrl && !pastedText) {
setSourceStatus("Paste a shared link, copied conversation text, or both.", "error");
return;
}
setSourceStatus("Reading source...", "");
els.importSource.disabled = true;
try {
let sourceText = pastedText;
if (sourceUrl) {
try {
const fetched = await fetchSourceText(sourceUrl);
sourceText = [pastedText, fetched].filter(Boolean).join("\n\n");
} catch (error) {
if (!sourceText) {
createSourceLinkMemory(sourceUrl);
setSourceStatus(
"The link was saved as a source memory, but the provider blocked automatic reading. Paste copied conversation text to extract deeper context.",
"error",
);
return;
}
}
}
const importedCount = importTextAsMemories(sourceText, sourceUrl, Boolean(sourceUrl));
setSourceStatus(`Imported ${importedCount} memory ${importedCount === 1 ? "node" : "nodes"}.`, "success");
els.sourceText.value = "";
} finally {
els.importSource.disabled = false;
}
}
async function fetchSourceText(url) {
const candidates = [url, `https://r.jina.ai/${url}`];
let lastError;
for (const candidate of candidates) {
try {
const response = await fetch(candidate, { cache: "no-store" });
if (!response.ok) throw new Error(`HTTP ${response.status}`);
const text = await response.text();
const cleaned = cleanFetchedText(text);
if (cleaned.length > 80) return cleaned;
} catch (error) {
lastError = error;
}
}
throw lastError || new Error("Could not read source");
}
function importTextAsMemories(text, sourceUrl = "", forceSingleBubble = false) {
const cleanText = cleanFetchedText(text);
els.preview.hidden = false;
els.importedText.textContent = cleanText.slice(0, 1400) + (cleanText.length > 1400 ? "..." : "");
const generated = forceSingleBubble ? [] : extractMemories(cleanText);
const nodes = generated.length ? generated : [createGeneralSourceMemory(cleanText, sourceUrl)];
nodes.forEach((node) => {
node.sourceUrl = sourceUrl || node.sourceUrl || "";
});
state.nodes.push(...nodes);
state.selectedId = nodes[0].id;
settleNodeLayout();
render();
return nodes.length;
}
function createSourceLinkMemory(sourceUrl) {
const position = findOpenPosition();
const node = {
id: nextNodeId(),
title: `${providerName(sourceUrl)} Shared Link`,
x: position.x,
y: position.y,
cluster: "imported",
summary:
"A shared AI conversation link was added. Paste copied conversation text to extract full memory nodes from this source.",
transferableContext: `Shared conversation source: ${sourceUrl}`,
related: selectedNode() ? [selectedNode().title] : [],
importance: 52,
sourceUrl,
};
state.nodes.push(node);
state.selectedId = node.id;
settleNodeLayout();
render();
}
function createGeneralSourceMemory(text, sourceUrl) {
const summary = summarizeText(text);
const position = findOpenPosition();
return {
id: nextNodeId(),
title: sourceUrl ? `${providerName(sourceUrl)} Context` : "Imported Context",
x: position.x,
y: position.y,
cluster: "imported",
summary,
transferableContext: buildTransferableContext(text, sourceUrl),
related: selectedNode() ? [selectedNode().title] : [],
importance: 68,
sourceUrl,
};
}
function buildTransferableContext(text, sourceUrl) {
const cleaned = cleanFetchedText(text);
const heading = sourceUrl ? `Imported conversation from ${sourceUrl}` : "Imported conversation";
return `${heading}\n\n${cleaned.slice(0, 5000)}`;
}
function cleanFetchedText(text) {
const rawText = String(text);
const embeddedContent = extractSharedPageContent(rawText);
return (embeddedContent || rawText)
.replace(/<script[\s\S]*?<\/script>/gi, " ")
.replace(/<style[\s\S]*?<\/style>/gi, " ")
.replace(/<[^>]+>/g, " ")
.replace(/\\n/g, "\n")
.replace(/\\"/g, '"')
.replace(/"/g, '"')
.replace(/&/g, "&")
.replace(/</g, "<")
.replace(/>/g, ">")
.replace(/\s+/g, " ")
.trim();
}
function extractSharedPageContent(text) {
const markers = [
['\\"content\\",\\"', '\\",\\"access\\"'],
['"content","', '","access"'],
];
for (const [startMarker, endMarker] of markers) {
const start = text.indexOf(startMarker);
if (start === -1) continue;
const contentStart = start + startMarker.length;
const end = text.indexOf(endMarker, contentStart);
if (end === -1) continue;
return text
.slice(contentStart, end)
.replace(/\\u003c/g, "<")
.replace(/\\u003e/g, ">")
.replace(/\\u0026/g, "&")
.replace(/\\n/g, "\n")
.replace(/\\"/g, '"')
.replace(/\\\\/g, "\\");
}
return "";
}
function summarizeText(text) {
const sentences = cleanFetchedText(text)
.split(/(?<=[.!?])\s+/)
.filter((sentence) => sentence.length > 35 && sentence.length < 260);
return (sentences.slice(0, 3).join(" ") || cleanFetchedText(text).slice(0, 360)).slice(0, 420);
}
function nextNodeId() {
return Math.max(0, ...state.nodes.map((node) => node.id)) + 1;
}
function normalizeUrl(value) {
if (!value) return "";
if (/^https?:\/\//i.test(value)) return value;
return `https://${value}`;
}
function providerName(sourceUrl) {
try {
const host = new URL(sourceUrl).hostname.replace(/^www\./, "");
if (host.includes("chatgpt")) return "ChatGPT";
if (host.includes("claude")) return "Claude";
if (host.includes("gemini")) return "Gemini";
if (host.includes("perplexity")) return "Perplexity";
if (host.includes("poe")) return "Poe";
return titleCase(host.split(".")[0] || "AI");
} catch {
return "AI";
}
}
function setSourceStatus(message, type) {
els.sourceStatus.textContent = message;
els.sourceStatus.classList.toggle("is-error", type === "error");
els.sourceStatus.classList.toggle("is-success", type === "success");
}
function extractMemories(text) {
const topics = [
["AI", "career", "model", "agent", "engineer", "machine learning"],
["Python", "Django", "FastAPI", "backend", "API", "code"],
["hackathon", "startup", "project", "demo", "portfolio"],
["GPU", "Colab", "cloud", "training", "inference"],
["laptop", "battery", "portable", "budget", "device"],
];
const sentences = text
.replace(/\s+/g, " ")
.split(/(?<=[.!?])\s+/)
.filter((sentence) => sentence.length > 28);
return topics
.map((keywords, index) => {
const matches = sentences.filter((sentence) =>
keywords.some((keyword) => sentence.toLowerCase().includes(keyword.toLowerCase())),
);
if (!matches.length) return null;
const title = titleCase(keywords[0]);
const nextId = nextNodeId() + index;
const summary = matches.slice(0, 2).join(" ").slice(0, 320);
return {
id: nextId,
title: `Imported ${title}`,
...findOpenPosition(index),
cluster: "imported",
summary,
transferableContext: `Imported chat suggests this relevant context: ${summary}`,
related: [selectedNode()?.title].filter(Boolean),
importance: clamp(58 + matches.length * 6, 58, 96),
};
})
.filter(Boolean);
}
function findOpenPosition(offset = 0) {
const candidates = [];
const rings = [
[50, 44, 0],
[50, 44, 19],
[50, 44, 30],
[50, 44, 40],
];
rings.forEach(([centerX, centerY, radius], ringIndex) => {
const count = ringIndex === 0 ? 1 : 10 + ringIndex * 4;
for (let index = 0; index < count; index += 1) {
const angle = ((index + offset * 2.3) / count) * Math.PI * 2;
candidates.push({
x: clamp(centerX + Math.cos(angle) * radius, 9, 91),
y: clamp(centerY + Math.sin(angle) * radius, 12, 88),
});
}
});
return candidates
.map((candidate) => ({
...candidate,
score: Math.min(
...state.nodes.map((node) => distance(candidate.x, candidate.y, node.x, node.y)),
100,
),
}))
.sort((a, b) => b.score - a.score)[0];
}
function distance(x1, y1, x2, y2) {
return Math.hypot(x1 - x2, y1 - y2);
}
function settleNodeLayout(iterations = 28) {
const minGap = 15;
for (let step = 0; step < iterations; step += 1) {
for (let a = 0; a < state.nodes.length; a += 1) {
for (let b = a + 1; b < state.nodes.length; b += 1) {
const first = state.nodes[a];
const second = state.nodes[b];
const dx = second.x - first.x;
const dy = second.y - first.y;
const gap = Math.hypot(dx, dy) || 0.01;
if (gap >= minGap) continue;
const push = (minGap - gap) * 0.22;
const nx = dx / gap;
const ny = dy / gap;
first.x = clamp(first.x - nx * push, 8, 92);
first.y = clamp(first.y - ny * push, 10, 90);
second.x = clamp(second.x + nx * push, 8, 92);
second.y = clamp(second.y + ny * push, 10, 90);
}
}
}
}
function animatedPosition(node, time) {
const phase = node.id * 1.7;
const speed = time / 1000;
const strength = state.mode === "focus" ? 0.55 : 1;
const x = node.x + Math.sin(speed * 0.42 + phase) * 1.2 * strength;
const y = node.y + Math.cos(speed * 0.36 + phase * 0.8) * 1.45 * strength;
return { x: clamp(x, 6, 94), y: clamp(y, 8, 92) };
}
function updateAnimatedPositions(time) {
state.nodes.forEach((node) => {
const element = state.nodeElements.get(node.id);
if (!element) return;
const position = animatedPosition(node, time);
element.style.left = `${position.x}%`;
element.style.top = `${position.y}%`;
});
state.connectionElements.forEach(({ line, fromId, toId }) => {
const from = state.nodes.find((node) => node.id === fromId);
const to = state.nodes.find((node) => node.id === toId);
if (!from || !to) return;
const start = animatedPosition(from, time);
const end = animatedPosition(to, time);
line.setAttribute("x1", `${start.x}%`);
line.setAttribute("y1", `${start.y}%`);
line.setAttribute("x2", `${end.x}%`);
line.setAttribute("y2", `${end.y}%`);
});
}
function startMapAnimation() {
if (state.animationFrame) return;
const tick = (time) => {
updateAnimatedPositions(time);
state.animationFrame = requestAnimationFrame(tick);
};
state.animationFrame = requestAnimationFrame(tick);
}
function normalizeImportedNodes(nodes) {
return nodes.map((node, index) => ({
id: Number(node.id) || index + 1,
title: String(node.title || `Imported Memory ${index + 1}`),
x: clamp(Number(node.x) || 25 + index * 12, 7, 93),
y: clamp(Number(node.y) || 25 + index * 9, 9, 91),
cluster: node.cluster || "imported",
summary: String(node.summary || ""),
transferableContext: String(node.transferableContext || node.context || ""),
related: Array.isArray(node.related) ? node.related.map(String) : parseRelated(node.related || ""),
importance: clamp(Number(node.importance) || 60, 0, 100),
}));
}
function parseRelated(value) {
return String(value)
.split(",")
.map((item) => item.trim())
.filter(Boolean);
}
function escapeHtml(value) {
return String(value).replace(/[&<>"']/g, (char) => {
const entities = { "&": "&", "<": "<", ">": ">", '"': """, "'": "'" };
return entities[char];
});
}
function titleCase(value) {
return String(value)
.replace(/[-_]/g, " ")
.replace(/\b\w/g, (char) => char.toUpperCase());
}
function clamp(value, min, max) {
return Math.max(min, Math.min(max, value));
}
els.search.addEventListener("input", (event) => {
state.search = event.target.value;
render();
});
els.importanceFilter.addEventListener("input", (event) => {
state.minImportance = Number(event.target.value);
els.importanceValue.textContent = state.minImportance;
render();
});
els.importance.addEventListener("input", (event) => {
els.importanceText.textContent = event.target.value;
});
els.modeButtons.forEach((button) => {
button.addEventListener("click", () => {
state.mode = button.dataset.mode;
els.modeButtons.forEach((item) => item.classList.toggle("is-active", item === button));
render();
});
});
els.form.addEventListener("submit", upsertNodeFromForm);
els.addNode.addEventListener("click", addNode);
els.deleteNode.addEventListener("click", deleteSelectedNode);
els.copyContext.addEventListener("click", copyContext);
els.importSource.addEventListener("click", importSourceContext);
els.exportJson.addEventListener("click", exportJson);
els.resetMap.addEventListener("click", resetMap);
els.importFile.addEventListener("change", handleImport);
settleNodeLayout();
render();
startMapAnimation();