Skip to main content

parsec_css/cascade/
mod.rs

1// SPDX-License-Identifier: Apache-2.0
2// Copyright 2026 James Conway
3
4//! The cascade, CSS Cascading and Inheritance Level 5, over a Parsec
5//! document: stylesheets from the user agent, the user and the author,
6//! `@media` and `@supports` evaluated against an [`Environment`],
7//! `@layer`, nesting, specificity, `!important` and `style=""`, then
8//! every element's computed values with inheritance, the CSS-wide
9//! keywords (`revert` and `revert-layer` included), custom properties and
10//! `var()`.
11//!
12//! ```
13//! use parsec_css::cascade::Styler;
14//!
15//! let doc = parsec::parse(
16//!     "<style>@media (min-width: 600px) { p { font-size: 2em } } .x { color: red !important }</style>\
17//!      <p class=x style='color: blue'>hi</p>",
18//!     false,
19//! );
20//! let styled = Styler::new(Default::default()).with_document_styles(&doc).style(&doc);
21//! let p = parsec::css::SelectorList::parse("p").unwrap().select_first(&doc, doc.root()).unwrap();
22//! assert_eq!(styled.get(p, "color").as_deref(), Some("rgb(255, 0, 0)"));
23//! assert_eq!(styled.get(p, "font-size").as_deref(), Some("32px"));
24//! assert_eq!(styled.get(p, "display").as_deref(), Some("block"));
25//! ```
26//!
27//! `@scope` applies with scoping proximity in the cascade order;
28//! `@container`, and the `cq*` units, against the sizes
29//! [`Styler::container_sizes`] gives;
30//! `@import` through the fetch [`Styler::fetch`] gives, with `layer()`,
31//! `supports()` and media; `@property` registers custom properties, which
32//! then take their syntax, initial value and inheritance from it; and
33//! [`Styler::at_rules`] gives the `@keyframes`, `@counter-style` and
34//! `@property` rules that win.
35//!
36//! Pseudo-elements are styled too, CSS Pseudo-Elements 4: a rule whose
37//! selector ends in `::before`, `::after`, `::marker`, `::placeholder`,
38//! `::first-line`, `::first-letter`, `::selection`, `::backdrop`,
39//! `::file-selector-button` or `::highlight()` applies to that
40//! pseudo-element of the elements the rest of it matches, and
41//! [`Styled::get_pseudo`] gives its computed values, inherited from the
42//! originating element, with only the properties that apply to it
43//! counted, and `content` worked out. They're computed when asked for,
44//! not before.
45//!
46//! What it doesn't do is layout: a value that needs boxes to work out,
47//! `width: 50%` as pixels say, stays as its computed value, and a
48//! container's size is the caller's to give.
49
50mod compute;
51mod pseudo;
52
53use std::collections::HashMap;
54use std::sync::Arc;
55
56use parsec::css::SelectorList;
57use parsec::{Document, Kind, NodeId};
58
59use crate::media::{Environment, MediaQueryList};
60use crate::parser::{Block, ComponentValue, Item, Rule};
61use crate::rules::{
62    ContainerQuery, CounterStyle, Import, Keyframes, PropertyRule, ScopeBounds, Syntax,
63};
64use crate::tokenizer::Token;
65use crate::values::{CssWide, Specified, expand, property};
66
67pub use compute::Computed;
68pub use pseudo::Pseudo;
69use pseudo::{PseudoRule, PseudoStyles, Split, split_pseudo};
70
71/// Where a stylesheet comes from, which decides what wins between them.
72#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)]
73pub enum Origin {
74    UserAgent,
75    User,
76    Author,
77}
78
79/// The HTML Standard's default styles, from its rendering section
80/// (§15.3), the parts that don't need layout or form controls.
81pub const HTML_UA_STYLESHEET: &str = include_str!("html.css");
82
83struct Sheet {
84    css: String,
85    origin: Origin,
86    media: Option<MediaQueryList>,
87    /// The `<style>` it came from, whose parent an `@scope` with no root
88    /// is scoped to.
89    owner: Option<NodeId>,
90}
91
92/// What an `@import`'s URL gives: the stylesheet's text, or `None`.
93pub type Fetch = Arc<dyn Fn(&str) -> Option<String> + Send + Sync>;
94
95/// A container's size, width and height in CSS pixels, from the element
96/// and its computed values; `None` for one whose size isn't known.
97pub type ContainerSize = Arc<dyn Fn(NodeId, &Computed) -> Option<(f64, f64)> + Send + Sync>;
98
99/// Collects stylesheets and styles documents with them.
100#[derive(Default)]
101pub struct Styler {
102    env: Environment,
103    sheets: Vec<Sheet>,
104    /// Whether `style=""` attributes count, as they do in a browser.
105    style_attributes: bool,
106    fetch: Option<Fetch>,
107    container_size: Option<ContainerSize>,
108}
109
110/// How deep `@import`s may nest, and how many one styling may follow:
111/// past either, the rest aren't fetched.
112const MAX_IMPORT_DEPTH: usize = 16;
113const MAX_IMPORTS: usize = 256;
114
115/// The `@keyframes`, `@counter-style` and `@property` rules that win, by
116/// name: the last of a name in the cascade's order, layers counted.
117#[derive(Clone, Debug, Default, PartialEq)]
118pub struct AtRules {
119    pub keyframes: Vec<Keyframes>,
120    pub counter_styles: Vec<CounterStyle>,
121    pub properties: Vec<PropertyRule>,
122}
123
124/// A declaration where the cascade put it.
125#[derive(Clone)]
126struct Declared<'s> {
127    value: Specified<'s>,
128    /// For a longhand set from a shorthand with `var()` in it: the
129    /// shorthand, whose value is split once it's substituted.
130    from_shorthand: Option<&'static str>,
131    key: Key,
132}
133
134/// What orders declarations, CSS Cascade 5 §6: origin and importance,
135/// then `style=""`, then layer, then specificity, then order.
136#[derive(Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Debug)]
137struct Key {
138    origin: u8,
139    attached: bool,
140    layer: u32,
141    specificity: (u32, u32, u32),
142    /// Scoping proximity, CSS Cascade 6 §6.6: nearer roots win, and an
143    /// unscoped rule is the farthest of all.
144    proximity: u32,
145    order: u32,
146}
147
148/// One style rule's selector, one complex selector of its list each, and
149/// its declarations.
150#[derive(Clone)]
151struct Entry<'s> {
152    selector: SelectorList,
153    /// What an element must have for the selector to have a chance.
154    bucket: Bucket,
155    specificity: (u32, u32, u32),
156    origin: Origin,
157    layer: usize,
158    order: u32,
159    declarations: Vec<(&'s str, &'s [ComponentValue<'s>], bool)>,
160    scope: Option<Arc<Scope>>,
161    /// The `@container` rules it's in, each a list of queries any of
162    /// which may hold.
163    containers: Vec<Arc<Vec<ContainerQuery>>>,
164    /// The pseudo-element a rule styles, whose originating element
165    /// `selector` matches.
166    pseudo: Option<Pseudo>,
167    /// Whether the selector is `*`, which every element matches.
168    any: bool,
169}
170
171/// An `@scope` a rule is in.
172struct Scope {
173    start: ScopeStart,
174    end: Option<SelectorList>,
175    /// The `@scope` this one is in, which its roots must be in scope of.
176    outer: Option<Arc<Scope>>,
177}
178
179enum ScopeStart {
180    Selector(SelectorList),
181    /// No `<scope-start>`: the parent of the `<style>` it's in, or the
182    /// document for a sheet with none.
183    Owner(Option<NodeId>),
184}
185
186/// Every element's computed values.
187pub struct Styled {
188    styles: HashMap<NodeId, Computed>,
189    pseudo: PseudoStyles,
190}
191
192impl Styled {
193    /// `property`'s value on `el`, as `getComputedStyle()` writes it, or
194    /// `None` for a node that isn't an element or a property that isn't.
195    pub fn get(&self, el: NodeId, property: &str) -> Option<String> {
196        self.styles.get(&el)?.get(property)
197    }
198
199    /// Everything about one element's style.
200    pub fn computed(&self, el: NodeId) -> Option<&Computed> {
201        self.styles.get(&el)
202    }
203}
204
205impl Styler {
206    /// A styler with the HTML user agent stylesheet, `style=""` counted.
207    pub fn new(env: Environment) -> Styler {
208        let mut s = Styler {
209            env,
210            style_attributes: true,
211            ..Styler::default()
212        };
213        s.add(HTML_UA_STYLESHEET, Origin::UserAgent);
214        s
215    }
216
217    /// A styler with no stylesheet at all, not even the user agent's.
218    pub fn bare(env: Environment) -> Styler {
219        Styler {
220            env,
221            style_attributes: true,
222            ..Styler::default()
223        }
224    }
225
226    pub fn environment(&self) -> &Environment {
227        &self.env
228    }
229
230    /// Adds a stylesheet.
231    pub fn add(&mut self, css: &str, origin: Origin) -> &mut Styler {
232        self.sheets.push(Sheet {
233            css: css.to_string(),
234            origin,
235            media: None,
236            owner: None,
237        });
238        self
239    }
240
241    /// Adds a stylesheet that applies only where `media` matches, as a
242    /// `<style media>` or `<link media>` does.
243    pub fn add_with_media(&mut self, css: &str, origin: Origin, media: &str) -> &mut Styler {
244        self.sheets.push(Sheet {
245            css: css.to_string(),
246            origin,
247            media: Some(MediaQueryList::parse_str(media)),
248            owner: None,
249        });
250        self
251    }
252
253    /// Fetches `@import`ed stylesheets with `fetch`, given each URL as
254    /// written; without it, `@import` is ignored.
255    pub fn fetch(
256        mut self,
257        fetch: impl Fn(&str) -> Option<String> + Send + Sync + 'static,
258    ) -> Styler {
259        self.fetch = Some(Arc::new(fetch));
260        self
261    }
262
263    /// Gives each container's size, for `@container` and the `cq*` units:
264    /// `size` is asked for an element whose `container-type` makes it a
265    /// container, with its computed values, and gives its width and height
266    /// in CSS pixels. A query on a container with no size given is false,
267    /// and `cq*` units look past it to the next container out, or the
268    /// viewport.
269    pub fn container_sizes(
270        mut self,
271        size: impl Fn(NodeId, &Computed) -> Option<(f64, f64)> + Send + Sync + 'static,
272    ) -> Styler {
273        self.container_size = Some(Arc::new(size));
274        self
275    }
276
277    /// Adds the document's own `<style>` elements, with their `media`, as
278    /// author stylesheets.
279    pub fn with_document_styles(mut self, doc: &Document) -> Styler {
280        let style = SelectorList::parse("style").unwrap();
281        for el in style.select(doc, doc.root()) {
282            let media = doc
283                .attrs(el)
284                .find(|(_, n, _)| *n == "media")
285                .map(|(_, _, v)| v.to_string());
286            let css = doc.text(el);
287            match media {
288                Some(m) => self.add_with_media(&css, Origin::Author, &m),
289                None => self.add(&css, Origin::Author),
290            };
291            if let Some(last) = self.sheets.last_mut() {
292                last.owner = Some(el);
293            }
294        }
295        self
296    }
297
298    /// Whether `style=""` attributes count; they do unless this says not.
299    pub fn style_attributes(mut self, on: bool) -> Styler {
300        self.style_attributes = on;
301        self
302    }
303
304    /// Styles every element of `doc`.
305    pub fn style(&self, doc: &Document) -> Styled {
306        self.style_some(doc, None)
307    }
308
309    /// Styles one element, and the ancestors it inherits from, but no
310    /// other: the cheap way to one element's computed values.
311    pub fn style_element(&self, doc: &Document, el: NodeId) -> Option<Computed> {
312        let mut chain = vec![el];
313        let mut at = el;
314        while let Some(p) = doc.parent(at) {
315            if matches!(doc.kind(p), Kind::Element { .. }) {
316                chain.push(p);
317            }
318            at = p;
319        }
320        chain.reverse();
321        let mut styled = self.style_some(doc, Some(&chain));
322        styled.styles.remove(&el)
323    }
324
325    /// Each sheet that applies, with what it `@import`s before it, in the
326    /// cascade's order.
327    fn units(&self) -> Vec<Unit> {
328        let mut out = Vec::new();
329        let mut count = 0;
330        for s in &self.sheets {
331            if s.origin == Origin::UserAgent && s.css == HTML_UA_STYLESHEET {
332                continue;
333            }
334            if !s.media.as_ref().is_none_or(|m| m.matches(&self.env)) {
335                continue;
336            }
337            self.expand(
338                s.css.clone(),
339                (s.origin, s.owner),
340                (Vec::new(), Vec::new()),
341                0,
342                &mut count,
343                &mut out,
344            );
345        }
346        out
347    }
348
349    /// A sheet, after the sheets its `@import`s bring in, each in the
350    /// layer the import puts it.
351    #[allow(clippy::too_many_arguments)]
352    fn expand(
353        &self,
354        css: String,
355        (origin, owner): (Origin, Option<NodeId>),
356        (layer, scopes): (Vec<String>, Vec<ScopeBounds>),
357        depth: usize,
358        count: &mut usize,
359        out: &mut Vec<Unit>,
360    ) {
361        if let Some(fetch) = &self.fetch {
362            let sheet = crate::parse_stylesheet(&css);
363            // `@layer` statements before the imports name their layers
364            // first.
365            let mut declared = Vec::new();
366            for rule in &sheet.rules {
367                let Rule::At(a) = rule else { break };
368                match a.name.to_ascii_lowercase().as_str() {
369                    "charset" => {}
370                    "layer" if a.block.is_none() => {
371                        for n in layer_names(&a.prelude) {
372                            let mut path = layer.clone();
373                            path.extend(n);
374                            if path.len() <= MAX_LAYER_DEPTH {
375                                declared.push(path);
376                            }
377                        }
378                    }
379                    "import" => {
380                        let Some(import) = Import::parse(a) else {
381                            continue;
382                        };
383                        if !import.applies(&self.env)
384                            || depth >= MAX_IMPORT_DEPTH
385                            || *count >= MAX_IMPORTS
386                        {
387                            continue;
388                        }
389                        *count += 1;
390                        let mut path = layer.clone();
391                        match &import.layer {
392                            Some(Some(n)) => path.extend(n.split('.').map(String::from)),
393                            // Each anonymous layer its own.
394                            Some(None) => path.push(format!("\u{0}import{count}")),
395                            None => {}
396                        }
397                        if path.len() > MAX_LAYER_DEPTH {
398                            continue;
399                        }
400                        // The layer is named whether the sheet loads or not.
401                        if import.layer.is_some() {
402                            declared.push(path.clone());
403                        }
404                        out.push(Unit::layers(std::mem::take(&mut declared)));
405                        let Some(text) = fetch(&import.url) else {
406                            continue;
407                        };
408                        let mut inner = scopes.clone();
409                        inner.extend(import.scope.clone());
410                        self.expand(text, (origin, owner), (path, inner), depth + 1, count, out);
411                    }
412                    _ => break,
413                }
414            }
415        }
416        out.push(Unit {
417            css,
418            origin,
419            owner,
420            layer,
421            declare: Vec::new(),
422            scopes,
423        });
424    }
425
426    /// The rules of every sheet that applies, collected.
427    fn collect<'u>(
428        &self,
429        parsed: &'u [(&'u Unit, crate::Stylesheet<'u, Block<'u>>)],
430        layers: &mut Layers,
431        entries: &mut Vec<Entry<'u>>,
432        at: &mut Collected,
433    ) {
434        let mut order = 0;
435        // The HTML user agent stylesheet is the same every time: its rules
436        // are collected once, for every styler.
437        if self
438            .sheets
439            .iter()
440            .any(|s| s.origin == Origin::UserAgent && s.css == HTML_UA_STYLESHEET)
441        {
442            let (ua, n) = ua_entries();
443            entries.extend(ua.iter().cloned());
444            order = *n;
445        }
446        for (unit, parsed) in parsed {
447            for path in &unit.declare {
448                layers.id(path);
449            }
450            let mut cx = Collect {
451                env: &self.env,
452                origin: unit.origin,
453                layers,
454                entries,
455                order: &mut order,
456                owner: unit.owner,
457                scope: None,
458                containers: Vec::new(),
459                at,
460                depth: 0,
461            };
462            // An `@import … scope()`'s sheet is as if in that `@scope`.
463            if unit.scopes.iter().all(|b| cx.enter_scope(b, &[])) {
464                cx.rules(&parsed.rules, &[], &unit.layer);
465            }
466        }
467    }
468
469    /// The `@keyframes`, `@counter-style` and `@property` rules in force:
470    /// for each name, the one the cascade's order puts last.
471    pub fn at_rules(&self) -> AtRules {
472        let units = self.units();
473        let parsed: Vec<_> = units
474            .iter()
475            .map(|u| (u, crate::parse_stylesheet_deep(&u.css)))
476            .collect();
477        let mut layers = Layers::default();
478        let mut entries = Vec::new();
479        let mut at = Collected::default();
480        self.collect(&parsed, &mut layers, &mut entries, &mut at);
481        let ranks = layers.ranks();
482        at.resolved(&ranks)
483    }
484
485    fn style_some(&self, doc: &Document, only: Option<&[NodeId]>) -> Styled {
486        let units = self.units();
487        let parsed: Vec<_> = units
488            .iter()
489            .map(|u| (u, crate::parse_stylesheet_deep(&u.css)))
490            .collect();
491        let mut layers = Layers::default();
492        let mut entries = Vec::new();
493        let mut at = Collected::default();
494        self.collect(&parsed, &mut layers, &mut entries, &mut at);
495        let ranks = layers.ranks();
496        let registered: HashMap<String, (PropertyRule, Syntax)> = at
497            .resolved(&ranks)
498            .properties
499            .into_iter()
500            .filter(PropertyRule::registers)
501            .filter_map(|p| {
502                let syntax = Syntax::parse(&p.syntax)?;
503                Some((p.name.clone(), (p, syntax)))
504            })
505            .collect();
506        let mut scope_cache = ScopeCache::default();
507        let mut index = Index::default();
508        let mut pseudo = PseudoStyles {
509            env: self.env.clone(),
510            root: doc_element(doc),
511            ..PseudoStyles::default()
512        };
513        // Each pseudo-element rule's place in `pseudo.rules`, where it's
514        // copied the first time an element matches it.
515        let mut rule_of: HashMap<usize, usize> = HashMap::new();
516        for (i, e) in entries.iter().enumerate() {
517            // On every element alike: kept once, not per element.
518            if e.pseudo.is_some() && e.any && e.scope.is_none() && e.containers.is_empty() {
519                let rule = PseudoRule::of(e);
520                if !rule.needs_attrs {
521                    pseudo.rules.push(rule);
522                    let key = self.key(e, &ranks, 0);
523                    pseudo.always.push((pseudo.rules.len() - 1, key));
524                    continue;
525                }
526            }
527            match &e.bucket {
528                Bucket::Id(x) => index.ids.entry(x.clone()).or_default().push(i),
529                Bucket::Class(x) => index.classes.entry(x.clone()).or_default().push(i),
530                Bucket::Tag(x) => index.tags.entry(x.clone()).or_default().push(i),
531                Bucket::Attr(x) => index.attrs.entry(x.clone()).or_default().push(i),
532                Bucket::Universal => index.universal.push(i),
533            }
534        }
535        // Style attributes, parsed once each.
536        let mut inline = HashMap::new();
537        let attrs: Vec<(NodeId, String)> = if self.style_attributes {
538            elements(doc)
539                .filter_map(|el| {
540                    doc.attrs(el)
541                        .find(|(_, n, _)| *n == "style")
542                        .map(|(_, _, v)| (el, v.to_string()))
543                })
544                .collect()
545        } else {
546            Vec::new()
547        };
548        let parsed_attrs: Vec<(NodeId, crate::BlockContents<'_>)> = attrs
549            .iter()
550            .map(|(el, css)| (*el, crate::parse_declaration_list(css)))
551            .collect();
552        for (el, block) in &parsed_attrs {
553            inline.insert(*el, block);
554        }
555        let mut styles = HashMap::new();
556        let root = doc_element(doc);
557        // Parents before children: document order.
558        let order: Vec<NodeId> = match only {
559            Some(chain) => chain.to_vec(),
560            None => elements(doc).collect(),
561        };
562        for el in order {
563            let mut declared: HashMap<&'static str, Vec<Declared<'_>>> = HashMap::new();
564            let mut custom: HashMap<String, Vec<(Key, Vec<ComponentValue<'_>>)>> = HashMap::new();
565            // Only the rules whose rightmost id, class or type this element
566            // has are tried.
567            let mut candidates: Vec<usize> = index.universal.clone();
568            if let Some(name) = doc.lower_name(el) {
569                candidates.extend(index.tags.get(name).into_iter().flatten());
570            }
571            for (_, n, v) in doc.attrs(el) {
572                candidates.extend(index.attrs.get(n).into_iter().flatten());
573                if n == "id" {
574                    candidates.extend(index.ids.get(v).into_iter().flatten());
575                } else if n == "class" {
576                    for c in v.split_ascii_whitespace() {
577                        candidates.extend(index.classes.get(c).into_iter().flatten());
578                    }
579                }
580            }
581            candidates.sort_unstable();
582            candidates.dedup();
583            let mut pseudo_candidates = Vec::new();
584            for &i in &candidates {
585                let e = &entries[i];
586                if e.pseudo.is_some() {
587                    // Once this element's style is known: a pseudo-element's
588                    // container may be its originating element.
589                    pseudo_candidates.push(i);
590                    continue;
591                }
592                let Some(proximity) =
593                    self.entry_matches(e, doc, el, &styles, &mut scope_cache, false)
594                else {
595                    continue;
596                };
597                let key = self.key(e, &ranks, proximity);
598                for (name, value, important) in &e.declarations {
599                    add(&mut declared, &mut custom, name, value, *important, key);
600                }
601            }
602            if let Some(block) = inline.get(&el) {
603                for item in &block.items {
604                    if let Item::Declaration(d) = item {
605                        let key = Key {
606                            origin: Origin::Author as u8,
607                            attached: true,
608                            layer: ranks[0],
609                            specificity: (0, 0, 0),
610                            proximity: 0,
611                            order: u32::MAX,
612                        };
613                        add(
614                            &mut declared,
615                            &mut custom,
616                            &d.name,
617                            &d.value,
618                            d.important,
619                            key,
620                        );
621                    }
622                }
623            }
624            for list in declared.values_mut() {
625                list.sort_by_key(|d| d.key);
626            }
627            for list in custom.values_mut() {
628                list.sort_by_key(|d| d.0);
629            }
630            let parent_id = doc.parent(el);
631            let parent = parent_id.and_then(|p| styles.get(&p));
632            let parent_id = parent_id.filter(|_| parent.is_some());
633            let root_style = if Some(el) == root {
634                None
635            } else {
636                root.and_then(|r| styles.get(&r))
637            };
638            let mut computed = compute::compute(compute::Input {
639                declared: &declared,
640                custom: &custom,
641                parent,
642                root: root_style,
643                is_root: Some(el) == root,
644                env: &self.env,
645                cq: parent.map_or((self.env.width, self.env.height), |p| p.cq_children),
646                registered: &registered,
647            });
648            // A size container is what its descendants' `cq*` units are
649            // relative to, on the axes it contains; one with no size given
650            // passes its own on.
651            let (w, h) = computed.size_axes();
652            if (w || h)
653                && let Some((width, height)) =
654                    self.container_size.as_ref().and_then(|f| f(el, &computed))
655            {
656                if w {
657                    computed.cq_children.0 = width;
658                }
659                if h {
660                    computed.cq_children.1 = height;
661                }
662            }
663            computed.parent = parent_id;
664            styles.insert(el, computed);
665            let mut matched = Vec::new();
666            for i in pseudo_candidates {
667                let e = &entries[i];
668                if let Some(proximity) =
669                    self.entry_matches(e, doc, el, &styles, &mut scope_cache, true)
670                {
671                    let r = *rule_of.entry(i).or_insert_with(|| {
672                        pseudo.rules.push(PseudoRule::of(e));
673                        pseudo.rules.len() - 1
674                    });
675                    if pseudo.rules[r].needs_attrs && !pseudo.attrs.contains_key(&el) {
676                        let attrs = doc
677                            .attrs(el)
678                            .map(|(_, n, v)| (n.to_string(), v.to_string()))
679                            .collect();
680                        pseudo.attrs.insert(el, attrs);
681                    }
682                    matched.push((r, self.key(e, &ranks, proximity)));
683                }
684            }
685            if !matched.is_empty() {
686                pseudo.matched.insert(el, matched);
687            }
688        }
689        pseudo.registered = registered;
690        Styled { styles, pseudo }
691    }
692
693    /// Where a rule's declarations go in the cascade's order.
694    #[inline]
695    fn key(&self, e: &Entry<'_>, ranks: &[u32], proximity: u32) -> Key {
696        Key {
697            origin: e.origin as u8,
698            attached: false,
699            layer: ranks[e.layer],
700            specificity: e.specificity,
701            proximity,
702            order: e.order,
703        }
704    }
705
706    /// Whether a rule applies to `el`, with its scoping proximity if so.
707    /// `inclusive` is for a pseudo-element's rule, whose containers start
708    /// at `el`, the originating element, which must be styled already.
709    #[inline]
710    fn entry_matches(
711        &self,
712        e: &Entry<'_>,
713        doc: &Document,
714        el: NodeId,
715        styles: &HashMap<NodeId, Computed>,
716        scope_cache: &mut ScopeCache,
717        inclusive: bool,
718    ) -> Option<u32> {
719        if !e
720            .containers
721            .iter()
722            .all(|c| self.container_holds(c, doc, el, styles, inclusive))
723        {
724            return None;
725        }
726        match &e.scope {
727            None => e.selector.matches(doc, el, None).then_some(0),
728            Some(scope) => {
729                let levels = scope_roots(scope, doc, el, scope_cache);
730                let roots = levels.last().map_or(&[][..], |r| &r[..]);
731                roots
732                    .iter()
733                    .find(|(r, _)| e.selector.matches(doc, el, Some(*r)))
734                    .map(|(_, hops)| u32::MAX - hops)
735            }
736        }
737    }
738}
739
740/// Puts a declaration where the cascade sorts it: shorthands split, custom
741/// properties apart.
742fn add<'x>(
743    declared: &mut HashMap<&'static str, Vec<Declared<'x>>>,
744    custom: &mut HashMap<String, Vec<(Key, Vec<ComponentValue<'x>>)>>,
745    name: &str,
746    value: &'x [ComponentValue<'x>],
747    important: bool,
748    key: Key,
749) {
750    let mut key = key;
751    key.origin = rank(key.origin, important);
752    if important {
753        key.layer = u32::MAX - key.layer;
754    }
755    if name.starts_with("--") {
756        custom
757            .entry(name.to_string())
758            .or_default()
759            .push((key, trim(value).to_vec()));
760        return;
761    }
762    let Some(p) = property(name) else { return };
763    let p = p.alias_of.and_then(property).unwrap_or(p);
764    // `all`: a CSS-wide keyword for every property but `direction`,
765    // `unicode-bidi` and the custom ones.
766    if p.name == "all" {
767        if let Ok(v @ Specified::CssWide(_)) = crate::values::parse_value("all", value) {
768            for q in crate::values::properties() {
769                if q.is_shorthand()
770                    || q.alias_of.is_some()
771                    || matches!(q.name, "all" | "direction" | "unicode-bidi")
772                {
773                    continue;
774                }
775                declared.entry(q.name).or_default().push(Declared {
776                    value: v.clone(),
777                    from_shorthand: None,
778                    key,
779                });
780            }
781        }
782        return;
783    }
784    if !p.is_shorthand() {
785        if let Ok(v) = crate::values::parse_value(p.name, value) {
786            declared.entry(p.name).or_default().push(Declared {
787                value: v,
788                from_shorthand: None,
789                key,
790            });
791        }
792        return;
793    }
794    // The shorthand too, so its computed value can be written as it was
795    // given when none of its longhands comes from anything later.
796    if let Ok(v) = crate::values::parse_value(p.name, value) {
797        declared.entry(p.name).or_default().push(Declared {
798            value: v,
799            from_shorthand: None,
800            key,
801        });
802    }
803    let Ok(longhands) = expand(p.name, value) else {
804        return;
805    };
806    let pending = matches!(longhands.first(), Some((_, Specified::Unparsed(_))));
807    for (l, v) in longhands {
808        declared.entry(l).or_default().push(Declared {
809            value: v,
810            from_shorthand: pending.then_some(p.name),
811            key,
812        });
813    }
814}
815
816/// The HTML user agent stylesheet's rules, collected once. Nothing in it
817/// depends on the environment.
818fn ua_entries() -> &'static (Vec<Entry<'static>>, u32) {
819    static SHEET: std::sync::OnceLock<crate::Stylesheet<'static, Block<'static>>> =
820        std::sync::OnceLock::new();
821    static ENTRIES: std::sync::OnceLock<(Vec<Entry<'static>>, u32)> = std::sync::OnceLock::new();
822    ENTRIES.get_or_init(|| {
823        let sheet = SHEET.get_or_init(|| crate::parse_stylesheet_deep(HTML_UA_STYLESHEET));
824        let env = Environment::default();
825        let mut layers = Layers::default();
826        let mut entries = Vec::new();
827        let mut order = 0;
828        let mut at = Collected::default();
829        let mut cx = Collect {
830            env: &env,
831            origin: Origin::UserAgent,
832            layers: &mut layers,
833            entries: &mut entries,
834            order: &mut order,
835            owner: None,
836            scope: None,
837            containers: Vec::new(),
838            at: &mut at,
839            depth: 0,
840        };
841        cx.rules(&sheet.rules, &[], &[]);
842        (entries, order)
843    })
844}
845
846impl Styler {
847    /// Whether one of an `@container`'s queries holds for `el`: its
848    /// nearest container of the name with the axes the query needs, of
849    /// the size [`Styler::container_sizes`] gives.
850    fn container_holds(
851        &self,
852        queries: &[ContainerQuery],
853        doc: &Document,
854        el: NodeId,
855        styles: &HashMap<NodeId, Computed>,
856        inclusive: bool,
857    ) -> bool {
858        queries.iter().any(|q| {
859            let axes = q.axes();
860            let sized = axes.inline || axes.block;
861            let mut at = if inclusive { Some(el) } else { doc.parent(el) };
862            while let Some(a) = at {
863                at = doc.parent(a);
864                let Some(c) = styles.get(&a) else { continue };
865                let ty = c.get("container-type").unwrap_or_default();
866                let size = ty.split_ascii_whitespace().any(|w| w == "size");
867                let inline = size || ty.split_ascii_whitespace().any(|w| w == "inline-size");
868                // Every element is a style container; a size container
869                // needs the type for the axes asked of it, and a box.
870                let boxed = !matches!(c.get("display").as_deref(), Some("none" | "contents"));
871                let eligible = if axes.block {
872                    size && boxed
873                } else if axes.inline {
874                    inline && boxed
875                } else {
876                    true
877                };
878                let named = q.name.as_ref().is_none_or(|n| {
879                    c.get("container-name")
880                        .is_some_and(|names| names.split_ascii_whitespace().any(|x| x == n))
881                });
882                if !eligible || !named {
883                    continue;
884                }
885                let size = match sized {
886                    true => match self.container_size.as_ref().and_then(|f| f(a, c)) {
887                        Some(s) => Some(s),
888                        None => return false,
889                    },
890                    false => None,
891                };
892                let get = |name: &str| c.get(name);
893                let number = |value: &str| c.range_value(value);
894                return q.evaluate(size, &c.query_lengths(), &get, &number) == Some(true);
895            }
896            false
897        })
898    }
899}
900
901/// Each nesting level's scoping roots, outermost first, each root with
902/// how many generations up it is.
903type Levels = Vec<Vec<(NodeId, u32)>>;
904
905/// Each element's scoping roots for each `@scope`, worked out once: an
906/// element's are its parent's, a generation farther, less those it limits,
907/// and itself if it's a root.
908#[derive(Default)]
909struct ScopeCache {
910    /// By the scope's address and the node: the roots at each level of
911    /// nesting, outermost first.
912    roots: HashMap<(usize, NodeId), Arc<Levels>>,
913}
914
915/// The scoping roots `el` is in scope of for `scope`, nearest first, each
916/// with how many generations up it is.
917fn scope_roots(scope: &Scope, doc: &Document, el: NodeId, cache: &mut ScopeCache) -> Arc<Levels> {
918    let key = |n: NodeId| (scope as *const Scope as usize, n);
919    // Up to the nearest element already done, then down from there, so
920    // nothing recurses on the document's depth.
921    let mut chain = vec![el];
922    let mut start = None;
923    let mut at = el;
924    if let Some(r) = cache.roots.get(&key(el)) {
925        return r.clone();
926    }
927    while let Some(p) = doc.parent(at) {
928        if let Some(r) = cache.roots.get(&key(p)) {
929            start = Some(r.clone());
930            break;
931        }
932        chain.push(p);
933        at = p;
934    }
935    let mut levels: Vec<&Scope> = Vec::new();
936    let mut s = Some(scope);
937    while let Some(x) = s {
938        levels.push(x);
939        s = x.outer.as_deref();
940    }
941    levels.reverse();
942    let owner_root = |o: &Option<NodeId>| o.and_then(|o| doc.parent(o)).unwrap_or(doc.root());
943    let mut roots: Levels = match start {
944        Some(r) => (*r).clone(),
945        None => vec![Vec::new(); levels.len()],
946    };
947    for &n in chain.iter().rev() {
948        let element = matches!(doc.kind(n), Kind::Element { .. });
949        for i in 0..levels.len() {
950            let sc = levels[i];
951            for r in &mut roots[i] {
952                r.1 += 1;
953            }
954            // A limit, and what's under it, is out of its root's scope.
955            if let Some(end) = &sc.end
956                && element
957            {
958                roots[i].retain(|(r, _)| !end.matches(doc, n, Some(*r)));
959            }
960            let is_root = match &sc.start {
961                ScopeStart::Owner(o) => n == owner_root(o),
962                ScopeStart::Selector(sel) => {
963                    element
964                        && if i == 0 {
965                            sel.matches(doc, n, None)
966                        } else {
967                            roots[i - 1]
968                                .iter()
969                                .any(|(r, _)| sel.matches(doc, n, Some(*r)))
970                        }
971                }
972            };
973            // A root that's its own limit, `to (:scope)`, scopes nothing.
974            let own_limit = is_root
975                && sc
976                    .end
977                    .as_ref()
978                    .is_some_and(|end| end.matches(doc, n, Some(n)));
979            if is_root && !own_limit {
980                roots[i].insert(0, (n, 0));
981            }
982        }
983        cache.roots.insert(key(n), Arc::new(roots.clone()));
984    }
985    cache.roots[&key(el)].clone()
986}
987
988/// Origin and importance as one rank: normal user agent, user, author,
989/// then important author, user, user agent.
990fn rank(origin: u8, important: bool) -> u8 {
991    if important { 5 - origin } else { origin }
992}
993
994fn trim<'v, 'a>(values: &'v [ComponentValue<'a>]) -> &'v [ComponentValue<'a>] {
995    let start = values
996        .iter()
997        .position(|v| !v.is_whitespace())
998        .unwrap_or(values.len());
999    let end = values
1000        .iter()
1001        .rposition(|v| !v.is_whitespace())
1002        .map_or(start, |i| i + 1);
1003    &values[start..end]
1004}
1005
1006fn elements(doc: &Document) -> impl Iterator<Item = NodeId> + '_ {
1007    // Every node in document order, elements only.
1008    let mut stack = vec![doc.root()];
1009    std::iter::from_fn(move || {
1010        while let Some(n) = stack.pop() {
1011            let children: Vec<NodeId> = doc.children(n).collect();
1012            stack.extend(children.into_iter().rev());
1013            if matches!(doc.kind(n), Kind::Element { .. }) {
1014                return Some(n);
1015            }
1016        }
1017        None
1018    })
1019}
1020
1021fn doc_element(doc: &Document) -> Option<NodeId> {
1022    doc.children(doc.root())
1023        .find(|n| matches!(doc.kind(*n), Kind::Element { .. }))
1024}
1025
1026#[derive(Clone, Debug, PartialEq)]
1027enum Bucket {
1028    Id(String),
1029    Class(String),
1030    Tag(String),
1031    /// `[name…]`: an attribute the element must have.
1032    Attr(String),
1033    Universal,
1034}
1035
1036#[derive(Default)]
1037struct Index {
1038    ids: HashMap<String, Vec<usize>>,
1039    classes: HashMap<String, Vec<usize>>,
1040    tags: HashMap<String, Vec<usize>>,
1041    attrs: HashMap<String, Vec<usize>>,
1042    universal: Vec<usize>,
1043}
1044
1045/// The id, class or type a complex selector's rightmost compound needs,
1046/// read from its text; universal when that can't be told simply.
1047fn bucket(selector: &str) -> Bucket {
1048    if selector.contains('\\') {
1049        return Bucket::Universal;
1050    }
1051    // The rightmost compound: after the last combinator outside brackets.
1052    let b = selector.as_bytes();
1053    let (mut depth, mut start) = (0i32, 0);
1054    for (i, c) in b.iter().enumerate() {
1055        match c {
1056            b'(' | b'[' => depth += 1,
1057            b')' | b']' => depth -= 1,
1058            b' ' | b'>' | b'+' | b'~' if depth == 0 => start = i + 1,
1059            _ => {}
1060        }
1061    }
1062    let compound = &selector[start..];
1063    let name_end = |s: &str| {
1064        s.find(|c: char| !(c.is_ascii_alphanumeric() || c == '-' || c == '_'))
1065            .unwrap_or(s.len())
1066    };
1067    // Only what's outside any brackets counts.
1068    let (mut depth, mut i) = (0i32, 0);
1069    let cb = compound.as_bytes();
1070    let (mut id, mut class, mut attr) = (None, None, None);
1071    while i < cb.len() {
1072        match cb[i] {
1073            b'[' if depth == 0 && attr.is_none() => {
1074                let rest = compound[i + 1..].trim_start();
1075                let n = name_end(rest);
1076                // `[ns|name]` and the like stay universal.
1077                if n > 0 && !rest[n..].starts_with('|') {
1078                    attr = Some(rest[..n].to_ascii_lowercase());
1079                }
1080                depth += 1;
1081            }
1082            b'(' | b'[' => depth += 1,
1083            b')' | b']' => depth -= 1,
1084            b'#' if depth == 0 && id.is_none() => {
1085                let n = name_end(&compound[i + 1..]);
1086                if n > 0 {
1087                    id = Some(compound[i + 1..i + 1 + n].to_string());
1088                }
1089            }
1090            b'.' if depth == 0 && class.is_none() => {
1091                let n = name_end(&compound[i + 1..]);
1092                if n > 0 {
1093                    class = Some(compound[i + 1..i + 1 + n].to_string());
1094                }
1095            }
1096            _ => {}
1097        }
1098        i += 1;
1099    }
1100    if let Some(id) = id {
1101        return Bucket::Id(id);
1102    }
1103    if let Some(class) = class {
1104        return Bucket::Class(class);
1105    }
1106    let n = name_end(compound);
1107    if n > 0 && compound.as_bytes()[0].is_ascii_alphabetic() && !compound[n..].starts_with('|') {
1108        return Bucket::Tag(compound[..n].to_ascii_lowercase());
1109    }
1110    attr.map_or(Bucket::Universal, Bucket::Attr)
1111}
1112
1113/// Cascade layers, in the order they were first named. Each layer's
1114/// rank sorts its sublayers before its own declarations, and unlayered
1115/// declarations last of all (§6.4).
1116#[derive(Default)]
1117struct Layers {
1118    /// Every layer's full name, `a.b`, in the order first seen; index 0
1119    /// is the unlayered declarations.
1120    names: Vec<Vec<String>>,
1121    /// Each name's index in `names`.
1122    index: HashMap<Vec<String>, usize>,
1123}
1124
1125/// How many parts a layer's full name may have, nesting included; a
1126/// deeper `@layer`, or `@import` into one, is ignored. Each part costs
1127/// a lookup of every name above it.
1128const MAX_LAYER_DEPTH: usize = 64;
1129
1130impl Layers {
1131    fn id(&mut self, path: &[String]) -> usize {
1132        // Naming `a.b` names `a` first; the empty name, unlayered, is 0.
1133        for n in 0..=path.len() {
1134            if !self.index.contains_key(&path[..n]) {
1135                self.index.insert(path[..n].to_vec(), self.names.len());
1136                self.names.push(path[..n].to_vec());
1137            }
1138        }
1139        self.index[path]
1140    }
1141
1142    /// Each layer's rank: higher wins for normal declarations.
1143    fn ranks(&mut self) -> Vec<u32> {
1144        self.id(&[]);
1145        // Order of first mention among siblings, depth first, a layer
1146        // after its sublayers; unlayered (the empty path) at the end.
1147        let mut order: Vec<usize> = (0..self.names.len()).collect();
1148        let first = |path: &[String]| -> Vec<usize> {
1149            (1..=path.len()).map(|n| self.index[&path[..n]]).collect()
1150        };
1151        let keys: Vec<Vec<usize>> = self
1152            .names
1153            .iter()
1154            .map(|p| {
1155                let mut k = first(p);
1156                // A layer's own declarations come after its sublayers.
1157                k.push(usize::MAX);
1158                k
1159            })
1160            .collect();
1161        order.sort_by(|a, b| {
1162            let (ka, kb) = (&keys[*a], &keys[*b]);
1163            ka.cmp(kb)
1164        });
1165        let mut ranks = vec![0; self.names.len()];
1166        for (r, i) in order.iter().enumerate() {
1167            ranks[*i] = r as u32;
1168        }
1169        // The unlayered sort last: its key is just [MAX].
1170        ranks
1171    }
1172}
1173
1174struct Collect<'c, 's> {
1175    env: &'c Environment,
1176    origin: Origin,
1177    layers: &'c mut Layers,
1178    entries: &'c mut Vec<Entry<'s>>,
1179    order: &'c mut u32,
1180    owner: Option<NodeId>,
1181    scope: Option<Arc<Scope>>,
1182    containers: Vec<Arc<Vec<ContainerQuery>>>,
1183    at: &'c mut Collected,
1184    /// How many rules deep `rule` is.
1185    depth: usize,
1186}
1187
1188/// How deep rules may nest for the cascade to see them.
1189const MAX_RULE_DEPTH: usize = 128;
1190
1191/// One stylesheet to collect: its text, where it's from, and the layer
1192/// an `@import` put it in; or, with no text, layers to name first.
1193struct Unit {
1194    css: String,
1195    origin: Origin,
1196    owner: Option<NodeId>,
1197    layer: Vec<String>,
1198    declare: Vec<Vec<String>>,
1199    /// The `scope()`s `@import`s put its rules in, outermost first.
1200    scopes: Vec<ScopeBounds>,
1201}
1202
1203impl Unit {
1204    fn layers(declare: Vec<Vec<String>>) -> Unit {
1205        Unit {
1206            css: String::new(),
1207            origin: Origin::Author,
1208            owner: None,
1209            layer: Vec::new(),
1210            declare,
1211            scopes: Vec::new(),
1212        }
1213    }
1214}
1215
1216/// `@layer a.b, c`'s names, each as its parts.
1217fn layer_names(prelude: &[ComponentValue<'_>]) -> Vec<Vec<String>> {
1218    prelude
1219        .split(|v| matches!(v, ComponentValue::Token(Token::Comma, _)))
1220        .map(|n| {
1221            crate::to_css(n)
1222                .trim()
1223                .split('.')
1224                .map(|p| p.trim().to_string())
1225                .filter(|p| !p.is_empty())
1226                .collect()
1227        })
1228        .collect()
1229}
1230
1231/// The named at-rules as collected, each with its layer and order.
1232#[derive(Default)]
1233struct Collected {
1234    keyframes: Vec<(usize, u32, Keyframes)>,
1235    counter_styles: Vec<(usize, u32, CounterStyle)>,
1236    properties: Vec<(usize, u32, PropertyRule)>,
1237}
1238
1239impl Collected {
1240    /// For each name, the rule that's last in the cascade's order.
1241    fn resolved(&self, ranks: &[u32]) -> AtRules {
1242        fn last<T: Clone>(
1243            items: &[(usize, u32, T)],
1244            ranks: &[u32],
1245            name: impl Fn(&T) -> &str,
1246        ) -> Vec<T> {
1247            let mut sorted: Vec<&(usize, u32, T)> = items.iter().collect();
1248            sorted.sort_by_key(|(l, o, _)| (ranks.get(*l).copied().unwrap_or(0), *o));
1249            let mut out: Vec<T> = Vec::new();
1250            for (_, _, t) in sorted {
1251                out.retain(|x| name(x) != name(t));
1252                out.push(t.clone());
1253            }
1254            out
1255        }
1256        AtRules {
1257            keyframes: last(&self.keyframes, ranks, |k| &k.name),
1258            counter_styles: last(&self.counter_styles, ranks, |c| &c.name),
1259            properties: last(&self.properties, ranks, |p| &p.name),
1260        }
1261    }
1262}
1263
1264/// The parent "selector" of the rules straight inside an `@scope`.
1265const IN_SCOPE: &str = "\u{1}scope";
1266
1267/// How deep `@scope`s may nest; deeper ones are ignored, since each level
1268/// multiplies the work of finding roots.
1269const MAX_SCOPE_DEPTH: usize = 8;
1270
1271/// A prelude's complex selectors, each as text.
1272fn complex_selectors(prelude: &[ComponentValue<'_>]) -> Vec<String> {
1273    prelude
1274        .split(|v| matches!(v, ComponentValue::Token(Token::Comma, _)))
1275        .map(|p| crate::to_css(p).trim().to_string())
1276        .collect()
1277}
1278
1279/// How long the selectors of a nested style rule may grow, all told, with
1280/// their parents' written in. Each level of nesting writes in the one
1281/// above, so past this the rule, and what's nested in it, is ignored.
1282const MAX_NESTED_SELECTORS: usize = 64 * 1024;
1283
1284/// A nested selector against its parent's: `&` replaced by `:is(parent)`,
1285/// or the parent put in front, as CSS Nesting reads them.
1286fn nest(selector: &str, parents: &[String]) -> String {
1287    if parents.is_empty() {
1288        return selector.to_string();
1289    }
1290    // In `@scope`, CSS Cascade 6 §3.5.1: `&` is `:where(:scope)`, and a
1291    // selector without `:scope` or `&` is under the root.
1292    if parents == [IN_SCOPE] {
1293        let scope = ":where(:scope)";
1294        if selector.contains('&') {
1295            return selector.replace('&', scope);
1296        }
1297        if selector.contains(":scope") {
1298            return selector.to_string();
1299        }
1300        return format!("{scope} {selector}");
1301    }
1302    if let [parent] = parents {
1303        // One parent, standing alone where `&` is: written in as it is,
1304        // which matches the same and costs the same as `:is()` of it.
1305        // Nested `:is()`s are matched again for every ancestor, so each
1306        // level of them doubles the work.
1307        let alone = |rest: &str| rest.chars().next().is_none_or(|c| " \t\n>+~".contains(c));
1308        if !selector.contains('&') {
1309            return format!("{parent} {selector}");
1310        }
1311        if let Some(rest) = selector.strip_prefix('&')
1312            && !rest.contains('&')
1313            && alone(rest)
1314        {
1315            return format!("{parent}{rest}");
1316        }
1317    }
1318    let parent = format!(":is({})", parents.join(", "));
1319    if selector.contains('&') {
1320        return selector.replace('&', &parent);
1321    }
1322    format!("{parent} {selector}")
1323}
1324
1325impl<'s> Collect<'_, 's> {
1326    /// Makes `bounds` the scope rules are collected in, inside the one
1327    /// they're in now; `false` if its selectors don't parse or scopes
1328    /// nest too deep.
1329    fn enter_scope(&mut self, bounds: &ScopeBounds, parents: &[String]) -> bool {
1330        let mut depth = 0;
1331        let mut s = self.scope.as_deref();
1332        while let Some(x) = s {
1333            depth += 1;
1334            s = x.outer.as_deref();
1335        }
1336        if depth >= MAX_SCOPE_DEPTH {
1337            return false;
1338        }
1339        // Real parents: a style rule's selectors.
1340        let parents: Vec<String> = parents.iter().filter(|p| *p != IN_SCOPE).cloned().collect();
1341        let start = match &bounds.start {
1342            Some(sel) => match SelectorList::parse(&nest(sel, &parents)) {
1343                Ok(l) => ScopeStart::Selector(l),
1344                Err(_) => return false,
1345            },
1346            None if !parents.is_empty() => match SelectorList::parse(&parents.join(", ")) {
1347                Ok(l) => ScopeStart::Selector(l),
1348                Err(_) => return false,
1349            },
1350            None => ScopeStart::Owner(self.owner),
1351        };
1352        let end = match &bounds.end {
1353            Some(sel) => match SelectorList::parse(sel) {
1354                Ok(l) => Some(l),
1355                Err(_) => return false,
1356            },
1357            None => None,
1358        };
1359        self.scope = Some(Arc::new(Scope {
1360            start,
1361            end,
1362            outer: self.scope.take(),
1363        }));
1364        true
1365    }
1366
1367    fn rules(&mut self, rules: &'s [Rule<'s, Block<'s>>], parents: &[String], layer: &[String]) {
1368        for r in rules {
1369            self.rule(r, parents, layer);
1370        }
1371    }
1372
1373    fn items(&mut self, items: &'s [Item<'s, Block<'s>>], parents: &[String], layer: &[String]) {
1374        // Declarations straight in a nested group rule belong to the
1375        // parent's selector.
1376        let declarations: Vec<_> = items
1377            .iter()
1378            .filter_map(|i| match i {
1379                Item::Declaration(d) => Some((&*d.name, &d.value[..], d.important)),
1380                _ => None,
1381            })
1382            .collect();
1383        if !declarations.is_empty() && !parents.is_empty() {
1384            self.push(parents, declarations, layer);
1385        }
1386        for i in items {
1387            if let Item::Rule(r) = i {
1388                self.rule(r, parents, layer);
1389            }
1390        }
1391    }
1392
1393    fn push(
1394        &mut self,
1395        selectors: &[String],
1396        declarations: Vec<(&'s str, &'s [ComponentValue<'s>], bool)>,
1397        layer: &[String],
1398    ) {
1399        let layer = self.layers.id(layer);
1400        for s in selectors {
1401            let s = if s == IN_SCOPE {
1402                ":where(:scope)"
1403            } else {
1404                s.as_str()
1405            };
1406            let Ok(list) = SelectorList::parse(s) else {
1407                continue;
1408            };
1409            // A pseudo-element's rule matches its originating element, and
1410            // counts the pseudo-element in its specificity.
1411            let specificity = list.specificity();
1412            let mut origin_any = false;
1413            let (bucket, list, pseudo) = match split_pseudo(s) {
1414                Split::No => (bucket(s), list, None),
1415                // Only after a state, or as part of another pseudo-element.
1416                Split::Unstyled => continue,
1417                Split::Pseudo(origin, p) => match SelectorList::parse(&origin) {
1418                    Ok(l) => {
1419                        origin_any = origin == "*";
1420                        (bucket(&origin), l, Some(p))
1421                    }
1422                    Err(_) => continue,
1423                },
1424            };
1425            *self.order += 1;
1426            self.entries.push(Entry {
1427                bucket,
1428                specificity,
1429                selector: list,
1430                origin: self.origin,
1431                layer,
1432                order: *self.order,
1433                declarations: declarations.clone(),
1434                scope: self.scope.clone(),
1435                containers: self.containers.clone(),
1436                any: origin_any,
1437                pseudo,
1438            });
1439        }
1440    }
1441
1442    fn rule(&mut self, r: &'s Rule<'s, Block<'s>>, parents: &[String], layer: &[String]) {
1443        // This recurses on the rules' nesting, which the parser keeps
1444        // within MAX_NESTING; a frame here is bigger than a value's, so
1445        // rules deeper than this are ignored.
1446        if self.depth >= MAX_RULE_DEPTH {
1447            return;
1448        }
1449        self.depth += 1;
1450        self.rule_in(r, parents, layer);
1451        self.depth -= 1;
1452    }
1453
1454    fn rule_in(&mut self, r: &'s Rule<'s, Block<'s>>, parents: &[String], layer: &[String]) {
1455        match r {
1456            Rule::Qualified(q) => {
1457                let selectors = complex_selectors(&q.prelude);
1458                if !parents.is_empty() {
1459                    // Their size before writing them: each `&` is a copy
1460                    // of the parents, or one copy in front without one.
1461                    let parent: usize = parents.iter().map(|p| p.len() + 2).sum::<usize>() + 4;
1462                    let size = selectors.iter().fold(0usize, |n, s| {
1463                        let copies = s.matches('&').count().max(1);
1464                        n.saturating_add(s.len() + copies.saturating_mul(parent))
1465                    });
1466                    if size > MAX_NESTED_SELECTORS {
1467                        return;
1468                    }
1469                }
1470                let selectors: Vec<String> = selectors.iter().map(|s| nest(s, parents)).collect();
1471                // A selector list with one bad selector is no rule at all.
1472                if selectors.iter().any(|s| SelectorList::parse(s).is_err()) {
1473                    return;
1474                }
1475                let declarations = q
1476                    .block
1477                    .items
1478                    .iter()
1479                    .filter_map(|i| match i {
1480                        Item::Declaration(d) => Some((&*d.name, &d.value[..], d.important)),
1481                        _ => None,
1482                    })
1483                    .collect();
1484                self.push(&selectors, declarations, layer);
1485                for i in &q.block.items {
1486                    if let Item::Rule(r) = i {
1487                        self.rule(r, &selectors, layer);
1488                    }
1489                }
1490            }
1491            Rule::At(a) => {
1492                let name = a.name.to_ascii_lowercase();
1493                match name.as_str() {
1494                    "media" => {
1495                        if MediaQueryList::parse(&a.prelude).matches(self.env)
1496                            && let Some(b) = &a.block
1497                        {
1498                            self.items(&b.items, parents, layer);
1499                        }
1500                    }
1501                    "supports" => {
1502                        if crate::supports::supports(&a.prelude) == Some(true)
1503                            && let Some(b) = &a.block
1504                        {
1505                            self.items(&b.items, parents, layer);
1506                        }
1507                    }
1508                    "container" => {
1509                        if let (Some(queries), Some(b)) =
1510                            (ContainerQuery::parse_list(&a.prelude), &a.block)
1511                        {
1512                            self.containers.push(Arc::new(queries));
1513                            self.items(&b.items, parents, layer);
1514                            self.containers.pop();
1515                        }
1516                    }
1517                    "scope" => {
1518                        let (Some(bounds), Some(b)) = (ScopeBounds::parse(&a.prelude), &a.block)
1519                        else {
1520                            return;
1521                        };
1522                        let outer = self.scope.clone();
1523                        if self.enter_scope(&bounds, parents) {
1524                            self.items(&b.items, &[IN_SCOPE.to_string()], layer);
1525                        }
1526                        self.scope = outer;
1527                    }
1528                    "keyframes" | "-webkit-keyframes" | "counter-style" | "property" => {
1529                        let l = self.layers.id(layer);
1530                        *self.order += 1;
1531                        let o = *self.order;
1532                        if let Some(k) = Keyframes::parse(a) {
1533                            self.at.keyframes.push((l, o, k));
1534                        } else if let Some(c) = CounterStyle::parse(a) {
1535                            self.at.counter_styles.push((l, o, c));
1536                        } else if let Some(p) = PropertyRule::parse(a) {
1537                            self.at.properties.push((l, o, p));
1538                        }
1539                    }
1540                    "layer" => {
1541                        let names = layer_names(&a.prelude);
1542                        match &a.block {
1543                            // `@layer a, b;` names them, in that order.
1544                            None => {
1545                                for n in &names {
1546                                    let mut path = layer.to_vec();
1547                                    path.extend(n.iter().cloned());
1548                                    if path.len() <= MAX_LAYER_DEPTH {
1549                                        self.layers.id(&path);
1550                                    }
1551                                }
1552                            }
1553                            Some(b) => {
1554                                let mut path = layer.to_vec();
1555                                match names.first() {
1556                                    Some(n) if !n.is_empty() && names.len() == 1 => {
1557                                        path.extend(n.iter().cloned())
1558                                    }
1559                                    Some(n) if !n.is_empty() => return,
1560                                    // An anonymous layer, its own each time.
1561                                    _ => path.push(format!("\u{0}{}", *self.order)),
1562                                }
1563                                if path.len() > MAX_LAYER_DEPTH {
1564                                    return;
1565                                }
1566                                *self.order += 1;
1567                                self.layers.id(&path);
1568                                self.items(&b.items, parents, &path);
1569                            }
1570                        }
1571                    }
1572                    _ => {}
1573                }
1574            }
1575        }
1576    }
1577}
1578
1579/// The CSS-wide keyword a value is, if it is one.
1580pub(crate) fn css_wide(v: &Specified<'_>) -> Option<CssWide> {
1581    match v {
1582        Specified::CssWide(k) => Some(*k),
1583        _ => None,
1584    }
1585}
1586
1587#[cfg(test)]
1588mod tests {
1589    use super::*;
1590
1591    fn style(html: &str, sel: &str, property: &str) -> String {
1592        let doc = parsec::parse(html, false);
1593        let styled = Styler::new(Environment::default())
1594            .with_document_styles(&doc)
1595            .style(&doc);
1596        let el = SelectorList::parse(sel)
1597            .unwrap()
1598            .select_first(&doc, doc.root())
1599            .unwrap();
1600        styled.get(el, property).unwrap_or_default()
1601    }
1602
1603    #[test]
1604    fn origins_importance_and_style_attributes() {
1605        let html = "<style>p { color: red !important } #a { color: blue }</style><p id=a style='color: green'>";
1606        assert_eq!(style(html, "p", "color"), "rgb(255, 0, 0)");
1607        let html = "<style>#a { color: blue }</style><p id=a style='color: green'>";
1608        assert_eq!(style(html, "p", "color"), "rgb(0, 128, 0)");
1609        let html = "<style>p { color: red !important }</style><p style='color: green !important'>";
1610        assert_eq!(style(html, "p", "color"), "rgb(0, 128, 0)");
1611        // The user agent's `display: block` loses to the author's.
1612        assert_eq!(
1613            style(
1614                "<style>div { display: inline }</style><div>",
1615                "div",
1616                "display"
1617            ),
1618            "inline"
1619        );
1620    }
1621
1622    #[test]
1623    fn layers_order_and_importance() {
1624        let css = "@layer a, b; @layer b { p { color: green } } @layer a { p { color: red } }";
1625        assert_eq!(
1626            style(&format!("<style>{css}</style><p>"), "p", "color"),
1627            "rgb(0, 128, 0)"
1628        );
1629        // Unlayered beats layered, unless important, where it's the other way.
1630        let css = "p { color: green } @layer x { p { color: red } }";
1631        assert_eq!(
1632            style(&format!("<style>{css}</style><p>"), "p", "color"),
1633            "rgb(0, 128, 0)"
1634        );
1635        let css = "p { color: red !important } @layer x { p { color: green !important } }";
1636        assert_eq!(
1637            style(&format!("<style>{css}</style><p>"), "p", "color"),
1638            "rgb(0, 128, 0)"
1639        );
1640        // A layer's sublayers come before its own rules.
1641        let css = "@layer a { p { color: green } @layer b { p { color: red } } }";
1642        assert_eq!(
1643            style(&format!("<style>{css}</style><p>"), "p", "color"),
1644            "rgb(0, 128, 0)"
1645        );
1646    }
1647
1648    #[test]
1649    fn revert_and_revert_layer() {
1650        let html = "<style>div { display: inline } div { display: revert }</style><div>";
1651        assert_eq!(style(html, "div", "display"), "block");
1652        let css = "@layer a { p { color: green } } @layer b { p { color: revert-layer } }";
1653        assert_eq!(
1654            style(&format!("<style>{css}</style><p>"), "p", "color"),
1655            "rgb(0, 128, 0)"
1656        );
1657        let html =
1658            "<style>.r { all: revert }</style><style>div { display: inline }</style><div class=r>";
1659        assert_eq!(style(html, "div", "display"), "block");
1660    }
1661
1662    #[test]
1663    fn inheritance_and_keywords() {
1664        let html = "<div style='color: blue; margin-top: 3px; font-size: 20px'><p style='width: inherit'></div>";
1665        assert_eq!(style(html, "p", "color"), "rgb(0, 0, 255)");
1666        assert_eq!(style(html, "p", "margin-top"), "0px");
1667        let html = "<div style='font-size: 20px'><p style='font-size: 1.5em; line-height: 2em; margin-left: calc(1em + 2px)'></div>";
1668        assert_eq!(style(html, "p", "font-size"), "30px");
1669        assert_eq!(style(html, "p", "line-height"), "60px");
1670        assert_eq!(style(html, "p", "margin-left"), "32px");
1671        let html = "<div style='color: red'><p style='color: unset; border-top: 2px solid; border-bottom-width: 9px'></div>";
1672        assert_eq!(style(html, "p", "color"), "rgb(255, 0, 0)");
1673        assert_eq!(style(html, "p", "border-top-color"), "rgb(255, 0, 0)");
1674        assert_eq!(style(html, "p", "border-top-width"), "2px");
1675        // No style, no width.
1676        assert_eq!(style(html, "p", "border-bottom-width"), "0px");
1677        assert_eq!(style("<b><i>x", "b", "font-weight"), "700");
1678    }
1679
1680    #[test]
1681    fn custom_properties_and_var() {
1682        let html = "<style>:root { --gap: 4px; --c: var(--d) } p { margin: calc(var(--gap) * 2) var(--nope, 1px); color: var(--c, green) }</style><p>";
1683        assert_eq!(style(html, "p", "margin-top"), "8px");
1684        assert_eq!(style(html, "p", "margin-right"), "1px");
1685        // --c refers to nothing, so it's guaranteed-invalid, and the
1686        // var() that refers to it takes its fallback.
1687        assert_eq!(style(html, "p", "color"), "rgb(0, 128, 0)");
1688        let html = "<style>p { color: red; color: var(--missing) }</style><div style='color: blue'><p></div>";
1689        // Invalid at computed-value time is `unset`: inherited here.
1690        assert_eq!(style(html, "p", "color"), "rgb(0, 0, 255)");
1691        assert_eq!(style(html, "p", "--missing"), "");
1692    }
1693
1694    #[test]
1695    fn media_supports_and_nesting() {
1696        let css = "@media (min-width: 2000px) { p { color: red } } @supports (display: grid) { p { margin-top: 1px } } \
1697                   @supports (display: nonsense) { p { margin-top: 9px } } div { & > p { color: green } }";
1698        let html = format!("<style>{css}</style><div><p></div>");
1699        assert_eq!(style(&html, "p", "color"), "rgb(0, 128, 0)");
1700        assert_eq!(style(&html, "p", "margin-top"), "1px");
1701        let html = "<style media='print'>p { color: red }</style><p>";
1702        assert_eq!(style(html, "p", "color"), "rgb(0, 0, 0)");
1703    }
1704
1705    #[test]
1706    fn scope_and_proximity() {
1707        let html = "<style>@scope (.a) { p { color: green } } @scope (.b) to (.c) { p { color: blue } }</style>\
1708                    <div class=a><p id=one></p><div class=b><p id=two></p><div class=c><p id=three></p></div></div></div><p id=four>";
1709        assert_eq!(style(html, "#one", "color"), "rgb(0, 128, 0)");
1710        // .b is nearer than .a, so its rule wins though it's not later.
1711        let html2 = html
1712            .replace("@scope (.b) to (.c) { p { color: blue } }", "")
1713            .replace(
1714                "<style>",
1715                "<style>@scope (.b) to (.c) { p { color: blue } }",
1716            );
1717        assert_eq!(style(&html2, "#two", "color"), "rgb(0, 0, 255)");
1718        // Past the limit only .a's applies.
1719        assert_eq!(style(html, "#three", "color"), "rgb(0, 128, 0)");
1720        assert_eq!(style(html, "#four", "color"), "rgb(0, 0, 0)");
1721        // `:scope` itself, and declarations straight in the rule.
1722        let html = "<style>@scope (.a) { :scope { color: green } } @scope (.b) { color: blue }</style><div class=a></div><div class=b>";
1723        assert_eq!(style(html, ".a", "color"), "rgb(0, 128, 0)");
1724        assert_eq!(style(html, ".b", "color"), "rgb(0, 0, 255)");
1725        // With no root: the <style>'s parent.
1726        let html = "<div id=x><style>@scope { p { color: green } }</style><p></p></div><p id=y>";
1727        assert_eq!(style(html, "#x p", "color"), "rgb(0, 128, 0)");
1728        assert_eq!(style(html, "#y", "color"), "rgb(0, 0, 0)");
1729    }
1730
1731    #[test]
1732    fn container_units_and_style_ranges() {
1733        // `cqw` from the inline-size container, `cqh` from the size one
1734        // beyond it, and the small viewport's with no container.
1735        let doc = parsec::parse(
1736            "<style>.s { container-type: size } .i { container-type: inline-size } \
1737             p { width: 10cqw; height: 10cqh; margin-left: 10cqi; margin-top: 10cqmax }</style>\
1738             <div class=s id=s><div class=i id=i><p></p></div></div><p id=bare>",
1739            false,
1740        );
1741        let find = |s: &str| {
1742            SelectorList::parse(s)
1743                .unwrap()
1744                .select_first(&doc, doc.root())
1745                .unwrap()
1746        };
1747        let styled = Styler::new(Environment::default())
1748            .with_document_styles(&doc)
1749            .container_sizes(|_, c| {
1750                Some(match c.get("container-type").as_deref() {
1751                    Some("size") => (1000.0, 500.0),
1752                    _ => (200.0, 50.0),
1753                })
1754            })
1755            .style(&doc);
1756        let p = find("#i p");
1757        assert_eq!(styled.get(p, "width").as_deref(), Some("20px"));
1758        assert_eq!(styled.get(p, "height").as_deref(), Some("50px"));
1759        assert_eq!(styled.get(p, "margin-left").as_deref(), Some("20px"));
1760        assert_eq!(styled.get(p, "margin-top").as_deref(), Some("50px"));
1761        let bare = find("#bare");
1762        assert_eq!(styled.get(bare, "width").as_deref(), Some("128px"));
1763        assert_eq!(styled.get(bare, "height").as_deref(), Some("72px"));
1764
1765        // A range in `style()`, with a custom property's value and `em`
1766        // on the container.
1767        let doc = parsec::parse(
1768            "<style>.c { --n: 30px; font-size: 10px } @container style(2em < --n <= 3em) { p { color: green } } \
1769             @container style(--n > 5) { p { background-color: red } }</style><div class=c><p>",
1770            false,
1771        );
1772        let p = SelectorList::parse("p")
1773            .unwrap()
1774            .select_first(&doc, doc.root())
1775            .unwrap();
1776        let styled = Styler::new(Environment::default())
1777            .with_document_styles(&doc)
1778            .style(&doc);
1779        assert_eq!(styled.get(p, "color").as_deref(), Some("rgb(0, 128, 0)"));
1780        // A length against a number is false, not unknown.
1781        assert_eq!(
1782            styled.get(p, "background-color").as_deref(),
1783            Some("rgba(0, 0, 0, 0)")
1784        );
1785    }
1786
1787    #[test]
1788    fn containers_imports_and_registrations() {
1789        let doc = parsec::parse(
1790            "<style>.c { container: card / inline-size } @container card (width > 400px) { p { color: green } }</style><div class=c><p>",
1791            false,
1792        );
1793        let p = SelectorList::parse("p")
1794            .unwrap()
1795            .select_first(&doc, doc.root())
1796            .unwrap();
1797        let wide = Styler::new(Environment::default())
1798            .with_document_styles(&doc)
1799            .container_sizes(|_, _| Some((500.0, 100.0)))
1800            .style(&doc);
1801        assert_eq!(wide.get(p, "color").as_deref(), Some("rgb(0, 128, 0)"));
1802        let narrow = Styler::new(Environment::default())
1803            .with_document_styles(&doc)
1804            .container_sizes(|_, _| Some((300.0, 100.0)))
1805            .style(&doc);
1806        assert_eq!(narrow.get(p, "color").as_deref(), Some("rgb(0, 0, 0)"));
1807
1808        let doc = parsec::parse(
1809            "<style>@import 'a.css' layer(x); p { color: red } @layer x { p { color: blue } }</style><p>",
1810            false,
1811        );
1812        let p = SelectorList::parse("p")
1813            .unwrap()
1814            .select_first(&doc, doc.root())
1815            .unwrap();
1816        let styled = Styler::new(Environment::default())
1817            .with_document_styles(&doc)
1818            .fetch(|url| {
1819                (url == "a.css").then(|| "p { margin-top: 3px; color: green }".to_string())
1820            })
1821            .style(&doc);
1822        assert_eq!(styled.get(p, "margin-top").as_deref(), Some("3px"));
1823        // Unlayered beats layer x, imports included.
1824        assert_eq!(styled.get(p, "color").as_deref(), Some("rgb(255, 0, 0)"));
1825
1826        let html = "<style>@property --w { syntax: '<length>'; inherits: false; initial-value: 2px } \
1827                    div { --w: 2em; font-size: 10px } p { --w: oops }</style><div><p></p></div>";
1828        assert_eq!(style(html, "div", "--w"), "20px");
1829        // Not inherited, and an invalid value is the initial one.
1830        assert_eq!(style(html, "p", "--w"), "2px");
1831    }
1832
1833    #[test]
1834    fn at_rules() {
1835        let mut s = Styler::bare(Environment::default());
1836        s.add(
1837            "@keyframes a { to { opacity: 0 } } @layer l { @keyframes a { to { opacity: 1 } } } \
1838             @counter-style c { system: cyclic; symbols: x } @media (min-width: 9999px) { @keyframes b {} }",
1839            Origin::Author,
1840        );
1841        let r = s.at_rules();
1842        assert_eq!(r.keyframes.len(), 1);
1843        assert_eq!(r.keyframes[0].frames[0].declarations[0].1, "0");
1844        assert_eq!(r.counter_styles[0].name, "c");
1845    }
1846
1847    #[test]
1848    fn buckets() {
1849        assert_eq!(bucket("div > p.x"), Bucket::Class("x".into()));
1850        assert_eq!(bucket("#a:hover"), Bucket::Id("a".into()));
1851        assert_eq!(bucket("a[href]"), Bucket::Tag("a".into()));
1852        assert_eq!(bucket("[data-x]"), Bucket::Attr("data-x".into()));
1853        assert_eq!(bucket(":is(.a, .b)"), Bucket::Universal);
1854        assert_eq!(bucket("svg|a"), Bucket::Universal);
1855    }
1856}