-
-
Notifications
You must be signed in to change notification settings - Fork 661
/
Copy pathstore.ts
811 lines (765 loc) · 24.1 KB
/
store.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
import type { Atom, WritableAtom } from './atom.ts'
type AnyValue = unknown
type AnyError = unknown
type AnyAtom = Atom<AnyValue>
type AnyWritableAtom = WritableAtom<AnyValue, unknown[], unknown>
type OnUnmount = () => void
type Getter = Parameters<AnyAtom['read']>[0]
type Setter = Parameters<AnyWritableAtom['write']>[1]
const hasInitialValue = <T extends Atom<AnyValue>>(
atom: T
): atom is T & (T extends Atom<infer Value> ? { init: Value } : never) =>
'init' in atom
const isActuallyWritableAtom = (atom: AnyAtom): atom is AnyWritableAtom =>
!!(atom as AnyWritableAtom).write
type CancelPromise = (next?: Promise<unknown>) => void
const cancelPromiseMap = new WeakMap<Promise<unknown>, CancelPromise>()
const registerCancelPromise = (
promise: Promise<unknown>,
cancel: CancelPromise
) => {
cancelPromiseMap.set(promise, cancel)
promise.catch(() => {}).finally(() => cancelPromiseMap.delete(promise))
}
const cancelPromise = (promise: Promise<unknown>, next?: Promise<unknown>) => {
const cancel = cancelPromiseMap.get(promise)
if (cancel) {
cancelPromiseMap.delete(promise)
cancel(next)
}
}
type PromiseMeta<T> = {
status?: 'pending' | 'fulfilled' | 'rejected'
value?: T
reason?: AnyError
orig?: PromiseLike<T>
}
const resolvePromise = <T>(promise: Promise<T> & PromiseMeta<T>, value: T) => {
promise.status = 'fulfilled'
promise.value = value
}
const rejectPromise = <T>(
promise: Promise<T> & PromiseMeta<T>,
e: AnyError
) => {
promise.status = 'rejected'
promise.reason = e
}
const isPromiseLike = (x: unknown): x is PromiseLike<unknown> =>
typeof (x as any)?.then === 'function'
/**
* Immutable map from a dependency to the dependency's atom state
* when it was last read.
* We can skip recomputation of an atom by comparing the atom state
* of each dependency to that dependencies's current revision.
*/
type Dependencies = Map<AnyAtom, AtomState>
type NextDependencies = Map<AnyAtom, AtomState | undefined>
/**
* Immutable atom state,
* tracked for both mounted and unmounted atoms in a store.
*/
type AtomState<Value = AnyValue> = {
d: Dependencies
} & ({ e: AnyError } | { v: Value })
const isEqualAtomValue = <Value>(a: AtomState<Value>, b: AtomState<Value>) =>
'v' in a && 'v' in b && Object.is(a.v, b.v)
const isEqualAtomError = <Value>(a: AtomState<Value>, b: AtomState<Value>) =>
'e' in a && 'e' in b && Object.is(a.e, b.e)
const hasPromiseAtomValue = <Value>(
a: AtomState<Value>
): a is AtomState<Value> & { v: Value & Promise<unknown> } =>
'v' in a && a.v instanceof Promise
const isEqualPromiseAtomValue = <Value>(
a: AtomState<Promise<Value> & PromiseMeta<Value>>,
b: AtomState<Promise<Value> & PromiseMeta<Value>>
) => 'v' in a && 'v' in b && a.v.orig && a.v.orig === b.v.orig
const returnAtomValue = <Value>(atomState: AtomState<Value>): Value => {
if ('e' in atomState) {
throw atomState.e
}
return atomState.v
}
type Listeners = Set<() => void>
type Dependents = Set<AnyAtom>
/**
* State tracked for mounted atoms. An atom is considered "mounted" if it has a
* subscriber, or is a transitive dependency of another atom that has a
* subscriber.
*
* The mounted state of an atom is freed once it is no longer mounted.
*/
type Mounted = {
/** The list of subscriber functions. */
l: Listeners
/** Atoms that depend on *this* atom. Used to fan out invalidation. */
t: Dependents
/** Function to run when the atom is unmounted. */
u?: OnUnmount
}
// for debugging purpose only
type StoreListenerRev2 = (
action:
| { type: 'write'; flushed: Set<AnyAtom> }
| { type: 'async-write'; flushed: Set<AnyAtom> }
| { type: 'sub'; flushed: Set<AnyAtom> }
| { type: 'unsub' }
| { type: 'restore'; flushed: Set<AnyAtom> }
) => void
type MountedAtoms = Set<AnyAtom>
/**
* Create a new store. Each store is an independent, isolated universe of atom
* states.
*
* Jotai atoms are not themselves state containers. When you read or write an
* atom, that state is stored in a store. You can think of a Store like a
* multi-layered map from atoms to states, like this:
*
* ```
* // Conceptually, a Store is a map from atoms to states.
* // The real type is a bit different.
* type Store = Map<VersionObject, Map<Atom, AtomState>>
* ```
*
* @returns A store.
*/
export const createStore = () => {
const atomStateMap = new WeakMap<AnyAtom, AtomState>()
const mountedMap = new WeakMap<AnyAtom, Mounted>()
const pendingMap = new Map<
AnyAtom,
AtomState /* prevAtomState */ | undefined
>()
let storeListenersRev2: Set<StoreListenerRev2>
let mountedAtoms: MountedAtoms
if (import.meta.env?.MODE !== 'production') {
storeListenersRev2 = new Set()
mountedAtoms = new Set()
}
const getAtomState = <Value>(atom: Atom<Value>) =>
atomStateMap.get(atom) as AtomState<Value> | undefined
const setAtomState = <Value>(
atom: Atom<Value>,
atomState: AtomState<Value>
): void => {
if (import.meta.env?.MODE !== 'production') {
Object.freeze(atomState)
}
const prevAtomState = atomStateMap.get(atom)
atomStateMap.set(atom, atomState)
if (!pendingMap.has(atom)) {
pendingMap.set(atom, prevAtomState)
}
if (prevAtomState && hasPromiseAtomValue(prevAtomState)) {
const next =
'v' in atomState
? atomState.v instanceof Promise
? atomState.v
: Promise.resolve(atomState.v)
: Promise.reject(atomState.e)
cancelPromise(prevAtomState.v, next)
}
}
const updateDependencies = <Value>(
atom: Atom<Value>,
nextAtomState: AtomState<Value>,
nextDependencies: NextDependencies
): void => {
const dependencies: Dependencies = new Map()
let changed = false
nextDependencies.forEach((aState, a) => {
if (!aState && a === atom) {
aState = nextAtomState
}
if (aState) {
dependencies.set(a, aState)
if (nextAtomState.d.get(a) !== aState) {
changed = true
}
} else if (import.meta.env?.MODE !== 'production') {
console.warn('[Bug] atom state not found')
}
})
if (changed || nextAtomState.d.size !== dependencies.size) {
nextAtomState.d = dependencies
}
}
const setAtomValue = <Value>(
atom: Atom<Value>,
value: Value,
nextDependencies?: NextDependencies
): AtomState<Value> => {
const prevAtomState = getAtomState(atom)
const nextAtomState: AtomState<Value> = {
d: prevAtomState?.d || new Map(),
v: value,
}
if (nextDependencies) {
updateDependencies(atom, nextAtomState, nextDependencies)
}
if (
prevAtomState &&
isEqualAtomValue(prevAtomState, nextAtomState) &&
prevAtomState.d === nextAtomState.d
) {
// bail out
return prevAtomState
}
if (
prevAtomState &&
hasPromiseAtomValue(prevAtomState) &&
hasPromiseAtomValue(nextAtomState) &&
isEqualPromiseAtomValue(prevAtomState, nextAtomState)
) {
if (prevAtomState.d === nextAtomState.d) {
// bail out
return prevAtomState
} else {
// restore the wrapped promise
nextAtomState.v = prevAtomState.v
}
}
setAtomState(atom, nextAtomState)
return nextAtomState
}
const setAtomValueOrPromise = <Value>(
atom: Atom<Value>,
valueOrPromise: Value,
nextDependencies?: NextDependencies,
abortPromise?: () => void
): AtomState<Value> => {
if (isPromiseLike(valueOrPromise)) {
let continuePromise: (next: Promise<Awaited<Value>>) => void
const promise: Promise<Awaited<Value>> & PromiseMeta<Awaited<Value>> =
new Promise((resolve, reject) => {
let settled = false
valueOrPromise.then(
(v) => {
if (!settled) {
settled = true
const prevAtomState = getAtomState(atom)
// update dependencies, that could have changed
const nextAtomState = setAtomValue(
atom,
promise as Value,
nextDependencies
)
resolvePromise(promise, v)
resolve(v as Awaited<Value>)
if (
mountedMap.has(atom) &&
prevAtomState?.d !== nextAtomState.d
) {
mountDependencies(atom, nextAtomState, prevAtomState?.d)
}
}
},
(e) => {
if (!settled) {
settled = true
const prevAtomState = getAtomState(atom)
// update dependencies, that could have changed
const nextAtomState = setAtomValue(
atom,
promise as Value,
nextDependencies
)
rejectPromise(promise, e)
reject(e)
if (
mountedMap.has(atom) &&
prevAtomState?.d !== nextAtomState.d
) {
mountDependencies(atom, nextAtomState, prevAtomState?.d)
}
}
}
)
continuePromise = (next) => {
if (!settled) {
settled = true
next.then(
(v) => resolvePromise(promise, v),
(e) => rejectPromise(promise, e)
)
resolve(next)
}
}
})
promise.orig = valueOrPromise as PromiseLike<Awaited<Value>>
promise.status = 'pending'
registerCancelPromise(promise, (next) => {
if (next) {
continuePromise(next as Promise<Awaited<Value>>)
}
abortPromise?.()
})
return setAtomValue(atom, promise as Value, nextDependencies)
}
return setAtomValue(atom, valueOrPromise, nextDependencies)
}
const setAtomError = <Value>(
atom: Atom<Value>,
error: AnyError,
nextDependencies?: NextDependencies
): AtomState<Value> => {
const prevAtomState = getAtomState(atom)
const nextAtomState: AtomState<Value> = {
d: prevAtomState?.d || new Map(),
e: error,
}
if (nextDependencies) {
updateDependencies(atom, nextAtomState, nextDependencies)
}
if (
prevAtomState &&
isEqualAtomError(prevAtomState, nextAtomState) &&
prevAtomState.d === nextAtomState.d
) {
// bail out
return prevAtomState
}
setAtomState(atom, nextAtomState)
return nextAtomState
}
const readAtomState = <Value>(
atom: Atom<Value>,
force?: boolean
): AtomState<Value> => {
// See if we can skip recomputing this atom.
const atomState = getAtomState(atom)
if (!force && atomState) {
// If the atom is mounted, we can use the cache.
// because it should have been updated by dependencies.
if (mountedMap.has(atom)) {
return atomState
}
// Otherwise, check if the dependencies have changed.
// If all dependencies haven't changed, we can use the cache.
if (
Array.from(atomState.d).every(
([a, s]) => a === atom || readAtomState(a) === s
)
) {
return atomState
}
}
// Compute a new state for this atom.
const nextDependencies: NextDependencies = new Map()
let isSync = true
const getter: Getter = <V>(a: Atom<V>) => {
if ((a as AnyAtom) === atom) {
const aState = getAtomState(a)
if (aState) {
nextDependencies.set(a, aState)
return returnAtomValue(aState)
}
if (hasInitialValue(a)) {
nextDependencies.set(a, undefined)
return a.init
}
// NOTE invalid derived atoms can reach here
throw new Error('no atom init')
}
// a !== atom
const aState = readAtomState(a)
nextDependencies.set(a, aState)
return returnAtomValue(aState)
}
let controller: AbortController | undefined
let setSelf: ((...args: unknown[]) => unknown) | undefined
const options = {
get signal() {
if (!controller) {
controller = new AbortController()
}
return controller.signal
},
get setSelf() {
if (
import.meta.env?.MODE !== 'production' &&
!isActuallyWritableAtom(atom)
) {
console.warn('setSelf function cannot be used with read-only atom')
}
if (!setSelf && isActuallyWritableAtom(atom)) {
setSelf = (...args) => {
if (import.meta.env?.MODE !== 'production' && isSync) {
console.warn('setSelf function cannot be called in sync')
}
if (!isSync) {
return writeAtom(atom, ...args)
}
}
}
return setSelf
},
}
try {
const valueOrPromise = atom.read(getter, options as any)
return setAtomValueOrPromise(
atom,
valueOrPromise,
nextDependencies,
() => controller?.abort()
)
} catch (error) {
return setAtomError(atom, error, nextDependencies)
} finally {
isSync = false
}
}
const readAtom = <Value>(atom: Atom<Value>): Value =>
returnAtomValue(readAtomState(atom))
const addAtom = (atom: AnyAtom): Mounted => {
let mounted = mountedMap.get(atom)
if (!mounted) {
mounted = mountAtom(atom)
}
return mounted
}
// FIXME doesn't work with mutually dependent atoms
const canUnmountAtom = (atom: AnyAtom, mounted: Mounted) =>
!mounted.l.size &&
(!mounted.t.size || (mounted.t.size === 1 && mounted.t.has(atom)))
const delAtom = (atom: AnyAtom): void => {
const mounted = mountedMap.get(atom)
if (mounted && canUnmountAtom(atom, mounted)) {
unmountAtom(atom)
}
}
const recomputeDependents = (updatedAtoms: Set<AnyAtom>): void => {
if (!updatedAtoms.size) {
return
}
const dependencyMap = new Map<AnyAtom, Set<AnyAtom>>()
const dirtyMap = new WeakMap<AnyAtom, number>()
const loop1 = (a: AnyAtom) => {
const mounted = mountedMap.get(a)
mounted?.t.forEach((dependent) => {
if (dependent !== a) {
dependencyMap.set(
dependent,
(dependencyMap.get(dependent) || new Set()).add(a)
)
dirtyMap.set(dependent, (dirtyMap.get(dependent) || 0) + 1)
loop1(dependent)
}
})
}
updatedAtoms.forEach(loop1)
const loop2 = (a: AnyAtom) => {
const mounted = mountedMap.get(a)
mounted?.t.forEach((dependent) => {
if (dependent !== a) {
let dirtyCount = dirtyMap.get(dependent)
if (dirtyCount) {
dirtyMap.set(dependent, --dirtyCount)
}
if (!dirtyCount) {
let isChanged = !!dependencyMap.get(dependent)?.size
if (isChanged) {
const prevAtomState = getAtomState(dependent)
const nextAtomState = readAtomState(dependent, true)
isChanged =
!prevAtomState ||
!isEqualAtomValue(prevAtomState, nextAtomState)
}
if (!isChanged) {
dependencyMap.forEach((s) => s.delete(dependent))
}
}
loop2(dependent)
}
})
}
updatedAtoms.forEach(loop2)
updatedAtoms.clear()
}
const writeAtomState = <Value, Args extends unknown[], Result>(
updatedAtoms: Set<AnyAtom>,
atom: WritableAtom<Value, Args, Result>,
...args: Args
): Result => {
let isSync = true
const getter: Getter = <V>(a: Atom<V>) => returnAtomValue(readAtomState(a))
const setter: Setter = <V, As extends unknown[], R>(
a: WritableAtom<V, As, R>,
...args: As
) => {
let r: R | undefined
if ((a as AnyWritableAtom) === atom) {
if (!hasInitialValue(a)) {
// NOTE technically possible but restricted as it may cause bugs
throw new Error('atom not writable')
}
const prevAtomState = getAtomState(a)
const nextAtomState = setAtomValueOrPromise(a, args[0] as V)
if (!prevAtomState || !isEqualAtomValue(prevAtomState, nextAtomState)) {
updatedAtoms.add(a)
}
} else {
r = writeAtomState(updatedAtoms, a as AnyWritableAtom, ...args) as R
}
if (!isSync) {
recomputeDependents(updatedAtoms)
const flushed = flushPending()
if (import.meta.env?.MODE !== 'production') {
storeListenersRev2.forEach((l) =>
l({ type: 'async-write', flushed: flushed as Set<AnyAtom> })
)
}
}
return r as R
}
const result = atom.write(getter, setter, ...args)
isSync = false
return result
}
const writeAtom = <Value, Args extends unknown[], Result>(
atom: WritableAtom<Value, Args, Result>,
...args: Args
): Result => {
const updatedAtoms = new Set<AnyAtom>()
const result = writeAtomState(updatedAtoms, atom, ...args)
recomputeDependents(updatedAtoms)
const flushed = flushPending()
if (import.meta.env?.MODE !== 'production') {
storeListenersRev2.forEach((l) =>
l({ type: 'write', flushed: flushed as Set<AnyAtom> })
)
}
return result
}
const mountAtom = <Value>(
atom: Atom<Value>,
initialDependent?: AnyAtom,
onMountQueue?: (() => void)[]
): Mounted => {
const queue = onMountQueue || []
// mount dependencies before mounting self
getAtomState(atom)?.d.forEach((_, a) => {
const aMounted = mountedMap.get(a)
if (aMounted) {
aMounted.t.add(atom) // add dependent
} else {
if (a !== atom) {
mountAtom(a, atom, queue)
}
}
})
// recompute atom state
readAtomState(atom)
// mount self
const mounted: Mounted = {
t: new Set(initialDependent && [initialDependent]),
l: new Set(),
}
mountedMap.set(atom, mounted)
if (import.meta.env?.MODE !== 'production') {
mountedAtoms.add(atom)
}
// onMount
if (isActuallyWritableAtom(atom) && atom.onMount) {
const { onMount } = atom
queue.push(() => {
const onUnmount = onMount((...args) => writeAtom(atom, ...args))
if (onUnmount) {
mounted.u = onUnmount
}
})
}
if (!onMountQueue) {
queue.forEach((f) => f())
}
return mounted
}
const unmountAtom = <Value>(atom: Atom<Value>): void => {
// unmount self
const onUnmount = mountedMap.get(atom)?.u
if (onUnmount) {
onUnmount()
}
mountedMap.delete(atom)
if (import.meta.env?.MODE !== 'production') {
mountedAtoms.delete(atom)
}
// unmount dependencies afterward
const atomState = getAtomState(atom)
if (atomState) {
// cancel promise
if (hasPromiseAtomValue(atomState)) {
cancelPromise(atomState.v)
}
atomState.d.forEach((_, a) => {
if (a !== atom) {
const mounted = mountedMap.get(a)
if (mounted) {
mounted.t.delete(atom)
if (canUnmountAtom(a, mounted)) {
unmountAtom(a)
}
}
}
})
} else if (import.meta.env?.MODE !== 'production') {
console.warn('[Bug] could not find atom state to unmount', atom)
}
}
const mountDependencies = <Value>(
atom: Atom<Value>,
atomState: AtomState<Value>,
prevDependencies?: Dependencies
): void => {
const depSet = new Set(atomState.d.keys())
prevDependencies?.forEach((_, a) => {
if (depSet.has(a)) {
// not changed
depSet.delete(a)
return
}
const mounted = mountedMap.get(a)
if (mounted) {
mounted.t.delete(atom) // delete from dependents
if (canUnmountAtom(a, mounted)) {
unmountAtom(a)
}
}
})
depSet.forEach((a) => {
const mounted = mountedMap.get(a)
if (mounted) {
mounted.t.add(atom) // add to dependents
} else if (mountedMap.has(atom)) {
// we mount dependencies only when atom is already mounted
// Note: we should revisit this when you find other issues
// https://github.com/pmndrs/jotai/issues/942
mountAtom(a, atom)
}
})
}
const flushPending = (): void | Set<AnyAtom> => {
let flushed: Set<AnyAtom>
if (import.meta.env?.MODE !== 'production') {
flushed = new Set()
}
while (pendingMap.size) {
const pending = Array.from(pendingMap)
pendingMap.clear()
pending.forEach(([atom, prevAtomState]) => {
const atomState = getAtomState(atom)
if (atomState) {
const mounted = mountedMap.get(atom)
if (mounted && atomState.d !== prevAtomState?.d) {
mountDependencies(atom, atomState, prevAtomState?.d)
}
if (
mounted &&
!(
// TODO This seems pretty hacky. Hope to fix it.
// Maybe we could `mountDependencies` in `setAtomState`?
(
prevAtomState &&
!hasPromiseAtomValue(prevAtomState) &&
(isEqualAtomValue(prevAtomState, atomState) ||
isEqualAtomError(prevAtomState, atomState))
)
)
) {
mounted.l.forEach((listener) => listener())
if (import.meta.env?.MODE !== 'production') {
flushed.add(atom)
}
}
} else if (import.meta.env?.MODE !== 'production') {
console.warn('[Bug] no atom state to flush')
}
})
}
if (import.meta.env?.MODE !== 'production') {
// @ts-expect-error Variable 'flushed' is used before being assigned.
return flushed
}
}
const subscribeAtom = (atom: AnyAtom, listener: () => void) => {
const mounted = addAtom(atom)
const flushed = flushPending()
const listeners = mounted.l
listeners.add(listener)
if (import.meta.env?.MODE !== 'production') {
storeListenersRev2.forEach((l) =>
l({ type: 'sub', flushed: flushed as Set<AnyAtom> })
)
}
return () => {
listeners.delete(listener)
delAtom(atom)
if (import.meta.env?.MODE !== 'production') {
// devtools uses this to detect if it _can_ unmount or not
storeListenersRev2.forEach((l) => l({ type: 'unsub' }))
}
}
}
if (import.meta.env?.MODE !== 'production') {
return {
get: readAtom,
set: writeAtom,
sub: subscribeAtom,
// store dev methods (these are tentative and subject to change without notice)
dev_subscribe_store: (l: StoreListenerRev2, rev: 2) => {
if (rev !== 2) {
throw new Error('The current StoreListener revision is 2.')
}
storeListenersRev2.add(l as StoreListenerRev2)
return () => {
storeListenersRev2.delete(l as StoreListenerRev2)
}
},
dev_get_mounted_atoms: () => mountedAtoms.values(),
dev_get_atom_state: (a: AnyAtom) => atomStateMap.get(a),
dev_get_mounted: (a: AnyAtom) => mountedMap.get(a),
dev_restore_atoms: (values: Iterable<readonly [AnyAtom, AnyValue]>) => {
const updatedAtoms = new Set<AnyAtom>()
for (const [atom, valueOrPromise] of values) {
if (hasInitialValue(atom)) {
setAtomValueOrPromise(atom, valueOrPromise)
updatedAtoms.add(atom)
}
}
recomputeDependents(updatedAtoms)
const flushed = flushPending()
storeListenersRev2.forEach((l) =>
l({ type: 'restore', flushed: flushed as Set<AnyAtom> })
)
},
}
}
return {
get: readAtom,
set: writeAtom,
sub: subscribeAtom,
}
}
type Store = ReturnType<typeof createStore>
let defaultStore: Store | undefined
if (import.meta.env?.MODE !== 'production') {
if (typeof (globalThis as any).__NUMBER_OF_JOTAI_INSTANCES__ === 'number') {
++(globalThis as any).__NUMBER_OF_JOTAI_INSTANCES__
} else {
;(globalThis as any).__NUMBER_OF_JOTAI_INSTANCES__ = 1
}
}
export const getDefaultStore = () => {
if (!defaultStore) {
if (
import.meta.env?.MODE !== 'production' &&
(globalThis as any).__NUMBER_OF_JOTAI_INSTANCES__ !== 1
) {
console.warn(
'Detected multiple Jotai instances. It may cause unexpected behavior with the default store. https://github.com/pmndrs/jotai/discussions/2044'
)
}
defaultStore = createStore()
}
return defaultStore
}