makeover-immediate 0.55.1

The immediate-mode renderer for makeover-layout. Immediate mode is the constraint that matters, not the library: no cascade, no retained tree, one stroke per widget. Backed by egui.
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
//! Columns, narrowing, cell parts and the sort caret, over `egui_extras`.
//!
//! `makeover-webview`'s `list` module and `makeover-tui`'s `table` in the shape
//! immediate mode 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, which here is not a policy but
//! a fact of the mode: a cell's contents are drawn by the app's own closure, the
//! way [`group`](crate::group) already takes one per field.
//!
//! # Why `egui_extras` and not egui
//!
//! egui itself has no table. [`egui::Grid`] gives no per-column sizing, no
//! sticky header and no scroll sync, which is why audiofiles reached for
//! `egui_extras::TableBuilder` rather than building on `Grid`. Writing a third
//! answer here would be reimplementing that crate worse, so this is a mapping
//! layer over it.
//!
//! It is the first dependency this crate has taken beyond egui itself, and it
//! moves in lockstep with egui's own version, which is the cost worth naming.
//!
//! # What immediate mode costs the narrowing
//!
//! The terminal renderer measures a [`Width::Content`] column from its cells,
//! because it holds every cell before it draws any. Here the cells do not exist
//! until the app's closure runs, so nothing can be measured before the layout is
//! decided.
//!
//! That splits the answer in two, and both halves are honest:
//!
//! - **Sizing** hands a content column to
//!   [`egui_extras::Column::auto`], which measures it and holds the result
//!   between frames. This is better than the terminal gets, not worse.
//! - **Narrowing** cannot wait for that, so it budgets every column at its
//!   declared [`floor`](Column::floor), in `ch` of the body face. A column that
//!   turns out wider than its floor is still drawn; it is the *decision to drop*
//!   that uses the declared number, and it is the number the terminal counts in
//!   cells and the webview hides a column under, so the three drop together.
//!
//! # The table model
//!
//! Wiki `table-model`, drawn the way `makeover-webview` draws it, since egui
//! paints the same pixels a browser does: a raised ground inside a hairline
//! frame, the header a sunken strip over a `bevel-dark` edge in secondary
//! capitals, rows 45 points tall with a hairline between them, a stripe on
//! every second row and a tone under the pointer. A table holding a
//! [`ColumnKind::Code`] column keeps the frame and the header and drops the
//! stripe, the hairlines and the tall row.
//!
//! The row fills are painted here rather than by egui_extras, for two reasons
//! the crate cannot be configured past. Its stripe falls on the first row where
//! the model's falls on the second, and its selection repaints the row's text
//! in the selection stroke, which loses a failed row's red on exactly the row
//! the user picked. A selected row takes `row-selected` behind its text and
//! nothing else.
//!
//! # Why positions are the bug
//!
//! Carried from the other two renderers, because the mistake is not a CSS
//! mistake and not a terminal one. 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. A renderer narrows by raising a
//! cutoff and never by counting.

use crate::Palette;
use egui::{Response, RichText, Sense, Ui};
use egui_extras::{Column as Track, TableBuilder};
use makeover_layout::{CellPart, Column, ColumnKind, Priority, Sort, Width};

/// 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`; `makeover-tui` carries the same
/// list for the same reason, and the two have to agree or a description narrows
/// differently in a window than in a terminal.
const CUTOFFS: [Priority; 3] = [Priority::Optional, Priority::Secondary, Priority::Essential];

/// The lengths the description deferred, in points.
///
/// [`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. The other two renderers hold this same type over CSS lengths and over
/// terminal cells.
#[derive(Debug, Clone, Copy, Default)]
pub struct Sizing<'a> {
    /// `(column name, points)`. The track for a [`Width::Fixed`] column, the
    /// floor for a [`Width::Fill`] one, and the narrowing budget for a
    /// [`Width::Content`] one.
    pub lengths: &'a [(&'a str, f32)],
    /// Used for a column with no entry above.
    pub fallback: f32,
}

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

