UNPKG

31.4 kBJavaScriptView Raw
1'use strict';
2
3var react = require('react');
4
5function _extends() {
6 _extends = Object.assign ? Object.assign.bind() : function (target) {
7 for (var i = 1; i < arguments.length; i++) {
8 var source = arguments[i];
9 for (var key in source) {
10 if (Object.prototype.hasOwnProperty.call(source, key)) {
11 target[key] = source[key];
12 }
13 }
14 }
15 return target;
16 };
17 return _extends.apply(this, arguments);
18}
19function _unsupportedIterableToArray(o, minLen) {
20 if (!o) return;
21 if (typeof o === "string") return _arrayLikeToArray(o, minLen);
22 var n = Object.prototype.toString.call(o).slice(8, -1);
23 if (n === "Object" && o.constructor) n = o.constructor.name;
24 if (n === "Map" || n === "Set") return Array.from(o);
25 if (n === "Arguments" || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)) return _arrayLikeToArray(o, minLen);
26}
27function _arrayLikeToArray(arr, len) {
28 if (len == null || len > arr.length) len = arr.length;
29 for (var i = 0, arr2 = new Array(len); i < len; i++) arr2[i] = arr[i];
30 return arr2;
31}
32function _createForOfIteratorHelperLoose(o, allowArrayLike) {
33 var it = typeof Symbol !== "undefined" && o[Symbol.iterator] || o["@@iterator"];
34 if (it) return (it = it.call(o)).next.bind(it);
35 if (Array.isArray(o) || (it = _unsupportedIterableToArray(o)) || allowArrayLike && o && typeof o.length === "number") {
36 if (it) o = it;
37 var i = 0;
38 return function () {
39 if (i >= o.length) return {
40 done: true
41 };
42 return {
43 done: false,
44 value: o[i++]
45 };
46 };
47 }
48 throw new TypeError("Invalid attempt to iterate non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.");
49}
50
51var SUSPENSE_PROMISE = Symbol();
52var isSuspensePromise = function isSuspensePromise(promise) {
53 return !!promise[SUSPENSE_PROMISE];
54};
55var isSuspensePromiseAlreadyCancelled = function isSuspensePromiseAlreadyCancelled(suspensePromise) {
56 return !suspensePromise[SUSPENSE_PROMISE].c;
57};
58var cancelSuspensePromise = function cancelSuspensePromise(suspensePromise) {
59 var _suspensePromise$SUSP = suspensePromise[SUSPENSE_PROMISE],
60 basePromise = _suspensePromise$SUSP.b,
61 cancelPromise = _suspensePromise$SUSP.c;
62 if (cancelPromise) {
63 var _promiseAbortMap$get;
64 cancelPromise();
65 (_promiseAbortMap$get = promiseAbortMap.get(basePromise)) == null ? void 0 : _promiseAbortMap$get();
66 }
67};
68
69var isEqualSuspensePromise = function isEqualSuspensePromise(oldSuspensePromise, newSuspensePromise) {
70 var oldOriginalPromise = oldSuspensePromise[SUSPENSE_PROMISE].o;
71 var newOriginalPromise = newSuspensePromise[SUSPENSE_PROMISE].o;
72 return oldOriginalPromise === newOriginalPromise || oldSuspensePromise === newOriginalPromise || isSuspensePromise(oldOriginalPromise) && isEqualSuspensePromise(oldOriginalPromise, newSuspensePromise);
73};
74var createSuspensePromise = function createSuspensePromise(basePromise, promise) {
75 var suspensePromiseExtra = {
76 b: basePromise,
77 o: promise,
78 c: null
79 };
80 var suspensePromise = new Promise(function (resolve) {
81 suspensePromiseExtra.c = function () {
82 suspensePromiseExtra.c = null;
83 resolve();
84 };
85 promise.finally(suspensePromiseExtra.c);
86 });
87 suspensePromise[SUSPENSE_PROMISE] = suspensePromiseExtra;
88 return suspensePromise;
89};
90var copySuspensePromise = function copySuspensePromise(suspensePromise) {
91 return createSuspensePromise(suspensePromise[SUSPENSE_PROMISE].b, suspensePromise[SUSPENSE_PROMISE].o);
92};
93var promiseAbortMap = new WeakMap();
94var registerPromiseAbort = function registerPromiseAbort(basePromise, abort) {
95 promiseAbortMap.set(basePromise, abort);
96};
97
98var hasInitialValue = function hasInitialValue(atom) {
99 return 'init' in atom;
100};
101var READ_ATOM = 'r';
102var WRITE_ATOM = 'w';
103var COMMIT_ATOM = 'c';
104var SUBSCRIBE_ATOM = 's';
105var RESTORE_ATOMS = 'h';
106
107var DEV_SUBSCRIBE_STATE = 'n';
108var DEV_GET_MOUNTED_ATOMS = 'l';
109var DEV_GET_ATOM_STATE = 'a';
110var DEV_GET_MOUNTED = 'm';
111
112var createStore = function createStore(initialValues) {
113 var _ref4;
114 var committedAtomStateMap = new WeakMap();
115 var mountedMap = new WeakMap();
116 var pendingMap = new Map();
117 var stateListeners;
118 var mountedAtoms;
119 if (process.env.NODE_ENV !== "production") {
120 stateListeners = new Set();
121 mountedAtoms = new Set();
122 }
123 if (initialValues) {
124 for (var _iterator = _createForOfIteratorHelperLoose(initialValues), _step; !(_step = _iterator()).done;) {
125 var _step$value = _step.value,
126 atom = _step$value[0],
127 value = _step$value[1];
128 var atomState = {
129 v: value,
130 r: 0,
131 y: true,
132 d: new Map()
133 };
134 if (process.env.NODE_ENV !== "production") {
135 Object.freeze(atomState);
136 if (!hasInitialValue(atom)) {
137 console.warn('Found initial value for derived atom which can cause unexpected behavior', atom);
138 }
139 }
140 committedAtomStateMap.set(atom, atomState);
141 }
142 }
143 var suspensePromiseCacheMap = new WeakMap();
144 var addSuspensePromiseToCache = function addSuspensePromiseToCache(version, atom, suspensePromise) {
145 var cache = suspensePromiseCacheMap.get(atom);
146 if (!cache) {
147 cache = new Map();
148 suspensePromiseCacheMap.set(atom, cache);
149 }
150 suspensePromise.then(function () {
151 if (cache.get(version) === suspensePromise) {
152 cache.delete(version);
153 if (!cache.size) {
154 suspensePromiseCacheMap.delete(atom);
155 }
156 }
157 });
158 cache.set(version, suspensePromise);
159 };
160 var cancelAllSuspensePromiseInCache = function cancelAllSuspensePromiseInCache(atom) {
161 var versionSet = new Set();
162 var cache = suspensePromiseCacheMap.get(atom);
163 if (cache) {
164 suspensePromiseCacheMap.delete(atom);
165 cache.forEach(function (suspensePromise, version) {
166 cancelSuspensePromise(suspensePromise);
167 versionSet.add(version);
168 });
169 }
170 return versionSet;
171 };
172 var versionedAtomStateMapMap = new WeakMap();
173 var getVersionedAtomStateMap = function getVersionedAtomStateMap(version) {
174 var versionedAtomStateMap = versionedAtomStateMapMap.get(version);
175 if (!versionedAtomStateMap) {
176 versionedAtomStateMap = new Map();
177 versionedAtomStateMapMap.set(version, versionedAtomStateMap);
178 }
179 return versionedAtomStateMap;
180 };
181 var getAtomState = function getAtomState(version, atom) {
182 if (version) {
183 var versionedAtomStateMap = getVersionedAtomStateMap(version);
184 var _atomState = versionedAtomStateMap.get(atom);
185 if (!_atomState) {
186 _atomState = getAtomState(version.p, atom);
187 if (_atomState && 'p' in _atomState && isSuspensePromiseAlreadyCancelled(_atomState.p)) {
188 _atomState = undefined;
189 }
190 if (_atomState) {
191 versionedAtomStateMap.set(atom, _atomState);
192 }
193 }
194 return _atomState;
195 }
196 return committedAtomStateMap.get(atom);
197 };
198 var setAtomState = function setAtomState(version, atom, atomState) {
199 if (process.env.NODE_ENV !== "production") {
200 Object.freeze(atomState);
201 }
202 if (version) {
203 var versionedAtomStateMap = getVersionedAtomStateMap(version);
204 versionedAtomStateMap.set(atom, atomState);
205 } else {
206 var prevAtomState = committedAtomStateMap.get(atom);
207 committedAtomStateMap.set(atom, atomState);
208 if (!pendingMap.has(atom)) {
209 pendingMap.set(atom, prevAtomState);
210 }
211 }
212 };
213 var createReadDependencies = function createReadDependencies(version, prevReadDependencies, dependencies) {
214 if (prevReadDependencies === void 0) {
215 prevReadDependencies = new Map();
216 }
217 if (!dependencies) {
218 return prevReadDependencies;
219 }
220 var readDependencies = new Map();
221 var changed = false;
222 dependencies.forEach(function (atom) {
223 var _getAtomState;
224 var revision = ((_getAtomState = getAtomState(version, atom)) == null ? void 0 : _getAtomState.r) || 0;
225 readDependencies.set(atom, revision);
226 if (prevReadDependencies.get(atom) !== revision) {
227 changed = true;
228 }
229 });
230 if (prevReadDependencies.size === readDependencies.size && !changed) {
231 return prevReadDependencies;
232 }
233 return readDependencies;
234 };
235 var setAtomValue = function setAtomValue(version, atom, value, dependencies, suspensePromise) {
236 var atomState = getAtomState(version, atom);
237 if (atomState) {
238 if (suspensePromise && (!('p' in atomState) || !isEqualSuspensePromise(atomState.p, suspensePromise))) {
239 return atomState;
240 }
241 if ('p' in atomState) {
242 cancelSuspensePromise(atomState.p);
243 }
244 }
245 var nextAtomState = {
246 v: value,
247 r: (atomState == null ? void 0 : atomState.r) || 0,
248 y: true,
249 d: createReadDependencies(version, atomState == null ? void 0 : atomState.d, dependencies)
250 };
251 var changed = !(atomState != null && atomState.y);
252 if (!atomState || !('v' in atomState) ||
253 !Object.is(atomState.v, value)) {
254 changed = true;
255 ++nextAtomState.r;
256 if (nextAtomState.d.has(atom)) {
257 nextAtomState.d = new Map(nextAtomState.d).set(atom, nextAtomState.r);
258 }
259 } else if (nextAtomState.d !== atomState.d && (nextAtomState.d.size !== atomState.d.size || !Array.from(nextAtomState.d.keys()).every(function (a) {
260 return atomState.d.has(a);
261 }))) {
262 changed = true;
263 Promise.resolve().then(function () {
264 flushPending(version);
265 });
266 }
267 if (atomState && !changed) {
268 return atomState;
269 }
270 setAtomState(version, atom, nextAtomState);
271 return nextAtomState;
272 };
273 var setAtomReadError = function setAtomReadError(version, atom, error, dependencies, suspensePromise) {
274 var atomState = getAtomState(version, atom);
275 if (atomState) {
276 if (suspensePromise && (!('p' in atomState) || !isEqualSuspensePromise(atomState.p, suspensePromise))) {
277 return atomState;
278 }
279 if ('p' in atomState) {
280 cancelSuspensePromise(atomState.p);
281 }
282 }
283 var nextAtomState = {
284 e: error,
285 r: ((atomState == null ? void 0 : atomState.r) || 0) + 1,
286 y: true,
287 d: createReadDependencies(version, atomState == null ? void 0 : atomState.d, dependencies)
288 };
289 setAtomState(version, atom, nextAtomState);
290 return nextAtomState;
291 };
292 var setAtomSuspensePromise = function setAtomSuspensePromise(version, atom, suspensePromise, dependencies) {
293 var atomState = getAtomState(version, atom);
294 if (atomState && 'p' in atomState) {
295 if (isEqualSuspensePromise(atomState.p, suspensePromise) && !isSuspensePromiseAlreadyCancelled(atomState.p)) {
296 if (!atomState.y) {
297 return _extends({}, atomState, {
298 y: true
299 });
300 }
301 return atomState;
302 }
303 cancelSuspensePromise(atomState.p);
304 }
305 addSuspensePromiseToCache(version, atom, suspensePromise);
306 var nextAtomState = {
307 p: suspensePromise,
308 r: ((atomState == null ? void 0 : atomState.r) || 0) + 1,
309 y: true,
310 d: createReadDependencies(version, atomState == null ? void 0 : atomState.d, dependencies)
311 };
312 setAtomState(version, atom, nextAtomState);
313 return nextAtomState;
314 };
315 var setAtomPromiseOrValue = function setAtomPromiseOrValue(version, atom, promiseOrValue, dependencies) {
316 if (promiseOrValue instanceof Promise) {
317 var suspensePromise = createSuspensePromise(promiseOrValue, promiseOrValue.then(function (value) {
318 setAtomValue(version, atom, value, dependencies, suspensePromise);
319 }).catch(function (e) {
320 if (e instanceof Promise) {
321 if (isSuspensePromise(e)) {
322 return e.then(function () {
323 readAtomState(version, atom, true);
324 });
325 }
326 return e;
327 }
328 setAtomReadError(version, atom, e, dependencies, suspensePromise);
329 }));
330 return setAtomSuspensePromise(version, atom, suspensePromise, dependencies);
331 }
332 return setAtomValue(version, atom, promiseOrValue, dependencies);
333 };
334 var setAtomInvalidated = function setAtomInvalidated(version, atom) {
335 var atomState = getAtomState(version, atom);
336 if (atomState) {
337 var nextAtomState = _extends({}, atomState, {
338 y: false
339 });
340
341 setAtomState(version, atom, nextAtomState);
342 } else if (process.env.NODE_ENV !== "production") {
343 console.warn('[Bug] could not invalidate non existing atom', atom);
344 }
345 };
346 var readAtomState = function readAtomState(version, atom, force) {
347 if (!force) {
348 var _atomState2 = getAtomState(version, atom);
349 if (_atomState2) {
350 if (_atomState2.y &&
351 'p' in _atomState2 && !isSuspensePromiseAlreadyCancelled(_atomState2.p)) {
352 return _atomState2;
353 }
354 _atomState2.d.forEach(function (_, a) {
355 if (a !== atom) {
356 if (!mountedMap.has(a)) {
357 readAtomState(version, a);
358 } else {
359 var aState = getAtomState(version, a);
360 if (aState && !aState.y) {
361 readAtomState(version, a);
362 }
363 }
364 }
365 });
366 if (Array.from(_atomState2.d).every(function (_ref) {
367 var a = _ref[0],
368 r = _ref[1];
369 var aState = getAtomState(version, a);
370 return aState && !('p' in aState) &&
371 aState.r === r;
372 })) {
373 if (!_atomState2.y) {
374 return _extends({}, _atomState2, {
375 y: true
376 });
377 }
378 return _atomState2;
379 }
380 }
381 }
382 var dependencies = new Set();
383 try {
384 var promiseOrValue = atom.read(function (a) {
385 dependencies.add(a);
386 var aState = a === atom ? getAtomState(version, a) : readAtomState(version, a);
387 if (aState) {
388 if ('e' in aState) {
389 throw aState.e;
390 }
391
392 if ('p' in aState) {
393 throw aState.p;
394 }
395
396 return aState.v;
397 }
398
399 if (hasInitialValue(a)) {
400 return a.init;
401 }
402 throw new Error('no atom init');
403 });
404 return setAtomPromiseOrValue(version, atom, promiseOrValue, dependencies);
405 } catch (errorOrPromise) {
406 if (errorOrPromise instanceof Promise) {
407 var suspensePromise = isSuspensePromise(errorOrPromise) && isSuspensePromiseAlreadyCancelled(errorOrPromise) ? copySuspensePromise(errorOrPromise) : createSuspensePromise(errorOrPromise, errorOrPromise);
408 return setAtomSuspensePromise(version, atom, suspensePromise, dependencies);
409 }
410 return setAtomReadError(version, atom, errorOrPromise, dependencies);
411 }
412 };
413 var readAtom = function readAtom(readingAtom, version) {
414 var atomState = readAtomState(version, readingAtom);
415 return atomState;
416 };
417 var addAtom = function addAtom(version, addingAtom) {
418 var mounted = mountedMap.get(addingAtom);
419 if (!mounted) {
420 mounted = mountAtom(version, addingAtom);
421 }
422 return mounted;
423 };
424
425 var canUnmountAtom = function canUnmountAtom(atom, mounted) {
426 return !mounted.l.size && (!mounted.t.size || mounted.t.size === 1 && mounted.t.has(atom));
427 };
428 var delAtom = function delAtom(version, deletingAtom) {
429 var mounted = mountedMap.get(deletingAtom);
430 if (mounted && canUnmountAtom(deletingAtom, mounted)) {
431 unmountAtom(version, deletingAtom);
432 }
433 };
434 var invalidateDependents = function invalidateDependents(version, atom) {
435 var mounted = mountedMap.get(atom);
436 mounted == null ? void 0 : mounted.t.forEach(function (dependent) {
437 if (dependent !== atom) {
438 setAtomInvalidated(version, dependent);
439 invalidateDependents(version, dependent);
440 }
441 });
442 };
443 var writeAtomState = function writeAtomState(version, atom, update) {
444 var isSync = true;
445 var writeGetter = function writeGetter(a, options) {
446 var aState = readAtomState(version, a);
447 if ('e' in aState) {
448 throw aState.e;
449 }
450
451 if ('p' in aState) {
452 if (options != null && options.unstable_promise) {
453 return aState.p.then(function () {
454 var s = getAtomState(version, a);
455 if (s && 'p' in s && s.p === aState.p) {
456 return new Promise(function (resolve) {
457 return setTimeout(resolve);
458 }).then(function () {
459 return writeGetter(a, options);
460 });
461 }
462 return writeGetter(a, options);
463 });
464 }
465 if (process.env.NODE_ENV !== "production") {
466 console.info('Reading pending atom state in write operation. We throw a promise for now.', a);
467 }
468 throw aState.p;
469 }
470
471 if ('v' in aState) {
472 return aState.v;
473 }
474
475 if (process.env.NODE_ENV !== "production") {
476 console.warn('[Bug] no value found while reading atom in write operation. This is probably a bug.', a);
477 }
478 throw new Error('no value found');
479 };
480 var setter = function setter(a, v) {
481 var promiseOrVoid;
482 if (a === atom) {
483 if (!hasInitialValue(a)) {
484 throw new Error('atom not writable');
485 }
486 var versionSet = cancelAllSuspensePromiseInCache(a);
487 versionSet.forEach(function (cancelledVersion) {
488 if (cancelledVersion !== version) {
489 setAtomPromiseOrValue(cancelledVersion, a, v);
490 }
491 });
492 var prevAtomState = getAtomState(version, a);
493 var nextAtomState = setAtomPromiseOrValue(version, a, v);
494 if (prevAtomState !== nextAtomState) {
495 invalidateDependents(version, a);
496 }
497 } else {
498 promiseOrVoid = writeAtomState(version, a, v);
499 }
500 if (!isSync) {
501 flushPending(version);
502 }
503 return promiseOrVoid;
504 };
505 var promiseOrVoid = atom.write(writeGetter, setter, update);
506 isSync = false;
507 return promiseOrVoid;
508 };
509 var writeAtom = function writeAtom(writingAtom, update, version) {
510 var promiseOrVoid = writeAtomState(version, writingAtom, update);
511 flushPending(version);
512 return promiseOrVoid;
513 };
514 var isActuallyWritableAtom = function isActuallyWritableAtom(atom) {
515 return !!atom.write;
516 };
517 var mountAtom = function mountAtom(version, atom, initialDependent) {
518 var mounted = {
519 t: new Set(initialDependent && [initialDependent]),
520 l: new Set()
521 };
522 mountedMap.set(atom, mounted);
523 if (process.env.NODE_ENV !== "production") {
524 mountedAtoms.add(atom);
525 }
526 var atomState = readAtomState(undefined, atom);
527 atomState.d.forEach(function (_, a) {
528 var aMounted = mountedMap.get(a);
529 if (aMounted) {
530 aMounted.t.add(atom);
531 } else {
532 if (a !== atom) {
533 mountAtom(version, a, atom);
534 }
535 }
536 });
537 if (isActuallyWritableAtom(atom) && atom.onMount) {
538 var setAtom = function setAtom(update) {
539 return writeAtom(atom, update, version);
540 };
541 var onUnmount = atom.onMount(setAtom);
542 version = undefined;
543 if (onUnmount) {
544 mounted.u = onUnmount;
545 }
546 }
547 return mounted;
548 };
549 var unmountAtom = function unmountAtom(version, atom) {
550 var _mountedMap$get;
551 var onUnmount = (_mountedMap$get = mountedMap.get(atom)) == null ? void 0 : _mountedMap$get.u;
552 if (onUnmount) {
553 onUnmount();
554 }
555 mountedMap.delete(atom);
556 if (process.env.NODE_ENV !== "production") {
557 mountedAtoms.delete(atom);
558 }
559 var atomState = getAtomState(version, atom);
560 if (atomState) {
561 if ('p' in atomState) {
562 cancelSuspensePromise(atomState.p);
563 }
564 atomState.d.forEach(function (_, a) {
565 if (a !== atom) {
566 var mounted = mountedMap.get(a);
567 if (mounted) {
568 mounted.t.delete(atom);
569 if (canUnmountAtom(a, mounted)) {
570 unmountAtom(version, a);
571 }
572 }
573 }
574 });
575 } else if (process.env.NODE_ENV !== "production") {
576 console.warn('[Bug] could not find atom state to unmount', atom);
577 }
578 };
579 var mountDependencies = function mountDependencies(version, atom, atomState, prevReadDependencies) {
580 var dependencies = new Set(atomState.d.keys());
581 prevReadDependencies == null ? void 0 : prevReadDependencies.forEach(function (_, a) {
582 if (dependencies.has(a)) {
583 dependencies.delete(a);
584 return;
585 }
586 var mounted = mountedMap.get(a);
587 if (mounted) {
588 mounted.t.delete(atom);
589 if (canUnmountAtom(a, mounted)) {
590 unmountAtom(version, a);
591 }
592 }
593 });
594 dependencies.forEach(function (a) {
595 var mounted = mountedMap.get(a);
596 if (mounted) {
597 mounted.t.add(atom);
598 } else if (mountedMap.has(atom)) {
599 mountAtom(version, a, atom);
600 }
601 });
602 };
603 var flushPending = function flushPending(version) {
604 if (version) {
605 var versionedAtomStateMap = getVersionedAtomStateMap(version);
606 versionedAtomStateMap.forEach(function (atomState, atom) {
607 var committedAtomState = committedAtomStateMap.get(atom);
608 if (atomState !== committedAtomState) {
609 var mounted = mountedMap.get(atom);
610 mounted == null ? void 0 : mounted.l.forEach(function (listener) {
611 return listener(version);
612 });
613 }
614 });
615 return;
616 }
617 while (pendingMap.size) {
618 var pending = Array.from(pendingMap);
619 pendingMap.clear();
620 pending.forEach(function (_ref2) {
621 var atom = _ref2[0],
622 prevAtomState = _ref2[1];
623 var atomState = getAtomState(undefined, atom);
624 if (atomState && atomState.d !== (prevAtomState == null ? void 0 : prevAtomState.d)) {
625 mountDependencies(undefined, atom, atomState, prevAtomState == null ? void 0 : prevAtomState.d);
626 }
627 if (prevAtomState && !prevAtomState.y && atomState != null && atomState.y) {
628 return;
629 }
630 var mounted = mountedMap.get(atom);
631 mounted == null ? void 0 : mounted.l.forEach(function (listener) {
632 return listener();
633 });
634 });
635 }
636 if (process.env.NODE_ENV !== "production") {
637 stateListeners.forEach(function (l) {
638 return l();
639 });
640 }
641 };
642 var commitVersionedAtomStateMap = function commitVersionedAtomStateMap(version) {
643 var versionedAtomStateMap = getVersionedAtomStateMap(version);
644 versionedAtomStateMap.forEach(function (atomState, atom) {
645 var prevAtomState = committedAtomStateMap.get(atom);
646 if (!prevAtomState || atomState.r > prevAtomState.r || atomState.y !== prevAtomState.y || atomState.r === prevAtomState.r && atomState.d !== prevAtomState.d) {
647 committedAtomStateMap.set(atom, atomState);
648 if (atomState.d !== (prevAtomState == null ? void 0 : prevAtomState.d)) {
649 mountDependencies(version, atom, atomState, prevAtomState == null ? void 0 : prevAtomState.d);
650 }
651 }
652 });
653 };
654 var commitAtom = function commitAtom(_atom, version) {
655 if (version) {
656 commitVersionedAtomStateMap(version);
657 }
658 flushPending(undefined);
659 };
660 var subscribeAtom = function subscribeAtom(atom, callback, version) {
661 var mounted = addAtom(version, atom);
662 var listeners = mounted.l;
663 listeners.add(callback);
664 return function () {
665 listeners.delete(callback);
666 delAtom(version, atom);
667 };
668 };
669 var restoreAtoms = function restoreAtoms(values, version) {
670 for (var _iterator2 = _createForOfIteratorHelperLoose(values), _step2; !(_step2 = _iterator2()).done;) {
671 var _step2$value = _step2.value,
672 _atom2 = _step2$value[0],
673 _value = _step2$value[1];
674 if (hasInitialValue(_atom2)) {
675 setAtomPromiseOrValue(version, _atom2, _value);
676 invalidateDependents(version, _atom2);
677 }
678 }
679 flushPending(version);
680 };
681 if (process.env.NODE_ENV !== "production") {
682 var _ref3;
683 return _ref3 = {}, _ref3[READ_ATOM] = readAtom, _ref3[WRITE_ATOM] = writeAtom, _ref3[COMMIT_ATOM] = commitAtom, _ref3[SUBSCRIBE_ATOM] = subscribeAtom, _ref3[RESTORE_ATOMS] = restoreAtoms, _ref3[DEV_SUBSCRIBE_STATE] = function (l) {
684 stateListeners.add(l);
685 return function () {
686 stateListeners.delete(l);
687 };
688 }, _ref3[DEV_GET_MOUNTED_ATOMS] = function () {
689 return mountedAtoms.values();
690 }, _ref3[DEV_GET_ATOM_STATE] = function (a) {
691 return committedAtomStateMap.get(a);
692 }, _ref3[DEV_GET_MOUNTED] = function (a) {
693 return mountedMap.get(a);
694 }, _ref3;
695 }
696 return _ref4 = {}, _ref4[READ_ATOM] = readAtom, _ref4[WRITE_ATOM] = writeAtom, _ref4[COMMIT_ATOM] = commitAtom, _ref4[SUBSCRIBE_ATOM] = subscribeAtom, _ref4[RESTORE_ATOMS] = restoreAtoms, _ref4;
697};
698var createStoreForExport = function createStoreForExport(initialValues) {
699 var store = createStore(initialValues);
700 var get = function get(atom) {
701 var atomState = store[READ_ATOM](atom);
702 if ('e' in atomState) {
703 throw atomState.e;
704 }
705
706 if ('p' in atomState) {
707 return undefined;
708 }
709
710 return atomState.v;
711 };
712 var asyncGet = function asyncGet(atom) {
713 return new Promise(function (resolve, reject) {
714 var atomState = store[READ_ATOM](atom);
715 if ('e' in atomState) {
716 reject(atomState.e);
717 } else if ('p' in atomState) {
718 resolve(atomState.p.then(function () {
719 return asyncGet(atom);
720 }));
721 } else {
722 resolve(atomState.v);
723 }
724 });
725 };
726 var set = function set(atom, update) {
727 return store[WRITE_ATOM](atom, update);
728 };
729 var sub = function sub(atom, callback) {
730 return store[SUBSCRIBE_ATOM](atom, callback);
731 };
732 return {
733 get: get,
734 asyncGet: asyncGet,
735 set: set,
736 sub: sub,
737 SECRET_INTERNAL_store: store
738 };
739};
740
741var createScopeContainer = function createScopeContainer(initialValues, unstable_createStore) {
742 var store = unstable_createStore ? unstable_createStore(initialValues).SECRET_INTERNAL_store : createStore(initialValues);
743 return {
744 s: store
745 };
746};
747var ScopeContextMap = new Map();
748var getScopeContext = function getScopeContext(scope) {
749 if (!ScopeContextMap.has(scope)) {
750 ScopeContextMap.set(scope, react.createContext(createScopeContainer()));
751 }
752 return ScopeContextMap.get(scope);
753};
754
755var Provider = function Provider(_ref) {
756 var children = _ref.children,
757 initialValues = _ref.initialValues,
758 scope = _ref.scope,
759 unstable_createStore = _ref.unstable_createStore,
760 unstable_enableVersionedWrite = _ref.unstable_enableVersionedWrite;
761 var _useState = react.useState({}),
762 version = _useState[0],
763 setVersion = _useState[1];
764 react.useEffect(function () {
765 var scopeContainer = scopeContainerRef.current;
766 if (scopeContainer.w) {
767 scopeContainer.s[COMMIT_ATOM](null, version);
768 delete version.p;
769 scopeContainer.v = version;
770 }
771 }, [version]);
772 var scopeContainerRef = react.useRef();
773 if (!scopeContainerRef.current) {
774 var scopeContainer = createScopeContainer(initialValues, unstable_createStore);
775 if (unstable_enableVersionedWrite) {
776 var retrying = 0;
777 scopeContainer.w = function (write) {
778 setVersion(function (parentVersion) {
779 var nextVersion = retrying ? parentVersion : {
780 p: parentVersion
781 };
782 write(nextVersion);
783 return nextVersion;
784 });
785 };
786 scopeContainer.v = version;
787 scopeContainer.r = function (fn) {
788 ++retrying;
789 fn();
790 --retrying;
791 };
792 }
793 scopeContainerRef.current = scopeContainer;
794 }
795 var ScopeContainerContext = getScopeContext(scope);
796 return react.createElement(ScopeContainerContext.Provider, {
797 value: scopeContainerRef.current
798 }, children);
799};
800
801var keyCount = 0;
802
803function atom(read, write) {
804 var key = "atom" + ++keyCount;
805 var config = {
806 toString: function toString() {
807 return key;
808 }
809 };
810 if (typeof read === 'function') {
811 config.read = read;
812 } else {
813 config.init = read;
814 config.read = function (get) {
815 return get(config);
816 };
817 config.write = function (get, set, update) {
818 return set(config, typeof update === 'function' ? update(get(config)) : update);
819 };
820 }
821 if (write) {
822 config.write = write;
823 }
824 return config;
825}
826
827function useAtomValue(atom, scope) {
828 var ScopeContext = getScopeContext(scope);
829 var scopeContainer = react.useContext(ScopeContext);
830 var store = scopeContainer.s,
831 versionFromProvider = scopeContainer.v;
832 var getAtomValue = function getAtomValue(version) {
833 var atomState = store[READ_ATOM](atom, version);
834 if (process.env.NODE_ENV !== "production" && !atomState.y) {
835 throw new Error('should not be invalidated');
836 }
837 if ('e' in atomState) {
838 throw atomState.e;
839 }
840
841 if ('p' in atomState) {
842 throw atomState.p;
843 }
844
845 if ('v' in atomState) {
846 return atomState.v;
847 }
848 throw new Error('no atom value');
849 };
850
851 var _useReducer = react.useReducer(function (prev, nextVersion) {
852 var nextValue = getAtomValue(nextVersion);
853 if (Object.is(prev[1], nextValue) && prev[2] === atom) {
854 return prev;
855 }
856
857 return [nextVersion, nextValue, atom];
858 }, versionFromProvider, function (initialVersion) {
859 var initialValue = getAtomValue(initialVersion);
860 return [initialVersion, initialValue, atom];
861 }),
862 _useReducer$ = _useReducer[0],
863 version = _useReducer$[0],
864 valueFromReducer = _useReducer$[1],
865 atomFromReducer = _useReducer$[2],
866 rerenderIfChanged = _useReducer[1];
867 var value = valueFromReducer;
868 if (atomFromReducer !== atom) {
869 rerenderIfChanged(version);
870 value = getAtomValue(version);
871 }
872 react.useEffect(function () {
873 var versionFromProvider = scopeContainer.v;
874 if (versionFromProvider) {
875 store[COMMIT_ATOM](atom, versionFromProvider);
876 }
877 var unsubscribe = store[SUBSCRIBE_ATOM](atom, rerenderIfChanged, versionFromProvider);
878 rerenderIfChanged(versionFromProvider);
879 return unsubscribe;
880 }, [store, atom, scopeContainer]);
881 react.useEffect(function () {
882 store[COMMIT_ATOM](atom, version);
883 });
884 react.useDebugValue(value);
885 return value;
886}
887
888function useSetAtom(atom, scope) {
889 var ScopeContext = getScopeContext(scope);
890 var _useContext = react.useContext(ScopeContext),
891 store = _useContext.s,
892 versionedWrite = _useContext.w;
893 var setAtom = react.useCallback(function (update) {
894 if (process.env.NODE_ENV !== "production" && !('write' in atom)) {
895 throw new Error('not writable atom');
896 }
897 var write = function write(version) {
898 return store[WRITE_ATOM](atom, update, version);
899 };
900 return versionedWrite ? versionedWrite(write) : write();
901 }, [store, versionedWrite, atom]);
902 return setAtom;
903}
904
905function useAtom(atom, scope) {
906 if ('scope' in atom) {
907 console.warn('atom.scope is deprecated. Please do useAtom(atom, scope) instead.');
908 scope = atom.scope;
909 }
910 return [useAtomValue(atom, scope),
911 useSetAtom(atom, scope)];
912}
913
914exports.Provider = Provider;
915exports.SECRET_INTERNAL_getScopeContext = getScopeContext;
916exports.SECRET_INTERNAL_registerPromiseAbort = registerPromiseAbort;
917exports.atom = atom;
918exports.unstable_createStore = createStoreForExport;
919exports.useAtom = useAtom;
920exports.useAtomValue = useAtomValue;
921exports.useSetAtom = useSetAtom;