oxios-web 0.2.0

Web dashboard channel for Oxios
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
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
let tree;

function renderSidebar(focusDir = '', modifiedPaths) {
    let expandedDirs = new Set();
    let selectedNodes = new Set();

    // TODO save state
    if (tree) {
        // Save state for all nodes (both directories and files)
        function saveNodeState(node) {
            if (node.isExpanded()) {
                expandedDirs.add(node.toString());
            }
            if (node.isSelected()) {
                selectedNodes.add(node.toString());
            }

            // Recursively save state for child nodes
            if (node.getChildren) {
                node.getChildren().forEach(child => {
                    saveNodeState(child);
                });
            }
        }

        tree.getRoot().getChildren().forEach(child => {
            saveNodeState(child);
        });
    }

    root = new TreeNode('');
    root.path = '/';

    let chat = new TreeNode('chat');
    chat.path = CHAT_PATH;
    if ((currentEditor.path === undefined && !isMemFS) || selectedNodes.has('chat')) {
        chat.setSelected(true);
    }
    chat.on('click', async function (n, node) {
        await openChat();
    });
    root.addChild(chat)

    // Later sits right under the chat (today) at the top of the sidebar.
    if (files[toFilename(LATER_PATH)] !== undefined) {
        let laterNode = new TreeNode('later', {expanded: false, dir: false});
        laterNode.path = LATER_PATH;
        laterNode.on('click', async function (n, node) {
            await openFile(LATER_PATH);
        });
        root.addChild(laterNode);
        if (modifiedPaths !== undefined && modifiedPaths.includes(LATER_PATH)) {
            laterNode.shouldBlink = true;
        }
    }

    let dirNodes = {'/': root};

    // First pass: create all directories
    // Once got maximum call exceeded here
    walk(files, (path, isFile) => {
        if (path === '/media' || path.startsWith('/media/')) {
            return;
        }

        if (isFile) {
            return;
        }

        let dirNode = new TreeNode(toFilename(path), {expanded: false, dir: true});
        dirNode.path = removeTrailingSlash(path);
        if (path === '/archive/') {
            dirNode.isGroupEnd = true;
        }
        dirNodes[removeTrailingSlash(path)] = dirNode;

        // Add to parent
        const parentDirPath = toDirPath(path);
        const parentNode = dirNodes[parentDirPath] || root;
        parentNode.addChild(dirNode);

        // Handle focus directory or restore previous state
        let dir = toFilename(path);
        if (dir === focusDir) {
            dirNode.setExpanded(true);
            dirNode.setSelected(true);
        } else {
            if (expandedDirs.has(dir)) dirNode.setExpanded(true);
            if (selectedNodes.has(dir)) dirNode.setSelected(true);
        }

        if (modifiedPaths !== undefined && modifiedPaths.some(modPath => toRootDirName(modPath) === dir)) {
            dirNode.shouldBlink = true;
        }
    });

    // Drop the Archive node if it has nothing the user cares about. The
    // app writes /archive/Log.txt for its own diagnostics, so "empty" here
    // means: no entries at all, or only Log.txt.
    const archiveNode = dirNodes['/archive'];
    if (archiveNode) {
        const archiveEntries = Object.keys(files['archive/'] || {});
        const archiveIsEmpty = archiveEntries.length === 0
            || (archiveEntries.length === 1 && archiveEntries[0] === 'Log.txt');
        if (archiveIsEmpty) {
            if (archiveNode.parent) archiveNode.parent.removeChild(archiveNode);
            delete dirNodes['/archive'];
        }
    }

    const groupedDirs = new Set(['journal', 'habits', 'insights', 'archive']);

    // Step 0: Lists group
    let lastListNode = null;
    walk(files, (path, isFile) => {
        if (!isFile) {
            return;
        }

        // If is not root
        if (toRootPath(path) !== '/') {
            return;
        }

        if (!isChecklist(toFilename(path))) {
            return;
        }

        // Later.md is rendered at the top under the chat, skip it here.
        if (path === LATER_PATH) {
            return;
        }

        let filename = toFilename(path);
        if (filename.endsWith('.txt')) {
            filename = trimPostfix(filename, '.txt');
        } else if (filename.endsWith('.md')) {
            filename = trimPostfix(filename, '.md');
        }

        let node = new TreeNode(filename.toLowerCase(), {expanded: false, dir: false});
        node.path = path;
        node.on('click', async function (n, node) {
            await openFile(path);
        });
        lastListNode = node;
        root.addChild(node);
        if (modifiedPaths !== undefined && modifiedPaths.includes(path)) {
            node.shouldBlink = true;
        }
    });
    if (lastListNode !== null) {
        lastListNode.isGroupEnd = true;
    }

    // Step 2: Personal group
    let lastNode = null;
    if (dirNodes['/journal']) {
        const journalNode = dirNodes['/journal'];
        if (journalNode && journalNode.parent === root) {
            root.removeChild(journalNode);
            root.addChild(journalNode);
        }
        lastNode = journalNode;
    }
    if (dirNodes['/habits']) {
        const habitsNode = dirNodes['/habits'];
        if (habitsNode && habitsNode.parent === root) {
            root.removeChild(habitsNode);
            root.addChild(habitsNode);
        }
        lastNode = habitsNode;
    }
    if (dirNodes['/insights']) {
        const insightsNode = dirNodes['/insights'];
        if (insightsNode && insightsNode.parent === root) {
            root.removeChild(insightsNode);
            root.addChild(insightsNode);
            insightsNode.isGroupEnd = true;
        }
        lastNode = insightsNode;
    }
    if (lastNode !== null) {
        lastNode.isGroupEnd = true;
    }

    // Hide if only 2 groups
    let groupEndCount = 0;
    const rootChildren = root.getChildren();
    for (const child of rootChildren) {
        if (child.isGroupEnd) {
            groupEndCount++;
        }
    }
    if (groupEndCount < 2) {
        for (const child of rootChildren) {
            child.isGroupEnd = false;
        }
    }

    // Move all other nodes down, in alphabetical order. Iterating
    // dirNodes' insertion order would render them in walk() order, which
    // is the reverse of files' insertion order - so a freshly-created
    // folder would land at one end, then jump to its sorted slot only
    // after the next loadLocalFiles re-reads OPFS.
    const dirsAlpha = Object.keys(dirNodes).sort((a, b) => a.localeCompare(b));
    for (const dir of dirsAlpha) {
        if (dir === '/' || groupedDirs.has(toFilename(dir))) continue;

        const dirNode = dirNodes[dir];
        if (dirNode && dirNode.parent === root) {
            root.removeChild(dirNode);
            root.addChild(dirNode);
        }
    }

    // Archive is always the last folder, sitting just above the top-level
    // files added by the second pass below. It's the catch-all for things
    // the user has put away, so it shouldn't push active folders down.
    const archiveLastNode = dirNodes['/archive'];
    if (archiveLastNode && archiveLastNode.parent === root) {
        root.removeChild(archiveLastNode);
        root.addChild(archiveLastNode);
    }

    // Second pass: collect, sort alphabetically, then add. walk() pops
    // its stack so files would otherwise be appended in reverse order
    // and a freshly-created file would land at one end then jump on the
    // next render.
    const fileEntries = [];
    walk(files, (path, isFile) => {
        if (path === '/media' || path.startsWith('/media/')) {
            return;
        }

        if ([CONFIG_PATH, CHAT_PATH, LATER_PATH].includes(path)) {
            return;
        }

        if (isChecklist(toFilename(path))) {
            return;
        }

        if (!isFile) {
            return;
        }

        // Sidebar only lists .md files. Images, logs and other formats
        // can sit in OPFS but cluttering the sidebar with them is noise.
        if (!toFilename(path).endsWith('.md')) {
            return;
        }

        fileEntries.push(path);
    });
    // Journal entries are filenames like "2026.05 May.md" - sort reverse so
    // newest months land at the top of the journal folder.
    fileEntries.sort((a, b) => {
        const aJournal = a.startsWith('/journal/');
        const bJournal = b.startsWith('/journal/');
        if (aJournal && bJournal) return b.localeCompare(a);
        return a.localeCompare(b);
    });

    for (const path of fileEntries) {
        const {dirPath, filename} = toDirPathAndFilename(path);

        let fileNode = new TreeNode(filename.replace(/\.md$/, '').replace(/\.txt$/, ''), {expanded: false});
        fileNode.path = path;
        fileNode.on('click', async function (n, node) {
            await openFile(path);
        });

        const parentNode = dirNodes[dirPath] || root;
        parentNode.addChild(fileNode);

        if (currentEditor.path === path) {
            fileNode.setSelected(true);
        }

        if (modifiedPaths !== undefined && modifiedPaths.includes(path)) {
            fileNode.shouldBlink = true;
        }
    }

    tree = new TreeView(root, '#tree', {
        show_root: false,
    });
}

