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