@react-three/fiber 9.4.2 → 9.5.0

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.
@@ -1,2569 +0,0 @@
1
- 'use strict';
2
-
3
- var React = require('react');
4
- var constants = require('react-reconciler/constants');
5
- var THREE = require('three');
6
- var traditional = require('zustand/traditional');
7
- var suspendReact = require('suspend-react');
8
- var Reconciler = require('react-reconciler');
9
- var scheduler = require('scheduler');
10
- var jsxRuntime = require('react/jsx-runtime');
11
- var itsFine = require('its-fine');
12
-
13
- function _interopDefault (e) { return e && e.__esModule ? e : { 'default': e }; }
14
-
15
- function _interopNamespace(e) {
16
- if (e && e.__esModule) return e;
17
- var n = Object.create(null);
18
- if (e) {
19
- Object.keys(e).forEach(function (k) {
20
- if (k !== 'default') {
21
- var d = Object.getOwnPropertyDescriptor(e, k);
22
- Object.defineProperty(n, k, d.get ? d : {
23
- enumerable: true,
24
- get: function () { return e[k]; }
25
- });
26
- }
27
- });
28
- }
29
- n["default"] = e;
30
- return Object.freeze(n);
31
- }
32
-
33
- var React__namespace = /*#__PURE__*/_interopNamespace(React);
34
- var THREE__namespace = /*#__PURE__*/_interopNamespace(THREE);
35
- var Reconciler__default = /*#__PURE__*/_interopDefault(Reconciler);
36
-
37
- var threeTypes = /*#__PURE__*/Object.freeze({
38
- __proto__: null
39
- });
40
-
41
- /**
42
- * Returns the instance's initial (outmost) root.
43
- */
44
- function findInitialRoot(instance) {
45
- let root = instance.root;
46
- while (root.getState().previousRoot) root = root.getState().previousRoot;
47
- return root;
48
- }
49
- /**
50
- * Safely flush async effects when testing, simulating a legacy root.
51
- * @deprecated Import from React instead. import { act } from 'react'
52
- */
53
- // Reference with computed key to break Webpack static analysis
54
- // https://github.com/webpack/webpack/issues/14814
55
- const act = React__namespace['act' + ''];
56
- const isOrthographicCamera = def => def && def.isOrthographicCamera;
57
- const isRef = obj => obj && obj.hasOwnProperty('current');
58
- const isColorRepresentation = value => value != null && (typeof value === 'string' || typeof value === 'number' || value.isColor);
59
-
60
- /**
61
- * An SSR-friendly useLayoutEffect.
62
- *
63
- * React currently throws a warning when using useLayoutEffect on the server.
64
- * To get around it, we can conditionally useEffect on the server (no-op) and
65
- * useLayoutEffect elsewhere.
66
- *
67
- * @see https://github.com/facebook/react/issues/14927
68
- */
69
- const useIsomorphicLayoutEffect = /* @__PURE__ */((_window$document, _window$navigator) => typeof window !== 'undefined' && (((_window$document = window.document) == null ? void 0 : _window$document.createElement) || ((_window$navigator = window.navigator) == null ? void 0 : _window$navigator.product) === 'ReactNative'))() ? React__namespace.useLayoutEffect : React__namespace.useEffect;
70
- function useMutableCallback(fn) {
71
- const ref = React__namespace.useRef(fn);
72
- useIsomorphicLayoutEffect(() => void (ref.current = fn), [fn]);
73
- return ref;
74
- }
75
- /**
76
- * Bridges renderer Context and StrictMode from a primary renderer.
77
- */
78
- function useBridge() {
79
- const fiber = itsFine.useFiber();
80
- const ContextBridge = itsFine.useContextBridge();
81
- return React__namespace.useMemo(() => ({
82
- children
83
- }) => {
84
- const strict = !!itsFine.traverseFiber(fiber, true, node => node.type === React__namespace.StrictMode);
85
- const Root = strict ? React__namespace.StrictMode : React__namespace.Fragment;
86
- return /*#__PURE__*/jsxRuntime.jsx(Root, {
87
- children: /*#__PURE__*/jsxRuntime.jsx(ContextBridge, {
88
- children: children
89
- })
90
- });
91
- }, [fiber, ContextBridge]);
92
- }
93
- function Block({
94
- set
95
- }) {
96
- useIsomorphicLayoutEffect(() => {
97
- set(new Promise(() => null));
98
- return () => set(false);
99
- }, [set]);
100
- return null;
101
- }
102
-
103
- // NOTE: static members get down-level transpiled to mutations which break tree-shaking
104
- const ErrorBoundary = /* @__PURE__ */(_ErrorBoundary => (_ErrorBoundary = class ErrorBoundary extends React__namespace.Component {
105
- constructor(...args) {
106
- super(...args);
107
- this.state = {
108
- error: false
109
- };
110
- }
111
- componentDidCatch(err) {
112
- this.props.set(err);
113
- }
114
- render() {
115
- return this.state.error ? null : this.props.children;
116
- }
117
- }, _ErrorBoundary.getDerivedStateFromError = () => ({
118
- error: true
119
- }), _ErrorBoundary))();
120
- function calculateDpr(dpr) {
121
- var _window$devicePixelRa;
122
- // Err on the side of progress by assuming 2x dpr if we can't detect it
123
- // This will happen in workers where window is defined but dpr isn't.
124
- const target = typeof window !== 'undefined' ? (_window$devicePixelRa = window.devicePixelRatio) != null ? _window$devicePixelRa : 2 : 1;
125
- return Array.isArray(dpr) ? Math.min(Math.max(dpr[0], target), dpr[1]) : dpr;
126
- }
127
-
128
- /**
129
- * Returns instance root state
130
- */
131
- function getRootState(obj) {
132
- var _r3f;
133
- return (_r3f = obj.__r3f) == null ? void 0 : _r3f.root.getState();
134
- }
135
- // A collection of compare functions
136
- const is = {
137
- obj: a => a === Object(a) && !is.arr(a) && typeof a !== 'function',
138
- fun: a => typeof a === 'function',
139
- str: a => typeof a === 'string',
140
- num: a => typeof a === 'number',
141
- boo: a => typeof a === 'boolean',
142
- und: a => a === void 0,
143
- nul: a => a === null,
144
- arr: a => Array.isArray(a),
145
- equ(a, b, {
146
- arrays = 'shallow',
147
- objects = 'reference',
148
- strict = true
149
- } = {}) {
150
- // Wrong type or one of the two undefined, doesn't match
151
- if (typeof a !== typeof b || !!a !== !!b) return false;
152
- // Atomic, just compare a against b
153
- if (is.str(a) || is.num(a) || is.boo(a)) return a === b;
154
- const isObj = is.obj(a);
155
- if (isObj && objects === 'reference') return a === b;
156
- const isArr = is.arr(a);
157
- if (isArr && arrays === 'reference') return a === b;
158
- // Array or Object, shallow compare first to see if it's a match
159
- if ((isArr || isObj) && a === b) return true;
160
- // Last resort, go through keys
161
- let i;
162
- // Check if a has all the keys of b
163
- for (i in a) if (!(i in b)) return false;
164
- // Check if values between keys match
165
- if (isObj && arrays === 'shallow' && objects === 'shallow') {
166
- for (i in strict ? b : a) if (!is.equ(a[i], b[i], {
167
- strict,
168
- objects: 'reference'
169
- })) return false;
170
- } else {
171
- for (i in strict ? b : a) if (a[i] !== b[i]) return false;
172
- }
173
- // If i is undefined
174
- if (is.und(i)) {
175
- // If both arrays are empty we consider them equal
176
- if (isArr && a.length === 0 && b.length === 0) return true;
177
- // If both objects are empty we consider them equal
178
- if (isObj && Object.keys(a).length === 0 && Object.keys(b).length === 0) return true;
179
- // Otherwise match them by value
180
- if (a !== b) return false;
181
- }
182
- return true;
183
- }
184
- };
185
-
186
- // Collects nodes and materials from a THREE.Object3D
187
- function buildGraph(object) {
188
- const data = {
189
- nodes: {},
190
- materials: {},
191
- meshes: {}
192
- };
193
- if (object) {
194
- object.traverse(obj => {
195
- if (obj.name) data.nodes[obj.name] = obj;
196
- if (obj.material && !data.materials[obj.material.name]) data.materials[obj.material.name] = obj.material;
197
- if (obj.isMesh && !data.meshes[obj.name]) data.meshes[obj.name] = obj;
198
- });
199
- }
200
- return data;
201
- }
202
- // Disposes an object and all its properties
203
- function dispose(obj) {
204
- if (obj.type !== 'Scene') obj.dispose == null ? void 0 : obj.dispose();
205
- for (const p in obj) {
206
- const prop = obj[p];
207
- if ((prop == null ? void 0 : prop.type) !== 'Scene') prop == null ? void 0 : prop.dispose == null ? void 0 : prop.dispose();
208
- }
209
- }
210
- const REACT_INTERNAL_PROPS = ['children', 'key', 'ref'];
211
-
212
- // Gets only instance props from reconciler fibers
213
- function getInstanceProps(queue) {
214
- const props = {};
215
- for (const key in queue) {
216
- if (!REACT_INTERNAL_PROPS.includes(key)) props[key] = queue[key];
217
- }
218
- return props;
219
- }
220
-
221
- // Each object in the scene carries a small LocalState descriptor
222
- function prepare(target, root, type, props) {
223
- const object = target;
224
-
225
- // Create instance descriptor
226
- let instance = object == null ? void 0 : object.__r3f;
227
- if (!instance) {
228
- instance = {
229
- root,
230
- type,
231
- parent: null,
232
- children: [],
233
- props: getInstanceProps(props),
234
- object,
235
- eventCount: 0,
236
- handlers: {},
237
- isHidden: false
238
- };
239
- if (object) object.__r3f = instance;
240
- }
241
- return instance;
242
- }
243
- function resolve(root, key) {
244
- if (!key.includes('-')) return {
245
- root,
246
- key,
247
- target: root[key]
248
- };
249
-
250
- // First try the entire key as a single property (e.g., 'foo-bar')
251
- if (key in root) {
252
- return {
253
- root,
254
- key,
255
- target: root[key]
256
- };
257
- }
258
-
259
- // Try piercing (e.g., 'material-color' -> material.color)
260
- let target = root;
261
- const parts = key.split('-');
262
- for (const part of parts) {
263
- if (typeof target !== 'object' || target === null) {
264
- if (target !== undefined) {
265
- // Property exists but has unexpected shape
266
- const remaining = parts.slice(parts.indexOf(part)).join('-');
267
- return {
268
- root: target,
269
- key: remaining,
270
- target: undefined
271
- };
272
- }
273
- // Property doesn't exist - fallback to original key
274
- return {
275
- root,
276
- key,
277
- target: undefined
278
- };
279
- }
280
- key = part;
281
- root = target;
282
- target = target[key];
283
- }
284
- return {
285
- root,
286
- key,
287
- target
288
- };
289
- }
290
-
291
- // Checks if a dash-cased string ends with an integer
292
- const INDEX_REGEX = /-\d+$/;
293
- function attach(parent, child) {
294
- if (is.str(child.props.attach)) {
295
- // If attaching into an array (foo-0), create one
296
- if (INDEX_REGEX.test(child.props.attach)) {
297
- const index = child.props.attach.replace(INDEX_REGEX, '');
298
- const {
299
- root,
300
- key
301
- } = resolve(parent.object, index);
302
- if (!Array.isArray(root[key])) root[key] = [];
303
- }
304
- const {
305
- root,
306
- key
307
- } = resolve(parent.object, child.props.attach);
308
- child.previousAttach = root[key];
309
- root[key] = child.object;
310
- } else if (is.fun(child.props.attach)) {
311
- child.previousAttach = child.props.attach(parent.object, child.object);
312
- }
313
- }
314
- function detach(parent, child) {
315
- if (is.str(child.props.attach)) {
316
- const {
317
- root,
318
- key
319
- } = resolve(parent.object, child.props.attach);
320
- const previous = child.previousAttach;
321
- // When the previous value was undefined, it means the value was never set to begin with
322
- if (previous === undefined) delete root[key];
323
- // Otherwise set the previous value
324
- else root[key] = previous;
325
- } else {
326
- child.previousAttach == null ? void 0 : child.previousAttach(parent.object, child.object);
327
- }
328
- delete child.previousAttach;
329
- }
330
- const RESERVED_PROPS = [...REACT_INTERNAL_PROPS,
331
- // Instance props
332
- 'args', 'dispose', 'attach', 'object', 'onUpdate',
333
- // Behavior flags
334
- 'dispose'];
335
- const MEMOIZED_PROTOTYPES = new Map();
336
- function getMemoizedPrototype(root) {
337
- let ctor = MEMOIZED_PROTOTYPES.get(root.constructor);
338
- try {
339
- if (!ctor) {
340
- ctor = new root.constructor();
341
- MEMOIZED_PROTOTYPES.set(root.constructor, ctor);
342
- }
343
- } catch (e) {
344
- // ...
345
- }
346
- return ctor;
347
- }
348
-
349
- // This function prepares a set of changes to be applied to the instance
350
- function diffProps(instance, newProps) {
351
- const changedProps = {};
352
-
353
- // Sort through props
354
- for (const prop in newProps) {
355
- // Skip reserved keys
356
- if (RESERVED_PROPS.includes(prop)) continue;
357
- // Skip if props match
358
- if (is.equ(newProps[prop], instance.props[prop])) continue;
359
-
360
- // Props changed, add them
361
- changedProps[prop] = newProps[prop];
362
-
363
- // Reset pierced props
364
- for (const other in newProps) {
365
- if (other.startsWith(`${prop}-`)) changedProps[other] = newProps[other];
366
- }
367
- }
368
-
369
- // Reset removed props for HMR
370
- for (const prop in instance.props) {
371
- if (RESERVED_PROPS.includes(prop) || newProps.hasOwnProperty(prop)) continue;
372
- const {
373
- root,
374
- key
375
- } = resolve(instance.object, prop);
376
-
377
- // https://github.com/mrdoob/three.js/issues/21209
378
- // HMR/fast-refresh relies on the ability to cancel out props, but threejs
379
- // has no means to do this. Hence we curate a small collection of value-classes
380
- // with their respective constructor/set arguments
381
- // For removed props, try to set default values, if possible
382
- if (root.constructor && root.constructor.length === 0) {
383
- // create a blank slate of the instance and copy the particular parameter.
384
- const ctor = getMemoizedPrototype(root);
385
- if (!is.und(ctor)) changedProps[key] = ctor[key];
386
- } else {
387
- // instance does not have constructor, just set it to 0
388
- changedProps[key] = 0;
389
- }
390
- }
391
- return changedProps;
392
- }
393
-
394
- // https://github.com/mrdoob/three.js/pull/27042
395
- // https://github.com/mrdoob/three.js/pull/22748
396
- const colorMaps = ['map', 'emissiveMap', 'sheenColorMap', 'specularColorMap', 'envMap'];
397
- const EVENT_REGEX = /^on(Pointer|Click|DoubleClick|ContextMenu|Wheel)/;
398
- // This function applies a set of changes to the instance
399
- function applyProps(object, props) {
400
- var _instance$object;
401
- const instance = object.__r3f;
402
- const rootState = instance && findInitialRoot(instance).getState();
403
- const prevHandlers = instance == null ? void 0 : instance.eventCount;
404
- for (const prop in props) {
405
- let value = props[prop];
406
-
407
- // Don't mutate reserved keys
408
- if (RESERVED_PROPS.includes(prop)) continue;
409
-
410
- // Deal with pointer events, including removing them if undefined
411
- if (instance && EVENT_REGEX.test(prop)) {
412
- if (typeof value === 'function') instance.handlers[prop] = value;else delete instance.handlers[prop];
413
- instance.eventCount = Object.keys(instance.handlers).length;
414
- continue;
415
- }
416
-
417
- // Ignore setting undefined props
418
- // https://github.com/pmndrs/react-three-fiber/issues/274
419
- if (value === undefined) continue;
420
- let {
421
- root,
422
- key,
423
- target
424
- } = resolve(object, prop);
425
-
426
- // Throw an error if we attempted to set a pierced prop to a non-object
427
- if (target === undefined && (typeof root !== 'object' || root === null)) {
428
- throw Error(`R3F: Cannot set "${prop}". Ensure it is an object before setting "${key}".`);
429
- }
430
-
431
- // Layers must be written to the mask property
432
- if (target instanceof THREE__namespace.Layers && value instanceof THREE__namespace.Layers) {
433
- target.mask = value.mask;
434
- }
435
- // Set colors if valid color representation for automatic conversion (copy)
436
- else if (target instanceof THREE__namespace.Color && isColorRepresentation(value)) {
437
- target.set(value);
438
- }
439
- // Copy if properties match signatures and implement math interface (likely read-only)
440
- else if (target !== null && typeof target === 'object' && typeof target.set === 'function' && typeof target.copy === 'function' && value != null && value.constructor && target.constructor === value.constructor) {
441
- target.copy(value);
442
- }
443
- // Set array types
444
- else if (target !== null && typeof target === 'object' && typeof target.set === 'function' && Array.isArray(value)) {
445
- if (typeof target.fromArray === 'function') target.fromArray(value);else target.set(...value);
446
- }
447
- // Set literal types
448
- else if (target !== null && typeof target === 'object' && typeof target.set === 'function' && typeof value === 'number') {
449
- // Allow setting array scalars
450
- if (typeof target.setScalar === 'function') target.setScalar(value);
451
- // Otherwise just set single value
452
- else target.set(value);
453
- }
454
- // Else, just overwrite the value
455
- else {
456
- var _root$key;
457
- root[key] = value;
458
-
459
- // Auto-convert sRGB texture parameters for built-in materials
460
- // https://github.com/pmndrs/react-three-fiber/issues/344
461
- // https://github.com/mrdoob/three.js/pull/25857
462
- if (rootState && !rootState.linear && colorMaps.includes(key) && (_root$key = root[key]) != null && _root$key.isTexture &&
463
- // sRGB textures must be RGBA8 since r137 https://github.com/mrdoob/three.js/pull/23129
464
- root[key].format === THREE__namespace.RGBAFormat && root[key].type === THREE__namespace.UnsignedByteType) {
465
- // NOTE: this cannot be set from the renderer (e.g. sRGB source textures rendered to P3)
466
- root[key].colorSpace = THREE__namespace.SRGBColorSpace;
467
- }
468
- }
469
- }
470
-
471
- // Register event handlers
472
- if (instance != null && instance.parent && rootState != null && rootState.internal && (_instance$object = instance.object) != null && _instance$object.isObject3D && prevHandlers !== instance.eventCount) {
473
- const object = instance.object;
474
- // Pre-emptively remove the instance from the interaction manager
475
- const index = rootState.internal.interaction.indexOf(object);
476
- if (index > -1) rootState.internal.interaction.splice(index, 1);
477
- // Add the instance to the interaction manager only when it has handlers
478
- if (instance.eventCount && object.raycast !== null) {
479
- rootState.internal.interaction.push(object);
480
- }
481
- }
482
-
483
- // Auto-attach geometries and materials
484
- if (instance && instance.props.attach === undefined) {
485
- if (instance.object.isBufferGeometry) instance.props.attach = 'geometry';else if (instance.object.isMaterial) instance.props.attach = 'material';
486
- }
487
-
488
- // Instance was updated, request a frame
489
- if (instance) invalidateInstance(instance);
490
- return object;
491
- }
492
- function invalidateInstance(instance) {
493
- var _instance$root;
494
- if (!instance.parent) return;
495
- instance.props.onUpdate == null ? void 0 : instance.props.onUpdate(instance.object);
496
- const state = (_instance$root = instance.root) == null ? void 0 : _instance$root.getState == null ? void 0 : _instance$root.getState();
497
- if (state && state.internal.frames === 0) state.invalidate();
498
- }
499
- function updateCamera(camera, size) {
500
- // Do not mess with the camera if it belongs to the user
501
- // https://github.com/pmndrs/react-three-fiber/issues/92
502
- if (camera.manual) return;
503
- if (isOrthographicCamera(camera)) {
504
- camera.left = size.width / -2;
505
- camera.right = size.width / 2;
506
- camera.top = size.height / 2;
507
- camera.bottom = size.height / -2;
508
- } else {
509
- camera.aspect = size.width / size.height;
510
- }
511
- camera.updateProjectionMatrix();
512
- }
513
- const isObject3D = object => object == null ? void 0 : object.isObject3D;
514
-
515
- function makeId(event) {
516
- return (event.eventObject || event.object).uuid + '/' + event.index + event.instanceId;
517
- }
518
-
519
- /**
520
- * Release pointer captures.
521
- * This is called by releasePointerCapture in the API, and when an object is removed.
522
- */
523
- function releaseInternalPointerCapture(capturedMap, obj, captures, pointerId) {
524
- const captureData = captures.get(obj);
525
- if (captureData) {
526
- captures.delete(obj);
527
- // If this was the last capturing object for this pointer
528
- if (captures.size === 0) {
529
- capturedMap.delete(pointerId);
530
- captureData.target.releasePointerCapture(pointerId);
531
- }
532
- }
533
- }
534
- function removeInteractivity(store, object) {
535
- const {
536
- internal
537
- } = store.getState();
538
- // Removes every trace of an object from the data store
539
- internal.interaction = internal.interaction.filter(o => o !== object);
540
- internal.initialHits = internal.initialHits.filter(o => o !== object);
541
- internal.hovered.forEach((value, key) => {
542
- if (value.eventObject === object || value.object === object) {
543
- // Clear out intersects, they are outdated by now
544
- internal.hovered.delete(key);
545
- }
546
- });
547
- internal.capturedMap.forEach((captures, pointerId) => {
548
- releaseInternalPointerCapture(internal.capturedMap, object, captures, pointerId);
549
- });
550
- }
551
- function createEvents(store) {
552
- /** Calculates delta */
553
- function calculateDistance(event) {
554
- const {
555
- internal
556
- } = store.getState();
557
- const dx = event.offsetX - internal.initialClick[0];
558
- const dy = event.offsetY - internal.initialClick[1];
559
- return Math.round(Math.sqrt(dx * dx + dy * dy));
560
- }
561
-
562
- /** Returns true if an instance has a valid pointer-event registered, this excludes scroll, clicks etc */
563
- function filterPointerEvents(objects) {
564
- return objects.filter(obj => ['Move', 'Over', 'Enter', 'Out', 'Leave'].some(name => {
565
- var _r3f;
566
- return (_r3f = obj.__r3f) == null ? void 0 : _r3f.handlers['onPointer' + name];
567
- }));
568
- }
569
- function intersect(event, filter) {
570
- const state = store.getState();
571
- const duplicates = new Set();
572
- const intersections = [];
573
- // Allow callers to eliminate event objects
574
- const eventsObjects = filter ? filter(state.internal.interaction) : state.internal.interaction;
575
- // Reset all raycaster cameras to undefined
576
- for (let i = 0; i < eventsObjects.length; i++) {
577
- const state = getRootState(eventsObjects[i]);
578
- if (state) {
579
- state.raycaster.camera = undefined;
580
- }
581
- }
582
- if (!state.previousRoot) {
583
- // Make sure root-level pointer and ray are set up
584
- state.events.compute == null ? void 0 : state.events.compute(event, state);
585
- }
586
- function handleRaycast(obj) {
587
- const state = getRootState(obj);
588
- // Skip event handling when noEvents is set, or when the raycasters camera is null
589
- if (!state || !state.events.enabled || state.raycaster.camera === null) return [];
590
-
591
- // When the camera is undefined we have to call the event layers update function
592
- if (state.raycaster.camera === undefined) {
593
- var _state$previousRoot;
594
- state.events.compute == null ? void 0 : state.events.compute(event, state, (_state$previousRoot = state.previousRoot) == null ? void 0 : _state$previousRoot.getState());
595
- // If the camera is still undefined we have to skip this layer entirely
596
- if (state.raycaster.camera === undefined) state.raycaster.camera = null;
597
- }
598
-
599
- // Intersect object by object
600
- return state.raycaster.camera ? state.raycaster.intersectObject(obj, true) : [];
601
- }
602
-
603
- // Collect events
604
- let hits = eventsObjects
605
- // Intersect objects
606
- .flatMap(handleRaycast)
607
- // Sort by event priority and distance
608
- .sort((a, b) => {
609
- const aState = getRootState(a.object);
610
- const bState = getRootState(b.object);
611
- if (!aState || !bState) return a.distance - b.distance;
612
- return bState.events.priority - aState.events.priority || a.distance - b.distance;
613
- })
614
- // Filter out duplicates
615
- .filter(item => {
616
- const id = makeId(item);
617
- if (duplicates.has(id)) return false;
618
- duplicates.add(id);
619
- return true;
620
- });
621
-
622
- // https://github.com/mrdoob/three.js/issues/16031
623
- // Allow custom userland intersect sort order, this likely only makes sense on the root filter
624
- if (state.events.filter) hits = state.events.filter(hits, state);
625
-
626
- // Bubble up the events, find the event source (eventObject)
627
- for (const hit of hits) {
628
- let eventObject = hit.object;
629
- // Bubble event up
630
- while (eventObject) {
631
- var _r3f2;
632
- if ((_r3f2 = eventObject.__r3f) != null && _r3f2.eventCount) intersections.push({
633
- ...hit,
634
- eventObject
635
- });
636
- eventObject = eventObject.parent;
637
- }
638
- }
639
-
640
- // If the interaction is captured, make all capturing targets part of the intersect.
641
- if ('pointerId' in event && state.internal.capturedMap.has(event.pointerId)) {
642
- for (let captureData of state.internal.capturedMap.get(event.pointerId).values()) {
643
- if (!duplicates.has(makeId(captureData.intersection))) intersections.push(captureData.intersection);
644
- }
645
- }
646
- return intersections;
647
- }
648
-
649
- /** Handles intersections by forwarding them to handlers */
650
- function handleIntersects(intersections, event, delta, callback) {
651
- // If anything has been found, forward it to the event listeners
652
- if (intersections.length) {
653
- const localState = {
654
- stopped: false
655
- };
656
- for (const hit of intersections) {
657
- let state = getRootState(hit.object);
658
-
659
- // If the object is not managed by R3F, it might be parented to an element which is.
660
- // Traverse upwards until we find a managed parent and use its state instead.
661
- if (!state) {
662
- hit.object.traverseAncestors(obj => {
663
- const parentState = getRootState(obj);
664
- if (parentState) {
665
- state = parentState;
666
- return false;
667
- }
668
- });
669
- }
670
- if (state) {
671
- const {
672
- raycaster,
673
- pointer,
674
- camera,
675
- internal
676
- } = state;
677
- const unprojectedPoint = new THREE__namespace.Vector3(pointer.x, pointer.y, 0).unproject(camera);
678
- const hasPointerCapture = id => {
679
- var _internal$capturedMap, _internal$capturedMap2;
680
- return (_internal$capturedMap = (_internal$capturedMap2 = internal.capturedMap.get(id)) == null ? void 0 : _internal$capturedMap2.has(hit.eventObject)) != null ? _internal$capturedMap : false;
681
- };
682
- const setPointerCapture = id => {
683
- const captureData = {
684
- intersection: hit,
685
- target: event.target
686
- };
687
- if (internal.capturedMap.has(id)) {
688
- // if the pointerId was previously captured, we add the hit to the
689
- // event capturedMap.
690
- internal.capturedMap.get(id).set(hit.eventObject, captureData);
691
- } else {
692
- // if the pointerId was not previously captured, we create a map
693
- // containing the hitObject, and the hit. hitObject is used for
694
- // faster access.
695
- internal.capturedMap.set(id, new Map([[hit.eventObject, captureData]]));
696
- }
697
- event.target.setPointerCapture(id);
698
- };
699
- const releasePointerCapture = id => {
700
- const captures = internal.capturedMap.get(id);
701
- if (captures) {
702
- releaseInternalPointerCapture(internal.capturedMap, hit.eventObject, captures, id);
703
- }
704
- };
705
-
706
- // Add native event props
707
- let extractEventProps = {};
708
- // This iterates over the event's properties including the inherited ones. Native PointerEvents have most of their props as getters which are inherited, but polyfilled PointerEvents have them all as their own properties (i.e. not inherited). We can't use Object.keys() or Object.entries() as they only return "own" properties; nor Object.getPrototypeOf(event) as that *doesn't* return "own" properties, only inherited ones.
709
- for (let prop in event) {
710
- let property = event[prop];
711
- // Only copy over atomics, leave functions alone as these should be
712
- // called as event.nativeEvent.fn()
713
- if (typeof property !== 'function') extractEventProps[prop] = property;
714
- }
715
- let raycastEvent = {
716
- ...hit,
717
- ...extractEventProps,
718
- pointer,
719
- intersections,
720
- stopped: localState.stopped,
721
- delta,
722
- unprojectedPoint,
723
- ray: raycaster.ray,
724
- camera: camera,
725
- // Hijack stopPropagation, which just sets a flag
726
- stopPropagation() {
727
- // https://github.com/pmndrs/react-three-fiber/issues/596
728
- // Events are not allowed to stop propagation if the pointer has been captured
729
- const capturesForPointer = 'pointerId' in event && internal.capturedMap.get(event.pointerId);
730
-
731
- // We only authorize stopPropagation...
732
- if (
733
- // ...if this pointer hasn't been captured
734
- !capturesForPointer ||
735
- // ... or if the hit object is capturing the pointer
736
- capturesForPointer.has(hit.eventObject)) {
737
- raycastEvent.stopped = localState.stopped = true;
738
- // Propagation is stopped, remove all other hover records
739
- // An event handler is only allowed to flush other handlers if it is hovered itself
740
- if (internal.hovered.size && Array.from(internal.hovered.values()).find(i => i.eventObject === hit.eventObject)) {
741
- // Objects cannot flush out higher up objects that have already caught the event
742
- const higher = intersections.slice(0, intersections.indexOf(hit));
743
- cancelPointer([...higher, hit]);
744
- }
745
- }
746
- },
747
- // there should be a distinction between target and currentTarget
748
- target: {
749
- hasPointerCapture,
750
- setPointerCapture,
751
- releasePointerCapture
752
- },
753
- currentTarget: {
754
- hasPointerCapture,
755
- setPointerCapture,
756
- releasePointerCapture
757
- },
758
- nativeEvent: event
759
- };
760
-
761
- // Call subscribers
762
- callback(raycastEvent);
763
- // Event bubbling may be interrupted by stopPropagation
764
- if (localState.stopped === true) break;
765
- }
766
- }
767
- }
768
- return intersections;
769
- }
770
- function cancelPointer(intersections) {
771
- const {
772
- internal
773
- } = store.getState();
774
- for (const hoveredObj of internal.hovered.values()) {
775
- // When no objects were hit or the the hovered object wasn't found underneath the cursor
776
- // we call onPointerOut and delete the object from the hovered-elements map
777
- if (!intersections.length || !intersections.find(hit => hit.object === hoveredObj.object && hit.index === hoveredObj.index && hit.instanceId === hoveredObj.instanceId)) {
778
- const eventObject = hoveredObj.eventObject;
779
- const instance = eventObject.__r3f;
780
- internal.hovered.delete(makeId(hoveredObj));
781
- if (instance != null && instance.eventCount) {
782
- const handlers = instance.handlers;
783
- // Clear out intersects, they are outdated by now
784
- const data = {
785
- ...hoveredObj,
786
- intersections
787
- };
788
- handlers.onPointerOut == null ? void 0 : handlers.onPointerOut(data);
789
- handlers.onPointerLeave == null ? void 0 : handlers.onPointerLeave(data);
790
- }
791
- }
792
- }
793
- }
794
- function pointerMissed(event, objects) {
795
- for (let i = 0; i < objects.length; i++) {
796
- const instance = objects[i].__r3f;
797
- instance == null ? void 0 : instance.handlers.onPointerMissed == null ? void 0 : instance.handlers.onPointerMissed(event);
798
- }
799
- }
800
- function handlePointer(name) {
801
- // Deal with cancelation
802
- switch (name) {
803
- case 'onPointerLeave':
804
- case 'onPointerCancel':
805
- return () => cancelPointer([]);
806
- case 'onLostPointerCapture':
807
- return event => {
808
- const {
809
- internal
810
- } = store.getState();
811
- if ('pointerId' in event && internal.capturedMap.has(event.pointerId)) {
812
- // If the object event interface had onLostPointerCapture, we'd call it here on every
813
- // object that's getting removed. We call it on the next frame because onLostPointerCapture
814
- // fires before onPointerUp. Otherwise pointerUp would never be called if the event didn't
815
- // happen in the object it originated from, leaving components in a in-between state.
816
- requestAnimationFrame(() => {
817
- // Only release if pointer-up didn't do it already
818
- if (internal.capturedMap.has(event.pointerId)) {
819
- internal.capturedMap.delete(event.pointerId);
820
- cancelPointer([]);
821
- }
822
- });
823
- }
824
- };
825
- }
826
-
827
- // Any other pointer goes here ...
828
- return function handleEvent(event) {
829
- const {
830
- onPointerMissed,
831
- internal
832
- } = store.getState();
833
-
834
- // prepareRay(event)
835
- internal.lastEvent.current = event;
836
-
837
- // Get fresh intersects
838
- const isPointerMove = name === 'onPointerMove';
839
- const isClickEvent = name === 'onClick' || name === 'onContextMenu' || name === 'onDoubleClick';
840
- const filter = isPointerMove ? filterPointerEvents : undefined;
841
- const hits = intersect(event, filter);
842
- const delta = isClickEvent ? calculateDistance(event) : 0;
843
-
844
- // Save initial coordinates on pointer-down
845
- if (name === 'onPointerDown') {
846
- internal.initialClick = [event.offsetX, event.offsetY];
847
- internal.initialHits = hits.map(hit => hit.eventObject);
848
- }
849
-
850
- // If a click yields no results, pass it back to the user as a miss
851
- // Missed events have to come first in order to establish user-land side-effect clean up
852
- if (isClickEvent && !hits.length) {
853
- if (delta <= 2) {
854
- pointerMissed(event, internal.interaction);
855
- if (onPointerMissed) onPointerMissed(event);
856
- }
857
- }
858
- // Take care of unhover
859
- if (isPointerMove) cancelPointer(hits);
860
- function onIntersect(data) {
861
- const eventObject = data.eventObject;
862
- const instance = eventObject.__r3f;
863
-
864
- // Check presence of handlers
865
- if (!(instance != null && instance.eventCount)) return;
866
- const handlers = instance.handlers;
867
-
868
- /*
869
- MAYBE TODO, DELETE IF NOT:
870
- Check if the object is captured, captured events should not have intersects running in parallel
871
- But wouldn't it be better to just replace capturedMap with a single entry?
872
- Also, are we OK with straight up making picking up multiple objects impossible?
873
-
874
- const pointerId = (data as ThreeEvent<PointerEvent>).pointerId
875
- if (pointerId !== undefined) {
876
- const capturedMeshSet = internal.capturedMap.get(pointerId)
877
- if (capturedMeshSet) {
878
- const captured = capturedMeshSet.get(eventObject)
879
- if (captured && captured.localState.stopped) return
880
- }
881
- }*/
882
-
883
- if (isPointerMove) {
884
- // Move event ...
885
- if (handlers.onPointerOver || handlers.onPointerEnter || handlers.onPointerOut || handlers.onPointerLeave) {
886
- // When enter or out is present take care of hover-state
887
- const id = makeId(data);
888
- const hoveredItem = internal.hovered.get(id);
889
- if (!hoveredItem) {
890
- // If the object wasn't previously hovered, book it and call its handler
891
- internal.hovered.set(id, data);
892
- handlers.onPointerOver == null ? void 0 : handlers.onPointerOver(data);
893
- handlers.onPointerEnter == null ? void 0 : handlers.onPointerEnter(data);
894
- } else if (hoveredItem.stopped) {
895
- // If the object was previously hovered and stopped, we shouldn't allow other items to proceed
896
- data.stopPropagation();
897
- }
898
- }
899
- // Call mouse move
900
- handlers.onPointerMove == null ? void 0 : handlers.onPointerMove(data);
901
- } else {
902
- // All other events ...
903
- const handler = handlers[name];
904
- if (handler) {
905
- // Forward all events back to their respective handlers with the exception of click events,
906
- // which must use the initial target
907
- if (!isClickEvent || internal.initialHits.includes(eventObject)) {
908
- // Missed events have to come first
909
- pointerMissed(event, internal.interaction.filter(object => !internal.initialHits.includes(object)));
910
- // Now call the handler
911
- handler(data);
912
- }
913
- } else {
914
- // Trigger onPointerMissed on all elements that have pointer over/out handlers, but not click and weren't hit
915
- if (isClickEvent && internal.initialHits.includes(eventObject)) {
916
- pointerMissed(event, internal.interaction.filter(object => !internal.initialHits.includes(object)));
917
- }
918
- }
919
- }
920
- }
921
- handleIntersects(hits, event, delta, onIntersect);
922
- };
923
- }
924
- return {
925
- handlePointer
926
- };
927
- }
928
-
929
- const isRenderer = def => !!(def != null && def.render);
930
- const context = /* @__PURE__ */React__namespace.createContext(null);
931
- const createStore = (invalidate, advance) => {
932
- const rootStore = traditional.createWithEqualityFn((set, get) => {
933
- const position = new THREE__namespace.Vector3();
934
- const defaultTarget = new THREE__namespace.Vector3();
935
- const tempTarget = new THREE__namespace.Vector3();
936
- function getCurrentViewport(camera = get().camera, target = defaultTarget, size = get().size) {
937
- const {
938
- width,
939
- height,
940
- top,
941
- left
942
- } = size;
943
- const aspect = width / height;
944
- if (target.isVector3) tempTarget.copy(target);else tempTarget.set(...target);
945
- const distance = camera.getWorldPosition(position).distanceTo(tempTarget);
946
- if (isOrthographicCamera(camera)) {
947
- return {
948
- width: width / camera.zoom,
949
- height: height / camera.zoom,
950
- top,
951
- left,
952
- factor: 1,
953
- distance,
954
- aspect
955
- };
956
- } else {
957
- const fov = camera.fov * Math.PI / 180; // convert vertical fov to radians
958
- const h = 2 * Math.tan(fov / 2) * distance; // visible height
959
- const w = h * (width / height);
960
- return {
961
- width: w,
962
- height: h,
963
- top,
964
- left,
965
- factor: width / w,
966
- distance,
967
- aspect
968
- };
969
- }
970
- }
971
- let performanceTimeout = undefined;
972
- const setPerformanceCurrent = current => set(state => ({
973
- performance: {
974
- ...state.performance,
975
- current
976
- }
977
- }));
978
- const pointer = new THREE__namespace.Vector2();
979
- const rootState = {
980
- set,
981
- get,
982
- // Mock objects that have to be configured
983
- gl: null,
984
- camera: null,
985
- raycaster: null,
986
- events: {
987
- priority: 1,
988
- enabled: true,
989
- connected: false
990
- },
991
- scene: null,
992
- xr: null,
993
- invalidate: (frames = 1) => invalidate(get(), frames),
994
- advance: (timestamp, runGlobalEffects) => advance(timestamp, runGlobalEffects, get()),
995
- legacy: false,
996
- linear: false,
997
- flat: false,
998
- controls: null,
999
- clock: new THREE__namespace.Clock(),
1000
- pointer,
1001
- mouse: pointer,
1002
- frameloop: 'always',
1003
- onPointerMissed: undefined,
1004
- performance: {
1005
- current: 1,
1006
- min: 0.5,
1007
- max: 1,
1008
- debounce: 200,
1009
- regress: () => {
1010
- const state = get();
1011
- // Clear timeout
1012
- if (performanceTimeout) clearTimeout(performanceTimeout);
1013
- // Set lower bound performance
1014
- if (state.performance.current !== state.performance.min) setPerformanceCurrent(state.performance.min);
1015
- // Go back to upper bound performance after a while unless something regresses meanwhile
1016
- performanceTimeout = setTimeout(() => setPerformanceCurrent(get().performance.max), state.performance.debounce);
1017
- }
1018
- },
1019
- size: {
1020
- width: 0,
1021
- height: 0,
1022
- top: 0,
1023
- left: 0
1024
- },
1025
- viewport: {
1026
- initialDpr: 0,
1027
- dpr: 0,
1028
- width: 0,
1029
- height: 0,
1030
- top: 0,
1031
- left: 0,
1032
- aspect: 0,
1033
- distance: 0,
1034
- factor: 0,
1035
- getCurrentViewport
1036
- },
1037
- setEvents: events => set(state => ({
1038
- ...state,
1039
- events: {
1040
- ...state.events,
1041
- ...events
1042
- }
1043
- })),
1044
- setSize: (width, height, top = 0, left = 0) => {
1045
- const camera = get().camera;
1046
- const size = {
1047
- width,
1048
- height,
1049
- top,
1050
- left
1051
- };
1052
- set(state => ({
1053
- size,
1054
- viewport: {
1055
- ...state.viewport,
1056
- ...getCurrentViewport(camera, defaultTarget, size)
1057
- }
1058
- }));
1059
- },
1060
- setDpr: dpr => set(state => {
1061
- const resolved = calculateDpr(dpr);
1062
- return {
1063
- viewport: {
1064
- ...state.viewport,
1065
- dpr: resolved,
1066
- initialDpr: state.viewport.initialDpr || resolved
1067
- }
1068
- };
1069
- }),
1070
- setFrameloop: (frameloop = 'always') => {
1071
- const clock = get().clock;
1072
-
1073
- // if frameloop === "never" clock.elapsedTime is updated using advance(timestamp)
1074
- clock.stop();
1075
- clock.elapsedTime = 0;
1076
- if (frameloop !== 'never') {
1077
- clock.start();
1078
- clock.elapsedTime = 0;
1079
- }
1080
- set(() => ({
1081
- frameloop
1082
- }));
1083
- },
1084
- previousRoot: undefined,
1085
- internal: {
1086
- // Events
1087
- interaction: [],
1088
- hovered: new Map(),
1089
- subscribers: [],
1090
- initialClick: [0, 0],
1091
- initialHits: [],
1092
- capturedMap: new Map(),
1093
- lastEvent: /*#__PURE__*/React__namespace.createRef(),
1094
- // Updates
1095
- active: false,
1096
- frames: 0,
1097
- priority: 0,
1098
- subscribe: (ref, priority, store) => {
1099
- const internal = get().internal;
1100
- // If this subscription was given a priority, it takes rendering into its own hands
1101
- // For that reason we switch off automatic rendering and increase the manual flag
1102
- // As long as this flag is positive there can be no internal rendering at all
1103
- // because there could be multiple render subscriptions
1104
- internal.priority = internal.priority + (priority > 0 ? 1 : 0);
1105
- internal.subscribers.push({
1106
- ref,
1107
- priority,
1108
- store
1109
- });
1110
- // Register subscriber and sort layers from lowest to highest, meaning,
1111
- // highest priority renders last (on top of the other frames)
1112
- internal.subscribers = internal.subscribers.sort((a, b) => a.priority - b.priority);
1113
- return () => {
1114
- const internal = get().internal;
1115
- if (internal != null && internal.subscribers) {
1116
- // Decrease manual flag if this subscription had a priority
1117
- internal.priority = internal.priority - (priority > 0 ? 1 : 0);
1118
- // Remove subscriber from list
1119
- internal.subscribers = internal.subscribers.filter(s => s.ref !== ref);
1120
- }
1121
- };
1122
- }
1123
- }
1124
- };
1125
- return rootState;
1126
- });
1127
- const state = rootStore.getState();
1128
- let oldSize = state.size;
1129
- let oldDpr = state.viewport.dpr;
1130
- let oldCamera = state.camera;
1131
- rootStore.subscribe(() => {
1132
- const {
1133
- camera,
1134
- size,
1135
- viewport,
1136
- gl,
1137
- set
1138
- } = rootStore.getState();
1139
-
1140
- // Resize camera and renderer on changes to size and pixelratio
1141
- if (size.width !== oldSize.width || size.height !== oldSize.height || viewport.dpr !== oldDpr) {
1142
- oldSize = size;
1143
- oldDpr = viewport.dpr;
1144
- // Update camera & renderer
1145
- updateCamera(camera, size);
1146
- if (viewport.dpr > 0) gl.setPixelRatio(viewport.dpr);
1147
- const updateStyle = typeof HTMLCanvasElement !== 'undefined' && gl.domElement instanceof HTMLCanvasElement;
1148
- gl.setSize(size.width, size.height, updateStyle);
1149
- }
1150
-
1151
- // Update viewport once the camera changes
1152
- if (camera !== oldCamera) {
1153
- oldCamera = camera;
1154
- // Update viewport
1155
- set(state => ({
1156
- viewport: {
1157
- ...state.viewport,
1158
- ...state.viewport.getCurrentViewport(camera)
1159
- }
1160
- }));
1161
- }
1162
- });
1163
-
1164
- // Invalidate on any change
1165
- rootStore.subscribe(state => invalidate(state));
1166
-
1167
- // Return root state
1168
- return rootStore;
1169
- };
1170
-
1171
- /**
1172
- * Exposes an object's {@link Instance}.
1173
- * @see https://docs.pmnd.rs/react-three-fiber/api/additional-exports#useInstanceHandle
1174
- *
1175
- * **Note**: this is an escape hatch to react-internal fields. Expect this to change significantly between versions.
1176
- */
1177
- function useInstanceHandle(ref) {
1178
- const instance = React__namespace.useRef(null);
1179
- React__namespace.useImperativeHandle(instance, () => ref.current.__r3f, [ref]);
1180
- return instance;
1181
- }
1182
-
1183
- /**
1184
- * Returns the R3F Canvas' Zustand store. Useful for [transient updates](https://github.com/pmndrs/zustand#transient-updates-for-often-occurring-state-changes).
1185
- * @see https://docs.pmnd.rs/react-three-fiber/api/hooks#usestore
1186
- */
1187
- function useStore() {
1188
- const store = React__namespace.useContext(context);
1189
- if (!store) throw new Error('R3F: Hooks can only be used within the Canvas component!');
1190
- return store;
1191
- }
1192
-
1193
- /**
1194
- * Accesses R3F's internal state, containing renderer, canvas, scene, etc.
1195
- * @see https://docs.pmnd.rs/react-three-fiber/api/hooks#usethree
1196
- */
1197
- function useThree(selector = state => state, equalityFn) {
1198
- return useStore()(selector, equalityFn);
1199
- }
1200
-
1201
- /**
1202
- * Executes a callback before render in a shared frame loop.
1203
- * Can order effects with render priority or manually render with a positive priority.
1204
- * @see https://docs.pmnd.rs/react-three-fiber/api/hooks#useframe
1205
- */
1206
- function useFrame(callback, renderPriority = 0) {
1207
- const store = useStore();
1208
- const subscribe = store.getState().internal.subscribe;
1209
- // Memoize ref
1210
- const ref = useMutableCallback(callback);
1211
- // Subscribe on mount, unsubscribe on unmount
1212
- useIsomorphicLayoutEffect(() => subscribe(ref, renderPriority, store), [renderPriority, subscribe, store]);
1213
- return null;
1214
- }
1215
-
1216
- /**
1217
- * Returns a node graph of an object with named nodes & materials.
1218
- * @see https://docs.pmnd.rs/react-three-fiber/api/hooks#usegraph
1219
- */
1220
- function useGraph(object) {
1221
- return React__namespace.useMemo(() => buildGraph(object), [object]);
1222
- }
1223
- const memoizedLoaders = new WeakMap();
1224
- const isConstructor$1 = value => {
1225
- var _value$prototype;
1226
- return typeof value === 'function' && (value == null ? void 0 : (_value$prototype = value.prototype) == null ? void 0 : _value$prototype.constructor) === value;
1227
- };
1228
- function loadingFn(extensions, onProgress) {
1229
- return function (Proto, ...input) {
1230
- let loader;
1231
-
1232
- // Construct and cache loader if constructor was passed
1233
- if (isConstructor$1(Proto)) {
1234
- loader = memoizedLoaders.get(Proto);
1235
- if (!loader) {
1236
- loader = new Proto();
1237
- memoizedLoaders.set(Proto, loader);
1238
- }
1239
- } else {
1240
- loader = Proto;
1241
- }
1242
-
1243
- // Apply loader extensions
1244
- if (extensions) extensions(loader);
1245
-
1246
- // Go through the urls and load them
1247
- return Promise.all(input.map(input => new Promise((res, reject) => loader.load(input, data => {
1248
- if (isObject3D(data == null ? void 0 : data.scene)) Object.assign(data, buildGraph(data.scene));
1249
- res(data);
1250
- }, onProgress, error => reject(new Error(`Could not load ${input}: ${error == null ? void 0 : error.message}`))))));
1251
- };
1252
- }
1253
-
1254
- /**
1255
- * Synchronously loads and caches assets with a three loader.
1256
- *
1257
- * Note: this hook's caller must be wrapped with `React.Suspense`
1258
- * @see https://docs.pmnd.rs/react-three-fiber/api/hooks#useloader
1259
- */
1260
- function useLoader(loader, input, extensions, onProgress) {
1261
- // Use suspense to load async assets
1262
- const keys = Array.isArray(input) ? input : [input];
1263
- const results = suspendReact.suspend(loadingFn(extensions, onProgress), [loader, ...keys], {
1264
- equal: is.equ
1265
- });
1266
- // Return the object(s)
1267
- return Array.isArray(input) ? results : results[0];
1268
- }
1269
-
1270
- /**
1271
- * Preloads an asset into cache as a side-effect.
1272
- */
1273
- useLoader.preload = function (loader, input, extensions) {
1274
- const keys = Array.isArray(input) ? input : [input];
1275
- return suspendReact.preload(loadingFn(extensions), [loader, ...keys]);
1276
- };
1277
-
1278
- /**
1279
- * Removes a loaded asset from cache.
1280
- */
1281
- useLoader.clear = function (loader, input) {
1282
- const keys = Array.isArray(input) ? input : [input];
1283
- return suspendReact.clear([loader, ...keys]);
1284
- };
1285
-
1286
- var packageData = {
1287
- name: "@react-three/fiber",
1288
- version: "9.4.2",
1289
- description: "A React renderer for Threejs",
1290
- keywords: [
1291
- "react",
1292
- "renderer",
1293
- "fiber",
1294
- "three",
1295
- "threejs"
1296
- ],
1297
- author: "Paul Henschel (https://github.com/drcmda)",
1298
- license: "MIT",
1299
- maintainers: [
1300
- "Josh Ellis (https://github.com/joshuaellis)",
1301
- "Cody Bennett (https://github.com/codyjasonbennett)",
1302
- "Kris Baumgarter (https://github.com/krispya)"
1303
- ],
1304
- bugs: {
1305
- url: "https://github.com/pmndrs/react-three-fiber/issues"
1306
- },
1307
- homepage: "https://github.com/pmndrs/react-three-fiber#readme",
1308
- repository: {
1309
- type: "git",
1310
- url: "git+https://github.com/pmndrs/react-three-fiber.git"
1311
- },
1312
- collective: {
1313
- type: "opencollective",
1314
- url: "https://opencollective.com/react-three-fiber"
1315
- },
1316
- main: "dist/react-three-fiber.cjs.js",
1317
- module: "dist/react-three-fiber.esm.js",
1318
- types: "dist/react-three-fiber.cjs.d.ts",
1319
- "react-native": "native/dist/react-three-fiber-native.cjs.js",
1320
- sideEffects: false,
1321
- preconstruct: {
1322
- entrypoints: [
1323
- "index.tsx",
1324
- "native.tsx"
1325
- ]
1326
- },
1327
- scripts: {
1328
- prebuild: "cp ../../readme.md readme.md"
1329
- },
1330
- dependencies: {
1331
- "@babel/runtime": "^7.17.8",
1332
- "@types/react-reconciler": "^0.32.0",
1333
- "@types/webxr": "*",
1334
- "base64-js": "^1.5.1",
1335
- buffer: "^6.0.3",
1336
- "its-fine": "^2.0.0",
1337
- "react-reconciler": "^0.31.0",
1338
- "react-use-measure": "^2.1.7",
1339
- scheduler: "^0.25.0",
1340
- "suspend-react": "^0.1.3",
1341
- "use-sync-external-store": "^1.4.0",
1342
- zustand: "^5.0.3"
1343
- },
1344
- peerDependencies: {
1345
- expo: ">=43.0",
1346
- "expo-asset": ">=8.4",
1347
- "expo-file-system": ">=11.0",
1348
- "expo-gl": ">=11.0",
1349
- react: "^19.0.0",
1350
- "react-dom": "^19.0.0",
1351
- "react-native": ">=0.78",
1352
- three: ">=0.156"
1353
- },
1354
- peerDependenciesMeta: {
1355
- "react-dom": {
1356
- optional: true
1357
- },
1358
- "react-native": {
1359
- optional: true
1360
- },
1361
- expo: {
1362
- optional: true
1363
- },
1364
- "expo-asset": {
1365
- optional: true
1366
- },
1367
- "expo-file-system": {
1368
- optional: true
1369
- },
1370
- "expo-gl": {
1371
- optional: true
1372
- }
1373
- }
1374
- };
1375
-
1376
- function createReconciler(config) {
1377
- const reconciler = Reconciler__default["default"](config);
1378
-
1379
- // @ts-ignore DefinitelyTyped is not up to date
1380
- reconciler.injectIntoDevTools();
1381
- return reconciler;
1382
- }
1383
- const NoEventPriority = 0;
1384
-
1385
- // TODO: handle constructor overloads
1386
- // https://github.com/pmndrs/react-three-fiber/pull/2931
1387
- // https://github.com/microsoft/TypeScript/issues/37079
1388
-
1389
- const catalogue = {};
1390
- const PREFIX_REGEX = /^three(?=[A-Z])/;
1391
- const toPascalCase = type => `${type[0].toUpperCase()}${type.slice(1)}`;
1392
- let i = 0;
1393
- const isConstructor = object => typeof object === 'function';
1394
- function extend(objects) {
1395
- if (isConstructor(objects)) {
1396
- const Component = `${i++}`;
1397
- catalogue[Component] = objects;
1398
- return Component;
1399
- } else {
1400
- Object.assign(catalogue, objects);
1401
- }
1402
- }
1403
- function validateInstance(type, props) {
1404
- // Get target from catalogue
1405
- const name = toPascalCase(type);
1406
- const target = catalogue[name];
1407
-
1408
- // Validate element target
1409
- 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`);
1410
-
1411
- // Validate primitives
1412
- if (type === 'primitive' && !props.object) throw new Error(`R3F: Primitives without 'object' are invalid!`);
1413
-
1414
- // Throw if an object or literal was passed for args
1415
- if (props.args !== undefined && !Array.isArray(props.args)) throw new Error('R3F: The args prop must be an array!');
1416
- }
1417
- function createInstance(type, props, root) {
1418
- var _props$object;
1419
- // Remove three* prefix from elements if native element not present
1420
- type = toPascalCase(type) in catalogue ? type : type.replace(PREFIX_REGEX, '');
1421
- validateInstance(type, props);
1422
-
1423
- // Regenerate the R3F instance for primitives to simulate a new object
1424
- if (type === 'primitive' && (_props$object = props.object) != null && _props$object.__r3f) delete props.object.__r3f;
1425
- return prepare(props.object, root, type, props);
1426
- }
1427
- function hideInstance(instance) {
1428
- if (!instance.isHidden) {
1429
- var _instance$parent;
1430
- if (instance.props.attach && (_instance$parent = instance.parent) != null && _instance$parent.object) {
1431
- detach(instance.parent, instance);
1432
- } else if (isObject3D(instance.object)) {
1433
- instance.object.visible = false;
1434
- }
1435
- instance.isHidden = true;
1436
- invalidateInstance(instance);
1437
- }
1438
- }
1439
- function unhideInstance(instance) {
1440
- if (instance.isHidden) {
1441
- var _instance$parent2;
1442
- if (instance.props.attach && (_instance$parent2 = instance.parent) != null && _instance$parent2.object) {
1443
- attach(instance.parent, instance);
1444
- } else if (isObject3D(instance.object) && instance.props.visible !== false) {
1445
- instance.object.visible = true;
1446
- }
1447
- instance.isHidden = false;
1448
- invalidateInstance(instance);
1449
- }
1450
- }
1451
-
1452
- // https://github.com/facebook/react/issues/20271
1453
- // This will make sure events and attach are only handled once when trees are complete
1454
- function handleContainerEffects(parent, child, beforeChild) {
1455
- // Bail if tree isn't mounted or parent is not a container.
1456
- // This ensures that the tree is finalized and React won't discard results to Suspense
1457
- const state = child.root.getState();
1458
- if (!parent.parent && parent.object !== state.scene) return;
1459
-
1460
- // Create & link object on first run
1461
- if (!child.object) {
1462
- var _child$props$object, _child$props$args;
1463
- // Get target from catalogue
1464
- const target = catalogue[toPascalCase(child.type)];
1465
-
1466
- // Create object
1467
- child.object = (_child$props$object = child.props.object) != null ? _child$props$object : new target(...((_child$props$args = child.props.args) != null ? _child$props$args : []));
1468
- child.object.__r3f = child;
1469
- }
1470
-
1471
- // Set initial props
1472
- applyProps(child.object, child.props);
1473
-
1474
- // Append instance
1475
- if (child.props.attach) {
1476
- attach(parent, child);
1477
- } else if (isObject3D(child.object) && isObject3D(parent.object)) {
1478
- const childIndex = parent.object.children.indexOf(beforeChild == null ? void 0 : beforeChild.object);
1479
- if (beforeChild && childIndex !== -1) {
1480
- // If the child is already in the parent's children array, move it to the new position
1481
- // Otherwise, just insert it at the target position
1482
- const existingIndex = parent.object.children.indexOf(child.object);
1483
- if (existingIndex !== -1) {
1484
- parent.object.children.splice(existingIndex, 1);
1485
- const adjustedIndex = existingIndex < childIndex ? childIndex - 1 : childIndex;
1486
- parent.object.children.splice(adjustedIndex, 0, child.object);
1487
- } else {
1488
- child.object.parent = parent.object;
1489
- parent.object.children.splice(childIndex, 0, child.object);
1490
- child.object.dispatchEvent({
1491
- type: 'added'
1492
- });
1493
- parent.object.dispatchEvent({
1494
- type: 'childadded',
1495
- child: child.object
1496
- });
1497
- }
1498
- } else {
1499
- parent.object.add(child.object);
1500
- }
1501
- }
1502
-
1503
- // Link subtree
1504
- for (const childInstance of child.children) handleContainerEffects(child, childInstance);
1505
-
1506
- // Tree was updated, request a frame
1507
- invalidateInstance(child);
1508
- }
1509
- function appendChild(parent, child) {
1510
- if (!child) return;
1511
-
1512
- // Link instances
1513
- child.parent = parent;
1514
- parent.children.push(child);
1515
-
1516
- // Attach tree once complete
1517
- handleContainerEffects(parent, child);
1518
- }
1519
- function insertBefore(parent, child, beforeChild) {
1520
- if (!child || !beforeChild) return;
1521
-
1522
- // Link instances
1523
- child.parent = parent;
1524
- const childIndex = parent.children.indexOf(beforeChild);
1525
- if (childIndex !== -1) parent.children.splice(childIndex, 0, child);else parent.children.push(child);
1526
-
1527
- // Attach tree once complete
1528
- handleContainerEffects(parent, child, beforeChild);
1529
- }
1530
- function disposeOnIdle(object) {
1531
- if (typeof object.dispose === 'function') {
1532
- const handleDispose = () => {
1533
- try {
1534
- object.dispose();
1535
- } catch {
1536
- // no-op
1537
- }
1538
- };
1539
-
1540
- // In a testing environment, cleanup immediately
1541
- if (typeof IS_REACT_ACT_ENVIRONMENT !== 'undefined') handleDispose();
1542
- // Otherwise, using a real GPU so schedule cleanup to prevent stalls
1543
- else scheduler.unstable_scheduleCallback(scheduler.unstable_IdlePriority, handleDispose);
1544
- }
1545
- }
1546
- function removeChild(parent, child, dispose) {
1547
- if (!child) return;
1548
-
1549
- // Unlink instances
1550
- child.parent = null;
1551
- const childIndex = parent.children.indexOf(child);
1552
- if (childIndex !== -1) parent.children.splice(childIndex, 1);
1553
-
1554
- // Eagerly tear down tree
1555
- if (child.props.attach) {
1556
- detach(parent, child);
1557
- } else if (isObject3D(child.object) && isObject3D(parent.object)) {
1558
- parent.object.remove(child.object);
1559
- removeInteractivity(findInitialRoot(child), child.object);
1560
- }
1561
-
1562
- // Allow objects to bail out of unmount disposal with dispose={null}
1563
- const shouldDispose = child.props.dispose !== null && dispose !== false;
1564
-
1565
- // Recursively remove instance children
1566
- for (let i = child.children.length - 1; i >= 0; i--) {
1567
- const node = child.children[i];
1568
- removeChild(child, node, shouldDispose);
1569
- }
1570
- child.children.length = 0;
1571
-
1572
- // Unlink instance object
1573
- delete child.object.__r3f;
1574
-
1575
- // Dispose object whenever the reconciler feels like it.
1576
- // Never dispose of primitives because their state may be kept outside of React!
1577
- // In order for an object to be able to dispose it
1578
- // - has a dispose method
1579
- // - cannot be a <primitive object={...} />
1580
- // - cannot be a THREE.Scene, because three has broken its own API
1581
- if (shouldDispose && child.type !== 'primitive' && child.object.type !== 'Scene') {
1582
- disposeOnIdle(child.object);
1583
- }
1584
-
1585
- // Tree was updated, request a frame for top-level instance
1586
- if (dispose === undefined) invalidateInstance(child);
1587
- }
1588
- function setFiberRef(fiber, publicInstance) {
1589
- for (const _fiber of [fiber, fiber.alternate]) {
1590
- if (_fiber !== null) {
1591
- if (typeof _fiber.ref === 'function') {
1592
- _fiber.refCleanup == null ? void 0 : _fiber.refCleanup();
1593
- const cleanup = _fiber.ref(publicInstance);
1594
- if (typeof cleanup === 'function') _fiber.refCleanup = cleanup;
1595
- } else if (_fiber.ref) {
1596
- _fiber.ref.current = publicInstance;
1597
- }
1598
- }
1599
- }
1600
- }
1601
- const reconstructed = [];
1602
- function swapInstances() {
1603
- // Detach instance
1604
- for (const [instance] of reconstructed) {
1605
- const parent = instance.parent;
1606
- if (parent) {
1607
- if (instance.props.attach) {
1608
- detach(parent, instance);
1609
- } else if (isObject3D(instance.object) && isObject3D(parent.object)) {
1610
- parent.object.remove(instance.object);
1611
- }
1612
- for (const child of instance.children) {
1613
- if (child.props.attach) {
1614
- detach(instance, child);
1615
- } else if (isObject3D(child.object) && isObject3D(instance.object)) {
1616
- instance.object.remove(child.object);
1617
- }
1618
- }
1619
- }
1620
-
1621
- // If the old instance is hidden, we need to unhide it.
1622
- // React assumes it can discard instances since they're pure for DOM.
1623
- // This isn't true for us since our lifetimes are impure and longliving.
1624
- // So, we manually check if an instance was hidden and unhide it.
1625
- if (instance.isHidden) unhideInstance(instance);
1626
-
1627
- // Dispose of old object if able
1628
- if (instance.object.__r3f) delete instance.object.__r3f;
1629
- if (instance.type !== 'primitive') disposeOnIdle(instance.object);
1630
- }
1631
-
1632
- // Update instance
1633
- for (const [instance, props, fiber] of reconstructed) {
1634
- instance.props = props;
1635
- const parent = instance.parent;
1636
- if (parent) {
1637
- var _instance$props$objec, _instance$props$args;
1638
- // Get target from catalogue
1639
- const target = catalogue[toPascalCase(instance.type)];
1640
-
1641
- // Create object
1642
- instance.object = (_instance$props$objec = instance.props.object) != null ? _instance$props$objec : new target(...((_instance$props$args = instance.props.args) != null ? _instance$props$args : []));
1643
- instance.object.__r3f = instance;
1644
- setFiberRef(fiber, instance.object);
1645
-
1646
- // Set initial props
1647
- applyProps(instance.object, instance.props);
1648
- if (instance.props.attach) {
1649
- attach(parent, instance);
1650
- } else if (isObject3D(instance.object) && isObject3D(parent.object)) {
1651
- parent.object.add(instance.object);
1652
- }
1653
- for (const child of instance.children) {
1654
- if (child.props.attach) {
1655
- attach(instance, child);
1656
- } else if (isObject3D(child.object) && isObject3D(instance.object)) {
1657
- instance.object.add(child.object);
1658
- }
1659
- }
1660
-
1661
- // Tree was updated, request a frame
1662
- invalidateInstance(instance);
1663
- }
1664
- }
1665
- reconstructed.length = 0;
1666
- }
1667
-
1668
- // Don't handle text instances, make it no-op
1669
- const handleTextInstance = () => {};
1670
- const NO_CONTEXT = {};
1671
- let currentUpdatePriority = NoEventPriority;
1672
-
1673
- // https://github.com/facebook/react/blob/main/packages/react-reconciler/src/ReactFiberFlags.js
1674
- const NoFlags = 0;
1675
- const Update = 4;
1676
- const reconciler = /* @__PURE__ */createReconciler({
1677
- isPrimaryRenderer: false,
1678
- warnsIfNotActing: false,
1679
- supportsMutation: true,
1680
- supportsPersistence: false,
1681
- supportsHydration: false,
1682
- createInstance,
1683
- removeChild,
1684
- appendChild,
1685
- appendInitialChild: appendChild,
1686
- insertBefore,
1687
- appendChildToContainer(container, child) {
1688
- const scene = container.getState().scene.__r3f;
1689
- if (!child || !scene) return;
1690
- appendChild(scene, child);
1691
- },
1692
- removeChildFromContainer(container, child) {
1693
- const scene = container.getState().scene.__r3f;
1694
- if (!child || !scene) return;
1695
- removeChild(scene, child);
1696
- },
1697
- insertInContainerBefore(container, child, beforeChild) {
1698
- const scene = container.getState().scene.__r3f;
1699
- if (!child || !beforeChild || !scene) return;
1700
- insertBefore(scene, child, beforeChild);
1701
- },
1702
- getRootHostContext: () => NO_CONTEXT,
1703
- getChildHostContext: () => NO_CONTEXT,
1704
- commitUpdate(instance, type, oldProps, newProps, fiber) {
1705
- var _newProps$args, _oldProps$args, _newProps$args2;
1706
- validateInstance(type, newProps);
1707
- let reconstruct = false;
1708
-
1709
- // Reconstruct primitives if object prop changes
1710
- if (instance.type === 'primitive' && oldProps.object !== newProps.object) reconstruct = true;
1711
- // Reconstruct instance if args were added or removed
1712
- else if (((_newProps$args = newProps.args) == null ? void 0 : _newProps$args.length) !== ((_oldProps$args = oldProps.args) == null ? void 0 : _oldProps$args.length)) reconstruct = true;
1713
- // Reconstruct instance if args were changed
1714
- else if ((_newProps$args2 = newProps.args) != null && _newProps$args2.some((value, index) => {
1715
- var _oldProps$args2;
1716
- return value !== ((_oldProps$args2 = oldProps.args) == null ? void 0 : _oldProps$args2[index]);
1717
- })) reconstruct = true;
1718
-
1719
- // Reconstruct when args or <primitive object={...} have changes
1720
- if (reconstruct) {
1721
- reconstructed.push([instance, {
1722
- ...newProps
1723
- }, fiber]);
1724
- } else {
1725
- // Create a diff-set, flag if there are any changes
1726
- const changedProps = diffProps(instance, newProps);
1727
- if (Object.keys(changedProps).length) {
1728
- Object.assign(instance.props, changedProps);
1729
- applyProps(instance.object, changedProps);
1730
- }
1731
- }
1732
-
1733
- // Flush reconstructed siblings when we hit the last updated child in a sequence
1734
- const isTailSibling = fiber.sibling === null || (fiber.flags & Update) === NoFlags;
1735
- if (isTailSibling) swapInstances();
1736
- },
1737
- finalizeInitialChildren: () => false,
1738
- commitMount() {},
1739
- getPublicInstance: instance => instance == null ? void 0 : instance.object,
1740
- prepareForCommit: () => null,
1741
- preparePortalMount: container => prepare(container.getState().scene, container, '', {}),
1742
- resetAfterCommit: () => {},
1743
- shouldSetTextContent: () => false,
1744
- clearContainer: () => false,
1745
- hideInstance,
1746
- unhideInstance,
1747
- createTextInstance: handleTextInstance,
1748
- hideTextInstance: handleTextInstance,
1749
- unhideTextInstance: handleTextInstance,
1750
- scheduleTimeout: typeof setTimeout === 'function' ? setTimeout : undefined,
1751
- cancelTimeout: typeof clearTimeout === 'function' ? clearTimeout : undefined,
1752
- noTimeout: -1,
1753
- getInstanceFromNode: () => null,
1754
- beforeActiveInstanceBlur() {},
1755
- afterActiveInstanceBlur() {},
1756
- detachDeletedInstance() {},
1757
- prepareScopeUpdate() {},
1758
- getInstanceFromScope: () => null,
1759
- shouldAttemptEagerTransition: () => false,
1760
- trackSchedulerEvent: () => {},
1761
- resolveEventType: () => null,
1762
- resolveEventTimeStamp: () => -1.1,
1763
- requestPostPaintCallback() {},
1764
- maySuspendCommit: () => false,
1765
- preloadInstance: () => true,
1766
- // true indicates already loaded
1767
- startSuspendingCommit() {},
1768
- suspendInstance() {},
1769
- waitForCommitToBeReady: () => null,
1770
- NotPendingTransition: null,
1771
- // The reconciler types use the internal ReactContext with all the hidden properties
1772
- // so we have to cast from the public React.Context type
1773
- HostTransitionContext: /* @__PURE__ */React__namespace.createContext(null),
1774
- setCurrentUpdatePriority(newPriority) {
1775
- currentUpdatePriority = newPriority;
1776
- },
1777
- getCurrentUpdatePriority() {
1778
- return currentUpdatePriority;
1779
- },
1780
- resolveUpdatePriority() {
1781
- var _window$event;
1782
- if (currentUpdatePriority !== NoEventPriority) return currentUpdatePriority;
1783
- switch (typeof window !== 'undefined' && ((_window$event = window.event) == null ? void 0 : _window$event.type)) {
1784
- case 'click':
1785
- case 'contextmenu':
1786
- case 'dblclick':
1787
- case 'pointercancel':
1788
- case 'pointerdown':
1789
- case 'pointerup':
1790
- return constants.DiscreteEventPriority;
1791
- case 'pointermove':
1792
- case 'pointerout':
1793
- case 'pointerover':
1794
- case 'pointerenter':
1795
- case 'pointerleave':
1796
- case 'wheel':
1797
- return constants.ContinuousEventPriority;
1798
- default:
1799
- return constants.DefaultEventPriority;
1800
- }
1801
- },
1802
- resetFormInstance() {},
1803
- // @ts-ignore DefinitelyTyped is not up to date
1804
- rendererPackageName: '@react-three/fiber',
1805
- rendererVersion: packageData.version
1806
- });
1807
-
1808
- const _roots = new Map();
1809
- const shallowLoose = {
1810
- objects: 'shallow',
1811
- strict: false
1812
- };
1813
- function computeInitialSize(canvas, size) {
1814
- if (!size && typeof HTMLCanvasElement !== 'undefined' && canvas instanceof HTMLCanvasElement && canvas.parentElement) {
1815
- const {
1816
- width,
1817
- height,
1818
- top,
1819
- left
1820
- } = canvas.parentElement.getBoundingClientRect();
1821
- return {
1822
- width,
1823
- height,
1824
- top,
1825
- left
1826
- };
1827
- } else if (!size && typeof OffscreenCanvas !== 'undefined' && canvas instanceof OffscreenCanvas) {
1828
- return {
1829
- width: canvas.width,
1830
- height: canvas.height,
1831
- top: 0,
1832
- left: 0
1833
- };
1834
- }
1835
- return {
1836
- width: 0,
1837
- height: 0,
1838
- top: 0,
1839
- left: 0,
1840
- ...size
1841
- };
1842
- }
1843
- function createRoot(canvas) {
1844
- // Check against mistaken use of createRoot
1845
- const prevRoot = _roots.get(canvas);
1846
- const prevFiber = prevRoot == null ? void 0 : prevRoot.fiber;
1847
- const prevStore = prevRoot == null ? void 0 : prevRoot.store;
1848
- if (prevRoot) console.warn('R3F.createRoot should only be called once!');
1849
-
1850
- // Report when an error was detected in a previous render
1851
- // https://github.com/pmndrs/react-three-fiber/pull/2261
1852
- const logRecoverableError = typeof reportError === 'function' ?
1853
- // In modern browsers, reportError will dispatch an error event,
1854
- // emulating an uncaught JavaScript error.
1855
- reportError :
1856
- // In older browsers and test environments, fallback to console.error.
1857
- console.error;
1858
-
1859
- // Create store
1860
- const store = prevStore || createStore(invalidate, advance);
1861
- // Create renderer
1862
- const fiber = prevFiber || reconciler.createContainer(store,
1863
- // container
1864
- constants.ConcurrentRoot,
1865
- // tag
1866
- null,
1867
- // hydration callbacks
1868
- false,
1869
- // isStrictMode
1870
- null,
1871
- // concurrentUpdatesByDefaultOverride
1872
- '',
1873
- // identifierPrefix
1874
- logRecoverableError,
1875
- // onUncaughtError
1876
- logRecoverableError,
1877
- // onCaughtError
1878
- logRecoverableError,
1879
- // onRecoverableError
1880
- null // transitionCallbacks
1881
- );
1882
- // Map it
1883
- if (!prevRoot) _roots.set(canvas, {
1884
- fiber,
1885
- store
1886
- });
1887
-
1888
- // Locals
1889
- let onCreated;
1890
- let lastCamera;
1891
- let configured = false;
1892
- let pending = null;
1893
- return {
1894
- async configure(props = {}) {
1895
- let resolve;
1896
- pending = new Promise(_resolve => resolve = _resolve);
1897
- let {
1898
- gl: glConfig,
1899
- size: propsSize,
1900
- scene: sceneOptions,
1901
- events,
1902
- onCreated: onCreatedCallback,
1903
- shadows = false,
1904
- linear = false,
1905
- flat = false,
1906
- legacy = false,
1907
- orthographic = false,
1908
- frameloop = 'always',
1909
- dpr = [1, 2],
1910
- performance,
1911
- raycaster: raycastOptions,
1912
- camera: cameraOptions,
1913
- onPointerMissed
1914
- } = props;
1915
- let state = store.getState();
1916
-
1917
- // Set up renderer (one time only!)
1918
- let gl = state.gl;
1919
- if (!state.gl) {
1920
- const defaultProps = {
1921
- canvas: canvas,
1922
- powerPreference: 'high-performance',
1923
- antialias: true,
1924
- alpha: true
1925
- };
1926
- const customRenderer = typeof glConfig === 'function' ? await glConfig(defaultProps) : glConfig;
1927
- if (isRenderer(customRenderer)) {
1928
- gl = customRenderer;
1929
- } else {
1930
- gl = new THREE__namespace.WebGLRenderer({
1931
- ...defaultProps,
1932
- ...glConfig
1933
- });
1934
- }
1935
- state.set({
1936
- gl
1937
- });
1938
- }
1939
-
1940
- // Set up raycaster (one time only!)
1941
- let raycaster = state.raycaster;
1942
- if (!raycaster) state.set({
1943
- raycaster: raycaster = new THREE__namespace.Raycaster()
1944
- });
1945
-
1946
- // Set raycaster options
1947
- const {
1948
- params,
1949
- ...options
1950
- } = raycastOptions || {};
1951
- if (!is.equ(options, raycaster, shallowLoose)) applyProps(raycaster, {
1952
- ...options
1953
- });
1954
- if (!is.equ(params, raycaster.params, shallowLoose)) applyProps(raycaster, {
1955
- params: {
1956
- ...raycaster.params,
1957
- ...params
1958
- }
1959
- });
1960
-
1961
- // Create default camera, don't overwrite any user-set state
1962
- if (!state.camera || state.camera === lastCamera && !is.equ(lastCamera, cameraOptions, shallowLoose)) {
1963
- lastCamera = cameraOptions;
1964
- const isCamera = cameraOptions == null ? void 0 : cameraOptions.isCamera;
1965
- const camera = isCamera ? cameraOptions : orthographic ? new THREE__namespace.OrthographicCamera(0, 0, 0, 0, 0.1, 1000) : new THREE__namespace.PerspectiveCamera(75, 0, 0.1, 1000);
1966
- if (!isCamera) {
1967
- camera.position.z = 5;
1968
- if (cameraOptions) {
1969
- applyProps(camera, cameraOptions);
1970
- // Preserve user-defined frustum if possible
1971
- // https://github.com/pmndrs/react-three-fiber/issues/3160
1972
- if (!camera.manual) {
1973
- if ('aspect' in cameraOptions || 'left' in cameraOptions || 'right' in cameraOptions || 'bottom' in cameraOptions || 'top' in cameraOptions) {
1974
- camera.manual = true;
1975
- camera.updateProjectionMatrix();
1976
- }
1977
- }
1978
- }
1979
- // Always look at center by default
1980
- if (!state.camera && !(cameraOptions != null && cameraOptions.rotation)) camera.lookAt(0, 0, 0);
1981
- }
1982
- state.set({
1983
- camera
1984
- });
1985
-
1986
- // Configure raycaster
1987
- // https://github.com/pmndrs/react-xr/issues/300
1988
- raycaster.camera = camera;
1989
- }
1990
-
1991
- // Set up scene (one time only!)
1992
- if (!state.scene) {
1993
- let scene;
1994
- if (sceneOptions != null && sceneOptions.isScene) {
1995
- scene = sceneOptions;
1996
- prepare(scene, store, '', {});
1997
- } else {
1998
- scene = new THREE__namespace.Scene();
1999
- prepare(scene, store, '', {});
2000
- if (sceneOptions) applyProps(scene, sceneOptions);
2001
- }
2002
- state.set({
2003
- scene
2004
- });
2005
- }
2006
-
2007
- // Store events internally
2008
- if (events && !state.events.handlers) state.set({
2009
- events: events(store)
2010
- });
2011
- // Check size, allow it to take on container bounds initially
2012
- const size = computeInitialSize(canvas, propsSize);
2013
- if (!is.equ(size, state.size, shallowLoose)) {
2014
- state.setSize(size.width, size.height, size.top, size.left);
2015
- }
2016
- // Check pixelratio
2017
- if (dpr && state.viewport.dpr !== calculateDpr(dpr)) state.setDpr(dpr);
2018
- // Check frameloop
2019
- if (state.frameloop !== frameloop) state.setFrameloop(frameloop);
2020
- // Check pointer missed
2021
- if (!state.onPointerMissed) state.set({
2022
- onPointerMissed
2023
- });
2024
- // Check performance
2025
- if (performance && !is.equ(performance, state.performance, shallowLoose)) state.set(state => ({
2026
- performance: {
2027
- ...state.performance,
2028
- ...performance
2029
- }
2030
- }));
2031
-
2032
- // Set up XR (one time only!)
2033
- if (!state.xr) {
2034
- var _gl$xr;
2035
- // Handle frame behavior in WebXR
2036
- const handleXRFrame = (timestamp, frame) => {
2037
- const state = store.getState();
2038
- if (state.frameloop === 'never') return;
2039
- advance(timestamp, true, state, frame);
2040
- };
2041
-
2042
- // Toggle render switching on session
2043
- const handleSessionChange = () => {
2044
- const state = store.getState();
2045
- state.gl.xr.enabled = state.gl.xr.isPresenting;
2046
- state.gl.xr.setAnimationLoop(state.gl.xr.isPresenting ? handleXRFrame : null);
2047
- if (!state.gl.xr.isPresenting) invalidate(state);
2048
- };
2049
-
2050
- // WebXR session manager
2051
- const xr = {
2052
- connect() {
2053
- const gl = store.getState().gl;
2054
- gl.xr.addEventListener('sessionstart', handleSessionChange);
2055
- gl.xr.addEventListener('sessionend', handleSessionChange);
2056
- },
2057
- disconnect() {
2058
- const gl = store.getState().gl;
2059
- gl.xr.removeEventListener('sessionstart', handleSessionChange);
2060
- gl.xr.removeEventListener('sessionend', handleSessionChange);
2061
- }
2062
- };
2063
-
2064
- // Subscribe to WebXR session events
2065
- if (typeof ((_gl$xr = gl.xr) == null ? void 0 : _gl$xr.addEventListener) === 'function') xr.connect();
2066
- state.set({
2067
- xr
2068
- });
2069
- }
2070
-
2071
- // Set shadowmap
2072
- if (gl.shadowMap) {
2073
- const oldEnabled = gl.shadowMap.enabled;
2074
- const oldType = gl.shadowMap.type;
2075
- gl.shadowMap.enabled = !!shadows;
2076
- if (is.boo(shadows)) {
2077
- gl.shadowMap.type = THREE__namespace.PCFSoftShadowMap;
2078
- } else if (is.str(shadows)) {
2079
- var _types$shadows;
2080
- const types = {
2081
- basic: THREE__namespace.BasicShadowMap,
2082
- percentage: THREE__namespace.PCFShadowMap,
2083
- soft: THREE__namespace.PCFSoftShadowMap,
2084
- variance: THREE__namespace.VSMShadowMap
2085
- };
2086
- gl.shadowMap.type = (_types$shadows = types[shadows]) != null ? _types$shadows : THREE__namespace.PCFSoftShadowMap;
2087
- } else if (is.obj(shadows)) {
2088
- Object.assign(gl.shadowMap, shadows);
2089
- }
2090
- if (oldEnabled !== gl.shadowMap.enabled || oldType !== gl.shadowMap.type) gl.shadowMap.needsUpdate = true;
2091
- }
2092
- THREE__namespace.ColorManagement.enabled = !legacy;
2093
-
2094
- // Set color space and tonemapping preferences
2095
- if (!configured) {
2096
- gl.outputColorSpace = linear ? THREE__namespace.LinearSRGBColorSpace : THREE__namespace.SRGBColorSpace;
2097
- gl.toneMapping = flat ? THREE__namespace.NoToneMapping : THREE__namespace.ACESFilmicToneMapping;
2098
- }
2099
-
2100
- // Update color management state
2101
- if (state.legacy !== legacy) state.set(() => ({
2102
- legacy
2103
- }));
2104
- if (state.linear !== linear) state.set(() => ({
2105
- linear
2106
- }));
2107
- if (state.flat !== flat) state.set(() => ({
2108
- flat
2109
- }));
2110
-
2111
- // Set gl props
2112
- if (glConfig && !is.fun(glConfig) && !isRenderer(glConfig) && !is.equ(glConfig, gl, shallowLoose)) applyProps(gl, glConfig);
2113
-
2114
- // Set locals
2115
- onCreated = onCreatedCallback;
2116
- configured = true;
2117
- resolve();
2118
- return this;
2119
- },
2120
- render(children) {
2121
- // The root has to be configured before it can be rendered
2122
- if (!configured && !pending) this.configure();
2123
- pending.then(() => {
2124
- reconciler.updateContainer( /*#__PURE__*/jsxRuntime.jsx(Provider, {
2125
- store: store,
2126
- children: children,
2127
- onCreated: onCreated,
2128
- rootElement: canvas
2129
- }), fiber, null, () => undefined);
2130
- });
2131
- return store;
2132
- },
2133
- unmount() {
2134
- unmountComponentAtNode(canvas);
2135
- }
2136
- };
2137
- }
2138
- function Provider({
2139
- store,
2140
- children,
2141
- onCreated,
2142
- rootElement
2143
- }) {
2144
- useIsomorphicLayoutEffect(() => {
2145
- const state = store.getState();
2146
- // Flag the canvas active, rendering will now begin
2147
- state.set(state => ({
2148
- internal: {
2149
- ...state.internal,
2150
- active: true
2151
- }
2152
- }));
2153
- // Notify that init is completed, the scene graph exists, but nothing has yet rendered
2154
- if (onCreated) onCreated(state);
2155
- // Connect events to the targets parent, this is done to ensure events are registered on
2156
- // a shared target, and not on the canvas itself
2157
- if (!store.getState().events.connected) state.events.connect == null ? void 0 : state.events.connect(rootElement);
2158
- // eslint-disable-next-line react-hooks/exhaustive-deps
2159
- }, []);
2160
- return /*#__PURE__*/jsxRuntime.jsx(context.Provider, {
2161
- value: store,
2162
- children: children
2163
- });
2164
- }
2165
- function unmountComponentAtNode(canvas, callback) {
2166
- const root = _roots.get(canvas);
2167
- const fiber = root == null ? void 0 : root.fiber;
2168
- if (fiber) {
2169
- const state = root == null ? void 0 : root.store.getState();
2170
- if (state) state.internal.active = false;
2171
- reconciler.updateContainer(null, fiber, null, () => {
2172
- if (state) {
2173
- setTimeout(() => {
2174
- try {
2175
- var _state$gl, _state$gl$renderLists, _state$gl2, _state$gl3;
2176
- state.events.disconnect == null ? void 0 : state.events.disconnect();
2177
- (_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();
2178
- (_state$gl2 = state.gl) == null ? void 0 : _state$gl2.forceContextLoss == null ? void 0 : _state$gl2.forceContextLoss();
2179
- if ((_state$gl3 = state.gl) != null && _state$gl3.xr) state.xr.disconnect();
2180
- dispose(state.scene);
2181
- _roots.delete(canvas);
2182
- if (callback) callback(canvas);
2183
- } catch (e) {
2184
- /* ... */
2185
- }
2186
- }, 500);
2187
- }
2188
- });
2189
- }
2190
- }
2191
- function createPortal(children, container, state) {
2192
- return /*#__PURE__*/jsxRuntime.jsx(Portal, {
2193
- children: children,
2194
- container: container,
2195
- state: state
2196
- });
2197
- }
2198
- function Portal({
2199
- state = {},
2200
- children,
2201
- container
2202
- }) {
2203
- /** This has to be a component because it would not be able to call useThree/useStore otherwise since
2204
- * if this is our environment, then we are not in r3f's renderer but in react-dom, it would trigger
2205
- * the "R3F hooks can only be used within the Canvas component!" warning:
2206
- * <Canvas>
2207
- * {createPortal(...)} */
2208
- const {
2209
- events,
2210
- size,
2211
- ...rest
2212
- } = state;
2213
- const previousRoot = useStore();
2214
- const [raycaster] = React__namespace.useState(() => new THREE__namespace.Raycaster());
2215
- const [pointer] = React__namespace.useState(() => new THREE__namespace.Vector2());
2216
- const inject = useMutableCallback((rootState, injectState) => {
2217
- let viewport = undefined;
2218
- if (injectState.camera && size) {
2219
- const camera = injectState.camera;
2220
- // Calculate the override viewport, if present
2221
- viewport = rootState.viewport.getCurrentViewport(camera, new THREE__namespace.Vector3(), size);
2222
- // Update the portal camera, if it differs from the previous layer
2223
- if (camera !== rootState.camera) updateCamera(camera, size);
2224
- }
2225
- return {
2226
- // The intersect consists of the previous root state
2227
- ...rootState,
2228
- ...injectState,
2229
- // Portals have their own scene, which forms the root, a raycaster and a pointer
2230
- scene: container,
2231
- raycaster,
2232
- pointer,
2233
- mouse: pointer,
2234
- // Their previous root is the layer before it
2235
- previousRoot,
2236
- // Events, size and viewport can be overridden by the inject layer
2237
- events: {
2238
- ...rootState.events,
2239
- ...injectState.events,
2240
- ...events
2241
- },
2242
- size: {
2243
- ...rootState.size,
2244
- ...size
2245
- },
2246
- viewport: {
2247
- ...rootState.viewport,
2248
- ...viewport
2249
- },
2250
- // Layers are allowed to override events
2251
- setEvents: events => injectState.set(state => ({
2252
- ...state,
2253
- events: {
2254
- ...state.events,
2255
- ...events
2256
- }
2257
- }))
2258
- };
2259
- });
2260
- const usePortalStore = React__namespace.useMemo(() => {
2261
- // Create a mirrored store, based on the previous root with a few overrides ...
2262
- const store = traditional.createWithEqualityFn((set, get) => ({
2263
- ...rest,
2264
- set,
2265
- get
2266
- }));
2267
-
2268
- // Subscribe to previous root-state and copy changes over to the mirrored portal-state
2269
- const onMutate = prev => store.setState(state => inject.current(prev, state));
2270
- onMutate(previousRoot.getState());
2271
- previousRoot.subscribe(onMutate);
2272
- return store;
2273
- // eslint-disable-next-line react-hooks/exhaustive-deps
2274
- }, [previousRoot, container]);
2275
- return (
2276
- /*#__PURE__*/
2277
- // @ts-ignore, reconciler types are not maintained
2278
- jsxRuntime.jsx(jsxRuntime.Fragment, {
2279
- children: reconciler.createPortal( /*#__PURE__*/jsxRuntime.jsx(context.Provider, {
2280
- value: usePortalStore,
2281
- children: children
2282
- }), usePortalStore, null)
2283
- })
2284
- );
2285
- }
2286
-
2287
- /**
2288
- * Force React to flush any updates inside the provided callback synchronously and immediately.
2289
- * All the same caveats documented for react-dom's `flushSync` apply here (see https://react.dev/reference/react-dom/flushSync).
2290
- * Nevertheless, sometimes one needs to render synchronously, for example to keep DOM and 3D changes in lock-step without
2291
- * having to revert to a non-React solution. Note: this will only flush updates within the `Canvas` root.
2292
- */
2293
- function flushSync(fn) {
2294
- // @ts-ignore - reconciler types are not maintained
2295
- return reconciler.flushSyncFromReconciler(fn);
2296
- }
2297
-
2298
- function createSubs(callback, subs) {
2299
- const sub = {
2300
- callback
2301
- };
2302
- subs.add(sub);
2303
- return () => void subs.delete(sub);
2304
- }
2305
- const globalEffects = new Set();
2306
- const globalAfterEffects = new Set();
2307
- const globalTailEffects = new Set();
2308
-
2309
- /**
2310
- * Adds a global render callback which is called each frame.
2311
- * @see https://docs.pmnd.rs/react-three-fiber/api/additional-exports#addEffect
2312
- */
2313
- const addEffect = callback => createSubs(callback, globalEffects);
2314
-
2315
- /**
2316
- * Adds a global after-render callback which is called each frame.
2317
- * @see https://docs.pmnd.rs/react-three-fiber/api/additional-exports#addAfterEffect
2318
- */
2319
- const addAfterEffect = callback => createSubs(callback, globalAfterEffects);
2320
-
2321
- /**
2322
- * Adds a global callback which is called when rendering stops.
2323
- * @see https://docs.pmnd.rs/react-three-fiber/api/additional-exports#addTail
2324
- */
2325
- const addTail = callback => createSubs(callback, globalTailEffects);
2326
- function run(effects, timestamp) {
2327
- if (!effects.size) return;
2328
- for (const {
2329
- callback
2330
- } of effects.values()) {
2331
- callback(timestamp);
2332
- }
2333
- }
2334
- function flushGlobalEffects(type, timestamp) {
2335
- switch (type) {
2336
- case 'before':
2337
- return run(globalEffects, timestamp);
2338
- case 'after':
2339
- return run(globalAfterEffects, timestamp);
2340
- case 'tail':
2341
- return run(globalTailEffects, timestamp);
2342
- }
2343
- }
2344
- let subscribers;
2345
- let subscription;
2346
- function update(timestamp, state, frame) {
2347
- // Run local effects
2348
- let delta = state.clock.getDelta();
2349
-
2350
- // In frameloop='never' mode, clock times are updated using the provided timestamp
2351
- if (state.frameloop === 'never' && typeof timestamp === 'number') {
2352
- delta = timestamp - state.clock.elapsedTime;
2353
- state.clock.oldTime = state.clock.elapsedTime;
2354
- state.clock.elapsedTime = timestamp;
2355
- }
2356
-
2357
- // Call subscribers (useFrame)
2358
- subscribers = state.internal.subscribers;
2359
- for (let i = 0; i < subscribers.length; i++) {
2360
- subscription = subscribers[i];
2361
- subscription.ref.current(subscription.store.getState(), delta, frame);
2362
- }
2363
-
2364
- // Render content
2365
- if (!state.internal.priority && state.gl.render) state.gl.render(state.scene, state.camera);
2366
-
2367
- // Decrease frame count
2368
- state.internal.frames = Math.max(0, state.internal.frames - 1);
2369
- return state.frameloop === 'always' ? 1 : state.internal.frames;
2370
- }
2371
- let running = false;
2372
- let useFrameInProgress = false;
2373
- let repeat;
2374
- let frame;
2375
- let state;
2376
- function loop(timestamp) {
2377
- frame = requestAnimationFrame(loop);
2378
- running = true;
2379
- repeat = 0;
2380
-
2381
- // Run effects
2382
- flushGlobalEffects('before', timestamp);
2383
-
2384
- // Render all roots
2385
- useFrameInProgress = true;
2386
- for (const root of _roots.values()) {
2387
- var _state$gl$xr;
2388
- state = root.store.getState();
2389
-
2390
- // If the frameloop is invalidated, do not run another frame
2391
- if (state.internal.active && (state.frameloop === 'always' || state.internal.frames > 0) && !((_state$gl$xr = state.gl.xr) != null && _state$gl$xr.isPresenting)) {
2392
- repeat += update(timestamp, state);
2393
- }
2394
- }
2395
- useFrameInProgress = false;
2396
-
2397
- // Run after-effects
2398
- flushGlobalEffects('after', timestamp);
2399
-
2400
- // Stop the loop if nothing invalidates it
2401
- if (repeat === 0) {
2402
- // Tail call effects, they are called when rendering stops
2403
- flushGlobalEffects('tail', timestamp);
2404
-
2405
- // Flag end of operation
2406
- running = false;
2407
- return cancelAnimationFrame(frame);
2408
- }
2409
- }
2410
-
2411
- /**
2412
- * Invalidates the view, requesting a frame to be rendered. Will globally invalidate unless passed a root's state.
2413
- * @see https://docs.pmnd.rs/react-three-fiber/api/additional-exports#invalidate
2414
- */
2415
- function invalidate(state, frames = 1) {
2416
- var _state$gl$xr2;
2417
- if (!state) return _roots.forEach(root => invalidate(root.store.getState(), frames));
2418
- if ((_state$gl$xr2 = state.gl.xr) != null && _state$gl$xr2.isPresenting || !state.internal.active || state.frameloop === 'never') return;
2419
- if (frames > 1) {
2420
- // legacy support for people using frames parameters
2421
- // Increase frames, do not go higher than 60
2422
- state.internal.frames = Math.min(60, state.internal.frames + frames);
2423
- } else {
2424
- if (useFrameInProgress) {
2425
- //called from within a useFrame, it means the user wants an additional frame
2426
- state.internal.frames = 2;
2427
- } else {
2428
- //the user need a new frame, no need to increment further than 1
2429
- state.internal.frames = 1;
2430
- }
2431
- }
2432
-
2433
- // If the render-loop isn't active, start it
2434
- if (!running) {
2435
- running = true;
2436
- requestAnimationFrame(loop);
2437
- }
2438
- }
2439
-
2440
- /**
2441
- * Advances the frameloop and runs render effects, useful for when manually rendering via `frameloop="never"`.
2442
- * @see https://docs.pmnd.rs/react-three-fiber/api/additional-exports#advance
2443
- */
2444
- function advance(timestamp, runGlobalEffects = true, state, frame) {
2445
- if (runGlobalEffects) flushGlobalEffects('before', timestamp);
2446
- if (!state) for (const root of _roots.values()) update(timestamp, root.store.getState());else update(timestamp, state, frame);
2447
- if (runGlobalEffects) flushGlobalEffects('after', timestamp);
2448
- }
2449
-
2450
- const DOM_EVENTS = {
2451
- onClick: ['click', false],
2452
- onContextMenu: ['contextmenu', false],
2453
- onDoubleClick: ['dblclick', false],
2454
- onWheel: ['wheel', true],
2455
- onPointerDown: ['pointerdown', true],
2456
- onPointerUp: ['pointerup', true],
2457
- onPointerLeave: ['pointerleave', true],
2458
- onPointerMove: ['pointermove', true],
2459
- onPointerCancel: ['pointercancel', true],
2460
- onLostPointerCapture: ['lostpointercapture', true]
2461
- };
2462
-
2463
- /** Default R3F event manager for web */
2464
- function createPointerEvents(store) {
2465
- const {
2466
- handlePointer
2467
- } = createEvents(store);
2468
- return {
2469
- priority: 1,
2470
- enabled: true,
2471
- compute(event, state, previous) {
2472
- // https://github.com/pmndrs/react-three-fiber/pull/782
2473
- // Events trigger outside of canvas when moved, use offsetX/Y by default and allow overrides
2474
- state.pointer.set(event.offsetX / state.size.width * 2 - 1, -(event.offsetY / state.size.height) * 2 + 1);
2475
- state.raycaster.setFromCamera(state.pointer, state.camera);
2476
- },
2477
- connected: undefined,
2478
- handlers: Object.keys(DOM_EVENTS).reduce((acc, key) => ({
2479
- ...acc,
2480
- [key]: handlePointer(key)
2481
- }), {}),
2482
- update: () => {
2483
- var _internal$lastEvent;
2484
- const {
2485
- events,
2486
- internal
2487
- } = store.getState();
2488
- if ((_internal$lastEvent = internal.lastEvent) != null && _internal$lastEvent.current && events.handlers) events.handlers.onPointerMove(internal.lastEvent.current);
2489
- },
2490
- connect: target => {
2491
- const {
2492
- set,
2493
- events
2494
- } = store.getState();
2495
- events.disconnect == null ? void 0 : events.disconnect();
2496
- set(state => ({
2497
- events: {
2498
- ...state.events,
2499
- connected: target
2500
- }
2501
- }));
2502
- if (events.handlers) {
2503
- for (const name in events.handlers) {
2504
- const event = events.handlers[name];
2505
- const [eventName, passive] = DOM_EVENTS[name];
2506
- target.addEventListener(eventName, event, {
2507
- passive
2508
- });
2509
- }
2510
- }
2511
- },
2512
- disconnect: () => {
2513
- const {
2514
- set,
2515
- events
2516
- } = store.getState();
2517
- if (events.connected) {
2518
- if (events.handlers) {
2519
- for (const name in events.handlers) {
2520
- const event = events.handlers[name];
2521
- const [eventName] = DOM_EVENTS[name];
2522
- events.connected.removeEventListener(eventName, event);
2523
- }
2524
- }
2525
- set(state => ({
2526
- events: {
2527
- ...state.events,
2528
- connected: undefined
2529
- }
2530
- }));
2531
- }
2532
- }
2533
- };
2534
- }
2535
-
2536
- exports.Block = Block;
2537
- exports.ErrorBoundary = ErrorBoundary;
2538
- exports._roots = _roots;
2539
- exports.act = act;
2540
- exports.addAfterEffect = addAfterEffect;
2541
- exports.addEffect = addEffect;
2542
- exports.addTail = addTail;
2543
- exports.advance = advance;
2544
- exports.applyProps = applyProps;
2545
- exports.buildGraph = buildGraph;
2546
- exports.context = context;
2547
- exports.createEvents = createEvents;
2548
- exports.createPointerEvents = createPointerEvents;
2549
- exports.createPortal = createPortal;
2550
- exports.createRoot = createRoot;
2551
- exports.dispose = dispose;
2552
- exports.extend = extend;
2553
- exports.flushGlobalEffects = flushGlobalEffects;
2554
- exports.flushSync = flushSync;
2555
- exports.getRootState = getRootState;
2556
- exports.invalidate = invalidate;
2557
- exports.isRef = isRef;
2558
- exports.reconciler = reconciler;
2559
- exports.threeTypes = threeTypes;
2560
- exports.unmountComponentAtNode = unmountComponentAtNode;
2561
- exports.useBridge = useBridge;
2562
- exports.useFrame = useFrame;
2563
- exports.useGraph = useGraph;
2564
- exports.useInstanceHandle = useInstanceHandle;
2565
- exports.useIsomorphicLayoutEffect = useIsomorphicLayoutEffect;
2566
- exports.useLoader = useLoader;
2567
- exports.useMutableCallback = useMutableCallback;
2568
- exports.useStore = useStore;
2569
- exports.useThree = useThree;