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
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
//! [`Panel`]: a bordered, titled panel.
use alloc::vec::Vec;

use retroglyph_core::color::{Color, Style};
use retroglyph_core::grid::Rect;
use retroglyph_core::text::truncate_measured;

use super::{BorderType, BoxBorder, Measure, Widget};
use crate::Surface;
use crate::align::Align;
use crate::draw::fill_rect;
use crate::style::Sides;
use crate::text::draw_clipped;
use crate::theme::Theme;

/// Which border edge a [`PanelTitle`] is drawn into.
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)]
#[non_exhaustive]
pub enum TitlePosition {
    /// The top border row, the same edge [`Panel::title`]'s sugar title is drawn into.
    #[default]
    Top,
    /// The bottom border row.
    Bottom,
}

/// One title added via [`Panel::add_title`]: its text, which edge it's drawn on, and its
/// alignment.
///
/// Not constructed directly; built up through [`Panel::add_title`]'s arguments instead, the same
/// as [`Panel::title`]/[`Panel::title_align`] build the single implicit top title.
#[derive(Clone, Copy, Debug)]
pub struct PanelTitle<'a> {
    text: &'a str,
    position: TitlePosition,
    align: Align,
}

impl<'a> PanelTitle<'a> {
    /// Build a title for [`Modal::titles`](super::Modal::titles), the [`Modal`](super::Modal)
    /// equivalent of a [`Panel::add_title`] call. `Panel` itself never needs this constructor
    /// directly: [`Panel::add_title`] builds one from its own arguments.
    #[must_use]
    pub const fn new(text: &'a str, position: TitlePosition, align: Align) -> Self {
        Self {
            text,
            position,
            align,
        }
    }

    /// This title's fields, for [`Modal::render`](super::Modal::render) to feed into
    /// [`Panel::add_title`] without exposing them as public fields.
    pub(super) const fn parts(self) -> (&'a str, TitlePosition, Align) {
        (self.text, self.position, self.align)
    }
}

/// The style/layout fields [`Panel`] and [`Modal`](super::Modal) both carry: title text and
/// alignment, border/fill style, border glyph set, and padding. Split out so the two widgets'
/// builder methods, theming, and defaults live once instead of twice; `Panel` additionally holds
/// a `titles: Vec<PanelTitle>` that has no `Modal` equivalent, which is why this doesn't just
/// become `Panel` itself (that, plus keeping `Modal` [`Copy`] -- see its own doc comment).
#[derive(Clone, Copy, Debug, Default)]
pub(super) struct PanelChrome<'a> {
    title: Option<&'a str>,
    title_align: Align,
    border_style: Style,
    fill_style: Style,
    border_type: BorderType,
    padding: Sides,
}

impl<'a> PanelChrome<'a> {
    pub(super) const fn title(mut self, title: &'a str) -> Self {
        self.title = Some(title);
        self
    }

    pub(super) const fn title_align(mut self, align: Align) -> Self {
        self.title_align = align;
        self
    }

    pub(super) const fn border_style(mut self, style: Style) -> Self {
        self.border_style = style;
        self
    }

    pub(super) const fn fill_style(mut self, style: Style) -> Self {
        self.fill_style = style;
        self
    }

    pub(super) const fn border_type(mut self, border_type: BorderType) -> Self {
        self.border_type = border_type;
        self
    }

    pub(super) const fn padding(mut self, padding: Sides) -> Self {
        self.padding = padding;
        self
    }

    /// See [`Panel::theme`]/[`Modal::theme`](super::Modal::theme): both are exactly this call.
    pub(super) fn theme(self, theme: Theme) -> Self {
        self.theme_on(theme, theme.panel_bg)
    }

    /// See [`Panel::theme_on`]/[`Modal::theme_on`](super::Modal::theme_on): both are exactly this
    /// call.
    pub(super) fn theme_on(mut self, theme: Theme, bg: Color) -> Self {
        self.border_style = Style::new().fg(theme.border).bg(theme.title_bg);
        self.fill_style = Style::new().bg(bg);
        self
    }
}

