Skip to content

fix(cdk/testing): simulate focusin/focusout events #23768

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 1 commit into from
Oct 19, 2021
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
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