kimun-notes 0.24.2

A terminal-based notes application
Documentation
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
use std::sync::Arc;

use crate::settings::themes::Theme;
use async_trait::async_trait;
use chrono::NaiveDate;
use futures::StreamExt;
use kimun_core::nfs::VaultPath;
use kimun_core::{NoteVault, NotesValidation, ResultType, VaultBrowseOptionsBuilder};
use ratatui::Frame;
use ratatui::layout::{Constraint, Direction, Layout, Position, Rect};
use ratatui::style::Style;
use ratatui::text::{Line, Span};
use ratatui::widgets::{Block, Borders, Paragraph};

use crate::components::Component;
use crate::components::event_state::EventState;
use crate::components::events::{AppEvent, AppTx, AppTxExt, FileOp, InputEvent, redraw_callback};
use crate::components::file_list::{FileListEntry, SortField, SortOrder};
use crate::components::search_list::{
    Emit, Filter, KeyReaction, OrderFn, RowSource, SearchList, SearchMouse,
};
use crate::keys::KeyBindings;
use crate::settings::AppSettings;
use crate::settings::icons::Icons;

/// Streamed `RowSource` over one directory's listing. Pushes an `Up` row first
/// (when not at root) so it is always present, then forwards each entry the
/// moment `browse_vault_stream` yields it — rows show up while a slow drive is
/// still being read. Ordering is the engine's job (`order_by`, see
/// [`listing_order`]), so nothing is re-delivered at the end. Loads once; a
/// local `Filter::Fuzzy` narrows the set and `leading_row` provides the
/// "Create: …" affordance.
struct DirListingSource {
    vault: Arc<NoteVault>,
    dir: VaultPath,
}

/// The listing's row order for `(field, order)`, directories first when
/// `group_dirs` is set. `Up` sorts before everything (it is filter-exempt and
/// pinned by the engine anyway, but a total order must place it).
fn listing_order(field: SortField, order: SortOrder, group_dirs: bool) -> OrderFn<FileListEntry> {
    Arc::new(move |a: &FileListEntry, b: &FileListEntry| {
        let rank = |e: &FileListEntry| match e {
            FileListEntry::Up { .. } => 0,
            FileListEntry::Directory { .. } if group_dirs => 1,
            _ => 2,
        };
        rank(a).cmp(&rank(b)).then_with(|| {
            let ka = a.sort_key(field);
            let kb = b.sort_key(field);
            match order {
                SortOrder::Ascending => ka.cmp(&kb),
                SortOrder::Descending => kb.cmp(&ka),
            }
        })
    })
}

#[async_trait]
impl RowSource<FileListEntry> for DirListingSource {
    async fn load(&self, _query: &str, emit: Emit<FileListEntry>) {
        // Up row first (if not root) — pushed so it's always present.
        if !self.dir.is_root_or_empty() {
            emit.push(FileListEntry::Up {
                parent: self.dir.get_parent_path().0,
            });
        }

        let options = VaultBrowseOptionsBuilder::new(&self.dir)
            .recursive(false)
            .validation(NotesValidation::Full)
            .build();

        let mut stream = std::pin::pin!(self.vault.browse_vault_stream(options));
        while let Some(item) = stream.next().await {
            let result = match item {
                Ok(result) => result,
                Err(e) => {
                    tracing::warn!("sidebar directory listing failed: {e}");
                    break;
                }
            };
            // `is_like` ignores relative/absolute form: skip the current dir's
            // own "." entry whichever form each side carries.
            if matches!(result.rtype, ResultType::Directory) && result.path.is_like(&self.dir) {
                continue;
            }
            let journal_date = self
                .vault
                .journal_date(&result.path)
                .map(format_journal_date);
            emit.push(FileListEntry::from_result(result, journal_date));
        }
        emit.done();
    }

    fn leading_row(&self, query: &str) -> Option<FileListEntry> {
        if query.is_empty() {
            None
        } else {
            let path = self.dir.append(&VaultPath::note_path_from(query)).flatten();
            Some(FileListEntry::CreateNote {
                filename: path.to_string(),
                path,
            })
        }
    }

    fn reload_on_query(&self) -> bool {
        // Load the directory once; the local fuzzy filter narrows it and
        // `leading_row` keeps the create affordance in sync per keystroke.
        false
    }
}

pub struct SidebarComponent {
    current_dir: VaultPath,
    /// The note currently open in the editor, if any — drives the open-note
    /// marker. `None` on the Browse screen (it never opens notes). Matched
    /// against `FileListEntry::Note` rows by `is_like`.
    open_note: Option<VaultPath>,
    list: Option<SearchList<FileListEntry>>,
    vault: Arc<NoteVault>,
    icons: Icons,
    default_sort_field: SortField,
    default_sort_order: SortOrder,
    journal_sort_field: SortField,
    journal_sort_order: SortOrder,
    /// Sort field/order of the active listing. Set per `navigate` from the
    /// per-dir defaults; the sort shortcuts and dialog change it via
    /// `apply_sort`, which hands the engine a new order.
    sort: (SortField, SortOrder),
    /// "Group directories first" for the active listing; see `sort`.
    group_dirs: bool,
    rendered_rect: Rect,
    /// Screen cell each breadcrumb segment was drawn into on the last render,
    /// with the directory it navigates to — clickable breadcrumb hit-test.
    breadcrumb_cells: Vec<(Rect, VaultPath)>,
    key_bindings: KeyBindings,
}

impl SidebarComponent {
    /// Build a sidebar from the application settings, pulling its key bindings
    /// and icons from `settings`. The shared constructor for the screens that
    /// host a sidebar (Editor and Browse), so the kb/icons wiring lives once.
    pub fn from_settings(vault: Arc<NoteVault>, settings: &AppSettings) -> Self {
        Self::new(
            settings.key_bindings.clone(),
            vault,
            settings.icons(),
            settings,
        )
    }

    pub fn new(
        key_bindings: KeyBindings,
        vault: Arc<NoteVault>,
        icons: Icons,
        settings: &AppSettings,
    ) -> Self {
        let default_sort_field = SortField::from(settings.default_sort_field);
        let default_sort_order = SortOrder::from(settings.default_sort_order);
        Self {
            current_dir: VaultPath::root(),
            open_note: None,
            list: None,
            vault,
            icons,
            default_sort_field,
            default_sort_order,
            journal_sort_field: SortField::from(settings.journal_sort_field),
            journal_sort_order: SortOrder::from(settings.journal_sort_order),
            sort: (default_sort_field, default_sort_order),
            group_dirs: settings.group_directories,
            rendered_rect: Rect::default(),
            breadcrumb_cells: Vec::new(),
            key_bindings,
        }
    }

    /// The breadcrumb segment under the given screen cell, if any.
    fn breadcrumb_at(&self, column: u16, row: u16) -> Option<&VaultPath> {
        self.breadcrumb_cells
            .iter()
            .find(|(rect, _)| rect.contains(Position { x: column, y: row }))
            .map(|(_, dir)| dir)
    }