/// A bordered panel: a filled background with a box border and, optionally, one or more titles
/// along the top and/or bottom edge.
///
/// `border_style` (the box outline and titles) and `fill_style` (the
/// interior background) both default to [`Theme::DARK`] (as if [`Panel::theme`] had been called);
/// there is no title by default, and the title set by [`Panel::title`] (if any) defaults to
/// [`Align::Center`]. Set whichever of these a caller needs via
/// [`Panel::border_style`]/[`Panel::fill_style`]/[`Panel::title`]/[`Panel::title_align`].
///
/// [`Panel::title`] is sugar for the common case: one top, centered (by default) title. For
/// anything past that (a bottom title, more than one title on an edge, or a title aligned other
/// than via `title_align`), use [`Panel::add_title`], which is fully additive: it never disturbs
/// `title`/`title_align`, and multiple `add_title` calls stack rather than overwrite each other.
///
/// `Panel` draws in place into a [`Surface`] the caller already owns and has no concept of
/// margin. For a standalone box rendered into its own `Grid` -- composed outside a frame, laid
/// out with `join_h`/`join_v`, or needing margin (space outside the border) -- see
/// [`BoxStyle`](crate::style::BoxStyle) instead.
///
/// # Examples
///
/// ```
/// use retroglyph_core::grid::{Grid, Rect};
/// use retroglyph_ui::align::Align;
/// use retroglyph_ui::widget::{Panel, TitlePosition, Widget};
/// use retroglyph_ui::Surface;
///
/// let area = Rect::new(0, 0, 20, 5);
/// let mut grid = Grid::new(20, 5);
/// Panel::new()
///     .title("Status")
///     .add_title("3 / 10", TitlePosition::Bottom, Align::Right)
///     .render(&mut Surface::new(&mut grid, area, 0));
/// ```
///
/// Not [`Copy`] (unlike most other widgets here): [`Panel::add_title`] stores its titles in a
/// `Vec`, so an unbounded number of them is exactly as cheap, and as fallible in the same ways
/// (only an allocation failure, never a silently dropped title), as pushing onto any other `Vec`.
#[derive(Clone, Debug, Default)]
pub struct Panel<'a> {
    chrome: PanelChrome<'a>,
    titles: Vec<PanelTitle<'a>>,
}

impl<'a> Panel<'a> {
    /// A plain, untitled panel, styled from [`Theme::DARK`] (as if [`Panel::theme`] had been
    /// called).
    #[must_use]
    pub fn new() -> Self {
        Self {
            chrome: PanelChrome::default().title_align(Align::Center),
            titles: Vec::new(),
        }
        .theme(Theme::DARK)
    }

    /// Builds a [`Panel`] from chrome already assembled by [`Modal`](super::Modal), with no
    /// titles beyond whatever `chrome.title` (if any) draws through [`Panel::render`].
    pub(super) const fn from_chrome(chrome: PanelChrome<'a>) -> Self {
        Self {
            chrome,
            titles: Vec::new(),
        }
    }

    /// Set the panel's title.
    #[must_use]
    pub const fn title(mut self, title: &'a str) -> Self {
        self.chrome = self.chrome.title(title);
        self
    }

    /// Set how the title is aligned along the top border. Defaults to
    /// [`Align::Center`].
    #[must_use]
    pub const fn title_align(mut self, align: Align) -> Self {
        self.chrome = self.chrome.title_align(align);
        self
    }

    /// Add a title to `position`'s edge, aligned per `align`. Additive and independent of
    /// [`Panel::title`] and of every other `add_title` call: nothing here overwrites another
    /// title, so a top-left title plus a top-right status, or a top title plus a bottom hint
    /// bar, is two calls (or three, alongside `.title(...)`) rather than two overlapping
    /// `Panel`s.
    ///
    /// Multiple titles are allowed on the same edge. Each is drawn in declaration order:
    /// `.title(...)`'s implicit top title first (if set), then `add_title` calls in the order
    /// they were made, truncated to whatever room is left on that title's edge after the
    /// titles declared before it on the same edge have claimed theirs, the same way a single
    /// title already truncates to fit the whole edge. A title that has no room left once earlier
    /// titles on its edge are placed is clipped down to nothing rather than overdrawing them or
    /// panicking. Because a [`Align::Center`] title claims its edge's entire remaining span, a
    /// title declared after a centered one on the same edge always has no room left; put
    /// non-centered titles first if a centered one needs to share an edge.
    ///
    /// Unbounded: every call is kept (this is what makes [`Panel`] not [`Copy`]; see its own doc
    /// comment), there is no cap to silently drop past.
    #[must_use]
    pub fn add_title(mut self, title: &'a str, position: TitlePosition, align: Align) -> Self {
        self.titles.push(PanelTitle {
            text: title,
            position,
            align,
        });
        self
    }

