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