rs-rich 0.0.9

A faithful Rust port of the Python `rich` terminal-rendering library
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
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
//! Text styles.
//!
//! Port of upstream `rich/style.py` (core attributes). A [`Style`] holds an
//! optional foreground/background [`Color`] plus a set of boolean attributes
//! (bold, italic, …). Each attribute is tri-state: `Some(true)` = on,
//! `Some(false)` = explicitly off, `None` = unset — this preserves upstream's
//! `_set_attributes`/`_attributes` bitmask semantics under [`Style::combine`].

use crate::color::{Color, ColorSystem};
use crate::errors::{Result, RichError};

/// The 13 boolean attributes, in the SGR order upstream emits them.
const ATTR_COUNT: usize = 13;

/// SGR codes per attribute index (`rich.style._STYLE_MAP`).
const ATTR_SGR: [&str; ATTR_COUNT] = [
    "1", "2", "3", "4", "5", "6", "7", "8", "9", "21", "51", "52", "53",
];

/// Canonical attribute names per index.
const ATTR_NAMES: [&str; ATTR_COUNT] = [
    "bold",
    "dim",
    "italic",
    "underline",
    "blink",
    "blink2",
    "reverse",
    "conceal",
    "strike",
    "underline2",
    "frame",
    "encircle",
    "overline",
];

/// Map a style word (including upstream's short aliases) to its attribute index.
fn attribute_index(word: &str) -> Option<usize> {
    let canonical = match word {
        "b" => "bold",
        "d" => "dim",
        "i" => "italic",
        "u" => "underline",
        "r" => "reverse",
        "c" => "conceal",
        "s" => "strike",
        "uu" => "underline2",
        "o" => "overline",
        other => other,
    };
    ATTR_NAMES.iter().position(|&n| n == canonical)
}

/// A style, or the *name* of one to be looked up later. Port of upstream's
/// `StyleType = Union[str, "Style"]` (`rich/style.py`).
///
/// A [`Span`](crate::text::Span) that holds a [`Name`](StyleType::Name) is
/// resolved when it is rendered, against the theme of the console doing the
/// rendering — so the same [`Text`](crate::text::Text) printed to two differently
/// themed consoles comes out in two different colours, as it does upstream.
/// Resolving eagerly instead would freeze the colours at construction time.
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum StyleType {
    /// A theme key (`"repr.number"`) or a style definition (`"bold red"`),
    /// resolved by [`Theme::get_style`](crate::theme::Theme::get_style).
    Name(String),
    /// An already-resolved style.
    Style(Style),
}

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

impl StyleType {
    /// True when this is an already-resolved style that sets nothing. A
    /// [`Name`](StyleType::Name) is never null — it may resolve to anything.
    pub fn is_null_style(&self) -> bool {
        matches!(self, StyleType::Style(style) if style.is_null())
    }
}

impl From<Style> for StyleType {
    fn from(style: Style) -> Self {
        StyleType::Style(style)
    }
}

impl From<&Style> for StyleType {
    fn from(style: &Style) -> Self {
        StyleType::Style(style.clone())
    }
}

impl From<String> for StyleType {
    fn from(name: String) -> Self {
        StyleType::Name(name)
    }
}

impl From<&str> for StyleType {
    fn from(name: &str) -> Self {
        StyleType::Name(name.to_string())
    }
}

/// One value in a style's [`Meta`]. Upstream's meta is any marshal-able
/// Python value; this port keeps the scalar subset plus lists.
///
/// Equality follows marshal's bytes: `true` is not `1`, `1` is not `1.0`, and
/// floats compare by bit pattern (so `NaN == NaN` and `0.0 != -0.0`).
#[derive(Debug, Clone)]
pub enum MetaValue {
    /// Python `None`.
    None,
    Bool(bool),
    Int(i64),
    Float(f64),
    Str(String),
    /// A list or tuple of values.
    List(Vec<MetaValue>),
}

impl PartialEq for MetaValue {
    fn eq(&self, other: &Self) -> bool {
        match (self, other) {
            (MetaValue::None, MetaValue::None) => true,
            (MetaValue::Bool(a), MetaValue::Bool(b)) => a == b,
            (MetaValue::Int(a), MetaValue::Int(b)) => a == b,
            (MetaValue::Float(a), MetaValue::Float(b)) => a.to_bits() == b.to_bits(),
            (MetaValue::Str(a), MetaValue::Str(b)) => a == b,
            (MetaValue::List(a), MetaValue::List(b)) => a == b,
            _ => false,
        }
    }
}

impl Eq for MetaValue {}

impl std::hash::Hash for MetaValue {
    fn hash<H: std::hash::Hasher>(&self, state: &mut H) {
        std::mem::discriminant(self).hash(state);
        match self {
            MetaValue::None => {}
            MetaValue::Bool(value) => value.hash(state),
            MetaValue::Int(value) => value.hash(state),
            MetaValue::Float(value) => value.to_bits().hash(state),
            MetaValue::Str(value) => value.hash(state),
            MetaValue::List(values) => values.hash(state),
        }
    }
}

/// A style's metadata: upstream's `Style.meta` dict. Upstream stores it
/// marshal-encoded; this port keeps the entries themselves, **in insertion
/// order**, because marshal's bytes (and so style equality) depend on it.
/// Assigning an existing key replaces its value in place, as a `dict` does.
#[derive(Debug, Clone, PartialEq, Eq, Hash, Default)]
pub struct Meta {
    entries: Vec<(String, MetaValue)>,
}

impl Meta {
    /// An empty map.
    pub fn new() -> Self {
        Meta::default()
    }

    /// Set `key` (`meta[key] = value`).
    pub fn insert(&mut self, key: impl Into<String>, value: MetaValue) {
        let key = key.into();
        match self
            .entries
            .iter_mut()
            .find(|(existing, _)| *existing == key)
        {
            Some((_, slot)) => *slot = value,
            None => self.entries.push((key, value)),
        }
    }

    /// The value for `key`.
    pub fn get(&self, key: &str) -> Option<&MetaValue> {
        self.entries
            .iter()
            .find(|(existing, _)| existing == key)
            .map(|(_, value)| value)
    }

    /// Merge `other` in (`dict.update`): its values win.
    pub fn update(&mut self, other: &Meta) {
        for (key, value) in &other.entries {
            self.insert(key.clone(), value.clone());
        }
    }

    /// The entries in insertion order.
    pub fn iter(&self) -> impl Iterator<Item = (&str, &MetaValue)> {
        self.entries
            .iter()
            .map(|(key, value)| (key.as_str(), value))
    }

    pub fn len(&self) -> usize {
        self.entries.len()
    }

    pub fn is_empty(&self) -> bool {
        self.entries.is_empty()
    }
}

impl<K: Into<String>> FromIterator<(K, MetaValue)> for Meta {
    fn from_iter<I: IntoIterator<Item = (K, MetaValue)>>(iter: I) -> Self {
        let mut meta = Meta::new();
        for (key, value) in iter {
            meta.insert(key, value);
        }
        meta
    }
}

/// A terminal text style. Mirrors `rich.style.Style`.
#[derive(Debug, Clone, PartialEq, Eq, Default)]
pub struct Style {
    color: Option<Color>,
    bgcolor: Option<Color>,
    attrs: [Option<bool>; ATTR_COUNT],
    /// An OSC 8 hyperlink target, if any.
    link: Option<String>,
    /// Upstream's `_meta`: metadata that never renders but takes part in
    /// equality and combination (`None` is upstream's `_meta = None`).
    meta: Option<Meta>,
}

impl Style {
    /// The empty (null) style — sets nothing.
    pub fn new() -> Self {
        Style::default()
    }

    /// A style carrying only a foreground and/or background color.
    /// Port of `Style.from_color`.
    pub fn from_color(color: Option<Color>, bgcolor: Option<Color>) -> Self {
        Style {
            color,
            bgcolor,
            attrs: [None; ATTR_COUNT],
            link: None,
            meta: None,
        }
    }

    pub fn with_color(mut self, color: Color) -> Self {
        self.color = Some(color);
        self
    }

    /// Attach an OSC 8 hyperlink target. Port of `Style(link=…)`.
    pub fn with_link(mut self, url: impl Into<String>) -> Self {
        self.link = Some(url.into());
        self
    }

    /// The hyperlink target, if set.
    pub fn link(&self) -> Option<&str> {
        self.link.as_deref()
    }

