Skip to content

fix(sidenav): restore focus if drawer is closed through backdrop click #19534

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
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
31 changes: 30 additions & 1 deletion src/material/sidenav/drawer.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -284,7 +284,36 @@ describe('MatDrawer', () => {
expect(testComponent.closeStartCount).toBe(0);
}));

it('should restore focus on close if focus is inside drawer', fakeAsync(() => {
it('should restore focus on close if backdrop has been clicked', fakeAsync(() => {
const fixture = TestBed.createComponent(BasicTestApp);
fixture.detectChanges();

const drawer = fixture.debugElement.query(By.directive(MatDrawer))!.componentInstance;
const openButton = fixture.componentInstance.openButton.nativeElement;

openButton.focus();
drawer.open();
fixture.detectChanges();
flush();

const backdrop = fixture.nativeElement.querySelector('.mat-drawer-backdrop');
expect(backdrop).toBeTruthy();

// Ensure the element that has been focused on drawer open is blurred. This simulates
// the behavior where clicks on the backdrop blur the active element.
if (document.activeElement !== null && document.activeElement instanceof HTMLElement) {
document.activeElement.blur();
}

backdrop.click();
fixture.detectChanges();
flush();

expect(document.activeElement)
.toBe(openButton, 'Expected focus to be restored to the open button on close.');
}));

it('should restore focus on close if focus is on drawer', fakeAsync(() => {
let fixture = TestBed.createComponent(BasicTestApp);

fixture.detectChanges();
Expand Down
62 changes: 44 additions & 18 deletions src/material/sidenav/drawer.ts
Original file line number Diff line number Diff line change
Expand Up @@ -283,7 +283,7 @@ export class MatDrawer implements AfterContentInit, AfterContentChecked, OnDestr
}

this._takeFocus();
} else {
} else if (this._isFocusWithinDrawer()) {
this._restoreFocus();
}
});
Expand Down Expand Up @@ -339,29 +339,31 @@ export class MatDrawer implements AfterContentInit, AfterContentChecked, OnDestr
}

/**
* If focus is currently inside the drawer, restores it to where it was before the drawer
* opened.
* Restores focus to the element that was originally focused when the drawer opened.
* If no element was focused at that time, the focus will be restored to the drawer.
*/
private _restoreFocus() {
if (!this.autoFocus) {
return;
}

const activeEl = this._doc && this._doc.activeElement;

if (activeEl && this._elementRef.nativeElement.contains(activeEl)) {
// Note that we don't check via `instanceof HTMLElement` so that we can cover SVGs as well.
if (this._elementFocusedBeforeDrawerWasOpened) {
this._focusMonitor.focusVia(this._elementFocusedBeforeDrawerWasOpened, this._openedVia);
} else {
this._elementRef.nativeElement.blur();
}
// Note that we don't check via `instanceof HTMLElement` so that we can cover SVGs as well.
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Nice, this is definitely easier to understand with the helper broken out

if (this._elementFocusedBeforeDrawerWasOpened) {
this._focusMonitor.focusVia(this._elementFocusedBeforeDrawerWasOpened, this._openedVia);
} else {
this._elementRef.nativeElement.blur();
}

this._elementFocusedBeforeDrawerWasOpened = null;
this._openedVia = null;
}

/** Whether focus is currently within the drawer. */
private _isFocusWithinDrawer(): boolean {
const activeEl = this._doc?.activeElement;
return !!activeEl && this._elementRef.nativeElement.contains(activeEl);
}

ngAfterContentInit() {
this._focusTrap = this._focusTrapFactory.create(this._elementRef.nativeElement);
this._updateFocusTrapState();
Expand Down Expand Up @@ -403,23 +405,47 @@ export class MatDrawer implements AfterContentInit, AfterContentChecked, OnDestr
return this.toggle(false);
}

/** Closes the drawer with context that the backdrop was clicked. */
_closeViaBackdropClick(): Promise<MatDrawerToggleResult> {
// If the drawer is closed upon a backdrop click, we always want to restore focus. We
// don't need to check whether focus is currently in the drawer, as clicking on the
// backdrop causes blurring of the active element.
return this._setOpen(/* isOpen */ false, /* restoreFocus */ true);
}

/**
* Toggle this drawer.
* @param isOpen Whether the drawer should be open.
* @param openedVia Whether the drawer was opened by a key press, mouse click or programmatically.
* Used for focus management after the sidenav is closed.
*/
toggle(isOpen: boolean = !this.opened, openedVia: FocusOrigin = 'program'):
Promise<MatDrawerToggleResult> {
toggle(isOpen: boolean = !this.opened, openedVia?: FocusOrigin)
: Promise<MatDrawerToggleResult> {
// If the focus is currently inside the drawer content and we are closing the drawer,
// restore the focus to the initially focused element (when the drawer opened).
return this._setOpen(
isOpen, /* restoreFocus */ !isOpen && this._isFocusWithinDrawer(), openedVia);
}

/**
* Toggles the opened state of the drawer.
* @param isOpen Whether the drawer should open or close.
* @param restoreFocus Whether focus should be restored on close.
* @param openedVia Focus origin that can be optionally set when opening a drawer. The
* origin will be used later when focus is restored on drawer close.
*/
private _setOpen(isOpen: boolean, restoreFocus: boolean, openedVia: FocusOrigin = 'program')
: Promise<MatDrawerToggleResult> {
this._opened = isOpen;

if (isOpen) {
this._animationState = this._enableAnimations ? 'open' : 'open-instant';
this._openedVia = openedVia;
} else {
this._animationState = 'void';
this._restoreFocus();
if (restoreFocus) {
this._restoreFocus();
}
}

this._updateFocusTrapState();
Expand Down Expand Up @@ -818,14 +844,14 @@ export class MatDrawerContainer implements AfterContentInit, DoCheck, OnDestroy

_onBackdropClicked() {
this.backdropClick.emit();
this._closeModalDrawer();
this._closeModalDrawersViaBackdrop();
}

_closeModalDrawer() {
_closeModalDrawersViaBackdrop() {
// Close all open drawers where closing is not disabled and the mode is not `side`.
[this._start, this._end]
.filter(drawer => drawer && !drawer.disableClose && this._canHaveBackdrop(drawer))
.forEach(drawer => drawer!.close());
.forEach(drawer => drawer!._closeViaBackdropClick());
}

_isShowingBackdrop(): boolean {
Expand Down
3 changes: 2 additions & 1 deletion tools/public_api_guard/material/sidenav.d.ts
Original file line number Diff line number Diff line change
Expand Up @@ -29,6 +29,7 @@ export declare class MatDrawer implements AfterContentInit, AfterContentChecked,
_container?: MatDrawerContainer | undefined);
_animationDoneListener(event: AnimationEvent): void;
_animationStartListener(event: AnimationEvent): void;
_closeViaBackdropClick(): Promise<MatDrawerToggleResult>;
close(): Promise<MatDrawerToggleResult>;
ngAfterContentChecked(): void;
ngAfterContentInit(): void;
Expand Down Expand Up @@ -69,7 +70,7 @@ export declare class MatDrawerContainer implements AfterContentInit, DoCheck, On
get scrollable(): CdkScrollable;
get start(): MatDrawer | null;
constructor(_dir: Directionality, _element: ElementRef<HTMLElement>, _ngZone: NgZone, _changeDetectorRef: ChangeDetectorRef, viewportRuler: ViewportRuler, defaultAutosize?: boolean, _animationMode?: string | undefined);
_closeModalDrawer(): void;
_closeModalDrawersViaBackdrop(): void;
_isShowingBackdrop(): boolean;
_onBackdropClicked(): void;
close(): void;
Expand Down