retroglyph-ui 0.5.1

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
//! [`Tabs`]: a horizontal strip of tab labels with a highlighted selected index.
use retroglyph_core::color::{Color, Style};
use retroglyph_core::grid::{Rect, Size};
use retroglyph_core::text::width;

use super::strip::Strip;
use super::{InteractiveWidget, MinSize, Widget};
use crate::Surface;
use crate::align::Align;
use crate::draw::fill_rect;
use crate::interact::Density;
use crate::interact::Response;
use crate::interact::Sense;
use crate::text::draw_clipped;
use crate::theme::Theme;

/// A horizontal strip of `titles` with the tab at `selected` highlighted.
///
/// Unlike [`Table`](super::Table)/[`List`](super::List), `Tabs` is a plain [`Widget`], not a
/// [`StatefulWidget`](super::StatefulWidget): there is no scroll offset for a tab strip, only a
/// selected index, so it takes `selected: Option<usize>` directly (set via [`Tabs::select`])
/// rather than a [`ListState`](crate::state::ListState): the app is free to drive that index however
/// it likes (a plain `usize` it owns, a [`FocusRing`](crate::interact::FocusRing), whatever fits), the same
/// "app- or interaction-machinery-driven, widget just reads it" division of labor as every other
/// widget here.
///
/// Titles render left to right, `column_spacing` blank columns apart (default `1`, matching
/// [`Table::column_spacing`](super::Table::column_spacing)), with an optional single-character
/// `divider` (default `None`, i.e. no divider) centered in that spacing: set with
/// [`Tabs::divider`]. Drawing stops once a title would start past the area's right edge; there is
/// no horizontal scrolling.
///
/// `style` and `selected_style` default to [`Theme::DARK`] (as if [`Tabs::theme`] had been
/// called); set them with [`Tabs::style`]/[`Tabs::selected_style`].
///
/// As an [`InteractiveWidget`], `type State = usize` (the same index a caller already threads
/// into [`Tabs::select`] for the plain [`Widget`] path): a single id covers the whole strip, and
/// a click selects the tab whose column range contains [`Response::pointer_pos`], resolved
/// against the very same per-tab column layout the drawing routine uses, so the two can't
/// diverge.
///
/// # Examples
///
/// ```
/// use retroglyph_core::grid::{Grid, Rect};
/// use retroglyph_ui::widget::{Tabs, Widget};
/// use retroglyph_ui::Surface;
///
/// let titles = ["Overview", "Details", "Settings"];
/// let area = Rect::new(0, 0, 30, 1);
/// let mut grid = Grid::new(30, 1);
/// Tabs::new(&titles)
///     .select(Some(0))
///     .render(&mut Surface::new(&mut grid, area, 0));
/// ```
#[derive(Clone, Copy, Debug)]
pub struct Tabs<'a> {
    titles: &'a [&'a str],
    selected: Option<usize>,
    style: Style,
    selected_style: Style,
    column_spacing: u16,
    divider: Option<char>,
}

