dampen-core 0.3.2

Core parser, IR, and traits for Dampen 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
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
823
824
//! Theme and style class parsing
//!
//! This module provides parsers for theme definitions and style classes.

use crate::ir::layout::LayoutConstraints;
use crate::ir::style::{Color, StyleProperties};
use crate::ir::theme::{
    FontWeight, SpacingScale, StyleClass, Theme, ThemeDocument, ThemeError, ThemeErrorKind,
    ThemePalette, Typography, WidgetState,
};
use std::collections::HashMap;

/// Parse a complete theme.dampen document
pub fn parse_theme_document(xml: &str) -> Result<ThemeDocument, ThemeError> {
    let doc = roxmltree::Document::parse(xml).map_err(|e| ThemeError {
        kind: ThemeErrorKind::MissingPaletteColor,
        message: format!("THEME_003: Failed to parse XML: {}", e),
    })?;

    // Get the first child element (the <dampen> root)
    let root = doc.root().first_child().ok_or_else(|| ThemeError {
        kind: ThemeErrorKind::MissingPaletteColor,
        message: "THEME_003: No root element found".to_string(),
    })?;

    // Verify root element
    if root.tag_name().name() != "dampen" {
        return Err(ThemeError {
            kind: ThemeErrorKind::MissingPaletteColor,
            message: "THEME_003: Root element must be <dampen>".to_string(),
        });
    }

    let mut themes = HashMap::new();
    let mut default_theme = None;
    let mut follow_system = true;

    // Parse child elements
    for child in root.children() {
        if child.node_type() != roxmltree::NodeType::Element {
            continue;
        }

        let tag = child.tag_name().name();

        match tag {
            "themes" => {
                // Parse each theme
                for grandchild in child.children() {
                    if grandchild.node_type() != roxmltree::NodeType::Element {
                        continue;
                    }

                    if grandchild.tag_name().name() == "theme" {
                        let theme = parse_theme_from_node_simple(grandchild)?;
                        if themes.contains_key(&theme.name) {
                            return Err(ThemeError {
                                kind: ThemeErrorKind::DuplicateThemeName,
                                message: format!(
                                    "THEME_005: Duplicate theme name: '{}'",
                                    theme.name
                                ),
                            });
                        }
                        themes.insert(theme.name.clone(), theme);
                    }
                }
            }
            "default_theme" => {
                if let Some(name) = child.attribute("name") {
                    default_theme = Some(name.to_string());
                }
            }
            "follow_system" => {
                if let Some(enabled) = child.attribute("enabled") {
                    follow_system = enabled.parse::<bool>().unwrap_or(true);
                }
            }
            _ => {}
        }
    }

    let document = ThemeDocument {
        themes,
        default_theme,
        follow_system,
    };

    document.validate()?;
    Ok(document)
}

/// Parse a theme node (simplified version for ThemeDocument parsing)
fn parse_theme_from_node_simple(node: roxmltree::Node) -> Result<Theme, ThemeError> {
    let name = node
        .attribute("name")
        .map(|s| s.to_string())
        .unwrap_or_else(|| "default".to_string());

    let extends = node.attribute("extends").map(|s| s.to_string());

    let mut palette_attrs = HashMap::new();
    let mut typography_attrs = HashMap::new();
    let mut spacing_unit = None;

    // Parse child elements
    for child in node.children() {
        if child.node_type() != roxmltree::NodeType::Element {
            continue;
        }

        let tag = child.tag_name().name();

        match tag {
            "palette" => {
                for attr in child.attributes() {
                    palette_attrs.insert(attr.name().to_string(), attr.value().to_string());
                }
            }
            "typography" => {
                for attr in child.attributes() {
                    typography_attrs.insert(attr.name().to_string(), attr.value().to_string());
                }
            }
            "spacing" => {
                if let Some(unit) = child.attribute("unit") {
                    spacing_unit = unit.parse::<f32>().ok();
                }
            }
            _ => {}
        }
    }

    let palette = parse_palette(&palette_attrs).map_err(|e| ThemeError {
        kind: ThemeErrorKind::MissingPaletteColor,
        message: format!("THEME_003: Invalid palette: {}", e),
    })?;

    let typography = parse_typography(&typography_attrs).map_err(|e| ThemeError {
        kind: ThemeErrorKind::MissingPaletteColor,
        message: format!("THEME_003: Invalid typography: {}", e),
    })?;

    let spacing = SpacingScale { unit: spacing_unit };

    spacing.validate().map_err(|e| ThemeError {
        kind: ThemeErrorKind::MissingPaletteColor,
        message: format!("THEME_003: Invalid spacing: {}", e),
    })?;

    let theme = Theme {
        name,
        palette,
        typography,
        spacing,
        base_styles: HashMap::new(),
        extends,
    };

    Ok(theme)
}

