fix(focus): publish focus state at each event phase

Expose the old Document's viewport during blur and focusout, then commit the
new focus before focus and focusin. Preserve completed reentrant transitions,
revalidate target ownership and focusability, and suppress stale focus events.

Track viewport ownership across child Documents so ancestor activeElement
remains the iframe while the child blurs, and retire that focus on removal.
Preserve shared :focus-within ancestors during blur. Keep relatedTarget within
its Document and cover event state, computed styles,
reentry, text-change commitment, shadow roots and frame transitions.
This commit is contained in:
ldm0
2026-11-20 22:47:43 +08:00
parent 942909f368
commit b1da2cfb63
8 changed files with 459 additions and 15 deletions
+21 -2
View File
@@ -81,6 +81,7 @@ impl DomHost {
child_browsing_context_host_candidates: RefCell::new(Vec::new()),
shadow_disabled_custom_element_definitions: RefCell::new(HashSet::new()),
active_element: Cell::new(None),
focus_transition_common_ancestor: Cell::new(None),
hovered_elements: RefCell::new(IndexSet::new()),
mutation_observer_records_enabled: Cell::new(false),
devtools_mutation_records_enabled: Cell::new(false),
@@ -602,13 +603,25 @@ impl DomHost {
}
pub fn set_active_element_handle(&self, handle: Option<DomHandle>) {
if self.active_element.get() == handle {
let had_transition = self.focus_transition_common_ancestor.take().is_some();
if self.active_element.get() == handle && !had_transition {
return;
}
self.active_element.set(handle);
self.record_mutation(MutationScope::QueryState);
}
pub fn set_focus_transition_common_ancestor(
&self,
handle: Option<DomHandle>,
) -> Option<DomHandle> {
let previous = self.focus_transition_common_ancestor.replace(handle);
if previous != handle {
self.record_mutation(MutationScope::QueryState);
}
previous
}
pub fn element_matches_focus(&self, handle: DomHandle) -> bool {
let Some(active) = self.active_element_handle() else {
return false;
@@ -630,7 +643,13 @@ impl DomHost {
}
pub fn element_matches_focus_within(&self, handle: DomHandle) -> bool {
let Some(active) = self.active_element_handle() else {
// Shared ancestors retain :focus-within while blur listeners run,
// although neither the old nor the pending element matches :focus.
let Some(active) = self.active_element_handle().or_else(|| {
self.focus_transition_common_ancestor
.get()
.filter(|ancestor| self.node(*ancestor).is_some_and(Node::is_connected))
}) else {
return false;
};
let mut current = Some(active);
+1
View File
@@ -180,6 +180,7 @@ pub struct DomHost {
pub(super) child_browsing_context_host_candidates: RefCell<Vec<DomHandle>>,
pub(super) shadow_disabled_custom_element_definitions: RefCell<HashSet<String>>,
pub(super) active_element: Cell<Option<DomHandle>>,
pub(super) focus_transition_common_ancestor: Cell<Option<DomHandle>>,
pub(super) hovered_elements: RefCell<IndexSet<DomHandle>>,
pub(super) mutation_observer_records_enabled: Cell<bool>,
pub(super) devtools_mutation_records_enabled: Cell<bool>,
@@ -625,6 +625,7 @@ impl PageScriptHost {
next_javascript_dialog_id: 1,
pending_network_output: Vec::new(),
document_focus_changes: HashMap::new(),
focused_viewport_document: None,
subresource_activity_epoch: 0,
subresource_last_activity_at: std::time::Instant::now(),
page_network_policy,
@@ -38,7 +38,26 @@ impl PageScriptHost {
}
}
pub(crate) fn focused_viewport_document(&self) -> Option<DomHandle> {
self.focused_viewport_document.filter(|document| {
self.active_element_handle().is_none()
&& self.top_level_document_for_document(*document).is_some()
})
}
pub(crate) fn set_focused_viewport_document(&mut self, document: Option<DomHandle>) {
// An unfocused element leaves a concrete Document viewport. Its iframe
// remains the active element exposed by ancestor Documents during blur.
self.focused_viewport_document = document;
}
pub(crate) fn clear_disconnected_document_focus(&mut self) {
if self
.focused_viewport_document
.is_some_and(|document| self.top_level_document_for_document(document).is_none())
{
self.focused_viewport_document = None;
}
let documents = self
.document_focus_changes
.iter()
@@ -1166,6 +1166,7 @@ pub(crate) struct PageScriptHost {
next_javascript_dialog_id: u64,
pending_network_output: Vec<ScriptNetworkOutputItem>,
document_focus_changes: HashMap<DomHandle, focus::DocumentFocusChangeState>,
focused_viewport_document: Option<DomHandle>,
subresource_activity_epoch: u64,
subresource_last_activity_at: std::time::Instant,
/// The target policy remains available even when the current Document
@@ -18,6 +18,11 @@ pub(in crate::native_bridge) fn node_document_active_element_getter_function<'s>
let runtime = unsafe { &mut *runtime_ptr };
let handle = runtime
.active_element_handle()
.or_else(|| {
runtime.focused_viewport_document().and_then(|document| {
runtime.child_browsing_context_host_for_document_handle(document)
})
})
.and_then(|active| retarget_active_element_to_document(runtime, active, handle))
.or_else(|| {
runtime
@@ -811,24 +811,59 @@ fn update_focus_from_previous_with_previous_focus_within(
if previous == next {
return;
}
let next_value = wrap_handle_value(scope, runtime_ptr, next);
let next_document = next.and_then(|handle| {
unsafe { &*runtime_ptr }
.dom_host()
.owner_document_handle(handle)
});
let previous_document = previous.and_then(|handle| {
unsafe { &*runtime_ptr }
.dom_host()
.owner_document_handle(handle)
});
let window_focus_transition =
window_focus_transition_for_handles(scope, runtime_ptr, previous, next);
// Related targets do not cross Document boundaries in the focus chains.
let same_document = previous_document == next_document;
let next_value = same_document
.then(|| wrap_handle_value(scope, runtime_ptr, next))
.flatten();
let runtime = unsafe { &mut *runtime_ptr };
runtime.set_active_element_handle(next);
if let Some(handle) = next.filter(|handle| is_text_control(runtime, *handle)) {
runtime.note_text_control_selection(handle);
}
if viewport_document.is_none() || next.is_some() {
runtime.mark_focus_changed(previous, next);
// Blur listeners observe the viewport, before the new target gains focus.
// Keep inactive Documents' focused areas when moving between Documents.
let previous_viewport = previous_document.or(runtime.focused_viewport_document());
let common_ancestor = previous.zip(next).and_then(|(previous, next)| {
let mut candidate = Some(previous);
while let Some(handle) = candidate {
if shadow_including_contains(runtime, handle, next) {
return Some(handle);
}
candidate = flat_tree_parent(runtime, handle);
}
None
});
runtime.set_active_element_handle(None);
runtime
.dom_host()
.set_focus_transition_common_ancestor(common_ancestor);
runtime.set_focused_viewport_document(previous_viewport);
if viewport_document.is_none()
&& (next.is_none()
|| previous.and_then(|handle| runtime.dom_host().owner_document_handle(handle))
== next_document)
{
runtime.mark_focus_changed(previous, None);
}
if let Some(previous_focus_within) = previous_focus_within {
runtime.note_focus_style_activity_with_previous_focus_within(
previous,
next,
None,
Some(previous_focus_within),
);
} else {
runtime.note_focus_style_activity(previous, next);
runtime.note_focus_style_activity(previous, None);
}
let mut redirected = false;
if let Some(previous_handle) = previous {
dispatch_pending_text_control_change_if_needed(scope, runtime_ptr, previous_handle);
if let Some(event) = construct_node_focus_event(
@@ -841,24 +876,62 @@ fn update_focus_from_previous_with_previous_focus_within(
) {
let _ = dispatch_public_event(scope, runtime_ptr, previous_handle, event);
}
// A blur listener can complete a different focus transition. Finish the
// old target's focusout, but do not overwrite the listener's decision.
redirected = unsafe { &*runtime_ptr }.active_element_handle().is_some();
if let Some(event) = construct_node_focus_event(
scope,
runtime_ptr,
previous_handle,
"focusout",
next_value,
if redirected { None } else { next_value },
true,
) {
let _ = dispatch_public_event(scope, runtime_ptr, previous_handle, event);
}
dispatch_interest_event_if_needed(scope, runtime_ptr, previous_handle, "loseinterest");
}
let window_focus_transition =
window_focus_transition_for_handles(scope, runtime_ptr, previous, next);
if redirected || unsafe { &*runtime_ptr }.active_element_handle().is_some() {
clear_focus_transition_style(unsafe { &mut *runtime_ptr });
return;
}
let target_is_current = |runtime: &PageScriptHost| {
next.is_none_or(|handle| {
runtime.dom_host().owner_document_handle(handle) == next_document
&& next_document.is_some_and(|document| {
runtime.top_level_document_for_document(document).is_some()
})
&& is_focusable(runtime, handle)
})
};
if !target_is_current(unsafe { &*runtime_ptr }) {
clear_focus_transition_style(unsafe { &mut *runtime_ptr });
return;
}
if let Some((previous_window, _)) = window_focus_transition {
dispatch_window_focus_event(scope, runtime_ptr, previous_window, "blur");
}
let previous_value = wrap_handle_value(scope, runtime_ptr, previous);
let runtime = unsafe { &mut *runtime_ptr };
if runtime.active_element_handle().is_some() || !target_is_current(runtime) {
clear_focus_transition_style(runtime);
return;
}
runtime.set_active_element_handle(next);
runtime.set_focused_viewport_document(if next.is_some() {
None
} else {
viewport_document.or(previous_viewport)
});
if let Some(handle) = next.filter(|handle| is_text_control(runtime, *handle)) {
runtime.note_text_control_selection(handle);
}
if viewport_document.is_none() || next.is_some() {
runtime.mark_focus_changed(previous, next);
}
runtime.note_focus_style_activity(None, next);
let previous_value = same_document
.then(|| wrap_handle_value(scope, runtime_ptr, previous))
.flatten();
if let Some(next_handle) = next {
if selection == FocusSelection::Initialize
&& unsafe { &*runtime_ptr }.active_element_handle() == Some(next_handle)
@@ -883,6 +956,9 @@ fn update_focus_from_previous_with_previous_focus_within(
) {
let _ = dispatch_public_event(scope, runtime_ptr, next_handle, event);
}
if unsafe { &*runtime_ptr }.active_element_handle() != Some(next_handle) {
return;
}
if let Some(event) = construct_node_focus_event(
scope,
runtime_ptr,
@@ -893,11 +969,17 @@ fn update_focus_from_previous_with_previous_focus_within(
) {
let _ = dispatch_public_event(scope, runtime_ptr, next_handle, event);
}
if unsafe { &*runtime_ptr }.active_element_handle() != Some(next_handle) {
return;
}
if let Some(target) =
dispatch_interest_event_if_needed(scope, runtime_ptr, next_handle, "interest")
{
show_interest_popover_if_needed(scope, runtime_ptr, next_handle, target);
}
if unsafe { &*runtime_ptr }.active_element_handle() != Some(next_handle) {
return;
}
schedule_focus_blur_if_needed(scope, runtime_ptr, next_handle);
}
if let Some((_, next_window)) = window_focus_transition {
@@ -905,6 +987,15 @@ fn update_focus_from_previous_with_previous_focus_within(
}
}
fn clear_focus_transition_style(runtime: &mut PageScriptHost) {
if let Some(ancestor) = runtime
.dom_host()
.set_focus_transition_common_ancestor(None)
{
runtime.note_focus_style_activity(Some(ancestor), runtime.active_element_handle());
}
}
fn window_focus_transition_for_handles(
scope: &mut v8::PinScope<'_, '_>,
runtime_ptr: *mut PageScriptHost,
@@ -915,6 +1006,11 @@ fn window_focus_transition_for_handles(
let execution_window = current_execution_window_endpoint(scope);
let previous_window = previous
.and_then(|handle| focused_window_endpoint(runtime, handle))
.or_else(|| {
runtime
.focused_viewport_document()
.and_then(|document| runtime.window_endpoint_for_document(document))
})
.unwrap_or(execution_window);
// Clearing an element's focus does not blur its Window. A later focus in
// another Document supplies the concrete new focused-frame endpoint.
@@ -302,3 +302,305 @@ fn focusing_frame_owner_then_input_dispatches_child_window_focus_and_blur() {
"top-window-blur,frame-focus,child-window-focus,frame-blur,child-window-blur,input-focus,top-window-focus|true"
);
}
#[test]
fn focus_transitions_publish_state_before_each_event_phase() {
let mut vm = new_storage_test_vm("https://focus-state.test/");
let result = vm.eval(r#"
(() => {
const root = document.documentElement || document.appendChild(document.createElement('html'));
const body = document.body || root.appendChild(document.createElement('body'));
body.innerHTML = '<style>input { color: red } input:focus { color: blue }</style><input id=a><input id=b>';
const a = document.getElementById('a'), b = document.getElementById('b');
a.focus();
const events = [];
for (const node of [a, b]) for (const type of ['blur', 'focusout', 'focus', 'focusin']) {
node.addEventListener(type, e => events.push([
e.type, e.target.id, document.activeElement.id || 'body',
e.relatedTarget.id, e.target.matches(':focus'), getComputedStyle(e.target).color
].join(':')));
}
b.focus();
return events.join('|');
})()
"#).expect("focus event state fixture");
assert_eq!(
result,
"blur:a:body:b:false:rgb(255, 0, 0)|focusout:a:body:b:false:rgb(255, 0, 0)|focus:b:b:a:true:rgb(0, 0, 255)|focusin:b:b:a:true:rgb(0, 0, 255)"
);
}
#[test]
fn reentrant_focus_handlers_preserve_the_completed_transition() {
// These event traces also match Chromium. In particular, a temporary focus
// that is blurred before the handler returns does not cancel the request.
for (source, event_type, action, expected) in [
(
"a",
"blur",
"c.focus()",
"blur:a:body:b|focus:c:c:null|focusin:c:c:null|focusout:a:c:null;c",
),
(
"a",
"blur",
"b.focus()",
"blur:a:body:b|focus:b:b:null|focusin:b:b:null|focusout:a:b:null;b",
),
(
"a",
"blur",
"a.focus()",
"blur:a:body:b|focus:a:a:null|focusin:a:a:null|focusout:a:a:null;a",
),
(
"a",
"blur",
"c.focus(); c.blur()",
"blur:a:body:b|focus:c:c:null|focusin:c:c:null|blur:c:body:null|focusout:c:body:null|focusout:a:body:b|focus:b:b:a|focusin:b:b:a;b",
),
(
"a",
"blur",
"c.focus(); a.addEventListener('focusout', () => c.blur(), {once:true})",
"blur:a:body:b|focus:c:c:null|focusin:c:c:null|focusout:a:c:null|blur:c:body:null|focusout:c:body:null;body",
),
(
"a",
"focusout",
"c.focus()",
"blur:a:body:b|focusout:a:body:b|focus:c:c:null|focusin:c:c:null;c",
),
(
"a",
"focusout",
"c.focus(); c.blur()",
"blur:a:body:b|focusout:a:body:b|focus:c:c:null|focusin:c:c:null|blur:c:body:null|focusout:c:body:null|focus:b:b:a|focusin:b:b:a;b",
),
(
"b",
"focus",
"c.focus()",
"blur:a:body:b|focusout:a:body:b|focus:b:b:a|blur:b:body:c|focusout:b:body:c|focus:c:c:b|focusin:c:c:b;c",
),
(
"b",
"focus",
"b.blur()",
"blur:a:body:b|focusout:a:body:b|focus:b:b:a|blur:b:body:null|focusout:b:body:null;body",
),
(
"b",
"focus",
"b.remove()",
"blur:a:body:b|focusout:a:body:b|focus:b:b:a|blur:b:body:null|focusout:b:body:null;body",
),
] {
let mut vm = new_storage_test_vm("https://focus-reentry.test/");
let script = r#"
(() => {
const root = document.documentElement || document.appendChild(document.createElement('html'));
const body = document.body || root.appendChild(document.createElement('body'));
body.innerHTML = '<input id=a><input id=b><input id=c>';
const a = document.getElementById('a'), b = document.getElementById('b'), c = document.getElementById('c');
a.focus();
const label = node => node === body ? 'body' : node?.id ?? 'null';
const events = [];
for (const node of [a, b, c]) for (const type of ['blur', 'focusout', 'focus', 'focusin'])
node.addEventListener(type, e => events.push([e.type, e.target.id, label(document.activeElement), label(e.relatedTarget)].join(':')));
/*SOURCE*/.addEventListener(/*TYPE*/, () => { /*ACTION*/ }, {once:true});
b.focus();
return events.join('|') + ';' + label(document.activeElement);
})()
"#
.replace("/*SOURCE*/", source)
.replace("/*TYPE*/", &serde_json::to_string(event_type).unwrap())
.replace("/*ACTION*/", action);
assert_eq!(
vm.eval(&script).expect("reentrant focus fixture"),
expected,
"{source} {event_type}: {action}"
);
}
}
#[test]
fn focus_transitions_revalidate_the_target_after_blur_handlers() {
for mutation in [
"b.remove()",
"b.disabled = true",
"b.hidden = true",
"b.inert = true",
"document.implementation.createHTMLDocument().body.append(b)",
] {
let mut vm = new_storage_test_vm("https://focus-target-revalidation.test/");
let script = r#"
(() => {
const root = document.documentElement || document.appendChild(document.createElement('html'));
const body = document.body || root.appendChild(document.createElement('body'));
body.innerHTML = '<input id=a><input id=b>';
const a = document.getElementById('a'), b = document.getElementById('b');
a.focus();
let focused = 0;
b.addEventListener('focus', () => focused++);
b.addEventListener('focusin', () => focused++);
a.addEventListener('blur', () => { /*MUTATION*/ });
b.focus();
return [document.activeElement === body, focused].join(':');
})()
"#
.replace("/*MUTATION*/", mutation);
assert_eq!(
vm.eval(&script).expect("target retirement fixture"),
"true:0",
"{mutation}"
);
}
}
#[test]
fn shadow_root_active_element_tracks_focus_event_phases() {
let mut vm = new_storage_test_vm("https://shadow-focus-phases.test/");
let result = vm.eval(r#"
(() => {
const root = document.documentElement || document.appendChild(document.createElement('html'));
const body = document.body || root.appendChild(document.createElement('body'));
body.innerHTML = '<div id=host></div>';
const host = document.getElementById('host');
const shadow = host.attachShadow({mode:'closed'});
shadow.innerHTML = '<input id=a><input id=b>';
const a = shadow.querySelector('#a'), b = shadow.querySelector('#b');
a.focus();
const events = [];
for (const node of [a, b]) for (const type of ['blur', 'focusout', 'focus', 'focusin'])
node.addEventListener(type, e => events.push([
type, document.activeElement === host, shadow.activeElement?.id ?? 'null', host.matches(':focus-within')
].join(':')));
b.focus();
return events.join('|');
})()
"#).expect("shadow focus state fixture");
assert_eq!(
result,
"blur:false:null:true|focusout:false:null:true|focus:true:b:true|focusin:true:b:true"
);
}
#[test]
fn child_focus_transitions_preserve_the_viewport_and_scope_related_targets() {
for (scenario, expected) in [
(
"same-child",
"blur:a:one:body:body:b|focusout:a:one:body:body:b|focus:b:one:b:body:a|focusin:b:one:b:body:a",
),
(
"enter-child",
"blur:main:body:body:body:null|focusout:main:body:body:body:null|focus:b:one:b:body:null|focusin:b:one:b:body:null",
),
(
"leave-child",
"blur:a:one:body:body:null|focusout:a:one:body:body:null|focus:main:main:body:body:null|focusin:main:main:body:body:null",
),
(
"sibling-child",
"blur:a:one:body:body:null|focusout:a:one:body:body:null|focus:c:two:body:c:null|focusin:c:two:body:c:null",
),
] {
let mut vm = new_storage_test_vm("https://child-focus-phases.test/");
let script = r#"
(() => {
const root = document.documentElement || document.appendChild(document.createElement('html'));
const body = document.body || root.appendChild(document.createElement('body'));
body.innerHTML = '<input id=main><iframe id=one></iframe><iframe id=two></iframe>';
const scenario = /*SCENARIO*/;
const d1 = document.getElementById('one').contentDocument;
const d2 = document.getElementById('two').contentDocument;
d1.body.innerHTML = '<input id=a><input id=b>';
d2.body.innerHTML = '<input id=c>';
const a = scenario === 'enter-child' ? document.getElementById('main') : d1.getElementById('a');
const b = scenario === 'leave-child' ? document.getElementById('main') :
scenario === 'sibling-child' ? d2.getElementById('c') : d1.getElementById('b');
const label = node => node?.id || node?.localName || 'null';
a.focus();
const events = [];
for (const node of [a, b]) for (const type of ['blur', 'focusout', 'focus', 'focusin'])
node.addEventListener(type, e => events.push([
type, label(e.target), label(document.activeElement), label(d1.activeElement),
label(d2.activeElement), label(e.relatedTarget)
].join(':')));
b.focus();
return events.join('|');
})()
"#
.replace("/*SCENARIO*/", &serde_json::to_string(scenario).unwrap());
assert_eq!(
vm.eval(&script).expect("child focus transition fixture"),
expected,
"{scenario}"
);
}
}
#[test]
fn text_change_commit_can_redirect_a_pending_focus_transition() {
for (action, expected) in [
(
"",
"change:a:body:null|blur:a:body:b|focusout:a:body:b|focus:b:b:a|focusin:b:b:a;b",
),
(
"c.focus()",
"change:a:body:null|focus:c:c:null|focusin:c:c:null|blur:a:c:b|focusout:a:c:null;c",
),
] {
let mut vm = new_storage_test_vm("https://focus-change-commit.test/");
let script = r#"
(() => {
const root = document.documentElement || document.appendChild(document.createElement('html'));
const body = document.body || root.appendChild(document.createElement('body'));
body.innerHTML = '<input id=a><input id=b><input id=c>';
const a = document.getElementById('a'), b = document.getElementById('b'), c = document.getElementById('c');
a.focus();
document.execCommand('insertText', false, 'edited');
const label = node => node?.id || node?.localName || 'null';
const events = [];
for (const node of [a, b, c]) for (const type of ['change', 'blur', 'focusout', 'focus', 'focusin'])
node.addEventListener(type, e => events.push([type, label(e.target), label(document.activeElement), label(e.relatedTarget)].join(':')));
a.addEventListener('change', () => { /*ACTION*/ }, {once:true});
b.focus();
return events.join('|') + ';' + label(document.activeElement);
})()
"#.replace("/*ACTION*/", action);
assert_eq!(
vm.eval(&script).expect("text commit focus fixture"),
expected,
"{action}"
);
}
}
#[test]
fn child_viewport_focus_is_retired_when_its_container_is_removed() {
let mut vm = new_storage_test_vm("https://focus-viewport-retirement.test/");
let result = vm
.eval(
r#"
(() => {
const root = document.documentElement || document.appendChild(document.createElement('html'));
const body = document.body || root.appendChild(document.createElement('body'));
body.innerHTML = '<iframe id=frame></iframe>';
const frame = document.getElementById('frame'), child = frame.contentDocument;
child.body.innerHTML = '<input id=a>';
const input = child.getElementById('a');
input.focus(); input.blur();
const viewport = document.activeElement === frame && child.activeElement === child.body;
frame.remove();
const removed = document.activeElement === body;
body.append(frame);
return [viewport, removed, document.activeElement === body].join(':');
})()
"#,
)
.expect("child viewport retirement fixture");
assert_eq!(result, "true:true:true");
}