saorsa-tui 0.4.0

Retained-mode, CSS-styled terminal UI framework
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
//! CSS cascade resolution.
//!
//! Implements the CSS cascade algorithm that resolves matched rules
//! into a final [`ComputedStyle`] by applying specificity and source
//! order, with `!important` declarations overriding normal ones.

use std::collections::HashMap;

use crate::tcss::matcher::MatchedRule;
use crate::tcss::property::PropertyName;
use crate::tcss::value::CssValue;
use crate::tcss::variable::VariableEnvironment;

/// The computed style for a widget — final resolved property values.
///
/// After cascade resolution, this contains the winning value for each
/// property from all matching rules.
#[derive(Clone, Debug, Default)]
pub struct ComputedStyle {
    properties: HashMap<PropertyName, CssValue>,
}

impl ComputedStyle {
    /// Create a new empty computed style.
    pub fn new() -> Self {
        Self::default()
    }

    /// Get a property value.
    pub fn get(&self, prop: &PropertyName) -> Option<&CssValue> {
        self.properties.get(prop)
    }

    /// Set a property value.
    pub fn set(&mut self, prop: PropertyName, value: CssValue) {
        self.properties.insert(prop, value);
    }

    /// Check if a property is set.
    pub fn has(&self, prop: &PropertyName) -> bool {
        self.properties.contains_key(prop)
    }

    /// Return the number of set properties.
    pub fn len(&self) -> usize {
        self.properties.len()
    }

    /// Return whether no properties are set.
    pub fn is_empty(&self) -> bool {
        self.properties.is_empty()
    }

    /// Iterate over all property-value pairs.
    pub fn iter(&self) -> impl Iterator<Item = (&PropertyName, &CssValue)> {
        self.properties.iter()
    }

    /// Resolve all variable references using the given environment.
    ///
    /// Replaces `CssValue::Variable(name)` entries with the resolved
    /// value from the environment. Unresolved variables remain as-is.
    pub fn resolve_variables(&mut self, env: &VariableEnvironment) {
        let resolved: Vec<(PropertyName, CssValue)> = self
            .properties
            .iter()
            .filter_map(|(prop, value)| {
                if let CssValue::Variable(name) = value {
                    env.resolve(name).map(|v| (prop.clone(), v.clone()))
                } else {
                    None
                }
            })
            .collect();
        for (prop, value) in resolved {
            self.properties.insert(prop, value);
        }
    }

    /// Check if any property has an unresolved variable reference.
    pub fn has_unresolved_variables(&self) -> bool {
        self.properties
            .values()
            .any(|v| matches!(v, CssValue::Variable(_)))
    }
}

/// A cascade resolver.
///
/// Applies the CSS cascade algorithm to a list of matched rules,
/// producing a final [`ComputedStyle`].
pub struct CascadeResolver;

/// A declaration with its cascade ordering key (specificity + source order).
type CascadeEntry = (PropertyName, CssValue, (u16, u16, u16), usize);

impl CascadeResolver {
    /// Resolve matched rules into a computed style.
    ///
    /// # Algorithm
    ///
    /// 1. Separate declarations into normal and `!important`.
    /// 2. Sort normal declarations by (specificity, source_order) ascending.
    /// 3. Sort `!important` declarations by (specificity, source_order) ascending.
    /// 4. Apply normal declarations first (later entries override earlier).
    /// 5. Apply `!important` declarations last (they override everything).
    /// 6. Return the final [`ComputedStyle`].
    pub fn resolve(matches: &[MatchedRule]) -> ComputedStyle {
        let mut normal: Vec<CascadeEntry> = Vec::new();
        let mut important: Vec<CascadeEntry> = Vec::new();

        for matched in matches {
            for decl in &matched.declarations {
                let entry = (
                    decl.property.clone(),
                    decl.value.clone(),
                    matched.specificity,
                    matched.source_order,
                );
                if decl.important {
                    important.push(entry);
                } else {
                    normal.push(entry);
                }
            }
        }

        // Sort ascending by (specificity, source_order).
        // Later entries in the sorted list override earlier ones.
        normal.sort_by_key(|&(_, _, spec, order)| (spec, order));
        important.sort_by_key(|&(_, _, spec, order)| (spec, order));

        let mut style = ComputedStyle::new();

        // Apply normal declarations (last wins).
        for (prop, value, _, _) in normal {
            style.set(prop, value);
        }

        // Apply !important declarations (override everything).
        for (prop, value, _, _) in important {
            style.set(prop, value);
        }

        style
    }

