standout-render 7.2.0

Styled terminal rendering with templates, themes, and adaptive color support
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
//! Main stylesheet parser and theme variant builder.
//!
//! This module provides the entry point for parsing YAML stylesheets and
//! building [`ThemeVariants`] that can be resolved based on color mode.
//!
//! # Architecture
//!
//! The parsing process has two phases:
//!
//! 1. Parse: YAML → `HashMap<String, StyleDefinition>`
//! 2. Build: StyleDefinitions → `ThemeVariants` (base/light/dark style maps)
//!
//! During the build phase:
//! - Aliases are recorded for later resolution
//! - Base styles are computed from attribute definitions
//! - Light/dark variants are computed by merging mode overrides onto base
//!
//! # Mode Resolution
//!
//! When resolving styles for a specific mode, the variant merger:
//! - Returns the mode-specific style if one was defined
//! - Falls back to base style if no mode override exists
//!
//! This means styles with no `light:` or `dark:` sections work in all modes,
//! while adaptive styles provide mode-specific overrides.

use std::collections::HashMap;

use console::Style;

use crate::colorspace::ThemePalette;

use super::super::theme::ColorMode;
use super::definition::StyleDefinition;
use super::error::StylesheetError;
use super::value::StyleValue;

/// Theme variants containing styles for base, light, and dark modes.
///
/// Each variant is a map of style names to concrete `console::Style` values.
/// Alias definitions are stored separately and resolved at lookup time.
///
/// # Resolution Strategy
///
/// When looking up a style for a given mode:
///
/// 1. If the style is an alias, follow the chain to find the concrete style
/// 2. For concrete styles, check if a mode-specific variant exists
/// 3. If yes, return the mode variant (base merged with mode overrides)
/// 4. If no, return the base style
///
/// # Pruning
///
/// During construction, mode variants are only stored if they differ from base.
/// This optimization means:
/// - Styles with no `light:` or `dark:` sections only have base entries
/// - Styles with overrides have entries in the relevant mode map
#[derive(Debug, Clone)]
pub struct ThemeVariants {
    /// Base styles (always populated for non-alias definitions).
    base: HashMap<String, Style>,

    /// Light mode styles (only populated for styles with light overrides).
    light: HashMap<String, Style>,

    /// Dark mode styles (only populated for styles with dark overrides).
    dark: HashMap<String, Style>,

    /// Alias definitions: style name → target style name.
    aliases: HashMap<String, String>,
}

impl ThemeVariants {
    /// Creates empty theme variants.
    pub fn new() -> Self {
        Self {
            base: HashMap::new(),
            light: HashMap::new(),
            dark: HashMap::new(),
            aliases: HashMap::new(),
        }
    }

    /// Resolves styles for the given color mode.
    ///
    /// Returns a `HashMap<String, StyleValue>` where:
    /// - Aliases are preserved as `StyleValue::Alias`
    /// - Concrete styles are `StyleValue::Concrete` with the mode-appropriate style
    ///
    /// For light/dark modes, mode-specific styles take precedence over base.
    /// For unknown mode (None), only base styles are used.
    pub fn resolve(&self, mode: Option<ColorMode>) -> HashMap<String, StyleValue> {
        let mut result = HashMap::new();

        // Add aliases
        for (name, target) in &self.aliases {
            result.insert(name.clone(), StyleValue::Alias(target.clone()));
        }

        // Add concrete styles based on mode
        let mode_styles = match mode {
            Some(ColorMode::Light) => &self.light,
            Some(ColorMode::Dark) => &self.dark,
            None => &HashMap::new(), // No mode-specific overrides
        };

        for (name, style) in &self.base {
            // Check for mode-specific override
            let style = mode_styles.get(name).unwrap_or(style);
            result.insert(name.clone(), StyleValue::Concrete(style.clone()));
        }

        result
    }

    /// Returns the base styles map.
    pub fn base(&self) -> &HashMap<String, Style> {
        &self.base
    }

    /// Returns the light mode styles map.
    pub fn light(&self) -> &HashMap<String, Style> {
        &self.light
    }

    /// Returns the dark mode styles map.
    pub fn dark(&self) -> &HashMap<String, Style> {
        &self.dark
    }

    /// Returns the aliases map.
    pub fn aliases(&self) -> &HashMap<String, String> {
        &self.aliases
    }

    /// Returns true if no styles are defined.
    pub fn is_empty(&self) -> bool {
        self.base.is_empty() && self.aliases.is_empty()
    }

