-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathmain.js
1394 lines (1387 loc) · 92.3 KB
/
main.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
/* eslint-disable no-fallthrough */
/* jshint esversion: 6 */
'use strict';
let obsidian = require('obsidian');
let DEFAULT_SETTINGS = {
'allowSingleClickOpenFolder': false,
'allowSingleClickOpenFolderAction': 'disabled',
'alwaysHideNoteHeaders': false,
'alwaysOpenInContinuousMode': false,
'compactModeTabGroupIds': [],
'defaultSortOrder': 'alphabetical',
// 'disableScrollRootItemsIntoView': false,
// 'disableScrollSidebarsIntoView': false,
'disableWarnings': false,
'enableScrollIntoView': true,
'enableSmoothScroll': true,
'excludedNames': [],
'extraFileTypes': [],
'includeBlockLinks': false,
'includeEmbeddedFiles': false,
'includedFileTypes': ['markdown'],
"maximumItemsToOpen": '0',
'onlyShowFileName': false,
'tabGroupIds': [],
};
class ContinuousModePlugin extends obsidian.Plugin {
async onload() {
// console.log('Loading the Continuous Mode plugin.');
await this.loadSettings();
this.addSettingTab(new ContinuousModeSettings(this.app, this));
/*-----------------------------------------------*/
// HELPERS
const workspace = this.app.workspace;
const getAllTabGroups = () => {
let root_children = workspace.rootSplit?.children || [],
left_children = workspace.leftSplit?.children || [],
right_children = workspace.rightSplit?.children || [],
floating_children = workspace.floatingSplit?.children || [],
all_tab_groups = [];
let nodes = (floating_children).concat(root_children,right_children,left_children);
if ( nodes[0] === undefined ) { return []; }
nodes?.forEach( node => { if ( node && node.type === 'tabs' ) { all_tab_groups.push(node) } else { all_tab_groups = getTabGroupsRecursively(node,all_tab_groups) } });
return all_tab_groups;
}
const getTabGroupsRecursively = (begin_node,all_tab_groups) => {
let all_children = begin_node?.children;
if ( all_children === undefined ) { return }
all_tab_groups = all_tab_groups || [];
if ( begin_node.children ) {
begin_node.children.forEach(function(child) {
if (child.type === 'tabs') { all_tab_groups.push(child); }
all_children = all_children.concat(getTabGroupsRecursively(child,all_tab_groups));
});
}
return all_tab_groups;
}
const getTabGroupById = (id) => { return getAllTabGroups()?.find( tab_group => tab_group.id === id ); } // get tab group by id, not dataset-tab-group-id
const getTabHeaderIndex = (e) => { return Array.from(e.target.parentElement.children).indexOf(e.target); }
const getActiveLeaf = () => { return workspace.activeTabGroup.children?.find( child => child.tabHeaderEl?.className?.includes('active')) ?? workspace.activeTabGroup.children?.[0]; }
const getActiveEditor = () => { return workspace.activeEditor?.editor; }
const getActiveCursor = () => { return getActiveEditor()?.getCursor('anchor'); }
const getAnchorOffset = () => { return document.getSelection().anchorOffset; }
const getSelection = () => { return document.getSelection(); }
const selectAll = (el) => {
let sel = document.getSelection(), range = document.createRange();
range.selectNodeContents(el);
sel.removeAllRanges();
sel.addRange(range);
}
const getDocumentLinks = (file,leaf) => { // get document links
let document_links = (this.app.metadataCache.getFileCache(file).links)?.map( link => link?.link ) || []; // get document links from metadata cache
let document_embeds = (this.app.metadataCache.getFileCache(file)?.embeds)?.map( link => link?.link ) || []; // get document embeds from metadata cache
if ( this.settings.includeEmbeddedFiles === true ) { document_links = document_links.concat(document_embeds); } // concat doc links & embedded files
let query_links, query_block_links = [];
let query_blocks = leaf.view?.editor?.containerEl?.querySelectorAll('.block-language-folder-overview,.block-language-dataview,.internal-query .search-result-container'); // query blocks
for ( let i = 0; i < query_blocks?.length; i++ ) {
query_links = [];
query_blocks[i].querySelectorAll('a')?.forEach( link => query_links.push(link.href) ) || query_blocks[i].querySelectorAll('.search-result-container .tree-item-inner span:nth-of-type(2)')?.forEach( query_result => query_links.push(query_result?.innerText) );
query_block_links.push(query_links)
}
if ( this.settings.includeBlockLinks === true ) { document_links = document_links.concat(query_block_links).flat() }; // concat document & query block links
document_links = document_links.map(link => obsidian.normalizePath(link.split('//obsidian.md/').reverse()[0].replace(/%20/g,' '))); // clean up links
return document_links;
}
const getFilesFromLinks = (document_links) => { // get files from links
let files = [];
document_links.forEach( link => {
files.push(this.app.vault.getFileByPath(link) || this.app.metadataCache.getFirstLinkpathDest(link,''))
})
return files;
}
const getFilesFromSearchResults = () => {
let items = [];
workspace.getLeavesOfType('search')[0].view.dom.vChildren._children.forEach( item => items.push(item.file) )
return items
}
const findDuplicateLeaves = (leaves) => {
const seen = [], duplicateLeaves = [];
leaves.forEach(leaf => {
if ( !seen.includes(leaf.view.file) ) { seen.push(leaf.view.file); } else { duplicateLeaves.push(leaf); }
});
return duplicateLeaves;
}
const isVisible = (el) => { // determine if a scrollable el is visible
const rect = el.getBoundingClientRect();
return ( rect.top >= el.offsetHeight && rect.bottom <= (window.innerHeight - el.offsetHeight || document.documentElement.clientHeight - el.offsetHeight) );
}
const inlineTitleIsVisible = () => { return getActiveLeaf()?.view?.inlineTitleEl?.offsetHeight > 0; }
const isContinuousMode = () => { return workspace.activeTabGroup.containerEl.classList.contains('is_continuous_mode'); }
const isCompactMode = (active_leaf) => {
return active_leaf ? active_leaf.parent.containerEl.classList.contains('is_compact_mode') : !!workspace.rootSplit.containerEl.querySelectorAll('.is_compact_mode').length;
}
// code modified from https://github.com/johnoscott/Obsidian-Close-Similar-Tabs:
const activateLeafThenDetach = async (leafToActivate, leafToDetach, timeout) => {
let _a;
await activateLeaf(leafToActivate, timeout);
leafToDetach.setPinned(false);
if ( Array.isArray(leafToDetach) ) { ( _a = leafToDetach.pop() ) == null ? void 0 : _a?.detach(); } else { leafToDetach?.detach(); }
}
const activateLeaf = (leaf, timeout, bool) => {
return delayedPromise( timeout, () => {
workspace.setActiveLeaf(leaf, { focus: true });
if ( bool ) { leaf?.containerEl?.click(); leaf?.tabHeaderEl?.click(); }
});
}
const delayedPromise = (timeout, callback) => {
return new Promise((resolve) => {
setTimeout( () => {
const result = callback();
resolve(result);
}, timeout);
});
}
/*-----------------------------------------------*/
// HOUSEKEEPING
const resetPinnedLeaves = () => {
workspace.iterateAllLeaves( leaf => {
switch(true) { // unpin all tabs, except originally pinned tabs
case leaf.containerEl.classList.contains('pinned'): leaf.setPinned(true); leaf.containerEl.classList.remove('pinned'); break;
case leaf.containerEl.classList.contains('temp_pinned'): leaf.setPinned(false);
leaf.containerEl.classList.remove('temp_pinned'); leaf.tabHeaderEl.classList.remove('temp_pinned'); break;
default: leaf.setPinned(false);
}
});
}
const updateSavedIds = ( (tab_group_id,type,action) => { // prune saved ids
let app_id = this.app.appId, tab_group_ids = []; getAllTabGroups().forEach( tab_group => tab_group_ids.push(app_id+'_'+tab_group.id) );
let saved_continuous_mode_ids = this.settings.tabGroupIds, filtered_continuous_mode_ids = [];
let saved_compact_mode_ids = this.settings.compactModeTabGroupIds, filtered_compact_mode_ids = [];
switch(true) {
case tab_group_id === undefined: // on active leaf change, prune saved ids
saved_continuous_mode_ids.forEach( saved_id => {
if (saved_id.split('_')[0] === app_id && tab_group_ids.includes(saved_id) || saved_id.split('_')[0] !== app_id) {
filtered_continuous_mode_ids.push(saved_id)
}
});
saved_compact_mode_ids.forEach( saved_id => {
if (saved_id.split('_')[0] === app_id && tab_group_ids.includes(saved_id.slice(0,-1)) || saved_id.split('_')[0] !== app_id) {
filtered_compact_mode_ids.push(saved_id)
}
});
this.settings.tabGroupIds = [...new Set(filtered_continuous_mode_ids)];
this.settings.compactModeTabGroupIds = [...new Set(filtered_compact_mode_ids)];
this.saveSettings(); break; // save the settings
case ( /continuous/.test(type) ):
if ( action === true ) {
saved_continuous_mode_ids.push(tab_group_id); // add id
filtered_continuous_mode_ids = saved_continuous_mode_ids;
} else {
filtered_continuous_mode_ids = saved_continuous_mode_ids.filter( saved_tab_id => !saved_tab_id.includes(tab_group_id) ); // remove id
}
this.settings.tabGroupIds = [...new Set(filtered_continuous_mode_ids)]; break;
case ( /compact_mode/.test(type) ):
filtered_compact_mode_ids = saved_compact_mode_ids.filter(
saved_tab_id => !(saved_tab_id.slice(0,-1)).includes(tab_group_id.slice(0,-1)) // mode can be compact or semi_compact, so just remove id
);
if ( action === undefined || action === true ) { filtered_compact_mode_ids.push(tab_group_id); } // add id
this.settings.compactModeTabGroupIds = [...new Set(filtered_compact_mode_ids)]; break;
}
this.saveSettings(); // save the settings
});
/*-----------------------------------------------*/
// ICONS
const icons = {
appendFolder: `<svg width="100" height="100" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" class="lucide lucide-square-arrow-down" version="1.1" id="svg2" xmlns="http://www.w3.org/2000/svg" xmlns:svg="http://www.w3.org/2000/svg"> <defs id="defs2" /> <rect width="18" height="18" x="3" y="3" rx="2" id="rect1" /> <path d="m 12,8 v 8" id="path1" /> <path d="m 8,12 4,4 4,-4" id="path2" /> <path d="M 15.999999,8 H 8" id="path1-2" /></svg>`,
panelTopDashed: `<svg xmlns="http://www.w3.org/2000/svg" width="100" height="100" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" class="lucide lucide-panel-top-dashed"><rect width="18" height="18" x="3" y="3" rx="2"/><path d="M14 9h1"/><path d="M19 9h2"/><path d="M3 9h2"/><path d="M9 9h1"/></svg>`,
replaceFolder: `<svg width="100" height="100" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" class="lucide lucide-square-arrow-down" version="1.1" id="svg2" xmlns="http://www.w3.org/2000/svg" xmlns:svg="http://www.w3.org/2000/svg"> <defs id="defs2" /> <rect width="18" height="18" x="3" y="3" rx="2" id="rect1" /> <path d="m 8,14 4,4 4,-4" id="path2" /> <path d="m 8,9.9999586 4,-4 4,4" id="path2-3" /></svg>`,
chevronDown: `<svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" class="svg-icon lucide-chevron-down"><path d="m6 9 6 6 6-6"></path></svg>`,
compactMode: `<svg xmlns="http://www.w3.org/2000/svg" width="100" height="100" viewBox="0 0 24 24"><path fill="none" stroke="currentColor" stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M3 1h14a2 2 0 0 1 2 2v14a2 2 0 0 1-2 2H3a2 2 0 0 1-2-2V3a2 2 0 0 1 2-2M10 5.5H1M10 10H1M10 14.5H1M10 19V1"/></svg>`,
semiCompactMode: `<svg xmlns="http://www.w3.org/2000/svg" width="100" height="100" viewBox="0 0 24 24"><path fill="none" stroke="currentColor" stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M3 1h14a2 2 0 0 1 2 2v14a2 2 0 0 1-2 2H3a2 2 0 0 1-2-2V3a2 2 0 0 1 2-2M10 5.5H1M10 14.5H1M10 19V1"/></svg>`
}
const addIcons = () => {
Object.keys(icons).forEach((key) => {
(0, obsidian.addIcon)(key, icons[key]);
});
};
/*-----------------------------------------------*/
// TOGGLE CONTINUOUS MODE obsidian.debounce( () => {
const toggleContinuousMode = (tab_group_id,bool) => {
let id = tab_group_id?.split('_')?.[1];
let tab_group = getTabGroupById(id);
if ( bool === undefined ) { bool = ( tab_group.containerEl.classList?.contains('is_continuous_mode') ? false : true ) }
if ( !tab_group || this.app.appId !== tab_group_id?.split('_')?.[0] ) { return }
switch(true) {
case tab_group.containerEl?.classList?.contains('is_continuous_mode') && bool !== true: // remove continuous mode
workspace.activeTabGroup.children.forEach(leaf => {
leaf.containerEl.querySelectorAll('.continuous_mode_open_links_button').forEach( btn => btn?.remove() );
if ( !leaf.containerEl.classList.contains('mod-active') ) { leaf.containerEl.style.display = 'none'; }
});
tab_group.containerEl?.classList?.remove('is_continuous_mode','is_compact_mode','is_semi_compact_mode','hide_note_titles','show_note_titles','only_show_file_name', 'is_disable_scroll'); break;
default: // add continuous mode (e.g., on app launch)
tab_group.containerEl?.classList?.add('is_continuous_mode'); // add continuous mode class
if ( this.settings.alwaysHideNoteHeaders === true && !tab_group.containerEl?.classList?.contains('show_note_titles') ) {
tab_group.containerEl?.classList?.add('hide_note_titles');
} else {
tab_group.containerEl?.classList?.add('show_note_titles');
}
if ( this.settings.enableScrollIntoView === false ) { tab_group.containerEl?.classList?.add('is_disable_scroll') }
if ( this.settings.onlyShowFileName === true ) { tab_group.containerEl?.classList?.add('only_show_file_name'); } break;
}
updateSavedIds(tab_group_id,'continuous',bool);
}
// TOGGLE COMPACT MODE
const toggleCompactMode = obsidian.debounce( (tab_group_id,bool1,bool2) => { // bool1 === false ? compact mode : semi-compact mode; bool2 === true ? restore compact mode : null
let mode = ( bool1 === false || tab_group_id.endsWith('–') ? 'is_compact_mode' : 'is_semi_compact_mode' );
let mode_id = ( bool2 === true && /\+$|-$]/m.test(tab_group_id) ? tab_group_id.slice(-1) : bool1 === false ? '–' : '+' ); // get tab group id compact mode suffix
tab_group_id = ( tab_group_id?.endsWith('–') || tab_group_id?.endsWith('+') ? tab_group_id?.slice(0,-1) : tab_group_id); // remove mode_id from tab_group_id
let tab_group = getTabGroupById(tab_group_id.split('_')[1]) || getTabGroupById(workspace.rootSplit.children[0].id);
if ( !tab_group || this.app.appId !== tab_group_id.split('_')?.[0] ) { return }
switch(true) {
case tab_group.containerEl.classList?.contains(mode) && bool2 !== true: // toggle compact mode off
tab_group.containerEl?.classList?.remove('is_compact_mode','is_semi_compact_mode'); break; // remove compact mode classes
case tab_group_id && bool2 === true: // on startup, add compact mode (initContinuousMode())
case !tab_group.containerEl.classList.contains(mode): // toggle compact mode on
if ( !tab_group.containerEl.classList.contains('is_continuous_mode') ) { toggleContinuousMode(tab_group_id,true) } // toggle on continuous mode if necessary
tab_group.containerEl.classList.remove('is_compact_mode','is_semi_compact_mode');
tab_group.containerEl.classList.add(mode); break; // toggle compact_mode classes
}
updateSavedIds(tab_group_id + mode_id,mode,bool2); // update saved ids
},0);
/*-----------------------------------------------*/
// INITIALIZE CONTINUOUS MODE
const initContinuousMode = obsidian.debounce( () => {
addIcons();
if ( this.settings.tabGroupIds.length > 0 ) { // if there are any saved tabGroupIds...
this.settings.tabGroupIds.forEach( tab_group_id => { // for each id...
if ( this.app.appId === tab_group_id?.split('_')[0] ) { // if the tabgroup belongs to the current app (window)...
toggleContinuousMode(tab_group_id,true); // restore continuous mode
}
});
}
if ( this.settings.compactModeTabGroupIds.length > 0 ) { // if there are any saved tabGroupIds...
this.settings.compactModeTabGroupIds?.forEach( tab_group_id => { // for each id...
if ( tab_group_id.startsWith(this.app.appId) ) { // if the tabgroup belongs to the current app (window)...
toggleCompactMode(tab_group_id,tab_group_id.endsWith('+'),true); // restore compact or semi-compact mode
}
});
}
},250);
workspace.onLayoutReady( async () => { initContinuousMode(); }); // initial initialization
/*-----------------------------------------------*/
// DRAG TAB HEADERS to Rearrange Leaves on dragstart
const onTabHeaderDragEnd = (e,initial_tab_header_index) => {
e.target.ondragend = function(f) {
if ( getTabHeaderIndex(f) !== initial_tab_header_index ) { rearrangeLeaves(f,initial_tab_header_index); } // only rearrange leaves if tab header is actually moved to a new position
}
}
// REARRANGE LEAVES on dragend
const rearrangeLeaves = (e,initial_tab_header_index) => {
let leaves_container = e.target.closest('.workspace-tabs').querySelector('.workspace-tab-container'); // get current tab container
let leaves = Array.from(leaves_container.children); // get current tab container leaves
let final_tab_header_index = getTabHeaderIndex(e); // get final dropped tab header index
let moved = leaves.splice(initial_tab_header_index,1); // get the moved leave
let rearranged = leaves.toSpliced(final_tab_header_index,0,moved[0]); // move the moved leaf into position
leaves_container.setChildrenInPlace(rearranged); // replace tab container content with rearranged leaves
workspace.activeTabGroup?.tabHeaderEls[final_tab_header_index]?.click(); // confirm drag and focus leaf by clicking tab
}
/*-----------------------------------------------*/
// SCROLL ACTIVE ITEMS INTO VIEW
const scrollRootItems = (target) => {
let behavior = ( this.settings.enableSmoothScroll === false || this.settings.enableScrollIntoView === false ? 'instant' : 'smooth' );
let workspaceTabs = target.closest('.workspace-tabs');
let activeLeaf = workspaceTabs.querySelector('.workspace-leaf.mod-active') || getActiveLeaf();
let workspaceTabsHeader = workspaceTabs.querySelector('.workspace-tab-header-container');
workspaceTabs.querySelector('.workspace-tab-container').scrollTo({top:activeLeaf.offsetTop - workspaceTabsHeader.offsetHeight,behavior:behavior}); // scroll leaf into view
scrollTabHeader(); // scroll tab into view
}
const scrollTabHeader = () => {
if ( this.settings.enableScrollIntoView === false ) { return }
let tabsContainer = workspace.activeTabGroup.tabHeaderContainerEl.querySelector('.workspace-tab-header-container-inner');
tabsContainer.scrollTo({left:(getActiveLeaf().tabHeaderEl.offsetLeft - getActiveLeaf().tabHeaderEl.offsetWidth),behavior:'smooth'});
}
const scrollToActiveLine = (e,el) => {
if ( this.settings.enableScrollIntoView === false ) { return }
let offset = 0, behavior = ( ( this.settings.enableSmoothScroll === false || /page/i.test(e.key) ) ? 'instant' : 'smooth' )
switch(true) {
case ( /metadata-/.test(el?.className) ): // scroll metadata/properties
case ( /metadata-/.test(e.target.className) ): // scroll metadata/properties
getActiveEditor()?.containerEl?.querySelector('.cm-active')?.classList?.remove('cm-active'); // deselect editor active line
switch(true) {
case el !== undefined:
el?.focus();
workspace.activeTabGroup.tabsContainerEl.scrollTo(
{top:getActiveLeaf().containerEl.offsetTop - workspace.activeTabGroup.tabHeaderContainerEl.offsetHeight
- getActiveLeaf().containerEl.querySelector('.metadata-properties-heading').offsetTop
- workspace.activeTabGroup.containerEl.offsetHeight/2, behavior:behavior});
break;
default: document.activeElement.scrollIntoView({behavior:behavior,block:'center'});
}
break;
default: // scroll editor
offset = ( workspace.activeEditor !== null
? getActiveLeaf().containerEl.offsetTop + getActiveLeaf().containerEl.querySelector('.cm-active')?.offsetTop - workspace.activeTabGroup.containerEl.offsetHeight/2
: getActiveLeaf().containerEl.offsetTop - getActiveLeaf().tabHeaderEl.closest('.workspace-tab-header-container').offsetHeight
);
workspace.activeTabGroup.tabsContainerEl.scrollTo({top:offset,behavior:behavior});
}
}
const scrollSideBarItems = (target) => {
if ( this.settings.enableScrollIntoView === false ) { return }
let file_explorer = workspace.getLeavesOfType('file-explorer')[0];
let adjust_height = (file_explorer.containerEl.parentElement.offsetHeight/2) - file_explorer.containerEl.querySelector('.nav-header').offsetHeight; // center focused item
let file_explorer_item = file_explorer.containerEl.querySelector('.tree-item-self:is(.is-selected,.has-focus,.is-active)');
let type = ( /workspace-tab-header|nav-header|view-header-title-container|nav-buttons-container/.test(target?.className) ? 'leaf' : 'item' );
let workspaceTabs = target?.closest('.workspace-tabs');
let workspaceTabsContainer = workspaceTabs?.querySelector('.workspace-tab-container');
let scrollEl = ( type === 'leaf' ? workspaceTabs.querySelector('.workspace-leaf.mod-active') : file_explorer_item );
switch(true) {
case ( /workspace-leaf-content/.test(target.className) && target.dataset.type === 'search' ):
workspaceTabsContainer.scrollTo({top:workspace.activeLeaf.containerEl.offsetTop - workspaceTabs.querySelector('.workspace-tab-header-container').offsetHeight,behavior:'smooth'});
break;
case type === 'leaf':
workspaceTabsContainer.scrollTo({top:scrollEl.offsetTop - workspaceTabs.querySelector('.workspace-tab-header-container').offsetHeight,behavior:'smooth'});
break;
case type === 'item' && file_explorer_item !== null && !isVisible(file_explorer_item): // only scroll if item is not visible
workspaceTabsContainer.scrollTo({top:scrollEl.offsetTop - adjust_height,behavior:'smooth'});
break;
}
}
const scrollItemsIntoView = obsidian.debounce( (e,el) => {
let target = ( el ? el : /body/i.test(e?.target?.tagName) ? workspace.getActiveViewOfType(obsidian.View).containerEl : e?.target || e?.containerEl );
if ( target === undefined || target.closest('.is_continuous_mode') === null ) { return } // ignore e.target ancestor is not in continuous mode
switch(true) {
case ( target.closest('.mod-sidedock.mod-left-split,.mod-sidedock.mod-right-split') !== null ): scrollSideBarItems(target); break; // scroll sidebar items
case ( /workspace-tab-header|workspace-leaf/.test(target.className) ): scrollRootItems(target); break; // scroll leaf into view
default: scrollTabHeader(); scrollToActiveLine(e); break; // scroll active line into view
}
},0);
/*-----------------------------------------------*/
// ARROW NAVIGATION between open leaves
const leafArrowNavigation = (e) => {
let active_leaf = getActiveLeaf(), activeTabGroupChildren = workspace.activeTabGroup.children, el = null, anchorNode = getSelection()?.anchorNode;
const is_last_line = () => {
return getActiveCursor()?.ch === getActiveEditor()?.getLine(getActiveEditor()?.lastLine()).length && getActiveCursor()?.line === ( getActiveEditor()?.lastLine() );
}
switch(true) { // Ignore arrow navigation function in these cases:
case !active_leaf.parent.containerEl.classList.contains('is_continuous_mode'): return; // not in continuous mode
case isCompactMode(): compactModeNavigation(e,active_leaf,activeTabGroupChildren); return; // use compact mode navigation
case e.target.closest('.view-header') !== null: // allow arrows in note headers
case getActiveLeaf()?.containerEl?.closest('.mod-root') === null && !getActiveEditor()?.hasFocus(): // not in editor
case e.target.querySelector('.canvas-node.is-focused') && /Arrow/.test(e.key): // editing canvas
case e.target.querySelector('.workspace-leaf-content[data-set="graph"]') && /Arrow/.test(e.key) && e.shiftKey: return; // graph active; use shift key to move graph
case workspace.leftSplit.containerEl.querySelector('.tree-item-self.nav-file-title.is-selected.has-focus') !== null:
scrollSideBarItems(workspace.leftSplit.containerEl.querySelector('.tree-item-self.nav-file-title.is-selected.has-focus')); return; // scroll focused file explorer item into view
}
e.preventDefault();
switch(e.key) {
case 'ArrowUp': case 'ArrowLeft': case 'PageUp':
switch(true) {
case getActiveCursor()?.line === 1: getActiveEditor().containerEl.classList.add('first-line-active'); return; // add class to prevent immediate nav up
case e.target === active_leaf.view.inlineTitleEl && e.key === 'ArrowLeft' && inlineTitleIsVisible(): // inline title allow arrowleft
case getAnchorOffset() !== 0
&& e.key === 'ArrowUp'
&& /inline-title/.test(anchorNode?.parentElement?.className)
&& inlineTitleIsVisible(): return; // inline-title arrowup
case ( getActiveCursor()?.line === 0 )
&& e.key !== 'ArrowLeft'
&& /cm-/.test(anchorNode?.parentElement?.className)
&& /inline-title-/.test(e.target.className)
&& !getActiveEditor().containerEl.classList.contains('first-line-active')
&& inlineTitleIsVisible():
e.preventDefault(); getActiveEditor().containerEl.classList.add('first-line-active'); return; // first editor line becomes active
case getActiveCursor()?.ch === 0 && getAnchorOffset() === 2
&& e.key !== 'ArrowLeft'
&& /inline-title|cm-/.test(anchorNode?.parentElement?.className)
&& inlineTitleIsVisible(): // nobreak
case getActiveCursor()?.line === 0 && getAnchorOffset() === 0
&& e.key !== 'ArrowLeft'
&& /cm-/.test(anchorNode?.parentElement?.className)
&& !getActiveEditor().containerEl.classList.contains('first-line-active')
&& inlineTitleIsVisible(): // nobreak
case getActiveCursor()?.line === 0 && getAnchorOffset() === 2
&& e.key === 'ArrowLeft'
&& /HyperMD-header/.test(anchorNode?.className)
&& inlineTitleIsVisible():
selectAll(active_leaf.view.inlineTitleEl); break; // select inline-title text (default behavior)
case ( /outliner-editor-view/.test(active_leaf.getViewState().type) ):
case ( /metadata-/.test(e.target.className) && !/metadata-properties-head/.test(e.target.className)): break; // select previous metadata item
case ( /html/.test(active_leaf.view.getViewType()) && !/ArrowLeft/i.test(e.key) ): // html left arrow nav page up
active_leaf.containerEl.querySelector('iframe').focus();
active_leaf.containerEl.querySelector('iframe').contentWindow.scrollBy({top:-250,left:0,behavior:'smooth'}); break;
case ( /pdf/.test(active_leaf.view.getViewType() ) ):
switch(true) {
case e.key === 'ArrowLeft': pdfPageNavigation(e); return; // pdf page navigation
case e.key === 'ArrowUp': // pdf navigation up arrow to previous leaf
active_leaf.view.viewer?.containerEl?.querySelector('.pdf-toolbar')?.blur();
active_leaf.view.viewer.containerEl.querySelector('.focused_pdf_page')?.classList.remove('focused_pdf_page'); // nobreak
} // nobreak
case getAnchorOffset() > 0 && /HyperMD-header/.test(e.target.className) && e.key === 'ArrowUp' && !inlineTitleIsVisible():
case /metadata-properties-heading/.test(e.target.classList) && e.key === 'ArrowUp' && !inlineTitleIsVisible():
case getActiveCursor()?.line === 0 && getActiveCursor()?.ch === 0 && /inline-title/.test(e.target.className):
case getActiveCursor()?.line === 0 && getActiveCursor()?.ch === 0 && e.key === 'ArrowUp' && !inlineTitleIsVisible():
case getActiveCursor()?.line === 0 && getAnchorOffset() === 2 && /HyperMD-header/.test(anchorNode?.classList) && e.key === 'ArrowUp' && !inlineTitleIsVisible():
case getAnchorOffset() === 0 && e.target === active_leaf.view.inlineTitleEl && e.key === 'ArrowUp':
case getActiveLeaf().getViewState().state.mode === 'preview' && e.key !== 'ArrowLeft': // leaf is in preview mode
case ( !/markdown/.test(active_leaf.getViewState().type) ): // nobreak; leaf is empty (new tab)
if ( active_leaf.containerEl.previousSibling !== null ) { // if not first leaf
e.preventDefault(); // prevent up arrow when leaf becomes active
workspace.setActiveLeaf(activeTabGroupChildren[activeTabGroupChildren.indexOf(active_leaf) - 1],{focus:true}); // make previous leaf active
getActiveEditor()?.setCursor({line:getActiveEditor()?.lastLine(),ch:getActiveEditor()?.lastLine()?.length - 1});return; // select last char if editor
}
} break;
case 'ArrowDown': case 'ArrowRight': case 'PageDown':
switch(true) {
case getActiveEditor()?.getLine(getActiveEditor()?.lastLine()).length === getAnchorOffset()
&& getActiveCursor()?.line === getActiveEditor()?.lastLine()
&& e.key === 'ArrowDown'
&& !getActiveEditor().containerEl.classList.contains('last-line-active'):
getActiveEditor().containerEl.classList.add('last-line-active'); // add last line active class
getActiveEditor()?.setCursor({line:getActiveEditor()?.lastLine(),ch:getActiveEditor()?.getLine(getActiveEditor()?.lastLine()).length});
return; // last line active
case e.target === active_leaf.view.inlineTitleEl && inlineTitleIsVisible()
&& e.key === 'ArrowDown':
e.preventDefault(); break; // inline-title ArrowDown
case e.target === active_leaf.view.inlineTitleEl && inlineTitleIsVisible()
&& e.key === 'ArrowRight': break; // inline-title ArrowRight
case getAnchorOffset() !== 0 && e.key === 'ArrowDown'
&& /inline-title/.test(anchorNode?.parentElement?.className)
&& inlineTitleIsVisible():
selectAll(active_leaf.view.inlineTitleEl); break; // inline title select text
case ( /outliner-editor-view/.test(active_leaf.getViewState().type) ):
case ( /metadata-/.test(e.target.className) ): break;
case ( /html/.test(active_leaf.view.getViewType() ) && e.key === 'ArrowRight' ): // html page right arrow nav page down
active_leaf.containerEl.querySelector('iframe').focus();
active_leaf.containerEl.querySelector('iframe').contentWindow.scrollBy({top:250,left:0,behavior:'smooth'}); break;
case ( /pdf/.test(active_leaf.view.getViewType() ) ):
switch(true) {
case e.key === 'ArrowRight': pdfPageNavigation(e); return; // pdf page navigation
case e.key === 'ArrowDown': // pdf navigation down arrow to next leaf
active_leaf.view.viewer?.containerEl?.querySelector('.pdf-toolbar')?.blur();
active_leaf.view.viewer.containerEl.querySelector('.focused_pdf_page')?.classList.remove('focused_pdf_page'); // nobreak
} // nobreak
case is_last_line() && e.key !== 'ArrowRight':
case getActiveLeaf().getViewState().state.mode === 'preview' && e.key !== 'ArrowRight': // leaf is in preview mode
case ( !/markdown/.test(active_leaf.getViewState().type) ):
workspace.setActiveLeaf((activeTabGroupChildren[activeTabGroupChildren.indexOf(active_leaf) + 1] || active_leaf),{focus:true}); // make next leaf active
getSelection()?.removeAllRanges();
if ( getActiveLeaf().getViewState().state.mode !== 'preview' ) {
switch(true) {
case inlineTitleIsVisible(): e.preventDefault();
getActiveLeaf().view?.inlineTitleEl.focus();
selectAll(getActiveLeaf().view?.inlineTitleEl);
el = getActiveLeaf().view?.inlineTitleEl; break; // focus inline-title
case !inlineTitleIsVisible() && getActiveLeaf().containerEl.querySelector('.metadata-properties-heading') !== null:
getActiveLeaf().containerEl.querySelector('.metadata-properties-heading').focus();
el = getActiveLeaf().containerEl.querySelector('.metadata-properties-heading'); break; // focus metadata heading
default: getActiveEditor()?.setCursor({line:0,ch:0}); // select first line, first char
}
}
} break;
}
sleep(0).then( () => { scrollItemsIntoView(e,el); });
}
// COMPACT MODE NAVIGATION
const compactModeNavigation = (e,active_leaf,activeTabGroupChildren) => {
let incr = ( /Down|Right/.test(e.key) ? 1 : -1 ), index = activeTabGroupChildren.indexOf(active_leaf) + incr;
let next_leaf = ( activeTabGroupChildren[index] ? activeTabGroupChildren[index] : incr === 1 ? activeTabGroupChildren[0] : activeTabGroupChildren[activeTabGroupChildren.length - 1]);
delete active_leaf.containerEl.querySelector('iframe')?.scrolling;
openInRightSplit(e,next_leaf); // open file in right split
scrollItemsIntoView(e,next_leaf.containerEl);
}
// PDF PAGE NAVIGATION
const pdfPageNavigation = (e) => {
let focused_pdf_page = getActiveLeaf().view.viewer.containerEl.querySelector('.focused_pdf_page');
let pdf_pages = getActiveLeaf().view.viewer.child.pdfViewer.pdfViewer._pages;
let activeTabGroupChildren = workspace.activeTabGroup.children;
let scroll_top = 0;
switch(true) {
case ( e.key === 'ArrowRight' ):
switch(true) {
case focused_pdf_page === null: pdf_pages[0].div.classList.add('focused_pdf_page'); break; // add class to first page
case focused_pdf_page.nextSibling !== null: focused_pdf_page.nextSibling.classList.add('focused_pdf_page'); // add class to next page
focused_pdf_page.classList.remove('focused_pdf_page'); break; // remove class from previous page
case focused_pdf_page.nextSibling === null: focused_pdf_page.classList.remove('focused_pdf_page'); // remove class from last page
workspace.setActiveLeaf((activeTabGroupChildren?.[activeTabGroupChildren?.indexOf(getActiveLeaf()) + 1] || getActiveLeaf()),{focus:true}); // focus next leaf
break;
} break;
case ( e.key === 'ArrowLeft' ):
switch(true) {
case focused_pdf_page === null: pdf_pages[pdf_pages.length - 1].div.classList.add('focused_pdf_page'); break; // add class to last page
case focused_pdf_page.previousSibling !== null: focused_pdf_page.previousSibling.classList.add('focused_pdf_page'); // add class to previous page
focused_pdf_page.classList.remove('focused_pdf_page'); break; // remove class from last page
case focused_pdf_page.previousSibling === null: focused_pdf_page.classList.remove('focused_pdf_page'); // remove class from first page
workspace.setActiveLeaf((activeTabGroupChildren?.[activeTabGroupChildren?.indexOf(getActiveLeaf()) - 1] || getActiveLeaf()),{focus:true}); // focus previous leaf
break;
} break;
}
scroll_top = (getActiveLeaf().view.viewer?.containerEl?.querySelector('.focused_pdf_page')?.offsetTop || 0) + getActiveLeaf().containerEl?.querySelector('.pdf-toolbar')?.offsetHeight;
getActiveLeaf().containerEl?.querySelector('.pdf-container')?.scrollTo({left:0,top:scroll_top,behavior:'smooth'});
getActiveLeaf().view.viewer?.containerEl?.querySelector('.pdf-toobar')?.click(); // needed to focus pdf viewer and enable proper page navigation by arrow keys
}
/*-----------------------------------------------*/
// OPEN ITEMS IN CONTINUOUS MODE getAllTabGroups
const openItemsInContinuousMode = async (items,action,type) => {
if ( !items ) { return }
let active_leaf, new_leaf, recent_leaf = workspace.getMostRecentLeaf(), direction, bool;
let open_files = [], open_leaves = [], included_extensions = [];
recent_leaf?.parent?.children?.forEach( child => { open_files.push(child?.view?.file); open_leaves.push(child) }); // get open files in active tab group
let appended_leaf = ( items.length === 1 ? open_leaves.find( open_leaf => items[0] === open_leaf.view.file ) : null );
let extensions = {
markdown: ['md'],
images: ['avif','bmp','jpg','jpeg','gif','png','svg','webp'],
canvas: ['canvas'],
media: ['aac','aif','aiff','ape','flac','m4a','mka','mp3','ogg','opus','wav','m4v','mkv','mov','mp4','mpeg','webm'],
pdf: ['pdf']
};
for (const [key, value] of Object.entries(extensions)) { if ( this.settings.includedFileTypes.includes(key) ) { included_extensions.push(value); } } // get included extensions
included_extensions = included_extensions.concat(this.settings.extraFileTypes).flat(Infinity).map( ext => ext.trim() ); // add extra file types, trim, and flatten
open_files = open_files.filter( file => typeof file !== 'undefined' );
items = items.filter(
item => item instanceof obsidian.TFile // item must be TFile
&& included_extensions.includes( item.extension ) // remove items included by extension
&& !this.settings.excludedNames.includes( item.basename +'.'+ item.extension ) // remove items excluded by name
);
// warnings:
switch(true) {
case (/replace/.test(action)) && this.settings.disableWarnings !== true
&& !window.confirm('You are about to replace all items in the active split. Are you sure you want to do this?'): return; // confirm replace open notes
case items.length > 99 && !window.confirm('You are about to open '+ items.length +'. Are you sure you want to do this?'): return; // warn on opening > 99 notes
case items.length === 0: activateLeafThenDetach(workspace.getActiveViewOfType(obsidian.View).leaf, workspace.getActiveViewOfType(obsidian.View).leaf,0);
return alert(type === 'document links' ? 'No document links found.' :
'No readable files found.\nCheck the Settings to see if you have included any specific file types to be opened in Continuous Mode.'); // alert no items found
}
switch(true) {
case ( /replace/i.test(action) ):
workspace.setActiveLeaf(recent_leaf,{focus:true});
switch(true) {
case appended_leaf !== null: // open single file ==> close all open leaves except appended leaf
workspace.activeTabGroup.children.forEach( child => { if ( child !== appended_leaf ) { activateLeafThenDetach(child,child,10); } });
workspace.activeTabGroup.containerEl.classList.remove('hide_pins');
resetPinnedLeaves(); // reset pinned status
break;
default: // open folder/multiple files ==> close all open leaves
workspace.activeTabGroup.children.forEach( child => { activateLeafThenDetach(child,child,0); }); break;
} break;
case ( /append/.test(action) ): // append folder items to active tab group
if ( type === 'file' ) {
findDuplicateLeaves(open_leaves).forEach( leaf => { activateLeafThenDetach(workspace.getLeafById(leaf.id),workspace.getLeafById(leaf.id),100) } ); // close dupe notes
}
items = items.filter( item => !open_files.includes(item) ); // no dupe notes
workspace.iterateAllLeaves( child => { sleep(0).then( () => { child.setPinned(false); }); });
switch(true) {
case ( /append_compact/.test(action) ):
workspace.setActiveLeaf(workspace.rootSplit.children[0].children[0],{focus:true}); break; // set active leaf
case ( /append/.test(action) ):
if ( /compact/.test(workspace.activeTabGroup.containerEl.className) ) {
workspace.activeTabGroup.containerEl.classList.remove('is_compact_mode','is_semi_compact_mode');
} break;
default:
//case items.length === 1 && open_files.includes(items[0]):
// active_leaf === recent_leaf.parent.children.filter( child => items[0] === child.view.file )
// resetPinnedLeaves(); workspace.setActiveLeaf(active_leaf,{focus:true});
// console.log(recent_leaf);
// return;
workspace.setActiveLeaf(appended_leaf,{focus:true}); // set single appended leaf to active
scrollRootItems(appended_leaf.containerEl); break; // scroll single appended leaf into view
} break;
default: // open items in new splits L/R/U/D
if ( isCompactMode() ) {
makeFirstLeafInRightSplitActive(workspace.rootSplit.children[1]); // prevent use of compact mode left root split
recent_leaf = workspace.getActiveViewOfType(obsidian.View).leaf;
}
switch(true) {
case (/down/.test(action)): direction = 'horizontal'; bool = false; break;
case (/up/.test(action)): direction = 'horizontal'; bool = true; break;
case (/left/.test(action)): direction = 'vertical'; bool = true; break;
case (/right/.test(action)): direction = 'vertical'; bool = false; break;
}
new_leaf = workspace.createLeafBySplit(recent_leaf,direction,bool);
workspace.setActiveLeaf(workspace.getLeafById(new_leaf.id),{focus:true});
}
// sort items:
let sort_order = ( // get sort order
/query block links|document links|longform/i.test(type) ? 'none' // open doc links, etc. in their listed order
: /search/.test(type) ? workspace.getLeavesOfType('search')[0].view.dom.sortOrder // open search results in search order
: this.settings.defaultSortOrder !== undefined && this.settings.defaultSortOrder !== 'disabled' ? this.settings.defaultSortOrder // use default sort order from settings
: type === undefined ? 'alphabetical'
: workspace.getLeavesOfType('file-explorer')[0].view.sortOrder
);
switch(sort_order) {
case 'alphabetical': items.sort((a,b) => (a.basename).localeCompare(b.basename,navigator.language,{sensitivity:'base',numeric:true})); break;
case 'alphabeticalReverse': items.sort((a,b) => (b.basename).localeCompare(a.basename,navigator.language,{sensitivity:'base',numeric:true})); break;
case 'byModifiedTime': items.sort((a,b) => b?.stat.mtime - a?.stat.mtime); break;
case 'byModifiedTimeReverse': items.sort((a,b) => a?.stat.mtime - b?.stat.mtime); break;
case 'byCreatedTime': items.sort((a,b) => b?.stat.ctime - a?.stat.ctime); break;
case 'byCreatedTimeReverse': items.sort((a,b) => a?.stat.ctime - b?.stat.ctime); break;
case 'none': break; // no sort
}
// open sorted items:
workspace.activeTabGroup.containerEl.classList.add('hide_pins');
workspace.activeTabGroup.containerEl.dataset.sort_order = sort_order; // set data-sort_order
const openItems = async (items) => {
let maximumItemsToOpen = ( this.settings.maximumItemsToOpen < 1 || this.settings.maximumItemsToOpen === undefined ? Infinity : this.settings.maximumItemsToOpen );
let first_leaf;
for ( let i = 0; i < maximumItemsToOpen && i < items.length; i++ ) { // limit number of items to open
active_leaf = workspace.getLeaf(); // open new tab/leaf
active_leaf.openFile(items[i]); // open file
active_leaf.setPinned(true); // pin each new tab/leaf to stop Obsidian reusing it to open next file in loop
if ( i === 0 ) { first_leaf = active_leaf }
}
if ( !isContinuousMode() ) { toggleContinuousMode(this.app.appId +'_'+ workspace.activeTabGroup?.id,true); }
if ( !isCompactMode() && /compact/.test(action) ) { toggleCompactMode( this.app.appId +'_'+ workspace.rootSplit.children[0].children[0].id,/semi/.test(action),true); }
workspace.activeTabGroup.children.forEach( child => { if ( child.getViewState().type === 'empty' ) { activateLeafThenDetach(child,child,0); } }); // remove empty leaf
workspace.activeTabGroup.containerEl.classList.remove('hide_pins'); // remove class
resetPinnedLeaves(); // reset pinned status
activateLeaf(first_leaf,0,true); // hacky workaround: call activateLeaf twice
activateLeaf(first_leaf,1000,true); // activate the first leaf
}
openItems(items);
}
// end openItemsInContinuousMode
/*-----------------------------------------------*/
const makeFirstLeafInRightSplitActive = (split) => {
let bool = ( !workspace.rootSplit.children[1] ? false : true ); // is there a right split?
let source_split = split || workspace.rootSplit.children[1] || workspace.createLeafBySplit(workspace.rootSplit,'vertical',true); // create a right split if one doesn't exist
switch(true) {
case source_split?.type === 'tabs': workspace.setActiveLeaf(source_split.children[0],{focus:true}); break; //
case source_split?.type === 'split': makeFirstLeafInRightSplitActive(source_split.children[0]); break; // recurse through splits until a tabs container is reached
}
if ( !bool ) { workspace.setActiveLeaf(source_split,{focus:true}); } // focus empty tab in right split
}
const openInRightSplit = (e,next_leaf) => {
makeFirstLeafInRightSplitActive();
getActiveLeaf().openFile(next_leaf.view.file,{active:false}); // open file
workspace.setActiveLeaf(next_leaf,{focus:true});
}
/*-----------------------------------------------*/
// Sort Items
const sortItems = async (tab_group_id,sort_order) => {
let active_tab_group = getTabGroupById(tab_group_id?.split('_')[1]);
let items = active_tab_group.children, sorted = [], pinned_leaves = [], active_split;
if ( items === null ) { return }
switch(sort_order) { // sort files
case 'alphabetical': sorted = items.toSorted(
(a,b) => (a?.view.file?.basename || '').localeCompare(b?.view.file?.basename || '',navigator.language,{sensitivity:'base',numeric:true})); break;
case 'alphabeticalReverse': sorted = items.toSorted(
(a,b) => (b?.view.file?.basename || '').localeCompare(a?.view.file?.basename || '',navigator.language,{sensitivity:'base',numeric:true})); break;
case 'byModifiedTime': sorted = items.toSorted((a,b) => b?.view.file?.stat?.mtime - a?.view.file?.stat?.mtime); break;
case 'byModifiedTimeReverse': sorted = items.toSorted((a,b) => a?.view.file?.stat?.mtime - b?.view.file?.stat?.mtime); break;
case 'byCreatedTime': sorted = items.toSorted((a,b) => b?.view.file?.stat?.ctime - a?.view.file?.stat?.ctime); break;
case 'byCreatedTimeReverse': sorted = items.toSorted((a,b) => a?.view.file?.stat?.ctime - b?.view.file?.stat?.ctime); break;
}
workspace.iterateAllLeaves( leaf => { if ( leaf.pinned === true ) { pinned_leaves.push(leaf.id) } else { leaf.setPinned(true) } }); // pin all currently open tabs; remember pin status
workspace.setActiveLeaf(active_tab_group.children[0],{focus:true});
active_tab_group.children.forEach( child => { activateLeafThenDetach(child,child,0); });
sorted.forEach( item => { // open the files
active_split = workspace.getLeaf(); // open new tab/leaf
active_split.openFile(item.view.file); // open file
active_split.setPinned(true); // pin new tab/leaf to prevent Obsidian reusing it to open next file in loop
});
workspace.iterateAllLeaves( leaf => { if ( !pinned_leaves.includes(leaf.id) ) { leaf.setPinned(false); } }); // unpin all tabs, except for originally pinned tabs
active_tab_group.containerEl.dataset.sort_order = sort_order; // set data-sort_order
};
/*-----------------------------------------------*/
// REGISTER DOM EVENTS
this.registerDomEvent(document,'click', (e) => {
let action = this.settings.allowSingleClickOpenFolderAction, path = '', items = null, active_leaf, active_compact_leaf;
switch(true) {
case typeof e.target.className === 'string' && e.target?.className?.includes('metadata-'): break;
case e.target.classList.contains('continuous_mode_open_links_button'): // nobreak
case e.target.closest('.continuous_mode_open_links_button') !== null: showLinksMenu(e); break; // open links in continuous mode
case e.target.closest('.workspace-tabs.is_compact_mode') !== null // compact mode: open in right split on tab click
&& e.target.closest('.workspace-tab-header-new-tab') === null && e.target.closest('.workspace-tab-header-tab-list') === null:
active_compact_leaf = workspace.getActiveViewOfType(obsidian.View)?.leaf;
if ( active_compact_leaf.parent.containerEl.classList.contains('is_compact_mode') ) { openInRightSplit(e,active_compact_leaf); }
scrollItemsIntoView(e,active_compact_leaf.containerEl);
workspace.setActiveLeaf(active_compact_leaf,{focus:true})
break;
case ( e.target.closest('.nav-file.tree-item') !== null && this.settings.allowSingleClickOpenFolder === true ) // open file explorer files on single click
&& !e.altKey && !e.ctrlKey && !e.shiftKey && e.button !== 2
&& action !== 'disabled':
sleep(0).then( () => {
path = e.target.closest('.nav-file-title').dataset.path, items = this.app.vault.getFileByPath(path);
openItemsInContinuousMode([items],action,'file');
}); break;
case ( /nav-folder/.test(e.target.classList) && this.settings.allowSingleClickOpenFolder === true ) // open file explorer folders on single click
&& e.target.closest('.nav-folder-collapse-indicator') === null && e.target.closest('.collapse-icon') === null
&& !e.altKey && !e.ctrlKey && !e.shiftKey && e.button !== 2
&& action !== 'disabled':
sleep(0).then( () => {
path = e.target.closest('.nav-folder-title')?.dataset?.path, items = this.app.vault.getFolderByPath(path)?.children;
openItemsInContinuousMode(items,action,'folder');
}); break;
case e.target.classList.contains('menu-item-title'): // focus tab and scroll into view
sleep(0).then( () => {
active_leaf = workspace.activeTabGroup.children.find(child => child.tabHeaderEl.className.includes('is-active'));
workspace.setActiveLeaf(active_leaf,{focus:true});
}); // nobreak
// case ( e.target.closest('.workspace-leaf')?.classList.contains('mod-active')
// && e.target.closest('.workspace-tabs')?.classList.contains('is_continuous_mode')
// && !/view-header-title|inline-title|cm-line|cm-header|cm-preview|cm-embed/.test(e.target.className)):
case ( /workspace-tab-header|nav-header|view-header-title-container/.test(e.target.className)
&& workspace.activeTabGroup.containerEl.classList.contains('is_continuous_mode')
&& !/view-header-title|inline-title/.test(e.target.className)):
workspace.setActiveLeaf(getActiveLeaf(),{focus:true});
scrollItemsIntoView(e,getActiveLeaf().containerEl); break; // click tab, scroll into view
}
});
this.registerDomEvent(document,'mousedown', (e) => {
switch(true) {
case ( e.target.closest('.nav-file.tree-item') !== null
&& this.settings.allowSingleClickOpenFolder === true )
&& !e.altKey && !e.ctrlKey && !e.shiftKey && e.button !== 2: break;
case e.target.closest('.workspace-tabs.is_compact_mode') !== null
&& e.target.closest('.workspace-tab-header-new-tab') === null && e.target.closest('.workspace-tab-header-tab-list') === null: break;
case (e.buttons === 2 || e.ctrlKey) && e.target.closest('.longform-explorer') !== null: getLongformItems(e); break; // show longform menu
}
});
this.registerDomEvent(document,'mouseup', (e) => {
const testStr = /open or append .+ in active tab group|replace active tab group|open .+ in new split|compact mode:/i;
switch(true) {
case ( /Toggle Compact Mode/.test(e.target.innerText) ): // from Tab Group Menu
case this.settings.allowSingleClickOpenFolder === false:
case e.altKey || e.ctrlKey || e.shiftKey || e.button === 2: break; // do nothing
case ( e.target.classList.contains('menu-item-title') && testStr.test(e.target.innerText) ): // nobreak; CM menu items
case ( /nav-folder/.test(e.target.classList) // file explorer folders
&& e.target.closest('.nav-folder-collapse-indicator') === null && e.target.closest('.collapse-icon') === null ):
case ( e.target.closest('.nav-file.tree-item') !== null ): // nobreak; file explorer files
workspace.iterateAllLeaves( leaf => {
if ( leaf.pinned !== true ) {
leaf.setPinned(true); leaf.containerEl.classList.add('temp_pinned'); leaf.tabHeaderEl.classList.add('temp_pinned'); // pin all unpinned leaves, add class
} else {
leaf.containerEl.classList.add('pinned'); // mark originally pinned leaves
}
}); break;
}
});
this.registerDomEvent(window,'mouseover', (e) => {
let continuous_mode_open_links_button, button_container_el;
switch(true) {
case e.target.closest('.markdown-reading-view,.markdown-preview-view') !== null: // show button in reading view
switch(true) {
case e.target.closest('.block-language-dataview') !== null:
button_container_el = e.target.closest('.block-language-dataview'); break;
case e.target.closest('.internal-query') !== null:
button_container_el = e.target.closest('.internal-query')?.querySelector('.internal-query-header'); break;
} break;
case e.target.closest('.markdown-source-view') !== null: // show button in edit view
switch(true) {
case e.target.closest('.cm-preview-code-block')?.querySelector('.internal-query-header') !== null:
button_container_el = e.target.closest('.cm-preview-code-block')?.querySelector('.internal-query-header'); break;
case e.target.closest('.cm-preview-code-block')?.querySelector('.internal-query-header') === null:
button_container_el = e.target.closest('.cm-preview-code-block'); break;
} break;
}
if ( button_container_el?.querySelector('.continuous_mode_open_links_button') === null ) { // add open links button if needed
continuous_mode_open_links_button = button_container_el?.createEl('div',{cls:'continuous_mode_open_links_button clickable-icon'});
continuous_mode_open_links_button.setAttribute('aria-label','Continuous Mode');
continuous_mode_open_links_button.innerHTML = `<svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" class="lucide lucide-chevron-down"><path d="m6 9 6 6 6-6"/></svg>`;
}
});
this.registerDomEvent(window,'keydown', (e) => {
if ( /pageup|pagedown|arrow/i.test(e.key) && !e.altKey && !e.ctrlKey && !e.metaKey && !e.shiftKey ) {
leafArrowNavigation(e);
}
});
this.registerDomEvent(window,'dragstart', (e) => {
if ( !e.target.closest('.workspace-tabs')?.classList.contains('is_continuous_mode')) { return; }
if ( e.target.classList.contains('workspace-tab-header') ) { onTabHeaderDragEnd(e,getTabHeaderIndex(e)); } // get initial tab header index for onTabHeaderDragEnd()
});
/*-----------------------------------------------*/
// ADD CONTEXTUAL MENU ITEMS
const addContinuousModeMenuItem = (item, tab_group_id, leaf) => { // add continuous mode menu items (toggle, headers, sort)
let tab_group = getTabGroupById(tab_group_id?.split('_')[1]), tab_group_el = tab_group?.containerEl, tab_group_classList = tab_group_el?.classList;
item.setTitle('Continuous Mode')
.setIcon('scroll-text')
.setSection( leaf ? 'pane' : 'action' )
.setSubmenu().addItem((item2) => {
item2.setTitle('Toggle Continuous Mode')
.setIcon('scroll-text')
.setChecked( tab_group_classList?.contains('is_continuous_mode') ? true : false )
.onClick(async () => {
toggleContinuousMode(tab_group_id || this.app.appId +'_'+ workspace.activeTabGroup.id);
})
})
.addSeparator()
.addItem((item12) => {
if ( tab_group === workspace.rootSplit.children[0] ) {
item12.setTitle('Toggle Compact Mode')
.setIcon('compactMode')
// .setDisabled( tab_group_classList.contains('is_continuous_mode') ? false : true )
.setChecked( tab_group_classList?.contains('is_compact_mode') ? true : false )
.onClick(async () => {
toggleCompactMode(tab_group_id,false,( tab_group_classList?.contains('is_compact_mode') ? false : true ));
})
}
})
.addItem((item12) => {
if ( tab_group === workspace.rootSplit.children[0] ) {
item12.setTitle('Toggle Semi-Compact Mode')
.setIcon('semiCompactMode')
// .setDisabled( tab_group_classList.contains('is_continuous_mode') ? false : true )
.setChecked( tab_group_classList?.contains('is_semi_compact_mode') ? true : false )
.onClick(async () => {
toggleCompactMode(tab_group_id,true,( tab_group_classList?.contains('is_semi_compact_mode') ? false : true ));
})
}
})
.addSeparator()
.addItem((item3) => {
item3.setTitle( tab_group_classList?.contains('hide_note_titles') ? 'Show note headers' : 'Hide note headers' )
.setIcon('panelTopDashed')
.setDisabled( tab_group_classList?.contains('is_continuous_mode') ? false : true )
// .setChecked( tab_group_classList?.contains('hide_note_titles') ? true : false )
.onClick(async () => {
if ( workspace.activeTabGroup?.containerEl?.classList?.contains('hide_note_titles') ) {
workspace.activeTabGroup?.containerEl?.classList?.remove('hide_note_titles');
workspace.activeTabGroup?.containerEl?.classList?.add('show_note_titles');
} else {
workspace.activeTabGroup?.containerEl?.classList?.remove('show_note_titles');
workspace.activeTabGroup?.containerEl?.classList?.add('hide_note_titles');
}
})
})
.addItem((item4) => {
item4.setTitle('Change sort order')
.setIcon('arrow-up-narrow-wide')
.setDisabled( tab_group?.children?.length > 1 && tab_group_classList?.contains('is_continuous_mode') ? false : true )
.setSubmenu()
.addItem((item5) => {
item5.setTitle('File name (A to Z)')
.setChecked( tab_group_el?.dataset?.sort_order === 'alphabetical' ? true : false )
.onClick(async () => {
sortItems(tab_group_id,'alphabetical');
})
})
.addItem((item6) => {
item6.setTitle('File name (Z to A)')
.setChecked( tab_group_el?.dataset?.sort_order === 'alphabeticalReverse' ? true : false )
.onClick(async () => {
sortItems(tab_group_id,'alphabeticalReverse');
})
})
.addSeparator()
.addItem((item7) => {
item7.setTitle('Modified time (new to old)')
.setChecked( tab_group_el?.dataset?.sort_order === 'byModifiedTime' ? true : false )
.onClick(async () => {
sortItems(tab_group_id,'byModifiedTime');
})
})
.addItem((item8) => {
item8.setTitle('Modified time (old to new)')
.setChecked( tab_group_el?.dataset?.sort_order === 'byModifiedTimeReverse' ? true : false )
.onClick(async () => {
sortItems(tab_group_id,'byModifiedTimeReverse');
})
})
.addSeparator()
.addItem((item9) => {
item9.setTitle('Created time (new to old)')
.setChecked( tab_group_el?.dataset?.sort_order === 'byCreatedTime' ? true : false )
.onClick(async () => {
sortItems(tab_group_id,'byCreatedTime');
})
})
.addItem((item10) => {
item10.setTitle('Created time (old to new)')
.setChecked( tab_group_el?.dataset?.sort_order === 'byCreatedTimeReverse' ? true : false )
.onClick(async () => {
sortItems(tab_group_id,'byCreatedTimeReverse');
})
})
})
.addSeparator();
}
const openItemsInContinuousModeMenuItems = (item,file,type) => { // open items in continuous mode menu items
type = ( type !== undefined ? type : file instanceof obsidian.TFolder ? 'folder contents' : file instanceof obsidian.TFile ? 'file' : null );
file = ( file instanceof obsidian.TFile ? [file] : file instanceof obsidian.TFolder ? file.children : file );
item.setTitle('Continuous Mode')
.setIcon('scroll-text')
.setSection( 'open')
.setSubmenu()
.addItem((item6) => {
item6.setTitle('Open or append '+type+' in active tab group')
.setIcon('appendFolder')
.onClick(async () => {
openItemsInContinuousMode(file,'append',type); })
})
.addItem((item7) => {
item7.setTitle('Replace active tab group with '+type)
.setIcon('replaceFolder')
.onClick(async () => {
openItemsInContinuousMode(file,'replace',type) })
})
.addSeparator()
.addItem((item2) => {
item2.setTitle('Open '+type+' in new split left')
.setIcon('panel-left-close')
.onClick(async () => { openItemsInContinuousMode(file,'open_left',type); })
})
.addItem((item3) => {
item3.setTitle('Open '+type+' in new split right')
.setIcon('panel-right-close')
.onClick(async () => { openItemsInContinuousMode(file,'open_right',type); })
})
.addItem((item5) => {
item5.setTitle('Open '+type+' in new split up')
.setIcon('panel-top-close')
.onClick(async () => { openItemsInContinuousMode(file,'open_up',type); })
})
.addItem((item4) => {
item4.setTitle('Open '+type+' in new split down')
.setIcon('panel-bottom-close')
.onClick(async () => { openItemsInContinuousMode(file,'open_down',type); })
})
.addSeparator()
.addItem((item8) => {
item8.setTitle('Open or append '+type+' in Compact Mode')
.setIcon('compactMode')
.onClick(async () => { openItemsInContinuousMode(file,'append_compact_mode',type) })
})
.addItem((item8) => {
item8.setTitle('Replace Compact Mode with '+type)
.setIcon('compactMode')
.onClick(async () => {
if ( this.settings.disableWarnings === false && window.confirm('Warning: This will close all open notes in the active tab group. Are you sure you want to do this?') ) {
openItemsInContinuousMode(file,'replace_compact_mode',type)
}
})
})
}
const showLinksMenu = (e) => {
const open_links_menu = new obsidian.Menu(); let links, files = [];
switch(true) {
case e.target.closest('.cm-preview-code-block') !== null: // editing view
links = e.target.closest('.cm-preview-code-block')?.querySelectorAll('a.internal-link,.search-result .tree-item-inner'); break;
case e.target.closest('.internal-query') !== null: // reading-view
links = e.target.closest('.internal-query')?.querySelectorAll('.search-result .tree-item-inner'); break;
case e.target.closest('.block-language-dataview') !== null: // reading-view
links = e.target.closest('.block-language-dataview')?.querySelectorAll('a.internal-link'); break;
}
links = Array.from(links).map( link => link.dataset?.href || link.innerText ); // get links
files = getFilesFromLinks(links); // get files
open_links_menu.setUseNativeMenu(false);
open_links_menu.addItem( item => openItemsInContinuousModeMenuItems(item,files,'query block links') );
open_links_menu.showAtMouseEvent(e);
}
/*-----------------------------------------------*/
// OTHER PLUG-INS SUPPORT
// Longform async
const getLongformItems = (object) => { // object = mousedown event or file
let longform_explorer = workspace.getLeavesOfType('VIEW_TYPE_LONGFORM_EXPLORER')[0].view.contentEl.children[0];
let longform_scenes_arr = Array.from(longform_explorer.querySelectorAll('#scene-list > ul > li'));
let target_item, filtered_items, paths = [];
let kind = ( object.target?.classList.contains('current-draft-path') ? 'project' : 'scenes' );
const open_longform_menu = new obsidian.Menu();
switch(kind) {
case 'project':
longform_scenes_arr.forEach( scene => { paths.push( scene.querySelector('.scene-container').getAttribute('data-scene-path') ); }); // get all scenes paths
open_longform_menu.setUseNativeMenu(false);
open_longform_menu.addItem( item => openItemsInContinuousModeMenuItems(item,getFilesFromLinks(paths),'Longform project') ); // add the menu item
open_longform_menu.showAtMouseEvent(object); break;
case 'scenes':
if ( longform_scenes_arr === undefined ) { return }
target_item = longform_scenes_arr.find( item => item?.querySelector('.scene-container').getAttribute('data-scene-path') === object.path ); // get the clicked item
filtered_items = ( target_item === undefined ? undefined : [target_item] ); // add target item to the filtered list
longform_scenes_arr = longform_scenes_arr.slice(longform_scenes_arr.indexOf(target_item)); // remove items before target
for ( let i = 1; i < longform_scenes_arr.length; i++ ) { // start @ 1 => don't filter target item
if ( longform_scenes_arr[i].dataset.indent > target_item.dataset.indent ) { filtered_items.push(longform_scenes_arr[i]) } else { break }
};
if ( filtered_items ) {
filtered_items.forEach( filtered_item => { paths.push( filtered_item.querySelector('.scene-container').getAttribute('data-scene-path') ); }); // get paths
}
return getFilesFromLinks(paths);
}
}
/*-----------------------------------------------*/
// CONTEXT MENU EVENTS
this.registerEvent(
this.app.workspace.on('editor-menu', (menu,editor) => { // on editor-menu
if ( !!editor.containerEl.querySelectorAll('.cm-active .cm-link, .cm-active .cm-hmd-internal-link, .cm-active .cm-link-alias') ) { // prevent adding CM menus twice
menu.addItem((item) => {
let links = getDocumentLinks(editor.editorComponent.view.file,editor.editorComponent.view.leaf), files = getFilesFromLinks(links);
addContinuousModeMenuItem(item,this.app.appId +'_'+ editor?.editorComponent.owner.leaf.parent.id) // add continuous mode items