Skip to content

Commit bb8ab2e

Browse files
committed
feat(select): add ability to cycle through options with arrow keys when closed
* Adds the ability for users to select options by focusing on a closed `md-select` and pressing the up/down arrow keys. * Fixes a bug that prevents the selection from going to the first item in a `ListKeyManager`, if there were no previously-selected items. * Adds an extra null check to the `FocusKeyManager` to avoid issues where the focused item is cleared. Fixes #2990.
1 parent 94adecd commit bb8ab2e

File tree

5 files changed

+116
-7
lines changed

5 files changed

+116
-7
lines changed

src/lib/core/a11y/focus-key-manager.ts

Lines changed: 4 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -23,7 +23,10 @@ export class FocusKeyManager extends ListKeyManager<Focusable> {
2323
*/
2424
setActiveItem(index: number): void {
2525
super.setActiveItem(index);
26-
this.activeItem.focus();
26+
27+
if (this.activeItem) {
28+
this.activeItem.focus();
29+
}
2730
}
2831

2932
}

src/lib/core/a11y/list-key-manager.spec.ts

Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -240,6 +240,16 @@ describe('Key managers', () => {
240240
expect(TAB_EVENT.defaultPrevented).toBe(false);
241241
});
242242

243+
it('it should activate the first item when pressing down on a clean key manager', () => {
244+
keyManager = new ListKeyManager<FakeFocusable>(itemList);
245+
246+
expect(keyManager.activeItemIndex).toBeNull('Expected active index to default to null.');
247+
248+
keyManager.onKeydown(DOWN_ARROW_EVENT);
249+
250+
expect(keyManager.activeItemIndex).toBe(0, 'Expected first item to become active.');
251+
});
252+
243253
});
244254

