htui 0.2.0

A terminal HTML/CSS renderer with an embedded JavaScript engine — build interactive TUIs from HTML, CSS and JS
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
use std::str::FromStr;

use super::values::Viewport;
use crate::tdom::node::{NodeId, NodeType};

/// Errors produced while parsing a CSS selector string.
#[derive(Debug, Clone, PartialEq, Eq, thiserror::Error)]
pub enum SelectorError {
    /// The selector string is empty.
    #[error("empty selector")]
    EmptySelector,
    /// A compound part (e.g. `.class`, `#id`) is empty.
    #[error("empty compound")]
    EmptyCompound,
    /// A class name after `.` is empty.
    #[error("invalid class")]
    InvalidClass,
    /// An id after `#` is empty.
    #[error("invalid id")]
    InvalidId,
    /// A bare tag name is empty.
    #[error("invalid tag")]
    InvalidTag,
    /// `:hover` was given arguments, which it does not take.
    #[error(":hover takes no arguments")]
    HoverTakesNoArguments,
    /// `:focus` was given arguments, which it does not take.
    #[error(":focus takes no arguments")]
    FocusTakesNoArguments,
    /// `:nth-child` is missing its `(...)` argument list.
    #[error(":nth-child requires `(...)`")]
    NthChildRequiresParens,
    /// `:nth-child(...)` is missing the closing `)`.
    #[error(":nth-child(...) missing ')'")]
    NthChildMissingCloseParen,
    /// The `:nth-child` argument is not a supported `an+b` form.
    #[error("invalid :nth-child arg: {0:?}")]
    InvalidNthChildArg(String),
    /// `:nth-last-child` is missing its `(...)` argument list.
    #[error(":nth-last-child requires `(...)`")]
    NthLastChildRequiresParens,
    /// `:nth-last-child(...)` is missing the closing `)`.
    #[error(":nth-last-child(...) missing ')'")]
    NthLastChildMissingCloseParen,
    /// The `:nth-last-child` argument is not a supported `an+b` form.
    #[error("invalid :nth-last-child arg: {0:?}")]
    InvalidNthLastChildArg(String),
    /// `:not` is missing its `(...)` argument list.
    #[error(":not requires `(...)`")]
    NotRequiresParens,
    /// `:not(...)` is missing the closing `)`.
    #[error(":not(...) missing ')'")]
    NotMissingCloseParen,
    /// `:not(...)` arguments nest deeper than the supported limit.
    #[error(":not(...) nesting too deep")]
    NotNestedTooDeep,
    /// The pseudo-class is not one of the supported set.
    #[error("unsupported pseudo-class: :{0}")]
    UnsupportedPseudoClass(String),
    /// The tag name does not map to any known `NodeType`.
    #[error("unsupported CSS tag: {0:?}")]
    UnsupportedTag(String),
    /// An attribute selector is malformed (unclosed bracket, missing value,
    /// or an unsupported operator).
    #[error("invalid attribute selector: [{0}]")]
    InvalidAttributeSelector(String),
    /// `:nth-of-type` / `:nth-last-of-type` is missing its `(...)` list.
    #[error(":{0} requires `(...)`")]
    NthOfTypeRequiresParens(String),
    /// `:nth-of-type(...)` / `:nth-last-of-type(...)` is missing the `)`.
    #[error(":{0}(...) missing ')'")]
    NthOfTypeMissingCloseParen(String),
    /// The `:nth-of-type` / `:nth-last-of-type` argument is not a supported
    /// `an+b` form.
    #[error("invalid :{0} arg: {1:?}")]
    InvalidNthOfTypeArg(String, String),
}

/// `an + b` expression used by the `:nth-child()` pseudo-class.
///
/// The selector matches an element when its 1-based index among its parent's
/// siblings equals `a*n + b` for some non-negative integer `n`. Supported
/// forms are `even`, `odd`, and bare integers like `:nth-child(2)`.
/// More complex forms (`-n+3`, `n+2` with implicit coefficient) are rejected
/// during parsing so we never silently mis-match.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub struct NthExpr {
    /// Step. `0` means the expression degenerates to "match only index `b`".
    pub a: usize,
    /// 1-based offset (matches indices `b`, `a + b`, `2a + b`, …).
    pub b: usize,
}

impl NthExpr {
    /// `2n` — every 2nd child starting at the 2nd.
    pub const EVEN: NthExpr = NthExpr { a: 2, b: 0 };
    /// `2n + 1` — every 2nd child starting at the 1st.
    pub const ODD: NthExpr = NthExpr { a: 2, b: 1 };

    /// Evaluate the expression against a 1-based sibling index.
    pub fn matches(self, index_1based: usize) -> bool {
        if self.a == 0 {
            return index_1based == self.b;
        }
        index_1based >= self.b && (index_1based - self.b).is_multiple_of(self.a)
    }
}

