-
Notifications
You must be signed in to change notification settings - Fork 640
/
map.ts
516 lines (467 loc) · 14.8 KB
/
map.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
import {
_interceptReads,
action,
IInterceptor,
IKeyValueMap,
IMapDidChange,
IMapWillChange,
intercept,
Lambda,
observable,
ObservableMap,
observe,
values,
IObservableMapInitialValues
} from "mobx"
import {
ComplexType,
createObjectNode,
escapeJsonPath,
MstError,
flattenTypeErrors,
getContextForPath,
getStateTreeNode,
IAnyStateTreeNode,
IAnyType,
IChildNodesMap,
IValidationContext,
IJsonPatch,
isMutable,
isPlainObject,
isStateTreeNode,
isType,
IType,
IValidationResult,
ModelType,
ObjectNode,
typecheckInternal,
typeCheckFailure,
TypeFlags,
EMPTY_OBJECT,
normalizeIdentifier,
AnyObjectNode,
AnyNode,
IAnyModelType,
asArray,
cannotDetermineSubtype,
getSnapshot,
isValidIdentifier,
ExtractCSTWithSTN,
devMode,
createActionInvoker,
addHiddenFinalProp,
addHiddenWritableProp,
IHooksGetter
} from "../../internal"
/** @hidden */
export interface IMapType<IT extends IAnyType>
extends IType<
IKeyValueMap<IT["CreationType"]> | undefined,
IKeyValueMap<IT["SnapshotType"]>,
IMSTMap<IT>
> {
hooks(hooks: IHooksGetter<IMSTMap<IT>>): IMapType<IT>
}
/** @hidden */
export interface IMSTMap<IT extends IAnyType> {
// bases on ObservableMap, but fine tuned to the auto snapshot conversion of MST
clear(): void
delete(key: string): boolean
forEach(
callbackfn: (value: IT["Type"], key: string | number, map: this) => void,
thisArg?: any
): void
get(key: string | number): IT["Type"] | undefined
has(key: string | number): boolean
set(key: string | number, value: ExtractCSTWithSTN<IT>): this
readonly size: number
put(value: ExtractCSTWithSTN<IT>): IT["Type"]
keys(): IterableIterator<string>
values(): IterableIterator<IT["Type"]>
entries(): IterableIterator<[string, IT["Type"]]>
[Symbol.iterator](): IterableIterator<[string, IT["Type"]]>
/** Merge another object into this map, returns self. */
merge(
other:
| IMSTMap<IType<any, any, IT["TypeWithoutSTN"]>>
| IKeyValueMap<ExtractCSTWithSTN<IT>>
| any
): this
replace(
values:
| IMSTMap<IType<any, any, IT["TypeWithoutSTN"]>>
| IKeyValueMap<ExtractCSTWithSTN<IT>>
| any
): this
toJSON(): IKeyValueMap<IT["SnapshotType"]>
toString(): string
[Symbol.toStringTag]: "Map"
/**
* 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(
listener: (changes: IMapDidChange<string, IT["Type"]>) => void,
fireImmediately?: boolean
): Lambda
intercept(handler: IInterceptor<IMapWillChange<string, IT["Type"]>>): Lambda
}
const needsIdentifierError = `Map.put can only be used to store complex values that have an identifier type attribute`
function tryCollectModelTypes(type: IAnyType, modelTypes: Array<IAnyModelType>): boolean {
const subtypes = type.getSubTypes()
if (subtypes === cannotDetermineSubtype) {
return false
}
if (subtypes) {
const subtypesArray = asArray(subtypes)
for (const subtype of subtypesArray) {
if (!tryCollectModelTypes(subtype, modelTypes)) return false
}
}
if (type instanceof ModelType) {
modelTypes.push(type)
}
return true
}
/**
* @internal
* @hidden
*/
export enum MapIdentifierMode {
UNKNOWN,
YES,
NO
}
class MSTMap<IT extends IAnyType> extends ObservableMap<string, any> {
constructor(initialData?: IObservableMapInitialValues<string, any> | undefined, name?: string) {
super(initialData, (observable.ref as any).enhancer, name)
}
get(key: string): IT["Type"] | undefined {
// maybe this is over-enthousiastic? normalize numeric keys to strings
return super.get("" + key)
}
has(key: string) {
return super.has("" + key)
}
delete(key: string) {
return super.delete("" + key)
}
set(key: string, value: ExtractCSTWithSTN<IT>): this {
return super.set("" + key, value)
}
put(value: ExtractCSTWithSTN<IT>): IT["Type"] {
if (!value) throw new MstError(`Map.put cannot be used to set empty values`)
if (isStateTreeNode(value)) {
const node = getStateTreeNode(value)
if (devMode()) {
if (!node.identifierAttribute) {
throw new MstError(needsIdentifierError)
}
}
if (node.identifier === null) {
throw new MstError(needsIdentifierError)
}
this.set(node.identifier, value)
return value as any
} else if (!isMutable(value)) {
throw new MstError(`Map.put can only be used to store complex values`)
} else {
const mapNode = getStateTreeNode(this as IAnyStateTreeNode)
const mapType = mapNode.type as MapType<any>
if (mapType.identifierMode !== MapIdentifierMode.YES) {
throw new MstError(needsIdentifierError)
}
const idAttr = mapType.mapIdentifierAttribute!
const id = (value as any)[idAttr]
if (!isValidIdentifier(id)) {
// try again but this time after creating a node for the value
// since it might be an optional identifier
const newNode = this.put(mapType.getChildType().create(value, mapNode.environment))
return this.put(getSnapshot(newNode))
}
const key = normalizeIdentifier(id)
this.set(key, value)
return this.get(key) as any
}
}
}
/**
* @internal
* @hidden
*/
export class MapType<IT extends IAnyType> extends ComplexType<
IKeyValueMap<IT["CreationType"]> | undefined,
IKeyValueMap<IT["SnapshotType"]>,
IMSTMap<IT>
> {
identifierMode: MapIdentifierMode = MapIdentifierMode.UNKNOWN
mapIdentifierAttribute: string | undefined = undefined
readonly flags = TypeFlags.Map
private readonly hookInitializers: Array<IHooksGetter<IMSTMap<IT>>> = []
constructor(
name: string,
private readonly _subType: IAnyType,
hookInitializers: Array<IHooksGetter<IMSTMap<IT>>> = []
) {
super(name)
this._determineIdentifierMode()
this.hookInitializers = hookInitializers
}
hooks(hooks: IHooksGetter<IMSTMap<IT>>) {
const hookInitializers =
this.hookInitializers.length > 0 ? this.hookInitializers.concat(hooks) : [hooks]
return new MapType(this.name, this._subType, hookInitializers)
}
instantiate(
parent: AnyObjectNode | null,
subpath: string,
environment: any,
initialValue: this["C"] | this["T"]
): this["N"] {
this._determineIdentifierMode()
return createObjectNode(this, parent, subpath, environment, initialValue)
}
private _determineIdentifierMode() {
if (this.identifierMode !== MapIdentifierMode.UNKNOWN) {
return
}
const modelTypes: IAnyModelType[] = []
if (tryCollectModelTypes(this._subType, modelTypes)) {
const identifierAttribute: string | undefined = modelTypes.reduce(
(current: IAnyModelType["identifierAttribute"], type) => {
if (!type.identifierAttribute) return current
if (current && current !== type.identifierAttribute) {
throw new MstError(
`The objects in a map should all have the same identifier attribute, expected '${current}', but child of type '${type.name}' declared attribute '${type.identifierAttribute}' as identifier`
)
}
return type.identifierAttribute
},
undefined as IAnyModelType["identifierAttribute"]
)
if (identifierAttribute) {
this.identifierMode = MapIdentifierMode.YES
this.mapIdentifierAttribute = identifierAttribute
} else {
this.identifierMode = MapIdentifierMode.NO
}
}
}
initializeChildNodes(objNode: this["N"], initialSnapshot: this["C"] = {}): IChildNodesMap {
const subType = (objNode.type as this)._subType
const result: IChildNodesMap = {}
Object.keys(initialSnapshot!).forEach((name) => {
result[name] = subType.instantiate(objNode, name, undefined, initialSnapshot[name])
})
return result
}
createNewInstance(childNodes: IChildNodesMap): this["T"] {
return new MSTMap(childNodes, this.name) as any
}
finalizeNewInstance(node: this["N"], instance: ObservableMap<string, any>): void {
_interceptReads(instance, node.unbox)
const type = node.type as this
type.hookInitializers.forEach((initializer) => {
const hooks = initializer(instance as unknown as IMSTMap<IT>)
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, this.willChange)
observe(instance, this.didChange)
}
describe() {
return this.name
}
getChildren(node: this["N"]): ReadonlyArray<AnyNode> {
// return (node.storedValue as ObservableMap<any>).values()
return values(node.storedValue)
}
getChildNode(node: this["N"], key: string): AnyNode {
const childNode = node.storedValue.get("" + key)
if (!childNode) throw new MstError("Not a child " + key)
return childNode
}
willChange(change: IMapWillChange<string, AnyNode>): IMapWillChange<string, AnyNode> | null {
const node = getStateTreeNode(change.object as IAnyStateTreeNode)
const key = change.name
node.assertWritable({ subpath: key })
const mapType = node.type as this
const subType = mapType._subType
switch (change.type) {
case "update":
{
const { newValue } = change
const oldValue = change.object.get(key)
if (newValue === oldValue) return null
typecheckInternal(subType, newValue)
change.newValue = subType.reconcile(node.getChildNode(key), change.newValue, node, key)
mapType.processIdentifier(key, change.newValue)
}
break
case "add":
{
typecheckInternal(subType, change.newValue)
change.newValue = subType.instantiate(node, key, undefined, change.newValue)
mapType.processIdentifier(key, change.newValue)
}
break
}
return change
}
private processIdentifier(expected: string, node: AnyNode): void {
if (this.identifierMode === MapIdentifierMode.YES && node instanceof ObjectNode) {
const identifier = node.identifier!
if (identifier !== expected)
throw new MstError(
`A map of objects containing an identifier should always store the object under their own identifier. Trying to store key '${identifier}', but expected: '${expected}'`
)
}
}
getSnapshot(node: this["N"]): this["S"] {
const res: any = {}
node.getChildren().forEach((childNode) => {
res[childNode.subpath] = childNode.snapshot
})
return res
}
processInitialSnapshot(childNodes: IChildNodesMap): this["S"] {
const processed: any = {}
Object.keys(childNodes).forEach((key) => {
processed[key] = childNodes[key].getSnapshot()
})
return processed
}
didChange(change: IMapDidChange<string, AnyNode>): void {
const node = getStateTreeNode(change.object as IAnyStateTreeNode)
switch (change.type) {
case "update":
return void node.emitPatch(
{
op: "replace",
path: escapeJsonPath(change.name),
value: change.newValue.snapshot,
oldValue: change.oldValue ? change.oldValue.snapshot : undefined
},
node
)
case "add":
return void node.emitPatch(
{
op: "add",
path: escapeJsonPath(change.name),
value: change.newValue.snapshot,
oldValue: undefined
},
node
)
case "delete":
// a node got deleted, get the old snapshot and make the node die
const oldSnapshot = change.oldValue.snapshot
change.oldValue.die()
// emit the patch
return void node.emitPatch(
{
op: "remove",
path: escapeJsonPath(change.name),
oldValue: oldSnapshot
},
node
)
}
}
applyPatchLocally(node: this["N"], subpath: string, patch: IJsonPatch): void {
const target = node.storedValue
switch (patch.op) {
case "add":
case "replace":
target.set(subpath, patch.value)
break
case "remove":
target.delete(subpath)
break
}
}
applySnapshot(node: this["N"], snapshot: this["C"]): void {
typecheckInternal(this, snapshot)
const target = node.storedValue
const currentKeys: { [key: string]: boolean } = {}
Array.from(target.keys()).forEach((key) => {
currentKeys[key] = false
})
if (snapshot) {
// Don't use target.replace, as it will throw away all existing items first
for (let key in snapshot) {
target.set(key, snapshot[key])
currentKeys["" + key] = true
}
}
Object.keys(currentKeys).forEach((key) => {
if (currentKeys[key] === false) target.delete(key)
})
}
getChildType(): IAnyType {
return this._subType
}
isValidSnapshot(value: this["C"], context: IValidationContext): IValidationResult {
if (!isPlainObject(value)) {
return typeCheckFailure(context, value, "Value is not a plain object")
}
return flattenTypeErrors(
Object.keys(value).map((path) =>
this._subType.validate(value[path], getContextForPath(context, path, this._subType))
)
)
}
getDefaultSnapshot(): this["C"] {
return EMPTY_OBJECT as this["C"]
}
removeChild(node: this["N"], subpath: string) {
node.storedValue.delete(subpath)
}
}
MapType.prototype.applySnapshot = action(MapType.prototype.applySnapshot)
/**
* `types.map` - Creates a key based collection type who's children are all of a uniform declared type.
* If the type stored in a map has an identifier, it is mandatory to store the child under that identifier in the map.
*
* This type will always produce [observable maps](https://mobx.js.org/api.html#observablemap)
*
* Example:
* ```ts
* const Todo = types.model({
* id: types.identifier,
* task: types.string
* })
*
* const TodoStore = types.model({
* todos: types.map(Todo)
* })
*
* const s = TodoStore.create({ todos: {} })
* unprotect(s)
* s.todos.set(17, { task: "Grab coffee", id: 17 })
* s.todos.put({ task: "Grab cookie", id: 18 }) // put will infer key from the identifier
* console.log(s.todos.get(17).task) // prints: "Grab coffee"
* ```
*
* @param subtype
* @returns
*/
export function map<IT extends IAnyType>(subtype: IT): IMapType<IT> {
return new MapType<IT>(`Map<string, ${subtype.name}>`, subtype)
}
/**
* Returns if a given value represents a map type.
*
* @param type
* @returns `true` if it is a map type.
*/
export function isMapType<Items extends IAnyType = IAnyType>(
type: IAnyType
): type is IMapType<Items> {
return isType(type) && (type.flags & TypeFlags.Map) > 0
}