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