UNPKG

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