Navigation Menu

Skip to content

Instantly share code, notes, and snippets.

@chemitaxis
Forked from mattiamanzati/index.ts
Created May 9, 2018 10:02
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save chemitaxis/8a4bf06b168ea31077b0623cc4a0f64b to your computer and use it in GitHub Desktop.
Save chemitaxis/8a4bf06b168ea31077b0623cc4a0f64b 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