    /// Returns the number of defined styles (base + aliases).
    pub fn len(&self) -> usize {
        self.base.len() + self.aliases.len()
    }
}

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

/// Parses a YAML stylesheet and builds theme variants.
///
/// # Arguments
///
/// * `yaml` - YAML content as a string
///
/// # Returns
///
/// A `ThemeVariants` containing base, light, and dark style maps.
///
/// # Errors
///
/// Returns `StylesheetError` if:
/// - YAML parsing fails
/// - Style definitions are invalid
/// - Colors or attributes are unrecognized
///
/// # Example
///
/// ```rust
/// use standout_render::style::parse_stylesheet;
///
/// let yaml = r#"
/// header:
///   fg: cyan
///   bold: true
///
/// muted:
///   dim: true
///
/// footer:
///   fg: gray
///   light:
///     fg: black
///   dark:
///     fg: white
///
/// disabled: muted
/// "#;
///
/// let variants = parse_stylesheet(yaml, None).unwrap();
/// ```
pub fn parse_stylesheet(
    yaml: &str,
    palette: Option<&ThemePalette>,
) -> Result<ThemeVariants, StylesheetError> {
    // Parse YAML into a mapping
    let root: serde_yaml::Value =
        serde_yaml::from_str(yaml).map_err(|e| StylesheetError::Parse {
            path: None,
            message: e.to_string(),
        })?;

    let mapping = root.as_mapping().ok_or_else(|| StylesheetError::Parse {
        path: None,
        message: "Stylesheet must be a YAML mapping".to_string(),
    })?;

    // Parse each style definition
    let mut definitions: HashMap<String, StyleDefinition> = HashMap::new();

    for (key, value) in mapping {
        let name = key.as_str().ok_or_else(|| StylesheetError::Parse {
            path: None,
            message: format!("Style name must be a string, got {:?}", key),
        })?;

        // Skip the 'icons' section — it is parsed separately by Theme
        if name == "icons" {
            continue;
        }

        let def = StyleDefinition::parse(value, name)?;
        definitions.insert(name.to_string(), def);
    }

    // Build theme variants from definitions
    build_variants(&definitions, palette)
}