/// The tones and metrics a table draws with.
///
/// Metrics only, and the tones come from [`Palette`]. That is the division this
/// crate already draws: [`FieldStyle`](crate::FieldStyle) carries gaps and a
/// marker while the colours stay in the palette, and a table's colours are the
/// palette's `content`, `content_muted` and `action` rather than six new ones.
/// `makeover-tui` splits it the other way round because its palette carries no
/// text tones at all.
#[derive(Debug, Clone, Copy, PartialEq)]
pub struct TableStyle {
    /// The height of the heading row.
    pub header_height: f32,
    /// The height of a body row: the model's 45, `--row-block` at
    /// `makeover-geometry`'s base.
    pub row_height: f32,
    /// The height of a row in a table holding code, which is one line of
    /// source rather than a record.
    pub code_row_height: f32,
    /// The ground between the table's frame and the cells at either end of a
    /// row: the webview's `gap-group`, which pads both ends of a row.
    pub edge_padding: f32,
    /// 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. 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,
    /// Drawn after the heading of a descending column.
    pub descending: &'static str,
    /// Whether the user can drag the divider between two columns.
    ///
    /// The one knob that is not a metric. Not every setting egui_extras has
    /// becomes a field here: a sticky heading is what `TableBuilder::header`
    /// does and there is no version that does not, and the stripe is the table
    /// model's at every host, so a knob for either would offer a choice this
    /// renderer cannot make. Off by default: the description has no word for
    /// resizing, so a default that turned it on would be this renderer adding a
    /// claim the other two cannot make.
    ///
    /// It does not fight the narrowing. A drag moves a track for the frames it
    /// is held; [`cutoff_for`] still decides which columns exist, off each
    /// column's declared [`floor`](Column::floor), so a resize can never drop a
    /// column.
    pub resizable: bool,
}

impl Default for TableStyle {
    fn default() -> Self {
        Self {
            header_height: 32.0,
            row_height: 45.0,
            code_row_height: 20.0,
            edge_padding: 12.0,
            ascending: Sort::Ascending.glyph(),
            descending: Sort::Descending.glyph(),
            resizable: false,
        }
    }
}

/// The body's own facts for this frame: how many rows, which are selected, and
/// which one to bring into view.
///
/// Held apart from [`TableStyle`] because none of it is style and none of it
/// survives the frame: a row count changes when a folder does, a selection when
/// the user clicks, and a scroll request exists for exactly one frame. Held
/// apart from the [`Column`] slice because none of it is description either.
/// The description says what a table *is*, and this says what it holds right
/// now.
///
/// Both of the optional fields are here rather than left to the app because
/// egui_extras answers them on a handle the app never sees: `set_selected` is a
/// method on the row, and `scroll_to_row` a method on the builder, and this
/// crate owns both. That is the same reason [`cell`] exists.
#[derive(Default)]
pub struct Body<'a> {
    /// How many rows to draw.
    pub rows: usize,
    /// Whether a row is selected, by index.
    ///
    /// A predicate rather than a set, so an app whose selection is a range, a
    /// bitmap or a single index does not have to build a collection to be asked.
    /// `None` is a table no row of which is selected, which is not the same
    /// claim as a predicate that always answers false and costs nothing to make.
    pub selected: Option<&'a dyn Fn(usize) -> bool>,
    /// A row to bring into view this frame.
    ///
    /// Set it from a request the app then clears, the way a keyboard cursor
    /// moving off-screen raises one: held rather than taken, it would fight
    /// every scroll the user makes with the mouse.
    pub scroll_to: Option<usize>,
}

impl std::fmt::Debug for Body<'_> {
    // Hand-written because `selected` is a closure and `#[derive(Debug)]` will
    // not have it. What is worth printing is whether one was supplied.
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.debug_struct("Body")
            .field("rows", &self.rows)
            .field("selected", &self.selected.is_some())
            .field("scroll_to", &self.scroll_to)
            .finish()
    }
}

/// The colour a cell of this part takes.
///
/// [`CellPart`] is `#[non_exhaustive]`, and a member added upstream lands on
/// `content`: 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 const fn part_color(part: Option<CellPart>, palette: &Palette) -> egui::Color32 {
    match part {
        // A token paints its own background and carries its own tone. What is
        // set here is what shows between them, not what paints them.
        Some(CellPart::Tokens) => palette.content_muted,
        // The drift `CellPart` exists to end: a control in a cell inheriting the
        // cell's text colour. Both of these take the action intent instead.
        Some(CellPart::Actions | CellPart::Link) => palette.action,
        _ => palette.content,
    }
}

/// Draw a cell's contents with the tone its part takes.
///
/// The app calls this inside its own cell closure, wrapping whatever it draws.
/// A scoping function rather than a parameter on [`table`], for the reason
/// [`frame`](crate::frame) is one: the part is a property of the cell, the cell
/// does not exist until the closure runs, and immediate mode has no cascade to
/// carry the answer down on its own. This is the cascade, for one scope.
///
/// ```no_run
/// # use makeover_layout::CellPart;
/// # let palette: makeover_immediate::Palette = unimplemented!();
/// # let ui: &mut egui::Ui = unimplemented!();
/// makeover_immediate::table::cell(ui, Some(CellPart::Link), &palette, |ui| {
///     ui.label("opens the item");
/// });
/// ```
pub fn cell<R>(
    ui: &mut Ui,
    part: Option<CellPart>,
    palette: &Palette,
    add_contents: impl FnOnce(&mut Ui) -> R,
) -> R {
    let restore = ui.visuals().override_text_color;
    ui.visuals_mut().override_text_color = Some(part_color(part, palette));
    let out = add_contents(ui);
    ui.visuals_mut().override_text_color = restore;
    out
}