    /// Return a copy with the hyperlink target set (`Some`) or cleared (`None`),
    /// leaving every other attribute unchanged. Port of `Style.update_link`.
    pub fn update_link(&self, link: Option<String>) -> Style {
        let mut style = self.clone();
        style.link = link;
        style
    }

    pub fn with_bgcolor(mut self, color: Color) -> Self {
        self.bgcolor = Some(color);
        self
    }

    pub fn color(&self) -> Option<&Color> {
        self.color.as_ref()
    }

    pub fn bgcolor(&self) -> Option<&Color> {
        self.bgcolor.as_ref()
    }

    /// A copy with the foreground and background colours removed; attributes
    /// and link survive. Port of `Style.without_color`.
    pub fn without_color(&self) -> Style {
        Style {
            color: None,
            bgcolor: None,
            attrs: self.attrs,
            link: self.link.clone(),
            meta: self.meta.clone(),
        }
    }

    /// The tri-state value of attribute `index` (see the internal `attrs` order:
    /// 0=bold, 1=dim, 2=italic, 3=underline, 6=reverse, 8=strike, …).
    pub fn attr(&self, index: usize) -> Option<bool> {
        self.attrs.get(index).copied().flatten()
    }

    /// True when nothing at all is set (renders as a no-op). Non-empty
    /// metadata counts, as upstream's `_null` includes `meta`.
    pub fn is_null(&self) -> bool {
        self.color.is_none()
            && self.bgcolor.is_none()
            && self.link.is_none()
            && self.meta.as_ref().is_none_or(Meta::is_empty)
            && self.attrs.iter().all(Option::is_none)
    }

    /// Attach metadata. Port of `Style(meta=…)`. An empty map leaves the style
    /// null, but it still differs from one with no metadata at all (upstream
    /// hashes the marshal-encoded `{}`).
    pub fn with_meta(mut self, meta: Meta) -> Self {
        self.meta = Some(meta);
        self
    }

    /// The metadata, empty when none is set. Port of the `Style.meta`
    /// property.
    pub fn meta(&self) -> Meta {
        self.meta.clone().unwrap_or_default()
    }

    /// The metadata as stored: `None` when the style carries none.
    pub fn meta_ref(&self) -> Option<&Meta> {
        self.meta.as_ref()
    }

    /// A style carrying only `meta`. Port of `Style.from_meta` (null when
    /// `meta` is empty). Upstream also gives it a random `link_id`, which
    /// this port does not model (see DIVERGENCES #20).
    pub fn from_meta(meta: Meta) -> Style {
        Style::new().with_meta(meta)
    }

    /// A style with event-handler metadata. Port of `Style.on`: each handler
    /// is stored as `"@name"` over `meta` (default empty).
    pub fn on(meta: Option<Meta>, handlers: &[(&str, MetaValue)]) -> Style {
        let mut meta = meta.unwrap_or_default();
        for (name, value) in handlers {
            meta.insert(format!("@{name}"), value.clone());
        }
        Style::from_meta(meta)
    }

    /// A copy without metadata or link. Port of `Style.clear_meta_and_links`.
    pub fn clear_meta_and_links(&self) -> Style {
        let mut style = self.clone();
        style.link = None;
        style.meta = None;
        style
    }

    /// Regenerate the style definition string. Port of `Style.__str__`.
    ///
    /// Attributes come first in their canonical order, then the foreground
    /// colour, then `on <bgcolour>`, then `link <url>`. A style that sets nothing
    /// is `"none"` — never the empty string, which upstream reserves for "no
    /// style at all".
    pub fn definition(&self) -> String {
        let mut parts: Vec<String> = Vec::new();
        for (index, name) in ATTR_NAMES.iter().enumerate() {
            match self.attrs[index] {
                Some(true) => parts.push((*name).to_string()),
                Some(false) => parts.push(format!("not {name}")),
                None => {}
            }
        }
        if let Some(color) = &self.color {
            parts.push(color.name.clone());
        }
        if let Some(bgcolor) = &self.bgcolor {
            parts.push("on".to_string());
            parts.push(bgcolor.name.clone());
        }
        if let Some(link) = &self.link {
            parts.push("link".to_string());
            parts.push(link.clone());
        }
        if parts.is_empty() {
            "none".to_string()
        } else {
            parts.join(" ")
        }
    }