function TreeNode(userObject, options) {
    var children = new Array();
    var self = this;
    var events = new Array();

    var expanded = true;
    var enabled = true;
    var selected = false;
    var isDir = false;

    if (userObject) {
        if (typeof userObject !== "string" && typeof userObject.toString !== "function") {
            throw new Error("Parameter 1 must be of type String or Object, where it must have the function toString()");
        }
    } else {
        userObject = "";
    }

    if (!options || typeof options !== "object") {
        options = {};
    } else {
        expanded = TreeUtil.getProperty(options, "expanded", true);
        enabled = TreeUtil.getProperty(options, "enabled", true);
        selected = TreeUtil.getProperty(options, "selected", false);
        isDir = TreeUtil.getProperty(options, "dir", false);
    }

    /*
    * Methods
    */
    this.addChild = function (node) {
        if (!TreeUtil.getProperty(options, "allowsChildren", true)) {
            console.warn("Option allowsChildren is set to false, no child added");
            return;
        }

        if (node instanceof TreeNode) {
            children.push(node);

            //Konstante hinzufügen (workaround)
            Object.defineProperty(node, "parent", {
                value: this,
                writable: false,
                enumerable: true,
                configurable: true
            });
        } else {
            throw new Error("Parameter 1 must be of type TreeNode");
        }
    }

    this.prependChild = function (node) {
        if (!TreeUtil.getProperty(options, "allowsChildren", true)) {
            console.warn("Option allowsChildren is set to false, no child added");
            return;
        }
        if (node instanceof TreeNode) {
            children.unshift(node); // Add to beginning instead of end
            // Set parent property (same as addChild)
            Object.defineProperty(node, "parent", {
                value: this,
                writable: false,
                enumerable: true,
                configurable: true
            });
        } else {
            throw new Error("Parameter 1 must be of type TreeNode");
        }
    }

    this.removeChildPos = function (pos) {
        if (typeof children[pos] !== "undefined") {
            if (typeof children[pos] !== "undefined") {
                children.splice(pos, 1);
            }
        }
    }

    this.removeChild = function (node) {
        if (!(node instanceof TreeNode)) {
            throw new Error("Parameter 1 must be of type TreeNode");
        }

        this.removeChildPos(this.getIndexOfChild(node));
    }

    this.getChildren = function () {
        return children;
    }

    this.getChildCount = function () {
        return children.length;
    }

    this.getIndexOfChild = function (node) {
        for (var i = 0; i < children.length; i++) {
            if (children[i].equals(node)) {
                return i;
            }
        }

        return -1;
    }

    this.getRoot = function () {
        var node = this;

        while (typeof node.parent !== "undefined") {
            node = node.parent;
        }

        return node;
    }

    this.setUserObject = function (_userObject) {
        if (!(typeof _userObject === "string") || typeof _userObject.toString !== "function") {
            throw new Error("Parameter 1 must be of type String or Object, where it must have the function toString()");
        } else {
            userObject = _userObject;
        }
    }

    this.getUserObject = function () {
        return userObject;
    }

    this.setOptions = function (_options) {
        if (typeof _options === "object") {
            options = _options;
        }
    }

    this.changeOption = function (option, value) {
        options[option] = value;
    }

    this.getOptions = function () {
        return options;
    }

    this.isLeaf = function () {
        // PATCHED
        return !isDir;
        // return (children.length == 0);
    }

    this.setExpanded = function (_expanded) {
        if (this.isLeaf()) {
            return;
        }

        if (typeof _expanded === "boolean") {
            if (expanded == _expanded) {
                return;
            }

            expanded = _expanded;

            if (_expanded) {
                this.on("expand")(this);
            } else {
                this.on("collapse")(this);
            }

            this.on("toggle_expanded")(this);
        }
    }

    this.toggleExpanded = function () {
        if (expanded) {
            this.setExpanded(false);
        } else {
            this.setExpanded(true);
        }
    };

    this.isExpanded = function () {
        if (this.isLeaf()) {
            return true;
        } else {
            return expanded;
        }
    }

    this.setEnabled = function (_enabled) {
        if (typeof _enabled === "boolean") {
            if (enabled == _enabled) {
                return;
            }

            enabled = _enabled;

            if (_enabled) {
                this.on("enable")(this);
            } else {
                this.on("disable")(this);
            }

            this.on("toggle_enabled")(this);
        }
    }

    this.toggleEnabled = function () {
        if (enabled) {
            this.setEnabled(false);
        } else {
            this.setEnabled(true);
        }
    }

    this.isEnabled = function () {
        return enabled;
    }

    this.setSelected = function (_selected) {
        if (typeof _selected !== "boolean") {
            return;
        }

        if (selected == _selected) {
            return;
        }

        selected = _selected;

        if (_selected) {
            this.on("select")(this);
        } else {
            this.on("deselect")(this);
        }

        this.on("toggle_selected")(this);
    }

    this.toggleSelected = function () {
        if (selected) {
            this.setSelected(false);
        } else {
            this.setSelected(true);
        }
    }

    this.isSelected = function () {
        return selected;
    }

    this.open = function () {
        if (!this.isLeaf()) {
            this.on("open")(this);
        }
    }

    this.on = function (ev, callback) {
        if (typeof callback === "undefined") {
            if (typeof events[ev] !== "function") {
                return function () {
                };
            } else {
                return events[ev];
            }
        }

        if (typeof callback !== 'function') {
            throw new Error("Argument 2 must be of type function");
        }

        events[ev] = callback;
    }

    this.getListener = function (ev) {
        return events[ev];
    }

    this.equals = function (node) {
        if (node instanceof TreeNode) {
            if (node.getUserObject() == userObject) {
                return true;
            }
        }

        return false;
    }

    this.toString = function () {
        if (typeof userObject === "string") {
            return userObject;
        } else {
            return userObject.toString();
        }
    }
}

