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