/// The heading, in capitals, with the caret if the table is ordered by this
/// column.
///
/// Capitals because the header strip's label is set that way at every host.
/// 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.
#[must_use]
pub fn heading(column: &Column<'_>, style: &TableStyle) -> String {
    let caret = match column.sorted {
        Some(Sort::Ascending) => style.ascending,
        Some(Sort::Descending) => style.descending,
        // Sortable and not sorted draws the idle mark, in the ascending
        // spelling because that is the direction a first press takes. What
        // separates it from the column in force is the tone, which is
        // [`press`]'s to pick.
        None if column.sortable => style.ascending,
        None => return column.name.to_uppercase(),
    };
    format!("{} {caret}", column.name.to_uppercase())
}

/// Whether the columns kept at `cutoff` fit in `width`.
///
/// Budgeted at each column's declared [`floor`](Column::floor) in `ch`, turned
/// into points by `ch`, the width of one figure in the face the table draws
/// in. Nothing can be measured before the app's closure has drawn a cell, and
/// nothing needs to be: the floor is the number the terminal counts in cells
/// and the webview hides a column under, so all three drop at one declared
/// width.
fn fits(columns: &[Column<'_>], ch: f32, edge: f32, cutoff: Priority, width: f32) -> bool {
    columns
        .iter()
        .filter(|c| c.kept_at(cutoff))
        .map(|c| f32::from(c.floor()) * ch + 2.0 * edge)
        .sum::<f32>()
        <= 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 squeezed 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<'_>], ch: f32, edge: f32, width: f32) -> Priority {
    for cutoff in CUTOFFS {
        if fits(columns, ch, edge, cutoff, width) {
            return cutoff;
        }
    }
    Priority::Essential
}

/// The track for one column.
fn track(column: &Column<'_>, sizing: &Sizing<'_>) -> Track {
    match column.width {
        // The one place immediate mode beats the terminal: egui_extras measures
        // this and remembers it between frames, where `makeover-tui` has to walk
        // the cells itself.
        Width::Content => Track::auto(),
        Width::Fixed => Track::exact(sizing.length_for(column.name)),
        // Includes a width added to the description since this renderer was
        // built. Taking the slack above a floor is the behaviour that makes no
        // claim, which is the same fallback the webview renderer's `auto` track
        // is chosen to be.
        _ => Track::remainder().at_least(sizing.length_for(column.name)),
    }
}

/// A described table, narrowed for the width available.
///
/// `draw` is called once per cell of each kept column, in column order, for each
/// of [`Body::rows`] rows. Taking a closure rather than a slice of contents is
/// what keeps the app's own data borrowed one cell at a time, which is
/// [`group`](crate::group)'s reasoning and immediate mode's habit.
///
/// `body` is borrowed immutably and `draw` is `FnMut`, which is the split a
/// caller has to plan for: a selection read by [`Body::selected`] cannot be the
/// same value `draw` mutates. Snapshot it before the call. That is not this
/// crate imposing anything. It is the borrow the app already takes when it
/// clones its row list to hand egui a closure.
///
/// Returns the sortable column whose heading was pressed this frame, if any. The
/// app owns the ordering, so this reports the press and changes nothing: what a
/// press *calls* is an address, and the description names none. That is
/// [`Column::sortable`]'s own documented split.
///
/// A heading is only pressable when its column says
/// [`sortable`](Column::sortable). A column sorted by a key the user cannot
/// change still draws its caret and does not answer.
pub fn table<'a>(
    ui: &mut Ui,
    columns: &'a [Column<'a>],
    body: &Body<'_>,
    sizing: &Sizing<'_>,
    palette: &Palette,
    style: &TableStyle,
    mut draw: impl FnMut(&mut Ui, &'a Column<'a>, usize),
) -> Option<&'a Column<'a>> {
    // One `ch` in the face the cells are drawn in, which is what a declared
    // floor counts.
    let ch = {
        let font = egui::TextStyle::Body.resolve(ui.style());
        ui.fonts_mut(|fonts| fonts.glyph_width(&font, '0'))
    };
    let cutoff = cutoff_for(columns, ch, style.edge_padding, ui.available_width());
    let kept: Vec<&'a Column<'a>> = columns.iter().filter(|c| c.kept_at(cutoff)).collect();

    // egui_extras panics on a table with no tracks, and a description whose
    // every column dropped is reachable: `kept_at` keeps the essential ones, and
    // a table described with none at all has nothing to keep.
    if kept.is_empty() {
        return None;
    }

    let code = kept.iter().any(|column| column.kind == ColumnKind::Code);
    let row_height = if code {
        style.code_row_height
    } else {
        style.row_height
    };
    // The whole width the table takes, which is the frame's: a cell only knows
    // its own track. The fills stop a stroke's width inside it, so no row
    // paints over the frame.
    let outer = ui.available_rect_before_wrap();
    let across = outer.x_range();
    let fills = egui::Rangef::new(across.min + 1.0, across.max - 1.0);
    let top = ui.cursor().top();
    // Reserved before the table draws, so the ground lands under it once the
    // table's height is known.
    let ground = ui.painter().add(egui::Shape::Noop);
    // How far down the header and the drawn rows reach, which is the frame's
    // bottom. Not the scroll area's rect, which is the room the table was
    // offered rather than the room it took.
    let reach = std::cell::Cell::new(top);
    let inner = outer.shrink2(egui::vec2(style.edge_padding, 0.0));
    // Written through a Cell rather than returned, because egui_extras hands the
    // header and the body their own closures and neither can return a value past
    // the other.
    let pressed = std::cell::Cell::new(None::<&'a Column<'a>>);

    let viewport = ui
        .scope_builder(egui::UiBuilder::new().max_rect(inner), |ui| {
            let mut builder = TableBuilder::new(ui)
                .striped(false)
                .resizable(style.resizable)
                // Not a knob, because there is no second honest answer: a cell's
                // contents sit on the row's centre line. CSS says `vertical-align:
                // middle` and a terminal row is one line tall, so a field offering the
                // choice would be offering one only this renderer could take. egui's own
                // default is top-aligned, which is why it has to be said at all.
                .cell_layout(egui::Layout::left_to_right(egui::Align::Center));
            for column in &kept {
                builder = builder.column(track(column, sizing));
            }
            if let Some(row) = body.scroll_to {
                builder = builder.scroll_to_row(row, None);
            }

            builder
                .header(style.header_height, |mut header| {
                    for (at, column) in kept.iter().enumerate() {
                        header.col(|ui| {
                            if at == 0 {
                                strip(ui, fills, &reach, palette);
                            }
                            placed(ui, column, |ui| {
                                if press(ui, column, palette, style) {
                                    pressed.set(Some(column));
                                }
                            });
                        });
                    }
                })
                .body(|table_body| {
                    table_body.rows(row_height, body.rows, |mut row| {
                        let index = row.index();
                        let selected = body.selected.is_some_and(|selected| selected(index));
                        for (at, column) in kept.iter().enumerate() {
                            row.col(|ui| {
                                // In the first cell and across the whole row, before
                                // any cell's contents: a selection marks the row, and
                                // a fill per cell would leave the gaps unpainted.
                                if at == 0 {
                                    let row = Row {
                                        index,
                                        selected,
                                        code,
                                    };
                                    ground_row(ui, fills, row, &reach, palette);
                                }
                                placed(ui, column, |ui| draw(ui, column, index));
                            });
                        }
                    });
                })
                .inner_rect
        })
        .inner;

    let bottom = reach.get().min(viewport.bottom());
    let frame = egui::Rect::from_x_y_ranges(across, top..=bottom);
    ui.painter().set(
        ground,
        egui::epaint::RectShape::filled(frame, 0, palette.raised),
    );
    ui.painter().rect_stroke(
        frame,
        0,
        egui::Stroke::new(1.0, palette.row_rule),
        egui::StrokeKind::Inside,
    );

    pressed.get()
}

