rich_rust 0.2.1

A Rust port of Python's Rich library for beautiful terminal output
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
//! Rule - horizontal line with optional title.
//!
//! A Rule renders as a horizontal line that spans the console width,
//! optionally with a centered (or aligned) title.

use crate::cells;
use crate::console::{Console, ConsoleOptions};
use crate::renderables::Renderable;
use crate::segment::Segment;
use crate::style::Style;
use crate::text::{JustifyMethod, OverflowMethod, Text};

/// A horizontal rule with optional title.
#[derive(Debug, Clone)]
pub struct Rule {
    /// Optional title text.
    title: Option<Text>,
    /// Character to use for the rule line.
    character: String,
    /// Style for the rule line.
    style: Style,
    /// Title alignment.
    align: JustifyMethod,
}

impl Default for Rule {
    fn default() -> Self {
        Self {
            title: None,
            character: String::from("\u{2500}"), //            style: Style::parse("bright_green").unwrap_or_default(),
            align: JustifyMethod::Center,
        }
    }
}

impl Rule {
    /// Create a new rule without a title.
    #[must_use]
    pub fn new() -> Self {
        Self::default()
    }

    /// Create a rule with a title.
    #[must_use]
    pub fn with_title(title: impl Into<Text>) -> Self {
        Self {
            title: Some(title.into()),
            ..Self::default()
        }
    }

    /// Set the rule character.
    #[must_use]
    pub fn character(mut self, ch: impl Into<String>) -> Self {
        self.character = ch.into();
        self
    }

    /// Set the rule style.
    #[must_use]
    pub fn style(mut self, style: Style) -> Self {
        self.style = style;
        self
    }

    /// Set title alignment.
    #[must_use]
    pub fn align(mut self, align: JustifyMethod) -> Self {
        self.align = align;
        self
    }

    /// Left-align the title.
    #[must_use]
    pub fn align_left(self) -> Self {
        self.align(JustifyMethod::Left)
    }

    /// Center the title.
    #[must_use]
    pub fn align_center(self) -> Self {
        self.align(JustifyMethod::Center)
    }

    /// Right-align the title.
    #[must_use]
    pub fn align_right(self) -> Self {
        self.align(JustifyMethod::Right)
    }

    /// Render the rule to segments for a given width.
    #[must_use]
    pub fn render(&self, width: usize) -> Vec<Segment<'static>> {
        let char_width = cells::cell_len(&self.character);
        if char_width == 0 || width == 0 {
            return vec![Segment::line()];
        }

        let mut segments = Vec::new();