/// Builds theme variants from parsed style definitions.
pub(crate) fn build_variants(
    definitions: &HashMap<String, StyleDefinition>,
    palette: Option<&ThemePalette>,
) -> Result<ThemeVariants, StylesheetError> {
    let mut variants = ThemeVariants::new();

    for (name, def) in definitions {
        match def {
            StyleDefinition::Alias(target) => {
                variants.aliases.insert(name.clone(), target.clone());
            }
            StyleDefinition::Attributes { base, light, dark } => {
                // Build base style
                let base_style = base.to_style(palette);
                variants.base.insert(name.clone(), base_style);

                // Build light variant if overrides exist
                if let Some(light_attrs) = light {
                    let merged = base.merge(light_attrs);
                    variants
                        .light
                        .insert(name.clone(), merged.to_style(palette));
                }

                // Build dark variant if overrides exist
                if let Some(dark_attrs) = dark {
                    let merged = base.merge(dark_attrs);
                    variants.dark.insert(name.clone(), merged.to_style(palette));
                }
            }
        }
    }

    Ok(variants)
}

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

    // =========================================================================
    // parse_stylesheet basic tests
    // =========================================================================

    #[test]
    fn test_parse_empty_stylesheet() {
        let yaml = "{}";
        let variants = parse_stylesheet(yaml, None).unwrap();
        assert!(variants.is_empty());
    }

    #[test]
    fn test_parse_simple_style() {
        let yaml = r#"
            header:
                fg: cyan
                bold: true
        "#;
        let variants = parse_stylesheet(yaml, None).unwrap();

        assert_eq!(variants.len(), 1);
        assert!(variants.base().contains_key("header"));
        assert!(variants.light().is_empty());
        assert!(variants.dark().is_empty());
    }

    #[test]
    fn test_parse_shorthand_style() {
        let yaml = r#"
            bold_text: bold
            accent: cyan
            warning: "yellow italic"
        "#;
        let variants = parse_stylesheet(yaml, None).unwrap();

        assert_eq!(variants.base().len(), 3);
        assert!(variants.base().contains_key("bold_text"));
        assert!(variants.base().contains_key("accent"));
        assert!(variants.base().contains_key("warning"));
    }

    #[test]
    fn test_parse_alias() {
        let yaml = r#"
            muted:
                dim: true
            disabled: muted
        "#;
        let variants = parse_stylesheet(yaml, None).unwrap();

        assert_eq!(variants.base().len(), 1);
        assert_eq!(variants.aliases().len(), 1);
        assert_eq!(
            variants.aliases().get("disabled"),
            Some(&"muted".to_string())
        );
    }

    #[test]
    fn test_parse_adaptive_style() {
        let yaml = r#"
            footer:
                fg: gray
                bold: true
                light:
                    fg: black
                dark:
                    fg: white
        "#;
        let variants = parse_stylesheet(yaml, None).unwrap();

        assert!(variants.base().contains_key("footer"));
        assert!(variants.light().contains_key("footer"));
        assert!(variants.dark().contains_key("footer"));
    }

    #[test]
    fn test_parse_light_only() {
        let yaml = r#"
            panel:
                bg: gray
                light:
                    bg: white
        "#;
        let variants = parse_stylesheet(yaml, None).unwrap();

        assert!(variants.base().contains_key("panel"));
        assert!(variants.light().contains_key("panel"));
        assert!(!variants.dark().contains_key("panel"));
    }

    #[test]
    fn test_parse_dark_only() {
        let yaml = r#"
            panel:
                bg: gray
                dark:
                    bg: black
        "#;
        let variants = parse_stylesheet(yaml, None).unwrap();

        assert!(variants.base().contains_key("panel"));
        assert!(!variants.light().contains_key("panel"));
        assert!(variants.dark().contains_key("panel"));
    }

    // =========================================================================
    // ThemeVariants::resolve tests
    // =========================================================================

    #[test]
    fn test_resolve_no_mode() {
        let yaml = r#"
            header:
                fg: cyan
            footer:
                fg: gray
                light:
                    fg: black
                dark:
                    fg: white
        "#;
        let variants = parse_stylesheet(yaml, None).unwrap();
        let resolved = variants.resolve(None);

        // Should have both styles from base
        assert!(matches!(
            resolved.get("header"),
            Some(StyleValue::Concrete(_))
        ));
        assert!(matches!(
            resolved.get("footer"),
            Some(StyleValue::Concrete(_))
        ));
    }

    #[test]
    fn test_resolve_light_mode() {
        let yaml = r#"
            footer:
                fg: gray
                light:
                    fg: black
                dark:
                    fg: white
        "#;
        let variants = parse_stylesheet(yaml, None).unwrap();
        let resolved = variants.resolve(Some(ColorMode::Light));

        // footer should use light variant
        assert!(matches!(
            resolved.get("footer"),
            Some(StyleValue::Concrete(_))
        ));
    }

    #[test]
    fn test_resolve_dark_mode() {
        let yaml = r#"
            footer:
                fg: gray
                light:
                    fg: black
                dark:
                    fg: white
        "#;
        let variants = parse_stylesheet(yaml, None).unwrap();
        let resolved = variants.resolve(Some(ColorMode::Dark));

        // footer should use dark variant
        assert!(matches!(
            resolved.get("footer"),
            Some(StyleValue::Concrete(_))
        ));
    }

    #[test]
    fn test_resolve_preserves_aliases() {
        let yaml = r#"
            muted:
                dim: true
            disabled: muted
        "#;
        let variants = parse_stylesheet(yaml, None).unwrap();
        let resolved = variants.resolve(Some(ColorMode::Light));

        // muted should be concrete
        assert!(matches!(
            resolved.get("muted"),
            Some(StyleValue::Concrete(_))
        ));
        // disabled should be alias
        assert!(matches!(resolved.get("disabled"), Some(StyleValue::Alias(t)) if t == "muted"));
    }

    #[test]
    fn test_resolve_non_adaptive_uses_base() {
        let yaml = r#"
            header:
                fg: cyan
                bold: true
        "#;
        let variants = parse_stylesheet(yaml, None).unwrap();

        // Light mode
        let light = variants.resolve(Some(ColorMode::Light));
        assert!(matches!(light.get("header"), Some(StyleValue::Concrete(_))));

        // Dark mode
        let dark = variants.resolve(Some(ColorMode::Dark));
        assert!(matches!(dark.get("header"), Some(StyleValue::Concrete(_))));

        // No mode
        let none = variants.resolve(None);
        assert!(matches!(none.get("header"), Some(StyleValue::Concrete(_))));
    }

    // =========================================================================
    // Error tests
    // =========================================================================

    #[test]
    fn test_parse_invalid_yaml() {
        let yaml = "not: [valid: yaml";
        let result = parse_stylesheet(yaml, None);
        assert!(matches!(result, Err(StylesheetError::Parse { .. })));
    }

    #[test]
    fn test_parse_non_mapping_root() {
        let yaml = "- item1\n- item2";
        let result = parse_stylesheet(yaml, None);
        assert!(matches!(result, Err(StylesheetError::Parse { .. })));
    }

    #[test]
    fn test_parse_invalid_color() {
        let yaml = r#"
            bad:
                fg: not_a_color
        "#;
        let result = parse_stylesheet(yaml, None);
        assert!(result.is_err());
    }

    #[test]
    fn test_parse_unknown_attribute() {
        let yaml = r#"
            bad:
                unknown: true
        "#;
        let result = parse_stylesheet(yaml, None);
        assert!(matches!(
            result,
            Err(StylesheetError::UnknownAttribute { .. })
        ));
    }

    // =========================================================================
    // Complex stylesheet tests
    // =========================================================================

    #[test]
    fn test_parse_complete_stylesheet() {
        let yaml = r##"
            # Visual layer
            muted:
                dim: true

            accent:
                fg: cyan
                bold: true

            # Adaptive styles
            background:
                light:
                    bg: "#f8f8f8"
                dark:
                    bg: "#1e1e1e"

            text:
                light:
                    fg: "#333333"
                dark:
                    fg: "#d4d4d4"

            border:
                dim: true
                light:
                    fg: "#cccccc"
                dark:
                    fg: "#444444"

            # Semantic layer - aliases
            header: accent
            footer: muted
            timestamp: muted
            title: accent
            error: red
            success: green
            warning: "yellow bold"
        "##;

        let variants = parse_stylesheet(yaml, None).unwrap();

        // Check counts
        // Base: muted, accent, background, text, border, error, success, warning = 8
        // Aliases: header, footer, timestamp, title = 4
        assert_eq!(variants.base().len(), 8);
        assert_eq!(variants.aliases().len(), 4);

        // Check adaptive styles have light/dark variants
        assert!(variants.light().contains_key("background"));
        assert!(variants.light().contains_key("text"));
        assert!(variants.light().contains_key("border"));
        assert!(variants.dark().contains_key("background"));
        assert!(variants.dark().contains_key("text"));
        assert!(variants.dark().contains_key("border"));

        // Check aliases
        assert_eq!(
            variants.aliases().get("header"),
            Some(&"accent".to_string())
        );
        assert_eq!(variants.aliases().get("footer"), Some(&"muted".to_string()));
    }

    // =========================================================================
    // Cube color integration tests
    // =========================================================================

    #[test]
    fn test_parse_cube_color_in_stylesheet() {
        let yaml = r#"
            theme_accent:
                fg: "cube(60%, 20%, 0%)"
                bold: true
        "#;
        let variants = parse_stylesheet(yaml, None).unwrap();
        assert!(variants.base().contains_key("theme_accent"));
    }

    #[test]
    fn test_parse_cube_color_with_palette() {
        use crate::colorspace::{Rgb, ThemePalette};

        let palette = ThemePalette::new([
            Rgb(40, 40, 40),
            Rgb(204, 36, 29),
            Rgb(152, 151, 26),
            Rgb(215, 153, 33),
            Rgb(69, 133, 136),
            Rgb(177, 98, 134),
            Rgb(104, 157, 106),
            Rgb(168, 153, 132),
        ]);

        let yaml = r#"
            warm:
                fg: "cube(80%, 30%, 0%)"
            cool:
                fg: "cube(0%, 0%, 80%)"
        "#;
        let variants = parse_stylesheet(yaml, Some(&palette)).unwrap();
        assert!(variants.base().contains_key("warm"));
        assert!(variants.base().contains_key("cool"));
    }

    #[test]
    fn test_parse_cube_color_adaptive() {
        let yaml = r#"
            panel:
                fg: "cube(50%, 50%, 50%)"
                light:
                    fg: "cube(20%, 20%, 20%)"
                dark:
                    fg: "cube(80%, 80%, 80%)"
        "#;
        let variants = parse_stylesheet(yaml, None).unwrap();
        assert!(variants.base().contains_key("panel"));
        assert!(variants.light().contains_key("panel"));
        assert!(variants.dark().contains_key("panel"));
    }
}