forked from react-loadable/revised
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathindex.tsx
188 lines (161 loc) · 5.24 KB
/
index.tsx
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
import {
ComponentProps,
ComponentType,
createContext,
ReactElement,
ReactNode,
useCallback,
useContext,
useEffect,
useRef,
useState
} from 'react'
type LoaderType<T, P> = () => Promise<LoadableComponent<T, P>>
type LoaderTypeOptional<T, P> = () => Promise<LoadableComponent<T, P>> | undefined
const ALL_INITIALIZERS: LoaderType<any, any>[] = []
const READY_INITIALIZERS: LoaderTypeOptional<any, any>[] = []
const CaptureContext = createContext<((moduleId: string) => any) | undefined>(undefined)
CaptureContext.displayName = 'Capture'
export function Capture({report, children}: {
report(moduleId: string): any
children: ReactNode
}) {
return <CaptureContext.Provider value={report}>
{children}
</CaptureContext.Provider>
}
Capture.displayName = 'Capture'
type LoadableOptions<T, P> = {
loading: ComponentType<{
error?: Error
retry(): any
}>
webpack?(): string[]
loader(): Promise<T>
render?(loaded: T, props: P): ReactElement
}
type LoadableComponent<T, P> = ComponentType<T extends {default: ComponentType<infer Props>}
? Props
: P // this conditional branch is not 100% correct. It should be never if render property is not provided
>
declare const __webpack_modules__: any
const isWebpackReady = (getModuleIds: () => string[]) => typeof __webpack_modules__ === 'object'
&& getModuleIds().every(moduleId => typeof moduleId !== 'undefined' && typeof __webpack_modules__[moduleId] !== 'undefined')
interface LoadState<T, P> {
promise: Promise<LoadableComponent<T, P>>
loaded?: LoadableComponent<T, P>
error?: Error
}
const load = <T, P>(loader: LoaderType<T, P>) => {
const state = {
loaded: undefined,
error: undefined,
} as LoadState<T, P>
state.promise = new Promise<LoadableComponent<T, P>>(async (resolve, reject) => {
try {
resolve(state.loaded = await loader())
} catch (e) {
reject(state.error = e)
}
})
return state
}
type LoadComponent<P> = {
// __esModule: true
default: ComponentType<P>
} | ComponentType<P>
const resolve = <P, >(obj: LoadComponent<P>): ComponentType<P> => (obj as any)?.__esModule ? (obj as any).default : obj
const defaultRenderer = <P, T extends {default: ComponentType<P>}>(
loaded: T,
props: T extends {default: ComponentType<infer P>} ? P : never
) => {
const Loaded = resolve(loaded)
return <Loaded {...props}/>
}
type LoadableState<T, P, > = {
error?: Error
loaded?: LoadableComponent<T, P>
}
function createLoadableComponent<T, P>(
{
loading: Loading,
loader,
webpack,
render = defaultRenderer as (loaded: T, props: P) => ReactElement,
...opts
}: LoadableOptions<T, P>
): LoadableComponent<T, P> & {
displayName: string
preload: LoaderType<T, P>
} {
if (!Loading) throw new Error('react-loadable requires a `loading` component')
let loadState: LoadState<T, P>
const init = () => {
if (!loadState) loadState = load(loader as any)
return loadState.promise
}
ALL_INITIALIZERS.push(init)
if (typeof webpack === 'function') READY_INITIALIZERS.push(() => {
if (isWebpackReady(webpack)) return init()
})
const LoadableComponent = (props: ComponentProps<LoadableComponent<T, P>>) => {
init()
const report = useContext(CaptureContext)
const [state, setState] = useState<LoadableState<T, P>>({
error: loadState.error,
loaded: loadState.loaded
})
const mountedRef = useRef<boolean>(false)
const pendingStateRef = useRef<LoadableState<T, P>>()
useEffect(() => {
mountedRef.current = true
if (pendingStateRef.current) {
setState(pendingStateRef.current)
pendingStateRef.current = undefined
}
return () => void(mountedRef.current = false)
}, [])
const loadModule = useCallback(async () => {
if (report && Array.isArray(opts['modules'])) for (const moduleName of opts['modules']) report(moduleName)
if (loadState.error || loadState.loaded) return
try {
await loadState.promise
} catch {
} finally {
const newState = {
error: loadState.error,
loaded: loadState.loaded,
}
if (mountedRef.current) setState(newState)
else pendingStateRef.current = newState
}
}, [report, mountedRef])
const retry = useCallback(async () => {
if (!mountedRef.current) return
setState({error: undefined, loaded: undefined})
loadState = load(loader as any)
await loadModule()
}, [loadModule])
const firstStateRef = useRef<LoadableState<T, P> | undefined>(state)
if (firstStateRef.current) {
loadModule()
firstStateRef.current = undefined
}
return !state.loaded || state.error
? <Loading error={state.error} retry={retry}/>
: render(state.loaded as any, props as any)
}
LoadableComponent.preload = init
LoadableComponent.displayName = `LoadableComponent(${Array.isArray(opts['modules']) ? opts['modules'].join('-') : ''})`
return LoadableComponent as any
}
const flushInitializers = async <T, P>(initializers: (LoaderType<T, P> | LoaderTypeOptional<T, P>)[]): Promise<void> => {
const promises = []
while (initializers.length) promises.push(initializers.pop()!())
await Promise.all(promises)
if (initializers.length) return flushInitializers(initializers)
}
export const preloadAll = () => flushInitializers(ALL_INITIALIZERS)
export const preloadReady = () => flushInitializers(READY_INITIALIZERS)
const loadable = <T, P>(opts: LoadableOptions<T, P>) => createLoadableComponent(opts)
export default loadable