tuika 0.4.0

A composable terminal UI toolkit — flexbox layout, overlays, focus, and safe ratatui interoperability.
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
//! Bordered box — a single-child container with border, padding, background,
//! and an optional title. Focus-aware: its border recolors when the render
//! context reports focus, and [`Boxed::border_color`] overrides that with an
//! explicit color for semantic frames (accent/danger modals, per-pane colors).
//! This is `tuika`'s framing primitive (Pi's `DynamicBorder` / `Box`).

use ratatui_core::layout::{Alignment, Rect};
use ratatui_core::style::{Color, Style};
use ratatui_core::text::Line;

use crate::geometry::{Padding, Size};
use crate::style::{BorderStyle, Role};
use crate::surface::Surface;
use crate::view::{Element, RenderCtx, View};

use super::text::{aligned_x, line_width};

/// A bordered, padded container wrapping one child.
///
/// # Example
///
/// ```
/// use tuika::{Boxed, Text, Theme, element};
/// use tuika::testing::{grid, render};
///
/// // Default rounded border with symmetric horizontal padding.
/// let view = Boxed::new(element(Text::raw("hi")));
///
/// let buffer = render(&view, 6, 3, &Theme::default());
/// assert_eq!(
///     grid(&buffer),
///     "╭────╮\n\
///      │ hi │\n\
///      ╰────╯",
/// );
/// ```
///
/// A secondary title can ride the bottom border — a position counter, footer
/// legend, or hint — and defaults to flush-right:
///
/// ```
/// use tuika::{Boxed, Text, Theme, element};
/// use tuika::testing::{grid, render};
///
/// let view = Boxed::new(element(Text::raw("hi")))
///     .title(" files ")
///     .title_bottom(" 1/3 ");
///
/// let buffer = render(&view, 12, 3, &Theme::default());
/// assert_eq!(
///     grid(&buffer),
///     "╭─ files ──╮\n\
///      │ hi       │\n\
///      ╰──── 1/3 ─╯",
/// );
/// ```
///
/// ![boxed demo](https://raw.githubusercontent.com/everruns/yolop/main/crates/tuika/docs/demos/boxed.gif)
pub struct Boxed {
    child: Element,
    border: BorderStyle,
    border_color: Option<Color>,
    padding: Padding,
    title: Option<Line<'static>>,
    title_bottom: Option<Line<'static>>,
    background: Option<Style>,
}

impl Boxed {
    /// Wrap `child` with default rounded border and symmetric horizontal padding.
    pub fn new(child: Element) -> Self {
        Self {
            child,
            border: BorderStyle::Rounded,
            border_color: None,
            padding: Padding::symmetric(1, 0),
            title: None,
            title_bottom: None,
            background: None,
        }
    }

    /// Set the border style (`BorderStyle::None` removes the border).
    pub fn border(mut self, border: BorderStyle) -> Self {
        self.border = border;
        self
    }

    /// Paint the border in an explicit `color`, overriding the theme.
    ///
    /// By default the border follows the theme and the render context's focus
    /// flag (`theme.border` / `theme.border_focused`) — right for panes that
    /// take focus. Set this when the border encodes a *semantic* meaning the
    /// theme's border role can't express: an accent or danger frame on a modal,
    /// or a specific per-pane color a host resolves itself. The override wins
    /// over both theme and focus. To drive focused/unfocused coloring for a
    /// subtree instead, wrap it in a [`FocusScope`](crate::FocusScope) and leave
    /// this unset.
    pub fn border_color(mut self, color: Color) -> Self {
        self.border_color = Some(color);
        self
    }

    /// Set the padding between the border and the child.
    pub fn padding(mut self, padding: Padding) -> Self {
        self.padding = padding;
        self
    }

    /// Set a title drawn on the top border, clipped between the corners.
    ///
    /// The title's horizontal placement honors its [`Line::alignment`]; an unset
    /// alignment (the default) is flush-left, matching a plain string title.
    pub fn title(mut self, title: impl Into<Line<'static>>) -> Self {
        self.title = Some(title.into());
        self
    }

