retroglyph-ui 0.5.0

Immediate-mode terminal UI toolkit for retroglyph: widgets, layout, input/focus, theming, and animation
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
//! [`Table`]: a fixed-column, scrollable table with a highlighted row.
use retroglyph_core::color::{Color, Style};
use retroglyph_core::grid::Rect;

use super::window::visible_window;
use super::{InteractiveWidget, Measure, StatefulWidget};
use crate::Surface;
use crate::align::Align;
use crate::draw::fill_rect;
use crate::interact::Response;
use crate::interact::Sense;
use crate::state::ListState;
use crate::text::draw_clipped;
use crate::theme::Theme;

/// A fixed-column, scrollable table with a [`ListState`]-driven highlighted
/// row.
///
/// `headers` render on the first row of the area it's rendered into;
/// `rows` follow, one per line, clipped to that area. `widths` gives each
/// column's cell width; columns are space-separated and truncated to fit.
///
/// `state.offset()` is the index of the first row drawn below the header --
/// rendering draws whatever window `offset` names and does not clamp or
/// auto-scroll it, matching [`ListState`]'s existing "only the caller knows
/// the viewport height" design. Call
/// [`state.ensure_visible(visible_row_count)`](ListState::ensure_visible)
/// before rendering to keep `state.selected()` on-screen. If `selected()` is
/// `Some` and its row falls within the visible window, that row is drawn
/// with an inverted highlight background; if it has scrolled out of view,
/// no row is highlighted.
///
/// `header_style`, `row_style`, and `selected_style` default to [`Theme::DARK`] (as if
/// [`Table::theme`] had been called); set them with [`Table::header_style`],
/// [`Table::row_style`], and [`Table::selected_style`]. `column_spacing` defaults to `1` (a
/// single blank column between cells); set it with [`Table::column_spacing`].
///
/// As an [`InteractiveWidget`], a single id covers the whole table: a click selects the row
/// under [`Response::pointer_pos`], resolved from this table's own row geometry (the header row
/// plus `state.offset()`) the same way [`super::List`] resolves its own rows, and the wheel
/// scrolls it via [`Response::scroll_delta`]/[`ListState::scroll_by`]. A click on the header row
/// itself selects nothing.
///
/// # Examples
///
/// ```
/// use retroglyph_core::grid::{Grid, Rect};
/// use retroglyph_ui::state::ListState;
/// use retroglyph_ui::widget::{StatefulWidget, Table};
/// use retroglyph_ui::Surface;
///
/// let headers = ["Name", "Score"];
/// let widths = [10u16, 6];
/// let rows: [&[&str]; 2] = [&["Alpha", "10"], &["Bravo", "20"]];
///
/// let mut state = ListState::new();
/// state.select(Some(1));
///
/// let area = Rect::new(0, 0, 20, 3);
/// let mut grid = Grid::new(20, 3);
/// Table::new(&headers, &widths, &rows).render(&mut Surface::new(&mut grid, area, 0), &mut state);
/// ```
#[derive(Clone, Copy, Debug)]
pub struct Table<'a> {
    headers: &'a [&'a str],
    widths: &'a [u16],
    rows: &'a [&'a [&'a str]],
    header_style: Style,
    row_style: Style,
    selected_style: Style,
    column_spacing: u16,
}

