Skip to main content

eternal_styler/
selector.rs

1// This Source Code Form is subject to the terms of the Mozilla Public
2// License, v. 2.0. If a copy of the MPL was not distributed with this
3// file, You can obtain one at https://mozilla.org/MPL/2.0/.
4
5//! Selectors: the `selectors` crate configured for UI trees.
6
7use std::fmt;
8
9use cssparser::{CowRcStr, ParseError, Parser, ParserInput, SourceLocation, ToCss};
10use selectors::context::{
11    MatchingContext, MatchingForInvalidation, MatchingMode, NeedsSelectorFlags, QuirksMode,
12    SelectorCaches,
13};
14use selectors::matching::{matches_selector, matches_selector_list};
15use selectors::parser::{NonTSPseudoClass, ParseRelative, SelectorParseErrorKind};
16
17use crate::atom::{Atom, AttrValue};
18use crate::element::{Adapter, Element, ElementState};
19use crate::error::{Error, StyleError, StyleParseErrorKind};
20
21/// The type-level configuration handed to the `selectors` crate: which
22/// string types, pseudo-classes and pseudo-elements selectors are made of.
23#[derive(Clone, Debug, PartialEq, Eq)]
24pub struct SelectorImpl;
25
26impl selectors::parser::SelectorImpl for SelectorImpl {
27    type ExtraMatchingData<'a> = ();
28    type AttrValue = AttrValue;
29    type Identifier = Atom;
30    type LocalName = Atom;
31    type NamespaceUrl = Atom;
32    type NamespacePrefix = Atom;
33    type BorrowedNamespaceUrl = str;
34    type BorrowedLocalName = str;
35    type NonTSPseudoClass = PseudoClass;
36    type PseudoElement = PseudoElement;
37}
38
39/// A pseudo-class answered by [`Element::state`] or
40/// [`Element::has_custom_state`] rather than by the shape of the tree.
41#[derive(Clone, Debug, PartialEq, Eq, Hash)]
42pub enum PseudoClass {
43    Hover,
44    Active,
45    Focus,
46    FocusVisible,
47    FocusWithin,
48    Enabled,
49    Disabled,
50    Checked,
51    Indeterminate,
52    ReadOnly,
53    ReadWrite,
54    Required,
55    Optional,
56    Valid,
57    Invalid,
58    PlaceholderShown,
59    /// `:state(name)`, a state the toolkit defines itself.
60    CustomState(Atom),
61}
62
63impl PseudoClass {
64    pub(crate) fn matches<E: Element>(&self, element: &E) -> bool {
65        let state = element.state();
66        match self {
67            Self::Hover => state.contains(ElementState::HOVER),
68            Self::Active => state.contains(ElementState::ACTIVE),
69            Self::Focus => state.contains(ElementState::FOCUS),
70            Self::FocusVisible => state.contains(ElementState::FOCUS_VISIBLE),
71            Self::FocusWithin => state.contains(ElementState::FOCUS_WITHIN),
72            Self::Enabled => !state.contains(ElementState::DISABLED),
73            Self::Disabled => state.contains(ElementState::DISABLED),
74            Self::Checked => state.contains(ElementState::CHECKED),
75            Self::Indeterminate => state.contains(ElementState::INDETERMINATE),
76            Self::ReadOnly => state.contains(ElementState::READ_ONLY),
77            Self::ReadWrite => !state.contains(ElementState::READ_ONLY),
78            Self::Required => state.contains(ElementState::REQUIRED),
79            Self::Optional => !state.contains(ElementState::REQUIRED),
80            Self::Valid => !state.contains(ElementState::INVALID),
81            Self::Invalid => state.contains(ElementState::INVALID),
82            Self::PlaceholderShown => state.contains(ElementState::PLACEHOLDER_SHOWN),
83            Self::CustomState(name) => element.has_custom_state(name),
84        }
85    }
86
87    fn parse(location: SourceLocation, name: CowRcStr<'_>) -> Result<Self, StyleError<'_>> {
88        Ok(cssparser::match_ignore_ascii_case! { &name,
89            "hover" => Self::Hover,
90            "active" => Self::Active,
91            "focus" => Self::Focus,
92            "focus-visible" => Self::FocusVisible,
93            "focus-within" => Self::FocusWithin,
94            "enabled" => Self::Enabled,
95            "disabled" => Self::Disabled,
96            "checked" => Self::Checked,
97            "indeterminate" => Self::Indeterminate,
98            "read-only" => Self::ReadOnly,
99            "read-write" => Self::ReadWrite,
100            "required" => Self::Required,
101            "optional" => Self::Optional,
102            "valid" => Self::Valid,
103            "invalid" => Self::Invalid,
104            "placeholder-shown" => Self::PlaceholderShown,
105            _ => {
106                return Err(location.new_custom_error(
107                    SelectorParseErrorKind::UnsupportedPseudoClassOrElement(name),
108                ));
109            }
110        })
111    }
112}
113
114impl ToCss for PseudoClass {
115    fn to_css<W: fmt::Write>(&self, dest: &mut W) -> fmt::Result {
116        let name = match self {
117            Self::Hover => "hover",
118            Self::Active => "active",
119            Self::Focus => "focus",
120            Self::FocusVisible => "focus-visible",
121            Self::FocusWithin => "focus-within",
122            Self::Enabled => "enabled",
123            Self::Disabled => "disabled",
124            Self::Checked => "checked",
125            Self::Indeterminate => "indeterminate",
126            Self::ReadOnly => "read-only",
127            Self::ReadWrite => "read-write",
128            Self::Required => "required",
129            Self::Optional => "optional",
130            Self::Valid => "valid",
131            Self::Invalid => "invalid",
132            Self::PlaceholderShown => "placeholder-shown",
133            Self::CustomState(name) => {
134                dest.write_str(":state(")?;
135                name.to_css(dest)?;
136                return dest.write_str(")");
137            }
138        };
139        dest.write_str(":")?;
140        dest.write_str(name)
141    }
142}
143
144impl NonTSPseudoClass for PseudoClass {
145    type Impl = SelectorImpl;
146
147    fn is_active_or_hover(&self) -> bool {
148        matches!(self, Self::Active | Self::Hover)
149    }
150
151    fn is_user_action_state(&self) -> bool {
152        matches!(
153            self,
154            Self::Active | Self::Hover | Self::Focus | Self::FocusVisible | Self::FocusWithin
155        )
156    }
157}
158
159/// There are no pseudo-elements. This type has no values; it exists because
160/// the `selectors` crate needs one.
161#[derive(Clone, Debug, PartialEq, Eq, Hash)]
162pub enum PseudoElement {}
163
164impl ToCss for PseudoElement {
165    fn to_css<W: fmt::Write>(&self, _dest: &mut W) -> fmt::Result {
166        match *self {}
167    }
168}
169
170impl selectors::parser::PseudoElement for PseudoElement {
171    type Impl = SelectorImpl;
172}
173
174/// The hooks the `selectors` parser calls for the bits it does not define
175/// itself.
176pub(crate) struct SelectorParser;
177
178impl<'i> selectors::Parser<'i> for SelectorParser {
179    type Impl = SelectorImpl;
180    type Error = StyleParseErrorKind<'i>;
181
182    fn parse_is_and_where(&self) -> bool {
183        true
184    }
185
186    fn parse_has(&self) -> bool {
187        true
188    }
189
190    fn parse_nth_child_of(&self) -> bool {
191        true
192    }
193
194    fn parse_non_ts_pseudo_class(
195        &self,
196        location: SourceLocation,
197        name: CowRcStr<'i>,
198    ) -> Result<PseudoClass, ParseError<'i, Self::Error>> {
199        PseudoClass::parse(location, name)
200    }
201
202    fn parse_non_ts_functional_pseudo_class<'t>(
203        &self,
204        name: CowRcStr<'i>,
205        parser: &mut Parser<'i, 't>,
206        _after_part: bool,
207    ) -> Result<PseudoClass, ParseError<'i, Self::Error>> {
208        if name.eq_ignore_ascii_case("state") {
209            let state = parser.expect_ident()?;
210            return Ok(PseudoClass::CustomState(Atom::new(state)));
211        }
212        Err(
213            parser.new_custom_error(SelectorParseErrorKind::UnsupportedPseudoClassOrElement(
214                name,
215            )),
216        )
217    }
218}
219
220pub(crate) type RawSelector = selectors::parser::Selector<SelectorImpl>;
221pub(crate) type RawSelectorList = selectors::SelectorList<SelectorImpl>;
222
223pub(crate) fn parse_selector_list<'i>(
224    input: &mut Parser<'i, '_>,
225) -> Result<RawSelectorList, StyleError<'i>> {
226    RawSelectorList::parse(&SelectorParser, input, ParseRelative::No)
227}
228
229/// Runs `f` with a matching context set up the way this crate matches: no
230/// quirks, no bloom filter, no invalidation bookkeeping.
231pub(crate) fn with_matching_context<R>(
232    f: impl FnOnce(&mut MatchingContext<'_, SelectorImpl>) -> R,
233) -> R {
234    let mut caches = SelectorCaches::default();
235    let mut context = MatchingContext::new(
236        MatchingMode::Normal,
237        None,
238        &mut caches,
239        QuirksMode::NoQuirks,
240        NeedsSelectorFlags::No,
241        MatchingForInvalidation::No,
242    );
243    f(&mut context)
244}
245
246/// One parsed selector, such as `button.primary:hover`.
247#[derive(Clone, Debug)]
248pub struct Selector(RawSelector);
249
250impl Selector {
251    /// The selector's specificity, packed the way browsers do it: ids in the
252    /// top bits, then classes, attributes and pseudo-classes, then types.
253    /// Higher wins.
254    pub fn specificity(&self) -> u32 {
255        self.0.specificity()
256    }
257
258    pub fn matches<E: Element>(&self, element: &E) -> bool {
259        let element = Adapter(element.clone());
260        with_matching_context(|context| matches_selector(&self.0, 0, None, &element, context))
261    }
262}
263
264impl fmt::Display for Selector {
265    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
266        self.0.to_css(f)
267    }
268}
269
270/// A comma-separated list of selectors, the prelude of a style rule.
271#[derive(Clone, Debug)]
272pub struct SelectorList(RawSelectorList);
273
274impl SelectorList {
275    /// Parses something like `button, .link:hover`.
276    pub fn parse(css: &str) -> Result<Self, Error> {
277        let mut input = ParserInput::new(css);
278        let mut parser = Parser::new(&mut input);
279        parser
280            .parse_entirely(parse_selector_list)
281            .map(Self)
282            .map_err(Error::from_parse_error)
283    }
284
285    pub(crate) fn from_raw(raw: RawSelectorList) -> Self {
286        Self(raw)
287    }
288
289    pub(crate) fn raw(&self) -> &RawSelectorList {
290        &self.0
291    }
292
293    /// Whether any selector in the list matches.
294    pub fn matches<E: Element>(&self, element: &E) -> bool {
295        let element = Adapter(element.clone());
296        with_matching_context(|context| matches_selector_list(&self.0, &element, context))
297    }
298
299    pub fn len(&self) -> usize {
300        self.0.len()
301    }
302
303    pub fn is_empty(&self) -> bool {
304        self.0.len() == 0
305    }
306
307    /// The selectors in the list, in source order.
308    pub fn selectors(&self) -> impl Iterator<Item = Selector> + '_ {
309        self.0.slice().iter().map(|raw| Selector(raw.clone()))
310    }
311}
312
313impl fmt::Display for SelectorList {
314    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
315        self.0.to_css(f)
316    }
317}
318
319#[cfg(test)]
320mod tests {
321    use super::*;
322    use crate::ErrorKind;
323
324    #[test]
325    fn parses_and_serialises() {
326        let list = SelectorList::parse("button.primary:hover, #save:not(:disabled)").unwrap();
327        assert_eq!(list.len(), 2);
328        assert_eq!(
329            list.to_string(),
330            "button.primary:hover, #save:not(:disabled)"
331        );
332        let state = SelectorList::parse("panel:state(loading)").unwrap();
333        assert_eq!(state.to_string(), "panel:state(loading)");
334    }
335
336    #[test]
337    fn specificity_orders_as_expected() {
338        let spec = |css: &str| {
339            SelectorList::parse(css)
340                .unwrap()
341                .selectors()
342                .next()
343                .unwrap()
344                .specificity()
345        };
346        assert!(spec("#a") > spec(".a.b.c"));
347        assert!(spec(".a") > spec("a b c"));
348        assert!(spec("a:hover") > spec("a"));
349        assert_eq!(spec(":where(.a)"), spec("*"));
350        assert_eq!(spec(":is(.a, #b)"), spec("#b"));
351    }
352
353    #[test]
354    fn rejects_what_it_does_not_support() {
355        let err = SelectorList::parse("a::before").unwrap_err();
356        assert!(matches!(err.kind(), ErrorKind::InvalidSelector(_)), "{err}");
357        let err = SelectorList::parse("a:visited").unwrap_err();
358        assert_eq!(
359            err.to_string(),
360            "line 1, column 3: invalid selector: unsupported pseudo-class or pseudo-element ':visited'"
361        );
362        assert!(SelectorList::parse("a,").is_err());
363        assert!(SelectorList::parse("").is_err());
364    }
365}