mirador 1.22.2

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
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
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
//! A small column grid, so tabular data reads as a table.
//!
//! Every panel that lists things uses this. The point is not decoration: a
//! column that starts at a different place on every row cannot be scanned
//! vertically, and a column with no name leaves the reader guessing what the
//! number means. Headers are set in the utility face — bold uppercase — so they
//! read as labels rather than as another row of data.
//!
//! Widths are resolved once per draw against the available space. Fixed columns
//! take what they ask for; flexible columns share what is left in proportion to
//! their weight. When space runs short, columns are dropped from the *end* of
//! the optional list rather than every column being squeezed into illegibility.

use std::borrow::Cow;
use std::ops::Range;

use ratatui::layout::Rect;
use ratatui::style::{Modifier, Style};
use ratatui::text::{Line, Span};
use unicode_segmentation::UnicodeSegmentation;
use unicode_width::UnicodeWidthStr;

use crate::theme::Theme;

/// Display width of `text` in terminal cells.
///
/// Not the same as the character count, and the difference is not academic: a
/// weather glyph like `☀` or an emoji occupies two cells in most terminals, so
/// counting characters silently shifts every column after it and the values
/// end up under the wrong headers.
pub fn display_width(text: &str) -> usize {
    UnicodeWidthStr::width(text)
}

/// [`display_width`] as a `u16`, for arithmetic on `Rect` fields, saturating
/// at `u16::MAX` rather than wrapping or failing.
///
/// The one place the conversion is written. A width that does not fit in a
/// `u16` is wider than any terminal, so the largest one that does is the
/// honest answer: it still loses every comparison against the room on screen.
/// It is not an answer to place text by, and the clock's date line, which
/// centres by its width, writes its own conversion to draw such a date
/// nowhere rather than flush left. [`display_width`] stays a `usize` because
/// it also measures data against budgets that are not terminal widths.
pub fn cell_width(text: &str) -> u16 {
    u16::try_from(display_width(text)).unwrap_or(u16::MAX)
}

/// Cut `text` down to `width` terminal cells, ending in `…` if anything was
/// dropped.
///
/// Measured in cells for the same reason as [`display_width`]: budgeting by
/// `chars().count()` means one CJK glyph or emoji per two cells of overflow,
/// which is enough to push the text through the panel's own border.
///
/// The result never exceeds `width`, but may fall one cell short of it when a
/// double-width character would not fit — there is no half a cell to give
/// back. Callers that need an exact width should pad, as [`fit`] does.
pub fn truncate(text: &str, width: usize) -> String {
    if width == 0 {
        return String::new();
    }
    if walked_width(text) <= width {
        return text.to_string();
    }

    // Take glyphs while they fit, keeping one cell back for the ellipsis.
    let mut out = text[..prefix_fitting(text, width - 1)].to_string();
    out.push('…');
    out
}

/// Display width of a single character, treating unprintables as zero-width.
pub fn char_width(c: char) -> usize {
    unicode_width::UnicodeWidthChar::width(c).unwrap_or(0)
}

/// The byte length of the longest prefix of `text` that fits in `cells`
/// terminal cells, walked a glyph at a time (see [`glyphs`]) and stopping at
/// the first that does not fit.
///
/// **The one cell-budget walk in the module.** [`truncate`], [`break_lines`]
/// and [`assemble`] each wrote their own, and the third had drifted: it
/// measured each character as a one-character string, which allocated for
/// every character and disagreed with [`char_width`] about the ones a string
/// measure counts differently — a control character, a cell to the string and
/// none to ratatui, which never draws it.
fn prefix_fitting(text: &str, cells: usize) -> usize {
    let mut used = 0usize;
    for (at, glyph) in glyphs(text) {
        used += glyph_width(glyph);
        if used > cells {
            return at;
        }
    }
    text.len()
}

/// The cells `text` costs measured the way [`prefix_fitting`] walks it, so a
/// span measured with this and cut with that agree about where it ends.
///
/// It is also what ratatui draws, glyph for glyph, which [`display_width`]
/// is not quite: `unicode-width` measures a string as one run, so it counts
/// a control character that ratatui drops and joins a malformed sequence
/// that ratatui draws in two. So every fitting decision in this module —
/// whether a text fits whole, how wide a word is, what a part costs — is
/// made with this, and a text that is said to fit is one that does. Outside
/// the module, [`crate::frame::rule`] sizes its label with it for the same
/// reason.
pub(crate) fn walked_width(text: &str) -> usize {
    glyphs(text).map(|(_, glyph)| glyph_width(glyph)).sum()
}

/// `text` as the glyphs a terminal draws, each with its byte offset: the
/// extended grapheme clusters of UAX #29, which is exactly how ratatui's
/// `Buffer::set_stringn` splits a string before drawing it.
///
/// A character at a time is not enough, because ratatui draws a grapheme at
/// the width of the whole string, and several sequences are wider together
/// than their characters are apart: `❤` is one cell and the emoji selector
/// after it none, while `❤\u{fe0f}` is drawn as two. Walked by character, a
/// cut through a row of hearts came out a cell wider than asked for per
/// heart.
///
/// The segmentation is `unicode-segmentation`'s, the crate ratatui itself
/// segments with, so the clusters here are ratatui's by construction rather
/// than by a transcription of its rules. The first version joined by hand —
/// anything zero-width, a skin tone, whatever followed a joiner — and that
/// over-joined malformed input: the standard joins across a ZWJ only after a
/// pictograph, so `🏽\u{200d}👩` is two glyphs to ratatui, four cells, and
/// one two-cell run to the hand-rolled walk, which then cut a third-party
/// headline two cells wider than its room.
fn glyphs(text: &str) -> impl Iterator<Item = (usize, &str)> {
    text.grapheme_indices(true)
}

/// The cells one glyph from [`glyphs`] takes, measured as
/// `Buffer::set_stringn` measures it: none for a glyph holding a control
/// character, which ratatui drops without drawing; otherwise its width as a
/// string, plus a cell for each halfwidth voiced sound mark, which
/// `unicode-width` calls zero-width and ratatui — like the terminals it
/// cites — draws in a cell of its own.
fn glyph_width(glyph: &str) -> usize {
    if glyph.contains(char::is_control) {
        return 0;
    }
    display_width(glyph)
        + glyph
            .chars()
            .filter(|c| matches!(c, '\u{ff9e}' | '\u{ff9f}'))
            .count()
}

/// Break `text` into rows of at most `width` cells, handing each to `emit`.
///
/// **The single source of the wrapping rules.** [`wrap`] collects what this
/// yields and [`wrapped_height`] counts it without building anything, so the
/// two cannot drift. They used to be two transcriptions of the same rules held
/// equal by a test, and they *had* drifted: `wrapped_height` measured an
/// over-long word by subtracting `width` a row at a time, which assumes the
/// overflow can be split at any cell. A double-width glyph cannot be split, so
/// the two disagreed in both directions the moment a headline was not ASCII —
/// `日本語` at width 3 wraps to three rows and measured two. A panel that sizes
/// itself with one and draws with the other then puts content outside the box
/// it was measured for. The test that was supposed to catch this only ever fed
/// it ASCII.
///
/// Rows are emitted as byte ranges into `text`, so nothing here allocates, and
/// a caller that needs to know where a row came from — [`wrap_line`], mapping
/// it back onto styled spans — is handed the offset rather than left to
/// recover it. Measured in cells rather than characters, per the rule the
/// whole module exists for.
fn break_lines(text: &str, width: usize, mut emit: impl FnMut(Range<usize>)) {
    if width == 0 {
        return;
    }

    let mut any = false;
    // Where the current line starts in `text`. Lines are split the way
    // `str::lines` splits them, which is what this walked before it reported
    // offsets: a `\n` ends a line, and a `\r` directly before it goes with
    // it. A lone `\r` is text, and so is one at the very end with no `\n`.
    let mut offset = 0usize;
    for terminated in text.split_inclusive('\n') {
        let line = terminated
            .strip_suffix('\n')
            .map_or(terminated, |line| line.strip_suffix('\r').unwrap_or(line));
        let base = offset;
        offset += terminated.len();
        let mut emit = |row: Range<usize>| emit(base + row.start..base + row.end);

        // Byte offsets into `line`: where the row being built starts, and how
        // far the words consumed so far reach.
        let mut start = 0usize;
        let mut cursor = 0usize;
        let mut used = 0usize;
        let mut emitted_here = false;

        for word in line.split_inclusive(' ') {
            let w = walked_width(word);
            if used > 0 && used + w > width {
                emit(start..cursor);
                (any, emitted_here) = (true, true);
                start = cursor;
                used = 0;
            }
            // A row a break has just begun does not start with whitespace: it
            // is the break, however much of it there is (see
            // [`taken_by_a_break`]). `split_inclusive` hands the first space
            // of a run over with the word before it and each further one as a
            // word of its own, so two spaces after a full stop, met at a
            // break, stood on a row by themselves or indented the next:
            // `wrap("ab  cdef", 3)` drew a blank row between the words.
            // Whitespace at the start of a line no break began is the
            // author's, and keeps its cells.
            let begins_a_broken_row = emitted_here && start == cursor;
            cursor += word.len();
            used += w;
            if begins_a_broken_row {
                start += taken_by_a_break(&line[start..cursor]);
                used = walked_width(&line[start..cursor]);
            }

            // A single word longer than the row breaks inside itself, rather
            // than running off the edge.
            while used > width {
                let mut cut = start + prefix_fitting(&line[start..cursor], width);
                // Always take at least one character. A glyph wider than the
                // whole row — any CJK character or emoji in a one-cell column —
                // otherwise fits nowhere, so nothing is taken, nothing is
                // consumed, and this loops for ever. That is a hang, not a slow
                // path: the dashboard freezes and has to be killed.
                //
                // The row then exceeds `width` by a cell, which is the honest
                // outcome. A terminal cannot draw half a wide glyph either.
                //
                // A glyph rather than a character, so a heart and its emoji
                // selector stay on one row rather than the selector being
                // carried, alone and invisible, to the start of the next.
                if cut == start {
                    match glyphs(&line[start..cursor]).next() {
                        Some((_, glyph)) => cut += glyph.len(),
                        None => break,
                    }
                }
                emit(start..cut);
                (any, emitted_here) = (true, true);
                // A word exactly as wide as the row leaves only the space
                // after it, and that space is the break. Carried over, it
                // indented the next row by a cell or, when the next word did
                // not fit beside it, stood on a row of its own: `wrap("abcde
                // fghij", 5)` drew a blank row between the two words. A cut
                // can also land just before whitespace that is not a word's
                // last character — an ideographic space in unspaced Japanese,
                // a no-break space — and that is taken too. Any spaces after
                // the word are words of their own, and the check above takes
                // them as they arrive.
                start = cut + taken_by_a_break(&line[cut..cursor]);
                used = walked_width(&line[start..cursor]);
            }
        }

        // The remainder — but only if there is one. Emitting it unconditionally
        // appended a blank row whenever the break above consumed the line
        // exactly, which is what an over-long run of wide glyphs always does:
        // `wrap("🌞🌞", 1)` came out as three rows, the last one empty. A
        // genuinely empty source line still gets its row, hence `emitted_here`.
        if start < cursor || !emitted_here {
            emit(start..cursor);
            any = true;
        }
    }

    // An empty string has no lines at all, and still occupies one row.
    if !any {
        emit(0..0);
    }
}

