Skip to content

fix(material/menu): focus lost if active item is removed #14039

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
Feb 27, 2022
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
37 changes: 37 additions & 0 deletions src/material-experimental/mdc-menu/menu.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -259,6 +259,28 @@ describe('MDC-based MatMenu', () => {
tick(500);
}));

it('should move focus to another item if the active item is destroyed', fakeAsync(() => {
const fixture = createComponent(MenuWithRepeatedItems, [], [FakeIcon]);
fixture.detectChanges();
const triggerEl = fixture.componentInstance.triggerEl.nativeElement;

triggerEl.click();
fixture.detectChanges();
tick(500);

const items = overlayContainerElement.querySelectorAll(
'.mat-mdc-menu-panel .mat-mdc-menu-item',
);

expect(document.activeElement).toBe(items[0]);

fixture.componentInstance.items.shift();
fixture.detectChanges();
tick(500);

expect(document.activeElement).toBe(items[1]);
}));

it('should be able to set a custom class on the backdrop', fakeAsync(() => {
const fixture = createComponent(SimpleMenu, [], [FakeIcon]);

Expand Down Expand Up @@ -3071,3 +3093,18 @@ class StaticAriaLabelledByMenu {}
template: '<mat-menu aria-describedby="some-element"></mat-menu>',
})
class StaticAriaDescribedbyMenu {}

@Component({
template: `
<button [matMenuTriggerFor]="menu" #triggerEl>Toggle menu</button>
<mat-menu #menu="matMenu">
<button *ngFor="let item of items" mat-menu-item>{{item}}</button>
</mat-menu>
`,
})
class MenuWithRepeatedItems {
@ViewChild(MatMenuTrigger, {static: false}) trigger: MatMenuTrigger;
@ViewChild('triggerEl', {static: false}) triggerEl: ElementRef<HTMLElement>;
@ViewChild(MatMenu, {static: false}) menu: MatMenu;
items = ['One', 'Two', 'Three'];
}
9 changes: 6 additions & 3 deletions src/material/menu/menu-item.ts
Original file line number Diff line number Diff line change
Expand Up @@ -76,8 +76,7 @@ export class MatMenuItem
_triggersSubmenu: boolean = false;

/**
* @deprecated `document` parameter to be removed, `changeDetectorRef` and
* `focusMonitor` to become required.
* @deprecated `_document`, `changeDetectorRef` and `focusMonitor` to become required.
* @breaking-change 12.0.0
*/
constructor(
Expand All @@ -90,7 +89,7 @@ export class MatMenuItem

constructor(
private _elementRef: ElementRef<HTMLElement>,
@Inject(DOCUMENT) _document?: any,
@Inject(DOCUMENT) private _document?: any,
private _focusMonitor?: FocusMonitor,
@Inject(MAT_MENU_PANEL) @Optional() public _parentMenu?: MatMenuPanel<MatMenuItem>,
private _changeDetectorRef?: ChangeDetectorRef,
Expand Down Expand Up @@ -176,4 +175,8 @@ export class MatMenuItem
this._highlighted = isHighlighted;
this._changeDetectorRef?.markForCheck();
}

_hasFocus(): boolean {
return this._document && this._document.activeElement === this._getHostElement();
}
}
36 changes: 36 additions & 0 deletions src/material/menu/menu.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -259,6 +259,26 @@ describe('MatMenu', () => {
tick(500);
}));

it('should move focus to another item if the active item is destroyed', fakeAsync(() => {
const fixture = createComponent(MenuWithRepeatedItems, [], [FakeIcon]);
fixture.detectChanges();
const triggerEl = fixture.componentInstance.triggerEl.nativeElement;

triggerEl.click();
fixture.detectChanges();
tick(500);

const items = overlayContainerElement.querySelectorAll('.mat-menu-panel .mat-menu-item');

expect(document.activeElement).toBe(items[0]);

fixture.componentInstance.items.shift();
fixture.detectChanges();
tick(500);

expect(document.activeElement).toBe(items[1]);
}));

it('should be able to set a custom class on the backdrop', fakeAsync(() => {
const fixture = createComponent(SimpleMenu, [], [FakeIcon]);

Expand Down Expand Up @@ -351,6 +371,7 @@ describe('MatMenu', () => {
// Add 50 items to make the menu scrollable
fixture.componentInstance.extraItems = new Array(50).fill('Hello there');
fixture.detectChanges();
tick(50);

const triggerEl = fixture.componentInstance.triggerEl.nativeElement;
dispatchFakeEvent(triggerEl, 'mousedown');
Expand Down Expand Up @@ -3053,3 +3074,18 @@ class StaticAriaLabelledByMenu {}
template: '<mat-menu aria-describedby="some-element"></mat-menu>',
})
class StaticAriaDescribedbyMenu {}

@Component({
template: `
<button [matMenuTriggerFor]="menu" #triggerEl>Toggle menu</button>
<mat-menu #menu="matMenu">
<button *ngFor="let item of items" mat-menu-item>{{item}}</button>
</mat-menu>
`,
})
class MenuWithRepeatedItems {
@ViewChild(MatMenuTrigger, {static: false}) trigger: MatMenuTrigger;
@ViewChild('triggerEl', {static: false}) triggerEl: ElementRef<HTMLElement>;
@ViewChild(MatMenu, {static: false}) menu: MatMenu;
items = ['One', 'Two', 'Three'];
}
18 changes: 18 additions & 0 deletions src/material/menu/menu.ts
Original file line number Diff line number Diff line change
Expand Up @@ -298,6 +298,24 @@ export class _MatMenuBase
switchMap(items => merge(...items.map((item: MatMenuItem) => item._focused))),
)
.subscribe(focusedItem => this._keyManager.updateActiveItem(focusedItem as MatMenuItem));

this._directDescendantItems.changes.subscribe((itemsList: QueryList<MatMenuItem>) => {
// Move focus to another item, if the active item is removed from the list.
// We need to debounce the callback, because multiple items might be removed
// in quick succession.
const manager = this._keyManager;

if (this._panelAnimationState === 'enter' && manager.activeItem?._hasFocus()) {
const items = itemsList.toArray();
const index = Math.max(0, Math.min(items.length - 1, manager.activeItemIndex || 0));

if (items[index] && !items[index].disabled) {
manager.setActiveItem(index);
} else {
manager.setNextItemActive();
}
}
});
}

ngOnDestroy() {
Expand Down
2 changes: 2 additions & 0 deletions tools/public_api_guard/material/menu.md
Original file line number Diff line number Diff line change
Expand Up @@ -203,6 +203,8 @@ export class MatMenuItem extends _MatMenuItemBase implements FocusableOption, Ca
getLabel(): string;
_getTabIndex(): string;
_handleMouseEnter(): void;
// (undocumented)
_hasFocus(): boolean;
_highlighted: boolean;
readonly _hovered: Subject<MatMenuItem>;
// (undocumented)
Expand Down