sparcli 0.3.0

Lightweight, cross-platform toolkit for styled CLI output and interactive input widgets
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
//! Bordered panels framing content with an optional title and subtitle.

use crate::core::border::BorderType;
use crate::core::geometry::{Align, Edges, Position, Title};
use crate::core::render::{Renderable, Rendered};
use crate::core::style::Style;
use crate::core::text::{Line, Span, Text};
use crate::core::theme::theme;
use crate::core::width::truncate;
use crate::output::layout::{blank_line, pad_line};

/// Columns consumed by the two vertical border glyphs.
const BORDER_COLUMNS: usize = 2;

/// Box-drawing options shared by panels and other framed widgets.
pub(crate) struct BoxOpts {
    /// Border style.
    pub border: BorderType,
    /// Style applied to the border glyphs.
    pub border_style: Style,
    /// Fill style for the interior (padding and content background).
    pub fill: Style,
    /// Inner padding between border and content.
    pub padding: Edges,
    /// Optional title.
    pub title: Option<Title>,
    /// Optional subtitle (bottom edge by default).
    pub subtitle: Option<Title>,
    /// Optional fixed outer width in columns.
    pub width: Option<u16>,
    /// Horizontal alignment of content within the panel.
    pub content_align: Align,
}

impl Default for BoxOpts {
    fn default() -> Self {
        Self {
            border: theme().border,
            border_style: Style::new(),
            fill: Style::new(),
            padding: Edges::symmetric(0, 1),
            title: None,
            subtitle: None,
            width: None,
            content_align: Align::Left,
        }
    }
}

/// A bordered panel around rich content.
///
/// # Examples
///
/// ```
/// use sparcli::{Panel, Renderable, Title};
///
/// let out = Panel::new("Ready.").title(Title::new("Status")).render(40);
/// assert!(out.plain().contains("Ready."));
/// ```
pub struct Panel {
    content: Rendered,
    opts: BoxOpts,
}

impl Panel {
    /// Creates a panel around text content.
    pub fn new(content: impl Into<Text>) -> Self {
        let text = content.into();
        Self {
            content: Rendered::new(text.lines),
            opts: BoxOpts::default(),
        }
    }

    /// Creates a panel around an already rendered block.
    pub fn from_rendered(content: Rendered) -> Self {
        Self {
            content,
            opts: BoxOpts::default(),
        }
    }

    /// Sets the border type.
    #[must_use]
    pub fn border(mut self, border: BorderType) -> Self {
        self.opts.border = border;
        self
    }

    /// Sets the border glyph style.
    #[must_use]
    pub fn border_style(mut self, style: Style) -> Self {
        self.opts.border_style = style;
        self
    }

    /// Sets the interior fill style (e.g. a background color).
    #[must_use]
    pub fn fill(mut self, style: Style) -> Self {
        self.opts.fill = style;
        self
    }

    /// Sets the inner padding.
    #[must_use]
    pub fn padding(mut self, padding: Edges) -> Self {
        self.opts.padding = padding;
        self
    }

    /// Sets the title.
    #[must_use]
    pub fn title(mut self, title: impl Into<Title>) -> Self {
        self.opts.title = Some(title.into());
        self
    }

    /// Sets the subtitle (placed on the bottom edge unless overridden).
    #[must_use]
    pub fn subtitle(mut self, mut subtitle: Title) -> Self {
        subtitle.position = Position::Bottom;
        self.opts.subtitle = Some(subtitle);
        self
    }

    /// Sets a fixed outer width in columns.
    #[must_use]
    pub fn width(mut self, width: u16) -> Self {
        self.opts.width = Some(width);
        self
    }

    /// Sets the horizontal content alignment.
    #[must_use]
    pub fn content_align(mut self, align: Align) -> Self {
        self.opts.content_align = align;
        self
    }
}

impl Renderable for Panel {
    fn render(&self, max_width: u16) -> Rendered {
        draw_box(&self.content, &self.opts, max_width)
    }
}

/// Frames `content` according to `opts`, clamped to `max_width` columns.
///
/// The frame never exceeds `max_width`: a fixed width is capped, natural
/// content that overflows shrinks the frame, and a title too wide for the
/// interior is truncated rather than widening the box.
pub(crate) fn draw_box(
    content: &Rendered,
    opts: &BoxOpts,
    max_width: u16,
) -> Rendered {
    let max_width = max_width as usize;
    if opts.border.is_none() {
        return frame_borderless(content, opts, max_width);
    }
    let area_width = compute_area_width(content, opts, max_width);
    let content_area =
        area_width.saturating_sub(opts.padding.horizontal() as usize);

    let mut lines = Vec::new();
    let top_title = edge_title(opts, Position::Top);
    lines.push(edge_line(opts, area_width, Position::Top, top_title));
    push_padding_rows(&mut lines, opts, area_width, opts.padding.top);
    for line in &content.lines {
        lines.push(content_row(line, opts, content_area));
    }
    push_padding_rows(&mut lines, opts, area_width, opts.padding.bottom);
    let bottom_title = edge_title(opts, Position::Bottom);
    lines.push(edge_line(opts, area_width, Position::Bottom, bottom_title));
    Rendered::new(lines)
}