function TreePath(root, node) {
    var nodes = new Array();

    this.setPath = function (root, node) {
        nodes = new Array();

        while (typeof node !== "undefined" && !node.equals(root)) {
            nodes.push(node);
            node = node.parent;
        }

        if (node.equals(root)) {
            nodes.push(root);
        } else {
            nodes = new Array();
            throw new Error("Node is not contained in the tree of root");
        }

        nodes = nodes.reverse();

        return nodes;
    }

    this.getPath = function () {
        return nodes;
    }

    this.toString = function () {
        return nodes.join(" - ");
    }

    if (root instanceof TreeNode && node instanceof TreeNode) {
        this.setPath(root, node);
    }
}

function TreeView(root, container, options) {
    var self = this;
    var draggedNode = null;
    var draggedElement = null;
    var dropIndicator = null;

    if (typeof root === "undefined") {
        throw new Error("Parameter 1 must be set (root)");
    }

    if (!(root instanceof TreeNode)) {
        throw new Error("Parameter 1 must be of type TreeNode");
    }

    if (container) {
        if (!TreeUtil.isDOM(container)) {
            container = document.querySelector(container);

            if (container instanceof Array) {
                container = container[0];
            }

            if (!TreeUtil.isDOM(container)) {
                throw new Error("Parameter 2 must be either DOM-Object or CSS-QuerySelector (#, .)");
            }
        }
    } else {
        container = null;
    }

    if (!options || typeof options !== "object") {
        options = {};
    }


    function createDropIndicator() {
        const indicator = document.createElement('div');
        indicator.className = 'tree-drop_indicator';
        return indicator;
    }

    function findNodeElement(element) {
        while (element && !element.tree_node) {
            element = element.parentElement;
        }
        return element;
    }

    function getDropPosition(e, element) {
        const rect = element.getBoundingClientRect();
        const y = e.clientY - rect.top;
        const height = rect.height;

        if (y < height * 0.25) return 'before';
        if (y > height * 0.75) return 'after';
        return 'inside';
    }

    this.setRoot = function (_root) {
        if (root instanceof TreeNode) {
            root = _root;
        }
    }

    this.getRoot = function () {
        return root;
    }

    this.expandAllNodes = function () {
        root.setExpanded(true);
        root.getChildren().forEach(function (child) {
            TreeUtil.expandNode(child);
        });
    }

    this.expandPath = function (path) {
        if (!(path instanceof TreePath)) {
            throw new Error("Parameter 1 must be of type TreePath");
        }
        path.getPath().forEach(function (node) {
            node.setExpanded(true);
        });
    }

    this.collapseAllNodes = function () {
        root.setExpanded(false);
        root.getChildren().forEach(function (child) {
            TreeUtil.collapseNode(child);
        });
    }

    this.setContainer = function (_container) {
        if (TreeUtil.isDOM(_container)) {
            container = _container;
        } else {
            _container = document.querySelector(_container);
            if (_container instanceof Array) {
                _container = _container[0];
            }
            if (!TreeUtil.isDOM(_container)) {
                throw new Error("Parameter 1 must be either DOM-Object or CSS-QuerySelector (#, .)");
            }
        }
    }

    this.getContainer = function () {
        return container;
    }

    this.setOptions = function (_options) {
        if (typeof _options === "object") {
            options = _options;
        }
    }

    this.changeOption = function (option, value) {
        options[option] = value;
    }

    this.getOptions = function () {
        return options;
    }

    this.getSelectedNodes = function () {
        return TreeUtil.getSelectedNodesForNode(root);
    }

    this.reload = function () {
        if (container == null) {
            console.warn("No container specified");
            return;
        }

        container.classList.add("tree-container");
        var cnt = document.createElement("ul");

        if (TreeUtil.getProperty(options, "show_root", true)) {
            cnt.appendChild(renderNode(root));
        } else {
            root.getChildren().forEach(function (child) {
                cnt.appendChild(renderNode(child));
            });
        }

        container.innerHTML = "";
        container.appendChild(cnt);
        setupContainerDropZone();
    }

    function setupContainerDropZone() {
        container.addEventListener('dragover', function (e) {
            e.preventDefault();
            if (dropIndicator && !e.target.closest('.tree-item')) {
                dropIndicator.remove();
                dropIndicator = null;
            }
            e.dataTransfer.dropEffect = 'move';
        });

        container.addEventListener('drop', function (e) {
            e.preventDefault();
            if (dropIndicator) {
                dropIndicator.remove();
                dropIndicator = null;
            }

            if (e.dataTransfer.files.length > 0) {
                handleExternalFileDrop(e);
            }
        });
    }

    function handleExternalFileDrop(e) {
        const files = Array.from(e.dataTransfer.files);
        files.forEach(file => {
            if (file.type === 'text/plain' || file.name.endsWith('.md')) {
                const reader = new FileReader();
                reader.onload = function (event) {
                    const content = event.target.result;
                    const fileName = file.name.replace(/\.[^/.]+$/, "");

                    if (typeof window.handleDroppedFile === 'function') {
                        window.handleDroppedFile(fileName, content);
                    } else {
                        log('Dropped file:', fileName, content);
                    }
                };
                reader.readAsText(file);
            }
        });
    }

    function createGroupHeader(headerText, headerClass) {
        var li_header = document.createElement("li");
        li_header.className = "tree-group_header " + headerClass;
        li_header.innerHTML = '<span class="tree-group_title">' + headerText + '</span>';
        return li_header;
    }

    function shouldShowGroupHeaders() {
        return false;
    }

    function renderNode(node) {
        var li_outer = document.createElement("li");
        var span_desc = document.createElement("span");
        span_desc.className = "tree-item";
        span_desc.tree_node = node;

        var needsGroupHeader = false;
        var groupHeaderText = "";
        var groupHeaderClass = "";

        if (node.parent === root) {
            let siblings = root.getChildren();
            let myIndex = siblings.indexOf(node);

            // ?? =)
            if (myIndex === 0) {
                needsGroupHeader = true;
            } else if (myIndex > 0 && siblings[myIndex - 1].isGroupEnd) {
                needsGroupHeader = true;
            }

            if (needsGroupHeader) {
                let nodeStr = node.toString();
                if (nodeStr.endsWith('_') || nodeStr === 'read' || nodeStr === 'watch' || nodeStr === 'shop') {
                    groupHeaderText = "LISTS";
                    groupHeaderClass = "lists";
                } else if (['today', 'later'].includes(nodeStr)) {
                    groupHeaderText = "TASKS";
                    groupHeaderClass = "tasks";
                } else if (['journal', 'habits', 'insights'].includes(nodeStr)) {
                    groupHeaderText = "PERSONAL";
                    groupHeaderClass = "personal";
                } else if (nodeStr === 'chat') {
                    // groupHeaderText = "Personal";
                    groupHeaderClass = "personal";
                } else {
                    groupHeaderText = "FILES";
                    groupHeaderClass = "user-dirs";
                }
            }
        }

        // If we need a group header, we'll return a document fragment with both header and node
        if (needsGroupHeader && shouldShowGroupHeaders()) {
            var fragment = document.createDocumentFragment();
            fragment.appendChild(createGroupHeader(groupHeaderText, groupHeaderClass));
        }

        if (node.shouldBlink) {
            span_desc.classList.add('sidebar-blink');
            setTimeout(() => span_desc.classList.remove('sidebar-blink'), 4000);
            node.shouldBlink = false;
        }

        if (node.isGroupEnd) {
            span_desc.classList.add("group-end");
        }

        // Both files and folders are draggable. Only the synthetic system
        // entries (chat, later, the global lists) stay pinned in place.
        if (!['later', 'watch', 'shop', 'read', 'chat'].includes(node.toString())) {
            span_desc.draggable = true;
        }

        if (!node.isEnabled()) {
            li_outer.setAttribute("disabled", "");
            node.setExpanded(false);
            node.setSelected(false);
        }

        if (node.isSelected()) {
            span_desc.classList.add("selected");
        }

        // TODO dirty hack, for some reason expanded is set for leaf nodes
        if (node.isExpanded() &&
            node.toString() !== 'today' && node.toString() !== 'later' &&
            node.toString() !== 'watch' && node.toString() !== 'shop' && node.toString() !== 'read') {
            span_desc.classList.add("expanded");
        }

        span_desc.addEventListener("dragstart", function (e) {
            draggedNode = node;
            draggedElement = span_desc;
            span_desc.classList.add("tree-dragging");

            e.dataTransfer.effectAllowed = 'move';
            e.dataTransfer.setData('text/plain', node.toString());
            e.dataTransfer.setDragImage(span_desc, -10, span_desc.offsetHeight / 2);
        });

        span_desc.addEventListener("dragend", function (e) {
            span_desc.classList.remove("tree-dragging");
            if (dropIndicator) {
                dropIndicator.remove();
                dropIndicator = null;
            }
            draggedNode = null;
            draggedElement = null;
        });

        span_desc.addEventListener("dragover", function (e) {
            e.preventDefault();
            if (!draggedNode || draggedNode === node) return;

            const position = getDropPosition(e, span_desc);

            if (dropIndicator) dropIndicator.remove();
            dropIndicator = createDropIndicator();

            if (position === 'before') {
                const rect = li_outer.getBoundingClientRect();
                dropIndicator.style.top = rect.top + 'px';
                dropIndicator.style.left = rect.left + 'px';
                dropIndicator.style.width = rect.width + 'px';
                document.body.appendChild(dropIndicator);
            } else if (position === 'after') {
                const rect = li_outer.getBoundingClientRect();
                dropIndicator.style.top = rect.bottom + 'px';
                dropIndicator.style.left = rect.left + 'px';
                dropIndicator.style.width = rect.width + 'px';
                document.body.appendChild(dropIndicator);
            } else if (position === 'inside' && !node.isLeaf()) {
                span_desc.classList.add("tree-drop_target");
                return;
            }

            dropIndicator.classList.add("active");
        });

        span_desc.addEventListener("dragleave", function (e) {
            span_desc.classList.remove("tree-drop_target");
        });

        span_desc.addEventListener("drop", function (e) {
            e.preventDefault();
            e.stopPropagation();

            span_desc.classList.remove("tree-drop_target");

            if (!draggedNode || draggedNode === node) return;

            const position = getDropPosition(e, span_desc);

            if (typeof window.handleNodeMove === 'function') {
                // Use the absolute path from the dragged node (set during
                // tree construction). For folders this is /life, for files
                // /life/Pilaf.md - same handler covers both.
                const sourcePath = draggedNode.path;
                let targetDir;
                if (position === 'inside' && !node.isLeaf()) {
                    targetDir = node.path;
                } else {
                    targetDir = node.parent && node.parent.path ? node.parent.path : '/';
                }

                window.handleNodeMove(sourcePath, targetDir);
            }

            if (dropIndicator) {
                dropIndicator.remove();
                dropIndicator = null;
            }
        });

        span_desc.addEventListener("click", function (e) {
            var cur_el = e.target;

            while (typeof cur_el.tree_node === "undefined" || cur_el.classList.contains("tree-container")) {
                cur_el = cur_el.parentElement;
            }

            var node_cur = cur_el.tree_node;

            if (typeof node_cur === "undefined") {
                return;
            }

            if (node_cur.isEnabled()) {
                if (e.ctrlKey == false) {
                    if (!node_cur.isLeaf()) {
                        node_cur.toggleExpanded();
                        self.reload();
                    } else {
                        node_cur.open();
                    }

                    node_cur.on("click")(e, node_cur);
                }

                if (e.ctrlKey == true) {
                    node_cur.toggleSelected();
                    self.reload();
                } else {
                    var rt = node_cur.getRoot();

                    if (rt instanceof TreeNode) {
                        TreeUtil.getSelectedNodesForNode(rt).forEach(function (_nd) {
                            _nd.setSelected(false);
                        });
                    }
                    node_cur.setSelected(true);

                    self.reload();
                }
            }
        });

        span_desc.addEventListener("contextmenu", function (e) {
            var cur_el = e.target;

            while (typeof cur_el.tree_node === "undefined" || cur_el.classList.contains("tree-container")) {
                cur_el = cur_el.parentElement;
            }

            var node_cur = cur_el.tree_node;

            if (typeof node_cur === "undefined") {
                return;
            }

            if (typeof node_cur.getListener("contextmenu") !== "undefined") {
                node_cur.on("contextmenu")(e, node_cur);
                e.preventDefault();
            } else if (typeof TreeConfig.context_menu === "function") {
                TreeConfig.context_menu(e, node_cur);
                e.preventDefault();
            }
        });

        if (node.isLeaf() && !TreeUtil.getProperty(node.getOptions(), "forceParent", false)) {
            var ret = '';
            var icon = TreeUtil.getProperty(node.getOptions(), "icon", "");

            let name = node.toString();
            if (startsWithEmoji(name)) {
                ret += '<span class="tree-mod_icon" ><div style="width: 22px; text-align: center; transform: translateY(-2px);">' + getFirstEmoji(node.toString()) + '</div></span>';
                name = trimFirstEmoji(name);
            } else if (node.toString() === 'chat') {
                ret += '<span class="tree-mod_icon" style="padding-right: 2px">' + TreeConfig.chat_icon + '</span>';
                name = 'chat';
            } else if (icon != "") {
                ret += '<span class="tree-mod_icon">' + icon + '</span>';
            } else if ((icon = TreeUtil.getProperty(options, "leaf_icon", "")) != "") {
                ret += '<span class="tree-icon">' + icon + '</span>';
            } else if (node.toString() === 'today') {
                ret += '<span class="tree-mod_icon">' + TreeConfig.later_icon + '</span>';
            } else if (node.toString() === 'later') {
                ret += '<span class="tree-mod_icon">' + TreeConfig.later_icon + '</span>';
            } else if (node.toString().endsWith('_') || node.toString() === 'read' || node.toString() === 'watch' || node.toString() === 'shop') {
                ret += '<span class="tree-mod_icon">' + TreeConfig.checklists_icon + '</span>';
            } else {
                ret += '<span class="tree-icon">' + TreeConfig.leaf_icon + '</span>';
            }

            span_desc.innerHTML = ret + name + "</span>";
            span_desc.classList.add("tree-leaf");
            if (node.toString() === 'chat') {
                span_desc.classList.add("sidebar-chat");
            }

            li_outer.appendChild(span_desc);
        } else {
            var ret = '';
            if (node.toString() === 'journal') {
                const heart = node.isExpanded() ? TreeConfig.journal_icon_filled : TreeConfig.journal_icon;
                ret += '<span class="tree-mod_icon">' + heart + '</span>';
            } else if (node.isExpanded()) {
                ret += '<span class="tree-mod_icon">' + TreeConfig.open_icon + '</span>';
            } else {
                if (node.toString().startsWith('_') && node.toString().endsWith('_')) {
                    ret += '<span class="tree-mod_icon">' + TreeConfig.checklists_icon + '</span>';
                } else if (node.toString() === 'today' || node.toString() === 'later') {
                    ret += '<span class="tree-mod_icon">' + TreeConfig.later_icon + '</span>';
                } else {
                    ret += '<span class="tree-mod_icon">' + TreeConfig.close_icon + '</span>';
                }
            }

            var icon = TreeUtil.getProperty(node.getOptions(), "icon", "");
            icon = '';
            if (icon != "") {
                ret += '<span class="tree-icon">' + icon + '</span>';
            } else if ((icon = TreeUtil.getProperty(options, "parent_icon", "")) != "") {
                ret += '<span class="tree-icon">' + icon + '</span>';
            } else {
                ret += '<span class="tree-icon">' + TreeConfig.parent_icon + '</span>';
            }

            span_desc.innerHTML = ret + node.toString() + '</span>';

            li_outer.appendChild(span_desc);

            if (node.isExpanded()) {
                var ul_container = document.createElement("ul");

                node.getChildren().forEach(function (child) {
                    ul_container.appendChild(renderNode(child));
                });

                li_outer.appendChild(ul_container)
            }
        }


        if (needsGroupHeader && shouldShowGroupHeaders()) {
            fragment.appendChild(li_outer);
            return fragment;
        }

        return li_outer;
    }

    if (typeof container !== "undefined")
        this.reload();
}

