jotai
Version:
👻 Next gen state management that will spook you
55 lines (45 loc) • 1.99 kB
JavaScript
(function (global, factory) {
typeof exports === 'object' && typeof module !== 'undefined' ? factory(exports, require('valtio/vanilla'), require('jotai')) :
typeof define === 'function' && define.amd ? define(['exports', 'valtio/vanilla', 'jotai'], factory) :
(global = typeof globalThis !== 'undefined' ? globalThis : global || self, factory(global.jotaiValtio = {}, global.vanilla, global.jotai));
})(this, (function (exports, vanilla, jotai) { 'use strict';
var isObject = function isObject(x) {
return typeof x === 'object' && x !== null;
};
var applyChanges = function applyChanges(proxyObject, prev, next) {
Object.getOwnPropertyNames(prev).forEach(function (key) {
if (!(key in next)) {
delete proxyObject[key];
} else if (Object.is(prev[key], next[key])) ; 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(function (key) {
if (!(key in prev)) {
proxyObject[key] = next[key];
}
});
};
function atomWithProxy(proxyObject, options) {
var baseAtom = jotai.atom(vanilla.snapshot(proxyObject));
baseAtom.onMount = function (setValue) {
var callback = function callback() {
setValue(vanilla.snapshot(proxyObject));
};
var unsub = vanilla.subscribe(proxyObject, callback, options == null ? void 0 : options.sync);
callback();
return unsub;
};
var derivedAtom = jotai.atom(function (get) {
return get(baseAtom);
}, function (get, _set, update) {
var newValue = typeof update === 'function' ? update(get(baseAtom)) : update;
applyChanges(proxyObject, vanilla.snapshot(proxyObject), newValue);
});
return derivedAtom;
}
exports.atomWithProxy = atomWithProxy;
Object.defineProperty(exports, '__esModule', { value: true });
}));