    /// Set the box outline and title's style.
    #[must_use]
    pub const fn border_style(mut self, style: Style) -> Self {
        self.chrome = self.chrome.border_style(style);
        self
    }

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

    /// Set which box-drawing glyphs the border is drawn with. Defaults to
    /// [`BorderType::Plain`], the same as [`BoxBorder::border_type`].
    #[must_use]
    pub const fn border_type(mut self, border_type: BorderType) -> Self {
        self.chrome = self.chrome.border_type(border_type);
        self
    }

    /// Reserve `padding` between the border and the rect [`Panel::inner`] returns.
    ///
    /// Padding is not painted specially: [`Panel::render`] still fills the whole area inside the
    /// border with `fill_style` (padding cells included), the same as [`Panel::inner`]'s caller
    /// would see if they filled `area` themselves before drawing into the smaller inner rect.
    /// Defaults to [`Sides::ZERO`] (no padding beyond the 1-cell border).
    #[must_use]
    pub const fn padding(mut self, padding: Sides) -> Self {
        self.chrome = self.chrome.padding(padding);
        self
    }

    /// The content rect inside `area`'s border and padding, ready to hand to another widget.
    ///
    /// Derived from the same 1-cell border inset [`Panel::render`] uses plus this panel's
    /// [`Panel::padding`], so the two can't drift. Saturates to a zero-sized rect (at `area`'s
    /// origin) rather than underflowing when `area` is too small to hold the border and padding.
    ///
    /// # Examples
    ///
    /// ```
    /// use retroglyph_core::grid::Rect;
    /// use retroglyph_ui::style::Sides;
    /// use retroglyph_ui::widget::Panel;
    ///
    /// let panel = Panel::new().padding(Sides::symmetric(0, 1));
    /// let area = Rect::new(0, 0, 20, 5);
    /// assert_eq!(panel.inner(area), Rect::new(2, 1, 16, 3));
    /// ```
    #[must_use]
    pub const fn inner(&self, area: Rect) -> Rect {
        let padding = self.chrome.padding;
        let left = 1 + padding.left;
        let top = 1 + padding.top;
        let horizontal = 2 + padding.left + padding.right;
        let vertical = 2 + padding.top + padding.bottom;
        Rect::new(
            area.left().saturating_add(left),
            area.top().saturating_add(top),
            area.width().saturating_sub(horizontal),
            area.height().saturating_sub(vertical),
        )
    }

    /// Applies `theme`'s named roles to this panel's border and fill: `border_style` becomes
    /// `theme.border` on `theme.title_bg` (the same background the title, if any, is drawn on),
    /// and `fill_style` becomes `theme.panel_bg`.
    ///
    /// Like every other builder method here, whichever call comes last wins: call `.theme(...)`
    /// before any manual [`Panel::border_style`]/[`Panel::fill_style`] override you want to keep.
    #[must_use]
    pub fn theme(mut self, theme: Theme) -> Self {
        self.chrome = self.chrome.theme(theme);
        self
    }

    /// Same as [`Panel::theme`], but `fill_style` is drawn on `bg` instead of `theme.panel_bg` --
    /// for a panel whose interior should read as a different surface than `theme.panel_bg`
    /// (`border_style` still uses `theme.title_bg`, unaffected by `bg`). [`Panel::theme`] is
    /// exactly `theme_on(theme, theme.panel_bg)`.
    #[must_use]
    pub fn theme_on(mut self, theme: Theme, bg: Color) -> Self {
        self.chrome = self.chrome.theme_on(theme, bg);
        self
    }
}

impl Measure for Panel<'_> {
    /// The 1-cell border on each edge plus this panel's [`Panel::padding`] (the height a
    /// zero-height inner content area would need), matching [`Panel::inner`]'s own vertical inset.
    /// Every title (the one set by [`Panel::title`], and any added by [`Panel::add_title`],
    /// whichever edge it's on) is drawn into its border row rather than adding one of its own, so
    /// none of them add to this count. `width` is unused: `Panel` never wraps content of its own,
    /// only whatever a caller renders into [`Panel::inner`], so it has nothing to measure against
    /// `width` yet.
    fn height_for(&self, _width: u16) -> u16 {
        2u16.saturating_add(self.chrome.padding.top)
            .saturating_add(self.chrome.padding.bottom)
    }
}

