mirador 1.7.0

An opinionated personal dashboard for your terminal: world clocks, a calendar, weather, tasks, notes, a market watchlist, and live CPU and network graphs.
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
//! Notes: a list of what you wrote down, beside the note you are looking at.
//!
//! Master-detail, the shape a mail client uses. The list alone is not enough —
//! a note's whole value is the text inside it, and making the reader press a
//! key to see any of it turns "glance at the dashboard" into "operate the
//! dashboard". So the body is always on screen for the selected note.
//!
//! The split follows the panel: side by side when there is width for both, and
//! stacked when there is not, rather than squeezing two unreadable columns.

use jiff::civil::Date;
use ratatui::Frame;
use ratatui::crossterm::event::{
    KeyCode, KeyEvent, KeyModifiers, MouseButton, MouseEvent, MouseEventKind,
};
use ratatui::layout::{Constraint, Layout, Position, Rect};
use ratatui::style::{Modifier, Style};
use ratatui::text::{Line, Span};
use ratatui::widgets::{List, ListItem, ListState, Paragraph};

use crate::config::NotesConfig;
use crate::frame::Binding;
use crate::grid::{Column, Grid, wrapped_height};
use crate::note::{Note, NoteStore};
use crate::panel::{KeyOutcome, Panel, RenderContext};
use crate::textarea::TextArea;
use crate::textfield::TextField;
use crate::theme::Theme;

/// Every key the list responds to.
///
/// One declaration feeds the border hint, the status bar and the help overlay,
/// and `every_documented_key_works_and_every_working_key_is_documented` fails
/// if this list and the code drift apart.
const LIST_BINDINGS: &[Binding] = &[
    Binding::primary("a", "new"),
    Binding::primary("↵", "edit"),
    Binding::primary("d", "delete"),
    Binding::extra("↑ / ↓", "move selection"),
    Binding::extra("j / k", "move selection"),
    Binding::extra("g / G", "first / last"),
    Binding::extra("Home / End", "first / last"),
    Binding::extra("PgUp / PgDn", "scroll the note"),
    Binding::extra("e", "edit"),
    Binding::extra("n", "new"),
    Binding::extra("/", "search"),
    Binding::extra("Esc", "clear search"),
    Binding::extra("o", "show file path"),
];

/// Editing has a different vocabulary from browsing. Keeping it separate puts
/// the scratchpad's selection and clipboard actions in the border while the
/// form is open instead of continuing to advertise list actions that cannot
/// work there.
const TITLE_EDIT_BINDINGS: &[Binding] = &[
    Binding::primary("Tab", "body"),
    Binding::primary("Ctrl+S", "save"),
    Binding::primary("Esc", "cancel"),
];

const BODY_EDIT_BINDINGS: &[Binding] = &[
    Binding::primary("Shift+←↑→↓", "select"),
    Binding::primary("Ctrl+V", "paste"),
    Binding::primary("Ctrl+S", "save"),
    Binding::extra("Ctrl+A", "select all"),
    Binding::extra("Ctrl+C", "copy selection"),
    Binding::extra("Tab", "change field"),
    Binding::extra("Esc", "cancel"),
];

/// Once text is selected, the next useful action is copying or replacing it.
const SELECTION_BINDINGS: &[Binding] = &[
    Binding::primary("Ctrl+C", "copy"),
    Binding::primary("Ctrl+V", "paste"),
    Binding::primary("Ctrl+S", "save"),
    Binding::extra("Shift+←↑→↓", "adjust selection"),
    Binding::extra("Ctrl+A", "select all"),
    Binding::extra("Tab", "change field"),
    Binding::extra("Esc", "cancel"),
];

/// Columns of the note list. The date is right-aligned so the dates line up.
pub(crate) const COLUMNS: &[Column] = &[
    Column::flex("title", 1),
    Column::fixed("date", 6).right().drops_below(24),
];

/// Which field the edit form is on.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
enum Field {
    Title,
    Body,
}

/// The form used for both new and existing notes.
#[derive(Debug)]
struct EditForm {
    /// `None` for a note being created.
    id: Option<u64>,
    title: TextField,
    body: TextArea,
    field: Field,
    error: Option<String>,
}

impl EditForm {
    fn blank() -> Self {
        Self {
            id: None,
            title: TextField::new(),
            body: TextArea::new(),
            field: Field::Title,
            error: None,
        }
    }

    fn from_note(note: &Note) -> Self {
        Self {
            id: Some(note.id),
            title: TextField::with_value(note.title.clone()),
            body: TextArea::with_value(&note.body),
            field: Field::Title,
            error: None,
        }
    }
}

#[derive(Debug)]
enum Mode {
    List,
    Edit(Box<EditForm>),
    Search(TextField),
    ConfirmDelete { id: u64, title: String },
}

/// A note's body, wrapped once for a given width.
///
/// The reader used to wrap the whole body on *every* frame and then hand the
/// result to a `Paragraph` that scrolled past most of it — so the cost of
/// drawing a note was proportional to the note rather than to what was on
/// screen, which is the rule the agenda panel already had to learn. A 2MB note
/// cost 62ms a frame against a 250ms tick (#178).
///
/// Keyed on the text itself rather than on a note id and a dirty flag. Ids and
/// flags need every mutation site to remember to invalidate, and the one that
/// forgets shows stale prose with nothing to say it is stale. Comparing the
/// source is a memcmp — about 0.2ms for that same 2MB, against the 62ms it
/// saves — and it cannot be got wrong.
#[derive(Debug)]
struct WrappedBody {
    /// What was wrapped. The cache is valid exactly while this still matches.
    source: String,
    width: u16,
    rows: Vec<String>,
}

pub struct NotesPanel {
    store: NoteStore,
    config: NotesConfig,
    filter: String,
    mode: Mode,
    /// Note ids in display order, recomputed whenever the list changes.
    view: Vec<u64>,
    list_state: ListState,
    /// First body line drawn in the detail pane.
    body_scroll: u16,
    status: Option<(String, bool)>,
    today: Date,
    /// Where the rows and the body were last drawn, so the wheel can act on
    /// whichever one the pointer is over.
    list_area: Option<Rect>,
    detail_area: Option<Rect>,
    /// The body's rectangle as last drawn, so scrolling can clamp against the
    /// wrapped height rather than the number of newlines.
    body_area: Option<Rect>,
    /// The selected body, already wrapped. See [`WrappedBody`].
    wrapped_body: Option<WrappedBody>,
    /// The last body selection copied in this session. OSC 52 cannot read a
    /// system clipboard back, so keeping the text here is what makes Ctrl+V
    /// dependable even when the terminal declines the external copy request.
    clipboard: Option<String>,
}

impl NotesPanel {
    pub fn new(config: NotesConfig, path: std::path::PathBuf) -> anyhow::Result<Self> {
        let today = jiff::Zoned::now().date();
        let store = NoteStore::load_or_seed(path, today)?;
        let mut panel = Self {
            store,
            config,
            filter: String::new(),
            mode: Mode::List,
            view: Vec::new(),
            list_state: ListState::default(),
            body_scroll: 0,
            status: None,
            today,
            list_area: None,
            detail_area: None,
            body_area: None,
            wrapped_body: None,
            clipboard: None,
        };
        panel.refresh_view();
        Ok(panel)
    }

