quadraui 0.6.1

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

use ratatui::buffer::Buffer;
use ratatui::layout::Rect;
use ratatui::style::Modifier;

use super::{ratatui_color, set_cell};
use crate::primitives::data_table::{
    ColumnAlign, ColumnMeasure, DataTable, DataTableGlyphs, DataTableLayout, SortDirection,
};
use crate::theme::Theme;

/// Resolve the layout `draw_data_table` paints `table` at, without
/// touching a buffer.
///
/// This is the **single** definition of TUI DataTable geometry: both
/// [`draw_data_table`] and `Backend::data_table_layout` go through it,
/// so the layout a cache-free, layout-on-demand hit-test runs against is
/// bit-for-bit the layout that was painted.
pub fn data_table_layout(area: Rect, table: &DataTable) -> DataTableLayout {
    let mut layout = table.layout(
        area.width as f32,
        area.height as f32,
        1.0,
        1.0,
        1.0,
        |col| ColumnMeasure::new(col.title.chars().count() as f32),
    );

    // TUI is cell-granular: every column paints at a *rounded* offset,
    // not the raw fractional `h_scroll`. `hit_test` / `column_hit` do no
    // rounding of their own — they trust `DataTableLayout::h_scroll` to
    // already equal what was painted — so this must be rounded here, once,
    // before the layout is handed back to callers for hit-testing.
    layout.h_scroll = table.h_scroll.round();
    layout
}

/// Draw a `DataTable` into `area`. `hovered_idx` carries per-frame
/// hover state so the rasteriser can tint the hovered row. Returns
/// the layout used for painting so callers can hit-test at the same
/// coordinates.
pub fn draw_data_table(
    buf: &mut Buffer,
    area: Rect,
    table: &DataTable,
    theme: &Theme,
    hovered_idx: Option<usize>,
) -> DataTableLayout {
    draw_data_table_with_glyphs(buf, area, table, theme, hovered_idx, None, false)
}

