@react-three/fiber 8.0.0-alpha.0 → 8.0.0-beta-04

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (33) hide show
  1. package/CHANGELOG.md +103 -0
  2. package/dist/declarations/src/core/events.d.ts +64 -59
  3. package/dist/declarations/src/core/hooks.d.ts +21 -29
  4. package/dist/declarations/src/core/index.d.ts +31 -0
  5. package/dist/declarations/src/core/loop.d.ts +12 -12
  6. package/dist/declarations/src/core/renderer.d.ts +50 -52
  7. package/dist/declarations/src/core/store.d.ts +117 -106
  8. package/dist/declarations/src/core/utils.d.ts +50 -0
  9. package/dist/declarations/src/index.d.ts +10 -7
  10. package/dist/declarations/src/native/Canvas.d.ts +13 -0
  11. package/dist/declarations/src/native/events.d.ts +5 -0
  12. package/dist/declarations/src/native/hooks.d.ts +9 -0
  13. package/dist/declarations/src/native.d.ts +10 -0
  14. package/dist/declarations/src/three-types.d.ts +309 -320
  15. package/dist/declarations/src/web/Canvas.d.ts +13 -13
  16. package/dist/declarations/src/web/events.d.ts +4 -4
  17. package/dist/index-eb414398.cjs.prod.js +1805 -0
  18. package/dist/index-fccd77b0.esm.js +1750 -0
  19. package/dist/index-ff3eb68b.cjs.dev.js +1805 -0
  20. package/dist/react-three-fiber.cjs.dev.js +108 -1734
  21. package/dist/react-three-fiber.cjs.prod.js +108 -1734
  22. package/dist/react-three-fiber.esm.js +63 -1686
  23. package/native/dist/react-three-fiber-native.cjs.d.ts +1 -0
  24. package/native/dist/react-three-fiber-native.cjs.dev.js +388 -0
  25. package/native/dist/react-three-fiber-native.cjs.js +7 -0
  26. package/native/dist/react-three-fiber-native.cjs.prod.js +388 -0
  27. package/native/dist/react-three-fiber-native.esm.js +336 -0
  28. package/native/package.json +5 -0
  29. package/package.json +19 -8
  30. package/readme.md +10 -10
  31. package/__mocks__/react-use-measure/index.ts +0 -22
  32. package/dist/declarations/src/core/is.d.ts +0 -9
  33. package/dist/declarations/src/web/index.d.ts +0 -30
@@ -1,1404 +1,35 @@
1
- import * as THREE from 'three';
1
+ import { c as createEvents, e as extend, p as pick, o as omit, a as createRoot, u as unmountComponentAtNode } from './index-fccd77b0.esm.js';
2
+ export { t as ReactThreeFiber, y as _roots, x as act, v as addAfterEffect, s as addEffect, w as addTail, q as advance, l as applyProps, i as context, j as createPortal, a as createRoot, m as dispose, e as extend, n as invalidate, k as reconciler, r as render, u as unmountComponentAtNode, f as useFrame, g as useGraph, h as useLoader, b as useStore, d as useThree } from './index-fccd77b0.esm.js';
3
+ import _extends from '@babel/runtime/helpers/esm/extends';
2
4
  import * as React from 'react';
3
- import { DefaultEventPriority, ConcurrentRoot } from 'react-reconciler/constants';
4
- import create from 'zustand';
5
- import shallow from 'zustand/shallow';
6
- import Reconciler from 'react-reconciler';
7
- import { unstable_now, unstable_runWithPriority, unstable_IdlePriority } from 'scheduler';
8
- import { useAsset } from 'use-asset';
5
+ import * as THREE from 'three';
9
6
  import mergeRefs from 'react-merge-refs';
10
7
  import useMeasure from 'react-use-measure';