/// What decides one body row's fill.
#[derive(Clone, Copy)]
struct Row {
    index: usize,
    selected: bool,
    code: bool,
}

/// The rect a row's fill covers: the whole table's width, and the cell's
/// height with the half of the spacing either side that egui_extras leaves
/// between rows.
fn row_rect(ui: &Ui, across: egui::Rangef) -> egui::Rect {
    let half = 0.5 * ui.spacing().item_spacing.y;
    let cell = ui.max_rect();
    egui::Rect::from_x_y_ranges(across, (cell.top() - half)..=(cell.bottom() + half))
}

/// The header strip: sunken, with the `bevel-dark` edge under it.
fn strip(ui: &Ui, across: egui::Rangef, reach: &std::cell::Cell<f32>, palette: &Palette) {
    let rect = row_rect(ui, across);
    reach.set(reach.get().max(rect.bottom()));
    ui.painter().rect_filled(rect, 0, palette.sunken);
    ui.painter().hline(
        across,
        rect.bottom(),
        egui::Stroke::new(1.0, palette.bevel_dark),
    );
}

/// One body row's fill and the hairline above it.
///
/// Selected, then hovered, then the stripe on every second row, and the first
/// of those that holds is the fill. A table holding code takes the selection
/// and the hover and neither the stripe nor the hairline, which break the
/// reading of source one line to a row.
fn ground_row(
    ui: &Ui,
    across: egui::Rangef,
    Row {
        index,
        selected,
        code,
    }: Row,
    reach: &std::cell::Cell<f32>,
    palette: &Palette,
) {
    let rect = row_rect(ui, across);
    reach.set(reach.get().max(rect.bottom()));
    let fill = if selected {
        Some(palette.row_selected)
    } else if ui.rect_contains_pointer(rect) {
        Some(palette.row_hover)
    } else if !code && index % 2 == 1 {
        Some(palette.row_stripe)
    } else {
        None
    };
    if let Some(fill) = fill {
        ui.painter().rect_filled(rect, 0, fill);
    }
    if !code && index > 0 {
        ui.painter()
            .hline(across, rect.top(), egui::Stroke::new(1.0, palette.row_rule));
    }
}

