Skip to content

Commit 4bf751e

Browse files
committed
feat(cdk/a11y): add activeItem into the TreeKeyManager
1 parent 03e09a2 commit 4bf751e

File tree

1 file changed

+30
-4
lines changed

1 file changed

+30
-4
lines changed

src/cdk/a11y/key-manager/tree-key-manager.ts

Lines changed: 30 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -7,7 +7,7 @@
77
*/
88

99
import {QueryList} from '@angular/core';
10-
import {Observable, Subject} from 'rxjs';
10+
import {isObservable, Observable, Subject} from 'rxjs';
1111

1212
// TODO(cassc): Temporarily disable tslint since this is just the raw API.
1313
// tslint:disable
@@ -91,7 +91,23 @@ export interface TreeKeyManagerOptions<T extends TreeKeyManagerItem> {
9191
* keyboard events occur.
9292
*/
9393
export class TreeKeyManager<T extends TreeKeyManagerItem> {
94-
constructor(options: TreeKeyManagerOptions<T>) {}
94+
private _activeItemIndex = -1;
95+
private _activeItem: T | null = null;
96+
97+
constructor({items}: TreeKeyManagerOptions<T>) {
98+
// We allow for the items to be an array or Observable because, in some cases, the consumer may
99+
// not have access to a QueryList of the items they want to manage (e.g. when the
100+
// items aren't being collected via `ViewChildren` or `ContentChildren`).
101+
if (items instanceof QueryList) {
102+
items.changes.subscribe((newItems: QueryList<T>) => {
103+
this._updateActiveItemIndex(newItems.toArray());
104+
});
105+
} else if (isObservable(items)) {
106+
items.subscribe(newItems => {
107+
this._updateActiveItemIndex(newItems);
108+
});
109+
}
110+
}
95111

96112
/**
97113
* Stream that emits any time the TAB key is pressed, so components can react
@@ -113,12 +129,22 @@ export class TreeKeyManager<T extends TreeKeyManagerItem> {
113129

114130
/** Index of the currently active item. */
115131
getActiveItemIndex(): number | null {
116-
return null;
132+
return this._activeItemIndex;
117133
}
118134

119135
/** The currently active item. */
120136
getActiveItem(): T | null {
121-
return null;
137+
return this._activeItem;
138+
}
139+
140+
private _updateActiveItemIndex(newItems: T[]) {
141+
if (this._activeItem) {
142+
const newIndex = newItems.indexOf(this._activeItem);
143+
144+
if (newIndex > -1 && newIndex !== this._activeItemIndex) {
145+
this._activeItemIndex = newIndex;
146+
}
147+
}
122148
}
123149
}
124150

0 commit comments

Comments
 (0)