Lightpanda: the headless browser designed for AI and automation
webapi: matchMedia change events and real (add|remove)Listener
Adrià Arrufat6c59aa6df164
diff --git a/src/browser/Browser.zig b/src/browser/Browser.zigindex 79cad999b..fc62cfb58 100644--- a/src/browser/Browser.zig+++ b/src/browser/Browser.zig@@ -189,6 +189,12 @@ pub fn clearPermissions(self: *Browser) void {// The viewport every consumer should read: the runtime override if set,// otherwise the compile-time default.+pub fn setViewportOverride(self: *Browser, viewport: ?Viewport) void {+ self.viewport_override = viewport;+ const session = &(self.session orelse return);+ for (session.pages.items) |page| page.viewportChanged();+}+pub fn getViewport(self: *const Browser) Viewport {return self.viewport_override orelse Viewport.default;}diff --git a/src/browser/Page.zig b/src/browser/Page.zigindex 5044ce378..9952eeff4 100644--- a/src/browser/Page.zig+++ b/src/browser/Page.zig@@ -22,6 +22,7 @@ const lp = @import("lightpanda");const js = @import("js/js.zig");const Frame = @import("Frame.zig");+const MediaQueryList = @import("webapi/css/MediaQueryList.zig");const Session = @import("Session.zig");const Factory = @import("Factory.zig");const Viewport = @import("Viewport.zig");@@ -130,6 +131,9 @@ popups: std.ArrayList(*Frame) = .empty,// ideal from a memory point of view).closed_frames: std.ArrayList(*Frame) = .empty,+// Every matchMedia() result, so a viewport change can fire their `change`.+media_query_lists: std.ArrayList(*MediaQueryList) = .empty,+// SharedWorkerGlobalScopes created by this Page's frames (also registered in// session.shared_workers so other pages can connect).shared_workers: std.ArrayList(*SharedWorkerGlobalScope) = .empty,@@ -159,6 +163,10 @@ pub fn getViewport(self: *const Page) Viewport {return self.session.browser.getViewport();}+pub fn viewportChanged(self: *Page) void {+ for (self.media_query_lists.items) |mql| mql.viewportChanged();+}+// Initialize a Page and its root Frame.pub fn init(self: *Page, session: *Session, frame_id: u32) !void {const frame_arena = try session.arena_pool.acquire(.large, "Page.frame_arena");diff --git a/src/browser/js/bridge.zig b/src/browser/js/bridge.zigindex f79297a77..7dc1d5fd6 100644--- a/src/browser/js/bridge.zig+++ b/src/browser/js/bridge.zig@@ -1139,6 +1139,7 @@ pub const PageJsApis = flattenTypes(&.{@import("../webapi/event/PageTransitionEvent.zig"),@import("../webapi/event/PopStateEvent.zig"),@import("../webapi/event/HashChangeEvent.zig"),+ @import("../webapi/event/MediaQueryListEvent.zig"),@import("../webapi/event/BeforeUnloadEvent.zig"),@import("../webapi/event/StorageEvent.zig"),@import("../webapi/event/DeviceMotionEvent.zig"),diff --git a/src/browser/tests/css/media_query_list.html b/src/browser/tests/css/media_query_list.htmlindex a0b4b9c08..07ff6e972 100644--- a/src/browser/tests/css/media_query_list.html+++ b/src/browser/tests/css/media_query_list.html@@ -160,3 +160,31 @@testing.expectEqual('function', typeof mql.dispatchEvent);}</script>++<script id=listeners>+{+ const mql = window.matchMedia('(min-width: 600px)');+ let calls = 0;+ const fn = () => calls++;++ mql.addListener(fn);+ mql.dispatchEvent(new Event('change'));+ testing.expectEqual(1, calls);++ mql.removeListener(fn);+ mql.dispatchEvent(new Event('change'));+ testing.expectEqual(1, calls);++ mql.onchange = fn;+ testing.expectEqual(fn, mql.onchange);+ mql.dispatchEvent(new Event('change'));+ testing.expectEqual(2, calls);+ mql.onchange = null;+ mql.dispatchEvent(new Event('change'));+ testing.expectEqual(2, calls);++ const ev = new MediaQueryListEvent('change', { matches: true, media: '(min-width: 600px)' });+ testing.expectEqual(true, ev.matches);+ testing.expectEqual('(min-width: 600px)', ev.media);+}+</script>diff --git a/src/browser/webapi/Event.zig b/src/browser/webapi/Event.zigindex 3641a8fae..a9f96bed6 100644--- a/src/browser/webapi/Event.zig+++ b/src/browser/webapi/Event.zig@@ -85,6 +85,7 @@ pub const Type = union(enum) {page_transition_event: *@import("event/PageTransitionEvent.zig"),pop_state_event: *@import("event/PopStateEvent.zig"),hash_change_event: *@import("event/HashChangeEvent.zig"),+ media_query_list_event: *@import("event/MediaQueryListEvent.zig"),before_unload_event: *@import("event/BeforeUnloadEvent.zig"),storage_event: *@import("event/StorageEvent.zig"),device_motion_event: *@import("event/DeviceMotionEvent.zig"),@@ -200,6 +201,7 @@ pub fn is(self: *Event, comptime T: type) ?*T {.page_transition_event => |e| return if (T == @import("event/PageTransitionEvent.zig")) e else null,.pop_state_event => |e| return if (T == @import("event/PopStateEvent.zig")) e else null,.hash_change_event => |e| return if (T == @import("event/HashChangeEvent.zig")) e else null,+ .media_query_list_event => |e| return if (T == @import("event/MediaQueryListEvent.zig")) e else null,.before_unload_event => |e| return if (T == @import("event/BeforeUnloadEvent.zig")) e else null,.storage_event => |e| return if (T == @import("event/StorageEvent.zig")) e else null,.device_motion_event => |e| return if (T == @import("event/DeviceMotionEvent.zig")) e else null,diff --git a/src/browser/webapi/Window.zig b/src/browser/webapi/Window.zigindex dadb7baf7..63ed85407 100644--- a/src/browser/webapi/Window.zig+++ b/src/browser/webapi/Window.zig@@ -654,11 +654,8 @@ pub fn reportError(self: *Window, err: js.Value, frame: *Frame) !void {}}-pub fn matchMedia(_: *const Window, query: []const u8, frame: *Frame) !*MediaQueryList {- return frame._factory.eventTarget(MediaQueryList{- ._proto = undefined,- ._media = try frame.dupeString(query),- });+pub fn matchMedia(_: *const Window, query: []const u8, exec: *const js.Execution) !*MediaQueryList {+ return MediaQueryList.init(query, exec);}pub fn getComputedStyle(_: *const Window, element: *Element, pseudo_element: ?[]const u8, frame: *Frame) !*CSSStyleProperties {diff --git a/src/browser/webapi/css/MediaQueryList.zig b/src/browser/webapi/css/MediaQueryList.zigindex 4d0c2097e..392c81ce6 100644--- a/src/browser/webapi/css/MediaQueryList.zig+++ b/src/browser/webapi/css/MediaQueryList.zig@@ -16,11 +16,15 @@// 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/>.-// zlint-disable unused-decls+const lp = @import("lightpanda");+const js = @import("../../js/js.zig");const Frame = @import("../../Frame.zig");const EventTarget = @import("../EventTarget.zig");const MediaQuery = @import("../../css/MediaQuery.zig");+const MediaQueryListEvent = @import("../event/MediaQueryListEvent.zig");++const log = lp.log;const MediaQueryList = @This();@@ -28,9 +32,31 @@ pub const Proto = EventTarget;_proto: *EventTarget,_media: []const u8,+_frame: *Frame,+_exec: *const js.Execution,+// What listeners last observed; `change` fires when the viewport flips it.+_matches: bool,+_on_change: ?js.Function.Global = null,++pub fn init(query: []const u8, exec: *const js.Execution) !*MediaQueryList {+ const frame = switch (exec.js.global) {+ .frame => |f| f,+ .worker => unreachable,+ };+ const media = try frame.dupeString(query);+ const self = try exec._factory.eventTarget(MediaQueryList{+ ._proto = undefined,+ ._media = media,+ ._frame = frame,+ ._exec = exec,+ ._matches = MediaQuery.matches(media, frame._page.getViewport()),+ });+ try frame._page.media_query_lists.append(frame._page.frame_arena, self);+ return self;+}pub fn deinit(self: *MediaQueryList) void {- _ = self;+ if (self._on_change) |f| f.release();}pub fn asEventTarget(self: *MediaQueryList) *EventTarget {@@ -45,16 +71,55 @@ pub fn getMedia(self: *const MediaQueryList) []const u8 {/// so the result stays in sync with viewport emulation. The viewport comes/// from the page (overridable via Emulation.setDeviceMetricsOverride),/// matching `Window.innerWidth` / `innerHeight`.-pub fn getMatches(self: *const MediaQueryList, frame: *Frame) bool {- return MediaQuery.matches(self._media, frame._page.getViewport());+pub fn getMatches(self: *const MediaQueryList) bool {+ return MediaQuery.matches(self._media, self._frame._page.getViewport());+}++pub fn viewportChanged(self: *MediaQueryList) void {+ const matches = self.getMatches();+ if (matches == self._matches) return;+ self._matches = matches;++ const target = self.asEventTarget();+ if (!self._exec.hasDirectListeners(target, "change", @as(?js.Function.Global, null))) return;+ self.dispatchChange(matches) catch |err| {+ log.warn(.browser, "matchMedia change", .{ .err = err, .media = self._media });+ };}-// TODO: `change` events need to fire on every listener registered here (and-// via `addEventListener("change", ...)` through the EventTarget proto) when a-// viewport override crosses the breakpoint that flips `matches`. Today these-// registrations are no-ops rather than stored hooks.-pub fn addListener(_: *const MediaQueryList, _: js.Function) void {}-pub fn removeListener(_: *const MediaQueryList, _: js.Function) void {}+fn dispatchChange(self: *MediaQueryList, matches: bool) !void {+ const event = try MediaQueryListEvent.initTrusted(comptime .wrap("change"), .{+ .matches = matches,+ .media = self._media,+ }, self._frame);+ try self._exec.dispatch(self.asEventTarget(), event.asEvent(), @as(?js.Function.Global, null), .{ .context = "MediaQueryList change" });+}++pub fn addListener(self: *MediaQueryList, cb_: ?js.Function, exec: *js.Execution) !void {+ const cb = cb_ orelse return;+ try self._proto.addEventListener("change", .{ .value = .{ .function = cb } }, null, exec);+}++pub fn removeListener(self: *MediaQueryList, cb_: ?js.Function, exec: *js.Execution) !void {+ const cb = cb_ orelse return;+ try self._proto.removeEventListener("change", .{ .value = .{ .function = cb } }, null, exec);+}++pub fn getOnChange(self: *const MediaQueryList) ?js.Function.Global {+ return self._on_change;+}++// Registered as a listener so JS-side dispatchEvent reaches it too.+pub fn setOnChange(self: *MediaQueryList, cb_: ?js.Function, exec: *js.Execution) !void {+ if (self._on_change) |old| {+ try self._proto.removeEventListener("change", .{ .value = .{ .function = old.local(exec.js.local.?) } }, null, exec);+ old.release();+ self._on_change = null;+ }+ const cb = cb_ orelse return;+ try self._proto.addEventListener("change", .{ .value = .{ .function = cb } }, null, exec);+ self._on_change = try cb.persist();+}pub const JsApi = struct {pub const bridge = js.Bridge(MediaQueryList);@@ -67,8 +132,9 @@ pub const JsApi = struct {pub const media = bridge.accessor(MediaQueryList.getMedia, null, .{});pub const matches = bridge.accessor(MediaQueryList.getMatches, null, .{});- pub const addListener = bridge.function(MediaQueryList.addListener, .{ .noop = true });- pub const removeListener = bridge.function(MediaQueryList.removeListener, .{ .noop = true });+ pub const addListener = bridge.function(MediaQueryList.addListener, .{});+ pub const removeListener = bridge.function(MediaQueryList.removeListener, .{});+ pub const onchange = bridge.accessor(MediaQueryList.getOnChange, MediaQueryList.setOnChange, .{});};const testing = @import("../../../testing.zig");diff --git a/src/browser/webapi/event/MediaQueryListEvent.zig b/src/browser/webapi/event/MediaQueryListEvent.zignew file mode 100644index 000000000..3ddd638b9--- /dev/null+++ b/src/browser/webapi/event/MediaQueryListEvent.zig@@ -0,0 +1,97 @@+// 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 lp = @import("lightpanda");++const js = @import("../../js/js.zig");+const Frame = @import("../../Frame.zig");++const Event = @import("../Event.zig");++const String = lp.String;++const MediaQueryListEvent = @This();++pub const Proto = Event;++_proto: *Event,+_matches: bool,+_media: []const u8,++const MediaQueryListEventOptions = struct {+ matches: bool = false,+ media: []const u8 = "",+};++const Options = Event.inheritOptions(MediaQueryListEvent, MediaQueryListEventOptions);++pub fn init(typ: []const u8, _opts: ?Options, frame: *Frame) !*MediaQueryListEvent {+ const arena = try frame.getArena(.tiny, "MediaQueryListEvent");+ errdefer arena.release();+ const type_string = try String.init(arena.allocator(), typ, .{});+ return initWithTrusted(arena, type_string, _opts, false, frame);+}++pub fn initTrusted(typ: String, _opts: ?Options, frame: *Frame) !*MediaQueryListEvent {+ const arena = try frame.getArena(.tiny, "MediaQueryListEvent.trusted");+ errdefer arena.release();+ return initWithTrusted(arena, typ, _opts, true, frame);+}++fn initWithTrusted(arena: *lp.Arena, typ: String, _opts: ?Options, trusted: bool, frame: *Frame) !*MediaQueryListEvent {+ const opts = _opts orelse Options{};++ const event = try frame._factory.event(+ arena,+ typ,+ MediaQueryListEvent{+ ._proto = undefined,+ ._matches = opts.matches,+ ._media = try arena.dupe(u8, opts.media),+ },+ );++ Event.populatePrototypes(event, opts, trusted);+ return event;+}++pub fn asEvent(self: *MediaQueryListEvent) *Event {+ return self._proto;+}++pub fn getMatches(self: *const MediaQueryListEvent) bool {+ return self._matches;+}++pub fn getMedia(self: *const MediaQueryListEvent) []const u8 {+ return self._media;+}++pub const JsApi = struct {+ pub const bridge = js.Bridge(MediaQueryListEvent);++ pub const Meta = struct {+ pub const name = "MediaQueryListEvent";+ pub const prototype_chain = bridge.prototypeChain();+ pub var class_id: bridge.ClassId = undefined;+ };++ pub const constructor = bridge.constructor(MediaQueryListEvent.init, .{});+ pub const matches = bridge.accessor(MediaQueryListEvent.getMatches, null, .{});+ pub const media = bridge.accessor(MediaQueryListEvent.getMedia, null, .{});+};diff --git a/src/server/cdp/domains/emulation.zig b/src/server/cdp/domains/emulation.zigindex 93ae674fc..57f04bac7 100644--- a/src/server/cdp/domains/emulation.zig+++ b/src/server/cdp/domains/emulation.zig@@ -130,17 +130,17 @@ fn setDeviceMetricsOverride(cmd: *CDP.Command) !void {const current = browser.getViewport();// Same convention for deviceScaleFactor: 0 means "don't override".const dsf: f32 = if (params.deviceScaleFactor) |v| @floatCast(v) else 0;- browser.viewport_override = .{+ browser.setViewportOverride(.{.width = if (params.width > 0) params.width else current.width,.height = if (params.height > 0) params.height else current.height,.scale = if (dsf > 0) dsf else current.scale,- };+ });return cmd.sendResult(null, .{});}fn clearDeviceMetricsOverride(cmd: *CDP.Command) !void {- cmd.cdp.browser.viewport_override = null;+ cmd.cdp.browser.setViewportOverride(null);return cmd.sendResult(null, .{});}@@ -266,6 +266,37 @@ test "cdp.Emulation: locale, timezone and script execution stubs" {try ctx.expectSentResult(null, .{ .id = 5 });}+test "cdp.Emulation: viewport override fires matchMedia change events" {+ var ctx = try testing.context();+ defer ctx.deinit();+ var bc = try ctx.loadBrowserContext(.{ .id = "BID-MQL", .url = "hi.html", .target_id = "FID-0000000MQL".* });+ const frame = bc.mainFrame() orelse unreachable;++ {+ var ls: js.Local.Scope = undefined;+ frame.js.localScope(&ls);+ defer ls.deinit();+ _ = try ls.local.exec(+ \\window.mql = matchMedia('(max-width: 500px)');+ \\window.events = [];+ \\mql.addListener(e => events.push('listener:' + e.matches));+ \\mql.onchange = e => events.push('onchange:' + e.media);+ , null);+ }++ try ctx.processMessage(.{ .id = 1, .method = "Emulation.setDeviceMetricsOverride", .params = .{ .width = 400, .height = 800, .deviceScaleFactor = 1, .mobile = false } });+ try ctx.expectSentResult(null, .{ .id = 1 });+ // Same side of the breakpoint: nothing to report.+ try ctx.processMessage(.{ .id = 2, .method = "Emulation.setDeviceMetricsOverride", .params = .{ .width = 300, .height = 800, .deviceScaleFactor = 1, .mobile = false } });+ try ctx.processMessage(.{ .id = 3, .method = "Emulation.clearDeviceMetricsOverride" });++ var ls: js.Local.Scope = undefined;+ frame.js.localScope(&ls);+ defer ls.deinit();+ const v = try ls.local.exec("events.join() === 'listener:true,onchange:(max-width: 500px),listener:false,onchange:(max-width: 500px)'", null);+ try testing.expect(v.toBool());+}+test "cdp.Emulation: setUserAgentOverride with valid user agent" {var ctx = try testing.context();defer ctx.deinit();