-
Notifications
You must be signed in to change notification settings - Fork 34
/
index.js
315 lines (280 loc) · 10 KB
/
index.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
/* eslint-disable no-console */
// Inspired by the awesome work by the Apollo team: 😘
// https://github.com/apollographql/react-apollo/blob/master/src/getDataFromTree.ts
//
// This version has been adapted to be Promise based and support native Preact.
const defaultOptions = {
componentWillUnmount: false,
}
const forwardRefSymbol = Symbol.for('react.forward_ref')
// Lifted from https://github.com/sindresorhus/p-reduce
// Thanks @sindresorhus! 🙏
const pReduce = (iterable, reducer, initVal) =>
new Promise((resolve, reject) => {
const iterator = iterable[Symbol.iterator]()
let i = 0
const next = total => {
const el = iterator.next()
if (el.done) {
resolve(total)
return
}
Promise.all([total, el.value])
.then(value => {
// eslint-disable-next-line no-plusplus
next(reducer(value[0], value[1], i++))
})
.catch(reject)
}
next(initVal)
})
// Lifted from https://github.com/sindresorhus/p-map-series
// Thanks @sindresorhus! 🙏
const pMapSeries = (iterable, iterator) => {
const ret = []
return pReduce(iterable, (a, b, i) =>
Promise.resolve(iterator(b, i)).then(val => {
ret.push(val)
}),
).then(() => ret)
}
const ensureChild = child =>
child && typeof child.render === 'function'
? ensureChild(child.render())
: child
// Preact puts children directly on element, and React via props
const getChildren = element =>
element.props && element.props.children
? element.props.children
: element.children
? element.children
: undefined
// Preact uses "nodeName", React uses "type"
const getType = element => element.type || element.nodeName
// Preact uses "attributes", React uses "props"
const getProps = element => element.props || element.attributes
const isReactElement = element => !!getType(element)
const isClassComponent = Comp =>
Comp.prototype &&
(Comp.prototype.render ||
Comp.prototype.isReactComponent ||
Comp.prototype.isPureReactComponent)
const isForwardRef = Comp =>
Comp.type && Comp.type.$$typeof === forwardRefSymbol
const providesChildContext = instance => !!instance.getChildContext
// Recurse a React Element tree, running the provided visitor against each element.
// If a visitor call returns `false` then we will not recurse into the respective
// elements children.
export default function reactTreeWalker(
tree,
visitor,
context,
options = defaultOptions,
) {
return new Promise((resolve, reject) => {
const safeVisitor = (...args) => {
try {
return visitor(...args)
} catch (err) {
reject(err)
}
return undefined
}
const recursive = (currentElement, currentContext) => {
if (Array.isArray(currentElement)) {
return Promise.all(
currentElement.map(item => recursive(item, currentContext)),
)
}
if (!currentElement) {
return Promise.resolve()
}
if (
typeof currentElement === 'string' ||
typeof currentElement === 'number'
) {
// Just visit these, they are leaves so we don't keep traversing.
safeVisitor(currentElement, null, currentContext)
return Promise.resolve()
}
if (currentElement.type) {
const _context =
currentElement.type._context ||
(currentElement.type.Provider &&
currentElement.type.Provider._context)
if (_context) {
if ('value' in currentElement.props) {
// <Provider>
// eslint-disable-next-line no-param-reassign
currentElement.type._context._currentValue =
currentElement.props.value
}
if (typeof currentElement.props.children === 'function') {
// <Consumer>
const el = currentElement.props.children(_context._currentValue)
return recursive(el, currentContext)
}
}
}
if (isReactElement(currentElement)) {
return new Promise(innerResolve => {
const visitCurrentElement = (
render,
compInstance,
elContext,
childContext,
) =>
Promise.resolve(
safeVisitor(
currentElement,
compInstance,
elContext,
childContext,
),
)
.then(result => {
if (result !== false) {
// A false wasn't returned so we will attempt to visit the children
// for the current element.
const tempChildren = render()
const children = ensureChild(tempChildren)
if (children) {
if (Array.isArray(children)) {
// If its a react Children collection we need to breadth-first
// traverse each of them, and pMapSeries allows us to do a
// depth-first traversal that respects Promises. Thanks @sindresorhus!
return pMapSeries(
children,
child =>
child
? recursive(child, childContext)
: Promise.resolve(),
)
.then(innerResolve, reject)
.catch(reject)
}
// Otherwise we pass the individual child to the next recursion.
return recursive(children, childContext)
.then(innerResolve, reject)
.catch(reject)
}
}
return undefined
})
.catch(reject)
if (
typeof getType(currentElement) === 'function' ||
isForwardRef(currentElement)
) {
const Component = getType(currentElement)
const props = Object.assign(
{},
Component.defaultProps,
getProps(currentElement),
// For Preact support so that the props get passed into render
// function.
{
children: getChildren(currentElement),
},
)
if (isForwardRef(currentElement)) {
visitCurrentElement(
() => currentElement.type.render(props),
null,
currentContext,
currentContext,
).then(innerResolve)
} else if (isClassComponent(Component)) {
// Class component
const instance = new Component(props, currentContext)
// In case the user doesn't pass these to super in the constructor
Object.defineProperty(instance, 'props', {
value: instance.props || props,
})
instance.context = instance.context || currentContext
// set the instance state to null (not undefined) if not set, to match React behaviour
instance.state = instance.state || null
// Make the setState synchronous.
instance.setState = newState => {
if (typeof newState === 'function') {
// eslint-disable-next-line no-param-reassign
newState = newState(
instance.state,
instance.props,
instance.context,
)
}
instance.state = Object.assign({}, instance.state, newState)
}
if (Component.getDerivedStateFromProps) {
const result = Component.getDerivedStateFromProps(
instance.props,
instance.state,
)
if (result !== null) {
instance.state = Object.assign({}, instance.state, result)
}
} else if (instance.UNSAFE_componentWillMount) {
instance.UNSAFE_componentWillMount()
} else if (instance.componentWillMount) {
instance.componentWillMount()
}
const childContext = providesChildContext(instance)
? Object.assign({}, currentContext, instance.getChildContext())
: currentContext
visitCurrentElement(
// Note: preact API also allows props and state to be referenced
// as arguments to the render func, so we pass them through
// here
() => instance.render(instance.props, instance.state),
instance,
currentContext,
childContext,
)
.then(() => {
if (
options.componentWillUnmount &&
instance.componentWillUnmount
) {
instance.componentWillUnmount()
}
})
.then(innerResolve)
} else {
// Stateless Functional Component
visitCurrentElement(
() => Component(props, currentContext),
null,
currentContext,
currentContext,
).then(innerResolve)
}
} else {
// A basic element, such as a dom node, string, number etc.
visitCurrentElement(
() => getChildren(currentElement),
null,
currentContext,
currentContext,
).then(innerResolve)
}
})
}
// Portals
if (
currentElement.containerInfo &&
currentElement.children &&
currentElement.children.props &&
Array.isArray(currentElement.children.props.children)
) {
return Promise.all(
currentElement.children.props.children.map(child =>
recursive(child, currentContext),
),
)
}
return Promise.resolve()
}
recursive(tree, context).then(resolve, reject)
})
}