From b24dcff4b45e680ff4cd131e9f362ef65c5e9168 Mon Sep 17 00:00:00 2001 From: ldm0 Date: Sat, 26 Sep 2026 02:38:51 +0800 Subject: [PATCH] fix(focus): schedule late autofocus candidates --- .../src/document_runtime/dom_facade.rs | 8 +- .../tree/insertion_followups.rs | 12 +- .../context_host/rendering_updates.rs | 8 +- .../src/native_bridge/element/focus.rs | 8 +- .../rendering_update/update_lifecycle.rs | 151 ++++++++++++++++++ 5 files changed, 177 insertions(+), 10 deletions(-) diff --git a/moli-renderer-v8/src/document_runtime/dom_facade.rs b/moli-renderer-v8/src/document_runtime/dom_facade.rs index d98347105a0..12f61eb1fee 100644 --- a/moli-renderer-v8/src/document_runtime/dom_facade.rs +++ b/moli-renderer-v8/src/document_runtime/dom_facade.rs @@ -809,12 +809,14 @@ impl DocumentRuntime { &self.autofocus_candidates } - pub(crate) fn queue_autofocus_candidates_in_subtrees(&mut self, roots: &[DomHandle]) { + /// Returns whether this insertion added or reordered an autofocus candidate. + pub(crate) fn queue_autofocus_candidates_in_subtrees(&mut self, roots: &[DomHandle]) -> bool { if self.autofocus_processed { - return; + return false; } let document = self.dom_host.document_handle(); let mut pending = roots.iter().rev().copied().collect::>(); + let mut queued = false; while let Some(handle) = pending.pop() { if self.dom_host.is_connected(handle) && self.dom_host.owner_document_handle(handle) == Some(document) @@ -827,9 +829,11 @@ impl DocumentRuntime { self.autofocus_candidates .retain(|candidate| *candidate != handle); self.autofocus_candidates.push(handle); + queued = true; } pending.extend(self.dom_host.child_handles_reversed(handle)); } + queued } pub(crate) fn mark_autofocus_processed(&mut self) { diff --git a/moli-renderer-v8/src/document_runtime/mutation_commands/tree/insertion_followups.rs b/moli-renderer-v8/src/document_runtime/mutation_commands/tree/insertion_followups.rs index d09b0e2cb84..96a16190dd7 100644 --- a/moli-renderer-v8/src/document_runtime/mutation_commands/tree/insertion_followups.rs +++ b/moli-renderer-v8/src/document_runtime/mutation_commands/tree/insertion_followups.rs @@ -19,7 +19,8 @@ impl DocumentRuntime { insertion_plan: &TreeInsertionPlan<'_>, profile: TreeMutationSourceProfile, ) { - self.queue_autofocus_candidates_in_subtrees(insertion_plan.insertion_roots); + let queued_autofocus_candidate = + self.queue_autofocus_candidates_in_subtrees(insertion_plan.insertion_roots); let attribute_reaction_policy = match profile.reaction_policy { TreeReactionDispatchPolicy::DispatchNow => AttributeChangedReactionPolicy::DispatchNow, TreeReactionDispatchPolicy::AppendToCurrentQueue => { @@ -50,6 +51,15 @@ impl DocumentRuntime { ); } } + // Parser-time candidates use the DOMContentLoaded admission. Later + // insertions need another rendering update, including those made + // while subresources still delay load or from a load listener. + if queued_autofocus_candidate + && self.dom_content_loaded_dispatched() + && let Some(owner) = unsafe { &*host_ptr }.current_main_document_task_owner() + { + let _ = unsafe { &mut *host_ptr }.queue_main_document_post_parse_autofocus(owner); + } } pub(super) fn dispatch_tree_insertion_pre_reaction_followups_after_change( diff --git a/moli-renderer-v8/src/native_bridge/context_host/rendering_updates.rs b/moli-renderer-v8/src/native_bridge/context_host/rendering_updates.rs index ba89d207bb0..4de4adde71a 100644 --- a/moli-renderer-v8/src/native_bridge/context_host/rendering_updates.rs +++ b/moli-renderer-v8/src/native_bridge/context_host/rendering_updates.rs @@ -28,7 +28,7 @@ pub(super) struct PendingEnvironmentChange { pub(crate) enum PostParseAutofocusAdmission { /// The exact lifecycle owner was replaced before admission. StaleOwner, - /// Focus already exists or the Document has no eligible candidate. + /// Autofocus is processed, focus already exists, or no candidates remain. NotNeeded, /// One exact rendering-update entry owns the pending flush. Published, @@ -44,10 +44,10 @@ pub(super) type RenderingUpdateState = ExactWindowDocumentTaskLedger< impl PageScriptHost { /// Publish post-parse autofocus as a rendering update for the exact main - /// Document that just completed DOMContentLoaded. + /// Document after DOMContentLoaded or a subsequent candidate insertion. /// - /// DOMContentLoaded listeners and their microtasks run before this - /// admission. Re-checking the exact owner here prevents a listener's + /// The DOMContentLoaded completion caller admits after its listeners and + /// microtasks. Re-checking the exact owner here prevents a listener's /// `document.open()` from retargeting old lifecycle work to the replacement /// Document. pub(crate) fn queue_main_document_post_parse_autofocus( diff --git a/moli-renderer-v8/src/native_bridge/element/focus.rs b/moli-renderer-v8/src/native_bridge/element/focus.rs index 7159d1b2d2d..3d72ab8e45e 100644 --- a/moli-renderer-v8/src/native_bridge/element/focus.rs +++ b/moli-renderer-v8/src/native_bridge/element/focus.rs @@ -444,10 +444,12 @@ fn first_autofocus_candidate(runtime: &PageScriptHost) -> Option { /// Whether the current Document has post-parse autofocus work worth /// admitting to the rendering-update task source. /// -/// The selected rendering task checks whether the Document still has author -/// focus. Script can blur that element between admission and execution. +/// Do not check candidate focusability here: the inserting script can enable +/// or reveal an element before the rendering task runs. The selected task +/// resolves the candidate because script can also remove it or move focus +/// between publication and execution. pub(crate) fn post_parse_autofocus_is_pending(runtime: &PageScriptHost) -> bool { - !runtime.autofocus_processed() && first_autofocus_candidate(runtime).is_some() + !runtime.autofocus_processed() && !runtime.autofocus_candidates().is_empty() } pub(crate) fn process_post_parse_autofocus( diff --git a/moli-renderer-v8/src/runtime/page_vm/tests/rendering_update/update_lifecycle.rs b/moli-renderer-v8/src/runtime/page_vm/tests/rendering_update/update_lifecycle.rs index a26462137b3..ec7c23c1fe6 100644 --- a/moli-renderer-v8/src/runtime/page_vm/tests/rendering_update/update_lifecycle.rs +++ b/moli-renderer-v8/src/runtime/page_vm/tests/rendering_update/update_lifecycle.rs @@ -75,6 +75,157 @@ defaultFocus.addEventListener("focus", () => { .expect("post-parse autofocus rendering-update test should run"); } +#[tokio::test(flavor = "current_thread")] +async fn late_autofocus_insertion_queues_a_rendering_update_across_load_boundaries() { + run_page_vm_async_test(async move { + let loader = + crate::network::ResourceRequestClient::new(&FetchConfig::default()).expect("loader"); + for phase in ["before-load", "load-listener", "after-load"] { + let document_url = Url::parse("https://example.com/late-autofocus").unwrap(); + let (mut page_vm, _resource_source, _owner_wake_rx) = + page_vm_with_bound_task_sources_and_owner_wake(&loader, document_url); + + let owner = + dispatch_main_document_domcontentloaded_for_rendering_test(&mut page_vm).await?; + assert!( + page_vm + .claim_exact_selected_page_task_for_test( + PageSelectedTaskTestSelector::RenderingUpdate, + ) + .is_none(), + "a Document without candidates has no autofocus rendering task" + ); + + page_vm.vm_mut().eval( + r#" +let lateFocus; +function insertLateAutofocus() { + lateFocus = document.createElement('input'); + lateFocus.autofocus = true; + lateFocus.disabled = true; + document.body.appendChild(lateFocus); + // Focusability must be resolved after the inserting task's checkpoint. + Promise.resolve().then(() => { lateFocus.disabled = false; }); +} +"installed" +"#, + )?; + if phase == "load-listener" { + page_vm + .vm_mut() + .eval("addEventListener('load', insertLateAutofocus, {once: true})")?; + } + if phase != "before-load" { + execute_main_document_lifecycle_on_owner_local_task( + &mut page_vm, + MainDocumentLifecycleBody::WindowLoad { owner }, + ) + .await?; + assert_eq!(page_vm.vm_mut().eval("document.readyState")?, "complete"); + } else { + assert_eq!(page_vm.vm_mut().eval("document.readyState")?, "interactive"); + } + if phase != "load-listener" { + page_vm.vm_mut().eval("insertLateAutofocus()")?; + } + assert_eq!( + page_vm + .vm_mut() + .eval("document.activeElement === lateFocus")?, + "false", + "{phase}: insertion must queue autofocus instead of focusing synchronously" + ); + + let claimed = page_vm + .claim_exact_selected_page_task_for_test( + PageSelectedTaskTestSelector::RenderingUpdate, + ) + .unwrap_or_else(|| panic!("{phase}: insertion should publish the late candidate")); + let (selected_owner, selected_kind) = claimed + .rendering_update_owner_and_kind() + .expect("rendering selector must retain the exact task identity"); + assert_eq!( + selected_owner.target().owner(), + crate::native_bridge::WindowDocumentOwner::Frame(owner) + ); + assert_eq!( + selected_kind, + RendererPageRenderingUpdateTaskKind::PostParseAutofocus + ); + page_vm + .run_claimed_selected_page_task_for_test(claimed, &loader) + .await?; + assert_eq!( + page_vm + .vm_mut() + .eval("document.activeElement === lateFocus")?, + "true", + "{phase}: an input enabled before the rendering update must receive focus" + ); + } + Ok::<_, anyhow::Error>(()) + }) + .await + .expect("late autofocus rendering-update test should run"); +} + +#[tokio::test(flavor = "current_thread")] +async fn late_autofocus_rendering_update_coalesces_and_rechecks_candidates() { + run_page_vm_async_test(async move { + let loader = + crate::network::ResourceRequestClient::new(&FetchConfig::default()).expect("loader"); + for mutation in ["first.remove()", "manual.focus()"] { + let document_url = Url::parse("https://example.com/late-autofocus-recheck").unwrap(); + let (mut page_vm, _resource_source, _owner_wake_rx) = + page_vm_with_bound_task_sources_and_owner_wake(&loader, document_url); + dispatch_main_document_domcontentloaded_for_rendering_test(&mut page_vm).await?; + page_vm.vm_mut().eval( + r#" +const first = document.createElement('input'); +const second = document.createElement('input'); +const manual = document.createElement('input'); +first.autofocus = second.autofocus = true; +document.body.append(first); +document.body.append(second, manual); +"installed" +"#, + )?; + let claimed = page_vm + .claim_exact_selected_page_task_for_test( + PageSelectedTaskTestSelector::RenderingUpdate, + ) + .expect("late insertions should publish one autofocus task"); + assert!( + page_vm + .claim_exact_selected_page_task_for_test( + PageSelectedTaskTestSelector::RenderingUpdate + ) + .is_none(), + "repeated insertions must share the pending rendering update" + ); + page_vm.vm_mut().eval(mutation)?; + page_vm + .run_claimed_selected_page_task_for_test(claimed, &loader) + .await?; + let expected = if mutation == "first.remove()" { + "second" + } else { + "manual" + }; + assert_eq!( + page_vm + .vm_mut() + .eval(&format!("document.activeElement === {expected}"))?, + "true", + "{mutation}: execution must observe candidate removal or author focus" + ); + } + Ok::<_, anyhow::Error>(()) + }) + .await + .expect("late autofocus revalidation test should run"); +} + #[tokio::test(flavor = "current_thread")] async fn domcontentloaded_microtask_focus_is_resolved_when_autofocus_runs() { run_page_vm_async_test(async move {