Skip to main content

parsec_css/cascade/
pseudo.rs

1// SPDX-License-Identifier: Apache-2.0
2// Copyright 2026 James Conway
3
4//! Pseudo-elements, CSS Pseudo-Elements 4: which rules style them, and
5//! their computed values, from their originating element.
6//!
7//! A rule whose selector ends in a pseudo-element is matched, minus that
8//! pseudo-element, against the originating element while the document is
9//! styled, and remembered with its place in the cascade. Its computed
10//! values are only worked out when they're asked for, so a page whose
11//! pseudo-elements nobody reads costs no more than matching their rules.
12
13use std::collections::HashMap;
14use std::fmt;
15
16use parsec::NodeId;
17
18use super::{Computed, Declared, Key, add, compute};
19use crate::media::Environment;
20use crate::parser::ComponentValue;
21use crate::rules::{PropertyRule, Syntax};
22use crate::tokenizer::{Token, Tokenizer};
23
24/// A pseudo-element the cascade styles.
25#[derive(Clone, Debug, PartialEq, Eq, Hash)]
26pub enum Pseudo {
27    Before,
28    After,
29    Marker,
30    Placeholder,
31    FirstLine,
32    FirstLetter,
33    Selection,
34    Backdrop,
35    FileSelectorButton,
36    /// `::highlight(name)`, a custom highlight.
37    Highlight(String),
38}
39
40impl Pseudo {
41    /// `::before`, or the one-colon `:before` CSS 2 allowed for its four,
42    /// as `getComputedStyle()` takes them; ASCII case-insensitive.
43    pub fn parse(text: &str) -> Option<Pseudo> {
44        let text = text.trim();
45        let (name, legacy) = match text.strip_prefix("::") {
46            Some(n) => (n, false),
47            None => (text.strip_prefix(':')?, true),
48        };
49        let p = Pseudo::named(name)?;
50        let legacy_ok = matches!(
51            p,
52            Pseudo::Before | Pseudo::After | Pseudo::FirstLine | Pseudo::FirstLetter
53        );
54        (!legacy || legacy_ok).then_some(p)
55    }
56
57    fn named(name: &str) -> Option<Pseudo> {
58        let lower = name.to_ascii_lowercase();
59        if let Some(arg) = lower
60            .strip_prefix("highlight(")
61            .and_then(|a| a.strip_suffix(')'))
62        {
63            // The name keeps its case: it's a custom identifier.
64            let start = name.len() - arg.len() - 1;
65            let arg = name[start..name.len() - 1].trim();
66            return (!arg.is_empty()).then(|| Pseudo::Highlight(arg.to_string()));
67        }
68        Some(match lower.as_str() {
69            "before" => Pseudo::Before,
70            "after" => Pseudo::After,
71            "marker" => Pseudo::Marker,
72            "placeholder" => Pseudo::Placeholder,
73            "first-line" => Pseudo::FirstLine,
74            "first-letter" => Pseudo::FirstLetter,
75            "selection" => Pseudo::Selection,
76            "backdrop" => Pseudo::Backdrop,
77            "file-selector-button" => Pseudo::FileSelectorButton,
78            _ => return None,
79        })
80    }
81
82    /// A highlight pseudo-element, which inherits from its parent
83    /// element's, CSS Pseudo 4 §3.5.
84    fn is_highlight(&self) -> bool {
85        matches!(self, Pseudo::Selection | Pseudo::Highlight(_))
86    }
87}
88
89impl fmt::Display for Pseudo {
90    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
91        let name = match self {
92            Pseudo::Before => "before",
93            Pseudo::After => "after",
94            Pseudo::Marker => "marker",
95            Pseudo::Placeholder => "placeholder",
96            Pseudo::FirstLine => "first-line",
97            Pseudo::FirstLetter => "first-letter",
98            Pseudo::Selection => "selection",
99            Pseudo::Backdrop => "backdrop",
100            Pseudo::FileSelectorButton => "file-selector-button",
101            Pseudo::Highlight(n) => return write!(f, "::highlight({n})"),
102        };
103        write!(f, "::{name}")
104    }
105}
106
107/// What a complex selector's pseudo-element is.
108#[derive(Debug, PartialEq)]
109pub(super) enum Split {
110    /// It has none: it styles elements.
111    No,
112    /// It styles this pseudo-element of what the text before it matches.
113    Pseudo(String, Pseudo),
114    /// A pseudo-element this doesn't style, or one followed by more (a
115    /// state like `:hover`, or `::marker` on `::before`), which nothing
116    /// in a static document matches.
117    Unstyled,
118}
119
120/// Splits a complex selector at its pseudo-element: the first one outside
121/// any brackets, read with the CSS tokenizer so strings and escapes can't
122/// fool it. The originating part is `*` when nothing comes before.
123pub(super) fn split_pseudo(selector: &str) -> Split {
124    if !selector.contains(':') {
125        return Split::No;
126    }
127    let tokens: Vec<(Token<'_>, crate::Span)> = Tokenizer::new(selector).collect();
128    let mut depth = 0usize;
129    let mut i = 0;
130    while i < tokens.len() {
131        match &tokens[i].0 {
132            Token::Function(_) | Token::LeftParen | Token::LeftBracket => depth += 1,
133            Token::RightParen | Token::RightBracket => depth = depth.saturating_sub(1),
134            Token::Colon if depth == 0 => {
135                let double = matches!(tokens.get(i + 1), Some((Token::Colon, _)));
136                let at = if double { i + 2 } else { i + 1 };
137                let (name, end) = match tokens.get(at) {
138                    Some((Token::Ident(n), s)) => (n.to_string(), s.end),
139                    // `::highlight(name)`: up to its `)`.
140                    Some((Token::Function(n), _)) if double => {
141                        let close = tokens[at..]
142                            .iter()
143                            .position(|(t, _)| *t == Token::RightParen)
144                            .map(|k| at + k);
145                        let Some(close) = close else {
146                            return Split::Unstyled;
147                        };
148                        let inner = &selector[tokens[at].1.end..tokens[close].1.start];
149                        (format!("{n}({inner})"), tokens[close].1.end)
150                    }
151                    _ => {
152                        i += 1;
153                        continue;
154                    }
155                };
156                let legacy = ["before", "after", "first-line", "first-letter"]
157                    .iter()
158                    .any(|l| name.eq_ignore_ascii_case(l));
159                if !double && !legacy {
160                    // A pseudo-class.
161                    i = at + 1;
162                    continue;
163                }
164                if !selector[end..].trim().is_empty() {
165                    return Split::Unstyled;
166                }
167                let Some(p) = Pseudo::named(&name) else {
168                    return Split::Unstyled;
169                };
170                let before = &selector[..tokens[i].1.start];
171                let origin = before.trim_end();
172                // With nothing in its compound but itself, `a > ::before`,
173                // it's on `*`.
174                let bare = origin.is_empty()
175                    || before.ends_with(char::is_whitespace)
176                    || origin.ends_with(['>', '+', '~']);
177                return match bare {
178                    true => Split::Pseudo(format!("{before}*").trim_start().to_string(), p),
179                    false => Split::Pseudo(origin.to_string(), p),
180                };
181            }
182            _ => {}
183        }
184        i += 1;
185    }
186    Split::No
187}
188
189/// One rule for pseudo-elements, its declarations kept as text, so the
190/// styles can be worked out after the stylesheets have gone.
191pub(super) struct PseudoRule {
192    pub pseudo: Pseudo,
193    /// Name, value and importance.
194    pub declarations: Vec<(String, String, bool)>,
195    /// Whether a `content` has `attr()` in it, which needs the
196    /// originating element's attributes.
197    pub needs_attrs: bool,
198}
199
200impl PseudoRule {
201    /// A rule's declarations copied out of its stylesheet.
202    pub fn of(e: &super::Entry<'_>) -> PseudoRule {
203        PseudoRule {
204            pseudo: e.pseudo.clone().unwrap_or(Pseudo::Before),
205            declarations: e
206                .declarations
207                .iter()
208                .map(|(n, v, imp)| (n.to_string(), crate::to_css(v), *imp))
209                .collect(),
210            needs_attrs: e
211                .declarations
212                .iter()
213                .any(|(n, v, _)| n.eq_ignore_ascii_case("content") && has_attr(v)),
214        }
215    }
216}
217
218/// Everything working out a pseudo-element's style needs, kept with the
219/// document's styles.
220#[derive(Default)]
221pub(super) struct PseudoStyles {
222    pub rules: Vec<PseudoRule>,
223    /// Rules that match every element: the originating part is `*`.
224    pub always: Vec<(usize, Key)>,
225    /// The other rules each element matched, by element.
226    pub matched: HashMap<NodeId, Vec<(usize, Key)>>,
227    /// Elements' attributes, for `attr()` in `content`.
228    pub attrs: HashMap<NodeId, Vec<(String, String)>>,
229    pub env: Environment,
230    pub registered: HashMap<String, (PropertyRule, Syntax)>,
231    pub root: Option<NodeId>,
232}
233
234/// Whether `value` has an `attr()` in it, at any depth.
235pub(super) fn has_attr(values: &[ComponentValue<'_>]) -> bool {
236    values.iter().any(|v| match v {
237        ComponentValue::Function(f) => {
238            f.name.eq_ignore_ascii_case("attr") || has_attr(&f.arguments)
239        }
240        ComponentValue::Block(b) => has_attr(&b.contents),
241        _ => false,
242    })
243}
244
245/// `content`'s `attr()`s replaced by the attribute's value as a string,
246/// as CSS Values 5 substitutes them at computed-value time; a missing
247/// attribute is its fallback, or the empty string. A typed `attr()`
248/// stays as written.
249fn substitute_attrs(value: &str, attrs: &[(String, String)]) -> String {
250    let values = crate::parse_component_values(value);
251    let mut out = String::new();
252    for v in &values {
253        if let ComponentValue::Function(f) = v
254            && f.name.eq_ignore_ascii_case("attr")
255        {
256            let args = crate::to_css(&f.arguments);
257            let (name, fallback) = match args.split_once(',') {
258                Some((n, fb)) => (n.trim(), Some(fb.trim())),
259                None => (args.trim(), None),
260            };
261            let name = name.strip_suffix("raw-string").map_or(name, str::trim_end);
262            if !name.contains(|c: char| c.is_whitespace() || c == '|') && !name.is_empty() {
263                match attrs.iter().find(|(n, _)| n.eq_ignore_ascii_case(name)) {
264                    Some((_, v)) => crate::write_string(&mut out, v).unwrap(),
265                    None => match fallback {
266                        Some(fb) if !fb.is_empty() => out.push_str(fb),
267                        _ => out.push_str("\"\""),
268                    },
269                }
270                continue;
271            }
272        }
273        out.push_str(&crate::to_css(std::slice::from_ref(v)));
274    }
275    out
276}
277
278/// Whether a property applies to a pseudo-element, so its declarations
279/// there count. What doesn't apply takes its value as if undeclared.
280fn applies(p: &Pseudo, name: &str) -> bool {
281    let font = name.starts_with("font");
282    let background = name.starts_with("background");
283    let decoration = name.starts_with("text-decoration")
284        || name.starts_with("text-underline")
285        || name.starts_with("text-emphasis")
286        || name == "text-shadow";
287    // Typesetting that applies to inline boxes and doesn't change where
288    // lines break, which would change what the first line is.
289    let typesetting = matches!(
290        name,
291        "letter-spacing" | "word-spacing" | "text-transform" | "text-justify"
292    );
293    let inline_layout = matches!(
294        name,
295        "line-height"
296            | "vertical-align"
297            | "baseline-shift"
298            | "baseline-source"
299            | "alignment-baseline"
300            | "dominant-baseline"
301    );
302    // What browsers apply as well, which CSS Pseudo 4 allows.
303    let animation = name.starts_with("animation");
304    let first_line = font
305        || background
306        || decoration
307        || typesetting
308        || animation
309        || matches!(name, "color" | "opacity" | "ruby-position");
310    match p {
311        Pseudo::Before | Pseudo::After | Pseudo::Backdrop | Pseudo::FileSelectorButton => true,
312        Pseudo::FirstLine => first_line || inline_layout,
313        Pseudo::Placeholder => first_line,
314        Pseudo::FirstLetter => {
315            first_line
316                || inline_layout
317                || name.starts_with("margin")
318                || name.starts_with("padding")
319                || (name.starts_with("border") && !name.starts_with("border-collapse"))
320                || matches!(name, "box-shadow" | "float")
321        }
322        // CSS Lists 3 §3.1.1, and the text properties a marker's text
323        // takes, as browsers have them.
324        Pseudo::Marker => {
325            font || animation
326                || name.starts_with("transition")
327                || name.starts_with("white-space")
328                || name.starts_with("text-emphasis")
329                || matches!(
330                    name,
331                    "color"
332                        | "content"
333                        | "quotes"
334                        | "direction"
335                        | "unicode-bidi"
336                        | "text-combine-upright"
337                        | "line-height"
338                        | "letter-spacing"
339                        | "word-spacing"
340                        | "tab-size"
341                        | "text-transform"
342                        | "text-indent"
343                        | "hyphens"
344                        | "line-break"
345                        | "overflow-wrap"
346                        | "word-break"
347                        | "text-shadow"
348                        | "text-decoration-skip-ink"
349                        | "cursor"
350                )
351        }
352        // CSS Pseudo 4 §3.2.
353        Pseudo::Selection | Pseudo::Highlight(_) => highlight_applies(name),
354    }
355}
356
357pub(super) fn highlight_applies(name: &str) -> bool {
358    name.starts_with("text-decoration")
359        || name.starts_with("text-underline")
360        || matches!(
361            name,
362            "color"
363                | "background-color"
364                | "text-shadow"
365                | "stroke-color"
366                | "fill-color"
367                | "stroke-width"
368        )
369}
370
371impl PseudoStyles {
372    /// The cascade's declarations for `p` on `el`, put in order.
373    fn style(
374        &self,
375        el: NodeId,
376        p: &Pseudo,
377        parent: &Computed,
378        originating: &Computed,
379        root: Option<&Computed>,
380        parent_highlight: Option<&Computed>,
381    ) -> Computed {
382        let none = Vec::new();
383        let matched = self.matched.get(&el).unwrap_or(&none);
384        let attrs = self.attrs.get(&el).map_or(&[][..], |a| &a[..]);
385        // Values as text first, `attr()` substituted, then parsed: what
386        // the declarations borrow has to outlive them.
387        let mut texts: Vec<(Key, &str, std::borrow::Cow<'_, str>, bool)> = Vec::new();
388        for &(r, key) in self.always.iter().chain(matched) {
389            let rule = &self.rules[r];
390            if rule.pseudo != *p {
391                continue;
392            }
393            for (name, value, important) in &rule.declarations {
394                let value = if rule.needs_attrs && name.eq_ignore_ascii_case("content") {
395                    std::borrow::Cow::Owned(substitute_attrs(value, attrs))
396                } else {
397                    std::borrow::Cow::Borrowed(value.as_str())
398                };
399                texts.push((key, name, value, *important));
400            }
401        }
402        let parsed: Vec<Vec<ComponentValue<'_>>> = texts
403            .iter()
404            .map(|(_, _, v, _)| crate::parse_component_values(v))
405            .collect();
406        let mut declared: HashMap<&'static str, Vec<Declared<'_>>> = HashMap::new();
407        let mut custom: HashMap<String, Vec<(Key, Vec<ComponentValue<'_>>)>> = HashMap::new();
408        for ((key, name, _, important), values) in texts.iter().zip(&parsed) {
409            add(&mut declared, &mut custom, name, values, *important, *key);
410        }
411        declared.retain(|name, _| applies(p, name));
412        for list in declared.values_mut() {
413            list.sort_by_key(|d| d.key);
414        }
415        for list in custom.values_mut() {
416            list.sort_by_key(|d| d.0);
417        }
418        let mut out = compute::compute(compute::Input {
419            declared: &declared,
420            custom: &custom,
421            parent: Some(parent),
422            root,
423            is_root: false,
424            env: &self.env,
425            cq: parent.cq_children,
426            registered: &self.registered,
427        });
428        compute::pseudo_fix_up(&mut out, p, originating, parent_highlight);
429        out
430    }
431}
432
433impl super::Styled {
434    /// `property`'s value on `el`'s pseudo-element `p`, as
435    /// `getComputedStyle(el, "::before")` writes it; `None` for a node
436    /// that isn't an element or a property that isn't.
437    ///
438    /// ```
439    /// use parsec_css::cascade::{Pseudo, Styler};
440    ///
441    /// let doc = parsec::parse("<style>p::before { content: 'x'; color: green }</style><p>", false);
442    /// let styled = Styler::new(Default::default()).with_document_styles(&doc).style(&doc);
443    /// let p = parsec::css::SelectorList::parse("p").unwrap().select_first(&doc, doc.root()).unwrap();
444    /// assert_eq!(styled.get_pseudo(p, &Pseudo::Before, "color").as_deref(), Some("rgb(0, 128, 0)"));
445    /// assert_eq!(styled.get_pseudo(p, &Pseudo::After, "content").as_deref(), Some("none"));
446    /// assert_eq!(styled.pseudo_exists(p, &Pseudo::Before), Some(true));
447    /// ```
448    pub fn get_pseudo(&self, el: NodeId, p: &Pseudo, property: &str) -> Option<String> {
449        self.computed_pseudo(el, p)?.get(property)
450    }
451
452    /// Everything about the style of `el`'s pseudo-element `p`, worked out
453    /// now: it inherits from `el`, `::first-letter` from `::first-line`,
454    /// and a highlight from its parent element's highlight.
455    pub fn computed_pseudo(&self, el: NodeId, p: &Pseudo) -> Option<Computed> {
456        let own = self.styles.get(&el)?;
457        let ps = &self.pseudo;
458        let root = ps.root.and_then(|r| self.styles.get(&r));
459        if p.is_highlight() {
460            // Down from the outermost element styled, each highlight
461            // inheriting from the one before.
462            let mut chain = vec![el];
463            let mut at = own.parent;
464            while let Some(a) = at {
465                let Some(c) = self.styles.get(&a) else { break };
466                chain.push(a);
467                at = c.parent;
468            }
469            let mut highlight: Option<Computed> = None;
470            for &n in chain.iter().rev() {
471                let originating = &self.styles[&n];
472                let h = ps.style(n, p, originating, originating, root, highlight.as_ref());
473                highlight = Some(h);
474            }
475            return highlight;
476        }
477        let first_line;
478        let parent = match p {
479            Pseudo::FirstLetter => {
480                first_line = self.computed_pseudo(el, &Pseudo::FirstLine)?;
481                &first_line
482            }
483            _ => own,
484        };
485        Some(ps.style(el, p, parent, own, root, None))
486    }
487
488    /// Whether `el` has the pseudo-element `p` at all: `::before` and
489    /// `::after` when their `content` is something, `::marker` on a list
490    /// item with a marker to show, none of them under `display: none`.
491    /// `None` for the others, whose being there depends on text, layout or
492    /// state (the first line, a selection, the top layer), and for a node
493    /// that isn't an element.
494    pub fn pseudo_exists(&self, el: NodeId, p: &Pseudo) -> Option<bool> {
495        let own = self.styles.get(&el)?;
496        if !matches!(p, Pseudo::Before | Pseudo::After | Pseudo::Marker) {
497            return None;
498        }
499        if own.get("display").as_deref() == Some("none") {
500            return Some(false);
501        }
502        let c = self.computed_pseudo(el, p)?;
503        let content = c.get("content").unwrap_or_default();
504        Some(match p {
505            Pseudo::Marker => {
506                let list_item = own
507                    .get("display")
508                    .is_some_and(|d| d.split_ascii_whitespace().any(|w| w == "list-item"));
509                let shown = content != "normal"
510                    || own.get("list-style-type").as_deref() != Some("none")
511                    || own.get("list-style-image").as_deref() != Some("none");
512                list_item && content != "none" && shown
513            }
514            _ => {
515                !matches!(content.as_str(), "none" | "normal")
516                    && c.get("display").as_deref() != Some("none")
517            }
518        })
519    }
520}
521
522#[cfg(test)]
523mod tests {
524    use super::*;
525    use crate::cascade::Styler;
526    use parsec::css::SelectorList;
527
528    /// Each `(selector, pseudo, property)`'s value on `html` styled.
529    fn styled(html: &str) -> (parsec::Document, super::super::Styled) {
530        let doc = parsec::parse(html, false);
531        let styled = Styler::new(Environment::default())
532            .with_document_styles(&doc)
533            .style(&doc);
534        (doc, styled)
535    }
536
537    fn at(doc: &parsec::Document, sel: &str) -> NodeId {
538        SelectorList::parse(sel)
539            .unwrap()
540            .select_first(doc, doc.root())
541            .unwrap()
542    }
543
544    fn get(html: &str, sel: &str, p: &str, property: &str) -> String {
545        let (doc, s) = styled(html);
546        let p = Pseudo::parse(p).unwrap();
547        s.get_pseudo(at(&doc, sel), &p, property)
548            .unwrap_or_default()
549    }
550
551    #[test]
552    fn before_and_after() {
553        let html = "<style>p { color: blue; margin-top: 3px } #a::before { content: 'x' counter(c) open-quote attr(title); margin-left: 2em } \
554                    p:before { color: green } p::after { content: normal }</style><p id=a title='hi' style='font-size: 10px'>";
555        assert_eq!(get(html, "p", "::before", "color"), "rgb(0, 128, 0)");
556        // Inherited from the paragraph, `em` its font size; not inherited
557        // isn't.
558        assert_eq!(get(html, "p", "::before", "margin-left"), "20px");
559        assert_eq!(get(html, "p", "::before", "margin-top"), "0px");
560        assert_eq!(get(html, "p", "::after", "color"), "rgb(0, 0, 255)");
561        assert_eq!(
562            get(html, "p", "::before", "content"),
563            "\"x\" counter(c) open-quote \"hi\""
564        );
565        assert_eq!(get(html, "p", "::after", "content"), "none");
566        let (doc, s) = styled(html);
567        let p = at(&doc, "p");
568        assert_eq!(s.pseudo_exists(p, &Pseudo::Before), Some(true));
569        assert_eq!(s.pseudo_exists(p, &Pseudo::After), Some(false));
570        assert_eq!(s.pseudo_exists(p, &Pseudo::FirstLine), None);
571        // The UA's quotes.
572        assert_eq!(get("<q>", "q", "::before", "content"), "open-quote");
573        let (doc, s) = styled("<style>q { display: none }</style><q>");
574        assert_eq!(s.pseudo_exists(at(&doc, "q"), &Pseudo::Before), Some(false));
575    }
576
577    #[test]
578    fn cascade_order() {
579        // `p::before` is (0,0,2), and beats `*::before` and `::before`.
580        let html = "<style>p::before { color: green } ::before { color: red } *::before { color: red }</style><p>";
581        assert_eq!(get(html, "p", "::before", "color"), "rgb(0, 128, 0)");
582        let html = "<style>@layer a { #x::before { color: green !important } } #x::before { color: red !important }</style><p id=x>";
583        assert_eq!(get(html, "p", "::before", "color"), "rgb(0, 128, 0)");
584        // `attr()` from a rule for every element.
585        let html = "<style>*::before { content: attr(data-n) }</style><p data-n=3><i>";
586        assert_eq!(get(html, "p", "::before", "content"), "\"3\"");
587        assert_eq!(get(html, "i", "::before", "content"), "\"\"");
588        // Scoped, and in a container that's the originating element.
589        let html = "<style>@scope (.s) { p::before { color: green } } .c { container-type: inline-size } \
590                    @container (width > 100px) { .c::after { color: green } }</style><div class=s><p></p></div><p class=c>";
591        assert_eq!(get(html, "div p", "::before", "color"), "rgb(0, 128, 0)");
592        assert_eq!(get(html, "body > p", "::before", "color"), "rgb(0, 0, 0)");
593        let doc = parsec::parse(html, false);
594        let s = Styler::new(Environment::default())
595            .with_document_styles(&doc)
596            .container_sizes(|_, _| Some((200.0, 10.0)))
597            .style(&doc);
598        let c = at(&doc, ".c");
599        assert_eq!(
600            s.get_pseudo(c, &Pseudo::After, "color").as_deref(),
601            Some("rgb(0, 128, 0)")
602        );
603        // A pseudo-element after a state never matches here.
604        let html = "<style>p::before:hover { color: red }</style><p>";
605        assert_eq!(get(html, "p", "::before", "color"), "rgb(0, 0, 0)");
606    }
607
608    #[test]
609    fn the_wiki_example() {
610        let html = "<style>li { color: blue } li::marker { color: green; position: absolute } \
611                    .n::before { content: '#' attr(data-n) ' ' }</style><ol><li class=n data-n=1>One</ol>";
612        assert_eq!(get(html, "li", "::marker", "color"), "rgb(0, 128, 0)");
613        assert_eq!(get(html, "li", "::marker", "position"), "static");
614        assert_eq!(get(html, "li", "::before", "content"), "\"#\" \"1\" \" \"");
615    }
616
617    #[test]
618    fn markers() {
619        let html = "<style>li { text-indent: 4px; text-transform: uppercase } .in { list-style-position: inside } \
620                    li::marker { color: green; position: absolute; list-style-type: square; display: none } .none { list-style-type: none }</style>\
621                    <ul><li>a<li class=in>b<li class=none>c</ul><p>";
622        assert_eq!(get(html, "li", "::marker", "color"), "rgb(0, 128, 0)");
623        assert_eq!(get(html, "li", "::marker", "unicode-bidi"), "isolate");
624        assert_eq!(
625            get(html, "li", "::marker", "font-variant-numeric"),
626            "tabular-nums"
627        );
628        assert_eq!(get(html, "li", "::marker", "text-transform"), "none");
629        assert_eq!(get(html, "li", "::marker", "text-indent"), "0px");
630        // What doesn't apply to a marker doesn't count.
631        assert_eq!(get(html, "li", "::marker", "position"), "static");
632        assert_eq!(get(html, "li", "::marker", "list-style-type"), "disc");
633        assert_eq!(get(html, "li", "::marker", "display"), "block");
634        assert_eq!(get(html, ".in", "::marker", "display"), "inline");
635        assert_eq!(get(html, "li", "::marker", "content"), "normal");
636        let (doc, s) = styled(html);
637        assert_eq!(s.pseudo_exists(at(&doc, "li"), &Pseudo::Marker), Some(true));
638        assert_eq!(
639            s.pseudo_exists(at(&doc, ".none"), &Pseudo::Marker),
640            Some(false)
641        );
642        assert_eq!(s.pseudo_exists(at(&doc, "p"), &Pseudo::Marker), Some(false));
643    }
644
645    #[test]
646    fn first_line_and_letter() {
647        let html = "<style>p { color: blue } p::first-line { color: green; margin-left: 9px; font-size: 20px } \
648                    p::first-letter { margin-left: 3px; float: left; position: absolute }</style><p>";
649        assert_eq!(get(html, "p", "::first-line", "color"), "rgb(0, 128, 0)");
650        assert_eq!(get(html, "p", "::first-line", "margin-left"), "0px");
651        // The first letter is in the first line.
652        assert_eq!(get(html, "p", "::first-letter", "color"), "rgb(0, 128, 0)");
653        assert_eq!(get(html, "p", "::first-letter", "font-size"), "20px");
654        assert_eq!(get(html, "p", "::first-letter", "margin-left"), "3px");
655        assert_eq!(get(html, "p", "::first-letter", "float"), "left");
656        assert_eq!(get(html, "p", "::first-letter", "position"), "static");
657        let html = "<style>input::placeholder { color: green; line-height: 9px; background-color: inherit } input { background-color: red }</style><input>";
658        assert_eq!(
659            get(html, "input", "::placeholder", "color"),
660            "rgb(0, 128, 0)"
661        );
662        assert_eq!(
663            get(html, "input", "::placeholder", "background-color"),
664            "rgb(255, 0, 0)"
665        );
666        assert_eq!(get(html, "input", "::placeholder", "line-height"), "normal");
667    }
668
669    #[test]
670    fn highlights() {
671        let html = "<style>body { color: blue; margin-top: 2px } div::selection { background-color: green; color: red; margin-top: 7px } \
672                    p::highlight(x) { color: green }</style><div><p></p></div>";
673        // The child's ::selection inherits the parent's, `background-color`
674        // too, though it's not an inherited property.
675        assert_eq!(
676            get(html, "p", "::selection", "background-color"),
677            "rgb(0, 128, 0)"
678        );
679        assert_eq!(get(html, "p", "::selection", "color"), "rgb(255, 0, 0)");
680        // What doesn't apply is the originating element's.
681        assert_eq!(get(html, "div", "::selection", "margin-top"), "0px");
682        assert_eq!(get(html, "body", "::selection", "margin-top"), "2px");
683        // From the root's highlight, whose colour is the root's: not the
684        // body's own.
685        assert_eq!(get(html, "body", "::selection", "color"), "rgb(0, 0, 0)");
686        assert_eq!(get(html, "p", "::highlight(x)", "color"), "rgb(0, 128, 0)");
687        assert_eq!(get(html, "p", "::highlight(y)", "color"), "rgb(0, 0, 0)");
688        let html = "<style>:root { color: blue }</style><p>";
689        assert_eq!(get(html, "p", "::selection", "color"), "rgb(0, 0, 255)");
690    }
691
692    #[test]
693    fn splits() {
694        use Split::*;
695        assert_eq!(split_pseudo("p.x"), No);
696        assert_eq!(split_pseudo("p:hover"), No);
697        assert_eq!(
698            split_pseudo("#t::before"),
699            Pseudo("#t".into(), super::Pseudo::Before)
700        );
701        assert_eq!(
702            split_pseudo("li:BEFORE"),
703            Pseudo("li".into(), super::Pseudo::Before)
704        );
705        assert_eq!(
706            split_pseudo("::marker"),
707            Pseudo("*".into(), super::Pseudo::Marker)
708        );
709        assert_eq!(
710            split_pseudo("a > b:not(.c)::first-line"),
711            Pseudo("a > b:not(.c)".into(), super::Pseudo::FirstLine)
712        );
713        assert_eq!(
714            split_pseudo("#t::highlight(Foo)"),
715            Pseudo("#t".into(), super::Pseudo::Highlight("Foo".into()))
716        );
717        // Inside `:is()`, or in an attribute value, it isn't one.
718        assert_eq!(split_pseudo(":is(a::before)"), No);
719        assert_eq!(split_pseudo("[title='::before']"), No);
720        assert_eq!(split_pseudo("a::before:hover"), Unstyled);
721        assert_eq!(split_pseudo("a::before::marker"), Unstyled);
722        assert_eq!(split_pseudo("a::part(x)"), Unstyled);
723        assert_eq!(
724            split_pseudo("a ::before"),
725            Pseudo("a *".into(), super::Pseudo::Before)
726        );
727        assert_eq!(
728            split_pseudo("a>::after"),
729            Pseudo("a>*".into(), super::Pseudo::After)
730        );
731        // `:marker` was never one with one colon.
732        assert_eq!(split_pseudo("a:marker"), No);
733    }
734
735    #[test]
736    fn parses_names() {
737        assert_eq!(Pseudo::parse("::BEFORE"), Some(Pseudo::Before));
738        assert_eq!(Pseudo::parse(":first-line"), Some(Pseudo::FirstLine));
739        assert_eq!(Pseudo::parse(":marker"), None);
740        assert_eq!(
741            Pseudo::parse("::highlight(foo)"),
742            Some(Pseudo::Highlight("foo".into()))
743        );
744        assert_eq!(Pseudo::parse("::nope"), None);
745        assert_eq!(
746            Pseudo::FileSelectorButton.to_string(),
747            "::file-selector-button"
748        );
749    }
750
751    #[test]
752    fn attr_in_content() {
753        let attrs = vec![("title".to_string(), "a\"b".to_string())];
754        assert_eq!(substitute_attrs("attr(title)", &attrs), "\"a\\\"b\"");
755        assert_eq!(
756            substitute_attrs("\"[\" attr(nope) \"]\"", &attrs),
757            "\"[\" \"\" \"]\""
758        );
759        assert_eq!(substitute_attrs("attr(nope, 'x')", &attrs), "\"x\"");
760    }
761}