UNPKG

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