/*
* Util-Methods
*/

const TreeUtil = {
    default_leaf_icon: "<span>&#128441;</span>",
    default_parent_icon: "<span>&#128449;</span>",
    default_open_icon: "<svg width=\"22px\" height=\"22px\" viewBox=\"0 0 32 32\" xmlns=\"http://www.w3.org/2000/svg\" fill=\"none\"> <path stroke-linecap=\"round\" stroke-width=\"2\" d=\"M4 26V8a2 2 0 012-2h6c3 0 3 3 5 3h7a2 2 0 012 2v2M4 26l3.783-12.294A1 1 0 018.739 13H26M4 26h19.523a2 2 0 001.911-1.412l3.168-10.294A1 1 0 0027.646 13H26\"/> </svg>",
    default_close_icon: "<svg width=\"22px\" height=\"22px\" viewBox=\"0 0 32 32\" xmlns=\"http://www.w3.org/2000/svg\" fill=\"none\"> <path stroke-linecap=\"round\" stroke-width=\"2\" d=\"M28 11v13a2 2 0 01-2 2H6a2 2 0 01-2-2V8a2 2 0 012-2h6c3 0 3 3 5 3h9.003C27.108 9 28 9.895 28 11z\"/> </svg>",
    later_icon: "<svg xmlns=\"http://www.w3.org/2000/svg\" width=\"22\" height=\"22\" fill=\"none\" viewBox=\"0 0 32 32\"><circle cx=\"16\" cy=\"16\" r=\"13\"  stroke-width=\"2\"/> <path stroke-linecap=\"round\" stroke-linejoin=\"round\" stroke-width=\"2\" d=\"M16 8v8l4 4\"/></svg>\n",
    checklists_icon: "\n" +
        "<svg xmlns=\"http://www.w3.org/2000/svg\" width=\"22\" height=\"22\" fill=\"none\" viewBox=\"0 0 32 32\"><path stroke-linecap=\"round\" stroke-linejoin=\"round\" stroke-width=\"2\" d=\"M29 16a13 13 0 11-26 0 13 13 0 0126 0h0z\"/><path stroke-linecap=\"round\" stroke-linejoin=\"round\" stroke-width=\"2\" d=\"M11.5 16l3.5 3.5 6-6\"/></svg>\n",
    chat_icon: "<svg xmlns=\"http://www.w3.org/2000/svg\" style=\"transform: translateX(-3px);\" width=\"25px\" height=\"25px\" fill=\"none\" viewBox=\"0 0 30 30\"> <path stroke-linecap=\"round\" stroke-linejoin=\"round\" stroke-width=\"2\" d=\"M 25 7 H 11 a 4 4 0 0 0 -4 4 v 10 a 4 4 0 0 0 4 4 h 7 l 6 4 v -4 h 1 a 4 4 0 0 0 4 -4 V 11 a 4 4 0 0 0 -4 -4 z\"/> </svg>",
    journal_icon: "<svg width=\"22px\" height=\"22px\" viewBox=\"0 0 24 24\" fill=\"none\" xmlns=\"http://www.w3.org/2000/svg\"><path fill-rule=\"evenodd\" clip-rule=\"evenodd\" d=\"M12 6.00019C10.2006 3.90317 7.19377 3.2551 4.93923 5.17534C2.68468 7.09558 2.36727 10.3061 4.13778 12.5772C5.60984 14.4654 10.0648 18.4479 11.5249 19.7369C11.6882 19.8811 11.7699 19.9532 11.8652 19.9815C11.9483 20.0062 12.0393 20.0062 12.1225 19.9815C12.2178 19.9532 12.2994 19.8811 12.4628 19.7369C13.9229 18.4479 18.3778 14.4654 19.8499 12.5772C21.6204 10.3061 21.3417 7.07538 19.0484 5.17534C16.7551 3.2753 13.7994 3.90317 12 6.00019Z\" stroke-width=\"1.7\" stroke-linecap=\"round\" stroke-linejoin=\"round\"/></svg>",
    journal_open_icon: "<svg width=\"22px\" height=\"22px\" viewBox=\"0 0 24 24\" fill=\"currentColor\" xmlns=\"http://www.w3.org/2000/svg\"><path fill-rule=\"evenodd\" clip-rule=\"evenodd\" d=\"M12 6.00019C10.2006 3.90317 7.19377 3.2551 4.93923 5.17534C2.68468 7.09558 2.36727 10.3061 4.13778 12.5772C5.60984 14.4654 10.0648 18.4479 11.5249 19.7369C11.6882 19.8811 11.7699 19.9532 11.8652 19.9815C11.9483 20.0062 12.0393 20.0062 12.1225 19.9815C12.2178 19.9532 12.2994 19.8811 12.4628 19.7369C13.9229 18.4479 18.3778 14.4654 19.8499 12.5772C21.6204 10.3061 21.3417 7.07538 19.0484 5.17534C16.7551 3.2753 13.7994 3.90317 12 6.00019Z\" stroke=\"currentColor\" stroke-width=\"1.7\" stroke-linecap=\"round\" stroke-linejoin=\"round\"/></svg>",

    isDOM: function (obj) {
        try {
            return obj instanceof HTMLElement;
        } catch (e) {
            return (typeof obj === "object") &&
                (obj.nodeType === 1) && (typeof obj.style === "object") &&
                (typeof obj.ownerDocument === "object");
        }
    },

    getProperty: function (options, opt, def) {
        if (typeof options[opt] === "undefined") {
            return def;
        }

        return options[opt];
    },

    expandNode: function (node) {
        node.setExpanded(true);

        if (!node.isLeaf()) {
            node.getChildren().forEach(function (child) {
                TreeUtil.expandNode(child);
            });
        }
    },

    collapseNode: function (node) {
        node.setExpanded(false);

        if (!node.isLeaf()) {
            node.getChildren().forEach(function (child) {
                TreeUtil.collapseNode(child);
            });
        }
    },

    getSelectedNodesForNode: function (node) {
        if (!(node instanceof TreeNode)) {
            throw new Error("Parameter 1 must be of type TreeNode");
        }

        var ret = new Array();

        if (node.isSelected()) {
            ret.push(node);
        }

        node.getChildren().forEach(function (child) {
            if (child.isSelected()) {
                if (ret.indexOf(child) == -1) {
                    ret.push(child);
                }
            }

            if (!child.isLeaf()) {
                TreeUtil.getSelectedNodesForNode(child).forEach(function (_node) {
                    if (ret.indexOf(_node) == -1) {
                        ret.push(_node);
                    }
                });
            }
        });

        return ret;
    }
};