/// Parse a theme definition from XML attributes
pub fn parse_theme(
    name: String,
    palette_attrs: &HashMap<String, String>,
    typography_attrs: &HashMap<String, String>,
    spacing_unit: Option<f32>,
    extends: Option<String>,
) -> Result<Theme, String> {
    let palette = parse_palette(palette_attrs)?;
    let typography = parse_typography(typography_attrs)?;
    let spacing = SpacingScale { unit: spacing_unit };

    let theme = Theme {
        name,
        palette,
        typography,
        spacing,
        base_styles: HashMap::new(),
        extends: extends.clone(),
    };

    theme.validate(extends.is_some())?;
    Ok(theme)
}

/// Parse theme palette from attributes
pub fn parse_palette(attrs: &HashMap<String, String>) -> Result<ThemePalette, String> {
    let get_color = |key: &str| -> Result<Option<Color>, String> {
        if let Some(value) = attrs.get(key) {
            Ok(Some(Color::parse(value)?))
        } else {
            Ok(None)
        }
    };

    Ok(ThemePalette {
        primary: get_color("primary")?,
        secondary: get_color("secondary")?,
        success: get_color("success")?,
        warning: get_color("warning")?,
        danger: get_color("danger")?,
        background: get_color("background")?,
        surface: get_color("surface")?,
        text: get_color("text")?,
        text_secondary: get_color("text_secondary")?,
    })
}

/// Parse typography from attributes
pub fn parse_typography(attrs: &HashMap<String, String>) -> Result<Typography, String> {
    let font_family = attrs.get("font_family").cloned();

    let font_size_base = if let Some(s) = attrs.get("font_size_base") {
        Some(s.parse().map_err(|_| "Invalid font_size_base")?)
    } else {
        None
    };

    let font_size_small = if let Some(s) = attrs.get("font_size_small") {
        Some(s.parse().map_err(|_| "Invalid font_size_small")?)
    } else {
        None
    };

    let font_size_large = if let Some(s) = attrs.get("font_size_large") {
        Some(s.parse().map_err(|_| "Invalid font_size_large")?)
    } else {
        None
    };

    let font_weight = match attrs.get("font_weight") {
        Some(w) => FontWeight::parse(w)?,
        None => FontWeight::Normal,
    };

    let line_height = if let Some(s) = attrs.get("line_height") {
        Some(s.parse().map_err(|_| "Invalid line_height")?)
    } else {
        None
    };

    Ok(Typography {
        font_family,
        font_size_base,
        font_size_small,
        font_size_large,
        font_weight,
        line_height,
    })
}

/// Parse a style class definition
pub fn parse_style_class(
    name: String,
    base_attrs: &HashMap<String, String>,
    extends: Vec<String>,
    state_variants: HashMap<WidgetState, StyleProperties>,
    combined_state_variants: HashMap<crate::ir::theme::StateSelector, StyleProperties>,
    layout: Option<LayoutConstraints>,
) -> Result<StyleClass, String> {
    let style = parse_style_properties_from_attrs(base_attrs)?;

    let class = StyleClass {
        name,
        style,
        layout,
        extends,
        state_variants,
        combined_state_variants,
    };

    Ok(class)
}

