Skip to content

Commit c4b3484

Browse files
crisbetommalerba
authored andcommittedDec 4, 2018
fix(a11y): inconsistent runtime value for ListKeyManager.activeItem (#14154)
The `activeItem` is currently typed to `T | null`, however on init and when assigning incorrect values, the `activeItem` will actually be `undefined` at runtime. These changes add some logic to make sure that the value is consistent with its type. Fixes #14152.
1 parent 48e4f65 commit c4b3484

File tree

2 files changed

+13
-2
lines changed

2 files changed

+13
-2
lines changed
 

‎src/cdk/a11y/key-manager/list-key-manager.spec.ts

+9
Original file line numberDiff line numberDiff line change
@@ -93,6 +93,15 @@ describe('Key managers', () => {
9393
expect(keyManager.activeItem!.getLabel()).toBe('one');
9494
});
9595

96+
it('should start off the activeItem as null', () => {
97+
expect(new ListKeyManager([]).activeItem).toBeNull();
98+
});
99+
100+
it('should set the activeItem to null if an invalid index is passed in', () => {
101+
keyManager.setActiveItem(1337);
102+
expect(keyManager.activeItem).toBeNull();
103+
});
104+
96105
describe('Key events', () => {
97106

98107
it('should emit tabOut when the tab key is pressed', () => {

‎src/cdk/a11y/key-manager/list-key-manager.ts

+4-2
Original file line numberDiff line numberDiff line change
@@ -40,7 +40,7 @@ export type ListKeyManagerModifierKey = 'altKey' | 'ctrlKey' | 'metaKey' | 'shif
4040
*/
4141
export class ListKeyManager<T extends ListKeyManagerOption> {
4242
private _activeItemIndex = -1;
43-
private _activeItem: T;
43+
private _activeItem: T | null = null;
4444
private _wrap = false;
4545
private _letterKeyStream = new Subject<string>();
4646
private _typeaheadSubscription = Subscription.EMPTY;
@@ -310,9 +310,11 @@ export class ListKeyManager<T extends ListKeyManagerOption> {
310310
updateActiveItem(item: any): void {
311311
const itemArray = this._getItemsArray();
312312
const index = typeof item === 'number' ? item : itemArray.indexOf(item);
313+
const activeItem = itemArray[index];
313314

315+
// Explicitly check for `null` and `undefined` because other falsy values are valid.
316+
this._activeItem = activeItem == null ? null : activeItem;
314317
this._activeItemIndex = index;
315-
this._activeItem = itemArray[index];
316318
}
317319

318320
/**

0 commit comments

Comments
 (0)
Please sign in to comment.