/// The bytes at the head of `text` that a break takes rather than carrying
/// to the row it begins: whole glyphs of whitespace, so a mark joined to a
/// space stays with it.
///
/// Whitespace means everything `char::is_whitespace` calls it, the no-break
/// and ideographic spaces and the tab included, and not only U+0020. A
/// no-break space forbids a break *at* itself, and [`break_lines`] never
/// chooses one there: it breaks only at U+0020, or inside a word too long for
/// its row. So the rule meets a no-break space only where a row has already
/// ended beside it, and carried over it is the gap the rule exists to remove —
/// `wrap("Done.\u{a0} Next one", 5)` drew a blank row after `Done.`, and
/// `今日は晴れ\u{3000}明日は雨` at ten cells indented its second row by two.
fn taken_by_a_break(text: &str) -> usize {
    glyphs(text)
        .find(|(_, glyph)| !glyph.chars().all(char::is_whitespace))
        .map_or(text.len(), |(at, _)| at)
}

/// Which characters a prefix of text about to be wrapped can leave out, for
/// a panel that shows only its first few rows and must not read the rest.
///
/// A prefix measured by a budget of cells assumes that what it reads, rows
/// draw. Whitespace a break takes draws nothing, so a run of it would spend
/// the budget on padding, and the value after the padding would be lost with
/// rows to spare: a plugin's `Battery`, a hundred spaces and `80%` would draw
/// `Battery` alone in a panel with a row left. A run wider than the row
/// always holds a break, and the break takes everything in the run after it
/// (see [`taken_by_a_break`]), so a run kept only to just past the row's
/// width wraps as the whole run does.
pub(crate) struct WrapSource {
    width: usize,
    run: usize,
}

impl WrapSource {
    /// For rows `width` cells wide.
    pub(crate) fn new(width: usize) -> Self {
        Self { width, run: 0 }
    }

    /// Whether the wrap needs `c`, the text's next character: every one but
    /// the whitespace past the first `width + 1` cells of a run. A line break
    /// ends a run, and is always needed.
    pub(crate) fn needs(&mut self, c: char) -> bool {
        if c == '\n' || !c.is_whitespace() {
            self.run = 0;
            return true;
        }
        if self.run > self.width {
            return false;
        }
        self.run += char_width(c);
        true
    }

    /// The cells of what [`Self::needs`] keeps that one row can use up: the
    /// row's own `width`, and as much again and two more for the run a break
    /// after it takes. A budget of this many a row fills them all.
    pub(crate) fn row_cells(width: usize) -> usize {
        width.saturating_mul(2).saturating_add(2)
    }
}

/// Break `text` into lines no wider than `width` display cells.
///
/// The companion to [`wrapped_height`], which counts the same rows without
/// producing them. Both are [`break_lines`] with a different consumer, so
/// `wrap(t, w).len()` and `wrapped_height(t, w)` agree by construction rather
/// than by a test that has to remember to try a wide glyph.
pub fn wrap(text: &str, width: usize) -> Vec<String> {
    let mut out = Vec::new();
    break_lines(text, width, |row| out.push(text[row].to_string()));
    out
}

