-
Notifications
You must be signed in to change notification settings - Fork 0
/
extension.js
1173 lines (872 loc) · 37.8 KB
/
extension.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
// based on previous work done by:
// - Dhrumil Shah (@wandcrafting) and Robert Haisfield (@RobertHaisfield): https://www.figma.com/file/5shwLdUCHxSaPNEO7pazbe/
// - Azlen Elza (@azlenelza): https://gist.github.com/azlen/cc8d543f0e46e17d978e705650df0e9e
let internals = {};
internals.extensionId = 'roam-reference-path';
// dev mode can activated by using the special key/value 'dev=true' in the query string;
// example: https://roamresearch.com?dev=true/#/app/<GRAPH_NAME>
internals.isDev = String(new URLSearchParams(window.location.search).get('dev')).includes('true');
internals.extensionAPI = null;
internals.cleaners = [];
internals.settingsCached = {
color: null,
bulletColorShade: null,
bulletScaleFactor: null,
referenceColorShade: null,
referenceFontWeightDescription: null,
lineColorShade: null,
lineWidth: null,
lineStyle: null,
lineRoundness: null,
showOnHover: null,
lineTopOffset: null,
lineLeftOffset: null,
// derived settings
bulletColorHex: null, // derived from color + bulletColorShade
referenceColorHex: null, // derived from color + referenceColorShade
lineColorHex: null, // derived from color + lineColorShade
bulletColorHoverHex: null, // derived from bulletColorHex
referenceColorHoverHex: null, // derived from colreferenceColorHex
lineColorHoverHex: null, // derived frolineColorHex
referenceFontWeightValue: null, // derived from referenceFontWeightDescription
};
internals.settingsDefault = {
color: 'indigo',
bulletColorShade: '500',
bulletScaleFactor: '1.5',
referenceColorShade: '500',
referenceFontWeightDescription: 'medium',
lineColorShade: '500',
lineWidth: '1px',
lineStyle: 'solid',
lineRoundness: '2px',
showOnHover: false,
lineTopOffset: 'auto',
lineLeftOffset: 'auto',
};
internals.installedExtensions = {
roamStudio: false, // https://github.com/rcvd/RoamStudio
};
internals.serialId = 0;
internals.selector = {};
internals.selector.permanent = {
mainView: 'div.roam-main',
sidebar: 'div#right-sidebar'
};
internals.selector.temporary = {
mainView: 'div.rm-article-wrapper',
sidebar: 'div#roam-right-sidebar-content'
};
internals.blockList = {
mainView: [],
sidebar: [],
};
internals.isEditing = {
mainView: false,
sidebar: false,
};
internals.onMouseEnter = {
mainView: function onMouseEnterMainView (ev) {
// console.log('onMouseEnter (mainView) @ ' + Date.now());
if (internals.isEditing.mainView) { return }
removeReferencePath(internals.blockList.mainView);
addReferencePath(internals.blockList.mainView, ev.target, true);
},
sidebar: function onMouseEnterSidebar (ev) {
// console.log('onMouseEnter (sidebar) @ ' + Date.now());
if (internals.isEditing.sidebar) { return }
removeReferencePath(internals.blockList.sidebar);
addReferencePath(internals.blockList.sidebar, ev.target, true);
},
};
internals.onMouseLeave = {
mainView: function onMouseLeaveMainView (ev) {
// console.log('onMouseLeave (mainView) @ ' + Date.now());
if (internals.isEditing.mainView) { return }
removeReferencePath(internals.blockList.mainView);
},
sidebar: function onMouseLeaveSidebar (ev) {
// console.log('onMouseLeave (sidebar) @ ' + Date.now());
if (internals.isEditing.sidebar) { return }
removeReferencePath(internals.blockList.sidebar);
},
};
function onload({ extensionAPI }) {
log('ONLOAD (start)');
internals.extensionAPI = extensionAPI;
initializeSettings();
resetStyle();
startPermanentObserver({ target: document.querySelector(internals.selector.permanent.mainView) });
startPermanentObserver({ target: document.querySelector(internals.selector.permanent.sidebar) });
log('ONLOAD (end)');
}
function onunload() {
log('ONUNLOAD (start)');
stopObserver({ target: 'all' });
removeStyle();
log('ONUNLOAD (end)');
}
function log() {
let isProd = !internals.isDev;
if (isProd) { return }
console.log(`${internals.extensionId} ${Date.now()}]`, ...arguments);
}
function initializeSettings() {
log('initializeSettings');
let panelConfig = {
tabTitle: `Reference Path${internals.isDev ? ' (dev)' : ''}`,
settings: []
};
panelConfig.settings.push({
id: 'color',
name: 'Main color',
// description: '...',
action: {
type: 'select',
// roam uses tailwindcss, but the full color palette is not available in the css loaded by roam;
// so we add the full palette manually in internals.tailwindColors (at the bottom);
items: ['gray', 'slate (gray variant)', 'zinc (gray variant)', 'neutral (gray variant)', 'stone (gray variant)', 'red', 'orange', 'amber', 'yellow', 'lime', 'green', 'emerald', 'teal', 'cyan', 'sky', 'blue', 'indigo', 'violet', 'purple', 'fuchsia', 'pink', 'rose'],
onChange: value => { updateSettingsCached({ key: 'color', value }) },
}
});
panelConfig.settings.push({
id: 'bulletColorShade',
name: 'Bullets: color shade',
description: '100 is light; 900 is dark. Values between 400 and 600 should be good for most people. See the full color palette here: https://tailwindcss.com/docs/customizing-colors',
action: {
type: 'select',
items: ['disabled', '100', '200', '300', '400', '500', '600', '700', '800', '900'],
onChange: value => { updateSettingsCached({ key: 'bulletColorShade', value }) },
}
});
panelConfig.settings.push({
id: 'bulletScaleFactor',
name: 'Bullets: scale factor',
description: 'Use 2 to make the bullet size twice of the original size.',
action: {
type: 'select',
items: ['disabled', '1.25', '1.5', '1.75', '2', '2.25', '2.5'],
onChange: value => { updateSettingsCached({ key: 'bulletScaleFactor', value }) },
},
});
panelConfig.settings.push({
id: 'referenceColorShade',
name: 'References (double brackets and tags): color shade',
description: 'See the description given for bullets.',
action: {
type: 'select',
items: ['disabled', '100', '200', '300', '400', '500', '600', '700', '800', '900'],
onChange: value => { updateSettingsCached({ key: 'referenceColorShade', value }) },
}
});
panelConfig.settings.push({
id: 'referenceFontWeightDescription',
name: 'References (double brackets and tags): font weight',
// description: 'Make the references that belong to blocks in the active path stand out.',
action: {
type: 'select',
// weight names corresponding to ['300', '400', '500', '600', '700']
items: ['disabled', 'light', 'normal', 'medium', 'semibold', 'bold'],
onChange: value => { updateSettingsCached({ key: 'referenceFontWeightDescription', value }) },
},
});
panelConfig.settings.push({
id: 'lineColorShade',
name: 'Lines: color shade',
description: 'See the description given for bullets. If this setting is disabled, the remaining settings for lines will also be disabled.',
action: {
type: 'select',
items: ['disabled', '100', '200', '300', '400', '500', '600', '700', '800', '900'],
onChange: value => { updateSettingsCached({ key: 'lineColorShade', value }) },
}
});
panelConfig.settings.push({
id: 'lineWidth',
name: 'Lines: width',
description: '',
action: {
type: 'select',
// TODO: consider subpixel values? does any browser actually implements them for border-width?
items: ['1px', '2px', '3px'],
onChange: value => { updateSettingsCached({ key: 'lineWidth', value }) },
},
});
panelConfig.settings.push({
id: 'lineStyle',
name: 'Lines: style',
description: 'See examples here: https://developer.mozilla.org/en-US/docs/Web/CSS/border-style',
action: {
type: 'select',
items: ['solid', 'dotted', 'dashed'],
onChange: value => { updateSettingsCached({ key: 'lineStyle', value }) },
},
});
panelConfig.settings.push({
id: 'lineRoundness',
name: 'Lines: corner roundness',
description: 'Use 0px for no roundness, that is, to get right angle corners.',
action: {
type: 'select',
items: ['0px', '1px', '2px', '3px', '4px', '5px', '6px', '7px', '8px', '9px'],
onChange: value => { updateSettingsCached({ key: 'lineRoundness', value }) },
},
});
panelConfig.settings.push({
id: 'showOnHover',
name: 'Hover mode',
description: 'Show reference path on hover (when there is no block being edited).',
action: {
type: 'switch',
onChange: ev => { updateSettingsCached({ key: 'showOnHover', value: ev.target.checked }) },
},
});
panelConfig.settings.push({
id: 'lineTopOffset',
name: 'Lines: top offset (ADVANCED)',
description: 'Use a value different from auto only if the line seems out of place vertically. Recommended values are between 9.5px and 10.5px (depends on the line width).',
action: {
type: 'select',
items: ['auto', '6.5px', '7.0px', '7.5px', '8px', '8.5px', '9px', '9.5px', '10px', '10.5px', '11px', '11.5px', '12.0px', '12.5px'],
onChange: value => { updateSettingsCached({ key: 'lineTopOffset', value }) },
},
});
panelConfig.settings.push({
id: 'lineLeftOffset',
name: 'Lines: left offset (ADVANCED)',
description: 'Use a value different from auto only if the line seems out of place horizontally. Recommended values are between 5px and 6px (depends on the line width).',
action: {
type: 'select',
items: ['auto', '3.5px', '4px', '4.5px', '5px', '5.5px', '6px', '6.5px', '7px', '7.5px', '8px', '8.5px'],
onChange: value => { updateSettingsCached({ key: 'lineLeftOffset', value }) },
},
});
let { extensionAPI } = internals;
extensionAPI.settings.panel.create(panelConfig);
let settingsKeys = panelConfig.settings.map(o => o.id);
// cache the panel settings internally for best performance;
// if necessary, initialize the panel settings with our default values;
// the styles will be reseted manually in onload, to avoid adding/removing
// incomplete style tag several times;
for (let key of settingsKeys) {
let value = extensionAPI.settings.get(key);
if (value == null) {
value = internals.settingsDefault[key];
extensionAPI.settings.set(key, value);
}
updateSettingsCached({ key, value, resetStyle: false });
}
// make an initial detection for other extensions
for (let delayInSeconds of [1, 2, 4, 8]) {
setTimeout(detectOtherExtensions, delayInSeconds * 1000);
}
}
function detectOtherExtensions() {
internals.installedExtensions.roamStudio = (document.querySelectorAll('style[id^="roamstudio"]').length > 0);
// add more detections here
}
function updateSettingsCached({ key, value, resetStyle: _resetStyle }) {
internals.settingsCached[key] = value;
// derived settings
let { bulletColorShade, referenceColorShade, lineColorShade, referenceFontWeightDescription } = internals.settingsCached;
internals.settingsCached.bulletColorHex = getColorHex({ shade: bulletColorShade });
internals.settingsCached.referenceColorHex = getColorHex({ shade: referenceColorShade });
internals.settingsCached.lineColorHex = getColorHex({ shade: lineColorShade });
internals.settingsCached.bulletColorHoverHex = getShadeAndTint(internals.settingsCached.bulletColorHex, 4).tint;
internals.settingsCached.referenceColorHoverHex = getShadeAndTint(internals.settingsCached.referenceColorHex, 4).tint;
internals.settingsCached.lineColorHoverHex = getShadeAndTint(internals.settingsCached.lineColorHex, 4).tint;
internals.settingsCached.referenceFontWeightValue = getFontWeightValue({ fontWeightDescription: referenceFontWeightDescription });
// styles are reseted here, unless we explicitly turn it off
if (_resetStyle !== false) {
resetStyle();
}
if (key === 'showOnHover') {
if (value === true) {
addMouseHoverListeners(document.querySelector(internals.selector.temporary.mainView));
addMouseHoverListeners(document.querySelector(internals.selector.temporary.sidebar));
}
else {
removeMouseHoverListeners(document.querySelector(internals.selector.temporary.mainView));
removeMouseHoverListeners(document.querySelector(internals.selector.temporary.sidebar));
}
}
log('updateSettingsCached', { key, value, 'internals.settingsCached': internals.settingsCached });
}
function getColorHex({ shade }) {
let { color } = internals.settingsCached;
if (shade === 'disabled' || color == null) { return 'disabled' }
color = color.split('(')[0].trim(); // strip the '(' from the grays
let shadeIdx = Math.floor(Number(shade) / 100); // we want a mapping like { 50: 0, 100: 1, 200: 2, ... }
let colorHex = internals.tailwindColors[color][shadeIdx];
return colorHex;
}
function getFontWeightValue({ fontWeightDescription }) {
// https://developer.mozilla.org/en-US/docs/Web/CSS/font-weight#common_weight_name_mapping
let nameToValue = {
'light': '300',
'normal': '400',
'medium': '500',
'semibold': '600',
'bold': '700',
'disabled': 'disabled'
}
return nameToValue[fontWeightDescription];
}
function resetStyle() {
// we have to resort to dynamic stylesheets (instead of using extension.css directly) to be able
// to support the 'disabled' option in our settings (when 'disabled' is selected, we don't add
// any css at all relative to that setting/feature); this is the simplest way to avoid having
// css rules that might conflict with other extensions/themes;
// on top of that, the fact that css cascade doesn't work as expected with css custom variables is
// another reason to use dynamic styles; more details here: https://adactio.com/journal/16993
removeStyle();
// use setTimeout to make sure our css styles are loaded after styles from other extensions
setTimeout(addStyle, internals.isDev ? 200 : 100);
}
function addStyle() {
log('addStyle');
let { extensionId } = internals;
let textContent = '';
if (internals.settingsCached.bulletColorHex !== 'disabled') {
textContent += `
[data-reference-path-has-style] > div.controls span.rm-bullet__inner,
[data-reference-path-has-style] > div.controls span.rm-bullet__inner--user-icon {
background-color: var(--${extensionId}-bullet-color);
}
`;
}
if (internals.settingsCached.bulletScaleFactor !== 'disabled') {
textContent += `
[data-reference-path-has-style] > div.controls span.rm-bullet__inner,
[data-reference-path-has-style] > div.controls span.rm-bullet__inner--user-icon {
transform: scale(var(--${extensionId}-bullet-scale-factor));
}
`;
}
if (internals.settingsCached.referenceColorHex !== 'disabled') {
textContent += `
[data-reference-path-has-style] > div.rm-block-text span.rm-page-ref__brackets {
color: var(--${extensionId}-brackets-color);
}
[data-reference-path-has-style] > div.rm-block-text span.rm-page-ref--link {
color: var(--${extensionId}-link-color);
}
[data-reference-path-has-style] > div.rm-block-text span.rm-page-ref--tag {
color: var(--${extensionId}-link-color);
}
`;
}
if (internals.settingsCached.referenceFontWeightValue !== 'disabled') {
textContent += `
[data-reference-path-has-style] > div.rm-block-text span.rm-page-ref__brackets {
font-weight: var(--${extensionId}-brackets-weight);
}
[data-reference-path-has-style] > div.rm-block-text span.rm-page-ref--link {
font-weight: var(--${extensionId}-link-weight);
}
[data-reference-path-has-style] > div.rm-block-text span.rm-page-ref--tag {
font-weight: var(--${extensionId}-link-weight);
}
`;
}
if (internals.settingsCached.lineColorHex !== 'disabled') {
textContent += `
[data-reference-path-has-style] > div.controls span.bp3-popover-target::before {
border-color: var(--${extensionId}-line-color);
border-width: var(--${extensionId}-line-width);
border-style: var(--${extensionId}-line-style);
border-bottom-left-radius: var(--${extensionId}-line-roundness);
position: absolute;
top: var(--${extensionId}-line-top-offset);
left: var(--${extensionId}-line-left-offset);
width: var(--${extensionId}-box-width);
height: var(--${extensionId}-box-height);
content: '';
border-right: none;
border-top: none;
pointer-events: none;
z-index: 20;
}
`;
}
let extensionStyle = document.createElement('style');
extensionStyle.textContent = textContent;
extensionStyle.dataset.extensionId = `${extensionId}-${Date.now()}`;
extensionStyle.dataset.title = `dynamic styles added by the ${extensionId} extension`;
document.head.appendChild(extensionStyle);
}
function removeStyle() {
log('removeStyle');
// we assume no one else has added a <style data-extension-id="reference-path-28373625"> before, which seems
// to be a strong hypothesis
let extensionStyles = Array.from(document.head.querySelectorAll(`style[data-extension-id^="${internals.extensionId}"]`));
for (let styleEl of extensionStyles) {
styleEl.remove()
}
}
function addMouseHoverListeners (target) {
if (target == null) { return; }
// get blocks that don't already have hover listeners
let blocksWithoutListeners = Array.from(target.querySelectorAll(`div.roam-block:not([data-reference-path-has-hover])`));
// console.log({ 'blocksWithoutListeners.length': blocksWithoutListeners.length })
if (blocksWithoutListeners.length === 0) { return }
let targetKey = getTargetKey({ target });
let onMouseEnter = internals.onMouseEnter[targetKey];
let onMouseLeave = internals.onMouseLeave[targetKey];
for (let idx = 0; idx < blocksWithoutListeners.length; idx++) {
let el = blocksWithoutListeners[idx];
el.addEventListener('mouseenter', onMouseEnter);
el.addEventListener('mouseleave', onMouseLeave);
el.dataset.referencePathHasHover = 'true';
}
}
function removeMouseHoverListeners (target) {
if (target == null) { return; }
// get blocks that have hover listeners
let blocksWithListeners = Array.from(target.querySelectorAll(`div.roam-block[data-reference-path-has-hover]`));
// console.log({ 'blocksWithListeners.length': blocksWithListeners.length })
if (blocksWithListeners.length === 0) { return }
let targetKey = getTargetKey({ target });
let onMouseEnter = internals.onMouseEnter[targetKey];
let onMouseLeave = internals.onMouseLeave[targetKey];
for (let idx = 0; idx < blocksWithListeners.length; idx++) {
let el = blocksWithListeners[idx];
el.removeEventListener('mouseenter', onMouseEnter);
el.removeEventListener('mouseleave', onMouseLeave);
delete el.dataset.referencePathHasHover; // might not work in safari <= 10?
}
}
function startTemporaryObserver ({ target }) {
// if (target == null) { return }
if (target.dataset.referencePathObserverId != null) { return }
log('main');
let targetKey = getTargetKey({ target });
// array to store a list of div.rm-block-main (where we will add our custom css properties);
// we will mutate this array in addReferencePath / removeReferencePath
let blockList = internals.blockList[targetKey];
// some evidence that getElementsByTagName is faster than querySelector:
// https://humanwhocodes.com/blog/2010/09/28/why-is-getelementsbytagname-faster-that-queryselectorall/
// https://gomakethings.com/javascript-selector-performance/
// this assumes that the only textarea element inside target is the one that exists
// when a block is being edited
let textareaLiveList = target.getElementsByTagName('textarea');
// TODO: comment
internals.isEditing[targetKey] = false;
// reference: https://developer.mozilla.org/en-US/docs/Web/API/MutationObserver/MutationObserver
let temporaryObserverCallback = function temporaryObserverCallback (mutationList) {
// return early 1: typing in the active block (in edit mode)
let mutationCount = mutationList.length;
let isProbablyTyping = (mutationCount === 1);
if (isProbablyTyping) {
let mutation0 = mutationList[0];
// 2 cases to consider
// 1) the textarea/block does not become empty with the mutation (common case)
// 2) the textarea/block becomes empty (example: using the backspace on the last character)
let isMutationForTyping = true
&& mutation0.target.tagName === 'TEXTAREA'
&& (false
|| (mutation0.addedNodes.length === 1 && mutation0.addedNodes[0].nodeType === 3)
|| (mutation0.removedNodes.length === 1 && mutation0.removedNodes[0].nodeType === 3)
);
if (isMutationForTyping) { return; }
}
// return early 2: are there any other special cases to consider?
if (internals.isDev) {
log('observerCallback', { mutationList });
}
// is there any situation where we have 2 or more textareas?
if (internals.isDev && textareaLiveList.length > 1) { debugger }
// common case: when the textarea exists somewhere
if (textareaLiveList.length > 0 /*&& textareaLiveList.item(0).contains(document.activeElement)*/) {
removeReferencePath(blockList);
addReferencePath(blockList, textareaLiveList.item(0));
internals.isEditing[targetKey] = true;
}
else if (textareaLiveList.length === 0) {
if (document.activeElement != null && document.activeElement.className.includes('cm-content') && target.contains(document.activeElement)) {
// edge case: the focus **IS** in a code block (and the code block is a child of target)
let closestBlock = document.activeElement.closest('div.rm-block-main');
if (closestBlock.dataset.referencePathHasStyle == null) {
removeReferencePath(blockList);
addReferencePath(blockList, document.activeElement);
}
// else { debugger }
internals.isEditing[targetKey] = true;
}
else {
// common case: the focus **IS NOT** in a code block
removeReferencePath(blockList);
internals.isEditing[targetKey] = false;
}
}
if (internals.settingsCached.showOnHover) {
addMouseHoverListeners(target);
}
};
// for the temporary observers we want to monitor the target element and the entire subtree
// of elements rooted at target; we also use the characterData option to observe changes in
// code editor blocks (useful in particular when syntax highlighting is set to "plain text")
// reference: https://developer.mozilla.org/en-US/docs/Web/API/MutationObserver/observe#parameters
let options = {
subtree: true,
childList: true,
characterData: true,
//attributes: true // warning! this will make the observer terribly slow!
}
let { observer, observerId } = startObserver({ target, callback: temporaryObserverCallback, options });
internals.cleaners.push({
observerId,
handler: () => {
log('cleaner for temporary observer', { observerId });
observer.disconnect();
delete target.dataset.referencePathObserverId; // might not work in safari <= 10?
removeReferencePath(blockList);
removeMouseHoverListeners(target);
}
});
// initialize the hover behaviours; note that addMouseHoverListeners is also called in the temporary
// observer callback, but it's ok to also have it here because it will only add listeners for blocks that
// don't have them already; in fact we need to initialize it here because the temporary callback is not always called immediatelly
// after the observer is started
if (internals.settingsCached.showOnHover) {
addMouseHoverListeners(target);
}
}
function addReferencePath(blockList, el, isHover = false) {
if (internals.isDev) {
log('addReferencePath', { el });
}
// removeReferencePath();
let { extensionId } = internals;
let { bulletColorHex, bulletColorHoverHex, bulletScaleFactor } = internals.settingsCached;
let { referenceColorHex, referenceColorHoverHex, referenceFontWeightValue } = internals.settingsCached;
let { lineColorHex, lineColorHoverHex, lineRoundness, lineWidth, lineStyle, lineTopOffset, lineLeftOffset } = internals.settingsCached;
let blockPrevious = null;
if (lineColorHex !== 'disabled') {
if (lineTopOffset === 'auto') {
lineTopOffset = getLineTopOffsetAuto(lineWidth);
}
if (lineLeftOffset === 'auto') {
lineLeftOffset = getLineLeftOffsetAuto(lineWidth);
}
}
let iterationCount = 0, iterationLimit = 99;
for(;;) {
if (++iterationCount > iterationLimit) {
log('iterationLimit reached');
break;
}
let blockContainerEl;
// 1) we are looking for the closest div.roam-block-container (relative to el) in the ancestor elements
// 1a) optimized case: do not call closest()
// this is usually safe because the DOM tree in roam is known and stable, and we usually are able to reach
// the correct elements by using the .parentElement property directly; however if other extensions are loaded
// the DOM tree might be changed; those cases are handled below
if (el.tagName === 'TEXTAREA') {
blockContainerEl = el.parentElement.parentElement.parentElement;
}
else {
blockContainerEl = el.parentElement;
}
// 1b) non-optimized case: if necessary, call .closest()
if (!(blockContainerEl.className.includes('roam-block-container'))) {
blockContainerEl = el.closest('div.roam-block-container');
}
// if div.roam-block-container was not found at this point, it means we have reached
// the root of the DOM tree, so it's time to exit; it might also mean that the DOM tree
// is not as expected, in which case we exit early and abort showing the reference path;
if (blockContainerEl == null) { break; }
// 2) we are now looking for the closest div.rm-block-main (relative to blockContainerEl)
// in the descendant elements; we use a strategy similar to the above;
// 2a) optimized case: do not call .querySelector()
let blockEl = blockContainerEl.firstElementChild;
// 2b) non-optimized case: if necessary, call .querySelector()
if (!(blockEl.className.includes('rm-block-main'))) {
blockEl = blockContainerEl.querySelector('div.rm-block-main');
}
// if div.rm-block-main was not found at this point it means the DOM tree is not as expected;
// exit early and abort showing the reference path;
if (blockEl == null) { break; }
// we now have everything we need to show the reference path
// 1 - set css variables for bullets
if (bulletColorHex !== 'disabled') {
blockEl.style.setProperty(`--${extensionId}-bullet-color`, isHover ? bulletColorHoverHex : bulletColorHex);
}
if (bulletScaleFactor !== 'disabled') {
blockEl.style.setProperty(`--${extensionId}-bullet-scale-factor`, bulletScaleFactor);
}
// 2 - set css variables for references (brackets and tags)
if (referenceColorHex !== 'disabled') {
blockEl.style.setProperty(`--${extensionId}-brackets-color`, isHover ? referenceColorHoverHex : referenceColorHex);
blockEl.style.setProperty(`--${extensionId}-link-color`, isHover ? referenceColorHoverHex : referenceColorHex);
}
if (referenceFontWeightValue !== 'disabled') {
blockEl.style.setProperty(`--${extensionId}-brackets-weight`, referenceFontWeightValue);
blockEl.style.setProperty(`--${extensionId}-link-weight`, referenceFontWeightValue);
}
if (lineColorHex !== 'disabled') {
// 3 - set css variables for lines
let isInitialBlock = (blockPrevious == null);
if (isInitialBlock) {
// make sure the span.bp3-popover-target::before pseudo-element is not drawn for the initial block
blockEl.style.setProperty(`--${extensionId}-line-width`, '0');
blockEl.style.setProperty(`--${extensionId}-box-width`, '0');
blockEl.style.setProperty(`--${extensionId}-box-height`, '0');
}
else {
// reference: https://developer.mozilla.org/en-US/docs/Web/API/Element/getBoundingClientRect
let bboxCurrent = blockEl.getBoundingClientRect()
let bboxPrevious = blockPrevious.getBoundingClientRect()
// normally we have boxWidth > 0 and boxHeight > 0, but there are some cases in which
// boxHeight is 0 (embedded blocks)
// TODO: in RTL languages this logic must be inverted somehow
let boxWidthNumeric = bboxPrevious.x - bboxCurrent.x;
let boxHeightNumeric = bboxPrevious.y - bboxCurrent.y;
if (boxWidthNumeric > 0 && boxHeightNumeric > 0) {
blockEl.style.setProperty(`--${extensionId}-line-width`, `${lineWidth}`);
blockEl.style.setProperty(`--${extensionId}-line-color`, isHover ? lineColorHoverHex : lineColorHex);
blockEl.style.setProperty(`--${extensionId}-line-style`, lineStyle);
blockEl.style.setProperty(`--${extensionId}-line-roundness`, `${lineRoundness}`);
blockEl.style.setProperty(`--${extensionId}-line-top-offset`, `${lineTopOffset}`);
blockEl.style.setProperty(`--${extensionId}-line-left-offset`, `${lineLeftOffset}`);
let boxWidth = `${boxWidthNumeric}px`;
let boxHeight = `${boxHeightNumeric}px`;
blockEl.style.setProperty(`--${extensionId}-box-width`, `${boxWidth}`);
blockEl.style.setProperty(`--${extensionId}-box-height`, `${boxHeight}`);
}
}
}
blockEl.dataset.referencePathHasStyle = 'true';
blockList.push(blockEl);
// go to the parent and repeat
blockPrevious = blockEl;
el = blockContainerEl.parentElement;
}
}
function removeReferencePath(blockList) {
if (internals.isDev) {
log('removeReferencePath');
}
if (blockList.length === 0) { return }
let { extensionId } = internals;
for (let idx = 0; idx < blockList.length; idx++) {
let blockEl = blockList[idx];
blockEl.style.removeProperty(`--${extensionId}-bullet-scale-factor`);
blockEl.style.removeProperty(`--${extensionId}-bullet-color`);
blockEl.style.removeProperty(`--${extensionId}-brackets-color`);
blockEl.style.removeProperty(`--${extensionId}-brackets-weight`);
blockEl.style.removeProperty(`--${extensionId}-link-color`);
blockEl.style.removeProperty(`--${extensionId}-link-weight`);
blockEl.style.removeProperty(`--${extensionId}-line-color`);
blockEl.style.removeProperty(`--${extensionId}-line-roundness`);
blockEl.style.removeProperty(`--${extensionId}-line-width`);
blockEl.style.removeProperty(`--${extensionId}-line-style`);
blockEl.style.removeProperty(`--${extensionId}-line-top-offset`);
blockEl.style.removeProperty(`--${extensionId}-line-left-offset`);
blockEl.style.removeProperty(`--${extensionId}-box-width`);
blockEl.style.removeProperty(`--${extensionId}-box-height`);
delete blockEl.dataset.referencePathHasStyle; // might not work in safari <= 10?
}
// https://stackoverflow.com/questions/1232040/how-do-i-empty-an-array-in-javascript
blockList.length = 0;
}
function getLineTopOffsetAuto(lineWidth) {
lineWidth = parseFloat(lineWidth);
let lineTopOffset = '';
if (internals.installedExtensions.roamStudio) {
if (lineWidth === 1) {
lineTopOffset = '7.0px';
}
else if (lineWidth === 2) {
lineTopOffset = '7.5px';
}
else if (lineWidth === 3) {
lineTopOffset = '8.0px';
}
}
else {
if (lineWidth === 1) {
lineTopOffset = '9.5px';
}
else if (lineWidth === 2) {
lineTopOffset = '10px';
}
else if (lineWidth === 3) {
lineTopOffset = '10.5px';
}
}
return lineTopOffset;
}
function getTargetKey({ target }) {
let targetKey = '';
if (target.matches(internals.selector.permanent.mainView) || target.matches(internals.selector.temporary.mainView)) {
targetKey = 'mainView';
}
else if (target.matches(internals.selector.permanent.sidebar) || target.matches(internals.selector.temporary.sidebar)) {
targetKey = 'sidebar';
}
else {
throw new Error('unexpected target element');
}
return targetKey;
}
function getLineLeftOffsetAuto(lineWidth, bulletScaleFactor) {
lineWidth = parseFloat(lineWidth);
let lineLeftOffset = '';
if (lineWidth === 1) {
lineLeftOffset = '6px';
}
else if (lineWidth === 2) {
lineLeftOffset = '5.5px';
}
else if (lineWidth === 3) {
lineLeftOffset = '5px';
}
return lineLeftOffset;
}
function startPermanentObserver({ target }) {
// avoid having repeated observers in the same target (though in theory it should never happen)
if (target.dataset.referencePathObserverId != null) { return }
let targetKey = getTargetKey({ target });
let permanentObserverCallback = function permanentObserverCallback (mutationList) {
for (let mutation of mutationList) {
let wasOpened = false;
let wasClosed = false;
if (targetKey === 'mainView') {
// a page is opened/closed in the main view when this element is added/removed: target > div.roam-body-main > div.rm-article-wrapper
wasOpened = true
&& mutation.addedNodes.length > 0
&& mutation.addedNodes[0].children.length > 0
&& mutation.addedNodes[0].children[0].matches(internals.selector.temporary.mainView);
wasClosed = true
&& mutation.removedNodes.length > 0