impl<'a> Table<'a> {
    /// A table with the given header labels, column widths, and rows, styled from
    /// [`Theme::DARK`] (as if [`Table::theme`] had been called).
    #[must_use]
    pub fn new(headers: &'a [&'a str], widths: &'a [u16], rows: &'a [&'a [&'a str]]) -> Self {
        Self {
            headers,
            widths,
            rows,
            header_style: Style::new(),
            row_style: Style::new(),
            selected_style: Style::new(),
            column_spacing: 1,
        }
        .theme(Theme::DARK)
    }

    /// Set the header row's style.
    #[must_use]
    pub const fn header_style(mut self, style: Style) -> Self {
        self.header_style = style;
        self
    }

    /// Set the style of unselected rows.
    #[must_use]
    pub const fn row_style(mut self, style: Style) -> Self {
        self.row_style = style;
        self
    }

    /// Set the style of the selected row, including its background fill.
    #[must_use]
    pub const fn selected_style(mut self, style: Style) -> Self {
        self.selected_style = style;
        self
    }

    /// Set the number of blank columns between cells.
    #[must_use]
    pub const fn column_spacing(mut self, spacing: u16) -> Self {
        self.column_spacing = spacing;
        self
    }

    /// Applies `theme`'s named roles to this table's row styles: `header_style` becomes
    /// `theme.fg` (brighter, matching the header's original brighter-than-row default) on
    /// `theme.panel_bg`, `row_style` becomes `theme.dim` (the same de-emphasized role a plain
    /// body row already reads as) on `theme.panel_bg`, and `selected_style` becomes `theme.bg`
    /// on `theme.accent`: the same bright-on-accent highlight [`super::List::theme`] and
    /// [`super::Button::theme`] use.
    ///
    /// `header_style`/`row_style` always set an explicit background for the same reason, and with
    /// the same caveat, as [`super::Gauge::theme`]; see its doc comment for the full explanation.
    /// Drawing this table directly on the raw screen background instead of inside a themed panel
    /// needs a manual `.header_style(...)`/`.row_style(...)` override afterwards.
    ///
    /// Call before any manual [`Table::header_style`]/[`Table::row_style`]/
    /// [`Table::selected_style`] override you want to keep.
    #[must_use]
    pub fn theme(self, theme: Theme) -> Self {
        self.theme_on(theme, theme.panel_bg)
    }

    /// Same as [`Table::theme`], but `header_style`/`row_style` are drawn on `bg` instead of
    /// `theme.panel_bg`: for a table drawn directly on a backdrop other than a themed
    /// [`super::Panel`]/[`super::Modal`]'s fill, e.g. the raw screen background or a different
    /// panel's fill color. [`Table::theme`] is exactly `theme_on(theme, theme.panel_bg)`.
    #[must_use]
    pub fn theme_on(mut self, theme: Theme, bg: Color) -> Self {
        self.header_style = Style::new().fg(theme.fg).bg(bg);
        self.row_style = Style::new().fg(theme.dim).bg(bg);
        self.selected_style = Style::new().fg(theme.bg).bg(theme.accent);
        self
    }
}

impl Table<'_> {
    /// The shared drawing routine both [`StatefulWidget::render`] and
    /// [`InteractiveWidget::render`] use.
    fn draw(&self, surface: &mut Surface<'_>, state: &ListState) {
        let (width, height) = (surface.width(), surface.height());
        if width == 0 || height == 0 {
            return;
        }
        draw_row(
            surface,
            width,
            0,
            self.headers,
            self.widths,
            RowStyle {
                style: self.header_style,
                bg: None,
                column_spacing: self.column_spacing,
            },
        );

        let visible_rows = usize::from(height).saturating_sub(1);
        let selected = state.selected();
        for (row_index, row) in visible_window(self.rows, state.offset(), visible_rows) {
            // `row_index - state.offset()` is a row within the visible window, so it never
            // exceeds `visible_rows` (this surface's own `u16` height).
            #[allow(clippy::cast_possible_truncation)]
            let row_offset = (row_index - state.offset()) as u16;
            let y = 1 + row_offset;
            let (style, bg) = if Some(row_index) == selected {
                (self.selected_style, Some(self.selected_style.background()))
            } else {
                (self.row_style, None)
            };
            draw_row(
                surface,
                width,
                y,
                row,
                self.widths,
                RowStyle {
                    style,
                    bg,
                    column_spacing: self.column_spacing,
                },
            );
        }
    }

    /// The row index at `pos`, given `state`'s current scroll offset, or `None` if `pos` falls
    /// on the header row or past the last row (not clamped to the last row).
    fn index_at(
        &self,
        area: Rect,
        state: &ListState,
        pos: retroglyph_core::grid::Pos,
    ) -> Option<usize> {
        let row = pos.y.checked_sub(area.top())?.checked_sub(1)?; // row 0 is the header
        let index = state.offset() + usize::from(row);
        (index < self.rows.len()).then_some(index)
    }
}

impl StatefulWidget for Table<'_> {
    type State = ListState;

    fn render(&self, surface: &mut Surface<'_>, state: &mut Self::State) {
        self.draw(surface, state);
    }
}

