-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathindex.ts
73 lines (66 loc) · 2.17 KB
/
index.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
import {EventManager} from '@axtk/event-manager';
import type {KeyPath, NestedProperty} from './lib/types';
import {getValue} from './lib/getValue';
import {setValue} from './lib/setValue';
import {removeValue} from './lib/removeValue';
const UPDATE_EVENT = 'update';
export class Store<
State extends object = Record<PropertyKey, unknown>,
TypedKeyPathDepth extends number = 5
> {
eventManager: EventManager;
revision: number;
state: State;
constructor(initialState?: State) {
this.eventManager = new EventManager();
this.revision = 0;
this.setState(initialState);
this.eventManager.addListener(UPDATE_EVENT, () => {
this.revision = this.revision === Number.MAX_SAFE_INTEGER ? 1 : this.revision + 1;
});
}
onUpdate(handler: (store?: Store<State, TypedKeyPathDepth>) => void): () => void {
if (typeof handler !== 'function')
throw new Error('handler is not a function');
let listener = this.eventManager.addListener(UPDATE_EVENT, () => {
handler(this);
});
return () => listener.remove();
}
dispatchUpdate(): void {
this.eventManager.dispatch(UPDATE_EVENT);
}
getRevision(): number {
return this.revision;
}
getState() {
return this.state;
}
get<K extends KeyPath<State, TypedKeyPathDepth>>(
keyPath: K,
defaultValue?: NestedProperty<State, K>,
): NestedProperty<State, K> {
return getValue(this.state, keyPath, defaultValue);
}
setState(value: State): void {
this.state = value;
this.dispatchUpdate();
}
set<K extends KeyPath<State, TypedKeyPathDepth>>(
keyPath: K,
value: NestedProperty<State, K>,
): void {
if (this.state == null && keyPath != null)
this.state = {} as State;
setValue(this.state, keyPath, value);
this.dispatchUpdate();
}
removeState() {
this.setState(undefined);
}
remove<K extends KeyPath<State, TypedKeyPathDepth>>(keyPath: K): void {
removeValue(this.state, keyPath);
this.dispatchUpdate();
}
}
export type {KeyPath, NestedProperty};