/// Parse style properties from a map of attributes
pub fn parse_style_properties_from_attrs(
    attrs: &HashMap<String, String>,
) -> Result<StyleProperties, String> {
    use crate::parser::style_parser::*;

    let mut background = None;
    let mut color = None;
    let mut shadow = None;
    let mut opacity = None;
    let mut transform = None;

    // Parse background
    if let Some(value) = attrs.get("background") {
        background = Some(parse_background_attr(value)?);
    }

    // Parse color
    if let Some(value) = attrs.get("color") {
        color = Some(parse_color_attr(value)?);
    }

    // Parse border properties
    let border_width = attrs
        .get("border_width")
        .map(|v| parse_border_width(v))
        .transpose()?;
    let border_color = attrs
        .get("border_color")
        .map(|v| parse_border_color(v))
        .transpose()?;
    let border_radius = attrs
        .get("border_radius")
        .map(|v| parse_border_radius(v))
        .transpose()?;
    let border_style = attrs
        .get("border_style")
        .map(|v| parse_border_style(v))
        .transpose()?;

    let border = build_border(border_width, border_color, border_radius, border_style)?;

    // Parse shadow
    if let Some(value) = attrs.get("shadow") {
        shadow = Some(parse_shadow_attr(value)?);
    }

    // Parse opacity
    if let Some(value) = attrs.get("opacity") {
        opacity = Some(parse_opacity(value)?);
    }

    // Parse transform
    if let Some(value) = attrs.get("transform") {
        transform = Some(parse_transform(value)?);
    }

    build_style_properties(background, color, border, shadow, opacity, transform)
}

/// Parse layout constraints from attributes
pub fn parse_layout_constraints(
    attrs: &HashMap<String, String>,
) -> Result<Option<LayoutConstraints>, String> {
    use crate::parser::style_parser::*;

    let mut constraints = LayoutConstraints::default();
    let mut has_any = false;

    // Parse sizing
    if let Some(value) = attrs.get("width") {
        constraints.width = Some(parse_length_attr(value)?);
        has_any = true;
    }

    if let Some(value) = attrs.get("height") {
        constraints.height = Some(parse_length_attr(value)?);
        has_any = true;
    }

    // Parse constraints
    if let Some(value) = attrs.get("min_width") {
        constraints.min_width = Some(parse_constraint(value)?);
        has_any = true;
    }

    if let Some(value) = attrs.get("max_width") {
        constraints.max_width = Some(parse_constraint(value)?);
        has_any = true;
    }

    if let Some(value) = attrs.get("min_height") {
        constraints.min_height = Some(parse_constraint(value)?);
        has_any = true;
    }

    if let Some(value) = attrs.get("max_height") {
        constraints.max_height = Some(parse_constraint(value)?);
        has_any = true;
    }

    // Parse layout
    if let Some(value) = attrs.get("padding") {
        constraints.padding = Some(parse_padding_attr(value)?);
        has_any = true;
    }

    if let Some(value) = attrs.get("spacing") {
        constraints.spacing = Some(parse_spacing(value)?);
        has_any = true;
    }

    // Parse alignment
    if let Some(value) = attrs.get("align_items") {
        constraints.align_items = Some(parse_alignment(value)?);
        has_any = true;
    }

    if let Some(value) = attrs.get("justify_content") {
        constraints.justify_content = Some(parse_justification(value)?);
        has_any = true;
    }

    if let Some(value) = attrs.get("align_self") {
        constraints.align_self = Some(parse_alignment(value)?);
        has_any = true;
    }

    // Parse direction
    if let Some(value) = attrs.get("direction") {
        constraints.direction = Some(crate::ir::layout::Direction::parse(value)?);
        has_any = true;
    }

    if has_any {
        constraints.validate()?;
        Ok(Some(constraints))
    } else {
        Ok(None)
    }
}

