jotai-valtio
Version:
51 lines (50 loc) • 1.84 kB
JavaScript
;
Object.defineProperty(exports, "__esModule", { value: true });
exports.atomWithProxy = atomWithProxy;
const vanilla_1 = require("jotai/vanilla");
const vanilla_2 = require("valtio/vanilla");
const isObject = (x) => typeof x === 'object' && x !== null && !(x instanceof Promise);
const applyChanges = (proxyObject, prev, next) => {
Object.getOwnPropertyNames(prev).forEach((key) => {
if (!(key in next)) {
delete proxyObject[key];
}
else if (Object.is(prev[key], next[key])) {
// unchanged
}
else if (isObject(proxyObject[key]) &&
isObject(prev[key]) &&
isObject(next[key])) {
applyChanges(proxyObject[key], prev[key], next[key]);
}
else {
proxyObject[key] = next[key];
}
});
Object.keys(next).forEach((key) => {
if (!(key in prev)) {
proxyObject[key] = next[key];
}
});
};
function atomWithProxy(proxyObject, options) {
const baseAtom = (0, vanilla_1.atom)((0, vanilla_2.snapshot)(proxyObject));
if (process.env.NODE_ENV !== 'production') {
baseAtom.debugPrivate = true;
}
baseAtom.onMount = (setValue) => {
const callback = () => {
setValue((0, vanilla_2.snapshot)(proxyObject));
};
const unsub = (0, vanilla_2.subscribe)(proxyObject, callback, options === null || options === void 0 ? void 0 : options.sync);
callback();
return unsub;
};
const derivedAtom = (0, vanilla_1.atom)((get) => get(baseAtom), (get, _set, update) => {
const newValue = typeof update === 'function'
? update(get(baseAtom))
: update;
applyChanges(proxyObject, (0, vanilla_2.snapshot)(proxyObject), newValue);
});
return derivedAtom;
}