/// Session-level dynamic pseudo-class state (`:hover` / `:focus`).
///
/// One slot per dynamic pseudo-class, populated by whoever owns that piece of
/// interaction state (the script thread's pointer state machine fills
/// `hovered`; the input loop's focus state fills `focused`). The cascade and
/// the render thread treat it as a single value: adding a pseudo-class means
/// adding one field here, one `PseudoClass` variant and one method arm.
/// Session-level dynamic pseudo-class state (`:hover` / `:focus`) plus the
/// cascade environment.
///
/// One slot per dynamic pseudo-class, populated by whoever owns that piece of
/// interaction state (the script thread's pointer state machine fills
/// `hovered`; the input loop's focus state fills `focused`). The cascade and
/// the render thread treat it as a single value: adding a pseudo-class means
/// adding one field here, one `PseudoClass` variant and one method arm.
///
/// `viewport` carries the terminal cell grid for `@media` matching. The
/// default (`0x0`) matches no size condition — unconditional rules are
/// unaffected — so callers that never cascade a real viewport keep working.
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
pub struct DynamicState {
    /// The node currently under the pointer (`:hover` matches it and its
    /// ancestors).
    pub hovered: Option<NodeId>,
    /// The focused text field (`:focus` matches it exactly).
    pub focused: Option<NodeId>,
    /// Terminal viewport (columns × rows in cells) for `@media` conditions.
    pub viewport: Viewport,
}

/// The set of dynamic pseudo-classes a stylesheet actually uses, packed as a
/// bitmask so rule detection is a single parse-time pass and command
/// processing is an O(1) membership test.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct PseudoClassSet(u8);

impl PseudoClassSet {
    /// No dynamic pseudo-class rules.
    pub const EMPTY: Self = Self(0);
    /// `:hover` rules present.
    pub const HOVER: Self = Self(1 << 0);
    /// `:focus` rules present.
    pub const FOCUS: Self = Self(1 << 1);

    /// Whether `pseudo` is a member of the set.
    pub fn contains_pseudo(&self, pseudo: PseudoClass) -> bool {
        self.0 & pseudo.as_flag().0 != 0
    }

    /// Union of two sets.
    pub fn union(self, other: Self) -> Self {
        Self(self.0 | other.0)
    }

    /// The pseudo-classes appearing anywhere in a selector chain.
    pub fn from_selector(sel: &CssSelector) -> Self {
        let mut set = Self::EMPTY;
        for compound in &sel.compounds {
            for s in compound {
                if let Selector::PseudoClass(p) = s {
                    set = set.union(p.as_flag());
                }
            }
        }
        set
    }
}

/// Dynamic pseudo-classes supported by the selector parser.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub enum PseudoClass {
    /// `:hover` — matches while the pointer is over the element (or one of
    /// its descendants). Evaluated against the cascade's hovered node.
    Hover,
    /// `:focus` — matches the element that currently holds keyboard focus
    /// (the session's focused text field). Unlike `:hover`, it matches the
    /// focused element itself, not its ancestors (`:focus-within` would).
    Focus,
}

impl PseudoClass {
    /// The bit this pseudo-class maps to in [`PseudoClassSet`].
    pub fn as_flag(&self) -> PseudoClassSet {
        match self {
            PseudoClass::Hover => PseudoClassSet::HOVER,
            PseudoClass::Focus => PseudoClassSet::FOCUS,
        }
    }
}

/// CSS attribute selector comparison operator.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub enum AttributeOp {
    /// `[attr]` — the attribute is present (value ignored).
    Exists,
    /// `[attr="value"]` — exact match.
    Equals,
    /// `[attr~="value"]` — whitespace-separated word contains `value`.
    Includes,
    /// `[attr|="value"]` — equals `value` or starts with `value-`.
    DashMatch,
    /// `[attr^="value"]` — starts with `value`.
    PrefixMatch,
    /// `[attr$="value"]` — ends with `value`.
    SuffixMatch,
    /// `[attr*="value"]` — contains `value` as a substring.
    SubstringMatch,
}

/// A parsed CSS attribute selector (`[type="range"]`, `[disabled]`, …).
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
pub struct AttributeSelector {
    /// Lowercased attribute name (HTML attribute names are case-insensitive).
    pub name: String,
    /// Comparison operator.
    pub op: AttributeOp,
    /// The right-hand value (empty for `Exists`).
    pub value: String,
    /// `true` when the optional `i` flag is present (`[attr=val i]`).
    pub case_insensitive: bool,
}

impl AttributeSelector {
    /// Evaluate this attribute selector against an attribute lookup callback
    /// (decouples the selector from the arena's concrete map type).
    pub fn matches_lookup(&self, lookup: &dyn Fn(&str) -> Option<String>) -> bool {
        let Some(raw) = lookup(&self.name) else {
            return false;
        };
        let raw = raw.as_str();
        match self.op {
            AttributeOp::Exists => true,
            _ => {
                let val = self.value.as_str();
                let (raw, val) = if self.case_insensitive {
                    (raw.to_ascii_lowercase(), val.to_ascii_lowercase())
                } else {
                    (raw.to_string(), val.to_string())
                };
                match self.op {
                    AttributeOp::Equals => raw == val,
                    AttributeOp::Includes => {
                        !val.is_empty() && raw.split_whitespace().any(|w| w == val)
                    }
                    AttributeOp::DashMatch => raw == val || raw.starts_with(&format!("{val}-")),
                    AttributeOp::PrefixMatch => !val.is_empty() && raw.starts_with(&val),
                    AttributeOp::SuffixMatch => !val.is_empty() && raw.ends_with(&val),
                    AttributeOp::SubstringMatch => !val.is_empty() && raw.contains(&val),
                    AttributeOp::Exists => true,
                }
            }
        }
    }
}