    /// Recompute the ordered id list, keeping the selection on the same note
    /// where possible so that typing a search does not move the cursor.
    fn refresh_view(&mut self) {
        let previous = self.selected_id();
        self.view = self.store.view(&self.filter);

        let index = previous
            .and_then(|id| self.view.iter().position(|v| *v == id))
            .or_else(|| (!self.view.is_empty()).then_some(0));
        self.list_state
            .select(index.filter(|_| !self.view.is_empty()));

        // A different note under the cursor means the body pane is showing
        // something else now, and an inherited scroll offset would drop the
        // reader into the middle of it.
        if self.selected_id() != previous {
            self.body_scroll = 0;
        }
    }

    fn selected_id(&self) -> Option<u64> {
        self.list_state
            .selected()
            .and_then(|index| self.view.get(index))
            .copied()
    }

    fn selected(&self) -> Option<&Note> {
        self.selected_id().and_then(|id| self.store.get(id))
    }

    fn select_to(&mut self, index: usize) {
        let Some(last) = self.view.len().checked_sub(1) else {
            return;
        };
        let index = index.min(last);
        if self.list_state.selected() != Some(index) {
            self.list_state.select(Some(index));
            self.body_scroll = 0;
        }
    }

    fn select_down(&mut self, n: usize) {
        let current = self.list_state.selected().unwrap_or(0);
        self.select_to(current.saturating_add(n));
    }

    fn select_up(&mut self, n: usize) {
        let current = self.list_state.selected().unwrap_or(0);
        self.select_to(current.saturating_sub(n));
    }

    /// The selected body wrapped to `width`, wrapping only if it has to.
    ///
    /// See [`WrappedBody`] for why this is keyed on the text rather than on an
    /// id and a dirty flag.
    fn wrapped_body(&mut self, body: &str, width: u16) -> &[String] {
        let fresh = self
            .wrapped_body
            .as_ref()
            .is_some_and(|cache| cache.width == width && cache.source == body);
        if !fresh {
            self.wrapped_body = Some(WrappedBody {
                source: body.to_string(),
                width,
                rows: crate::grid::wrap(body, usize::from(width)),
            });
        }
        self.wrapped_body
            .as_ref()
            .map_or(&[], |cache| cache.rows.as_slice())
    }

    /// Rows the selected body occupies, from the cache when it is warm.
    fn wrapped_rows(&self, body: &str, width: u16) -> Option<u16> {
        self.wrapped_body
            .as_ref()
            .filter(|cache| cache.width == width && cache.source == body)
            .map(|cache| u16::try_from(cache.rows.len()).unwrap_or(u16::MAX))
    }

    fn scroll_body(&mut self, delta: i16) {
        // Clamped so the body cannot be scrolled off into blank space, against
        // the height it actually occupies once wrapped rather than its count of
        // newlines. Before the first draw there is no width to wrap against, so
        // fall back to logical lines.
        let area = self.body_area;
        // The cache the reader filled on the last draw already knows this;
        // measuring again would walk the whole body on every keypress.
        let cached = self
            .selected()
            .zip(area)
            .and_then(|(note, area)| self.wrapped_rows(&note.body, area.width));
        let height = cached.unwrap_or_else(|| {
            self.selected().map_or(0, |note| match area {
                Some(area) if area.width > 0 => wrapped_height(&note.body, area.width),
                _ => u16::try_from(note.body.lines().count()).unwrap_or(u16::MAX),
            })
        });
        // Stop when the last line reaches the top of the viewport, so a long
        // note does not scroll into emptiness.
        let visible = area.map_or(1, |a| a.height).max(1);
        let max = i32::from(height.saturating_sub(visible));
        let next = i32::from(self.body_scroll) + i32::from(delta);
        self.body_scroll = u16::try_from(next.clamp(0, max.max(0))).unwrap_or(0);
    }

    fn persist(&mut self) {
        self.store.save_reporting();
        if let Some(err) = self.store.last_error.clone() {
            self.status = Some((format!("save failed: {err}"), true));
        }
    }

    fn set_status(&mut self, message: impl Into<String>) {
        self.status = Some((message.into(), false));
    }

    /// Send the selected body text outward and retain it for an in-editor
    /// paste. The selection then collapses so another Ctrl+C can quit. The
    /// injected writer keeps the OSC 52 side effect out of tests.
    fn copy_body_selection_with(
        &mut self,
        copy: impl FnOnce(&str) -> std::io::Result<()>,
    ) -> KeyOutcome {
        let selected = match &self.mode {
            Mode::Edit(form) => form.body.selected_text(),
            _ => None,
        };
        let Some(text) = selected else {
            return KeyOutcome::Ignored;
        };

        let count = text.chars().count();
        self.clipboard = Some(text.clone());
        self.status = Some(match copy(&text) {
            // OSC 52 is write-only. "Sent" is true; "copied" is unknowable.
            Ok(()) => (format!("sent {count} chars — Ctrl+V pastes here"), false),
            // The internal copy still succeeded, so lead with what remains
            // usable rather than making the whole action sound lost.
            Err(error) => (
                format!("ready to paste; terminal clipboard failed: {error}"),
                true,
            ),
        });
        if let Mode::Edit(form) = &mut self.mode {
            form.body.clear_selection();
        }
        KeyOutcome::Consumed
    }

    fn paste_body_clipboard(&mut self) -> KeyOutcome {
        let Mode::Edit(form) = &mut self.mode else {
            return KeyOutcome::Ignored;
        };
        if form.field != Field::Body {
            self.set_status("Tab to the body to paste copied text");
            return KeyOutcome::Consumed;
        }
        let Some(text) = self.clipboard.clone() else {
            self.set_status("nothing copied here yet; terminal paste still works");
            return KeyOutcome::Consumed;
        };

        let count = text.chars().count();
        form.body.insert_text(&text);
        form.error = None;
        self.set_status(format!("pasted {count} chars"));
        KeyOutcome::Consumed
    }

    /// Write the form back, returning an error message to show in the form.
    fn commit_form(&mut self) -> Result<(), String> {
        let Mode::Edit(form) = &self.mode else {
            return Ok(());
        };
        if form.title.is_blank() {
            return Err("a note needs a title".to_string());
        }

        let title = form.title.trimmed().to_string();
        let body = form.body.value();
        let id = form.id;

        let Some(id) = id else {
            let mut note = Note::new(0, title, self.today);
            note.body = body;
            let new_id = self.store.add(note);
            self.mode = Mode::List;
            self.refresh_view();
            // Land on the note just written rather than wherever the sort
            // happened to put the cursor.
            if let Some(index) = self.view.iter().position(|v| *v == new_id) {
                self.list_state.select(Some(index));
                self.body_scroll = 0;
            }
            self.set_status("added");
            self.persist();
            return Ok(());
        };

        self.store.with_note(id, self.today, |n| {
            n.title = title;
            n.body = body;
        });
        self.set_status("saved");
        self.mode = Mode::List;
        self.refresh_view();
        self.persist();
        Ok(())
    }

    fn handle_list_key(&mut self, key: KeyEvent) -> KeyOutcome {
        match key.code {
            KeyCode::Char('j') | KeyCode::Down => self.select_down(1),
            KeyCode::Char('k') | KeyCode::Up => self.select_up(1),
            KeyCode::Char('g') | KeyCode::Home => self.select_up(usize::MAX),
            KeyCode::Char('G') | KeyCode::End => self.select_down(usize::MAX),

            // The list is usually short and the body usually is not, so the
            // paging keys move the note rather than the selection — the
            // opposite of the task list, where the rows are the long thing.
            KeyCode::PageDown => self.scroll_body(5),
            KeyCode::PageUp => self.scroll_body(-5),

            KeyCode::Char('a' | 'n') => {
                self.mode = Mode::Edit(Box::new(EditForm::blank()));
            }

            KeyCode::Enter | KeyCode::Char('e') => {
                if let Some(note) = self.selected() {
                    self.mode = Mode::Edit(Box::new(EditForm::from_note(note)));
                }
            }

            KeyCode::Char('d') => {
                if let Some(note) = self.selected() {
                    self.mode = Mode::ConfirmDelete {
                        id: note.id,
                        title: note.title.clone(),
                    };
                }
            }

            KeyCode::Char('/') => {
                self.mode = Mode::Search(TextField::with_value(self.filter.clone()));
            }

            KeyCode::Char('o') => {
                let path = self.store.path().display().to_string();
                self.set_status(path);
            }

            KeyCode::Esc if !self.filter.is_empty() => {
                self.filter.clear();
                self.set_status("search cleared");
                self.refresh_view();
            }

            _ => return KeyOutcome::Ignored,
        }
        KeyOutcome::Consumed
    }

