diff --git a/moli-renderer-v8/src/document_runtime/mutation_commands.rs b/moli-renderer-v8/src/document_runtime/mutation_commands.rs index 7bd1d3890b0..09c711339bd 100644 --- a/moli-renderer-v8/src/document_runtime/mutation_commands.rs +++ b/moli-renderer-v8/src/document_runtime/mutation_commands.rs @@ -252,21 +252,6 @@ impl DocumentRuntime { crate::native_bridge::element::handle_popover_attribute_change( scope, host_ptr, handle, namespace, local_name, old_value, new_value, ); - if namespace.is_none() - && local_name.eq_ignore_ascii_case("inert") - && old_value.is_none() - && new_value.is_some() - && self - .dom_host - .node(handle) - .and_then(Node::as_element) - .is_some_and(|element| { - element.namespace() == crate::native_bridge::document::XHTML_NS - }) - && let Some(active) = self.active_element_handle() - { - crate::native_bridge::element::schedule_focus_blur_if_needed(scope, host_ptr, active); - } } pub(crate) fn set_text_content( diff --git a/moli-renderer-v8/src/document_runtime/mutation_commands/tree/insertion.rs b/moli-renderer-v8/src/document_runtime/mutation_commands/tree/insertion.rs index 9f48c84a0e9..617233ddb61 100644 --- a/moli-renderer-v8/src/document_runtime/mutation_commands/tree/insertion.rs +++ b/moli-renderer-v8/src/document_runtime/mutation_commands/tree/insertion.rs @@ -431,9 +431,6 @@ impl DocumentRuntime { insertion_plan.insertion_roots, ); } - if is_atomic_move && let Some(active) = self.active_element_handle() { - crate::native_bridge::element::schedule_focus_blur_if_needed(scope, host_ptr, active); - } self.preserve_selectedness_for_insertion_plan(scope, host_ptr, &insertion_plan); record_dom_binding_timing( if self.dom_host.is_html_element_named(child, "script") { diff --git a/moli-renderer-v8/src/native_bridge/context_host/animation_frames.rs b/moli-renderer-v8/src/native_bridge/context_host/animation_frames.rs index b9413e06e84..a5516fe7fdb 100644 --- a/moli-renderer-v8/src/native_bridge/context_host/animation_frames.rs +++ b/moli-renderer-v8/src/native_bridge/context_host/animation_frames.rs @@ -1,5 +1,6 @@ //! Document-owned animation callbacks. A timer only wakes the rendering -//! source; one rendering task snapshots and invokes a Document's callback map. +//! source; one rendering task snapshots and invokes a Document's callback map, +//! then applies focus fixup after callback cleanup. use super::{ OwnerDispatchScope, PageScriptHost, RuntimeObservableContextToken, WindowDocumentTaskTarget, @@ -30,6 +31,7 @@ struct AnimationFrameProvider { owner: WindowExecutionContextOwner, next_handle: u32, wake_pending: bool, + focus_fixup_target: Option, handles: Vec, callbacks: HashMap, } @@ -65,12 +67,76 @@ impl AnimationFrameState { .find(|provider| provider.owner == owner) } + fn ensure_provider( + &mut self, + owner: WindowExecutionContextOwner, + dispatch_scope: OwnerDispatchScope, + ) -> &mut AnimationFrameProvider { + if !self + .providers + .iter() + .any(|provider| provider.owner == owner) + { + self.providers.push(AnimationFrameProvider { + dispatch_scope, + owner, + next_handle: 0, + wake_pending: false, + focus_fixup_target: None, + handles: Vec::new(), + callbacks: HashMap::new(), + }); + } + self.provider_mut(owner).expect("provider was inserted") + } + fn discard(&mut self, owner: WindowExecutionContextOwner) { self.providers.retain(|provider| provider.owner != owner); } } impl PageScriptHost { + /// DOM changes and focus styling can make the focused element unavailable. + /// Revalidate it at the end of a rendering update, using the same native + /// wake and exact Document owner as animation callbacks. No author timer + /// or animation-frame function participates in this internal scheduling. + pub(crate) fn queue_focused_document_fixup(&mut self, scope: &mut v8::PinScope<'_, '_>) { + let Some(active) = self.active_element_handle() else { + return; + }; + let Some(document) = self.dom_host().owner_document_handle(active) else { + return; + }; + let Some(endpoint) = self.window_endpoint_for_document(document) else { + return; + }; + let dispatch_scope = endpoint.dispatch_scope(); + let Some(owner) = self.current_window_execution_context_owner(dispatch_scope) else { + return; + }; + let Some(target) = + self.current_window_document_task_target_for_dispatch_scope(dispatch_scope) + else { + return; + }; + let provider = self.animation_frames.ensure_provider(owner, dispatch_scope); + provider.focus_fixup_target = Some(target); + if provider.wake_pending { + return; + } + let Some(binding) = + self.clone_window_execution_context_binding(scope, owner, dispatch_scope) + else { + self.animation_frames.discard(owner); + return; + }; + self.animation_frames + .provider_mut(owner) + .expect("provider was inserted") + .wake_pending = true; + self.queue_window_animation_frame_wake(scope, binding); + } + pub(crate) fn request_window_animation_frame<'s>( &mut self, scope: &mut v8::PinScope<'s, '_>, @@ -87,22 +153,9 @@ impl PageScriptHost { } // document.open() preserves this callback map and its handle counter. // Actual Window retirement removes both through the owner registry. - if self.animation_frames.provider_mut(owner).is_none() { - self.animation_frames - .providers - .push(AnimationFrameProvider { - dispatch_scope: binding.dispatch_scope(), - owner, - next_handle: 0, - wake_pending: false, - handles: Vec::new(), - callbacks: HashMap::new(), - }); - } let provider = self .animation_frames - .provider_mut(owner) - .expect("provider was inserted"); + .ensure_provider(owner, binding.dispatch_scope()); let handle = loop { provider.next_handle = provider.next_handle.wrapping_add(1); if provider.next_handle != 0 && !provider.callbacks.contains_key(&provider.next_handle) @@ -150,11 +203,6 @@ impl PageScriptHost { let Some(provider) = self.animation_frames.provider_mut(owner) else { return; }; - if provider.callbacks.is_empty() { - provider.wake_pending = false; - provider.handles.clear(); - return; - } let dispatch_scope = provider.dispatch_scope; if !self.window_execution_context_owner_is_current(owner, dispatch_scope) { self.animation_frames.discard(owner); @@ -166,6 +214,20 @@ impl PageScriptHost { self.animation_frames.discard(owner); return; }; + let provider = self + .animation_frames + .provider_mut(owner) + .expect("provider is current"); + if provider.focus_fixup_target != Some(target) { + // Unlike the Window's callback map, an old Document's pending + // focus check must not survive document.open(). + provider.focus_fixup_target = None; + } + if provider.callbacks.is_empty() && provider.focus_fixup_target.is_none() { + provider.wake_pending = false; + provider.handles.clear(); + return; + } if !self.queue_rendering_update( target, RendererPageRenderingUpdateTaskKind::AnimationFrameCallbacks, @@ -259,6 +321,27 @@ impl PageScriptHost { } invoked = true; } + // A callback can replace its Document or move focus elsewhere. The + // rendering entry must never clear focus in a replacement Document. + if self.window_document_owner_is_current_for_dispatch_scope(target.owner(), dispatch_scope) + && self + .animation_frames + .provider_mut(owner) + .is_some_and(|provider| { + if provider.focus_fixup_target == Some(target) { + provider.focus_fixup_target = None; + true + } else { + false + } + }) + { + invoked |= super::super::element::apply_document_focus_fixup( + scope, + host_ptr, + resolved.document_handle, + ); + } dispatch_scope.restore(scope, previous_scope); invoked } diff --git a/moli-renderer-v8/src/native_bridge/element.rs b/moli-renderer-v8/src/native_bridge/element.rs index ed8d085a422..86dcb8bb9c4 100644 --- a/moli-renderer-v8/src/native_bridge/element.rs +++ b/moli-renderer-v8/src/native_bridge/element.rs @@ -334,12 +334,12 @@ use focus::is_focusable; #[cfg(feature = "devtools")] pub(crate) use focus::perform_mouse_focus_default_action; pub(crate) use focus::{ - contenteditable_editing_host, focus_element, focus_text_control_preserving_selection, + apply_document_focus_fixup, contenteditable_editing_host, focus_element, focus_text_control_preserving_selection, perform_access_key_default_action_for_dispatched_event, perform_hover_interest_default_action_for_dispatched_event, perform_tab_focus_default_action_for_dispatched_event, post_parse_autofocus_is_pending, - process_post_parse_autofocus, reset_document_navigation_focus, reset_focus_from_previous_handle, - reset_focus_from_previous_handle_with_previous_focus_within, schedule_focus_blur_if_needed, + process_post_parse_autofocus, reset_document_navigation_focus, + reset_focus_from_previous_handle, reset_focus_from_previous_handle_with_previous_focus_within, update_focus, update_focus_preserving_selection, }; pub(super) use focus::{node_blur_callback, node_focus_callback}; diff --git a/moli-renderer-v8/src/native_bridge/element/focus.rs b/moli-renderer-v8/src/native_bridge/element/focus.rs index 05cbd40f934..0494d703566 100644 --- a/moli-renderer-v8/src/native_bridge/element/focus.rs +++ b/moli-renderer-v8/src/native_bridge/element/focus.rs @@ -22,6 +22,10 @@ use crate::document_runtime::{DomHandle, EventTargetHandle}; #[cfg(feature = "devtools")] use crate::runtime::RendererDomFocusOutcome; use crate::util::{node_wrapper_from_handle, v8_string, v8str}; +use crate::v8_execution_watchdog::{ + SCRIPT_TURN_WATCHDOG_TIMEOUT, V8ExecutionWatchdog, V8ExecutionWatchdogKind, + V8ExecutionWatchdogOutcome, +}; mod navigation; @@ -554,46 +558,35 @@ fn flat_tree_contains(runtime: &PageScriptHost, ancestor: DomHandle, node: DomHa false } -fn blur_if_focused_chain_is_display_none_callback( - scope: &mut v8::PinScope<'_, '_>, - _args: v8::FunctionCallbackArguments<'_>, - _rv: v8::ReturnValue<'_, v8::Value>, -) { - let Some(runtime_ptr) = crate::util::context_host_ptr_from_global_bridge(scope) else { - return; - }; - let runtime = unsafe { &*runtime_ptr }; - let Some(active) = runtime.active_element_handle() else { - return; - }; - if focused_chain_requires_async_blur(runtime, active) { - update_focus(scope, runtime_ptr, None); - } -} - -pub(crate) fn schedule_focus_blur_if_needed( +pub(crate) fn apply_document_focus_fixup( scope: &mut v8::PinScope<'_, '_>, runtime_ptr: *mut PageScriptHost, - active: DomHandle, -) { + document: DomHandle, +) -> bool { let runtime = unsafe { &*runtime_ptr }; - if !focused_chain_requires_async_blur(runtime, active) { - return; - } - if let Some(callback) = v8::Function::new(scope, blur_if_focused_chain_is_display_none_callback) + let Some(active) = runtime.active_element_handle() else { + return false; + }; + if runtime.dom_host().owner_document_handle(active) != Some(document) + || is_focusable(runtime, active) { - let global = scope.get_current_context().global(scope); - let Some(set_timeout) = global - .get(scope, v8str(scope, "setTimeout").into()) - .and_then(|value| v8::Local::::try_from(value).ok()) - else { - crate::util::enqueue_host_microtask(scope, callback); - return; - }; - let delay = v8::Integer::new(scope, 0); - let args = [callback.into(), delay.into()]; - let _ = set_timeout.call(scope, global.into(), &args); + return false; } + // The ordinary focus transition owns events, text-control change commits, + // viewport fallback, and retention of the sequential navigation origin. + // This runs outside an author animation callback or timer. Its change/blur + // handlers and cleanup microtasks still need their own execution budget. + let watchdog = V8ExecutionWatchdog::arm( + V8ExecutionWatchdogKind::FocusFixup, + scope.thread_safe_handle(), + SCRIPT_TURN_WATCHDOG_TIMEOUT, + ); + update_focus(scope, runtime_ptr, None); + crate::script_cleanup::perform_callback_cleanup_checkpoint(scope); + if watchdog.disarm() == V8ExecutionWatchdogOutcome::TimedOut { + tracing::warn!("focus fixup exceeded its execution deadline"); + } + true } fn wrap_handle_value<'s>( @@ -900,7 +893,7 @@ fn update_focus_from_previous_with_previous_focus_within( if unsafe { &*runtime_ptr }.active_element_handle() != Some(next_handle) { return; } - schedule_focus_blur_if_needed(scope, runtime_ptr, next_handle); + unsafe { &mut *runtime_ptr }.queue_focused_document_fixup(scope); } if let Some((_, next_window)) = window_focus_transition { dispatch_window_focus_event(scope, runtime_ptr, next_window, "focus"); diff --git a/moli-renderer-v8/src/native_bridge/element/forms.rs b/moli-renderer-v8/src/native_bridge/element/forms.rs index a1fddc6ce49..73d7f582549 100644 --- a/moli-renderer-v8/src/native_bridge/element/forms.rs +++ b/moli-renderer-v8/src/native_bridge/element/forms.rs @@ -31,7 +31,7 @@ use super::{ element_has_attribute, html_element_getter_receiver, html_element_setter_receiver, parse_non_negative_dimension, property_usv_string_value, reflected_element_attribute_handle, resolve_url_like_attribute, set_attribute_property_on_object_or_detached, - set_reflected_attribute, set_reflected_boolean_attribute, update_focus, + set_reflected_attribute, set_reflected_boolean_attribute, }; use std::str::FromStr; diff --git a/moli-renderer-v8/src/native_bridge/element/forms/owner.rs b/moli-renderer-v8/src/native_bridge/element/forms/owner.rs index 44ab05be7cd..f1e39da6367 100644 --- a/moli-renderer-v8/src/native_bridge/element/forms/owner.rs +++ b/moli-renderer-v8/src/native_bridge/element/forms/owner.rs @@ -109,21 +109,6 @@ pub(crate) fn form_control_is_effectively_disabled( || dom.disabled_fieldset_ancestor(handle).is_some())) } -pub(super) fn node_contains( - runtime: &PageScriptHost, - ancestor: DomHandle, - node: DomHandle, -) -> bool { - let mut current = Some(node); - while let Some(handle) = current { - if handle == ancestor { - return true; - } - current = runtime.dom_host().parent_node(handle); - } - false -} - pub(in crate::native_bridge) fn form_associated_form_getter_function<'s>( scope: &mut v8::PinScope<'s, '_>, args: v8::FunctionCallbackArguments<'s>, diff --git a/moli-renderer-v8/src/native_bridge/element/forms/simple_controls.rs b/moli-renderer-v8/src/native_bridge/element/forms/simple_controls.rs index 128fc30a191..52c84031f8d 100644 --- a/moli-renderer-v8/src/native_bridge/element/forms/simple_controls.rs +++ b/moli-renderer-v8/src/native_bridge/element/forms/simple_controls.rs @@ -229,18 +229,6 @@ pub(in crate::native_bridge) fn fieldset_disabled_setter_function<'s>( "disabled", args.get(0).boolean_value(scope), ); - let runtime = unsafe { &*runtime_ptr }; - if runtime - .dom_host() - .node(handle) - .and_then(Node::as_element) - .is_some_and(|element| element.has_attribute("disabled")) - && runtime - .active_element_handle() - .is_some_and(|active| node_contains(runtime, handle, active)) - { - update_focus(scope, runtime_ptr, None); - } rv.set_undefined(); } @@ -624,8 +612,6 @@ pub(in crate::native_bridge) fn output_default_value_setter_function<'s>( rv.set_undefined(); } -use super::owner::node_contains; - fn legend_fieldset_ancestor(runtime: &PageScriptHost, handle: DomHandle) -> Option { let mut current = runtime.dom_host().parent_node(handle); while let Some(parent) = current { diff --git a/moli-renderer-v8/src/script_vm/tests/dom_xhr/shadow_dom.rs b/moli-renderer-v8/src/script_vm/tests/dom_xhr/shadow_dom.rs index 5178e56117b..250a04c64cf 100644 --- a/moli-renderer-v8/src/script_vm/tests/dom_xhr/shadow_dom.rs +++ b/moli-renderer-v8/src/script_vm/tests/dom_xhr/shadow_dom.rs @@ -2477,10 +2477,12 @@ fn focus_pseudo_matches_wpt_shadow_host_matrix() { assert_eq!(result, ""); } #[tokio::test] -async fn focused_display_none_shadow_host_blurs_on_timer_task() { +async fn focused_display_none_shadow_host_blurs_during_rendering_update() { let loader = ResourceRequestClient::new(&moli_fetch::FetchConfig::default()).expect("loader"); - let mut vm = - new_storage_test_vm_with_loader("https://shadow-focus-display-none-blur.test/", &loader); + let mut vm = new_storage_page_task_executor_test_vm_with_loader( + "https://shadow-focus-display-none-blur.test/", + &loader, + ); let plain_sync_state = vm .eval( @@ -2517,11 +2519,9 @@ async fn focused_display_none_shadow_host_blurs_on_timer_task() { ) .expect("plain display:none focus setup should evaluate"); - assert!( - vm.run_next_due_timer_callback_for_test(&loader) - .await - .expect("plain display:none focus blur timer should run") - ); + vm.advance_timers_until_deadline_for_test(&loader) + .await + .expect("plain display:none focus fixup should run during rendering"); let plain_async_state = vm .eval( @@ -2560,11 +2560,9 @@ async fn focused_display_none_shadow_host_blurs_on_timer_task() { ) .expect("delegated display:none focus setup should evaluate"); - assert!( - vm.run_next_due_timer_callback_for_test(&loader) - .await - .expect("delegated display:none focus blur timer should run") - ); + vm.advance_timers_until_deadline_for_test(&loader) + .await + .expect("delegated display:none focus fixup should run during rendering"); let delegated_async_state = vm .eval( @@ -2587,7 +2585,10 @@ async fn focused_display_none_shadow_host_blurs_on_timer_task() { #[tokio::test] async fn focused_display_none_blur_listener_sees_updated_focus_state() { let loader = ResourceRequestClient::new(&moli_fetch::FetchConfig::default()).expect("loader"); - let mut vm = new_storage_test_vm_with_loader("https://shadow-focus-blur-order.test/", &loader); + let mut vm = new_storage_page_task_executor_test_vm_with_loader( + "https://shadow-focus-blur-order.test/", + &loader, + ); let sync_state = vm .eval( @@ -2631,15 +2632,9 @@ async fn focused_display_none_blur_listener_sees_updated_focus_state() { ) .expect("display none focus setup should evaluate"); - assert!( - vm.apply_next_connected_style_event_body_for_test(), - "the inline setup stylesheet queues its own event body before focus-update work" - ); - assert!( - vm.run_next_due_timer_callback_for_test(&loader) - .await - .expect("exact display-none focus blur timer should run") - ); + vm.advance_timers_until_deadline_for_test(&loader) + .await + .expect("the production executor should deliver style events and rendering focus fixup"); let blur_state = vm .eval( @@ -2659,8 +2654,10 @@ async fn focused_display_none_blur_listener_sees_updated_focus_state() { #[tokio::test] async fn focused_element_blurs_after_it_becomes_inert() { let loader = ResourceRequestClient::new(&moli_fetch::FetchConfig::default()).expect("loader"); - let mut vm = - new_storage_test_vm_with_loader("https://dynamic-inert-focus-fixup.test/", &loader); + let mut vm = new_storage_page_task_executor_test_vm_with_loader( + "https://dynamic-inert-focus-fixup.test/", + &loader, + ); let direct_sync_state = vm .eval( @@ -2682,11 +2679,9 @@ async fn focused_element_blurs_after_it_becomes_inert() { ) .expect("direct inert focus setup should evaluate"); - assert!( - vm.run_next_due_timer_callback_for_test(&loader) - .await - .expect("direct inert focus-fixup timer should run") - ); + vm.advance_timers_until_deadline_for_test(&loader) + .await + .expect("direct inert focus fixup should run during rendering"); let direct_async_state = vm .eval( r#" @@ -2709,11 +2704,9 @@ async fn focused_element_blurs_after_it_becomes_inert() { ) .expect("ancestor inert focus setup should evaluate"); - assert!( - vm.run_next_due_timer_callback_for_test(&loader) - .await - .expect("ancestor inert focus-fixup timer should run") - ); + vm.advance_timers_until_deadline_for_test(&loader) + .await + .expect("ancestor inert focus fixup should run during rendering"); let ancestor_async_state = vm .eval( r#" diff --git a/moli-renderer-v8/src/script_vm/tests/rendering_update.rs b/moli-renderer-v8/src/script_vm/tests/rendering_update.rs index 105f46ae52d..8337ba508e6 100644 --- a/moli-renderer-v8/src/script_vm/tests/rendering_update.rs +++ b/moli-renderer-v8/src/script_vm/tests/rendering_update.rs @@ -1,6 +1,160 @@ use super::{ChildFrameSemanticTurnKind, new_storage_page_task_executor_test_vm}; use crate::network::ResourceRequestClient; +#[tokio::test(flavor = "current_thread")] +async fn focus_fixup_bounds_runaway_blur_handlers_and_their_microtasks() { + use crate::v8_execution_watchdog::{V8ExecutionWatchdog, V8ExecutionWatchdogKind}; + + let _budget = V8ExecutionWatchdog::override_timeout_for_test( + V8ExecutionWatchdogKind::FocusFixup, + std::time::Duration::from_millis(50), + ); + let loader = ResourceRequestClient::new(&moli_fetch::FetchConfig::default()).expect("loader"); + for runaway in [ + "while (true) {}", + "queueMicrotask(() => { while (true) {} });", + ] { + let mut vm = new_storage_page_task_executor_test_vm("https://focus-fixup-watchdog.test/"); + vm.eval(&format!( + r#" +const root = document.documentElement || document.appendChild(document.createElement('html')); +const body = document.body || root.appendChild(document.createElement('body')); +const button = body.appendChild(document.createElement('button')); +globalThis.__blurCount = 0; +button.addEventListener('blur', () => {{ + __blurCount++; + {runaway} +}}); +button.focus(); +button.hidden = true; +"# + )) + .expect("queue native focus fixup without an author timer or frame callback"); + vm.advance_timers_until_deadline_for_test(&loader) + .await + .expect("runaway focus event work must return control to the Page executor"); + assert_eq!( + vm.eval("[__blurCount, document.activeElement === document.body, 6 * 7].join('|')") + .expect("the isolate must recover after focus fixup termination"), + "1|true|42", + "{runaway}" + ); + } +} + +#[tokio::test(flavor = "current_thread")] +async fn focus_fixup_revalidates_the_document_after_animation_callbacks() { + let loader = ResourceRequestClient::new(&moli_fetch::FetchConfig::default()).expect("loader"); + let mut vm = new_storage_page_task_executor_test_vm("https://focus-fixup-rendering.test/"); + let count = vm + .eval(include_str!("../../../tests/fixtures/focus-fixup.js")) + .expect("focus fixup scenarios") + .parse::() + .unwrap(); + for index in 0..count { + let name = vm + .eval(&format!("__focusFixup.setup({index})")) + .expect("set up focus loss without invoking author timer getters"); + vm.advance_timers_until_deadline_for_test(&loader) + .await + .expect("native rendering opportunities should settle focus fixup"); + let result = vm.eval("JSON.stringify(__focusFixup.snapshot())").unwrap(); + let result: serde_json::Value = serde_json::from_str(&result).unwrap(); + for phase in ["sync", "microtask"] { + assert_eq!(result[phase], result["expectedBefore"], "{name}: {result}"); + } + assert_eq!(result["frame"], result["expectedFrame"], "{name}: {result}"); + assert_eq!(result["final"], result["expected"], "{name}: {result}"); + assert_eq!(result["timerGets"], 0, "{name}: {result}"); + let events = result["events"].as_array().unwrap(); + if result["expected"] == "focus" { + assert!(events.is_empty(), "{name}: {result}"); + } else { + assert_eq!( + events.first().map(|e| &e["type"]), + Some(&serde_json::json!("blur")), + "{name}: {result}" + ); + assert!( + events.iter().all(|e| e["trusted"] == true), + "{name}: {result}" + ); + if result["expected"] == "BODY" { + assert_eq!(events.len(), 2, "{name}: {result}"); + assert!( + events.iter().all(|e| e["nullRelatedTarget"] == true), + "{name}: {result}" + ); + } + } + } +} + +#[tokio::test(flavor = "current_thread")] +async fn focus_fixup_keeps_document_replacement_and_child_retirement_boundaries() { + let loader = ResourceRequestClient::new(&moli_fetch::FetchConfig::default()).expect("loader"); + let mut vm = new_storage_page_task_executor_test_vm("https://focus-fixup-owner.test/"); + vm.eval( + r#" +const root = document.documentElement || document.appendChild(document.createElement('html')); +const body = document.body || root.appendChild(document.createElement('body')); +body.innerHTML = ''; +globalThis.__focusFixupLifecycle = []; +const old = document.getElementById('old'); +old.focus(); +old.disabled = true; +requestAnimationFrame(() => { + __focusFixupLifecycle.push('old-frame:' + document.activeElement.id); + document.open(); + document.write(''); + document.close(); + const replacement = document.getElementById('replacement'); + replacement.focus(); + replacement.addEventListener('blur', () => __focusFixupLifecycle.push('replacement-blur')); + replacement.disabled = true; + requestAnimationFrame(() => { + __focusFixupLifecycle.push('replacement-frame:' + document.activeElement.id); + requestAnimationFrame(() => __focusFixupLifecycle.push(document.activeElement.tagName)); + }); +}); +"#, + ) + .expect("queue fixup across document.open in an animation callback"); + vm.advance_timers_until_deadline_for_test(&loader) + .await + .expect("replacement Document should receive its own rendering update"); + assert_eq!( + vm.eval("__focusFixupLifecycle.join('|')").unwrap(), + "old-frame:old|replacement-frame:replacement|replacement-blur|BODY" + ); + + vm.eval( + r#" +document.body.innerHTML = ''; +const retired = document.getElementById('retired'); +const child = retired.contentWindow; +child.document.body.innerHTML = ''; +const childFocus = child.document.getElementById('child-focus'); +childFocus.focus(); +childFocus.disabled = true; +childFocus.addEventListener('blur', () => __focusFixupLifecycle.push('child-blur')); +child.requestAnimationFrame(() => __focusFixupLifecycle.push('retired-child-frame')); +retired.remove(); +document.getElementById('parent-focus').focus(); +__focusFixupLifecycle.length = 0; +"#, + ) + .expect("retire a child with focus fixup and callbacks pending"); + vm.advance_timers_until_deadline_for_test(&loader) + .await + .expect("retired child work should be discarded"); + assert_eq!(vm.eval("__focusFixupLifecycle.join('|')").unwrap(), ""); + assert_eq!( + vm.eval("document.activeElement.id").unwrap(), + "parent-focus" + ); +} + #[tokio::test(flavor = "current_thread")] async fn window_scroll_coalesces_into_one_rendering_update_without_a_timer() { let loader = ResourceRequestClient::new(&moli_fetch::FetchConfig::default()).expect("loader"); diff --git a/moli-renderer-v8/src/v8_execution_watchdog.rs b/moli-renderer-v8/src/v8_execution_watchdog.rs index 810aa2ef215..3f56f6e7ae7 100644 --- a/moli-renderer-v8/src/v8_execution_watchdog.rs +++ b/moli-renderer-v8/src/v8_execution_watchdog.rs @@ -28,6 +28,7 @@ pub(crate) enum V8ExecutionWatchdogKind { TimerCallback, AnimationFrameCallback, LifecycleEvent, + FocusFixup, } #[cfg(test)] @@ -38,6 +39,7 @@ impl V8ExecutionWatchdogKind { Self::TimerCallback => 1, Self::LifecycleEvent => 2, Self::AnimationFrameCallback => 3, + Self::FocusFixup => 4, } } } @@ -45,8 +47,8 @@ impl V8ExecutionWatchdogKind { #[cfg(test)] std::thread_local! { static V8_EXECUTION_WATCHDOG_TIMEOUT_OVERRIDES: - std::cell::Cell<[Option; 4]> = - const { std::cell::Cell::new([None, None, None, None]) }; + std::cell::Cell<[Option; 5]> = + const { std::cell::Cell::new([None, None, None, None, None]) }; } #[cfg(test)] diff --git a/moli-renderer-v8/src/webidl_callback_source_boundary_tests.rs b/moli-renderer-v8/src/webidl_callback_source_boundary_tests.rs index 94db54fa1ee..6ead2b5646a 100644 --- a/moli-renderer-v8/src/webidl_callback_source_boundary_tests.rs +++ b/moli-renderer-v8/src/webidl_callback_source_boundary_tests.rs @@ -225,11 +225,6 @@ const DIRECT_V8_CALL_ALLOWLIST: &[AllowedDirectCallFile] = &[ 2, DirectCallOwner::NativeForwardingOrScript, ), - allowed( - "native_bridge/element/focus.rs", - 1, - DirectCallOwner::NativeForwardingOrScript, - ), allowed( "script_vm/frame_script_jobs.rs", 1, diff --git a/moli-renderer-v8/tests/fixtures/focus-fixup.js b/moli-renderer-v8/tests/fixtures/focus-fixup.js new file mode 100644 index 00000000000..fa2893b8396 --- /dev/null +++ b/moli-renderer-v8/tests/fixtures/focus-fixup.js @@ -0,0 +1,132 @@ +(() => { + if (!document.documentElement) document.appendChild(document.createElement('html')); + if (!document.body) document.documentElement.appendChild(document.createElement('body')); + const cases = []; + const button = ''; + const add = (name, change, html = button, extra = {}) => + cases.push({name, change, html, expected: 'BODY', ...extra}); + + add('disabled property', c => { c.focus.disabled = true; }); + add('disabled attribute', c => c.focus.setAttribute('disabled', '')); + add('fieldset disabled property', c => { c.focus.parentNode.disabled = true; }, + '
' + button + '
'); + add('fieldset disabled attribute', c => c.focus.parentNode.setAttribute('disabled', ''), + '
' + button + '
'); + add('first legend stays enabled', c => { c.root.querySelector('fieldset').disabled = true; }, + '
' + button + '
', {expected: 'focus'}); + add('replacing the first legend disables the control', c => { + const fieldset = c.root.querySelector('fieldset'); + fieldset.prepend(document.createElement('legend')); + }, '
' + button + '
'); + add('input becomes hidden', c => { c.focus.type = 'hidden'; }, ''); + add('tabindex removed', c => c.focus.removeAttribute('tabindex'), '
focus
'); + add('negative tabindex stays focusable', c => { c.focus.tabIndex = -1; }, button, {expected: 'focus'}); + add('readonly stays focusable', c => { c.focus.readOnly = true; }, '', {expected: 'focus'}); + add('editing host becomes uneditable', c => { c.focus.contentEditable = 'false'; }, + '
focus
'); + add('anchor loses href', c => c.focus.removeAttribute('href'), 'focus'); + add('hidden attribute', c => { c.focus.hidden = true; }); + add('display none', c => { c.focus.style.display = 'none'; }); + add('visibility hidden', c => { c.focus.style.visibility = 'hidden'; }); + add('hidden ancestor', c => { c.focus.parentNode.hidden = true; }, '
' + button + '
'); + add('inert ancestor', c => { c.focus.parentNode.inert = true; }, '
' + button + '
'); + add('inert control', c => { c.focus.inert = true; }); + add('class hides control', c => { c.focus.className = 'hidden-control'; }, + '' + button); + add('unrelated disabled sibling', c => { c.other.disabled = true; }, button, {expected: 'focus'}); + add('reenabled before rendering', c => { c.focus.disabled = true; c.focus.disabled = false; }, button, {expected: 'focus'}); + add('unhidden before rendering', c => { c.focus.hidden = true; c.focus.hidden = false; }, button, {expected: 'focus'}); + add('reenabled in animation callback', c => { c.focus.disabled = true; }, button, + {expected: 'focus', duringFrame: c => { c.focus.disabled = false; }}); + add('focus moves before rendering', c => { c.focus.disabled = true; c.other.focus(); }, button, + {before: 'other', expected: 'other'}); + add('focus moves in animation callback', c => { c.focus.disabled = true; }, button, + {frame: 'other', expected: 'other', duringFrame: c => c.other.focus()}); + add('blur handler moves focus', c => { + c.focus.addEventListener('blur', () => c.other.focus(), {once: true}); + c.focus.disabled = true; + }, button, {expected: 'other', reentrant: true}); + for (const mode of ['open', 'closed']) { + for (const changeHost of [false, true]) { + add(`${mode} shadow ${changeHost ? 'inert host' : 'disabled control'}`, c => { + if (changeHost) c.host.inert = true; + else c.focus.disabled = true; + }, '
', {prepare(c) { + c.host = c.root.querySelector('#host'); + const shadow = c.host.attachShadow({mode}); + shadow.innerHTML = button; + c.shadows.push(shadow); + c.focus = shadow.firstChild; + }}); + } + } + add('child document disabled from its parent realm', c => { c.focus.disabled = true; }, + '', {prepare(c) { + c.window = c.root.firstChild.contentWindow; + c.window.document.body.innerHTML = button; + c.focus = c.window.document.getElementById('focus'); + }}); + let current; + const active = c => { + let element = c.window.document.activeElement; + for (;;) { + const shadow = c.shadows.find(root => root.host === element); + if (!shadow?.activeElement) break; + element = shadow.activeElement; + } + return element?.id || element?.tagName || null; + }; + globalThis.__focusFixup = { + names: cases.map(c => c.name), + setup(index) { + document.body.innerHTML = '
'; + const item = cases[index]; + const c = {window, root: document.getElementById('root'), other: document.getElementById('other'), shadows: [], events: [], timerGets: 0}; + c.root.innerHTML = item.html; + c.focus = c.root.querySelector('#focus'); + item.prepare?.(c); + c.focus.focus(); + if (active(c) !== 'focus') throw new Error('initial focus failed: ' + item.name); + for (const type of ['blur', 'focusout']) c.focus.addEventListener(type, event => { + c.events.push({type, trusted: event.isTrusted, nullRelatedTarget: event.relatedTarget === null}); + }); + const raf = c.window.requestAnimationFrame.bind(c.window); + const descriptors = new Map(); + for (const name of ['setTimeout', 'requestAnimationFrame']) { + descriptors.set(name, Object.getOwnPropertyDescriptor(c.window, name)); + Object.defineProperty(c.window, name, {configurable: true, get() { + c.timerGets++; + throw new Error('focus fixup accessed author ' + name); + }}); + } + c.restore = () => { + for (const [name, descriptor] of descriptors) Object.defineProperty(c.window, name, descriptor); + }; + current = c; + try { + item.change(c); + c.sync = active(c); + c.expectedBefore = item.before || 'focus'; + c.expectedFrame = item.frame || c.expectedBefore; + c.expected = item.expected; + c.reentrant = !!item.reentrant; + c.done = new Promise(resolve => raf(() => { + item.duringFrame?.(c); + c.frame = active(c); + raf(() => { c.final = active(c); c.restore(); resolve(); }); + })); + queueMicrotask(() => { c.microtask = active(c); }); + } catch (error) { c.restore(); throw error; } + return item.name; + }, + done() { return current.done; }, + snapshot() { + const c = current; + return {sync: c.sync, microtask: c.microtask, frame: c.frame, final: c.final, + expectedBefore: c.expectedBefore, expectedFrame: c.expectedFrame, + expected: c.expected, events: c.events, timerGets: c.timerGets, + reentrant: c.reentrant}; + }, + }; + return cases.length; +})() diff --git a/moli-wpt-compat/fixtures/wpt/manifest.toml b/moli-wpt-compat/fixtures/wpt/manifest.toml index 61c73d71490..f3e65464c73 100644 --- a/moli-wpt-compat/fixtures/wpt/manifest.toml +++ b/moli-wpt-compat/fixtures/wpt/manifest.toml @@ -18246,7 +18246,7 @@ source = "upstream-wpt" source_path = "html/semantics/forms/the-fieldset-element/disabled-003.html" source_commit = "59c8d70847593453e2e611b184d6e9072a527ba0" tags = ["forms", "html", "fieldset", "focus"] -notes = "Imported upstream WPT disabled nested fieldset focus cleanup coverage." +notes = "Imported upstream WPT disabled nested fieldset focus cleanup coverage. Local timing adaptation follows HTML update-the-rendering focus fixup: assert focus is retained synchronously, then moves to the viewport after animation callbacks. The upstream copy still assumes synchronous blur." [[test]] id = "upstream-html-semantics-forms-the-fieldset-element-fieldset-checkvalidity" diff --git a/moli-wpt-compat/fixtures/wpt/upstream/html/semantics/forms/the-fieldset-element/disabled-003.html b/moli-wpt-compat/fixtures/wpt/upstream/html/semantics/forms/the-fieldset-element/disabled-003.html index de01eb57fcc..9eeb8a6f2d4 100644 --- a/moli-wpt-compat/fixtures/wpt/upstream/html/semantics/forms/the-fieldset-element/disabled-003.html +++ b/moli-wpt-compat/fixtures/wpt/upstream/html/semantics/forms/the-fieldset-element/disabled-003.html @@ -2,6 +2,7 @@ Disable nested fieldsets with focused element + @@ -17,23 +18,34 @@
-