/// A cell laid out the way its column's kind says, wiki `table-model`.
///
/// Alignment is the kind fact this renderer acts on. A number or actions
/// column runs right to left, on the row's centre line like every cell, and
/// its heading does the same so the label sits over its figures. The face and
/// the figures a kind names are the caller's, who draws the cell's contents.
fn placed(ui: &mut Ui, column: &Column<'_>, add: impl FnOnce(&mut Ui)) {
    if column.kind.aligns_end() {
        ui.with_layout(egui::Layout::right_to_left(egui::Align::Center), add);
    } else {
        add(ui);
    }
}

/// What a heading's caret is drawn in.
///
/// Three states (wiki `three-tone-convention`), carried by the caret as the
/// webview carries them: the column in force takes content, a column offering
/// to reorder takes secondary, and a column that is not a control draws no
/// caret. The label is the strip's own secondary ink in every state.
///
/// The offering state may not take `content_muted`, which is what
/// [`State::Disabled`](makeover_layout::State::Disabled) resolves to: a heading
/// the user can press would be claiming it will not answer.
fn caret_color(column: &Column<'_>, palette: &Palette) -> egui::Color32 {
    match column.sorted {
        Some(_) => palette.content,
        None => palette.content_secondary,
    }
}

/// One heading, and whether it was pressed.
fn press(ui: &mut Ui, column: &Column<'_>, palette: &Palette, style: &TableStyle) -> bool {
    // The strip's type: small, strong and tracked, as the webview sets it, with
    // the caret in its own run so it can take its own tone.
    let size = egui::TextStyle::Small.resolve(ui.style()).size;
    let heading = heading(column, style);
    let label_len = column.name.to_uppercase().len();
    let mut job = egui::text::LayoutJob::default();
    RichText::new(&heading[..label_len])
        .color(palette.content_secondary)
        .small()
        .strong()
        .extra_letter_spacing(0.06 * size)
        .append_to(
            &mut job,
            ui.style(),
            egui::FontSelection::Default,
            egui::Align::Center,
        );
    if heading.len() > label_len {
        RichText::new(&heading[label_len..])
            .color(caret_color(column, palette))
            .small()
            .append_to(
                &mut job,
                ui.style(),
                egui::FontSelection::Default,
                egui::Align::Center,
            );
    }
    let text = job;
    if !column.sortable {
        // Not sensed. A heading a user cannot press must not look like one they
        // can, which is the affordance `Column::sortable` exists to carry, and
        // the missing caret is half of saying so.
        ui.label(text);
        return false;
    }
    let response: Response = ui
        .add(egui::Label::new(text).sense(Sense::click()))
        .on_hover_cursor(egui::CursorIcon::PointingHand);
    // Announced as the control it is, rather than as the `Label` it is drawn
    // with. egui maps a `Label` to `Role::Label` whatever it senses, so until
    // 2026-08-22 a screen reader was told this was static text and a user who
    // could not see the pointer change had no way to know the table sorts.
    // The same argument the comment above makes about affordance, made about
    // the half of the interface that is not pixels.
    //
    // The name is the column's own, not `heading`'s: the caret is a rendering of
    // `Column::sorted`, and reading a triangle aloud after every heading is
    // noise. Which column is in force is a fact a client should get from the
    // sort state, and egui has nowhere to put that yet -- worth revisiting if it
    // grows a sort field on `WidgetInfo`.
    response.widget_info(|| {
        egui::WidgetInfo::labeled(egui::WidgetType::Button, ui.is_enabled(), column.name)
    });
    response.clicked()
}

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

    /// What the accessibility tree says a heading row drew.
    ///
    /// egui builds it from the `WidgetInfo` each widget reports, so this is
    /// what a screen reader would be handed rather than a second opinion.
    fn announced(draw: impl FnMut(&mut Ui)) -> Vec<(egui::accesskit::Role, String)> {
        let ctx = egui::Context::default();
        ctx.enable_accesskit();
        let mut draw = draw;
        let input = || egui::RawInput {
            screen_rect: Some(egui::Rect::from_min_size(
                egui::Pos2::ZERO,
                egui::vec2(800.0, 600.0),
            )),
            ..Default::default()
        };
        let _ = ctx.run_ui(input(), &mut draw);
        let out = ctx.run_ui(input(), &mut draw);
        out.platform_output
            .accesskit_update
            .expect("accesskit is on")
            .nodes
            .iter()
            .map(|(_, node)| {
                (
                    node.role(),
                    node.label()
                        .or_else(|| node.value())
                        .unwrap_or_default()
                        .to_owned(),
                )
            })
            .collect()
    }

    #[test]
    fn a_sortable_heading_is_announced_as_something_you_press() {
        let column = Column {
            name: "Name",
            width: Width::Fill,
            priority: Priority::Essential,
            kind: ColumnKind::Text,
            min: None,
            sortable: true,
            sorted: Some(Sort::Ascending),
        };
        let p = palette();
        let drawn = announced(|ui| {
            press(ui, &column, &p, &TableStyle::default());
        });

        // The name is the column's, with no caret in it: the glyph renders
        // `Column::sorted` and is not part of what the control is called.
        assert!(
            drawn
                .iter()
                .any(|(role, name)| *role == egui::accesskit::Role::Button && name == "Name"),
            "{drawn:?}"
        );
    }

    #[test]
    fn a_heading_that_is_not_a_control_is_not_announced_as_one() {
        let column = Column {
            name: "Tags",
            width: Width::Fixed,
            priority: Priority::Optional,
            kind: ColumnKind::Text,
            min: None,
            sortable: false,
            sorted: None,
        };
        let p = palette();
        let drawn = announced(|ui| {
            press(ui, &column, &p, &TableStyle::default());
        });

        assert!(
            !drawn
                .iter()
                .any(|(role, _)| *role == egui::accesskit::Role::Button),
            "a heading with no sort answers nothing and must not claim to: {drawn:?}"
        );
    }
    use egui::Color32;

    fn palette() -> Palette {
        Palette {
            page: Color32::from_rgb(1, 1, 1),
            raised: Color32::from_rgb(2, 2, 2),
            overlay: Color32::from_rgb(3, 3, 3),
            well: Color32::from_rgb(4, 4, 4),
            sunken: Color32::from_rgb(5, 5, 5),
            bevel_light: Color32::WHITE,
            bevel_dark: Color32::BLACK,
            elevation: Color32::from_black_alpha(46),
            content: Color32::from_rgb(6, 6, 6),
            content_secondary: Color32::from_rgb(56, 56, 56),
            content_muted: Color32::from_rgb(7, 7, 7),
            action: Color32::from_rgb(8, 8, 8),
            content_on_action: Color32::from_rgb(250, 250, 250),
            danger: Color32::from_rgb(9, 9, 9),
            success: Color32::from_rgb(10, 10, 10),
            warning: Color32::from_rgb(11, 11, 11),
            info: Color32::from_rgb(12, 12, 12),
            border: Color32::from_rgb(200, 200, 200),
            info_surface: Color32::from_rgb(201, 201, 201),
            success_surface: Color32::from_rgb(202, 202, 202),
            warning_surface: Color32::from_rgb(203, 203, 203),
            danger_surface: Color32::from_rgb(204, 204, 204),
            row_stripe: Color32::from_rgb(205, 205, 205),
            row_hover: Color32::from_rgb(206, 206, 206),
            row_rule: Color32::from_rgb(207, 207, 207),
            row_selected: Color32::from_rgb(208, 208, 208),
        }
    }

    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", 120.0), ("size", 60.0), ("note", 80.0)],
            fallback: 40.0,
        }
    }

    #[test]
    fn narrowing_drops_the_optional_column_first_and_the_essential_one_never() {
        // Floors of 16ch (the name fills), 8 and 8, at 10 points a ch, and 12
        // points of edge either side of each: 184, 104 and 104.
        let cols = columns();
        assert_eq!(cutoff_for(&cols, 10.0, 12.0, 392.0), Priority::Optional);
        assert_eq!(cutoff_for(&cols, 10.0, 12.0, 391.0), Priority::Secondary);
        assert_eq!(cutoff_for(&cols, 10.0, 12.0, 288.0), Priority::Secondary);
        assert_eq!(cutoff_for(&cols, 10.0, 12.0, 287.0), Priority::Essential);
        // Narrower than the essential column, which stays anyway.
        assert_eq!(cutoff_for(&cols, 10.0, 12.0, 10.0), Priority::Essential);
    }

    #[test]
    fn the_same_floors_drop_at_the_same_ch_count_as_a_terminal() {
        // A terminal counts one cell a ch. At one point a ch and no edge, the
        // cut falls on the floors alone, which is the number both other hosts
        // read, so a description narrows at one declared width everywhere.
        let cols = columns();
        assert_eq!(cutoff_for(&cols, 1.0, 0.0, 32.0), Priority::Optional);
        assert_eq!(cutoff_for(&cols, 1.0, 0.0, 31.0), Priority::Secondary);
        assert_eq!(cutoff_for(&cols, 1.0, 0.0, 24.0), Priority::Secondary);
        assert_eq!(cutoff_for(&cols, 1.0, 0.0, 23.0), Priority::Essential);
    }

    #[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
        // moves the cut onto a different column with nothing edited.
        //
        // Asserted at a fixed cutoff, because that is where the two ways of
        // addressing a column disagree. A narrower budget SHOULD drop more; what
        // must not change is which ones, 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));
        }
        assert_eq!(dropped(&before, Priority::Secondary), vec!["note"]);
    }

    #[test]
    fn the_two_renderers_narrow_a_description_the_same_way() {
        // The cutoff ladder is duplicated in `makeover-tui` because neither
        // crate depends on the other, and duplication is what drifts. This is
        // the assertion that would catch it: the ladder is the description's
        // order, weakest first, and a tier added upstream belongs in both.
        assert_eq!(CUTOFFS.len(), 3);
        assert!(CUTOFFS.windows(2).all(|pair| pair[0] < pair[1]));
        assert_eq!(CUTOFFS[0], Priority::Optional);
        assert_eq!(CUTOFFS[2], Priority::Essential);
    }

    #[test]
    fn a_content_column_is_measured_by_egui_and_budgeted_by_its_floor() {
        // The split the module header names. The track defers to egui_extras,
        // which can measure; the narrowing cannot wait for that and uses the
        // declared floor. Both readings of the same column, and both honest.
        let cols = columns();
        let note = &cols[2];
        assert!(matches!(note.width, Width::Content));
        assert_eq!(note.floor(), 8, "undeclared, so the kind's floor");
        // Floors of 16, 8 and 8ch at 10 points, each with 12 points of edge
        // either side: 392 fits and 391 does not, whatever the cells turn out to
        // hold.
        assert!(fits(&cols, 10.0, 12.0, Priority::Optional, 392.0));
        assert!(!fits(&cols, 10.0, 12.0, Priority::Optional, 391.0));
    }

    #[test]
    fn a_column_with_no_length_of_its_own_takes_the_fallback() {
        let column = Column {
            name: "unlisted",
            width: Width::Fixed,
            priority: Priority::Essential,
            kind: ColumnKind::Text,
            min: None,
            sortable: false,
            sorted: None,
        };
        // The fallback sizes a track and nothing else: which columns exist is
        // the floor's to decide.
        assert!((sizing().length_for(column.name) - 40.0).abs() < f32::EPSILON);
    }

    #[test]
    fn the_parts_a_cell_can_be_are_coloured_apart() {
        // The drift `CellPart` exists to end: one colour for a whole cell paints
        // a control as though it were text.
        let p = palette();
        assert_eq!(part_color(Some(CellPart::Value), &p), p.content);
        assert_eq!(part_color(Some(CellPart::Tokens), &p), p.content_muted);
        assert_eq!(part_color(Some(CellPart::Actions), &p), p.action);
        assert_eq!(part_color(Some(CellPart::Link), &p), p.action);
        assert_ne!(part_color(Some(CellPart::Link), &p), p.content);
        // A cell mixing parts says nothing, and takes the text colour.
        assert_eq!(part_color(None, &p), p.content);
    }

    #[test]
    fn a_heading_carries_a_caret_when_it_is_ordered_by_or_offers_to_be() {
        let style = TableStyle::default();
        let cols = columns();
        assert_eq!(heading(&cols[0], &style), "NAME \u{25B2}");
        // Sortable and idle. It draws the mark a first press would give, which
        // is what stops the press from widening the column and shifting the
        // ones after it.
        assert_eq!(heading(&cols[1], &style), "SIZE \u{25B2}");
        // Not a control. Nothing to mark.
        assert_eq!(heading(&cols[2], &style), "NOTE");
    }

    #[test]
    fn the_three_states_of_a_heading_are_carried_by_its_caret() {
        // wiki `three-tone-convention`, as the webview draws it: the caret in
        // force takes content, the idle caret secondary, and a heading that is
        // not a control has no caret. The offering state may not take
        // content_muted, which is what `State::Disabled` resolves to.
        let p = palette();
        let cols = columns();
        let style = TableStyle::default();
        assert_eq!(caret_color(&cols[0], &p), p.content);
        assert_eq!(caret_color(&cols[1], &p), p.content_secondary);
        assert_ne!(caret_color(&cols[1], &p), p.content_muted);
        assert!(
            !heading(&cols[2], &style).contains(' '),
            "an inert heading has no caret"
        );
    }

    #[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.
        let column = Column {
            name: "rank",
            width: Width::Content,
            priority: Priority::Essential,
            kind: ColumnKind::Text,
            min: None,
            sortable: false,
            sorted: Some(Sort::Descending),
        };
        assert_eq!(heading(&column, &TableStyle::default()), "RANK \u{25BC}");
    }

    #[test]
    fn the_carets_match_the_terminal_renderers() {
        // Two crates, one glyph pair, and no dependency between them to enforce
        // it. A description sorted ascending must not point up in a window and
        // down in a terminal.
        // Composition rather than agreement since makeover-layout 0.27.5: both
        // read `Sort::glyph`, so a fourth spelling cannot appear in one crate.
        let style = TableStyle::default();
        assert_eq!(style.ascending, Sort::Ascending.glyph());
        assert_eq!(style.descending, Sort::Descending.glyph());
        // Bare. The gap is `heading`'s, so a consumer swapping the glyph for an
        // ASCII one does not have to remember to bring a space with it.
        assert_eq!(style.ascending.trim(), style.ascending);
    }

    #[test]
    fn resizing_is_off_because_the_description_has_no_word_for_it() {
        // egui_extras offers it and the other two renderers cannot say it. A
        // default that turned it on would be this renderer adding a claim.
        assert!(!TableStyle::default().resizable);
    }

    #[test]
    fn a_record_row_is_the_models_45_and_a_code_row_is_one_line() {
        let style = TableStyle::default();
        assert!((style.row_height - 45.0).abs() < f32::EPSILON);
        assert!(style.code_row_height < style.row_height);
    }

    #[test]
    fn a_body_claims_nothing_until_it_is_asked_to() {
        // The default is a table of no rows, no selection and no scroll
        // request. All three absences are the honest reading of an app that has
        // not said otherwise, which is why they are `Option` and not a
        // predicate that always answers false.
        let body = Body::default();
        assert_eq!(body.rows, 0);
        assert!(body.selected.is_none());
        assert!(body.scroll_to.is_none());
    }

    #[test]
    fn a_selection_is_asked_per_row_and_not_collected() {
        // A predicate, so an app whose selection is a range or a single index
        // does not build a set to be asked. Exercised the way `table` asks it:
        // once per row index, in order.
        let selected = |index: usize| index.is_multiple_of(2);
        let body = Body {
            rows: 4,
            selected: Some(&selected),
            scroll_to: None,
        };
        let f = body.selected.expect("a predicate was supplied");
        assert_eq!(
            (0..body.rows).map(f).collect::<Vec<_>>(),
            vec![true, false, true, false]
        );
    }

    #[test]
    fn narrowing_reads_the_declared_widths_and_not_a_dragged_track() {
        // `resizable` lets the user move a divider, and `cutoff_for` must not
        // hear about it: a drag that could drop a column would make the
        // narrowing a thing the user does by accident rather than a property of
        // the description. That `cutoff_for` takes the columns and two numbers,
        // and no `TableStyle` or track state, is the structural half of the
        // guarantee; this is the behavioural half, and it is what would fail if a
        // measured width were ever threaded in beside the declared floor.
        let cols = columns();
        assert_eq!(cutoff_for(&cols, 10.0, 12.0, 392.0), Priority::Optional);
        assert_eq!(cutoff_for(&cols, 10.0, 12.0, 288.0), Priority::Secondary);
    }
}