    /// Canonicalise a style definition so that definitions with the same effect
    /// have the same string. Port of `Style.normalize`.
    ///
    /// A definition that parses round-trips through [`definition`](Self::definition),
    /// so `"b"` and `"BOLD"` both become `"bold"`. One that does not parse is
    /// merely trimmed and lowercased — that is the path a *theme name* like
    /// `"repr.number"` takes, and it is why theme lookups are effectively
    /// case-insensitive on the markup side while [`Theme::get_style`] itself is
    /// case-sensitive.
    ///
    /// [`Theme::get_style`]: crate::theme::Theme::get_style
    pub fn normalize(definition: &str) -> String {
        match Style::parse(definition) {
            Ok(style) => style.definition(),
            Err(_) => definition.trim().to_lowercase(),
        }
    }

    /// Parse a style definition such as `"bold red on blue"`.
    ///
    /// Port of `Style.parse` covering attributes, `not <attr>`, `link <url>`, and
    /// `<color> on <color>`. (`meta` is deferred — see DIVERGENCES.)
    pub fn parse(definition: &str) -> Result<Self> {
        // Port of upstream's leading guard:
        //     if style_definition.strip() == "none" or not style_definition
        // `none` is only valid as the WHOLE definition — upstream raises on
        // `"bold none"`, because inside the word loop `none` is treated as a
        // colour name and fails to parse. Many `DEFAULT_STYLES` entries are
        // exactly `"none"`, so without this they would all be dropped.
        if definition.is_empty() || definition.trim() == "none" {
            return Ok(Style::new());
        }
        let mut style = Style::new();
        let mut words = definition.split_whitespace();
        while let Some(raw) = words.next() {
            let word = raw.to_ascii_lowercase();
            match word.as_str() {
                "on" => {
                    let color_word = words.next().ok_or_else(|| {
                        RichError::StyleSyntax("color expected after 'on'".to_string())
                    })?;
                    style.bgcolor = Some(Color::parse(color_word)?);
                }
                "not" => {
                    let attr_word = words.next().ok_or_else(|| {
                        RichError::StyleSyntax("attribute expected after 'not'".to_string())
                    })?;
                    // Deliberately NOT lowercased: upstream folds case only on
                    // the loop word, and looks the `not` operand up verbatim —
                    // so `"not BOLD"` is a syntax error there, and must be here.
                    let idx = attribute_index(attr_word).ok_or_else(|| {
                        RichError::StyleSyntax(format!(
                            "{attr_word:?} is not a recognized attribute"
                        ))
                    })?;
                    style.attrs[idx] = Some(false);
                }
                "link" => {
                    // A bare `link` is a syntax error upstream, not an empty
                    // link — accepting it would emit a hyperlink to nowhere.
                    let url = words.next().filter(|url| !url.is_empty()).ok_or_else(|| {
                        RichError::StyleSyntax("URL expected after 'link'".to_string())
                    })?;
                    style.link = Some(url.to_string());
                }
                _ => {
                    if let Some(idx) = attribute_index(&word) {
                        style.attrs[idx] = Some(true);
                    } else {
                        style.color = Some(Color::parse(&word)?);
                    }
                }
            }
        }
        Ok(style)
    }

    /// Combine two styles, `other` winning wherever it sets a value.
    ///
    /// Port of `Style.__add__`.
    pub fn combine(&self, other: &Style) -> Style {
        let mut attrs = self.attrs;
        for (slot, over) in attrs.iter_mut().zip(other.attrs.iter()) {
            if over.is_some() {
                *slot = *over;
            }
        }
        Style {
            color: other.color.clone().or_else(|| self.color.clone()),
            bgcolor: other.bgcolor.clone().or_else(|| self.bgcolor.clone()),
            attrs,
            link: other.link.clone().or_else(|| self.link.clone()),
            // `if self._meta and style._meta: {**self.meta, **style.meta}`,
            // else `style._meta or self._meta`.
            meta: match (&self.meta, &other.meta) {
                (Some(mine), Some(theirs)) => {
                    let mut merged = mine.clone();
                    merged.update(theirs);
                    Some(merged)
                }
                (mine, theirs) => theirs.clone().or_else(|| mine.clone()),
            },
        }
    }

