-
-
Notifications
You must be signed in to change notification settings - Fork 122
/
deepObserve.ts
141 lines (130 loc) · 4.71 KB
/
deepObserve.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
import {
observe,
isObservableMap,
isObservableObject,
isObservableArray,
IObjectDidChange,
IArrayDidChange,
IMapDidChange,
values,
entries,
} from "mobx"
import { IDisposer } from "./utils"
type IChange = IObjectDidChange | IArrayDidChange | IMapDidChange
type Entry = {
dispose: IDisposer
path: string
parent: Entry | undefined
}
function buildPath(entry: Entry | undefined): string {
if (!entry) return "ROOT"
const res: string[] = []
while (entry.parent) {
res.push(entry.path)
entry = entry.parent
}
return res.reverse().join("/")
}
function isRecursivelyObservable(thing: any) {
return isObservableObject(thing) || isObservableArray(thing) || isObservableMap(thing)
}
/**
* Given an object, deeply observes the given object.
* It is like `observe` from mobx, but applied recursively, including all future children.
*
* Note that the given object cannot ever contain cycles and should be a tree.
*
* As benefit: path and root will be provided in the callback, so the signature of the listener is
* (change, path, root) => void
*
* The returned disposer can be invoked to clean up the listener
*
* deepObserve cannot be used on computed values.
*
* @example
* const disposer = deepObserve(target, (change, path) => {
* console.dir(change)
* })
*/
export function deepObserve<T = any>(
target: T,
listener: (change: IChange, path: string, root: T) => void
): IDisposer {
const entrySet = new WeakMap<any, Entry>()
function genericListener(change: IChange) {
const entry = entrySet.get(change.object)!
processChange(change, entry)
listener(change, buildPath(entry), target)
}
function processChange(change: IChange, parent: Entry) {
switch (change.type) {
// Object changes
case "add": // also for map
observeRecursively(change.newValue, parent, change.name)
break
case "update": // also for array and map
unobserveRecursively(change.oldValue)
observeRecursively(
change.newValue,
parent,
(change as any).name || "" + (change as any).index
)
break
case "remove": // object
case "delete": // map
unobserveRecursively(change.oldValue)
break
// Array changes
case "splice":
change.removed.map(unobserveRecursively)
change.added.forEach((value, idx) =>
observeRecursively(value, parent, "" + (change.index + idx))
)
// update paths
for (let i = change.index + change.addedCount; i < change.object.length; i++) {
if (isRecursivelyObservable(change.object[i])) {
const entry = entrySet.get(change.object[i])
if (entry) entry.path = "" + i
}
}
break
}
}
function observeRecursively(thing: any, parent: Entry | undefined, path: string) {
if (isRecursivelyObservable(thing)) {
const entry = entrySet.get(thing)
if (entry) {
if (entry.parent !== parent || entry.path !== path)
// MWE: this constraint is artificial, and this tool could be made to work with cycles,
// but it increases administration complexity, has tricky edge cases and the meaning of 'path'
// would become less clear. So doesn't seem to be needed for now
throw new Error(
`The same observable object cannot appear twice in the same tree,` +
` trying to assign it to '${buildPath(parent)}/${path}',` +
` but it already exists at '${buildPath(entry.parent)}/${entry.path}'`
)
} else {
const entry = {
parent,
path,
dispose: observe(thing, genericListener),
}
entrySet.set(thing, entry)
entries(thing).forEach(([key, value]) => observeRecursively(value, entry, key))
}
}
}
function unobserveRecursively(thing: any) {
if (isRecursivelyObservable(thing)) {
const entry = entrySet.get(thing)
if (!entry) return
entrySet.delete(thing)
entry.dispose()
values(thing).forEach(unobserveRecursively)
}
}
observeRecursively(target, undefined, "")
return () => {
unobserveRecursively(target)
}
}