UNPKG

22.2 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 atoms.delete(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
434function createJSONStorage(getStringStorage) {
435 let lastStr;
436 let lastValue;
437 return {
438 getItem: (key) => {
439 const parse = (str2) => {
440 str2 = str2 || "";
441 if (lastStr !== str2) {
442 lastValue = JSON.parse(str2);
443 lastStr = str2;
444 }
445 return lastValue;
446 };
447 const str = getStringStorage().getItem(key);
448 if (str instanceof Promise) {
449 return str.then(parse);
450 }
451 return parse(str);
452 },
453 setItem: (key, newValue) => getStringStorage().setItem(key, JSON.stringify(newValue)),
454 removeItem: (key) => getStringStorage().removeItem(key)
455 };
456}
457const defaultStorage = createJSONStorage(() => localStorage);
458defaultStorage.subscribe = (key, callback) => {
459 const storageEventCallback = (e) => {
460 if (e.key === key && e.newValue) {
461 callback(JSON.parse(e.newValue));
462 }
463 };
464 window.addEventListener("storage", storageEventCallback);
465 return () => {
466 window.removeEventListener("storage", storageEventCallback);
467 };
468};
469function atomWithStorage(key, initialValue, storage = defaultStorage) {
470 const getInitialValue = () => {
471 try {
472 const value = storage.getItem(key);
473 if (value instanceof Promise) {
474 return value.catch(() => initialValue);
475 }
476 return value;
477 } catch {
478 return initialValue;
479 }
480 };
481 const baseAtom = atom(storage.delayInit ? initialValue : getInitialValue());
482 baseAtom.onMount = (setAtom) => {
483 let unsub;
484 if (storage.subscribe) {
485 unsub = storage.subscribe(key, setAtom);
486 setAtom(getInitialValue());
487 }
488 if (storage.delayInit) {
489 const value = getInitialValue();
490 if (value instanceof Promise) {
491 value.then(setAtom);
492 } else {
493 setAtom(value);
494 }
495 }
496 return unsub;
497 };
498 const anAtom = atom(
499 (get) => get(baseAtom),
500 (get, set, update) => {
501 const nextValue = typeof update === "function" ? update(get(baseAtom)) : update;
502 if (nextValue === RESET) {
503 set(baseAtom, initialValue);
504 return storage.removeItem(key);
505 }
506 set(baseAtom, nextValue);
507 return storage.setItem(key, nextValue);
508 }
509 );
510 return anAtom;
511}
512function atomWithHash(key, initialValue, options) {
513 const serialize = (options == null ? void 0 : options.serialize) || JSON.stringify;
514 const deserialize = (options == null ? void 0 : options.deserialize) || JSON.parse;
515 const subscribe = (options == null ? void 0 : options.subscribe) || ((callback) => {
516 window.addEventListener("hashchange", callback);
517 return () => {
518 window.removeEventListener("hashchange", callback);
519 };
520 });
521 const hashStorage = {
522 getItem: (key2) => {
523 const searchParams = new URLSearchParams(location.hash.slice(1));
524 const storedValue = searchParams.get(key2);
525 if (storedValue === null) {
526 throw new Error("no value stored");
527 }
528 return deserialize(storedValue);
529 },
530 setItem: (key2, newValue) => {
531 const searchParams = new URLSearchParams(location.hash.slice(1));
532 searchParams.set(key2, serialize(newValue));
533 if (options == null ? void 0 : options.replaceState) {
534 history.replaceState(null, "", "#" + searchParams.toString());
535 } else {
536 location.hash = searchParams.toString();
537 }
538 },
539 removeItem: (key2) => {
540 const searchParams = new URLSearchParams(location.hash.slice(1));
541 searchParams.delete(key2);
542 if (options == null ? void 0 : options.replaceState) {
543 history.replaceState(null, "", "#" + searchParams.toString());
544 } else {
545 location.hash = searchParams.toString();
546 }
547 },
548 ...(options == null ? void 0 : options.delayInit) && { delayInit: true },
549 subscribe: (key2, setValue) => {
550 const callback = () => {
551 const searchParams = new URLSearchParams(location.hash.slice(1));
552 const str = searchParams.get(key2);
553 if (str !== null) {
554 setValue(deserialize(str));
555 } else {
556 setValue(initialValue);
557 }
558 };
559 return subscribe(callback);
560 }
561 };
562 return atomWithStorage(key, initialValue, hashStorage);
563}
564
565function atomWithObservable(createObservable, options) {
566 const observableResultAtom = atom((get) => {
567 var _a;
568 let observable = createObservable(get);
569 const itself = (_a = observable[Symbol.observable]) == null ? void 0 : _a.call(observable);
570 if (itself) {
571 observable = itself;
572 }
573 const EMPTY = Symbol();
574 let resolveEmittedInitialValue = null;
575 let initialEmittedValue = (options == null ? void 0 : options.initialValue) === void 0 ? new Promise((resolve) => {
576 resolveEmittedInitialValue = resolve;
577 }) : void 0;
578 let initialValueWasEmitted = false;
579 let emittedValueBeforeMount = EMPTY;
580 let isSync = true;
581 let setData = (data) => {
582 if ((options == null ? void 0 : options.initialValue) === void 0 && !initialValueWasEmitted) {
583 if (isSync) {
584 initialEmittedValue = data;
585 }
586 resolveEmittedInitialValue == null ? void 0 : resolveEmittedInitialValue(data);
587 initialValueWasEmitted = true;
588 resolveEmittedInitialValue = null;
589 } else {
590 emittedValueBeforeMount = data;
591 }
592 };
593 const dataListener = (data) => {
594 setData(data);
595 };
596 const errorListener = (error) => {
597 setData(Promise.reject(error));
598 };
599 let subscription = null;
600 let initialValue;
601 if ((options == null ? void 0 : options.initialValue) !== void 0) {
602 initialValue = getInitialValue(options);
603 } else {
604 subscription = observable.subscribe(dataListener, errorListener);
605 initialValue = initialEmittedValue;
606 }
607 isSync = false;
608 const dataAtom = atom(initialValue);
609 dataAtom.onMount = (update) => {
610 setData = update;
611 if (emittedValueBeforeMount !== EMPTY) {
612 update(emittedValueBeforeMount);
613 }
614 if (!subscription) {
615 subscription = observable.subscribe(dataListener, errorListener);
616 }
617 return () => {
618 subscription == null ? void 0 : subscription.unsubscribe();
619 subscription = null;
620 };
621 };
622 return { dataAtom, observable };
623 });
624 const observableAtom = atom(
625 (get) => {
626 const { dataAtom } = get(observableResultAtom);
627 return get(dataAtom);
628 },
629 (get, set, data) => {
630 const { dataAtom, observable } = get(observableResultAtom);
631 if ("next" in observable) {
632 let subscription = null;
633 const callback = (data2) => {
634 set(dataAtom, data2);
635 subscription == null ? void 0 : subscription.unsubscribe();
636 };
637 subscription = observable.subscribe(callback);
638 observable.next(data);
639 } else {
640 throw new Error("observable is not subject");
641 }
642 }
643 );
644 return observableAtom;
645}
646function getInitialValue(options) {
647 const initialValue = options.initialValue;
648 return initialValue instanceof Function ? initialValue() : initialValue;
649}
650
651const hydratedMap = /* @__PURE__ */ new WeakMap();
652function useHydrateAtoms(values, scope) {
653 const ScopeContext = SECRET_INTERNAL_getScopeContext(scope);
654 const scopeContainer = useContext(ScopeContext);
655 const store = scopeContainer.s;
656 const hydratedSet = getHydratedSet(scopeContainer);
657 const tuplesToRestore = [];
658 for (const tuple of values) {
659 const atom = tuple[0];
660 if (!hydratedSet.has(atom)) {
661 hydratedSet.add(atom);
662 tuplesToRestore.push(tuple);
663 }
664 }
665 if (tuplesToRestore.length) {
666 store[RESTORE_ATOMS](tuplesToRestore);
667 }
668}
669function getHydratedSet(scopeContainer) {
670 let hydratedSet = hydratedMap.get(scopeContainer);
671 if (!hydratedSet) {
672 hydratedSet = /* @__PURE__ */ new WeakSet();
673 hydratedMap.set(scopeContainer, hydratedSet);
674 }
675 return hydratedSet;
676}
677
678const memoizeAtom = createMemoizeAtom();
679const LOADING = { state: "loading" };
680function loadable(anAtom) {
681 return memoizeAtom(() => {
682 const loadableAtomCache = /* @__PURE__ */ new WeakMap();
683 const catchAtom = atom((get) => {
684 let promise;
685 try {
686 const data = get(anAtom);
687 const loadableAtom2 = atom({ state: "hasData", data });
688 return loadableAtom2;
689 } catch (error) {
690 if (error instanceof Promise) {
691 promise = error;
692 } else {
693 const loadableAtom2 = atom({
694 state: "hasError",
695 error
696 });
697 return loadableAtom2;
698 }
699 }
700 const cached = loadableAtomCache.get(promise);
701 if (cached) {
702 return cached;
703 }
704 const loadableAtom = atom(
705 LOADING,
706 async (get2, set) => {
707 try {
708 const data = await get2(anAtom, { unstable_promise: true });
709 set(loadableAtom, { state: "hasData", data });
710 } catch (error) {
711 set(loadableAtom, { state: "hasError", error });
712 }
713 }
714 );
715 loadableAtom.onMount = (init) => {
716 init();
717 };
718 loadableAtomCache.set(promise, loadableAtom);
719 return loadableAtom;
720 });
721 const derivedAtom = atom((get) => {
722 const loadableAtom = get(catchAtom);
723 return get(loadableAtom);
724 });
725 return derivedAtom;
726 }, [anAtom]);
727}
728
729function abortableAtom(read, write) {
730 return atom((get) => {
731 const controller = new AbortController();
732 const promise = read(get, { signal: controller.signal });
733 if (promise instanceof Promise) {
734 SECRET_INTERNAL_registerPromiseAbort(promise, () => controller.abort());
735 }
736 return promise;
737 }, write);
738}
739
740export { RESET, abortableAtom, atomFamily, atomWithDefault, atomWithHash, atomWithObservable, atomWithReducer, atomWithReset, atomWithStorage, createJSONStorage, freezeAtom, freezeAtomCreator, loadable, selectAtom, splitAtom, useAtomCallback, useHydrateAtoms, useReducerAtom, useResetAtom, waitForAll };