-
Notifications
You must be signed in to change notification settings - Fork 208
/
KeySet.ts
517 lines (476 loc) · 16.1 KB
/
KeySet.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
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
/*---------------------------------------------------------------------------------------------
* Copyright (c) Bentley Systems, Incorporated. All rights reserved.
* See LICENSE.md in the project root for license terms and full copyright notice.
*--------------------------------------------------------------------------------------------*/
/** @packageDocumentation
* @module Core
*/
import { CompressedId64Set, Guid, GuidString, Id64, Id64String } from "@itwin/core-bentley";
import { EntityProps } from "@itwin/core-common";
import { InstanceId, InstanceKey } from "./EC";
import { PresentationError, PresentationStatus } from "./Error";
import { NodeKey, NodeKeyJSON } from "./hierarchy/Key";
/**
* A single key that identifies something in an iTwin.js application
* @public
*/
export type Key = Readonly<NodeKey> | Readonly<InstanceKey> | Readonly<EntityProps>;
/** @public */
// eslint-disable-next-line @typescript-eslint/no-redeclare
export namespace Key {
/** Check if the supplied key is a `NodeKey` */
export function isNodeKey(key: Key): key is NodeKey {
return !!(key as NodeKey).type;
}
/** Check if the supplied key is an `InstanceKey` */
export function isInstanceKey(key: Key): key is InstanceKey {
return !!(key as InstanceKey).className && !!(key as InstanceKey).id;
}
/** Check if the supplied key is an `EntityProps` */
export function isEntityProps(key: Key): key is EntityProps {
return !!(key as EntityProps).classFullName && !!(key as EntityProps).id;
}
}
/**
* A type for multiple keys that identify something in iModel.js application
* @public
*/
export type Keys = ReadonlyArray<Key> | Readonly<KeySet>;
/**
* A data structure of serialized [[KeySet]]
* @public
*/
export interface KeySetJSON {
/** JSON representation of a list of instance keys */
instanceKeys: Array<[string, string]>;
/** An array of serialized node keys */
// eslint-disable-next-line deprecation/deprecation
nodeKeys: NodeKeyJSON[];
}
/**
* A class that holds multiple [[Key]] objects. It's basically
* used as a container that holds multiple keys of different types.
*
* @public
*/
export class KeySet {
// note: all keys are stored as strings because we need ability to find them by value
private _instanceKeys: Map<string, Set<string>>; // lower case class name => instance ids
private _lowerCaseMap: Map<string, string>; // lower case class name => most recent class name
private _nodeKeys: Set<string>;
private _guid!: GuidString;
/**
* Creates an instance of KeySet.
* @param source Optional source to initialize from.
*/
constructor(source?: Keys) {
this._instanceKeys = new Map();
this._lowerCaseMap = new Map();
this._nodeKeys = new Set();
this.recalculateGuid();
if (source) {
this.add(source);
}
}
private recalculateGuid() {
// empty keyset should have empty guid, otherwise use a random guid value
this._guid = this.isEmpty ? Guid.empty : Guid.createValue();
}
/**
* Get a GUID that identifies changes in this keyset. The value
* does not uniquely identify contents of the keyset, but it can be
* used to check whether keyset has changed.
*/
public get guid(): GuidString {
return this._guid;
}
/**
* Get a map of instance keys stored in this KeySet
*
* **Warning**: getting instance keys might be expensive for
* large KeySets.
*/
public get instanceKeys(): Map<string, Set<InstanceId>> {
const map = new Map<string, Set<InstanceId>>();
for (const entry of this._instanceKeys) {
map.set(this._lowerCaseMap.get(entry["0"])!, new Set([...entry["1"]].map((key: string) => Id64.fromJSON(key))));
}
return map;
}
/**
* Get instance keys count
*/
public get instanceKeysCount(): number {
let count = 0;
this._instanceKeys.forEach((set: Set<string>) => (count += set.size));
return count;
}
/**
* Get a set of node keys stored in this KeySet
*
* **Warning**: getting node keys might be expensive for
* large KeySets.
*/
public get nodeKeys(): Set<NodeKey> {
const set = new Set<NodeKey>();
for (const serialized of this._nodeKeys) {
// eslint-disable-next-line deprecation/deprecation
const key = NodeKey.fromJSON(JSON.parse(serialized));
set.add(key);
}
return set;
}
/**
* Get node keys count
*/
public get nodeKeysCount(): number {
return this._nodeKeys.size;
}
private isKeySet(set: Keys | Key): set is Readonly<KeySet> {
return !!(set as KeySet)._nodeKeys && !!(set as KeySet)._instanceKeys;
}
private isKeysArray(keys: Keys | Key): keys is ReadonlyArray<Key> {
return Array.isArray(keys);
}
/**
* Clear this KeySet.
* @returns itself
*/
public clear(): KeySet {
if (this.isEmpty) {
return this;
}
this._instanceKeys = new Map();
this._lowerCaseMap = new Map();
this._nodeKeys = new Set();
this.recalculateGuid();
return this;
}
private addKeySet(keyset: Readonly<KeySet>, pred?: (key: Key) => boolean): void {
for (const key of (keyset as any)._nodeKeys) {
// eslint-disable-next-line deprecation/deprecation
if (!pred || pred(NodeKey.fromJSON(JSON.parse(key)))) {
this._nodeKeys.add(key);
}
}
for (const entry of (keyset as any)._instanceKeys) {
let set = this._instanceKeys.get(entry["0"]);
const className = (keyset as KeySet)._lowerCaseMap.get(entry["0"])!;
if (!set) {
set = new Set();
this._instanceKeys.set(entry["0"], set);
this._lowerCaseMap.set(entry["0"], className);
}
entry["1"].forEach((id: Id64String) => {
if (!pred || pred({ className, id })) {
set!.add(id);
}
});
}
}
private addKeySetJSON(keyset: Readonly<KeySetJSON>): void {
for (const key of keyset.nodeKeys) {
this._nodeKeys.add(JSON.stringify(key));
}
for (const entry of keyset.instanceKeys) {
const lcClassName = normalizeClassName(entry["0"]);
const idsJson: string | Id64String[] = entry["1"];
const ids: Set<Id64String> =
typeof idsJson === "string" ? (idsJson === Id64.invalid ? new Set([Id64.invalid]) : CompressedId64Set.decompressSet(idsJson)) : new Set(idsJson);
this._instanceKeys.set(lcClassName, ids);
this._lowerCaseMap.set(lcClassName, entry["0"]);
}
}
/**
* Add a key or keys to this KeySet.
* @param value A key or keys to add.
* @param pred An optional predicate function that indicates whether a key should be added
* @returns itself
*/
public add(value: Keys | Key, pred?: (key: Key) => boolean): KeySet {
if (!value) {
throw new PresentationError(PresentationStatus.InvalidArgument, `Invalid argument: value = ${value}`);
}
const sizeBefore = this.size;
if (this.isKeySet(value)) {
this.addKeySet(value, pred);
} else if (this.isKeysArray(value)) {
value.forEach((key) => this.add(key, pred));
} else if (!pred || pred(value)) {
if (Key.isEntityProps(value)) {
this.add({ className: value.classFullName, id: Id64.fromJSON(value.id) } as InstanceKey);
} else if (Key.isInstanceKey(value)) {
const lcClassName = normalizeClassName(value.className);
if (!this._instanceKeys.has(lcClassName)) {
this._instanceKeys.set(lcClassName, new Set());
this._lowerCaseMap.set(lcClassName, value.className);
}
this._lowerCaseMap.set(lcClassName, value.className);
this._instanceKeys.get(lcClassName)!.add(value.id);
} else if (Key.isNodeKey(value)) {
this._nodeKeys.add(JSON.stringify(value));
} else {
throw new PresentationError(PresentationStatus.InvalidArgument, `Invalid argument: value = ${JSON.stringify(value)}`);
}
}
if (this.size !== sizeBefore) {
this.recalculateGuid();
}
return this;
}
private deleteKeySet(keyset: Readonly<KeySet>): void {
for (const key of (keyset as any)._nodeKeys) {
this._nodeKeys.delete(key);
}
for (const entry of (keyset as any)._instanceKeys) {
const set = this._instanceKeys.get(entry["0"]);
if (set) {
entry["1"].forEach((key: string) => {
set.delete(key);
});
}
}
}
/**
* Deletes a key or keys from this KeySet.
* @param value A key or keys to delete.
* @returns itself
*/
public delete(value: Keys | Key): KeySet {
if (!value) {
throw new PresentationError(PresentationStatus.InvalidArgument, `Invalid argument: value = ${value}`);
}
const sizeBefore = this.size;
if (this.isKeySet(value)) {
this.deleteKeySet(value);
} else if (this.isKeysArray(value)) {
for (const key of value) {
this.delete(key);
}
} else if (Key.isEntityProps(value)) {
this.delete({ className: value.classFullName, id: value.id! } as InstanceKey);
} else if (Key.isInstanceKey(value)) {
const set = this._instanceKeys.get(normalizeClassName(value.className));
if (set) {
set.delete(value.id);
}
} else if (Key.isNodeKey(value)) {
this._nodeKeys.delete(JSON.stringify(value));
} else {
throw new PresentationError(PresentationStatus.InvalidArgument, `Invalid argument: value = ${JSON.stringify(value)}`);
}
if (this.size !== sizeBefore) {
this.recalculateGuid();
}
return this;
}
/**
* Check if this KeySet contains the specified key.
* @param value The key to check.
*/
public has(value: Key): boolean {
if (!value) {
throw new PresentationError(PresentationStatus.InvalidArgument, `Invalid argument: value = ${value}`);
}
if (Key.isEntityProps(value)) {
return this.has({ className: value.classFullName, id: value.id! } as InstanceKey);
}
if (Key.isInstanceKey(value)) {
const set = this._instanceKeys.get(normalizeClassName(value.className));
return !!(set && set.has(value.id));
}
if (Key.isNodeKey(value)) {
return this._nodeKeys.has(JSON.stringify(value));
}
throw new PresentationError(PresentationStatus.InvalidArgument, `Invalid argument: value = ${JSON.stringify(value)}`);
}
private hasKeySet(readonlyKeys: Readonly<KeySet>, checkType: "all" | "any"): boolean {
// note: cast-away read-onlyness to access private members...
const keys = readonlyKeys as KeySet;
if (checkType === "all") {
if (this._nodeKeys.size < keys._nodeKeys.size || this._instanceKeys.size < keys._instanceKeys.size) {
return false;
}
if ([...keys._nodeKeys].some((key) => !this._nodeKeys.has(key))) {
return false;
}
for (const otherEntry of keys._instanceKeys) {
const thisEntryKeys = this._instanceKeys.get(otherEntry["0"]);
if (!thisEntryKeys || thisEntryKeys.size < otherEntry["1"].size) {
return false;
}
if ([...otherEntry["1"]].some((key) => !thisEntryKeys.has(key))) {
return false;
}
}
return true;
}
// "any" check type
if ([...keys._nodeKeys].some((key) => this._nodeKeys.has(key))) {
return true;
}
for (const otherEntry of keys._instanceKeys) {
const thisEntryKeys = this._instanceKeys.get(otherEntry["0"]);
if (thisEntryKeys && [...otherEntry["1"]].some((key) => thisEntryKeys.has(key))) {
return true;
}
}
return false;
}
private hasKeysArray(keys: ReadonlyArray<Key>, checkType: "all" | "any"): boolean {
if (checkType === "all") {
if (this.size < keys.length) {
return false;
}
for (const key of keys) {
if (!this.has(key)) {
return false;
}
}
return true;
}
// "any" check type
for (const key of keys) {
if (this.has(key)) {
return true;
}
}
return false;
}
/**
* Check if this KeySet contains all the specified keys.
* @param keys The keys to check.
*/
public hasAll(keys: Keys): boolean {
if (!keys) {
throw new PresentationError(PresentationStatus.InvalidArgument, `Invalid argument: value = ${keys}`);
}
if (this.isKeySet(keys)) {
return this.hasKeySet(keys, "all");
}
if (this.isKeysArray(keys)) {
return this.hasKeysArray(keys, "all");
}
throw new PresentationError(PresentationStatus.InvalidArgument, `Invalid argument: keys = ${keys}`);
}
/**
* Check if this KeySet contains any of the specified keys.
* @param keys The keys to check.
*/
public hasAny(keys: Keys): boolean {
if (!keys) {
throw new PresentationError(PresentationStatus.InvalidArgument, `Invalid argument: value = ${keys}`);
}
if (this.isKeySet(keys)) {
return this.hasKeySet(keys, "any");
}
if (this.isKeysArray(keys)) {
return this.hasKeysArray(keys, "any");
}
throw new PresentationError(PresentationStatus.InvalidArgument, `Invalid argument: keys = ${keys}`);
}
/**
* Get the number of keys stored in this KeySet.
*/
public get size(): number {
const nodeKeysCount = this._nodeKeys.size;
let instanceIdsCount = 0;
for (const set of this._instanceKeys.values()) {
instanceIdsCount += set.size;
}
return nodeKeysCount + instanceIdsCount;
}
/**
* Is this KeySet currently empty.
*/
public get isEmpty(): boolean {
return 0 === this.size;
}
/** Iterate over all keys in this keyset. */
public some(callback: (key: Key) => boolean) {
for (const entry of this._instanceKeys) {
const className = this._lowerCaseMap.get(entry["0"].toLowerCase())!;
if (some(entry[1], (id: Id64String) => callback({ className, id }))) {
return true;
}
}
// eslint-disable-next-line deprecation/deprecation
return some(this._nodeKeys, (serializedKey: string) => callback(NodeKey.fromJSON(JSON.parse(serializedKey))));
}
/** Iterate over all keys in this keyset. */
public forEach(callback: (key: InstanceKey | NodeKey, index: number) => void) {
let index = 0;
this._instanceKeys.forEach((ids: Set<Id64String>, className: string) => {
const recentClassName = this._lowerCaseMap.get(className.toLowerCase())!;
ids.forEach((id: Id64String) => callback({ className: recentClassName, id }, index++));
});
this._nodeKeys.forEach((serializedKey: string) => {
// eslint-disable-next-line deprecation/deprecation
callback(NodeKey.fromJSON(JSON.parse(serializedKey)), index++);
});
}
/** Iterate over all keys in this keyset in batches */
public forEachBatch(batchSize: number, callback: (batch: KeySet, index: number) => void) {
const size = this.size;
const count = Math.ceil(size / batchSize);
if (1 === count) {
callback(this, 0);
return;
}
let batch = new KeySet();
let batchIndex = 0;
let currBatchSize = 0;
this.forEach((key, index) => {
batch.add(key);
++currBatchSize;
if (currBatchSize === batchSize || index === size - 1) {
callback(batch, batchIndex++);
batch = new KeySet();
currBatchSize = 0;
}
});
}
/**
* Serializes this KeySet to JSON
* @public
*/
public toJSON(): KeySetJSON {
const instanceKeys: [string, string][] = [];
for (const entry of this._instanceKeys.entries()) {
if (entry["1"].size > 0) {
const className = this._lowerCaseMap.get(entry["0"].toLowerCase());
const compressedIds = CompressedId64Set.sortAndCompress(entry["1"]);
instanceKeys.push([className!, compressedIds.length > 0 ? compressedIds : Id64.invalid]);
}
}
// eslint-disable-next-line deprecation/deprecation
const nodeKeys: NodeKeyJSON[] = [];
for (const serializedKey of this._nodeKeys.values()) {
nodeKeys.push(JSON.parse(serializedKey));
}
return {
instanceKeys,
nodeKeys,
};
}
/**
* Creates a KeySet from JSON
* @public
*/
public static fromJSON(json: KeySetJSON): KeySet {
const keyset = new KeySet();
keyset.addKeySetJSON(json);
return keyset;
}
}
function normalizeClassName(className: string) {
return className.replace(".", ":").toLowerCase();
}
const some = <TItem>(set: Set<TItem>, cb: (item: TItem) => boolean) => {
for (const item of set) {
if (cb(item)) {
return true;
}
}
return false;
};