    /// The SGR parameter list (e.g. `"1;31;44"`) for a given color system.
    ///
    /// Port of `Style._make_ansi_codes`.
    pub fn ansi_codes(&self, system: ColorSystem) -> String {
        let mut sgr: Vec<String> = Vec::new();
        for (idx, attr) in self.attrs.iter().enumerate() {
            if *attr == Some(true) {
                sgr.push(ATTR_SGR[idx].to_string());
            }
        }
        if let Some(color) = &self.color {
            sgr.extend(color.downgrade(system).ansi_codes(true));
        }
        if let Some(bgcolor) = &self.bgcolor {
            sgr.extend(bgcolor.downgrade(system).ansi_codes(false));
        }
        sgr.join(";")
    }

    /// The CSS declarations for this style under `theme` (for HTML export).
    /// Port of `Style.get_html_style`.
    pub fn get_html_style(&self, theme: &crate::terminal_theme::TerminalTheme) -> String {
        use crate::terminal_theme::blend_rgb;
        let mut css: Vec<String> = Vec::new();

        let mut color = self.color.clone();
        let mut bgcolor = self.bgcolor.clone();
        // reverse (attr index 6): swap fore/background.
        if self.attrs[6] == Some(true) {
            std::mem::swap(&mut color, &mut bgcolor);
        }
        // dim (attr index 1): blend the foreground halfway to the background.
        if self.attrs[1] == Some(true) {
            let fg = match &color {
                Some(c) => theme.resolve(c, true),
                None => theme.foreground,
            };
            let blended = blend_rgb(fg, theme.background, 0.5);
            color = Some(Color::from_rgb(blended.red, blended.green, blended.blue));
        }

        if let Some(c) = &color {
            let hex = theme.resolve(c, true).hex();
            css.push(format!("color: {hex}"));
            css.push(format!("text-decoration-color: {hex}"));
        }
        if let Some(c) = &bgcolor {
            let hex = theme.resolve(c, false).hex();
            css.push(format!("background-color: {hex}"));
        }
        if self.attrs[0] == Some(true) {
            css.push("font-weight: bold".to_string());
        }
        if self.attrs[2] == Some(true) {
            css.push("font-style: italic".to_string());
        }
        if self.attrs[3] == Some(true) {
            css.push("text-decoration: underline".to_string());
        }
        if self.attrs[8] == Some(true) {
            css.push("text-decoration: line-through".to_string());
        }
        if self.attrs[12] == Some(true) {
            css.push("text-decoration: overline".to_string());
        }
        css.join("; ")
    }

    /// The SVG `<text>` CSS declarations for this style under `theme`. Port of
    /// the `get_svg_style` closure in `Console.export_svg`. Unlike
    /// [`get_html_style`](Self::get_html_style), the colour is always resolved to
    /// a concrete triplet (the theme fore/background stands in for a missing or
    /// default colour), `dim` blends 40% toward the background (not 50%), and the
    /// rules are joined with a bare `;`.
    pub fn get_svg_style(&self, theme: &crate::terminal_theme::TerminalTheme) -> String {
        use crate::terminal_theme::blend_rgb;
        // Resolve fore/background to concrete triplets (theme defaults fill in for
        // a None/default colour, exactly as `theme.resolve` does for `Default`).
        let mut color = self
            .color
            .as_ref()
            .map_or(theme.foreground, |c| theme.resolve(c, true));
        let mut bgcolor = self
            .bgcolor
            .as_ref()
            .map_or(theme.background, |c| theme.resolve(c, false));
        if self.attrs[6] == Some(true) {
            std::mem::swap(&mut color, &mut bgcolor);
        }
        if self.attrs[1] == Some(true) {
            color = blend_rgb(color, bgcolor, 0.4);
        }
        let mut rules = vec![format!("fill: {}", color.hex())];
        if self.attrs[0] == Some(true) {
            rules.push("font-weight: bold".to_string());
        }
        if self.attrs[2] == Some(true) {
            rules.push("font-style: italic;".to_string());
        }
        if self.attrs[3] == Some(true) {
            rules.push("text-decoration: underline;".to_string());
        }
        if self.attrs[8] == Some(true) {
            rules.push("text-decoration: line-through;".to_string());
        }
        rules.join(";")
    }

