mirador 1.7.0

An opinionated personal dashboard for your terminal: world clocks, a calendar, weather, tasks, notes, a market watchlist, and live CPU and network graphs.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
//! 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 ratatui::style::{Modifier, Style};
use ratatui::text::{Line, Span};
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)
}

/// 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 display_width(text) <= width {
        return text.to_string();
    }

    // Take characters while they fit, keeping one cell back for the ellipsis.
    let budget = width - 1;
    let mut out = String::new();
    let mut used = 0usize;
    for c in text.chars() {
        let w = char_width(c);
        if used + w > budget {
            break;
        }
        out.push(c);
        used += w;
    }
    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)
}

/// 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 slices of `text`, so nothing here allocates. Measured in
/// cells rather than characters, per the rule the whole module exists for.
fn break_lines<'a>(text: &'a str, width: usize, mut emit: impl FnMut(&'a str)) {
    if width == 0 {
        return;
    }

    let mut any = false;
    for line in text.lines() {
        // 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 = display_width(word);
            if used > 0 && used + w > width {
                emit(&line[start..cursor]);
                (any, emitted_here) = (true, true);
                start = cursor;
                used = 0;
            }
            cursor += word.len();
            used += w;

            // A single word longer than the row breaks inside itself, rather
            // than running off the edge.
            while used > width {
                let mut cut = start;
                let mut taken = 0usize;
                for c in line[start..cursor].chars() {
                    let cw = char_width(c);
                    if taken + cw > width {
                        break;
                    }
                    taken += cw;
                    cut += c.len_utf8();
                }
                // 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.
                if cut == start {
                    match line[start..cursor].chars().next() {
                        Some(c) => cut += c.len_utf8(),
                        None => break,
                    }
                }
                emit(&line[start..cut]);
                (any, emitted_here) = (true, true);
                start = cut;
                used = display_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(&line[start..cursor]);
            any = true;
        }
    }

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

/// 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, |line| out.push(line.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 by mapping each wrapped row back to its absolute source range,
/// so a delimiter can never drift the styled-byte cursor or become a slice
/// panic. If an internal range ever stops landing on UTF-8 boundaries, the row
/// falls back to the line style instead of trusting an assertion in release
/// code.
pub fn wrap_line(line: &Line<'_>, width: usize) -> Vec<Line<'static>> {
    if width == 0 {
        return Vec::new();
    }
    let text: String = line
        .spans
        .iter()
        .map(|span| span.content.as_ref())
        .collect();
    let base = text.as_ptr() as usize;
    let mut output = Vec::new();
    break_lines(&text, width, |row| {
        let spans = (row.as_ptr() as usize)
            .checked_sub(base)
            .filter(|start| start.saturating_add(row.len()) <= text.len())
            .and_then(|start| styled_byte_range(&line.spans, start, start + row.len()));
        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| display_width(&span.content)).sum();
        if rendered_width > width {
            output.push(Line::from(Span::styled(truncate(row, width), style)));
        } else {
            output.push(Line::from(spans).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.
pub fn wrapped(text: &str, width: u16) -> String {
    let width = usize::from(width);
    let mut out = String::with_capacity(text.len());
    break_lines(text, width, |line| {
        if !out.is_empty() {
            out.push('\n');
        }
        out.push_str(line);
    });
    out
}

/// 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_attr(not(test), allow(dead_code))]
    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);

        let mut spans = Vec::new();
        for (column, width, _) in &self.resolved {
            if *width == 0 {
                continue;
            }
            if !spans.is_empty() {
                spans.push(Span::raw(" ".repeat(GUTTER as usize)));
            }
            let text = crate::glyphs::utility(column.label);
            spans.push(Span::styled(fit(&text, *width, column.align), style));
        }
        Line::from(spans)
    }

    /// A data row. Extra cells are ignored; missing cells render blank.
    pub fn row(&self, cells: &[Span<'_>]) -> 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)));
            }
            // 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.
            let (content, style) = match cells.get(*declared) {
                Some(span) => (span.content.as_ref(), span.style),
                None => ("", Style::default()),
            };
            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| display_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.
            if spans.is_empty() {
                let mut room = width;
                for span in part {
                    if room == 0 {
                        break;
                    }
                    let text = truncate(&span.content, room);
                    room -= display_width(&text);
                    spans.push(Span::styled(text, span.style));
                }
            }
            break;
        }
        used += part_width;
        spans.extend(part);
    }

    Line::from(spans)
}

/// 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 = width as usize;
    if width == 0 {
        return String::new();
    }

    let actual = display_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(display_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::*;
    use ratatui::Terminal;
    use ratatui::backend::TestBackend;
    use ratatui::widgets::{Paragraph, Wrap};

    /// The two must agree: a panel sizes itself with one and draws with the
    /// other, so a disagreement puts content outside the box measured for it.
    ///
    /// They are one function with two consumers now, so this cannot fail by
    /// drift any more — but it could once, and for a long time it 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.
    #[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",
        ];
        for text in samples {
            for width in 1..40u16 {
                assert_eq!(
                    u16::try_from(wrap(text, usize::from(width)).len()).unwrap(),
                    wrapped_height(text, width),
                    "`{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 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()
    }

    /// 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.
    /// 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() {
        fn walk(dir: &std::path::Path, needle: &str, found: &mut Vec<String>) {
            let Ok(entries) = std::fs::read_dir(dir) else {
                return;
            };
            for entry in entries.flatten() {
                let path = entry.path();
                if path.is_dir() {
                    walk(&path, needle, found);
                } else if path.extension().is_some_and(|e| e == "rs")
                    // This module's own tests use the wrapper deliberately, to
                    // prove it still panics. Testing the thing is not using it.
                    && path.file_name().is_some_and(|n| n != "grid.rs")
                    && let Ok(text) = std::fs::read_to_string(&path)
                {
                    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) {
                            let name = path
                                .file_name()
                                .unwrap_or_default()
                                .to_string_lossy()
                                .to_string();
                            found.push(format!("{name}: {}", trimmed.trim_end()));
                        }
                    }
                }
            }
        }

        // Split so this test's own source is not a match.
        let needle = concat!(".wr", "ap(");
        let root = std::path::Path::new(env!("CARGO_MANIFEST_DIR")).join("src");

        let mut found = Vec::new();
        walk(&root, needle, &mut found);
        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 how many composite lines it may build.
        // 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)] = &[
            ("agenda.rs", 1, "the row's summary is truncated to `room`"),
            (
                "notes.rs",
                2,
                "search field and caret, both cut to the pane",
            ),
            ("stocks.rs", 1, "the add field, assembled by `status_line`"),
            (
                "todo.rs",
                1,
                "the priority marker: three short fixed strings",
            ),
            (
                "watchlog.rs",
                2,
                "entry text truncated; the rule line is built to width",
            ),
        ];

        fn walk(dir: &std::path::Path, needle: &str, found: &mut Vec<String>) {
            let Ok(entries) = std::fs::read_dir(dir) else {
                return;
            };
            for entry in entries.flatten() {
                let path = entry.path();
                if path.is_dir() {
                    walk(&path, needle, found);
                } else if path.extension().is_some_and(|e| e == "rs")
                    && let Ok(text) = std::fs::read_to_string(&path)
                {
                    // 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(),
                            );
                        }
                    }
                }
            }
        }

        // Split so this test's own source is not a match.
        let needle = concat!("Line::fr", "om(vec![");
        let mut found = Vec::new();
        let source = std::path::Path::new(env!("CARGO_MANIFEST_DIR")).join("src");
        // 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 ["widgets", "plugin"] {
            walk(&source.join(directory), needle, &mut found);
        }

        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 add the module here \
                 with the reason."
            );
        }
    }

    #[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}"
                );
            }
        }
    }

    #[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}");
    }

    #[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),
        ("notes", crate::widgets::notes::COLUMNS),
        ("stocks", crate::widgets::stocks::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 are built by separate loops,
    /// and only one of them was wrong the first time.
    #[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() {
        fn walk(dir: &std::path::Path, found: &mut Vec<String>) {
            for entry in std::fs::read_dir(dir).unwrap().flatten() {
                let path = entry.path();
                if path.is_dir() {
                    walk(&path, found);
                } else if path.extension().is_some_and(|e| e == "rs") {
                    let text = std::fs::read_to_string(&path).unwrap();
                    if text.contains(concat!("const COLUMNS: &[", "Column]")) {
                        found.push(path.file_stem().unwrap().to_string_lossy().into_owned());
                    }
                }
            }
        }

        let mut found = Vec::new();
        walk(
            &std::path::Path::new(env!("CARGO_MANIFEST_DIR")).join("src"),
            &mut found,
        );
        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");
    }

    #[test]
    fn a_grid_with_no_room_still_produces_a_full_width_row() {
        // Fixed columns can exceed a tiny total; the row must still not
        // overflow the area it is drawn into by more than its declared width.
        let grid = Grid::new(&columns(), 4);
        let row = grid.row(&[Span::raw("14:00")]);
        assert!(width_of(&row) >= 4);
    }

    #[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), "");
    }

    #[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"
        );
    }

    #[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);
    }
}