Created
January 12, 2017 16:27
-
-
Save mattiamanzati/b4e6c469045d9bb5d67c2b01cabc1fbe to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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