Skip to content

Commit

Permalink
fix(autocomplete): don't block default arrow keys when using modifiers
Browse files Browse the repository at this point in the history
Currently we hijack all up/down arrow key events, however this interferes with keyboard shortcuts such as shift + up arrow for marking all of the text. These changes stop intercepting the arrow keys, if they're used with a modifier.

These changes also fix an issue where all the mocked out key events had the `metaKey` set to `true` on some browsers.
  • Loading branch information
crisbeto committed Jan 1, 2020
1 parent 09dc459 commit 49fa9c8
Show file tree
Hide file tree
Showing 2 changed files with 17 additions and 4 deletions.
9 changes: 5 additions & 4 deletions src/material/autocomplete/autocomplete-trigger.ts
Original file line number Diff line number Diff line change
Expand Up @@ -412,15 +412,16 @@ export class MatAutocompleteTrigger implements ControlValueAccessor, AfterViewIn
event.preventDefault();
} else if (this.autocomplete) {
const prevActiveItem = this.autocomplete._keyManager.activeItem;
const isArrowKey = keyCode === UP_ARROW || keyCode === DOWN_ARROW;
const isVerticalArrowKey = keyCode === UP_ARROW || keyCode === DOWN_ARROW;
const hasModifier = event.ctrlKey || event.altKey || event.metaKey || event.shiftKey;

if (this.panelOpen || keyCode === TAB) {
if ((isVerticalArrowKey && !hasModifier) || keyCode === TAB) {
this.autocomplete._keyManager.onKeydown(event);
} else if (isArrowKey && this._canOpen()) {
} else if (isVerticalArrowKey && this._canOpen()) {
this.openPanel();
}

if (isArrowKey || this.autocomplete._keyManager.activeItem !== prevActiveItem) {
if (isVerticalArrowKey || this.autocomplete._keyManager.activeItem !== prevActiveItem) {
this._scrollToOption();
}
}
Expand Down
12 changes: 12 additions & 0 deletions src/material/autocomplete/autocomplete.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -1250,6 +1250,18 @@ describe('MatAutocomplete', () => {
expect(!!trigger.activeOption).toBe(false, 'Expected no active options.');
}));

it('should not prevent the default action when a modifier key is pressed', () => {
['metaKey', 'ctrlKey', 'altKey', 'shiftKey'].forEach(name => {
const event = createKeyboardEvent('keydown', DOWN_ARROW);
Object.defineProperty(event, name, {get: () => true});

fixture.componentInstance.trigger._handleKeydown(event);
fixture.detectChanges();

expect(event.defaultPrevented).toBe(false, `Expected autocompete not to block ${name} key`);
});
});

});

describe('option groups', () => {
Expand Down

0 comments on commit 49fa9c8

Please sign in to comment.