Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
36 changes: 36 additions & 0 deletions src/cdk/a11y/key-manager/list-key-manager.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -93,6 +93,42 @@ describe('Key managers', () => {
expect(keyManager.activeItem!.getLabel()).toBe('one');
});

it('should update the active item if the current one is removed and there is ' +
'a new one at the same index', () => {
expect(keyManager.activeItemIndex).toBe(0);
expect(keyManager.activeItem!.getLabel()).toBe('one');

itemList.reset([new FakeFocusable('new-0'), new FakeFocusable('new-1')]);
itemList.notifyOnChanges();

expect(keyManager.activeItemIndex).toBe(0);
expect(keyManager.activeItem!.getLabel()).toBe('new-0');
});

it('should clear the active item if nothing exists at the new index', () => {
keyManager.setActiveItem(2);

expect(keyManager.activeItemIndex).toBe(2);
expect(keyManager.activeItem!.getLabel()).toBe('three');

itemList.reset(itemList.toArray().slice(0, 1));
itemList.notifyOnChanges();

expect(keyManager.activeItemIndex).toBe(-1);
expect(keyManager.activeItem).toBe(null);
});

it('should clear the active item if the list is cleared', () => {
expect(keyManager.activeItemIndex).toBe(0);
expect(keyManager.activeItem!.getLabel()).toBe('one');

itemList.reset([]);
itemList.notifyOnChanges();

expect(keyManager.activeItemIndex).toBe(-1);
expect(keyManager.activeItem).toBe(null);
});

it('should start off the activeItem as null', () => {
expect(new ListKeyManager([]).activeItem).toBeNull();
});
Expand Down
6 changes: 4 additions & 2 deletions src/cdk/a11y/key-manager/list-key-manager.ts
Original file line number Diff line number Diff line change
Expand Up @@ -70,7 +70,9 @@ export class ListKeyManager<T extends ListKeyManagerOption> {
const itemArray = newItems.toArray();
const newIndex = itemArray.indexOf(this._activeItem);

if (newIndex > -1 && newIndex !== this._activeItemIndex) {
if (newIndex === -1) {
this.updateActiveItem(this._activeItemIndex);
} else if (newIndex !== this._activeItemIndex) {
this._activeItemIndex = newIndex;
}
}
Expand Down Expand Up @@ -349,7 +351,7 @@ export class ListKeyManager<T extends ListKeyManagerOption> {

// Explicitly check for `null` and `undefined` because other falsy values are valid.
this._activeItem = activeItem == null ? null : activeItem;
this._activeItemIndex = index;
this._activeItemIndex = activeItem == null ? -1 : index;
}

/**
Expand Down