    /// Set a secondary title drawn on the bottom border, clipped between the
    /// corners — the slot list/table TUIs use for a `1 of 3` position counter, a
    /// footer legend, or a keybinding hint.
    ///
    /// Placement honors the title's [`Line::alignment`]. An unset alignment
    /// defaults to flush-**right** here (unlike the top title's flush-left),
    /// since a bottom-right counter is the common case; pass a `.centered()` or
    /// `.left_aligned()` [`Line`] to override.
    pub fn title_bottom(mut self, title: impl Into<Line<'static>>) -> Self {
        self.title_bottom = Some(title.into());
        self
    }

    /// Fill the box interior with `style` before drawing the child.
    pub fn background(mut self, style: Style) -> Self {
        self.background = Some(style);
        self
    }

    fn has_border(&self) -> bool {
        !matches!(self.border, BorderStyle::None)
    }

    /// Interior rect available to the child after border + padding.
    fn inner(&self, area: Rect) -> Rect {
        let bordered = if self.has_border() {
            Rect {
                x: area.x.saturating_add(1),
                y: area.y.saturating_add(1),
                width: area.width.saturating_sub(2),
                height: area.height.saturating_sub(2),
            }
        } else {
            area
        };
        self.padding.inner(bordered)
    }

    fn chrome(&self) -> Size {
        let border = if self.has_border() { 2 } else { 0 };
        Size::new(
            self.padding.horizontal().saturating_add(border),
            self.padding.vertical().saturating_add(border),
        )
    }
}

impl View for Boxed {
    fn measure(&self, available: Size) -> Size {
        let chrome = self.chrome();
        let inner_avail = Size::new(
            available.width.saturating_sub(chrome.width),
            available.height.saturating_sub(chrome.height),
        );
        let content = self.child.measure(inner_avail);
        Size::new(
            content.width.saturating_add(chrome.width),
            content.height.saturating_add(chrome.height),
        )
    }

    fn render(&self, area: Rect, surface: &mut Surface, ctx: &RenderCtx) {
        if area.width == 0 || area.height == 0 {
            return;
        }
        let panel = ctx.sheet.resolve(Role::Panel);
        // Background: an explicit `.background(..)` wins; otherwise the sheet's
        // panel fill, which a host uses to opt every panel into a shared surface
        // color without a per-call-site `.background(..)`.
        let background = self
            .background
            .or_else(|| panel.bg.map(|c| Style::default().bg(c)));
        if let Some(bg) = background {
            let mut fill = surface.child(area);
            fill.fill(bg);
        }
        if self.has_border() {
            // Precedence: an explicit `.border_color(..)` wins over everything;
            // else a focused panel takes the theme's focus color; else the sheet's
            // panel `fg` (when set) recolors every unfocused border, falling back
            // to the theme border color. The border *glyphs* stay instance-level
            // because their presence affects layout, which `measure` resolves
            // without a stylesheet.
            let color = self.border_color.unwrap_or_else(|| {
                if ctx.focused {
                    ctx.theme.border_focused
                } else {
                    panel.fg.unwrap_or(ctx.theme.border)
                }
            });
            let border_style = Style::default().fg(color);
            surface.draw_border(area, self.border.glyphs(), border_style);
            if let Some(title) = &self.title {
                draw_title(surface, area, area.y, title, Alignment::Left);
            }
            if let Some(title) = &self.title_bottom {
                let bottom = area.bottom().saturating_sub(1);
                draw_title(surface, area, bottom, title, Alignment::Right);
            }
        }
        let inner = self.inner(area);
        let mut inner_surface = surface.child(inner);
        self.child.render(inner, &mut inner_surface, ctx);
    }
}

