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): derive interaction input and retain native range state

ldm0ebdd36ba2927
diff --git a/moli-renderer-v8/src/context_bootstrap/event_template.rs b/moli-renderer-v8/src/context_bootstrap/event_template.rs
index a01a27e96..15aefbda2 100644
--- a/moli-renderer-v8/src/context_bootstrap/event_template.rs
+++ b/moli-renderer-v8/src/context_bootstrap/event_template.rs
@@ -18,12 +18,12 @@ use super::{
event_stop_immediate_propagation_callback, event_stop_propagation_callback,
event_target_getter_function, event_time_stamp_getter_function, event_type_getter_function,
event_value_attribute_getter, focus_event_related_target_getter_function,
- form_data_event_form_data_getter_function, keyboard_event_init_callback,
- message_event_init_callback, mouse_event_related_target_getter_function,
- pointer_event_get_predicted_events_callback, submit_event_agent_invoked_getter_function,
- submit_event_respond_with_callback, submit_event_submitter_getter_function,
- track_event_track_getter_function, ui_event_pseudo_target_getter_function,
- ui_event_which_getter_function,
+ form_data_event_form_data_getter_function, input_event_get_target_ranges_callback,
+ keyboard_event_init_callback, message_event_init_callback,
+ mouse_event_related_target_getter_function, pointer_event_get_predicted_events_callback,
+ submit_event_agent_invoked_getter_function, submit_event_respond_with_callback,
+ submit_event_submitter_getter_function, track_event_track_getter_function,
+ ui_event_pseudo_target_getter_function, ui_event_which_getter_function,
},
selection_surface::document_get_selection_callback,
specs::ConstructorSpec,
@@ -231,6 +231,12 @@ struct CustomEventTemplateMethodsDeclaration {
#[derive(WebApiFunctionTemplate)]
#[webapi(interface = web_api_interfaces::InputEvent, enumerable, receiver)]
struct InputEventTemplateAccessorsDeclaration {
+ #[webapi(accessor_property, getter = event_value_attribute_getter, data = crate::util::v8str(scope, "dataTransfer"))]
+ data_transfer: (),
+
+ #[webapi(method, length = 0, callback = input_event_get_target_ranges_callback)]
+ get_target_ranges: (),
+
#[webapi(accessor_property, getter = event_value_attribute_getter, data = crate::util::v8str(scope, "data"))]
data: (),
diff --git a/moli-renderer-v8/src/context_bootstrap/events.rs b/moli-renderer-v8/src/context_bootstrap/events.rs
index 24359cbc1..ee99e0079 100644
--- a/moli-renderer-v8/src/context_bootstrap/events.rs
+++ b/moli-renderer-v8/src/context_bootstrap/events.rs
@@ -13,6 +13,7 @@ mod methods;
mod modifiers;
mod subclasses;
pub(crate) use subclasses::initialize_native_security_policy_violation_event;
+pub(in crate::context_bootstrap) use subclasses::input_event_get_target_ranges_callback;
mod submit;
mod ui;
mod value;
diff --git a/moli-renderer-v8/src/context_bootstrap/events/init.rs b/moli-renderer-v8/src/context_bootstrap/events/init.rs
index 83c38edc4..0b4695cbc 100644
--- a/moli-renderer-v8/src/context_bootstrap/events/init.rs
+++ b/moli-renderer-v8/src/context_bootstrap/events/init.rs
@@ -1,7 +1,4 @@
-use crate::{
- util::{context_host_ptr_from_window_object, throw_type_error},
- webidl,
-};
+use crate::webidl;
#[derive(Default, webidl::WebIdlDictionary)]
#[webidl(prefix = "EventInit", snapshot)]
@@ -45,18 +42,6 @@ pub(super) fn init_bool_property<'s>(
webidl::legacy_bool_member_or(scope, object, "EventInit", key, default)
}
-pub(super) fn init_number_property<'s>(
- scope: &mut v8::PinScope<'s, '_>,
- init: Option<v8::Local<'s, v8::Object>>,
- key: &'static str,
- default: f64,
-) -> f64 {
- let Some(object) = init else {
- return default;
- };
- webidl::legacy_number_member_or(scope, object, "EventInit", key, default)
-}
-
pub(super) fn init_string_property<'s>(
scope: &mut v8::PinScope<'s, '_>,
init: Option<v8::Local<'s, v8::Object>>,
@@ -77,38 +62,6 @@ pub(super) fn init_value_property<'s>(
init.and_then(|object| webidl::property_non_undefined(scope, object, key))
}
-pub(super) fn init_window_view_property<'s>(
- scope: &mut v8::PinScope<'s, '_>,
- init: Option<v8::Local<'s, v8::Object>>,
- constructor_name: &'static str,
-) -> Result<v8::Local<'s, v8::Value>, ()> {
- let Some(value) = init_value_property(scope, init, "view") else {
- return Ok(v8::null(scope).into());
- };
- if value.is_null() {
- return Ok(value);
- }
- let Ok(object) = v8::Local::<v8::Object>::try_from(value) else {
- throw_type_error(
- scope,
- &format!(
- "Failed to construct '{constructor_name}': member view is not of type Window."
- ),
- );
- return Err(());
- };
- if context_host_ptr_from_window_object(scope, object).is_none() {
- throw_type_error(
- scope,
- &format!(
- "Failed to construct '{constructor_name}': member view is not of type Window."
- ),
- );
- return Err(());
- }
- Ok(value)
-}
-
pub(super) fn read_event_init<'s>(
scope: &mut v8::PinScope<'s, '_>,
args: &v8::FunctionCallbackArguments<'s>,
diff --git a/moli-renderer-v8/src/context_bootstrap/events/modifiers.rs b/moli-renderer-v8/src/context_bootstrap/events/modifiers.rs
index 46981df89..3749a302c 100644
--- a/moli-renderer-v8/src/context_bootstrap/events/modifiers.rs
+++ b/moli-renderer-v8/src/context_bootstrap/events/modifiers.rs
@@ -78,6 +78,17 @@ impl<'s> EventModifierInit<'s> {
self.initialize_modifiers(scope, event);
}
+ // TouchEvent keeps its key accessors in private state. Installing the own
+ // modifier properties used by Mouse/Keyboard events would change its shape.
+ pub(super) fn initialize_touch_event_base(
+ &self,
+ scope: &mut v8::PinScope<'s, '_>,
+ event: v8::Local<'s, v8::Object>,
+ ) -> (bool, bool, bool, bool) {
+ self.ui.initialize(scope, event);
+ (self.alt_key, self.meta_key, self.ctrl_key, self.shift_key)
+ }
+
fn initialize_modifiers(
&self,
scope: &mut v8::PinScope<'s, '_>,
diff --git a/moli-renderer-v8/src/context_bootstrap/events/subclasses.rs b/moli-renderer-v8/src/context_bootstrap/events/subclasses.rs
index db40bc477..1e5b4c761 100644
--- a/moli-renderer-v8/src/context_bootstrap/events/subclasses.rs
+++ b/moli-renderer-v8/src/context_bootstrap/events/subclasses.rs
@@ -1,8 +1,5 @@
use super::base::{define_event_property, event_type_argument, initialize_event_object_with_type};
-use super::init::{
- init_bool_property, init_number_property, init_string_property, init_value_property,
- init_window_view_property, read_event_init,
-};
+use super::init::{init_bool_property, init_string_property, init_value_property, read_event_init};
use super::kind::EventSubclassKind;
use super::*;
@@ -10,6 +7,7 @@ mod basic;
mod constructor;
mod data;
mod error;
+mod input;
mod keyboard;
mod pointer;
mod security_policy;
@@ -31,3 +29,5 @@ pub(in crate::context_bootstrap::events) use data::{
pub(crate) use error::construct_original_error_event;
pub(in crate::context_bootstrap) use keyboard::keyboard_event_init_callback;
pub(crate) use security_policy::initialize_native_security_policy_violation_event;
+
+pub(in crate::context_bootstrap) use input::input_event_get_target_ranges_callback;
diff --git a/moli-renderer-v8/src/context_bootstrap/events/subclasses/basic.rs b/moli-renderer-v8/src/context_bootstrap/events/subclasses/basic.rs
index 934820f07..cb48da017 100644
--- a/moli-renderer-v8/src/context_bootstrap/events/subclasses/basic.rs
+++ b/moli-renderer-v8/src/context_bootstrap/events/subclasses/basic.rs
@@ -97,29 +97,6 @@ pub(in crate::context_bootstrap::events) fn initialize_text_event<'s>(
}
}
-use moli_webapi_declare::WebApiObject;
-#[derive(WebApiObject)]
-#[webapi(plain, data_properties, enumerable)]
-struct UiEventInitDeclaration<'scope> {
- view: v8::Local<'scope, v8::Value>,
- detail: f64,
-}
-
-pub(in crate::context_bootstrap::events::subclasses) fn initialize_ui_event<'s>(
- scope: &mut v8::PinScope<'s, '_>,
- event: v8::Local<'s, v8::Object>,
- init: Option<v8::Local<'s, v8::Object>>,
-) -> bool {
- let Ok(view) = init_window_view_property(scope, init, "UIEvent") else {
- return false;
- };
- let detail = init_number_property(scope, init, "detail", 0.0);
- UiEventInitDeclaration::new(view, detail)
- .initialize(scope, event)
- .expect("UIEvent init declaration should initialize");
- true
-}
-
pub(super) enum BasicEventInit<'s> {
Ui(UiEventInit<'s>),
Focus(FocusEventInit<'s>),
diff --git a/moli-renderer-v8/src/context_bootstrap/events/subclasses/constructor.rs b/moli-renderer-v8/src/context_bootstrap/events/subclasses/constructor.rs
index 2aa298af1..ca8024f88 100644
--- a/moli-renderer-v8/src/context_bootstrap/events/subclasses/constructor.rs
+++ b/moli-renderer-v8/src/context_bootstrap/events/subclasses/constructor.rs
@@ -71,6 +71,19 @@ fn event_subclass_constructor_callback<'s>(
} else {
None
};
+ let interaction_event_init = if matches!(
+ kind,
+ EventSubclassKind::InputEvent
+ | EventSubclassKind::TouchEvent
+ | EventSubclassKind::CapturedMouseEvent
+ ) {
+ let Some(init) = input::InteractionEventInit::parse(scope, &args, kind) else {
+ return;
+ };
+ Some(init)
+ } else {
+ None
+ };
let value_event_init = if matches!(
kind,
EventSubclassKind::ClipboardEvent
@@ -171,6 +184,7 @@ fn event_subclass_constructor_callback<'s>(
})
.or_else(|| font_face_init.as_ref().map(crate::context_bootstrap::css_fontface_runtime::FontFaceSetLoadEventInit::event_flags))
.or_else(|| value_event_init.as_ref().map(values::ValueEventInit::event_flags))
+ .or_else(|| interaction_event_init.as_ref().map(input::InteractionEventInit::event_flags))
.or_else(|| read_event_init(scope, &args))
else {
return;
@@ -214,8 +228,13 @@ fn event_subclass_constructor_callback<'s>(
| EventSubclassKind::PageTransitionEvent => value_event_init
.expect("value event init is parsed")
.initialize(scope, event),
- EventSubclassKind::CapturedMouseEvent => {
- if !data::initialize_captured_mouse_event(scope, event, init) {
+ EventSubclassKind::InputEvent
+ | EventSubclassKind::TouchEvent
+ | EventSubclassKind::CapturedMouseEvent => {
+ if !interaction_event_init
+ .expect("interaction event init is parsed")
+ .initialize(scope, event)
+ {
return;
}
}
@@ -226,10 +245,6 @@ fn event_subclass_constructor_callback<'s>(
keyboard_event_init.expect("KeyboardEvent init should be parsed"),
);
}
- EventSubclassKind::InputEvent => data::initialize_input_event(scope, event, init),
- EventSubclassKind::TouchEvent => {
- crate::context_bootstrap::touch_runtime::initialize_touch_event(scope, event, init);
- }
EventSubclassKind::MessageEvent => message::initialize_message_event(
scope,
event,
diff --git a/moli-renderer-v8/src/context_bootstrap/events/subclasses/data.rs b/moli-renderer-v8/src/context_bootstrap/events/subclasses/data.rs
index 264898c03..c8ad4a966 100644
--- a/moli-renderer-v8/src/context_bootstrap/events/subclasses/data.rs
+++ b/moli-renderer-v8/src/context_bootstrap/events/subclasses/data.rs
@@ -130,21 +130,6 @@ struct NavigateEventMethodsDeclaration {
scroll: (),
}
-#[derive(WebApiObject)]
-#[webapi(plain, data_properties, enumerable)]
-struct CapturedMouseEventInitDeclaration {
- surface_x: i32,
- surface_y: i32,
-}
-
-#[derive(WebApiObject)]
-#[webapi(plain, data_properties, enumerable)]
-struct InputEventInitDeclaration<'scope> {
- data: v8::Local<'scope, v8::Value>,
- input_type: v8::Local<'scope, v8::String>,
- is_composing: bool,
-}
-
#[derive(webidl::WebIdlDictionary)]
#[webidl(prefix = "PromiseRejectionEventInit", snapshot)]
struct PromiseRejectionEventInitMembers<'s> {
@@ -229,65 +214,6 @@ pub(super) fn parse_storage_event_init<'s>(
crate::context_bootstrap::events::parse_event_dictionary(scope, args, "StorageEvent")
}
-fn captured_mouse_coordinate<'s>(
- scope: &mut v8::PinScope<'s, '_>,
- init: Option<v8::Local<'s, v8::Object>>,
- name: &'static str,
-) -> Option<i32> {
- let Some(init) = init else {
- return Some(-1);
- };
- let context = webidl::Context::member("CapturedMouseEventInit", name);
- let value = match webidl::property_result(scope, init, name, context) {
- Ok(Some(value)) if !value.is_undefined() => value,
- Ok(_) => return Some(-1),
- Err(error) => {
- webidl::throw_error(scope, &error);
- return None;
- }
- };
- let value = match webidl::convert::<webidl::EnforceRangeLong>(scope, value, context) {
- Ok(value) => i32::from(value),
- Err(error) if error.is_pending_exception() => return None,
- Err(error) => {
- crate::util::throw_range_error(scope, &error.to_string());
- return None;
- }
- };
- if value < -1 {
- crate::util::throw_range_error(
- scope,
- "CapturedMouseEvent coordinates must be -1 or non-negative.",
- );
- return None;
- }
- Some(value)
-}
-
-pub(in crate::context_bootstrap::events::subclasses) fn initialize_captured_mouse_event<'s>(
- scope: &mut v8::PinScope<'s, '_>,
- event: v8::Local<'s, v8::Object>,
- init: Option<v8::Local<'s, v8::Object>>,
-) -> bool {
- let Some(surface_x) = captured_mouse_coordinate(scope, init, "surfaceX") else {
- return false;
- };
- let Some(surface_y) = captured_mouse_coordinate(scope, init, "surfaceY") else {
- return false;
- };
- if (surface_x == -1) != (surface_y == -1) {
- crate::util::throw_range_error(
- scope,
- "CapturedMouseEvent coordinates must both be -1 or both be non-negative.",
- );
- return false;
- }
- CapturedMouseEventInitDeclaration::new(surface_x, surface_y)
- .initialize(scope, event)
- .expect("CapturedMouseEvent init declaration should initialize");
- true
-}
-
pub(in crate::context_bootstrap::events::subclasses) fn initialize_storage_event<'s>(
scope: &mut v8::PinScope<'s, '_>,
event: v8::Local<'s, v8::Object>,
@@ -298,21 +224,6 @@ pub(in crate::context_bootstrap::events::subclasses) fn initialize_storage_event
.expect("StorageEvent state");
}
-pub(in crate::context_bootstrap::events::subclasses) fn initialize_input_event<'s>(
- scope: &mut v8::PinScope<'s, '_>,
- event: v8::Local<'s, v8::Object>,
- init: Option<v8::Local<'s, v8::Object>>,
-) {
- basic::initialize_ui_event(scope, event, init);
- let data = init_value_property(scope, init, "data").unwrap_or_else(|| v8::null(scope).into());
- let input_type = init_string_property(scope, init, "inputType", "");
- let input_type_value = v8_string(scope, &input_type).expect("input event inputType");
- let is_composing = init_bool_property(scope, init, "isComposing", false);
- InputEventInitDeclaration::new(data, input_type_value, is_composing)
- .initialize(scope, event)
- .expect("InputEvent init declaration should initialize");
-}
-
pub(in crate::context_bootstrap::events::subclasses) fn initialize_promise_rejection_event<'s>(
scope: &mut v8::PinScope<'s, '_>,
event: v8::Local<'s, v8::Object>,
diff --git a/moli-renderer-v8/src/context_bootstrap/events/subclasses/input.rs b/moli-renderer-v8/src/context_bootstrap/events/subclasses/input.rs
new file mode 100644
index 000000000..b34cd1ded
--- /dev/null
+++ b/moli-renderer-v8/src/context_bootstrap/events/subclasses/input.rs
@@ -0,0 +1,182 @@
+use super::*;
+use crate::context_bootstrap::events::{EventInit, modifiers::EventModifierInit, ui::UiEventInit};
+use crate::context_bootstrap::{range, touch_runtime};
+use crate::util::get_private_value;
+use crate::{web_api_interfaces, webidl};
+use webidl::WebIdlDictionarySerialize;
+
+const INPUT_EVENT_TARGET_RANGES_SLOT: &str = "__moliInputEventTargetRanges";
+
+#[derive(webidl::WebIdlDictionary)]
+#[webidl(prefix = "InputEventInit", snapshot)]
+pub(super) struct InputEventInit<'s> {
+ #[webidl(inherit)]
+ ui: UiEventInit<'s>,
+ #[webidl(nullable, converter = "raw")]
+ data: Option<webidl::DomString16>,
+ #[webidl(nullable, interface = web_api_interfaces::DataTransfer)]
+ data_transfer: Option<v8::Local<'s, v8::Object>>,
+ #[webidl(default = webidl::DomString16(Vec::new()), converter = "raw")]
+ input_type: webidl::DomString16,
+ #[webidl(default = false)]
+ is_composing: bool,
+ #[webidl(sequence, interface = web_api_interfaces::StaticRange, default = Vec::new())]
+ #[webidl(snapshot_slot = INPUT_EVENT_TARGET_RANGES_SLOT, snapshot_state_with = live_range_value)]
+ target_ranges: Vec<v8::Local<'s, v8::Object>>,
+}
+
+fn live_range_value<'s>(
+ scope: &mut v8::PinScope<'s, '_>,
+ range: &v8::Local<'s, v8::Object>,
+) -> Option<v8::Local<'s, v8::Value>> {
+ range::live_range_from_static_range(scope, *range).map(Into::into)
+}
+
+#[derive(webidl::WebIdlDictionary)]
+#[webidl(prefix = "TouchEventInit")]
+pub(super) struct TouchEventInit<'s> {
+ #[webidl(inherit)]
+ modifiers: EventModifierInit<'s>,
+ #[webidl(sequence, interface = web_api_interfaces::Touch, default = Vec::new())]
+ changed_touches: Vec<v8::Local<'s, v8::Object>>,
+ #[webidl(sequence, interface = web_api_interfaces::Touch, default = Vec::new())]
+ target_touches: Vec<v8::Local<'s, v8::Object>>,
+ #[webidl(sequence, interface = web_api_interfaces::Touch, default = Vec::new())]
+ touches: Vec<v8::Local<'s, v8::Object>>,
+}
+
+#[derive(webidl::WebIdlDictionary)]
+#[webidl(prefix = "CapturedMouseEventInit", snapshot)]
+pub(super) struct CapturedMouseEventInit {
+ #[webidl(inherit)]
+ base: EventInit,
+ #[webidl(with = captured_mouse_coordinate)]
+ surface_x: i32,
+ #[webidl(with = captured_mouse_coordinate)]
+ surface_y: i32,
+}
+
+// Preserve the existing extension's RangeError policy while the derive controls
+// Get order and propagates abrupt completion without reading later members.
+fn captured_mouse_coordinate<'s>(
+ scope: &mut v8::PinScope<'s, '_>,
+ object: v8::Local<'s, v8::Object>,
+ name: &'static str,
+) -> Result<i32, webidl::WebIdlError> {
+ let context = webidl::Context::member("CapturedMouseEventInit", name);
+ let value = match webidl::property_result(scope, object, name, context)? {
+ Some(value) if !value.is_undefined() => value,
+ _ => return Ok(-1),
+ };
+ let value = match webidl::convert::<webidl::EnforceRangeLong>(scope, value, context) {
+ Ok(value) => i32::from(value),
+ Err(error) if error.is_pending_exception() => return Err(error),
+ Err(error) => {
+ crate::util::throw_range_error(scope, &error.to_string());
+ return Err(webidl::WebIdlError::pending_exception(context));
+ }
+ };
+ if value < -1 {
+ crate::util::throw_range_error(
+ scope,
+ "CapturedMouseEvent coordinates must be -1 or non-negative.",
+ );
+ return Err(webidl::WebIdlError::pending_exception(context));
+ }
+ Ok(value)
+}
+
+pub(super) enum InteractionEventInit<'s> {
+ Input(InputEventInit<'s>),
+ Touch(TouchEventInit<'s>),
+ Captured(CapturedMouseEventInit),
+}
+
+impl<'s> InteractionEventInit<'s> {
+ pub(super) fn parse(
+ scope: &mut v8::PinScope<'s, '_>,
+ args: &v8::FunctionCallbackArguments<'s>,
+ kind: EventSubclassKind,
+ ) -> Option<Self> {
+ use super::super::parse_event_dictionary;
+ Some(match kind {
+ EventSubclassKind::InputEvent => {
+ Self::Input(parse_event_dictionary(scope, args, "InputEvent")?)
+ }
+ EventSubclassKind::TouchEvent => {
+ Self::Touch(parse_event_dictionary(scope, args, "TouchEvent")?)
+ }
+ EventSubclassKind::CapturedMouseEvent => {
+ let init: CapturedMouseEventInit =
+ parse_event_dictionary(scope, args, "CapturedMouseEvent")?;
+ if (init.surface_x == -1) != (init.surface_y == -1) {
+ crate::util::throw_range_error(
+ scope,
+ "CapturedMouseEvent coordinates must both be -1 or both be non-negative.",
+ );
+ return None;
+ }
+ Self::Captured(init)
+ }
+ _ => unreachable!("interaction event kind"),
+ })
+ }
+
+ pub(super) fn event_flags(&self) -> (bool, bool, bool) {
+ match self {
+ Self::Input(init) => init.ui.event_flags(),
+ Self::Touch(init) => init.modifiers.event_flags(),
+ Self::Captured(init) => (init.base.bubbles, init.base.cancelable, init.base.composed),
+ }
+ }
+
+ pub(super) fn initialize(
+ self,
+ scope: &mut v8::PinScope<'s, '_>,
+ event: v8::Local<'s, v8::Object>,
+ ) -> bool {
+ match self {
+ Self::Input(init) => init.initialize_snapshot(scope, event).is_some(),
+ Self::Captured(init) => init.initialize_snapshot(scope, event).is_some(),
+ Self::Touch(init) => {
+ let keys = init.modifiers.initialize_touch_event_base(scope, event);
+ touch_runtime::initialize_touch_event_lists(
+ scope,
+ event,
+ &init.touches,
+ &init.target_touches,
+ &init.changed_touches,
+ keys,
+ );
+ true
+ }
+ }
+ }
+}
+
+pub(in crate::context_bootstrap) fn input_event_get_target_ranges_callback<'s>(
+ scope: &mut v8::PinScope<'s, '_>,
+ args: v8::FunctionCallbackArguments<'s>,
+ mut rv: v8::ReturnValue<'_, v8::Value>,
+) {
+ let event = event_backing(scope, args.this());
+ let mut snapshots = Vec::new();
+ if let Some(ranges) = get_private_value(scope, event, INPUT_EVENT_TARGET_RANGES_SLOT)
+ .and_then(|value| v8::Local::<v8::Array>::try_from(value).ok())
+ {
+ snapshots.reserve(ranges.length() as usize);
+ for index in 0..ranges.length() {
+ let Some(range) = ranges
+ .get_index(scope, index)
+ .and_then(|value| v8::Local::<v8::Object>::try_from(value).ok())
+ else {
+ return;
+ };
+ let Some(snapshot) = range::static_range_snapshot(scope, range) else {
+ return;
+ };
+ snapshots.push(snapshot.into());
+ }
+ }
+ rv.set(v8::Array::new_with_elements(scope, &snapshots).into());
+}
diff --git a/moli-renderer-v8/src/context_bootstrap/range.rs b/moli-renderer-v8/src/context_bootstrap/range.rs
index 034285772..00c2216f3 100644
--- a/moli-renderer-v8/src/context_bootstrap/range.rs
+++ b/moli-renderer-v8/src/context_bootstrap/range.rs
@@ -11,9 +11,9 @@ pub(super) use arguments::webidl_node_arg;
pub(super) use exceptions::throw_named_dom_exception;
pub(super) use object::{
RANGE_WRAPPER_INTERNAL_FIELD_COUNT, current_document_object, initialize_range_object,
- native_range_boundary_handles, native_range_boundary_point, new_range_for_document,
- range_boundary_container_object, range_boundary_offset, range_is_collapsed,
- range_native_record_handle, set_range_boundary,
+ live_range_from_static_range, native_range_boundary_handles, native_range_boundary_point,
+ new_range_for_document, range_boundary_container_object, range_boundary_offset,
+ range_is_collapsed, range_native_record_handle, set_range_boundary, static_range_snapshot,
};
pub(super) use static_storage::{StaticRangeInitMembers, initialize_static_range_object};
pub(super) use validation::{child_index, range_node_length, range_validate_boundary_point};
diff --git a/moli-renderer-v8/src/context_bootstrap/range/object.rs b/moli-renderer-v8/src/context_bootstrap/range/object.rs
index 880442613..7134a6c84 100644
--- a/moli-renderer-v8/src/context_bootstrap/range/object.rs
+++ b/moli-renderer-v8/src/context_bootstrap/range/object.rs
@@ -42,6 +42,57 @@ pub(in crate::context_bootstrap) fn initialize_range_object<'s>(
initialize_native_range_record(scope, range, document, existing_handle);
}
+// InputEvent stores live copies and exposes fresh StaticRanges. Use intrinsic
+// templates and native boundary storage, without invoking author constructors
+// or boundary getters.
+pub(in crate::context_bootstrap) fn live_range_from_static_range<'s>(
+ scope: &mut v8::PinScope<'s, '_>,
+ source: v8::Local<'s, v8::Object>,
+) -> Option<v8::Local<'s, v8::Object>> {
+ let start = static_range_boundary_container_object(scope, source, RangeBoundarySide::Start)?;
+ let end = static_range_boundary_container_object(scope, source, RangeBoundarySide::End)?;
+ let start_offset = static_range_boundary_offset(scope, source, RangeBoundarySide::Start) as u32;
+ let end_offset = static_range_boundary_offset(scope, source, RangeBoundarySide::End) as u32;
+ let document = current_document_object(scope)?;
+ let range =
+ super::super::exposed_interfaces::build_intrinsic_interface_instance(scope, "Range")
+ .ok()?;
+ initialize_range_object(scope, range, document);
+ set_range_boundary(scope, range, RangeBoundarySide::Start, start, start_offset);
+ set_range_boundary(scope, range, RangeBoundarySide::End, end, end_offset);
+ crate::web_api_interfaces::initialize(scope, range, "Range").ok()?;
+ Some(range)
+}
+
+pub(in crate::context_bootstrap) fn static_range_snapshot<'s>(
+ scope: &mut v8::PinScope<'s, '_>,
+ source: v8::Local<'s, v8::Object>,
+) -> Option<v8::Local<'s, v8::Object>> {
+ let start = range_boundary_container_object(scope, source, RangeBoundarySide::Start)?;
+ let end = range_boundary_container_object(scope, source, RangeBoundarySide::End)?;
+ let start_offset = range_boundary_offset(scope, source, RangeBoundarySide::Start) as u32;
+ let end_offset = range_boundary_offset(scope, source, RangeBoundarySide::End) as u32;
+ let range =
+ super::super::exposed_interfaces::build_intrinsic_interface_instance(scope, "StaticRange")
+ .ok()?;
+ super::static_storage::initialize_static_range_object(
+ scope,
+ range,
+ start,
+ start_offset,
+ end,
+ end_offset,
+ );
+ let prototype = super::super::exposed_interfaces::ensure_intrinsic_interface_prototype(
+ scope,
+ "StaticRange",
+ )
+ .ok()?;
+ range.set_prototype(scope, prototype.into())?;
+ crate::web_api_interfaces::initialize(scope, range, "StaticRange").ok()?;
+ Some(range)
+}
+
pub(in crate::context_bootstrap) fn set_range_boundary<'s>(
scope: &mut v8::PinScope<'s, '_>,
range: v8::Local<'s, v8::Object>,
diff --git a/moli-renderer-v8/src/context_bootstrap/touch_runtime.rs b/moli-renderer-v8/src/context_bootstrap/touch_runtime.rs
index c0515c193..104ce036c 100644
--- a/moli-renderer-v8/src/context_bootstrap/touch_runtime.rs
+++ b/moli-renderer-v8/src/context_bootstrap/touch_runtime.rs
@@ -80,13 +80,6 @@ struct TouchListPrototypeDeclaration {
item: (),
}
-#[derive(WebApiObject)]
-#[webapi(plain, data_properties, enumerable)]
-struct TouchUiEventInitDeclaration<'scope> {
- view: v8::Local<'scope, v8::Value>,
- detail: f64,
-}
-
#[derive(WebApiObject)]
#[webapi(interface = web_api_interfaces::TouchEvent)]
struct TouchEventObjectDeclaration<'scope> {
@@ -107,7 +100,7 @@ struct TouchEventObjectDeclaration<'scope> {
}
#[derive(WebApiFunctionTemplate)]
-#[webapi(interface = web_api_interfaces::TouchEvent)]
+#[webapi(interface = web_api_interfaces::TouchEvent, receiver)]
struct TouchEventPrototypeDeclaration {
#[webapi(accessor_property, getter = touch_event_getter, data = callback_data_index_value(scope, 0), enumerable)]
touches: (),
@@ -248,56 +241,6 @@ pub(in crate::context_bootstrap) fn touch_list_item_callback<'s>(
}
}
-fn touch_event_init_bool(
- scope: &mut v8::PinScope<'_, '_>,
- init: Option<v8::Local<'_, v8::Object>>,
- key: &'static str,
- default: bool,
-) -> bool {
- init.and_then(|object| object.get(scope, v8str(scope, key).into()))
- .filter(|value| !value.is_null_or_undefined())
- .map(|value| value.boolean_value(scope))
- .unwrap_or(default)
-}
-
-fn touch_event_init_value<'s>(
- scope: &mut v8::PinScope<'s, '_>,
- init: Option<v8::Local<'s, v8::Object>>,
- key: &'static str,
-) -> Option<v8::Local<'s, v8::Value>> {
- init.and_then(|object| object.get(scope, v8str(scope, key).into()))
- .filter(|value| !value.is_undefined())
-}
-
-fn initialize_touch_ui_event<'s>(
- scope: &mut v8::PinScope<'s, '_>,
- event: v8::Local<'s, v8::Object>,
- init: Option<v8::Local<'s, v8::Object>>,
-) {
- let view = touch_event_init_value(scope, init, "view")
- .unwrap_or_else(|| scope.get_current_context().global(scope).into());
- let detail = init
- .and_then(|object| object.get(scope, v8str(scope, "detail").into()))
- .filter(|value| !value.is_null_or_undefined())
- .and_then(|value| value.number_value(scope))
- .filter(|value| !value.is_nan())
- .unwrap_or(0.0);
- TouchUiEventInitDeclaration::new(view, detail)
- .initialize(scope, event)
- .expect("Touch UIEvent init declaration should initialize");
-}
-
-fn touch_init_object<'s>(
- scope: &mut v8::PinScope<'s, '_>,
- value: v8::Local<'s, v8::Value>,
-) -> Option<v8::Local<'s, v8::Object>> {
- if value.is_null_or_undefined() || !value.is_object() {
- None
- } else {
- value.to_object(scope)
- }
-}
-
pub(in crate::context_bootstrap) fn touch_constructor_callback<'s>(
scope: &mut v8::PinScope<'s, '_>,
args: v8::FunctionCallbackArguments<'s>,
@@ -328,47 +271,34 @@ pub(in crate::context_bootstrap) fn touch_constructor_callback<'s>(
rv.set(touch.into());
}
-pub(in crate::context_bootstrap) fn build_touch_list<'s>(
+fn build_touch_list<'s>(
scope: &mut v8::PinScope<'s, '_>,
- value: Option<v8::Local<'s, v8::Value>>,
+ touches: &[v8::Local<'s, v8::Object>],
) -> v8::Local<'s, v8::Object> {
- let source = value.and_then(|value| touch_init_object(scope, value));
- let length = source
- .and_then(|source| source.get(scope, v8str(scope, "length").into()))
- .and_then(|value| value.number_value(scope))
- .filter(|value| value.is_finite() && *value >= 0.0)
- .map(|value| value as u32)
- .unwrap_or(0);
-
- let list = TouchListObjectDeclaration::new(length)
+ let list = TouchListObjectDeclaration::new(touches.len() as u32)
.bind(scope)
.expect("TouchList declaration should bind");
- for index in 0..length {
- if let Some(item) = source.and_then(|source| source.get_index(scope, index)) {
- let _ = list.set_index(scope, index, item);
- }
+ for (index, touch) in touches.iter().enumerate() {
+ let key = v8::Integer::new_from_unsigned(scope, index as u32)
+ .to_string(scope)
+ .expect("TouchList index");
+ list.create_data_property(scope, key.into(), (*touch).into())
+ .expect("TouchList item");
}
-
list
}
-pub(in crate::context_bootstrap) fn initialize_touch_event<'s>(
+pub(in crate::context_bootstrap) fn initialize_touch_event_lists<'s>(
scope: &mut v8::PinScope<'s, '_>,
event: v8::Local<'s, v8::Object>,
- init: Option<v8::Local<'s, v8::Object>>,
+ touches: &[v8::Local<'s, v8::Object>],
+ target_touches: &[v8::Local<'s, v8::Object>],
+ changed_touches: &[v8::Local<'s, v8::Object>],
+ (alt_key, meta_key, ctrl_key, shift_key): (bool, bool, bool, bool),
) {
- initialize_touch_ui_event(scope, event, init);
-
- let touches_value = touch_event_init_value(scope, init, "touches");
- let target_touches_value = touch_event_init_value(scope, init, "targetTouches");
- let changed_touches_value = touch_event_init_value(scope, init, "changedTouches");
- let touches = build_touch_list(scope, touches_value);
- let target_touches = build_touch_list(scope, target_touches_value);
- let changed_touches = build_touch_list(scope, changed_touches_value);
- let alt_key = touch_event_init_bool(scope, init, "altKey", false);
- let meta_key = touch_event_init_bool(scope, init, "metaKey", false);
- let ctrl_key = touch_event_init_bool(scope, init, "ctrlKey", false);
- let shift_key = touch_event_init_bool(scope, init, "shiftKey", false);
+ let touches = build_touch_list(scope, touches);
+ let target_touches = build_touch_list(scope, target_touches);
+ let changed_touches = build_touch_list(scope, changed_touches);
TouchEventObjectDeclaration::new(
touches,
target_touches,
@@ -379,7 +309,7 @@ pub(in crate::context_bootstrap) fn initialize_touch_event<'s>(
shift_key,
)
.initialize(scope, event)
- .expect("TouchEvent declaration should initialize object");
+ .expect("TouchEvent lists");
}
pub(in crate::context_bootstrap) fn install_touch_template_bindings<'s>(
diff --git a/moli-renderer-v8/src/script_vm/tests/browser_api/input_event_init.rs b/moli-renderer-v8/src/script_vm/tests/browser_api/input_event_init.rs
new file mode 100644
index 000000000..411f6f7f8
--- /dev/null
+++ b/moli-renderer-v8/src/script_vm/tests/browser_api/input_event_init.rs
@@ -0,0 +1,30 @@
+use super::*;
+
+#[test]
+fn input_and_touch_dictionaries_convert_before_native_sequences_and_range_state() {
+ let mut vm = new_storage_html_test_vm("https://input-touch-dictionary.test/");
+ assert_eq!(
+ vm.eval(include_str!(
+ "../../../../tests/fixtures/input-touch-dictionary.js"
+ ))
+ .unwrap(),
+ "true"
+ );
+ assert_eq!(vm.eval(r#"(() => {
+ const raw = '\ud800\0\udc00';
+ if (new InputEvent('audit', {inputType: raw}).inputType !== raw) throw Error('legacy inputType UTF16');
+ for (const sentinel of [{}, null, undefined, 7]) {
+ const reads = [];
+ let caught = Symbol();
+ try {new CapturedMouseEvent('audit', {
+ get bubbles() {reads.push('bubbles');return false;},
+ get cancelable() {reads.push('cancelable');return false;},
+ get composed() {reads.push('composed');return false;},
+ get surfaceX() {reads.push('surfaceX');throw sentinel;},
+ get surfaceY() {throw Error('must stop');}
+ });} catch(e) {caught=e;}
+ if (caught !== sentinel || reads.join() !== 'bubbles,cancelable,composed,surfaceX') throw Error('CapturedMouse abrupt completion');
+ }
+ return true;
+ })()"#).unwrap(), "true");
+}
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 af5838aa4..3fe32fbe4 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
@@ -35,6 +35,7 @@ mod ice_error_event;
mod idle_callbacks;
mod idle_detection;
mod images;
+mod input_event_init;
mod legacy_event_init;
mod media;
mod media_devices;
diff --git a/moli-renderer-v8/tests/fixtures/input-touch-dictionary.js b/moli-renderer-v8/tests/fixtures/input-touch-dictionary.js
new file mode 100644
index 000000000..dd7029656
--- /dev/null
+++ b/moli-renderer-v8/tests/fixtures/input-touch-dictionary.js
@@ -0,0 +1,99 @@
+(() => {
+ const assert = (value, label) => { if (!value) throw Error(label); };
+ const base = ['bubbles', 'cancelable', 'composed'];
+ const ui = ['detail', 'sourceCapabilities', 'view'];
+ const modifiers = ['altKey', 'ctrlKey', 'metaKey', 'modifierAltGraph', 'modifierCapsLock',
+ 'modifierFn', 'modifierNumLock', 'modifierScrollLock', 'modifierSymbol', 'shiftKey'];
+ const cases = [
+ [InputEvent, [...base, ...ui, 'data', 'dataTransfer', 'inputType', 'isComposing', 'targetRanges']],
+ [TouchEvent, [...base, ...ui, ...modifiers, 'changedTouches', 'targetTouches', 'touches']]
+ ];
+ for (const [Constructor, members] of cases) {
+ for (const value of [1, true, 'init', 1n, Symbol('init')]) {
+ let caught;
+ try { new Constructor('audit', value); } catch (e) { caught = e; }
+ assert(caught instanceof TypeError, Constructor.name + ' primitive dictionary');
+ }
+ const reads = [];
+ const options = new Proxy({}, {get(_, key) {
+ if (members.includes(key)) reads.push(key);
+ return base.includes(key) ? true : undefined;
+ }, has() {throw Error('Get required');}});
+ const event = new Constructor('audit', options);
+ assert(reads.join() === members.join(), Constructor.name + ' inherited conversion order: ' + reads);
+ assert(event.bubbles && event.cancelable && event.composed, Constructor.name + ' flags');
+ for (const member of members) for (const sentinel of [{}, undefined, null, 7]) {
+ reads.length = 0;
+ const bad = new Proxy({}, {get(_, key) {
+ if (members.includes(key)) reads.push(key);
+ if (key === member) throw sentinel;
+ return undefined;
+ }});
+ let caught = Symbol();
+ try { new Constructor('audit', bad); } catch (e) { caught = e; }
+ assert(caught === sentinel, Constructor.name + '/' + member + ' exception');
+ assert(reads.join() === members.slice(0, members.indexOf(member) + 1).join(),
+ Constructor.name + '/' + member + ' abrupt completion: ' + reads);
+ }
+ }
+ const transfer = new DataTransfer();
+ Object.setPrototypeOf(transfer, null);
+ const utf16 = '\ud800\0\udc00';
+ const input = new InputEvent('audit', {data: utf16, inputType: 'insertText', dataTransfer: transfer});
+ assert(input.data === utf16 && input.inputType === 'insertText' && input.dataTransfer === transfer, 'InputEvent native and UTF16');
+ assert(new InputEvent('audit').data === null && new InputEvent('audit', {data: null}).data === null, 'nullable data');
+ assert(new InputEvent('audit', {data: {toString() {return 'text';}}}).data === 'text', 'data DOMString');
+ for (const dataTransfer of [{}, new Proxy(transfer, {})]) {
+ let caught;
+ try { new InputEvent('audit', {dataTransfer}); } catch (e) { caught = e; }
+ assert(caught instanceof TypeError, 'InputEvent DataTransfer brand');
+ }
+ const text = document.createTextNode('abcdef'); document.body.append(text);
+ const original = new StaticRange({startContainer: text, startOffset: 1, endContainer: text, endOffset: 4});
+ Object.setPrototypeOf(original, null);
+ Object.defineProperty(original, 'startContainer', {get() {throw Error('public range boundary');}});
+ const NativeRange = Range, NativeStaticRange = StaticRange;
+ let ranged, a, b;
+ try {
+ globalThis.Range = function () {throw Error('public Range constructor');};
+ globalThis.StaticRange = function () {throw Error('public StaticRange constructor');};
+ ranged = new InputEvent('audit', {targetRanges: [original]});
+ a = ranged.getTargetRanges(); b = ranged.getTargetRanges();
+ } finally {
+ globalThis.Range = NativeRange; globalThis.StaticRange = NativeStaticRange;
+ }
+ assert(a !== b && a[0] !== b[0] && a[0] !== original && a[0] instanceof StaticRange, 'fresh native snapshots');
+ text.deleteData(0, 2);
+ const after = ranged.getTargetRanges()[0];
+ assert(after.startContainer === text && after.startOffset === 0 && after.endOffset === 2, 'internal live range');
+ let caught;
+ try { InputEvent.prototype.getTargetRanges.call({}); } catch (e) { caught = e; }
+ assert(caught instanceof TypeError, 'range method native receiver');
+ const touch = new Touch({identifier: 3, target: document.body, clientX: 2});
+ Object.setPrototypeOf(touch, null);
+ const touched = new TouchEvent('audit', {touches: new Set([touch]), altKey: true, ctrlKey: true});
+ assert(touched.touches.length === 1 && touched.touches[0] === touch && touched.touches.item(0) === touch, 'native Touch sequence');
+ assert(touched.altKey && touched.ctrlKey && !touched.metaKey && !touched.shiftKey, 'TouchEvent modifiers');
+ try {
+ Object.defineProperty(TouchList.prototype, '0', {configurable: true, set() {throw Error('author TouchList setter');}});
+ assert(new TouchEvent('audit', {touches: [touch]}).touches[0] === touch, 'intrinsic TouchList item creation');
+ } finally { delete TouchList.prototype[0]; }
+ for (const [Constructor, member, native] of [[InputEvent, 'targetRanges', original],
+ [TouchEvent, 'changedTouches', touch], [TouchEvent, 'targetTouches', touch], [TouchEvent, 'touches', touch]]) {
+ for (const value of [null, {}, [new Proxy(native, {})]]) {
+ let caught;
+ try { new Constructor('audit', {[member]: value}); } catch (e) { caught = e; }
+ assert(caught instanceof TypeError, Constructor.name + '/' + member + ' strict sequence/native brand');
+ }
+ let next = 0;
+ const sequence = {[Symbol.iterator]() {return {next() {
+ if (next++ === 0) return {done: false, value: {}};
+ throw Error('must validate first item');
+ }}}};
+ let caught;
+ try { new Constructor('audit', {[member]: sequence}); } catch (e) { caught = e; }
+ assert(caught instanceof TypeError && next === 1, Constructor.name + '/' + member + ' item conversion timing');
+ }
+ text.remove();
+ return true;
+})()