Skip to content

Instantly share code, notes, and snippets.

@mattiamanzati
Created January 12, 2017 16:27
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save mattiamanzati/b4e6c469045d9bb5d67c2b01cabc1fbe to your computer and use it in GitHub Desktop.
Save mattiamanzati/b4e6c469045d9bb5d67c2b01cabc1fbe to your computer and use it in GitHub Desktop.
import {createFactory, arrayOf, onPatch, getSnapshot, applySnapshot, onSnapshot, applyPatches, IModelFactory, unionOf, primitiveFactory} from 'mobx-state-tree'
const Patch = createFactory({
op: '',
path: '',
value: ''
})
function createForm(Factory){
const F = createFactory({
value: Factory,
binding: Factory,
patches: arrayOf(Patch)
})
return (state?, env?) => {
const instance = F()
let inRestore = false
const getValueSnapshot = () =>
getSnapshot(instance.value === null ? Factory() : instance.value )
instance.value = !!state && !!state.value ? Factory(state.value) : Factory()
instance.binding = Factory(getValueSnapshot())
const runInRestore = fn => (...args) => {
if(inRestore) return
inRestore = true
const value = fn(...args)
inRestore = false
return value
}
onPatch(instance.binding, runInRestore(patch => {
instance.patches.push(Patch(patch))
}))
onSnapshot(instance, runInRestore(snapshot => {
const newInstance = Factory(getValueSnapshot())
applyPatches(newInstance, instance.patches.slice() as any[])
applySnapshot(instance.binding, getSnapshot(newInstance))
}))
return instance
}
}
const User = createFactory({
name: '',
password: ''
})
const UserForm = createForm(User)
const form = UserForm()
form.binding.password = 'mattia'
form.value = User({name: 'michel'})
console.log(getSnapshot(form), getSnapshot(form.binding))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment