makeover-tui 0.64.0

The terminal renderer for makeover-layout, on ratatui. Colour stops being the constraint above 256 entries; geometry never does, because an edge occupies a whole cell on every side.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
//! Column layout and row structure for tables.
//!
//! `makeover-webview`'s `list` module in the shape a terminal allows. It owns
//! the same four things: which columns exist, how wide they are, which ones
//! survive a narrow viewport, and what each part of a cell is. It does not own
//! what goes in a cell, for the reason that module states: a cell holds whatever
//! the app builds, and a description expressive enough to emit a task row's five
//! nested spans is a templating language wearing a description's name.
//!
//! # What ratatui already answers
//!
//! Most of the drawing. [`ratatui::widgets::Table`] lays tracks out from
//! [`Constraint`]s, draws a header, highlights a selected row and scrolls
//! through [`TableState`](ratatui::widgets::TableState). So this is a mapping
//! layer over it rather than a second table implementation, and it hands back a
//! `Table` instead of painting one: selection and scroll belong to the app's
//! state, and a function that painted would have to take that state to give it
//! back.
//!
//! Two things ratatui does not answer, and they are what this module is:
//!
//! - **Content measurement.** There is no track that sizes to what is in it, so
//!   [`Width::Content`] is measured here from the cells and the heading.
//! - **Narrowing.** A terminal window is resized far more often than a browser
//!   one, and [`Priority`] is how a column earns its place. See below.
//!
//! # Why positions are the bug
//!
//! The mistake is not a CSS one. Hiding columns by position (`nth-child(n+5)`
//! against a seven-column table) means inserting a column left of the cut hides
//! the wrong one, silently, because nothing in the rule knows what column five
//! *is*. A renderer narrows by raising a cutoff and never by counting, which is
//! the whole reason [`Priority`] exists. `a_column_inserted_left_of_the_cut_does_not_change_what_drops`
//! is that bug as a test.
//!
//! # What it costs when nothing fits
//!
//! [`Priority::Essential`] never drops, so a window narrower than the essential
//! columns leaves them overflowing rather than emptying the table. That is
//! deliberate: a row that cannot identify itself is not a narrower row, it is a
//! different one, and ratatui truncates a cell it cannot fit. Truncated and
//! present beats absent.
//!
//! # The table model in cells
//!
//! Wiki `table-model`, which the webview renderer draws in pixels. A cell is
//! one line tall and an edge occupies a whole cell, so three of its facts are
//! translated rather than copied:
//!
//! - **No hairlines and no frame.** A rule between rows costs a row, which
//!   halves what a screen shows. The stripe separates rows alone.
//! - **No 45px row.** A row is one line. The block padding survives as a cell
//!   of ground at either end, [`TableStyle::column_spacing`] wide, the way
//!   `gap-group` pads both ends of a webview row.
//! - **A cursor row.** A terminal has a cursor where a browser has a hover, and
//!   it has to read over the stripe at a glance; see [`TableInk::selected`].
//!
//! The rest carries over as it is: rows on the raised ground with a stripe on
//! alternate rows, the header as a sunken strip in secondary ink, and a table
//! holding code keeping its header while dropping the stripe.

use makeover_layout::{Caret, CellPart, ColumnKind, ColumnRoom, Priority, Sort, Width};
use ratatui::layout::Constraint;
use ratatui::style::{Color, Modifier, Style};
use ratatui::text::Line;
use ratatui::widgets::{Cell as TrackCell, Row, Table};

use crate::Palette;

/// The lengths a description defers, looked up by column name: terminal cells
/// here, as `Sizing<'_, u16>`.
pub use makeover_layout::Sizing;

/// One column of a table: the room it asks the sizer for, and the order in
/// force on it, if any.
///
/// The table's own column input. The sizing half is
/// [`ColumnRoom`], the record every host sizes a
/// table from, so a column drops at one declared width on every renderer; the
/// order in force is the one fact a heading draws that sizing does not need.
/// Whether the column offers to be reordered is [`ColumnRoom::caret`]: a caret
/// sits beside a heading that is sortable or is the one the table is ordered by.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub struct Head<'a> {
    /// What the column asks of the sizer, and whether its heading has a caret.
    pub room: ColumnRoom<'a>,
    /// The order in force on this column, when the table is ordered by it.
    pub sorted: Option<Sort>,
}

impl<'a> Head<'a> {
    /// A text column under `heading` that fills and is essential, the defaults
    /// [`ColumnRoom::new`] gives.
    #[must_use]
    pub const fn new(heading: &'a str) -> Self {
        Self {
            room: ColumnRoom::new(heading),
            sorted: None,
        }
    }

    /// The heading, which is also the name a [`Cell`] fills the column by.
    #[must_use]
    pub const fn name(&self) -> &'a str {
        self.room.heading
    }

    /// The same column, declaring the narrowest it may be before it drops.
    #[must_use]
    pub const fn min(mut self, ch: u16) -> Self {
        self.room.min = Some(ch);
        self
    }

    /// The same column, asking for this much room.
    #[must_use]
    pub const fn width(mut self, width: Width) -> Self {
        self.room.width = width;
        self
    }

    /// The same column, worth this much when room runs out.
    #[must_use]
    pub const fn priority(mut self, priority: Priority) -> Self {
        self.room.priority = priority;
        self
    }

    /// The same column, holding this kind of value.
    #[must_use]
    pub const fn kind(mut self, kind: ColumnKind) -> Self {
        self.room.kind = kind;
        self
    }

    /// The same column, reorderable by the user or not. A column the table is
    /// ordered by keeps its caret either way.
    #[must_use]
    pub const fn sortable(mut self, sortable: bool) -> Self {
        self.room.caret = sortable || self.sorted.is_some();
        self
    }

    /// The same column, the one the table is ordered by, in this direction.
    #[must_use]
    pub const fn sorted(mut self, sort: Sort) -> Self {
        self.sorted = Some(sort);
        self.room.caret = true;
        self
    }

    /// The narrowest this column is drawn, in `ch`. See [`ColumnRoom::floor`].
    #[must_use]
    pub const fn floor(&self) -> u16 {
        self.room.floor()
    }

    /// Whether this column is kept at `cutoff`.
    #[must_use]
    pub const fn kept_at(&self, cutoff: Priority) -> bool {
        self.room.kept_at(cutoff)
    }
}

/// The sizing records for `heads`, in order.
fn rooms<'a>(heads: &[Head<'a>]) -> Vec<ColumnRoom<'a>> {
    heads.iter().map(|head| head.room).collect()
}

