This repository was archived by the owner on Jun 24, 2025. It is now read-only.
-
-
Notifications
You must be signed in to change notification settings - Fork 152
Expand file tree
/
Copy pathnote_tree.ts
More file actions
1807 lines (1430 loc) · 67 KB
/
Copy pathnote_tree.ts
File metadata and controls
1807 lines (1430 loc) · 67 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import hoistedNoteService from "../services/hoisted_note.js";
import treeService from "../services/tree.js";
import utils from "../services/utils.js";
import contextMenu from "../menus/context_menu.js";
import froca from "../services/froca.js";
import branchService from "../services/branches.js";
import ws from "../services/ws.js";
import NoteContextAwareWidget from "./note_context_aware_widget.js";
import server from "../services/server.js";
import noteCreateService from "../services/note_create.js";
import toastService from "../services/toast.js";
import appContext, { type CommandListenerData, type EventData } from "../components/app_context.js";
import keyboardActionsService from "../services/keyboard_actions.js";
import clipboard from "../services/clipboard.js";
import protectedSessionService from "../services/protected_session.js";
import linkService from "../services/link.js";
import options from "../services/options.js";
import protectedSessionHolder from "../services/protected_session_holder.js";
import dialogService from "../services/dialog.js";
import shortcutService from "../services/shortcuts.js";
import { t } from "../services/i18n.js";
import type FBranch from "../entities/fbranch.js";
import type LoadResults from "../services/load_results.js";
import type FNote from "../entities/fnote.js";
import type { NoteType } from "../entities/fnote.js";
import type { AttributeRow, BranchRow } from "../services/load_results.js";
import type { SetNoteOpts } from "../components/note_context.js";
import type { TouchBarItem } from "../components/touch_bar.js";
import type { TreeCommandNames } from "../menus/tree_context_menu.js";
const TPL = /*html*/`
<div class="tree-wrapper">
<style>
.tree-wrapper {
flex-grow: 1;
flex-shrink: 1;
flex-basis: 60%;
font-family: var(--tree-font-family);
font-size: var(--tree-font-size);
position: relative;
min-height: 0;
}
.tree {
height: 100%;
overflow: auto;
padding-bottom: 35px;
padding-top: 5px;
}
.tree-actions {
background-color: var(--launcher-pane-background-color);
z-index: 100;
position: absolute;
bottom: 0;
display: flex;
align-items: flex-end;
justify-content: flex-end;
right: 17px;
border-radius: 7px;
border: 1px solid var(--main-border-color);
}
button.tree-floating-button {
margin: 1px;
font-size: 1.5em;
padding: 5px;
max-height: 34px;
color: var(--launcher-pane-text-color);
background-color: var(--button-background-color);
border-radius: var(--button-border-radius);
border: 1px solid transparent;
}
button.tree-floating-button:hover {
border: 1px solid var(--button-border-color);
}
.collapse-tree-button {
right: 100px;
}
.scroll-to-active-note-button {
right: 55px;
}
.tree-settings-button {
right: 10px;
}
.tree-settings-popup {
display: none;
position: absolute;
background-color: var(--accented-background-color);
border: 1px solid var(--main-border-color);
padding: 20px;
z-index: 1000;
width: 340px;
border-radius: 10px;
}
.tree .hidden-node-is-hidden {
display: none;
}
</style>
<div class="tree"></div>
<div class="tree-actions">
<button class="tree-floating-button bx bx-layer-minus collapse-tree-button"
title="${t("note_tree.collapse-title")}"
data-trigger-command="collapseTree"></button>
<button class="tree-floating-button bx bx-crosshair scroll-to-active-note-button"
title="${t("note_tree.scroll-active-title")}"
data-trigger-command="scrollToActiveNote"></button>
<button class="tree-floating-button bx bxs-tree tree-settings-button"
title="${t("note_tree.tree-settings-title")}"></button>
</div>
<div class="tree-settings-popup">
<h4>${t("note_tree.tree-settings-title")}</h4>
<div class="form-check">
<label class="form-check-label tn-checkbox">
<input class="form-check-input hide-archived-notes" type="checkbox" value="">
${t("note_tree.hide-archived-notes")}
</label>
</div>
<div class="form-check">
<label class="form-check-label tn-checkbox">
<input class="form-check-input auto-collapse-note-tree" type="checkbox" value="">
${t("note_tree.automatically-collapse-notes")}
<span class="bx bx-info-circle"
title="${t("note_tree.automatically-collapse-notes-title")}"></span>
</label>
</div>
<br/>
<button class="btn btn-sm btn-primary save-tree-settings-button" type="submit">${t("note_tree.save-changes")}</button>
</div>
</div>
`;
const MAX_SEARCH_RESULTS_IN_TREE = 100;
// this has to be hanged on the actual elements to effectively intercept and stop click event
const cancelClickPropagation: JQuery.TypeEventHandler<unknown, unknown, unknown, unknown, any> = (e) => e.stopPropagation();
// TODO: Fix once we remove Node.js API from public
type Timeout = NodeJS.Timeout | string | number | undefined;
// TODO: Deduplicate with server special_notes
type LauncherType = "launcher" | "note" | "script" | "customWidget" | "spacer";
// TODO: Deduplicate with the server
interface CreateLauncherResponse {
success: boolean;
message: string;
note: {
noteId: string;
};
}
interface ExpandedSubtreeResponse {
branchIds: string[];
}
interface Node extends Fancytree.NodeData {
noteId: string;
parentNoteId: string;
branchId: string;
isProtected: boolean;
noteType: NoteType;
}
interface RefreshContext {
noteIdsToUpdate: Set<string>;
noteIdsToReload: Set<string>;
}
export default class NoteTreeWidget extends NoteContextAwareWidget {
private $tree!: JQuery<HTMLElement>;
private $treeActions!: JQuery<HTMLElement>;
private $treeSettingsButton!: JQuery<HTMLElement>;
private $treeSettingsPopup!: JQuery<HTMLElement>;
private $saveTreeSettingsButton!: JQuery<HTMLElement>;
private $hideArchivedNotesCheckbox!: JQuery<HTMLElement>;
private $autoCollapseNoteTree!: JQuery<HTMLElement>;
private treeName: "main";
private autoCollapseTimeoutId?: Timeout;
private lastFilteredHoistedNotePath?: string | null;
private tree!: Fancytree.Fancytree;
constructor() {
super();
this.treeName = "main"; // legacy value
}
doRender() {
this.$widget = $(TPL);
this.$tree = this.$widget.find(".tree");
this.$treeActions = this.$widget.find(".tree-actions");
this.$tree.on("mousedown", ".unhoist-button", () => hoistedNoteService.unhoist());
this.$tree.on("mousedown", ".refresh-search-button", (e) => this.refreshSearch(e));
this.$tree.on("mousedown", ".add-note-button", (e) => {
const node = $.ui.fancytree.getNode(e as unknown as Event);
const parentNotePath = treeService.getNotePath(node);
noteCreateService.createNote(parentNotePath, {
isProtected: node.data.isProtected
});
});
this.$tree.on("mousedown", ".enter-workspace-button", (e) => {
const node = $.ui.fancytree.getNode(e as unknown as Event);
this.triggerCommand("hoistNote", { noteId: node.data.noteId });
});
// fancytree doesn't support middle click, so this is a way to support it
this.$tree.on("mousedown", ".fancytree-title", (e) => {
if (e.which === 2) {
const node = $.ui.fancytree.getNode(e as unknown as Event);
const notePath = treeService.getNotePath(node);
if (notePath) {
appContext.tabManager.openTabWithNoteWithHoisting(notePath, {
activate: e.shiftKey ? true : false
});
}
e.stopPropagation();
e.preventDefault();
}
});
this.$treeSettingsPopup = this.$widget.find(".tree-settings-popup");
this.$hideArchivedNotesCheckbox = this.$treeSettingsPopup.find(".hide-archived-notes");
this.$autoCollapseNoteTree = this.$treeSettingsPopup.find(".auto-collapse-note-tree");
this.$treeSettingsButton = this.$widget.find(".tree-settings-button");
this.$treeSettingsButton.on("click", (e) => {
if (this.$treeSettingsPopup.is(":visible")) {
this.$treeSettingsPopup.hide();
return;
}
this.$hideArchivedNotesCheckbox.prop("checked", this.hideArchivedNotes);
this.$autoCollapseNoteTree.prop("checked", this.autoCollapseNoteTree);
const top = this.$treeActions[0].offsetTop - (this.$treeSettingsPopup.outerHeight() ?? 0);
const left = Math.max(0, this.$treeActions[0].offsetLeft - (this.$treeSettingsPopup.outerWidth() ?? 0) + (this.$treeActions.outerWidth() ?? 0));
this.$treeSettingsPopup
.css({
top,
left
})
.show();
return false;
});
this.$treeSettingsPopup.on("click", (e) => {
e.stopPropagation();
});
$(document).on("click", () => this.$treeSettingsPopup.hide());
this.$saveTreeSettingsButton = this.$treeSettingsPopup.find(".save-tree-settings-button");
this.$saveTreeSettingsButton.on("click", async () => {
await this.setHideArchivedNotes(this.$hideArchivedNotesCheckbox.prop("checked"));
await this.setAutoCollapseNoteTree(this.$autoCollapseNoteTree.prop("checked"));
this.$treeSettingsPopup.hide();
this.reloadTreeFromCache();
});
// note tree starts initializing already during render which is atypical
Promise.all([options.initializedPromise, froca.initializedPromise]).then(() => this.initFancyTree());
this.setupNoteTitleTooltip();
}
setupNoteTitleTooltip() {
// the following will dynamically set tree item's tooltip if the whole item's text is not currently visible
// if the whole text is visible then no tooltip is show since that's unnecessarily distracting
// see https://github.com/zadam/trilium/pull/1120 for discussion
// code inspired by https://gist.github.com/jtsternberg/c272d7de5b967cec2d3d
const isEnclosing = ($container: JQuery<HTMLElement>, $sub: JQuery<HTMLElement>) => {
const conOffset = $container.offset();
const conDistanceFromTop = (conOffset?.top ?? 0) + ($container.outerHeight(true) ?? 0);
const conDistanceFromLeft = (conOffset?.left ?? 0) + ($container.outerWidth(true) ?? 0);
const subOffset = $sub.offset();
const subDistanceFromTop = (subOffset?.top ?? 0) + ($sub.outerHeight(true) ?? 0);
const subDistanceFromLeft = (subOffset?.left ?? 0) + ($sub.outerWidth(true) ?? 0);
return conDistanceFromTop > subDistanceFromTop
&& (conOffset?.top ?? 0) < (subOffset?.top ?? 0)
&& conDistanceFromLeft > subDistanceFromLeft
&& (conOffset?.left ?? 0) < (subOffset?.left ?? 0);
};
this.$tree.on("mouseenter", "span.fancytree-title", (e) => {
e.currentTarget.title = isEnclosing(this.$tree, $(e.currentTarget)) ? "" : e.currentTarget.innerText;
});
}
get hideArchivedNotes() {
return options.is(`hideArchivedNotes_${this.treeName}`);
}
async setHideArchivedNotes(val: string) {
await options.save(`hideArchivedNotes_${this.treeName}`, val.toString());
}
get autoCollapseNoteTree() {
return options.is("autoCollapseNoteTree");
}
async setAutoCollapseNoteTree(val: string) {
await options.save("autoCollapseNoteTree", val.toString());
}
initFancyTree() {
const treeData = [this.prepareRootNode()];
this.$tree.fancytree({
titlesTabbable: true,
keyboard: true,
extensions: ["dnd5", "clones", "filter"],
source: treeData,
scrollOfs: {
top: 100,
bottom: 100
},
scrollParent: this.$tree,
minExpandLevel: 2, // root can't be collapsed
click: (event: MouseEvent | JQuery.ClickEvent | JQuery.MouseDownEvent | React.PointerEvent<HTMLCanvasElement>, data): boolean => {
this.activityDetected();
const targetType = data.targetType;
const node = data.node;
const ctrlKey = utils.isCtrlKey(event);
if (node.isSelected() && targetType === "icon") {
this.triggerCommand("openBulkActionsDialog", {
selectedOrActiveNoteIds: this.getSelectedOrActiveNoteIds(node)
});
return false;
} else if (targetType === "title" || targetType === "icon") {
if (event.shiftKey && !ctrlKey) {
const activeNode = this.getActiveNode();
if (activeNode.getParent() !== node.getParent()) {
return true;
}
this.clearSelectedNodes();
function selectInBetween(first: Fancytree.FancytreeNode, second: Fancytree.FancytreeNode) {
for (let i = 0; first && first !== second && i < 10000; i++) {
first.setSelected(true);
first = first.getNextSibling();
}
second.setSelected();
}
if (activeNode.getIndex() < node.getIndex()) {
selectInBetween(activeNode, node);
} else {
selectInBetween(node, activeNode);
}
node.setFocus(true);
} else if (ctrlKey) {
const notePath = treeService.getNotePath(node);
appContext.tabManager.openTabWithNoteWithHoisting(notePath, {
activate: event.shiftKey ? true : false
});
} else if (event.altKey) {
node.setSelected(!node.isSelected());
node.setFocus(true);
} else if (data.node.isActive()) {
// this is important for single column mobile view, otherwise it's not possible to see again previously displayed note
this.tree.reactivate();
} else {
node.setActive();
}
return false;
}
return true;
},
beforeActivate: (event, { node }) => {
// hidden subtree is hidden hackily - we want it to be present in the tree so that we can switch to it
// without reloading the whole tree, but we want it to be hidden when hoisted to root. FancyTree allows
// filtering the display only by ascendant - i.e. if the root is visible, all the descendants are as well.
// We solve it by hiding the hidden subtree via CSS (class "hidden-node-is-hidden"),
// but then we need to prevent activating it, e.g. by keyboard
if (hoistedNoteService.getHoistedNoteId() === "_hidden") {
// if we're hoisted in hidden subtree, we want to avoid crossing to "visible" tree,
// which could happen via UP key from hidden root
return node.data.noteId !== "root";
}
// we're not hoisted to hidden subtree, the only way to cross is via DOWN key to the hidden root
return node.data.noteId !== "_hidden";
},
activate: async (event, data) => {
// click event won't propagate so let's close context menu manually
contextMenu.hide();
// hide all dropdowns, fix calendar widget dropdown doesn't close when click on a note
$('.dropdown-menu').parent('.dropdown').find('[data-bs-toggle="dropdown"]').dropdown('hide');
this.clearSelectedNodes();
const notePath = treeService.getNotePath(data.node);
const activeNoteContext = appContext.tabManager.getActiveContext();
const opts: SetNoteOpts = {};
if (activeNoteContext?.viewScope?.viewMode === "contextual-help") {
opts.viewScope = activeNoteContext.viewScope;
}
await activeNoteContext?.setNote(notePath, opts);
},
expand: (event, data) => this.setExpanded(data.node.data.branchId, true),
collapse: (event, data) => this.setExpanded(data.node.data.branchId, false),
filter: {
counter: false,
mode: "hide",
autoExpand: true
},
dnd5: {
autoExpandMS: 600,
preventLazyParents: false,
dragStart: (node, data) => {
if (node.data.noteId === "root" || utils.isLaunchBarConfig(node.data.noteId) || node.data.noteId.startsWith("_options")) {
return false;
}
const notes = this.getSelectedOrActiveNodes(node).map((node) => ({
noteId: node.data.noteId,
branchId: node.data.branchId,
title: node.title
}));
if (notes.length === 1) {
linkService.createLink(notes[0].noteId, { referenceLink: true, autoConvertToImage: true }).then(($link) => data.dataTransfer.setData("text/html", $link[0].outerHTML));
} else {
Promise.all(notes.map((note) => linkService.createLink(note.noteId, { referenceLink: true, autoConvertToImage: true }))).then((links) => {
const $list = $("<ul>").append(...links.map(($link) => $("<li>").append($link)));
data.dataTransfer.setData("text/html", $list[0].outerHTML);
});
}
data.dataTransfer.setData("text", JSON.stringify(notes));
return true; // allow dragging to start
},
dragEnter: (node, data) => {
if (node.data.noteType === "search") {
return false;
} else if (node.data.noteId === "_lbRoot") {
return false;
} else if (node.data.noteId.startsWith("_options")) {
return false;
} else if (node.data.noteType === "launcher") {
return ["before", "after"];
} else if (["_lbAvailableLaunchers", "_lbVisibleLaunchers"].includes(node.data.noteId)) {
return ["over"];
} else {
return true;
}
},
dragDrop: async (node, data) => {
if (
(data.hitMode === "over" && node.data.noteType === "search") ||
(["after", "before"].includes(data.hitMode) && (node.data.noteId === hoistedNoteService.getHoistedNoteId() || node.getParent().data.noteType === "search"))
) {
await dialogService.info("Dropping notes into this location is not allowed.");
return;
}
const dataTransfer = data.dataTransfer;
if (dataTransfer && dataTransfer.files && dataTransfer.files.length > 0) {
const files = [...dataTransfer.files]; // chrome has issue that dataTransfer.files empties after async operation
const importService = await import("../services/import.js");
importService.uploadFiles("notes", node.data.noteId, files, {
safeImport: true,
shrinkImages: true,
textImportedAsText: true,
codeImportedAsCode: true,
explodeArchives: true,
replaceUnderscoresWithSpaces: true
});
} else {
const jsonStr = dataTransfer.getData("text");
let notes: BranchRow[];
try {
notes = JSON.parse(jsonStr);
} catch (e) {
logError(`Cannot parse JSON '${jsonStr}' into notes for drop`);
return;
}
// This function MUST be defined to enable dropping of items on the tree.
// data.hitMode is 'before', 'after', or 'over'.
const selectedBranchIds = notes
.map((note) => note.branchId)
.filter((branchId) => branchId) as string[];
if (data.hitMode === "before") {
branchService.moveBeforeBranch(selectedBranchIds, node.data.branchId);
} else if (data.hitMode === "after") {
branchService.moveAfterBranch(selectedBranchIds, node.data.branchId);
} else if (data.hitMode === "over") {
branchService.moveToParentNote(selectedBranchIds, node.data.branchId);
} else {
throw new Error(`Unknown hitMode '${data.hitMode}'`);
}
}
}
},
lazyLoad: (event, data) => {
const { noteId, noteType } = data.node.data;
if (noteType === "search") {
const notePath = treeService.getNotePath(data.node.getParent());
// this is a search cycle (search note is a descendant of its own search result)
if (notePath.includes(noteId)) {
data.result = [];
return;
}
data.result = froca
.loadSearchNote(noteId)
.then(() => {
const note = froca.getNoteFromCache(noteId);
let childNoteIds = note.getChildNoteIds();
if (note.type === "search" && childNoteIds.length > MAX_SEARCH_RESULTS_IN_TREE) {
childNoteIds = childNoteIds.slice(0, MAX_SEARCH_RESULTS_IN_TREE);
}
return froca.getNotes(childNoteIds);
})
.then(() => {
const note = froca.getNoteFromCache(noteId);
return this.prepareChildren(note);
});
} else {
data.result = froca.loadSubTree(noteId).then((note) => this.prepareChildren(note));
}
},
clones: {
highlightActiveClones: true
},
enhanceTitle: async function (
event: Event,
data: {
node: Fancytree.FancytreeNode;
noteId: string;
}
) {
const node = data.node;
if (!node.data.noteId) {
// if there's "non-note" node, then don't enhance
// this can happen for e.g. "Load error!" node
return;
}
const note = await froca.getNote(node.data.noteId, true);
if (!note) {
return;
}
const activeNoteContext = appContext.tabManager.getActiveContext();
const $span = $(node.span);
$span.find(".tree-item-button").remove();
const isHoistedNote = activeNoteContext && activeNoteContext.hoistedNoteId === note.noteId && note.noteId !== "root";
if (note.hasLabel("workspace") && !isHoistedNote) {
const $enterWorkspaceButton = $(`<span class="tree-item-button enter-workspace-button bx bx-door-open" title="${t("note_tree.hoist-this-note-workspace")}"></span>`).on(
"click",
cancelClickPropagation
);
$span.append($enterWorkspaceButton);
}
if (note.type === "search") {
const $refreshSearchButton = $(`<span class="tree-item-button refresh-search-button bx bx-refresh" title="${t("note_tree.refresh-saved-search-results")}"></span>`).on(
"click",
cancelClickPropagation
);
$span.append($refreshSearchButton);
}
// TODO: Deduplicate with server's notes.ts#getAndValidateParent
if (!["search", "launcher"].includes(note.type)
&& !note.isOptions()
&& !note.isLaunchBarConfig()
&& !note.noteId.startsWith("_help")
) {
const $createChildNoteButton = $(`<span class="tree-item-button add-note-button bx bx-plus" title="${t("note_tree.create-child-note")}"></span>`).on(
"click",
cancelClickPropagation
);
$span.append($createChildNoteButton);
}
if (isHoistedNote) {
const $unhoistButton = $(`<span class="tree-item-button unhoist-button bx bx-door-open" title="${t("note_tree.unhoist")}"></span>`).on("click", cancelClickPropagation);
$span.append($unhoistButton);
}
},
// this is done to automatically lazy load all expanded notes after tree load
loadChildren: (event, data) => {
data.node.visit((subNode) => {
// Load all lazy/unloaded child nodes
// (which will trigger `loadChildren` recursively)
if (subNode.isUndefined() && subNode.isExpanded()) {
subNode.load();
}
});
},
select: (event, { node }) => {
if (hoistedNoteService.getHoistedNoteId() === "root" && node.data.noteId === "_hidden" && node.isSelected()) {
// hidden is hackily hidden from the tree via CSS when root is hoisted
// make sure it's not selected by mistake, it could be e.g. deleted by mistake otherwise
node.setSelected(false);
return;
}
$(node.span)
.find(".fancytree-custom-icon")
.attr("title", node.isSelected() ? "Apply bulk actions on selected notes" : "");
}
});
const isMobile = utils.isMobile();
if (isMobile) {
let showTimeout: Timeout;
this.$tree.on("touchstart", ".fancytree-node", (e) => {
touchStart = new Date().getTime();
showTimeout = setTimeout(() => {
this.showContextMenu(e);
}, 300);
});
this.$tree.on("touchmove", ".fancytree-node", (e) => {
clearTimeout(showTimeout);
});
this.$tree.on("touchend", ".fancytree-node", (e) => {
clearTimeout(showTimeout);
});
} else {
this.$tree.on("contextmenu", ".fancytree-node", (e) => {
this.showContextMenu(e);
return false; // blocks default browser right click menu
});
this.getHotKeys().then((hotKeys) => {
for (const key in hotKeys) {
const handler = hotKeys[key];
$(this.tree.$container).on("keydown", null, key, (evt) => {
const node = this.tree.getActiveNode();
return handler(node, evt);
// return false from the handler will stop default handling.
});
}
});
}
let touchStart;
this.tree = $.ui.fancytree.getTree(this.$tree);
}
showContextMenu(e: PointerEvent | JQuery.TouchStartEvent | JQuery.ContextMenuEvent) {
const node = $.ui.fancytree.getNode(e as unknown as Event);
const note = froca.getNoteFromCache(node.data.noteId);
if (note.isLaunchBarConfig()) {
import("../menus/launcher_context_menu.js").then(({ default: LauncherContextMenu }) => {
const launcherContextMenu = new LauncherContextMenu(this, node);
launcherContextMenu.show(e);
});
} else {
import("../menus/tree_context_menu.js").then(({ default: TreeContextMenu }) => {
const treeContextMenu = new TreeContextMenu(this, node);
treeContextMenu.show(e);
});
}
}
prepareRootNode() {
const branch = froca.getBranch("none_root");
return branch && this.prepareNode(branch);
}
prepareChildren(parentNote: FNote) {
utils.assertArguments(parentNote);
const noteList = [];
const hideArchivedNotes = this.hideArchivedNotes;
let childBranches = parentNote.getFilteredChildBranches();
if (parentNote.type === "search" && childBranches.length > MAX_SEARCH_RESULTS_IN_TREE) {
childBranches = childBranches.slice(0, MAX_SEARCH_RESULTS_IN_TREE);
}
for (const branch of childBranches) {
if (hideArchivedNotes) {
const note = branch.getNoteFromCache();
if (note.hasLabel("archived")) {
continue;
}
}
const node = this.prepareNode(branch);
if (node) {
noteList.push(node);
}
}
return noteList;
}
async updateNode(node: Fancytree.FancytreeNode) {
const note = froca.getNoteFromCache(node.data.noteId);
const branch = froca.getBranch(node.data.branchId);
if (!note) {
console.log(`Node update not possible because note '${node.data.noteId}' was not found.`);
return;
} else if (!branch) {
console.log(`Node update not possible because branch '${node.data.branchId}' was not found.`);
return;
}
const title = `${branch.prefix ? `${branch.prefix} - ` : ""}${note.title}`;
node.data.isProtected = note.isProtected;
node.data.noteType = note.type;
node.folder = note.isFolder();
node.icon = note.getIcon();
node.extraClasses = this.getExtraClasses(note);
node.title = utils.escapeHtml(title);
if (node.isExpanded() !== branch.isExpanded) {
await node.setExpanded(branch.isExpanded, { noEvents: true, noAnimation: true });
}
node.renderTitle();
}
prepareNode(branch: FBranch, forceLazy = false) {
const note = branch.getNoteFromCache();
if (!note) {
console.warn(`Branch '${branch.branchId}' has no child note '${branch.noteId}'`);
return null;
}
const title = `${branch.prefix ? `${branch.prefix} - ` : ""}${note.title}`;
const isFolder = note.isFolder();
const node: Node = {
noteId: note.noteId,
parentNoteId: branch.parentNoteId,
branchId: branch.branchId,
isProtected: note.isProtected,
noteType: note.type,
title: utils.escapeHtml(title),
extraClasses: this.getExtraClasses(note),
icon: note.getIcon(),
refKey: note.noteId,
lazy: true,
folder: isFolder,
expanded: branch.isExpanded && note.type !== "search",
key: utils.randomString(12) // this should prevent some "duplicate key" errors
};
if (isFolder && node.expanded && !forceLazy) {
node.children = this.prepareChildren(note);
}
return node;
}
getExtraClasses(note: FNote) {
utils.assertArguments(note);
const extraClasses = [];
if (note.isProtected) {
extraClasses.push("protected");
}
if (note.isShared()) {
extraClasses.push("shared");
}
if (note.getParentNoteIds().length > 1) {
const realClones = note
.getParentNoteIds()
.map((noteId: string) => froca.notes[noteId])
.filter((note: FNote) => !!note)
.filter((note: FNote) => !["_share", "_lbBookmarks"].includes(note.noteId) && note.type !== "search");
if (realClones.length > 1) {
extraClasses.push("multiple-parents");
}
}
const cssClass = note.getCssClass();
if (cssClass) {
extraClasses.push(cssClass);
}
extraClasses.push(utils.getNoteTypeClass(note.type));
if (note.mime) {
// some notes should not have mime type (e.g. render)
extraClasses.push(utils.getMimeTypeClass(note.mime));
}
if (note.hasLabel("archived")) {
extraClasses.push("archived");
}
const colorClass = note.getColorClass();
if (colorClass) {
extraClasses.push(colorClass);
}
return extraClasses.join(" ");
}
/** @returns {FancytreeNode[]} */
getSelectedNodes(stopOnParents = false) {
return this.tree.getSelectedNodes(stopOnParents);
}
getSelectedOrActiveNodes(node: Fancytree.FancytreeNode | null = null) {
const nodes = this.getSelectedNodes(true);
// the node you start dragging should be included even if not selected
if (node && !nodes.find((n) => n.key === node.key)) {
nodes.push(node);
}
if (nodes.length === 0) {
nodes.push(this.getActiveNode());
}
// hidden subtree is hackily hidden via CSS when hoisted to root
// make sure it's never selected for e.g. deletion in such a case
return nodes.filter((node) => hoistedNoteService.getHoistedNoteId() !== "root" || node.data.noteId !== "_hidden");
}
async setExpandedStatusForSubtree(node: Fancytree.FancytreeNode | null, isExpanded: boolean) {
if (!node) {
const hoistedNoteId = hoistedNoteService.getHoistedNoteId();
node = this.getNodesByNoteId(hoistedNoteId)[0];
}
const { branchIds } = await server.put<ExpandedSubtreeResponse>(`branches/${node.data.branchId}/expanded-subtree/${isExpanded ? 1 : 0}`);
froca.getBranches(branchIds, true).forEach((branch) => (branch.isExpanded = !!isExpanded));
await this.batchUpdate(async () => {
await node.load(true);
if (node.data.noteId !== hoistedNoteService.getHoistedNoteId()) {
// hoisted note should always be expanded
await node.setExpanded(isExpanded, { noEvents: true, noAnimation: true });
}
});
await this.filterHoistedBranch(true);
// don't activate the active note, see discussion in https://github.com/zadam/trilium/issues/3664
}
async expandTree(node: Fancytree.FancytreeNode | null = null) {
await this.setExpandedStatusForSubtree(node, true);
}
async collapseTree(node: Fancytree.FancytreeNode | null = null) {
await this.setExpandedStatusForSubtree(node, false);
}
collapseTreeEvent() {
this.collapseTree();
}
/**
* @returns {FancytreeNode|null}
*/
getActiveNode() {
return this.tree.getActiveNode();
}
/**
* focused & not active node can happen during multiselection where the node is selected
* but not activated (its content is not displayed in the detail)
* @returns {FancytreeNode|null}
*/
getFocusedNode() {
return this.tree.getFocusNode();
}
clearSelectedNodes() {
for (const selectedNode of this.getSelectedNodes()) {
selectedNode.setSelected(false);
}
}
async scrollToActiveNoteEvent() {
const activeContext = appContext.tabManager.getActiveContext();
if (activeContext && activeContext.notePath) {
this.tree.$container.focus();
this.tree.setFocus(true);
const node = await this.expandToNote(activeContext.notePath);
if (node) {
await node.makeVisible({ scrollIntoView: true });
node.setActive(true, { noEvents: true, noFocus: false });
}
}
}
async focusTreeEvent() {
this.tree.$container.focus();
this.tree.setFocus(true);
}
async getNodeFromPath(notePath: string, expand = false, logErrors = true) {
utils.assertArguments(notePath);
/** @let {FancytreeNode} */
let parentNode = this.getNodesByNoteId("root")[0];
let resolvedNotePathSegments = await treeService.resolveNotePathToSegments(notePath, this.hoistedNoteId, logErrors);
if (!resolvedNotePathSegments) {
if (logErrors) {
logError("Could not find run path for notePath:", notePath);
}
return;
}