urushi 0.1.1

Composable styling, components, and terminal rendering for Rust CLIs
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
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
//! The [`TextStyle`] builder: everything a terminal can express about a run of
//! text.

use crate::{Color, Hyperlink, TextAttribute, TextAttributes, Underline, UnderlineStyle};

/// A reusable set of text styling rules.
///
/// A `TextStyle` carries no geometry. A position that renders inline text cannot
/// honor padding, a border, or a dimension, so those properties live on
/// [`BlockStyle`](crate::BlockStyle) instead and the illegal combination is
/// unrepresentable rather than merely discouraged.
///
/// A `TextStyle` is an immutable value: builder methods consume and return it, so
/// styles can be stored, cloned, and extended without affecting each other.
///
/// ```
/// use urushi::{Color, TextStyle};
///
/// let base = TextStyle::new().foreground(Color::CYAN);
/// let emphasized = base.clone().bold();
///
/// let text = urushi::StyledText::new("hello", emphasized);
/// let _ = text;
/// ```
///
/// Geometry is not merely discouraged here, it is unrepresentable:
///
/// ```compile_fail
/// use urushi::{Border, TextStyle};
///
/// let _ = TextStyle::new().border(Border::ROUNDED);
/// ```
#[derive(Debug, Clone, Default, PartialEq, Eq)]
pub struct TextStyle {
    pub(crate) foreground: Option<Color>,
    pub(crate) background: Option<Color>,
    pub(crate) underline: Option<Underline>,
    pub(crate) hyperlink: Option<Hyperlink>,
    pub(crate) attributes: TextAttributes,
}

impl TextStyle {
    pub fn new() -> Self {
        Self::default()
    }

    /// Sets the text foreground color.
    pub fn foreground(mut self, color: impl Into<Color>) -> Self {
        self.foreground = Some(color.into());
        self
    }

    /// Returns the text foreground color to the terminal default.
    pub fn reset_foreground(mut self) -> Self {
        self.foreground = None;
        self
    }

    /// Sets the text background color.
    pub fn background(mut self, color: impl Into<Color>) -> Self {
        self.background = Some(color.into());
        self
    }

    /// Returns the text background color to the terminal default.
    pub fn reset_background(mut self) -> Self {
        self.background = None;
        self
    }

    /// Adds one active text attribute.
    pub fn add_attribute(mut self, attribute: TextAttribute) -> Self {
        self.attributes = self.attributes.union(attribute.into());
        self
    }

    /// Adds a set of active text attributes.
    pub fn add_attributes(mut self, attributes: TextAttributes) -> Self {
        self.attributes = self.attributes.union(attributes);
        self
    }

    /// Removes one active text attribute.
    pub fn remove_attribute(mut self, attribute: TextAttribute) -> Self {
        self.attributes = self.attributes.difference(attribute.into());
        self
    }

    /// Removes a set of active text attributes.
    pub fn remove_attributes(mut self, attributes: TextAttributes) -> Self {
        self.attributes = self.attributes.difference(attributes);
        self
    }

    /// Removes every active text attribute.
    pub fn reset_attributes(mut self) -> Self {
        self.attributes = TextAttributes::empty();
        self
    }

    pub fn bold(self) -> Self {
        self.add_attribute(TextAttribute::Bold)
    }

    pub fn dim(self) -> Self {
        self.add_attribute(TextAttribute::Dim)
    }

    pub fn italic(self) -> Self {
        self.add_attribute(TextAttribute::Italic)
    }

    /// Underlines the text with a single line in the foreground color.
    ///
    /// This sets the complete default underline value; the other two builders
    /// below refine an underline that may already be set.
    pub fn underlined(self) -> Self {
        self.underline(Underline::default())
    }

    /// Sets the shape the underline is drawn with, adding an underline in the
    /// foreground color when the style has none.
    pub fn underline_style(self, style: UnderlineStyle) -> Self {
        let mut underline = Underline::new(style);
        if let Some(color) = self.underline.and_then(Underline::get_color) {
            underline = underline.color(color);
        }
        self.underline(underline)
    }

    /// Sets the color the underline is drawn in, adding a single underline when
    /// the style has none.
    ///
    /// A color is only reachable through an underline, so a style cannot carry
    /// an underline color that nothing draws.
    pub fn underline_color(self, color: impl Into<Color>) -> Self {
        let underline = self.underline.unwrap_or_default().color(color.into());
        self.underline(underline)
    }

    /// Replaces the complete underline value.
    pub fn underline(mut self, underline: Underline) -> Self {
        self.underline = Some(underline);
        self
    }

