UNPKG

1.87 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(
22 proxyObject[key],
23 prev[key],
24 next[key]
25 );
26 } else {
27 proxyObject[key] = next[key];
28 }
29 });
30 Object.keys(next).forEach((key) => {
31 if (!(key in prev)) {
32 proxyObject[key] = next[key];
33 }
34 });
35 };
36 function atomWithProxy(proxyObject, options) {
37 const baseAtom = atom(snapshot(proxyObject));
38 baseAtom.onMount = (setValue) => {
39 const callback = () => {
40 setValue(snapshot(proxyObject));
41 };
42 const unsub = subscribe(proxyObject, callback, options == null ? void 0 : options.sync);
43 callback();
44 return unsub;
45 };
46 const derivedAtom = atom(
47 (get) => get(baseAtom),
48 (get, _set, update) => {
49 const newValue = typeof update === "function" ? update(get(baseAtom)) : update;
50 applyChanges(proxyObject, snapshot(proxyObject), newValue);
51 }
52 );
53 return derivedAtom;
54 }
55
56 })
57 };
58}));