diff --git a/moli-renderer-v8/src/context_bootstrap.rs b/moli-renderer-v8/src/context_bootstrap.rs index d7def987454..3d73fcb2c65 100644 --- a/moli-renderer-v8/src/context_bootstrap.rs +++ b/moli-renderer-v8/src/context_bootstrap.rs @@ -331,11 +331,11 @@ pub(crate) use self::events::{ construct_original_message_event, error_event_handler_arguments, event_attribute, event_backing, event_bool_attribute, event_callback_values, event_initialized, event_internal_bool_flag, event_is_dispatching, event_is_error_event, event_is_mouse_event, - event_private_value, initialize_event_object, initialize_event_object_with_type, - initialize_event_wrapper, initialize_native_security_policy_violation_event, - mark_agent_submit_event, mark_event_trusted, new_event_state, new_event_wrapper, - node_event_callback_values, set_event_composed_path, set_event_internal_flag, - set_event_private_value, set_event_trusted, submit_event_submitter_value, + event_private_value, initialize_event_object, + initialize_native_security_policy_violation_event, mark_agent_submit_event, mark_event_trusted, + new_event_state, new_event_wrapper, node_event_callback_values, set_event_composed_path, + set_event_internal_flag, set_event_private_value, set_event_trusted, + submit_event_submitter_value, }; #[cfg(test)] pub(crate) use self::file_api::drag_data_read_count_for_test; diff --git a/moli-renderer-v8/src/context_bootstrap/animation_runtime.rs b/moli-renderer-v8/src/context_bootstrap/animation_runtime.rs index 06cd2432f41..a2f9c69a6a7 100644 --- a/moli-renderer-v8/src/context_bootstrap/animation_runtime.rs +++ b/moli-renderer-v8/src/context_bootstrap/animation_runtime.rs @@ -1,5 +1,12 @@ use super::*; use crate::web_api_interfaces; +pub(super) use moli_webapi::animation::{ + ANIMATION_EFFECT_SLOT, ANIMATION_FINISH_TOKEN_SLOT, ANIMATION_FINISHED_RESOLVE_SLOT, + ANIMATION_ONFINISH_SLOT, ANIMATION_PLAY_STATE_SLOT, ANIMATION_START_TIME_SLOT, + KEYFRAME_EFFECT_KEYFRAMES_SLOT, KEYFRAME_EFFECT_TARGET_SLOT, animation_constructor_callback, + animation_effect_getter, animation_start_time_getter, keyframe_effect_constructor_callback, + require_animation_receiver, +}; use moli_webapi_declare::{WebApiFunctionTemplate, WebApiObject}; use crate::native_bridge::node_runtime_and_handle_from_object; @@ -9,39 +16,13 @@ use crate::util::{ mod element_registry; -const ANIMATION_PLAY_STATE_SLOT: &str = "__moliAnimationPlayState"; -const ANIMATION_ID_SLOT: &str = "__moliAnimationId"; -const ANIMATION_READY_SLOT: &str = "__moliAnimationReady"; -const ANIMATION_FINISHED_SLOT: &str = "__moliAnimationFinished"; -const ANIMATION_FINISHED_RESOLVE_SLOT: &str = "__moliAnimationFinishedResolve"; -const ANIMATION_PROMISE_RESOLVE_SLOT: &str = "__moliAnimationPromiseResolve"; -const ANIMATION_EFFECT_SLOT: &str = "__moliAnimationEffect"; -const ANIMATION_TIMELINE_SLOT: &str = "__moliAnimationTimeline"; -const ANIMATION_START_TIME_SLOT: &str = "__moliAnimationStartTime"; -const ANIMATION_ONFINISH_SLOT: &str = "__moliAnimationOnfinish"; -const ANIMATION_FINISH_TOKEN_SLOT: &str = "__moliAnimationFinishToken"; const ANIMATION_MICROTASK_ANIMATION_SLOT: &str = "__moliAnimationMicrotaskAnimation"; const ANIMATION_MICROTASK_TOKEN_SLOT: &str = "__moliAnimationMicrotaskToken"; const CSS_ANIMATION_TARGET_SLOT: &str = "__moliCssAnimationTarget"; -const KEYFRAME_EFFECT_TARGET_SLOT: &str = "__moliKeyframeEffectTarget"; -const KEYFRAME_EFFECT_KEYFRAMES_SLOT: &str = "__moliKeyframeEffectKeyframes"; - -#[derive(Default, WebApiObject)] -#[webapi(plain)] -struct AnimationPromiseEntryDeclaration { - #[webapi(slot = ANIMATION_PROMISE_RESOLVE_SLOT, init = "undefined")] - resolve: (), -} #[derive(WebApiFunctionTemplate)] #[webapi(interface = web_api_interfaces::Animation, enumerable)] struct AnimationPrototypeMethodsDeclaration { - #[webapi( - accessor_property, - getter = animation_id_getter_callback, - setter = animation_id_setter_callback - )] - id: (), #[webapi(method, length = 0, callback = animation_play_callback)] play: (), #[webapi(method, length = 0, callback = animation_pause_callback)] @@ -56,96 +37,6 @@ struct AnimationPrototypeMethodsDeclaration { commit_styles: (), } -#[derive(WebApiObject)] -#[webapi(interface = web_api_interfaces::Animation)] -struct AnimationObjectDeclaration<'s> { - #[webapi(slot = ANIMATION_ID_SLOT, constructor_default = "")] - id: &'static str, - #[webapi(slot = ANIMATION_PLAY_STATE_SLOT, constructor_default = "idle")] - play_state: &'static str, - #[webapi(slot = ANIMATION_EFFECT_SLOT)] - effect: v8::Local<'s, v8::Value>, - #[webapi(slot = ANIMATION_TIMELINE_SLOT)] - timeline: v8::Local<'s, v8::Value>, - #[webapi(slot = ANIMATION_START_TIME_SLOT, init = "null")] - start_time: (), - #[webapi(slot = ANIMATION_ONFINISH_SLOT, init = "null")] - onfinish: (), - #[webapi(slot = ANIMATION_FINISH_TOKEN_SLOT, constructor_default)] - finish_token: f64, - #[webapi(slot = ANIMATION_READY_SLOT)] - ready: Option>, - #[webapi(slot = ANIMATION_FINISHED_SLOT)] - finished: Option>, - #[webapi(slot = ANIMATION_FINISHED_RESOLVE_SLOT)] - finished_resolve: Option>, -} - -fn animation_id_getter_callback<'s>( - scope: &mut v8::PinScope<'s, '_>, - args: v8::FunctionCallbackArguments<'s>, - mut rv: v8::ReturnValue<'_, v8::Value>, -) { - if get_private_value(scope, args.this(), ANIMATION_PLAY_STATE_SLOT).is_none() { - throw_type_error( - scope, - "Animation.id getter called on incompatible receiver.", - ); - return; - } - let id = get_private_value(scope, args.this(), ANIMATION_ID_SLOT) - .and_then(|value| value.to_string(scope)) - .map(|value| value.to_rust_string_lossy(scope)) - .unwrap_or_default(); - if let Some(id) = v8_string(scope, &id) { - rv.set(id.into()); - } -} - -fn animation_id_setter_callback<'s>( - scope: &mut v8::PinScope<'s, '_>, - args: v8::FunctionCallbackArguments<'s>, - _rv: v8::ReturnValue<'_, v8::Value>, -) { - if get_private_value(scope, args.this(), ANIMATION_PLAY_STATE_SLOT).is_none() { - throw_type_error( - scope, - "Animation.id setter called on incompatible receiver.", - ); - return; - } - let id = match crate::webidl::convert::( - scope, - args.get(0), - crate::webidl::Context::member("Animation", "id"), - ) { - Ok(id) => id.0, - Err(error) => { - crate::webidl::throw_error(scope, &error); - return; - } - }; - if let Some(id) = v8_string(scope, &id) { - set_private_value(scope, args.this(), ANIMATION_ID_SLOT, id.into()); - } -} - -#[derive(WebApiObject)] -#[webapi(interface = web_api_interfaces::KeyframeEffect)] -struct KeyframeEffectObjectDeclaration<'s> { - #[webapi(slot = KEYFRAME_EFFECT_TARGET_SLOT)] - target: v8::Local<'s, v8::Value>, - #[webapi(slot = KEYFRAME_EFFECT_KEYFRAMES_SLOT)] - keyframes: v8::Local<'s, v8::Value>, -} - -#[derive(WebApiFunctionTemplate)] -#[webapi(interface = web_api_interfaces::KeyframeEffect, enumerable)] -struct KeyframeEffectPrototypeDeclaration { - #[webapi(method, length = 1, callback = keyframe_effect_set_keyframes_callback)] - set_keyframes: (), -} - #[derive(WebApiFunctionTemplate)] #[webapi(interface = web_api_interfaces::Element, enumerable, receiver)] struct ElementAnimationPrototypeDeclaration { @@ -164,26 +55,17 @@ struct AnimationFinishMicrotaskPayloadDeclaration<'s> { token: f64, } -#[derive(WebApiObject)] -#[webapi(plain)] -struct AnimationPromiseResolverDeclaration<'s> { - #[webapi(slot = ANIMATION_PROMISE_RESOLVE_SLOT)] - resolve: v8::Local<'s, v8::Value>, -} - pub(super) fn install_animation_template_bindings<'s>( scope: &mut v8::PinScope<'s, '_, ()>, template: v8::Local<'s, v8::FunctionTemplate>, interface_name: &str, ) { + moli_webapi::animation::install_value_template_bindings(scope, template, interface_name); let prototype = template.prototype_template(scope); match interface_name { "Animation" => { AnimationPrototypeMethodsDeclaration::initialize_prototype_template(scope, prototype); } - "KeyframeEffect" => { - KeyframeEffectPrototypeDeclaration::initialize_prototype_template(scope, prototype); - } "Element" => { ElementAnimationPrototypeDeclaration::initialize_prototype_template(scope, prototype); } @@ -191,159 +73,6 @@ pub(super) fn install_animation_template_bindings<'s>( } } -pub(super) fn animation_constructor_callback<'s>( - scope: &mut v8::PinScope<'s, '_>, - args: v8::FunctionCallbackArguments<'s>, - mut rv: v8::ReturnValue<'_, v8::Value>, -) { - if !args.is_construct_call() { - throw_type_error( - scope, - "Failed to construct 'Animation': Please use the 'new' operator.", - ); - return; - } - let effect = if args.get(0).is_null_or_undefined() { - v8::null(scope).into() - } else { - args.get(0) - }; - let timeline = if args.get(1).is_null_or_undefined() { - v8::null(scope).into() - } else { - args.get(1) - }; - initialize_animation_object(scope, args.this(), effect, timeline); - rv.set(args.this().into()); -} - -pub(super) fn keyframe_effect_constructor_callback<'s>( - scope: &mut v8::PinScope<'s, '_>, - args: v8::FunctionCallbackArguments<'s>, - mut rv: v8::ReturnValue<'_, v8::Value>, -) { - if !args.is_construct_call() { - throw_type_error( - scope, - "Failed to construct 'KeyframeEffect': Please use the 'new' operator.", - ); - return; - } - KeyframeEffectObjectDeclaration::new(args.get(0), args.get(1)) - .initialize(scope, args.this()) - .expect("KeyframeEffect declaration should initialize object"); - rv.set(args.this().into()); -} - -fn keyframe_effect_set_keyframes_callback<'s>( - scope: &mut v8::PinScope<'s, '_>, - args: v8::FunctionCallbackArguments<'s>, - mut rv: v8::ReturnValue<'_, v8::Value>, -) { - set_private_value( - scope, - args.this(), - KEYFRAME_EFFECT_KEYFRAMES_SLOT, - args.get(0), - ); - rv.set_undefined(); -} - -fn initialize_animation_object<'s>( - scope: &mut v8::PinScope<'s, '_>, - animation: v8::Local<'s, v8::Object>, - effect: v8::Local<'s, v8::Value>, - timeline: v8::Local<'s, v8::Value>, -) { - let ready = if let Some(ready_resolver) = v8::PromiseResolver::new(scope) { - let ready = ready_resolver.get_promise(scope); - let _ = ready_resolver.resolve(scope, animation.into()); - Some(ready) - } else { - None - }; - let (finished, finished_resolve) = new_animation_pending_promise(scope) - .map(|(finished, resolve)| (Some(finished), Some(resolve))) - .unwrap_or((None, None)); - AnimationObjectDeclaration::new(effect, timeline, ready, finished, finished_resolve) - .initialize(scope, animation) - .expect("Animation declaration should initialize object"); -} - -fn require_animation_receiver<'s>( - scope: &mut v8::PinScope<'s, '_>, - receiver: v8::Local<'s, v8::Object>, - member: &str, -) -> bool { - if web_api_interfaces::Animation::is_instance(scope, receiver) { - return true; - } - throw_type_error( - scope, - &format!("Animation.{member} called on incompatible receiver."), - ); - false -} - -pub(super) fn animation_play_state_getter<'s>( - scope: &mut v8::PinScope<'s, '_>, - args: v8::FunctionCallbackArguments<'s>, - mut rv: v8::ReturnValue<'_, v8::Value>, -) { - if !require_animation_receiver(scope, args.this(), "playState getter") { - return; - } - rv.set(animation_play_state_value(scope, args.this())); -} - -pub(super) fn animation_pending_getter<'s>( - scope: &mut v8::PinScope<'s, '_>, - args: v8::FunctionCallbackArguments<'s>, - mut rv: v8::ReturnValue<'_, v8::Value>, -) { - if !require_animation_receiver(scope, args.this(), "pending getter") { - return; - } - rv.set(animation_pending_value(scope)); -} - -pub(super) fn animation_ready_getter<'s>( - scope: &mut v8::PinScope<'s, '_>, - args: v8::FunctionCallbackArguments<'s>, - mut rv: v8::ReturnValue<'_, v8::Value>, -) { - if !require_animation_receiver(scope, args.this(), "ready getter") { - return; - } - rv.set(animation_ready_value(scope, args.this())); -} - -pub(super) fn animation_finished_getter<'s>( - scope: &mut v8::PinScope<'s, '_>, - args: v8::FunctionCallbackArguments<'s>, - mut rv: v8::ReturnValue<'_, v8::Value>, -) { - if !require_animation_receiver(scope, args.this(), "finished getter") { - return; - } - rv.set(animation_finished_value(scope, args.this())); -} - -pub(super) fn animation_effect_getter<'s>( - scope: &mut v8::PinScope<'s, '_>, - args: v8::FunctionCallbackArguments<'s>, - mut rv: v8::ReturnValue<'_, v8::Value>, -) { - if !require_animation_receiver(scope, args.this(), "effect getter") { - return; - } - rv.set(animation_slot_value( - scope, - args.this(), - ANIMATION_EFFECT_SLOT, - )); -} - pub(super) fn animation_effect_setter<'s>( scope: &mut v8::PinScope<'s, '_>, args: v8::FunctionCallbackArguments<'s>, @@ -356,48 +85,6 @@ pub(super) fn animation_effect_setter<'s>( rv.set_undefined(); } -pub(super) fn animation_timeline_getter<'s>( - scope: &mut v8::PinScope<'s, '_>, - args: v8::FunctionCallbackArguments<'s>, - mut rv: v8::ReturnValue<'_, v8::Value>, -) { - if !require_animation_receiver(scope, args.this(), "timeline getter") { - return; - } - rv.set(animation_slot_value( - scope, - args.this(), - ANIMATION_TIMELINE_SLOT, - )); -} - -pub(super) fn animation_timeline_setter<'s>( - scope: &mut v8::PinScope<'s, '_>, - args: v8::FunctionCallbackArguments<'s>, - mut rv: v8::ReturnValue<'_, v8::Value>, -) { - if !require_animation_receiver(scope, args.this(), "timeline setter") { - return; - } - set_animation_timeline_value(scope, args.this(), args.get(0)); - rv.set_undefined(); -} - -pub(super) fn animation_start_time_getter<'s>( - scope: &mut v8::PinScope<'s, '_>, - args: v8::FunctionCallbackArguments<'s>, - mut rv: v8::ReturnValue<'_, v8::Value>, -) { - if !require_animation_receiver(scope, args.this(), "startTime getter") { - return; - } - rv.set(animation_slot_value( - scope, - args.this(), - ANIMATION_START_TIME_SLOT, - )); -} - pub(super) fn animation_start_time_setter<'s>( scope: &mut v8::PinScope<'s, '_>, args: v8::FunctionCallbackArguments<'s>, @@ -410,33 +97,6 @@ pub(super) fn animation_start_time_setter<'s>( rv.set_undefined(); } -pub(super) fn animation_onfinish_getter<'s>( - scope: &mut v8::PinScope<'s, '_>, - args: v8::FunctionCallbackArguments<'s>, - mut rv: v8::ReturnValue<'_, v8::Value>, -) { - if !require_animation_receiver(scope, args.this(), "onfinish getter") { - return; - } - rv.set(animation_slot_value( - scope, - args.this(), - ANIMATION_ONFINISH_SLOT, - )); -} - -pub(super) fn animation_onfinish_setter<'s>( - scope: &mut v8::PinScope<'s, '_>, - args: v8::FunctionCallbackArguments<'s>, - mut rv: v8::ReturnValue<'_, v8::Value>, -) { - if !require_animation_receiver(scope, args.this(), "onfinish setter") { - return; - } - set_animation_onfinish_value(scope, args.this(), args.get(0)); - rv.set_undefined(); -} - pub(super) fn animation_play_callback<'s>( scope: &mut v8::PinScope<'s, '_>, args: v8::FunctionCallbackArguments<'s>, @@ -828,42 +488,6 @@ fn animation_finish_microtask_callback<'s>( animation_finish(scope, animation, true); } -fn animation_slot_value<'s>( - scope: &mut v8::PinScope<'s, '_>, - animation: v8::Local<'s, v8::Object>, - slot: &'static str, -) -> v8::Local<'s, v8::Value> { - get_private_value(scope, animation, slot).unwrap_or_else(|| v8::null(scope).into()) -} - -fn animation_play_state_value<'s>( - scope: &mut v8::PinScope<'s, '_>, - animation: v8::Local<'s, v8::Object>, -) -> v8::Local<'s, v8::Value> { - get_private_value(scope, animation, ANIMATION_PLAY_STATE_SLOT) - .unwrap_or_else(|| v8str(scope, "idle").into()) -} - -fn animation_pending_value<'s>(scope: &mut v8::PinScope<'s, '_>) -> v8::Local<'s, v8::Value> { - v8::Boolean::new(scope, false).into() -} - -fn animation_ready_value<'s>( - scope: &mut v8::PinScope<'s, '_>, - animation: v8::Local<'s, v8::Object>, -) -> v8::Local<'s, v8::Value> { - get_private_value(scope, animation, ANIMATION_READY_SLOT) - .unwrap_or_else(|| v8::undefined(scope).into()) -} - -fn animation_finished_value<'s>( - scope: &mut v8::PinScope<'s, '_>, - animation: v8::Local<'s, v8::Object>, -) -> v8::Local<'s, v8::Value> { - get_private_value(scope, animation, ANIMATION_FINISHED_SLOT) - .unwrap_or_else(|| v8::undefined(scope).into()) -} - fn set_animation_effect_value<'s>( scope: &mut v8::PinScope<'s, '_>, animation: v8::Local<'s, v8::Object>, @@ -882,19 +506,6 @@ fn set_animation_effect_value<'s>( } } -fn set_animation_timeline_value<'s>( - scope: &mut v8::PinScope<'s, '_>, - animation: v8::Local<'s, v8::Object>, - value: v8::Local<'s, v8::Value>, -) { - let value = if value.is_null_or_undefined() { - v8::null(scope).into() - } else { - value - }; - set_private_value(scope, animation, ANIMATION_TIMELINE_SLOT, value); -} - fn set_animation_start_time_value<'s>( scope: &mut v8::PinScope<'s, '_>, animation: v8::Local<'s, v8::Object>, @@ -913,52 +524,6 @@ fn set_animation_start_time_value<'s>( } } -fn set_animation_onfinish_value<'s>( - scope: &mut v8::PinScope<'s, '_>, - animation: v8::Local<'s, v8::Object>, - value: v8::Local<'s, v8::Value>, -) { - let value = if value.is_null_or_undefined() || value.is_function() { - value - } else { - v8::null(scope).into() - }; - set_private_value(scope, animation, ANIMATION_ONFINISH_SLOT, value); -} - -fn new_animation_pending_promise<'s>( - scope: &mut v8::PinScope<'s, '_>, -) -> Option<(v8::Local<'s, v8::Value>, v8::Local<'s, v8::Function>)> { - let entry = AnimationPromiseEntryDeclaration::default() - .bind(scope) - .expect("Animation promise entry declaration should bind"); - let executor = v8::Function::builder(animation_promise_executor_callback) - .data(entry.into()) - .length(2) - .build(scope)?; - let promise_constructor = global_constructor_object(scope, "Promise") - .and_then(|constructor| v8::Local::::try_from(constructor).ok())?; - let promise = promise_constructor.new_instance(scope, &[executor.into()])?; - let resolve = get_private_value(scope, entry, ANIMATION_PROMISE_RESOLVE_SLOT) - .and_then(|value| v8::Local::::try_from(value).ok())?; - Some((promise.into(), resolve)) -} - -fn animation_promise_executor_callback<'s>( - scope: &mut v8::PinScope<'s, '_>, - args: v8::FunctionCallbackArguments<'s>, - mut rv: v8::ReturnValue<'_, v8::Value>, -) { - let Ok(entry) = v8::Local::::try_from(args.data()) else { - rv.set_undefined(); - return; - }; - AnimationPromiseResolverDeclaration::new(args.get(0)) - .initialize(scope, entry) - .expect("Animation promise resolver declaration should initialize object"); - rv.set_undefined(); -} - fn animation_play_state<'s>( scope: &mut v8::PinScope<'s, '_>, animation: v8::Local<'s, v8::Object>, diff --git a/moli-renderer-v8/src/context_bootstrap/assets/prototype_bindings.rs b/moli-renderer-v8/src/context_bootstrap/assets/prototype_bindings.rs index 0d912fee193..3fae89098f9 100644 --- a/moli-renderer-v8/src/context_bootstrap/assets/prototype_bindings.rs +++ b/moli-renderer-v8/src/context_bootstrap/assets/prototype_bindings.rs @@ -1,10 +1,7 @@ use super::super::{ animation_runtime::{ - animation_effect_getter, animation_effect_setter, animation_finished_getter, - animation_onfinish_getter, animation_onfinish_setter, animation_pending_getter, - animation_play_state_getter, animation_ready_getter, animation_start_time_getter, - animation_start_time_setter, animation_timeline_getter, animation_timeline_setter, - install_animation_template_bindings, + animation_effect_getter, animation_effect_setter, animation_start_time_getter, + animation_start_time_setter, install_animation_template_bindings, }, broadcast_channel::install_broadcast_channel_template_bindings, constructors::{ @@ -126,18 +123,6 @@ struct HtmlDocumentTemplateAccessorsDeclaration { #[derive(WebApiFunctionTemplate)] #[webapi(interface = web_api_interfaces::Animation, enumerable)] struct AnimationTemplateAccessorsDeclaration { - #[webapi(accessor_property = "playState", getter = animation_play_state_getter)] - play_state: (), - - #[webapi(accessor_property, getter = animation_pending_getter)] - pending: (), - - #[webapi(accessor_property, getter = animation_ready_getter)] - ready: (), - - #[webapi(accessor_property, getter = animation_finished_getter)] - finished: (), - #[webapi( accessor_property, getter = animation_effect_getter, @@ -145,26 +130,12 @@ struct AnimationTemplateAccessorsDeclaration { )] effect: (), - #[webapi( - accessor_property, - getter = animation_timeline_getter, - setter = animation_timeline_setter - )] - timeline: (), - #[webapi( accessor_property = "startTime", getter = animation_start_time_getter, setter = animation_start_time_setter )] start_time: (), - - #[webapi( - accessor_property, - getter = animation_onfinish_getter, - setter = animation_onfinish_setter - )] - onfinish: (), } #[derive(WebApiFunctionTemplate)] diff --git a/moli-renderer-v8/src/context_bootstrap/canvas.rs b/moli-renderer-v8/src/context_bootstrap/canvas.rs index 453fb9e5e93..c8ca389c7c9 100644 --- a/moli-renderer-v8/src/context_bootstrap/canvas.rs +++ b/moli-renderer-v8/src/context_bootstrap/canvas.rs @@ -7,32 +7,17 @@ use crate::webidl; use moli_webapi_declare::WebApiFunctionTemplate; use std::str::FromStr; -const OFFSCREEN_CANVAS_WIDTH_SLOT: &str = "__moliOffscreenCanvasWidth"; -const OFFSCREEN_CANVAS_HEIGHT_SLOT: &str = "__moliOffscreenCanvasHeight"; -const CANVAS_CONTEXT_FILL_STYLE_SLOT: &str = "__moliCanvasContextFillStyle"; -const CANVAS_CONTEXT_FONT_SLOT: &str = "__moliCanvasContextFont"; -const CANVAS_CONTEXT_IMAGE_SMOOTHING_ENABLED_SLOT: &str = - "__moliCanvasContextImageSmoothingEnabled"; -const CANVAS_CONTEXT_IMAGE_SMOOTHING_QUALITY_SLOT: &str = - "__moliCanvasContextImageSmoothingQuality"; -const CANVAS_CONTEXT_GLOBAL_ALPHA_SLOT: &str = "__moliCanvasContextGlobalAlpha"; -const CANVAS_CONTEXT_GLOBAL_COMPOSITE_OPERATION_SLOT: &str = - "__moliCanvasContextGlobalCompositeOperation"; -const CANVAS_CONTEXT_LINE_WIDTH_SLOT: &str = "__moliCanvasContextLineWidth"; -const CANVAS_CONTEXT_LINE_CAP_SLOT: &str = "__moliCanvasContextLineCap"; -const CANVAS_CONTEXT_LINE_JOIN_SLOT: &str = "__moliCanvasContextLineJoin"; -const CANVAS_CONTEXT_MITER_LIMIT_SLOT: &str = "__moliCanvasContextMiterLimit"; -const CANVAS_CONTEXT_LINE_DASH_OFFSET_SLOT: &str = "__moliCanvasContextLineDashOffset"; -const CANVAS_CONTEXT_STROKE_STYLE_SLOT: &str = "__moliCanvasContextStrokeStyle"; - -pub(crate) const DEFAULT_GLOBAL_ALPHA: f64 = 1.0; -pub(crate) const DEFAULT_GLOBAL_COMPOSITE_OPERATION: &str = "source-over"; -pub(crate) const DEFAULT_LINE_WIDTH: f64 = 1.0; -pub(crate) const DEFAULT_LINE_CAP: &str = "butt"; -pub(crate) const DEFAULT_LINE_JOIN: &str = "miter"; -pub(crate) const DEFAULT_MITER_LIMIT: f64 = 10.0; -pub(crate) const DEFAULT_LINE_DASH_OFFSET: f64 = 0.0; -pub(crate) const DEFAULT_STROKE_STYLE: &str = "#000000"; +pub(crate) use moli_webapi::canvas_context_values::{ + CANVAS_CONTEXT_FILL_STYLE_SLOT, CANVAS_CONTEXT_FONT_SLOT, CANVAS_CONTEXT_GLOBAL_ALPHA_SLOT, + CANVAS_CONTEXT_GLOBAL_COMPOSITE_OPERATION_SLOT, CANVAS_CONTEXT_IMAGE_SMOOTHING_ENABLED_SLOT, + CANVAS_CONTEXT_IMAGE_SMOOTHING_QUALITY_SLOT, CANVAS_CONTEXT_LINE_CAP_SLOT, + CANVAS_CONTEXT_LINE_DASH_OFFSET_SLOT, CANVAS_CONTEXT_LINE_JOIN_SLOT, + CANVAS_CONTEXT_LINE_WIDTH_SLOT, CANVAS_CONTEXT_MITER_LIMIT_SLOT, + CANVAS_CONTEXT_STROKE_STYLE_SLOT, DEFAULT_GLOBAL_ALPHA, DEFAULT_GLOBAL_COMPOSITE_OPERATION, + DEFAULT_LINE_CAP, DEFAULT_LINE_DASH_OFFSET, DEFAULT_LINE_JOIN, DEFAULT_LINE_WIDTH, + DEFAULT_MITER_LIMIT, DEFAULT_STROKE_STYLE, OFFSCREEN_CANVAS_HEIGHT_SLOT, + OFFSCREEN_CANVAS_WIDTH_SLOT, +}; /// Composite operations recognised by the HTML Canvas 2D spec. /// diff --git a/moli-renderer-v8/src/context_bootstrap/canvas/backing_store.rs b/moli-renderer-v8/src/context_bootstrap/canvas/backing_store.rs index 49b01cb6331..b529fc3c1a7 100644 --- a/moli-renderer-v8/src/context_bootstrap/canvas/backing_store.rs +++ b/moli-renderer-v8/src/context_bootstrap/canvas/backing_store.rs @@ -9,7 +9,7 @@ use crate::{ use moli_canvas::{byte_len as canvas_byte_len, encode_data_url}; use moli_webapi_declare::WebApiObject; -const CANVAS_BACKING_STORE_SLOT: &str = "__moliCanvasBackingStore"; +use moli_webapi::canvas_context_values::CANVAS_BACKING_STORE_SLOT; const CANVAS_OWNER_SLOT: &str = "__moliCanvasOwner"; const CANVAS_HAS_CONTEXT_SLOT: &str = "__moliCanvasHasContext"; const CANVAS_2D_CONTEXT_SLOT: &str = "__moliCanvas2DContext"; diff --git a/moli-renderer-v8/src/context_bootstrap/canvas/constructors.rs b/moli-renderer-v8/src/context_bootstrap/canvas/constructors.rs index bf1c38860b3..aad94c7cc1f 100644 --- a/moli-renderer-v8/src/context_bootstrap/canvas/constructors.rs +++ b/moli-renderer-v8/src/context_bootstrap/canvas/constructors.rs @@ -1,51 +1,4 @@ -use super::helpers::init_canvas_like_context_object; -use super::offscreen::init_offscreen_canvas_object; -use super::*; -use crate::webidl; - -#[derive(webidl::WebIdlArgs)] -#[webidl(prefix = "OffscreenCanvas")] -struct OffscreenCanvasConstructorArgs { - #[webidl(required, converter = "enforce_range_unsigned_long")] - width: u32, - #[webidl(required, converter = "enforce_range_unsigned_long")] - height: u32, -} - -pub(crate) fn offscreen_canvas_constructor_callback<'s>( - scope: &mut v8::PinScope<'s, '_>, - args: v8::FunctionCallbackArguments<'s>, - mut rv: v8::ReturnValue<'_, v8::Value>, -) { - if !args.is_construct_call() { - throw_type_error( - scope, - "Failed to construct 'OffscreenCanvas': Please use the 'new' operator.", - ); - return; - } - - let Some(parsed) = webidl::parse_args::(scope, &args) else { - return; - }; - init_offscreen_canvas_object(scope, args.this(), parsed.width, parsed.height); - rv.set(args.this().into()); -} - -pub(crate) fn canvas_rendering_context_2d_constructor_callback<'s>( - scope: &mut v8::PinScope<'s, '_>, - args: v8::FunctionCallbackArguments<'s>, - mut rv: v8::ReturnValue<'_, v8::Value>, -) { - init_canvas_like_context_object(scope, args.this()); - rv.set(args.this().into()); -} - -pub(crate) fn offscreen_canvas_rendering_context_2d_constructor_callback<'s>( - scope: &mut v8::PinScope<'s, '_>, - args: v8::FunctionCallbackArguments<'s>, - mut rv: v8::ReturnValue<'_, v8::Value>, -) { - init_canvas_like_context_object(scope, args.this()); - rv.set(args.this().into()); -} +pub(crate) use moli_webapi::canvas_context_values::{ + canvas_rendering_context_2d_constructor_callback, offscreen_canvas_constructor_callback, + offscreen_canvas_rendering_context_2d_constructor_callback, +}; diff --git a/moli-renderer-v8/src/context_bootstrap/canvas/helpers.rs b/moli-renderer-v8/src/context_bootstrap/canvas/helpers.rs index 270d0e83feb..58bfffa263e 100644 --- a/moli-renderer-v8/src/context_bootstrap/canvas/helpers.rs +++ b/moli-renderer-v8/src/context_bootstrap/canvas/helpers.rs @@ -1,60 +1,4 @@ -use super::*; use crate::webidl; -use moli_canvas::{DEFAULT_FILL_STYLE, DEFAULT_FONT}; -use moli_webapi_declare::WebApiObject; - -#[derive(WebApiObject)] -#[webapi(fragment, prototype = "CanvasRenderingContext2D")] -struct CanvasLikeContextObjectDeclaration { - #[webapi( - slot = CANVAS_CONTEXT_FILL_STYLE_SLOT, - constructor_default = DEFAULT_FILL_STYLE - )] - fill_style: &'static str, - #[webapi(slot = CANVAS_CONTEXT_FONT_SLOT, constructor_default = DEFAULT_FONT)] - font: &'static str, - #[webapi( - slot = CANVAS_CONTEXT_IMAGE_SMOOTHING_ENABLED_SLOT, - constructor_default = true - )] - image_smoothing_enabled: bool, - #[webapi( - slot = CANVAS_CONTEXT_IMAGE_SMOOTHING_QUALITY_SLOT, - constructor_default = "low" - )] - image_smoothing_quality: &'static str, - #[webapi( - slot = CANVAS_CONTEXT_GLOBAL_ALPHA_SLOT, - constructor_default = super::DEFAULT_GLOBAL_ALPHA - )] - global_alpha: f64, - #[webapi( - slot = CANVAS_CONTEXT_GLOBAL_COMPOSITE_OPERATION_SLOT, - constructor_default = super::DEFAULT_GLOBAL_COMPOSITE_OPERATION - )] - global_composite_operation: &'static str, - #[webapi(slot = CANVAS_CONTEXT_LINE_WIDTH_SLOT, constructor_default = super::DEFAULT_LINE_WIDTH)] - line_width: f64, - #[webapi(slot = CANVAS_CONTEXT_LINE_CAP_SLOT, constructor_default = super::DEFAULT_LINE_CAP)] - line_cap: &'static str, - #[webapi(slot = CANVAS_CONTEXT_LINE_JOIN_SLOT, constructor_default = super::DEFAULT_LINE_JOIN)] - line_join: &'static str, - #[webapi( - slot = CANVAS_CONTEXT_MITER_LIMIT_SLOT, - constructor_default = super::DEFAULT_MITER_LIMIT - )] - miter_limit: f64, - #[webapi( - slot = CANVAS_CONTEXT_LINE_DASH_OFFSET_SLOT, - constructor_default = super::DEFAULT_LINE_DASH_OFFSET - )] - line_dash_offset: f64, - #[webapi( - slot = CANVAS_CONTEXT_STROKE_STYLE_SLOT, - constructor_default = super::DEFAULT_STROKE_STYLE - )] - stroke_style: &'static str, -} pub(super) fn canvas_unrestricted_double_arg<'s>( scope: &mut v8::PinScope<'s, '_>, @@ -76,11 +20,4 @@ pub(super) fn canonical_canvas_fill_style(raw: &str) -> Option { moli_canvas::canonicalize_fill_style(raw) } -pub(super) fn init_canvas_like_context_object<'s>( - scope: &mut v8::PinScope<'s, '_>, - object: v8::Local<'s, v8::Object>, -) { - CanvasLikeContextObjectDeclaration::new() - .initialize(scope, object) - .expect("canvas context declaration should initialize object"); -} +pub(super) use moli_webapi::canvas_context_values::init_canvas_like_context_object; diff --git a/moli-renderer-v8/src/context_bootstrap/canvas/offscreen.rs b/moli-renderer-v8/src/context_bootstrap/canvas/offscreen.rs index b09b626744c..830aa1ab1f1 100644 --- a/moli-renderer-v8/src/context_bootstrap/canvas/offscreen.rs +++ b/moli-renderer-v8/src/context_bootstrap/canvas/offscreen.rs @@ -11,20 +11,11 @@ use crate::util::{ use crate::web_api_interfaces; use crate::webidl; use moli_webapi::webgl::{build_webgl_context_object, build_webgl2_context_object}; -use moli_webapi_declare::{WebApiFunctionTemplate, WebApiObject}; +use moli_webapi_declare::WebApiFunctionTemplate; const OFFSCREEN_CANVAS_CONTEXT_SLOT: &str = "__moliOffscreenCanvasContext"; const OFFSCREEN_CANVAS_CONTEXT_KIND_SLOT: &str = "__moliOffscreenCanvasContextKind"; -#[derive(WebApiObject)] -#[webapi(interface = web_api_interfaces::OffscreenCanvas)] -struct OffscreenCanvasObjectDeclaration { - #[webapi(slot = OFFSCREEN_CANVAS_WIDTH_SLOT)] - width: f64, - #[webapi(slot = OFFSCREEN_CANVAS_HEIGHT_SLOT)] - height: f64, -} - #[derive(WebApiFunctionTemplate)] #[webapi(interface = web_api_interfaces::OffscreenCanvas, receiver)] struct OffscreenCanvasPrototypeAccessorsDeclaration { @@ -242,15 +233,3 @@ pub(crate) fn offscreen_canvas_transfer_to_image_bitmap_callback<'s>( const OFFSCREEN_CANVAS_ATTRIBUTE_SLOTS: &[&str] = &[OFFSCREEN_CANVAS_WIDTH_SLOT, OFFSCREEN_CANVAS_HEIGHT_SLOT]; - -pub(super) fn init_offscreen_canvas_object<'s>( - scope: &mut v8::PinScope<'s, '_>, - object: v8::Local<'s, v8::Object>, - width: u32, - height: u32, -) { - OffscreenCanvasObjectDeclaration::new(width as f64, height as f64) - .bind_into(scope, object) - .expect("OffscreenCanvas declaration should initialize object"); - reset_canvas_like_backing_store(scope, object); -} diff --git a/moli-renderer-v8/src/context_bootstrap/events.rs b/moli-renderer-v8/src/context_bootstrap/events.rs index 30e6e34a6be..76ff34b9ae0 100644 --- a/moli-renderer-v8/src/context_bootstrap/events.rs +++ b/moli-renderer-v8/src/context_bootstrap/events.rs @@ -116,8 +116,8 @@ pub(crate) use base::{ EVENT_DISPATCHING_SLOT, EVENT_PASSIVE_SLOT, EVENT_STOP_IMMEDIATE_PROPAGATION_SLOT, EVENT_STOP_PROPAGATION_SLOT, clear_event_composed_path, define_event_property, event_backing, event_initialized, event_internal_bool_flag, event_is_dispatching, initialize_event_object, - initialize_event_object_with_type, mark_event_trusted, reinitialize_event_object, - set_event_composed_path, set_event_internal_flag, set_event_trusted, + mark_event_trusted, reinitialize_event_object, set_event_composed_path, + set_event_internal_flag, set_event_trusted, }; pub(crate) fn event_is_error_event<'s>( diff --git a/moli-renderer-v8/src/context_bootstrap/events/subclasses.rs b/moli-renderer-v8/src/context_bootstrap/events/subclasses.rs index c9726eae7b0..61d6a00c4d5 100644 --- a/moli-renderer-v8/src/context_bootstrap/events/subclasses.rs +++ b/moli-renderer-v8/src/context_bootstrap/events/subclasses.rs @@ -7,7 +7,6 @@ mod constructor; mod data; mod input; mod keyboard; -mod navigation_init; mod pointer; mod security_policy; 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 16554d0cd9c..dec7724f13e 100644 --- a/moli-renderer-v8/src/context_bootstrap/events/subclasses/constructor.rs +++ b/moli-renderer-v8/src/context_bootstrap/events/subclasses/constructor.rs @@ -7,8 +7,6 @@ enum SubclassInit<'s> { Pointing(pointer::PointerEventInitPayload<'s>), Interaction(input::InteractionEventInit<'s>), Keyboard(keyboard::KeyboardEventInit<'s>), - CurrentEntry(navigation_init::NavigationCurrentEntryChangeEventInitMembers<'s>), - Navigate(navigation_init::NavigateEventInitMembers<'s>), } impl<'s> SubclassInit<'s> { @@ -36,12 +34,6 @@ impl<'s> SubclassInit<'s> { EventSubclassKind::KeyboardEvent => { Self::Keyboard(keyboard::parse_keyboard_event_init(scope, args)?) } - EventSubclassKind::NavigationCurrentEntryChangeEvent => Self::CurrentEntry( - navigation_init::parse_current_entry_change_event_init(scope, args)?, - ), - EventSubclassKind::NavigateEvent => { - Self::Navigate(navigation_init::parse_navigate_event_init(scope, args)?) - } _ => unreachable!("value event templates are constructed in moli-webapi"), }) } @@ -52,8 +44,6 @@ impl<'s> SubclassInit<'s> { Self::Pointing(init) => init.event_flags(), Self::Interaction(init) => init.event_flags(), Self::Keyboard(init) => init.event_flags(), - Self::CurrentEntry(init) => init.event_flags(), - Self::Navigate(init) => init.event_flags(), } } @@ -67,10 +57,6 @@ impl<'s> SubclassInit<'s> { Self::Pointing(init) => init.initialize(scope, event), Self::Interaction(init) => return init.initialize(scope, event), Self::Keyboard(init) => keyboard::initialize_keyboard_event(scope, event, init), - Self::CurrentEntry(init) => { - data::initialize_navigation_current_entry_change_event(scope, event, init) - } - Self::Navigate(init) => data::initialize_navigate_event(scope, event, init), } true } 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 7b61678e20c..8d852839ee1 100644 --- a/moli-renderer-v8/src/context_bootstrap/events/subclasses/data.rs +++ b/moli-renderer-v8/src/context_bootstrap/events/subclasses/data.rs @@ -20,9 +20,8 @@ use crate::web_api_interfaces; use crate::webidl; use moli_webapi_declare::WebApiObject; use url::Url; -use webidl::WebIdlDictionarySerialize; -const NAVIGATE_EVENT_SYNTHETIC_SLOT: &str = "__lmNavigateEventSynthetic"; +use moli_webapi::events::subclasses::NAVIGATE_EVENT_SYNTHETIC_SLOT; const NAVIGATE_EVENT_INTERCEPTED_SLOT: &str = "__lmNavigateEventIntercepted"; const NAVIGATION_DESTINATION_STATE_SLOT: &str = "__lmNavigationDestinationState"; const NAVIGATE_EVENT_PRECOMMIT_SEEN_SLOT: &str = "__lmNavigateEventPrecommitSeen"; @@ -131,38 +130,6 @@ struct NavigateEventMethodsDeclaration { scroll: (), } -pub(super) fn initialize_navigation_current_entry_change_event<'s>( - scope: &mut v8::PinScope<'s, '_>, - event: v8::Local<'s, v8::Object>, - init: super::navigation_init::NavigationCurrentEntryChangeEventInitMembers<'s>, -) { - init.initialize_snapshot(scope, event) - .expect("current entry event state"); -} - -pub(super) fn initialize_navigate_event<'s>( - scope: &mut v8::PinScope<'s, '_>, - event: v8::Local<'s, v8::Object>, - init: super::navigation_init::NavigateEventInitMembers<'s>, -) { - init.initialize_snapshot(scope, event) - .expect("NavigateEvent state"); - define_navigate_event_internal_flag(scope, event, true); -} - -fn define_navigate_event_internal_flag( - scope: &mut v8::PinScope<'_, '_>, - event: v8::Local<'_, v8::Object>, - synthetic: bool, -) { - crate::context_bootstrap::set_event_private_value( - scope, - event, - NAVIGATE_EVENT_SYNTHETIC_SLOT, - v8::Boolean::new(scope, synthetic).into(), - ); -} - fn navigate_event_private_value<'s>( scope: &mut v8::PinScope<'s, '_>, event: v8::Local<'s, v8::Object>, diff --git a/moli-renderer-v8/src/context_bootstrap/file_api/file_reader_sync.rs b/moli-renderer-v8/src/context_bootstrap/file_api/file_reader_sync.rs index efe3e47d6fa..3f5dd8b0f7b 100644 --- a/moli-renderer-v8/src/context_bootstrap/file_api/file_reader_sync.rs +++ b/moli-renderer-v8/src/context_bootstrap/file_api/file_reader_sync.rs @@ -2,11 +2,8 @@ use super::*; use crate::web_api_interfaces; use crate::webidl; use moli_file_api::{file_reader_binary_string, file_reader_data_url, file_reader_text}; -use moli_webapi_declare::{WebApiFunctionTemplate, WebApiObject}; - -#[derive(Default, WebApiObject)] -#[webapi(interface = web_api_interfaces::FileReaderSync)] -struct FileReaderSyncObjectDeclaration {} +pub(in crate::context_bootstrap) use moli_webapi::constructors::file_reader_sync_constructor_callback; +use moli_webapi_declare::WebApiFunctionTemplate; #[derive(WebApiFunctionTemplate)] #[webapi(interface = web_api_interfaces::FileReaderSync, enumerable, receiver)] @@ -54,24 +51,6 @@ struct FileReaderSyncReadAsTextArgs<'s> { encoding: Option, } -pub(in crate::context_bootstrap) fn file_reader_sync_constructor_callback<'s>( - scope: &mut v8::PinScope<'s, '_>, - args: v8::FunctionCallbackArguments<'s>, - mut rv: v8::ReturnValue<'_, v8::Value>, -) { - if !args.is_construct_call() { - throw_type_error( - scope, - "Failed to construct 'FileReaderSync': Please use the 'new' operator.", - ); - return; - } - FileReaderSyncObjectDeclaration::default() - .initialize(scope, args.this()) - .expect("FileReaderSync declaration should initialize"); - rv.set(args.this().into()); -} - pub(super) fn install_file_reader_sync_template_bindings<'s>( scope: &mut v8::PinScope<'s, '_, ()>, template: v8::Local<'s, v8::FunctionTemplate>, diff --git a/moli-renderer-v8/src/context_bootstrap/idle_detection.rs b/moli-renderer-v8/src/context_bootstrap/idle_detection.rs index 0837ae69afb..991c3ed52b6 100644 --- a/moli-renderer-v8/src/context_bootstrap/idle_detection.rs +++ b/moli-renderer-v8/src/context_bootstrap/idle_detection.rs @@ -1,7 +1,6 @@ use super::{ - SIMPLE_EVENT_TARGET_LISTENERS_SLOT, dispatch_simple_event_target_event, - global_constructor_object, simple_event_target_handler_getter_callback, - simple_event_target_handler_setter_callback, + dispatch_simple_event_target_event, global_constructor_object, + simple_event_target_handler_getter_callback, simple_event_target_handler_setter_callback, }; use crate::web_api_interfaces; use crate::{ @@ -13,13 +12,13 @@ use crate::{ webidl, }; use moli_v8_util::reject_promise_with_type_error as reject_type_error; -use moli_webapi_declare::{WebApiFunctionTemplate, WebApiObject}; +pub(in crate::context_bootstrap) use moli_webapi::idle_detector_values::idle_detector_constructor_callback; +use moli_webapi::idle_detector_values::{ + IDLE_DETECTOR_ABORT_ALGORITHM_SLOT, IDLE_DETECTOR_ABORT_SIGNAL_SLOT, + IDLE_DETECTOR_SCREEN_UNLOCKED_SLOT, IDLE_DETECTOR_STARTED_SLOT, IDLE_DETECTOR_USER_ACTIVE_SLOT, +}; +use moli_webapi_declare::WebApiFunctionTemplate; -const IDLE_DETECTOR_STARTED_SLOT: &str = "__lmIdleDetectorStarted"; -const IDLE_DETECTOR_USER_ACTIVE_SLOT: &str = "__lmIdleDetectorUserActive"; -const IDLE_DETECTOR_SCREEN_UNLOCKED_SLOT: &str = "__lmIdleDetectorScreenUnlocked"; -const IDLE_DETECTOR_ABORT_SIGNAL_SLOT: &str = "__lmIdleDetectorAbortSignal"; -const IDLE_DETECTOR_ABORT_ALGORITHM_SLOT: &str = "__lmIdleDetectorAbortAlgorithm"; const IDLE_DETECTOR_REGISTRY_SLOT: &str = "__lmIdleDetectorRegistry"; const MINIMUM_IDLE_THRESHOLD_MS: u32 = 60_000; const ACTUAL_IDLE_STATE: crate::protocol_types::EmulatedIdleOverride = @@ -28,28 +27,6 @@ const ACTUAL_IDLE_STATE: crate::protocol_types::EmulatedIdleOverride = is_screen_unlocked: true, }; -#[derive(WebApiObject)] -#[webapi(interface = web_api_interfaces::IdleDetector)] -struct IdleDetectorObjectDeclaration { - #[webapi(slot = IDLE_DETECTOR_STARTED_SLOT)] - started: bool, - - #[webapi(slot = IDLE_DETECTOR_USER_ACTIVE_SLOT)] - is_user_active: bool, - - #[webapi(slot = IDLE_DETECTOR_SCREEN_UNLOCKED_SLOT)] - is_screen_unlocked: bool, - - #[webapi(slot = SIMPLE_EVENT_TARGET_LISTENERS_SLOT, init = "null_object")] - event_listeners: (), - - #[webapi(slot = IDLE_DETECTOR_ABORT_SIGNAL_SLOT, init = "null")] - abort_signal: (), - - #[webapi(slot = IDLE_DETECTOR_ABORT_ALGORITHM_SLOT, init = "null")] - abort_algorithm: (), -} - #[derive(WebApiFunctionTemplate)] #[webapi(interface = web_api_interfaces::IdleDetector)] struct IdleDetectorPrototypeDeclaration { @@ -94,30 +71,6 @@ struct IdleDetectorConstructorDeclaration { request_permission: (), } -pub(in crate::context_bootstrap) fn idle_detector_constructor_callback<'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, - "Failed to construct 'IdleDetector': Please use the 'new' operator.", - ); - return; - } - - let detector = args.this(); - if IdleDetectorObjectDeclaration::new(false, true, true) - .initialize(scope, detector) - .is_err() - { - rv.set_undefined(); - return; - } - rv.set(detector.into()); -} - pub(in crate::context_bootstrap) fn install_idle_detector_template_bindings<'s>( scope: &mut v8::PinScope<'s, '_, ()>, template: v8::Local<'s, v8::FunctionTemplate>, diff --git a/moli-renderer-v8/src/context_bootstrap/media_cues.rs b/moli-renderer-v8/src/context_bootstrap/media_cues.rs index 96f81cb59a9..a87d19dbfc0 100644 --- a/moli-renderer-v8/src/context_bootstrap/media_cues.rs +++ b/moli-renderer-v8/src/context_bootstrap/media_cues.rs @@ -1,32 +1,25 @@ +pub(super) use moli_webapi::media_cue_values::vtt_cue_constructor_callback; +pub(crate) use moli_webapi::media_cue_values::{ + TEXT_TRACK_CUE_ALIGN_SLOT, TEXT_TRACK_CUE_END_TIME_SLOT, TEXT_TRACK_CUE_ID_SLOT, + TEXT_TRACK_CUE_LINE_SLOT, TEXT_TRACK_CUE_ONENTER_SLOT, TEXT_TRACK_CUE_ONEXIT_SLOT, + TEXT_TRACK_CUE_PAUSE_ON_EXIT_SLOT, TEXT_TRACK_CUE_POSITION_SLOT, TEXT_TRACK_CUE_SIZE_SLOT, + TEXT_TRACK_CUE_SNAP_TO_LINES_SLOT, TEXT_TRACK_CUE_START_TIME_SLOT, TEXT_TRACK_CUE_TEXT_SLOT, + TEXT_TRACK_CUE_TRACK_SLOT, TEXT_TRACK_CUE_VERTICAL_SLOT, +}; pub(crate) use moli_webapi::media_error::{ media_error_constructor_callback, new_media_error_value, }; use super::super::util::{throw_type_error, v8_string}; use super::context_host_ptr_from_global_bridge; -use super::{initialize_simple_event_target, simple_object_event_set_handler}; +use super::simple_object_event_set_handler; use crate::document_runtime::DomHandle; use crate::native_bridge::PageScriptHost; use crate::native_bridge::throw_dom_exception; use crate::util::{get_private_value, set_private_value, v8str}; use crate::web_api_interfaces; use crate::webidl; -use moli_webapi_declare::{WebApiFunctionTemplate, WebApiObject}; - -pub(crate) const TEXT_TRACK_CUE_TRACK_SLOT: &str = "__moliTextTrackCueTrack"; -const TEXT_TRACK_CUE_START_TIME_SLOT: &str = "__moliTextTrackCueStartTime"; -const TEXT_TRACK_CUE_END_TIME_SLOT: &str = "__moliTextTrackCueEndTime"; -const TEXT_TRACK_CUE_ID_SLOT: &str = "__moliTextTrackCueId"; -const TEXT_TRACK_CUE_PAUSE_ON_EXIT_SLOT: &str = "__moliTextTrackCuePauseOnExit"; -const TEXT_TRACK_CUE_VERTICAL_SLOT: &str = "__moliTextTrackCueVertical"; -const TEXT_TRACK_CUE_SNAP_TO_LINES_SLOT: &str = "__moliTextTrackCueSnapToLines"; -const TEXT_TRACK_CUE_LINE_SLOT: &str = "__moliTextTrackCueLine"; -const TEXT_TRACK_CUE_POSITION_SLOT: &str = "__moliTextTrackCuePosition"; -const TEXT_TRACK_CUE_SIZE_SLOT: &str = "__moliTextTrackCueSize"; -const TEXT_TRACK_CUE_ALIGN_SLOT: &str = "__moliTextTrackCueAlign"; -const TEXT_TRACK_CUE_ONENTER_SLOT: &str = "__moliTextTrackCueOnEnter"; -const TEXT_TRACK_CUE_ONEXIT_SLOT: &str = "__moliTextTrackCueOnExit"; -const TEXT_TRACK_CUE_TEXT_SLOT: &str = "__moliTextTrackCueText"; +use moli_webapi_declare::WebApiFunctionTemplate; pub(crate) fn text_track_cue_times<'s>( scope: &mut v8::PinScope<'s, '_>, @@ -61,63 +54,6 @@ pub(crate) fn text_track_cue_id<'s>( .map(|value| value.to_rust_string_lossy(scope)) } -#[derive(webidl::WebIdlArgs)] -#[webidl(prefix = "VTTCue")] -struct VttCueConstructorArgs { - #[webidl(required, name = "startTime", converter = "double")] - start_time: f64, - #[webidl(required, name = "endTime", converter = "double")] - end_time: f64, - #[webidl(required)] - text: String, -} - -#[derive(WebApiObject)] -#[webapi(interface = web_api_interfaces::VTTCue)] -struct VttCuePrivateStateDeclaration { - #[webapi(slot = TEXT_TRACK_CUE_START_TIME_SLOT)] - _start_time: f64, - - #[webapi(slot = TEXT_TRACK_CUE_END_TIME_SLOT)] - _end_time: f64, - - #[webapi(slot = TEXT_TRACK_CUE_ID_SLOT, constructor_default = "")] - _id: &'static str, - - #[webapi(slot = TEXT_TRACK_CUE_PAUSE_ON_EXIT_SLOT, constructor_default = false)] - _pause_on_exit: bool, - - #[webapi(slot = TEXT_TRACK_CUE_VERTICAL_SLOT, constructor_default = "")] - _vertical: &'static str, - - #[webapi(slot = TEXT_TRACK_CUE_SNAP_TO_LINES_SLOT, constructor_default = true)] - _snap_to_lines: bool, - - #[webapi(slot = TEXT_TRACK_CUE_LINE_SLOT, constructor_default = "auto")] - _line: &'static str, - - #[webapi(slot = TEXT_TRACK_CUE_POSITION_SLOT, constructor_default = "auto")] - _position: &'static str, - - #[webapi(slot = TEXT_TRACK_CUE_SIZE_SLOT, constructor_default = 100.0)] - _size: f64, - - #[webapi(slot = TEXT_TRACK_CUE_ALIGN_SLOT, constructor_default = "center")] - _align: &'static str, - - #[webapi(slot = TEXT_TRACK_CUE_ONENTER_SLOT, init = "null")] - _onenter_slot: (), - - #[webapi(slot = TEXT_TRACK_CUE_ONEXIT_SLOT, init = "null")] - _onexit_slot: (), - - #[webapi(slot = TEXT_TRACK_CUE_TRACK_SLOT, init = "null")] - _track_slot: (), - - #[webapi(slot = TEXT_TRACK_CUE_TEXT_SLOT)] - text: String, -} - #[derive(WebApiFunctionTemplate)] #[webapi(interface = web_api_interfaces::TextTrackCue, enumerable)] struct TextTrackCueTemplateDeclaration { @@ -239,31 +175,6 @@ pub(super) fn text_track_cue_constructor_callback<'s>( ); } -pub(super) fn vtt_cue_constructor_callback<'s>( - scope: &mut v8::PinScope<'s, '_>, - args: v8::FunctionCallbackArguments<'s>, - mut rv: v8::ReturnValue<'_, v8::Value>, -) { - if !args.is_construct_call() { - throw_type_error( - scope, - "Failed to construct 'VTTCue': Please use the 'new' operator.", - ); - return; - } - - let Some(parsed) = webidl::parse_args::(scope, &args) else { - return; - }; - - initialize_simple_event_target(scope, args.this()); - VttCuePrivateStateDeclaration::new(parsed.start_time, parsed.end_time, parsed.text) - .initialize(scope, args.this()) - .expect("VTTCue private state declaration should initialize"); - - rv.set(args.this().into()); -} - pub(crate) fn set_text_track_cue_track<'s>( scope: &mut v8::PinScope<'s, '_>, cue: v8::Local<'s, v8::Object>, diff --git a/moli-renderer-v8/src/dom_parser.rs b/moli-renderer-v8/src/dom_parser.rs index 8df9bc62f5a..d796dae42fc 100644 --- a/moli-renderer-v8/src/dom_parser.rs +++ b/moli-renderer-v8/src/dom_parser.rs @@ -18,7 +18,7 @@ use super::{ }; pub(crate) const DOM_PARSER_FOREIGN_NODE_SLOT: &str = "__moliDomParserForeignNode"; -const DOM_PARSER_CONSTRUCTION_REALM_SLOT: &str = "__moliDomParserConstructionRealm"; +use moli_webapi::dom_parser_values::DOM_PARSER_CONSTRUCTION_REALM_SLOT; const HTML_NAMESPACE: &str = "http://www.w3.org/1999/xhtml"; const PARSER_ERROR_STYLE: &str = "display: block; white-space: pre; border: 2px solid #c77; padding: 0 1em 0 1em; margin: 1em; background-color: #fdd; color: black"; const PARSER_ERROR_DETAIL_STYLE: &str = "font-family:monospace;font-size:12px"; @@ -110,27 +110,7 @@ struct DomParserPrototypeMethodsDeclaration { parse_from_string: (), } -pub(super) fn dom_parser_constructor_callback( - scope: &mut v8::PinScope<'_, '_>, - args: v8::FunctionCallbackArguments<'_>, - mut rv: v8::ReturnValue<'_, v8::Value>, -) { - if !args.is_construct_call() { - throw_type_error(scope, "DOMParser constructor must be called with new"); - return; - } - // The constructor's Window is independent of newTarget.prototype. Keep - // a V8-traced creation-Realm witness, not a native persistent Context root - // or a WindowProxy that can be rebound to another Window on navigation. - let realm = crate::util::new_null_prototype_object(scope); - crate::util::set_private_value( - scope, - args.this(), - DOM_PARSER_CONSTRUCTION_REALM_SLOT, - realm.into(), - ); - rv.set(args.this().into()); -} +pub(super) use moli_webapi::dom_parser_values::dom_parser_constructor_callback; pub(super) fn dom_parser_parse_from_string_callback<'s>( scope: &mut v8::PinScope<'s, '_>, diff --git a/moli-renderer-v8/src/worker/global_scope/extendable_events.rs b/moli-renderer-v8/src/worker/global_scope/extendable_events.rs index 9ded212dbfd..ad26b1dabd5 100644 --- a/moli-renderer-v8/src/worker/global_scope/extendable_events.rs +++ b/moli-renderer-v8/src/worker/global_scope/extendable_events.rs @@ -1,4 +1,7 @@ //! Service Worker extendable events and their pending dispatch state. +use moli_webapi::events::service_worker::{ + extendable_event_constructor_callback, extendable_message_event_constructor_callback, +}; use super::*; @@ -35,35 +38,6 @@ struct ExtendableMessageEventConstructorGlobalDeclaration<'scope> { extendable_message_event: v8::Local<'scope, v8::Function>, } -#[derive(WebApiObject)] -#[webapi(interface = web_api_interfaces::ExtendableEvent, prototype = "Object")] -struct ExtendableEventStateDeclaration { - #[webapi(data_property, enumerable)] - composed: bool, -} - -#[derive(WebApiObject)] -#[webapi( - interface = web_api_interfaces::ExtendableMessageEvent, - prototype = "Object" -)] -struct ExtendableMessageEventStateDeclaration<'scope> { - #[webapi(data_property, enumerable)] - data: v8::Local<'scope, v8::Value>, - - #[webapi(data_property, enumerable)] - origin: String, - - #[webapi(data_property = "lastEventId", enumerable)] - last_event_id: String, - - #[webapi(data_property, enumerable)] - source: v8::Local<'scope, v8::Value>, - - #[webapi(data_property, enumerable)] - ports: v8::Local<'scope, v8::Array>, -} - pub(in crate::worker) struct PendingServiceWorkerLifecycleEvent { pub(in crate::worker) completion: ServiceWorkerLifecycleCompletion, pub(in crate::worker) pending_wait_until_count: usize, @@ -218,350 +192,3 @@ pub(super) fn install_service_worker_extendable_event_constructors<'s>( Ok(()) } - -fn extendable_event_constructor_callback<'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, - "Failed to construct 'ExtendableEvent': Please use the 'new' operator.", - ); - return; - } - let Some(event_type) = extendable_event_type_argument(scope, &args, "ExtendableEvent") else { - return; - }; - let Some((bubbles, cancelable, composed)) = - extendable_event_init_flags(scope, &args, "ExtendableEvent") - else { - return; - }; - initialize_extendable_event_object( - scope, - args.this(), - &event_type, - bubbles, - cancelable, - composed, - ); - rv.set(args.this().into()); -} - -fn extendable_message_event_constructor_callback<'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, - "Failed to construct 'ExtendableMessageEvent': Please use the 'new' operator.", - ); - return; - } - let Some(event_type) = extendable_event_type_argument(scope, &args, "ExtendableMessageEvent") - else { - return; - }; - let init = extendable_event_init_object(&args); - let Some((bubbles, cancelable, composed)) = - extendable_event_init_flags(scope, &args, "ExtendableMessageEvent") - else { - return; - }; - let Some(data) = extendable_message_event_data(scope, init) else { - return; - }; - let Some(origin) = extendable_message_event_string_member(scope, init, "origin", "") else { - return; - }; - let Some(last_event_id) = - extendable_message_event_string_member(scope, init, "lastEventId", "") - else { - return; - }; - let Some(source) = extendable_message_event_source(scope, init) else { - return; - }; - let Some(ports) = extendable_message_event_ports(scope, init) else { - return; - }; - - let event = args.this(); - initialize_extendable_event_object(scope, event, &event_type, bubbles, cancelable, composed); - let _ = ExtendableMessageEventStateDeclaration::new(data, origin, last_event_id, source, ports) - .initialize(scope, event); - rv.set(event.into()); -} - -fn extendable_event_type_argument<'s>( - scope: &mut v8::PinScope<'s, '_>, - args: &v8::FunctionCallbackArguments<'s>, - constructor_name: &'static str, -) -> Option { - if args.length() == 0 { - throw_type_error( - scope, - &format!("Failed to construct '{constructor_name}': 1 argument required."), - ); - return None; - } - webidl::argument::( - scope, - args, - 0, - webidl::Context::argument(constructor_name, 1), - ) - .map(Into::into) - .map_or_else( - |error| { - webidl::throw_error(scope, &error); - None - }, - Some, - ) -} - -fn extendable_event_init_object<'s>( - args: &v8::FunctionCallbackArguments<'s>, -) -> Option> { - if args.length() <= 1 { - return None; - } - let value = args.get(1); - if value.is_null_or_undefined() || !value.is_object() { - None - } else { - v8::Local::::try_from(value).ok() - } -} - -fn extendable_event_init_flags<'s>( - scope: &mut v8::PinScope<'s, '_>, - args: &v8::FunctionCallbackArguments<'s>, - constructor_name: &'static str, -) -> Option<(bool, bool, bool)> { - let init = extendable_event_init_object(args); - Some(( - extendable_event_bool_member(scope, init, constructor_name, "bubbles")?, - extendable_event_bool_member(scope, init, constructor_name, "cancelable")?, - extendable_event_bool_member(scope, init, constructor_name, "composed")?, - )) -} - -fn extendable_event_bool_member<'s>( - scope: &mut v8::PinScope<'s, '_>, - init: Option>, - prefix: &'static str, - key: &'static str, -) -> Option { - let Some(init) = init else { - return Some(false); - }; - let value = - match webidl::property_result(scope, init, key, webidl::Context::member(prefix, key)) { - Ok(Some(value)) if !value.is_undefined() => value, - Ok(_) => return Some(false), - Err(error) => { - webidl::throw_error(scope, &error); - return None; - } - }; - webidl::convert::(scope, value, webidl::Context::member(prefix, key)) - .map(Into::into) - .map_or_else( - |error| { - webidl::throw_error(scope, &error); - None - }, - Some, - ) -} - -fn initialize_extendable_event_object<'s>( - scope: &mut v8::PinScope<'s, '_>, - event: v8::Local<'s, v8::Object>, - event_type: &str, - bubbles: bool, - cancelable: bool, - composed: bool, -) { - // EventTarget dispatch and inherited Event methods require the base - // event's internal state, in addition to its visible properties. - crate::context_bootstrap::initialize_event_object( - scope, event, event_type, bubbles, cancelable, - ); - ExtendableEventStateDeclaration::new(composed) - .initialize(scope, event) - .expect("extendable event state should initialize"); -} - -fn extendable_message_event_data<'s>( - scope: &mut v8::PinScope<'s, '_>, - init: Option>, -) -> Option> { - let Some(init) = init else { - return Some(v8::null(scope).into()); - }; - match webidl::property_result( - scope, - init, - "data", - webidl::Context::member("ExtendableMessageEvent", "data"), - ) { - Ok(Some(value)) if !value.is_undefined() => Some(value), - Ok(_) => Some(v8::null(scope).into()), - Err(error) => { - webidl::throw_error(scope, &error); - None - } - } -} - -fn extendable_message_event_string_member<'s>( - scope: &mut v8::PinScope<'s, '_>, - init: Option>, - key: &'static str, - default: &'static str, -) -> Option { - let Some(init) = init else { - return Some(default.to_owned()); - }; - let value = match webidl::property_result( - scope, - init, - key, - webidl::Context::member("ExtendableMessageEvent", key), - ) { - Ok(Some(value)) if !value.is_undefined() => value, - Ok(_) => return Some(default.to_owned()), - Err(error) => { - webidl::throw_error(scope, &error); - return None; - } - }; - webidl::convert::( - scope, - value, - webidl::Context::member("ExtendableMessageEvent", key), - ) - .map(Into::into) - .map_or_else( - |error| { - webidl::throw_error(scope, &error); - None - }, - Some, - ) -} - -fn extendable_message_event_source<'s>( - scope: &mut v8::PinScope<'s, '_>, - init: Option>, -) -> Option> { - let Some(init) = init else { - return Some(v8::null(scope).into()); - }; - let value = match webidl::property_result( - scope, - init, - "source", - webidl::Context::member("ExtendableMessageEvent", "source"), - ) { - Ok(Some(value)) if !value.is_null_or_undefined() => value, - Ok(_) => return Some(v8::null(scope).into()), - Err(error) => { - webidl::throw_error(scope, &error); - return None; - } - }; - let Ok(object) = v8::Local::::try_from(value) else { - throw_type_error( - scope, - "Failed to construct 'ExtendableMessageEvent': member source is not of type Client, ServiceWorker, or MessagePort.", - ); - return None; - }; - if extendable_message_event_source_object_is_valid(scope, object) { - Some(value) - } else { - throw_type_error( - scope, - "Failed to construct 'ExtendableMessageEvent': member source is not of type Client, ServiceWorker, or MessagePort.", - ); - None - } -} - -fn extendable_message_event_source_object_is_valid<'s>( - scope: &mut v8::PinScope<'s, '_>, - object: v8::Local<'s, v8::Object>, -) -> bool { - crate::context_bootstrap::message_port_id_from_object(scope, object).is_some() - || get_private_value(scope, object, SERVICE_WORKER_CLIENT_ID_SLOT).is_some() - || (get_private_value(scope, object, SERVICE_WORKER_VERSION_ID_SLOT).is_some() - && object - .get(scope, v8str(scope, "scriptURL").into()) - .is_some_and(|value| value.is_string())) -} - -fn extendable_message_event_ports<'s>( - scope: &mut v8::PinScope<'s, '_>, - init: Option>, -) -> Option> { - let Some(init) = init else { - return Some(frozen_empty_worker_array(scope)); - }; - let value = match webidl::property_result( - scope, - init, - "ports", - webidl::Context::member("ExtendableMessageEvent", "ports"), - ) { - Ok(Some(value)) if !value.is_undefined() => value, - Ok(_) => return Some(frozen_empty_worker_array(scope)), - Err(error) => { - webidl::throw_error(scope, &error); - return None; - } - }; - let Ok(source) = v8::Local::::try_from(value) else { - throw_type_error( - scope, - "Failed to construct 'ExtendableMessageEvent': member ports is not a sequence.", - ); - return None; - }; - let ports = v8::Array::new(scope, source.length() as i32); - for index in 0..source.length() { - let port = source.get_index(scope, index)?; - let Ok(port_object) = v8::Local::::try_from(port) else { - throw_type_error( - scope, - "Failed to construct 'ExtendableMessageEvent': member ports contains a non-MessagePort value.", - ); - return None; - }; - if crate::context_bootstrap::message_port_id_from_object(scope, port_object).is_none() { - throw_type_error( - scope, - "Failed to construct 'ExtendableMessageEvent': member ports contains a non-MessagePort value.", - ); - return None; - } - let _ = ports.set_index(scope, index, port); - } - ports - .set_integrity_level(scope, v8::IntegrityLevel::Frozen)? - .then_some(())?; - Some(ports) -} - -fn frozen_empty_worker_array<'s>(scope: &mut v8::PinScope<'s, '_>) -> v8::Local<'s, v8::Array> { - let array = v8::Array::new(scope, 0); - let _ = array.set_integrity_level(scope, v8::IntegrityLevel::Frozen); - array -} diff --git a/moli-renderer-v8/src/worker/global_scope/fetch_events.rs b/moli-renderer-v8/src/worker/global_scope/fetch_events.rs index 7d1b63d3668..e1d7f28c204 100644 --- a/moli-renderer-v8/src/worker/global_scope/fetch_events.rs +++ b/moli-renderer-v8/src/worker/global_scope/fetch_events.rs @@ -1,15 +1,9 @@ //! FetchEvent construction and the state shared with native fetch dispatch. +use moli_webapi::events::fetch::fetch_event_constructor_callback; use super::*; -use crate::webidl; const FETCH_EVENT_PROTOTYPE_SLOT: &str = "__moliFetchEventPrototype"; -const REQUEST_SLOT: &str = "__moliFetchEventRequest"; -const PRELOAD_RESPONSE_SLOT: &str = "__moliFetchEventPreloadResponse"; -const CLIENT_ID_SLOT: &str = "__moliFetchEventClientId"; -const RESULTING_CLIENT_ID_SLOT: &str = "__moliFetchEventResultingClientId"; -const REPLACES_CLIENT_ID_SLOT: &str = "__moliFetchEventReplacesClientId"; -const HANDLED_SLOT: &str = "__moliFetchEventHandled"; #[derive(WebApiFunctionTemplate)] #[webapi( @@ -20,18 +14,6 @@ const HANDLED_SLOT: &str = "__moliFetchEventHandled"; receiver = web_api_interfaces::FetchEvent::is_instance )] struct FetchEventTemplateDeclaration { - #[webapi(accessor_property, enumerable, getter = fetch_event_attribute_getter, data = v8str(scope, REQUEST_SLOT))] - request: (), - #[webapi(accessor_property, enumerable, getter = fetch_event_attribute_getter, data = v8str(scope, PRELOAD_RESPONSE_SLOT))] - preload_response: (), - #[webapi(accessor_property, enumerable, getter = fetch_event_attribute_getter, data = v8str(scope, CLIENT_ID_SLOT))] - client_id: (), - #[webapi(accessor_property, enumerable, getter = fetch_event_attribute_getter, data = v8str(scope, RESULTING_CLIENT_ID_SLOT))] - resulting_client_id: (), - #[webapi(accessor_property, enumerable, getter = fetch_event_attribute_getter, data = v8str(scope, REPLACES_CLIENT_ID_SLOT))] - replaces_client_id: (), - #[webapi(accessor_property, enumerable, getter = fetch_event_attribute_getter, data = v8str(scope, HANDLED_SLOT))] - handled: (), #[webapi(method = "respondWith", enumerable, callback = fetch_event_respond_with_callback, length = 1)] respond_with: (), } @@ -43,90 +25,12 @@ struct FetchEventConstructorGlobalDeclaration<'scope> { fetch_event: v8::Local<'scope, v8::Function>, } -#[derive(webidl::WebIdlDictionary)] -struct FetchEventBaseInit { - #[webidl(default = false)] - bubbles: bool, - #[webidl(default = false)] - cancelable: bool, - #[webidl(default = false)] - composed: bool, -} - -// Promise-valued dictionary members need a fresh intrinsic capability even -// when the input is already a native Promise with an author-defined `then`. -struct FetchEventInitPromise<'s>(v8::Local<'s, v8::Promise>); - -impl<'s> webidl::WebIdlConverter<'s> for FetchEventInitPromise<'s> { - type Options = (); - - fn convert( - scope: &mut v8::PinScope<'s, '_>, - value: v8::Local<'s, v8::Value>, - context: webidl::Context, - _options: &Self::Options, - ) -> std::result::Result { - let error = || webidl::WebIdlError::cannot_convert(context, "Promise"); - let resolver = v8::PromiseResolver::new(scope).ok_or_else(error)?; - let promise = resolver.get_promise(scope); - if resolver.resolve(scope, value) == Some(true) { - Ok(Self(promise)) - } else { - Err(error()) - } - } -} - -#[derive(webidl::WebIdlDictionary)] -#[webidl(prefix = "FetchEventInit")] -struct FetchEventInit<'s> { - #[webidl(inherit)] - base: FetchEventBaseInit, - #[webidl(default = webidl::DomString16(Vec::new()), converter = "raw")] - client_id: webidl::DomString16, - #[webidl(converter = "raw")] - handled: Option>, - #[webidl(converter = "raw")] - preload_response: Option>, - #[webidl(default = webidl::DomString16(Vec::new()), converter = "raw")] - replaces_client_id: webidl::DomString16, - #[webidl(required, interface = web_api_interfaces::Request)] - request: v8::Local<'s, v8::Object>, - #[webidl(default = webidl::DomString16(Vec::new()), converter = "raw")] - resulting_client_id: webidl::DomString16, -} - -#[derive(webidl::WebIdlArgs)] -#[webidl(prefix = "FetchEvent")] -struct FetchEventConstructorArgs<'s> { - #[webidl(required, converter = "raw")] - event_type: webidl::DomString16, - #[webidl(required, dictionary)] - init: FetchEventInit<'s>, -} - -#[derive(WebApiObject)] -#[webapi(interface = web_api_interfaces::FetchEvent, prototype = "Object")] -struct FetchEventStateDeclaration<'scope> { - #[webapi(slot = REQUEST_SLOT)] - request: v8::Local<'scope, v8::Object>, - #[webapi(slot = PRELOAD_RESPONSE_SLOT)] - preload_response: v8::Local<'scope, v8::Promise>, - #[webapi(slot = CLIENT_ID_SLOT)] - client_id: v8::Local<'scope, v8::String>, - #[webapi(slot = RESULTING_CLIENT_ID_SLOT)] - resulting_client_id: v8::Local<'scope, v8::String>, - #[webapi(slot = REPLACES_CLIENT_ID_SLOT)] - replaces_client_id: v8::Local<'scope, v8::String>, - #[webapi(slot = HANDLED_SLOT)] - handled: v8::Local<'scope, v8::Promise>, -} - pub(super) fn install_service_worker_fetch_event_constructor<'s>( scope: &mut v8::PinScope<'s, '_>, global: v8::Local<'s, v8::Object>, ) -> Result<()> { let template = FetchEventTemplateDeclaration::build(scope); + moli_webapi::events::fetch::install_value_template_bindings(scope, template); let constructor = template .get_function(scope) .ok_or_else(|| anyhow!("failed to build FetchEvent constructor"))?; @@ -145,80 +49,6 @@ pub(super) fn install_service_worker_fetch_event_constructor<'s>( .map_err(Into::into) } -fn fetch_event_constructor_callback<'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, "FetchEvent requires the 'new' operator."); - return; - } - let Some(parsed) = webidl::parse_args::(scope, &args) else { - return; - }; - let init = parsed.init; - let event_type = - v8::String::new_from_two_byte(scope, &parsed.event_type.0, v8::NewStringType::Normal) - .expect("FetchEvent type"); - let state = crate::context_bootstrap::new_event_state(scope); - crate::context_bootstrap::initialize_event_object_with_type( - scope, - state, - event_type, - init.base.bubbles, - init.base.cancelable, - ); - let _ = state.set( - scope, - v8str(scope, "composed").into(), - v8::Boolean::new(scope, init.base.composed).into(), - ); - let event = args.this(); - if crate::context_bootstrap::initialize_event_wrapper(scope, event, state).is_none() { - return; - } - let preload_response = init - .preload_response - .map(|promise| promise.0) - .unwrap_or_else(|| { - let resolver = v8::PromiseResolver::new(scope).expect("FetchEvent preload promise"); - let _ = resolver.resolve(scope, v8::undefined(scope).into()); - resolver.get_promise(scope) - }); - let handled = init.handled.map(|promise| promise.0).unwrap_or_else(|| { - v8::PromiseResolver::new(scope) - .expect("FetchEvent handled promise") - .get_promise(scope) - }); - let string = |scope: &mut v8::PinScope<'s, '_>, value: webidl::DomString16| { - v8::String::new_from_two_byte(scope, &value.0, v8::NewStringType::Normal) - .expect("FetchEvent client ID") - }; - FetchEventStateDeclaration::new( - init.request, - preload_response, - string(scope, init.client_id), - string(scope, init.resulting_client_id), - string(scope, init.replaces_client_id), - handled, - ) - .initialize(scope, event) - .expect("FetchEvent state"); - rv.set(event.into()); -} - -fn fetch_event_attribute_getter<'s>( - scope: &mut v8::PinScope<'s, '_>, - args: v8::FunctionCallbackArguments<'s>, - mut rv: v8::ReturnValue<'s, v8::Value>, -) { - let slot = args.data().to_rust_string_lossy(scope); - if let Some(value) = get_private_value(scope, args.this(), &slot) { - rv.set(value); - } -} - fn fetch_event_respond_with_callback<'s>( scope: &mut v8::PinScope<'s, '_>, args: v8::FunctionCallbackArguments<'s>, @@ -246,14 +76,13 @@ pub(in crate::worker) fn initialize_native_fetch_event<'s>( assert_eq!(event.set_prototype(scope, prototype), Some(true)); crate::context_bootstrap::initialize_event_object(scope, event, "fetch", false, true); crate::context_bootstrap::mark_event_trusted(scope, event); - FetchEventStateDeclaration::new( + moli_webapi::events::fetch::initialize_native_fetch_event_values( + scope, + event, request, - preload_response, - v8::String::new(scope, client_id).unwrap_or_else(|| v8::String::empty(scope)), - v8::String::new(scope, resulting_client_id).unwrap_or_else(|| v8::String::empty(scope)), - v8::String::empty(scope), handled, - ) - .initialize(scope, event) - .expect("native FetchEvent state"); + preload_response, + client_id, + resulting_client_id, + ); } diff --git a/moli-renderer-v8/src/xml_serializer.rs b/moli-renderer-v8/src/xml_serializer.rs index 38e3d32c5d2..4501c643c9f 100644 --- a/moli-renderer-v8/src/xml_serializer.rs +++ b/moli-renderer-v8/src/xml_serializer.rs @@ -6,7 +6,7 @@ use crate::{ web_api_interfaces, webidl, }; -use super::util::{throw_type_error, v8_string, v8str}; +use super::util::{v8_string, v8str}; const VOID_HTML: &[&str] = &[ "area", "base", "basefont", "bgsound", "br", "col", "embed", "frame", "hr", "img", "input", @@ -16,20 +16,7 @@ const HTML_NAMESPACE: &str = "http://www.w3.org/1999/xhtml"; const XML_NAMESPACE: &str = "http://www.w3.org/XML/1998/namespace"; const XMLNS_NAMESPACE: &str = "http://www.w3.org/2000/xmlns/"; -pub(super) fn xml_serializer_constructor_callback( - scope: &mut v8::PinScope<'_, '_>, - args: v8::FunctionCallbackArguments<'_>, - mut rv: v8::ReturnValue<'_, v8::Value>, -) { - if !args.is_construct_call() { - throw_type_error( - scope, - "Failed to construct 'XMLSerializer': Please use the 'new' operator.", - ); - return; - } - rv.set(args.this().into()); -} +pub(super) use moli_webapi::constructors::xml_serializer_constructor_callback; #[derive(webidl::WebIdlArgs)] #[webidl(prefix = "XMLSerializer.serializeToString")] diff --git a/moli-webapi/README.md b/moli-webapi/README.md index 26495038d3d..460eec481ed 100644 --- a/moli-webapi/README.md +++ b/moli-webapi/README.md @@ -15,6 +15,7 @@ The direct binding migration includes these groups: | Collections and records | FileList, Touch/TouchList, native WebIDL collection iterators, CryptoKey, IDBKeyRange/IDBRecord, MutationRecord, IntersectionObserverEntry, IdleDeadline, EventCounts, Highlight/HighlightRegistry and their live iterators | | Canvas and media values | WebGL binding state and methods, ImageBitmap value lifetime, TextMetrics, CanvasGradient validation, MediaCapabilities and MediaSource capability queries | | Standalone constructors and conversions | TextEncoder, value-event dictionaries and constructors, TrustedHTML/TrustedScript/TrustedScriptURL, credential values and JSON conversions, NavigatorUAData, AbortSignal value/argument shapes, base64, CSS identifier escaping, PushMessageData and PushSubscriptionOptions | +| Constructor and owner separation | Event/ProgressEvent, navigation event values, ExtendableEvent/ExtendableMessageEvent/FetchEvent values, WebSocketError and close dictionaries, TextDecoder with a weakly bound codec component, Animation/KeyframeEffect values, DOMParser creation-realm state, XMLSerializer/FileReaderSync shells, IdleDetector/VTTCue initial state, and initial OffscreenCanvas/2D context values | The remaining Renderer bindings were checked for actual host dependencies, including dependencies hidden behind parent-module imports. These groups still require their current native owners: @@ -22,14 +23,14 @@ The remaining Renderer bindings were checked for actual host dependencies, inclu | --- | --- | | Window, navigation, DOM, CSSOM and SVG | Document identity, wrapper projection, live nodes and collections, layout/style state, mutation and navigation lifecycle | | UI, pointer, keyboard, InputEvent and TouchEvent construction | Window authorization, native target/range conversion and dispatch; independent Touch values and lists are shared | -| TextDecoder, streams and compression | The context-owned codec store, native finalizers and execution queues | +| Streams and compression | Stream/controller ownership, callback residence and execution queues; TextDecoder and its codec store are shared, with the host explicitly retiring the component at teardown | | Fetch, Request/Response, Blob/File, WebSocket, service workers, storage and IndexedDB | Request/body ownership, backend handles, asynchronous execution and lifecycle checks; IDBKeyRange/IDBRecord, key conversions and version-event payloads are shared | | WebCrypto execution | Backend work and owner-bound completion; CryptoKey values are shared | | Screen, viewport, permissions, media devices, battery and network information | Live host state, active-document checks, overrides or handler ownership | -| TextTrackCue/VTTCue | Native track ordering, DOM fragment creation and event-handler ownership | +| TextTrackCue/VTTCue operations | Native track ordering, DOM fragment creation and event-handler ownership; VTTCue construction and initial values are shared | | MediaSession and credential signals | Traced callbacks retain resource initiators; signals validate the effective RP domain; independent credential values and JSON rules are shared | | Trusted Types policies | CSP enforcement, default-policy callbacks, violations and realm materialization; trusted value objects are shared | -| Canvas 2D, OffscreenCanvas and image sources | Pixel/backing-store ownership, source conversion and layout-dependent measurement; already-resolved values and WebGL state are shared | +| Canvas 2D, OffscreenCanvas and image operations | Drawing/backing-store ownership, source conversion and layout-dependent measurement; construction, initial values and WebGL state are shared | `tests/` exercises the extracted bindings in bare V8 realms. Renderer, Worker and browser integration tests continue to cover their host wiring. The callback source-boundary tests inventory both Renderer and shared binding calls so moving code does not remove those checks. diff --git a/moli-webapi/src/animation.rs b/moli-webapi/src/animation.rs new file mode 100644 index 00000000000..63e25baa112 --- /dev/null +++ b/moli-webapi/src/animation.rs @@ -0,0 +1,510 @@ +//! Animation and KeyframeEffect value state. DOM style updates and animation +//! playback/dispatch stay with the embedding runtime. +use crate::interfaces as web_api_interfaces; +use moli_v8_util::{ + get_private_value, global_constructor_object, set_private_value, throw_type_error, v8_string, + v8str, +}; +use moli_webapi_declare::{WebApiFunctionTemplate, WebApiObject}; +use moli_webidl as webidl; + +pub const ANIMATION_PLAY_STATE_SLOT: &str = "__moliAnimationPlayState"; + +const ANIMATION_ID_SLOT: &str = "__moliAnimationId"; + +const ANIMATION_READY_SLOT: &str = "__moliAnimationReady"; + +const ANIMATION_FINISHED_SLOT: &str = "__moliAnimationFinished"; + +pub const ANIMATION_FINISHED_RESOLVE_SLOT: &str = "__moliAnimationFinishedResolve"; + +const ANIMATION_PROMISE_RESOLVE_SLOT: &str = "__moliAnimationPromiseResolve"; + +pub const ANIMATION_EFFECT_SLOT: &str = "__moliAnimationEffect"; + +const ANIMATION_TIMELINE_SLOT: &str = "__moliAnimationTimeline"; + +pub const ANIMATION_START_TIME_SLOT: &str = "__moliAnimationStartTime"; + +pub const ANIMATION_ONFINISH_SLOT: &str = "__moliAnimationOnfinish"; + +pub const ANIMATION_FINISH_TOKEN_SLOT: &str = "__moliAnimationFinishToken"; + +pub const KEYFRAME_EFFECT_TARGET_SLOT: &str = "__moliKeyframeEffectTarget"; + +pub const KEYFRAME_EFFECT_KEYFRAMES_SLOT: &str = "__moliKeyframeEffectKeyframes"; + +#[derive(Default, WebApiObject)] +#[webapi(plain)] +struct AnimationPromiseEntryDeclaration { + #[webapi(slot = ANIMATION_PROMISE_RESOLVE_SLOT, init = "undefined")] + resolve: (), +} + +#[derive(WebApiObject)] +#[webapi(interface = web_api_interfaces::Animation)] +struct AnimationObjectDeclaration<'s> { + #[webapi(slot = ANIMATION_ID_SLOT, constructor_default = "")] + id: &'static str, + #[webapi(slot = ANIMATION_PLAY_STATE_SLOT, constructor_default = "idle")] + play_state: &'static str, + #[webapi(slot = ANIMATION_EFFECT_SLOT)] + effect: v8::Local<'s, v8::Value>, + #[webapi(slot = ANIMATION_TIMELINE_SLOT)] + timeline: v8::Local<'s, v8::Value>, + #[webapi(slot = ANIMATION_START_TIME_SLOT, init = "null")] + start_time: (), + #[webapi(slot = ANIMATION_ONFINISH_SLOT, init = "null")] + onfinish: (), + #[webapi(slot = ANIMATION_FINISH_TOKEN_SLOT, constructor_default)] + finish_token: f64, + #[webapi(slot = ANIMATION_READY_SLOT)] + ready: Option>, + #[webapi(slot = ANIMATION_FINISHED_SLOT)] + finished: Option>, + #[webapi(slot = ANIMATION_FINISHED_RESOLVE_SLOT)] + finished_resolve: Option>, +} + +#[derive(WebApiObject)] +#[webapi(interface = web_api_interfaces::KeyframeEffect)] +struct KeyframeEffectObjectDeclaration<'s> { + #[webapi(slot = KEYFRAME_EFFECT_TARGET_SLOT)] + target: v8::Local<'s, v8::Value>, + #[webapi(slot = KEYFRAME_EFFECT_KEYFRAMES_SLOT)] + keyframes: v8::Local<'s, v8::Value>, +} + +#[derive(WebApiFunctionTemplate)] +#[webapi(interface = web_api_interfaces::KeyframeEffect, enumerable)] +struct KeyframeEffectPrototypeDeclaration { + #[webapi(method, length = 1, callback = keyframe_effect_set_keyframes_callback)] + set_keyframes: (), +} + +#[derive(WebApiObject)] +#[webapi(plain)] +struct AnimationPromiseResolverDeclaration<'s> { + #[webapi(slot = ANIMATION_PROMISE_RESOLVE_SLOT)] + resolve: v8::Local<'s, v8::Value>, +} + +#[derive(WebApiFunctionTemplate)] +#[webapi(interface = web_api_interfaces::Animation, enumerable)] +struct AnimationValuePrototypeDeclaration { + #[webapi( + accessor_property, + getter = animation_id_getter_callback, + setter = animation_id_setter_callback + )] + id: (), + + #[webapi(accessor_property = "playState", getter = animation_play_state_getter)] + play_state: (), + + #[webapi(accessor_property, getter = animation_pending_getter)] + pending: (), + + #[webapi(accessor_property, getter = animation_ready_getter)] + ready: (), + + #[webapi(accessor_property, getter = animation_finished_getter)] + finished: (), + + #[webapi( + accessor_property, + getter = animation_timeline_getter, + setter = animation_timeline_setter + )] + timeline: (), + + #[webapi( + accessor_property, + getter = animation_onfinish_getter, + setter = animation_onfinish_setter + )] + onfinish: (), +} + +fn animation_id_getter_callback<'s>( + scope: &mut v8::PinScope<'s, '_>, + args: v8::FunctionCallbackArguments<'s>, + mut rv: v8::ReturnValue<'_, v8::Value>, +) { + if get_private_value(scope, args.this(), ANIMATION_PLAY_STATE_SLOT).is_none() { + throw_type_error( + scope, + "Animation.id getter called on incompatible receiver.", + ); + return; + } + let id = get_private_value(scope, args.this(), ANIMATION_ID_SLOT) + .and_then(|value| value.to_string(scope)) + .map(|value| value.to_rust_string_lossy(scope)) + .unwrap_or_default(); + if let Some(id) = v8_string(scope, &id) { + rv.set(id.into()); + } +} + +fn animation_id_setter_callback<'s>( + scope: &mut v8::PinScope<'s, '_>, + args: v8::FunctionCallbackArguments<'s>, + _rv: v8::ReturnValue<'_, v8::Value>, +) { + if get_private_value(scope, args.this(), ANIMATION_PLAY_STATE_SLOT).is_none() { + throw_type_error( + scope, + "Animation.id setter called on incompatible receiver.", + ); + return; + } + let id = match webidl::convert::( + scope, + args.get(0), + webidl::Context::member("Animation", "id"), + ) { + Ok(id) => id.0, + Err(error) => { + webidl::throw_error(scope, &error); + return; + } + }; + if let Some(id) = v8_string(scope, &id) { + set_private_value(scope, args.this(), ANIMATION_ID_SLOT, id.into()); + } +} + +pub fn animation_constructor_callback<'s>( + scope: &mut v8::PinScope<'s, '_>, + args: v8::FunctionCallbackArguments<'s>, + mut rv: v8::ReturnValue<'_, v8::Value>, +) { + if !args.is_construct_call() { + throw_type_error( + scope, + "Failed to construct 'Animation': Please use the 'new' operator.", + ); + return; + } + let effect = if args.get(0).is_null_or_undefined() { + v8::null(scope).into() + } else { + args.get(0) + }; + let timeline = if args.get(1).is_null_or_undefined() { + v8::null(scope).into() + } else { + args.get(1) + }; + initialize_animation_object(scope, args.this(), effect, timeline); + rv.set(args.this().into()); +} + +pub fn keyframe_effect_constructor_callback<'s>( + scope: &mut v8::PinScope<'s, '_>, + args: v8::FunctionCallbackArguments<'s>, + mut rv: v8::ReturnValue<'_, v8::Value>, +) { + if !args.is_construct_call() { + throw_type_error( + scope, + "Failed to construct 'KeyframeEffect': Please use the 'new' operator.", + ); + return; + } + KeyframeEffectObjectDeclaration::new(args.get(0), args.get(1)) + .initialize(scope, args.this()) + .expect("KeyframeEffect declaration should initialize object"); + rv.set(args.this().into()); +} + +fn keyframe_effect_set_keyframes_callback<'s>( + scope: &mut v8::PinScope<'s, '_>, + args: v8::FunctionCallbackArguments<'s>, + mut rv: v8::ReturnValue<'_, v8::Value>, +) { + set_private_value( + scope, + args.this(), + KEYFRAME_EFFECT_KEYFRAMES_SLOT, + args.get(0), + ); + rv.set_undefined(); +} + +fn initialize_animation_object<'s>( + scope: &mut v8::PinScope<'s, '_>, + animation: v8::Local<'s, v8::Object>, + effect: v8::Local<'s, v8::Value>, + timeline: v8::Local<'s, v8::Value>, +) { + let ready = if let Some(ready_resolver) = v8::PromiseResolver::new(scope) { + let ready = ready_resolver.get_promise(scope); + let _ = ready_resolver.resolve(scope, animation.into()); + Some(ready) + } else { + None + }; + let (finished, finished_resolve) = new_animation_pending_promise(scope) + .map(|(finished, resolve)| (Some(finished), Some(resolve))) + .unwrap_or((None, None)); + AnimationObjectDeclaration::new(effect, timeline, ready, finished, finished_resolve) + .initialize(scope, animation) + .expect("Animation declaration should initialize object"); +} + +pub fn require_animation_receiver<'s>( + scope: &mut v8::PinScope<'s, '_>, + receiver: v8::Local<'s, v8::Object>, + member: &str, +) -> bool { + if web_api_interfaces::Animation::is_instance(scope, receiver) { + return true; + } + throw_type_error( + scope, + &format!("Animation.{member} called on incompatible receiver."), + ); + false +} + +fn animation_play_state_getter<'s>( + scope: &mut v8::PinScope<'s, '_>, + args: v8::FunctionCallbackArguments<'s>, + mut rv: v8::ReturnValue<'_, v8::Value>, +) { + if !require_animation_receiver(scope, args.this(), "playState getter") { + return; + } + rv.set(animation_play_state_value(scope, args.this())); +} + +fn animation_pending_getter<'s>( + scope: &mut v8::PinScope<'s, '_>, + args: v8::FunctionCallbackArguments<'s>, + mut rv: v8::ReturnValue<'_, v8::Value>, +) { + if !require_animation_receiver(scope, args.this(), "pending getter") { + return; + } + rv.set(animation_pending_value(scope)); +} + +fn animation_ready_getter<'s>( + scope: &mut v8::PinScope<'s, '_>, + args: v8::FunctionCallbackArguments<'s>, + mut rv: v8::ReturnValue<'_, v8::Value>, +) { + if !require_animation_receiver(scope, args.this(), "ready getter") { + return; + } + rv.set(animation_ready_value(scope, args.this())); +} + +fn animation_finished_getter<'s>( + scope: &mut v8::PinScope<'s, '_>, + args: v8::FunctionCallbackArguments<'s>, + mut rv: v8::ReturnValue<'_, v8::Value>, +) { + if !require_animation_receiver(scope, args.this(), "finished getter") { + return; + } + rv.set(animation_finished_value(scope, args.this())); +} + +pub fn animation_effect_getter<'s>( + scope: &mut v8::PinScope<'s, '_>, + args: v8::FunctionCallbackArguments<'s>, + mut rv: v8::ReturnValue<'_, v8::Value>, +) { + if !require_animation_receiver(scope, args.this(), "effect getter") { + return; + } + rv.set(animation_slot_value( + scope, + args.this(), + ANIMATION_EFFECT_SLOT, + )); +} + +fn animation_timeline_getter<'s>( + scope: &mut v8::PinScope<'s, '_>, + args: v8::FunctionCallbackArguments<'s>, + mut rv: v8::ReturnValue<'_, v8::Value>, +) { + if !require_animation_receiver(scope, args.this(), "timeline getter") { + return; + } + rv.set(animation_slot_value( + scope, + args.this(), + ANIMATION_TIMELINE_SLOT, + )); +} + +fn animation_onfinish_getter<'s>( + scope: &mut v8::PinScope<'s, '_>, + args: v8::FunctionCallbackArguments<'s>, + mut rv: v8::ReturnValue<'_, v8::Value>, +) { + if !require_animation_receiver(scope, args.this(), "onfinish getter") { + return; + } + rv.set(animation_slot_value( + scope, + args.this(), + ANIMATION_ONFINISH_SLOT, + )); +} + +pub fn animation_start_time_getter<'s>( + scope: &mut v8::PinScope<'s, '_>, + args: v8::FunctionCallbackArguments<'s>, + mut rv: v8::ReturnValue<'_, v8::Value>, +) { + if !require_animation_receiver(scope, args.this(), "startTime getter") { + return; + } + rv.set(animation_slot_value( + scope, + args.this(), + ANIMATION_START_TIME_SLOT, + )); +} + +fn animation_slot_value<'s>( + scope: &mut v8::PinScope<'s, '_>, + animation: v8::Local<'s, v8::Object>, + slot: &'static str, +) -> v8::Local<'s, v8::Value> { + get_private_value(scope, animation, slot).unwrap_or_else(|| v8::null(scope).into()) +} + +fn animation_play_state_value<'s>( + scope: &mut v8::PinScope<'s, '_>, + animation: v8::Local<'s, v8::Object>, +) -> v8::Local<'s, v8::Value> { + get_private_value(scope, animation, ANIMATION_PLAY_STATE_SLOT) + .unwrap_or_else(|| v8str(scope, "idle").into()) +} + +fn animation_pending_value<'s>(scope: &mut v8::PinScope<'s, '_>) -> v8::Local<'s, v8::Value> { + v8::Boolean::new(scope, false).into() +} + +fn animation_ready_value<'s>( + scope: &mut v8::PinScope<'s, '_>, + animation: v8::Local<'s, v8::Object>, +) -> v8::Local<'s, v8::Value> { + get_private_value(scope, animation, ANIMATION_READY_SLOT) + .unwrap_or_else(|| v8::undefined(scope).into()) +} + +fn animation_finished_value<'s>( + scope: &mut v8::PinScope<'s, '_>, + animation: v8::Local<'s, v8::Object>, +) -> v8::Local<'s, v8::Value> { + get_private_value(scope, animation, ANIMATION_FINISHED_SLOT) + .unwrap_or_else(|| v8::undefined(scope).into()) +} + +fn new_animation_pending_promise<'s>( + scope: &mut v8::PinScope<'s, '_>, +) -> Option<(v8::Local<'s, v8::Value>, v8::Local<'s, v8::Function>)> { + let entry = AnimationPromiseEntryDeclaration::default() + .bind(scope) + .expect("Animation promise entry declaration should bind"); + let executor = v8::Function::builder(animation_promise_executor_callback) + .data(entry.into()) + .length(2) + .build(scope)?; + let promise_constructor = global_constructor_object(scope, "Promise") + .and_then(|constructor| v8::Local::::try_from(constructor).ok())?; + let promise = promise_constructor.new_instance(scope, &[executor.into()])?; + let resolve = get_private_value(scope, entry, ANIMATION_PROMISE_RESOLVE_SLOT) + .and_then(|value| v8::Local::::try_from(value).ok())?; + Some((promise.into(), resolve)) +} + +fn animation_promise_executor_callback<'s>( + scope: &mut v8::PinScope<'s, '_>, + args: v8::FunctionCallbackArguments<'s>, + mut rv: v8::ReturnValue<'_, v8::Value>, +) { + let Ok(entry) = v8::Local::::try_from(args.data()) else { + rv.set_undefined(); + return; + }; + AnimationPromiseResolverDeclaration::new(args.get(0)) + .initialize(scope, entry) + .expect("Animation promise resolver declaration should initialize object"); + rv.set_undefined(); +} + +pub fn install_value_template_bindings<'s>( + scope: &mut v8::PinScope<'s, '_, ()>, + template: v8::Local<'s, v8::FunctionTemplate>, + name: &str, +) { + let prototype = template.prototype_template(scope); + match name { + "Animation" => { + AnimationValuePrototypeDeclaration::initialize_prototype_template(scope, prototype) + } + "KeyframeEffect" => { + KeyframeEffectPrototypeDeclaration::initialize_prototype_template(scope, prototype) + } + _ => (), + } +} + +fn animation_timeline_setter<'s>( + scope: &mut v8::PinScope<'s, '_>, + args: v8::FunctionCallbackArguments<'s>, + mut rv: v8::ReturnValue<'_, v8::Value>, +) { + if !require_animation_receiver(scope, args.this(), "timeline setter") { + return; + } + set_animation_timeline_value(scope, args.this(), args.get(0)); + rv.set_undefined(); +} + +fn animation_onfinish_setter<'s>( + scope: &mut v8::PinScope<'s, '_>, + args: v8::FunctionCallbackArguments<'s>, + mut rv: v8::ReturnValue<'_, v8::Value>, +) { + if !require_animation_receiver(scope, args.this(), "onfinish setter") { + return; + } + set_animation_onfinish_value(scope, args.this(), args.get(0)); + rv.set_undefined(); +} + +fn set_animation_timeline_value<'s>( + scope: &mut v8::PinScope<'s, '_>, + animation: v8::Local<'s, v8::Object>, + value: v8::Local<'s, v8::Value>, +) { + let value = if value.is_null_or_undefined() { + v8::null(scope).into() + } else { + value + }; + set_private_value(scope, animation, ANIMATION_TIMELINE_SLOT, value); +} + +fn set_animation_onfinish_value<'s>( + scope: &mut v8::PinScope<'s, '_>, + animation: v8::Local<'s, v8::Object>, + value: v8::Local<'s, v8::Value>, +) { + let value = if value.is_null_or_undefined() || value.is_function() { + value + } else { + v8::null(scope).into() + }; + set_private_value(scope, animation, ANIMATION_ONFINISH_SLOT, value); +} diff --git a/moli-webapi/src/canvas_context_values.rs b/moli-webapi/src/canvas_context_values.rs new file mode 100644 index 00000000000..260bece10d4 --- /dev/null +++ b/moli-webapi/src/canvas_context_values.rs @@ -0,0 +1,164 @@ +//! Initial 2D context values and OffscreenCanvas construction. Drawing and +//! HTMLCanvasElement write-through remain embedding operations. +use crate::image_data::new_uint8_clamped_array_from_bytes; +use crate::interfaces as web_api_interfaces; +use moli_canvas::{DEFAULT_FILL_STYLE, DEFAULT_FONT}; +use moli_v8_util::{set_private_value, throw_type_error}; +use moli_webapi_declare::WebApiObject; +use moli_webidl as webidl; + +pub const CANVAS_BACKING_STORE_SLOT: &str = "__moliCanvasBackingStore"; +pub const OFFSCREEN_CANVAS_WIDTH_SLOT: &str = "__moliOffscreenCanvasWidth"; +pub const OFFSCREEN_CANVAS_HEIGHT_SLOT: &str = "__moliOffscreenCanvasHeight"; +pub const CANVAS_CONTEXT_FILL_STYLE_SLOT: &str = "__moliCanvasContextFillStyle"; +pub const CANVAS_CONTEXT_FONT_SLOT: &str = "__moliCanvasContextFont"; +pub const CANVAS_CONTEXT_IMAGE_SMOOTHING_ENABLED_SLOT: &str = + "__moliCanvasContextImageSmoothingEnabled"; +pub const CANVAS_CONTEXT_IMAGE_SMOOTHING_QUALITY_SLOT: &str = + "__moliCanvasContextImageSmoothingQuality"; +pub const CANVAS_CONTEXT_GLOBAL_ALPHA_SLOT: &str = "__moliCanvasContextGlobalAlpha"; +pub const CANVAS_CONTEXT_GLOBAL_COMPOSITE_OPERATION_SLOT: &str = + "__moliCanvasContextGlobalCompositeOperation"; +pub const CANVAS_CONTEXT_LINE_WIDTH_SLOT: &str = "__moliCanvasContextLineWidth"; +pub const CANVAS_CONTEXT_LINE_CAP_SLOT: &str = "__moliCanvasContextLineCap"; +pub const CANVAS_CONTEXT_LINE_JOIN_SLOT: &str = "__moliCanvasContextLineJoin"; +pub const CANVAS_CONTEXT_MITER_LIMIT_SLOT: &str = "__moliCanvasContextMiterLimit"; +pub const CANVAS_CONTEXT_LINE_DASH_OFFSET_SLOT: &str = "__moliCanvasContextLineDashOffset"; +pub const CANVAS_CONTEXT_STROKE_STYLE_SLOT: &str = "__moliCanvasContextStrokeStyle"; + +pub const DEFAULT_GLOBAL_ALPHA: f64 = 1.0; +pub const DEFAULT_GLOBAL_COMPOSITE_OPERATION: &str = "source-over"; +pub const DEFAULT_LINE_WIDTH: f64 = 1.0; +pub const DEFAULT_LINE_CAP: &str = "butt"; +pub const DEFAULT_LINE_JOIN: &str = "miter"; +pub const DEFAULT_MITER_LIMIT: f64 = 10.0; +pub const DEFAULT_LINE_DASH_OFFSET: f64 = 0.0; +pub const DEFAULT_STROKE_STYLE: &str = "#000000"; + +#[derive(WebApiObject)] +#[webapi(fragment, prototype = "CanvasRenderingContext2D")] +struct CanvasLikeContextObjectDeclaration { + #[webapi( + slot = CANVAS_CONTEXT_FILL_STYLE_SLOT, + constructor_default = DEFAULT_FILL_STYLE + )] + fill_style: &'static str, + #[webapi(slot = CANVAS_CONTEXT_FONT_SLOT, constructor_default = DEFAULT_FONT)] + font: &'static str, + #[webapi( + slot = CANVAS_CONTEXT_IMAGE_SMOOTHING_ENABLED_SLOT, + constructor_default = true + )] + image_smoothing_enabled: bool, + #[webapi( + slot = CANVAS_CONTEXT_IMAGE_SMOOTHING_QUALITY_SLOT, + constructor_default = "low" + )] + image_smoothing_quality: &'static str, + #[webapi( + slot = CANVAS_CONTEXT_GLOBAL_ALPHA_SLOT, + constructor_default = DEFAULT_GLOBAL_ALPHA + )] + global_alpha: f64, + #[webapi( + slot = CANVAS_CONTEXT_GLOBAL_COMPOSITE_OPERATION_SLOT, + constructor_default = DEFAULT_GLOBAL_COMPOSITE_OPERATION + )] + global_composite_operation: &'static str, + #[webapi(slot = CANVAS_CONTEXT_LINE_WIDTH_SLOT, constructor_default = DEFAULT_LINE_WIDTH)] + line_width: f64, + #[webapi(slot = CANVAS_CONTEXT_LINE_CAP_SLOT, constructor_default = DEFAULT_LINE_CAP)] + line_cap: &'static str, + #[webapi(slot = CANVAS_CONTEXT_LINE_JOIN_SLOT, constructor_default = DEFAULT_LINE_JOIN)] + line_join: &'static str, + #[webapi( + slot = CANVAS_CONTEXT_MITER_LIMIT_SLOT, + constructor_default = DEFAULT_MITER_LIMIT + )] + miter_limit: f64, + #[webapi( + slot = CANVAS_CONTEXT_LINE_DASH_OFFSET_SLOT, + constructor_default = DEFAULT_LINE_DASH_OFFSET + )] + line_dash_offset: f64, + #[webapi( + slot = CANVAS_CONTEXT_STROKE_STYLE_SLOT, + constructor_default = DEFAULT_STROKE_STYLE + )] + stroke_style: &'static str, +} + +#[derive(WebApiObject)] +#[webapi(interface = web_api_interfaces::OffscreenCanvas)] +struct OffscreenCanvasObjectDeclaration { + #[webapi(slot = OFFSCREEN_CANVAS_WIDTH_SLOT)] + width: f64, + #[webapi(slot = OFFSCREEN_CANVAS_HEIGHT_SLOT)] + height: f64, +} + +pub fn init_canvas_like_context_object<'s>( + scope: &mut v8::PinScope<'s, '_>, + object: v8::Local<'s, v8::Object>, +) { + CanvasLikeContextObjectDeclaration::new() + .initialize(scope, object) + .expect("canvas context declaration should initialize object"); +} +#[derive(webidl::WebIdlArgs)] +#[webidl(prefix = "OffscreenCanvas")] +struct OffscreenCanvasConstructorArgs { + #[webidl(required, converter = "enforce_range_unsigned_long")] + width: u32, + #[webidl(required, converter = "enforce_range_unsigned_long")] + height: u32, +} + +pub fn offscreen_canvas_constructor_callback<'s>( + scope: &mut v8::PinScope<'s, '_>, + args: v8::FunctionCallbackArguments<'s>, + mut rv: v8::ReturnValue<'_, v8::Value>, +) { + if !args.is_construct_call() { + throw_type_error( + scope, + "Failed to construct 'OffscreenCanvas': Please use the 'new' operator.", + ); + return; + } + + let Some(parsed) = webidl::parse_args::(scope, &args) else { + return; + }; + init_offscreen_canvas_object(scope, args.this(), parsed.width, parsed.height); + rv.set(args.this().into()); +} + +pub fn canvas_rendering_context_2d_constructor_callback<'s>( + scope: &mut v8::PinScope<'s, '_>, + args: v8::FunctionCallbackArguments<'s>, + mut rv: v8::ReturnValue<'_, v8::Value>, +) { + init_canvas_like_context_object(scope, args.this()); + rv.set(args.this().into()); +} + +pub use canvas_rendering_context_2d_constructor_callback as offscreen_canvas_rendering_context_2d_constructor_callback; + +fn init_offscreen_canvas_object<'s>( + scope: &mut v8::PinScope<'s, '_>, + object: v8::Local<'s, v8::Object>, + width: u32, + height: u32, +) { + OffscreenCanvasObjectDeclaration::new(f64::from(width), f64::from(height)) + .bind_into(scope, object) + .expect("OffscreenCanvas declaration should initialize object"); + // A fresh OffscreenCanvas has no HTMLCanvasElement or attached context. + // Allocate its initial pixels once; native drawing attaches its owner later. + if let Some(bytes) = moli_canvas::byte_len(width, height) + .and_then(|len| new_uint8_clamped_array_from_bytes(scope, vec![0; len])) + { + set_private_value(scope, object, CANVAS_BACKING_STORE_SLOT, bytes.into()); + } +} diff --git a/moli-webapi/src/constructors.rs b/moli-webapi/src/constructors.rs index 50f6984708b..9802dd79ca2 100644 --- a/moli-webapi/src/constructors.rs +++ b/moli-webapi/src/constructors.rs @@ -1,6 +1,7 @@ use crate::dom_exception::new_dom_exception_value as dom_exception_value; use crate::event_target::initialize_simple_event_target; use moli_v8_util::throw_type_error; +use moli_webapi_declare::WebApiObject; pub fn event_target_constructor_callback<'s>( scope: &mut v8::PinScope<'s, '_>, @@ -66,3 +67,40 @@ pub fn unsupported_constructor_callback( ); scope.throw_exception(exception); } + +pub fn xml_serializer_constructor_callback( + scope: &mut v8::PinScope<'_, '_>, + args: v8::FunctionCallbackArguments<'_>, + mut rv: v8::ReturnValue<'_, v8::Value>, +) { + if !args.is_construct_call() { + throw_type_error( + scope, + "Failed to construct 'XMLSerializer': Please use the 'new' operator.", + ); + return; + } + rv.set(args.this().into()); +} + +#[derive(Default, WebApiObject)] +#[webapi(interface = crate::interfaces::FileReaderSync)] +struct FileReaderSyncObjectDeclaration {} + +pub fn file_reader_sync_constructor_callback<'s>( + scope: &mut v8::PinScope<'s, '_>, + args: v8::FunctionCallbackArguments<'s>, + mut rv: v8::ReturnValue<'_, v8::Value>, +) { + if !args.is_construct_call() { + throw_type_error( + scope, + "Failed to construct 'FileReaderSync': Please use the 'new' operator.", + ); + return; + } + FileReaderSyncObjectDeclaration::default() + .initialize(scope, args.this()) + .expect("FileReaderSync declaration should initialize"); + rv.set(args.this().into()); +} diff --git a/moli-webapi/src/dom_parser_values.rs b/moli-webapi/src/dom_parser_values.rs new file mode 100644 index 00000000000..fc699c12271 --- /dev/null +++ b/moli-webapi/src/dom_parser_values.rs @@ -0,0 +1,33 @@ +//! Parser construction keeps its creation realm witness in the V8 heap. +//! Parsing and native Document creation remain embedding operations. +use crate::interfaces; +use moli_v8_util::throw_type_error; +use moli_webapi_declare::WebApiObject; + +pub const DOM_PARSER_CONSTRUCTION_REALM_SLOT: &str = "__moliDomParserConstructionRealm"; + +#[derive(WebApiObject)] +#[webapi(interface = interfaces::DOMParser)] +struct DomParserObjectDeclaration<'s> { + #[webapi(slot = DOM_PARSER_CONSTRUCTION_REALM_SLOT)] + creation_realm: v8::Local<'s, v8::Object>, +} + +pub fn dom_parser_constructor_callback<'s>( + scope: &mut v8::PinScope<'s, '_>, + args: v8::FunctionCallbackArguments<'s>, + mut rv: v8::ReturnValue<'_, v8::Value>, +) { + if !args.is_construct_call() { + throw_type_error(scope, "DOMParser constructor must be called with new"); + return; + } + // The constructor's Window is independent of newTarget.prototype. Keep + // a V8-traced creation-Realm witness, not a native persistent Context root + // or a WindowProxy that can be rebound to another Window on navigation. + let realm = moli_v8_util::new_null_prototype_object(scope); + DomParserObjectDeclaration::new(realm) + .initialize(scope, args.this()) + .expect("DOMParser state should initialize"); + rv.set(args.this().into()); +} diff --git a/moli-webapi/src/events.rs b/moli-webapi/src/events.rs index 040697a3db3..e75cb933d44 100644 --- a/moli-webapi/src/events.rs +++ b/moli-webapi/src/events.rs @@ -7,10 +7,12 @@ use std::rc::Rc; pub mod audio; pub mod device; +pub mod fetch; pub mod ice_error_event; pub mod init; pub mod kind; pub mod progress; +pub mod service_worker; pub mod speech; pub mod state; pub mod subclasses; diff --git a/moli-webapi/src/events/fetch.rs b/moli-webapi/src/events/fetch.rs new file mode 100644 index 00000000000..f3b7621226d --- /dev/null +++ b/moli-webapi/src/events/fetch.rs @@ -0,0 +1,211 @@ +//! FetchEvent dictionaries, promise values and native snapshot construction. +//! respondWith and fetch-dispatch completion belong to the worker runtime. +use crate::interfaces as web_api_interfaces; +use moli_v8_util::{get_private_value, throw_type_error, v8str}; +use moli_webapi_declare::{WebApiFunctionTemplate, WebApiObject}; +use moli_webidl as webidl; + +pub const REQUEST_SLOT: &str = "__moliFetchEventRequest"; + +pub const PRELOAD_RESPONSE_SLOT: &str = "__moliFetchEventPreloadResponse"; + +pub const CLIENT_ID_SLOT: &str = "__moliFetchEventClientId"; + +pub const RESULTING_CLIENT_ID_SLOT: &str = "__moliFetchEventResultingClientId"; + +pub const REPLACES_CLIENT_ID_SLOT: &str = "__moliFetchEventReplacesClientId"; + +pub const HANDLED_SLOT: &str = "__moliFetchEventHandled"; + +// Promise-valued dictionary members need a fresh intrinsic capability even +// when the input is already a native Promise with an author-defined `then`. +struct FetchEventInitPromise<'s>(v8::Local<'s, v8::Promise>); + +impl<'s> webidl::WebIdlConverter<'s> for FetchEventInitPromise<'s> { + type Options = (); + + fn convert( + scope: &mut v8::PinScope<'s, '_>, + value: v8::Local<'s, v8::Value>, + context: webidl::Context, + _options: &Self::Options, + ) -> std::result::Result { + let error = || webidl::WebIdlError::cannot_convert(context, "Promise"); + let resolver = v8::PromiseResolver::new(scope).ok_or_else(error)?; + let promise = resolver.get_promise(scope); + if resolver.resolve(scope, value) == Some(true) { + Ok(Self(promise)) + } else { + Err(error()) + } + } +} + +#[derive(webidl::WebIdlDictionary)] +#[webidl(prefix = "FetchEventInit")] +struct FetchEventInit<'s> { + #[webidl(inherit)] + base: super::init::EventInit, + #[webidl(default = webidl::DomString16(Vec::new()), converter = "raw")] + client_id: webidl::DomString16, + #[webidl(converter = "raw")] + handled: Option>, + #[webidl(converter = "raw")] + preload_response: Option>, + #[webidl(default = webidl::DomString16(Vec::new()), converter = "raw")] + replaces_client_id: webidl::DomString16, + #[webidl(required, interface = web_api_interfaces::Request)] + request: v8::Local<'s, v8::Object>, + #[webidl(default = webidl::DomString16(Vec::new()), converter = "raw")] + resulting_client_id: webidl::DomString16, +} + +#[derive(webidl::WebIdlArgs)] +#[webidl(prefix = "FetchEvent")] +struct FetchEventConstructorArgs<'s> { + #[webidl(required, converter = "raw")] + event_type: webidl::DomString16, + #[webidl(required, dictionary)] + init: FetchEventInit<'s>, +} + +#[derive(WebApiObject)] +#[webapi(interface = web_api_interfaces::FetchEvent, prototype = "Object")] +struct FetchEventStateDeclaration<'scope> { + #[webapi(slot = REQUEST_SLOT)] + request: v8::Local<'scope, v8::Object>, + #[webapi(slot = PRELOAD_RESPONSE_SLOT)] + preload_response: v8::Local<'scope, v8::Promise>, + #[webapi(slot = CLIENT_ID_SLOT)] + client_id: v8::Local<'scope, v8::String>, + #[webapi(slot = RESULTING_CLIENT_ID_SLOT)] + resulting_client_id: v8::Local<'scope, v8::String>, + #[webapi(slot = REPLACES_CLIENT_ID_SLOT)] + replaces_client_id: v8::Local<'scope, v8::String>, + #[webapi(slot = HANDLED_SLOT)] + handled: v8::Local<'scope, v8::Promise>, +} + +pub fn fetch_event_constructor_callback<'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, "FetchEvent requires the 'new' operator."); + return; + } + let Some(parsed) = webidl::parse_args::(scope, &args) else { + return; + }; + let init = parsed.init; + let event_type = + v8::String::new_from_two_byte(scope, &parsed.event_type.0, v8::NewStringType::Normal) + .expect("FetchEvent type"); + let state = super::new_event_state(scope); + super::initialize_event_object_with_type( + scope, + state, + event_type, + init.base.bubbles, + init.base.cancelable, + ); + let _ = state.set( + scope, + v8str(scope, "composed").into(), + v8::Boolean::new(scope, init.base.composed).into(), + ); + let event = args.this(); + if super::initialize_event_wrapper(scope, event, state).is_none() { + return; + } + let preload_response = init + .preload_response + .map(|promise| promise.0) + .unwrap_or_else(|| { + let resolver = v8::PromiseResolver::new(scope).expect("FetchEvent preload promise"); + let _ = resolver.resolve(scope, v8::undefined(scope).into()); + resolver.get_promise(scope) + }); + let handled = init.handled.map(|promise| promise.0).unwrap_or_else(|| { + v8::PromiseResolver::new(scope) + .expect("FetchEvent handled promise") + .get_promise(scope) + }); + let string = |scope: &mut v8::PinScope<'s, '_>, value: webidl::DomString16| { + v8::String::new_from_two_byte(scope, &value.0, v8::NewStringType::Normal) + .expect("FetchEvent client ID") + }; + FetchEventStateDeclaration::new( + init.request, + preload_response, + string(scope, init.client_id), + string(scope, init.resulting_client_id), + string(scope, init.replaces_client_id), + handled, + ) + .initialize(scope, event) + .expect("FetchEvent state"); + rv.set(event.into()); +} + +pub fn fetch_event_attribute_getter<'s>( + scope: &mut v8::PinScope<'s, '_>, + args: v8::FunctionCallbackArguments<'s>, + mut rv: v8::ReturnValue<'s, v8::Value>, +) { + let slot = args.data().to_rust_string_lossy(scope); + if let Some(value) = get_private_value(scope, args.this(), &slot) { + rv.set(value); + } +} + +#[derive(WebApiFunctionTemplate)] +#[webapi( + interface = web_api_interfaces::FetchEvent, + readonly_prototype, + receiver = web_api_interfaces::FetchEvent::is_instance +)] +struct FetchEventValueTemplateDeclaration { + #[webapi(accessor_property, enumerable, getter = fetch_event_attribute_getter, data = v8str(scope, REQUEST_SLOT))] + request: (), + #[webapi(accessor_property, enumerable, getter = fetch_event_attribute_getter, data = v8str(scope, PRELOAD_RESPONSE_SLOT))] + preload_response: (), + #[webapi(accessor_property, enumerable, getter = fetch_event_attribute_getter, data = v8str(scope, CLIENT_ID_SLOT))] + client_id: (), + #[webapi(accessor_property, enumerable, getter = fetch_event_attribute_getter, data = v8str(scope, RESULTING_CLIENT_ID_SLOT))] + resulting_client_id: (), + #[webapi(accessor_property, enumerable, getter = fetch_event_attribute_getter, data = v8str(scope, REPLACES_CLIENT_ID_SLOT))] + replaces_client_id: (), + #[webapi(accessor_property, enumerable, getter = fetch_event_attribute_getter, data = v8str(scope, HANDLED_SLOT))] + handled: (), +} + +pub fn install_value_template_bindings<'s>( + scope: &mut v8::PinScope<'s, '_>, + template: v8::Local<'s, v8::FunctionTemplate>, +) { + let prototype = template.prototype_template(scope); + FetchEventValueTemplateDeclaration::initialize_prototype_template(scope, prototype); +} + +pub fn initialize_native_fetch_event_values<'s>( + scope: &mut v8::PinScope<'s, '_>, + event: v8::Local<'s, v8::Object>, + request: v8::Local<'s, v8::Object>, + handled: v8::Local<'s, v8::Promise>, + preload_response: v8::Local<'s, v8::Promise>, + client_id: &str, + resulting_client_id: &str, +) { + FetchEventStateDeclaration::new( + request, + preload_response, + v8::String::new(scope, client_id).unwrap_or_else(|| v8::String::empty(scope)), + v8::String::new(scope, resulting_client_id).unwrap_or_else(|| v8::String::empty(scope)), + v8::String::empty(scope), + handled, + ) + .initialize(scope, event) + .expect("native FetchEvent state"); +} diff --git a/moli-webapi/src/events/service_worker.rs b/moli-webapi/src/events/service_worker.rs new file mode 100644 index 00000000000..b318cad5360 --- /dev/null +++ b/moli-webapi/src/events/service_worker.rs @@ -0,0 +1,135 @@ +//! Service Worker event values. Dispatch associations and waitUntil remain with the worker. +use crate::interfaces as web_api_interfaces; +use moli_v8_util::{throw_type_error, v8_string_from_utf16_units}; +use moli_webapi_declare::WebApiObject; +use moli_webidl as webidl; +use webidl::WebIdlDictionarySerialize; + +#[derive(webidl::WebIdlArgs)] +#[webidl(prefix = "ExtendableEvent")] +struct ExtendableEventConstructorArgs { + #[webidl(required, converter = "raw")] + event_type: webidl::DomString16, + #[webidl(dictionary)] + init: super::init::EventInit, +} + +// Interface identity, rather than live endpoint IDs or author-visible +// scriptURL properties, determines membership in this WebIDL union. +struct ExtendableMessageEventSource; + +impl ExtendableMessageEventSource { + const NAME: &'static str = "ExtendableMessageEventSource"; + + fn is_instance<'s>( + scope: &mut v8::PinScope<'s, '_>, + object: v8::Local<'s, v8::Object>, + ) -> bool { + web_api_interfaces::Client::is_instance(scope, object) + || web_api_interfaces::ServiceWorker::is_instance(scope, object) + || web_api_interfaces::MessagePort::is_instance(scope, object) + } +} + +#[derive(webidl::WebIdlDictionary)] +#[webidl(prefix = "ExtendableMessageEventInit", snapshot)] +struct ExtendableMessageEventInit<'s> { + #[webidl(inherit)] + base: super::init::EventInit, + #[webidl(converter = "raw", snapshot_default = v8::null(scope).into())] + data: Option>, + #[webidl(name = "lastEventId", default = webidl::DomString16(Vec::new()), converter = "raw")] + last_event_id: webidl::DomString16, + #[webidl(default = "", converter = "usv_string")] + origin: String, + #[webidl(sequence, interface = web_api_interfaces::MessagePort, default = Vec::new(), snapshot_frozen)] + ports: Vec>, + #[webidl(nullable, interface = ExtendableMessageEventSource)] + source: Option>, +} + +#[derive(webidl::WebIdlArgs)] +#[webidl(prefix = "ExtendableMessageEvent")] +struct ExtendableMessageEventConstructorArgs<'s> { + #[webidl(required, converter = "raw")] + event_type: webidl::DomString16, + #[webidl(dictionary)] + init: ExtendableMessageEventInit<'s>, +} + +pub fn extendable_event_constructor_callback<'s>( + scope: &mut v8::PinScope<'s, '_>, + args: v8::FunctionCallbackArguments<'s>, + mut rv: v8::ReturnValue<'_, v8::Value>, +) { + if !args.is_construct_call() { + throw_type_error( + scope, + "Failed to construct 'ExtendableEvent': Please use the 'new' operator.", + ); + return; + } + let Some(parsed) = webidl::parse_args::(scope, &args) else { + return; + }; + let Some(event_type) = v8_string_from_utf16_units(scope, &parsed.event_type.0) else { + return; + }; + initialize_extendable_event_object(scope, args.this(), event_type, &parsed.init); + rv.set(args.this().into()); +} + +pub fn extendable_message_event_constructor_callback<'s>( + scope: &mut v8::PinScope<'s, '_>, + args: v8::FunctionCallbackArguments<'s>, + mut rv: v8::ReturnValue<'_, v8::Value>, +) { + if !args.is_construct_call() { + throw_type_error( + scope, + "Failed to construct 'ExtendableMessageEvent': Please use the 'new' operator.", + ); + return; + } + let Some(parsed) = webidl::parse_args::(scope, &args) + else { + return; + }; + let Some(event_type) = v8_string_from_utf16_units(scope, &parsed.event_type.0) else { + return; + }; + let event = args.this(); + initialize_extendable_event_object(scope, event, event_type, &parsed.init.base); + if parsed.init.initialize_own_snapshot(scope, event).is_none() { + return; + } + web_api_interfaces::ExtendableMessageEvent::DESCRIPTOR + .initialize(scope, event) + .expect("extendable message event state"); + rv.set(event.into()); +} + +#[derive(WebApiObject)] +#[webapi(interface = web_api_interfaces::ExtendableEvent, prototype = "Object")] +struct ExtendableEventStateDeclaration { + #[webapi(data_property, enumerable)] + composed: bool, +} + +fn initialize_extendable_event_object<'s>( + scope: &mut v8::PinScope<'s, '_>, + event: v8::Local<'s, v8::Object>, + event_type: v8::Local<'s, v8::String>, + init: &super::init::EventInit, +) { + super::initialize_event_object_with_type( + scope, + event, + event_type, + init.bubbles, + init.cancelable, + ); + ExtendableEventStateDeclaration::new(init.composed) + .initialize(scope, event) + .expect("extendable event state should initialize"); +} diff --git a/moli-webapi/src/events/subclasses.rs b/moli-webapi/src/events/subclasses.rs index 7085b16ca72..fe4f5f4cb32 100644 --- a/moli-webapi/src/events/subclasses.rs +++ b/moli-webapi/src/events/subclasses.rs @@ -11,6 +11,8 @@ mod accessors; mod captured_mouse; mod clipboard_change; mod custom; +mod navigation; +pub use navigation::NAVIGATE_EVENT_SYNTHETIC_SLOT; pub mod error; pub mod font; pub mod message; @@ -42,6 +44,8 @@ const BEFORE_UNLOAD_EVENT_RETURN_VALUE_SLOT: &str = "__moliBeforeUnloadEventRetu pub const FONT_FACE_SET_LOAD_EVENT_FONTFACES_SLOT: &str = "__moliFontFaceSetLoadEventFontfaces"; enum SubclassInit<'s> { + CurrentEntry(navigation::NavigationCurrentEntryChangeEventInitMembers<'s>), + Navigate(navigation::NavigateEventInitMembers<'s>), Captured(captured_mouse::CapturedMouseEventInit), Custom(custom::CustomEventInit<'s>), Message(message::MessageEventInit<'s>), @@ -60,6 +64,12 @@ impl<'s> SubclassInit<'s> { kind: EventSubclassKind, ) -> Option { Some(match kind { + EventSubclassKind::NavigationCurrentEntryChangeEvent => Self::CurrentEntry( + navigation::parse_current_entry_change_event_init(scope, args)?, + ), + EventSubclassKind::NavigateEvent => { + Self::Navigate(navigation::parse_navigate_event_init(scope, args)?) + } EventSubclassKind::CapturedMouseEvent => { Self::Captured(captured_mouse::CapturedMouseEventInit::parse(scope, args)?) } @@ -105,6 +115,8 @@ impl<'s> SubclassInit<'s> { } fn event_flags(&self) -> (bool, bool, bool) { match self { + Self::CurrentEntry(init) => init.event_flags(), + Self::Navigate(init) => init.event_flags(), Self::Captured(init) => init.event_flags(), Self::Custom(init) => init.event_flags(), Self::Message(init) => init.event_flags(), @@ -123,6 +135,8 @@ impl<'s> SubclassInit<'s> { event: v8::Local<'s, v8::Object>, ) -> bool { match self { + Self::CurrentEntry(init) => init.initialize(scope, event), + Self::Navigate(init) => init.initialize(scope, event), Self::Captured(init) => return init.initialize(scope, event), Self::Custom(init) => init.initialize(scope, event), Self::Message(init) => message::initialize_message_event(scope, event, init), @@ -240,6 +254,8 @@ pub fn build_template<'s>( ) -> Option> { match kind { EventSubclassKind::CapturedMouseEvent + | EventSubclassKind::NavigateEvent + | EventSubclassKind::NavigationCurrentEntryChangeEvent | EventSubclassKind::MessageEvent | EventSubclassKind::StorageEvent | EventSubclassKind::CustomEvent diff --git a/moli-renderer-v8/src/context_bootstrap/events/subclasses/navigation_init.rs b/moli-webapi/src/events/subclasses/navigation.rs similarity index 79% rename from moli-renderer-v8/src/context_bootstrap/events/subclasses/navigation_init.rs rename to moli-webapi/src/events/subclasses/navigation.rs index 49e4cdc9d3a..c54d8ece524 100644 --- a/moli-renderer-v8/src/context_bootstrap/events/subclasses/navigation_init.rs +++ b/moli-webapi/src/events/subclasses/navigation.rs @@ -1,5 +1,8 @@ -use crate::context_bootstrap::events::EventInit; -use crate::{web_api_interfaces, webidl}; +pub const NAVIGATE_EVENT_SYNTHETIC_SLOT: &str = "__lmNavigateEventSynthetic"; +use super::super::init::EventInit; +use crate::interfaces as web_api_interfaces; +use moli_webidl as webidl; +use webidl::WebIdlDictionarySerialize; #[derive(Clone, Copy, webidl::WebIdlEnum)] #[webidl(name = "NavigationType", rename_all = "kebab-case")] @@ -91,3 +94,30 @@ pub(super) fn parse_current_entry_change_event_init<'s>( ) -> Option> { webidl::parse_args::(scope, args).map(|parsed| parsed.init) } + +impl<'s> NavigateEventInitMembers<'s> { + pub(super) fn initialize( + &self, + scope: &mut v8::PinScope<'s, '_>, + event: v8::Local<'s, v8::Object>, + ) { + self.initialize_snapshot(scope, event) + .expect("NavigateEvent state"); + super::super::state::set_event_private_value( + scope, + event, + NAVIGATE_EVENT_SYNTHETIC_SLOT, + v8::Boolean::new(scope, true).into(), + ); + } +} +impl<'s> NavigationCurrentEntryChangeEventInitMembers<'s> { + pub(super) fn initialize( + &self, + scope: &mut v8::PinScope<'s, '_>, + event: v8::Local<'s, v8::Object>, + ) { + self.initialize_snapshot(scope, event) + .expect("current entry event state"); + } +} diff --git a/moli-webapi/src/idle_detector_values.rs b/moli-webapi/src/idle_detector_values.rs new file mode 100644 index 00000000000..faff3149469 --- /dev/null +++ b/moli-webapi/src/idle_detector_values.rs @@ -0,0 +1,56 @@ +//! IdleDetector construction values; permission, start and abort ownership stay with the host. +use crate::{event_target::SIMPLE_EVENT_TARGET_LISTENERS_SLOT, interfaces as web_api_interfaces}; +use moli_v8_util::throw_type_error; +use moli_webapi_declare::WebApiObject; + +pub const IDLE_DETECTOR_STARTED_SLOT: &str = "__lmIdleDetectorStarted"; +pub const IDLE_DETECTOR_USER_ACTIVE_SLOT: &str = "__lmIdleDetectorUserActive"; +pub const IDLE_DETECTOR_SCREEN_UNLOCKED_SLOT: &str = "__lmIdleDetectorScreenUnlocked"; +pub const IDLE_DETECTOR_ABORT_SIGNAL_SLOT: &str = "__lmIdleDetectorAbortSignal"; +pub const IDLE_DETECTOR_ABORT_ALGORITHM_SLOT: &str = "__lmIdleDetectorAbortAlgorithm"; + +#[derive(WebApiObject)] +#[webapi(interface = web_api_interfaces::IdleDetector)] +struct IdleDetectorObjectDeclaration { + #[webapi(slot = IDLE_DETECTOR_STARTED_SLOT)] + started: bool, + + #[webapi(slot = IDLE_DETECTOR_USER_ACTIVE_SLOT)] + is_user_active: bool, + + #[webapi(slot = IDLE_DETECTOR_SCREEN_UNLOCKED_SLOT)] + is_screen_unlocked: bool, + + #[webapi(slot = SIMPLE_EVENT_TARGET_LISTENERS_SLOT, init = "null_object")] + event_listeners: (), + + #[webapi(slot = IDLE_DETECTOR_ABORT_SIGNAL_SLOT, init = "null")] + abort_signal: (), + + #[webapi(slot = IDLE_DETECTOR_ABORT_ALGORITHM_SLOT, init = "null")] + abort_algorithm: (), +} + +pub fn idle_detector_constructor_callback<'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, + "Failed to construct 'IdleDetector': Please use the 'new' operator.", + ); + return; + } + + let detector = args.this(); + if IdleDetectorObjectDeclaration::new(false, true, true) + .initialize(scope, detector) + .is_err() + { + rv.set_undefined(); + return; + } + rv.set(detector.into()); +} diff --git a/moli-webapi/src/lib.rs b/moli-webapi/src/lib.rs index f470bc16ac0..7776f5633a2 100644 --- a/moli-webapi/src/lib.rs +++ b/moli-webapi/src/lib.rs @@ -12,8 +12,10 @@ mod embedding; pub mod abort_signal_values; +pub mod animation; pub mod base64; pub mod callbacks; +pub mod canvas_context_values; pub mod canvas_gradient; pub mod constructors; pub mod credentials; @@ -21,6 +23,7 @@ pub mod crypto_key; pub mod css_escape; pub mod css_values; pub mod dom_exception; +pub mod dom_parser_values; pub mod dom_quad; pub mod dom_rect; pub mod dom_rect_list; @@ -37,12 +40,14 @@ pub mod geometry_clone; pub mod headers; pub mod highlights; pub mod idle_deadline; +pub mod idle_detector_values; pub mod image_bitmap; pub mod image_data; pub mod indexed_db_values; pub mod interfaces; pub mod intersection_observer_entry; pub mod media_capabilities; +pub mod media_cue_values; pub mod media_device_info; pub mod media_error; pub mod media_source; diff --git a/moli-webapi/src/media_cue_values.rs b/moli-webapi/src/media_cue_values.rs new file mode 100644 index 00000000000..b8b3f9d9d51 --- /dev/null +++ b/moli-webapi/src/media_cue_values.rs @@ -0,0 +1,115 @@ +//! Timed text construction and value state; native tracks and cue DOM remain host-owned. +use crate::{event_target::initialize_simple_event_target, interfaces as web_api_interfaces}; +use moli_v8_util::throw_type_error; +use moli_webapi_declare::WebApiObject; +use moli_webidl as webidl; + +pub const TEXT_TRACK_CUE_TRACK_SLOT: &str = "__moliTextTrackCueTrack"; + +pub const TEXT_TRACK_CUE_START_TIME_SLOT: &str = "__moliTextTrackCueStartTime"; + +pub const TEXT_TRACK_CUE_END_TIME_SLOT: &str = "__moliTextTrackCueEndTime"; + +pub const TEXT_TRACK_CUE_ID_SLOT: &str = "__moliTextTrackCueId"; + +pub const TEXT_TRACK_CUE_PAUSE_ON_EXIT_SLOT: &str = "__moliTextTrackCuePauseOnExit"; + +pub const TEXT_TRACK_CUE_VERTICAL_SLOT: &str = "__moliTextTrackCueVertical"; + +pub const TEXT_TRACK_CUE_SNAP_TO_LINES_SLOT: &str = "__moliTextTrackCueSnapToLines"; + +pub const TEXT_TRACK_CUE_LINE_SLOT: &str = "__moliTextTrackCueLine"; + +pub const TEXT_TRACK_CUE_POSITION_SLOT: &str = "__moliTextTrackCuePosition"; + +pub const TEXT_TRACK_CUE_SIZE_SLOT: &str = "__moliTextTrackCueSize"; + +pub const TEXT_TRACK_CUE_ALIGN_SLOT: &str = "__moliTextTrackCueAlign"; + +pub const TEXT_TRACK_CUE_ONENTER_SLOT: &str = "__moliTextTrackCueOnEnter"; + +pub const TEXT_TRACK_CUE_ONEXIT_SLOT: &str = "__moliTextTrackCueOnExit"; + +pub const TEXT_TRACK_CUE_TEXT_SLOT: &str = "__moliTextTrackCueText"; + +#[derive(webidl::WebIdlArgs)] +#[webidl(prefix = "VTTCue")] +struct VttCueConstructorArgs { + #[webidl(required, name = "startTime", converter = "double")] + start_time: f64, + #[webidl(required, name = "endTime", converter = "double")] + end_time: f64, + #[webidl(required)] + text: String, +} + +#[derive(WebApiObject)] +#[webapi(interface = web_api_interfaces::VTTCue)] +struct VttCuePrivateStateDeclaration { + #[webapi(slot = TEXT_TRACK_CUE_START_TIME_SLOT)] + _start_time: f64, + + #[webapi(slot = TEXT_TRACK_CUE_END_TIME_SLOT)] + _end_time: f64, + + #[webapi(slot = TEXT_TRACK_CUE_ID_SLOT, constructor_default = "")] + _id: &'static str, + + #[webapi(slot = TEXT_TRACK_CUE_PAUSE_ON_EXIT_SLOT, constructor_default = false)] + _pause_on_exit: bool, + + #[webapi(slot = TEXT_TRACK_CUE_VERTICAL_SLOT, constructor_default = "")] + _vertical: &'static str, + + #[webapi(slot = TEXT_TRACK_CUE_SNAP_TO_LINES_SLOT, constructor_default = true)] + _snap_to_lines: bool, + + #[webapi(slot = TEXT_TRACK_CUE_LINE_SLOT, constructor_default = "auto")] + _line: &'static str, + + #[webapi(slot = TEXT_TRACK_CUE_POSITION_SLOT, constructor_default = "auto")] + _position: &'static str, + + #[webapi(slot = TEXT_TRACK_CUE_SIZE_SLOT, constructor_default = 100.0)] + _size: f64, + + #[webapi(slot = TEXT_TRACK_CUE_ALIGN_SLOT, constructor_default = "center")] + _align: &'static str, + + #[webapi(slot = TEXT_TRACK_CUE_ONENTER_SLOT, init = "null")] + _onenter_slot: (), + + #[webapi(slot = TEXT_TRACK_CUE_ONEXIT_SLOT, init = "null")] + _onexit_slot: (), + + #[webapi(slot = TEXT_TRACK_CUE_TRACK_SLOT, init = "null")] + _track_slot: (), + + #[webapi(slot = TEXT_TRACK_CUE_TEXT_SLOT)] + text: String, +} + +pub fn vtt_cue_constructor_callback<'s>( + scope: &mut v8::PinScope<'s, '_>, + args: v8::FunctionCallbackArguments<'s>, + mut rv: v8::ReturnValue<'_, v8::Value>, +) { + if !args.is_construct_call() { + throw_type_error( + scope, + "Failed to construct 'VTTCue': Please use the 'new' operator.", + ); + return; + } + + let Some(parsed) = webidl::parse_args::(scope, &args) else { + return; + }; + + initialize_simple_event_target(scope, args.this()); + VttCuePrivateStateDeclaration::new(parsed.start_time, parsed.end_time, parsed.text) + .initialize(scope, args.this()) + .expect("VTTCue private state declaration should initialize"); + + rv.set(args.this().into()); +} diff --git a/moli-webapi/tests/event_payloads.rs b/moli-webapi/tests/event_payloads.rs index 41ec90ef941..a3694987617 100644 --- a/moli-webapi/tests/event_payloads.rs +++ b/moli-webapi/tests/event_payloads.rs @@ -124,8 +124,31 @@ fn install(scope: &mut v8::PinScope<'_, '_>, now: f64) { events::progress::install_progress_event_template_bindings(scope, progress, "ProgressEvent"); finish_template(scope, interfaces::ProgressEvent::DESCRIPTOR, progress); + let extendable = v8::FunctionTemplate::new( + scope, + events::service_worker::extendable_event_constructor_callback, + ); + extendable.inherit(event); + finish_template(scope, interfaces::ExtendableEvent::DESCRIPTOR, extendable); + let message = v8::FunctionTemplate::new( + scope, + events::service_worker::extendable_message_event_constructor_callback, + ); + message.inherit(extendable); + finish_template( + scope, + interfaces::ExtendableMessageEvent::DESCRIPTOR, + message, + ); + let fetch = v8::FunctionTemplate::new(scope, events::fetch::fetch_event_constructor_callback); + fetch.inherit(extendable); + events::fetch::install_value_template_bindings(scope, fetch); + finish_template(scope, interfaces::FetchEvent::DESCRIPTOR, fetch); + for kind in [ EventSubclassKind::CustomEvent, + EventSubclassKind::NavigateEvent, + EventSubclassKind::NavigationCurrentEntryChangeEvent, EventSubclassKind::MessageEvent, EventSubclassKind::StorageEvent, EventSubclassKind::CloseEvent, @@ -1078,3 +1101,61 @@ fn standalone_event_and_progress_constructors_share_realm_clock_and_native_proje publish(scope, "nativeProgress", event); assert!(eval(scope, "nativeProgress instanceof NativeProgress && nativeProgress.isTrusted && nativeProgress.timeStamp === 81.5 && nativeProgress.loaded === 3 && nativeProgress.total === 7").is_true()); } + +#[test] +fn standalone_navigation_and_worker_events_preserve_native_references_and_promises() { + ensure_v8(); + let mut isolate = v8::Isolate::new(Default::default()); + let scope = pin!(v8::HandleScope::new(&mut isolate)); + let scope = &mut scope.init(); + let context = v8::Context::new(scope, Default::default()); + let scope = &mut v8::ContextScope::new(scope, context); + install(scope, 64.0); + // The embedder supplies already-resolved native identities. These value + // constructors do not allocate a Request, history entry or AbortSignal owner. + for (name, interface) in [ + ("requestValue", interfaces::Request::DESCRIPTOR), + ("entryValue", interfaces::NavigationHistoryEntry::DESCRIPTOR), + ( + "destinationValue", + interfaces::NavigationDestination::DESCRIPTOR, + ), + ("signalValue", interfaces::AbortSignal::DESCRIPTOR), + ("workerValue", interfaces::ServiceWorker::DESCRIPTOR), + ] { + let template = v8::FunctionTemplate::new(scope, illegal_constructor); + finish_template(scope, interface, template); + let object = v8::Object::new(scope); + interface.initialize(scope, object).unwrap(); + publish(scope, name, object); + } + assert!(eval(scope, r#"(() => { + const check = ok => { if (!ok) throw new Error('event values'); }; + const entry = new NavigationCurrentEntryChangeEvent('currententrychange', {from:entryValue, navigationType:'replace'}); + check(entry.from === entryValue && entry.navigationType === 'replace' && entry.timeStamp === 64); + check(new NavigationCurrentEntryChangeEvent('change', {from:entryValue}).navigationType === null); + const navigate = new NavigateEvent('navigate', {destination:destinationValue, signal:signalValue, canIntercept:true}); + check(navigate.destination === destinationValue && navigate.signal === signalValue && navigate.canIntercept); + const extendable = new ExtendableEvent('activate', {bubbles:true, composed:true}); + check(extendable.type === 'activate' && extendable.bubbles && extendable.composed); + const order = [], messageInit = {}; + Object.defineProperty(workerValue, 'scriptURL', {get() {throw new Error('identity must not read scriptURL');}}); + for (const key of ['bubbles', 'cancelable', 'composed', 'data', 'lastEventId', 'origin', 'ports', 'source']) { + Object.defineProperty(messageInit, key, {get() { + order.push(key); + return ({data:7, lastEventId:'id\ud800', origin:'https://example.test', ports:new Set([endpoint]), source:workerValue})[key]; + }}); + } + const message = new ExtendableMessageEvent('message', messageInit); + check(order.join() === 'bubbles,cancelable,composed,data,lastEventId,origin,ports,source'); + check(message.data === 7 && message.source === workerValue && message.ports[0] === endpoint && Object.isFrozen(message.ports)); + check(message.lastEventId === 'id\ud800'); + const fetch = new FetchEvent('fetch', {request:requestValue, clientId:'client', preloadResponse:7}); + check(fetch instanceof ExtendableEvent && fetch.request === requestValue && fetch.clientId === 'client'); + check(fetch.preloadResponse instanceof Promise && fetch.handled instanceof Promise); + check(fetch.resultingClientId === '' && fetch.replacesClientId === ''); + try { new FetchEvent('fetch', {request:{}}); throw new Error('unbranded'); } + catch (error) { check(error instanceof TypeError); } + return true; + })()"#).is_true()); +} diff --git a/moli-webapi/tests/host_independent_constructors.rs b/moli-webapi/tests/host_independent_constructors.rs new file mode 100644 index 00000000000..c3751b6f657 --- /dev/null +++ b/moli-webapi/tests/host_independent_constructors.rs @@ -0,0 +1,201 @@ +mod support; + +use moli_v8_test_util::ensure_v8; +use moli_v8_util::{get_private_value, set_private_value}; +use moli_webapi::{ + animation, canvas_context_values as canvas, constructors, dom_parser_values, + event_target::{self, EventTargetRuntime}, + idle_detector_values as idle, interfaces, media_cue_values as cues, +}; +use std::pin::pin; +use support::{eval, finish_template, install_errors, publish}; + +fn initialize_target(scope: &mut v8::PinScope<'_, '_>, object: v8::Local<'_, v8::Object>) { + let registry = moli_v8_util::new_null_prototype_object(scope); + set_private_value( + scope, + object, + event_target::SIMPLE_EVENT_TARGET_LISTENERS_SLOT, + registry.into(), + ); +} + +fn set_handler( + scope: &mut v8::PinScope<'_, '_>, + object: v8::Local<'_, v8::Object>, + _: &str, + slot: &str, + value: v8::Local<'_, v8::Value>, +) { + set_private_value(scope, object, slot, value); +} + +fn with_values(test: impl FnOnce(&mut v8::PinScope<'_, '_>)) { + ensure_v8(); + let mut isolate = v8::Isolate::new(Default::default()); + let scope = pin!(v8::HandleScope::new(&mut isolate)); + let scope = &mut scope.init(); + let context = v8::Context::new(scope, Default::default()); + let scope = &mut v8::ContextScope::new(scope, context); + install_errors(scope); + event_target::install_runtime( + scope, + EventTargetRuntime { + initialize: initialize_target, + set_handler, + }, + ); + macro_rules! install { + ($interface:ident, $callback:path) => {{ + let template = v8::FunctionTemplate::new( + scope, + moli_webapi_declare::web_api_constructor!(interfaces::$interface, $callback), + ); + animation::install_value_template_bindings(scope, template, stringify!($interface)); + finish_template(scope, interfaces::$interface::DESCRIPTOR, template); + }}; + } + install!(Animation, animation::animation_constructor_callback); + install!( + KeyframeEffect, + animation::keyframe_effect_constructor_callback + ); + install!( + DOMParser, + dom_parser_values::dom_parser_constructor_callback + ); + install!( + XMLSerializer, + constructors::xml_serializer_constructor_callback + ); + install!( + FileReaderSync, + constructors::file_reader_sync_constructor_callback + ); + install!(IdleDetector, idle::idle_detector_constructor_callback); + install!(VTTCue, cues::vtt_cue_constructor_callback); + install!( + OffscreenCanvas, + canvas::offscreen_canvas_constructor_callback + ); + install!( + CanvasRenderingContext2D, + canvas::canvas_rendering_context_2d_constructor_callback + ); + install!( + OffscreenCanvasRenderingContext2D, + canvas::offscreen_canvas_rendering_context_2d_constructor_callback + ); + test(scope); +} + +#[test] +fn animation_values_construct_with_intrinsic_promises_without_dom_or_dispatch() { + with_values(|scope| { + assert!( + eval( + scope, + r#"(() => { + const check = ok => { if (!ok) throw new Error('animation value'); }; + const target = {}, keyframes = [{opacity:0}, {opacity:1}], timeline = {}; + const effect = new KeyframeEffect(target, keyframes); + const animation = new Animation(effect, timeline); + check(animation.id === '' && animation.playState === 'idle' && !animation.pending); + check(animation.ready instanceof Promise && animation.finished instanceof Promise); + check(animation.timeline === timeline); + animation.id = 'retained'; animation.timeline = null; + check(animation.id === 'retained' && animation.timeline === null); + const handler = () => {}; + animation.onfinish = handler; check(animation.onfinish === handler); + effect.setKeyframes([{opacity:0.5}]); + globalThis.savedAnimation = animation; + return true; + })()"# + ) + .is_true() + ); + let animation = v8::Local::::try_from(eval(scope, "savedAnimation")).unwrap(); + let effect = get_private_value(scope, animation, animation::ANIMATION_EFFECT_SLOT).unwrap(); + publish( + scope, + "savedEffect", + v8::Local::::try_from(effect).unwrap(), + ); + assert!(eval(scope, "savedEffect instanceof KeyframeEffect").is_true()); + }); +} + +#[test] +fn independent_constructor_values_keep_native_identity_and_creation_realm() { + with_values(|scope| { + let parser = v8::Local::::try_from(eval(scope, "new DOMParser()")).unwrap(); + let witness = get_private_value( + scope, + parser, + dom_parser_values::DOM_PARSER_CONSTRUCTION_REALM_SLOT, + ) + .unwrap(); + let witness = v8::Local::::try_from(witness).unwrap(); + assert!(witness.get_creation_context(scope).unwrap() == scope.get_current_context()); + assert!(eval(scope, "Object.prototype.toString.call(new XMLSerializer()) === '[object XMLSerializer]' && Object.prototype.toString.call(new FileReaderSync()) === '[object FileReaderSync]'").is_true()); + let detector = + v8::Local::::try_from(eval(scope, "new IdleDetector()")).unwrap(); + assert!( + get_private_value(scope, detector, idle::IDLE_DETECTOR_STARTED_SLOT) + .unwrap() + .is_false() + ); + let cue = + v8::Local::::try_from(eval(scope, "new VTTCue(1, 3, 'text')")).unwrap(); + assert_eq!( + get_private_value(scope, cue, cues::TEXT_TRACK_CUE_START_TIME_SLOT) + .unwrap() + .number_value(scope), + Some(1.0) + ); + assert_eq!( + get_private_value(scope, cue, cues::TEXT_TRACK_CUE_TEXT_SLOT) + .unwrap() + .to_rust_string_lossy(scope), + "text" + ); + }); +} + +#[test] +fn canvas_construction_converts_dimensions_once_and_allocates_initial_pixels_without_dom() { + with_values(|scope| { + let object = v8::Local::::try_from(eval(scope, r#"(() => { + const order = []; + const canvas = new OffscreenCanvas({valueOf(){order.push('width');return 2;}}, {valueOf(){order.push('height');return 3;}}); + if (order.join() !== 'width,height') throw new Error('conversion order'); + return canvas; + })()"#)).unwrap(); + assert_eq!( + get_private_value(scope, object, canvas::OFFSCREEN_CANVAS_WIDTH_SLOT) + .unwrap() + .number_value(scope), + Some(2.0) + ); + let pixels = v8::Local::::try_from( + get_private_value(scope, object, canvas::CANVAS_BACKING_STORE_SLOT).unwrap(), + ) + .unwrap(); + assert_eq!(pixels.byte_length(), 24); + let mut bytes = [1; 24]; + pixels.copy_contents(&mut bytes); + assert_eq!(bytes, [0; 24]); + for source in [ + "new CanvasRenderingContext2D()", + "new OffscreenCanvasRenderingContext2D()", + ] { + let context = v8::Local::::try_from(eval(scope, source)).unwrap(); + assert_eq!( + get_private_value(scope, context, canvas::CANVAS_CONTEXT_FILL_STYLE_SLOT) + .unwrap() + .to_rust_string_lossy(scope), + moli_canvas::DEFAULT_FILL_STYLE + ); + } + }); +}