/// One simple selector inside a compound: a type / id / class match, a
/// structural or dynamic pseudo-class, or an attribute test. Variants carry
/// their own match semantics; [`Selector::Universal`] through
/// [`Selector::Not`] are structural, the rest depend on element state.
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
pub enum Selector {
    /// `*` — the universal selector: matches any element (never text,
    /// comment or document nodes). Contributes nothing to specificity.
    Universal,
    Tag(NodeType),
    Class(String),
    Id(String),
    /// `:nth-child(<expr>)` — match when the element is the n-th child of its
    /// parent (counting all siblings, including text nodes, per CSS spec).
    NthChild(NthExpr),
    /// `:nth-last-child(<expr>)` — the `:nth-child` mirror counting from the
    /// end of the sibling list (the last child is index 1).
    NthLastChild(NthExpr),
    /// `:nth-of-type(<expr>)` — like `:nth-child` but counting only siblings
    /// of the same element type (same `NodeType`; text / comment siblings
    /// never count, matching the CSS "of its type" semantics).
    NthOfType(NthExpr),
    /// `:nth-last-of-type(<expr>)` — the `:nth-of-type` mirror counting
    /// same-type siblings from the end.
    NthLastOfType(NthExpr),
    /// `:root` — the document's root element (the child of the `Document`
    /// node, i.e. `<html>` in a parsed document).
    Root,
    /// `:empty` — an element with no children that affect emptiness: element
    /// children always do, text children do when their data is non-empty
    /// (whitespace counts), comments never do (CSS Selectors semantics).
    Empty,
    /// `:not(<compound list>)` — matches when **none** of the argument
    /// compound selectors match. Arguments are comma-separated compounds
    /// without combinators (the common L3/L4 subset).
    Not(Vec<CompoundSelector>),
    /// `:checked` — a checked `<input type=checkbox|radio>` (the `checked`
    /// attribute the engine toggles on click) or a `<option selected>`.
    Checked,
    /// `:enabled` — a form control that is not `:disabled`.
    Enabled,
    /// `:disabled` — a form control carrying the `disabled` attribute, or a
    /// descendant of a `<fieldset disabled>` (legend exemption not modelled).
    Disabled,
    /// `:lang(<tag>)` — the element (or its nearest ancestor with a `lang`
    /// attribute) declares a language whose primary tag matches (case-
    /// insensitive; `zh` matches `lang="zh-CN"`).
    Lang(String),
    /// A dynamic pseudo-class (currently `:hover`).
    PseudoClass(PseudoClass),
    /// An attribute selector (`[type="range"]`, `[disabled]`, …).
    Attribute(AttributeSelector),
}

/// The combinator between two adjacent compounds of a complex selector.
/// The engine is LTR-only, so `NextSibling` / `SubsequentSibling` match the
/// immediately preceding / any preceding element sibling respectively.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub enum Combinator {
    /// ` ` — any ancestor.
    Descendant,
    /// `>` — the direct parent.
    Child,
    /// `+` — the immediately preceding element sibling.
    NextSibling,
    /// `~` — any preceding element sibling.
    SubsequentSibling,
}

/// One compound selector: simple selectors that must all match the same
/// element (`div.card#main`), no combinators inside.
pub type CompoundSelector = Vec<Selector>;

/// A complex selector: compounds joined by combinators, read left to right
/// (`ancestor > child + next`). Matches when the last compound matches the
/// candidate and every combinator chain holds; specificity is the sum over
/// the compounds.
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
pub struct CssSelector {
    pub compounds: Vec<CompoundSelector>,
    pub combinators: Vec<Combinator>,
    /// A trailing `::before` / `::after` pseudo-element. The compounds match
    /// the origin element; the pseudo-element's declarations are stored
    /// key-prefixed by the cascade (`content::before` …) and turned into
    /// generated runs by the inline collector.
    pub pseudo_element: Option<PseudoElement>,
}

