gilt 2.3.1

Fast, beautiful terminal formatting for Rust — styles, tables, trees, syntax highlighting, progress bars, markdown.
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
//! Padding widget -- adds whitespace around renderable content.
//!

use crate::console::{Console, ConsoleOptions, Renderable, RenderableArc};
use crate::measure::Measurement;
use crate::segment::Segment;
use crate::style::Style;

// ---------------------------------------------------------------------------
// PaddingDimensions
// ---------------------------------------------------------------------------

/// CSS-style padding specification.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum PaddingDimensions {
    /// Same padding on all four sides.
    Uniform(usize),
    /// (vertical, horizontal) -- top & bottom share first, left & right share second.
    Pair(usize, usize),
    /// (top, right, bottom, left) -- explicit per-side.
    Full(usize, usize, usize, usize),
}

impl PaddingDimensions {
    /// Unpack any variant into `(top, right, bottom, left)`.
    pub fn unpack(&self) -> (usize, usize, usize, usize) {
        match *self {
            PaddingDimensions::Uniform(v) => (v, v, v, v),
            PaddingDimensions::Pair(vert, horiz) => (vert, horiz, vert, horiz),
            PaddingDimensions::Full(t, r, b, l) => (t, r, b, l),
        }
    }
}

impl From<usize> for PaddingDimensions {
    fn from(n: usize) -> Self {
        PaddingDimensions::Uniform(n)
    }
}

impl From<(usize, usize)> for PaddingDimensions {
    fn from((v, h): (usize, usize)) -> Self {
        PaddingDimensions::Pair(v, h)
    }
}

impl From<(usize, usize, usize, usize)> for PaddingDimensions {
    fn from((t, r, b, l): (usize, usize, usize, usize)) -> Self {
        PaddingDimensions::Full(t, r, b, l)
    }
}

/// CSS-style 1-element array: uniform padding on all four sides.
///
/// Matches the existing [`From<usize>`] semantics: `[n]` is identical to
/// `n` or `(n, n, n, n)`.
impl From<[usize; 1]> for PaddingDimensions {
    fn from([n]: [usize; 1]) -> Self {
        PaddingDimensions::Uniform(n)
    }
}

// ---------------------------------------------------------------------------
// Padding
// ---------------------------------------------------------------------------

/// A renderable that adds whitespace padding around renderable content.
#[derive(Clone)]
pub struct Padding {
    /// The inner content to pad (any renderable widget).
    pub content: RenderableArc,
    /// Top padding (blank lines above content).
    pub top: usize,
    /// Right padding (spaces after each content line).
    pub right: usize,
    /// Bottom padding (blank lines below content).
    pub bottom: usize,
    /// Left padding (spaces before each content line).
    pub left: usize,
    /// Style applied to the padding whitespace.
    pub style: Style,
    /// If true, expand to fill the available width.
    pub expand: bool,
}

// Manual Debug — RenderableArc (Arc<dyn Renderable + Send + Sync>) doesn't
// implement Debug, so we print a placeholder for the content field.
impl std::fmt::Debug for Padding {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.debug_struct("Padding")
            .field("content", &"<renderable>")
            .field("top", &self.top)
            .field("right", &self.right)
            .field("bottom", &self.bottom)
            .field("left", &self.left)
            .field("style", &self.style)
            .field("expand", &self.expand)
            .finish()
    }
}

impl Padding {
    /// Wrap content in padding with default style and `expand: true`.
    /// `pad` accepts `usize` (uniform), `(v, h)`, or `(t, r, b, l)`. For
    /// styled padding background or `expand: false`, use [`new`](Self::new).
    ///
    /// ```
    /// # use gilt::{padding::Padding, text::Text, style::Style};
    /// let p = Padding::wrap(Text::new("Hello", Style::null()), (2, 4));
    /// ```
    pub fn wrap(
        content: impl Renderable + Send + Sync + 'static,
        pad: impl Into<PaddingDimensions>,
    ) -> Self {
        Self::new(content, pad.into(), Style::null(), true)
    }

    /// Create a new `Padding` around the given content.
    pub fn new(
        content: impl Renderable + Send + Sync + 'static,
        pad: PaddingDimensions,
        style: Style,
        expand: bool,
    ) -> Self {
        let (top, right, bottom, left) = pad.unpack();
        Padding {
            content: std::sync::Arc::new(content),
            top,
            right,
            bottom,
            left,
            style,
            expand,
        }
    }