    pub fn current_dir(&self) -> &VaultPath {
        &self.current_dir
    }

    /// `true` until a directory has been loaded (no engine yet). The editor
    /// uses this to decide whether to issue the first-open navigation.
    pub fn is_empty(&self) -> bool {
        self.list.is_none()
    }

    /// Sort field/order to apply for `dir` (journal dirs get their own).
    fn sort_for(&self, dir: &VaultPath) -> (SortField, SortOrder) {
        if dir.is_like(self.vault.journal_path()) {
            (self.journal_sort_field, self.journal_sort_order)
        } else {
            (self.default_sort_field, self.default_sort_order)
        }
    }

    /// (Re)build the engine for `dir`, replacing any prior listing. This is the
    /// single directory-navigation entry point: changing directory = rebuild
    /// the engine with a fresh `DirListingSource` for the new dir.
    pub fn navigate(&mut self, dir: VaultPath, tx: &AppTx) {
        self.current_dir = dir.clone();
        let (sort_field, sort_order) = self.sort_for(&dir);
        self.sort = (sort_field, sort_order);
        let source = DirListingSource {
            vault: self.vault.clone(),
            dir,
        };
        self.list = Some(
            SearchList::builder(source, redraw_callback(tx.clone()))
                .filter(Filter::Fuzzy)
                .order_by(listing_order(sort_field, sort_order, self.group_dirs))
                .yank_combos_from(&self.key_bindings)
                .icons(self.icons.clone())
                .build(),
        );
    }

    /// Rebuild the listing only when it is currently showing `dir`, so a
    /// create/rename/delete/move in that directory is reflected without yanking
    /// the user away from an unrelated directory they browsed to. A no-op
    /// otherwise. Shared by every screen that hosts a sidebar.
    pub fn refresh_if_showing(&mut self, dir: &VaultPath, tx: &AppTx) {
        if dir.is_like(&self.current_dir) {
            self.navigate(self.current_dir.clone(), tx);
        }
    }

    /// Set (or clear) the note the editor currently has open, then re-stamp the
    /// marker on the live rows. The editor calls this on every open and on an
    /// open-note rename.
    pub fn set_open_note(&mut self, path: Option<VaultPath>) {
        self.open_note = path;
        self.stamp_open_marker();
    }

    /// Re-apply `is_open` to the rows so exactly the open note's row is marked.
    /// Idempotent: a full reload rebuilds rows without the flag, so this runs
    /// again after each load (see `render`).
    fn stamp_open_marker(&mut self) {
        let open = self.open_note.clone();
        if let Some(list) = &mut self.list {
            list.update_rows(|row| {
                if let FileListEntry::Note { path, is_open, .. } = row {
                    let want = open.as_ref().is_some_and(|o| path.is_like(o));
                    if *is_open != want {
                        *is_open = want;
                        return true;
                    }
                }
                false
            });
        }
    }

    /// Update the title of the row whose note path matches `path`, if it is in
    /// the current listing. Called when a note is saved and its title (first
    /// body line) may have changed. Position is left unchanged (no re-sort).
    pub fn update_note_row(&mut self, path: &VaultPath, new_title: &str) {
        if let Some(list) = &mut self.list {
            list.update_rows(|row| {
                if let FileListEntry::Note {
                    path: row_path,
                    title,
                    ..
                } = row
                    && row_path.is_like(path)
                    && title != new_title
                {
                    *title = new_title.to_string();
                    return true;
                }
                false
            });
        }
    }

    /// Move the row at `from` to `to` (path + filename + journal_date) in
    /// place, for a same-directory note rename. The row is re-sorted into its
    /// new spot under the active `listing_order` (a Name sort reads the very
    /// field this changes) and keeps the highlight if it had it.
    /// `journal_date` is recomputed so a rename into/out of a
    /// `YYYY-MM-DD` name under the journal directory flips the glyph and the
    /// secondary date line correctly.
    pub fn rename_note_row(&mut self, from: &VaultPath, to: &VaultPath) {
        let new_filename = to.get_parent_path().1;
        let new_journal_date = self.vault.journal_date(to).map(format_journal_date);
        if let Some(list) = &mut self.list {
            list.update_rows(|row| {
                if let FileListEntry::Note {
                    path,
                    filename,
                    journal_date,
                    ..
                } = row
                    && path.is_like(from)
                {
                    *path = to.clone();
                    *filename = new_filename.clone();
                    *journal_date = new_journal_date.clone();
                    return true;
                }
                false
            });
        }
    }

    /// Seed the directory the sidebar will show before its first `navigate`.
    /// Lets a screen open at a non-root path while keeping `current_dir` the
    /// single source of truth for the browsed directory.
    pub fn set_current_dir(&mut self, dir: VaultPath) {
        self.current_dir = dir;
    }

    /// Current sort field/order for the active listing.
    pub fn current_sort(&self) -> (SortField, SortOrder) {
        self.sort
    }

    /// Current "group directories first" flag.
    pub fn group_dirs(&self) -> bool {
        self.group_dirs
    }

    /// Apply a sort selection from the sort dialog: the engine re-orders the
    /// rows it already holds — no second walk of the directory.
    pub fn apply_sort(&mut self, field: SortField, order: SortOrder, group_dirs: bool) {
        self.sort = (field, order);
        self.group_dirs = group_dirs;
        if let Some(list) = &mut self.list {
            list.set_order(Some(listing_order(field, order, group_dirs)));
        }
    }

    /// `true` when the active directory is the journal (so its sort default is
    /// the journal one). Lets the caller persist to the matching settings.
    pub fn is_current_journal(&self) -> bool {
        self.current_dir.is_like(self.vault.journal_path())
    }

    /// Save the dialog's selection as the in-session default for the active
    /// context (journal vs. normal), then apply it live. Without this, the
    /// cached per-context defaults that `sort_for`/`navigate` read stay at their
    /// construction-time values, so a saved default would have no effect until
    /// restart. The caller is responsible for persisting to the settings file.
    pub fn save_default(&mut self, field: SortField, order: SortOrder, group_dirs: bool) {
        if self.is_current_journal() {
            self.journal_sort_field = field;
            self.journal_sort_order = order;
        } else {
            self.default_sort_field = field;
            self.default_sort_order = order;
        }
        self.apply_sort(field, order, group_dirs);
    }

    /// Number of note rows currently visible (excludes Up / dirs / create).
    fn note_count(&self) -> usize {
        match &self.list {
            None => 0,
            Some(list) => list
                .visible_rows()
                .iter()
                .filter(|e| matches!(e, FileListEntry::Note { .. }))
                .count(),
        }
    }

