Skip to main content

strata_style/
types.rs

1//! Core CSS style types, layout enums, and ComputedStyle representation.
2
3use std::sync::Arc;
4pub use strata_primitives::color::Rgba;
5pub use strata_primitives::geom::{EdgeInsets, Matrix4x4};
6pub use strata_primitives::AtomId;
7
8pub type Color = Rgba;
9pub type CustomPropertyMap = Arc<Vec<(AtomId, AtomId)>>;
10
11/// Box layout display model.
12#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
13pub enum Display {
14    #[default]
15    Block,
16    Inline,
17    InlineBlock,
18    ListItem,
19    Flex,
20    InlineFlex,
21    Grid,
22    InlineGrid,
23    Table,
24    InlineTable,
25    TableRowGroup,
26    TableHeaderGroup,
27    TableFooterGroup,
28    TableRow,
29    TableCell,
30    TableCaption,
31    TableColumnGroup,
32    TableColumn,
33    None,
34}
35
36/// CSS table layout algorithm mode.
37#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
38pub enum TableLayout {
39    #[default]
40    Auto,
41    Fixed,
42}
43
44/// CSS border collapse model for tables.
45#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
46pub enum BorderCollapse {
47    #[default]
48    Separate,
49    Collapse,
50}
51
52/// CSS table caption placement.
53#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
54pub enum CaptionSide {
55    #[default]
56    Top,
57    Bottom,
58}
59
60/// Positioning scheme in CSS box layout.
61#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
62pub enum Position {
63    #[default]
64    Static,
65    Relative,
66    Absolute,
67    Fixed,
68    Sticky,
69}
70
71/// CSS float property defining element lateral drift.
72#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
73pub enum Float {
74    #[default]
75    None,
76    Left,
77    Right,
78    InlineStart,
79    InlineEnd,
80}
81
82/// CSS clear property defining clearance below floating boxes.
83#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
84pub enum Clear {
85    #[default]
86    None,
87    Left,
88    Right,
89    Both,
90    InlineStart,
91    InlineEnd,
92}
93
94/// CSS Length and Dimension units.
95#[derive(Debug, Clone, Copy, PartialEq, Default)]
96pub enum Dimension {
97    #[default]
98    Auto,
99    Px(f32),
100    Percent(f32),
101    Vw(f32),
102    Vh(f32),
103    Rem(f32),
104    Em(f32),
105    Calc(crate::calc::CalcId),
106    MinContent,
107    MaxContent,
108    FitContent(f32),
109}
110
111impl Dimension {
112    /// Creates a Dimension variant from an AST calc expression.
113    pub fn calc(expr: crate::calc::CalcExpr) -> Self {
114        Self::Calc(crate::calc::intern_calc(expr))
115    }
116
117    /// Resolves the dimension into concrete pixels given a context.
118    pub fn resolve_px(
119        &self,
120        parent_size: f32,
121        root_font_size: f32,
122        current_font_size: f32,
123    ) -> Option<f32> {
124        match *self {
125            Self::Auto => None,
126            Self::Px(px) => Some(px),
127            Self::Percent(pct) => Some(parent_size * (pct / 100.0)),
128            Self::Vw(vw) => Some(vw), // Handled by viewport context in layout
129            Self::Vh(vh) => Some(vh),
130            Self::Rem(rem) => Some(rem * root_font_size),
131            Self::Em(em) => Some(em * current_font_size),
132            Self::Calc(id) => crate::calc::get_calc(id).map(|expr| {
133                let ctx = crate::calc::CalcContext {
134                    parent_size,
135                    root_font_size,
136                    current_font_size,
137                    viewport_width: 1920.0,
138                    viewport_height: 1080.0,
139                };
140                expr.eval(&ctx)
141            }),
142            Self::MinContent | Self::MaxContent | Self::FitContent(_) => None,
143        }
144    }
145}
146
147/// Box sizing model (CSS box-sizing).
148#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
149pub enum BoxSizing {
150    #[default]
151    BorderBox,
152    ContentBox,
153}
154
155/// Flex container main axis direction.
156#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
157pub enum FlexDirection {
158    #[default]
159    Row,
160    RowReverse,
161    Column,
162    ColumnReverse,
163}
164
165/// Flex line wrapping behavior.
166#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
167pub enum FlexWrap {
168    #[default]
169    NoWrap,
170    Wrap,
171    WrapReverse,
172}
173
174/// Main-axis alignment within flex containers and grid tracks.
175#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
176pub enum JustifyContent {
177    #[default]
178    FlexStart,
179    FlexEnd,
180    Center,
181    SpaceBetween,
182    SpaceAround,
183    SpaceEvenly,
184}
185
186/// Cross-axis alignment for items in flex/grid containers.
187#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
188pub enum AlignItems {
189    #[default]
190    Stretch,
191    FlexStart,
192    FlexEnd,
193    Center,
194    Baseline,
195}
196
197/// Self-alignment on the cross-axis overriding container `align-items`.
198#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
199pub enum AlignSelf {
200    #[default]
201    Auto,
202    Stretch,
203    FlexStart,
204    FlexEnd,
205    Center,
206    Baseline,
207}
208
209/// Individual track sizing breadth used in CSS minmax() functions.
210#[derive(Debug, Clone, Copy, PartialEq)]
211pub enum GridTrackBreadth {
212    Auto,
213    Px(f32),
214    Percent(f32),
215    Fr(f32),
216    MinContent,
217    MaxContent,
218}
219
220/// CSS Grid track sizing definition (W3C CSS Grid Layout Level 2).
221#[derive(Debug, Clone, Copy, PartialEq)]
222pub enum GridTrack {
223    Auto,
224    Px(f32),
225    Percent(f32),
226    Fr(f32),
227    MinContent,
228    MaxContent,
229    Subgrid,
230    MinMax(GridTrackBreadth, GridTrackBreadth),
231}
232
233/// CSS grid-auto-flow property (W3C CSS Grid Level 2).
234#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
235pub enum GridAutoFlow {
236    #[default]
237    Row,
238    Column,
239    RowDense,
240    ColumnDense,
241}
242
243impl GridAutoFlow {
244    pub fn is_row(&self) -> bool {
245        matches!(self, Self::Row | Self::RowDense)
246    }
247
248    pub fn is_dense(&self) -> bool {
249        matches!(self, Self::RowDense | Self::ColumnDense)
250    }
251
252    pub fn parse(s: &str) -> Option<Self> {
253        let s = s.trim().to_ascii_lowercase();
254        let tokens: Vec<&str> = s.split_whitespace().collect();
255        match tokens.as_slice() {
256            ["row"] => Some(Self::Row),
257            ["column"] => Some(Self::Column),
258            ["dense"] => Some(Self::RowDense),
259            ["row", "dense"] | ["dense", "row"] => Some(Self::RowDense),
260            ["column", "dense"] | ["dense", "column"] => Some(Self::ColumnDense),
261            _ => None,
262        }
263    }
264}
265
266/// 4-corner border radius definition.
267#[repr(C)]
268#[derive(Debug, Clone, Copy, PartialEq, Default)]
269pub struct BorderRadius {
270    pub top_left: f32,
271    pub top_right: f32,
272    pub bottom_right: f32,
273    pub bottom_left: f32,
274}
275
276impl BorderRadius {
277    pub const ZERO: Self = Self::all(0.0);
278
279    pub const fn new(top_left: f32, top_right: f32, bottom_right: f32, bottom_left: f32) -> Self {
280        Self {
281            top_left,
282            top_right,
283            bottom_right,
284            bottom_left,
285        }
286    }
287
288    pub const fn all(radius: f32) -> Self {
289        Self {
290            top_left: radius,
291            top_right: radius,
292            bottom_right: radius,
293            bottom_left: radius,
294        }
295    }
296}
297
298/// Standard W3C CSS blend modes for mix-blend-mode and background-blend-mode.
299#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Default)]
300pub enum BlendMode {
301    #[default]
302    Normal,
303    Multiply,
304    Screen,
305    Overlay,
306    Darken,
307    Lighten,
308    ColorDodge,
309    ColorBurn,
310    HardLight,
311    SoftLight,
312    Difference,
313    Exclusion,
314    Hue,
315    Saturation,
316    Color,
317    Luminosity,
318}
319
320impl BlendMode {
321    pub fn as_str(&self) -> &'static str {
322        match self {
323            Self::Normal => "normal",
324            Self::Multiply => "multiply",
325            Self::Screen => "screen",
326            Self::Overlay => "overlay",
327            Self::Darken => "darken",
328            Self::Lighten => "lighten",
329            Self::ColorDodge => "color-dodge",
330            Self::ColorBurn => "color-burn",
331            Self::HardLight => "hard-light",
332            Self::SoftLight => "soft-light",
333            Self::Difference => "difference",
334            Self::Exclusion => "exclusion",
335            Self::Hue => "hue",
336            Self::Saturation => "saturation",
337            Self::Color => "color",
338            Self::Luminosity => "luminosity",
339        }
340    }
341
342    pub fn parse(s: &str) -> Option<Self> {
343        match s.trim().to_ascii_lowercase().as_str() {
344            "normal" => Some(Self::Normal),
345            "multiply" => Some(Self::Multiply),
346            "screen" => Some(Self::Screen),
347            "overlay" => Some(Self::Overlay),
348            "darken" => Some(Self::Darken),
349            "lighten" => Some(Self::Lighten),
350            "color-dodge" => Some(Self::ColorDodge),
351            "color-burn" => Some(Self::ColorBurn),
352            "hard-light" => Some(Self::HardLight),
353            "soft-light" => Some(Self::SoftLight),
354            "difference" => Some(Self::Difference),
355            "exclusion" => Some(Self::Exclusion),
356            "hue" => Some(Self::Hue),
357            "saturation" => Some(Self::Saturation),
358            "color" => Some(Self::Color),
359            "luminosity" => Some(Self::Luminosity),
360            _ => None,
361        }
362    }
363
364    /// Returns true if this blend mode evaluates color channels independently.
365    #[inline]
366    pub fn is_separable(&self) -> bool {
367        !matches!(
368            self,
369            Self::Hue | Self::Saturation | Self::Color | Self::Luminosity
370        )
371    }
372}
373
374/// CSS isolation property determining stacking group containment for blend modes.
375#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Default)]
376pub enum Isolation {
377    #[default]
378    Auto,
379    Isolate,
380}
381
382impl Isolation {
383    pub fn as_str(&self) -> &'static str {
384        match self {
385            Self::Auto => "auto",
386            Self::Isolate => "isolate",
387        }
388    }
389
390    pub fn parse(s: &str) -> Option<Self> {
391        match s.trim().to_ascii_lowercase().as_str() {
392            "auto" => Some(Self::Auto),
393            "isolate" => Some(Self::Isolate),
394            _ => None,
395        }
396    }
397}
398
399/// CSS box-shadow effect definition.
400#[derive(Debug, Clone, PartialEq)]
401pub struct BoxShadow {
402    pub offset_x: f32,
403    pub offset_y: f32,
404    pub blur_radius: f32,
405    pub spread_radius: f32,
406    pub color: Color,
407    pub inset: bool,
408}
409
410/// A color stop in a CSS gradient definition.
411#[derive(Debug, Clone, PartialEq)]
412pub struct ColorStop {
413    pub color: Color,
414    /// Stop position as a fraction [0.0, 1.0], or None for automatic distribution.
415    pub position: Option<f32>,
416}
417
418/// CSS Gradient background specification.
419#[derive(Debug, Clone, PartialEq)]
420pub enum Gradient {
421    Linear {
422        /// Gradient orientation in degrees (0 = to top, 90 = to right, 180 = to bottom).
423        angle_deg: f32,
424        stops: Vec<ColorStop>,
425    },
426    Radial {
427        /// Center origin fraction (cx, cy), typically (0.5, 0.5).
428        center: (f32, f32),
429        stops: Vec<ColorStop>,
430    },
431    Conic {
432        angle_deg: f32,
433        center: (f32, f32),
434        stops: Vec<ColorStop>,
435    },
436}
437
438/// Content overflow clipping behavior.
439#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
440pub enum Overflow {
441    #[default]
442    Visible,
443    Hidden,
444    Scroll,
445    Auto,
446}
447
448/// Typographic font weight.
449#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
450pub enum FontWeight {
451    Thin = 100,
452    ExtraLight = 200,
453    Light = 300,
454    #[default]
455    Normal = 400,
456    Medium = 500,
457    SemiBold = 600,
458    Bold = 700,
459    ExtraBold = 800,
460    Black = 900,
461}
462
463impl FontWeight {
464    pub fn from_u16(weight: u16) -> Self {
465        match weight {
466            0..=150 => Self::Thin,
467            151..=250 => Self::ExtraLight,
468            251..=350 => Self::Light,
469            351..=450 => Self::Normal,
470            451..=550 => Self::Medium,
471            551..=650 => Self::SemiBold,
472            651..=750 => Self::Bold,
473            751..=850 => Self::ExtraBold,
474            _ => Self::Black,
475        }
476    }
477}
478
479/// Text horizontal alignment.
480#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
481pub enum TextAlign {
482    #[default]
483    Left,
484    Center,
485    Right,
486    Justify,
487}
488
489/// Font style (normal, italic, oblique).
490#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
491pub enum FontStyle {
492    #[default]
493    Normal,
494    Italic,
495    Oblique,
496}
497
498/// Text overflow behavior.
499#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
500pub enum TextOverflow {
501    #[default]
502    Clip,
503    Ellipsis,
504}
505
506/// Text decoration line.
507#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
508pub enum TextDecoration {
509    #[default]
510    None,
511    Underline,
512    LineThrough,
513    Overline,
514}
515
516/// Text capitalization transform.
517#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
518pub enum TextTransform {
519    #[default]
520    None,
521    Uppercase,
522    Lowercase,
523    Capitalize,
524}
525
526/// Whitespace handling behavior.
527#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
528pub enum WhiteSpace {
529    #[default]
530    Normal,
531    NoWrap,
532    Pre,
533    PreWrap,
534    PreLine,
535}
536
537/// Vertical alignment within line box or table cell.
538#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
539pub enum VerticalAlign {
540    #[default]
541    Baseline,
542    Top,
543    Middle,
544    Bottom,
545    TextTop,
546    TextBottom,
547    Sub,
548    Super,
549}
550
551/// Mouse pointer cursor style.
552#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
553pub enum Cursor {
554    #[default]
555    Default,
556    Pointer,
557    Text,
558    Move,
559    NotAllowed,
560    Crosshair,
561    Grab,
562    Grabbing,
563    ColResize,
564    RowResize,
565    Wait,
566    Help,
567    None,
568}
569
570/// Text selection behavior.
571#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
572pub enum UserSelect {
573    #[default]
574    Auto,
575    None,
576    Text,
577    All,
578}
579
580/// Pointer event pass-through behavior.
581#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
582pub enum PointerEvents {
583    #[default]
584    Auto,
585    None,
586}
587
588/// Element visibility.
589#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
590pub enum Visibility {
591    #[default]
592    Visible,
593    Hidden,
594    Collapse,
595}
596
597/// Border and outline stroke style.
598#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
599pub enum BorderStyle {
600    #[default]
601    Solid,
602    Dashed,
603    Dotted,
604    Double,
605    None,
606    Hidden,
607}
608
609/// Content visibility optimization (W3C CSS Containment Module Level 2).
610#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
611pub enum ContentVisibility {
612    #[default]
613    Visible,
614    Auto,
615    Hidden,
616}
617
618/// CSS Containment specification (W3C CSS Containment Module Level 2).
619#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
620pub struct Containment {
621    pub size: bool,
622    pub inline_size: bool,
623    pub layout: bool,
624    pub paint: bool,
625    pub style: bool,
626}
627
628impl Containment {
629    pub const NONE: Self = Self {
630        size: false,
631        inline_size: false,
632        layout: false,
633        paint: false,
634        style: false,
635    };
636
637    pub const STRICT: Self = Self {
638        size: true,
639        inline_size: false,
640        layout: true,
641        paint: true,
642        style: false,
643    };
644
645    pub const CONTENT: Self = Self {
646        size: false,
647        inline_size: false,
648        layout: true,
649        paint: true,
650        style: false,
651    };
652
653    #[inline]
654    pub fn contains_layout(&self) -> bool {
655        self.layout
656    }
657
658    #[inline]
659    pub fn contains_size(&self) -> bool {
660        self.size
661    }
662
663    #[inline]
664    pub fn contains_paint(&self) -> bool {
665        self.paint
666    }
667}
668
669/// Stepped timing function transition position (W3C CSS Easing Functions Level 1).
670#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
671pub enum StepPosition {
672    JumpStart,
673    #[default]
674    JumpEnd,
675    JumpNone,
676    JumpBoth,
677    Start,
678    End,
679}
680
681/// Animation and transition timing function (easing curve).
682#[derive(Debug, Clone, Copy, PartialEq, Default)]
683pub enum TransitionEasing {
684    Linear,
685    #[default]
686    Ease,
687    EaseIn,
688    EaseOut,
689    EaseInOut,
690    StepStart,
691    StepEnd,
692    Steps(u32, StepPosition),
693    CubicBezier(f32, f32, f32, f32),
694}
695
696impl TransitionEasing {
697    /// Evaluates the easing function at normalized progression `t` in `[0.0, 1.0]`.
698    pub fn evaluate(&self, t: f32) -> f32 {
699        let t = t.clamp(0.0, 1.0);
700        match self {
701            Self::Linear => t,
702            Self::Ease => cubic_bezier_solve(t, 0.25, 0.1, 0.25, 1.0),
703            Self::EaseIn => cubic_bezier_solve(t, 0.42, 0.0, 1.0, 1.0),
704            Self::EaseOut => cubic_bezier_solve(t, 0.0, 0.0, 0.58, 1.0),
705            Self::EaseInOut => cubic_bezier_solve(t, 0.42, 0.0, 0.58, 1.0),
706            Self::StepStart => {
707                if t > 0.0 {
708                    1.0
709                } else {
710                    0.0
711                }
712            }
713            Self::StepEnd => {
714                if t >= 1.0 {
715                    1.0
716                } else {
717                    0.0
718                }
719            }
720            Self::Steps(n, pos) => evaluate_steps(t, *n, *pos),
721            Self::CubicBezier(x1, y1, x2, y2) => cubic_bezier_solve(t, *x1, *y1, *x2, *y2),
722        }
723    }
724
725    /// Solves the easing function at normalized progression `t` in `[0.0, 1.0]`.
726    #[inline(always)]
727    pub fn solve(&self, t: f32) -> f32 {
728        self.evaluate(t)
729    }
730
731    /// Parses a CSS timing function string into a `TransitionEasing`.
732    pub fn parse(s: &str) -> Option<Self> {
733        let s = s.trim();
734        let lower = s.to_ascii_lowercase();
735        match lower.as_str() {
736            "linear" => return Some(Self::Linear),
737            "ease" => return Some(Self::Ease),
738            "ease-in" => return Some(Self::EaseIn),
739            "ease-out" => return Some(Self::EaseOut),
740            "ease-in-out" => return Some(Self::EaseInOut),
741            "step-start" => return Some(Self::StepStart),
742            "step-end" => return Some(Self::StepEnd),
743            _ => {}
744        }
745
746        if lower.starts_with("cubic-bezier(") && lower.ends_with(')') {
747            let inner = &s[13..s.len() - 1];
748            let parts: Vec<&str> = inner.split(',').collect();
749            if parts.len() == 4 {
750                if let (Ok(x1), Ok(y1), Ok(x2), Ok(y2)) = (
751                    parts[0].trim().parse::<f32>(),
752                    parts[1].trim().parse::<f32>(),
753                    parts[2].trim().parse::<f32>(),
754                    parts[3].trim().parse::<f32>(),
755                ) {
756                    return Some(Self::CubicBezier(x1, y1, x2, y2));
757                }
758            }
759        }
760
761        if lower.starts_with("steps(") && lower.ends_with(')') {
762            let inner = &s[6..s.len() - 1];
763            let parts: Vec<&str> = inner.split(',').collect();
764            if parts.len() == 1 {
765                if let Ok(n) = parts[0].trim().parse::<u32>() {
766                    return Some(Self::Steps(n, StepPosition::End));
767                }
768            } else if parts.len() == 2 {
769                if let Ok(n) = parts[0].trim().parse::<u32>() {
770                    let pos = match parts[1].trim().to_ascii_lowercase().as_str() {
771                        "jump-start" | "start" => StepPosition::JumpStart,
772                        "jump-end" | "end" => StepPosition::JumpEnd,
773                        "jump-none" => StepPosition::JumpNone,
774                        "jump-both" => StepPosition::JumpBoth,
775                        _ => StepPosition::End,
776                    };
777                    return Some(Self::Steps(n, pos));
778                }
779            }
780        }
781
782        None
783    }
784}
785
786/// Solves a cubic Bézier curve for parameter `x` using De Casteljau's algorithm and root finding.
787#[inline(always)]
788pub fn cubic_bezier_solve(x: f32, x1: f32, y1: f32, x2: f32, y2: f32) -> f32 {
789    crate::bezier::cubic_bezier_solve(x, x1, y1, x2, y2)
790}
791
792/// Evaluates stepped progress for `steps(n, position)`.
793pub fn evaluate_steps(t: f32, n: u32, pos: StepPosition) -> f32 {
794    let n = n.max(1) as f32;
795    let t = t.clamp(0.0, 1.0);
796    match pos {
797        StepPosition::JumpStart | StepPosition::Start => ((t * n).floor() + 1.0) / n,
798        StepPosition::JumpEnd | StepPosition::End => (t * n).floor() / n,
799        StepPosition::JumpNone => {
800            if n <= 1.0 {
801                t
802            } else {
803                (t * (n - 1.0)).floor() / (n - 1.0)
804            }
805        }
806        StepPosition::JumpBoth => ((t * (n + 1.0)).floor() + 1.0) / (n + 1.0),
807    }
808    .clamp(0.0, 1.0)
809}
810
811/// Identifies an individual animatable CSS property target for transitions.
812#[derive(Debug, Clone, PartialEq, Eq, Hash, Default)]
813pub enum TransitionProperty {
814    #[default]
815    All,
816    None,
817    Color,
818    BackgroundColor,
819    Opacity,
820    Transform,
821    Width,
822    Height,
823    MinWidth,
824    MaxWidth,
825    MinHeight,
826    MaxHeight,
827    Margin,
828    Padding,
829    BorderColor,
830    BorderWidth,
831    BorderRadius,
832    Flex,
833    FlexGrow,
834    FlexShrink,
835    FlexBasis,
836    Gap,
837    GapRow,
838    GapCol,
839    BoxShadow,
840    Filter,
841    BackdropFilter,
842    ClipPath,
843    MixBlendMode,
844    Isolation,
845    ViewTransitionName,
846    Custom(String),
847}
848
849impl TransitionProperty {
850    /// Parses a property identifier string into a `TransitionProperty`.
851    pub fn parse(s: &str) -> Self {
852        match s.trim().to_ascii_lowercase().as_str() {
853            "all" => Self::All,
854            "none" => Self::None,
855            "color" => Self::Color,
856            "background-color" | "background" => Self::BackgroundColor,
857            "opacity" => Self::Opacity,
858            "transform" => Self::Transform,
859            "width" => Self::Width,
860            "height" => Self::Height,
861            "min-width" => Self::MinWidth,
862            "max-width" => Self::MaxWidth,
863            "min-height" => Self::MinHeight,
864            "max-height" => Self::MaxHeight,
865            "margin" => Self::Margin,
866            "padding" => Self::Padding,
867            "border-color" => Self::BorderColor,
868            "border-width" => Self::BorderWidth,
869            "border-radius" => Self::BorderRadius,
870            "flex" => Self::Flex,
871            "flex-grow" => Self::FlexGrow,
872            "flex-shrink" => Self::FlexShrink,
873            "flex-basis" => Self::FlexBasis,
874            "gap" => Self::Gap,
875            "row-gap" | "gap-row" => Self::GapRow,
876            "column-gap" | "gap-col" => Self::GapCol,
877            "box-shadow" => Self::BoxShadow,
878            "filter" => Self::Filter,
879            "backdrop-filter" => Self::BackdropFilter,
880            "clip-path" => Self::ClipPath,
881            "mix-blend-mode" => Self::MixBlendMode,
882            "isolation" => Self::Isolation,
883            "view-transition-name" => Self::ViewTransitionName,
884            other => Self::Custom(other.to_string()),
885        }
886    }
887
888    /// Evaluates if this transition property matches a specific target CSS property.
889    pub fn matches(&self, target: &str) -> bool {
890        match self {
891            Self::All => true,
892            Self::None => false,
893            Self::Color => target == "color",
894            Self::BackgroundColor => target == "background-color" || target == "background",
895            Self::Opacity => target == "opacity",
896            Self::Transform => target == "transform",
897            Self::Width => target == "width",
898            Self::Height => target == "height",
899            Self::MinWidth => target == "min-width",
900            Self::MaxWidth => target == "max-width",
901            Self::MinHeight => target == "min-height",
902            Self::MaxHeight => target == "max-height",
903            Self::Margin => target.starts_with("margin"),
904            Self::Padding => target.starts_with("padding"),
905            Self::BorderColor => target.starts_with("border-color"),
906            Self::BorderWidth => target.starts_with("border-width"),
907            Self::BorderRadius => target.starts_with("border-radius"),
908            Self::Flex => {
909                target == "flex"
910                    || target == "flex-grow"
911                    || target == "flex-shrink"
912                    || target == "flex-basis"
913            }
914            Self::FlexGrow => target == "flex-grow",
915            Self::FlexShrink => target == "flex-shrink",
916            Self::FlexBasis => target == "flex-basis",
917            Self::Gap => target == "gap" || target == "row-gap" || target == "column-gap",
918            Self::GapRow => target == "row-gap",
919            Self::GapCol => target == "column-gap",
920            Self::BoxShadow => target == "box-shadow",
921            Self::Filter => target == "filter",
922            Self::BackdropFilter => target == "backdrop-filter",
923            Self::ClipPath => target == "clip-path",
924            Self::MixBlendMode => target == "mix-blend-mode",
925            Self::Isolation => target == "isolation",
926            Self::ViewTransitionName => target == "view-transition-name",
927            Self::Custom(c) => c.eq_ignore_ascii_case(target),
928        }
929    }
930
931    /// Returns `true` when animating or transitioning this property affects box layout/reflow.
932    #[inline]
933    pub fn is_layout_affecting(&self) -> bool {
934        matches!(
935            self,
936            Self::Width
937                | Self::Height
938                | Self::MinWidth
939                | Self::MaxWidth
940                | Self::MinHeight
941                | Self::MaxHeight
942                | Self::Margin
943                | Self::Padding
944                | Self::BorderWidth
945                | Self::Flex
946                | Self::FlexGrow
947                | Self::FlexShrink
948                | Self::FlexBasis
949                | Self::Gap
950                | Self::GapRow
951                | Self::GapCol
952        )
953    }
954
955    /// Returns the canonical CSS property name string.
956    pub fn as_str(&self) -> &str {
957        match self {
958            Self::All => "all",
959            Self::None => "none",
960            Self::Color => "color",
961            Self::BackgroundColor => "background-color",
962            Self::Opacity => "opacity",
963            Self::Transform => "transform",
964            Self::Width => "width",
965            Self::Height => "height",
966            Self::MinWidth => "min-width",
967            Self::MaxWidth => "max-width",
968            Self::MinHeight => "min-height",
969            Self::MaxHeight => "max-height",
970            Self::Margin => "margin",
971            Self::Padding => "padding",
972            Self::BorderColor => "border-color",
973            Self::BorderWidth => "border-width",
974            Self::BorderRadius => "border-radius",
975            Self::Flex => "flex",
976            Self::FlexGrow => "flex-grow",
977            Self::FlexShrink => "flex-shrink",
978            Self::FlexBasis => "flex-basis",
979            Self::Gap => "gap",
980            Self::GapRow => "row-gap",
981            Self::GapCol => "column-gap",
982            Self::BoxShadow => "box-shadow",
983            Self::Filter => "filter",
984            Self::BackdropFilter => "backdrop-filter",
985            Self::ClipPath => "clip-path",
986            Self::MixBlendMode => "mix-blend-mode",
987            Self::Isolation => "isolation",
988            Self::ViewTransitionName => "view-transition-name",
989            Self::Custom(s) => s.as_str(),
990        }
991    }
992}
993
994/// Transition behavior for discrete animatable properties (W3C CSS Transitions Level 2).
995#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
996pub enum TransitionBehavior {
997    #[default]
998    Normal,
999    AllowDiscrete,
1000}
1001
1002impl TransitionBehavior {
1003    /// Parses a CSS transition-behavior string.
1004    pub fn parse(s: &str) -> Option<Self> {
1005        match s.trim().to_ascii_lowercase().as_str() {
1006            "normal" => Some(Self::Normal),
1007            "allow-discrete" => Some(Self::AllowDiscrete),
1008            _ => None,
1009        }
1010    }
1011}
1012
1013/// Complete transition descriptor specifying timing, delay, easing, and behavior.
1014#[derive(Debug, Clone, PartialEq)]
1015pub struct TransitionSpec {
1016    pub property: TransitionProperty,
1017    pub duration_ms: f32,
1018    pub timing_function: TransitionEasing,
1019    pub delay_ms: f32,
1020    pub behavior: TransitionBehavior,
1021}
1022
1023impl Default for TransitionSpec {
1024    fn default() -> Self {
1025        Self {
1026            property: TransitionProperty::All,
1027            duration_ms: 0.0,
1028            timing_function: TransitionEasing::Ease,
1029            delay_ms: 0.0,
1030            behavior: TransitionBehavior::Normal,
1031        }
1032    }
1033}
1034
1035/// CSS animation-direction property (W3C CSS Animations Level 1).
1036#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
1037pub enum AnimationDirection {
1038    #[default]
1039    Normal,
1040    Reverse,
1041    Alternate,
1042    AlternateReverse,
1043}
1044
1045impl AnimationDirection {
1046    pub fn parse(s: &str) -> Option<Self> {
1047        match s.trim().to_ascii_lowercase().as_str() {
1048            "normal" => Some(Self::Normal),
1049            "reverse" => Some(Self::Reverse),
1050            "alternate" => Some(Self::Alternate),
1051            "alternate-reverse" => Some(Self::AlternateReverse),
1052            _ => None,
1053        }
1054    }
1055
1056    pub fn as_str(&self) -> &'static str {
1057        match self {
1058            Self::Normal => "normal",
1059            Self::Reverse => "reverse",
1060            Self::Alternate => "alternate",
1061            Self::AlternateReverse => "alternate-reverse",
1062        }
1063    }
1064}
1065
1066/// CSS animation-fill-mode property (W3C CSS Animations Level 1).
1067#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
1068pub enum AnimationFillMode {
1069    #[default]
1070    None,
1071    Forwards,
1072    Backwards,
1073    Both,
1074}
1075
1076impl AnimationFillMode {
1077    pub fn parse(s: &str) -> Option<Self> {
1078        match s.trim().to_ascii_lowercase().as_str() {
1079            "none" => Some(Self::None),
1080            "forwards" => Some(Self::Forwards),
1081            "backwards" => Some(Self::Backwards),
1082            "both" => Some(Self::Both),
1083            _ => None,
1084        }
1085    }
1086
1087    pub fn as_str(&self) -> &'static str {
1088        match self {
1089            Self::None => "none",
1090            Self::Forwards => "forwards",
1091            Self::Backwards => "backwards",
1092            Self::Both => "both",
1093        }
1094    }
1095}
1096
1097/// CSS animation-play-state property (W3C CSS Animations Level 1).
1098#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
1099pub enum AnimationPlayState {
1100    #[default]
1101    Running,
1102    Paused,
1103}
1104
1105impl AnimationPlayState {
1106    pub fn parse(s: &str) -> Option<Self> {
1107        match s.trim().to_ascii_lowercase().as_str() {
1108            "running" => Some(Self::Running),
1109            "paused" => Some(Self::Paused),
1110            _ => None,
1111        }
1112    }
1113
1114    pub fn as_str(&self) -> &'static str {
1115        match self {
1116            Self::Running => "running",
1117            Self::Paused => "paused",
1118        }
1119    }
1120}
1121
1122/// CSS animation-iteration-count property (W3C CSS Animations Level 1).
1123#[derive(Debug, Clone, Copy, PartialEq)]
1124pub enum AnimationIterationCount {
1125    Infinite,
1126    Count(f32),
1127}
1128
1129impl Default for AnimationIterationCount {
1130    fn default() -> Self {
1131        Self::Count(1.0)
1132    }
1133}
1134
1135impl AnimationIterationCount {
1136    pub fn parse(s: &str) -> Option<Self> {
1137        let s = s.trim();
1138        if s.eq_ignore_ascii_case("infinite") {
1139            Some(Self::Infinite)
1140        } else if let Ok(n) = s.parse::<f32>() {
1141            if n >= 0.0 {
1142                Some(Self::Count(n))
1143            } else {
1144                None
1145            }
1146        } else {
1147            None
1148        }
1149    }
1150}
1151
1152/// Target scroll axis for scroll-driven animations (W3C CSS Scroll-Driven Animations Level 1).
1153#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
1154pub enum ScrollAxis {
1155    #[default]
1156    Block,
1157    Inline,
1158    Vertical,
1159    Horizontal,
1160}
1161
1162/// Target scroller source container for `scroll()` functional timeline.
1163#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
1164pub enum ScrollTimelineSource {
1165    #[default]
1166    Nearest,
1167    Root,
1168    SelfNode,
1169}
1170
1171/// CSS animation timeline descriptor per W3C Scroll-Driven Animations Level 1.
1172#[derive(Debug, Clone, PartialEq, Default)]
1173pub enum AnimationTimeline {
1174    /// Traditional wall-clock time timeline.
1175    #[default]
1176    Time,
1177    /// Container scroll-driven timeline with source scroller and axis.
1178    Scroll(ScrollTimelineSource, ScrollAxis),
1179    /// Element visibility in scrollport view timeline with axis and start/end insets.
1180    View(ScrollAxis, f32, f32),
1181    /// Named timeline referencing a @scroll-timeline or scroll-timeline-name.
1182    Named(String),
1183}
1184
1185/// Named range anchor for scroll-driven animations per W3C specification.
1186#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
1187pub enum AnimationRangeName {
1188    #[default]
1189    Normal,
1190    Cover,
1191    Contain,
1192    Entry,
1193    Exit,
1194}
1195
1196/// Start and end range boundaries for scroll-driven animations.
1197#[derive(Debug, Clone, Copy, PartialEq)]
1198pub struct AnimationRange {
1199    pub name: AnimationRangeName,
1200    pub start_offset: f32,
1201    pub end_offset: f32,
1202}
1203
1204impl Default for AnimationRange {
1205    fn default() -> Self {
1206        Self {
1207            name: AnimationRangeName::Normal,
1208            start_offset: 0.0,
1209            end_offset: 1.0,
1210        }
1211    }
1212}
1213
1214/// Complete CSS animation descriptor specifying name, timing, delay, iterations, direction, fill mode, timeline, and range.
1215#[derive(Debug, Clone, PartialEq)]
1216pub struct AnimationSpec {
1217    pub name: String,
1218    pub duration_ms: f32,
1219    pub timing_function: TransitionEasing,
1220    pub delay_ms: f32,
1221    pub iteration_count: AnimationIterationCount,
1222    pub direction: AnimationDirection,
1223    pub fill_mode: AnimationFillMode,
1224    pub play_state: AnimationPlayState,
1225    pub timeline: AnimationTimeline,
1226    pub range: AnimationRange,
1227}
1228
1229impl Default for AnimationSpec {
1230    fn default() -> Self {
1231        Self {
1232            name: String::new(),
1233            duration_ms: 0.0,
1234            timing_function: TransitionEasing::Ease,
1235            delay_ms: 0.0,
1236            iteration_count: AnimationIterationCount::Count(1.0),
1237            direction: AnimationDirection::Normal,
1238            fill_mode: AnimationFillMode::None,
1239            play_state: AnimationPlayState::Running,
1240            timeline: AnimationTimeline::Time,
1241            range: AnimationRange::default(),
1242        }
1243    }
1244}
1245
1246/// An individual CSS 2D or 3D transform operation.
1247#[derive(Debug, Clone, PartialEq)]
1248pub enum TransformOp {
1249    Translate(Dimension, Dimension),
1250    Translate3d(Dimension, Dimension, Dimension),
1251    Scale(f32, f32),
1252    Scale3d(f32, f32, f32),
1253    Rotate(f32), // Radians (around Z)
1254    RotateX(f32),
1255    RotateY(f32),
1256    RotateZ(f32),
1257    Rotate3d(f32, f32, f32, f32), // x, y, z, rad
1258    Skew(f32, f32),               // Radians (ax, ay)
1259    Perspective(f32),             // Pixels
1260    Matrix([f32; 6]),
1261    Matrix3d([f32; 16]),
1262}
1263
1264impl TransformOp {
1265    /// Computes the 4x4 matrix for this individual transform operation given element size.
1266    pub fn to_matrix(&self, width: f32, height: f32) -> Matrix4x4 {
1267        match self {
1268            Self::Translate(dx, dy) => {
1269                let tx = match dx {
1270                    Dimension::Px(px) => *px,
1271                    Dimension::Percent(pct) => width * (pct / 100.0),
1272                    Dimension::Rem(rem) => rem * 16.0,
1273                    Dimension::Em(em) => em * 16.0,
1274                    _ => 0.0,
1275                };
1276                let ty = match dy {
1277                    Dimension::Px(px) => *px,
1278                    Dimension::Percent(pct) => height * (pct / 100.0),
1279                    Dimension::Rem(rem) => rem * 16.0,
1280                    Dimension::Em(em) => em * 16.0,
1281                    _ => 0.0,
1282                };
1283                Matrix4x4::translation(tx, ty, 0.0)
1284            }
1285            Self::Translate3d(dx, dy, dz) => {
1286                let tx = match dx {
1287                    Dimension::Px(px) => *px,
1288                    Dimension::Percent(pct) => width * (pct / 100.0),
1289                    Dimension::Rem(rem) => rem * 16.0,
1290                    Dimension::Em(em) => em * 16.0,
1291                    _ => 0.0,
1292                };
1293                let ty = match dy {
1294                    Dimension::Px(px) => *px,
1295                    Dimension::Percent(pct) => height * (pct / 100.0),
1296                    Dimension::Rem(rem) => rem * 16.0,
1297                    Dimension::Em(em) => em * 16.0,
1298                    _ => 0.0,
1299                };
1300                let tz = match dz {
1301                    Dimension::Px(px) => *px,
1302                    Dimension::Rem(rem) => rem * 16.0,
1303                    Dimension::Em(em) => em * 16.0,
1304                    _ => 0.0,
1305                };
1306                Matrix4x4::translation(tx, ty, tz)
1307            }
1308            Self::Scale(sx, sy) => Matrix4x4::scaling(*sx, *sy, 1.0),
1309            Self::Scale3d(sx, sy, sz) => Matrix4x4::scaling(*sx, *sy, *sz),
1310            Self::Rotate(rad) | Self::RotateZ(rad) => Matrix4x4::rotation_z(*rad),
1311            Self::RotateX(rad) => Matrix4x4::rotation_x(*rad),
1312            Self::RotateY(rad) => Matrix4x4::rotation_y(*rad),
1313            Self::Rotate3d(x, y, z, rad) => Matrix4x4::rotation_axis(*x, *y, *z, *rad),
1314            Self::Skew(ax, ay) => Matrix4x4::skew(*ax, *ay),
1315            Self::Perspective(d) => Matrix4x4::perspective(*d),
1316            Self::Matrix(m) => Matrix4x4::from_2d(m[0], m[1], m[2], m[3], m[4], m[5]),
1317            Self::Matrix3d(m) => Matrix4x4::from_array(*m),
1318        }
1319    }
1320
1321    /// Returns the identity equivalent for this operation type per CSS Transitions.
1322    pub fn to_identity(&self) -> Self {
1323        match self {
1324            Self::Translate(..) => Self::Translate(Dimension::Px(0.0), Dimension::Px(0.0)),
1325            Self::Translate3d(..) => {
1326                Self::Translate3d(Dimension::Px(0.0), Dimension::Px(0.0), Dimension::Px(0.0))
1327            }
1328            Self::Scale(..) => Self::Scale(1.0, 1.0),
1329            Self::Scale3d(..) => Self::Scale3d(1.0, 1.0, 1.0),
1330            Self::Rotate(..) => Self::Rotate(0.0),
1331            Self::RotateX(..) => Self::RotateX(0.0),
1332            Self::RotateY(..) => Self::RotateY(0.0),
1333            Self::RotateZ(..) => Self::RotateZ(0.0),
1334            Self::Rotate3d(x, y, z, _) => Self::Rotate3d(*x, *y, *z, 0.0),
1335            Self::Skew(..) => Self::Skew(0.0, 0.0),
1336            Self::Perspective(d) => Self::Perspective(*d),
1337            Self::Matrix(..) => Self::Matrix([1.0, 0.0, 0.0, 1.0, 0.0, 0.0]),
1338            Self::Matrix3d(..) => Self::Matrix3d([
1339                1.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 0.0, 1.0,
1340            ]),
1341        }
1342    }
1343}
1344
1345/// The origin point around which transforms are applied.
1346#[derive(Debug, Clone, Copy, PartialEq)]
1347pub struct TransformOrigin {
1348    pub x: Dimension,
1349    pub y: Dimension,
1350    pub z: f32,
1351}
1352
1353impl Default for TransformOrigin {
1354    fn default() -> Self {
1355        Self {
1356            x: Dimension::Percent(50.0),
1357            y: Dimension::Percent(50.0),
1358            z: 0.0,
1359        }
1360    }
1361}
1362
1363/// CSS transform-style property defining 3D rendering context hierarchy.
1364#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
1365pub enum TransformStyle {
1366    #[default]
1367    Flat,
1368    Preserve3d,
1369}
1370
1371/// CSS backface-visibility property determining if reverse side of 3D element is rendered.
1372#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
1373pub enum BackfaceVisibility {
1374    #[default]
1375    Visible,
1376    Hidden,
1377}
1378
1379/// Computes the composite 4x4 matrix for a list of transform operations relative to `origin`.
1380pub fn compute_transform_matrix(
1381    ops: &[TransformOp],
1382    width: f32,
1383    height: f32,
1384    origin: &TransformOrigin,
1385) -> Matrix4x4 {
1386    if ops.is_empty() {
1387        return Matrix4x4::identity();
1388    }
1389
1390    let ox = match origin.x {
1391        Dimension::Px(px) => px,
1392        Dimension::Percent(pct) => width * (pct / 100.0),
1393        Dimension::Rem(rem) => rem * 16.0,
1394        Dimension::Em(em) => em * 16.0,
1395        _ => width * 0.5,
1396    };
1397    let oy = match origin.y {
1398        Dimension::Px(px) => px,
1399        Dimension::Percent(pct) => height * (pct / 100.0),
1400        Dimension::Rem(rem) => rem * 16.0,
1401        Dimension::Em(em) => em * 16.0,
1402        _ => height * 0.5,
1403    };
1404    let oz = origin.z;
1405
1406    let t_origin = Matrix4x4::translation(ox, oy, oz);
1407    let t_origin_inv = Matrix4x4::translation(-ox, -oy, -oz);
1408
1409    let mut combined_ops = Matrix4x4::identity();
1410    for op in ops {
1411        combined_ops = combined_ops.multiply(&op.to_matrix(width, height));
1412    }
1413
1414    t_origin.multiply(&combined_ops).multiply(&t_origin_inv)
1415}
1416
1417/// Fully computed and resolved styles for an element node.
1418#[derive(Debug, Clone, PartialEq)]
1419pub struct ComputedStyle {
1420    // Layout Display & Box Model
1421    pub display: Display,
1422    pub position: Position,
1423    pub float: Float,
1424    pub clear: Clear,
1425    pub box_sizing: BoxSizing,
1426    pub content_visibility: ContentVisibility,
1427    pub contain: Containment,
1428    pub contain_intrinsic_width: Option<Dimension>,
1429    pub contain_intrinsic_height: Option<Dimension>,
1430    pub width: Dimension,
1431    pub height: Dimension,
1432    pub min_width: Dimension,
1433    pub max_width: Dimension,
1434    pub min_height: Dimension,
1435    pub max_height: Dimension,
1436    pub margin: EdgeInsets<f32>,
1437    pub margin_auto_top: bool,
1438    pub margin_auto_right: bool,
1439    pub margin_auto_bottom: bool,
1440    pub margin_auto_left: bool,
1441    pub padding: EdgeInsets<f32>,
1442    pub insets: EdgeInsets<Dimension>, // top, right, bottom, left
1443    pub z_index: Option<i32>,
1444
1445    // Flexbox
1446    pub flex_direction: FlexDirection,
1447    pub flex_wrap: FlexWrap,
1448    pub justify_content: JustifyContent,
1449    pub align_items: AlignItems,
1450    pub align_self: AlignSelf,
1451    pub flex_grow: f32,
1452    pub flex_shrink: f32,
1453    pub flex_basis: Dimension,
1454    pub gap: f32,
1455    pub gap_row: f32,
1456    pub gap_col: f32,
1457
1458    // CSS Grid
1459    pub grid_template_columns: Vec<GridTrack>,
1460    pub grid_template_rows: Vec<GridTrack>,
1461    pub grid_template_areas: Vec<Vec<String>>,
1462    pub grid_auto_flow: GridAutoFlow,
1463    pub grid_area: Option<String>,
1464    pub grid_column_start: Option<i32>,
1465    pub grid_column_end: Option<i32>,
1466    pub grid_column_span: Option<u32>,
1467    pub grid_row_start: Option<i32>,
1468    pub grid_row_end: Option<i32>,
1469    pub grid_row_span: Option<u32>,
1470
1471    // CSS Table
1472    pub table_layout: TableLayout,
1473    pub border_collapse: BorderCollapse,
1474    pub border_spacing: (f32, f32),
1475    pub caption_side: CaptionSide,
1476    pub colspan: u32,
1477    pub rowspan: u32,
1478
1479    // Visuals & Backgrounds
1480    pub background_color: Option<Color>,
1481    pub background_gradient: Option<Gradient>,
1482    pub border_color: Option<Color>,
1483    pub border_width: EdgeInsets<f32>,
1484    pub border_radius: BorderRadius,
1485    pub opacity: f32,
1486    pub box_shadow: Vec<BoxShadow>,
1487    pub overflow_x: Overflow,
1488    pub overflow_y: Overflow,
1489
1490    // Typography (Inheritable)
1491    pub color: Color,
1492    pub font_family: AtomId,
1493    pub font_size: f32,
1494    pub root_font_size: f32,
1495    pub font_weight: FontWeight,
1496    pub font_style: FontStyle,
1497    pub text_align: TextAlign,
1498    pub line_height: f32,
1499    pub letter_spacing: f32,
1500    pub text_decoration: TextDecoration,
1501    pub text_transform: TextTransform,
1502    pub text_overflow: TextOverflow,
1503    pub white_space: WhiteSpace,
1504    pub vertical_align: VerticalAlign,
1505
1506    // Interaction & Behavior (Inheritable)
1507    pub cursor: Cursor,
1508    pub user_select: UserSelect,
1509    pub pointer_events: PointerEvents,
1510    pub visibility: Visibility,
1511    pub caret_color: Option<Color>,
1512
1513    // Border & Outline Styles
1514    pub border_style: BorderStyle,
1515    pub outline_width: f32,
1516    pub outline_style: BorderStyle,
1517    pub outline_color: Option<Color>,
1518    pub outline_offset: f32,
1519
1520    // Aspect Ratio & Layout
1521    pub aspect_ratio: Option<f32>,
1522
1523    // Visual Effects
1524    pub backdrop_filter: Option<crate::effects::BackdropFilter>,
1525    pub filter: Option<crate::effects::BackdropFilter>,
1526    pub clip_path: Option<crate::effects::ClipPath>,
1527    pub mix_blend_mode: BlendMode,
1528    pub isolation: Isolation,
1529
1530    // Transitions (W3C CSS Transitions Level 1 & 2)
1531    pub transitions: Vec<TransitionSpec>,
1532
1533    // Animations (W3C CSS Animations Level 1 & 2)
1534    pub animations: Vec<AnimationSpec>,
1535
1536    // CSS 2D & 3D Transforms (Level 1 & Level 2)
1537    pub transform: Vec<TransformOp>,
1538    pub transform_origin: TransformOrigin,
1539    pub transform_style: TransformStyle,
1540    pub perspective: Option<f32>,
1541    pub perspective_origin: (Dimension, Dimension),
1542    pub backface_visibility: BackfaceVisibility,
1543
1544    // CSS Custom Properties (Inheritable - Copy-On-Write Arc)
1545    pub custom_properties: Option<CustomPropertyMap>,
1546
1547    // Next-Gen CSS Standards (Milestone 48)
1548    pub starting_style: Option<Box<ComputedStyle>>,
1549    pub view_transition_name: Option<String>,
1550    pub animation_timeline: AnimationTimeline,
1551    pub animation_range: AnimationRange,
1552}
1553
1554impl Default for ComputedStyle {
1555    fn default() -> Self {
1556        Self {
1557            display: Display::Block,
1558            position: Position::Static,
1559            float: Float::None,
1560            clear: Clear::None,
1561            box_sizing: BoxSizing::BorderBox,
1562            content_visibility: ContentVisibility::Visible,
1563            contain: Containment::NONE,
1564            contain_intrinsic_width: None,
1565            contain_intrinsic_height: None,
1566            width: Dimension::Auto,
1567            height: Dimension::Auto,
1568            min_width: Dimension::Auto,
1569            max_width: Dimension::Auto,
1570            min_height: Dimension::Auto,
1571            max_height: Dimension::Auto,
1572            margin: EdgeInsets::ZERO,
1573            margin_auto_top: false,
1574            margin_auto_right: false,
1575            margin_auto_bottom: false,
1576            margin_auto_left: false,
1577            padding: EdgeInsets::ZERO,
1578            insets: EdgeInsets::new(
1579                Dimension::Auto,
1580                Dimension::Auto,
1581                Dimension::Auto,
1582                Dimension::Auto,
1583            ),
1584            z_index: None,
1585
1586            flex_direction: FlexDirection::Row,
1587            flex_wrap: FlexWrap::NoWrap,
1588            justify_content: JustifyContent::FlexStart,
1589            align_items: AlignItems::Stretch,
1590            align_self: AlignSelf::Auto,
1591            flex_grow: 0.0,
1592            flex_shrink: 1.0,
1593            flex_basis: Dimension::Auto,
1594            gap: 0.0,
1595            gap_row: 0.0,
1596            gap_col: 0.0,
1597
1598            grid_template_columns: Vec::new(),
1599            grid_template_rows: Vec::new(),
1600            grid_template_areas: Vec::new(),
1601            grid_auto_flow: GridAutoFlow::Row,
1602            grid_area: None,
1603            grid_column_start: None,
1604            grid_column_end: None,
1605            grid_column_span: None,
1606            grid_row_start: None,
1607            grid_row_end: None,
1608            grid_row_span: None,
1609
1610            table_layout: TableLayout::Auto,
1611            border_collapse: BorderCollapse::Separate,
1612            border_spacing: (0.0, 0.0),
1613            caption_side: CaptionSide::Top,
1614            colspan: 1,
1615            rowspan: 1,
1616
1617            background_color: None,
1618            background_gradient: None,
1619            border_color: None,
1620            border_width: EdgeInsets::ZERO,
1621            border_radius: BorderRadius::ZERO,
1622            opacity: 1.0,
1623            box_shadow: Vec::new(),
1624            overflow_x: Overflow::Visible,
1625            overflow_y: Overflow::Visible,
1626
1627            color: Color::BLACK,
1628            font_family: AtomId::FONT_SANS,
1629            font_size: 16.0,
1630            root_font_size: 16.0,
1631            font_weight: FontWeight::Normal,
1632            font_style: FontStyle::Normal,
1633            text_align: TextAlign::Left,
1634            line_height: 1.2,
1635            letter_spacing: 0.0,
1636            text_decoration: TextDecoration::None,
1637            text_transform: TextTransform::None,
1638            text_overflow: TextOverflow::Clip,
1639            white_space: WhiteSpace::Normal,
1640            vertical_align: VerticalAlign::Baseline,
1641
1642            cursor: Cursor::Default,
1643            user_select: UserSelect::Auto,
1644            pointer_events: PointerEvents::Auto,
1645            visibility: Visibility::Visible,
1646            caret_color: None,
1647
1648            border_style: BorderStyle::Solid,
1649            outline_width: 0.0,
1650            outline_style: BorderStyle::None,
1651            outline_color: None,
1652            outline_offset: 0.0,
1653
1654            aspect_ratio: None,
1655
1656            backdrop_filter: None,
1657            filter: None,
1658            clip_path: None,
1659            mix_blend_mode: BlendMode::Normal,
1660            isolation: Isolation::Auto,
1661            transitions: Vec::new(),
1662            animations: Vec::new(),
1663
1664            transform: Vec::new(),
1665            transform_origin: TransformOrigin::default(),
1666            transform_style: TransformStyle::default(),
1667            perspective: None,
1668            perspective_origin: (Dimension::Percent(50.0), Dimension::Percent(50.0)),
1669            backface_visibility: BackfaceVisibility::default(),
1670
1671            custom_properties: None,
1672
1673            starting_style: None,
1674            view_transition_name: None,
1675            animation_timeline: AnimationTimeline::Time,
1676            animation_range: AnimationRange::default(),
1677        }
1678    }
1679}
1680
1681impl ComputedStyle {
1682    /// Returns true if this style defines any animations.
1683    #[inline(always)]
1684    pub fn has_animations(&self) -> bool {
1685        !self.animations.is_empty()
1686    }
1687
1688    /// Returns true if this style defines any 2D or 3D transform operations.
1689    #[inline(always)]
1690    pub fn has_transform(&self) -> bool {
1691        !self.transform.is_empty()
1692    }
1693
1694    /// Returns true if this style defines any visual filters, backdrop filters, clip-paths, or blend modes.
1695    #[inline(always)]
1696    pub fn has_visual_effects(&self) -> bool {
1697        self.mix_blend_mode != BlendMode::Normal
1698            || self.isolation == Isolation::Isolate
1699            || self.filter.as_ref().is_some_and(|f| !f.is_empty())
1700            || self.backdrop_filter.as_ref().is_some_and(|b| !b.is_empty())
1701            || self.clip_path.as_ref().is_some_and(|c| !c.is_none())
1702    }
1703
1704    /// Computes the composite 4x4 matrix for this element's transform given layout width and height.
1705    #[inline(always)]
1706    pub fn compute_transform_matrix(&self, width: f32, height: f32) -> Matrix4x4 {
1707        compute_transform_matrix(&self.transform, width, height, &self.transform_origin)
1708    }
1709
1710    /// Evaluates if this element establishes a containing block for `position: fixed`
1711    /// (and `position: absolute`) descendants per CSS Transforms Level 1 §2 and Filter Effects Level 1 §5.
1712    #[inline(always)]
1713    pub fn establishes_fixed_containing_block(&self) -> bool {
1714        self.has_transform()
1715            || self.filter.as_ref().is_some_and(|f| !f.is_empty())
1716            || self.backdrop_filter.as_ref().is_some_and(|b| !b.is_empty())
1717    }
1718
1719    /// Evaluates if this element establishes an isolated stacking context per
1720    /// W3C CSS 2.1 Appendix E, CSS Flexbox §4.3, CSS Grid §5.4, CSS Positioned Layout Level 3 §3.1,
1721    /// and CSS Compositing Level 1.
1722    ///
1723    /// Note: Per CSS 2.1 Appendix E / CSS Overflow Level 3, `overflow != Visible` clips scrollable
1724    /// content without establishing an atomic stacking context.
1725    #[inline]
1726    pub fn establishes_stacking_context_in(
1727        &self,
1728        parent_display: Option<Display>,
1729        is_root: bool,
1730    ) -> bool {
1731        if is_root {
1732            return true;
1733        }
1734        let is_positioned = self.position != Position::Static;
1735        let is_flex_or_grid_item = matches!(
1736            parent_display,
1737            Some(Display::Flex | Display::InlineFlex | Display::Grid | Display::InlineGrid)
1738        );
1739        let z_index_triggers = self.z_index.is_some() && (is_positioned || is_flex_or_grid_item);
1740        let fixed_or_sticky = matches!(self.position, Position::Fixed | Position::Sticky);
1741
1742        z_index_triggers
1743            || fixed_or_sticky
1744            || self.opacity < 0.999
1745            || self.has_transform()
1746            || self.has_visual_effects()
1747    }
1748
1749    /// Evaluates if this element establishes an isolated stacking context without parent display context.
1750    #[inline]
1751    pub fn establishes_stacking_context(&self) -> bool {
1752        self.establishes_stacking_context_in(None, false)
1753    }
1754    /// Constructs an unstyled node inheriting inheritable properties from parent with zero heap allocations.
1755    pub fn inherit_from(parent: &Self) -> Self {
1756        // Inheritable properties per W3C CSS Cascading and Inheritance Level 4:
1757        Self {
1758            color: parent.color,
1759            font_family: parent.font_family,
1760            font_size: parent.font_size,
1761            root_font_size: parent.root_font_size,
1762            font_weight: parent.font_weight,
1763            font_style: parent.font_style,
1764            text_align: parent.text_align,
1765            line_height: parent.line_height,
1766            letter_spacing: parent.letter_spacing,
1767            text_decoration: parent.text_decoration,
1768            text_transform: parent.text_transform,
1769            text_overflow: parent.text_overflow,
1770            white_space: parent.white_space,
1771            cursor: parent.cursor,
1772            user_select: parent.user_select,
1773            pointer_events: parent.pointer_events,
1774            visibility: parent.visibility,
1775            caret_color: parent.caret_color,
1776            border_collapse: parent.border_collapse,
1777            border_spacing: parent.border_spacing,
1778            caption_side: parent.caption_side,
1779            custom_properties: parent.custom_properties.clone(),
1780            ..Self::default()
1781        }
1782    }
1783
1784    /// Looks up a CSS custom property by AtomId.
1785    pub fn get_custom_property(&self, key: AtomId) -> Option<AtomId> {
1786        let map = self.custom_properties.as_ref()?;
1787        for (k, v) in map.iter().rev() {
1788            if *k == key {
1789                return Some(*v);
1790            }
1791        }
1792        None
1793    }
1794
1795    /// Sets or overrides a CSS custom property using Copy-On-Write semantics.
1796    pub fn set_custom_property(&mut self, key: AtomId, value: AtomId) {
1797        let mut list = match &self.custom_properties {
1798            Some(arc) => (**arc).clone(),
1799            None => Vec::with_capacity(4),
1800        };
1801        if let Some(pos) = list.iter().position(|(k, _)| *k == key) {
1802            list[pos].1 = value;
1803        } else {
1804            list.push((key, value));
1805        }
1806        self.custom_properties = Some(Arc::new(list));
1807    }
1808}