impl Widget for Panel<'_> {
    fn render(&self, surface: &mut Surface<'_>) {
        let (width, height) = (surface.width(), surface.height());
        if width < 2 || height < 2 {
            return;
        }

        // Fill interior (inside the border), in this surface's own local coordinates.
        let inner = Rect::new(1, 1, width.saturating_sub(2), height.saturating_sub(2));
        fill_rect(surface, inner, ' ', self.chrome.fill_style);

        BoxBorder::new()
            .style(self.chrome.border_style)
            .border_type(self.chrome.border_type)
            .render(surface);

        // Top edge: `.title(...)`'s implicit title (if any) claims space first, then any
        // `add_title(..., TitlePosition::Top, ...)` titles in declaration order.
        let mut top = TitleCursor::new(width);
        if let Some(t) = self.chrome.title {
            top.draw(
                surface,
                0,
                t,
                self.chrome.title_align,
                self.chrome.border_style,
            );
        }
        for title in &self.titles {
            if title.position == TitlePosition::Top {
                top.draw(
                    surface,
                    0,
                    title.text,
                    title.align,
                    self.chrome.border_style,
                );
            }
        }

        // Bottom edge: `add_title(..., TitlePosition::Bottom, ...)` titles in declaration order.
        // `height >= 2` (checked above) means `height - 1 >= 1`, always a different row than the
        // top edge's row `0`.
        let mut bottom = TitleCursor::new(width);
        for title in &self.titles {
            if title.position == TitlePosition::Bottom {
                bottom.draw(
                    surface,
                    height - 1,
                    title.text,
                    title.align,
                    self.chrome.border_style,
                );
            }
        }
    }
}

/// Tracks how much of one border edge's span (the columns strictly between its two corners) is
/// still free while [`Panel::render`] draws that edge's titles in declaration order, so a title
/// that would overlap an earlier one on the same edge is truncated down to whatever room is left
/// instead of overdrawing it.
struct TitleCursor {
    /// Leftmost free column (inclusive).
    lo: u16,
    /// Rightmost free column (exclusive).
    hi: u16,
}

impl TitleCursor {
    /// A cursor over the whole span between `width`'s two corners: columns `1..width - 1`.
    const fn new(width: u16) -> Self {
        Self {
            lo: 1,
            hi: width.saturating_sub(1),
        }
    }

    /// Draw one title into whatever of this cursor's span is still free, then shrink the span so
    /// a later call on the same edge doesn't overdraw it. Mirrors the truncate-then-pad sequence
    /// a single top title always used: [`truncate_measured`] up front (the padding spaces flank
    /// the title, so their position depends on the truncated title's own width, not the other
    /// way around) then a leading/trailing space either side of it.
    ///
    /// A title with no room left (`lo >= hi`, or fewer than 2 free columns, not even enough for
    /// the two padding spaces) is dropped entirely, drawing nothing, rather than panicking.
    /// [`Align::Center`] claims this cursor's whole remaining span regardless of how much of it
    /// the title itself actually used, so a title declared after a centered one on the same edge
    /// always finds `lo >= hi` and is dropped.
    fn draw(&mut self, surface: &mut Surface<'_>, y: u16, text: &str, align: Align, style: Style) {
        if self.lo >= self.hi {
            return;
        }
        let avail = self.hi - self.lo;
        let Some(max_title_w) = avail.checked_sub(2) else {
            return;
        };
        let (t, t_w) = truncate_measured(text, max_title_w);
        let padded = t_w + 2;
        let title_x = self.lo + align.offset(avail, padded);
        surface.put((title_x, y), ' ', style);
        let _ = draw_clipped(surface, (title_x + 1, y), t_w, t, Align::Left, style);
        surface.put((title_x + 1 + t_w, y), ' ', style);

        match align {
            Align::Left => self.lo = title_x + padded,
            Align::Right => self.hi = title_x,
            // `Align::Center`, and any future variant, centers by collapsing the title span.
            _ => self.hi = self.lo,
        }
    }
}