245255
describe('programmatic focus', () => {

src/lib/core/a11y/list-key-manager.ts

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -16,7 +16,7 @@ export interface CanDisable {
1616
* of items, it will set the active item correctly when arrow events occur.
1717
*/
1818
export class ListKeyManager<T extends CanDisable> {
19-
private _activeItemIndex: number;
19+
private _activeItemIndex: number = null;
2020
private _activeItem: T;
2121
private _tabOut: Subject<any> = new Subject();
2222
private _wrap: boolean = false;

src/lib/select/select.spec.ts

Lines changed: 77 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -14,11 +14,12 @@ import {OverlayContainer} from '../core/overlay/overlay-container';
1414
import {MdSelect, MdSelectFloatPlaceholderType} from './select';
1515
import {MdOption} from '../core/option/option';
1616
import {Dir} from '../core/rtl/dir';
17+
import {DOWN_ARROW, UP_ARROW} from '../core/keyboard/keycodes';
1718
import {
1819
ControlValueAccessor, FormControl, FormsModule, NG_VALUE_ACCESSOR, ReactiveFormsModule
1920
} from '@angular/forms';
2021
import {ViewportRuler} from '../core/overlay/position/viewport-ruler';
21-
import {dispatchFakeEvent} from '../core/testing/dispatch-events';
22+
import {dispatchFakeEvent, dispatchKeyboardEvent} from '../core/testing/dispatch-events';
2223

2324
describe('MdSelect', () => {
2425
let overlayContainerElement: HTMLElement;
@@ -1079,6 +1080,81 @@ describe('MdSelect', () => {
10791080
expect(select.getAttribute('tabindex')).toEqual('0');
10801081
});
10811082

1083+
it('should be able to select options via the arrow keys on a closed select', () => {
1084+
const formControl = fixture.componentInstance.control;
1085+
const options = fixture.componentInstance.options.toArray();
1086+
1087+
expect(formControl.value).toBeFalsy('Expected no initial value.');
1088+
1089+
dispatchKeyboardEvent(select, 'keydown', DOWN_ARROW);
1090+
1091+
expect(options[0].selected).toBe(true, 'Expected first option to be selected.');
1092+
expect(formControl.value).toBe(options[0].value,
1093+
'Expected value from first option to have been set on the model.');
1094+
1095+
dispatchKeyboardEvent(select, 'keydown', DOWN_ARROW);
1096+
dispatchKeyboardEvent(select, 'keydown', DOWN_ARROW);
1097+
1098+
// Note that the third option is skipped, because it is disabled.
1099+
expect(options[3].selected).toBe(true, 'Expected fourth option to be selected.');
1100+
expect(formControl.value).toBe(options[3].value,
1101+
'Expected value from fourth option to have been set on the model.');
1102+
1103+
dispatchKeyboardEvent(select, 'keydown', UP_ARROW);
1104+
1105+
expect(options[1].selected).toBe(true, 'Expected second option to be selected.');
1106+
expect(formControl.value).toBe(options[1].value,
1107+
'Expected value from second option to have been set on the model.');
1108+
});
1109+
1110+
it('should do nothing if the key manager did not change the active item', () => {
1111+
const formControl = fixture.componentInstance.control;
1112+
1113+
expect(formControl.value).toBeNull('Expected form control value to be empty.');
1114+
expect(formControl.pristine).toBe(true, 'Expected form control to be clean.');
1115+
1116+
dispatchKeyboardEvent(select, 'keydown', 16); // Press a random key.
1117+
1118+
expect(formControl.value).toBeNull('Expected form control value to stay empty.');
1119+
expect(formControl.pristine).toBe(true, 'Expected form control to stay clean.');
1120+
});
1121+
1122+
it('should continue from the selected option when the value is set programmatically', () => {
1123+
const formControl = fixture.componentInstance.control;
1124+
1125+
formControl.setValue('eggs-5');
1126+
fixture.detectChanges();
1127+
1128+
dispatchKeyboardEvent(select, 'keydown', DOWN_ARROW);
1129+
1130+
expect(formControl.value).toBe('pasta-6');
1131+
expect(fixture.componentInstance.options.toArray()[6].selected).toBe(true);
1132+
});
1133+
1134+
it('should not cycle through the options if the control is disabled', () => {
1135+
const formControl = fixture.componentInstance.control;
1136+
1137+
formControl.setValue('eggs-5');
1138+
formControl.disable();
1139+
dispatchKeyboardEvent(select, 'keydown', DOWN_ARROW);
1140+
1141+
expect(formControl.value).toBe('eggs-5', 'Expected value to remain unchaged.');
1142+
});
1143+
1144+
it('should not wrap selection around after reaching the end of the options', () => {
1145+
const lastOption = fixture.componentInstance.options.last;
1146+
1147+
fixture.componentInstance.options.forEach(() => {
1148+
dispatchKeyboardEvent(select, 'keydown', DOWN_ARROW);
1149+
});
1150+
1151+
expect(lastOption.selected).toBe(true, 'Expected last option to be selected.');
1152+
1153+
dispatchKeyboardEvent(select, 'keydown', DOWN_ARROW);
1154+
1155+
expect(lastOption.selected).toBe(true, 'Expected last option to stay selected.');
1156+
});
1157+
10821158
});
10831159

10841160
describe('for options', () => {

src/lib/select/select.ts

Lines changed: 24 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -363,7 +363,8 @@ export class MdSelect implements AfterContentInit, ControlValueAccessor, OnDestr
363363
return this._dir ? this._dir.value === 'rtl' : false;
364364
}
365365

366-
/** The width of the trigger element. This is necessary to match
366+
/**
367+
* The width of the trigger element. This is necessary to match
367368
* the overlay width to the trigger width.
368369
*/
369370
_getWidth(): number {
@@ -374,6 +375,21 @@ export class MdSelect implements AfterContentInit, ControlValueAccessor, OnDestr
374375
_handleKeydown(event: KeyboardEvent): void {
375376
if (event.keyCode === ENTER || event.keyCode === SPACE) {
376377
this.open();
378+
} else if (!this.disabled) {
379+
let prevActiveItem = this._keyManager.activeItem;
380+
381+
// TODO(crisbeto): native selects also cycle through the options with left/right arrows,
382+
// however the key manager only supports up/down at the moment.
383+
this._keyManager.onKeydown(event);
384+
385+
let currentActiveItem = this._keyManager.activeItem as MdOption;
386+
387+
// TODO(crisbeto): once #2722 gets in, this should open
388+
// the panel instead of selecting in `multiple` mode.
389+
if (currentActiveItem !== prevActiveItem) {
390+
this._emitChangeEvent(currentActiveItem);
391+
currentActiveItem.select();
392+
}
377393
}
378394
}
379395

@@ -435,6 +451,7 @@ export class MdSelect implements AfterContentInit, ControlValueAccessor, OnDestr
435451
for (let i = 0; i < this.options.length; i++) {
436452
if (options[i].value === value) {
437453
options[i].select();
454+
this._keyManager.setActiveItem(i);
438455
return;
439456
}
440457
}
@@ -447,6 +464,7 @@ export class MdSelect implements AfterContentInit, ControlValueAccessor, OnDestr
447464
private _clearSelection(): void {
448465
this._selected = null;
449466
this._updateOptions();
467+
this._keyManager.setActiveItem(null);
450468
}
451469

452470
private _getTriggerRect(): ClientRect {
@@ -472,7 +490,7 @@ export class MdSelect implements AfterContentInit, ControlValueAccessor, OnDestr
472490
private _listenToOptions(): void {
473491
this.options.forEach((option: MdOption) => {
474492
const sub = option.onSelect.subscribe((event: MdOptionSelectEvent) => {
475-
if (event.isUserInput && this._selected !== option) {
493+
if (event.isUserInput) {
476494
this._emitChangeEvent(option);
477495
}
478496
this._onSelect(option);
@@ -489,8 +507,10 @@ export class MdSelect implements AfterContentInit, ControlValueAccessor, OnDestr
489507

490508
/** Emits an event when the user selects an option. */
491509
private _emitChangeEvent(option: MdOption): void {
492-
this._onChange(option.value);
493-
this.change.emit(new MdSelectChange(this, option.value));
510+
if (this._selected !== option) {
511+
this._onChange(option.value);
512+
this.change.emit(new MdSelectChange(this, option.value));
513+
}
494514
}
495515

496516
/** Records option IDs to pass to the aria-owns property. */

0 commit comments

Comments
 (0)