UNPKG

20.3 kBJavaScriptView Raw
1'use strict';
2
3var vanilla = require('jotai/vanilla');
4
5var RESET = Symbol();
6
7function atomWithReset(initialValue) {
8 var anAtom = vanilla.atom(initialValue, function (get, set, update) {
9 var nextValue = typeof update === 'function' ? update(get(anAtom)) : update;
10 set(anAtom, nextValue === RESET ? initialValue : nextValue);
11 });
12 return anAtom;
13}
14
15function atomWithReducer(initialValue, reducer) {
16 var anAtom = vanilla.atom(initialValue, function (get, set, action) {
17 return set(anAtom, reducer(get(anAtom), action));
18 });
19 return anAtom;
20}
21
22function _unsupportedIterableToArray(o, minLen) {
23 if (!o) return;
24 if (typeof o === "string") return _arrayLikeToArray(o, minLen);
25 var n = Object.prototype.toString.call(o).slice(8, -1);
26 if (n === "Object" && o.constructor) n = o.constructor.name;
27 if (n === "Map" || n === "Set") return Array.from(o);
28 if (n === "Arguments" || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)) return _arrayLikeToArray(o, minLen);
29}
30function _arrayLikeToArray(arr, len) {
31 if (len == null || len > arr.length) len = arr.length;
32 for (var i = 0, arr2 = new Array(len); i < len; i++) arr2[i] = arr[i];
33 return arr2;
34}
35function _createForOfIteratorHelperLoose(o, allowArrayLike) {
36 var it = typeof Symbol !== "undefined" && o[Symbol.iterator] || o["@@iterator"];
37 if (it) return (it = it.call(o)).next.bind(it);
38 if (Array.isArray(o) || (it = _unsupportedIterableToArray(o)) || allowArrayLike && o && typeof o.length === "number") {
39 if (it) o = it;
40 var i = 0;
41 return function () {
42 if (i >= o.length) return {
43 done: true
44 };
45 return {
46 done: false,
47 value: o[i++]
48 };
49 };
50 }
51 throw new TypeError("Invalid attempt to iterate non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.");
52}
53
54function atomFamily(initializeAtom, areEqual) {
55 var shouldRemove = null;
56 var atoms = new Map();
57 var createAtom = function createAtom(param) {
58 var item;
59 if (areEqual === undefined) {
60 item = atoms.get(param);
61 } else {
62 for (var _iterator = _createForOfIteratorHelperLoose(atoms), _step; !(_step = _iterator()).done;) {
63 var _step$value = _step.value,
64 key = _step$value[0],
65 value = _step$value[1];
66 if (areEqual(key, param)) {
67 item = value;
68 break;
69 }
70 }
71 }
72 if (item !== undefined) {
73 if (shouldRemove != null && shouldRemove(item[1], param)) {
74 createAtom.remove(param);
75 } else {
76 return item[0];
77 }
78 }
79 var newAtom = initializeAtom(param);
80 atoms.set(param, [newAtom, Date.now()]);
81 return newAtom;
82 };
83 createAtom.remove = function (param) {
84 if (areEqual === undefined) {
85 atoms.delete(param);
86 } else {
87 for (var _iterator2 = _createForOfIteratorHelperLoose(atoms), _step2; !(_step2 = _iterator2()).done;) {
88 var _step2$value = _step2.value,
89 key = _step2$value[0];
90 if (areEqual(key, param)) {
91 atoms.delete(key);
92 break;
93 }
94 }
95 }
96 };
97 createAtom.setShouldRemove = function (fn) {
98 shouldRemove = fn;
99 if (!shouldRemove) return;
100 for (var _iterator3 = _createForOfIteratorHelperLoose(atoms), _step3; !(_step3 = _iterator3()).done;) {
101 var _step3$value = _step3.value,
102 key = _step3$value[0],
103 value = _step3$value[1];
104 if (shouldRemove(value[1], key)) {
105 atoms.delete(key);
106 }
107 }
108 };
109 return createAtom;
110}
111
112var getCached$1 = function getCached(c, m, k) {
113 return (m.has(k) ? m : m.set(k, c())).get(k);
114};
115var cache1$4 = new WeakMap();
116var memo3 = function memo3(create, dep1, dep2, dep3) {
117 var cache2 = getCached$1(function () {
118 return new WeakMap();
119 }, cache1$4, dep1);
120 var cache3 = getCached$1(function () {
121 return new WeakMap();
122 }, cache2, dep2);
123 return getCached$1(create, cache3, dep3);
124};
125function selectAtom(anAtom, selector, equalityFn) {
126 if (equalityFn === void 0) {
127 equalityFn = Object.is;
128 }
129 return memo3(function () {
130 var refAtom = vanilla.atom(function () {
131 return {};
132 });
133 var derivedAtom = vanilla.atom(function (get) {
134 var ref = get(refAtom);
135 var selectValue = function selectValue(value) {
136 var slice = selector(value);
137 if ('prev' in ref && equalityFn(ref.prev, slice)) {
138 return ref.prev;
139 }
140 return ref.prev = slice;
141 };
142 var value = get(anAtom);
143 if (value instanceof Promise) {
144 return value.then(selectValue);
145 }
146 return selectValue(value);
147 });
148 return derivedAtom;
149 }, anAtom, selector, equalityFn);
150}
151
152var cache1$3 = new WeakMap();
153var memo1$2 = function memo1(create, dep1) {
154 return (cache1$3.has(dep1) ? cache1$3 : cache1$3.set(dep1, create())).get(dep1);
155};
156var deepFreeze = function deepFreeze(obj) {
157 if (typeof obj !== 'object' || obj === null) return;
158 Object.freeze(obj);
159 var propNames = Object.getOwnPropertyNames(obj);
160 for (var _iterator = _createForOfIteratorHelperLoose(propNames), _step; !(_step = _iterator()).done;) {
161 var name = _step.value;
162 var value = obj[name];
163 deepFreeze(value);
164 }
165 return obj;
166};
167function freezeAtom(anAtom) {
168 return memo1$2(function () {
169 var frozenAtom = vanilla.atom(function (get) {
170 return deepFreeze(get(anAtom));
171 }, function (_get, set, arg) {
172 return set(anAtom, arg);
173 });
174 return frozenAtom;
175 }, anAtom);
176}
177function freezeAtomCreator(createAtom) {
178 return function () {
179 var anAtom = createAtom.apply(void 0, arguments);
180 var origRead = anAtom.read;
181 anAtom.read = function (get, options) {
182 return deepFreeze(origRead(get, options));
183 };
184 return anAtom;
185 };
186}
187
188var getCached = function getCached(c, m, k) {
189 return (m.has(k) ? m : m.set(k, c())).get(k);
190};
191var cache1$2 = new WeakMap();
192var memo2 = function memo2(create, dep1, dep2) {
193 var cache2 = getCached(function () {
194 return new WeakMap();
195 }, cache1$2, dep1);
196 return getCached(create, cache2, dep2);
197};
198var cacheKeyForEmptyKeyExtractor = {};
199var isWritable = function isWritable(atom) {
200 return !!atom.write;
201};
202var isFunction = function isFunction(x) {
203 return typeof x === 'function';
204};
205function splitAtom(arrAtom, keyExtractor) {
206 return memo2(function () {
207 var mappingCache = new WeakMap();
208 var getMapping = function getMapping(arr, prev) {
209 var mapping = mappingCache.get(arr);
210 if (mapping) {
211 return mapping;
212 }
213 var prevMapping = prev && mappingCache.get(prev);
214 var atomList = [];
215 var keyList = [];
216 arr.forEach(function (item, index) {
217 var key = keyExtractor ? keyExtractor(item) : index;
218 keyList[index] = key;
219 var cachedAtom = prevMapping && prevMapping.atomList[prevMapping.keyList.indexOf(key)];
220 if (cachedAtom) {
221 atomList[index] = cachedAtom;
222 return;
223 }
224 var read = function read(get) {
225 var ref = get(refAtom);
226 var currArr = get(arrAtom);
227 var mapping = getMapping(currArr, ref.prev);
228 var index = mapping.keyList.indexOf(key);
229 if (index < 0 || index >= currArr.length) {
230 var prevItem = arr[getMapping(arr).keyList.indexOf(key)];
231 if (prevItem) {
232 return prevItem;
233 }
234 throw new Error('splitAtom: index out of bounds for read');
235 }
236 return currArr[index];
237 };
238 var write = function write(get, set, update) {
239 var ref = get(refAtom);
240 var arr = get(arrAtom);
241 var mapping = getMapping(arr, ref.prev);
242 var index = mapping.keyList.indexOf(key);
243 if (index < 0 || index >= arr.length) {
244 throw new Error('splitAtom: index out of bounds for write');
245 }
246 var nextItem = isFunction(update) ? update(arr[index]) : update;
247 set(arrAtom, [].concat(arr.slice(0, index), [nextItem], arr.slice(index + 1)));
248 };
249 atomList[index] = isWritable(arrAtom) ? vanilla.atom(read, write) : vanilla.atom(read);
250 });
251 if (prevMapping && prevMapping.keyList.length === keyList.length && prevMapping.keyList.every(function (x, i) {
252 return x === keyList[i];
253 })) {
254 mapping = prevMapping;
255 } else {
256 mapping = {
257 atomList: atomList,
258 keyList: keyList
259 };
260 }
261 mappingCache.set(arr, mapping);
262 return mapping;
263 };
264 var refAtom = vanilla.atom(function () {
265 return {};
266 });
267 var read = function read(get) {
268 var ref = get(refAtom);
269 var arr = get(arrAtom);
270 var mapping = getMapping(arr, ref.prev);
271 ref.prev = arr;
272 return mapping.atomList;
273 };
274 var write = function write(get, set, action) {
275 switch (action.type) {
276 case 'remove':
277 {
278 var index = get(splittedAtom).indexOf(action.atom);
279 if (index >= 0) {
280 var arr = get(arrAtom);
281 set(arrAtom, [].concat(arr.slice(0, index), arr.slice(index + 1)));
282 }
283 break;
284 }
285 case 'insert':
286 {
287 var _index = action.before ? get(splittedAtom).indexOf(action.before) : get(splittedAtom).length;
288 if (_index >= 0) {
289 var _arr = get(arrAtom);
290 set(arrAtom, [].concat(_arr.slice(0, _index), [action.value], _arr.slice(_index)));
291 }
292 break;
293 }
294 case 'move':
295 {
296 var index1 = get(splittedAtom).indexOf(action.atom);
297 var index2 = action.before ? get(splittedAtom).indexOf(action.before) : get(splittedAtom).length;
298 if (index1 >= 0 && index2 >= 0) {
299 var _arr2 = get(arrAtom);
300 if (index1 < index2) {
301 set(arrAtom, [].concat(_arr2.slice(0, index1), _arr2.slice(index1 + 1, index2), [_arr2[index1]], _arr2.slice(index2)));
302 } else {
303 set(arrAtom, [].concat(_arr2.slice(0, index2), [_arr2[index1]], _arr2.slice(index2, index1), _arr2.slice(index1 + 1)));
304 }
305 }
306 break;
307 }
308 }
309 };
310 var splittedAtom = isWritable(arrAtom) ? vanilla.atom(read, write) : vanilla.atom(read);
311 return splittedAtom;
312 }, arrAtom, keyExtractor || cacheKeyForEmptyKeyExtractor);
313}
314
315var updateValue = function updateValue(prevValue, update) {
316 return typeof update === 'function' ? update(prevValue) : update;
317};
318function atomWithDefault(getDefault) {
319 var EMPTY = Symbol();
320 var overwrittenAtom = vanilla.atom(EMPTY);
321 var anAtom = vanilla.atom(function (get, options) {
322 var overwritten = get(overwrittenAtom);
323 if (overwritten !== EMPTY) {
324 return overwritten;
325 }
326 return getDefault(get, options);
327 }, function (get, set, update) {
328 if (update === RESET) {
329 return set(overwrittenAtom, EMPTY);
330 }
331 var prevValue = get(anAtom);
332 if (prevValue instanceof Promise) {
333 return prevValue.then(function (v) {
334 return set(overwrittenAtom, updateValue(v, update));
335 });
336 }
337 return set(overwrittenAtom, updateValue(prevValue, update));
338 });
339 return anAtom;
340}
341
342var NO_STORAGE_VALUE = Symbol();
343function createJSONStorage(getStringStorage) {
344 var lastStr;
345 var lastValue;
346 var storage = {
347 getItem: function getItem(key) {
348 var _getStringStorage$get, _getStringStorage;
349 var parse = function parse(str) {
350 str = str || '';
351 if (lastStr !== str) {
352 try {
353 lastValue = JSON.parse(str);
354 } catch (_unused) {
355 return NO_STORAGE_VALUE;
356 }
357 lastStr = str;
358 }
359 return lastValue;
360 };
361 var str = (_getStringStorage$get = (_getStringStorage = getStringStorage()) == null ? void 0 : _getStringStorage.getItem(key)) != null ? _getStringStorage$get : null;
362 if (str instanceof Promise) {
363 return str.then(parse);
364 }
365 return parse(str);
366 },
367 setItem: function setItem(key, newValue) {
368 var _getStringStorage2;
369 return (_getStringStorage2 = getStringStorage()) == null ? void 0 : _getStringStorage2.setItem(key, JSON.stringify(newValue));
370 },
371 removeItem: function removeItem(key) {
372 var _getStringStorage3;
373 return (_getStringStorage3 = getStringStorage()) == null ? void 0 : _getStringStorage3.removeItem(key);
374 }
375 };
376 if (typeof window !== 'undefined' && typeof window.addEventListener === 'function') {
377 storage.subscribe = function (key, callback) {
378 var storageEventCallback = function storageEventCallback(e) {
379 if (e.key === key && e.newValue) {
380 callback(JSON.parse(e.newValue));
381 }
382 };
383 window.addEventListener('storage', storageEventCallback);
384 return function () {
385 window.removeEventListener('storage', storageEventCallback);
386 };
387 };
388 }
389 return storage;
390}
391var defaultStorage = createJSONStorage(function () {
392 return typeof window !== 'undefined' ? window.localStorage : undefined;
393});
394function atomWithStorage(key, initialValue, storage) {
395 if (storage === void 0) {
396 storage = defaultStorage;
397 }
398 var baseAtom = vanilla.atom(initialValue);
399 baseAtom.onMount = function (setAtom) {
400 var value = storage.getItem(key);
401 if (value instanceof Promise) {
402 value.then(function (v) {
403 return setAtom(v === NO_STORAGE_VALUE ? initialValue : v);
404 });
405 } else {
406 setAtom(value === NO_STORAGE_VALUE ? initialValue : value);
407 }
408 var unsub;
409 if (storage.subscribe) {
410 unsub = storage.subscribe(key, setAtom);
411 }
412 return unsub;
413 };
414 var anAtom = vanilla.atom(function (get) {
415 return get(baseAtom);
416 }, function (get, set, update) {
417 var nextValue = typeof update === 'function' ? update(get(baseAtom)) : update;
418 if (nextValue === RESET) {
419 set(baseAtom, initialValue);
420 return storage.removeItem(key);
421 }
422 set(baseAtom, nextValue);
423 return storage.setItem(key, nextValue);
424 });
425 return anAtom;
426}
427
428function atomWithObservable(getObservable, options) {
429 var returnResultData = function returnResultData(result) {
430 if ('e' in result) {
431 throw result.e;
432 }
433 return result.d;
434 };
435 var observableResultAtom = vanilla.atom(function (get) {
436 var _observable$Symbol$ob, _observable;
437 var observable = getObservable(get);
438 var itself = (_observable$Symbol$ob = (_observable = observable)[Symbol.observable]) == null ? void 0 : _observable$Symbol$ob.call(_observable);
439 if (itself) {
440 observable = itself;
441 }
442 var resolve;
443 var makePending = function makePending() {
444 return new Promise(function (r) {
445 resolve = r;
446 });
447 };
448 var initialResult = options && 'initialValue' in options ? {
449 d: typeof options.initialValue === 'function' ? options.initialValue() : options.initialValue
450 } : makePending();
451 var setResult;
452 var lastResult;
453 var listener = function listener(result) {
454 lastResult = result;
455 resolve == null ? void 0 : resolve(result);
456 setResult == null ? void 0 : setResult(result);
457 };
458 var subscription;
459 var timer;
460 var isNotMounted = function isNotMounted() {
461 return !setResult;
462 };
463 var start = function start() {
464 if (subscription) {
465 clearTimeout(timer);
466 subscription.unsubscribe();
467 }
468 subscription = observable.subscribe({
469 next: function next(d) {
470 return listener({
471 d: d
472 });
473 },
474 error: function error(e) {
475 return listener({
476 e: e
477 });
478 },
479 complete: function complete() {}
480 });
481 if (isNotMounted() && options != null && options.unstable_timeout) {
482 timer = setTimeout(function () {
483 if (subscription) {
484 subscription.unsubscribe();
485 subscription = undefined;
486 }
487 }, options.unstable_timeout);
488 }
489 };
490 start();
491 var resultAtom = vanilla.atom(lastResult || initialResult);
492 resultAtom.onMount = function (update) {
493 setResult = update;
494 if (lastResult) {
495 update(lastResult);
496 }
497 if (subscription) {
498 clearTimeout(timer);
499 } else {
500 start();
501 }
502 return function () {
503 setResult = undefined;
504 if (subscription) {
505 subscription.unsubscribe();
506 subscription = undefined;
507 }
508 };
509 };
510 return [resultAtom, observable, makePending, start, isNotMounted];
511 });
512 var observableAtom = vanilla.atom(function (get) {
513 var _get = get(observableResultAtom),
514 resultAtom = _get[0];
515 var result = get(resultAtom);
516 if (result instanceof Promise) {
517 return result.then(returnResultData);
518 }
519 return returnResultData(result);
520 }, function (get, set, data) {
521 var _get2 = get(observableResultAtom),
522 resultAtom = _get2[0],
523 observable = _get2[1],
524 makePending = _get2[2],
525 start = _get2[3],
526 isNotMounted = _get2[4];
527 if ('next' in observable) {
528 if (isNotMounted()) {
529 set(resultAtom, makePending());
530 start();
531 }
532 observable.next(data);
533 } else {
534 throw new Error('observable is not subject');
535 }
536 });
537 return observableAtom;
538}
539
540var cache1$1 = new WeakMap();
541var memo1$1 = function memo1(create, dep1) {
542 return (cache1$1.has(dep1) ? cache1$1 : cache1$1.set(dep1, create())).get(dep1);
543};
544var LOADING = {
545 state: 'loading'
546};
547function loadable(anAtom) {
548 return memo1$1(function () {
549 var loadableCache = new WeakMap();
550 var refreshAtom = vanilla.atom(0);
551 var derivedAtom = vanilla.atom(function (get, _ref) {
552 var setSelf = _ref.setSelf;
553 get(refreshAtom);
554 var promise = get(anAtom);
555 if (!(promise instanceof Promise)) {
556 return {
557 state: 'hasData',
558 data: promise
559 };
560 }
561 var cached = loadableCache.get(promise);
562 if (cached) {
563 return cached;
564 }
565 loadableCache.set(promise, LOADING);
566 promise.then(function (data) {
567 loadableCache.set(promise, {
568 state: 'hasData',
569 data: data
570 });
571 }, function (error) {
572 loadableCache.set(promise, {
573 state: 'hasError',
574 error: error
575 });
576 }).finally(setSelf);
577 return LOADING;
578 }, function (_get, set) {
579 set(refreshAtom, function (c) {
580 return c + 1;
581 });
582 });
583 return vanilla.atom(function (get) {
584 return get(derivedAtom);
585 });
586 }, anAtom);
587}
588
589var cache1 = new WeakMap();
590var memo1 = function memo1(create, dep1) {
591 return (cache1.has(dep1) ? cache1 : cache1.set(dep1, create())).get(dep1);
592};
593function unwrap(anAtom, defaultValue) {
594 return memo1(function () {
595 var refAtom = vanilla.atom(function () {
596 return {};
597 });
598 var refreshAtom = vanilla.atom(0);
599 var derivedAtom = vanilla.atom(function (get, _ref) {
600 var setSelf = _ref.setSelf;
601 get(refreshAtom);
602 var ref = get(refAtom);
603 var promise = get(anAtom);
604 if (ref.p !== promise) {
605 promise.then(function (v) {
606 return ref.v = v;
607 }, function (e) {
608 return ref.e = e;
609 }).finally(setSelf);
610 ref.p = promise;
611 }
612 if ('e' in ref) {
613 throw ref.e;
614 }
615 if ('v' in ref) {
616 return ref.v;
617 }
618 return defaultValue;
619 }, function (_get, set) {
620 set(refreshAtom, function (c) {
621 return c + 1;
622 });
623 });
624 return vanilla.atom(function (get) {
625 return get(derivedAtom);
626 });
627 }, anAtom);
628}
629
630exports.RESET = RESET;
631exports.atomFamily = atomFamily;
632exports.atomWithDefault = atomWithDefault;
633exports.atomWithObservable = atomWithObservable;
634exports.atomWithReducer = atomWithReducer;
635exports.atomWithReset = atomWithReset;
636exports.atomWithStorage = atomWithStorage;
637exports.createJSONStorage = createJSONStorage;
638exports.freezeAtom = freezeAtom;
639exports.freezeAtomCreator = freezeAtomCreator;
640exports.loadable = loadable;
641exports.selectAtom = selectAtom;
642exports.splitAtom = splitAtom;
643exports.unstable_NO_STORAGE_VALUE = NO_STORAGE_VALUE;
644exports.unstable_unwrap = unwrap;