#[cfg(test)]
mod tests {
    use alloc::string::String;

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

    use super::*;

    #[test]
    fn draws_border_fill_and_title() {
        let area = Rect::new(0, 0, 10, 4);
        let border = Style::new().fg(Color::WHITE);
        let fill = Style::new();

        let mut grid = Grid::new(10, 4);
        Panel::new()
            .border_style(border)
            .fill_style(fill)
            .title("hi")
            .render(&mut Surface::new(&mut grid, area, 0));

        assert_eq!(grid[Pos::new(0, 0)].glyph(), '┌');
        assert_eq!(grid[Pos::new(1, 1)].glyph(), ' '); // interior filled
        // Title centred in the top border somewhere.
        let top_row: String = (0..10).map(|x| grid[Pos::new(x, 0)].glyph()).collect();
        assert!(top_row.contains("hi"));
    }

    #[test]
    fn long_title_is_truncated_to_fit() {
        let area = Rect::new(0, 0, 8, 3); // max_title_w = 8 - 4 = 4
        let mut grid = Grid::new(8, 3);
        Panel::new()
            .title("a very long title")
            .render(&mut Surface::new(&mut grid, area, 0));

        let top_row: String = (0..8).map(|x| grid[Pos::new(x, 0)].glyph()).collect();
        assert!(!top_row.contains("a very long title"));
    }