impl FromStr for CssSelector {
    type Err = SelectorError;
    fn from_str(s: &str) -> std::result::Result<Self, Self::Err> {
        let s = s.trim();
        if s.is_empty() {
            return Err(SelectorError::EmptySelector);
        }
        // Split the selector chain into segments and the combinator that
        // introduces each segment. Whitespace is a descendant combinator; `>`,
        // `+`, `~` are explicit combinators. Empty segments (e.g. from `>` at
        // the start) are dropped — they're a parse error handled by the empty
        // check at the bottom.
        let (segments, combinators) = split_by_combinators(s);
        if segments.is_empty() {
            return Err(SelectorError::EmptySelector);
        }
        // A trailing `::before` / `::after` pseudo-element (inside the last
        // segment) is lifted off the chain: the chain itself matches the
        // origin element and the pseudo-element rides along as a flag.
        // Only `::before` / `::after` are recognized, including their
        // single-colon CSS compatibility spellings; other `::` names remain
        // unsupported pseudo-class errors.
        let mut pseudo_element = None;
        let mut segments: Vec<String> = segments.iter().map(|s| s.to_string()).collect();
        if let Some(last) = segments.last_mut()
            && let Some((trimmed, element)) = strip_pseudo_element(last)
        {
            pseudo_element = Some(element);
            if trimmed.trim().is_empty() {
                // The pseudo-element was the entire segment — a bare
                // `::before` has no origin to match.
                return Err(SelectorError::UnsupportedPseudoClass(match element {
                    PseudoElement::Before => "::before".to_string(),
                    PseudoElement::After => "::after".to_string(),
                    PseudoElement::SliderThumb => "::slider-thumb".to_string(),
                    PseudoElement::SliderTrack => "::slider-track".to_string(),
                    PseudoElement::SliderProgress => "::slider-progress".to_string(),
                }));
            }
            *last = trimmed.trim().to_string();
        }
        let mut compounds = Vec::with_capacity(segments.len());
        for seg in &segments {
            // A segment is one compound selector whose parts all apply to the
            // same element. The split is parenthesis-aware so whitespace
            // inside a function argument (`:nth-child(2n + 1)`,
            // `:not(p, div)`) never splits the pseudo-class in half.
            let mut compound = CompoundSelector::new();
            for part in split_top_level_whitespace(seg) {
                compound.extend(parse_compound(part)?);
            }
            compounds.push(compound);
        }
        Ok(CssSelector {
            compounds,
            combinators,
            pseudo_element,
        })
    }
}

/// The pseudo-elements the engine recognises (CSS `::before` / `::after`
/// and the browser-standard slider sub-parts).
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub enum PseudoElement {
    Before,
    After,
    /// `::-webkit-slider-thumb` / `::-moz-range-thumb`.
    SliderThumb,
    /// `::-webkit-slider-runnable-track` / `::-moz-range-track`.
    SliderTrack,
    /// `::-moz-range-progress` (Firefox filled-track overlay).
    SliderProgress,
}

/// If `seg` ends with a `::before` / `::after` pseudo-element suffix, return
/// the segment with the suffix stripped plus the element kind.
fn strip_pseudo_element(seg: &str) -> Option<(String, PseudoElement)> {
    let lower = seg.to_ascii_lowercase();
    // Longest suffix first so `::-webkit-slider-runnable-track` wins over
    // shorter partial matches.
    for (suffix, element) in [
        (
            "::-webkit-slider-runnable-track",
            PseudoElement::SliderTrack,
        ),
        ("::-moz-range-progress", PseudoElement::SliderProgress),
        ("::-moz-range-track", PseudoElement::SliderTrack),
        ("::-webkit-slider-thumb", PseudoElement::SliderThumb),
        ("::-moz-range-thumb", PseudoElement::SliderThumb),
        ("::before", PseudoElement::Before),
        (":before", PseudoElement::Before),
        ("::after", PseudoElement::After),
        (":after", PseudoElement::After),
    ] {
        if let Some(stripped) = lower.strip_suffix(suffix) {
            return Some((seg[..stripped.len()].to_string(), element));
        }
    }
    None
}

impl CssSelector {
    /// CSS specificity `(a, b, c)` of the selector chain, computed by summing
    /// every compound part:
    ///
    /// - `a` — id selectors (`#id`);
    /// - `b` — class selectors, attribute selectors and pseudo-classes
    ///   (`.class`, `:hover`, `:nth-child(...)`);
    /// - `c` — type selectors (`div`, `p`, …).
    ///
    /// Combinators contribute nothing. Used by the cascade to order rules so
    /// the most specific rule wins for a property regardless of source order.
    pub fn specificity(&self) -> (u32, u32, u32) {
        let mut spec = (0u32, 0u32, 0u32);
        for compound in &self.compounds {
            let part = compound_specificity(compound);
            spec.0 += part.0;
            spec.1 += part.1;
            spec.2 += part.2;
        }
        spec
    }
}

/// Split a selector chain into segments and the combinator that introduces each
/// segment after the first.
///
/// `div p` → `(["div", "p"], [Descendant])`
/// `div > p` → `(["div", "p"], [Child])`
/// `div.foo` → `(["div.foo"], [])`
/// `div > p + span` → `(["div", "p", "span"], [Child, NextSibling])`
///
/// `(` and `[` open a balanced group; combinator chars inside a group
/// (e.g. the `+` in `:nth-child(3n+2)`) are kept as part of the segment
/// instead of being promoted to a sibling/child combinator.
fn split_by_combinators(s: &str) -> (Vec<&str>, Vec<Combinator>) {
    let mut segments: Vec<&str> = Vec::new();
    let mut combinators: Vec<Combinator> = Vec::new();
    let mut iter = s.char_indices().peekable();
    let mut start = 0;
    let mut depth: usize = 0;

    while let Some((i, ch)) = iter.next() {
        // Track parentheses / brackets so combinator chars inside an
        // argument list (`:nth-child(3n+2)`, `:not(a > b)`) stay put.
        match ch {
            '(' | '[' => {
                depth = depth.saturating_add(1);
                continue;
            }
            ')' | ']' => {
                depth = depth.saturating_sub(1);
                continue;
            }
            _ => {}
        }
        if depth > 0 {
            continue;
        }
        if !ch.is_whitespace() && !matches!(ch, '>' | '+' | '~') {
            continue;
        }
        let before = s[start..i].trim();
        if !before.is_empty() {
            segments.push(before);
        }
        // Skip whitespace surrounding the next segment, then look for an
        // explicit combinator char. An explicit `>`/`+`/`~` wins over a bare
        // whitespace (Descendant) combinator — so `div > p` is a single
        // `Child` combinator, not `Descendant + Child`.
        while let Some(&(_, next_ch)) = iter.peek() {
            if next_ch.is_whitespace() {
                iter.next();
            } else {
                break;
            }
        }
        let mut combinator = Combinator::Descendant;
        if let Some(&(_, next_ch)) = iter.peek() {
            combinator = match next_ch {
                '>' => {
                    iter.next();
                    Combinator::Child
                }
                '+' => {
                    iter.next();
                    Combinator::NextSibling
                }
                '~' => {
                    iter.next();
                    Combinator::SubsequentSibling
                }
                _ => Combinator::Descendant,
            };
            while let Some(&(_, next_ch)) = iter.peek() {
                if next_ch.is_whitespace() {
                    iter.next();
                } else {
                    break;
                }
            }
        }
        if iter.peek().is_some() {
            combinators.push(combinator);
        }
        start = iter.peek().map(|&(i, _)| i).unwrap_or(s.len());
    }

    let last = s[start..].trim();
    if !last.is_empty() {
        segments.push(last);
    }

    (segments, combinators)
}

