Skip to content

Commit

Permalink
fix(cdk/testing): simulate focusin/focusout events (#23768)
Browse files Browse the repository at this point in the history
Fixes that our fake fallback focus events weren't dispatching `focusin` and `focusout` events as well.

Fixes #23757.

(cherry picked from commit 3cd505f)
  • Loading branch information
crisbeto authored and andrewseguin committed Oct 19, 2021
1 parent ab2af87 commit 11e591b
Showing 1 changed file with 12 additions and 3 deletions.
15 changes: 12 additions & 3 deletions src/cdk/testing/testbed/fake-events/element-focus.ts
Original file line number Diff line number Diff line change
Expand Up @@ -14,11 +14,20 @@ function triggerFocusChange(element: HTMLElement, event: 'focus' | 'blur') {
element.addEventListener(event, handler);
element[event]();
element.removeEventListener(event, handler);

// Some browsers won't move focus if the browser window is blurred while other will move it
// asynchronously. If that is the case, we fake the event sequence as a fallback.
if (!eventFired) {
dispatchFakeEvent(element, event);
simulateFocusSequence(element, event);
}
}

/** Simulates the full event sequence for a focus event. */
function simulateFocusSequence(element: HTMLElement, event: 'focus' | 'blur') {
dispatchFakeEvent(element, event);
dispatchFakeEvent(element, event === 'focus' ? 'focusin' : 'focusout');
}

/**
* Patches an elements focus and blur methods to emit events consistently and predictably.
* This is necessary, because some browsers can call the focus handlers asynchronously,
Expand All @@ -28,8 +37,8 @@ function triggerFocusChange(element: HTMLElement, event: 'focus' | 'blur') {
// TODO: Check if this element focus patching is still needed for local testing,
// where browser is not necessarily focused.
export function patchElementFocus(element: HTMLElement) {
element.focus = () => dispatchFakeEvent(element, 'focus');
element.blur = () => dispatchFakeEvent(element, 'blur');
element.focus = () => simulateFocusSequence(element, 'focus');
element.blur = () => simulateFocusSequence(element, 'blur');
}

/** @docs-private */
Expand Down

0 comments on commit 11e591b

Please sign in to comment.