/// Parse state-prefixed attributes into state variants
/// Type alias for state variant maps
pub type StateVariantMaps = (
    HashMap<WidgetState, StyleProperties>,
    HashMap<crate::ir::theme::StateSelector, StyleProperties>,
);

/// Returns both single and combined state variants
pub fn parse_state_variants(attrs: &HashMap<String, String>) -> Result<StateVariantMaps, String> {
    use crate::ir::theme::StateSelector;

    let mut single_variants: HashMap<WidgetState, HashMap<String, String>> = HashMap::new();
    let mut combined_variants: HashMap<StateSelector, HashMap<String, String>> = HashMap::new();

    for (key, value) in attrs {
        // Check if key has state prefix
        if let Some((prefix, attr_name)) = split_state_prefix(key) {
            // Try to parse as combined states first
            if let Some(states) = parse_combined_states(prefix) {
                if states.len() == 1 {
                    // Single state
                    single_variants
                        .entry(states[0])
                        .or_default()
                        .insert(attr_name.to_string(), value.to_string());
                } else {
                    // Combined states
                    let selector = StateSelector::combined(states);
                    combined_variants
                        .entry(selector)
                        .or_default()
                        .insert(attr_name.to_string(), value.to_string());
                }
            } else {
                return Err(format!("Invalid state prefix: {}", prefix));
            }
        }
    }

    // Parse each single state's properties
    let mut single_result = HashMap::new();
    for (state, state_attrs) in single_variants {
        let style = parse_style_properties_from_attrs(&state_attrs)?;
        single_result.insert(state, style);
    }

    // Parse each combined state's properties
    let mut combined_result = HashMap::new();
    for (selector, state_attrs) in combined_variants {
        let style = parse_style_properties_from_attrs(&state_attrs)?;
        combined_result.insert(selector, style);
    }

    Ok((single_result, combined_result))
}

/// Split a state-prefixed attribute name
/// e.g., "hover:background" -> Some(("hover", "background"))
/// Also handles combined states: "hover:active:background" -> Some(("hover:active", "background"))
fn split_state_prefix(key: &str) -> Option<(&str, &str)> {
    // Find all colons
    let colons: Vec<usize> = key.match_indices(':').map(|(i, _)| i).collect();

    // The attribute name is after the last colon
    let last_colon = match colons.last() {
        Some(&pos) => pos,
        None => return None,
    };
    let attr_name = &key[last_colon + 1..];

    // Check if what comes after the last colon looks like an attribute name
    // (not a state name like "hover", "active", etc.)
    let potential_states = &key[..last_colon];

    // Split potential states by ':'
    let state_parts: Vec<&str> = potential_states.split(':').collect();

    // Verify all parts except the last are valid state names
    let all_valid_states = state_parts.iter().all(|&s| {
        matches!(
            s.trim().to_lowercase().as_str(),
            "hover" | "focus" | "active" | "disabled"
        )
    });

    if all_valid_states && !state_parts.is_empty() {
        // Return the combined state prefix and attribute name
        return Some((potential_states, attr_name));
    }

    None
}

/// Parse combined state prefix into individual states
/// e.g., "hover:active" -> vec![WidgetState::Hover, WidgetState::Active]
fn parse_combined_states(prefix: &str) -> Option<Vec<WidgetState>> {
    let parts: Vec<&str> = prefix.split(':').collect();
    let mut states = Vec::new();

    for part in parts {
        if let Some(state) = WidgetState::from_prefix(part) {
            // Avoid duplicates
            if !states.contains(&state) {
                states.push(state);
            }
        } else {
            return None;
        }
    }

    if states.is_empty() {
        None
    } else {
        Some(states)
    }
}