    /// Resolve matched rules into a computed style, resolving variable references.
    ///
    /// First applies the standard cascade, then resolves any
    /// `CssValue::Variable` references using the given environment.
    pub fn resolve_with_variables(
        matches: &[MatchedRule],
        env: &VariableEnvironment,
    ) -> ComputedStyle {
        let mut style = Self::resolve(matches);
        style.resolve_variables(env);
        style
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::Color;
    use crate::color::NamedColor;
    use crate::tcss::property::Declaration;
    use crate::tcss::value::Length;
    use crate::tcss::variable::VariableEnvironment;

    fn matched_rule(
        specificity: (u16, u16, u16),
        source_order: usize,
        declarations: Vec<Declaration>,
    ) -> MatchedRule {
        MatchedRule {
            specificity,
            source_order,
            declarations,
        }
    }

    #[test]
    fn empty_matches_empty_style() {
        let style = CascadeResolver::resolve(&[]);
        assert!(style.is_empty());
        assert_eq!(style.len(), 0);
    }

    #[test]
    fn single_rule_applied() {
        let rules = vec![matched_rule(
            (0, 0, 1),
            0,
            vec![Declaration::new(
                PropertyName::Color,
                CssValue::Color(Color::Named(NamedColor::Red)),
            )],
        )];
        let style = CascadeResolver::resolve(&rules);
        assert_eq!(style.len(), 1);
        assert!(style.has(&PropertyName::Color));
    }

    #[test]
    fn later_rule_overrides() {
        // Same specificity: later source order wins.
        let rules = vec![
            matched_rule(
                (0, 0, 1),
                0,
                vec![Declaration::new(
                    PropertyName::Color,
                    CssValue::Keyword("red".into()),
                )],
            ),
            matched_rule(
                (0, 0, 1),
                1,
                vec![Declaration::new(
                    PropertyName::Color,
                    CssValue::Keyword("blue".into()),
                )],
            ),
        ];
        let style = CascadeResolver::resolve(&rules);
        assert_eq!(
            style.get(&PropertyName::Color),
            Some(&CssValue::Keyword("blue".into()))
        );
    }

    #[test]
    fn higher_specificity_wins() {
        // Higher specificity wins regardless of order.
        let rules = vec![
            matched_rule(
                (0, 1, 0),
                0,
                vec![Declaration::new(
                    PropertyName::Color,
                    CssValue::Keyword("class-wins".into()),
                )],
            ),
            matched_rule(
                (0, 0, 1),
                1,
                vec![Declaration::new(
                    PropertyName::Color,
                    CssValue::Keyword("type-loses".into()),
                )],
            ),
        ];
        let style = CascadeResolver::resolve(&rules);
        assert_eq!(
            style.get(&PropertyName::Color),
            Some(&CssValue::Keyword("class-wins".into()))
        );
    }

    #[test]
    fn important_overrides_specificity() {
        let rules = vec![
            matched_rule(
                (1, 0, 0),
                0,
                vec![Declaration::new(
                    PropertyName::Color,
                    CssValue::Keyword("high-spec".into()),
                )],
            ),
            matched_rule(
                (0, 0, 1),
                1,
                vec![Declaration::important(
                    PropertyName::Color,
                    CssValue::Keyword("important-wins".into()),
                )],
            ),
        ];
        let style = CascadeResolver::resolve(&rules);
        assert_eq!(
            style.get(&PropertyName::Color),
            Some(&CssValue::Keyword("important-wins".into()))
        );
    }

    #[test]
    fn important_vs_important() {
        // Both !important: higher specificity wins.
        let rules = vec![
            matched_rule(
                (0, 1, 0),
                0,
                vec![Declaration::important(
                    PropertyName::Color,
                    CssValue::Keyword("class-important".into()),
                )],
            ),
            matched_rule(
                (0, 0, 1),
                1,
                vec![Declaration::important(
                    PropertyName::Color,
                    CssValue::Keyword("type-important".into()),
                )],
            ),
        ];
        let style = CascadeResolver::resolve(&rules);
        assert_eq!(
            style.get(&PropertyName::Color),
            Some(&CssValue::Keyword("class-important".into()))
        );
    }

    #[test]
    fn multiple_properties_merged() {
        let rules = vec![
            matched_rule(
                (0, 0, 1),
                0,
                vec![Declaration::new(
                    PropertyName::Color,
                    CssValue::Keyword("red".into()),
                )],
            ),
            matched_rule(
                (0, 0, 1),
                1,
                vec![Declaration::new(
                    PropertyName::Background,
                    CssValue::Keyword("blue".into()),
                )],
            ),
        ];
        let style = CascadeResolver::resolve(&rules);
        assert_eq!(style.len(), 2);
        assert!(style.has(&PropertyName::Color));
        assert!(style.has(&PropertyName::Background));
    }

    #[test]
    fn same_property_last_wins() {
        let rules = vec![
            matched_rule(
                (0, 0, 1),
                0,
                vec![Declaration::new(
                    PropertyName::Color,
                    CssValue::Keyword("first".into()),
                )],
            ),
            matched_rule(
                (0, 0, 1),
                1,
                vec![Declaration::new(
                    PropertyName::Color,
                    CssValue::Keyword("second".into()),
                )],
            ),
            matched_rule(
                (0, 0, 1),
                2,
                vec![Declaration::new(
                    PropertyName::Color,
                    CssValue::Keyword("third".into()),
                )],
            ),
        ];
        let style = CascadeResolver::resolve(&rules);
        assert_eq!(
            style.get(&PropertyName::Color),
            Some(&CssValue::Keyword("third".into()))
        );
    }

    #[test]
    fn computed_style_accessors() {
        let mut style = ComputedStyle::new();
        assert!(style.is_empty());
        assert_eq!(style.len(), 0);
        assert!(!style.has(&PropertyName::Color));
        assert!(style.get(&PropertyName::Color).is_none());

        style.set(PropertyName::Color, CssValue::Keyword("red".into()));
        assert!(!style.is_empty());
        assert_eq!(style.len(), 1);
        assert!(style.has(&PropertyName::Color));
        assert_eq!(
            style.get(&PropertyName::Color),
            Some(&CssValue::Keyword("red".into()))
        );
    }

    #[test]
    fn computed_style_iteration() {
        let mut style = ComputedStyle::new();
        style.set(PropertyName::Color, CssValue::Keyword("red".into()));
        style.set(PropertyName::Width, CssValue::Length(Length::Cells(10)));
        let pairs: Vec<_> = style.iter().collect();
        assert_eq!(pairs.len(), 2);
    }

    // --- Variable resolution tests ---

    #[test]
    fn resolve_with_no_variables() {
        let rules = vec![matched_rule(
            (0, 0, 1),
            0,
            vec![Declaration::new(
                PropertyName::Color,
                CssValue::Color(Color::Named(NamedColor::Red)),
            )],
        )];
        let env = VariableEnvironment::new();
        let style = CascadeResolver::resolve_with_variables(&rules, &env);
        assert_eq!(
            style.get(&PropertyName::Color),
            Some(&CssValue::Color(Color::Named(NamedColor::Red)))
        );
    }

    #[test]
    fn resolve_variable_from_global() {
        let rules = vec![matched_rule(
            (0, 0, 1),
            0,
            vec![Declaration::new(
                PropertyName::Color,
                CssValue::Variable("fg".into()),
            )],
        )];
        let mut env = VariableEnvironment::new();
        env.set_global("fg", CssValue::Color(Color::Named(NamedColor::White)));
        let style = CascadeResolver::resolve_with_variables(&rules, &env);
        assert_eq!(
            style.get(&PropertyName::Color),
            Some(&CssValue::Color(Color::Named(NamedColor::White)))
        );
    }

    #[test]
    fn resolve_variable_from_theme() {
        let rules = vec![matched_rule(
            (0, 0, 1),
            0,
            vec![Declaration::new(
                PropertyName::Color,
                CssValue::Variable("fg".into()),
            )],
        )];
        let mut env = VariableEnvironment::new();
        env.set_global("fg", CssValue::Color(Color::Named(NamedColor::White)));
        env.set_theme("fg", CssValue::Color(Color::Named(NamedColor::Red)));
        let style = CascadeResolver::resolve_with_variables(&rules, &env);
        assert_eq!(
            style.get(&PropertyName::Color),
            Some(&CssValue::Color(Color::Named(NamedColor::Red)))
        );
    }

    #[test]
    fn resolve_variable_missing_stays_variable() {
        let rules = vec![matched_rule(
            (0, 0, 1),
            0,
            vec![Declaration::new(
                PropertyName::Color,
                CssValue::Variable("missing".into()),
            )],
        )];
        let env = VariableEnvironment::new();
        let style = CascadeResolver::resolve_with_variables(&rules, &env);
        assert_eq!(
            style.get(&PropertyName::Color),
            Some(&CssValue::Variable("missing".into()))
        );
    }

    #[test]
    fn resolve_multiple_variables() {
        let rules = vec![matched_rule(
            (0, 0, 1),
            0,
            vec![
                Declaration::new(PropertyName::Color, CssValue::Variable("fg".into())),
                Declaration::new(PropertyName::Background, CssValue::Variable("bg".into())),
            ],
        )];
        let mut env = VariableEnvironment::new();
        env.set_global("fg", CssValue::Color(Color::Named(NamedColor::White)));
        env.set_global("bg", CssValue::Color(Color::Named(NamedColor::Black)));
        let style = CascadeResolver::resolve_with_variables(&rules, &env);
        assert_eq!(
            style.get(&PropertyName::Color),
            Some(&CssValue::Color(Color::Named(NamedColor::White)))
        );
        assert_eq!(
            style.get(&PropertyName::Background),
            Some(&CssValue::Color(Color::Named(NamedColor::Black)))
        );
    }

    #[test]
    fn resolve_mixed_variables_and_concrete() {
        let rules = vec![matched_rule(
            (0, 0, 1),
            0,
            vec![
                Declaration::new(PropertyName::Color, CssValue::Variable("fg".into())),
                Declaration::new(PropertyName::Width, CssValue::Length(Length::Cells(20))),
            ],
        )];
        let mut env = VariableEnvironment::new();
        env.set_global("fg", CssValue::Color(Color::Named(NamedColor::Red)));
        let style = CascadeResolver::resolve_with_variables(&rules, &env);
        assert_eq!(
            style.get(&PropertyName::Color),
            Some(&CssValue::Color(Color::Named(NamedColor::Red)))
        );
        assert_eq!(
            style.get(&PropertyName::Width),
            Some(&CssValue::Length(Length::Cells(20)))
        );
    }

    #[test]
    fn has_unresolved_true() {
        let mut style = ComputedStyle::new();
        style.set(PropertyName::Color, CssValue::Variable("fg".into()));
        assert!(style.has_unresolved_variables());
    }

    #[test]
    fn has_unresolved_false() {
        let mut style = ComputedStyle::new();
        style.set(
            PropertyName::Color,
            CssValue::Color(Color::Named(NamedColor::Red)),
        );
        assert!(!style.has_unresolved_variables());
    }

    #[test]
    fn has_unresolved_empty() {
        let style = ComputedStyle::new();
        assert!(!style.has_unresolved_variables());
    }

    #[test]
    fn real_cascade_example() {
        // Simulate: Label { color: white; } .error { color: red; } #main { width: 30; }
        let rules = vec![
            matched_rule(
                (0, 0, 1),
                0,
                vec![
                    Declaration::new(PropertyName::Color, CssValue::Keyword("white".into())),
                    Declaration::new(PropertyName::TextStyle, CssValue::Keyword("bold".into())),
                ],
            ),
            matched_rule(
                (0, 1, 0),
                1,
                vec![Declaration::new(
                    PropertyName::Color,
                    CssValue::Keyword("red".into()),
                )],
            ),
            matched_rule(
                (1, 0, 0),
                2,
                vec![Declaration::new(
                    PropertyName::Width,
                    CssValue::Length(Length::Cells(30)),
                )],
            ),
        ];
        let style = CascadeResolver::resolve(&rules);
        assert_eq!(style.len(), 3);
        // .error overrides Label for color (higher specificity).
        assert_eq!(
            style.get(&PropertyName::Color),
            Some(&CssValue::Keyword("red".into()))
        );
        // text-style from Label rule persists.
        assert_eq!(
            style.get(&PropertyName::TextStyle),
            Some(&CssValue::Keyword("bold".into()))
        );
        // width from #main rule.
        assert_eq!(
            style.get(&PropertyName::Width),
            Some(&CssValue::Length(Length::Cells(30)))
        );
    }
}