Skip to content

Commit 97b2758

Browse files
asamuzaKdomeniccodex
authored
Align focusing and unfocusing with HTML
Fix a regression introduced in 30.1.0 when focusing an element after removing the previously focused element. Removal leaves the document's viewport focused, represented internally by the Document. Treating that sentinel as the previous element caused spurious window blur and focusout events and exposed the Document as relatedTarget. Use focus chains and remove their common trailing entries so this transition fires only focus and focusin, with a null relatedTarget. Implement shared focusing, unfocusing, and focus-update steps. Resolve non-focusable document elements to their viewports, redirect iframe targets to their content documents, and track focus transitions through ancestor documents. Unfocusing checks chain membership and current focusability before focusing the top-level viewport. Recheck focusability before designating each new focused area, so targets removed or disabled by blur listeners do not become active. Apply selection changes before focus dispatch and stop clearing selection after blur, preserving selections established by event listeners. Preserve the interoperable behavior of clearing old focus before blur dispatch and honoring focus changes made by blur listeners. These gaps in the written algorithm are tracked by whatwg/html#1569 and whatwg/html#12329. Follow the specified viewport resolution and top-level unfocusing behavior where browsers differ. Document unsupported steps, including inertness, shadow-root focus delegation, rendering, and system focus. Documents continue to represent their viewports; asynchronous focus fixup remains separate. Fixes #4344. Fixes #4347. Co-authored-by: Domenic Denicola <[email protected]> Co-authored-by: codex <[email protected]>
1 parent b7b460b commit 97b2758

11 files changed

Lines changed: 798 additions & 43 deletions

File tree

‎lib/jsdom/living/helpers/focusing.js‎

Lines changed: 204 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -6,13 +6,15 @@ const { firstChildWithLocalName } = require("./traversal");
66
const { createAnEvent } = require("./events");
77
const { HTML_NS, SVG_NS } = require("./namespaces");
88
const { isRenderedElement } = require("./svg/render");
9+
const NODE_TYPE = require("../node-type");
910

1011
const focusableFormElements = new Set(["input", "select", "textarea", "button"]);
1112

