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