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