/// One cell of a row.
///
/// The contents are a ratatui [`Line`] rather than a string, which is this
/// crate's version of the webview `Cell` holding markup: the app owns what goes
/// in the cell, spans and all, and says which column it belongs to by name.
#[derive(Debug, Clone)]
pub struct Cell<'a> {
    /// Which column this fills, by name.
    pub column: &'a str,
    /// What the cell holds, when the whole cell is one thing.
    ///
    /// `None` for a cell mixing parts. A cell holding a value *and* a strip of
    /// tokens *and* a control is three parts in one cell, and a terminal cell
    /// has one style to give, so the app styles the spans itself. This field is
    /// for the single-part case, which is the common one.
    pub part: Option<CellPart>,
    /// The contents.
    pub content: Line<'a>,
}

impl<'a> Cell<'a> {
    /// A cell with no cell part.
    #[must_use]
    pub fn new(column: &'a str, content: impl Into<Line<'a>>) -> Self {
        Self {
            column,
            part: None,
            content: content.into(),
        }
    }

    /// The same cell, saying which part it is.
    #[must_use]
    pub fn part(mut self, part: CellPart) -> Self {
        self.part = Some(part);
        self
    }
}

/// The metrics and marks a table draws with.
///
/// No colours: those are the [`Palette`]'s, and [`TableInk`] is the two
/// resolved together, the split `makeover-immediate` draws between its palette
/// and its styles.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
#[non_exhaustive]
pub struct TableStyle {
    /// Cells between columns, and the ground at either end of a row. Counted
    /// when deciding what fits, so a table that narrows and a table that draws
    /// agree about the room available.
    pub column_spacing: u16,
    /// The caret drawn after the heading of an ascending column.
    ///
    /// Defaults to [`Sort::glyph`]. A knob because a terminal is the one host
    /// that may not be able to draw it: a font without the geometric-shapes
    /// block leaves a box, and `"^"` is a better caret than a tofu.
    ///
    /// Bare, with no leading space: the gap is the heading's, written once for
    /// all three states.
    pub ascending: &'static str,
    /// The caret drawn after the heading of a descending column.
    pub descending: &'static str,
}

impl Default for TableStyle {
    fn default() -> Self {
        Self {
            column_spacing: 1,
            ascending: Sort::Ascending.glyph(),
            descending: Sort::Descending.glyph(),
        }
    }
}

/// A [`Palette`] and a [`TableStyle`], resolved into the styles a table draws
/// with.
///
/// The table model (wiki `table-model`): rows on the raised ground with a
/// stripe, the heading a sunken strip in bold secondary ink with the ordered
/// column brought up to primary, each cell part in the ink
/// [`CellPart::intent`] names, and selection carried by the background alone.
///
/// Where the palette has no colour for a role the table says it with a
/// modifier: a bold heading, a reversed cursor row. Where
/// the terminal cannot tell the strip from the ground, the heading is
/// underlined as well, since the separation is what the strip is for.
///
/// Selection carries no foreground on purpose. A row can be red for a failed
/// upload or green for a published item, and repainting its text on selection
/// loses that on exactly the row the user is looking at.
///
/// Public for a caller assembling its own [`Table`], which takes
/// [`stripe`](Self::stripe) and [`selected`](Self::selected) from here.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
#[non_exhaustive]
pub struct TableInk {
    /// The heading row.
    pub header: Style,
    /// The heading of the column the table is ordered by.
    pub sorted: Style,
    /// The heading of a column that offers to reorder and is not doing it now.
    ///
    /// The middle of three tones (wiki `three-tone-convention`): it answers a
    /// press, so it is neither the emphasised thing nor the inert one.
    pub sortable: Style,
    /// A cell that is text.
    pub value: Style,
    /// A cell holding badges or chips. They carry their own tone, so this is
    /// what shows through the gaps rather than what paints them.
    pub tokens: Style,
    /// A cell holding controls. They carry their own ink, so this is what an
    /// unstyled run beside them takes.
    pub actions: Style,
    /// A cell whose value is itself a link: its row's title, in the ink the
    /// values beside it take and with no underline, since the row is what
    /// activates.
    pub link: Style,
    /// The row under the cursor, for a caller rendering with a
    /// [`TableState`](ratatui::widgets::TableState).
    pub selected: Style,
    /// What a row sits on.
    pub ground: Style,
    /// What every second row sits on, counting from the first body row.
    ///
    /// Not drawn in a table holding a [`ColumnKind::Code`] column, which is
    /// read as source: one row per line, where a stripe breaks the reading.
    pub stripe: Style,
    /// The metrics and marks.
    pub style: TableStyle,
}

impl TableInk {
    /// Resolve `palette`'s tones under `style`'s metrics.
    #[must_use]
    pub fn new(palette: &Palette, style: &TableStyle) -> Self {
        let t = &palette.tones;
        let fg = |c: Option<Color>| c.map_or(Style::new(), |c| Style::new().fg(c));
        let bg = |c: Option<Color>| c.map_or(Style::new(), |c| Style::new().bg(c));
        let mut header = fg(t.secondary)
            .patch(bg(t.sunken))
            .add_modifier(Modifier::BOLD);
        if t.sunken
            .is_some_and(|sunken| !Palette::shows(sunken, t.ground.unwrap_or(palette.raised)))
        {
            header = header.add_modifier(Modifier::UNDERLINED);
        }
        Self {
            header,
            sorted: fg(t.content).add_modifier(Modifier::BOLD),
            // The strip's own ink. Offering and inert differ by the idle caret,
            // which is the webview's split too.
            sortable: fg(t.secondary),
            value: fg(intent_tone(t, CellPart::Value.intent())),
            tokens: fg(intent_tone(t, CellPart::Tokens.intent())),
            actions: fg(intent_tone(t, CellPart::Actions.intent())),
            link: fg(intent_tone(t, CellPart::Link.intent())),
            selected: match t.selected {
                Some(selected) => Style::new().bg(selected).add_modifier(Modifier::BOLD),
                None => Style::new().add_modifier(Modifier::REVERSED),
            },
            ground: bg(t.ground),
            stripe: bg(t.stripe),
            style: *style,
        }
    }

