Repository navigation
Expand file tree
/
Copy pathbase.ts
More file actions
78 lines (67 loc) · 1.93 KB
/
Copy pathbase.ts
File metadata and controls
78 lines (67 loc) · 1.93 KB
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
import EventEmitter from "eventemitter3";
import type CCStore from ".";
import type {
CCObject,
CCObjectByType,
CCObjectId,
CCObjectStore,
CCObjectType,
CCReferences,
} from "./types";
/** Events emitted by every object-specific store */
export type CCObjectStoreEvents<T> = {
didRegister(object: T): void;
willUnregister(object: T): void;
didUnregister(object: T): void;
};
/** Base class of the object-specific stores (components, nodes, pins, and connections) */
export abstract class CCObjectStoreBase<
K extends CCObjectType,
Events extends CCObjectStoreEvents<CCObjectByType[K]>,
>
extends EventEmitter<Events>
implements CCObjectStore<K>
{
protected readonly store: CCStore;
readonly #objects: Map<CCObjectId<K>, CCObjectByType[K]> = new Map();
protected get objects(): ReadonlyMap<CCObjectId<K>, CCObjectByType[K]> {
return this.#objects;
}
/**
* Fields of the objects holding the id of another object, mapped to the object type of that id.
* Every such field must be listed with its correct object type.
*/
abstract readonly references: CCReferences<CCObjectByType[K]>;
protected setObject(
object: CCObjectByType[K] & CCObject<K>,
{ changesCircuit = true }: { changesCircuit?: boolean } = {},
): void {
this.#objects.set(object.id, object);
if (changesCircuit) this.store.countCircuitChange();
}
protected deleteObject(id: CCObjectId<K>): void {
this.#objects.delete(id);
this.store.countCircuitChange();
}
constructor(store: CCStore) {
super();
this.store = store;
}
/** Subscribe to the events of other stores. Called after all stores are constructed. */
abstract mount(): void;
/**
* Get an object by id
* @param id id of object
* @returns object of `id`
*/
get(id: CCObjectId<K>): CCObjectByType[K] | undefined {
return this.objects.get(id);
}
/**
* Get array of objects
* @returns array of objects
*/
getMany(): CCObjectByType[K][] {
return [...this.objects.values()];
}
}