Skip to main content

sk_css/
lib.rs

1//! sk-css: lightningcss parses stylesheets, parcel_selectors matches them against the retained
2//! tree, and the cascade folds matched rules into per-state `gpui::StyleRefinement`s that the
3//! renderer installs into gpui's state ladder (base / focus / focus-visible / hover / active).
4//! - The cascade runs once per tree mutation, never inside gpui's per-frame style computation;
5//!   interaction states never round-trip through JS.
6//! - `:disabled` / `:checked` are not ladder states: the element property is the state, so they
7//!   fold into the base bucket.
8//! - Selectors the matcher cannot run (`:has()`, unflattened nesting, `:nth-child(.. of S)`) panic
9//!   inside parcel_selectors, so they are probed and rejected at compile time with a diagnostic.
10//!   Selectors it can run but could only answer "no" for (`:visited`, ...) are reported by
11//!   [`audit_selector`], never compiled into a rule that silently never matches.
12
13mod animator;
14mod calc_size;
15pub mod catalog;
16pub mod container;
17#[cfg(test)]
18mod container_tests;
19mod corner_shape;
20mod dynamic_range;
21mod element;
22#[cfg(test)]
23mod em_tests;
24mod functions;
25mod has;
26mod keyframes;
27mod mapper;
28mod media;
29mod path_data;
30pub mod perf;
31mod prefix;
32mod registered;
33mod rgb_space;
34mod share;
35pub mod snap;
36mod transition;
37mod vars;
38pub mod view_transition;
39
40use std::rc::Rc;
41
42use gpui::{Refineable, StyleRefinement};
43use lightningcss::declaration::DeclarationBlock;
44use lightningcss::rules::CssRule;
45use lightningcss::selector::{PseudoClass, Selector};
46use lightningcss::stylesheet::{ParserOptions, StyleSheet};
47use parcel_selectors::context::{MatchingContext, MatchingMode, QuirksMode};
48use parcel_selectors::matching::matches_selector;
49use parcel_selectors::parser::Component;
50
51pub use animator::{
52    script_keyframes, strip_transitioned, AnimEvent, AnimEventKind, Animator, ScriptClock,
53    ScriptFrame, ScriptKeyframeNotes, ScriptSample, ScriptTiming,
54};
55pub use corner_shape::to_css as corner_shape_css;
56pub use dynamic_range::{DynamicRangeLimit, CONSTRAINED_HEADROOM};
57pub use element::{Interaction, MatchDom};
58#[doc(hidden)]
59pub use keyframes::AnimationDeclarations;
60pub use keyframes::{
61    AnimationPatch, AnimationSpec, Direction as AnimationDirection, FillMode, Keyframe, Keyframes,
62    PlayState,
63};
64pub use mapper::COLOR_SCHEME;
65pub use mapper::{
66    accepts_declaration, parse_inline, parse_inline_full, parse_inline_style,
67    parse_inline_with_transitions, rem_basis, set_font_metric_source, set_font_source,
68    set_rem_basis, set_viewport_basis, set_web_font_families, take_font_misses,
69    uses_viewport_units, viewport_basis, BackgroundLayer, BackgroundSize, BackgroundUrl,
70    CurrentColorTargets, Decls, Extras, FontRelativeMetrics, InlineMotion, InlinePriority,
71    InlineStyle, ListMarker, MaskClips, MaskCompositing, MaskImages, MaskPatch, MaskStack,
72    ObjectFit, OverscrollBehavior, PaintLayer, RadiusInherit, ScrollbarWidth, SvgPaint, TextFill,
73    TextTransform, TileLength, UserSelect, WhiteSpaceMode, WindowControl, WindowDrag,
74    INITIAL_REM_BASIS, INITIAL_VIEWPORT_BASIS,
75};
76pub use mapper::{
77    parse_color, parse_color_in, set_composed_font_families, take_unreached_fonts, text_shadow_css,
78    transform_css,
79};
80pub use media::{match_media, DisplayMode, Env};
81#[doc(hidden)]
82pub use registered::CustomAnimationContext;
83pub use rgb_space::{convert_rgb, from_linear, to_linear, RgbSpace};
84pub use transition::{
85    covered, parse_easing, spec_for, Delay, Easing, StepPosition, TransitionProperty,
86    TransitionSpec, ANIMATABLE_COUNT,
87};
88pub use vars::Vars;
89
90/// These are exactly the states gpui's own interactivity ladder can pick live, in gpui's
91/// application order (later wins — see `Interactivity::compute_style_internal`).
92const STATE_FOCUS: u8 = 1;
93const STATE_FOCUS_VISIBLE: u8 = 2;
94const STATE_HOVER: u8 = 4;
95const STATE_ACTIVE: u8 = 8;
96const STATE_FOCUS_WITHIN: u8 = 16;
97
98const STATE_RUNGS: usize = 5;
99
100/// Mirrors the bucket selection in `compute_node` (a compound naming several states lands on the
101/// strongest): a rung's custom properties must be the ones its declarations read.
102fn rung_of(states: u8) -> Option<usize> {
103    match states {
104        0 => None,
105        s if s & STATE_ACTIVE != 0 => Some(0),
106        s if s & STATE_HOVER != 0 => Some(1),
107        s if s & STATE_FOCUS_VISIBLE != 0 => Some(2),
108        s if s & STATE_FOCUS != 0 => Some(3),
109        _ => Some(4),
110    }
111}
112
113#[derive(Clone, Debug, Default, PartialEq)]
114pub struct ComputedStates {
115    pub base: Rc<StyleRefinement>,
116    pub hover: Option<Rc<StyleRefinement>>,
117    pub active: Option<Rc<StyleRefinement>>,
118    /// `:focus` — gpui's `.focus()` rung. A node that has one MUST be given a tracked focus handle
119    /// by the renderer, or gpui has nothing to key it on.
120    pub focus: Option<Rc<StyleRefinement>>,
121    pub focus_visible: Option<Rc<StyleRefinement>>,
122    pub focus_within: Option<Rc<StyleRefinement>>,
123    pub group_hover: Option<(u64, Rc<StyleRefinement>)>,
124    pub group_active: Option<(u64, Rc<StyleRefinement>)>,
125    /// `:focus`, `:focus-visible` and `:focus-within` on an ancestor compound, folded at render.
126    pub group_focus: Option<Rc<GroupFocus>>,
127    pub transitions: Rc<Vec<TransitionSpec>>,
128    pub animations: Rc<Vec<AnimationSpec>>,
129    pub extras: Extras,
130    pub before: Option<Rc<PseudoBox>>,
131    pub after: Option<Rc<PseudoBox>>,
132    pub placeholder: Option<Rc<StyleRefinement>>,
133    /// Only `background-color` reaches the widget: gpui's selection is a quad behind the glyphs.
134    pub selection: Option<Rc<StyleRefinement>>,
135    pub file_selector_button: Option<Rc<StyleRefinement>>,
136    pub range_track: Option<Rc<ControlPseudo>>,
137    pub range_thumb: Option<Rc<ControlPseudo>>,
138    pub color_swatch: Option<Rc<ControlPseudo>>,
139    pub color_swatch_wrapper: Option<Rc<ControlPseudo>>,
140    /// Children read this one, so the restyle pass must walk in document order.
141    pub vars: Rc<Vars>,
142    #[doc(hidden)]
143    pub custom_animation: Option<Rc<CustomAnimationContext>>,
144    /// The effective `color` (own or threaded from the parent), kept only because `currentColor` is
145    /// a computed value that needs it; no other inherited text property is folded here.
146    pub color: Option<gpui::Hsla>,
147    pub font_size: f32,
148    pub computed_font: gpui::Font,
149}
150
151#[derive(Clone, Debug, PartialEq)]
152pub struct GroupFocus {
153    pub focus: Option<(u64, Rc<StyleRefinement>)>,
154    pub focus_visible: Option<(u64, Rc<StyleRefinement>)>,
155    pub focus_within: Option<(u64, Rc<StyleRefinement>)>,
156}
157
158impl GroupFocus {
159    fn of(
160        focus: Option<(u64, StyleRefinement)>,
161        focus_visible: Option<(u64, StyleRefinement)>,
162        focus_within: Option<(u64, StyleRefinement)>,
163    ) -> Option<Rc<Self>> {
164        let wrap = |b: Option<(u64, StyleRefinement)>| b.map(|(key, r)| (key, Rc::new(r)));
165        (focus.is_some() || focus_visible.is_some() || focus_within.is_some()).then(|| {
166            Rc::new(GroupFocus {
167                focus: wrap(focus),
168                focus_visible: wrap(focus_visible),
169                focus_within: wrap(focus_within),
170            })
171        })
172    }
173
174    pub fn anchors(&self) -> impl Iterator<Item = u64> + '_ {
175        [&self.focus, &self.focus_visible, &self.focus_within]
176            .into_iter()
177            .flatten()
178            .map(|(key, _)| *key)
179    }
180
181    /// Folds the buckets whose anchor is in the state, weakest first as on the element's own ladder.
182    pub fn fold(&self, into: &mut StyleRefinement, holds: impl Fn(u64, Interaction) -> bool) {
183        use gpui::Refineable as _;
184        for (bucket, state) in [
185            (&self.focus_within, Interaction::FocusWithin),
186            (&self.focus, Interaction::Focus),
187            (&self.focus_visible, Interaction::FocusVisible),
188        ] {
189            if let Some((key, style)) = bucket {
190                if holds(*key, state) {
191                    into.refine(style);
192                }
193            }
194        }
195    }
196}
197
198#[derive(Clone, Copy, Debug, PartialEq, Eq)]
199pub enum PseudoElement {
200    Before,
201    After,
202    /// Not a generated box: it styles the placeholder STRING the native text-input widget paints,
203    /// so it folds into its own refinement and the renderer reads `text.color` off it.
204    Placeholder,
205    Selection,
206    FileSelectorButton,
207    RangeTrack,
208    RangeThumb,
209    ColorSwatch,
210    ColorSwatchWrapper,
211}
212
213impl PseudoElement {
214    fn control_index(self) -> Option<usize> {
215        match self {
216            Self::RangeTrack => Some(0),
217            Self::RangeThumb => Some(1),
218            Self::ColorSwatch => Some(2),
219            Self::ColorSwatchWrapper => Some(3),
220            _ => None,
221        }
222    }
223}
224
225#[derive(Clone, Debug, PartialEq)]
226pub struct ControlPseudo {
227    pub base: Rc<StyleRefinement>,
228    pub extras: Extras,
229    pub states: [Option<(Rc<StyleRefinement>, Extras)>; STATE_RUNGS],
230}
231
232impl ControlPseudo {
233    pub fn resolve(
234        &self,
235        active: bool,
236        hover: bool,
237        focus_visible: bool,
238        focus: bool,
239        focus_within: bool,
240    ) -> (&StyleRefinement, &Extras) {
241        for (index, on) in [active, hover, focus_visible, focus, focus_within]
242            .into_iter()
243            .enumerate()
244        {
245            if on {
246                if let Some((style, extras)) = &self.states[index] {
247                    return (style, extras);
248                }
249            }
250        }
251        (&self.base, &self.extras)
252    }
253}
254
255struct ControlFold {
256    slots: Vec<(StyleRefinement, Extras)>,
257    states: [bool; STATE_RUNGS],
258}
259
260impl Default for ControlFold {
261    fn default() -> Self {
262        Self {
263            slots: (0..=STATE_RUNGS).map(|_| Default::default()).collect(),
264            states: [false; STATE_RUNGS],
265        }
266    }
267}
268
269impl ControlFold {
270    fn finish(self) -> Rc<ControlPseudo> {
271        let mut slots = self.slots.into_iter();
272        let (base, extras) = slots.next().expect("base control style");
273        let states = std::array::from_fn(|index| {
274            let (style, extras) = slots.next().expect("control state");
275            self.states[index].then(|| (Rc::new(style), extras))
276        });
277        Rc::new(ControlPseudo {
278            base: Rc::new(base),
279            extras,
280            states,
281        })
282    }
283}
284
285#[derive(Clone, Debug, PartialEq)]
286pub struct PseudoBox {
287    pub content: Rc<str>,
288    pub style: Rc<StyleRefinement>,
289    pub extras: Extras,
290}
291
292#[derive(Clone, Copy, Debug, Default, PartialEq)]
293pub struct InheritedRadii {
294    lengths: [Option<gpui::AbsoluteLength>; 4],
295    relative: [Option<Option<gpui::VnCornerRadius>>; 4],
296    shapes: [Option<gpui::CornerShape>; 4],
297}
298
299impl InheritedRadii {
300    pub fn of(style: &StyleRefinement) -> Self {
301        let (c, v, s) = (
302            &style.corner_radii,
303            &style.vn_corner_radii,
304            &style.vn_corner_shapes,
305        );
306        Self {
307            lengths: [c.top_left, c.top_right, c.bottom_right, c.bottom_left],
308            relative: [v.top_left, v.top_right, v.bottom_right, v.bottom_left],
309            shapes: [s.top_left, s.top_right, s.bottom_right, s.bottom_left],
310        }
311    }
312
313    fn fill(&self, style: &mut StyleRefinement, corners: u8) {
314        let (c, v, s) = (
315            &mut style.corner_radii,
316            &mut style.vn_corner_radii,
317            &mut style.vn_corner_shapes,
318        );
319        let slots = [
320            (&mut c.top_left, &mut v.top_left, &mut s.top_left),
321            (&mut c.top_right, &mut v.top_right, &mut s.top_right),
322            (
323                &mut c.bottom_right,
324                &mut v.bottom_right,
325                &mut s.bottom_right,
326            ),
327            (&mut c.bottom_left, &mut v.bottom_left, &mut s.bottom_left),
328        ];
329        for (i, (length, relative, shape)) in slots.into_iter().enumerate() {
330            if corners & (1 << i) != 0 {
331                *length = Some(self.lengths[i].unwrap_or(gpui::px(0.).into()));
332                *relative = Some(self.relative[i].flatten());
333            }
334            if corners & corner_shape::inherit_bit(i) != 0 {
335                *shape = Some(self.shapes[i].unwrap_or_default());
336            }
337        }
338    }
339}
340
341/// `radius_inherit` is shared by every rung but filled into the base style only, so `.x:hover {
342/// border-radius: 8px }` must not cancel `.x { border-radius: inherit }` outside the hover.
343fn keep_base_radius_inherit(
344    extras: &mut Extras,
345    before: RadiusInherit,
346    diagnostics: &mut Vec<String>,
347) {
348    if extras.radius_inherit.inherit & !before.inherit != 0 {
349        mapper::once(
350            diagnostics,
351            "`border-radius: inherit` in a :hover/:focus/:active (or group-) rule is not \
352             applied (v1): the parent's radius is inherited into the element's base style \
353             only. Declare the inherit without the state"
354                .to_string(),
355        );
356    }
357    extras.radius_inherit = before;
358}
359
360type SvgBase = (
361    Option<SvgPaint>,
362    Option<SvgPaint>,
363    Option<Rc<Vec<(&'static str, Rc<str>)>>>,
364);
365
366fn svg_base(extras: &Extras) -> SvgBase {
367    (extras.fill, extras.stroke, extras.svg_presentation.clone())
368}
369
370/// `Extras` have no state ladder, so a state rule's SVG paint would be drawn all the time
371/// (`.btn:hover svg { fill: red }` a red icon at rest).
372fn keep_base_svg_paint(extras: &mut Extras, before: SvgBase, diagnostics: &mut Vec<String>) {
373    let (fill, stroke, presentation) = before;
374    if extras.fill != fill || extras.stroke != stroke || extras.svg_presentation != presentation {
375        mapper::once(
376            diagnostics,
377            "`fill`, `stroke` and the other SVG presentation properties in a \
378             :hover/:focus/:active (or group-) rule are not applied (v1): they are drawn into \
379             the <svg>'s rasterised document from the base state only. Toggle a class instead"
380                .to_string(),
381        );
382    }
383    extras.fill = fill;
384    extras.stroke = stroke;
385    extras.svg_presentation = presentation;
386}
387
388pub fn resolve_inherited_radii(
389    states: &mut ComputedStates,
390    parent: InheritedRadii,
391) -> InheritedRadii {
392    let corners = states.extras.radius_inherit.inherit;
393    if corners != 0 {
394        parent.fill(Rc::make_mut(&mut states.base), corners);
395    }
396    let own = InheritedRadii::of(&states.base);
397    for slot in [&mut states.before, &mut states.after]
398        .into_iter()
399        .flatten()
400    {
401        let corners = slot.extras.radius_inherit.inherit;
402        if corners != 0 {
403            own.fill(Rc::make_mut(&mut Rc::make_mut(slot).style), corners);
404        }
405    }
406    own
407}
408
409impl ComputedStates {
410    /// True when the renderer has to give this node a focus handle for gpui to have anything to
411    /// hang the focus rungs on.
412    pub fn needs_focus_handle(&self) -> bool {
413        self.focus.is_some()
414            || self.focus_visible.is_some()
415            || self.focus_within.is_some()
416            || (2..STATE_RUNGS).any(|rung| self.control_state(rung))
417    }
418
419    pub fn control_state(&self, rung: usize) -> bool {
420        [
421            &self.range_track,
422            &self.range_thumb,
423            &self.color_swatch,
424            &self.color_swatch_wrapper,
425        ]
426        .into_iter()
427        .flatten()
428        .any(|part| part.states[rung].is_some())
429    }
430
431    pub fn hover_transitions(&self) -> bool {
432        !self.transitions.is_empty() && (self.hover.is_some() || self.group_hover.is_some())
433    }
434
435    /// The refinement with the pointer over the element and/or its `.group` ancestor. It must fold
436    /// in gpui's order (group-hover, then hover) so both paths end on the same value.
437    pub fn hovered(&self, own: bool, group: bool) -> Option<StyleRefinement> {
438        use gpui::Refineable as _;
439        if !own && !group {
440            return None;
441        }
442        let mut out = (*self.base).clone();
443        if group {
444            if let Some((_, style)) = &self.group_hover {
445                out.refine(style);
446            }
447        }
448        if own {
449            if let Some(style) = &self.hover {
450                out.refine(style);
451            }
452        }
453        Some(out)
454    }
455}
456
457struct RuleEntry {
458    selector: Selector<'static>,
459    control_origin: Option<Box<Selector<'static>>>,
460    normal: Option<Rc<StyleRefinement>>,
461    important: Option<Rc<StyleRefinement>>,
462    normal_transitions: Option<Rc<Vec<TransitionSpec>>>,
463    important_transitions: Option<Rc<Vec<TransitionSpec>>>,
464    normal_transition_declarations: Option<Rc<transition::Collector>>,
465    important_transition_declarations: Option<Rc<transition::Collector>>,
466    normal_animations: Option<Rc<Vec<AnimationSpec>>>,
467    important_animations: Option<Rc<Vec<AnimationSpec>>>,
468    normal_animation_patch: Option<keyframes::AnimationPatch>,
469    important_animation_patch: Option<keyframes::AnimationPatch>,
470    normal_extras: Extras,
471    important_extras: Extras,
472    normal_custom: Option<Rc<Decls>>,
473    important_custom: Option<Rc<Decls>>,
474    normal_dynamic: Option<Rc<Decls>>,
475    important_dynamic: Option<Rc<Decls>>,
476    normal_font: Option<mapper::FontDecls>,
477    important_font: Option<mapper::FontDecls>,
478    specificity: u32,
479    order: u32,
480    states: u8,
481    ancestor: Option<AncestorState>,
482    /// `::before` / `::after`. A rule that carries one styles a GENERATED box, not the element it
483    /// matched, so it is folded separately.
484    pseudo: Option<PseudoElement>,
485    /// Rewritten from a view transition pseudo-element: it matches the stand-ins only.
486    vt: bool,
487    condition: Option<u32>,
488    /// Index into [`Engine::container_queries`]: the `@container` rules around this one.
489    container: Option<u32>,
490    /// A declaration reads a container query unit, so the result depends on the container's size.
491    cq: bool,
492    diagnostics: Option<Rc<Vec<String>>>,
493    /// Author-written declarations; captured only under `set_capture_rule_text` since a Tailwind
494    /// sheet is tens of thousands of strings.
495    decls: Option<Rc<Vec<(String, String, bool)>>>,
496}
497
498impl RuleEntry {
499    fn set_declarations(&mut self, c: &mapper::Converted) {
500        self.normal = c.normal.clone();
501        self.important = c.important.clone();
502        self.normal_transitions = c.normal_transitions.clone();
503        self.important_transitions = c.important_transitions.clone();
504        self.normal_transition_declarations = c.normal_transition_declarations.clone();
505        self.important_transition_declarations = c.important_transition_declarations.clone();
506        self.normal_animations = c.normal_animations.clone();
507        self.important_animations = c.important_animations.clone();
508        self.normal_animation_patch = c.normal_animation_patch.clone();
509        self.important_animation_patch = c.important_animation_patch.clone();
510        self.normal_extras = c.normal_extras.clone();
511        self.important_extras = c.important_extras.clone();
512        self.normal_custom = c.normal_custom.clone();
513        self.important_custom = c.important_custom.clone();
514        self.normal_dynamic = c.normal_dynamic.clone();
515        self.important_dynamic = c.important_dynamic.clone();
516        self.normal_font = c.normal_font.clone();
517        self.important_font = c.important_font.clone();
518    }
519
520    fn half(&self, important: bool) -> Half<'_> {
521        if important {
522            Half {
523                refinement: self.important.as_ref(),
524                font: self.important_font.as_ref(),
525                dynamic: self.important_dynamic.as_deref().map(Vec::as_slice),
526                outline: self.important_extras.outline,
527            }
528        } else {
529            Half {
530                refinement: self.normal.as_ref(),
531                font: self.normal_font.as_ref(),
532                dynamic: self.normal_dynamic.as_deref().map(Vec::as_slice),
533                outline: self.normal_extras.outline,
534            }
535        }
536    }
537}
538
539fn refine_font(parent: &gpui::Font, refinement: &gpui::TextStyleRefinement) -> gpui::Font {
540    gpui::Font {
541        family: refinement
542            .font_family
543            .clone()
544            .unwrap_or_else(|| parent.family.clone()),
545        features: refinement
546            .font_features
547            .clone()
548            .unwrap_or_else(|| parent.features.clone()),
549        fallbacks: refinement
550            .font_fallbacks
551            .clone()
552            .or_else(|| parent.fallbacks.clone()),
553        weight: refinement.font_weight.unwrap_or(parent.weight),
554        style: refinement.font_style.unwrap_or(parent.style),
555    }
556}
557
558#[derive(Clone, Copy)]
559struct Half<'a> {
560    refinement: Option<&'a Rc<StyleRefinement>>,
561    font: Option<&'a mapper::FontDecls>,
562    dynamic: Option<&'a [(String, String)]>,
563    outline: mapper::OutlinePatch,
564}
565
566impl<'a> Half<'a> {
567    fn of_inline(inline: &'a InlineStyle) -> Self {
568        Half {
569            refinement: inline.refinement.as_ref(),
570            font: inline.font.as_ref(),
571            dynamic: (!inline.dynamic.is_empty()).then_some(inline.dynamic.as_slice()),
572            outline: inline.extras.outline,
573        }
574    }
575
576    fn of_inline_at(inline: &'a InlineStyle, important: bool) -> Option<(Self, &'a Extras)> {
577        let split = inline.priority.as_ref().filter(|halves| {
578            let important = &halves[1];
579            important.refinement.is_some()
580                || important.font.is_some()
581                || important.dynamic.is_some()
582                || important.extras != Extras::default()
583        });
584        match split {
585            Some(halves) => {
586                let half = &halves[important as usize];
587                Some((
588                    Half {
589                        refinement: half.refinement.as_ref(),
590                        font: half.font.as_ref(),
591                        dynamic: half.dynamic.as_deref().map(Vec::as_slice),
592                        outline: half.extras.outline,
593                    },
594                    &half.extras,
595                ))
596            }
597            None if important => None,
598            None => Some((Half::of_inline(inline), &inline.extras)),
599        }
600    }
601
602    fn is_empty(&self) -> bool {
603        self.refinement.is_none() && self.font.is_none() && self.dynamic.is_none()
604    }
605
606    fn font_relative(&self) -> bool {
607        self.font.is_some() || self.dynamic.is_some()
608    }
609
610    #[allow(clippy::too_many_arguments)]
611    fn apply(
612        &self,
613        vars: &Vars,
614        env: &Env,
615        basis: f32,
616        parent: f32,
617        font: &gpui::Font,
618        parent_font: &gpui::Font,
619        bucket: &mut StyleRefinement,
620        extras: &mut Extras,
621        diagnostics: &mut Vec<String>,
622    ) {
623        let outline = bucket.vn_outline;
624        if let Some(r) = self.refinement {
625            bucket.refine(r);
626        }
627        self.outline.merge_over(outline, &mut bucket.vn_outline);
628        if let Some(list) = self.font {
629            for p in list.iter() {
630                let at = if mapper::sets_font_size(p) {
631                    parent
632                } else {
633                    basis
634                };
635                let face = if mapper::sets_font_size(p) {
636                    parent_font
637                } else {
638                    font
639                };
640                mapper::with_font_face(face, || {
641                    mapper::apply_at(p, at, bucket, extras, diagnostics)
642                });
643            }
644        }
645        if let Some(list) = self.dynamic {
646            for (name, raw) in list {
647                let at = if name == "font-size" { parent } else { basis };
648                let face = if name == "font-size" {
649                    parent_font
650                } else {
651                    font
652                };
653                mapper::with_font_face(face, || {
654                    mapper::with_font_basis(at, || {
655                        mapper::apply_dynamic(name, raw, vars, env, bucket, extras, diagnostics)
656                    })
657                });
658            }
659        }
660    }
661
662    fn font_descriptor(&self, vars: &Vars, env: &Env, into: &mut gpui::TextStyleRefinement) {
663        if let Some(refinement) = self.refinement {
664            into.refine(&refinement.text);
665        }
666        let mut scratch = StyleRefinement::default();
667        let mut extras = Extras::default();
668        let mut quiet = Vec::new();
669        if let Some(properties) = self.font {
670            for property in properties.iter().filter(|property| {
671                matches!(
672                    property,
673                    lightningcss::properties::Property::FontFamily(_)
674                        | lightningcss::properties::Property::FontWeight(_)
675                        | lightningcss::properties::Property::FontStyle(_)
676                )
677            }) {
678                mapper::apply_at(
679                    property,
680                    mapper::rem_basis(),
681                    &mut scratch,
682                    &mut extras,
683                    &mut quiet,
684                );
685            }
686        }
687        if let Some(properties) = self.dynamic {
688            for (name, raw) in properties.iter().filter(|(name, _)| {
689                matches!(
690                    name.as_str(),
691                    "font-family"
692                        | "font-weight"
693                        | "font-style"
694                        | "font-feature-settings"
695                        | "font-variant-numeric"
696                )
697            }) {
698                mapper::apply_dynamic(name, raw, vars, env, &mut scratch, &mut extras, &mut quiet);
699            }
700        }
701        into.refine(&scratch.text);
702    }
703
704    fn font_size(&self, vars: &Vars, env: &Env, parent: f32) -> Option<f32> {
705        let mut size = self
706            .refinement
707            .and_then(|r| r.text.font_size)
708            .map(mapper::font_size_px);
709        let sets = self
710            .font
711            .is_some_and(|l| l.iter().any(mapper::sets_font_size))
712            || self
713                .dynamic
714                .is_some_and(|l| l.iter().any(|(n, _)| n == "font-size"));
715        if sets {
716            let mut scratch = StyleRefinement::default();
717            let mut extras = Extras::default();
718            let mut quiet = Vec::new();
719            if let Some(list) = self.font {
720                for p in list.iter().filter(|p| mapper::sets_font_size(p)) {
721                    mapper::apply_at(p, parent, &mut scratch, &mut extras, &mut quiet);
722                }
723            }
724            if let Some(list) = self.dynamic {
725                for (name, raw) in list.iter().filter(|(n, _)| n == "font-size") {
726                    mapper::with_font_basis(parent, || {
727                        mapper::apply_dynamic(
728                            name,
729                            raw,
730                            vars,
731                            env,
732                            &mut scratch,
733                            &mut extras,
734                            &mut quiet,
735                        )
736                    });
737                }
738            }
739            if let Some(l) = scratch.text.font_size {
740                size = Some(mapper::font_size_px(l));
741            }
742        }
743        size
744    }
745}
746
747/// `:where()` gives specificity 0 and the sheet is collected first, and no `@layer` is modelled, so
748/// every author rule beats these.
749pub(crate) const UA_SHEET: &str = ":where([hidden]) { display: none }";
750
751/// An element's used color scheme from its computed `color-scheme` (inherited in `vars`): `None`
752/// under `normal`, else whether it is dark, the environment's preference winning when both are
753/// listed.
754pub fn color_scheme(vars: &Vars, env: &Env) -> Option<bool> {
755    let (mut light, mut dark) = (false, false);
756    for word in vars.get(mapper::COLOR_SCHEME)?.split_ascii_whitespace() {
757        light |= word.eq_ignore_ascii_case("light");
758        dark |= word.eq_ignore_ascii_case("dark");
759    }
760    (light || dark).then_some(dark && (env.dark || !light))
761}
762
763/// Whether `light-dark()` takes its dark half: `normal` is light, as in a browser.
764pub fn used_dark(vars: &Vars, env: &Env) -> bool {
765    color_scheme(vars, env).unwrap_or(false)
766}
767
768thread_local! {
769    /// The element's own `color`, handed to a second cascade pass by a first one in which a
770    /// colour function read `currentColor` before `color` was known.
771    static OWN_COLOR_GUESS: std::cell::Cell<Option<gpui::Hsla>> = const { std::cell::Cell::new(None) };
772}
773
774pub struct Engine {
775    rules: Vec<RuleEntry>,
776    index: RuleIndex,
777    conditions: Vec<media::Cond>,
778    condition_text: Vec<String>,
779    sibling_combinators: bool,
780    group_states: bool,
781    keyframes: std::collections::HashMap<Box<str>, Vec<KeyframesBlock>>,
782    percentage_properties: Vec<(Option<u32>, registered::PercentageRegistration)>,
783    viewport_blocks: Vec<ViewportBlock>,
784    viewport_unkept: bool,
785    functions: Rc<functions::Table>,
786    /// Compile and viewport rebase counter: the matched-properties cache keys on it, since rule
787    /// indices mean nothing across sheets and a rebase rewrites declarations in place.
788    generation: u64,
789    share: bool,
790    collecting_ua: bool,
791    container_queries: Vec<container::Query>,
792    /// The `@container` rules being collected into, innermost last.
793    collecting_container: Option<u32>,
794    /// The sheet has a `@container` rule or a container query unit.
795    uses_containers: bool,
796    pub diagnostics: Vec<String>,
797}
798
799fn next_generation() -> u64 {
800    static NEXT: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(1);
801    NEXT.fetch_add(1, std::sync::atomic::Ordering::Relaxed)
802}
803
804/// Kept as printed text: an owned `DeclarationBlock` added 248 KB to the exe, and re-parsing a few
805/// dozen short blocks is negligible.
806struct ViewportBlock {
807    css: Box<str>,
808    rules: std::ops::Range<u32>,
809}
810
811struct KeyframesBlock {
812    condition: Option<u32>,
813    block: Rc<keyframes::Keyframes>,
814}
815
816#[derive(Default)]
817struct RuleIndex {
818    by_id: std::collections::HashMap<Box<str>, Vec<u32>>,
819    by_class: std::collections::HashMap<Box<str>, Vec<u32>>,
820    by_tag: std::collections::HashMap<Box<str>, Vec<u32>>,
821    root: Vec<u32>,
822    by_parent_id: std::collections::HashMap<Box<str>, Vec<u32>>,
823    by_parent_class: std::collections::HashMap<Box<str>, Vec<u32>>,
824    by_parent_tag: std::collections::HashMap<Box<str>, Vec<u32>>,
825    any: Vec<u32>,
826    enabled: bool,
827}
828
829const BUCKET_ANY: usize = 0;
830const BUCKET_TAG: usize = 1;
831const BUCKET_CLASS: usize = 2;
832const BUCKET_ID: usize = 3;
833const BUCKET_ROOT: usize = 4;
834const BUCKET_PARENT: usize = 5;
835
836enum Key {
837    Id(Box<str>),
838    Class(Box<str>),
839    Tag(Box<str>),
840}
841
842enum Bucket {
843    Subject(Key),
844    Root,
845    Parent(Key),
846    Any,
847}
848
849macro_rules! compound_key {
850    ($iter:expr) => {{
851        let mut id: Option<Box<str>> = None;
852        let mut class: Option<Box<str>> = None;
853        let mut tag: Option<Box<str>> = None;
854        let mut root = false;
855        for component in &mut $iter {
856            match component {
857                Component::ID(i) if id.is_none() => id = Some(i.0.as_ref().into()),
858                Component::Class(c) if class.is_none() => class = Some(c.0.as_ref().into()),
859                // `is_html_element_in_html_document()` is false for us, so the matcher compares
860                // against `name` as written, never `lower_name`.
861                Component::LocalName(ln) if tag.is_none() => tag = Some(ln.name.0.as_ref().into()),
862                Component::Root => root = true,
863                _ => {}
864            }
865        }
866        let key = id
867            .map(Key::Id)
868            .or(class.map(Key::Class))
869            .or(tag.map(Key::Tag));
870        (key, root)
871    }};
872}
873
874fn bucket_of(sel: &Selector<'_>) -> Bucket {
875    use parcel_selectors::parser::Combinator;
876    let mut iter = sel.iter();
877    let (mut key, mut root) = compound_key!(iter);
878    let mut next = iter.next_sequence();
879    if next == Some(Combinator::PseudoElement) {
880        (key, root) = compound_key!(iter);
881        next = iter.next_sequence();
882    }
883    match (key, root) {
884        (Some(Key::Tag(_)), true) => return Bucket::Root,
885        (Some(key), _) => return Bucket::Subject(key),
886        (None, true) => return Bucket::Root,
887        (None, false) => {}
888    }
889    loop {
890        match next {
891            Some(Combinator::NextSibling | Combinator::LaterSibling) => {
892                let _ = compound_key!(iter);
893                next = iter.next_sequence();
894            }
895            Some(Combinator::Child) => {
896                return match compound_key!(iter) {
897                    (Some(key), _) => Bucket::Parent(key),
898                    (None, _) => Bucket::Any,
899                };
900            }
901            _ => return Bucket::Any,
902        }
903    }
904}
905
906type KeyMap = std::collections::HashMap<Box<str>, Vec<u32>>;
907
908fn offer_keyed<D: MatchDom>(
909    node: &D,
910    maps: [&KeyMap; 3],
911    buckets: [usize; 3],
912    f: &mut dyn FnMut(u32, usize),
913) {
914    let [by_tag, by_class, by_id] = maps;
915    if !by_tag.is_empty() {
916        if let Some(v) = by_tag.get(node.tag_name()) {
917            for &i in v {
918                f(i, buckets[0]);
919            }
920        }
921        if node.is_root() {
922            for name in ["html", "body"] {
923                if let Some(v) = by_tag.get(name) {
924                    for &i in v {
925                        f(i, buckets[0]);
926                    }
927                }
928            }
929        }
930    }
931    if !by_class.is_empty() {
932        node.each_class(&mut |c| {
933            if let Some(v) = by_class.get(c) {
934                for &i in v {
935                    f(i, buckets[1]);
936                }
937            }
938        });
939    }
940    if !by_id.is_empty() {
941        if let Some(id) = node.attr("id") {
942            if let Some(v) = by_id.get(id) {
943                for &i in v {
944                    f(i, buckets[2]);
945                }
946            }
947        }
948    }
949}
950
951fn has_sibling_combinator(sel: &Selector<'_>) -> bool {
952    let mut iter = sel.iter();
953    loop {
954        for component in &mut iter {
955            let nested = match component {
956                Component::Negation(list)
957                | Component::Where(list)
958                | Component::Is(list)
959                | Component::Any(_, list) => list,
960                _ => continue,
961            };
962            if list_has_sibling_combinator(nested) {
963                return true;
964            }
965        }
966        match iter.next_sequence() {
967            Some(parcel_selectors::parser::Combinator::NextSibling)
968            | Some(parcel_selectors::parser::Combinator::LaterSibling) => return true,
969            Some(_) => continue,
970            None => return false,
971        }
972    }
973}
974
975fn list_has_sibling_combinator(list: &[Selector<'_>]) -> bool {
976    list.iter().any(has_sibling_combinator)
977}
978
979impl RuleIndex {
980    fn file(&mut self, sel: &Selector<'_>, rule: u32) {
981        match bucket_of(sel) {
982            Bucket::Subject(Key::Id(k)) => self.by_id.entry(k).or_default().push(rule),
983            Bucket::Subject(Key::Class(k)) => self.by_class.entry(k).or_default().push(rule),
984            Bucket::Subject(Key::Tag(k)) => self.by_tag.entry(k).or_default().push(rule),
985            Bucket::Root => self.root.push(rule),
986            Bucket::Parent(Key::Id(k)) => self.by_parent_id.entry(k).or_default().push(rule),
987            Bucket::Parent(Key::Class(k)) => self.by_parent_class.entry(k).or_default().push(rule),
988            Bucket::Parent(Key::Tag(k)) => self.by_parent_tag.entry(k).or_default().push(rule),
989            Bucket::Any => self.any.push(rule),
990        }
991    }
992
993    fn shrink(&mut self) {
994        for map in [
995            &mut self.by_id,
996            &mut self.by_class,
997            &mut self.by_tag,
998            &mut self.by_parent_id,
999            &mut self.by_parent_class,
1000            &mut self.by_parent_tag,
1001        ] {
1002            map.values_mut().for_each(Vec::shrink_to_fit);
1003            map.shrink_to_fit();
1004        }
1005        self.root.shrink_to_fit();
1006        self.any.shrink_to_fit();
1007    }
1008}
1009
1010/// Is the `SK_PERF` probe on? sk-css cannot see sk-tree's copy of the flag and the three `Instant`s
1011/// per element are only free when nobody is looking.
1012fn perf_on() -> bool {
1013    static ON: std::sync::atomic::AtomicU8 = std::sync::atomic::AtomicU8::new(0);
1014    match ON.load(std::sync::atomic::Ordering::Relaxed) {
1015        1 => false,
1016        2 => true,
1017        _ => {
1018            let on = std::env::var("SK_PERF")
1019                .map(|v| {
1020                    let v = v.trim().to_ascii_lowercase();
1021                    !(v.is_empty() || v == "0" || v == "false" || v == "off")
1022                })
1023                .unwrap_or(false);
1024            ON.store(if on { 2 } else { 1 }, std::sync::atomic::Ordering::Relaxed);
1025            on
1026        }
1027    }
1028}
1029
1030fn rule_index_enabled() -> bool {
1031    static ON: std::sync::atomic::AtomicU8 = std::sync::atomic::AtomicU8::new(0);
1032    match ON.load(std::sync::atomic::Ordering::Relaxed) {
1033        1 => false,
1034        2 => true,
1035        _ => {
1036            let off = std::env::var("SK_CSS_NO_RULE_INDEX")
1037                .map(|v| {
1038                    let v = v.trim().to_ascii_lowercase();
1039                    !(v.is_empty() || v == "0" || v == "false" || v == "off")
1040                })
1041                .unwrap_or(false);
1042            ON.store(
1043                if off { 1 } else { 2 },
1044                std::sync::atomic::Ordering::Relaxed,
1045            );
1046            !off
1047        }
1048    }
1049}
1050
1051struct ParsedSheet<'i> {
1052    sheet: Option<StyleSheet<'i>>,
1053    diagnostics: Vec<String>,
1054}
1055
1056thread_local! {
1057    static UA_PARSED: std::cell::OnceCell<Option<&'static StyleSheet<'static>>> =
1058        const { std::cell::OnceCell::new() };
1059    static REPARSED: std::cell::RefCell<std::collections::HashMap<String, Option<&'static Selector<'static>>>> =
1060        std::cell::RefCell::new(std::collections::HashMap::new());
1061}
1062
1063fn parse_author_sheet(src: &str) -> ParsedSheet<'_> {
1064    // Without it, ONE stray `}` anywhere — the Argon client ships one after a `@keyframes` — failed
1065    // the whole sheet, and the app painted unstyled.
1066    let warnings = std::sync::Arc::new(std::sync::RwLock::new(Vec::new()));
1067    let options = ParserOptions {
1068        error_recovery: true,
1069        warnings: Some(warnings.clone()),
1070        ..ParserOptions::default()
1071    };
1072    let mut diagnostics = Vec::new();
1073    let sheet = match StyleSheet::parse(src, options) {
1074        Ok(s) => Some(s),
1075        Err(e) => {
1076            diagnostics.push(format!("stylesheet parse error: {e}"));
1077            None
1078        }
1079    };
1080    if sheet.is_some() {
1081        if let Ok(skipped) = warnings.read() {
1082            // lightningcss keeps an `@function` as an unknown at-rule, which the engine reads.
1083            let skipped: Vec<_> = skipped
1084                .iter()
1085                .filter(|e| !e.to_string().starts_with("Unknown at rule: @function"))
1086                .collect();
1087            const SHOWN: usize = 20;
1088            for e in skipped.iter().take(SHOWN) {
1089                diagnostics.push(format!("stylesheet: {e} — skipped, as a browser skips it"));
1090            }
1091            if skipped.len() > SHOWN {
1092                diagnostics.push(format!(
1093                    "stylesheet: {} more invalid rules or declarations skipped",
1094                    skipped.len() - SHOWN
1095                ));
1096            }
1097        }
1098    }
1099    ParsedSheet { sheet, diagnostics }
1100}
1101
1102impl Engine {
1103    pub fn compile(css: &str) -> Engine {
1104        Engine::compile_sheets(&[css])
1105    }
1106
1107    pub fn compile_sheets(sheets: &[&str]) -> Engine {
1108        let mut engine = Engine {
1109            rules: Vec::new(),
1110            index: RuleIndex {
1111                enabled: rule_index_enabled(),
1112                ..RuleIndex::default()
1113            },
1114            conditions: Vec::new(),
1115            condition_text: Vec::new(),
1116            sibling_combinators: false,
1117            group_states: false,
1118            keyframes: std::collections::HashMap::new(),
1119            percentage_properties: Vec::new(),
1120            viewport_blocks: Vec::new(),
1121            viewport_unkept: false,
1122            functions: Rc::default(),
1123            generation: next_generation(),
1124            share: share::enabled(),
1125            collecting_ua: false,
1126            container_queries: Vec::new(),
1127            collecting_container: None,
1128            uses_containers: false,
1129            diagnostics: Vec::new(),
1130        };
1131        // The flag describes THIS sheet: a resize only recompiles when the sheet currently
1132        // installed actually resolves a viewport unit.
1133        mapper::reset_viewport_units_seen();
1134        let mut order = 0u32;
1135        engine.collect_ua(&mut order);
1136        for css in sheets {
1137            let parsed = parse_author_sheet(css);
1138            engine.diagnostics.extend(parsed.diagnostics);
1139            if let Some(sheet) = &parsed.sheet {
1140                engine.collect(&sheet.rules.0, None, &mut order);
1141            }
1142        }
1143        engine.shrink();
1144        engine
1145    }
1146
1147    fn shrink(&mut self) {
1148        self.rules.shrink_to_fit();
1149        self.index.shrink();
1150        self.conditions.shrink_to_fit();
1151        self.condition_text.shrink_to_fit();
1152        self.viewport_blocks.shrink_to_fit();
1153    }
1154
1155    fn collect_ua(&mut self, order: &mut u32) {
1156        let parsed = UA_PARSED.with(|ua| {
1157            *ua.get_or_init(|| {
1158                let text: &'static str =
1159                    Box::leak(format!("{UA_SHEET}{}", view_transition::UA_SHEET).into_boxed_str());
1160                match StyleSheet::parse(text, ParserOptions::default()) {
1161                    Ok(sheet) => Some(&*Box::leak(Box::new(sheet))),
1162                    Err(_) => None,
1163                }
1164            })
1165        });
1166        self.collecting_ua = true;
1167        match parsed {
1168            Some(sheet) => self.collect(&sheet.rules.0, None, order),
1169            None => self
1170                .diagnostics
1171                .push("Skathi's UA defaults did not parse".into()),
1172        }
1173        self.collecting_ua = false;
1174    }
1175
1176    pub fn uses_sibling_combinators(&self) -> bool {
1177        self.sibling_combinators
1178    }
1179
1180    pub fn classes_keyed_on_the_parent(&self) -> impl Iterator<Item = &str> {
1181        self.index.by_parent_class.keys().map(|k| &**k)
1182    }
1183
1184    pub fn uses_group_states(&self) -> bool {
1185        self.group_states
1186    }
1187
1188    /// Whether a style can depend on a query container: the sheet has `@container` or a `cq*`
1189    /// unit. Inline styles with a `cq*` unit are the caller's to notice.
1190    pub fn uses_containers(&self) -> bool {
1191        self.uses_containers
1192    }
1193
1194    /// The last block of that name whose condition holds in `env` (CSS duplicate-name rule). `Rc`
1195    /// because a running animation keeps the block it started with.
1196    pub fn keyframes(&self, name: &str, env: &Env) -> Option<Rc<keyframes::Keyframes>> {
1197        self.keyframes
1198            .get(name)?
1199            .iter()
1200            .rev()
1201            .find_map(|entry| match entry.condition {
1202                Some(c) if !self.conditions[c as usize].eval(env) => None,
1203                _ => Some(entry.block.clone()),
1204            })
1205    }
1206
1207    pub fn keyframes_for(
1208        &self,
1209        name: &str,
1210        vars: &Vars,
1211        env: &Env,
1212        diagnostics: &mut Vec<String>,
1213    ) -> Option<Rc<keyframes::Keyframes>> {
1214        let block = self.keyframes(name, env)?;
1215        if !block.dynamic {
1216            return Some(block);
1217        }
1218        let _functions = functions::Scope::enter(&self.functions, None);
1219        let steps = block
1220            .steps
1221            .iter()
1222            .map(|step| {
1223                let mut style = (*step.style).clone();
1224                let mut extras = Extras::default();
1225                if let Some(list) = &step.dynamic {
1226                    for (property, raw) in list.iter() {
1227                        mapper::apply_dynamic(
1228                            property,
1229                            raw,
1230                            vars,
1231                            env,
1232                            &mut style,
1233                            &mut extras,
1234                            diagnostics,
1235                        );
1236                    }
1237                }
1238                keyframes::Keyframe {
1239                    offset: step.offset,
1240                    easing: step.easing,
1241                    style: Rc::new(style),
1242                    dynamic: None,
1243                    custom: step.custom.clone(),
1244                }
1245            })
1246            .collect();
1247        Some(Rc::new(keyframes::Keyframes {
1248            steps,
1249            dynamic: false,
1250        }))
1251    }
1252
1253    /// Runs `f` with this sheet's `@function`s callable, for values compiled outside the cascade.
1254    pub fn with_functions<R>(&self, f: impl FnOnce() -> R) -> R {
1255        let _functions = functions::Scope::enter(&self.functions, None);
1256        f()
1257    }
1258
1259    pub fn has_keyframes(&self) -> bool {
1260        !self.keyframes.is_empty()
1261    }
1262
1263    fn candidates<D: MatchDom>(&self, node: &D, f: &mut dyn FnMut(u32, usize)) {
1264        let vt = node.is_view_transition_pseudo();
1265        let f = &mut |i: u32, bucket: usize| {
1266            if self.rules[i as usize].vt == vt {
1267                f(i, bucket)
1268            }
1269        };
1270        if !self.index.enabled {
1271            for i in 0..self.rules.len() as u32 {
1272                f(i, BUCKET_ANY);
1273            }
1274            return;
1275        }
1276        let ix = &self.index;
1277        for &i in &ix.any {
1278            f(i, BUCKET_ANY);
1279        }
1280        offer_keyed(
1281            node,
1282            [&ix.by_tag, &ix.by_class, &ix.by_id],
1283            [BUCKET_TAG, BUCKET_CLASS, BUCKET_ID],
1284            f,
1285        );
1286        // The root answers to `html` and `body` too (`MatchDom::has_tag`); without these a `body {
1287        // }` rule would never be a candidate.
1288        if node.is_root() {
1289            for &i in &ix.root {
1290                f(i, BUCKET_ROOT);
1291            }
1292        }
1293        if !(ix.by_parent_tag.is_empty()
1294            && ix.by_parent_class.is_empty()
1295            && ix.by_parent_id.is_empty())
1296        {
1297            if let Some(parent) = node.parent() {
1298                offer_keyed(
1299                    &parent,
1300                    [&ix.by_parent_tag, &ix.by_parent_class, &ix.by_parent_id],
1301                    [BUCKET_PARENT; 3],
1302                    f,
1303                );
1304            }
1305        }
1306    }
1307
1308    fn collect(&mut self, rules: &[CssRule<'_>], condition: Option<u32>, order: &mut u32) {
1309        for rule in rules {
1310            let style = match rule {
1311                CssRule::Style(style) => style,
1312                CssRule::Media(m) => {
1313                    match media::parse_list(&m.query) {
1314                        Ok(cond) => {
1315                            let idx =
1316                                self.push_condition(cond, condition, &media::list_text(&m.query));
1317                            self.collect(&m.rules.0, Some(idx), order);
1318                        }
1319                        Err(reason) => mapper::once(
1320                            &mut self.diagnostics,
1321                            format!(
1322                                "@media {} uses {reason} — the whole block was dropped ({})",
1323                                media::list_text(&m.query),
1324                                media::SUPPORTED
1325                            ),
1326                        ),
1327                    }
1328                    continue;
1329                }
1330                CssRule::Property(property) => {
1331                    use lightningcss::values::syntax::{
1332                        ParsedComponent, SyntaxComponentKind, SyntaxString,
1333                    };
1334                    let percentage = matches!(&property.syntax, SyntaxString::Components(parts)
1335                        if parts.len() == 1 && matches!(parts[0].kind, SyntaxComponentKind::Percentage));
1336                    if percentage {
1337                        if let Some(ParsedComponent::Percentage(initial)) = &property.initial_value
1338                        {
1339                            self.percentage_properties.push((
1340                                condition,
1341                                registered::PercentageRegistration {
1342                                    name: property.name.0.to_string(),
1343                                    inherits: property.inherits,
1344                                    initial: initial.0,
1345                                },
1346                            ));
1347                        }
1348                    } else {
1349                        at_rule_ignored(rule, &mut self.diagnostics);
1350                    }
1351                    continue;
1352                }
1353                CssRule::Keyframes(kf) => {
1354                    self.collect_keyframes(kf, condition);
1355                    continue;
1356                }
1357                CssRule::Supports(sup) => {
1358                    if supports_condition(&sup.condition) {
1359                        self.collect(&sup.rules.0, condition, order);
1360                    }
1361                    continue;
1362                }
1363                CssRule::Container(c) => {
1364                    let outer = self.collecting_container;
1365                    let around = outer
1366                        .map(|i| self.container_queries[i as usize].clone())
1367                        .unwrap_or_default();
1368                    match around.nest(c) {
1369                        Ok(query) => {
1370                            self.uses_containers = true;
1371                            self.container_queries.push(query);
1372                            self.collecting_container =
1373                                Some((self.container_queries.len() - 1) as u32);
1374                            self.collect(&c.rules.0, condition, order);
1375                            self.collecting_container = outer;
1376                        }
1377                        Err(reason) => mapper::once(
1378                            &mut self.diagnostics,
1379                            format!(
1380                                "@container {} uses {reason} — the whole block was dropped ({})",
1381                                container::prelude_text(c),
1382                                container::SUPPORTED
1383                            ),
1384                        ),
1385                    }
1386                    continue;
1387                }
1388                CssRule::Unknown(u) if u.name.eq_ignore_ascii_case("function") => {
1389                    use lightningcss::traits::ToCss as _;
1390                    let text = rule
1391                        .to_css_string(lightningcss::printer::PrinterOptions::default())
1392                        .unwrap_or_default();
1393                    let cond = condition.map(|c| self.conditions[c as usize].clone());
1394                    let table = Rc::get_mut(&mut self.functions)
1395                        .expect("functions are collected before the engine is shared");
1396                    table.add(&text, cond, &mut self.diagnostics);
1397                    self.uses_containers |= table.uses_containers();
1398                    continue;
1399                }
1400                other => {
1401                    at_rule_ignored(other, &mut self.diagnostics);
1402                    continue;
1403                }
1404            };
1405            let ((converted, viewport), cq) = container::noting_units(|| {
1406                mapper::noting_viewport_units(|| mapper::convert_block(&style.declarations))
1407            });
1408            self.uses_containers |= cq;
1409            let first_rule = self.rules.len() as u32;
1410            let decls =
1411                capture_rule_text().then(|| Rc::new(mapper::decl_pairs(&style.declarations)));
1412            let declares_transition =
1413                converted.normal_transitions.is_some() || converted.important_transitions.is_some();
1414            let declares_extras = {
1415                let mut e = converted.normal_extras.clone();
1416                e.refine(&converted.important_extras);
1417                e
1418            };
1419            for sel in &style.selectors.0 {
1420                use lightningcss::traits::IntoOwned as _;
1421                let vt = sel_text(sel).contains("::view-transition");
1422                let owned: Selector<'static> = if vt {
1423                    match view_transition::rewrite(&sel_text(sel), self.collecting_ua)
1424                        .and_then(|text| reparse_selector(&text))
1425                    {
1426                        Some(s) => s.clone(),
1427                        None => {
1428                            mapper::once(
1429                                &mut self.diagnostics,
1430                                format!(
1431                                    "a view transition pseudo-element selector that cannot be \
1432                                     compiled was dropped: `{}`",
1433                                    sel_text(sel)
1434                                ),
1435                            );
1436                            continue;
1437                        }
1438                    }
1439                } else if has::present(&sel_text(sel)) {
1440                    match has::rewrite(&sel_text(sel)).and_then(|text| reparse_selector(&text)) {
1441                        Some(s) => s.clone(),
1442                        None => {
1443                            mapper::once(
1444                                &mut self.diagnostics,
1445                                format!(
1446                                    "`:has()` with an argument that cannot be compiled — rules                                      using it were dropped (first seen in `{}`)",
1447                                    sel_text(sel)
1448                                ),
1449                            );
1450                            continue;
1451                        }
1452                    }
1453                } else {
1454                    sel.clone().into_owned()
1455                };
1456                let sel = &owned;
1457                let Some((states, ancestor)) = classify_states(sel, &mut self.diagnostics) else {
1458                    continue;
1459                };
1460                let pseudo = sel.pseudo_element().and_then(pseudo_box);
1461                let control_origin = if pseudo.is_some_and(|p| p.control_index().is_some()) {
1462                    let Some(origin) = control_origin_selector(sel) else {
1463                        continue;
1464                    };
1465                    Some(Box::new(origin))
1466                } else {
1467                    None
1468                };
1469                if !probe_runnable(sel) {
1470                    self.diagnostics.push(format!(
1471                        "selector rejected (matcher cannot run it — :has()/nesting?): {}",
1472                        sel_text(sel)
1473                    ));
1474                    continue;
1475                }
1476                if !audit_selector(sel, &mut self.diagnostics) {
1477                    continue;
1478                }
1479                // A generated box is not in gpui's interactivity ladder — it is a plain child div
1480                // with no hitbox of its own — so a `:hover::after` rule has nothing to install
1481                // into.
1482                if pseudo.is_some()
1483                    && ((states != 0 && pseudo.is_some_and(|p| p.control_index().is_none()))
1484                        || ancestor.is_some())
1485                {
1486                    self.diagnostics.push(format!(
1487                        "a state-qualified pseudo-element rule is dropped (v1) — the generated                          box is not in the pointer-state ladder. Drive it from an ATTRIBUTE on                          the originating element instead (`[data-state=open]::after`), which does                          match: {}",
1488                        sel_text(sel)
1489                    ));
1490                    continue;
1491                }
1492                // Advisories ride with the rule and are said when it matches: a Tailwind sheet
1493                // carries a `focus:z-10` whether or not anything is focusable.
1494                let mut rule_diagnostics: Vec<String> = converted
1495                    .diagnostics
1496                    .as_deref()
1497                    .cloned()
1498                    .unwrap_or_default();
1499                if (states != 0 || ancestor.is_some())
1500                    && !pseudo.is_some_and(|p| p.control_index().is_some())
1501                {
1502                    // Only fields the author wrote count: some `Extras` are derived
1503                    // (`background_key_color`), and guarding on "any extra" flagged every
1504                    // `hover:bg-*` utility.
1505                    let names = extras_names(&declares_extras);
1506                    if !names.is_empty() {
1507                        rule_diagnostics.push(format!(
1508                            "{names} on a state selector applies unconditionally (v1) — these                              values are read from the base state only, not from gpui's state                              ladder: {}",
1509                            sel_text(sel)
1510                        ));
1511                    }
1512                    if declares_transition {
1513                        // State refinements are installed into gpui's own state ladder and never
1514                        // pass through our animator, so a `transition` declared on a state rule
1515                        // cannot run.
1516                        rule_diagnostics.push(format!(
1517                            "transition declared on a state selector is ignored (v1) — move it                              to the base rule: {}",
1518                            sel_text(sel)
1519                        ));
1520                    }
1521                }
1522                self.sibling_combinators |= has_sibling_combinator(sel);
1523                self.group_states |= ancestor.is_some();
1524                self.index.file(sel, self.rules.len() as u32);
1525                let specificity = sel.specificity();
1526                self.rules.push(RuleEntry {
1527                    selector: owned,
1528                    control_origin,
1529                    normal: converted.normal.clone(),
1530                    important: converted.important.clone(),
1531                    normal_transitions: converted.normal_transitions.clone(),
1532                    important_transitions: converted.important_transitions.clone(),
1533                    normal_transition_declarations: converted
1534                        .normal_transition_declarations
1535                        .clone(),
1536                    important_transition_declarations: converted
1537                        .important_transition_declarations
1538                        .clone(),
1539                    normal_animations: converted.normal_animations.clone(),
1540                    important_animations: converted.important_animations.clone(),
1541                    normal_animation_patch: converted.normal_animation_patch.clone(),
1542                    important_animation_patch: converted.important_animation_patch.clone(),
1543                    normal_extras: converted.normal_extras.clone(),
1544                    important_extras: converted.important_extras.clone(),
1545                    normal_custom: converted.normal_custom.clone(),
1546                    important_custom: converted.important_custom.clone(),
1547                    normal_dynamic: converted.normal_dynamic.clone(),
1548                    important_dynamic: converted.important_dynamic.clone(),
1549                    normal_font: converted.normal_font.clone(),
1550                    important_font: converted.important_font.clone(),
1551                    specificity,
1552                    order: *order,
1553                    states,
1554                    ancestor,
1555                    pseudo,
1556                    vt,
1557                    condition,
1558                    container: self.collecting_container,
1559                    cq,
1560                    diagnostics: (!rule_diagnostics.is_empty())
1561                        .then(|| Rc::new(std::mem::take(&mut rule_diagnostics))),
1562                    decls: decls.clone(),
1563                });
1564                *order += 1;
1565            }
1566            let rules = first_rule..self.rules.len() as u32;
1567            if viewport && !rules.is_empty() {
1568                use lightningcss::traits::ToCss as _;
1569                match style
1570                    .declarations
1571                    .to_css_string(lightningcss::printer::PrinterOptions::default())
1572                {
1573                    Ok(css) => self.viewport_blocks.push(ViewportBlock {
1574                        css: css.into(),
1575                        rules,
1576                    }),
1577                    Err(_) => self.viewport_unkept = true,
1578                }
1579            }
1580        }
1581    }
1582
1583    #[doc(hidden)]
1584    pub fn into_parts_for_measuring(self) -> Vec<(&'static str, usize, Box<dyn std::any::Any>)> {
1585        fn part<T: 'static>(
1586            name: &'static str,
1587            v: Vec<T>,
1588        ) -> (&'static str, usize, Box<dyn std::any::Any>) {
1589            (name, v.len() * std::mem::size_of::<T>(), Box::new(v))
1590        }
1591        let table = self.rules.capacity() * std::mem::size_of::<RuleEntry>();
1592        let n = self.rules.len();
1593        let mut selectors = Vec::with_capacity(n);
1594        let mut refinements = Vec::with_capacity(n);
1595        let mut transitions = Vec::with_capacity(n);
1596        let mut animations = Vec::with_capacity(n);
1597        let mut extras = Vec::with_capacity(n);
1598        let mut custom = Vec::with_capacity(n);
1599        let mut dynamic = Vec::with_capacity(n);
1600        let mut font = Vec::with_capacity(n);
1601        let mut diagnostics = Vec::with_capacity(n);
1602        let mut decls = Vec::with_capacity(n);
1603        for r in self.rules {
1604            font.push((r.normal_font, r.important_font));
1605            selectors.push(r.selector);
1606            refinements.push((r.normal, r.important));
1607            transitions.push((r.normal_transitions, r.important_transitions));
1608            animations.push((
1609                r.normal_animations,
1610                r.important_animations,
1611                r.normal_animation_patch,
1612                r.important_animation_patch,
1613            ));
1614            extras.push((r.normal_extras, r.important_extras));
1615            custom.push((r.normal_custom, r.important_custom));
1616            dynamic.push((r.normal_dynamic, r.important_dynamic));
1617            diagnostics.push(r.diagnostics);
1618            decls.push(r.decls);
1619        }
1620        vec![
1621            (
1622                "rule table (every field inline, before the parts below moved out)",
1623                table,
1624                Box::new(()),
1625            ),
1626            part("selectors", selectors),
1627            part("style refinements (normal, !important)", refinements),
1628            part("extras (normal, !important)", extras),
1629            part("transitions", transitions),
1630            part("animations", animations),
1631            part("custom properties", custom),
1632            part("var()-composed declarations", dynamic),
1633            part("font-relative declarations", font),
1634            part("per-rule advisories", diagnostics),
1635            part("author text (devtools capture)", decls),
1636            ("rule index", 0, Box::new(self.index)),
1637            (
1638                "@media conditions and their text",
1639                0,
1640                Box::new((self.conditions, self.condition_text)),
1641            ),
1642            ("@keyframes", 0, Box::new(self.keyframes)),
1643            ("viewport blocks", 0, Box::new(self.viewport_blocks)),
1644            ("sheet advisories", 0, Box::new(self.diagnostics)),
1645        ]
1646    }
1647
1648    pub fn rebase_viewport(&mut self) -> bool {
1649        if self.viewport_unkept {
1650            return false;
1651        }
1652        self.generation = next_generation();
1653        let options = || ParserOptions {
1654            error_recovery: true,
1655            ..ParserOptions::default()
1656        };
1657        for block in &self.viewport_blocks {
1658            let Ok(declarations) = DeclarationBlock::parse_string(&block.css, options()) else {
1659                return false;
1660            };
1661            let converted = mapper::convert_block(&declarations);
1662            for i in block.rules.clone() {
1663                self.rules[i as usize].set_declarations(&converted);
1664            }
1665        }
1666        true
1667    }
1668
1669    fn push_condition(&mut self, cond: media::Cond, parent: Option<u32>, text: &str) -> u32 {
1670        let cond = match parent {
1671            Some(p) => self.conditions[p as usize].clone().and(cond),
1672            None => cond,
1673        };
1674        let text = match parent {
1675            Some(p) => format!("{} and {text}", self.condition_text[p as usize]),
1676            None => text.to_string(),
1677        };
1678        if let Some(i) = self.conditions.iter().position(|c| *c == cond) {
1679            return i as u32;
1680        }
1681        self.conditions.push(cond);
1682        self.condition_text.push(text);
1683        (self.conditions.len() - 1) as u32
1684    }
1685
1686    pub fn compute<D: MatchDom>(
1687        &self,
1688        node: D,
1689        inline: Option<&StyleRefinement>,
1690        env: &Env,
1691    ) -> ComputedStates {
1692        self.compute_with(node, inline, None, env)
1693    }
1694
1695    pub fn compute_with<D: MatchDom>(
1696        &self,
1697        node: D,
1698        inline: Option<&StyleRefinement>,
1699        inline_transitions: Option<&Rc<Vec<TransitionSpec>>>,
1700        env: &Env,
1701    ) -> ComputedStates {
1702        self.compute_full(node, inline, inline_transitions, Extras::default(), env)
1703    }
1704
1705    pub fn compute_full<D: MatchDom>(
1706        &self,
1707        node: D,
1708        inline: Option<&StyleRefinement>,
1709        inline_transitions: Option<&Rc<Vec<TransitionSpec>>>,
1710        inline_extras: Extras,
1711        env: &Env,
1712    ) -> ComputedStates {
1713        let style = InlineStyle {
1714            refinement: inline.map(|r| Rc::new(r.clone())),
1715            transitions: inline_transitions.cloned(),
1716            extras: inline_extras,
1717            ..Default::default()
1718        };
1719        let mut diagnostics = Vec::new();
1720        self.compute_node(
1721            node,
1722            Some(&style),
1723            &Rc::new(Vars::default()),
1724            None,
1725            env,
1726            &mut diagnostics,
1727        )
1728    }
1729
1730    /// Custom properties inherit, so the caller must walk the tree in document order and thread
1731    /// each node's `vars` into its children. `diagnostics` are per element; the caller dedupes.
1732    pub fn compute_node<D: MatchDom>(
1733        &self,
1734        node: D,
1735        inline: Option<&InlineStyle>,
1736        parent_vars: &Rc<Vars>,
1737        parent_color: Option<gpui::Hsla>,
1738        env: &Env,
1739        diagnostics: &mut Vec<String>,
1740    ) -> ComputedStates {
1741        self.compute_node_at(
1742            node,
1743            inline,
1744            parent_vars,
1745            parent_color,
1746            mapper::rem_basis(),
1747            env,
1748            diagnostics,
1749        )
1750    }
1751
1752    #[allow(clippy::too_many_arguments)]
1753    pub fn compute_node_at<D: MatchDom>(
1754        &self,
1755        node: D,
1756        inline: Option<&InlineStyle>,
1757        parent_vars: &Rc<Vars>,
1758        parent_color: Option<gpui::Hsla>,
1759        parent_font_size: f32,
1760        env: &Env,
1761        diagnostics: &mut Vec<String>,
1762    ) -> ComputedStates {
1763        self.compute_node_with_font(
1764            node,
1765            inline,
1766            parent_vars,
1767            parent_color,
1768            parent_font_size,
1769            &gpui::Font::default(),
1770            env,
1771            diagnostics,
1772        )
1773    }
1774
1775    #[allow(clippy::too_many_arguments)]
1776    pub fn compute_node_with_font<D: MatchDom>(
1777        &self,
1778        node: D,
1779        inline: Option<&InlineStyle>,
1780        parent_vars: &Rc<Vars>,
1781        parent_color: Option<gpui::Hsla>,
1782        parent_font_size: f32,
1783        parent_font: &gpui::Font,
1784        env: &Env,
1785        diagnostics: &mut Vec<String>,
1786    ) -> ComputedStates {
1787        let guessed = OWN_COLOR_GUESS.with(std::cell::Cell::take);
1788        let _functions = functions::Scope::enter(&self.functions, Some(parent_vars));
1789        let probe = perf_on();
1790        let t0 = probe.then(std::time::Instant::now);
1791        let el = element::El(node);
1792        let mut matched: Vec<&RuleEntry> = Vec::new();
1793        let mut tested = 0u64;
1794        let mut by_bucket = [0u32; 6];
1795        self.candidates(&node, &mut |i, bucket| {
1796            let rule = &self.rules[i as usize];
1797            if let Some(c) = rule.condition {
1798                if !self.conditions[c as usize].eval(env) {
1799                    return;
1800                }
1801            }
1802            tested += 1;
1803            by_bucket[bucket] += 1;
1804            let mode = if rule.pseudo.is_some() && rule.control_origin.is_none() {
1805                MatchingMode::ForStatelessPseudoElement
1806            } else {
1807                MatchingMode::Normal
1808            };
1809            let mut ctx: MatchingContext<'_, '_, element::Impl> =
1810                MatchingContext::new(mode, None, None, QuirksMode::NoQuirks);
1811            if matches_selector(
1812                rule.control_origin.as_deref().unwrap_or(&rule.selector),
1813                0,
1814                None,
1815                &el,
1816                &mut ctx,
1817                &mut |_, _| {},
1818            ) && rule
1819                .container
1820                .is_none_or(|q| self.container_queries[q as usize].eval(parent_vars))
1821            {
1822                matched.push(rule);
1823            }
1824        });
1825        let base = self.rules.as_ptr() as usize;
1826        let index_of = |r: &RuleEntry| {
1827            ((r as *const RuleEntry as usize - base) / std::mem::size_of::<RuleEntry>()) as u32
1828        };
1829        matched.sort_by_key(|r| (r.specificity, r.order, index_of(r)));
1830        let t1 = probe.then(std::time::Instant::now);
1831
1832        let share_key = (self.share
1833            && inline.is_none()
1834            && !self.functions.uses_containers()
1835            && !matched.iter().any(|r| r.ancestor.is_some() || r.cq))
1836        .then(|| {
1837            let rules = matched.iter().map(|r| index_of(r)).collect();
1838            share::Key::new(
1839                self.generation,
1840                rules,
1841                parent_vars,
1842                parent_color,
1843                parent_font_size,
1844                parent_font,
1845                env,
1846            )
1847        });
1848        if let Some(key) = &share_key {
1849            let hit = share::lookup(key);
1850            if probe {
1851                perf::note_share(hit.is_some());
1852            }
1853            if let Some(states) = hit {
1854                if let (Some(t0), Some(t1)) = (t0, t1) {
1855                    let ms = t1.saturating_duration_since(t0).as_secs_f32() * 1000.0;
1856                    perf::note_node(tested, ms, 0.0, 0.0);
1857                    perf::note_split(by_bucket, matched.len());
1858                }
1859                return states;
1860            }
1861        }
1862        let parent_current = parent_color.unwrap_or_else(gpui::black);
1863        let current_color =
1864            mapper::CurrentColorScope::enter(parent_current, guessed.unwrap_or(parent_current));
1865
1866        // Duplicates stay (`vars::resolve` is last-wins in push order). Borrowed because Tailwind's
1867        // universal block is ~40 declarations per element.
1868        let mut own_custom: Vec<&(String, String)> = Vec::new();
1869        let mut state_custom: [Vec<&(String, String)>; STATE_RUNGS] = Default::default();
1870        for important_pass in [false, true] {
1871            for r in &matched {
1872                let declared = if important_pass {
1873                    &r.important_custom
1874                } else {
1875                    &r.normal_custom
1876                };
1877                if let Some(list) = declared {
1878                    match rung_of(r.states) {
1879                        None => own_custom.extend(list.iter()),
1880                        Some(rung) => state_custom[rung].extend(list.iter()),
1881                    }
1882                }
1883            }
1884            if let Some(inline) = inline {
1885                if let Some(priority) = &inline.priority {
1886                    if let Some(custom) = &priority[important_pass as usize].custom {
1887                        own_custom.extend(custom.iter());
1888                    }
1889                } else if !important_pass {
1890                    own_custom.extend(inline.custom.iter());
1891                }
1892            }
1893        }
1894        let mut registrations = Vec::new();
1895        for (condition, registration) in &self.percentage_properties {
1896            if condition.is_some_and(|c| !self.conditions[c as usize].eval(env)) {
1897                continue;
1898            }
1899            registrations
1900                .retain(|r: &registered::PercentageRegistration| r.name != registration.name);
1901            registrations.push(registration.clone());
1902        }
1903        let vars =
1904            vars::resolve_registered(parent_vars, &own_custom, &registrations, env, diagnostics);
1905        let _color_scheme = mapper::ColorSchemeScope::enter(used_dark(&vars, env));
1906        let state_vars: [Option<Rc<Vars>>; STATE_RUNGS] = std::array::from_fn(|rung| {
1907            if state_custom[rung].is_empty() {
1908                return None;
1909            }
1910            let mut combined = own_custom.clone();
1911            combined.extend(state_custom[rung].iter().copied());
1912            Some(vars::resolve_registered(
1913                parent_vars,
1914                &combined,
1915                &registrations,
1916                env,
1917                diagnostics,
1918            ))
1919        });
1920
1921        let mut font_size: Option<f32> = None;
1922        let mut rung_font: [Option<f32>; STATE_RUNGS] = [None; STATE_RUNGS];
1923        for important_pass in [false, true] {
1924            for r in &matched {
1925                if r.pseudo.is_some() || r.ancestor.is_some() {
1926                    continue;
1927                }
1928                let rung = rung_of(r.states);
1929                let scope = rung.and_then(|i| state_vars[i].as_ref()).unwrap_or(&vars);
1930                if let Some(size) = mapper::with_font_face(parent_font, || {
1931                    r.half(important_pass)
1932                        .font_size(scope, env, parent_font_size)
1933                }) {
1934                    match rung {
1935                        None => font_size = Some(size),
1936                        Some(i) => rung_font[i] = Some(size),
1937                    }
1938                }
1939            }
1940            let inline_half = inline.and_then(|i| Half::of_inline_at(i, important_pass));
1941            if let Some(size) = mapper::with_font_face(parent_font, || {
1942                inline_half.and_then(|(half, _)| half.font_size(&vars, env, parent_font_size))
1943            }) {
1944                font_size = Some(size);
1945            }
1946        }
1947        let font_size = font_size.unwrap_or(parent_font_size);
1948        let mut descriptor = gpui::TextStyleRefinement::default();
1949        let mut rung_descriptors: [gpui::TextStyleRefinement; STATE_RUNGS] = Default::default();
1950        for important in [false, true] {
1951            for rule in matched
1952                .iter()
1953                .filter(|rule| rule.pseudo.is_none() && rule.ancestor.is_none())
1954            {
1955                let rung = rung_of(rule.states);
1956                let scope = rung
1957                    .and_then(|index| state_vars[index].as_ref())
1958                    .unwrap_or(&vars);
1959                let target = rung.map_or(&mut descriptor, |index| &mut rung_descriptors[index]);
1960                rule.half(important).font_descriptor(scope, env, target);
1961            }
1962            if let Some((half, _)) = inline.and_then(|i| Half::of_inline_at(i, important)) {
1963                half.font_descriptor(&vars, env, &mut descriptor);
1964            }
1965        }
1966        let computed_font = refine_font(parent_font, &descriptor);
1967        let rung_faces: [gpui::Font; STATE_RUNGS] =
1968            std::array::from_fn(|index| refine_font(&computed_font, &rung_descriptors[index]));
1969        let t2 = probe.then(std::time::Instant::now);
1970
1971        for r in &matched {
1972            if let Some(list) = &r.diagnostics {
1973                for d in list.iter() {
1974                    mapper::once(diagnostics, d.clone());
1975                }
1976            }
1977        }
1978
1979        let mut base = StyleRefinement::default();
1980        let mut hover = StyleRefinement::default();
1981        let mut active = StyleRefinement::default();
1982        let mut focus = StyleRefinement::default();
1983        let mut focus_visible = StyleRefinement::default();
1984        let mut focus_within = StyleRefinement::default();
1985        let (mut any_hover, mut any_active) = (false, false);
1986        let (mut any_focus, mut any_focus_visible, mut any_focus_within) = (false, false, false);
1987        // `.group:hover .this` — one group per state, because gpui carries one `group_hover` / one
1988        // `group_active` per element.
1989        let mut group = GroupFold::default();
1990        let mut transitions: Option<Rc<Vec<TransitionSpec>>> = None;
1991        let mut animations: Option<Rc<Vec<AnimationSpec>>> = None;
1992        let mut animation_patch = keyframes::AnimationPatch::default();
1993        let mut extras = Extras::default();
1994        // Kept out of `base`: a `::after { content: "" }` must not give the originating element an
1995        // empty content string.
1996        let mut before = (StyleRefinement::default(), Extras::default());
1997        let mut after = (StyleRefinement::default(), Extras::default());
1998        let mut placeholder = (StyleRefinement::default(), Extras::default());
1999        let mut selection = (StyleRefinement::default(), Extras::default());
2000        let mut file_button = (StyleRefinement::default(), Extras::default());
2001        let mut controls: [Option<ControlFold>; 4] = Default::default();
2002        let (mut any_before, mut any_after, mut any_placeholder) = (false, false, false);
2003        let (mut any_selection, mut any_file_button) = (false, false);
2004        let mut rung_outline = [mapper::OutlinePatch::default(); STATE_RUNGS];
2005        let mut held_decoration: Option<mapper::DecorationPatch> = None;
2006        macro_rules! over_state_buckets {
2007            ($half:expr) => {{
2008                let rungs = [
2009                    (any_active, &mut active),
2010                    (any_hover, &mut hover),
2011                    (any_focus_visible, &mut focus_visible),
2012                    (any_focus, &mut focus),
2013                    (any_focus_within, &mut focus_within),
2014                ];
2015                for (index, (seen, bucket)) in rungs.into_iter().enumerate() {
2016                    if !seen {
2017                        continue;
2018                    }
2019                    let (mut scratch, mut quiet) = (extras.clone(), Vec::new());
2020                    rung_outline[index].refine(&$half.outline);
2021                    $half.apply(
2022                        state_vars[index].as_ref().unwrap_or(&vars),
2023                        env,
2024                        rung_font[index].unwrap_or(font_size),
2025                        parent_font_size,
2026                        &rung_faces[index],
2027                        parent_font,
2028                        bucket,
2029                        &mut scratch,
2030                        &mut quiet,
2031                    );
2032                }
2033                for (_, bucket) in group.buckets_mut() {
2034                    let (mut scratch, mut quiet) = (extras.clone(), Vec::new());
2035                    $half.apply(
2036                        &vars,
2037                        env,
2038                        font_size,
2039                        parent_font_size,
2040                        &computed_font,
2041                        parent_font,
2042                        bucket,
2043                        &mut scratch,
2044                        &mut quiet,
2045                    );
2046                }
2047            }};
2048        }
2049        for important_pass in [false, true] {
2050            for r in &matched {
2051                if let Some(decoration) = held_decoration.take() {
2052                    extras.decoration = decoration;
2053                }
2054                if let Some(which) = r.pseudo {
2055                    if let Some(index) = which.control_index() {
2056                        let fold = controls[index].get_or_insert_with(ControlFold::default);
2057                        let rung = rung_of(r.states);
2058                        if let Some(rung) = rung {
2059                            fold.states[rung] = true;
2060                        }
2061                        for slot_index in 0..=STATE_RUNGS {
2062                            if rung.is_some_and(|rung| slot_index != rung + 1) {
2063                                continue;
2064                            }
2065                            let vars = if slot_index == 0 {
2066                                &vars
2067                            } else {
2068                                state_vars[slot_index - 1].as_ref().unwrap_or(&vars)
2069                            };
2070                            let slot = &mut fold.slots[slot_index];
2071                            slot.1.refine(if important_pass {
2072                                &r.important_extras
2073                            } else {
2074                                &r.normal_extras
2075                            });
2076                            r.half(important_pass).apply(
2077                                vars,
2078                                env,
2079                                font_size,
2080                                font_size,
2081                                &computed_font,
2082                                &computed_font,
2083                                &mut slot.0,
2084                                &mut slot.1,
2085                                diagnostics,
2086                            );
2087                        }
2088                        continue;
2089                    }
2090                    let (slot, seen) = match which {
2091                        PseudoElement::Before => (&mut before, &mut any_before),
2092                        PseudoElement::After => (&mut after, &mut any_after),
2093                        PseudoElement::Placeholder => (&mut placeholder, &mut any_placeholder),
2094                        PseudoElement::Selection => (&mut selection, &mut any_selection),
2095                        PseudoElement::FileSelectorButton => {
2096                            (&mut file_button, &mut any_file_button)
2097                        }
2098                        _ => unreachable!("control pseudo-elements handled above"),
2099                    };
2100                    *seen = true;
2101                    slot.1.refine(if important_pass {
2102                        &r.important_extras
2103                    } else {
2104                        &r.normal_extras
2105                    });
2106                    r.half(important_pass).apply(
2107                        &vars,
2108                        env,
2109                        font_size,
2110                        font_size,
2111                        &computed_font,
2112                        &computed_font,
2113                        &mut slot.0,
2114                        &mut slot.1,
2115                        diagnostics,
2116                    );
2117                    continue;
2118                }
2119                // `border-radius: inherit` is filled into the base after the cascade, so only a
2120                // base rule may say which corners inherit.
2121                let state_rule = r.states != 0 || r.ancestor.is_some();
2122                // Nor may a state rule's `text-decoration-*` reach the base decoration, which is
2123                // the only one the folded values are applied to.
2124                if state_rule {
2125                    held_decoration = Some(extras.decoration);
2126                }
2127                let radius_inherit = extras.radius_inherit;
2128                let svg_before = state_rule.then(|| svg_base(&extras));
2129                extras.refine(if important_pass {
2130                    &r.important_extras
2131                } else {
2132                    &r.normal_extras
2133                });
2134                if state_rule {
2135                    keep_base_radius_inherit(&mut extras, radius_inherit, diagnostics);
2136                }
2137                if let Some(before) = svg_before {
2138                    keep_base_svg_paint(&mut extras, before, diagnostics);
2139                }
2140                let half = r.half(important_pass);
2141                if half.is_empty() {
2142                    continue;
2143                }
2144                if let Some(a) = r.ancestor {
2145                    let Some(key) = nearest_group_ancestor(&node, &r.selector, a.offset) else {
2146                        continue;
2147                    };
2148                    let Some(bucket) = group.bucket(a.states, key) else {
2149                        continue;
2150                    };
2151                    let svg_before = svg_base(&extras);
2152                    half.apply(
2153                        &vars,
2154                        env,
2155                        font_size,
2156                        parent_font_size,
2157                        &computed_font,
2158                        parent_font,
2159                        bucket,
2160                        &mut extras,
2161                        diagnostics,
2162                    );
2163                    if half.font_relative() {
2164                        keep_base_radius_inherit(&mut extras, radius_inherit, diagnostics);
2165                    }
2166                    keep_base_svg_paint(&mut extras, svg_before, diagnostics);
2167                    continue;
2168                }
2169                let rung = rung_of(r.states);
2170                let bucket = match rung {
2171                    None => &mut base,
2172                    Some(0) => {
2173                        any_active = true;
2174                        &mut active
2175                    }
2176                    Some(1) => {
2177                        any_hover = true;
2178                        &mut hover
2179                    }
2180                    Some(2) => {
2181                        any_focus_visible = true;
2182                        &mut focus_visible
2183                    }
2184                    Some(3) => {
2185                        any_focus = true;
2186                        &mut focus
2187                    }
2188                    _ => {
2189                        any_focus_within = true;
2190                        &mut focus_within
2191                    }
2192                };
2193                // `hover:shadow-lg` sets and reads `--tw-shadow` in one `:hover` rule;
2194                // `focus-visible:ring-2` does the same one rung over, and the two must not see each
2195                // other.
2196                if let Some(index) = rung {
2197                    rung_outline[index].refine(&half.outline);
2198                }
2199                let scope = rung.and_then(|i| state_vars[i].as_ref()).unwrap_or(&vars);
2200                let basis = rung.and_then(|i| rung_font[i]).unwrap_or(font_size);
2201                let radius_inherit = extras.radius_inherit;
2202                let svg_before = rung.is_some().then(|| svg_base(&extras));
2203                half.apply(
2204                    scope,
2205                    env,
2206                    basis,
2207                    parent_font_size,
2208                    rung.map_or(&computed_font, |index| &rung_faces[index]),
2209                    parent_font,
2210                    bucket,
2211                    &mut extras,
2212                    diagnostics,
2213                );
2214                if rung.is_some() && half.font_relative() {
2215                    keep_base_radius_inherit(&mut extras, radius_inherit, diagnostics);
2216                }
2217                if let Some(before) = svg_before {
2218                    keep_base_svg_paint(&mut extras, before, diagnostics);
2219                }
2220                if rung.is_none() {
2221                    over_state_buckets!(half);
2222                }
2223            }
2224            if let Some(decoration) = held_decoration.take() {
2225                extras.decoration = decoration;
2226            }
2227            if let Some((half, inline_extras)) =
2228                inline.and_then(|i| Half::of_inline_at(i, important_pass))
2229            {
2230                half.apply(
2231                    &vars,
2232                    env,
2233                    font_size,
2234                    parent_font_size,
2235                    &computed_font,
2236                    parent_font,
2237                    &mut base,
2238                    &mut extras,
2239                    diagnostics,
2240                );
2241                extras.refine(inline_extras);
2242                over_state_buckets!(half);
2243            }
2244        }
2245        let mut transition_components = transition::Collector::default();
2246        for important in [false, true] {
2247            for rule in &matched {
2248                if rule.pseudo.is_some() || rule.states != 0 || rule.ancestor.is_some() {
2249                    continue;
2250                }
2251                let declarations = if important {
2252                    &rule.important_transition_declarations
2253                } else {
2254                    &rule.normal_transition_declarations
2255                };
2256                if let Some(declarations) = declarations {
2257                    transition_components.merge(declarations);
2258                }
2259                let patch = if important {
2260                    &rule.important_animation_patch
2261                } else {
2262                    &rule.normal_animation_patch
2263                };
2264                if let Some(patch) = patch {
2265                    patch.apply_over(&mut animation_patch);
2266                }
2267            }
2268            if let Some(inline) = inline {
2269                if inline.normal_motion.is_some() || inline.important_motion.is_some() {
2270                    let motion = if important {
2271                        &inline.important_motion
2272                    } else {
2273                        &inline.normal_motion
2274                    };
2275                    if let Some(motion) = motion {
2276                        if let Some(declarations) = &motion.transitions {
2277                            transition_components.merge(declarations);
2278                        }
2279                        if let Some(patch) = &motion.animations {
2280                            patch.apply_over(&mut animation_patch);
2281                        }
2282                    }
2283                } else if !important {
2284                    if let Some(list) = &inline.transitions {
2285                        transition_components.merge(&transition::Collector::from_specs(list));
2286                    }
2287                    if let Some(list) = &inline.animations {
2288                        animations = Some(list.clone());
2289                        if let Some(patch) =
2290                            keyframes::AnimationCollector::from_specs(list).finish().1
2291                        {
2292                            patch.apply_over(&mut animation_patch);
2293                        }
2294                    }
2295                    if let Some(patch) = &inline.animation_patch {
2296                        patch.apply_over(&mut animation_patch);
2297                    }
2298                }
2299            }
2300        }
2301        if let Some(list) = transition_components.finish() {
2302            transitions = Some(Rc::new(list));
2303        }
2304
2305        let base_font_relative = matched
2306            .iter()
2307            .filter(|r| r.pseudo.is_none() && r.ancestor.is_none() && r.states == 0)
2308            .any(|r| r.half(false).font_relative() || r.half(true).font_relative())
2309            || inline.is_some_and(|i| Half::of_inline(i).font_relative());
2310        if base_font_relative {
2311            let rungs = [
2312                &mut active,
2313                &mut hover,
2314                &mut focus_visible,
2315                &mut focus,
2316                &mut focus_within,
2317            ];
2318            for (i, bucket) in rungs.into_iter().enumerate() {
2319                let size = rung_font[i].unwrap_or(font_size);
2320                if size == font_size && rung_faces[i] == computed_font {
2321                    continue;
2322                }
2323                let mut again = StyleRefinement::default();
2324                let mut scratch = Extras::default();
2325                let mut quiet = Vec::new();
2326                for important_pass in [false, true] {
2327                    for r in matched
2328                        .iter()
2329                        .filter(|r| r.pseudo.is_none() && r.ancestor.is_none() && r.states == 0)
2330                    {
2331                        r.half(important_pass).apply(
2332                            &vars,
2333                            env,
2334                            size,
2335                            parent_font_size,
2336                            &rung_faces[i],
2337                            parent_font,
2338                            &mut again,
2339                            &mut scratch,
2340                            &mut quiet,
2341                        );
2342                    }
2343                }
2344                if let Some(inline) = inline {
2345                    Half::of_inline(inline).apply(
2346                        &vars,
2347                        env,
2348                        size,
2349                        parent_font_size,
2350                        &rung_faces[i],
2351                        parent_font,
2352                        &mut again,
2353                        &mut scratch,
2354                        &mut quiet,
2355                    );
2356                }
2357                again.refine(bucket);
2358                *bucket = again;
2359            }
2360        }
2361        if group.conflict {
2362            diagnostics.push(
2363                "this element is styled by rules on the same state of TWO different ancestors \
2364                 (`group-hover:`, `.menu:focus .item`) — an element follows one ancestor per \
2365                 state, so only the first (most specific) one applies. Give the outer group its \
2366                 own named variant (`group//name` + `group-hover/name:`) on a different element"
2367                    .to_string(),
2368            );
2369        }
2370        if let (Some(t0), Some(t1), Some(t2)) = (t0, t1, t2) {
2371            let ms = |a: std::time::Instant, b: std::time::Instant| {
2372                b.saturating_duration_since(a).as_secs_f32() * 1000.0
2373            };
2374            perf::note_node(
2375                tested,
2376                ms(t0, t1),
2377                ms(t1, t2),
2378                ms(t2, std::time::Instant::now()),
2379            );
2380            perf::note_split(by_bucket, matched.len());
2381        }
2382        if let Some(ring) = base.vn_outline {
2383            let rungs = [
2384                &mut active,
2385                &mut hover,
2386                &mut focus_visible,
2387                &mut focus,
2388                &mut focus_within,
2389            ];
2390            for (index, bucket) in rungs.into_iter().enumerate() {
2391                if let Some(own) = bucket.vn_outline.as_mut() {
2392                    rung_outline[index].inherit_from(ring, own);
2393                }
2394            }
2395        }
2396        // Every rung gets the same value: `color` itself is not in gpui's state ladder, so a
2397        // `:hover` rule cannot change what `currentColor` means.
2398        let effective_color = base.text.color.or(parent_color);
2399        let own_current = effective_color.unwrap_or_else(gpui::black);
2400        if current_color.read() && guessed.is_none() && own_current != parent_current {
2401            drop(current_color);
2402            OWN_COLOR_GUESS.with(|g| g.set(Some(own_current)));
2403            return self.compute_node_with_font(
2404                node,
2405                inline,
2406                parent_vars,
2407                parent_color,
2408                parent_font_size,
2409                parent_font,
2410                env,
2411                diagnostics,
2412            );
2413        }
2414        if extras.current_color != mapper::CurrentColorTargets::default()
2415            || [
2416                &base,
2417                &hover,
2418                &active,
2419                &focus,
2420                &focus_visible,
2421                &focus_within,
2422            ]
2423            .iter()
2424            .any(|refinement| mapper::border_needs_current_color(refinement))
2425        {
2426            let value = effective_color.unwrap_or_else(gpui::black);
2427            let targets = extras.current_color;
2428            for refinement in [
2429                Some(&mut base),
2430                any_hover.then_some(&mut hover),
2431                any_active.then_some(&mut active),
2432                any_focus.then_some(&mut focus),
2433                any_focus_visible.then_some(&mut focus_visible),
2434                any_focus_within.then_some(&mut focus_within),
2435            ]
2436            .into_iter()
2437            .flatten()
2438            {
2439                mapper::apply_current_color(refinement, targets, value);
2440            }
2441        }
2442        for (_, refinement) in group.buckets_mut() {
2443            if mapper::border_needs_current_color(refinement) {
2444                let color = refinement
2445                    .text
2446                    .color
2447                    .or(effective_color)
2448                    .unwrap_or_else(gpui::black);
2449                mapper::apply_current_color(refinement, CurrentColorTargets::default(), color);
2450            }
2451        }
2452        for (refinement, own) in [&mut before, &mut after] {
2453            if own.current_color != CurrentColorTargets::default()
2454                || mapper::border_needs_current_color(refinement)
2455            {
2456                let color = refinement
2457                    .text
2458                    .color
2459                    .or(effective_color)
2460                    .unwrap_or_else(gpui::black);
2461                mapper::apply_current_color(refinement, own.current_color, color);
2462            }
2463        }
2464        if let Some(offset) = extras.underline_offset {
2465            for refinement in [
2466                Some(&mut base),
2467                any_hover.then_some(&mut hover),
2468                any_active.then_some(&mut active),
2469                any_focus.then_some(&mut focus),
2470                any_focus_visible.then_some(&mut focus_visible),
2471                any_focus_within.then_some(&mut focus_within),
2472            ]
2473            .into_iter()
2474            .flatten()
2475            {
2476                if let Some(underline) = refinement.text.underline.as_mut() {
2477                    underline.offset = gpui::px(offset);
2478                }
2479            }
2480        }
2481        extras.decoration.apply(&mut base.text);
2482        for (refinement, own) in [
2483            &mut before,
2484            &mut after,
2485            &mut placeholder,
2486            &mut selection,
2487            &mut file_button,
2488        ] {
2489            own.decoration.apply(&mut refinement.text);
2490        }
2491        mapper::compute_overflow(&mut base, &mut extras);
2492        mapper::apply_size_containment(&mut base, &extras);
2493        mapper::compute_overflow(&mut before.0, &mut before.1);
2494        mapper::compute_overflow(&mut after.0, &mut after.1);
2495
2496        let mut states = ComputedStates {
2497            base: Rc::new(base),
2498            hover: any_hover.then(|| Rc::new(hover)),
2499            active: any_active.then(|| Rc::new(active)),
2500            focus: any_focus.then(|| Rc::new(focus)),
2501            focus_visible: any_focus_visible.then(|| Rc::new(focus_visible)),
2502            focus_within: any_focus_within.then(|| Rc::new(focus_within)),
2503            group_hover: group.hover.map(|(key, r)| (key, Rc::new(r))),
2504            group_active: group.active.map(|(key, r)| (key, Rc::new(r))),
2505            group_focus: GroupFocus::of(group.focus, group.focus_visible, group.focus_within),
2506            transitions: transitions.unwrap_or_default(),
2507            animations: {
2508                if let Some(list) = animation_patch.computed_list() {
2509                    Rc::new(list)
2510                } else {
2511                    let list = animations.unwrap_or_default();
2512                    if animation_patch.is_empty() || list.is_empty() {
2513                        list
2514                    } else {
2515                        let mut patched = (*list).clone();
2516                        for spec in patched.iter_mut() {
2517                            animation_patch.apply(spec);
2518                        }
2519                        Rc::new(patched)
2520                    }
2521                }
2522            },
2523            extras,
2524            before: any_before
2525                .then(|| before.1.content.clone())
2526                .flatten()
2527                .map(|content| {
2528                    Rc::new(PseudoBox {
2529                        content,
2530                        style: Rc::new(before.0),
2531                        extras: before.1,
2532                    })
2533                }),
2534            after: any_after
2535                .then(|| after.1.content.clone())
2536                .flatten()
2537                .map(|content| {
2538                    Rc::new(PseudoBox {
2539                        content,
2540                        style: Rc::new(after.0),
2541                        extras: after.1,
2542                    })
2543                }),
2544            placeholder: any_placeholder.then(|| Rc::new(placeholder.0)),
2545            selection: any_selection.then(|| Rc::new(selection.0)),
2546            file_selector_button: any_file_button.then(|| Rc::new(file_button.0)),
2547            range_track: controls[0].take().map(ControlFold::finish),
2548            range_thumb: controls[1].take().map(ControlFold::finish),
2549            color_swatch: controls[2].take().map(ControlFold::finish),
2550            color_swatch_wrapper: controls[3].take().map(ControlFold::finish),
2551            vars,
2552            custom_animation: None,
2553            color: effective_color,
2554            font_size,
2555            computed_font,
2556        };
2557        let animated_registrations: Vec<_> = registrations
2558            .into_iter()
2559            .filter(|registration| {
2560                states.animations.iter().any(|animation| {
2561                    self.keyframes(&animation.name, env).is_some_and(|frames| {
2562                        frames.steps.iter().any(|step| {
2563                            step.custom.as_ref().is_some_and(|declarations| {
2564                                declarations
2565                                    .iter()
2566                                    .any(|(name, _)| name == &registration.name)
2567                            })
2568                        })
2569                    })
2570                })
2571            })
2572            .collect();
2573        if !animated_registrations.is_empty() {
2574            states.custom_animation = Some(Rc::new(CustomAnimationContext::new(
2575                animated_registrations,
2576                &states,
2577                &matched,
2578                inline,
2579                *env,
2580                parent_font_size,
2581                parent_font,
2582            )));
2583        }
2584        if let Some(key) = share_key {
2585            share::insert(key, &states);
2586        }
2587        states
2588    }
2589}
2590
2591impl Engine {
2592    fn collect_keyframes(
2593        &mut self,
2594        rule: &lightningcss::rules::keyframes::KeyframesRule<'_>,
2595        condition: Option<u32>,
2596    ) {
2597        use lightningcss::rules::keyframes::{KeyframeSelector, KeyframesName};
2598        let name: Box<str> = match &rule.name {
2599            KeyframesName::Ident(i) => i.0.as_ref().into(),
2600            KeyframesName::Custom(c) => c.as_ref().into(),
2601        };
2602        let mut steps: Vec<keyframes::Keyframe> = Vec::new();
2603        for frame in &rule.keyframes {
2604            let (converted, viewport) =
2605                mapper::noting_viewport_units(|| mapper::convert_block(&frame.declarations));
2606            self.viewport_unkept |= viewport;
2607            if let Some(list) = &converted.diagnostics {
2608                for d in list.iter() {
2609                    mapper::once(&mut self.diagnostics, d.clone());
2610                }
2611            }
2612            let mut style = StyleRefinement::default();
2613            let mut any = false;
2614            if let Some(r) = &converted.normal {
2615                style.refine(r);
2616                any = true;
2617            }
2618            if let Some(r) = &converted.important {
2619                style.refine(r);
2620                any = true;
2621            }
2622            let easing = converted
2623                .normal_animation_patch
2624                .or(converted.important_animation_patch)
2625                .and_then(|p| p.easing);
2626            // A declaration whose value referenced `var()` or `env()` cannot be mapped HERE: a
2627            // `@keyframes` block is document-scoped and a custom property belongs to an element.
2628            let dynamic = match (converted.normal_dynamic, converted.important_dynamic) {
2629                (None, None) => None,
2630                (Some(only), None) | (None, Some(only)) => Some(only),
2631                (Some(normal), Some(important)) => {
2632                    let mut all = (*normal).clone();
2633                    all.extend(important.iter().cloned());
2634                    Some(Rc::new(all))
2635                }
2636            };
2637            let custom = converted.normal_custom;
2638            if !any && easing.is_none() && dynamic.is_none() && custom.is_none() {
2639                continue;
2640            }
2641            let style = Rc::new(style);
2642            for selector in &frame.selectors {
2643                let offset = match selector {
2644                    KeyframeSelector::From => 0.0,
2645                    KeyframeSelector::To => 1.0,
2646                    KeyframeSelector::Percentage(p) => p.0,
2647                    KeyframeSelector::TimelineRangePercentage(_) => {
2648                        mapper::once(
2649                            &mut self.diagnostics,
2650                            format!(
2651                                "a named timeline range in @keyframes {name} is not supported                                  (v1) — that keyframe was dropped"
2652                            ),
2653                        );
2654                        continue;
2655                    }
2656                };
2657                steps.push(keyframes::Keyframe {
2658                    offset: offset.clamp(0.0, 1.0),
2659                    easing,
2660                    style: style.clone(),
2661                    dynamic: dynamic.clone(),
2662                    custom: custom.clone(),
2663                });
2664            }
2665        }
2666        steps.sort_by(|a, b| a.offset.total_cmp(&b.offset));
2667        let dynamic = steps.iter().any(|s| s.dynamic.is_some());
2668        // Appended, not replaced: "a later block with the same name wins" is still the rule, but
2669        // only among the blocks that are DECLARED — and a media-scoped one is declared per window.
2670        self.keyframes
2671            .entry(name)
2672            .or_default()
2673            .push(KeyframesBlock {
2674                condition,
2675                block: Rc::new(keyframes::Keyframes { steps, dynamic }),
2676            });
2677    }
2678}
2679
2680fn at_rule_ignored(rule: &CssRule<'_>, diagnostics: &mut Vec<String>) {
2681    let msg = match rule {
2682        CssRule::FontFace(_) => return,
2683        other => format!("at-rule ignored (v1): {other:?}")
2684            .chars()
2685            .take(120)
2686            .collect(),
2687    };
2688    mapper::once(diagnostics, msg);
2689}
2690
2691/// `CSS.supports(conditionText)`: a `@supports` condition, or a bare declaration as browsers also take.
2692pub fn supports_condition_text(text: &str) -> bool {
2693    use lightningcss::rules::supports::SupportsCondition;
2694    use lightningcss::traits::Parse;
2695    match SupportsCondition::parse_string(text) {
2696        Ok(c) => supports_condition(&c),
2697        Err(_) => SupportsCondition::parse_string(&format!("({text})"))
2698            .is_ok_and(|c| supports_condition(&c)),
2699    }
2700}
2701
2702fn supports_condition(condition: &lightningcss::rules::supports::SupportsCondition<'_>) -> bool {
2703    use lightningcss::rules::supports::SupportsCondition as C;
2704    use lightningcss::vendor_prefix::VendorPrefix;
2705    match condition {
2706        C::Not(inner) => !supports_condition(inner),
2707        C::And(list) => list.iter().all(supports_condition),
2708        C::Or(list) => list.iter().any(supports_condition),
2709        // `(-webkit-x: v) or (x: v)` arrives as one declaration carrying both prefixes.
2710        C::Declaration { property_id, value } => {
2711            let name = property_id.name();
2712            let prefix = property_id.prefix();
2713            [
2714                (VendorPrefix::None, ""),
2715                (VendorPrefix::WebKit, "-webkit-"),
2716                (VendorPrefix::Moz, "-moz-"),
2717                (VendorPrefix::Ms, "-ms-"),
2718                (VendorPrefix::O, "-o-"),
2719            ]
2720            .into_iter()
2721            .filter(|(p, _)| prefix.contains(*p) || (*p == VendorPrefix::None && prefix.is_empty()))
2722            .any(|(_, spelling)| catalog::supports(&format!("{spelling}{name}"), value))
2723        }
2724        C::Selector(text) => {
2725            if text.contains(['{', '}']) {
2726                return false;
2727            }
2728            let src = format!("{text}{{color:red}}");
2729            let Ok(sheet) = StyleSheet::parse(&src, ParserOptions::default()) else {
2730                return false;
2731            };
2732            let mut probe = Vec::new();
2733            sheet.rules.0.iter().all(|rule| match rule {
2734                CssRule::Style(style) => style.selectors.0.iter().all(|sel| {
2735                    // Two calls, not one rebinding: `Selector` is invariant in its lifetime.
2736                    fn runs(sel: &Selector<'_>, probe: &mut Vec<String>) -> bool {
2737                        classify_states(sel, probe).is_some()
2738                            && probe_runnable(sel)
2739                            && audit_selector(sel, probe)
2740                    }
2741                    if has::present(&sel_text(sel)) {
2742                        match has::rewrite(&sel_text(sel)).and_then(|t| reparse_selector(&t)) {
2743                            Some(s) => runs(s, &mut probe),
2744                            None => false,
2745                        }
2746                    } else {
2747                        runs(sel, &mut probe)
2748                    }
2749                }),
2750                _ => false,
2751            })
2752        }
2753        C::Unknown(_) => false,
2754    }
2755}
2756
2757/// `:disabled` / `:checked` / `:enabled` are absent on purpose: the element property is the state,
2758/// so the matcher answers them for real.
2759fn ladder_state(pc: &PseudoClass<'_>) -> u8 {
2760    match pc {
2761        PseudoClass::Hover => STATE_HOVER,
2762        PseudoClass::Active => STATE_ACTIVE,
2763        PseudoClass::Focus => STATE_FOCUS,
2764        PseudoClass::FocusVisible => STATE_FOCUS_VISIBLE,
2765        PseudoClass::FocusWithin => STATE_FOCUS_WITHIN,
2766        _ => 0,
2767    }
2768}
2769
2770#[derive(Clone, Copy, Debug, PartialEq, Eq)]
2771struct AncestorState {
2772    offset: usize,
2773    states: u8,
2774}
2775
2776/// The nearest ancestor is exact, not an approximation: the rule applies while any matching
2777/// ancestor is hovered, and gpui's `GroupHitboxes` returns the innermost group of that name.
2778fn nearest_group_ancestor<D: MatchDom>(
2779    node: &D,
2780    selector: &Selector<'static>,
2781    offset: usize,
2782) -> Option<u64> {
2783    let mut cursor = node.parent();
2784    // A corrupt parent chain must not hang the cascade (same bound the tree's own ancestor walk
2785    // uses).
2786    for _ in 0..1024 {
2787        let anc = cursor?;
2788        let el = element::El(anc);
2789        let mut ctx: MatchingContext<'_, '_, element::Impl> =
2790            MatchingContext::new(MatchingMode::Normal, None, None, QuirksMode::NoQuirks);
2791        if matches_selector(selector, offset, None, &el, &mut ctx, &mut |_, _| {}) {
2792            return Some(anc.key());
2793        }
2794        cursor = anc.parent();
2795    }
2796    None
2797}
2798
2799#[derive(Default)]
2800struct GroupFold {
2801    hover: Option<(u64, StyleRefinement)>,
2802    active: Option<(u64, StyleRefinement)>,
2803    focus: Option<(u64, StyleRefinement)>,
2804    focus_visible: Option<(u64, StyleRefinement)>,
2805    focus_within: Option<(u64, StyleRefinement)>,
2806    conflict: bool,
2807}
2808
2809impl GroupFold {
2810    fn buckets_mut(&mut self) -> impl Iterator<Item = &mut (u64, StyleRefinement)> {
2811        [
2812            &mut self.hover,
2813            &mut self.active,
2814            &mut self.focus,
2815            &mut self.focus_visible,
2816            &mut self.focus_within,
2817        ]
2818        .into_iter()
2819        .flatten()
2820    }
2821
2822    fn bucket(&mut self, states: u8, key: u64) -> Option<&mut StyleRefinement> {
2823        let conflict = &mut self.conflict;
2824        let slot = match rung_of(states) {
2825            Some(0) => &mut self.active,
2826            Some(1) => &mut self.hover,
2827            Some(2) => &mut self.focus_visible,
2828            Some(3) => &mut self.focus,
2829            _ => &mut self.focus_within,
2830        };
2831        match slot.as_ref().map(|(owner, _)| *owner) {
2832            Some(owner) if owner != key => {
2833                *conflict = true;
2834                return None;
2835            }
2836            Some(_) => {}
2837            None => *slot = Some((key, StyleRefinement::default())),
2838        }
2839        slot.as_mut().map(|(_, r)| r)
2840    }
2841}
2842
2843pub(crate) fn classify_states(
2844    sel: &Selector<'_>,
2845    diagnostics: &mut Vec<String>,
2846) -> Option<(u8, Option<AncestorState>)> {
2847    let mut states = 0u8;
2848    let mut ancestor: Option<AncestorState> = None;
2849    let mut iter = sel.iter();
2850    let mut compound_start = 0usize;
2851    let mut compound_len = 0usize;
2852    for component in &mut iter {
2853        compound_len += 1;
2854        if let Component::NonTSPseudoClass(pc) = component {
2855            states |= ladder_state(pc);
2856        }
2857    }
2858    if states.count_ones() > 1 {
2859        mapper::once(
2860            diagnostics,
2861            format!(
2862                "a selector naming several interaction states at once cannot be an AND in gpui's \
2863                 state ladder — it was installed on the strongest rung it names \
2864                 (active > hover > focus-visible > focus): {}",
2865                sel_text(sel)
2866            ),
2867        );
2868    }
2869    // Past the first compound, a state pseudo is an ancestor-state rule, except across a
2870    // pseudo-element boundary: in `.nav:hover::after` the `:hover` is in the next sequence but on
2871    // the same element.
2872    let mut same_element = true;
2873    while let Some(combinator) = iter.next_sequence() {
2874        compound_start += compound_len + 1;
2875        compound_len = 0;
2876        same_element &= matches!(
2877            combinator,
2878            parcel_selectors::parser::Combinator::PseudoElement
2879                | parcel_selectors::parser::Combinator::SlotAssignment
2880                | parcel_selectors::parser::Combinator::Part
2881        );
2882        let sibling = matches!(
2883            combinator,
2884            parcel_selectors::parser::Combinator::NextSibling
2885                | parcel_selectors::parser::Combinator::LaterSibling
2886        );
2887        let mut here = 0u8;
2888        for component in &mut iter {
2889            compound_len += 1;
2890            if let Component::NonTSPseudoClass(pc) = component {
2891                here |= ladder_state(pc);
2892            }
2893        }
2894        if here == 0 {
2895            continue;
2896        }
2897        if same_element {
2898            states |= here;
2899            continue;
2900        }
2901        if sibling {
2902            diagnostics.push(format!(
2903                "a sibling-state selector (`+` / `~` with `:hover` on the LEFT) has nothing to \
2904                 hang on — gpui's group mechanism keys off an ANCESTOR's hitbox. The rule was \
2905                 dropped: {}",
2906                sel_text(sel)
2907            ));
2908            return None;
2909        }
2910        if ancestor.is_some() {
2911            mapper::once(
2912                diagnostics,
2913                format!(
2914                    "two ancestor-state compounds in one selector — only the INNERMOST is \
2915                     honoured, because gpui gives an element one group to watch: {}",
2916                    sel_text(sel)
2917                ),
2918            );
2919            continue;
2920        }
2921        ancestor = Some(AncestorState {
2922            offset: compound_start,
2923            states: here,
2924        });
2925    }
2926    Some((states, ancestor))
2927}
2928
2929/// `::before` / `::after` give the generated box; any other pseudo-element styles part of a box and
2930/// is `None`. Returns `false` when the rule must be dropped, so no rule compiles into an entry that
2931/// never matches without saying so.
2932fn pseudo_box(
2933    pe: &<element::Impl as parcel_selectors::parser::SelectorImpl<'_>>::PseudoElement,
2934) -> Option<PseudoElement> {
2935    use lightningcss::selector::PseudoElement as PE;
2936    match pe {
2937        PE::Before => Some(PseudoElement::Before),
2938        PE::After => Some(PseudoElement::After),
2939        PE::Placeholder(_) => Some(PseudoElement::Placeholder),
2940        PE::Selection(_) => Some(PseudoElement::Selection),
2941        PE::FileSelectorButton(_) => Some(PseudoElement::FileSelectorButton),
2942        PE::Custom { name } => match name.as_ref() {
2943            "-webkit-slider-runnable-track" | "-moz-range-track" => Some(PseudoElement::RangeTrack),
2944            "-webkit-slider-thumb" | "-moz-range-thumb" => Some(PseudoElement::RangeThumb),
2945            "-webkit-color-swatch" | "-moz-color-swatch" => Some(PseudoElement::ColorSwatch),
2946            "-webkit-color-swatch-wrapper" => Some(PseudoElement::ColorSwatchWrapper),
2947            _ => None,
2948        },
2949        _ => None,
2950    }
2951}
2952
2953/// The vendor part is a CSS target, not a DOM descendant. LightningCSS calls it unknown and parcel
2954/// stores it in the input's compound, so the stateless pseudo mode cannot consume it.
2955fn control_origin_selector(sel: &Selector<'_>) -> Option<Selector<'static>> {
2956    use lightningcss::selector::PseudoElement as PE;
2957    use lightningcss::traits::IntoOwned as _;
2958    let PE::Custom { name } = sel.pseudo_element()? else {
2959        return None;
2960    };
2961    let mut text = sel_text(sel);
2962    let marker = format!("::{name}");
2963    let start = text.rfind(&marker)?;
2964    text.replace_range(start..start + marker.len(), "");
2965    if text.trim().is_empty() || text.ends_with(char::is_whitespace) {
2966        text.push('*');
2967    }
2968    let source = format!("{text}{{color:red}}");
2969    let parsed = StyleSheet::parse(&source, ParserOptions::default()).ok()?;
2970    let CssRule::Style(style) = parsed.rules.0.first()? else {
2971        return None;
2972    };
2973    Some(style.selectors.0.first()?.clone().into_owned())
2974}
2975
2976fn never_matches_anywhere(
2977    pe: &<element::Impl as parcel_selectors::parser::SelectorImpl<'_>>::PseudoElement,
2978) -> bool {
2979    use lightningcss::selector::PseudoElement as PE;
2980    match pe {
2981        PE::Backdrop(_) => true,
2982        PE::WebKitScrollbar(_) => false,
2983        PE::Custom { name } => {
2984            let name = name.as_ref();
2985            name.starts_with("-webkit-") || name.starts_with("-moz-") || name.starts_with("-ms-")
2986        }
2987        _ => false,
2988    }
2989}
2990
2991fn is_webkit_scrollbar(
2992    pe: &<element::Impl as parcel_selectors::parser::SelectorImpl<'_>>::PseudoElement,
2993) -> bool {
2994    use lightningcss::selector::PseudoElement as PE;
2995    matches!(pe, PE::WebKitScrollbar(_))
2996}
2997
2998pub(crate) fn audit_selector(sel: &Selector<'_>, diagnostics: &mut Vec<String>) -> bool {
2999    audit_components(sel, sel.iter_raw_match_order(), false, false, diagnostics)
3000}
3001
3002fn audit_live_selector(sel: &Selector<'_>, diagnostics: &mut Vec<String>) -> bool {
3003    audit_components(sel, sel.iter_raw_match_order(), false, true, diagnostics)
3004}
3005
3006fn audit_components<'a, 'i>(
3007    sel: &Selector<'i>,
3008    components: impl Iterator<Item = &'a Component<'i, element::Impl>>,
3009    nested: bool,
3010    live: bool,
3011    diagnostics: &mut Vec<String>,
3012) -> bool
3013where
3014    'i: 'a,
3015{
3016    let mut ok = true;
3017    for c in components {
3018        let reason: Option<String> = match c {
3019            Component::NonTSPseudoClass(pc) => {
3020                if nested && !live && ladder_state(pc) != 0 {
3021                    // Outside a functional pseudo an interaction state is a ladder bucket; inside
3022                    // one the matcher has to answer it with a bare yes/no and always says "yes",
3023                    // which silently inverts `:not(:hover)`.
3024                    Some(format!("`:{}` inside :not()/:is()/:where()", pseudo_name(pc)))
3025                } else if ladder_state(pc) == 0 && !matches_from_props(pc) {
3026                    let name = pseudo_name(pc);
3027                    if name.starts_with("-moz-") || name.starts_with("-webkit-") {
3028                        None
3029                    } else {
3030                        Some(format!("the pseudo-class `:{name}`"))
3031                    }
3032                } else {
3033                    None
3034                }
3035            }
3036            Component::PseudoElement(pe) if !nested && pseudo_box(pe).is_some() => None,
3037            Component::PseudoElement(pe) if !nested && never_matches_anywhere(pe) => None,
3038            Component::PseudoElement(pe) if !nested && is_webkit_scrollbar(pe) => Some(
3039                "a `::-webkit-scrollbar*` pseudo-element — Skathi draws overlay scrollbars                  but does not expose them as styleable boxes; use the standard                  `scrollbar-width: auto | thin | none` and `scrollbar-color: <thumb> <track>`,                  which both reach the painter"
3040                    .into(),
3041            ),
3042            Component::PseudoElement(_) => Some(
3043                "a pseudo-element other than `::before` / `::after` / `::placeholder` (nothing here paints part of a box separately from the box)"
3044                    .into(),
3045            ),
3046            // Preflight writes `html, :host { }`; `:host` matches nothing in a browser either, so
3047            // dropping it is exact.
3048            Component::Slotted(_) | Component::Part(_) | Component::Host(_) => None,
3049            Component::Scope => None,
3050            Component::Nesting => Some("an unflattened `&` nesting selector".into()),
3051            Component::Namespace(..) | Component::DefaultNamespace(_) => {
3052                Some("a namespaced selector (`@namespace` is not implemented)".into())
3053            }
3054            Component::AttributeOther(attr) if attr.namespace.is_some() => {
3055                Some("a namespaced attribute selector (`[ns|attr]`)".into())
3056            }
3057            // These two do not merely fail to match — parcel's matcher hits an `unreachable!()` /
3058            // `todo!()` on them and takes the process with it.
3059            Component::Has(_) => Some("`:has()` (the matcher has no implementation)".into()),
3060            Component::NthOf(_) => {
3061                Some("`:nth-child(… of S)` (the matcher has no implementation)".into())
3062            }
3063            Component::Negation(list)
3064            | Component::Where(list)
3065            | Component::Is(list)
3066            | Component::Any(_, list) => {
3067                for inner in list.iter() {
3068                    if !audit_components(inner, inner.iter_raw_match_order(), true, live, diagnostics) {
3069                        ok = false;
3070                    }
3071                }
3072                None
3073            }
3074            _ => None,
3075        };
3076        if let Some(what) = reason {
3077            ok = false;
3078            if !diagnostics.iter().any(|d| d.starts_with(&what)) {
3079                diagnostics.push(format!(
3080                    "{what} — rules using it can never match and were dropped \
3081                     (first seen in `{}`)",
3082                    sel_text(sel)
3083                ));
3084            }
3085        }
3086    }
3087    ok
3088}
3089
3090fn matches_from_props(pc: &PseudoClass<'_>) -> bool {
3091    match pc {
3092        PseudoClass::Disabled
3093        | PseudoClass::Enabled
3094        | PseudoClass::Checked
3095        | PseudoClass::Indeterminate
3096        | PseudoClass::Fullscreen(_)
3097        | PseudoClass::ActiveViewTransition
3098        | PseudoClass::ActiveViewTransitionType { .. } => true,
3099        PseudoClass::Custom { name } => crate::has::is_marker(name.as_ref()),
3100        _ => false,
3101    }
3102}
3103
3104fn pseudo_name(pc: &PseudoClass<'_>) -> String {
3105    let name = match pc {
3106        PseudoClass::Lang { .. } => "lang()",
3107        PseudoClass::Dir { .. } => "dir()",
3108        PseudoClass::Hover => "hover",
3109        PseudoClass::Active => "active",
3110        PseudoClass::Focus => "focus",
3111        PseudoClass::FocusVisible => "focus-visible",
3112        PseudoClass::FocusWithin => "focus-within",
3113        PseudoClass::Current => "current",
3114        PseudoClass::Past => "past",
3115        PseudoClass::Future => "future",
3116        PseudoClass::Playing => "playing",
3117        PseudoClass::Paused => "paused",
3118        PseudoClass::Seeking => "seeking",
3119        PseudoClass::Buffering => "buffering",
3120        PseudoClass::Stalled => "stalled",
3121        PseudoClass::Muted => "muted",
3122        PseudoClass::VolumeLocked => "volume-locked",
3123        PseudoClass::Fullscreen(_) => "fullscreen",
3124        PseudoClass::Open => "open",
3125        PseudoClass::Closed => "closed",
3126        PseudoClass::Modal => "modal",
3127        PseudoClass::PictureInPicture => "picture-in-picture",
3128        PseudoClass::PopoverOpen => "popover-open",
3129        PseudoClass::Defined => "defined",
3130        PseudoClass::AnyLink(_) => "any-link",
3131        PseudoClass::Link => "link",
3132        PseudoClass::LocalLink => "local-link",
3133        PseudoClass::Target => "target",
3134        PseudoClass::TargetCurrent => "target-current",
3135        PseudoClass::TargetBefore => "target-before",
3136        PseudoClass::TargetAfter => "target-after",
3137        PseudoClass::TargetWithin => "target-within",
3138        PseudoClass::Visited => "visited",
3139        PseudoClass::Enabled => "enabled",
3140        PseudoClass::Disabled => "disabled",
3141        PseudoClass::ReadOnly(_) => "read-only",
3142        PseudoClass::ReadWrite(_) => "read-write",
3143        PseudoClass::PlaceholderShown(_) => "placeholder-shown",
3144        PseudoClass::Default => "default",
3145        PseudoClass::Checked => "checked",
3146        PseudoClass::Indeterminate => "indeterminate",
3147        PseudoClass::Blank => "blank",
3148        PseudoClass::Valid => "valid",
3149        PseudoClass::Invalid => "invalid",
3150        PseudoClass::InRange => "in-range",
3151        PseudoClass::OutOfRange => "out-of-range",
3152        PseudoClass::Required => "required",
3153        PseudoClass::Optional => "optional",
3154        PseudoClass::UserValid => "user-valid",
3155        PseudoClass::UserInvalid => "user-invalid",
3156        PseudoClass::Autofill(_) => "autofill",
3157        PseudoClass::ActiveViewTransition => "active-view-transition",
3158        PseudoClass::ActiveViewTransitionType { .. } => "active-view-transition-type()",
3159        PseudoClass::State { .. } => "state()",
3160        PseudoClass::Local { .. } => "local()",
3161        PseudoClass::Global { .. } => "global()",
3162        PseudoClass::WebKitScrollbar(_) => "-webkit-scrollbar-*",
3163        PseudoClass::Custom { name } => return name.as_ref().to_string(),
3164        PseudoClass::CustomFunction { name, .. } => return format!("{}()", name.as_ref()),
3165    };
3166    name.to_string()
3167}
3168
3169pub(crate) fn probe_runnable(sel: &Selector<'_>) -> bool {
3170    #[derive(Clone, Copy)]
3171    struct Probe;
3172    impl MatchDom for Probe {
3173        fn key(&self) -> u64 {
3174            0
3175        }
3176        fn parent(&self) -> Option<Self> {
3177            None
3178        }
3179        fn prev_sibling(&self) -> Option<Self> {
3180            None
3181        }
3182        fn next_sibling(&self) -> Option<Self> {
3183            None
3184        }
3185        fn has_tag(&self, _: &str) -> bool {
3186            false
3187        }
3188        fn tag_eq(&self, _: &Self) -> bool {
3189            true
3190        }
3191        fn has_class(&self, _: &str) -> bool {
3192            false
3193        }
3194        fn tag_name(&self) -> &str {
3195            ""
3196        }
3197        fn each_class(&self, _: &mut dyn FnMut(&str)) {}
3198        fn has_scope(&self, _: &str) -> bool {
3199            false
3200        }
3201        fn attr(&self, _: &str) -> Option<&str> {
3202            None
3203        }
3204        fn is_empty(&self) -> bool {
3205            true
3206        }
3207        fn is_root(&self) -> bool {
3208            true
3209        }
3210    }
3211    std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| {
3212        let el = element::El(Probe);
3213        let mut ctx: MatchingContext<'_, '_, element::Impl> =
3214            MatchingContext::new(MatchingMode::Normal, None, None, QuirksMode::NoQuirks);
3215        matches_selector(sel, 0, None, &el, &mut ctx, &mut |_, _| {});
3216    }))
3217    .is_ok()
3218}
3219
3220fn extras_names(e: &Extras) -> String {
3221    let mut names: Vec<&str> = Vec::new();
3222    if e.object_fit.is_some() {
3223        names.push("`object-fit`");
3224    }
3225    if e.window_drag.is_some() {
3226        names.push("`window-drag`");
3227    }
3228    if e.window_control.is_some() {
3229        names.push("`--window-control`");
3230    }
3231    names.join(" / ")
3232}
3233
3234/// Leaks, but once per distinct text: recompiles rewrite to the same text and get the same selector
3235/// back.
3236fn reparse_selector(text: &str) -> Option<&'static Selector<'static>> {
3237    if text.contains(['{', '}']) {
3238        return None;
3239    }
3240    if let Some(hit) = REPARSED.with(|r| r.borrow().get(text).copied()) {
3241        return hit;
3242    }
3243    let parsed = (|| {
3244        let source: &'static str = Box::leak(format!("{text}{{color:red}}").into_boxed_str());
3245        let sheet: &'static StyleSheet<'static> = Box::leak(Box::new(
3246            StyleSheet::parse(source, ParserOptions::default()).ok()?,
3247        ));
3248        match sheet.rules.0.first() {
3249            Some(CssRule::Style(style)) => style.selectors.0.first(),
3250            _ => None,
3251        }
3252    })();
3253    REPARSED.with(|r| r.borrow_mut().insert(text.to_string(), parsed));
3254    parsed
3255}
3256
3257fn sel_text(sel: &Selector<'_>) -> String {
3258    use lightningcss::traits::ToCss;
3259    sel.to_css_string(lightningcss::printer::PrinterOptions::default())
3260        .unwrap_or_else(|_| "<selector>".into())
3261}
3262
3263static CAPTURE_RULE_TEXT: std::sync::atomic::AtomicBool = std::sync::atomic::AtomicBool::new(false);
3264
3265/// Turns rule-text capture on (or off) for every sheet compiled AFTER this call — the sheet already
3266/// installed keeps whatever it was compiled with.
3267pub fn set_capture_rule_text(on: bool) {
3268    CAPTURE_RULE_TEXT.store(on, std::sync::atomic::Ordering::Relaxed);
3269}
3270
3271fn capture_rule_text() -> bool {
3272    CAPTURE_RULE_TEXT.load(std::sync::atomic::Ordering::Relaxed)
3273}
3274
3275#[derive(Debug, Clone)]
3276pub struct MatchedRule {
3277    pub selector: String,
3278    pub specificity: u32,
3279    pub order: u32,
3280    pub media: Option<String>,
3281    pub state: &'static str,
3282    pub ancestor_state: bool,
3283    pub pseudo: Option<&'static str>,
3284    pub declarations: Vec<(String, String, bool)>,
3285    pub diagnostics: Vec<String>,
3286}
3287
3288fn state_name(states: u8) -> &'static str {
3289    match states {
3290        0 => "base",
3291        s if s & STATE_ACTIVE != 0 => "active",
3292        s if s & STATE_HOVER != 0 => "hover",
3293        s if s & STATE_FOCUS_VISIBLE != 0 => "focus-visible",
3294        s if s & STATE_FOCUS != 0 => "focus",
3295        _ => "focus-within",
3296    }
3297}
3298
3299impl Engine {
3300    pub fn matched_rules<D: MatchDom>(&self, node: D, env: &Env) -> Vec<MatchedRule> {
3301        let el = element::El(node);
3302        let mut matched: Vec<&RuleEntry> = Vec::new();
3303        self.candidates(&node, &mut |i, _| {
3304            let rule = &self.rules[i as usize];
3305            if let Some(c) = rule.condition {
3306                if !self.conditions[c as usize].eval(env) {
3307                    return;
3308                }
3309            }
3310            let mode = if rule.pseudo.is_some() && rule.control_origin.is_none() {
3311                MatchingMode::ForStatelessPseudoElement
3312            } else {
3313                MatchingMode::Normal
3314            };
3315            let mut ctx: MatchingContext<'_, '_, element::Impl> =
3316                MatchingContext::new(mode, None, None, QuirksMode::NoQuirks);
3317            if matches_selector(
3318                rule.control_origin.as_deref().unwrap_or(&rule.selector),
3319                0,
3320                None,
3321                &el,
3322                &mut ctx,
3323                &mut |_, _| {},
3324            ) && rule
3325                .container
3326                .is_none_or(|q| self.container_queries[q as usize].eval(&Rc::new(Vars::default())))
3327            {
3328                matched.push(rule);
3329            }
3330        });
3331        matched.sort_by_key(|r| (r.specificity, r.order));
3332        matched
3333            .into_iter()
3334            .map(|r| MatchedRule {
3335                selector: sel_text(&r.selector),
3336                specificity: r.specificity,
3337                order: r.order,
3338                media: r.condition.map(|c| self.condition_text[c as usize].clone()),
3339                state: state_name(r.ancestor.map_or(r.states, |a| a.states)),
3340                ancestor_state: r.ancestor.is_some(),
3341                pseudo: r.pseudo.map(|p| match p {
3342                    PseudoElement::Before => "::before",
3343                    PseudoElement::After => "::after",
3344                    PseudoElement::Placeholder => "::placeholder",
3345                    PseudoElement::Selection => "::selection",
3346                    PseudoElement::FileSelectorButton => "::file-selector-button",
3347                    PseudoElement::RangeTrack => "::-webkit-slider-runnable-track",
3348                    PseudoElement::RangeThumb => "::-webkit-slider-thumb",
3349                    PseudoElement::ColorSwatch => "::-webkit-color-swatch",
3350                    PseudoElement::ColorSwatchWrapper => "::-webkit-color-swatch-wrapper",
3351                }),
3352                declarations: r.decls.as_deref().cloned().unwrap_or_default(),
3353                diagnostics: r.diagnostics.as_deref().cloned().unwrap_or_default(),
3354            })
3355            .collect()
3356    }
3357}
3358
3359#[derive(Debug, Default)]
3360pub struct QueryResult {
3361    pub matched: Vec<usize>,
3362    pub warnings: Vec<String>,
3363}
3364
3365/// An unsupported selector is `Err(advisory)`, not a silent empty match. Takes candidates because
3366/// `MatchDom` has no child accessor; a scoped `querySelector` uses `query_all_in`.
3367pub fn query_all<D: MatchDom>(selector: &str, candidates: &[D]) -> Result<QueryResult, String> {
3368    query_all_in(selector, candidates, None)
3369}
3370
3371/// `scope` is the `:scope` root; without it `:scope > div` would ask about the document root.
3372/// `None` matches the document element, as in the cascade.
3373pub fn query_all_in<D: MatchDom>(
3374    selector: &str,
3375    candidates: &[D],
3376    scope: Option<D>,
3377) -> Result<QueryResult, String> {
3378    let sel = selector.trim();
3379    if sel.is_empty() {
3380        return Err("empty selector".into());
3381    }
3382    // The selector is spliced into a one-rule stylesheet to reach exactly the parser the cascade
3383    // uses; `{`/`}` would let it declare rules of its own.
3384    if sel.contains(['{', '}']) {
3385        return Err("a selector cannot contain `{` or `}`".into());
3386    }
3387    let src = format!("{sel}{{color:red}}");
3388    let sheet = StyleSheet::parse(&src, ParserOptions::default())
3389        .map_err(|e| format!("selector parse error: {e}"))?;
3390    let mut diagnostics: Vec<String> = Vec::new();
3391    let mut selectors: Vec<&Selector<'_>> = Vec::new();
3392    for rule in &sheet.rules.0 {
3393        let CssRule::Style(style) = rule else {
3394            return Err(format!("`{sel}` is not a selector"));
3395        };
3396        for s in &style.selectors.0 {
3397            if !probe_runnable(s) {
3398                return Err(format!(
3399                    "selector rejected (matcher cannot run it — :has()/nesting?): {}",
3400                    sel_text(s)
3401                ));
3402            }
3403            if D::LIVE_STATE {
3404                if !audit_live_selector(s, &mut diagnostics) {
3405                    return Err(join_diagnostics(&diagnostics));
3406                }
3407                selectors.push(s);
3408                continue;
3409            }
3410            let (states, ancestor) = match classify_states(s, &mut diagnostics) {
3411                Some(pair) => pair,
3412                None => return Err(join_diagnostics(&diagnostics)),
3413            };
3414            if !audit_selector(s, &mut diagnostics) {
3415                return Err(join_diagnostics(&diagnostics));
3416            }
3417            if states != 0 || ancestor.is_some() {
3418                diagnostics.push(format!(
3419                    "`{}` names an interaction state, and this element view has no live state: \
3420                     `:hover`/`:active`/`:focus`/`:focus-visible`/`:focus-within` match as \
3421                     \"would match when in that state\", so the query is NOT filtered by it",
3422                    sel_text(s)
3423                ));
3424            }
3425            selectors.push(s);
3426        }
3427    }
3428    if selectors.is_empty() {
3429        return Err(format!("`{sel}` matched no selector"));
3430    }
3431    let scope_element = scope.map(|s| {
3432        use parcel_selectors::Element as _;
3433        element::El(s).opaque()
3434    });
3435    let mut matched = Vec::new();
3436    for (i, candidate) in candidates.iter().enumerate() {
3437        let el = element::El(*candidate);
3438        let hit = selectors.iter().any(|s| {
3439            let mut ctx: MatchingContext<'_, '_, element::Impl> =
3440                MatchingContext::new(MatchingMode::Normal, None, None, QuirksMode::NoQuirks);
3441            ctx.scope_element = scope_element;
3442            matches_selector(s, 0, None, &el, &mut ctx, &mut |_, _| {})
3443        });
3444        if hit {
3445            matched.push(i);
3446        }
3447    }
3448    Ok(QueryResult {
3449        matched,
3450        warnings: diagnostics,
3451    })
3452}
3453
3454fn join_diagnostics(diagnostics: &[String]) -> String {
3455    if diagnostics.is_empty() {
3456        "selector rejected".to_string()
3457    } else {
3458        diagnostics.join("; ")
3459    }
3460}
3461
3462#[cfg(test)]
3463mod tests {
3464    use super::*;
3465    use std::time::Duration;
3466
3467    #[derive(Clone, Copy)]
3468    struct Node {
3469        tag: &'static str,
3470        class: &'static str,
3471        attrs: &'static [(&'static str, &'static str)],
3472    }
3473
3474    impl MatchDom for Node {
3475        fn key(&self) -> u64 {
3476            0
3477        }
3478        fn parent(&self) -> Option<Self> {
3479            None
3480        }
3481        fn prev_sibling(&self) -> Option<Self> {
3482            None
3483        }
3484        fn next_sibling(&self) -> Option<Self> {
3485            None
3486        }
3487        fn has_tag(&self, name: &str) -> bool {
3488            self.tag == name
3489        }
3490        fn tag_eq(&self, other: &Self) -> bool {
3491            self.tag == other.tag
3492        }
3493        fn has_class(&self, name: &str) -> bool {
3494            self.class.split_whitespace().any(|c| c == name)
3495        }
3496        fn tag_name(&self) -> &str {
3497            self.tag
3498        }
3499        fn each_class(&self, f: &mut dyn FnMut(&str)) {
3500            for c in self.class.split_whitespace() {
3501                f(c);
3502            }
3503        }
3504        fn has_scope(&self, _: &str) -> bool {
3505            false
3506        }
3507        fn attr(&self, name: &str) -> Option<&str> {
3508            self.attrs.iter().find(|(k, _)| *k == name).map(|(_, v)| *v)
3509        }
3510        fn is_empty(&self) -> bool {
3511            true
3512        }
3513        fn is_root(&self) -> bool {
3514            true
3515        }
3516    }
3517
3518    fn box_node() -> Node {
3519        Node {
3520            tag: "div",
3521            class: "box",
3522            attrs: &[],
3523        }
3524    }
3525
3526    #[test]
3527    fn recompiling_the_same_text_retains_nothing_new() {
3528        let css = ".box { height: 10vh } .box:has(> .c) { opacity: 0.5 } \
3529                   @supports selector(:has(a)) { .box { width: 1px } }";
3530        let counts = || (REPARSED.with(|r| r.borrow().len()), has::registry_len());
3531        let first = Engine::compile(css);
3532        let after_first = counts();
3533        assert!(after_first.1 >= 1, "the :has() argument was filed");
3534        for _ in 0..5 {
3535            let again = Engine::compile(css);
3536            assert_eq!(again.rules.len(), first.rules.len());
3537        }
3538        assert_eq!(counts(), after_first);
3539    }
3540
3541    #[test]
3542    fn compile_sheets_is_one_ordered_cascade_of_separate_parses() {
3543        let engine = Engine::compile_sheets(&[".box { opacity: 0.1 }", ".box { opacity: 0.5 }"]);
3544        assert_eq!(
3545            engine
3546                .compute(box_node(), None, &Env::default())
3547                .base
3548                .opacity,
3549            Some(0.5)
3550        );
3551        let engine = Engine::compile_sheets(&[".box { opacity: 0.1 } }", ".box { opacity: 0.6 }"]);
3552        assert_eq!(
3553            engine
3554                .compute(box_node(), None, &Env::default())
3555                .base
3556                .opacity,
3557            Some(0.6)
3558        );
3559    }
3560
3561    fn node_with(attrs: &'static [(&'static str, &'static str)]) -> Node {
3562        Node {
3563            tag: "div",
3564            class: "box",
3565            attrs,
3566        }
3567    }
3568
3569    fn transitions(css: &str) -> Vec<TransitionSpec> {
3570        let engine = Engine::compile(css);
3571        (*engine
3572            .compute(box_node(), None, &Env::default())
3573            .transitions)
3574            .clone()
3575    }
3576
3577    #[test]
3578    fn a_syntax_error_skips_one_rule_not_the_sheet() {
3579        let css = "@keyframes pulse { 0% { opacity: 0 } 100% { opacity: 1 } }\n\
3580                   }\n\
3581                   .eaten { opacity: 0 }\n\
3582                   .box { transition: opacity 200ms linear }";
3583        let engine = Engine::compile(css);
3584        assert!(
3585            engine.keyframes.contains_key("pulse"),
3586            "the @keyframes before the stray brace survives"
3587        );
3588        assert_eq!(
3589            transitions(css).len(),
3590            1,
3591            "parsing resumed: the rule after the damage applies"
3592        );
3593    }
3594
3595    #[test]
3596    fn cascade_carries_a_rules_transition() {
3597        let t = transitions(".box { transition: opacity 200ms linear }");
3598        assert_eq!(t.len(), 1);
3599        assert_eq!(t[0].property, TransitionProperty::Opacity);
3600        assert_eq!(t[0].duration, Duration::from_millis(200));
3601    }
3602
3603    #[test]
3604    fn later_rules_replace_the_whole_list() {
3605        let t = transitions(
3606            ".box { transition: opacity 1s, color 1s } \
3607             div { transition: width 300ms ease-in }",
3608        );
3609        assert_eq!(t.len(), 2);
3610        assert_eq!(t[0].property, TransitionProperty::Opacity);
3611
3612        let t = transitions(
3613            ".box { transition: opacity 1s, color 1s } \
3614             .box { transition: width 300ms ease-in }",
3615        );
3616        assert_eq!(t.len(), 1);
3617        assert_eq!(t[0].property, TransitionProperty::Width);
3618        assert_eq!(t[0].easing, Easing::EaseIn);
3619    }
3620
3621    #[test]
3622    fn transition_none_in_a_later_rule_clears() {
3623        let t = transitions(
3624            ".box { transition: opacity 1s } \
3625             .box { transition: none }",
3626        );
3627        assert!(t.is_empty());
3628    }
3629
3630    #[test]
3631    fn important_transitions_win_over_normal_ones() {
3632        let t = transitions(
3633            ".box { transition: opacity 1s !important } \
3634             div.box { transition: width 2s }",
3635        );
3636        assert_eq!(t.len(), 1);
3637        assert_eq!(t[0].property, TransitionProperty::Opacity);
3638    }
3639
3640    #[test]
3641    fn state_rule_transitions_are_rejected() {
3642        let engine = Engine::compile(".box:hover { transition: opacity 1s; opacity: 0.5 }");
3643        let states = engine.compute(box_node(), None, &Env::default());
3644        assert!(states.transitions.is_empty());
3645        assert!(states.hover.is_some());
3646    }
3647
3648    #[test]
3649    fn inline_transitions_override_the_sheet() {
3650        let engine = Engine::compile(".box { transition: opacity 1s }");
3651        let mut diagnostics = Vec::new();
3652        let (inline, inline_transitions) =
3653            parse_inline_with_transitions("transition: width 50ms linear", &mut diagnostics);
3654        assert!(diagnostics.is_empty(), "{diagnostics:?}");
3655        let states = engine.compute_with(
3656            box_node(),
3657            Some(&inline),
3658            Some(&Rc::new(inline_transitions)),
3659            &Env::default(),
3660        );
3661        assert_eq!(states.transitions.len(), 1);
3662        assert_eq!(states.transitions[0].property, TransitionProperty::Width);
3663        assert_eq!(states.transitions[0].duration, Duration::from_millis(50));
3664    }
3665
3666    #[test]
3667    fn transition_declarations_do_not_leak_into_the_refinement_diagnostics() {
3668        let engine = Engine::compile(
3669            ".box { transition: opacity 1s; transition-delay: 20ms; opacity: 0.5 }",
3670        );
3671        assert!(engine.diagnostics.is_empty(), "{:?}", engine.diagnostics);
3672        let states = engine.compute(box_node(), None, &Env::default());
3673        assert_eq!(states.base.opacity, Some(0.5));
3674        assert_eq!(
3675            states.transitions[0].delay,
3676            Duration::from_millis(20).into()
3677        );
3678    }
3679
3680    #[test]
3681    fn tailwinds_transition_colors_plus_duration_300_preserves_properties_and_easing() {
3682        let t = transitions(
3683            ".box { /* .transition-colors */ \
3684               transition-property: color, background-color, border-color, \
3685                                    text-decoration-color, fill, stroke; \
3686               transition-timing-function: cubic-bezier(0.4, 0, 0.2, 1); \
3687               transition-duration: 150ms } \
3688             .box { /* .duration-300 */ transition-duration: 300ms }",
3689        );
3690        assert_eq!(
3691            t.iter()
3692                .map(|transition| transition.property.clone())
3693                .collect::<Vec<_>>(),
3694            vec![
3695                TransitionProperty::Color,
3696                TransitionProperty::BackgroundColor,
3697                TransitionProperty::BorderColor,
3698                TransitionProperty::TextDecorationColor,
3699                TransitionProperty::Fill,
3700                TransitionProperty::Stroke,
3701            ]
3702        );
3703        assert!(t.iter().all(
3704            |transition| transition.duration == Duration::from_millis(300)
3705                && transition.easing == Easing::CubicBezier(0.4, 0.0, 0.2, 1.0)
3706        ));
3707        assert!(spec_for(&t, &TransitionProperty::BackgroundColor).is_some());
3708        assert!(
3709            spec_for(&t, &TransitionProperty::Width).is_none(),
3710            "the color-only utility must not start animating layout"
3711        );
3712    }
3713
3714    fn states_of(css: &str) -> ComputedStates {
3715        Engine::compile(css).compute(box_node(), None, &Env::default())
3716    }
3717
3718    #[test]
3719    fn focus_rules_land_on_their_own_rung_not_in_base() {
3720        let s = states_of(".box { opacity: 0.2 } .box:focus { opacity: 0.9 }");
3721        assert_eq!(s.base.opacity, Some(0.2));
3722        assert_eq!(s.focus.as_ref().and_then(|f| f.opacity), Some(0.9));
3723        assert!(s.focus_visible.is_none());
3724        assert!(s.hover.is_none() && s.active.is_none());
3725        assert!(s.needs_focus_handle());
3726    }
3727
3728    #[test]
3729    fn focus_visible_is_its_own_rung() {
3730        let s = states_of(".box:focus-visible { opacity: 0.7 }");
3731        assert_eq!(s.focus_visible.as_ref().and_then(|f| f.opacity), Some(0.7));
3732        assert!(s.focus.is_none());
3733        assert!(s.needs_focus_handle());
3734        assert!(!states_of(".box { opacity: 0.5 }").needs_focus_handle());
3735    }
3736
3737    #[test]
3738    fn tailwinds_focus_variant_compiles_onto_the_focus_rung() {
3739        let engine = Engine::compile(r".focus\:opacity-100:focus { opacity: 1 }");
3740        assert!(engine.diagnostics.is_empty(), "{:?}", engine.diagnostics);
3741        let node = Node {
3742            tag: "div",
3743            class: "focus:opacity-100",
3744            attrs: &[],
3745        };
3746        let s = engine.compute(node, None, &Env::default());
3747        assert_eq!(s.focus.as_ref().and_then(|f| f.opacity), Some(1.0));
3748    }
3749
3750    #[test]
3751    fn several_states_in_one_compound_pick_the_strongest_rung() {
3752        let engine = Engine::compile(".box:hover:focus { opacity: 0.4 }");
3753        let s = engine.compute(box_node(), None, &Env::default());
3754        assert_eq!(s.hover.as_ref().and_then(|f| f.opacity), Some(0.4));
3755        assert!(s.focus.is_none());
3756    }
3757
3758    fn group_doc() -> Doc {
3759        Doc {
3760            nodes: vec![
3761                ("", "", 0, vec![]),
3762                ("div", "card group", 0, vec![]),
3763                ("div", "row", 1, vec![]),
3764                ("span", "icon", 2, vec![]),
3765                ("div", "card group", 0, vec![]),
3766                ("span", "icon", 4, vec![]),
3767            ],
3768        }
3769    }
3770
3771    #[test]
3772    fn group_hover_folds_onto_its_ancestor_and_not_onto_the_element() {
3773        let engine = Engine::compile(
3774            ".group:hover .icon { color: rgb(255 0 0) } .icon { color: rgb(0 0 0) }",
3775        );
3776        assert!(engine.diagnostics.is_empty(), "{:?}", engine.diagnostics);
3777        assert!(engine.uses_group_states());
3778        let d = group_doc();
3779        let states = cascade(&engine, &d, &Env::default());
3780        let icon = &states[2];
3781        assert_eq!(icon.base.text.color, Some(gpui::rgb(0x000000).into()));
3782        assert!(icon.hover.is_none());
3783        let (anchor, style) = icon.group_hover.as_ref().expect("a group-hover bucket");
3784        assert_eq!(*anchor, 1);
3785        assert_eq!(style.text.color, Some(gpui::rgb(0xff0000).into()));
3786    }
3787
3788    #[test]
3789    fn group_hover_picks_the_nearest_matching_ancestor() {
3790        let engine = Engine::compile(".group:hover .icon { opacity: 0.5 }");
3791        let d = group_doc();
3792        let states = cascade(&engine, &d, &Env::default());
3793        assert_eq!(states[2].group_hover.as_ref().map(|(k, _)| *k), Some(1));
3794        assert_eq!(states[4].group_hover.as_ref().map(|(k, _)| *k), Some(4));
3795    }
3796
3797    #[test]
3798    fn group_active_has_its_own_bucket() {
3799        let engine = Engine::compile(".group:active .icon { opacity: 0.5 }");
3800        let d = group_doc();
3801        let states = cascade(&engine, &d, &Env::default());
3802        assert!(states[2].group_hover.is_none());
3803        assert_eq!(states[2].group_active.as_ref().map(|(k, _)| *k), Some(1));
3804    }
3805
3806    #[test]
3807    fn focus_states_on_an_ancestor_fold_into_their_own_buckets() {
3808        let engine = Engine::compile(
3809            ".group:focus .icon { opacity: 0.5 } .group:focus-visible .icon { opacity: 0.6 } \
3810             .row:focus-within > .icon { opacity: 0.7 }",
3811        );
3812        assert!(engine.diagnostics.is_empty(), "{:?}", engine.diagnostics);
3813        let d = group_doc();
3814        let states = cascade(&engine, &d, &Env::default());
3815        let icon = &states[2];
3816        assert!(icon.focus.is_none() && icon.focus_within.is_none());
3817        let group = icon.group_focus.as_ref().expect("ancestor focus buckets");
3818        assert_eq!(
3819            group.focus.as_ref().map(|(k, s)| (*k, s.opacity)),
3820            Some((1, Some(0.5)))
3821        );
3822        assert_eq!(
3823            group.focus_visible.as_ref().map(|(k, s)| (*k, s.opacity)),
3824            Some((1, Some(0.6)))
3825        );
3826        assert_eq!(
3827            group.focus_within.as_ref().map(|(k, s)| (*k, s.opacity)),
3828            Some((2, Some(0.7)))
3829        );
3830        let mut folded = StyleRefinement::default();
3831        group.fold(&mut folded, |key, state| {
3832            key == 1 && matches!(state, Interaction::Focus)
3833        });
3834        assert_eq!(folded.opacity, Some(0.5));
3835    }
3836
3837    #[test]
3838    fn group_hover_does_not_reach_outside_the_group() {
3839        let engine = Engine::compile(".group:hover .icon { opacity: 0.5 }");
3840        let d = doc();
3841        let states = cascade(&engine, &d, &Env::default());
3842        assert!(states.iter().all(|s| s.group_hover.is_none()));
3843    }
3844
3845    #[test]
3846    fn a_state_before_a_pseudo_element_is_not_an_ancestor_state() {
3847        let engine = Engine::compile(r#".nav:hover::after { content: "x" }"#);
3848        assert!(!engine.uses_group_states(), "{:?}", engine.diagnostics);
3849    }
3850
3851    #[test]
3852    fn viewport_units_resolve_against_the_published_viewport() {
3853        assert!(set_viewport_basis(1000.0, 800.0));
3854        let engine = Engine::compile(
3855            ".box { width: 90vw; max-height: 85vh; min-width: 50vmin; padding-top: 10vmax }",
3856        );
3857        assert!(uses_viewport_units());
3858        let s = engine.compute(box_node(), None, &Env::default());
3859        assert_eq!(s.base.size.width, Some(gpui::px(900.0).into()));
3860        assert_eq!(s.base.max_size.height, Some(gpui::px(680.0).into()));
3861        assert_eq!(s.base.min_size.width, Some(gpui::px(400.0).into()));
3862        assert_eq!(s.base.padding.top, Some(gpui::px(100.0).into()));
3863        assert!(!set_viewport_basis(1000.0, 800.0));
3864        assert!(set_viewport_basis(1280.0, 720.0));
3865        set_viewport_basis(INITIAL_VIEWPORT_BASIS.0, INITIAL_VIEWPORT_BASIS.1);
3866    }
3867
3868    #[test]
3869    fn a_sheet_without_viewport_units_does_not_ask_for_a_recompile() {
3870        Engine::compile(".box { width: 10px }");
3871        assert!(!uses_viewport_units());
3872    }
3873
3874    #[test]
3875    fn calc_over_viewport_units_resolves_too() {
3876        assert!(set_viewport_basis(1000.0, 800.0));
3877        let engine = Engine::compile(".box { height: calc(85vh - 80px) }");
3878        let s = engine.compute(box_node(), None, &Env::default());
3879        assert_eq!(s.base.size.height, Some(gpui::px(600.0).into()));
3880        set_viewport_basis(INITIAL_VIEWPORT_BASIS.0, INITIAL_VIEWPORT_BASIS.1);
3881    }
3882
3883    #[test]
3884    fn a_resize_rebases_the_viewport_rules_in_place() {
3885        assert!(set_viewport_basis(1000.0, 800.0));
3886        let css = ".box, .other { width: 90vw; color: red } .plain { width: 10px } \
3887                   .box { max-height: calc(85vh - 80px); transition: max-height 1s } \
3888                   .other { padding-top: 10vmin }";
3889        let mut engine = Engine::compile(css);
3890        assert!(uses_viewport_units());
3891        assert!(set_viewport_basis(1200.0, 600.0));
3892        assert!(engine.rebase_viewport());
3893        let fresh = Engine::compile(css);
3894        for class in ["box", "other", "plain"] {
3895            let node = Node {
3896                tag: "div",
3897                class,
3898                attrs: &[],
3899            };
3900            assert_eq!(
3901                engine.compute(node, None, &Env::default()),
3902                fresh.compute(node, None, &Env::default()),
3903                ".{class}"
3904            );
3905        }
3906        let s = engine.compute(box_node(), None, &Env::default());
3907        assert_eq!(s.base.size.width, Some(gpui::px(1080.0).into()));
3908        assert_eq!(s.base.max_size.height, Some(gpui::px(430.0).into()));
3909        assert_eq!(
3910            s.transitions.len(),
3911            1,
3912            "the rebased rule keeps its transition"
3913        );
3914        set_viewport_basis(INITIAL_VIEWPORT_BASIS.0, INITIAL_VIEWPORT_BASIS.1);
3915    }
3916
3917    #[test]
3918    fn a_viewport_unit_in_keyframes_asks_for_a_recompile() {
3919        let mut engine =
3920            Engine::compile("@keyframes grow { from { height: 50vh } to { height: 10px } }");
3921        assert!(uses_viewport_units());
3922        assert!(!engine.rebase_viewport());
3923        let mut plain = Engine::compile(".box { width: 10px }");
3924        assert!(
3925            plain.rebase_viewport(),
3926            "nothing to re-resolve is not a failure"
3927        );
3928    }
3929
3930    fn engine_digest(engine: &Engine) -> Vec<String> {
3931        let mut out = Vec::new();
3932        for r in &engine.rules {
3933            out.push(format!(
3934                "{} | {} {} {} {:?} {:?} {:?} | {:?} | {:?} | {:?} {:?} | {:?} {:?} | {:?} {:?} | {:?} | {:?} | \
3935                 {:?} {:?} | {:?} {:?} | {:?} | {:?}",
3936                sel_text(&r.selector),
3937                r.specificity,
3938                r.order,
3939                r.states,
3940                r.ancestor,
3941                r.pseudo,
3942                r.condition,
3943                r.normal,
3944                r.important,
3945                r.normal_transitions,
3946                r.important_transitions,
3947                r.normal_animations,
3948                r.important_animations,
3949                r.normal_animation_patch,
3950                r.important_animation_patch,
3951                r.normal_extras,
3952                r.important_extras,
3953                r.normal_custom,
3954                r.important_custom,
3955                r.normal_dynamic,
3956                r.important_dynamic,
3957                r.diagnostics,
3958                r.decls,
3959            ));
3960        }
3961        let mut buckets: Vec<String> = [
3962            ("id", &engine.index.by_id),
3963            ("class", &engine.index.by_class),
3964            ("tag", &engine.index.by_tag),
3965            ("parent id", &engine.index.by_parent_id),
3966            ("parent class", &engine.index.by_parent_class),
3967            ("parent tag", &engine.index.by_parent_tag),
3968        ]
3969        .into_iter()
3970        .flat_map(|(kind, map)| {
3971            map.iter()
3972                .map(move |(k, v)| format!("index {kind} {k}: {v:?}"))
3973        })
3974        .collect();
3975        buckets.sort();
3976        out.extend(buckets);
3977        out.push(format!("index root: {:?}", engine.index.root));
3978        out.push(format!(
3979            "index any: {:?} enabled {}",
3980            engine.index.any, engine.index.enabled
3981        ));
3982        for (c, t) in engine.conditions.iter().zip(&engine.condition_text) {
3983            out.push(format!("media {t}: {c:?}"));
3984        }
3985        let mut names: Vec<&Box<str>> = engine.keyframes.keys().collect();
3986        names.sort();
3987        for name in names {
3988            for b in &engine.keyframes[name] {
3989                let steps: Vec<String> = b
3990                    .block
3991                    .steps
3992                    .iter()
3993                    .map(|k| {
3994                        format!(
3995                            "{:?} {:?} {:?} {:?}",
3996                            k.offset, k.easing, k.style, k.dynamic
3997                        )
3998                    })
3999                    .collect();
4000                out.push(format!(
4001                    "keyframes {name} {:?} {} {steps:?}",
4002                    b.condition, b.block.dynamic
4003                ));
4004            }
4005        }
4006        for b in &engine.viewport_blocks {
4007            out.push(format!("viewport {:?} {}", b.rules, b.css));
4008        }
4009        out.push(format!(
4010            "flags {} {} {}",
4011            engine.sibling_combinators, engine.group_states, engine.viewport_unkept
4012        ));
4013        out.extend(engine.diagnostics.iter().map(|d| format!("advisory {d}")));
4014        out
4015    }
4016
4017    #[test]
4018    #[ignore = "needs SK_SHEET=<css file> and SK_ENGINE_DIGEST=<file>"]
4019    fn engine_digest_matches_the_recorded_one() {
4020        use std::hash::{Hash as _, Hasher as _};
4021        let (Ok(sheet), Ok(file)) = (std::env::var("SK_SHEET"), std::env::var("SK_ENGINE_DIGEST"))
4022        else {
4023            return;
4024        };
4025        let css = std::fs::read_to_string(&sheet).expect("SK_SHEET is readable");
4026        set_viewport_basis(INITIAL_VIEWPORT_BASIS.0, INITIAL_VIEWPORT_BASIS.1);
4027        let lines = engine_digest(&Engine::compile(&css));
4028        let hashed: Vec<String> = lines
4029            .iter()
4030            .map(|l| {
4031                let mut h = std::collections::hash_map::DefaultHasher::new();
4032                l.hash(&mut h);
4033                format!("{:016x}", h.finish())
4034            })
4035            .collect();
4036        match std::fs::read_to_string(&file) {
4037            Err(_) => {
4038                std::fs::write(&file, hashed.join("\n")).expect("SK_ENGINE_DIGEST is writable");
4039                eprintln!("recorded {} lines to {file}", hashed.len());
4040            }
4041            Ok(recorded) => {
4042                let recorded: Vec<&str> = recorded.lines().collect();
4043                for (i, (a, b)) in recorded.iter().zip(&hashed).enumerate() {
4044                    assert_eq!(
4045                        *a,
4046                        b.as_str(),
4047                        "line {i} differs; it now reads: {}",
4048                        lines[i]
4049                    );
4050                }
4051                assert_eq!(recorded.len(), hashed.len(), "line count");
4052                eprintln!("{} lines, all equal to {file}", hashed.len());
4053            }
4054        }
4055    }
4056
4057    #[test]
4058    #[ignore = "needs SK_SHEET=<css file>"]
4059    fn rebase_matches_a_fresh_compile_on_a_real_sheet() {
4060        let Ok(path) = std::env::var("SK_SHEET") else {
4061            return;
4062        };
4063        let css = std::fs::read_to_string(&path).expect("SK_SHEET is readable");
4064        set_viewport_basis(1000.0, 800.0);
4065        let mut engine = Engine::compile(&css);
4066        set_viewport_basis(1371.0, 655.0);
4067        assert!(engine.rebase_viewport());
4068        let fresh = Engine::compile(&css);
4069        assert_eq!(engine.rules.len(), fresh.rules.len());
4070        let touched: usize = engine.viewport_blocks.iter().map(|b| b.rules.len()).sum();
4071        for (i, (a, b)) in engine.rules.iter().zip(&fresh.rules).enumerate() {
4072            let same = a.normal == b.normal
4073                && a.important == b.important
4074                && a.normal_transitions == b.normal_transitions
4075                && a.important_transitions == b.important_transitions
4076                && a.normal_transition_declarations == b.normal_transition_declarations
4077                && a.important_transition_declarations == b.important_transition_declarations
4078                && a.normal_animations == b.normal_animations
4079                && a.important_animations == b.important_animations
4080                && a.normal_animation_patch == b.normal_animation_patch
4081                && a.important_animation_patch == b.important_animation_patch
4082                && a.normal_extras == b.normal_extras
4083                && a.important_extras == b.important_extras
4084                && a.normal_custom == b.normal_custom
4085                && a.important_custom == b.important_custom
4086                && a.normal_dynamic == b.normal_dynamic
4087                && a.important_dynamic == b.important_dynamic
4088                && a.normal_font == b.normal_font
4089                && a.important_font == b.important_font;
4090            assert!(
4091                same,
4092                "rule {i} ({}) differs after the rebase",
4093                sel_text(&a.selector)
4094            );
4095        }
4096        eprintln!(
4097            "{} rules, {} viewport blocks filling {touched} of them: all equal to a fresh compile",
4098            engine.rules.len(),
4099            engine.viewport_blocks.len()
4100        );
4101        set_viewport_basis(INITIAL_VIEWPORT_BASIS.0, INITIAL_VIEWPORT_BASIS.1);
4102    }
4103
4104    #[test]
4105    fn inline_level_display_is_recorded_for_the_renderer() {
4106        let engine = Engine::compile(
4107            ".a { display: inline-flex } .b { display: flex } .c { display: inline }",
4108        );
4109        let a = engine.compute(
4110            Node {
4111                tag: "div",
4112                class: "a",
4113                attrs: &[],
4114            },
4115            None,
4116            &Env::default(),
4117        );
4118        let b = engine.compute(
4119            Node {
4120                tag: "div",
4121                class: "b",
4122                attrs: &[],
4123            },
4124            None,
4125            &Env::default(),
4126        );
4127        let c = engine.compute(
4128            Node {
4129                tag: "div",
4130                class: "c",
4131                attrs: &[],
4132            },
4133            None,
4134            &Env::default(),
4135        );
4136        assert_eq!(a.extras.inline_level, Some(true));
4137        assert_eq!(a.base.display, Some(gpui::Display::Flex));
4138        assert_eq!(b.extras.inline_level, Some(false));
4139        assert_eq!(c.extras.inline_level, Some(true));
4140    }
4141
4142    #[test]
4143    fn disabled_matches_the_property_and_folds_into_base() {
4144        let engine = Engine::compile(".box { opacity: 1 } .box:disabled { opacity: 0.4 }");
4145        assert!(engine.diagnostics.is_empty(), "{:?}", engine.diagnostics);
4146
4147        let off = engine.compute(node_with(&[("disabled", "")]), None, &Env::default());
4148        assert_eq!(off.base.opacity, Some(0.4));
4149        assert!(off.focus.is_none() && off.hover.is_none() && off.active.is_none());
4150
4151        let on = engine.compute(box_node(), None, &Env::default());
4152        assert_eq!(on.base.opacity, Some(1.0));
4153    }
4154
4155    #[test]
4156    fn disabled_false_is_not_disabled() {
4157        let engine = Engine::compile(".box:disabled { opacity: 0.4 }");
4158        let s = engine.compute(node_with(&[("disabled", "false")]), None, &Env::default());
4159        assert_eq!(s.base.opacity, None);
4160        let s = engine.compute(node_with(&[("disabled", "true")]), None, &Env::default());
4161        assert_eq!(s.base.opacity, Some(0.4));
4162    }
4163
4164    #[test]
4165    fn enabled_is_the_complement_and_checked_reads_its_own_property() {
4166        let engine = Engine::compile(".box:enabled { opacity: 1 } .box:checked { opacity: 0.5 }");
4167        assert_eq!(
4168            engine
4169                .compute(box_node(), None, &Env::default())
4170                .base
4171                .opacity,
4172            Some(1.0)
4173        );
4174        assert_eq!(
4175            engine
4176                .compute(node_with(&[("disabled", "")]), None, &Env::default())
4177                .base
4178                .opacity,
4179            None
4180        );
4181        assert_eq!(
4182            engine
4183                .compute(node_with(&[("checked", "true")]), None, &Env::default())
4184                .base
4185                .opacity,
4186            Some(0.5)
4187        );
4188    }
4189
4190    #[test]
4191    fn checked_and_indeterminate_follow_a_controls_state_not_its_attribute() {
4192        let checked = Engine::compile(":checked { opacity: 0.5 }");
4193        let indeterminate = Engine::compile(":indeterminate { opacity: 0.5 }");
4194        let style = |tag: &'static str, attrs: &'static [(&'static str, &'static str)]| {
4195            let node = Node {
4196                tag,
4197                class: "",
4198                attrs,
4199            };
4200            let hit = |e: &Engine| {
4201                e.compute(node, None, &Env::default())
4202                    .base
4203                    .opacity
4204                    .is_some()
4205            };
4206            (hit(&checked), hit(&indeterminate))
4207        };
4208        assert_eq!(
4209            style("input", &[("type", "checkbox"), ("checked", "")]),
4210            (false, false)
4211        );
4212        assert_eq!(
4213            style("input", &[("type", "Radio"), (":checked", "")]),
4214            (true, false)
4215        );
4216        assert_eq!(
4217            style("input", &[("type", "text"), (":checked", "")]),
4218            (false, false)
4219        );
4220        assert_eq!(
4221            style("input", &[("type", "checkbox"), (":indeterminate", "")]),
4222            (false, true)
4223        );
4224        assert_eq!(
4225            style("input", &[("type", "radio"), (":indeterminate", "")]),
4226            (false, false)
4227        );
4228        assert_eq!(style("option", &[(":checked", "")]), (true, false));
4229        assert_eq!(style("option", &[("selected", "")]), (false, false));
4230    }
4231
4232    fn attr_matches(selector: &str, attrs: &'static [(&'static str, &'static str)]) -> bool {
4233        let engine = Engine::compile(&format!("{selector} {{ opacity: 0.5 }}"));
4234        assert!(engine.diagnostics.is_empty(), "{:?}", engine.diagnostics);
4235        engine
4236            .compute(node_with(attrs), None, &Env::default())
4237            .base
4238            .opacity
4239            .is_some()
4240    }
4241
4242    #[test]
4243    fn attribute_presence_and_exact_value() {
4244        assert!(attr_matches("[disabled]", &[("disabled", "")]));
4245        assert!(!attr_matches("[disabled]", &[]));
4246        assert!(attr_matches(
4247            r#"[data-state="open"]"#,
4248            &[("data-state", "open")]
4249        ));
4250        assert!(!attr_matches(
4251            r#"[data-state="open"]"#,
4252            &[("data-state", "closed")]
4253        ));
4254        assert!(!attr_matches(r#"[data-state="open"]"#, &[]));
4255        assert!(attr_matches(
4256            r#"[aria-expanded="true"]"#,
4257            &[("aria-expanded", "true")]
4258        ));
4259    }
4260
4261    #[test]
4262    fn hidden_is_display_none_below_every_author_rule() {
4263        use gpui::Display::{Flex, Grid, None as Gone};
4264        let display = |css: &str, attrs: &'static [(&'static str, &'static str)]| {
4265            let engine = Engine::compile(css);
4266            assert!(engine.diagnostics.is_empty(), "{:?}", engine.diagnostics);
4267            engine
4268                .compute(node_with(attrs), None, &Env::default())
4269                .base
4270                .display
4271        };
4272        assert_eq!(display("", &[("hidden", "")]), Some(Gone));
4273        assert_eq!(
4274            display("", &[("hidden", "until-found")]),
4275            Some(Gone),
4276            "treated as hidden"
4277        );
4278        assert_eq!(display("", &[]), None, "no attribute, no rule");
4279        assert_eq!(
4280            display("div { display: flex }", &[("hidden", "")]),
4281            Some(Flex),
4282            "a type selector"
4283        );
4284        assert_eq!(
4285            display("* { display: grid }", &[("hidden", "")]),
4286            Some(Grid),
4287            "even `*`"
4288        );
4289        assert_eq!(
4290            display(
4291                ".box[hidden] { display: none } .box { display: flex }",
4292                &[("hidden", "")]
4293            ),
4294            Some(Gone),
4295            "the author's own [hidden] rule is an ordinary rule"
4296        );
4297    }
4298
4299    #[test]
4300    fn attribute_substring_operators() {
4301        let a: &'static [(&'static str, &'static str)] = &[("data-x", "alpha-beta gamma")];
4302        assert!(attr_matches(r#"[data-x^="alpha"]"#, a));
4303        assert!(!attr_matches(r#"[data-x^="beta"]"#, a));
4304        assert!(attr_matches(r#"[data-x$="gamma"]"#, a));
4305        assert!(!attr_matches(r#"[data-x$="alpha"]"#, a));
4306        assert!(attr_matches(r#"[data-x*="beta"]"#, a));
4307        assert!(!attr_matches(r#"[data-x*="delta"]"#, a));
4308        assert!(attr_matches(r#"[data-x~="gamma"]"#, a));
4309        assert!(!attr_matches(r#"[data-x~="alpha"]"#, a));
4310        assert!(attr_matches(r#"[lang|="en"]"#, &[("lang", "en-GB")]));
4311        assert!(!attr_matches(r#"[lang|="en"]"#, &[("lang", "eng")]));
4312        assert!(attr_matches(
4313            r#"[data-state="OPEN" i]"#,
4314            &[("data-state", "open")]
4315        ));
4316        assert!(!attr_matches(
4317            r#"[data-state="OPEN"]"#,
4318            &[("data-state", "open")]
4319        ));
4320    }
4321
4322    #[test]
4323    fn tailwinds_data_variant_works() {
4324        let engine = Engine::compile(
4325            r#".data-\[state\=open\]\:opacity-100[data-state="open"] { opacity: 1 }"#,
4326        );
4327        assert!(engine.diagnostics.is_empty(), "{:?}", engine.diagnostics);
4328        let on = Node {
4329            tag: "div",
4330            class: "data-[state=open]:opacity-100",
4331            attrs: &[("data-state", "open")],
4332        };
4333        let off = Node {
4334            attrs: &[("data-state", "closed")],
4335            ..on
4336        };
4337        assert_eq!(
4338            engine.compute(on, None, &Env::default()).base.opacity,
4339            Some(1.0)
4340        );
4341        assert_eq!(
4342            engine.compute(off, None, &Env::default()).base.opacity,
4343            None
4344        );
4345    }
4346
4347    #[test]
4348    fn id_selectors_read_the_id_attribute() {
4349        assert!(attr_matches("#main", &[("id", "main")]));
4350        assert!(!attr_matches("#main", &[("id", "other")]));
4351        assert!(!attr_matches("#main", &[]));
4352    }
4353
4354    #[test]
4355    fn scope_hashes_still_take_the_scope_path() {
4356        assert!(!attr_matches("[data-v-abc123]", &[("data-v-abc123", "")]));
4357    }
4358
4359    fn env_at(width: f32, dark: bool, reduce_motion: bool) -> Env {
4360        Env {
4361            viewport_width: width,
4362            viewport_height: 800.0,
4363            dark,
4364            reduce_motion,
4365            ..Env::default()
4366        }
4367    }
4368
4369    #[test]
4370    fn media_rules_apply_only_when_their_condition_holds() {
4371        let engine = Engine::compile(
4372            ".box { opacity: 0.1 } @media (min-width: 640px) { .box { opacity: 0.9 } }",
4373        );
4374        assert!(engine.diagnostics.is_empty(), "{:?}", engine.diagnostics);
4375        let narrow = engine.compute(box_node(), None, &env_at(500.0, false, false));
4376        let wide = engine.compute(box_node(), None, &env_at(700.0, false, false));
4377        assert_eq!(narrow.base.opacity, Some(0.1));
4378        assert_eq!(wide.base.opacity, Some(0.9));
4379        assert_ne!(narrow, wide);
4380    }
4381
4382    #[test]
4383    fn dark_and_reduced_motion_conditions_reach_the_cascade() {
4384        let engine = Engine::compile(
4385            ".box { opacity: 0.1 } \
4386             @media (prefers-color-scheme: dark) { .box { opacity: 0.8 } } \
4387             @media (prefers-reduced-motion: reduce) { .box { opacity: 0.3 } }",
4388        );
4389        assert!(engine.diagnostics.is_empty(), "{:?}", engine.diagnostics);
4390        let base = engine.compute(box_node(), None, &env_at(800.0, false, false));
4391        let dark = engine.compute(box_node(), None, &env_at(800.0, true, false));
4392        let calm = engine.compute(box_node(), None, &env_at(800.0, false, true));
4393        assert_eq!(base.base.opacity, Some(0.1));
4394        assert_eq!(dark.base.opacity, Some(0.8));
4395        assert_eq!(calm.base.opacity, Some(0.3));
4396    }
4397
4398    #[test]
4399    fn media_state_rules_still_reach_their_rung() {
4400        let engine = Engine::compile("@media (min-width: 640px) { .box:focus { opacity: 0.9 } }");
4401        assert!(engine
4402            .compute(box_node(), None, &env_at(500.0, false, false))
4403            .focus
4404            .is_none());
4405        assert_eq!(
4406            engine
4407                .compute(box_node(), None, &env_at(700.0, false, false))
4408                .focus
4409                .as_ref()
4410                .and_then(|f| f.opacity),
4411            Some(0.9)
4412        );
4413    }
4414
4415    #[test]
4416    fn nested_media_blocks_and_the_document_order_tiebreak() {
4417        let engine = Engine::compile(
4418            "@media (min-width: 640px) { \
4419                @media (prefers-color-scheme: dark) { .box { opacity: 0.7 } } \
4420             } \
4421             .box { opacity: 0.2 }",
4422        );
4423        assert!(engine.diagnostics.is_empty(), "{:?}", engine.diagnostics);
4424        assert_eq!(
4425            engine
4426                .compute(box_node(), None, &env_at(700.0, false, false))
4427                .base
4428                .opacity,
4429            Some(0.2)
4430        );
4431        assert_eq!(
4432            engine
4433                .compute(box_node(), None, &env_at(500.0, true, false))
4434                .base
4435                .opacity,
4436            Some(0.2)
4437        );
4438        assert_eq!(
4439            engine
4440                .compute(box_node(), None, &env_at(700.0, true, false))
4441                .base
4442                .opacity,
4443            Some(0.2)
4444        );
4445    }
4446
4447    #[test]
4448    fn an_unsupported_media_feature_drops_the_block() {
4449        let engine = Engine::compile("@media (prefers-contrast: more) { .box { opacity: 0.9 } }");
4450        assert_eq!(
4451            engine
4452                .compute(box_node(), None, &Env::default())
4453                .base
4454                .opacity,
4455            None
4456        );
4457    }
4458
4459    #[test]
4460    fn print_only_rules_parse_and_simply_never_apply() {
4461        let engine = Engine::compile("@media print { .box { opacity: 0.9 } }");
4462        assert!(engine.diagnostics.is_empty(), "{:?}", engine.diagnostics);
4463        assert_eq!(
4464            engine
4465                .compute(box_node(), None, &Env::default())
4466                .base
4467                .opacity,
4468            None
4469        );
4470    }
4471
4472    fn audited(selector: &str) -> Engine {
4473        Engine::compile(&format!("{selector} {{ opacity: 0.5 }}"))
4474    }
4475
4476    #[test]
4477    fn unanswerable_pseudo_classes_are_dropped() {
4478        for selector in [
4479            ".box:visited",
4480            ".box:required",
4481            ".box:placeholder-shown",
4482            ".box:target",
4483            ".box:lang(en)",
4484            ".box::first-line",
4485        ] {
4486            let engine = audited(selector);
4487            assert_eq!(
4488                engine
4489                    .compute(box_node(), None, &Env::default())
4490                    .base
4491                    .opacity,
4492                None,
4493                "{selector} must not compile into a never-matching rule"
4494            );
4495        }
4496    }
4497
4498    #[test]
4499    fn structural_and_answerable_selectors_pass_the_audit() {
4500        for selector in [
4501            ".box",
4502            "div.box",
4503            ".box:nth-child(1)",
4504            ".box:first-child",
4505            ".box:only-child",
4506            ":root",
4507            ".box:empty",
4508            ".box:not(.other)",
4509            ".box:is(.box, .other)",
4510            ".box:where(.box)",
4511            ".box:disabled, .box:enabled",
4512            "[data-state]",
4513            "#main",
4514        ] {
4515            let engine = audited(selector);
4516            assert!(
4517                engine.diagnostics.is_empty(),
4518                "{selector} should be accepted: {:?}",
4519                engine.diagnostics
4520            );
4521        }
4522    }
4523
4524    /// A ladder state inside `:not()` silently INVERTS: the matcher answers "would match" for
4525    /// `:hover`, so `:not(:hover)` could only ever be false.
4526    #[test]
4527    fn a_ladder_state_inside_a_functional_pseudo_is_rejected() {
4528        let engine = audited(".box:not(:hover)");
4529        assert_eq!(
4530            engine
4531                .compute(box_node(), None, &Env::default())
4532                .base
4533                .opacity,
4534            None
4535        );
4536    }
4537
4538    /// `:nth-child(… of S)` makes parcel's matcher `unreachable!()` — a process abort, not a failed
4539    /// match.
4540    #[test]
4541    fn selectors_that_would_crash_the_matcher_are_rejected() {
4542        let engine = audited(".box:nth-child(1 of .other)");
4543        assert_eq!(
4544            engine
4545                .compute(box_node(), None, &Env::default())
4546                .base
4547                .opacity,
4548            None
4549        );
4550    }
4551
4552    #[test]
4553    fn inline_object_fit_beats_the_sheet() {
4554        let engine = Engine::compile("div.box { object-fit: cover }");
4555        let mut diags = Vec::new();
4556        let (r, t, x) = parse_inline_full("object-fit: contain", &mut diags);
4557        assert!(diags.is_empty(), "{diags:?}");
4558        let computed = engine.compute_full(
4559            box_node(),
4560            Some(&r),
4561            (!t.is_empty()).then(|| Rc::new(t)).as_ref(),
4562            x,
4563            &Env::default(),
4564        );
4565        assert_eq!(computed.extras.object_fit, Some(ObjectFit::Contain));
4566    }
4567
4568    fn base_with_inline(css: &str, style: &str) -> Rc<StyleRefinement> {
4569        let engine = Engine::compile(css);
4570        let mut diags = Vec::new();
4571        let inline = mapper::parse_inline_style(style, &mut diags);
4572        assert!(diags.is_empty(), "{diags:?}");
4573        engine
4574            .compute_node(
4575                box_node(),
4576                Some(&inline),
4577                &Rc::new(Vars::default()),
4578                None,
4579                &Env::default(),
4580                &mut diags,
4581            )
4582            .base
4583    }
4584
4585    #[test]
4586    fn outline_longhands_from_several_rules_fold_into_one_ring() {
4587        let rules = [
4588            ".box { outline-style: solid }",
4589            ".box { outline-width: 2px }",
4590            ".box { outline-offset: 4px }",
4591            ".box { outline-color: #ff0000 }",
4592        ];
4593        let reversed: Vec<&str> = rules.iter().rev().copied().collect();
4594        for sheet in [rules.join("\n"), reversed.join("\n")] {
4595            let (base, d) = computed_with_env(&sheet, &Env::default());
4596            assert!(d.is_empty(), "{d:?}");
4597            let ring = base.vn_outline.expect("an outline");
4598            assert_eq!(ring.width, gpui::px(2.0), "{sheet}");
4599            assert_eq!(ring.offset, gpui::px(4.0), "{sheet}");
4600            assert!(
4601                (ring.color.a - 1.0).abs() < 1e-3 && ring.color.s > 0.9,
4602                "{sheet}: {ring:?}"
4603            );
4604        }
4605        let (base, _) = computed_with_env(
4606            ".box { outline: 2px solid #ff0000 } .box { outline: none }",
4607            &Env::default(),
4608        );
4609        assert_eq!(base.vn_outline.expect("an outline").width, gpui::px(0.0));
4610    }
4611
4612    #[test]
4613    fn a_state_rules_outline_longhand_keeps_the_base_ring() {
4614        let engine = Engine::compile(
4615            ".box { outline: 2px dashed #ff0000 } .box:focus { outline-offset: 4px } .box:hover { outline-color: #0000ff }",
4616        );
4617        let states = engine.compute(box_node(), None, &Env::default());
4618        let base = states.base.vn_outline.expect("a base outline");
4619        let focus = states
4620            .focus
4621            .as_ref()
4622            .and_then(|r| r.vn_outline)
4623            .expect("a focus outline");
4624        assert_eq!(focus.offset, gpui::px(4.0));
4625        assert_eq!(
4626            (focus.width, focus.style, focus.color),
4627            (base.width, base.style, base.color)
4628        );
4629        let hover = states
4630            .hover
4631            .as_ref()
4632            .and_then(|r| r.vn_outline)
4633            .expect("a hover outline");
4634        assert_eq!(
4635            (hover.width, hover.style),
4636            (gpui::px(2.0), gpui::BorderStyle::Dashed)
4637        );
4638        assert_ne!(hover.color, base.color);
4639        let engine =
4640            Engine::compile(".box { outline: 2px solid #ff0000 } .box:focus { outline: none }");
4641        let states = engine.compute(box_node(), None, &Env::default());
4642        assert_eq!(
4643            states
4644                .focus
4645                .as_ref()
4646                .and_then(|r| r.vn_outline)
4647                .expect("a focus outline")
4648                .width,
4649            gpui::px(0.0)
4650        );
4651    }
4652
4653    #[test]
4654    fn decoration_longhands_reach_a_line_from_another_rule() {
4655        for sheet in [
4656            ".box { text-decoration-line: underline } .box { text-decoration-color: #ff0000 } .box { text-decoration-thickness: 2px }",
4657            ".box { text-decoration-thickness: 2px } .box { text-decoration-color: #ff0000 } .box { text-decoration-line: underline }",
4658        ] {
4659            let (base, d) = computed_with_env(sheet, &Env::default());
4660            assert!(d.is_empty(), "{d:?}");
4661            let underline = base.text.underline.expect("an underline");
4662            assert_eq!(underline.thickness, gpui::px(2.0), "{sheet}");
4663            assert!(underline.color.is_some_and(|c| c.s > 0.9), "{sheet}: {underline:?}");
4664        }
4665        let (base, _) = computed_with_env(
4666            ".box { text-decoration-color: #ff0000 } .box { text-decoration: underline }",
4667            &Env::default(),
4668        );
4669        assert_eq!(base.text.underline.expect("an underline").color, None);
4670        let (base, _) = computed_with_env(
4671            ".box { text-decoration-thickness: 2px } .box { text-decoration-line: none }",
4672            &Env::default(),
4673        );
4674        assert_eq!(
4675            base.text
4676                .underline
4677                .expect("the cancelling underline")
4678                .thickness,
4679            gpui::px(0.0)
4680        );
4681        let engine = Engine::compile(".box { text-decoration-line: underline } .box:hover { text-decoration-color: #ff0000 }");
4682        let states = engine.compute(box_node(), None, &Env::default());
4683        assert_eq!(
4684            states.base.text.underline.expect("an underline").color,
4685            None
4686        );
4687    }
4688
4689    #[test]
4690    fn a_has_argument_with_an_interaction_state_is_refused() {
4691        for sheet in [
4692            ".box:has(input:focus-visible) { opacity: 0.5 }",
4693            ".box:has(.row:hover .icon) { opacity: 0.5 }",
4694        ] {
4695            let engine = Engine::compile(sheet);
4696            assert_eq!(
4697                engine
4698                    .compute(box_node(), None, &Env::default())
4699                    .base
4700                    .opacity,
4701                None,
4702                "{sheet}"
4703            );
4704        }
4705        let engine = Engine::compile(".box:has(input[disabled]) { opacity: 0.5 }");
4706        assert!(engine.diagnostics.is_empty(), "{:?}", engine.diagnostics);
4707    }
4708
4709    #[test]
4710    fn a_sheets_important_beats_a_normal_inline_declaration() {
4711        let sheet = ".box { opacity: 0.5 !important; font-size: 20px !important }";
4712        let base = base_with_inline(sheet, "opacity: 0.9; font-size: 10px");
4713        assert_eq!(base.opacity, Some(0.5));
4714        assert_eq!(base.text.font_size, Some(gpui::px(20.0).into()));
4715        assert_eq!(
4716            base_with_inline(".box { opacity: 0.5 }", "opacity: 0.9").opacity,
4717            Some(0.9)
4718        );
4719        let base = base_with_inline(sheet, "opacity: 0.9 !important; font-size: 10px");
4720        assert_eq!(base.opacity, Some(0.9));
4721        assert_eq!(base.text.font_size, Some(gpui::px(20.0).into()));
4722    }
4723
4724    #[test]
4725    fn contain_paint_clips_and_the_other_containments_are_hints() {
4726        let computed = |css: &str| {
4727            let engine = Engine::compile(css);
4728            assert!(engine.diagnostics.is_empty(), "{:?}", engine.diagnostics);
4729            let mut diags = Vec::new();
4730            let states = engine.compute_node(
4731                box_node(),
4732                None,
4733                &Rc::new(Vars::default()),
4734                None,
4735                &Env::default(),
4736                &mut diags,
4737            );
4738            (states.extras.overflow_names(&states.base), diags)
4739        };
4740        for value in ["paint", "content", "layout paint style"] {
4741            let (overflow, d) = computed(&format!(".box {{ contain: {value} }}"));
4742            assert_eq!(overflow, ["clip", "clip"], "{value}");
4743            assert!(d.is_empty(), "{d:?}");
4744        }
4745        let (overflow, _) = computed(".box { contain: paint; overflow-y: auto }");
4746        assert_eq!(overflow, ["hidden", "auto"]);
4747        let (overflow, _) = computed(".box { contain: paint } .box { contain: none }");
4748        assert_eq!(overflow, ["visible", "visible"]);
4749        let (overflow, d) =
4750            computed(".box { contain: layout style; will-change: transform, opacity }");
4751        assert_eq!((overflow, d.len()), (["visible", "visible"], 0));
4752
4753        let (overflow, d) = computed(".box { contain: strict; width: 10px; height: 10px }");
4754        assert_eq!((overflow, d.len()), (["clip", "clip"], 0));
4755        for value in ["inline-size", "size"] {
4756            let (_, d) = computed(&format!(".box {{ contain: {value}; width: 10px }}"));
4757            assert!(d.is_empty(), "{d:?}");
4758        }
4759    }
4760
4761    fn hovered_opacity(css: &str, style: Option<&str>) -> Option<f32> {
4762        use gpui::Refineable as _;
4763        let engine = Engine::compile(css);
4764        let mut diags = Vec::new();
4765        let inline = style.map(|style| mapper::parse_inline_style(style, &mut diags));
4766        let states = engine.compute_node(
4767            box_node(),
4768            inline.as_ref(),
4769            &Rc::new(Vars::default()),
4770            None,
4771            &Env::default(),
4772            &mut diags,
4773        );
4774        let mut painted = (*states.base).clone();
4775        if let Some(hover) = &states.hover {
4776            painted.refine(hover);
4777        }
4778        painted.opacity
4779    }
4780
4781    #[test]
4782    fn a_state_rule_loses_to_a_stateless_one_that_outranks_it() {
4783        assert_eq!(
4784            hovered_opacity(".box { opacity: 0.9 } .box:hover { opacity: 0.5 }", None),
4785            Some(0.5)
4786        );
4787        let stronger = "div.box.box { opacity: 0.9 } .box:hover { opacity: 0.5 }";
4788        assert_eq!(hovered_opacity(stronger, None), Some(0.9));
4789        let later = ".box:hover { opacity: 0.5 } .box.box { opacity: 0.9 }";
4790        assert_eq!(hovered_opacity(later, None), Some(0.9));
4791        let important = ".box { opacity: 0.9 !important } .box.box:hover { opacity: 0.5 }";
4792        assert_eq!(hovered_opacity(important, None), Some(0.9));
4793        let both = ".box { opacity: 0.9 !important } .box:hover { opacity: 0.5 !important }";
4794        assert_eq!(hovered_opacity(both, None), Some(0.5));
4795        assert_eq!(
4796            hovered_opacity(".box:hover { opacity: 0.5 }", Some("opacity: 0.9")),
4797            Some(0.9)
4798        );
4799        let over_inline = ".box:hover { opacity: 0.5 !important }";
4800        assert_eq!(
4801            hovered_opacity(over_inline, Some("opacity: 0.9")),
4802            Some(0.5)
4803        );
4804        let engine =
4805            Engine::compile(".box:hover { opacity: 0.5; width: 10px } .box.box { opacity: 0.9 }");
4806        let hover = engine
4807            .compute(box_node(), None, &Env::default())
4808            .hover
4809            .expect("a hover rung");
4810        assert_eq!(hover.size.width, Some(gpui::px(10.0).into()));
4811    }
4812
4813    #[test]
4814    fn object_fit_on_a_state_selector_applies_unconditionally() {
4815        let engine = Engine::compile(".box:hover { object-fit: cover }");
4816        assert_eq!(
4817            engine
4818                .compute(box_node(), None, &Env::default())
4819                .extras
4820                .object_fit,
4821            Some(ObjectFit::Cover)
4822        );
4823    }
4824
4825    fn drag_of(css: &str) -> Option<WindowDrag> {
4826        Engine::compile(css)
4827            .compute(box_node(), None, &Env::default())
4828            .extras
4829            .window_drag
4830    }
4831
4832    #[test]
4833    fn every_window_drag_spelling_parses_without_an_advisory() {
4834        for (css, want) in [
4835            ("window-drag: move", WindowDrag::Move),
4836            ("window-drag: none", WindowDrag::None),
4837            ("app-region: drag", WindowDrag::Move),
4838            ("app-region: no-drag", WindowDrag::None),
4839            ("-webkit-app-region: drag", WindowDrag::Move),
4840            ("-webkit-app-region: no-drag", WindowDrag::None),
4841        ] {
4842            let engine = Engine::compile(&format!(".box {{ {css} }}"));
4843            assert!(
4844                engine.diagnostics.is_empty(),
4845                "{css}: {:?}",
4846                engine.diagnostics
4847            );
4848            assert_eq!(
4849                engine
4850                    .compute(box_node(), None, &Env::default())
4851                    .extras
4852                    .window_drag,
4853                Some(want),
4854                "{css}"
4855            );
4856        }
4857    }
4858
4859    #[test]
4860    fn window_drag_folds_by_specificity_and_importance() {
4861        assert_eq!(
4862            drag_of(".box { window-drag: move } div.box { app-region: no-drag }"),
4863            Some(WindowDrag::None)
4864        );
4865        assert_eq!(
4866            drag_of("div.box { window-drag: none } .box { window-drag: move !important }"),
4867            Some(WindowDrag::Move)
4868        );
4869    }
4870
4871    #[test]
4872    fn window_control_does_not_fold_into_the_custom_property_map() {
4873        let mut diags = Vec::new();
4874        let engine = Engine::compile(".box { --window-control: close; --tw-shadow: 0 0 0 red }");
4875        assert!(engine.diagnostics.is_empty(), "{:?}", engine.diagnostics);
4876        let computed = engine.compute_node(
4877            box_node(),
4878            None,
4879            &Rc::new(Vars::default()),
4880            None,
4881            &Env::default(),
4882            &mut diags,
4883        );
4884        assert_eq!(computed.extras.window_control, Some(WindowControl::Close));
4885        assert_eq!(computed.vars.get(mapper::WINDOW_CONTROL), None);
4886        assert!(
4887            computed.vars.get("--tw-shadow").is_some(),
4888            "{:?}",
4889            computed.vars
4890        );
4891    }
4892
4893    fn computed_with_env(css: &str, env: &Env) -> (Rc<StyleRefinement>, Vec<String>) {
4894        let engine = Engine::compile(css);
4895        let mut diags = engine.diagnostics.clone();
4896        let states = engine.compute_node(
4897            box_node(),
4898            None,
4899            &Rc::new(Vars::default()),
4900            None,
4901            env,
4902            &mut diags,
4903        );
4904        (states.base, diags)
4905    }
4906
4907    #[test]
4908    fn drawer_pseudo_inset_initial_and_variable_fallback_reset_to_auto() {
4909        let engine = Engine::compile(
4910            ".box::after { content: \"\"; inset: 12px } \
4911             [data-vaul-drawer][data-vaul-drawer-direction=bottom]::after { \
4912                 top: 100%; bottom: initial; left: 0; right: 0; height: 200% } \
4913             .box { bottom: 16px; bottom: var(--missing-edge, initial) }",
4914        );
4915        let mut diagnostics = engine.diagnostics.clone();
4916        let states = engine.compute_node(
4917            Node {
4918                tag: "div",
4919                class: "box",
4920                attrs: &[
4921                    ("data-vaul-drawer", ""),
4922                    ("data-vaul-drawer-direction", "bottom"),
4923                ],
4924            },
4925            None,
4926            &Rc::new(Vars::default()),
4927            None,
4928            &Env::default(),
4929            &mut diagnostics,
4930        );
4931        assert!(diagnostics.is_empty(), "{diagnostics:?}");
4932        assert_eq!(states.base.inset.bottom, Some(gpui::Length::Auto));
4933        let after = states.after.expect("the drawer extension is generated");
4934        assert_eq!(after.style.inset.top, Some(gpui::relative(1.0).into()));
4935        assert_eq!(after.style.inset.bottom, Some(gpui::Length::Auto));
4936        assert_eq!(after.style.inset.left, Some(gpui::px(0.0).into()));
4937        assert_eq!(after.style.inset.right, Some(gpui::px(0.0).into()));
4938    }
4939
4940    fn titlebar_env(x: f32, y: f32, w: f32, h: f32) -> Env {
4941        Env {
4942            titlebar_area: Some([x, y, w, h]),
4943            ..Env::default()
4944        }
4945    }
4946
4947    #[test]
4948    fn env_titlebar_area_resolves_from_the_window_state() {
4949        let (base, diags) = computed_with_env(
4950            ".box { height: env(titlebar-area-height, 32px); width: env(titlebar-area-width) }",
4951            &titlebar_env(0.0, 0.0, 940.0, 36.0),
4952        );
4953        assert!(diags.is_empty(), "{diags:?}");
4954        assert_eq!(base.size.height, Some(gpui::px(36.0).into()));
4955        assert_eq!(base.size.width, Some(gpui::px(940.0).into()));
4956
4957        let (base, _) = computed_with_env(
4958            ".box { height: env(titlebar-area-height) }",
4959            &titlebar_env(0.0, 0.0, 940.0, 48.0),
4960        );
4961        assert_eq!(base.size.height, Some(gpui::px(48.0).into()));
4962    }
4963
4964    #[test]
4965    fn env_titlebar_area_x_is_a_real_offset_not_always_zero() {
4966        let (base, diags) = computed_with_env(
4967            ".box { margin-left: env(titlebar-area-x) }",
4968            &titlebar_env(78.0, 0.0, 862.0, 28.0),
4969        );
4970        assert!(diags.is_empty(), "{diags:?}");
4971        assert_eq!(base.margin.left, Some(gpui::px(78.0).into()));
4972    }
4973
4974    #[test]
4975    fn env_titlebar_area_is_undefined_when_the_overlay_is_hidden() {
4976        let hidden = Env {
4977            titlebar_area: None,
4978            ..Env::default()
4979        };
4980        let (base, diags) = computed_with_env(
4981            ".box { height: env(titlebar-area-height, 40px); padding-left: env(titlebar-area-x, 3px) }",
4982            &hidden,
4983        );
4984        assert!(diags.is_empty(), "{diags:?}");
4985        assert_eq!(base.size.height, Some(gpui::px(40.0).into()));
4986        assert_eq!(base.padding.left, Some(gpui::px(3.0).into()));
4987
4988        let (base, diags) =
4989            computed_with_env(".box { height: env(titlebar-area-height) }", &hidden);
4990        assert!(diags.is_empty(), "{diags:?}");
4991        assert_eq!(base.size.height, None);
4992    }
4993
4994    #[test]
4995    fn env_safe_area_insets_resolve_to_zero() {
4996        let (base, diags) = computed_with_env(
4997            ".box { padding-left: env(safe-area-inset-left); \
4998             padding-bottom: env(safe-area-inset-bottom) }",
4999            &Env::default(),
5000        );
5001        assert!(diags.is_empty(), "{diags:?}");
5002        assert_eq!(base.padding.left, Some(gpui::px(0.0).into()));
5003        assert_eq!(base.padding.bottom, Some(gpui::px(0.0).into()));
5004    }
5005
5006    #[test]
5007    fn drawer_background_transform_resolves_safe_area_calc() {
5008        let (style, diagnostics) = computed_with_env(
5009            ".box { transform: scale(0.96) translate3d(0, calc(env(safe-area-inset-top) + 14px), 0); \
5010             transition: transform .5s cubic-bezier(.32,.72,0,1) }",
5011            &Env::default(),
5012        );
5013        let transform = style
5014            .vn_transform
5015            .expect("the background transform is retained");
5016        assert_eq!(transform.translate.1, gpui::TransformLength::Pixels(13.44));
5017        assert!((transform.scale.0 - 0.96).abs() < 1e-6);
5018        assert!((transform.scale.1 - 0.96).abs() < 1e-6);
5019        let bounds = gpui::Bounds::new(
5020            gpui::point(gpui::px(20.0), gpui::px(30.0)),
5021            gpui::size(gpui::px(200.0), gpui::px(100.0)),
5022        );
5023        let matrix = transform.to_matrix(bounds, 1.0);
5024        let centre = matrix.apply(bounds.center());
5025        assert!((f32::from(centre.x) - 120.0).abs() < 0.001);
5026        assert!((f32::from(centre.y) - 93.44).abs() < 0.001);
5027        let corner = matrix.apply(bounds.origin);
5028        assert!((f32::from(corner.x) - 24.0).abs() < 0.001);
5029        assert!((f32::from(corner.y) - 45.44).abs() < 0.001);
5030        assert!(diagnostics.is_empty(), "{diagnostics:?}");
5031    }
5032
5033    #[test]
5034    fn an_unknown_env_uses_its_fallback_and_otherwise_drops_the_declaration() {
5035        let (base, diags) = computed_with_env(
5036            ".box { height: env(keyboard-inset-height, 12px) }",
5037            &Env::default(),
5038        );
5039        assert!(diags.is_empty(), "{diags:?}");
5040        assert_eq!(base.size.height, Some(gpui::px(12.0).into()));
5041
5042        let (base, _) = computed_with_env(
5043            ".box { height: env(keyboard-inset-height) }",
5044            &Env::default(),
5045        );
5046        assert_eq!(base.size.height, None);
5047    }
5048
5049    #[test]
5050    fn env_and_var_nest_in_each_others_fallbacks_and_in_custom_properties() {
5051        let (base, diags) = computed_with_env(
5052            ".box { --bar: env(titlebar-area-height); height: var(--bar); \
5053             padding-top: var(--nope, env(titlebar-area-height)); \
5054             margin-top: env(nope, var(--bar)) }",
5055            &titlebar_env(0.0, 0.0, 800.0, 40.0),
5056        );
5057        assert!(diags.is_empty(), "{diags:?}");
5058        assert_eq!(base.size.height, Some(gpui::px(40.0).into()));
5059        assert_eq!(base.padding.top, Some(gpui::px(40.0).into()));
5060        assert_eq!(base.margin.top, Some(gpui::px(40.0).into()));
5061    }
5062
5063    struct Doc {
5064        nodes: Vec<(
5065            &'static str,
5066            &'static str,
5067            usize,
5068            Vec<(&'static str, &'static str)>,
5069        )>,
5070    }
5071
5072    #[derive(Clone, Copy)]
5073    struct DocRef<'d> {
5074        doc: &'d Doc,
5075        i: usize,
5076    }
5077
5078    impl<'d> DocRef<'d> {
5079        fn siblings(&self) -> Vec<usize> {
5080            let parent = self.doc.nodes[self.i].2;
5081            (0..self.doc.nodes.len())
5082                .filter(|&j| j != 0 && self.doc.nodes[j].2 == parent)
5083                .collect()
5084        }
5085    }
5086
5087    impl<'d> MatchDom for DocRef<'d> {
5088        fn key(&self) -> u64 {
5089            self.i as u64
5090        }
5091        fn parent(&self) -> Option<Self> {
5092            let p = self.doc.nodes[self.i].2;
5093            (p != 0).then(|| DocRef {
5094                doc: self.doc,
5095                i: p,
5096            })
5097        }
5098        fn prev_sibling(&self) -> Option<Self> {
5099            let sibs = self.siblings();
5100            let pos = sibs.iter().position(|&j| j == self.i)?;
5101            (pos > 0).then(|| DocRef {
5102                doc: self.doc,
5103                i: sibs[pos - 1],
5104            })
5105        }
5106        fn next_sibling(&self) -> Option<Self> {
5107            let sibs = self.siblings();
5108            let pos = sibs.iter().position(|&j| j == self.i)?;
5109            sibs.get(pos + 1).map(|&j| DocRef {
5110                doc: self.doc,
5111                i: j,
5112            })
5113        }
5114        fn has_tag(&self, name: &str) -> bool {
5115            self.doc.nodes[self.i].0 == name
5116        }
5117        fn tag_eq(&self, other: &Self) -> bool {
5118            self.doc.nodes[self.i].0 == other.doc.nodes[other.i].0
5119        }
5120        fn has_class(&self, name: &str) -> bool {
5121            self.doc.nodes[self.i]
5122                .1
5123                .split_whitespace()
5124                .any(|c| c == name)
5125        }
5126        fn tag_name(&self) -> &str {
5127            self.doc.nodes[self.i].0
5128        }
5129        fn each_class(&self, f: &mut dyn FnMut(&str)) {
5130            for c in self.doc.nodes[self.i].1.split_whitespace() {
5131                f(c);
5132            }
5133        }
5134        fn has_scope(&self, _name: &str) -> bool {
5135            false
5136        }
5137        fn attr(&self, name: &str) -> Option<&str> {
5138            self.doc.nodes[self.i]
5139                .3
5140                .iter()
5141                .find(|(k, _)| *k == name)
5142                .map(|(_, v)| *v)
5143        }
5144        fn is_empty(&self) -> bool {
5145            !self.doc.nodes.iter().any(|n| n.2 == self.i)
5146        }
5147        fn is_root(&self) -> bool {
5148            self.doc.nodes[self.i].2 == 0
5149        }
5150        fn each_child(&self, f: &mut dyn FnMut(Self)) {
5151            for j in 1..self.doc.nodes.len() {
5152                if self.doc.nodes[j].2 == self.i {
5153                    f(DocRef {
5154                        doc: self.doc,
5155                        i: j,
5156                    });
5157                }
5158            }
5159        }
5160    }
5161
5162    fn doc() -> Doc {
5163        Doc {
5164            nodes: vec![
5165                ("", "", 0, vec![]),
5166                ("div", "nav", 0, vec![]),
5167                ("a", "tab router-link-active", 1, vec![("href", "/")]),
5168                ("a", "tab", 1, vec![("href", "/list")]),
5169                ("input", "field", 1, vec![("disabled", "true")]),
5170            ],
5171        }
5172    }
5173
5174    fn refs(d: &Doc) -> Vec<DocRef<'_>> {
5175        (1..d.nodes.len()).map(|i| DocRef { doc: d, i }).collect()
5176    }
5177
5178    #[test]
5179    fn the_index_files_a_rule_where_its_subject_or_parent_must_carry_a_key() {
5180        let engine = Engine::compile(concat!(
5181            ".a::before { content: \"x\" }\n",
5182            ":root { --x: 1px }\n",
5183            ".p > :not([hidden]) ~ :not([hidden]) { margin-left: 1px }\n",
5184            "ul > * { margin-top: 1px }\n",
5185            ".p > * + * { margin-top: 2px }\n",
5186            ".a * { color: red }\n",
5187            "* { margin: 0 }\n",
5188            ".a ~ * { color: blue }\n",
5189            ":is(.x) > * { color: green }\n",
5190            "#i > * { color: black }\n",
5191            ".b::placeholder { color: gray }\n",
5192            "[data-x] { color: white }\n",
5193        ));
5194        let ix = &engine.index;
5195        let names = |v: Option<&Vec<u32>>| -> Vec<String> {
5196            v.map_or(vec![], |v| {
5197                v.iter()
5198                    .map(|&i| sel_text(&engine.rules[i as usize].selector))
5199                    .collect()
5200            })
5201        };
5202        assert_eq!(names(ix.by_class.get("a")), [".a:before"]);
5203        assert_eq!(names(ix.by_class.get("b")), [".b::placeholder"]);
5204        assert_eq!(names(Some(&ix.root)), [":root"]);
5205        assert_eq!(
5206            names(ix.by_parent_class.get("p")),
5207            [".p > :not([hidden]) ~ :not([hidden])", ".p > * + *"]
5208        );
5209        assert_eq!(names(ix.by_parent_tag.get("ul")), ["ul > *"]);
5210        assert_eq!(names(ix.by_parent_id.get("i")), ["#i > *"]);
5211        assert_eq!(
5212            names(Some(&ix.any)),
5213            [
5214                ":where([hidden])",
5215                ".a *",
5216                "*",
5217                ".a ~ *",
5218                ".x > *",
5219                "[data-x]"
5220            ]
5221        );
5222    }
5223
5224    #[test]
5225    fn the_index_hands_back_exactly_what_matching_every_rule_would() {
5226        let css = concat!(
5227            ":root { --x: 1px }\n",
5228            ".app:root { --y: 1px }\n",
5229            ".a::before { content: \"a\" }\n",
5230            ".a:hover::after { content: \"h\" }\n",
5231            "::before { width: 1px }\n",
5232            ".p > :not([hidden]) ~ :not([hidden]) { margin-left: 1px }\n",
5233            ".p > * + * { margin-top: 1px }\n",
5234            ".p > *:first-child { margin-top: 2px }\n",
5235            "ul > * { padding: 1px }\n",
5236            "ul > li + li { padding: 2px }\n",
5237            "#i > * { color: black }\n",
5238            "#i b { color: gray }\n",
5239            ".a * { color: red }\n",
5240            ".app .p > span { color: green }\n",
5241            "* + span { color: blue }\n",
5242            "span ~ .a { color: white }\n",
5243            ":is(.p, ul) > * { margin: 3px }\n",
5244            ":not(.p) > span { margin: 4px }\n",
5245            "[hidden] { display: none }\n",
5246            "* { box-sizing: border-box }\n",
5247            ".missing > * { margin: 5px }\n",
5248        );
5249        let indexed = Engine::compile(css);
5250        let mut every = Engine::compile(css);
5251        every.index.enabled = false;
5252        let d = Doc {
5253            nodes: vec![
5254                ("", "", 0, vec![]),
5255                ("div", "app", 0, vec![]),
5256                ("div", "p", 1, vec![]),
5257                ("span", "", 2, vec![]),
5258                ("span", "", 2, vec![("hidden", "")]),
5259                ("span", "a", 2, vec![]),
5260                ("ul", "", 1, vec![]),
5261                ("li", "", 6, vec![]),
5262                ("li", "a", 6, vec![]),
5263                ("div", "", 1, vec![("id", "i")]),
5264                ("b", "", 9, vec![]),
5265                ("p", "a", 1, vec![]),
5266                ("em", "", 11, vec![]),
5267            ],
5268        };
5269        let env = Env::default();
5270        let selectors = |e: &Engine, n: DocRef<'_>| {
5271            let mut v: Vec<(u32, String)> = e
5272                .matched_rules(n, &env)
5273                .into_iter()
5274                .map(|r| (r.order, r.selector))
5275                .collect();
5276            v.sort();
5277            v
5278        };
5279        let mut matched_somewhere = 0;
5280        for n in refs(&d) {
5281            let want = selectors(&every, n);
5282            matched_somewhere += want.len();
5283            assert_eq!(selectors(&indexed, n), want, "node {}", n.i);
5284        }
5285        assert!(
5286            matched_somewhere > 30,
5287            "the sheet exercises the tree ({matched_somewhere} matches)"
5288        );
5289    }
5290
5291    fn cascade_both(css: &str, d: &Doc, env: &Env) -> (Vec<ComputedStates>, Vec<ComputedStates>) {
5292        let cached = Engine::compile(css);
5293        let mut plain = Engine::compile(css);
5294        plain.share = false;
5295        assert!(
5296            cached.share,
5297            "SK_CSS_NO_SHARE is set in the test environment"
5298        );
5299        let run = |e: &Engine| {
5300            let root_vars = Rc::new(Vars::default());
5301            let mut out = vec![ComputedStates::default()];
5302            for i in 1..d.nodes.len() {
5303                let p = d.nodes[i].2;
5304                let (vars, color) = if p == 0 {
5305                    (root_vars.clone(), None)
5306                } else {
5307                    (out[p].vars.clone(), out[p].color)
5308                };
5309                let mut diags = Vec::new();
5310                out.push(e.compute_node(DocRef { doc: d, i }, None, &vars, color, env, &mut diags));
5311            }
5312            out
5313        };
5314        let (with, without) = (run(&cached), run(&plain));
5315        for i in 1..d.nodes.len() {
5316            assert_eq!(
5317                with[i], without[i],
5318                "node {i} folds the same with the cache as without"
5319            );
5320        }
5321        (with, without)
5322    }
5323
5324    fn shared(s: &[ComputedStates], a: usize, b: usize) -> bool {
5325        Rc::ptr_eq(&s[a].base, &s[b].base)
5326    }
5327
5328    #[test]
5329    fn the_cache_folds_once_for_cousins() {
5330        let css = ".row { padding: 4px } .label { color: #ff0000; opacity: 0.5 } \
5331                   .meta { --gap: 3px } .meta > .t { margin-left: var(--gap); border-color: currentColor }";
5332        let d = Doc {
5333            nodes: vec![
5334                ("", "", 0, vec![]),
5335                ("div", "list", 0, vec![]),
5336                ("div", "row", 1, vec![]),
5337                ("span", "label", 2, vec![]),
5338                ("div", "meta", 2, vec![]),
5339                ("span", "t", 4, vec![]),
5340                ("div", "row", 1, vec![]),
5341                ("span", "label", 6, vec![]),
5342                ("div", "meta", 6, vec![]),
5343                ("span", "t", 8, vec![]),
5344            ],
5345        };
5346        let (s, _) = cascade_both(css, &d, &Env::default());
5347        for (a, b) in [(2, 6), (3, 7), (4, 8), (5, 9)] {
5348            assert!(shared(&s, a, b), "node {b} takes node {a}'s fold");
5349        }
5350        assert_eq!(s[9].base.margin.left, Some(gpui::px(3.0).into()));
5351    }
5352
5353    #[test]
5354    fn the_cache_keeps_apart_what_a_selector_tells_apart() {
5355        type Nodes = Vec<(
5356            &'static str,
5357            &'static str,
5358            usize,
5359            Vec<(&'static str, &'static str)>,
5360        )>;
5361        let pair =
5362            |a: Vec<(&'static str, &'static str)>, b: Vec<(&'static str, &'static str)>| -> Nodes {
5363                vec![
5364                    ("", "", 0, vec![]),
5365                    ("div", "list", 0, vec![]),
5366                    ("div", "i", 1, a),
5367                    ("div", "i", 1, b),
5368                ]
5369            };
5370        let cases: Vec<(&str, &str, Nodes)> = vec![
5371            (
5372                "position",
5373                ".i:first-child { opacity: 0.5 }",
5374                pair(vec![], vec![]),
5375            ),
5376            (
5377                "nth-child",
5378                ".i:nth-child(2n) { opacity: 0.5 }",
5379                pair(vec![], vec![]),
5380            ),
5381            (
5382                "attribute",
5383                ".i[data-state=open] { opacity: 0.5 }",
5384                pair(vec![("data-state", "open")], vec![]),
5385            ),
5386            (
5387                "attribute presence",
5388                ".i:not([hidden]) { opacity: 0.5 }",
5389                pair(vec![], vec![("hidden", "")]),
5390            ),
5391            ("sibling", ".i + .i { opacity: 0.5 }", pair(vec![], vec![])),
5392            (
5393                "later sibling",
5394                ".i ~ .i { opacity: 0.5 }",
5395                pair(vec![], vec![]),
5396            ),
5397            (
5398                ":has()",
5399                ".i:has(.badge) { opacity: 0.5 }",
5400                vec![
5401                    ("", "", 0, vec![]),
5402                    ("div", "list", 0, vec![]),
5403                    ("div", "i", 1, vec![]),
5404                    ("div", "i", 1, vec![]),
5405                    ("b", "badge", 3, vec![]),
5406                ],
5407            ),
5408            (
5409                ":empty",
5410                ".i:empty { opacity: 0.5 }",
5411                vec![
5412                    ("", "", 0, vec![]),
5413                    ("div", "list", 0, vec![]),
5414                    ("div", "i", 1, vec![]),
5415                    ("div", "i", 1, vec![]),
5416                    ("b", "", 3, vec![]),
5417                ],
5418            ),
5419        ];
5420        for (what, rule, nodes) in cases {
5421            let css = format!(".i {{ opacity: 0.9; padding: 2px }} {rule}");
5422            let d = Doc { nodes };
5423            let (s, _) = cascade_both(&css, &d, &Env::default());
5424            assert!(
5425                !shared(&s, 2, 3),
5426                "{what}: the second element folds on its own"
5427            );
5428            assert_ne!(
5429                s[2].base.opacity, s[3].base.opacity,
5430                "{what}: and the two differ"
5431            );
5432        }
5433    }
5434
5435    #[test]
5436    fn the_cache_keeps_apart_what_the_parent_hands_down() {
5437        let css = ".p1 { --w: 10px; color: #ff0000 } .p2 { --w: 20px; color: #0000ff } \
5438                   .c { width: var(--w); border-color: currentColor }";
5439        let d = Doc {
5440            nodes: vec![
5441                ("", "", 0, vec![]),
5442                ("div", "list", 0, vec![]),
5443                ("div", "p1", 1, vec![]),
5444                ("div", "c", 2, vec![]),
5445                ("div", "p2", 1, vec![]),
5446                ("div", "c", 4, vec![]),
5447                ("div", "p1", 1, vec![]),
5448                ("div", "c", 6, vec![]),
5449            ],
5450        };
5451        let (s, _) = cascade_both(css, &d, &Env::default());
5452        assert!(!shared(&s, 3, 5));
5453        assert_ne!(s[3].base.size.width, s[5].base.size.width);
5454        assert_ne!(s[3].base.border_color, s[5].base.border_color);
5455        assert!(shared(&s, 3, 7), "and the same parent inputs again meet");
5456    }
5457
5458    #[test]
5459    fn the_cache_leaves_out_inline_styles_and_group_rules() {
5460        let css = ".group:hover .c { opacity: 0.5 } .c { padding: 2px } .d { padding: 3px }";
5461        let d = Doc {
5462            nodes: vec![
5463                ("", "", 0, vec![]),
5464                ("div", "list", 0, vec![]),
5465                ("div", "group", 1, vec![]),
5466                ("div", "c", 2, vec![]),
5467                ("div", "group", 1, vec![]),
5468                ("div", "c", 4, vec![]),
5469            ],
5470        };
5471        let (s, _) = cascade_both(css, &d, &Env::default());
5472        assert!(!shared(&s, 3, 5));
5473        assert_eq!(s[3].group_hover.as_ref().map(|g| g.0), Some(2));
5474        assert_eq!(s[5].group_hover.as_ref().map(|g| g.0), Some(4));
5475
5476        let engine = Engine::compile(css);
5477        let inline = parse_inline_style("opacity: 0.25", &mut Vec::new());
5478        let vars = Rc::new(Vars::default());
5479        let fold = |i: usize| {
5480            engine.compute_node(
5481                DocRef { doc: &d, i },
5482                Some(&inline),
5483                &vars,
5484                None,
5485                &Env::default(),
5486                &mut Vec::new(),
5487            )
5488        };
5489        let doc_d = Doc {
5490            nodes: vec![
5491                ("", "", 0, vec![]),
5492                ("div", "d", 0, vec![]),
5493                ("div", "d", 0, vec![]),
5494            ],
5495        };
5496        let (a, b) = (
5497            engine.compute_node(
5498                DocRef { doc: &doc_d, i: 1 },
5499                Some(&inline),
5500                &vars,
5501                None,
5502                &Env::default(),
5503                &mut Vec::new(),
5504            ),
5505            engine.compute_node(
5506                DocRef { doc: &doc_d, i: 2 },
5507                Some(&inline),
5508                &vars,
5509                None,
5510                &Env::default(),
5511                &mut Vec::new(),
5512            ),
5513        );
5514        assert!(
5515            !Rc::ptr_eq(&a.base, &b.base),
5516            "an inline style folds on its own"
5517        );
5518        assert_eq!(a, b);
5519        assert_eq!(fold(3).base.opacity, Some(0.25));
5520    }
5521
5522    #[test]
5523    fn the_cache_does_not_outlive_what_the_fold_read() {
5524        let node = |class| Node {
5525            tag: "div",
5526            class,
5527            attrs: &[],
5528        };
5529        let vars = Rc::new(Vars::default());
5530        let fold = |e: &Engine, class, env: &Env| {
5531            e.compute_node(node(class), None, &vars, None, env, &mut Vec::new())
5532        };
5533
5534        let engine = Engine::compile(".c { height: env(titlebar-area-height, 32px) }");
5535        let low = fold(&engine, "c", &titlebar_env(0.0, 0.0, 940.0, 36.0));
5536        let high = fold(&engine, "c", &titlebar_env(0.0, 0.0, 940.0, 48.0));
5537        assert_eq!(low.base.size.height, Some(gpui::px(36.0).into()));
5538        assert_eq!(high.base.size.height, Some(gpui::px(48.0).into()));
5539
5540        assert!(set_viewport_basis(1000.0, 800.0) || viewport_basis() == (1000.0, 800.0));
5541        let mut engine = Engine::compile(".c { width: 50vw }");
5542        assert_eq!(
5543            fold(&engine, "c", &Env::default()).base.size.width,
5544            Some(gpui::px(500.0).into())
5545        );
5546        assert!(set_viewport_basis(1200.0, 600.0));
5547        assert!(engine.rebase_viewport());
5548        assert_eq!(
5549            fold(&engine, "c", &Env::default()).base.size.width,
5550            Some(gpui::px(600.0).into())
5551        );
5552        set_viewport_basis(INITIAL_VIEWPORT_BASIS.0, INITIAL_VIEWPORT_BASIS.1);
5553
5554        let css = ".c { --w: 2rem; width: var(--w) }";
5555        let engine = Engine::compile(css);
5556        let before = fold(&engine, "c", &Env::default());
5557        let old = rem_basis();
5558        assert!(set_rem_basis(old + 4.0));
5559        let after = fold(&engine, "c", &Env::default());
5560        let mut plain = Engine::compile(css);
5561        plain.share = false;
5562        assert_eq!(
5563            after,
5564            fold(&plain, "c", &Env::default()),
5565            "a new rem basis folds again"
5566        );
5567        assert_ne!(before.base.size.width, after.base.size.width);
5568        set_rem_basis(old);
5569    }
5570
5571    #[test]
5572    fn content_none_takes_back_an_earlier_rules_box() {
5573        let engine = Engine::compile(
5574            r#".nav::before { content: "|" } .nav::before { content: none }
5575               .nav::after { content: none } .nav::after { content: "+" }"#,
5576        );
5577        let d = doc();
5578        let states = cascade(&engine, &d, &Env::default());
5579        assert!(states[0].before.is_none());
5580        assert_eq!(
5581            &*states[0].after.as_ref().expect("an ::after box").content,
5582            "+"
5583        );
5584    }
5585
5586    #[test]
5587    fn a_pseudo_element_rule_becomes_its_own_box() {
5588        let engine = Engine::compile(
5589            r#".nav::before { content: "|"; width: 2px; background-color: rgb(255 0 0) }"#,
5590        );
5591        assert!(engine.diagnostics.is_empty(), "{:?}", engine.diagnostics);
5592        let d = doc();
5593        let states = cascade(&engine, &d, &Env::default());
5594        let nav = &states[0];
5595        let before = nav.before.as_ref().expect("a ::before box");
5596        assert_eq!(&*before.content, "|");
5597        assert_eq!(before.style.size.width, Some(gpui::px(2.0).into()));
5598        assert!(before.style.background.is_some());
5599        assert_eq!(nav.base.size.width, None);
5600        assert_eq!(nav.base.background, None);
5601        assert!(nav.after.is_none());
5602    }
5603
5604    #[test]
5605    fn a_pseudo_element_without_content_generates_nothing() {
5606        let engine = Engine::compile(".nav::after { width: 2px }");
5607        let d = doc();
5608        let states = cascade(&engine, &d, &Env::default());
5609        assert!(states[0].after.is_none(), "no content, no box");
5610    }
5611
5612    #[test]
5613    fn pseudo_boxes_cascade_and_follow_attributes() {
5614        let engine = Engine::compile(
5615            r#"a::before { content: "-"; width: 1px }
5616               a.tab::before { width: 4px }
5617               a::after { content: "+" }
5618               a[href="/list"]::after { content: "!" }"#,
5619        );
5620        assert!(engine.diagnostics.is_empty(), "{:?}", engine.diagnostics);
5621        let d = doc();
5622        let states = cascade(&engine, &d, &Env::default());
5623        let first = &states[1];
5624        assert_eq!(
5625            first.before.as_ref().unwrap().style.size.width,
5626            Some(gpui::px(4.0).into())
5627        );
5628        assert_eq!(&*first.after.as_ref().unwrap().content, "+");
5629        let second = &states[2];
5630        assert_eq!(&*second.after.as_ref().unwrap().content, "!");
5631    }
5632
5633    #[test]
5634    fn a_state_qualified_pseudo_element_rule_generates_no_box_at_rest() {
5635        let engine = Engine::compile(r#".nav:hover::after { content: "x" }"#);
5636        let d = doc();
5637        assert!(cascade(&engine, &d, &Env::default())[0].after.is_none());
5638    }
5639
5640    #[test]
5641    fn control_parts_fold_custom_properties_and_state_styles() {
5642        let engine = Engine::compile(
5643            r#"input { --tip: rgb(1 2 3); --fill: 50% }
5644               input::-webkit-slider-runnable-track {
5645                 height: 4px; border-radius: 999px;
5646                 background: linear-gradient(90deg, var(--tip) var(--fill), transparent var(--fill))
5647               }
5648               input::-webkit-slider-thumb { width: 11px; height: 11px; background: var(--tip) }
5649               input:hover::-webkit-slider-thumb { width: 13px }
5650               input:focus-visible::-webkit-slider-thumb { border: 2px solid red }
5651               input::-webkit-color-swatch-wrapper { padding: 2px }
5652               input::-webkit-color-swatch { border: none; border-radius: 6px }"#,
5653        );
5654        assert!(engine.diagnostics.is_empty(), "{:?}", engine.diagnostics);
5655        let d = doc();
5656        let states = cascade(&engine, &d, &Env::default());
5657        let input = &states[3];
5658        let track = input.range_track.as_ref().unwrap();
5659        assert_eq!(track.base.size.height, Some(gpui::px(4.).into()));
5660        assert!(!track.extras.resolve_background_layers().is_empty());
5661        let thumb = input.range_thumb.as_ref().unwrap();
5662        assert_eq!(thumb.base.size.width, Some(gpui::px(11.).into()));
5663        assert!(thumb.base.background.is_some());
5664        let (hover, _) = thumb.resolve(false, true, false, false, false);
5665        assert_eq!(hover.size.width, Some(gpui::px(13.).into()));
5666        assert_eq!(
5667            hover.size.height, thumb.base.size.height,
5668            "state retains the base declarations"
5669        );
5670        let (focus, _) = thumb.resolve(false, false, true, true, true);
5671        assert_eq!(focus.border_widths.left, Some(gpui::px(2.).into()));
5672        assert!(input.color_swatch.is_some());
5673        assert!(input
5674            .color_swatch_wrapper
5675            .as_ref()
5676            .unwrap()
5677            .base
5678            .padding
5679            .left
5680            .is_some());
5681        assert!(
5682            input.base.size.height.is_none(),
5683            "parts must not style the input itself"
5684        );
5685    }
5686
5687    #[test]
5688    fn control_part_important_cascade_reaches_every_state() {
5689        let engine = Engine::compile(
5690            "input:hover::-moz-range-thumb { width: 30px } \
5691             input::-moz-range-thumb { width: 17px !important }",
5692        );
5693        let d = doc();
5694        let states = cascade(&engine, &d, &Env::default());
5695        let thumb = states[3].range_thumb.as_ref().unwrap();
5696        assert_eq!(thumb.base.size.width, Some(gpui::px(17.).into()));
5697        assert_eq!(
5698            thumb.resolve(false, true, false, false, false).0.size.width,
5699            thumb.base.size.width
5700        );
5701    }
5702
5703    #[test]
5704    fn placeholder_folds_into_its_own_refinement() {
5705        let engine = Engine::compile("input::placeholder { color: rgb(1 2 3) }");
5706        assert!(engine.diagnostics.is_empty(), "{:?}", engine.diagnostics);
5707        let d = doc();
5708        let states = cascade(&engine, &d, &Env::default());
5709        let input = &states[3];
5710        assert!(input.placeholder.as_ref().unwrap().text.color.is_some());
5711        assert_eq!(input.base.text.color, None, "the input itself is untouched");
5712    }
5713
5714    #[test]
5715    fn file_selector_button_folds_into_its_own_refinement() {
5716        let engine = Engine::compile(
5717            ".file\\:border-0::file-selector-button { border-width: 0px } \
5718             input::file-selector-button { background-color: rgb(1 2 3); padding-left: 12px }",
5719        );
5720        assert!(engine.diagnostics.is_empty(), "{:?}", engine.diagnostics);
5721        let d = doc();
5722        let states = cascade(&engine, &d, &Env::default());
5723        let input = &states[3];
5724        let button = input
5725            .file_selector_button
5726            .as_ref()
5727            .expect("the rule reaches the input's button");
5728        assert!(button.background.is_some());
5729        assert!(button.padding.left.is_some());
5730        assert!(
5731            input.base.background.is_none(),
5732            "the input itself is untouched"
5733        );
5734        assert!(
5735            states[0].file_selector_button.is_none(),
5736            "only an element a rule matched gets one"
5737        );
5738    }
5739
5740    #[test]
5741    fn file_selector_button_rules_are_listed_with_their_pseudo() {
5742        let engine = Engine::compile("input::-webkit-file-upload-button { color: red }");
5743        assert!(
5744            engine.diagnostics.is_empty(),
5745            "the -webkit- spelling is the same pseudo: {:?}",
5746            engine.diagnostics
5747        );
5748        let d = doc();
5749        let rules = engine.matched_rules(DocRef { doc: &d, i: 4 }, &Env::default());
5750        assert_eq!(rules.len(), 1, "{rules:?}");
5751        assert_eq!(rules[0].pseudo, Some("::file-selector-button"));
5752    }
5753
5754    #[test]
5755    fn html_and_body_rules_reach_the_document_root() {
5756        let engine = Engine::compile(
5757            "html { --fg: rgb(1 2 3) } \
5758             body { opacity: 0.5 } \
5759             :root { flex-grow: 3 } \
5760             html.dark { --fg: rgb(9 9 9) } \
5761             .tab { color: var(--fg) }",
5762        );
5763        assert!(engine.diagnostics.is_empty(), "{:?}", engine.diagnostics);
5764        let mut d = doc();
5765        d.nodes[1] = ("root", "dark", 0, vec![]);
5766        let states = cascade(&engine, &d, &Env::default());
5767        let root = &states[0];
5768        assert_eq!(root.base.opacity, Some(0.5), "a `body` rule matched");
5769        assert_eq!(root.base.flex_grow, Some(3.0), "a `:root` rule matched");
5770        assert_eq!(
5771            root.vars.get("--fg").as_deref(),
5772            Some("#090909"),
5773            "the .dark override won"
5774        );
5775        let tab = &states[1];
5776        assert!(
5777            tab.base.text.color.is_some(),
5778            "the palette reached a descendant"
5779        );
5780    }
5781
5782    #[test]
5783    fn a_class_on_the_root_is_matched_by_the_compound_form_not_the_descendant_one() {
5784        let opacity = |css: &str| {
5785            let engine = Engine::compile(css);
5786            assert!(engine.diagnostics.is_empty(), "{:?}", engine.diagnostics);
5787            let mut d = doc();
5788            d.nodes[1] = ("root", "suspended", 0, vec![]);
5789            cascade(&engine, &d, &Env::default())[0].base.opacity
5790        };
5791        let base = "body:not(.oled) { opacity: 0.1 !important } ";
5792        assert_eq!(
5793            opacity(&format!(
5794                "{base}html.suspended body:not(.oled) {{ opacity: 0.5 !important }}"
5795            )),
5796            Some(0.1)
5797        );
5798        assert_eq!(
5799            opacity(&format!(
5800                "{base}html.suspended body:not(.oled), body.suspended:not(.oled) {{ opacity: 0.5 !important }}"
5801            )),
5802            Some(0.5)
5803        );
5804    }
5805
5806    #[test]
5807    fn query_all_uses_the_real_matcher() {
5808        let d = doc();
5809        let c = refs(&d);
5810        assert_eq!(query_all(".tab", &c).unwrap().matched, vec![1, 2]);
5811        assert_eq!(
5812            query_all(".tab.router-link-active", &c).unwrap().matched,
5813            vec![1]
5814        );
5815        assert_eq!(query_all(".nav a", &c).unwrap().matched, vec![1, 2]);
5816        assert_eq!(query_all("input:disabled", &c).unwrap().matched, vec![3]);
5817        assert_eq!(query_all("[href=\"/list\"]", &c).unwrap().matched, vec![2]);
5818        assert_eq!(
5819            query_all("input, .router-link-active", &c).unwrap().matched,
5820            vec![1, 3]
5821        );
5822        assert!(query_all(".nope", &c).unwrap().matched.is_empty());
5823    }
5824
5825    #[test]
5826    fn query_all_refuses_unsupported_selectors_like_the_cascade_does() {
5827        let d = doc();
5828        let c = refs(&d);
5829        assert!(query_all(".nav:has(.tab)", &c).is_err());
5830        assert!(query_all("a::first-line", &c).is_err());
5831        assert!(query_all("a::before", &c).is_ok());
5832        assert!(query_all("a:visited", &c).is_err());
5833        assert!(query_all(".a { color: red } .b", &c).is_err());
5834    }
5835
5836    fn nested_doc() -> Doc {
5837        Doc {
5838            nodes: vec![
5839                ("", "", 0, vec![]),
5840                ("div", "page", 0, vec![]),
5841                ("div", "nav", 1, vec![]),
5842                ("a", "tab", 2, vec![]),
5843                ("div", "inner", 2, vec![]),
5844                ("a", "tab", 4, vec![]),
5845            ],
5846        }
5847    }
5848
5849    #[test]
5850    fn scope_anchors_a_query_at_the_element_it_was_called_on() {
5851        let d = nested_doc();
5852        let all = refs(&d);
5853        let nav = all[1];
5854        let under_nav: Vec<DocRef<'_>> = all[2..].to_vec();
5855
5856        let r = query_all_in(":scope > .tab", &under_nav, Some(nav)).unwrap();
5857        assert_eq!(r.matched, vec![0], "only the .tab that is a child of .nav");
5858
5859        let r = query_all_in(":scope .tab", &under_nav, Some(nav)).unwrap();
5860        assert_eq!(r.matched, vec![0, 2]);
5861
5862        let r = query_all(":scope > .tab", &under_nav).unwrap();
5863        assert!(r.matched.is_empty(), "unscoped, `:scope` is the root");
5864    }
5865
5866    #[test]
5867    fn scope_with_no_scoping_root_is_the_document_element() {
5868        let d = nested_doc();
5869        let all = refs(&d);
5870        let nav = all[1];
5871        assert_eq!(
5872            query_all_in(":scope", &[nav], Some(nav)).unwrap().matched,
5873            vec![0]
5874        );
5875        assert!(query_all_in(":scope", &[all[2]], Some(nav))
5876            .unwrap()
5877            .matched
5878            .is_empty());
5879        assert_eq!(query_all(":scope", &all).unwrap().matched, vec![0]);
5880    }
5881
5882    #[test]
5883    fn a_scope_rule_in_a_sheet_styles_the_root() {
5884        let engine = Engine::compile(":scope { background-color: rgb(1 2 3) }");
5885        assert!(engine.diagnostics.is_empty(), "{:?}", engine.diagnostics);
5886        let d = themed_doc();
5887        let states = cascade(&engine, &d, &Env::default());
5888        assert!(states[0].base.background.is_some(), "the root is styled");
5889        assert!(
5890            states[1].base.background.is_none(),
5891            "and nothing below it is"
5892        );
5893    }
5894
5895    fn themed_doc() -> Doc {
5896        Doc {
5897            nodes: vec![
5898                ("", "", 0, vec![]),
5899                ("root", "", 0, vec![]),
5900                ("div", "page", 1, vec![]),
5901                ("button", "btn", 2, vec![]),
5902            ],
5903        }
5904    }
5905
5906    fn cascade(engine: &Engine, doc: &Doc, env: &Env) -> Vec<ComputedStates> {
5907        let mut out: Vec<ComputedStates> = Vec::new();
5908        let mut diagnostics = Vec::new();
5909        for i in 1..doc.nodes.len() {
5910            let parent = doc.nodes[i].2;
5911            let parent_vars = if parent == 0 {
5912                Rc::new(Vars::default())
5913            } else {
5914                out[parent - 1].vars.clone()
5915            };
5916            out.push(engine.compute_node(
5917                DocRef { doc, i },
5918                None,
5919                &parent_vars,
5920                None,
5921                env,
5922                &mut diagnostics,
5923            ));
5924        }
5925        out
5926    }
5927
5928    #[test]
5929    fn custom_properties_inherit_down_the_tree_and_substitute() {
5930        let engine = Engine::compile(":root { --fg: rgb(10 20 30) } .btn { color: var(--fg) }");
5931        assert!(engine.diagnostics.is_empty(), "{:?}", engine.diagnostics);
5932        let d = themed_doc();
5933        let states = cascade(&engine, &d, &Env::default());
5934        assert_eq!(states[0].vars.get("--fg"), Some("#0a141e"));
5935        assert!(Rc::ptr_eq(&states[0].vars, &states[2].vars));
5936        assert!(states[2].base.text.color.is_some());
5937    }
5938
5939    #[test]
5940    fn an_svg_paint_resolves_through_var() {
5941        let engine = Engine::compile(
5942            ".page { --surface: #06080b } .btn { fill: var(--surface); stroke: rgba(219, 232, 255, 0.17) } \
5943             button { filter: drop-shadow(0 18px 30px rgba(0, 0, 0, 0.45)) } .page .btn { stroke-width: 1 }",
5944        );
5945        assert!(engine.diagnostics.is_empty(), "{:?}", engine.diagnostics);
5946        let states = cascade(&engine, &themed_doc(), &Env::default());
5947        let fill = states[2].extras.fill.expect("fill computed");
5948        assert_eq!(fill.as_attr(), "rgb(6,8,11)");
5949        assert_eq!(
5950            states[2].extras.stroke.expect("stroke computed").as_attr(),
5951            "rgba(219,232,255,0.169)"
5952        );
5953        let shadow = states[2].extras.drop_shadow.expect("drop-shadow computed");
5954        assert_eq!((shadow.dx, shadow.dy, shadow.blur), (0.0, 18.0, 30.0));
5955        let engine = Engine::compile(
5956            ".btn { filter: drop-shadow(0 1px 2px #000) } .page .btn { filter: none }",
5957        );
5958        let states = cascade(&engine, &themed_doc(), &Env::default());
5959        assert_eq!(states[2].extras.drop_shadow, None);
5960    }
5961
5962    #[test]
5963    fn a_state_rule_does_not_paint_an_svg_at_rest() {
5964        let engine = Engine::compile(
5965            ".btn { fill: #f00 } .btn:hover { fill: #00f; stroke-width: 3 } \
5966             .page:hover .btn { stroke: var(--x, #0f0) }",
5967        );
5968        let d = themed_doc();
5969        let mut diagnostics = Vec::new();
5970        let vars = Rc::new(Vars::default());
5971        let btn = engine.compute_node(
5972            DocRef { doc: &d, i: 3 },
5973            None,
5974            &vars,
5975            None,
5976            &Env::default(),
5977            &mut diagnostics,
5978        );
5979        assert_eq!(
5980            btn.extras.fill.map(|p| p.as_attr().into_owned()).as_deref(),
5981            Some("rgb(255,0,0)")
5982        );
5983        assert_eq!(btn.extras.svg_presentation, None);
5984        assert_eq!(btn.extras.stroke, None);
5985    }
5986
5987    #[test]
5988    fn a_class_on_an_ancestor_can_redefine_an_inherited_token() {
5989        let engine = Engine::compile(
5990            ":root { --bg: #ffffff } .dark { --bg: #000000 } .btn { background-color: var(--bg) }",
5991        );
5992        let light = themed_doc();
5993        let mut dark = themed_doc();
5994        dark.nodes[2].1 = "page dark";
5995
5996        let l = cascade(&engine, &light, &Env::default());
5997        let k = cascade(&engine, &dark, &Env::default());
5998        assert_eq!(l[2].vars.get("--bg"), Some("#fff"));
5999        assert_eq!(k[2].vars.get("--bg"), Some("#000"));
6000        assert_ne!(l[2].base.background, k[2].base.background);
6001        assert_eq!(k[0].vars.get("--bg"), Some("#fff"));
6002    }
6003
6004    #[test]
6005    fn light_dark_follows_each_elements_used_color_scheme() {
6006        let engine = Engine::compile(
6007            ":root { color-scheme: light dark; --edge: light-dark(rgb(1 1 1), rgb(2 2 2)) } \
6008             .page { color: light-dark(rgb(255 0 0), rgb(0 0 255)); \
6009                     background-color: var(--edge) } \
6010             .btn { color-scheme: only light; background-color: var(--edge); \
6011                    border: 1px solid light-dark(rgb(255 0 0), rgb(0 0 255)) }",
6012        );
6013        assert!(engine.diagnostics.is_empty(), "{:?}", engine.diagnostics);
6014        let d = themed_doc();
6015        let light = cascade(&engine, &d, &env_at(800.0, false, false));
6016        let dark = cascade(&engine, &d, &env_at(800.0, true, false));
6017        let red = Some(gpui::Hsla::from(gpui::rgb(0xff0000)));
6018        let blue = Some(gpui::Hsla::from(gpui::rgb(0x0000ff)));
6019        assert_eq!(light[1].base.text.color, red);
6020        assert_eq!(dark[1].base.text.color, blue);
6021        assert_ne!(light[1].base.background, dark[1].base.background);
6022        assert_eq!(
6023            dark[2].base.background, light[2].base.background,
6024            "a var holding light-dark() resolves where it is used"
6025        );
6026        assert_eq!(dark[2].base.border_color, red);
6027
6028        let unscheme = Engine::compile(".btn { color: light-dark(rgb(255 0 0), rgb(0 0 255)) }");
6029        assert_eq!(
6030            cascade(&unscheme, &d, &env_at(800.0, true, false))[2]
6031                .base
6032                .text
6033                .color,
6034            red,
6035            "`color-scheme: normal` is light"
6036        );
6037    }
6038
6039    #[test]
6040    fn media_scoped_redefinitions_reach_the_var_map() {
6041        let engine = Engine::compile(
6042            ":root { --bg: #ffffff } \
6043             @media (prefers-color-scheme: dark) { :root { --bg: #000000 } } \
6044             .btn { background-color: var(--bg) }",
6045        );
6046        assert!(engine.diagnostics.is_empty(), "{:?}", engine.diagnostics);
6047        let d = themed_doc();
6048        let light = cascade(&engine, &d, &env_at(800.0, false, false));
6049        let dark = cascade(&engine, &d, &env_at(800.0, true, false));
6050        assert_eq!(light[0].vars.get("--bg"), Some("#fff"));
6051        assert_eq!(dark[0].vars.get("--bg"), Some("#000"));
6052        assert_ne!(light[2].base.background, dark[2].base.background);
6053    }
6054
6055    #[test]
6056    fn custom_property_declarations_obey_the_cascade() {
6057        let engine = Engine::compile(
6058            ".btn { --v: a } button.btn { --v: b } .btn { --v: c } \
6059             .page { --w: 1 } .page { --w: 2 !important } .page { --w: 3 }",
6060        );
6061        let d = themed_doc();
6062        let states = cascade(&engine, &d, &Env::default());
6063        assert_eq!(states[2].vars.get("--v"), Some("b"));
6064        assert_eq!(states[1].vars.get("--w"), Some("2"));
6065    }
6066
6067    #[test]
6068    fn an_unresolvable_var_drops_one_declaration_silently() {
6069        let engine = Engine::compile(".btn { opacity: 0.5; color: var(--nope) }");
6070        let d = themed_doc();
6071        let mut diagnostics = Vec::new();
6072        let s = engine.compute_node(
6073            DocRef { doc: &d, i: 3 },
6074            None,
6075            &Rc::new(Vars::default()),
6076            None,
6077            &Env::default(),
6078            &mut diagnostics,
6079        );
6080        assert_eq!(
6081            s.base.opacity,
6082            Some(0.5),
6083            "the sibling declaration survives"
6084        );
6085        assert_eq!(s.base.text.color, None);
6086        assert!(diagnostics.is_empty(), "{diagnostics:?}");
6087    }
6088
6089    #[test]
6090    fn a_fallback_rescues_an_unset_variable() {
6091        let engine = Engine::compile(".btn { opacity: var(--nope, 0.25) }");
6092        let d = themed_doc();
6093        let s = cascade(&engine, &d, &Env::default());
6094        assert_eq!(s[2].base.opacity, Some(0.25));
6095    }
6096
6097    #[test]
6098    fn a_reference_cycle_invalidates_the_users() {
6099        let engine =
6100            Engine::compile(":root { --a: var(--b); --b: var(--a) } .btn { opacity: var(--a, 1) }");
6101        let d = themed_doc();
6102        let mut diagnostics = Vec::new();
6103        let mut vars = Rc::new(Vars::default());
6104        let mut opacity = None;
6105        for i in 1..d.nodes.len() {
6106            let s = engine.compute_node(
6107                DocRef { doc: &d, i },
6108                None,
6109                &vars,
6110                None,
6111                &Env::default(),
6112                &mut diagnostics,
6113            );
6114            vars = s.vars.clone();
6115            opacity = s.base.opacity;
6116        }
6117        assert_eq!(opacity, Some(1.0));
6118    }
6119
6120    #[test]
6121    fn scoped_rules_carry_custom_properties_through_the_normal_matcher() {
6122        let engine = Engine::compile(".page[data-v-abc] { --v: 1 } .page { --v: 2 }");
6123        assert!(engine.diagnostics.is_empty(), "{:?}", engine.diagnostics);
6124        let d = themed_doc();
6125        let s = cascade(&engine, &d, &Env::default());
6126        assert_eq!(
6127            s[1].vars.get("--v"),
6128            Some("2"),
6129            "the unscoped rule is the only match"
6130        );
6131    }
6132
6133    #[test]
6134    fn tailwinds_shadow_compound_renders() {
6135        let engine = Engine::compile(
6136            ".btn { --tw-shadow: 0 1px 2px 0 rgb(0 0 0 / 0.05); \
6137                    box-shadow: var(--tw-ring-offset-shadow, 0 0 #0000), \
6138                                var(--tw-ring-shadow, 0 0 #0000), var(--tw-shadow) }",
6139        );
6140        assert!(engine.diagnostics.is_empty(), "{:?}", engine.diagnostics);
6141        let d = themed_doc();
6142        let s = cascade(&engine, &d, &Env::default());
6143        let shadows = s[2].base.box_shadow.as_ref().expect("box-shadow");
6144        assert_eq!(shadows.len(), 3, "{shadows:?}");
6145        assert_eq!(shadows[2].blur_radius, gpui::px(2.0));
6146    }
6147
6148    #[test]
6149    fn the_shadcn_token_shape_resolves_to_a_colour() {
6150        let engine = Engine::compile(
6151            ":root { --primary: 240 5.9% 10% } .btn { background-color: hsl(var(--primary)) }",
6152        );
6153        let d = themed_doc();
6154        let s = cascade(&engine, &d, &Env::default());
6155        assert!(
6156            matches!(s[2].base.background, Some(gpui::Fill::Color(_))),
6157            "{:?}",
6158            s[2].base.background
6159        );
6160    }
6161
6162    #[test]
6163    fn query_all_ignores_interaction_states_without_a_live_view() {
6164        let d = doc();
6165        let c = refs(&d);
6166        let r = query_all(".tab:hover", &c).unwrap();
6167        assert_eq!(r.matched, vec![1, 2]);
6168    }
6169
6170    #[derive(Clone, Copy)]
6171    struct LiveRef<'d> {
6172        r: DocRef<'d>,
6173        hovered: &'d [usize],
6174        focused: usize,
6175        keyboard: bool,
6176    }
6177
6178    impl<'d> LiveRef<'d> {
6179        fn wrap(&self, r: DocRef<'d>) -> Self {
6180            LiveRef { r, ..*self }
6181        }
6182    }
6183
6184    impl<'d> MatchDom for LiveRef<'d> {
6185        const LIVE_STATE: bool = true;
6186        fn interaction(&self, state: Interaction) -> Option<bool> {
6187            let i = self.r.i;
6188            let within = || {
6189                let mut at = self.focused;
6190                while at != 0 {
6191                    if at == i {
6192                        return true;
6193                    }
6194                    at = self.r.doc.nodes[at].2;
6195                }
6196                false
6197            };
6198            Some(match state {
6199                Interaction::Hover => self.hovered.contains(&i),
6200                Interaction::Active => false,
6201                Interaction::Focus => self.focused == i,
6202                Interaction::FocusVisible => self.focused == i && self.keyboard,
6203                Interaction::FocusWithin => within(),
6204            })
6205        }
6206        fn key(&self) -> u64 {
6207            self.r.key()
6208        }
6209        fn parent(&self) -> Option<Self> {
6210            self.r.parent().map(|r| self.wrap(r))
6211        }
6212        fn prev_sibling(&self) -> Option<Self> {
6213            self.r.prev_sibling().map(|r| self.wrap(r))
6214        }
6215        fn next_sibling(&self) -> Option<Self> {
6216            self.r.next_sibling().map(|r| self.wrap(r))
6217        }
6218        fn has_tag(&self, name: &str) -> bool {
6219            self.r.has_tag(name)
6220        }
6221        fn tag_eq(&self, other: &Self) -> bool {
6222            self.r.tag_eq(&other.r)
6223        }
6224        fn has_class(&self, name: &str) -> bool {
6225            self.r.has_class(name)
6226        }
6227        fn tag_name(&self) -> &str {
6228            self.r.tag_name()
6229        }
6230        fn each_class(&self, f: &mut dyn FnMut(&str)) {
6231            self.r.each_class(f)
6232        }
6233        fn has_scope(&self, name: &str) -> bool {
6234            self.r.has_scope(name)
6235        }
6236        fn attr(&self, name: &str) -> Option<&str> {
6237            self.r.attr(name)
6238        }
6239        fn is_empty(&self) -> bool {
6240            self.r.is_empty()
6241        }
6242        fn is_root(&self) -> bool {
6243            self.r.is_root()
6244        }
6245    }
6246
6247    #[test]
6248    fn a_live_view_filters_a_query_by_the_interaction_state() {
6249        fn live<'d>(
6250            d: &'d Doc,
6251            hovered: &'d [usize],
6252            focused: usize,
6253            keyboard: bool,
6254        ) -> Vec<LiveRef<'d>> {
6255            refs(d)
6256                .into_iter()
6257                .map(|r| LiveRef {
6258                    r,
6259                    hovered,
6260                    focused,
6261                    keyboard,
6262                })
6263                .collect()
6264        }
6265        fn q(s: &str, c: &[LiveRef<'_>]) -> Result<(Vec<usize>, Vec<String>), String> {
6266            query_all(s, c).map(|r| (r.matched, r.warnings))
6267        }
6268        let d = doc();
6269        let c = live(&d, &[1, 2], 3, false);
6270        assert_eq!(q(".tab:hover", &c).unwrap(), (vec![1], vec![]));
6271        assert_eq!(q(":hover", &c).unwrap().0, vec![0, 1]);
6272        assert_eq!(q(":focus", &c).unwrap().0, vec![2]);
6273        assert!(q(":focus-visible", &c).unwrap().0.is_empty());
6274        assert_eq!(q(":focus-within", &c).unwrap().0, vec![0, 2]);
6275        assert!(q(":active", &c).unwrap().0.is_empty());
6276        assert_eq!(q(".tab:not(:hover)", &c).unwrap().0, vec![2]);
6277        assert_eq!(q(".tab:hover + .tab", &c).unwrap().0, vec![2]);
6278        assert_eq!(q(".nav:focus-within .tab:focus", &c).unwrap().0, vec![2]);
6279        assert!(q(".tab:hover:focus", &c).unwrap().0.is_empty());
6280        let k = live(&d, &[], 3, true);
6281        assert_eq!(q(":focus-visible", &k).unwrap().0, vec![2]);
6282        assert!(q(":hover", &k).unwrap().0.is_empty());
6283    }
6284
6285    #[test]
6286    fn has_matches_a_descendant_for_real() {
6287        let doc = Doc {
6288            nodes: vec![
6289                ("", "", 0, vec![]),
6290                ("div", "card", 0, vec![]),
6291                ("span", "badge", 1, vec![]),
6292                ("div", "card", 0, vec![]),
6293            ],
6294        };
6295        let engine = Engine::compile(".card:has(.badge) { opacity: 0.5 }");
6296        assert!(
6297            engine.diagnostics.is_empty(),
6298            "no advisory: it renders now — {:?}",
6299            engine.diagnostics
6300        );
6301        let opacity = |i: usize| {
6302            let mut d = Vec::new();
6303            engine
6304                .compute_node(
6305                    DocRef { doc: &doc, i },
6306                    None,
6307                    &Rc::new(Vars::default()),
6308                    None,
6309                    &Env::default(),
6310                    &mut d,
6311                )
6312                .base
6313                .opacity
6314        };
6315        assert_eq!(opacity(1), Some(0.5), "the card that HAS a badge");
6316        assert_eq!(opacity(3), None, "the card that does not");
6317        assert_eq!(opacity(2), None, "the badge itself is not the subject");
6318    }
6319
6320    #[test]
6321    fn has_with_plus_only_looks_at_the_next_sibling() {
6322        let doc = Doc {
6323            nodes: vec![
6324                ("", "", 0, vec![]),
6325                ("label", "label", 0, vec![]),
6326                ("span", "hint", 0, vec![]),
6327                ("input", "bad", 0, vec![]),
6328            ],
6329        };
6330        let next = Engine::compile(
6331            ".label:has(+ .bad) { opacity: 0.5 } .hint:has(+ .bad) { opacity: 0.5 }",
6332        );
6333        let later = Engine::compile(".label:has(~ .bad) { opacity: 0.5 }");
6334        let opacity = |engine: &Engine, i: usize| {
6335            let mut d = Vec::new();
6336            engine
6337                .compute_node(
6338                    DocRef { doc: &doc, i },
6339                    None,
6340                    &Rc::new(Vars::default()),
6341                    None,
6342                    &Env::default(),
6343                    &mut d,
6344                )
6345                .base
6346                .opacity
6347        };
6348        assert_eq!(opacity(&next, 1), None, "a hint sits between them");
6349        assert_eq!(opacity(&next, 2), Some(0.5), "the hint is right before it");
6350        assert_eq!(opacity(&later, 1), Some(0.5));
6351    }
6352
6353    #[test]
6354    fn has_with_a_child_combinator_does_not_reach_a_grandchild() {
6355        let doc = Doc {
6356            nodes: vec![
6357                ("", "", 0, vec![]),
6358                ("div", "card", 0, vec![]),
6359                ("div", "wrap", 1, vec![]),
6360                ("span", "badge", 2, vec![]),
6361            ],
6362        };
6363        let direct = Engine::compile(".card:has(> .badge) { opacity: 0.5 }");
6364        let nested = Engine::compile(".card:has(.badge) { opacity: 0.5 }");
6365        let opacity = |engine: &Engine| {
6366            let mut d = Vec::new();
6367            engine
6368                .compute_node(
6369                    DocRef { doc: &doc, i: 1 },
6370                    None,
6371                    &Rc::new(Vars::default()),
6372                    None,
6373                    &Env::default(),
6374                    &mut d,
6375                )
6376                .base
6377                .opacity
6378        };
6379        assert_eq!(opacity(&direct), None, "the badge is a GRANDchild");
6380        assert_eq!(opacity(&nested), Some(0.5), "…but it is a descendant");
6381    }
6382
6383    #[test]
6384    fn focus_within_folds_into_its_own_rung() {
6385        let engine = Engine::compile(".box:focus-within { opacity: 0.5 }");
6386        assert!(engine.diagnostics.is_empty(), "{:?}", engine.diagnostics);
6387        let states = engine.compute(box_node(), None, &Env::default());
6388        assert_eq!(states.base.opacity, None, "not in the base state");
6389        assert_eq!(
6390            states.focus_within.as_ref().and_then(|f| f.opacity),
6391            Some(0.5)
6392        );
6393        assert!(
6394            states.needs_focus_handle(),
6395            "gpui needs a handle to key it on"
6396        );
6397    }
6398
6399    #[test]
6400    fn supports_conditions_are_evaluated_rather_than_dropped() {
6401        let applies = |css: &str| {
6402            let engine = Engine::compile(css);
6403            assert!(
6404                engine.diagnostics.is_empty(),
6405                "{css}: {:?}",
6406                engine.diagnostics
6407            );
6408            engine
6409                .compute(box_node(), None, &Env::default())
6410                .base
6411                .opacity
6412        };
6413        assert_eq!(
6414            applies("@supports (display: flex) { .box { opacity: 0.5 } }"),
6415            Some(0.5),
6416            "a property sk-css maps"
6417        );
6418        assert_eq!(
6419            applies("@supports (shape-outside: none) { .box { opacity: 0.5 } }"),
6420            None,
6421            "a property it does not"
6422        );
6423        assert_eq!(
6424            applies("@supports not (shape-outside: none) { .box { opacity: 0.5 } }"),
6425            Some(0.5)
6426        );
6427        assert_eq!(
6428            applies(
6429                "@supports (display: flex) and (shape-outside: none) \
6430                 { .box { opacity: 0.5 } }"
6431            ),
6432            None
6433        );
6434        assert_eq!(
6435            applies(
6436                "@supports (display: flex) or (shape-outside: none) \
6437                 { .box { opacity: 0.5 } }"
6438            ),
6439            Some(0.5)
6440        );
6441        assert_eq!(
6442            applies("@supports selector(:has(a)) { .box { opacity: 0.5 } }"),
6443            Some(0.5)
6444        );
6445        assert_eq!(
6446            applies("@supports selector(::first-line) { .box { opacity: 0.5 } }"),
6447            None
6448        );
6449    }
6450
6451    #[test]
6452    fn current_color_inside_a_colour_function_is_the_computed_color() {
6453        let engine = Engine::compile(
6454            ".mix { border-color: color-mix(in srgb, currentColor 50%, #0000ff) } \
6455             .mix { color: #ff0000 } \
6456             .rel { color: rgb(from currentColor r g b / 50%); \
6457                    background-color: color-mix(in srgb, currentColor, transparent) } \
6458             .var { --c: currentColor; box-shadow: 0 0 1px color-mix(in srgb, var(--c), #00ff00) } \
6459             .scroll { overflow: auto; scrollbar-color: color-mix(in srgb, currentColor, white) red }",
6460        );
6461        assert!(engine.diagnostics.is_empty(), "{:?}", engine.diagnostics);
6462        let doc = Doc {
6463            nodes: vec![
6464                ("", "", 0, vec![]),
6465                ("div", "mix", 0, vec![]),
6466                ("div", "rel", 0, vec![]),
6467                ("div", "var", 0, vec![]),
6468                ("div", "scroll", 0, vec![]),
6469            ],
6470        };
6471        let green: gpui::Hsla = gpui::rgb(0x00ff00).into();
6472        let compute = |i: usize| {
6473            let mut d = Vec::new();
6474            let states = engine.compute_node(
6475                DocRef { doc: &doc, i },
6476                None,
6477                &Rc::new(Vars::default()),
6478                Some(green),
6479                &Env::default(),
6480                &mut d,
6481            );
6482            assert!(d.is_empty(), "{d:?}");
6483            states
6484        };
6485        let rgba = |c: Option<gpui::Hsla>| {
6486            let c = gpui::Rgba::from(c.expect("resolved"));
6487            [c.r, c.g, c.b, c.a].map(|v| (v * 255.0).round() as u8)
6488        };
6489
6490        let mix = compute(1);
6491        assert_eq!(
6492            rgba(mix.base.border_color),
6493            [128, 0, 128, 255],
6494            "its own red, declared later"
6495        );
6496
6497        let rel = compute(2);
6498        assert_eq!(
6499            rgba(rel.color),
6500            [0, 255, 0, 128],
6501            "`color` reads the parent's"
6502        );
6503        let background = match rel.base.background {
6504            Some(gpui::Fill::Color(bg)) => bg.as_solid(),
6505            _ => None,
6506        };
6507        assert_eq!(rgba(background), [0, 255, 0, 64], "the rest read its own");
6508
6509        let shadow = compute(3).base.box_shadow.clone().expect("mapped");
6510        assert_eq!(rgba(Some(shadow[0].color)), [0, 255, 0, 255]);
6511
6512        let (thumb, _) = compute(4).extras.scrollbar_color.expect("mapped");
6513        assert_eq!(rgba(Some(thumb)), [128, 255, 128, 255]);
6514    }
6515
6516    #[test]
6517    fn current_color_resolves_against_the_computed_color() {
6518        let engine = Engine::compile(
6519            ".parent { color: #ff0000 } .child { border-color: currentColor } \
6520             .own { color: #0000ff; border-color: currentColor }",
6521        );
6522        assert!(engine.diagnostics.is_empty(), "{:?}", engine.diagnostics);
6523        let doc = Doc {
6524            nodes: vec![
6525                ("", "", 0, vec![]),
6526                ("div", "parent", 0, vec![]),
6527                ("div", "child", 0, vec![]),
6528                ("div", "own", 0, vec![]),
6529            ],
6530        };
6531        let compute = |i: usize, parent_color: Option<gpui::Hsla>| {
6532            let mut d = Vec::new();
6533            let states = engine.compute_node(
6534                DocRef { doc: &doc, i },
6535                None,
6536                &Rc::new(Vars::default()),
6537                parent_color,
6538                &Env::default(),
6539                &mut d,
6540            );
6541            assert!(d.is_empty(), "{d:?}");
6542            states
6543        };
6544        let red = compute(1, None).color.expect("declared");
6545        let inherited = compute(2, Some(red));
6546        assert_eq!(inherited.base.border_color, Some(red));
6547        assert_eq!(
6548            inherited.color,
6549            Some(red),
6550            "and it passes the same colour on"
6551        );
6552        let own = compute(3, Some(red));
6553        assert_ne!(own.base.border_color, Some(red));
6554        assert_eq!(own.base.border_color, own.color);
6555
6556        // A `::before` icon filled with the text colour.
6557        let engine = Engine::compile(".icon::before { content: \"\"; background: currentColor }");
6558        let doc = Doc {
6559            nodes: vec![("", "", 0, vec![]), ("i", "icon", 0, vec![])],
6560        };
6561        let mut d = Vec::new();
6562        let states = engine.compute_node(
6563            DocRef { doc: &doc, i: 1 },
6564            None,
6565            &Rc::new(Vars::default()),
6566            Some(red),
6567            &Env::default(),
6568            &mut d,
6569        );
6570        let before = states.before.as_ref().expect("a ::before box");
6571        assert_eq!(before.style.background, Some(gpui::Fill::Color(red.into())));
6572    }
6573
6574    #[test]
6575    fn border_radius_inherit_takes_the_parents_radius() {
6576        use gpui::{AbsoluteLength, DefiniteLength, VnCornerRadius};
6577        let engine = Engine::compile(
6578            ".card { border-radius: 16px } \
6579             .bg { border-radius: inherit } \
6580             .zone { border-bottom-left-radius: inherit; border-bottom-right-radius: inherit } \
6581             .body { border-bottom-left-radius: inherit; border-bottom-right-radius: inherit } \
6582             .pct { border-radius: 50% 4px } \
6583             .late { border-radius: inherit } .late.flat { border-radius: 2px } \
6584             .hov { border-radius: inherit } .hov:hover { border-radius: 8px } \
6585             .ring { border-radius: 10px } .ring::after { content: ''; border-radius: inherit }",
6586        );
6587        assert!(engine.diagnostics.is_empty(), "{:?}", engine.diagnostics);
6588        let doc = Doc {
6589            nodes: vec![
6590                ("", "", 0, vec![]),
6591                ("div", "card", 0, vec![]),
6592                ("div", "bg", 1, vec![]),
6593                ("div", "zone", 1, vec![]),
6594                ("div", "body", 3, vec![]),
6595                ("div", "pct", 0, vec![]),
6596                ("div", "bg", 5, vec![]),
6597                ("div", "late flat", 1, vec![]),
6598                ("div", "hov", 1, vec![]),
6599                ("div", "ring", 0, vec![]),
6600            ],
6601        };
6602        let mut handed: Vec<InheritedRadii> = vec![InheritedRadii::default(); doc.nodes.len()];
6603        let mut computed = Vec::new();
6604        for i in 1..doc.nodes.len() {
6605            let mut d = Vec::new();
6606            let mut states = engine.compute_node(
6607                DocRef { doc: &doc, i },
6608                None,
6609                &Rc::new(Vars::default()),
6610                None,
6611                &Env::default(),
6612                &mut d,
6613            );
6614            assert!(d.is_empty(), "{d:?}");
6615            let parent = doc.nodes[i].2;
6616            let parent = if parent == 0 {
6617                InheritedRadii::default()
6618            } else {
6619                handed[parent]
6620            };
6621            handed[i] = resolve_inherited_radii(&mut states, parent);
6622            computed.push(states);
6623        }
6624        let px = |v: f32| Some(AbsoluteLength::Pixels(gpui::px(v)));
6625        let at = |i: usize| &computed[i - 1];
6626
6627        let bg = &at(2).base;
6628        assert_eq!(
6629            [bg.corner_radii.top_left, bg.corner_radii.bottom_right],
6630            [px(16.), px(16.)]
6631        );
6632        assert_eq!(
6633            bg.vn_corner_radii.top_left,
6634            Some(None),
6635            "a length, not a percentage"
6636        );
6637        let zone = &at(3).base;
6638        assert_eq!(zone.corner_radii.bottom_left, px(16.));
6639        assert_eq!(
6640            zone.corner_radii.top_left, None,
6641            "an undeclared corner stays undeclared"
6642        );
6643        let body = &at(4).base;
6644        assert_eq!(
6645            [
6646                body.corner_radii.bottom_left,
6647                body.corner_radii.bottom_right
6648            ],
6649            [px(16.), px(16.)]
6650        );
6651        let from_pct = &at(6).base;
6652        assert_eq!(
6653            from_pct.vn_corner_radii.top_left,
6654            Some(Some(VnCornerRadius {
6655                x: DefiniteLength::Fraction(0.5),
6656                y: DefiniteLength::Fraction(0.5),
6657            }))
6658        );
6659        assert_eq!(from_pct.corner_radii.top_right, px(4.));
6660        assert_eq!(from_pct.vn_corner_radii.top_right, Some(None));
6661        assert_eq!(at(7).base.corner_radii.top_left, px(2.));
6662        let hov = at(8);
6663        assert_eq!(hov.base.corner_radii.top_left, px(16.));
6664        assert_eq!(hov.hover.as_ref().unwrap().corner_radii.top_left, px(8.));
6665        let ring = at(9).after.as_ref().expect("an ::after box");
6666        assert_eq!(ring.style.corner_radii.bottom_right, px(10.));
6667        let mut orphan = engine.compute_node(
6668            DocRef { doc: &doc, i: 2 },
6669            None,
6670            &Rc::new(Vars::default()),
6671            None,
6672            &Env::default(),
6673            &mut Vec::new(),
6674        );
6675        resolve_inherited_radii(&mut orphan, InheritedRadii::default());
6676        assert_eq!(orphan.base.corner_radii.top_left, px(0.));
6677    }
6678
6679    #[test]
6680    fn border_radius_inherit_on_a_state_rule_is_ignored() {
6681        let engine = Engine::compile(".x:hover { border-radius: inherit }");
6682        let doc = Doc {
6683            nodes: vec![("", "", 0, vec![]), ("div", "x", 0, vec![])],
6684        };
6685        let mut d = Vec::new();
6686        let states = engine.compute_node(
6687            DocRef { doc: &doc, i: 1 },
6688            None,
6689            &Rc::new(Vars::default()),
6690            None,
6691            &Env::default(),
6692            &mut d,
6693        );
6694        assert_eq!(states.extras.radius_inherit, RadiusInherit::default());
6695    }
6696
6697    use crate::animator::{AnimEventKind, Animator};
6698    use std::time::Instant;
6699
6700    fn animated(css: &str) -> ComputedStates {
6701        Engine::compile(css).compute(box_node(), None, &Env::default())
6702    }
6703
6704    fn opacity(r: &StyleRefinement) -> f32 {
6705        r.opacity.expect("opacity was not animated")
6706    }
6707
6708    const SPIN: &str = "@keyframes spin { from { opacity: 0 } to { opacity: 1 } } \
6709                        .box { animation: spin 1000ms linear }";
6710
6711    #[test]
6712    fn an_animation_runs_from_the_sheets_keyframes() {
6713        let engine = Engine::compile(SPIN);
6714        let cs = engine.compute(box_node(), None, &Env::default());
6715        assert_eq!(cs.animations.len(), 1);
6716        assert_eq!(&*cs.animations[0].name, "spin");
6717        assert_eq!(cs.animations[0].duration, Duration::from_millis(1000));
6718
6719        let mut a = Animator::new();
6720        let now = Instant::now();
6721        a.on_computed_animations(1, &cs, now, &|name| engine.keyframes(name, &Env::default()));
6722
6723        let base = StyleRefinement::default();
6724        let at = |ms: u64| {
6725            a.overlay(1, &base, now + Duration::from_millis(ms))
6726                .unwrap()
6727        };
6728        assert!((opacity(&at(0)) - 0.0).abs() < 1e-6);
6729        assert!((opacity(&at(500)) - 0.5).abs() < 1e-3);
6730        assert!((opacity(&at(999)) - 1.0).abs() < 1e-2);
6731    }
6732
6733    #[test]
6734    fn keyframes_fade_an_effect_in_from_the_unset_value() {
6735        let engine = Engine::compile(
6736            "@keyframes appear { to { --shading: glow(10px, 0.5) } } \
6737             .box { animation: appear 1000ms linear }",
6738        );
6739        let cs = engine.compute(box_node(), None, &Env::default());
6740        let mut a = Animator::new();
6741        let now = Instant::now();
6742        a.on_computed_animations(1, &cs, now, &|name| engine.keyframes(name, &Env::default()));
6743        let r = a
6744            .overlay(
6745                1,
6746                &StyleRefinement::default(),
6747                now + Duration::from_millis(250),
6748            )
6749            .unwrap();
6750        assert_eq!(r.vn_effect.map(|e| e.id), Some(gpui::effect_id::GLOW));
6751        let fade = r
6752            .vn_effect_fade
6753            .expect("the implicit from-keyframe is no effect");
6754        assert!(!fade.from.is_some());
6755        assert!((fade.progress - 0.25).abs() < 1e-3);
6756    }
6757
6758    #[test]
6759    fn corner_shape_keyframes_move_the_half_corner() {
6760        let engine = Engine::compile(
6761            "@keyframes morph { from { corner-shape: bevel } to { corner-shape: square } } \
6762             .box { animation: morph 1000ms linear }",
6763        );
6764        assert!(engine.diagnostics.is_empty(), "{:?}", engine.diagnostics);
6765        let cs = engine.compute(box_node(), None, &Env::default());
6766        let mut a = Animator::new();
6767        let now = Instant::now();
6768        a.on_computed_animations(1, &cs, now, &|name| engine.keyframes(name, &Env::default()));
6769        let half = a
6770            .overlay(
6771                1,
6772                &StyleRefinement::default(),
6773                now + Duration::from_millis(500),
6774            )
6775            .unwrap();
6776        let mid = gpui::CornerShape::BEVEL.interpolate(gpui::CornerShape::SQUARE, 0.5);
6777        assert_eq!(half.vn_corner_shapes.top_left, Some(mid));
6778        assert_eq!(half.vn_corner_shapes.bottom_left, Some(mid));
6779    }
6780
6781    #[test]
6782    fn a_100_percent_keyframe_holds_under_fill_forwards() {
6783        let engine = Engine::compile(
6784            ".box { animation: pulse 80ms linear 1 forwards }              @keyframes pulse { to { opacity: 0.2 } }",
6785        );
6786        let cs = engine.compute(box_node(), None, &Env::default());
6787        let mut a = Animator::new();
6788        let now = Instant::now();
6789        a.on_computed_animations(1, &cs, now, &|name| engine.keyframes(name, &Env::default()));
6790
6791        let base = StyleRefinement::default();
6792        let at = |ms: u64| {
6793            opacity(
6794                &a.overlay(1, &base, now + Duration::from_millis(ms))
6795                    .unwrap(),
6796            )
6797        };
6798        assert!((at(0) - 1.0).abs() < 1e-6);
6799        assert!((at(40) - 0.6).abs() < 1e-3);
6800        assert!(
6801            (at(200) - 0.2).abs() < 1e-6,
6802            "forwards holds the 100 % keyframe"
6803        );
6804        assert!((at(5000) - 0.2).abs() < 1e-6, "…and keeps holding it");
6805    }
6806
6807    #[test]
6808    fn fill_mode_decides_what_the_ends_paint() {
6809        let engine = Engine::compile(SPIN);
6810        let cs = engine.compute(box_node(), None, &Env::default());
6811        let mut a = Animator::new();
6812        let now = Instant::now();
6813        a.on_computed_animations(1, &cs, now, &|name| engine.keyframes(name, &Env::default()));
6814        let base = StyleRefinement::default();
6815        assert!(a
6816            .overlay(1, &base, now + Duration::from_millis(2000))
6817            .is_none());
6818
6819        let forwards = Engine::compile(
6820            "@keyframes spin { from { opacity: 0 } to { opacity: 1 } } \
6821             .box { animation: spin 1000ms linear forwards }",
6822        );
6823        let cs = forwards.compute(box_node(), None, &Env::default());
6824        let mut a = Animator::new();
6825        a.on_computed_animations(1, &cs, now, &|name| {
6826            forwards.keyframes(name, &Env::default())
6827        });
6828        let held = a
6829            .overlay(1, &base, now + Duration::from_millis(2000))
6830            .unwrap();
6831        assert!((opacity(&held) - 1.0).abs() < 1e-6);
6832
6833        // `backwards` freezes the START value during the delay; without it the delay paints nothing
6834        // at all.
6835        let backwards = Engine::compile(
6836            "@keyframes spin { from { opacity: 0.25 } to { opacity: 1 } } \
6837             .box { animation: spin 1000ms linear 500ms backwards }",
6838        );
6839        let cs = backwards.compute(box_node(), None, &Env::default());
6840        let mut a = Animator::new();
6841        a.on_computed_animations(1, &cs, now, &|name| {
6842            backwards.keyframes(name, &Env::default())
6843        });
6844        let during_delay = a
6845            .overlay(1, &base, now + Duration::from_millis(100))
6846            .unwrap();
6847        assert!((opacity(&during_delay) - 0.25).abs() < 1e-6);
6848    }
6849
6850    #[test]
6851    fn a_missing_keyframe_end_is_the_elements_own_value() {
6852        let engine = Engine::compile(
6853            "@keyframes fade { to { opacity: 1 } } .box { animation: fade 1000ms linear }",
6854        );
6855        let cs = engine.compute(box_node(), None, &Env::default());
6856        let mut a = Animator::new();
6857        let now = Instant::now();
6858        a.on_computed_animations(1, &cs, now, &|name| engine.keyframes(name, &Env::default()));
6859        let mut base = StyleRefinement::default();
6860        base.opacity = Some(0.2);
6861        let half = a
6862            .overlay(1, &base, now + Duration::from_millis(500))
6863            .unwrap();
6864        assert!((opacity(&half) - 0.6).abs() < 1e-2, "{:?}", half.opacity);
6865    }
6866
6867    #[test]
6868    fn infinite_animations_keep_the_pump_awake() {
6869        let engine = Engine::compile(
6870            "@keyframes pulse { 0%,100% { opacity: 1 } 50% { opacity: 0.5 } } \
6871             .box { animation: pulse 2s cubic-bezier(0.4,0,0.6,1) infinite }",
6872        );
6873        let cs = engine.compute(box_node(), None, &Env::default());
6874        assert!(!cs.animations[0].iterations.is_finite());
6875        let mut a = Animator::new();
6876        let now = Instant::now();
6877        a.on_computed_animations(1, &cs, now, &|name| engine.keyframes(name, &Env::default()));
6878        assert!(a.any_animation(now + Duration::from_secs(3600)));
6879        let base = StyleRefinement::default();
6880        let mid = a
6881            .overlay(1, &base, now + Duration::from_millis(1000))
6882            .unwrap();
6883        assert!((opacity(&mid) - 0.5).abs() < 1e-3);
6884        let back = a
6885            .overlay(1, &base, now + Duration::from_millis(1999))
6886            .unwrap();
6887        assert!(opacity(&back) > 0.9, "{:?}", back.opacity);
6888    }
6889
6890    #[test]
6891    fn animation_start_and_end_are_reported() {
6892        let engine = Engine::compile(
6893            "@keyframes fade { from { opacity: 0 } to { opacity: 1 } } \
6894             .box { animation: fade 100ms linear 50ms }",
6895        );
6896        let cs = engine.compute(box_node(), None, &Env::default());
6897        let mut a = Animator::new();
6898        let now = Instant::now();
6899        a.on_computed_animations(1, &cs, now, &|name| engine.keyframes(name, &Env::default()));
6900
6901        a.tick(now + Duration::from_millis(10));
6902        assert!(a.take_events().is_empty());
6903
6904        a.tick(now + Duration::from_millis(60));
6905        let started = a.take_events();
6906        assert_eq!(started.len(), 1);
6907        assert_eq!(started[0].kind, AnimEventKind::AnimationStart);
6908        assert_eq!(started[0].name, "fade");
6909
6910        a.tick(now + Duration::from_millis(500));
6911        let ended = a.take_events();
6912        assert_eq!(ended.len(), 1);
6913        assert_eq!(ended[0].kind, AnimEventKind::AnimationEnd);
6914        // `elapsedTime` excludes the delay: 100 ms of animation, not 150.
6915        assert!(
6916            (ended[0].elapsed - 0.1).abs() < 1e-6,
6917            "{}",
6918            ended[0].elapsed
6919        );
6920
6921        // Once ended, removing the animation is NOT a cancel — the DOM fires exactly one of
6922        // `animationend` / `animationcancel`.
6923        let none = animated(".box { color: red }");
6924        a.on_computed_animations(1, &none, now + Duration::from_millis(600), &|_| None);
6925        assert!(a.take_events().is_empty());
6926    }
6927
6928    #[test]
6929    fn removing_a_running_animation_cancels_it() {
6930        let engine = Engine::compile(SPIN);
6931        let cs = engine.compute(box_node(), None, &Env::default());
6932        let mut a = Animator::new();
6933        let now = Instant::now();
6934        a.on_computed_animations(1, &cs, now, &|name| engine.keyframes(name, &Env::default()));
6935        a.tick(now);
6936        a.take_events();
6937
6938        let none = animated(".box { color: red }");
6939        a.on_computed_animations(1, &none, now + Duration::from_millis(300), &|_| None);
6940        let events = a.take_events();
6941        assert_eq!(events.len(), 1);
6942        assert_eq!(events[0].kind, AnimEventKind::AnimationCancel);
6943        assert!((events[0].elapsed - 0.3).abs() < 1e-2);
6944        assert!(a.is_idle());
6945    }
6946
6947    #[test]
6948    fn reduced_motion_suppresses_animations() {
6949        let engine = Engine::compile(SPIN);
6950        let cs = engine.compute(box_node(), None, &Env::default());
6951        let mut a = Animator::new();
6952        a.set_reduce_motion(true);
6953        let now = Instant::now();
6954        a.on_computed_animations(1, &cs, now, &|name| engine.keyframes(name, &Env::default()));
6955        assert!(a.is_idle());
6956        assert!(a.overlay(1, &StyleRefinement::default(), now).is_none());
6957    }
6958
6959    #[test]
6960    fn a_finished_transition_reports_transitionend() {
6961        let old = animated(".box { opacity: 0; transition: opacity 200ms linear }");
6962        let new = animated(".box { opacity: 1; transition: opacity 200ms linear }");
6963        let mut a = Animator::new();
6964        let now = Instant::now();
6965        a.on_computed(1, Some(&old), &new, now);
6966
6967        a.finish_settled(now + Duration::from_millis(100));
6968        assert!(a.take_events().is_empty());
6969
6970        a.finish_settled(now + Duration::from_millis(250));
6971        let events = a.take_events();
6972        assert_eq!(events.len(), 1);
6973        assert_eq!(events[0].kind, AnimEventKind::TransitionEnd);
6974        assert_eq!(events[0].name, "opacity");
6975        // `elapsedTime` is the DURATION, not the wall clock since the start.
6976        assert!((events[0].elapsed - 0.2).abs() < 1e-6);
6977        assert_eq!(events[0].node, 1);
6978    }
6979
6980    #[test]
6981    fn an_unknown_animation_name_is_not_faked() {
6982        let cs = animated(".box { animation: nope 1s linear }");
6983        let mut a = Animator::new();
6984        a.on_computed_animations(1, &cs, Instant::now(), &|_| None);
6985        assert!(a.is_idle());
6986    }
6987
6988    #[test]
6989    fn animation_longhands_compile() {
6990        let engine = Engine::compile(
6991            "@keyframes spin { to { transform: rotate(360deg) } } \
6992             .box { animation-name: spin; animation-duration: 1s; \
6993                    animation-iteration-count: infinite; animation-timing-function: linear }",
6994        );
6995        assert!(engine.diagnostics.is_empty(), "{:?}", engine.diagnostics);
6996        let cs = engine.compute(box_node(), None, &Env::default());
6997        assert_eq!(cs.animations.len(), 1);
6998        assert!(!cs.animations[0].iterations.is_finite());
6999        assert_eq!(cs.animations[0].duration, Duration::from_secs(1));
7000        assert_eq!(cs.animations[0].easing, crate::Easing::Linear);
7001        let frames = engine.keyframes("spin", &Env::default()).unwrap();
7002        assert_eq!(frames.steps.len(), 1);
7003        assert_eq!(frames.steps[0].offset, 1.0);
7004    }
7005
7006    #[test]
7007    fn media_scoped_keyframes_resolve_per_environment() {
7008        let engine = Engine::compile(
7009            "@keyframes slide { to { opacity: 0.25 } }              @media (max-width: 420px) { @keyframes slide { to { opacity: 0.75 } } }",
7010        );
7011        let wide = Env {
7012            viewport_width: 1280.0,
7013            ..Env::default()
7014        };
7015        let narrow = Env {
7016            viewport_width: 380.0,
7017            ..Env::default()
7018        };
7019
7020        let opacity = |env: &Env| {
7021            engine
7022                .keyframes("slide", env)
7023                .map(|k| k.steps.last().unwrap().style.opacity.unwrap())
7024        };
7025        assert_eq!(
7026            opacity(&wide),
7027            Some(0.25),
7028            "the unconditional block, in a wide window"
7029        );
7030        assert_eq!(
7031            opacity(&narrow),
7032            Some(0.75),
7033            "the @media block, in a window the query holds in — the SAME sheet, the same name"
7034        );
7035
7036        let only_narrow =
7037            Engine::compile("@media (max-width: 420px) { @keyframes pop { to { opacity: 0.5 } } }");
7038        assert!(
7039            only_narrow.keyframes("pop", &narrow).is_some(),
7040            "declared in the narrow window"
7041        );
7042        assert!(
7043            only_narrow.keyframes("pop", &wide).is_none(),
7044            "not declared in the wide one"
7045        );
7046
7047        let twice = Engine::compile(
7048            "@keyframes dup { to { opacity: 0.1 } } @keyframes dup { to { opacity: 0.9 } }",
7049        );
7050        assert_eq!(
7051            twice
7052                .keyframes("dup", &wide)
7053                .map(|k| k.steps.last().unwrap().style.opacity.unwrap()),
7054            Some(0.9),
7055            "a later block with the same name wins, as in CSS"
7056        );
7057    }
7058
7059    const TW_ANIMATE: &str = "@keyframes enter { from { \
7060            opacity: var(--tw-enter-opacity, 1); \
7061            transform: translate3d(var(--tw-enter-translate-x, 0), var(--tw-enter-translate-y, 0), 0) \
7062                       scale3d(var(--tw-enter-scale, 1), var(--tw-enter-scale, 1), var(--tw-enter-scale, 1)) } } \
7063        .box { animation-name: enter; animation-duration: 200ms; animation-timing-function: linear; \
7064               --tw-enter-opacity: 0; --tw-enter-scale: 0.95 }";
7065
7066    #[test]
7067    fn a_var_composed_keyframe_resolves_against_the_animating_element() {
7068        let engine = Engine::compile(TW_ANIMATE);
7069        let raw = engine
7070            .keyframes("enter", &Env::default())
7071            .expect("@keyframes enter");
7072        assert_eq!(raw.steps.len(), 1, "the `from` step is kept, unresolved");
7073        assert!(raw.dynamic, "and it is flagged as needing per-element work");
7074
7075        let cs = engine.compute(box_node(), None, &Env::default());
7076        assert_eq!(cs.vars.get("--tw-enter-opacity"), Some("0"));
7077        let mut diagnostics = Vec::new();
7078        let frames = engine
7079            .keyframes_for("enter", &cs.vars, &Env::default(), &mut diagnostics)
7080            .expect("resolved");
7081        assert!(diagnostics.is_empty(), "{diagnostics:?}");
7082        let from = &frames.steps[0].style;
7083        assert_eq!(
7084            from.opacity,
7085            Some(0.0),
7086            "var(--tw-enter-opacity) substituted"
7087        );
7088        let t = from.vn_transform.expect("scale3d reached the refinement");
7089        assert!((t.scale.0 - 0.95).abs() < 1e-6, "{:?}", t.scale);
7090        assert!((t.scale.1 - 0.95).abs() < 1e-6, "{:?}", t.scale);
7091
7092        let mut a = Animator::new();
7093        let now = Instant::now();
7094        a.on_computed_animations(1, &cs, now, &|name| {
7095            engine.keyframes_for(name, &cs.vars, &Env::default(), &mut Vec::new())
7096        });
7097        let base = StyleRefinement::default();
7098        let at = |ms: u64| {
7099            a.overlay(1, &base, now + Duration::from_millis(ms))
7100                .unwrap()
7101        };
7102        assert!((opacity(&at(0)) - 0.0).abs() < 1e-6);
7103        assert!(
7104            (opacity(&at(100)) - 0.5).abs() < 1e-2,
7105            "halfway through the fade"
7106        );
7107        let half = at(100).vn_transform.expect("the zoom is interpolated too");
7108        assert!((half.scale.0 - 0.975).abs() < 1e-2, "{:?}", half.scale);
7109    }
7110
7111    #[test]
7112    fn two_elements_resolve_the_same_keyframes_differently() {
7113        let engine = Engine::compile(
7114            "@keyframes enter { from { opacity: var(--tw-enter-opacity, 1) } } \
7115             .box { animation: enter 200ms linear; --tw-enter-opacity: 0 } \
7116             .half { --tw-enter-opacity: 0.5 }",
7117        );
7118        let env = Env::default();
7119        let faint = engine.compute(box_node(), None, &env);
7120        let half = engine.compute(
7121            Node {
7122                tag: "div",
7123                class: "box half",
7124                attrs: &[],
7125            },
7126            None,
7127            &env,
7128        );
7129        let mut d = Vec::new();
7130        let a = engine
7131            .keyframes_for("enter", &faint.vars, &env, &mut d)
7132            .unwrap();
7133        let b = engine
7134            .keyframes_for("enter", &half.vars, &env, &mut d)
7135            .unwrap();
7136        assert_eq!(a.steps[0].style.opacity, Some(0.0));
7137        assert_eq!(b.steps[0].style.opacity, Some(0.5));
7138        assert!(d.is_empty(), "{d:?}");
7139    }
7140
7141    #[test]
7142    fn an_unresolvable_keyframe_declaration_drops_only_itself() {
7143        let engine = Engine::compile(
7144            "@keyframes enter { from { opacity: var(--missing); width: 10px } } \
7145             .box { animation: enter 200ms linear }",
7146        );
7147        let env = Env::default();
7148        let cs = engine.compute(box_node(), None, &env);
7149        let mut d = Vec::new();
7150        let frames = engine
7151            .keyframes_for("enter", &cs.vars, &env, &mut d)
7152            .unwrap();
7153        assert_eq!(frames.steps[0].style.opacity, None);
7154        assert!(
7155            frames.steps[0].style.size.width.is_some(),
7156            "the sibling survives"
7157        );
7158        assert!(
7159            d.is_empty(),
7160            "an unset var() is silent — a browser drops it too"
7161        );
7162    }
7163
7164    #[test]
7165    fn the_shadcn_dialog_enter_slides_as_well_as_zooms() {
7166        let engine = Engine::compile(
7167            "@keyframes enter { from { \
7168                opacity: var(--tw-enter-opacity, 1); \
7169                transform: translate3d(var(--tw-enter-translate-x, 0), var(--tw-enter-translate-y, 0), 0) \
7170                           scale3d(var(--tw-enter-scale, 1), var(--tw-enter-scale, 1), var(--tw-enter-scale, 1)) \
7171                           rotate(var(--tw-enter-rotate, 0)) } } \
7172             .animate-in { animation: enter 200ms linear; \
7173                    --tw-enter-opacity: initial; --tw-enter-scale: initial; \
7174                    --tw-enter-rotate: initial; --tw-enter-translate-x: initial; \
7175                    --tw-enter-translate-y: initial } \
7176             .fade-in-0 { --tw-enter-opacity: 0 } .zoom-in-95 { --tw-enter-scale: 0.95 } \
7177             .box { transform: translate(-50%, -50%) }",
7178        );
7179        let env = Env::default();
7180        let node = Node {
7181            tag: "div",
7182            class: "box animate-in fade-in-0 zoom-in-95",
7183            attrs: &[],
7184        };
7185        let cs = engine.compute(node, None, &env);
7186        let mut d = Vec::new();
7187        let frames = engine
7188            .keyframes_for("enter", &cs.vars, &env, &mut d)
7189            .unwrap();
7190        assert!(
7191            d.is_empty(),
7192            "`rotate(0)` and the rest must all parse: {d:?}"
7193        );
7194        let start = frames.steps[0]
7195            .style
7196            .vn_transform
7197            .expect("the keyframe's transform");
7198        assert_eq!(start.translate.0, gpui::TransformLength::Pixels(0.0));
7199        assert!((start.scale.0 - 0.95).abs() < 1e-6, "{:?}", start.scale);
7200        assert_eq!(frames.steps[0].style.opacity, Some(0.0));
7201
7202        let mut a = Animator::new();
7203        let now = Instant::now();
7204        a.on_computed_animations(1, &cs, now, &|name| {
7205            engine.keyframes_for(name, &cs.vars, &env, &mut Vec::new())
7206        });
7207        a.tick(now);
7208        let half = a
7209            .overlay(1, &cs.base, now + Duration::from_millis(100))
7210            .unwrap()
7211            .vn_transform
7212            .expect("an interpolated transform");
7213        assert_eq!(half.translate.0, gpui::TransformLength::Fraction(-0.25));
7214        assert_eq!(half.translate.1, gpui::TransformLength::Fraction(-0.25));
7215        assert!((half.scale.0 - 0.975).abs() < 1e-4, "{:?}", half.scale);
7216    }
7217
7218    #[test]
7219    fn a_longhand_patch_loses_to_a_more_specific_rule_that_declares_the_list() {
7220        let engine = Engine::compile(
7221            "@keyframes enter { from { opacity: 0 } } \
7222             .duration-200 { animation-duration: 200ms } \
7223             .animate-in[data-state=open] { animation-name: enter; animation-duration: 150ms }",
7224        );
7225        let node = Node {
7226            tag: "div",
7227            class: "duration-200 animate-in",
7228            attrs: &[("data-state", "open")],
7229        };
7230        let cs = engine.compute(node, None, &Env::default());
7231        assert_eq!(cs.animations.len(), 1);
7232        assert_eq!(cs.animations[0].duration, Duration::from_millis(150));
7233
7234        let engine = Engine::compile(
7235            "@keyframes enter { from { opacity: 0 } } \
7236             .animate-in { animation-name: enter; animation-duration: 150ms } \
7237             .duration-200[data-state=open] { animation-duration: 200ms }",
7238        );
7239        let cs = engine.compute(node, None, &Env::default());
7240        assert_eq!(cs.animations[0].duration, Duration::from_millis(200));
7241    }
7242
7243    #[test]
7244    fn animation_name_does_not_reset_separately_cascaded_component_lists() {
7245        let engine = Engine::compile(
7246            "@keyframes slide { from { transform: translateY(100%) } to { transform: translateY(0) } } \
7247             [data-drawer] { animation-duration: 500ms; animation-timing-function: linear; animation-delay: 20ms } \
7248             [data-drawer][data-state=open] { animation-name: slide }",
7249        );
7250        let node = Node {
7251            tag: "div",
7252            class: "",
7253            attrs: &[("data-drawer", ""), ("data-state", "open")],
7254        };
7255        let computed = engine.compute(node, None, &Env::default());
7256        assert_eq!(computed.animations[0].duration, Duration::from_millis(500));
7257        assert_eq!(
7258            computed.animations[0].delay,
7259            Duration::from_millis(20).into()
7260        );
7261        assert_eq!(computed.animations[0].easing, Easing::Linear);
7262    }
7263
7264    #[test]
7265    fn animation_component_lists_cycle_after_names_and_inline_longhands_cascade() {
7266        let engine = Engine::compile(
7267            ".box { animation-duration: 100ms, 250ms; animation-iteration-count: 2, 3; animation-delay: 30ms } \
7268             .box.on { animation-name: first, second, third }",
7269        );
7270        let node = Node {
7271            tag: "div",
7272            class: "box on",
7273            attrs: &[],
7274        };
7275        let computed = engine.compute(node, None, &Env::default());
7276        assert_eq!(
7277            computed
7278                .animations
7279                .iter()
7280                .map(|animation| animation.duration)
7281                .collect::<Vec<_>>(),
7282            vec![
7283                Duration::from_millis(100),
7284                Duration::from_millis(250),
7285                Duration::from_millis(100)
7286            ]
7287        );
7288        assert_eq!(
7289            computed
7290                .animations
7291                .iter()
7292                .map(|animation| animation.iterations)
7293                .collect::<Vec<_>>(),
7294            vec![2.0, 3.0, 2.0]
7295        );
7296        let fold_inline = |source: &str| {
7297            let inline = parse_inline_style(source, &mut Vec::new());
7298            engine.compute_node(
7299                node,
7300                Some(&inline),
7301                &Rc::new(Vars::default()),
7302                None,
7303                &Env::default(),
7304                &mut Vec::new(),
7305            )
7306        };
7307        let computed =
7308            fold_inline("animation-duration: 400ms, 600ms; animation-fill-mode: forwards");
7309        assert_eq!(
7310            computed
7311                .animations
7312                .iter()
7313                .map(|animation| animation.duration)
7314                .collect::<Vec<_>>(),
7315            vec![
7316                Duration::from_millis(400),
7317                Duration::from_millis(600),
7318                Duration::from_millis(400)
7319            ]
7320        );
7321        assert!(computed
7322            .animations
7323            .iter()
7324            .all(|animation| animation.fill == FillMode::Forwards
7325                && animation.delay == Duration::from_millis(30).into()));
7326        let computed = fold_inline("animation: replacement 75ms ease-in");
7327        assert_eq!(computed.animations.len(), 1);
7328        assert_eq!(computed.animations[0].duration, Duration::from_millis(75));
7329        assert_eq!(computed.animations[0].delay, Delay::ZERO);
7330        assert_eq!(computed.animations[0].iterations, 1.0);
7331        assert_eq!(computed.animations[0].easing, Easing::EaseIn);
7332    }
7333
7334    #[test]
7335    fn important_motion_longhands_override_normal_inline_but_preserve_other_components() {
7336        let engine = Engine::compile(".box { animation: slide 2s ease-in-out; transition: opacity 2s linear } .box { animation-duration: 10ms !important; animation-iteration-count: 1 !important; transition-duration: 12ms !important }");
7337        let fold = |source: &str| {
7338            let inline = parse_inline_style(source, &mut Vec::new());
7339            engine.compute_node(
7340                box_node(),
7341                Some(&inline),
7342                &Rc::new(Vars::default()),
7343                None,
7344                &Env::default(),
7345                &mut Vec::new(),
7346            )
7347        };
7348        let computed = fold("animation-duration: 500ms; animation-fill-mode: forwards; animation-iteration-count: 3; transition-property: transform, border-radius; transition-duration: 500ms; transition-timing-function: ease-in");
7349        assert_eq!(computed.animations[0].duration, Duration::from_millis(10));
7350        assert_eq!(computed.animations[0].iterations, 1.0);
7351        assert_eq!(computed.animations[0].fill, FillMode::Forwards);
7352        assert_eq!(computed.transitions.len(), 5);
7353        assert_eq!(
7354            computed.transitions[0].property,
7355            TransitionProperty::Transform
7356        );
7357        assert!(computed
7358            .transitions
7359            .iter()
7360            .all(
7361                |transition| transition.duration == Duration::from_millis(12)
7362                    && transition.easing == Easing::EaseIn
7363            ));
7364        let computed = fold("animation-duration: 500ms; animation-duration: 75ms !important; transition-property: transform; transition-duration: 500ms; transition-duration: 80ms !important");
7365        assert_eq!(computed.animations[0].duration, Duration::from_millis(75));
7366        assert_eq!(
7367            computed.transitions[0].property,
7368            TransitionProperty::Transform
7369        );
7370        assert_eq!(computed.transitions[0].duration, Duration::from_millis(80));
7371        let legacy = Rc::new(vec![TransitionSpec {
7372            property: TransitionProperty::Width,
7373            duration: Duration::from_millis(900),
7374            delay: Delay::ZERO,
7375            easing: Easing::Linear,
7376        }]);
7377        let computed = engine.compute_with(box_node(), None, Some(&legacy), &Env::default());
7378        assert_eq!(computed.transitions[0].property, TransitionProperty::Width);
7379        assert_eq!(computed.transitions[0].duration, Duration::from_millis(12));
7380    }
7381
7382    #[test]
7383    fn important_motion_shorthand_resets_normal_inline_components_and_inline_important_wins() {
7384        let engine = Engine::compile(".box { animation: sheet 10ms linear !important; transition: transform 20ms ease-in !important }");
7385        let fold = |source: &str| {
7386            let inline = parse_inline_style(source, &mut Vec::new());
7387            engine.compute_node(
7388                box_node(),
7389                Some(&inline),
7390                &Rc::new(Vars::default()),
7391                None,
7392                &Env::default(),
7393                &mut Vec::new(),
7394            )
7395        };
7396        let computed = fold("animation: normal 500ms ease-out; animation-fill-mode: forwards; transition: opacity 500ms linear");
7397        assert_eq!(&*computed.animations[0].name, "sheet");
7398        assert_eq!(computed.animations[0].duration, Duration::from_millis(10));
7399        assert_eq!(computed.animations[0].fill, FillMode::None);
7400        assert_eq!(
7401            computed.transitions[0].property,
7402            TransitionProperty::Transform
7403        );
7404        assert_eq!(computed.transitions[0].duration, Duration::from_millis(20));
7405        let computed = fold("animation: own 75ms ease-out !important; animation-duration: 900ms; transition: opacity 80ms linear !important; transition-duration: 900ms");
7406        assert_eq!(&*computed.animations[0].name, "own");
7407        assert_eq!(computed.animations[0].duration, Duration::from_millis(75));
7408        assert_eq!(
7409            computed.transitions[0].property,
7410            TransitionProperty::Opacity
7411        );
7412        assert_eq!(computed.transitions[0].duration, Duration::from_millis(80));
7413    }
7414
7415    #[test]
7416    fn an_animations_clock_starts_at_the_first_frame() {
7417        let engine = Engine::compile(SPIN);
7418        let cs = engine.compute(box_node(), None, &Env::default());
7419        let mut a = Animator::new();
7420        let created = Instant::now();
7421        a.on_computed_animations(1, &cs, created, &|name| {
7422            engine.keyframes(name, &Env::default())
7423        });
7424
7425        let first_frame = created + Duration::from_millis(300);
7426        a.tick(first_frame);
7427        let base = StyleRefinement::default();
7428        let halfway = first_frame + Duration::from_millis(500);
7429        assert!(
7430            (opacity(&a.overlay(1, &base, first_frame).unwrap()) - 0.0).abs() < 1e-6,
7431            "the first painted frame is the animation's frame 0"
7432        );
7433        assert!((opacity(&a.overlay(1, &base, halfway).unwrap()) - 0.5).abs() < 1e-2);
7434        a.tick(halfway);
7435        assert!((opacity(&a.overlay(1, &base, halfway).unwrap()) - 0.5).abs() < 1e-2);
7436    }
7437
7438    #[test]
7439    fn scale3d_decomposes_to_the_two_axes_that_exist() {
7440        let (r, _) =
7441            computed_with_env(".box { transform: scale3d(0.95, 0.8, 1) }", &Env::default());
7442        let t = r.vn_transform.expect("a transform");
7443        assert!((t.scale.0 - 0.95).abs() < 1e-6);
7444        assert!((t.scale.1 - 0.8).abs() < 1e-6);
7445    }
7446
7447    #[test]
7448    fn a_hover_rung_gives_up_exactly_its_transitioned_properties() {
7449        let engine = Engine::compile(
7450            ".box { transition: background-color 200ms linear; background: #000 } \
7451             .box:hover { background: #fff; padding-left: 8px }",
7452        );
7453        let cs = engine.compute(box_node(), None, &Env::default());
7454        let rung = cs.hover.as_ref().expect("a hover rung");
7455        assert!(rung.background.is_some());
7456        assert!(rung.padding.left.is_some());
7457
7458        let split = crate::strip_transitioned(rung, &cs.transitions).expect("something to strip");
7459        assert!(split.background.is_none());
7460        assert!(split.padding.left.is_some());
7461    }
7462
7463    #[test]
7464    fn the_hover_fold_follows_gpuis_own_rung_order() {
7465        let engine = Engine::compile(
7466            ".group:hover .icon { opacity: 0.5 } .icon:hover { opacity: 0.9 } \
7467             .icon { opacity: 0.1 }",
7468        );
7469        let d = group_doc();
7470        let states = cascade(&engine, &d, &Env::default());
7471        let icon = &states[2];
7472        assert!(
7473            icon.hovered(false, false).is_none(),
7474            "base state is not a fold"
7475        );
7476        assert_eq!(icon.hovered(false, true).unwrap().opacity, Some(0.5));
7477        assert_eq!(icon.hovered(true, false).unwrap().opacity, Some(0.9));
7478        assert_eq!(icon.hovered(true, true).unwrap().opacity, Some(0.9));
7479    }
7480
7481    #[test]
7482    fn a_hover_flip_interpolates_and_then_holds() {
7483        use crate::animator::Animator;
7484        let engine = Engine::compile(
7485            ".box { transition: opacity 200ms linear; opacity: 0 } .box:hover { opacity: 1 }",
7486        );
7487        let cs = engine.compute(box_node(), None, &Env::default());
7488        let base = (*cs.base).clone();
7489        let mut a = Animator::new();
7490        let now = Instant::now();
7491
7492        let target = cs.hovered(true, false);
7493        a.on_state(1, &cs, target.as_ref(), now);
7494        let half = a
7495            .overlay(1, &base, now + Duration::from_millis(100))
7496            .unwrap();
7497        assert!(
7498            (half.opacity.unwrap() - 0.5).abs() < 1e-2,
7499            "midway through, not snapped: {:?}",
7500            half.opacity
7501        );
7502
7503        let late = now + Duration::from_millis(400);
7504        a.finish_settled(late);
7505        assert!(!a.any_active(late));
7506        let held = a.overlay(1, &base, late).unwrap();
7507        assert_eq!(held.opacity, Some(1.0));
7508
7509        a.on_state(1, &cs, None, late);
7510        let back = a
7511            .overlay(1, &base, late + Duration::from_millis(100))
7512            .unwrap();
7513        assert!(
7514            (back.opacity.unwrap() - 0.5).abs() < 1e-2,
7515            "reverses: {:?}",
7516            back.opacity
7517        );
7518        let done = late + Duration::from_millis(400);
7519        a.finish_settled(done);
7520        assert!(!a.holds_state(1));
7521    }
7522
7523    #[test]
7524    fn reduced_motion_snaps_a_state_flip_rather_than_dropping_it() {
7525        use crate::animator::Animator;
7526        let engine = Engine::compile(
7527            ".box { transition: opacity 200ms linear; opacity: 0 } .box:hover { opacity: 1 }",
7528        );
7529        let cs = engine.compute(box_node(), None, &Env::default());
7530        let base = (*cs.base).clone();
7531        let mut a = Animator::new();
7532        a.set_reduce_motion(true);
7533        let now = Instant::now();
7534        a.on_state(1, &cs, cs.hovered(true, false).as_ref(), now);
7535        assert!(!a.any_active(now));
7536        assert_eq!(a.overlay(1, &base, now).unwrap().opacity, Some(1.0));
7537    }
7538
7539    #[test]
7540    fn matched_rules_report_the_cascade_in_its_own_order() {
7541        set_capture_rule_text(true);
7542        let engine = Engine::compile(
7543            r#"@media (min-width: 100px) { .tab { color: #f00 } }
7544               a { color: #001 }
7545               .tab { color: #002; padding: 4px }
7546               .tab:hover { color: #003 }
7547               .tab::after { content: "x" }"#,
7548        );
7549        set_capture_rule_text(false);
7550        let d = doc();
7551        let rules = engine.matched_rules(DocRef { doc: &d, i: 2 }, &Env::default());
7552
7553        let seen: Vec<(&str, &str)> = rules
7554            .iter()
7555            .map(|r| (r.selector.as_str(), r.state))
7556            .collect();
7557        assert_eq!(
7558            seen,
7559            vec![
7560                ("a", "base"),
7561                (".tab", "base"),
7562                (".tab", "base"),
7563                (".tab:after", "base"),
7564                (".tab:hover", "hover"),
7565            ],
7566            "ascending (specificity, order) — the cascade's own order"
7567        );
7568        let keys: Vec<(u32, u32)> = rules.iter().map(|r| (r.specificity, r.order)).collect();
7569        let mut sorted = keys.clone();
7570        sorted.sort();
7571        assert_eq!(keys, sorted);
7572
7573        let media: Vec<Option<&str>> = rules.iter().map(|r| r.media.as_deref()).collect();
7574        assert_eq!(media[1], Some("(width >= 100px)"));
7575        assert_eq!(media[2], None);
7576        assert_eq!(rules[3].pseudo, Some("::after"));
7577
7578        let tab = &rules[2];
7579        assert_eq!(
7580            tab.declarations,
7581            vec![
7582                ("color".to_string(), "#002".to_string(), false),
7583                ("padding".to_string(), "4px".to_string(), false),
7584            ]
7585        );
7586    }
7587
7588    #[test]
7589    fn border_currentcolor_cascades_per_side_without_overwriting_literal_edges() {
7590        let engine = Engine::compile(".box { color:#0000ff; border:1px solid currentColor } .box { border-left-color:#ff0000 }");
7591        let style = engine.compute(box_node(), None, &Env::default());
7592        assert_eq!(
7593            style.base.vn_border_colors.top,
7594            Some(Some(gpui::rgb(0x0000ff).into()))
7595        );
7596        assert_eq!(
7597            style.base.vn_border_colors.left,
7598            Some(Some(gpui::rgb(0xff0000).into()))
7599        );
7600        let engine=Engine::compile(".box { color:#0000ff; border:1px solid #ff0000 } .box { border-left-color:currentColor }");
7601        let style = engine.compute(box_node(), None, &Env::default());
7602        assert_eq!(
7603            style.base.vn_border_colors.top,
7604            Some(Some(gpui::rgb(0xff0000).into()))
7605        );
7606        assert_eq!(
7607            style.base.vn_border_colors.left,
7608            Some(Some(gpui::rgb(0x0000ff).into()))
7609        );
7610    }
7611
7612    #[test]
7613    fn scrollbar_color_uses_theme_variables_and_transparent_track() {
7614        let engine=Engine::compile(".box { --muted-foreground:240 5% 64%; scrollbar-color:hsl(var(--muted-foreground) / .35) transparent }");
7615        let style = engine.compute(box_node(), None, &Env::default());
7616        let (thumb, track) = style
7617            .extras
7618            .scrollbar_color
7619            .expect("theme colour pair is retained");
7620        assert!((thumb.a - 0.35).abs() < 0.01, "{thumb:?}");
7621        assert!(track.is_transparent());
7622        assert!(engine.diagnostics.is_empty(), "{:?}", engine.diagnostics);
7623    }
7624
7625    fn test_font_metrics() -> impl Drop {
7626        set_font_source(|| {
7627            vec![
7628                "Arial".into(),
7629                "SK Metric Narrow".into(),
7630                "SK Metric Wide".into(),
7631            ]
7632        });
7633        set_font_metric_source(|font, size| {
7634            let ratio = match font.family.as_ref() {
7635                "SK Metric Narrow" => {
7636                    if font.weight == gpui::FontWeight::BOLD {
7637                        0.6
7638                    } else {
7639                        0.55
7640                    }
7641                }
7642                "SK Metric Wide" => 0.8,
7643                _ => return None,
7644            };
7645            Some(FontRelativeMetrics {
7646                zero_advance: ratio * size,
7647                x_height: 0.4 * size,
7648            })
7649        });
7650        struct Reset;
7651        impl Drop for Reset {
7652            fn drop(&mut self) {
7653                set_font_metric_source(|_, _| None);
7654            }
7655        }
7656        Reset
7657    }
7658
7659    #[test]
7660    fn character_units_use_the_computed_face_weight_size_and_hover_face() {
7661        let _metrics = test_font_metrics();
7662        let engine = Engine::compile(".box { width:1ch; height:2ex; font-family:'SK Metric Narrow'; font-weight:bold; font-size:9px } .box:hover {font-family:'SK Metric Wide'; font-size:12px}");
7663        let computed = engine.compute(box_node(), None, &Env::default());
7664        assert_eq!(computed.base.size.width, Some(gpui::px(5.4).into()));
7665        assert_eq!(
7666            computed.base.size.height,
7667            Some(gpui::px(9.0 * 0.4 * 2.0).into())
7668        );
7669        assert_eq!(computed.computed_font.weight, gpui::FontWeight::BOLD);
7670        let hovered = computed.hover.expect("font state retained");
7671        assert_eq!(hovered.size.width, Some(gpui::px(9.6).into()));
7672    }
7673
7674    #[test]
7675    fn character_units_in_font_size_use_the_parent_face() {
7676        let _metrics = test_font_metrics();
7677        let engine = Engine::compile(".box {font-family:'SK Metric Wide';font-size:2ch;width:1ch}");
7678        let computed = engine.compute_node_with_font(
7679            box_node(),
7680            None,
7681            &Rc::new(Vars::default()),
7682            None,
7683            10.0,
7684            &gpui::font("SK Metric Narrow"),
7685            &Env::default(),
7686            &mut Vec::new(),
7687        );
7688        assert_eq!(computed.font_size, 11.0);
7689        assert_eq!(computed.base.size.width, Some(gpui::px(11.0 * 0.8).into()));
7690    }
7691
7692    #[test]
7693    fn inherited_faces_separate_character_unit_share_cache_entries() {
7694        let _metrics = test_font_metrics();
7695        let engine = Engine::compile(".box {width:2ch}");
7696        let vars = Rc::new(Vars::default());
7697        let read = |family| {
7698            engine.compute_node_with_font(
7699                box_node(),
7700                None,
7701                &vars,
7702                None,
7703                10.0,
7704                &gpui::font(family),
7705                &Env::default(),
7706                &mut Vec::new(),
7707            )
7708        };
7709        assert_eq!(
7710            read("SK Metric Narrow").base.size.width,
7711            Some(gpui::px(11.0).into())
7712        );
7713        assert_eq!(
7714            read("SK Metric Wide").base.size.width,
7715            Some(gpui::px(16.0).into())
7716        );
7717        assert_eq!(
7718            read("SK Metric Narrow").base.size.width,
7719            Some(gpui::px(11.0).into())
7720        );
7721    }
7722
7723    #[test]
7724    fn dynamic_character_units_use_variable_font_family_and_provider_changes_invalidate_cache() {
7725        let _metrics = test_font_metrics();
7726        let engine = Engine::compile(".box {--face:'SK Metric Wide'; font-family:var(--face); width:calc(2ch + 1px);font-size:10px}");
7727        assert_eq!(
7728            engine
7729                .compute(box_node(), None, &Env::default())
7730                .base
7731                .size
7732                .width,
7733            Some(gpui::px(17.0).into())
7734        );
7735        set_font_metric_source(|_, size| {
7736            Some(FontRelativeMetrics {
7737                zero_advance: size * 0.9,
7738                x_height: size * 0.5,
7739            })
7740        });
7741        assert_eq!(
7742            engine
7743                .compute(box_node(), None, &Env::default())
7744                .base
7745                .size
7746                .width,
7747            Some(gpui::px(19.0).into())
7748        );
7749        set_font_metric_source(|_, _| None);
7750        assert_eq!(
7751            engine
7752                .compute(box_node(), None, &Env::default())
7753                .base
7754                .size
7755                .width,
7756            Some(gpui::px(11.0).into()),
7757            "an unavailable glyph retains the CSS half-em fallback"
7758        );
7759    }
7760
7761    #[test]
7762    fn border_currentcolor_is_resolved_per_state_without_mask_bleed() {
7763        for (base_color, hover_color) in [("currentColor", "#0000ff"), ("#0000ff", "currentColor")]
7764        {
7765            let css=format!(".box {{ color:#ff0000; border:2px solid {base_color} }} .box:hover {{ border-top-color:{hover_color} }}");
7766            let computed = Engine::compile(&css).compute(box_node(), None, &Env::default());
7767            let red = gpui::rgb(0xff0000).into();
7768            let blue = gpui::rgb(0x0000ff).into();
7769            let base = if base_color == "currentColor" {
7770                red
7771            } else {
7772                blue
7773            };
7774            let hover = if hover_color == "currentColor" {
7775                red
7776            } else {
7777                blue
7778            };
7779            assert_eq!(
7780                computed.base.vn_border_colors.top,
7781                Some(Some(base)),
7782                "{css}: base top"
7783            );
7784            assert_eq!(
7785                computed.base.vn_border_colors.right,
7786                Some(Some(base)),
7787                "{css}: base right"
7788            );
7789            assert_eq!(
7790                computed.hover.as_ref().expect("hover").vn_border_colors.top,
7791                Some(Some(hover)),
7792                "{css}: hovered top"
7793            );
7794        }
7795    }
7796
7797    #[test]
7798    fn border_currentcolor_resolves_group_and_generated_box_placeholders() {
7799        let engine=Engine::compile(".icon {color:#ff0000;border:2px solid blue} .group:hover .icon {border-top-color:currentColor} .group:active .icon {border-left-color:currentColor}");
7800        let document = group_doc();
7801        let computed = cascade(&engine, &document, &Env::default());
7802        let icon = &computed[2];
7803        let red = gpui::rgb(0xff0000).into();
7804        let blue = gpui::rgb(0x0000ff).into();
7805        assert_eq!(icon.base.vn_border_colors.top, Some(Some(blue)));
7806        assert_eq!(
7807            icon.group_hover
7808                .as_ref()
7809                .expect("group hover")
7810                .1
7811                .vn_border_colors
7812                .top,
7813            Some(Some(red))
7814        );
7815        assert_eq!(
7816            icon.group_active
7817                .as_ref()
7818                .expect("group active")
7819                .1
7820                .vn_border_colors
7821                .left,
7822            Some(Some(red))
7823        );
7824        let engine=Engine::compile(".box {color:blue;border:2px solid red} .box::before {content:'x';color:#00ff00;border-top:2px solid currentColor}");
7825        let computed = engine.compute(box_node(), None, &Env::default());
7826        assert_eq!(computed.base.vn_border_colors.top, Some(Some(red)));
7827        assert_eq!(
7828            computed
7829                .before
7830                .as_ref()
7831                .expect("generated box")
7832                .style
7833                .vn_border_colors
7834                .top,
7835            Some(Some(gpui::rgb(0x00ff00).into()))
7836        );
7837    }
7838
7839    #[test]
7840    fn registered_percentage_drift_remaps_background_position_without_overriding_hover_or_typed_animation(
7841    ) {
7842        let engine = Engine::compile(
7843            r#"
7844            @property --offset { syntax: "<percentage>"; inherits: false; initial-value: 0%; }
7845            @keyframes travel { to { --offset: -200%; } }
7846            @keyframes fade { to { opacity: 1; } }
7847            .box { color: red; opacity: .4; background-image: linear-gradient(red, blue);
7848                background-size: 200% 100%; background-position: var(--offset) 0;
7849                animation: travel 6s linear infinite, fade 6s linear; }
7850            .box:hover { color: blue; transform: translateX(9px); }
7851            .box:focus { color: green; }
7852        "#,
7853        );
7854        let env = Env::default();
7855        let states = engine.compute(box_node(), None, &env);
7856        assert_eq!(states.vars.get("--offset"), Some("0%"));
7857        let frames = engine
7858            .keyframes_for("travel", &states.vars, &env, &mut Vec::new())
7859            .unwrap();
7860        assert_eq!(
7861            frames.steps.len(),
7862            1,
7863            "custom-only keyframes must survive compilation"
7864        );
7865        assert!(frames.steps[0].custom.is_some());
7866        let now = Instant::now();
7867        let mut animator = Animator::new();
7868        animator.on_computed_animations(1, &states, now, &|name| {
7869            engine.keyframes_for(name, &states.vars, &env, &mut Vec::new())
7870        });
7871        for (ms, expected) in [(0, 0.), (1500, -0.5), (3000, -1.), (4500, -1.5)] {
7872            let at = now + Duration::from_millis(ms);
7873            let extras = animator
7874                .animated_extras(1, at)
7875                .expect("registered dependent paint");
7876            assert_eq!(
7877                extras.background_position.as_ref().unwrap()[0].0,
7878                TileLength::Fraction(expected)
7879            );
7880            assert_eq!(
7881                extras.background_size, states.extras.background_size,
7882                "the travelling tile retains its authored size"
7883            );
7884            let overlay = animator.overlay(1, &states.base, at).unwrap();
7885            assert!(
7886                overlay.text.color.is_none(),
7887                "unrelated base text must not override interaction rungs"
7888            );
7889            assert!(overlay.vn_transform.is_none());
7890            assert!((overlay.opacity.unwrap() - (0.4 + 0.6 * ms as f32 / 6000.)).abs() < 1e-5);
7891            let mut live = (*states.base).clone();
7892            live.refine(&overlay);
7893            live.refine(states.hover.as_ref().unwrap());
7894            assert_eq!(live.text.color, Some(gpui::blue()));
7895            assert!(live.vn_transform.is_some());
7896            live.refine(states.focus.as_ref().unwrap());
7897            assert_eq!(live.text.color, Some(gpui::rgb(0x008000).into()));
7898        }
7899    }
7900
7901    #[test]
7902    fn registered_percentage_defaults_and_scoped_overrides_respect_inherits_false() {
7903        let engine = Engine::compile(
7904            r#"
7905            @property --local { syntax: "<percentage>"; inherits: false; initial-value: 7%; }
7906            @property --shared { syntax: "<percentage>"; inherits: true; initial-value: 3%; }
7907            :root { --local: 80%; --shared: 90%; }
7908            .page { --local: 40%; }
7909            .btn { background-position: var(--local) var(--shared); }
7910        "#,
7911        );
7912        let states = cascade(&engine, &themed_doc(), &Env::default());
7913        assert_eq!(states[0].vars.get("--local"), Some("80%"));
7914        assert_eq!(states[1].vars.get("--local"), Some("40%"));
7915        assert_eq!(
7916            states[2].vars.get("--local"),
7917            Some("7%"),
7918            "registered non-inherited values reset on each element"
7919        );
7920        assert_eq!(states[2].vars.get("--shared"), Some("90%"));
7921        assert_eq!(
7922            states[2].extras.background_position.as_ref().unwrap()[0],
7923            (TileLength::Fraction(0.07), TileLength::Fraction(0.9))
7924        );
7925    }
7926
7927    #[test]
7928    fn registered_animation_preserves_important_custom_and_dependent_declarations() {
7929        for important in [
7930            "--offset: 25% !important",
7931            "background-position: 75% 0 !important",
7932        ] {
7933            let engine = Engine::compile(&format!(
7934                r#"
7935                @property --offset {{ syntax: "<percentage>"; inherits: false; initial-value: 0%; }}
7936                @keyframes travel {{ to {{ --offset: -200%; }} }}
7937                .box {{ background-position: var(--offset) 0; animation: travel 6s linear infinite; }}
7938                .box {{ {important}; }}
7939            "#
7940            ));
7941            let env = Env::default();
7942            let states = engine.compute(box_node(), None, &env);
7943            let now = Instant::now();
7944            let mut animator = Animator::new();
7945            animator.on_computed_animations(1, &states, now, &|name| {
7946                engine.keyframes_for(name, &states.vars, &env, &mut Vec::new())
7947            });
7948            let extras = animator
7949                .animated_extras(1, now + Duration::from_secs(3))
7950                .unwrap_or_else(|| states.extras.clone());
7951            let expected = if important.starts_with("--") {
7952                0.25
7953            } else {
7954                0.75
7955            };
7956            assert_eq!(
7957                extras.background_position.as_ref().unwrap()[0].0,
7958                TileLength::Fraction(expected),
7959                "{important}"
7960            );
7961        }
7962    }
7963
7964    #[test]
7965    fn registered_animation_implicit_endpoint_uses_each_elements_own_variables_and_pauses() {
7966        let engine = Engine::compile(
7967            r#"
7968            @property --offset { syntax: "<percentage>"; inherits: false; initial-value: 0%; }
7969            @keyframes travel { to { --offset: -200%; } }
7970            .box { background-position: var(--offset) 0; animation: travel 6s linear infinite paused; }
7971        "#,
7972        );
7973        let env = Env::default();
7974        for initial in ["0%", "50%"] {
7975            let inline = parse_inline_style(&format!("--offset:{initial}"), &mut Vec::new());
7976            let states = engine.compute_node(
7977                box_node(),
7978                Some(&inline),
7979                &Rc::new(Vars::default()),
7980                None,
7981                &env,
7982                &mut Vec::new(),
7983            );
7984            let now = Instant::now();
7985            let mut animator = Animator::new();
7986            animator.on_computed_animations(1, &states, now, &|name| {
7987                engine.keyframes_for(name, &states.vars, &env, &mut Vec::new())
7988            });
7989            for elapsed in [0, 3000] {
7990                let extras = animator
7991                    .animated_extras(1, now + Duration::from_millis(elapsed))
7992                    .unwrap();
7993                assert_eq!(
7994                    extras.background_position.as_ref().unwrap()[0].0,
7995                    TileLength::Fraction(crate::registered::percentage(initial).unwrap())
7996                );
7997            }
7998        }
7999    }
8000
8001    #[test]
8002    fn registered_defaults_share_variables_and_unrelated_animations_keep_no_recipe() {
8003        let engine = Engine::compile(
8004            r#"
8005            @property --offset { syntax: "<percentage>"; inherits: false; initial-value: 0%; }
8006            @keyframes spin { to { transform: rotate(360deg); } }
8007            .btn { animation: spin 1s linear infinite; }
8008        "#,
8009        );
8010        let states = cascade(&engine, &themed_doc(), &Env::default());
8011        assert!(Rc::ptr_eq(&states[0].vars, &states[1].vars));
8012        assert!(
8013            Rc::ptr_eq(&states[1].vars, &states[2].vars),
8014            "unchanged defaults retain the no-allocation inheritance path"
8015        );
8016        assert!(
8017            states[2].custom_animation.is_none(),
8018            "a spinner does not animate a registered property"
8019        );
8020    }
8021
8022    #[test]
8023    fn registered_sample_is_invalidated_when_same_frame_computed_values_change() {
8024        let engine = Engine::compile(
8025            r#"
8026            @property --offset { syntax: "<percentage>"; inherits: false; initial-value: 0%; }
8027            @keyframes travel { to { --offset: -200%; } }
8028            .box { background-position: var(--offset) 0; animation: travel 6s linear infinite; }
8029        "#,
8030        );
8031        let env = Env::default();
8032        let now = Instant::now();
8033        let mut animator = Animator::new();
8034        for value in ["0%", "50%"] {
8035            let inline = parse_inline_style(&format!("--offset:{value}"), &mut Vec::new());
8036            let states = engine.compute_node(
8037                box_node(),
8038                Some(&inline),
8039                &Rc::new(Vars::default()),
8040                None,
8041                &env,
8042                &mut Vec::new(),
8043            );
8044            animator.on_computed_animations(1, &states, now, &|name| {
8045                engine.keyframes_for(name, &states.vars, &env, &mut Vec::new())
8046            });
8047            let _ = animator.overlay(1, &states.base, now);
8048            let extras = animator.animated_extras(1, now).unwrap();
8049            assert_eq!(
8050                extras.background_position.as_ref().unwrap()[0].0,
8051                TileLength::Fraction(crate::registered::percentage(value).unwrap())
8052            );
8053        }
8054        animator.cancel_animations(1, now);
8055        assert!(
8056            animator.animated_extras(1, now).is_none(),
8057            "cancel cannot reuse a cached paint sample"
8058        );
8059    }
8060
8061    #[test]
8062    fn registered_replay_interleaves_inline_priority_and_fences_inline_important_custom_values() {
8063        let env = Env::default();
8064        for (sheet, inline_css, expected) in [
8065            (
8066                "background-position:75% 0!important",
8067                "background-position:var(--offset) 0",
8068                0.75,
8069            ),
8070            (
8071                "background-position:75% 0!important",
8072                "background-position:35% 0!important",
8073                0.35,
8074            ),
8075            ("--offset:25%!important", "--offset:50%", 0.25),
8076            ("--offset:25%!important", "--offset:30%!important", 0.30),
8077        ] {
8078            let engine = Engine::compile(&format!(
8079                r#"
8080                @property --offset {{ syntax:"<percentage>"; inherits:false; initial-value:0%; }}
8081                @keyframes travel {{ to {{ --offset:-200%; }} }}
8082                .box {{ background-position:var(--offset) 0; animation:travel 6s linear infinite; {sheet} }}
8083            "#
8084            ));
8085            let inline = parse_inline_style(inline_css, &mut Vec::new());
8086            let states = engine.compute_node(
8087                box_node(),
8088                Some(&inline),
8089                &Rc::new(Vars::default()),
8090                None,
8091                &env,
8092                &mut Vec::new(),
8093            );
8094            let now = Instant::now();
8095            let mut animator = Animator::new();
8096            animator.on_computed_animations(1, &states, now, &|name| {
8097                engine.keyframes_for(name, &states.vars, &env, &mut Vec::new())
8098            });
8099            let extras = animator
8100                .animated_extras(1, now + Duration::from_secs(3))
8101                .unwrap_or_else(|| states.extras.clone());
8102            assert_eq!(
8103                extras.background_position.as_ref().unwrap()[0].0,
8104                TileLength::Fraction(expected),
8105                "sheet={sheet}, inline={inline_css}"
8106            );
8107        }
8108    }
8109}