    /// Removes the underline, including its color.
    pub fn reset_underline(mut self) -> Self {
        self.underline = None;
        self
    }

    /// Attaches an OSC 8 hyperlink to this text.
    ///
    /// A URI converts directly for the ordinary case. Use [`Hyperlink`] when
    /// the link needs parameters such as `id`.
    pub fn hyperlink(mut self, hyperlink: impl Into<Hyperlink>) -> Self {
        self.hyperlink = Some(hyperlink.into());
        self
    }

    /// Removes the OSC 8 hyperlink from this text.
    pub fn reset_hyperlink(mut self) -> Self {
        self.hyperlink = None;
        self
    }

    pub fn blink(self) -> Self {
        self.add_attribute(TextAttribute::SlowBlink)
    }

    pub fn reverse(self) -> Self {
        self.add_attribute(TextAttribute::Reversed)
    }

    pub fn hide(self) -> Self {
        self.add_attribute(TextAttribute::Hidden)
    }

    pub fn strikethrough(self) -> Self {
        self.add_attribute(TextAttribute::CrossedOut)
    }

    /// Returns the foreground color instruction, if this style sets one.
    pub const fn get_foreground(&self) -> Option<Color> {
        self.foreground
    }

    /// Returns the background color instruction, if this style sets one.
    pub const fn get_background(&self) -> Option<Color> {
        self.background
    }

    /// Returns the underline instruction, if this style sets one.
    pub const fn get_underline(&self) -> Option<Underline> {
        self.underline
    }

    /// Returns the hyperlink attached to this text, if any.
    pub fn get_hyperlink(&self) -> Option<&Hyperlink> {
        self.hyperlink.as_ref()
    }

    /// Returns the active text attributes.
    pub const fn get_attributes(&self) -> TextAttributes {
        self.attributes
    }

    pub(crate) fn overlay(mut self, contribution: &Self) -> Self {
        let Self {
            foreground,
            background,
            underline,
            hyperlink,
            attributes,
        } = contribution;
        if let Some(color) = foreground {
            self.foreground = Some(*color);
        }
        if let Some(color) = background {
            self.background = Some(*color);
        }
        if let Some(underline) = underline {
            self.underline = Some(*underline);
        }
        if let Some(hyperlink) = hyperlink {
            self.hyperlink = Some(hyperlink.clone());
        }
        self.attributes = self.attributes.union(*attributes);
        self
    }

    /// Folds values that cannot reach the output, so that two styles with the
    /// same appearance are the same value.
    ///
    /// One fold exists: an underline color equal to the foreground draws
    /// exactly what an absent one draws, since an absent one means "the
    /// foreground color". Nothing else is folded — a value is dropped only when
    /// doing so cannot change the output whatever the terminal does, which is
    /// why reversed video, whose equivalence assumes how a terminal implements
    /// `dim`, stays as written.
    ///
    /// Applied once the style is final: [`RenderSettings`](crate::RenderSettings)
    /// calls it as its last step, after degradation, because degradation is what
    /// makes two logical colors equal. A `TextStyle` is an immutable value built
    /// by consuming builders, so any earlier fold is undone by the next call that
    /// changes the foreground, which is why this is not part of the public
    /// builder surface.
    ///
    /// One residue is not closable: when the foreground is absent its concrete
    /// color is the terminal's default and unknown here, so an underline color
    /// equal to it cannot be recognized.
    pub(crate) fn canonical(mut self) -> Self {
        if let Some(underline) = self.underline
            && underline.get_color().is_some()
            && underline.get_color() == self.foreground
        {
            self.underline = Some(underline.reset_color());
        }
        self
    }

    /// Replaces every color property while preserving the rest of the style.
    pub(crate) fn map_colors(mut self, map: impl Fn(Color) -> Color) -> Self {
        self.foreground = self.foreground.map(&map);
        self.background = self.background.map(&map);
        self.underline = self.underline.map(|underline| {
            underline
                .get_color()
                .map(&map)
                .map_or_else(|| underline.reset_color(), |color| underline.color(color))
        });
        self
    }

