UNPKG

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