    /// Convenience: create padding that acts as a left-indent.
    pub fn indent(content: impl Renderable + Send + Sync + 'static, level: usize) -> Self {
        Padding::new(
            content,
            PaddingDimensions::Full(0, 0, 0, level),
            Style::null(),
            true,
        )
    }

    /// Measure the minimum and maximum width requirements.
    pub fn measure(&self, console: &Console, options: &ConsoleOptions) -> Measurement {
        let max_width = options.max_width.saturating_sub(self.left + self.right);
        let inner_opts = options.update_width(max_width.max(1));
        let content_width = self.content.gilt_measure(console, &inner_opts).maximum;
        let min_w = content_width + self.left + self.right;
        let max_w = if self.expand {
            options.max_width
        } else {
            min_w.min(options.max_width)
        };
        Measurement::new(
            min_w.min(inner_opts.max_width + self.left + self.right),
            max_w,
        )
    }
}

impl Renderable for Padding {
    fn gilt_measure(&self, console: &Console, options: &ConsoleOptions) -> Measurement {
        self.measure(console, options)
    }

    fn gilt_console(&self, console: &Console, options: &ConsoleOptions) -> Vec<Segment> {
        let mut segments = Vec::new();

        // Compute the total available width
        let inner_width_for_measure = options
            .max_width
            .saturating_sub(self.left + self.right)
            .max(1);
        let width = if self.expand {
            options.max_width
        } else {
            let measure_opts = options.update_width(inner_width_for_measure);
            let content_width = self.content.gilt_measure(console, &measure_opts).maximum;
            (content_width + self.left + self.right).min(options.max_width)
        };

        // Compute inner width for the content
        let inner_width = width.saturating_sub(self.left + self.right).max(1);

        // Render the content into lines
        let inner_opts = options.update_width(inner_width);
        let lines =
            console.render_lines(self.content.as_ref(), Some(&inner_opts), None, true, false);

        // Left/right padding strings
        let left_pad = " ".repeat(self.left);
        let right_pad_base = self.right;

        // Top blank lines
        let blank_line = " ".repeat(width);
        for _ in 0..self.top {
            segments.push(Segment::styled(&blank_line, self.style.clone()));
            segments.push(Segment::line());
        }

        // Content lines with left/right padding
        for line in &lines {
            // Left padding
            if self.left > 0 {
                segments.push(Segment::styled(&left_pad, self.style.clone()));
            }

            // Content segments
            segments.extend(line.iter().cloned());

            // Right padding -- fill remaining space to reach full width
            let line_len = self.left + Segment::get_line_length(line);
            let remaining = width.saturating_sub(line_len);
            if remaining > 0 {
                segments.push(Segment::styled(&" ".repeat(remaining), self.style.clone()));
            } else if right_pad_base > 0 && remaining == 0 {
                // Content exactly fills; no extra padding needed
            }

            segments.push(Segment::line());
        }

        // Bottom blank lines
        for _ in 0..self.bottom {
            segments.push(Segment::styled(&blank_line, self.style.clone()));
            segments.push(Segment::line());
        }

        segments
    }
}

// ---------------------------------------------------------------------------
// Tests
// ---------------------------------------------------------------------------

#[cfg(test)]
mod tests {
    use super::*;
    use crate::text::Text;
    use crate::utils::cells::cell_len;

    // -- PaddingDimensions --------------------------------------------------

    #[test]
    fn test_unpack_uniform() {
        let pd = PaddingDimensions::Uniform(2);
        assert_eq!(pd.unpack(), (2, 2, 2, 2));
    }

    #[test]
    fn test_unpack_pair() {
        let pd = PaddingDimensions::Pair(1, 3);
        assert_eq!(pd.unpack(), (1, 3, 1, 3));
    }

    #[test]
    fn test_unpack_full() {
        let pd = PaddingDimensions::Full(1, 2, 3, 4);
        assert_eq!(pd.unpack(), (1, 2, 3, 4));
    }

    #[test]
    fn test_unpack_uniform_zero() {
        let pd = PaddingDimensions::Uniform(0);
        assert_eq!(pd.unpack(), (0, 0, 0, 0));
    }

    // -- Plan 7.18 Task 3: From<[usize; 1]> --------------------------------

