-
Notifications
You must be signed in to change notification settings - Fork 642
/
Copy patharray.ts
514 lines (462 loc) · 16.8 KB
/
array.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
import {
_getAdministration,
action,
IArrayDidChange,
IArrayWillChange,
IArrayWillSplice,
intercept,
IObservableArray,
observable,
observe
} from "mobx"
import {
addHiddenFinalProp,
addHiddenWritableProp,
AnyNode,
AnyObjectNode,
assertIsType,
ComplexType,
convertChildNodesToArray,
createActionInvoker,
createObjectNode,
devMode,
EMPTY_ARRAY,
EMPTY_OBJECT,
ExtractCSTWithSTN,
MstError,
flattenTypeErrors,
getContextForPath,
getStateTreeNode,
IAnyStateTreeNode,
IAnyType,
IChildNodesMap,
IHooksGetter,
IJsonPatch,
isArray,
isNode,
isPlainObject,
isStateTreeNode,
IStateTreeNode,
isType,
IType,
IValidationContext,
IValidationResult,
mobxShallow,
ObjectNode,
typeCheckFailure,
typecheckInternal,
TypeFlags
} from "../../internal"
/** @hidden */
export interface IMSTArray<IT extends IAnyType> extends IObservableArray<IT["Type"]> {
// needs to be split or else it will complain about not being compatible with the array interface
push(...items: IT["Type"][]): number
push(...items: ExtractCSTWithSTN<IT>[]): number
concat(...items: ConcatArray<IT["Type"]>[]): IT["Type"][]
concat(...items: ConcatArray<ExtractCSTWithSTN<IT>>[]): IT["Type"][]
concat(...items: (IT["Type"] | ConcatArray<IT["Type"]>)[]): IT["Type"][]
concat(...items: (ExtractCSTWithSTN<IT> | ConcatArray<ExtractCSTWithSTN<IT>>)[]): IT["Type"][]
splice(start: number, deleteCount?: number): IT["Type"][]
splice(start: number, deleteCount: number, ...items: IT["Type"][]): IT["Type"][]
splice(start: number, deleteCount: number, ...items: ExtractCSTWithSTN<IT>[]): IT["Type"][]
unshift(...items: IT["Type"][]): number
unshift(...items: ExtractCSTWithSTN<IT>[]): number
}
/** @hidden */
export interface IArrayType<IT extends IAnyType>
extends IType<readonly IT["CreationType"][] | undefined, IT["SnapshotType"][], IMSTArray<IT>> {
hooks(hooks: IHooksGetter<IMSTArray<IAnyType>>): IArrayType<IT>
}
/**
* @internal
* @hidden
*/
export class ArrayType<IT extends IAnyType> extends ComplexType<
readonly IT["CreationType"][] | undefined,
IT["SnapshotType"][],
IMSTArray<IT>
> {
readonly flags = TypeFlags.Array
private readonly hookInitializers: Array<IHooksGetter<IMSTArray<IT>>> = []
constructor(
name: string,
private readonly _subType: IT,
hookInitializers: Array<IHooksGetter<IMSTArray<IT>>> = []
) {
super(name)
this.hookInitializers = hookInitializers
}
hooks(hooks: IHooksGetter<IMSTArray<IT>>) {
const hookInitializers =
this.hookInitializers.length > 0 ? this.hookInitializers.concat(hooks) : [hooks]
return new ArrayType(this.name, this._subType, hookInitializers)
}
instantiate(
parent: AnyObjectNode | null,
subpath: string,
environment: any,
initialValue: this["C"] | this["T"]
): this["N"] {
return createObjectNode(this, parent, subpath, environment, initialValue)
}
initializeChildNodes(objNode: this["N"], snapshot: this["C"] = []): IChildNodesMap {
const subType = (objNode.type as this)._subType
const result: IChildNodesMap = {}
snapshot.forEach((item, index) => {
const subpath = "" + index
result[subpath] = subType.instantiate(objNode, subpath, undefined, item)
})
return result
}
createNewInstance(childNodes: IChildNodesMap): this["T"] {
const options = { ...mobxShallow, name: this.name }
return observable.array(convertChildNodesToArray(childNodes), options) as this["T"]
}
finalizeNewInstance(node: this["N"], instance: this["T"]): void {
_getAdministration(instance).dehancer = node.unbox
const type = node.type as this
type.hookInitializers.forEach(initializer => {
const hooks = initializer(instance)
Object.keys(hooks).forEach(name => {
const hook = hooks[name as keyof typeof hooks]!
const actionInvoker = createActionInvoker(instance as IAnyStateTreeNode, name, hook)
;(!devMode() ? addHiddenFinalProp : addHiddenWritableProp)(
instance,
name,
actionInvoker
)
})
})
intercept(instance as IObservableArray<AnyNode>, this.willChange)
observe(instance as IObservableArray<AnyNode>, this.didChange)
}
describe() {
return this.name
}
getChildren(node: this["N"]): AnyNode[] {
return node.storedValue.slice()
}
getChildNode(node: this["N"], key: string): AnyNode {
const index = Number(key)
if (index < node.storedValue.length) return node.storedValue[index]
throw new MstError("Not a child: " + key)
}
willChange(
change: IArrayWillChange<AnyNode> | IArrayWillSplice<AnyNode>
): IArrayWillChange<AnyNode> | IArrayWillSplice<AnyNode> | null {
const node = getStateTreeNode(change.object as IStateTreeNode<this>)
node.assertWritable({ subpath: "" + change.index })
const subType = (node.type as this)._subType
const childNodes = node.getChildren()
switch (change.type) {
case "update":
{
if (change.newValue === change.object[change.index]) return null
const updatedNodes = reconcileArrayChildren(
node,
subType,
[childNodes[change.index]],
[change.newValue],
[change.index]
)
if (!updatedNodes) {
return null
}
change.newValue = updatedNodes[0]
}
break
case "splice":
{
const { index, removedCount, added } = change
const addedNodes = reconcileArrayChildren(
node,
subType,
childNodes.slice(index, index + removedCount),
added,
added.map((_, i) => index + i)
)
if (!addedNodes) {
return null
}
change.added = addedNodes
// update paths of remaining items
for (let i = index + removedCount; i < childNodes.length; i++) {
childNodes[i].setParent(node, "" + (i + added.length - removedCount))
}
}
break
}
return change
}
getSnapshot(node: this["N"]): this["S"] {
return node.getChildren().map(childNode => childNode.snapshot)
}
processInitialSnapshot(childNodes: IChildNodesMap): this["S"] {
const processed: this["S"] = []
Object.keys(childNodes).forEach(key => {
processed.push(childNodes[key].getSnapshot())
})
return processed
}
didChange(change: IArrayDidChange<AnyNode>): void {
const node = getStateTreeNode(change.object as IAnyStateTreeNode)
switch (change.type) {
case "update":
return void node.emitPatch(
{
op: "replace",
path: "" + change.index,
value: change.newValue.snapshot,
oldValue: change.oldValue ? change.oldValue.snapshot : undefined
},
node
)
case "splice":
// Perf: emit one patch for clear and replace ops.
if (change.removedCount && change.addedCount === change.object.length) {
return void node.emitPatch(
{
op: "replace",
path: "",
value: node.snapshot,
oldValue: change.removed.map(node => node.snapshot)
},
node
)
}
for (let i = change.removedCount - 1; i >= 0; i--)
node.emitPatch(
{
op: "remove",
path: "" + (change.index + i),
oldValue: change.removed[i].snapshot
},
node
)
for (let i = 0; i < change.addedCount; i++)
node.emitPatch(
{
op: "add",
path: "" + (change.index + i),
value: change.added[i].snapshot,
oldValue: undefined
},
node
)
return
}
}
applyPatchLocally(node: this["N"], subpath: string, patch: IJsonPatch): void {
const target = node.storedValue
const index = subpath === "-" ? target.length : Number(subpath)
switch (patch.op) {
case "replace":
target[index] = patch.value
break
case "add":
target.splice(index, 0, patch.value)
break
case "remove":
target.splice(index, 1)
break
}
}
applySnapshot(node: this["N"], snapshot: this["C"]): void {
typecheckInternal(this, snapshot)
const target = node.storedValue
target.replace(snapshot as any)
}
getChildType(): IAnyType {
return this._subType
}
isValidSnapshot(value: this["C"], context: IValidationContext): IValidationResult {
if (!isArray(value)) {
return typeCheckFailure(context, value, "Value is not an array")
}
return flattenTypeErrors(
value.map((item, index) =>
this._subType.validate(item, getContextForPath(context, "" + index, this._subType))
)
)
}
getDefaultSnapshot(): this["C"] {
return EMPTY_ARRAY as this["C"]
}
removeChild(node: this["N"], subpath: string) {
node.storedValue.splice(Number(subpath), 1)
}
}
ArrayType.prototype.applySnapshot = action(ArrayType.prototype.applySnapshot)
/**
* `types.array` - Creates an index based collection type who's children are all of a uniform declared type.
*
* This type will always produce [observable arrays](https://mobx.js.org/api.html#observablearray)
*
* Example:
* ```ts
* const Todo = types.model({
* task: types.string
* })
*
* const TodoStore = types.model({
* todos: types.array(Todo)
* })
*
* const s = TodoStore.create({ todos: [] })
* unprotect(s) // needed to allow modifying outside of an action
* s.todos.push({ task: "Grab coffee" })
* console.log(s.todos[0]) // prints: "Grab coffee"
* ```
*
* @param subtype
* @returns
*/
export function array<IT extends IAnyType>(subtype: IT): IArrayType<IT> {
assertIsType(subtype, 1)
return new ArrayType<IT>(`${subtype.name}[]`, subtype)
}
function reconcileArrayChildren<TT>(
parent: AnyObjectNode,
childType: IType<any, any, TT>,
oldNodes: AnyNode[],
newValues: TT[],
newPaths: (string | number)[]
): AnyNode[] | null {
let nothingChanged = true
for (let i = 0; ; i++) {
const hasNewNode = i <= newValues.length - 1
const oldNode = oldNodes[i]
let newValue = hasNewNode ? newValues[i] : undefined
const newPath = "" + newPaths[i]
// for some reason, instead of newValue we got a node, fallback to the storedValue
// TODO: https://github.com/mobxjs/mobx-state-tree/issues/340#issuecomment-325581681
if (isNode(newValue)) newValue = newValue.storedValue
if (!oldNode && !hasNewNode) {
// both are empty, end
break
} else if (!hasNewNode) {
// new one does not exists
nothingChanged = false
oldNodes.splice(i, 1)
if (oldNode instanceof ObjectNode) {
// since it is going to be returned by pop/splice/shift better create it before killing it
// so it doesn't end up in an undead state
oldNode.createObservableInstanceIfNeeded()
}
oldNode.die()
i--
} else if (!oldNode) {
// there is no old node, create it
// check if already belongs to the same parent. if so, avoid pushing item in. only swapping can occur.
if (isStateTreeNode(newValue) && getStateTreeNode(newValue).parent === parent) {
// this node is owned by this parent, but not in the reconcilable set, so it must be double
throw new MstError(
`Cannot add an object to a state tree if it is already part of the same or another state tree. Tried to assign an object to '${
parent.path
}/${newPath}', but it lives already at '${getStateTreeNode(newValue).path}'`
)
}
nothingChanged = false
const newNode = valueAsNode(childType, parent, newPath, newValue)
oldNodes.splice(i, 0, newNode)
} else if (areSame(oldNode, newValue)) {
// both are the same, reconcile
oldNodes[i] = valueAsNode(childType, parent, newPath, newValue, oldNode)
} else {
// nothing to do, try to reorder
let oldMatch = undefined
// find a possible candidate to reuse
for (let j = i; j < oldNodes.length; j++) {
if (areSame(oldNodes[j], newValue)) {
oldMatch = oldNodes.splice(j, 1)[0]
break
}
}
nothingChanged = false
const newNode = valueAsNode(childType, parent, newPath, newValue, oldMatch)
oldNodes.splice(i, 0, newNode)
}
}
return nothingChanged ? null : oldNodes
}
/**
* Convert a value to a node at given parent and subpath. Attempts to reuse old node if possible and given.
*/
function valueAsNode(
childType: IAnyType,
parent: AnyObjectNode,
subpath: string,
newValue: any,
oldNode?: AnyNode
) {
// ensure the value is valid-ish
typecheckInternal(childType, newValue)
function getNewNode() {
// the new value has a MST node
if (isStateTreeNode(newValue)) {
const childNode = getStateTreeNode(newValue)
childNode.assertAlive(EMPTY_OBJECT)
// the node lives here
if (childNode.parent !== null && childNode.parent === parent) {
childNode.setParent(parent, subpath)
return childNode
}
}
// there is old node and new one is a value/snapshot
if (oldNode) {
return childType.reconcile(oldNode, newValue, parent, subpath)
}
// nothing to do, create from scratch
return childType.instantiate(parent, subpath, undefined, newValue)
}
const newNode = getNewNode()
if (oldNode && oldNode !== newNode) {
if (oldNode instanceof ObjectNode) {
// since it is going to be returned by pop/splice/shift better create it before killing it
// so it doesn't end up in an undead state
oldNode.createObservableInstanceIfNeeded()
}
oldNode.die()
}
return newNode
}
/**
* Check if a node holds a value.
*/
function areSame(oldNode: AnyNode, newValue: any) {
// never consider dead old nodes for reconciliation
if (!oldNode.isAlive) {
return false
}
// the new value has the same node
if (isStateTreeNode(newValue)) {
const newNode = getStateTreeNode(newValue)
return newNode.isAlive && newNode === oldNode
}
// the provided value is the snapshot of the old node
if (oldNode.snapshot === newValue) {
return true
}
// Non object nodes don't get reconciled
if (!(oldNode instanceof ObjectNode)) {
return false
}
const oldNodeType = oldNode.getReconciliationType()
// new value is a snapshot with the correct identifier
return (
oldNode.identifier !== null &&
oldNode.identifierAttribute &&
isPlainObject(newValue) &&
oldNodeType.is(newValue) &&
(oldNodeType as any).isMatchingSnapshotId(oldNode, newValue)
)
}
/**
* Returns if a given value represents an array type.
*
* @param type
* @returns `true` if the type is an array type.
*/
export function isArrayType(type: unknown): type is IArrayType<IAnyType> {
return isType(type) && (type.flags & TypeFlags.Array) > 0
}