    fn handle_edit_key(&mut self, key: KeyEvent) -> KeyOutcome {
        if key.modifiers.contains(KeyModifiers::CONTROL) && matches!(key.code, KeyCode::Char('v')) {
            return self.paste_body_clipboard();
        }

        let Mode::Edit(form) = &mut self.mode else {
            return KeyOutcome::Ignored;
        };

        match key.code {
            KeyCode::Esc => {
                self.mode = Mode::List;
                self.set_status("cancelled");
                return KeyOutcome::Consumed;
            }
            // Tab moves between fields; it cannot be Enter, because Enter has
            // to mean "new line" once the cursor is in the body. With only two
            // fields, forward and backward are the same move.
            KeyCode::Tab | KeyCode::BackTab => {
                form.field = match form.field {
                    Field::Title => Field::Body,
                    Field::Body => Field::Title,
                };
                return KeyOutcome::Consumed;
            }
            _ => {}
        }

        // Ctrl+S saves from either field. The footer advertises it while the
        // form is open, and it used to work only in the body — pressing it in
        // the title did nothing at all, so anyone who trusted the footer and
        // then pressed Esc lost the note. Enter also saves, but only from the
        // title, where it cannot be mistaken for a newline.
        let save = (key.modifiers.contains(KeyModifiers::CONTROL)
            && matches!(key.code, KeyCode::Char('s')))
            || (form.field == Field::Title && key.code == KeyCode::Enter);

        if save {
            if let Err(message) = self.commit_form()
                && let Mode::Edit(form) = &mut self.mode
            {
                form.error = Some(message);
            }
            return KeyOutcome::Consumed;
        }

        match form.field {
            Field::Title => {
                form.title.handle_key(key);
            }
            Field::Body => {
                form.body.handle_key(key);
            }
        }
        form.error = None;
        KeyOutcome::Consumed
    }

    fn handle_search_key(&mut self, key: KeyEvent) -> KeyOutcome {
        let Mode::Search(field) = &mut self.mode else {
            return KeyOutcome::Ignored;
        };
        match key.code {
            KeyCode::Esc => {
                self.mode = Mode::List;
            }
            KeyCode::Enter => {
                self.filter = field.trimmed().to_string();
                self.mode = Mode::List;
                self.refresh_view();
            }
            _ => {
                field.handle_key(key);
                // Filter as you type, so the list answers before you commit.
                self.filter = field.trimmed().to_string();
                self.refresh_view();
            }
        }
        KeyOutcome::Consumed
    }

    fn handle_confirm_key(&mut self, key: KeyEvent) -> KeyOutcome {
        let Mode::ConfirmDelete { id, .. } = &self.mode else {
            return KeyOutcome::Ignored;
        };
        let id = *id;
        // `y` alone; see the note on the same arm in `todo.rs`.
        if matches!(key.code, KeyCode::Char('y' | 'Y')) {
            self.store.remove(id);
            self.mode = Mode::List;
            self.refresh_view();
            self.set_status("deleted");
            self.persist();
        } else {
            self.mode = Mode::List;
            self.set_status("kept");
        }
        KeyOutcome::Consumed
    }

    /// One row of the list.
    fn note_line(&self, note: &Note, theme: &Theme, grid: &Grid) -> Line<'static> {
        let date = note
            .shown_date()
            .strftime(&self.config.date_format)
            .to_string();
        // An edited note shows when it changed; the mark says which date this
        // is, so the column is not two different facts sharing a heading.
        let date = if note.updated.is_some() {
            format!("·{date}")
        } else {
            date
        };