    /// Wrap `text` in this style's escape sequence for `system`.
    ///
    /// With `system == None` (no color) or a null style, `text` is returned
    /// unchanged. A [`link`](Self::with_link) additionally wraps the result in an
    /// OSC 8 hyperlink. Port of `Style.render`.
    ///
    /// **Divergence:** upstream tags each hyperlink with a random `id=` field (to
    /// group multi-segment links for hover); we omit it so output is
    /// deterministic. See docs/DIVERGENCES.md.
    pub fn render(&self, text: &str, system: Option<ColorSystem>) -> String {
        let Some(system) = system else {
            return text.to_string();
        };
        if text.is_empty() {
            return text.to_string();
        }
        let codes = self.ansi_codes(system);
        let rendered = if codes.is_empty() {
            text.to_string()
        } else {
            format!("\x1b[{codes}m{text}\x1b[0m")
        };
        match &self.link {
            Some(url) => format!("\x1b]8;;{url}\x1b\\{rendered}\x1b]8;;\x1b\\"),
            None => rendered,
        }
    }
}

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

    /// Expectations captured from real rich 15.0.0.
    #[test]
    fn meta_matches_upstream() {
        let meta = |entries: &[(&str, MetaValue)]| -> Meta { entries.iter().cloned().collect() };
        let a = Style::parse("bold")
            .unwrap()
            .with_meta(meta(&[("x", MetaValue::Int(1)), ("y", MetaValue::Int(2))]));
        let b = Style::new().with_meta(meta(&[("y", MetaValue::Int(3)), ("z", MetaValue::Int(4))]));
        // `{'x': 1, 'y': 3, 'z': 4}`
        assert_eq!(
            a.combine(&b).meta(),
            meta(&[
                ("x", MetaValue::Int(1)),
                ("y", MetaValue::Int(3)),
                ("z", MetaValue::Int(4))
            ])
        );
        assert!(Style::new().with_meta(Meta::new()).is_null());
        assert!(Style::from_meta(Meta::new()).is_null());
        let ab = meta(&[("a", MetaValue::Int(1)), ("b", MetaValue::Int(2))]);
        let ba = meta(&[("b", MetaValue::Int(2)), ("a", MetaValue::Int(1))]);
        assert_ne!(Style::new().with_meta(ab), Style::new().with_meta(ba));
        assert_ne!(
            Style::new().with_meta(meta(&[("a", MetaValue::Bool(true))])),
            Style::new().with_meta(meta(&[("a", MetaValue::Int(1))]))
        );
        assert_eq!(
            Style::on(
                Some(meta(&[("k", MetaValue::Int(1))])),
                &[("click", MetaValue::Str("go".into()))]
            )
            .meta(),
            meta(&[
                ("k", MetaValue::Int(1)),
                ("@click", MetaValue::Str("go".into()))
            ])
        );
        let rich = Style::parse("bold link x")
            .unwrap()
            .with_meta(meta(&[("a", MetaValue::Int(1))]));
        assert_eq!(rich.definition(), "bold link x");
        assert_eq!(rich.clear_meta_and_links(), Style::parse("bold").unwrap());
        // Meta never renders.
        assert_eq!(
            rich.ansi_codes(ColorSystem::Truecolor),
            Style::parse("bold")
                .unwrap()
                .ansi_codes(ColorSystem::Truecolor)
        );
    }

    /// `normalize` round-trips a parseable definition through `definition()` and
    /// merely trims+lowercases one that isn't. Every expectation here was taken
    /// from real rich 15.0.0's `Style.normalize`.
    #[test]
    fn normalize_matches_upstream() {
        for (input, expected) in [
            ("b", "bold"),
            ("bold", "bold"),
            ("BOLD", "bold"),
            ("  Bold  ", "bold"),
            ("dim i", "dim italic"),
            ("not bold", "not bold"),
            ("bold red", "bold red"),
            ("red on blue", "red on blue"),
            ("link https://x", "link https://x"),
            // Not a style definition, so it falls through to trim+lowercase —
            // this is the path every theme name takes.
            ("nope", "nope"),
            ("REPR.Number", "repr.number"),
            // `not` is case-sensitive upstream, so this fails to parse and takes
            // the fallback, which happens to produce the same string.
            ("not BOLD", "not bold"),
        ] {
            assert_eq!(Style::normalize(input), expected, "normalize({input:?})");
        }
    }

    /// A style that sets nothing renders as `"none"`, never as an empty string.
    #[test]
    fn definition_of_null_style_is_none() {
        assert_eq!(Style::new().definition(), "none");
        assert_eq!(Style::parse("none").unwrap().definition(), "none");
    }

    /// `not <attr>` is case-sensitive, matching upstream, which looks the operand
    /// up without folding and raises when it misses. Accepting `not BOLD` would
    /// silently *cancel* an enclosing bold instead of being ignored.
    #[test]
    fn not_operand_is_case_sensitive() {
        assert!(Style::parse("not bold").is_ok());
        assert!(Style::parse("not BOLD").is_err());
    }

    /// `link <url>` is a style keyword, not a colour name. Without it the whole
    /// definition failed to parse and the hyperlink was silently dropped.
    #[test]
    fn parse_understands_link() {
        let style = Style::parse("link https://example.com").expect("link parses");
        assert_eq!(style.link.as_deref(), Some("https://example.com"));
        assert_eq!(style.definition(), "link https://example.com");
        // A bare `link` is a syntax error, exactly as upstream — accepting it
        // would emit a hyperlink to nowhere.
        assert!(Style::parse("link").is_err());
    }

    #[test]
    fn parse_bold_red() {
        let style = Style::parse("bold red").unwrap();
        assert_eq!(style.ansi_codes(ColorSystem::Truecolor), "1;31");
        assert_eq!(
            style.render("hello", Some(ColorSystem::Truecolor)),
            "\x1b[1;31mhello\x1b[0m"
        );
    }

    #[test]
    fn svg_style_matches_upstream() {
        // Captured from real rich 15.0.0 `export_svg`'s `get_svg_style` under
        // `SVG_EXPORT_THEME`. Note: bgcolor is excluded from the fill style,
        // `reverse` swaps to the background, and dim blends 40% toward it.
        use crate::terminal_theme::SVG_EXPORT_THEME as theme;
        let svg = |spec: &str| Style::parse(spec).unwrap().get_svg_style(&theme);
        assert_eq!(Style::new().get_svg_style(&theme), "fill: #c5c8c6");
        assert_eq!(svg("bold red"), "fill: #cc555a;font-weight: bold");
        assert_eq!(svg("italic green"), "fill: #98a84b;font-style: italic;");
        assert_eq!(svg("dim"), "fill: #868887");
        assert_eq!(
            svg("underline blue on yellow"),
            "fill: #608ab1;text-decoration: underline;"
        );
        assert_eq!(svg("reverse"), "fill: #292929");
    }

    #[test]
    fn link_wraps_in_osc8() {
        let style = Style::parse("underline blue")
            .unwrap()
            .with_link("https://example.com");
        assert_eq!(
            style.render("click", Some(ColorSystem::Truecolor)),
            "\x1b]8;;https://example.com\x1b\\\x1b[4;34mclick\x1b[0m\x1b]8;;\x1b\\"
        );
        // A link-only style still wraps (no SGR inside).
        let bare = Style::new().with_link("https://x.com");
        assert_eq!(
            bare.render("y", Some(ColorSystem::Truecolor)),
            "\x1b]8;;https://x.com\x1b\\y\x1b]8;;\x1b\\"
        );
        assert!(!bare.is_null());
    }

    #[test]
    fn parse_fg_on_bg() {
        let style = Style::parse("white on blue").unwrap();
        assert_eq!(style.ansi_codes(ColorSystem::Truecolor), "37;44");
    }

    #[test]
    fn combine_overrides() {
        let base = Style::parse("bold red").unwrap();
        let over = Style::parse("blue").unwrap();
        let combined = base.combine(&over);
        // bold retained from base, color replaced by blue (34)
        assert_eq!(combined.ansi_codes(ColorSystem::Truecolor), "1;34");
    }

    #[test]
    fn no_color_system_is_plaintext() {
        let style = Style::parse("bold red").unwrap();
        assert_eq!(style.render("hello", None), "hello");
    }

    #[test]
    fn null_style_does_not_wrap() {
        let style = Style::new();
        assert_eq!(style.render("hello", Some(ColorSystem::Truecolor)), "hello");
    }
}