    /// Removes every color while preserving attributes and the underline shape.
    ///
    /// An underline survives colorless render settings — it is a shape, not a
    /// color — but its color does not, exactly as a foreground does not.
    pub(crate) fn without_colors(mut self) -> Self {
        self.foreground = None;
        self.background = None;
        self.underline = self.underline.map(Underline::reset_color);
        self
    }
}

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

    #[test]
    fn named_operations_preserve_effective_value_semantics() {
        let style = TextStyle::new()
            .bold()
            .add_attribute(TextAttribute::Italic)
            .foreground(Color::CYAN)
            .remove_attribute(TextAttribute::Italic)
            .reset_foreground();

        assert_eq!(style.get_attributes(), TextAttribute::Bold.into());
        assert_eq!(style.get_foreground(), None);
    }

    #[test]
    fn reset_builders_restore_every_property_default() {
        let style = TextStyle::new()
            .foreground(Color::RED)
            .background(Color::BLUE)
            .add_attributes(TextAttribute::Bold | TextAttribute::Italic)
            .underline_color(Color::GREEN)
            .hyperlink("https://example.com")
            .reset_foreground()
            .reset_background()
            .reset_attributes()
            .reset_underline()
            .reset_hyperlink();

        assert_eq!(style, TextStyle::new());
    }

    #[test]
    fn hyperlink_is_one_replaceable_and_removable_property() {
        let style = TextStyle::new()
            .hyperlink("https://first.example")
            .hyperlink(Hyperlink::new("https://second.example").parameter("id", "docs"));

        assert_eq!(
            style.get_hyperlink(),
            Some(&Hyperlink::new("https://second.example").parameter("id", "docs"))
        );
        assert_eq!(render_style(&style.reset_hyperlink(), "link"), "link");
    }

    #[test]
    fn hyperlink_scope_contains_sgr_and_closes_after_its_reset() {
        assert_eq!(
            render_style(
                &TextStyle::new()
                    .hyperlink(Hyperlink::new("https://example.com").parameter("id", "docs"))
                    .bold(),
                "link",
            ),
            "\x1b]8;id=docs;https://example.com\x1b\\\x1b[1mlink\x1b[0m\x1b]8;;\x1b\\"
        );
    }

    #[test]
    fn hyperlink_on_empty_text_emits_nothing() {
        assert_eq!(
            render_style(&TextStyle::new().hyperlink("https://example.com"), ""),
            ""
        );
    }

    #[test]
    fn multiline_hyperlink_closes_before_each_newline() {
        let style = TextStyle::new().hyperlink("https://example.com");
        let open = "\x1b]8;;https://example.com\x1b\\";
        let close = "\x1b]8;;\x1b\\";

        assert_eq!(
            render_style(&style, "first\n\nsecond\nthird\n"),
            format!("{open}first{close}\n\n{open}second{close}\n{open}third{close}\n")
        );
    }

    #[test]
    fn removing_an_attribute_removes_it_from_painted_value() {
        let style = TextStyle::new()
            .bold()
            .dim()
            .remove_attribute(TextAttribute::Bold);

        assert_eq!(render_style(&style, "text"), "\x1b[2mtext\x1b[0m");
        assert_eq!(
            render_style(
                &TextStyle::new().remove_attributes(TextAttributes::all()),
                "text",
            ),
            "text"
        );
    }

    #[test]
    fn singleton_properties_replace_and_remove_to_defaults() {
        let style = TextStyle::new()
            .foreground(Color::RED)
            .foreground(Color::BLUE)
            .background(Color::GREEN)
            .reset_background();

        assert_eq!(style.get_foreground(), Some(Color::BLUE));
        assert_eq!(style.get_background(), None);
    }

    #[test]
    fn every_underline_shape_paints_its_own_sgr_parameter() {
        let painted = [
            UnderlineStyle::Single,
            UnderlineStyle::Double,
            UnderlineStyle::Curly,
            UnderlineStyle::Dotted,
            UnderlineStyle::Dashed,
        ]
        .map(|style| render_style(&TextStyle::new().underline_style(style), "t"));

        assert_eq!(
            painted,
            [
                "\x1b[4mt\x1b[0m",
                "\x1b[4:2mt\x1b[0m",
                "\x1b[4:3mt\x1b[0m",
                "\x1b[4:4mt\x1b[0m",
                "\x1b[4:5mt\x1b[0m",
            ]
        );
    }

    #[test]
    fn an_underline_color_paints_sgr_fifty_eight_in_its_indexed_or_rgb_form() {
        assert_eq!(
            render_style(&TextStyle::new().underline_color(Color::RED), "t"),
            "\x1b[4;58;5;1mt\x1b[0m"
        );
        assert_eq!(
            render_style(&TextStyle::new().underline_color(Color::Ansi256(212)), "t",),
            "\x1b[4;58;5;212mt\x1b[0m"
        );
        assert_eq!(
            render_style(
                &TextStyle::new()
                    .underline_style(UnderlineStyle::Curly)
                    .underline_color(Color::Rgb(1, 2, 3)),
                "t",
            ),
            "\x1b[4:3;58;2;1;2;3mt\x1b[0m"
        );
    }

    #[test]
    fn an_absent_underline_color_paints_no_underline_color_parameter() {
        // A style holds effective values and text rendering closes with a reset, so
        // the terminal default is expressed by emitting nothing — there is no
        // SGR 59 to restore it, and no color to spell it with.
        let painted = render_style(
            &TextStyle::new()
                .foreground(Color::RED)
                .underline_style(UnderlineStyle::Double),
            "t",
        );

        assert_eq!(painted, "\x1b[4:2;31mt\x1b[0m");
        assert!(!painted.contains("58"));
        assert!(!painted.contains("59"));
    }

    #[test]
    fn hidden_paints_sgr_eight() {
        assert_eq!(
            render_style(&TextStyle::new().hide(), "t"),
            "\x1b[8mt\x1b[0m"
        );
        assert_eq!(
            render_style(
                &TextStyle::new()
                    .hide()
                    .add_attribute(TextAttribute::Reversed),
                "t",
            ),
            "\x1b[7;8mt\x1b[0m"
        );
    }

    #[test]
    fn shared_terminal_attributes_keep_their_ansi_meaning() {
        let attributes = TextAttribute::RapidBlink
            | TextAttribute::Fraktur
            | TextAttribute::Framed
            | TextAttribute::Encircled
            | TextAttribute::Overlined;

        assert_eq!(
            render_style(&TextStyle::new().add_attributes(attributes), "t"),
            "\x1b[6;20;51;52;53mt\x1b[0m"
        );
    }

    #[test]
    fn an_underline_color_is_only_reachable_through_an_underline() {
        // Setting a color on a style with no underline adds the underline that
        // draws it, so "invisible underline color" is not a value that exists.
        let style = TextStyle::new().underline_color(Color::RED);

        assert_eq!(
            style.get_underline(),
            Some(Underline::default().color(Color::RED))
        );
        assert_eq!(
            render_style(
                &TextStyle::new()
                    .underline_color(Color::RED)
                    .reset_underline(),
                "t",
            ),
            "t"
        );
    }

    #[test]
    fn setting_a_shape_keeps_the_color_and_setting_a_color_keeps_the_shape() {
        let expected = Some(Underline::new(UnderlineStyle::Dotted).color(Color::GREEN));

        assert_eq!(
            TextStyle::new()
                .underline_color(Color::GREEN)
                .underline_style(UnderlineStyle::Dotted)
                .get_underline(),
            expected
        );
        assert_eq!(
            TextStyle::new()
                .underline_style(UnderlineStyle::Dotted)
                .underline_color(Color::GREEN)
                .get_underline(),
            expected
        );
        assert_eq!(
            TextStyle::new()
                .underline_color(Color::RED)
                .underline(Underline::new(UnderlineStyle::Double))
                .get_underline(),
            Some(Underline::new(UnderlineStyle::Double))
        );
    }

    #[test]
    fn canonical_folds_an_underline_color_equal_to_the_foreground() {
        let folded = TextStyle::new()
            .foreground(Color::RED)
            .underline_style(UnderlineStyle::Curly)
            .underline_color(Color::RED)
            .canonical();

        assert_eq!(
            folded,
            TextStyle::new()
                .foreground(Color::RED)
                .underline_style(UnderlineStyle::Curly)
        );
        assert_eq!(render_style(&folded, "t"), "\x1b[4:3;31mt\x1b[0m");
    }

    #[test]
    fn canonical_folds_only_what_the_terminal_cannot_draw_differently() {
        // Equal appearance is not the admission rule: a color the terminal
        // resolves separately is not folded, and neither is reversed video,
        // whose equivalence assumes how a terminal implements `dim`.
        let distinct_spellings = TextStyle::new()
            .foreground(Color::Ansi(1))
            .underline_color(Color::Rgb(255, 0, 0));
        let reversed = TextStyle::new()
            .foreground(Color::RED)
            .background(Color::BLUE)
            .reverse();

        assert_eq!(
            distinct_spellings.clone().canonical(),
            distinct_spellings.clone()
        );
        assert_eq!(reversed.clone().canonical(), reversed);
        // An absent foreground is the terminal's default, whose concrete color
        // is unknown here, so a matching underline color cannot be recognized.
        let default_foreground = TextStyle::new().underline_color(Color::RED);
        assert_eq!(
            default_foreground.clone().canonical(),
            default_foreground.clone()
        );
    }
}