function isChecklist(filename) {
    if ([
        toFilename(WATCH_PATH),
        toFilename(SHOP_PATH),
        toFilename(READ_PATH)
    ].includes(filename)) {
        return true;
    }

    return filename.endsWith('_.txt') || filename.endsWith('_.md');
}

window.handleNodeMove = async function (sourcePath, targetDir) {
    log(`Moving ${sourcePath} to ${targetDir}/`);

    const memFile = getMemFile(sourcePath);
    const isFolder = memFile === null || memFile.isFile !== true;

    const parts = sourcePath.split('/').filter(Boolean);
    const name = parts.pop();
    const newPath = (targetDir === '/' ? '' : targetDir) + '/' + name;
    if (newPath === sourcePath) return;

    if (isFolder) {
        try {
            await moveDir(sourcePath, newPath);
        } catch (err) {
            logError('handleNodeMove: moveDir failed', err);
        }
        await renderSidebar();
        return;
    }

    if (currentEditor.path === sourcePath) {
        await moveCurrentFile(targetDir);
    } else {
        await moveFile(sourcePath, newPath);
    }
};

// WHEN?
window.handleDroppedFile = async function (fileName, content) {
    log(`Creating new file: ${fileName}`, content);

    if (typeof createFileFromContent === 'function') {
        await createFileFromContent(fileName + '.md', content);
    }

    if (typeof renderSidebar === 'function') {
        renderSidebar();
    }
};