/// Returns the title that sits on the given edge, if any.
fn edge_title(opts: &BoxOpts, position: Position) -> Option<&Title> {
    [opts.title.as_ref(), opts.subtitle.as_ref()]
        .into_iter()
        .flatten()
        .find(|title| title.position == position)
}

/// Computes the interior width between the vertical borders, clamped so the
/// whole frame fits within `max_width`.
fn compute_area_width(
    content: &Rendered,
    opts: &BoxOpts,
    max_width: usize,
) -> usize {
    let border_cols = if opts.border.is_none() {
        0
    } else {
        BORDER_COLUMNS
    };
    let padding = opts.padding.horizontal() as usize;
    let overhead = border_cols + padding;
    let content_area = match opts.width {
        Some(total) => (total as usize).min(max_width).saturating_sub(overhead),
        None => {
            let natural = content.width();
            if natural + overhead <= max_width {
                natural
            } else {
                max_width.saturating_sub(overhead)
            }
        }
    };
    content_area + padding
}

/// Builds the content padding rows (blank interior lines).
fn push_padding_rows(
    lines: &mut Vec<Line>,
    opts: &BoxOpts,
    area_width: usize,
    count: u16,
) {
    for _ in 0..count {
        lines.push(wrap_with_borders(blank_line(area_width, opts.fill), opts));
    }
}

/// Builds one aligned, padded content line without border glyphs.
fn inner_row(line: &Line, opts: &BoxOpts, content_area: usize) -> Line {
    let mut spans = Vec::new();
    if opts.padding.left > 0 {
        spans.push(Span::styled(
            " ".repeat(opts.padding.left as usize),
            opts.fill,
        ));
    }
    let padded =
        pad_line(line.clone(), content_area, opts.content_align, opts.fill);
    spans.extend(padded.spans);
    if opts.padding.right > 0 {
        spans.push(Span::styled(
            " ".repeat(opts.padding.right as usize),
            opts.fill,
        ));
    }
    Line::new(spans)
}

/// Wraps one content line with padding and vertical borders.
fn content_row(line: &Line, opts: &BoxOpts, content_area: usize) -> Line {
    wrap_with_borders(inner_row(line, opts, content_area), opts)
}

/// Adds left/right vertical border glyphs around `inner`.
fn wrap_with_borders(inner: Line, opts: &BoxOpts) -> Line {
    let chars = opts.border.chars();
    let mut spans = Vec::with_capacity(inner.spans.len() + 2);
    spans.push(Span::styled(chars.vertical.to_string(), opts.border_style));
    spans.extend(inner.spans);
    spans.push(Span::styled(chars.vertical.to_string(), opts.border_style));
    Line::new(spans)
}

/// Builds a top or bottom border line, optionally embedding a title.
fn edge_line(
    opts: &BoxOpts,
    area_width: usize,
    position: Position,
    title: Option<&Title>,
) -> Line {
    let chars = opts.border.chars();
    let (left, right) = match position {
        Position::Bottom => (chars.bottom_left, chars.bottom_right),
        Position::Top => (chars.top_left, chars.top_right),
    };
    let mut spans = vec![Span::styled(left.to_string(), opts.border_style)];
    match title {
        None => spans.push(horizontal_fill(chars.horizontal, area_width, opts)),
        Some(title) => {
            push_titled_fill(&mut spans, title, area_width, opts);
        }
    }
    spans.push(Span::styled(right.to_string(), opts.border_style));
    Line::new(spans)
}

/// Builds a horizontal fill span of `width` border glyphs.
fn horizontal_fill(glyph: char, width: usize, opts: &BoxOpts) -> Span {
    Span::styled(glyph.to_string().repeat(width), opts.border_style)
}

