Skip to content

Commit 3cddd0a

Browse files
committed
fix(material/sidenav): end position sidenav tab order not matching visual order
We project all sidenavs before the content in the DOM since we can't know ahead of time what their position will be. This is problematic when the drawer is in the end position, because the visual order of the content no longer matches the tab order. These changes fix the issue by moving the sidenav after the content manually when it's set to `end` and then moving it back if it's set to `start` again. A couple of notes: 1. We could technically do this with content projection, but it would only work when the `position` value is static (e.g. `position="end"`). I did it this way so we can cover the case where it's data bound. 2. Currently the focus trap anchors are set around the sidenav, but that's problematic when we're moving the element around since the anchors will be left at their old positions. To avoid adding extra logic for moving the anchors, I've moved the focus trap to be inside the sidenav. Here's what the DOM looks like at the moment: ```html <container> <anchor/> <sidenav>Content</sidenav> <anchor/> </container> ``` And this is what I've changed it to: ```html <container> <sidenav> <anchor/> Content <anchor/> </sidenav> </container ``` Fixes #15247.
1 parent 20d3469 commit 3cddd0a

File tree

4 files changed

+195
-12
lines changed

4 files changed

+195
-12
lines changed

src/material/sidenav/drawer.html

+1-1
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,3 @@
1-
<div class="mat-drawer-inner-container" cdkScrollable>
1+
<div class="mat-drawer-inner-container" cdkScrollable #content>
22
<ng-content></ng-content>
33
</div>

src/material/sidenav/drawer.spec.ts

+132-1
Original file line numberDiff line numberDiff line change
@@ -653,6 +653,110 @@ describe('MatDrawer', () => {
653653
expect(scrollable.getElementRef().nativeElement).toBe(content.nativeElement);
654654
});
655655

656+
describe('DOM position', () => {
657+
it('should project start drawer before the content', () => {
658+
const fixture = TestBed.createComponent(BasicTestApp);
659+
fixture.componentInstance.position = 'start';
660+
fixture.detectChanges();
661+
662+
const allNodes = getDrawerNodesArray(fixture);
663+
const drawerIndex = allNodes.indexOf(fixture.nativeElement.querySelector('.mat-drawer'));
664+
const contentIndex =
665+
allNodes.indexOf(fixture.nativeElement.querySelector('.mat-drawer-content'));
666+
667+
expect(drawerIndex).toBeGreaterThan(-1, 'Expected drawer to be inside the container');
668+
expect(contentIndex).toBeGreaterThan(-1, 'Expected content to be inside the container');
669+
expect(drawerIndex).toBeLessThan(contentIndex, 'Expected drawer to be before the content');
670+
});
671+
672+
it('should project end drawer after the content', () => {
673+
const fixture = TestBed.createComponent(BasicTestApp);
674+
fixture.componentInstance.position = 'end';
675+
fixture.detectChanges();
676+
677+
const allNodes = getDrawerNodesArray(fixture);
678+
const drawerIndex = allNodes.indexOf(fixture.nativeElement.querySelector('.mat-drawer'));
679+
const contentIndex =
680+
allNodes.indexOf(fixture.nativeElement.querySelector('.mat-drawer-content'));
681+
682+
expect(drawerIndex).toBeGreaterThan(-1, 'Expected drawer to be inside the container');
683+
expect(contentIndex).toBeGreaterThan(-1, 'Expected content to be inside the container');
684+
expect(drawerIndex).toBeGreaterThan(contentIndex, 'Expected drawer to be after the content');
685+
});
686+
687+
it('should move the drawer before/after the content when its position changes after being ' +
688+
'initialized at `start`', () => {
689+
const fixture = TestBed.createComponent(BasicTestApp);
690+
fixture.componentInstance.position = 'start';
691+
fixture.detectChanges();
692+
693+
const drawer = fixture.nativeElement.querySelector('.mat-drawer');
694+
const content = fixture.nativeElement.querySelector('.mat-drawer-content');
695+
696+
let allNodes = getDrawerNodesArray(fixture);
697+
const startDrawerIndex = allNodes.indexOf(drawer);
698+
const startContentIndex = allNodes.indexOf(content);
699+
700+
expect(startDrawerIndex).toBeGreaterThan(-1, 'Expected drawer to be inside the container');
701+
expect(startContentIndex)
702+
.toBeGreaterThan(-1, 'Expected content to be inside the container');
703+
expect(startDrawerIndex)
704+
.toBeLessThan(startContentIndex, 'Expected drawer to be before the content on init');
705+
706+
fixture.componentInstance.position = 'end';
707+
fixture.detectChanges();
708+
allNodes = getDrawerNodesArray(fixture);
709+
710+
expect(allNodes.indexOf(drawer)).toBeGreaterThan(allNodes.indexOf(content),
711+
'Expected drawer to be after content when position changes to `end`');
712+
713+
fixture.componentInstance.position = 'start';
714+
fixture.detectChanges();
715+
allNodes = getDrawerNodesArray(fixture);
716+
717+
expect(allNodes.indexOf(drawer)).toBeLessThan(allNodes.indexOf(content),
718+
'Expected drawer to be before content when position changes back to `start`');
719+
});
720+
721+
it('should move the drawer before/after the content when its position changes after being ' +
722+
'initialized at `end`', () => {
723+
const fixture = TestBed.createComponent(BasicTestApp);
724+
fixture.componentInstance.position = 'end';
725+
fixture.detectChanges();
726+
727+
const drawer = fixture.nativeElement.querySelector('.mat-drawer');
728+
const content = fixture.nativeElement.querySelector('.mat-drawer-content');
729+
730+
let allNodes = getDrawerNodesArray(fixture);
731+
const startDrawerIndex = allNodes.indexOf(drawer);
732+
const startContentIndex = allNodes.indexOf(content);
733+
734+
expect(startDrawerIndex).toBeGreaterThan(-1, 'Expected drawer to be inside the container');
735+
expect(startContentIndex)
736+
.toBeGreaterThan(-1, 'Expected content to be inside the container');
737+
expect(startDrawerIndex)
738+
.toBeGreaterThan(startContentIndex, 'Expected drawer to be after the content on init');
739+
740+
fixture.componentInstance.position = 'start';
741+
fixture.detectChanges();
742+
allNodes = getDrawerNodesArray(fixture);
743+
744+
expect(allNodes.indexOf(drawer)).toBeLessThan(allNodes.indexOf(content),
745+
'Expected drawer to be before content when position changes to `start`');
746+
747+
fixture.componentInstance.position = 'end';
748+
fixture.detectChanges();
749+
allNodes = getDrawerNodesArray(fixture);
750+
751+
expect(allNodes.indexOf(drawer)).toBeGreaterThan(allNodes.indexOf(content),
752+
'Expected drawer to be after content when position changes back to `end`');
753+
});
754+
755+
function getDrawerNodesArray(fixture: ComponentFixture<any>): HTMLElement[] {
756+
return Array.from(fixture.nativeElement.querySelector('.mat-drawer-container').childNodes);
757+
}
758+
759+
});
656760
});
657761

