use parsec::css::{MatchOptions, MatchTimeout, ParseOptions, SelectorList};
use parsec::{AttrNs, Document, Kind, NodeId, Ns, parse};
const PAGE: &str = r#"<!DOCTYPE html><html><head><title>Shop</title></head><body>
<div id="main" class="Wide page">
<h1>Books</h1>
<ul>
<li class="item first" data-id="17"><a href="/p/1" title="Book A, B">A</a></li>
<li class="item sold" data-id="27"><a href="/p/2">B</a><span class="price">£2</span></li>
<li class="item" data-id="30"><a href="https://x.example/p/3" hreflang="en-GB">C</a></li>
<li class="item last"><p></p><p> </p><p><!--c--></p></li>
</ul>
<form><fieldset disabled><legend><input name="in-legend"></legend><input name="off"></fieldset>
<input type="checkbox" checked name="box"><input type="TEXT" required readonly name="ro">
<select><optgroup disabled><option>x</option></optgroup><option selected>y</option></select>
<textarea placeholder="say"></textarea><input placeholder="p" value="v">
</form>
<svg viewBox="0 0 1 1"><clipPath id="cp"></clipPath><rect/></svg>
</div></body></html>"#;
fn names(doc: &Document, nodes: &[NodeId]) -> Vec<String> {
nodes
.iter()
.map(|&n| {
let Kind::Element { name, .. } = doc.kind(n) else {
unreachable!()
};
let id = doc
.attrs(n)
.find(|(_, a, _)| *a == "id" || *a == "name" || *a == "data-id")
.map(|(_, _, v)| format!("#{v}"))
.unwrap_or_default();
format!("{name}{id}")
})
.collect()
}
fn select(html: &str, css: &str) -> Vec<String> {
let doc = parse(html, false);
let list = SelectorList::parse(css).unwrap_or_else(|e| panic!("{css}: {e}"));
names(&doc, &list.select(&doc, doc.root()))
}
fn page(css: &str) -> Vec<String> {
select(PAGE, css)
}
#[test]
fn simple_selectors_and_combinators() {
assert_eq!(page("h1"), ["h1"]);
assert_eq!(page("li.item.sold"), ["li#27"]);
assert_eq!(page("#main > h1"), ["h1"]);
assert_eq!(page("ul a"), ["a", "a", "a"]);
assert_eq!(page("li.first + li"), ["li#27"]);
assert_eq!(page("li.first ~ li"), ["li#27", "li#30", "li"]);
assert_eq!(page("*").len(), page("html, html *").len());
assert_eq!(page("h1, #main > h1, h1:not(p)"), ["h1"]);
assert_eq!(page(r"#a\:b, .w-1\/2, #\39 lives"), Vec::<String>::new());
}
#[test]
fn attribute_selectors() {
assert_eq!(page("[data-id]"), ["li#17", "li#27", "li#30"]);
assert_eq!(page("a[href^='/']"), ["a", "a"]);
assert_eq!(page("[data-id$='7']"), ["li#17", "li#27"]);
assert_eq!(page("a[href*='/p/']").len(), 3);
assert_eq!(page("[class~=sold]"), ["li#27"]);
assert_eq!(page("[class~='']"), Vec::<String>::new());
assert_eq!(page("[hreflang|=en]"), ["a"]);
assert_eq!(page("a[title='Book A, B']"), ["a"]);
assert_eq!(page("[data-id=\"17\"]"), ["li#17"]);
assert_eq!(page("[class='ITEM FIRST' i]"), ["li#17"]);
assert_eq!(page("[href^='']"), Vec::<String>::new());
}
#[test]
fn html_lists_attributes_whose_values_ignore_case() {
assert_eq!(page("input[type=text]"), ["input#ro"]);
assert_eq!(page("input[type=text s]"), Vec::<String>::new());
assert_eq!(page("[data-id='17' s]"), ["li#17"]);
}
#[test]
fn ids_and_classes_compare_exactly_unless_quirks() {
assert_eq!(page(".wide"), Vec::<String>::new());
assert_eq!(page(".Wide"), ["div#main"]);
let quirky = "<div id=X class=Y></div>";
assert_eq!(select(quirky, "#x"), ["div#X"]);
assert_eq!(select(quirky, ".y"), ["div#X"]);
assert_eq!(
select(&format!("<!DOCTYPE html>{quirky}"), "#x"),
Vec::<String>::new()
);
}
#[test]
fn type_selectors_ignore_case_for_html_only() {
assert_eq!(page("H1"), ["h1"]);
assert_eq!(page("clipPath"), ["clipPath#cp"]);
assert_eq!(page("clippath"), Vec::<String>::new());
assert_eq!(page("[viewBox]"), ["svg"]);
assert_eq!(page("[viewbox]"), Vec::<String>::new());
assert_eq!(page("*|rect"), ["rect"]);
assert_eq!(page("|rect, |*"), Vec::<String>::new());
}
#[test]
fn plain_attribute_names_mean_no_namespace() {
let svg = "<svg><use xlink:href=#a></use><a href=b></a></svg>";
assert_eq!(select(svg, "[href]"), ["a"]);
assert_eq!(select(svg, "[*|href]"), ["use", "a"]);
}
#[test]
fn declared_namespace_prefixes() {
let html = r#"<a id=1></a><svg><a id=2 href=x></a><title id=3></title></svg>
<math><mi id=4></mi></math>"#;
let doc = parse(html, false);
let root = doc.root();
let with = |css: &str, opts: &ParseOptions| {
let list = SelectorList::parse_with(css, opts).unwrap();
names(&doc, &list.select(&doc, root))
};
let ns = [("s", Ns::Svg), ("m", Ns::MathMl), ("h", Ns::Html)];
let prefixes = ParseOptions {
namespaces: &ns,
..ParseOptions::default()
};
assert_eq!(with("s|a", &prefixes), ["a#2"]);
assert_eq!(with("h|a", &prefixes), ["a#1"]);
assert_eq!(with("s|*", &prefixes), ["svg", "a#2", "title#3"]);
assert_eq!(with("m|*:not(math)", &prefixes), ["mi#4"]);
assert_eq!(with("svg > s|title, *|mi", &prefixes), ["title#3", "mi#4"]);
assert_eq!(with("[s|href]", &prefixes), Vec::<String>::new());
assert_eq!(with("[*|href]", &prefixes), ["a#2"]);
let spec = |css| {
SelectorList::parse_with(css, &prefixes)
.unwrap()
.specificity()
};
assert_eq!(spec("s|a"), (0, 0, 1));
assert_eq!(spec("s|*"), (0, 0, 0));
assert!(SelectorList::parse_with("S|a", &prefixes).is_err());
assert!(SelectorList::parse("s|a").is_err());
assert!(SelectorList::parse("[s|href]").is_err());
let svg = ParseOptions {
namespaces: &ns,
default: Some(Ns::Svg),
..ParseOptions::default()
};
assert_eq!(with("a", &svg), ["a#2"]);
assert_eq!(with("[id]", &svg), ["a#2", "title#3"]);
assert_eq!(with("h|a, *|mi", &svg), ["a#1", "mi#4"]);
assert_eq!(with("svg *:not([href])", &svg), ["title#3"]);
assert_eq!(with("*|*:not(a)[id]", &svg), ["a#1", "title#3", "mi#4"]);
assert_eq!(
with("*|*:not([href])[id]", &svg),
["a#1", "title#3", "mi#4"]
);
let xml = [("x", Ns::Xml)];
let refused = ParseOptions {
namespaces: &xml,
..ParseOptions::default()
};
assert!(SelectorList::parse_with("x|a", &refused).is_err());
let col = [("col", Ns::Html)];
let col = ParseOptions {
namespaces: &col,
..ParseOptions::default()
};
let spec = |css| SelectorList::parse_with(css, &col).unwrap().specificity();
assert_eq!(spec("col|td"), (0, 0, 1));
assert_eq!(spec("col||td"), (0, 0, 2));
}
#[test]
fn table_columns() {
let html = r#"<table>
<colgroup><col id=c1><col id=c2 span=2></colgroup><colgroup span=2></colgroup>
<tr><td id=a><td id=b colspan=2><td id=c rowspan=2><td id=d><table><tr><td id=n></table>
<tr><th id=e rowspan=0><td id=f><td id=g><td id=h>
<tr><td id=i>
</table>"#;
assert_eq!(select(html, "#c1 || td"), ["td#a"]);
assert_eq!(select(html, "#c1 || th"), ["th#e"]);
assert_eq!(select(html, "#c2 || *"), ["td#b", "td#f", "td#g", "td#i"]);
assert_eq!(
select(html, "col||td"),
["td#a", "td#b", "td#f", "td#g", "td#i"]
);
assert_eq!(select(html, "col:has(|| #f)"), ["col#c2"]);
assert_eq!(select(html, ":nth-col(1)"), ["td#a", "td#n", "th#e"]);
assert_eq!(select(html, ":nth-col(2)"), ["td#b", "td#f", "td#i"]);
assert_eq!(select(html, ":nth-col(4)"), ["td#c"]);
assert_eq!(select(html, ":nth-last-col(1)"), ["td#d", "td#n", "td#h"]);
assert_eq!(
select(html, ":nth-col(n+6), col:nth-col(1)"),
Vec::<String>::new()
);
let clash = "<table><tr><td id=p><td id=q rowspan=3>\
<tr><td id=r colspan=2><td id=s><tr><td id=t><td id=u></table>";
assert_eq!(select(clash, ":nth-col(2)"), ["td#q", "td#r"]);
assert_eq!(select(clash, ":nth-col(3)"), ["td#s", "td#u"]);
let four = "<table><col id=x><col id=y><col id=z><col id=w>\
<tr><td id=a><td id=b><td id=c><td id=d>\
<tr><td id=e colspan=2></table>";
assert_eq!(select(four, "#y || td"), ["td#b", "td#e"]);
assert_eq!(select(four, "#x || td ~ td"), ["td#b", "td#c", "td#d"]);
assert_eq!(select(four, "#y || td + td"), ["td#c"]);
assert_eq!(select(html, "|td"), Vec::<String>::new());
assert!(SelectorList::parse("col|td").is_err());
assert_eq!(
SelectorList::parse("col || td:nth-col(2)")
.unwrap()
.specificity(),
(0, 1, 2)
);
}
#[test]
fn hostile_tables_lay_out_in_linear_time() {
let wide = format!(
"<table><tr>{}{}</table>",
"<td colspan=1000>".repeat(1_000),
"<tr><td>".repeat(50_000)
);
let mega = format!("<table><tr>{}</table>", "<td colspan=1000>".repeat(55_000));
let cols = format!(
"<table><colgroup>{}</colgroup><tr>{}</table>",
"<col>".repeat(30_000),
"<td>".repeat(30_000)
);
let stack = format!(
"<table><tr>{}{}</table>",
(0..20_000)
.map(|i| format!("<td rowspan={}>", 60_000 - i))
.collect::<String>(),
"<tr><td>".repeat(50_000)
);
for (html, css, n) in [
(&wide, ":nth-col(1)", 50_001),
(&mega, ":nth-last-col(1)", 1),
(&cols, "col || td", 30_000),
(&stack, ":nth-col(20001)", 40_000),
] {
let doc = parse(html, false);
let list = SelectorList::parse(css).unwrap();
let started = std::time::Instant::now();
assert_eq!(list.select(&doc, doc.root()).len(), n, "{css}");
let took = started.elapsed();
assert!(
took < std::time::Duration::from_secs(3),
"{css} took {took:?}"
);
}
}
#[test]
fn declared_attribute_namespace_prefixes() {
let html = r##"<svg><use id=1 xlink:href="#a"></use><a id=2 href="#a"></a>
<text id=3 xml:lang=fr></text></svg><p id=4 xml:lang=en></p>"##;
let doc = parse(html, false);
let attrs = [
("xl", AttrNs::XLink),
("xml", AttrNs::Xml),
("s", AttrNs::XLink),
];
let elements = [("s", Ns::Svg)];
let opts = ParseOptions {
namespaces: &elements,
attr_namespaces: &attrs,
..ParseOptions::default()
};
let with = |css: &str| {
let list = SelectorList::parse_with(css, &opts).unwrap();
names(&doc, &list.select(&doc, doc.root()))
};
assert_eq!(with("[xl|href]"), ["use#1"]);
assert_eq!(with("[xl|href='#a'], [href^='#']"), ["use#1", "a#2"]);
assert_eq!(with("[xml|lang]"), ["text#3"]);
assert_eq!(with("[xml|lang|=fr]"), ["text#3"]);
assert_eq!(with("p[xml\\:lang]"), ["p#4"]);
assert_eq!(with("s|use[s|href]"), ["use#1"]);
assert!(SelectorList::parse_with("[xlink|href]", &opts).is_err());
let host = [("h", AttrNs::Host(0))];
let refused = ParseOptions {
attr_namespaces: &host,
..ParseOptions::default()
};
assert!(SelectorList::parse_with("[h|x]", &refused).is_err());
}
#[test]
fn child_index_pseudo_classes() {
assert_eq!(page("li:nth-child(2)"), ["li#27"]);
assert_eq!(page("li:nth-child(odd)"), ["li#17", "li#30"]);
assert_eq!(page("li:nth-child(2n + 2)"), ["li#27", "li"]);
assert_eq!(page("li:nth-child(-n+2)"), ["li#17", "li#27"]);
assert_eq!(page("li:nth-last-child(1)"), ["li"]);
assert_eq!(page("li:nth-child(2 of .item:not(.sold))"), ["li#30"]);
assert_eq!(page("li:first-child"), ["li#17"]);
assert_eq!(page("li:last-child"), ["li"]);
assert_eq!(page("p:nth-of-type(2)"), ["p"]);
assert_eq!(page("p:last-of-type"), ["p"]);
assert_eq!(page("h1:only-of-type, title:only-child"), ["title", "h1"]);
assert_eq!(page("li:nth-child(0)"), Vec::<String>::new());
}
#[test]
fn stepped_child_index_counts_mixed_siblings() {
let html = "<div><p id=1></p>text<span id=2></span><!-- c --><p id=3></p>\
<b id=4></b><p id=5></p><span id=6></span></div>\
<svg><g id=7></g><rect id=8></rect><g id=9></g></svg>";
assert_eq!(
select(html, "div > :nth-child(2n+1)"),
["p#1", "p#3", "p#5"]
);
assert_eq!(
select(html, "div > :nth-last-child(2n+1)"),
["span#2", "b#4", "span#6"]
);
assert_eq!(
select(html, "div > :nth-of-type(2n+1)"),
["p#1", "span#2", "b#4", "p#5"]
);
assert_eq!(
select(html, "div > :nth-last-of-type(n+2)"),
["p#1", "span#2", "p#3"]
);
assert_eq!(select(html, "svg > :nth-of-type(2n+1)"), ["g#7", "rect#8"]);
assert_eq!(select(html, "svg > :nth-last-child(2n+1)"), ["g#7", "g#9"]);
assert_eq!(
select(html, ":is(p:nth-child(2n+1), p:nth-child(2n+1))"),
["p#1", "p#3", "p#5"]
);
}
#[test]
fn logical_pseudo_classes() {
assert_eq!(page(":is(h1, li.sold)"), ["h1", "li#27"]);
assert_eq!(page(":where(h1)"), ["h1"]);
assert_eq!(page(":is(h1, ::nonsense, )"), ["h1"]);
assert_eq!(page("li:not(.sold):not(.last)"), ["li#17", "li#30"]);
assert_eq!(page("li:has(.price)"), ["li#27"]);
assert_eq!(page("li:has(> a[href^=http])"), ["li#30"]);
assert_eq!(page("li:has(+ li.sold)"), ["li#17"]);
assert_eq!(page("li:has(~ .last)").len(), 3);
assert_eq!(page("ul:has(p:empty)"), ["ul"]);
}
#[test]
fn state_and_structure_pseudo_classes() {
assert_eq!(page(":root"), ["html"]);
assert_eq!(page("p:empty").len(), 2);
assert_eq!(page("a:any-link, a:link").len(), 3);
assert_eq!(page(":checked"), ["input#box", "option"]);
assert_eq!(page("input:disabled"), ["input#off"]);
assert_eq!(page("option:disabled"), ["option"]);
assert_eq!(page("fieldset:disabled"), ["fieldset"]);
assert_eq!(page("input:enabled").len(), 4);
assert_eq!(page(":required"), ["input#ro"]);
assert_eq!(
page("input:read-only"),
["input#off", "input#box", "input#ro"]
);
assert_eq!(page(":placeholder-shown"), ["textarea"]);
assert_eq!(page("a:hover, a:focus, a:visited"), Vec::<String>::new());
}
#[test]
fn blank() {
let html = r#"<input id=1><input id=2 value=""><input id=3 value=x>
<input id=4 type=SEARCH><input id=5 type=number value=7>
<input id=6 type=bogus><input id=7 type=checkbox><input id=8 type=hidden>
<textarea id=9></textarea><textarea id=10> </textarea>
<p id=11></p><svg><input id=12/></svg>"#;
assert_eq!(
select(html, ":blank"),
["input#1", "input#2", "input#4", "input#6", "textarea#9"]
);
}
#[test]
fn defined() {
let html = r#"<p id=1></p><my-card id=2></my-card><x-é id=3></x-é>
<font-face id=4></font-face><button id=5 is=x-fancy></button>
<svg><my-icon id=6></my-icon></svg><a-1 id=7></a-1><notcustom id=8></notcustom>"#;
assert_eq!(
select(html, ":not(:defined)"),
["my-card#2", "x-é#3", "button#5", "a-1#7"]
);
assert!(select(html, ":defined").contains(&"font-face#4".to_string()));
assert!(select(html, ":defined").contains(&"my-icon#6".to_string()));
}
#[test]
fn scope_is_the_element_a_query_runs_from() {
let doc = parse(PAGE, false);
let ul = SelectorList::parse("ul").unwrap().select(&doc, doc.root())[0];
let direct = SelectorList::parse(":scope > li.sold").unwrap();
assert_eq!(names(&doc, &direct.select(&doc, ul)), ["li#27"]);
let past = SelectorList::parse("div li.sold").unwrap();
assert_eq!(names(&doc, &past.select(&doc, ul)), ["li#27"]);
assert!(
SelectorList::parse("ul")
.unwrap()
.select(&doc, ul)
.is_empty()
);
}
#[test]
fn bad_selectors_are_errors() {
for bad in [
"",
" ",
"div[",
"p >",
"##x",
"!!",
"a,",
", a",
"a,,b",
"a::nope",
"a::text",
"a::attr(href)",
"a::before.x",
"a::before#x",
"a::part()",
"a::slotted()",
"svg|rect",
"[xlink|href]",
":nth-child(x)",
":nth-of-type(2 of p)",
":not()",
":has()",
":nope",
":lexbor-contains('x')",
"[a=b c]",
"[a!=b]",
] {
assert!(SelectorList::parse(bad).is_err(), "{bad:?} parsed");
}
}
#[test]
fn heading_is_an_h1_to_h6_of_a_listed_level() {
let html = r#"<h1 id="a"></h1><h2 id="b" aria-level="3"></h2><h6 id="f"></h6><h7 id="g"></h7>
<p id="p" role="heading" aria-level="1"></p>"#;
assert_eq!(select(html, ":heading"), ["h1#a", "h2#b", "h6#f"]);
assert_eq!(select(html, ":heading(2, 7)"), ["h2#b"]);
assert_eq!(select(html, ":heading( +6 , 0)"), ["h6#f"]);
assert_eq!(
select(html, ":heading(0), :heading(-1), :heading(99999)"),
Vec::<String>::new()
);
for bad in [
":heading()",
":heading(1.0)",
":heading(n)",
":heading(odd)",
":heading(2n+1)",
":heading(2n, 3n)",
":heading(1,)",
] {
assert!(SelectorList::parse(bad).is_err(), "{bad:?} parsed");
}
}
#[test]
fn pseudo_elements_are_valid_and_match_nothing() {
for css in [
"li::before",
"p::first-line",
"a:after",
"a:FIRST-LETTER",
"::marker",
"::placeholder, ::selection",
"::part(label icon)",
"::slotted(span.x)",
"::highlight(found)",
"li::before:hover",
":is(li)::after",
"::part(x):is(:hover)",
"::part(x)::before",
"::slotted(li)::before",
":is(::before)",
] {
assert_eq!(page(css), Vec::<String>::new(), "{css}");
}
for bad in [
"li::before > a",
"::part(x) + ::part(y)",
":not(::before)",
"::slotted(::before)",
"::part(x):has(li)",
"::before:first-child",
"li:after:empty",
"::slotted(li):hover",
"::slotted(li):lang(en)",
] {
assert!(SelectorList::parse(bad).is_err(), "{bad:?} parsed");
}
assert_eq!(page("li::before, li.first"), ["li#17"]);
let list = SelectorList::parse("li::before").unwrap();
assert_eq!(list.specificity(), (0, 0, 2));
}
#[test]
fn the_end_of_the_input_closes_open_brackets() {
assert_eq!(page("li[data-id"), ["li#17", "li#27", "li#30"]);
assert_eq!(page("[data-id=\"17\""), ["li#17"]);
assert_eq!(page("[data-id=\"17"), ["li#17"]);
assert_eq!(page("li:not(.item"), Vec::<String>::new());
assert_eq!(page("li:not([class"), Vec::<String>::new());
assert_eq!(page("ul > li:nth-child(2n+1"), ["li#17", "li#30"]);
assert_eq!(page(":is(#, li.first"), ["li#17"]);
assert!(SelectorList::parse("li[data-id=").is_err());
assert!(SelectorList::parse("li:nth-child(").is_err());
assert!(SelectorList::parse(":is(# %=[x)").is_err());
assert!(SelectorList::parse(":where(.a, #(x").is_err());
}
#[test]
fn deeply_nested_selectors_are_errors_not_crashes() {
let result = std::thread::Builder::new()
.stack_size(512 * 1024)
.spawn(|| {
let not = format!("{}a{}", ":not(".repeat(20_000), ")".repeat(20_000));
let is = format!("{}a{}", ":is(".repeat(5_000), ")".repeat(5_000));
{
let _ = SelectorList::parse(&is);
(SelectorList::parse(¬).is_err(), true)
}
})
.unwrap()
.join()
.unwrap();
assert_eq!(result, (true, true));
let ok = format!("{}a{}", ":not(".repeat(20), ")".repeat(20));
assert!(SelectorList::parse(&ok).is_ok());
}
#[test]
fn long_chains_match_on_a_small_stack() {
std::thread::Builder::new()
.stack_size(2 << 20)
.spawn(|| {
let doc = parse(&("<div>".repeat(20_000) + "<b></b>"), false);
let b = SelectorList::parse("b").unwrap().select(&doc, 0)[0];
let div = SelectorList::parse("div").unwrap().select(&doc, 0)[1000];
let long = SelectorList::parse(&("div ".repeat(20_000) + "b")).unwrap();
assert!(long.matches(&doc, b, None));
let longer = SelectorList::parse(&("div ".repeat(100_000) + "b")).unwrap();
assert!(!longer.matches(&doc, b, None));
assert_eq!(longer.select(&doc, 0), []);
let chain = "div ".repeat(50);
let mut css = format!(":nth-child(1 of {chain}b)");
css = format!(":has(> {chain}{css})");
for _ in 0..30 {
css = format!(":is({chain}{css})");
}
let nested = SelectorList::parse(&format!("{chain}{css}")).unwrap();
assert!(nested.matches(&doc, div, None));
})
.unwrap()
.join()
.unwrap();
}
#[test]
fn has_and_nth_of_answer_from_what_they_kept() {
let html = "<div id=a><div id=b><p></p><div id=c><b></b></div></div>\
<div id=d><div id=e></div></div></div>";
assert_eq!(select(html, "div:has(b)"), ["div#a", "div#b", "div#c"]);
assert_eq!(select(html, "div:has(> b)"), ["div#c"]);
assert_eq!(select(html, ":has(+ div)"), ["div#b", "p"]);
assert_eq!(select(html, ":has(~ div)"), ["div#b", "p"]);
assert_eq!(select(html, ":has(~ p)"), Vec::<String>::new());
assert_eq!(select(html, "div:has(div b)"), ["div#a", "div#b"]);
assert_eq!(select(html, "div:not(:has(b))"), ["div#d", "div#e"]);
let list = "<ul><li id=1 class=x><li id=2><li id=3 class=x><li id=4 class=x></ul>";
assert_eq!(select(list, "li:nth-child(2 of .x)"), ["li#3"]);
assert_eq!(select(list, "li:nth-last-child(1 of .x)"), ["li#4"]);
assert_eq!(select(list, "li:nth-child(odd of :not(.x))"), ["li#2"]);
let deep = parse(&("<div>".repeat(20_000) + "<b></b>"), false);
let count = |doc: &Document, css: &str| SelectorList::parse(css).unwrap().select(doc, 0).len();
assert_eq!(count(&deep, "div:has(b)"), 20_000);
assert_eq!(count(&deep, "div:has(p)"), 0);
let long = parse(
&format!("<ul>{}<b></b></ul>", "<li class=x></li>".repeat(20_000)),
false,
);
assert_eq!(count(&long, "li:has(~ b)"), 20_000);
assert_eq!(count(&long, "li:nth-child(2n of .x)"), 10_000);
assert_eq!(count(&long, "li:nth-last-child(-n+100000 of .x)"), 20_000);
assert_eq!(count(&long, "li:nth-child(-n+100000)"), 20_000);
let kinds: String = (0..20_000).map(|i| format!("<x-{i}></x-{i}>")).collect();
let kinds = parse(&format!("<div>{kinds}</div>"), false);
assert_eq!(count(&kinds, "div > :only-of-type"), 20_000);
assert_eq!(count(&kinds, "div > :last-of-type"), 20_000);
assert_eq!(count(&kinds, "div > :nth-of-type(2)"), 0);
}
#[test]
fn a_chain_that_cant_match_gives_up_soon() {
let doc = parse(&"<div>".repeat(200), false);
let css = String::from("x") + &" div".repeat(12);
assert_eq!(SelectorList::parse(&css).unwrap().select(&doc, 0), []);
let css = String::from("x ~ div") + &" div".repeat(12);
assert_eq!(SelectorList::parse(&css).unwrap().select(&doc, 0), []);
assert_eq!(select("<p><i></i><b></b><u></u></p>", "p > i ~ u"), ["u"]);
assert_eq!(
select(
"<a><p><b></b></p><i><u></u></i></a>",
"a > i > u, a b, p ~ i u"
),
["b", "u"]
);
}
#[test]
fn a_budget_stops_a_long_query() {
let doc = parse(&"<div>".repeat(20_000), false);
let slow = SelectorList::parse("div:has(p div)").unwrap();
let tight = MatchOptions {
budget: Some(std::time::Duration::from_micros(50)),
..MatchOptions::default()
};
let budget = tight.budget.unwrap();
assert_eq!(
slow.try_select_with(&doc, 0, &tight),
Err(MatchTimeout { budget })
);
let first = SelectorList::parse("div").unwrap().select(&doc, 0)[0];
assert_eq!(
slow.try_matches_with(&doc, first, None, &tight),
Err(MatchTimeout { budget })
);
let fast = SelectorList::parse("div:has(> div)").unwrap();
let roomy = MatchOptions {
budget: Some(std::time::Duration::MAX),
..MatchOptions::default()
};
assert_eq!(fast.try_select_with(&doc, 0, &roomy).unwrap().len(), 19_999);
assert_eq!(fast.try_matches_with(&doc, first, None, &roomy), Ok(true));
}
#[test]
fn selectors_read_as_css_reads_them() {
assert_eq!(page("li/**/.sold"), ["li#27"]);
assert_eq!(page("li /**/.price"), ["span"]);
assert_eq!(page("li /**/ .price"), ["span"]);
assert_eq!(page("li/**/ .price"), ["span"]);
assert_eq!(page("ul/**/>/**/li").len(), 4);
assert!(SelectorList::parse("*/**/").is_ok());
assert!(SelectorList::parse("a/**/b").is_err());
for bad in [
":nth-child(2 n)",
":nth-child(+ 5)",
":nth-child(- n+1)",
":nth-child(2n 1)",
] {
assert!(SelectorList::parse(bad).is_err(), "{bad:?} parsed");
}
for good in [
":nth-child(2n + 1)",
":nth-child( 2n- 1 )",
":nth-child(-n +3)",
":nth-child(+5)",
] {
assert!(SelectorList::parse(good).is_ok(), "{good:?} didn't parse");
}
for (bad, why) in [
("#1a", "an ID can't start with a digit"),
("#-1", "an ID can't start with a hyphen and a digit"),
("#", "a # with no ID after it"),
("p#", "a # with no ID after it"),
] {
let e = SelectorList::parse(bad).expect_err(bad);
assert!(e.to_string().contains(why), "{bad:?}: {e}");
}
assert!(SelectorList::parse(r"#\31 a").is_ok());
assert!(SelectorList::parse("#--x").is_ok());
for bad in [
":has(:has(a))",
":has(a, :has(b))",
":has(:nth-child(1 of :has(a)))",
":has(:not(:has(a)))",
] {
assert!(SelectorList::parse(bad).is_err(), "{bad:?} parsed");
}
assert!(SelectorList::parse(":has(a):has(b)").is_ok());
assert!(SelectorList::parse(":is(:has(a))").is_ok());
}
#[test]
fn select_iter_finds_matches_lazily_and_select_first_stops_at_one() {
let doc = parse(PAGE, false);
let list = SelectorList::parse("li, a").unwrap();
let all = list.select(&doc, doc.root());
assert_eq!(list.select_iter(&doc, doc.root()).collect::<Vec<_>>(), all);
assert_eq!(list.select_first(&doc, doc.root()), all.first().copied());
assert_eq!(
list.select_iter(&doc, doc.root()).nth(2),
all.get(2).copied()
);
let none = SelectorList::parse("table").unwrap();
assert_eq!(none.select_first(&doc, doc.root()), None);
let ul = SelectorList::parse("ul")
.unwrap()
.select_first(&doc, doc.root())
.unwrap();
let first_li = SelectorList::parse("li")
.unwrap()
.select_first(&doc, ul)
.unwrap();
assert_eq!(names(&doc, &[first_li]), ["li#17"]);
}
#[test]
fn specificity_counts_as_selectors_4_does() {
let spec = |s: &str| SelectorList::parse(s).unwrap().specificity();
assert_eq!(spec("*"), (0, 0, 0));
assert_eq!(spec("li"), (0, 0, 1));
assert_eq!(spec("ul li.item[data-id]"), (0, 2, 2));
assert_eq!(spec("#main > a:hover"), (1, 1, 1));
assert_eq!(spec("a, #x, .y"), (1, 0, 0));
assert_eq!(spec(":is(#x, .y) p"), (1, 0, 1));
assert_eq!(spec(":where(#x, .y) p"), (0, 0, 1));
assert_eq!(spec("p:not(.a, #b)"), (1, 0, 1));
assert_eq!(spec("li:has(> a.x)"), (0, 1, 2));
assert_eq!(spec("li:nth-child(2n of .item)"), (0, 2, 1));
assert_eq!(spec("li:nth-child(odd)"), (0, 1, 1));
}
fn select_at(html: &str, css: &str, url: &str) -> Vec<String> {
let doc = parse(html, false);
let list = SelectorList::parse(css).unwrap_or_else(|e| panic!("{css}: {e}"));
names(
&doc,
&list.select_with(
&doc,
doc.root(),
&MatchOptions {
url: Some(url),
..MatchOptions::default()
},
),
)
}
#[test]
fn target_is_the_element_the_fragment_indicates() {
let html = r#"<div id="outer"><p id="sec">a</p><a name="sec" id="named">b</a><a name="old" id="anchor">c</a></div>
<p id="top">t</p><p id="café">d</p>"#;
assert_eq!(select_at(html, ":target", "https://x.test/#sec"), ["p#sec"]);
assert_eq!(select_at(html, ":target", "https://x.test/#old"), ["a#old"]);
assert_eq!(select_at(html, ":target", "https://x.test/#top"), ["p#top"]);
assert_eq!(
select_at(html, ":target", "https://x.test/#caf%C3%A9"),
["p#café"]
);
assert_eq!(
select_at(html, ":target", "https://x.test/#"),
Vec::<String>::new()
);
assert_eq!(
select_at(html, ":target", "https://x.test/#gone"),
Vec::<String>::new()
);
assert_eq!(
select_at(html, ":target-within", "https://x.test/#sec"),
["html", "body", "div#outer", "p#sec"]
);
assert_eq!(select(html, ":target"), Vec::<String>::new());
assert_eq!(
select_at("<p id=top>t</p>", ":target", "https://x.test/#TOP"),
Vec::<String>::new()
);
}
#[test]
fn lang_matches_the_nearest_language_by_extended_filtering() {
let html = r#"<div id="ch" lang="de-CH"><p id="in">x</p></div>
<p id="latn" lang="de-Latn-CH">a</p><p id="en" lang="EN-gb">b</p><p id="fr" lang="fr">c</p>
<p id="none">d</p><p id="private" lang="de-x-CH">e</p>
<div id="outer" lang="de"><p id="inner" lang="en">f</p></div>
<svg id="svg" xml:lang="fr" lang="de"></svg>
<p id="long" lang="de-ninecharacters">g</p><p id="dash" lang="de-">h</p><p id="odd" lang="de_CH">i</p>"#;
assert_eq!(
select(html, ":lang(de)"),
["div#ch", "p#in", "p#latn", "p#private", "div#outer"]
);
assert_eq!(select(html, ":lang(de-CH)"), ["div#ch", "p#in", "p#latn"]);
assert_eq!(select(html, ":lang('*-CH')"), ["div#ch", "p#in", "p#latn"]);
assert_eq!(
select(html, ":lang(en, fr)"),
["p#en", "p#fr", "p#inner", "svg#svg"]
);
assert_eq!(select(html, ":lang(EN-GB)"), ["p#en"]);
assert_eq!(select(html, "p:lang(e)"), Vec::<String>::new());
assert_eq!(select(html, "svg:lang(de)"), Vec::<String>::new());
assert!(SelectorList::parse(":lang()").is_err());
}
#[test]
fn dir_follows_the_dir_attribute_and_the_text_for_auto() {
let html = r#"<p id="plain">x</p><div id="r" dir="RTL"><span id="in">x</span></div>
<div id="he" dir="auto">123 שלום abc</div>
<div id="digits" dir="auto">123</div>
<div id="script" dir="auto"><script>ש</script>abc</div>
<div id="nested" dir="auto"><span dir="ltr">abc</span>مرحبا</div>
<bdi id="bdi">مرحبا</bdi>
<input id="field" dir="auto" value="שלום"><textarea id="ta" dir="auto">abc</textarea>
<div id="bad" dir="sideways"><i id="i">x</i></div>"#;
assert_eq!(
select(html, ":dir(rtl)"),
[
"div#r",
"span#in",
"div#he",
"div#nested",
"bdi#bdi",
"input#field"
]
);
assert_eq!(
select(
html,
"div:dir(ltr), p:dir(ltr), textarea:dir(ltr), i:dir(ltr)"
),
[
"p#plain",
"div#digits",
"div#script",
"textarea#ta",
"div#bad",
"i#i"
]
);
assert_eq!(select(html, ":dir(up), :dir(auto)"), Vec::<String>::new());
assert!(SelectorList::parse(":dir()").is_err());
assert!(SelectorList::parse(":dir('ltr')").is_err());
assert!(SelectorList::parse(":dir(ltr, rtl)").is_err());
}
#[test]
fn default_and_indeterminate_follow_the_markup() {
let html = r#"<form id="f">
<input type="text" name="t"><button id="first" type="button">no</button>
<button id="go">go</button><input type="submit" id="second">
<input type="checkbox" id="c1" checked><input type="checkbox" id="c2">
<input type="radio" id="a1" name="a"><input type="radio" id="a2" name="a" checked>
<input type="radio" id="b1" name="b"><input type="radio" id="b2" name="b">
<input type="radio" id="alone">
<select><option id="o1">x</option><option id="o2" selected>y</option></select>
</form>
<form id="g"></form><input type="submit" id="outside" form="g">
<input type="radio" id="b3" name="b" checked>
<progress id="busy"></progress><progress id="half" value="0.5"></progress>"#;
assert_eq!(
select(html, ":default"),
[
"button#go",
"input#c1",
"input#a2",
"option#o2",
"input#outside",
"input#b3"
]
);
assert_eq!(
select(html, ":indeterminate"),
["input#b1", "input#b2", "input#alone", "progress#busy"]
);
}
#[test]
fn local_link_resolves_against_the_document_url() {
let html = r##"<a id="frag" href="#other">1</a><a id="rel" href="b?q">2</a><a id="path" href="b">3</a>
<a id="abs" href="/a/b?q#x">4</a><a id="host" href="//X.TEST:443/a/b?q">5</a><a id="elsewhere" href="https://y.test/a/b?q">6</a>
<a id="nohref">7</a><area id="area" href="?q">"##;
assert_eq!(
select_at(html, ":local-link", "https://x.test/a/b?q#sec"),
["a#frag", "a#rel", "a#abs", "a#host", "area#area"]
);
let based = r#"<base href="/c/"><a id="here" href="d">1</a><a id="there" href="b">2</a>"#;
assert_eq!(
select_at(based, ":local-link", "https://x.test/c/d"),
["a#here"]
);
assert_eq!(select(html, ":local-link"), Vec::<String>::new());
}
#[test]
fn in_range_and_out_of_range_follow_min_max_and_the_value() {
let html = r#"<input id="n1" type="number" min="1" max="10" value="5">
<input id="n2" type="number" min="1" max="10" value="11"><input id="n3" type="number" min="1" value="0.5e0">
<input id="n4" type="number" min="1" max="10"><input id="n5" type="number" min="1" value="ten">
<input id="n6" type="number" value="5"><input id="n7" type="number" min="1" value="0" disabled>
<input id="n8" type="number" min="1" value="0" readonly><datalist><input id="n9" type="number" min="1" value="0"></datalist>
<input id="r1" type="range" value="500"><input id="r2" type="range" readonly value="-5">
<input id="d1" type="date" min="2024-01-01" value="2024-02-29"><input id="d2" type="date" max="2023-12-31" value="2024-01-01">
<input id="d3" type="date" min="2024-01-01" value="2023-02-29">
<input id="m1" type="month" max="2024-06" value="2024-07"><input id="w1" type="week" min="2025-W53" value="2025-W01">
<input id="w2" type="week" min="2020-W53" value="2020-W53">
<input id="t1" type="time" min="22:00" max="06:00" value="23:30"><input id="t2" type="time" min="22:00" max="06:00" value="12:00">
<input id="dt" type="datetime-local" max="2024-01-01T12:00" value="2024-01-01 12:00:01">
<input id="text" type="text" min="1" value="0"><input id="dot" type="number" min="1." value="0">
<input id="n10" type="number" min="1" value="1.">"#;
assert_eq!(
select(html, ":in-range"),
[
"input#n1",
"input#n4",
"input#n5",
"input#r1",
"input#r2",
"input#d1",
"input#d3",
"input#w2",
"input#t1",
"input#n10"
]
);
assert_eq!(
select(html, ":out-of-range"),
[
"input#n2", "input#n3", "input#d2", "input#m1", "input#t2", "input#dt"
]
);
}
#[test]
fn valid_and_invalid_follow_the_constraints_the_markup_sets() {
let html = r#"<form id="f">
<input id="req" required><input id="req-ok" required value="x"><input id="plain">
<input id="mail" type="email" value="a@b.example"><input id="bad-mail" type="email" value="a@-b">
<input id="mails" type="email" multiple value=" a@b.example , c@d.example "><input id="url" type="url" value="https://x.test/">
<input id="bad-url" type="url" value="not a url"><input id="num" type="number" min="1" max="10" step="2" value="5">
<input id="off-step" type="number" min="1" step="2" value="4"><input id="over" type="number" max="3" value="4">
<input id="any" type="number" min="0" step="any" value="0.5"><input id="wk" type="week" min="2020-W53" step="2" value="2021-W02">
<input id="box" type="checkbox" required><input id="file" type="file" required>
<input id="r1" type="radio" name="g" required><input id="r2" type="radio" name="g">
<textarea id="ta" required></textarea>
<select id="sel" required><option value="">Pick</option><option>A</option></select>
<select id="sel-ok" required><option value="">Pick</option><option selected>A</option></select>
<input id="ro" required readonly><input id="off" required disabled><input id="hid" type="hidden" required>
<button id="go">go</button><button id="nope" type="button">x</button>
</form>
<form id="g"><input id="fine" value="x"></form>
<fieldset id="fs"><input id="in-fs" type="email" value="x"></fieldset>"#;
assert_eq!(
select(html, "input:invalid, textarea:invalid, select:invalid"),
[
"input#req",
"input#bad-mail",
"input#bad-url",
"input#off-step",
"input#over",
"input#box",
"input#file",
"input#r1",
"input#r2",
"textarea#ta",
"select#sel",
"input#in-fs"
]
);
assert_eq!(
select(html, "input:valid, select:valid, button:valid"),
[
"input#req-ok",
"input#plain",
"input#mail",
"input#mails",
"input#url",
"input#num",
"input#any",
"input#wk",
"select#sel-ok",
"button#go",
"input#fine"
]
);
assert_eq!(
select(html, "form:invalid, fieldset:invalid"),
["form#f", "fieldset#fs"]
);
assert_eq!(select(html, "form:valid"), ["form#g"]);
}
#[test]
fn valid_checks_pattern_as_javascript_reads_it() {
let html = r#"<input id="three" pattern="\d{3}" value="123"><input id="four" pattern="\d{3}" value="1234">
<input id="upper" pattern="[a-z]+" value="abC"><input id="arabic" pattern="\d+" value="٣">
<input id="minus" pattern="[\w--\d]+" value="ab_"><input id="minus-bad" pattern="[\w--\d]+" value="a1">
<input id="and" pattern="[[a-z]&&[^aeiou]]+" value="bcd"><input id="and-bad" pattern="[[a-z]&&[^aeiou]]+" value="bad">
<input id="alt" pattern="ab|cd" value="abcd">
<input id="mails" type="email" multiple pattern=".+@x\.test" value="a@x.test, b@x.test">
<input id="mails-bad" type="email" multiple pattern=".+@x\.test" value="a@x.test,b@y.test">
<input id="broken" pattern="[" value="anything"><input id="prop" pattern="\p{L}+" value="Zoë">
<input id="prop-bad" pattern="\p{L}+" value="123"><input id="greek" pattern="[\p{sc=Greek}\s]+" value="Ελένη Παπά">
<input id="not-letter" pattern="\P{L}+" value="a1"><input id="strings" pattern="\p{RGI_Emoji}" value="x">
<input id="redos" pattern="(a+)+b" value="aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa">
<input id="num" type="number" pattern="x" value="5"><input id="empty" pattern="x">"#;
assert_eq!(
select(html, ":invalid"),
[
"input#four",
"input#upper",
"input#arabic",
"input#minus-bad",
"input#and-bad",
"input#alt",
"input#mails-bad",
"input#prop-bad",
"input#not-letter",
"input#redos"
]
);
assert_eq!(
select(html, ":valid"),
[
"input#three",
"input#minus",
"input#and",
"input#mails",
"input#broken",
"input#prop",
"input#greek",
"input#strings",
"input#num",
"input#empty"
]
);
}
#[test]
fn valid_reads_attributes_as_the_standard_parses_them() {
let html = r#"<input id="one-mail" type="email" value="a@b.example,c@d.example">
<input id="two-mails" type="email" multiple value="a@b.example,c@d.example">
<select id="list" required size="3"><option>A</option></select>
<input id="step-ws" type="number" min="0" step=" 2 " value="3">
<input id="step-unit" type="number" min="0" step="2px" value="4">
<select id="px" required size="2px"><option value="" selected>None</option><option>A</option></select>"#;
assert_eq!(
select(html, ":invalid"),
["input#one-mail", "select#list", "input#step-ws"]
);
assert_eq!(
select(html, ":valid"),
["input#two-mails", "input#step-unit", "select#px"]
);
}