UNPKG

27.5 kBJavaScriptView Raw
1System.register(['jotai', 'react'], (function (exports) {
2 'use strict';
3 var atom, SECRET_INTERNAL_getScopeContext, useAtom, useSetAtom, SECRET_INTERNAL_registerPromiseAbort, useContext, useCallback, useMemo;
4 return {
5 setters: [function (module) {
6 atom = module.atom;
7 SECRET_INTERNAL_getScopeContext = module.SECRET_INTERNAL_getScopeContext;
8 useAtom = module.useAtom;
9 useSetAtom = module.useSetAtom;
10 SECRET_INTERNAL_registerPromiseAbort = module.SECRET_INTERNAL_registerPromiseAbort;
11 exports({ useAtomValue: module.useAtomValue, useUpdateAtom: module.useSetAtom });
12 }, function (module) {
13 useContext = module.useContext;
14 useCallback = module.useCallback;
15 useMemo = module.useMemo;
16 }],
17 execute: (function () {
18
19 exports({
20 abortableAtom: abortableAtom,
21 atomFamily: atomFamily,
22 atomWithDefault: atomWithDefault,
23 atomWithHash: atomWithHash,
24 atomWithObservable: atomWithObservable,
25 atomWithReducer: atomWithReducer,
26 atomWithReset: atomWithReset,
27 atomWithStorage: atomWithStorage,
28 createJSONStorage: createJSONStorage,
29 freezeAtom: freezeAtom,
30 freezeAtomCreator: freezeAtomCreator,
31 loadable: loadable,
32 selectAtom: selectAtom,
33 splitAtom: splitAtom,
34 useAtomCallback: useAtomCallback,
35 useHydrateAtoms: useHydrateAtoms,
36 useReducerAtom: useReducerAtom,
37 useResetAtom: useResetAtom,
38 waitForAll: waitForAll
39 });
40
41 const RESET = exports('RESET', Symbol());
42
43 function atomWithReset(initialValue) {
44 const anAtom = atom(initialValue, (get, set, update) => {
45 const nextValue = typeof update === "function" ? update(get(anAtom)) : update;
46 set(anAtom, nextValue === RESET ? initialValue : nextValue);
47 });
48 return anAtom;
49 }
50
51 const WRITE_ATOM = "w";
52 const RESTORE_ATOMS = "h";
53
54 function useResetAtom(anAtom, scope) {
55 const ScopeContext = SECRET_INTERNAL_getScopeContext(scope);
56 const store = useContext(ScopeContext).s;
57 const setAtom = useCallback(
58 () => store[WRITE_ATOM](anAtom, RESET),
59 [store, anAtom]
60 );
61 return setAtom;
62 }
63
64 function useReducerAtom(anAtom, reducer, scope) {
65 const [state, setState] = useAtom(anAtom, scope);
66 const dispatch = useCallback(
67 (action) => {
68 setState((prev) => reducer(prev, action));
69 },
70 [setState, reducer]
71 );
72 return [state, dispatch];
73 }
74
75 function atomWithReducer(initialValue, reducer) {
76 const anAtom = atom(
77 initialValue,
78 (get, set, action) => set(anAtom, reducer(get(anAtom), action))
79 );
80 return anAtom;
81 }
82
83 function atomFamily(initializeAtom, areEqual) {
84 let shouldRemove = null;
85 const atoms = /* @__PURE__ */ new Map();
86 const createAtom = (param) => {
87 let item;
88 if (areEqual === void 0) {
89 item = atoms.get(param);
90 } else {
91 for (const [key, value] of atoms) {
92 if (areEqual(key, param)) {
93 item = value;
94 break;
95 }
96 }
97 }
98 if (item !== void 0) {
99 if (shouldRemove == null ? void 0 : shouldRemove(item[1], param)) {
100 atoms.delete(param);
101 } else {
102 return item[0];
103 }
104 }
105 const newAtom = initializeAtom(param);
106 atoms.set(param, [newAtom, Date.now()]);
107 return newAtom;
108 };
109 createAtom.remove = (param) => {
110 if (areEqual === void 0) {
111 atoms.delete(param);
112 } else {
113 for (const [key] of atoms) {
114 if (areEqual(key, param)) {
115 atoms.delete(key);
116 break;
117 }
118 }
119 }
120 };
121 createAtom.setShouldRemove = (fn) => {
122 shouldRemove = fn;
123 if (!shouldRemove)
124 return;
125 for (const [key, value] of atoms) {
126 if (shouldRemove(value[1], key)) {
127 atoms.delete(key);
128 }
129 }
130 };
131 return createAtom;
132 }
133
134 const getWeakCacheItem = (cache, deps) => {
135 do {
136 const [dep, ...rest] = deps;
137 const entry = cache.get(dep);
138 if (!entry) {
139 return;
140 }
141 if (!rest.length) {
142 return entry[1];
143 }
144 cache = entry[0];
145 deps = rest;
146 } while (deps.length);
147 };
148 const setWeakCacheItem = (cache, deps, item) => {
149 do {
150 const [dep, ...rest] = deps;
151 let entry = cache.get(dep);
152 if (!entry) {
153 entry = [ new WeakMap()];
154 cache.set(dep, entry);
155 }
156 if (!rest.length) {
157 entry[1] = item;
158 return;
159 }
160 cache = entry[0];
161 deps = rest;
162 } while (deps.length);
163 };
164 const createMemoizeAtom = () => {
165 const cache = /* @__PURE__ */ new WeakMap();
166 const memoizeAtom = (createAtom, deps) => {
167 const cachedAtom = getWeakCacheItem(cache, deps);
168 if (cachedAtom) {
169 return cachedAtom;
170 }
171 const createdAtom = createAtom();
172 setWeakCacheItem(cache, deps, createdAtom);
173 return createdAtom;
174 };
175 return memoizeAtom;
176 };
177
178 const memoizeAtom$4 = createMemoizeAtom();
179 function selectAtom(anAtom, selector, equalityFn = Object.is) {
180 return memoizeAtom$4(() => {
181 const refAtom = atom(() => ({}));
182 const derivedAtom = atom((get) => {
183 const slice = selector(get(anAtom));
184 const ref = get(refAtom);
185 if ("prev" in ref && equalityFn(ref.prev, slice)) {
186 return ref.prev;
187 }
188 ref.prev = slice;
189 return slice;
190 });
191 return derivedAtom;
192 }, [anAtom, selector, equalityFn]);
193 }
194
195 function useAtomCallback(callback, scope) {
196 const anAtom = useMemo(
197 () => atom(
198 null,
199 (get, set, [arg, resolve, reject]) => {
200 try {
201 resolve(callback(get, set, arg));
202 } catch (e) {
203 reject(e);
204 }
205 }
206 ),
207 [callback]
208 );
209 const invoke = useSetAtom(anAtom, scope);
210 return useCallback(
211 (arg) => {
212 let isSync = true;
213 let settled = {};
214 const promise = new Promise((resolve, reject) => {
215 invoke([
216 arg,
217 (v) => {
218 if (isSync) {
219 settled = { v };
220 } else {
221 resolve(v);
222 }
223 },
224 (e) => {
225 if (isSync) {
226 settled = { e };
227 } else {
228 reject(e);
229 }
230 }
231 ]);
232 });
233 isSync = false;
234 if ("e" in settled) {
235 throw settled.e;
236 }
237 if ("v" in settled) {
238 return settled.v;
239 }
240 return promise;
241 },
242 [invoke]
243 );
244 }
245
246 const memoizeAtom$3 = createMemoizeAtom();
247 const deepFreeze = (obj) => {
248 if (typeof obj !== "object" || obj === null)
249 return;
250 Object.freeze(obj);
251 const propNames = Object.getOwnPropertyNames(obj);
252 for (const name of propNames) {
253 const value = obj[name];
254 deepFreeze(value);
255 }
256 return obj;
257 };
258 function freezeAtom(anAtom) {
259 return memoizeAtom$3(() => {
260 const frozenAtom = atom(
261 (get) => deepFreeze(get(anAtom)),
262 (_get, set, arg) => set(anAtom, arg)
263 );
264 return frozenAtom;
265 }, [anAtom]);
266 }
267 function freezeAtomCreator(createAtom) {
268 return (...params) => {
269 const anAtom = createAtom(...params);
270 const origRead = anAtom.read;
271 anAtom.read = (get) => deepFreeze(origRead(get));
272 return anAtom;
273 };
274 }
275
276 const memoizeAtom$2 = createMemoizeAtom();
277 const isWritable = (atom2) => !!atom2.write;
278 const isFunction = (x) => typeof x === "function";
279 function splitAtom(arrAtom, keyExtractor) {
280 return memoizeAtom$2(
281 () => {
282 const mappingCache = /* @__PURE__ */ new WeakMap();
283 const getMapping = (arr, prev) => {
284 let mapping = mappingCache.get(arr);
285 if (mapping) {
286 return mapping;
287 }
288 const prevMapping = prev && mappingCache.get(prev);
289 const atomList = [];
290 const keyList = [];
291 arr.forEach((item, index) => {
292 const key = keyExtractor ? keyExtractor(item) : index;
293 keyList[index] = key;
294 const cachedAtom = prevMapping && prevMapping.atomList[prevMapping.keyList.indexOf(key)];
295 if (cachedAtom) {
296 atomList[index] = cachedAtom;
297 return;
298 }
299 const read2 = (get) => {
300 const ref = get(refAtom);
301 const currArr = get(arrAtom);
302 const mapping2 = getMapping(currArr, ref.prev);
303 const index2 = mapping2.keyList.indexOf(key);
304 if (index2 < 0 || index2 >= currArr.length) {
305 const prevItem = arr[getMapping(arr).keyList.indexOf(key)];
306 if (prevItem) {
307 return prevItem;
308 }
309 throw new Error("splitAtom: index out of bounds for read");
310 }
311 return currArr[index2];
312 };
313 const write2 = (get, set, update) => {
314 const ref = get(refAtom);
315 const arr2 = get(arrAtom);
316 const mapping2 = getMapping(arr2, ref.prev);
317 const index2 = mapping2.keyList.indexOf(key);
318 if (index2 < 0 || index2 >= arr2.length) {
319 throw new Error("splitAtom: index out of bounds for write");
320 }
321 const nextItem = isFunction(update) ? update(arr2[index2]) : update;
322 set(arrAtom, [
323 ...arr2.slice(0, index2),
324 nextItem,
325 ...arr2.slice(index2 + 1)
326 ]);
327 };
328 atomList[index] = isWritable(arrAtom) ? atom(read2, write2) : atom(read2);
329 });
330 if (prevMapping && prevMapping.keyList.length === keyList.length && prevMapping.keyList.every((x, i) => x === keyList[i])) {
331 mapping = prevMapping;
332 } else {
333 mapping = { atomList, keyList };
334 }
335 mappingCache.set(arr, mapping);
336 return mapping;
337 };
338 const refAtom = atom(() => ({}));
339 const read = (get) => {
340 const ref = get(refAtom);
341 const arr = get(arrAtom);
342 const mapping = getMapping(arr, ref.prev);
343 ref.prev = arr;
344 return mapping.atomList;
345 };
346 const write = (get, set, action) => {
347 if ("read" in action) {
348 console.warn("atomToRemove is deprecated. use action with type");
349 action = { type: "remove", atom: action };
350 }
351 switch (action.type) {
352 case "remove": {
353 const index = get(splittedAtom).indexOf(action.atom);
354 if (index >= 0) {
355 const arr = get(arrAtom);
356 set(arrAtom, [
357 ...arr.slice(0, index),
358 ...arr.slice(index + 1)
359 ]);
360 }
361 break;
362 }
363 case "insert": {
364 const index = action.before ? get(splittedAtom).indexOf(action.before) : get(splittedAtom).length;
365 if (index >= 0) {
366 const arr = get(arrAtom);
367 set(arrAtom, [
368 ...arr.slice(0, index),
369 action.value,
370 ...arr.slice(index)
371 ]);
372 }
373 break;
374 }
375 case "move": {
376 const index1 = get(splittedAtom).indexOf(action.atom);
377 const index2 = action.before ? get(splittedAtom).indexOf(action.before) : get(splittedAtom).length;
378 if (index1 >= 0 && index2 >= 0) {
379 const arr = get(arrAtom);
380 if (index1 < index2) {
381 set(arrAtom, [
382 ...arr.slice(0, index1),
383 ...arr.slice(index1 + 1, index2),
384 arr[index1],
385 ...arr.slice(index2)
386 ]);
387 } else {
388 set(arrAtom, [
389 ...arr.slice(0, index2),
390 arr[index1],
391 ...arr.slice(index2, index1),
392 ...arr.slice(index1 + 1)
393 ]);
394 }
395 }
396 break;
397 }
398 }
399 };
400 const splittedAtom = isWritable(arrAtom) ? atom(read, write) : atom(read);
401 return splittedAtom;
402 },
403 keyExtractor ? [arrAtom, keyExtractor] : [arrAtom]
404 );
405 }
406
407 function atomWithDefault(getDefault) {
408 const EMPTY = Symbol();
409 const overwrittenAtom = atom(EMPTY);
410 const anAtom = atom(
411 (get) => {
412 const overwritten = get(overwrittenAtom);
413 if (overwritten !== EMPTY) {
414 return overwritten;
415 }
416 return getDefault(get);
417 },
418 (get, set, update) => {
419 if (update === RESET) {
420 return set(overwrittenAtom, EMPTY);
421 }
422 return set(
423 overwrittenAtom,
424 typeof update === "function" ? update(get(anAtom)) : update
425 );
426 }
427 );
428 return anAtom;
429 }
430
431 const memoizeAtom$1 = createMemoizeAtom();
432 const emptyArrayAtom = atom(() => []);
433 function waitForAll(atoms) {
434 const createAtom = () => {
435 const unwrappedAtoms = unwrapAtoms(atoms);
436 const derivedAtom = atom((get) => {
437 const promises = [];
438 const values = unwrappedAtoms.map((anAtom, index) => {
439 try {
440 return get(anAtom);
441 } catch (e) {
442 if (e instanceof Promise) {
443 promises[index] = e;
444 } else {
445 throw e;
446 }
447 }
448 });
449 if (promises.length) {
450 throw Promise.all(promises);
451 }
452 return wrapResults(atoms, values);
453 });
454 return derivedAtom;
455 };
456 if (Array.isArray(atoms)) {
457 if (atoms.length) {
458 return memoizeAtom$1(createAtom, atoms);
459 }
460 return emptyArrayAtom;
461 }
462 return createAtom();
463 }
464 const unwrapAtoms = (atoms) => Array.isArray(atoms) ? atoms : Object.getOwnPropertyNames(atoms).map((key) => atoms[key]);
465 const wrapResults = (atoms, results) => Array.isArray(atoms) ? results : Object.getOwnPropertyNames(atoms).reduce(
466 (out, key, idx) => ({ ...out, [key]: results[idx] }),
467 {}
468 );
469
470 function createJSONStorage(getStringStorage) {
471 let lastStr;
472 let lastValue;
473 return {
474 getItem: (key) => {
475 const parse = (str2) => {
476 str2 = str2 || "";
477 if (lastStr !== str2) {
478 lastValue = JSON.parse(str2);
479 lastStr = str2;
480 }
481 return lastValue;
482 };
483 const str = getStringStorage().getItem(key);
484 if (str instanceof Promise) {
485 return str.then(parse);
486 }
487 return parse(str);
488 },
489 setItem: (key, newValue) => getStringStorage().setItem(key, JSON.stringify(newValue)),
490 removeItem: (key) => getStringStorage().removeItem(key)
491 };
492 }
493 const defaultStorage = createJSONStorage(() => localStorage);
494 defaultStorage.subscribe = (key, callback) => {
495 const storageEventCallback = (e) => {
496 if (e.key === key && e.newValue) {
497 callback(JSON.parse(e.newValue));
498 }
499 };
500 window.addEventListener("storage", storageEventCallback);
501 return () => {
502 window.removeEventListener("storage", storageEventCallback);
503 };
504 };
505 function atomWithStorage(key, initialValue, storage = defaultStorage) {
506 const getInitialValue = () => {
507 try {
508 const value = storage.getItem(key);
509 if (value instanceof Promise) {
510 return value.catch(() => initialValue);
511 }
512 return value;
513 } catch {
514 return initialValue;
515 }
516 };
517 const baseAtom = atom(storage.delayInit ? initialValue : getInitialValue());
518 baseAtom.onMount = (setAtom) => {
519 let unsub;
520 if (storage.subscribe) {
521 unsub = storage.subscribe(key, setAtom);
522 setAtom(getInitialValue());
523 }
524 if (storage.delayInit) {
525 const value = getInitialValue();
526 if (value instanceof Promise) {
527 value.then(setAtom);
528 } else {
529 setAtom(value);
530 }
531 }
532 return unsub;
533 };
534 const anAtom = atom(
535 (get) => get(baseAtom),
536 (get, set, update) => {
537 const nextValue = typeof update === "function" ? update(get(baseAtom)) : update;
538 if (nextValue === RESET) {
539 set(baseAtom, initialValue);
540 return storage.removeItem(key);
541 }
542 set(baseAtom, nextValue);
543 return storage.setItem(key, nextValue);
544 }
545 );
546 return anAtom;
547 }
548 function atomWithHash(key, initialValue, options) {
549 const serialize = (options == null ? void 0 : options.serialize) || JSON.stringify;
550 const deserialize = (options == null ? void 0 : options.deserialize) || JSON.parse;
551 const subscribe = (options == null ? void 0 : options.subscribe) || ((callback) => {
552 window.addEventListener("hashchange", callback);
553 return () => {
554 window.removeEventListener("hashchange", callback);
555 };
556 });
557 const hashStorage = {
558 getItem: (key2) => {
559 const searchParams = new URLSearchParams(location.hash.slice(1));
560 const storedValue = searchParams.get(key2);
561 if (storedValue === null) {
562 throw new Error("no value stored");
563 }
564 return deserialize(storedValue);
565 },
566 setItem: (key2, newValue) => {
567 const searchParams = new URLSearchParams(location.hash.slice(1));
568 searchParams.set(key2, serialize(newValue));
569 if (options == null ? void 0 : options.replaceState) {
570 history.replaceState(null, "", "#" + searchParams.toString());
571 } else {
572 location.hash = searchParams.toString();
573 }
574 },
575 removeItem: (key2) => {
576 const searchParams = new URLSearchParams(location.hash.slice(1));
577 searchParams.delete(key2);
578 if (options == null ? void 0 : options.replaceState) {
579 history.replaceState(null, "", "#" + searchParams.toString());
580 } else {
581 location.hash = searchParams.toString();
582 }
583 },
584 ...(options == null ? void 0 : options.delayInit) && { delayInit: true },
585 subscribe: (key2, setValue) => {
586 const callback = () => {
587 const searchParams = new URLSearchParams(location.hash.slice(1));
588 const str = searchParams.get(key2);
589 if (str !== null) {
590 setValue(deserialize(str));
591 } else {
592 setValue(initialValue);
593 }
594 };
595 return subscribe(callback);
596 }
597 };
598 return atomWithStorage(key, initialValue, hashStorage);
599 }
600
601 function atomWithObservable(createObservable, options) {
602 const observableResultAtom = atom((get) => {
603 var _a;
604 let observable = createObservable(get);
605 const itself = (_a = observable[Symbol.observable]) == null ? void 0 : _a.call(observable);
606 if (itself) {
607 observable = itself;
608 }
609 const EMPTY = Symbol();
610 let resolveEmittedInitialValue = null;
611 let initialEmittedValue = (options == null ? void 0 : options.initialValue) === void 0 ? new Promise((resolve) => {
612 resolveEmittedInitialValue = resolve;
613 }) : void 0;
614 let initialValueWasEmitted = false;
615 let emittedValueBeforeMount = EMPTY;
616 let isSync = true;
617 let setData = (data) => {
618 if ((options == null ? void 0 : options.initialValue) === void 0 && !initialValueWasEmitted) {
619 if (isSync) {
620 initialEmittedValue = data;
621 }
622 resolveEmittedInitialValue == null ? void 0 : resolveEmittedInitialValue(data);
623 initialValueWasEmitted = true;
624 resolveEmittedInitialValue = null;
625 } else {
626 emittedValueBeforeMount = data;
627 }
628 };
629 const dataListener = (data) => {
630 setData(data);
631 };
632 const errorListener = (error) => {
633 setData(Promise.reject(error));
634 };
635 let subscription = null;
636 let initialValue;
637 if ((options == null ? void 0 : options.initialValue) !== void 0) {
638 initialValue = getInitialValue(options);
639 } else {
640 subscription = observable.subscribe(dataListener, errorListener);
641 initialValue = initialEmittedValue;
642 }
643 isSync = false;
644 const dataAtom = atom(initialValue);
645 dataAtom.onMount = (update) => {
646 setData = update;
647 if (emittedValueBeforeMount !== EMPTY) {
648 update(emittedValueBeforeMount);
649 }
650 if (!subscription) {
651 subscription = observable.subscribe(dataListener, errorListener);
652 }
653 return () => {
654 subscription == null ? void 0 : subscription.unsubscribe();
655 subscription = null;
656 };
657 };
658 return { dataAtom, observable };
659 });
660 const observableAtom = atom(
661 (get) => {
662 const { dataAtom } = get(observableResultAtom);
663 return get(dataAtom);
664 },
665 (get, set, data) => {
666 const { dataAtom, observable } = get(observableResultAtom);
667 if ("next" in observable) {
668 let subscription = null;
669 const callback = (data2) => {
670 set(dataAtom, data2);
671 subscription == null ? void 0 : subscription.unsubscribe();
672 };
673 subscription = observable.subscribe(callback);
674 observable.next(data);
675 } else {
676 throw new Error("observable is not subject");
677 }
678 }
679 );
680 return observableAtom;
681 }
682 function getInitialValue(options) {
683 const initialValue = options.initialValue;
684 return initialValue instanceof Function ? initialValue() : initialValue;
685 }
686
687 const hydratedMap = /* @__PURE__ */ new WeakMap();
688 function useHydrateAtoms(values, scope) {
689 const ScopeContext = SECRET_INTERNAL_getScopeContext(scope);
690 const scopeContainer = useContext(ScopeContext);
691 const store = scopeContainer.s;
692 const hydratedSet = getHydratedSet(scopeContainer);
693 const tuplesToRestore = [];
694 for (const tuple of values) {
695 const atom = tuple[0];
696 if (!hydratedSet.has(atom)) {
697 hydratedSet.add(atom);
698 tuplesToRestore.push(tuple);
699 }
700 }
701 if (tuplesToRestore.length) {
702 store[RESTORE_ATOMS](tuplesToRestore);
703 }
704 }
705 function getHydratedSet(scopeContainer) {
706 let hydratedSet = hydratedMap.get(scopeContainer);
707 if (!hydratedSet) {
708 hydratedSet = /* @__PURE__ */ new WeakSet();
709 hydratedMap.set(scopeContainer, hydratedSet);
710 }
711 return hydratedSet;
712 }
713
714 const memoizeAtom = createMemoizeAtom();
715 const LOADING = { state: "loading" };
716 function loadable(anAtom) {
717 return memoizeAtom(() => {
718 const loadableAtomCache = /* @__PURE__ */ new WeakMap();
719 const catchAtom = atom((get) => {
720 let promise;
721 try {
722 const data = get(anAtom);
723 const loadableAtom2 = atom({ state: "hasData", data });
724 return loadableAtom2;
725 } catch (error) {
726 if (error instanceof Promise) {
727 promise = error;
728 } else {
729 const loadableAtom2 = atom({
730 state: "hasError",
731 error
732 });
733 return loadableAtom2;
734 }
735 }
736 const cached = loadableAtomCache.get(promise);
737 if (cached) {
738 return cached;
739 }
740 const loadableAtom = atom(
741 LOADING,
742 async (get2, set) => {
743 try {
744 const data = await get2(anAtom, { unstable_promise: true });
745 set(loadableAtom, { state: "hasData", data });
746 } catch (error) {
747 set(loadableAtom, { state: "hasError", error });
748 }
749 }
750 );
751 loadableAtom.onMount = (init) => {
752 init();
753 };
754 loadableAtomCache.set(promise, loadableAtom);
755 return loadableAtom;
756 });
757 const derivedAtom = atom((get) => {
758 const loadableAtom = get(catchAtom);
759 return get(loadableAtom);
760 });
761 return derivedAtom;
762 }, [anAtom]);
763 }
764
765 function abortableAtom(read, write) {
766 return atom((get) => {
767 const controller = new AbortController();
768 const promise = read(get, { signal: controller.signal });
769 if (promise instanceof Promise) {
770 SECRET_INTERNAL_registerPromiseAbort(promise, () => controller.abort());
771 }
772 return promise;
773 }, write);
774 }
775
776 })
777 };
778}));