UNPKG

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