    /// Act on the selected row: Up/Note/Directory → `OpenPath` (directories and
    /// Up route back through the editor's navigate, rebuilding the engine);
    /// CreateNote → materialise the note, then open it.
    fn activate_selected_entry(&self, tx: &AppTx) {
        let Some(list) = &self.list else { return };
        let Some(entry) = list.selected_row() else {
            return;
        };
        match entry {
            FileListEntry::CreateNote { path, .. } => {
                let path = path.clone();
                let vault = Arc::clone(&self.vault);
                let tx2 = tx.clone();
                tokio::spawn(async move {
                    match vault.load_or_create_note(&path, None).await {
                        Ok((_, created)) => tx2.announce_and_open(path, created),
                        Err(e) => {
                            tracing::warn!("create note failed for {path}: {e}");
                        }
                    }
                });
            }
            FileListEntry::Attachment { path, .. } => {
                tx.send(AppEvent::OpenAttachment(path.clone())).ok();
            }
            other => {
                tx.send(AppEvent::open(other.path().clone())).ok();
            }
        }
    }
}

/// Format a `NaiveDate` as a human-readable string with day-of-week.
/// Example: "Wednesday, March 17, 2026"
fn format_journal_date(date: NaiveDate) -> String {
    date.format("%A, %B %-d, %Y").to_string()
}

impl Component for SidebarComponent {
    fn handle_input(&mut self, event: &InputEvent, tx: &AppTx) -> EventState {
        if let InputEvent::Mouse(mouse) = event {
            let pos = Position {
                x: mouse.column,
                y: mouse.row,
            };
            if !self.rendered_rect.contains(pos) {
                return EventState::NotConsumed;
            }
            // A click on a breadcrumb segment jumps up the tree.
            if matches!(
                mouse.kind,
                ratatui::crossterm::event::MouseEventKind::Down(
                    ratatui::crossterm::event::MouseButton::Left
                )
            ) && let Some(dir) = self.breadcrumb_at(mouse.column, mouse.row)
            {
                tx.send(AppEvent::open(dir.clone())).ok();
                return EventState::Consumed;
            }
            // Click-to-focus is handled centrally by `PanelSet::handle_mouse`;
            // only the sidebar's internal behavior lives here. The engine
            // hit-tests the wheel against the recorded panel rect (the whole
            // sidebar — header and search box included) and clicks against
            // the list rect.
            if let Some(list) = &mut self.list {
                match list.handle_mouse(mouse) {
                    SearchMouse::Activated(_) => self.activate_selected_entry(tx),
                    // Right-click on a file/dir row → context menu (spec §10).
                    SearchMouse::Context(_) => {
                        if let Some(entry) = list.selected_row()
                            && !matches!(
                                entry,
                                FileListEntry::Up { .. } | FileListEntry::CreateNote { .. }
                            )
                        {
                            tx.send(AppEvent::FileOp(FileOp::ShowMenu(entry.path().clone())))
                                .ok();
                        }
                    }
                    // ContentScroll* are unreachable: this host records no
                    // content sub-region.
                    SearchMouse::Selected(_)
                    | SearchMouse::Scrolled
                    | SearchMouse::ContentScrollUp
                    | SearchMouse::ContentScrollDown
                    | SearchMouse::None => {}
                }
            }
            return EventState::Consumed;
        }

        if let InputEvent::Key(key) = event {
            if self.list.is_none() {
                return EventState::NotConsumed;
            }
            let reaction = self.list.as_mut().unwrap().handle_key(key);
            match reaction {
                KeyReaction::Submit => {
                    self.activate_selected_entry(tx);
                    EventState::Consumed
                }
                KeyReaction::Consumed | KeyReaction::Cancel => EventState::Consumed,
                KeyReaction::Yank(target) => {
                    crate::components::yank_row(target, tx);
                    EventState::Consumed
                }
                KeyReaction::Intercepted(_) | KeyReaction::ListVerb(_) | KeyReaction::Unhandled => {
                    EventState::NotConsumed
                }
            }
        } else {
            EventState::NotConsumed
        }
    }

    fn hint_shortcuts(&self) -> Vec<(String, String)> {
        use crate::keys::action_shortcuts::ActionShortcuts;

        crate::components::hints::hints_for(
            &self.key_bindings,
            &[
                (ActionShortcuts::FocusSidebar, "\u{2190} focus left"),
                (ActionShortcuts::FocusEditor, "focus right \u{2192}"),
                (ActionShortcuts::OpenSortDialog, "sort"),
            ],
        )
    }

    fn render(&mut self, f: &mut Frame, rect: Rect, theme: &Theme, focused: bool) {
        self.rendered_rect = rect;

        let rows = Layout::default()
            .direction(Direction::Vertical)
            .constraints([
                Constraint::Length(3),
                Constraint::Length(3),
                Constraint::Min(0),
            ])
            .split(rect);

        let border_style = theme.border_style(focused);

        let header = Block::default()
            .title(format!("─ Files · {} ", self.current_dir))
            .borders(Borders::ALL)
            .border_style(border_style)
            .style(theme.panel_style());
        let header_inner = header.inner(rows[0]);
        f.render_widget(header, rows[0]);

        // Clickable breadcrumb: one span per ancestor directory, separated by
        // " / ", with the note count right-aligned. Each segment's cell is
        // recorded for the click hit-test.
        self.breadcrumb_cells.clear();
        let seg_style = Style::default()
            .fg(theme.fg_secondary.to_ratatui())
            .bg(theme.bg_panel.to_ratatui());
        let sep_style = Style::default()
            .fg(theme.gray.to_ratatui())
            .bg(theme.bg_panel.to_ratatui());
        let mut spans: Vec<Span> = Vec::new();
        let mut x = header_inner.x;
        let mut push_segment =
            |spans: &mut Vec<Span>, x: &mut u16, label: String, dir: VaultPath| {
                let w = unicode_width::UnicodeWidthStr::width(label.as_str()) as u16;
                // Only record cells that are (at least partly) visible — the
                // Paragraph clips at the header edge, so fully clipped
                // segments must not be clickable.
                if *x < header_inner.right() {
                    let visible = w.min(header_inner.right() - *x);
                    self.breadcrumb_cells
                        .push((Rect::new(*x, header_inner.y, visible, 1), dir));
                }
                spans.push(Span::styled(label, seg_style));
                *x += w;
            };
        push_segment(&mut spans, &mut x, "~".to_string(), VaultPath::root());
        let slices = self.current_dir.get_slices();
        let mut acc = String::new();
        for slice in &slices {
            spans.push(Span::styled(" / ", sep_style));
            x += 3;
            acc.push('/');
            acc.push_str(slice);
            push_segment(&mut spans, &mut x, slice.clone(), VaultPath::new(&acc));
        }
        let count = format!("{} notes", self.note_count());
        let used: u16 = x - header_inner.x;
        let pad = header_inner
            .width
            .saturating_sub(used)
            .saturating_sub(unicode_width::UnicodeWidthStr::width(count.as_str()) as u16);
        spans.push(Span::styled(" ".repeat(pad as usize), sep_style));
        spans.push(Span::styled(count, sep_style));
        f.render_widget(Paragraph::new(Line::from(spans)), header_inner);

        let search_block = Block::default()
            .title(" Search")
            .borders(Borders::ALL)
            .border_style(border_style)
            .style(theme.panel_style());
        let search_inner = search_block.inner(rows[1]);
        f.render_widget(search_block, rows[1]);

        let list_block = Block::default()
            .borders(Borders::ALL)
            .border_style(border_style)
            .style(theme.panel_style());
        let list_inner = list_block.inner(rows[2]);
        f.render_widget(list_block, rows[2]);

        // Poll the engine so a just-completed load's rows are applied, then
        // re-stamp the open-note marker (the reload rebuilt rows without it)
        // before the list renders.
        if let Some(list) = &mut self.list {
            list.poll();
        }
        self.stamp_open_marker();
        if let Some(list) = &mut self.list {
            list.render_query(f, search_inner, theme, focused);
            list.render(f, list_inner, theme, focused);
            // Record the rendered-items rect (block inner area) for mouse
            // hit-testing: the engine maps a click to `row - rect.y`, so row 0
            // is the first item. The panel rect (whole sidebar) lets the wheel
            // scroll from anywhere within the sidebar, not just over the list.
            list.set_list_rect(list_inner);
            list.set_panel_rect(rect);
        }
    }
}

