-
-
Notifications
You must be signed in to change notification settings - Fork 1.7k
/
Copy pathreconciler.ts
426 lines (367 loc) Β· 13.7 KB
/
reconciler.ts
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
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
import * as THREE from 'three'
import Reconciler from 'react-reconciler'
import { ContinuousEventPriority, DiscreteEventPriority, DefaultEventPriority } from 'react-reconciler/constants'
import { unstable_IdlePriority as idlePriority, unstable_scheduleCallback as scheduleCallback } from 'scheduler'
import {
is,
diffProps,
applyProps,
invalidateInstance,
attach,
detach,
prepare,
globalScope,
now,
isObject3D,
} from './utils'
import type { RootStore } from './store'
import { removeInteractivity, type EventHandlers } from './events'
export interface Root {
fiber: Reconciler.FiberRoot
store: RootStore
}
export type AttachFnType<O = any> = (parent: any, self: O) => () => void
export type AttachType<O = any> = string | AttachFnType<O>
export type ConstructorRepresentation = new (...args: any[]) => any
export interface Catalogue {
[name: string]: ConstructorRepresentation
}
export type Args<T> = T extends ConstructorRepresentation ? ConstructorParameters<T> : any[]
export interface InstanceProps<T = any, P = any> {
args?: Args<P>
object?: T
visible?: boolean
dispose?: null
attach?: AttachType<T>
}
export interface Instance<O = any> {
root: RootStore
type: string
parent: Instance | null
children: Instance[]
props: InstanceProps<O> & Record<string, unknown>
object: O & { __r3f?: Instance<O> }
eventCount: number
handlers: Partial<EventHandlers>
attach?: AttachType<O>
previousAttach?: any
isHidden: boolean
autoRemovedBeforeAppend?: boolean
}
interface HostConfig {
type: string
props: Instance['props']
container: RootStore
instance: Instance
textInstance: void
suspenseInstance: Instance
hydratableInstance: never
publicInstance: Instance['object']
hostContext: never
updatePayload: null | [true] | [false, Instance['props']]
childSet: never
timeoutHandle: number | undefined
noTimeout: -1
}
const catalogue: Catalogue = {}
export const extend = (objects: Partial<Catalogue>): void => void Object.assign(catalogue, objects)
function createInstance(type: string, props: HostConfig['props'], root: RootStore): HostConfig['instance'] {
// Get target from catalogue
const name = `${type[0].toUpperCase()}${type.slice(1)}`
const target = catalogue[name]
// Validate element target
if (type !== 'primitive' && !target)
throw new Error(
`R3F: ${name} is not part of the THREE namespace! Did you forget to extend? See: https://docs.pmnd.rs/react-three-fiber/api/objects#using-3rd-party-objects-declaratively`,
)
// Validate primitives
if (type === 'primitive' && !props.object) throw new Error(`R3F: Primitives without 'object' are invalid!`)
// Throw if an object or literal was passed for args
if (props.args !== undefined && !Array.isArray(props.args)) throw new Error('R3F: The args prop must be an array!')
// Create instance
const object = props.object ?? new target(...(props.args ?? []))
const instance = prepare(object, root, type, props)
// Auto-attach geometries and materials
if (instance.props.attach === undefined) {
if (instance.object instanceof THREE.BufferGeometry) instance.props.attach = 'geometry'
else if (instance.object instanceof THREE.Material) instance.props.attach = 'material'
}
// Set initial props
applyProps(instance.object, props)
return instance
}
// https://github.com/facebook/react/issues/20271
// This will make sure events and attach are only handled once when trees are complete
function handleContainerEffects(parent: Instance, child: Instance) {
// Bail if tree isn't mounted or parent is not a container.
// This ensures that the tree is finalized and React won't discard results to Suspense
const state = child.root.getState()
if (!parent.parent && parent.object !== state.scene) return
// Handle interactivity
if (child.eventCount > 0 && child.object.raycast !== null && isObject3D(child.object)) {
state.internal.interaction.push(child.object)
}
// Handle attach
if (child.props.attach) attach(parent, child)
for (const childInstance of child.children) handleContainerEffects(child, childInstance)
}
function appendChild(parent: HostConfig['instance'], child: HostConfig['instance'] | HostConfig['textInstance']) {
if (!child) return
// Link instances
child.parent = parent
parent.children.push(child)
// Add Object3Ds if able
if (!child.props.attach && isObject3D(parent.object) && isObject3D(child.object)) {
parent.object.add(child.object)
}
// Attach tree once complete
handleContainerEffects(parent, child)
// Tree was updated, request a frame
invalidateInstance(child)
}
function insertBefore(
parent: HostConfig['instance'],
child: HostConfig['instance'] | HostConfig['textInstance'],
beforeChild: HostConfig['instance'] | HostConfig['textInstance'],
replace: boolean = false,
) {
if (!child || !beforeChild) return
// Link instances
child.parent = parent
const childIndex = parent.children.indexOf(beforeChild)
if (childIndex !== -1) parent.children.splice(childIndex, replace ? 1 : 0, child)
if (replace) beforeChild.parent = null
// Manually splice Object3Ds
if (!child.props.attach && isObject3D(parent.object) && isObject3D(child.object) && isObject3D(beforeChild.object)) {
child.object.parent = parent.object
parent.object.children.splice(parent.object.children.indexOf(beforeChild.object), replace ? 1 : 0, child.object)
child.object.dispatchEvent({ type: 'added' })
}
// Attach tree once complete
handleContainerEffects(parent, child)
// Tree was updated, request a frame
invalidateInstance(child)
}
function removeChild(
parent: HostConfig['instance'],
child: HostConfig['instance'] | HostConfig['textInstance'],
dispose?: boolean,
recursive?: boolean,
) {
if (!child) return
// Unlink instances
child.parent = null
if (recursive === undefined) {
const childIndex = parent.children.indexOf(child)
if (childIndex !== -1) parent.children.splice(childIndex, 1)
}
// Eagerly tear down tree
if (child.props.attach) {
detach(parent, child)
} else if (isObject3D(child.object) && isObject3D(parent.object)) {
parent.object.remove(child.object)
removeInteractivity(child.root, child.object)
}
// Allow objects to bail out of unmount disposal with dispose={null}
const shouldDispose = child.props.dispose !== null && dispose !== false
// Recursively remove instance children
if (recursive !== false) {
for (const node of child.children) removeChild(child, node, shouldDispose, true)
child.children = []
}
// Unlink instance object
delete child.object.__r3f
// Dispose object whenever the reconciler feels like it.
// Never dispose of primitives because their state may be kept outside of React!
// In order for an object to be able to dispose it
// - has a dispose method
// - cannot be a <primitive object={...} />
// - cannot be a THREE.Scene, because three has broken its own API
if (shouldDispose && child.type !== 'primitive' && child.object.type !== 'Scene') {
const dispose = child.object.dispose
if (typeof dispose === 'function') {
scheduleCallback(idlePriority, () => {
try {
dispose()
} catch (e) {
/* ... */
}
})
}
}
// Tree was updated, request a frame for top-level instance
if (dispose === undefined) invalidateInstance(child)
}
function switchInstance(
oldInstance: HostConfig['instance'],
type: HostConfig['type'],
props: HostConfig['props'],
fiber: Reconciler.Fiber,
) {
// Create a new instance
const newInstance = createInstance(type, props, oldInstance.root)
// Move children to new instance
for (const child of oldInstance.children) {
removeChild(oldInstance, child, false, false)
appendChild(newInstance, child)
}
oldInstance.children = []
// Link up new instance
const parent = oldInstance.parent
if (parent) {
// Manually handle replace https://github.com/pmndrs/react-three-fiber/pull/2680
// insertBefore(parent, newInstance, oldInstance, true)
if (!oldInstance.autoRemovedBeforeAppend) removeChild(parent, oldInstance)
if (newInstance.parent) newInstance.autoRemovedBeforeAppend = true
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.object)
else fiber.ref.current = newInstance.object
}
}
})
// Tree was updated, request a frame
invalidateInstance(newInstance)
return newInstance
}
// Don't handle text instances, warn on undefined behavior
const handleTextInstance = () =>
console.warn('R3F: Text is not allowed in JSX! This could be stray whitespace or characters.')
export const reconciler = Reconciler<
HostConfig['type'],
HostConfig['props'],
HostConfig['container'],
HostConfig['instance'],
HostConfig['textInstance'],
HostConfig['suspenseInstance'],
HostConfig['hydratableInstance'],
HostConfig['publicInstance'],
HostConfig['hostContext'],
HostConfig['updatePayload'],
HostConfig['childSet'],
HostConfig['timeoutHandle'],
HostConfig['noTimeout']
>({
supportsMutation: true,
isPrimaryRenderer: false,
supportsPersistence: false,
supportsHydration: false,
noTimeout: -1,
createInstance,
removeChild,
appendChild,
appendInitialChild: appendChild,
insertBefore,
appendChildToContainer(container, child) {
const scene = (container.getState().scene as unknown as Instance<THREE.Scene>['object']).__r3f
if (!child || !scene) return
appendChild(scene, child)
},
removeChildFromContainer(container, child) {
const scene = (container.getState().scene as unknown as Instance<THREE.Scene>['object']).__r3f
if (!child || !scene) return
removeChild(scene, child)
},
insertInContainerBefore(container, child, beforeChild) {
const scene = (container.getState().scene as unknown as Instance<THREE.Scene>['object']).__r3f
if (!child || !beforeChild || !scene) return
insertBefore(scene, child, beforeChild)
},
getRootHostContext: () => null,
getChildHostContext: (parentHostContext) => parentHostContext,
prepareUpdate(instance, _type, oldProps, newProps) {
// Reconstruct primitives if object prop changes
if (instance.type === 'primitive' && oldProps.object !== newProps.object) return [true]
// Throw if an object or literal was passed for args
if (newProps.args !== undefined && !Array.isArray(newProps.args))
throw new Error('R3F: The args prop must be an array!')
// Reconstruct instance if args change
if (newProps.args?.length !== oldProps.args?.length) return [true]
if (newProps.args?.some((value, index) => value !== oldProps.args?.[index])) return [true]
// Create a diff-set, flag if there are any changes
const changedProps = diffProps(instance, newProps, true)
if (Object.keys(changedProps).length) return [false, changedProps]
// Otherwise do not touch the instance
return null
},
commitUpdate(instance, diff, type, _oldProps, newProps, fiber) {
const [reconstruct, changedProps] = diff!
// Reconstruct when args or <primitive object={...} have changes
if (reconstruct) return switchInstance(instance, type, newProps, fiber)
// Otherwise just overwrite props
Object.assign(instance.props, changedProps)
applyProps(instance.object, changedProps)
},
finalizeInitialChildren: () => false,
commitMount() {},
getPublicInstance: (instance) => instance?.object!,
prepareForCommit: () => null,
preparePortalMount: (container) => prepare(container.getState().scene, container, '', {}),
resetAfterCommit: () => {},
shouldSetTextContent: () => false,
clearContainer: () => false,
hideInstance(instance) {
if (instance.props.attach && instance.parent?.object) {
detach(instance.parent, instance)
} else if (isObject3D(instance.object)) {
instance.object.visible = false
}
instance.isHidden = true
invalidateInstance(instance)
},
unhideInstance(instance) {
if (instance.isHidden) {
if (instance.props.attach && instance.parent?.object) {
attach(instance.parent, instance)
} else if (isObject3D(instance.object) && instance.props.visible !== false) {
instance.object.visible = true
}
}
instance.isHidden = false
invalidateInstance(instance)
},
createTextInstance: handleTextInstance,
hideTextInstance: handleTextInstance,
unhideTextInstance: handleTextInstance,
// SSR fallbacks
now,
scheduleTimeout: (is.fun(setTimeout) ? setTimeout : undefined) as any,
cancelTimeout: (is.fun(clearTimeout) ? clearTimeout : undefined) as any,
// @ts-ignore Deprecated experimental APIs
// https://github.com/facebook/react/blob/main/packages/shared/ReactFeatureFlags.js
// https://github.com/pmndrs/react-three-fiber/pull/2360#discussion_r916356874
beforeActiveInstanceBlur: () => {},
afterActiveInstanceBlur: () => {},
detachDeletedInstance: () => {},
// Gives React a clue as to how import the current interaction is
// https://github.com/facebook/react/tree/main/packages/react-reconciler#getcurrenteventpriority
getCurrentEventPriority() {
if (!globalScope) return DefaultEventPriority
const name = globalScope.event?.type
switch (name) {
case 'click':
case 'contextmenu':
case 'dblclick':
case 'pointercancel':
case 'pointerdown':
case 'pointerup':
return DiscreteEventPriority
case 'pointermove':
case 'pointerout':
case 'pointerover':
case 'pointerenter':
case 'pointerleave':
case 'wheel':
return ContinuousEventPriority
default:
return DefaultEventPriority
}
},
})