Skip to content
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
12 changes: 11 additions & 1 deletion src/material/bottom-sheet/bottom-sheet-container.ts
Original file line number Diff line number Diff line change
Expand Up @@ -222,7 +222,17 @@ export class MatBottomSheetContainer extends BasePortalOutlet implements OnDestr

// We need the extra check, because IE can set the `activeElement` to null in some cases.
if (this.bottomSheetConfig.restoreFocus && toFocus && typeof toFocus.focus === 'function') {
toFocus.focus();
const activeElement = this._document.activeElement;
const element = this._elementRef.nativeElement;

// Make sure that focus is still inside the bottom sheet or is on the body (usually because a
// non-focusable element like the backdrop was clicked) before moving it. It's possible that
// the consumer moved it themselves before the animation was done, in which case we shouldn't
// do anything.
if (!activeElement || activeElement === this._document.body || activeElement === element ||
element.contains(activeElement)) {
toFocus.focus();
}
}

if (this._focusTrap) {
Expand Down
38 changes: 38 additions & 0 deletions src/material/bottom-sheet/bottom-sheet.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -690,6 +690,44 @@ describe('MatBottomSheet', () => {
document.body.removeChild(button);
}));

it('should not move focus if it was moved outside the sheet while animating', fakeAsync(() => {
// Create a element that has focus before the bottom sheet is opened.
const button = document.createElement('button');
const otherButton = document.createElement('button');
const body = document.body;
button.id = 'bottom-sheet-trigger';
otherButton.id = 'other-button';
body.appendChild(button);
body.appendChild(otherButton);
button.focus();

const bottomSheetRef = bottomSheet.open(PizzaMsg, {viewContainerRef: testViewContainerRef});

flushMicrotasks();
viewContainerFixture.detectChanges();
flushMicrotasks();

expect(document.activeElement!.id).not.toBe('bottom-sheet-trigger',
'Expected the focus to change when the bottom sheet was opened.');

// Start the closing sequence and move focus out of bottom sheet.
bottomSheetRef.dismiss();
otherButton.focus();

expect(document.activeElement!.id)
.toBe('other-button', 'Expected focus to be on the alternate button.');

flushMicrotasks();
viewContainerFixture.detectChanges();
flush();

expect(document.activeElement!.id)
.toBe('other-button', 'Expected focus to stay on the alternate button.');

body.removeChild(button);
body.removeChild(otherButton);
}));

});

});
Expand Down