/// Wrap one already-styled logical line without handing untrusted text to
/// ratatui's wrapper.
///
/// Span styles follow their source bytes across row boundaries. The final
/// width check deliberately sums the spans the way ratatui does: a joined
/// emoji sequence can occupy fewer cells as one string than it does when a
/// style boundary splits it. In that exceptional case the row is collapsed
/// and truncated as one span so it still cannot cross the requested edge.
/// Embedded `\n` and `\r\n` are accepted as hard line boundaries. Their bytes
/// are skipped because [`break_lines`] hands back each row as its range in the
/// joined text, so a delimiter can never drift the styled-byte cursor or
/// become a slice panic.
///
/// The line's own style goes on every row, the collapsed one included.
pub fn wrap_line(line: &Line<'_>, width: u16) -> Vec<Line<'static>> {
    if width == 0 {
        return Vec::new();
    }
    let width = usize::from(width);
    let text: String = line
        .spans
        .iter()
        .map(|span| span.content.as_ref())
        .collect();
    let mut output = Vec::new();
    break_lines(&text, width, |range| {
        let row = &text[range.clone()];
        let spans = styled_byte_range(&line.spans, range.start, range.end);
        let style = spans
            .as_ref()
            .and_then(|spans| spans.first())
            .map_or(line.style, |span| span.style);
        let spans = spans.unwrap_or_else(|| vec![Span::styled(row.to_string(), style)]);
        let rendered_width: usize = spans.iter().map(|span| walked_width(&span.content)).sum();
        let row = if rendered_width > width {
            Line::from(Span::styled(truncate(row, width), style))
        } else {
            Line::from(spans)
        };
        output.push(row.style(line.style));
    });
    output
}

fn styled_byte_range(source: &[Span<'_>], start: usize, end: usize) -> Option<Vec<Span<'static>>> {
    let expected = end.checked_sub(start)?;
    let mut output = Vec::new();
    let mut offset = 0usize;
    let mut copied = 0usize;
    for span in source {
        let span_end = offset.checked_add(span.content.len())?;
        if start < span_end && end > offset {
            let local_start = start.saturating_sub(offset);
            let local_end = end.min(span_end).checked_sub(offset)?;
            let content = span.content.get(local_start..local_end)?;
            if !content.is_empty() {
                copied = copied.checked_add(content.len())?;
                output.push(Span::styled(content.to_string(), span.style));
            }
        }
        offset = span_end;
        if offset >= end {
            break;
        }
    }
    (copied == expected).then_some(output)
}

/// `text` wrapped to `width` and rejoined, ready for a `Paragraph` that must
/// **not** be given `Wrap`.
///
/// This exists because ratatui's own word wrapper panics on text mirador did
/// not write. `Paragraph::new("a🌞b").wrap(…)` rendered two cells wide indexes
/// past the end of the buffer and brings the whole dashboard down, and a
/// leading combining mark — a grapheme with no base character — does the same
/// at any width. Both are reachable from a note, a task's notes, or a fetch
/// error: emoji in prose is ordinary, and the panic is a crash rather than a
/// misdraw.
///
/// So the rule is that ratatui never wraps anything a user or a server wrote.
/// Wrapping here first means its wrapper never runs, and the wrapping is the
/// one in this module, which is measured in cells and tested against a corpus
/// of wide glyphs and combining marks.
///
/// The rows are exactly [`wrap`]'s, joined by `\n`. A separator goes before
/// every row but the first, counted rather than inferred from what has been
/// written so far: an empty first row writes nothing, and asking whether
/// anything had been written dropped a blank line the text began with.
pub fn wrapped(text: &str, width: u16) -> String {
    let width = usize::from(width);
    let mut out = String::with_capacity(text.len());
    let mut first = true;
    break_lines(text, width, |row| {
        if !first {
            out.push('\n');
        }
        first = false;
        out.push_str(&text[row]);
    });
    out
}

/// `text` wrapped into `area`, keeping the rows that fit and ending the last
/// of them in `…` when anything did not — or when the caller already cut the
/// text short (`abridged`), since rows that fill the pane look finished
/// either way (invariant 19). Ready for a `Paragraph` given no `Wrap`; see
/// [`wrapped`].
///
/// This is the mechanism for prose in a region of several rows. [`truncate`]
/// is for a region of one: handed a taller one, it keeps the first row and
/// leaves the rest blank, so a sentence that had the room is cut anyway. It
/// lived in the task panel, for the note preview and the form's message,
/// until the empty states of several panels were found cut by the terminal
/// and needed the same thing.
pub fn fitted_rows(text: &str, area: Rect, abridged: bool) -> String {
    let width = usize::from(area.width);
    let height = usize::from(area.height);
    let mut lines = wrap(text, width);
    if lines.len() > height || abridged {
        lines.truncate(height);
        if let Some(last) = lines.last_mut() {
            *last = truncate(&format!("{}…", last.trim_end()), width);
        }
    }
    lines.join("\n")
}

/// Rows that `text` occupies once word-wrapped to `width` cells.
///
/// Needed wherever something is sized to fit its own contents — a scroll
/// clamp, or a dialog that must not be shorter than the text inside it. The
/// unwrapped line count is not a substitute: it is right until a line is
/// longer than the box, and then it is short by exactly the amount that
/// matters.
///
/// Counts the rows [`wrap`] would produce, without producing them — the whole
/// point, since a scroll clamp runs against a note's entire body and must not
/// allocate in proportion to it. An empty line still occupies a row.
///
/// This used to be documented as matching `Paragraph::wrap`, whose own
/// `line_count` is private. It no longer needs to: nothing is handed to
/// ratatui's wrapper any more (see [`wrapped`]), so the thing worth agreeing
/// with is mirador's own wrapping, which is what gets drawn.
pub fn wrapped_height(text: &str, width: u16) -> u16 {
    if width == 0 {
        return 0;
    }
    let mut rows: usize = 0;
    break_lines(text, usize::from(width), |_| rows += 1);
    u16::try_from(rows.max(1)).unwrap_or(u16::MAX)
}

/// How a column is sized.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum Width {
    /// Exactly this many columns.
    Fixed(u16),
    /// A share of the leftover space, proportional to this weight.
    Flex(u16),
}

/// Which edge a cell's content is aligned to.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum Align {
    Left,
    Right,
}

/// One column of a grid.
#[derive(Debug, Clone, Copy)]
pub struct Column {
    /// Header text. Rendered uppercased and bold.
    pub label: &'static str,
    pub width: Width,
    pub align: Align,
    /// The narrowest total grid width at which this column is worth showing.
    /// Zero means it is never dropped.
    pub min_total: u16,
}

impl Column {
    /// A left-aligned column that flexes to fill space.
    pub const fn flex(label: &'static str, weight: u16) -> Self {
        Self {
            label,
            width: Width::Flex(weight),
            align: Align::Left,
            min_total: 0,
        }
    }

    /// A fixed-width, left-aligned column.
    pub const fn fixed(label: &'static str, width: u16) -> Self {
        Self {
            label,
            width: Width::Fixed(width),
            align: Align::Left,
            min_total: 0,
        }
    }

    /// Right-align this column. Numbers and dates belong on the right so their
    /// last digits line up.
    pub const fn right(mut self) -> Self {
        self.align = Align::Right;
        self
    }

    /// Drop this column when the grid is narrower than `total`.
    pub const fn drops_below(mut self, total: u16) -> Self {
        self.min_total = total;
        self
    }
}

/// Columns resolved against a concrete width.
#[derive(Debug, Clone)]
pub struct Grid {
    /// The columns that survived the width budget, each with its resolved
    /// width and the index it held in the caller's declaration.
    ///
    /// The declared index is what keeps a row's cells under the right headers.
    /// Indexing the caller's cells by *surviving* position instead means that
    /// dropping one column slides every value after it one header to the left
    /// — a task's tags appearing under DUE, a forecast's feels-like under RAIN.
    resolved: Vec<(Column, u16, usize)>,
}

/// Space between adjacent columns.
pub(crate) const GUTTER: u16 = 1;

impl Grid {
    /// Resolve `columns` against a total width.
    pub fn new(columns: &[Column], total: u16) -> Self {
        // Drop optional columns that this width cannot justify, narrowest
        // threshold last, so the most valuable columns survive.
        let kept: Vec<(usize, Column)> = columns
            .iter()
            .copied()
            .enumerate()
            .filter(|(_, c)| c.min_total == 0 || total >= c.min_total)
            .collect();

        if kept.is_empty() {
            return Self {
                resolved: Vec::new(),
            };
        }

        let gutters = GUTTER * u16::try_from(kept.len().saturating_sub(1)).unwrap_or(0);
        let fixed: u16 = kept
            .iter()
            .filter_map(|(_, c)| match c.width {
                Width::Fixed(w) => Some(w),
                Width::Flex(_) => None,
            })
            .sum();

        let flexible: u16 = kept
            .iter()
            .filter_map(|(_, c)| match c.width {
                Width::Flex(w) => Some(w.max(1)),
                Width::Fixed(_) => None,
            })
            .sum();

        let spare = total.saturating_sub(fixed).saturating_sub(gutters);

        let mut resolved = Vec::with_capacity(kept.len());
        let mut handed_out = 0u16;
        let flex_count = kept
            .iter()
            .filter(|(_, c)| matches!(c.width, Width::Flex(_)))
            .count();
        let mut flex_seen = 0usize;

        for (declared, column) in kept {
            let width = match column.width {
                Width::Fixed(w) => w,
                Width::Flex(weight) => {
                    flex_seen += 1;
                    if flex_seen == flex_count {
                        // The last flexible column absorbs the rounding
                        // remainder, so the grid always fills its width exactly.
                        spare.saturating_sub(handed_out)
                    } else {
                        let portion = spare
                            .checked_mul(weight.max(1))
                            .and_then(|scaled| scaled.checked_div(flexible))
                            .unwrap_or(0);
                        handed_out += portion;
                        portion
                    }
                }
            };
            resolved.push((column, width, declared));
        }

        // No column may take space the grid has not got.
        //
        // `drops_below` is how a grid *chooses* what to lose, and it is the
        // mechanism panels should reach for — a threshold names the width at
        // which a column stops being worth its room. This is the floor
        // underneath it, for the widths no threshold anticipated: a fixed
        // width is declared without reference to the total, so three fixed
        // columns in a pane narrower than their sum built a row wider than the
        // pane it was resolved for. What the reader then saw was decided by
        // the terminal, which cannot tell a value from a fragment and cuts
        // wherever the edge falls.
        //
        // Clamping hands the short column whatever is left, and `fit`
        // ellipsises it. That is the same bargain the rest of the module
        // makes: degrade visibly rather than silently.
        let mut left = total;
        let mut emitted = false;
        for (_, width, _) in &mut resolved {
            if *width == 0 {
                continue;
            }
            let gutter = if emitted { GUTTER } else { 0 };
            if left <= gutter {
                *width = 0;
                continue;
            }
            *width = (*width).min(left - gutter);
            if *width > 0 {
                left -= gutter + *width;
                emitted = true;
            }
        }

        Self { resolved }
    }

    /// Whether any column survived.
    pub fn is_empty(&self) -> bool {
        self.resolved.is_empty()
    }

    /// Whether the column with this label is being drawn.
    #[cfg(test)]
    pub fn has(&self, label: &str) -> bool {
        self.resolved
            .iter()
            .any(|(c, w, _)| c.label == label && *w > 0)
    }

    /// The resolved width of a column, or zero if it was dropped.
    ///
    /// For panels that draw something sized to a column — a sparkline, a bar —
    /// and would otherwise have to re-derive the width the grid already
    /// computed. Two copies of that arithmetic drift, and the symptom is a
    /// column that silently renders empty.
    pub fn column_width(&self, label: &str) -> u16 {
        self.resolved
            .iter()
            .find(|(c, _, _)| c.label == label)
            .map_or(0, |(_, w, _)| *w)
    }

    /// The header row.
    ///
    /// Every column gets the same treatment, which used to require deciding
    /// tracking once for the whole row: per column it produced `DONE PRI
    /// T A S K`, where the mixed treatment reads as an accident. Now that the
    /// utility face is bold rather than letterspaced it costs no extra width,
    /// so there is no longer a fit to fail and nothing to decide.
    pub fn header(&self, theme: &Theme) -> Line<'static> {
        let style = Style::default()
            .fg(theme.label)
            .add_modifier(Modifier::BOLD);
        self.line(|column, _| (Cow::Owned(crate::glyphs::utility(column.label)), style))
    }

    /// A data row. Extra cells are ignored; missing cells render blank.
    pub fn row(&self, cells: &[Span<'_>]) -> Line<'static> {
        // Indexed by the column's declared position, not its surviving one,
        // so a dropped column takes its own value with it rather than shifting
        // every later value under the wrong header.
        self.line(|_, declared| match cells.get(declared) {
            Some(span) => (Cow::Borrowed(span.content.as_ref()), span.style),
            None => (Cow::Borrowed(""), Style::default()),
        })
    }

    /// One line of the grid, with `cell` saying what goes in each surviving
    /// column — given the column and its declared position — and in what
    /// style.
    ///
    /// The header and the rows were this loop written out twice, and the
    /// sweep over every grid records that only one of them was wrong the first
    /// time. The gutter, the dropped columns and the fit to each width are
    /// decided here, once, for both.
    fn line<'a>(&self, cell: impl Fn(&Column, usize) -> (Cow<'a, str>, Style)) -> Line<'static> {
        let mut spans = Vec::new();
        for (column, width, declared) in &self.resolved {
            if *width == 0 {
                continue;
            }
            if !spans.is_empty() {
                spans.push(Span::raw(" ".repeat(GUTTER as usize)));
            }
            let (content, style) = cell(column, *declared);
            spans.push(Span::styled(fit(&content, *width, column.align), style));
        }
        Line::from(spans)
    }
}

/// Assemble `parts` into a line that fits `width`, dropping whole parts from
/// the end rather than letting the terminal cut one in half.
///
/// **A line assembled from parts must lose whole parts, never half a value.**
/// This is the same rule [`Grid`] applies to columns, for the many lines in
/// this program that are not tables: a readout, a summary, a settings line.
/// Those were all built at their natural width and handed to a `Paragraph`,
/// which draws what fits and drops the rest on the floor. The terminal has no
/// idea what a value is, so it cuts wherever the edge falls — and a fragment
/// of a value is not a smaller truth, it is a different one. `↑ 6.4 KB` is a
/// total where a rate was meant, `+52.0` is a number nobody holds, and `13 1`
/// under a calendar's THU is a date. All three were on screen at ordinary
/// terminal widths.
///
/// A part is a group of spans that means nothing on its own — a value and its
/// unit, an arrow and the figure it points at, a separator and what follows
/// it. Put the separator at the *front* of the part it introduces, so dropping
/// the part takes the separator with it and no line ends in a dangling `·`.
///
/// When not even the first part fits it is truncated rather than dropped. A
/// blank where a number belongs reads as a broken panel — invariant 11, one
/// scale up — and the ellipsis is what keeps that honest: something was cut,
/// and the reader can see that it was.
pub fn assemble(parts: Vec<Vec<Span<'static>>>, width: u16) -> Line<'static> {
    let width = usize::from(width);
    let mut spans: Vec<Span<'static>> = Vec::new();
    let mut used = 0usize;

    for part in parts {
        let part_width: usize = part.iter().map(|s| walked_width(&s.content)).sum();
        if used + part_width > width {
            // Nothing has been placed and this part is too wide for the line:
            // show as much of it as fits, ellipsised, rather than nothing.
            //
            // Abridged as one value, not span by span. The first version
            // truncated each span into the room left and stopped when the room
            // ran out — so when a span fitted *exactly*, the spans after it
            // were dropped and nothing said so: ` 38` where ` 38%` was meant,
            // the `%` gone without an ellipsis, at three columns. The memory
            // panel's readout sweep found it. The whole part is truncated as
            // one string and then handed back to its spans in order, so the
            // `…` lands wherever the cut falls, boundary or not.
            if spans.is_empty() {
                let whole: String = part.iter().map(|s| s.content.as_ref()).collect();
                let mut abridged = truncate(&whole, width);
                for span in part {
                    if abridged.is_empty() {
                        break;
                    }
                    // This span's share is its own width, or whatever is left
                    // of the abridged text — the ellipsis included — if the cut
                    // fell inside or at the end of it. The width is the walk's
                    // own measure: measured as a plain string it disagrees
                    // with the walk over a control character, and the walk
                    // then ran into the next span.
                    let own = walked_width(&span.content);
                    let rest = abridged.split_off(prefix_fitting(&abridged, own));
                    spans.push(Span::styled(
                        std::mem::replace(&mut abridged, rest),
                        span.style,
                    ));
                }
            }
            break;
        }
        used += part_width;
        spans.extend(part);
    }

    Line::from(spans)
}

/// Parts for [`assemble`] that end in a way out, fitted to `width` so the
/// way out is the last to go: whole parts drop, the ones before it first and
/// from the right, and a narrow row still says how to leave.
///
/// `separator` goes at the front of each part after the first that is kept,
/// so a dropped part takes its separator with it. The way out alone and
/// still too wide is left to `assemble`, which ellipsises it. A prompt's
/// help, a dialog's key row and the task and note forms' keys all fit this
/// way; see `prompt::way_out_last` for the plain-text form.
pub fn way_out_last(
    mut parts: Vec<Vec<Span<'static>>>,
    separator: &Span<'static>,
    width: u16,
) -> Vec<Vec<Span<'static>>> {
    let width = usize::from(width);
    let gap = display_width(&separator.content);
    let row = |parts: &[Vec<Span<'static>>]| {
        parts
            .iter()
            .flatten()
            .map(|span| display_width(&span.content))
            .sum::<usize>()
            + gap * parts.len().saturating_sub(1)
    };
    while parts.len() > 1 && row(&parts) > width {
        parts.remove(parts.len() - 2);
    }
    for part in parts.iter_mut().skip(1) {
        part.insert(0, separator.clone());
    }
    parts
}