    #[test]
    fn test_from_array1_uniform_padding() {
        // CSS-style 1-element array means uniform padding on all four sides,
        // matching the existing From<usize> and From<(usize,usize,usize,usize)>
        // semantics (the variant may differ — Uniform vs Full — but the
        // unpacked (t, r, b, l) is identical).
        let pd: PaddingDimensions = [3].into();
        assert_eq!(
            pd,
            PaddingDimensions::Uniform(3),
            "[3].into() must equal Uniform(3) (matches From<usize> of 3)"
        );
        assert_eq!(pd.unpack(), (3, 3, 3, 3));

        // Semantically identical to both From<usize> and the explicit 4-tuple.
        let pd_uniform: PaddingDimensions = 3usize.into();
        assert_eq!(pd, pd_uniform);
        let pd_full: PaddingDimensions = (3, 3, 3, 3).into();
        assert_eq!(pd.unpack(), pd_full.unpack());
    }

    #[test]
    fn test_from_array1_zero() {
        // Zero is a valid uniform padding (no padding at all).
        let pd: PaddingDimensions = [0].into();
        assert_eq!(pd, PaddingDimensions::Uniform(0));
        assert_eq!(pd.unpack(), (0, 0, 0, 0));
    }

    // -- Padding construction -----------------------------------------------

    #[test]
    fn test_padding_new() {
        let text = Text::new("Hello", Style::null());
        let padding = Padding::new(
            text,
            PaddingDimensions::Full(1, 2, 3, 4),
            Style::null(),
            true,
        );
        assert_eq!(padding.top, 1);
        assert_eq!(padding.right, 2);
        assert_eq!(padding.bottom, 3);
        assert_eq!(padding.left, 4);
        assert!(padding.expand);
    }

    #[test]
    fn test_indent() {
        let text = Text::new("Hello", Style::null());
        let padding = Padding::indent(text, 4);
        assert_eq!(padding.top, 0);
        assert_eq!(padding.right, 0);
        assert_eq!(padding.bottom, 0);
        assert_eq!(padding.left, 4);
        assert!(padding.expand);
    }

    // -- Rendering ----------------------------------------------------------

    fn make_console(width: usize) -> Console {
        Console::builder()
            .width(width)
            .force_terminal(true)
            .no_color(true)
            .markup(false)
            .build()
    }

    fn segments_to_text(segments: &[Segment]) -> String {
        segments.iter().map(|s| s.text.as_str()).collect()
    }

    #[test]
    fn test_render_no_padding() {
        let console = make_console(20);
        let text = Text::new("Hello", Style::null());
        let padding = Padding::new(text, PaddingDimensions::Uniform(0), Style::null(), false);
        let opts = console.options();
        let segments = padding.gilt_console(&console, &opts);
        let output = segments_to_text(&segments);
        assert!(output.contains("Hello"));
    }

    #[test]
    fn test_render_with_left_padding() {
        let console = make_console(20);
        let text = Text::new("Hi", Style::null());
        let padding = Padding::new(
            text,
            PaddingDimensions::Full(0, 0, 0, 4),
            Style::null(),
            true,
        );
        let opts = console.options();
        let segments = padding.gilt_console(&console, &opts);
        let output = segments_to_text(&segments);
        // Should have 4 spaces before "Hi"
        assert!(output.contains("    Hi"));
    }

    #[test]
    fn test_render_top_bottom_padding() {
        let console = make_console(20);
        let text = Text::new("X", Style::null());
        let padding = Padding::new(
            text,
            PaddingDimensions::Full(2, 0, 3, 0),
            Style::null(),
            true,
        );
        let opts = console.options();
        let segments = padding.gilt_console(&console, &opts);
        let output = segments_to_text(&segments);
        let lines: Vec<&str> = output.split('\n').collect();
        // 2 top blank lines + 1 content line + 3 bottom blank lines = 6 lines
        // (each with a trailing newline, so split gives 7 with last empty)
        let non_empty_lines: Vec<&&str> = lines.iter().filter(|l| !l.is_empty()).collect();
        assert_eq!(non_empty_lines.len(), 6);
    }

    #[test]
    fn test_render_expand_fills_width() {
        let console = make_console(30);
        let text = Text::new("Hi", Style::null());
        let padding = Padding::new(text, PaddingDimensions::Uniform(1), Style::null(), true);
        let opts = console.options();
        let segments = padding.gilt_console(&console, &opts);
        let output = segments_to_text(&segments);
        let lines: Vec<&str> = output.split('\n').collect();
        // First non-empty line (top padding) should be 30 chars wide
        let top_line = lines[0];
        assert_eq!(cell_len(top_line), 30);
    }