/// [`draw_data_table`] with an optional app-supplied [`DataTableGlyphs`]
/// override for the column-header sort-direction indicators.
/// `nerd_fonts_enabled` selects which half of each override [`Icon`][crate::Icon] —
/// `glyph` or `fallback` — is resolved (see
/// [`crate::Backend::nerd_fonts_enabled`]); it is ignored when `glyphs`
/// does not set the indicator being drawn.
///
/// `glyphs: None` reproduces [`draw_data_table`] cell for cell — the
/// default `â–²`/`â–¼` indicators are unchanged. Passing `Some` only
/// overrides the glyph it sets; a field left `None` keeps the default for
/// that direction. Unlike the GUI backends' codicon defaults
/// (`crate::codicon::SORT_ASCENDING`/`SORT_DESCENDING`), TUI's own default
/// is the plain Unicode arrow — this function preserves that default
/// rather than adopting the codicon one.
pub fn draw_data_table_with_glyphs(
    buf: &mut Buffer,
    area: Rect,
    table: &DataTable,
    theme: &Theme,
    hovered_idx: Option<usize>,
    glyphs: Option<&DataTableGlyphs>,
    nerd_fonts_enabled: bool,
) -> DataTableLayout {
    let layout = data_table_layout(area, table);

    if area.width == 0 || area.height == 0 {
        return layout;
    }

    let header_bg = ratatui_color(theme.tab_bar_bg);
    let header_fg = ratatui_color(theme.foreground);
    let body_bg = ratatui_color(theme.background);
    let body_fg = ratatui_color(theme.foreground);
    let sel_bg = ratatui_color(theme.selection_bg);
    let muted_fg = ratatui_color(theme.muted_fg);

    // ── Header row ────────────────────────────────────────────────────
    let header_y = area.y;
    for x in 0..area.width {
        set_cell(buf, area.x + x, header_y, ' ', header_fg, header_bg);
    }

    let sep_fg = ratatui_color(theme.separator);
    // Same rounded value now carried on `layout.h_scroll` — kept as a
    // local `i16` here since every paint-position computation below
    // works in signed cell-offset arithmetic.
    let h_off = layout.h_scroll as i16;

    for (col_idx, rc) in layout.columns.iter().enumerate() {
        if col_idx >= table.columns.len() {
            break;
        }
        let col = &table.columns[col_idx];
        let col_x_raw = area.x as i32 + rc.x.round() as i32 - h_off as i32;
        let col_x_end = col_x_raw + rc.width.round() as i32;
        if col_x_end <= area.x as i32 || col_x_raw >= (area.x + area.width) as i32 {
            continue;
        }
        let col_w = rc.width.round() as u16;
        if col_w == 0 {
            continue;
        }

        // Column separator on the right edge (skip last column).
        if col_idx + 1 < table.columns.len() {
            let sep_cx = col_x_raw + col_w as i32 - 1;
            if sep_cx >= area.x as i32 && sep_cx < (area.x + area.width) as i32 {
                set_cell(buf, sep_cx as u16, header_y, '│', sep_fg, header_bg);
            }
        }

        let sort_glyph: Option<&str> = match &table.sort {
            Some((si, dir)) if *si == col_idx => Some(match dir {
                SortDirection::Ascending => glyphs
                    .and_then(DataTableGlyphs::sort_ascending_glyph)
                    .map(|icon| icon.resolve(nerd_fonts_enabled))
                    .unwrap_or("â–²"),
                SortDirection::Descending => glyphs
                    .and_then(DataTableGlyphs::sort_descending_glyph)
                    .map(|icon| icon.resolve(nerd_fonts_enabled))
                    .unwrap_or("â–¼"),
            }),
            _ => None,
        };
        let title = match sort_glyph {
            Some(glyph) => format!("{} {glyph}", col.title),
            None => col.title.clone(),
        };
        let text_len = title.chars().count() as i32;
        let usable_w = if col_idx + 1 < table.columns.len() {
            col_w.saturating_sub(1) as i32
        } else {
            col_w as i32
        };
        let start = align_offset(col.align, text_len as u16, usable_w as u16) as i32;

        for (i, ch) in title.chars().enumerate() {
            let cx = col_x_raw + start + i as i32;
            if cx >= col_x_raw + usable_w || cx >= (area.x + area.width) as i32 {
                break;
            }
            if cx >= area.x as i32 {
                set_cell(buf, cx as u16, header_y, ch, header_fg, header_bg);
                if let Some(cell) =
                    buf.cell_mut(ratatui::prelude::Position::new(cx as u16, header_y))
                {
                    cell.set_style(ratatui::style::Style::default().add_modifier(Modifier::BOLD));
                }
            }
        }
    }

    // ── Body rows ─────────────────────────────────────────────────────
    let body_y = area.y + 1;
    let visible = layout
        .visible_rows
        .min(table.rows.len().saturating_sub(table.scroll_offset));

    for row_idx in 0..visible {
        let abs_idx = table.scroll_offset + row_idx;
        let row = &table.rows[abs_idx];
        let y = body_y + row_idx as u16;
        let is_selected = table.selected_idx == Some(abs_idx);
        let is_hovered = hovered_idx == Some(abs_idx) && !is_selected;

        let (row_fg, row_bg) = if is_selected {
            (body_fg, sel_bg)
        } else if is_hovered {
            (body_fg, ratatui_color(theme.tab_bar_bg))
        } else {
            (body_fg, body_bg)
        };

        // Fill row background
        for x in 0..area.width {
            set_cell(buf, area.x + x, y, ' ', row_fg, row_bg);
        }

        for (col_idx, rc) in layout.columns.iter().enumerate() {
            let col_x_raw = area.x as i32 + rc.x.round() as i32 - h_off as i32;
            let col_x_end = col_x_raw + rc.width.round() as i32;
            if col_x_end <= area.x as i32 || col_x_raw >= (area.x + area.width) as i32 {
                continue;
            }
            let col_w = rc.width.round() as u16;
            if col_w == 0 {
                continue;
            }

            // Column separator on the right edge (skip last column) —
            // drawn regardless of whether this cell has text, mirroring
            // the header separator.
            if col_idx + 1 < table.columns.len() {
                let sep_cx = col_x_raw + col_w as i32 - 1;
                if sep_cx >= area.x as i32 && sep_cx < (area.x + area.width) as i32 {
                    set_cell(buf, sep_cx as u16, y, '│', sep_fg, row_bg);
                }
            }

            let styled = match row.cells.get(col_idx) {
                Some(c) if !c.spans.is_empty() => c,
                _ => continue,
            };
            let full_text: String = styled.spans.iter().map(|s| s.text.as_str()).collect();
            if full_text.is_empty() {
                continue;
            }

            let align = table
                .columns
                .get(col_idx)
                .map(|c| c.align)
                .unwrap_or(ColumnAlign::Left);

            // Reserve one cell for the separator (except on the last
            // column) — the same `usable_w` term the header already
            // uses — so an over-long body cell is clipped at its own
            // column boundary instead of painting across its neighbours.
            let usable_w: u16 = if col_idx + 1 < table.columns.len() {
                col_w.saturating_sub(1)
            } else {
                col_w
            };

            let text_len = full_text.chars().count() as u16;
            let (visible_len, needs_ellipsis) = if text_len <= usable_w {
                (text_len, false)
            } else if usable_w == 0 {
                (0, false)
            } else {
                (usable_w - 1, true)
            };
            let displayed_len = visible_len + u16::from(needs_ellipsis);
            let start = align_offset(align, displayed_len, usable_w) as i32;

            let is_muted = row.decoration == crate::types::Decoration::Muted;
            let mut char_idx = 0u16;
            'cell: for span in &styled.spans {
                let span_fg = if is_muted {
                    muted_fg
                } else {
                    span.fg.map(ratatui_color).unwrap_or(row_fg)
                };
                for ch in span.text.chars() {
                    if char_idx == visible_len {
                        if needs_ellipsis {
                            let cx = col_x_raw + start + char_idx as i32;
                            if cx >= area.x as i32 && cx < (area.x + area.width) as i32 {
                                set_cell(buf, cx as u16, y, '…', span_fg, row_bg);
                            }
                        }
                        break 'cell;
                    }
                    let cx = col_x_raw + start + char_idx as i32;
                    if cx >= (area.x + area.width) as i32 {
                        break 'cell;
                    }
                    if cx >= area.x as i32 {
                        set_cell(buf, cx as u16, y, ch, span_fg, row_bg);
                    }
                    char_idx += 1;
                }
            }
        }
    }

    // ── Scrollbar ──────────────────────────────────────────────────────
    let footer_h = layout.footer_height.round() as u16;
    if table.show_scrollbar
        && table.rows.len() > layout.visible_rows
        && layout.scrollbar_width > 0.0
    {
        let sb_x = area.x + area.width - layout.scrollbar_width.round() as u16;
        let sb_track = crate::event::Rect::new(
            sb_x as f32,
            (area.y + 1) as f32,
            1.0,
            (area.height.saturating_sub(1).saturating_sub(footer_h)) as f32,
        );
        let sb = crate::primitives::scrollbar::Scrollbar::vertical(
            table.id,
            sb_track,
            table.scroll_offset as f32,
            table.rows.len() as f32,
            layout.visible_rows as f32,
            1.0,
        );
        super::draw_scrollbar(buf, &sb, theme, theme.background);
    }

    // ── Horizontal scrollbar ─────────────────────────────────────────
    if layout.h_scrollbar_height > 0.0 && layout.content_width > 0.0 {
        let hsb_y = area.y + area.height - footer_h - layout.h_scrollbar_height.round() as u16;
        let track_w = (area.width as f32 - layout.scrollbar_width).max(1.0);
        let hsb_track = crate::event::Rect::new(area.x as f32, hsb_y as f32, track_w, 1.0);
        let visible_w = (area.width as f32 - layout.scrollbar_width).max(1.0);
        let hsb = crate::primitives::scrollbar::Scrollbar::horizontal(
            table.id,
            hsb_track,
            table.h_scroll,
            layout.content_width,
            visible_w,
            1.0,
        );
        super::draw_scrollbar(buf, &hsb, theme, theme.background);
    }

    // ── Footer (pinned summary row) ────────────────────────────────────
    if let Some(footer) = &table.footer {
        if footer_h > 0 {
            // Content always sits on the viewport's bottom-most row;
            // the divider gets the row directly above it. Both rows
            // are reserved via `footer_height == row_height * 2.0`
            // (see `DataTable::layout`), so neither is ever painted
            // over by a body row.
            let footer_y = area.y + area.height - 1;
            let footer_bg = ratatui_color(theme.tab_bar_bg);
            let footer_fg = ratatui_color(theme.foreground);

            // Divider rule directly above the footer row.
            if footer_y > area.y {
                for x in 0..area.width {
                    set_cell(buf, area.x + x, footer_y - 1, '─', sep_fg, header_bg);
                }
            }

            for x in 0..area.width {
                set_cell(buf, area.x + x, footer_y, ' ', footer_fg, footer_bg);
            }

            for (col_idx, rc) in layout.columns.iter().enumerate() {
                let styled = match footer.cells.get(col_idx) {
                    Some(c) if !c.spans.is_empty() => c,
                    _ => continue,
                };
                let full_text: String = styled.spans.iter().map(|s| s.text.as_str()).collect();
                let col_x_raw = area.x as i32 + rc.x.round() as i32 - h_off as i32;
                let col_x_end = col_x_raw + rc.width.round() as i32;
                if col_x_end <= area.x as i32 || col_x_raw >= (area.x + area.width) as i32 {
                    continue;
                }
                let col_w = rc.width.round() as u16;
                if col_w == 0 || full_text.is_empty() {
                    continue;
                }

                let align = table
                    .columns
                    .get(col_idx)
                    .map(|c| c.align)
                    .unwrap_or(ColumnAlign::Left);
                let text_len = full_text.chars().count() as u16;
                let start = align_offset(align, text_len, col_w) as i32;

                let mut char_offset = 0i32;
                for span in &styled.spans {
                    let span_fg = span.fg.map(ratatui_color).unwrap_or(footer_fg);
                    for ch in span.text.chars() {
                        let cx = col_x_raw + start + char_offset;
                        if cx >= (area.x + area.width) as i32 {
                            break;
                        }
                        if cx >= area.x as i32 {
                            set_cell(buf, cx as u16, footer_y, ch, span_fg, footer_bg);
                            if let Some(cell) =
                                buf.cell_mut(ratatui::prelude::Position::new(cx as u16, footer_y))
                            {
                                cell.set_style(
                                    ratatui::style::Style::default().add_modifier(Modifier::BOLD),
                                );
                            }
                        }
                        char_offset += 1;
                    }
                }
            }
        }
    }

    layout
}