fn parse_compound(s: &str) -> std::result::Result<CompoundSelector, SelectorError> {
    parse_compound_inner(s, 0)
}

/// Max supported `:not(...)` nesting depth. Real stylesheets never come close;
/// the cap stops pathological CSS from recursing the parser to stack
/// exhaustion.
const NOT_MAX_NESTING: usize = 8;

fn parse_compound_inner(
    s: &str,
    not_depth: usize,
) -> std::result::Result<CompoundSelector, SelectorError> {
    let s = s.trim();
    if s.is_empty() {
        return Err(SelectorError::EmptyCompound);
    }
    let mut out = Vec::new();
    let chars: Vec<char> = s.chars().collect();
    let mut i = 0usize;
    while i < chars.len() {
        match chars[i] {
            '.' => {
                i += 1;
                let start = i;
                while i < chars.len()
                    && chars[i] != '.'
                    && chars[i] != '#'
                    && chars[i] != ':'
                    && chars[i] != '['
                {
                    i += 1;
                }
                let name: String = chars[start..i].iter().collect();
                if name.is_empty() {
                    return Err(SelectorError::InvalidClass);
                }
                out.push(Selector::Class(name));
            }
            '#' => {
                i += 1;
                let start = i;
                while i < chars.len()
                    && chars[i] != '.'
                    && chars[i] != '#'
                    && chars[i] != ':'
                    && chars[i] != '['
                {
                    i += 1;
                }
                let name: String = chars[start..i].iter().collect();
                if name.is_empty() {
                    return Err(SelectorError::InvalidId);
                }
                out.push(Selector::Id(name));
            }
            ':' => {
                // Pseudo-class. Pull the identifier, expect `(...)` where the
                // pseudo-class takes arguments, and emit the corresponding
                // Selector variant.
                i += 1;
                let name_start = i;
                while i < chars.len()
                    && chars[i] != '('
                    && chars[i] != '.'
                    && chars[i] != '#'
                    && chars[i] != ':'
                    && chars[i] != '['
                {
                    i += 1;
                }
                let name: String = chars[name_start..i].iter().collect();
                match name.to_ascii_lowercase().as_str() {
                    "hover" => {
                        if i < chars.len() && chars[i] == '(' {
                            return Err(SelectorError::HoverTakesNoArguments);
                        }
                        out.push(Selector::PseudoClass(PseudoClass::Hover));
                    }
                    "focus" => {
                        if i < chars.len() && chars[i] == '(' {
                            return Err(SelectorError::FocusTakesNoArguments);
                        }
                        out.push(Selector::PseudoClass(PseudoClass::Focus));
                    }
                    "nth-child" | "nth-last-child" => {
                        let from_last = name.eq_ignore_ascii_case("nth-last-child");
                        if i >= chars.len() || chars[i] != '(' {
                            return Err(if from_last {
                                SelectorError::NthLastChildRequiresParens
                            } else {
                                SelectorError::NthChildRequiresParens
                            });
                        }
                        let Some(arg) = capture_balanced_arg(&chars, &mut i) else {
                            return Err(if from_last {
                                SelectorError::NthLastChildMissingCloseParen
                            } else {
                                SelectorError::NthChildMissingCloseParen
                            });
                        };
                        let expr = parse_nth_child_arg(&arg).ok_or_else(|| {
                            if from_last {
                                SelectorError::InvalidNthLastChildArg(arg.clone())
                            } else {
                                SelectorError::InvalidNthChildArg(arg.clone())
                            }
                        })?;
                        out.push(if from_last {
                            Selector::NthLastChild(expr)
                        } else {
                            Selector::NthChild(expr)
                        });
                    }
                    "nth-of-type" | "nth-last-of-type" => {
                        let lower_name = name.to_ascii_lowercase();
                        if i >= chars.len() || chars[i] != '(' {
                            return Err(SelectorError::NthOfTypeRequiresParens(lower_name));
                        }
                        let Some(arg) = capture_balanced_arg(&chars, &mut i) else {
                            return Err(SelectorError::NthOfTypeMissingCloseParen(lower_name));
                        };
                        let from_last = lower_name == "nth-last-of-type";
                        let expr = parse_nth_child_arg(&arg).ok_or_else(|| {
                            SelectorError::InvalidNthOfTypeArg(lower_name, arg.clone())
                        })?;
                        out.push(if from_last {
                            Selector::NthLastOfType(expr)
                        } else {
                            Selector::NthOfType(expr)
                        });
                    }
                    // `:first-child` / `:last-child` / `:only-child` are
                    // positional special cases of the nth machinery: they
                    // decompose into index-1-from-start / index-1-from-end
                    // expressions, so the matcher keeps one code path. The
                    // `*-of-type` forms do the same over the same-type index.
                    "first-child" => out.push(Selector::NthChild(FIRST_CHILD_EXPR)),
                    "last-child" => out.push(Selector::NthLastChild(FIRST_CHILD_EXPR)),
                    "only-child" => {
                        out.push(Selector::NthChild(FIRST_CHILD_EXPR));
                        out.push(Selector::NthLastChild(FIRST_CHILD_EXPR));
                    }
                    "first-of-type" => out.push(Selector::NthOfType(FIRST_CHILD_EXPR)),
                    "last-of-type" => out.push(Selector::NthLastOfType(FIRST_CHILD_EXPR)),
                    "only-of-type" => {
                        out.push(Selector::NthOfType(FIRST_CHILD_EXPR));
                        out.push(Selector::NthLastOfType(FIRST_CHILD_EXPR));
                    }
                    "root" => out.push(Selector::Root),
                    "empty" => out.push(Selector::Empty),
                    "checked" => out.push(Selector::Checked),
                    "enabled" => out.push(Selector::Enabled),
                    "disabled" => out.push(Selector::Disabled),
                    "lang" => {
                        if i >= chars.len() || chars[i] != '(' {
                            return Err(SelectorError::NthOfTypeRequiresParens("lang".to_string()));
                        }
                        let Some(arg) = capture_balanced_arg(&chars, &mut i) else {
                            return Err(SelectorError::NthOfTypeMissingCloseParen(
                                "lang".to_string(),
                            ));
                        };
                        let tag = arg.trim().to_ascii_lowercase();
                        if tag.is_empty() || tag.contains(char::is_whitespace) {
                            return Err(SelectorError::InvalidNthOfTypeArg(
                                "lang".to_string(),
                                arg.clone(),
                            ));
                        }
                        out.push(Selector::Lang(tag));
                    }
                    "not" => {
                        if i >= chars.len() || chars[i] != '(' {
                            return Err(SelectorError::NotRequiresParens);
                        }
                        let Some(arg) = capture_balanced_arg(&chars, &mut i) else {
                            return Err(SelectorError::NotMissingCloseParen);
                        };
                        if not_depth >= NOT_MAX_NESTING {
                            return Err(SelectorError::NotNestedTooDeep);
                        }
                        out.push(Selector::Not(parse_not_args(&arg, not_depth + 1)?));
                    }
                    _ => return Err(SelectorError::UnsupportedPseudoClass(name)),
                }
            }
            '[' => {
                // Attribute selector: capture the balanced `[...]` content and
                // parse `name`, `op`, `value`, and the optional `i` flag.
                let Some(inner) = capture_balanced_bracket(&chars, &mut i) else {
                    return Err(SelectorError::InvalidAttributeSelector(
                        chars.iter().collect(),
                    ));
                };
                out.push(Selector::Attribute(parse_attribute_selector(&inner)?));
            }
            _ => {
                let start = i;
                while i < chars.len()
                    && chars[i] != '.'
                    && chars[i] != '#'
                    && chars[i] != ':'
                    && chars[i] != '['
                {
                    i += 1;
                }
                let tag: String = chars[start..i].iter().collect();
                if tag.is_empty() {
                    return Err(SelectorError::InvalidTag);
                }
                if tag == "*" {
                    out.push(Selector::Universal);
                } else {
                    out.push(Selector::Tag(tag_str_to_node_type(&tag)?));
                }
            }
        }
    }
    Ok(out)
}

