UNPKG

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