impl<'a> Tabs<'a> {
    /// A tab strip over `titles`, with nothing selected, styled from [`Theme::DARK`] (as if
    /// [`Tabs::theme`] had been called).
    #[must_use]
    pub fn new(titles: &'a [&'a str]) -> Self {
        Self {
            titles,
            selected: None,
            style: Style::new(),
            selected_style: Style::new(),
            column_spacing: 1,
            divider: None,
        }
        .theme(Theme::DARK)
    }

    /// Select tab `index` (or clear the selection with `None`).
    #[must_use]
    pub const fn select(mut self, index: Option<usize>) -> Self {
        self.selected = index;
        self
    }

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

    /// Set the style of the selected tab, 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 tabs.
    #[must_use]
    pub const fn column_spacing(mut self, spacing: u16) -> Self {
        self.column_spacing = spacing;
        self
    }

    /// Set a divider character drawn within the spacing between tabs. `None` (the default) draws
    /// no divider: just `column_spacing` blank columns.
    #[must_use]
    pub const fn divider(mut self, divider: Option<char>) -> Self {
        self.divider = divider;
        self
    }

    /// Applies `theme`'s named roles to this tab strip: `style` becomes `theme.dim` (unselected
    /// tabs read as de-emphasized) on `theme.panel_bg`, and `selected_style` becomes `theme.bg`
    /// on `theme.accent`: the same bright-on-accent highlight [`super::List::theme`] and
    /// [`super::Table::theme`] give their own selected state.
    ///
    /// `style` sets an explicit background rather than leaving it at [`Style::new()`]'s default:
    /// an unset background isn't "transparent" once a real backend draws it (a bare
    /// `Color::Default` cell paints as solid black behind the glyph; see
    /// `retroglyph-software`'s `DEFAULT_BG`), so this widget assumes it's drawn on
    /// `theme.panel_bg`, true when composed with a themed [`super::Panel`]/[`super::Modal`].
    /// Drawing this tab strip directly on the raw screen background instead needs a manual
    /// `.style(...)` override afterwards.
    ///
    /// Call before any manual [`Tabs::style`]/[`Tabs::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 [`Tabs::theme`], but `style` is drawn on `bg` instead of `theme.panel_bg`: for a
    /// tab strip drawn directly on a backdrop other than a themed [`super::Panel`]/
    /// [`super::Modal`]'s fill. `selected_style` still uses `theme.accent` as its background,
    /// unaffected by `bg`. [`Tabs::theme`] is exactly `theme_on(theme, theme.panel_bg)`.
    #[must_use]
    pub fn theme_on(mut self, theme: Theme, bg: Color) -> Self {
        self.style = Style::new().fg(theme.dim).bg(bg);
        self.selected_style = Style::new().fg(theme.bg).bg(theme.accent);
        self
    }
}

impl Tabs<'_> {
    /// The shared drawing routine both [`Widget::render`] and [`InteractiveWidget::render`] use,
    /// parameterized on which tab (if any) is highlighted as selected.
    fn draw(&self, surface: &mut Surface<'_>, selected: Option<usize>) {
        let area = surface.area();
        if area.width() == 0 || area.height() == 0 {
            return;
        }

        // `Strip::columns` reports absolute `x`, matching `area`'s own space (needed so
        // `Strip::index_at` can compare it directly against an absolute pointer position); `put`/
        // `print`/`fill_rect` below address this surface's own local coordinates instead, so
        // `area.left()` is subtracted back out at the point of drawing.
        let strip = Strip::new(self.titles, self.column_spacing);
        for (index, abs_x, text_width) in strip.columns(area) {
            let x = abs_x - area.left();
            let title = self.titles[index];
            let style = if Some(index) == selected {
                self.selected_style
            } else {
                self.style
            };
            if Some(index) == selected && text_width > 0 {
                fill_rect(
                    surface,
                    Rect::new(x, 0, text_width, 1),
                    ' ',
                    Style::new().bg(style.background()),
                );
            }
            let _ = draw_clipped(surface, (x, 0), text_width, title, Align::Left, style);

            if let Some(divider) = self.divider
                && index + 1 < self.titles.len()
            {
                // Divider column: floor of half the inter-tab gap, so it sits just left of center
                // for an even `column_spacing`.
                let mid = x + text_width + self.column_spacing / 2;
                if mid < area.width() {
                    surface.put((mid, 0), divider, Style::new());
                }
            }
        }
    }

    /// The index of the tab whose column range contains `pos`, or `None` if `pos` falls in the
    /// spacing between tabs, past the last drawn tab, or outside `area` entirely: a click there
    /// selects nothing rather than clamping to the nearest tab.
    fn tab_at(&self, area: Rect, pos: retroglyph_core::grid::Pos) -> Option<usize> {
        Strip::new(self.titles, self.column_spacing).index_at(area, pos)
    }
}