658762
describe('MatDrawerContainer', () => {
@@ -936,6 +1040,32 @@ describe('MatDrawerContainer', () => {
9361040
expect(spy).toHaveBeenCalled();
9371041
subscription.unsubscribe();
9381042
}));
1043+
1044+
it('should position the drawers before/after the content in the DOM based on their position',
1045+
fakeAsync(() => {
1046+
const fixture = TestBed.createComponent(DrawerContainerTwoDrawerTestApp);
1047+
fixture.detectChanges();
1048+
1049+
const drawerDebugElements = fixture.debugElement.queryAll(By.directive(MatDrawer));
1050+
const [start, end] = drawerDebugElements.map(el => el.componentInstance);
1051+
const [startNode, endNode] = drawerDebugElements.map(el => el.nativeElement);
1052+
const contentNode = fixture.nativeElement.querySelector('.mat-drawer-content');
1053+
const allNodes: HTMLElement[] =
1054+
Array.from(fixture.nativeElement.querySelector('.mat-drawer-container').childNodes);
1055+
const startIndex = allNodes.indexOf(startNode);
1056+
const endIndex = allNodes.indexOf(endNode);
1057+
const contentIndex = allNodes.indexOf(contentNode);
1058+
1059+
expect(start.position).toBe('start');
1060+
expect(end.position).toBe('end');
1061+
expect(contentIndex).toBeGreaterThan(-1, 'Expected content to be inside the container');
1062+
expect(startIndex).toBeGreaterThan(-1, 'Expected start drawer to be inside the container');
1063+
expect(endIndex).toBeGreaterThan(-1, 'Expected end drawer to be inside the container');
1064+
1065+
expect(startIndex).toBeLessThan(contentIndex, 'Expected start drawer to be before content');
1066+
expect(endIndex).toBeGreaterThan(contentIndex, 'Expected end drawer to be after content');
1067+
}));
1068+
9391069
});
9401070

9411071

