Skip to content

Commit

Permalink
fix(list-key-manager): prevent the default keyboard actions
Browse files Browse the repository at this point in the history
Calls preventDefault when handling keyboard events in the ListKeyManager. This avoids the user scrolling the page when using the arrow keys to navigate.

Relates to #1999.
  • Loading branch information
crisbeto committed Nov 28, 2016
1 parent cf1b4b9 commit 6868127
Show file tree
Hide file tree
Showing 2 changed files with 31 additions and 5 deletions.
32 changes: 27 additions & 5 deletions src/lib/core/a11y/list-key-manager.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -15,15 +15,23 @@ class FakeQueryList<T> extends QueryList<T> {
}
}

const DOWN_ARROW_EVENT = { keyCode: DOWN_ARROW } as KeyboardEvent;
const UP_ARROW_EVENT = { keyCode: UP_ARROW } as KeyboardEvent;
const TAB_EVENT = { keyCode: TAB } as KeyboardEvent;
const HOME_EVENT = { keyCode: HOME } as KeyboardEvent;
const END_EVENT = { keyCode: END } as KeyboardEvent;
class FakeEvent {
defaultPrevented: boolean = false;
constructor(public keyCode: number) {}
preventDefault() {
this.defaultPrevented = true;
}
}


describe('ListKeyManager', () => {
let keyManager: ListKeyManager;
let itemList: FakeQueryList<FakeFocusable>;
let DOWN_ARROW_EVENT: KeyboardEvent;
let UP_ARROW_EVENT: KeyboardEvent;
let TAB_EVENT: KeyboardEvent;
let HOME_EVENT: KeyboardEvent;
let END_EVENT: KeyboardEvent;

beforeEach(() => {
itemList = new FakeQueryList<FakeFocusable>();
Expand All @@ -35,6 +43,12 @@ describe('ListKeyManager', () => {

keyManager = new ListKeyManager(itemList);

DOWN_ARROW_EVENT = new FakeEvent(DOWN_ARROW) as KeyboardEvent;
UP_ARROW_EVENT = new FakeEvent(UP_ARROW) as KeyboardEvent;
TAB_EVENT = new FakeEvent(TAB) as KeyboardEvent;
HOME_EVENT = new FakeEvent(HOME) as KeyboardEvent;
END_EVENT = new FakeEvent(END) as KeyboardEvent;

// first item is already focused
keyManager.focusFirstItem();

Expand Down Expand Up @@ -166,6 +180,14 @@ describe('ListKeyManager', () => {
expect(tabOutEmitted).toBe(true);
});

it('should prevent the default keyboard action', () => {
expect(DOWN_ARROW_EVENT.defaultPrevented).toBe(false);

keyManager.onKeydown(DOWN_ARROW_EVENT);

expect(DOWN_ARROW_EVENT.defaultPrevented).toBe(true);
});

});

describe('programmatic focus', () => {
Expand Down
4 changes: 4 additions & 0 deletions src/lib/core/a11y/list-key-manager.ts
Original file line number Diff line number Diff line change
Expand Up @@ -42,15 +42,19 @@ export class ListKeyManager {
onKeydown(event: KeyboardEvent): void {
switch (event.keyCode) {
case DOWN_ARROW:
event.preventDefault();
this.focusNextItem();
break;
case UP_ARROW:
event.preventDefault();
this.focusPreviousItem();
break;
case HOME:
event.preventDefault();
this.focusFirstItem();
break;
case END:
event.preventDefault();
this.focusLastItem();
break;
case TAB:
Expand Down

0 comments on commit 6868127

Please sign in to comment.