#[cfg(test)]
impl SidebarComponent {
    pub(crate) fn poll_for_test(&mut self) {
        if let Some(list) = &mut self.list {
            list.poll();
        }
        self.stamp_open_marker();
    }

    pub(crate) fn is_loading_for_test(&self) -> bool {
        self.list.as_ref().is_some_and(|l| l.is_loading())
    }

    pub(crate) fn note_row_is_open_for_test(&self, name: &str) -> bool {
        self.list.as_ref().is_some_and(|l| {
            l.rows().iter().any(|r| {
                matches!(r, FileListEntry::Note { path, is_open, .. }
                    if path.get_name() == name && *is_open)
            })
        })
    }

    pub(crate) fn note_row_title_for_test(&self, name: &str) -> Option<String> {
        self.list.as_ref().and_then(|l| {
            l.rows().iter().find_map(|r| match r {
                FileListEntry::Note { path, title, .. } if path.get_name() == name => {
                    Some(title.clone())
                }
                _ => None,
            })
        })
    }

    pub(crate) fn note_row_journal_date_for_test(&self, path: &VaultPath) -> Option<String> {
        self.list.as_ref().and_then(|l| {
            l.rows().iter().find_map(|r| match r {
                FileListEntry::Note {
                    path: row_path,
                    journal_date,
                    ..
                } if row_path.is_like(path) => journal_date.clone(),
                _ => None,
            })
        })
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::settings::AppSettings;
    use crate::test_support::{mouse_down_at, temp_vault};
    use ratatui::crossterm::event::{KeyModifiers, MouseEvent, MouseEventKind};
    use tokio::sync::mpsc::unbounded_channel;

    async fn make_sidebar() -> SidebarComponent {
        let vault = temp_vault("sidebar").await;
        vault.validate_and_init().await.unwrap();
        let settings = AppSettings::default();
        SidebarComponent::new(
            settings.key_bindings.clone(),
            vault,
            settings.icons(),
            &settings,
        )
    }

    /// Build a sidebar over `vault` after creating each named note at root.
    async fn sidebar_with_notes(prefix: &str, names: &[&str]) -> SidebarComponent {
        let vault = temp_vault(prefix).await;
        vault.validate_and_init().await.unwrap();
        for name in names {
            vault
                .create_note(&VaultPath::note_path_from(name), "body")
                .await
                .unwrap();
        }
        let settings = AppSettings::default();
        SidebarComponent::new(
            settings.key_bindings.clone(),
            vault,
            settings.icons(),
            &settings,
        )
    }

    /// Clicks anywhere in the sidebar bounds — header, search box, list — are
    /// consumed by the sidebar. (Click-to-focus itself is handled centrally by
    /// `PanelSet::handle_mouse`, not here.)
    #[tokio::test]
    async fn mouse_down_in_sidebar_bounds_is_consumed() {
        let mut sidebar = make_sidebar().await;
        sidebar.rendered_rect = Rect {
            x: 0,
            y: 3,
            width: 30,
            height: 20,
        };
        let (tx, _rx) = unbounded_channel();

        // Header (top-of-sidebar) area.
        assert_eq!(
            sidebar.handle_input(&mouse_down_at(5, 4), &tx),
            EventState::Consumed
        );
        // Search-box area (rows 6..9 within the sidebar layout).
        assert_eq!(
            sidebar.handle_input(&mouse_down_at(5, 7), &tx),
            EventState::Consumed
        );
        // Outside the sidebar bounds.
        assert_eq!(
            sidebar.handle_input(&mouse_down_at(40, 7), &tx),
            EventState::NotConsumed
        );
    }

    fn scroll_event_at(col: u16, row: u16, kind: MouseEventKind) -> InputEvent {
        InputEvent::Mouse(MouseEvent {
            kind,
            column: col,
            row,
            modifiers: KeyModifiers::NONE,
        })
    }

    /// Load the sidebar at the vault root, then poll the engine to idle so the
    /// streamed rows have arrived.
    async fn navigate_to_root(sidebar: &mut SidebarComponent, tx: &AppTx) {
        sidebar.navigate(VaultPath::root(), tx);
        // The streamed source awaits `browse_vault_stream`; give the background
        // work real time to land, polling the engine between waits.
        for _ in 0..50 {
            if let Some(list) = &mut sidebar.list {
                list.poll();
                if !list.is_loading() {
                    break;
                }
            }
            tokio::time::sleep(std::time::Duration::from_millis(5)).await;
        }
        if let Some(list) = &mut sidebar.list {
            list.poll();
        }
    }

    /// Two clicks on the same list row activate it: first selects, second sends
    /// `OpenPath` (or, for `CreateNote`, materialises the note then opens it).
    #[tokio::test(flavor = "multi_thread")]
    async fn mouse_double_click_on_list_row_sends_open_path() {
        let mut sidebar = sidebar_with_notes("sidebar-dbl", &["alpha"]).await;
        let (tx, mut rx) = unbounded_channel();
        navigate_to_root(&mut sidebar, &tx).await;

        sidebar.rendered_rect = Rect {
            x: 0,
            y: 3,
            width: 30,
            height: 20,
        };
        // The engine records the rendered-items rect; clicks hit-test as
        // `row - rect.y`, so row 0 (y=9) is the first item.
        if let Some(list) = &mut sidebar.list {
            list.set_list_rect(Rect {
                x: 0,
                y: 9,
                width: 30,
                height: 14,
            });
        }

        // First click: in the list area, on the first row (rect.y) — selects.
        sidebar.handle_input(&mouse_down_at(5, 9), &tx);

        // Second click on the same row activates the entry.
        sidebar.handle_input(&mouse_down_at(5, 9), &tx);
        let mut events = Vec::new();
        while let Ok(evt) = rx.try_recv() {
            events.push(evt);
        }
        assert!(
            events
                .iter()
                .any(|e| matches!(e, AppEvent::OpenPath { path: p, .. } if p.to_string().contains("alpha"))),
            "expected OpenPath for the activated note, got {events:?}"
        );
    }

    /// Scroll wheel anywhere in the sidebar bounds scrolls the file list — even
    /// when the cursor is over the header or search box. The viewport moves and
    /// the selection is carried along (keeping its screen position), so with a
    /// 1-row viewport the selected row changes on the first scroll.
    #[tokio::test(flavor = "multi_thread")]
    async fn scroll_down_in_sidebar_bounds_scrolls_list() {
        let mut sidebar = sidebar_with_notes("sidebar-scroll", &["alpha", "beta"]).await;
        let (tx, _rx) = unbounded_channel();
        navigate_to_root(&mut sidebar, &tx).await;

        sidebar.rendered_rect = Rect {
            x: 0,
            y: 3,
            width: 30,
            height: 20,
        };
        // A 1-row viewport over 2 notes, so the list overflows and can scroll.
        // The panel rect covers the whole sidebar, so the wheel works from the
        // header/search box too.
        if let Some(list) = &mut sidebar.list {
            list.set_list_rect(Rect {
                x: 0,
                y: 9,
                width: 30,
                height: 1,
            });
            list.set_panel_rect(Rect {
                x: 0,
                y: 3,
                width: 30,
                height: 20,
            });
        }

        let first = sidebar
            .list
            .as_ref()
            .unwrap()
            .selected_row()
            .map(|e| e.path().to_string());

        // Scroll down with the cursor inside the sidebar header (not the list).
        let result = sidebar.handle_input(&scroll_event_at(5, 4, MouseEventKind::ScrollDown), &tx);
        assert_eq!(result, EventState::Consumed);
        let after = sidebar
            .list
            .as_ref()
            .unwrap()
            .selected_row()
            .map(|e| e.path().to_string());
        assert_ne!(
            first, after,
            "scroll-from-header should scroll the list, carrying the selection"
        );
    }

    #[tokio::test]
    async fn mouse_down_outside_sidebar_is_not_consumed() {
        let mut sidebar = make_sidebar().await;
        sidebar.rendered_rect = Rect {
            x: 0,
            y: 3,
            width: 30,
            height: 20,
        };
        let (tx, mut rx) = unbounded_channel();

        // Click to the right of the sidebar (in the editor area).
        let result = sidebar.handle_input(&mouse_down_at(50, 10), &tx);
        assert_eq!(result, EventState::NotConsumed);
        assert!(rx.try_recv().is_err());
    }

    /// Navigating loads the directory's notes via the streamed source.
    #[tokio::test(flavor = "multi_thread")]
    async fn navigate_loads_directory_notes() {
        let mut sidebar = sidebar_with_notes("sidebar-nav", &["hello"]).await;
        assert!(sidebar.is_empty());
        let (tx, _rx) = unbounded_channel();
        navigate_to_root(&mut sidebar, &tx).await;
        assert!(!sidebar.is_empty());
        assert_eq!(sidebar.note_count(), 1);
    }

    /// Poll the (already-navigated) engine to idle so a reload's streamed rows
    /// have arrived.
    async fn poll_to_idle(sidebar: &mut SidebarComponent) {
        for _ in 0..50 {
            if let Some(list) = &mut sidebar.list {
                list.poll();
                if !list.is_loading() {
                    break;
                }
            }
            tokio::time::sleep(std::time::Duration::from_millis(5)).await;
        }
        if let Some(list) = &mut sidebar.list {
            list.poll();
        }
    }

    /// Names of the visible note rows, in display order.
    fn note_names(sidebar: &SidebarComponent) -> Vec<String> {
        sidebar
            .list
            .as_ref()
            .unwrap()
            .visible_rows()
            .iter()
            .filter_map(|e| match e {
                FileListEntry::Note { filename, .. } => Some(filename.clone()),
                _ => None,
            })
            .collect()
    }

    /// The directory listing streams each row the moment the walk yields it
    /// and nothing else: ordering is the engine's job (`order_by`), so there
    /// is no end-of-walk re-delivery to make rows jump.
    #[tokio::test(flavor = "multi_thread")]
    async fn listing_streams_each_row_then_done() {
        use crate::components::search_list::Loaded;

        let sidebar = sidebar_with_notes("sidebar-stream", &["charlie", "alpha", "bravo"]).await;
        let source = DirListingSource {
            vault: sidebar.vault.clone(),
            dir: VaultPath::root(),
        };
        let (emit, rx) = Emit::capture();

        source.load("", emit).await;

        let events: Vec<Loaded<FileListEntry>> = rx.try_iter().map(|(_, ev)| ev).collect();
        let pushed_notes = events
            .iter()
            .filter(|e| matches!(e, Loaded::Push(FileListEntry::Note { .. })))
            .count();
        assert_eq!(pushed_notes, 3, "each note is streamed as its own row");
        assert!(
            !events.iter().any(|e| matches!(e, Loaded::Replace(_))),
            "no whole-set re-delivery"
        );
        assert!(
            matches!(events.last(), Some(Loaded::Done)),
            "done closes the load"
        );
    }

    /// A sort change re-orders the rows already loaded; it must not walk the
    /// directory again.
    #[tokio::test(flavor = "multi_thread")]
    async fn apply_sort_reorders_without_reloading() {
        let mut sidebar =
            sidebar_with_notes("sidebar-resort", &["alpha", "bravo", "charlie"]).await;
        let (tx, _rx) = unbounded_channel();
        navigate_to_root(&mut sidebar, &tx).await;
        let before = note_names(&sidebar);
        assert_eq!(before.len(), 3, "expected three notes, got {before:?}");

        sidebar.apply_sort(SortField::Name, SortOrder::Descending, false);

        let list = sidebar.list.as_ref().unwrap();
        assert!(
            !list.is_loading(),
            "a sort change must not reload the listing"
        );
        assert_eq!(
            note_names(&sidebar),
            before.iter().rev().cloned().collect::<Vec<_>>(),
            "rows re-ordered in place"
        );
    }

    #[tokio::test(flavor = "multi_thread")]
    async fn apply_sort_reverse_flips_listing_order() {
        let mut sidebar = sidebar_with_notes("sidebar-sort", &["alpha", "bravo", "charlie"]).await;
        let (tx, _rx) = unbounded_channel();
        navigate_to_root(&mut sidebar, &tx).await;
        let before = note_names(&sidebar);
        assert_eq!(before.len(), 3, "expected three notes, got {before:?}");
        sidebar.apply_sort(SortField::Name, SortOrder::Descending, false);
        poll_to_idle(&mut sidebar).await;
        let after = note_names(&sidebar);
        assert_eq!(
            after,
            before.iter().rev().cloned().collect::<Vec<_>>(),
            "descending order should reverse the listing"
        );
    }

    #[tokio::test(flavor = "multi_thread")]
    async fn apply_sort_changes_field() {
        let mut sidebar = sidebar_with_notes("sidebar-cycle", &["alpha", "bravo"]).await;
        let (tx, _rx) = unbounded_channel();
        navigate_to_root(&mut sidebar, &tx).await;
        sidebar.apply_sort(SortField::Title, SortOrder::Ascending, false);
        poll_to_idle(&mut sidebar).await;
        assert_eq!(sidebar.current_sort().0, SortField::Title);
        assert_eq!(note_names(&sidebar).len(), 2, "notes survive the resort");
    }

    /// Build a sidebar over a vault with both notes and a subdirectory.
    async fn sidebar_with_notes_and_dir(prefix: &str) -> SidebarComponent {
        let vault = temp_vault(prefix).await;
        vault.validate_and_init().await.unwrap();
        vault
            .create_note(&VaultPath::note_path_from("alpha"), "body")
            .await
            .unwrap();
        vault
            .create_note(&VaultPath::note_path_from("z-dir/inner"), "body")
            .await
            .unwrap();
        let settings = AppSettings::default();
        SidebarComponent::new(
            settings.key_bindings.clone(),
            vault,
            settings.icons(),
            &settings,
        )
    }

    /// Kinds of the visible rows, in display order (excluding the Up row).
    fn row_kinds(sidebar: &SidebarComponent) -> Vec<&'static str> {
        sidebar
            .list
            .as_ref()
            .unwrap()
            .visible_rows()
            .iter()
            .filter_map(|e| match e {
                FileListEntry::Note { .. } => Some("note"),
                FileListEntry::Directory { .. } => Some("dir"),
                _ => None,
            })
            .collect()
    }