/// Parse the argument of `:nth-child(...)`.
///
/// Accepted `an+b` forms:
/// - `even`     → `2n`     (every 2nd starting at 2)
/// - `odd`      → `2n + 1` (every 2nd starting at 1)
/// - `<n>`      → bare integer, matches exactly that 1-based index
/// - `<a>n`     → e.g. `3n` matches the 3rd, 6th, 9th, …
/// - `<a>n+<b>` / `<a>n-<b>` → e.g. `2n+1` matches the 1st, 3rd, 5th, …
///
/// Returns `None` for unsupported forms (`-n+3`, `n+2` with implicit `1n`,
/// `n` alone, signed/zero coefficients, trailing junk) so the parser can
/// surface them as errors instead of silently mis-matching.
fn parse_nth_child_arg(s: &str) -> Option<NthExpr> {
    let s = s.trim();
    if s.is_empty() {
        return None;
    }
    let lower = s.to_ascii_lowercase();
    if lower == "even" {
        return Some(NthExpr::EVEN);
    }
    if lower == "odd" {
        return Some(NthExpr::ODD);
    }
    // Bare integer → fixed position.
    if let Ok(n) = s.parse::<usize>() {
        if n == 0 {
            return None;
        }
        return Some(NthExpr { a: 0, b: n });
    }
    // Otherwise expect `<a>n[+|-<b>]`. Reject sign on `a`, implicit `1n`,
    // signed offsets, and trailing whitespace/junk.
    let (coef_part, tail) = {
        let idx = lower.find('n')?;
        lower.split_at(idx)
    };

    let tail = &tail[1..]; // skip the 'n' itself
    let a: usize = if coef_part.is_empty() {
        return None; // bare `n` is not supported
    } else {
        coef_part.parse().ok()?
    };
    if a == 0 {
        return None;
    }
    let tail = tail.trim();
    if tail.is_empty() {
        return Some(NthExpr { a, b: 0 });
    }
    let (sign, num) = match tail.chars().next()? {
        '+' => (1i32, &tail[1..]),
        '-' => (-1i32, &tail[1..]),
        _ => return None,
    };
    let n: i32 = num.trim().parse().ok()?;
    if n == 0 {
        return None;
    }
    let b_signed = n * sign;
    if b_signed <= 0 {
        return None;
    }
    Some(NthExpr {
        a,
        b: b_signed as usize,
    })
}

