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