        if let Some(title) = &self.title {
            // Sanitize title to prevent broken layout
            let mut title = title.clone();
            if title.plain().contains('\n') {
                let sanitized = title.plain().replace('\n', " ");
                title = Text::new(sanitized);
            }

            if title.plain().is_empty() {
                let count = width / char_width;
                let rule_text = self.character.repeat(count);
                segments.push(Segment::new(rule_text, Some(self.style.clone())));
                segments.push(Segment::line());
                return segments;
            }

            let title_width = cells::cell_len(title.plain());
            let (left_pad, right_pad) = match self.align {
                JustifyMethod::Left => (0, 1),
                JustifyMethod::Right => (1, 0),
                JustifyMethod::Center | JustifyMethod::Full | JustifyMethod::Default => (1, 1),
            };
            let title_total_width = title_width
                .saturating_add(left_pad)
                .saturating_add(right_pad);

            if title_total_width > width {
                let mut truncated = title.clone();
                truncated.truncate(width, OverflowMethod::Crop, false);
                segments.extend(
                    truncated
                        .render("")
                        .into_iter()
                        .map(super::super::segment::Segment::into_owned),
                );
                segments.push(Segment::line());
                return segments;
            }

            // Calculate available space for rule characters
            let available = width.saturating_sub(title_total_width);
            let rule_chars = available / char_width;

            if rule_chars < 1 {
                // Not enough space for rule, just show title
                if left_pad > 0 {
                    segments.push(Segment::new(
                        " ".repeat(left_pad),
                        Some(title.style().clone()),
                    ));
                }
                segments.extend(
                    title
                        .render("")
                        .into_iter()
                        .map(super::super::segment::Segment::into_owned),
                );
                if right_pad > 0 {
                    segments.push(Segment::new(
                        " ".repeat(right_pad),
                        Some(title.style().clone()),
                    ));
                }
            } else {
                let (left_count, right_count) = match self.align {
                    JustifyMethod::Left => (0, rule_chars),
                    JustifyMethod::Right => (rule_chars, 0),
                    JustifyMethod::Center | JustifyMethod::Full => {
                        let left = rule_chars / 2;
                        let right = rule_chars - left;
                        (left, right)
                    }
                    JustifyMethod::Default => {
                        let left = rule_chars / 2;
                        let right = rule_chars - left;
                        (left, right)
                    }
                };

                // Left rule section
                if left_count > 0 {
                    let left_rule = self.character.repeat(left_count);
                    segments.push(Segment::new(left_rule, Some(self.style.clone())));
                }

                // Title with surrounding spaces
                if left_pad > 0 {
                    segments.push(Segment::new(
                        " ".repeat(left_pad),
                        Some(title.style().clone()),
                    ));
                }
                segments.extend(
                    title
                        .render("")
                        .into_iter()
                        .map(super::super::segment::Segment::into_owned),
                );
                if right_pad > 0 {
                    segments.push(Segment::new(
                        " ".repeat(right_pad),
                        Some(title.style().clone()),
                    ));
                }

                // Right rule section
                if right_count > 0 {
                    let right_rule = self.character.repeat(right_count);
                    segments.push(Segment::new(right_rule, Some(self.style.clone())));
                }
            }
        } else {
            // No title, just a full-width rule
            let count = width / char_width;
            let rule_text = self.character.repeat(count);
            segments.push(Segment::new(rule_text, Some(self.style.clone())));
        }

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

    /// Render the rule as a string (for simple output).
    #[must_use]
    pub fn render_plain(&self, width: usize) -> String {
        self.render(width)
            .into_iter()
            .map(|seg| seg.text.into_owned())
            .collect()
    }
}

impl Renderable for Rule {
    fn render<'a>(&'a self, _console: &Console, options: &ConsoleOptions) -> Vec<Segment<'a>> {
        self.render(options.max_width).into_iter().collect()
    }
}

/// Create an ASCII-safe rule.
#[must_use]
pub fn ascii_rule() -> Rule {
    Rule::new().character("-")
}