fn align_offset(align: ColumnAlign, text_len: u16, col_w: u16) -> u16 {
    match align {
        ColumnAlign::Left => 0,
        ColumnAlign::Center => col_w.saturating_sub(text_len) / 2,
        ColumnAlign::Right => col_w.saturating_sub(text_len),
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::primitives::data_table::{Column, ColumnWidth, DataRow, DataTable, DataTableHit};
    use crate::types::{Decoration, StyledText, WidgetId};

    /// Char-cell index of `needle`'s first occurrence in `line` — unlike
    /// `str::find`, which returns a *byte* offset and desyncs from the
    /// screen column as soon as a row contains a multi-byte glyph.
    fn find_char_pos(line: &str, needle: &str) -> Option<usize> {
        let chars: Vec<char> = line.chars().collect();
        let needle: Vec<char> = needle.chars().collect();
        if needle.is_empty() || chars.len() < needle.len() {
            return None;
        }
        chars
            .windows(needle.len())
            .position(|w| w == needle.as_slice())
    }

    fn make_table() -> DataTable {
        DataTable {
            id: WidgetId::new("test"),
            columns: vec![
                Column {
                    title: "Name".into(),
                    width: ColumnWidth::Flex(2.0),
                    align: ColumnAlign::Left,
                },
                Column {
                    title: "Status".into(),
                    width: ColumnWidth::Flex(1.0),
                    align: ColumnAlign::Left,
                },
                Column {
                    title: "Age".into(),
                    width: ColumnWidth::Fixed(5.0),
                    align: ColumnAlign::Right,
                },
            ],
            rows: vec![
                DataRow {
                    cells: vec![
                        StyledText::plain("pod-abc"),
                        StyledText::plain("Running"),
                        StyledText::plain("3d"),
                    ],
                    decoration: Decoration::Normal,
                },
                DataRow {
                    cells: vec![
                        StyledText::plain("pod-xyz"),
                        StyledText::plain("Pending"),
                        StyledText::plain("1h"),
                    ],
                    decoration: Decoration::Normal,
                },
            ],
            selected_idx: Some(0),
            scroll_offset: 0,
            sort: Some((0, SortDirection::Ascending)),
            has_focus: true,
            show_scrollbar: false,
            min_total_width: None,
            h_scroll: 0.0,
            column_overrides: Vec::new(),
            footer: None,
        }
    }

    #[test]
    fn header_paints_column_titles() {
        let table = make_table();
        let area = Rect::new(0, 0, 40, 10);
        let mut buf = Buffer::empty(area);
        draw_data_table(&mut buf, area, &table, &Theme::default(), None);

        // Header row at y=0 should contain "Name" somewhere
        let header: String = (0..40)
            .map(|x| buf[(x, 0)].symbol().chars().next().unwrap_or(' '))
            .collect();
        assert!(
            header.contains("Name"),
            "header should contain 'Name', got: {header}"
        );
        assert!(
            header.contains("Status"),
            "header should contain 'Status', got: {header}"
        );
        assert!(
            header.contains("Age"),
            "header should contain 'Age', got: {header}"
        );
        assert!(
            header.contains("â–²"),
            "sorted column should show â–², got: {header}"
        );
    }

    /// An app-supplied [`DataTableGlyphs`] override replaces the
    /// sort-direction indicator appended to the sorted column's header;
    /// with no override, [`draw_data_table_with_glyphs`] (what
    /// [`draw_data_table`] always calls) appends the same `â–²`/`â–¼` as
    /// today's default.
    #[test]
    fn data_table_glyphs_override_swaps_sort_arrow_default_keeps_arrow() {
        let area = Rect::new(0, 0, 40, 10);

        // Default (no override): ascending sort shows 'â–²'.
        let table = make_table();
        let mut buf = Buffer::empty(area);
        draw_data_table_with_glyphs(&mut buf, area, &table, &Theme::default(), None, None, false);
        let header: String = (0..40)
            .map(|x| buf[(x, 0)].symbol().chars().next().unwrap_or(' '))
            .collect();
        assert!(
            header.contains('â–²'),
            "expected default 'â–²' sort glyph, got: {header}"
        );

        // Override: the app's own ascending glyph replaces 'â–²', and 'â–²'
        // no longer appears in the header.
        let glyphs = DataTableGlyphs::new().with_sort_ascending_glyph("^");
        let mut buf = Buffer::empty(area);
        draw_data_table_with_glyphs(
            &mut buf,
            area,
            &table,
            &Theme::default(),
            None,
            Some(&glyphs),
            false,
        );
        let header: String = (0..40)
            .map(|x| buf[(x, 0)].symbol().chars().next().unwrap_or(' '))
            .collect();
        assert!(
            !header.contains('â–²'),
            "default 'â–²' sort glyph leaked through override, got: {header}"
        );
        assert!(
            header.contains('^'),
            "expected overridden '^' sort glyph, got: {header}"
        );

        // Descending sort with no override still shows the default 'â–¼'.
        let mut desc_table = make_table();
        desc_table.sort = Some((0, SortDirection::Descending));
        let mut buf = Buffer::empty(area);
        draw_data_table_with_glyphs(
            &mut buf,
            area,
            &desc_table,
            &Theme::default(),
            None,
            None,
            false,
        );
        let header: String = (0..40)
            .map(|x| buf[(x, 0)].symbol().chars().next().unwrap_or(' '))
            .collect();
        assert!(
            header.contains('â–¼'),
            "expected default 'â–¼' sort glyph, got: {header}"
        );

        // Override: the app's own descending glyph replaces 'â–¼', and 'â–¼'
        // no longer appears in the header.
        let desc_glyphs = DataTableGlyphs::new().with_sort_descending_glyph("v");
        let mut buf = Buffer::empty(area);
        draw_data_table_with_glyphs(
            &mut buf,
            area,
            &desc_table,
            &Theme::default(),
            None,
            Some(&desc_glyphs),
            false,
        );
        let header: String = (0..40)
            .map(|x| buf[(x, 0)].symbol().chars().next().unwrap_or(' '))
            .collect();
        assert!(
            !header.contains('â–¼'),
            "default 'â–¼' sort glyph leaked through override, got: {header}"
        );
        assert!(
            header.contains('v'),
            "expected overridden 'v' sort glyph, got: {header}"
        );
    }

    #[test]
    fn body_paints_row_content() {
        let table = make_table();
        let area = Rect::new(0, 0, 40, 10);
        let mut buf = Buffer::empty(area);
        draw_data_table(&mut buf, area, &table, &Theme::default(), None);

        // Row 0 at y=1 should contain "pod-abc"
        let row0: String = (0..40)
            .map(|x| buf[(x, 1)].symbol().chars().next().unwrap_or(' '))
            .collect();
        assert!(
            row0.contains("pod-abc"),
            "row 0 should contain 'pod-abc', got: {row0}"
        );
        assert!(
            row0.contains("Running"),
            "row 0 should contain 'Running', got: {row0}"
        );
    }

    #[test]
    fn body_rows_draw_column_separator_at_same_x_as_header() {
        // Column separator is drawn in body rows at the same position as
        let table = make_table();
        let area = Rect::new(0, 0, 40, 10);
        let mut buf = Buffer::empty(area);
        draw_data_table(&mut buf, area, &table, &Theme::default(), None);

        let find_seps =
            |y: u16| -> Vec<u16> { (0..40).filter(|&x| buf[(x, y)].symbol() == "│").collect() };

        let header_seps = find_seps(0);
        assert_eq!(
            header_seps.len(),
            table.columns.len() - 1,
            "header should have one separator per internal column boundary, got {header_seps:?}"
        );

        // `make_table()` has 2 rows, painted at y=1 and y=2.
        for row_y in [1u16, 2u16] {
            let body_seps = find_seps(row_y);
            assert_eq!(
                body_seps, header_seps,
                "body row {row_y} separators should sit at the same x as the header's"
            );
        }
    }

    #[test]
    fn body_cell_exactly_filling_column_still_gets_a_separator() {
        // Acceptance: a cell whose text exactly fills its column must
        // still be separated from its neighbour — no zero-gap abutment.
        let mut table = make_table();
        // Column 0 ("Name") is Flex(2.0) of a 40-wide, 3-Flex-weight-unit
        // area minus the 5-wide fixed "Age" column: (40-5)*2/3 ≈ 23.33 →
        // resolves to 23 cells wide, of which 22 are usable (one cell is
        // reserved for the separator, same as the header). Fill exactly
        // that usable width.
        table.rows[0].cells[0] = StyledText::plain("x".repeat(22));
        let area = Rect::new(0, 0, 40, 10);
        let mut buf = Buffer::empty(area);
        let layout = draw_data_table(&mut buf, area, &table, &Theme::default(), None);

        let sep_x = (layout.columns[0].x.round() as i32 + layout.columns[0].width.round() as i32
            - 1) as u16;
        let ch = buf[(sep_x, 1)].symbol().to_string();
        assert_eq!(
            ch, "│",
            "an exactly-filling cell must not paint over the separator column"
        );
    }

    #[test]
    fn body_cell_wider_than_column_is_clipped_and_does_not_bleed_into_neighbour() {
        // An over-long column cell is clipped to its own boundary, not to
        let table = DataTable {
            id: WidgetId::new("clip-test"),
            columns: vec![
                Column {
                    title: "A".into(),
                    width: ColumnWidth::Flex(1.0),
                    align: ColumnAlign::Left,
                },
                Column {
                    title: "B".into(),
                    width: ColumnWidth::Flex(1.0),
                    align: ColumnAlign::Left,
                },
                Column {
                    title: "C".into(),
                    width: ColumnWidth::Flex(1.0),
                    align: ColumnAlign::Left,
                },
            ],
            rows: vec![DataRow {
                cells: vec![
                    StyledText::plain("A"),
                    StyledText::plain("this-value-is-far-wider-than-its-resolved-column-share"),
                    StyledText::plain("C"),
                ],
                decoration: Decoration::Normal,
            }],
            selected_idx: None,
            scroll_offset: 0,
            sort: None,
            has_focus: false,
            show_scrollbar: false,
            min_total_width: None,
            h_scroll: 0.0,
            column_overrides: Vec::new(),
            footer: None,
        };
        let area = Rect::new(0, 0, 30, 10);
        let mut buf = Buffer::empty(area);
        let layout = draw_data_table(&mut buf, area, &table, &Theme::default(), None);

        let row: Vec<char> = (0..30)
            .map(|x| buf[(x, 1)].symbol().chars().next().unwrap_or(' '))
            .collect();
        let row_str: String = row.iter().collect();

        let c_col = &layout.columns[2];
        let c_start = c_col.x.round() as usize;

        // Column C's own value paints intact at its own column start...
        assert_eq!(row[c_start], 'C', "row: {row_str:?}");
        // ...and every other cell inside C's column is untouched
        // background, never a stray character bled over from B.
        for (x, &ch) in row.iter().enumerate().skip(c_start + 1) {
            assert_eq!(
                ch, ' ',
                "cell at x={x} inside column C should be blank, not corrupted by B's overflow \
                 (row: {row_str:?})"
            );
        }

        // The overflowing B cell shows an ellipsis rather than a hard cut.
        let b_col = &layout.columns[1];
        let b_range = (b_col.x.round() as usize)..c_start;
        assert!(
            b_range.clone().any(|x| row[x] == '…'),
            "over-long body cell should end in an ellipsis, not a hard cut: {row_str:?}"
        );
    }

    #[test]
    fn paint_click_round_trip_header() {
        let table = make_table();
        let area = Rect::new(0, 0, 40, 10);
        let mut buf = Buffer::empty(area);
        let layout = draw_data_table(&mut buf, area, &table, &Theme::default(), None);

        // Find "Status" in the header row
        let header: String = (0..40)
            .map(|x| buf[(x, 0)].symbol().chars().next().unwrap_or(' '))
            .collect();
        let status_pos = header.find("Status").expect("Status should be in header");
        // Click in the middle of "Status" (not at the left edge where the
        // divider grab zone would match).
        let hit = layout.hit_test(status_pos as f32 + 3.0, 0.5, 0, table.rows.len());
        assert_eq!(hit, DataTableHit::Header { col: 1 });
    }

    /// LESSONS.md non-zero-origin regression guard:
    /// `data_table_layout` never reads `area.x`/`area.y` (see its doc
    /// comment) — it, and therefore `hit_test`, is table-**local**, unlike
    /// most of this batch's other layout fns which bake the origin in.
    /// Painting still happens at the absolute `area.x`/`area.y` (mirrors
    /// `tui/activity_bar.rs`'s relative-hit-regions / absolute-paint split),
    /// so this scans the buffer at the shifted absolute position but keeps
    /// the resulting index — and the `hit_test` call — table-local.
    #[test]
    fn paint_click_round_trip_header_at_nonzero_origin() {
        let table = make_table();
        let area = Rect::new(7, 13, 40, 10);
        let mut buf = Buffer::empty(area);
        let layout = draw_data_table(&mut buf, area, &table, &Theme::default(), None);

        let header: String = (area.x..area.x + 40)
            .map(|x| buf[(x, area.y)].symbol().chars().next().unwrap_or(' '))
            .collect();
        let status_pos = header.find("Status").expect("Status should be in header");
        let hit = layout.hit_test(status_pos as f32 + 3.0, 0.5, 0, table.rows.len());
        assert_eq!(hit, DataTableHit::Header { col: 1 });
    }

    #[test]
    fn paint_click_round_trip_row() {
        let table = make_table();
        let area = Rect::new(0, 0, 40, 10);
        let mut buf = Buffer::empty(area);
        let layout = draw_data_table(&mut buf, area, &table, &Theme::default(), None);

        // Find "pod-xyz" in row 1 (y=2)
        let row1: String = (0..40)
            .map(|x| buf[(x, 2)].symbol().chars().next().unwrap_or(' '))
            .collect();
        let pod_pos = row1.find("pod-xyz").expect("pod-xyz should be in row 1");
        let hit = layout.hit_test(pod_pos as f32, 2.5, 0, table.rows.len());
        assert_eq!(hit, DataTableHit::Row { idx: 1 });
    }

    /// Non-zero-origin sibling of `paint_click_round_trip_row` — see
    /// `paint_click_round_trip_header_at_nonzero_origin`.
    #[test]
    fn paint_click_round_trip_row_at_nonzero_origin() {
        let table = make_table();
        let area = Rect::new(7, 13, 40, 10);
        let mut buf = Buffer::empty(area);
        let layout = draw_data_table(&mut buf, area, &table, &Theme::default(), None);

        // Row 1 paints on the *absolute* screen row `area.y + 2`.
        let row1: String = (area.x..area.x + 40)
            .map(|x| buf[(x, area.y + 2)].symbol().chars().next().unwrap_or(' '))
            .collect();
        let pod_pos = row1.find("pod-xyz").expect("pod-xyz should be in row 1");
        let hit = layout.hit_test(pod_pos as f32, 2.5, 0, table.rows.len());
        assert_eq!(hit, DataTableHit::Row { idx: 1 });
    }

    /// Direct "bounds do not move" guard, mirroring
    /// `tui/activity_bar.rs`'s `hit_regions_do_not_move_when_the_bar_does`:
    /// the resolved column bounds must be byte-for-byte identical no matter
    /// where `area` sits on screen, since `data_table_layout` is table-local
    /// by construction.
    #[test]
    fn column_bounds_do_not_move_when_the_table_does() {
        let table = make_table();
        let cols_at = |origin_x: u16, origin_y: u16| {
            let area = Rect::new(origin_x, origin_y, 40, 10);
            let mut buf = Buffer::empty(area);
            let layout = draw_data_table(&mut buf, area, &table, &Theme::default(), None);
            layout
                .columns
                .iter()
                .map(|c| (c.x, c.width))
                .collect::<Vec<_>>()
        };

        let at_zero = cols_at(0, 0);
        assert!(!at_zero.is_empty(), "sanity: some columns were resolved");
        assert_eq!(
            cols_at(7, 13),
            at_zero,
            "column bounds must be table-local, independent of area.x/area.y"
        );
    }

    /// A table with many more rows than fit the viewport, for footer
    /// pinning + scroll tests.
    fn make_scrolling_table(nrows: usize) -> DataTable {
        let mut table = make_table();
        table.rows = (0..nrows)
            .map(|r| DataRow {
                cells: vec![
                    StyledText::plain(format!("pod-{r}")),
                    StyledText::plain("Running"),
                    StyledText::plain(format!("{r}d")),
                ],
                decoration: Decoration::Normal,
            })
            .collect();
        table
    }

    #[test]
    fn footer_row_renders_pinned_regardless_of_scroll_offset() {
        let mut table = make_scrolling_table(50);
        table.footer = Some(DataRow {
            cells: vec![
                StyledText::plain("TOTAL"),
                StyledText::plain(""),
                StyledText::plain("50d"),
            ],
            decoration: Decoration::Normal,
        });
        let area = Rect::new(0, 0, 40, 10);

        for scroll_offset in [0, 5, 30] {
            table.scroll_offset = scroll_offset;
            let mut buf = Buffer::empty(area);
            let layout = draw_data_table(&mut buf, area, &table, &Theme::default(), None);
            assert!(layout.footer_height > 0.0);

            // Footer text is always painted on the last row of the
            // viewport, no matter how far the body has scrolled.
            let last_row: String = (0..40)
                .map(|x| {
                    buf[(x, area.height - 1)]
                        .symbol()
                        .chars()
                        .next()
                        .unwrap_or(' ')
                })
                .collect();
            assert!(
                last_row.contains("TOTAL"),
                "footer should stay pinned at scroll_offset={scroll_offset}, got: {last_row}"
            );
        }
    }

    #[test]
    fn footer_cell_aligns_under_its_column() {
        // Right-aligned "Age" column → its footer total should sit at
        // the same right edge as a normal right-aligned body cell.
        let mut table = make_table();
        table.footer = Some(DataRow {
            cells: vec![
                StyledText::plain(""),
                StyledText::plain(""),
                StyledText::plain("4d"),
            ],
            decoration: Decoration::Normal,
        });
        let area = Rect::new(0, 0, 40, 10);
        let mut buf = Buffer::empty(area);
        let layout = draw_data_table(&mut buf, area, &table, &Theme::default(), None);
        let footer_y = area.height - 1;

        let footer_line: String = (0..40)
            .map(|x| buf[(x, footer_y)].symbol().chars().next().unwrap_or(' '))
            .collect();
        let body_line: String = (0..40)
            .map(|x| buf[(x, 1)].symbol().chars().next().unwrap_or(' '))
            .collect();
        // Char-cell position, not byte offset: `str::find` returns a byte
        // index, and body rows now paint a `'│'` separator which is 3 bytes
        // but exactly 1 cell — a byte-offset comparison would fail even
        // though the two cells line up.
        let footer_pos = find_char_pos(&footer_line, "4d").expect("footer total painted");
        let body_pos = find_char_pos(&body_line, "3d").expect("body cell painted");
        assert_eq!(
            footer_pos, body_pos,
            "footer's Age total should align at the same x as a body row's Age cell"
        );

        // And it should land inside the Age column's resolved bounds.
        let age_col = &layout.columns[2];
        assert!(footer_pos as f32 >= age_col.x && (footer_pos as f32) < age_col.x + age_col.width);
    }

    #[test]
    fn footer_click_is_footer_hit_not_row() {
        let mut table = make_scrolling_table(50);
        table.footer = Some(DataRow {
            cells: vec![StyledText::plain("TOTAL")],
            decoration: Decoration::Normal,
        });
        let area = Rect::new(0, 0, 40, 10);
        let layout = {
            let mut buf = Buffer::empty(area);
            draw_data_table(&mut buf, area, &table, &Theme::default(), None)
        };

        let hit = layout.hit_test(
            2.0,
            (area.height - 1) as f32 + 0.5,
            table.scroll_offset,
            table.rows.len(),
        );
        assert_eq!(hit, DataTableHit::Footer);
    }

    #[test]
    fn none_footer_body_unaffected() {
        // With `footer: None`, the last paintable row is still a body row,
        // not blank footer space.
        let table = make_scrolling_table(3);
        let area = Rect::new(0, 0, 40, 10);
        let mut buf = Buffer::empty(area);
        let layout = draw_data_table(&mut buf, area, &table, &Theme::default(), None);
        assert_eq!(layout.footer_height, 0.0);
        let row2: String = (0..40)
            .map(|x| buf[(x, 3)].symbol().chars().next().unwrap_or(' '))
            .collect();
        assert!(
            row2.contains("pod-2"),
            "row 2 should paint normally, got: {row2}"
        );
    }

    /// A table laid out wider than its viewport, so `h_scroll` is
    /// genuinely drivable: 4 × `Fixed(12.0)` columns (48 content cells)
    /// inside a 24-cell viewport.
    fn make_h_scrolling_table() -> DataTable {
        let titles = ["Alpha", "Bravo", "Charlie", "Delta"];
        DataTable {
            id: WidgetId::new("hscroll"),
            columns: titles
                .iter()
                .map(|t| Column {
                    title: (*t).into(),
                    width: ColumnWidth::Fixed(12.0),
                    align: ColumnAlign::Left,
                })
                .collect(),
            rows: vec![DataRow {
                cells: vec![
                    StyledText::plain("a-one"),
                    StyledText::plain("b-two"),
                    StyledText::plain("c-three"),
                    StyledText::plain("d-four"),
                ],
                decoration: Decoration::Normal,
            }],
            selected_idx: None,
            scroll_offset: 0,
            sort: None,
            has_focus: false,
            show_scrollbar: false,
            min_total_width: Some(48.0),
            h_scroll: 0.0,
            column_overrides: Vec::new(),
            footer: None,
        }
    }

    /// Whatever header title the rasteriser paints at a given screen cell,
    /// hit-testing that cell must name the same column — at every scroll
    /// offset, including one large enough to push the first column fully
    /// off-screen.
    #[test]
    fn h_scrolled_header_click_resolves_to_the_painted_column() {
        let area = Rect::new(0, 0, 24, 6);
        // 0 → nothing scrolled; 14 → "Alpha" partially off; 30 → "Alpha"
        // and "Bravo" both fully off-screen.
        for h_scroll in [0.0_f32, 6.0, 14.0, 30.0] {
            let mut table = make_h_scrolling_table();
            table.h_scroll = h_scroll;
            let mut buf = Buffer::empty(area);
            let layout = draw_data_table(&mut buf, area, &table, &Theme::default(), None);

            let header: String = (0..area.width)
                .map(|x| buf[(x, 0)].symbol().chars().next().unwrap_or(' '))
                .collect();

            let mut checked = 0;
            for (col_idx, col) in table.columns.iter().enumerate() {
                let Some(pos) = find_char_pos(&header, &col.title) else {
                    continue; // title scrolled off (or clipped) — nothing to click
                };
                checked += 1;
                // Click the last painted char of the title: still inside
                // the column, and for a fully-visible title far enough
                // from the left edge that the previous column's divider
                // grab zone can't claim it.
                let x = pos + col.title.chars().count() - 1;
                assert_eq!(
                    layout.hit_test(x as f32 + 0.5, 0.5, 0, table.rows.len()),
                    DataTableHit::Header { col: col_idx },
                    "h_scroll={h_scroll}: cell {x} paints '{}' but hit-tests elsewhere\n\
                     header: {header:?}",
                    col.title
                );
            }
            assert!(
                checked > 0,
                "h_scroll={h_scroll} painted no fully-visible header title — the assertion \
                 loop above would be vacuous\nheader: {header:?}"
            );
        }
    }

    #[test]
    fn h_scrolled_body_cell_click_resolves_to_the_painted_column() {
        let area = Rect::new(0, 0, 24, 6);
        for h_scroll in [0.0_f32, 6.0, 14.0, 30.0] {
            let mut table = make_h_scrolling_table();
            table.h_scroll = h_scroll;
            let mut buf = Buffer::empty(area);
            let layout = draw_data_table(&mut buf, area, &table, &Theme::default(), None);

            let row: String = (0..area.width)
                .map(|x| buf[(x, 1)].symbol().chars().next().unwrap_or(' '))
                .collect();

            let mut checked = 0;
            for (col_idx, cell) in table.rows[0].cells.iter().enumerate() {
                let text: String = cell.spans.iter().map(|s| s.text.as_str()).collect();
                let Some(pos) = find_char_pos(&row, &text) else {
                    continue;
                };
                checked += 1;
                // The body band still routes to a row...
                assert_eq!(
                    layout.hit_test(pos as f32 + 0.5, 1.5, 0, table.rows.len()),
                    DataTableHit::Row { idx: 0 },
                    "h_scroll={h_scroll}: body click should stay row 0"
                );
                // ...and `column_hit` names the cell painted there.
                assert_eq!(
                    layout.column_hit(pos as f32 + 0.5),
                    Some(col_idx),
                    "h_scroll={h_scroll}: cell {pos} paints '{text}' but column_hit disagrees\n\
                     row: {row:?}"
                );
            }
            assert!(
                checked > 0,
                "h_scroll={h_scroll} painted no fully-visible body cell — the assertion loop \
                 above would be vacuous\nrow: {row:?}"
            );
        }
    }

    // TUI pointer input is a raw integer cell index (`Point::new(event.column as f32,
    // event.row as f32)`), not cell-centre coordinates. Painting rounds fractional
    // `h_scroll` values; these tests use raw integer `x` at deliberately fractional
    // `h_scroll` values whose fractional part is `>= 0.5` to verify the layout stays
    // consistent across rounding.

    /// 4 × `Fixed(30.0)` columns (content boundaries 0/30/60/90/120) inside a
    /// 60-wide viewport.
    fn make_wide_hscroll_table() -> DataTable {
        let titles = ["Alpha", "Bravo", "Charlie", "Delta"];
        DataTable {
            id: WidgetId::new("wide-hscroll"),
            columns: titles
                .iter()
                .map(|t| Column {
                    title: (*t).into(),
                    width: ColumnWidth::Fixed(30.0),
                    align: ColumnAlign::Left,
                })
                .collect(),
            rows: vec![DataRow {
                cells: vec![
                    StyledText::plain("a-one"),
                    StyledText::plain("b-two"),
                    StyledText::plain("c-three"),
                    StyledText::plain("d-four"),
                ],
                decoration: Decoration::Normal,
            }],
            selected_idx: None,
            scroll_offset: 0,
            sort: None,
            has_focus: false,
            show_scrollbar: false,
            min_total_width: Some(120.0),
            h_scroll: 0.0,
            column_overrides: Vec::new(),
            footer: None,
        }
    }

    #[test]
    fn raw_integer_click_at_fractional_h_scroll_hits_the_painted_column() {
        // At h_scroll = 15.6, h_off = round(15.6) = 16. The renderer paints column c1
        // (content [30,60)) at screen [14,44). A real click at integer screen x=14 is
        // squarely on c1 as painted, and `column_hit` (the divider-agnostic
        // "which column is painted here" query) resolves it correctly.
        let area = Rect::new(0, 0, 60, 3);
        let mut table = make_wide_hscroll_table();
        table.h_scroll = 15.6;
        let mut buf = Buffer::empty(area);
        let layout = draw_data_table(&mut buf, area, &table, &Theme::default(), None);

        assert_eq!(
            layout.h_scroll, 16.0,
            "TUI layout must carry the rounded offset"
        );

        // Raw integer coordinate (no `+ 0.5`), exactly as `tui::events`
        // constructs a real pointer position.
        assert_eq!(
            layout.column_hit(14.0),
            Some(1),
            "integer click x=14 sits on c1's painted left edge at h_scroll=15.6"
        );

        // The pre-fix bug: adding the *un-rounded* 15.6 back would put
        // this at content x=29.6, inside c0's [0,30) — never c1's.
        assert_ne!(layout.column_hit(14.0), Some(0));

        // The header branch of `hit_test` sits at the exact same screen
        // x, but content x=30 lands precisely on the c0/c1 divider's
        // grab zone (`DIVIDER_GRAB_PX = 3.0`), so per the review's own
        // analysis it resolves to `HeaderDivider` rather than either
        // header — never the *wrong* header (`Header { col: 0 }`, the
        // original defect this fix closes).
        assert_eq!(
            layout.hit_test(14.0, 0.0, 0, table.rows.len()),
            DataTableHit::HeaderDivider { col: 0 },
            "residual at an exact boundary falls in the pre-existing divider grab zone"
        );
        assert_ne!(
            layout.hit_test(14.0, 0.0, 0, table.rows.len()),
            DataTableHit::Header { col: 0 },
        );
    }

    #[test]
    fn raw_integer_body_click_at_fractional_h_scroll_hits_the_painted_column() {
        // Same geometry, but a body-row click — the "cell hit" half of
        // the same repro.
        let area = Rect::new(0, 0, 60, 3);
        let mut table = make_wide_hscroll_table();
        table.h_scroll = 15.6;
        let mut buf = Buffer::empty(area);
        let layout = draw_data_table(&mut buf, area, &table, &Theme::default(), None);

        assert_eq!(
            layout.hit_test(14.0, 1.0, 0, table.rows.len()),
            DataTableHit::Row { idx: 0 },
            "row resolution is unaffected by h_scroll rounding"
        );
        assert_eq!(layout.column_hit(14.0), Some(1));
    }

    #[test]
    fn raw_integer_header_click_at_fractional_h_scroll_does_not_silently_arm_a_resize_drag() {
        // At fractional offsets whose fractional part is >= 0.5, the residual always
        // falls inside DIVIDER_GRAB_PX of some boundary, so the header click resolves
        // to `HeaderDivider` rather than a wrong `Header` column.
        let area = Rect::new(0, 0, 60, 3);
        for h_scroll in [15.6_f32, 45.7, 75.9] {
            let mut table = make_wide_hscroll_table();
            table.h_scroll = h_scroll;
            let mut buf = Buffer::empty(area);
            let layout = draw_data_table(&mut buf, area, &table, &Theme::default(), None);
            let h_off = h_scroll.round();

            for x in 0..60u16 {
                let hit = layout.hit_test(x as f32, 0.0, 0, table.rows.len());
                if let DataTableHit::Header { col } = hit {
                    // The column this integer x resolves to must be the
                    // column actually painted there — content x is
                    // `x + h_off` (the rounded offset baked into
                    // `layout.h_scroll`).
                    let content_x = x as f32 + h_off;
                    let painted = layout
                        .columns
                        .iter()
                        .position(|rc| content_x >= rc.x && content_x < rc.x + rc.width);
                    assert_eq!(
                        painted,
                        Some(col),
                        "h_scroll={h_scroll}: integer x={x} resolved to Header{{col: {col}}} \
                         but the renderer paints column {painted:?} there"
                    );
                }
            }
        }
    }

    #[test]
    fn h_scrolled_header_divider_click_resolves_to_the_painted_separator() {
        let area = Rect::new(0, 0, 24, 6);
        for h_scroll in [0.0_f32, 6.0, 14.0, 30.0] {
            let mut table = make_h_scrolling_table();
            table.h_scroll = h_scroll;
            let mut buf = Buffer::empty(area);
            let layout = draw_data_table(&mut buf, area, &table, &Theme::default(), None);

            // The rasteriser paints '│' on the right edge cell of every
            // column but the last, i.e. one cell *before* the boundary
            // `hit_test` measures the grab zone from.
            let painted_seps: Vec<u16> = (0..area.width)
                .filter(|&x| buf[(x, 0)].symbol() == "│")
                .collect();
            assert!(
                !painted_seps.is_empty(),
                "h_scroll={h_scroll}: expected at least one painted separator"
            );
            for sep_x in painted_seps {
                let hit = layout.hit_test(sep_x as f32 + 0.5, 0.5, 0, table.rows.len());
                let DataTableHit::HeaderDivider { col } = hit else {
                    panic!(
                        "h_scroll={h_scroll}: separator painted at x={sep_x} must hit-test as a \
                         divider, got {hit:?}"
                    );
                };
                // Round-trip the column index back to the boundary it
                // owns and confirm it is the one painted here.
                let boundary = layout.columns[col].x + layout.columns[col].width;
                assert!(
                    ((boundary - h_scroll) - (sep_x as f32 + 1.0)).abs() < 0.01,
                    "h_scroll={h_scroll}: separator at x={sep_x} resolved to divider {col}, \
                     whose boundary paints at {}",
                    boundary - h_scroll
                );
            }
        }
    }

    #[test]
    fn vertical_scrollbar_track_excludes_footer_band() {
        // Regression guard: the vertical scrollbar's track must span
        // only the body band (header..footer), not header..bottom-of
        // -viewport. With area.height=10, header_height=1 and a footer
        // present (footer_height=2), the track should be exactly
        // `visible_rows` cells tall — not `area.height - 1` (9).
        let mut table = make_scrolling_table(50);
        table.show_scrollbar = true;
        table.footer = Some(DataRow {
            cells: vec![StyledText::plain("TOTAL")],
            decoration: Decoration::Normal,
        });
        let area = Rect::new(0, 0, 40, 10);
        let mut buf = Buffer::empty(area);
        let layout = draw_data_table(&mut buf, area, &table, &Theme::default(), None);
        assert_eq!(layout.footer_height, 2.0);
        assert_eq!(layout.visible_rows, 7);

        // Scrollbar column sits at the right edge of the area.
        let sb_x = area.width - 1;
        let track_cells = (0..area.height)
            .filter(|&y| matches!(buf[(sb_x, y)].symbol(), "â–ˆ" | "â–‘"))
            .count();
        assert_eq!(
            track_cells, layout.visible_rows,
            "scrollbar track should span exactly the body band (visible_rows), \
             not bleed into the reserved footer band"
        );

        // The footer band itself (last `footer_height` rows) must be
        // free of scrollbar track/thumb glyphs.
        for y in (area.height - 2)..area.height {
            let sym = buf[(sb_x, y)].symbol();
            assert_ne!(
                sym, "â–ˆ",
                "footer row {y} should not be painted over by the scrollbar thumb"
            );
            assert_ne!(
                sym, "â–‘",
                "footer row {y} should not be painted over by the scrollbar track"
            );
        }
    }
}

/// Multi-select keyboard wiring over [`crate::tui::testing::TuiDriver`].
///
/// `DataTable` stays purely declarative (no selection-set field of its
/// own — see `crate::types::apply_selection_gesture`'s doc), so the app
/// owns the selected-index set, the keyboard cursor, and the gesture
/// anchor. TUI has no mouse, so unlike the click-driven
/// `crate::gtk::data_table`/`crate::win::data_table` counterparts, a
/// plain Up/Down only moves the cursor; Shift+Up/Down extends a range
/// from the anchor via [`SelectionGesture::from_modifiers`], and Space
/// toggles the cursor row without moving it.
#[cfg(test)]
mod multi_select_driver_tests {
    use crate::primitives::data_table::{Column, DataRow, DataTable};
    use crate::runner::{AppLogic, Reaction};
    use crate::tui::testing::TuiDriver;
    use crate::{
        apply_selection_gesture, Backend, DataTableEvent, Decoration, Key, Modifiers, NamedKey,
        Rect, SelectionGesture, StyledText, UiEvent, WidgetId,
    };

    const VIEWPORT_W: u16 = 40;
    const VIEWPORT_H: u16 = 10;

    fn row(label: &str) -> DataRow {
        DataRow {
            cells: vec![StyledText::plain(label.to_string())],
            decoration: Decoration::Normal,
        }
    }

    fn sample_table() -> DataTable {
        DataTable {
            id: WidgetId::new("dt"),
            columns: vec![Column {
                title: "Name".to_string(),
                width: Default::default(),
                align: Default::default(),
            }],
            rows: (0..5).map(|i| row(&format!("row {i}"))).collect(),
            selected_idx: None,
            scroll_offset: 0,
            sort: None,
            has_focus: true,
            show_scrollbar: false,
            min_total_width: None,
            h_scroll: 0.0,
            column_overrides: vec![],
            footer: None,
        }
    }

    struct TableApp {
        table: DataTable,
        cursor: usize,
        selected: Vec<usize>,
        anchor: usize,
        events: Vec<DataTableEvent>,
    }

    impl TableApp {
        fn new() -> Self {
            Self {
                table: sample_table(),
                cursor: 0,
                selected: Vec::new(),
                anchor: 0,
                events: Vec::new(),
            }
        }
    }

    impl AppLogic for TableApp {
        type AreaId = ();

        fn render(&self, backend: &mut dyn Backend, _area: ()) {
            backend.draw_data_table(
                Rect::new(0.0, 0.0, VIEWPORT_W as f32, VIEWPORT_H as f32),
                &self.table,
                None,
            );
        }

        fn handle(&mut self, event: UiEvent, _backend: &mut dyn Backend) -> Reaction {
            let UiEvent::KeyPressed { key, modifiers, .. } = event else {
                return Reaction::Continue;
            };
            let last = self.table.rows.len().saturating_sub(1);
            match key {
                Key::Named(NamedKey::Down) | Key::Named(NamedKey::Up) => {
                    let delta: isize = if key == Key::Named(NamedKey::Down) {
                        1
                    } else {
                        -1
                    };
                    self.cursor = (self.cursor as isize + delta).clamp(0, last as isize) as usize;
                    if !modifiers.shift {
                        // A plain move repositions the cursor only; the
                        // selection changes explicitly via Space/Shift.
                        return Reaction::Redraw;
                    }
                    let indices = apply_selection_gesture(
                        &self.selected,
                        self.anchor,
                        self.cursor,
                        SelectionGesture::Range,
                    );
                    self.selected = indices.clone();
                    self.events.push(DataTableEvent::SelectionSet { indices });
                    Reaction::Redraw
                }
                Key::Char(' ') => {
                    let indices = apply_selection_gesture(
                        &self.selected,
                        self.anchor,
                        self.cursor,
                        SelectionGesture::Toggle,
                    );
                    self.selected = indices.clone();
                    self.anchor = self.cursor;
                    self.events.push(DataTableEvent::SelectionSet { indices });
                    Reaction::Redraw
                }
                _ => Reaction::Continue,
            }
        }
    }

    fn key_event(key: Key, modifiers: Modifiers) -> UiEvent {
        UiEvent::KeyPressed {
            key,
            modifiers,
            repeat: false,
        }
    }

    fn driver() -> TuiDriver<TableApp> {
        TuiDriver::new(TableApp::new(), VIEWPORT_W, VIEWPORT_H)
    }

    #[test]
    fn plain_arrow_moves_the_cursor_without_changing_selection() {
        let mut driver = driver();
        driver.dispatch(key_event(Key::Named(NamedKey::Down), Modifiers::default()));
        assert_eq!(driver.app().cursor, 1);
        assert_eq!(driver.app().selected, Vec::<usize>::new());
    }

    #[test]
    fn space_toggles_rows_into_a_multi_selection() {
        let mut driver = driver();
        driver.dispatch(key_event(Key::Char(' '), Modifiers::default()));
        driver.dispatch(key_event(Key::Named(NamedKey::Down), Modifiers::default()));
        driver.dispatch(key_event(Key::Named(NamedKey::Down), Modifiers::default()));
        driver.dispatch(key_event(Key::Char(' '), Modifiers::default()));
        assert_eq!(driver.app().selected, vec![0, 2]);
        // Space toggles the same row back off.
        driver.dispatch(key_event(Key::Named(NamedKey::Up), Modifiers::default()));
        driver.dispatch(key_event(Key::Named(NamedKey::Up), Modifiers::default()));
        driver.dispatch(key_event(Key::Char(' '), Modifiers::default()));
        assert_eq!(driver.app().selected, vec![2]);
        assert_eq!(
            driver.app().events.last(),
            Some(&DataTableEvent::SelectionSet { indices: vec![2] })
        );
    }

    #[test]
    fn shift_arrow_extends_a_range_from_the_anchor() {
        let mut driver = driver();
        driver.dispatch(key_event(Key::Char(' '), Modifiers::default()));
        let shift = Modifiers {
            shift: true,
            ..Default::default()
        };
        driver.dispatch(key_event(Key::Named(NamedKey::Down), shift));
        driver.dispatch(key_event(Key::Named(NamedKey::Down), shift));
        driver.dispatch(key_event(Key::Named(NamedKey::Down), shift));
        assert_eq!(driver.app().selected, vec![0, 1, 2, 3]);
        assert_eq!(
            driver.app().events.last(),
            Some(&DataTableEvent::SelectionSet {
                indices: vec![0, 1, 2, 3]
            })
        );
    }
}