Lightpanda: the headless browser designed for AI and automation
webapi: Mouse events pierce into shadowdom
Karl Seguin762ce2e3aa6d
diff --git a/src/browser/frame/user_input.zig b/src/browser/frame/user_input.zigindex e81ce0383..6d1b6bbc9 100644--- a/src/browser/frame/user_input.zig+++ b/src/browser/frame/user_input.zig@@ -169,13 +169,13 @@ fn dispatchBoundaryEvents(frame: *Frame, from: ?*Element, to: ?*Element, emitterconst pivot: ?*Node = blk: {const a = from orelse break :blk null;const b = to orelse break :blk null;- break :blk commonAncestor(a.asNode(), b.asNode());+ break :blk commonAncestor(a.asNode(), b.asNode(), frame);};if (from) |old| {emitter.emit(frame, old, "out", to, true);var current: ?*Node = old.asNode();- while (current) |node| : (current = node.parentNode()) {+ while (current) |node| : (current = node.flatTreeParent(frame)) {if (node == pivot) {break;}@@ -193,7 +193,7 @@ fn dispatchBoundaryEvents(frame: *Frame, from: ?*Element, to: ?*Element, emitter// reach each one from the deepest ancestor down.var count: usize = 0;var current: ?*Node = new.asNode();- while (current) |node| : (current = node.parentNode()) {+ while (current) |node| : (current = node.flatTreeParent(frame)) {if (node == pivot) {break;}@@ -204,7 +204,7 @@ fn dispatchBoundaryEvents(frame: *Frame, from: ?*Element, to: ?*Element, emitterwhile (count > 0) : (count -= 1) {var remaining = count;current = new.asNode();- while (current) |node| : (current = node.parentNode()) {+ while (current) |node| : (current = node.flatTreeParent(frame)) {const element = node.is(Element) orelse continue;remaining -= 1;if (remaining == 0) {@@ -432,26 +432,37 @@ pub const PointerButtons = struct {}};-fn commonAncestor(a: *Node, b: *Node) ?*Node {+/// The nearest common inclusive ancestor in the flat tree, where a shadow+/// tree sits inside its host, as hit-testing sees it.+fn commonAncestor(a: *Node, b: *Node, frame: *const Frame) ?*Node {var current: ?*Node = a;- while (current) |node| : (current = node.parentNode()) {- if (node.contains(b)) {- return node;+ while (current) |node| : (current = node.flatTreeParent(frame)) {+ var other: ?*Node = b;+ while (other) |candidate| : (other = candidate.flatTreeParent(frame)) {+ if (node == candidate) {+ return node;+ }}}return null;}/// A click whose mousedown and mouseup landed on different elements fires at-/// their nearest common inclusive ancestor element.+/// their nearest common inclusive ancestor element. Two nodes of one shadow+/// tree meet at its shadow root, which isn't an element: the host is.fn commonClickTarget(frame: *Frame, down: *Element, up: *Element) ?*Element {const owner = down.ownerFrame(frame) orelse return null;if (up.ownerFrame(frame) != owner) return null;if (down == up) {return up;}- const ancestor = commonAncestor(down.asNode(), up.asNode()) orelse return up;- return ancestor.is(Element) orelse up;+ var current = commonAncestor(down.asNode(), up.asNode(), frame);+ while (current) |ancestor| : (current = ancestor.flatTreeParent(frame)) {+ if (ancestor.is(Element)) |element| {+ return element;+ }+ }+ return up;}pub fn moveSequence(frame: *Frame, target: *Element, g: Gesture) !void {@@ -587,7 +598,7 @@ fn mouseHitTest(frame: *Frame, x: f64, y: f64) !MouseHit {/// Like Chrome, a point inside the viewport that no element box covers lands/// on the root element, unless the root itself can't be hit.fn documentHit(frame: *Frame, x: f64, y: f64, width: f64, height: f64) !?*Element {- if (try frame.document.elementFromPoint(x, y, frame)) |target| {+ if (try frame.document.hitTest(x, y, frame)) |target| {return target;}if (!inBox(x, y, width, height)) {@@ -789,7 +800,7 @@ fn scrollAxis(target: *Element, comptime axis: Element.Axis, delta: i32, frame:if (container.containsOverscroll(axes, frame)) {return;}- current = container.parentElement();+ current = container.asNode().flatTreeParentElement(frame);}const opts: Element.ScrollToOpts = switch (axis) {@@ -938,7 +949,7 @@ pub fn touchStart(frame: *Frame, target: ?*Element, point: Touch.Point, modifier}const owner = if (target) |el| el.ownerFrame(frame) orelse frame else frame;const resolved = target orelse- (try owner.window._document.elementFromPoint(point.x, point.y, owner)) orelse+ (try owner.window._document.hitTest(point.x, point.y, owner)) orelseowner.window._document.getDocumentElement() orelse return;if (comptime lp.IS_DEBUG) {log.debug(.frame, "frame touch", .{@@ -1099,7 +1110,7 @@ pub fn touchCancel(frame: *Frame, modifiers: Modifiers) !void {fn touchCompatTarget(frame: *Frame, point: Touch.Point, pinned: ?*Element) !?*Element {if (pinned) |el| return el;- return frame.window._document.elementFromPoint(point.x, point.y, frame);+ return frame.window._document.hitTest(point.x, point.y, frame);}/// Drops the page's input state on `frame`'s elements, which are going away.@@ -1968,7 +1979,7 @@ test "user_input: mouse hit testing descends nested iframe viewports" {const y = rect.y + nested_rect.y + child_rect.y + 1;// The DOM API intentionally returns the iframe in the calling document.- try testing.expect((try main.document.elementFromPoint(x, y, main)) == child.iframe.?.asElement());+ try testing.expect((try main.document.hitTest(x, y, main)) == child.iframe.?.asElement());var ls: js.Local.Scope = undefined;nested.js.localScope(&ls);defer ls.deinit();@@ -2023,7 +2034,7 @@ test "user_input: a blank viewport point hovers the root; only leaving the viewpconst rect = outer.boundingClientRectValues(main);const viewport = main.page.getViewport();const blank_y: f64 = @floatFromInt(viewport.height - 1);- try testing.expect((try main.document.elementFromPoint(1, blank_y, main)) == null);+ try testing.expect((try main.document.hitTest(1, blank_y, main)) == null);var ls: js.Local.Scope = undefined;main.js.localScope(&ls);@@ -2068,7 +2079,7 @@ test "user_input: removing hit iframe in pointerdown stops its mouse sequence" {\\childInput.addEventListener('pointerdown', e => { e.preventDefault(); events.push('pointerdown'); document.getElementById('child').remove(); });\\for (const type of ['mousedown', 'focus', 'mouseup', 'click']) childInput.addEventListener(type, () => events.push(type));, null);- try testing.expect((try main.document.elementFromPoint(rect.x + iframe_rect.x + 1, rect.y + iframe_rect.y + 1, main)) == child.iframe.?.asElement());+ try testing.expect((try main.document.hitTest(rect.x + iframe_rect.x + 1, rect.y + iframe_rect.y + 1, main)) == child.iframe.?.asElement());try triggerMousePress(main, rect.x + iframe_rect.x + 1, rect.y + iframe_rect.y + 1, mouse_button.main, 1);try testing.expect((try ls.local.compileAndRun("events.join(',') === 'pointerdown'", null)).isTrue());try testing.expect(child.window._closed);@@ -2111,8 +2122,8 @@ test "user_input: an excluded child document root is not a mouse target" {for ([_][]const u8{ "display: none", "pointer-events: none" }) |style| {try root.setStyle(style, child);- try testing.expect((try main.document.elementFromPoint(x, y, main)) == iframe);- try testing.expect((try child.document.elementFromPoint(1, 1, child)) == null);+ try testing.expect((try main.document.hitTest(x, y, main)) == iframe);+ try testing.expect((try child.document.hitTest(1, 1, child)) == null);try triggerMouseMove(main, x, y);try triggerMousePress(main, x, y, mouse_button.main, 1);@@ -2143,8 +2154,8 @@ test "user_input: mouse hit testing still enters a blank child document" {_ = try ls.local.compileAndRun("document.documentElement.replaceChildren()", null);const hit = try mouseHitTest(main, x, y);- try testing.expect((try main.document.elementFromPoint(x, y, main)) == iframe.asElement());- try testing.expect((try child.document.elementFromPoint(1, 1, child)) == null);+ try testing.expect((try main.document.hitTest(x, y, main)) == iframe.asElement());+ try testing.expect((try child.document.hitTest(1, 1, child)) == null);try testing.expect(hit.frame == child);try testing.expect(hit.target == child.document.getDocumentElement().?);@@ -2192,7 +2203,7 @@ test "user_input: excluded child roots clear hover without releasing held buttontry testing.expect(main.page.input_hover_target == target);const root = child.document.getDocumentElement().?;try root.setStyle(style, child);- try testing.expect((try child.document.elementFromPoint(1, 1, child)) == null);+ try testing.expect((try child.document.hitTest(1, 1, child)) == null);try triggerMouseMove(main, iframe_rect.x + 1, iframe_rect.y + 1);try testing.expect(main.page.input_hover_target == null);try testing.expectEqual(1, main.page.input_pointer.held);@@ -2308,7 +2319,7 @@ test "user_input: wheel listener removing its iframe prevents the scroll defaultconst y = box_rect.y + iframe_rect.y + 1;try testing.expect(box.getScrollHeight(child) > box.getClientHeight(child));try testing.expectEqual(@as(u32, 0), box.getScrollTop(child));- const child_hit = (try child.document.elementFromPoint(box_rect.x + 1, box_rect.y + 1, child)).?;+ const child_hit = (try child.document.hitTest(box_rect.x + 1, box_rect.y + 1, child)).?;try testing.expect(box.asNode().contains(child_hit.asNode()));try triggerMouseWheel(main, x, y, 0, 20);@@ -2585,3 +2596,194 @@ test "user_input: synthetic blank iframe click preserves focus" {try testing.expect(main.document._active_element == outer);try testing.expect(focusedFrame(main) == main);}++test "user_input: shadow mouse rects are viewport relative and native clicks reach inner target" {+ const page = try testing.pageTest("input_mouse_shadow.html", .{});+ defer page.close();+ const frame = page.frame().?;+ var ls: js.Local.Scope = undefined;+ frame.js.localScope(&ls);+ defer ls.deinit();+ const host = frame.document.getElementById("host", frame).?;+ const inner = try ls.local.jsValueToZig(*Element, try ls.local.compileAndRun("inner", null));+ const host_rect = host.boundingClientRectValues(frame);+ const rect = inner.boundingClientRectValues(frame);+ try testing.expectEqual(host_rect.x + 20, rect.x);+ try testing.expectEqual(host_rect.y + 5, rect.y);+ const x = rect.x + 1;+ const y = rect.y + 1;+ try testing.expect((try mouseHitTest(frame, x, y)).target == inner);+ try triggerMouseMove(frame, x, y);+ try triggerMousePress(frame, x, y, mouse_button.main, 1);+ try triggerMouseRelease(frame, x, y, mouse_button.main, 1);+ try testing.expect((try ls.local.compileAndRun(+ \\events.length === 2 && events[0].listener === 'inner' && events[0].target === 'inner' &&+ \\events[1].listener === 'host' && events[1].target === 'host' && events[1].inner && events.every(e => e.trusted)+ , null)).isTrue());+}++test "user_input: shadow mouse hit testing respects bounds and hidden descendants" {+ const page = try testing.pageTest("input_mouse_shadow.html", .{});+ defer page.close();+ const frame = page.frame().?;+ var ls: js.Local.Scope = undefined;+ frame.js.localScope(&ls);+ defer ls.deinit();+ const host = frame.document.getElementById("host", frame).?;+ const inner = try ls.local.jsValueToZig(*Element, try ls.local.compileAndRun("inner", null));+ const rect = inner.boundingClientRectValues(frame);+ try testing.expect((try mouseHitTest(frame, rect.x, rect.y)).target == inner);+ try testing.expect((try mouseHitTest(frame, rect.x + rect.width + 1, rect.y + 1)).target == host);+ try testing.expect((try mouseHitTest(frame, rect.x + 1, rect.y + rect.height + 1)).target == host);+ try testing.expect((try mouseHitTest(frame, rect.x - 1, rect.y + 1)).target == host);+ for ([_][]const u8{ "pointer-events:none", "visibility:hidden", "display:none" }) |style| {+ try inner.setStyle(try std.fmt.allocPrint(frame.local_arena, "transform:translateX(20px);width:80px;height:60px;{s}", .{style}), frame);+ try testing.expect((try mouseHitTest(frame, rect.x + 1, rect.y + 1)).target == host);+ }+ _ = try ls.local.compileAndRun(+ \\root.innerHTML = '<div style="display:none"><button style="width:100px;height:100px">Hidden</button></div>';+ , null);+ try testing.expect((try mouseHitTest(frame, rect.x + 1, rect.y + 1)).target == host);+}++test "user_input: shadow mouse nested closed roots and window scroll share coordinates" {+ const page = try testing.pageTest("input_mouse_shadow.html", .{});+ defer page.close();+ const frame = page.frame().?;+ var ls: js.Local.Scope = undefined;+ frame.js.localScope(&ls);+ defer ls.deinit();+ const target = try ls.local.jsValueToZig(*Element, try ls.local.compileAndRun(+ \\root.innerHTML = '<div id="nested" style="transform:translateX(10px);width:150px;height:150px"></div>';+ \\const nested = root.getElementById('nested');+ \\const closedRoot = nested.attachShadow({mode:'closed'});+ \\closedRoot.innerHTML = '<button id="deep" style="transform:translateX(15px);width:60px;height:40px">Deep</button>';+ \\const deep = closedRoot.getElementById('deep');+ \\window.deepClicks = 0;+ \\deep.addEventListener('click', e => { if (e.isTrusted && e.target === deep) deepClicks++; });+ \\deep;+ , null));+ const host = frame.document.getElementById("host", frame).?;+ const host_rect = host.boundingClientRectValues(frame);+ const before = target.boundingClientRectValues(frame);+ try testing.expectEqual(host_rect.x + 25, before.x);+ try testing.expectEqual(host_rect.y + 10, before.y);+ _ = try ls.local.compileAndRun("document.body.style.width = '3000px'; document.body.style.height = '3000px'; window.scrollTo(30, 10)", null);+ const rect = target.boundingClientRectValues(frame);+ try testing.expectEqual(before.x - 30, rect.x);+ try testing.expectEqual(before.y - 10, rect.y);+ try testing.expect((try mouseHitTest(frame, rect.x + 1, rect.y + 1)).target == target);+ try triggerMousePress(frame, rect.x + 1, rect.y + 1, mouse_button.main, 1);+ try triggerMouseRelease(frame, rect.x + 1, rect.y + 1, mouse_button.main, 1);+ try testing.expect((try ls.local.compileAndRun("deepClicks === 1 && nested.shadowRoot === null", null)).isTrue());+ _ = try ls.local.compileAndRun("nested.style.display = 'none'", null);+ try testing.expect((try mouseHitTest(frame, rect.x + 1, rect.y + 1)).target == host);+}++test "user_input: shadow mouse descendants can override inherited hit exclusions" {+ const page = try testing.pageTest("input_mouse_shadow.html", .{});+ defer page.close();+ const frame = page.frame().?;+ var ls: js.Local.Scope = undefined;+ frame.js.localScope(&ls);+ defer ls.deinit();+ const target = try ls.local.jsValueToZig(*Element, try ls.local.compileAndRun(+ \\root.innerHTML = '<div style="pointer-events:none;visibility:hidden;width:150px;height:150px"><button id="enabled" style="pointer-events:auto;visibility:visible;width:60px;height:40px">Enabled</button></div>';+ \\root.getElementById('enabled');+ , null));+ const rect = target.boundingClientRectValues(frame);+ try testing.expect((try mouseHitTest(frame, rect.x + 1, rect.y + 1)).target == target);+}++test "user_input: shadow mouse keeps host boundary path and common click target" {+ for ([_][]const u8{ "open", "closed" }) |mode| {+ const page = try testing.pageTest("input_mouse_shadow.html", .{});+ defer page.close();+ const frame = page.frame().?;+ var ls: js.Local.Scope = undefined;+ frame.js.localScope(&ls);+ defer ls.deinit();+ _ = try ls.local.compileAndRun(try std.fmt.allocPrint(frame.local_arena, "window.boundaryMode = '{s}'", .{mode}), null);+ const inner = try ls.local.jsValueToZig(*Element, try ls.local.compileAndRun(+ \\document.body.innerHTML = '<div id="boundaryHost" style="transform:translateX(80px);width:200px;height:200px"></div>';+ \\const boundaryHost = document.getElementById('boundaryHost');+ \\const boundaryRoot = boundaryHost.attachShadow({mode:boundaryMode});+ \\boundaryRoot.innerHTML = '<button id="boundaryInner" style="transform:translateX(20px);width:80px;height:60px">Inner</button>';+ \\const boundaryInner = boundaryRoot.getElementById('boundaryInner');+ \\window.enters = []; window.leaves = []; window.clicks = [];+ \\boundaryHost.addEventListener('mouseenter', () => enters.push('mouse'));+ \\boundaryHost.addEventListener('pointerenter', () => enters.push('pointer'));+ \\boundaryHost.addEventListener('mouseleave', () => leaves.push('mouse'));+ \\boundaryHost.addEventListener('pointerleave', () => leaves.push('pointer'));+ \\boundaryInner.addEventListener('click', e => clicks.push({where:'inner', target:e.target.id, trusted:e.isTrusted}));+ \\boundaryHost.addEventListener('click', e => clicks.push({where:'host', target:e.target.id, trusted:e.isTrusted, inner:e.composedPath().includes(boundaryInner)}));+ \\boundaryInner;+ , null));+ const host = frame.document.getElementById("boundaryHost", frame).?;+ const rect = inner.boundingClientRectValues(frame);+ const host_rect = host.boundingClientRectValues(frame);+ try triggerMouseMove(frame, rect.x + 1, rect.y + 1);+ try testing.expect((try ls.local.compileAndRun("enters.join(',') === 'pointer,mouse' && leaves.length === 0", null)).isTrue());+ // Moving within the host does not leave or re-enter it.+ try triggerMouseMove(frame, host_rect.x + 1, host_rect.y + 1);+ try triggerMouseMove(frame, rect.x + 1, rect.y + 1);+ try testing.expect((try ls.local.compileAndRun("enters.length === 2 && leaves.length === 0", null)).isTrue());+ try triggerMousePress(frame, rect.x + 1, rect.y + 1, mouse_button.main, 1);+ try triggerMouseRelease(frame, rect.x + 1, rect.y + 1, mouse_button.main, 1);+ try testing.expect((try ls.local.compileAndRun(+ \\clicks.length === 2 && clicks[0].where === 'inner' && clicks[0].target === 'boundaryInner' &&+ \\clicks[1].where === 'host' && clicks[1].target === 'boundaryHost' &&+ \\clicks[1].inner === (boundaryMode === 'open') && clicks.every(e => e.trusted)+ , null)).isTrue());+ _ = try ls.local.compileAndRun("clicks = []", null);+ try triggerMousePress(frame, host_rect.x + 1, host_rect.y + 1, mouse_button.main, 1);+ try triggerMouseRelease(frame, rect.x + 1, rect.y + 1, mouse_button.main, 1);+ try testing.expect((try ls.local.compileAndRun("clicks.length === 1 && clicks[0].where === 'host' && clicks[0].trusted", null)).isTrue());+ try triggerMouseMove(frame, -1, -1);+ try testing.expect((try ls.local.compileAndRun("leaves.join(',') === 'pointer,mouse'", null)).isTrue());+ }+}++test "user_input: shadow mouse wheel preserves outer scroll container" {+ const page = try testing.pageTest("input_mouse_shadow.html", .{});+ defer page.close();+ const frame = page.frame().?;+ var ls: js.Local.Scope = undefined;+ frame.js.localScope(&ls);+ defer ls.deinit();+ const inner = try ls.local.jsValueToZig(*Element, try ls.local.compileAndRun(+ \\const scroller = document.createElement('div');+ \\scroller.id = 'scroller'; scroller.style = 'overflow:auto;width:400px;height:100px';+ \\host.before(scroller); scroller.appendChild(host);+ \\inner;+ , null));+ const rect = inner.boundingClientRectValues(frame);+ const scroller = frame.document.getElementById("scroller", frame).?;+ try testing.expect(scroller.getScrollHeight(frame) > scroller.getClientHeight(frame));+ try triggerMouseWheel(frame, rect.x + 1, rect.y + 1, 0, 20);+ try testing.expectEqual(@as(u32, 20), scroller.getScrollTop(frame));+ try testing.expectEqual(@as(u32, 0), frame.window.getScrollY());+}++test "user_input: shadow mouse press and release on shadow siblings clicks the host" {+ const page = try testing.pageTest("input_mouse_shadow.html", .{});+ defer page.close();+ const frame = page.frame().?;+ var ls: js.Local.Scope = undefined;+ frame.js.localScope(&ls);+ defer ls.deinit();+ const other = try ls.local.jsValueToZig(*Element, try ls.local.compileAndRun(+ \\const other = document.createElement('button');+ \\other.style = 'width:50px;height:60px'; other.textContent = 'Other'; root.appendChild(other);+ \\other.addEventListener('click', () => events.push({listener:'other'}));+ \\other;+ , null));+ const inner = try ls.local.jsValueToZig(*Element, try ls.local.compileAndRun("inner", null));+ const start = inner.boundingClientRectValues(frame);+ const end = other.boundingClientRectValues(frame);+ try testing.expect((try mouseHitTest(frame, start.x + 1, start.y + 1)).target == inner);+ try testing.expect((try mouseHitTest(frame, end.x + end.width - 1, end.y + 1)).target == other);+ try triggerMousePress(frame, start.x + 1, start.y + 1, mouse_button.main, 1);+ try triggerMouseRelease(frame, end.x + end.width - 1, end.y + 1, mouse_button.main, 1);+ try testing.expect((try ls.local.compileAndRun("events.length === 1 && events[0].listener === 'host' && events[0].trusted", null)).isTrue());+}diff --git a/src/browser/tests/document/element_from_point_shadow.html b/src/browser/tests/document/element_from_point_shadow.htmlnew file mode 100644index 000000000..5cc7302db--- /dev/null+++ b/src/browser/tests/document/element_from_point_shadow.html@@ -0,0 +1,67 @@+<!DOCTYPE html>+<script src="../testing.js"></script>++<body>+ <div id="host" style="width:200px;height:200px"></div>+ <div id="slot_host"><span id="slotted">Slotted</span><span id="unslotted" slot="nowhere">Unslotted</span></div>+ <div id="after">After</div>+</body>++<script id="shadow_content_laid_out_in_host">+{+ const host = document.getElementById('host');+ const root = host.attachShadow({mode: 'open'});+ root.innerHTML = '<button id="shadowButton" style="width:100px;height:100px">Shadow</button>';+ const button = root.getElementById('shadowButton');++ const h = host.getBoundingClientRect();+ const b = button.getBoundingClientRect();+ // shadow content is laid out inside its host+ testing.expectEqual(true, b.x >= h.x && b.x + b.width <= h.x + h.width);+ testing.expectEqual(true, b.y >= h.y && b.y + b.height <= h.y + h.height);++ // The document-level API sees only its own tree: a hit on shadow content+ // retargets to the host, as in Chrome.+ const x = b.x + 1;+ const y = b.y + 1;+ testing.expectEqual(host, document.elementFromPoint(x, y));+ testing.expectEqual(host, document.elementsFromPoint(x, y)[0]);+}+</script>++<script id="slotted_content_laid_out_in_slot">+{+ const host = document.getElementById('slot_host');+ const root = host.attachShadow({mode: 'open'});+ root.innerHTML = '<p id="before">Before</p><slot></slot>';+ const before = root.getElementById('before');+ const slotted = document.getElementById('slotted');++ const hy = host.getBoundingClientRect().y;+ const by = before.getBoundingClientRect().y;+ const ly = slotted.getBoundingClientRect().y;+ // the slotted span comes after the shadow <p> that precedes its slot+ testing.expectEqual(true, by >= hy);+ testing.expectEqual(true, ly > by);++ const r = slotted.getBoundingClientRect();+ testing.expectEqual(slotted, document.elementFromPoint(r.x + 1, r.y + 1));++ // positions after the host follow the flat tree too+ const after = document.getElementById('after');+ testing.expectEqual(true, after.getBoundingClientRect().y > ly);+}+</script>++<script id="shadow_content_extends_document">+{+ const host = document.createElement('div');+ document.body.appendChild(host);+ const root = host.attachShadow({mode: 'open'});+ root.innerHTML = '<div></div>'.repeat(400) + '<button id="last">Last</button>';+ const last = root.getElementById('last');++ const bottom = last.getBoundingClientRect().bottom + window.scrollY;+ testing.expectEqual(true, document.scrollingElement.scrollHeight >= bottom);+}+</script>diff --git a/src/browser/tests/input_mouse_shadow.html b/src/browser/tests/input_mouse_shadow.htmlnew file mode 100644index 000000000..0bc7d736b--- /dev/null+++ b/src/browser/tests/input_mouse_shadow.html@@ -0,0 +1,13 @@+<!DOCTYPE html>+<html><head><title>Native shadow mouse input</title></head><body>+<div id="host" style="transform:translateX(80px);width:200px;height:200px"></div>+<script>+const host = document.getElementById('host');+const root = host.attachShadow({mode:'open'});+root.innerHTML = '<button id="inner" style="transform:translateX(20px);width:80px;height:60px">Shadow</button>';+const inner = root.getElementById('inner');+window.events = [];+inner.addEventListener('click', e => events.push({listener:'inner', target:e.target.id, trusted:e.isTrusted}));+host.addEventListener('click', e => events.push({listener:'host', target:e.target.id, trusted:e.isTrusted, inner:e.composedPath().includes(inner)}));+</script>+</body></html>diff --git a/src/browser/webapi/Document.zig b/src/browser/webapi/Document.zigindex 3c98b5377..d2e576510 100644--- a/src/browser/webapi/Document.zig+++ b/src/browser/webapi/Document.zig@@ -36,6 +36,7 @@ const Location = @import("Location.zig");const collections = @import("collections.zig");const Selector = @import("selector/Selector.zig");const DOMTreeWalker = @import("DOMTreeWalker.zig");+const TreeWalker = @import("TreeWalker.zig");const DOMNodeIterator = @import("DOMNodeIterator.zig");const DOMImplementation = @import("DOMImplementation.zig");const StyleSheetList = @import("css/StyleSheetList.zig");@@ -430,7 +431,7 @@ pub fn getElementById(self: *Document, id: []const u8, frame: *Frame) ?*Element//ID was removed but might have duplicatesif (self._removed_ids.remove(id)) {- var tw = @import("TreeWalker.zig").Full.Elements.init(self.asNode(), .{});+ var tw = TreeWalker.Full.Elements.init(self.asNode(), .{});while (tw.next()) |el| {const element_id = el.getId() orelse continue;if (std.mem.eql(u8, element_id, id)) {@@ -504,11 +505,12 @@ pub fn extent(self: *Document) Extent {// its auto-height ancestors count as 5px each. Body's own children are// stacked below instead. Only inline heights: virtualizers set theirs// inline, and the cascade per element is too slow on every mutation.+ // Walks the flat tree, the order Element positions are numbered in.var index: f64 = 0;- var tw = @import("TreeWalker.zig").Full.init(self.asNode(), .{});+ var tw: TreeWalker.Flat = .init(self.asNode(), .{ .frame = frame });while (tw.next()) |node| : (index += 1) {const el = node.is(Element) orelse continue;- const parent = el.parentElement() orelse continue;+ const parent = el.asNode().flatTreeParentElement(frame) orelse continue;if (parent.isRootContainer()) {continue;}@@ -523,8 +525,8 @@ pub fn extent(self: *Document) Extent {const body = html_body.asElement();size.height = @max(size.height, body.contentAxis(frame, .height), style_manager.inlineSize(body, .height) orelse 0);size.width = style_manager.inlineSize(body, .width) orelse 0;- var child = body.asNode().firstChild();- while (child) |node| : (child = node.nextSibling()) {+ var children: TreeWalker.FlatChildren = .init(body.asNode(), .{ .frame = frame });+ while (children.next()) |node| {const el = node.is(Element) orelse continue;if (!style_manager.hasDisplayNone(el)) {size.width = @max(size.width, el.getElementAxis(frame, .width).value);@@ -950,19 +952,37 @@ pub fn moveBefore(self: *Document, node: js.Value, child: js.Value, frame: *Framreturn self.asNode().moveBefore(node, child, frame);}-pub fn elementFromPoint(self: *Document, x: f64, y: f64, frame: *Frame) !?*Element {- return self.elementFromPointImpl(x, y, false, frame);+/// The deepest element at the point, shadow trees included+pub fn hitTest(self: *Document, x: f64, y: f64, frame: *Frame) !?*Element {+ return self.hitTestImpl(x, y, false, frame);+}++// document.elementFromPoint only sees the document's tree: a hit inside a+// shadow tree reports its outermost host, as in Chrome.+fn elementFromPoint(self: *Document, x: f64, y: f64, frame: *Frame) !?*Element {+ const hit = (try self.hitTest(x, y, frame)) orelse return null;+ return retargetToDocumentTree(hit);+}++fn retargetToDocumentTree(element: *Element) *Element {+ var current = element;+ while (current.asNode().containingShadowRoot()) |shadow| {+ current = shadow._host;+ }+ return current;}// The faux layout gives most elements no useful horizontal extent, so// viewport-relative hit-testing (WebDriver scroll actions) matches on the// vertical axis only.-pub fn elementFromVerticalPoint(self: *Document, y: f64, frame: *Frame) !?*Element {- return self.elementFromPointImpl(0, y, true, frame);+pub fn hitTestVertical(self: *Document, y: f64, frame: *Frame) !?*Element {+ return self.hitTestImpl(0, y, true, frame);}-fn elementFromPointImpl(self: *Document, viewport_x: f64, viewport_y: f64, ignore_x: bool, frame: *Frame) !?*Element {- // DFS in document order; topmost = last visited element whose rect contains (x, y).+fn hitTestImpl(self: *Document, viewport_x: f64, viewport_y: f64, ignore_x: bool, frame: *Frame) !?*Element {+ // DFS in flat-tree order (shadow content inside its host, slotted nodes+ // inside their slot, as Element.calculateDocumentPosition lays them out);+ // topmost = last visited element whose rect contains (x, y).//// Faux-layout shortcut: rect.top is calculateDocumentPosition × 5, which is// monotonically increasing in document order. So we maintain a running@@ -1020,12 +1040,13 @@ fn elementFromPointImpl(self: *Document, viewport_x: f64, viewport_y: f64, ignor}}- // Add children to stack in reverse order so we process them in document order- var child = node.lastChild();- while (child) |c| {+ // Push the children, then reverse them so they pop in flat-tree order+ const first = stack.items.len;+ var children: TreeWalker.FlatChildren = .init(node, .{ .frame = frame });+ while (children.next()) |c| {try stack.append(frame.local_arena, .{ .node = c, .hidden = hidden });- child = c.previousSibling();}+ std.mem.reverse(Entry, stack.items[first..]);}return topmost;@@ -1047,7 +1068,7 @@ fn elementsFromPoint(self: *Document, x: f64, y: f64, frame: *Frame) ![]const *E}fn getDocType(self: *Document) ?*Node {- var tw = @import("TreeWalker.zig").Full.init(self.asNode(), .{});+ var tw = TreeWalker.Full.init(self.asNode(), .{});while (tw.next()) |node| {if (node._type == .document_type) {return node;diff --git a/src/browser/webapi/Element.zig b/src/browser/webapi/Element.zigindex d3a25023d..a7cea90eb 100644--- a/src/browser/webapi/Element.zig+++ b/src/browser/webapi/Element.zig@@ -27,8 +27,8 @@ const text_measure = @import("../text_measure.zig");const CSS = @import("CSS.zig");const Node = @import("Node.zig");-const TreeWalker = @import("TreeWalker.zig");const ShadowRoot = @import("ShadowRoot.zig");+const TreeWalker = @import("TreeWalker.zig");const EventTarget = @import("EventTarget.zig");const collections = @import("collections.zig");const Sanitizer = @import("Sanitizer.zig");@@ -1740,7 +1740,7 @@ pub fn boundingClientRectValuesForVisible(self: *Element, frame: *Frame) DOMRectconst window = (self.ownerFrame(frame) orelse frame).window;return .{.x = self.horizontalPosition(frame) - @as(f64, @floatFromInt(window.getScrollX())),- .y = calculateDocumentPosition(self.asNode()) - @as(f64, @floatFromInt(window.getScrollY())),+ .y = calculateDocumentPosition(self.asNode(), frame) - @as(f64, @floatFromInt(window.getScrollY())),.width = self.boxAxis(frame, .width),.height = self.boxAxis(frame, .height),};@@ -1795,7 +1795,8 @@ pub fn scrollContainer(self: *Element, axes: ScrollAxes, frame: *Frame) ScrollTaconst owner = self.ownerFrame(frame) orelse return .viewport;const style_manager = &owner._style_manager;var current: ?*Element = self;- while (current) |el| : (current = el.parentElement()) {+ // Shadow content scrolls its host's containers: walk the flat tree.+ while (current) |el| : (current = el.asNode().flatTreeParentElement(frame)) {if (el.isRootContainer()) break;const scrolls = style_manager.overflowAxes(el);if ((axes.x and scrolls.x) or (axes.y and scrolls.y)) {@@ -1896,8 +1897,8 @@ pub fn contentAxis(self: *Element, frame: *Frame, comptime axis: Axis) f64 {}}- var child = self.asNode().firstChild();- while (child) |node| : (child = node.nextSibling()) {+ var children: TreeWalker.FlatChildren = .init(self.asNode(), .{ .frame = frame });+ while (children.next()) |node| {if (node.is(Element)) |el| {if (!style_manager.hasDisplayNone(el)) {total += el.getElementAxis(frame, axis).value;@@ -1935,7 +1936,7 @@ pub fn getOffsetTop(self: *Element, frame: *Frame) f64 {if (!self.isVisible(frame)) {return 0.0;}- return calculateDocumentPosition(self.asNode());+ return calculateDocumentPosition(self.asNode(), frame);}pub fn getOffsetLeft(self: *Element, frame: *Frame) f64 {@@ -2025,18 +2026,17 @@ pub fn getClientLeft(_: *Element) f64 {// - Linear scaling: 5px per node// - Perfect document order, guaranteed unique positions// - Compact coordinates (1000 nodes ≈ 5,000px)-fn calculateDocumentPosition(node: *Node) f64 {+fn calculateDocumentPosition(node: *Node, frame: *const Frame) f64 {var position: f64 = 0.0;var current = node;// Walk up to root, counting preceding nodes- while (current.parentNode()) |parent| {+ while (current.flatParent(frame)) |parent| {// Count all previous siblings and their descendants- var sibling = parent.firstChild();- while (sibling) |s| {+ var siblings: TreeWalker.FlatChildren = .init(parent, .{ .frame = frame });+ while (siblings.next()) |s| {if (s == current) break;- position += countSubtreeNodes(s);- sibling = s.nextSibling();+ position += countSubtreeNodes(s, frame);}// Count the parent itself@@ -2047,11 +2047,11 @@ fn calculateDocumentPosition(node: *Node) f64 {return position * 5.0; // 5px per node}-// Counts total nodes in a subtree (node + all descendants)-fn countSubtreeNodes(node: *Node) f64 {+// Counts total nodes in a flat-tree subtree (node + all descendants)+fn countSubtreeNodes(node: *Node, frame: *const Frame) f64 {var count: f64 = 0;- var tw = TreeWalker.Full.init(node, .{});- while (tw.next()) |_| {+ var walker: TreeWalker.Flat = .init(node, .{ .frame = frame });+ while (walker.next()) |_| {count += 1;}return count;@@ -2073,14 +2073,14 @@ pub fn horizontalPosition(self: *Element, frame: *Frame) f64 {x += CSS.parseTranslateX(style.asCSSStyleDeclaration().getPropertyValue("transform", frame));}- while (current.parentNode()) |parent| {+ while (current.flatParent(frame)) |parent| {if (parent.is(Element)) |el| {if (el.inlineStyle(frame)) |style| {x += CSS.parseTranslateX(style.asCSSStyleDeclaration().getPropertyValue("transform", frame));}}- var sibling = parent.firstChild();- while (sibling) |s| : (sibling = s.nextSibling()) {+ var siblings: TreeWalker.FlatChildren = .init(parent, .{ .frame = frame });+ while (siblings.next()) |s| {if (s == current) break;if (s.is(Element)) |el| {if (!style_manager.hasDisplayNone(el)) {@@ -2150,7 +2150,7 @@ pub fn clone(self: *Element, deep: bool, document: *const Node.Document, frame:pub fn scrollIntoViewIfNeeded(self: *Element, center_if_needed: ?bool, frame: *Frame) void {_ = center_if_needed;- const y = calculateDocumentPosition(self.asNode());+ const y = calculateDocumentPosition(self.asNode(), frame);const scroll_y: f64 = @floatFromInt(frame.window.getScrollY());const viewport_height: f64 = @floatFromInt(frame.window.getInnerHeight(frame));if (y >= scroll_y and y < scroll_y + viewport_height) {@@ -2168,7 +2168,7 @@ pub fn scrollIntoView(self: *Element, opts: ?ScrollIntoViewOpts, frame: *Frame)// Scroll the window so the element's top is brought into the viewport.// Positions come from the faux-layout document position (top = preorder// depth-scaled y), the same source getBoundingClientRect uses.- const y = calculateDocumentPosition(self.asNode());+ const y = calculateDocumentPosition(self.asNode(), frame);frame.window.scrollTo(.{ .x = 0 }, @trunc(@max(0, y)), frame) catch {};}diff --git a/src/browser/webapi/Node.zig b/src/browser/webapi/Node.zigindex d45fb55cd..991b1cebd 100644--- a/src/browser/webapi/Node.zig+++ b/src/browser/webapi/Node.zig@@ -1774,6 +1774,18 @@ pub fn flatTreeParentElement(self: *Node, frame: *const Frame) ?*Element {return (parent.flatTreeParent(frame) orelse return null).is(Element);}+/// Like flatTreeParent, but never a shadow root: the parent as+/// TreeWalker.Flat walks, which doesn't visit shadow roots.+pub fn flatParent(self: *Node, frame: *const Frame) ?*Node {+ const parent = self.flatTreeParent(frame) orelse return null;+ // A shadow tree's top-level nodes have the shadow root as their parent;+ // skip to its host.+ if (parent.is(ShadowRoot)) |shadow| {+ return shadow._host.asNode();+ }+ return parent;+}+pub const JsApi = struct {pub const bridge = js.Bridge(Node);diff --git a/src/browser/webapi/TreeWalker.zig b/src/browser/webapi/TreeWalker.zigindex a0a46bc02..fdccf6d8f 100644--- a/src/browser/webapi/TreeWalker.zig+++ b/src/browser/webapi/TreeWalker.zig@@ -16,12 +16,19 @@// You should have received a copy of the GNU Affero General Public License// along with this program. If not, see <https://www.gnu.org/licenses/>.+const std = @import("std");+const Node = @import("Node.zig");const Element = @import("Element.zig");+const Frame = @import("../Frame.zig");++pub const Full = TreeWalker(.full, .dom);+pub const FullExcludeSelf = TreeWalker(.exclude_self, .dom);+pub const Children = TreeWalker(.children, .dom);-pub const Full = TreeWalker(.full);-pub const FullExcludeSelf = TreeWalker(.exclude_self);-pub const Children = TreeWalker(.children);+// Pierces the shadow roots, apply slots/fallback and skip unslotted light children+pub const Flat = TreeWalker(.full, .flat);+pub const FlatChildren = TreeWalker(.children, .flat);const Mode = enum {full,@@ -29,21 +36,29 @@ const Mode = enum {exclude_self,};-pub fn TreeWalker(comptime mode: Mode) type {+const Tree = enum {+ dom,+ flat,+};++pub fn TreeWalker(comptime mode: Mode, comptime tree: Tree) type {return struct {_current: ?*Node = null,_next: ?*Node,_root: *Node,+ _frame: if (tree == .flat) *const Frame else void,const Self = @This();- const Opts = struct {};+ const Opts = if (tree == .flat) struct { frame: *const Frame } else struct {};pub fn init(root: *Node, opts: Opts) Self {- _ = opts;- return .{- ._next = firstNext(root),+ var self: Self = .{+ ._next = null,._root = root,+ ._frame = if (comptime tree == .flat) opts.frame else {},};+ self._next = self.firstNext();+ return self;}pub fn next(self: *Self) ?*Node {@@ -51,20 +66,20 @@ pub fn TreeWalker(comptime mode: Mode) type {self._current = node;if (comptime mode == .children) {- self._next = node.nextSibling();+ self._next = self.nextSiblingOf(node);return node;}- if (node.firstChild()) |child| {+ if (self.firstChildOf(node)) |child| {self._next = child;} else {var current: *Node = node;while (current != self._root) {- if (current.nextSibling()) |sibling| {+ if (self.nextSiblingOf(current)) |sibling| {self._next = sibling;return node;}- current = current._parent orelse break;+ current = self.parentOf(current) orelse break;}self._next = null;}@@ -77,27 +92,27 @@ pub fn TreeWalker(comptime mode: Mode) type {var current: *Node = current_node;while (current != self._root) {- if (current.nextSibling()) |sibling| {+ if (self.nextSiblingOf(current)) |sibling| {self._next = sibling;return;}- current = current._parent orelse break;+ current = self.parentOf(current) orelse break;}self._next = null;}pub fn reset(self: *Self) void {self._current = null;- self._next = firstNext(self._root);+ self._next = self.firstNext();}pub fn contains(self: *const Self, target: *const Node) bool {const root = self._root;if (comptime mode == .children) {- var it = root.childrenIterator();- while (it.next()) |child| {- if (child == target) {+ var child = self.firstChildOf(root);+ while (child) |c| : (child = self.nextSiblingOf(c)) {+ if (c == target) {return true;}}@@ -113,30 +128,66 @@ pub fn TreeWalker(comptime mode: Mode) type {if (node == root) {return true;}- node = node._parent orelse return false;+ node = self.parentOf(@constCast(node)) orelse return false;}}pub fn clone(self: *const Self) Self {- const root = self._root;- return .{- ._next = firstNext(root),- ._root = root,+ var copy: Self = .{+ ._next = null,+ ._root = self._root,+ ._frame = self._frame,};+ copy._next = copy.firstNext();+ return copy;}- fn firstNext(root: *Node) ?*Node {+ fn firstNext(self: *const Self) ?*Node {return switch (comptime mode) {- .full => root,- .exclude_self => root.firstChild(),- .children => root.firstChild(),+ .full => self._root,+ .exclude_self, .children => self.firstChildOf(self._root),};}+ fn firstChildOf(self: *const Self, node: *Node) ?*Node {+ if (comptime tree == .flat) {+ if (node.is(Element)) |el| {+ if (el.hostedShadowRoot(self._frame)) |shadow| {+ return shadow.asNode().firstChild();+ }+ }+ if (node.is(Element.Html.Slot)) |slot| {+ // empty while the slot isn't in a shadow tree+ if (slot._assigned.items.len > 0) {+ return slot._assigned.items[0];+ }+ }+ }+ return node.firstChild();+ }++ fn nextSiblingOf(self: *const Self, node: *Node) ?*Node {+ if (comptime tree == .flat) {+ if (node.assignedSlot(self._frame)) |slot| {+ const assigned = slot._assigned.items;+ const i = std.mem.indexOfScalar(*Node, assigned, node) orelse return null;+ return if (i + 1 < assigned.len) assigned[i + 1] else null;+ }+ }+ return node.nextSibling();+ }++ fn parentOf(self: *const Self, node: *Node) ?*Node {+ if (comptime tree == .flat) {+ return node.flatParent(self._frame);+ }+ return node._parent;+ }+pub const Elements = struct {tw: Self,- pub fn init(root: *Node, comptime opts: Opts) Elements {+ pub fn init(root: *Node, opts: Opts) Elements {return .{.tw = Self.init(root, opts),};diff --git a/src/browser/webapi/WebDriver.zig b/src/browser/webapi/WebDriver.zigindex bdfbcf748..d3e839b5f 100644--- a/src/browser/webapi/WebDriver.zig+++ b/src/browser/webapi/WebDriver.zig@@ -243,7 +243,7 @@ fn performPointerSource(source: js.Object, frame: *Frame) !void {target = origin.local.jsValueToZig(*Element, origin) catch null;} else {const y = readI32(action, "y", 0);- if (frame.document.elementFromVerticalPoint(@floatFromInt(y), frame) catch null) |el| {+ if (frame.document.hitTestVertical(@floatFromInt(y), frame) catch null) |el| {target = el;} else if (frame.document.getDocumentElement()) |root| {target = root;@@ -333,7 +333,7 @@ fn performWheelSource(source: js.Object, frame: *Frame) !void {} else {// "viewport"/"pointer" origins: approximate hit-testing with// the faux layout's vertical axis, falling back to the root.- el = frame.document.elementFromVerticalPoint(@floatFromInt(y), frame) catch null;+ el = frame.document.hitTestVertical(@floatFromInt(y), frame) catch null;if (el == null) {el = frame.document.getDocumentElement();}