-
Notifications
You must be signed in to change notification settings - Fork 6
/
main.ts
2099 lines (1738 loc) · 74.3 KB
/
main.ts
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
import { Plugin, ItemView, WorkspaceLeaf, debounce, Notice } from 'obsidian';
import * as d3 from "d3";
import _ from 'lodash';
const DEFAULT_NETWORK_SETTINGS : any = {
relevanceScoreThreshold: 0.5,
nodeSize: 4,
linkThickness: 0.3,
repelForce: 400,
linkForce: 0.4,
linkDistance: 70,
centerForce: 0.1,
textFadeThreshold: 1.1,
minLinkThickness: 0.3,
maxLinkThickness: 0.6,
maxLabelCharacters: 18,
linkLabelSize: 7,
nodeLabelSize: 6,
connectionType: 'block',
noteFillColor: '#7c8594',
blockFillColor: '#926ec9'
}
/*
Main Colors
Menu text: #a3aecb
HoveredOverNode: #d46ebe
NormalNode: #926ec9
centralNode: #7c8594
Link: #4c7787
SliderKnob: #f3ee5d
*/
interface PluginSettings {
relevanceScoreThreshold: number;
nodeSize: number;
linkThickness: number;
repelForce: number;
linkForce: number;
linkDistance: number;
centerForce: number;
textFadeThreshold: number;
minLinkThickness: number;
maxLinkThickness: number;
maxLabelCharacters: number;
linkLabelSize: number;
nodeLabelSize: number;
connectionType: string;
noteFillColor: string;
blockFillColor: string;
}
declare global {
interface Window {
SmartSearch: any;
}
}
class ScGraphItemView extends ItemView {
private plugin: ScGraphView;
currentNoteKey: string;
centralNote: any;
centralNode: any;
connectionType = 'block';
isHovering: boolean;
relevanceScoreThreshold = 0.5;
nodeSize = 4;
linkThickness = 0.3;
repelForce = 400;
linkForce = 0.4;
linkDistance = 70;
centerForce = 0.3;
textFadeThreshold = 1.1;
minScore = 1;
maxScore = 0;
minNodeSize = 3;
maxNodeSize = 6;
minLinkThickness = 0.3;
maxLinkThickness = 0.6;
nodeSelection: any;
linkSelection: any;
linkLabelSelection: any;
labelSelection: any;
updatingVisualization: boolean;
isCtrlPressed = false;
isAltPressed = false;
isDragging = false;
isChangingConnectionType = true;
selectionBox: any;
validatedLinks: any;
maxLabelCharacters = 18;
linkLabelSize = 7;
nodeLabelSize = 6;
blockFillColor = '#926ec9';
noteFillColor = '#7c8594';
startX = 0;
startY = 0;
nodes : any = [];
links : any = [];
connections : any = [];
svgGroup: d3.Selection<SVGGElement, unknown, null, undefined>;
svg: d3.Selection<SVGSVGElement, unknown, null, undefined>;
centerHighlighted = false;
simulation: any;
dragging = false;
highlightedNodeId = '-1';
currentNoteChanging = false;
isFiltering = false;
settingsMade = false;
constructor(leaf: WorkspaceLeaf, plugin: ScGraphView) {
super(leaf);
this.currentNoteKey = '';
this.isHovering = false;
this.plugin = plugin;
// Set the initial values from the loaded settings
this.relevanceScoreThreshold = this.plugin.settings.relevanceScoreThreshold;
this.nodeSize = this.plugin.settings.nodeSize;
this.linkThickness = this.plugin.settings.linkThickness;
this.repelForce = this.plugin.settings.repelForce;
this.linkForce = this.plugin.settings.linkForce;
this.linkDistance = this.plugin.settings.linkDistance;
this.centerForce = this.plugin.settings.centerForce;
this.textFadeThreshold = this.plugin.settings.textFadeThreshold;
this.minLinkThickness = this.plugin.settings.minLinkThickness;
this.maxLinkThickness = this.plugin.settings.maxLinkThickness;
this.maxLabelCharacters = this.plugin.settings.maxLabelCharacters;
this.linkLabelSize = this.plugin.settings.linkLabelSize;
this.nodeLabelSize = this.plugin.settings.nodeLabelSize;
this.connectionType = this.plugin.settings.connectionType;
this.noteFillColor = this.plugin.settings.noteFillColor;
this.blockFillColor = this.plugin.settings.blockFillColor;
}
getViewType(): string {
return "smart-connections-visualizer";
}
getDisplayText(): string {
return "Smart connections visualizer";
}
getIcon(): string {
return "git-fork";
}
updateNodeAppearance() {
this.nodeSelection.transition().duration(500)
.attr('fill', (d: any) => d.fill)
.attr('stroke', (d: any) => d.selected ? 'blanchedalmond' : (d.highlighted ? '#d46ebe' : 'transparent'))
.attr('stroke-width', (d: any) => d.selected ? 1.5 : (d.highlighted ? 0.3 : 0))
.attr('opacity', (d: any) => this.getNodeOpacity(d));
}
// getNodeFill(d: any) {
// if (d.id === this.centralNode.id) return '#7c8594';
// if (d.highlighted && !d.selected) return '#d46ebe';
// return d.group === 'note' ? '#7c8594' : '#926ec9';
// }
getNodeOpacity(d: any) {
if (d.id === this.centralNode.id) return 1;
if (d.selected) return 1;
if (d.highlighted) return 0.8;
return this.isHovering ? 0.1 : 1;
}
toggleNodeSelection(nodeId: string) {
const node = this.nodeSelection.data().find((d: any) => d.id === nodeId);
if (node) {
node.selected = !node.selected;
if (!node.selected) {
node.highlighted = false;
}
this.updateNodeAppearance();
}
}
clearSelections() {
this.nodeSelection.each((d: any) => {
d.selected = false;
d.highlighted = false;
});
this.updateNodeAppearance();
}
highlightNode(node: any) {
if (node.id === this.centralNode.id) {
this.centerHighlighted = true;
}
this.highlightedNodeId = node.id;
this.nodeSelection.each((d: any) => {
if (d.id !== this.centralNode.id) {
d.highlighted = (d.id === node.id || this.validatedLinks.some((link: any) =>
(link.source.id === node.id && link.target.id === d.id) ||
(link.target.id === node.id && link.source.id === d.id)));
}
});
this.updateNodeAppearance();
this.updateLinkAppearance(node);
this.updateLabelAppearance(node);
this.updateLinkLabelAppearance(node);
}
updateHighlight(d: any, node: any) {
if (d.id !== this.centralNode.id) {
d.highlighted = (d.id === node.id || this.validatedLinks.some((link: any) =>
(link.source.id === node.id && link.target.id === d.id) ||
(link.target.id === node.id && link.source.id === d.id)));
}
}
updateLinkAppearance(node: any) {
this.linkSelection.transition().duration(500)
.attr('opacity', (d: any) => (d.source.id === node.id || d.target.id === node.id) ? 1 : 0.1);
}
updateLabelAppearance(node: any) {
this.labelSelection.transition().duration(500)
.attr('opacity', (d: any) => this.getLabelOpacity(d, node))
.text((d: any) => d.id === this.highlightedNodeId ? this.formatLabel(d.name, false) : this.formatLabel(d.name, true));
}
getLabelOpacity(d: any, node: any) {
if (!node) {
return 1; // Reset to full opacity if no node is highlighted
}
return (d.id === node.id || this.validatedLinks.some((link: any) =>
(link.source.id === node.id && link.target.id === d.id)) || d.id == this.centralNode.id) ? 1 : 0.1;
}
updateLinkLabelAppearance(node: any) {
this.linkLabelSelection.transition().duration(500)
.attr('opacity', (d: any) => {
return (d.source.id === node.id || d.target.id === node.id) ? 1 : 0;
})
}
unhighlightNode(node : any) {
// Reset highlighted nodeid
this.highlightedNodeId = '-1';
this.nodeSelection.each((d: any) => {
if (d.id !== this.centralNode.id) d.highlighted = false;
});
this.updateNodeAppearance();
this.resetLinkAppearance();
this.resetLabelAppearance();
this.resetLinkLabelAppearance();
this.updateLabelAppearance(null); // Pass false to reset label position
}
resetLinkAppearance() {
this.linkSelection.transition().duration(500).attr('opacity', 1);
}
resetLabelAppearance() {
this.labelSelection.transition().duration(500).attr('opacity', 1)
.text((d: any) => this.formatLabel(d.name, true));
}
resetLinkLabelAppearance() {
this.linkLabelSelection.transition().duration(500).attr('opacity', 0);
}
formatLabel(path: string, truncate: boolean = true) {
let label = this.extractLabel(path);
return truncate ? this.truncateLabel(label) : label;
}
extractLabel(path: string) {
let label = path;
// Remove the anchor part if it exists
if (path && path.includes('#')) {
const parts = path.split('#');
let lastPart = parts[parts.length - 1]; // Take the last part after splitting by '#'
// Check if the last part is empty or matches the pattern {number}
if (lastPart === '' || /^\{\d+\}$/.test(lastPart)) {
// Concatenate the last two parts
lastPart = parts[parts.length - 2] + '#' + lastPart;
}
// // Check if lastPart contains any '/' and if so, take the last part after splitting by '/'
if (lastPart.includes('/')) {
lastPart = lastPart.split('/').pop() || lastPart;
}
label = lastPart;
} else if (path) {
label = path.split('/').pop() || label; // Take the last part after splitting by '/'
} else {
return '';
}
label = label.replace(/[\[\]]/g, '') // Remove brackets if they exist
.replace(/\.[^/#]+#(?=\{\d+\}$)/, '') // Remove hashtag if it exists
.replace(/\.[^/.]+$/, ''); // Remove file extension if it exists
return label;
}
truncateLabel(label: string) {
return label.length > this.maxLabelCharacters ? label.slice(0, this.maxLabelCharacters) + '...' : label;
}
get env() { return window.SmartSearch?.main?.env; }
get smartNotes() { return window.SmartSearch?.main?.env?.smart_sources?.items; }
async onOpen() {
this.contentEl.createEl('h2', { text: 'Smart Visualizer' });
this.contentEl.createEl('p', { text: 'Waiting for Smart Connections to load...' });
console.log(this.app);
// Introduce a small delay before rendering to give view time to load
setTimeout(() => {
this.render();
}, 500); // Adjust the delay as needed
}
async render() {
// wait until this.smartNotes is available
while (!this.env?.entities_loaded) {
await new Promise(resolve => setTimeout(resolve, 2000));
}
this.contentEl.empty();
this.initializeVariables();
if (Object.keys(this.smartNotes).length === 0) {
return;
}
this.setupSettingsMenu();
this.setupSVG();
this.addEventListeners();
this.watchForNoteChanges();
// Load latest active file if opening view for first time
const currentNodeChange = this.app.workspace.getActiveFile();
if (currentNodeChange && !this.currentNoteChanging) {
this.currentNoteKey = currentNodeChange.path;
this.currentNoteChanging = true;
this.render();
return
}
this.updateVisualization();
}
async waitForSmartNotes() {
const maxRetries = 10; // Set a max number of retries to avoid infinite loop
const delay = 2000; // Delay in milliseconds between retries
for (let attempt = 0; attempt < maxRetries; attempt++) {
console.log(this.env);
if (this.env?.entities_loaded) {
return;
}
await new Promise(resolve => setTimeout(resolve, delay));
}
// If we reach here, it means the entities are still not loaded
console.error('Smart notes did not load in time');
this.contentEl.createEl('p', { text: 'Failed to load Smart Connections.' });
}
initializeVariables() {
this.minScore = 1;
this.maxScore = 0;
}
setupSVG() {
const width = this.contentEl.clientWidth;
const height = this.contentEl.clientHeight;
const svg = d3.select(this.contentEl)
.append('svg')
.attr('width', '100%')
.attr('height', '98%')
.attr('viewBox', `0 0 ${width} ${height}`)
.attr('preserveAspectRatio', 'xMidYMid meet')
.call(d3.zoom()
.scaleExtent([0.1, 10])
.on('zoom', (event) => {
svgGroup.attr('transform', event.transform);
this.updateLabelOpacity(event.transform.k);
}));
const svgGroup = svg.append('g');
svgGroup.append('g').attr('class', 'smart-connections-visualizer-links');
svgGroup.append('g').attr('class', 'smart-connections-visualizer-node-labels');
svgGroup.append('g').attr('class', 'smart-connections-visualizer-link-labels');
svgGroup.append('g').attr('class', 'smart-connections-visualizer-nodes');
this.svgGroup = svgGroup;
this.svg = svg;
}
getSVGDimensions() {
const width = this.contentEl.clientWidth || this.contentEl.getBoundingClientRect().width;
const height = this.contentEl.clientHeight || this.contentEl.getBoundingClientRect().height;
return { width, height };
}
createSVG(width: number, height: number) {
return d3.select(this.contentEl)
.append('svg')
.attr('width', '100%')
.attr('height', '98%')
.attr('viewBox', `0 0 ${width} ${height}`)
.attr('preserveAspectRatio', 'xMidYMid meet')
.style('background', '#2d3039')
.call(d3.zoom().scaleExtent([0.1, 10]).on('zoom', this.onZoom.bind(this)));
}
createSVGGroup(svg: any) {
return svg.append('g');
}
onZoom(event: any) {
d3.select('g').attr('transform', event.transform);
this.updateLabelOpacity(event.transform.k);
}
initializeSimulation(width: number, height: number) {
this.simulation = d3.forceSimulation()
.force('center', d3.forceCenter(width / 2, height / 2).strength(this.centerForce))
.force('charge', d3.forceManyBody().strength(-this.repelForce))
// .force('link', d3.forceLink().id((d: any) => d.id).distance(this.linkDistance).strength(this.linkForce))
.force('link', d3.forceLink()
.id((d: any) => d.id)
.distance((d: any) => this.linkDistanceScale(d.score))
.strength(this.linkForce))
.force('collide', d3.forceCollide().radius(this.nodeSize + 3).strength(0.7))
.on('tick', this.simulationTickHandler.bind(this));
// Add the custom force for labels
this.simulation.force('labels', this.avoidLabelCollisions.bind(this));
// Disable the centering force after the initial positioning
// this.simulation.on('end', () => {
// console.log('Simulation ended, center force removed.');
// this.simulation.force('center', null); // Remove the center force after initial stabilization
// });
}
renderLegend() {
if (this.validatedLinks.length === 0) {
return;
}
const types = ['block', 'note']; // Connection types
const counts = types.map(type => this.nodes.filter((node: any) => (node.group === type) && node.id !== this.centralNode.id).length);
// Initialize colors with default values
let colors: { [key: string]: string } = { 'block': DEFAULT_NETWORK_SETTINGS.blockFillColor, 'note': DEFAULT_NETWORK_SETTINGS.noteFillColor };
// Iterate over nodes to find the color for each type
for (let node of this.nodes) {
if (colors[node.group]) {
colors[node.group] = node.fill;
}
}
// Use contentEl to create a table container
const tableContainer = this.contentEl.createEl('div', { cls: 'smart-connections-visualizer-legend-container' });
// Create table header
const header = tableContainer.createEl('div', { cls: 'smart-connections-visualizer-legend-header' });
['Connection Type', 'Count', 'Color'].forEach(headerTitle => {
// Assign appropiate class based on column
switch(headerTitle) {
case "Connection Type":
header.createEl('div', { text: headerTitle, cls: 'smart-connections-visualizer-variable-col' });
break;
case "Count":
header.createEl('div', { text: headerTitle, cls: 'smart-connections-visualizer-count-col' });
break;
case "Color":
header.createEl('div', { text: headerTitle, cls: 'smart-connections-visualizer-color-col' });
break;
default:
header.createEl('div', { text: headerTitle, cls: 'smart-connections-visualizer-variable-col' });
break
}
});
// Create rows for each type
types.forEach((type, index) => {
if (counts[index] > 0) { // Check if the count is greater than zero
const row = tableContainer.createEl('div', { cls: 'smart-connections-visualizer-legend-row' });
row.createEl('div', { text: this.capitalizeFirstLetter(type), cls: 'smart-connections-visualizer-variable-col' });
row.createEl('div', { text: `${counts[index]}`, cls: 'smart-connections-visualizer-count-col' });
const colorCell = row.createEl('div', { cls: 'smart-connections-visualizer-color-col' });
const colorPicker = colorCell.createEl('input', { type: 'color', value: colors[type as keyof typeof colors], cls: 'smart-connections-visualizer-legend-color-picker' });
colorPicker.addEventListener('change', (e) => this.updateNodeColors(type, (e.target as HTMLInputElement).value));
}
});
}
capitalizeFirstLetter(str: string): string {
if (!str) return str;
console.log('string: ', str);
return str.charAt(0).toUpperCase() + str.slice(1);
}
updateNodeColors(type: string, color: string) {
if (type === 'note' && color !== this.noteFillColor) {
this.noteFillColor = color;
this.plugin.settings.noteFillColor = color;
this.plugin.saveSettings(); // Save the settings
}
if (type === 'block' && color !== this.blockFillColor) {
this.blockFillColor = color;
this.plugin.settings.noteFillColor = color;
this.plugin.saveSettings(); // Save the settings
}
this.nodes.forEach((node : any) => {
if (node.group === type) {
node.fill = color;
}
});
this.updateNodeFill();
}
updateNodeFill() {
// Update the D3 visualization here
this.nodeSelection.attr('fill', (d: any) => d.fill);
}
// Ensure node labels dont collide with any elements
avoidLabelCollisions() {
const padding = 5; // Adjust padding as needed
return (alpha: number) => {
const quadtree = d3.quadtree()
.x((d: any) => d.x)
.y((d: any) => d.y)
.addAll(this.labelSelection.data());
this.labelSelection.each((d: any) => {
const radius = d.radius + padding; // Assuming each label has a radius, adjust as necessary
const nx1 = d.x - radius, nx2 = d.x + radius, ny1 = d.y - radius, ny2 = d.y + radius;
quadtree.visit((quad, x1, y1, x2, y2) => {
if ('data' in quad && quad.data && (quad.data !== d)) {
let x = d.x - (quad.data as any).x,
y = d.y - (quad.data as any).y,
l = Math.sqrt(x * x + y * y),
r = radius + (quad.data as any).radius;
if (l < r) {
l = (l - r) / l * alpha;
d.x -= x *= l;
d.y -= y *= l;
(quad.data as any).x += x;
(quad.data as any).y += y;
}
}
return x1 > nx2 || x2 < nx1 || y1 > ny2 || y2 < ny1;
});
});
};
}
addEventListeners() {
this.setupSVGEventListeners();
this.setupKeyboardEventListeners();
}
setupSVGEventListeners() {
d3.select('svg')
.on('mousedown', this.onMouseDown.bind(this))
.on('mousemove', this.onMouseMove.bind(this))
.on('mouseup', this.onMouseUp.bind(this))
.on('click', this.onSVGClick.bind(this));
}
// TODO: Add back in when ready for multiselect
onMouseDown(event: any) {
// if (!event.ctrlKey) this.clearSelections();
// this.startBoxSelection(event);
}
onMouseMove(event: any) {
// event.stopPropagation();
// this.updateBoxSelection(event);
}
onMouseUp() {
// this.endBoxSelection();
}
onSVGClick(event: any) {
if (!event.defaultPrevented && !event.ctrlKey) this.clearSelections();
}
setupKeyboardEventListeners() {
document.addEventListener('keydown', this.onKeyDown.bind(this));
document.addEventListener('keyup', this.onKeyUp.bind(this));
}
// TODO:: Add back when ready for multiselect
onKeyDown(event: any) {
// if (event.key === 'Alt' || event.key === 'AltGraph') this.isAltPressed = true;
// if (event.key === 'Control') {
// this.isCtrlPressed = true;
// d3.select('svg').style('cursor', 'crosshair');
// }
}
onKeyUp(event: any) {
// if (event.key === 'Alt' || event.key === 'AltGraph') this.isAltPressed = false;
// if (event.key === 'Control') {
// this.isCtrlPressed = false;
// d3.select('svg').style('cursor', 'default');
// }
}
setupSettingsMenu() {
// Remove any existing settings icon and dropdown menu
const existingIcon = this.contentEl.querySelector('.smart-connections-visualizer-settings-icon');
if (existingIcon) {
existingIcon.remove();
}
const existingDropdownMenu = this.contentEl.querySelector('.sc-visualizer-dropdown-menu');
if (existingDropdownMenu) {
existingDropdownMenu.remove();
}
// Create new settings icon and dropdown menu
this.createSettingsIcon();
this.createDropdownMenu();
this.setupAccordionHeaders();
this.setupSettingsEventListeners();
}
createDropdownMenu() {
const dropdownMenu = this.contentEl.createEl('div', { cls: 'sc-visualizer-dropdown-menu' });
this.buildDropdownMenuContent(dropdownMenu);
}
buildDropdownMenuContent(dropdownMenu: HTMLElement) {
const menuHeader = dropdownMenu.createEl('div', { cls: 'smart-connections-visualizer-menu-header' });
// Append the refresh icon created by createRefreshIcon
const refreshIcon = this.createRefreshIcon();
refreshIcon.classList.add('smart-connections-visualizer-icon'); // Ensure it has the 'icon' class for styling
refreshIcon.setAttribute('id', 'smart-connections-visualizer-refresh-icon'); // Set the ID for specific styling or selection
menuHeader.appendChild(refreshIcon);
// Append the new X icon created by createNewXIcon
const xIcon = this.createNewXIcon();
xIcon.classList.add('smart-connections-visualizer-icon'); // Ensure it has the 'icon' class for styling
xIcon.setAttribute('id', 'smart-connections-visualizer-close-icon'); // Set the ID for specific styling or selection
menuHeader.appendChild(xIcon);
this.addAccordionItem(dropdownMenu, 'Filters', this.getFiltersContent.bind(this));
this.addAccordionItem(dropdownMenu, 'Display', this.getDisplayContent.bind(this));
this.addAccordionItem(dropdownMenu, 'Forces', this.getForcesContent.bind(this));
}
addAccordionItem(parent: HTMLElement, title: string, buildContent: (parent: HTMLElement) => void) {
const accordionItem = parent.createEl('div', { cls: 'smart-connections-visualizer-accordion-item' });
const header = accordionItem.createEl('div', { cls: 'smart-connections-visualizer-accordion-header' });
const arrowIcon = header.createEl('span', { cls: 'smart-connections-visualizer-arrow-icon' });
arrowIcon.appendChild(this.createRightArrow());
header.createEl('span', { text: title });
const accordionContent = accordionItem.createEl('div', { cls: 'smart-connections-visualizer-accordion-content' });
buildContent(accordionContent);
}
getFiltersContent(parent: HTMLElement) {
const sliderContainer1 = parent.createEl('div', { cls: 'smart-connections-visualizer-slider-container' });
sliderContainer1.createEl('label', {
text: `Min relevance: ${(this.relevanceScoreThreshold * 100).toFixed(0)}%`,
attr: { id: 'smart-connections-visualizer-scoreThresholdLabel', for: 'smart-connections-visualizer-scoreThreshold' }
});
const relevanceSlider = sliderContainer1.createEl('input', {
attr: {
type: 'range',
id: 'smart-connections-visualizer-scoreThreshold',
class: 'smart-connections-visualizer-slider',
name: 'scoreThreshold',
min: '0',
max: '0.99',
step: '0.01'
}
});
// Ensure the slider's value is set after it is appended to the DOM
relevanceSlider.value = this.relevanceScoreThreshold.toString();
parent.createEl('label', { text: 'Connection type:', cls: 'smart-connections-visualizer-settings-item-content-label' });
const radioContainer = parent.createEl('div', { cls: 'smart-connections-visualizer-radio-container' });
const radioBlockLabel = radioContainer.createEl('label');
const blockRadio = radioBlockLabel.createEl('input', {
attr: {
type: 'radio',
name: 'connectionType',
value: 'block'
}
});
blockRadio.checked = (this.connectionType === 'block'); // Set checked based on connectionType
radioBlockLabel.appendText(' Block');
const radioNoteLabel = radioContainer.createEl('label');
const noteRadio = radioNoteLabel.createEl('input', {
attr: {
type: 'radio',
name: 'connectionType',
value: 'note'
}
});
noteRadio.checked = (this.connectionType === 'note'); // Set checked based on connectionType
radioNoteLabel.appendText(' Note');
const radioBothLabel = radioContainer.createEl('label');
const bothRadio = radioBothLabel.createEl('input', {
attr: {
type: 'radio',
name: 'connectionType',
value: 'both'
}
});
bothRadio.checked = (this.connectionType === 'both'); // Set checked based on connectionType
radioBothLabel.appendText(' Both');
}
getDisplayContent(parent: HTMLElement) {
const displaySettings = [
{ id: 'smart-connections-visualizer-nodeSize', label: 'Node size', value: this.nodeSize, min: 1, max: 15, step: 0.01 },
{ id: 'smart-connections-visualizer-maxLabelCharacters', label: 'Max label characters', value: this.maxLabelCharacters, min: 1, max: 50, step: 1 },
{ id: 'smart-connections-visualizer-linkLabelSize', label: 'Link label size', value: this.linkLabelSize, min: 1, max: 15, step: 0.01 },
{ id: 'smart-connections-visualizer-nodeLabelSize', label: 'Node label size', value: this.nodeLabelSize, min: 1, max: 26, step: 1 },
{ id: 'smart-connections-visualizer-minLinkThickness', label: 'Min link thickness', value: this.minLinkThickness, min: 0.1, max: 10, step: 0.01 },
{ id: 'smart-connections-visualizer-maxLinkThickness', label: 'Max link thickness', value: this.maxLinkThickness, min: 0.1, max: 10, step: 0.01 },
{ id: 'smart-connections-visualizer-fadeThreshold', label: 'Text fade threshold', value: this.textFadeThreshold, min: 0.1, max: 10, step: 0.01 }
];
displaySettings.forEach(setting => {
const sliderContainer = parent.createEl('div', { cls: 'smart-connections-visualizer-slider-container' });
sliderContainer.createEl('label', { text: `${setting.label}: ${setting.value}`, attr: { id: `${setting.id}Label`, for: setting.id } });
sliderContainer.createEl('input', { attr: { type: 'range', id: setting.id, class: 'smart-connections-visualizer-slider', name: setting.id, min: `${setting.min}`, max: `${setting.max}`, value: `${setting.value}`, step: `${setting.step}` } });
});
}
getForcesContent(parent: HTMLElement) {
const forcesSettings = [
{ id: 'smart-connections-visualizer-repelForce', label: 'Repel force', value: this.repelForce, min: 0, max: 1500, step: 1 },
{ id: 'smart-connections-visualizer-linkForce', label: 'Link force', value: this.linkForce, min: 0, max: 1, step: 0.01 },
{ id: 'smart-connections-visualizer-linkDistance', label: 'Link distance', value: this.linkDistance, min: 10, max: 200, step: 1 }
];
forcesSettings.forEach(setting => {
const sliderContainer = parent.createEl('div', { cls: 'smart-connections-visualizer-slider-container' });
sliderContainer.createEl('label', { text: `${setting.label}: ${setting.value}`, attr: { id: `${setting.id}Label`, for: setting.id } });
sliderContainer.createEl('input', { attr: { type: 'range', id: setting.id, class: 'smart-connections-visualizer-slider', name: setting.id, min: `${setting.min}`, max: `${setting.max}`, value: `${setting.value}`, step: `${setting.step}` } });
});
}
toggleDropdownMenu() {
const dropdownMenu = document.querySelector('.sc-visualizer-dropdown-menu') as HTMLElement;
if (dropdownMenu) {
dropdownMenu.classList.toggle('visible');
} else {
console.error('Dropdown menu element not found');
}
}
setupAccordionHeaders() {
const accordionHeaders = document.querySelectorAll('.smart-connections-visualizer-accordion-header');
accordionHeaders.forEach(header => header.addEventListener('click', this.toggleAccordionContent.bind(this)));
}
toggleAccordionContent(event: any) {
const content = event.currentTarget.nextElementSibling;
const arrowIcon = event.currentTarget.querySelector('.smart-connections-visualizer-arrow-icon');
if (content && arrowIcon) {
content.classList.toggle('show');
arrowIcon.innerHTML = ''; // Clear current content
arrowIcon.appendChild(content.classList.contains('show') ? this.createDropdownArrow() : this.createRightArrow());
}
}
createDropdownArrow() {
const svg = document.createElementNS("http://www.w3.org/2000/svg", "svg");
svg.setAttribute("class", "smart-connections-visualizer-dropdown-indicator");
svg.setAttribute("viewBox", "0 0 16 16");
svg.setAttribute("fill", "currentColor");
const path = document.createElementNS("http://www.w3.org/2000/svg", "path");
path.setAttribute("fill-rule", "evenodd");
path.setAttribute("d", "M1.646 4.646a.5.5 0 0 1 .708 0L8 10.293l5.646-5.647a.5.5 0 0 1 .708.708l-6 6a.5.5 0 0 1-.708 0l-6-6a.5.5 0 0 1 0-.708z");
svg.appendChild(path);
return svg;
}
createRightArrow() {
const svg = document.createElementNS("http://www.w3.org/2000/svg", "svg");
svg.setAttribute("class", "smart-connections-visualizer-dropdown-indicator");
svg.setAttribute("viewBox", "0 0 16 16");
svg.setAttribute("fill", "currentColor");
const path = document.createElementNS("http://www.w3.org/2000/svg", "path");
path.setAttribute("fill-rule", "evenodd");
path.setAttribute("d", "M4.646 1.646a.5.5 0 0 1 .708 0l6 6a.5.5 0 0 1 0 .708l-6 6a.5.5 0 0 1-.708-.708L10.293 8 4.646 2.354a.5.5 0 0 1 0-.708z");
svg.appendChild(path);
return svg;
}
createSettingsIcon() {
// Create the container div for the settings icon
const settingsIcon = this.contentEl.createEl('div', {
cls: ['smart-connections-visualizer-settings-icon', ],
attr: { 'aria-label': 'Open graph settings' }
});
// Create SVG element for settings icon
const svg = document.createElementNS("http://www.w3.org/2000/svg", "svg");
svg.setAttribute("width", "24");
svg.setAttribute("height", "24");
svg.setAttribute("viewBox", "0 0 24 24");
svg.setAttribute("fill", "none");
svg.setAttribute("stroke", "currentColor");
svg.setAttribute("stroke-width", "2");
svg.setAttribute("stroke-linecap", "round");
svg.setAttribute("stroke-linejoin", "round");
svg.setAttribute("class", "smart-connections-visualizer-svg-icon smart-connections-visualizer-lucide-settings");
// Create path element for settings icon
const path = document.createElementNS("http://www.w3.org/2000/svg", "path");
path.setAttribute("d", "M12.22 2h-.44a2 2 0 0 0-2 2v.18a2 2 0 0 1-1 1.73l-.43.25a2 2 0 0 1-2 0l-.15-.08a2 2 0 0 0-2.73.73l-.22.38a2 2 0 0 0 .73 2.73l.15.1a2 2 0 0 1 1 1.72v.51a2 2 0 0 1-1 1.74l-.15.09a2 2 0 0 0-.73 2.73l.22.38a2 2 0 0 0 2.73.73l.15-.08a2 2 0 0 1 2 0l.43.25a2 2 0 0 1 1 1.73V20a2 2 0 0 0 2 2h.44a2 2 0 0 0 2-2v-.18a2 2 0 0 1 1-1.73l.43-.25a2 2 0 0 1 2 0l.15.08a2 2 0 0 0 2.73-.73l.22-.39a2 2 0 0 0-.73-2.73l-.15-.08a2 2 0 0 1-1-1.74v-.5a2 2 0 0 1 1-1.74l.15-.09a2 2 0 0 0 .73-2.73l-.22-.38a2 2 0 0 0-2.73-.73l-.15.08a2 2 0 0 1-2 0l-.43-.25a2 2 0 0 1-1-1.73V4a2 2 0 0 0-2-2z");
svg.appendChild(path);
// Create circle element for settings icon
const circle = document.createElementNS("http://www.w3.org/2000/svg", "circle");
circle.setAttribute("cx", "12");
circle.setAttribute("cy", "12");
circle.setAttribute("r", "3");
svg.appendChild(circle);
// Append SVG to settings icon container
settingsIcon.appendChild(svg);
settingsIcon.addEventListener('click', this.toggleDropdownMenu);
}
createRefreshIcon() {
const refreshIcon = this.contentEl.createEl('div', { cls: 'smart-connections-visualizer-refresh-icon' });
const svg = document.createElementNS("http://www.w3.org/2000/svg", "svg");
svg.setAttribute("width", "24");
svg.setAttribute("height", "24");
svg.setAttribute("viewBox", "0 0 24 24");
svg.setAttribute("fill", "none");
svg.setAttribute("stroke", "currentColor");
svg.setAttribute("stroke-width", "2");
svg.setAttribute("stroke-linecap", "round");
svg.setAttribute("stroke-linejoin", "round");
svg.setAttribute("class", "smart-connections-visualizer-svg-icon smart-connections-visualizer-lucide-rotate-ccw");
const path1 = document.createElementNS("http://www.w3.org/2000/svg", "path");
path1.setAttribute("d", "M3 12a9 9 0 1 0 9-9 9.75 9.75 0 0 0-6.74 2.74L3 8");
svg.appendChild(path1);
const path2 = document.createElementNS("http://www.w3.org/2000/svg", "path");
path2.setAttribute("d", "M3 3v5h5");
svg.appendChild(path2);
refreshIcon.appendChild(svg);
return refreshIcon; // Return the complete icon element
}
createNewXIcon() {
const xIcon = this.contentEl.createEl('div', { cls: 'smart-connections-visualizer-x-icon' });
const svg = document.createElementNS("http://www.w3.org/2000/svg", "svg");
svg.setAttribute("width", "24");
svg.setAttribute("height", "24");
svg.setAttribute("viewBox", "0 0 24 24");
svg.setAttribute("fill", "none");
svg.setAttribute("stroke", "currentColor");
svg.setAttribute("stroke-width", "2");
svg.setAttribute("stroke-linecap", "round");
svg.setAttribute("stroke-linejoin", "round");
svg.setAttribute("class", "smart-connections-visualizer-svg-icon smart-connections-visualizer-lucide-x");
const path1 = document.createElementNS("http://www.w3.org/2000/svg", "path");
path1.setAttribute("d", "M18 6 6 18");
svg.appendChild(path1);
const path2 = document.createElementNS("http://www.w3.org/2000/svg", "path");
path2.setAttribute("d", "m6 6 12 12");
svg.appendChild(path2);
xIcon.appendChild(svg);
return xIcon; // Return the complete icon element
}
setupSettingsEventListeners() {
this.setupScoreThresholdSlider();
this.setupNodeSizeSlider();
this.setupLineThicknessSlider();
this.setupCenterForceSlider();
this.setupRepelForceSlider();
this.setupLinkForceSlider();
this.setupLinkDistanceSlider();
this.setupFadeThresholdSlider();
this.setupMinLinkThicknessSlider();
this.setupMaxLinkThicknessSlider();
this.setupConnectionTypeRadios();
this.setupMaxLabelCharactersSlider();
this.setupLinkLabelSizeSlider();
this.setupNodeLabelSizeSlider();
this.setupCloseIcon();
this.setupRefreshIcon();
}
setupScoreThresholdSlider() {
const scoreThresholdSlider = document.getElementById('smart-connections-visualizer-scoreThreshold') as HTMLInputElement;
if (scoreThresholdSlider) {
scoreThresholdSlider.addEventListener('input', (event) => this.updateScoreThreshold(event));
const debouncedUpdate = debounce((event: Event) => {
this.updateVisualization(parseFloat((event.target as HTMLInputElement).value));
}, 500, true);
scoreThresholdSlider.addEventListener('input', debouncedUpdate);
}
}
updateScoreThreshold(event: any) {
const newScoreThreshold = parseFloat(event.target.value);
const label = document.getElementById('smart-connections-visualizer-scoreThresholdLabel');
this.plugin.settings.relevanceScoreThreshold = newScoreThreshold; // Update the settings
this.plugin.saveSettings(); // Save the settings
if (label) label.textContent = `Min relevance: ${(newScoreThreshold * 100).toFixed(0)}%`;
}
setupNodeSizeSlider() {
const nodeSizeSlider = document.getElementById('smart-connections-visualizer-nodeSize') as HTMLInputElement;
if (nodeSizeSlider) {
nodeSizeSlider.addEventListener('input', (event) => this.updateNodeSize(event));
}
}
updateNodeSize(event: any) {
const newNodeSize = parseFloat(event.target.value);