UNPKG

2.7 kBJavaScriptView Raw
1'use strict';
2
3var O = require('optics-ts');
4var jotai = require('jotai');
5
6function _interopNamespaceDefault(e) {
7 var n = Object.create(null);
8 if (e) {
9 Object.keys(e).forEach(function (k) {
10 if (k !== 'default') {
11 var d = Object.getOwnPropertyDescriptor(e, k);
12 Object.defineProperty(n, k, d.get ? d : {
13 enumerable: true,
14 get: function () { return e[k]; }
15 });
16 }
17 });
18 }
19 n.default = e;
20 return Object.freeze(n);
21}
22
23var O__namespace = /*#__PURE__*/_interopNamespaceDefault(O);
24
25var getWeakCacheItem = function getWeakCacheItem(cache, deps) {
26 do {
27 var _deps = deps,
28 dep = _deps[0],
29 rest = _deps.slice(1);
30 var entry = cache.get(dep);
31 if (!entry) {
32 return;
33 }
34 if (!rest.length) {
35 return entry[1];
36 }
37 cache = entry[0];
38 deps = rest;
39 } while (deps.length);
40};
41var setWeakCacheItem = function setWeakCacheItem(cache, deps, item) {
42 do {
43 var _deps2 = deps,
44 dep = _deps2[0],
45 rest = _deps2.slice(1);
46 var entry = cache.get(dep);
47 if (!entry) {
48 entry = [new WeakMap()];
49 cache.set(dep, entry);
50 }
51 if (!rest.length) {
52 entry[1] = item;
53 return;
54 }
55 cache = entry[0];
56 deps = rest;
57 } while (deps.length);
58};
59var createMemoizeAtom = function createMemoizeAtom() {
60 var cache = new WeakMap();
61 var memoizeAtom = function memoizeAtom(createAtom, deps) {
62 var cachedAtom = getWeakCacheItem(cache, deps);
63 if (cachedAtom) {
64 return cachedAtom;
65 }
66 var createdAtom = createAtom();
67 setWeakCacheItem(cache, deps, createdAtom);
68 return createdAtom;
69 };
70 return memoizeAtom;
71};
72
73var memoizeAtom = createMemoizeAtom();
74var isFunction = function isFunction(x) {
75 return typeof x === 'function';
76};
77function focusAtom(baseAtom, callback) {
78 return memoizeAtom(function () {
79 var focus = callback(O__namespace.optic());
80 var derivedAtom = jotai.atom(function (get) {
81 return getValueUsingOptic(focus, get(baseAtom));
82 }, function (get, set, update) {
83 var newValueProducer = isFunction(update) ? O__namespace.modify(focus)(update) : O__namespace.set(focus)(update);
84 return set(baseAtom, newValueProducer(get(baseAtom)));
85 });
86 return derivedAtom;
87 }, [baseAtom, callback]);
88}
89var getValueUsingOptic = function getValueUsingOptic(focus, bigValue) {
90 if (focus._tag === 'Traversal') {
91 var values = O__namespace.collect(focus)(bigValue);
92 return values;
93 }
94 if (focus._tag === 'Prism') {
95 var _value = O__namespace.preview(focus)(bigValue);
96 return _value;
97 }
98 var value = O__namespace.get(focus)(bigValue);
99 return value;
100};
101
102exports.focusAtom = focusAtom;