forked from pmndrs/jotai
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathProvider.ts
703 lines (667 loc) · 18.9 KB
/
Provider.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
import React, {
Dispatch,
SetStateAction,
MutableRefObject,
ReactElement,
createElement,
useCallback,
useMemo,
useState,
useRef,
useEffect,
useDebugValue,
} from 'react'
import {
unstable_UserBlockingPriority as UserBlockingPriority,
unstable_runWithPriority as runWithPriority,
} from 'scheduler'
import { createContext, useContextUpdate } from 'use-context-selector'
import {
Atom,
WritableAtom,
AnyAtom,
AnyWritableAtom,
Getter,
Setter,
} from './types'
import { useIsoLayoutEffect } from './useIsoLayoutEffect'
import {
ImmutableMap,
mCreate,
mGet,
mSet,
mDel,
mKeys,
mMerge,
mToPrintable,
} from './immutableMap'
const warningObject = new Proxy(
{},
{
get() {
throw new Error('Please use <Provider>')
},
apply() {
throw new Error('Please use <Provider>')
},
}
)
const useWeakMapRef = <T extends WeakMap<object, unknown>>() => {
const ref = useRef<T>()
if (!ref.current) {
ref.current = new WeakMap() as T
}
return ref.current
}
const warnAtomStateNotFound = (info: string, atom: AnyAtom) => {
console.warn(
'[Bug] Atom state not found. Please file an issue with repro: ' + info,
atom
)
}
export type AtomState<Value = unknown> = {
readE?: Error // read error
readP?: Promise<void> // read promise
writeP?: Promise<void> // write promise
value?: Value
deps: Set<AnyAtom> // read dependents
}
type State = ImmutableMap<AnyAtom, AtomState>
const initialState: State = mCreate()
type UsedState = ImmutableMap<AnyAtom, Set<symbol>> // symbol is id from useAtom
const initialUsedState: UsedState = mCreate()
// we store last atom state before deleting from provider state
// and reuse it as long as it's not gc'd
type AtomStateCache = WeakMap<AnyAtom, AtomState>
// pending state for adding a new atom
type ReadPendingMap = WeakMap<State, State> // the value is next state
type ContextUpdate = (t: () => void) => void
type WriteThunk = (lastState: State) => State // returns next state
export type Actions = {
add: <Value>(id: symbol, atom: Atom<Value>) => void
del: <Value>(id: symbol, atom: Atom<Value>) => void
read: <Value>(state: State, atom: Atom<Value>) => AtomState<Value>
write: <Value, Update>(
atom: WritableAtom<Value, Update>,
update: Update
) => void | Promise<void>
}
const updateAtomState = <Value>(
atom: Atom<Value>,
prevState: State,
partial: Partial<AtomState<Value>>,
prevPromise?: Promise<void>,
isNew?: boolean
) => {
let atomState = mGet(prevState, atom) as AtomState<Value> | undefined
if (!atomState) {
if (!isNew && process.env.NODE_ENV !== 'production') {
warnAtomStateNotFound('updateAtomState', atom)
}
atomState = { deps: new Set() }
}
if (prevPromise && prevPromise !== atomState.readP) {
return prevState
}
return mSet(prevState, atom, { ...atomState, ...partial })
}
const addDependent = (atom: AnyAtom, dependent: AnyAtom, prevState: State) => {
const atomState = mGet(prevState, atom)
if (atomState) {
if (!atomState.deps.has(dependent)) {
const newDeps = new Set(atomState.deps).add(dependent)
return mSet(prevState, atom, { ...atomState, deps: newDeps })
}
} else if (process.env.NODE_ENV !== 'production') {
warnAtomStateNotFound('addDependent', atom)
}
return prevState
}
const replaceDependencies = (
atom: AnyAtom,
prevState: State,
dependenciesToReplace: Set<AnyAtom>
) => {
const dependencies = new Set(dependenciesToReplace)
let nextState = prevState
mKeys(nextState).forEach((a) => {
const aState = mGet(nextState, a) as AtomState<unknown>
if (aState.deps.has(atom)) {
if (dependencies.has(a)) {
// not changed
dependencies.delete(a)
} else {
const newDeps = new Set(aState.deps)
newDeps.delete(atom)
nextState = mSet(nextState, a, { ...aState, deps: newDeps })
}
}
})
dependencies.forEach((a) => {
const aState = mGet(nextState, a)
if (aState) {
const newDeps = new Set(aState.deps).add(atom)
nextState = mSet(nextState, a, { ...aState, deps: newDeps })
} else if (process.env.NODE_ENV !== 'production') {
warnAtomStateNotFound('replaceDependencies', a)
}
})
return nextState
}
const readAtomState = <Value>(
atom: Atom<Value>,
prevState: State,
setState: Dispatch<(prev: State) => State>,
atomStateCache: AtomStateCache,
force?: boolean
) => {
if (!force) {
let atomState = mGet(prevState, atom) as AtomState<Value> | undefined
if (atomState) {
return [atomState, prevState] as const
}
atomState = atomStateCache.get(atom) as AtomState<Value> | undefined
if (atomState) {
return [atomState, mSet(prevState, atom, atomState)] as const
}
}
let isSync = true
let nextState = prevState
let error: Error | undefined = undefined
let promise: Promise<void> | undefined = undefined
let value: Value | undefined = undefined
let dependencies: Set<AnyAtom> | null = new Set()
let flushDependencies = false
try {
const promiseOrValue = atom.read(((a: AnyAtom) => {
if (dependencies) {
dependencies.add(a)
} else {
setState((prev) => addDependent(a, atom, prev))
}
if (a !== atom) {
const [aState, nextNextState] = readAtomState(
a,
nextState,
setState,
atomStateCache
)
if (isSync) {
nextState = nextNextState
} else {
// XXX is this really correct?
setState((prev) => mMerge(nextNextState, prev))
}
if (aState.readE) {
throw aState.readE
}
if (aState.readP) {
throw aState.readP
}
return aState.value
}
// a === atom
const aState = mGet(nextState, a)
if (aState) {
if (aState.readP) {
throw aState.readP
}
return aState.value
}
return a.init // this should not be undefined
}) as Getter)
if (promiseOrValue instanceof Promise) {
promise = promiseOrValue
.then((value) => {
const dependenciesToReplace = dependencies as Set<AnyAtom>
dependencies = null
setState((prev) =>
updateAtomState(
atom,
replaceDependencies(atom, prev, dependenciesToReplace),
{ readE: undefined, readP: undefined, value },
promise
)
)
})
.catch((e) => {
const dependenciesToReplace = dependencies as Set<AnyAtom>
dependencies = null
setState((prev) =>
updateAtomState(
atom,
replaceDependencies(atom, prev, dependenciesToReplace),
{
readE: e instanceof Error ? e : new Error(e),
readP: undefined,
},
promise
)
)
})
} else {
value = promiseOrValue
flushDependencies = true
}
} catch (errorOrPromise) {
if (errorOrPromise instanceof Promise) {
promise = errorOrPromise.then(() => {
setState(
(prev) =>
readAtomState(atom, mDel(prev, atom), setState, atomStateCache)[1]
)
})
} else if (errorOrPromise instanceof Error) {
error = errorOrPromise
} else {
error = new Error(errorOrPromise)
}
flushDependencies = true
}
nextState = updateAtomState(
atom,
nextState,
{
readE: error,
readP: promise,
value: promise ? atom.init : value,
},
undefined,
true
)
if (flushDependencies) {
nextState = replaceDependencies(atom, nextState, dependencies)
dependencies = null
}
const atomState = mGet(nextState, atom) as AtomState<Value>
isSync = false
return [atomState, nextState] as const
}
const updateDependentsState = <Value>(
atom: Atom<Value>,
prevState: State,
setState: Dispatch<(prev: State) => State>,
atomStateCache: AtomStateCache
) => {
const atomState = mGet(prevState, atom)
if (!atomState) {
if (process.env.NODE_ENV !== 'production') {
warnAtomStateNotFound('updateDependentsState', atom)
}
return prevState
}
let nextState = prevState
atomState.deps.forEach((dependent) => {
if (
dependent === atom ||
typeof dependent === 'symbol' ||
!mGet(nextState, dependent)
) {
return
}
const [dependentState, nextNextState] = readAtomState(
dependent,
nextState,
setState,
atomStateCache,
true
)
const promise = dependentState.readP
if (promise) {
promise.then(() => {
setState((prev) =>
updateDependentsState(dependent, prev, setState, atomStateCache)
)
})
nextState = nextNextState
} else {
nextState = updateDependentsState(
dependent,
nextNextState,
setState,
atomStateCache
)
}
})
return nextState
}
const readAtom = <Value>(
state: State,
readingAtom: Atom<Value>,
setState: Dispatch<(prev: State) => State>,
readPendingMap: ReadPendingMap,
atomStateCache: AtomStateCache
) => {
const prevState = readPendingMap.get(state) || state
const [atomState, nextState] = readAtomState(
readingAtom,
prevState,
setState,
atomStateCache
)
if (nextState !== prevState) {
readPendingMap.set(state, nextState)
}
return atomState
}
const writeAtom = <Value, Update>(
writingAtom: WritableAtom<Value, Update>,
update: Update,
setState: Dispatch<(prev: State) => State>,
atomStateCache: AtomStateCache,
addWriteThunk: (thunk: WriteThunk) => void
) => {
const pendingPromises: Promise<void>[] = []
const writeAtomState = <Value, Update>(
prevState: State,
atom: WritableAtom<Value, Update>,
update: Update
) => {
const prevAtomState = mGet(prevState, atom)
if (prevAtomState && prevAtomState.writeP) {
const promise = prevAtomState.writeP.then(() => {
addWriteThunk((prev) => writeAtomState(prev, atom, update))
})
pendingPromises.push(promise)
return prevState
}
let nextState = prevState
let isSync = true
try {
const promiseOrVoid = atom.write(
((a: AnyAtom) => {
const aState = mGet(nextState, a)
if (!aState) {
if (process.env.NODE_ENV !== 'production') {
warnAtomStateNotFound('writeAtomState', a)
}
return a.init
}
if (aState.readP && process.env.NODE_ENV !== 'production') {
// TODO will try to detect this
console.warn(
'Reading pending atom state in write operation. We need to detect this and fallback. Please file an issue with repro.',
a
)
}
return aState.value
}) as Getter,
((a: AnyWritableAtom, v: unknown) => {
if (a === atom) {
const partialAtomState = {
readE: undefined,
readP: undefined,
value: v,
}
if (isSync) {
nextState = updateDependentsState(
a,
updateAtomState(a, nextState, partialAtomState),
setState,
atomStateCache
)
} else {
setState((prev) =>
updateDependentsState(
a,
updateAtomState(a, prev, partialAtomState),
setState,
atomStateCache
)
)
}
} else {
if (isSync) {
nextState = writeAtomState(nextState, a, v)
} else {
addWriteThunk((prev) => writeAtomState(prev, a, v))
}
}
}) as Setter,
update
)
if (promiseOrVoid instanceof Promise) {
pendingPromises.push(promiseOrVoid)
nextState = updateAtomState(atom, nextState, {
writeP: promiseOrVoid.then(() => {
addWriteThunk((prev) =>
updateAtomState(atom, prev, { writeP: undefined })
)
}),
})
}
} catch (e) {
if (pendingPromises.length) {
pendingPromises.push(
new Promise((_resolve, reject) => {
reject(e)
})
)
} else {
throw e
}
}
isSync = false
return nextState
}
let isSync = true
let writeResolve: () => void
const writePromise = new Promise<void>((resolve) => {
writeResolve = resolve
})
pendingPromises.unshift(writePromise)
addWriteThunk((prevState) => {
if (isSync) {
pendingPromises.shift()
}
const nextState = writeAtomState(prevState, writingAtom, update)
if (!isSync) {
writeResolve()
}
return nextState
})
isSync = false
if (pendingPromises.length) {
return new Promise<void>((resolve, reject) => {
const loop = () => {
const len = pendingPromises.length
if (len === 0) {
resolve()
} else {
Promise.all(pendingPromises)
.then(() => {
pendingPromises.splice(0, len)
loop()
})
.catch(reject)
}
}
loop()
})
}
}
const runWriteThunk = (
lastStateRef: MutableRefObject<State | null>,
pendingStateRef: MutableRefObject<State | null>,
setState: Dispatch<State>,
contextUpdate: ContextUpdate,
writeThunkQueue: WriteThunk[]
) => {
while (true) {
if (!lastStateRef.current || !writeThunkQueue.length) {
return
}
const thunk = writeThunkQueue.shift() as WriteThunk
const prevState = pendingStateRef.current || lastStateRef.current
const nextState = thunk(prevState)
if (nextState !== prevState) {
pendingStateRef.current = nextState
Promise.resolve().then(() => {
const pendingState = pendingStateRef.current
if (pendingState) {
pendingStateRef.current = null
contextUpdate(() => {
runWithPriority(UserBlockingPriority, () => {
setState(pendingState)
})
})
}
})
}
}
}
export const ActionsContext = createContext(warningObject as Actions)
export const StateContext = createContext(warningObject as State)
const InnerProvider: React.FC<{
r: MutableRefObject<ContextUpdate | undefined>
}> = ({ r, children }) => {
const contextUpdate = useContextUpdate(StateContext)
if (!r.current) {
r.current = contextUpdate
}
return children as ReactElement
}
export const Provider: React.FC = ({ children }) => {
const contextUpdateRef = useRef<ContextUpdate>()
const readPendingMap = useWeakMapRef<ReadPendingMap>()
const atomStateCache = useWeakMapRef<AtomStateCache>()
const [state, setStateOrig] = useState(initialState)
const lastStateRef = useRef<State | null>(null)
const pendingStateRef = useRef<State | null>(null)
const setState = useCallback(
(setStateAction: SetStateAction<State>) => {
const pendingState = pendingStateRef.current
if (pendingState) {
pendingStateRef.current = null
setStateOrig(pendingState)
}
if (lastStateRef.current) {
const readPending = readPendingMap.get(lastStateRef.current)
if (readPending) {
setStateOrig(readPending)
if (pendingState && process.env.NODE_ENV !== 'production') {
console.warn('[Bug] conflict pendingState and readPending')
}
}
}
lastStateRef.current = null
setStateOrig(setStateAction)
},
[readPendingMap]
)
useIsoLayoutEffect(() => {
const readPending = readPendingMap.get(state)
if (readPending) {
setState(readPending)
return
}
lastStateRef.current = state
})
const [used, setUsed] = useState(initialUsedState)
useEffect(() => {
const lastState = lastStateRef.current
if (!lastState) return
let nextState = lastState
let deleted: boolean
do {
deleted = false
mKeys(nextState).forEach((a) => {
const aState = mGet(nextState, a) as AtomState<unknown>
// do not delete while promises are not resolved
if (aState.writeP || aState.readP) return
const depsSize = aState.deps.size
const isEmpty =
(depsSize === 0 || (depsSize === 1 && aState.deps.has(a))) &&
!mGet(used, a)?.size
if (isEmpty) {
atomStateCache.set(a, aState)
nextState = mDel(nextState, a)
deleted = true
}
})
} while (deleted)
if (nextState !== lastState) {
setState(nextState)
}
}, [used, atomStateCache, setState])
const writeThunkQueueRef = useRef<WriteThunk[]>([])
useEffect(() => {
runWriteThunk(
lastStateRef,
pendingStateRef,
setState,
contextUpdateRef.current as ContextUpdate,
writeThunkQueueRef.current
)
}, [state, setState])
const actions = useMemo(
() => ({
add: <Value>(id: symbol, atom: Atom<Value>) => {
setUsed((prev) => mSet(prev, atom, new Set(mGet(prev, atom)).add(id)))
},
del: <Value>(id: symbol, atom: Atom<Value>) => {
setUsed((prev) => {
const oldSet = mGet(prev, atom)
if (!oldSet) return prev
const newSet = new Set(oldSet)
newSet.delete(id)
if (newSet.size) {
return mSet(prev, atom, newSet)
}
return mDel(prev, atom)
})
},
read: <Value>(state: State, atom: Atom<Value>) =>
readAtom(state, atom, setState, readPendingMap, atomStateCache),
write: <Value, Update>(
atom: WritableAtom<Value, Update>,
update: Update
) =>
writeAtom(
atom,
update,
setState,
atomStateCache,
(thunk: WriteThunk) => {
writeThunkQueueRef.current.push(thunk)
if (lastStateRef.current) {
runWriteThunk(
lastStateRef,
pendingStateRef,
setState,
contextUpdateRef.current as ContextUpdate,
writeThunkQueueRef.current
)
} else {
// force update (FIXME this is a workaround for now)
setState((prev) => mMerge(prev, mCreate()))
}
}
),
}),
[readPendingMap, atomStateCache, setState]
)
if (process.env.NODE_ENV !== 'production') {
// eslint-disable-next-line react-hooks/rules-of-hooks
useDebugState(state)
}
return createElement(
ActionsContext.Provider,
{ value: actions },
createElement(
StateContext.Provider,
{ value: state },
createElement(InnerProvider, { r: contextUpdateRef }, children)
)
)
}
const atomToPrintable = (atom: AnyAtom) =>
`${atom.key}:${atom.debugLabel ?? '<no debugLabel>'}`
const stateToPrintable = (state: State) =>
mToPrintable(state, atomToPrintable, (v) => ({
value: v.readE || v.readP || v.writeP || v.value,
deps: Array.from(v.deps).map(atomToPrintable),
}))
const useDebugState = (state: State) => {
useDebugValue(state, stateToPrintable)
}