    #[tokio::test(flavor = "multi_thread")]
    async fn group_dirs_puts_directories_first() {
        let mut sidebar = sidebar_with_notes_and_dir("sidebar-group").await;
        let (tx, _rx) = unbounded_channel();
        navigate_to_root(&mut sidebar, &tx).await;
        assert_eq!(row_kinds(&sidebar), vec!["note", "dir"]);
        sidebar.apply_sort(SortField::Name, SortOrder::Ascending, true);
        poll_to_idle(&mut sidebar).await;
        assert_eq!(
            row_kinds(&sidebar),
            vec!["dir", "note"],
            "grouping must cluster directories first"
        );
    }

    #[tokio::test(flavor = "multi_thread")]
    async fn apply_sort_updates_shared_state() {
        let mut sidebar = sidebar_with_notes("sidebar-apply", &["alpha", "bravo"]).await;
        let (tx, _rx) = unbounded_channel();
        navigate_to_root(&mut sidebar, &tx).await;
        sidebar.apply_sort(SortField::Title, SortOrder::Descending, false);
        poll_to_idle(&mut sidebar).await;
        assert_eq!(
            sidebar.current_sort(),
            (SortField::Title, SortOrder::Descending)
        );
        assert!(!sidebar.group_dirs());
    }

    #[tokio::test(flavor = "multi_thread")]
    async fn set_open_note_stamps_matching_row() {
        let mut sb = sidebar_with_notes("sb-open", &["alpha", "beta"]).await;
        let (tx, _rx) = unbounded_channel();
        navigate_to_root(&mut sb, &tx).await;

        sb.set_open_note(Some(VaultPath::note_path_from("alpha")));
        assert!(
            sb.note_row_is_open_for_test("alpha.md"),
            "open note is marked"
        );
        assert!(
            !sb.note_row_is_open_for_test("beta.md"),
            "other note is not marked"
        );

        sb.set_open_note(Some(VaultPath::note_path_from("beta")));
        assert!(!sb.note_row_is_open_for_test("alpha.md"));
        assert!(sb.note_row_is_open_for_test("beta.md"));

        sb.set_open_note(None);
        assert!(!sb.note_row_is_open_for_test("beta.md"));
    }

