-
Notifications
You must be signed in to change notification settings - Fork 5
/
useSourceModern.ts
89 lines (77 loc) · 2.46 KB
/
useSourceModern.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
/* eslint-disable react-hooks/rules-of-hooks */
/// <reference types="react/experimental" />
import React, { useCallback, useMemo } from 'react'
import {
GettableSourceCore,
SourceCore,
Source,
SourceGetVersion,
hasSnapshot,
identitySelector,
nullSource,
} from '../source'
import { UseSourceFunction, UseSourceOptions } from './useSourceType'
interface ReactMutableSource {
_source: SourceCore
_getVersion: SourceGetVersion
}
const {
unstable_createMutableSource: createMutableSource,
unstable_useMutableSource: useMutableSource,
} = React as any as {
unstable_createMutableSource: (
source: SourceCore,
getVersion: SourceGetVersion,
) => ReactMutableSource
unstable_useMutableSource: <T>(
source: ReactMutableSource,
getSnapshot: (core: SourceCore) => T,
subscribe: (core: SourceCore, callback: () => void) => () => void,
) => T
}
const MissingToken = Symbol()
const subscribe = ([, subscribe]: SourceCore, cb: () => void) => subscribe(cb)
let mutableSources: WeakMap<SourceCore, ReactMutableSource>
export const useSourceModern: UseSourceFunction = <T = null, U = T>(
maybeSource: Source<T> | null,
options: UseSourceOptions<U> = {},
): T | U | null => {
const hasDefaultValue = 'defaultValue' in options
const { defaultValue, startTransition } = options
const [core, select] = maybeSource || nullSource
if (!mutableSources) {
mutableSources = new WeakMap<SourceCore, ReactMutableSource>([
[nullSource[0], createMutableSource(nullSource[0], nullSource[0][0])],
])
}
const getSnapshot = useCallback(
([getVersion]: GettableSourceCore) =>
hasDefaultValue && !hasSnapshot([[getVersion], select])
? MissingToken
: select(getVersion()),
[hasDefaultValue, select],
)
const subscribeWithTransition = useMemo(
() =>
startTransition
? ([, subscribe]: SourceCore, callback: () => void) =>
subscribe(() => {
startTransition(callback)
})
: subscribe,
[startTransition],
)
let mutableSource = mutableSources.get(core)!
if (!mutableSource) {
const getVersion = () =>
hasSnapshot([core, identitySelector]) ? core[0]() : MissingToken
mutableSource = createMutableSource(core, getVersion)
mutableSources.set(core, mutableSource)
}
const value = useMutableSource(
mutableSource,
getSnapshot,
subscribeWithTransition,
)
return value === MissingToken || maybeSource === null ? defaultValue! : value
}