richrs 0.2.1

A Rust port of the Rich Python 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
//! Rule component for horizontal dividers.
//!
//! Rules draw horizontal lines across the terminal, optionally
//! with a centered title.

use crate::errors::Result;
use crate::measure::{Measurable, MeasureOptions, Measurement, cell_len};
use crate::segment::{Segment, Segments};
use crate::style::Style;
use crate::text::{Justify, Text};
use serde::{Deserialize, Serialize};

/// A horizontal rule/divider.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct Rule {
    /// Optional title displayed in the rule.
    title: Option<Text>,
    /// Character used for the rule line.
    character: char,
    /// Style for the rule line.
    style: Option<Style>,
    /// Style for the title.
    title_style: Option<Style>,
    /// Title alignment.
    align: Justify,
    /// End character (optional).
    end: Option<String>,
}

impl Rule {
    /// Creates a new rule without a title.
    #[inline]
    #[must_use]
    pub fn new() -> Self {
        Self {
            title: None,
            character: '',
            style: None,
            title_style: None,
            align: Justify::Center,
            end: None,
        }
    }

    /// Creates a rule with a title.
    #[inline]
    #[must_use]
    pub fn with_title(title: impl Into<Text>) -> Self {
        Self {
            title: Some(title.into()),
            character: '',
            style: None,
            title_style: None,
            align: Justify::Center,
            end: None,
        }
    }

    /// Sets the rule character.
    #[inline]
    #[must_use]
    pub const fn character(mut self, ch: char) -> Self {
        self.character = ch;
        self
    }

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

    /// Sets the title style.
    #[inline]
    #[must_use]
    pub fn title_style(mut self, style: Style) -> Self {
        self.title_style = Some(style);
        self
    }

    /// Sets the title alignment.
    #[inline]
    #[must_use]
    pub const fn align(mut self, align: Justify) -> Self {
        self.align = align;
        self
    }

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

    /// Renders the rule to segments.
    #[must_use]
    pub fn render(&self, width: usize) -> Segments {
        let mut segments = Segments::new();

        match &self.title {
            Some(title) => {
                let title_text = title.plain();
                let title_width = cell_len(title_text);

                // Space needed for title with padding
                let padding_width: usize = 2; // Space on each side of title
                let min_line_width: usize = 1; // Minimum line on each side

                if title_width
                    .saturating_add(padding_width.saturating_mul(2))
                    .saturating_add(min_line_width.saturating_mul(2))
                    > width
                {
                    // Not enough space, just render the line
                    self.render_line(&mut segments, width);
                } else {
                    // Calculate line widths based on alignment
                    let available = width
                        .saturating_sub(title_width)
                        .saturating_sub(padding_width.saturating_mul(2));
                    let (left_width, right_width) = match self.align {
                        Justify::Left | Justify::Default => {
                            (min_line_width, available.saturating_sub(min_line_width))
                        }
                        Justify::Right => {
                            (available.saturating_sub(min_line_width), min_line_width)
                        }
                        Justify::Center | Justify::Full => {
                            let half = available.checked_div(2).unwrap_or(0);
                            (half, available.saturating_sub(half))
                        }
                    };

                    // Left line
                    self.render_line(&mut segments, left_width);

                    // Space before title
                    segments.push(Segment::new(" "));

                    // Title
                    let title_segments = title.to_segments();
                    if let Some(ref style) = self.title_style {
                        for seg in title_segments.iter() {
                            let combined = seg
                                .style
                                .clone()
                                .map(|s| s.combine(style))
                                .unwrap_or_else(|| style.clone());
                            segments.push(Segment::styled(seg.text.clone(), combined));
                        }
                    } else {
                        segments.extend(title_segments);
                    }

                    // Space after title
                    segments.push(Segment::new(" "));

                    // Right line
                    self.render_line(&mut segments, right_width);
                }
            }
            None => {
                self.render_line(&mut segments, width);
            }
        }

        // End string (typically newline)
        if let Some(ref end_str) = self.end {
            segments.push(Segment::new(end_str.clone()));
        } else {
            segments.push(Segment::newline());
        }

        segments
    }

    /// Renders a line segment.
    fn render_line(&self, segments: &mut Segments, width: usize) {
        let line = self.character.to_string().repeat(width);
        if let Some(ref style) = self.style {
            segments.push(Segment::styled(line, style.clone()));
        } else {
            segments.push(Segment::new(line));
        }
    }
}

impl Default for Rule {
    fn default() -> Self {
        Self::new()
    }
}

impl Measurable for Rule {
    fn measure(&self, options: &MeasureOptions) -> Result<Measurement> {
        // Rules always expand to fill available width
        Ok(Measurement::fixed(options.max_width))
    }
}

#[cfg(test)]
mod tests {
    #![allow(clippy::unwrap_used)]
    use super::*;
    use crate::color::{Color, StandardColor};

    #[test]
    fn test_rule_new() {
        let rule = Rule::new();
        assert!(rule.title.is_none());
        assert_eq!(rule.character, '');
    }

