UNPKG

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