/// Parse a theme node from XML
pub fn parse_theme_from_node(
    node: roxmltree::Node,
    _source: &str,
) -> Result<Theme, crate::parser::error::ParseError> {
    use crate::parser::error::{ParseError, ParseErrorKind};

    let name = node
        .attribute("name")
        .map(|s| s.to_string())
        .unwrap_or_else(|| "default".to_string());

    let extends = node.attribute("extends").map(|s| s.to_string());

    let mut palette_attrs = HashMap::new();
    let mut typography_attrs = HashMap::new();
    let mut spacing_unit = None;

    // Parse child elements
    for child in node.children() {
        if child.node_type() != roxmltree::NodeType::Element {
            continue;
        }

        let tag = child.tag_name().name();

        if tag == "palette" {
            for attr in child.attributes() {
                palette_attrs.insert(attr.name().to_string(), attr.value().to_string());
            }
        } else if tag == "typography" {
            for attr in child.attributes() {
                typography_attrs.insert(attr.name().to_string(), attr.value().to_string());
            }
        } else if tag == "spacing"
            && let Some(unit) = child.attribute("unit")
        {
            spacing_unit = unit.parse::<f32>().ok();
        }
    }

    // Parse using existing function
    let theme = parse_theme(
        name,
        &palette_attrs,
        &typography_attrs,
        spacing_unit,
        extends,
    )
    .map_err(|e| ParseError {
        kind: ParseErrorKind::InvalidValue,
        message: format!("Failed to parse theme: {}", e),
        span: crate::ir::Span::default(),
        suggestion: None,
    })?;

    Ok(theme)
}

