UNPKG

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