UNPKG

2.54 kBJavaScriptView Raw
1System.register(['optics-ts', 'jotai'], (function (exports) {
2 'use strict';
3 var O, atom;
4 return {
5 setters: [function (module) {
6 O = module;
7 }, function (module) {
8 atom = module.atom;
9 }],
10 execute: (function () {
11
12 exports('focusAtom', focusAtom);
13
14 const getWeakCacheItem = (cache, deps) => {
15 do {
16 const [dep, ...rest] = deps;
17 const entry = cache.get(dep);
18 if (!entry) {
19 return;
20 }
21 if (!rest.length) {
22 return entry[1];
23 }
24 cache = entry[0];
25 deps = rest;
26 } while (deps.length);
27 };
28 const setWeakCacheItem = (cache, deps, item) => {
29 do {
30 const [dep, ...rest] = deps;
31 let entry = cache.get(dep);
32 if (!entry) {
33 entry = [ new WeakMap()];
34 cache.set(dep, entry);
35 }
36 if (!rest.length) {
37 entry[1] = item;
38 return;
39 }
40 cache = entry[0];
41 deps = rest;
42 } while (deps.length);
43 };
44 const createMemoizeAtom = () => {
45 const cache = /* @__PURE__ */ new WeakMap();
46 const memoizeAtom = (createAtom, deps) => {
47 const cachedAtom = getWeakCacheItem(cache, deps);
48 if (cachedAtom) {
49 return cachedAtom;
50 }
51 const createdAtom = createAtom();
52 setWeakCacheItem(cache, deps, createdAtom);
53 return createdAtom;
54 };
55 return memoizeAtom;
56 };
57
58 const memoizeAtom = createMemoizeAtom();
59 const isFunction = (x) => typeof x === "function";
60 function focusAtom(baseAtom, callback) {
61 return memoizeAtom(() => {
62 const focus = callback(O.optic());
63 const derivedAtom = atom((get) => getValueUsingOptic(focus, get(baseAtom)), (get, set, update) => {
64 const newValueProducer = isFunction(update) ? O.modify(focus)(update) : O.set(focus)(update);
65 return set(baseAtom, newValueProducer(get(baseAtom)));
66 });
67 return derivedAtom;
68 }, [baseAtom, callback]);
69 }
70 const getValueUsingOptic = (focus, bigValue) => {
71 if (focus._tag === "Traversal") {
72 const values = O.collect(focus)(bigValue);
73 return values;
74 }
75 if (focus._tag === "Prism") {
76 const value2 = O.preview(focus)(bigValue);
77 return value2;
78 }
79 const value = O.get(focus)(bigValue);
80 return value;
81 };
82
83 })
84 };
85}));