Skip to content

fix(focus-monitor): allow native focus options to be passed through focusVia #11962

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
Jun 29, 2018
Merged
Show file tree
Hide file tree
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
13 changes: 13 additions & 0 deletions src/cdk/a11y/focus-monitor/focus-monitor.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -212,6 +212,19 @@ describe('FocusMonitor', () => {

expect(buttonElement.classList.length).toBe(0, 'button should not have any focus classes');
}));

it('should pass focus options to the native focus method', fakeAsync(() => {
spyOn(buttonElement, 'focus');

focusMonitor.focusVia(buttonElement, 'program', {preventScroll: true});
fixture.detectChanges();
tick();

expect(buttonElement.focus).toHaveBeenCalledWith(jasmine.objectContaining({
preventScroll: true
}));
}));

});


Expand Down
20 changes: 16 additions & 4 deletions src/cdk/a11y/focus-monitor/focus-monitor.ts
Original file line number Diff line number Diff line change
Expand Up @@ -29,6 +29,16 @@ export const TOUCH_BUFFER_MS = 650;
export type FocusOrigin = 'touch' | 'mouse' | 'keyboard' | 'program' | null;


/**
* Corresponds to the options that can be passed to the native `focus` event.
* via https://developer.mozilla.org/en-US/docs/Web/API/HTMLElement/focus
*/
export interface FocusOptions {
/** Whether the browser should scroll to the element when it is focused. */
preventScroll?: boolean;
}


type MonitoredElementInfo = {
unlisten: Function,
checkChildren: boolean,
Expand Down Expand Up @@ -135,15 +145,17 @@ export class FocusMonitor implements OnDestroy {

/**
* Focuses the element via the specified focus origin.
* @param element The element to focus.
* @param origin The focus origin.
* @param element Element to focus.
* @param origin Focus origin.
* @param focusOption Options that can be used to configure the focus behavior.
*/
focusVia(element: HTMLElement, origin: FocusOrigin): void {
focusVia(element: HTMLElement, origin: FocusOrigin, options?: FocusOptions): void {
this._setOriginForCurrentEventQueue(origin);

// `focus` isn't available on the server
if (typeof element.focus === 'function') {
element.focus();
// Cast the element to `any`, because the TS typings don't have the `options` parameter yet.
(element as any).focus(options);
}
}

Expand Down