    #[test]
    fn test_rule_default() {
        let rule = Rule::default();
        assert!(rule.title.is_none());
        assert_eq!(rule.character, '');
        assert!(rule.style.is_none());
        assert!(rule.title_style.is_none());
    }

    #[test]
    fn test_rule_with_title() {
        let rule = Rule::with_title("Test");
        assert!(rule.title.is_some());
    }

    #[test]
    fn test_rule_with_title_text() {
        let text = Text::from("Title");
        let rule = Rule::with_title(text);
        assert!(rule.title.is_some());
    }

    #[test]
    fn test_rule_render() {
        let rule = Rule::new();
        let segments = rule.render(40);
        let text = segments.plain_text();
        assert_eq!(text.trim(), "".repeat(40));
    }

    #[test]
    fn test_rule_render_with_title() {
        let rule = Rule::with_title("Title");
        let segments = rule.render(40);
        let text = segments.plain_text();
        assert!(text.contains("Title"));
        assert!(text.contains(''));
    }

    #[test]
    fn test_rule_character() {
        let rule = Rule::new().character('=');
        let segments = rule.render(20);
        let text = segments.plain_text();
        assert!(text.contains('='));
    }

    #[test]
    fn test_rule_character_asterisk() {
        let rule = Rule::new().character('*');
        let segments = rule.render(10);
        let text = segments.plain_text();
        assert!(text.contains('*'));
    }

    #[test]
    fn test_rule_style() {
        let style = Style::new()
            .bold()
            .with_color(Color::Standard(StandardColor::Red));
        let rule = Rule::new().style(style);
        let segments = rule.render(20);
        // Just check it renders without error
        assert!(!segments.is_empty());
    }

    #[test]
    fn test_rule_title_style() {
        let style = Style::new()
            .bold()
            .with_color(Color::Standard(StandardColor::Blue));
        let rule = Rule::with_title("Title").title_style(style);
        let segments = rule.render(40);
        let text = segments.plain_text();
        assert!(text.contains("Title"));
    }

    #[test]
    fn test_rule_title_with_existing_style() {
        // Title already has a style, and we apply title_style on top
        let title = Text::from("Title");
        let title_style = Style::new().bold();
        let rule = Rule::with_title(title).title_style(title_style);
        let segments = rule.render(40);
        let text = segments.plain_text();
        assert!(text.contains("Title"));
    }

    #[test]
    fn test_rule_align_left() {
        let rule = Rule::with_title("Title").align(Justify::Left);
        let segments = rule.render(40);
        let text = segments.plain_text();
        assert!(text.contains("Title"));
    }

    #[test]
    fn test_rule_align_right() {
        let rule = Rule::with_title("Title").align(Justify::Right);
        let segments = rule.render(40);
        let text = segments.plain_text();
        assert!(text.contains("Title"));
    }

    #[test]
    fn test_rule_align_center() {
        let rule = Rule::with_title("Title").align(Justify::Center);
        let segments = rule.render(40);
        let text = segments.plain_text();
        assert!(text.contains("Title"));
    }

    #[test]
    fn test_rule_align_full() {
        let rule = Rule::with_title("Title").align(Justify::Full);
        let segments = rule.render(40);
        let text = segments.plain_text();
        assert!(text.contains("Title"));
    }

    #[test]
    fn test_rule_align_default() {
        let rule = Rule::with_title("Title").align(Justify::Default);
        let segments = rule.render(40);
        let text = segments.plain_text();
        assert!(text.contains("Title"));
    }

    #[test]
    fn test_rule_end() {
        let rule = Rule::new().end("");
        let segments = rule.render(20);
        let text = segments.plain_text();
        // Without newline at end
        assert!(!text.ends_with('\n'));
    }

    #[test]
    fn test_rule_end_custom() {
        let rule = Rule::new().end("\r\n");
        let segments = rule.render(20);
        let text = segments.plain_text();
        assert!(text.ends_with("\r\n"));
    }

    #[test]
    fn test_rule_narrow_width() {
        // When width is too small for title, just render the line
        let rule = Rule::with_title("Very Long Title That Won't Fit");
        let segments = rule.render(10);
        let text = segments.plain_text();
        // Should just render the line without title
        assert!(!text.contains("Title"));
    }

    #[test]
    fn test_rule_measure() {
        let rule = Rule::new();
        let options = MeasureOptions::new(80);
        let measurement = rule.measure(&options).unwrap();
        assert_eq!(measurement.minimum, 80);
        assert_eq!(measurement.maximum, 80);
    }

    #[test]
    fn test_rule_measure_narrow() {
        let rule = Rule::with_title("Test");
        let options = MeasureOptions::new(20);
        let measurement = rule.measure(&options).unwrap();
        assert_eq!(measurement.minimum, 20);
    }

    #[test]
    fn test_rule_builder_chain() {
        let rule = Rule::with_title("Section")
            .character('=')
            .style(Style::new().bold())
            .title_style(Style::new().italic())
            .align(Justify::Left)
            .end("");

        let segments = rule.render(50);
        let text = segments.plain_text();
        assert!(text.contains("Section"));
        assert!(text.contains('='));
    }
}