impl<Id> InteractiveWidget<Id> for Table<'_> {
    type State = ListState;

    /// A single id covers the whole table: clicking resolves which row via
    /// [`Response::pointer_pos`] and this table's own row geometry, rather than each row
    /// registering its own id.
    fn sense(&self) -> Sense {
        Sense::click() | Sense::SCROLL | Sense::HOVER
    }

    fn render(&self, surface: &mut Surface<'_>, state: &mut Self::State, response: Response<Id>) {
        let area = surface.area();

        // A click past the last row (or on the header row) selects nothing: it's neither
        // clamped to the last row nor left as whatever was selected before.
        if response.clicked()
            && let Some(pos) = response.pointer_pos()
            && let Some(index) = self.index_at(area, state, pos)
        {
            state.select(Some(index));
        }
        let scroll_delta = response.scroll_delta();
        if scroll_delta != 0 {
            state.scroll_by(scroll_delta);
        }

        self.draw(surface, state);
    }
}

impl Measure for Table<'_> {
    /// One row per data row, plus the always-drawn header row; `width` is ignored, since cells
    /// are truncated per column rather than wrapped.
    fn height_for(&self, _width: u16) -> u16 {
        #[allow(clippy::cast_possible_truncation)]
        let rows = self.rows.len().min(usize::from(u16::MAX)) as u16;
        rows.saturating_add(1)
    }
}

/// The style and layout options for drawing one [`Table`] row, grouped to keep [`draw_row`]'s
/// argument count within clippy's limit.
#[derive(Clone, Copy)]
struct RowStyle {
    /// The text (and, for the selected row, background) style.
    style: Style,
    /// When set, the whole row width is filled with this background first.
    bg: Option<Color>,
    /// The number of blank columns between cells.
    column_spacing: u16,
}

/// Draw one table row of `column_spacing`-separated, per-column-clipped cells at row `y`, in
/// this surface's own local coordinates (`width` columns starting at `0`).
fn draw_row(
    surface: &mut Surface<'_>,
    width: u16,
    y: u16,
    cells: &[&str],
    widths: &[u16],
    row_style: RowStyle,
) {
    let RowStyle {
        style,
        bg,
        column_spacing,
    } = row_style;
    if let Some(bg) = bg {
        fill_rect(surface, Rect::new(0, y, width, 1), ' ', Style::new().bg(bg));
    }
    let mut x = 0u16;
    for (cell, &w) in cells.iter().zip(widths) {
        if x >= width {
            break;
        }
        let avail = (width - x).min(w);
        let _ = draw_clipped(surface, (x, y), avail, cell, Align::Left, style);
        x = x.saturating_add(w.saturating_add(column_spacing));
    }
}

#[cfg(test)]
mod tests {
    use alloc::vec;
    use alloc::vec::Vec;

    use retroglyph_core::grid::{Grid, Pos};

    use super::*;

    #[test]
    fn table_widget_highlights_the_selected_row() {
        let area = Rect::new(0, 0, 20, 3);
        let headers = ["Name"];
        let widths = [10u16];
        let rows: [&[&str]; 2] = [&["Alpha"], &["Bravo"]];
        let table = Table::new(&headers, &widths, &rows);

        let mut grid = Grid::new(20, 3);
        let mut state = ListState::new();
        state.select(Some(1));
        StatefulWidget::render(&table, &mut Surface::new(&mut grid, area, 0), &mut state);

        // Row 1 ("Bravo") is highlighted; row 0 ("Alpha") is not.
        let highlighted_bg = grid[Pos::new(0, 2)].style().background();
        let plain_bg = grid[Pos::new(0, 1)].style().background();
        assert_ne!(highlighted_bg, plain_bg);
    }

    #[test]
    fn table_widget_highlights_nothing_when_unselected() {
        let area = Rect::new(0, 0, 20, 3);
        let headers = ["Name"];
        let widths = [10u16];
        let rows: [&[&str]; 2] = [&["Alpha"], &["Bravo"]];
        let table = Table::new(&headers, &widths, &rows);

        let mut grid = Grid::new(20, 3);
        let mut state = ListState::new(); // nothing selected
        StatefulWidget::render(&table, &mut Surface::new(&mut grid, area, 0), &mut state);

        let row0_bg = grid[Pos::new(0, 1)].style().background();
        let row1_bg = grid[Pos::new(0, 2)].style().background();
        assert_eq!(row0_bg, row1_bg);
    }