/// Parse a style class node from XML
pub fn parse_style_class_from_node(
    node: roxmltree::Node,
    _source: &str,
) -> Result<StyleClass, crate::parser::error::ParseError> {
    use crate::parser::error::{ParseError, ParseErrorKind};

    let name = node
        .attribute("name")
        .map(|s| s.to_string())
        .unwrap_or_default();

    if name.is_empty() {
        return Err(ParseError {
            kind: ParseErrorKind::InvalidValue,
            message: "Style class must have a name".to_string(),
            span: crate::ir::Span::default(),
            suggestion: None,
        });
    }

    // Collect all attributes
    let mut base_attrs = HashMap::new();
    let mut extends = Vec::new();
    let mut state_variants_raw: HashMap<WidgetState, HashMap<String, String>> = HashMap::new();
    let mut combined_state_variants_raw: HashMap<
        crate::ir::theme::StateSelector,
        HashMap<String, String>,
    > = HashMap::new();
    let mut layout = None;

    for attr in node.attributes() {
        let key = attr.name();
        let value = attr.value();

        // Check for extends
        if key == "extends" {
            extends = value.split_whitespace().map(|s| s.to_string()).collect();
            continue;
        }

        // Check for state variants (prefixed attributes)
        if let Some((prefix, attr_name)) = split_state_prefix(key) {
            // Try to parse as combined states
            if let Some(states) = parse_combined_states(prefix) {
                if states.len() == 1 {
                    // Single state
                    let state_attr = state_variants_raw.entry(states[0]).or_default();
                    state_attr.insert(attr_name.to_string(), value.to_string());
                } else {
                    // Combined states
                    let selector = crate::ir::theme::StateSelector::combined(states);
                    let state_attr = combined_state_variants_raw.entry(selector).or_default();
                    state_attr.insert(attr_name.to_string(), value.to_string());
                }
            } else {
                return Err(ParseError {
                    kind: ParseErrorKind::InvalidValue,
                    message: format!("Invalid state prefix: {}", prefix),
                    span: crate::ir::Span::default(),
                    suggestion: None,
                });
            }
            continue;
        }

        // Check for layout attributes
        let layout_attr_names = [
            "width",
            "height",
            "min_width",
            "max_width",
            "min_height",
            "max_height",
            "padding",
            "spacing",
            "align_items",
            "justify_content",
            "align_self",
            "direction",
        ];

        if layout_attr_names.contains(&key) {
            base_attrs.insert(key.to_string(), value.to_string());
            continue;
        }

        // Regular style attribute
        base_attrs.insert(key.to_string(), value.to_string());
    }

    // Parse child elements for state variants and base styles
    for child in node.children() {
        if child.node_type() != roxmltree::NodeType::Element {
            continue;
        }

        let tag = child.tag_name().name();

        // Handle state variant child elements
        if let Some(state) = WidgetState::from_prefix(tag) {
            let state_attr = state_variants_raw.entry(state).or_default();
            for attr in child.attributes() {
                state_attr.insert(attr.name().to_string(), attr.value().to_string());
            }
            continue;
        }

        // Handle base element
        if tag == "base" {
            for attr in child.attributes() {
                base_attrs.insert(attr.name().to_string(), attr.value().to_string());
            }
            continue;
        }

        // Handle layout child element
        if tag == "layout" {
            let mut layout_attrs = HashMap::new();
            for attr in child.attributes() {
                layout_attrs.insert(attr.name().to_string(), attr.value().to_string());
            }
            layout = parse_layout_constraints(&layout_attrs).map_err(|e| ParseError {
                kind: ParseErrorKind::InvalidValue,
                message: format!("Failed to parse layout: {}", e),
                span: crate::ir::Span::default(),
                suggestion: None,
            })?;
            continue;
        }
    }

    // Parse layout if any layout attributes present
    if base_attrs.keys().any(|k| {
        matches!(
            k.as_str(),
            "width"
                | "height"
                | "min_width"
                | "max_width"
                | "min_height"
                | "max_height"
                | "padding"
                | "spacing"
                | "align_items"
                | "justify_content"
                | "align_self"
                | "direction"
        )
    }) {
        layout = parse_layout_constraints(&base_attrs).map_err(|e| ParseError {
            kind: ParseErrorKind::InvalidValue,
            message: format!("Failed to parse layout: {}", e),
            span: crate::ir::Span::default(),
            suggestion: None,
        })?;

        // Remove layout attributes from base_attrs
        let layout_keys: Vec<String> = base_attrs
            .keys()
            .filter(|k| {
                matches!(
                    k.as_str(),
                    "width"
                        | "height"
                        | "min_width"
                        | "max_width"
                        | "min_height"
                        | "max_height"
                        | "padding"
                        | "spacing"
                        | "align_items"
                        | "justify_content"
                        | "align_self"
                        | "direction"
                )
            })
            .cloned()
            .collect();

        for key in layout_keys {
            base_attrs.remove(&key);
        }
    }

    // Parse state variants into StyleProperties
    let mut state_variants = HashMap::new();
    for (state, state_attrs) in state_variants_raw {
        let style = parse_style_properties_from_attrs(&state_attrs).map_err(|e| ParseError {
            kind: ParseErrorKind::InvalidValue,
            message: format!("Failed to parse state variant for {:?}: {}", state, e),
            span: crate::ir::Span::default(),
            suggestion: None,
        })?;
        state_variants.insert(state, style);
    }

    // Parse combined state variants into StyleProperties
    let mut combined_state_variants = HashMap::new();
    for (selector, state_attrs) in combined_state_variants_raw {
        let style = parse_style_properties_from_attrs(&state_attrs).map_err(|e| ParseError {
            kind: ParseErrorKind::InvalidValue,
            message: format!(
                "Failed to parse combined state variant for {:?}: {}",
                selector, e
            ),
            span: crate::ir::Span::default(),
            suggestion: None,
        })?;
        combined_state_variants.insert(selector, style);
    }

    // Parse using existing function
    let class = parse_style_class(
        name,
        &base_attrs,
        extends,
        state_variants,
        combined_state_variants,
        layout,
    )
    .map_err(|e| ParseError {
        kind: ParseErrorKind::InvalidValue,
        message: format!("Failed to parse style class: {}", e),
        span: crate::ir::Span::default(),
        suggestion: None,
    })?;

    Ok(class)
}