11
-
12
- var threeTypes = /*#__PURE__*/Object.freeze({
13
- __proto__: null
14
- });
15
-
16
- const is = {
17
- obj: a => a === Object(a) && !is.arr(a) && typeof a !== 'function',
18
- fun: a => typeof a === 'function',
19
- str: a => typeof a === 'string',
20
- num: a => typeof a === 'number',
21
- und: a => a === void 0,
22
- arr: a => Array.isArray(a),
23
-
24
- equ(a, b) {
25
- // Wrong type or one of the two undefined, doesn't match
26
- if (typeof a !== typeof b || !!a !== !!b) return false; // Atomic, just compare a against b
27
-
28
- if (is.str(a) || is.num(a) || is.obj(a)) return a === b; // Array, shallow compare first to see if it's a match
29
-
30
- if (is.arr(a) && a == b) return true; // Last resort, go through keys
31
-
32
- let i;
33
-
34
- for (i in a) if (!(i in b)) return false;
35
-
36
- for (i in b) if (a[i] !== b[i]) return false;
37
-
38
- return is.und(i) ? a === b : true;
39
- }
40
-
8
+ import 'suspend-react';
9
+ import 'react-reconciler/constants';
10
+ import 'zustand';
11
+ import 'react-reconciler';
12
+ import 'scheduler';
13
+
14
+ const DOM_EVENTS = {
15
+ onClick: ['click', false],
16
+ onContextMenu: ['contextmenu', false],
17
+ onDoubleClick: ['dblclick', false],
18
+ onWheel: ['wheel', true],
19
+ onPointerDown: ['pointerdown', true],
20
+ onPointerUp: ['pointerup', true],
21
+ onPointerLeave: ['pointerleave', true],
22
+ onPointerMove: ['pointermove', true],
23
+ onPointerCancel: ['pointercancel', true],
24
+ onLostPointerCapture: ['lostpointercapture', true]
41
25
  };
42
-
43
- function makeId(event) {
44
- return (event.eventObject || event.object).uuid + '/' + event.index;
45
- }
46
-
47
- function removeInteractivity(store, object) {
48
- const {
49
- internal
50
- } = store.getState(); // Removes every trace of an object from the data store
51
-
52
- internal.interaction = internal.interaction.filter(o => o !== object);
53
- internal.initialHits = internal.initialHits.filter(o => o !== object);
54
- internal.hovered.forEach((value, key) => {
55
- if (value.eventObject === object || value.object === object) {
56
- internal.hovered.delete(key);
57
- }
58
- });
59
- }
60
- function createEvents(store) {
61
- const temp = new THREE.Vector3();
62
- /** Sets up defaultRaycaster */
63
-
64
- function prepareRay(event) {
65
- var _raycaster$computeOff;
66
-
67
- const state = store.getState();
68
- const {
69
- raycaster,
70
- mouse,
71
- camera,
72
- size
73
- } = state; // https://github.com/pmndrs/react-three-fiber/pull/782
74
- // Events trigger outside of canvas when moved
75
-
76
- const {
77
- offsetX,
78
- offsetY
79
- } = (_raycaster$computeOff = raycaster.computeOffsets == null ? void 0 : raycaster.computeOffsets(event, state)) != null ? _raycaster$computeOff : event;
80
- const {
81
- width,
82
- height
83
- } = size;
84
- mouse.set(offsetX / width * 2 - 1, -(offsetY / height) * 2 + 1);
85
- raycaster.setFromCamera(mouse, camera);
86
- }
87
- /** Calculates delta */
88
-
89
-
90
- function calculateDistance(event) {
91
- const {
92
- internal
93
- } = store.getState();
94
- const dx = event.offsetX - internal.initialClick[0];
95
- const dy = event.offsetY - internal.initialClick[1];
96
- return Math.round(Math.sqrt(dx * dx + dy * dy));
97
- }
98
- /** Returns true if an instance has a valid pointer-event registered, this excludes scroll, clicks etc */
99
-
100
-
101
- function filterPointerEvents(objects) {
102
- return objects.filter(obj => ['Move', 'Over', 'Enter', 'Out', 'Leave'].some(name => {
103
- var _r3f$handlers;
104
-
105
- return (_r3f$handlers = obj.__r3f.handlers) == null ? void 0 : _r3f$handlers['onPointer' + name];
106
- }));
107
- }
108
-
109
- function intersect(filter) {
110
- const state = store.getState();
111
- const {
112
- raycaster,
113
- internal
114
- } = state; // Skip event handling when noEvents is set
115
-
116
- if (!raycaster.enabled) return [];
117
- const seen = new Set();
118
- const intersections = []; // Allow callers to eliminate event objects
119
-
120
- const eventsObjects = filter ? filter(internal.interaction) : internal.interaction; // Intersect known handler objects and filter against duplicates
121
-
122
- let intersects = raycaster.intersectObjects(eventsObjects, true).filter(item => {
123
- const id = makeId(item);
124
- if (seen.has(id)) return false;
125
- seen.add(id);
126
- return true;
127
- }); // https://github.com/mrdoob/three.js/issues/16031
128
- // Allow custom userland intersect sort order
129
-
130
- if (raycaster.filter) intersects = raycaster.filter(intersects, state);
131
-
132
- for (const intersect of intersects) {
133
- let eventObject = intersect.object; // Bubble event up
134
-
135
- while (eventObject) {
136
- var _r3f;
137
-
138
- const handlers = (_r3f = eventObject.__r3f) == null ? void 0 : _r3f.handlers;
139
- if (handlers) intersections.push({ ...intersect,
140
- eventObject
141
- });
142
- eventObject = eventObject.parent;
143
- }
144
- }
145
-
146
- return intersections;
147
- }
148
- /** Creates filtered intersects and returns an array of positive hits */
149
-
150
-
151
- function patchIntersects(intersections, event) {
152
- const {
153
- internal
154
- } = store.getState(); // If the interaction is captured, make all capturing targets part of the
155
- // intersect.
156
-
157
- if ('pointerId' in event && internal.capturedMap.has(event.pointerId)) {
158
- intersections.push(...internal.capturedMap.get(event.pointerId).values());
159
- }
160
-
161
- return intersections;
162
- }
163
- /** Handles intersections by forwarding them to handlers */
164
-
165
-
166
- function handleIntersects(intersections, event, callback) {
167
- const {
168
- raycaster,
169
- mouse,
170
- camera,
171
- internal
172
- } = store.getState(); // If anything has been found, forward it to the event listeners
173
-
174
- if (intersections.length) {
175
- const unprojectedPoint = temp.set(mouse.x, mouse.y, 0).unproject(camera);
176
- const delta = event.type === 'click' ? calculateDistance(event) : 0;
177
-
178
- const releasePointerCapture = id => event.target.releasePointerCapture(id);
179
-
180
- const localState = {
181
- stopped: false
182
- };
183
-
184
- for (const hit of intersections) {
185
- const hasPointerCapture = id => {
186
- var _internal$capturedMap, _internal$capturedMap2;
187
-
188
- return (_internal$capturedMap = (_internal$capturedMap2 = internal.capturedMap.get(id)) == null ? void 0 : _internal$capturedMap2.has(hit.eventObject)) != null ? _internal$capturedMap : false;
189
- };
190
-
191
- const setPointerCapture = id => {
192
- if (internal.capturedMap.has(id)) {
193
- // if the pointerId was previously captured, we add the hit to the
194
- // event capturedMap.
195
- internal.capturedMap.get(id).set(hit.eventObject, hit);
196
- } else {
197
- // if the pointerId was not previously captured, we create a map
198
- // containing the hitObject, and the hit. hitObject is used for
199
- // faster access.
200
- internal.capturedMap.set(id, new Map([[hit.eventObject, hit]]));
201
- } // Call the original event now
202
- event.target.setPointerCapture(id);
203
- }; // Add native event props
204
-
205
-
206
- let extractEventProps = {};
207
-
208
- for (let prop in Object.getPrototypeOf(event)) {
209
- let property = event[prop]; // Only copy over atomics, leave functions alone as these should be
210
- // called as event.nativeEvent.fn()
211
-
212
- if (typeof property !== 'function') extractEventProps[prop] = property;
213
- }
214
-
215
- let raycastEvent = { ...hit,
216
- ...extractEventProps,
217
- spaceX: mouse.x,
218
- spaceY: mouse.y,
219
- intersections,
220
- stopped: localState.stopped,
221
- delta,
222
- unprojectedPoint,
223
- ray: raycaster.ray,
224
- camera: camera,
225
- // Hijack stopPropagation, which just sets a flag
226
- stopPropagation: () => {
227
- // https://github.com/pmndrs/react-three-fiber/issues/596
228
- // Events are not allowed to stop propagation if the pointer has been captured
229
- const capturesForPointer = 'pointerId' in event && internal.capturedMap.get(event.pointerId); // We only authorize stopPropagation...
230
-
231
- if ( // ...if this pointer hasn't been captured
232
- !capturesForPointer || // ... or if the hit object is capturing the pointer
233
- capturesForPointer.has(hit.eventObject)) {
234
- raycastEvent.stopped = localState.stopped = true; // Propagation is stopped, remove all other hover records
235
- // An event handler is only allowed to flush other handlers if it is hovered itself
236
-
237
- if (internal.hovered.size && Array.from(internal.hovered.values()).find(i => i.eventObject === hit.eventObject)) {
238
- // Objects cannot flush out higher up objects that have already caught the event
239
- const higher = intersections.slice(0, intersections.indexOf(hit));
240
- cancelPointer([...higher, hit]);
241
- }
242
- }
243
- },
244
- // there should be a distinction between target and currentTarget
245
- target: {
246
- hasPointerCapture,
247
- setPointerCapture,
248
- releasePointerCapture
249
- },
250
- currentTarget: {
251
- hasPointerCapture,
252
- setPointerCapture,
253
- releasePointerCapture
254
- },
255
- sourceEvent: event,
256
- // deprecated
257
- nativeEvent: event
258
- }; // Call subscribers
259
-
260
- callback(raycastEvent); // Event bubbling may be interrupted by stopPropagation
261
-
262
- if (localState.stopped === true) break;
263
- }
264
- }
265
-
266
- return intersections;
267
- }
268
-
269
- function cancelPointer(hits) {
270
- const {
271
- internal
272
- } = store.getState();
273
- Array.from(internal.hovered.values()).forEach(hoveredObj => {
274
- // When no objects were hit or the the hovered object wasn't found underneath the cursor
275
- // we call onPointerOut and delete the object from the hovered-elements map
276
- if (!hits.length || !hits.find(hit => hit.object === hoveredObj.object && hit.index === hoveredObj.index)) {
277
- const eventObject = hoveredObj.eventObject;
278
- const handlers = eventObject.__r3f.handlers;
279
- internal.hovered.delete(makeId(hoveredObj));
280
-
281
- if (handlers) {
282
- // Clear out intersects, they are outdated by now
283
- const data = { ...hoveredObj,
284
- intersections: hits || []
285
- };
286
- handlers.onPointerOut == null ? void 0 : handlers.onPointerOut(data);
287
- handlers.onPointerLeave == null ? void 0 : handlers.onPointerLeave(data);
288
- }
289
- }
290
- });
291
- }
292
-
293
- const handlePointer = name => {
294
- // Deal with cancelation
295
- switch (name) {
296
- case 'onPointerLeave':
297
- case 'onPointerCancel':
298
- return () => cancelPointer([]);
299
-
300
- case 'onLostPointerCapture':
301
- return event => {
302
- if ('pointerId' in event) {
303
- // this will be a problem if one target releases the pointerId
304
- // and another one is still keeping it, as the line below
305
- // indifferently deletes all capturing references.
306
- store.getState().internal.capturedMap.delete(event.pointerId);
307
- }
308
-
309
- cancelPointer([]);
310
- };
311
- } // Any other pointer goes here ...
312
-
313
-
314
- return event => {
315
- const {
316
- onPointerMissed,
317
- internal
318
- } = store.getState();
319
- prepareRay(event); // Get fresh intersects
320
-
321
- const isPointerMove = name === 'onPointerMove';
322
- const filter = isPointerMove ? filterPointerEvents : undefined;
323
- const hits = patchIntersects(intersect(filter), event); // Take care of unhover
324
-
325
- if (isPointerMove) cancelPointer(hits);
326
- handleIntersects(hits, event, data => {
327
- const eventObject = data.eventObject;
328
- const handlers = eventObject.__r3f.handlers; // Check presence of handlers
329
-
330
- if (!handlers) return;
331
-
332
- if (isPointerMove) {
333
- // Move event ...
334
- if (handlers.onPointerOver || handlers.onPointerEnter || handlers.onPointerOut || handlers.onPointerLeave) {
335
- // When enter or out is present take care of hover-state
336
- const id = makeId(data);
337
- const hoveredItem = internal.hovered.get(id);
338
-
339
- if (!hoveredItem) {
340
- // If the object wasn't previously hovered, book it and call its handler
341
- internal.hovered.set(id, data);
342
- handlers.onPointerOver == null ? void 0 : handlers.onPointerOver(data);
343
- handlers.onPointerEnter == null ? void 0 : handlers.onPointerEnter(data);
344
- } else if (hoveredItem.stopped) {
345
- // If the object was previously hovered and stopped, we shouldn't allow other items to proceed
346
- data.stopPropagation();
347
- }
348
- } // Call mouse move
349
-
350
-
351
- handlers.onPointerMove == null ? void 0 : handlers.onPointerMove(data);
352
- } else {
353
- // All other events ...
354
- const handler = handlers == null ? void 0 : handlers[name];
355
-
356
- if (handler) {
357
- // Forward all events back to their respective handlers with the exception of click events,
358
- // which must use the initial target
359
- if (name !== 'onClick' && name !== 'onContextMenu' && name !== 'onDoubleClick' || internal.initialHits.includes(eventObject)) {
360
- handler(data);
361
- pointerMissed(event, internal.interaction.filter(object => object !== eventObject));
362
- }
363
- }
364
- }
365
- }); // Save initial coordinates on pointer-down
366
-
367
- if (name === 'onPointerDown') {
368
- internal.initialClick = [event.offsetX, event.offsetY];
369
- internal.initialHits = hits.map(hit => hit.eventObject);
370
- } // If a click yields no results, pass it back to the user as a miss
371
-
372
-
373
- if ((name === 'onClick' || name === 'onContextMenu' || name === 'onDoubleClick') && !hits.length) {
374
- if (calculateDistance(event) <= 2) {
375
- pointerMissed(event, internal.interaction);
376
- if (onPointerMissed) onPointerMissed(event);
377
- }
378
- }
379
- };
380
- };
381
-
382
- function pointerMissed(event, objects) {
383
- objects.forEach(object => {
384
- var _r3f$handlers2;
385
-
386
- return (_r3f$handlers2 = object.__r3f.handlers) == null ? void 0 : _r3f$handlers2.onPointerMissed == null ? void 0 : _r3f$handlers2.onPointerMissed(event);
387
- });
388
- }
389
-
390
- return {
391
- handlePointer
392
- };
393
- }
394
-
395
- // Type guard to tell a store from a portal
396
- const isStore = def => def && !!def.getState;
397
-
398
- const getContainer = (container, child) => {
399
- var _container$__r3f$root, _container$__r3f;
400
-
401
- return {
402
- // If the container is not a root-store then it must be a THREE.Object3D into which part of the
403
- // scene is portalled into. Now there can be two variants of this, either that object is part of
404
- // the regular jsx tree, in which case it already has __r3f with a valid root attached, or it lies
405
- // outside react, in which case we must take the root of the child that is about to be attached to it.
406
- root: isStore(container) ? container : (_container$__r3f$root = (_container$__r3f = container.__r3f) == null ? void 0 : _container$__r3f.root) != null ? _container$__r3f$root : child.__r3f.root,
407
- // The container is the eventual target into which objects are mounted, it has to be a THREE.Object3D
408
- container: isStore(container) ? container.getState().scene : container
409
- };
410
- };
411
-
412
- const DEFAULT = '__default';
413
- const EMPTY = {};
414
- const FILTER = ['children', 'key', 'ref'];
415
- let catalogue = {};
416
-
417
- let extend = objects => void (catalogue = { ...catalogue,
418
- ...objects
419
- }); // Each object in the scene carries a small LocalState descriptor
420
-
421
-
422
- function prepare(object, state) {
423
- const instance = object;
424
-
425
- if (state != null && state.instance || !instance.__r3f) {
426
- instance.__r3f = {
427
- root: null,
428
- memoizedProps: {},
429
- objects: [],
430
- ...state
431
- };
432
- }
433
-
434
- return object;
435
- }
436
-
437
- function createRenderer(roots) {
438
- function applyProps(instance, newProps, oldProps = {}, accumulative = false) {
439
- var _instance$__r3f, _root$getState, _instance$__r3f2;
440
-
441
- // Filter equals, events and reserved props
442
- const localState = (_instance$__r3f = instance == null ? void 0 : instance.__r3f) != null ? _instance$__r3f : {};
443
- const root = localState.root;
444
- const rootState = (_root$getState = root == null ? void 0 : root.getState == null ? void 0 : root.getState()) != null ? _root$getState : {};
445
- const sameProps = [];
446
- const handlers = [];
447
- const newMemoizedProps = {};
448
- let i = 0;
449
- Object.entries(newProps).forEach(([key, entry]) => {
450
- // we don't want children, ref or key in the memoized props
451
- if (FILTER.indexOf(key) === -1) {
452
- newMemoizedProps[key] = entry;
453
- }
454
- });
455
-
456
- if (localState.memoizedProps && localState.memoizedProps.args) {
457
- newMemoizedProps.args = localState.memoizedProps.args;
458
- }
459
-
460
- if (localState.memoizedProps && localState.memoizedProps.attach) {
461
- newMemoizedProps.attach = localState.memoizedProps.attach;
462
- }
463
-
464
- if (instance.__r3f) {
465
- instance.__r3f.memoizedProps = newMemoizedProps;
466
- }
467
-
468
- let objectKeys = Object.keys(newProps);
469
-
470
- for (i = 0; i < objectKeys.length; i++) {
471
- if (is.equ(newProps[objectKeys[i]], oldProps[objectKeys[i]])) {
472
- sameProps.push(objectKeys[i]);
473
- } // Event-handlers ...
474
- // are functions, that
475
- // start with "on", and
476
- // contain the name "Pointer", "Click", "DoubleClick", "ContextMenu", or "Wheel"
477
-
478
-
479
- if (is.fun(newProps[objectKeys[i]]) && /^on(Pointer|Click|DoubleClick|ContextMenu|Wheel)/.test(objectKeys[i])) {
480
- handlers.push(objectKeys[i]);
481
- }
482
- } // Catch props that existed, but now exist no more ...
483
-
484
-
485
- const leftOvers = [];
486
-
487
- if (accumulative) {
488
- objectKeys = Object.keys(oldProps);
489
-
490
- for (i = 0; i < objectKeys.length; i++) {
491
- if (!newProps.hasOwnProperty(objectKeys[i])) {
492
- leftOvers.push(objectKeys[i]);
493
- }
494
- }
495
- }
496
-
497
- const toFilter = [...sameProps, ...FILTER]; // Instances use "object" as a reserved identifier
498
-
499
- if ((_instance$__r3f2 = instance.__r3f) != null && _instance$__r3f2.instance) toFilter.push('object');
500
- const filteredProps = { ...newProps
501
- }; // Removes sameProps and reserved props from newProps
502
-
503
- objectKeys = Object.keys(filteredProps);
504
-
505
- for (i = 0; i < objectKeys.length; i++) {
506
- if (toFilter.indexOf(objectKeys[i]) > -1) {
507
- delete filteredProps[objectKeys[i]];
508
- }
509
- } // Collect all new props
510
-
511
-
512
- const filteredPropsEntries = Object.entries(filteredProps); // Prepend left-overs so they can be reset or removed
513
- // Left-overs must come first!
514
-
515
- for (i = 0; i < leftOvers.length; i++) {
516
- if (leftOvers[i] !== 'children') {
517
- filteredPropsEntries.unshift([leftOvers[i], DEFAULT + 'remove']);
518
- }
519
- }
520
-
521
- if (filteredPropsEntries.length > 0) {
522
- filteredPropsEntries.forEach(([key, value]) => {
523
- if (!handlers.includes(key)) {
524
- let currentInstance = instance;
525
- let targetProp = currentInstance[key];
526
-
527
- if (key.includes('-')) {
528
- const entries = key.split('-');
529
- targetProp = entries.reduce((acc, key) => acc[key], instance); // If the target is atomic, it forces us to switch the root
530
-
531
- if (!(targetProp && targetProp.set)) {
532
- const [name, ...reverseEntries] = entries.reverse();
533
- currentInstance = reverseEntries.reverse().reduce((acc, key) => acc[key], instance);
534
- key = name;
535
- }
536
- } // https://github.com/mrdoob/three.js/issues/21209
537
- // HMR/fast-refresh relies on the ability to cancel out props, but threejs
538
- // has no means to do this. Hence we curate a small collection of value-classes
539
- // with their respective constructor/set arguments
540
- // For removed props, try to set default values, if possible
541
-
542
-
543
- if (value === DEFAULT + 'remove') {
544
- if (targetProp && targetProp.constructor) {
545
- // use the prop constructor to find the default it should be
546
- value = new targetProp.constructor(newMemoizedProps.args);
547
- } else if (currentInstance.constructor) {
548
- // create a blank slate of the instance and copy the particular parameter.
549
- // @ts-ignore
550
- const defaultClassCall = new currentInstance.constructor(currentInstance.__r3f.memoizedProps.args);
551
- value = defaultClassCall[targetProp]; // destory the instance
552
-
553
- if (defaultClassCall.dispose) {
554
- defaultClassCall.dispose();
555
- }
556
- } else {
557
- // instance does not have constructor, just set it to 0
558
- value = 0;
559
- }
560
- } // Special treatment for objects with support for set/copy, and layers
561
-
562
-
563
- if (targetProp && targetProp.set && (targetProp.copy || targetProp instanceof THREE.Layers)) {
564
- // If value is an array
565
- if (Array.isArray(value)) {
566
- if (targetProp.fromArray) {
567
- targetProp.fromArray(value);
568
- } else {
569
- targetProp.set(...value);
570
- }
571
- } // Test again target.copy(class) next ...
572
- else if (targetProp.copy && value && value.constructor && targetProp.constructor.name === value.constructor.name) {
573
- targetProp.copy(value);
574
- } // If nothing else fits, just set the single value, ignore undefined
575
- // https://github.com/react-spring/react-three-fiber/issues/274
576
- else if (value !== undefined) {
577
- const isColor = targetProp instanceof THREE.Color; // Allow setting array scalars
578
-
579
- if (!isColor && targetProp.setScalar) targetProp.setScalar(value); // Layers have no copy function, we must therefore copy the mask property
580
- else if (targetProp instanceof THREE.Layers && value instanceof THREE.Layers) targetProp.mask = value.mask; // Otherwise just set ...
581
- else targetProp.set(value); // Auto-convert sRGB colors, for now ...
582
- // https://github.com/react-spring/react-three-fiber/issues/344
583
-
584
- if (!rootState.linear && isColor) targetProp.convertSRGBToLinear();
585
- } // Else, just overwrite the value
586
-
587
- } else {
588
- currentInstance[key] = value; // Auto-convert sRGB textures, for now ...
589
- // https://github.com/react-spring/react-three-fiber/issues/344
590
-
591
- if (!rootState.linear && currentInstance[key] instanceof THREE.Texture) currentInstance[key].encoding = THREE.sRGBEncoding;
592
- }
593
-
594
- invalidateInstance(instance);
595
- }
596
- }); // Preemptively delete the instance from the containers interaction
597
-
598
- if (accumulative && root && instance.raycast && localState.handlers) {
599
- localState.handlers = undefined;
600
- const index = rootState.internal.interaction.indexOf(instance);
601
- if (index > -1) rootState.internal.interaction.splice(index, 1);
602
- } // Prep interaction handlers
603
-
604
-
605
- if (handlers.length) {
606
- if (accumulative && root && instance.raycast) {
607
- rootState.internal.interaction.push(instance);
608
- } // Add handlers to the instances handler-map
609
-
610
-
611
- localState.handlers = handlers.reduce((acc, key) => ({ ...acc,
612
- [key]: newProps[key]
613
- }), {});
614
- } // Call the update lifecycle when it is being updated, but only when it is part of the scene
615
-
616
-
617
- if (instance.parent) updateInstance(instance);
618
- }
619
- }
620
-
621
- function invalidateInstance(instance) {
622
- var _instance$__r3f3, _instance$__r3f3$root;
623
-
624
- const state = (_instance$__r3f3 = instance.__r3f) == null ? void 0 : (_instance$__r3f3$root = _instance$__r3f3.root) == null ? void 0 : _instance$__r3f3$root.getState == null ? void 0 : _instance$__r3f3$root.getState();
625
- if (state && state.internal.frames === 0) state.invalidate();
626
- }
627
-
628
- function updateInstance(instance) {
629
- instance.onUpdate == null ? void 0 : instance.onUpdate(instance);
630
- }
631
-
632
- function createInstance(type, {
633
- args = [],
634
- ...props
635
- }, root, hostContext, internalInstanceHandle) {
636
- let name = `${type[0].toUpperCase()}${type.slice(1)}`;
637
- let instance; // https://github.com/facebook/react/issues/17147
638
- // Portals do not give us a root, they are themselves treated as a root by the reconciler
639
- // In order to figure out the actual root we have to climb through fiber internals :(
640
-
641
- if (!isStore(root) && internalInstanceHandle) {
642
- const fn = node => {
643
- if (!node.return) return node.stateNode && node.stateNode.containerInfo;else return fn(node.return);
644
- };
645
-
646
- root = fn(internalInstanceHandle);
647
- } // Assert that by now we have a valid root
648
-
649
-
650
- if (!root || !isStore(root)) throw `No valid root for ${name}!`;
651
-
652
- if (type === 'primitive') {
653
- if (props.object === undefined) throw `Primitives without 'object' are invalid!`;
654
- const object = props.object;
655
- instance = prepare(object, {
656
- root,
657
- instance: true
658
- });
659
- } else {
660
- const target = catalogue[name] || THREE[name];
661
- if (!target) throw `${name} is not part of the THREE namespace! Did you forget to extend? See: https://github.com/pmndrs/react-three-fiber/blob/master/markdown/api.md#using-3rd-party-objects-declaratively`;
662
- const isArgsArr = is.arr(args); // Instanciate new object, link it to the root
663
-
664
- instance = prepare(isArgsArr ? new target(...args) : new target(args), {
665
- root,
666
- // append memoized props with args so it's not forgotten
667
- memoizedProps: {
668
- args: isArgsArr && args.length === 0 ? null : args
669
- }
670
- });
671
- } // Auto-attach geometries and materials
672
-
673
-
674
- if (!('attachFns' in props)) {
675
- if (name.endsWith('Geometry')) {
676
- props = {
677
- attach: 'geometry',
678
- ...props
679
- };
680
- } else if (name.endsWith('Material')) {
681
- props = {
682
- attach: 'material',
683
- ...props
684
- };
685
- }
686
- } // It should NOT call onUpdate on object instanciation, because it hasn't been added to the
687
- // view yet. If the callback relies on references for instance, they won't be ready yet, this is
688
- // why it passes "true" here
689
-
690
-
691
- applyProps(instance, props, {});
692
- return instance;
693
- }
694
-
695
- function appendChild(parentInstance, child) {
696
- let addedAsChild = false;
697
-
698
- if (child) {
699
- // The attach attribute implies that the object attaches itself on the parent
700
- if (child.attachArray) {
701
- if (!is.arr(parentInstance[child.attachArray])) parentInstance[child.attachArray] = [];
702
- parentInstance[child.attachArray].push(child);
703
- } else if (child.attachObject) {
704
- if (!is.obj(parentInstance[child.attachObject[0]])) parentInstance[child.attachObject[0]] = {};
705
- parentInstance[child.attachObject[0]][child.attachObject[1]] = child;
706
- } else if (child.attach && !is.fun(child.attach)) {
707
- parentInstance[child.attach] = child;
708
- } else if (is.arr(child.attachFns)) {
709
- const [attachFn] = child.attachFns;
710
-
711
- if (is.str(attachFn) && is.fun(parentInstance[attachFn])) {
712
- parentInstance[attachFn](child);
713
- } else if (is.fun(attachFn)) {
714
- attachFn(child, parentInstance);
715
- }
716
- } else if (child.isObject3D) {
717
- // add in the usual parent-child way
718
- parentInstance.add(child);
719
- addedAsChild = true;
720
- }
721
-
722
- if (!addedAsChild) {
723
- // This is for anything that used attach, and for non-Object3Ds that don't get attached to props;
724
- // that is, anything that's a child in React but not a child in the scenegraph.
725
- parentInstance.__r3f.objects.push(child);
726
-
727
- child.parent = parentInstance;
728
- }
729
-
730
- updateInstance(child);
731
- invalidateInstance(child);
732
- }
733
- }
734
-
735
- function insertBefore(parentInstance, child, beforeChild) {
736
- let added = false;
737
-
738
- if (child) {
739
- if (child.attachArray) {
740
- const array = parentInstance[child.attachArray];
741
- if (!is.arr(array)) parentInstance[child.attachArray] = [];
742
- array.splice(array.indexOf(beforeChild), 0, child);
743
- } else if (child.attachObject || child.attach && !is.fun(child.attach)) {
744
- // attach and attachObject don't have an order anyway, so just append
745
- return appendChild(parentInstance, child);
746
- } else if (child.isObject3D) {
747
- child.parent = parentInstance;
748
- child.dispatchEvent({
749
- type: 'added'
750
- });
751
- const restSiblings = parentInstance.children.filter(sibling => sibling !== child);
752
- const index = restSiblings.indexOf(beforeChild);
753
- parentInstance.children = [...restSiblings.slice(0, index), child, ...restSiblings.slice(index)];
754
- added = true;
755
- }
756
-
757
- if (!added) {
758
- parentInstance.__r3f.objects.push(child);
759
-
760
- child.parent = parentInstance;
761
- }
762
-
763
- updateInstance(child);
764
- invalidateInstance(child);
765
- }
766
- }
767
-
768
- function removeRecursive(array, parent, dispose = false) {
769
- if (array) [...array].forEach(child => removeChild(parent, child, dispose));
770
- }
771
-
772
- function removeChild(parentInstance, child, dispose) {
773
- if (child) {
774
- var _child$__r3f2;
775
-
776
- if (parentInstance.__r3f.objects) {
777
- const oldLength = parentInstance.__r3f.objects.length;
778
- parentInstance.__r3f.objects = parentInstance.__r3f.objects.filter(x => x !== child);
779
- const newLength = parentInstance.__r3f.objects.length; // was it in the list?
780
-
781
- if (newLength < oldLength) {
782
- // we had also set this, so we must clear it now
783
- child.parent = null;
784
- }
785
- } // Remove attachment
786
-
787
-
788
- if (child.attachArray) {
789
- parentInstance[child.attachArray] = parentInstance[child.attachArray].filter(x => x !== child);
790
- } else if (child.attachObject) {
791
- delete parentInstance[child.attachObject[0]][child.attachObject[1]];
792
- } else if (child.attach && !is.fun(child.attach)) {
793
- parentInstance[child.attach] = null;
794
- } else if (is.arr(child.attachFns)) {
795
- const [, detachFn] = child.attachFns;
796
-
797
- if (is.str(detachFn) && is.fun(parentInstance[detachFn])) {
798
- parentInstance[detachFn](child);
799
- } else if (is.fun(detachFn)) {
800
- detachFn(child, parentInstance);
801
- }
802
- } else if (child.isObject3D) {
803
- var _child$__r3f;
804
-
805
- parentInstance.remove(child); // Remove interactivity
806
-
807
- if ((_child$__r3f = child.__r3f) != null && _child$__r3f.root) {
808
- removeInteractivity(child.__r3f.root, child);
809
- }
810
- } // Allow objects to bail out of recursive dispose alltogether by passing dispose={null}
811
- // Never dispose of primitives because their state may be kept outside of React!
812
- // In order for an object to be able to dispose it has to have
813
- // - a dispose method,
814
- // - it cannot be an <instance object={...} />
815
- // - it cannot be a THREE.Scene, because three has broken it's own api
816
- //
817
- // Since disposal is recursive, we can check the optional dispose arg, which will be undefined
818
- // when the reconciler calls it, but then carry our own check recursively
819
-
820
-
821
- const isInstance = (_child$__r3f2 = child.__r3f) == null ? void 0 : _child$__r3f2.instance;
822
- const shouldDispose = dispose === undefined ? child.dispose !== null && !isInstance : dispose; // Remove nested child objects. Primitives should not have objects and children that are
823
- // attached to them declaratively ...
824
-
825
- if (!isInstance) {
826
- var _child$__r3f3;
827
-
828
- removeRecursive((_child$__r3f3 = child.__r3f) == null ? void 0 : _child$__r3f3.objects, child, shouldDispose);
829
- removeRecursive(child.children, child, shouldDispose);
830
- } // Remove references
831
-
832
-
833
- if (child.__r3f) {
834
- delete child.__r3f.root;
835
- delete child.__r3f.objects;
836
- delete child.__r3f.handlers;
837
- delete child.__r3f.memoizedProps;
838
- if (!isInstance) delete child.__r3f;
839
- } // Dispose item whenever the reconciler feels like it
840
-
841
-
842
- if (shouldDispose && child.dispose && child.type !== 'Scene') {
843
- unstable_runWithPriority(unstable_IdlePriority, () => child.dispose());
844
- }
845
-
846
- invalidateInstance(parentInstance);
847
- }
848
- }
849
-
850
- function switchInstance(instance, type, newProps, fiber) {
851
- const parent = instance.parent;
852
- if (!parent) return;
853
- const newInstance = createInstance(type, newProps, instance.__r3f.root); // https://github.com/pmndrs/react-three-fiber/issues/1348
854
- // When args change the instance has to be re-constructed, which then
855
- // forces r3f to re-parent the children and non-scene objects
856
-
857
- if (instance.children) {
858
- instance.children.forEach(child => appendChild(newInstance, child));
859
- instance.children = [];
860
- }
861
-
862
- instance.__r3f.objects.forEach(child => appendChild(newInstance, child));
863
-
864
- instance.__r3f.objects = [];
865
- removeChild(parent, instance);
866
- appendChild(parent, newInstance) // This evil hack switches the react-internal fiber node
867
- // https://github.com/facebook/react/issues/14983
868
- // https://github.com/facebook/react/pull/15021
869
- ;
870
- [fiber, fiber.alternate].forEach(fiber => {
871
- if (fiber !== null) {
872
- fiber.stateNode = newInstance;
873
-
874
- if (fiber.ref) {
875
- if (typeof fiber.ref === 'function') fiber.ref(newInstance);else fiber.ref.current = newInstance;
876
- }
877
- }
878
- });
879
- }
880
-
881
- const reconciler = Reconciler({
882
- now: unstable_now,
883
- createInstance,
884
- removeChild,
885
- appendChild,
886
- appendInitialChild: appendChild,
887
- insertBefore,
888
- warnsIfNotActing: true,
889
- supportsMutation: true,
890
- isPrimaryRenderer: false,
891
- getCurrentEventPriority: () => DefaultEventPriority,
892
- // @ts-ignore
893
- scheduleTimeout: is.fun(setTimeout) ? setTimeout : undefined,
894
- // @ts-ignore
895
- cancelTimeout: is.fun(clearTimeout) ? clearTimeout : undefined,
896
- // @ts-ignore
897
- setTimeout: is.fun(setTimeout) ? setTimeout : undefined,
898
- // @ts-ignore
899
- clearTimeout: is.fun(clearTimeout) ? clearTimeout : undefined,
900
- noTimeout: -1,
901
- appendChildToContainer: (parentInstance, child) => {
902
- const {
903
- container,
904
- root
905
- } = getContainer(parentInstance, child); // Link current root to the default scene
906
-
907
- container.__r3f.root = root;
908
- appendChild(container, child);
909
- },
910
- removeChildFromContainer: (parentInstance, child) => {
911
- const {
912
- container
913
- } = getContainer(parentInstance, child);
914
- removeChild(container, child);
915
- },
916
- insertInContainerBefore: (parentInstance, child, beforeChild) => {
917
- const {
918
- container
919
- } = getContainer(parentInstance, child);
920
- insertBefore(container, child, beforeChild);
921
- },
922
-
923
- commitUpdate(instance, updatePayload, type, oldProps, newProps, fiber) {
924
- if (instance.__r3f.instance && newProps.object && newProps.object !== instance) {
925
- // <instance object={...} /> where the object reference has changed
926
- switchInstance(instance, type, newProps, fiber);
927
- } else {
928
- // This is a data object, let's extract critical information about it
929
- const {
930
- args: argsNew = [],
931
- ...restNew
932
- } = newProps;
933
- const {
934
- args: argsOld = [],
935
- ...restOld
936
- } = oldProps; // If it has new props or arguments, then it needs to be re-instanciated
937
-
938
- const hasNewArgs = argsNew.some((value, index) => is.obj(value) ? Object.entries(value).some(([key, val]) => val !== argsOld[index][key]) : value !== argsOld[index]);
939
-
940
- if (hasNewArgs) {
941
- // Next we create a new instance and append it again
942
- switchInstance(instance, type, newProps, fiber);
943
- } else {
944
- // Otherwise just overwrite props
945
- applyProps(instance, restNew, restOld, true);
946
- }
947
- }
948
- },
949
-
950
- hideInstance(instance) {
951
- if (instance.isObject3D) {
952
- instance.visible = false;
953
- invalidateInstance(instance);
954
- }
955
- },
956
-
957
- unhideInstance(instance, props) {
958
- if (instance.isObject3D && props.visible == null || props.visible) {
959
- instance.visible = true;
960
- invalidateInstance(instance);
961
- }
962
- },
963
-
964
- hideTextInstance() {
965
- throw new Error('Text is not allowed in the R3F tree.');
966
- },
967
-
968
- getPublicInstance(instance) {
969
- // TODO: might fix switchInstance (?)
970
- return instance;
971
- },
972
-
973
- getRootHostContext(rootContainer) {
974
- return EMPTY;
975
- },
976
-
977
- getChildHostContext(parentHostContext) {
978
- return EMPTY;
979
- },
980
-
981
- createTextInstance() {},
982
-
983
- finalizeInitialChildren(instance) {
984
- // https://github.com/facebook/react/issues/20271
985
- // Returning true will trigger commitMount
986
- return !!instance.__r3f.handlers;
987
- },
988
-
989
- commitMount(instance)
990
- /*, type, props*/
991
- {
992
- // https://github.com/facebook/react/issues/20271
993
- // This will make sure events are only added once to the central container
994
- if (instance.raycast && instance.__r3f.handlers) instance.__r3f.root.getState().internal.interaction.push(instance);
995
- },
996
-
997
- prepareUpdate() {
998
- return EMPTY;
999
- },
1000
-
1001
- shouldDeprioritizeSubtree() {
1002
- return false;
1003
- },
1004
-
1005
- prepareForCommit() {
1006
- return null;
1007
- },
1008
-
1009
- preparePortalMount(...args) {// noop
1010
- },
1011
-
1012
- resetAfterCommit() {// noop
1013
- },
1014
-
1015
- shouldSetTextContent() {
1016
- return false;
1017
- },
1018
-
1019
- clearContainer() {
1020
- return false;
1021
- },
1022
-
1023
- detachDeletedInstance() {// noop
1024
- }
1025
-
1026
- });
1027
- return {
1028
- reconciler,
1029
- applyProps
1030
- };
1031
- }
1032
-
1033
- const isRenderer = def => def && !!def.render;
1034
- const isOrthographicCamera = def => def && def.isOrthographicCamera;
1035
- const context = /*#__PURE__*/React.createContext(null);
1036
-
1037
- const createStore = (applyProps, invalidate, advance, props) => {
1038
- const {
1039
- gl,
1040
- size,
1041
- shadows = false,
1042
- linear = false,
1043
- flat = false,
1044
- vr = false,
1045
- orthographic = false,
1046
- frameloop = 'always',
1047
- dpr = 1,
1048
- performance,
1049
- clock = new THREE.Clock(),
1050
- raycaster: raycastOptions,
1051
- camera: cameraOptions,
1052
- onPointerMissed
1053
- } = props; // Set shadowmap
1054
-
1055
- if (shadows) {
1056
- gl.shadowMap.enabled = true;
1057
- if (typeof shadows === 'object') Object.assign(gl.shadowMap, shadows);else gl.shadowMap.type = THREE.PCFSoftShadowMap;
1058
- } // Set color management
1059
-
1060
-
1061
- if (!linear) {
1062
- if (!flat) gl.toneMapping = THREE.ACESFilmicToneMapping;
1063
- gl.outputEncoding = THREE.sRGBEncoding;
1064
- } // clock.elapsedTime is updated using advance(timestamp)
1065
-
1066
-
1067
- if (frameloop === 'never') {
1068
- clock.stop();
1069
- clock.elapsedTime = 0;
1070
- }
1071
-
1072
- const rootState = create((set, get) => {
1073
- // Create custom raycaster
1074
- const raycaster = new THREE.Raycaster();
1075
- const {
1076
- params,
1077
- ...options
1078
- } = raycastOptions || {};
1079
- applyProps(raycaster, {
1080
- enabled: true,
1081
- ...options,
1082
- params: { ...raycaster.params,
1083
- ...params
1084
- }
1085
- }, {}); // Create default camera
1086
-
1087
- const isCamera = cameraOptions instanceof THREE.Camera;
1088
- const camera = isCamera ? cameraOptions : orthographic ? new THREE.OrthographicCamera(0, 0, 0, 0, 0.1, 1000) : new THREE.PerspectiveCamera(75, 0, 0.1, 1000);
1089
-
1090
- if (!isCamera) {
1091
- camera.position.z = 5;
1092
- if (cameraOptions) applyProps(camera, cameraOptions, {}); // Always look at center by default
1093
-
1094
- camera.lookAt(0, 0, 0);
1095
- }
1096
-
1097
- function setDpr(dpr) {
1098
- return Array.isArray(dpr) ? Math.min(Math.max(dpr[0], window.devicePixelRatio), dpr[1]) : dpr;
1099
- }
1100
-
1101
- const initialDpr = setDpr(dpr);
1102
- const position = new THREE.Vector3();
1103
- const defaultTarget = new THREE.Vector3();
1104
-
1105
- function getCurrentViewport(camera = get().camera, target = defaultTarget, size = get().size) {
1106
- const {
1107
- width,
1108
- height
1109
- } = size;
1110
- const aspect = width / height;
1111
- const distance = camera.getWorldPosition(position).distanceTo(target);
1112
-
1113
- if (isOrthographicCamera(camera)) {
1114
- return {
1115
- width: width / camera.zoom,
1116
- height: height / camera.zoom,
1117
- factor: 1,
1118
- distance,
1119
- aspect
1120
- };
1121
- } else {
1122
- const fov = camera.fov * Math.PI / 180; // convert vertical fov to radians
1123
-
1124
- const h = 2 * Math.tan(fov / 2) * distance; // visible height
1125
-
1126
- const w = h * (width / height);
1127
- return {
1128
- width: w,
1129
- height: h,
1130
- factor: width / w,
1131
- distance,
1132
- aspect
1133
- };
1134
- }
1135
- }
1136
-
1137
- let performanceTimeout = undefined;
1138
-
1139
- const setPerformanceCurrent = current => set(state => ({
1140
- performance: { ...state.performance,
1141
- current
1142
- }
1143
- }));
1144
-
1145
- return {
1146
- gl,
1147
- set,
1148
- get,
1149
- invalidate: () => invalidate(get()),
1150
- advance: (timestamp, runGlobalEffects) => advance(timestamp, runGlobalEffects, get()),
1151
- linear,
1152
- flat,
1153
- scene: prepare(new THREE.Scene()),
1154
- camera,
1155
- controls: null,
1156
- raycaster,
1157
- clock,
1158
- mouse: new THREE.Vector2(),
1159
- vr,
1160
- frameloop,
1161
- onPointerMissed,
1162
- performance: {
1163
- current: 1,
1164
- min: 0.5,
1165
- max: 1,
1166
- debounce: 200,
1167
- ...performance,
1168
- regress: () => {
1169
- const state = get(); // Clear timeout
1170
-
1171
- if (performanceTimeout) clearTimeout(performanceTimeout); // Set lower bound performance
1172
-
1173
- if (state.performance.current !== state.performance.min) setPerformanceCurrent(state.performance.min); // Go back to upper bound performance after a while unless something regresses meanwhile
1174
-
1175
- performanceTimeout = setTimeout(() => setPerformanceCurrent(get().performance.max), state.performance.debounce);
1176
- }
1177
- },
1178
- size: {
1179
- width: 0,
1180
- height: 0
1181
- },
1182
- viewport: {
1183
- initialDpr,
1184
- dpr: initialDpr,
1185
- width: 0,
1186
- height: 0,
1187
- aspect: 0,
1188
- distance: 0,
1189
- factor: 0,
1190
- getCurrentViewport
1191
- },
1192
- setSize: (width, height) => {
1193
- const size = {
1194
- width,
1195
- height
1196
- };
1197
- set(state => ({
1198
- size,
1199
- viewport: { ...state.viewport,
1200
- ...getCurrentViewport(camera, defaultTarget, size)
1201
- }
1202
- }));
1203
- },
1204
- setDpr: dpr => set(state => ({
1205
- viewport: { ...state.viewport,
1206
- dpr: setDpr(dpr)
1207
- }
1208
- })),
1209
- events: {
1210
- connected: false
1211
- },
1212
- internal: {
1213
- active: false,
1214
- priority: 0,
1215
- frames: 0,
1216
- lastProps: props,
1217
- interaction: [],
1218
- hovered: new Map(),
1219
- subscribers: [],
1220
- initialClick: [0, 0],
1221
- initialHits: [],
1222
- capturedMap: new Map(),
1223
- subscribe: (ref, priority = 0) => {
1224
- set(({
1225
- internal
1226
- }) => ({
1227
- internal: { ...internal,
1228
- // If this subscription was given a priority, it takes rendering into its own hands
1229
- // For that reason we switch off automatic rendering and increase the manual flag
1230
- // As long as this flag is positive (there could be multiple render subscription)
1231
- // ..there can be no internal rendering at all
1232
- priority: internal.priority + (priority > 0 ? 1 : 0),
1233
- // Register subscriber and sort layers from lowest to highest, meaning,
1234
- // highest priority renders last (on top of the other frames)
1235
- subscribers: [...internal.subscribers, {
1236
- ref,
1237
- priority
1238
- }].sort((a, b) => a.priority - b.priority)
1239
- }
1240
- }));
1241
- return () => {
1242
- set(({
1243
- internal
1244
- }) => ({
1245
- internal: { ...internal,
1246
- // Decrease manual flag if this subscription had a priority
1247
- priority: internal.priority - (priority > 0 ? 1 : 0),
1248
- // Remove subscriber from list
1249
- subscribers: internal.subscribers.filter(s => s.ref !== ref)
1250
- }
1251
- }));
1252
- };
1253
- }
1254
- }
1255
- };
1256
- }); // Resize camera and renderer on changes to size and pixelratio
1257
-
1258
- rootState.subscribe(() => {
1259
- const {
1260
- camera,
1261
- size,
1262
- viewport,
1263
- internal
1264
- } = rootState.getState(); // https://github.com/pmndrs/react-three-fiber/issues/92
1265
- // Do not mess with the camera if it belongs to the user
1266
-
1267
- if (!(internal.lastProps.camera instanceof THREE.Camera)) {
1268
- if (isOrthographicCamera(camera)) {
1269
- camera.left = size.width / -2;
1270
- camera.right = size.width / 2;
1271
- camera.top = size.height / 2;
1272
- camera.bottom = size.height / -2;
1273
- } else {
1274
- camera.aspect = size.width / size.height;
1275
- }
1276
-
1277
- camera.updateProjectionMatrix(); // https://github.com/pmndrs/react-three-fiber/issues/178
1278
- // Update matrix world since the renderer is a frame late
1279
-
1280
- camera.updateMatrixWorld();
1281
- } // Update renderer
1282
-
1283
-
1284
- gl.setPixelRatio(viewport.dpr);
1285
- gl.setSize(size.width, size.height);
1286
- }, state => [state.viewport.dpr, state.size], shallow);
1287
- const state = rootState.getState(); // Update size
1288
-
1289
- if (size) state.setSize(size.width, size.height); // Invalidate on any change
1290
-
1291
- rootState.subscribe(state => invalidate(state)); // Return root state
1292
-
1293
- return rootState;
1294
- };
1295
-
1296
- function createSubs(callback, subs) {
1297
- const index = subs.length;
1298
- subs.push(callback);
1299
- return () => void subs.splice(index, 1);
1300
- }
1301
-
1302
- let i;
1303
- let globalEffects = [];
1304
- let globalAfterEffects = [];
1305
- let globalTailEffects = [];
1306
- const addEffect = callback => createSubs(callback, globalEffects);
1307
- const addAfterEffect = callback => createSubs(callback, globalAfterEffects);
1308
- const addTail = callback => createSubs(callback, globalTailEffects);
1309
-
1310
- function run(effects, timestamp) {
1311
- for (i = 0; i < effects.length; i++) effects[i](timestamp);
1312
- }
1313
-
1314
- function render$1(timestamp, state) {
1315
- // Run local effects
1316
- let delta = state.clock.getDelta(); // In frameloop='never' mode, clock times are updated using the provided timestamp
1317
-
1318
- if (state.frameloop === 'never' && typeof timestamp === 'number') {
1319
- delta = timestamp - state.clock.elapsedTime;
1320
- state.clock.oldTime = state.clock.elapsedTime;
1321
- state.clock.elapsedTime = timestamp;
1322
- } // Call subscribers (useFrame)
1323
-
1324
-
1325
- for (i = 0; i < state.internal.subscribers.length; i++) state.internal.subscribers[i].ref.current(state, delta); // Render content
1326
-
1327
-
1328
- if (!state.internal.priority && state.gl.render) state.gl.render(state.scene, state.camera); // Decrease frame count
1329
-
1330
- state.internal.frames = Math.max(0, state.internal.frames - 1);
1331
- return state.frameloop === 'always' ? 1 : state.internal.frames;
1332
- }
1333
-
1334
- function createLoop(roots) {
1335
- let running = false;
1336
- let repeat;
1337
-
1338
- function loop(timestamp) {
1339
- running = true;
1340
- repeat = 0; // Run effects
1341
-
1342
- run(globalEffects, timestamp); // Render all roots
1343
-
1344
- roots.forEach(root => {
1345
- const state = root.store.getState(); // If the frameloop is invalidated, do not run another frame
1346
-
1347
- if (state.internal.active && (state.frameloop === 'always' || state.internal.frames > 0)) repeat += render$1(timestamp, state);
1348
- }); // Run after-effects
1349
-
1350
- run(globalAfterEffects, timestamp); // Keep on looping if anything invalidates the frameloop
1351
-
1352
- if (repeat > 0) return requestAnimationFrame(loop); // Tail call effects, they are called when rendering stops
1353
- else run(globalTailEffects, timestamp); // Flag end of operation
1354
-
1355
- running = false;
1356
- }
1357
-
1358
- function invalidate(state) {
1359
- if (!state) return roots.forEach(root => invalidate(root.store.getState()));
1360
- if (state.vr || !state.internal.active || state.frameloop === 'never') return; // Increase frames, do not go higher than 60
1361
-
1362
- state.internal.frames = Math.min(60, state.internal.frames + 1); // If the render-loop isn't active, start it
1363
-
1364
- if (!running) {
1365
- running = true;
1366
- requestAnimationFrame(loop);
1367
- }
1368
- }
1369
-
1370
- function advance(timestamp, runGlobalEffects = true, state) {
1371
- if (runGlobalEffects) run(globalEffects, timestamp);
1372
- if (!state) roots.forEach(root => render$1(timestamp, root.store.getState()));else render$1(timestamp, state);
1373
- if (runGlobalEffects) run(globalAfterEffects, timestamp);
1374
- }
1375
-
1376
- return {
1377
- loop,
1378
- invalidate,
1379
- advance
1380
- };
1381
- }
1382
-
1383
26
  function createPointerEvents(store) {
1384
27
  const {
1385
28
  handlePointer
1386
29
  } = createEvents(store);
1387
- const names = {
1388
- onClick: ['click', false],
1389
- onContextMenu: ['contextmenu', false],
1390
- onDoubleClick: ['dblclick', false],
1391
- onWheel: ['wheel', true],
1392
- onPointerDown: ['pointerdown', true],
1393
- onPointerUp: ['pointerup', true],
1394
- onPointerLeave: ['pointerleave', true],
1395
- onPointerMove: ['pointermove', true],
1396
- onPointerCancel: ['pointercancel', true],
1397
- onLostPointerCapture: ['lostpointercapture', true]
1398
- };
1399
30
  return {
1400
31
  connected: false,
1401
- handlers: Object.keys(names).reduce((acc, key) => ({ ...acc,
32
+ handlers: Object.keys(DOM_EVENTS).reduce((acc, key) => ({ ...acc,
1402
33
  [key]: handlePointer(key)
1403
34
  }), {}),
1404
35
  connect: target => {
@@ -1415,7 +46,7 @@ function createPointerEvents(store) {
1415
46
  }
1416
47
  }));
1417
48
  Object.entries((_events$handlers = events == null ? void 0 : events.handlers) != null ? _events$handlers : []).forEach(([name, event]) => {
1418
- const [eventName, passive] = names[name];
49
+ const [eventName, passive] = DOM_EVENTS[name];
1419
50
  target.addEventListener(eventName, event, {
1420
51
  passive
1421
52
  });
@@ -1432,7 +63,7 @@ function createPointerEvents(store) {
1432
63
 
1433
64
  Object.entries((_events$handlers2 = events.handlers) != null ? _events$handlers2 : []).forEach(([name, event]) => {
1434
65
  if (events && events.connected instanceof HTMLElement) {
1435
- const [eventName] = names[name];
66
+ const [eventName] = DOM_EVENTS[name];
1436
67
  events.connected.removeEventListener(eventName, event);
1437
68
  }
1438
69
  });
@@ -1446,18 +77,15 @@ function createPointerEvents(store) {
1446
77
  };
1447
78
  }
1448
79
 
1449
- // React currently throws a warning when using useLayoutEffect on the server.
1450
- // To get around it, we can conditionally useEffect on the server (no-op) and
1451
- // useLayoutEffect in the browser.
1452
- const useIsomorphicLayoutEffect = typeof window !== 'undefined' ? React.useLayoutEffect : React.useEffect;
80
+ const CANVAS_PROPS = ['gl', 'events', 'shadows', 'linear', 'flat', 'orthographic', 'frameloop', 'dpr', 'performance', 'clock', 'raycaster', 'camera', 'onPointerMissed', 'onCreated'];
1453
81
 
1454
82
  function Block({
1455
83
  set
1456
84
  }) {
1457
- useIsomorphicLayoutEffect(() => {
85
+ React.useLayoutEffect(() => {
1458
86
  set(new Promise(() => null));
1459
87
  return () => set(false);
1460
- }, []);
88
+ }, [set]);
1461
89
  return null;
1462
90
  }
1463
91
 
@@ -1486,15 +114,19 @@ ErrorBoundary.getDerivedStateFromError = () => ({
1486
114
  const Canvas = /*#__PURE__*/React.forwardRef(function Canvas({
1487
115
  children,
1488
116
  fallback,
1489
- tabIndex,
1490
117
  resize,
1491
- id,
1492
118
  style,
1493
- className,
1494
119
  events,
1495
120
  ...props
1496
121
  }, forwardedRef) {
1497
- const [containerRef, size] = useMeasure({
122
+ // Create a known catalogue of Threejs-native elements
123
+ // This will include the entire THREE namespace by default, users can extend
124
+ // their own elements by using the createRoot API instead
125
+ React.useMemo(() => extend(THREE), []);
126
+ const [containerRef, {
127
+ width,
128
+ height
129
+ }] = useMeasure({
1498
130
  scroll: true,
1499
131
  debounce: {
1500
132
  scroll: 50,
@@ -1503,36 +135,40 @@ const Canvas = /*#__PURE__*/React.forwardRef(function Canvas({
1503
135
  ...resize
1504
136
  });
1505
137
  const canvasRef = React.useRef(null);
138
+ const [canvas, setCanvas] = React.useState(null);
139
+ const canvasProps = pick(props, CANVAS_PROPS);
140
+ const divProps = omit(props, CANVAS_PROPS);
1506
141
  const [block, setBlock] = React.useState(false);
1507
142
  const [error, setError] = React.useState(false); // Suspend this component if block is a promise (2nd run)
1508
143
 
1509
144
  if (block) throw block; // Throw exception outwards if anything within canvas throws
1510
145
 
1511
- if (error) throw error; // Execute JSX in the reconciler as a layout-effect
146
+ if (error) throw error;
1512
147
 
1513
- useIsomorphicLayoutEffect(() => {
1514
- if (size.width > 0 && size.height > 0) {
1515
- render( /*#__PURE__*/React.createElement(ErrorBoundary, {
1516
- set: setError
1517
- }, /*#__PURE__*/React.createElement(React.Suspense, {
1518
- fallback: /*#__PURE__*/React.createElement(Block, {
1519
- set: setBlock
1520
- })
1521
- }, children)), canvasRef.current, { ...props,
1522
- size,
1523
- events: events || createPointerEvents
1524
- });
1525
- }
1526
- }, [size, children]);
1527
- React.useEffect(() => {
1528
- const container = canvasRef.current;
1529
- return () => unmountComponentAtNode(container);
148
+ if (width > 0 && height > 0 && canvas) {
149
+ createRoot(canvas, { ...canvasProps,
150
+ size: {
151
+ width,
152
+ height
153
+ },
154
+ events: events || createPointerEvents
155
+ }).render( /*#__PURE__*/React.createElement(ErrorBoundary, {
156
+ set: setError
157
+ }, /*#__PURE__*/React.createElement(React.Suspense, {
158
+ fallback: /*#__PURE__*/React.createElement(Block, {
159
+ set: setBlock
160
+ })
161
+ }, children)));
162
+ }
163
+
164
+ React.useLayoutEffect(() => {
165
+ setCanvas(canvasRef.current);
1530
166
  }, []);
1531
- return /*#__PURE__*/React.createElement("div", {
167
+ React.useEffect(() => {
168
+ return () => unmountComponentAtNode(canvas);
169
+ }, [canvas]);
170
+ return /*#__PURE__*/React.createElement("div", _extends({
1532
171
  ref: containerRef,
1533
- id: id,
1534
- className: className,
1535
- tabIndex: tabIndex,
1536
172
  style: {
1537
173
  position: 'relative',
1538
174
  width: '100%',
@@ -1540,7 +176,7 @@ const Canvas = /*#__PURE__*/React.forwardRef(function Canvas({
1540
176
  overflow: 'hidden',
1541
177
  ...style
1542
178
  }
1543
- }, /*#__PURE__*/React.createElement("canvas", {
179
+ }, divProps), /*#__PURE__*/React.createElement("canvas", {
1544
180
  ref: mergeRefs([canvasRef, forwardedRef]),
1545
181
  style: {
1546
182
  display: 'block'
@@ -1548,263 +184,4 @@ const Canvas = /*#__PURE__*/React.forwardRef(function Canvas({
1548
184
  }, fallback));
1549
185
  });
1550
186
 
1551
- function useStore() {
1552
- const store = React.useContext(context);
1553
- if (!store) throw `R3F hooks can only be used within the Canvas component!`;
1554
- return store;
1555
- }
1556
- function useThree(selector = state => state, equalityFn) {
1557
- return useStore()(selector, equalityFn);
1558
- }
1559
- function useFrame(callback, renderPriority = 0) {
1560
- const {
1561
- subscribe
1562
- } = useStore().getState().internal; // Update ref
1563
-
1564
- const ref = React.useRef(callback);
1565
- React.useLayoutEffect(() => void (ref.current = callback), [callback]); // Subscribe/unsub
1566
-
1567
- React.useLayoutEffect(() => {
1568
- const unsubscribe = subscribe(ref, renderPriority);
1569
- return () => unsubscribe();
1570
- }, [renderPriority, subscribe]);
1571
- return null;
1572
- }
1573
-
1574
- function buildGraph(object) {
1575
- const data = {
1576
- nodes: {},
1577
- materials: {}
1578
- };
1579
-
1580
- if (object) {
1581
- object.traverse(obj => {
1582
- if (obj.name) {
1583
- data.nodes[obj.name] = obj;
1584
- }
1585
-
1586
- if (obj.material && !data.materials[obj.material.name]) {
1587
- data.materials[obj.material.name] = obj.material;
1588
- }
1589
- });
1590
- }
1591
-
1592
- return data;
1593
- }
1594
-
1595
- function useGraph(object) {
1596
- return React.useMemo(() => buildGraph(object), [object]);
1597
- }
1598
-
1599
- function loadingFn(extensions, onProgress) {
1600
- return function (Proto, ...input) {
1601
- // Construct new loader and run extensions
1602
- const loader = new Proto();
1603
- if (extensions) extensions(loader); // Go through the urls and load them
1604
-
1605
- return Promise.all(input.map(input => new Promise((res, reject) => loader.load(input, data => {
1606
- if (data.scene) Object.assign(data, buildGraph(data.scene));
1607
- res(data);
1608
- }, onProgress, error => reject(`Could not load ${input}: ${error.message}`)))));
1609
- };
1610
- }
1611
-
1612
- function useLoader(Proto, input, extensions, onProgress) {
1613
- // Use suspense to load async assets
1614
- const keys = Array.isArray(input) ? input : [input];
1615
- const results = useAsset(loadingFn(extensions, onProgress), Proto, ...keys); // Return the object/s
1616
-
1617
- return Array.isArray(input) ? results : results[0];
1618
- }
1619
-
1620
- useLoader.preload = function (Proto, input, extensions) {
1621
- const keys = Array.isArray(input) ? input : [input];
1622
- return useAsset.preload(loadingFn(extensions), Proto, ...keys);
1623
- };
1624
-
1625
- useLoader.clear = function (Proto, input) {
1626
- const keys = Array.isArray(input) ? input : [input];
1627
- return useAsset.clear(Proto, ...keys);
1628
- };
1629
-
1630
- const roots = new Map();
1631
- const {
1632
- invalidate,
1633
- advance
1634
- } = createLoop(roots);
1635
- const {
1636
- reconciler,
1637
- applyProps
1638
- } = createRenderer();
1639
-
1640
- const createRendererInstance = (gl, canvas) => isRenderer(gl) ? gl : new THREE.WebGLRenderer({
1641
- powerPreference: 'high-performance',
1642
- canvas: canvas,
1643
- antialias: true,
1644
- alpha: true,
1645
- ...gl
1646
- });
1647
-
1648
- function render(element, canvas, {
1649
- gl,
1650
- size,
1651
- events,
1652
- onCreated,
1653
- ...props
1654
- } = {}) {
1655
- var _store;
1656
-
1657
- // Allow size to take on container bounds initially
1658
- if (!size) {
1659
- var _canvas$parentElement, _canvas$parentElement2, _canvas$parentElement3, _canvas$parentElement4;
1660
-
1661
- size = {
1662
- width: (_canvas$parentElement = (_canvas$parentElement2 = canvas.parentElement) == null ? void 0 : _canvas$parentElement2.clientWidth) != null ? _canvas$parentElement : 0,
1663
- height: (_canvas$parentElement3 = (_canvas$parentElement4 = canvas.parentElement) == null ? void 0 : _canvas$parentElement4.clientHeight) != null ? _canvas$parentElement3 : 0
1664
- };
1665
- }
1666
-
1667
- let root = roots.get(canvas);
1668
- let fiber = root == null ? void 0 : root.fiber;
1669
- let store = root == null ? void 0 : root.store;
1670
- let state = (_store = store) == null ? void 0 : _store.getState();
1671
-
1672
- if (fiber && state) {
1673
- const lastProps = state.internal.lastProps; // When a root was found, see if any fundamental props must be changed or exchanged
1674
- // Check pixelratio
1675
-
1676
- if (props.dpr !== undefined && !is.equ(lastProps.dpr, props.dpr)) state.setDpr(props.dpr); // Check size
1677
-
1678
- if (!is.equ(lastProps.size, size)) state.setSize(size.width, size.height); // For some props we want to reset the entire root
1679
- // Changes to the color-space
1680
-
1681
- const linearChanged = props.linear !== lastProps.linear;
1682
-
1683
- if (linearChanged) {
1684
- unmountComponentAtNode(canvas);
1685
- fiber = undefined;
1686
- }
1687
- }
1688
-
1689
- if (!fiber) {
1690
- // If no root has been found, make one
1691
- // Create gl
1692
- const glRenderer = createRendererInstance(gl, canvas); // Enable VR if requested
1693
-
1694
- if (props.vr) {
1695
- glRenderer.xr.enabled = true;
1696
- glRenderer.setAnimationLoop(timestamp => advance(timestamp, true));
1697
- } // Create store
1698
-
1699
-
1700
- store = createStore(applyProps, invalidate, advance, {
1701
- gl: glRenderer,
1702
- size,
1703
- ...props
1704
- });
1705
- const state = store.getState(); // Create renderer
1706
-
1707
- fiber = reconciler.createContainer(store, ConcurrentRoot, false, null); // Map it
1708
-
1709
- roots.set(canvas, {
1710
- fiber,
1711
- store
1712
- }); // Store events internally
1713
-
1714
- if (events) state.set({
1715
- events: events(store)
1716
- });
1717
- }
1718
-
1719
- if (store && fiber) {
1720
- reconciler.updateContainer( /*#__PURE__*/React.createElement(Provider, {
1721
- store: store,
1722
- element: element,
1723
- onCreated: onCreated,
1724
- target: canvas
1725
- }), fiber, null, () => undefined);
1726
- return store;
1727
- } else {
1728
- throw 'Error creating root!';
1729
- }
1730
- }
1731
-
1732
- function Provider({
1733
- store,
1734
- element,
1735
- onCreated,
1736
- target
1737
- }) {
1738
- React.useEffect(() => {
1739
- const state = store.getState(); // Flag the canvas active, rendering will now begin
1740
-
1741
- state.set(state => ({
1742
- internal: { ...state.internal,
1743
- active: true
1744
- }
1745
- })); // Connect events
1746
-
1747
- state.events.connect == null ? void 0 : state.events.connect(target); // Notifiy that init is completed, the scene graph exists, but nothing has yet rendered
1748
-
1749
- if (onCreated) onCreated(state);
1750
- }, []);
1751
- return /*#__PURE__*/React.createElement(context.Provider, {
1752
- value: store
1753
- }, element);
1754
- }
1755
-
1756
- function unmountComponentAtNode(canvas, callback) {
1757
- const root = roots.get(canvas);
1758
- const fiber = root == null ? void 0 : root.fiber;
1759
-
1760
- if (fiber) {
1761
- const state = root == null ? void 0 : root.store.getState();
1762
- if (state) state.internal.active = false;
1763
- reconciler.updateContainer(null, fiber, null, () => {
1764
- if (state) {
1765
- setTimeout(() => {
1766
- var _state$gl, _state$gl$renderLists, _state$gl2;
1767
-
1768
- state.events.disconnect == null ? void 0 : state.events.disconnect();
1769
- (_state$gl = state.gl) == null ? void 0 : (_state$gl$renderLists = _state$gl.renderLists) == null ? void 0 : _state$gl$renderLists.dispose == null ? void 0 : _state$gl$renderLists.dispose();
1770
- (_state$gl2 = state.gl) == null ? void 0 : _state$gl2.forceContextLoss == null ? void 0 : _state$gl2.forceContextLoss();
1771
- dispose(state);
1772
- roots.delete(canvas);
1773
- if (callback) callback(canvas);
1774
- }, 500);
1775
- }
1776
- });
1777
- }
1778
- }
1779
-
1780
- function dispose(obj) {
1781
- if (obj.dispose && obj.type !== 'Scene') obj.dispose();
1782
-
1783
- for (const p in obj) {
1784
- var _dispose, _ref;
1785
- (_dispose = (_ref = p).dispose) == null ? void 0 : _dispose.call(_ref);
1786
- delete obj[p];
1787
- }
1788
- }
1789
-
1790
- const act = reconciler.act;
1791
- const hasSymbol = is.fun(Symbol) && Symbol.for;
1792
- const REACT_PORTAL_TYPE = hasSymbol ? Symbol.for('react.portal') : 0xeaca;
1793
-
1794
- function createPortal(children, container, implementation, key = null) {
1795
- return {
1796
- $$typeof: REACT_PORTAL_TYPE,
1797
- key: key == null ? null : '' + key,
1798
- children,
1799
- containerInfo: prepare(container),
1800
- implementation
1801
- };
1802
- }
1803
-
1804
- reconciler.injectIntoDevTools({
1805
- bundleType: process.env.NODE_ENV === 'production' ? 0 : 1,
1806
- rendererPackageName: '@react-three/fiber',
1807
- version: '17.0.2'
1808
- });
1809
-
1810
- export { Canvas, threeTypes as ReactThreeFiber, roots as _roots, act, addAfterEffect, addEffect, addTail, advance, applyProps, context, createPortal, dispose, createPointerEvents as events, extend, invalidate, reconciler, render, unmountComponentAtNode, useFrame, useGraph, useLoader, useStore, useThree };
187
+ export { Canvas, createPointerEvents as events };