Skip to content

Commit 59eee5d

Browse files
crisbetoandrewseguin
authored andcommitted
fix(cdk/testing): simulate focusin/focusout events (#23768)
Fixes that our fake fallback focus events weren't dispatching `focusin` and `focusout` events as well. Fixes #23757. (cherry picked from commit 3cd505f)
1 parent 2792291 commit 59eee5d

File tree

1 file changed

+12
-3
lines changed

1 file changed

+12
-3
lines changed

src/cdk/testing/testbed/fake-events/element-focus.ts

Lines changed: 12 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -14,20 +14,29 @@ function triggerFocusChange(element: HTMLElement, event: 'focus' | 'blur') {
1414
element.addEventListener(event, handler);
1515
element[event]();
1616
element.removeEventListener(event, handler);
17+
18+
// Some browsers won't move focus if the browser window is blurred while other will move it
19+
// asynchronously. If that is the case, we fake the event sequence as a fallback.
1720
if (!eventFired) {
18-
dispatchFakeEvent(element, event);
21+
simulateFocusSequence(element, event);
1922
}
2023
}
2124

25+
/** Simulates the full event sequence for a focus event. */
26+
function simulateFocusSequence(element: HTMLElement, event: 'focus' | 'blur') {
27+
dispatchFakeEvent(element, event);
28+
dispatchFakeEvent(element, event === 'focus' ? 'focusin' : 'focusout');
29+
}
30+
2231
/**
2332
* Patches an elements focus and blur methods to emit events consistently and predictably.
2433
* This is necessary, because some browsers, like IE11, will call the focus handlers asynchronously,
2534
* while others won't fire them at all if the browser window is not focused.
2635
* @docs-private
2736
*/
2837
export function patchElementFocus(element: HTMLElement) {
29-
element.focus = () => dispatchFakeEvent(element, 'focus');
30-
element.blur = () => dispatchFakeEvent(element, 'blur');
38+
element.focus = () => simulateFocusSequence(element, 'focus');
39+
element.blur = () => simulateFocusSequence(element, 'blur');
3140
}
3241

3342
/** @docs-private */

0 commit comments

Comments
 (0)