/
AsyncProps.js
307 lines (268 loc) · 7.86 KB
/
AsyncProps.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
/*global __ASYNC_PROPS__*/
import React from 'react'
import RouterContext from 'react-router/lib/RouterContext'
import computeChangedRoutes from 'react-router/lib/computeChangedRoutes'
const { array, func, object } = React.PropTypes
function eachComponents(components, iterator) {
for (var i = 0, l = components.length; i < l; i++) {
if (typeof components[i] === 'object') {
for (var key in components[i]) {
iterator(components[i][key], i, key)
}
} else {
iterator(components[i], i)
}
}
}
function filterAndFlattenComponents(components) {
var flattened = []
eachComponents(components, (Component) => {
if (Component && Component.loadProps)
flattened.push(Component)
})
return flattened
}
function loadAsyncProps({ components, params, loadContext }, cb) {
let componentsArray = []
let propsArray = []
let needToLoadCounter = components.length
let hasCalledBack = []
const maybeFinish = (err) => {
if (err)
cb(err)
else if (needToLoadCounter === 0)
cb(null, { propsArray, componentsArray })
}
// If there are no components we should resolve directly
if (needToLoadCounter === 0) {
maybeFinish()
} else {
components.forEach((Component, index) => {
Component.loadProps({ params, loadContext }, (error, props) => {
const isDeferredCallback = hasCalledBack[index]
if (isDeferredCallback && needToLoadCounter === 0) {
cb(error, {
propsArray: [ props ],
componentsArray: [ Component ]
})
} else {
if (!hasCalledBack[index])
needToLoadCounter--
propsArray[index] = props
componentsArray[index] = Component
hasCalledBack[index] = true
maybeFinish(error)
}
})
})
}
}
function lookupPropsForComponent(Component, propsAndComponents) {
const { componentsArray, propsArray } = propsAndComponents
var index = componentsArray.indexOf(Component)
return propsArray[index]
}
function mergePropsAndComponents(current, changes) {
for (var i = 0, l = changes.propsArray.length; i < l; i++) {
let Component = changes.componentsArray[i]
let position = current.componentsArray.indexOf(Component)
let isNew = position === -1
if (isNew) {
current.propsArray.push(changes.propsArray[i])
current.componentsArray.push(changes.componentsArray[i])
} else {
current.propsArray[position] = changes.propsArray[i]
}
}
return current
}
function createElement(Component, props) {
if (Component.loadProps)
return <AsyncPropsContainer Component={Component} routerProps={props}/>
else
return <Component {...props}/>
}
export function loadPropsOnServer({ components, params }, loadContext, cb) {
loadAsyncProps({
components: filterAndFlattenComponents(components),
params,
loadContext
}, (err, propsAndComponents) => {
if (err) {
cb(err)
}
else {
const json = JSON.stringify(propsAndComponents.propsArray, null, 2)
const scriptString = `<script>__ASYNC_PROPS__ = ${json}</script>`
cb(null, propsAndComponents, scriptString)
}
})
}
function hydrate(props) {
if (typeof __ASYNC_PROPS__ !== 'undefined')
return {
propsArray: __ASYNC_PROPS__,
componentsArray: filterAndFlattenComponents(props.components)
}
else
return null
}
const AsyncPropsContainer = React.createClass({
propTypes: {
Component: func.isRequired,
routerProps: object.isRequired
},
contextTypes: {
asyncProps: object.isRequired
},
render() {
const { Component, routerProps, ...props } = this.props
const { propsAndComponents, loading, reloadComponent } = this.context.asyncProps
const asyncProps = lookupPropsForComponent(Component, propsAndComponents)
const reload = () => reloadComponent(Component)
return (
<Component
{...props}
{...routerProps}
{...asyncProps}
reloadAsyncProps={reload}
loading={loading}
/>
)
}
})
const AsyncProps = React.createClass({
childContextTypes: {
asyncProps: object
},
propTypes: {
loadContext: object,
components: array.isRequired,
params: object.isRequired,
location: object.isRequired,
onError: func.isRequired,
renderLoading: func.isRequired,
// server rendering
propsArray: array,
componentsArray: array
},
getDefaultProps() {
return {
onError(err) {
throw err
},
renderLoading() {
return null
},
render(props) {
return <RouterContext {...props} createElement={createElement}/>
}
}
},
getInitialState() {
const { propsArray, componentsArray } = this.props
const isServerRender = propsArray && componentsArray
return {
loading: false,
prevProps: null,
propsAndComponents: isServerRender ?
{ propsArray, componentsArray } :
hydrate(this.props)
}
},
getChildContext() {
const { loading, propsAndComponents } = this.state
return {
asyncProps: {
loading,
propsAndComponents,
reloadComponent: (Component) => {
this.reloadComponent(Component)
}
}
}
},
componentDidMount() {
const wasHydrated = this.state.propsAndComponents !== null
if (!wasHydrated) {
const { components, params, location } = this.props
this.loadAsyncProps(components, params, location)
}
},
componentWillReceiveProps(nextProps) {
if (nextProps.location === this.props.location)
return
const { enterRoutes } = computeChangedRoutes(
{ routes: this.props.routes, params: this.props.params },
{ routes: nextProps.routes, params: nextProps.params }
)
const indexDiff = nextProps.components.length - enterRoutes.length
const components = []
for (let i = 0, l = enterRoutes.length; i < l; i++)
components.push(nextProps.components[indexDiff + i])
this.loadAsyncProps(
filterAndFlattenComponents(components),
nextProps.params,
nextProps.location
)
},
handleError(cb) {
return (err, ...args) => {
if (err && this.props.onError)
this.props.onError(err)
else
cb(null, ...args)
}
},
componentWillUnmount() {
this._unmounted = true
},
loadAsyncProps(components, params, location, options) {
const { loadContext } = this.props
this.setState({
loading: true,
prevProps: this.props
}, () => {
loadAsyncProps({
components: filterAndFlattenComponents(components),
params,
loadContext
}, this.handleError((err, propsAndComponents) => {
const reloading = options && options.reload
const didNotChangeRoutes = this.props.location === location
// FIXME: next line has potential (rare) race conditions I think. If
// somebody calls reloadAsyncProps, changes location, then changes
// location again before its done and state gets out of whack (Rx folks
// are like "LOL FLAT MAP LATEST NEWB"). Will revisit later.
if ((reloading || didNotChangeRoutes) && !this._unmounted) {
if (this.state.propsAndComponents) {
propsAndComponents = mergePropsAndComponents(
this.state.propsAndComponents,
propsAndComponents
)
}
this.setState({
loading: false,
propsAndComponents,
prevProps: null
})
}
}))
})
},
reloadComponent(Component) {
const { params } = this.props
this.loadAsyncProps([ Component ], params, null, { reload: true })
},
render() {
const { propsAndComponents } = this.state
if (!propsAndComponents) {
return this.props.renderLoading()
}
else {
const props = this.state.loading ? this.state.prevProps : this.props
return this.props.render(props)
}
}
})
export default AsyncProps