forked from mobxjs/mobx-state-tree
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmap.ts
More file actions
218 lines (191 loc) · 8.5 KB
/
map.ts
File metadata and controls
218 lines (191 loc) · 8.5 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
import { getIdentifierAttribute } from "./object"
import { observable, ObservableMap, IMapChange, IMapWillChange, action, intercept, observe } from "mobx"
import { getMSTAdministration, maybeMST, MSTAdministration, valueToSnapshot, escapeJsonPath, IJsonPatch } from "../../core"
import { identity, isPlainObject, nothing, isPrimitive, fail, addHiddenFinalProp } from "../../utils"
import { IType, IComplexType, TypeFlags, isType } from "../type"
import { IContext, IValidationResult, typeCheckFailure, flattenTypeErrors, getContextForPath } from "../type-checker"
import { ComplexType } from "./complex-type"
interface IMapFactoryConfig {
isMapFactory: true
}
export interface IExtendedObservableMap<T> extends ObservableMap<T> {
put(value: T | any): this // downtype to any, again, because we cannot type the snapshot, see
}
export function mapToString(this: ObservableMap<any>) {
return `${getMSTAdministration(this)}(${this.size} items)`
}
function put(this: ObservableMap<any>, value: any) {
const identifierAttr = getIdentifierAttribute((getMSTAdministration(this).type as MapType<any, any>).subType)
if (!(!!identifierAttr)) fail(`Map.put is only supported if the subtype has an idenfier attribute`)
if (!(!!value)) fail(`Map.put cannot be used to set empty values`)
this.set(value[identifierAttr!], value)
return this
}
export class MapType<S, T> extends ComplexType<{[key: string]: S}, IExtendedObservableMap<T>> {
isMapFactory = true
subType: IType<any, any>
readonly flags = TypeFlags.Map
constructor(name: string, subType: IType<any, any>) {
super(name)
this.subType = subType
}
describe() {
return "Map<string, " + this.subType.describe() + ">"
}
createNewInstance() {
// const identifierAttr = getIdentifierAttribute(this.subType)
const map = observable.shallowMap()
addHiddenFinalProp(map, "put", put)
addHiddenFinalProp(map, "toString", mapToString)
return map
}
finalizeNewInstance(instance: ObservableMap<any>, snapshot: any) {
intercept(instance, c => this.willChange(c))
observe(instance, this.didChange)
getMSTAdministration(instance).applySnapshot(snapshot)
}
getChildMSTs(node: MSTAdministration): [string, MSTAdministration][] {
const res: [string, MSTAdministration][] = []
; (node.target as ObservableMap<any>).forEach((value: any, key: string) => {
maybeMST(value, childNode => { res.push([key, childNode])})
})
return res
}
getChildMST(node: MSTAdministration, key: string): MSTAdministration | null {
const target = node.target as ObservableMap<any>
if (target.has(key))
return maybeMST(target.get(key), identity, nothing)
return null
}
willChange(change: IMapWillChange<any>): IMapWillChange<any> | null {
const node = getMSTAdministration(change.object)
node.assertWritable()
// Q: how to create a map that is not keyed by identifier, but contains objects with identifiers? Is that a use case? A: No, that is were reference maps should come into play...
const identifierAttr = getIdentifierAttribute(node.type)
if (identifierAttr && change.newValue && typeof change.newValue === "object" && change.newValue[identifierAttr] !== change.name)
fail(`A map of objects containing an identifier should always store the object under their own identifier. Trying to store key '${change.name}', but expected: '${change.newValue[identifierAttr!]}'`)
switch (change.type) {
case "update":
{
const {newValue} = change
const oldValue = change.object.get(change.name)
if (newValue === oldValue)
return null
change.newValue = node.reconcileChildren(this.subType, [oldValue], [newValue], [change.name])[0]
}
break
case "add":
{
const {newValue} = change
change.newValue = node.reconcileChildren(this.subType, [], [newValue], [change.name])[0]
}
break
case "delete":
{
const oldValue = change.object.get(change.name)
node.reconcileChildren(this.subType, [oldValue], [], [])
}
break
}
return change
}
serialize(node: MSTAdministration): Object {
const target = node.target as ObservableMap<any>
const res: {[key: string]: any} = {}
target.forEach((value, key) => {
res[key] = valueToSnapshot(value)
})
return res
}
didChange(change: IMapChange<any>): void {
const node = getMSTAdministration(change.object)
switch (change.type) {
case "update":
case "add":
return void node.emitPatch({
op: change.type === "add" ? "add" : "replace",
path: escapeJsonPath(change.name),
value: valueToSnapshot(change.newValue)
}, node)
case "delete":
return void node.emitPatch({
op: "remove",
path: escapeJsonPath(change.name)
}, node)
}
}
applyPatchLocally(node: MSTAdministration, subpath: string, patch: IJsonPatch): void {
const target = node.target as ObservableMap<any>
switch (patch.op) {
case "add":
case "replace":
target.set(subpath, patch.value)
break
case "remove":
target.delete(subpath)
break
}
}
@action applySnapshot(node: MSTAdministration, snapshot: any): void {
node.pseudoAction(() => {
const target = node.target as ObservableMap<any>
const identifierAttr = getIdentifierAttribute(this.subType)
// Try to update snapshot smartly, by reusing instances under the same key as much as possible
const currentKeys: { [key: string]: boolean } = {}
target.keys().forEach(key => { currentKeys[key] = false })
Object.keys(snapshot).forEach(key => {
const item = snapshot[key]
if (identifierAttr && item && typeof item === "object" && key !== item[identifierAttr])
fail(`A map of objects containing an identifier should always store the object under their own identifier. Trying to store key '${key}', but expected: '${item[identifierAttr]}'`)
// if snapshot[key] is non-primitive, and this.get(key) has a Node, update it, instead of replace
if (key in currentKeys && !isPrimitive(item)) {
maybeMST(
target.get(key),
propertyNode => {
// update existing instance
propertyNode.applySnapshot(item)
},
() => {
target.set(key, item)
}
)
} else {
target.set(key, item)
}
currentKeys[key] = true
})
Object.keys(currentKeys).forEach(key => {
if (currentKeys[key] === false)
target.delete(key)
})
})
}
getChildType(key: string): IType<any, any> {
return this.subType
}
isValidSnapshot(value: any, context: IContext): IValidationResult {
if (!isPlainObject(value)) {
return typeCheckFailure(context, value)
}
return flattenTypeErrors(
Object.keys(value).map(
(path) => this.subType.validate(value[path], getContextForPath(context, path, this.subType))
)
)
}
getDefaultSnapshot() {
return {}
}
removeChild(node: MSTAdministration, subpath: string) {
(node.target as ObservableMap<any>).delete(subpath)
}
get identifierAttribute() {
return null
}
}
export function map<S, T>(subtype: IType<S, T>): IComplexType<{[key: string]: S}, IExtendedObservableMap<T>> {
return new MapType<S, T>(`map<string, ${subtype.name}>`, subtype)
}
export function isMapFactory<S, T>(type: any): type is IComplexType<{[key: string]: S}, IExtendedObservableMap<T>> {
return isType(type) && ((type as IType<any, any>).flags & TypeFlags.Map) > 0
}