/
observableobject.ts
782 lines (719 loc) · 25.1 KB
/
observableobject.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
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
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
import {
CreateObservableOptions,
getAnnotationFromOptions,
propagateChanged,
isAnnotation,
$mobx,
Atom,
Annotation,
ComputedValue,
IAtom,
IComputedValueOptions,
IEnhancer,
IInterceptable,
IListenable,
Lambda,
ObservableValue,
addHiddenProp,
createInstanceofPredicate,
endBatch,
getNextId,
hasInterceptors,
hasListeners,
interceptChange,
isObject,
isPlainObject,
isSpyEnabled,
notifyListeners,
referenceEnhancer,
registerInterceptor,
registerListener,
spyReportEnd,
spyReportStart,
startBatch,
stringifyKey,
globalState,
ADD,
UPDATE,
die,
hasProp,
getDescriptor,
storedAnnotationsSymbol,
ownKeys,
isOverride,
defineProperty,
autoAnnotation,
getAdministration,
getDebugName,
objectPrototype,
MakeResult
} from "../internal"
const descriptorCache = Object.create(null)
export type IObjectDidChange<T = any> = {
observableKind: "object"
name: PropertyKey
object: T
debugObjectName: string
} & (
| {
type: "add"
newValue: any
}
| {
type: "update"
oldValue: any
newValue: any
}
| {
type: "remove"
oldValue: any
}
)
export type IObjectWillChange<T = any> =
| {
object: T
type: "update" | "add"
name: PropertyKey
newValue: any
}
| {
object: T
type: "remove"
name: PropertyKey
}
const REMOVE = "remove"
export class ObservableObjectAdministration
implements IInterceptable<IObjectWillChange>, IListenable
{
keysAtom_: IAtom
changeListeners_
interceptors_
proxy_: any
isPlainObject_: boolean
appliedAnnotations_?: object
private pendingKeys_: undefined | Map<PropertyKey, ObservableValue<boolean>>
constructor(
public target_: any,
public values_ = new Map<PropertyKey, ObservableValue<any> | ComputedValue<any>>(),
public name_: string,
// Used anytime annotation is not explicitely provided
public defaultAnnotation_: Annotation = autoAnnotation
) {
this.keysAtom_ = new Atom(__DEV__ ? `${this.name_}.keys` : "ObservableObject.keys")
// Optimization: we use this frequently
this.isPlainObject_ = isPlainObject(this.target_)
if (__DEV__ && !isAnnotation(this.defaultAnnotation_)) {
die(`defaultAnnotation must be valid annotation`)
}
if (__DEV__) {
// Prepare structure for tracking which fields were already annotated
this.appliedAnnotations_ = {}
}
}
getObservablePropValue_(key: PropertyKey): any {
return this.values_.get(key)!.get()
}
setObservablePropValue_(key: PropertyKey, newValue): boolean | null {
const observable = this.values_.get(key)
if (observable instanceof ComputedValue) {
observable.set(newValue)
return true
}
// intercept
if (hasInterceptors(this)) {
const change = interceptChange<IObjectWillChange>(this, {
type: UPDATE,
object: this.proxy_ || this.target_,
name: key,
newValue
})
if (!change) {
return null
}
newValue = (change as any).newValue
}
newValue = (observable as any).prepareNewValue_(newValue)
// notify spy & observers
if (newValue !== globalState.UNCHANGED) {
const notify = hasListeners(this)
const notifySpy = __DEV__ && isSpyEnabled()
const change: IObjectDidChange | null =
notify || notifySpy
? {
type: UPDATE,
observableKind: "object",
debugObjectName: this.name_,
object: this.proxy_ || this.target_,
oldValue: (observable as any).value_,
name: key,
newValue
}
: null
if (__DEV__ && notifySpy) {
spyReportStart(change!)
}
;(observable as ObservableValue<any>).setNewValue_(newValue)
if (notify) {
notifyListeners(this, change)
}
if (__DEV__ && notifySpy) {
spyReportEnd()
}
}
return true
}
get_(key: PropertyKey): any {
if (globalState.trackingDerivation && !hasProp(this.target_, key)) {
// Key doesn't exist yet, subscribe for it in case it's added later
this.has_(key)
}
return this.target_[key]
}
/**
* @param {PropertyKey} key
* @param {any} value
* @param {Annotation|boolean} annotation true - use default annotation, false - copy as is
* @param {boolean} proxyTrap whether it's called from proxy trap
* @returns {boolean|null} true on success, false on failure (proxyTrap + non-configurable), null when cancelled by interceptor
*/
set_(key: PropertyKey, value: any, proxyTrap: boolean = false): boolean | null {
// Don't use .has(key) - we care about own
if (hasProp(this.target_, key)) {
// Existing prop
if (this.values_.has(key)) {
// Observable (can be intercepted)
return this.setObservablePropValue_(key, value)
} else if (proxyTrap) {
// Non-observable - proxy
return Reflect.set(this.target_, key, value)
} else {
// Non-observable
this.target_[key] = value
return true
}
} else {
// New prop
return this.extend_(
key,
{ value, enumerable: true, writable: true, configurable: true },
this.defaultAnnotation_,
proxyTrap
)
}
}
// Trap for "in"
has_(key: PropertyKey): boolean {
if (!globalState.trackingDerivation) {
// Skip key subscription outside derivation
return key in this.target_
}
this.pendingKeys_ ||= new Map()
let entry = this.pendingKeys_.get(key)
if (!entry) {
entry = new ObservableValue(
key in this.target_,
referenceEnhancer,
__DEV__ ? `${this.name_}.${stringifyKey(key)}?` : "ObservableObject.key?",
false
)
this.pendingKeys_.set(key, entry)
}
return entry.get()
}
/**
* @param {PropertyKey} key
* @param {Annotation|boolean} annotation true - use default annotation, false - ignore prop
*/
make_(key: PropertyKey, annotation: Annotation | boolean): void {
if (annotation === true) {
annotation = this.defaultAnnotation_
}
if (annotation === false) {
return
}
assertAnnotable(this, annotation, key)
if (!(key in this.target_)) {
// Throw on missing key, except for decorators:
// Decorator annotations are collected from whole prototype chain.
// When called from super() some props may not exist yet.
// However we don't have to worry about missing prop,
// because the decorator must have been applied to something.
if (this.target_[storedAnnotationsSymbol]?.[key]) {
return // will be annotated by subclass constructor
} else {
die(1, annotation.annotationType_, `${this.name_}.${key.toString()}`)
}
}
let source = this.target_
while (source && source !== objectPrototype) {
const descriptor = getDescriptor(source, key)
if (descriptor) {
const outcome = annotation.make_(this, key, descriptor, source)
if (outcome === MakeResult.Cancel) {
return
}
if (outcome === MakeResult.Break) {
break
}
}
source = Object.getPrototypeOf(source)
}
recordAnnotationApplied(this, annotation, key)
}
/**
* @param {PropertyKey} key
* @param {PropertyDescriptor} descriptor
* @param {Annotation|boolean} annotation true - use default annotation, false - copy as is
* @param {boolean} proxyTrap whether it's called from proxy trap
* @returns {boolean|null} true on success, false on failure (proxyTrap + non-configurable), null when cancelled by interceptor
*/
extend_(
key: PropertyKey,
descriptor: PropertyDescriptor,
annotation: Annotation | boolean,
proxyTrap: boolean = false
): boolean | null {
if (annotation === true) {
annotation = this.defaultAnnotation_
}
if (annotation === false) {
return this.defineProperty_(key, descriptor, proxyTrap)
}
assertAnnotable(this, annotation, key)
const outcome = annotation.extend_(this, key, descriptor, proxyTrap)
if (outcome) {
recordAnnotationApplied(this, annotation, key)
}
return outcome
}
/**
* @param {PropertyKey} key
* @param {PropertyDescriptor} descriptor
* @param {boolean} proxyTrap whether it's called from proxy trap
* @returns {boolean|null} true on success, false on failure (proxyTrap + non-configurable), null when cancelled by interceptor
*/
defineProperty_(
key: PropertyKey,
descriptor: PropertyDescriptor,
proxyTrap: boolean = false
): boolean | null {
try {
startBatch()
// Delete
const deleteOutcome = this.delete_(key)
if (!deleteOutcome) {
// Failure or intercepted
return deleteOutcome
}
// ADD interceptor
if (hasInterceptors(this)) {
const change = interceptChange<IObjectWillChange>(this, {
object: this.proxy_ || this.target_,
name: key,
type: ADD,
newValue: descriptor.value
})
if (!change) {
return null
}
const { newValue } = change as any
if (descriptor.value !== newValue) {
descriptor = {
...descriptor,
value: newValue
}
}
}
// Define
if (proxyTrap) {
if (!Reflect.defineProperty(this.target_, key, descriptor)) {
return false
}
} else {
defineProperty(this.target_, key, descriptor)
}
// Notify
this.notifyPropertyAddition_(key, descriptor.value)
} finally {
endBatch()
}
return true
}
// If original descriptor becomes relevant, move this to annotation directly
defineObservableProperty_(
key: PropertyKey,
value: any,
enhancer: IEnhancer<any>,
proxyTrap: boolean = false
): boolean | null {
try {
startBatch()
// Delete
const deleteOutcome = this.delete_(key)
if (!deleteOutcome) {
// Failure or intercepted
return deleteOutcome
}
// ADD interceptor
if (hasInterceptors(this)) {
const change = interceptChange<IObjectWillChange>(this, {
object: this.proxy_ || this.target_,
name: key,
type: ADD,
newValue: value
})
if (!change) {
return null
}
value = (change as any).newValue
}
const cachedDescriptor = getCachedObservablePropDescriptor(key)
const descriptor = {
configurable: globalState.safeDescriptors ? this.isPlainObject_ : true,
enumerable: true,
get: cachedDescriptor.get,
set: cachedDescriptor.set
}
// Define
if (proxyTrap) {
if (!Reflect.defineProperty(this.target_, key, descriptor)) {
return false
}
} else {
defineProperty(this.target_, key, descriptor)
}
const observable = new ObservableValue(
value,
enhancer,
__DEV__ ? `${this.name_}.${key.toString()}` : "ObservableObject.key",
false
)
this.values_.set(key, observable)
// Notify (value possibly changed by ObservableValue)
this.notifyPropertyAddition_(key, observable.value_)
} finally {
endBatch()
}
return true
}
// If original descriptor becomes relevant, move this to annotation directly
defineComputedProperty_(
key: PropertyKey,
options: IComputedValueOptions<any>,
proxyTrap: boolean = false
): boolean | null {
try {
startBatch()
// Delete
const deleteOutcome = this.delete_(key)
if (!deleteOutcome) {
// Failure or intercepted
return deleteOutcome
}
// ADD interceptor
if (hasInterceptors(this)) {
const change = interceptChange<IObjectWillChange>(this, {
object: this.proxy_ || this.target_,
name: key,
type: ADD,
newValue: undefined
})
if (!change) {
return null
}
}
options.name ||= __DEV__ ? `${this.name_}.${key.toString()}` : "ObservableObject.key"
options.context = this.proxy_ || this.target_
const cachedDescriptor = getCachedObservablePropDescriptor(key)
const descriptor = {
configurable: globalState.safeDescriptors ? this.isPlainObject_ : true,
enumerable: false,
get: cachedDescriptor.get,
set: cachedDescriptor.set
}
// Define
if (proxyTrap) {
if (!Reflect.defineProperty(this.target_, key, descriptor)) {
return false
}
} else {
defineProperty(this.target_, key, descriptor)
}
this.values_.set(key, new ComputedValue(options))
// Notify
this.notifyPropertyAddition_(key, undefined)
} finally {
endBatch()
}
return true
}
/**
* @param {PropertyKey} key
* @param {PropertyDescriptor} descriptor
* @param {boolean} proxyTrap whether it's called from proxy trap
* @returns {boolean|null} true on success, false on failure (proxyTrap + non-configurable), null when cancelled by interceptor
*/
delete_(key: PropertyKey, proxyTrap: boolean = false): boolean | null {
// No such prop
if (!hasProp(this.target_, key)) {
return true
}
// Intercept
if (hasInterceptors(this)) {
const change = interceptChange<IObjectWillChange>(this, {
object: this.proxy_ || this.target_,
name: key,
type: REMOVE
})
// Cancelled
if (!change) {
return null
}
}
// Delete
try {
startBatch()
const notify = hasListeners(this)
const notifySpy = __DEV__ && isSpyEnabled()
const observable = this.values_.get(key)
// Value needed for spies/listeners
let value = undefined
// Optimization: don't pull the value unless we will need it
if (!observable && (notify || notifySpy)) {
value = getDescriptor(this.target_, key)?.value
}
// delete prop (do first, may fail)
if (proxyTrap) {
if (!Reflect.deleteProperty(this.target_, key)) {
return false
}
} else {
delete this.target_[key]
}
// Allow re-annotating this field
if (__DEV__) {
delete this.appliedAnnotations_![key]
}
// Clear observable
if (observable) {
this.values_.delete(key)
// for computed, value is undefined
if (observable instanceof ObservableValue) {
value = observable.value_
}
// Notify: autorun(() => obj[key]), see #1796
propagateChanged(observable)
}
// Notify "keys/entries/values" observers
this.keysAtom_.reportChanged()
// Notify "has" observers
// "in" as it may still exist in proto
this.pendingKeys_?.get(key)?.set(key in this.target_)
// Notify spies/listeners
if (notify || notifySpy) {
const change: IObjectDidChange = {
type: REMOVE,
observableKind: "object",
object: this.proxy_ || this.target_,
debugObjectName: this.name_,
oldValue: value,
name: key
}
if (__DEV__ && notifySpy) {
spyReportStart(change!)
}
if (notify) {
notifyListeners(this, change)
}
if (__DEV__ && notifySpy) {
spyReportEnd()
}
}
} finally {
endBatch()
}
return true
}
/**
* 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 {
if (__DEV__ && fireImmediately === true) {
die("`observe` doesn't support the fire immediately property for observable objects.")
}
return registerListener(this, callback)
}
intercept_(handler): Lambda {
return registerInterceptor(this, handler)
}
notifyPropertyAddition_(key: PropertyKey, value: any) {
const notify = hasListeners(this)
const notifySpy = __DEV__ && isSpyEnabled()
if (notify || notifySpy) {
const change: IObjectDidChange | null =
notify || notifySpy
? ({
type: ADD,
observableKind: "object",
debugObjectName: this.name_,
object: this.proxy_ || this.target_,
name: key,
newValue: value
} as const)
: null
if (__DEV__ && notifySpy) {
spyReportStart(change!)
}
if (notify) {
notifyListeners(this, change)
}
if (__DEV__ && notifySpy) {
spyReportEnd()
}
}
this.pendingKeys_?.get(key)?.set(true)
// Notify "keys/entries/values" observers
this.keysAtom_.reportChanged()
}
ownKeys_(): ArrayLike<string | symbol> {
this.keysAtom_.reportObserved()
return ownKeys(this.target_)
}
keys_(): PropertyKey[] {
// Returns enumerable && own, but unfortunately keysAtom will report on ANY key change.
// There is no way to distinguish between Object.keys(object) and Reflect.ownKeys(object) - both are handled by ownKeys trap.
// We can either over-report in Object.keys(object) or under-report in Reflect.ownKeys(object)
// We choose to over-report in Object.keys(object), because:
// - typically it's used with simple data objects
// - when symbolic/non-enumerable keys are relevant Reflect.ownKeys works as expected
this.keysAtom_.reportObserved()
return Object.keys(this.target_)
}
}
export interface IIsObservableObject {
$mobx: ObservableObjectAdministration
}
export function asObservableObject(
target: any,
options?: CreateObservableOptions
): IIsObservableObject {
if (__DEV__ && options && isObservableObject(target)) {
die(`Options can't be provided for already observable objects.`)
}
if (hasProp(target, $mobx)) {
if (__DEV__ && !(getAdministration(target) instanceof ObservableObjectAdministration)) {
die(
`Cannot convert '${getDebugName(target)}' into observable object:` +
`\nThe target is already observable of different type.` +
`\nExtending builtins is not supported.`
)
}
return target
}
if (__DEV__ && !Object.isExtensible(target)) {
die("Cannot make the designated object observable; it is not extensible")
}
const name =
options?.name ??
(__DEV__
? `${
isPlainObject(target) ? "ObservableObject" : target.constructor.name
}@${getNextId()}`
: "ObservableObject")
const adm = new ObservableObjectAdministration(
target,
new Map(),
String(name),
getAnnotationFromOptions(options)
)
addHiddenProp(target, $mobx, adm)
return target
}
const isObservableObjectAdministration = createInstanceofPredicate(
"ObservableObjectAdministration",
ObservableObjectAdministration
)
function getCachedObservablePropDescriptor(key) {
return (
descriptorCache[key] ||
(descriptorCache[key] = {
get() {
return this[$mobx].getObservablePropValue_(key)
},
set(value) {
return this[$mobx].setObservablePropValue_(key, value)
}
})
)
}
export function isObservableObject(thing: any): boolean {
if (isObject(thing)) {
return isObservableObjectAdministration((thing as any)[$mobx])
}
return false
}
export function recordAnnotationApplied(
adm: ObservableObjectAdministration,
annotation: Annotation,
key: PropertyKey
) {
if (__DEV__) {
adm.appliedAnnotations_![key] = annotation
}
// Remove applied decorator annotation so we don't try to apply it again in subclass constructor
delete adm.target_[storedAnnotationsSymbol]?.[key]
}
function assertAnnotable(
adm: ObservableObjectAdministration,
annotation: Annotation,
key: PropertyKey
) {
// Valid annotation
if (__DEV__ && !isAnnotation(annotation)) {
die(`Cannot annotate '${adm.name_}.${key.toString()}': Invalid annotation.`)
}
/*
// Configurable, not sealed, not frozen
// Possibly not needed, just a little better error then the one thrown by engine.
// Cases where this would be useful the most (subclass field initializer) are not interceptable by this.
if (__DEV__) {
const configurable = getDescriptor(adm.target_, key)?.configurable
const frozen = Object.isFrozen(adm.target_)
const sealed = Object.isSealed(adm.target_)
if (!configurable || frozen || sealed) {
const fieldName = `${adm.name_}.${key.toString()}`
const requestedAnnotationType = annotation.annotationType_
let error = `Cannot apply '${requestedAnnotationType}' to '${fieldName}':`
if (frozen) {
error += `\nObject is frozen.`
}
if (sealed) {
error += `\nObject is sealed.`
}
if (!configurable) {
error += `\nproperty is not configurable.`
// Mention only if caused by us to avoid confusion
if (hasProp(adm.appliedAnnotations!, key)) {
error += `\nTo prevent accidental re-definition of a field by a subclass, `
error += `all annotated fields of non-plain objects (classes) are not configurable.`
}
}
die(error)
}
}
*/
// Not annotated
if (__DEV__ && !isOverride(annotation) && hasProp(adm.appliedAnnotations_!, key)) {
const fieldName = `${adm.name_}.${key.toString()}`
const currentAnnotationType = adm.appliedAnnotations_![key].annotationType_
const requestedAnnotationType = annotation.annotationType_
die(
`Cannot apply '${requestedAnnotationType}' to '${fieldName}':` +
`\nThe field is already annotated with '${currentAnnotationType}'.` +
`\nRe-annotating fields is not allowed.` +
`\nUse 'override' annotation for methods overridden by subclass.`
)
}
}