    #[test]
    fn test_render_no_expand_minimal_width() {
        let console = make_console(80);
        let text = Text::new("AB", Style::null());
        let padding = Padding::new(
            text,
            PaddingDimensions::Full(0, 1, 0, 1),
            Style::null(),
            false,
        );
        let opts = console.options();
        let segments = padding.gilt_console(&console, &opts);
        let output = segments_to_text(&segments);
        // Width should be content(2) + left(1) + right(1) = 4
        let first_line: &str = output.split('\n').next().unwrap();
        assert_eq!(cell_len(first_line), 4);
    }

    #[test]
    fn test_indent_rendering() {
        let console = make_console(40);
        let text = Text::new("indented", Style::null());
        let padding = Padding::indent(text, 8);
        let opts = console.options();
        let segments = padding.gilt_console(&console, &opts);
        let output = segments_to_text(&segments);
        assert!(output.contains("        indented"));
    }

    #[test]
    fn test_measure() {
        let console = make_console(40);
        let text = Text::new("Hello", Style::null());
        let padding = Padding::new(
            text,
            PaddingDimensions::Full(0, 2, 0, 2),
            Style::null(),
            true,
        );
        let opts = console.options();
        let m = padding.measure(&console, &opts);
        // min: 5 + 2 + 2 = 9, max: 40 (expand)
        assert_eq!(m.minimum, 9);
        assert_eq!(m.maximum, 40);
    }

    #[test]
    fn test_measure_no_expand() {
        let console = make_console(40);
        let text = Text::new("Hello", Style::null());
        let padding = Padding::new(
            text,
            PaddingDimensions::Full(0, 2, 0, 2),
            Style::null(),
            false,
        );
        let opts = console.options();
        let m = padding.measure(&console, &opts);
        // min: 9, max: min(9, 40) = 9
        assert_eq!(m.maximum, 9);
    }

    #[test]
    fn test_padding_with_styled_content() {
        let console = make_console(20);
        let text = Text::styled("Bold", "bold");
        let padding = Padding::new(text, PaddingDimensions::Uniform(1), Style::null(), true);
        let opts = console.options();
        let segments = padding.gilt_console(&console, &opts);
        let plain: String = segments.iter().map(|s| s.text.as_str()).collect();
        assert!(plain.contains("Bold"));
    }

    #[test]
    fn test_padding_dimensions_equality() {
        assert_eq!(PaddingDimensions::Uniform(1), PaddingDimensions::Uniform(1));
        assert_ne!(PaddingDimensions::Uniform(1), PaddingDimensions::Uniform(2));
        assert_eq!(PaddingDimensions::Pair(1, 2), PaddingDimensions::Pair(1, 2));
        assert_ne!(PaddingDimensions::Pair(1, 2), PaddingDimensions::Pair(2, 1));
    }

    // -- gilt_measure override -----------------------------------------------

    #[test]
    fn padding_gilt_measure_matches_standalone() {
        let console = make_console(80);
        let opts = console.options();
        let text = Text::new("Hello", Style::null());
        let padding = Padding::new(
            text,
            PaddingDimensions::Full(0, 2, 0, 2),
            Style::null(),
            false,
        );
        let m_standalone = padding.measure(&console, &opts);
        let m_trait = padding.gilt_measure(&console, &opts);
        assert_eq!(
            m_trait, m_standalone,
            "Padding::gilt_measure must delegate to Padding::measure"
        );
    }

    #[test]
    fn padding_gilt_measure_expand_matches_standalone() {
        let console = make_console(80);
        let opts = console.options();
        let text = Text::new("Hello World", Style::null());
        let padding = Padding::new(text, PaddingDimensions::Uniform(1), Style::null(), true);
        let m_standalone = padding.measure(&console, &opts);
        let m_trait = padding.gilt_measure(&console, &opts);
        assert_eq!(
            m_trait, m_standalone,
            "Padding::gilt_measure expand must delegate to Padding::measure"
        );
    }

    // -- Task 4.5: RenderableArc constructor tests ---------------------------

    #[test]
    // Updated: constructors now accept impl Renderable + Send + Sync + 'static (Text still works via Renderable impl)
    fn padding_new_text_still_compiles() {
        let _ = Padding::new(
            Text::new("x", Style::null()),
            PaddingDimensions::Uniform(0),
            Style::null(),
            false,
        );
    }

    #[test]
    // Updated: constructors now accept impl Renderable + Send + Sync + 'static (Panel works too)
    fn padding_wrap_panel_compiles() {
        let p = crate::panel::Panel::new(Text::new("x", Style::null()));
        let _ = Padding::wrap(p, 1usize);
    }
}