forked from mobxjs/mobx
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathobservableobject.ts
More file actions
402 lines (370 loc) · 12.6 KB
/
Copy pathobservableobject.ts
File metadata and controls
402 lines (370 loc) · 12.6 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
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
import {
$mobx,
Atom,
ComputedValue,
IAtom,
IComputedValueOptions,
IEnhancer,
IInterceptable,
IListenable,
Lambda,
ObservableValue,
addHiddenProp,
assertPropertyConfigurable,
createInstanceofPredicate,
deepEnhancer,
endBatch,
getNextId,
hasInterceptors,
hasListeners,
initializeInstance,
interceptChange,
invariant,
isObject,
isPlainObject,
isPropertyConfigurable,
isSpyEnabled,
notifyListeners,
referenceEnhancer,
registerInterceptor,
registerListener,
spyReportEnd,
spyReportStart,
startBatch,
globalState
} from "../internal"
export interface IObservableObject {
"observable-object": IObservableObject
}
export type IObjectDidChange =
| {
name: string
object: any
type: "add"
newValue: any
}
| {
name: string
object: any
type: "update"
oldValue: any
newValue: any
}
| {
name: string
object: any
type: "remove"
oldValue: any
}
export type IObjectWillChange =
| {
object: any
type: "update" | "add"
name: string
newValue: any
}
| {
object: any
type: "remove"
name: string
}
export class ObservableObjectAdministration
implements IInterceptable<IObjectWillChange>, IListenable {
keysAtom: IAtom
changeListeners
interceptors
private proxy: any
private pendingKeys: undefined | Map<string, ObservableValue<boolean>>
constructor(
public target: any,
public values = new Map<string, ObservableValue<any> | ComputedValue<any>>(),
public name: string,
public defaultEnhancer: IEnhancer<any>
) {
this.keysAtom = new Atom(name + ".keys")
}
read(key: string) {
return this.values.get(key)!.get()
}
write(key: string, newValue) {
const instance = this.target
const observable = this.values.get(key)
if (observable instanceof ComputedValue) {
observable.set(newValue)
return
}
// intercept
if (hasInterceptors(this)) {
const change = interceptChange<IObjectWillChange>(this, {
type: "update",
object: this.proxy || instance,
name: key,
newValue
})
if (!change) return
newValue = (change as any).newValue
}
newValue = (observable as any).prepareNewValue(newValue)
// notify spy & observers
if (newValue !== globalState.UNCHANGED) {
const notify = hasListeners(this)
const notifySpy = isSpyEnabled()
const change =
notify || notifySpy
? {
type: "update",
object: this.proxy || instance,
oldValue: (observable as any).value,
name: key,
newValue
}
: null
if (notifySpy && process.env.NODE_ENV !== "production")
spyReportStart({ ...change, name: this.name, key })
;(observable as ObservableValue<any>).setNewValue(newValue)
if (notify) notifyListeners(this, change)
if (notifySpy && process.env.NODE_ENV !== "production") spyReportEnd()
}
}
has(key: string) {
const map = this.pendingKeys || (this.pendingKeys = new Map())
let entry = map.get(key)
if (entry) return entry.get()
else {
const exists = !!this.values.get(key)
// Possible optimization: Don't have a separate map for non existing keys,
// but store them in the values map instead, using a special symbol to denote "not existing"
entry = new ObservableValue(
exists,
referenceEnhancer,
`${this.name}.${key.toString()}?`,
false
)
map.set(key, entry)
return entry.get() // read to subscribe
}
}
addObservableProp(propName: string, newValue, enhancer: IEnhancer<any> = this.defaultEnhancer) {
const { target } = this
assertPropertyConfigurable(target, propName)
if (hasInterceptors(this)) {
const change = interceptChange<IObjectWillChange>(this, {
object: this.proxy || target,
name: propName,
type: "add",
newValue
})
if (!change) return
newValue = (change as any).newValue
}
const observable = new ObservableValue(
newValue,
enhancer,
`${this.name}.${propName}`,
false
)
this.values.set(propName, observable)
newValue = (observable as any).value // observableValue might have changed it
Object.defineProperty(target, propName, generateObservablePropConfig(propName))
this.notifyPropertyAddition(propName, newValue)
}
addComputedProp(
propertyOwner: any, // where is the property declared?
propName: string,
options: IComputedValueOptions<any>
) {
const { target } = this
options.name = options.name || `${this.name}.${propName}`
this.values.set(propName, new ComputedValue(options))
if (propertyOwner === target || isPropertyConfigurable(propertyOwner, propName))
Object.defineProperty(propertyOwner, propName, generateComputedPropConfig(propName))
}
remove(key: string) {
if (!this.values.has(key)) return
const { target } = this
if (hasInterceptors(this)) {
const change = interceptChange<IObjectWillChange>(this, {
object: this.proxy || target,
name: key,
type: "remove"
})
if (!change) return
}
try {
startBatch()
const notify = hasListeners(this)
const notifySpy = isSpyEnabled()
const oldObservable = this.values.get(key)
const oldValue = oldObservable && oldObservable.get()
oldObservable && oldObservable.set(undefined)
// notify key and keyset listeners
this.keysAtom.reportChanged()
this.values.delete(key)
if (this.pendingKeys) {
const entry = this.pendingKeys.get(key)
if (entry) entry.set(false)
}
// delete the prop
delete this.target[key]
const change =
notify || notifySpy
? {
type: "remove",
object: this.proxy || target,
oldValue: oldValue,
name: key
}
: null
if (notifySpy && process.env.NODE_ENV !== "production")
spyReportStart({ ...change, name: this.name, key })
if (notify) notifyListeners(this, change)
if (notifySpy && process.env.NODE_ENV !== "production") spyReportEnd()
} finally {
endBatch()
}
}
illegalAccess(owner, propName) {
/**
* This happens if a property is accessed through the prototype chain, but the property was
* declared directly as own property on the prototype.
*
* E.g.:
* class A {
* }
* extendObservable(A.prototype, { x: 1 })
*
* classB extens A {
* }
* console.log(new B().x)
*
* It is unclear whether the property should be considered 'static' or inherited.
* Either use `console.log(A.x)`
* or: decorate(A, { x: observable })
*
* When using decorate, the property will always be redeclared as own property on the actual instance
*/
console.warn(
`Property '${propName}' of '${owner}' was accessed through the prototype chain. Use 'decorate' instead to declare the prop or access it statically through it's owner`
)
}
/**
* Observes this object. Triggers for the events 'add', 'update' and 'delete'.
* See: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/observe
* for callback details
*/
observe(callback: (changes: IObjectDidChange) => void, fireImmediately?: boolean): Lambda {
process.env.NODE_ENV !== "production" &&
invariant(
fireImmediately !== true,
"`observe` doesn't support the fire immediately property for observable objects."
)
return registerListener(this, callback)
}
intercept(handler): Lambda {
return registerInterceptor(this, handler)
}
notifyPropertyAddition(key: string, newValue) {
const notify = hasListeners(this)
const notifySpy = isSpyEnabled()
const change =
notify || notifySpy
? {
type: "add",
object: this.proxy || this.target,
name: key,
newValue
}
: null
if (notifySpy && process.env.NODE_ENV !== "production")
spyReportStart({ ...change, name: this.name, key })
if (notify) notifyListeners(this, change)
if (notifySpy && process.env.NODE_ENV !== "production") spyReportEnd()
if (this.pendingKeys) {
const entry = this.pendingKeys.get(key)
if (entry) entry.set(true)
}
this.keysAtom.reportChanged()
}
getKeys(): string[] {
this.keysAtom.reportObserved()
// return Reflect.ownKeys(this.values) as any
const res: string[] = []
for (const [key, value] of this.values) if (value instanceof ObservableValue) res.push(key)
return res
}
}
export interface IIsObservableObject {
$mobx: ObservableObjectAdministration
}
export function asObservableObject(
target: any,
name: string = "",
defaultEnhancer: IEnhancer<any> = deepEnhancer
): ObservableObjectAdministration {
if (Object.prototype.hasOwnProperty.call(target, $mobx)) return target[$mobx]
process.env.NODE_ENV !== "production" &&
invariant(
Object.isExtensible(target),
"Cannot make the designated object observable; it is not extensible"
)
if (!isPlainObject(target))
name = (target.constructor.name || "ObservableObject") + "@" + getNextId()
if (!name) name = "ObservableObject@" + getNextId()
const adm = new ObservableObjectAdministration(target, new Map(), name, defaultEnhancer)
addHiddenProp(target, $mobx, adm)
return adm
}
const observablePropertyConfigs = Object.create(null)
const computedPropertyConfigs = Object.create(null)
export function generateObservablePropConfig(propName) {
return (
observablePropertyConfigs[propName] ||
(observablePropertyConfigs[propName] = {
configurable: true,
enumerable: true,
get() {
return this[$mobx].read(propName)
},
set(v) {
this[$mobx].write(propName, v)
}
})
)
}
function getAdministrationForComputedPropOwner(owner: any): ObservableObjectAdministration {
const adm = owner[$mobx]
if (!adm) {
// because computed props are declared on proty,
// the current instance might not have been initialized yet
initializeInstance(owner)
return owner[$mobx]
}
return adm
}
export function generateComputedPropConfig(propName) {
return (
computedPropertyConfigs[propName] ||
(computedPropertyConfigs[propName] = {
configurable: true,
enumerable: false,
get() {
return getAdministrationForComputedPropOwner(this).read(propName)
},
set(v) {
getAdministrationForComputedPropOwner(this).write(propName, v)
}
})
)
}
const isObservableObjectAdministration = createInstanceofPredicate(
"ObservableObjectAdministration",
ObservableObjectAdministration
)
export function isObservableObject(thing: any): thing is IObservableObject {
if (isObject(thing)) {
// Initializers run lazily when transpiling to babel, so make sure they are run...
initializeInstance(thing)
return isObservableObjectAdministration((thing as any)[$mobx])
}
return false
}