    #[test]
    fn theme_maps_named_roles_onto_border_and_fill() {
        let area = Rect::new(0, 0, 10, 4);
        let mut grid = Grid::new(10, 4);
        Panel::new()
            .theme(Theme::DARK)
            .render(&mut Surface::new(&mut grid, area, 0));

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

    #[test]
    fn theme_on_uses_the_given_backdrop_instead_of_panel_bg() {
        let area = Rect::new(0, 0, 10, 4);
        let mut grid = Grid::new(10, 4);
        Panel::new()
            .theme_on(Theme::DARK, Color::Default)
            .render(&mut Surface::new(&mut grid, area, 0));

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

    #[test]
    fn left_aligned_title_starts_after_the_corner() {
        let area = Rect::new(0, 0, 12, 3);
        let mut grid = Grid::new(12, 3);
        Panel::new()
            .title("hi")
            .title_align(Align::Left)
            .render(&mut Surface::new(&mut grid, area, 0));

        // Padded title " hi " starts at column 1 (just inside the corner):
        // space at 1, text at 2..4, trailing space at 4.
        assert_eq!(grid[Pos::new(1, 0)].glyph(), ' ');
        assert_eq!(grid[Pos::new(2, 0)].glyph(), 'h');
        assert_eq!(grid[Pos::new(3, 0)].glyph(), 'i');
    }

    #[test]
    fn right_aligned_title_ends_before_the_corner() {
        let area = Rect::new(0, 0, 12, 3);
        let mut grid = Grid::new(12, 3);
        Panel::new()
            .title("hi")
            .title_align(Align::Right)
            .render(&mut Surface::new(&mut grid, area, 0));

        // Padded title " hi " (4 cols) ends against the right corner at
        // column 11: trailing space at 10, text at 8..10.
        assert_eq!(grid[Pos::new(8, 0)].glyph(), 'h');
        assert_eq!(grid[Pos::new(9, 0)].glyph(), 'i');
        assert_eq!(grid[Pos::new(10, 0)].glyph(), ' ');
    }

    #[test]
    fn height_for_is_the_border_plus_padding() {
        assert_eq!(Panel::new().height_for(80), 2);
        let padded = Panel::new().padding(Sides::symmetric(1, 0));
        assert_eq!(padded.height_for(80), 4); // 2 border + 1 top + 1 bottom
    }

    #[test]
    fn inner_insets_by_the_one_cell_border() {
        let area = Rect::new(0, 0, 20, 5);
        assert_eq!(Panel::new().inner(area), Rect::new(1, 1, 18, 3));
    }

    #[test]
    fn inner_also_insets_by_padding() {
        let area = Rect::new(0, 0, 20, 5);
        let panel = Panel::new().padding(Sides::symmetric(0, 1));
        assert_eq!(panel.inner(area), Rect::new(2, 1, 16, 3));
    }

    #[test]
    fn inner_saturates_instead_of_underflowing_when_area_is_too_small() {
        let area = Rect::new(3, 4, 1, 1);
        let panel = Panel::new().padding(Sides::all(2));
        assert_eq!(panel.inner(area), Rect::new(6, 7, 0, 0));
    }

    #[test]
    fn too_small_is_a_no_op() {
        let area = Rect::new(0, 0, 1, 1);
        let mut grid = Grid::new(1, 1);
        Panel::new().render(&mut Surface::new(&mut grid, area, 0));
        assert_eq!(grid[Pos::new(0, 0)].glyph(), ' ');
    }

    #[test]
    fn border_type_selects_the_glyph_set() {
        let area = Rect::new(0, 0, 10, 4);
        let mut grid = Grid::new(10, 4);
        Panel::new()
            .border_type(BorderType::Double)
            .render(&mut Surface::new(&mut grid, area, 0));

        assert_eq!(grid[Pos::new(0, 0)].glyph(), '╔');
        assert_eq!(grid[Pos::new(9, 0)].glyph(), '╗');
        assert_eq!(grid[Pos::new(0, 3)].glyph(), '╚');
        assert_eq!(grid[Pos::new(9, 3)].glyph(), '╝');
    }

    #[test]
    fn wide_char_title_is_centred_by_display_width_not_byte_length() {
        // "あ" is 1 char, 3 bytes (UTF-8), 2 display columns. A byte-length
        // title width (the pre-fix bug) would reserve 3 columns for it and
        // miscentre the title, and would place the trailing space one
        // column further right than it should be.
        let area = Rect::new(0, 0, 10, 3); // max_title_w = 10 - 4 = 6
        let mut grid = Grid::new(10, 3);
        Panel::new()
            .title("あ")
            .render(&mut Surface::new(&mut grid, area, 0));

        // title_x = 0 + (10 - 2 - 2) / 2 = 3; title glyph at 4, trailing
        // space at 5. With the pre-fix byte-length bug (width 3) this would
        // compute title_x = (10 - 3 - 2) / 2 = 2, off by one.
        assert_eq!(grid[Pos::new(3, 0)].glyph(), ' ');
        assert_eq!(grid[Pos::new(4, 0)].glyph(), 'あ');

        // Column 5 is where a wide char's spacer column sits, reserved on every feature
        // combination: `Grid::put_tile` (which `put` uses without `egc`, and `write_grapheme`
        // uses with it) always writes a real spacer there (retroglyph#869), so it reads back as
        // the trailing pad space this widget also explicitly writes at column 6.
        assert_eq!(grid[Pos::new(5, 0)].glyph(), ' ');
        assert_eq!(grid[Pos::new(6, 0)].glyph(), ' ');
    }

    #[test]
    fn add_title_draws_into_the_bottom_border_row() {
        let area = Rect::new(0, 0, 12, 4);
        let mut grid = Grid::new(12, 4);
        Panel::new()
            .add_title("hint", TitlePosition::Bottom, Align::Center)
            .render(&mut Surface::new(&mut grid, area, 0));

        let bottom_row: String = (0..12).map(|x| grid[Pos::new(x, 3)].glyph()).collect();
        assert!(bottom_row.contains("hint"));
        // Top row is untouched: no title was set for it.
        let top_row: String = (0..12).map(|x| grid[Pos::new(x, 0)].glyph()).collect();
        assert!(!top_row.contains("hint"));
    }

    #[test]
    fn title_and_add_title_coexist_on_different_edges() {
        let area = Rect::new(0, 0, 20, 4);
        let mut grid = Grid::new(20, 4);
        Panel::new()
            .title("Inventory")
            .add_title("3 / 10 items", TitlePosition::Bottom, Align::Right)
            .render(&mut Surface::new(&mut grid, area, 0));

        let top_row: String = (0..20).map(|x| grid[Pos::new(x, 0)].glyph()).collect();
        assert!(top_row.contains("Inventory"));
        let bottom_row: String = (0..20).map(|x| grid[Pos::new(x, 3)].glyph()).collect();
        assert!(bottom_row.contains("3 / 10 items"));
    }

    #[test]
    fn two_titles_on_the_same_edge_are_left_and_right_aligned() {
        let area = Rect::new(0, 0, 20, 3);
        let mut grid = Grid::new(20, 3);
        Panel::new()
            .add_title("left", TitlePosition::Top, Align::Left)
            .add_title("right", TitlePosition::Top, Align::Right)
            .render(&mut Surface::new(&mut grid, area, 0));

        let top_row: String = (0..20).map(|x| grid[Pos::new(x, 0)].glyph()).collect();
        assert!(top_row.contains("left"));
        assert!(top_row.contains("right"));
        assert!(top_row.find("left").unwrap() < top_row.find("right").unwrap());
    }

    #[test]
    fn a_later_title_overlapping_an_earlier_one_is_clipped_instead_of_overdrawing_it() {
        // Only 10 columns wide: an 8-column left title (" long L ") leaves no room for a
        // right title declared after it, so the right title must be dropped rather than
        // overdrawing the left one or panicking.
        let area = Rect::new(0, 0, 10, 3);
        let mut grid = Grid::new(10, 3);
        Panel::new()
            .add_title("long L", TitlePosition::Top, Align::Left)
            .add_title("R", TitlePosition::Top, Align::Right)
            .render(&mut Surface::new(&mut grid, area, 0));

        let top_row: String = (0..10).map(|x| grid[Pos::new(x, 0)].glyph()).collect();
        assert!(top_row.contains("long L"));
        assert!(!top_row.contains('R'));
    }

    #[test]
    fn a_title_after_a_centered_title_on_the_same_edge_finds_no_room() {
        let area = Rect::new(0, 0, 20, 3);
        let mut grid = Grid::new(20, 3);
        Panel::new()
            .add_title("centered", TitlePosition::Top, Align::Center)
            .add_title("dropped", TitlePosition::Top, Align::Right)
            .render(&mut Surface::new(&mut grid, area, 0));

        let top_row: String = (0..20).map(|x| grid[Pos::new(x, 0)].glyph()).collect();
        assert!(top_row.contains("centered"));
        assert!(!top_row.contains("dropped"));
    }

    #[test]
    fn a_fifth_add_title_call_still_renders() {
        // `Panel::add_title` has no cap (unlike an earlier fixed-slot design): a fifth call
        // (across both edges) must still draw, not silently drop.
        let area = Rect::new(0, 0, 40, 3);
        let mut grid = Grid::new(40, 3);
        Panel::new()
            .add_title("a", TitlePosition::Top, Align::Left)
            .add_title("b", TitlePosition::Bottom, Align::Left)
            .add_title("c", TitlePosition::Top, Align::Right)
            .add_title("d", TitlePosition::Bottom, Align::Right)
            .add_title("e", TitlePosition::Top, Align::Center)
            .render(&mut Surface::new(&mut grid, area, 0));

        let top_row: String = (0..40).map(|x| grid[Pos::new(x, 0)].glyph()).collect();
        assert!(top_row.contains('a'));
        assert!(top_row.contains('c'));
        assert!(top_row.contains('e'));
    }

    #[test]
    fn renders_identically_at_the_origin_and_at_a_scoped_offset() {
        // #738: a widget correct only by not touching `surface.area()`'s absolute `left()`/
        // `top()` should draw the same relative to its own area regardless of where that area
        // sits on the grid. `Panel::render` is written that way (`surface.width()`/`height()`,
        // never `area().left()`/`top()`), so this must hold for it already.
        let (width, height) = (10, 4);
        let mut origin_grid = Grid::new(width, height);
        Panel::new().title("hi").render(&mut Surface::new(
            &mut origin_grid,
            Rect::new(0, 0, width, height),
            0,
        ));

        let (ox, oy) = (3, 2);
        let mut offset_grid = Grid::new(width + ox, height + oy);
        let mut root = Surface::new(
            &mut offset_grid,
            Rect::new(0, 0, width + ox, height + oy),
            0,
        );
        Panel::new()
            .title("hi")
            .render(&mut root.scope(Rect::new(ox, oy, width, height)));

        for y in 0..height {
            for x in 0..width {
                assert_eq!(
                    origin_grid[Pos::new(x, y)].glyph(),
                    offset_grid[Pos::new(x + ox, y + oy)].glyph(),
                    "mismatch at local ({x}, {y})"
                );
            }
        }
    }
}