        grid.row(&[
            Span::styled(note.title.clone(), Style::default().fg(theme.text)),
            Span::styled(date, Style::default().fg(theme.muted)),
        ])
    }

    /// The detail pane: the selected note's title, date and body.
    fn render_detail(&mut self, frame: &mut Frame, area: Rect, theme: &Theme) {
        if area.width == 0 || area.height == 0 {
            return;
        }

        let Some(note) = self.selected() else {
            let message = if self.view.is_empty() && self.filter.is_empty() {
                "No notes yet. Press `a` to write one."
            } else {
                "Nothing matches this search. Esc to clear."
            };
            frame.render_widget(
                Paragraph::new(Span::styled(message, Style::default().fg(theme.muted))),
                area,
            );
            return;
        };

        let rows = Layout::vertical([
            Constraint::Length(1), // title
            Constraint::Length(1), // dates
            Constraint::Min(0),    // body
        ])
        .split(area);

        // Wrapped by `grid` rather than by ratatui, whose own wrapper panics on
        // text mirador did not write — and a note is exactly that. See
        // `grid::wrapped`.
        frame.render_widget(
            Paragraph::new(crate::grid::wrapped(&note.title, rows[0].width)).style(
                Style::default()
                    .fg(theme.accent)
                    .add_modifier(Modifier::BOLD),
            ),
            rows[0],
        );

        let mut dates = vec![Span::styled(
            format!("written {}", note.created.strftime("%d %b %Y")),
            Style::default().fg(theme.muted),
        )];
        if let Some(updated) = note.updated {
            dates.push(Span::styled(
                format!("   edited {}", updated.strftime("%d %b %Y")),
                Style::default().fg(theme.muted),
            ));
        }
        frame.render_widget(Paragraph::new(Line::from(dates)), rows[1]);

        if rows[2].height == 0 {
            return;
        }
        // Taken by value because filling the wrap cache needs `&mut self`, and
        // `note` is borrowed from `self.store`.
        let body_text = note.body.clone();
        let body = if note.body.trim().is_empty() {
            Paragraph::new(Span::styled("(no body)", Style::default().fg(theme.muted)))
        } else {
            // Only the rows that will be drawn are built. Handing a `Paragraph`
            // the whole wrapped body and asking it to `scroll` past most of it
            // made the cost of a frame proportional to the note rather than to
            // the pane — see `WrappedBody` and #178.
            let scroll = usize::from(self.body_scroll);
            let height = usize::from(rows[2].height);
            let wrapped = self.wrapped_body(&body_text, rows[2].width);
            let visible: Vec<Line<'static>> = wrapped
                .iter()
                .skip(scroll.min(wrapped.len()))
                .take(height)
                .map(|row| Line::from(row.clone()))
                .collect();
            Paragraph::new(visible).style(Style::default().fg(theme.text))
        };
        // The reader wraps even though the editor does not: prose written at
        // one width has to be readable at another.
        // Remembered so scrolling can clamp against the *wrapped* height. The
        // reader wraps and the clamp used to count `body.lines()`, so a note
        // written as one paragraph — the normal way — reported a single line
        // and would not scroll at all however long it was.
        self.body_area = Some(rows[2]);
        // No `.scroll()`: the offset was applied when the visible rows were
        // chosen. Scrolling here as well would skip twice.
        frame.render_widget(body, rows[2]);
    }

    /// The count line above the split, plus the active search if there is one.
    fn summary_line(&self, theme: &Theme) -> Line<'static> {
        let mut spans = vec![Span::styled(
            match self.store.notes().len() {
                0 => "no notes".to_string(),
                1 => "1 note".to_string(),
                n => format!("{n} notes"),
            },
            Style::default().fg(theme.muted),
        )];
        if !self.filter.is_empty() {
            spans.push(Span::styled(
                format!("   search: {}", self.filter),
                Style::default().fg(theme.label),
            ));
        }
        Line::from(spans)
    }

    /// The bottom line: a delete confirmation, the search prompt, or the last
    /// status message. A save failure outranks nothing — it stays until the
    /// next keypress, because a note that failed to save must not look saved.
    /// The status line, cut to `width` with an ellipsis rather than by the
    /// terminal. See `StocksPanel::status_line`: a note title in a delete
    /// prompt and a typed search term are both as long as the user made them.
    fn status_line(&self, theme: &Theme, width: u16) -> Line<'static> {
        crate::grid::assemble(vec![self.status_text(theme).spans], width)
    }

    fn status_text(&self, theme: &Theme) -> Line<'static> {
        match (&self.mode, &self.status) {
            (Mode::ConfirmDelete { title, .. }, _) => Line::from(Span::styled(
                format!("delete \"{title}\"?  y / n"),
                Style::default()
                    .fg(theme.error)
                    .add_modifier(Modifier::BOLD),
            )),
            (Mode::Search(field), _) => Line::from(vec![
                Span::styled("search  ", Style::default().fg(theme.accent)),
                Span::styled(field.value().to_string(), Style::default().fg(theme.text)),
                Span::styled("▏", Style::default().fg(theme.accent)),
            ]),
            (_, Some((message, is_error))) => Line::from(Span::styled(
                message.clone(),
                Style::default().fg(if *is_error { theme.error } else { theme.muted }),
            )),
            _ => Line::default(),
        }
    }

    /// One editor row, split wherever the selection or caret changes style.
    fn editor_line(
        text: &str,
        caret: Option<usize>,
        selection: Option<std::ops::Range<usize>>,
        theme: &Theme,
    ) -> Line<'static> {
        let selection = selection.filter(|range| range.start < range.end);
        let mut cuts = vec![0, text.len()];
        if let Some(range) = &selection {
            cuts.extend([range.start, range.end]);
        }
        if let Some(at) = caret {
            cuts.push(at);
        }
        cuts.sort_unstable();
        cuts.dedup();

        let mut spans = Vec::new();
        for pair in cuts.windows(2) {
            let (start, end) = (pair[0], pair[1]);
            if caret == Some(start) {
                spans.push(Span::styled("▏", Style::default().fg(theme.accent)));
            }
            if start == end {
                continue;
            }
            let selected = selection
                .as_ref()
                .is_some_and(|range| start >= range.start && end <= range.end);
            let style = if selected {
                Style::default()
                    .fg(theme.text)
                    .add_modifier(Modifier::REVERSED)
            } else {
                Style::default().fg(theme.text)
            };
            spans.push(Span::styled(text[start..end].to_string(), style));
        }
        if caret == Some(text.len()) {
            spans.push(Span::styled("▏", Style::default().fg(theme.accent)));
        }
        Line::from(spans)
    }

    /// The edit form, drawn over the whole panel.
    fn render_form(
        frame: &mut Frame,
        area: Rect,
        theme: &Theme,
        form: &EditForm,
        status: Option<(&str, bool)>,
    ) {
        let rows = Layout::vertical([
            Constraint::Length(1), // heading
            Constraint::Length(1), // title field
            Constraint::Length(1), // body label
            Constraint::Min(1),    // body
            Constraint::Length(1), // hint or error
        ])
        .split(area);

        let heading = if form.id.is_some() {
            "EDIT NOTE"
        } else {
            "NEW NOTE"
        };
        frame.render_widget(
            Paragraph::new(Span::styled(
                heading,
                Style::default()
                    .fg(theme.label)
                    .add_modifier(Modifier::BOLD),
            )),
            rows[0],
        );

        let active = |field: Field| {
            if form.field == field {
                Style::default()
                    .fg(theme.accent)
                    .add_modifier(Modifier::BOLD)
            } else {
                Style::default().fg(theme.muted)
            }
        };

        let (title_text, title_cursor) =
            form.title.visible(rows[1].width.saturating_sub(7) as usize);
        let mut title_spans = vec![Span::styled("title  ", active(Field::Title))];
        title_spans.push(Span::styled(title_text, Style::default().fg(theme.text)));
        if form.field == Field::Title {
            title_spans.push(Span::styled("▏", Style::default().fg(theme.accent)));
            let _ = title_cursor;
        }
        frame.render_widget(Paragraph::new(Line::from(title_spans)), rows[1]);

        frame.render_widget(
            Paragraph::new(Span::styled("body", active(Field::Body))),
            rows[2],
        );

        if rows[3].height > 0 {
            let height = usize::from(rows[3].height);
            let width = usize::from(rows[3].width);
            let offset = form.body.scroll_offset(height);
            let editing = form.field == Field::Body;
            let last = form.body.lines().len().min(offset + height);
            let lines: Vec<Line> = (offset..last)
                .map(|index| {
                    // The editor scrolls sideways as well as down, so a long
                    // line does not carry the caret off the right-hand edge.
                    // `visible_with_selection` owns the arithmetic — it is
                    // measured in display cells, and getting that wrong here
                    // is what invariant 9 is about.
                    let (text, caret, selection) = form.body.visible_with_selection(index, width);
                    // Draw the caret inline rather than moving the terminal
                    // cursor: the panel does not own the screen cursor, and a
                    // caret that only appears in the focused field is what
                    // tells the user where typing will land.
                    Self::editor_line(&text, caret.filter(|_| editing), selection, theme)
                })
                .collect();
            frame.render_widget(Paragraph::new(lines), rows[3]);
        }

        let footer = match (&form.error, status) {
            (Some(message), _) => Span::styled(message.clone(), Style::default().fg(theme.error)),
            (None, Some((message, is_error))) => Span::styled(
                message.to_string(),
                Style::default().fg(if is_error { theme.error } else { theme.muted }),
            ),
            (None, None) if form.body.has_selection() => Span::styled(
                "Ctrl+C copy   Ctrl+V replace   Ctrl+S save",
                Style::default().fg(theme.muted),
            ),
            (None, None) if form.field == Field::Body => Span::styled(
                "Shift+arrows select   Ctrl+A all   Ctrl+V paste",
                Style::default().fg(theme.muted),
            ),
            (None, None) => Span::styled(
                "Tab body   Ctrl+S save   Esc cancel",
                Style::default().fg(theme.muted),
            ),
        };
        frame.render_widget(Paragraph::new(footer), rows[4]);
    }
}

impl Panel for NotesPanel {
    fn title(&self) -> String {
        "Notes".to_string()
    }

    fn counter(&self) -> Option<String> {
        // See the note on `TodoPanel::counter`: a failed save is a standing
        // condition and outranks the count.
        if self.store.last_error.is_some() {
            return Some("unsaved!".into());
        }
        let total = self.store.notes().len();
        if total == 0 {
            return None;
        }
        if self.filter.is_empty() {
            Some(format!("{total}"))
        } else {
            // While searching, the pair is the useful fact: how much of the
            // pile the search actually matched.
            Some(format!("{}/{total}", self.view.len()))
        }
    }

