-
-
Notifications
You must be signed in to change notification settings - Fork 1.5k
/
reconciler.tsx
319 lines (294 loc) Β· 10.9 KB
/
reconciler.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
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
import * as THREE from 'three'
import Reconciler from 'react-reconciler'
import {
unstable_scheduleCallback as scheduleDeferredCallback,
unstable_cancelCallback as cancelDeferredCallback,
unstable_now as now,
unstable_IdlePriority as idlePriority,
unstable_runWithPriority as run,
} from 'scheduler'
const roots = new Map()
const emptyObject = {}
const is = {
obj: a => a === Object(a),
str: a => typeof a === 'string',
num: a => typeof a === 'number',
und: a => a === void 0,
arr: a => Array.isArray(a),
equ(a, b) {
// Wrong type, doesn't match
if (typeof a !== typeof b) return false
// Atomic, just compare a against b
if (is.str(a) || is.num(a) || is.obj(a)) return a === b
// Array, shallow compare first to see if it's a match
if (is.arr(a) && a == b) return true
// Last resort, go through keys
let i
for (i in a) if (!(i in b)) return false
for (i in b) if (a[i] !== b[i]) return false
return is.und(i) ? a === b : true
},
}
let globalEffects = []
export function addEffect(callback) {
globalEffects.push(callback)
}
export function renderGl(state, time, repeat = 0, runGlobalEffects = false) {
// Run global effects
if (runGlobalEffects) globalEffects.forEach(effect => effect(time) && repeat++)
// Decrease frame count
state.current.frames = Math.max(0, state.current.frames - 1)
repeat += !state.current.invalidateFrameloop ? 1 : state.current.frames
// Run local effects
state.current.subscribers.forEach(fn => fn(state.current, time))
// Render content
if (!state.current.manual) state.current.gl.render(state.current.scene, state.current.camera)
return repeat
}
let running = false
function renderLoop(t) {
running = true
let repeat = 0
// Run global effects
globalEffects.forEach(effect => effect(t) && repeat++)
roots.forEach(root => {
const state = root.containerInfo.__state
// If the frameloop is invalidated, do not run another frame
if (state.current.active && state.current.ready && (!state.current.invalidateFrameloop || state.current.frames > 0))
repeat = renderGl(state, t, repeat)
})
if (repeat !== 0) return requestAnimationFrame(renderLoop)
// Flag end of operation
running = false
}
export function invalidate(state, frames = 1) {
if (state && state.current) {
if (state.current.vr) return
state.current.frames = frames
} else if (state === true) roots.forEach(root => (root.containerInfo.__state.current.frames = frames))
if (!running) {
running = true
requestAnimationFrame(renderLoop)
}
}
let catalogue = {}
export const apply = objects => (catalogue = { ...catalogue, ...objects })
export function applyProps(instance, newProps, oldProps = {}, container) {
// Filter equals, events and reserved props
const sameProps = Object.keys(newProps).filter(key => is.equ(newProps[key], oldProps[key]))
const handlers = Object.keys(newProps).filter(key => typeof newProps[key] === 'function' && key.startsWith('on'))
const filteredProps = [...sameProps, 'children', 'key', 'ref'].reduce((acc, prop) => {
let { [prop]: _, ...rest } = acc
return rest
}, newProps)
if (Object.keys(filteredProps).length > 0) {
Object.entries(filteredProps).forEach(([key, value]) => {
if (!handlers.includes(key)) {
let root = instance
let target = root[key]
if (key.includes('-')) {
const entries = key.split('-')
target = entries.reduce((acc, key) => acc[key], instance)
// If the target is atomic, it forces us to switch the root
if (!(target && target.set)) {
const [name, ...reverseEntries] = entries.reverse()
root = reverseEntries.reverse().reduce((acc, key) => acc[key], instance)
key = name
}
}
// Special treatment for objects with support for set/copy
if (target && target.set && target.copy) {
if (target.constructor.name === value.constructor.name) target.copy(value)
else if (Array.isArray(value)) target.set(...value)
else target.set(value)
// Else, just overwrite the value
} else root[key] = value
invalidateInstance(instance)
}
})
// Prep interaction handlers
if (handlers.length) {
// Add interactive object to central container
if (container && instance.raycast && !(handlers.length === 1 && handlers[0] === 'onUpdate')) {
container.__interaction.push(instance)
}
instance.__handlers = handlers.reduce(
(acc, key) => ({ ...acc, [key.charAt(2).toLowerCase() + key.substr(3)]: newProps[key] }),
{}
)
}
// Call the update lifecycle when it is being updated
if (!container) updateInstance(instance)
}
}
function invalidateInstance(instance) {
if (instance.__container && instance.__container.__state) invalidate(instance.__container.__state)
}
function updateInstance(instance) {
if (instance.__handlers && instance.__handlers.update) instance.__handlers.update(instance)
}
function createInstance(type, { args = [], ...props }, container) {
let name = `${type[0].toUpperCase()}${type.slice(1)}`
let instance
if (type === 'primitive') instance = props.object
else {
const target = catalogue[name] || THREE[name]
instance = is.arr(args) ? new target(...args) : new target(args)
}
// Apply initial props
instance.__objects = []
instance.__container = container
applyProps(instance, props, {}, container)
return instance
}
function appendChild(parentInstance, child) {
if (child) {
if (child.isObject3D) parentInstance.add(child)
else {
parentInstance.__objects.push(child)
child.parent = parentInstance
// The attach attribute implies that the object attaches itself on the parent
if (child.attach) parentInstance[child.attach] = child
else if (child.attachArray) {
if (!is.arr(parentInstance[child.attachArray])) parentInstance[child.attachArray] = []
parentInstance[child.attachArray].push(child)
} else if (child.attachObject) {
if (!is.obj(parentInstance[child.attachObject[0]])) parentInstance[child.attachObject[0]] = {}
parentInstance[child.attachObject[0]][child.attachObject[1]] = child
}
}
updateInstance(child)
invalidateInstance(child)
}
}
function insertBefore(parentInstance, child, beforeChild) {
if (child) {
if (child.isObject3D) {
child.parent = parentInstance
child.dispatchEvent({ type: 'added' })
// TODO: the order is out of whack if data objects are present, has to be recalculated
const index = parentInstance.children.indexOf(beforeChild)
parentInstance.children = [
...parentInstance.children.slice(0, index),
child,
...parentInstance.children.slice(index),
]
updateInstance(child)
} else appendChild(parentInstance, child) // TODO: order!!!
invalidateInstance(child)
}
}
function removeChild(parentInstance, child) {
if (child) {
if (child.isObject3D) {
parentInstance.remove(child)
} else {
child.parent = undefined
parentInstance.__objects = parentInstance.__objects.filter(x => x !== child)
// Remove attachment
if (child.attach) parentInstance[child.attach] = undefined
else if (child.attachArray)
parentInstance[child.attachArray] = parentInstance[child.attachArray].filter(x => x !== child)
else if (child.attachObject) parentInstance[child.attachObject[0]][child.attachObject[1]] = undefined
}
invalidateInstance(child)
run(idlePriority, () => {
// Remove interactivity
if (child.__container) child.__container.__interaction = child.__container.__interaction.filter(x => x !== child)
// Remove nested child objects
if (child.__objects) child.__objects.forEach(obj => removeChild(child, obj))
if (child.children) child.children.forEach(obj => removeChild(child, obj))
// Dispose item
if (child.dispose) child.dispose()
// Remove references
delete child.__container
delete child.__objects
})
}
}
const Renderer = Reconciler({
now,
createInstance,
removeChild,
appendChild,
insertBefore,
supportsMutation: true,
isPrimaryRenderer: false,
schedulePassiveEffects: scheduleDeferredCallback,
cancelPassiveEffects: cancelDeferredCallback,
appendInitialChild: appendChild,
appendChildToContainer: appendChild,
removeChildFromContainer: removeChild,
insertInContainerBefore: insertBefore,
commitUpdate(instance, updatePayload, type, oldProps, newProps, fiber) {
if (instance.isObject3D) {
applyProps(instance, newProps, oldProps)
} else {
// This is a data object, let's extract critical information about it
const parent = instance.parent
const { args: argsNew = [], ...restNew } = newProps
const { args: argsOld = [], ...restOld } = oldProps
// If it has new props or arguments, then it needs to be re-instanciated
// TODO, are colors falsely detected here?
if (argsNew.some((value, index) => value !== argsOld[index])) {
// Next we create a new instance and append it again
const newInstance = createInstance(type, newProps, instance.__container)
removeChild(parent, instance)
appendChild(parent, newInstance)
// This evil hack switches the react-internal fiber node
// https://github.com/facebook/react/issues/14983
// https://github.com/facebook/react/pull/15021
;[fiber, fiber.alternate].forEach(fiber => {
if (fiber !== null) {
fiber.stateNode = newInstance
if (fiber.ref) {
if (typeof fiber.ref === 'function') fiber.ref(newInstance)
else fiber.ref.current = newInstance
}
}
})
} else {
// Otherwise just overwrite props
applyProps(instance, restNew, restOld)
}
}
},
getPublicInstance(instance) {
return instance
},
getRootHostContext(rootContainerInstance) {
return emptyObject
},
getChildHostContext(parentHostContext, type) {
return emptyObject
},
createTextInstance() {},
finalizeInitialChildren(instance, type, props, rootContainerInstance) {
return false
},
prepareUpdate(instance, type, oldProps, newProps, rootContainerInstance, hostContext) {
return emptyObject
},
shouldDeprioritizeSubtree(type, props) {
return false
},
prepareForCommit() {},
resetAfterCommit() {},
shouldSetTextContent(props) {
return false
},
})
export function render(element, container, state) {
let root = roots.get(container)
if (!root) {
root = Renderer.createContainer(container)
container.__state = state
roots.set(container, root)
}
Renderer.updateContainer(element, root, null, undefined)
return Renderer.getPublicRootInstance(root)
}
export function unmountComponentAtNode(container) {
const root = roots.get(container)
if (root) Renderer.updateContainer(null, root, null, () => roots.delete(container))
}