|
| 1 | +import MicrostateType from './microstate-type'; |
| 2 | +import { At, view, compose, Path } from './lens'; |
| 3 | +import { typeOf, valueOf, pathOf, link2, AtomOf } from './meta'; |
| 4 | +import { treemap } from './tree'; |
| 5 | +import create from './create'; |
| 6 | + |
| 7 | +class Id { |
| 8 | + static symbol = Symbol('@id'); |
| 9 | + static data = At(Id.symbol); |
| 10 | + static ref = compose(Id.data, At('ref')); |
| 11 | + static value = compose(Id.data, At('value')); |
| 12 | + static Type = compose(Id.data, At('Type')); |
| 13 | + |
| 14 | + constructor(Type, path, value, ref) { |
| 15 | + this.Type = Type; |
| 16 | + this.path = path; |
| 17 | + this.value = value; |
| 18 | + this.ref = ref; |
| 19 | + } |
| 20 | +} |
| 21 | + |
| 22 | +export default function Identity(microstate, fn) { |
| 23 | + |
| 24 | + let paths = identify(microstate, {}); |
| 25 | + |
| 26 | + return { get, transition }; |
| 27 | + |
| 28 | + function get() { |
| 29 | + return view(Id.ref, paths); |
| 30 | + } |
| 31 | + |
| 32 | + function transition(Type, name, path, args) { |
| 33 | + let atom = view(Id.value, paths); |
| 34 | + let Root = view(Id.Type, paths); |
| 35 | + let local = link2(create(Type), Type, path, atom, Root, []); |
| 36 | + let next = local[name](...args); |
| 37 | + return paths = identify(next, paths); |
| 38 | + } |
| 39 | + |
| 40 | + function identify(microstate, pathmap) { |
| 41 | + return treemap(node => { |
| 42 | + let path = pathOf(node); |
| 43 | + let id = view(compose(Path(path), Id.data), pathmap); |
| 44 | + if (id != null && id.Type === typeOf(node) && id.value === valueOf(node)) { |
| 45 | + return id; |
| 46 | + } else { |
| 47 | + return proxy(node, path); |
| 48 | + } |
| 49 | + }, microstate); |
| 50 | + |
| 51 | + function proxy(microstate, path) { |
| 52 | + let Type = typeOf(microstate); |
| 53 | + let Proxy = MicrostateType(Type, transitionFn, propertyFn); |
| 54 | + Proxy.name = `Id<${Type.name}>`; |
| 55 | + AtomOf.instance(Proxy, { atomOf: () => view(Id.value, paths) }); |
| 56 | + |
| 57 | + let value = valueOf(microstate); |
| 58 | + |
| 59 | + let ref = link2(new Proxy(value), Type, path, 'polymorphic', view(Id.Type, paths), []); |
| 60 | + |
| 61 | + return { |
| 62 | + [Id.symbol]: new Id(Type, path, value, ref) |
| 63 | + }; |
| 64 | + } |
| 65 | + } |
| 66 | + |
| 67 | + function transitionFn(object, Type, path, name, method, ...args) { |
| 68 | + return fn(Type, name, path, args); |
| 69 | + } |
| 70 | + |
| 71 | + function propertyFn(self, slot, key, path) { |
| 72 | + let location = compose(Path(path), Id.ref); |
| 73 | + return view(location, paths); |
| 74 | + } |
| 75 | +} |
0 commit comments