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
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
//! `SourcesPanel` — the Ask workspace's drawer view (CONTEXT.md: **Sources
//! view**, **Source reader**; adr/0030): a ranked per-turn source list that
//! reveals the full note — the retrieved section highlighted — in an inline
//! preview, without leaving the answer.
//!
//! Composes the shared list engine ([`SearchList`]) the same way the FIND
//! drawer (`query_panel.rs`) does — the panel no longer hand-rolls
//! `List`/`ListState`, a cursor, selection styling, plain-letter matching, or a
//! chord pre-intercept. The engine owns navigation, the (new) filter input,
//! selection, list scroll, the list-focus verbs (`l`/`h`/`o`/`y`), the
//! FollowLink / `Ctrl+Y` intercepts, and mouse hit-testing; on top of it the
//! panel composes the shared [`PreviewPane`] reveal (the **Source reader**) and
//! the per-turn note-load lifecycle.
//!
//! Unlike FIND (which opens on its query input), the Sources view opens on the
//! list ([`Focus::List`]) — the first production user of `opening_focus`. Its
//! rows are per-turn in-memory sources, so it composes `SearchList` directly
//! (built synchronously over a [`StaticRowSource`]) rather than through
//! `QueryListPanel`:
//! `QueryListPanel` is a bare list with no `PreviewPane` and it swallows the
//! `ListVerb`/`Intercepted` reactions the reveal is driven by.
//!
//! The per-turn sources live in the engine's row set (there is no parallel
//! copy): `set_turn`/`refresh`/`reset` rebuild the engine over the turn's rows,
//! and the directed reveals (`open_reader`/`focus_source`) and note-load
//! resolution all read them back through the engine.
use std::ops::Range;
use std::sync::Arc;
use kimun_core::NoteVault;
use kimun_core::nfs::VaultPath;
use ratatui::Frame;
use ratatui::crossterm::event::{
KeyCode, KeyEvent, KeyModifiers, MouseButton, MouseEvent, MouseEventKind,
};
use ratatui::layout::{Constraint, Direction, Layout, Position, Rect};
use ratatui::style::{Modifier, Style};
use ratatui::widgets::{Block, Borders, ListItem, Paragraph};
use crate::ask::{AskSource, locate};
use crate::components::event_state::EventState;
use crate::components::events::{AppEvent, AppTx, AskData, InputEvent, redraw_callback};
use crate::components::panel::panel_block;
use crate::components::preview_pane::{Highlight, PreviewPane};
use crate::components::rich_row::RichRow;
use crate::components::search_list::{
Filter, Focus, KeyReaction, SearchList, SearchMouse, SearchRow, StaticRowSource,
};
use crate::keys::KeyBindings;
use crate::keys::action_shortcuts::ActionShortcuts;
use crate::keys::key_combo::KeyCombo;
use crate::settings::icons::Icons;
use crate::settings::themes::Theme;
/// Rows a PageUp/PageDown leaves visible from the previous view (shared
/// convention with the note preview and the Ask thread).
const PAGE_OVERLAP: u16 = 2;
/// The load state for the currently-anchored source's note text.
enum ReaderContent {
/// The note load is in flight.
Loading,
/// The note loaded successfully. `highlight` is the byte range
/// `locate::section_range` resolved, if any.
Loaded {
text: String,
highlight: Option<Range<usize>>,
},
/// The note load failed.
Failed,
}
/// The async note load backing the preview. Keyed by `path` for stale-drop of
/// an in-flight vault load (a selection change, or a new turn, before the load
/// lands must not clobber the note anchored now), and additionally by the
/// source `ordinal` so that selecting a *different section of the same note*
/// re-resolves the highlight against the new heading without a refetch.
struct LoadedNote {
path: VaultPath,
/// The anchored source's citation ordinal — the section identity within the
/// note. Distinguishes two sources sharing a `path` but a different heading.
ordinal: usize,
content: ReaderContent,
}
/// One list-engine row: a per-turn source plus its 1-based rank (its position
/// in the turn's ranked list — kept on the row so it survives filtering). The
/// [`SearchRow`] bridge draws it as the shared [`RichRow`] and exposes the
/// heading + path as the fuzzy-filter haystack.
#[derive(Clone)]
struct SourceRow {
rank: usize,
source: AskSource,
/// The `heading path` haystack the list's `Filter::Fuzzy` matches, so the
/// new filter input narrows the turn's sources by heading or path text.
filter_text: String,
}
impl SourceRow {
fn new(rank: usize, source: AskSource) -> Self {
let filter_text = format!("{} {}", source.heading, source.path);
Self {
rank,
source,
filter_text,
}
}
}
impl SearchRow for SourceRow {
fn to_list_item(&self, theme: &Theme, _icons: &Icons, _selected: bool) -> ListItem<'static> {
source_row(self.rank, &self.source, theme).into_list_item(theme)
}
fn visual_height(&self) -> u16 {
// Title line + dim filename line (the date is inline on the title).
2
}
fn match_text(&self) -> Option<&str> {
Some(&self.filter_text)
}
}
/// The Ask workspace's Sources drawer view: a ranked source list (on the shared
/// [`SearchList`]) with the shared [`PreviewPane`] revealing the selected
/// source's note below/over it.
pub struct SourcesPanel {
turn_id: Option<u64>,
/// The shared list engine: query/filter input, result list, selection,
/// list scroll, list-focus verbs and intercepts. Rebuilt per turn,
/// synchronously, over the turn's in-memory rows (a [`StaticRowSource`]).
list: SearchList<SourceRow>,
/// The note-preview surface (expand cycle + content scroll + content
/// render), shared with the FIND drawer. Anchored by the located section
/// byte range as the highlight.
preview: PreviewPane,
/// The note load for the currently-anchored source. `None` until a preview
/// first opens.
loaded: Option<LoadedNote>,
/// Vault handle for the preview's note load (`ensure_note_load` spawns a
/// `vault.get_note_text`). Owned here so `handle_input` needs no vault
/// passed in.
vault: Arc<NoteVault>,
icons: Icons,
/// Combos the engine intercepts: FollowLink (open) plus `Ctrl+Y` (yank).
/// Registered on every rebuilt list.
intercept: Vec<KeyCombo>,
/// The `Ctrl+Y` combo, kept to route an [`KeyReaction::Intercepted`] to
/// yank (any other intercepted combo is a FollowLink → open).
ctrl_y_combo: Option<KeyCombo>,
/// The preview content viewport height from the last render — the page size
/// for PageUp/PageDown content scrolling in the Full preview.
preview_page: u16,
}
impl SourcesPanel {
pub fn new(vault: Arc<NoteVault>, key_bindings: &KeyBindings) -> Self {
let map = key_bindings.to_hashmap();
let follow = map
.get(&ActionShortcuts::FollowLink)
.cloned()
.unwrap_or_default();
let ctrl_y_combo = crate::keys::key_event_to_combo(&KeyEvent::new(
KeyCode::Char('y'),
KeyModifiers::CONTROL,
));
let mut intercept = follow;
if let Some(c) = ctrl_y_combo {
intercept.push(c);
}
let icons = Icons::new(false);
// The initial (turn-less) list is empty and built synchronously
// ([`build_list`] uses `build_with_rows`), so the redraw callback is
// never fired — a no-op is harmless by construction.
let list = build_list(Vec::new(), &intercept, &icons, Arc::new(|| {}));
Self {
turn_id: None,
list,
preview: PreviewPane::new(),
loaded: None,
vault,
icons,
intercept,
ctrl_y_combo,
preview_page: 0,
}
}
/// Repopulates the list for `turn_id` and collapses the preview. A repeated
/// call with the same `turn_id` is a no-op — it keeps the selection (and the
/// preview state) exactly as-is when a selection sync re-points the drawer
/// at the already-shown turn. Regeneration replaces a turn's sources with
/// the fresh ones on completion, but that goes through
/// [`refresh`](Self::refresh) (which never short-circuits), not here.
pub fn set_turn(&mut self, turn_id: u64, sources: Vec<AskSource>, tx: &AppTx) {
if self.turn_id == Some(turn_id) {
return;
}
self.refresh(turn_id, sources, tx);
}
/// Force the source list for `turn_id` to `sources`, even when it's the
/// turn already shown — the answer-completion path, where a `Thinking`
/// turn (empty sources) gains its sources once the answer lands. Unlike
/// [`set_turn`](Self::set_turn), it never short-circuits on a matching id.
/// Collapses the preview and resets to the top.
pub fn refresh(&mut self, turn_id: u64, sources: Vec<AskSource>, tx: &AppTx) {
self.turn_id = Some(turn_id);
self.rebuild_list(sources, tx);
self.preview.reset();
self.loaded = None;
}
/// Clear the panel back to its empty, collapsed state — the "new
/// conversation" action (leader `a n`) drops the old turn's sources.
pub fn reset(&mut self, tx: &AppTx) {
self.turn_id = None;
self.rebuild_list(Vec::new(), tx);
self.preview.reset();
self.loaded = None;
}
/// (Re)build the list engine over `sources` (rank = 1-based position), the
/// engine-per-turn pattern: the turn's rows live only in the engine. The
/// rows are applied synchronously ([`build_list`] uses `build_with_rows`),
/// so they are present the instant this returns — no async load to wake a
/// redraw for. `tx` is still threaded to the engine's (never-fired) redraw
/// callback, harmless by construction.
fn rebuild_list(&mut self, sources: Vec<AskSource>, tx: &AppTx) {
let rows: Vec<SourceRow> = sources
.into_iter()
.enumerate()
.map(|(i, s)| SourceRow::new(i + 1, s))
.collect();
self.list = build_list(
rows,
&self.intercept,
&self.icons,
redraw_callback(tx.clone()),
);
}
/// Whether the current turn has any sources — read from the engine's row
/// set (the panel keeps no parallel copy).
fn has_sources(&self) -> bool {
!self.list.rows().is_empty()
}
/// The source at rank position `index` (0-based), from the engine's full
/// (unfiltered) row set.
fn source_at(&self, index: usize) -> Option<&AskSource> {
self.list.rows().get(index).map(|r| &r.source)
}
/// Point the list selection at the source with citation `ordinal` and
/// collapse the preview — a citation click in the thread asks the drawer to
/// reveal that exact source in the list. This is the ordinal→row boundary:
/// the panel lists sources in rank order, so it resolves the ordinal to a
/// position by matching the engine's rows, never by assuming `ordinal - 1`.
/// An ordinal with no matching source is ignored. Clears any active filter
/// so the target is never hidden.
pub fn focus_source(&mut self, ordinal: usize) {
self.list.set_query(""); // clear any filter so the target is never hidden
self.preview.reset();
self.loaded = None;
// The turn's rows are applied synchronously on rebuild, so the target is
// present now: resolve the ordinal to its visible position and select it
// inline — no deferral, even for a cross-turn citation click that ran
// `set_turn` in the same tick. An unknown ordinal is ignored.
if let Some(pos) = self
.list
.visible_rows()
.iter()
.position(|r| r.source.ordinal == ordinal)
{
self.list.select(pos);
}
}
/// Reveal `sources[source_index]` in the preview (leader `a s`): point the
/// selection at it and make sure the preview ends *revealed* on that source.
/// Collapsed opens to the half-height Context preview; an already-open
/// Context/Full stays at its expand level and re-points onto the new source
/// (never collapsing the way a plain selection move would). Spawns/refreshes
/// the note load. No-op for an out-of-range index.
pub fn open_reader(&mut self, source_index: usize, tx: &AppTx) {
self.list.set_query("");
// The turn's rows are present synchronously after `set_turn`, so this
// resolves on the first press — even when leader `a s` runs `set_turn`
// then `open_reader(0)` in the same tick.
let Some(source) = self.source_at(source_index).cloned() else {
return;
};
self.list.select(source_index);
let sel = Some(source.path.clone());
if self.preview.is_collapsed() {
self.preview.toggle(sel); // Collapsed -> Context
} else {
self.preview.repoint(sel); // keep the expand level, re-anchor here
}
self.ensure_note_load(
source.path.clone(),
source.ordinal,
source.match_heading().to_string(),
source.text.clone(),
tx,
);
}
/// Accepts a `ReaderNote` only when the panel is currently awaiting that
/// exact path (stale-drop: a source switch, or a new turn, before the load
/// lands must not clobber whatever is anchored now). Any other `AskData`
/// variant is addressed elsewhere and ignored.
pub fn handle_data(&mut self, data: AskData) {
let AskData::ReaderNote { path, text } = data else {
return;
};
if self.loaded.as_ref().map(|l| &l.path) != Some(&path) {
return;
}
// Resolve the highlight against the anchored source (prefer the one with
// the loaded ordinal; fall back to any source with this path) — read
// back from the engine's row set.
let ord = self.loaded.as_ref().map(|l| l.ordinal);
let rows = self.list.rows();
let hl_src = rows
.iter()
.map(|r| &r.source)
.find(|s| s.path == path && Some(s.ordinal) == ord)
.or_else(|| rows.iter().map(|r| &r.source).find(|s| s.path == path))
.map(|s| (s.match_heading().to_string(), s.text.clone()));
let content = match text {
Some(loaded) => {
let highlight = hl_src
.and_then(|(heading, chunk)| locate::section_range(&loaded, &heading, &chunk));
ReaderContent::Loaded {
text: loaded,
highlight,
}
}
None => ReaderContent::Failed,
};
if let Some(l) = &mut self.loaded {
l.content = content;
}
}
pub fn hint_shortcuts(&self) -> Vec<(String, String)> {
if self.list.focus() == Focus::Input {
return vec![
("Esc".into(), "list".into()),
("type".into(), "filter".into()),
];
}
if self.preview.is_collapsed() {
vec![
("j/k".into(), "Select".into()),
("Enter/l".into(), "Preview".into()),
("o/^N".into(), "Open".into()),
("y".into(), "Yank".into()),
("i".into(), "Filter".into()),
]
} else {
vec![
("j/k".into(), "Select".into()),
("Enter/l".into(), "Expand".into()),
("h/Esc".into(), "Back".into()),
("o/^N".into(), "Open".into()),
]
}
}
pub fn handle_input(&mut self, event: &InputEvent, tx: &AppTx) -> EventState {
let key = match event {
InputEvent::Key(key) => key,
// The mouse wheel scrolls the open preview's content or the list
// (converged with FIND, where the engine routes the wheel).
InputEvent::Mouse(mouse) => return self.handle_mouse(mouse, tx),
_ => return EventState::NotConsumed,
};
// Full takes over the arrow/page keys for content scroll BEFORE the
// engine sees them (mirrors FIND). `j`/`k` reach the engine so the list
// cursor stays reachable under the full preview.
if self.preview.is_full() {
match key.code {
KeyCode::Up => {
self.preview.scroll_up();
return EventState::Consumed;
}
KeyCode::Down => {
self.preview.scroll_down();
return EventState::Consumed;
}
KeyCode::PageUp => {
self.scroll_preview_page(true);
return EventState::Consumed;
}
KeyCode::PageDown => {
self.scroll_preview_page(false);
return EventState::Consumed;
}
_ => {}
}
}
// Esc ladder: in list focus with the preview revealed, Esc steps the
// reveal back (Full → Context → Collapsed) and is consumed; from a
// collapsed list the engine's `Cancel` bubbles so the drawer host
// returns focus to the thread. (In input focus, Esc first returns to
// the list — the engine handles that.)
if key.code == KeyCode::Esc
&& self.list.focus() == Focus::List
&& !self.preview.is_collapsed()
{
self.preview.collapse_step(self.selected_path());
return EventState::Consumed;
}
match self.list.handle_key(key) {
// FollowLink opens; `Ctrl+Y` yanks — the canonical chords, now via
// the engine's intercept mechanism instead of a hand-rolled
// pre-check. From any focus / reveal state.
KeyReaction::Intercepted(c) => {
if Some(c) == self.ctrl_y_combo {
self.yank_selected_path(tx);
} else {
self.open_selected(tx);
}
EventState::Consumed
}
// Enter (with no autocomplete open) cycles the reveal, like `l`.
KeyReaction::Submit => {
if self.has_sources() {
self.preview.toggle(self.selected_path());
self.ensure_loaded(tx);
}
EventState::Consumed
}
// List-focus verbs: `l`/`h` cycle the reveal, `o` opens, `y` yanks.
KeyReaction::ListVerb(c) => {
match c {
'l' => {
if self.has_sources() {
self.preview.toggle(self.selected_path());
self.ensure_loaded(tx);
}
}
'h' => self.preview.collapse_step(self.selected_path()),
'o' => self.open_selected(tx),
'y' => self.yank_selected_path(tx),
_ => {}
}
EventState::Consumed
}
// A consumed navigation / filter keystroke: re-anchor the preview on
// the new selection and refresh its note load (Context sticks across
// moves, Full collapses — see [`PreviewPane::sync`]).
KeyReaction::Consumed => {
self.sync_preview();
self.ensure_loaded(tx);
EventState::Consumed
}
// Esc from a collapsed list bubbles so the host returns focus to the
// thread.
KeyReaction::Cancel | KeyReaction::Unhandled => EventState::NotConsumed,
}
}
/// Route a mouse event through the engine (converged with FIND): the wheel
/// scrolls the open preview's content (inside its region) or the list
/// (elsewhere in the panel); a click selects a row, a second click on the
/// selected row cycles the reveal.
fn handle_mouse(&mut self, mouse: &MouseEvent, tx: &AppTx) -> EventState {
let was_full = self.preview.is_full();
self.sync_preview();
// In Full the list is not rendered (its recorded rect is stale), so only
// the wheel may reach the engine; a click on the header collapses the
// reveal, anything else is swallowed.
if was_full {
match mouse.kind {
MouseEventKind::ScrollUp | MouseEventKind::ScrollDown => {}
MouseEventKind::Down(MouseButton::Left)
if self.preview.full_header_rect().contains(Position {
x: mouse.column,
y: mouse.row,
}) =>
{
self.preview.toggle(self.selected_path());
return EventState::Consumed;
}
_ => return EventState::Consumed,
}
}
match self.list.handle_mouse(mouse) {
SearchMouse::ContentScrollUp => {
self.preview.scroll_up();
EventState::Consumed
}
SearchMouse::ContentScrollDown => {
self.preview.scroll_down();
EventState::Consumed
}
SearchMouse::Activated(_) => {
self.preview.toggle(self.selected_path());
self.ensure_loaded(tx);
EventState::Consumed
}
SearchMouse::Selected(_) | SearchMouse::Scrolled | SearchMouse::Context(_) => {
self.sync_preview();
self.ensure_loaded(tx);
EventState::Consumed
}
SearchMouse::None => EventState::NotConsumed,
}
}
/// Scroll the Full preview by a page (last render's content viewport, less
/// a small overlap), `up` toward the top. Single-tick scrolls under the
/// hood so the anchor-takeover/clamp rules hold.
fn scroll_preview_page(&mut self, up: bool) {
let page = self.preview_page.saturating_sub(PAGE_OVERLAP).max(1);
for _ in 0..page {
if up {
self.preview.scroll_up();
} else {
self.preview.scroll_down();
}
}
}
/// The selected source (read from the engine's selected row, so it is
/// correct even under an active filter).
fn selected_source(&self) -> Option<&AskSource> {
self.list.selected_row().map(|r| &r.source)
}
/// The selected source's path, for preview anchoring and open/yank.
fn selected_path(&self) -> Option<VaultPath> {
self.selected_source().map(|s| s.path.clone())
}
/// Re-anchor the preview onto the current selection (Context sticks across
/// moves, Full collapses — see [`PreviewPane::sync`]).
fn sync_preview(&mut self) {
let sel = self.selected_path();
self.preview.sync(sel);
}
/// Ensure the preview is backed by the *selected* source's note (the
/// interactive path — `open_reader` calls [`ensure_note_load`] directly with
/// its directed source). No-op while collapsed or with nothing selected.
fn ensure_loaded(&mut self, tx: &AppTx) {
if self.preview.is_collapsed() {
return;
}
let Some(source) = self.selected_source() else {
return;
};
let path = source.path.clone();
let ordinal = source.ordinal;
let heading = source.match_heading().to_string();
let chunk = source.text.clone();
self.ensure_note_load(path, ordinal, heading, chunk, tx);
}
/// Ensure the preview is backed by the given source's note. Three cases,
/// keyed on the source identity (`path` + `ordinal`), not `path` alone:
///
/// - **Same source** (same path and ordinal): nothing to do.
/// - **Same note, different section** (same path, new ordinal): reuse the
/// already-loaded text, re-resolve the highlight against the new heading,
/// and re-anchor — no vault refetch.
/// - **Different note**: spawn the load, re-keying `loaded` so an earlier
/// path's late `ReaderNote` is dropped on arrival.
fn ensure_note_load(
&mut self,
path: VaultPath,
ordinal: usize,
heading: String,
chunk: String,
tx: &AppTx,
) {
match &self.loaded {
Some(l) if l.path == path && l.ordinal == ordinal => return,
Some(l) if l.path == path => {
// Same note, new section: re-resolve the highlight in place and
// re-anchor the preview, without a fresh vault load.
if let Some(l) = &mut self.loaded {
l.ordinal = ordinal;
if let ReaderContent::Loaded { text, highlight } = &mut l.content {
*highlight = locate::section_range(text, &heading, &chunk);
}
}
self.preview.re_anchor();
return;
}
_ => {}
}
self.loaded = Some(LoadedNote {
path: path.clone(),
ordinal,
content: ReaderContent::Loading,
});
let vault = self.vault.clone();
let tx = tx.clone();
tokio::spawn(async move {
let text = vault.get_note_text(&path).await.ok();
let _ = tx.send(AppEvent::Ask(AskData::ReaderNote { path, text }));
});
}
/// Open the selected source's note in the editor (plain `o`, or the
/// FollowLink intercept) — from any reveal state.
fn open_selected(&self, tx: &AppTx) {
if let Some(source) = self.selected_source() {
tx.send(AppEvent::open(source.path.clone())).ok();
}
}
/// Copy the selected source's path to the OS clipboard, reusing the
/// shared [`crate::components::yank`] seam `ThreadPanel` and the FIND
/// drawer use.
fn yank_selected_path(&self, tx: &AppTx) {
let Some(source) = self.selected_source() else {
return;
};
crate::components::yank(source.path.to_string(), "path copied", tx);
}
pub fn render(&mut self, f: &mut Frame, rect: Rect, theme: &Theme, focused: bool) {
self.list.poll();
// Keep the preview anchored to the selection every frame (Context sticks
// across moves; Full collapses on a change) before laying anything out.
self.sync_preview();
// The whole panel is wheel-scrollable; the content sub-region is
// re-recorded (or cleared) by the branch that draws a preview.
self.list.set_panel_rect(rect);
self.list.set_content_rect(Rect::default());
self.preview.clear_header();
let block = panel_block("Sources", theme, focused);
let inner = block.inner(rect);
f.render_widget(block, rect);
// No sources at all for this turn: the prompt. The row set is applied
// synchronously on rebuild, so there is no in-flight load to wait on —
// an empty list here means the turn genuinely has no sources.
if self.list.rows().is_empty() {
let style = Style::default().fg(theme.gray.to_ratatui());
f.render_widget(
Paragraph::new("no sources — ask something").style(style),
inner,
);
return;
}
// A bordered filter box on top, converged with FIND's query searchbox
// (query_panel.rs): same `Length(3)` box chrome, same `render_query`
// call. Always visible — like FIND — rather than only once the user
// has left list focus, so the `/` filter affordance always reads.
// `render_query` itself dims the field and hides the cursor outside
// Input sub-focus (the List-focus work), so no extra styling is
// needed here beyond the shared border-focus style.
let rows = Layout::default()
.direction(Direction::Vertical)
.constraints([Constraint::Length(3), Constraint::Min(0)])
.split(inner);
let filter_block = Block::default()
.title(" filter ")
.borders(Borders::ALL)
.border_style(theme.border_style(focused))
.style(theme.panel_style());
let filter_inner = filter_block.inner(rows[0]);
f.render_widget(filter_block, rows[0]);
self.list.render_query(f, filter_inner, theme, focused);
let body = rows[1];
// A zero-match filter: mirror FIND's "No results" (query_panel.rs) so a
// narrowed-to-nothing filter reads as a result, not a silent blank.
if self.list.visible_rows().is_empty() {
let gray = theme.gray.to_ratatui();
let bg = theme.bg_panel.to_ratatui();
f.render_widget(
Paragraph::new(" No results").style(Style::default().fg(gray).bg(bg)),
body,
);
return;
}
// Full: the preview takes the whole body, no list visible. The wheel
// scrolls the content from anywhere in the panel.
if self.preview.is_full() {
self.list.set_content_rect(rect);
self.render_preview(f, body, true, theme);
return;
}
// Context: list on top, half-height preview below, divider between.
if self.preview.is_context() {
let max_list = body.height / 2;
// Rows are two lines each; cap the list at half the panel but shrink
// for a short (or filtered) list so the preview gets the rest. Use
// the VISIBLE (filtered) count, like FIND (query_panel.rs), so a
// narrowing filter shrinks the list pane.
let visible = self.list.visible_rows().len();
let list_height = (visible as u16 * 2).min(max_list).max(1);
let areas = Layout::default()
.direction(Direction::Vertical)
.constraints([
Constraint::Length(list_height),
Constraint::Length(1),
Constraint::Min(0),
])
.split(body);
self.list.render(f, areas[0], theme, focused);
self.list.set_list_rect(areas[0]);
let gray = theme.gray.to_ratatui();
let bg = theme.bg_panel.to_ratatui();
f.render_widget(
Paragraph::new("\u{2500}".repeat(areas[1].width as usize))
.style(Style::default().fg(gray).bg(bg)),
areas[1],
);
self.render_preview(f, areas[2], false, theme);
self.list.set_content_rect(areas[2]);
return;
}
// Collapsed: list only.
self.list.render(f, body, theme, focused);
self.list.set_list_rect(body);
}
/// Feed the anchored source's loaded note into the preview surface (Context
/// or Full), or show the load's placeholder.
fn render_preview(&mut self, f: &mut Frame, area: Rect, full: bool, theme: &Theme) {
// Record the content viewport for page scrolling: Full spends two rows
// on the fixed title + divider chrome; Context uses the whole area.
self.preview_page = area.height.saturating_sub(if full { 2 } else { 0 });
let title_fn = self
.list
.selected_row()
.map(|r| (r.source.display_heading(), r.source.path.to_string()));
let Self {
loaded, preview, ..
} = self;
match loaded {
Some(LoadedNote {
content: ReaderContent::Loaded { text, highlight },
..
}) => {
if full {
let (title, filename) =
title_fn.unwrap_or_else(|| ("Source".to_string(), String::new()));
preview.render_full(
f,
area,
&title,
&filename,
text,
Highlight::Range(highlight.as_ref()),
theme,
);
} else {
preview.render_context(
f,
area,
text,
Highlight::Range(highlight.as_ref()),
theme,
);
}
}
Some(LoadedNote {
content: ReaderContent::Failed,
..
}) => {
let red = Style::default().fg(theme.red.to_ratatui());
f.render_widget(Paragraph::new("failed to load note").style(red), area);
}
None
| Some(LoadedNote {
content: ReaderContent::Loading,
..
}) => {
let dim = Style::default().fg(theme.gray.to_ratatui());
f.render_widget(Paragraph::new("loading\u{2026}").style(dim), area);
}
}
}
#[cfg(test)]
pub(crate) async fn settle(&mut self) {
// The static list is applied synchronously at build, so it is already
// idle; this is a no-op kept so tests read the same as the FIND drawer.
self.list.poll_until_idle().await;
}
#[cfg(test)]
pub(crate) fn match_count(&self) -> usize {
self.list.match_count()
}
}
/// (Re)build a [`SearchList`] over the given per-turn rows, wired the same way
/// on every turn: fuzzy local filter, opening on the list, the `l`/`h`/`o`/`y`
/// verbs, and the FollowLink / `Ctrl+Y` intercepts. The rows are applied
/// synchronously (`build_with_rows` over a [`StaticRowSource`]), so they are
/// live the instant this returns; `redraw` is threaded to the engine but never
/// fired on this path.
fn build_list(
rows: Vec<SourceRow>,
intercept: &[KeyCombo],
icons: &Icons,
redraw: Arc<dyn Fn() + Send + Sync>,
) -> SearchList<SourceRow> {
SearchList::builder(StaticRowSource, redraw)
.icons(icons.clone())
.filter(Filter::Fuzzy)
.opening_focus(Focus::List)
.intercept(intercept.to_vec())
.list_verb('l')
.list_verb('h')
.list_verb('o')
.list_verb('y')
.build_with_rows(rows)
}
/// The similarity as a whole-percent integer (`score` is the server's
/// normalized `0.0..=1.0` similarity — clamped defensively).
fn score_percent(score: f64) -> u32 {
(score.clamp(0.0, 1.0) * 100.0).round() as u32
}
/// Build the shared [`RichRow`] for a source: the 1-based `rank` as the leading
/// glyph, the journal date and heading kept as distinct spaced elements (never
/// the wire's glued `2026-04-08Afternoon`), the score percentage as dim meta,
/// and the path on the dim filename line.
fn source_row(rank: usize, source: &AskSource, theme: &Theme) -> RichRow {
let bold = Style::default()
.fg(theme.fg_bright.to_ratatui())
.add_modifier(Modifier::BOLD);
let date_style = Style::default().fg(theme.color_journal_date.to_ratatui());
let rank_style = Style::default()
.fg(theme.accent.to_ratatui())
.add_modifier(Modifier::BOLD);
let pct = format!("{}%", score_percent(source.score));
let mut row = if source.heading.is_empty() {
// A bare-date chunk (empty heading) shows just the date as its title,
// in the date color, so there is no dangling separator.
match &source.date {
Some(date) => RichRow::new(rank.to_string(), date.clone()).title_style(date_style),
None => RichRow::new(rank.to_string(), String::new()).title_style(bold),
}
} else {
let mut r = RichRow::new(rank.to_string(), source.heading.clone()).title_style(bold);
if let Some(date) = &source.date {
r = r.date(date.clone(), Some(date_style));
}
r
};
row = row.glyph_style(rank_style).meta(pct);
row.filename(source.path.to_string())
}
#[cfg(test)]
mod tests {
use super::*;
use kimun_core::VaultConfig;
use ratatui::Terminal;
use ratatui::backend::TestBackend;
use tempfile::TempDir;
fn source(path: &str, heading: &str, score: f64, text: &str) -> AskSource {
AskSource {
path: VaultPath::new(path),
heading: heading.to_string(),
date: None,
score,
text: text.to_string(),
ordinal: 0,
}
}
fn dated_source(path: &str, heading: &str, date: &str, score: f64) -> AskSource {
AskSource {
path: VaultPath::new(path),
heading: heading.to_string(),
date: Some(date.to_string()),
score,
text: String::new(),
ordinal: 0,
}
}
async fn test_vault() -> (TempDir, NoteVault) {
let dir = TempDir::new().unwrap();
let vault = NoteVault::new(VaultConfig::new(dir.path())).await.unwrap();
(dir, vault)
}
fn key_bindings() -> KeyBindings {
crate::settings::AppSettings::default().key_bindings.clone()
}
/// A throwaway sender for `set_turn`/`refresh` in tests that do not inspect
/// the engine's redraw wake (its receiver is dropped, so the redraw send is
/// a harmless no-op). Tests that assert on the Redraw event use a live
/// channel instead.
fn noop_tx() -> AppTx {
tokio::sync::mpsc::unbounded_channel().0
}
/// A panel over a throwaway vault, for tests that never touch the note load.
/// The backing dir is leaked so the vault stays valid for the test's
/// lifetime.
async fn test_panel() -> SourcesPanel {
let (dir, vault) = test_vault().await;
std::mem::forget(dir);
SourcesPanel::new(Arc::new(vault), &key_bindings())
}
fn key(code: KeyCode) -> KeyEvent {
KeyEvent::new(code, KeyModifiers::NONE)
}
fn ctrl(code: KeyCode) -> KeyEvent {
KeyEvent::new(code, KeyModifiers::CONTROL)
}
/// Populate `p` with two sources and drain the engine's initial load so the
/// rows (and the seeded selection) are live.
async fn two_source_panel(p: &mut SourcesPanel) {
p.set_turn(
1,
vec![
source("a.md", "A", 0.9, "alpha body"),
source("b.md", "B", 0.5, "beta body"),
],
&noop_tx(),
);
p.settle().await;
}
/// Move the list selection to visible index `i` by driving the engine.
async fn select_index(p: &mut SourcesPanel, i: usize) {
let (tx, _rx) = tokio::sync::mpsc::unbounded_channel();
for _ in 0..i {
p.handle_input(&InputEvent::Key(key(KeyCode::Char('j'))), &tx);
}
}
fn selected_heading(p: &SourcesPanel) -> Option<String> {
p.selected_source().map(|s| s.heading.clone())
}
/// Heading of the source at rank position `i` (0-based) in the engine's row
/// set — the panel keeps no parallel sources copy.
fn nth_heading(p: &SourcesPanel, i: usize) -> Option<String> {
p.source_at(i).map(|s| s.heading.clone())
}
#[test]
fn score_percent_rounds_and_clamps() {
assert_eq!(score_percent(0.874), 87);
assert_eq!(score_percent(1.5), 100);
assert_eq!(score_percent(-0.2), 0);
}
#[test]
fn dated_source_display_heading_separates_date_and_heading() {
let s = dated_source("journal/2026-04-08.md", "Afternoon", "2026-04-08", 0.9);
assert_eq!(s.display_heading(), "2026-04-08 \u{b7} Afternoon");
assert_eq!(source("n.md", "Ideas", 0.5, "").display_heading(), "Ideas");
}
#[tokio::test]
async fn new_panel_starts_empty_and_collapsed() {
let p = test_panel().await;
assert_eq!(p.match_count(), 0);
assert!(p.preview.is_collapsed());
}
#[tokio::test]
async fn set_turn_populates_and_collapses() {
let mut p = test_panel().await;
p.set_turn(1, vec![source("a.md", "A", 0.9, "text a")], &noop_tx());
p.settle().await;
assert_eq!(p.turn_id, Some(1));
assert_eq!(p.match_count(), 1, "the engine mirrors the turn's rows");
assert!(p.preview.is_collapsed());
}
#[tokio::test]
async fn set_turn_same_id_is_a_noop_and_keeps_selection() {
let mut p = test_panel().await;
two_source_panel(&mut p).await;
select_index(&mut p, 1).await;
assert_eq!(selected_heading(&p).as_deref(), Some("B"));
p.set_turn(1, vec![source("c.md", "C", 0.1, "text c")], &noop_tx());
p.settle().await;
assert_eq!(
selected_heading(&p).as_deref(),
Some("B"),
"selection must survive a same-id set_turn"
);
assert_eq!(p.match_count(), 2, "rows must not be replaced");
assert_eq!(nth_heading(&p, 0).as_deref(), Some("A"));
}
#[tokio::test]
async fn set_turn_new_id_resets_selection_and_collapses() {
let mut p = test_panel().await;
two_source_panel(&mut p).await;
select_index(&mut p, 1).await;
p.preview.toggle(Some(VaultPath::new("a.md")));
p.set_turn(2, vec![source("c.md", "C", 0.1, "text c")], &noop_tx());
p.settle().await;
assert_eq!(selected_heading(&p).as_deref(), Some("C"));
assert_eq!(p.match_count(), 1);
assert!(p.preview.is_collapsed());
}
#[tokio::test]
async fn focus_source_points_selection_by_ordinal_through_the_engine() {
let mut p = test_panel().await;
let mut a = source("a.md", "A", 0.9, "a");
a.ordinal = 3;
let mut b = source("b.md", "B", 0.5, "b");
b.ordinal = 7;
p.set_turn(1, vec![a, b], &noop_tx());
p.settle().await;
p.preview.toggle(Some(VaultPath::new("a.md")));
p.focus_source(7);
assert_eq!(
p.selected_source().map(|s| s.ordinal),
Some(7),
"resolved ordinal 7 to its row through the engine, not ordinal-1"
);
assert_eq!(selected_heading(&p).as_deref(), Some("B"));
assert!(p.preview.is_collapsed());
// An unknown ordinal is ignored.
p.focus_source(99);
assert_eq!(p.selected_source().map(|s| s.ordinal), Some(7));
}
/// `refresh` (the answer-completion path) applies the turn's rows
/// synchronously — they are present the instant it returns, with ZERO prior
/// interaction and no `poll`/`settle`. There is no async row load to wait
/// on, so the drawer paints the freshly-ranked sources on the next frame
/// without needing a Redraw wake.
#[tokio::test]
async fn refresh_applies_rows_synchronously_no_redraw_needed() {
let mut p = test_panel().await;
let (tx, mut rx) = tokio::sync::mpsc::unbounded_channel();
p.refresh(1, vec![source("a.md", "A", 0.9, "alpha body")], &tx);
// No poll, no settle: the rows are live now.
assert_eq!(
p.match_count(),
1,
"refresh's rows are applied synchronously"
);
assert!(!p.list.is_loading(), "no async load is in flight");
assert_eq!(nth_heading(&p, 0).as_deref(), Some("A"));
// The synchronous path never fires the engine's redraw callback — the
// render loop repaints on its own; no Redraw event is required.
let mut redraws = 0;
while let Ok(ev) = rx.try_recv() {
if matches!(ev, AppEvent::Redraw) {
redraws += 1;
}
}
assert_eq!(redraws, 0, "no Redraw wake is needed for the sync row set");
}
/// A cross-turn citation click runs `set_turn` (rebuild) then `focus_source`
/// in the SAME tick. Because the rows are applied synchronously, the ordinal
/// jump lands immediately — no deferral, no `settle` needed.
#[tokio::test]
async fn cross_turn_focus_source_applies_immediately() {
let mut p = test_panel().await;
let (tx, _rx) = tokio::sync::mpsc::unbounded_channel();
let mut a = source("a.md", "A", 0.9, "a");
a.ordinal = 3;
let mut b = source("b.md", "B", 0.5, "b");
b.ordinal = 7;
// New turn + citation focus in the same tick: rows are present now.
p.set_turn(2, vec![a, b], &tx);
p.focus_source(7);
assert_eq!(
p.selected_source().map(|s| s.ordinal),
Some(7),
"citation focus applied in the same tick as set_turn"
);
assert_eq!(selected_heading(&p).as_deref(), Some("B"));
}
/// Leader `a s` shape: `set_turn(new id)` then `open_reader(0)` in the SAME
/// tick. The rows are synchronous, so the preview opens on the requested
/// source on the FIRST press (the pre-fix bug needed two presses because the
/// rows had not landed when `open_reader` read `source_at(0)`).
#[tokio::test]
async fn set_turn_then_open_reader_same_tick_opens_first_press() {
let (_dir, vault) = test_vault().await;
vault
.create_note(&VaultPath::new("a.md"), "# ha\nalpha text\n")
.await
.unwrap();
let mut p = SourcesPanel::new(Arc::new(vault), &key_bindings());
let (tx, _rx) = tokio::sync::mpsc::unbounded_channel();
// Fresh turn + open the top source in the same tick — no settle between.
p.set_turn(9, vec![source("a.md", "ha", 0.9, "alpha text")], &tx);
p.open_reader(0, &tx);
assert!(
p.preview.is_context(),
"open_reader opens the preview on the first press"
);
assert_eq!(
selected_heading(&p).as_deref(),
Some("ha"),
"the requested source is selected"
);
assert_eq!(
p.loaded.as_ref().map(|l| l.path.clone()),
Some(VaultPath::new("a.md")),
"the note load is anchored to the opened source"
);
}
// ── New filter input (in-memory, heading/path text) ───────────────────
#[tokio::test]
async fn filter_input_narrows_sources_by_heading_or_path_text() {
let mut p = test_panel().await;
p.set_turn(
1,
vec![
source("alpha.md", "Alpha section", 0.9, "a"),
source("beta.md", "Beta section", 0.5, "b"),
source("gamma.md", "Gamma section", 0.3, "g"),
],
&noop_tx(),
);
p.settle().await;
assert_eq!(p.match_count(), 3, "no filter shows every source");
let (tx, _rx) = tokio::sync::mpsc::unbounded_channel();
// `i` reveals the filter input; typing filters by heading text.
assert_eq!(p.list.focus(), Focus::List);
p.handle_input(&InputEvent::Key(key(KeyCode::Char('i'))), &tx);
assert_eq!(p.list.focus(), Focus::Input, "`i` reveals the filter input");
for c in ['B', 'e', 't', 'a'] {
p.handle_input(&InputEvent::Key(key(KeyCode::Char(c))), &tx);
}
p.settle().await;
assert_eq!(p.match_count(), 1, "typed filter narrows to the match");
assert_eq!(selected_heading(&p).as_deref(), Some("Beta section"));
}
#[tokio::test]
async fn slash_also_reveals_the_filter_and_matches_path_text() {
let mut p = test_panel().await;
p.set_turn(
1,
vec![
source("notes/alpha.md", "One", 0.9, "a"),
source("journal/beta.md", "Two", 0.5, "b"),
],
&noop_tx(),
);
p.settle().await;
let (tx, _rx) = tokio::sync::mpsc::unbounded_channel();
p.handle_input(&InputEvent::Key(key(KeyCode::Char('/'))), &tx);
assert_eq!(p.list.focus(), Focus::Input, "`/` reveals the filter input");
for c in ['j', 'o', 'u', 'r'] {
p.handle_input(&InputEvent::Key(key(KeyCode::Char(c))), &tx);
}
p.settle().await;
assert_eq!(p.match_count(), 1, "path text filters too");
assert_eq!(selected_heading(&p).as_deref(), Some("Two"));
}
// ── Reveal cycle (Enter / l / h) ──────────────────────────────────────
#[tokio::test]
async fn enter_and_l_cycle_forward_h_cycles_back() {
let mut p = test_panel().await;
two_source_panel(&mut p).await;
let (tx, _rx) = tokio::sync::mpsc::unbounded_channel();
assert!(p.preview.is_collapsed());
p.handle_input(&InputEvent::Key(key(KeyCode::Enter)), &tx);
assert!(p.preview.is_context(), "Enter: Collapsed -> Context");
p.handle_input(&InputEvent::Key(key(KeyCode::Char('l'))), &tx);
assert!(p.preview.is_full(), "l: Context -> Full");
p.handle_input(&InputEvent::Key(key(KeyCode::Char('l'))), &tx);
assert!(p.preview.is_collapsed(), "l: Full -> Collapsed (wraps)");
// Back cycle with h stops at Collapsed.
p.handle_input(&InputEvent::Key(key(KeyCode::Char('l'))), &tx); // -> Context
p.handle_input(&InputEvent::Key(key(KeyCode::Char('l'))), &tx); // -> Full
assert!(p.preview.is_full());
p.handle_input(&InputEvent::Key(key(KeyCode::Char('h'))), &tx);
assert!(p.preview.is_context(), "h: Full -> Context");
p.handle_input(&InputEvent::Key(key(KeyCode::Char('h'))), &tx);
assert!(p.preview.is_collapsed(), "h: Context -> Collapsed");
p.handle_input(&InputEvent::Key(key(KeyCode::Char('h'))), &tx);
assert!(p.preview.is_collapsed(), "h at Collapsed stays Collapsed");
}
#[tokio::test]
async fn esc_steps_back_then_bubbles_to_thread() {
let mut p = test_panel().await;
two_source_panel(&mut p).await;
let (tx, _rx) = tokio::sync::mpsc::unbounded_channel();
p.preview.toggle(Some(VaultPath::new("a.md"))); // Context
let st = p.handle_input(&InputEvent::Key(key(KeyCode::Esc)), &tx);
assert_eq!(st, EventState::Consumed);
assert!(p.preview.is_collapsed(), "Esc steps back one reveal state");
// From Collapsed (list focus), Esc bubbles so the host returns focus to
// the thread.
let st = p.handle_input(&InputEvent::Key(key(KeyCode::Esc)), &tx);
assert_eq!(
st,
EventState::NotConsumed,
"Collapsed Esc -> back to thread"
);
}
#[tokio::test]
async fn jk_moves_selection_within_bounds() {
let mut p = test_panel().await;
two_source_panel(&mut p).await;
let (tx, _rx) = tokio::sync::mpsc::unbounded_channel();
p.handle_input(&InputEvent::Key(key(KeyCode::Char('j'))), &tx);
assert_eq!(selected_heading(&p).as_deref(), Some("B"));
p.handle_input(&InputEvent::Key(key(KeyCode::Char('j'))), &tx);
assert_eq!(
selected_heading(&p).as_deref(),
Some("B"),
"clamped at the last row"
);
p.handle_input(&InputEvent::Key(key(KeyCode::Char('k'))), &tx);
assert_eq!(selected_heading(&p).as_deref(), Some("A"));
p.handle_input(&InputEvent::Key(key(KeyCode::Char('k'))), &tx);
assert_eq!(
selected_heading(&p).as_deref(),
Some("A"),
"clamped at the first row"
);
}
// ── Open (o / FollowLink) — from any reveal state ─────────────────────
async fn assert_opens_selected(setup: impl Fn(&mut SourcesPanel), open: KeyEvent) {
let mut p = test_panel().await;
two_source_panel(&mut p).await;
select_index(&mut p, 1).await;
setup(&mut p);
let (tx, mut rx) = tokio::sync::mpsc::unbounded_channel();
let st = p.handle_input(&InputEvent::Key(open), &tx);
assert_eq!(st, EventState::Consumed);
let mut opened = None;
while let Ok(ev) = rx.try_recv() {
if let AppEvent::OpenPath { path, .. } = ev {
opened = Some(path);
}
}
assert_eq!(
opened,
Some(VaultPath::new("b.md")),
"opened the selected source"
);
}
#[tokio::test]
async fn o_opens_selected_from_every_reveal_state() {
// Collapsed, Context, Full — `o` opens the selected source each time.
assert_opens_selected(|_p| {}, key(KeyCode::Char('o'))).await;
assert_opens_selected(
|p| p.preview.toggle(Some(VaultPath::new("b.md"))),
key(KeyCode::Char('o')),
)
.await;
assert_opens_selected(
|p| {
p.preview.toggle(Some(VaultPath::new("b.md")));
p.preview.toggle(Some(VaultPath::new("b.md")));
},
key(KeyCode::Char('o')),
)
.await;
}
#[tokio::test]
async fn followlink_ctrl_n_opens_selected() {
assert_opens_selected(|_p| {}, ctrl(KeyCode::Char('n'))).await;
// Also from Full.
assert_opens_selected(
|p| {
p.preview.toggle(Some(VaultPath::new("b.md")));
p.preview.toggle(Some(VaultPath::new("b.md")));
},
ctrl(KeyCode::Char('n')),
)
.await;
}
// ── Yank (y / Ctrl+Y) ─────────────────────────────────────────────────
async fn assert_yanks(k: KeyEvent) {
let mut p = test_panel().await;
two_source_panel(&mut p).await;
let (tx, mut rx) = tokio::sync::mpsc::unbounded_channel();
let st = p.handle_input(&InputEvent::Key(k), &tx);
assert_eq!(st, EventState::Consumed);
let mut flashed = false;
while let Ok(ev) = rx.try_recv() {
if matches!(ev, AppEvent::FlashMessage(_)) {
flashed = true;
}
}
assert!(
flashed,
"yank emits a flash message (ok or clipboard error)"
);
}
#[tokio::test]
async fn plain_y_and_ctrl_y_both_yank() {
assert_yanks(key(KeyCode::Char('y'))).await;
assert_yanks(ctrl(KeyCode::Char('y'))).await;
}
// ── Async note load + stale-drop ──────────────────────────────────────
#[tokio::test]
async fn reader_note_for_the_wrong_path_is_dropped() {
let mut p = test_panel().await;
p.set_turn(1, vec![source("a.md", "A", 0.9, "alpha body")], &noop_tx());
p.loaded = Some(LoadedNote {
path: VaultPath::new("a.md"),
ordinal: 0,
content: ReaderContent::Loading,
});
p.handle_data(AskData::ReaderNote {
path: VaultPath::new("other.md"),
text: Some("nope".to_string()),
});
assert!(
matches!(p.loaded.as_ref().unwrap().content, ReaderContent::Loading),
"wrong-path ReaderNote must be dropped, not accepted"
);
}
#[tokio::test]
async fn reader_note_for_the_right_path_loads_and_highlights() {
let mut p = test_panel().await;
p.set_turn(1, vec![source("a.md", "b", 0.9, "beta body")], &noop_tx());
p.settle().await;
p.loaded = Some(LoadedNote {
path: VaultPath::new("a.md"),
ordinal: 0,
content: ReaderContent::Loading,
});
p.handle_data(AskData::ReaderNote {
path: VaultPath::new("a.md"),
text: Some("# a\nalpha body\n# b\nbeta body\n".to_string()),
});
match &p.loaded.as_ref().unwrap().content {
ReaderContent::Loaded { text, highlight } => {
let r = highlight.clone().expect("chunk resolves");
assert_eq!(&text[r], "beta body");
}
_ => panic!("expected Loaded"),
}
}
#[tokio::test]
async fn reader_note_load_failure_is_recorded() {
let mut p = test_panel().await;
p.set_turn(1, vec![source("a.md", "A", 0.9, "alpha body")], &noop_tx());
p.loaded = Some(LoadedNote {
path: VaultPath::new("a.md"),
ordinal: 0,
content: ReaderContent::Loading,
});
p.handle_data(AskData::ReaderNote {
path: VaultPath::new("a.md"),
text: None,
});
assert!(matches!(
p.loaded.as_ref().unwrap().content,
ReaderContent::Failed
));
}
#[tokio::test]
async fn handle_data_ignores_answer_ready() {
let mut p = test_panel().await;
p.set_turn(1, vec![source("a.md", "A", 0.9, "alpha body")], &noop_tx());
p.loaded = Some(LoadedNote {
path: VaultPath::new("a.md"),
ordinal: 0,
content: ReaderContent::Loading,
});
p.handle_data(AskData::AnswerReady {
turn_id: 1,
result: Ok(("x".into(), vec![])),
});
assert!(matches!(
p.loaded.as_ref().unwrap().content,
ReaderContent::Loading
));
}
#[tokio::test]
async fn open_reader_opens_preview_and_round_trips_a_real_vault() {
let (_dir, vault) = test_vault().await;
let path = VaultPath::new("note.md");
vault.create_note(&path, "# h\nbody text\n").await.unwrap();
let mut p = SourcesPanel::new(Arc::new(vault), &key_bindings());
p.set_turn(
1,
vec![source("note.md", "h", 0.9, "body text")],
&noop_tx(),
);
p.settle().await;
let (tx, mut rx) = tokio::sync::mpsc::unbounded_channel();
p.open_reader(0, &tx);
assert!(
p.preview.is_context(),
"open_reader opens the Context preview"
);
let event = rx.recv().await.expect("open_reader spawns a ReaderNote");
let AppEvent::Ask(data) = event else {
panic!("expected an Ask event");
};
p.handle_data(data);
match &p.loaded.as_ref().unwrap().content {
ReaderContent::Loaded { text, .. } => assert_eq!(text, "# h\nbody text\n"),
_ => panic!("expected Loaded"),
}
}
#[tokio::test]
async fn navigating_in_context_reloads_for_the_new_source() {
let (_dir, vault) = test_vault().await;
std::mem::forget(_dir);
let mut p = SourcesPanel::new(Arc::new(vault), &key_bindings());
two_source_panel(&mut p).await;
let (tx, _rx) = tokio::sync::mpsc::unbounded_channel();
p.preview.toggle(Some(VaultPath::new("a.md"))); // Context
p.ensure_loaded(&tx);
assert_eq!(p.loaded.as_ref().unwrap().path, VaultPath::new("a.md"));
// Move down while the preview is open: the load re-keys to b.md, so a
// late a.md ReaderNote would now be dropped.
p.handle_input(&InputEvent::Key(key(KeyCode::Char('j'))), &tx);
assert_eq!(p.loaded.as_ref().unwrap().path, VaultPath::new("b.md"));
}
// ── Rendering ─────────────────────────────────────────────────────────
fn buffer_text(p: &mut SourcesPanel, w: u16, h: u16) -> String {
let theme = Theme::default();
let mut term = Terminal::new(TestBackend::new(w, h)).unwrap();
term.draw(|f| {
let area = f.area();
p.render(f, area, &theme, true);
})
.unwrap();
let buf = term.backend().buffer().clone();
(0..buf.area.height)
.map(|y| {
(0..buf.area.width)
.map(|x| buf[(x, y)].symbol())
.collect::<String>()
})
.collect::<Vec<_>>()
.join("\n")
}
#[tokio::test]
async fn row_render_carries_rank_and_score() {
let mut p = test_panel().await;
p.set_turn(
1,
vec![
dated_source("journal/2026-04-08.md", "Afternoon", "2026-04-08", 0.9),
source("b.md", "Beta section", 0.42, "beta body"),
],
&noop_tx(),
);
p.settle().await;
// Height grown to fit the always-visible filter box (Length(3)) above
// the list plus both two-line rows.
let text = buffer_text(&mut p, 60, 11);
assert!(text.contains("1 "), "rank 1 leads the first row: {text}");
assert!(text.contains("2 "), "rank 2 leads the second row: {text}");
assert!(text.contains("90%"), "score percent shown: {text}");
assert!(text.contains("42%"), "second score shown: {text}");
assert!(text.contains("2026-04-08"), "date kept: {text}");
assert!(
text.contains('\u{b7}'),
"date \u{b7} heading separation: {text}"
);
assert!(text.contains("Afternoon"), "heading kept: {text}");
}
/// Converged with FIND (query_panel.rs): the filter field is a bordered
/// box titled "filter", always visible — even before the user leaves list
/// focus for the input — not a bare text line that only appears once `/`
/// or `i` is pressed.
#[tokio::test]
async fn filter_box_is_bordered_and_always_visible() {
let mut p = test_panel().await;
p.set_turn(
1,
vec![source("a.md", "Alpha", 0.9, "alpha body")],
&noop_tx(),
);
p.settle().await;
// Sources opens on the list (CONTEXT.md "List focus"), but the filter
// box must already be on screen — the pre-convergence behavior only
// rendered it once focus moved to Input.
assert_eq!(p.list.focus(), Focus::List, "Sources opens on the list");
let text = buffer_text(&mut p, 40, 10);
assert!(
text.contains("filter"),
"filter box shows in list focus, before `/`/`i`: {text}"
);
assert!(
text.contains('\u{250c}') || text.contains('\u{2500}'),
"filter field is boxed (bordered), not a bare line: {text}"
);
// Same boxed chrome once the user reveals the input — no layout
// change, just the (already-existing) focused/unfocused input style.
p.handle_input(&InputEvent::Key(key(KeyCode::Char('/'))), &noop_tx());
assert_eq!(p.list.focus(), Focus::Input);
let text = buffer_text(&mut p, 40, 10);
assert!(
text.contains("filter"),
"filter box stays visible in input focus: {text}"
);
}
/// F3: a filter that matches nothing must render FIND's "No results"
/// message, not a silent blank — the row set is non-empty, only the visible
/// (filtered) set is empty.
#[tokio::test]
async fn zero_match_filter_shows_no_results() {
let mut p = test_panel().await;
p.set_turn(1, vec![source("a.md", "Alpha", 0.9, "body")], &noop_tx());
p.settle().await;
p.list.set_query("zzznomatch");
assert_eq!(p.list.visible_rows().len(), 0, "filter narrows to nothing");
let text = buffer_text(&mut p, 40, 10);
assert!(
text.contains("No results"),
"zero-match filter shows the No results message: {text}"
);
}
/// F2: the Context list pane is sized by the VISIBLE (filtered) count, so a
/// narrowing filter shrinks the list and the preview gets the reclaimed
/// space (more of the note is shown).
#[tokio::test]
async fn context_list_pane_shrinks_when_filter_narrows() {
let mut p = test_panel().await;
let srcs: Vec<_> = (0..10)
.map(|i| source(&format!("n{i}.md"), &format!("Alpha{i}"), 0.9, "body"))
.collect();
p.set_turn(1, srcs, &noop_tx());
p.settle().await;
// Open Context on the first source with a long note and NO highlight, so
// the preview renders from the top and a taller pane shows more lines.
p.preview.toggle(Some(VaultPath::new("n0.md")));
let mut text = String::new();
for i in 0..40 {
text.push_str(&format!("noteline{i}\n"));
}
p.loaded = Some(LoadedNote {
path: VaultPath::new("n0.md"),
ordinal: 0,
content: ReaderContent::Loaded {
text,
highlight: None,
},
});
let count_lines = |p: &mut SourcesPanel| buffer_text(p, 40, 20).matches("noteline").count();
let before = count_lines(&mut p);
// Narrow to a single source: the list pane shrinks, the preview grows.
p.list.set_query("Alpha3");
assert_eq!(p.list.visible_rows().len(), 1, "filter narrows to one");
let after = count_lines(&mut p);
assert!(
after > before,
"preview gained the space the shrunken list gave up: before={before} after={after}"
);
}
#[tokio::test]
async fn render_does_not_panic_across_states_and_sizes() {
let mut p = test_panel().await;
buffer_text(&mut p, 40, 10); // empty list
p.set_turn(
1,
vec![
dated_source("journal/2026-04-08.md", "Afternoon", "2026-04-08", 0.9),
source("b.md", "Beta section", 0.4, "beta body"),
],
&noop_tx(),
);
p.settle().await;
buffer_text(&mut p, 40, 10); // collapsed list
select_index(&mut p, 1).await;
buffer_text(&mut p, 40, 3); // tiny viewport
// Context with a loaded note.
p.preview.toggle(Some(VaultPath::new("b.md")));
p.loaded = Some(LoadedNote {
path: VaultPath::new("b.md"),
ordinal: 0,
content: ReaderContent::Loaded {
text: "# Beta\nbeta body\nmore\n".to_string(),
highlight: Some(7..16),
},
});
buffer_text(&mut p, 40, 12); // context + preview
p.preview.toggle(Some(VaultPath::new("b.md"))); // -> Full
buffer_text(&mut p, 40, 12); // full preview
// Loading / Failed placeholders.
p.loaded = Some(LoadedNote {
path: VaultPath::new("b.md"),
ordinal: 0,
content: ReaderContent::Loading,
});
buffer_text(&mut p, 40, 12);
p.loaded = Some(LoadedNote {
path: VaultPath::new("b.md"),
ordinal: 0,
content: ReaderContent::Failed,
});
buffer_text(&mut p, 40, 12);
buffer_text(&mut p, 3, 3); // degenerate
buffer_text(&mut p, 0, 0); // zero rect
}
#[tokio::test]
async fn full_preview_anchors_scroll_to_the_highlighted_section() {
let mut p = test_panel().await;
p.set_turn(1, vec![source("a.md", "b", 0.9, "beta body")], &noop_tx());
p.settle().await;
// Open to Full and load a note where the section is several lines down.
p.preview.toggle(Some(VaultPath::new("a.md"))); // Context
p.preview.toggle(Some(VaultPath::new("a.md"))); // Full
// Section is deep enough that anchoring scrolls past the top (the "two
// lines of context above the section" rule needs room above it).
let mut body = String::new();
for i in 0..8 {
body.push_str(&format!("line{i}\n"));
}
body.push_str("beta body\n");
for i in 0..8 {
body.push_str(&format!("tail{i}\n"));
}
let start = body.find("beta body").unwrap();
p.loaded = Some(LoadedNote {
path: VaultPath::new("a.md"),
ordinal: 0,
content: ReaderContent::Loaded {
text: body,
highlight: Some(start..start + "beta body".len()),
},
});
// Full mode: title(1) + divider(1) + content; a short content viewport so
// the section (line 2) is scrollable into view.
buffer_text(&mut p, 40, 6);
assert!(
p.preview.scroll_offset() > 0,
"preview anchored the scroll to the section, offset={}",
p.preview.scroll_offset()
);
}
// ── Full-preview content scroll (F1) ──────────────────────────────────
#[tokio::test]
async fn full_down_scrolls_content_not_the_list() {
let mut p = test_panel().await;
two_source_panel(&mut p).await;
let (tx, _rx) = tokio::sync::mpsc::unbounded_channel();
p.preview.toggle(Some(VaultPath::new("a.md"))); // Context
p.preview.toggle(Some(VaultPath::new("a.md"))); // Full
// A note taller than the viewport with the section at the very top, so
// the anchor sits at offset 0 with room to scroll down.
let mut body = String::from("alpha body\n");
for i in 0..20 {
body.push_str(&format!("line{i}\n"));
}
p.loaded = Some(LoadedNote {
path: VaultPath::new("a.md"),
ordinal: 0,
content: ReaderContent::Loaded {
text: body,
highlight: Some(0.."alpha body".len()),
},
});
buffer_text(&mut p, 40, 6); // render sets max; anchor at the top
assert_eq!(p.preview.scroll_offset(), 0);
// Down scrolls the preview content; the list selection stays put.
p.handle_input(&InputEvent::Key(key(KeyCode::Down)), &tx);
assert_eq!(
selected_heading(&p).as_deref(),
Some("A"),
"Down in Full scrolls content, not the list"
);
assert!(
p.preview.scroll_offset() > 0,
"Full + Down scrolled the content, offset={}",
p.preview.scroll_offset()
);
}
#[tokio::test]
async fn full_j_still_moves_the_list_selection() {
let mut p = test_panel().await;
two_source_panel(&mut p).await;
let (tx, _rx) = tokio::sync::mpsc::unbounded_channel();
p.preview.toggle(Some(VaultPath::new("a.md"))); // Context
p.preview.toggle(Some(VaultPath::new("a.md"))); // Full
assert!(p.preview.is_full());
// `j` is left for list navigation even under the full preview.
p.handle_input(&InputEvent::Key(key(KeyCode::Char('j'))), &tx);
assert_eq!(
selected_heading(&p).as_deref(),
Some("B"),
"j moves the list selection in Full"
);
}
#[tokio::test]
async fn wheel_scrolls_the_open_preview_and_is_ignored_when_collapsed() {
let mut p = test_panel().await;
two_source_panel(&mut p).await;
let (tx, _rx) = tokio::sync::mpsc::unbounded_channel();
// Collapsed with no list rect recorded yet: the wheel misses everything
// and is left unconsumed for the host.
let wheel = |kind| {
InputEvent::Mouse(MouseEvent {
kind,
column: 0,
row: 0,
modifiers: KeyModifiers::NONE,
})
};
assert_eq!(
p.handle_input(&wheel(MouseEventKind::ScrollDown), &tx),
EventState::NotConsumed,
"collapsed preview with no recorded rect does not eat the wheel"
);
// Open to Full with scrollable content.
p.preview.toggle(Some(VaultPath::new("a.md")));
p.preview.toggle(Some(VaultPath::new("a.md")));
let mut body = String::from("alpha body\n");
for i in 0..20 {
body.push_str(&format!("line{i}\n"));
}
p.loaded = Some(LoadedNote {
path: VaultPath::new("a.md"),
ordinal: 0,
content: ReaderContent::Loaded {
text: body,
highlight: Some(0.."alpha body".len()),
},
});
buffer_text(&mut p, 40, 6);
assert_eq!(
p.handle_input(&wheel(MouseEventKind::ScrollDown), &tx),
EventState::Consumed,
"open preview consumes the wheel"
);
assert!(p.preview.scroll_offset() > 0, "wheel scrolled the content");
}
// ── Same-note, different-section re-anchor (F2) ───────────────────────
#[tokio::test]
async fn same_note_different_heading_recomputes_highlight_without_reload() {
let (_dir, vault) = test_vault().await;
std::mem::forget(_dir);
let mut p = SourcesPanel::new(Arc::new(vault), &key_bindings());
// Two sources in the SAME note, different sections (distinct ordinals).
let mut s0 = source("doc.md", "Alpha", 0.9, "alpha body");
s0.ordinal = 1;
let mut s1 = source("doc.md", "Beta", 0.8, "beta body");
s1.ordinal = 2;
p.set_turn(1, vec![s0, s1], &noop_tx());
p.settle().await;
let (tx, _rx) = tokio::sync::mpsc::unbounded_channel();
p.preview.toggle(Some(VaultPath::new("doc.md"))); // Context
p.ensure_loaded(&tx); // spawns a load for doc.md, ordinal 1
// Deliver the note text (simulating the load landing).
let note = "# Alpha\nalpha body\n# Beta\nbeta body\n".to_string();
p.handle_data(AskData::ReaderNote {
path: VaultPath::new("doc.md"),
text: Some(note),
});
let first = match &p.loaded.as_ref().unwrap().content {
ReaderContent::Loaded { text, highlight } => {
let r = highlight.clone().expect("section resolves");
assert_eq!(&text[r.clone()], "alpha body");
r
}
_ => panic!("expected Loaded"),
};
// Move to the second source (same note): the highlight re-resolves to
// the new section and the loaded note is REUSED (no drop to Loading).
p.handle_input(&InputEvent::Key(key(KeyCode::Char('j'))), &tx);
match &p.loaded.as_ref().unwrap().content {
ReaderContent::Loaded { text, highlight } => {
let r = highlight.clone().expect("re-resolved");
assert_eq!(&text[r.clone()], "beta body");
assert_ne!(r, first, "highlight moved to the new section");
}
_ => panic!("must reuse the loaded note, not reload"),
}
assert_eq!(
p.loaded.as_ref().unwrap().ordinal,
2,
"re-keyed to the new source"
);
}
// ── open_reader keeps the reveal (F5) ─────────────────────────────────
#[tokio::test]
async fn open_reader_stays_full_and_re_points_to_the_source() {
let (_dir, vault) = test_vault().await;
vault
.create_note(&VaultPath::new("a.md"), "# ha\nalpha text\n")
.await
.unwrap();
vault
.create_note(&VaultPath::new("b.md"), "# hb\nbeta text\n")
.await
.unwrap();
let mut p = SourcesPanel::new(Arc::new(vault), &key_bindings());
let mut s0 = source("a.md", "ha", 0.9, "alpha text");
s0.ordinal = 1;
let mut s1 = source("b.md", "hb", 0.8, "beta text");
s1.ordinal = 2;
p.set_turn(1, vec![s0, s1], &noop_tx());
p.settle().await;
let (tx, mut rx) = tokio::sync::mpsc::unbounded_channel();
// Reveal source 1 in Full.
select_index(&mut p, 1).await;
p.preview.toggle(Some(VaultPath::new("b.md"))); // Context
p.preview.toggle(Some(VaultPath::new("b.md"))); // Full
assert!(p.preview.is_full());
// Directed reveal of source 0 must STAY Full (not collapse) and re-point.
p.open_reader(0, &tx);
assert!(p.preview.is_full(), "open_reader keeps the Full reveal");
assert_eq!(selected_heading(&p).as_deref(), Some("ha"));
// It spawned a load for source 0's note; deliver it and check the section.
let ev = rx.recv().await.expect("open_reader spawns a ReaderNote");
let AppEvent::Ask(data) = ev else {
panic!("expected an Ask event");
};
p.handle_data(data);
match &p.loaded.as_ref().unwrap().content {
ReaderContent::Loaded { text, highlight } => {
assert_eq!(text, "# ha\nalpha text\n", "source 0's note is shown");
let r = highlight.clone().expect("section resolves");
assert_eq!(&text[r], "alpha text");
}
_ => panic!("expected Loaded for source 0"),
}
}
}