Skip to main content

strata_style/
selector.rs

1//! CSS Selector parser, specificity calculator, and hierarchical element matcher.
2//!
3//! Implements W3C Selectors Level 3 & Level 4:
4//! - Compound selectors (Universal, Type, ID, Class, Attribute, Pseudo-class)
5//! - Combinators: Descendant (` `), Child (`>`), Adjacent Sibling (`+`), Subsequent Sibling (`~`)
6//! - Attribute matching operators: `[attr]`, `[attr=val]`, `[attr^=val]`, `[attr$=val]`, `[attr*=val]`, `[attr~=val]`, `[attr|=val]`
7//! - W3C 4-tuple specificity calculation `(inline, id, class/attr/pseudo, type)`
8
9use crate::specificity::Specificity;
10
11/// Interactive element pseudo-classes and environmental state.
12#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
13pub struct PseudoState {
14    pub is_hovered: bool,
15    pub is_focused: bool,
16    pub is_active: bool,
17    pub is_disabled: bool,
18    pub is_dark: bool,
19    pub is_group_hovered: bool,
20    pub is_group_focused: bool,
21    pub is_group_active: bool,
22}
23
24/// Attribute matching operator per W3C CSS Selectors Level 4.
25#[derive(Debug, Clone, PartialEq, Eq)]
26pub enum AttributeMatchOp {
27    /// `[attr]` - Element has attribute regardless of value.
28    Exists,
29    /// `[attr=val]` - Element attribute equals exact value.
30    Exact(String),
31    /// `[attr^=val]` - Element attribute value begins with prefix.
32    Prefix(String),
33    /// `[attr$=val]` - Element attribute value ends with suffix.
34    Suffix(String),
35    /// `[attr*=val]` - Element attribute value contains substring.
36    Substring(String),
37    /// `[attr~=val]` - Element attribute value is a whitespace-separated list containing word.
38    Includes(String),
39    /// `[attr|=val]` - Element attribute value is exactly val or starts with val followed by '-'.
40    DashMatch(String),
41}
42
43/// Parsed attribute selector declaration.
44#[derive(Debug, Clone, PartialEq, Eq)]
45pub struct AttributeSelector {
46    pub name: String,
47    pub op: AttributeMatchOp,
48}
49
50impl AttributeSelector {
51    /// Evaluates whether this attribute selector matches a list of key-value attributes.
52    pub fn matches(&self, attributes: &[(String, String)]) -> bool {
53        for (k, v) in attributes {
54            if k.eq_ignore_ascii_case(&self.name) {
55                return match &self.op {
56                    AttributeMatchOp::Exists => true,
57                    AttributeMatchOp::Exact(expected) => v == expected,
58                    AttributeMatchOp::Prefix(prefix) => v.starts_with(prefix),
59                    AttributeMatchOp::Suffix(suffix) => v.ends_with(suffix),
60                    AttributeMatchOp::Substring(sub) => v.contains(sub),
61                    AttributeMatchOp::Includes(word) => v.split_whitespace().any(|w| w == word),
62                    AttributeMatchOp::DashMatch(prefix) => {
63                        v == prefix || v.starts_with(&format!("{}-", prefix))
64                    }
65                };
66            }
67        }
68        false
69    }
70}
71
72/// Atomic part of a CSS compound selector.
73#[derive(Debug, Clone, PartialEq, Eq)]
74pub enum SelectorPart {
75    Universal,
76    Tag(String),
77    Id(String),
78    Class(String),
79    Attribute(AttributeSelector),
80    PseudoClass(String),
81}
82
83/// Combinator relating two compound selectors in a complex selector.
84#[derive(Debug, Clone, Copy, PartialEq, Eq)]
85pub enum Combinator {
86    /// `E F` - Element F is an arbitrary descendant of element E.
87    Descendant,
88    /// `E > F` - Element F is an immediate child of element E.
89    Child,
90    /// `E + F` - Element F is immediately preceded by sibling element E.
91    AdjacentSibling,
92    /// `E ~ F` - Element F is preceded by sibling element E.
93    SubsequentSibling,
94}
95
96/// A compound selector representing a sequence of simple selectors without combinators.
97#[derive(Debug, Clone, PartialEq, Eq, Default)]
98pub struct CompoundSelector {
99    pub parts: Vec<SelectorPart>,
100    pub specificity: Specificity,
101}
102
103/// Splits a comma-separated selector list respecting parentheses, brackets, and quotes.
104pub fn split_selector_list(input: &str) -> Vec<String> {
105    let mut result = Vec::new();
106    let mut cur = String::new();
107    let mut paren_depth = 0;
108    let mut bracket_depth = 0;
109    let mut in_quote = None;
110
111    for c in input.chars() {
112        if let Some(q) = in_quote {
113            cur.push(c);
114            if c == q {
115                in_quote = None;
116            }
117        } else if c == '"' || c == '\'' {
118            in_quote = Some(c);
119            cur.push(c);
120        } else if c == '(' {
121            paren_depth += 1;
122            cur.push(c);
123        } else if c == ')' {
124            if paren_depth > 0 {
125                paren_depth -= 1;
126            }
127            cur.push(c);
128        } else if c == '[' {
129            bracket_depth += 1;
130            cur.push(c);
131        } else if c == ']' {
132            if bracket_depth > 0 {
133                bracket_depth -= 1;
134            }
135            cur.push(c);
136        } else if c == ',' && paren_depth == 0 && bracket_depth == 0 {
137            let s = cur.trim();
138            if !s.is_empty() {
139                result.push(s.to_string());
140            }
141            cur.clear();
142        } else {
143            cur.push(c);
144        }
145    }
146    let s = cur.trim();
147    if !s.is_empty() {
148        result.push(s.to_string());
149    }
150    result
151}
152
153/// Computes specificity for a subselector, including pseudo-classes (:is, :where, :not, :has).
154pub fn compute_subselector_specificity(input: &str) -> Specificity {
155    let trimmed = input.trim();
156    let clean = if let Some(s) = trimmed.strip_prefix('>') {
157        s.trim()
158    } else if let Some(s) = trimmed.strip_prefix('+') {
159        s.trim()
160    } else if let Some(s) = trimmed.strip_prefix('~') {
161        s.trim()
162    } else {
163        trimmed
164    };
165
166    let mut spec = Specificity::ZERO;
167    let mut in_bracket = false;
168    let mut chars = clean.chars().peekable();
169    let mut last_was_boundary = true;
170
171    while let Some(c) = chars.next() {
172        if in_bracket {
173            if c == ']' {
174                in_bracket = false;
175            }
176            continue;
177        }
178        match c {
179            '#' => {
180                spec += Specificity::ID;
181                last_was_boundary = false;
182            }
183            '.' => {
184                spec += Specificity::CLASS;
185                last_was_boundary = false;
186            }
187            '[' => {
188                in_bracket = true;
189                spec += Specificity::CLASS;
190                last_was_boundary = false;
191            }
192            ':' => {
193                if chars.peek() == Some(&':') {
194                    chars.next();
195                    spec += Specificity::TYPE;
196                } else {
197                    let mut ident = String::new();
198                    while let Some(&nc) = chars.peek() {
199                        if nc.is_alphanumeric() || nc == '-' || nc == '_' {
200                            ident.push(chars.next().unwrap());
201                        } else {
202                            break;
203                        }
204                    }
205                    if chars.peek() == Some(&'(') {
206                        chars.next();
207                        let mut depth = 1;
208                        let mut inner = String::new();
209                        for nc in chars.by_ref() {
210                            if nc == '(' {
211                                depth += 1;
212                                inner.push(nc);
213                            } else if nc == ')' {
214                                depth -= 1;
215                                if depth == 0 {
216                                    break;
217                                }
218                                inner.push(nc);
219                            } else {
220                                inner.push(nc);
221                            }
222                        }
223                        if ident == "where" {
224                            // :where() has 0 specificity
225                        } else if ident == "is" || ident == "not" || ident == "has" {
226                            let mut inner_max = Specificity::ZERO;
227                            for sub in split_selector_list(&inner) {
228                                let sub_spec = compute_subselector_specificity(&sub);
229                                if sub_spec > inner_max {
230                                    inner_max = sub_spec;
231                                }
232                            }
233                            spec += inner_max;
234                        } else {
235                            spec += Specificity::CLASS;
236                        }
237                    } else {
238                        spec += Specificity::CLASS;
239                    }
240                }
241                last_was_boundary = false;
242            }
243            c if c.is_alphabetic() && last_was_boundary => {
244                spec += Specificity::TYPE;
245                last_was_boundary = false;
246            }
247            c if c.is_whitespace() || c == '>' || c == '+' || c == '~' => {
248                last_was_boundary = true;
249            }
250            _ => {
251                last_was_boundary = false;
252            }
253        }
254    }
255    spec
256}
257
258impl CompoundSelector {
259    /// Parses a single compound selector (e.g. `button.btn-primary:hover[disabled]`).
260    pub fn parse(input: &str) -> Result<Self, String> {
261        let trimmed = input.trim();
262        if trimmed.is_empty() {
263            return Err("Empty compound selector".to_string());
264        }
265
266        let mut parts = Vec::new();
267        let mut spec = Specificity::ZERO;
268        let mut chars = trimmed.chars().peekable();
269
270        while let Some(&c) = chars.peek() {
271            match c {
272                '*' => {
273                    chars.next();
274                    parts.push(SelectorPart::Universal);
275                }
276                '#' => {
277                    chars.next();
278                    let ident = parse_ident(&mut chars);
279                    if ident.is_empty() {
280                        return Err("Empty ID selector after '#' in CSS".to_string());
281                    }
282                    parts.push(SelectorPart::Id(ident));
283                    spec += Specificity::ID;
284                }
285                '.' => {
286                    chars.next();
287                    let ident = parse_ident(&mut chars);
288                    if ident.is_empty() {
289                        return Err("Empty class selector after '.' in CSS".to_string());
290                    }
291                    parts.push(SelectorPart::Class(ident));
292                    spec += Specificity::CLASS;
293                }
294                ':' => {
295                    chars.next();
296                    // Handle double colons for pseudo-elements as pseudo-classes
297                    let is_pseudo_element = if chars.peek() == Some(&':') {
298                        chars.next();
299                        true
300                    } else {
301                        false
302                    };
303                    let mut ident = parse_ident(&mut chars);
304                    if ident.is_empty() {
305                        return Err("Empty pseudo-class after ':' in CSS".to_string());
306                    }
307                    if chars.peek() == Some(&'(') {
308                        chars.next();
309                        let mut depth = 1;
310                        ident.push('(');
311                        for ch in chars.by_ref() {
312                            ident.push(ch);
313                            if ch == '(' {
314                                depth += 1;
315                            } else if ch == ')' {
316                                depth -= 1;
317                                if depth == 0 {
318                                    break;
319                                }
320                            }
321                        }
322                    }
323
324                    if is_pseudo_element {
325                        spec += Specificity::TYPE;
326                    } else if ident.starts_with("where(") && ident.ends_with(')') {
327                        // W3C Selectors Level 4: :where() always has zero specificity
328                    } else if (ident.starts_with("is(")
329                        || ident.starts_with("not(")
330                        || ident.starts_with("has("))
331                        && ident.ends_with(')')
332                    {
333                        // W3C Selectors Level 4: :is(), :not(), :has() take max specificity of their selector list
334                        let start = if ident.starts_with("is(") { 3 } else { 4 };
335                        let inner = &ident[start..ident.len() - 1];
336                        let mut max_arg_spec = Specificity::ZERO;
337                        for sub in split_selector_list(inner) {
338                            let sub_spec = compute_subselector_specificity(&sub);
339                            if sub_spec > max_arg_spec {
340                                max_arg_spec = sub_spec;
341                            }
342                        }
343                        spec += max_arg_spec;
344                    } else {
345                        spec += Specificity::CLASS;
346                    }
347
348                    parts.push(SelectorPart::PseudoClass(ident));
349                }
350                '[' => {
351                    chars.next();
352                    let attr_sel = parse_attribute_selector(&mut chars)?;
353                    parts.push(SelectorPart::Attribute(attr_sel));
354                    spec += Specificity::CLASS;
355                }
356                _ if c.is_alphabetic() || c == '_' || c == '-' => {
357                    let ident = parse_ident(&mut chars);
358                    parts.push(SelectorPart::Tag(ident));
359                    spec += Specificity::TYPE;
360                }
361                _ => {
362                    return Err(format!(
363                        "Unexpected character '{}' in compound selector '{}'",
364                        c, trimmed
365                    ));
366                }
367            }
368        }
369
370        Ok(Self {
371            parts,
372            specificity: spec,
373        })
374    }
375
376    /// Evaluates whether this compound selector matches an element's attributes and pseudo-state.
377    pub fn matches<C: AsRef<str>>(
378        &self,
379        tag: &str,
380        classes: &[C],
381        id: Option<&str>,
382        attributes: &[(String, String)],
383        state: &PseudoState,
384    ) -> bool {
385        self.matches_with_context(tag, classes, id, attributes, state, &[], None, None, &[])
386    }
387
388    /// Evaluates whether this compound selector matches an element considering sibling, positional, and children context.
389    #[allow(clippy::too_many_arguments)]
390    pub fn matches_with_context<C: AsRef<str>>(
391        &self,
392        tag: &str,
393        classes: &[C],
394        id: Option<&str>,
395        attributes: &[(String, String)],
396        state: &PseudoState,
397        preceding_siblings: &[ElementRef],
398        is_last_child: Option<bool>,
399        is_last_of_type: Option<bool>,
400        children: &[ElementRef],
401    ) -> bool {
402        for part in &self.parts {
403            match part {
404                SelectorPart::Universal => {}
405                SelectorPart::Tag(expected_tag) => {
406                    if !expected_tag.eq_ignore_ascii_case(tag) {
407                        return false;
408                    }
409                }
410                SelectorPart::Id(expected_id) => match id {
411                    Some(actual_id) if actual_id == expected_id => {}
412                    _ => return false,
413                },
414                SelectorPart::Class(expected_class) => {
415                    if !classes
416                        .iter()
417                        .any(|c| c.as_ref() == expected_class.as_str())
418                    {
419                        return false;
420                    }
421                }
422                SelectorPart::Attribute(attr_sel) => {
423                    if !attr_sel.matches(attributes) {
424                        return false;
425                    }
426                }
427                SelectorPart::PseudoClass(pseudo) => {
428                    let p = pseudo.trim();
429                    if p.eq_ignore_ascii_case("hover") {
430                        if !state.is_hovered {
431                            return false;
432                        }
433                    } else if p.eq_ignore_ascii_case("focus") {
434                        if !state.is_focused {
435                            return false;
436                        }
437                    } else if p.eq_ignore_ascii_case("active") {
438                        if !state.is_active {
439                            return false;
440                        }
441                    } else if p.eq_ignore_ascii_case("disabled") {
442                        if !state.is_disabled {
443                            return false;
444                        }
445                    } else if p.eq_ignore_ascii_case("dark") {
446                        if !state.is_dark {
447                            return false;
448                        }
449                    } else if p.eq_ignore_ascii_case("root") {
450                        if !tag.eq_ignore_ascii_case("html") && !tag.eq_ignore_ascii_case(":root") {
451                            return false;
452                        }
453                    } else if p.eq_ignore_ascii_case("first-child") {
454                        let elem_siblings = preceding_siblings
455                            .iter()
456                            .filter(|s| !s.tag.starts_with('#'))
457                            .count();
458                        if elem_siblings != 0 {
459                            return false;
460                        }
461                    } else if p.eq_ignore_ascii_case("last-child") {
462                        if is_last_child != Some(true) {
463                            return false;
464                        }
465                    } else if p.eq_ignore_ascii_case("only-child") {
466                        let elem_siblings = preceding_siblings
467                            .iter()
468                            .filter(|s| !s.tag.starts_with('#'))
469                            .count();
470                        if elem_siblings != 0 || is_last_child != Some(true) {
471                            return false;
472                        }
473                    } else if p.eq_ignore_ascii_case("first-of-type") {
474                        let type_siblings = preceding_siblings
475                            .iter()
476                            .filter(|s| s.tag.eq_ignore_ascii_case(tag))
477                            .count();
478                        if type_siblings != 0 {
479                            return false;
480                        }
481                    } else if p.eq_ignore_ascii_case("last-of-type") {
482                        if is_last_of_type != Some(true) {
483                            return false;
484                        }
485                    } else if p.eq_ignore_ascii_case("only-of-type") {
486                        let type_siblings = preceding_siblings
487                            .iter()
488                            .filter(|s| s.tag.eq_ignore_ascii_case(tag))
489                            .count();
490                        if type_siblings != 0 || is_last_of_type != Some(true) {
491                            return false;
492                        }
493                    } else if p.starts_with("nth-child(") && p.ends_with(')') {
494                        let formula = &p[10..p.len() - 1];
495                        let child_idx = preceding_siblings
496                            .iter()
497                            .filter(|s| !s.tag.starts_with('#'))
498                            .count()
499                            + 1;
500                        if !matches_an_plus_b(formula, child_idx) {
501                            return false;
502                        }
503                    } else if p.starts_with("nth-of-type(") && p.ends_with(')') {
504                        let formula = &p[12..p.len() - 1];
505                        let type_idx = preceding_siblings
506                            .iter()
507                            .filter(|s| s.tag.eq_ignore_ascii_case(tag))
508                            .count()
509                            + 1;
510                        if !matches_an_plus_b(formula, type_idx) {
511                            return false;
512                        }
513                    } else if p.starts_with("not(") && p.ends_with(')') {
514                        let inner = &p[4..p.len() - 1];
515                        let el_classes: Vec<String> =
516                            classes.iter().map(|c| c.as_ref().to_string()).collect();
517                        let el = ElementRef {
518                            tag,
519                            classes: &el_classes,
520                            id,
521                            attributes,
522                            children,
523                        };
524                        for sub in split_selector_list(inner) {
525                            let sub_trimmed = sub.trim();
526                            let matches_sub = if let Ok(sub_sel) = Selector::parse(sub_trimmed) {
527                                sub_sel.matches_hierarchy_full(
528                                    &el,
529                                    &[],
530                                    preceding_siblings,
531                                    is_last_child,
532                                    is_last_of_type,
533                                    state,
534                                )
535                            } else if let Ok(inner_sel) = CompoundSelector::parse(sub_trimmed) {
536                                inner_sel.matches_with_context(
537                                    tag,
538                                    classes,
539                                    id,
540                                    attributes,
541                                    state,
542                                    preceding_siblings,
543                                    is_last_child,
544                                    is_last_of_type,
545                                    children,
546                                )
547                            } else {
548                                false
549                            };
550                            if matches_sub {
551                                return false;
552                            }
553                        }
554                    } else if (p.starts_with("is(") || p.starts_with("where(")) && p.ends_with(')')
555                    {
556                        let start = if p.starts_with("is(") { 3 } else { 6 };
557                        let inner = &p[start..p.len() - 1];
558                        let el_classes: Vec<String> =
559                            classes.iter().map(|c| c.as_ref().to_string()).collect();
560                        let el = ElementRef {
561                            tag,
562                            classes: &el_classes,
563                            id,
564                            attributes,
565                            children,
566                        };
567                        let mut any_matched = false;
568                        for sub in split_selector_list(inner) {
569                            let sub_trimmed = sub.trim();
570                            let matches_sub = if let Ok(sub_sel) = Selector::parse(sub_trimmed) {
571                                sub_sel.matches_hierarchy_full(
572                                    &el,
573                                    &[],
574                                    preceding_siblings,
575                                    is_last_child,
576                                    is_last_of_type,
577                                    state,
578                                )
579                            } else if let Ok(sub_sel) = CompoundSelector::parse(sub_trimmed) {
580                                sub_sel.matches_with_context(
581                                    tag,
582                                    classes,
583                                    id,
584                                    attributes,
585                                    state,
586                                    preceding_siblings,
587                                    is_last_child,
588                                    is_last_of_type,
589                                    children,
590                                )
591                            } else {
592                                false
593                            };
594                            if matches_sub {
595                                any_matched = true;
596                                break;
597                            }
598                        }
599                        if !any_matched {
600                            return false;
601                        }
602                    } else if p.starts_with("has(") && p.ends_with(')') {
603                        let inner = &p[4..p.len() - 1];
604                        let mut any_matched = false;
605                        for sub in split_selector_list(inner) {
606                            let sub_trimmed = sub.trim();
607                            if let Some(child_sel_str) = sub_trimmed.strip_prefix('>') {
608                                let child_sel_str = child_sel_str.trim();
609                                if let Ok(child_sel) = Selector::parse(child_sel_str) {
610                                    for child in children {
611                                        if child_sel.matches_hierarchy_full(
612                                            child,
613                                            &[],
614                                            &[],
615                                            None,
616                                            None,
617                                            state,
618                                        ) {
619                                            any_matched = true;
620                                            break;
621                                        }
622                                    }
623                                } else if let Ok(comp) = CompoundSelector::parse(child_sel_str) {
624                                    for child in children {
625                                        if comp.matches_with_context(
626                                            child.tag,
627                                            child.classes,
628                                            child.id,
629                                            child.attributes,
630                                            state,
631                                            &[],
632                                            None,
633                                            None,
634                                            child.children,
635                                        ) {
636                                            any_matched = true;
637                                            break;
638                                        }
639                                    }
640                                }
641                            } else {
642                                // Descendant match across entire subtree
643                                if let Ok(desc_sel) = Selector::parse(sub_trimmed) {
644                                    fn check_desc(
645                                        node: &ElementRef,
646                                        sel: &Selector,
647                                        st: &PseudoState,
648                                    ) -> bool {
649                                        if sel.matches_hierarchy_full(
650                                            node,
651                                            &[],
652                                            &[],
653                                            None,
654                                            None,
655                                            st,
656                                        ) {
657                                            return true;
658                                        }
659                                        for ch in node.children {
660                                            if check_desc(ch, sel, st) {
661                                                return true;
662                                            }
663                                        }
664                                        false
665                                    }
666                                    for child in children {
667                                        if check_desc(child, &desc_sel, state) {
668                                            any_matched = true;
669                                            break;
670                                        }
671                                    }
672                                }
673                            }
674                            if any_matched {
675                                break;
676                            }
677                        }
678                        if !any_matched {
679                            return false;
680                        }
681                    } else if p.eq_ignore_ascii_case("empty") {
682                        let is_empty = children.is_empty()
683                            && attributes
684                                .iter()
685                                .any(|(k, v)| k == "data-empty" && v == "true");
686                        if !is_empty && !children.is_empty() {
687                            return false;
688                        }
689                    } else {
690                        return false;
691                    }
692                }
693            }
694        }
695        true
696    }
697
698    /// Returns true if this compound selector references `:hover`, `:active`, or `:focus`.
699    pub fn has_interactive_pseudo(&self) -> bool {
700        self.parts.iter().any(|p| match p {
701            SelectorPart::PseudoClass(name) => {
702                let n = name.trim().to_ascii_lowercase();
703                n == "hover"
704                    || n == "active"
705                    || n == "focus"
706                    || n.contains(":hover")
707                    || n.contains(":active")
708                    || n.contains(":focus")
709            }
710            _ => false,
711        })
712    }
713}
714
715/// Light-weight reference to a DOM element for hierarchical selector matching.
716#[derive(Debug, Clone, Copy)]
717pub struct ElementRef<'a> {
718    pub tag: &'a str,
719    pub classes: &'a [String],
720    pub id: Option<&'a str>,
721    pub attributes: &'a [(String, String)],
722    pub children: &'a [ElementRef<'a>],
723}
724
725impl<'a> ElementRef<'a> {
726    /// Constructs a basic ElementRef with no children.
727    pub const fn new(
728        tag: &'a str,
729        classes: &'a [String],
730        id: Option<&'a str>,
731        attributes: &'a [(String, String)],
732    ) -> Self {
733        Self {
734            tag,
735            classes,
736            id,
737            attributes,
738            children: &[],
739        }
740    }
741
742    /// Attaches child ElementRefs for :has() and structural evaluation.
743    pub const fn with_children(mut self, children: &'a [ElementRef<'a>]) -> Self {
744        self.children = children;
745        self
746    }
747}
748
749/// Parsed CSS selector with support for combinators and W3C specificity calculation.
750#[derive(Debug, Clone, PartialEq, Eq)]
751pub struct Selector {
752    pub raw: String,
753    /// Target compound selector (rightmost subject in CSS rule).
754    pub target: CompoundSelector,
755    /// Combinator steps from right to left (Combinator preceding the target, CompoundSelector of that element).
756    pub steps: Vec<(Combinator, CompoundSelector)>,
757    /// Simple parts of the target compound selector for backward compatibility.
758    pub parts: Vec<SelectorPart>,
759    /// Total W3C specificity for the entire selector chain.
760    pub specificity: Specificity,
761}
762
763/// Evaluates whether a 1-based index matches an `An+B` CSS formula per W3C Selectors Level 4.
764pub fn matches_an_plus_b(formula: &str, index: usize) -> bool {
765    let trimmed = formula.trim().to_ascii_lowercase();
766    if trimmed == "odd" {
767        return index % 2 == 1;
768    }
769    if trimmed == "even" {
770        return index.is_multiple_of(2);
771    }
772    if let Ok(exact) = trimmed.parse::<usize>() {
773        return index == exact;
774    }
775    let n_idx = match trimmed.find('n') {
776        Some(i) => i,
777        None => return false,
778    };
779    let a_str = trimmed[..n_idx].trim();
780    let a: i64 = match a_str {
781        "" | "+" => 1,
782        "-" => -1,
783        s => match s.parse::<i64>() {
784            Ok(v) => v,
785            Err(_) => return false,
786        },
787    };
788    let b: i64 = if n_idx + 1 < trimmed.len() {
789        let b_str = trimmed[n_idx + 1..].replace(' ', "");
790        b_str.parse::<i64>().unwrap_or(0)
791    } else {
792        0
793    };
794
795    let idx = index as i64;
796    if a == 0 {
797        idx == b
798    } else {
799        let diff = idx - b;
800        if a > 0 {
801            diff >= 0 && diff % a == 0
802        } else {
803            diff <= 0 && diff % a == 0
804        }
805    }
806}
807
808impl Selector {
809    /// Parses a complete CSS selector, including combinators (e.g. `div.card > ul + p.text[title]`).
810    pub fn parse(input: &str) -> Result<Self, String> {
811        let trimmed = input.trim();
812        if trimmed.is_empty() {
813            return Err("Empty selector".to_string());
814        }
815
816        // Tokenize selector into alternating compound selector strings and combinators
817        let mut segments: Vec<(Option<Combinator>, String)> = Vec::new();
818        let mut cur_buf = String::new();
819        let mut pending_combinator: Option<Combinator> = None;
820        let mut in_bracket = false;
821        let mut in_quote = None;
822        let mut paren_depth = 0;
823
824        let chars: Vec<char> = trimmed.chars().collect();
825        let mut i = 0;
826        while i < chars.len() {
827            let c = chars[i];
828            if in_bracket {
829                cur_buf.push(c);
830                if let Some(q) = in_quote {
831                    if c == q {
832                        in_quote = None;
833                    }
834                } else if c == '"' || c == '\'' {
835                    in_quote = Some(c);
836                } else if c == ']' {
837                    in_bracket = false;
838                }
839                i += 1;
840                continue;
841            }
842
843            if c == '[' {
844                in_bracket = true;
845                cur_buf.push(c);
846                i += 1;
847                continue;
848            }
849
850            if let Some(q) = in_quote {
851                cur_buf.push(c);
852                if c == q {
853                    in_quote = None;
854                }
855                i += 1;
856                continue;
857            } else if c == '"' || c == '\'' {
858                in_quote = Some(c);
859                cur_buf.push(c);
860                i += 1;
861                continue;
862            }
863
864            if c == '(' {
865                paren_depth += 1;
866                cur_buf.push(c);
867                i += 1;
868                continue;
869            }
870
871            if c == ')' {
872                if paren_depth > 0 {
873                    paren_depth -= 1;
874                }
875                cur_buf.push(c);
876                i += 1;
877                continue;
878            }
879
880            if paren_depth > 0 {
881                cur_buf.push(c);
882                i += 1;
883                continue;
884            }
885
886            if c == '>' || c == '+' || c == '~' {
887                let trimmed_buf = cur_buf.trim().to_string();
888                if !trimmed_buf.is_empty() {
889                    segments.push((pending_combinator.take(), trimmed_buf));
890                    cur_buf.clear();
891                }
892                let comb = match c {
893                    '>' => Combinator::Child,
894                    '+' => Combinator::AdjacentSibling,
895                    '~' => Combinator::SubsequentSibling,
896                    _ => unreachable!(),
897                };
898                pending_combinator = Some(comb);
899                i += 1;
900                continue;
901            }
902
903            if c.is_whitespace() {
904                let trimmed_buf = cur_buf.trim().to_string();
905                if !trimmed_buf.is_empty() {
906                    segments.push((pending_combinator.take(), trimmed_buf));
907                    cur_buf.clear();
908                    // Set default descendant combinator if no explicit combinator follows
909                    pending_combinator = Some(Combinator::Descendant);
910                }
911                i += 1;
912                continue;
913            }
914
915            cur_buf.push(c);
916            i += 1;
917        }
918
919        let trimmed_buf = cur_buf.trim().to_string();
920        if !trimmed_buf.is_empty() {
921            segments.push((pending_combinator.take(), trimmed_buf));
922        }
923
924        if segments.is_empty() {
925            return Err("Failed to extract selector segments".to_string());
926        }
927
928        // Parse each compound segment and accumulate specificity
929        let mut parsed_compounds: Vec<(Option<Combinator>, CompoundSelector)> = Vec::new();
930        let mut total_spec = Specificity::ZERO;
931
932        for (comb, seg_str) in segments {
933            let compound = CompoundSelector::parse(&seg_str)?;
934            total_spec += compound.specificity;
935            parsed_compounds.push((comb, compound));
936        }
937
938        // Rightmost segment is the target selector
939        let (mut pending_comb, target) = parsed_compounds.pop().unwrap();
940        let parts = target.parts.clone();
941
942        // Remaining segments in reverse order represent the right-to-left traversal steps
943        let mut steps = Vec::new();
944        while let Some((prev_comb, compound)) = parsed_compounds.pop() {
945            let comb = pending_comb.unwrap_or(Combinator::Descendant);
946            steps.push((comb, compound));
947            pending_comb = prev_comb;
948        }
949
950        Ok(Self {
951            raw: trimmed.to_string(),
952            target,
953            steps,
954            parts,
955            specificity: total_spec,
956        })
957    }
958
959    /// Returns true if this compound selector references `:hover`, `:active`, or `:focus` (including inside `:is`/`:where`).
960    pub fn has_interactive_pseudo(&self) -> bool {
961        self.parts.iter().any(|p| match p {
962            SelectorPart::PseudoClass(name) => {
963                let n = name.trim().to_ascii_lowercase();
964                n == "hover"
965                    || n == "active"
966                    || n == "focus"
967                    || n.contains(":hover")
968                    || n.contains(":active")
969                    || n.contains(":focus")
970            }
971            _ => false,
972        })
973    }
974
975    /// Returns true if this selector (either on the target or any ancestor/sibling combinator step)
976    /// depends on `:hover`, `:active`, or `:focus`.
977    pub fn has_any_interactive_pseudo(&self) -> bool {
978        self.target.has_interactive_pseudo()
979            || self
980                .steps
981                .iter()
982                .any(|(_, comp)| comp.has_interactive_pseudo())
983    }
984
985    /// Returns true if this selector (either on target or any ancestor/sibling step) uses `:hover`.
986    pub fn has_any_hover_pseudo(&self) -> bool {
987        let compound_has_hover = |comp: &CompoundSelector| {
988            comp.parts.iter().any(|p| match p {
989                SelectorPart::PseudoClass(name) => {
990                    let n = name.trim().to_ascii_lowercase();
991                    n == "hover" || n.contains(":hover")
992                }
993                _ => false,
994            })
995        };
996        compound_has_hover(&self.target) || self.steps.iter().any(|(_, c)| compound_has_hover(c))
997    }
998
999    /// Evaluates whether this selector matches an element without ancestors (simple matching).
1000    pub fn matches(
1001        &self,
1002        tag: &str,
1003        classes: &[&str],
1004        id: Option<&str>,
1005        state: &PseudoState,
1006    ) -> bool {
1007        self.target.matches(tag, classes, id, &[], state)
1008    }
1009
1010    /// Evaluates whether this selector matches an element given its full ancestor chain and preceding siblings.
1011    pub fn matches_hierarchy(
1012        &self,
1013        target: &ElementRef,
1014        ancestors: &[ElementRef],
1015        preceding_siblings: &[ElementRef],
1016        state: &PseudoState,
1017    ) -> bool {
1018        self.matches_hierarchy_full(target, ancestors, preceding_siblings, None, None, state)
1019    }
1020
1021    /// Evaluates whether this selector matches an element given full ancestor, sibling, and position context.
1022    pub fn matches_hierarchy_full(
1023        &self,
1024        target: &ElementRef,
1025        ancestors: &[ElementRef],
1026        preceding_siblings: &[ElementRef],
1027        is_last_child: Option<bool>,
1028        is_last_of_type: Option<bool>,
1029        state: &PseudoState,
1030    ) -> bool {
1031        self.matches_hierarchy_with_ancestor_states(
1032            target,
1033            ancestors,
1034            None,
1035            preceding_siblings,
1036            None,
1037            is_last_child,
1038            is_last_of_type,
1039            state,
1040        )
1041    }
1042
1043    /// Evaluates whether this selector matches an element using per-ancestor and per-sibling `PseudoState`s
1044    /// when provided (enabling descendant rules like `.resizer:hover .resizer-line` when the ancestor is hovered).
1045    #[allow(clippy::too_many_arguments)]
1046    pub fn matches_hierarchy_with_ancestor_states(
1047        &self,
1048        target: &ElementRef,
1049        ancestors: &[ElementRef],
1050        ancestor_states: Option<&[PseudoState]>,
1051        preceding_siblings: &[ElementRef],
1052        sibling_states: Option<&[PseudoState]>,
1053        is_last_child: Option<bool>,
1054        is_last_of_type: Option<bool>,
1055        state: &PseudoState,
1056    ) -> bool {
1057        // Step 1: Target element must match target compound selector
1058        if !self.target.matches_with_context(
1059            target.tag,
1060            target.classes,
1061            target.id,
1062            target.attributes,
1063            state,
1064            preceding_siblings,
1065            is_last_child,
1066            is_last_of_type,
1067            target.children,
1068        ) {
1069            return false;
1070        }
1071
1072        if self.steps.is_empty() {
1073            return true;
1074        }
1075
1076        // Step 2: Traverse right-to-left combinator chain
1077        let mut cur_ancestor_idx = ancestors.len();
1078        let mut cur_sibling_idx = preceding_siblings.len();
1079
1080        for (comb, compound) in &self.steps {
1081            match comb {
1082                Combinator::Child => {
1083                    if cur_ancestor_idx == 0 {
1084                        return false;
1085                    }
1086                    cur_ancestor_idx -= 1;
1087                    let parent = &ancestors[cur_ancestor_idx];
1088                    let parent_state = ancestor_states
1089                        .and_then(|s| s.get(cur_ancestor_idx))
1090                        .unwrap_or(state);
1091                    let _parent_preceding = if cur_ancestor_idx > 0 {
1092                        &ancestors[..cur_ancestor_idx]
1093                    } else {
1094                        &[]
1095                    };
1096                    if !compound.matches_with_context(
1097                        parent.tag,
1098                        parent.classes,
1099                        parent.id,
1100                        parent.attributes,
1101                        parent_state,
1102                        _parent_preceding,
1103                        None,
1104                        None,
1105                        parent.children,
1106                    ) {
1107                        return false;
1108                    }
1109                }
1110                Combinator::Descendant => {
1111                    let mut matched = false;
1112                    while cur_ancestor_idx > 0 {
1113                        cur_ancestor_idx -= 1;
1114                        let anc = &ancestors[cur_ancestor_idx];
1115                        let anc_state = ancestor_states
1116                            .and_then(|s| s.get(cur_ancestor_idx))
1117                            .unwrap_or(state);
1118                        if compound.matches_with_context(
1119                            anc.tag,
1120                            anc.classes,
1121                            anc.id,
1122                            anc.attributes,
1123                            anc_state,
1124                            &[],
1125                            None,
1126                            None,
1127                            anc.children,
1128                        ) {
1129                            matched = true;
1130                            break;
1131                        }
1132                    }
1133                    if !matched {
1134                        return false;
1135                    }
1136                }
1137                Combinator::AdjacentSibling => {
1138                    if cur_sibling_idx == 0 {
1139                        return false;
1140                    }
1141                    cur_sibling_idx -= 1;
1142                    let sib = &preceding_siblings[cur_sibling_idx];
1143                    let sib_state = sibling_states
1144                        .and_then(|s| s.get(cur_sibling_idx))
1145                        .unwrap_or(state);
1146                    let sib_preceding = &preceding_siblings[..cur_sibling_idx];
1147                    if !compound.matches_with_context(
1148                        sib.tag,
1149                        sib.classes,
1150                        sib.id,
1151                        sib.attributes,
1152                        sib_state,
1153                        sib_preceding,
1154                        None,
1155                        None,
1156                        sib.children,
1157                    ) {
1158                        return false;
1159                    }
1160                }
1161                Combinator::SubsequentSibling => {
1162                    let mut matched = false;
1163                    while cur_sibling_idx > 0 {
1164                        cur_sibling_idx -= 1;
1165                        let sib = &preceding_siblings[cur_sibling_idx];
1166                        let sib_state = sibling_states
1167                            .and_then(|s| s.get(cur_sibling_idx))
1168                            .unwrap_or(state);
1169                        let sib_preceding = &preceding_siblings[..cur_sibling_idx];
1170                        if compound.matches_with_context(
1171                            sib.tag,
1172                            sib.classes,
1173                            sib.id,
1174                            sib.attributes,
1175                            sib_state,
1176                            sib_preceding,
1177                            None,
1178                            None,
1179                            sib.children,
1180                        ) {
1181                            matched = true;
1182                            break;
1183                        }
1184                    }
1185                    if !matched {
1186                        return false;
1187                    }
1188                }
1189            }
1190        }
1191
1192        true
1193    }
1194}
1195
1196fn parse_attribute_selector<I: Iterator<Item = char>>(
1197    chars: &mut std::iter::Peekable<I>,
1198) -> Result<AttributeSelector, String> {
1199    let mut name = String::new();
1200    while let Some(&c) = chars.peek() {
1201        if c == ']' || c == '=' || c == '~' || c == '|' || c == '^' || c == '$' || c == '*' {
1202            break;
1203        }
1204        if !c.is_whitespace() {
1205            name.push(c);
1206        }
1207        chars.next();
1208    }
1209
1210    if name.is_empty() {
1211        return Err("Empty attribute name in '[...]' selector".to_string());
1212    }
1213
1214    let mut op_str = String::new();
1215    while let Some(&c) = chars.peek() {
1216        if c == '=' || c == '~' || c == '|' || c == '^' || c == '$' || c == '*' {
1217            op_str.push(c);
1218            chars.next();
1219        } else {
1220            break;
1221        }
1222    }
1223
1224    if op_str.is_empty() {
1225        // [attr]
1226        if chars.peek() == Some(&']') {
1227            chars.next();
1228        }
1229        return Ok(AttributeSelector {
1230            name,
1231            op: AttributeMatchOp::Exists,
1232        });
1233    }
1234
1235    // Skip whitespace before value
1236    while let Some(&c) = chars.peek() {
1237        if c.is_whitespace() {
1238            chars.next();
1239        } else {
1240            break;
1241        }
1242    }
1243
1244    // Read attribute value (handling optional single/double quotes)
1245    let mut val = String::new();
1246    let quote = if chars.peek() == Some(&'"') || chars.peek() == Some(&'\'') {
1247        Some(chars.next().unwrap())
1248    } else {
1249        None
1250    };
1251
1252    while let Some(&c) = chars.peek() {
1253        if let Some(q) = quote {
1254            if c == q {
1255                chars.next();
1256                break;
1257            }
1258            val.push(c);
1259            chars.next();
1260        } else {
1261            if c == ']' || c.is_whitespace() {
1262                break;
1263            }
1264            val.push(c);
1265            chars.next();
1266        }
1267    }
1268
1269    // Advance past closing ']'
1270    for c in chars.by_ref() {
1271        if c == ']' {
1272            break;
1273        }
1274    }
1275
1276    let op = match op_str.as_str() {
1277        "=" => AttributeMatchOp::Exact(val),
1278        "^=" => AttributeMatchOp::Prefix(val),
1279        "$=" => AttributeMatchOp::Suffix(val),
1280        "*=" => AttributeMatchOp::Substring(val),
1281        "~=" => AttributeMatchOp::Includes(val),
1282        "|=" => AttributeMatchOp::DashMatch(val),
1283        _ => return Err(format!("Unsupported attribute match operator '{}'", op_str)),
1284    };
1285
1286    Ok(AttributeSelector { name, op })
1287}
1288
1289fn parse_ident<I: Iterator<Item = char>>(chars: &mut std::iter::Peekable<I>) -> String {
1290    let mut s = String::new();
1291    while let Some(&c) = chars.peek() {
1292        if c.is_alphanumeric() || c == '-' || c == '_' {
1293            s.push(chars.next().unwrap());
1294        } else {
1295            break;
1296        }
1297    }
1298    s
1299}