/
CombineNodeCollectionBase.ts
72 lines (60 loc) · 2.05 KB
/
CombineNodeCollectionBase.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
/*!
* Copyright 2021 Cognite AS
*/
import { IndexSet } from '@reveal/utilities';
import { NodeCollectionBase, SerializedNodeCollection } from './NodeCollectionBase';
/**
* Node collection that combines the result from multiple underlying node collections.
*/
export abstract class CombineNodeCollectionBase extends NodeCollectionBase {
private readonly _changedUnderlyingNodeCollectionHandler: () => void;
private _cachedCombinedIndexSet: IndexSet | undefined = undefined;
protected _nodeCollections: NodeCollectionBase[] = [];
constructor(classToken: string, nodeCollections?: NodeCollectionBase[]) {
super(classToken);
this._changedUnderlyingNodeCollectionHandler = this.makeDirty.bind(this);
if (nodeCollections) {
nodeCollections.forEach(x => this.add(x));
}
}
add(nodeCollection: NodeCollectionBase): void {
nodeCollection.on('changed', this._changedUnderlyingNodeCollectionHandler);
this._nodeCollections.push(nodeCollection);
this.makeDirty();
}
remove(nodeCollection: NodeCollectionBase): void {
const index = this._nodeCollections.indexOf(nodeCollection);
if (index < 0) {
throw new Error('Could not find set');
}
nodeCollection.off('changed', this._changedUnderlyingNodeCollectionHandler);
this._nodeCollections.splice(index, 1);
this.makeDirty();
}
/**
* Clears all underlying node collections.
*/
clear(): void {
this._nodeCollections.forEach(collection => collection.clear());
}
private makeDirty(): void {
if (this._cachedCombinedIndexSet === undefined) return;
this._cachedCombinedIndexSet = undefined;
this.notifyChanged();
}
/**
* @override
*/
getIndexSet(): IndexSet {
this._cachedCombinedIndexSet = this._cachedCombinedIndexSet ?? this.createCombinedIndexSet();
return this._cachedCombinedIndexSet;
}
/**
* @override
*/
get isLoading(): boolean {
return this._nodeCollections.some(x => x.isLoading);
}
public abstract serialize(): SerializedNodeCollection;
protected abstract createCombinedIndexSet(): IndexSet;
}