Skip to main content

retroglyph_widgets/
style.rs

1//! [`BoxStyle`]: a Lip-Gloss-style box model (padding, border, margin).
2//!
3//! Renders content into a standalone [`Grid`], independent of any
4//! [`Backend`]/[`Terminal`].
5//!
6//! `BoxStyle` does not word-wrap: it lays out already-broken lines (only
7//! `'\n'` is treated specially).
8//!
9//! For word-wrapping text to a width first, use
10//! `Paragraph`/`retroglyph_core::layout::TextLayout` (behind the `egc`
11//! feature), then hand the wrapped result to `BoxStyle::render`. Keeping
12//! wrapping and box-model layout separate avoids tying every consumer of
13//! this module to the `egc` feature.
14use retroglyph_core::{Backend, Grid, Rect, Style, Terminal, Tile};
15use unicode_width::{UnicodeWidthChar, UnicodeWidthStr};
16
17use crate::draw::{BL, BR, H, TL, TR, V};
18use crate::text::truncate;
19use crate::widget::Widget;
20
21/// CSS-style box-model sides: top/right/bottom/left, in terminal cells.
22#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
23pub struct Sides {
24    /// Cells above.
25    pub top: u16,
26    /// Cells to the right.
27    pub right: u16,
28    /// Cells below.
29    pub bottom: u16,
30    /// Cells to the left.
31    pub left: u16,
32}
33
34impl Sides {
35    /// No space on any side.
36    pub const ZERO: Self = Self {
37        top: 0,
38        right: 0,
39        bottom: 0,
40        left: 0,
41    };
42
43    /// The same number of cells on all four sides.
44    #[must_use]
45    pub const fn all(n: u16) -> Self {
46        Self {
47            top: n,
48            right: n,
49            bottom: n,
50            left: n,
51        }
52    }
53
54    /// `vertical` cells top/bottom, `horizontal` cells left/right (CSS
55    /// `padding: v h` shorthand).
56    #[must_use]
57    pub const fn symmetric(vertical: u16, horizontal: u16) -> Self {
58        Self {
59            top: vertical,
60            right: horizontal,
61            bottom: vertical,
62            left: horizontal,
63        }
64    }
65
66    /// Returns `self` with `top` replaced.
67    #[must_use]
68    pub const fn top(mut self, top: u16) -> Self {
69        self.top = top;
70        self
71    }
72
73    /// Returns `self` with `right` replaced.
74    #[must_use]
75    pub const fn right(mut self, right: u16) -> Self {
76        self.right = right;
77        self
78    }
79
80    /// Returns `self` with `bottom` replaced.
81    #[must_use]
82    pub const fn bottom(mut self, bottom: u16) -> Self {
83        self.bottom = bottom;
84        self
85    }
86
87    /// Returns `self` with `left` replaced.
88    #[must_use]
89    pub const fn left(mut self, left: u16) -> Self {
90        self.left = left;
91        self
92    }
93
94    const fn horizontal(self) -> u16 {
95        self.left.saturating_add(self.right)
96    }
97
98    const fn vertical(self) -> u16 {
99        self.top.saturating_add(self.bottom)
100    }
101}
102
103/// A box-model wrapper: content, padding, an optional single-line border,
104/// and margin, rendered into a standalone [`Grid`] via [`BoxStyle::render`].
105///
106/// Layers from the inside out: content -> padding -> border -> margin.
107/// Margin cells are left empty (transparent, per [`Grid::new`]'s default
108/// tiles), matching CSS margin being outside the box's own background.
109///
110/// # Examples
111///
112/// ```
113/// use retroglyph_core::Style;
114/// use retroglyph_widgets::{BoxStyle, Sides};
115///
116/// let grid = BoxStyle::new(Style::new())
117///     .border(true)
118///     .padding(Sides::all(1))
119///     .render("hi");
120/// assert_eq!(grid.get(2, 2).glyph(), 'h'); // 1 border + 1 padding cell in from the corner
121/// ```
122#[derive(Clone, Copy, Debug)]
123pub struct BoxStyle {
124    style: Style,
125    padding: Sides,
126    margin: Sides,
127    border: bool,
128    width: Option<u16>,
129    height: Option<u16>,
130}
131
132impl BoxStyle {
133    /// A borderless box with no padding/margin, in `style`, sized to fit its
134    /// content.
135    #[must_use]
136    pub const fn new(style: Style) -> Self {
137        Self {
138            style,
139            padding: Sides::ZERO,
140            margin: Sides::ZERO,
141            border: false,
142            width: None,
143            height: None,
144        }
145    }
146
147    /// Sets the padding, between the border (if any) and the content.
148    #[must_use]
149    pub const fn padding(mut self, padding: Sides) -> Self {
150        self.padding = padding;
151        self
152    }
153
154    /// Sets the margin, outside the border (if any); left transparent.
155    #[must_use]
156    pub const fn margin(mut self, margin: Sides) -> Self {
157        self.margin = margin;
158        self
159    }
160
161    /// Draws a single-line border, in `style`, around the padding.
162    #[must_use]
163    pub const fn border(mut self, border: bool) -> Self {
164        self.border = border;
165        self
166    }
167
168    /// Sets an explicit content width (excludes padding/border/margin).
169    ///
170    /// Lines wider than this are clipped; without this, the box sizes to
171    /// its widest content line.
172    #[must_use]
173    pub const fn width(mut self, width: u16) -> Self {
174        self.width = Some(width);
175        self
176    }
177
178    /// Sets an explicit content height (excludes padding/border/margin).
179    ///
180    /// Lines past this are dropped; without this, the box sizes to the
181    /// number of lines in the content.
182    #[must_use]
183    pub const fn height(mut self, height: u16) -> Self {
184        self.height = Some(height);
185        self
186    }
187
188    /// Renders `text` into a standalone [`Grid`]: content, padding, border,
189    /// and margin, in that order from the inside out.
190    ///
191    /// `text` is split only on `'\n'`; it is not word-wrapped (see the
192    /// module docs).
193    ///
194    /// Content is positioned by display column (via `unicode-width`), so a
195    /// wide (2-column) character correctly pushes later characters on the
196    /// same line over by 2 columns rather than 1. It is, however, written
197    /// without a `WIDE_CHAR_SPACER` reservation on the cell to its right (see
198    /// `retroglyph_core::Grid::write_grapheme`, which requires the `egc`
199    /// feature this module deliberately does not depend on) -- terminal-
200    /// rendering backends may misalign output by one column per wide
201    /// character as a result. Fully correct wide-character rendering needs
202    /// an `egc`-gated code path; not yet implemented here.
203    #[must_use]
204    pub fn render(&self, text: &str) -> Grid {
205        let lines: Vec<&str> = text.split('\n').collect();
206        let content_w = self.width.unwrap_or_else(|| {
207            u16::try_from(lines.iter().map(|l| l.width()).max().unwrap_or(0)).unwrap_or(u16::MAX)
208        });
209        let content_h = self
210            .height
211            .unwrap_or_else(|| u16::try_from(lines.len()).unwrap_or(u16::MAX));
212
213        let (mut grid, content_x, content_y) = self.scaffold(content_w, content_h);
214        for (row, line) in lines.iter().take(usize::from(content_h)).enumerate() {
215            let Ok(row) = u16::try_from(row) else { break };
216            let clipped = truncate(line, usize::from(content_w));
217            let mut col = 0u16;
218            for ch in clipped.chars() {
219                let w = u16::try_from(ch.width().unwrap_or(0)).unwrap_or(u16::MAX);
220                if col.saturating_add(w) > content_w {
221                    break;
222                }
223                grid.put(content_x + col, content_y + row, Tile::new(ch, self.style));
224                col = col.saturating_add(w);
225            }
226        }
227        grid
228    }
229
230    /// Word-wraps `text` to this box's content width, then renders it the
231    /// same way as [`render`](Self::render): content, padding, border, and
232    /// margin, from the inside out.
233    ///
234    /// Requires the `egc` feature: wrapping is delegated to
235    /// `retroglyph_core::layout::TextLayout`, which (unlike `render`) also
236    /// places wide characters correctly, with a proper `WIDE_CHAR_SPACER`.
237    /// If no explicit width was set via [`BoxStyle::width`], `text` is
238    /// measured but not wrapped (there is no width to wrap to), matching
239    /// `render`'s own natural-width fallback.
240    #[cfg(feature = "egc")]
241    #[must_use]
242    pub fn render_wrapped(&self, text: &str) -> Grid {
243        use retroglyph_core::Headless;
244        use retroglyph_core::layout::TextLayout;
245        use retroglyph_core::text::{Line, Span};
246
247        let content_w = self.width.unwrap_or_else(|| {
248            u16::try_from(
249                text.split('\n')
250                    .map(UnicodeWidthStr::width)
251                    .max()
252                    .unwrap_or(0),
253            )
254            .unwrap_or(u16::MAX)
255        });
256        let line = Line::from(Span::styled(text, self.style));
257        let content_h = self.height.unwrap_or_else(|| {
258            TextLayout::new(&line)
259                .rect(Rect::new(0, 0, content_w, u16::MAX))
260                .measure()
261                .height
262        });
263
264        let (mut grid, content_x, content_y) = self.scaffold(content_w, content_h);
265
266        // TextLayout::render only knows how to draw into a Terminal; render
267        // into a scratch headless one sized to the content area, then blit
268        // that (layer 0 only) onto the scaffold. This also gets
269        // wide-character placement right "for free", since TextLayout uses
270        // `Grid::write_grapheme` internally.
271        let mut scratch = Terminal::new(Headless::new(content_w.max(1), content_h.max(1)));
272        TextLayout::new(&line)
273            .rect(Rect::new(0, 0, content_w, content_h))
274            .render(&mut scratch);
275        let content_rect = Rect::new(0, 0, content_w, content_h);
276        grid.blit(0, scratch.grid(), content_rect, content_x, content_y);
277
278        grid
279    }
280
281    /// Builds the padding/border/margin scaffold for a `content_w`x`content_h`
282    /// content area: a fresh [`Grid`] with the box's background (and border,
283    /// if any) already drawn, plus the `(x, y)` offset where content should
284    /// be written.
285    fn scaffold(&self, content_w: u16, content_h: u16) -> (Grid, u16, u16) {
286        let border_wh = u16::from(self.border) * 2;
287        let inner_w = content_w
288            .saturating_add(self.padding.horizontal())
289            .saturating_add(border_wh);
290        let inner_h = content_h
291            .saturating_add(self.padding.vertical())
292            .saturating_add(border_wh);
293        let outer_w = inner_w.saturating_add(self.margin.horizontal()).max(1);
294        let outer_h = inner_h.saturating_add(self.margin.vertical()).max(1);
295
296        let mut grid = Grid::new(outer_w, outer_h);
297        let box_x = self.margin.left;
298        let box_y = self.margin.top;
299
300        fill_rect(&mut grid, box_x, box_y, inner_w, inner_h, self.style);
301        if self.border {
302            // `inner_w`/`inner_h` already include the border's own 2 cells
303            // (`border_wh` above), so both are always >= 2 here.
304            draw_border(&mut grid, box_x, box_y, inner_w, inner_h, self.style);
305        }
306
307        let content_x = box_x
308            .saturating_add(u16::from(self.border))
309            .saturating_add(self.padding.left);
310        let content_y = box_y
311            .saturating_add(u16::from(self.border))
312            .saturating_add(self.padding.top);
313        (grid, content_x, content_y)
314    }
315}
316
317/// Pairs a [`BoxStyle`] with the text it should render, so the pair can
318/// implement [`Widget`] (which has no room for a text parameter). Build one
319/// via [`BoxStyle::text`].
320///
321/// [`Widget::render`] places the box at `area`'s top-left corner, sized to
322/// the style's own explicit-or-content-fit dimensions -- it does not stretch
323/// or clip to fill `area`. It always uses [`BoxStyle::render`] (not
324/// `BoxStyle::render_wrapped`, behind the `egc` feature); for wrapped
325/// content, call `render_wrapped` directly and [`crate::blit_into`] the
326/// result yourself.
327#[derive(Clone, Copy, Debug)]
328pub struct Boxed<'a> {
329    style: BoxStyle,
330    text: &'a str,
331}
332
333impl BoxStyle {
334    /// Pairs this style with `text`, ready to draw via [`Widget::render`].
335    #[must_use]
336    pub const fn text(self, text: &str) -> Boxed<'_> {
337        Boxed { style: self, text }
338    }
339}
340
341impl<B: Backend> Widget<B> for Boxed<'_> {
342    fn render(self, area: Rect, term: &mut Terminal<B>) {
343        let grid = self.style.render(self.text);
344        crate::block::blit_into(term, &grid, area.left(), area.top());
345    }
346}
347
348/// Fill `w`×`h` starting at `(x, y)` with a `style`d space.
349fn fill_rect(grid: &mut Grid, x: u16, y: u16, w: u16, h: u16, style: Style) {
350    for dy in 0..h {
351        for dx in 0..w {
352            grid.put(x + dx, y + dy, Tile::new(' ', style));
353        }
354    }
355}
356
357/// Draw a single-line border around the `w`×`h` rect at `(x, y)`, in
358/// `style`. Caller must ensure `w >= 2 && h >= 2`.
359fn draw_border(grid: &mut Grid, x: u16, y: u16, w: u16, h: u16, style: Style) {
360    let right = x + w - 1;
361    let bottom = y + h - 1;
362
363    grid.put(x, y, Tile::new(TL, style));
364    grid.put(right, y, Tile::new(TR, style));
365    grid.put(x, bottom, Tile::new(BL, style));
366    grid.put(right, bottom, Tile::new(BR, style));
367    for cx in (x + 1)..right {
368        grid.put(cx, y, Tile::new(H, style));
369        grid.put(cx, bottom, Tile::new(H, style));
370    }
371    for cy in (y + 1)..bottom {
372        grid.put(x, cy, Tile::new(V, style));
373        grid.put(right, cy, Tile::new(V, style));
374    }
375}
376
377#[cfg(test)]
378mod tests {
379    use super::*;
380
381    fn glyphs(grid: &Grid) -> Vec<String> {
382        (0..grid.height())
383            .map(|y| (0..grid.width()).map(|x| grid.get(x, y).glyph()).collect())
384            .collect()
385    }
386
387    #[test]
388    fn sides_helpers() {
389        assert_eq!(
390            Sides::all(2),
391            Sides {
392                top: 2,
393                right: 2,
394                bottom: 2,
395                left: 2
396            }
397        );
398        assert_eq!(
399            Sides::symmetric(1, 3),
400            Sides {
401                top: 1,
402                right: 3,
403                bottom: 1,
404                left: 3
405            }
406        );
407    }
408
409    #[test]
410    fn sizes_to_content_with_no_padding_or_border() {
411        let grid = BoxStyle::new(Style::default()).render("hi");
412        assert_eq!((grid.width(), grid.height()), (2, 1));
413        assert_eq!(grid.get(0, 0).glyph(), 'h');
414        assert_eq!(grid.get(1, 0).glyph(), 'i');
415    }
416
417    #[test]
418    fn sizes_to_the_widest_of_multiple_lines() {
419        let grid = BoxStyle::new(Style::default()).render("a\nbcd\nef");
420        assert_eq!((grid.width(), grid.height()), (3, 3));
421        assert_eq!(grid.get(0, 0).glyph(), 'a');
422        assert_eq!(grid.get(1, 0).glyph(), ' '); // shorter line padded with blanks
423        assert_eq!(grid.get(0, 1).glyph(), 'b');
424        assert_eq!(grid.get(2, 1).glyph(), 'd');
425    }
426
427    #[test]
428    fn explicit_width_clips_longer_lines_and_pads_shorter_ones() {
429        let grid = BoxStyle::new(Style::default()).width(3).render("hello");
430        assert_eq!(grid.width(), 3);
431        let row: String = (0..3).map(|x| grid.get(x, 0).glyph()).collect();
432        assert_eq!(row, "hel");
433    }
434
435    #[test]
436    fn explicit_height_drops_extra_lines() {
437        let grid = BoxStyle::new(Style::default()).height(1).render("a\nb\nc");
438        assert_eq!(grid.height(), 1);
439        assert_eq!(grid.get(0, 0).glyph(), 'a');
440    }
441
442    #[test]
443    fn padding_surrounds_content_with_the_box_style() {
444        let grid = BoxStyle::new(Style::default())
445            .padding(Sides::all(1))
446            .render("x");
447        // 1 content col/row + 1 padding on each side = 3x3.
448        assert_eq!((grid.width(), grid.height()), (3, 3));
449        assert_eq!(grid.get(1, 1).glyph(), 'x');
450        assert_eq!(grid.get(0, 0).glyph(), ' ');
451    }
452
453    #[test]
454    fn border_draws_a_box_around_padding_and_content() {
455        let grid = BoxStyle::new(Style::default()).border(true).render("x");
456        // 1 content col/row + 2 border = 3x3.
457        assert_eq!((grid.width(), grid.height()), (3, 3));
458        let rows = glyphs(&grid);
459        assert_eq!(rows[0], "┌─┐");
460        assert_eq!(rows[1], "│x│");
461        assert_eq!(rows[2], "└─┘");
462    }
463
464    #[test]
465    fn margin_is_left_transparent_outside_the_border() {
466        let grid = BoxStyle::new(Style::default())
467            .margin(Sides::all(1))
468            .render("x");
469        // 1x1 content, 1 margin on each side = 3x3; margin cells are never
470        // written, so they keep Grid::new's default "empty" tile, which
471        // Grid::blit treats as transparent.
472        assert_eq!((grid.width(), grid.height()), (3, 3));
473        assert!(grid.get(0, 0).is_empty());
474        assert_eq!(grid.get(1, 1).glyph(), 'x');
475    }
476
477    #[test]
478    fn wide_characters_push_later_columns_over_by_their_width() {
479        // "あ" (HIRAGANA A) is 2 columns wide: width("aあb") == 4, and 'b'
480        // must land at column 3, not column 2 (its char index), or it would
481        // collide with あ's second visual column.
482        //
483        // Note: this only checks *sizing*/*column offset* correctness. The
484        // wide glyph itself is still written without a WIDE_CHAR_SPACER (see
485        // render()'s doc comment); a real terminal backend may still
486        // misrender the cell to its right.
487        let grid = BoxStyle::new(Style::default()).render("aあb");
488        assert_eq!(grid.width(), 4);
489        assert_eq!(grid.get(0, 0).glyph(), 'a');
490        assert_eq!(grid.get(1, 0).glyph(), 'あ');
491        assert_eq!(grid.get(3, 0).glyph(), 'b');
492    }
493
494    #[test]
495    fn border_with_empty_content_is_still_at_least_a_2x2_box() {
496        // No content, no padding: inner size is exactly the border's own 2
497        // cells in each axis (content_w = 0, content_h = 1 line of "").
498        let grid = BoxStyle::new(Style::default()).border(true).render("");
499        assert_eq!((grid.width(), grid.height()), (2, 3));
500        let rows = glyphs(&grid);
501        assert_eq!(rows[0], "┌┐");
502        assert_eq!(rows[2], "└┘");
503    }
504
505    #[test]
506    #[cfg(feature = "egc")]
507    fn render_wrapped_word_wraps_to_the_explicit_width() {
508        // Same text/width Paragraph's own tests use (see widget/paragraph.rs),
509        // so this is exercising the same, already-verified TextLayout wrap.
510        let grid = BoxStyle::new(Style::default())
511            .width(10)
512            .render_wrapped("the quick brown fox jumps");
513        assert_eq!(grid.width(), 10);
514        let rows = glyphs(&grid);
515        assert_eq!(rows[0].trim_end(), "the quick");
516        assert_eq!(rows[1].trim_end(), "brown fox");
517        assert_eq!(rows[2].trim_end(), "jumps");
518    }
519
520    #[test]
521    #[cfg(feature = "egc")]
522    fn render_wrapped_without_an_explicit_width_measures_but_does_not_wrap() {
523        // No width set: same natural-width fallback as `render`, so nothing
524        // is short enough to need wrapping.
525        let grid = BoxStyle::new(Style::default()).render_wrapped("hi");
526        assert_eq!((grid.width(), grid.height()), (2, 1));
527        assert_eq!(grid.get(0, 0).glyph(), 'h');
528        assert_eq!(grid.get(1, 0).glyph(), 'i');
529    }
530
531    #[test]
532    #[cfg(feature = "egc")]
533    fn render_wrapped_respects_padding_and_border_like_render() {
534        let grid = BoxStyle::new(Style::default())
535            .border(true)
536            .padding(Sides::all(1))
537            .width(3)
538            .render_wrapped("hi");
539        // 3 content cols + 2 padding + 2 border = 7; 1 content row + 2
540        // padding + 2 border = 5.
541        assert_eq!((grid.width(), grid.height()), (7, 5));
542        assert_eq!(grid.get(2, 2).glyph(), 'h');
543        assert_eq!(grid.get(3, 2).glyph(), 'i');
544    }
545
546    #[test]
547    fn boxed_widget_places_the_box_at_the_areas_top_left() {
548        use retroglyph_core::Headless;
549
550        let styled = BoxStyle::new(Style::default()).border(true).text("hi");
551        let mut term = Terminal::new(Headless::new(10, 6));
552        styled.render(Rect::new(2, 1, 10, 6), &mut term);
553
554        // 2 content cols + 2 border = 4 wide, 1 content row + 2 border = 3
555        // tall, anchored at (2, 1) regardless of the much larger area.
556        assert_eq!(term.grid().get(2, 1).glyph(), '┌');
557        assert_eq!(term.grid().get(3, 2).glyph(), 'h');
558        assert_eq!(term.grid().get(4, 2).glyph(), 'i');
559        assert_eq!(term.grid().get(5, 3).glyph(), '┘');
560    }
561}