Skip to content

Lightpanda: the headless browser designed for AI and automation

refactor(input): split the touch entry points and trim the touch comments

Adrià Arrufat5f01bfe648f5
diff --git a/src/browser/EventManager.zig b/src/browser/EventManager.zig
index 14a0047fb..655d74785 100644
--- a/src/browser/EventManager.zig
+++ b/src/browser/EventManager.zig
@@ -292,7 +292,7 @@ fn dispatchNode(self: *EventManager, target: *Node, event: *Event) !void {
// DOM dispatch: decide up front — on the pre-dispatch tree, so listener
// mutations can't affect it — whether target and relatedTarget must be
// reset after dispatch because they would expose nodes inside a shadow
- // tree.
+ // tree. The same goes for a Touch's target.
if (node_path_len > 0) {
const last = path_buffer[node_path_len - 1];
if (event._needs_retargeting) {
@@ -307,12 +307,8 @@ fn dispatchNode(self: *EventManager, target: *Node, event: *Event) !void {
}
}
}
- if (event.touchTargetPtr()) |touch_ptr| {
- if (touch_ptr.*) |touch_target| {
- if (rootIsShadowRoot(getAdjustedTarget(touch_target, last))) {
- clear_targets = true;
- }
- }
+ if (event._needs_retargeting and rootIsShadowRoot(getAdjustedTarget(original_touch, last))) {
+ clear_targets = true;
}
}
diff --git a/src/browser/Frame.zig b/src/browser/Frame.zig
index 0ecfca7fd..23ee7b739 100644
--- a/src/browser/Frame.zig
+++ b/src/browser/Frame.zig
@@ -468,6 +468,11 @@ pub fn deinit(self: *Frame) void {
page.input_pointer.reset();
}
}
+ if (page.input_touch_contact) |contact| {
+ if (contact.target.ownerFrame(self) == self) {
+ page.input_touch_contact = null;
+ }
+ }
if (comptime lp.IS_DEBUG) {
log.debug(.frame, "frame.deinit", .{ .url = self.url, .type = self._type });
diff --git a/src/browser/Page.zig b/src/browser/Page.zig
index 55bdee8b5..2e8047fab 100644
--- a/src/browser/Page.zig
+++ b/src/browser/Page.zig
@@ -190,10 +190,9 @@ input_modifiers: if (lp.build_config.wpt_extensions) @import("frame/user_input.z
// The element the synthetic pointer is currently over
input_hover_target: ?*Element = null,
-// Last CDP touch contact. Empty TouchEnd/TouchCancel reuse this instead of
-// re-hit-testing at (0, 0).
+// The active touch contact; single-touch, so at most one.
input_touch_contact: ?@import("frame/user_input.zig").TouchContact = null,
-input_touch_next_pointer_id: i32 = 2,
+input_touch_next_pointer_id: i32 = @import("frame/user_input.zig").first_touch_pointer_id,
// Per-gesture button state for the synthetic mouse pointer; see
// user_input.PointerButtons.
diff --git a/src/browser/frame/user_input.zig b/src/browser/frame/user_input.zig
index 42f1e2c23..00e2ea83e 100644
--- a/src/browser/frame/user_input.zig
+++ b/src/browser/frame/user_input.zig
@@ -79,9 +79,8 @@ pub fn updateHoverTarget(frame: *Frame, to: ?*Element, ctx: HoverContext) void {
dispatchBoundaryEvents(frame, from, to, ctx);
}
-/// out and leave up from `from`, then over and enter down to `to`, the leave
-/// and enter chains stopping at their common ancestor. `emitter.emit` fires one
-/// boundary event, named by its suffix ("out", "leave", "over", "enter").
+/// `emitter.emit` fires one boundary event, named by its suffix ("out",
+/// "leave", "over", "enter").
fn dispatchBoundaryEvents(frame: *Frame, from: ?*Element, to: ?*Element, emitter: anytype) void {
const pivot: ?*Node = blk: {
const a = from orelse break :blk null;
@@ -193,12 +192,10 @@ const Gesture = struct {
x: f64 = 0,
y: f64 = 0,
modifiers: Modifiers = .{},
- emit_mouse_compat: bool = true,
pointer_type: []const u8 = "mouse",
pointer_id: i32 = 1,
width: f64 = 1,
height: f64 = 1,
- /// Reported while a button is held, 0 otherwise.
pressure: f64 = 0.5,
};
@@ -206,15 +203,15 @@ const Gesture = struct {
fn emitPointer(
frame: *Frame,
target: *Element,
- typ: []const u8,
+ comptime typ: []const u8,
g: Gesture,
detail: u32,
) !bool {
const owner = target.ownerFrame(frame) orelse frame;
- const boundary = std.mem.eql(u8, typ, "pointerenter") or std.mem.eql(u8, typ, "pointerleave");
+ const boundary = comptime std.mem.eql(u8, typ, "pointerenter") or std.mem.eql(u8, typ, "pointerleave");
const event: *PointerEvent = try .initTrusted(typ, .{
.bubbles = !boundary,
- .cancelable = !boundary and !std.mem.eql(u8, typ, "pointercancel"),
+ .cancelable = !boundary and comptime !std.mem.eql(u8, typ, "pointercancel"),
.composed = !boundary,
.clientX = g.x,
.clientY = g.y,
@@ -354,16 +351,12 @@ fn commonClickTarget(down: *Element, up: *Element) *Element {
}
pub fn moveSequence(frame: *Frame, target: *Element, g: Gesture) !void {
- if (g.emit_mouse_compat) {
- updateHoverTarget(frame, target, .{ .x = g.x, .y = g.y, .buttons = g.buttons_down, .modifiers = g.modifiers });
- }
+ updateHoverTarget(frame, target, .{ .x = g.x, .y = g.y, .buttons = g.buttons_down, .modifiers = g.modifiers });
// A move changes no button: https://www.w3.org/TR/pointerevents3/#the-button-property
var pg = g;
pg.button = -1;
_ = try emitPointer(frame, target, "pointermove", pg, 0);
- if (g.emit_mouse_compat) {
- _ = try emitMouse(frame, target, "mousemove", g, 0);
- }
+ _ = try emitMouse(frame, target, "mousemove", g, 0);
}
/// Returns whether the gesture's compat mouse events are suppressed: by the
@@ -378,10 +371,6 @@ fn pressSequence(frame: *Frame, target: *Element, g: Gesture, chord_suppressed:
_ = try emitPointer(frame, target, "pointermove", g, 0);
break :blk chord_suppressed;
};
- if (!g.emit_mouse_compat) {
- return suppressed;
- }
-
if (!suppressed) {
try mouseDown(frame, target, g);
}
@@ -404,10 +393,12 @@ fn mouseDown(frame: *Frame, target: *Element, g: Gesture) !void {
/// A null `click_target` releases without a click, as for a later release in
/// a chord.
fn releaseSequence(frame: *Frame, up_target: *Element, g: Gesture, suppressed: bool, click_target: ?*Element) !void {
- _ = try emitPointer(frame, up_target, if (g.buttons_down == 0) "pointerup" else "pointermove", g, 0);
- if (g.emit_mouse_compat) {
- try mouseUpAndClick(frame, up_target, g, suppressed, click_target);
+ if (g.buttons_down == 0) {
+ _ = try emitPointer(frame, up_target, "pointerup", g, 0);
+ } else {
+ _ = try emitPointer(frame, up_target, "pointermove", g, 0);
}
+ try mouseUpAndClick(frame, up_target, g, suppressed, click_target);
}
/// `suppressed` drops the mouseup but keeps the click, as a cancelled
@@ -608,7 +599,10 @@ fn deltaToScroll(d: f64) i32 {
return @trunc(std.math.clamp(d, std.math.minInt(i32), std.math.maxInt(i32)));
}
-/// The CDP-tracked touch contact. Single-touch scope: at most one.
+// pointerId 1 is the mouse.
+pub const first_touch_pointer_id: i32 = 2;
+const tap_slop_px = 15;
+
pub const TouchContact = struct {
target: *Element,
point: Touch.Point,
@@ -617,9 +611,8 @@ pub const TouchContact = struct {
suppress_mouse: bool = false,
suppress_click: bool = false,
- /// The touch pointer's attributes at each phase. Pressed, it reports the
- /// contact's size and force; released, a 1x1 point at no pressure; and a
- /// cancelled contact keeps its geometry.
+ /// A released contact reports a 1x1 point; a cancelled one keeps its
+ /// geometry.
fn gesture(self: TouchContact, point: Touch.Point, phase: enum { down, up, cancel }, modifiers: Modifiers) Gesture {
const released = phase == .up;
return .{
@@ -650,7 +643,7 @@ const TouchBoundary = struct {
}
};
-pub const TouchType = enum {
+const TouchType = enum {
touchstart,
touchmove,
touchend,
@@ -659,8 +652,7 @@ pub const TouchType = enum {
/// Fires the touch event on `target` (no hit-test); returns whether
/// preventDefault() cancelled it.
-pub fn dispatchTouchEvent(frame: *Frame, target: *Element, typ: TouchType, point: Touch.Point, modifiers: Modifiers) !bool {
- const active = typ == .touchstart or typ == .touchmove;
+fn dispatchTouchEvent(frame: *Frame, target: *Element, typ: TouchType, point: Touch.Point, modifiers: Modifiers) !bool {
const event: *TouchEvent = try .initTrustedWithTouch(@tagName(typ), .{
.bubbles = true,
.composed = true,
@@ -668,7 +660,7 @@ pub fn dispatchTouchEvent(frame: *Frame, target: *Element, typ: TouchType, point
.ctrlKey = modifiers.ctrl,
.metaKey = modifiers.meta,
.shiftKey = modifiers.shift,
- }, target, point, active, frame);
+ }, target, point, frame);
// touchcancel is never cancelable per spec; the others follow the same
// passive-listener-dependent rule as wheel (see EventManager).
@@ -679,15 +671,15 @@ pub fn dispatchTouchEvent(frame: *Frame, target: *Element, typ: TouchType, point
return frame._event_manager.dispatchCancelable(target.asEventTarget(), event.asEvent());
}
-/// touchstart or touchmove. `target` names the touchstart element, for
-/// WebDriver actions that have an element and no viewport point; null
-/// hit-tests the point instead. A point that misses every element falls back
-/// to the document element rather than dropping the contact, as WebDriver's
-/// pointerMove does. touchmove stays pinned to the contact either way.
-pub fn triggerTouch(frame: *Frame, target: ?*Element, typ: TouchType, point: Touch.Point, modifiers: Modifiers) !void {
+/// A point that misses every element falls back to the document element, as
+/// WebDriver's pointerMove does, rather than dropping the contact. `target`
+/// replaces the hit-test for WebDriver, whose actions have no viewport point.
+pub fn touchStart(frame: *Frame, target: ?*Element, point: Touch.Point, modifiers: Modifiers) !void {
const page = frame.page;
- const pinned = if (typ == .touchstart) null else if (page.input_touch_contact) |c| c.target else null;
- const resolved = pinned orelse target orelse
+ if (page.input_touch_contact != null) {
+ return;
+ }
+ const resolved = target orelse
(try frame.window._document.elementFromPoint(point.x, point.y, frame)) orelse
frame.window._document.getDocumentElement() orelse return;
if (comptime lp.IS_DEBUG) {
@@ -699,28 +691,38 @@ pub fn triggerTouch(frame: *Frame, target: ?*Element, typ: TouchType, point: Tou
.type = frame._type,
});
}
- var contact: TouchContact = if (typ == .touchstart) .{
+ var contact: TouchContact = .{
.target = resolved,
.point = point,
.start = point,
.pointer_id = page.input_touch_next_pointer_id,
- } else page.input_touch_contact orelse return;
+ };
+ page.input_touch_next_pointer_id = if (contact.pointer_id == std.math.maxInt(i32)) first_touch_pointer_id else contact.pointer_id + 1;
+ const g = contact.gesture(point, .down, modifiers);
+ dispatchBoundaryEvents(frame, null, resolved, TouchBoundary{ .g = g });
+ contact.suppress_mouse = try emitPointer(frame, resolved, "pointerdown", g, 0);
+ contact.suppress_click = try dispatchTouchEvent(frame, resolved, .touchstart, point, modifiers);
+ page.input_touch_contact = contact;
+}
+
+/// Stays on the touchstart element. A drag never activates: past the slop, or
+/// for WebDriver, which has no viewport distance, onto another element `over`.
+pub fn touchMove(frame: *Frame, over: ?*Element, point: Touch.Point, modifiers: Modifiers) !void {
+ const page = frame.page;
+ var contact = page.input_touch_contact orelse return;
contact.point = point;
+ const dx = point.x - contact.start.x;
+ const dy = point.y - contact.start.y;
+ const moved_off = if (over) |el| el != contact.target else false;
+ if (moved_off or dx * dx + dy * dy > tap_slop_px * tap_slop_px) {
+ contact.suppress_click = true;
+ }
var g = contact.gesture(point, .down, modifiers);
- if (typ == .touchstart) {
- page.input_touch_next_pointer_id = if (contact.pointer_id == std.math.maxInt(i32)) 2 else contact.pointer_id + 1;
- dispatchBoundaryEvents(frame, null, resolved, TouchBoundary{ .g = g });
- contact.suppress_mouse = try emitPointer(frame, resolved, "pointerdown", g, 0);
- } else {
- // Keep small finger jitter tappable, but never activate after a drag.
- const dx = point.x - contact.start.x;
- const dy = point.y - contact.start.y;
- contact.suppress_click = contact.suppress_click or dx * dx + dy * dy > 15 * 15;
- g.button = -1;
- _ = try emitPointer(frame, resolved, "pointermove", g, 0);
- }
- const prevented = try dispatchTouchEvent(frame, resolved, typ, point, modifiers);
- contact.suppress_click = contact.suppress_click or prevented;
+ g.button = -1;
+ _ = try emitPointer(frame, contact.target, "pointermove", g, 0);
+ if (try dispatchTouchEvent(frame, contact.target, .touchmove, point, modifiers)) {
+ contact.suppress_click = true;
+ }
page.input_touch_contact = contact;
}
@@ -734,36 +736,21 @@ pub fn touchHover(frame: *Frame, target: *Element, modifiers: Modifiers) !void {
}, 0);
}
-/// touchend or touchcancel, then for a tap the compatibility mouse events and
-/// click.
-///
-/// Playwright sends an empty touchPoints list, so there's nowhere to read a
-/// release position from but the stored contact. Puppeteer sends the point
-/// being released, and Chrome dispatches at that wire position rather than
-/// the last-seen one, so `point` (when given) wins over the stored
-/// coordinates.
-///
-/// The compatibility events hit-test the release point, after touchend
-/// listeners have had a chance to change the DOM, while pointer and touch
-/// delivery stays pinned to the contact. `compat_target` replaces that
-/// hit-test for WebDriver, whose actions have no viewport point.
-pub fn triggerTouchLift(frame: *Frame, typ: TouchType, point: ?Touch.Point, modifiers: Modifiers, compat_target: ?*Element) !void {
+/// Puppeteer sends the released point and Chrome dispatches there; Playwright
+/// sends none, so the stored contact is used. The compatibility mouse events
+/// hit-test the release point; `compat_target` replaces that for WebDriver.
+pub fn touchEnd(frame: *Frame, point: ?Touch.Point, modifiers: Modifiers, compat_target: ?*Element) !void {
const contact = frame.page.input_touch_contact orelse return;
- // Consume the state before the fallible dispatch, so a dispatch that
- // fails partway through (e.g. a listener throws) can't leave a stale
- // contact that locks out every future touchStart for this page.
+ // Cleared before dispatch so a throwing listener can't leave a stale
+ // contact blocking every later touchStart.
frame.page.input_touch_contact = null;
- // The lift keeps the contact's id whatever the client re-sent, so a
- // released point can move the position but not rename the contact.
- var lift = point orelse contact.point;
- lift.id = contact.point.id;
-
- const cancelled = typ == .touchcancel;
- const g = contact.gesture(lift, if (cancelled) .cancel else .up, modifiers);
- _ = try emitPointer(frame, contact.target, if (cancelled) "pointercancel" else "pointerup", g, 0);
+ const lift = point orelse contact.point;
+
+ const g = contact.gesture(lift, .up, modifiers);
+ _ = try emitPointer(frame, contact.target, "pointerup", g, 0);
dispatchBoundaryEvents(frame, contact.target, null, TouchBoundary{ .g = g });
- const prevented = try dispatchTouchEvent(frame, contact.target, typ, lift, modifiers);
- if (cancelled or contact.suppress_click or prevented) return;
+ const prevented = try dispatchTouchEvent(frame, contact.target, .touchend, lift, modifiers);
+ if (contact.suppress_click or prevented) return;
var target = try touchCompatTarget(frame, lift, compat_target) orelse return;
updateHoverTarget(frame, target, .{ .x = lift.x, .y = lift.y, .modifiers = modifiers, .with_pointer = false });
@@ -786,9 +773,15 @@ pub fn triggerTouchLift(frame: *Frame, typ: TouchType, point: ?Touch.Point, modi
try mouseUpAndClick(frame, up_target, g, false, click_target);
}
-/// The element the tap's compatibility mouse events hit. A caller-supplied
-/// element wins; otherwise the release point is hit-tested, and a miss drops
-/// the click.
+pub fn touchCancel(frame: *Frame, modifiers: Modifiers) !void {
+ const contact = frame.page.input_touch_contact orelse return;
+ frame.page.input_touch_contact = null;
+ const g = contact.gesture(contact.point, .cancel, modifiers);
+ _ = try emitPointer(frame, contact.target, "pointercancel", g, 0);
+ dispatchBoundaryEvents(frame, contact.target, null, TouchBoundary{ .g = g });
+ _ = try dispatchTouchEvent(frame, contact.target, .touchcancel, contact.point, modifiers);
+}
+
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);
@@ -1488,3 +1481,100 @@ pub const Modifiers = struct {
alt: bool = false,
meta: bool = false,
};
+
+const testing = @import("../../testing.zig");
+
+test "user_input: dispatchTouchEvent touchcancel is never cancelable" {
+ const page = try testing.pageTest("mcp_actions.html", .{});
+ defer page.close();
+ const frame = page.frame().?;
+ var ls: js.Local.Scope = undefined;
+ frame.js.localScope(&ls);
+ defer ls.deinit();
+ var tc: js.TryCatch = undefined;
+ tc.init(&ls.local);
+ defer tc.deinit();
+
+ const value = try ls.local.compileAndRun(
+ \\const t = document.getElementById('hoverTarget');
+ \\t.addEventListener('touchcancel', e => {
+ \\ e.preventDefault();
+ \\ window.result = !e.cancelable && !e.defaultPrevented;
+ \\}, {passive: false});
+ \\t;
+ , null);
+ const target = try ls.local.jsValueToZig(*Element, value);
+ _ = try dispatchTouchEvent(frame, target, .touchcancel, .{ .x = 10, .y = 20 }, .{});
+ try testing.expect((try ls.local.compileAndRun("window.result === true", null)).isTrue());
+}
+
+test "user_input: dispatchTouchEvent a passive-only touchstart listener is not cancelable" {
+ const page = try testing.pageTest("mcp_actions.html", .{});
+ defer page.close();
+ const frame = page.frame().?;
+ var ls: js.Local.Scope = undefined;
+ frame.js.localScope(&ls);
+ defer ls.deinit();
+ var tc: js.TryCatch = undefined;
+ tc.init(&ls.local);
+ defer tc.deinit();
+
+ const value = try ls.local.compileAndRun(
+ \\const t = document.getElementById('hoverTarget');
+ \\t.addEventListener('touchstart', e => { window.result = !e.cancelable; }, {passive: true});
+ \\t;
+ , null);
+ const target = try ls.local.jsValueToZig(*Element, value);
+ _ = try dispatchTouchEvent(frame, target, .touchstart, .{ .x = 10, .y = 20 }, .{});
+ try testing.expect((try ls.local.compileAndRun("window.result === true", null)).isTrue());
+}
+
+test "user_input: dispatchTouchEvent a non-passive listener makes touchstart cancelable" {
+ const page = try testing.pageTest("mcp_actions.html", .{});
+ defer page.close();
+ const frame = page.frame().?;
+ var ls: js.Local.Scope = undefined;
+ frame.js.localScope(&ls);
+ defer ls.deinit();
+ var tc: js.TryCatch = undefined;
+ tc.init(&ls.local);
+ defer tc.deinit();
+
+ const value = try ls.local.compileAndRun(
+ \\const t = document.getElementById('hoverTarget');
+ \\t.addEventListener('touchstart', e => { window.result = e.cancelable; });
+ \\t;
+ , null);
+ const target = try ls.local.jsValueToZig(*Element, value);
+ _ = try dispatchTouchEvent(frame, target, .touchstart, .{ .x = 10, .y = 20 }, .{});
+ try testing.expect((try ls.local.compileAndRun("window.result === true", null)).isTrue());
+}
+
+test "user_input: dispatchTouchEvent a closed-shadow touch target retargets to the host" {
+ const page = try testing.pageTest("mcp_actions.html", .{});
+ defer page.close();
+ const frame = page.frame().?;
+ var ls: js.Local.Scope = undefined;
+ frame.js.localScope(&ls);
+ defer ls.deinit();
+ var tc: js.TryCatch = undefined;
+ tc.init(&ls.local);
+ defer tc.deinit();
+
+ const value = try ls.local.compileAndRun(
+ \\const host = document.createElement('div');
+ \\document.body.appendChild(host);
+ \\const root = host.attachShadow({mode: 'closed'});
+ \\const inner = document.createElement('button');
+ \\root.appendChild(inner);
+ \\host.addEventListener('touchstart', e => {
+ \\ window.eventTargetOK = e.target === host;
+ \\ window.touchTargetOK = e.touches[0].target === host;
+ \\});
+ \\inner;
+ , null);
+ const target = try ls.local.jsValueToZig(*Element, value);
+ _ = try dispatchTouchEvent(frame, target, .touchstart, .{ .x = 10, .y = 20 }, .{});
+ const result = try ls.local.compileAndRun("window.eventTargetOK === true && window.touchTargetOK === true", null);
+ try testing.expect(result.isTrue());
+}
diff --git a/src/browser/webapi/WebDriver.zig b/src/browser/webapi/WebDriver.zig
index 0a5bcd702..8706533d2 100644
--- a/src/browser/webapi/WebDriver.zig
+++ b/src/browser/webapi/WebDriver.zig
@@ -211,9 +211,8 @@ fn performPointerSource(source: js.Object, frame: *Frame) !void {
}
const actions = actions_val.toArray();
- // A touch pointer shares CDP's single-contact sequence (pointer boundary
- // events, the touch event, then the compatibility mouse events and click).
- // The element comes from the action origin: actions carry no viewport point.
+ // Touch actions carry no viewport point, so the element comes from the
+ // action origin.
var is_touch = false;
const params = try source.get("parameters");
if (params.isObject()) {
@@ -254,71 +253,61 @@ fn performPointerSource(source: js.Object, frame: *Frame) !void {
if (is_touch) {
if (frame.page.input_touch_contact) |contact| {
// Touch implicitly captures the original down target.
- const captured = contact.target;
- const owner = captured.ownerFrame(frame) orelse continue;
- Frame.user_input.triggerTouch(owner, null, .touchmove, .{ .x = 0, .y = 0 }, frame.page.input_modifiers) catch |err| {
+ const owner = contact.target.ownerFrame(frame) orelse continue;
+ Frame.user_input.touchMove(owner, el, .{ .x = 0, .y = 0 }, frame.page.input_modifiers) catch |err| {
log.debug(.app, "webdriver touch", .{ .err = err });
};
- // No viewport distance, so a move whose origin element
- // changed is the drag that keeps the tap from clicking.
- if (el != captured) {
- if (frame.page.input_touch_contact) |*held| held.suppress_click = true;
- }
} else {
const owner = el.ownerFrame(frame) orelse continue;
Frame.user_input.touchHover(owner, el, frame.page.input_modifiers) catch |err| {
log.debug(.app, "webdriver touch", .{ .err = err });
};
}
- } else {
- Frame.user_input.moveSequence(frame, el, .{
- .buttons_down = pointer.held,
- .modifiers = frame.page.input_modifiers,
- }) catch {};
+ continue;
}
+ Frame.user_input.moveSequence(frame, el, .{
+ .buttons_down = pointer.held,
+ .modifiers = frame.page.input_modifiers,
+ }) catch {};
} else if (action_type.eql(comptime .wrap("pointerDown"))) {
const el = target orelse continue;
- const button = readI32(action, "button", 0);
- if (last_click_target == el and last_click_button == button) {
- click_count += 1;
- } else {
- click_count = 1;
- }
if (is_touch) {
- // One contact. A second pointerDown while it is still down would
- // fire another touchstart for the same finger.
- if (frame.page.input_touch_contact != null) continue;
const owner = el.ownerFrame(frame) orelse continue;
- Frame.user_input.triggerTouch(owner, el, .touchstart, .{ .x = 0, .y = 0 }, frame.page.input_modifiers) catch |err| {
+ Frame.user_input.touchStart(owner, el, .{ .x = 0, .y = 0 }, frame.page.input_modifiers) catch |err| {
log.debug(.app, "webdriver touch", .{ .err = err });
};
+ continue;
+ }
+ const button = readI32(action, "button", 0);
+ if (last_click_target == el and last_click_button == button) {
+ click_count += 1;
} else {
- pointer.press(frame, el, .{
- .button = button,
- .click_count = click_count,
- .modifiers = frame.page.input_modifiers,
- }) catch {};
+ click_count = 1;
}
+ pointer.press(frame, el, .{
+ .button = button,
+ .click_count = click_count,
+ .modifiers = frame.page.input_modifiers,
+ }) catch {};
} else if (action_type.eql(comptime .wrap("pointerUp"))) {
- const el = target orelse continue;
- const button = readI32(action, "button", 0);
if (is_touch) {
const contact = frame.page.input_touch_contact orelse continue;
- const captured = contact.target;
- const owner = captured.ownerFrame(frame) orelse continue;
- Frame.user_input.triggerTouchLift(owner, .touchend, null, frame.page.input_modifiers, captured) catch |err| {
+ const owner = contact.target.ownerFrame(frame) orelse continue;
+ Frame.user_input.touchEnd(owner, null, frame.page.input_modifiers, contact.target) catch |err| {
log.debug(.app, "webdriver touch", .{ .err = err });
};
- } else {
- // Ignore a bare or repeated release without an active press.
- if (pointer.held == 0) continue;
- last_click_button = button;
- last_click_target = pointer.release(frame, el, .{
- .button = button,
- .click_count = click_count,
- .modifiers = frame.page.input_modifiers,
- }) catch null;
+ continue;
}
+ const el = target orelse continue;
+ // WebDriver: releasing a button that isn't pressed is a no-op.
+ if (pointer.held == 0) continue;
+ const button = readI32(action, "button", 0);
+ last_click_button = button;
+ last_click_target = pointer.release(frame, el, .{
+ .button = button,
+ .click_count = click_count,
+ .modifiers = frame.page.input_modifiers,
+ }) catch null;
}
// "pause" carries timing only and is ignored. ("pointerCancel" is not
// emitted by the testdriver Actions builder.)
@@ -526,9 +515,7 @@ test "WebApi: WebDriver touchmove/touchend stay on the touchstart target" {
\\ window.endOnA = e.changedTouches.length === 1 && e.changedTouches[0].target === a;
\\});
\\b.addEventListener('touchend', () => { window.endOnB = true; });
- \\// The initial unpressed pointerMove(origin: a) also lands on `a`,
- \\// so the count (not just "did it fire on a") is what discriminates
- \\// the captured second move from an uncaptured one landing on `b`.
+ \\// `a` also gets the initial unpressed move, hence the count.
\\a.addEventListener('pointermove', e => { if (e.pointerType === 'touch') window.pointerMoveOnACount++; });
\\b.addEventListener('pointermove', () => { window.pointerMoveOnBCount++; });
\\a.addEventListener('pointerup', e => { window.pointerUpOnA = e.pointerType === 'touch'; });
@@ -547,9 +534,6 @@ test "WebApi: WebDriver touchmove/touchend stay on the touchstart target" {
try testing.waitForFrame();
- // Pointer Events implicitly capture to the pointerdown element for a
- // touch source: the pressed pointermove and the pointerup must stay on
- // `a`, never reach `b`, exactly like the Touch events above.
const result = try ls.local.compileAndRun(
"window.moveOnA === true && window.moveOnB !== true && window.endOnA === true && window.endOnB !== true" ++
" && window.pointerMoveOnACount === 2 && window.pointerMoveOnBCount === 0" ++
@@ -559,9 +543,6 @@ test "WebApi: WebDriver touchmove/touchend stay on the touchstart target" {
try testing.expect(result.isTrue());
}
-// An unmatched touch release (no preceding pointerDown in the source) must
-// not fabricate a touchend: per the WebDriver spec, releasing a button
-// that isn't pressed is a no-op.
test "WebApi: WebDriver a touch pointerUp with no preceding pointerDown dispatches no touchend" {
if (!lp.build_config.wpt_extensions) return error.SkipZigTest;
@@ -596,8 +577,6 @@ test "WebApi: WebDriver a touch pointerUp with no preceding pointerDown dispatch
try testing.expect(result.isTrue());
}
-// A second pointerUp for the same source (no intervening pointerDown) must
-// not fire a second touchend for a contact the first release already ended.
test "WebApi: WebDriver a second touch pointerUp dispatches no second touchend" {
if (!lp.build_config.wpt_extensions) return error.SkipZigTest;
@@ -634,8 +613,6 @@ test "WebApi: WebDriver a second touch pointerUp dispatches no second touchend"
try testing.expect(result.isTrue());
}
-// The touch path has to activate, same as a CDP tap. A move to another element
-// is a drag: the finger stays captured and the release must not click.
test "WebApi: WebDriver a touch tap activates and a drag does not" {
if (!lp.build_config.wpt_extensions) return error.SkipZigTest;
@@ -683,9 +660,6 @@ test "WebApi: WebDriver a touch tap activates and a drag does not" {
try testing.expect(result.isTrue());
}
-// The WebDriver "release a button that isn't pressed is a no-op" rule
-// applies to every pointer type, not just touch: a bare mouse pointerUp
-// must not fabricate pointerup/mouseup/click either.
test "WebApi: WebDriver a mouse pointerUp with no preceding pointerDown dispatches no click" {
if (!lp.build_config.wpt_extensions) return error.SkipZigTest;
@@ -728,8 +702,6 @@ test "WebApi: WebDriver a mouse pointerUp with no preceding pointerDown dispatch
try testing.expect(result.isTrue());
}
-// A second mouse pointerUp for the same source (no intervening pointerDown)
-// must not fire a second click for a press the first release already ended.
test "WebApi: WebDriver a second mouse pointerUp dispatches no second click" {
if (!lp.build_config.wpt_extensions) return error.SkipZigTest;
diff --git a/src/browser/webapi/event/TouchEvent.zig b/src/browser/webapi/event/TouchEvent.zig
index 7ab07c53a..7a33b1175 100644
--- a/src/browser/webapi/event/TouchEvent.zig
+++ b/src/browser/webapi/event/TouchEvent.zig
@@ -31,9 +31,6 @@ const TouchList = @import("TouchList.zig");
const String = lp.String;
// https://w3c.github.io/touch-events/#touchevent-interface
-//
-// The lists are cached on first read, so repeated property reads don't grow
-// the event's arena.
const TouchEvent = @This();
pub const Proto = UIEvent;
@@ -44,7 +41,6 @@ _meta_key: bool = false,
_ctrl_key: bool = false,
_shift_key: bool = false,
_touch: ?Touch = null,
-_touch_active: bool = false,
_touches_list: ?*TouchList = null,
_target_touches_list: ?*TouchList = null,
_changed_list: ?*TouchList = null,
@@ -69,12 +65,9 @@ pub fn initTrusted(typ: []const u8, _opts: ?Options, frame: *Frame) !*TouchEvent
return initWithTrusted(typ, _opts, true, frame);
}
-/// Assigning the touch is a plain value write (no arena allocation), so
-/// nothing can fail between creating the event and returning it.
-pub fn initTrustedWithTouch(typ: []const u8, _opts: ?Options, target: *Element, point: Touch.Point, active: bool, frame: *Frame) !*TouchEvent {
+pub fn initTrustedWithTouch(typ: []const u8, _opts: ?Options, target: *Element, point: Touch.Point, frame: *Frame) !*TouchEvent {
const event = try initWithTrusted(typ, _opts, true, frame);
event._touch = .{ ._event = event, ._target = target.asEventTarget(), ._point = point };
- event._touch_active = active;
return event;
}
@@ -104,44 +97,40 @@ pub fn asEvent(self: *TouchEvent) *Event {
return self._proto.asEvent();
}
-/// The live Touch's target, for EventManager's shadow-retargeting swap
-/// (mirrors Event.relatedTargetPtr).
pub fn touchTargetPtr(self: *TouchEvent) ?*?*EventTarget {
- if (self._touch == null) return null;
- return &self._touch.?._target;
+ if (self._touch) |*t| return &t._target;
+ return null;
}
-/// touches and targetTouches hold the same set here but keep separate cached
-/// lists: they are distinct objects in real browsers ([SameObject] only ties
-/// identity to repeated reads of one attribute).
+/// Cached, so repeated reads don't grow the event's arena. touches and
+/// targetTouches hold the same set here but keep separate lists: they are
+/// distinct objects in real browsers ([SameObject] only ties identity to
+/// repeated reads of one attribute).
fn touchList(self: *TouchEvent, active_only: bool, cache: *?*TouchList) !*TouchList {
if (cache.*) |list| {
return list;
}
- const arena = self.asEvent()._arena;
- var touch: ?*Touch = null;
- if (self._touch) |*t| {
- if (!active_only or self._touch_active) {
- touch = t;
- }
- }
+ const event = self.asEvent();
+ // touchend and touchcancel report the lifted contact in changedTouches only.
+ const lifted = event._type_string.eql(comptime .wrap("touchend")) or event._type_string.eql(comptime .wrap("touchcancel"));
+ const touch: ?*Touch = if (self._touch) |*t| (if (active_only and lifted) null else t) else null;
- const list = try arena.create(TouchList);
+ const list = try event._arena.create(TouchList);
list.* = .{ ._event = self, ._touch = touch };
cache.* = list;
return list;
}
-pub fn getTouches(self: *TouchEvent) !*TouchList {
+fn getTouches(self: *TouchEvent) !*TouchList {
return self.touchList(true, &self._touches_list);
}
-pub fn getTargetTouches(self: *TouchEvent) !*TouchList {
+fn getTargetTouches(self: *TouchEvent) !*TouchList {
return self.touchList(true, &self._target_touches_list);
}
-pub fn getChangedTouches(self: *TouchEvent) !*TouchList {
+fn getChangedTouches(self: *TouchEvent) !*TouchList {
return self.touchList(false, &self._changed_list);
}
@@ -179,3 +168,21 @@ pub const JsApi = struct {
pub const ctrlKey = bridge.accessor(TouchEvent.getCtrlKey, null, .{});
pub const shiftKey = bridge.accessor(TouchEvent.getShiftKey, null, .{});
};
+
+const testing = @import("../../../testing.zig");
+
+test "WebApi: TouchEvent caches its touch lists" {
+ const page = try testing.pageTest("mcp_actions.html", .{});
+ defer page.close();
+ const frame = page.frame().?;
+ const target = frame.document.getDocumentElement().?;
+
+ const event = try initTrustedWithTouch("touchstart", null, target, .{ .x = 10, .y = 20 }, frame);
+ event.asEvent().acquireRef();
+ defer event.asEvent().releaseRef(frame.page);
+
+ try testing.expect(try event.getTouches() == try event.getTouches());
+ try testing.expect(try event.getTargetTouches() == try event.getTargetTouches());
+ try testing.expect(try event.getChangedTouches() == try event.getChangedTouches());
+ try testing.expect(try event.getTouches() != try event.getTargetTouches());
+}
diff --git a/src/browser/webapi/event/TouchList.zig b/src/browser/webapi/event/TouchList.zig
index 44c5caf0e..175f9b39f 100644
--- a/src/browser/webapi/event/TouchList.zig
+++ b/src/browser/webapi/event/TouchList.zig
@@ -24,8 +24,7 @@ const TouchEvent = @import("TouchEvent.zig");
// https://w3c.github.io/touch-events/#idl-def-touchlist
//
-// Holds the Touch directly rather than a slice, so the (up to) three lists a
-// TouchEvent caches never alias one backing array.
+// Single-touch: at most one Touch.
const TouchList = @This();
_event: *TouchEvent,
@@ -43,10 +42,6 @@ fn length(self: *const TouchList) u32 {
return if (self._touch != null) 1 else 0;
}
-pub fn indexedGet(self: *TouchList, index: usize, _: *Frame) !*Touch {
- return self.item(index) orelse error.NotHandled;
-}
-
pub fn item(self: *TouchList, index: usize) ?*Touch {
if (index != 0) {
return null;
@@ -64,7 +59,7 @@ pub const JsApi = struct {
};
pub const length = bridge.accessor(TouchList.length, null, .{});
- pub const @"[]" = bridge.indexed(TouchList.indexedGet, getIndexes, .{ .null_as_undefined = true });
+ pub const @"[]" = bridge.indexed(TouchList.item, getIndexes, .{ .null_as_undefined = true });
pub const item = bridge.function(TouchList.item, .{});
fn getIndexes(self: *TouchList, frame: *Frame) !js.Array {
diff --git a/src/server/cdp/domains/input.zig b/src/server/cdp/domains/input.zig
index 635f9543f..c3decc29c 100644
--- a/src/server/cdp/domains/input.zig
+++ b/src/server/cdp/domains/input.zig
@@ -19,7 +19,6 @@
const std = @import("std");
const CDP = @import("../CDP.zig");
const Frame = @import("../../../browser/Frame.zig");
-const Element = @import("../../../browser/webapi/Element.zig");
const Touch = @import("../../../browser/webapi/event/Touch.zig");
const dom_button = Frame.user_input.mouse_button;
@@ -159,21 +158,11 @@ fn dispatchMouseEvent(cmd: *CDP.Command) !void {
/// https://chromedevtools.github.io/devtools-protocol/tot/Input/#method-dispatchTouchEvent
///
-/// Only one contact is tracked, so more than one point is rejected rather than
-/// silently dropping the rest. touchEnd takes zero or one point because
-/// Playwright sends an empty list and Puppeteer sends the point being
-/// released; touchCancel must be empty, as in Chrome.
-///
-/// Chrome is looser than this everywhere except touchCancel: it reads the
-/// point list as the set of contacts now down, so a longer list or an unknown
-/// id just opens more contacts. Refusing is the honest answer while only one
-/// contact exists, but it is this engine's rule and not Chrome's.
-///
-/// Puppeteer's ids start at 1, so the contact keeps the id from touchStart
-/// instead of assuming 0. Touch.identifier is a DOM i32, so a fractional or
-/// out-of-range id fails to parse and lands on the same InvalidParams a bad
-/// shape does. Chrome instead truncates, and overflows to INT_MIN past the
-/// range, which is not worth matching.
+/// Single contact only: more than one point is InvalidParams, where Chrome
+/// would open more contacts. touchEnd takes zero or one point (Playwright
+/// sends none, Puppeteer the released one); touchCancel must be empty, as in
+/// Chrome. Touch.identifier is an i32, so a fractional or out-of-range id
+/// fails to parse, where Chrome truncates.
fn dispatchTouchEvent(cmd: *CDP.Command) !void {
const params = (cmd.params(struct {
type: Type,
@@ -204,9 +193,6 @@ fn dispatchTouchEvent(cmd: *CDP.Command) !void {
};
switch (params.type) {
- // Single-touch scope: a second touchStart while the one supported
- // contact is still active would overwrite it, losing the original
- // target/coordinates and reporting two starts for one contact.
.touchStart => {
if (frame.page.input_touch_contact != null) return error.InvalidParams;
},
@@ -220,21 +206,17 @@ fn dispatchTouchEvent(cmd: *CDP.Command) !void {
try cmd.sendResult(null, .{});
- // Puppeteer's touchEnd carries the point being released, and Chrome
- // dispatches there rather than at the last touchmove; Playwright's empty
- // list and touchCancel fall back to the stored contact.
const point: ?Touch.Point = if (params.touchPoints.len == 1) params.touchPoints[0] else null;
const modifiers = cdpModifiers(params.modifiers);
switch (params.type) {
- .touchStart => try Frame.user_input.triggerTouch(frame, null, .touchstart, point.?, modifiers),
- .touchMove => try Frame.user_input.triggerTouch(frame, null, .touchmove, point.?, modifiers),
- .touchEnd => try Frame.user_input.triggerTouchLift(frame, .touchend, point, modifiers, null),
- .touchCancel => try Frame.user_input.triggerTouchLift(frame, .touchcancel, point, modifiers, null),
+ .touchStart => try Frame.user_input.touchStart(frame, null, point.?, modifiers),
+ .touchMove => try Frame.user_input.touchMove(frame, null, point.?, modifiers),
+ .touchEnd => try Frame.user_input.touchEnd(frame, point, modifiers, null),
+ .touchCancel => try Frame.user_input.touchCancel(frame, modifiers),
}
}
-/// CDP's wire bitmask: Alt=1, Ctrl=2, Meta/Command=4, Shift=8.
fn cdpModifiers(bits: u4) Frame.user_input.Modifiers {
return .{
.alt = bits & 1 != 0,
@@ -1392,9 +1374,7 @@ test "cdp.input: chorded mousedown focuses its target unless pointerdown or mous
}
}
-// Puppeteer sends radiusX/radiusY/force of 0.5 on every tap, and Chrome hands
-// them back to the page rather than substituting a default, so a page reading
-// pressure sees what the client sent.
+// Puppeteer sends radius and force 0.5; Chrome passes them through unchanged.
test "cdp.input: dispatchTouchEvent reports the client's radius, angle and force" {
var ctx = try testing.context();
defer ctx.deinit();
@@ -1616,10 +1596,8 @@ test "cdp.input: dispatchTouchEvent touchEnd empties touches but keeps changedTo
try testing.expect(result.isTrue());
}
-// A point past the last element (e.g. Playwright's touchscreen.tap(400,
-// 3000) on a short page) must not drop the contact silently: Chrome
-// completes the sequence, so this falls back to the document element the
-// same way WebDriver's pointerMove does.
+// Playwright's touchscreen.tap(400, 3000) on a short page; Chrome completes
+// the sequence.
test "cdp.input: dispatchTouchEvent a touchStart past every element still opens a contact" {
var ctx = try testing.context();
defer ctx.deinit();
@@ -1739,10 +1717,6 @@ test "cdp.input: dispatchTouchEvent tracks the client's chosen id and rejects mi
const x = try (try ls.local.compileAndRun("target.getBoundingClientRect().x", null)).toF64();
const y = try (try ls.local.compileAndRun("target.getBoundingClientRect().y", null)).toF64();
- // A fractional id is rejected before it can create a contact. Chrome
- // truncates instead (0.5 arrives as 0, and a value past i32 wraps to
- // INT_MIN), which is not behaviour worth matching. No real client sends
- // one: Puppeteer and Playwright ids are both integers.
try ctx.processMessage(.{
.id = 1,
.method = "Input.dispatchTouchEvent",
@@ -1751,9 +1725,6 @@ test "cdp.input: dispatchTouchEvent tracks the client's chosen id and rejects mi
try ctx.expectSentError(-31998, "InvalidParams", .{ .id = 1 });
try testing.expect(frame.page.input_touch_contact == null);
- // Puppeteer's id generator starts at 1 and increments; any integer id
- // (including one Chrome would also accept, like a negative one) opens
- // the contact under that id.
try ctx.processMessage(.{
.id = 2,
.method = "Input.dispatchTouchEvent",
@@ -1761,8 +1732,6 @@ test "cdp.input: dispatchTouchEvent tracks the client's chosen id and rejects mi
});
try testing.expectEqual(@as(i32, 7), frame.page.input_touch_contact.?.point.id);
- // A touchMove for a different id than the open contact is rejected and
- // leaves the contact untouched.
try ctx.processMessage(.{
.id = 3,
.method = "Input.dispatchTouchEvent",
@@ -1778,8 +1747,6 @@ test "cdp.input: dispatchTouchEvent tracks the client's chosen id and rejects mi
.params = .{ .type = "touchMove", .touchPoints = &.{.{ .x = x + 1, .y = y + 2, .id = 7 }} },
});
- // touchEnd carrying a mismatched id (Puppeteer always sends the released
- // point) is rejected without lifting the contact.
try ctx.processMessage(.{
.id = 5,
.method = "Input.dispatchTouchEvent",
@@ -1788,7 +1755,6 @@ test "cdp.input: dispatchTouchEvent tracks the client's chosen id and rejects mi
try ctx.expectSentError(-31998, "InvalidParams", .{ .id = 5 });
try testing.expect(frame.page.input_touch_contact != null);
- // touchEnd with the matching id (Puppeteer) lifts the contact.
try ctx.processMessage(.{
.id = 6,
.method = "Input.dispatchTouchEvent",
@@ -1804,7 +1770,6 @@ test "cdp.input: dispatchTouchEvent tracks the client's chosen id and rejects mi
, null)).isTrue());
}
-// Single-touch scope: a second touchStart must not overwrite the contact.
test "cdp.input: dispatchTouchEvent a second touchStart while a contact is active is InvalidParams" {
var ctx = try testing.context();
defer ctx.deinit();
@@ -1844,8 +1809,6 @@ test "cdp.input: dispatchTouchEvent a second touchStart while a contact is activ
});
try ctx.expectSentError(-31998, "InvalidParams", .{ .id = 2 });
- // The original contact is untouched: exactly one touchstart fired, and
- // touchEnd still resolves against the first target's coordinates.
_ = try ls.local.compileAndRun(
\\document.getElementById('hoverTarget')
\\ .addEventListener('touchend', (e) => {
@@ -1862,10 +1825,7 @@ test "cdp.input: dispatchTouchEvent a second touchStart while a contact is activ
try testing.expect(result.isTrue());
}
-// Puppeteer's touchEnd always carries the point being released, and Chrome
-// dispatches at that wire position (not the last touchmove/touchstart one)
-// when it's given. A client releasing without an intervening touchMove must
-// still land on the released coordinates.
+// Puppeteer releases without an intervening touchMove.
test "cdp.input: dispatchTouchEvent a touchEnd carrying the released point is accepted" {
var ctx = try testing.context();
defer ctx.deinit();
@@ -1903,7 +1863,6 @@ test "cdp.input: dispatchTouchEvent a touchEnd carrying the released point is ac
.params = .{ .type = "touchStart", .touchPoints = &.{.{ .x = rect_x, .y = rect_y }} },
});
- // No touchMove in between: the release point is a fresh position.
try ctx.processMessage(.{
.id = 2,
.method = "Input.dispatchTouchEvent",
@@ -1918,7 +1877,6 @@ test "cdp.input: dispatchTouchEvent a touchEnd carrying the released point is ac
);
try testing.expect(result.isTrue());
- // The contact clearing is not left dangling: a fresh touchStart works.
try ctx.processMessage(.{
.id = 3,
.method = "Input.dispatchTouchEvent",
@@ -1927,8 +1885,6 @@ test "cdp.input: dispatchTouchEvent a touchEnd carrying the released point is ac
try testing.expect(frame.page.input_touch_contact != null);
}
-// Playwright's empty touchPoints list has no position to read: the lift
-// keeps dispatching at the stored contact (last touchstart/touchmove point).
test "cdp.input: dispatchTouchEvent an empty touchEnd uses the stored position" {
var ctx = try testing.context();
defer ctx.deinit();
@@ -2064,132 +2020,6 @@ test "cdp.input: dispatchTouchEvent a multi-point touchEnd/touchCancel is Invali
try ctx.expectSentError(-31998, "InvalidParams", .{ .id = 2 });
}
-// The next four tests call Frame.user_input.dispatchTouchEvent directly
-// (bypassing CDP message dispatch) to exercise per-type event shape, which
-// Input.dispatchTouchEvent doesn't itself vary by target.
-test "cdp.input: dispatchTouchEvent touchcancel is never cancelable" {
- const page = try testing.pageTest("mcp_actions.html", .{});
- defer page.close();
- const frame = page.frame().?;
- var ls: lp.js.Local.Scope = undefined;
- frame.js.localScope(&ls);
- defer ls.deinit();
- var tc: lp.js.TryCatch = undefined;
- tc.init(&ls.local);
- defer tc.deinit();
-
- const value = try ls.local.compileAndRun(
- \\const t = document.getElementById('hoverTarget');
- \\t.addEventListener('touchcancel', e => {
- \\ e.preventDefault();
- \\ window.result = !e.cancelable && !e.defaultPrevented;
- \\}, {passive: false});
- \\t;
- , null);
- const target = try ls.local.jsValueToZig(*Element, value);
- _ = try Frame.user_input.dispatchTouchEvent(frame, target, .touchcancel, .{ .x = 10, .y = 20 }, .{});
- try testing.expect((try ls.local.compileAndRun("window.result === true", null)).isTrue());
-}
-
-test "cdp.input: dispatchTouchEvent a passive-only touchstart listener is not cancelable" {
- const page = try testing.pageTest("mcp_actions.html", .{});
- defer page.close();
- const frame = page.frame().?;
- var ls: lp.js.Local.Scope = undefined;
- frame.js.localScope(&ls);
- defer ls.deinit();
- var tc: lp.js.TryCatch = undefined;
- tc.init(&ls.local);
- defer tc.deinit();
-
- const value = try ls.local.compileAndRun(
- \\const t = document.getElementById('hoverTarget');
- \\t.addEventListener('touchstart', e => { window.result = !e.cancelable; }, {passive: true});
- \\t;
- , null);
- const target = try ls.local.jsValueToZig(*Element, value);
- _ = try Frame.user_input.dispatchTouchEvent(frame, target, .touchstart, .{ .x = 10, .y = 20 }, .{});
- try testing.expect((try ls.local.compileAndRun("window.result === true", null)).isTrue());
-}
-
-test "cdp.input: dispatchTouchEvent a non-passive listener makes touchstart cancelable" {
- const page = try testing.pageTest("mcp_actions.html", .{});
- defer page.close();
- const frame = page.frame().?;
- var ls: lp.js.Local.Scope = undefined;
- frame.js.localScope(&ls);
- defer ls.deinit();
- var tc: lp.js.TryCatch = undefined;
- tc.init(&ls.local);
- defer tc.deinit();
-
- const value = try ls.local.compileAndRun(
- \\const t = document.getElementById('hoverTarget');
- \\t.addEventListener('touchstart', e => { window.result = e.cancelable; });
- \\t;
- , null);
- const target = try ls.local.jsValueToZig(*Element, value);
- _ = try Frame.user_input.dispatchTouchEvent(frame, target, .touchstart, .{ .x = 10, .y = 20 }, .{});
- try testing.expect((try ls.local.compileAndRun("window.result === true", null)).isTrue());
-}
-
-test "cdp.input: dispatchTouchEvent a closed-shadow touch target retargets to the host" {
- const page = try testing.pageTest("mcp_actions.html", .{});
- defer page.close();
- const frame = page.frame().?;
- var ls: lp.js.Local.Scope = undefined;
- frame.js.localScope(&ls);
- defer ls.deinit();
- var tc: lp.js.TryCatch = undefined;
- tc.init(&ls.local);
- defer tc.deinit();
-
- const value = try ls.local.compileAndRun(
- \\const host = document.createElement('div');
- \\document.body.appendChild(host);
- \\const root = host.attachShadow({mode: 'closed'});
- \\const inner = document.createElement('button');
- \\root.appendChild(inner);
- \\host.addEventListener('touchstart', e => {
- \\ window.eventTargetOK = e.target === host;
- \\ window.touchTargetOK = e.touches[0].target === host;
- \\});
- \\inner;
- , null);
- const target = try ls.local.jsValueToZig(*Element, value);
- _ = try Frame.user_input.dispatchTouchEvent(frame, target, .touchstart, .{ .x = 10, .y = 20 }, .{});
- const result = try ls.local.compileAndRun("window.eventTargetOK === true && window.touchTargetOK === true", null);
- try testing.expect(result.isTrue());
-}
-
-test "cdp.input: dispatchTouchEvent repeated touches reads have bounded arena storage" {
- const TouchEvent = @import("../../../browser/webapi/event/TouchEvent.zig");
-
- const page = try testing.pageTest("mcp_actions.html", .{});
- defer page.close();
- const frame = page.frame().?;
- const target = frame.document.getDocumentElement().?;
-
- const event = try TouchEvent.initTrustedWithTouch("touchstart", null, target, .{ .x = 10, .y = 20 }, true, frame);
- event.asEvent().acquireRef();
- defer event.asEvent().releaseRef(frame.page);
-
- // Warm all three caches (touches, targetTouches, changedTouches are each
- // a distinct cached TouchList) before measuring, so the loop only
- // exercises the cache-hit path.
- _ = try event.getTouches();
- _ = try event.getTargetTouches();
- _ = try event.getChangedTouches();
- const before = event.asEvent()._arena.bytes;
- for (0..10_000) |_| {
- _ = try event.getTouches();
- _ = try event.getTargetTouches();
- _ = try event.getChangedTouches();
- }
- const after = event.asEvent()._arena.bytes;
- try testing.expectEqual(before, after);
-}
-
test "cdp.input: dispatchKeyEvent Tab runs sequential focus navigation" {
var ctx = try testing.context();
defer ctx.deinit();
@@ -3054,19 +2884,19 @@ test "cdp.input: touch tap respects disabled controls across compatibility handl
frame.js.localScope(&ls);
defer ls.deinit();
const cases = .{
- .{ "t.disabled = true;", "clicks === 0 && !t.checked && !events.includes('mousedown') && !events.includes('mouseup')" },
- .{ "fieldset.disabled = true;", "clicks === 0 && !t.checked" },
- .{ "fieldset.disabled = true; const legend = document.createElement('legend'); fieldset.prepend(legend); legend.append(t);", "clicks === 1 && t.checked" },
- .{ "t.disabled = true; t.addEventListener('pointerdown', e => e.preventDefault());", "clicks === 0 && !t.checked" },
- .{ "t.disabled = true; t.addEventListener('mousemove', () => t.disabled = false);", "clicks === 1 && t.checked" },
- .{ "t.addEventListener('pointerup', () => t.disabled = true);", "clicks === 0 && !t.checked" },
- .{ "t.addEventListener('touchend', () => t.disabled = true);", "clicks === 0 && !t.checked" },
- .{ "t.addEventListener('mouseover', () => t.disabled = true);", "clicks === 0 && !t.checked" },
- .{ "t.addEventListener('mousemove', () => t.disabled = true);", "clicks === 0 && !t.checked" },
- .{ "t.addEventListener('mousedown', () => t.disabled = true);", "clicks === 0 && !t.checked && !events.includes('mouseup')" },
- .{ "t.addEventListener('focus', () => t.disabled = true);", "clicks === 0 && !t.checked" },
- .{ "t.addEventListener('mouseup', () => t.disabled = true);", "clicks === 0 && !t.checked" },
- .{ "t.addEventListener('click', () => t.disabled = true);", "clicks === 1" },
+ .{ "t.disabled = true;", "clicks === 0 && !t.checked && !events.includes('mousedown') && !events.includes('mouseup')", 1 },
+ .{ "fieldset.disabled = true;", "clicks === 0 && !t.checked", 1 },
+ .{ "fieldset.disabled = true; const legend = document.createElement('legend'); fieldset.prepend(legend); legend.append(t);", "clicks === 1 && t.checked", 1 },
+ .{ "t.disabled = true; t.addEventListener('pointerdown', e => e.preventDefault());", "clicks === 0 && !t.checked", 1 },
+ .{ "t.disabled = true; t.addEventListener('mousemove', () => t.disabled = false);", "clicks === 1 && t.checked", 1 },
+ .{ "t.addEventListener('pointerup', () => t.disabled = true);", "clicks === 0 && !t.checked", 1 },
+ .{ "t.addEventListener('touchend', () => t.disabled = true);", "clicks === 0 && !t.checked", 1 },
+ .{ "t.addEventListener('mouseover', () => t.disabled = true);", "clicks === 0 && !t.checked", 1 },
+ .{ "t.addEventListener('mousemove', () => t.disabled = true);", "clicks === 0 && !t.checked", 1 },
+ .{ "t.addEventListener('mousedown', () => t.disabled = true);", "clicks === 0 && !t.checked && !events.includes('mouseup')", 1 },
+ .{ "t.addEventListener('focus', () => t.disabled = true);", "clicks === 0 && !t.checked", 1 },
+ .{ "t.addEventListener('mouseup', () => t.disabled = true);", "clicks === 0 && !t.checked", 1 },
+ .{ "t.addEventListener('click', () => t.disabled = true);", "clicks === 1", 2 },
};
inline for (cases) |case| {
_ = try ls.local.compileAndRun(
@@ -3078,9 +2908,7 @@ test "cdp.input: touch tap respects disabled controls across compatibility handl
++ case[0], null);
const x = try (try ls.local.compileAndRun("t.getBoundingClientRect().x + 1", null)).toF64();
const y = try (try ls.local.compileAndRun("t.getBoundingClientRect().y + 1", null)).toF64();
- // A second tap must not activate a control disabled by the first click.
- for (0..2) |tap| {
- if (tap == 1 and comptime !std.mem.eql(u8, case[0], "t.addEventListener('click', () => t.disabled = true);")) break;
+ for (0..case[2]) |_| {
try ctx.processMessage(.{ .id = 1, .method = "Input.dispatchTouchEvent", .params = .{ .type = "touchStart", .touchPoints = &.{.{ .x = x, .y = y }} } });
try ctx.processMessage(.{ .id = 2, .method = "Input.dispatchTouchEvent", .params = .{ .type = "touchEnd", .touchPoints = &.{} } });
}
@@ -3089,8 +2917,6 @@ test "cdp.input: touch tap respects disabled controls across compatibility handl
try testing.expect(passed);
try testing.expect(frame.page.input_touch_contact == null);
}
- // Explicit script dispatch is not trusted input and must still reach listeners.
- try testing.expect((try ls.local.compileAndRun("t.disabled = true; clicks = 0; t.dispatchEvent(new MouseEvent('click')); clicks === 1", null)).isTrue());
}
test "cdp.input: touch tap revalidates targets between compatibility events" {
@@ -3205,17 +3031,17 @@ test "cdp.input: mouse activation rechecks disabled state between events" {
frame.js.localScope(&ls);
defer ls.deinit();
const cases = .{
- .{ "t.disabled = true;", "clicks === 0 && !t.checked && events.join(',') === 'pointerdown,pointerup'" },
- .{ "fieldset.disabled = true;", "clicks === 0 && !t.checked" },
- .{ "fieldset.disabled = true; const legend = document.createElement('legend'); fieldset.prepend(legend); legend.append(t);", "clicks === 1 && t.checked" },
- .{ "t.disabled = true; t.addEventListener('pointerdown', e => e.preventDefault());", "clicks === 0 && !t.checked" },
- .{ "t.addEventListener('pointerdown', () => t.disabled = true);", "clicks === 0 && !t.checked && !events.includes('mousedown')" },
- .{ "t.addEventListener('mousedown', () => t.disabled = true);", "clicks === 0 && !t.checked && !events.includes('mouseup')" },
- .{ "t.addEventListener('pointerup', () => t.disabled = true);", "clicks === 0 && !t.checked && !events.includes('mouseup')" },
- .{ "t.addEventListener('mouseup', () => t.disabled = true);", "clicks === 0 && !t.checked" },
- .{ "t.disabled = true; t.addEventListener('pointerdown', () => t.disabled = false);", "clicks === 1 && t.checked && events.includes('mousedown')" },
- .{ "t.disabled = true; t.addEventListener('pointerup', () => t.disabled = false);", "clicks === 1 && t.checked && !events.includes('mousedown') && events.includes('mouseup')" },
- .{ "t.addEventListener('click', () => t.disabled = true);", "clicks === 1" },
+ .{ "t.disabled = true;", "clicks === 0 && !t.checked && events.join(',') === 'pointerdown,pointerup'", 1 },
+ .{ "fieldset.disabled = true;", "clicks === 0 && !t.checked", 1 },
+ .{ "fieldset.disabled = true; const legend = document.createElement('legend'); fieldset.prepend(legend); legend.append(t);", "clicks === 1 && t.checked", 1 },
+ .{ "t.disabled = true; t.addEventListener('pointerdown', e => e.preventDefault());", "clicks === 0 && !t.checked", 1 },
+ .{ "t.addEventListener('pointerdown', () => t.disabled = true);", "clicks === 0 && !t.checked && !events.includes('mousedown')", 1 },
+ .{ "t.addEventListener('mousedown', () => t.disabled = true);", "clicks === 0 && !t.checked && !events.includes('mouseup')", 1 },
+ .{ "t.addEventListener('pointerup', () => t.disabled = true);", "clicks === 0 && !t.checked && !events.includes('mouseup')", 1 },
+ .{ "t.addEventListener('mouseup', () => t.disabled = true);", "clicks === 0 && !t.checked", 1 },
+ .{ "t.disabled = true; t.addEventListener('pointerdown', () => t.disabled = false);", "clicks === 1 && t.checked && events.includes('mousedown')", 1 },
+ .{ "t.disabled = true; t.addEventListener('pointerup', () => t.disabled = false);", "clicks === 1 && t.checked && !events.includes('mousedown') && events.includes('mouseup')", 1 },
+ .{ "t.addEventListener('click', () => t.disabled = true);", "clicks === 1", 2 },
};
inline for (cases) |case| {
_ = try ls.local.compileAndRun(
@@ -3227,9 +3053,7 @@ test "cdp.input: mouse activation rechecks disabled state between events" {
++ case[0], null);
const x = try (try ls.local.compileAndRun("t.getBoundingClientRect().x + 1", null)).toF64();
const y = try (try ls.local.compileAndRun("t.getBoundingClientRect().y + 1", null)).toF64();
- // A second click must not activate a control disabled by the first click.
- for (0..2) |tap| {
- if (tap == 1 and comptime !std.mem.eql(u8, case[0], "t.addEventListener('click', () => t.disabled = true);")) break;
+ for (0..case[2]) |_| {
try ctx.processMessage(.{ .id = 1, .method = "Input.dispatchMouseEvent", .params = .{ .type = "mousePressed", .x = x, .y = y, .button = "left", .clickCount = 1 } });
try ctx.processMessage(.{ .id = 2, .method = "Input.dispatchMouseEvent", .params = .{ .type = "mouseReleased", .x = x, .y = y, .button = "left", .clickCount = 1 } });
}