/// Create a double-line rule.
#[must_use]
pub fn double_rule() -> Rule {
    Rule::new().character("\u{2550}") //}

/// Create a heavy (thick) rule.
#[must_use]
pub fn heavy_rule() -> Rule {
    Rule::new().character("\u{2501}") //}

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

    #[test]
    fn test_rule_no_title() {
        let rule = Rule::new();
        let segments = rule.render(10);
        assert!(!segments.is_empty());
        let text: String = segments.iter().map(|s| s.text.as_ref()).collect();
        assert!(text.contains('\u{2500}')); //    }

    #[test]
    fn test_rule_with_title() {
        let rule = Rule::with_title("Test");
        let segments = rule.render(20);
        let text: String = segments.iter().map(|s| s.text.as_ref()).collect();
        assert!(text.contains("Test"));
        assert!(text.contains('\u{2500}')); //    }

    #[test]
    fn test_rule_custom_char() {
        let rule = Rule::new().character("=");
        let segments = rule.render(10);
        let text: String = segments.iter().map(|s| s.text.as_ref()).collect();
        assert!(text.contains('='));
    }

    #[test]
    fn test_rule_alignment() {
        let rule = Rule::with_title("X").align_left();
        let plain = rule.render_plain(20);
        // Left alignment: "X <rule chars>" - title at left edge with trailing space
        // Verify title is at the start (after trimming)
        let trimmed = plain.trim();
        assert!(
            trimmed.starts_with("X "),
            "Left-aligned title should start with 'X ', got: '{trimmed}'"
        );
        // Verify there are rule characters after the title
        assert!(trimmed.contains(''), "Should contain rule characters");
    }

    #[test]
    fn test_ascii_rule() {
        let rule = ascii_rule();
        let segments = rule.render(10);
        let text: String = segments.iter().map(|s| s.text.as_ref()).collect();
        assert!(text.contains('-'));
    }

    #[test]
    fn test_heavy_rule() {
        let rule = heavy_rule();
        let segments = rule.render(10);
        let text: String = segments.iter().map(|s| s.text.as_ref()).collect();
        assert!(text.contains('\u{2501}')); //    }

    #[test]
    fn test_double_rule() {
        let rule = double_rule();
        let segments = rule.render(10);
        let text: String = segments.iter().map(|s| s.text.as_ref()).collect();
        assert!(text.contains('\u{2550}')); //    }

    #[test]
    fn test_rule_width_zero() {
        let rule = Rule::new();
        let segments = rule.render(0);
        // Should handle zero width gracefully
        assert!(!segments.is_empty()); // At least a newline segment
    }

    #[test]
    fn test_rule_width_one() {
        let rule = Rule::new();
        let segments = rule.render(1);
        let text: String = segments.iter().map(|s| s.text.as_ref()).collect();
        // Width 1 should produce at least one rule char
        assert!(text.contains('\u{2500}') || text.is_empty() || text == "\n");
    }

    #[test]
    fn test_rule_title_narrow_width() {
        let rule = Rule::with_title("Very Long Title Text");
        let segments = rule.render(10);
        let text: String = segments.iter().map(|s| s.text.as_ref()).collect();
        // Should handle narrow width without panicking
        assert!(!text.is_empty());
    }

    #[test]
    fn test_rule_title_insufficient_space() {
        let rule = Rule::with_title("Test");
        // Width too small for title + surrounding rules
        let segments = rule.render(5);
        let text: String = segments.iter().map(|s| s.text.as_ref()).collect();
        // Should handle gracefully
        assert!(!text.is_empty());
    }

    #[test]
    fn test_rule_right_align() {
        let rule = Rule::with_title("X").align_right();
        let plain = rule.render_plain(20);
        // Right alignment: "<rule chars> X" - title at right edge with leading space
        // Verify title is at the end (after trimming)
        let trimmed = plain.trim();
        assert!(
            trimmed.ends_with(" X"),
            "Right-aligned title should end with ' X', got: '{trimmed}'"
        );
        // Verify there are rule characters before the title
        assert!(trimmed.contains(''), "Should contain rule characters");
    }

    #[test]
    fn test_rule_center_align() {
        let rule = Rule::with_title("Hi").align_center();
        let plain = rule.render_plain(20);
        // Title should be in center
        assert!(plain.contains(" Hi "));
    }

    #[test]
    fn test_rule_with_styled_title() {
        let title = Text::new("Styled");
        let rule = Rule::with_title(title);
        let segments = rule.render(20);
        let text: String = segments.iter().map(|s| s.text.as_ref()).collect();
        assert!(text.contains("Styled"));
    }

    #[test]
    fn test_rule_multi_char() {
        // Multi-character rule string
        let rule = Rule::new().character("=-");
        let segments = rule.render(10);
        let text: String = segments.iter().map(|s| s.text.as_ref()).collect();
        assert!(text.contains("=-"));
    }

    #[test]
    fn test_rule_fills_width_no_title() {
        let rule = Rule::new();
        let segments = rule.render(10);
        // Count rule characters (excluding control segments like newline)
        let text: String = segments
            .iter()
            .filter(|s| !s.is_control())
            .map(|s| s.text.as_ref())
            .collect();
        // The rule chars are repeated to fill width, minus any trailing newline
        let rule_width = cells::cell_len(&text);
        assert!(rule_width >= 10, "Rule should fill width: got {rule_width}");
    }
}