-
-
Notifications
You must be signed in to change notification settings - Fork 614
/
vanilla.ts
665 lines (626 loc) · 17.5 KB
/
vanilla.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
import type { Atom, WritableAtom } from './atom'
type AnyAtom = Atom<unknown>
type AnyWritableAtom = WritableAtom<unknown, unknown>
type OnUnmount = () => void
type NonPromise<T> = T extends Promise<infer V> ? V : T
type WriteGetter = Parameters<WritableAtom<unknown, unknown>['write']>[0]
type Setter = Parameters<WritableAtom<unknown, unknown>['write']>[1]
const hasInitialValue = <T extends Atom<unknown>>(
atom: T
): atom is T & (T extends Atom<infer Value> ? { init: Value } : never) =>
'init' in atom
const IS_EQUAL_PROMISE = Symbol()
const INTERRUPT_PROMISE = Symbol()
type InterruptablePromise = Promise<void> & {
[IS_EQUAL_PROMISE]: (p: Promise<void>) => boolean
[INTERRUPT_PROMISE]: () => void
}
const isInterruptablePromise = (
promise: Promise<void>
): promise is InterruptablePromise =>
!!(promise as InterruptablePromise)[INTERRUPT_PROMISE]
const createInterruptablePromise = (
promise: Promise<void>
): InterruptablePromise => {
let interrupt: (() => void) | undefined
const interruptablePromise = new Promise<void>((resolve, reject) => {
interrupt = resolve
promise.then(resolve, reject)
}) as InterruptablePromise
interruptablePromise[IS_EQUAL_PROMISE] = (p: Promise<void>) =>
p === interruptablePromise || p === promise
interruptablePromise[INTERRUPT_PROMISE] = interrupt as () => void
return interruptablePromise
}
type Revision = number
type InvalidatedRevision = number
type ReadDependencies = Map<AnyAtom, Revision>
// immutable atom state
export type AtomState<Value = unknown> = {
e?: Error // read error
p?: InterruptablePromise // read promise
c?: () => void // cancel read promise
w?: Promise<void> // write promise
v?: NonPromise<Value>
r: Revision
i?: InvalidatedRevision
d: ReadDependencies
}
type AtomStateMap = WeakMap<AnyAtom, AtomState>
type Listeners = Set<() => void>
type Dependents = Set<AnyAtom>
type Mounted = {
l: Listeners
d: Dependents
u: OnUnmount | void
}
type MountedMap = WeakMap<AnyAtom, Mounted>
// for debugging purpose only
type StateListener = (updatedAtom: AnyAtom, isNewAtom: boolean) => void
type StateVersion = number
type PendingMap = Map<AnyAtom, ReadDependencies | undefined>
// mutable state
export type State = {
l?: StateListener
v: StateVersion
a: AtomStateMap
m: MountedMap
p: PendingMap
}
export const createState = (
initialValues?: Iterable<readonly [AnyAtom, unknown]>,
stateListener?: StateListener
): State => {
const state: State = {
l: stateListener,
v: 0,
a: new WeakMap(),
m: new WeakMap(),
p: new Map(),
}
if (initialValues) {
for (const [atom, value] of initialValues) {
const atomState: AtomState = { v: value, r: 0, d: new Map() }
if (
typeof process === 'object' &&
process.env.NODE_ENV !== 'production'
) {
Object.freeze(atomState)
if (!hasInitialValue(atom)) {
console.warn(
'Found initial value for derived atom which can cause unexpected behavior',
atom
)
}
}
state.a.set(atom, atomState)
}
}
return state
}
const getAtomState = <Value>(state: State, atom: Atom<Value>) =>
state.a.get(atom) as AtomState<Value> | undefined
const wipAtomState = <Value>(
state: State,
atom: Atom<Value>,
dependencies?: Set<AnyAtom>
): [AtomState<Value>, ReadDependencies] => {
const atomState = getAtomState(state, atom)
const nextAtomState = {
r: 0,
...atomState,
d: dependencies
? new Map(
Array.from(dependencies).map((a) => [
a,
getAtomState(state, a)?.r ?? 0,
])
)
: atomState?.d || new Map(),
}
return [nextAtomState, atomState?.d || new Map()]
}
const setAtomValue = <Value>(
state: State,
atom: Atom<Value>,
value: NonPromise<Value>,
dependencies?: Set<AnyAtom>,
promise?: Promise<void>
): void => {
const [atomState, prevDependencies] = wipAtomState(state, atom, dependencies)
if (promise && !atomState.p?.[IS_EQUAL_PROMISE](promise)) {
// newer async read is running, not updating
return
}
atomState.c?.() // cancel read promise
delete atomState.e // read error
delete atomState.p // read promise
delete atomState.c // cancel read promise
delete atomState.i // invalidated revision
if (!('v' in atomState) || !Object.is(atomState.v, value)) {
atomState.v = value
++atomState.r // increment revision
}
commitAtomState(state, atom, atomState, dependencies && prevDependencies)
}
const setAtomReadError = <Value>(
state: State,
atom: Atom<Value>,
error: Error,
dependencies?: Set<AnyAtom>,
promise?: Promise<void>
): void => {
const [atomState, prevDependencies] = wipAtomState(state, atom, dependencies)
if (promise && !atomState.p?.[IS_EQUAL_PROMISE](promise)) {
// newer async read is running, not updating
return
}
atomState.c?.() // cancel read promise
delete atomState.p // read promise
delete atomState.c // cancel read promise
delete atomState.i // invalidated revision
atomState.e = error // read error
commitAtomState(state, atom, atomState, prevDependencies)
}
const setAtomReadPromise = <Value>(
state: State,
atom: Atom<Value>,
promise: Promise<void>,
dependencies?: Set<AnyAtom>
): void => {
const [atomState, prevDependencies] = wipAtomState(state, atom, dependencies)
if (atomState.p?.[IS_EQUAL_PROMISE](promise)) {
// the same promise, not updating
return
}
atomState.c?.() // cancel read promise
if (isInterruptablePromise(promise)) {
atomState.p = promise // read promise
delete atomState.c // this promise is from another atom state, shouldn't be canceled here
} else {
const interruptablePromise = createInterruptablePromise(promise)
atomState.p = interruptablePromise // read promise
atomState.c = interruptablePromise[INTERRUPT_PROMISE]
}
commitAtomState(state, atom, atomState, prevDependencies)
}
const setAtomInvalidated = <Value>(state: State, atom: Atom<Value>): void => {
const [atomState] = wipAtomState(state, atom)
atomState.i = atomState.r // invalidated revision
commitAtomState(state, atom, atomState)
}
const setAtomWritePromise = <Value>(
state: State,
atom: Atom<Value>,
promise?: Promise<void>
): void => {
const [atomState] = wipAtomState(state, atom)
if (promise) {
atomState.w = promise
} else {
delete atomState.w // write promise
}
commitAtomState(state, atom, atomState)
}
const scheduleReadAtomState = <Value>(
state: State,
atom: Atom<Value>,
promise: Promise<unknown>
): void => {
promise.finally(() => {
readAtomState(state, atom, true)
})
}
const readAtomState = <Value>(
state: State,
atom: Atom<Value>,
force?: boolean
): AtomState<Value> => {
if (!force) {
const atomState = getAtomState(state, atom)
if (atomState) {
atomState.d.forEach((_, a) => {
if (a !== atom) {
const aState = getAtomState(state, a)
if (
aState &&
!aState.e && // no read error
!aState.p && // no read promise
aState.r === aState.i // revision is invalidated
) {
readAtomState(state, a, true)
}
}
})
if (
Array.from(atomState.d.entries()).every(([a, r]) => {
const aState = getAtomState(state, a)
return (
aState &&
!aState.e && // no read error
!aState.p && // no read promise
aState.r !== aState.i && // revision is not invalidated
aState.r === r // revision is equal to the last one
)
})
) {
return atomState
}
}
}
let error: Error | undefined
let promise: Promise<void> | undefined
let value: NonPromise<Value> | undefined
const dependencies = new Set<AnyAtom>()
try {
const promiseOrValue = atom.read((a: AnyAtom) => {
dependencies.add(a)
if (a !== atom) {
const aState = readAtomState(state, a)
if (aState.e) {
throw aState.e // read error
}
if (aState.p) {
throw aState.p // read promise
}
return aState.v // value
}
// a === atom
const aState = getAtomState(state, a)
if (aState) {
if (aState.e) {
throw aState.e // read error
}
if (aState.p) {
throw aState.p // read promise
}
return aState.v // value
}
if (hasInitialValue(a)) {
return a.init
}
throw new Error('no atom init')
})
if (promiseOrValue instanceof Promise) {
promise = promiseOrValue
.then((value) => {
setAtomValue(
state,
atom,
value as NonPromise<Value>,
dependencies,
promise as Promise<void>
)
flushPending(state)
})
.catch((e) => {
if (e instanceof Promise) {
scheduleReadAtomState(state, atom, e)
return e
}
setAtomReadError(
state,
atom,
e instanceof Error ? e : new Error(e),
dependencies,
promise as Promise<void>
)
flushPending(state)
})
} else {
value = promiseOrValue as NonPromise<Value>
}
} catch (errorOrPromise) {
if (errorOrPromise instanceof Promise) {
promise = errorOrPromise
} else if (errorOrPromise instanceof Error) {
error = errorOrPromise
} else {
error = new Error(errorOrPromise)
}
}
if (error) {
setAtomReadError(state, atom, error, dependencies)
} else if (promise) {
setAtomReadPromise(state, atom, promise, dependencies)
} else {
setAtomValue(state, atom, value as NonPromise<Value>, dependencies)
}
return getAtomState(state, atom) as AtomState<Value>
}
export const readAtom = <Value>(
state: State,
readingAtom: Atom<Value>
): AtomState<Value> => {
const atomState = readAtomState(state, readingAtom)
return atomState
}
const addAtom = (state: State, addingAtom: AnyAtom): Mounted => {
let mounted = state.m.get(addingAtom)
if (!mounted) {
mounted = mountAtom(state, addingAtom)
}
flushPending(state)
return mounted
}
// FIXME doesn't work with mutally dependent atoms
const canUnmountAtom = (atom: AnyAtom, mounted: Mounted) =>
!mounted.l.size &&
(!mounted.d.size || (mounted.d.size === 1 && mounted.d.has(atom)))
const delAtom = (state: State, deletingAtom: AnyAtom): void => {
const mounted = state.m.get(deletingAtom)
if (mounted && canUnmountAtom(deletingAtom, mounted)) {
unmountAtom(state, deletingAtom)
}
flushPending(state)
}
const invalidateDependents = <Value>(state: State, atom: Atom<Value>): void => {
const mounted = state.m.get(atom)
mounted?.d.forEach((dependent) => {
if (dependent === atom) {
return
}
setAtomInvalidated(state, dependent)
invalidateDependents(state, dependent)
})
}
const writeAtomState = <Value, Update>(
state: State,
atom: WritableAtom<Value, Update>,
update: Update
): void => {
const writePromise = getAtomState(state, atom)?.w
if (writePromise) {
writePromise.then(() => {
writeAtomState(state, atom, update)
flushPending(state)
})
return
}
const writeGetter: WriteGetter = (
a: AnyAtom,
unstable_promise: boolean = false
) => {
const aState = readAtomState(state, a)
if (aState.e) {
throw aState.e // read error
}
if (aState.p) {
if (
typeof process === 'object' &&
process.env.NODE_ENV !== 'production'
) {
if (unstable_promise) {
console.info(
'promise option in getter is an experimental feature.',
a
)
} else {
console.warn(
'Reading pending atom state in write operation. We throw a promise for now.',
a
)
}
}
if (unstable_promise) {
return aState.p.then(() => writeGetter(a, unstable_promise))
}
throw aState.p // read promise
}
if ('v' in aState) {
return aState.v // value
}
if (typeof process === 'object' && process.env.NODE_ENV !== 'production') {
console.warn(
'[Bug] no value found while reading atom in write operation. This is probably a bug.',
a
)
}
throw new Error('no value found')
}
const promiseOrVoid = atom.write(
writeGetter,
((a: AnyWritableAtom, v: unknown) => {
if (a === atom) {
if (!hasInitialValue(a)) {
// NOTE technically possible but restricted as it may cause bugs
throw new Error('no atom init')
}
if (v instanceof Promise) {
const promise = v
.then((resolvedValue) => {
setAtomValue(state, a, resolvedValue)
invalidateDependents(state, a)
flushPending(state)
})
.catch((e) => {
setAtomReadError(
state,
atom,
e instanceof Error ? e : new Error(e)
)
flushPending(state)
})
setAtomReadPromise(state, atom, promise)
} else {
setAtomValue(state, a, v)
}
invalidateDependents(state, a)
} else {
writeAtomState(state, a, v)
}
flushPending(state)
}) as Setter,
update
)
if (promiseOrVoid instanceof Promise) {
const promise = promiseOrVoid.finally(() => {
setAtomWritePromise(state, atom)
flushPending(state)
})
setAtomWritePromise(state, atom, promise)
}
// TODO write error is not handled
}
export const writeAtom = <Value, Update>(
state: State,
writingAtom: WritableAtom<Value, Update>,
update: Update
): void => {
writeAtomState(state, writingAtom, update)
flushPending(state)
}
const isActuallyWritableAtom = (atom: AnyAtom): atom is AnyWritableAtom =>
!!(atom as AnyWritableAtom).write
const mountAtom = <Value>(
state: State,
atom: Atom<Value>,
initialDependent?: AnyAtom
): Mounted => {
const atomState = readAtomState(state, atom)
// mount read dependencies beforehand
atomState.d.forEach((_, a) => {
if (a !== atom) {
const aMounted = state.m.get(a)
if (aMounted) {
aMounted.d.add(atom) // add dependent
} else {
mountAtom(state, a, atom)
}
}
})
// mount self
const mounted: Mounted = {
d: new Set(initialDependent && [initialDependent]),
l: new Set(),
u: undefined,
}
state.m.set(atom, mounted)
if (isActuallyWritableAtom(atom) && atom.onMount) {
const setAtom = (update: unknown) => writeAtom(state, atom, update)
mounted.u = atom.onMount(setAtom)
}
return mounted
}
const unmountAtom = <Value>(state: State, atom: Atom<Value>): void => {
// unmount self
const onUnmount = state.m.get(atom)?.u
if (onUnmount) {
onUnmount()
}
state.m.delete(atom)
// unmount read dependencies afterward
const atomState = getAtomState(state, atom)
if (atomState) {
atomState.d.forEach((_, a) => {
if (a !== atom) {
const mounted = state.m.get(a)
if (mounted) {
mounted.d.delete(atom)
if (canUnmountAtom(a, mounted)) {
unmountAtom(state, a)
}
}
}
})
} else if (
typeof process === 'object' &&
process.env.NODE_ENV !== 'production'
) {
console.warn('[Bug] could not find atom state to unmount', atom)
}
}
const mountDependencies = <Value>(
state: State,
atom: Atom<Value>,
atomState: AtomState<Value>,
prevDependencies: ReadDependencies
): void => {
const dependencies = new Set(atomState.d.keys())
prevDependencies.forEach((_, a) => {
if (dependencies.has(a)) {
// not changed
dependencies.delete(a)
return
}
const mounted = state.m.get(a)
if (mounted) {
mounted.d.delete(atom)
if (canUnmountAtom(a, mounted)) {
unmountAtom(state, a)
}
}
})
dependencies.forEach((a) => {
const mounted = state.m.get(a)
if (mounted) {
const dependents = mounted.d
dependents.add(atom)
} else {
mountAtom(state, a, atom)
}
})
}
const commitAtomState = <Value>(
state: State,
atom: Atom<Value>,
atomState: AtomState<Value>,
prevDependencies?: ReadDependencies
): void => {
if (typeof process === 'object' && process.env.NODE_ENV !== 'production') {
Object.freeze(atomState)
}
const isNewAtom = !state.a.has(atom)
state.a.set(atom, atomState)
if (state.l) {
state.l(atom, isNewAtom)
}
++state.v
if (!state.p.has(atom)) {
state.p.set(atom, prevDependencies)
}
}
export const flushPending = (state: State): void => {
const pending = Array.from(state.p)
state.p.clear()
pending.forEach(([atom, prevDependencies]) => {
const atomState = getAtomState(state, atom)
if (atomState) {
if (prevDependencies) {
mountDependencies(state, atom, atomState, prevDependencies)
}
} else if (
typeof process === 'object' &&
process.env.NODE_ENV !== 'production'
) {
console.warn('[Bug] atom state not found in flush', atom)
}
const mounted = state.m.get(atom)
mounted?.l.forEach((listener) => listener())
})
}
export const subscribeAtom = (
state: State,
atom: AnyAtom,
callback: () => void
) => {
const mounted = addAtom(state, atom)
const listeners = mounted.l
listeners.add(callback)
return () => {
listeners.delete(callback)
delAtom(state, atom)
}
}
export const restoreAtoms = (
state: State,
values: Iterable<readonly [AnyAtom, unknown]>
): void => {
for (const [atom, value] of values) {
if (hasInitialValue(atom)) {
setAtomValue(state, atom, value)
invalidateDependents(state, atom)
}
}
flushPending(state)
}