-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathinit.js
3873 lines (3273 loc) · 154 KB
/
init.js
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
// Version info
const VERSION = '03.02.25'; // Last modified date
// Online info
const HOST = 'https://dangarte.github.io/epi-embedding-maps-viewer';
const INDEX_URL = `${HOST}/data/index.json`;
const ISLOCAL = !window.location?.href?.startsWith(HOST);
const SELECTED_DATA_FROM_URL = !ISLOCAL ? new URLSearchParams(window.location.search).get('json-id') || null : null;
// Preferences
const IS_DARK = window.matchMedia('(prefers-color-scheme: dark)').matches;
const IS_REDUCED_MOTION = window.matchMedia(`(prefers-reduced-motion: reduce)`).matches;
// Settings structure in local storage
const SETTINGS_PREFIX = 'epi-embedding-maps-viewer--';
const SETTINGS = {
'render-engine': { default: '2d', options: [ '2d', 'webgl2', 'dom' ], titles: { '2d': 'Canvas 2d', 'webgl2': 'Canvas WebGL2', 'dom': 'HTML Elements' } },
'graph-line-style': { default: 'C', options: [ 'C', 'Q', 'L', 'S' ], titles: { 'C': 'Cubic curve', 'Q': 'Quadratic curve', 'L': 'Linear', 'S': 'Straight' } },
};
function tryGetSetting(settingKey, otherDefault) {
if (!SETTINGS[settingKey]) {
console.error(`Unknown setting: ${settingKey}`);
return otherDefault;
}
try {
const value = localStorage.getItem(SETTINGS_PREFIX + settingKey);
if (SETTINGS[settingKey].options.includes(value)) return value;
else return otherDefault ?? SETTINGS[settingKey].default;
} catch(_) {
return otherDefault ?? SETTINGS[settingKey].default;
}
}
function trySetSetting(settingKey, settingValue) {
if (!SETTINGS[settingKey]) {
console.error(`Unknown setting: ${settingKey}`);
return;
}
try {
const value = SETTINGS[settingKey].options.includes(settingValue) ? settingValue : SETTINGS[settingKey].default;
localStorage.setItem(SETTINGS_PREFIX + settingKey, value);
} catch(_) {
console.error(_);
return;
}
}
// IndexedDB info
const DB_NAME = 'epi-embedding-maps-viewer';
const DB_VERSION = 2;
// Display options
const PAGE_BACKGROUND = IS_DARK ? '#000' : '#eee';
const CARD_STYLE = {
fontSize: 24,
font: "system-ui, -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, Oxygen, Ubuntu, Cantarell, 'Open Sans', 'Helvetica Neue', sans-serif",
color: IS_DARK ? '#dedfe2' : '#232529',
colorDim: IS_DARK ? '#6d6f76' : '#9da3b2',
backgroundColor: IS_DARK ? '#232529' : '#dedfe2',
btnBackgroundColor: IS_DARK ? '#3b3d45' : '#e3e3e3',
btnBackgroundColorHover: IS_DARK ? '#525660' : '#c8e1ff',
borderColor: IS_DARK ? '#464953' : '#757a8a',
noImageBackground: '#008aff33',
noImageSize: 200,
borderWidth: 1,
padding: 6,
borderRadius: 10,
lineHeight: 1.3,
matchedColor: '#ff272f',
};
let GRAPH_LINE_STYLE = tryGetSetting('graph-line-style'); // Type of curves between cards: C, Q, L. Where C is a cubic curve, Q is a quadratic curve, L is a line
const MOVE_CARDS_HALF_SIZE = true; // Offset the cards by half their size (i.e. so that their center is at the specified coordinates, instead of the upper left corner)
// Optimization
// WARNING: webgl2 for some reason, even with hardware acceleration disabled and the --disable-gpu flag when starting the browser, uses VRAM, but it is VERY fast (compared to 2d or dom)
// NOTE: So if you don't need the browser to use VRAM (for example, you have a small amount of it and you generate images), then DO NOT USE webgl2
const RENDER_ENGINE = tryGetSetting('render-engine') ; // Toggle card rendering method: webgl2, 2d, dom
const CANVAS_SMOOTHING = true; // anti-aliasing
const CANVAS_SMOOTHING_QUALITY = 'low'; // quality of anti-aliasing: low, medium, high
const CANVAS_TEXT_QUALITY = 'optimizeLegibility'; // canvas textRendering option: optimizeSpeed, optimizeLegibility, geometricPrecigion
// Perhaps it makes sense to redesign the preview system from "at a certain size" to "at a certain number on the screen"
const CARD_PREVIEW_SCALING = [ // List of aviable preview scales (Sorted by scale, lower first)
{ id: 'micro', title: 'Micro preview', scale: .017, quality: .65 },
{ id: 'tiny', title: 'Tiny preview', scale: .06, quality: .8 },
{ id: 'small', title: 'Small preview', scale: .145, quality: .95 },
{ id: 'normal', title: 'Normal preview', scale: .36, quality: 1 }, // Recommended set quality to 1 at first preview (because it's more noticeable if it's of lower quality)
// id - Internal size identifier (Must be unique)
// title - Size name, needed to display in status
// scale - Size at which to move to the next quality
// quality - Preview Quality (Internal size multiplier)
];
const CARD_SCALE_PREVIEW = CARD_PREVIEW_SCALING.at(-1).scale; // At this scale elements changed to preview canvas (set to 0 for disable)
const SORT_SEARCH_BY_PROXIMITY = true; // Sort search results by distance. That is, when going to a result, go to the nearest card, instead of the standard order.
const CONVERT_PREVIEW_CANVAS_TO_IMAGE = false; // Convert preview canvas to image (not recommended, it takes a long time to convert, then it takes a long time to "decode image", but use less VRAM (if GPU acceleration is enabled) and fix OOM browser errors)
const PAUSES_LONG_OPERATIONS_EVERY_N_OPERATIONS = 200; // Pauses in long operations every N operations
// Zooming
const SCALE_BASE = .6; // Default Zoom
const SCALE_MAX = 4; // Maximum zoom
const SCALE_MIN = .004; // Minimum zoom
const SCALE_SEARCH = .6; // Zoom when moving to search element
const SCALE_ZOOM_INTENSITY = .18; // Zoom Intensity
// Panning
const PANNING_INERTIA_FRICTION = .95; // Friction force when applying inertia after panning (Less - faster stop)
const PANNING_INERTIA_TOUCH = true; // Apply inertia on touches
const PANNING_INERTIA_MOUSE = false; // Apply inertia on mouse
// Index of sources
const INDEX = [];
// Define icons
const ICON_COPY = document.querySelector('.icon[data-icon="copy"]')?.cloneNode(true);
const ICON_BOOK = document.querySelector('.icon[data-icon="book"]')?.cloneNode(true);
// Insert card styles in page
CARD_STYLE.lineHeight = String(CARD_STYLE.lineHeight);
const cardStyleConfigsElement = insertElement('style', document.head);
cardStyleConfigsElement.textContent = `:root {${Object.keys(CARD_STYLE).map(key => `--card-${key}: ${ typeof CARD_STYLE[key] !== 'number' ? CARD_STYLE[key] : `${CARD_STYLE[key]}px` };`).join(' ')} }`;
CARD_STYLE.lineHeight = Number(CARD_STYLE.lineHeight);
// Checking previews to see if they can be skipped
if (RENDER_ENGINE === 'dom') CARD_PREVIEW_SCALING.forEach(i => i.allowed = false);
else if (RENDER_ENGINE === 'webgl2') {
CARD_PREVIEW_SCALING.forEach(i => i.allowed = false);
CARD_PREVIEW_SCALING.at(-1).allowed = true;
} else if (RENDER_ENGINE === '2d') CARD_PREVIEW_SCALING.forEach(i => i.allowed = true);
// Current viewer state
const STATE = {
selectData: null,
ready: false,
renderController: null,
data: [],
source: {},
previewControllers: {},
renderController: {},
space: 0,
spacing: 50,
mouseX: 0,
mouseY: 0,
velocityX: 0,
velocityY: 0,
mousedown: false,
mousemove: false,
altKey: false,
isZooming: false,
pinchDistance: null,
};
// Controller classes
class DataController {
static supportedDataFormats = [ 'epi-space-v0', 'epi-space-v1', 'epi-graph-v1', 'dangart-v0' ];
static getDataFormat(data) {
if (Array.isArray(data)) return 'epi-space-v0';
if (data.dataFormat === 'dangart-v0') return 'dangart-v0';
if (Array.isArray(data.spaces) && Array.isArray(data.proj)) return 'epi-space-v1';
if (Array.isArray(data.edges) && Array.isArray(data.nodes)) return 'epi-graph-v1';
return 'unknown';
}
static getDataType(data) {
return Array.isArray(data.edges) ? 'graphs' : 'spaces';
}
static normalizeData(data) {
let dataFormat = this.getDataFormat(data);
if (dataFormat === 'unknown') throw new Error('Unknown data format');
// Convert data from old formats
if (dataFormat === 'epi-space-v0') {
dataFormat = 'epi-space-v1';
data = this.#convert__epi_space_v0_to_v1(data);
}
// Convert data to internal format
if (dataFormat === 'dangart-v0') return this.#convert_dangart_v0_to_normal(data);
if (dataFormat === 'epi-space-v1') return this.#convert__epi_space_v1_to_normal(data);
if (dataFormat === 'epi-graph-v1') return this.#convert__epi_graph_v1_to_noraml(data);
}
static #graph_layoutDagre(nodesTree) {
const xGap = 500;
const yGap = 900;
const lastRowHeight = 3;
const nodePositions = new Map();
let currentX = 0;
let i = 0;
function placeNode(branch, depth) {
const y = depth * yGap;
if (branch.branches && branch.branches.length > 0) {
const childXPositions = branch.branches.map(child => placeNode(child, depth + 2));
let xMin = Infinity, xMax = -Infinity;
for (const xPos of childXPositions) {
if (xPos < xMin) xMin = xPos;
if (xPos > xMax) xMax = xPos;
}
const x = (xMin + xMax) / 2;
nodePositions.set(branch.id, { x, y });
return x;
} else {
i++;
const x = currentX;
nodePositions.set(branch.id, { x, y: y + (i%lastRowHeight) * yGap });
currentX += xGap;
return x;
}
}
for (const rootId in nodesTree) {
const rootBranches = nodesTree[rootId];
placeNode({ id: rootId, branches: rootBranches }, 0);
}
return nodePositions;
}
static #graph_layoutCircular(nodesTree) {
const nodeWidth = 400;
const nodeHeight = 800;
const gap = 50;
const nodePositions = new Map();
const applyShift = (shiftX, shiftY, childrens) => {
childrens.forEach(node => {
const pos = node.position;
pos.x += shiftX;
pos.y += shiftY;
if (node.childrens) applyShift(shiftX, shiftY, node.childrens);
});
};
const placeInCirccle = node => {
const childrens = [];
const placeInfo = { id: node.id, width: 0, height: 0, childrens: childrens };
if (node.branches && node.branches.length) {
node.branches.forEach(n => {
if (n.branches && n.branches.length) childrens.push(placeInCirccle(n));
else childrens.push({ id: n.id, width: n.width || nodeWidth, height: n.height || nodeHeight });
});
const totalNodes = childrens.length;
let maxWidth = 0, maxHeight = 0, maxDiameter = 0, circumference = 0;
childrens.forEach(node => {
if (!node.hypot) node.hypot = Math.hypot(node.width, node.height);
if (node.width > maxWidth) maxWidth = node.width;
if (node.height > maxHeight) maxHeight = node.height;
if (node.hypot > maxDiameter) maxDiameter = node.hypot;
circumference += node.hypot;
});
const rC = (circumference + gap * totalNodes) / (2 * Math.PI);
const rD = maxDiameter*.75 + gap * totalNodes;
const useEqual = rD > rC;
const radius = useEqual ? rD : rC;
const diameter = radius * 2;
let minX = Infinity, maxX = -Infinity, minY = Infinity, maxY = -Infinity;
let angle = 0;
const angleIncrement = Math.PI / totalNodes;
childrens.forEach(node => {
angle += useEqual ? angleIncrement : Math.asin((node.hypot + gap)/(2 * diameter)) * 2;
const x = radius * Math.cos(angle);
const y = radius * Math.sin(angle);
const position = { x, y };
if (x > maxX) maxX = x;
if (x < minX) minX = x;
if (y > maxY) maxY = y;
if (y < minY) minY = y;
nodePositions.set(node.id, position);
node.position = position;
if (node.childrens) applyShift(position.x, position.y, node.childrens); // Move all nodes to their new positions
angle += useEqual ? angleIncrement : Math.asin((node.hypot + gap)/(2 * diameter)) * 2;
});
placeInfo.width = Math.abs(maxX - minX) + maxWidth;
placeInfo.height = Math.abs(maxY - minY) + maxHeight;
placeInfo.hypot = diameter + maxDiameter;
const position = { x: placeInfo.width / 2, y: placeInfo.height / 2 };
nodePositions.set(node.id, position);
placeInfo.position = position;
} else {
console.warn(`This shouldn't have activated...`);
nodePositions.set(node.id, { x: 0, y: 0 });
placeInfo.width = node.width || nodeWidth;
placeInfo.height = node.height || nodeHeight;
}
return placeInfo;
};
let shiftX = 0;
for (const rootId in nodesTree) {
const rootBranches = nodesTree[rootId];
const placeInfo = placeInCirccle({ id: rootId, branches: rootBranches });
const position = placeInfo.position;
position.x = shiftX;
position.y = 0;
if (shiftX && placeInfo.childrens) applyShift(shiftX, 0, placeInfo.childrens);
shiftX + placeInfo.width + gap * 4;
}
return nodePositions;
}
static #convert_dangart_v0_to_normal(data) {
data.nodes.forEach((node, i) => {
node.edges = [];
node.index = i;
});
// Find node indices for a graph
if (data.edges) {
const nodesMap = new Map();
data.nodes.forEach(node => nodesMap.set(node.id, node));
data.edges.forEach((edge, i) => {
const nodeFrom = nodesMap.get(edge.from);
const nodeTo = nodesMap.get(edge.to);
if (!nodeFrom.edges.includes(i)) nodeFrom.edges.push(i);
if (!nodeTo.edges.includes(i)) nodeTo.edges.push(i);
edge.indexFrom = nodeFrom.index;
edge.indexTo = nodeTo.index;
});
}
return data;
}
static #convert__epi_graph_v1_to_noraml(data) {
const viewportWidth = window.innerWidth;
const viewportHeight = window.innerHeight;
const width = data.kv.width;
const height = data.kv.height;
const aspectRatio = width && height ? width / height : null;
const newData = {
dataFormat: 'normal',
nodes: data.nodes.map((node, i) => ({ id: node.id, title: node.prompt, index: i, image: node.image, imageAspectRatio: aspectRatio, spaces: [], edges: [] })),
spaces: [],
edges: data.edges,
};
// Find node indices for a graph
const nodesMap = new Map();
const nodesTree = {};
newData.nodes.forEach(node => nodesMap.set(node.id, node));
newData.edges.forEach((edge, i) => {
const nodeFrom = nodesMap.get(edge.from);
const nodeTo = nodesMap.get(edge.to);
if (!nodeFrom.edges.includes(i)) nodeFrom.edges.push(i);
if (!nodeTo.edges.includes(i)) nodeTo.edges.push(i);
edge.indexFrom = nodeFrom.index;
edge.indexTo = nodeTo.index;
if (nodesTree[edge.from]) nodesTree[edge.from].push({ id: edge.to });
else nodesTree[edge.from] = [{ id: edge.to }];
});
const hasParent = new Set();
Object.keys(nodesTree).forEach(branchId => {
const branches = nodesTree[branchId];
branches.forEach((branch, i) => {
if (!branch.branches && nodesTree[branch.id]) {
branch.branches = nodesTree[branch.id];
hasParent.add(branch.id);
}
});
});
Object.keys(nodesTree).forEach(branchId => {
if (hasParent.has(branchId)) delete nodesTree[branchId];
});
const dagreLayout = this.#graph_layoutDagre(nodesTree);
const circularLayout = this.#graph_layoutCircular(nodesTree);
// Create spaces
newData.spaces = ['Dagre Layout', 'Circular Layout', 'FCose Layout (placeholder)', 'Random'];
newData.nodes.forEach(node => {
// Dagre
const dagreSpace = dagreLayout.get(node.id) ?? { x: 0, y: 0 };
node.spaces.push({ x: dagreSpace.x, y: dagreSpace.y, positionAbsolute: true });
// Circular
const circularSpace = circularLayout.get(node.id) ?? { x: 0, y: 0 };
node.spaces.push({ x: circularSpace.x, y: circularSpace.y, positionAbsolute: true });
// FCose Layout
// TODO
node.spaces.push({ x: Math.random() * viewportWidth, y: Math.random() * viewportHeight });
// Random
node.spaces.push({ x: Math.random() * viewportWidth, y: Math.random() * viewportHeight });
});
return newData;
}
static #convert__epi_space_v1_to_normal(data) {
const width = data.kv.width;
const height = data.kv.height;
const aspectRatio = width && height ? width / height : null;
const newData = {
dataFormat: 'normal',
nodes: data.proj.map((node, i) => ({ id: node.id, title: node.title, index: i, image: node.image, imageAspectRatio: aspectRatio, spaces: node.spaces })),
spaces: data.spaces,
};
const nodes = newData.nodes;
let hasDanbooruUrl = false;
data.proj.forEach((node, i) => {
if (node.kv?.danbooru_wiki_url) {
hasDanbooruUrl = true;
nodes[i].information = { danbooru: node.kv?.danbooru_wiki_url };
}
});
if (hasDanbooruUrl) newData.information = [ { id: 'danbooru', title: 'Danbooru', type: 'url' } ];
delete data.proj;
return newData;
}
static #convert__epi_space_v0_to_v1(data) {
const hasSecondSpace = data[0].x2 !== undefined && data[0].y2 !== undefined;
const newData = {
spaces: [
'Nomic Vision'
],
kv: {
// resolution from old viewer
width: 256,
height: 256 * 1.46
},
proj: hasSecondSpace ? data.map(({ x, y, x2, y2, title, image }) => ({ image, title, spaces: [{ x, y }, { x: x2, y: y2 }] })) : data.map(({ x, y, title, image }) => ({ image, title, spaces: [{ x, y }] }))
};
if (hasSecondSpace) newData.spaces.push('SDLX Pooled Text Encoders');
return newData;
}
static async dataImported(index, originalData) {
const indexItem = copyThis(INDEX[index]);
INDEX[index].inIndexedDB = true;
await this.setData(indexItem, originalData);
}
static async fetchData(index) {
const url = INDEX[index]?.url;
if (!url) throw new Error('No download link');
const response = await fetch(url);
const reader = response.body.getReader();
const contentLength = +response.headers.get('Content-Length');
const chunks = [];
let receivedLength = 0;
// TODO: Add current download speed
while(true) {
const chunk = await reader.read();
if (chunk.done) break;
chunks.push(chunk.value);
receivedLength += chunk.value.length;
ControlsController.loadingProgress = (receivedLength/contentLength) * 100;
}
const chunksAll = new Uint8Array(receivedLength);
let position = 0;
for(let chunk of chunks) {
chunksAll.set(chunk, position);
position += chunk.length;
}
const result = new TextDecoder("utf-8").decode(chunksAll);
const json = JSON.parse(result);
const indexItem = copyThis(INDEX[index]);
await this.setData(indexItem, json);
INDEX[index].inIndexedDB = true;
return json;
}
static loadIndex() {
return new Promise(async resolve => {
if (INDEX.length > 0) return resolve();
// Fetch from web index if online
if (!ISLOCAL) {
const indexJSON = await fetch(INDEX_URL).then(response => response.json());
indexJSON.forEach(item => INDEX.push(item));
}
// Load from DB index
const localIndex = await this.getIndexFromDB();
localIndex.forEach(item => {
const existItem = INDEX.find(a => a.id === item.id);
if (existItem) {
existItem.inIndexedDB = true;
} else {
item.inIndexedDB = true;
INDEX.push(item);
}
});
resolve();
});
}
static getData(index) {
return new Promise(async (resolve, reject) => {
const { db, close } = await this.#connectDB();
const transaction = db.transaction('embedding-maps-data', "readonly");
const getRequest = transaction.objectStore('embedding-maps-data').index('id').get(INDEX[index].id);
getRequest.onsuccess = e => resolve(e.target.result.data);
getRequest.onerror = () => reject();
transaction.oncomplete = () => close();
});
}
static removeData(index) {
return new Promise(async (resolve, reject) => {
const { db, close } = await this.#connectDB();
const transaction = db.transaction(['embedding-maps-index', 'embedding-maps-data'], "readwrite");
const storeIndex = transaction.objectStore('embedding-maps-index');
const storeData = transaction.objectStore('embedding-maps-data');
const getIndexRequest = storeIndex.index('id').get(INDEX[index].id);
const getDataRequest = storeData.index('id').get(INDEX[index].id);
getIndexRequest.onsuccess = () => storeIndex.delete(getIndexRequest.result.db_index);
getDataRequest.onsuccess = () => storeData.delete(getDataRequest.result.db_index);
transaction.onerror = () => reject();
transaction.oncomplete = () => {
close();
if (INDEX[index].url) INDEX[index].inIndexedDB = false;
else delete INDEX[index];
resolve();
};
});
}
static setData(indexItem, data) {
return new Promise(async (resolve, reject) => {
if (!data) return reject();
const { db, close } = await this.#connectDB();
const transaction = db.transaction(['embedding-maps-index', 'embedding-maps-data'], "readwrite");
const storeIndex = transaction.objectStore('embedding-maps-index');
const storeData = transaction.objectStore('embedding-maps-data');
const itemData = { id: indexItem.id, data: data };
storeIndex.add(indexItem);
storeData.add(itemData);
transaction.onerror = () => reject();
transaction.oncomplete = () => {
resolve();
close();
}
});
}
static getIndexFromDB() {
return new Promise(async (resolve, reject) => {
const { db, close } = await this.#connectDB();
const transaction = db.transaction('embedding-maps-index', "readonly");
const tableDB = transaction.objectStore('embedding-maps-index');
const request = tableDB.openCursor();
const result = [];
request.onsuccess = () => {
const cursor = request.result;
if (!cursor) return resolve(result);
result.push(cursor.value);
return cursor.continue();
};
request.onerror = () => reject();
transaction.oncomplete = () => close();
});
}
static #connectDB() {
return new Promise((resolve, reject) => {
let isUpgradeNeeded = false;
const openRequest = indexedDB.open(DB_NAME, DB_VERSION);
openRequest.onsuccess = () => {
const db = openRequest.result;
const close = () => db.close();
resolve({ db, close });
if (isUpgradeNeeded) {
ControlsController.loadingEnd();
addNotify('✔ IndexedDB successfully upgraded');
}
};
openRequest.onerror = error => {
console.error(error);
reject(error);
if (isUpgradeNeeded) {
ControlsController.loadingEnd();
addNotify('❌ Error upgrading IndexedDB');
} else addNotify('❌ Error opening IndexedDB');
};
openRequest.onupgradeneeded = e => {
isUpgradeNeeded = true;
ControlsController.loadingStart();
ControlsController.loadingTitle = `Upgrading Indexed DB from ${e.oldVersion} to ${DB_VERSION}`;
if (!e.oldVersion) return this.#createDB(e);
else return this.#upgradeDB(e);
};
});
}
static #createDB(event) {
const db = event.target.result;
const tableIndex = db.createObjectStore('embedding-maps-index', { keyPath: 'db_index', autoIncrement: true });
tableIndex.createIndex('id', 'id', { unique: true });
const tableData = db.createObjectStore('embedding-maps-data', { keyPath: 'db_index', autoIncrement: true });
tableData.createIndex('id', 'id', { unique: true });
}
static #upgradeDB(event) {
const db = event.target.result;
return new Promise(resolve => {
switch (event.oldVersion) {
case 0: {
const table = db.createObjectStore('embedding-maps', { keyPath: 'db_index', autoIncrement: true });
table.createIndex('id', 'id', { unique: true });
}
case 1: {
// Split data into 2 tables
const tableIndex = db.createObjectStore('embedding-maps-index', { keyPath: 'db_index', autoIncrement: true });
tableIndex.createIndex('id', 'id', { unique: true });
const tableData = db.createObjectStore('embedding-maps-data', { keyPath: 'db_index', autoIncrement: true });
tableData.createIndex('id', 'id', { unique: true });
const transaction = event.target.transaction;
const oldStore = transaction.objectStore('embedding-maps');
const storeIndex = transaction.objectStore('embedding-maps-index');
const storeData = transaction.objectStore('embedding-maps-data');
transaction.oncomplete = () => resolve();
oldStore.openCursor().onsuccess = e => {
const cursor = e.target.result;
if (!cursor) {
db.deleteObjectStore('embedding-maps');
return;
}
const data = cursor.value;
const newData = { id: data.id, data: data.data };
delete data.data;
storeIndex.add(data);
storeData.add(newData);
cursor.continue();
};
}
}
});
}
}
class ControlsController {
static viewportStatusElement = document.getElementById('cards-in-viewport');
static searchInputElement = document.getElementById('search');
static searchControlsElement = this.searchInputElement?.parentElement;
static searchGoToElement = document.getElementById('goto-search');
static searchClearElement = document.getElementById('search-clear');
static searchRegexToggleElement = document.getElementById('search-regex-toggle');
static dataListDialogElement = document.getElementById('data-list-container');
static dataListElement = document.getElementById('data-list');
static dataListSelectedElement = document.getElementById('data-list-selected');
static spacesListElement = document.getElementById('switch-spaces');
static recenterViewButtonElement = document.getElementById('recenter-view');
static overlapFixButtonElement = document.getElementById('overlap-fix');
static randomButtonElement = document.getElementById('random');
static spacingFactorCoefElement = document.getElementById('spacing-factor-coef');
static renderEngineListElement = document.getElementById('render-engine');
static graphLineStyleElement = document.getElementById('graph-line-style');
static uploadJsonInput = document.getElementById('upload-json-input');
static loadingElement = document.getElementById('loading');
static loadingBarProgressElement = document.getElementById('loading-bar-progress');
static loadingTitleElement = document.getElementById('loading-title');
static buttons = {
'switch-spaces': this.spacesListElement,
'render-engine': this.renderEngineListElement,
'graph-line-style': this.graphLineStyleElement,
'search-group': [ this.searchInputElement, this.searchClearElement, this.searchGoToElement, this.searchRegexToggleElement ],
'data-list': this.dataListSelectedElement,
'spacing-factor-coef': this.spacingFactorCoefElement,
'recenter-view': this.recenterViewButtonElement,
'overlap-fix': this.overlapFixButtonElement,
'random': this.randomButtonElement,
'only-with-data-group': [ this.spacesListElement, this.searchInputElement, this.searchClearElement, this.searchGoToElement, this.searchRegexToggleElement, this.spacingFactorCoefElement, this.recenterViewButtonElement, this.overlapFixButtonElement, this.randomButtonElement ],
};
static dataListElements = [];
static #visibleCardsCount = 0;
static #visibleCardsScale = 'Empty';
static #searchUseRegex = true;
static #isLoading = false;
static updateEmbeddingList(newEmbeddingList) {
STATE.space = 0;
const switchEmbList = this.spacesListElement;
switchEmbList.textContent = '';
newEmbeddingList.forEach((title, index) => insertElement('option', switchEmbList, { value: index }, title));
switchEmbList.value = STATE.space;
}
static updateDataSwitcher() {
const dataTypes = {
spaces: { text: 'Space', emoji: '🗃️' },
graphs: { text: 'Graph', emoji: '🕸️' }
};
const createOptionTag = (parent, text, emoji, title) => {
const tag = insertElement('div', parent, { class: 'option-tag', 'data-tag': text, title: title || text });
if (emoji) insertElement('span', tag, { class: 'emoji' }, emoji);
if (text) insertTextNode(tag, ` ${text}`);
return tag;
};
const createOptionButton = (parent, key, text, emoji, title) => {
const button = insertElement('button', parent, { class: `option-button option-${key}`, 'data-id': key, title: title || text });
if (emoji) insertElement('span', button, { class: 'emoji' }, emoji);
if (text) insertTextNode(button, ` ${text}`);
return button;
};
const selectedId = STATE.selectData ?? null;
const selectedItem = INDEX.find(item => item?.id === selectedId);
if (selectedItem) this.dataListSelectedElement.textContent = selectedItem.title || selectedId;
if (INDEX.length) {
const favoritesList = tryParseLocalStorageJSON(SETTINGS_PREFIX + 'favorite-list', []);
const favorites = Array.isArray(favoritesList) ? favoritesList.map(id => INDEX.findIndex(item => item?.id === id)) : [];
const order = [...favorites];
INDEX.forEach((item, i) => !order.includes(i) ? order.push(i) : null);
const fragment = new DocumentFragment();
const nowTime = Date.now();
order.forEach(i => {
if (i === -1) return;
const item = INDEX[i];
const option = insertElement('div', fragment, { class: 'data-option', 'data-id': i });
const isFavorite = favorites.includes(i);
if (item.id === selectedId) option.classList.add('data-option-selected');
if (isFavorite) option.classList.add('data-option-favorite');
// Title
const titleWrap = insertElement('h3', option, { class: 'option-title' });
createOptionButton(titleWrap, 'favorite', '', '⭐', isFavorite ? 'Remove from favorite' : 'Add to favorite');
insertElement('span', titleWrap, { title: item.description ?? item.title }, item.title);
// Description (with some inline markdown)
if (item.description) insertElement('p', option, { class: 'option-description' }).innerHTML = markdownInlineToHTML(item.description);
// Tags
if (item.tags && Array.isArray(item.tags)) {
const optionTagsElement = insertElement('div', option, { class: 'option-tags' });
item.tags.forEach(tag => createOptionTag(optionTagsElement, tag));
}
// Default tags
const optionTagsDefaultElement = insertElement('div', option, { class: 'option-tags option-tags-default' });
if (item.nodesCount) createOptionTag(optionTagsDefaultElement, item.nodesCount ?? 'Unknown', '🧩', 'Number of nodes');
if (item.fileSize) createOptionTag(optionTagsDefaultElement, filesizeToString(+item.fileSize), '📦', 'File size');
if (item.changed) {
const changed = new Date(item.changed);
createOptionTag(optionTagsDefaultElement, timeAgo(Math.round((nowTime - +changed)/1000)), '🕒', `Last modified: ${changed.toLocaleString()}`);
}
if (item.imported) createOptionTag(optionTagsDefaultElement, 'Imported', '📄', 'The file was imported locally');
if (item.author) createOptionTag(optionTagsDefaultElement, `by ${item.author}`, '📝', 'Creator of the original map');
if (item.type && item.type !== 'spaces') { // Show only if it's not spaces
const type = dataTypes[item.type] ?? { text: item.type, emoji: undefined };
createOptionTag(optionTagsDefaultElement, type.text, type.emoji, 'Display method');
}
// Buttons
const buttonsContainer = insertElement('div', option, { class: 'option-controls' });
if (item.inIndexedDB) {
createOptionButton(buttonsContainer, 'remove', 'Delete', '❌', 'Delete from IndexedDB');
createOptionButton(buttonsContainer, 'load', 'Load', '🗄️', 'Load from IndexedDB');
} else createOptionButton(buttonsContainer, 'download', 'Download', '📥', 'Download from the Internet');
this.dataListElements[i] = option;
});
this.dataListElement.textContent = '';
this.dataListElement.appendChild(fragment);
} else {
this.dataListElement.textContent = '';
const p = insertElement('p', this.dataListElement);
insertElement('span', p, { class: 'emoji' }, '📄');
insertTextNode(p, ' Drag & Drop ');
insertElement('code', p, undefined, '.json');
insertTextNode(p, ' file with embedding map');
}
}
static updateViewportStatus() {
this.viewportStatusElement.textContent = `${this.#visibleCardsScale} (x${this.#visibleCardsCount})`;
}
static emptyAllInputs() {
this.searchInputElement.value = '';
this.spacesListElement.textContent = '';
this.dataListDialogElement.close();
this.dataListDialogElement.classList.remove('data-allowed-deletion');
this.updateDataSwitcher();
this.dataListSelectedElement.textContent = 'Nothing selected';
this.loadingElement.style.display = 'none';
this.loadingBarProgressElement.style.width = '0%';
this.loadingTitleElement.textContent = 'Loading...';
this.searchGoToElement.setAttribute('data-next', 0);
this.searchGoToElement.setAttribute('data-count', 0);
this.searchRegexToggleElement.classList.toggle('control-btn-active', this.#searchUseRegex);
this.searchClearElement.style.visibility = 'hidden';
this.renderEngineListElement.textContent = '';
SETTINGS['render-engine'].options.forEach(value => insertElement('option', this.renderEngineListElement, { value }, SETTINGS['render-engine'].titles[value]));
this.renderEngineListElement.value = RENDER_ENGINE;
this.graphLineStyleElement.textContent = '';
SETTINGS['graph-line-style'].options.forEach(value => insertElement('option', this.graphLineStyleElement, { value }, SETTINGS['graph-line-style'].titles[value]));
this.graphLineStyleElement.value = GRAPH_LINE_STYLE;
}
static loadingStart() {
if (this.#isLoading) return;
this.loadingTitleElement.textContent = 'Loading...';
this.loadingBarProgressElement.style.width = '0%';
this.loadingElement.style.display = '';
document.body.classList.add('loading');
this.#isLoading = true;
}
static toggleButtonInteract(buttonId, enable = null) {
if (!this.buttons[buttonId]) return;
const toggleList = Array.isArray(this.buttons[buttonId]) ? this.buttons[buttonId] : [ this.buttons[buttonId] ];
if (enable === null) enable = Boolean(toggleList.getAttribute('disabled'));
if (enable) {
toggleList.forEach(button => {
button.setAttribute('tabindex', '0');
button.removeAttribute('disabled');
});
} else {
toggleList.forEach(button => {
button.setAttribute('tabindex', '-1');
button.setAttribute('disabled', '');
});
}
}
static set loadingTitle(newTitle) {
this.loadingTitleElement.textContent = newTitle;
}
static set loadingProgress(newProgress) { // from 0 to 100
this.loadingBarProgressElement.style.width = `${ newProgress > 0 ? newProgress < 100 ? newProgress : 100 : 0 }%`;
}
static loadingEnd() {
if (!this.#isLoading) return;
this.loadingElement.style.display = 'none';
document.body.classList.remove('loading');
this.#isLoading = false;
}
static set visibleCardsCount(newCount) {
this.#visibleCardsCount = newCount;
}
static get visibleCardsCount() {
return this.#visibleCardsCount;
}
static set visibleCardsScale(newCardsScale) {
this.#visibleCardsScale = newCardsScale;
}
static get visibleCardsScale() {
return this.#visibleCardsScale;
}
static set searchUseRegex(newState) {
this.#searchUseRegex = Boolean(newState);
}
static get searchUseRegex() {
return this.#searchUseRegex;
}
}
class CardsPreviewController {
data = [];
grid = { layers: [], cellWidth: 0, cellHeight: 0 };
key;
scale;
constructor(key, data, scale) {
scale = +scale.toFixed(5);
this.key = key;
this.scale = scale;
// List of maximum canvas sizes in browsers: https://jhildenbiddle.github.io/canvas-size/#/?id=test-results
// Maximum texture layers in WebGL2: https://developer.mozilla.org/en-US/docs/Web/API/WebGLRenderingContext/activeTexture#:~:text=It%20is%2C%20per%20specification%2C%20at%20least%208
const canvasScaleMultiplyer = .5; // Temporary solution to the problem with VRAM consumption spike and browser crash when generating preview
const maxHeight = 16384 * canvasScaleMultiplyer;
const maxWidth = 16384 * canvasScaleMultiplyer;
const maxLayers = 8;
this.data = data;
const cardsCount = data.length;
const cardWidthReal = Math.max(...data.map(item => item.width)) * scale;
const cardHeightReal = Math.max(...data.map(item => item.height)) * scale;
const isSizeOk = Math.min(cardWidthReal, cardHeightReal) >= 1;
const reScale = isSizeOk ? 1 : 1 / Math.min(cardWidthReal, cardHeightReal);
const cellWidth = Math.round(cardWidthReal * reScale);
const cellHeight = Math.round(cardHeightReal * reScale);
this.scale = scale * reScale;
const gridSizeX = Math.floor(maxWidth/cellWidth);
const gridSizeY = Math.ceil(cardsCount/gridSizeX);
const maxGridY = Math.floor(maxHeight/cellHeight);
const layers = [];
const pushCanvas = (gridSizeX, gridSizeY) => {
const width = gridSizeX * cellWidth;
const height = gridSizeY * cellHeight;
const canvas = new OffscreenCanvas(width, height);
layers.push({ canvas, width, height, gridSizeX, gridSizeY });
}
this.grid = { cellWidth, cellHeight, layers };
if (gridSizeY > maxGridY) {
const wholeLayersCount = Math.floor(gridSizeY / maxGridY);
if (wholeLayersCount >= maxLayers) console.warn(`Warning: Too many texture layers!\nThe current number of texture layers is ${wholeLayersCount}, which exceeds the guaranteed minimum support of ${maxLayers} layers.`);
for (let i = 0; i < wholeLayersCount; i++) {
pushCanvas(gridSizeX, maxGridY);
}
pushCanvas(gridSizeX, gridSizeY - maxGridY * wholeLayersCount);
} else pushCanvas(gridSizeX, gridSizeY);
}
async drawCards(referenceController, convertCanvasAfterDone = 'canvas') { // convertCanvasAfterDone - 'canvas', 'bitmap', 'image'
const scale = this.scale;
const count = this.data.length;
const key = this.key;
const padding = CARD_STYLE.padding * scale;
const fontSize = CARD_STYLE.fontSize * scale;
const borderWidth = CARD_STYLE.borderWidth * scale;
const borderWidthX2 = borderWidth * 2;
const borderRadius = Math.round(CARD_STYLE.borderRadius * scale);
const borderRadiusInside = borderRadius > padding ? borderRadius - padding : 0;
const hasReference = Boolean(referenceController);
const { cellWidth, cellHeight, layers } = this.grid;
const contentOffset = padding + borderWidth;
const lineHeight = fontSize * CARD_STYLE.lineHeight;
const controls = [ ICON_BOOK.cloneNode(true), ICON_COPY.cloneNode(true) ];
const controlsFontSize = 1.5 * fontSize;
const controlsWidth = controls.length * controlsFontSize + (controls.length - 1) * controlsFontSize * .125;
const fontString = `normal ${fontSize}px ${CARD_STYLE.font}`;
let ctx, gridSizeX, gridSizeY, layerMaxCards, currentLayerIndex = 0, cardOffsetY = 0;
const referenceLayers = hasReference ? referenceController.grid.layers : null;
const refCardWidth = hasReference ? referenceController.grid.cellWidth : null;
const refCardHeight = hasReference ? referenceController.grid.cellHeight : null;
let refCanvas, refGridX, refGridY, refCardsCount, refCurrentLayerIndex = 0, refCardOffsetY = 0;
const convertCanvasToImage = offscreenCanvas => {
return new Promise(r => {
offscreenCanvas.convertToBlob({ type: 'image/png', quality: 1 }).then(blob => {
const image = new Image(offscreenCanvas.width, offscreenCanvas.height);
// Destroy canvas ASAP after using
offscreenCanvas.width = 0;
offscreenCanvas.height = 0;
offscreenCanvas = null;
const url = URL.createObjectURL(blob);
image.addEventListener('load', () => {
URL.revokeObjectURL(url);
r(image);
}, { once: true });
image.src = url;
});
});
};
const convertCanvasToBitmap = async offscreenCanvas => {
const imageBitmap = await offscreenCanvas.transferToImageBitmap();
// Destroy canvas ASAP after using
offscreenCanvas.width = 0;
offscreenCanvas.height = 0;
offscreenCanvas = null;
return imageBitmap;
};
const selectLayer = async i => {