    #[tokio::test(flavor = "multi_thread")]
    async fn update_note_row_changes_title_in_place() {
        let mut sb = sidebar_with_notes("sb-title", &["alpha"]).await;
        let (tx, _rx) = unbounded_channel();
        navigate_to_root(&mut sb, &tx).await;

        sb.update_note_row(&VaultPath::note_path_from("alpha"), "Fresh Title");
        assert_eq!(
            sb.note_row_title_for_test("alpha.md").as_deref(),
            Some("Fresh Title")
        );
    }

    #[tokio::test(flavor = "multi_thread")]
    async fn rename_note_row_updates_path_and_filename() {
        let mut sb = sidebar_with_notes("sb-rename", &["alpha"]).await;
        let (tx, _rx) = unbounded_channel();
        navigate_to_root(&mut sb, &tx).await;

        let to = VaultPath::note_path_from("gamma");
        let expected_filename = to.get_parent_path().1;
        sb.rename_note_row(&VaultPath::note_path_from("alpha"), &to);
        assert!(
            sb.note_row_title_for_test("gamma.md").is_some(),
            "row now at new name"
        );
        assert!(
            sb.note_row_title_for_test("alpha.md").is_none(),
            "old name gone"
        );
        // Also verify the filename field itself was updated to the new name.
        let renamed_filename = sb
            .list
            .as_ref()
            .unwrap()
            .rows()
            .iter()
            .find_map(|r| match r {
                FileListEntry::Note { path, filename, .. } if path.is_like(&to) => {
                    Some(filename.clone())
                }
                _ => None,
            });
        assert_eq!(
            renamed_filename.as_deref(),
            Some(expected_filename.as_str()),
            "filename field must be updated to the new name"
        );
    }

    /// Renaming a journal-dir note (`YYYY-MM-DD`) to a non-date name clears
    /// `journal_date` on the row so the glyph and secondary date line update.
    #[tokio::test(flavor = "multi_thread")]
    async fn rename_note_row_clears_journal_date_when_renamed_away_from_date_name() {
        // Build a vault and create a note inside the journal directory with a
        // valid YYYY-MM-DD name so `vault.journal_date` returns Some(_).
        let vault = crate::test_support::temp_vault("sb-jdate").await;
        vault.validate_and_init().await.unwrap();
        let journal_path = vault.journal_path().clone();
        let date_name = "2026-06-09";
        let from = journal_path
            .append(&VaultPath::note_path_from(date_name))
            .absolute();
        vault.create_note(&from, "journal body").await.unwrap();

        let settings = AppSettings::default();
        let mut sb = SidebarComponent::new(
            settings.key_bindings.clone(),
            vault,
            settings.icons(),
            &settings,
        );
        let (tx, _rx) = unbounded_channel();
        // Navigate to the journal directory (not root) so the note row is listed.
        sb.navigate(journal_path.clone(), &tx);
        for _ in 0..50 {
            sb.poll_for_test();
            if !sb.is_loading_for_test() {
                break;
            }
            tokio::time::sleep(std::time::Duration::from_millis(5)).await;
        }
        sb.poll_for_test();

        // Precondition: the journal row has a non-None `journal_date`.
        assert!(
            sb.note_row_journal_date_for_test(&from).is_some(),
            "journal note must have a journal_date before rename"
        );

        // Rename the note to a plain name (not a date) in the same directory.
        let to = journal_path
            .append(&VaultPath::note_path_from("meeting"))
            .absolute();
        sb.rename_note_row(&from, &to);

        // The row should now have journal_date = None.
        assert_eq!(
            sb.note_row_journal_date_for_test(&to),
            None,
            "journal_date must be cleared after renaming to a non-date name"
        );
    }

