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.
This commit is contained in:
Kristiyan Kostadinov
2018-12-04 22:38:24 +01:00
committed by mmalerba
parent 48e4f65187
commit c4b3484632
2 changed files with 13 additions and 2 deletions
@@ -93,6 +93,15 @@ describe('Key managers', () => {
expect(keyManager.activeItem!.getLabel()).toBe('one');
});
it('should start off the activeItem as null', () => {
expect(new ListKeyManager([]).activeItem).toBeNull();
});
it('should set the activeItem to null if an invalid index is passed in', () => {
keyManager.setActiveItem(1337);
expect(keyManager.activeItem).toBeNull();
});
describe('Key events', () => {
it('should emit tabOut when the tab key is pressed', () => {
+4 -2
View File
@@ -40,7 +40,7 @@ export type ListKeyManagerModifierKey = 'altKey' | 'ctrlKey' | 'metaKey' | 'shif
*/
export class ListKeyManager<T extends ListKeyManagerOption> {
private _activeItemIndex = -1;
private _activeItem: T;
private _activeItem: T | null = null;
private _wrap = false;
private _letterKeyStream = new Subject<string>();
private _typeaheadSubscription = Subscription.EMPTY;
@@ -310,9 +310,11 @@ export class ListKeyManager<T extends ListKeyManagerOption> {
updateActiveItem(item: any): void {
const itemArray = this._getItemsArray();
const index = typeof item === 'number' ? item : itemArray.indexOf(item);
const activeItem = itemArray[index];
// Explicitly check for `null` and `undefined` because other falsy values are valid.
this._activeItem = activeItem == null ? null : activeItem;
this._activeItemIndex = index;
this._activeItem = itemArray[index];
}
/**