/// Specificity of one compound selector (the per-compound slice of
/// [`CssSelector::specificity`]): ids in `a`, classes / pseudo-classes in
/// `b`, tags in `c`. Used by `:not(...)` which takes its most specific
/// argument's specificity.
fn compound_specificity(compound: &[Selector]) -> (u32, u32, u32) {
    let mut spec = (0u32, 0u32, 0u32);
    for sel in compound {
        match sel {
            Selector::Universal => {}
            Selector::Id(_) => spec.0 += 1,
            Selector::Class(_)
            | Selector::Attribute(_)
            | Selector::PseudoClass(_)
            | Selector::NthChild(_)
            | Selector::NthLastChild(_)
            | Selector::NthOfType(_)
            | Selector::NthLastOfType(_)
            | Selector::Root
            | Selector::Empty
            | Selector::Checked
            | Selector::Enabled
            | Selector::Disabled
            | Selector::Lang(_) => spec.1 += 1,
            Selector::Not(compounds) => {
                let arg = compounds
                    .iter()
                    .map(|c| compound_specificity(c))
                    .max()
                    .unwrap_or((0, 0, 0));
                spec.0 += arg.0;
                spec.1 += arg.1;
                spec.2 += arg.2;
            }
            Selector::Tag(_) => spec.2 += 1,
        }
    }
    spec
}

fn tag_str_to_node_type(tag: &str) -> std::result::Result<NodeType, SelectorError> {
    // Reverse lookup against the single tag table on [`NodeType`] — see
    // [`NodeType::from_tag_name`]. Keeps the selector mapping in sync with
    // the HTML parser and the DOM's `tag_name` by construction.
    NodeType::from_tag_name(tag).ok_or_else(|| SelectorError::UnsupportedTag(tag.to_string()))
}

/// `:first-child` / `:only-child` decompose to "index 1 from the start" —
/// the same `NthExpr` the nth machinery already evaluates.
const FIRST_CHILD_EXPR: NthExpr = NthExpr { a: 0, b: 1 };

/// Capture the balanced `(...)` argument whose `(` is at `chars[*i]`,
/// advancing `*i` past the closing `)`. Unlike the plain scan, nested
/// parentheses (e.g. the inner `:nth-child(2)` of `:not(:nth-child(2))`)
/// stay inside the argument. Returns `None` when the `)` never comes.
fn capture_balanced_arg(chars: &[char], i: &mut usize) -> Option<String> {
    let arg_start = *i + 1;
    let mut depth = 0usize;
    while *i < chars.len() {
        match chars[*i] {
            '(' => depth = depth.saturating_add(1),
            ')' => {
                depth = depth.saturating_sub(1);
                if depth == 0 {
                    let arg: String = chars[arg_start..*i].iter().collect();
                    *i += 1;
                    return Some(arg);
                }
            }
            _ => {}
        }
        *i += 1;
    }
    None
}

/// Parse the argument of `:not(...)`: a comma-separated list of compound
/// selectors without combinators (the common L3/L4 subset). Combinators
/// inside an argument fail with the argument's own parse error.
fn parse_not_args(
    arg: &str,
    not_depth: usize,
) -> std::result::Result<Vec<CompoundSelector>, SelectorError> {
    let parts = split_top_level_commas(arg);
    if parts.is_empty() {
        return Err(SelectorError::EmptyCompound);
    }
    parts
        .into_iter()
        .map(|part| parse_compound_inner(part, not_depth))
        .collect()
}

/// Split on whitespace that sits outside `(...)` / `[...]`, so the space
/// inside a function argument (`:nth-child(2n + 1)`) never splits the
/// pseudo-class in half.
fn split_top_level_whitespace(s: &str) -> Vec<&str> {
    split_top_level(s, char::is_whitespace)
        .into_iter()
        .filter(|p| !p.is_empty())
        .collect()
}

