UNPKG

42.4 kBJavaScriptView Raw
1'use strict';
2
3Object.defineProperty(exports, '__esModule', { value: true });
4
5var jotai = require('jotai');
6var react = require('react');
7
8var RESET = Symbol();
9
10function atomWithReset(initialValue) {
11 var anAtom = jotai.atom(initialValue, function (get, set, update) {
12 var nextValue = typeof update === 'function' ? update(get(anAtom)) : update;
13 set(anAtom, nextValue === RESET ? initialValue : nextValue);
14 });
15 return anAtom;
16}
17
18function _regeneratorRuntime() {
19 /*! regenerator-runtime -- Copyright (c) 2014-present, Facebook, Inc. -- license (MIT): https://github.com/facebook/regenerator/blob/main/LICENSE */
20
21 _regeneratorRuntime = function () {
22 return exports;
23 };
24
25 var exports = {},
26 Op = Object.prototype,
27 hasOwn = Op.hasOwnProperty,
28 $Symbol = "function" == typeof Symbol ? Symbol : {},
29 iteratorSymbol = $Symbol.iterator || "@@iterator",
30 asyncIteratorSymbol = $Symbol.asyncIterator || "@@asyncIterator",
31 toStringTagSymbol = $Symbol.toStringTag || "@@toStringTag";
32
33 function define(obj, key, value) {
34 return Object.defineProperty(obj, key, {
35 value: value,
36 enumerable: !0,
37 configurable: !0,
38 writable: !0
39 }), obj[key];
40 }
41
42 try {
43 define({}, "");
44 } catch (err) {
45 define = function (obj, key, value) {
46 return obj[key] = value;
47 };
48 }
49
50 function wrap(innerFn, outerFn, self, tryLocsList) {
51 var protoGenerator = outerFn && outerFn.prototype instanceof Generator ? outerFn : Generator,
52 generator = Object.create(protoGenerator.prototype),
53 context = new Context(tryLocsList || []);
54 return generator._invoke = function (innerFn, self, context) {
55 var state = "suspendedStart";
56 return function (method, arg) {
57 if ("executing" === state) throw new Error("Generator is already running");
58
59 if ("completed" === state) {
60 if ("throw" === method) throw arg;
61 return doneResult();
62 }
63
64 for (context.method = method, context.arg = arg;;) {
65 var delegate = context.delegate;
66
67 if (delegate) {
68 var delegateResult = maybeInvokeDelegate(delegate, context);
69
70 if (delegateResult) {
71 if (delegateResult === ContinueSentinel) continue;
72 return delegateResult;
73 }
74 }
75
76 if ("next" === context.method) context.sent = context._sent = context.arg;else if ("throw" === context.method) {
77 if ("suspendedStart" === state) throw state = "completed", context.arg;
78 context.dispatchException(context.arg);
79 } else "return" === context.method && context.abrupt("return", context.arg);
80 state = "executing";
81 var record = tryCatch(innerFn, self, context);
82
83 if ("normal" === record.type) {
84 if (state = context.done ? "completed" : "suspendedYield", record.arg === ContinueSentinel) continue;
85 return {
86 value: record.arg,
87 done: context.done
88 };
89 }
90
91 "throw" === record.type && (state = "completed", context.method = "throw", context.arg = record.arg);
92 }
93 };
94 }(innerFn, self, context), generator;
95 }
96
97 function tryCatch(fn, obj, arg) {
98 try {
99 return {
100 type: "normal",
101 arg: fn.call(obj, arg)
102 };
103 } catch (err) {
104 return {
105 type: "throw",
106 arg: err
107 };
108 }
109 }
110
111 exports.wrap = wrap;
112 var ContinueSentinel = {};
113
114 function Generator() {}
115
116 function GeneratorFunction() {}
117
118 function GeneratorFunctionPrototype() {}
119
120 var IteratorPrototype = {};
121 define(IteratorPrototype, iteratorSymbol, function () {
122 return this;
123 });
124 var getProto = Object.getPrototypeOf,
125 NativeIteratorPrototype = getProto && getProto(getProto(values([])));
126 NativeIteratorPrototype && NativeIteratorPrototype !== Op && hasOwn.call(NativeIteratorPrototype, iteratorSymbol) && (IteratorPrototype = NativeIteratorPrototype);
127 var Gp = GeneratorFunctionPrototype.prototype = Generator.prototype = Object.create(IteratorPrototype);
128
129 function defineIteratorMethods(prototype) {
130 ["next", "throw", "return"].forEach(function (method) {
131 define(prototype, method, function (arg) {
132 return this._invoke(method, arg);
133 });
134 });
135 }
136
137 function AsyncIterator(generator, PromiseImpl) {
138 function invoke(method, arg, resolve, reject) {
139 var record = tryCatch(generator[method], generator, arg);
140
141 if ("throw" !== record.type) {
142 var result = record.arg,
143 value = result.value;
144 return value && "object" == typeof value && hasOwn.call(value, "__await") ? PromiseImpl.resolve(value.__await).then(function (value) {
145 invoke("next", value, resolve, reject);
146 }, function (err) {
147 invoke("throw", err, resolve, reject);
148 }) : PromiseImpl.resolve(value).then(function (unwrapped) {
149 result.value = unwrapped, resolve(result);
150 }, function (error) {
151 return invoke("throw", error, resolve, reject);
152 });
153 }
154
155 reject(record.arg);
156 }
157
158 var previousPromise;
159
160 this._invoke = function (method, arg) {
161 function callInvokeWithMethodAndArg() {
162 return new PromiseImpl(function (resolve, reject) {
163 invoke(method, arg, resolve, reject);
164 });
165 }
166
167 return previousPromise = previousPromise ? previousPromise.then(callInvokeWithMethodAndArg, callInvokeWithMethodAndArg) : callInvokeWithMethodAndArg();
168 };
169 }
170
171 function maybeInvokeDelegate(delegate, context) {
172 var method = delegate.iterator[context.method];
173
174 if (undefined === method) {
175 if (context.delegate = null, "throw" === context.method) {
176 if (delegate.iterator.return && (context.method = "return", context.arg = undefined, maybeInvokeDelegate(delegate, context), "throw" === context.method)) return ContinueSentinel;
177 context.method = "throw", context.arg = new TypeError("The iterator does not provide a 'throw' method");
178 }
179
180 return ContinueSentinel;
181 }
182
183 var record = tryCatch(method, delegate.iterator, context.arg);
184 if ("throw" === record.type) return context.method = "throw", context.arg = record.arg, context.delegate = null, ContinueSentinel;
185 var info = record.arg;
186 return info ? info.done ? (context[delegate.resultName] = info.value, context.next = delegate.nextLoc, "return" !== context.method && (context.method = "next", context.arg = undefined), context.delegate = null, ContinueSentinel) : info : (context.method = "throw", context.arg = new TypeError("iterator result is not an object"), context.delegate = null, ContinueSentinel);
187 }
188
189 function pushTryEntry(locs) {
190 var entry = {
191 tryLoc: locs[0]
192 };
193 1 in locs && (entry.catchLoc = locs[1]), 2 in locs && (entry.finallyLoc = locs[2], entry.afterLoc = locs[3]), this.tryEntries.push(entry);
194 }
195
196 function resetTryEntry(entry) {
197 var record = entry.completion || {};
198 record.type = "normal", delete record.arg, entry.completion = record;
199 }
200
201 function Context(tryLocsList) {
202 this.tryEntries = [{
203 tryLoc: "root"
204 }], tryLocsList.forEach(pushTryEntry, this), this.reset(!0);
205 }
206
207 function values(iterable) {
208 if (iterable) {
209 var iteratorMethod = iterable[iteratorSymbol];
210 if (iteratorMethod) return iteratorMethod.call(iterable);
211 if ("function" == typeof iterable.next) return iterable;
212
213 if (!isNaN(iterable.length)) {
214 var i = -1,
215 next = function next() {
216 for (; ++i < iterable.length;) if (hasOwn.call(iterable, i)) return next.value = iterable[i], next.done = !1, next;
217
218 return next.value = undefined, next.done = !0, next;
219 };
220
221 return next.next = next;
222 }
223 }
224
225 return {
226 next: doneResult
227 };
228 }
229
230 function doneResult() {
231 return {
232 value: undefined,
233 done: !0
234 };
235 }
236
237 return GeneratorFunction.prototype = GeneratorFunctionPrototype, define(Gp, "constructor", GeneratorFunctionPrototype), define(GeneratorFunctionPrototype, "constructor", GeneratorFunction), GeneratorFunction.displayName = define(GeneratorFunctionPrototype, toStringTagSymbol, "GeneratorFunction"), exports.isGeneratorFunction = function (genFun) {
238 var ctor = "function" == typeof genFun && genFun.constructor;
239 return !!ctor && (ctor === GeneratorFunction || "GeneratorFunction" === (ctor.displayName || ctor.name));
240 }, exports.mark = function (genFun) {
241 return Object.setPrototypeOf ? Object.setPrototypeOf(genFun, GeneratorFunctionPrototype) : (genFun.__proto__ = GeneratorFunctionPrototype, define(genFun, toStringTagSymbol, "GeneratorFunction")), genFun.prototype = Object.create(Gp), genFun;
242 }, exports.awrap = function (arg) {
243 return {
244 __await: arg
245 };
246 }, defineIteratorMethods(AsyncIterator.prototype), define(AsyncIterator.prototype, asyncIteratorSymbol, function () {
247 return this;
248 }), exports.AsyncIterator = AsyncIterator, exports.async = function (innerFn, outerFn, self, tryLocsList, PromiseImpl) {
249 void 0 === PromiseImpl && (PromiseImpl = Promise);
250 var iter = new AsyncIterator(wrap(innerFn, outerFn, self, tryLocsList), PromiseImpl);
251 return exports.isGeneratorFunction(outerFn) ? iter : iter.next().then(function (result) {
252 return result.done ? result.value : iter.next();
253 });
254 }, defineIteratorMethods(Gp), define(Gp, toStringTagSymbol, "Generator"), define(Gp, iteratorSymbol, function () {
255 return this;
256 }), define(Gp, "toString", function () {
257 return "[object Generator]";
258 }), exports.keys = function (object) {
259 var keys = [];
260
261 for (var key in object) keys.push(key);
262
263 return keys.reverse(), function next() {
264 for (; keys.length;) {
265 var key = keys.pop();
266 if (key in object) return next.value = key, next.done = !1, next;
267 }
268
269 return next.done = !0, next;
270 };
271 }, exports.values = values, Context.prototype = {
272 constructor: Context,
273 reset: function (skipTempReset) {
274 if (this.prev = 0, this.next = 0, this.sent = this._sent = undefined, this.done = !1, this.delegate = null, this.method = "next", this.arg = undefined, this.tryEntries.forEach(resetTryEntry), !skipTempReset) for (var name in this) "t" === name.charAt(0) && hasOwn.call(this, name) && !isNaN(+name.slice(1)) && (this[name] = undefined);
275 },
276 stop: function () {
277 this.done = !0;
278 var rootRecord = this.tryEntries[0].completion;
279 if ("throw" === rootRecord.type) throw rootRecord.arg;
280 return this.rval;
281 },
282 dispatchException: function (exception) {
283 if (this.done) throw exception;
284 var context = this;
285
286 function handle(loc, caught) {
287 return record.type = "throw", record.arg = exception, context.next = loc, caught && (context.method = "next", context.arg = undefined), !!caught;
288 }
289
290 for (var i = this.tryEntries.length - 1; i >= 0; --i) {
291 var entry = this.tryEntries[i],
292 record = entry.completion;
293 if ("root" === entry.tryLoc) return handle("end");
294
295 if (entry.tryLoc <= this.prev) {
296 var hasCatch = hasOwn.call(entry, "catchLoc"),
297 hasFinally = hasOwn.call(entry, "finallyLoc");
298
299 if (hasCatch && hasFinally) {
300 if (this.prev < entry.catchLoc) return handle(entry.catchLoc, !0);
301 if (this.prev < entry.finallyLoc) return handle(entry.finallyLoc);
302 } else if (hasCatch) {
303 if (this.prev < entry.catchLoc) return handle(entry.catchLoc, !0);
304 } else {
305 if (!hasFinally) throw new Error("try statement without catch or finally");
306 if (this.prev < entry.finallyLoc) return handle(entry.finallyLoc);
307 }
308 }
309 }
310 },
311 abrupt: function (type, arg) {
312 for (var i = this.tryEntries.length - 1; i >= 0; --i) {
313 var entry = this.tryEntries[i];
314
315 if (entry.tryLoc <= this.prev && hasOwn.call(entry, "finallyLoc") && this.prev < entry.finallyLoc) {
316 var finallyEntry = entry;
317 break;
318 }
319 }
320
321 finallyEntry && ("break" === type || "continue" === type) && finallyEntry.tryLoc <= arg && arg <= finallyEntry.finallyLoc && (finallyEntry = null);
322 var record = finallyEntry ? finallyEntry.completion : {};
323 return record.type = type, record.arg = arg, finallyEntry ? (this.method = "next", this.next = finallyEntry.finallyLoc, ContinueSentinel) : this.complete(record);
324 },
325 complete: function (record, afterLoc) {
326 if ("throw" === record.type) throw record.arg;
327 return "break" === record.type || "continue" === record.type ? this.next = record.arg : "return" === record.type ? (this.rval = this.arg = record.arg, this.method = "return", this.next = "end") : "normal" === record.type && afterLoc && (this.next = afterLoc), ContinueSentinel;
328 },
329 finish: function (finallyLoc) {
330 for (var i = this.tryEntries.length - 1; i >= 0; --i) {
331 var entry = this.tryEntries[i];
332 if (entry.finallyLoc === finallyLoc) return this.complete(entry.completion, entry.afterLoc), resetTryEntry(entry), ContinueSentinel;
333 }
334 },
335 catch: function (tryLoc) {
336 for (var i = this.tryEntries.length - 1; i >= 0; --i) {
337 var entry = this.tryEntries[i];
338
339 if (entry.tryLoc === tryLoc) {
340 var record = entry.completion;
341
342 if ("throw" === record.type) {
343 var thrown = record.arg;
344 resetTryEntry(entry);
345 }
346
347 return thrown;
348 }
349 }
350
351 throw new Error("illegal catch attempt");
352 },
353 delegateYield: function (iterable, resultName, nextLoc) {
354 return this.delegate = {
355 iterator: values(iterable),
356 resultName: resultName,
357 nextLoc: nextLoc
358 }, "next" === this.method && (this.arg = undefined), ContinueSentinel;
359 }
360 }, exports;
361}
362
363function asyncGeneratorStep(gen, resolve, reject, _next, _throw, key, arg) {
364 try {
365 var info = gen[key](arg);
366 var value = info.value;
367 } catch (error) {
368 reject(error);
369 return;
370 }
371
372 if (info.done) {
373 resolve(value);
374 } else {
375 Promise.resolve(value).then(_next, _throw);
376 }
377}
378
379function _asyncToGenerator(fn) {
380 return function () {
381 var self = this,
382 args = arguments;
383 return new Promise(function (resolve, reject) {
384 var gen = fn.apply(self, args);
385
386 function _next(value) {
387 asyncGeneratorStep(gen, resolve, reject, _next, _throw, "next", value);
388 }
389
390 function _throw(err) {
391 asyncGeneratorStep(gen, resolve, reject, _next, _throw, "throw", err);
392 }
393
394 _next(undefined);
395 });
396 };
397}
398
399function _extends() {
400 _extends = Object.assign ? Object.assign.bind() : function (target) {
401 for (var i = 1; i < arguments.length; i++) {
402 var source = arguments[i];
403
404 for (var key in source) {
405 if (Object.prototype.hasOwnProperty.call(source, key)) {
406 target[key] = source[key];
407 }
408 }
409 }
410
411 return target;
412 };
413 return _extends.apply(this, arguments);
414}
415
416function _unsupportedIterableToArray(o, minLen) {
417 if (!o) return;
418 if (typeof o === "string") return _arrayLikeToArray(o, minLen);
419 var n = Object.prototype.toString.call(o).slice(8, -1);
420 if (n === "Object" && o.constructor) n = o.constructor.name;
421 if (n === "Map" || n === "Set") return Array.from(o);
422 if (n === "Arguments" || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)) return _arrayLikeToArray(o, minLen);
423}
424
425function _arrayLikeToArray(arr, len) {
426 if (len == null || len > arr.length) len = arr.length;
427
428 for (var i = 0, arr2 = new Array(len); i < len; i++) arr2[i] = arr[i];
429
430 return arr2;
431}
432
433function _createForOfIteratorHelperLoose(o, allowArrayLike) {
434 var it = typeof Symbol !== "undefined" && o[Symbol.iterator] || o["@@iterator"];
435 if (it) return (it = it.call(o)).next.bind(it);
436
437 if (Array.isArray(o) || (it = _unsupportedIterableToArray(o)) || allowArrayLike && o && typeof o.length === "number") {
438 if (it) o = it;
439 var i = 0;
440 return function () {
441 if (i >= o.length) return {
442 done: true
443 };
444 return {
445 done: false,
446 value: o[i++]
447 };
448 };
449 }
450
451 throw new TypeError("Invalid attempt to iterate non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.");
452}
453
454var WRITE_ATOM = 'w';
455var RESTORE_ATOMS = 'h';
456
457function useResetAtom(anAtom, scope) {
458 var ScopeContext = jotai.SECRET_INTERNAL_getScopeContext(scope);
459 var store = react.useContext(ScopeContext).s;
460 var setAtom = react.useCallback(function () {
461 return store[WRITE_ATOM](anAtom, RESET);
462 }, [store, anAtom]);
463 return setAtom;
464}
465
466function useReducerAtom(anAtom, reducer, scope) {
467 var _useAtom = jotai.useAtom(anAtom, scope),
468 state = _useAtom[0],
469 setState = _useAtom[1];
470
471 var dispatch = react.useCallback(function (action) {
472 setState(function (prev) {
473 return reducer(prev, action);
474 });
475 }, [setState, reducer]);
476 return [state, dispatch];
477}
478
479function atomWithReducer(initialValue, reducer) {
480 var anAtom = jotai.atom(initialValue, function (get, set, action) {
481 return set(anAtom, reducer(get(anAtom), action));
482 });
483 return anAtom;
484}
485
486function atomFamily(initializeAtom, areEqual) {
487 var shouldRemove = null;
488 var atoms = new Map();
489
490 var createAtom = function createAtom(param) {
491 var item;
492
493 if (areEqual === undefined) {
494 item = atoms.get(param);
495 } else {
496 for (var _iterator = _createForOfIteratorHelperLoose(atoms), _step; !(_step = _iterator()).done;) {
497 var _step$value = _step.value,
498 key = _step$value[0],
499 value = _step$value[1];
500
501 if (areEqual(key, param)) {
502 item = value;
503 break;
504 }
505 }
506 }
507
508 if (item !== undefined) {
509 if (shouldRemove != null && shouldRemove(item[1], param)) {
510 createAtom.remove(param);
511 } else {
512 return item[0];
513 }
514 }
515
516 var newAtom = initializeAtom(param);
517 atoms.set(param, [newAtom, Date.now()]);
518 return newAtom;
519 };
520
521 createAtom.remove = function (param) {
522 if (areEqual === undefined) {
523 atoms.delete(param);
524 } else {
525 for (var _iterator2 = _createForOfIteratorHelperLoose(atoms), _step2; !(_step2 = _iterator2()).done;) {
526 var _step2$value = _step2.value,
527 key = _step2$value[0];
528
529 if (areEqual(key, param)) {
530 atoms.delete(key);
531 break;
532 }
533 }
534 }
535 };
536
537 createAtom.setShouldRemove = function (fn) {
538 shouldRemove = fn;
539 if (!shouldRemove) return;
540
541 for (var _iterator3 = _createForOfIteratorHelperLoose(atoms), _step3; !(_step3 = _iterator3()).done;) {
542 var _step3$value = _step3.value,
543 key = _step3$value[0],
544 value = _step3$value[1];
545
546 if (shouldRemove(value[1], key)) {
547 atoms.delete(key);
548 }
549 }
550 };
551
552 return createAtom;
553}
554
555var getWeakCacheItem = function getWeakCacheItem(cache, deps) {
556 do {
557 var _deps = deps,
558 dep = _deps[0],
559 rest = _deps.slice(1);
560
561 var entry = cache.get(dep);
562
563 if (!entry) {
564 return;
565 }
566
567 if (!rest.length) {
568 return entry[1];
569 }
570
571 cache = entry[0];
572 deps = rest;
573 } while (deps.length);
574};
575
576var setWeakCacheItem = function setWeakCacheItem(cache, deps, item) {
577 do {
578 var _deps2 = deps,
579 dep = _deps2[0],
580 rest = _deps2.slice(1);
581
582 var entry = cache.get(dep);
583
584 if (!entry) {
585 entry = [new WeakMap()];
586 cache.set(dep, entry);
587 }
588
589 if (!rest.length) {
590 entry[1] = item;
591 return;
592 }
593
594 cache = entry[0];
595 deps = rest;
596 } while (deps.length);
597};
598
599var createMemoizeAtom = function createMemoizeAtom() {
600 var cache = new WeakMap();
601
602 var memoizeAtom = function memoizeAtom(createAtom, deps) {
603 var cachedAtom = getWeakCacheItem(cache, deps);
604
605 if (cachedAtom) {
606 return cachedAtom;
607 }
608
609 var createdAtom = createAtom();
610 setWeakCacheItem(cache, deps, createdAtom);
611 return createdAtom;
612 };
613
614 return memoizeAtom;
615};
616
617var memoizeAtom$4 = createMemoizeAtom();
618function selectAtom(anAtom, selector, equalityFn) {
619 if (equalityFn === void 0) {
620 equalityFn = Object.is;
621 }
622
623 return memoizeAtom$4(function () {
624 var refAtom = jotai.atom(function () {
625 return {};
626 });
627 var derivedAtom = jotai.atom(function (get) {
628 var slice = selector(get(anAtom));
629 var ref = get(refAtom);
630
631 if ('prev' in ref && equalityFn(ref.prev, slice)) {
632 return ref.prev;
633 }
634
635 ref.prev = slice;
636 return slice;
637 });
638 return derivedAtom;
639 }, [anAtom, selector, equalityFn]);
640}
641
642function useAtomCallback(callback, scope) {
643 var anAtom = react.useMemo(function () {
644 return jotai.atom(null, function (get, set, _ref) {
645 var arg = _ref[0],
646 resolve = _ref[1],
647 reject = _ref[2];
648
649 try {
650 resolve(callback(get, set, arg));
651 } catch (e) {
652 reject(e);
653 }
654 });
655 }, [callback]);
656 var invoke = jotai.useSetAtom(anAtom, scope);
657 return react.useCallback(function (arg) {
658 var isSync = true;
659 var settled = {};
660 var promise = new Promise(function (resolve, reject) {
661 invoke([arg, function (v) {
662 if (isSync) {
663 settled = {
664 v: v
665 };
666 } else {
667 resolve(v);
668 }
669 }, function (e) {
670 if (isSync) {
671 settled = {
672 e: e
673 };
674 } else {
675 reject(e);
676 }
677 }]);
678 });
679 isSync = false;
680
681 if ('e' in settled) {
682 throw settled.e;
683 }
684
685 if ('v' in settled) {
686 return settled.v;
687 }
688
689 return promise;
690 }, [invoke]);
691}
692
693var memoizeAtom$3 = createMemoizeAtom();
694
695var deepFreeze = function deepFreeze(obj) {
696 if (typeof obj !== 'object' || obj === null) return;
697 Object.freeze(obj);
698 var propNames = Object.getOwnPropertyNames(obj);
699
700 for (var _iterator = _createForOfIteratorHelperLoose(propNames), _step; !(_step = _iterator()).done;) {
701 var name = _step.value;
702 var value = obj[name];
703 deepFreeze(value);
704 }
705
706 return obj;
707};
708
709function freezeAtom(anAtom) {
710 return memoizeAtom$3(function () {
711 var frozenAtom = jotai.atom(function (get) {
712 return deepFreeze(get(anAtom));
713 }, function (_get, set, arg) {
714 return set(anAtom, arg);
715 });
716 return frozenAtom;
717 }, [anAtom]);
718}
719function freezeAtomCreator(createAtom) {
720 return function () {
721 var anAtom = createAtom.apply(void 0, arguments);
722 var origRead = anAtom.read;
723
724 anAtom.read = function (get) {
725 return deepFreeze(origRead(get));
726 };
727
728 return anAtom;
729 };
730}
731
732var memoizeAtom$2 = createMemoizeAtom();
733
734var isWritable = function isWritable(atom) {
735 return !!atom.write;
736};
737
738var isFunction = function isFunction(x) {
739 return typeof x === 'function';
740};
741
742function splitAtom(arrAtom, keyExtractor) {
743 return memoizeAtom$2(function () {
744 var mappingCache = new WeakMap();
745
746 var getMapping = function getMapping(arr, prev) {
747 var mapping = mappingCache.get(arr);
748
749 if (mapping) {
750 return mapping;
751 }
752
753 var prevMapping = prev && mappingCache.get(prev);
754 var atomList = [];
755 var keyList = [];
756 arr.forEach(function (item, index) {
757 var key = keyExtractor ? keyExtractor(item) : index;
758 keyList[index] = key;
759 var cachedAtom = prevMapping && prevMapping.atomList[prevMapping.keyList.indexOf(key)];
760
761 if (cachedAtom) {
762 atomList[index] = cachedAtom;
763 return;
764 }
765
766 var read = function read(get) {
767 var ref = get(refAtom);
768 var currArr = get(arrAtom);
769 var mapping = getMapping(currArr, ref.prev);
770 var index = mapping.keyList.indexOf(key);
771
772 if (index < 0 || index >= currArr.length) {
773 var prevItem = arr[getMapping(arr).keyList.indexOf(key)];
774
775 if (prevItem) {
776 return prevItem;
777 }
778
779 throw new Error('splitAtom: index out of bounds for read');
780 }
781
782 return currArr[index];
783 };
784
785 var write = function write(get, set, update) {
786 var ref = get(refAtom);
787 var arr = get(arrAtom);
788 var mapping = getMapping(arr, ref.prev);
789 var index = mapping.keyList.indexOf(key);
790
791 if (index < 0 || index >= arr.length) {
792 throw new Error('splitAtom: index out of bounds for write');
793 }
794
795 var nextItem = isFunction(update) ? update(arr[index]) : update;
796 set(arrAtom, [].concat(arr.slice(0, index), [nextItem], arr.slice(index + 1)));
797 };
798
799 atomList[index] = isWritable(arrAtom) ? jotai.atom(read, write) : jotai.atom(read);
800 });
801
802 if (prevMapping && prevMapping.keyList.length === keyList.length && prevMapping.keyList.every(function (x, i) {
803 return x === keyList[i];
804 })) {
805 mapping = prevMapping;
806 } else {
807 mapping = {
808 atomList: atomList,
809 keyList: keyList
810 };
811 }
812
813 mappingCache.set(arr, mapping);
814 return mapping;
815 };
816
817 var refAtom = jotai.atom(function () {
818 return {};
819 });
820
821 var read = function read(get) {
822 var ref = get(refAtom);
823 var arr = get(arrAtom);
824 var mapping = getMapping(arr, ref.prev);
825 ref.prev = arr;
826 return mapping.atomList;
827 };
828
829 var write = function write(get, set, action) {
830 if ('read' in action) {
831 console.warn('atomToRemove is deprecated. use action with type');
832 action = {
833 type: 'remove',
834 atom: action
835 };
836 }
837
838 switch (action.type) {
839 case 'remove':
840 {
841 var index = get(splittedAtom).indexOf(action.atom);
842
843 if (index >= 0) {
844 var arr = get(arrAtom);
845 set(arrAtom, [].concat(arr.slice(0, index), arr.slice(index + 1)));
846 }
847
848 break;
849 }
850
851 case 'insert':
852 {
853 var _index = action.before ? get(splittedAtom).indexOf(action.before) : get(splittedAtom).length;
854
855 if (_index >= 0) {
856 var _arr = get(arrAtom);
857
858 set(arrAtom, [].concat(_arr.slice(0, _index), [action.value], _arr.slice(_index)));
859 }
860
861 break;
862 }
863
864 case 'move':
865 {
866 var index1 = get(splittedAtom).indexOf(action.atom);
867 var index2 = action.before ? get(splittedAtom).indexOf(action.before) : get(splittedAtom).length;
868
869 if (index1 >= 0 && index2 >= 0) {
870 var _arr2 = get(arrAtom);
871
872 if (index1 < index2) {
873 set(arrAtom, [].concat(_arr2.slice(0, index1), _arr2.slice(index1 + 1, index2), [_arr2[index1]], _arr2.slice(index2)));
874 } else {
875 set(arrAtom, [].concat(_arr2.slice(0, index2), [_arr2[index1]], _arr2.slice(index2, index1), _arr2.slice(index1 + 1)));
876 }
877 }
878
879 break;
880 }
881 }
882 };
883
884 var splittedAtom = isWritable(arrAtom) ? jotai.atom(read, write) : jotai.atom(read);
885 return splittedAtom;
886 }, keyExtractor ? [arrAtom, keyExtractor] : [arrAtom]);
887}
888
889function atomWithDefault(getDefault) {
890 var EMPTY = Symbol();
891 var overwrittenAtom = jotai.atom(EMPTY);
892 var anAtom = jotai.atom(function (get) {
893 var overwritten = get(overwrittenAtom);
894
895 if (overwritten !== EMPTY) {
896 return overwritten;
897 }
898
899 return getDefault(get);
900 }, function (get, set, update) {
901 if (update === RESET) {
902 return set(overwrittenAtom, EMPTY);
903 }
904
905 return set(overwrittenAtom, typeof update === 'function' ? update(get(anAtom)) : update);
906 });
907 return anAtom;
908}
909
910var memoizeAtom$1 = createMemoizeAtom();
911var emptyArrayAtom = jotai.atom(function () {
912 return [];
913});
914function waitForAll(atoms) {
915 var createAtom = function createAtom() {
916 var unwrappedAtoms = unwrapAtoms(atoms);
917 var derivedAtom = jotai.atom(function (get) {
918 var promises = [];
919 var values = unwrappedAtoms.map(function (anAtom, index) {
920 try {
921 return get(anAtom);
922 } catch (e) {
923 if (e instanceof Promise) {
924 promises[index] = e;
925 } else {
926 throw e;
927 }
928 }
929 });
930
931 if (promises.length) {
932 throw Promise.all(promises);
933 }
934
935 return wrapResults(atoms, values);
936 });
937 return derivedAtom;
938 };
939
940 if (Array.isArray(atoms)) {
941 if (atoms.length) {
942 return memoizeAtom$1(createAtom, atoms);
943 }
944
945 return emptyArrayAtom;
946 }
947
948 return createAtom();
949}
950
951var unwrapAtoms = function unwrapAtoms(atoms) {
952 return Array.isArray(atoms) ? atoms : Object.getOwnPropertyNames(atoms).map(function (key) {
953 return atoms[key];
954 });
955};
956
957var wrapResults = function wrapResults(atoms, results) {
958 return Array.isArray(atoms) ? results : Object.getOwnPropertyNames(atoms).reduce(function (out, key, idx) {
959 var _extends2;
960
961 return _extends({}, out, (_extends2 = {}, _extends2[key] = results[idx], _extends2));
962 }, {});
963};
964
965var NO_STORAGE_VALUE = Symbol();
966function createJSONStorage(getStringStorage) {
967 var lastStr;
968 var lastValue;
969 var storage = {
970 getItem: function getItem(key) {
971 var _getStringStorage$get, _getStringStorage;
972
973 var parse = function parse(str) {
974 str = str || '';
975
976 if (lastStr !== str) {
977 try {
978 lastValue = JSON.parse(str);
979 } catch (_unused) {
980 return NO_STORAGE_VALUE;
981 }
982
983 lastStr = str;
984 }
985
986 return lastValue;
987 };
988
989 var str = (_getStringStorage$get = (_getStringStorage = getStringStorage()) == null ? void 0 : _getStringStorage.getItem(key)) != null ? _getStringStorage$get : null;
990
991 if (str instanceof Promise) {
992 return str.then(parse);
993 }
994
995 return parse(str);
996 },
997 setItem: function setItem(key, newValue) {
998 var _getStringStorage2;
999
1000 return (_getStringStorage2 = getStringStorage()) == null ? void 0 : _getStringStorage2.setItem(key, JSON.stringify(newValue));
1001 },
1002 removeItem: function removeItem(key) {
1003 var _getStringStorage3;
1004
1005 return (_getStringStorage3 = getStringStorage()) == null ? void 0 : _getStringStorage3.removeItem(key);
1006 }
1007 };
1008
1009 if (typeof window !== 'undefined' && typeof window.addEventListener === 'function') {
1010 storage.subscribe = function (key, callback) {
1011 var storageEventCallback = function storageEventCallback(e) {
1012 if (e.key === key && e.newValue) {
1013 callback(JSON.parse(e.newValue));
1014 }
1015 };
1016
1017 window.addEventListener('storage', storageEventCallback);
1018 return function () {
1019 window.removeEventListener('storage', storageEventCallback);
1020 };
1021 };
1022 }
1023
1024 return storage;
1025}
1026var defaultStorage = createJSONStorage(function () {
1027 return typeof window !== 'undefined' ? window.localStorage : undefined;
1028});
1029function atomWithStorage(key, initialValue, storage) {
1030 if (storage === void 0) {
1031 storage = defaultStorage;
1032 }
1033
1034 var getInitialValue = function getInitialValue() {
1035 var value = storage.getItem(key);
1036
1037 if (value instanceof Promise) {
1038 return value.then(function (v) {
1039 return v === NO_STORAGE_VALUE ? initialValue : v;
1040 });
1041 }
1042
1043 return value === NO_STORAGE_VALUE ? initialValue : value;
1044 };
1045
1046 var baseAtom = jotai.atom(storage.delayInit ? initialValue : getInitialValue());
1047
1048 baseAtom.onMount = function (setAtom) {
1049 var unsub;
1050
1051 if (storage.subscribe) {
1052 unsub = storage.subscribe(key, setAtom);
1053 setAtom(getInitialValue());
1054 }
1055
1056 if (storage.delayInit) {
1057 var _value = getInitialValue();
1058
1059 if (_value instanceof Promise) {
1060 _value.then(setAtom);
1061 } else {
1062 setAtom(_value);
1063 }
1064 }
1065
1066 return unsub;
1067 };
1068
1069 var anAtom = jotai.atom(function (get) {
1070 return get(baseAtom);
1071 }, function (get, set, update) {
1072 var nextValue = typeof update === 'function' ? update(get(baseAtom)) : update;
1073
1074 if (nextValue === RESET) {
1075 set(baseAtom, initialValue);
1076 return storage.removeItem(key);
1077 }
1078
1079 set(baseAtom, nextValue);
1080 return storage.setItem(key, nextValue);
1081 });
1082 return anAtom;
1083}
1084function atomWithHash(key, initialValue, options) {
1085 var serialize = (options == null ? void 0 : options.serialize) || JSON.stringify;
1086
1087 var deserialize = (options == null ? void 0 : options.deserialize) || function (str) {
1088 try {
1089 return JSON.parse(str || '');
1090 } catch (_unused2) {
1091 return NO_STORAGE_VALUE;
1092 }
1093 };
1094
1095 var _subscribe = (options == null ? void 0 : options.subscribe) || function (callback) {
1096 window.addEventListener('hashchange', callback);
1097 return function () {
1098 window.removeEventListener('hashchange', callback);
1099 };
1100 };
1101
1102 var hashStorage = _extends({
1103 getItem: function getItem(key) {
1104 if (typeof location === 'undefined') {
1105 return NO_STORAGE_VALUE;
1106 }
1107
1108 var searchParams = new URLSearchParams(location.hash.slice(1));
1109 var storedValue = searchParams.get(key);
1110 return deserialize(storedValue);
1111 },
1112 setItem: function setItem(key, newValue) {
1113 var searchParams = new URLSearchParams(location.hash.slice(1));
1114 searchParams.set(key, serialize(newValue));
1115
1116 if (options != null && options.replaceState) {
1117 history.replaceState(null, '', '#' + searchParams.toString());
1118 } else {
1119 location.hash = searchParams.toString();
1120 }
1121 },
1122 removeItem: function removeItem(key) {
1123 var searchParams = new URLSearchParams(location.hash.slice(1));
1124 searchParams.delete(key);
1125
1126 if (options != null && options.replaceState) {
1127 history.replaceState(null, '', '#' + searchParams.toString());
1128 } else {
1129 location.hash = searchParams.toString();
1130 }
1131 }
1132 }, (options == null ? void 0 : options.delayInit) && {
1133 delayInit: true
1134 }, {
1135 subscribe: function subscribe(key, setValue) {
1136 var callback = function callback() {
1137 var searchParams = new URLSearchParams(location.hash.slice(1));
1138 var str = searchParams.get(key);
1139
1140 if (str !== null) {
1141 setValue(deserialize(str));
1142 } else {
1143 setValue(initialValue);
1144 }
1145 };
1146
1147 return _subscribe(callback);
1148 }
1149 });
1150
1151 return atomWithStorage(key, initialValue, hashStorage);
1152}
1153
1154function atomWithObservable(getObservable, options) {
1155 var observableResultAtom = jotai.atom(function (get) {
1156 var _observable$Symbol$ob, _observable;
1157
1158 var observable = getObservable(get);
1159 var itself = (_observable$Symbol$ob = (_observable = observable)[Symbol.observable]) == null ? void 0 : _observable$Symbol$ob.call(_observable);
1160
1161 if (itself) {
1162 observable = itself;
1163 }
1164
1165 var resolve;
1166
1167 var makePending = function makePending() {
1168 return new Promise(function (r) {
1169 resolve = r;
1170 });
1171 };
1172
1173 var initialResult = options && 'initialValue' in options ? {
1174 d: typeof options.initialValue === 'function' ? options.initialValue() : options.initialValue
1175 } : makePending();
1176 var setResult;
1177 var lastResult;
1178
1179 var listener = function listener(result) {
1180 lastResult = result;
1181 resolve == null ? void 0 : resolve(result);
1182 setResult == null ? void 0 : setResult(result);
1183 };
1184
1185 var subscription;
1186 var timer;
1187
1188 var isNotMounted = function isNotMounted() {
1189 return !setResult;
1190 };
1191
1192 var start = function start() {
1193 if (subscription) {
1194 clearTimeout(timer);
1195 subscription.unsubscribe();
1196 }
1197
1198 subscription = observable.subscribe({
1199 next: function next(d) {
1200 return listener({
1201 d: d
1202 });
1203 },
1204 error: function error(e) {
1205 return listener({
1206 e: e
1207 });
1208 },
1209 complete: function complete() {}
1210 });
1211
1212 if (isNotMounted() && options != null && options.unstable_timeout) {
1213 timer = setTimeout(function () {
1214 if (subscription) {
1215 subscription.unsubscribe();
1216 subscription = undefined;
1217 }
1218 }, options.unstable_timeout);
1219 }
1220 };
1221
1222 start();
1223 var resultAtom = jotai.atom(lastResult || initialResult);
1224
1225 resultAtom.onMount = function (update) {
1226 setResult = update;
1227
1228 if (lastResult) {
1229 update(lastResult);
1230 }
1231
1232 if (subscription) {
1233 clearTimeout(timer);
1234 } else {
1235 start();
1236 }
1237
1238 return function () {
1239 setResult = undefined;
1240
1241 if (subscription) {
1242 subscription.unsubscribe();
1243 subscription = undefined;
1244 }
1245 };
1246 };
1247
1248 return [resultAtom, observable, makePending, start, isNotMounted];
1249 });
1250 var observableAtom = jotai.atom(function (get) {
1251 var _get = get(observableResultAtom),
1252 resultAtom = _get[0];
1253
1254 var result = get(resultAtom);
1255
1256 if ('e' in result) {
1257 throw result.e;
1258 }
1259
1260 return result.d;
1261 }, function (get, set, data) {
1262 var _get2 = get(observableResultAtom),
1263 resultAtom = _get2[0],
1264 observable = _get2[1],
1265 makePending = _get2[2],
1266 start = _get2[3],
1267 isNotMounted = _get2[4];
1268
1269 if ('next' in observable) {
1270 if (isNotMounted()) {
1271 set(resultAtom, makePending());
1272 start();
1273 }
1274
1275 observable.next(data);
1276 } else {
1277 throw new Error('observable is not subject');
1278 }
1279 });
1280 return observableAtom;
1281}
1282
1283var hydratedMap = new WeakMap();
1284function useHydrateAtoms(values, scope) {
1285 var ScopeContext = jotai.SECRET_INTERNAL_getScopeContext(scope);
1286 var scopeContainer = react.useContext(ScopeContext);
1287 var store = scopeContainer.s;
1288 var hydratedSet = getHydratedSet(scopeContainer);
1289 var tuplesToRestore = [];
1290
1291 for (var _iterator = _createForOfIteratorHelperLoose(values), _step; !(_step = _iterator()).done;) {
1292 var tuple = _step.value;
1293 var atom = tuple[0];
1294
1295 if (!hydratedSet.has(atom)) {
1296 hydratedSet.add(atom);
1297 tuplesToRestore.push(tuple);
1298 }
1299 }
1300
1301 if (tuplesToRestore.length) {
1302 store[RESTORE_ATOMS](tuplesToRestore);
1303 }
1304}
1305
1306function getHydratedSet(scopeContainer) {
1307 var hydratedSet = hydratedMap.get(scopeContainer);
1308
1309 if (!hydratedSet) {
1310 hydratedSet = new WeakSet();
1311 hydratedMap.set(scopeContainer, hydratedSet);
1312 }
1313
1314 return hydratedSet;
1315}
1316
1317var memoizeAtom = createMemoizeAtom();
1318var LOADING = {
1319 state: 'loading'
1320};
1321function loadable(anAtom) {
1322 return memoizeAtom(function () {
1323 var loadableAtomCache = new WeakMap();
1324 var catchAtom = jotai.atom(function (get) {
1325 var promise;
1326
1327 try {
1328 var data = get(anAtom);
1329
1330 var _loadableAtom = jotai.atom({
1331 state: 'hasData',
1332 data: data
1333 });
1334
1335 return _loadableAtom;
1336 } catch (error) {
1337 if (error instanceof Promise) {
1338 promise = error;
1339 } else {
1340 var _loadableAtom2 = jotai.atom({
1341 state: 'hasError',
1342 error: error
1343 });
1344
1345 return _loadableAtom2;
1346 }
1347 }
1348
1349 var cached = loadableAtomCache.get(promise);
1350
1351 if (cached) {
1352 return cached;
1353 }
1354
1355 var loadableAtom = jotai.atom(LOADING, function () {
1356 var _ref = _asyncToGenerator(_regeneratorRuntime().mark(function _callee(get, set) {
1357 var _data;
1358
1359 return _regeneratorRuntime().wrap(function _callee$(_context) {
1360 while (1) {
1361 switch (_context.prev = _context.next) {
1362 case 0:
1363 _context.prev = 0;
1364 _context.next = 3;
1365 return get(anAtom, {
1366 unstable_promise: true
1367 });
1368
1369 case 3:
1370 _data = _context.sent;
1371 set(loadableAtom, {
1372 state: 'hasData',
1373 data: _data
1374 });
1375 _context.next = 10;
1376 break;
1377
1378 case 7:
1379 _context.prev = 7;
1380 _context.t0 = _context["catch"](0);
1381 set(loadableAtom, {
1382 state: 'hasError',
1383 error: _context.t0
1384 });
1385
1386 case 10:
1387 case "end":
1388 return _context.stop();
1389 }
1390 }
1391 }, _callee, null, [[0, 7]]);
1392 }));
1393
1394 return function (_x, _x2) {
1395 return _ref.apply(this, arguments);
1396 };
1397 }());
1398
1399 loadableAtom.onMount = function (init) {
1400 init();
1401 };
1402
1403 loadableAtomCache.set(promise, loadableAtom);
1404 return loadableAtom;
1405 });
1406 var derivedAtom = jotai.atom(function (get) {
1407 var loadableAtom = get(catchAtom);
1408 return get(loadableAtom);
1409 });
1410 return derivedAtom;
1411 }, [anAtom]);
1412}
1413
1414function abortableAtom(read, write) {
1415 return jotai.atom(function (get) {
1416 var controller = new AbortController();
1417 var promise = read(get, {
1418 signal: controller.signal
1419 });
1420
1421 if (promise instanceof Promise) {
1422 jotai.SECRET_INTERNAL_registerPromiseAbort(promise, function () {
1423 return controller.abort();
1424 });
1425 }
1426
1427 return promise;
1428 }, write);
1429}
1430
1431Object.defineProperty(exports, 'useAtomValue', {
1432 enumerable: true,
1433 get: function () { return jotai.useAtomValue; }
1434});
1435Object.defineProperty(exports, 'useUpdateAtom', {
1436 enumerable: true,
1437 get: function () { return jotai.useSetAtom; }
1438});
1439exports.RESET = RESET;
1440exports.abortableAtom = abortableAtom;
1441exports.atomFamily = atomFamily;
1442exports.atomWithDefault = atomWithDefault;
1443exports.atomWithHash = atomWithHash;
1444exports.atomWithObservable = atomWithObservable;
1445exports.atomWithReducer = atomWithReducer;
1446exports.atomWithReset = atomWithReset;
1447exports.atomWithStorage = atomWithStorage;
1448exports.createJSONStorage = createJSONStorage;
1449exports.freezeAtom = freezeAtom;
1450exports.freezeAtomCreator = freezeAtomCreator;
1451exports.loadable = loadable;
1452exports.selectAtom = selectAtom;
1453exports.splitAtom = splitAtom;
1454exports.unstable_NO_STORAGE_VALUE = NO_STORAGE_VALUE;
1455exports.useAtomCallback = useAtomCallback;
1456exports.useHydrateAtoms = useHydrateAtoms;
1457exports.useReducerAtom = useReducerAtom;
1458exports.useResetAtom = useResetAtom;
1459exports.waitForAll = waitForAll;