UNPKG

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