    /// Regression: saving a default must survive navigation. `save_default`
    /// updates the cached per-context default that `sort_for`/`navigate` read;
    /// without it, navigating re-derives the construction-time default and the
    /// saved choice is silently lost.
    #[tokio::test(flavor = "multi_thread")]
    async fn save_default_survives_navigation() {
        let mut sidebar = sidebar_with_notes("sidebar-savedef", &["alpha", "bravo"]).await;
        let (tx, _rx) = unbounded_channel();
        navigate_to_root(&mut sidebar, &tx).await;

        sidebar.save_default(SortField::Title, SortOrder::Descending, false);
        poll_to_idle(&mut sidebar).await;

        // Re-navigate (root is non-journal) — sort_for must now yield the saved
        // default, not the constructor-time (Name, Ascending).
        sidebar.navigate(VaultPath::root(), &tx);
        poll_to_idle(&mut sidebar).await;
        assert_eq!(
            sidebar.current_sort(),
            (SortField::Title, SortOrder::Descending),
            "saved default must persist across navigation"
        );
    }

    // ── A slow filesystem: streamed rows on the test's schedule ──────────
    //
    // `DirListingSource` forwards each entry the moment `browse_vault_stream`
    // yields it, so on a slow drive the sidebar shows a PARTIAL listing for
    // many frames — and the user can sort, filter and select inside that
    // window while more rows keep landing. A real vault settles on the first
    // poll, so none of that window is reachable through `navigate_to_root`.
    // This source parks its `Emit` instead and lets the test say when each row
    // arrives, which is the only way to pin what the selection does across
    // LATER polls.

    struct SlowListingSource {
        slot: Arc<std::sync::Mutex<Option<Emit<FileListEntry>>>>,
    }

    #[async_trait]
    impl RowSource<FileListEntry> for SlowListingSource {
        async fn load(&self, _query: &str, emit: Emit<FileListEntry>) {
            *self.slot.lock().unwrap() = Some(emit);
        }
        fn reload_on_query(&self) -> bool {
            false
        }
    }

    /// The engine `navigate` builds — same filter and same `listing_order` —
    /// over a listing the test drives row by row.
    async fn slow_listing(
        field: SortField,
        order: SortOrder,
        group_dirs: bool,
    ) -> (SearchList<FileListEntry>, Emit<FileListEntry>) {
        let slot = Arc::new(std::sync::Mutex::new(None));
        let list = SearchList::builder(
            SlowListingSource { slot: slot.clone() },
            Arc::new(|| {}) as Arc<dyn Fn() + Send + Sync>,
        )
        .filter(Filter::Fuzzy)
        .order_by(listing_order(field, order, group_dirs))
        .build();
        let emit = loop {
            if let Some(e) = slot.lock().unwrap().clone() {
                break e;
            }
            tokio::task::yield_now().await;
        };
        (list, emit)
    }

    fn note_row(title: &str) -> FileListEntry {
        let path = VaultPath::note_path_from(title);
        let filename = path.get_parent_path().1;
        FileListEntry::Note {
            path,
            title: title.to_string(),
            filename,
            journal_date: None,
            is_open: false,
        }
    }

    fn dir_row(name: &str) -> FileListEntry {
        FileListEntry::Directory {
            path: VaultPath::new(name),
            name: name.to_string(),
        }
    }

    /// Row labels in display order. Avoids `sort_key`, which would put the
    /// note extension into every assertion.
    fn labels(list: &SearchList<FileListEntry>) -> Vec<String> {
        list.visible_rows().iter().map(|r| label(r)).collect()
    }

    fn label(row: &FileListEntry) -> String {
        match row {
            FileListEntry::Up { .. } => "..".to_string(),
            FileListEntry::Directory { name, .. } => format!("{name}/"),
            FileListEntry::Note { title, .. } => title.clone(),
            FileListEntry::Attachment { filename, .. } => filename.clone(),
            FileListEntry::CreateNote { filename, .. } => format!("create:{filename}"),
        }
    }

    fn highlighted(list: &SearchList<FileListEntry>) -> Option<String> {
        list.selected_row().map(label)
    }

    /// The baseline for a slow drive: until the user touches it, the highlight
    /// belongs to the TOP of the sort, not to whichever entry the walker
    /// happened to reach first. Every later poll re-decides it.
    #[tokio::test]
    async fn a_slow_listing_keeps_the_untouched_highlight_on_the_top_row() {
        let (mut list, emit) = slow_listing(SortField::Name, SortOrder::Ascending, false).await;

        emit.push(note_row("mike"));
        list.poll();
        assert_eq!(highlighted(&list).as_deref(), Some("mike"));

        emit.push(note_row("delta"));
        list.poll();
        assert_eq!(labels(&list), ["delta", "mike"]);
        assert_eq!(highlighted(&list).as_deref(), Some("delta"));

        emit.push(note_row("alpha"));
        list.poll();
        assert_eq!(labels(&list), ["alpha", "delta", "mike"]);
        assert_eq!(
            highlighted(&list).as_deref(),
            Some("alpha"),
            "the highlight follows the top of the sort, not the first row to arrive"
        );
        emit.done();
    }

    /// In a subdirectory the `Up` row is PUSHED (not a leading row) and is
    /// filter-exempt, so it is both the first row to arrive and the first in
    /// `listing_order`. The untouched highlight must sit on it and stay there
    /// as the directory's own entries trickle in.
    #[tokio::test]
    async fn a_slow_subdirectory_listing_keeps_the_highlight_on_the_up_row() {
        let (mut list, emit) = slow_listing(SortField::Name, SortOrder::Ascending, false).await;

        emit.push(FileListEntry::Up {
            parent: VaultPath::root(),
        });
        list.poll();
        assert_eq!(highlighted(&list).as_deref(), Some(".."));

        emit.push(note_row("alpha"));
        list.poll();
        emit.push(note_row("aaron")); // sorts above "alpha", but below `Up`
        list.poll();
        assert_eq!(labels(&list), ["..", "aaron", "alpha"]);
        assert_eq!(
            highlighted(&list).as_deref(),
            Some(".."),
            "`Up` outranks every arriving entry, so the seed never leaves it"
        );
        emit.done();
    }

