-
Notifications
You must be signed in to change notification settings - Fork 1
/
index.js
308 lines (267 loc) · 8.9 KB
/
index.js
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
import {
types as MstTypes,
flow as mstFlow,
clone as mstClone,
onSnapshot as mstOnSnapshot,
onPatch as mstOnPatch,
onAction as mstOnAction,
isType as mstIsType,
} from 'mobx-state-tree'
import {merge, pick, omit, pipe, map as rdMap, filter, forEach, isEmpty} from 'rambda'
import {propertyDecorator, classDecorator, isPropertyDecorator} from 'decorating'
import {setPrototypeOf, getOwnPropertyDescriptors, capitalize} from './utils'
import * as is from './is'
const TypeKey = tagKey('type')
const PropsKey = tagKey('props')
const ViewsKey = tagKey('views')
const ExcludeKeys = [
'constructor', 'onPatch', 'onSnapshot', 'onAction',
TypeKey, PropsKey, ViewsKey,
]
export const model = classDecorator((
Class,
name = Class.name,
options = {auto: false},
) => {
if (is.obj(name)) {
options = merge(options, name)
name = Class.name
}
const {preProcessSnapshot, postProcessSnapshot} = Class
// TS class property initializers and defaults from constructor
const values = new Class()
const {onSnapshot, onPatch, onAction} = values
let props = extractTaggedProps(Class, PropsKey)
props = pipe(
rdMap(args => args[0]),
convertValuesToMst,
)(props)
const propKeys = Object.keys(props)
const viewKeys = Object.keys(extractTaggedProps(Class, ViewsKey))
const ownKeys = Object.getOwnPropertyNames(values)
const omitKeys = ExcludeKeys.concat(propKeys).concat(viewKeys)
const descs = getOwnPropertyDescriptors(Class.prototype)
const views = pick(viewKeys, descs)
const volatile = omit(omitKeys, pick(ownKeys, values))
const actions = {}
pipe(
filter((desc, key) => !omitKeys.includes(key)),
forEach((desc, key) => {
const {get, set, value} = desc
if (get || set) return views[key] = desc
if (is.fn(value)) return actions[key] = value
}),
)(descs)
const mstType = getMstType(Class) // es6 extending
let Model = mstType
? mstType.named(name).props(props)
: MstTypes.model(name, props)
Model = isEmpty(volatile) ? Model : Model.volatile(() => volatile)
Model = isEmpty(actions) ? Model : modelActions(Model)(() => actions)
Model = isEmpty(views) ? Model : Model.views(viewBinder(views))
Model = Model.preProcessSnapshot(snapshot => {
snapshot = preProcessSnapshot ? preProcessSnapshot(snapshot) : snapshot
if (!is.obj(snapshot)) {
if (!options.auto) return snapshot
snapshot = {}
}
return merge(values, snapshot)
})
if (postProcessSnapshot) {
Model = Model.postProcessSnapshot(postProcessSnapshot)
}
Model = Model.actions(obj => ({
afterCreate() {
if (onSnapshot) mstOnSnapshot(obj, onSnapshot.bind(obj))
if (onPatch) mstOnPatch(obj, onPatch.bind(obj))
if (onAction) mstOnAction(obj, onAction.bind(obj))
}
}))
const modelDecorator = prop(Model)
const Constructor = assignType(Model, function (...args) {
if (isPropertyDecorator(args)) {
return modelDecorator(...args)
}
if (this instanceof Constructor) {
throw new Error(`You should use ${name}.create() to instantiate object`)
}
})
return setPrototypeOf(Constructor, Class)
})
export const prop = propertyTagger(PropsKey)
export const view = propertyTagger(ViewsKey)
export const enumeration = createTypeDecorator(MstTypes.enumeration)
export const _model = createTypeDecorator(MstTypes.model)
export const compose = createTypeDecorator(MstTypes.compose)
export const custom = createTypeDecorator(MstTypes.custom)
export const reference = createTypeDecorator(MstTypes.reference)
export const safeReference = createTypeDecorator(MstTypes.safeReference)
export const union = createTypeDecorator(MstTypes.union)
export const optional = createTypeDecorator(MstTypes.optional)
export const literal = createTypeDecorator(MstTypes.literal)
export const maybe = createTypeDecorator(MstTypes.maybe)
export const maybeNull = createTypeDecorator(MstTypes.maybeNull)
export const refinement = createTypeDecorator(MstTypes.refinement)
export const string = createTypeDecorator(MstTypes.string)
export const boolean = createTypeDecorator(MstTypes.boolean)
export const number = createTypeDecorator(MstTypes.number)
export const integer = createTypeDecorator(MstTypes.integer)
export const date = createTypeDecorator(MstTypes.Date)
export const map = createTypeDecorator(MstTypes.map)
export const array = createTypeDecorator(MstTypes.array)
export const frozen = createTypeDecorator(MstTypes.frozen)
export const identifier = createTypeDecorator(MstTypes.identifier)
export const identifierNumber = createTypeDecorator(MstTypes.identifierNumber)
export const late = createTypeDecorator(MstTypes.late, getDef => () => {
const def = getDef()
return getMstType(def) || def
})
export const _undefined = createTypeDecorator(MstTypes.undefined)
export const _null = createTypeDecorator(MstTypes.null)
export const snapshotProcessor = createTypeDecorator(MstTypes.snapshotProcessor)
// alias
export const ref = reference
export const safeRef = safeReference
export const opt = optional
export const str = string
export const bool = boolean
export const num = number
export const int = integer
export const id = identifier
export const idNum = identifierNumber
export const undef = _undefined
export const nul = _null
export const snapProc = snapshotProcessor
// extra
export const jsonDate = custom({
name: 'JSONDate',
fromSnapshot: val => is.str(val) || is.int(val) ? new Date(val) : val,
toSnapshot: date => date.toJSON(),
isTargetType: date => date instanceof Date,
getValidationMessage: val => is.nul(val) || !is.def(val)
? "null or undefined is not a valid value for JSONDate"
: "",
})
export const types = {
enumeration, model: _model, compose, custom, reference, safeReference,
union, optional, literal, maybe, maybeNull, refinement,
string, boolean, number, integer, date, map, array, frozen,
identifier, identifierNumber, late, undefined: _undefined, null: _null,
snapshotProcessor,
ref, safeRef, opt, str, bool, num, int, id, idNum, undef, nul,
snapProc,
jsonDate,
}
export const setter = propertyDecorator((
target, prop, desc,
{
name = setterName(prop),
value: customValue,
clone,
keepEnvironment = false,
} = {},
) => {
target[name] = function (value) {
if (is.def(customValue)) {
value = is.fn(customValue)
? customValue.call(this, value)
: customValue
}
this[prop] = is.def(value) && clone
? mstClone(value, keepEnvironment)
: value
}
})
export function getMstType(type) {
return type && type[TypeKey]
}
function propertyTagger(key) {
return propertyDecorator((target, property, desc, ...args) => {
target[key] = target[key] || {}
target[key][property] = args
})
}
function createTypeDecorator(
type,
transformArg = transformArgToMst,
) {
return assignType(type, function decorator(...args) {
if (isPropertyDecorator(args)) {
return prop(this)(...args)
}
const decoratorType = is.fn(type)
? type(...args.map(transformArg))
: type
return assignType(decoratorType, decorator)
})
}
function transformArgToMst(arg) {
if (mstIsType(arg)) return arg
const mstType = getMstType(arg)
if (mstType) return mstType
return is.obj(arg)
? convertValuesToMst(arg)
: arg
}
function assignType(type, fn) {
type = {
[TypeKey]: type,
create: type.create && type.create.bind(type),
is: type.is && type.is.bind(type),
validate: type.validate && type.validate.bind(type),
instantiate: type.instantiate && type.instantiate.bind(type),
props: type.props && modelProps(type),
actions: type.actions && modelActions(type),
views: type.views && type.views.bind(type),
volatile: type.volatile && type.volatile.bind(type),
}
return Object.assign(fn.bind(type), type)
}
function modelProps(type) {
return pipe(
convertValuesToMst,
type.props,
)
}
function modelActions(type) {
return getActions => type.actions(store => {
const actions = getActions(store)
return rdMap(action => {
const isGen = is.gen(action)
action = action.bind(store)
return isGen ? mstFlow(action) : action
})(actions)
})
}
function convertValuesToMst(obj) {
return rdMap(val => getMstType(val) || val)(obj)
}
function viewBinder(descs) {
return obj => (
Object.entries(descs).reduce((fns, [key, desc]) => {
desc = descBind(obj, desc, 'get')
desc = descBind(obj, desc, 'set')
desc = descBind(obj, desc, 'value')
desc = {...desc, enumerable: true}
return Object.defineProperty(fns, key, desc)
}, {})
)
}
function descBind(obj, desc, fnName) {
const fn = desc[fnName]
if (!is.fn(fn)) return desc
return {...desc, [fnName]: fn.bind(obj)}
}
function tagKey(tag) {
return `__mst_decorators_${tag}`
}
export function setterName(prop, prefix = 'set') {
const Name = capitalize(prop)
return prefix + Name
}
function extractTaggedProps(Class, key) {
const proto = Class.prototype
const props = proto[key]
delete proto[key]
return props || {}
}