1 | 'use strict';
|
2 |
|
3 | Object.defineProperty(exports, '__esModule', { value: true });
|
4 |
|
5 | var immer = require('immer');
|
6 | var jotai = require('jotai');
|
7 | var react = require('react');
|
8 |
|
9 | function atomWithImmer(initialValue) {
|
10 | var anAtom = jotai.atom(initialValue, function (get, set, fn) {
|
11 | return set(anAtom, immer.produce(get(anAtom), typeof fn === 'function' ? fn : function () {
|
12 | return fn;
|
13 | }));
|
14 | });
|
15 | return anAtom;
|
16 | }
|
17 |
|
18 | function useImmerAtom(anAtom, scope) {
|
19 | var _useAtom = jotai.useAtom(anAtom, scope),
|
20 | state = _useAtom[0],
|
21 | setState = _useAtom[1];
|
22 |
|
23 | var setStateWithImmer = react.useCallback(function (fn) {
|
24 | return setState(immer.produce(fn));
|
25 | }, [setState]);
|
26 | return [state, setStateWithImmer];
|
27 | }
|
28 |
|
29 | var getWeakCacheItem = function getWeakCacheItem(cache, deps) {
|
30 | do {
|
31 | var _deps = deps,
|
32 | dep = _deps[0],
|
33 | rest = _deps.slice(1);
|
34 |
|
35 | var entry = cache.get(dep);
|
36 |
|
37 | if (!entry) {
|
38 | return;
|
39 | }
|
40 |
|
41 | if (!rest.length) {
|
42 | return entry[1];
|
43 | }
|
44 |
|
45 | cache = entry[0];
|
46 | deps = rest;
|
47 | } while (deps.length);
|
48 | };
|
49 |
|
50 | var setWeakCacheItem = function setWeakCacheItem(cache, deps, item) {
|
51 | do {
|
52 | var _deps2 = deps,
|
53 | dep = _deps2[0],
|
54 | rest = _deps2.slice(1);
|
55 |
|
56 | var entry = cache.get(dep);
|
57 |
|
58 | if (!entry) {
|
59 | entry = [new WeakMap()];
|
60 | cache.set(dep, entry);
|
61 | }
|
62 |
|
63 | if (!rest.length) {
|
64 | entry[1] = item;
|
65 | return;
|
66 | }
|
67 |
|
68 | cache = entry[0];
|
69 | deps = rest;
|
70 | } while (deps.length);
|
71 | };
|
72 |
|
73 | var createMemoizeAtom = function createMemoizeAtom() {
|
74 | var cache = new WeakMap();
|
75 |
|
76 | var memoizeAtom = function memoizeAtom(createAtom, deps) {
|
77 | var cachedAtom = getWeakCacheItem(cache, deps);
|
78 |
|
79 | if (cachedAtom) {
|
80 | return cachedAtom;
|
81 | }
|
82 |
|
83 | var createdAtom = createAtom();
|
84 | setWeakCacheItem(cache, deps, createdAtom);
|
85 | return createdAtom;
|
86 | };
|
87 |
|
88 | return memoizeAtom;
|
89 | };
|
90 |
|
91 | var memoizeAtom = createMemoizeAtom();
|
92 | function withImmer(anAtom) {
|
93 | return memoizeAtom(function () {
|
94 | var derivedAtom = jotai.atom(function (get) {
|
95 | return get(anAtom);
|
96 | }, function (get, set, fn) {
|
97 | return set(anAtom, immer.produce(get(anAtom), typeof fn === 'function' ? fn : function () {
|
98 | return fn;
|
99 | }));
|
100 | });
|
101 | return derivedAtom;
|
102 | }, [anAtom]);
|
103 | }
|
104 |
|
105 | exports.atomWithImmer = atomWithImmer;
|
106 | exports.useImmerAtom = useImmerAtom;
|
107 | exports.withImmer = withImmer;
|