    /// The sort dialog is reachable while the drive is still being read.
    /// Re-sorting an untouched listing must leave the highlight on the top of
    /// the NEW order — and must not silently promote the seed to a choice, so
    /// rows arriving afterwards still take the top with it.
    #[tokio::test]
    async fn a_sort_change_mid_stream_keeps_the_untouched_highlight_on_top() {
        let (mut list, emit) = slow_listing(SortField::Name, SortOrder::Ascending, false).await;

        emit.push(note_row("bravo"));
        emit.push(note_row("delta"));
        list.poll();
        assert_eq!(labels(&list), ["bravo", "delta"]);
        assert_eq!(highlighted(&list).as_deref(), Some("bravo"));

        // The user flips to descending while rows are still arriving.
        list.set_order(Some(listing_order(
            SortField::Name,
            SortOrder::Descending,
            false,
        )));
        assert_eq!(labels(&list), ["delta", "bravo"]);
        assert_eq!(
            highlighted(&list).as_deref(),
            Some("delta"),
            "a re-sort moves the untouched highlight to the new top row"
        );

        // ...and the rest of the slow listing keeps landing, still sorted,
        // still carrying the highlight.
        emit.push(note_row("echo"));
        list.poll();
        assert_eq!(labels(&list), ["echo", "delta", "bravo"]);
        assert_eq!(
            highlighted(&list).as_deref(),
            Some("echo"),
            "the sort change must not turn the seed into a user choice"
        );
        emit.done();
    }

    /// The chosen half of the same window: a row the user picked mid-stream is
    /// theirs. A re-sort and every later arrival move it around the list, and
    /// it stays highlighted throughout.
    #[tokio::test]
    async fn a_row_chosen_mid_stream_survives_a_sort_change_and_later_arrivals() {
        let (mut list, emit) = slow_listing(SortField::Name, SortOrder::Ascending, false).await;

        emit.push(note_row("bravo"));
        emit.push(note_row("delta"));
        list.poll();
        list.select_next(); // "delta", by the user's own keys
        assert_eq!(highlighted(&list).as_deref(), Some("delta"));

        list.set_order(Some(listing_order(
            SortField::Name,
            SortOrder::Descending,
            false,
        )));
        assert_eq!(labels(&list), ["delta", "bravo"]);
        assert_eq!(highlighted(&list).as_deref(), Some("delta"));

        emit.push(note_row("echo")); // sorts above it under the new order
        list.poll();
        assert_eq!(labels(&list), ["echo", "delta", "bravo"]);
        assert_eq!(
            highlighted(&list).as_deref(),
            Some("delta"),
            "a chosen row keeps the highlight through a re-sort and later arrivals"
        );
        emit.done();
    }

    /// `listing_order` ranks directories above notes when `group_dirs` is set,
    /// so a directory the walker reaches LAST still lands at the top — and
    /// takes an untouched highlight with it.
    #[tokio::test]
    async fn a_late_directory_takes_the_top_when_directories_are_grouped() {
        let (mut list, emit) = slow_listing(SortField::Name, SortOrder::Ascending, true).await;

        emit.push(note_row("alpha"));
        emit.push(note_row("bravo"));
        list.poll();
        assert_eq!(highlighted(&list).as_deref(), Some("alpha"));

        emit.push(dir_row("zeta"));
        list.poll();
        assert_eq!(labels(&list), ["zeta/", "alpha", "bravo"]);
        assert_eq!(
            highlighted(&list).as_deref(),
            Some("zeta/"),
            "grouped directories outrank notes whenever they arrive"
        );
        emit.done();
    }

    /// Typing narrows the partial listing locally (`reload_on_query` is false,
    /// so no reload). A row the user picked stays picked while the rest of the
    /// slow listing lands behind the filter.
    #[tokio::test]
    async fn filtering_mid_stream_keeps_a_chosen_row_while_more_rows_arrive() {
        let (mut list, emit) = slow_listing(SortField::Name, SortOrder::Ascending, false).await;

        emit.push(note_row("alpha"));
        emit.push(note_row("albatross"));
        emit.push(note_row("zebra"));
        list.poll();
        list.set_query("al");
        assert_eq!(labels(&list), ["albatross", "alpha"]);
        list.select_next(); // "alpha", chosen behind the filter
        assert_eq!(highlighted(&list).as_deref(), Some("alpha"));

        // More of the directory lands; one entry matches the filter and sorts
        // above the chosen row, the other is filtered out entirely.
        emit.push(note_row("alabama"));
        emit.push(note_row("yankee"));
        list.poll();
        assert_eq!(labels(&list), ["alabama", "albatross", "alpha"]);
        assert_eq!(
            highlighted(&list).as_deref(),
            Some("alpha"),
            "the chosen row keeps the highlight behind an active filter"
        );

        // Clearing the filter reveals the rest without losing the choice.
        list.set_query("");
        assert_eq!(
            labels(&list),
            ["alabama", "albatross", "alpha", "yankee", "zebra"]
        );
        assert_eq!(highlighted(&list).as_deref(), Some("alpha"));
        emit.done();
    }

    /// An in-place row update (the editor renaming the open note's title) is a
    /// recompute, and a recompute re-applies `order_by` — so under a Title sort
    /// the touched row MOVES. The highlight has to move with it: the user is
    /// pointing at a note, not at a slot.
    #[tokio::test]
    async fn an_in_place_update_that_re_sorts_carries_the_highlight_with_the_row() {
        let (mut list, emit) = slow_listing(SortField::Title, SortOrder::Ascending, false).await;
        emit.push(note_row("alpha"));
        emit.push(note_row("bravo"));
        emit.push(note_row("charlie"));
        list.poll();
        list.select_next();
        list.select_next();
        assert_eq!(highlighted(&list).as_deref(), Some("charlie"));

        // The editor retitles the selected note to something that sorts first.
        list.update_rows(|row| {
            if let FileListEntry::Note { title, .. } = row
                && title == "charlie"
            {
                *title = "aaa".to_string();
                return true;
            }
            false
        });

        assert_eq!(labels(&list), ["aaa", "alpha", "bravo"]);
        assert_eq!(
            highlighted(&list).as_deref(),
            Some("aaa"),
            "the highlight belongs to the row, not to the position it used to hold"
        );
        emit.done();
    }

    /// ...and the seeded half: an untouched highlight keeps the top slot when
    /// an in-place update re-sorts the listing under it.
    #[tokio::test]
    async fn an_in_place_update_that_re_sorts_leaves_a_seed_on_the_top_row() {
        let (mut list, emit) = slow_listing(SortField::Title, SortOrder::Ascending, false).await;
        emit.push(note_row("bravo"));
        emit.push(note_row("charlie"));
        list.poll();
        assert_eq!(highlighted(&list).as_deref(), Some("bravo"));

        list.update_rows(|row| {
            if let FileListEntry::Note { title, .. } = row
                && title == "charlie"
            {
                *title = "aaa".to_string();
                return true;
            }
            false
        });

        assert_eq!(labels(&list), ["aaa", "bravo"]);
        assert_eq!(
            highlighted(&list).as_deref(),
            Some("aaa"),
            "an untouched highlight belongs to the top of the order after any recompute"
        );
        emit.done();
    }
}