Lightpanda: the headless browser designed for AI and automation
feat(input): single-contact touch input for CDP and WebDriver
Ramiro_quai95f807c18c38
diff --git a/src/browser/EventManager.zig b/src/browser/EventManager.zigindex 36b937cf6..14a0047fb 100644--- a/src/browser/EventManager.zig+++ b/src/browser/EventManager.zig@@ -173,6 +173,12 @@ fn dispatchNode(self: *EventManager, target: *Node, event: *Event) !void {}}+ // A TouchEvent's Touch.target, retargeted the same way as relatedTarget.+ const original_touch: ?*EventTarget = if (event.touchTargetPtr()) |p| p.* else null;+ if (rootIsShadowRoot(original_touch)) {+ event._needs_retargeting = true;+ }+const frame = self.frame;// Set window.event to the currently dispatching event (WHATWG spec)@@ -216,6 +222,9 @@ fn dispatchNode(self: *EventManager, target: *Node, event: *Event) !void {if (event.relatedTargetPtr()) |related_ptr| {related_ptr.* = null;}+ if (event.touchTargetPtr()) |touch_ptr| {+ touch_ptr.* = null;+ }} else if (event._needs_retargeting and node_path_len > 0) {const last = path_buffer[node_path_len - 1];const adjusted = getAdjustedTarget(event._dispatch_target, last);@@ -223,6 +232,9 @@ fn dispatchNode(self: *EventManager, target: *Node, event: *Event) !void {if (event.relatedTargetPtr()) |related_ptr| {related_ptr.* = getAdjustedTarget(original_related, last);}+ if (event.touchTargetPtr()) |touch_ptr| {+ touch_ptr.* = getAdjustedTarget(original_touch, last);+ }}// Handle checkbox/radio activation rollback or commitif (activation_state) |state| {@@ -295,6 +307,13 @@ 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;+ }+ }+ }}const path = path_buffer[0..path_len];@@ -623,19 +642,27 @@ const AdjustedTargets = struct {target: ?*EventTarget,related: ?*EventTarget,related_ptr: ?*?*EventTarget,+ touch: ?*EventTarget,+ touch_ptr: ?*?*EventTarget,fn apply(event: *Event, current_target: *EventTarget) AdjustedTargets {const related_ptr = event.relatedTargetPtr();+ const touch_ptr = event.touchTargetPtr();const original: AdjustedTargets = .{.target = event._target,.related = if (related_ptr) |p| p.* else null,.related_ptr = related_ptr,+ .touch = if (touch_ptr) |p| p.* else null,+ .touch_ptr = touch_ptr,};event._target = getAdjustedTarget(original.target, current_target);if (related_ptr) |p| {p.* = getAdjustedTarget(original.related, current_target);}+ if (touch_ptr) |p| {+ p.* = getAdjustedTarget(original.touch, current_target);+ }return original;}@@ -644,6 +671,9 @@ const AdjustedTargets = struct {if (self.related_ptr) |p| {p.* = self.related;}+ if (self.touch_ptr) |p| {+ p.* = self.touch;+ }}};diff --git a/src/browser/Page.zig b/src/browser/Page.zigindex 9e7f20d6c..55bdee8b5 100644--- a/src/browser/Page.zig+++ b/src/browser/Page.zig@@ -190,6 +190,11 @@ input_modifiers: if (lp.build_config.wpt_extensions) @import("frame/user_input.z// The element the synthetic pointer is currently overinput_hover_target: ?*Element = null,+// Last CDP touch contact. Empty TouchEnd/TouchCancel reuse this instead of+// re-hit-testing at (0, 0).+input_touch_contact: ?@import("frame/user_input.zig").TouchContact = null,+input_touch_next_pointer_id: i32 = 2,+// Per-gesture button state for the synthetic mouse pointer; see// user_input.PointerButtons.input_pointer: @import("frame/user_input.zig").PointerButtons = .{},diff --git a/src/browser/frame/user_input.zig b/src/browser/frame/user_input.zigindex 571303e1a..7438bb08d 100644--- a/src/browser/frame/user_input.zig+++ b/src/browser/frame/user_input.zig@@ -35,6 +35,7 @@ const TreeWalker = @import("../webapi/TreeWalker.zig");const TextEvent = @import("../webapi/event/TextEvent.zig");const InputEvent = @import("../webapi/event/InputEvent.zig");const MouseEvent = @import("../webapi/event/MouseEvent.zig");+const TouchEvent = @import("../webapi/event/TouchEvent.zig");const WheelEvent = @import("../webapi/event/WheelEvent.zig");const PointerEvent = @import("../webapi/event/PointerEvent.zig");const KeyboardEvent = @import("../webapi/event/KeyboardEvent.zig");@@ -56,6 +57,7 @@ const HoverContext = struct {y: f64 = 0,buttons: u16 = 0,modifiers: Modifiers = .{},+ with_pointer: bool = true,};// Update the element being hovered. The page always tracks the currently@@ -125,30 +127,32 @@ fn dispatchBoundaryEvent(frame: *Frame, target: *Element, comptime mouse_typ: []const modifiers = ctx.modifiers;const related_target = if (related) |r| r.asEventTarget() else null;- const pointer_event = PointerEvent.initTrusted(pointer_typ, .{- .bubbles = bubbling,- .cancelable = bubbling,- .composed = bubbling,- .clientX = ctx.x,- .clientY = ctx.y,- // No button changed state: https://www.w3.org/TR/pointerevents3/#the-button-property- .button = -1,- .buttons = ctx.buttons,- .pointerId = 1,- .pointerType = "mouse",- .isPrimary = true,- .relatedTarget = related_target,- .ctrlKey = modifiers.ctrl,- .shiftKey = modifiers.shift,- .altKey = modifiers.alt,- .metaKey = modifiers.meta,- }, frame) catch |err| {- log.debug(.frame, "boundary pointer event", .{ .err = err, .type = pointer_typ });- return;- };- frame._event_manager.dispatch(target.asEventTarget(), pointer_event.asEvent()) catch |err| {- log.debug(.frame, "boundary pointer dispatch", .{ .err = err, .type = pointer_typ });- };+ if (ctx.with_pointer) {+ const pointer_event = PointerEvent.initTrusted(pointer_typ, .{+ .bubbles = bubbling,+ .cancelable = bubbling,+ .composed = bubbling,+ .clientX = ctx.x,+ .clientY = ctx.y,+ // No button changed state: https://www.w3.org/TR/pointerevents3/#the-button-property+ .button = -1,+ .buttons = ctx.buttons,+ .pointerId = 1,+ .pointerType = "mouse",+ .isPrimary = true,+ .relatedTarget = related_target,+ .ctrlKey = modifiers.ctrl,+ .shiftKey = modifiers.shift,+ .altKey = modifiers.alt,+ .metaKey = modifiers.meta,+ }, frame) catch |err| {+ log.debug(.frame, "boundary pointer event", .{ .err = err, .type = pointer_typ });+ return;+ };+ frame._event_manager.dispatch(target.asEventTarget(), pointer_event.asEvent()) catch |err| {+ log.debug(.frame, "boundary pointer dispatch", .{ .err = err, .type = pointer_typ });+ };+ }const mouse_event = MouseEvent.initTrusted(comptime .wrap(mouse_typ), .{.bubbles = bubbling,@@ -570,6 +574,278 @@ fn deltaToScroll(d: f64) i32 {return @trunc(std.math.clamp(d, std.math.minInt(i32), std.math.maxInt(i32)));}+/// One contact as the client described it. The id is whatever the client+/// picked on touchstart (Puppeteer counts up from 1; a bare CDP call with no+/// id defaults to 0). The radius, angle and force defaults are Chrome's for a+/// point that leaves them out, and Puppeteer overrides all three per tap.+pub const TouchPoint = struct {+ x: f64,+ y: f64,+ identifier: i32 = 0,+ radius_x: f64 = 1,+ radius_y: f64 = 1,+ rotation_angle: f64 = 0,+ force: f64 = 1,+};++/// The CDP-tracked touch contact. Single-touch scope: at most one.+pub const TouchContact = struct {+ target: *Element,+ point: TouchPoint,+ start: TouchPoint,+ pointer_id: i32,+ suppress_mouse: bool = false,+ suppress_click: bool = false,+};++pub const TouchType = enum {+ touchstart,+ touchmove,+ touchend,+ touchcancel,++ fn name(self: TouchType) []const u8 {+ return @tagName(self);+ }++ fn isLift(self: TouchType) bool {+ return self == .touchend or self == .touchcancel;+ }+};++/// The caller supplies the target (no hit-test), so touchmove/touchend/+/// touchcancel can stay pinned to the touchstart element instead of+/// re-resolving at the current point.+pub fn dispatchTouchEventOn(frame: *Frame, target: *Element, typ: TouchType, point: TouchPoint, modifiers: Modifiers) !void {+ _ = try dispatchTouchEventCancelable(frame, target, typ, point, modifiers);+}++fn dispatchTouchEventCancelable(frame: *Frame, target: *Element, typ: TouchType, point: TouchPoint, modifiers: Modifiers) !bool {+ const active = !typ.isLift();++ const event: *TouchEvent = try .initTrustedWithTouch(typ.name(), .{+ .bubbles = true,+ .composed = true,+ .altKey = modifiers.alt,+ .ctrlKey = modifiers.ctrl,+ .metaKey = modifiers.meta,+ .shiftKey = modifiers.shift,+ }, .{+ .identifier = point.identifier,+ .target = target,+ .clientX = point.x,+ .clientY = point.y,+ .radiusX = point.radius_x,+ .radiusY = point.radius_y,+ .rotationAngle = point.rotation_angle,+ .force = point.force,+ }, active, frame);++ // touchcancel is never cancelable per spec; the others follow the same+ // passive-listener-dependent rule as wheel (see EventManager).+ if (typ != .touchcancel) {+ event.asEvent()._cancelable_unless_passive = true;+ }++ return frame._event_manager.dispatchCancelable(target.asEventTarget(), event.asEvent());+}++fn dispatchTouchPointerEventOn(frame: *Frame, target: *Element, comptime typ: []const u8, contact: TouchContact, point: TouchPoint, modifiers: Modifiers, cancelled: bool) !bool {+ const lift = comptime std.mem.eql(u8, typ, "pointerup") or std.mem.eql(u8, typ, "pointercancel") or+ std.mem.eql(u8, typ, "pointerout") or std.mem.eql(u8, typ, "pointerleave") or std.mem.eql(u8, typ, "click");+ 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 !comptime std.mem.eql(u8, typ, "pointercancel"),+ .composed = !boundary,+ .clientX = point.x,+ .clientY = point.y,+ .button = if (cancelled or comptime std.mem.eql(u8, typ, "pointermove")) -1 else mouse_button.main,+ .buttons = if (lift) 0 else 1,+ .detail = if (comptime std.mem.eql(u8, typ, "click")) 1 else 0,+ .pointerId = contact.pointer_id,+ .pointerType = "touch",+ .isPrimary = true,+ .width = if (lift and !cancelled) 1 else point.radius_x * 2,+ .height = if (lift and !cancelled) 1 else point.radius_y * 2,+ .pressure = if (lift) 0 else point.force,+ .ctrlKey = modifiers.ctrl,+ .shiftKey = modifiers.shift,+ .altKey = modifiers.alt,+ .metaKey = modifiers.meta,+ }, frame);+ return frame._event_manager.dispatchCancelable(target.asEventTarget(), event.asEvent());+}++fn dispatchTouchPointerEnter(frame: *Frame, contact: TouchContact, modifiers: Modifiers) !void {+ _ = try dispatchTouchPointerEventOn(frame, contact.target, "pointerover", contact, contact.point, modifiers, false);+ var count: usize = 0;+ var current: ?*Node = contact.target.asNode();+ while (current) |node| : (current = node.parentNode()) {+ if (node.is(Element) != null) count += 1;+ }+ while (count > 0) : (count -= 1) {+ var remaining = count;+ current = contact.target.asNode();+ while (current) |node| : (current = node.parentNode()) {+ const element = node.is(Element) orelse continue;+ remaining -= 1;+ if (remaining == 0) {+ _ = try dispatchTouchPointerEventOn(frame, element, "pointerenter", contact, contact.point, modifiers, false);+ break;+ }+ }+ }+}++fn dispatchTouchPointerLeave(frame: *Frame, contact: TouchContact, point: TouchPoint, modifiers: Modifiers, cancelled: bool) !void {+ _ = try dispatchTouchPointerEventOn(frame, contact.target, "pointerout", contact, point, modifiers, cancelled);+ var current: ?*Node = contact.target.asNode();+ while (current) |node| : (current = node.parentNode()) {+ const element = node.is(Element) orelse continue;+ _ = try dispatchTouchPointerEventOn(frame, element, "pointerleave", contact, point, modifiers, cancelled);+ }+}++pub fn hasActiveTouch(frame: *Frame) bool {+ return frame.page.input_touch_contact != null;+}++/// When the point misses every element (e.g. past the end of a short faux+/// layout), fall back to the document element rather than dropping the+/// contact silently, the same fallback WebDriver's pointerMove uses.+pub fn triggerTouch(frame: *Frame, typ: TouchType, point: TouchPoint, modifiers: Modifiers) !void {+ return dispatchTouchContact(frame, null, typ, point, modifiers);+}++/// `target` is the touchstart element. WebDriver actions name an element and+/// have no viewport point, so they cannot hit-test. touchmove and later stay+/// pinned to the contact either way.+pub fn triggerTouchOn(frame: *Frame, target: *Element, typ: TouchType, point: TouchPoint, modifiers: Modifiers) !void {+ return dispatchTouchContact(frame, target, typ, point, modifiers);+}++fn dispatchTouchContact(frame: *Frame, explicit: ?*Element, typ: TouchType, point: TouchPoint, 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 explicit orelse+ (try frame.window._document.elementFromPoint(point.x, point.y, frame)) orelse+ frame.window._document.getDocumentElement() orelse return;+ if (comptime lp.IS_DEBUG) {+ log.debug(.frame, "frame touch", .{+ .url = frame.url,+ .node = resolved,+ .x = point.x,+ .y = point.y,+ .type = frame._type,+ });+ }+ var contact: TouchContact = if (typ == .touchstart) .{+ .target = resolved,+ .point = point,+ .start = point,+ .pointer_id = page.input_touch_next_pointer_id,+ } else page.input_touch_contact orelse return;+ contact.point = point;+ if (typ == .touchstart) {+ page.input_touch_next_pointer_id = if (contact.pointer_id == std.math.maxInt(i32)) 2 else contact.pointer_id + 1;+ try dispatchTouchPointerEnter(frame, contact, modifiers);+ contact.suppress_mouse = try dispatchTouchPointerEventOn(frame, resolved, "pointerdown", contact, point, modifiers, false);+ } 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;+ _ = try dispatchTouchPointerEventOn(frame, resolved, "pointermove", contact, point, modifiers, false);+ }+ const prevented = try dispatchTouchEventCancelable(frame, resolved, typ, point, modifiers);+ contact.suppress_click = contact.suppress_click or prevented;+ page.input_touch_contact = contact;+}++/// The element compatibility mouse events hit. A caller-supplied element wins;+/// otherwise the release point is hit-tested, and a miss drops the click.+fn touchCompatTarget(frame: *Frame, point: TouchPoint, pinned: ?*Element) !?*Element {+ if (pinned) |el| return el;+ return frame.window._document.elementFromPoint(point.x, point.y, frame);+}++/// 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.+pub fn triggerTouchLift(frame: *Frame, typ: TouchType, point: ?TouchPoint, modifiers: Modifiers) !void {+ return triggerTouchLiftAt(frame, typ, point, modifiers, null);+}++/// Compatibility mouse events and the click land on `compat_target` instead+/// of a hit-test. WebDriver actions name an element and have no viewport point;+/// CDP uses `triggerTouchLift`, which hit-tests the release coordinate.+pub fn triggerTouchLiftOn(frame: *Frame, typ: TouchType, point: ?TouchPoint, modifiers: Modifiers, compat_target: *Element) !void {+ return triggerTouchLiftAt(frame, typ, point, modifiers, compat_target);+}++fn triggerTouchLiftAt(frame: *Frame, typ: TouchType, point: ?TouchPoint, 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.+ 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.identifier = contact.point.identifier;+ if (typ == .touchcancel) {+ _ = try dispatchTouchPointerEventOn(frame, contact.target, "pointercancel", contact, lift, modifiers, true);+ } else {+ _ = try dispatchTouchPointerEventOn(frame, contact.target, "pointerup", contact, lift, modifiers, false);+ }+ try dispatchTouchPointerLeave(frame, contact, lift, modifiers, typ == .touchcancel);+ const prevented = try dispatchTouchEventCancelable(frame, contact.target, typ, lift, modifiers);+ if (typ == .touchcancel or contact.suppress_click or prevented) return;++ // Compatibility mouse events use the release hit-test, after touchend+ // listeners have had a chance to change the DOM. Pointer/touch delivery+ // above remains pinned to the original contact target.+ var target = (try touchCompatTarget(frame, lift, compat_target)) orelse return;+ updateHoverTarget(frame, target, .{ .x = lift.x, .y = lift.y, .modifiers = modifiers, .with_pointer = false });+ if (!contact.suppress_mouse) {+ // Hover and move listeners can replace the element before the press.+ target = (try touchCompatTarget(frame, lift, compat_target)) orelse return;+ _ = try emitMouse(frame, target, "mousemove", .{ .x = lift.x, .y = lift.y, .modifiers = modifiers }, 0);+ const down_target = (try touchCompatTarget(frame, lift, compat_target)) orelse return;+ if (down_target.isDisabled()) return;+ const suppress_focus = try emitMouse(frame, down_target, "mousedown", .{ .x = lift.x, .y = lift.y, .buttons_down = 1, .modifiers = modifiers }, 1);+ if (!suppress_focus and down_target.asNode().isConnected() and !down_target.isDisabled()) {+ try focusForMouseDown(frame, down_target);+ }++ // Mousedown and focus/blur handlers may have removed or moved the+ // pressed control. Release at the current hit-test, then click only+ // the common ancestor of the connected press and release targets.+ const up_target = (try touchCompatTarget(frame, lift, compat_target)) orelse return;+ if (up_target.isDisabled()) return;+ var click_target: ?*Element = null;+ if (down_target.asNode().isConnected()) {+ var current: ?*Node = down_target.asNode();+ while (current) |node| : (current = node.parentNode()) {+ if (node.contains(up_target.asNode())) {+ click_target = node.is(Element);+ break;+ }+ }+ }+ _ = try emitMouse(frame, up_target, "mouseup", .{ .x = lift.x, .y = lift.y, .modifiers = modifiers }, 1);+ // Chrome retains the selected click target if mouseup removes it.+ target = click_target orelse return;+ }+ // Recheck after mouseup too: disabling a control suppresses activation,+ // including when pointerdown suppressed the compatibility mouse events.+ if (target.isDisabled()) return;+ _ = try dispatchTouchPointerEventOn(frame, target, "click", contact, lift, modifiers, false);+}+/// Whether the element has a click activation behavior that handleClick/// implements.fn hasClickActivationBehavior(node: *Node) bool {diff --git a/src/browser/js/bridge.zig b/src/browser/js/bridge.zigindex 964c76a9a..97d221b2c 100644--- a/src/browser/js/bridge.zig+++ b/src/browser/js/bridge.zig@@ -1229,6 +1229,8 @@ pub const PageJsApis = flattenTypes(&.{@import("../webapi/event/GamepadEvent.zig"),@import("../webapi/event/DeviceOrientationEvent.zig"),@import("../webapi/event/TouchEvent.zig"),+ @import("../webapi/event/Touch.zig"),+ @import("../webapi/event/TouchList.zig"),@import("../webapi/event/UIEvent.zig"),@import("../webapi/event/MouseEvent.zig"),@import("../webapi/event/PointerEvent.zig"),diff --git a/src/browser/webapi/Event.zig b/src/browser/webapi/Event.zigindex cd15525b8..c74b5c8b7 100644--- a/src/browser/webapi/Event.zig+++ b/src/browser/webapi/Event.zig@@ -194,6 +194,18 @@ pub fn relatedTargetPtr(self: *Event) ?*?*EventTarget {}}+/// Storage of a TouchEvent's Touch.target, for dispatch's shadow-tree+/// retargeting and resets. Mirrors relatedTargetPtr.+pub fn touchTargetPtr(self: *Event) ?*?*EventTarget {+ switch (self._type) {+ .ui_event => |ui| switch (ui._type) {+ .touch_event => |te| return te.touchTargetPtr(),+ else => return null,+ },+ else => return null,+ }+}+pub fn is(self: *Event, comptime T: type) ?*T {switch (self._type) {.generic => return if (T == Event) self else null,diff --git a/src/browser/webapi/WebDriver.zig b/src/browser/webapi/WebDriver.zigindex 4a2ae956d..f9dab4f24 100644--- a/src/browser/webapi/WebDriver.zig+++ b/src/browser/webapi/WebDriver.zig@@ -29,7 +29,7 @@ const Element = @import("Element.zig");const EventTarget = @import("EventTarget.zig");const Cookie = @import("storage/Cookie.zig");-const TouchEvent = @import("event/TouchEvent.zig");+const PointerEvent = @import("event/PointerEvent.zig");const Label = @import("element/html/Label.zig");const log = lp.log;@@ -212,7 +212,9 @@ fn performPointerSource(source: js.Object, frame: *Frame) !void {}const actions = actions_val.toArray();- // A touch pointer dispatches touch events instead of mouse events.+ // 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.var is_touch = false;const params = try source.get("parameters");if (params.isObject()) {@@ -250,13 +252,28 @@ fn performPointerSource(source: js.Object, frame: *Frame) !void {}}const el = target orelse continue;- Frame.user_input.moveSequence(frame, el, .{- .buttons_down = pointer.held,- .modifiers = frame.page.input_modifiers,- .emit_mouse_compat = !is_touch,- }) catch {};- if (is_touch and pointer.held != 0) {- dispatchTouch(el, "touchmove", frame);+ 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, .touchmove, .{ .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;+ dispatchPointer(owner, el, "pointermove", -1, 0, "touch", frame.page.input_touch_next_pointer_id);+ }+ } else {+ 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;@@ -266,27 +283,40 @@ fn performPointerSource(source: js.Object, frame: *Frame) !void {} else {click_count = 1;}- pointer.press(frame, el, .{- .button = button,- .click_count = click_count,- .modifiers = frame.page.input_modifiers,- .emit_mouse_compat = !is_touch,- }) catch {};if (is_touch) {- dispatchTouch(el, "touchstart", frame);+ // 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.triggerTouchOn(owner, el, .touchstart, .{ .x = 0, .y = 0 }, frame.page.input_modifiers) catch |err| {+ log.debug(.app, "webdriver touch", .{ .err = err });+ };+ } else {+ 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);- last_click_button = button;- last_click_target = pointer.release(frame, el, .{- .button = button,- .click_count = click_count,- .modifiers = frame.page.input_modifiers,- .emit_mouse_compat = !is_touch,- }) catch null;if (is_touch) {- dispatchTouch(el, "touchend", frame);+ const contact = frame.page.input_touch_contact orelse continue;+ const captured = contact.target;+ const owner = captured.ownerFrame(frame) orelse continue;+ Frame.user_input.triggerTouchLiftOn(owner, .touchend, null, frame.page.input_modifiers, captured) 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;}}// "pause" carries timing only and is ignored. ("pointerCancel" is not@@ -374,6 +404,28 @@ fn readI32(obj: js.Object, key: []const u8, default: i32) i32 {return val.toI32() catch default;}+fn dispatchPointer(frame: *Frame, el: *Element, comptime typ: []const u8, button: i32, buttons: u16, pointer_type: []const u8, pointer_id: i32) void {+ const modifiers = frame.page.input_modifiers;+ const event = PointerEvent.initTrusted(typ, .{+ .bubbles = true,+ .cancelable = true,+ .composed = true,+ .button = button,+ .buttons = buttons,+ .pointerId = pointer_id,+ .pointerType = pointer_type,+ .isPrimary = true,+ .ctrlKey = modifiers.ctrl,+ .shiftKey = modifiers.shift,+ .altKey = modifiers.alt,+ .metaKey = modifiers.meta,+ }, frame) catch |err| {+ log.debug(.app, "webdriver pointer event", .{ .err = err, .type = typ });+ return;+ };+ dispatch(el.asEventTarget(), event.asEvent(), frame, typ);+}+// The action's x/y, which the caller already resolved the target from. An// element origin makes them offsets from its center, but the faux layout has// no center worth computing.@@ -389,19 +441,6 @@ fn dispatch(target: *EventTarget, event: *Event, frame: *Frame, typ: []const u8)};}-fn dispatchTouch(el: *Element, comptime typ: []const u8, frame: *Frame) void {- const owner = el.ownerFrame(frame) orelse return;- const event = TouchEvent.initTrusted(typ, .{- .bubbles = true,- .composed = true,- }, owner) catch |err| {- log.debug(.app, "webdriver touch event", .{ .err = err });- return;- };- event.asEvent()._cancelable_unless_passive = true;- dispatch(el.asEventTarget(), event.asEvent(), owner, typ);-}-pub const JsApi = struct {pub const bridge = js.Bridge(WebDriver);@@ -417,3 +456,343 @@ pub const JsApi = struct {pub const actionSequence = bridge.function(WebDriver.actionSequence, .{});pub const click = bridge.function(WebDriver.click, .{});};++const testing = @import("../../testing.zig");++test "WebApi: WebDriver touch actionSequence populates touches" {+ if (!lp.build_config.wpt_extensions) return error.SkipZigTest;++ const page = try testing.pageTest("mcp_actions.html", .{});+ defer page.close();+ const frame = page.frame().?;+ frame.page.input_modifiers = .{ .alt = true, .ctrl = true, .meta = true, .shift = true };++ var ls: js.Local.Scope = undefined;+ frame.js.localScope(&ls);+ defer ls.deinit();++ var try_catch: js.TryCatch = undefined;+ try_catch.init(&ls.local);+ defer try_catch.deinit();++ _ = try ls.local.compileAndRun(+ \\const t = document.getElementById('hoverTarget');+ \\window.pointerTypes = [];+ \\for (const type of ['pointermove', 'pointerdown', 'pointerup']) {+ \\ t.addEventListener(type, e => { pointerTypes.push(e.pointerType); });+ \\}+ \\t.addEventListener('touchstart', (e) => {+ \\ window.start = e.touches.length === 1 &&+ \\ e.targetTouches.length === 1 &&+ \\ e.changedTouches.length === 1 &&+ \\ e.touches[0].target === t && e.altKey && e.ctrlKey && e.metaKey && e.shiftKey;+ \\});+ \\t.addEventListener('touchend', (e) => {+ \\ window.end = e.touches.length === 0 &&+ \\ e.targetTouches.length === 0 &&+ \\ e.changedTouches.length === 1 &&+ \\ e.changedTouches[0].target === t && e.altKey && e.ctrlKey && e.metaKey && e.shiftKey;+ \\});+ \\window.webdriver.actionSequence([{+ \\ type: 'pointer',+ \\ parameters: { pointerType: 'touch' },+ \\ actions: [+ \\ { type: 'pointerMove', origin: t },+ \\ { type: 'pointerDown', button: 0 },+ \\ { type: 'pointerUp', button: 0 },+ \\ ],+ \\}]);+ , null);++ try testing.waitForFrame();++ const result = try ls.local.compileAndRun(+ "window.start === true && window.end === true && JSON.stringify(pointerTypes) === '[\"touch\",\"touch\",\"touch\"]'",+ null,+ );+ try testing.expect(result.isTrue());+}++test "WebApi: WebDriver touchmove/touchend stay on the touchstart target" {+ if (!lp.build_config.wpt_extensions) return error.SkipZigTest;++ 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 try_catch: js.TryCatch = undefined;+ try_catch.init(&ls.local);+ defer try_catch.deinit();++ _ = try ls.local.compileAndRun(+ \\const a = document.getElementById('hoverTarget');+ \\const b = document.getElementById('btn');+ \\window.moveOnA = false;+ \\window.moveOnB = false;+ \\window.endOnA = false;+ \\window.endOnB = false;+ \\window.pointerMoveOnACount = 0;+ \\window.pointerMoveOnBCount = 0;+ \\window.pointerUpOnA = false;+ \\window.pointerUpOnB = false;+ \\a.addEventListener('touchmove', (e) => {+ \\ window.moveOnA = e.touches.length === 1 && e.touches[0].target === a;+ \\});+ \\b.addEventListener('touchmove', () => { window.moveOnB = true; });+ \\a.addEventListener('touchend', (e) => {+ \\ 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.addEventListener('pointermove', e => { if (e.pointerType === 'touch') window.pointerMoveOnACount++; });+ \\b.addEventListener('pointermove', () => { window.pointerMoveOnBCount++; });+ \\a.addEventListener('pointerup', e => { window.pointerUpOnA = e.pointerType === 'touch'; });+ \\b.addEventListener('pointerup', () => { window.pointerUpOnB = true; });+ \\window.webdriver.actionSequence([{+ \\ type: 'pointer',+ \\ parameters: { pointerType: 'touch' },+ \\ actions: [+ \\ { type: 'pointerMove', origin: a },+ \\ { type: 'pointerDown', button: 0 },+ \\ { type: 'pointerMove', origin: b },+ \\ { type: 'pointerUp', button: 0 },+ \\ ],+ \\}]);+ , null);++ 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" +++ " && window.pointerUpOnA === true && window.pointerUpOnB !== true",+ null,+ );+ 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;++ 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 try_catch: js.TryCatch = undefined;+ try_catch.init(&ls.local);+ defer try_catch.deinit();++ _ = try ls.local.compileAndRun(+ \\window.sawTouchend = false;+ \\document.getElementById('hoverTarget').addEventListener('touchend', () => { window.sawTouchend = true; });+ \\window.webdriver.actionSequence([{+ \\ type: 'pointer',+ \\ parameters: { pointerType: 'touch' },+ \\ actions: [+ \\ { type: 'pointerMove', origin: document.getElementById('hoverTarget') },+ \\ { type: 'pointerUp', button: 0 },+ \\ ],+ \\}]);+ , null);++ try testing.waitForFrame();++ const result = try ls.local.compileAndRun("window.sawTouchend === false", null);+ 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;++ 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 try_catch: js.TryCatch = undefined;+ try_catch.init(&ls.local);+ defer try_catch.deinit();++ _ = try ls.local.compileAndRun(+ \\window.touchendCount = 0;+ \\document.getElementById('hoverTarget').addEventListener('touchend', () => { window.touchendCount++; });+ \\window.webdriver.actionSequence([{+ \\ type: 'pointer',+ \\ parameters: { pointerType: 'touch' },+ \\ actions: [+ \\ { type: 'pointerMove', origin: document.getElementById('hoverTarget') },+ \\ { type: 'pointerDown', button: 0 },+ \\ { type: 'pointerUp', button: 0 },+ \\ { type: 'pointerUp', button: 0 },+ \\ ],+ \\}]);+ , null);++ try testing.waitForFrame();++ const result = try ls.local.compileAndRun("window.touchendCount === 1", null);+ 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;++ 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 try_catch: js.TryCatch = undefined;+ try_catch.init(&ls.local);+ defer try_catch.deinit();++ _ = try ls.local.compileAndRun(+ \\const box = document.getElementById('chk');+ \\const other = document.getElementById('btn');+ \\window.clicked = false;+ \\window.tapIds = [];+ \\box.addEventListener('pointerdown', e => { if (e.pointerType === 'touch') window.tapIds.push(e.pointerId); });+ \\box.addEventListener('pointerup', e => { if (e.pointerType === 'touch') window.tapIds.push(e.pointerId); });+ \\window.webdriver.actionSequence([{+ \\ type: 'pointer',+ \\ parameters: { pointerType: 'touch' },+ \\ actions: [+ \\ { type: 'pointerMove', origin: box },+ \\ { type: 'pointerDown', button: 0 },+ \\ { type: 'pointerUp', button: 0 },+ \\ { type: 'pointerMove', origin: box },+ \\ { type: 'pointerDown', button: 0 },+ \\ { type: 'pointerMove', origin: other },+ \\ { type: 'pointerUp', button: 0 },+ \\ ],+ \\}]);+ , null);++ try testing.waitForFrame();++ const result = try ls.local.compileAndRun(+ \\box.checked === true && document.activeElement === box && window.clicked !== true &&+ \\window.tapIds.length === 4 && window.tapIds[0] === window.tapIds[1] && window.tapIds[0] !== 1 &&+ \\window.tapIds[2] === window.tapIds[3] && window.tapIds[2] !== window.tapIds[0]+ , null);+ 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;++ 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 try_catch: js.TryCatch = undefined;+ try_catch.init(&ls.local);+ defer try_catch.deinit();++ _ = try ls.local.compileAndRun(+ \\window.sawPointerup = false;+ \\window.sawMouseup = false;+ \\window.sawClick = false;+ \\const t = document.getElementById('hoverTarget');+ \\t.addEventListener('pointerup', () => { window.sawPointerup = true; });+ \\t.addEventListener('mouseup', () => { window.sawMouseup = true; });+ \\t.addEventListener('click', () => { window.sawClick = true; });+ \\window.webdriver.actionSequence([{+ \\ type: 'pointer',+ \\ parameters: { pointerType: 'mouse' },+ \\ actions: [+ \\ { type: 'pointerMove', origin: t },+ \\ { type: 'pointerUp', button: 0 },+ \\ ],+ \\}]);+ , null);++ try testing.waitForFrame();++ const result = try ls.local.compileAndRun(+ "window.sawPointerup === false && window.sawMouseup === false && window.sawClick === false",+ null,+ );+ 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;++ 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 try_catch: js.TryCatch = undefined;+ try_catch.init(&ls.local);+ defer try_catch.deinit();++ _ = try ls.local.compileAndRun(+ \\window.clickCount = 0;+ \\window.dblclickCount = 0;+ \\window.mousePointerTypes = [];+ \\const t = document.getElementById('hoverTarget');+ \\for (const type of ['pointermove', 'pointerdown', 'pointerup']) {+ \\ t.addEventListener(type, e => { mousePointerTypes.push(e.pointerType); });+ \\}+ \\t.addEventListener('click', () => { window.clickCount++; });+ \\t.addEventListener('dblclick', () => { window.dblclickCount++; });+ \\window.webdriver.actionSequence([{+ \\ type: 'pointer',+ \\ parameters: { pointerType: 'mouse' },+ \\ actions: [+ \\ { type: 'pointerMove', origin: t },+ \\ { type: 'pointerDown', button: 0 },+ \\ { type: 'pointerUp', button: 0 },+ \\ { type: 'pointerUp', button: 0 },+ \\ ],+ \\}]);+ , null);++ try testing.waitForFrame();++ const result = try ls.local.compileAndRun(+ "window.clickCount === 1 && window.dblclickCount === 0 && JSON.stringify(mousePointerTypes) === '[\"mouse\",\"mouse\",\"mouse\"]'",+ null,+ );+ try testing.expect(result.isTrue());+}diff --git a/src/browser/webapi/event/Touch.zig b/src/browser/webapi/event/Touch.zignew file mode 100644index 000000000..eeca1625e--- /dev/null+++ b/src/browser/webapi/event/Touch.zig@@ -0,0 +1,122 @@+// Copyright (C) 2023-2026 Lightpanda (Selecy SAS)+//+// Francis Bouvier <[email protected]>+// Pierre Tachoire <[email protected]>+//+// This program is free software: you can redistribute it and/or modify+// it under the terms of the GNU Affero General Public License as+// published by the Free Software Foundation, either version 3 of the+// License, or (at your option) any later version.+//+// This program is distributed in the hope that it will be useful,+// but WITHOUT ANY WARRANTY; without even the implied warranty of+// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the+// GNU Affero General Public License for more details.+//+// 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 js = @import("../../js/js.zig");+const Page = @import("../../Page.zig");+const EventTarget = @import("../EventTarget.zig");+const TouchEvent = @import("TouchEvent.zig");++// https://w3c.github.io/touch-events/#idl-def-touch+//+// Stored by value inside its TouchEvent, so its address is stable for the+// event's lifetime.+const Touch = @This();++_event: *TouchEvent,+_identifier: i32,+// EventTarget, not Element, per spec, and because dispatch retargets it+// across shadow boundaries the same way it retargets Event.target (see+// TouchEvent.touchTargetPtr / EventManager's AdjustedTargets).+_target: ?*EventTarget,+_client_x: f64,+_client_y: f64,+_radius_x: f64,+_radius_y: f64,+_rotation_angle: f64,+_force: f64,++pub fn acquireRef(self: *Touch) void {+ self._event.asEvent().acquireRef();+}++pub fn releaseRef(self: *Touch, page: *Page) void {+ self._event.asEvent().releaseRef(page);+}++fn getIdentifier(self: *const Touch) i32 {+ return self._identifier;+}++fn getTarget(self: *const Touch) ?*EventTarget {+ return self._target;+}++fn getClientX(self: *const Touch) f64 {+ return self._client_x;+}++fn getClientY(self: *const Touch) f64 {+ return self._client_y;+}++/// This engine has no layout, so screenX/screenY and pageX/pageY alias+/// clientX/clientY, the same simplification MouseEvent.compatCoordinate makes.+fn getPageX(self: *const Touch) f64 {+ return self._client_x;+}++fn getPageY(self: *const Touch) f64 {+ return self._client_y;+}++fn getScreenX(self: *const Touch) f64 {+ return self._client_x;+}++fn getScreenY(self: *const Touch) f64 {+ return self._client_y;+}++fn getRadiusX(self: *const Touch) f64 {+ return self._radius_x;+}++fn getRadiusY(self: *const Touch) f64 {+ return self._radius_y;+}++fn getRotationAngle(self: *const Touch) f64 {+ return self._rotation_angle;+}++fn getForce(self: *const Touch) f64 {+ return self._force;+}++pub const JsApi = struct {+ pub const bridge = js.Bridge(Touch);++ pub const Meta = struct {+ pub const name = "Touch";+ pub const prototype_chain = bridge.prototypeChain();+ pub var class_id: bridge.ClassId = undefined;+ };++ pub const identifier = bridge.accessor(Touch.getIdentifier, null, .{});+ pub const target = bridge.accessor(Touch.getTarget, null, .{});+ pub const clientX = bridge.accessor(Touch.getClientX, null, .{});+ pub const clientY = bridge.accessor(Touch.getClientY, null, .{});+ pub const pageX = bridge.accessor(Touch.getPageX, null, .{});+ pub const pageY = bridge.accessor(Touch.getPageY, null, .{});+ pub const screenX = bridge.accessor(Touch.getScreenX, null, .{});+ pub const screenY = bridge.accessor(Touch.getScreenY, null, .{});+ pub const radiusX = bridge.accessor(Touch.getRadiusX, null, .{});+ pub const radiusY = bridge.accessor(Touch.getRadiusY, null, .{});+ pub const rotationAngle = bridge.accessor(Touch.getRotationAngle, null, .{});+ pub const force = bridge.accessor(Touch.getForce, null, .{});+};diff --git a/src/browser/webapi/event/TouchEvent.zig b/src/browser/webapi/event/TouchEvent.zigindex b46c60cdc..113a3f176 100644--- a/src/browser/webapi/event/TouchEvent.zig+++ b/src/browser/webapi/event/TouchEvent.zig@@ -22,12 +22,18 @@ const js = @import("../../js/js.zig");const Frame = @import("../../Frame.zig");const Event = @import("../Event.zig");+const Element = @import("../Element.zig");+const EventTarget = @import("../EventTarget.zig");const UIEvent = @import("UIEvent.zig");+const Touch = @import("Touch.zig");+const TouchList = @import("TouchList.zig");const String = lp.String;// https://w3c.github.io/touch-events/#touchevent-interface-// There is no touch input source: the touch lists are always empty.+//+// 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;@@ -37,8 +43,13 @@ _alt_key: bool = false,_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,-const TouchEventOptions = struct {+pub const TouchEventOptions = struct {altKey: bool = false,ctrlKey: bool = false,metaKey: bool = false,@@ -50,6 +61,17 @@ pub const Options = Event.inheritOptions(TouchEventOptions,);+pub const TouchInit = struct {+ identifier: i32 = 0,+ target: *Element,+ clientX: f64,+ clientY: f64,+ radiusX: f64 = 1,+ radiusY: f64 = 1,+ rotationAngle: f64 = 0,+ force: f64 = 1,+};+pub fn init(typ: []const u8, _opts: ?Options, frame: *Frame) !*TouchEvent {return initWithTrusted(typ, _opts, false, frame);}@@ -58,6 +80,25 @@ pub fn initTrusted(typ: []const u8, _opts: ?Options, frame: *Frame) !*TouchEventreturn 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, touch_init: TouchInit, active: bool, frame: *Frame) !*TouchEvent {+ const event = try initWithTrusted(typ, _opts, true, frame);+ event._touch = .{+ ._event = event,+ ._identifier = touch_init.identifier,+ ._target = touch_init.target.asEventTarget(),+ ._client_x = touch_init.clientX,+ ._client_y = touch_init.clientY,+ ._radius_x = touch_init.radiusX,+ ._radius_y = touch_init.radiusY,+ ._rotation_angle = touch_init.rotationAngle,+ ._force = touch_init.force,+ };+ event._touch_active = active;+ return event;+}+fn initWithTrusted(typ: []const u8, _opts: ?Options, trusted: bool, frame: *Frame) !*TouchEvent {const arena = try frame.getArena(.tiny, "TouchEvent");errdefer arena.release();@@ -84,16 +125,45 @@ pub fn asEvent(self: *TouchEvent) *Event {return self._proto.asEvent();}-fn getTouches(_: *const TouchEvent) []const bool {- return &.{};+/// 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;+}++/// 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).+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 list = try arena.create(TouchList);+ list.* = .{ ._event = self, ._touch = touch };+ cache.* = list;+ return list;+}++pub fn getTouches(self: *TouchEvent) !*TouchList {+ return self.touchList(true, &self._touches_list);}-fn getTargetTouches(_: *const TouchEvent) []const bool {- return &.{};+pub fn getTargetTouches(self: *TouchEvent) !*TouchList {+ return self.touchList(true, &self._target_touches_list);}-fn getChangedTouches(_: *const TouchEvent) []const bool {- return &.{};+pub fn getChangedTouches(self: *TouchEvent) !*TouchList {+ return self.touchList(false, &self._changed_list);}pub fn getAltKey(self: *const TouchEvent) bool {diff --git a/src/browser/webapi/event/TouchList.zig b/src/browser/webapi/event/TouchList.zignew file mode 100644index 000000000..44c5caf0e--- /dev/null+++ b/src/browser/webapi/event/TouchList.zig@@ -0,0 +1,78 @@+// Copyright (C) 2023-2026 Lightpanda (Selecy SAS)+//+// Francis Bouvier <[email protected]>+// Pierre Tachoire <[email protected]>+//+// This program is free software: you can redistribute it and/or modify+// it under the terms of the GNU Affero General Public License as+// published by the Free Software Foundation, either version 3 of the+// License, or (at your option) any later version.+//+// This program is distributed in the hope that it will be useful,+// but WITHOUT ANY WARRANTY; without even the implied warranty of+// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the+// GNU Affero General Public License for more details.+//+// 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 js = @import("../../js/js.zig");+const Page = @import("../../Page.zig");+const Frame = @import("../../Frame.zig");+const Touch = @import("Touch.zig");+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.+const TouchList = @This();++_event: *TouchEvent,+_touch: ?*Touch,++pub fn acquireRef(self: *TouchList) void {+ self._event.asEvent().acquireRef();+}++pub fn releaseRef(self: *TouchList, page: *Page) void {+ self._event.asEvent().releaseRef(page);+}++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;+ }+ return self._touch;+}++pub const JsApi = struct {+ pub const bridge = js.Bridge(TouchList);++ pub const Meta = struct {+ pub const name = "TouchList";+ pub const prototype_chain = bridge.prototypeChain();+ pub var class_id: bridge.ClassId = undefined;+ };++ pub const length = bridge.accessor(TouchList.length, null, .{});+ pub const @"[]" = bridge.indexed(TouchList.indexedGet, getIndexes, .{ .null_as_undefined = true });+ pub const item = bridge.function(TouchList.item, .{});++ fn getIndexes(self: *TouchList, frame: *Frame) !js.Array {+ const len = self.length();+ var arr = frame.js.local.?.newArray(len);+ for (0..len) |i| {+ _ = try arr.set(@intCast(i), i, .{});+ }+ return arr;+ }+};diff --git a/src/server/cdp/domains/input.zig b/src/server/cdp/domains/input.zigindex 96ae3cab2..9a092591e 100644--- a/src/server/cdp/domains/input.zig+++ b/src/server/cdp/domains/input.zig@@ -19,6 +19,7 @@const std = @import("std");const CDP = @import("../CDP.zig");const Frame = @import("../../../browser/Frame.zig");+const Element = @import("../../../browser/webapi/Element.zig");const dom_button = Frame.user_input.mouse_button;@@ -26,12 +27,14 @@ pub fn processMessage(cmd: *CDP.Command) !void {const action = std.meta.stringToEnum(enum {dispatchKeyEvent,dispatchMouseEvent,+ dispatchTouchEvent,insertText,}, cmd.input.action) orelse return error.UnknownMethod;switch (action) {.dispatchKeyEvent => return dispatchKeyEvent(cmd),.dispatchMouseEvent => return dispatchMouseEvent(cmd),+ .dispatchTouchEvent => return dispatchTouchEvent(cmd),.insertText => return insertText(cmd),}}@@ -66,13 +69,14 @@ fn dispatchKeyEvent(cmd: *CDP.Command) !void {// like Backspace, the arrows and Escape.const text: ?[]const u8 = if (params.text.len == 0 or params.type == .rawKeyDown) null else params.text;const KeyboardEvent = @import("../../../browser/webapi/event/KeyboardEvent.zig");+ const modifiers = cdpModifiers(params.modifiers);const opts: KeyboardEvent.Options = .{.key = if (params.key.len > 0) params.key else params.text,.code = params.code,- .altKey = params.modifiers & 1 == 1,- .ctrlKey = params.modifiers & 2 == 2,- .metaKey = params.modifiers & 4 == 4,- .shiftKey = params.modifiers & 8 == 8,+ .altKey = modifiers.alt,+ .ctrlKey = modifiers.ctrl,+ .metaKey = modifiers.meta,+ .shiftKey = modifiers.shift,};switch (params.type) {@@ -152,6 +156,116 @@ fn dispatchMouseEvent(cmd: *CDP.Command) !void {// result already sent}+/// 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.+fn dispatchTouchEvent(cmd: *CDP.Command) !void {+ const params = (cmd.params(struct {+ type: Type,+ modifiers: u4 = 0,+ touchPoints: []const struct {+ x: f64,+ y: f64,+ // 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.+ id: i32 = 0,+ // Puppeteer sends 0.5 for all three on every tap, so a page+ // reading pressure sees the client's value and not a default.+ radiusX: f64 = 1,+ radiusY: f64 = 1,+ rotationAngle: f64 = 0,+ force: f64 = 1,+ },++ const Type = enum {+ touchStart,+ touchMove,+ touchEnd,+ touchCancel,+ };+ }) catch return error.InvalidParams) orelse return error.InvalidParams;++ switch (params.type) {+ .touchStart, .touchMove => if (params.touchPoints.len != 1) return error.InvalidParams,+ .touchEnd => if (params.touchPoints.len > 1) return error.InvalidParams,+ .touchCancel => if (params.touchPoints.len != 0) return error.InvalidParams,+ }++ const bc = cmd.browser_context orelse {+ try cmd.sendResult(null, .{});+ return;+ };+ const frame = bc.mainFrame() orelse {+ try cmd.sendResult(null, .{});+ return;+ };++ 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.user_input.hasActiveTouch(frame)) return error.InvalidParams;+ },+ .touchMove, .touchEnd, .touchCancel => {+ const contact = frame.page.input_touch_contact orelse return error.InvalidParams;+ if (params.touchPoints.len == 1 and params.touchPoints[0].id != contact.point.identifier) {+ return error.InvalidParams;+ }+ },+ }++ 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 lift_point: ?Frame.user_input.TouchPoint = if (params.touchPoints.len == 1) p: {+ const wire = params.touchPoints[0];+ break :p .{+ .x = wire.x,+ .y = wire.y,+ .identifier = wire.id,+ .radius_x = wire.radiusX,+ .radius_y = wire.radiusY,+ .rotation_angle = wire.rotationAngle,+ .force = wire.force,+ };+ } else null;++ const modifiers = cdpModifiers(params.modifiers);++ switch (params.type) {+ .touchStart => try Frame.user_input.triggerTouch(frame, .touchstart, lift_point.?, modifiers),+ .touchMove => try Frame.user_input.triggerTouch(frame, .touchmove, lift_point.?, modifiers),+ .touchEnd => try Frame.user_input.triggerTouchLift(frame, .touchend, lift_point, modifiers),+ .touchCancel => try Frame.user_input.triggerTouchLift(frame, .touchcancel, lift_point, 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,+ .ctrl = bits & 2 != 0,+ .meta = bits & 4 != 0,+ .shift = bits & 8 != 0,+ };+}+// https://chromedevtools.github.io/devtools-protocol/tot/Input/#method-insertTextfn insertText(cmd: *CDP.Command) !void {const params = (try cmd.params(struct {@@ -1300,7 +1414,10 @@ test "cdp.input: chorded mousedown focuses its target unless pointerdown or mous}}-test "cdp.input: dispatchKeyEvent Tab runs sequential focus navigation" {+// 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.+test "cdp.input: dispatchTouchEvent reports the client's radius, angle and force" {var ctx = try testing.context();defer ctx.deinit();@@ -1315,128 +1432,112 @@ test "cdp.input: dispatchKeyEvent Tab runs sequential focus navigation" {var ls: lp.js.Local.Scope = undefined;frame.js.localScope(&ls);defer ls.deinit();-- var try_catch: lp.js.TryCatch = undefined;- try_catch.init(&ls.local);- defer try_catch.deinit();-- // Three controls whose tabindex order (1, 2, 3) differs from document- // order (2, 1, 3): focus order must follow tabindex, not the tree._ = try ls.local.compileAndRun(- \\document.body.innerHTML =- \\ '<input id="i2" tabindex="2">' +- \\ '<button id="b1" tabindex="1">b</button>' +- \\ '<select id="s3" tabindex="3"></select>';+ \\window.seen = [];+ \\const target = document.getElementById('hoverTarget');+ \\for (const type of ['touchstart', 'touchend']) {+ \\ target.addEventListener(type, e => {+ \\ const t = e.changedTouches[0];+ \\ seen.push([t.radiusX, t.radiusY, t.rotationAngle, t.force]);+ \\ });+ \\}, null);+ const x = try (try ls.local.compileAndRun("target.getBoundingClientRect().x", null)).toF64();+ const y = try (try ls.local.compileAndRun("target.getBoundingClientRect().y", null)).toF64();- // Nothing focused yet → activeElement is <body>.- try testing.expect((try ls.local.compileAndRun("document.activeElement === document.body", null)).isTrue());-- // First Tab → lowest positive tabindex (#b1), regardless of document order.try ctx.processMessage(.{.id = 1,- .method = "Input.dispatchKeyEvent",- .params = .{ .type = "keyDown", .key = "Tab", .code = "Tab" },+ .method = "Input.dispatchTouchEvent",+ .params = .{ .type = "touchStart", .touchPoints = &.{+ .{ .x = x, .y = y, .radiusX = 0.5, .radiusY = 0.5, .force = 0.5 },+ } },});- try testing.expect((try ls.local.compileAndRun("document.activeElement.id === 'b1'", null)).isTrue());- // Second Tab → next in tabindex order (#i2).+ // Chrome defaults each omitted radius independently to 1.try ctx.processMessage(.{.id = 2,- .method = "Input.dispatchKeyEvent",- .params = .{ .type = "keyDown", .key = "Tab", .code = "Tab" },+ .method = "Input.dispatchTouchEvent",+ .params = .{ .type = "touchEnd", .touchPoints = &.{+ .{ .x = x, .y = y, .radiusX = 3, .rotationAngle = 45 },+ } },});- try testing.expect((try ls.local.compileAndRun("document.activeElement.id === 'i2'", null)).isTrue());- // Shift+Tab (modifiers bit 8) walks backward → back to #b1.try ctx.processMessage(.{.id = 3,- .method = "Input.dispatchKeyEvent",- .params = .{ .type = "keyDown", .key = "Tab", .code = "Tab", .modifiers = 8 },+ .method = "Input.dispatchTouchEvent",+ .params = .{ .type = "touchStart", .touchPoints = &.{+ .{ .x = x, .y = y, .radiusY = 4 },+ } },});- try testing.expect((try ls.local.compileAndRun("document.activeElement.id === 'b1'", null)).isTrue());++ try testing.expect((try ls.local.compileAndRun(+ \\JSON.stringify(seen) === JSON.stringify([[0.5, 0.5, 0, 0.5], [3, 1, 45, 1], [1, 4, 0, 1]])+ , null)).isTrue());}-test "cdp.input: dispatchKeyEvent beforeinput can veto the edit" {+test "cdp.input: dispatchTouchEvent touchStart populates touches/targetTouches/changedTouches" {var ctx = try testing.context();defer ctx.deinit();const bc = try ctx.loadBrowserContext(.{});const page = try bc.session.createPage();const frame = page.frame().?;- try frame.navigate("http://localhost:9582/src/browser/tests/mcp_actions.html", .{- .reason = .address_bar,- .kind = .{ .push = null },- });++ const url = "http://localhost:9582/src/browser/tests/mcp_actions.html";+ try frame.navigate(url, .{ .reason = .address_bar, .kind = .{ .push = null } });try testing.waitForPage(bc);var ls: lp.js.Local.Scope = undefined;frame.js.localScope(&ls);defer ls.deinit();- // A listener that rejects every keystroke, the way masked-input libraries- // do. Records what it saw so we can assert the event was cancelable.+ var try_catch: lp.js.TryCatch = undefined;+ try_catch.init(&ls.local);+ defer try_catch.deinit();+_ = try ls.local.compileAndRun(- \\const inp = document.getElementById('inp');- \\inp.value = 'ab';- \\inp.focus();- \\window.seen = [];- \\inp.addEventListener('beforeinput', (e) => {- \\ window.seen.push(['beforeinput', e.cancelable].join(':'));- \\ e.preventDefault();- \\ window.seen.push(['defaultPrevented', e.defaultPrevented].join(':'));+ \\const t = document.getElementById('hoverTarget');+ \\t.addEventListener('touchstart', (e) => {+ \\ const touch = e.touches[0];+ \\ window.result = e.touches.length === 1 &&+ \\ e.targetTouches.length === 1 &&+ \\ e.changedTouches.length === 1 &&+ \\ touch.target === t &&+ \\ touch === e.changedTouches[0] &&+ \\ e.touches !== e.targetTouches &&+ \\ touch.pageX === touch.clientX &&+ \\ touch.pageY === touch.clientY &&+ \\ touch.screenX === touch.clientX &&+ \\ touch.screenY === touch.clientY &&+ \\ touch.radiusX === 1 &&+ \\ touch.radiusY === 1 &&+ \\ touch.rotationAngle === 0 &&+ \\ touch.force === 1;+ \\ window.touchX = touch.clientX;+ \\ window.touchY = touch.clientY;\\});- \\inp.addEventListener('input', () => window.seen.push('input'));, null);- try ctx.processMessage(.{- .id = 1,- .method = "Input.dispatchKeyEvent",- .params = .{ .type = "keyDown", .key = "c", .text = "c" },- });-- // The veto held: no character inserted and no `input` event followed.- try testing.expect((try ls.local.compileAndRun(- \\inp.value === 'ab' &&- \\window.seen.join(',') === 'beforeinput:true,defaultPrevented:true'- , null)).isTrue());+ const rect_x = try (try ls.local.compileAndRun("document.getElementById('hoverTarget').getBoundingClientRect().x", null)).toF64();+ const rect_y = try (try ls.local.compileAndRun("document.getElementById('hoverTarget').getBoundingClientRect().y", null)).toF64();- // Backspace goes through the same pre-edit gate.try ctx.processMessage(.{- .id = 2,- .method = "Input.dispatchKeyEvent",- .params = .{ .type = "keyDown", .key = "Backspace", .code = "Backspace" },+ .id = 1,+ .method = "Input.dispatchTouchEvent",+ .params = .{ .type = "touchStart", .touchPoints = &.{.{ .x = rect_x, .y = rect_y }} },});- try testing.expect((try ls.local.compileAndRun("inp.value === 'ab'", null)).isTrue());-- // Without the veto, the edit goes through and `input` is dispatched — and- // `input` itself is not cancelable.- _ = try ls.local.compileAndRun(- \\const clone = inp.cloneNode(true);- \\inp.replaceWith(clone);- \\clone.focus();- \\window.seen = [];- \\clone.addEventListener('input', (e) => window.seen.push(['input', e.cancelable].join(':')));- , null);- try ctx.processMessage(.{- .id = 3,- .method = "Input.dispatchKeyEvent",- .params = .{ .type = "keyDown", .key = "c", .text = "c" },- });- try testing.expect((try ls.local.compileAndRun(- \\clone.value === 'abc' && window.seen.join(',') === 'input:false'- , null)).isTrue());+ const result = try ls.local.compileAndRun("window.result === true && window.touchX === document.getElementById('hoverTarget').getBoundingClientRect().x && window.touchY === document.getElementById('hoverTarget').getBoundingClientRect().y", null);+ try testing.expect(result.isTrue());}-test "cdp.input: editing keys honor the selection of a default-valued textarea" {+test "cdp.input: dispatchTouchEvent preserves each event's modifier keys" {var ctx = try testing.context();defer ctx.deinit();const bc = try ctx.loadBrowserContext(.{});const page = try bc.session.createPage();const frame = page.frame().?;-try frame.navigate("http://localhost:9582/src/browser/tests/mcp_actions.html", .{ .reason = .address_bar, .kind = .{ .push = null } });try testing.waitForPage(bc);@@ -1444,36 +1545,50 @@ test "cdp.input: editing keys honor the selection of a default-valued textarea"frame.js.localScope(&ls);defer ls.deinit();- // This <textarea>'s value comes from its child text node — nothing assigns- // to `value` — so the selection has to clamp against the parsed text._ = try ls.local.compileAndRun(- \\document.body.innerHTML = '<textarea id="ta">abcdef</textarea>';- \\const ta = document.getElementById('ta');- \\ta.focus();- \\ta.setSelectionRange(2, 4);+ \\window.touchModifiers = [];+ \\for (const type of ['touchstart', 'touchmove', 'touchend', 'touchcancel']) {+ \\ document.addEventListener(type, e => {+ \\ touchModifiers.push([e.type, e.altKey, e.ctrlKey, e.metaKey, e.shiftKey]);+ \\ });+ \\}, null);- try testing.expect((try ls.local.compileAndRun("ta.selectionStart === 2 && ta.selectionEnd === 4", null)).isTrue());- // Backspace over a range deletes the range, leaving the caret at its start.+ const steps = .{+ .{ "touchStart", 1 },+ .{ "touchMove", 2 },+ .{ "touchEnd", 4 },+ .{ "touchStart", 15 },+ .{ "touchCancel", 8 },+ };+ inline for (steps, 1..) |step, id| {+ const is_lift = comptime std.mem.eql(u8, step[0], "touchEnd") or std.mem.eql(u8, step[0], "touchCancel");+ try ctx.processMessage(.{+ .id = id,+ .method = "Input.dispatchTouchEvent",+ .params = .{ .type = step[0], .modifiers = step[1], .touchPoints = if (is_lift) &.{} else &.{.{ .x = 0, .y = 0 }} },+ });+ }+ // Omitted modifiers reset to false, even after a modified gesture.try ctx.processMessage(.{- .id = 1,- .method = "Input.dispatchKeyEvent",- .params = .{ .type = "keyDown", .key = "Backspace", .code = "Backspace" },+ .id = 6,+ .method = "Input.dispatchTouchEvent",+ .params = .{ .type = "touchStart", .touchPoints = &.{.{ .x = 0, .y = 0 }} },});- try testing.expect((try ls.local.compileAndRun("ta.value === 'abef'", null)).isTrue());- try testing.expect((try ls.local.compileAndRun("ta.selectionStart === 2 && ta.selectionEnd === 2", null)).isTrue());- // Collapsed caret: Backspace removes the character on its left.- _ = try ls.local.compileAndRun("ta.setSelectionRange(3, 3)", null);- try ctx.processMessage(.{- .id = 2,- .method = "Input.dispatchKeyEvent",- .params = .{ .type = "keyDown", .key = "Backspace", .code = "Backspace" },- });- try testing.expect((try ls.local.compileAndRun("ta.value === 'abf'", null)).isTrue());+ try testing.expect((try ls.local.compileAndRun(+ \\JSON.stringify(touchModifiers) === JSON.stringify([+ \\ ['touchstart', true, false, false, false],+ \\ ['touchmove', false, true, false, false],+ \\ ['touchend', false, false, true, false],+ \\ ['touchstart', true, true, true, true],+ \\ ['touchcancel', false, false, false, true],+ \\ ['touchstart', false, false, false, false]+ \\])+ , null)).isTrue());}-test "cdp.input: dispatchKeyEvent caret movement keys move the text entry cursor" {+test "cdp.input: dispatchTouchEvent touchEnd empties touches but keeps changedTouches" {var ctx = try testing.context();defer ctx.deinit();@@ -1494,104 +1609,905 @@ test "cdp.input: dispatchKeyEvent caret movement keys move the text entry cursordefer try_catch.deinit();_ = try ls.local.compileAndRun(- \\document.body.innerHTML = '<input id="t" type="text"><textarea id="ta"></textarea>';- \\const t = document.getElementById('t');- \\const ta = document.getElementById('ta');- \\const sel = (e) => [e.selectionStart, e.selectionEnd, e.selectionDirection].join(',');- \\t.focus(); t.value = 'abcdef'; t.setSelectionRange(6, 6);+ \\const t = document.getElementById('hoverTarget');+ \\t.addEventListener('touchend', (e) => {+ \\ window.result = e.touches.length === 0 &&+ \\ e.targetTouches.length === 0 &&+ \\ e.changedTouches.length === 1 &&+ \\ e.changedTouches[0].target === t &&+ \\ e.changedTouches[0].clientX === t.getBoundingClientRect().x &&+ \\ e.changedTouches[0].clientY === t.getBoundingClientRect().y;+ \\});, null);- const Step = struct { key: []const u8, modifiers: u4 = 0, expect: []const u8 };- const shift = 8;-- // <input>: plain moves collapse, Shift extends from the anchor, a plain- // arrow on a selection collapses to its edge, ArrowUp/ArrowDown reach the- // ends of a single-line value.- const input_steps = [_]Step{- .{ .key = "ArrowLeft", .expect = "5,5,none" },- .{ .key = "ArrowRight", .expect = "6,6,none" },- .{ .key = "Home", .expect = "0,0,none" },- .{ .key = "End", .expect = "6,6,none" },- .{ .key = "ArrowUp", .expect = "0,0,none" },- .{ .key = "ArrowDown", .expect = "6,6,none" },- .{ .key = "ArrowRight", .expect = "6,6,none" },- .{ .key = "ArrowLeft", .modifiers = shift, .expect = "5,6,backward" },- .{ .key = "Home", .modifiers = shift, .expect = "0,6,backward" },- .{ .key = "ArrowLeft", .expect = "0,0,none" },- .{ .key = "ArrowLeft", .expect = "0,0,none" },- .{ .key = "End", .modifiers = shift, .expect = "0,6,forward" },- .{ .key = "ArrowLeft", .modifiers = shift, .expect = "0,5,forward" },- .{ .key = "ArrowRight", .expect = "5,5,none" },- };- var id: u32 = 1;- for (input_steps) |step| {- try ctx.processMessage(.{- .id = id,- .method = "Input.dispatchKeyEvent",- .params = .{ .type = "keyDown", .key = step.key, .code = step.key, .modifiers = step.modifiers },- });- id += 1;- const got = try (try ls.local.compileAndRun("sel(t)", null)).toStringSlice();- try testing.expectEqualSlices(u8, step.expect, got);- }-- // Type-then-correct: move back two characters and insert in the middle.- _ = try ls.local.compileAndRun("t.setSelectionRange(6, 6)", null);- for (0..2) |_| {- try ctx.processMessage(.{- .id = id,- .method = "Input.dispatchKeyEvent",- .params = .{ .type = "keyDown", .key = "ArrowLeft", .code = "ArrowLeft" },- });- id += 1;- }- try ctx.processMessage(.{ .id = id, .method = "Input.insertText", .params = .{ .text = "X" } });- id += 1;- try testing.expect((try ls.local.compileAndRun("t.value === 'abcdXef' && sel(t) === '5,5,none'", null)).isTrue());+ const rect_x = try (try ls.local.compileAndRun("document.getElementById('hoverTarget').getBoundingClientRect().x", null)).toF64();+ const rect_y = try (try ls.local.compileAndRun("document.getElementById('hoverTarget').getBoundingClientRect().y", null)).toF64();- // Moves step over whole UTF-8 sequences, never landing inside one.- _ = try ls.local.compileAndRun("t.value = 'aé'; t.setSelectionRange(t.value.length, t.value.length)", null);try ctx.processMessage(.{- .id = id,- .method = "Input.dispatchKeyEvent",- .params = .{ .type = "keyDown", .key = "ArrowLeft", .code = "ArrowLeft" },+ .id = 1,+ .method = "Input.dispatchTouchEvent",+ .params = .{ .type = "touchStart", .touchPoints = &.{.{ .x = rect_x, .y = rect_y }} },+ });+ try ctx.processMessage(.{+ .id = 2,+ .method = "Input.dispatchTouchEvent",+ .params = .{ .type = "touchEnd", .touchPoints = &.{} },});- id += 1;- try ctx.processMessage(.{ .id = id, .method = "Input.insertText", .params = .{ .text = "X" } });- id += 1;- try testing.expect((try ls.local.compileAndRun("t.value === 'aXé'", null)).isTrue());- // <textarea>: Home/End stop at the enclosing line break, ArrowLeft crosses it.- _ = try ls.local.compileAndRun("ta.focus(); ta.value = 'ab\\ncd'; ta.setSelectionRange(5, 5)", null);- const textarea_steps = [_]Step{- .{ .key = "Home", .expect = "3,3,none" },- .{ .key = "End", .expect = "5,5,none" },- .{ .key = "Home", .modifiers = shift, .expect = "3,5,backward" },- .{ .key = "ArrowLeft", .expect = "3,3,none" },- .{ .key = "ArrowLeft", .expect = "2,2,none" },- };- for (textarea_steps) |step| {- try ctx.processMessage(.{- .id = id,- .method = "Input.dispatchKeyEvent",- .params = .{ .type = "keyDown", .key = step.key, .code = step.key, .modifiers = step.modifiers },- });- id += 1;- const got = try (try ls.local.compileAndRun("sel(ta)", null)).toStringSlice();- try testing.expectEqualSlices(u8, step.expect, got);- }+ const result = try ls.local.compileAndRun("window.result === true", null);+ try testing.expect(result.isTrue());}-// chromedp's SendKeys shape: a text-less keyDown, the char with the text, keyUp.-test "cdp.input: dispatchKeyEvent text-less keyDown then char types once" {+// 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.+test "cdp.input: dispatchTouchEvent a touchStart past every element still opens a contact" {var ctx = try testing.context();defer ctx.deinit();- const bc = try ctx.loadBrowserContext(.{ .url = "mcp_actions.html" });- const frame = bc.mainFrame().?;+ const bc = try ctx.loadBrowserContext(.{});+ const page = try bc.session.createPage();+ const frame = page.frame().?;- var ls: lp.js.Local.Scope = undefined;- frame.js.localScope(&ls);+ const url = "http://localhost:9582/src/browser/tests/mcp_actions.html";+ try frame.navigate(url, .{ .reason = .address_bar, .kind = .{ .push = null } });+ try testing.waitForPage(bc);++ try ctx.processMessage(.{+ .id = 1,+ .method = "Input.dispatchTouchEvent",+ .params = .{ .type = "touchStart", .touchPoints = &.{.{ .x = 0, .y = 3000 }} },+ });+ try testing.expect(Frame.user_input.hasActiveTouch(frame));++ try ctx.processMessage(.{+ .id = 2,+ .method = "Input.dispatchTouchEvent",+ .params = .{ .type = "touchEnd", .touchPoints = &.{} },+ });+ try testing.expect(!Frame.user_input.hasActiveTouch(frame));+}++test "cdp.input: dispatchTouchEvent empty touchStart is InvalidParams" {+ var ctx = try testing.context();+ defer ctx.deinit();++ const bc = try ctx.loadBrowserContext(.{});+ _ = try bc.session.createPage();++ try ctx.processMessage(.{+ .id = 1,+ .method = "Input.dispatchTouchEvent",+ .params = .{ .type = "touchStart", .touchPoints = &.{} },+ });+ try ctx.expectSentError(-31998, "InvalidParams", .{ .id = 1 });+}++test "cdp.input: dispatchTouchEvent a multi-contact touchStart/touchMove is InvalidParams" {+ var ctx = try testing.context();+ defer ctx.deinit();++ const bc = try ctx.loadBrowserContext(.{});+ _ = try bc.session.createPage();++ try ctx.processMessage(.{+ .id = 1,+ .method = "Input.dispatchTouchEvent",+ .params = .{ .type = "touchStart", .touchPoints = &.{ .{ .x = 0, .y = 0 }, .{ .x = 10, .y = 10 } } },+ });+ try ctx.expectSentError(-31998, "InvalidParams", .{ .id = 1 });++ try ctx.processMessage(.{+ .id = 2,+ .method = "Input.dispatchTouchEvent",+ .params = .{ .type = "touchMove", .touchPoints = &.{ .{ .x = 0, .y = 0 }, .{ .x = 10, .y = 10 } } },+ });+ try ctx.expectSentError(-31998, "InvalidParams", .{ .id = 2 });+}++test "cdp.input: dispatchTouchEvent empty touchEnd with no active contact is InvalidParams" {+ var ctx = try testing.context();+ defer ctx.deinit();++ const bc = try ctx.loadBrowserContext(.{});+ _ = try bc.session.createPage();++ try ctx.processMessage(.{+ .id = 1,+ .method = "Input.dispatchTouchEvent",+ .params = .{ .type = "touchEnd", .touchPoints = &.{} },+ });+ try ctx.expectSentError(-31998, "InvalidParams", .{ .id = 1 });+}++test "cdp.input: dispatchTouchEvent touchMove with no active contact is InvalidParams" {+ var ctx = try testing.context();+ defer ctx.deinit();++ const bc = try ctx.loadBrowserContext(.{});+ _ = try bc.session.createPage();++ try ctx.processMessage(.{+ .id = 1,+ .method = "Input.dispatchTouchEvent",+ .params = .{ .type = "touchMove", .touchPoints = &.{.{ .x = 0, .y = 0 }} },+ });+ try ctx.expectSentError(-31998, "InvalidParams", .{ .id = 1 });+}++test "cdp.input: dispatchTouchEvent tracks the client's chosen id and rejects mismatches" {+ var ctx = try testing.context();+ defer ctx.deinit();+ const bc = try ctx.loadBrowserContext(.{});+ const page = try bc.session.createPage();+ const frame = page.frame().?;+ try frame.navigate("http://localhost:9582/src/browser/tests/mcp_actions.html", .{ .reason = .address_bar, .kind = .{ .push = null } });+ try testing.waitForPage(bc);++ var ls: lp.js.Local.Scope = undefined;+ frame.js.localScope(&ls);+ defer ls.deinit();+ _ = try ls.local.compileAndRun(+ \\window.touchEvents = [];+ \\const target = document.getElementById('hoverTarget');+ \\for (const type of ['touchstart', 'touchmove', 'touchend']) {+ \\ target.addEventListener(type, e => {+ \\ const t = e.changedTouches[0];+ \\ touchEvents.push([e.type, t.identifier, t.clientX, t.clientY]);+ \\ });+ \\}+ , null);+ 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",+ .params = .{ .type = "touchStart", .touchPoints = &.{.{ .x = x, .y = y, .id = 0.5 }} },+ });+ try ctx.expectSentError(-31998, "InvalidParams", .{ .id = 1 });+ try testing.expect(!Frame.user_input.hasActiveTouch(frame));++ // 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",+ .params = .{ .type = "touchStart", .touchPoints = &.{.{ .x = x, .y = y, .id = 7 }} },+ });+ try testing.expectEqual(@as(i32, 7), frame.page.input_touch_contact.?.point.identifier);++ // 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",+ .params = .{ .type = "touchMove", .touchPoints = &.{.{ .x = x + 100, .y = y + 100, .id = 8 }} },+ });+ try ctx.expectSentError(-31998, "InvalidParams", .{ .id = 3 });+ try testing.expectEqual(x, frame.page.input_touch_contact.?.point.x);+ try testing.expectEqual(y, frame.page.input_touch_contact.?.point.y);++ try ctx.processMessage(.{+ .id = 4,+ .method = "Input.dispatchTouchEvent",+ .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",+ .params = .{ .type = "touchEnd", .touchPoints = &.{.{ .x = x + 1, .y = y + 2, .id = 8 }} },+ });+ try ctx.expectSentError(-31998, "InvalidParams", .{ .id = 5 });+ try testing.expect(Frame.user_input.hasActiveTouch(frame));++ // touchEnd with the matching id (Puppeteer) lifts the contact.+ try ctx.processMessage(.{+ .id = 6,+ .method = "Input.dispatchTouchEvent",+ .params = .{ .type = "touchEnd", .touchPoints = &.{.{ .x = x + 1, .y = y + 2, .id = 7 }} },+ });+ try testing.expect(!Frame.user_input.hasActiveTouch(frame));+ try testing.expect((try ls.local.compileAndRun(+ \\JSON.stringify(touchEvents) === JSON.stringify([+ \\ ['touchstart', 7, target.getBoundingClientRect().x, target.getBoundingClientRect().y],+ \\ ['touchmove', 7, target.getBoundingClientRect().x + 1, target.getBoundingClientRect().y + 2],+ \\ ['touchend', 7, target.getBoundingClientRect().x + 1, target.getBoundingClientRect().y + 2]+ \\])+ , 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();++ const bc = try ctx.loadBrowserContext(.{});+ const page = try bc.session.createPage();+ const frame = page.frame().?;++ const url = "http://localhost:9582/src/browser/tests/mcp_actions.html";+ try frame.navigate(url, .{ .reason = .address_bar, .kind = .{ .push = null } });+ try testing.waitForPage(bc);++ var ls: lp.js.Local.Scope = undefined;+ frame.js.localScope(&ls);+ defer ls.deinit();++ _ = try ls.local.compileAndRun(+ \\document.getElementById('hoverTarget')+ \\ .addEventListener('touchstart', () => { window.starts = (window.starts || 0) + 1; });+ , null);++ const first_x = try (try ls.local.compileAndRun("document.getElementById('hoverTarget').getBoundingClientRect().x", null)).toF64();+ const first_y = try (try ls.local.compileAndRun("document.getElementById('hoverTarget').getBoundingClientRect().y", null)).toF64();+ const other_x = try (try ls.local.compileAndRun("document.getElementById('btn').getBoundingClientRect().x", null)).toF64();+ const other_y = try (try ls.local.compileAndRun("document.getElementById('btn').getBoundingClientRect().y", null)).toF64();++ try ctx.processMessage(.{+ .id = 1,+ .method = "Input.dispatchTouchEvent",+ .params = .{ .type = "touchStart", .touchPoints = &.{.{ .x = first_x, .y = first_y }} },+ });++ try ctx.processMessage(.{+ .id = 2,+ .method = "Input.dispatchTouchEvent",+ .params = .{ .type = "touchStart", .touchPoints = &.{.{ .x = other_x, .y = other_y }} },+ });+ 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) => {+ \\ window.endedOnOriginal = e.changedTouches[0].clientX === document.getElementById('hoverTarget').getBoundingClientRect().x;+ \\ });+ , null);+ try ctx.processMessage(.{+ .id = 3,+ .method = "Input.dispatchTouchEvent",+ .params = .{ .type = "touchEnd", .touchPoints = &.{} },+ });++ const result = try ls.local.compileAndRun("window.starts === 1 && window.endedOnOriginal === true", null);+ 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.+test "cdp.input: dispatchTouchEvent a touchEnd carrying the released point is accepted" {+ var ctx = try testing.context();+ defer ctx.deinit();++ const bc = try ctx.loadBrowserContext(.{});+ const page = try bc.session.createPage();+ const frame = page.frame().?;++ const url = "http://localhost:9582/src/browser/tests/mcp_actions.html";+ try frame.navigate(url, .{ .reason = .address_bar, .kind = .{ .push = null } });+ try testing.waitForPage(bc);++ var ls: lp.js.Local.Scope = undefined;+ frame.js.localScope(&ls);+ defer ls.deinit();++ _ = try ls.local.compileAndRun(+ \\const t = document.getElementById('hoverTarget');+ \\t.addEventListener('touchend', (e) => {+ \\ const touch = e.changedTouches[0];+ \\ window.endTarget = touch.target === t;+ \\ window.endX = touch.clientX;+ \\ window.endY = touch.clientY;+ \\});+ , null);++ const rect_x = try (try ls.local.compileAndRun("document.getElementById('hoverTarget').getBoundingClientRect().x", null)).toF64();+ const rect_y = try (try ls.local.compileAndRun("document.getElementById('hoverTarget').getBoundingClientRect().y", null)).toF64();+ const end_x = rect_x + 5;+ const end_y = rect_y + 9;++ try ctx.processMessage(.{+ .id = 1,+ .method = "Input.dispatchTouchEvent",+ .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",+ .params = .{ .type = "touchEnd", .touchPoints = &.{.{ .x = end_x, .y = end_y }} },+ });+ try testing.expect(!Frame.user_input.hasActiveTouch(frame));++ const result = try ls.local.compileAndRun(+ "window.endTarget === true && window.endX === " ++ "document.getElementById('hoverTarget').getBoundingClientRect().x + 5" +++ " && window.endY === document.getElementById('hoverTarget').getBoundingClientRect().y + 9",+ null,+ );+ try testing.expect(result.isTrue());++ // The contact clearing is not left dangling: a fresh touchStart works.+ try ctx.processMessage(.{+ .id = 3,+ .method = "Input.dispatchTouchEvent",+ .params = .{ .type = "touchStart", .touchPoints = &.{.{ .x = rect_x, .y = rect_y }} },+ });+ try testing.expect(Frame.user_input.hasActiveTouch(frame));+}++// 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();++ const bc = try ctx.loadBrowserContext(.{});+ const page = try bc.session.createPage();+ const frame = page.frame().?;++ const url = "http://localhost:9582/src/browser/tests/mcp_actions.html";+ try frame.navigate(url, .{ .reason = .address_bar, .kind = .{ .push = null } });+ try testing.waitForPage(bc);++ var ls: lp.js.Local.Scope = undefined;+ frame.js.localScope(&ls);+ defer ls.deinit();++ _ = try ls.local.compileAndRun(+ \\const t = document.getElementById('hoverTarget');+ \\t.addEventListener('touchend', (e) => {+ \\ const touch = e.changedTouches[0];+ \\ window.endX = touch.clientX;+ \\ window.endY = touch.clientY;+ \\});+ , null);++ const rect_x = try (try ls.local.compileAndRun("document.getElementById('hoverTarget').getBoundingClientRect().x", null)).toF64();+ const rect_y = try (try ls.local.compileAndRun("document.getElementById('hoverTarget').getBoundingClientRect().y", null)).toF64();++ try ctx.processMessage(.{+ .id = 1,+ .method = "Input.dispatchTouchEvent",+ .params = .{ .type = "touchStart", .touchPoints = &.{.{ .x = rect_x, .y = rect_y }} },+ });+ try ctx.processMessage(.{+ .id = 2,+ .method = "Input.dispatchTouchEvent",+ .params = .{ .type = "touchEnd", .touchPoints = &.{} },+ });++ const result = try ls.local.compileAndRun("window.endX === document.getElementById('hoverTarget').getBoundingClientRect().x && window.endY === document.getElementById('hoverTarget').getBoundingClientRect().y", null);+ try testing.expect(result.isTrue());+}++test "cdp.input: dispatchTouchEvent rejects populated touchCancel without lifting contact" {+ var ctx = try testing.context();+ defer ctx.deinit();++ const bc = try ctx.loadBrowserContext(.{});+ const page = try bc.session.createPage();+ const frame = page.frame().?;++ const url = "http://localhost:9582/src/browser/tests/mcp_actions.html";+ try frame.navigate(url, .{ .reason = .address_bar, .kind = .{ .push = null } });+ try testing.waitForPage(bc);++ var ls: lp.js.Local.Scope = undefined;+ frame.js.localScope(&ls);+ defer ls.deinit();++ _ = try ls.local.compileAndRun(+ \\const t = document.getElementById('hoverTarget');+ \\t.addEventListener('touchcancel', (e) => {+ \\ const touch = e.changedTouches[0];+ \\ window.cancelable = e.cancelable;+ \\ window.cancelX = touch.clientX;+ \\ window.cancelY = touch.clientY;+ \\});+ , null);++ const rect_x = try (try ls.local.compileAndRun("document.getElementById('hoverTarget').getBoundingClientRect().x", null)).toF64();+ const rect_y = try (try ls.local.compileAndRun("document.getElementById('hoverTarget').getBoundingClientRect().y", null)).toF64();+ const cancel_x = rect_x + 3;+ const cancel_y = rect_y + 4;++ try ctx.processMessage(.{+ .id = 1,+ .method = "Input.dispatchTouchEvent",+ .params = .{ .type = "touchStart", .touchPoints = &.{.{ .x = rect_x, .y = rect_y }} },+ });+ try ctx.processMessage(.{+ .id = 2,+ .method = "Input.dispatchTouchEvent",+ .params = .{ .type = "touchCancel", .touchPoints = &.{.{ .x = cancel_x, .y = cancel_y }} },+ });+ try ctx.expectSentError(-31998, "InvalidParams", .{ .id = 2 });+ try testing.expect(Frame.user_input.hasActiveTouch(frame));++ try ctx.processMessage(.{+ .id = 3,+ .method = "Input.dispatchTouchEvent",+ .params = .{ .type = "touchCancel", .touchPoints = &.{} },+ });+ try testing.expect(!Frame.user_input.hasActiveTouch(frame));++ const result = try ls.local.compileAndRun(+ "window.cancelable === false && window.cancelX === " ++ "document.getElementById('hoverTarget').getBoundingClientRect().x" +++ " && window.cancelY === document.getElementById('hoverTarget').getBoundingClientRect().y",+ null,+ );+ try testing.expect(result.isTrue());+}++test "cdp.input: dispatchTouchEvent a multi-point touchEnd/touchCancel is InvalidParams" {+ var ctx = try testing.context();+ defer ctx.deinit();++ const bc = try ctx.loadBrowserContext(.{});+ const page = try bc.session.createPage();+ const frame = page.frame().?;++ const url = "http://localhost:9582/src/browser/tests/mcp_actions.html";+ try frame.navigate(url, .{ .reason = .address_bar, .kind = .{ .push = null } });+ try testing.waitForPage(bc);++ var ls: lp.js.Local.Scope = undefined;+ frame.js.localScope(&ls);+ defer ls.deinit();++ const rect_x = try (try ls.local.compileAndRun("document.getElementById('hoverTarget').getBoundingClientRect().x", null)).toF64();+ const rect_y = try (try ls.local.compileAndRun("document.getElementById('hoverTarget').getBoundingClientRect().y", null)).toF64();++ try ctx.processMessage(.{+ .id = 1,+ .method = "Input.dispatchTouchEvent",+ .params = .{ .type = "touchStart", .touchPoints = &.{.{ .x = rect_x, .y = rect_y }} },+ });++ try ctx.processMessage(.{+ .id = 2,+ .method = "Input.dispatchTouchEvent",+ .params = .{ .type = "touchEnd", .touchPoints = &.{ .{ .x = rect_x, .y = rect_y }, .{ .x = rect_x, .y = rect_y, .id = 1 } } },+ });+ try ctx.expectSentError(-31998, "InvalidParams", .{ .id = 2 });+}++// The next four tests call Frame.user_input.dispatchTouchEventOn 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.dispatchTouchEventOn(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.dispatchTouchEventOn(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.dispatchTouchEventOn(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.dispatchTouchEventOn(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 = target,+ .clientX = 10,+ .clientY = 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();++ const bc = try ctx.loadBrowserContext(.{});+ const page = try bc.session.createPage();+ const frame = page.frame().?;++ const url = "http://localhost:9582/src/browser/tests/mcp_actions.html";+ try frame.navigate(url, .{ .reason = .address_bar, .kind = .{ .push = null } });+ try testing.waitForPage(bc);++ var ls: lp.js.Local.Scope = undefined;+ frame.js.localScope(&ls);+ defer ls.deinit();++ var try_catch: lp.js.TryCatch = undefined;+ try_catch.init(&ls.local);+ defer try_catch.deinit();++ // Three controls whose tabindex order (1, 2, 3) differs from document+ // order (2, 1, 3): focus order must follow tabindex, not the tree.+ _ = try ls.local.compileAndRun(+ \\document.body.innerHTML =+ \\ '<input id="i2" tabindex="2">' ++ \\ '<button id="b1" tabindex="1">b</button>' ++ \\ '<select id="s3" tabindex="3"></select>';+ , null);++ // Nothing focused yet → activeElement is <body>.+ try testing.expect((try ls.local.compileAndRun("document.activeElement === document.body", null)).isTrue());++ // First Tab → lowest positive tabindex (#b1), regardless of document order.+ try ctx.processMessage(.{+ .id = 1,+ .method = "Input.dispatchKeyEvent",+ .params = .{ .type = "keyDown", .key = "Tab", .code = "Tab" },+ });+ try testing.expect((try ls.local.compileAndRun("document.activeElement.id === 'b1'", null)).isTrue());++ // Second Tab → next in tabindex order (#i2).+ try ctx.processMessage(.{+ .id = 2,+ .method = "Input.dispatchKeyEvent",+ .params = .{ .type = "keyDown", .key = "Tab", .code = "Tab" },+ });+ try testing.expect((try ls.local.compileAndRun("document.activeElement.id === 'i2'", null)).isTrue());++ // Shift+Tab (modifiers bit 8) walks backward → back to #b1.+ try ctx.processMessage(.{+ .id = 3,+ .method = "Input.dispatchKeyEvent",+ .params = .{ .type = "keyDown", .key = "Tab", .code = "Tab", .modifiers = 8 },+ });+ try testing.expect((try ls.local.compileAndRun("document.activeElement.id === 'b1'", null)).isTrue());+}++test "cdp.input: dispatchKeyEvent beforeinput can veto the edit" {+ var ctx = try testing.context();+ defer ctx.deinit();++ const bc = try ctx.loadBrowserContext(.{});+ const page = try bc.session.createPage();+ const frame = page.frame().?;+ try frame.navigate("http://localhost:9582/src/browser/tests/mcp_actions.html", .{+ .reason = .address_bar,+ .kind = .{ .push = null },+ });+ try testing.waitForPage(bc);++ var ls: lp.js.Local.Scope = undefined;+ frame.js.localScope(&ls);+ defer ls.deinit();++ // A listener that rejects every keystroke, the way masked-input libraries+ // do. Records what it saw so we can assert the event was cancelable.+ _ = try ls.local.compileAndRun(+ \\const inp = document.getElementById('inp');+ \\inp.value = 'ab';+ \\inp.focus();+ \\window.seen = [];+ \\inp.addEventListener('beforeinput', (e) => {+ \\ window.seen.push(['beforeinput', e.cancelable].join(':'));+ \\ e.preventDefault();+ \\ window.seen.push(['defaultPrevented', e.defaultPrevented].join(':'));+ \\});+ \\inp.addEventListener('input', () => window.seen.push('input'));+ , null);++ try ctx.processMessage(.{+ .id = 1,+ .method = "Input.dispatchKeyEvent",+ .params = .{ .type = "keyDown", .key = "c", .text = "c" },+ });++ // The veto held: no character inserted and no `input` event followed.+ try testing.expect((try ls.local.compileAndRun(+ \\inp.value === 'ab' &&+ \\window.seen.join(',') === 'beforeinput:true,defaultPrevented:true'+ , null)).isTrue());++ // Backspace goes through the same pre-edit gate.+ try ctx.processMessage(.{+ .id = 2,+ .method = "Input.dispatchKeyEvent",+ .params = .{ .type = "keyDown", .key = "Backspace", .code = "Backspace" },+ });+ try testing.expect((try ls.local.compileAndRun("inp.value === 'ab'", null)).isTrue());++ // Without the veto, the edit goes through and `input` is dispatched — and+ // `input` itself is not cancelable.+ _ = try ls.local.compileAndRun(+ \\const clone = inp.cloneNode(true);+ \\inp.replaceWith(clone);+ \\clone.focus();+ \\window.seen = [];+ \\clone.addEventListener('input', (e) => window.seen.push(['input', e.cancelable].join(':')));+ , null);++ try ctx.processMessage(.{+ .id = 3,+ .method = "Input.dispatchKeyEvent",+ .params = .{ .type = "keyDown", .key = "c", .text = "c" },+ });+ try testing.expect((try ls.local.compileAndRun(+ \\clone.value === 'abc' && window.seen.join(',') === 'input:false'+ , null)).isTrue());+}++test "cdp.input: editing keys honor the selection of a default-valued textarea" {+ var ctx = try testing.context();+ defer ctx.deinit();++ const bc = try ctx.loadBrowserContext(.{});+ const page = try bc.session.createPage();+ const frame = page.frame().?;++ try frame.navigate("http://localhost:9582/src/browser/tests/mcp_actions.html", .{ .reason = .address_bar, .kind = .{ .push = null } });+ try testing.waitForPage(bc);++ var ls: lp.js.Local.Scope = undefined;+ frame.js.localScope(&ls);+ defer ls.deinit();++ // This <textarea>'s value comes from its child text node — nothing assigns+ // to `value` — so the selection has to clamp against the parsed text.+ _ = try ls.local.compileAndRun(+ \\document.body.innerHTML = '<textarea id="ta">abcdef</textarea>';+ \\const ta = document.getElementById('ta');+ \\ta.focus();+ \\ta.setSelectionRange(2, 4);+ , null);+ try testing.expect((try ls.local.compileAndRun("ta.selectionStart === 2 && ta.selectionEnd === 4", null)).isTrue());++ // Backspace over a range deletes the range, leaving the caret at its start.+ try ctx.processMessage(.{+ .id = 1,+ .method = "Input.dispatchKeyEvent",+ .params = .{ .type = "keyDown", .key = "Backspace", .code = "Backspace" },+ });+ try testing.expect((try ls.local.compileAndRun("ta.value === 'abef'", null)).isTrue());+ try testing.expect((try ls.local.compileAndRun("ta.selectionStart === 2 && ta.selectionEnd === 2", null)).isTrue());++ // Collapsed caret: Backspace removes the character on its left.+ _ = try ls.local.compileAndRun("ta.setSelectionRange(3, 3)", null);+ try ctx.processMessage(.{+ .id = 2,+ .method = "Input.dispatchKeyEvent",+ .params = .{ .type = "keyDown", .key = "Backspace", .code = "Backspace" },+ });+ try testing.expect((try ls.local.compileAndRun("ta.value === 'abf'", null)).isTrue());+}++test "cdp.input: dispatchKeyEvent caret movement keys move the text entry cursor" {+ var ctx = try testing.context();+ defer ctx.deinit();++ const bc = try ctx.loadBrowserContext(.{});+ const page = try bc.session.createPage();+ const frame = page.frame().?;++ const url = "http://localhost:9582/src/browser/tests/mcp_actions.html";+ try frame.navigate(url, .{ .reason = .address_bar, .kind = .{ .push = null } });+ try testing.waitForPage(bc);++ var ls: lp.js.Local.Scope = undefined;+ frame.js.localScope(&ls);+ defer ls.deinit();++ var try_catch: lp.js.TryCatch = undefined;+ try_catch.init(&ls.local);+ defer try_catch.deinit();++ _ = try ls.local.compileAndRun(+ \\document.body.innerHTML = '<input id="t" type="text"><textarea id="ta"></textarea>';+ \\const t = document.getElementById('t');+ \\const ta = document.getElementById('ta');+ \\const sel = (e) => [e.selectionStart, e.selectionEnd, e.selectionDirection].join(',');+ \\t.focus(); t.value = 'abcdef'; t.setSelectionRange(6, 6);+ , null);++ const Step = struct { key: []const u8, modifiers: u4 = 0, expect: []const u8 };+ const shift = 8;++ // <input>: plain moves collapse, Shift extends from the anchor, a plain+ // arrow on a selection collapses to its edge, ArrowUp/ArrowDown reach the+ // ends of a single-line value.+ const input_steps = [_]Step{+ .{ .key = "ArrowLeft", .expect = "5,5,none" },+ .{ .key = "ArrowRight", .expect = "6,6,none" },+ .{ .key = "Home", .expect = "0,0,none" },+ .{ .key = "End", .expect = "6,6,none" },+ .{ .key = "ArrowUp", .expect = "0,0,none" },+ .{ .key = "ArrowDown", .expect = "6,6,none" },+ .{ .key = "ArrowRight", .expect = "6,6,none" },+ .{ .key = "ArrowLeft", .modifiers = shift, .expect = "5,6,backward" },+ .{ .key = "Home", .modifiers = shift, .expect = "0,6,backward" },+ .{ .key = "ArrowLeft", .expect = "0,0,none" },+ .{ .key = "ArrowLeft", .expect = "0,0,none" },+ .{ .key = "End", .modifiers = shift, .expect = "0,6,forward" },+ .{ .key = "ArrowLeft", .modifiers = shift, .expect = "0,5,forward" },+ .{ .key = "ArrowRight", .expect = "5,5,none" },+ };+ var id: u32 = 1;+ for (input_steps) |step| {+ try ctx.processMessage(.{+ .id = id,+ .method = "Input.dispatchKeyEvent",+ .params = .{ .type = "keyDown", .key = step.key, .code = step.key, .modifiers = step.modifiers },+ });+ id += 1;+ const got = try (try ls.local.compileAndRun("sel(t)", null)).toStringSlice();+ try testing.expectEqualSlices(u8, step.expect, got);+ }++ // Type-then-correct: move back two characters and insert in the middle.+ _ = try ls.local.compileAndRun("t.setSelectionRange(6, 6)", null);+ for (0..2) |_| {+ try ctx.processMessage(.{+ .id = id,+ .method = "Input.dispatchKeyEvent",+ .params = .{ .type = "keyDown", .key = "ArrowLeft", .code = "ArrowLeft" },+ });+ id += 1;+ }+ try ctx.processMessage(.{ .id = id, .method = "Input.insertText", .params = .{ .text = "X" } });+ id += 1;+ try testing.expect((try ls.local.compileAndRun("t.value === 'abcdXef' && sel(t) === '5,5,none'", null)).isTrue());++ // Moves step over whole UTF-8 sequences, never landing inside one.+ _ = try ls.local.compileAndRun("t.value = 'aé'; t.setSelectionRange(t.value.length, t.value.length)", null);+ try ctx.processMessage(.{+ .id = id,+ .method = "Input.dispatchKeyEvent",+ .params = .{ .type = "keyDown", .key = "ArrowLeft", .code = "ArrowLeft" },+ });+ id += 1;+ try ctx.processMessage(.{ .id = id, .method = "Input.insertText", .params = .{ .text = "X" } });+ id += 1;+ try testing.expect((try ls.local.compileAndRun("t.value === 'aXé'", null)).isTrue());++ // <textarea>: Home/End stop at the enclosing line break, ArrowLeft crosses it.+ _ = try ls.local.compileAndRun("ta.focus(); ta.value = 'ab\\ncd'; ta.setSelectionRange(5, 5)", null);+ const textarea_steps = [_]Step{+ .{ .key = "Home", .expect = "3,3,none" },+ .{ .key = "End", .expect = "5,5,none" },+ .{ .key = "Home", .modifiers = shift, .expect = "3,5,backward" },+ .{ .key = "ArrowLeft", .expect = "3,3,none" },+ .{ .key = "ArrowLeft", .expect = "2,2,none" },+ };+ for (textarea_steps) |step| {+ try ctx.processMessage(.{+ .id = id,+ .method = "Input.dispatchKeyEvent",+ .params = .{ .type = "keyDown", .key = step.key, .code = step.key, .modifiers = step.modifiers },+ });+ id += 1;+ const got = try (try ls.local.compileAndRun("sel(ta)", null)).toStringSlice();+ try testing.expectEqualSlices(u8, step.expect, got);+ }+}++// chromedp's SendKeys shape: a text-less keyDown, the char with the text, keyUp.+test "cdp.input: dispatchKeyEvent text-less keyDown then char types once" {+ var ctx = try testing.context();+ defer ctx.deinit();++ const bc = try ctx.loadBrowserContext(.{ .url = "mcp_actions.html" });+ const frame = bc.mainFrame().?;++ var ls: lp.js.Local.Scope = undefined;+ frame.js.localScope(&ls);defer ls.deinit();_ = try ls.local.compileAndRun(@@ -1956,6 +2872,327 @@ test "cdp.input: dispatchKeyEvent Enter on a checkbox, radio or select" {}}+test "cdp.input: touch tap emits pointer and compatibility activation in order" {+ var ctx = try testing.context();+ defer ctx.deinit();+ const bc = try ctx.loadBrowserContext(.{});+ const page = try bc.session.createPage();+ const frame = page.frame().?;+ try frame.navigate("http://localhost:9582/src/browser/tests/mcp_actions.html", .{ .reason = .address_bar, .kind = .{ .push = null } });+ try testing.waitForPage(bc);+ var ls: lp.js.Local.Scope = undefined;+ frame.js.localScope(&ls);+ defer ls.deinit();+ _ = try ls.local.compileAndRun(+ \\window.tapEvents = [];+ \\const tapTarget = document.getElementById('btn');+ \\for (const type of ['pointerover', 'pointerenter', 'pointerdown', 'touchstart', 'pointerup', 'pointerout', 'pointerleave', 'touchend', 'mouseover', 'mouseenter', 'mousemove', 'mousedown', 'focus', 'mouseup', 'click']) {+ \\ tapTarget.addEventListener(type, e => tapEvents.push({type: e.type, pointerType: e.pointerType, id: e.pointerId, button: e.button, buttons: e.buttons, detail: e.detail, trusted: e.isTrusted, x: e.clientX, y: e.clientY, width: e.width, height: e.height, pressure: e.pressure, shift: e.shiftKey}));+ \\}+ , null);+ const x = try (try ls.local.compileAndRun("tapTarget.getBoundingClientRect().x + 1", null)).toF64();+ const y = try (try ls.local.compileAndRun("tapTarget.getBoundingClientRect().y + 1", null)).toF64();+ try ctx.processMessage(.{+ .id = 1,+ .method = "Input.dispatchTouchEvent",+ .params = .{ .type = "touchStart", .modifiers = 8, .touchPoints = &.{.{ .x = x, .y = y, .id = 7, .radiusX = 3, .radiusY = 4, .force = 0.7 }} },+ });+ try testing.expect((try ls.local.compileAndRun("!window.clicked && tapEvents.map(e => e.type).join(',') === 'pointerover,pointerenter,pointerdown,touchstart'", null)).isTrue());+ try ctx.processMessage(.{+ .id = 2,+ .method = "Input.dispatchTouchEvent",+ .params = .{ .type = "touchEnd", .modifiers = 8, .touchPoints = &.{} },+ });+ try testing.expect((try ls.local.compileAndRun(+ \\tapEvents.map(e => e.type).join(',') === 'pointerover,pointerenter,pointerdown,touchstart,pointerup,pointerout,pointerleave,touchend,mouseover,mouseenter,mousemove,mousedown,focus,mouseup,click' && window.clicked && document.activeElement === tapTarget &&+ \\tapEvents.every(e => e.trusted) &&+ \\tapEvents.filter(e => e.pointerType).every(e => e.pointerType === 'touch' && e.id === 2 && e.shift) &&+ \\tapEvents.find(e => e.type === 'pointerdown').width === 6 && tapEvents.find(e => e.type === 'pointerdown').height === 8 && tapEvents.find(e => e.type === 'pointerdown').pressure === 0.7 &&+ \\tapEvents.find(e => e.type === 'pointerup').buttons === 0 && tapEvents.find(e => e.type === 'pointerup').pressure === 0 &&+ \\tapEvents.find(e => e.type === 'mousedown').buttons === 1 && tapEvents.find(e => e.type === 'mousedown').detail === 1 &&+ \\tapEvents.find(e => e.type === 'mouseup').buttons === 0 && tapEvents.find(e => e.type === 'click').detail === 1+ , null)).isTrue());+ try testing.expect(frame.page.input_touch_contact == null);+ try testing.expectEqual(@as(u16, 0), frame.page.input_pointer.held);+}++test "cdp.input: touch tap cancellation distinguishes touch pointer and mouse defaults" {+ var ctx = try testing.context();+ defer ctx.deinit();+ const bc = try ctx.loadBrowserContext(.{});+ const page = try bc.session.createPage();+ const frame = page.frame().?;+ try frame.navigate("http://localhost:9582/src/browser/tests/mcp_actions.html", .{ .reason = .address_bar, .kind = .{ .push = null } });+ try testing.waitForPage(bc);+ var ls: lp.js.Local.Scope = undefined;+ frame.js.localScope(&ls);+ defer ls.deinit();+ _ = try ls.local.compileAndRun(+ \\const tapTarget = document.getElementById('chk');+ \\window.preventType = '';+ \\window.tapEvents = [];+ \\for (const type of ['pointerdown', 'pointerup', 'pointercancel', 'touchstart', 'touchmove', 'touchend', 'touchcancel', 'mousemove', 'mousedown', 'mouseup', 'click']) {+ \\ tapTarget.addEventListener(type, e => { tapEvents.push(e.type); if (e.type === preventType) e.preventDefault(); }, {passive: false});+ \\}+ , null);+ const x = try (try ls.local.compileAndRun("tapTarget.getBoundingClientRect().x + 1", null)).toF64();+ const y = try (try ls.local.compileAndRun("tapTarget.getBoundingClientRect().y + 1", null)).toF64();+ const cases = .{+ .{ "touchstart", "!tapTarget.checked && !tapEvents.includes('mousedown') && !tapEvents.includes('click')" },+ .{ "touchmove", "!tapTarget.checked && !tapEvents.includes('mousedown') && !tapEvents.includes('click')" },+ .{ "touchend", "!tapTarget.checked && !tapEvents.includes('mousedown') && !tapEvents.includes('click')" },+ .{ "pointerdown", "tapTarget.checked && tapEvents.includes('click') && !tapEvents.includes('mousedown') && !tapEvents.includes('mouseup') && !tapEvents.includes('mousemove') && document.activeElement.id === 'inp'" },+ .{ "pointerup", "tapTarget.checked && tapEvents.includes('mousedown') && tapEvents.includes('mouseup')" },+ .{ "mousedown", "tapTarget.checked && document.activeElement.id === 'inp'" },+ .{ "click", "!tapTarget.checked && tapEvents.includes('mousedown') && tapEvents.includes('mouseup')" },+ .{ "touchcancel", "!tapTarget.checked && tapEvents.includes('pointercancel') && !tapEvents.includes('pointerup') && !tapEvents.includes('mousedown') && !tapEvents.includes('click')" },+ .{ "", "tapTarget.checked && tapEvents.includes('mousedown') && tapEvents.includes('mouseup') && document.activeElement === tapTarget" },+ };+ inline for (cases) |case| {+ _ = try ls.local.compileAndRun("tapTarget.checked = false; tapEvents = []; document.getElementById('inp').focus(); preventType = '" ++ case[0] ++ "';", null);+ try ctx.processMessage(.{+ .id = 1,+ .method = "Input.dispatchTouchEvent",+ .params = .{ .type = "touchStart", .touchPoints = &.{.{ .x = x, .y = y }} },+ });+ if (comptime std.mem.eql(u8, case[0], "touchmove")) {+ try ctx.processMessage(.{+ .id = 2,+ .method = "Input.dispatchTouchEvent",+ .params = .{ .type = "touchMove", .touchPoints = &.{.{ .x = x + 1, .y = y }} },+ });+ }+ try ctx.processMessage(.{+ .id = 3,+ .method = "Input.dispatchTouchEvent",+ .params = .{ .type = if (comptime std.mem.eql(u8, case[0], "touchcancel")) "touchCancel" else "touchEnd", .touchPoints = &.{} },+ });+ const passed = (try ls.local.compileAndRun(case[1], null)).isTrue();+ if (!passed) std.debug.print("failed prevention case: {s}\n", .{case[0]});+ try testing.expect(passed);+ try testing.expect(frame.page.input_touch_contact == null);+ }+}++test "cdp.input: touch pointer retains its target while compatibility events hit test release" {+ var ctx = try testing.context();+ defer ctx.deinit();+ const bc = try ctx.loadBrowserContext(.{});+ const page = try bc.session.createPage();+ const frame = page.frame().?;+ try frame.navigate("http://localhost:9582/src/browser/tests/mcp_actions.html", .{ .reason = .address_bar, .kind = .{ .push = null } });+ try testing.waitForPage(bc);+ var ls: lp.js.Local.Scope = undefined;+ frame.js.localScope(&ls);+ defer ls.deinit();+ _ = try ls.local.compileAndRun(+ \\const startTarget = document.getElementById('btn');+ \\const releaseTarget = document.getElementById('inp');+ \\window.tapEvents = [];+ \\for (const type of ['pointerdown', 'pointermove', 'pointerup', 'touchstart', 'touchmove', 'touchend', 'mousedown', 'mouseup', 'click']) {+ \\ document.addEventListener(type, e => tapEvents.push(e.type + ':' + e.target.id), {passive: false});+ \\}+ , null);+ const x = try (try ls.local.compileAndRun("startTarget.getBoundingClientRect().x + 1", null)).toF64();+ const y = try (try ls.local.compileAndRun("startTarget.getBoundingClientRect().y + 1", null)).toF64();+ const release_x = try (try ls.local.compileAndRun("releaseTarget.getBoundingClientRect().x + 1", null)).toF64();+ const release_y = try (try ls.local.compileAndRun("releaseTarget.getBoundingClientRect().y + 1", null)).toF64();+ 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 = &.{.{ .x = release_x, .y = release_y }} },+ });+ try testing.expect((try ls.local.compileAndRun("tapEvents.join(',') === 'pointerdown:btn,touchstart:btn,pointerup:btn,touchend:btn,mousedown:inp,mouseup:inp,click:inp'", null)).isTrue());++ // A drag retains pointer/touch delivery but must not activate on release.+ _ = try ls.local.compileAndRun("tapEvents = [];", null);+ try ctx.processMessage(.{+ .id = 3,+ .method = "Input.dispatchTouchEvent",+ .params = .{ .type = "touchStart", .touchPoints = &.{.{ .x = x, .y = y }} },+ });+ try ctx.processMessage(.{+ .id = 4,+ .method = "Input.dispatchTouchEvent",+ .params = .{ .type = "touchMove", .touchPoints = &.{.{ .x = release_x, .y = release_y }} },+ });+ try ctx.processMessage(.{+ .id = 5,+ .method = "Input.dispatchTouchEvent",+ .params = .{ .type = "touchEnd", .touchPoints = &.{} },+ });+ try testing.expect((try ls.local.compileAndRun("tapEvents.join(',') === 'pointerdown:btn,touchstart:btn,pointermove:btn,touchmove:btn,pointerup:btn,touchend:btn'", null)).isTrue());+}++test "cdp.input: passive prevention and finger jitter do not suppress repeated taps" {+ var ctx = try testing.context();+ defer ctx.deinit();+ const bc = try ctx.loadBrowserContext(.{});+ const page = try bc.session.createPage();+ const frame = page.frame().?;+ try frame.navigate("http://localhost:9582/src/browser/tests/mcp_actions.html", .{ .reason = .address_bar, .kind = .{ .push = null } });+ try testing.waitForPage(bc);+ var ls: lp.js.Local.Scope = undefined;+ frame.js.localScope(&ls);+ defer ls.deinit();+ _ = try ls.local.compileAndRun(+ \\const tapTarget = document.getElementById('btn');+ \\window.clickIds = [];+ \\tapTarget.addEventListener('touchstart', e => e.preventDefault(), {passive: true});+ \\tapTarget.addEventListener('click', e => clickIds.push(e.pointerId));+ , null);+ const x = try (try ls.local.compileAndRun("tapTarget.getBoundingClientRect().x + 1", null)).toF64();+ const y = try (try ls.local.compileAndRun("tapTarget.getBoundingClientRect().y + 1", null)).toF64();+ for (0..2) |_| {+ try ctx.processMessage(.{+ .id = 1,+ .method = "Input.dispatchTouchEvent",+ .params = .{ .type = "touchStart", .touchPoints = &.{.{ .x = x, .y = y, .id = 2147483647 }} },+ });+ try ctx.processMessage(.{+ .id = 2,+ .method = "Input.dispatchTouchEvent",+ .params = .{ .type = "touchMove", .touchPoints = &.{.{ .x = x + 1, .y = y, .id = 2147483647 }} },+ });+ try ctx.processMessage(.{+ .id = 3,+ .method = "Input.dispatchTouchEvent",+ .params = .{ .type = "touchEnd", .touchPoints = &.{} },+ });+ }+ try testing.expect((try ls.local.compileAndRun("clickIds.join(',') === '2,3'", null)).isTrue());+}++test "cdp.input: touch tap respects disabled controls across compatibility handlers" {+ var ctx = try testing.context();+ defer ctx.deinit();+ const bc = try ctx.loadBrowserContext(.{});+ const page = try bc.session.createPage();+ const frame = page.frame().?;+ try frame.navigate("http://localhost:9582/src/browser/tests/mcp_actions.html", .{ .reason = .address_bar, .kind = .{ .push = null } });+ try testing.waitForPage(bc);+ var ls: lp.js.Local.Scope = undefined;+ 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" },+ };+ inline for (cases) |case| {+ _ = try ls.local.compileAndRun(+ \\document.body.innerHTML = '<fieldset id="fieldset"><input id="t" type="checkbox"></fieldset>';+ \\window.t = document.getElementById('t'); window.fieldset = document.getElementById('fieldset');+ \\window.clicks = 0; window.events = [];+ \\t.addEventListener('click', () => clicks++);+ \\for (const type of ['mousemove', 'mousedown', 'mouseup']) t.addEventListener(type, e => events.push(e.type));+ ++ 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;+ 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 = &.{} } });+ }+ const passed = (try ls.local.compileAndRun(case[1], null)).isTrue();+ if (!passed) std.debug.print("disabled tap case: {s}\n", .{case[0]});+ 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" {+ var ctx = try testing.context();+ defer ctx.deinit();+ const bc = try ctx.loadBrowserContext(.{});+ const page = try bc.session.createPage();+ const frame = page.frame().?;+ try frame.navigate("http://localhost:9582/src/browser/tests/mcp_actions.html", .{ .reason = .address_bar, .kind = .{ .push = null } });+ try testing.waitForPage(bc);+ var ls: lp.js.Local.Scope = undefined;+ frame.js.localScope(&ls);+ defer ls.deinit();+ const cases = .{+ .{ "t.addEventListener('mouseover', replace);", "clicks === 0 && replacementClicks === 1 && ups === 0" },+ .{ "t.addEventListener('mousemove', replace);", "clicks === 0 && replacementClicks === 1 && ups === 0" },+ .{ "t.addEventListener('mousedown', () => t.remove());", "clicks === 0 && replacementClicks === 0 && ups === 0" },+ .{ "t.addEventListener('mousedown', replace);", "clicks === 0 && replacementClicks === 0 && ups === 0" },+ .{ "t.addEventListener('focus', replace);", "clicks === 0 && replacementClicks === 0 && ups === 0" },+ .{ "old.focus(); old.addEventListener('blur', replace);", "clicks === 0 && replacementClicks === 0 && ups === 0" },+ .{ "t.addEventListener('mouseup', () => t.remove());", "clicks === 1 && replacementClicks === 0 && ups === 1" },+ .{ "t.addEventListener('mouseup', replace);", "clicks === 1 && replacementClicks === 0 && ups === 1" },+ .{ "t.addEventListener('mouseup', () => t.style.display = 'none');", "clicks === 1 && ups === 1" },+ .{ "t.addEventListener('mousedown', () => t.style.display = 'none');", "clicks === 0 && ups === 0" },+ .{ "t.addEventListener('mousedown', () => { const b = document.createElement('button'); b.textContent = 'New'; b.addEventListener('click', () => replacementClicks++); t.parentNode.append(b); t.style.display = 'none'; });", "clicks === 0 && replacementClicks === 0 && parentClicks === 1 && ups === 0" },+ };+ inline for (cases) |case| {+ _ = try ls.local.compileAndRun(+ \\document.body.innerHTML = '<input id="old"><div style="height:50px;width:200px"><button id="t">Send</button></div>';+ \\window.t = document.getElementById('t'); window.old = document.getElementById('old');+ \\window.clicks = 0; window.replacementClicks = 0; window.ups = 0; window.parentClicks = 0;+ \\t.addEventListener('click', () => clicks++); t.addEventListener('mouseup', () => ups++);+ \\t.parentNode.addEventListener('click', e => { if (e.target === e.currentTarget) parentClicks++; });+ \\window.replace = () => { const b = document.createElement('button'); b.textContent = 'New'; b.addEventListener('click', () => replacementClicks++); t.replaceWith(b); };+ ++ 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();+ 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 = &.{} } });+ const passed = (try ls.local.compileAndRun(case[1], null)).isTrue();+ if (!passed) std.debug.print("mutating tap case: {s}\n", .{case[0]});+ try testing.expect(passed);+ try testing.expect(frame.page.input_touch_contact == null);+ }+}++test "cdp.input: touch cancellation retains last contact geometry through pointer leave" {+ var ctx = try testing.context();+ defer ctx.deinit();+ const bc = try ctx.loadBrowserContext(.{});+ const page = try bc.session.createPage();+ const frame = page.frame().?;+ try frame.navigate("http://localhost:9582/src/browser/tests/mcp_actions.html", .{ .reason = .address_bar, .kind = .{ .push = null } });+ try testing.waitForPage(bc);+ var ls: lp.js.Local.Scope = undefined;+ frame.js.localScope(&ls);+ defer ls.deinit();+ _ = try ls.local.compileAndRun(+ \\window.t = document.getElementById('btn'); window.events = [];+ \\for (const type of ['pointercancel', 'pointerout', 'pointerleave', 'click']) {+ \\ t.addEventListener(type, e => events.push({type: e.type, button: e.button, buttons: e.buttons, width: e.width, height: e.height, pressure: e.pressure, cancelable: e.cancelable, id: e.pointerId}));+ \\}+ , 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();+ try ctx.processMessage(.{ .id = 1, .method = "Input.dispatchTouchEvent", .params = .{ .type = "touchStart", .touchPoints = &.{.{ .x = x, .y = y, .radiusX = 1, .radiusY = 2 }} } });+ try ctx.processMessage(.{ .id = 2, .method = "Input.dispatchTouchEvent", .params = .{ .type = "touchMove", .touchPoints = &.{.{ .x = x + 1, .y = y, .radiusX = 3, .radiusY = 4, .force = 0.7 }} } });+ try ctx.processMessage(.{ .id = 3, .method = "Input.dispatchTouchEvent", .params = .{ .type = "touchCancel", .touchPoints = &.{} } });+ try testing.expect((try ls.local.compileAndRun(+ \\events.map(e => e.type).join(',') === 'pointercancel,pointerout,pointerleave' &&+ \\events.every(e => e.button === -1 && e.buttons === 0 && e.width === 6 && e.height === 8 && e.pressure === 0 && e.id === 2) &&+ \\!events[0].cancelable && events[1].cancelable && !events[2].cancelable+ , null)).isTrue());+ try testing.expect(frame.page.input_touch_contact == null);+}+test "cdp.input: re-navigating an iframe drops the pointer state on its elements" {var ctx = try testing.context();defer ctx.deinit();@@ -1981,3 +3218,53 @@ test "cdp.input: re-navigating an iframe drops the pointer state on its elementstry testing.expect(page.input_pointer.down_target == null);try testing.expectEqual(0, page.input_pointer.held);}++test "cdp.input: mouse activation rechecks disabled state between events" {+ var ctx = try testing.context();+ defer ctx.deinit();+ const bc = try ctx.loadBrowserContext(.{});+ const page = try bc.session.createPage();+ const frame = page.frame().?;+ try frame.navigate("http://localhost:9582/src/browser/tests/mcp_actions.html", .{ .reason = .address_bar, .kind = .{ .push = null } });+ try testing.waitForPage(bc);+ var ls: lp.js.Local.Scope = undefined;+ 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" },+ };+ inline for (cases) |case| {+ _ = try ls.local.compileAndRun(+ \\document.body.innerHTML = '<fieldset id="fieldset"><input id="t" type="checkbox"></fieldset>';+ \\window.t = document.getElementById('t'); window.fieldset = document.getElementById('fieldset');+ \\window.clicks = 0; window.events = [];+ \\t.addEventListener('click', () => clicks++);+ \\for (const type of ['pointerdown', 'mousedown', 'pointerup', 'mouseup']) t.addEventListener(type, e => events.push(e.type));+ ++ 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;+ 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 } });+ }+ const passed = (try ls.local.compileAndRun(case[1], null)).isTrue();+ if (!passed) std.debug.print("disabled mouse case: {s}\n", .{case[0]});+ try testing.expect(passed);+ try testing.expectEqual(@as(u16, 0), frame.page.input_pointer.held);+ try testing.expect(frame.page.input_pointer.down_target == 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());+}