UNPKG

1.52 kBJavaScriptView Raw
1'use strict';
2
3Object.defineProperty(exports, '__esModule', { value: true });
4
5var vanilla = require('valtio/vanilla');
6var jotai = require('jotai');
7
8var isObject = function isObject(x) {
9 return typeof x === 'object' && x !== null;
10};
11
12var applyChanges = function applyChanges(proxyObject, prev, next) {
13 Object.getOwnPropertyNames(prev).forEach(function (key) {
14 if (!(key in next)) {
15 delete proxyObject[key];
16 } else if (Object.is(prev[key], next[key])) ; else if (isObject(proxyObject[key]) && isObject(prev[key]) && isObject(next[key])) {
17 applyChanges(proxyObject[key], prev[key], next[key]);
18 } else {
19 proxyObject[key] = next[key];
20 }
21 });
22 Object.keys(next).forEach(function (key) {
23 if (!(key in prev)) {
24 proxyObject[key] = next[key];
25 }
26 });
27};
28
29function atomWithProxy(proxyObject, options) {
30 var baseAtom = jotai.atom(vanilla.snapshot(proxyObject));
31
32 baseAtom.onMount = function (setValue) {
33 var callback = function callback() {
34 setValue(vanilla.snapshot(proxyObject));
35 };
36
37 var unsub = vanilla.subscribe(proxyObject, callback, options == null ? void 0 : options.sync);
38 callback();
39 return unsub;
40 };
41
42 var derivedAtom = jotai.atom(function (get) {
43 return get(baseAtom);
44 }, function (get, _set, update) {
45 var newValue = typeof update === 'function' ? update(get(baseAtom)) : update;
46 applyChanges(proxyObject, vanilla.snapshot(proxyObject), newValue);
47 });
48 return derivedAtom;
49}
50
51exports.atomWithProxy = atomWithProxy;