fix(focus): schedule late autofocus candidates

This commit is contained in:
ldm0
2026-11-24 14:34:55 +08:00
parent 455e944fd5
commit b24dcff4b4
5 changed files with 177 additions and 10 deletions
@@ -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::<Vec<_>>();
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) {
@@ -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(
@@ -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(
@@ -444,10 +444,12 @@ fn first_autofocus_candidate(runtime: &PageScriptHost) -> Option<DomHandle> {
/// 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(
@@ -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 {