makeover-tui 0.52.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
//! 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
//!
//! Carried from the webview renderer verbatim, because the mistake is not a CSS
//! mistake. goingson hides its mobile columns with `nth-child(n+5)` against a
//! seven-column table; insert a column left of the cut and the wrong one
//! disappears, 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 [`TableStyle::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::{CellPart, Column, ColumnKind, Priority, Sort, Width};
use ratatui::layout::Constraint;
use ratatui::style::{Modifier, Style};
use ratatui::text::Line;
use ratatui::widgets::{Cell as TrackCell, Row, Table};

/// The cutoffs, weakest first.
///
/// [`Priority`] is `#[non_exhaustive]` and a tier added upstream has to be added
/// here in its place in the sequence, or a table will never narrow to it. Grep
/// this when adopting a new `makeover-layout`, the way
/// `makeover-webview`'s `part_class` asks to be grepped. The cost of missing one
/// is a column that drops later than it should, which is visible, rather than a
/// build that stops.
const CUTOFFS: [Priority; 3] = [Priority::Optional, Priority::Secondary, Priority::Essential];

/// The lengths the description deferred, in cells.
///
/// [`Width`] says `Content`, `Fixed` or `Fill` and carries no magnitude, because
/// a magnitude is an answer for one renderer and the description is read by
/// three. `makeover-webview`'s `Sizing` is this same type holding CSS lengths;
/// this one holds terminal cells, and both are looked up by column name for the
/// same reason: an app's columns are not all one size.
#[derive(Debug, Clone, Copy, Default)]
pub struct Sizing<'a> {
    /// `(column name, cells)`. The track for a [`Width::Fixed`] column and the
    /// floor for a [`Width::Fill`] one.
    pub lengths: &'a [(&'a str, u16)],
    /// Used for a column with no entry above.
    pub fallback: u16,
}

impl Sizing<'_> {
    /// The length for a named column.
    fn length_for(&self, name: &str) -> u16 {
        self.lengths
            .iter()
            .find(|(column, _)| *column == name)
            .map_or(self.fallback, |(_, length)| *length)
    }
}

/// 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 tones and metrics a table draws with.
///
/// Apart from [`Palette`] rather than added to it, and the split is the one
/// `makeover-immediate` draws between its palette and its `FieldStyle`:
/// [`Palette`] answers what a *surface* is, which is what
/// [`frame`](crate::frame) needs, and a table is the first thing in this crate
/// that draws text. Folding text tones into [`Palette`] would make every
/// consumer that only paints a bevel supply six colours it never uses.
///
/// [`from_theme`](Self::from_theme) is the answer for anyone with a loaded
/// theme, and is what a consumer should reach for first.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct TableStyle {
    /// 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. A
    /// heading that took [`header`](Self::header) here would be indistinguishable
    /// from a column that cannot be reordered at all, which is the state this
    /// separates it from.
    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 sits under one rather than what paints it.
    pub tokens: Style,
    /// A cell holding controls.
    pub actions: Style,
    /// A cell whose value is itself a link.
    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,
    /// 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`], which is where the spelling lives now: three
    /// renderers holding the same literal agreed by coincidence. Still 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 [`heading`]'s, written once for
    /// all three states rather than baked into two strings and forgotten in the
    /// third.
    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 {
            header: Style::new().add_modifier(Modifier::BOLD),
            sorted: Style::new().add_modifier(Modifier::BOLD),
            // Nothing of its own. A cell style patches the row's, so a colour
            // is the only thing that could separate this from the header row it
            // sits in, and the colourless default has none to spend: the idle
            // caret is what says the heading answers a press. `from_theme` is
            // where the three tones are real.
            sortable: Style::new(),
            value: Style::new(),
            tokens: Style::new(),
            actions: Style::new(),
            link: Style::new().add_modifier(Modifier::UNDERLINED),
            selected: Style::new().add_modifier(Modifier::REVERSED),
            ground: Style::new(),
            stripe: Style::new(),
            column_spacing: 1,
            ascending: Sort::Ascending.glyph(),
            descending: Sort::Descending.glyph(),
        }
    }
}

