forked from cerebral/overmind
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathMutationTree.ts
More file actions
110 lines (98 loc) · 2.52 KB
/
MutationTree.ts
File metadata and controls
110 lines (98 loc) · 2.52 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
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
import { Proxifier } from './Proxyfier'
import {
IMutation,
IMutationCallback,
IMutationTree,
IProxifier,
IProxyStateTree,
} from './types'
export class MutationTree<T extends object> implements IMutationTree<T> {
private mutationCallbacks: IMutationCallback[] = []
master: IProxyStateTree<T>
state: T
proxifier: IProxifier<T>
mutations: IMutation[] = []
objectChanges = new Set<string>()
isTracking: boolean = false
isBlocking: boolean = false
trackPathListeners: Array<(path: string) => void> = []
constructor(master: IProxyStateTree<T>, proxifier?: IProxifier<T>) {
this.isTracking = true
this.master = master
this.proxifier = proxifier || new Proxifier(this)
this.state = this.proxifier.proxify(master.sourceState, '')
}
trackPaths() {
const paths = new Set<string>()
const listener = (path) => {
paths.add(path)
}
this.trackPathListeners.push(listener)
return () => {
this.trackPathListeners.splice(
this.trackPathListeners.indexOf(listener),
1
)
return paths
}
}
getMutations() {
const mutations = this.mutations.slice()
this.mutations.length = 0
return mutations
}
getObjectChanges() {
const objectChanges = new Set([...this.objectChanges])
this.objectChanges.clear()
return objectChanges
}
addMutation(mutation: IMutation, objectChangePath?: string) {
const currentFlushId = this.master.currentFlushId
this.mutations.push(mutation)
if (objectChangePath) {
this.objectChanges.add(objectChangePath)
}
for (let cb of this.master.mutationCallbacks) {
cb(
mutation,
new Set(
objectChangePath ? [mutation.path, objectChangePath] : [mutation.path]
),
currentFlushId
)
}
for (let callback of this.mutationCallbacks) {
callback(
mutation,
new Set(
objectChangePath ? [mutation.path, objectChangePath] : [mutation.path]
),
currentFlushId
)
}
}
flush(isAsync: boolean = false) {
return this.master.flush(this, isAsync)
}
onMutation(callback: IMutationCallback) {
this.mutationCallbacks.push(callback)
}
canMutate() {
return this.isTracking && !this.isBlocking
}
canTrack() {
return false
}
blockMutations() {
this.isBlocking = true
}
enableMutations() {
this.isBlocking = false
}
dispose() {
this.isTracking = false
this.mutationCallbacks.length = 0
this.proxifier = this.master.proxifier
return this
}
}