ae2f1481 |
import { Map, fromJS } from 'immutable';
|
ee0444ba |
let Symbol = (window['Symbol'] !== undefined) ? window['Symbol'] : x => `_Symbol__${x}`;
export const fireListeners = Symbol('fireListeners');
const noOpTransform = val => val;
export function lensTransformer(
lens,
getTransform = noOpTransform,
setTransform = noOpTransform
) {
return {
get: () => getTransform(lens.get()),
set: (val) => lens.set(setTransform(val)),
withValue(cb) {
return cb(this.get());
},
};
}
export function makeLens(key, self) {
const createLens = (keyPath) => {
return {
get() {
|
7524a4a6 |
let result = self._currentState.getIn(keyPath);
|
ee0444ba |
if (result && result.toJS !== undefined) {
result = result.toJS();
}
return result;
},
set(val) {
|
7524a4a6 |
const oldState = self._currentState;
|
ee0444ba |
|
7524a4a6 |
if (self._currentState.getIn(keyPath) === undefined) {
|
ee0444ba |
for (let x = 0; x < keyPath.length; x++) {
const subPath = keyPath.slice(0, x);
|
7524a4a6 |
if (self._currentState.getIn(subPath) === undefined && self._currentState.hasIn(subPath)) {
self._currentState = self._currentState.setIn(subPath, Map());
|
ee0444ba |
}
}
}
|
7524a4a6 |
self._currentState = self._currentState.setIn(keyPath, fromJS(val));
self[fireListeners](oldState, self._currentState);
|
ee0444ba |
},
lensFor(key) {
let subPath = key instanceof Array ? key : [key];
return createLens([...keyPath, ...subPath]);
},
|
7524a4a6 |
withValue(cb, ...rest) {
return cb(this.get(), ...rest);
|
ee0444ba |
},
swap(cb) {
this.set(cb(this.get()));
return this.get();
}
};
};
return createLens(key instanceof Array ? key : [key]);
|
ae2f1481 |
}
|