@@ -959,7 +1089,7 @@ class DrawerContainerTwoDrawerTestApp {
9591089
@Component({
9601090
template: `
9611091
<mat-drawer-container (backdropClick)="backdropClicked()" [hasBackdrop]="hasBackdrop">
962-
<mat-drawer #drawer="matDrawer" position="start"
1092+
<mat-drawer #drawer="matDrawer" [position]="position"
9631093
(opened)="open()"
9641094
(openedStart)="openStart()"
9651095
(closed)="close()"
@@ -985,6 +1115,7 @@ class BasicTestApp {
9851115
closeStartCount = 0;
9861116
backdropClickedCount = 0;
9871117
hasBackdrop: boolean | null = null;
1118+
position = 'start';
9881119

9891120
@ViewChild('drawer') drawer: MatDrawer;
9901121
@ViewChild('drawerButton') drawerButton: ElementRef<HTMLButtonElement>;

src/material/sidenav/drawer.ts

+58-7
Original file line numberDiff line numberDiff line change
@@ -37,6 +37,7 @@ import {
3737
ViewEncapsulation,
3838
HostListener,
3939
HostBinding,
40+
AfterViewInit,
4041
} from '@angular/core';
4142
import {fromEvent, merge, Observable, Subject} from 'rxjs';
4243
import {
@@ -138,20 +139,32 @@ export class MatDrawerContent extends CdkScrollable implements AfterContentInit
138139
changeDetection: ChangeDetectionStrategy.OnPush,
139140
encapsulation: ViewEncapsulation.None,
140141
})
141-
export class MatDrawer implements AfterContentInit, AfterContentChecked, OnDestroy {
142+
export class MatDrawer implements AfterViewInit, AfterContentChecked, OnDestroy {
142143
private _focusTrap: FocusTrap;
143144
private _elementFocusedBeforeDrawerWasOpened: HTMLElement | null = null;
145+
private _document: Document;
144146

145147
/** Whether the drawer is initialized. Used for disabling the initial animation. */
146148
private _enableAnimations = false;
147149

150+
/** Whether the view of the component has been attached. */
151+
private _isAttached: boolean;
152+
153+
/** Anchor node used to restore the drawer to its initial position. */
154+
private _anchor: Comment | null;
155+
148156
/** The side that the drawer is attached to. */
149157
@Input()
150158
get position(): 'start' | 'end' { return this._position; }
151159
set position(value: 'start' | 'end') {
152160
// Make sure we have a valid value.
153161
value = value === 'end' ? 'end' : 'start';
154-
if (value != this._position) {
162+
if (value !== this._position) {
163+
// Static inputs in Ivy are set before the element is in the DOM.
164+
if (this._isAttached) {
165+
this._updatePositionInParent(value);
166+
}
167+
155168
this._position = value;
156169
this.onPositionChanged.emit();
157170
}
@@ -251,6 +264,9 @@ export class MatDrawer implements AfterContentInit, AfterContentChecked, OnDestr
251264
// tslint:disable-next-line:no-output-on-prefix
252265
@Output('positionChanged') readonly onPositionChanged = new EventEmitter<void>();
253266

267+
/** Reference to the inner element that contains all the content. */
268+
@ViewChild('content') _content: ElementRef<HTMLElement>;
269+
254270
/**
255271
* An observable that emits when the drawer mode changes. This is used by the drawer container to
256272
* to know when to when the mode changes so it can adapt the margins on the content.
@@ -262,13 +278,14 @@ export class MatDrawer implements AfterContentInit, AfterContentChecked, OnDestr
262278
private _focusMonitor: FocusMonitor,
263279
private _platform: Platform,
264280
private _ngZone: NgZone,
265-
@Optional() @Inject(DOCUMENT) private _doc: any,
281+
@Optional() @Inject(DOCUMENT) _document: any,
266282
@Optional() @Inject(MAT_DRAWER_CONTAINER) public _container?: MatDrawerContainer) {
267283

284+
this._document = _document;
268285
this.openedChange.subscribe((opened: boolean) => {
269286
if (opened) {
270-
if (this._doc) {
271-
this._elementFocusedBeforeDrawerWasOpened = this._doc.activeElement as HTMLElement;
287+
if (this._document) {
288+
this._elementFocusedBeforeDrawerWasOpened = this._document.activeElement as HTMLElement;
272289
}
273290

274291
this._takeFocus();
@@ -349,13 +366,20 @@ export class MatDrawer implements AfterContentInit, AfterContentChecked, OnDestr
349366

350367
/** Whether focus is currently within the drawer. */
351368
private _isFocusWithinDrawer(): boolean {
352-
const activeEl = this._doc?.activeElement;
369+
const activeEl = this._document.activeElement;
353370
return !!activeEl && this._elementRef.nativeElement.contains(activeEl);
354371
}
355372

356-
ngAfterContentInit() {
373+
ngAfterViewInit() {
374+
this._isAttached = true;
357375
this._focusTrap = this._focusTrapFactory.create(this._elementRef.nativeElement);
358376
this._updateFocusTrapState();
377+
378+
// Only update the DOM position when the sidenav is positioned at
379+
// the end since we project the sidenav before the content by default.
380+
if (this._position === 'end') {
381+
this._updatePositionInParent('end');
382+
}
359383
}
360384

361385
ngAfterContentChecked() {
@@ -373,6 +397,11 @@ export class MatDrawer implements AfterContentInit, AfterContentChecked, OnDestr
373397
this._focusTrap.destroy();
374398
}
375399

400+
if (this._anchor && this._anchor.parentNode) {
401+
this._anchor.parentNode.removeChild(this._anchor);
402+
}
403+
404+
this._anchor = null;
376405
this._animationStarted.complete();
377406
this._animationEnd.complete();
378407
this._modeChanged.complete();
@@ -456,6 +485,28 @@ export class MatDrawer implements AfterContentInit, AfterContentChecked, OnDestr
456485
}
457486
}
458487

488+
/**
489+
* Updates the position of the drawer in the DOM. We need to move the element around ourselves
490+
* when it's in the `end` position so that it comes after the content and the visual order
491+
* matches the tab order. We also need to be able to move it back to `start` if the sidenav
492+
* started off as `end` and was changed to `start`.
493+
*/
494+
private _updatePositionInParent(newPosition: 'start' | 'end') {
495+
const element = this._elementRef.nativeElement;
496+
const parent = element.parentNode!;
497+
498+
if (newPosition === 'end') {
499+
if (!this._anchor) {
500+
this._anchor = this._document.createComment('mat-drawer-anchor');
501+
parent.insertBefore(this._anchor, element);
502+
}
503+
504+
parent.appendChild(element);
505+
} else if (this._anchor) {
506+
this._anchor.parentNode!.insertBefore(element, this._anchor);
507+
}
508+
}
509+
459510
// We have to use a `HostListener` here in order to support both Ivy and ViewEngine.
460511
// In Ivy the `host` bindings will be merged when this class is extended, whereas in
461512
// ViewEngine they're overwritten.

tools/public_api_guard/material/sidenav.d.ts

+4-3
Original file line numberDiff line numberDiff line change
@@ -2,12 +2,13 @@ export declare const MAT_DRAWER_DEFAULT_AUTOSIZE: InjectionToken<boolean>;
22

33
export declare function MAT_DRAWER_DEFAULT_AUTOSIZE_FACTORY(): boolean;
44

5-
export declare class MatDrawer implements AfterContentInit, AfterContentChecked, OnDestroy {
5+
export declare class MatDrawer implements AfterViewInit, AfterContentChecked, OnDestroy {
66
readonly _animationEnd: Subject<AnimationEvent>;
77
readonly _animationStarted: Subject<AnimationEvent>;
88
_animationState: 'open-instant' | 'open' | 'void';
99
readonly _closedStream: Observable<void>;
1010
_container?: MatDrawerContainer | undefined;
11+
_content: ElementRef<HTMLElement>;
1112
readonly _modeChanged: Subject<void>;
1213
readonly _openedStream: Observable<void>;
1314
get autoFocus(): boolean;
@@ -24,14 +25,14 @@ export declare class MatDrawer implements AfterContentInit, AfterContentChecked,
2425
readonly openedStart: Observable<void>;
2526
get position(): 'start' | 'end';
2627
set position(value: 'start' | 'end');
27-
constructor(_elementRef: ElementRef<HTMLElement>, _focusTrapFactory: FocusTrapFactory, _focusMonitor: FocusMonitor, _platform: Platform, _ngZone: NgZone, _doc: any, _container?: MatDrawerContainer | undefined);
28+
constructor(_elementRef: ElementRef<HTMLElement>, _focusTrapFactory: FocusTrapFactory, _focusMonitor: FocusMonitor, _platform: Platform, _ngZone: NgZone, _document: any, _container?: MatDrawerContainer | undefined);
2829
_animationDoneListener(event: AnimationEvent): void;
2930
_animationStartListener(event: AnimationEvent): void;
3031
_closeViaBackdropClick(): Promise<MatDrawerToggleResult>;
3132
_getWidth(): number;
3233
close(): Promise<MatDrawerToggleResult>;
3334
ngAfterContentChecked(): void;
34-
ngAfterContentInit(): void;
35+
ngAfterViewInit(): void;
3536
ngOnDestroy(): void;
3637
open(openedVia?: FocusOrigin): Promise<MatDrawerToggleResult>;
3738
toggle(isOpen?: boolean, openedVia?: FocusOrigin): Promise<MatDrawerToggleResult>;

0 commit comments

Comments
 (0)