-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathscript.js
More file actions
1922 lines (1700 loc) · 81.9 KB
/
Copy pathscript.js
File metadata and controls
1922 lines (1700 loc) · 81.9 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
'use strict';
// ═══════════════════════════════════════════════════
// LENS DEFINITIONS
// ═══════════════════════════════════════════════════
const LENSES = {
fact: { key:'fact', icon:'◈', name:'FACT', desc:'Objective, verifiable statement', color:'#00d4ff', face:'fr', hint:'The prime truth. What is known.' },
counter: { key:'counter', icon:'⊘', name:'COUNTER', desc:'Refutation or opposing argument', color:'#ff4e4e', face:'bk', hint:'The challenge. What pushes back.' },
opinion: { key:'opinion', icon:'◎', name:'OPINION', desc:'Personal or cultural perspective', color:'#a855f7', face:'lt', hint:'The view. What someone believes.' },
fiction: { key:'fiction', icon:'◇', name:'FICTION', desc:'Speculative, narrative or imagined take', color:'#f59e0b', face:'rt', hint:'The story. What could be imagined.' },
context: { key:'context', icon:'⊡', name:'CONTEXT', desc:'Historical, scientific or wider setting', color:'#10b981', face:'tp', hint:'The frame. Where it sits in time or space.' },
unknown: { key:'unknown', icon:'?', name:'UNKNOWN', desc:'What remains unknown or unresolved', color:'#6b7a99', face:'bt', hint:'The gap. What we do not yet know.' },
};
const LENS_ORDER = ['fact','counter','opinion','fiction','context','unknown'];
const FACE_TO_LENS = Object.fromEntries(LENS_ORDER.map(k=>[ LENSES[k].face, k ]));
const LENS_TO_FACE = Object.fromEntries(LENS_ORDER.map(k=>[ k, LENSES[k].face ]));
// ═══════════════════════════════════════════════════
// RULE-BASED CLASSIFIER
// ═══════════════════════════════════════════════════
const STOPWORDS = new Set(['a','an','the','is','it','its','in','on','at','to','of','for','and','or','but','with','by','from','as','are','was','were','be','been','being','have','has','had','do','does','did','will','would','could','should','may','might','can','this','that','these','those','their','they','we','us','our','i','my','you','your','he','she','him','her','his','which','who','what','when','where','how','than','then','so','if','not','no','only','also','just','about','into','through','during','before','after','above','below','between','such','more','most','other','some','any','all','each','both','few','many','much','very','too','s','t','re','ve','ll','d','m']);
// Lens-suggesting keyword rules
const LENS_HINTS = {
counter: ['however','but','wrong','false','actually','contrary','dispute','refute','incorrect','argument','against','disagree','myth','debunk','oppose','challenge'],
opinion: ['think','believe','feel','seems','perhaps','arguably','perspective','view','opinion','suggest','should','might','could','consider','personally','many','some people'],
fiction: ['imagine','story','tale','what if','suppose','fiction','novel','character','narrative','universe','world','dream','fantasy','legend','myth','speculative','sci-fi'],
context: ['history','historical','ancient','century','background','origin','context','because','since','during','era','period','traditionally','science','research','study','discovered'],
unknown: ['unknown','unclear','mystery','uncertain','unsolved','question','wonder','perhaps','maybe','possibly','hypothesis','theory','yet','still','remains','unresolved','enigma'],
};
function tokenise(text) {
const words = text.toLowerCase().replace(/[^a-z0-9\s]/g,' ').split(/\s+/).filter(w=>w.length>2&&!STOPWORDS.has(w));
const bigrams = [];
for(let i=0;i<words.length-1;i++) if(!STOPWORDS.has(words[i])&&!STOPWORDS.has(words[i+1])) bigrams.push(words[i]+'_'+words[i+1]);
return { words, bigrams, all:[...words,...bigrams] };
}
function feedMemory(mem,tokens) { for(const t of tokens.all) mem.set(t,(mem.get(t)||0)+1); }
function scoreSimilarity(tokens, mem) {
if(!mem.size) return 0;
let w=0;
for(const t of tokens.all) if(mem.has(t)) w+=t.includes('_')?2:1;
for(const word of tokens.words) { const root=word.slice(0,5); for(const [mt] of mem) if(!mt.includes('_')&&mt.slice(0,5)===root&&!tokens.all.includes(mt)) w+=0.5; }
const max=tokens.all.length*2+tokens.words.length;
return max>0?Math.min(1,w/Math.max(max*0.4,3)):0;
}
// Suggest which lens a piece of text should go on, based on language cues
function suggestLens(text) {
const lower = text.toLowerCase();
let best = null, bestScore = 0;
for(const [lens, hints] of Object.entries(LENS_HINTS)) {
const score = hints.filter(h=>lower.includes(h)).length;
if(score>bestScore) { bestScore=score; best=lens; }
}
return bestScore>0 ? best : null;
}
function deriveTopicLabel(mem, existing='') {
if(existing&&existing!=='NEW NODE'&&existing!=='INITIALISING') return existing;
const sorted=[...mem.entries()].filter(([t])=>!t.includes('_')).sort((a,b)=>b[1]-a[1]);
return sorted.slice(0,3).map(([t])=>t).join(' ').toUpperCase().slice(0,22)||'DATA NODE';
}
function classifyToNode(text, nodes) {
const tokens=tokenise(text);
const candidates=[];
for(const node of nodes) {
const score=scoreSimilarity(tokens,node.memory);
if(score>0.08) candidates.push({nodeId:node.id,score,label:node.topic});
}
candidates.sort((a,b)=>b.score-a.score);
return {tokens,candidates};
}
// ═══════════════════════════════════════════════════
// PERSISTENCE
// ═══════════════════════════════════════════════════
const STORAGE_KEY='datacube_v3';
function saveState(){
try{
localStorage.setItem(STORAGE_KEY,JSON.stringify({nextId,totalEntries,nodes:nodes.map(n=>({id:n.id,topic:n.topic,entries:n.entries,memory:[...n.memory.entries()],position:n.position,velocity:n.velocity, notes: n.notes || [], locked: n.locked}))}));
}catch(e){}
// refresh open panels live
if(document.getElementById('layer-panel').classList.contains('open')){ buildLayerTabs(); renderLayerCards(activeLayerTab); }
if(document.getElementById('search-panel').classList.contains('open')) runSearch();
}
function loadState(){
try{
const raw=localStorage.getItem(STORAGE_KEY); if(!raw) return false;
const data=JSON.parse(raw);
nextId=data.nextId||0; totalEntries=data.totalEntries||0;
for(const nd of data.nodes){
const node={id:nd.id,topic:nd.topic,entries:nd.entries,memory:new Map(nd.memory),el:null,position:nd.position||{x:(Math.random()-0.5)*40,y:(Math.random()-0.5)*40,z:(Math.random()-0.5)*40},velocity:nd.velocity||{x:0,y:0,z:0}, notes: nd.notes || [], locked: nd.locked || false};
nodes.push(node);
const el=createCubeEl(node);
el.style.transform=`translate3d(${node.position.x-75}px,${node.position.y-75}px,${node.position.z}px)`;
}
updateMeta(); return true;
}catch(e){return false;}
}
// ═══════════════════════════════════════════════════
// DATA MODEL
// ═══════════════════════════════════════════════════
let nodes=[], nextId=0, totalEntries=0, focusedNode=null, IS_REMOTE_ACTION = false, selectedCubes = new Set(), similarityCache = new Map();
function makeNode(topic=''){
return {id:nextId++,topic,entries:[],memory:new Map(),el:null,position:{x:(Math.random()-0.5)*40,y:(Math.random()-0.5)*40,z:(Math.random()-0.5)*40},velocity:{x:0,y:0,z:0}, notes: [], locked: false};
}
function getLensEntry(node, lensKey) {
return node.entries.find(e=>e.lens===lensKey);
}
function getFreeLenses(node) {
return LENS_ORDER.filter(k=>!getLensEntry(node,k));
}
// ═══════════════════════════════════════════════════
// BATCH OPERATIONS
// ═══════════════════════════════════════════════════
function toggleSelect(node, isMultiSelect) {
if (!isMultiSelect) {
const wasOnlySelection = selectedCubes.size === 1 && selectedCubes.has(node.id);
selectedCubes.clear();
if (!wasOnlySelection) {
selectedCubes.add(node.id);
}
} else {
if (selectedCubes.has(node.id)) {
selectedCubes.delete(node.id);
} else {
selectedCubes.add(node.id);
}
}
updateSelectionVisuals();
updateBatchPanel();
}
function updateSelectionVisuals() {
nodes.forEach(n => {
if (n.el) {
const body = n.el.querySelector('.cube-body');
body.classList.toggle('selected', selectedCubes.has(n.id));
}
});
}
function updateBatchPanel() {
const panel = document.getElementById('batch-panel');
const countEl = document.getElementById('batch-count');
const count = selectedCubes.size;
if (count > 0) {
countEl.textContent = `${count} CUBE${count > 1 ? 'S' : ''} SELECTED`;
panel.classList.add('visible');
} else {
panel.classList.remove('visible');
}
document.getElementById('batch-merge-btn').disabled = count < 2;
}
function clearSelection() {
selectedCubes.clear();
updateSelectionVisuals();
updateBatchPanel();
}
function batchDelete() {
const count = selectedCubes.size;
if (count === 0) return;
if (confirm(`Delete ${count} selected cube(s)? This cannot be undone.`)) {
const toDelete = [...selectedCubes].map(id => nodes.find(n => n.id === id)).filter(Boolean);
toDelete.forEach(node => deleteCube(node));
clearSelection();
toast(`${toDelete.length} CUBES DELETED`);
}
}
function batchMerge() {
const count = selectedCubes.size;
if (count < 2) return;
if (confirm(`Merge ${count} cubes into one? The original cubes will be deleted.`)) {
const selectedNodes = [...selectedCubes].map(id => nodes.find(n => n.id === id)).filter(Boolean);
const newNode = makeNode('MERGED NODE');
nodes.push(newNode);
const el = createCubeEl(newNode);
el.classList.add('appearing');
setTimeout(() => el.classList.remove('appearing'), 800);
const allEntries = selectedNodes.flatMap(n => n.entries);
for (const lens of LENS_ORDER) { const entryForLens = allEntries.find(e => e.lens === lens); if (entryForLens) commitToLens(entryForLens.text, newNode, lens); }
selectedNodes.forEach(node => deleteCube(node));
clearSelection(); toast(`${count} CUBES MERGED`); jumpToCube(newNode);
}
}
// ═══════════════════════════════════════════════════
// 3D ORBIT + ZOOM
// ═══════════════════════════════════════════════════
let az=25,el=-18,zoom=1.0;
const LOD_ZOOM_CLUSTER = 0.0;
const LOD_ZOOM_CUBE = 1.2;
const ZOOM_MIN=0.25,ZOOM_MAX=3.0;
let drag=null,pinchStartDist=null,pinchStartZoom=null;
const stage=document.getElementById('stage');
const world=document.getElementById('world');
function applyOrbit(){ stage.style.transform=`scale(${zoom}) rotateX(${el}deg) rotateY(${az}deg)`; }
function pt(e){return e.touches?e.touches[0]:e;}
world.addEventListener('mousedown',e=>startDrag(e));
world.addEventListener('touchstart',e=>startDrag(e),{passive:false});
window.addEventListener('mousemove',e=>moveDrag(e));
window.addEventListener('touchmove',e=>moveDrag(e),{passive:false});
window.addEventListener('mouseup',()=>{drag=null;});
window.addEventListener('touchend',e=>{if(e.touches.length<2)pinchStartDist=null;if(e.touches.length===0)drag=null;});
world.addEventListener('wheel',e=>{
if(e.target.closest('#lens-modal,#overlay,#input-bar,#import-modal'))return;
e.preventDefault();
zoom=Math.min(ZOOM_MAX,Math.max(ZOOM_MIN,zoom*(e.deltaY>0?0.92:1.08)));
applyOrbit();
},{passive:false});
function startDrag(e){
if(e.target.closest('#lens-modal,#overlay,#input-bar,#import-modal'))return;
e.preventDefault();
if(e.touches&&e.touches.length===2){pinchStartDist=Math.hypot(e.touches[0].clientX-e.touches[1].clientX,e.touches[0].clientY-e.touches[1].clientY);pinchStartZoom=zoom;drag=null;return;}
const p=pt(e); drag={x:p.clientX,y:p.clientY,az,el};
document.getElementById('orbit-hint').style.opacity='0';
}
function moveDrag(e){
if(e.touches&&e.touches.length===2&&pinchStartDist!==null){e.preventDefault();const d=Math.hypot(e.touches[0].clientX-e.touches[1].clientX,e.touches[0].clientY-e.touches[1].clientY);zoom=Math.min(ZOOM_MAX,Math.max(ZOOM_MIN,pinchStartZoom*(d/pinchStartDist)));applyOrbit();return;}
if(!drag)return;e.preventDefault();const p=pt(e);
az=drag.az+(p.clientX-drag.x)*0.45;
el=Math.max(-80,Math.min(80,drag.el-(p.clientY-drag.y)*0.35));
applyOrbit();
}
applyOrbit();
// ═══════════════════════════════════════════════════
// CLUSTER ENGINE
// ═══════════════════════════════════════════════════
const CLUSTER_THRESHOLD = 0.3;
const CLUSTER_MIN_SIZE = 3;
let activeClusters = [];
function mergeMemories(clusterNodes) {
const merged = new Map();
for(const n of clusterNodes) {
for(const [k,v] of n.memory) merged.set(k, (merged.get(k)||0)+v);
}
return merged;
}
function detectClusters() {
const adj = new Map();
nodes.forEach(n => adj.set(n.id, []));
// Build Graph
for(let i=0; i<nodes.length; i++){
for(let j=i+1; j<nodes.length; j++){
const sim = computeAttraction(nodes[i], nodes[j]);
if(sim >= CLUSTER_THRESHOLD){
adj.get(nodes[i].id).push(nodes[j].id);
adj.get(nodes[j].id).push(nodes[i].id);
}
}
}
// Find Components
const visited = new Set();
const components = [];
for(const node of nodes){
if(visited.has(node.id)) continue;
const comp = [];
const queue = [node.id];
visited.add(node.id);
while(queue.length){
const currId = queue.shift();
comp.push(currId);
const neighbors = adj.get(currId) || [];
for(const nid of neighbors){
if(!visited.has(nid)){
visited.add(nid);
queue.push(nid);
}
}
}
if(comp.length >= CLUSTER_MIN_SIZE) components.push(comp);
}
// Render Units
document.querySelectorAll('.cluster-label').forEach(el => el.remove());
document.querySelectorAll('.cluster-meta-cube').forEach(el => el.remove());
activeClusters = [];
components.forEach(ids => {
const clusterNodes = ids.map(id => nodes.find(n => n.id === id));
const merged = mergeMemories(clusterNodes);
const mainTopic = deriveTopicLabel(merged, 'CLUSTER').replace('NEW NODE','UNNAMED CLUSTER');
const el = document.createElement('div');
el.className = 'cluster-label';
el.innerHTML = `<span style="opacity:0.6">CLUSTER //</span> ${mainTopic}`;
stage.appendChild(el);
const clusterObj = { ids, el };
createMetaCube(clusterObj);
activeClusters.push(clusterObj);
});
checkFission();
}
function createMetaCube(cluster) {
const size = 60 + Math.min(cluster.ids.length * 8, 80);
cluster.metaSize = size;
const el = document.createElement('div');
el.className = 'cluster-meta-cube';
// Position will be set in updateClusterVisuals, but init here
el.style.cssText = `width:${size}px; height:${size}px; opacity:0; transition:opacity 0.4s;`;
// Add glowing faces
const colors = ['#00d4ff','#ff4e4e','#a855f7','#f59e0b','#10b981','#6b7a99'];
const transforms = ['translateZ('+size/2+'px)', 'rotateY(180deg) translateZ('+size/2+'px)', 'rotateY(-90deg) translateZ('+size/2+'px)', 'rotateY(90deg) translateZ('+size/2+'px)', 'rotateX(90deg) translateZ('+size/2+'px)', 'rotateX(-90deg) translateZ('+size/2+'px)'];
colors.forEach((col, i) => {
const face = document.createElement('div');
face.style.cssText = `
position:absolute; width:100%; height:100%;
background:${col}; opacity:0.1;
transform: ${transforms[i]};
border:1px solid ${col}; box-shadow:0 0 40px ${col};
backface-visibility:visible;
`;
el.appendChild(face);
});
stage.appendChild(el);
cluster.metaEl = el;
return el;
}
const FISSION_THRESHOLD = 0.6; // 1.0 = distinct, 0.0 = identical
const FISSION_MIN_SIZE = 6;
function getCentroid(nodes) {
const cent = new Map();
for(const n of nodes) for(const [k,v] of n.memory) cent.set(k, (cent.get(k)||0) + v);
return cent;
}
function cosineSim(vecA, vecB) {
let dot=0, magA=0, magB=0;
for(const v of vecA.values()) magA+=v*v;
for(const v of vecB.values()) magB+=v*v;
if(!magA || !magB) return 0;
for(const [k,vA] of vecA) if(vecB.has(k)) dot += vA * vecB.get(k);
return dot / (Math.sqrt(magA) * Math.sqrt(magB));
}
function computeKeywordVariance(nodes) {
if(nodes.length<2) return 0;
const c = getCentroid(nodes);
let sum = 0;
for(const n of nodes) sum += (1 - cosineSim(n.memory, c));
return sum / nodes.length;
}
function kMeansSplit(nodes) {
let c1 = nodes[0].memory, c2 = nodes[nodes.length-1].memory;
if(nodes.length>2) { c1=nodes[Math.floor(Math.random()*nodes.length)].memory; do{c2=nodes[Math.floor(Math.random()*nodes.length)].memory}while(c1===c2); }
let gA=[], gB=[];
for(let i=0;i<4;i++){
gA=[]; gB=[];
for(const n of nodes) {
if((1-cosineSim(n.memory,c1)) < (1-cosineSim(n.memory,c2))) gA.push(n); else gB.push(n);
}
if(!gA.length||!gB.length) break;
c1=getCentroid(gA); c2=getCentroid(gB);
}
if(!gA.length||!gB.length){ const h=Math.floor(nodes.length/2); gA=nodes.slice(0,h); gB=nodes.slice(h); }
return [gA, gB];
}
function checkFission() {
for(const c of activeClusters) {
const cNodes = c.ids.map(id => nodes.find(n => n.id === id)).filter(n=>n);
if(cNodes.length < FISSION_MIN_SIZE) continue;
const v = computeKeywordVariance(cNodes);
if(v > FISSION_THRESHOLD || cNodes.length > 12) {
const [subA, subB] = kMeansSplit(cNodes);
// Animate
cNodes.forEach(n => { if(n.el) n.el.classList.add('splitting'); });
c.el.style.opacity = '0';
setTimeout(() => {
c.el.remove();
const kick = { x:(Math.random()-0.5), y:(Math.random()-0.5), z:(Math.random()-0.5) };
const mag = Math.hypot(kick.x,kick.y,kick.z)||1;
const apply = (g, dir) => g.forEach(n => {
if(n.el) { n.el.classList.remove('splitting'); n.el.classList.add('appearing'); setTimeout(()=>n.el?.classList.remove('appearing'),800); }
n.velocity.x += (kick.x/mag) * dir * 2.5; n.velocity.y += (kick.y/mag) * dir * 2.5; n.velocity.z += (kick.z/mag) * dir * 2.5;
});
apply(subA, 1); apply(subB, -1);
toast('CLUSTER FISSION DETECTED — REORGANISING');
activeClusters = activeClusters.filter(x => x !== c);
}, 600);
}
}
}
function updateClusterVisuals() {
for(const c of activeClusters) {
let sx=0, sy=0, sz=0, count=0;
for(const id of c.ids) {
const n = nodes.find(x => x.id === id);
if(n) { sx+=n.position.x; sy+=n.position.y; sz+=n.position.z; count++; }
}
if(count > 0) {
const cx = sx/count, cy = sy/count, cz = sz/count;
c.el.style.transform = `translate3d(${cx}px, ${cy}px, ${cz}px) translate(-50%, -50%)`;
if(c.metaEl) c.metaEl.style.transform = `translate3d(${cx - c.metaSize/2}px, ${cy - c.metaSize/2}px, ${cz}px)`;
}
}
}
function updateLOD() {
if(timelineActive) return;
const isClusterView = zoom < LOD_ZOOM_CLUSTER;
// Cluster Labels
activeClusters.forEach(c => {
if(c.el) c.el.style.display = isClusterView ? 'block' : 'none';
if(c.metaEl) c.metaEl.style.opacity = isClusterView ? '1' : '0';
});
if(isClusterView) {
activeClusters.forEach(c => {
c.ids.forEach(id => {
const n = nodes.find(x => x.id === id);
if(n && n.el) n.el.style.display = 'none';
});
});
} else {
nodes.forEach(n => { if(n.el) n.el.style.display = ''; });
}
}
// GRAVITY & ATTRACTION
// ═══════════════════════════════════════════════════
const edgePool = [];
const EDGE_THRESHOLD = 0.15;
function getEdgeEl(i) {
if(edgePool[i]) return edgePool[i];
const edgeEl = document.createElement('div');
edgeEl.className = 'edge-line';
stage.insertBefore(edgeEl, stage.firstChild);
edgePool.push(edgeEl);
return edgeEl;
}
function drawEdges() {
let edgeIdx = 0;
for(let i=0; i<nodes.length; i++){
for(let j=i+1; j<nodes.length; j++){
const A = nodes[i];
const B = nodes[j];
const sim = computeAttraction(A, B);
if(sim > EDGE_THRESHOLD) {
const el = getEdgeEl(edgeIdx++);
const dx = B.position.x - A.position.x;
const dy = B.position.y - A.position.y;
const dz = B.position.z - A.position.z;
const dist = Math.sqrt(dx*dx + dy*dy + dz*dz);
const ry = Math.atan2(dz, dx);
const rz = Math.atan2(dy, Math.sqrt(dx*dx + dz*dz));
el.style.width = `${dist}px`;
el.style.transform = `translate3d(${A.position.x}px, ${A.position.y}px, ${A.position.z}px) rotateY(${ry}rad) rotateZ(${rz}rad)`;
let opacity = Math.max(0, (sim - 0.1) * 3 - (dist/800));
if (focusedNode) {
const isFocusedEdge = (A.id === focusedNode.id || B.id === focusedNode.id);
if (!isFocusedEdge) opacity *= 0.1; // Dim unfocused edges
}
el.style.opacity = opacity;
el.style.display = '';
el.style.transition = 'box-shadow 0.5s';
el.style.boxShadow = `0 0 ${5 + Math.sin(Date.now() * 0.003) * 3}px var(--holo)`;
el.setAttribute('data-strength', sim.toFixed(2));
el.title = `${Math.round(sim*100)}% similarity`;
el.onclick = (e) => {
e.stopPropagation();
toast(`CONNECTION STRENGTH: ${Math.round(sim*100)}% · ${A.topic} ↔ ${B.topic}`);
};
}
}
}
for(let k=edgeIdx; k<edgePool.length; k++) edgePool[k].style.display = 'none';
}
function getSimCacheKey(idA, idB) {
return idA < idB ? `${idA}-${idB}` : `${idB}-${idA}`;
}
function invalidateNodeCache(nodeId) {
const nodeIdStr = String(nodeId);
const keysToDelete = [];
for (const key of similarityCache.keys()) {
const ids = key.split('-');
if (ids[0] === nodeIdStr || ids[1] === nodeIdStr) {
keysToDelete.push(key);
}
}
for (const key of keysToDelete) {
similarityCache.delete(key);
}
}
function computeAttraction(nodeA, nodeB) {
const cacheKey = getSimCacheKey(nodeA.id, nodeB.id);
if (similarityCache.has(cacheKey)) return similarityCache.get(cacheKey);
// Get top 10 keywords from each
const vecA = [...nodeA.memory.entries()]
.sort((a,b) => b[1] - a[1])
.slice(0,10)
.map(([k]) => k);
const vecB = [...nodeB.memory.entries()]
.sort((a,b) => b[1] - a[1])
.slice(0,10)
.map(([k]) => k);
// Jaccard similarity
const intersection = vecA.filter(k => vecB.includes(k)).length;
const union = new Set([...vecA, ...vecB]).size;
const sim = union === 0 ? 0 : intersection / union; // 0 to 1
similarityCache.set(cacheKey, sim);
return sim;
}
let animFrame;
const REPULSION = 280000;
const CENTER_GRAVITY = 0.0008;
const ATTRACTION = 0.03;
const MAX_VEL = 2.0;
function tickGravity() {
for(let i=0;i<nodes.length;i++){
const A=nodes[i];
if(!A.velocity) A.velocity={x:0,y:0,z:0};
// Center pull
A.velocity.x -= A.position.x * CENTER_GRAVITY;
A.velocity.y -= A.position.y * CENTER_GRAVITY;
A.velocity.z -= A.position.z * CENTER_GRAVITY;
for(let j=0;j<nodes.length;j++){
if(i===j) continue;
const B=nodes[j];
const dx = A.position.x - B.position.x;
const dy = A.position.y - B.position.y;
const dz = A.position.z - B.position.z;
let distSq = dx*dx + dy*dy + dz*dz;
if(distSq<100) distSq=100;
const dist = Math.sqrt(distSq);
// Repulsion
const fRep = REPULSION / (distSq * dist);
A.velocity.x += dx * fRep;
A.velocity.y += dy * fRep;
A.velocity.z += dz * fRep;
// Attraction
const sim = computeAttraction(A, B);
if(sim > 0) {
const fAtt = sim * ATTRACTION;
A.velocity.x -= dx * fAtt;
A.velocity.y -= dy * fAtt;
A.velocity.z -= dz * fAtt;
}
}
}
// Update
for(const n of nodes){
// Damping
n.velocity.x *= 0.94;
n.velocity.y *= 0.94;
n.velocity.z *= 0.94;
// Cap
const vSq = n.velocity.x**2 + n.velocity.y**2 + n.velocity.z**2;
if(vSq > MAX_VEL*MAX_VEL){
const sc = MAX_VEL / Math.sqrt(vSq);
n.velocity.x*=sc; n.velocity.y*=sc; n.velocity.z*=sc;
}
n.position.x += n.velocity.x;
n.position.y += n.velocity.y;
n.position.z += n.velocity.z;
if(n.el) {
let transform = `translate3d(${n.position.x-75}px,${n.position.y-75}px,${n.position.z}px)`;
if(n.locked) transform += ` rotateY(${-az}deg) rotateX(${-el}deg)`;
n.el.style.transform = transform;
}
}
updateClusterVisuals();
drawEdges();
updateLOD();
animFrame = requestAnimationFrame(tickGravity);
}
function repositionAll(){
// No-op: gravity loop handles layout now
}
// ═══════════════════════════════════════════════════
// RENDER CUBE
// ═══════════════════════════════════════════════════
function createCubeEl(node){
const wrap=document.createElement('div');
wrap.className='cube-entity'; wrap.dataset.nodeId=node.id;
const body=document.createElement('div');
body.className='cube-body';
LENS_ORDER.forEach(lensKey=>{
const L=LENSES[lensKey];
const face=document.createElement('div');
face.className=`face face-${L.face}`; face.dataset.lens=lensKey;
['tl','tr','bl','br'].forEach(p=>{const fc=document.createElement('div');fc.className=`fc ${p}`;face.appendChild(fc);});
const iconEl=document.createElement('div'); iconEl.className='face-lens-icon'; iconEl.textContent=L.icon;
const labelEl=document.createElement('div'); labelEl.className='face-label'; labelEl.textContent=L.name;
const textEl=document.createElement('div'); textEl.className='face-text';
const hintEl=document.createElement('div'); hintEl.className='face-empty-hint'; hintEl.textContent=L.hint;
face.appendChild(iconEl); face.appendChild(labelEl); face.appendChild(textEl); face.appendChild(hintEl);
body.appendChild(face);
face.addEventListener('click', e => {
e.stopPropagation();
toggleSelect(node, e.shiftKey);
});
face.addEventListener('dblclick',e=>{
e.stopPropagation();
const entry=getLensEntry(node,lensKey);
if(entry) openExpand(entry,node,lensKey);
else openLensPicker(null,node,[lensKey]); // tap empty face → add to that lens
});
});
const topicEl=document.createElement('div'); topicEl.className='cube-topic'; topicEl.textContent=node.topic;
// pip row
const pipsEl=document.createElement('div'); pipsEl.className='cube-pips';
LENS_ORDER.forEach(k=>{
const pip=document.createElement('div'); pip.className='cube-pip'; pip.dataset.lensKey=k;
pip.style.setProperty('--pip-c',LENSES[k].color);
pipsEl.appendChild(pip);
});
const notesIndicator = document.createElement('div');
notesIndicator.className = 'cube-notes-indicator';
notesIndicator.innerHTML = '<svg width="10" height="10" viewBox="0 0 12 12" fill="none"><path d="M1 1h10v7H6L3 11V8H1V1z" stroke="currentColor" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round"/></svg>';
notesIndicator.title = 'This cube has private notes';
const shadow=document.createElement('div'); shadow.className='cube-shadow';
wrap.appendChild(body); wrap.appendChild(topicEl); wrap.appendChild(pipsEl); wrap.appendChild(notesIndicator); wrap.appendChild(shadow);
stage.appendChild(wrap);
node.el=wrap;
updateCubeEl(node);
return wrap;
}
function _updateFace(faceEl, pipEl, entry) {
const textEl = faceEl.querySelector('.face-text');
const hintEl = faceEl.querySelector('.face-empty-hint');
if (entry) {
faceEl.classList.add('has-data');
textEl.textContent = entry.text;
if (hintEl) hintEl.style.display = 'none';
if (pipEl) pipEl.classList.add('filled');
} else {
faceEl.classList.remove('has-data');
textEl.textContent = '';
if (hintEl) hintEl.style.display = '';
if (pipEl) pipEl.classList.remove('filled');
}
}
function updateCubeEl(node){
if(!node.el)return;
const topicEl=node.el.querySelector('.cube-topic');
if(topicEl) topicEl.textContent=node.topic;
LENS_ORDER.forEach(lensKey=>{
const L=LENSES[lensKey];
const faceEl=node.el.querySelector(`.face-${L.face}`);
const pipEl=node.el.querySelector(`.cube-pip[data-lens-key="${lensKey}"]`);
if(!faceEl) return;
const entry=getLensEntry(node,lensKey);
_updateFace(faceEl, pipEl, entry);
});
const notesIndicator = node.el.querySelector('.cube-notes-indicator');
if (notesIndicator) {
notesIndicator.classList.toggle('has-notes', node.notes && node.notes.length > 0);
}
}
// ═══════════════════════════════════════════════════
// LENS PICKER MODAL
// ═══════════════════════════════════════════════════
let _lensResolve=null;
function openLensPicker(text, targetNode, forceLenses=null){
return new Promise(resolve=>{
_lensResolve=resolve;
const modal=document.getElementById('lens-modal');
if(text){
document.getElementById('lens-sub').textContent='Choose which perspective lens to store this on. The classifier has suggested options based on language cues.';
document.getElementById('lens-entry-preview').textContent=text;
} else {
document.getElementById('lens-sub').textContent='This face is empty. Add a perspective entry to it:';
document.getElementById('lens-entry-preview').style.display='none';
}
if(targetNode){
document.getElementById('lens-target-info').textContent=`TARGET CUBE: ${targetNode.topic.toUpperCase()}`;
} else {
document.getElementById('lens-target-info').textContent='';
}
const grid=document.getElementById('lens-grid');
grid.innerHTML='';
const allowedLenses = forceLenses || LENS_ORDER;
const suggested = text ? suggestLens(text) : null;
allowedLenses.forEach(lensKey=>{
const L=LENSES[lensKey];
const alreadyFilled = targetNode && getLensEntry(targetNode,lensKey);
const btn=document.createElement('button');
btn.className=`lens-btn${alreadyFilled?' disabled':''}`;
btn.dataset.lens=lensKey;
btn.style.setProperty('--lc',L.color);
const suggestBadge = (lensKey===suggested&&!alreadyFilled) ? ' ◀ SUGGESTED' : '';
btn.innerHTML=`<span class="lens-btn-icon">${L.icon}</span><span class="lens-btn-name">${L.name}${suggestBadge}</span><span class="lens-btn-desc">${L.desc}</span>${alreadyFilled?`<span class="lens-btn-filled">⬤ ALREADY FILLED</span>`:''}`;
if(!alreadyFilled){
btn.addEventListener('click',()=>{
closeLensPicker();
if(text===null){
// prompt for text then resolve
promptTextForLens(lensKey,targetNode,resolve);
} else {
resolve({action:'place',lensKey,targetNodeId:targetNode?.id});
}
});
}
grid.appendChild(btn);
});
// new node option (only if text is provided and it's not a forced-face tap)
const newBtn=document.getElementById('lens-new-btn');
if(text&&!forceLenses){
newBtn.style.display='';
newBtn.onclick=()=>{ closeLensPicker(); resolve({action:'new'}); };
} else {
newBtn.style.display='none';
}
document.getElementById('lens-cancel-btn').onclick=()=>{ closeLensPicker(); resolve({action:'cancel'}); };
modal.style.display='flex';
requestAnimationFrame(()=>modal.classList.add('open'));
});
}
function promptTextForLens(lensKey, targetNode, resolve){
const L=LENSES[lensKey];
const text=window.prompt(`Enter ${L.name} for "${targetNode.topic}":\n\n${L.hint}`);
if(text&&text.trim()){
commitToLens(text.trim(),targetNode,lensKey);
resolve({action:'done'});
} else {
resolve({action:'cancel'});
}
}
function closeLensPicker(){
const modal=document.getElementById('lens-modal');
modal.classList.remove('open');
setTimeout(()=>{ modal.style.display='none'; document.getElementById('lens-entry-preview').style.display=''; },300);
}
// ═══════════════════════════════════════════════════
// CORE: place text on a specific lens of a node
// ═══════════════════════════════════════════════════
function commitToLens(text, node, lensKey){
if(getLensEntry(node,lensKey)) return; // already filled
const tokens=tokenise(text);
node.entries.push({lens:lensKey,text,addedAt:Date.now()});
totalEntries++;
feedMemory(node.memory,tokens);
if(lensKey==='fact') node.topic=deriveTopicLabel(node.memory,node.topic);
invalidateNodeCache(node.id);
updateCubeEl(node);
const L=LENSES[lensKey];
const faceEl=node.el?.querySelector(`.face-${L.face}`);
if(faceEl){ faceEl.style.animation='faceFlash 0.8s ease forwards'; setTimeout(()=>{faceEl.style.animation='';},800); }
// Flash world briefly for full cube
if(node.entries.length>=6){
world.style.transition='filter 0.1s'; world.style.filter='brightness(1.4)';
setTimeout(()=>{world.style.filter='';},150);
toast(`CUBE COMPLETE — ALL 6 LENSES FILLED`);
}
updateMeta(); saveState();
if(nodes.length>2) detectClusters();
return lensKey;
}
// ═══════════════════════════════════════════════════
// ADD ENTRY FLOW
// ═══════════════════════════════════════════════════
const AUTO_ROUTE=0.42;
const ASK_THRESHOLD=0.12;
async function addEntry(text){
if(!text.trim()) return;
const tokens=tokenise(text);
const {candidates}=classifyToNode(text,nodes);
const best=candidates[0];
// Step 1: determine target node
let targetNode=null;
if(!best||best.score<ASK_THRESHOLD){
// No match — this becomes a new cube seeded with FACT
const newTokens = tokenise(text);
const tempMem = new Map();
feedMemory(tempMem, newTokens);
targetNode = makeNode(deriveTopicLabel(tempMem, '') || 'NEW NODE');
nodes.push(targetNode);
const el=createCubeEl(targetNode);
el.classList.add('appearing'); setTimeout(()=>el.classList.remove('appearing'),800);
repositionAll();
commitToLens(text,targetNode,'fact');
targetNode.position.x+=(Math.random()-0.5)*20; // jitter
toast(`NEW CUBE — ${targetNode.topic.toUpperCase()}`);
return;
}
if(best.score>=AUTO_ROUTE){
targetNode=nodes.find(n=>n.id===best.nodeId);
toast(`MATCHED → ${targetNode.topic.toUpperCase()} (${Math.round(best.score*100)}%)`);
} else {
// Ambiguous: ask which node (re-use lens modal heading)
// For simplicity we use the best match but ask which lens
targetNode=nodes.find(n=>n.id===best.nodeId);
}
// Step 2: determine which lens
const freeLenses=getFreeLenses(targetNode);
if(!freeLenses.length){ toast('ALL LENSES FULL — SPAWNING NEW CUBE'); addEntryAsNew(text); return; }
const suggested=suggestLens(text);
let chosenLens=null;
// If the suggested lens is free AND score is confident → auto place
if(suggested&&freeLenses.includes(suggested)&&best.score>=AUTO_ROUTE){
chosenLens=suggested;
commitToLens(text,targetNode,chosenLens);
toast(`AUTO → ${targetNode.topic} · ${LENSES[chosenLens].name.toUpperCase()}`);
} else {
// Ask user to pick lens
const result=await openLensPicker(text,targetNode,freeLenses);
if(result.action==='place'){
commitToLens(text,targetNode,result.lensKey);
toast(`STORED → ${targetNode.topic} · ${LENSES[result.lensKey].name.toUpperCase()}`);
} else if(result.action==='new'){
addEntryAsNew(text);
}
}
}
function addEntryAsNew(text){
const tokens=tokenise(text);
const tempMem = new Map();
feedMemory(tempMem, tokens);
const node=makeNode(deriveTopicLabel(tempMem,'')||'NEW NODE');
nodes.push(node);
const el=createCubeEl(node);
el.classList.add('appearing'); setTimeout(()=>el.classList.remove('appearing'),800);
repositionAll();
commitToLens(text,node,'fact');
node.position.x+=(Math.random()-0.5)*20; // jitter
toast(`NEW CUBE — ${node.topic.toUpperCase()}`);
}
// ═══════════════════════════════════════════════════
// EXPAND OVERLAY
// ═══════════════════════════════════════════════════
function openExpand(entry, node, lensKey){
document.getElementById('world').classList.add('focus-active');
if (focusedNode && focusedNode.el) focusedNode.el.classList.remove('focused');
focusedNode = node;
if (node.el) node.el.classList.add('focused');
const L=LENSES[lensKey];
const card=document.getElementById('expand-card');
card.style.setProperty('--expand-lc',L.color);
document.getElementById('expand-lens-icon').textContent=L.icon;
document.getElementById('expand-lens-name').textContent=' '+L.name;
document.getElementById('expand-topic').textContent=`CUBE: ${node.topic.toUpperCase()}`;
document.getElementById('expand-text').textContent=entry.text;
document.getElementById('expand-meta').textContent=`RECORDED ${new Date(entry.addedAt).toLocaleString().toUpperCase()}`;
const lockBtn = document.getElementById('expand-lock');
lockBtn.textContent = node.locked ? 'UNLOCK ROTATION' : 'LOCK ROTATION';
lockBtn.onclick = () => {
node.locked = !node.locked;
lockBtn.textContent = node.locked ? 'UNLOCK ROTATION' : 'LOCK ROTATION';
saveState();
toast(node.locked ? 'CUBE ROTATION LOCKED' : 'CUBE ROTATION UNLOCKED');
};
document.getElementById('expand-delete').onclick = () => {
if(confirm(`Permanently delete cube "${node.topic}"?`)){
deleteCube(node);
closeExpand();
}
};
renderNotes(node);
const noteInput = document.getElementById('expand-note-input');
const addNoteBtn = document.getElementById('expand-note-add-btn');
const addNoteAction = () => { const noteText = noteInput.value.trim(); if (noteText) { addNoteToCube(node, noteText); noteInput.value = ''; renderNotes(node); noteInput.focus(); } };
addNoteBtn.onclick = addNoteAction;
noteInput.onkeydown = (e) => { if(e.key === 'Enter') { e.preventDefault(); addNoteAction(); } };
const ov=document.getElementById('overlay');
ov.style.display='flex'; requestAnimationFrame(()=>ov.classList.add('open'));
}
function closeExpand(){
document.getElementById('world').classList.remove('focus-active');
if (focusedNode && focusedNode.el) focusedNode.el.classList.remove('focused');
focusedNode = null;
const ov=document.getElementById('overlay');
ov.classList.remove('open');
setTimeout(()=>{ov.style.display='none';},300);
}
function addNoteToCube(node, noteText) {
if(!node.notes) node.notes = [];
node.notes.push({text: noteText, addedAt: Date.now()});
updateCubeEl(node);
saveState();
}
function renderNotes(node) {
const listEl = document.getElementById('expand-notes-list');
listEl.innerHTML = '';
if (!node.notes || node.notes.length === 0) {
listEl.innerHTML = '<div class="expand-note-item" style="opacity:0.3;font-style:italic;">No private notes for this cube.</div>';
return;
}
node.notes.slice().reverse().forEach(note => { // show newest first
const item = document.createElement('div');
item.className = 'expand-note-item';
const dateStr = new Date(note.addedAt).toLocaleString('en-GB', { day:'numeric', month:'short', hour:'2-digit', minute:'2-digit' }).toUpperCase();
item.innerHTML = `${escHtml(note.text)}<div class="expand-note-meta">${dateStr}</div>`;
listEl.appendChild(item);
});
}
function deleteCube(node){
if(node.el) node.el.remove();
if (focusedNode && focusedNode.id === node.id) closeExpand();
nodes = nodes.filter(n => n.id !== node.id);
totalEntries -= node.entries.length;
invalidateNodeCache(node.id);
updateMeta();
detectClusters();
saveState();
toast('CUBE DELETED');