/// Draw a border `title` on row `y`, inset one cell from each corner and clipped
/// to fit between them. Horizontal placement honors the line's alignment,
/// falling back to `default_align` when it is unset. A title too wide for the
/// span between the corners is dropped rather than overrunning a corner.
fn draw_title(
    surface: &mut Surface,
    area: Rect,
    y: u16,
    title: &Line<'static>,
    default_align: Alignment,
) {
    let max = area.width.saturating_sub(4);
    if line_width(title) > max {
        return;
    }
    // The title span runs from one cell past the left corner to one cell before
    // the right corner; align the content within that inset region.
    let region = Rect {
        x: area.x.saturating_add(2),
        y,
        width: max,
        height: 1,
    };
    let align = title.alignment.unwrap_or(default_align);
    let mut x = aligned_x(align, line_width(title), region);
    for span in &title.spans {
        x = surface.set_string(x, y, span.content.as_ref(), span.style);
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::Surface;
    use crate::components::Text;
    use crate::style::Theme;
    use crate::test_support::{buffer, rainbow_theme, row};
    use crate::view::{RenderCtx, View, element};
    use ratatui_core::style::Color;

    #[test]
    fn boxed_border_closed_across_sizes() {
        let theme = Theme::default();
        let ctx = RenderCtx::new(&theme);
        for w in 2..=12u16 {
            for h in 2..=8u16 {
                let mut buf = buffer(w, h);
                let area = buf.area;
                let mut surface = Surface::new(&mut buf, area);
                Boxed::new(element(Text::raw("x"))).render(area, &mut surface, &ctx);
                assert_eq!(buf[(0, 0)].symbol(), "", "top-left at {w}x{h}");
                assert_eq!(buf[(w - 1, 0)].symbol(), "", "top-right at {w}x{h}");
                assert_eq!(buf[(0, h - 1)].symbol(), "", "bottom-left at {w}x{h}");
                assert_eq!(buf[(w - 1, h - 1)].symbol(), "", "bottom-right at {w}x{h}");
            }
        }
    }

    #[test]
    fn bottom_title_defaults_flush_right() {
        let theme = Theme::default();
        let ctx = RenderCtx::new(&theme);
        let mut buf = buffer(10, 3);
        let area = buf.area;
        let mut surface = Surface::new(&mut buf, area);
        // Plain string title, no explicit alignment -> flush-right on the
        // bottom border, one cell inside the right corner.
        Boxed::new(element(Text::raw("x")))
            .title_bottom(" 1/3 ")
            .render(area, &mut surface, &ctx);
        // Width 10: corners at 0 and 9, inset span [2..8) is 6 cols, " 1/3 " is
        // 5 cols -> right-aligned start at column 3.
        assert_eq!(row(&buf, 2), "╰── 1/3 ─╯");
    }

    #[test]
    fn bottom_title_honors_explicit_alignment() {
        let theme = Theme::default();
        let ctx = RenderCtx::new(&theme);
        let mut buf = buffer(10, 3);
        let area = buf.area;
        let mut surface = Surface::new(&mut buf, area);
        Boxed::new(element(Text::raw("x")))
            .title_bottom(Line::from("ab").left_aligned())
            .render(area, &mut surface, &ctx);
        // Left-aligned -> one cell in from the left corner.
        assert_eq!(row(&buf, 2), "╰─ab─────╯");
    }

    #[test]
    fn top_title_honors_center_alignment() {
        let theme = Theme::default();
        let ctx = RenderCtx::new(&theme);
        let mut buf = buffer(10, 3);
        let area = buf.area;
        let mut surface = Surface::new(&mut buf, area);
        Boxed::new(element(Text::raw("x")))
            .title(Line::from("ab").centered())
            .render(area, &mut surface, &ctx);
        // Inset span [2..8) width 6, content 2 -> slack 4, centered start col
        // 2 + 4/2 = 4.
        assert_eq!(row(&buf, 0), "╭───ab───╮");
    }

    #[test]
    fn oversized_bottom_title_is_dropped() {
        let theme = Theme::default();
        let ctx = RenderCtx::new(&theme);
        let mut buf = buffer(6, 3);
        let area = buf.area;
        let mut surface = Surface::new(&mut buf, area);
        Boxed::new(element(Text::raw("x")))
            .title_bottom("a title far too wide")
            .render(area, &mut surface, &ctx);
        // Doesn't fit between the corners -> border stays intact, no overrun.
        assert_eq!(row(&buf, 2), "╰────╯");
    }

    #[test]
    fn boxed_border_follows_theme_focus_color() {
        let t = rainbow_theme();

        let make = |focused: bool| {
            let mut buf = buffer(8, 3);
            let area = buf.area;
            let ctx = RenderCtx::new(&t).with_focus(focused);
            let boxed = Boxed::new(element(Text::raw("x")));
            let mut surface = Surface::new(&mut buf, area);
            boxed.render(area, &mut surface, &ctx);
            buf[(0, 0)].fg // the '╭' corner
        };

        assert_eq!(make(false), t.border, "unfocused border uses theme.border");
        assert_eq!(
            make(true),
            t.border_focused,
            "focused border uses theme.border_focused"
        );
    }

    #[test]
    fn explicit_border_color_overrides_theme_and_focus() {
        let t = rainbow_theme();
        let make = |focused: bool| {
            let mut buf = buffer(8, 3);
            let area = buf.area;
            let ctx = RenderCtx::new(&t).with_focus(focused);
            let boxed = Boxed::new(element(Text::raw("x"))).border_color(Color::Indexed(201));
            let mut surface = Surface::new(&mut buf, area);
            boxed.render(area, &mut surface, &ctx);
            buf[(0, 0)].fg
        };
        // The explicit color wins regardless of the context's focus flag and
        // ignores both theme.border and theme.border_focused.
        assert_eq!(make(false), Color::Indexed(201));
        assert_eq!(make(true), Color::Indexed(201));
        assert_ne!(Color::Indexed(201), t.border);
        assert_ne!(Color::Indexed(201), t.border_focused);
    }

    #[test]
    fn swapping_theme_restyles_the_same_tree() {
        let tree = || Boxed::new(element(Text::raw("x")));
        let render_border = |theme: &Theme| {
            let mut buf = buffer(8, 3);
            let area = buf.area;
            let ctx = RenderCtx::new(theme);
            let mut surface = Surface::new(&mut buf, area);
            tree().render(area, &mut surface, &ctx);
            buf[(0, 0)].fg
        };

        let a = Theme {
            border: Color::Indexed(21),
            ..rainbow_theme()
        };
        let b = Theme {
            border: Color::Indexed(99),
            ..rainbow_theme()
        };
        assert_eq!(render_border(&a), Color::Indexed(21));
        assert_eq!(render_border(&b), Color::Indexed(99));
        assert_ne!(
            render_border(&a),
            render_border(&b),
            "theme swap must restyle"
        );
    }

    #[test]
    fn stylesheet_panel_recolors_border_and_fills_background() {
        use crate::style::{StyleBundle, StyleSheet};

        let t = rainbow_theme();
        // One central rule: every panel gets an accent-alt border and a surface
        // fill — no per-`Boxed` `.background(..)` or border color needed.
        let sheet = StyleSheet {
            panel: StyleBundle::new().fg(t.accent_alt).bg(t.surface),
            ..StyleSheet::from_theme(&t)
        };

        let mut buf = buffer(8, 3);
        let area = buf.area;
        let ctx = RenderCtx::new(&t).with_sheet(sheet);
        let mut surface = Surface::new(&mut buf, area);
        Boxed::new(element(Text::raw("x"))).render(area, &mut surface, &ctx);

        // The border corner takes the sheet's panel color, not the theme border.
        assert_eq!(buf[(0, 0)].fg, t.accent_alt, "sheet recolors the border");
        assert_ne!(t.accent_alt, t.border, "guard: the sheet color is distinct");
        // The interior is filled with the sheet's panel background.
        assert_eq!(
            buf[(1, 1)].bg,
            t.surface,
            "sheet fills the panel background"
        );
    }

    #[test]
    fn explicit_background_overrides_the_sheet_panel_fill() {
        use crate::style::{StyleBundle, StyleSheet};

        let t = rainbow_theme();
        let sheet = StyleSheet {
            panel: StyleBundle::new().bg(t.surface),
            ..StyleSheet::from_theme(&t)
        };
        let mut buf = buffer(8, 3);
        let area = buf.area;
        let ctx = RenderCtx::new(&t).with_sheet(sheet);
        let mut surface = Surface::new(&mut buf, area);
        // An inline `.background(..)` still wins over the sheet default.
        Boxed::new(element(Text::raw("x")))
            .background(Style::default().bg(t.selection_bg))
            .render(area, &mut surface, &ctx);
        assert_eq!(
            buf[(1, 1)].bg,
            t.selection_bg,
            "inline style beats the sheet"
        );
    }
}