diff --git a/moli-protocol/src/domains/input/tests/keyboard_events.rs b/moli-protocol/src/domains/input/tests/keyboard_events.rs index fc4b5ec28be..033d3a196db 100644 --- a/moli-protocol/src/domains/input/tests/keyboard_events.rs +++ b/moli-protocol/src/domains/input/tests/keyboard_events.rs @@ -59,6 +59,133 @@ async fn dispatch(ctx: &mut TestContext, event_type: &str, key: &str, code: &str ctx.expect_result(901, json!({}), None); } +async fn install_keyboard_microtask_log(ctx: &mut TestContext) { + assert!(evaluate_bool(ctx, r#"(() => { + window.__microtaskLog = []; + for (const type of ['keydown', 'keypress', 'beforeinput', 'input', 'keyup']) { + for (let listener = 1; listener <= 2; ++listener) { + document.addEventListener(type, () => { + __microtaskLog.push(type + ':' + listener); + Promise.resolve().then(() => __microtaskLog.push('microtask-' + type + ':' + listener)); + }); + } + } + return true; + })()"#).await); +} + +#[tokio::test(flavor = "multi_thread")] +async fn cdp_native_keyboard_events_checkpoint_between_listeners_and_before_defaults() { + for route in ["keyDown", "rawKeyDown"] { + let mut ctx = keyboard_fixture("").await; + install_keyboard_microtask_log(&mut ctx).await; + dispatch(&mut ctx, route, "x", "KeyX", "x").await; + if route == "rawKeyDown" { + dispatch(&mut ctx, "char", "x", "KeyX", "x").await; + } + dispatch(&mut ctx, "keyUp", "x", "KeyX", "").await; + + let actual: serde_json::Value = serde_json::from_str( + &evaluate_string(&mut ctx, "JSON.stringify(__microtaskLog)").await, + ) + .unwrap(); + assert_eq!( + actual, + json!([ + "keydown:1", + "microtask-keydown:1", + "keydown:2", + "microtask-keydown:2", + "keypress:1", + "microtask-keypress:1", + "keypress:2", + "microtask-keypress:2", + "beforeinput:1", + "microtask-beforeinput:1", + "beforeinput:2", + "microtask-beforeinput:2", + "input:1", + "microtask-input:1", + "input:2", + "microtask-input:2", + "keyup:1", + "microtask-keyup:1", + "keyup:2", + "microtask-keyup:2" + ]), + "route: {route}" + ); + assert_eq!(field_value(&mut ctx).await, "x"); + } +} + +#[tokio::test(flavor = "multi_thread")] +async fn cdp_keyboard_callback_microtasks_can_retarget_and_cancel_character_insertion() { + for cancel in [false, true] { + let mut ctx = keyboard_fixture("").await; + assert!( + evaluate_bool( + &mut ctx, + &format!( + r#"(() => {{ + window.__microtaskLog = []; + field.addEventListener('keydown', () => {{ + __microtaskLog.push('keydown'); + Promise.resolve().then(() => {{ + __microtaskLog.push('microtask-keydown'); + other.focus(); + }}); + }}); + other.addEventListener('keypress', event => {{ + __microtaskLog.push('keypress:' + event.target.id); + Promise.resolve().then(() => {{ + __microtaskLog.push('microtask-keypress'); + if ({cancel}) event.preventDefault(); + }}); + }}); + return true; + }})()"# + ) + ) + .await + ); + dispatch(&mut ctx, "keyDown", "x", "KeyX", "x").await; + assert_eq!( + evaluate_string(&mut ctx, "JSON.stringify(__microtaskLog)").await, + r#"["keydown","microtask-keydown","keypress:other","microtask-keypress"]"# + ); + assert_eq!(field_value(&mut ctx).await, ""); + assert_eq!( + evaluate_string(&mut ctx, "other.value").await, + if cancel { "" } else { "x" } + ); + } +} + +#[tokio::test(flavor = "multi_thread")] +async fn cdp_synthetic_keyboard_events_keep_microtasks_inside_the_outer_script_boundary() { + let mut ctx = keyboard_fixture("").await; + // Exercise a native input first so its temporary policy must not leak. + dispatch(&mut ctx, "keyDown", "x", "KeyX", "x").await; + install_keyboard_microtask_log(&mut ctx).await; + assert!( + evaluate_bool( + &mut ctx, + r#"(() => { + field.dispatchEvent(new KeyboardEvent('keydown', {key: 'x', bubbles: true})); + field.dispatchEvent(new KeyboardEvent('keypress', {key: 'x', bubbles: true})); + __microtaskLog.push('script-end'); + return true; + })()"# + ) + .await + ); + assert_eq!( + evaluate_string(&mut ctx, "JSON.stringify(__microtaskLog)").await, + r#"["keydown:1","keydown:2","keypress:1","keypress:2","script-end","microtask-keydown:1","microtask-keydown:2","microtask-keypress:1","microtask-keypress:2"]"# + ); +} + async fn field_value(ctx: &mut TestContext) -> String { evaluate_string( ctx, diff --git a/moli-renderer-v8/src/script_vm/input_dispatch.rs b/moli-renderer-v8/src/script_vm/input_dispatch.rs index cc3a5fbec1c..6c3272c0a54 100644 --- a/moli-renderer-v8/src/script_vm/input_dispatch.rs +++ b/moli-renderer-v8/src/script_vm/input_dispatch.rs @@ -50,7 +50,8 @@ use crate::native_bridge::element::{ text_control_set_selection_range_with_direction_internal, text_control_value, update_focus, }; use crate::native_bridge::{ - CurrentInputEvent, CurrentInputEventScope, MouseReleaseFollowUp, PointerCaptureDispatchEvent, + CurrentInputEvent, CurrentInputEventScope, MouseReleaseFollowUp, PageScriptHost, + PointerCaptureDispatchEvent, }; use crate::runtime::{ RendererDragData, RendererInputDispatchOutcome, RendererInterceptedDrag, @@ -815,6 +816,20 @@ fn dispatch_touch_pointer_boundary_events( } impl ScriptVm { + /// Native keyboard delivery has no outer JavaScript invocation. Checkpoint + /// when each outermost callback returns, including between listeners and + /// before defaults. Nested dispatchEvent() stays inside its calling script. + fn with_native_keyboard_event_scope( + &mut self, + operation: impl FnOnce(&mut v8::PinScope<'_, '_>, *mut PageScriptHost) -> Result, + ) -> Result { + self.with_default_context_scope(|scope, host_ptr| { + moli_v8_util::with_microtasks_policy(scope, v8::MicrotasksPolicy::Scoped, |scope| { + operation(scope, host_ptr) + }) + }) + } + /// Completes one JS-capable input protocol command. /// /// Entering a V8 realm only authorizes the command body; it is not a task @@ -2627,7 +2642,7 @@ impl ScriptVm { let shift = modifiers & 8 == 8; let canceled_raw_keydown = Cell::new(false); - let result = self.with_default_context_scope(|scope, runtime_ptr| { + let result = self.with_native_keyboard_event_scope(|scope, runtime_ptr| { let Some(event) = construct_keyboard_event( scope, event_name, @@ -2651,8 +2666,8 @@ impl ScriptVm { } // Combined keydown/text input includes a cancelable keypress before - // editing. Keep both events in this input turn; an explicit char - // command already dispatched keypress and must not emit it twice. + // editing. Callback cleanup checkpoints between native listeners; + // an explicit char command must not emit keypress twice. let handle = if event_name == "keydown" && should_insert_text && !text.is_empty() { // Like Blink's KeyboardEventManager, resolve focus again after // keydown listeners before targeting the character event. diff --git a/moli-v8-util/src/microtasks.rs b/moli-v8-util/src/microtasks.rs index 3bd3cf73ee9..ff3beb150ab 100644 --- a/moli-v8-util/src/microtasks.rs +++ b/moli-v8-util/src/microtasks.rs @@ -17,9 +17,34 @@ pub fn with_microtasks_scope<'s, R>( operation(microtasks.init()) } +/// Selects the checkpoint policy for a native host entry without adding a +/// JavaScript nesting scope. With Scoped policy, each outermost callback can +/// checkpoint independently; a callback invoked by JavaScript remains nested. +pub fn with_microtasks_policy<'s, R>( + scope: &mut v8::PinScope<'s, '_>, + policy: v8::MicrotasksPolicy, + operation: impl FnOnce(&mut v8::PinScope<'s, '_>) -> R, +) -> R { + let previous = scope.get_microtasks_policy(); + scope.set_microtasks_policy(policy); + let restore = MicrotasksPolicyRestore { scope, previous }; + operation(restore.scope) +} + +struct MicrotasksPolicyRestore<'a, 's, 'i> { + scope: &'a mut v8::PinScope<'s, 'i>, + previous: v8::MicrotasksPolicy, +} + +impl Drop for MicrotasksPolicyRestore<'_, '_, '_> { + fn drop(&mut self) { + self.scope.set_microtasks_policy(self.previous); + } +} + #[cfg(test)] mod tests { - use super::with_microtasks_scope; + use super::{with_microtasks_policy, with_microtasks_scope}; use moli_v8_test_util::ensure_v8; #[test] @@ -80,4 +105,49 @@ mod tests { ); }); } + + #[test] + fn scoped_host_entry_checkpoints_each_callback_and_restores_explicit_policy() { + ensure_v8(); + let mut isolate = v8::Isolate::new(v8::CreateParams::default()); + isolate.set_microtasks_policy(v8::MicrotasksPolicy::Explicit); + let scope = std::pin::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); + let source = v8::String::new( + scope, + "globalThis.log = []; (() => { log.push('callback'); Promise.resolve().then(() => log.push('microtask')); })", + ) + .unwrap(); + let script = v8::Script::compile(scope, source, None).unwrap(); + let callback = v8::Local::::try_from(script.run(scope).unwrap()).unwrap(); + + with_microtasks_policy(scope, v8::MicrotasksPolicy::Scoped, |scope| { + assert_eq!( + context + .get_microtask_queue() + .unwrap() + .get_microtasks_scope_depth(), + 0 + ); + for _ in 0..2 { + with_microtasks_scope(scope, |scope| { + let receiver = v8::undefined(scope).into(); + callback.call(scope, receiver, &[]).unwrap(); + }); + } + }); + + assert_eq!( + scope.get_microtasks_policy(), + v8::MicrotasksPolicy::Explicit + ); + let source = v8::String::new(scope, "log.join(',')").unwrap(); + let script = v8::Script::compile(scope, source, None).unwrap(); + assert_eq!( + script.run(scope).unwrap().to_rust_string_lossy(scope), + "callback,microtask,callback,microtask" + ); + } }