var TreeConfig = {
    leaf_icon: TreeUtil.default_leaf_icon,
    parent_icon: TreeUtil.default_parent_icon,
    open_icon: TreeUtil.default_open_icon,
    close_icon: TreeUtil.default_close_icon,
    later_icon: TreeUtil.later_icon,
    chat_icon: TreeUtil.chat_icon,
    checklists_icon: TreeUtil.checklists_icon,
    journal_icon: TreeUtil.journal_icon,
    journal_icon_filled: TreeUtil.journal_open_icon,
    context_menu: function (e, node) {
        return folderContextMenu(e, node);
    }
};

// openContextMenu renders a small floating menu at (e.clientX, e.clientY) and
// calls build(addItem) where addItem(label, onClick) appends a row. The menu
// closes on outside click or Esc. If the menu would overflow the bottom of
// the viewport, it flips up so its bottom edge sits at the cursor instead.
function openContextMenu(e, build, onClose) {
    const menu = document.createElement('div');
    menu.className = 'sidebar-ctx-menu';
    menu.style.left = e.clientX + 'px';
    menu.style.top = e.clientY + 'px';

    function addItem(label, onClick) {
        const el = document.createElement('div');
        el.className = 'sidebar-ctx-menu-item';
        el.textContent = label;
        el.addEventListener('click', async (ev) => {
            ev.stopPropagation();
            close();
            await onClick();
        });
        menu.appendChild(el);
    }

    function close() {
        menu.remove();
        document.removeEventListener('mousedown', onOutside, true);
        document.removeEventListener('keydown', onEsc, true);
        if (typeof onClose === 'function') onClose();
    }

    function onOutside(ev) {
        if (!menu.contains(ev.target)) close();
    }

    function onEsc(ev) {
        if (ev.key === 'Escape') close();
    }

    build(addItem);

    document.body.appendChild(menu);

    // Flip upward if the menu would clip past the viewport bottom. Measure
    // after append so offsetHeight reflects the rendered rows.
    const overflowY = e.clientY + menu.offsetHeight - window.innerHeight;
    if (overflowY > 0) {
        const top = Math.max(0, e.clientY - menu.offsetHeight);
        menu.style.top = top + 'px';
    }

    setTimeout(() => {
        document.addEventListener('mousedown', onOutside, true);
        document.addEventListener('keydown', onEsc, true);
    });
}

