Skip to content

Commit

Permalink
fix(menu): nested trigger staying highlighted after click
Browse files Browse the repository at this point in the history
Prevents the sub-menu trigger from staying highlighted if the user clicks on it and moves away to another menu item.

Fixes #6838.
  • Loading branch information
crisbeto committed Sep 11, 2017
1 parent f2cae6e commit 291dbb1
Show file tree
Hide file tree
Showing 3 changed files with 22 additions and 1 deletion.
6 changes: 5 additions & 1 deletion src/cdk/testing/event-objects.ts
Expand Up @@ -57,7 +57,11 @@ export function createKeyboardEvent(type: string, keyCode: number, target?: Elem

/** Creates a fake event object with any desired event type. */
export function createFakeEvent(type: string) {
let event = document.createEvent('Event');
const event = document.createEvent('Event');
event.initEvent(type, true, true);

// IE won't set `defaultPrevented` on synthetic events so we need to do it manually.
event.preventDefault = () => Object.defineProperty(event, 'defaultPrevented', {get: () => true});

return event;
}
7 changes: 7 additions & 0 deletions src/lib/menu/menu-trigger.ts
Expand Up @@ -413,6 +413,13 @@ export class MdMenuTrigger implements AfterViewInit, OnDestroy {
_handleMousedown(event: MouseEvent): void {
if (!isFakeMousedownFromScreenReader(event)) {
this._openedByMouse = true;

// Since clicking on the trigger won't close the menu if it opens a sub-menu,
// we should prevent focus from moving onto it via click to avoid the
// highlight from lingering on the menu item.
if (this.triggersSubmenu) {
event.preventDefault();
}
}
}

Expand Down
10 changes: 10 additions & 0 deletions src/lib/menu/menu.spec.ts
Expand Up @@ -29,6 +29,7 @@ import {
dispatchMouseEvent,
dispatchEvent,
createKeyboardEvent,
dispatchFakeEvent,
} from '@angular/cdk/testing';


Expand Down Expand Up @@ -1014,6 +1015,15 @@ describe('MdMenu', () => {
expect(overlay.querySelectorAll('.mat-menu-panel').length).toBe(2, 'Expected two open menus');
}));

it('should prevent the default mousedown action if the menu item opens a sub-menu', () => {
compileTestComponent();
instance.rootTrigger.openMenu();
fixture.detectChanges();

const event = dispatchFakeEvent(overlay.querySelector('[md-menu-item]')!, 'mousedown');
expect(event.defaultPrevented).toBe(true);
});

});

});
Expand Down

0 comments on commit 291dbb1

Please sign in to comment.