impl TableStyle {
    /// The house table, from a loaded theme.
    ///
    /// 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, actions and links on the action colour
    /// rather than on the cell's text colour, and selection carried by the
    /// background alone.
    ///
    /// Where the terminal cannot tell the strip from the ground, which is
    /// sixteen colours on most themes, the heading is underlined instead: the
    /// separation is what the strip is for, and a line is what is left to say
    /// it with.
    ///
    /// 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 distinction on exactly the row the user is looking
    /// at. `mnw-cli`'s `selected_style` found this and its comment says so;
    /// this is that comment's code, in the library, once.
    #[cfg(feature = "theme")]
    #[must_use]
    pub fn from_theme(theme: &crate::Theme) -> Self {
        let mut strip = Style::new()
            .fg(theme.content_secondary)
            .bg(theme.surface_sunken)
            .add_modifier(Modifier::BOLD);
        if !crate::Palette::shows(theme.surface_sunken, theme.surface_raised) {
            strip = strip.add_modifier(Modifier::UNDERLINED);
        }
        Self {
            header: strip,
            sorted: Style::new()
                .fg(theme.content_primary)
                .add_modifier(Modifier::BOLD),
            // The strip's own ink. Offering and inert differ by the idle caret,
            // which is the webview's split too: the strip separates the header
            // now, so no heading has to stay quiet by being pale.
            sortable: Style::new().fg(theme.content_secondary),
            value: Style::new().fg(theme.content_primary),
            // A token paints its own background, and a tone underneath it would
            // fight the one sitting on it. Secondary is what shows through the
            // gaps.
            tokens: Style::new().fg(theme.content_secondary),
            actions: Style::new().fg(theme.action_primary),
            link: Style::new()
                .fg(theme.action_primary)
                .add_modifier(Modifier::UNDERLINED),
            selected: Style::new()
                .bg(theme.row_selected)
                .add_modifier(Modifier::BOLD),
            ground: Style::new().bg(theme.surface_raised),
            stripe: Style::new().bg(theme.row_stripe),
            column_spacing: 1,
            ascending: Sort::Ascending.glyph(),
            descending: Sort::Descending.glyph(),
        }
    }

    /// 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.
    /// Grep this when adopting a new `makeover-layout`.
    #[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,
        }
    }
}

/// 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: &Column<'a>, line: Line<'a>) -> Line<'a> {
    if column.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`](Column::sorted) but not
/// [`sortable`](Column::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: &Column<'_>, style: &TableStyle) -> Line<'static> {
    let label = column.name.to_uppercase();
    let caret = match column.sorted {
        Some(Sort::Ascending) => style.ascending,
        Some(Sort::Descending) => style.descending,
        None if column.sortable => style.ascending,
        None => return Line::from(label),
    };
    // The gap, once, rather than inside each of the two style strings. A
    // consumer swapping the glyph for an ASCII one does not have to remember to
    // bring a space with it.
    Line::from(format!("{label} {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 widest thing in a column, heading included.
///
/// 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 [`Column::name`].
fn measure<'a, R>(column: &Column<'a>, rows: &[R], style: &TableStyle) -> u16
where
    R: AsRef<[Cell<'a>]>,
{
    let widest = rows
        .iter()
        .filter_map(|row| {
            row.as_ref()
                .iter()
                .find(|cell| cell.column == column.name)
                .map(|cell| cell.content.width())
        })
        .max()
        .unwrap_or(0);
    u16::try_from(widest.max(heading(column, style).width())).unwrap_or(u16::MAX)
}

/// Whether the columns kept at `cutoff` fit in `width`.
///
/// Budgeted at each column's declared [`floor`](Column::floor), never at its
/// measured width. A cell is one `ch`, so this is the same number the webview
/// hides a column under and the immediate-mode painter budgets in points, which
/// is what makes the three hosts drop a column at one declared width. What a
/// kept track is drawn at is still measured, in [`constraints`].
fn fits(columns: &[Column<'_>], style: &TableStyle, cutoff: Priority, width: u16) -> bool {
    let kept = columns.iter().filter(|c| c.kept_at(cutoff));
    // One gap either side of every column, since the two edges are tracks.
    let (count, floors) = kept.fold((0u32, 0u32), |(n, sum), c| {
        (n + 1, sum + u32::from(c.floor()))
    });
    let gaps = u32::from(style.column_spacing) * (count + 1);
    floors + gaps <= u32::from(width)
}

/// The weakest cutoff whose columns fit in `width`.
///
/// Raised until the layout fits, and never past [`Priority::Essential`]: the
/// essential columns are what makes a row identify itself, so a window too
/// narrow for them gets them truncated rather than dropped. Nothing here counts
/// positions, so which column drops is a property of the column.
#[must_use]
pub fn cutoff_for(columns: &[Column<'_>], style: &TableStyle, width: u16) -> Priority {
    for cutoff in CUTOFFS {
        if fits(columns, style, cutoff, width) {
            return cutoff;
        }
    }
    Priority::Essential
}

/// 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, which is the other half of the goingson bug the
/// webview renderer's `grid_template_columns` names.
///
/// 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: &[Column<'a>],
    rows: &[R],
    sizing: &Sizing<'_>,
    style: &TableStyle,
    cutoff: Priority,
) -> Vec<Constraint>
where
    R: AsRef<[Cell<'a>]>,
{
    let tracks = columns
        .iter()
        .filter(|column| column.kept_at(cutoff))
        .map(|column| match column.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, rows, style)),
            Width::Fixed => Constraint::Length(sizing.length_for(column.name)),
            // `Min` and not `Fill`: a fill column absorbs the slack *and* keeps
            // its floor, which is what `minmax(len, 1fr)` says at the webview
            // renderer. `Fill` would let it collapse below the floor when a
            // fixed column takes the room.
            _ => Constraint::Min(sizing.length_for(column.name)),
        });
    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 [`TableStyle::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