// folderContextMenu handles right-click on sidebar nodes. Renders a small
// context menu: Rename/Delete for directories, Move/Delete/Rename/New dir for
// files. Prompts are native so this works on touch via long-press, too.
async function folderContextMenu(e, node) {
    const isDir = node && node.getOptions && node.getOptions().dir === true;
    const path = node && node.path;
    if (!path || path === '/') return;

    const isFile = !isDir && !path.endsWith('/') && path !== CHAT_PATH;
    if (!isDir && !isFile) return;

    // Visually mark the targeted node as selected while the menu is open, so
    // scrolling the menu or moving the mouse doesn't make it unclear which
    // node the action applies to.
    const span = e.target.closest('.tree-item');
    if (span) span.classList.add('selected');

    openContextMenu(e, (item) => {
        if (isDir) {
            buildFolderMenu(item, path);
        } else {
            buildFileMenu(item, path);
        }
    }, () => {
        if (span) span.classList.remove('selected');
    });
}

// addNewFileItem/addNewDirItem add the "New file"/"New dir" rows that create
// under parentDir. parentDir is '/' for root or '/some/dir' for a sub-path.
function addNewFileItem(item, parentDir) {
    item('New file', async () => {
        try {
            await newFile(parentDir);
        } catch (err) {
            logError('new file failed', err);
            alert('Create file failed: ' + (err && err.message ? err.message : err));
        }
    });
}