/// Split on top-level commas (outside `(...)` / `[...]`), trimming each part
/// and dropping empties: the `:not( p , div )` argument yields `["p", "div"]`.
fn split_top_level_commas(s: &str) -> Vec<&str> {
    split_top_level(s, |c| c == ',')
        .into_iter()
        .map(str::trim)
        .filter(|p| !p.is_empty())
        .collect()
}

/// Shared splitter for `split_top_level_whitespace` / `split_top_level_commas`:
/// cut at every `is_sep` character not enclosed in parentheses or brackets.
fn split_top_level(s: &str, is_sep: impl Fn(char) -> bool) -> Vec<&str> {
    let mut parts = Vec::new();
    let mut depth = 0usize;
    let mut start = 0usize;
    for (i, ch) in s.char_indices() {
        match ch {
            '(' | '[' => depth = depth.saturating_add(1),
            ')' | ']' => depth = depth.saturating_sub(1),
            c if depth == 0 && is_sep(c) => {
                parts.push(&s[start..i]);
                start = i + ch.len_utf8();
            }
            _ => {}
        }
    }
    parts.push(&s[start..]);
    parts
}

/// Capture the balanced `[...]` content starting at `chars[*i] == '['`,
/// advancing `*i` past the closing `]`. Returns `None` when the bracket is
/// never closed.
fn capture_balanced_bracket(chars: &[char], i: &mut usize) -> Option<String> {
    debug_assert_eq!(chars[*i], '[');
    let start = *i + 1;
    let mut depth = 0usize;
    while *i < chars.len() {
        match chars[*i] {
            '[' => depth += 1,
            ']' => {
                depth -= 1;
                if depth == 0 {
                    let inner: String = chars[start..*i].iter().collect();
                    *i += 1;
                    return Some(inner);
                }
            }
            _ => {}
        }
        *i += 1;
    }
    None
}

/// Parse the inner content of an attribute selector (`type="range"`,
/// `disabled`, `href^="https"` with optional trailing ` i` / `I` flag).
fn parse_attribute_selector(inner: &str) -> std::result::Result<AttributeSelector, SelectorError> {
    let inner = inner.trim();
    if inner.is_empty() {
        return Err(SelectorError::InvalidAttributeSelector(inner.to_string()));
    }

    // Detect and strip the trailing case-insensitive flag (` ... i` / ` I`).
    let mut case_insensitive = false;
    let mut body = inner;
    for flag in [" i", " I"] {
        if let Some(stripped) = body.strip_suffix(flag) {
            case_insensitive = true;
            body = stripped.trim_end();
            break;
        }
    }

    // Bare `[attr]` — existence check.
    if !body.contains('=') {
        let name = body.trim().to_ascii_lowercase();
        if name.is_empty() {
            return Err(SelectorError::InvalidAttributeSelector(inner.to_string()));
        }
        return Ok(AttributeSelector {
            name,
            op: AttributeOp::Exists,
            value: String::new(),
            case_insensitive,
        });
    }

    // Split at the first `~=` / `|=` / `^=` / `$=` / `*=` / `=` operator.
    // Scan for the operator character followed by `=`, breaking at the first
    // match so quoted values containing `=` are never split prematurely.
    let bytes = body.as_bytes();
    let mut op_start = None; // index just past the operator symbol
    let mut op = AttributeOp::Equals;
    let mut name_end = None; // index of the last char of the name
    for (idx, &b) in bytes.iter().enumerate() {
        if b != b'=' || idx == 0 {
            continue;
        }
        match bytes[idx - 1] {
            b'~' => {
                op = AttributeOp::Includes;
                name_end = Some(idx - 1);
                op_start = Some(idx + 1);
            }
            b'|' => {
                op = AttributeOp::DashMatch;
                name_end = Some(idx - 1);
                op_start = Some(idx + 1);
            }
            b'^' => {
                op = AttributeOp::PrefixMatch;
                name_end = Some(idx - 1);
                op_start = Some(idx + 1);
            }
            b'$' => {
                op = AttributeOp::SuffixMatch;
                name_end = Some(idx - 1);
                op_start = Some(idx + 1);
            }
            b'*' => {
                op = AttributeOp::SubstringMatch;
                name_end = Some(idx - 1);
                op_start = Some(idx + 1);
            }
            _ => {
                op = AttributeOp::Equals;
                name_end = Some(idx);
                op_start = Some(idx + 1);
            }
        }
        break;
    }
    let (Some(name_end), Some(op_start)) = (name_end, op_start) else {
        return Err(SelectorError::InvalidAttributeSelector(inner.to_string()));
    };
    let name = body[..name_end].trim().to_ascii_lowercase();
    if name.is_empty() {
        return Err(SelectorError::InvalidAttributeSelector(inner.to_string()));
    }
    let mut value = body[op_start..].trim();
    // Strip matching quotes (single or double).
    if value.len() >= 2
        && ((value.starts_with('"') && value.ends_with('"'))
            || (value.starts_with('\'') && value.ends_with('\'')))
    {
        value = &value[1..value.len() - 1];
    }
    Ok(AttributeSelector {
        name,
        op,
        value: value.to_string(),
        case_insensitive,
    })
}