UNPKG

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