Skip to content

Lightpanda: the headless browser designed for AI and automation

selector: support relative :has() arguments per Selectors Level 4

Navid EMAD25077d8ddc21
diff --git a/src/browser/tests/document/query_selector_has.html b/src/browser/tests/document/query_selector_has.html
new file mode 100644
index 000000000..f3e438307
--- /dev/null
+++ b/src/browser/tests/document/query_selector_has.html
@@ -0,0 +1,120 @@
+<!DOCTYPE html>
+<script src="../testing.js"></script>
+
+<div id="root">
+ <ul id="list">
+ <li id="li1" class="item">One</li>
+ <li id="li2" class="item">Two</li>
+ <li id="li3" class="item active">Three</li>
+ <li id="li4" class="item">Four</li>
+ </ul>
+ <div id="box">
+ <p id="direct">direct child</p>
+ <section id="wrap">
+ <p id="nested">nested</p>
+ </section>
+ </div>
+ <div id="adjacent">
+ <span id="a1"></span>
+ text between
+ <em id="a2"></em>
+ </div>
+ <div id="rel">
+ <div id="r1"></div>
+ <div id="r2"><b id="deep"></b></div>
+ </div>
+ <span id="outer-span">
+ <div id="inverted"><p id="inner-p">text</p></div>
+ </span>
+</div>
+
+<script id=hasDescendant>
+{
+ // No leading combinator = descendant search (pre-existing behavior).
+ const withP = document.querySelectorAll('#root div:has(p)');
+ testing.expectEqual(2, withP.length);
+ testing.expectEqual('box', withP[0].id);
+ testing.expectEqual('inverted', withP[1].id);
+
+ // The argument is anchored at the element: #inner-p has a <span> ancestor,
+ // but that span is ABOVE #inverted, so ':scope span p' must not match.
+ const spanP = document.querySelectorAll('#root div:has(span p)');
+ testing.expectEqual(0, spanP.length);
+}
+</script>
+
+<script id=hasChild>
+{
+ const directP = document.querySelectorAll('#root div:has(> p)');
+ testing.expectEqual(2, directP.length);
+ testing.expectEqual('box', directP[0].id);
+ testing.expectEqual('inverted', directP[1].id);
+
+ // #nested is a grandchild of #box: the child constraint must exclude it.
+ const box = document.getElementById('box');
+ testing.expectEqual(true, box.matches(':has(#nested)'));
+ testing.expectEqual(false, box.matches(':has(> #nested)'));
+}
+</script>
+
+<script id=hasSubsequentSibling>
+{
+ const beforeActive = document.querySelectorAll('#list li:has(~ .active)');
+ testing.expectEqual(2, beforeActive.length);
+ testing.expectEqual('li1', beforeActive[0].id);
+ testing.expectEqual('li2', beforeActive[1].id);
+
+ const idiom = document.querySelectorAll('#list .item:not(.active):has(~ .item.active)');
+ testing.expectEqual(2, idiom.length);
+ testing.expectEqual('li1', idiom[0].id);
+ testing.expectEqual('li2', idiom[1].id);
+
+ // Siblings only look forward: nothing precedes #li1.
+ const beforeFirst = document.querySelectorAll('#list li:has(~ #li1)');
+ testing.expectEqual(0, beforeFirst.length);
+
+ // The argument's own combinators still apply after the sibling anchor.
+ const siblingDesc = document.querySelectorAll('#rel div:has(~ div b)');
+ testing.expectEqual(1, siblingDesc.length);
+ testing.expectEqual('r1', siblingDesc[0].id);
+}
+</script>
+
+<script id=hasNextSibling>
+{
+ // Non-element siblings (the text node) are skipped.
+ const beforeEm = document.querySelectorAll('#adjacent span:has(+ em)');
+ testing.expectEqual(1, beforeEm.length);
+ testing.expectEqual('a1', beforeEm[0].id);
+
+ const beforeActive = document.querySelectorAll('#list li:has(+ .active)');
+ testing.expectEqual(1, beforeActive.length);
+ testing.expectEqual('li2', beforeActive[0].id);
+}
+</script>
+
+<script id=hasRelativeList>
+{
+ const list = document.querySelectorAll('#root > *:has(> .active, > #direct)');
+ testing.expectEqual(2, list.length);
+ testing.expectEqual('list', list[0].id);
+ testing.expectEqual('box', list[1].id);
+}
+</script>
+
+<script id=hasMatches>
+{
+ const li2 = document.getElementById('li2');
+ const li4 = document.getElementById('li4');
+ testing.expectEqual(true, li2.matches(':has(~ .active)'));
+ testing.expectEqual(false, li4.matches(':has(~ .active)'));
+}
+</script>
+
+<script id=hasInvalid>
+{
+ // A combinator with nothing after it is not a valid relative selector.
+ testing.expectError("SyntaxError", () => document.querySelectorAll(':has(>)'));
+ testing.expectError("SyntaxError", () => document.querySelectorAll(':has(~ )'));
+}
+</script>
diff --git a/src/browser/webapi/selector/List.zig b/src/browser/webapi/selector/List.zig
index a2576928d..0ac7c6dcb 100644
--- a/src/browser/webapi/selector/List.zig
+++ b/src/browser/webapi/selector/List.zig
@@ -683,23 +683,23 @@ fn matchesPseudoClass(el: *Node.Element, pseudo: Selector.PseudoClass, scope: *N
return false;
},
.has => |selectors| {
+ // Arguments were absolutized at parse time (":has(~ .a)" is stored
+ // as ":scope ~ .a"), so candidates are matched with :scope bound to
+ // this element. The leading combinator decides where candidates can
+ // live: sibling combinators anchor them in the parent's subtree,
+ // descendant/child in this element's own subtree.
for (selectors) |selector| {
- var child = node.firstChild();
- while (child) |c| {
- const child_el = c.is(Node.Element) orelse {
- child = c.nextSibling();
- continue;
- };
-
- if (matches(child_el.asNode(), selector, scope, frame)) {
- return true;
- }
+ const search_root = switch (selector.segments[0].combinator) {
+ .next_sibling, .subsequent_sibling => node.parentNode() orelse continue,
+ .descendant, .child => node,
+ };
- if (matchesHasDescendant(child_el, selector, scope, frame)) {
+ var tw = TreeWalker.init(search_root, .{});
+ _ = tw.next(); // the search root itself is never a candidate
+ while (tw.next()) |candidate| {
+ if (matches(candidate, selector, node, frame)) {
return true;
}
-
- child = c.nextSibling();
}
}
return false;
@@ -707,27 +707,6 @@ fn matchesPseudoClass(el: *Node.Element, pseudo: Selector.PseudoClass, scope: *N
}
}
-fn matchesHasDescendant(el: *Node.Element, selector: Selector.Selector, scope: *Node, frame: *Frame) bool {
- var child = el.asNode().firstChild();
- while (child) |c| {
- const child_el = c.is(Node.Element) orelse {
- child = c.nextSibling();
- continue;
- };
-
- if (matches(child_el.asNode(), selector, scope, frame)) {
- return true;
- }
-
- if (matchesHasDescendant(child_el, selector, scope, frame)) {
- return true;
- }
-
- child = c.nextSibling();
- }
- return false;
-}
-
fn hasInvalidDescendant(parent: *Node, frame: *Frame) bool {
var child = parent.firstChild();
while (child) |c| {
diff --git a/src/browser/webapi/selector/Parser.zig b/src/browser/webapi/selector/Parser.zig
index 7cf6a6042..caf6f1d7f 100644
--- a/src/browser/webapi/selector/Parser.zig
+++ b/src/browser/webapi/selector/Parser.zig
@@ -287,6 +287,24 @@ pub fn parse(arena: Allocator, input: []const u8) ParseError!Selector.Selector {
};
}
+// :has() arguments are relative selectors. Absolutize them at parse time by
+// prepending a :scope anchor, e.g. ":has(~ .a .b)" is stored as
+// ":scope ~ .a .b". Matching then reuses the regular segment walk, binding
+// :scope to the element :has() is evaluated against.
+// https://drafts.csswg.org/selectors-4/#absolutizing
+const scope_anchor = [_]Part{.{ .pseudo_class = .scope }};
+
+fn absolutize(arena: Allocator, selector: Selector.Selector, combinator: Combinator) !Selector.Selector {
+ const segments = try arena.alloc(Segment, selector.segments.len + 1);
+ segments[0] = .{ .combinator = combinator, .compound = selector.first };
+ @memcpy(segments[1..], selector.segments);
+
+ return .{
+ .first = .{ .parts = &scope_anchor },
+ .segments = segments,
+ };
+}
+
fn parsePart(self: *Parser, arena: Allocator) !Part {
return switch (self.peek()) {
'#' => .{ .id = try self.id(arena) },
@@ -525,8 +543,24 @@ fn pseudoClass(self: *Parser, arena: Allocator) !Selector.PseudoClass {
if (self.peek() == ')') break;
if (self.peek() == 0) return error.InvalidPseudoClass;
+ // :has() takes a <relative-selector-list>: each argument may
+ // start with an explicit combinator (":has(> div)", ":has(~ p)")
+ // and is anchored at the element being matched, with an implied
+ // descendant combinator when none is written.
+ // https://drafts.csswg.org/selectors-4/#relational
+ const combinator: Combinator = switch (self.peek()) {
+ '>' => .child,
+ '+' => .next_sibling,
+ '~' => .subsequent_sibling,
+ else => .descendant,
+ };
+ if (combinator != .descendant) {
+ self.input = self.input[1..];
+ _ = self.skipSpaces();
+ }
+
const selector = try parse(arena, self.consumeUntilCommaOrParen());
- try selectors.append(arena, selector);
+ try selectors.append(arena, try absolutize(arena, selector, combinator));
_ = self.skipSpaces();
if (self.peek() == ',') {
@@ -1740,3 +1774,69 @@ test "Selector: Parser.attributeName" {
try testing.expectError(error.InvalidAttributeSelector, parser.attributeName(arena));
}
}
+
+test "Selector: Parser.has" {
+ const arena = testing.arena_allocator;
+
+ // No leading combinator: absolutized with an implied descendant combinator.
+ {
+ const selector = try parse(arena, "div:has(p)");
+ const args = selector.first.parts[1].pseudo_class.has;
+ try testing.expectEqual(1, args.len);
+ try testing.expectEqual(true, args[0].first.parts[0].pseudo_class == .scope);
+ try testing.expectEqual(1, args[0].segments.len);
+ try testing.expectEqual(.descendant, args[0].segments[0].combinator);
+ try testing.expectEqual(.p, args[0].segments[0].compound.parts[0].tag);
+ }
+
+ // Explicit leading combinators.
+ {
+ const selector = try parse(arena, "div:has(> p)");
+ const arg = selector.first.parts[1].pseudo_class.has[0];
+ try testing.expectEqual(true, arg.first.parts[0].pseudo_class == .scope);
+ try testing.expectEqual(.child, arg.segments[0].combinator);
+ }
+
+ {
+ const selector = try parse(arena, "li:has(~ li.active)");
+ const arg = selector.first.parts[1].pseudo_class.has[0];
+ try testing.expectEqual(.subsequent_sibling, arg.segments[0].combinator);
+ try testing.expectEqual(.li, arg.segments[0].compound.parts[0].tag);
+ try testing.expectEqual("active", arg.segments[0].compound.parts[1].class);
+ }
+
+ {
+ const selector = try parse(arena, "span:has(+em)");
+ const arg = selector.first.parts[1].pseudo_class.has[0];
+ try testing.expectEqual(.next_sibling, arg.segments[0].combinator);
+ }
+
+ // The argument's own combinators are preserved after the anchor segment.
+ {
+ const selector = try parse(arena, "div:has(~ p a)");
+ const arg = selector.first.parts[1].pseudo_class.has[0];
+ try testing.expectEqual(2, arg.segments.len);
+ try testing.expectEqual(.subsequent_sibling, arg.segments[0].combinator);
+ try testing.expectEqual(.descendant, arg.segments[1].combinator);
+ }
+
+ // Comma-separated relative selector list.
+ {
+ const selector = try parse(arena, "div:has(> p, ~ a)");
+ const args = selector.first.parts[1].pseudo_class.has;
+ try testing.expectEqual(2, args.len);
+ try testing.expectEqual(.child, args[0].segments[0].combinator);
+ try testing.expectEqual(.subsequent_sibling, args[1].segments[0].combinator);
+ }
+
+ // A combinator with nothing after it is invalid.
+ {
+ try testing.expectError(error.InvalidSelector, parse(arena, "div:has(>)"));
+ try testing.expectError(error.InvalidSelector, parse(arena, "div:has(~ )"));
+ }
+
+ // Empty :has() stays invalid.
+ {
+ try testing.expectError(error.InvalidPseudoClass, parse(arena, "div:has()"));
+ }
+}