    fn bindings(&self) -> &'static [Binding] {
        match &self.mode {
            Mode::Edit(form) if form.body.has_selection() => SELECTION_BINDINGS,
            Mode::Edit(form) if form.field == Field::Body => BODY_EDIT_BINDINGS,
            Mode::Edit(_) => TITLE_EDIT_BINDINGS,
            _ => LIST_BINDINGS,
        }
    }

    fn refresh_interval(&self) -> std::time::Duration {
        // Nothing here changes on its own; the tick only rolls the date over
        // so a note written after midnight is stamped correctly.
        std::time::Duration::from_mins(1)
    }

    fn tick(&mut self) -> bool {
        // Only the date matters here, and only when it changes: `today` decides
        // whether a note is labelled "today" or by its date.
        let today = jiff::Zoned::now().date();
        let moved = today != self.today;
        self.today = today;
        moved
    }

    fn alert(&self) -> Option<crate::panel::Alert> {
        // A save that is failing is the clearest case there is: the work is on
        // screen and not on disk, and every further edit widens the gap.
        self.store
            .last_error
            .as_ref()
            .map(|why| crate::panel::Alert::failing(format!("Notes could not be saved — {why}")))
    }

    fn captures_input(&self) -> bool {
        !matches!(self.mode, Mode::List)
    }

    fn handle_key(&mut self, key: KeyEvent) -> KeyOutcome {
        self.status = None;
        match &self.mode {
            Mode::List => self.handle_list_key(key),
            Mode::Edit(_) => self.handle_edit_key(key),
            Mode::Search(_) => self.handle_search_key(key),
            Mode::ConfirmDelete { .. } => self.handle_confirm_key(key),
        }
    }

    fn copy_selection(&mut self) -> KeyOutcome {
        self.copy_body_selection_with(crate::clipboard::copy)
    }

    fn handle_paste(&mut self, text: &str) -> KeyOutcome {
        self.status = None;
        let Mode::Edit(form) = &mut self.mode else {
            return KeyOutcome::Ignored;
        };

        let text = text.replace("\r\n", "\n").replace('\r', "\n");
        let count = text.chars().count();
        match form.field {
            Field::Body => form.body.insert_text(&text),
            Field::Title => {
                // A title is one line. Preserve the words from a multiline
                // paste without letting Enter accidentally submit the form.
                for character in text.chars() {
                    match character {
                        '\n' | '\t' => form.title.insert(' '),
                        c if !c.is_control() => form.title.insert(c),
                        _ => {}
                    }
                }
            }
        }
        form.error = None;
        self.set_status(format!("pasted {count} chars from terminal"));
        KeyOutcome::Consumed
    }

    fn handle_mouse(&mut self, event: MouseEvent, _area: Rect) -> KeyOutcome {
        if !matches!(self.mode, Mode::List) {
            return KeyOutcome::Ignored;
        }
        let at = Position::new(event.column, event.row);
        let over_body = self.detail_area.is_some_and(|a| a.contains(at));

        match event.kind {
            // The wheel acts on whichever half it is pointing at: the list
            // scrolls through notes, the body scrolls through one note.
            MouseEventKind::ScrollDown if over_body => self.scroll_body(2),
            MouseEventKind::ScrollUp if over_body => self.scroll_body(-2),
            MouseEventKind::ScrollDown => self.select_down(1),
            MouseEventKind::ScrollUp => self.select_up(1),
            MouseEventKind::Down(MouseButton::Left) => {
                let Some(area) = self.list_area else {
                    return KeyOutcome::Ignored;
                };
                let Some(index) =
                    crate::selection::row_at(&self.list_state, area, at, self.view.len())
                else {
                    return KeyOutcome::Ignored;
                };
                self.status = None;
                self.select_to(index);
            }
            _ => return KeyOutcome::Ignored,
        }
        KeyOutcome::Consumed
    }

    fn render(&mut self, frame: &mut Frame, area: Rect, ctx: RenderContext<'_>) {
        let theme = ctx.theme;
        if area.width == 0 || area.height == 0 {
            return;
        }

        // Cleared each pass; the branches below set them only where something
        // was really drawn, so a stale rectangle cannot keep catching clicks.
        self.list_area = None;
        self.detail_area = None;

        if let Mode::Edit(form) = &self.mode {
            let status = self
                .status
                .as_ref()
                .map(|(message, is_error)| (message.as_str(), *is_error));
            Self::render_form(frame, area, theme, form, status);
            return;
        }

        let rows = Layout::vertical([
            Constraint::Length(1), // summary
            Constraint::Min(1),    // master + detail
            Constraint::Length(1), // status
        ])
        .split(area);

        frame.render_widget(Paragraph::new(self.summary_line(theme)), rows[0]);

        // Master-detail split. Stacked by default: side by side divides a
        // finite width between a list that wants room for titles and a body
        // that wants room for prose, and neither gets enough. Stacking gives
        // both the full width and spends height instead.
        let body = rows[1];
        let side_by_side = self.config.preview.eq_ignore_ascii_case("beside");

        // A rule between the two halves. Without it the panel reads as one
        // list whose last few rows have gone strange, rather than as a list
        // and the note it is pointing at — the two are the same kind of text
        // in the same colours, so nothing else separates them.
        let (list_area, detail_area) = if side_by_side {
            let parts = Layout::horizontal([
                Constraint::Percentage(42),
                Constraint::Length(3),
                Constraint::Min(0),
            ])
            .split(body);
            for row in 0..parts[1].height {
                frame.render_widget(
                    Paragraph::new(Span::styled("│", Style::default().fg(theme.rule))),
                    Rect::new(parts[1].x + 1, parts[1].y + row, 1, 1),
                );
            }
            (parts[0], parts[2])
        } else {
            let parts = Layout::vertical([
                Constraint::Percentage(45),
                Constraint::Length(1),
                Constraint::Min(0),
            ])
            .split(body);
            crate::frame::rule(frame, parts[1], theme, "");
            (parts[0], parts[2])
        };

        if !self.view.is_empty() && list_area.height > 1 {
            let marker = 2u16;
            let grid = Grid::new(COLUMNS, list_area.width.saturating_sub(marker));
            let header_area = Rect::new(
                list_area.x + marker,
                list_area.y,
                list_area.width.saturating_sub(marker),
                1,
            );
            frame.render_widget(Paragraph::new(grid.header(theme)), header_area);

            // `NoteStore::get` is a linear scan; see the same fix in `todo.rs`.
            let by_id: std::collections::HashMap<u64, &Note> =
                self.store.notes().iter().map(|n| (n.id, n)).collect();
            let visible: Vec<&Note> = self
                .view
                .iter()
                .filter_map(|id| by_id.get(id).copied())
                .collect();
            let items: Vec<ListItem> = visible
                .iter()
                .map(|note| ListItem::new(self.note_line(note, theme, &grid)))
                .collect();

            let rows_area = Rect {
                y: list_area.y + 1,
                height: list_area.height - 1,
                ..list_area
            };
            self.list_area = Some(rows_area);

            let list = List::new(items)
                .highlight_symbol(if ctx.focused { "▸ " } else { "  " })
                .highlight_style(if ctx.focused {
                    Style::default()
                        .fg(theme.accent)
                        .add_modifier(Modifier::BOLD)
                } else {
                    Style::default().fg(theme.muted)
                });
            frame.render_stateful_widget(list, rows_area, &mut self.list_state);
        }

        self.detail_area = Some(detail_area);
        self.render_detail(frame, detail_area, theme);

        frame.render_widget(
            Paragraph::new(self.status_line(theme, rows[2].width)),
            rows[2],
        );
    }

    fn shutdown(&mut self) {
        self.store.save_reporting();
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    struct TempDir(std::path::PathBuf);

    impl Drop for TempDir {
        fn drop(&mut self) {
            let _ = std::fs::remove_dir_all(&self.0);
        }
    }

    fn panel(name: &str) -> (NotesPanel, TempDir) {
        let dir = std::env::temp_dir().join(format!("mirador-notes-{}-{name}", std::process::id()));
        let _ = std::fs::remove_dir_all(&dir);
        std::fs::create_dir_all(&dir).unwrap();
        let path = dir.join("notes.toml");
        // An empty file rather than no file: the panel seeds an example note
        // when the file is absent, and these tests are about the panel, not
        // the seed. This is the branch every run after the first one takes.
        std::fs::write(&path, "").unwrap();
        let p = NotesPanel::new(NotesConfig::default(), path).unwrap();
        (p, TempDir(dir))
    }

    fn press(p: &mut NotesPanel, code: KeyCode) {
        p.handle_key(KeyEvent::new(code, KeyModifiers::NONE));
    }

    fn chord(p: &mut NotesPanel, code: KeyCode, modifiers: KeyModifiers) {
        p.handle_key(KeyEvent::new(code, modifiers));
    }

    fn type_str(p: &mut NotesPanel, text: &str) {
        for c in text.chars() {
            press(p, KeyCode::Char(c));
        }
    }

    /// Add a note through the form: `a`, title, Tab, body, Ctrl+S.
    /// Draw the panel and return what reached the screen.
    fn draw(p: &mut NotesPanel, width: u16, height: u16) -> String {
        use ratatui::Terminal;
        use ratatui::backend::TestBackend;
        let config = crate::config::Config::default();
        let gradients = config.theme.gradients();
        let mut terminal = Terminal::new(TestBackend::new(width, height)).unwrap();
        terminal
            .draw(|frame| {
                p.render(
                    frame,
                    frame.area(),
                    RenderContext {
                        theme: &config.theme,
                        gradients: &gradients,
                        focused: true,
                        watch: &crate::watch::WatchLog::default(),
                    },
                );
            })
            .unwrap();
        let buffer = terminal.backend().buffer().clone();
        (0..height)
            .map(|y| {
                (0..width)
                    .map(|x| buffer[(x, y)].symbol().to_string())
                    .collect::<String>()
            })
            .collect::<Vec<_>>()
            .join("\n")
    }

    fn add_note(p: &mut NotesPanel, title: &str, body: &str) {
        press(p, KeyCode::Char('a'));
        type_str(p, title);
        if body.is_empty() {
            press(p, KeyCode::Enter);
            return;
        }
        press(p, KeyCode::Tab);
        for c in body.chars() {
            if c == '\n' {
                press(p, KeyCode::Enter);
            } else {
                press(p, KeyCode::Char(c));
            }
        }
        p.handle_key(KeyEvent::new(KeyCode::Char('s'), KeyModifiers::CONTROL));
    }

    #[test]
    fn a_note_can_be_written_and_survives_a_reload() {
        let (mut p, guard) = panel("write");
        add_note(&mut p, "Shopping", "milk\neggs");

        assert!(matches!(p.mode, Mode::List), "the form must close on save");
        assert_eq!(p.view.len(), 1);

        let reloaded = NotesPanel::new(NotesConfig::default(), guard.0.join("notes.toml")).unwrap();
        assert_eq!(reloaded.store.notes().len(), 1);
        let note = &reloaded.store.notes()[0];
        assert_eq!(note.title, "Shopping");
        assert_eq!(note.body, "milk\neggs");
    }

    #[test]
    fn ctrl_s_saves_from_the_title_field_and_not_only_the_body() {
        // The footer advertises Ctrl+S the whole time the form is open. It used
        // to be handled only under Field::Body, so pressing it in the title did
        // nothing at all — and anyone who trusted the footer then pressed Esc
        // and lost the note.
        let (mut p, _g) = panel("ctrl-s-title");
        press(&mut p, KeyCode::Char('a'));
        type_str(&mut p, "Saved from the title");

        p.handle_key(KeyEvent::new(KeyCode::Char('s'), KeyModifiers::CONTROL));

        assert!(
            matches!(p.mode, Mode::List),
            "Ctrl+S in the title must close the form, not be swallowed"
        );
        assert_eq!(p.store.notes().len(), 1);
        assert_eq!(p.store.notes()[0].title, "Saved from the title");
    }

    #[test]
    fn a_single_paragraph_body_can_still_be_scrolled() {
        // The clamp counted `body.lines()` while the reader wraps, so a note
        // written as one long paragraph — the normal way — reported one line
        // and would not scroll however long it was.
        let (mut p, _g) = panel("scroll-wrapped");
        let long = "word ".repeat(400);
        add_note(&mut p, "Wrapped", &long);

        p.body_area = Some(Rect::new(0, 0, 40, 5));
        p.scroll_body(3);
        assert_eq!(p.body_scroll, 3, "a wrapped body must scroll");

        // And it must still stop rather than running off into blank space.
        p.scroll_body(i16::MAX);
        let height = wrapped_height(&long, 40);
        assert_eq!(p.body_scroll, height.saturating_sub(5));
    }

    /// The reader must cost what is on screen, not what is in the note.
    ///
    /// #178: the body was wrapped in full on every frame and then scrolled
    /// past, so a 2MB note cost 62ms a frame against a 250ms tick. The fix is
    /// a cache, and the property worth pinning is not the timing — which is
    /// machine-dependent — but that a second draw of an unchanged note does no
    /// wrapping at all.
    #[test]
    fn an_unchanged_note_is_not_rewrapped_on_every_frame() {
        let (mut p, _g) = panel("rewrap");
        add_note(&mut p, "Long", &"lorem ipsum dolor sit amet ".repeat(40));
        draw(&mut p, 40, 20);

        let first = p
            .wrapped_body
            .as_ref()
            .expect("the first draw fills the cache")
            .rows
            .as_ptr();

        draw(&mut p, 40, 20);
        let second = p.wrapped_body.as_ref().unwrap().rows.as_ptr();
        assert_eq!(
            first, second,
            "the second draw rebuilt the wrap instead of reusing it"
        );
    }

    /// The cache is keyed on the text, so an edit invalidates it with nothing
    /// having to remember to say so.
    #[test]
    fn editing_a_note_rewraps_it() {
        let (mut p, _g) = panel("rewrap-edit");
        add_note(&mut p, "Long", "one two three");
        draw(&mut p, 40, 20);
        let before = p.wrapped_body.as_ref().unwrap().rows.clone();

        add_note(&mut p, "Other", "wholly different prose here");
        draw(&mut p, 40, 20);
        let after = p.wrapped_body.as_ref().unwrap().rows.clone();
        assert_ne!(before, after, "a different body must be rewrapped");
    }

    /// So does a resize, since the rows depend on the width.
    #[test]
    fn resizing_rewraps_the_body() {
        let (mut p, _g) = panel("rewrap-resize");
        add_note(&mut p, "Long", &"lorem ipsum dolor sit amet ".repeat(20));
        draw(&mut p, 40, 20);
        let wide = p.wrapped_body.as_ref().unwrap().rows.len();
        draw(&mut p, 20, 20);
        let narrow = p.wrapped_body.as_ref().unwrap().rows.len();
        assert!(
            narrow > wide,
            "a narrower pane needs more rows: {wide} then {narrow}"
        );
    }

    /// Scrolling still shows the right slice — the offset moved from the
    /// `Paragraph` to the row selection, and applying it in both places would
    /// skip twice.
    #[test]
    fn the_visible_rows_follow_the_scroll_offset() {
        let (mut p, _g) = panel("rewrap-scroll");
        let body = (0..60)
            .map(|n| format!("line{n}"))
            .collect::<Vec<_>>()
            .join("\n");
        add_note(&mut p, "Long", &body);
        let top = draw(&mut p, 40, 20);
        assert!(top.contains("line0"), "the top of the body:\n{top}");

        p.scroll_body(5);
        let scrolled = draw(&mut p, 40, 20);
        assert!(
            !scrolled.contains("line0") && scrolled.contains("line5"),
            "scrolling by five should start at line5:\n{scrolled}"
        );
    }

    #[test]
    fn wrapped_height_measures_cells_not_characters() {
        assert_eq!(wrapped_height("", 10), 1, "an empty body still has a row");
        assert_eq!(wrapped_height("a\nb\nc", 10), 3);
        // Ten two-cell glyphs need two rows at width 10, not one.
        assert_eq!(wrapped_height(&"日".repeat(10), 10), 2);
        assert_eq!(wrapped_height("x", 0), 0);
    }

    #[test]
    fn a_note_needs_a_title() {
        let (mut p, _g) = panel("blank");
        press(&mut p, KeyCode::Char('a'));
        press(&mut p, KeyCode::Enter);

        assert!(
            matches!(p.mode, Mode::Edit(_)),
            "an empty title must keep the form open"
        );
        let Mode::Edit(form) = &p.mode else {
            unreachable!()
        };
        assert!(form.error.is_some(), "and say why");
        assert!(p.store.notes().is_empty());
    }

    #[test]
    fn enter_inside_the_body_makes_a_new_line_rather_than_saving() {
        let (mut p, _g) = panel("newline");
        press(&mut p, KeyCode::Char('a'));
        type_str(&mut p, "Title");
        press(&mut p, KeyCode::Tab);
        type_str(&mut p, "one");
        press(&mut p, KeyCode::Enter);
        type_str(&mut p, "two");

        assert!(
            matches!(p.mode, Mode::Edit(_)),
            "Enter in the body must not close the form"
        );
        let Mode::Edit(form) = &p.mode else {
            unreachable!()
        };
        assert_eq!(form.body.value(), "one\ntwo");
    }

    #[test]
    fn selected_body_text_can_be_copied_and_reused() {
        let (mut p, _g) = panel("copy-paste");
        add_note(&mut p, "Scratch", "red blue");
        press(&mut p, KeyCode::Enter);
        assert_eq!(p.bindings()[0].key, "Tab", "the title points to the body");
        press(&mut p, KeyCode::Tab);
        assert_eq!(p.bindings()[0].action, "select");

        for _ in 0..4 {
            chord(&mut p, KeyCode::Left, KeyModifiers::SHIFT);
        }
        assert_eq!(p.bindings()[0].key, "Ctrl+C");
        assert_eq!(
            p.copy_body_selection_with(|text| {
                assert_eq!(text, "blue");
                Ok(())
            }),
            KeyOutcome::Consumed
        );
        assert_eq!(p.clipboard.as_deref(), Some("blue"));
        let Mode::Edit(form) = &p.mode else {
            unreachable!()
        };
        assert!(!form.body.has_selection(), "copy collapses the selection");
        assert_eq!(
            p.copy_body_selection_with(|_| panic!("a second Ctrl+C must fall through")),
            KeyOutcome::Ignored
        );

        // Select another word and replace it with the internal copy. This does
        // not depend on the terminal accepting OSC 52 or exposing a readable
        // system clipboard.
        press(&mut p, KeyCode::Home);
        for _ in 0..3 {
            chord(&mut p, KeyCode::Right, KeyModifiers::SHIFT);
        }
        chord(&mut p, KeyCode::Char('v'), KeyModifiers::CONTROL);

        let Mode::Edit(form) = &p.mode else {
            unreachable!()
        };
        assert_eq!(form.body.value(), "blue blue");
        assert!(!form.body.has_selection(), "paste consumes the selection");
        assert_eq!(
            p.status.as_ref().map(|s| s.0.as_str()),
            Some("pasted 4 chars")
        );
    }

    #[test]
    fn terminal_paste_preserves_multiline_scratchpad_text() {
        let (mut p, _g) = panel("terminal-paste");
        add_note(&mut p, "Scratch", "red blue");
        press(&mut p, KeyCode::Enter);
        press(&mut p, KeyCode::Tab);
        press(&mut p, KeyCode::Home);
        for _ in 0..3 {
            chord(&mut p, KeyCode::Right, KeyModifiers::SHIFT);
        }

        assert_eq!(p.handle_paste("one\r\ntwo\t"), KeyOutcome::Consumed);
        let Mode::Edit(form) = &p.mode else {
            unreachable!()
        };
        assert_eq!(form.body.value(), "one\ntwo\t blue");
        assert!(!form.body.has_selection());
        assert_eq!(
            p.status.as_ref().map(|s| s.0.as_str()),
            Some("pasted 8 chars from terminal")
        );
    }

    #[test]
    fn ctrl_c_remains_quit_when_the_editor_has_nothing_to_copy() {
        let (mut p, _g) = panel("copy-empty");
        press(&mut p, KeyCode::Char('a'));
        press(&mut p, KeyCode::Tab);
        assert_eq!(
            p.copy_body_selection_with(|_| panic!("copy must not be called")),
            KeyOutcome::Ignored
        );
    }

    #[test]
    fn a_body_selection_is_visibly_reversed() {
        let theme = Theme::default();
        let line = NotesPanel::editor_line("abcd", Some(3), Some(1..3), &theme);
        let selected: String = line
            .spans
            .iter()
            .filter(|span| span.style.add_modifier.contains(Modifier::REVERSED))
            .map(|span| span.content.as_ref())
            .collect();
        assert_eq!(selected, "bc");
        assert!(line.spans.iter().any(|span| span.content == "▏"));
    }

    #[test]
    fn copy_and_paste_both_reach_the_border_at_the_default_width() {
        let line = crate::frame::hint_line(
            SELECTION_BINDINGS,
            &Theme::default(),
            28, // a 36-column default Notes panel reserves eight for its frame
        )
        .expect("the selected-text actions should fit");
        let text: String = line
            .spans
            .iter()
            .map(|span| span.content.as_ref())
            .collect();
        assert!(text.contains("Ctrl+C copy · Ctrl+V paste"), "got {text:?}");
    }

    #[test]
    fn editing_an_existing_note_updates_it_in_place() {
        let (mut p, _g) = panel("edit");
        add_note(&mut p, "Original", "body");
        assert_eq!(p.store.notes().len(), 1);

        press(&mut p, KeyCode::Enter);
        assert!(matches!(p.mode, Mode::Edit(_)), "Enter opens the note");
        type_str(&mut p, " revised");
        press(&mut p, KeyCode::Enter);

        assert_eq!(p.store.notes().len(), 1, "editing must not duplicate");
        assert_eq!(p.store.notes()[0].title, "Original revised");
    }

    #[test]
    fn deleting_asks_first_and_keeps_the_note_on_any_other_key() {
        let (mut p, _g) = panel("delete");
        add_note(&mut p, "Keep me", "");

        press(&mut p, KeyCode::Char('d'));
        assert!(matches!(p.mode, Mode::ConfirmDelete { .. }));
        press(&mut p, KeyCode::Char('n'));
        assert_eq!(p.store.notes().len(), 1, "n must keep it");

        press(&mut p, KeyCode::Char('d'));
        press(&mut p, KeyCode::Char('y'));
        assert!(p.store.notes().is_empty(), "y deletes");
    }

    #[test]
    fn searching_filters_as_you_type_and_esc_restores_everything() {
        let (mut p, _g) = panel("search");
        add_note(&mut p, "Groceries", "milk");
        add_note(&mut p, "Meeting", "invoice question");
        assert_eq!(p.view.len(), 2);

        press(&mut p, KeyCode::Char('/'));
        type_str(&mut p, "invoice");
        assert_eq!(p.view.len(), 1, "the body is searched, not just the title");
        press(&mut p, KeyCode::Enter);

        assert!(matches!(p.mode, Mode::List));
        press(&mut p, KeyCode::Esc);
        assert_eq!(p.view.len(), 2, "Esc clears the search");
    }

    #[test]
    fn the_form_captures_input_so_typing_q_cannot_quit() {
        let (mut p, _g) = panel("capture");
        assert!(!p.captures_input(), "the list must not swallow global keys");
        press(&mut p, KeyCode::Char('a'));
        assert!(p.captures_input(), "an open form must swallow them");
    }

    #[test]
    fn moving_the_selection_resets_the_body_scroll() {
        let (mut p, _g) = panel("scroll-reset");
        add_note(&mut p, "Long", &"line\n".repeat(40));
        add_note(&mut p, "Short", "short");

        // Newest first, so the cursor starts on "Short"; step down to the long
        // one, which is the only one with anywhere to scroll.
        press(&mut p, KeyCode::Char('j'));
        assert_eq!(p.selected().unwrap().title, "Long");

        p.scroll_body(10);
        assert!(p.body_scroll > 0, "the long note scrolls");
        press(&mut p, KeyCode::Char('k'));
        assert_eq!(
            p.body_scroll, 0,
            "a different note must start at its own top"
        );
    }

    #[test]
    fn the_body_cannot_be_scrolled_past_its_own_end() {
        let (mut p, _g) = panel("scroll-clamp");
        add_note(&mut p, "Short", "one\ntwo\nthree");

        p.scroll_body(500);
        assert_eq!(p.body_scroll, 2, "clamped to the last line");
        p.scroll_body(-500);
        assert_eq!(p.body_scroll, 0, "and cannot go negative");
    }

    #[test]
    fn the_counter_shows_the_match_count_only_while_searching() {
        let (mut p, _g) = panel("counter");
        assert_eq!(p.counter(), None, "no counter with nothing to count");
        add_note(&mut p, "Groceries", "milk");
        add_note(&mut p, "Meeting", "invoice");
        assert_eq!(p.counter(), Some("2".to_string()));

        press(&mut p, KeyCode::Char('/'));
        type_str(&mut p, "milk");
        assert_eq!(p.counter(), Some("1/2".to_string()));
    }

    /// Every key list mode responds to, paired with the binding documenting it.
    const DOCUMENTED_LIST_KEYS: &[(KeyCode, &str)] = &[
        (KeyCode::Char('a'), "a"),
        (KeyCode::Char('n'), "n"),
        (KeyCode::Enter, "↵"),
        (KeyCode::Char('e'), "e"),
        (KeyCode::Char('d'), "d"),
        (KeyCode::Down, "↑ / ↓"),
        (KeyCode::Up, "↑ / ↓"),
        (KeyCode::Char('j'), "j / k"),
        (KeyCode::Char('k'), "j / k"),
        (KeyCode::Char('g'), "g / G"),
        (KeyCode::Char('G'), "g / G"),
        (KeyCode::Home, "Home / End"),
        (KeyCode::End, "Home / End"),
        (KeyCode::PageUp, "PgUp / PgDn"),
        (KeyCode::PageDown, "PgUp / PgDn"),
        (KeyCode::Char('/'), "/"),
        (KeyCode::Char('o'), "o"),
    ];

    #[test]
    fn every_documented_key_works_and_every_working_key_is_documented() {
        for (code, key) in DOCUMENTED_LIST_KEYS {
            assert!(
                LIST_BINDINGS.iter().any(|b| b.key == *key),
                "`{key}` is handled but missing from BINDINGS, so nothing tells the user it exists"
            );

            let (mut p, _g) = panel("keymap");
            add_note(&mut p, "a note", "body");
            assert!(matches!(p.mode, Mode::List));

            let outcome = p.handle_key(KeyEvent::new(*code, KeyModifiers::NONE));
            assert_eq!(
                outcome,
                KeyOutcome::Consumed,
                "`{key}` is documented but the list ignores it"
            );
        }
    }

    /// A note is prose somebody wrote, and prose contains emoji. Handing that
    /// to ratatui's word wrapper crashes the dashboard — see `grid::wrapped`,
    /// which is why this panel wraps its own title and body and renders a
    /// `Paragraph` with no `Wrap`.
    ///
    /// This is the guard against putting `.wrap(…)` back. The grid has its own
    /// test for the wrapping; this one exists because the mistake is made here.
    #[test]
    fn a_note_full_of_wide_glyphs_draws_at_every_width() {
        use ratatui::Terminal;
        use ratatui::backend::TestBackend;

        let config = crate::config::Config::default();
        let gradients = config.theme.gradients();

        let (mut p, _g) = panel("wide-glyphs");
        add_note(
            &mut p,
            "a\u{1F31E}b \u{4E2D}\u{6587}\u{6807}\u{9898}",
            "\u{0301} \u{1F31E}\u{65E5}\u{65E5}\u{65E5}\u{1F31E}\u{1F31E}a\n\
             prose with a \u{1F31E} in it and a \u{65E5}\u{672C}\u{8A9E} word",
        );

        // The height matters as much as the width, and that is not obvious: the
        // fault is on a later row, so a one-row pane never reaches it. This
        // test passed against the very bug it exists for until the panes were
        // given room to wrap into.
        for width in 1..24u16 {
            for height in 1..40u16 {
                let mut terminal = Terminal::new(TestBackend::new(width, height)).unwrap();
                terminal
                    .draw(|frame| {
                        p.render(
                            frame,
                            frame.area(),
                            RenderContext {
                                theme: &config.theme,
                                gradients: &gradients,
                                focused: true,
                                watch: &crate::watch::WatchLog::default(),
                            },
                        );
                    })
                    .unwrap();
            }
        }
    }

    #[test]
    fn the_preview_sits_below_the_list_by_default_and_beside_it_on_request() {
        use ratatui::Terminal;
        use ratatui::backend::TestBackend;

        let config = crate::config::Config::default();
        let gradients = config.theme.gradients();

        let draw = |p: &mut NotesPanel| {
            let mut terminal = Terminal::new(TestBackend::new(100, 14)).unwrap();
            terminal
                .draw(|frame| {
                    p.render(
                        frame,
                        frame.area(),
                        RenderContext {
                            theme: &config.theme,
                            gradients: &gradients,
                            focused: true,
                            watch: &crate::watch::WatchLog::default(),
                        },
                    );
                })
                .unwrap();
            (p.list_area.unwrap(), p.detail_area.unwrap())
        };

        // Default: stacked, even at a width that would fit both side by side.
        // Splitting the width starves the titles and the prose at once.
        let (mut p, _g) = panel("split-below");
        add_note(&mut p, "Note", "body text");
        let (list, detail) = draw(&mut p);
        assert_eq!(detail.x, list.x, "stacked: {list:?} {detail:?}");
        assert!(detail.y > list.y, "and the body is below");
        assert_eq!(detail.width, list.width, "both get the full width");

        // Opt in to beside.
        p.config.preview = "beside".to_string();
        let (list, detail) = draw(&mut p);
        assert!(detail.x > list.x, "beside: {list:?} {detail:?}");
    }
}