UNPKG

16 kBJavaScriptView Raw
1'use strict';
2
3Object.defineProperty(exports, '__esModule', { value: true });
4
5var react = require('react');
6var jotai = require('jotai');
7
8function useUpdateAtom(anAtom) {
9 var StoreContext = jotai.SECRET_INTERNAL_getStoreContext(anAtom.scope);
10
11 var _useContext = react.useContext(StoreContext),
12 updateAtom = _useContext[1];
13
14 var setAtom = react.useCallback(function (update) {
15 return updateAtom(anAtom, update);
16 }, [updateAtom, anAtom]);
17 return setAtom;
18}
19
20function useAtomValue(anAtom) {
21 return jotai.useAtom(anAtom)[0];
22}
23
24var RESET = Symbol();
25function atomWithReset(initialValue) {
26 var anAtom = jotai.atom(initialValue, function (get, set, update) {
27 if (update === RESET) {
28 set(anAtom, initialValue);
29 } else {
30 set(anAtom, typeof update === 'function' ? update(get(anAtom)) : update);
31 }
32 });
33 return anAtom;
34}
35
36function useResetAtom(anAtom) {
37 var StoreContext = jotai.SECRET_INTERNAL_getStoreContext(anAtom.scope);
38
39 var _useContext = react.useContext(StoreContext),
40 updateAtom = _useContext[1];
41
42 var setAtom = react.useCallback(function () {
43 return updateAtom(anAtom, RESET);
44 }, [updateAtom, anAtom]);
45 return setAtom;
46}
47
48function useReducerAtom(anAtom, reducer) {
49 var _useAtom = jotai.useAtom(anAtom),
50 state = _useAtom[0],
51 setState = _useAtom[1];
52
53 var dispatch = react.useCallback(function (action) {
54 setState(function (prev) {
55 return reducer(prev, action);
56 });
57 }, [setState, reducer]);
58 return [state, dispatch];
59}
60
61function atomWithReducer(initialValue, reducer) {
62 var anAtom = jotai.atom(initialValue, function (get, set, action) {
63 return set(anAtom, reducer(get(anAtom), action));
64 });
65 return anAtom;
66}
67
68function _extends() {
69 _extends = Object.assign || function (target) {
70 for (var i = 1; i < arguments.length; i++) {
71 var source = arguments[i];
72
73 for (var key in source) {
74 if (Object.prototype.hasOwnProperty.call(source, key)) {
75 target[key] = source[key];
76 }
77 }
78 }
79
80 return target;
81 };
82
83 return _extends.apply(this, arguments);
84}
85
86function _unsupportedIterableToArray(o, minLen) {
87 if (!o) return;
88 if (typeof o === "string") return _arrayLikeToArray(o, minLen);
89 var n = Object.prototype.toString.call(o).slice(8, -1);
90 if (n === "Object" && o.constructor) n = o.constructor.name;
91 if (n === "Map" || n === "Set") return Array.from(o);
92 if (n === "Arguments" || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)) return _arrayLikeToArray(o, minLen);
93}
94
95function _arrayLikeToArray(arr, len) {
96 if (len == null || len > arr.length) len = arr.length;
97
98 for (var i = 0, arr2 = new Array(len); i < len; i++) arr2[i] = arr[i];
99
100 return arr2;
101}
102
103function _createForOfIteratorHelperLoose(o, allowArrayLike) {
104 var it = typeof Symbol !== "undefined" && o[Symbol.iterator] || o["@@iterator"];
105 if (it) return (it = it.call(o)).next.bind(it);
106
107 if (Array.isArray(o) || (it = _unsupportedIterableToArray(o)) || allowArrayLike && o && typeof o.length === "number") {
108 if (it) o = it;
109 var i = 0;
110 return function () {
111 if (i >= o.length) return {
112 done: true
113 };
114 return {
115 done: false,
116 value: o[i++]
117 };
118 };
119 }
120
121 throw new TypeError("Invalid attempt to iterate non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.");
122}
123
124function atomFamily(initializeAtom, areEqual) {
125 var shouldRemove = null;
126 var atoms = new Map();
127
128 var createAtom = function createAtom(param) {
129 var item;
130
131 if (areEqual === undefined) {
132 item = atoms.get(param);
133 } else {
134 for (var _iterator = _createForOfIteratorHelperLoose(atoms), _step; !(_step = _iterator()).done;) {
135 var _step$value = _step.value,
136 key = _step$value[0],
137 value = _step$value[1];
138
139 if (areEqual(key, param)) {
140 item = value;
141 break;
142 }
143 }
144 }
145
146 if (item !== undefined) {
147 if (shouldRemove != null && shouldRemove(item[1], param)) {
148 atoms.delete(param);
149 } else {
150 return item[0];
151 }
152 }
153
154 var newAtom = initializeAtom(param);
155 atoms.set(param, [newAtom, Date.now()]);
156 return newAtom;
157 };
158
159 createAtom.remove = function (param) {
160 if (areEqual === undefined) {
161 atoms.delete(param);
162 } else {
163 for (var _iterator2 = _createForOfIteratorHelperLoose(atoms), _step2; !(_step2 = _iterator2()).done;) {
164 var _step2$value = _step2.value,
165 key = _step2$value[0];
166
167 if (areEqual(key, param)) {
168 atoms.delete(key);
169 break;
170 }
171 }
172 }
173 };
174
175 createAtom.setShouldRemove = function (fn) {
176 shouldRemove = fn;
177 if (!shouldRemove) return;
178
179 for (var _iterator3 = _createForOfIteratorHelperLoose(atoms), _step3; !(_step3 = _iterator3()).done;) {
180 var _step3$value = _step3.value,
181 key = _step3$value[0],
182 value = _step3$value[1];
183
184 if (shouldRemove(value[1], key)) {
185 atoms.delete(key);
186 }
187 }
188 };
189
190 return createAtom;
191}
192
193var getWeakCacheItem = function getWeakCacheItem(cache, deps) {
194 var dep = deps[0],
195 rest = deps.slice(1);
196 var entry = cache.get(dep);
197
198 if (!entry) {
199 return;
200 }
201
202 if (!rest.length) {
203 return entry[1];
204 }
205
206 return getWeakCacheItem(entry[0], rest);
207};
208var setWeakCacheItem = function setWeakCacheItem(cache, deps, item) {
209 var dep = deps[0],
210 rest = deps.slice(1);
211 var entry = cache.get(dep);
212
213 if (!entry) {
214 entry = [new WeakMap()];
215 cache.set(dep, entry);
216 }
217
218 if (!rest.length) {
219 entry[1] = item;
220 return;
221 }
222
223 setWeakCacheItem(entry[0], rest, item);
224};
225
226var selectAtomCache = new WeakMap();
227function selectAtom(anAtom, selector, equalityFn) {
228 if (equalityFn === void 0) {
229 equalityFn = Object.is;
230 }
231
232 var deps = [anAtom, selector, equalityFn];
233 var cachedAtom = getWeakCacheItem(selectAtomCache, deps);
234
235 if (cachedAtom) {
236 return cachedAtom;
237 }
238
239 var initialized = false;
240 var prevSlice;
241 var derivedAtom = jotai.atom(function (get) {
242 var slice = selector(get(anAtom));
243
244 if (initialized && equalityFn(prevSlice, slice)) {
245 return prevSlice;
246 }
247
248 initialized = true;
249 prevSlice = slice;
250 return slice;
251 });
252 derivedAtom.scope = anAtom.scope;
253 setWeakCacheItem(selectAtomCache, deps, derivedAtom);
254 return derivedAtom;
255}
256
257function useAtomCallback(callback, scope) {
258 var anAtom = react.useMemo(function () {
259 return jotai.atom(null, function (get, set, _ref) {
260 var arg = _ref[0],
261 resolve = _ref[1],
262 reject = _ref[2];
263
264 try {
265 resolve(callback(get, set, arg));
266 } catch (e) {
267 reject(e);
268 }
269 });
270 }, [callback]);
271 anAtom.scope = scope;
272
273 var _useAtom = jotai.useAtom(anAtom),
274 invoke = _useAtom[1];
275
276 return react.useCallback(function (arg) {
277 return new Promise(function (resolve, reject) {
278 invoke([arg, resolve, reject]);
279 });
280 }, [invoke]);
281}
282
283var freezeAtomCache = new WeakMap();
284
285var deepFreeze = function deepFreeze(obj) {
286 if (typeof obj !== 'object' || obj === null) return;
287 Object.freeze(obj);
288 var propNames = Object.getOwnPropertyNames(obj);
289
290 for (var _iterator = _createForOfIteratorHelperLoose(propNames), _step; !(_step = _iterator()).done;) {
291 var name = _step.value;
292 var value = obj[name];
293 deepFreeze(value);
294 }
295
296 return obj;
297};
298
299function freezeAtom(anAtom) {
300 var deps = [anAtom];
301 var cachedAtom = getWeakCacheItem(freezeAtomCache, deps);
302
303 if (cachedAtom) {
304 return cachedAtom;
305 }
306
307 var frozenAtom = jotai.atom(function (get) {
308 return deepFreeze(get(anAtom));
309 }, function (_get, set, arg) {
310 return set(anAtom, arg);
311 });
312 frozenAtom.scope = anAtom.scope;
313 setWeakCacheItem(freezeAtomCache, deps, frozenAtom);
314 return frozenAtom;
315}
316function freezeAtomCreator(createAtom) {
317 return function () {
318 var anAtom = createAtom.apply(void 0, arguments);
319 var origRead = anAtom.read;
320
321 anAtom.read = function (get) {
322 return deepFreeze(origRead(get));
323 };
324
325 return anAtom;
326 };
327}
328
329var splitAtomCache = new WeakMap();
330
331var isWritable = function isWritable(atom) {
332 return !!atom.write;
333};
334
335var isFunction = function isFunction(x) {
336 return typeof x === 'function';
337};
338
339function splitAtom(arrAtom, keyExtractor) {
340 var deps = keyExtractor ? [arrAtom, keyExtractor] : [arrAtom];
341 var cachedAtom = getWeakCacheItem(splitAtomCache, deps);
342
343 if (cachedAtom) {
344 return cachedAtom;
345 }
346
347 var currentAtomList;
348 var currentKeyList;
349
350 var keyToAtom = function keyToAtom(key) {
351 var _currentKeyList, _currentAtomList;
352
353 var index = (_currentKeyList = currentKeyList) == null ? void 0 : _currentKeyList.indexOf(key);
354
355 if (index === undefined || index === -1) {
356 return undefined;
357 }
358
359 return (_currentAtomList = currentAtomList) == null ? void 0 : _currentAtomList[index];
360 };
361
362 var read = function read(get) {
363 var nextAtomList = [];
364 var nextKeyList = [];
365 get(arrAtom).forEach(function (item, index) {
366 var key = keyExtractor ? keyExtractor(item) : index;
367 nextKeyList[index] = key;
368 var cachedAtom = keyToAtom(key);
369
370 if (cachedAtom) {
371 nextAtomList[index] = cachedAtom;
372 return;
373 }
374
375 var read = function read(get) {
376 var _currentKeyList2;
377
378 var index = (_currentKeyList2 = currentKeyList) == null ? void 0 : _currentKeyList2.indexOf(key);
379
380 if (index === undefined || index === -1) {
381 throw new Error('index not found');
382 }
383
384 return get(arrAtom)[index];
385 };
386
387 var write = function write(get, set, update) {
388 var _currentKeyList3;
389
390 var index = (_currentKeyList3 = currentKeyList) == null ? void 0 : _currentKeyList3.indexOf(key);
391
392 if (index === undefined || index === -1) {
393 throw new Error('index not found');
394 }
395
396 var prev = get(arrAtom);
397 var nextItem = isFunction(update) ? update(prev[index]) : update;
398 set(arrAtom, [].concat(prev.slice(0, index), [nextItem], prev.slice(index + 1)));
399 };
400
401 var itemAtom = isWritable(arrAtom) ? jotai.atom(read, write) : jotai.atom(read);
402 itemAtom.scope = arrAtom.scope;
403 nextAtomList[index] = itemAtom;
404 });
405 currentKeyList = nextKeyList;
406
407 if (currentAtomList && currentAtomList.length === nextAtomList.length && currentAtomList.every(function (x, i) {
408 return x === nextAtomList[i];
409 })) {
410 return currentAtomList;
411 }
412
413 return currentAtomList = nextAtomList;
414 };
415
416 var write = function write(get, set, atomToRemove) {
417 var index = get(splittedAtom).indexOf(atomToRemove);
418
419 if (index >= 0) {
420 var prev = get(arrAtom);
421 set(arrAtom, [].concat(prev.slice(0, index), prev.slice(index + 1)));
422 }
423 };
424
425 var splittedAtom = isWritable(arrAtom) ? jotai.atom(read, write) : jotai.atom(read);
426 splittedAtom.scope = arrAtom.scope;
427 setWeakCacheItem(splitAtomCache, deps, splittedAtom);
428 return splittedAtom;
429}
430
431function atomWithDefault(getDefault) {
432 var EMPTY = Symbol();
433 var overwrittenAtom = jotai.atom(EMPTY);
434 var anAtom = jotai.atom(function (get) {
435 var overwritten = get(overwrittenAtom);
436
437 if (overwritten !== EMPTY) {
438 return overwritten;
439 }
440
441 return getDefault(get);
442 }, function (get, set, update) {
443 return set(overwrittenAtom, typeof update === 'function' ? update(get(anAtom)) : update);
444 });
445 return anAtom;
446}
447
448var waitForAllCache = new WeakMap();
449function waitForAll(atoms) {
450 var cachedAtom = Array.isArray(atoms) && getWeakCacheItem(waitForAllCache, atoms);
451
452 if (cachedAtom) {
453 return cachedAtom;
454 }
455
456 var unwrappedAtoms = unwrapAtoms(atoms);
457 var derivedAtom = jotai.atom(function (get) {
458 var promises = [];
459 var values = unwrappedAtoms.map(function (anAtom, index) {
460 try {
461 return get(anAtom);
462 } catch (e) {
463 if (e instanceof Promise) {
464 promises[index] = e;
465 } else {
466 throw e;
467 }
468 }
469 });
470
471 if (promises.length) {
472 throw Promise.all(promises);
473 }
474
475 return wrapResults(atoms, values);
476 });
477 var waitForAllScope = unwrappedAtoms[0].scope;
478 derivedAtom.scope = waitForAllScope;
479 validateAtomScopes(waitForAllScope, unwrappedAtoms);
480
481 if (Array.isArray(atoms)) {
482 setWeakCacheItem(waitForAllCache, atoms, derivedAtom);
483 }
484
485 return derivedAtom;
486}
487
488var unwrapAtoms = function unwrapAtoms(atoms) {
489 return Array.isArray(atoms) ? atoms : Object.getOwnPropertyNames(atoms).map(function (key) {
490 return atoms[key];
491 });
492};
493
494var wrapResults = function wrapResults(atoms, results) {
495 return Array.isArray(atoms) ? results : Object.getOwnPropertyNames(atoms).reduce(function (out, key, idx) {
496 var _extends2;
497
498 return _extends({}, out, (_extends2 = {}, _extends2[key] = results[idx], _extends2));
499 }, {});
500};
501
502function validateAtomScopes(scope, atoms) {
503 if (scope && !atoms.every(function (a) {
504 return a.scope === scope;
505 })) {
506 console.warn('Different scopes were found for atoms supplied to waitForAll. This is unsupported and will result in unexpected behavior.');
507 }
508}
509
510function atomWithHash(key, initialValue, serialize, deserialize) {
511 if (serialize === void 0) {
512 serialize = JSON.stringify;
513 }
514
515 if (deserialize === void 0) {
516 deserialize = JSON.parse;
517 }
518
519 var anAtom = jotai.atom(initialValue, function (get, set, update) {
520 var newValue = typeof update === 'function' ? update(get(anAtom)) : update;
521 set(anAtom, newValue);
522 var searchParams = new URLSearchParams(location.hash.slice(1));
523 searchParams.set(key, serialize(newValue));
524 location.hash = searchParams.toString();
525 });
526
527 anAtom.onMount = function (setAtom) {
528 var callback = function callback() {
529 var searchParams = new URLSearchParams(location.hash.slice(1));
530 var str = searchParams.get(key);
531
532 if (str !== null) {
533 setAtom(deserialize(str));
534 }
535 };
536
537 window.addEventListener('hashchange', callback);
538 callback();
539 return function () {
540 window.removeEventListener('hashchange', callback);
541 };
542 };
543
544 return anAtom;
545}
546
547var defaultStorage = {
548 getItem: function getItem(key) {
549 var storedValue = localStorage.getItem(key);
550
551 if (storedValue === null) {
552 throw new Error('no value stored');
553 }
554
555 return JSON.parse(storedValue);
556 },
557 setItem: function setItem(key, newValue) {
558 localStorage.setItem(key, JSON.stringify(newValue));
559 }
560};
561function atomWithStorage(key, initialValue, storage) {
562 if (storage === void 0) {
563 storage = defaultStorage;
564 }
565
566 var getInitialValue = function getInitialValue() {
567 try {
568 return storage.getItem(key);
569 } catch (_unused) {
570 return initialValue;
571 }
572 };
573
574 var baseAtom = jotai.atom(initialValue);
575
576 baseAtom.onMount = function (setAtom) {
577 var value = getInitialValue();
578
579 if (value instanceof Promise) {
580 value.then(setAtom);
581 } else {
582 setAtom(value);
583 }
584 };
585
586 var anAtom = jotai.atom(function (get) {
587 return get(baseAtom);
588 }, function (get, set, update) {
589 var newValue = typeof update === 'function' ? update(get(baseAtom)) : update;
590 set(baseAtom, newValue);
591 storage.setItem(key, newValue);
592 });
593 return anAtom;
594}
595
596exports.RESET = RESET;
597exports.atomFamily = atomFamily;
598exports.atomWithDefault = atomWithDefault;
599exports.atomWithHash = atomWithHash;
600exports.atomWithReducer = atomWithReducer;
601exports.atomWithReset = atomWithReset;
602exports.atomWithStorage = atomWithStorage;
603exports.freezeAtom = freezeAtom;
604exports.freezeAtomCreator = freezeAtomCreator;
605exports.selectAtom = selectAtom;
606exports.splitAtom = splitAtom;
607exports.useAtomCallback = useAtomCallback;
608exports.useAtomValue = useAtomValue;
609exports.useReducerAtom = useReducerAtom;
610exports.useResetAtom = useResetAtom;
611exports.useUpdateAtom = useUpdateAtom;
612exports.waitForAll = waitForAll;