/// Pad or truncate `text` to exactly `width` terminal cells.
///
/// Measured in display width rather than characters, so a cell containing a
/// double-width glyph still occupies exactly its column. Truncation appends an
/// ellipsis, so a long value degrades visibly instead of silently pushing its
/// neighbours sideways.
fn fit(text: &str, width: u16, align: Align) -> String {
    let width = usize::from(width);
    if width == 0 {
        return String::new();
    }

    let actual = walked_width(text);
    if actual > width {
        let mut out = truncate(text, width);
        // A double-width character can leave the result a cell short.
        out.push_str(&" ".repeat(width.saturating_sub(walked_width(&out))));
        return out;
    }

    let pad = " ".repeat(width - actual);
    match align {
        Align::Left => format!("{text}{pad}"),
        Align::Right => format!("{pad}{text}"),
    }
}

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

    /// The first part of a line that does not fit is abridged *as a value*:
    /// however its spans are cut, the result ends in `…`. Span by span, a span
    /// that fitted exactly left the ones after it dropped in silence —
    /// ` 38` for ` 38%` at three columns, the unit gone and nothing marking it —
    /// which is the one thing this function exists to prevent.
    #[test]
    fn a_first_part_abridged_at_a_span_boundary_still_says_so() {
        use ratatui::style::Style;
        let part = || {
            vec![
                Span::styled(" 38", Style::default()),
                Span::styled("%", Style::default()),
            ]
        };
        let text = |line: &Line<'static>| -> String {
            line.spans.iter().map(|s| s.content.as_ref()).collect()
        };

        // Exactly at the boundary between the spans.
        let cut = assemble(vec![part()], 3);
        assert_eq!(
            text(&cut),
            " 3\u{2026}",
            "the cut at the span boundary is marked"
        );
        assert_eq!(display_width(&text(&cut)), 3);

        // Inside the first span.
        assert_eq!(text(&assemble(vec![part()], 2)), " \u{2026}");

        // Fits whole: untouched, both spans intact.
        let whole = assemble(vec![part()], 4);
        assert_eq!(text(&whole), " 38%");
        assert_eq!(
            whole.spans.len(),
            2,
            "no spans are merged when nothing is cut"
        );

        // Nothing at all.
        assert_eq!(text(&assemble(vec![part()], 0)), "");
    }

    /// An abridged part gives each span back its own text, in its own style.
    ///
    /// The split used to measure a span as a string and then walk the
    /// abridged text a character at a time, and the two measures disagree:
    /// `☀` with the emoji selector was two cells as a string and one as its
    /// characters, so the walk ran a cell past the span and took the next
    /// one's first letter into the sun's style. Both sides are the walk's
    /// measure now — and the walk takes the sun and its selector as the one
    /// two-cell glyph ratatui draws, so it leaves room for one letter, not
    /// two. The control character holds the walk itself to what ratatui
    /// draws: measured as a one-character string, the way the walk in
    /// `assemble` used to, it is a cell, where ratatui, which never draws
    /// it, makes it none.
    #[test]
    fn an_abridged_part_gives_each_span_its_own_text() {
        use ratatui::style::{Color, Style};
        let (lead_style, rest_style) = (Style::new().fg(Color::Red), Style::new().fg(Color::Blue));
        for (lead, rest) in [("\u{2600}\u{fe0f}", "b\u{2026}"), ("a\u{7}", "bc\u{2026}")] {
            let line = assemble(
                vec![vec![
                    Span::styled(lead, lead_style),
                    Span::styled("bcdef", rest_style),
                ]],
                4,
            );
            let spans: Vec<(&str, Style)> = line
                .spans
                .iter()
                .map(|span| (span.content.as_ref(), span.style))
                .collect();
            assert_eq!(spans, [(lead, lead_style), (rest, rest_style)], "{lead:?}");
            // And never wider than asked for. The bell is a cell to
            // `display_width` and none to ratatui, which never draws it, so
            // the line is measured as it will be drawn: without it.
            let drawn: String = spans
                .iter()
                .flat_map(|(text, _)| text.chars())
                .filter(|c| !c.is_control())
                .collect();
            assert!(display_width(&drawn) <= 4, "{drawn:?} is wider than 4");
        }
    }

    use ratatui::Terminal;
    use ratatui::backend::TestBackend;
    use ratatui::widgets::{Paragraph, Wrap};

    /// The three must agree: a panel sizes itself with `wrapped_height` and
    /// draws with `wrap` or `wrapped`, so a disagreement puts content outside
    /// the box measured for it, or leaves a measured row unused.
    ///
    /// The row count cannot drift any more, since all three consume one
    /// function — but it could once, and for a long time this did not notice.
    /// Every sample was ASCII, and the bug was that `wrapped_height` measured
    /// an over-long word by subtracting `width` a row at a time, which is only
    /// right when every glyph is one cell. The wide glyphs and the widths below
    /// 8 are the part of this test that ever had a chance.
    ///
    /// What can still drift is how a consumer puts the rows together, and
    /// `wrapped` did: it wrote a separator only once something had been
    /// written, so an empty first row read as nothing yet. `"\nabc"` came out
    /// as `"abc"`, one row where two were measured and the blank line the
    /// author wrote gone. No sample began with a newline and nothing compared
    /// `wrapped` with `wrap`; the corpus starts with one about a time in six.
    #[test]
    fn wrapping_produces_exactly_as_many_rows_as_it_measures() {
        let samples = [
            "Wildfire now nine miles away from the French city of Bordeaux, mayor warns",
            "short",
            "",
            "a supercalifragilisticexpialidociousandthensomeword in a line",
            "Europa Clipper returns its first images — and they are extraordinary",
            "line one\nline two is a good deal longer than the first one is",
            // A headline is somebody else's text, and it is not always Latin.
            "\u{4E2D}\u{6587}\u{6807}\u{9898}",
            "\u{65E5}\u{672C}\u{8A9E}\u{306E}\u{30CB}\u{30E5}\u{30FC}\u{30B9}\u{3067}\u{3059}",
            "a\u{1F31E}b\u{1F31E}c",
            "\u{1F31E}\u{1F31E}\u{1F31E}\u{1F31E}",
            "mixed \u{4E2D}\u{6587} and english \u{1F31E} together",
            // A combining mark with no base character, which is a grapheme all
            // the same and measures zero cells.
            "\u{0301}\u{0301}leading marks",
            "blank\n\nline in the middle",
            "\nblank line first",
            "\n\n",
            // A run of spaces at a break, which the break takes whole.
            "Done.  Next one.   And   another",
            "ab  cdef   ",
            // Whitespace that is not U+0020, which a break takes too.
            "Done.\u{a0} Next\u{a0}\u{a0}one \u{a0} \u{a0}and\u{a0}",
            "今日は晴れ\u{3000}明日は雨\u{3000}\u{3000}です\u{3000}",
            "tab\t \tand\t\tcr\r \r\n\u{2003}em\u{2003} space",
            " \u{301}mark on a space  \u{3000}\u{301}",
        ];
        let corpus = samples
            .iter()
            .map(ToString::to_string)
            .chain(crashing_corpus());
        for text in corpus {
            for width in 1..40u8 {
                let rows = wrap(&text, usize::from(width));
                assert_eq!(
                    u16::try_from(rows.len()).unwrap(),
                    wrapped_height(&text, u16::from(width)),
                    "{text:?} at {width}"
                );
                assert_eq!(
                    wrapped(&text, u16::from(width)),
                    rows.join("\n"),
                    "{text:?} at {width}"
                );
                // Styled, the same rows, but for one glyph wider than its row,
                // which `wrap_line` collapses to an ellipsis on purpose.
                // One span, since `Line::from` a `&str` drops its newlines.
                let line = Line::from(Span::raw(text.as_str()));
                let styled: Vec<String> = wrap_line(&line, width.into())
                    .iter()
                    .map(|row| row.spans.iter().map(|s| s.content.as_ref()).collect())
                    .collect();
                assert_eq!(styled.len(), rows.len(), "{text:?} at {width}");
                for (styled, row) in styled.iter().zip(&rows) {
                    if walked_width(row) <= usize::from(width) {
                        assert_eq!(styled, row, "{text:?} at {width}");
                    }
                }
            }
        }
    }

    /// An over-long run of wide glyphs consumes the row exactly, and the
    /// remainder is then empty. Emitting it anyway appended a blank row that
    /// nothing asked for — `wrap("🌞🌞", 1)` came out as three rows, the last
    /// one empty, which in the news panel is a wasted line at the bottom of
    /// every headline that ends on a boundary.
    #[test]
    fn a_row_consumed_exactly_leaves_no_blank_behind() {
        assert_eq!(wrap("\u{1F31E}\u{1F31E}", 1), ["\u{1F31E}", "\u{1F31E}"]);
        assert_eq!(wrap("abcdef", 3), ["abc", "def"]);
        assert_eq!(wrap("\u{65E5}\u{672C}", 2), ["\u{65E5}", "\u{672C}"]);

        // But a blank line the author actually wrote still gets its row.
        assert_eq!(wrap("a\n\nb", 4), ["a", "", "b"]);
        assert_eq!(wrap("", 4), [""]);
        assert_eq!(wrap("\n", 4), [""]);
    }

    /// A word exactly as wide as the row was measured with the space after
    /// it, so it took the over-long path and was broken before that space —
    /// which was then carried to the next row. Where the next word fitted
    /// beside it the row came out indented by a cell; where it did not, the
    /// space stood on a row of its own, a blank line in the middle of a
    /// sentence. Found by the empty-state sweeps, at the widths where `tasks`
    /// or `notes` is the whole row.
    #[test]
    fn a_word_that_fills_the_row_leaves_its_space_behind() {
        assert_eq!(wrap("abcde fghij", 5), ["abcde", "fghij"]);
        assert_eq!(wrap("abcde fgh", 5), ["abcde", "fgh"]);
        assert_eq!(wrap("abcde ", 5), ["abcde"]);
        assert_eq!(
            wrap("No tasks yet. Press", 5),
            ["No ", "tasks", "yet. ", "Press"]
        );
        assert_eq!(wrapped_height("abcde fghij", 5), 2);

        // Two spaces after a full stop are ordinary in a typed note and in a
        // headline, and only the first belongs to the word before them: each
        // further space arrives as a word of its own. The first fix took the
        // one space and left the rest to stand on a row by themselves, or to
        // indent the next. The break takes the whole run, wherever it falls —
        // inside a word too long for its row, or between two words.
        assert_eq!(wrap("abcde  fghij", 5), ["abcde", "fghij"]);
        assert_eq!(wrap("Done.  Next one", 5), ["Done.", "Next ", "one"]);
        assert_eq!(wrap("abcde  fgh", 5), ["abcde", "fgh"]);
        assert_eq!(wrap("ab  cdef", 3), ["ab ", "cde", "f"]);
        assert_eq!(wrap("ab   ", 3), ["ab "]);
        assert_eq!(wrapped_height("abcde  fghij", 5), 2);
        assert_eq!(wrapped_height("ab  cdef", 3), 3);

        // Whitespace is not only U+0020. A no-break space typed for the second
        // space after a full stop (`&#160;` in a feed), an ideographic space
        // in Japanese, which has no other spaces for a row to break at, and a
        // tab each stood on a row of their own or indented the next.
        assert_eq!(wrap("Done.\u{a0} Next one", 5), ["Done.", "Next ", "one"]);
        assert_eq!(wrap("abcde\u{a0}fgh", 5), ["abcde", "fgh"]);
        assert_eq!(
            wrap("今日は晴れ\u{3000}明日は雨", 10),
            ["今日は晴れ", "明日は雨"]
        );
        assert_eq!(wrap("今日は晴れ\u{3000}", 10), ["今日は晴れ"]);
        assert_eq!(wrap("abcd \t efgh", 5), ["abcd ", "efgh"]);
        assert_eq!(wrap("abcde \u{3000}fgh", 5), ["abcde", "fgh"]);
        assert_eq!(wrapped_height("今日は晴れ\u{3000}", 10), 1);
        // A mark joined to a space is a glyph that draws, and stays.
        assert_eq!(wrap("abcde \u{301}fg", 5), ["abcde", "\u{301}fg"]);

        // Spaces no break produced are the author's, and keep their cells: an
        // indent at the start of a line, and a line of nothing else.
        assert_eq!(wrap("  ab\n  cd", 5), ["  ab", "  cd"]);
        assert_eq!(wrap("\u{3000}ab\n\tcd", 5), ["\u{3000}ab", "\tcd"]);
        assert_eq!(wrap("a\n   \nb", 5), ["a", "   ", "b"]);
        assert_eq!(wrap("a\n\nb", 5), ["a", "", "b"]);

        // Styled text breaks in the same places, its spans intact.
        for spans in [
            vec![Span::raw("abcde "), Span::raw("fghij")],
            vec![Span::raw("abcde  "), Span::raw("fghij")],
            vec![Span::raw("abcde "), Span::raw(" fghij")],
        ] {
            let line = Line::from(spans);
            let rows: Vec<String> = wrap_line(&line, 5)
                .iter()
                .map(|row| row.spans.iter().map(|s| s.content.as_ref()).collect())
                .collect();
            assert_eq!(rows, ["abcde", "fghij"], "{line:?}");
        }
    }

    /// A glyph wider than the whole line fits nowhere, so "take as many
    /// characters as fit" takes none, consumes nothing, and loops for ever.
    /// That is a hang — the dashboard freezes and has to be killed — and it is
    /// reachable by any CJK or emoji headline in a narrow panel.
    #[test]
    fn a_glyph_wider_than_the_line_does_not_hang() {
        for text in [
            "\u{1F31E}\u{1F31E}",
            "\u{4E2D}\u{6587}\u{6807}\u{9898}",
            "a\u{1F31E}b",
        ] {
            for width in 1..4usize {
                let out = wrap(text, width);
                assert!(
                    out.len() <= text.chars().count() + 1,
                    "`{text}` at {width} produced {} lines",
                    out.len()
                );
                // Every character survives; the line may exceed the width by a
                // cell, because a terminal cannot draw half a wide glyph.
                let joined: String = out.concat();
                assert_eq!(joined, text, "at {width}");
            }
        }
    }

    /// The corpus that crashes ratatui: narrow and wide glyphs at every offset,
    /// spaces, newlines, and a combining mark with no base character.
    ///
    /// Deterministic and hand-rolled for the same reason as `ical`'s — what
    /// matters is that every fragment is in it because of something the
    /// wrapper does, not that the bytes are random.
    fn crashing_corpus() -> Vec<String> {
        let alphabet = ["a", "\u{1F31E}", "\u{65E5}", " ", "\n", "\u{0301}"];
        let mut seed = 0x2545_F491_4F6C_DD1Du64;
        let mut next = move || {
            seed ^= seed << 13;
            seed ^= seed >> 7;
            seed ^= seed << 17;
            seed
        };
        (0..600)
            .map(|_| {
                let len = (next() % 9) as usize + 1;
                (0..len)
                    .map(|_| alphabet[(next() % alphabet.len() as u64) as usize])
                    .collect()
            })
            .collect()
    }

    fn renders_without_panicking(paragraph: impl Fn() -> Paragraph<'static>, width: u16) -> bool {
        let mut terminal = Terminal::new(TestBackend::new(width, 12)).unwrap();
        std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| {
            terminal
                .draw(|frame| frame.render_widget(paragraph(), frame.area()))
                .unwrap();
        }))
        .is_ok()
    }

    /// Nothing outside this module may hand text to ratatui's word wrapper.
    ///
    /// [`wrapped`] exists because that wrapper panics on text mirador did not
    /// write, and the fix was to route every such site through here. The panels
    /// that were fixed have their own tests — `a_note_full_of_wide_glyphs_draws_at_every_width`
    /// is the model — but those guard the sites that were *known* about. A new
    /// panel, or a new render site in an old one, would reintroduce the crash
    /// with nothing to catch it.
    ///
    /// This is that catch, and it is structural rather than behavioural on
    /// purpose. A geometry sweep was tried first and abandoned: to trigger the
    /// fault a specific string has to meet a specific pane width, panels
    /// sub-divide their own area, and only one note's body is ever drawn — so
    /// the sweep passed cheerfully with the defect reintroduced. Counting the
    /// call sites cannot miss.
    ///
    /// One is allowed: the delete confirmation, whose one variable line is
    /// truncated to the width before it gets there. The help overlay used to
    /// be the second, but external panel bindings made its text plugin-owned;
    /// it now comes through [`wrap_line`] instead.
    #[test]
    fn only_the_known_delete_confirmation_uses_ratatuis_own_wrapper() {
        // Split so this test's own source is not a match.
        let needle = concat!(".wr", "ap(");

        let mut found = Vec::new();
        for (path, text) in crate::docs::source_files("src") {
            // This module's own tests use the wrapper deliberately, to prove
            // it still panics. Testing the thing is not using it.
            if path == std::path::Path::new("grid.rs") {
                continue;
            }
            let name = path.file_name().unwrap_or_default().to_string_lossy();
            for line in text.lines() {
                let trimmed = line.trim_start();
                // Prose about the rule is not a use of it.
                if trimmed.starts_with("//") {
                    continue;
                }
                if line.contains(needle) {
                    found.push(format!("{name}: {}", trimmed.trim_end()));
                }
            }
        }
        found.sort();

        assert_eq!(
            found.len(),
            1,
            "expected exactly one use of ratatui's wrapper — the delete \
             confirmation — and found {}:\n  {}\n\n\
             If this is a new site rendering text mirador did not write, wrap it \
             with `grid::wrapped` instead: ratatui's wrapper panics on a leading \
             combining mark, and on a double-width glyph in a word too long for \
             a two-cell area, which is ordinary prose. If it really is text this \
             program wrote itself, widen this count and say why.",
            found.len(),
            found.join("\n  ")
        );
        assert!(
            found.iter().any(|f| f.starts_with("todo.rs:")),
            "the delete confirmation's wrap went missing: {found:?}"
        );
    }

    /// Every multi-span line a widget builds by hand is accounted for.
    ///
    /// The clipping pass found nine lines assembled from parts and handed to a
    /// `Paragraph` at their natural width, in nine different modules, each
    /// written as if the pane would be wide enough. Four of them were cutting
    /// values at ordinary terminal sizes — the upload rate reduced to a bare
    /// `↑`, `humidity` with no figure, `25m focus ·` trailing into nothing,
    /// `+52.0`. The defect was not in any one of them; it was that nothing
    /// asked the question.
    ///
    /// So this counts the remaining hand-built composite lines and names why
    /// each is safe. It is a coarse instrument — `Line::from(vec![…])` is not
    /// itself wrong — and that is the intent: a new one has to be justified out
    /// loud, here, rather than discovered on somebody's narrow terminal.
    ///
    /// The alternative was a render-level sweep, and it was tried first. It
    /// cannot work: a buffer records what the terminal *kept*, so an overflowing
    /// line and a line that happens to end there are the same bytes. Overflow
    /// has to be caught where the line is built, which makes the call site the
    /// only thing there is to count.
    #[test]
    fn every_hand_built_composite_line_in_a_widget_is_accounted_for() {
        // Each entry is a module and exactly how many composite lines it
        // builds.
        // A line is exempt only when its width is *already* bounded — every
        // span truncated to a computed room, or the whole thing measured before
        // it is built.
        const ALLOWED: &[(&str, usize, &str)] = &[
            (
                "battery.rs",
                1,
                "the cell's caps are `body + 2` wide, and `body` is cut to the \
                 width less the chrome beside it before anything is built",
            ),
            (
                "todo.rs",
                1,
                "the priority marker: three short fixed strings",
            ),
            (
                "watchlog.rs",
                2,
                "entry text truncated; the rule line is built to width",
            ),
        ];

        // Split so this test's own source is not a match.
        let needle = concat!("Line::fr", "om(vec![");
        let mut found = Vec::new();
        // External panel output is bounded by the same invariant as an in-tree
        // widget. Sweep both implementation trees so moving composition behind
        // the process boundary cannot make this guard pass vacuously.
        for directory in ["src/widgets", "src/plugin"] {
            for (path, text) in crate::docs::source_files(directory) {
                // Tests build lines to assert about them, which is not
                // drawing one.
                let body = text.split("mod tests").next().unwrap_or(&text);
                for line in body.lines() {
                    if line.trim_start().starts_with("//") {
                        continue;
                    }
                    if line.contains(needle) {
                        found.push(
                            path.file_name()
                                .unwrap_or_default()
                                .to_string_lossy()
                                .to_string(),
                        );
                    }
                }
            }
        }

        // Both directions, and each with its own advice, because the two
        // failures want opposite fixes. Fewer than allowed is an allowance to
        // retire: one nothing uses is a hole the next line in that module walks
        // through without anyone being asked about it, and while this checked
        // only `actual <= allowed` two had opened — `agenda.rs` kept one for a
        // row #239 had moved onto `assemble`, and `notes.rs` was allowed two
        // lines and built one. It is also what makes a sweep that reads nothing
        // fail, rather than pass by finding nothing to object to. More than
        // allowed is a new line to justify, and that is the loop after this
        // one: a single `assert_eq!` here caught it first and told the author
        // to raise the count to match.
        for (module, allowed, _) in ALLOWED {
            let actual = found.iter().filter(|f| f == module).count();
            assert!(
                actual >= *allowed,
                "{module} is allowed {allowed} composite line(s) and builds only \
                 {actual}. Bring the count down to what is there, or take the \
                 entry out: an allowance that outlives its line passes the next \
                 one unexamined."
            );
        }
        for name in &found {
            let allowed = ALLOWED
                .iter()
                .find(|(module, _, _)| module == name)
                .map_or(0, |(_, count, _)| *count);
            let actual = found.iter().filter(|f| *f == name).count();
            assert!(
                actual <= allowed,
                "{name} builds {actual} composite line(s) by hand; {allowed} are \
                 accounted for.\n\n\
                 A line assembled from parts and drawn at its natural width is \
                 cut by the terminal, which cannot tell a value from a fragment \
                 — `↑ 6.4 KB` where a rate was meant, `+52.0` where a price was. \
                 Build it with `grid::assemble` so whole parts are dropped \
                 instead, or bound every span yourself and account for the line \
                 in `ALLOWED` with the reason."
            );
        }
    }

    /// The reason [`wrapped`] exists, pinned rather than described.
    ///
    /// ratatui's own word wrapper indexes past the end of the buffer and
    /// panics, which for a dashboard is a crash rather than a misdraw. Two ways
    /// in: a double-width glyph inside a word too long for a two-cell area, and
    /// a leading combining mark, which throws the accounting off at any width.
    /// Neither needs unusual input — emoji in a note is ordinary.
    ///
    /// Reported upstream as <https://github.com/ratatui/ratatui/issues/2679>.
    ///
    /// **If this test starts failing, ratatui has fixed it.** That is good
    /// news, and the thing to do is check whether `wrapped` can go, not to
    /// delete the assertion. The bound lives in a dependency and would leave
    /// with it.
    #[test]
    fn ratatuis_own_wrapper_is_why_this_module_wraps_first() {
        let hook = std::panic::take_hook();
        std::panic::set_hook(Box::new(|_| {}));
        let straddles_a_two_cell_row = renders_without_panicking(
            || Paragraph::new("a\u{1F31E}b").wrap(Wrap { trim: false }),
            2,
        );
        let leading_combining_mark = renders_without_panicking(
            || {
                Paragraph::new("\u{0301} \u{1F31E}\u{65E5}\u{65E5}\u{65E5}\u{1F31E}\u{1F31E}a")
                    .wrap(Wrap { trim: false })
            },
            8,
        );
        std::panic::set_hook(hook);

        assert!(
            !straddles_a_two_cell_row && !leading_combining_mark,
            "ratatui no longer panics here (two-cell row: {}, combining mark: {}). \
             Check whether `grid::wrapped` is still needed before removing this.",
            !straddles_a_two_cell_row,
            !leading_combining_mark
        );
    }

    /// And the fix: the same corpus, wrapped here and handed to a `Paragraph`
    /// with no `Wrap`, draws at every width without bringing the dashboard
    /// down.
    #[test]
    fn pre_wrapping_survives_what_crashes_ratatui() {
        let hook = std::panic::take_hook();
        std::panic::set_hook(Box::new(|_| {}));
        let mut crashed = Vec::new();
        for text in crashing_corpus() {
            for width in 1..12u16 {
                let wrapped_text = wrapped(&text, width);
                if !renders_without_panicking(|| Paragraph::new(wrapped_text.clone()), width) {
                    crashed.push(format!("{text:?} at {width}"));
                }
            }
        }
        std::panic::set_hook(hook);
        assert!(crashed.is_empty(), "still panics: {crashed:?}");
    }

    #[test]
    fn no_wrapped_line_is_wider_than_asked_for() {
        let text = "Wildfire now nine miles away from the French city of Bordeaux";
        for width in 8..40usize {
            for line in wrap(text, width) {
                assert!(
                    display_width(&line) <= width,
                    "`{line}` is wider than {width}"
                );
            }
        }
    }

    /// A glyph too wide for its row is carried whole, not a character at a
    /// time. Stepped by character, `❤\u{fe0f}` in a one-cell column left the
    /// heart on one row and its emoji selector alone on the next — a row
    /// that draws nothing, and that `wrapped_height` counts, so a panel
    /// sized by it reserved a blank row per heart. A joined family breaks
    /// the same way, into its people and its joiners.
    #[test]
    fn a_glyph_too_wide_for_its_row_keeps_its_selector_and_joins() {
        let heart = "\u{2764}\u{fe0f}";
        let family = "\u{1f468}\u{200d}\u{1f469}\u{200d}\u{1f467}";
        for glyph in [heart, family] {
            let text = glyph.repeat(2);
            assert_eq!(wrap(&text, 1), [glyph, glyph], "{text:?}");
            assert_eq!(wrapped_height(&text, 1), 2, "{text:?}");
        }
    }

    #[test]
    fn styled_wrapping_uses_the_width_ratatui_will_render() {
        let line = Line::from(vec![
            Span::styled("👩", Style::default().add_modifier(Modifier::BOLD)),
            Span::styled(
                "\u{200d}💻",
                Style::default().add_modifier(Modifier::ITALIC),
            ),
        ]);
        let wrapped = wrap_line(&line, 2);
        assert_eq!(wrapped.len(), 1);
        let rendered_width: usize = wrapped[0]
            .spans
            .iter()
            .map(|span| display_width(&span.content))
            .sum();
        assert!(rendered_width <= 2, "rendered width was {rendered_width}");
    }

    /// A line's own style belongs to every row it wraps to, whichever way the
    /// row was built.
    ///
    /// `wrap_line` builds a row one of two ways: the source spans copied
    /// across, or — when a joined emoji split by a style boundary would draw
    /// wider than it measures — the row collapsed into one truncated span. Only
    /// the first applied `line.style`, so a red line came back with its
    /// collapsed rows in the terminal's own colour. Latent: nothing that
    /// reaches this sets a line style today (the help overlay and plugin
    /// output both build a bare `Line::from`), so the first caller to style a
    /// line would have met it on the one row that also held an emoji.
    #[test]
    fn a_wrapped_line_keeps_its_line_style_on_every_branch() {
        let red = Style::default().fg(ratatui::style::Color::Red);
        let bold = Style::default().add_modifier(Modifier::BOLD);
        let italic = Style::default().add_modifier(Modifier::ITALIC);

        let copied = wrap_line(
            &Line::from(vec![
                Span::styled("a", bold),
                Span::raw("b"),
                Span::raw("cd"),
            ])
            .style(red),
            2,
        );
        let collapsed = wrap_line(
            &Line::from(vec![
                Span::styled("👩", bold),
                Span::styled("\u{200d}💻", italic),
            ])
            .style(red),
            2,
        );

        // Each half has to have taken its own branch, or this checks one
        // branch twice and passes for the wrong reason. A row of one span
        // cannot say which it took, since collapsing it builds the same span,
        // so the copied half's first row is two: only copying keeps both.
        assert_eq!(copied.len(), 2, "{copied:?}");
        assert_eq!(
            copied[0].spans.len(),
            2,
            "a row that fits must take the copying branch: {copied:?}"
        );
        assert_eq!(copied[1].spans[0].style, Style::default(), "{copied:?}");
        assert_eq!(collapsed.len(), 1, "{collapsed:?}");
        assert_eq!(
            collapsed[0].spans.len(),
            1,
            "the joined emoji must take the collapsing branch: {collapsed:?}"
        );
        assert_eq!(collapsed[0].spans[0].style, bold, "{collapsed:?}");

        for row in copied.iter().chain(&collapsed) {
            assert_eq!(row.style, red, "a row lost its line's style: {row:?}");
        }
    }

    #[test]
    fn styled_wrapping_treats_embedded_line_endings_as_guarded_hard_breaks() {
        let first = Style::default().add_modifier(Modifier::BOLD);
        let second = Style::default().add_modifier(Modifier::ITALIC);
        let third = Style::default().add_modifier(Modifier::UNDERLINED);
        let line = Line::from(vec![
            Span::styled("ab\r", first),
            Span::styled("\né\n", second),
            Span::styled("界", third),
        ]);

        let wrapped = wrap_line(&line, 10);
        let text: Vec<String> = wrapped
            .iter()
            .map(|row| row.spans.iter().map(|span| span.content.as_ref()).collect())
            .collect();
        assert_eq!(text, ["ab", "é", "界"]);
        assert_eq!(wrapped[0].spans[0].style, first);
        assert_eq!(wrapped[1].spans[0].style, second);
        assert_eq!(wrapped[2].spans[0].style, third);
    }

    /// The one exception, and it is deliberate: a single glyph that cannot fit
    /// is emitted anyway rather than dropped or looped on. It overruns by a
    /// cell, which a terminal handles and an infinite loop does not.
    #[test]
    fn only_an_unfittable_glyph_may_overrun_and_only_by_itself() {
        let out = wrap("\u{1F31E}\u{1F31E}", 1);
        for line in &out {
            assert!(
                line.chars().count() <= 1,
                "an overrunning line holds one glyph and no more: `{line}`"
            );
        }
    }

    fn columns() -> Vec<Column> {
        vec![
            Column::fixed("hour", 5),
            Column::flex("sky", 1),
            Column::fixed("temp", 6).right(),
            Column::fixed("rain", 5).right().drops_below(40),
        ]
    }

    fn width_of(line: &Line<'_>) -> usize {
        line.spans.iter().map(|s| display_width(&s.content)).sum()
    }

    /// Every column set in the program, so the check below is about mirador
    /// rather than about a fixture written to pass it.
    ///
    /// Kept honest by `every_grid_in_the_program_is_on_this_list`, which counts
    /// the declarations in the tree. A grid that is not here is not checked,
    /// and an unchecked grid is what this whole module exists to prevent.
    const EVERY_GRID: &[(&str, &[Column])] = &[
        ("calculator", crate::widgets::calculator::COLUMNS),
        ("clocks", crate::widgets::clocks::COLUMNS),
        ("clocks", crate::widgets::clocks::COLUMNS_MERIDIEM),
        ("keymap_dialog", crate::keymap_dialog::COLUMNS),
        ("notes", crate::widgets::notes::COLUMNS),
        ("stocks", crate::widgets::stocks::COLUMNS),
        ("temperature", crate::widgets::temperature::COLUMNS),
        ("todo", crate::widgets::todo::COLUMNS),
        ("weather", crate::widgets::weather::COLUMNS),
    ];

    /// A grid must never build a row wider than the width it was resolved for.
    ///
    /// The one property that matters, and the one nothing checked. A row that
    /// overflows is not drawn wrong — it is drawn *by the terminal*, which
    /// keeps the cells that fit and discards the rest without saying so. The
    /// reader gets a value with its tail missing and no way to tell.
    ///
    /// Swept over every width rather than the handful a panel is usually given,
    /// because the widths that broke this were the ones nobody pictures: a
    /// tiling window manager quartering a screen, a pane dragged narrow. Both
    /// the header and a row are measured — they were built by separate loops,
    /// and only one of them was wrong the first time. They share `Grid::line`
    /// now, but not their content, and either could still overflow alone.
    #[test]
    fn no_grid_in_the_program_ever_overflows_its_width() {
        let cells = [
            Span::raw("wwwwwwwwwwwwwwwwwwww"),
            Span::raw("12:34:56"),
            Span::raw("日本語日本語"),
            Span::raw("🌞🌞🌞"),
            Span::raw("+52.07"),
            Span::raw("x"),
        ];
        for (name, columns) in EVERY_GRID {
            for total in 0u16..=200 {
                let grid = Grid::new(columns, total);
                let header = width_of(&grid.header(&Theme::default()));
                let row = width_of(&grid.row(&cells));
                assert!(
                    header <= usize::from(total),
                    "{name}'s header is {header} cells wide in a {total}-cell grid; \
                     the terminal will cut the overhang off a label without saying so"
                );
                assert!(
                    row <= usize::from(total),
                    "{name} builds a {row}-cell row for a {total}-cell grid. \
                     The overhang is not dropped by mirador, it is dropped by the \
                     terminal — so the last value on the row loses its tail and \
                     still reads as a whole number. Give the column a \
                     `drops_below` threshold that suits it."
                );
            }
        }
    }

    /// The rule [`assemble`] exists for, stated as the property.
    #[test]
    fn an_assembled_line_never_exceeds_the_width_it_was_given() {
        let parts = vec![
            vec![Span::raw("12.3"), Span::raw("% "), Span::raw("LOAD")],
            vec![Span::raw("   40s")],
            vec![Span::raw("   \u{2191} 6.4 KB/s")],
            vec![Span::raw("   \u{65E5}\u{672C}\u{8A9E}")],
            vec![Span::raw("   \u{1F31E}\u{1F31E}")],
        ];
        for width in 0u16..=60 {
            let line = assemble(parts.clone(), width);
            assert!(
                width_of(&line) <= usize::from(width),
                "assemble produced {} cells for a width of {width}",
                width_of(&line)
            );
        }
    }

    /// A part is all-or-nothing, which is the whole point of the function.
    ///
    /// Checked on the exact boundary rather than at a comfortable width: one
    /// cell short of fitting is where a hand-rolled version drops a character
    /// instead of a value, and every site this replaced was hand-rolled.
    #[test]
    fn a_part_that_does_not_fit_is_dropped_whole_rather_than_cut() {
        let parts = vec![
            vec![Span::raw("\u{2193} 6.4 KB/s")],
            vec![Span::raw("   \u{2191} 1.2 MB/s")],
        ];
        let whole = width_of(&assemble(parts.clone(), 60));
        assert_eq!(whole, 23, "the fixture should need 23 cells");

        // One cell short of the pair: the second reading goes, and its arrow
        // and separator go with it. An arrow left standing over nothing reads
        // as a value of zero.
        let line = assemble(parts.clone(), 22);
        let text: String = line.spans.iter().map(|s| s.content.to_string()).collect();
        assert_eq!(text, "\u{2193} 6.4 KB/s");

        // And exactly at the pair's width, nothing is given up at all.
        assert_eq!(width_of(&assemble(parts, 23)), 23);
    }

    /// A first part too wide to fit is ellipsised, not dropped.
    ///
    /// The alternative is a blank row where a reading belongs, which reads as a
    /// broken panel rather than a narrow one — invariant 11 one scale up. The
    /// `…` is what keeps it honest: the reader can see something was cut.
    #[test]
    fn a_lone_part_too_wide_to_fit_is_ellipsised_rather_than_dropped() {
        let parts = vec![vec![Span::raw("^GSPC: network access is refused")]];
        let line = assemble(parts, 12);
        let text: String = line.spans.iter().map(|s| s.content.to_string()).collect();
        assert!(
            text.ends_with('\u{2026}'),
            "an abridged message must say so, got {text:?}"
        );
        assert!(display_width(&text) <= 12);
        assert!(!text.is_empty(), "a blank line reads as a broken panel");
    }

    /// The list above has to name every grid, or the sweep passes by not
    /// looking.
    ///
    /// Counting declarations rather than checking each one by hand: the same
    /// shape as the guard on ratatui's wrapper, and for the same reason. A
    /// registry nothing reconciles with the tree is a registry that quietly
    /// stops being complete, and the failure mode is silence.
    #[test]
    fn every_grid_in_the_program_is_on_this_list() {
        let mut found = Vec::new();
        for (path, text) in crate::docs::source_files("src") {
            // Counted, not merely detected: a module can declare more than
            // one column set, and the clock does (#265).
            let declared = text.matches(concat!(": &[", "Column] = &[")).count();
            for _ in 0..declared {
                found.push(path.file_stem().unwrap().to_string_lossy().into_owned());
            }
        }
        found.sort();

        let mut listed: Vec<String> = EVERY_GRID.iter().map(|(n, _)| (*n).to_string()).collect();
        listed.sort();

        assert_eq!(
            found, listed,
            "the source declares grids {found:?} but EVERY_GRID names {listed:?}.\n\n\
             Add the new one to EVERY_GRID. Until it is there, \
             no_grid_in_the_program_ever_overflows_its_width does not cover it, \
             and it will pass anyway — which is the failure this check exists \
             to make impossible."
        );
    }

    #[test]
    fn a_grid_fills_its_width_exactly() {
        for total in [20u16, 33, 40, 80, 200] {
            let grid = Grid::new(&columns(), total);
            let header = grid.header(&Theme::default());
            assert_eq!(
                width_of(&header),
                total as usize,
                "header did not fill width {total}"
            );
        }
    }

    #[test]
    fn every_row_is_the_same_width_as_the_header() {
        let grid = Grid::new(&columns(), 60);
        let header = width_of(&grid.header(&Theme::default()));
        for cells in [
            vec![],
            vec![Span::raw("14:00")],
            vec![
                Span::raw("14:00"),
                Span::raw("partly cloudy"),
                Span::raw("72°"),
                Span::raw("20%"),
            ],
            // More cells than columns must not widen the row.
            vec![
                Span::raw("a"),
                Span::raw("b"),
                Span::raw("c"),
                Span::raw("d"),
                Span::raw("e"),
                Span::raw("f"),
            ],
        ] {
            assert_eq!(width_of(&grid.row(&cells)), header);
        }
    }

    #[test]
    fn optional_columns_drop_when_the_grid_is_narrow() {
        let wide = Grid::new(&columns(), 80);
        assert!(wide.has("rain"));

        let narrow = Grid::new(&columns(), 30);
        assert!(!narrow.has("rain"), "rain should drop below its threshold");
        assert!(narrow.has("hour"), "required columns must survive");
    }

    /// Fixed columns can exceed a tiny total, and the row must still not
    /// overflow the area it is drawn into. This asserted `>= 4`, the
    /// direction of the overflow it is named against, so a row of twelve —
    /// what the fixed columns add up to before the clamp — passed it.
    #[test]
    fn a_grid_with_no_room_is_cut_to_exactly_its_width() {
        let grid = Grid::new(&columns(), 4);
        let row = grid.row(&[Span::raw("14:00")]);
        assert_eq!(
            width_of(&row),
            4,
            "a grid narrower than its fixed columns is cut to the width it was given"
        );
    }

    #[test]
    fn an_empty_column_list_yields_an_empty_grid() {
        let grid = Grid::new(&[], 40);
        assert!(grid.is_empty());
        assert_eq!(width_of(&grid.row(&[Span::raw("x")])), 0);
    }

    #[test]
    fn flex_columns_split_the_leftover_space_by_weight() {
        let cols = [
            Column::fixed("a", 10),
            Column::flex("b", 1),
            Column::flex("c", 3),
        ];
        let grid = Grid::new(&cols, 50);
        let widths: Vec<u16> = grid.resolved.iter().map(|(_, w, _)| *w).collect();
        assert_eq!(widths[0], 10);
        // 50 - 10 fixed - 2 gutters = 38 spare, split 1:3.
        assert_eq!(widths[1] + widths[2], 38);
        assert!(
            widths[2] > widths[1] * 2,
            "weight 3 should dominate weight 1"
        );
    }

    #[test]
    fn fit_pads_and_aligns() {
        assert_eq!(fit("ab", 5, Align::Left), "ab   ");
        assert_eq!(fit("ab", 5, Align::Right), "   ab");
        assert_eq!(fit("", 3, Align::Left), "   ");
        assert_eq!(fit("abc", 3, Align::Left), "abc");
    }

    #[test]
    fn fit_truncates_with_an_ellipsis_on_char_boundaries() {
        assert_eq!(fit("abcdef", 4, Align::Left), "abc…");
        // Each CJK character is two cells, so only one fits before the
        // ellipsis in a three-cell column.
        assert_eq!(display_width(&fit("日本語テスト", 3, Align::Left)), 3);
        assert_eq!(fit("abc", 1, Align::Left), "…");
        assert_eq!(fit("abc", 0, Align::Left), "");
    }

    /// A cut is no wider than asked for when a glyph is a sequence of
    /// characters. `❤` is one cell and its emoji selector none, so the walk
    /// counted `❤\u{fe0f}` as one cell where ratatui draws the pair as one
    /// two-cell grapheme: `❤️❤️❤️…` came back for four cells and took seven.
    /// Measured by what ratatui draws, not by this module's own measure,
    /// which is the thing that was wrong; through `truncate`, `fit` and the
    /// abridged first part of `assemble`, which all cut with the same walk.
    ///
    /// The malformed sequences are what a walk joining by hand gets wrong: a
    /// joiner after a skin tone, a keycap or a flag joins nothing to
    /// ratatui, which draws `🏽\u{200d}👩` as two glyphs in four cells, while
    /// the walk took it as one in two and cut a line two cells over. Its
    /// whole-string measure was wrong the same way, so a text said to fit
    /// whole did not.
    #[test]
    fn a_cut_through_emoji_sequences_is_no_wider_than_asked_for() {
        use ratatui::buffer::Buffer;
        use ratatui::layout::Rect;
        let drawn = |text: &str| -> usize {
            let mut buffer = Buffer::empty(Rect::new(0, 0, 200, 1));
            usize::from(buffer.set_stringn(0, 0, text, 200, Style::default()).0)
        };
        let glyphs = [
            "\u{2764}\u{fe0f}",           // ❤️, a selector making one cell two
            "\u{2600}\u{fe0f}",           // ☀️, the weather's own
            "\u{1f469}\u{200d}\u{1f4bb}", // 👩‍💻, a joined pair
            "\u{1f468}\u{200d}\u{1f469}\u{200d}\u{1f467}", // 👨‍👩‍👧
            "\u{1f44d}\u{1f3fd}",         // 👍🏽, a skin tone
            "\u{31}\u{fe0f}\u{20e3}",     // 1️⃣, a keycap
            "a",
            "\u{754c}", // 界
            // Malformed: a joiner after something that is not a pictograph
            // joins nothing, so ratatui draws the two sides as two glyphs.
            "\u{1f3fd}\u{200d}\u{1f469}",              // 🏽, ZWJ, 👩
            "\u{31}\u{fe0f}\u{20e3}\u{200d}\u{1f469}", // 1️⃣, ZWJ, 👩
            "\u{1f1ef}\u{1f1f5}\u{200d}\u{1f469}",     // 🇯🇵, ZWJ, 👩
            "a\u{1f3fd}\u{200d}\u{1f469}",             // a, 🏽, ZWJ, 👩
            // A halfwidth voiced mark: zero cells to `unicode-width`, one to
            // ratatui, which draws it apart from the kana it extends.
            "\u{ff76}\u{ff9e}", // ガ
        ];
        let mut texts: Vec<String> = glyphs.iter().map(|g| g.repeat(5)).collect();
        texts.extend(glyphs.iter().map(|g| format!("ab{g}cd{g}{g}ef")));
        texts.push(glyphs.concat());

        let mut cut = 0;
        for text in &texts {
            for width in 1..=14usize {
                let truncated = truncate(text, width);
                assert!(
                    drawn(&truncated) <= width,
                    "truncate({text:?}, {width}) = {truncated:?} draws {}",
                    drawn(&truncated)
                );
                let column = u16::try_from(width).expect("small");
                let fitted = fit(text, column, Align::Left);
                assert!(
                    drawn(&fitted) <= width,
                    "fit({text:?}, {width}) = {fitted:?}"
                );
                let line = assemble(vec![vec![Span::raw(text.clone())]], column);
                let assembled: String = line.spans.iter().map(|s| s.content.as_ref()).collect();
                assert!(
                    drawn(&assembled) <= width,
                    "assemble({text:?}, {width}) = {assembled:?}"
                );
                if truncated != *text {
                    cut += 1;
                    assert!(truncated.ends_with('\u{2026}'), "{truncated:?}");
                }
            }
        }
        assert!(cut > 100, "the sweep cut something: {cut}");
    }

    #[test]
    fn fit_output_is_always_exactly_the_requested_width() {
        // Includes double-width glyphs, which are the whole reason this is
        // measured in cells rather than characters.
        for text in [
            "",
            "a",
            "hello",
            "a much longer value",
            "日本語テスト",
            "☀ clear",
            "⛈ thunderstorm",
            "🦀 rust",
        ] {
            for width in 0..14u16 {
                let out = fit(text, width, Align::Left);
                assert_eq!(
                    display_width(&out),
                    width as usize,
                    "`{text}` at width {width} produced `{out}`"
                );
            }
        }
    }

    #[test]
    fn a_double_width_glyph_does_not_shift_the_columns_after_it() {
        let cols = [Column::fixed("sky", 12), Column::fixed("temp", 6).right()];
        let grid = Grid::new(&cols, 19);
        let plain = grid.row(&[Span::raw("clear"), Span::raw("63°F")]);
        let wide = grid.row(&[Span::raw("☀ clear"), Span::raw("63°F")]);
        assert_eq!(
            width_of(&plain),
            width_of(&wide),
            "a wide glyph must not change the row width"
        );
    }

    /// A width too large for a `u16` saturates rather than wrapping to a
    /// small number that would fit anywhere, or falling back to zero.
    #[test]
    fn a_cell_width_too_wide_for_a_u16_saturates() {
        assert_eq!(cell_width(&"x".repeat(70_000)), u16::MAX);
        assert_eq!(cell_width("a🌞b"), 4, "measured in cells, not chars");
        assert_eq!(cell_width(""), 0);
    }

    #[test]
    fn a_dropped_column_takes_its_own_value_with_it() {
        // The bug this pins: row cells were indexed by surviving position, so
        // dropping a middle column slid every later value one header to the
        // left — a forecast's feels-like appearing under RAIN, a task's tags
        // under DUE. Silent, and exactly what this module exists to prevent.
        let cols = [
            Column::fixed("a", 4),
            Column::fixed("b", 4).drops_below(100),
            Column::fixed("c", 4),
        ];
        let cells = [Span::raw("AAA"), Span::raw("BBB"), Span::raw("CCC")];

        // Wide: everything shows, in order.
        let wide = Grid::new(&cols, 100);
        let text: String = wide
            .row(&cells)
            .spans
            .iter()
            .map(|s| s.content.as_ref())
            .collect();
        assert!(text.contains("AAA") && text.contains("BBB") && text.contains("CCC"));

        // Narrow: `b` is dropped. `c` must stay under its own header, and
        // `BBB` must not appear anywhere.
        let narrow = Grid::new(&cols, 20);
        assert!(!narrow.has("b"), "the test needs `b` dropped");
        let text: String = narrow
            .row(&cells)
            .spans
            .iter()
            .map(|s| s.content.as_ref())
            .collect();
        assert!(
            !text.contains("BBB"),
            "a dropped column's value must not be rendered: `{text}`"
        );
        assert!(text.contains("AAA") && text.contains("CCC"), "got `{text}`");

        // And the value sits under the right heading: compare cell positions
        // in the header and the row.
        let header: String = narrow
            .header(&Theme::default())
            .spans
            .iter()
            .map(|s| s.content.as_ref())
            .collect();
        assert_eq!(
            header.find('C'),
            text.find("CCC"),
            "`CCC` is not under the `C` header: header `{header}` row `{text}`"
        );
    }

    #[test]
    fn headers_are_uppercased_and_bold_rather_than_letterspaced() {
        let grid = Grid::new(&[Column::fixed("hour", 12)], 12);
        let header = grid.header(&Theme::default());
        let text: String = header.spans.iter().map(|s| s.content.as_ref()).collect();
        assert!(text.starts_with("HOUR"), "got `{text}`");
        assert!(
            header
                .spans
                .iter()
                .all(|s| s.style.add_modifier.contains(Modifier::BOLD)),
            "weight is what separates the header from the data now"
        );
    }

    #[test]
    fn every_column_in_a_header_gets_the_same_treatment() {
        // Mixed treatment within a row reads as a bug. This used to be a real
        // risk, because a column too narrow for its letterspaced label demoted
        // the whole row; the bold face costs no extra width, so a narrow column
        // can no longer force the question.
        let cols = [Column::fixed("done", 4), Column::fixed("sky", 20)];
        let grid = Grid::new(&cols, 25);
        let text: String = grid
            .header(&Theme::default())
            .spans
            .iter()
            .map(|s| s.content.as_ref())
            .collect();
        assert!(text.starts_with("DONE"), "got `{text}`");
        assert!(text.contains("SKY"), "got `{text}`");
        assert!(!text.contains("S K Y"), "no letterspacing: `{text}`");
        assert!(!text.contains("D O N E"), "no letterspacing: `{text}`");
    }

    #[test]
    fn a_header_too_long_for_its_column_truncates_rather_than_shifting() {
        // "TEMPERATURE" is 11 columns; the column is 6.
        let grid = Grid::new(
            &[Column::fixed("temperature", 6), Column::fixed("b", 4)],
            11,
        );
        let header = grid.header(&Theme::default());
        assert_eq!(width_of(&header), 11);
    }
}