    /// The style a cell of this part takes.
    ///
    /// [`CellPart`] is `#[non_exhaustive]`, and a member added upstream lands on
    /// [`value`](Self::value): a part this renderer has not learned draws as
    /// text, which is a cell rendering plainly rather than a build that stops.
    #[must_use]
    pub fn for_part(&self, part: Option<CellPart>) -> Style {
        match part {
            Some(CellPart::Tokens) => self.tokens,
            Some(CellPart::Actions) => self.actions,
            Some(CellPart::Link) => self.link,
            _ => self.value,
        }
    }
}

/// The tone a content intent names, from makeover-layout's `content*` set.
///
/// An intent outside that set takes `content`, so a part makeover-layout gives
/// a new intent draws as text until this renderer learns it.
fn intent_tone(t: &crate::Tones, intent: &str) -> Option<Color> {
    match intent {
        "content-secondary" => t.secondary,
        "content-muted" => t.muted,
        _ => t.content,
    }
}

/// A line placed the way its column's kind says, wiki `table-model`.
///
/// Alignment is the one kind fact a terminal has to act on. Every cell is
/// already the monospace face with even figures, and a terminal wraps nothing
/// it is not told to, so a number or an actions column aligning to its end is
/// what is left. The heading takes the same, so a label sits over its figures.
fn aligned<'a>(column: &Head<'_>, line: Line<'a>) -> Line<'a> {
    if column.room.kind.aligns_end() {
        line.right_aligned()
    } else {
        line
    }
}

/// The heading, in capitals, with the caret if this column is ordered by or
/// offers to be.
///
/// Capitals because the strip's label is set that way at every host. The
/// webview sets it small and tracked as well, and a cell has neither to give,
/// so the strip and the weight carry the rest.
///
/// A column [`sorted`](Head::sorted) but not
/// [`sortable`](Head::sortable) still gets its caret. Both combinations mean
/// something, which is why the description holds the two fields apart: a list
/// ordered by a key the user cannot change is a real thing, and the caret is how
/// it says so.
///
/// A column sortable and *not* sorted draws the idle mark, in the ascending
/// spelling because that is the direction a first press takes. The tone is what
/// separates it from the column in force, and [`header`] picks that; here the
/// point is the width. This is what closes the reflow: pressing a heading used
/// to widen its column by two cells and shift every column after it, because
/// [`measure`] sizes from this function and the caret appeared with the press.
fn heading(column: &Head<'_>, style: &TableStyle) -> Line<'static> {
    Line::from(caret(column).label(column.name(), style.ascending, style.descending))
}

/// The caret this column's heading draws, by the rule every host shares.
fn caret(column: &Head<'_>) -> Caret {
    Caret::of(column.sorted, column.room.caret)
}

/// The ground at either end of a row: a track of no width, which the table's
/// column spacing then separates from the first and last columns.
///
/// A track rather than a space in the first and last cells, because which
/// columns are first and last moves as the table narrows, and an end-aligned
/// last column would have to know to leave its space behind.
const EDGE: Constraint = Constraint::Length(0);

/// A row's cells between its two edges.
///
/// `Cell::new("")` and never `Cell::default()`: ratatui derives the default
/// with a column span of zero, and a cell spanning nothing takes no track, so
/// every cell after it lands one column to the left.
fn edged<'a>(cells: impl Iterator<Item = TrackCell<'a>>) -> Vec<TrackCell<'a>> {
    std::iter::once(TrackCell::new(""))
        .chain(cells)
        .chain(std::iter::once(TrackCell::new("")))
        .collect()
}