impl MinSize for Tabs<'_> {
    /// Every title's display width, `column_spacing` columns apart, one row tall, floored at
    /// `density`'s [`min_target_size`](Density::min_target_size) the same way [`Button`](super::Button)
    /// floors its own label: unlike the drawing routine, this ignores any drawing-time
    /// truncation, since `min_size` answers how much room the strip needs, not how it degrades
    /// when denied that room.
    fn min_size(&self, density: Density) -> Size {
        let mut content_width = 0u16;
        for (index, &title) in self.titles.iter().enumerate() {
            content_width = content_width.saturating_add(width(title));
            if index + 1 < self.titles.len() {
                content_width = content_width.saturating_add(self.column_spacing);
            }
        }
        Size::new(content_width, 1).max(density.min_target_size())
    }
}

impl Widget for Tabs<'_> {
    fn render(&self, surface: &mut Surface<'_>) {
        self.draw(surface, self.selected);
    }
}

impl<Id> InteractiveWidget<Id> for Tabs<'_> {
    type State = usize;

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

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

        if response.clicked()
            && let Some(pos) = response.pointer_pos()
            && let Some(index) = self.tab_at(area, pos)
        {
            *state = index;
        }

        self.draw(surface, Some(*state));
    }
}

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

    use retroglyph_core::grid::{Grid, HasSize as _, Pos};

    use super::*;

    #[test]
    fn draws_every_title_left_to_right() {
        let area = Rect::new(0, 0, 20, 1);
        let titles = ["One", "Two"];
        let mut grid = Grid::new(20, 1);
        let tabs = Tabs::new(&titles);
        Widget::render(&tabs, &mut Surface::new(&mut grid, area, 0));

        assert_eq!(grid[Pos::new(0, 0)].glyph(), 'O');
        // "One" (3) + column_spacing (1) = tab 2 starts at column 4.
        assert_eq!(grid[Pos::new(4, 0)].glyph(), 'T');
    }

    #[test]
    fn highlights_the_selected_tab() {
        let area = Rect::new(0, 0, 20, 1);
        let titles = ["One", "Two"];
        let mut grid = Grid::new(20, 1);
        let tabs = Tabs::new(&titles).select(Some(1));
        Widget::render(&tabs, &mut Surface::new(&mut grid, area, 0));

        // Themed tabs (the `new()` default) distinguish the selected tab by both foreground and
        // background color: `theme.bg` on `theme.accent` vs `theme.dim` on `theme.panel_bg`.
        let selected_style = grid[Pos::new(4, 0)].style();
        let unselected_style = grid[Pos::new(0, 0)].style();
        assert_ne!(selected_style.foreground(), unselected_style.foreground());
        assert_ne!(selected_style.background(), unselected_style.background());
    }

    #[test]
    fn nothing_highlighted_when_unselected() {
        let area = Rect::new(0, 0, 20, 1);
        let titles = ["One", "Two"];
        let mut grid = Grid::new(20, 1);
        let tabs = Tabs::new(&titles);
        Widget::render(&tabs, &mut Surface::new(&mut grid, area, 0));

        // With nothing selected, both tabs use the same unselected `style`, so their backgrounds
        // match (unlike a selected tab, which gets `theme.accent` instead).
        let bg0 = grid[Pos::new(0, 0)].style().background();
        let bg1 = grid[Pos::new(4, 0)].style().background();
        assert_eq!(bg0, bg1);
    }

    #[test]
    fn column_spacing_can_be_overridden() {
        let area = Rect::new(0, 0, 20, 1);
        let titles = ["A", "B"];
        let mut grid = Grid::new(20, 1);
        let tabs = Tabs::new(&titles).column_spacing(3);
        Widget::render(&tabs, &mut Surface::new(&mut grid, area, 0));

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

    #[test]
    fn divider_renders_between_tabs_when_set() {
        let area = Rect::new(0, 0, 20, 1);
        let titles = ["A", "B"];
        let mut grid = Grid::new(20, 1);
        let tabs = Tabs::new(&titles).column_spacing(3).divider(Some('|'));
        Widget::render(&tabs, &mut Surface::new(&mut grid, area, 0));

        // "A" at 0, spacing [1,3), midpoint at 1 + 3/2 = 2.
        assert_eq!(grid[Pos::new(2, 0)].glyph(), '|');
    }

    #[test]
    fn no_divider_by_default() {
        let area = Rect::new(0, 0, 20, 1);
        let titles = ["A", "B"];
        let mut grid = Grid::new(20, 1);
        let tabs = Tabs::new(&titles);
        Widget::render(&tabs, &mut Surface::new(&mut grid, area, 0));

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

    #[test]
    fn stops_drawing_past_the_area_width_without_panicking() {
        let area = Rect::new(0, 0, 4, 1);
        let titles = ["Alpha", "Bravo", "Charlie"];
        let mut grid = Grid::new(4, 1);
        let tabs = Tabs::new(&titles);
        Widget::render(&tabs, &mut Surface::new(&mut grid, area, 0)); // must not panic

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

    #[test]
    fn style_can_be_overridden() {
        use retroglyph_core::color::Color;

        let area = Rect::new(0, 0, 20, 1);
        let titles = ["One"];
        let custom = Style::new().fg(Color::RED);
        let mut grid = Grid::new(20, 1);
        let tabs = Tabs::new(&titles).style(custom);
        Widget::render(&tabs, &mut Surface::new(&mut grid, area, 0));

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

    #[test]
    fn selected_style_can_be_overridden() {
        use retroglyph_core::color::Color;

        let area = Rect::new(0, 0, 20, 1);
        let titles = ["One"];
        let custom = Style::new().fg(Color::GREEN).bg(Color::BLUE);
        let mut grid = Grid::new(20, 1);
        let tabs = Tabs::new(&titles).selected_style(custom).select(Some(0));
        Widget::render(&tabs, &mut Surface::new(&mut grid, area, 0));

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

    #[test]
    fn zero_width_is_a_no_op() {
        let area = Rect::new(0, 0, 0, 1);
        let titles = ["One"];
        let mut grid = Grid::new(1, 1);
        let tabs = Tabs::new(&titles);
        Widget::render(&tabs, &mut Surface::new(&mut grid, area, 0));
        assert_eq!(grid[Pos::new(0, 0)].glyph(), ' ');
    }

    #[test]
    fn theme_maps_named_roles_onto_style_and_selected_style() {
        let area = Rect::new(0, 0, 20, 1);
        let titles = ["One", "Two"];
        let mut grid = Grid::new(20, 1);
        let tabs = Tabs::new(&titles).theme(Theme::DARK).select(Some(1));
        Widget::render(&tabs, &mut Surface::new(&mut grid, area, 0));

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

    #[test]
    fn theme_on_uses_the_given_backdrop_instead_of_panel_bg() {
        use retroglyph_core::color::Color;

        let area = Rect::new(0, 0, 20, 1);
        let titles = ["One"];
        let mut grid = Grid::new(20, 1);
        let tabs = Tabs::new(&titles)
            .theme_on(Theme::DARK, Color::Default)
            .select(Some(0));
        Widget::render(&tabs, &mut Surface::new(&mut grid, area, 0));

        // `selected_style` uses `theme.accent` as its background regardless of `bg`: only the
        // unselected `style` picks up the custom backdrop.
        assert_eq!(grid[Pos::new(0, 0)].style().foreground(), Theme::DARK.bg);
        assert_eq!(
            grid[Pos::new(0, 0)].style().background(),
            Theme::DARK.accent
        );
    }

    #[test]
    fn click_selects_the_tab_under_the_pointer() {
        let area = Rect::new(0, 0, 20, 1);
        let titles = ["One", "Two"];
        let tabs = Tabs::new(&titles);
        let mut state = 0usize;

        let response: Response<()> = Response {
            hovered: true,
            clicked: true,
            pointer_pos: Some(Pos::new(4, 0)), // over "Two"
            ..Response::default()
        };
        let mut grid = Grid::new(20, 1);
        InteractiveWidget::render(
            &tabs,
            &mut Surface::new(&mut grid, area, 0),
            &mut state,
            response,
        );
        assert_eq!(state, 1);
    }

    #[test]
    fn click_past_the_last_tab_selects_nothing() {
        let area = Rect::new(0, 0, 20, 1);
        let titles = ["One", "Two"];
        let tabs = Tabs::new(&titles);
        let mut state = 0usize;

        let response: Response<()> = Response {
            hovered: true,
            clicked: true,
            pointer_pos: Some(Pos::new(10, 0)), // past "Two", still inside the wide area
            ..Response::default()
        };
        let mut grid = Grid::new(20, 1);
        InteractiveWidget::render(
            &tabs,
            &mut Surface::new(&mut grid, area, 0),
            &mut state,
            response,
        );
        assert_eq!(state, 0); // unchanged: not clamped to the last tab
    }

    #[test]
    fn tabs_wide_title_loses_half_its_characters() {
        let area = Rect::new(0, 0, 20, 1);
        let titles = ["設定", "次"];
        let mut grid = Grid::new(20, 1);
        let tabs = Tabs::new(&titles);
        Widget::render(&tabs, &mut Surface::new(&mut grid, area, 0));

        // "設定" is 4 columns wide; both characters must draw in full.
        assert_eq!(grid[Pos::new(0, 0)].glyph(), '設');
        assert_eq!(grid[Pos::new(2, 0)].glyph(), '定');
        // "次" (2 cols) starts after "設定" (4) + column_spacing (1) = column 5.
        assert_eq!(grid[Pos::new(5, 0)].glyph(), '次');
    }

    #[test]
    fn tabs_wide_title_does_not_overlap_the_next_tab() {
        let area = Rect::new(0, 0, 20, 1);
        let titles = ["設定", "次"];
        let tabs = Tabs::new(&titles);
        let columns: Vec<_> = Strip::new(&titles, tabs.column_spacing)
            .columns(area)
            .collect();

        // "設定" occupies 4 columns starting at 0; "次" must start no earlier than column 5
        // (4 + column_spacing 1), never inside "設定"'s own span.
        assert_eq!(columns[0], (0, 0, 4));
        assert_eq!(columns[1].1, 5);
    }

    #[test]
    fn min_size_sums_title_widths_and_spacing() {
        // "One" (3) + spacing (1) + "Two" (3) = 7 cols, past either density's 6-cell floor, and
        // a mouse density's 1-row floor doesn't grow the height, so the natural width wins.
        let titles = ["One", "Two"];
        let size = Tabs::new(&titles).min_size(Density::Mouse);
        assert_eq!(size.width(), 7);
        assert_eq!(size.height(), 1);
    }

    #[test]
    fn min_size_floors_a_narrow_strip_at_the_density_minimum() {
        // A single 1-col title is nowhere near either density's 6-cell width floor.
        let titles = ["A"];
        let size = Tabs::new(&titles).min_size(Density::Touch);
        assert_eq!(size, Density::Touch.min_target_size());
    }

    #[test]
    fn min_size_respects_custom_column_spacing() {
        // "A" (1) + spacing (3) + "B" (1) = 5 cols, still under the 6-cell floor, so the floor
        // wins; this only proves the spacing was actually added into the sum before flooring.
        let titles = ["A", "B"];
        let size = Tabs::new(&titles)
            .column_spacing(3)
            .min_size(Density::Mouse);
        assert_eq!(size.width(), 6);
    }
}