Skip to content

armgit / moli

Public Imported from GitHub
0

Best headless browser for AI agents. Lite, Fast, High-Compatibility. Built in Rust

fix(events): implement MediaQueryListEvent construction and attributes

ldm0f4d0893a34a8
diff --git a/moli-renderer-v8/src/context_bootstrap/assets/constructor_templates.rs b/moli-renderer-v8/src/context_bootstrap/assets/constructor_templates.rs
index e36f7a2ff..b8db5765b 100644
--- a/moli-renderer-v8/src/context_bootstrap/assets/constructor_templates.rs
+++ b/moli-renderer-v8/src/context_bootstrap/assets/constructor_templates.rs
@@ -187,6 +187,9 @@ pub(in crate::context_bootstrap) fn build_constructor_template<'s>(
ConstructorKind::PopStateEvent => {
build_event_subclass_template(scope, EventSubclassKind::PopStateEvent)
}
+ ConstructorKind::MediaQueryListEvent => {
+ super::super::media_queries::build_media_query_list_event_template(scope)
+ }
ConstructorKind::PageTransitionEvent => {
build_event_subclass_template(scope, EventSubclassKind::PageTransitionEvent)
}
diff --git a/moli-renderer-v8/src/context_bootstrap/media_queries.rs b/moli-renderer-v8/src/context_bootstrap/media_queries.rs
index 68e07773c..addeaa1f5 100644
--- a/moli-renderer-v8/src/context_bootstrap/media_queries.rs
+++ b/moli-renderer-v8/src/context_bootstrap/media_queries.rs
@@ -1,4 +1,6 @@
mod evaluation;
+mod event;
+pub(in crate::context_bootstrap) use event::build_media_query_list_event_template;
mod events;
pub(crate) use self::evaluation::dispatch_media_query_list_change_events;
diff --git a/moli-renderer-v8/src/context_bootstrap/media_queries/evaluation.rs b/moli-renderer-v8/src/context_bootstrap/media_queries/evaluation.rs
index e04c8e503..106f04353 100644
--- a/moli-renderer-v8/src/context_bootstrap/media_queries/evaluation.rs
+++ b/moli-renderer-v8/src/context_bootstrap/media_queries/evaluation.rs
@@ -1,7 +1,7 @@
use super::dispatch_media_query_list_event;
+use super::event::create_media_query_list_event;
use crate::context_bootstrap::DEFAULT_WINDOW_SURFACE_PROFILE;
use crate::context_bootstrap::current_window_style_viewport;
-use crate::context_bootstrap::events::initialize_event_object;
use crate::context_bootstrap::{
MEDIA_QUERY_LIST_MATCHES_SLOT, MEDIA_QUERY_LIST_MEDIA_SLOT, MEDIA_QUERY_LIST_ONCHANGE_SLOT,
MEDIA_QUERY_LIST_REGISTRY_SLOT,
@@ -56,19 +56,6 @@ struct MediaQueryListPrototypeAccessorsDeclaration {
onchange: (),
}
-#[derive(WebApiObject)]
-#[webapi(interface = web_api_interfaces::Event)]
-struct MediaQueryListChangeEventObjectDeclaration {}
-
-#[derive(WebApiObject)]
-#[webapi(interface = web_api_interfaces::Event)]
-struct MediaQueryListChangeEventPropertiesDeclaration {
- #[webapi(data_property)]
- media: String,
- #[webapi(data_property)]
- matches: bool,
-}
-
#[derive(webidl::WebIdlArgs)]
#[webidl(prefix = "Window.matchMedia")]
struct MatchMediaArgs {
@@ -234,29 +221,13 @@ pub(crate) fn dispatch_media_query_list_change_events<'s>(
if previous_matches == current_matches {
continue;
}
- let event = media_query_list_change_event(scope, &media, current_matches);
+ let event = create_media_query_list_event(scope, &media, current_matches);
let _ = dispatch_media_query_list_event(scope, mql, event);
dispatched = true;
}
dispatched
}
-fn media_query_list_change_event<'s>(
- scope: &mut v8::PinScope<'s, '_>,
- media: &str,
- matches: bool,
-) -> v8::Local<'s, v8::Object> {
- let event = MediaQueryListChangeEventObjectDeclaration::new()
- .bind(scope)
- .expect("MediaQueryList change Event declaration should bind");
- initialize_event_object(scope, event, "change", false, false);
- crate::context_bootstrap::events::mark_event_trusted(scope, event);
- MediaQueryListChangeEventPropertiesDeclaration::new(media.to_owned(), matches)
- .initialize(scope, event)
- .expect("MediaQueryList change Event properties should initialize object");
- event
-}
-
fn media_query_list_slot_value<'s>(
scope: &mut v8::PinScope<'s, '_>,
list: v8::Local<'s, v8::Object>,
diff --git a/moli-renderer-v8/src/context_bootstrap/media_queries/event.rs b/moli-renderer-v8/src/context_bootstrap/media_queries/event.rs
new file mode 100644
index 000000000..6307de47f
--- /dev/null
+++ b/moli-renderer-v8/src/context_bootstrap/media_queries/event.rs
@@ -0,0 +1,161 @@
+use crate::{
+ context_bootstrap::events::{initialize_event_object, mark_event_trusted},
+ util::{get_private_value, throw_type_error, v8str},
+ web_api_interfaces, webidl,
+};
+use moli_webapi_declare::{WebApiFunctionTemplate, WebApiObject};
+
+const MEDIA_SLOT: &str = "__moliMediaQueryListEventMedia";
+const MATCHES_SLOT: &str = "__moliMediaQueryListEventMatches";
+
+#[derive(WebApiObject)]
+#[webapi(interface = web_api_interfaces::MediaQueryListEvent)]
+struct MediaQueryListEventState<'scope> {
+ #[webapi(slot = MEDIA_SLOT)]
+ media: v8::Local<'scope, v8::String>,
+ #[webapi(slot = MATCHES_SLOT)]
+ matches: bool,
+}
+
+#[derive(WebApiFunctionTemplate)]
+#[webapi(interface = web_api_interfaces::MediaQueryListEvent, enumerable, receiver)]
+struct MediaQueryListEventPrototype {
+ #[webapi(accessor_property, getter = media_getter)]
+ media: (),
+ #[webapi(accessor_property, getter = matches_getter)]
+ matches: (),
+}
+
+// Inherited EventInit members precede this dictionary's own members, each
+// group in lexicographic order. Convert the complete dictionary only once.
+#[derive(webidl::WebIdlDictionary)]
+#[webidl(prefix = "MediaQueryListEventInit")]
+struct MediaQueryListEventInit<'s> {
+ #[webidl(default = false)]
+ bubbles: bool,
+ #[webidl(default = false)]
+ cancelable: bool,
+ #[webidl(default = false)]
+ composed: bool,
+ #[webidl(default = false)]
+ matches: bool,
+ #[webidl(with = media_member)]
+ media: v8::Local<'s, v8::String>,
+}
+
+fn media_member<'s>(
+ scope: &mut v8::PinScope<'s, '_>,
+ object: v8::Local<'s, v8::Object>,
+ name: &'static str,
+) -> Result<v8::Local<'s, v8::String>, webidl::WebIdlError> {
+ let context = webidl::Context::member("MediaQueryListEventInit", name);
+ let Some(value) = webidl::property_result(scope, object, name, context)?
+ .filter(|value| !value.is_undefined())
+ else {
+ return Ok(v8str(scope, ""));
+ };
+ // Keep the DOMString as UTF-16, including unpaired surrogates.
+ value
+ .to_string(scope)
+ .ok_or_else(|| webidl::WebIdlError::pending_exception(context))
+}
+
+fn constructor<'s>(
+ scope: &mut v8::PinScope<'s, '_>,
+ args: v8::FunctionCallbackArguments<'s>,
+ mut rv: v8::ReturnValue<'s, v8::Value>,
+) {
+ if !args.is_construct_call() {
+ throw_type_error(scope, "MediaQueryListEvent requires 'new'.");
+ return;
+ }
+ if args.length() == 0 {
+ throw_type_error(scope, "MediaQueryListEvent requires an event type.");
+ return;
+ }
+ let Some(event_type) = args.get(0).to_string(scope) else {
+ return;
+ };
+ let parsed = webidl::dictionary_arg(
+ &args,
+ 1,
+ webidl::Context::argument("MediaQueryListEvent", 2),
+ )
+ .and_then(|object| match object {
+ Some(object) => webidl::parse_dictionary_object::<MediaQueryListEventInit>(scope, object),
+ None => Ok(MediaQueryListEventInit {
+ bubbles: false,
+ cancelable: false,
+ composed: false,
+ matches: false,
+ media: v8str(scope, ""),
+ }),
+ });
+ let init = match parsed {
+ Ok(init) => init,
+ Err(error) => {
+ webidl::throw_error(scope, &error);
+ return;
+ }
+ };
+ let event = args.this();
+ initialize_event_object(scope, event, "", init.bubbles, init.cancelable);
+ let _ = event.set(scope, v8str(scope, "type").into(), event_type.into());
+ let _ = event.set(
+ scope,
+ v8str(scope, "composed").into(),
+ v8::Boolean::new(scope, init.composed).into(),
+ );
+ MediaQueryListEventState::new(init.media, init.matches)
+ .initialize(scope, event)
+ .expect("MediaQueryListEvent state should initialize");
+ rv.set(event.into());
+}
+
+pub(in crate::context_bootstrap) fn build_media_query_list_event_template<'s>(
+ scope: &mut v8::PinScope<'s, '_, ()>,
+) -> v8::Local<'s, v8::FunctionTemplate> {
+ let template = v8::FunctionTemplate::builder(moli_webapi_declare::web_api_constructor!(
+ web_api_interfaces::MediaQueryListEvent,
+ constructor
+ ))
+ .length(1)
+ .build(scope);
+ let prototype = template.prototype_template(scope);
+ MediaQueryListEventPrototype::initialize_prototype_template(scope, prototype);
+ template
+}
+
+pub(super) fn create_media_query_list_event<'s>(
+ scope: &mut v8::PinScope<'s, '_>,
+ media: &str,
+ matches: bool,
+) -> v8::Local<'s, v8::Object> {
+ let media = v8::String::new(scope, media).expect("media query string");
+ let event = MediaQueryListEventState::new(media, matches)
+ .bind(scope)
+ .expect("MediaQueryListEvent should bind");
+ initialize_event_object(scope, event, "change", false, false);
+ mark_event_trusted(scope, event);
+ event
+}
+
+fn media_getter<'s>(
+ scope: &mut v8::PinScope<'s, '_>,
+ args: v8::FunctionCallbackArguments<'s>,
+ mut rv: v8::ReturnValue<'_, v8::Value>,
+) {
+ if let Some(value) = get_private_value(scope, args.this(), MEDIA_SLOT) {
+ rv.set(value);
+ }
+}
+
+fn matches_getter<'s>(
+ scope: &mut v8::PinScope<'s, '_>,
+ args: v8::FunctionCallbackArguments<'s>,
+ mut rv: v8::ReturnValue<'_, v8::Value>,
+) {
+ if let Some(value) = get_private_value(scope, args.this(), MATCHES_SLOT) {
+ rv.set(value);
+ }
+}
diff --git a/moli-renderer-v8/src/context_bootstrap/specs/registry.rs b/moli-renderer-v8/src/context_bootstrap/specs/registry.rs
index 9be7d50c7..19634ac72 100644
--- a/moli-renderer-v8/src/context_bootstrap/specs/registry.rs
+++ b/moli-renderer-v8/src/context_bootstrap/specs/registry.rs
@@ -294,7 +294,7 @@ const CONSTRUCTOR_SPECS_BEFORE_STREAMS: &[ConstructorSpec] = &[
},
ConstructorSpec {
interface: web_api_interfaces::MediaQueryListEvent::DESCRIPTOR,
- kind: ConstructorKind::Illegal,
+ kind: ConstructorKind::MediaQueryListEvent,
},
ConstructorSpec {
interface: web_api_interfaces::SecurityPolicyViolationEvent::DESCRIPTOR,
diff --git a/moli-renderer-v8/src/context_bootstrap/specs/types.rs b/moli-renderer-v8/src/context_bootstrap/specs/types.rs
index fb9e175ac..faa534fbd 100644
--- a/moli-renderer-v8/src/context_bootstrap/specs/types.rs
+++ b/moli-renderer-v8/src/context_bootstrap/specs/types.rs
@@ -120,6 +120,7 @@ pub(in crate::context_bootstrap) enum ConstructorKind {
Animation,
KeyframeEffect,
MediaQueryList,
+ MediaQueryListEvent,
MediaSource,
MediaError,
TextTrack,
diff --git a/moli-renderer-v8/src/script_vm/tests/browser_api/media.rs b/moli-renderer-v8/src/script_vm/tests/browser_api/media.rs
index 85bc93f91..11ab83f9c 100644
--- a/moli-renderer-v8/src/script_vm/tests/browser_api/media.rs
+++ b/moli-renderer-v8/src/script_vm/tests/browser_api/media.rs
@@ -3064,6 +3064,7 @@ async fn match_media_change_event_uses_event_prototype_and_declared_properties()
targetIsMql: event.target === mql,
currentTargetIsMql: event.currentTarget === mql,
bubbles: event.bubbles,
+ isTrusted: event.isTrusted,
cancelable: event.cancelable
});
});
@@ -3091,7 +3092,7 @@ async fn match_media_change_event_uses_event_prototype_and_declared_properties()
assert_eq!(
result,
- r#"[{"tag":"[object Event]","ctor":"Event","protoCtor":"Event","keys":"type,target,srcElement,currentTarget,defaultPrevented,bubbles,cancelable,isTrusted,composed,eventPhase","type":"change","media":"(prefers-color-scheme: dark)","matches":true,"mediaEnumerable":false,"matchesEnumerable":false,"targetIsMql":true,"currentTargetIsMql":true,"bubbles":false,"cancelable":false}]"#
+ r#"[{"tag":"[object MediaQueryListEvent]","ctor":"MediaQueryListEvent","protoCtor":"MediaQueryListEvent","keys":"type,target,srcElement,currentTarget,defaultPrevented,bubbles,cancelable,isTrusted,composed,eventPhase","type":"change","media":"(prefers-color-scheme: dark)","matches":true,"mediaEnumerable":false,"matchesEnumerable":false,"targetIsMql":true,"currentTargetIsMql":true,"bubbles":false,"isTrusted":true,"cancelable":false}]"#
);
}
diff --git a/moli-renderer-v8/src/script_vm/tests/browser_api/media_query_list_events.js b/moli-renderer-v8/src/script_vm/tests/browser_api/media_query_list_events.js
new file mode 100644
index 000000000..62a99dcb1
--- /dev/null
+++ b/moli-renderer-v8/src/script_vm/tests/browser_api/media_query_list_events.js
@@ -0,0 +1,67 @@
+function mediaQueryListEventConstructorProbe() {
+ const failures = [];
+ let checks = 0;
+ const check = (value, message) => { ++checks; if (!value) failures.push(message); };
+ const throws = (operation, expected, message) => {
+ try { operation(); check(false, message); }
+ catch (error) { check(error === expected || (typeof expected === "function" && error instanceof expected), message); }
+ };
+ for (const init of [undefined, null, {}]) {
+ const event = new MediaQueryListEvent("custom", init);
+ check(event instanceof MediaQueryListEvent && event instanceof Event, "constructor inheritance");
+ check(event.type === "custom" && event.media === "" && !event.matches &&
+ !event.bubbles && !event.cancelable && !event.composed && !event.isTrusted, "event defaults");
+ }
+ const order = [];
+ const init = {};
+ for (const name of ["bubbles", "cancelable", "composed", "matches", "media"]) {
+ Object.defineProperty(init, name, {get() {
+ order.push(name);
+ return name === "media" ? {toString() { order.push("media:string"); return "\ud800"; }} : true;
+ }});
+ }
+ const event = new MediaQueryListEvent({toString() { order.push("type"); return "\udfff"; }}, init);
+ check(order.join() === "type,bubbles,cancelable,composed,matches,media,media:string", "dictionary order " + order);
+ check(event.type === "\udfff" && event.media === "\ud800" && event.matches &&
+ event.bubbles && event.cancelable && event.composed, "converted event fields");
+ for (const name of ["media", "matches"]) {
+ const descriptor = Object.getOwnPropertyDescriptor(MediaQueryListEvent.prototype, name);
+ check(descriptor.enumerable && descriptor.configurable && typeof descriptor.get === "function" &&
+ descriptor.set === undefined && !Object.hasOwn(event, name), "readonly prototype attribute " + name);
+ check(!Reflect.set(event, name, "changed"), "readonly value " + name);
+ throws(() => descriptor.get.call(new Proxy(event, {})), TypeError, "proxy getter " + name);
+ }
+ check(new MediaQueryListEvent(undefined, {media: null, matches: ""}).type === "undefined", "undefined type");
+ check(new MediaQueryListEvent("x", {media: null}).media === "null", "null media");
+ check(new MediaQueryListEvent("x", {matches: []}).matches, "boolean conversion");
+ for (const value of [false, 1, "", Symbol()]) {
+ throws(() => new MediaQueryListEvent("x", value), TypeError, "invalid dictionary");
+ }
+ throws(() => MediaQueryListEvent("x"), TypeError, "requires new");
+ throws(() => new MediaQueryListEvent(), TypeError, "required type");
+ throws(() => new MediaQueryListEvent(Symbol()), TypeError, "symbol type");
+ throws(() => new MediaQueryListEvent("x", {media: Symbol()}), TypeError, "symbol media");
+ const marker = {};
+ const members = ["bubbles", "cancelable", "composed", "matches", "media"];
+ for (const [index, member] of members.entries()) {
+ const reads = [];
+ const dictionary = new Proxy({}, {get(_, key) {
+ reads.push(key);
+ if (key === member) throw marker;
+ return undefined;
+ }});
+ throws(() => new MediaQueryListEvent("x", dictionary), marker, "getter exception " + member);
+ check(reads.join() === members.slice(0, index + 1).join(), "stopped dictionary conversion " + member);
+ }
+ class SubEvent extends MediaQueryListEvent {}
+ const subclass = new SubEvent("sub", {media: "all", matches: true});
+ check(subclass instanceof SubEvent && subclass.media === "all" && subclass.matches, "subclass brand");
+ const frame = document.body.appendChild(document.createElement("iframe"));
+ try {
+ const realm = frame.contentWindow;
+ const getter = Object.getOwnPropertyDescriptor(realm.MediaQueryListEvent.prototype, "media").get;
+ check(getter.call(event) === "\ud800", "cross-realm getter");
+ throws(() => getter.call(new Event("x")), realm.TypeError, "callee realm error");
+ } finally { frame.remove(); }
+ return {checks, failures};
+}
diff --git a/moli-renderer-v8/src/script_vm/tests/browser_api/media_query_list_events.rs b/moli-renderer-v8/src/script_vm/tests/browser_api/media_query_list_events.rs
new file mode 100644
index 000000000..f10018a3e
--- /dev/null
+++ b/moli-renderer-v8/src/script_vm/tests/browser_api/media_query_list_events.rs
@@ -0,0 +1,22 @@
+use super::*;
+
+const PROBE: &str = include_str!("media_query_list_events.js");
+
+fn run_probe(function: &str) -> serde_json::Value {
+ let mut vm = new_parsed_test_vm(
+ "https://media-query-list-events.test/",
+ "<!doctype html><body>",
+ );
+ let result = vm
+ .eval(&format!("{PROBE}\nJSON.stringify({function}())"))
+ .unwrap();
+ let result: serde_json::Value = serde_json::from_str(&result).unwrap();
+ assert_eq!(result["failures"], serde_json::json!([]), "{result}");
+ result
+}
+
+#[test]
+fn media_query_list_event_constructor_preserves_webidl_and_receiver_semantics() {
+ let result = run_probe("mediaQueryListEventConstructorProbe");
+ assert!(result["checks"].as_u64().unwrap() >= 35);
+}
diff --git a/moli-renderer-v8/src/script_vm/tests/browser_api/mod.rs b/moli-renderer-v8/src/script_vm/tests/browser_api/mod.rs
index f8940f565..c98b59360 100644
--- a/moli-renderer-v8/src/script_vm/tests/browser_api/mod.rs
+++ b/moli-renderer-v8/src/script_vm/tests/browser_api/mod.rs
@@ -23,6 +23,7 @@ mod idle_detection;
mod images;
mod media;
mod media_devices;
+mod media_query_list_events;
mod message_channel;
mod misc;
mod navigation;