    fn rows<'a>(names: &[&'a str]) -> Vec<[&'a str; 1]> {
        names.iter().map(|n| [*n]).collect()
    }

    fn row_refs<'a>(rows: &'a [[&'a str; 1]]) -> Vec<&'a [&'a str]> {
        rows.iter().map(<[&str; 1]>::as_slice).collect()
    }

    #[test]
    fn scroll_offset_renders_the_window_starting_at_offset() {
        // 2 visible rows (area height 3, minus the header row).
        let area = Rect::new(0, 0, 20, 3);
        let headers = ["Name"];
        let widths = [10u16];
        let rows = rows(&["Alpha", "Bravo", "Charlie", "Delta"]);
        let rows = row_refs(&rows);
        let table = Table::new(&headers, &widths, &rows);

        let mut grid = Grid::new(20, 3);
        let mut state = ListState::new();
        state.set_offset(2); // window is [Charlie, Delta]
        StatefulWidget::render(&table, &mut Surface::new(&mut grid, area, 0), &mut state);

        // Row 1 is "Charlie", row 2 is "Delta"; neither "Alpha" nor "Bravo"
        // (offset 0/1) are drawn anywhere.
        assert_eq!(grid[Pos::new(0, 1)].glyph(), 'C');
        assert_eq!(grid[Pos::new(0, 2)].glyph(), 'D');
    }

    #[test]
    fn selection_scrolled_out_of_view_highlights_nothing() {
        let area = Rect::new(0, 0, 20, 3);
        let headers = ["Name"];
        let widths = [10u16];
        let rows = rows(&["Alpha", "Bravo", "Charlie", "Delta"]);
        let rows = row_refs(&rows);
        let table = Table::new(&headers, &widths, &rows);

        let mut grid = Grid::new(20, 3);
        let mut state = ListState::new();
        state.select(Some(0)); // "Alpha"
        state.set_offset(2); // but the window starts at "Charlie"
        StatefulWidget::render(&table, &mut Surface::new(&mut grid, area, 0), &mut state);

        let row0_bg = grid[Pos::new(0, 1)].style().background();
        let row1_bg = grid[Pos::new(0, 2)].style().background();
        assert_eq!(row0_bg, row1_bg); // neither visible row is highlighted
    }

    #[test]
    fn height_for_is_row_count_plus_the_header_row() {
        let headers = ["Name"];
        let widths = [10u16];
        let rows = rows(&["Alpha", "Bravo", "Charlie"]);
        let rows = row_refs(&rows);
        let table = Table::new(&headers, &widths, &rows);

        assert_eq!(table.height_for(80), 4); // 3 rows + 1 header
    }

    #[test]
    fn default_header_style_matches_theme_dark() {
        let area = Rect::new(0, 0, 20, 2);
        let headers = ["Name"];
        let widths = [10u16];
        let rows: Vec<&[&str]> = vec![];
        let table = Table::new(&headers, &widths, &rows);

        let mut grid = Grid::new(20, 2);
        let mut state = ListState::new();
        StatefulWidget::render(&table, &mut Surface::new(&mut grid, area, 0), &mut state);

        assert_eq!(grid[Pos::new(0, 0)].style().foreground(), Theme::DARK.fg);
        assert_eq!(
            grid[Pos::new(0, 0)].style().background(),
            Theme::DARK.panel_bg
        );
    }

    #[test]
    fn header_style_can_be_overridden() {
        let area = Rect::new(0, 0, 20, 2);
        let headers = ["Name"];
        let widths = [10u16];
        let rows: Vec<&[&str]> = vec![];
        let custom = Style::new().fg(Color::RED);
        let table = Table::new(&headers, &widths, &rows).header_style(custom);

        let mut grid = Grid::new(20, 2);
        let mut state = ListState::new();
        StatefulWidget::render(&table, &mut Surface::new(&mut grid, area, 0), &mut state);

        assert_eq!(grid[Pos::new(0, 0)].style().foreground(), Color::RED);
    }

    #[test]
    fn selected_style_can_be_overridden() {
        let area = Rect::new(0, 0, 20, 3);
        let headers = ["Name"];
        let widths = [10u16];
        let rows: [&[&str]; 2] = [&["Alpha"], &["Bravo"]];
        let custom = Style::new().fg(Color::GREEN).bg(Color::BLUE);
        let table = Table::new(&headers, &widths, &rows).selected_style(custom);

        let mut grid = Grid::new(20, 3);
        let mut state = ListState::new();
        state.select(Some(1));
        StatefulWidget::render(&table, &mut Surface::new(&mut grid, area, 0), &mut state);

        assert_eq!(grid[Pos::new(0, 2)].style().foreground(), Color::GREEN);
        assert_eq!(grid[Pos::new(0, 2)].style().background(), Color::BLUE);
    }

    #[test]
    fn theme_maps_named_roles_onto_header_row_and_selected_styles() {
        let area = Rect::new(0, 0, 20, 3);
        let headers = ["Name"];
        let widths = [10u16];
        let rows: [&[&str]; 2] = [&["Alpha"], &["Bravo"]];
        let table = Table::new(&headers, &widths, &rows).theme(Theme::DARK);

        let mut grid = Grid::new(20, 3);
        let mut state = ListState::new();
        state.select(Some(1));
        StatefulWidget::render(&table, &mut Surface::new(&mut grid, area, 0), &mut state);

        assert_eq!(grid[Pos::new(0, 0)].style().foreground(), Theme::DARK.fg);
        assert_eq!(
            grid[Pos::new(0, 0)].style().background(),
            Theme::DARK.panel_bg
        );
        assert_eq!(grid[Pos::new(0, 1)].style().foreground(), Theme::DARK.dim);
        assert_eq!(
            grid[Pos::new(0, 1)].style().background(),
            Theme::DARK.panel_bg
        );
        assert_eq!(grid[Pos::new(0, 2)].style().foreground(), Theme::DARK.bg);
        assert_eq!(
            grid[Pos::new(0, 2)].style().background(),
            Theme::DARK.accent
        );
    }

    #[test]
    fn theme_on_uses_the_given_backdrop_instead_of_panel_bg() {
        let area = Rect::new(0, 0, 20, 2);
        let headers = ["Name"];
        let widths = [10u16];
        let rows: [&[&str]; 1] = [&["Alpha"]];
        let table = Table::new(&headers, &widths, &rows).theme_on(Theme::DARK, Color::Default);

        let mut grid = Grid::new(20, 2);
        let mut state = ListState::new();
        StatefulWidget::render(&table, &mut Surface::new(&mut grid, area, 0), &mut state);

        assert_eq!(grid[Pos::new(0, 0)].style().foreground(), Theme::DARK.fg);
        assert_eq!(grid[Pos::new(0, 0)].style().background(), Color::Default);
        assert_eq!(grid[Pos::new(0, 1)].style().foreground(), Theme::DARK.dim);
        assert_eq!(grid[Pos::new(0, 1)].style().background(), Color::Default);
    }

    #[test]
    fn column_spacing_can_be_overridden() {
        let area = Rect::new(0, 0, 20, 1);
        let headers = ["A", "B"];
        let widths = [1u16, 1u16];
        let rows: Vec<&[&str]> = vec![];
        let table = Table::new(&headers, &widths, &rows).column_spacing(3);

        let mut grid = Grid::new(20, 1);
        let mut state = ListState::new();
        StatefulWidget::render(&table, &mut Surface::new(&mut grid, area, 0), &mut state);

        // Default spacing (1) would put "B" at column 2; spacing 3 pushes
        // it out to column 4.
        assert_eq!(grid[Pos::new(0, 0)].glyph(), 'A');
        assert_eq!(grid[Pos::new(4, 0)].glyph(), 'B');
    }

    #[test]
    fn draw_row_column_width_plus_spacing_saturates_instead_of_overflowing() {
        // A column width near `u16::MAX` combined with a nonzero `column_spacing` must not
        // overflow the intermediate `w + column_spacing` addition (see issue #315); the whole
        // expression should saturate to `u16::MAX` instead of panicking (debug) or wrapping
        // (release).
        let area = Rect::new(0, 0, 20, 1);
        let cells: [&str; 2] = ["A", "B"];
        let widths = [u16::MAX - 1, 1];
        let row_style = RowStyle {
            style: Style::new(),
            bg: None,
            column_spacing: 3,
        };

        let mut grid = Grid::new(20, 1);
        draw_row(
            &mut Surface::new(&mut grid, area, 0),
            area.width(),
            0,
            &cells,
            &widths,
            row_style,
        );

        assert_eq!(grid[Pos::new(0, 0)].glyph(), 'A');
    }

    #[test]
    fn ensure_visible_before_render_keeps_selection_on_screen() {
        let area = Rect::new(0, 0, 20, 3); // 2 visible rows
        let headers = ["Name"];
        let widths = [10u16];
        let rows = rows(&["Alpha", "Bravo", "Charlie", "Delta"]);
        let rows = row_refs(&rows);
        let table = Table::new(&headers, &widths, &rows);

        let mut grid = Grid::new(20, 3);
        let mut state = ListState::new();
        state.select(Some(3)); // "Delta", off the front of the default window
        state.ensure_visible(2);
        StatefulWidget::render(&table, &mut Surface::new(&mut grid, area, 0), &mut state);

        // ensure_visible moved the window to [2, 4): "Charlie" then "Delta",
        // with "Delta" (the selection) highlighted on the last visible row.
        assert_eq!(grid[Pos::new(0, 2)].glyph(), 'D');
        let highlighted_bg = grid[Pos::new(0, 2)].style().background();
        let plain_bg = grid[Pos::new(0, 1)].style().background();
        assert_ne!(highlighted_bg, plain_bg);
    }

    #[test]
    fn click_selects_the_row_under_the_pointer() {
        let area = Rect::new(0, 0, 20, 3);
        let headers = ["Name"];
        let widths = [10u16];
        let rows = rows(&["Alpha", "Bravo"]);
        let rows = row_refs(&rows);
        let table = Table::new(&headers, &widths, &rows);
        let mut state = ListState::new();

        let response: Response<()> = Response {
            hovered: true,
            clicked: true,
            pointer_pos: Some(Pos::new(2, 2)), // row 1 of the table (below the header) -> "Bravo"
            ..Response::default()
        };
        let mut grid = Grid::new(20, 3);
        InteractiveWidget::render(
            &table,
            &mut Surface::new(&mut grid, area, 0),
            &mut state,
            response,
        );
        assert_eq!(state.selected(), Some(1));
    }

    #[test]
    fn click_selects_the_row_under_the_pointer_with_a_scroll_offset() {
        let area = Rect::new(0, 0, 20, 3); // 2 visible rows below the header
        let headers = ["Name"];
        let widths = [10u16];
        let rows = rows(&["Alpha", "Bravo", "Charlie", "Delta"]);
        let rows = row_refs(&rows);
        let table = Table::new(&headers, &widths, &rows);
        let mut state = ListState::new();
        state.set_offset(2); // window is [Charlie, Delta]

        let response: Response<()> = Response {
            hovered: true,
            clicked: true,
            pointer_pos: Some(Pos::new(2, 2)), // row 1 of the window -> "Delta" (index 3)
            ..Response::default()
        };
        let mut grid = Grid::new(20, 3);
        InteractiveWidget::render(
            &table,
            &mut Surface::new(&mut grid, area, 0),
            &mut state,
            response,
        );
        assert_eq!(state.selected(), Some(3));
    }

    #[test]
    fn click_on_the_header_row_selects_nothing() {
        let area = Rect::new(0, 0, 20, 3);
        let headers = ["Name"];
        let widths = [10u16];
        let rows = rows(&["Alpha", "Bravo"]);
        let rows = row_refs(&rows);
        let table = Table::new(&headers, &widths, &rows);
        let mut state = ListState::new();
        state.select(Some(0));

        let response: Response<()> = Response {
            hovered: true,
            clicked: true,
            pointer_pos: Some(Pos::new(2, 0)), // the header row itself
            ..Response::default()
        };
        let mut grid = Grid::new(20, 3);
        InteractiveWidget::render(
            &table,
            &mut Surface::new(&mut grid, area, 0),
            &mut state,
            response,
        );
        assert_eq!(state.selected(), Some(0)); // unchanged
    }

    #[test]
    fn wheel_scroll_moves_the_offset() {
        let area = Rect::new(0, 0, 20, 3);
        let headers = ["Name"];
        let widths = [10u16];
        let rows = rows(&["Alpha", "Bravo", "Charlie", "Delta"]);
        let rows = row_refs(&rows);
        let table = Table::new(&headers, &widths, &rows);
        let mut state = ListState::new();

        let response: Response<()> = Response {
            scroll_delta: 2,
            ..Response::default()
        };
        let mut grid = Grid::new(20, 3);
        InteractiveWidget::render(
            &table,
            &mut Surface::new(&mut grid, area, 0),
            &mut state,
            response,
        );
        assert_eq!(state.offset(), 2);
    }
}