/// `makeover-webview`'s `cells_html` rule, 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: &[Column<'a>],
    cells: &[Cell<'a>],
    style: &TableStyle,
    cutoff: Priority,
) -> Row<'a> {
    Row::new(edged(
        columns
            .iter()
            .filter(|column| column.kept_at(cutoff))
            .map(|column| {
                let found = cells.iter().find(|cell| cell.column == column.name);
                let part = found.and_then(|cell| cell.part);
                let content = found.map_or_else(Line::default, |cell| cell.content.clone());
                TrackCell::from(aligned(column, content)).style(style.for_part(part))
            }),
    ))
    .style(style.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. Assembling it a second time by hand is how they stop
/// agreeing.
#[must_use]
pub fn header<'a>(columns: &[Column<'a>], style: &TableStyle, cutoff: Priority) -> 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 -- and the middle
                // one is the state that had nowhere to be said, so a heading
                // you could press looked exactly like one you could not.
                let tone = match (column.sorted, column.sortable) {
                    (Some(_), _) => style.sorted,
                    (None, true) => style.sortable,
                    (None, false) => style.header,
                };
                TrackCell::from(aligned(column, heading(column, style))).style(tone)
            }),
    ))
    .style(style.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 [`TableStyle::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.
#[must_use]
pub fn table<'a, R>(
    columns: &[Column<'a>],
    rows: &[R],
    sizing: &Sizing<'_>,
    style: &TableStyle,
    width: u16,
) -> Table<'a>
where
    R: AsRef<[Cell<'a>]>,
{
    let cutoff = cutoff_for(columns, style, width);
    let widths = constraints(columns, rows, sizing, style, cutoff);
    let striped = striped(columns, cutoff);
    let body: Vec<Row<'a>> = rows
        .iter()
        .enumerate()
        .map(|(index, cells)| {
            let drawn = row(columns, cells.as_ref(), style, cutoff);
            if striped && index % 2 == 1 {
                drawn.style(style.stripe)
            } else {
                drawn
            }
        })
        .collect();

    Table::new(body, widths)
        .header(header(columns, style, cutoff))
        .column_spacing(style.column_spacing)
        .row_highlight_style(style.selected)
}

/// 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: &[Column<'_>], cutoff: Priority) -> bool {
    !columns
        .iter()
        .any(|column| column.kept_at(cutoff) && column.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: &[Column<'_>], style: &TableStyle, width: u16) -> bool {
    !fits(columns, style, Priority::Essential, width)
}

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

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

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

    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,
            &TableStyle::default(),
            Priority::Optional,
        );
        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, &TableStyle::default(), Priority::Optional);
        // 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(), &style, Priority::Optional);
        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![Column {
            name: "duration",
            width: Width::Content,
            priority: Priority::Essential,
            kind: ColumnKind::Text,
            min: None,
            sortable: false,
            sorted: None,
        }];
        let rows = vec![vec![Cell::new("duration", "3s")]];
        let widths = constraints(
            &cols,
            &rows,
            &sizing(),
            &TableStyle::default(),
            Priority::Optional,
        );
        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![Column {
            name: "size",
            width: Width::Content,
            priority: Priority::Essential,
            kind: ColumnKind::Text,
            min: None,
            sortable: true,
            sorted: Some(Sort::Descending),
        }];
        let rows: Vec<Vec<Cell<'_>>> = vec![];
        let style = TableStyle::default();
        let widths = constraints(&cols, &rows, &sizing(), &style, Priority::Optional);
        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, &style, 36), Priority::Optional);
        assert_eq!(cutoff_for(&cols, &style, 35), Priority::Secondary);
        // No room for the note: 24 + 3.
        assert_eq!(cutoff_for(&cols, &style, 27), Priority::Secondary);
        // No room for the size either: 16 + 2.
        assert_eq!(cutoff_for(&cols, &style, 26), Priority::Essential);
        assert_eq!(cutoff_for(&cols, &style, 18), Priority::Essential);
        // No room for anything, and the essential column stays anyway.
        assert_eq!(cutoff_for(&cols, &style, 2), Priority::Essential);
        assert!(overflows(&cols, &style, 2));
        assert!(!overflows(&cols, &style, 18));
    }

    #[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, &style, 36), Priority::Optional);
        cols[2] = cols[2].min(20);
        assert_eq!(cutoff_for(&cols, &style, 36), Priority::Secondary);
        assert_eq!(cutoff_for(&cols, &style, 48), 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: &[Column<'_>], 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![Column {
            name: "mark",
            width: Width::Fixed,
            priority: Priority::Essential,
            kind: ColumnKind::Text,
            min: None,
            sortable: false,
            sorted: None,
        }];
        after.extend(columns());

        for cutoff in CUTOFFS {
            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, &style, width);
            let kept: Vec<&str> = cols
                .iter()
                .filter(|c| c.kept_at(cutoff))
                .map(|c| c.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(), &style, Priority::Secondary);
        assert_eq!(widths.len(), 4, "two columns and the two edges");
        let drawn = row(&columns(), &rows()[0], &style, Priority::Secondary);
        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(), &style, Priority::Optional);
        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![Column {
            name: "unlisted",
            width: Width::Fixed,
            priority: Priority::Essential,
            kind: ColumnKind::Text,
            min: None,
            sortable: false,
            sorted: None,
        }];
        let rows: Vec<Vec<Cell<'_>>> = vec![];
        let widths = constraints(
            &cols,
            &rows,
            &sizing(),
            &TableStyle::default(),
            Priority::Optional,
        );
        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(), &style, Priority::Optional);
        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.
        use ratatui::style::Color;
        let style = TableStyle {
            sorted: Style::new().fg(Color::Red),
            sortable: Style::new().fg(Color::Green),
            header: Style::new().fg(Color::Blue),
            ..TableStyle::default()
        };
        let drawn = cell_colors(&header(&columns(), &style, Priority::Optional));
        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
        // `from_theme` is for.
        let house = TableStyle::default();
        let plain = cell_colors(&header(&columns(), &house, Priority::Optional));
        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 = Column {
            name: "size",
            width: Width::Content,
            priority: Priority::Secondary,
            kind: ColumnKind::Text,
            min: None,
            sortable: true,
            sorted: None,
        };
        let in_force = Column {
            sorted: Some(Sort::Descending),
            ..offering
        };
        let rows: Vec<Vec<Cell<'_>>> = vec![];
        assert_eq!(
            measure(&offering, &rows, &style),
            measure(&in_force, &rows, &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 = Column {
            sortable: false,
            ..offering
        };
        assert!(measure(&inert, &rows, &style) < measure(&offering, &rows, &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![Column {
            name: "rank",
            width: Width::Content,
            priority: Priority::Essential,
            kind: ColumnKind::Text,
            min: None,
            sortable: false,
            sorted: Some(Sort::Descending),
        }];
        let head = header(&cols, &TableStyle::default(), Priority::Optional);
        assert_eq!(cell_text(&head), vec!["RANK \u{25BC}", "", ""]);
    }

    #[test]
    fn the_parts_a_cell_can_be_are_styled_apart() {
        // The drift `CellPart` exists to end: one style for a whole cell paints
        // a control as though it were text.
        let style = TableStyle::default();
        assert_eq!(style.for_part(Some(CellPart::Value)), style.value);
        assert_eq!(style.for_part(Some(CellPart::Tokens)), style.tokens);
        assert_eq!(style.for_part(Some(CellPart::Actions)), style.actions);
        assert_eq!(style.for_part(Some(CellPart::Link)), style.link);
        assert_ne!(style.for_part(Some(CellPart::Link)), style.value);
        // A cell mixing parts says nothing, and takes the text style.
        assert_eq!(style.for_part(None), style.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(), &style, 40);
        let narrow = table(&columns(), &rows(), &sizing(), &style, 20);
        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 on the default so a caller who supplies no theme still
        // gets the rule.
        let style = TableStyle::default();
        assert!(style.selected.fg.is_none());
    }

    #[test]
    fn a_number_column_aligns_its_cells_and_heading_to_the_end() {
        let mut amount = Column::new("Amount");
        amount.kind = ColumnKind::Number;
        let prose = Column::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![Column::new("a").min(2), {
            let mut n = Column::new("n").min(2);
            n.kind = ColumnKind::Number;
            n.width = Width::Fill;
            n
        }];
        let rows = vec![vec![Cell::new("a", "x"), Cell::new("n", "9")]];
        let drawn = table(&cols, &rows, &sizing(), &TableStyle::default(), 12);
        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::style::Color;
        use ratatui::widgets::Widget;
        let style = TableStyle {
            ground: Style::new().bg(Color::Blue),
            stripe: Style::new().bg(Color::Green),
            ..TableStyle::default()
        };
        let grounds = |cols: &[Column<'_>]| -> 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(), &style, 8).render(Rect::new(0, 0, 8, 4), &mut buf);
            (1..4).map(|y| buf[(0, y)].bg).collect()
        };
        let records = vec![Column::new("a").min(2)];
        assert_eq!(
            grounds(&records),
            vec![Color::Blue, Color::Green, Color::Blue]
        );

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