-
-
Notifications
You must be signed in to change notification settings - Fork 385
/
Copy pathcreateLoadable.js
367 lines (312 loc) · 9.69 KB
/
createLoadable.js
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
/* eslint-disable no-use-before-define, react/no-multi-comp, no-underscore-dangle */
import React from 'react'
import hoistNonReactStatics from 'hoist-non-react-statics'
import { invariant } from './util'
import Context from './Context'
import { LOADABLE_SHARED } from './shared'
const STATUS_PENDING = 'PENDING'
const STATUS_RESOLVED = 'RESOLVED'
const STATUS_REJECTED = 'REJECTED'
function resolveConstructor(ctor) {
if (typeof ctor === 'function') {
return {
requireAsync: ctor,
resolve() {
return undefined
},
chunkName() {
return undefined
},
}
}
return ctor
}
const withChunkExtractor = Component => {
const LoadableWithChunkExtractor = props => (
<Context.Consumer>
{extractor => <Component __chunkExtractor={extractor} {...props} />}
</Context.Consumer>
)
if (Component.displayName) {
LoadableWithChunkExtractor.displayName = `${Component.displayName}WithChunkExtractor`
}
return LoadableWithChunkExtractor
}
const identity = v => v
function createLoadable({
defaultResolveComponent = identity,
render,
onLoad,
}) {
function loadable(loadableConstructor, options = {}) {
const ctor = resolveConstructor(loadableConstructor)
const cache = {}
/**
* Cachekey represents the component to be loaded
* if key changes - component has to be reloaded
* @param props
* @returns {null|Component}
*/
function getCacheKey(props) {
if (options.cacheKey) {
return options.cacheKey(props)
}
if (ctor.resolve) {
return ctor.resolve(props)
}
return 'static'
}
/**
* Resolves loaded `module` to a specific `Component
* @param module
* @param props
* @param Loadable
* @returns Component
*/
function resolve(module, props, Loadable) {
const Component = options.resolveComponent
? options.resolveComponent(module, props)
: defaultResolveComponent(module)
// FIXME: suppressed due to https://github.com/gregberge/loadable-components/issues/990
// if (options.resolveComponent && !ReactIs.isValidElementType(Component)) {
// throw new Error(
// `resolveComponent returned something that is not a React component!`,
// )
// }
hoistNonReactStatics(Loadable, Component, {
preload: true,
})
return Component
}
const cachedLoad = props => {
const cacheKey = getCacheKey(props)
let promise = cache[cacheKey]
if (!promise || promise.status === STATUS_REJECTED) {
promise = ctor.requireAsync(props)
promise.status = STATUS_PENDING
cache[cacheKey] = promise
promise.then(
() => {
promise.status = STATUS_RESOLVED
},
error => {
console.error(
'loadable-components: failed to asynchronously load component',
{
fileName: ctor.resolve(props),
chunkName: ctor.chunkName(props),
error: error ? error.message : error,
},
)
promise.status = STATUS_REJECTED
},
)
}
return promise
}
class InnerLoadable extends React.Component {
static getDerivedStateFromProps(props, state) {
const cacheKey = getCacheKey(props)
return {
...state,
cacheKey,
// change of a key triggers loading state automatically
loading: state.loading || state.cacheKey !== cacheKey,
}
}
constructor(props) {
super(props)
this.state = {
result: null,
error: null,
loading: true,
cacheKey: getCacheKey(props),
}
invariant(
!props.__chunkExtractor || ctor.requireSync,
'SSR requires `@loadable/babel-plugin`, please install it',
)
// Server-side
if (props.__chunkExtractor) {
// This module has been marked with no SSR
if (options.ssr === false) {
return
}
// We run load function, we assume that it won't fail and that it
// triggers a synchronous loading of the module
ctor.requireAsync(props).catch(() => null)
// So we can require now the module synchronously
this.loadSync()
props.__chunkExtractor.addChunk(ctor.chunkName(props))
return
}
// Client-side with `isReady` method present (SSR probably)
// If module is already loaded, we use a synchronous loading
// Only perform this synchronous loading if the component has not
// been marked with no SSR, else we risk hydration mismatches
if (
options.ssr !== false &&
// is ready - was loaded in this session
((ctor.isReady && ctor.isReady(props)) ||
// is ready - was loaded during SSR process
(ctor.chunkName &&
LOADABLE_SHARED.initialChunks[ctor.chunkName(props)]))
) {
this.loadSync()
}
}
componentDidMount() {
this.mounted = true
// retrieve loading promise from a global cache
const cachedPromise = this.getCache()
// if promise exists, but rejected - clear cache
if (cachedPromise && cachedPromise.status === STATUS_REJECTED) {
this.setCache()
}
// component might be resolved synchronously in the constructor
if (this.state.loading) {
this.loadAsync()
}
}
componentDidUpdate(prevProps, prevState) {
// Component has to be reloaded on cacheKey change
if (prevState.cacheKey !== this.state.cacheKey) {
this.loadAsync()
}
}
componentWillUnmount() {
this.mounted = false
}
safeSetState(nextState, callback) {
if (this.mounted) {
this.setState(nextState, callback)
}
}
/**
* returns a cache key for the current props
* @returns {Component|string}
*/
getCacheKey() {
return getCacheKey(this.props)
}
/**
* access the persistent cache
*/
getCache() {
return cache[this.getCacheKey()]
}
/**
* sets the cache value. If called without value sets it as undefined
*/
setCache(value = undefined) {
cache[this.getCacheKey()] = value
}
triggerOnLoad() {
if (onLoad) {
setTimeout(() => {
onLoad(this.state.result, this.props)
})
}
}
/**
* Synchronously loads component
* target module is expected to already exists in the module cache
* or be capable to resolve synchronously (webpack target=node)
*/
loadSync() {
// load sync is expecting component to be in the "loading" state already
// sounds weird, but loading=true is the initial state of InnerLoadable
if (!this.state.loading) return
try {
const loadedModule = ctor.requireSync(this.props)
const result = resolve(loadedModule, this.props, Loadable)
this.state.result = result
this.state.loading = false
} catch (error) {
console.error(
'loadable-components: failed to synchronously load component, which expected to be available',
{
fileName: ctor.resolve(this.props),
chunkName: ctor.chunkName(this.props),
error: error ? error.message : error,
},
)
this.state.error = error
}
}
/**
* Asynchronously loads a component.
*/
loadAsync() {
const promise = this.resolveAsync()
promise
.then(loadedModule => {
const result = resolve(loadedModule, this.props, Loadable)
this.safeSetState(
{
result,
loading: false,
},
() => this.triggerOnLoad(),
)
})
.catch(error => this.safeSetState({ error, loading: false }))
return promise
}
/**
* Asynchronously resolves(not loads) a component.
* Note - this function does not change the state
*/
resolveAsync() {
const { __chunkExtractor, forwardedRef, ...props } = this.props
return cachedLoad(props)
}
render() {
const {
forwardedRef,
fallback: propFallback,
__chunkExtractor,
...props
} = this.props
const { error, loading, result } = this.state
if (options.suspense) {
const cachedPromise = this.getCache() || this.loadAsync()
if (cachedPromise.status === STATUS_PENDING) {
throw this.loadAsync()
}
}
if (error) {
throw error
}
const fallback = propFallback || options.fallback || null
if (loading) {
return fallback
}
return render({
fallback,
result,
options,
props: { ...props, ref: forwardedRef },
})
}
}
const EnhancedInnerLoadable = withChunkExtractor(InnerLoadable)
const Loadable = React.forwardRef((props, ref) => (
<EnhancedInnerLoadable forwardedRef={ref} {...props} />
))
Loadable.displayName = 'Loadable'
// In future, preload could use `<link rel="preload">`
Loadable.preload = props => {
Loadable.load(props)
}
Loadable.load = props => {
return cachedLoad(props)
}
return Loadable
}
function lazy(ctor, options) {
return loadable(ctor, { ...options, suspense: true })
}
return { loadable, lazy }
}
export default createLoadable