function addNewDirItem(item, parentDir) {
    item('New dir', async () => {
        const name = prompt('New directory name:');
        if (name === null) return;
        const trimmed = name.trim().replace(/^\/+|\/+$/g, '');
        if (!trimmed) return;
        if (trimmed.includes('/')) {
            alert('Folder name cannot contain "/"');
            return;
        }
        const newDirPath = (parentDir === '/' ? '' : parentDir) + '/' + trimmed;
        try {
            await createDir(newDirPath);
            await renderSidebar();
        } catch (err) {
            logError('new dir failed', err);
            alert('Create dir failed: ' + (err && err.message ? err.message : err));
        }
    });
}

// rootContextMenu handles right-click on empty sidebar area — offers creating
// a new file or directory at the root.
function rootContextMenu(e) {
    if (e.defaultPrevented) return;
    e.preventDefault();
    openContextMenu(e, (item) => {
        addNewFileItem(item, '/');
        addNewDirItem(item, '/');
    });
}

document.addEventListener('DOMContentLoaded', () => {
    const sb = document.getElementById('sidebar');
    if (sb) sb.addEventListener('contextmenu', rootContextMenu);
});

function buildFolderMenu(item, dirPath) {
    const dirName = dirPath.split('/').filter(Boolean).pop();
    const pathIsInsideDir = (p) => p && (p === dirPath || p.startsWith(dirPath + '/'));

    addNewFileItem(item, dirPath);
    addNewDirItem(item, dirPath);

    item('Rename', async () => {
        let attempt = dirName;
        let trimmed;
        while (true) {
            const newName = prompt('Rename folder:', attempt);
            if (newName === null) return;
            trimmed = newName.trim();
            if (!trimmed || trimmed === dirName) return;
            const badDirChar = findForbiddenChar(trimmed);
            if (badDirChar === null) break;
            alert(`Folder name cannot contain "${badDirChar}"`);
            attempt = trimmed;
        }
        try {
            const editorWasInside = pathIsInsideDir(currentEditor.path);
            const oldEditorPath = currentEditor.path;
            await renameDir(dirPath, trimmed);
            if (editorWasInside) {
                const parentParts = dirPath.split('/').filter(Boolean).slice(0, -1);
                const newDirPath = '/' + parentParts.concat(trimmed).join('/');
                currentEditor.path = newDirPath + oldEditorPath.slice(dirPath.length);
            }
            await renderSidebar();
        } catch (err) {
            logError('renameDir failed', err);
            alert('Rename failed: ' + (err && err.message ? err.message : err));
        }
    });

    item('Delete', async () => {
        if (!confirm(`Delete folder "${dirName}" and everything inside it?`)) return;
        try {
            const editorWasInside = pathIsInsideDir(currentEditor.path);
            await removeDir(dirPath);
            if (editorWasInside) {
                currentEditor.path = undefined;
            }
            await renderSidebar();
            if (editorWasInside && typeof openRandomFile === 'function') {
                openRandomFile();
            }
        } catch (err) {
            logError('removeDir failed', err);
            alert('Delete failed: ' + (err && err.message ? err.message : err));
        }
    });
}

function isSystemChecklist(path) {
    return /^\/?(Read|Watch|Shop|Later)\.md$/i.test(path);
}

function buildFileMenu(item, filePath) {
    const fileName = filePath.split('/').filter(Boolean).pop();
    const parentDir = filePath.substring(0, filePath.length - fileName.length - 1) || '/';
    const isCurrent = currentEditor.path === filePath;

    addNewFileItem(item, parentDir);
    addNewDirItem(item, parentDir);

    if (!isSystemChecklist(filePath)) {
        item('Rename', async () => {
            const displayName = fileName.endsWith('.md') ? fileName.slice(0, -3) : fileName;
            let attempt = displayName;
            let trimmed;
            while (true) {
                const newName = prompt('Rename file:', attempt);
                if (newName === null) return;
                trimmed = newName.trim();
                if (!trimmed) return;
                const badFileChar = findForbiddenChar(trimmed);
                if (badFileChar === null) break;
                alert(`File name cannot contain "${badFileChar}"`);
                attempt = trimmed;
            }
            const finalName = fileName.endsWith('.md') && !trimmed.endsWith('.md') ? trimmed + '.md' : trimmed;
            if (finalName === fileName) return;
            const newPath = (parentDir === '/' ? '' : parentDir) + '/' + finalName;
            try {
                await moveFile(filePath, newPath);
                if (isCurrent) {
                    currentEditor.path = newPath;
                    // Editor still shows the old `# OldName` heading. The
                    // rename-from-header watcher in syncCurrentText will see
                    // the heading disagree with the new path and rename the
                    // file back, so rewrite line 0 to the new header.
                    const newHeader = toHeader(toFilename(newPath));
                    const firstLine = currentEditor.getLine(0) || '';
                    if (firstLine !== newHeader) {
                        currentEditor.replaceRange(
                            newHeader,
                            {line: 0, ch: 0},
                            {line: 0, ch: firstLine.length}
                        );
                    }
                }
                await renderSidebar();
            } catch (err) {
                logError('rename failed', err);
                alert('Rename failed: ' + (err && err.message ? err.message : err));
            }
        });
    }

    if (!isSystemChecklist(filePath)) {
        item('Move', async () => {
            try {
                if (!isCurrent) await openFile(filePath);
                document.getElementById('move-input').value = '';
                moveModal.open();
            } catch (err) {
                logError('move failed', err);
                alert('Move failed: ' + (err && err.message ? err.message : err));
            }
        });
    }

    item('Delete', async () => {
        if (!confirm(`Delete file "${fileName}"?`)) return;
        try {
            if (isCurrent && typeof removeCurrentFile === 'function') {
                await removeCurrentFile();
            } else {
                await remove(filePath);
                await renderSidebar();
            }
        } catch (err) {
            logError('delete failed', err);
            alert('Delete failed: ' + (err && err.message ? err.message : err));
        }
    });
}