-
Notifications
You must be signed in to change notification settings - Fork 640
/
object-node.ts
708 lines (597 loc) · 22.5 KB
/
object-node.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
// noinspection ES6UnusedImports
import { action, computed, reaction, _allowStateChangesInsideComputed } from "mobx"
import {
addHiddenFinalProp,
ComplexType,
convertChildNodesToArray,
createActionInvoker,
EMPTY_OBJECT,
extend,
fail,
freeze,
IAnyType,
IdentifierCache,
IDisposer,
IJsonPatch,
IMiddleware,
IMiddlewareHandler,
invalidateComputed,
IReversibleJsonPatch,
NodeLifeCycle,
resolveNodeByPathParts,
splitJsonPath,
splitPatch,
toJSON,
EventHandlers,
Hook,
BaseNode,
getLivelinessChecking,
normalizeIdentifier,
ReferenceIdentifier,
IMiddlewareEvent,
getCurrentActionContext,
escapeJsonPath,
getPath,
warnError,
AnyNode,
IStateTreeNode,
ArgumentTypes
} from "../../internal"
let nextNodeId = 1
const enum ObservableInstanceLifecycle {
// the actual observable instance has not been created yet
UNINITIALIZED,
// the actual observable instance is being created
CREATING,
// the actual observable instance has been created
CREATED
}
const enum InternalEvents {
Dispose = "dispose",
Patch = "patch",
Snapshot = "snapshot"
}
/**
* @internal
* @hidden
*/
export interface IChildNodesMap {
[key: string]: AnyNode
}
const snapshotReactionOptions = {
onError(e: any) {
throw e
}
}
type InternalEventHandlers<S> = {
[InternalEvents.Dispose]: IDisposer
[InternalEvents.Patch]: (patch: IJsonPatch, reversePatch: IJsonPatch) => void
[InternalEvents.Snapshot]: (snapshot: S) => void
}
/**
* @internal
* @hidden
*/
export class ObjectNode<C, S, T> extends BaseNode<C, S, T> {
readonly type!: ComplexType<C, S, T>
storedValue!: T & IStateTreeNode<C, S, T>
readonly nodeId = ++nextNodeId
readonly identifierAttribute?: string
readonly identifier: string | null // Identifier is always normalized to string, even if the identifier property isn't
readonly unnormalizedIdentifier: ReferenceIdentifier | null
identifierCache?: IdentifierCache
isProtectionEnabled = true
middlewares: IMiddleware[] | null = null
private _applyPatches?: (patches: IJsonPatch[]) => void
applyPatches(patches: IJsonPatch[]): void {
this.createObservableInstanceIfNeeded()
this._applyPatches!(patches)
}
private _applySnapshot?: (snapshot: C) => void
applySnapshot(snapshot: C): void {
this.createObservableInstanceIfNeeded()
this._applySnapshot!(snapshot)
}
private _autoUnbox = true // unboxing is disabled when reading child nodes
_isRunningAction = false // only relevant for root
private _hasSnapshotReaction = false
private _observableInstanceState = ObservableInstanceLifecycle.UNINITIALIZED
private _childNodes: IChildNodesMap
private _initialSnapshot: C
private _cachedInitialSnapshot?: S
private _cachedInitialSnapshotCreated = false
constructor(
complexType: ComplexType<C, S, T>,
parent: AnyObjectNode | null,
subpath: string,
environment: any,
initialValue: C
) {
super(complexType, parent, subpath, environment)
this.unbox = this.unbox.bind(this)
this._initialSnapshot = freeze(initialValue)
this.identifierAttribute = complexType.identifierAttribute
if (!parent) {
this.identifierCache = new IdentifierCache()
}
this._childNodes = complexType.initializeChildNodes(this, this._initialSnapshot)
// identifier can not be changed during lifecycle of a node
// so we safely can read it from initial snapshot
this.identifier = null
this.unnormalizedIdentifier = null
if (this.identifierAttribute && this._initialSnapshot) {
let id = (this._initialSnapshot as any)[this.identifierAttribute]
if (id === undefined) {
// try with the actual node if not (for optional identifiers)
const childNode = this._childNodes[this.identifierAttribute]
if (childNode) {
id = childNode.value
}
}
if (typeof id !== "string" && typeof id !== "number") {
throw fail(
`Instance identifier '${this.identifierAttribute}' for type '${
this.type.name
}' must be a string or a number`
)
}
// normalize internal identifier to string
this.identifier = normalizeIdentifier(id)
this.unnormalizedIdentifier = id
}
if (!parent) {
this.identifierCache!.addNodeToCache(this)
} else {
parent.root.identifierCache!.addNodeToCache(this)
}
}
@action
createObservableInstanceIfNeeded(): void {
if (this._observableInstanceState !== ObservableInstanceLifecycle.UNINITIALIZED) {
return
}
if (process.env.NODE_ENV !== "production") {
if (this.state !== NodeLifeCycle.INITIALIZING) {
// istanbul ignore next
throw fail(
"assertion failed: the creation of the observable instance must be done on the initializing phase"
)
}
}
this._observableInstanceState = ObservableInstanceLifecycle.CREATING
// make sure the parent chain is created as well
// array with parent chain from parent to child
const parentChain = []
let parent = this.parent
// for performance reasons we never go back further than the most direct
// uninitialized parent
// this is done to avoid traversing the whole tree to the root when using
// the same reference again
while (
parent &&
parent._observableInstanceState === ObservableInstanceLifecycle.UNINITIALIZED
) {
parentChain.unshift(parent)
parent = parent.parent
}
// initialize the uninitialized parent chain from parent to child
for (const p of parentChain) {
p.createObservableInstanceIfNeeded()
}
const type = this.type
try {
this.storedValue = type.createNewInstance(this, this._childNodes, this._initialSnapshot)
this.preboot()
this._isRunningAction = true
type.finalizeNewInstance(this, this.storedValue)
} catch (e) {
// short-cut to die the instance, to avoid the snapshot computed starting to throw...
this.state = NodeLifeCycle.DEAD
throw e
} finally {
this._isRunningAction = false
}
this._observableInstanceState = ObservableInstanceLifecycle.CREATED
// NOTE: we need to touch snapshot, because non-observable
// "_observableInstanceState" field was touched
invalidateComputed(this, "snapshot")
if (this.isRoot) this._addSnapshotReaction()
this._childNodes = EMPTY_OBJECT
this.state = NodeLifeCycle.CREATED
this.fireHook(Hook.afterCreate)
this.finalizeCreation()
}
get root(): AnyObjectNode {
const parent = this.parent
return parent ? parent.root : this
}
clearParent(): void {
if (!this.parent) return
// detach if attached
this.fireHook(Hook.beforeDetach)
const previousState = this.state
this.state = NodeLifeCycle.DETACHING
const newEnv = this.parent.environment
const root = this.root
const newIdCache = root.identifierCache!.splitCache(this)
try {
this.parent.removeChild(this.subpath)
this.baseSetParent(null, "")
this.environment = newEnv
this.identifierCache = newIdCache
} finally {
this.state = previousState
}
}
setParent(newParent: AnyObjectNode, subpath: string): void {
const parentChanged = newParent !== this.parent
const subpathChanged = subpath !== this.subpath
if (!parentChanged && !subpathChanged) return
if (process.env.NODE_ENV !== "production") {
if (!subpath) {
// istanbul ignore next
throw fail("assertion failed: subpath expected")
}
if (!newParent) {
// istanbul ignore next
throw fail("assertion failed: new parent expected")
}
if (this.parent && parentChanged) {
throw fail(
`A node cannot exists twice in the state tree. Failed to add ${this} to path '${
newParent.path
}/${subpath}'.`
)
}
if (!this.parent && newParent.root === this) {
throw fail(
`A state tree is not allowed to contain itself. Cannot assign ${this} to path '${
newParent.path
}/${subpath}'`
)
}
if (!this.parent && !!this.environment && this.environment !== newParent.environment) {
throw fail(
`A state tree cannot be made part of another state tree as long as their environments are different.`
)
}
}
if (parentChanged) {
// attach to new parent
newParent.root.identifierCache!.mergeCache(this)
this.baseSetParent(newParent, subpath)
this.fireHook(Hook.afterAttach)
} else if (subpathChanged) {
// moving to a new subpath on the same parent
this.baseSetParent(this.parent, subpath)
}
}
protected fireHook(name: Hook): void {
this.fireInternalHook(name)
const fn =
this.storedValue &&
typeof this.storedValue === "object" &&
(this.storedValue as any)[name]
if (typeof fn === "function") {
// we check for it to allow old mobx peer dependencies that don't have the method to work (even when still bugged)
if (_allowStateChangesInsideComputed) {
_allowStateChangesInsideComputed(() => {
fn.apply(this.storedValue)
})
} else {
fn.apply(this.storedValue)
}
}
}
private _snapshotUponDeath?: S
// advantage of using computed for a snapshot is that nicely respects transactions etc.
@computed
get snapshot(): S {
return freeze(this.getSnapshot())
}
// NOTE: we use this method to get snapshot without creating @computed overhead
getSnapshot(): S {
if (!this.isAlive) return this._snapshotUponDeath!
return this._observableInstanceState === ObservableInstanceLifecycle.CREATED
? this._getActualSnapshot()
: this._getCachedInitialSnapshot()
}
private _getActualSnapshot(): S {
return this.type.getSnapshot(this)
}
private _getCachedInitialSnapshot(): S {
if (!this._cachedInitialSnapshotCreated) {
const type = this.type
const childNodes = this._childNodes
const snapshot = this._initialSnapshot
this._cachedInitialSnapshot = type.processInitialSnapshot(childNodes, snapshot)
this._cachedInitialSnapshotCreated = true
}
return this._cachedInitialSnapshot!
}
private isRunningAction(): boolean {
if (this._isRunningAction) return true
if (this.isRoot) return false
return this.parent!.isRunningAction()
}
assertAlive(context: AssertAliveContext): void {
const livelinessChecking = getLivelinessChecking()
if (!this.isAlive && livelinessChecking !== "ignore") {
const error = this._getAssertAliveError(context)
switch (livelinessChecking) {
case "error":
throw fail(error)
case "warn":
warnError(error)
}
}
}
private _getAssertAliveError(context: AssertAliveContext): string {
const escapedPath = this.getEscapedPath(false) || this.pathUponDeath || ""
const subpath = (context.subpath && escapeJsonPath(context.subpath)) || ""
const actionContext = context.actionContext || getCurrentActionContext()
let actionFullPath = ""
if (actionContext && actionContext.name != null) {
// try to use the context, and if it not available use the node one
const actionPath =
(actionContext && actionContext.context && getPath(actionContext.context)) ||
escapedPath
actionFullPath = `${actionPath}.${actionContext.name}()`
}
return `You are trying to read or write to an object that is no longer part of a state tree. (Object type: '${
this.type.name
}', Path upon death: '${escapedPath}', Subpath: '${subpath}', Action: '${actionFullPath}'). Either detach nodes first, or don't use objects after removing / replacing them in the tree.`
}
getChildNode(subpath: string): AnyNode {
this.assertAlive({
subpath
})
this._autoUnbox = false
try {
return this._observableInstanceState === ObservableInstanceLifecycle.CREATED
? this.type.getChildNode(this, subpath)
: this._childNodes![subpath]
} finally {
this._autoUnbox = true
}
}
getChildren(): ReadonlyArray<AnyNode> {
this.assertAlive(EMPTY_OBJECT)
this._autoUnbox = false
try {
return this._observableInstanceState === ObservableInstanceLifecycle.CREATED
? this.type.getChildren(this)
: convertChildNodesToArray(this._childNodes)
} finally {
this._autoUnbox = true
}
}
getChildType(propertyName?: string): IAnyType {
return this.type.getChildType(propertyName)
}
get isProtected(): boolean {
return this.root.isProtectionEnabled
}
assertWritable(context: AssertAliveContext): void {
this.assertAlive(context)
if (!this.isRunningAction() && this.isProtected) {
throw fail(
`Cannot modify '${this}', the object is protected and can only be modified by using an action.`
)
}
}
removeChild(subpath: string): void {
this.type.removeChild(this, subpath)
}
// bound on the constructor
unbox(childNode: AnyNode | undefined): AnyNode | undefined {
if (!childNode) return childNode
this.assertAlive({
subpath: childNode.subpath || childNode.subpathUponDeath
})
return this._autoUnbox ? childNode.value : childNode
}
toString(): string {
const identifier = this.identifier ? `(id: ${this.identifier})` : ""
return `${this.type.name}@${this.path || "<root>"}${identifier}${
this.isAlive ? "" : "[dead]"
}`
}
finalizeCreation(): void {
this.baseFinalizeCreation(() => {
for (let child of this.getChildren()) {
child.finalizeCreation()
}
this.fireInternalHook(Hook.afterCreationFinalization)
})
}
@action
detach(): void {
if (!this.isAlive) throw fail(`Error while detaching, node is not alive.`)
this.clearParent()
}
private preboot(): void {
const self = this
this._applyPatches = createActionInvoker(
this.storedValue,
"@APPLY_PATCHES",
(patches: IJsonPatch[]) => {
patches.forEach(patch => {
const parts = splitJsonPath(patch.path)
const node = resolveNodeByPathParts(self, parts.slice(0, -1)) as AnyObjectNode
node.applyPatchLocally(parts[parts.length - 1], patch)
})
}
)
this._applySnapshot = createActionInvoker(
this.storedValue,
"@APPLY_SNAPSHOT",
(snapshot: C) => {
// if the snapshot is the same as the current one, avoid performing a reconcile
if (snapshot === (self.snapshot as any)) return
// else, apply it by calling the type logic
return self.type.applySnapshot(self, snapshot as any)
}
)
addHiddenFinalProp(this.storedValue, "$treenode", this)
addHiddenFinalProp(this.storedValue, "toJSON", toJSON)
}
@action
die(): void {
if (!this.isAlive || this.state === NodeLifeCycle.DETACHING) return
this.aboutToDie()
this.finalizeDeath()
}
aboutToDie(): void {
if (this._observableInstanceState === ObservableInstanceLifecycle.UNINITIALIZED) {
return
}
this.getChildren().forEach(node => {
node.aboutToDie()
})
// beforeDestroy should run before the disposers since else we could end up in a situation where
// a disposer added with addDisposer at this stage (beforeDestroy) is actually never released
this.baseAboutToDie()
this._internalEventsEmit(InternalEvents.Dispose)
this._internalEventsClear(InternalEvents.Dispose)
}
finalizeDeath(): void {
// invariant: not called directly but from "die"
this.getChildren().forEach(node => {
node.finalizeDeath()
})
this.root.identifierCache!.notifyDied(this)
// "kill" the computed prop and just store the last snapshot
const snapshot = this.snapshot
this._snapshotUponDeath = snapshot
this._internalEventsClearAll()
this.baseFinalizeDeath()
}
onSnapshot(onChange: (snapshot: S) => void): IDisposer {
this._addSnapshotReaction()
return this._internalEventsRegister(InternalEvents.Snapshot, onChange)
}
protected emitSnapshot(snapshot: S): void {
this._internalEventsEmit(InternalEvents.Snapshot, snapshot)
}
onPatch(handler: (patch: IJsonPatch, reversePatch: IJsonPatch) => void): IDisposer {
return this._internalEventsRegister(InternalEvents.Patch, handler)
}
emitPatch(basePatch: IReversibleJsonPatch, source: AnyNode): void {
if (this._internalEventsHasSubscribers(InternalEvents.Patch)) {
const localizedPatch: IReversibleJsonPatch = extend({}, basePatch, {
path: source.path.substr(this.path.length) + "/" + basePatch.path // calculate the relative path of the patch
})
const [patch, reversePatch] = splitPatch(localizedPatch)
this._internalEventsEmit(InternalEvents.Patch, patch, reversePatch)
}
if (this.parent) this.parent.emitPatch(basePatch, source)
}
hasDisposer(disposer: () => void): boolean {
return this._internalEventsHas(InternalEvents.Dispose, disposer)
}
addDisposer(disposer: () => void): void {
if (!this.hasDisposer(disposer)) {
this._internalEventsRegister(InternalEvents.Dispose, disposer, true)
return
}
throw fail("cannot add a disposer when it is already registered for execution")
}
removeDisposer(disposer: () => void): void {
if (!this._internalEventsHas(InternalEvents.Dispose, disposer)) {
throw fail("cannot remove a disposer which was never registered for execution")
}
this._internalEventsUnregister(InternalEvents.Dispose, disposer)
}
removeMiddleware(handler: IMiddlewareHandler): void {
if (this.middlewares)
this.middlewares = this.middlewares.filter(middleware => middleware.handler !== handler)
}
addMiddleWare(handler: IMiddlewareHandler, includeHooks: boolean = true): IDisposer {
if (!this.middlewares) this.middlewares = [{ handler, includeHooks }]
else this.middlewares.push({ handler, includeHooks })
return () => {
this.removeMiddleware(handler)
}
}
applyPatchLocally(subpath: string, patch: IJsonPatch): void {
this.assertWritable({
subpath
})
this.createObservableInstanceIfNeeded()
this.type.applyPatchLocally(this, subpath, patch)
}
private _addSnapshotReaction(): void {
if (!this._hasSnapshotReaction) {
const snapshotDisposer = reaction(
() => this.snapshot,
snapshot => this.emitSnapshot(snapshot),
snapshotReactionOptions
)
this.addDisposer(snapshotDisposer)
this._hasSnapshotReaction = true
}
}
// #region internal event handling
private _internalEvents?: EventHandlers<InternalEventHandlers<S>>
// we proxy the methods to avoid creating an EventHandlers instance when it is not needed
private _internalEventsHasSubscribers(event: InternalEvents): boolean {
return !!this._internalEvents && this._internalEvents.hasSubscribers(event)
}
private _internalEventsRegister<IE extends InternalEvents>(
event: IE,
eventHandler: InternalEventHandlers<S>[IE],
atTheBeginning = false
): IDisposer {
if (!this._internalEvents) {
this._internalEvents = new EventHandlers()
}
return this._internalEvents.register(event, eventHandler, atTheBeginning)
}
private _internalEventsHas<IE extends InternalEvents>(
event: IE,
eventHandler: InternalEventHandlers<S>[IE]
): boolean {
return !!this._internalEvents && this._internalEvents.has(event, eventHandler)
}
private _internalEventsUnregister<IE extends InternalEvents>(
event: IE,
eventHandler: InternalEventHandlers<S>[IE]
): void {
if (this._internalEvents) {
this._internalEvents.unregister(event, eventHandler)
}
}
private _internalEventsEmit<IE extends InternalEvents>(
event: IE,
...args: ArgumentTypes<InternalEventHandlers<S>[IE]>
): void {
if (this._internalEvents) {
this._internalEvents.emit(event, ...args)
}
}
private _internalEventsClear(event: InternalEvents): void {
if (this._internalEvents) {
this._internalEvents.clear(event)
}
}
private _internalEventsClearAll(): void {
if (this._internalEvents) {
this._internalEvents.clearAll()
}
}
// #endregion
}
/**
* @internal
* @hidden
*/
export type AnyObjectNode = ObjectNode<any, any, any>
/**
* @internal
* @hidden
*/
export interface AssertAliveContext {
subpath?: string
actionContext?: IMiddlewareEvent
}