UNPKG

41.7 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 atoms.delete(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
965function createJSONStorage(getStringStorage) {
966 var lastStr;
967 var lastValue;
968 return {
969 getItem: function getItem(key) {
970 var parse = function parse(str) {
971 str = str || '';
972
973 if (lastStr !== str) {
974 lastValue = JSON.parse(str);
975 lastStr = str;
976 }
977
978 return lastValue;
979 };
980
981 var str = getStringStorage().getItem(key);
982
983 if (str instanceof Promise) {
984 return str.then(parse);
985 }
986
987 return parse(str);
988 },
989 setItem: function setItem(key, newValue) {
990 return getStringStorage().setItem(key, JSON.stringify(newValue));
991 },
992 removeItem: function removeItem(key) {
993 return getStringStorage().removeItem(key);
994 }
995 };
996}
997var defaultStorage = createJSONStorage(function () {
998 return localStorage;
999});
1000
1001defaultStorage.subscribe = function (key, callback) {
1002 var storageEventCallback = function storageEventCallback(e) {
1003 if (e.key === key && e.newValue) {
1004 callback(JSON.parse(e.newValue));
1005 }
1006 };
1007
1008 window.addEventListener('storage', storageEventCallback);
1009 return function () {
1010 window.removeEventListener('storage', storageEventCallback);
1011 };
1012};
1013
1014function atomWithStorage(key, initialValue, storage) {
1015 if (storage === void 0) {
1016 storage = defaultStorage;
1017 }
1018
1019 var getInitialValue = function getInitialValue() {
1020 try {
1021 var _value = storage.getItem(key);
1022
1023 if (_value instanceof Promise) {
1024 return _value.catch(function () {
1025 return initialValue;
1026 });
1027 }
1028
1029 return _value;
1030 } catch (_unused) {
1031 return initialValue;
1032 }
1033 };
1034
1035 var baseAtom = jotai.atom(storage.delayInit ? initialValue : getInitialValue());
1036
1037 baseAtom.onMount = function (setAtom) {
1038 var unsub;
1039
1040 if (storage.subscribe) {
1041 unsub = storage.subscribe(key, setAtom);
1042 setAtom(getInitialValue());
1043 }
1044
1045 if (storage.delayInit) {
1046 var _value2 = getInitialValue();
1047
1048 if (_value2 instanceof Promise) {
1049 _value2.then(setAtom);
1050 } else {
1051 setAtom(_value2);
1052 }
1053 }
1054
1055 return unsub;
1056 };
1057
1058 var anAtom = jotai.atom(function (get) {
1059 return get(baseAtom);
1060 }, function (get, set, update) {
1061 var nextValue = typeof update === 'function' ? update(get(baseAtom)) : update;
1062
1063 if (nextValue === RESET) {
1064 set(baseAtom, initialValue);
1065 return storage.removeItem(key);
1066 }
1067
1068 set(baseAtom, nextValue);
1069 return storage.setItem(key, nextValue);
1070 });
1071 return anAtom;
1072}
1073function atomWithHash(key, initialValue, options) {
1074 var serialize = (options == null ? void 0 : options.serialize) || JSON.stringify;
1075 var deserialize = (options == null ? void 0 : options.deserialize) || JSON.parse;
1076
1077 var _subscribe = (options == null ? void 0 : options.subscribe) || function (callback) {
1078 window.addEventListener('hashchange', callback);
1079 return function () {
1080 window.removeEventListener('hashchange', callback);
1081 };
1082 };
1083
1084 var hashStorage = _extends({
1085 getItem: function getItem(key) {
1086 var searchParams = new URLSearchParams(location.hash.slice(1));
1087 var storedValue = searchParams.get(key);
1088
1089 if (storedValue === null) {
1090 throw new Error('no value stored');
1091 }
1092
1093 return deserialize(storedValue);
1094 },
1095 setItem: function setItem(key, newValue) {
1096 var searchParams = new URLSearchParams(location.hash.slice(1));
1097 searchParams.set(key, serialize(newValue));
1098
1099 if (options != null && options.replaceState) {
1100 history.replaceState(null, '', '#' + searchParams.toString());
1101 } else {
1102 location.hash = searchParams.toString();
1103 }
1104 },
1105 removeItem: function removeItem(key) {
1106 var searchParams = new URLSearchParams(location.hash.slice(1));
1107 searchParams.delete(key);
1108
1109 if (options != null && options.replaceState) {
1110 history.replaceState(null, '', '#' + searchParams.toString());
1111 } else {
1112 location.hash = searchParams.toString();
1113 }
1114 }
1115 }, (options == null ? void 0 : options.delayInit) && {
1116 delayInit: true
1117 }, {
1118 subscribe: function subscribe(key, setValue) {
1119 var callback = function callback() {
1120 var searchParams = new URLSearchParams(location.hash.slice(1));
1121 var str = searchParams.get(key);
1122
1123 if (str !== null) {
1124 setValue(deserialize(str));
1125 } else {
1126 setValue(initialValue);
1127 }
1128 };
1129
1130 return _subscribe(callback);
1131 }
1132 });
1133
1134 return atomWithStorage(key, initialValue, hashStorage);
1135}
1136
1137function atomWithObservable(createObservable, options) {
1138 var observableResultAtom = jotai.atom(function (get) {
1139 var _observable$Symbol$ob, _observable;
1140
1141 var observable = createObservable(get);
1142 var itself = (_observable$Symbol$ob = (_observable = observable)[Symbol.observable]) == null ? void 0 : _observable$Symbol$ob.call(_observable);
1143
1144 if (itself) {
1145 observable = itself;
1146 }
1147
1148 var EMPTY = Symbol();
1149 var resolveEmittedInitialValue = null;
1150 var initialEmittedValue = (options == null ? void 0 : options.initialValue) === undefined ? new Promise(function (resolve) {
1151 resolveEmittedInitialValue = resolve;
1152 }) : undefined;
1153 var initialValueWasEmitted = false;
1154 var emittedValueBeforeMount = EMPTY;
1155 var isSync = true;
1156
1157 var setData = function setData(data) {
1158 if ((options == null ? void 0 : options.initialValue) === undefined && !initialValueWasEmitted) {
1159 if (isSync) {
1160 initialEmittedValue = data;
1161 }
1162
1163 resolveEmittedInitialValue == null ? void 0 : resolveEmittedInitialValue(data);
1164 initialValueWasEmitted = true;
1165 resolveEmittedInitialValue = null;
1166 } else {
1167 emittedValueBeforeMount = data;
1168 }
1169 };
1170
1171 var dataListener = function dataListener(data) {
1172 setData(data);
1173 };
1174
1175 var errorListener = function errorListener(error) {
1176 setData(Promise.reject(error));
1177 };
1178
1179 var subscription = null;
1180 var initialValue;
1181
1182 if ((options == null ? void 0 : options.initialValue) !== undefined) {
1183 initialValue = getInitialValue(options);
1184 } else {
1185 subscription = observable.subscribe(dataListener, errorListener);
1186 initialValue = initialEmittedValue;
1187 }
1188
1189 isSync = false;
1190 var dataAtom = jotai.atom(initialValue);
1191
1192 dataAtom.onMount = function (update) {
1193 setData = update;
1194
1195 if (emittedValueBeforeMount !== EMPTY) {
1196 update(emittedValueBeforeMount);
1197 }
1198
1199 if (!subscription) {
1200 subscription = observable.subscribe(dataListener, errorListener);
1201 }
1202
1203 return function () {
1204 var _subscription;
1205
1206 (_subscription = subscription) == null ? void 0 : _subscription.unsubscribe();
1207 subscription = null;
1208 };
1209 };
1210
1211 return {
1212 dataAtom: dataAtom,
1213 observable: observable
1214 };
1215 });
1216 var observableAtom = jotai.atom(function (get) {
1217 var _get = get(observableResultAtom),
1218 dataAtom = _get.dataAtom;
1219
1220 return get(dataAtom);
1221 }, function (get, set, data) {
1222 var _get2 = get(observableResultAtom),
1223 dataAtom = _get2.dataAtom,
1224 observable = _get2.observable;
1225
1226 if ('next' in observable) {
1227 var subscription = null;
1228
1229 var callback = function callback(data) {
1230 var _subscription2;
1231
1232 set(dataAtom, data);
1233 (_subscription2 = subscription) == null ? void 0 : _subscription2.unsubscribe();
1234 };
1235
1236 subscription = observable.subscribe(callback);
1237 observable.next(data);
1238 } else {
1239 throw new Error('observable is not subject');
1240 }
1241 });
1242 return observableAtom;
1243}
1244
1245function getInitialValue(options) {
1246 var initialValue = options.initialValue;
1247 return initialValue instanceof Function ? initialValue() : initialValue;
1248}
1249
1250var hydratedMap = new WeakMap();
1251function useHydrateAtoms(values, scope) {
1252 var ScopeContext = jotai.SECRET_INTERNAL_getScopeContext(scope);
1253 var scopeContainer = react.useContext(ScopeContext);
1254 var store = scopeContainer.s;
1255 var hydratedSet = getHydratedSet(scopeContainer);
1256 var tuplesToRestore = [];
1257
1258 for (var _iterator = _createForOfIteratorHelperLoose(values), _step; !(_step = _iterator()).done;) {
1259 var tuple = _step.value;
1260 var atom = tuple[0];
1261
1262 if (!hydratedSet.has(atom)) {
1263 hydratedSet.add(atom);
1264 tuplesToRestore.push(tuple);
1265 }
1266 }
1267
1268 if (tuplesToRestore.length) {
1269 store[RESTORE_ATOMS](tuplesToRestore);
1270 }
1271}
1272
1273function getHydratedSet(scopeContainer) {
1274 var hydratedSet = hydratedMap.get(scopeContainer);
1275
1276 if (!hydratedSet) {
1277 hydratedSet = new WeakSet();
1278 hydratedMap.set(scopeContainer, hydratedSet);
1279 }
1280
1281 return hydratedSet;
1282}
1283
1284var memoizeAtom = createMemoizeAtom();
1285var LOADING = {
1286 state: 'loading'
1287};
1288function loadable(anAtom) {
1289 return memoizeAtom(function () {
1290 var loadableAtomCache = new WeakMap();
1291 var catchAtom = jotai.atom(function (get) {
1292 var promise;
1293
1294 try {
1295 var data = get(anAtom);
1296
1297 var _loadableAtom = jotai.atom({
1298 state: 'hasData',
1299 data: data
1300 });
1301
1302 return _loadableAtom;
1303 } catch (error) {
1304 if (error instanceof Promise) {
1305 promise = error;
1306 } else {
1307 var _loadableAtom2 = jotai.atom({
1308 state: 'hasError',
1309 error: error
1310 });
1311
1312 return _loadableAtom2;
1313 }
1314 }
1315
1316 var cached = loadableAtomCache.get(promise);
1317
1318 if (cached) {
1319 return cached;
1320 }
1321
1322 var loadableAtom = jotai.atom(LOADING, function () {
1323 var _ref = _asyncToGenerator(_regeneratorRuntime().mark(function _callee(get, set) {
1324 var _data;
1325
1326 return _regeneratorRuntime().wrap(function _callee$(_context) {
1327 while (1) {
1328 switch (_context.prev = _context.next) {
1329 case 0:
1330 _context.prev = 0;
1331 _context.next = 3;
1332 return get(anAtom, {
1333 unstable_promise: true
1334 });
1335
1336 case 3:
1337 _data = _context.sent;
1338 set(loadableAtom, {
1339 state: 'hasData',
1340 data: _data
1341 });
1342 _context.next = 10;
1343 break;
1344
1345 case 7:
1346 _context.prev = 7;
1347 _context.t0 = _context["catch"](0);
1348 set(loadableAtom, {
1349 state: 'hasError',
1350 error: _context.t0
1351 });
1352
1353 case 10:
1354 case "end":
1355 return _context.stop();
1356 }
1357 }
1358 }, _callee, null, [[0, 7]]);
1359 }));
1360
1361 return function (_x, _x2) {
1362 return _ref.apply(this, arguments);
1363 };
1364 }());
1365
1366 loadableAtom.onMount = function (init) {
1367 init();
1368 };
1369
1370 loadableAtomCache.set(promise, loadableAtom);
1371 return loadableAtom;
1372 });
1373 var derivedAtom = jotai.atom(function (get) {
1374 var loadableAtom = get(catchAtom);
1375 return get(loadableAtom);
1376 });
1377 return derivedAtom;
1378 }, [anAtom]);
1379}
1380
1381function abortableAtom(read, write) {
1382 return jotai.atom(function (get) {
1383 var controller = new AbortController();
1384 var promise = read(get, {
1385 signal: controller.signal
1386 });
1387
1388 if (promise instanceof Promise) {
1389 jotai.SECRET_INTERNAL_registerPromiseAbort(promise, function () {
1390 return controller.abort();
1391 });
1392 }
1393
1394 return promise;
1395 }, write);
1396}
1397
1398Object.defineProperty(exports, 'useAtomValue', {
1399 enumerable: true,
1400 get: function () { return jotai.useAtomValue; }
1401});
1402Object.defineProperty(exports, 'useUpdateAtom', {
1403 enumerable: true,
1404 get: function () { return jotai.useSetAtom; }
1405});
1406exports.RESET = RESET;
1407exports.abortableAtom = abortableAtom;
1408exports.atomFamily = atomFamily;
1409exports.atomWithDefault = atomWithDefault;
1410exports.atomWithHash = atomWithHash;
1411exports.atomWithObservable = atomWithObservable;
1412exports.atomWithReducer = atomWithReducer;
1413exports.atomWithReset = atomWithReset;
1414exports.atomWithStorage = atomWithStorage;
1415exports.createJSONStorage = createJSONStorage;
1416exports.freezeAtom = freezeAtom;
1417exports.freezeAtomCreator = freezeAtomCreator;
1418exports.loadable = loadable;
1419exports.selectAtom = selectAtom;
1420exports.splitAtom = splitAtom;
1421exports.useAtomCallback = useAtomCallback;
1422exports.useHydrateAtoms = useHydrateAtoms;
1423exports.useReducerAtom = useReducerAtom;
1424exports.useResetAtom = useResetAtom;
1425exports.waitForAll = waitForAll;