/// Embeds a title within a horizontal border run so it reads as part of the
/// frame. A left-aligned title keeps exactly one connecting border glyph before
/// it (`┌─ Title ─`), never a flush `┌ Title`; the glyphs on both sides take the
/// border style so the seam stays uniform.
fn push_titled_fill(
    spans: &mut Vec<Span>,
    title: &Title,
    area_width: usize,
    opts: &BoxOpts,
) {
    let chars = opts.border.chars();
    let pad = title.pad as usize;
    let title_line = title.content.lines.first().cloned().unwrap_or_default();
    let title_w = title_line.width() + 2 * pad;
    if title_w >= area_width {
        // Too wide for the interior: truncate into the border run instead of
        // widening the frame.
        let text = truncate(&title_line.plain(), area_width, "");
        spans.push(Span::styled(text, opts.border_style));
        return;
    }
    let remaining = area_width - title_w;
    let (left_fill, right_fill) = match title.align {
        Align::Left => (1.min(remaining), remaining.saturating_sub(1)),
        Align::Right => (remaining.saturating_sub(1), 1.min(remaining)),
        Align::Center => (remaining / 2, remaining - remaining / 2),
    };
    spans.push(horizontal_fill(chars.horizontal, left_fill, opts));
    if pad > 0 {
        spans.push(Span::raw(" ".repeat(pad)));
    }
    spans.extend(title_line.spans);
    if pad > 0 {
        spans.push(Span::raw(" ".repeat(pad)));
    }
    spans.push(horizontal_fill(chars.horizontal, right_fill, opts));
}

/// Frames content without borders: padding around it, clamped to `max_width`.
fn frame_borderless(
    content: &Rendered,
    opts: &BoxOpts,
    max_width: usize,
) -> Rendered {
    let area_width = compute_area_width(content, opts, max_width);
    let content_area =
        area_width.saturating_sub(opts.padding.horizontal() as usize);
    let mut lines = Vec::new();
    for _ in 0..opts.padding.top {
        lines.push(blank_line(area_width, opts.fill));
    }
    for line in &content.lines {
        lines.push(inner_row(line, opts, content_area));
    }
    for _ in 0..opts.padding.bottom {
        lines.push(blank_line(area_width, opts.fill));
    }
    Rendered::new(lines)
}

#[cfg(test)]
mod tests {
    use super::*;

    fn plain(rendered: &Rendered) -> Vec<String> {
        rendered.lines.iter().map(Line::plain).collect()
    }

    #[test]
    fn panel_frames_content_with_border() {
        let panel = Panel::new("hi").border(BorderType::Single);
        let lines = plain(&panel.render(40));
        assert_eq!(lines.len(), 3);
        assert!(lines[0].starts_with(''));
        assert!(lines[1].contains("hi"));
        assert!(lines[2].starts_with(''));
    }

    #[test]
    fn panel_embeds_title_in_top_border() {
        let panel = Panel::new("body")
            .border(BorderType::Single)
            .title(Title::new("Info"));
        let lines = plain(&panel.render(40));
        assert!(lines[0].contains("Info"));
    }

    #[test]
    fn left_title_reads_as_part_of_the_border() {
        // With slack around the title, a left-aligned title keeps one
        // connecting glyph between the corner and the title, so the top border
        // reads `┌─ Info ─` rather than a flush `┌ Info ─`.
        let panel = Panel::new("a wide body of content")
            .border(BorderType::Single)
            .title(Title::new("Info"));
        let lines = plain(&panel.render(40));
        assert!(lines[0].starts_with("\u{250c}\u{2500} Info "));
    }

    #[test]
    fn borderless_panel_only_pads() {
        let panel = Panel::new("x")
            .border(BorderType::None)
            .padding(Edges::all(1));
        let lines = plain(&panel.render(40));
        assert_eq!(lines.len(), 3);
        assert_eq!(lines[1], " x ");
    }

    #[test]
    fn fixed_width_is_clamped_to_max_width() {
        // A fixed width wider than the terminal is capped so the border fits.
        let panel = Panel::new("hi").border(BorderType::Single).width(200);
        let lines = plain(&panel.render(80));
        assert_eq!(lines[0].chars().count(), 80);
        assert_eq!(lines[2].chars().count(), 80);
    }

    #[test]
    fn overflowing_content_shrinks_the_frame() {
        // Natural content wider than max_width shrinks the frame instead of
        // overflowing the border edges.
        let panel =
            Panel::new("abcdefghijklmnopqrstuvwxyz").border(BorderType::Single);
        let lines = plain(&panel.render(12));
        assert_eq!(lines[0].chars().count(), 12);
    }

    #[test]
    fn overlong_title_is_truncated_not_widened() {
        // A title too wide for the interior is truncated into the border run
        // rather than widening the frame.
        let panel = Panel::new("x")
            .border(BorderType::Single)
            .title(Title::new("A very long title here"));
        let lines = plain(&panel.render(20));
        assert!(lines[0].chars().count() <= 20);
        assert!(lines[0].contains(''));
    }
}