12-
// https://html.spec.whatwg.org/multipage/interaction.html#focusable-area, but also some of
13-
// https://html.spec.whatwg.org/multipage/interaction.html#focusing-steps and some of
13+
// https://html.spec.whatwg.org/multipage/interaction.html#focusable-area and
1414
// https://svgwg.org/svg2-draft/interact.html#TermFocusable
1515
exports.isFocusableAreaElement = elImpl => {
16+
// TODO: Exclude inert elements and shadow hosts whose shadow root has `delegatesFocus` set.
17+
// TODO: Account for HTML rendering, including relevant canvas fallback content and `display: contents`.
1618
// We implemented most of the suggested focusable elements found here:
1719
// https://html.spec.whatwg.org/multipage/interaction.html#tabindex-value
1820
// However, some suggested elements are not focusable in web browsers, as detailed here:
@@ -103,3 +105,203 @@ exports.fireFocusEventWithTargetAdjustment = (name, target, relatedTarget, { bub
103105

104106
target._dispatch(event);
105107
};
108+
109+
function isFocusableArea(target) {
110+
// jsdom represents a document's viewport with the document itself.
111+
if (target.nodeType === NODE_TYPE.DOCUMENT_NODE) {
112+
return target._defaultView !== null;
113+
}
114+
return exports.isFocusableAreaElement(target);
115+
}
116+
117+
// https://html.spec.whatwg.org/multipage/interaction.html#get-the-focusable-area
118+
// The optional `focusTrigger` parameter to this algorithm and the focusing steps is omitted until
119+
// shadow roots support `delegatesFocus`.
120+
function getFocusableArea(focusTarget) {
121+
// TODO: Resolve image-map shapes and scrollable regions once we have a layout model.
122+
123+
const document = focusTarget._ownerDocument;
124+
if (focusTarget === document.documentElement) {
125+
return document._defaultView === null ? null : document;
126+
}
127+
128+
// TODO: Resolve navigables to their active documents once we have a navigable model.
129+
130+
if (focusTarget._contentDocument) {
131+
return focusTarget._contentDocument;
132+
}
133+
134+
// TODO: Resolve shadow hosts with `delegatesFocus`.
135+
136+
return null;
137+
}
138+
139+
// https://html.spec.whatwg.org/multipage/interaction.html#focusing-steps
140+
exports.focusingSteps = (newFocusTarget, fallbackTarget) => {
141+
if (!isFocusableArea(newFocusTarget)) {
142+
newFocusTarget = getFocusableArea(newFocusTarget);
143+
}
144+
145+
if (newFocusTarget === null) {
146+
if (fallbackTarget === undefined) {
147+
return;
148+
}
149+
newFocusTarget = fallbackTarget;
150+
}
151+
152+
if (newFocusTarget._contentDocument) {
153+
newFocusTarget = newFocusTarget._contentDocument;
154+
}
155+
156+
// TODO: Return if the new focus target's DOM anchor is inert.
157+
158+
const document = newFocusTarget._ownerDocument;
159+
const topDocument = getTopDocument(document);
160+
const oldTarget = getCurrentFocusTarget(topDocument);
161+
if (oldTarget === newFocusTarget) {
162+
return;
163+
}
164+
165+
const oldChain = getFocusChain(oldTarget);
166+
const newChain = getFocusChain(newFocusTarget);
167+
168+
focusUpdateSteps(oldChain, newChain, newFocusTarget);
169+
};
170+
171+
// https://html.spec.whatwg.org/multipage/interaction.html#unfocusing-steps
172+
exports.unfocusingSteps = oldFocusTarget => {
173+
// TODO: Resolve shadow hosts with `delegatesFocus` to the currently focused area when appropriate.
174+
// TODO: Return if the old focus target is inert.
175+
// TODO: Resolve image-map shapes and scrollable regions once we have a layout model.
176+
177+
const document = oldFocusTarget._ownerDocument;
178+
const oldChain = getFocusChain(getCurrentFocusTarget(getTopDocument(document)));
179+
if (!oldChain.includes(oldFocusTarget)) {
180+
return;
181+
}
182+
183+
if (!isFocusableArea(oldFocusTarget)) {
184+
return;
185+
}
186+
187+
const topDocument = oldChain.at(-1);
188+
// TODO: Handle the alternative for a top-level traversable without system focus. jsdom does not model that state.
189+
exports.focusingSteps(topDocument);
190+
};
191+
192+
function getTopDocument(document) {
193+
while (document._parentDocument) {
194+
document = document._parentDocument;
195+
}
196+
return document;
197+
}
198+
199+
// https://html.spec.whatwg.org/multipage/interaction.html#currently-focused-area-of-a-top-level-traversable
200+
function getCurrentFocusTarget(document) {
201+
// TODO: Return null if the top-level traversable does not have system focus.
202+
let target = document._lastFocusedElement;
203+
while (target && target._contentDocument) {
204+
document = target._contentDocument;
205+
target = document._lastFocusedElement;
206+
}
207+
return target || document;
208+
}
209+
210+
// https://html.spec.whatwg.org/multipage/interaction.html#focus-chain
211+
function getFocusChain(target) {
212+
const chain = [];
213+
if (target.nodeType === NODE_TYPE.ELEMENT_NODE) {
214+
chain.push(target);
215+
}
216+
217+
// Documents also represent their viewports, so those two entries are collapsed into one.
218+
// TODO: Traverse navigable parents when jsdom has a navigable model; for now traverse their documents.
219+
// Shadow hosts receive retargeted events from dispatch; they are not entries in the focus chain.
220+
for (let document = target._ownerDocument; document; document = document._parentDocument) {
221+
chain.push(document);
222+
}
223+
return chain;
224+
}
225+
226+
// https://html.spec.whatwg.org/multipage/interaction.html#focus-update-steps
227+
function focusUpdateSteps(oldChain, newChain, newFocusTarget) {
228+
const topDocument = oldChain.at(-1);
229+
while (oldChain.length > 0 && newChain.length > 0 && oldChain.at(-1) === newChain.at(-1)) {
230+
oldChain.pop();
231+
newChain.pop();
232+
}
233+
234+
// The spec does not describe when to clear the old focused area. Clear it before blur dispatch,
235+
// as required by the `activeElement` assertions in WPT's `focus-management/focus-events.html`.
236+
// See https://github.com/whatwg/html/issues/1569.
237+
for (const entry of oldChain) {
238+
const document = entry._ownerDocument;
239+
document._lastFocusedElement = null;
240+
document._clearDOMSelector();
241+
if (entry.nodeType === NODE_TYPE.DOCUMENT_NODE && document._parentDocument) {
242+
document._parentDocument._lastFocusedElement = null;
243+
document._parentDocument._clearDOMSelector();
244+
}
245+
}
246+
const focusDuringBlur = getCurrentFocusTarget(topDocument);
247+
248+
for (const entry of oldChain) {
249+
// TODO: Commit uncommitted user edits and update user validity when user editing is implemented.
250+
const relatedTarget = entry === oldChain.at(-1) && entry.nodeType === NODE_TYPE.ELEMENT_NODE &&
251+
newChain.at(-1)?.nodeType === NODE_TYPE.ELEMENT_NODE ?
252+
newChain.at(-1) :
253+
null;
254+
exports.fireFocusEventWithTargetAdjustment("blur", entry, relatedTarget);
255+
if (entry.nodeType === NODE_TYPE.ELEMENT_NODE) {
256+
exports.fireFocusEventWithTargetAdjustment("focusout", entry, relatedTarget, { bubbles: true });
257+
}
258+
}
259+
260+
// The spec omits this reentrancy check. A focus change from a blur listener takes precedence,
261+
// as required by WPT's `css/selectors/focus-within-focus-move.html` and implemented by browsers.
262+
// See https://github.com/whatwg/html/issues/12329 and, for related `:focus-within` state issues,
263+
// https://github.com/whatwg/html/issues/11835.
264+
if (getCurrentFocusTarget(topDocument) !== focusDuringBlur) {
265+
return;
266+
}
267+
268+
// Apply jsdom's selection convention at the platform-specific focusing step, before focus events.
269+
if (newFocusTarget !== null && newFocusTarget.nodeType === NODE_TYPE.ELEMENT_NODE) {
270+
newFocusTarget._ownerDocument.getSelection().collapse(newFocusTarget, 0);
271+
}
272+
273+
// A viewport can be the new target even when its Document was removed as a shared chain entry.
274+
if (newFocusTarget !== null && newFocusTarget.nodeType === NODE_TYPE.DOCUMENT_NODE) {
275+
newFocusTarget._lastFocusedElement = newFocusTarget;
276+
newFocusTarget._clearDOMSelector();
277+
}
278+
279+
for (let i = newChain.length - 1; i >= 0; i--) {
280+
const entry = newChain[i];
281+
const document = entry._ownerDocument;
282+
if (isFocusableArea(entry) && document._lastFocusedElement !== entry) {
283+
// TODO: Set the navigation API's "focus changed during ongoing navigation" flag.
284+
document._lastFocusedElement = entry;
285+
document._clearDOMSelector();
286+
}
287+
// Reflect child-document focus in the parent until navigables have their own focus state.
288+
if (entry.nodeType === NODE_TYPE.DOCUMENT_NODE && document._parentDocument) {
289+
document._parentDocument._lastFocusedElement = document._defaultView._frameElement;
290+
document._parentDocument._clearDOMSelector();
291+
}
292+
293+
const relatedTarget = entry === newChain.at(-1) && entry.nodeType === NODE_TYPE.ELEMENT_NODE &&
294+
oldChain.at(-1)?.nodeType === NODE_TYPE.ELEMENT_NODE ?
295+
oldChain.at(-1) :
296+
null;
297+
exports.fireFocusEventWithTargetAdjustment("focus", entry, relatedTarget);
298+
if (entry.nodeType === NODE_TYPE.ELEMENT_NODE) {
299+
exports.fireFocusEventWithTargetAdjustment("focusin", entry, relatedTarget, { bubbles: true });
300+
}
301+
302+
// Likewise, do not overwrite a focus change made while dispatching the new chain's events.
303+
if (getCurrentFocusTarget(topDocument) !== entry) {
304+
return;
305+
}
306+
}
307+
}

‎lib/jsdom/living/nodes/HTMLOrSVGElement-impl.js‎

Lines changed: 5 additions & 39 deletions
Original file line numberDiff line numberDiff line change
@@ -1,10 +1,10 @@
11
"use strict";
22

33
const conversions = require("webidl-conversions");
4+
const DOMStringMap = require("../../../generated/idl/DOMStringMap");
45
const { isSummaryForParentDetails } = require("../helpers/details");
5-
const focusing = require("../helpers/focusing");
6+
const { focusingSteps, unfocusingSteps } = require("../helpers/focusing");
67
const { HTML_NS, SVG_NS } = require("../helpers/namespaces");
7-
const DOMStringMap = require("../../../generated/idl/DOMStringMap");
88

99
const tabIndexReflectAllowedHTMLElements = new Set([
1010
"a", "area", "button", "frame", "iframe",
@@ -42,46 +42,12 @@ class HTMLOrSVGElementImpl {
4242
}
4343

4444
focus() {
45-
if (!focusing.isFocusableAreaElement(this)) {
46-
return;
47-
}
48-
const ownerDocument = this._ownerDocument;
49-
const previous = ownerDocument._lastFocusedElement;
50-
51-
if (previous === this) {
52-
return;
53-
}
54-
55-
ownerDocument._lastFocusedElement = null;
56-
if (previous) {
57-
focusing.fireFocusEventWithTargetAdjustment("blur", previous, this);
58-
focusing.fireFocusEventWithTargetAdjustment("focusout", previous, this, { bubbles: true });
59-
} else {
60-
const frameElement = ownerDocument._defaultView._frameElement;
61-
if (frameElement) {
62-
const frameLastFocusedElement = frameElement.ownerDocument._lastFocusedElement;
63-
frameElement.ownerDocument._lastFocusedElement = null;
64-
focusing.fireFocusEventWithTargetAdjustment("blur", frameLastFocusedElement, null);
65-
focusing.fireFocusEventWithTargetAdjustment("focusout", frameLastFocusedElement, null, { bubbles: true });
66-
frameElement.ownerDocument._lastFocusedElement = frameElement;
67-
}
68-
}
69-
70-
ownerDocument._lastFocusedElement = this;
71-
focusing.fireFocusEventWithTargetAdjustment("focus", this, previous);
72-
focusing.fireFocusEventWithTargetAdjustment("focusin", this, previous, { bubbles: true });
73-
ownerDocument.getSelection().collapse(this, 0);
45+
// TODO: Run the allow focus steps when we implement fully active documents and focus permissions.
46+
focusingSteps(this);
7447
}
7548

7649
blur() {
77-
if (this._ownerDocument._lastFocusedElement !== this || !focusing.isFocusableAreaElement(this)) {
78-
return;
79-
}
80-
81-
this._ownerDocument._lastFocusedElement = null;
82-
focusing.fireFocusEventWithTargetAdjustment("blur", this, null);
83-
focusing.fireFocusEventWithTargetAdjustment("focusout", this, null, { bubbles: true });
84-
this._ownerDocument.getSelection().empty();
50+
unfocusingSteps(this);
8551
}
8652
}
8753

‎test/web-platform-tests/to-run.yaml‎

Lines changed: 0 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1213,8 +1213,6 @@ focus-visible-023.html: [fail, https://github.com/jsdom/jsdom/issues/3426]
12131213
focus-visible-script-focus-001.html: [fail-slow, https://github.com/jsdom/jsdom/issues/3426]
12141214
focus-within-009.html: [fail-slow, Unknown]
12151215
focus-within-display-none-001.html: [fail, Focus fixup rule not properly implemented; https://github.com/jsdom/jsdom/issues/3029]
1216-
focus-within-focus-move.html: [fail, Unknown]
1217-
focus-within-removal.html: [fail, Unknown]
12181216
focus-within-toplayer-001.html: [fail, Unknown]
12191217
heading-prefixed.html: [fail, Unknown]
12201218
heading.html: [fail, Unknown]

‎test/web-platform-tests/to-upstream-expectations.yaml‎

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -9,3 +9,5 @@ jsdom-only/failure-example-2.html:
99
"failing test": [fail, https://github.com/jsdom/jsdom/issues/3835]
1010
svg/painting/parsed-svg-default-fill.html:
1111
"Default fill after inserting an XML element without the SVG namespace": [fail, https://github.com/jsdom/jsdom/issues/2688]
12+
uievents/focusevents/hasfocus-focus-blur.html:
13+
"document.hasFocus() returns true during internal focus shifts (blur and focus)": [fail, Need to fix document.hasFocus()]
Lines changed: 77 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,77 @@
1+
<!doctype html>
2+
<meta charset="utf-8">
3+
<title>Script running during the focus update steps</title>
4+
<link rel="help" href="https://html.spec.whatwg.org/multipage/interaction.html#focus-update-steps">
5+
<script src="/resources/testharness.js"></script>
6+
<script src="/resources/testharnessreport.js"></script>
7+
<body>
8+
<script>
9+
"use strict";
10+
11+
function fixture(t) {
12+
const container = document.createElement("div");
13+
container.innerHTML = "<input><input><input><p>Selected text</p>";
14+
document.body.append(container);
15+
t.add_cleanup(() => container.remove());
16+
t.add_cleanup(() => getSelection().removeAllRanges());
17+
return container;
18+
}
19+
20+
test(t => {
21+
const container = fixture(t);
22+
const input = container.firstElementChild;
23+
const text = container.lastElementChild.firstChild;
24+
input.addEventListener("focus", () => getSelection().setBaseAndExtent(text, 0, text, 8), { once: true });
25+
26+
input.focus();
27+
28+
assert_equals(getSelection().anchorNode, text);
29+
assert_equals(getSelection().anchorOffset, 0);
30+
assert_equals(getSelection().focusNode, text);
31+
assert_equals(getSelection().focusOffset, 8);
32+
}, "Focusing does not overwrite a selection set by the focus event listener");
33+
34+
test(t => {
35+
const container = fixture(t);
36+
const input = container.firstElementChild;
37+
const text = container.lastElementChild.firstChild;
38+
input.focus();
39+
input.addEventListener("blur", () => getSelection().setBaseAndExtent(text, 0, text, 8), { once: true });
40+
41+
input.blur();
42+
43+
assert_equals(getSelection().anchorNode, text);
44+
assert_equals(getSelection().anchorOffset, 0);
45+
assert_equals(getSelection().focusNode, text);
46+
assert_equals(getSelection().focusOffset, 8);
47+
}, "Unfocusing does not clear a selection set by the blur event listener");
48+
49+
test(t => {
50+
const container = fixture(t);
51+
const [first, second, third] = container.children;
52+
const text = container.lastElementChild.firstChild;
53+
first.focus();
54+
first.addEventListener("blur", () => third.focus(), { once: true });
55+
third.addEventListener("focus", () => getSelection().setBaseAndExtent(text, 0, text, 8), { once: true });
56+
57+
second.focus();
58+
59+
assert_equals(document.activeElement, third);
60+
assert_equals(getSelection().anchorNode, text);
61+
assert_equals(getSelection().anchorOffset, 0);
62+
assert_equals(getSelection().focusNode, text);
63+
assert_equals(getSelection().focusOffset, 8);
64+
}, "A focus change from a blur listener preserves the selection set by the new focus listener");
65+
66+
test(t => {
67+
const [first, second] = fixture(t).children;
68+
first.focus();
69+
first.addEventListener("blur", () => {
70+
second.disabled = true;
71+
}, { once: true });
72+
73+
second.focus();
74+
75+
assert_equals(document.activeElement, document.body);
76+
}, "A new-chain entry that becomes non-focusable during blur is not designated the focused area");
77+
</script>

0 commit comments

Comments
 (0)