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