/// The cell column `at` draws from a row's cells.
///
/// By name, and by place among the columns sharing that name: the second
/// column called `y` takes the second cell called `y`. Matching on the name
/// alone would hand every same-named column the first such cell, and the
/// second `y` would never be drawn.
fn cell_of<'c, 'a>(columns: &[Head<'_>], at: usize, cells: &'c [Cell<'a>]) -> Option<&'c Cell<'a>> {
    let name = columns.get(at)?.name();
    let nth = columns[..at]
        .iter()
        .filter(|column| column.name() == name)
        .count();
    cells.iter().filter(|cell| cell.column == name).nth(nth)
}

/// The widest cell column `at` holds across `rows`, in cells, heading not
/// included.
///
/// What [`table`] measures a [`Width::Content`] column with. A caller drawing
/// a [`Window`] of a long table hands [`table_window`] its own answer to this
/// question instead, worked out without building the rows it is not drawing.
#[must_use]
pub fn widest_cell<'a, R>(columns: &[Head<'_>], at: usize, rows: &[R]) -> u16
where
    R: AsRef<[Cell<'a>]>,
{
    let widest = rows
        .iter()
        .filter_map(|row| cell_of(columns, at, row.as_ref()).map(|cell| cell.content.width()))
        .max()
        .unwrap_or(0);
    u16::try_from(widest).unwrap_or(u16::MAX)
}

/// The widest thing in a column: its widest cell or its heading.
///
/// The heading counts because it is drawn: a column sized to its cells alone
/// truncates its own name, and a two-character column called `duration` reads as
/// `du`. The caret counts for the same reason, which is why this measures
/// [`heading`] rather than [`Head::name`].
fn measure(column: &Head<'_>, widest: u16, style: &TableStyle) -> u16 {
    widest.max(u16::try_from(heading(column, style).width()).unwrap_or(u16::MAX))
}

/// Whether a budget fits in `width` cells.
///
/// A floor is counted in `ch` and a cell is one `ch`, so the budget is
/// [`Budget::width`](makeover_layout::Budget::width) at one cell per `ch`, with
/// the column spacing as the gap between columns and at either end.
fn fits(budget: makeover_layout::Budget, style: &TableStyle, width: u16) -> bool {
    budget.width(1.0, f32::from(style.column_spacing)) <= f32::from(width)
}

/// The weakest cutoff whose columns fit in `width` cells.
///
/// [`ColumnRoom::cutoff_for`] with this renderer's unit filled in, which is
/// the one thing it adds: the narrowing rule and the gap model are the
/// description's, so all three renderers drop a column at one declared width.
#[must_use]
pub fn cutoff_for(columns: &[Head<'_>], width: u16, style: &TableStyle) -> Priority {
    ColumnRoom::cutoff_for(&rooms(columns), |budget| fits(budget, style, width))
}

/// The tracks for the columns kept at `cutoff`.
///
/// Only the surviving tracks, which is what keeps the track list and the hiding
/// in agreement. A caller that dropped a cell but left its track would get a
/// column of empty space.
///
/// Bracketed by the two edge tracks, which [`row`] and [`header`] fill, so the
/// list is two longer than the columns kept.
#[must_use]
pub fn constraints<'a, R>(
    columns: &[Head<'_>],
    rows: &[R],
    sizing: &Sizing<'_, u16>,
    cutoff: Priority,
    style: &TableStyle,
) -> Vec<Constraint>
where
    R: AsRef<[Cell<'a>]>,
{
    constraints_from(
        columns,
        |at| widest_cell(columns, at, rows),
        sizing,
        cutoff,
        style,
    )
}

/// [`constraints`], with each [`Width::Content`] column's widest cell answered
/// by `widest`, which takes the column's index in `columns`.
///
/// Asked only of the content columns kept at `cutoff`. The heading is still
/// measured here, so `widest` answers for the cells alone, as
/// [`widest_cell`] does.
#[must_use]
pub fn constraints_from(
    columns: &[Head<'_>],
    mut widest: impl FnMut(usize) -> u16,
    sizing: &Sizing<'_, u16>,
    cutoff: Priority,
    style: &TableStyle,
) -> Vec<Constraint> {
    let tracks = columns
        .iter()
        .enumerate()
        .filter(|(_, column)| column.kept_at(cutoff))
        .map(|(at, column)| match column.room.width {
            // Takes what it needs and no more, which is a fixed track once the
            // needing has been measured.
            Width::Content => Constraint::Length(measure(column, widest(at), style)),
            Width::Fixed => Constraint::Length(sizing.length_for(column.name())),
            // `Min` and not `Fill`: a fill column absorbs the slack *and* keeps
            // its floor. `Fill` would let it collapse below the floor when a
            // fixed column takes the room.
            _ => Constraint::Min(sizing.length_for(column.name())),
        })
        .collect::<Vec<_>>();
    std::iter::once(EDGE)
        .chain(tracks)
        .chain(std::iter::once(EDGE))
        .collect()
}

/// One row's cells, in column order, on the ground.
///
/// The ground and not the stripe, since a row does not know where it falls.
/// [`table`] lays the stripe over every second row; a caller assembling its
/// own [`Table`] takes [`TableInk::stripe`] for those rows itself, or asks
/// [`striped`].
///
/// Ordered by the columns and not by the cells, so a row cannot silently
/// disagree with its table about what comes where. A column with no cell gets an
/// empty cell, which keeps the tracks aligned; a cell naming no column is
/// dropped, because there is nowhere to put it. That is the webview renderer's
/// rule too, and it has to be the same rule or the two renderers disagree about
/// a row they were handed identically.
#[must_use]
pub fn row<'a>(
    columns: &[Head<'_>],
    cells: &[Cell<'a>],
    cutoff: Priority,
    ink: &TableInk,
) -> Row<'a> {
    Row::new(edged(
        columns
            .iter()
            .enumerate()
            .filter(|(_, column)| column.kept_at(cutoff))
            .map(|(at, column)| {
                let found = cell_of(columns, at, cells);
                let part = found.and_then(|cell| cell.part);
                let content = found.map_or_else(Line::default, |cell| {
                    crate::text::sanitise(cell.content.clone())
                });
                TrackCell::from(aligned(column, content)).style(ink.for_part(part))
            }),
    ))
    .style(ink.ground)
}

/// The heading row for the columns kept at `cutoff`.
///
/// Exposed beside [`table`] because a caller assembling its own [`Table`] still
/// has to draw a header that agrees with the body about what just disappeared.
#[must_use]
pub fn header<'a>(columns: &[Head<'_>], cutoff: Priority, ink: &TableInk) -> Row<'a> {
    Row::new(edged(
        columns
            .iter()
            .filter(|column| column.kept_at(cutoff))
            .map(|column| {
                // Three states, three tones (wiki `three-tone-convention`): in
                // force, offering, and not a control at all.
                let tone = match caret(column) {
                    Caret::Idle => ink.sortable,
                    Caret::None => ink.header,
                    // Sorted, and a mark this renderer has not learned, which
                    // reads as the column in force.
                    _ => ink.sorted,
                };
                let head = crate::text::sanitise(heading(column, &ink.style));
                TrackCell::from(aligned(column, head)).style(tone)
            }),
    ))
    .style(ink.header)
}

/// A described table, sized and narrowed for `width`.
///
/// Hands back a [`Table`] rather than drawing one. Selection and scroll live in
/// the app's [`TableState`](ratatui::widgets::TableState), and the row highlight
/// is already set from [`TableInk::selected`], so a caller renders this with
/// `render_stateful_widget` and gets the house selection without saying anything
/// further.
///
/// `width` is the area the table will be drawn in, which is what narrowing is
/// decided against. Pass the [`Rect`](ratatui::layout::Rect) width that
/// [`frame`](crate::frame) handed back rather than the region's own, or the
/// table budgets for the two cells the edge took.
///
/// Builds every row it is handed. A table longer than its area is cheaper
/// through [`table_window`], which builds only the rows drawn.
#[must_use]
pub fn table<'a, R>(
    columns: &[Head<'_>],
    rows: &[R],
    sizing: &Sizing<'_, u16>,
    width: u16,
    ink: &TableInk,
) -> Table<'a>
where
    R: AsRef<[Cell<'a>]>,
{
    table_window(
        columns,
        rows,
        Window::WHOLE,
        |at| widest_cell(columns, at, rows),
        sizing,
        width,
        ink,
    )
}

/// Which stretch of a longer table a caller is drawing.
///
/// A table's columns are sized from every row and its stripe is counted from
/// the first, so drawing a stretch of one is not drawing a shorter table: the
/// stretch has to know where it starts, and the widths have to come from rows
/// it was not handed.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct Window {
    /// The whole table's index of the first row handed over.
    pub first: usize,
    /// Whether the heading row is drawn above it.
    pub header: bool,
}

impl Window {
    /// The whole table, from its heading down.
    pub const WHOLE: Self = Self {
        first: 0,
        header: true,
    };
}

/// A stretch of a described table, sized for the whole of it.
///
/// [`table`] for a caller that knows which rows it will draw. `rows` is that
/// stretch alone, starting at the whole table's row `window.first`; `widest`
/// answers each [`Width::Content`] column's widest cell across the WHOLE table,
/// by column index, as [`constraints_from`] asks it. So the columns sit where
/// they would with every row built, and a reader scrolling through does not see
/// them move.
///
/// The stripe is counted from the whole table's first row, so a stretch
/// starting on an odd row starts striped.
#[must_use]
pub fn table_window<'a, R>(
    columns: &[Head<'_>],
    rows: &[R],
    window: Window,
    widest: impl FnMut(usize) -> u16,
    sizing: &Sizing<'_, u16>,
    width: u16,
    ink: &TableInk,
) -> Table<'a>
where
    R: AsRef<[Cell<'a>]>,
{
    let cutoff = cutoff_for(columns, width, &ink.style);
    let widths = constraints_from(columns, widest, sizing, cutoff, &ink.style);
    let striped = striped(columns, cutoff);
    let body: Vec<Row<'a>> = rows
        .iter()
        .enumerate()
        .map(|(index, cells)| {
            let drawn = row(columns, cells.as_ref(), cutoff, ink);
            if striped && (window.first + index) % 2 == 1 {
                drawn.style(ink.stripe)
            } else {
                drawn
            }
        })
        .collect();

    let drawn = Table::new(body, widths)
        .column_spacing(ink.style.column_spacing)
        .row_highlight_style(ink.selected);
    if window.header {
        drawn.header(header(columns, cutoff, ink))
    } else {
        drawn
    }
}

/// Whether the rows of a table with these columns take the stripe.
///
/// False for a table holding code at `cutoff`, which keeps its header and
/// drops the record treatment, as the webview renderer's code table does.
#[must_use]
pub fn striped(columns: &[Head<'_>], cutoff: Priority) -> bool {
    !columns
        .iter()
        .any(|column| column.kept_at(cutoff) && column.room.kind == ColumnKind::Code)
}

/// Whether a table drawn at `width` would leave anything overflowing.
///
/// True only when the essential columns alone do not fit, since that is the one
/// case narrowing cannot answer. A caller that would rather show fewer rows than
/// truncate a cell can ask this and draw something else.
#[must_use]
pub fn overflows(columns: &[Head<'_>], width: u16, style: &TableStyle) -> bool {
    !fits(
        ColumnRoom::budget(&rooms(columns), Priority::Essential),
        style,
        width,
    )
}

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

    fn columns() -> Vec<Head<'static>> {
        vec![
            Head::new("name")
                .width(Width::Fill)
                .priority(Priority::Essential)
                .kind(ColumnKind::Text)
                .sortable(true)
                .sorted(Sort::Ascending),
            Head::new("size")
                .width(Width::Fixed)
                .priority(Priority::Secondary)
                .kind(ColumnKind::Text)
                .sortable(true),
            Head::new("note")
                .width(Width::Content)
                .priority(Priority::Optional)
                .kind(ColumnKind::Text)
                .sortable(false),
        ]
    }

    fn sizing() -> Sizing<'static, u16> {
        Sizing::new(&[("name", 10), ("size", 6)], 4)
    }

    /// A table's tones on a palette with none: what a terminal with no colour
    /// to spend draws.
    fn ink_of(style: &TableStyle) -> TableInk {
        let palette = crate::Palette::new(
            Color::Reset,
            Color::Reset,
            Color::Reset,
            Color::Reset,
            Color::Reset,
            crate::Fidelity::TrueColor,
        );
        TableInk::new(&palette, style)
    }

    /// A table's ink on a palette with these tones.
    fn ink_with(tones: crate::Tones) -> TableInk {
        let palette = crate::Palette::new(
            Color::Reset,
            Color::Reset,
            Color::Reset,
            Color::Reset,
            Color::Reset,
            crate::Fidelity::TrueColor,
        )
        .tones(tones);
        TableInk::new(&palette, &TableStyle::default())
    }

    fn rows() -> Vec<Vec<Cell<'static>>> {
        vec![
            vec![
                Cell::new("name", "alpha"),
                Cell::new("size", "1kb"),
                Cell::new("note", "a longer note"),
            ],
            vec![Cell::new("name", "beta"), Cell::new("size", "2kb")],
        ]
    }

    fn cell_text(row: &Row<'_>) -> Vec<String> {
        // Rendering is the only way to read a ratatui Row back, and reading it
        // back is the point: these tests assert what a user sees.
        use ratatui::layout::Rect;
        use ratatui::widgets::Widget;
        let mut buf = ratatui::buffer::Buffer::empty(Rect::new(0, 0, 60, 1));
        Table::new(vec![row.clone()], tracks())
            .column_spacing(1)
            .render(Rect::new(0, 0, 60, 1), &mut buf);
        (0..3)
            .map(|i| {
                let start = 1 + i * 19;
                (start..start + 18)
                    .map(|x| buf[(x as u16, 0)].symbol())
                    .collect::<String>()
                    .trim_end()
                    .to_owned()
            })
            .collect()
    }

    /// The foreground each of the three heading cells was drawn in.
    ///
    /// Read off a rendered buffer for [`cell_text`]'s reason: a ratatui `Row`
    /// hands nothing back, and what is asserted is what a user sees.
    fn cell_colors(row: &Row<'_>) -> Vec<Option<ratatui::style::Color>> {
        use ratatui::layout::Rect;
        use ratatui::widgets::Widget;
        let mut buf = ratatui::buffer::Buffer::empty(Rect::new(0, 0, 60, 1));
        Table::new(vec![row.clone()], tracks())
            .column_spacing(1)
            .render(Rect::new(0, 0, 60, 1), &mut buf);
        (0..3).map(|i| buf[(1 + i * 19, 0)].fg).map(Some).collect()
    }

    /// Three columns of 18 between the two edges, which puts column `i` at
    /// `1 + i * 19`.
    fn tracks() -> [Constraint; 5] {
        [
            EDGE,
            Constraint::Length(18),
            Constraint::Length(18),
            Constraint::Length(18),
            EDGE,
        ]
    }

    #[test]
    fn cells_are_ordered_by_the_columns_and_not_by_the_row() {
        // The row hands them over backwards. The table decides the order, which
        // is what stops a row silently disagreeing with its own header.
        let cols = columns();
        let out_of_order = vec![
            Cell::new("note", "third"),
            Cell::new("name", "first"),
            Cell::new("size", "second"),
        ];
        let drawn = row(
            &cols,
            &out_of_order,
            Priority::Optional,
            &ink_of(&TableStyle::default()),
        );
        assert_eq!(cell_text(&drawn), vec!["first", "second", "third"]);
    }

    #[test]
    fn a_cell_naming_no_column_is_dropped_and_a_column_with_no_cell_keeps_its_place() {
        let cols = columns();
        let cells = vec![Cell::new("note", "kept"), Cell::new("nonesuch", "lost")];
        let drawn = row(
            &cols,
            &cells,
            Priority::Optional,
            &ink_of(&TableStyle::default()),
        );
        // Two empty tracks, then the note. The empties are what keeps the third
        // column under the third heading.
        assert_eq!(cell_text(&drawn), vec!["", "", "kept"]);
    }

    #[test]
    fn a_content_column_is_measured_from_its_widest_cell() {
        let style = TableStyle::default();
        let widths = constraints(&columns(), &rows(), &sizing(), Priority::Optional, &style);
        assert_eq!(widths[3], Constraint::Length("a longer note".len() as u16));
    }

    #[test]
    fn a_content_column_never_truncates_its_own_heading() {
        // The cells are two characters wide and the heading is eight. Sizing to
        // the cells alone would draw the column as `du`.
        let cols = vec![
            Head::new("duration")
                .width(Width::Content)
                .priority(Priority::Essential)
                .kind(ColumnKind::Text)
                .sortable(false),
        ];
        let rows = vec![vec![Cell::new("duration", "3s")]];
        let widths = constraints(
            &cols,
            &rows,
            &sizing(),
            Priority::Optional,
            &TableStyle::default(),
        );
        assert_eq!(widths[1], Constraint::Length(8));
    }

    #[test]
    fn a_caret_is_part_of_what_a_heading_costs() {
        // Measured off `heading` and not off `name`, or the sorted column is
        // exactly two cells too narrow and drops its own arrow.
        let cols = vec![
            Head::new("size")
                .width(Width::Content)
                .priority(Priority::Essential)
                .kind(ColumnKind::Text)
                .sortable(true)
                .sorted(Sort::Descending),
        ];
        let rows: Vec<Vec<Cell<'_>>> = vec![];
        let style = TableStyle::default();
        let widths = constraints(&cols, &rows, &sizing(), Priority::Optional, &style);
        assert_eq!(
            widths[1],
            Constraint::Length(6),
            "size plus a space and a caret"
        );
    }

    #[test]
    fn narrowing_drops_the_optional_column_first_and_the_essential_one_never() {
        let style = TableStyle::default();
        let cols = columns();
        // Everything: floors of 16 (the name fills), 8 and 8, and a cell of
        // spacing either side of each, which is 32 + 4.
        assert_eq!(cutoff_for(&cols, 36, &style), Priority::Optional);
        assert_eq!(cutoff_for(&cols, 35, &style), Priority::Secondary);
        // No room for the note: 24 + 3.
        assert_eq!(cutoff_for(&cols, 27, &style), Priority::Secondary);
        // No room for the size either: 16 + 2.
        assert_eq!(cutoff_for(&cols, 26, &style), Priority::Essential);
        assert_eq!(cutoff_for(&cols, 18, &style), Priority::Essential);
        // No room for anything, and the essential column stays anyway.
        assert_eq!(cutoff_for(&cols, 2, &style), Priority::Essential);
        assert!(overflows(&cols, 2, &style));
        assert!(!overflows(&cols, 18, &style));
    }

    #[test]
    fn a_declared_minimum_moves_the_cut_and_a_measured_cell_does_not() {
        // The floor is what the three hosts agree on, so a long value in a cell
        // must not change where a column drops, and a declared minimum must.
        let style = TableStyle::default();
        let mut cols = columns();
        assert_eq!(cutoff_for(&cols, 36, &style), Priority::Optional);
        cols[2] = cols[2].min(20);
        assert_eq!(cutoff_for(&cols, 36, &style), Priority::Secondary);
        assert_eq!(cutoff_for(&cols, 48, &style), Priority::Optional);
    }

    #[test]
    fn a_column_inserted_left_of_the_cut_does_not_change_what_drops() {
        // The goingson bug, as a test. `nth-child(n+5)` against a seven-column
        // table hides whatever lands at position five, so inserting a column
        // anywhere left of the cut moves it onto a different column with nothing
        // edited and nothing reported.
        //
        // Asserted at a fixed cutoff, because that is where the two ways of
        // addressing a column disagree. A narrower budget SHOULD drop more
        // columns, and does below; what must not change is which ones, in what
        // order, for a given cutoff.
        let dropped = |cols: &[Head<'_>], cutoff| -> Vec<String> {
            cols.iter()
                .filter(|c| !c.kept_at(cutoff))
                .map(|c| c.name().to_owned())
                .collect()
        };
        let before = columns();
        let mut after = vec![
            Head::new("mark")
                .width(Width::Fixed)
                .priority(Priority::Essential)
                .kind(ColumnKind::Text)
                .sortable(false),
        ];
        after.extend(columns());

        for &cutoff in Priority::RAISING {
            assert_eq!(
                dropped(&before, cutoff),
                dropped(&after, cutoff),
                "inserting a column changed what {cutoff:?} drops"
            );
        }
        assert_eq!(dropped(&before, Priority::Secondary), vec!["note"]);
    }

    #[test]
    fn a_column_never_outlives_a_more_essential_one() {
        // The ordering claim narrowing rests on: whatever the budget, the set
        // kept is closed upward. A layout that dropped `size` while keeping
        // `note` would be counting something other than priority.
        let style = TableStyle::default();
        let cols = columns();
        for width in 0..48u16 {
            let cutoff = cutoff_for(&cols, width, &style);
            let kept: Vec<&str> = cols
                .iter()
                .filter(|c| c.kept_at(cutoff))
                .map(Head::name)
                .collect();
            assert!(
                kept.contains(&"name"),
                "the essential column left at {width}"
            );
            if kept.contains(&"note") {
                assert!(
                    kept.contains(&"size"),
                    "optional outlived secondary at {width}"
                );
            }
        }
    }

    #[test]
    fn a_dropped_column_takes_its_track_with_it() {
        // A cell hidden with its track left behind is a column of empty space,
        // which is the half of the goingson bug that survives fixing the other.
        let style = TableStyle::default();
        let widths = constraints(&columns(), &rows(), &sizing(), Priority::Secondary, &style);
        assert_eq!(widths.len(), 4, "two columns and the two edges");
        let drawn = row(&columns(), &rows()[0], Priority::Secondary, &ink_of(&style));
        assert_eq!(cell_text(&drawn), vec!["alpha", "1kb", ""]);
    }

    #[test]
    fn a_fill_column_keeps_its_floor_while_taking_the_slack() {
        // `Min` and not `Fill`, which is `minmax(10, 1fr)` at the webview
        // renderer. A `Fill` track collapses under a fixed neighbour.
        let style = TableStyle::default();
        let widths = constraints(&columns(), &rows(), &sizing(), Priority::Optional, &style);
        assert_eq!(widths[1], Constraint::Min(10));
        assert_eq!(widths[2], Constraint::Length(6));
    }

    #[test]
    fn a_column_with_no_length_of_its_own_takes_the_fallback() {
        let cols = vec![
            Head::new("unlisted")
                .width(Width::Fixed)
                .priority(Priority::Essential)
                .kind(ColumnKind::Text)
                .sortable(false),
        ];
        let rows: Vec<Vec<Cell<'_>>> = vec![];
        let widths = constraints(
            &cols,
            &rows,
            &sizing(),
            Priority::Optional,
            &TableStyle::default(),
        );
        assert_eq!(widths[1], Constraint::Length(4));
    }

    #[test]
    fn a_heading_carries_a_caret_when_it_is_ordered_by_or_offers_to_be() {
        let style = TableStyle::default();
        let head = header(&columns(), Priority::Optional, &ink_of(&style));
        assert_eq!(
            cell_text(&head),
            vec!["NAME \u{25B2}", "SIZE \u{25B2}", "NOTE"],
            "in force and offering both carry one; not a control carries none"
        );
    }

    #[test]
    fn the_three_states_of_a_heading_are_three_tones() {
        // wiki `three-tone-convention`. The middle state is the one that had
        // nowhere to be said: a heading you can press looked exactly like one
        // you cannot, and the idle caret alone does not separate them, because
        // a sorted-but-unsortable column draws a caret too.
        let mut ink = ink_of(&TableStyle::default());
        ink.sorted = Style::new().fg(Color::Red);
        ink.sortable = Style::new().fg(Color::Green);
        ink.header = Style::new().fg(Color::Blue);
        let drawn = cell_colors(&header(&columns(), Priority::Optional, &ink));
        assert_eq!(
            drawn,
            vec![Some(Color::Red), Some(Color::Green), Some(Color::Blue)]
        );

        // The colourless default separates them by the caret and nothing else,
        // and that is the honest limit rather than an oversight: a cell style
        // patches the row's, so a plain cell under a bold header row is drawn
        // bold whatever it holds. Three tones need three colours, which is what
        // a palette's tones are for.
        let house = TableStyle::default();
        let plain = cell_colors(&header(&columns(), Priority::Optional, &ink_of(&house)));
        assert_eq!(plain[0], plain[1], "no colour to spend, so none is claimed");
    }

    #[test]
    fn pressing_a_heading_does_not_move_the_columns_after_it() {
        // The reflow the idle caret closes. `measure` sizes from `heading`, so
        // a caret that appeared with the press widened its own column by two
        // cells and shifted the rest of the row sideways.
        let style = TableStyle::default();
        let offering = Head::new("size")
            .width(Width::Content)
            .priority(Priority::Secondary)
            .kind(ColumnKind::Text)
            .sortable(true);
        let in_force = offering.sorted(Sort::Descending);
        assert_eq!(measure(&offering, 0, &style), measure(&in_force, 0, &style));

        // And the column that is not a control at all is narrower, which is the
        // width that would be wrong to reserve: it has no caret to draw.
        let inert = offering.sortable(false);
        assert!(measure(&inert, 0, &style) < measure(&offering, 0, &style));
    }

    #[test]
    fn a_column_sorted_without_being_sortable_still_draws_its_caret() {
        // A list ordered by a key the user cannot change is a real thing to
        // describe, which is why the description holds the two fields apart.
        // Drawing the caret only for a sortable column would collapse them.
        let cols = vec![
            Head::new("rank")
                .width(Width::Content)
                .priority(Priority::Essential)
                .kind(ColumnKind::Text)
                .sortable(false)
                .sorted(Sort::Descending),
        ];
        let head = header(&cols, Priority::Optional, &ink_of(&TableStyle::default()));
        assert_eq!(cell_text(&head), vec!["RANK \u{25BC}", "", ""]);
    }

    #[test]
    fn a_cell_part_takes_the_ink_its_intent_names() {
        // makeover-layout's `CellPart::intent` is the rule every host reads, so
        // a link here draws as the webview's does: in the values' ink, with no
        // underline.
        let tones = crate::Tones {
            content: Some(Color::Indexed(1)),
            secondary: Some(Color::Indexed(2)),
            muted: Some(Color::Indexed(3)),
            action: Some(Color::Indexed(4)),
            ..crate::Tones::default()
        };
        let ink = ink_with(tones);
        for part in [
            CellPart::Value,
            CellPart::Tokens,
            CellPart::Actions,
            CellPart::Link,
        ] {
            let want = match part.intent() {
                "content" => tones.content,
                "content-secondary" => tones.secondary,
                "content-muted" => tones.muted,
                other => panic!("{part:?} names {other}, which this renderer has not learned"),
            };
            let got = ink.for_part(Some(part));
            assert_eq!(got.fg, want, "{part:?}");
            assert_eq!(got.add_modifier, Modifier::empty(), "{part:?}");
        }
        // A cell mixing parts says nothing, and takes the text style.
        assert_eq!(ink.for_part(None), ink.value);
    }

    #[test]
    fn a_table_narrows_itself_from_the_width_it_is_given() {
        // The whole path in one call, which is what a consumer actually uses.
        let style = TableStyle::default();
        let wide = table(&columns(), &rows(), &sizing(), 40, &ink_of(&style));
        let narrow = table(&columns(), &rows(), &sizing(), 20, &ink_of(&style));
        use ratatui::layout::Rect;
        use ratatui::widgets::Widget;

        let mut buf = ratatui::buffer::Buffer::empty(Rect::new(0, 0, 40, 3));
        wide.render(Rect::new(0, 0, 40, 3), &mut buf);
        let head: String = (0..40).map(|x| buf[(x, 0)].symbol()).collect();
        assert!(head.contains("NOTE"));

        let mut buf = ratatui::buffer::Buffer::empty(Rect::new(0, 0, 20, 3));
        narrow.render(Rect::new(0, 0, 20, 3), &mut buf);
        let head: String = (0..20).map(|x| buf[(x, 0)].symbol()).collect();
        assert!(!head.contains("NOTE"), "the optional column is gone");
        assert!(head.contains("NAME"), "the essential one is not");
    }

    #[test]
    fn selection_is_carried_by_the_background_alone() {
        // A row can be red for a failure or green for a success, and a
        // foreground on the selection loses that on exactly the row being looked
        // at. Asserted with a selection colour and without one.
        assert!(ink_of(&TableStyle::default()).selected.fg.is_none());
        let coloured = ink_with(crate::Tones::NONE.selected(Color::Blue));
        assert_eq!(coloured.selected.bg, Some(Color::Blue));
        assert!(coloured.selected.fg.is_none());
    }

    #[test]
    fn a_number_column_aligns_its_cells_and_heading_to_the_end() {
        let mut amount = Head::new("Amount");
        amount.room.kind = ColumnKind::Number;
        let prose = Head::new("Buyer");
        assert_eq!(
            aligned(&amount, Line::from("9.99")).alignment,
            Some(ratatui::layout::Alignment::Right)
        );
        assert_eq!(aligned(&prose, Line::from("ada")).alignment, None);
    }

    #[test]
    fn a_row_keeps_a_cell_of_ground_at_either_end() {
        // The block padding, in cells. The first value does not touch the
        // table's left edge and an end-aligned last column does not touch its
        // right, whichever columns narrowing left first and last.
        use ratatui::layout::Rect;
        use ratatui::widgets::Widget;
        // Declared narrow, so both columns are kept in twelve cells: this is
        // about the ground at the ends, not about narrowing.
        let cols = vec![Head::new("a").min(2), {
            let mut n = Head::new("n").min(2);
            n.room.kind = ColumnKind::Number;
            n.room.width = Width::Fill;
            n
        }];
        let rows = vec![vec![Cell::new("a", "x"), Cell::new("n", "9")]];
        let drawn = table(&cols, &rows, &sizing(), 12, &ink_of(&TableStyle::default()));
        let mut buf = ratatui::buffer::Buffer::empty(Rect::new(0, 0, 12, 2));
        drawn.render(Rect::new(0, 0, 12, 2), &mut buf);
        let body: String = (0..12).map(|x| buf[(x, 1)].symbol()).collect();
        assert!(body.starts_with(" x"), "{body:?}");
        assert!(body.ends_with("9 "), "{body:?}");
    }

    #[test]
    fn every_second_row_takes_the_stripe_and_a_code_table_takes_none() {
        use ratatui::layout::Rect;
        use ratatui::widgets::Widget;
        let ink = ink_with(crate::Tones::NONE.ground(Color::Blue).stripe(Color::Green));
        let grounds = |cols: &[Head<'_>]| -> Vec<Color> {
            let rows: Vec<Vec<Cell<'_>>> = (0..3).map(|_| vec![Cell::new("a", "x")]).collect();
            let mut buf = ratatui::buffer::Buffer::empty(Rect::new(0, 0, 8, 4));
            table(cols, &rows, &sizing(), 8, &ink).render(Rect::new(0, 0, 8, 4), &mut buf);
            (1..4).map(|y| buf[(0, y)].bg).collect()
        };
        let records = vec![Head::new("a").min(2)];
        assert_eq!(
            grounds(&records),
            vec![Color::Blue, Color::Green, Color::Blue]
        );

        let mut code = Head::new("a").min(2);
        code.room.kind = ColumnKind::Code;
        assert_eq!(grounds(&[code]), vec![Color::Blue; 3]);
    }

    /// Two columns sharing a name draw two cells, in order. Matched on the
    /// name alone both would draw the first, and the second never showed.
    #[test]
    fn same_named_columns_take_same_named_cells_in_order() {
        let cols = vec![
            Head::new("y").width(Width::Fixed),
            Head::new("x").width(Width::Fixed),
            Head::new("y").width(Width::Content),
        ];
        let cells = vec![
            Cell::new("y", "first"),
            Cell::new("x", "middle"),
            Cell::new("y", "second, longer"),
        ];
        let drawn = row(
            &cols,
            &cells,
            Priority::Optional,
            &ink_of(&TableStyle::default()),
        );
        assert_eq!(cell_text(&drawn), vec!["first", "middle", "second, longer"]);
        assert_eq!(widest_cell(&cols, 0, &[&cells[..]]), 5);
        assert_eq!(widest_cell(&cols, 2, &[&cells[..]]), 14);
    }

    /// A stretch of a table draws exactly what the whole table draws on those
    /// lines: the same columns, the same stripe, the same cells. That is the
    /// contract a caller windowing a long table relies on, so it is asserted
    /// line by line against a render of every row.
    #[test]
    fn a_window_draws_what_the_whole_table_draws_on_its_lines() {
        use ratatui::layout::Rect;
        use ratatui::widgets::Widget;

        let cols = columns();
        let long: Vec<Vec<Cell<'static>>> = (0..9)
            .map(|i| {
                vec![
                    Cell::new("name", format!("row {i}")),
                    Cell::new("size", "1kb"),
                    Cell::new("note", "n".repeat(i * 3)),
                ]
            })
            .collect();
        let ink = ink_of(&TableStyle::default());
        let width = 60;

        let mut whole = ratatui::buffer::Buffer::empty(Rect::new(0, 0, width, 10));
        table(&cols, &long, &sizing(), width, &ink).render(whole.area, &mut whole);

        // Rows 3 to 5, no heading, drawn three lines tall.
        let mut part = ratatui::buffer::Buffer::empty(Rect::new(0, 0, width, 3));
        table_window(
            &cols,
            &long[3..6],
            Window {
                first: 3,
                header: false,
            },
            |at| widest_cell(&cols, at, &long),
            &sizing(),
            width,
            &ink,
        )
        .render(part.area, &mut part);

        for line in 0..3u16 {
            for x in 0..width {
                // Line 0 of the whole render is the heading, so row 3 is on
                // line 4.
                assert_eq!(
                    part[(x, line)],
                    whole[(x, line + 4)],
                    "line {line}, column {x}"
                );
            }
        }
    }

    /// With the heading kept, a window starting at the top is the table.
    #[test]
    fn the_whole_window_is_the_table() {
        use ratatui::layout::Rect;
        use ratatui::widgets::Widget;

        let ink = ink_of(&TableStyle::default());
        let area = Rect::new(0, 0, 40, 3);
        let mut a = ratatui::buffer::Buffer::empty(area);
        let mut b = ratatui::buffer::Buffer::empty(area);
        table(&columns(), &rows(), &sizing(), 40, &ink).render(area, &mut a);
        table_window(
            &columns(),
            &rows(),
            Window::WHOLE,
            |at| widest_cell(&columns(), at, &rows()),
            &sizing(),
            40,
            &ink,
        )
        .render(area, &mut b);
        assert_eq!(a, b);
    }
}