@react-three/fiber 10.0.0-canary.f5d9cbd → 10.0.0-canary.f81281f

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.
package/dist/index.d.mts CHANGED
@@ -1,3767 +1,144 @@
1
- import * as three_examples_jsm_inspector_Inspector_js from 'three/examples/jsm/inspector/Inspector.js';
2
- import * as three_webgpu from 'three/webgpu';
3
- import { CubeRenderTarget, RenderTarget, WebGPURenderer, Node, StorageTexture, Data3DTexture, CanvasTarget, ShaderNodeObject, Euler as Euler$2, Color as Color$2, ColorRepresentation as ColorRepresentation$1, Layers as Layers$1, Raycaster, Intersection as Intersection$1, BufferGeometry, Matrix4 as Matrix4$1, Quaternion as Quaternion$1, Vector2 as Vector2$1, Vector3 as Vector3$1, Vector4 as Vector4$1, Matrix3 as Matrix3$1, Loader as Loader$1, ColorSpace, Texture as Texture$1, CubeTexture, Scene, Object3D, Frustum, OrthographicCamera } from 'three/webgpu';
4
- import * as THREE$1 from 'three';
5
- import { WebGLCubeRenderTarget, WebGLRenderTarget, WebGLRenderer, Color as Color$1, ColorRepresentation, Euler as Euler$1, Loader, RenderTargetOptions as RenderTargetOptions$1 } from 'three';
6
- import { WebGLRendererParameters } from 'three/src/renderers/WebGLRenderer.js';
7
- import { Inspector } from 'three/addons/inspector/Inspector.js';
8
- import * as React$1 from 'react';
9
- import { ReactNode, Component, RefObject, JSX } from 'react';
10
- import { StoreApi } from 'zustand';
11
- import { UseBoundStoreWithEqualityFn } from 'zustand/traditional';
12
- import { FrameTimingState, FrameCallback as FrameCallback$1, SchedulerApi, UseFrameNextOptions, FrameNextControls } from '@pmndrs/scheduler';
13
- export { AddPhaseOptions, FrameControls, FrameNextControls, FrameTimingState, RootOptions, Scheduler, SchedulerApi, UseFrameNextOptions, UseFrameOptions, getScheduler } from '@pmndrs/scheduler';
14
- import { Options } from 'react-use-measure';
1
+ import * as ThreeWebGPU from 'three/webgpu';
2
+ import * as THREE from 'three';
15
3
  import * as react_jsx_runtime from 'react/jsx-runtime';
16
- import { GroundedSkybox } from 'three/examples/jsm/objects/GroundedSkybox.js';
17
-
18
- function _mergeNamespaces(n, m) {
19
- m.forEach(function (e) {
20
- e && typeof e !== 'string' && !Array.isArray(e) && Object.keys(e).forEach(function (k) {
21
- if (k !== 'default' && !(k in n)) {
22
- var d = Object.getOwnPropertyDescriptor(e, k);
23
- Object.defineProperty(n, k, d.get ? d : {
24
- enumerable: true,
25
- get: function () { return e[k]; }
26
- });
27
- }
28
- });
29
- });
30
- return Object.freeze(n);
31
- }
32
-
33
- /**
34
- * @fileoverview Internal Three.js re-exports - DEFAULT ENTRY
35
- *
36
- * This is the single source of truth for Three.js imports within R3F.
37
- * All internal code should import from '#three' (or '../three' relative).
38
- *
39
- * DEFAULT behavior (root import):
40
- * - Exports from three/webgpu (the new standard)
41
- * - Also exports WebGLRenderer for backwards compatibility (with deprecation)
42
- * - Both renderer types available, runtime decides which to use
43
- *
44
- * For explicit legacy or webgpu-only builds, use:
45
- * - #three/legacy - WebGL only, no WebGPU
46
- * - #three/webgpu - WebGPU only, no WebGL legacy
47
- */
48
- declare const R3F_BUILD_LEGACY = true;
49
- declare const R3F_BUILD_WEBGPU = true;
50
-
51
- /** Lazily load the three Inspector. Keeps it out of the eager module graph — see note above. */
52
- declare function loadInspector(): Promise<typeof three_examples_jsm_inspector_Inspector_js.Inspector>;
53
-
54
- var THREE = /*#__PURE__*/_mergeNamespaces({
55
- __proto__: null,
56
- CubeRenderTarget: CubeRenderTarget,
57
- CubeRenderTargetCompat: CubeRenderTarget,
58
- Inspector: Inspector,
59
- R3F_BUILD_LEGACY: R3F_BUILD_LEGACY,
60
- R3F_BUILD_WEBGPU: R3F_BUILD_WEBGPU,
61
- RenderTargetCompat: RenderTarget,
62
- WebGLCubeRenderTarget: WebGLCubeRenderTarget,
63
- WebGLRenderTarget: WebGLRenderTarget,
64
- WebGLRenderer: WebGLRenderer,
65
- WebGLRendererParameters: WebGLRendererParameters,
66
- loadInspector: loadInspector
67
- }, [three_webgpu]);
68
-
69
- //* Utility Types ==============================
70
-
71
- type NonFunctionKeys<P> = { [K in keyof P]-?: P[K] extends Function ? never : K }[keyof P]
72
- type Overwrite<P, O> = Omit<P, NonFunctionKeys<O>> & O
73
- type Properties<T> = Pick<T, NonFunctionKeys<T>>
74
- type Mutable<P> = { -readonly [K in keyof P]: P[K] }
75
- type IsOptional<T> = undefined extends T ? true : false
76
- type IsAllOptional<T extends any[]> = T extends [infer First, ...infer Rest]
77
- ? IsOptional<First> extends true
78
- ? IsAllOptional<Rest>
79
- : false
80
- : true
81
-
82
- //* Camera Types ==============================
83
-
84
- type ThreeCamera = (THREE$1.OrthographicCamera | THREE$1.PerspectiveCamera) & { manual?: boolean }
85
-
86
- //* Act Type ==============================
87
-
88
- type Act = <T = any>(cb: () => Promise<T>) => Promise<T>
89
-
90
- //* Bridge & Block Types ==============================
91
-
92
- type Bridge = React$1.FC<{ children?: React$1.ReactNode }>
93
-
94
- type SetBlock = false | Promise<null> | null
95
- type UnblockProps = { set: React$1.Dispatch<React$1.SetStateAction<SetBlock>>; children: React$1.ReactNode }
96
-
97
- //* Object Map Type ==============================
98
-
99
- /* Original version
100
- export interface ObjectMap {
101
- nodes: { [name: string]: THREE.Object3D }
102
- materials: { [name: string]: THREE.Material }
103
- meshes: { [name: string]: THREE.Mesh }
104
- }
105
- */
106
- /* This version is an expansion found in a PR by itsdouges that seems abandoned but looks useful.
107
- It allows expansion but falls back to the original shape. (deleted due to stale, but If it doesnt conflict
108
- I will keep the use here)
109
- https://github.com/pmndrs/react-three-fiber/commits/generic-object-map/
110
- His description is:
111
- The object map type is now generic and can optionally declare the available properties for nodes, materials, and meshes.
112
- */
113
- interface ObjectMap<
114
- T extends { nodes?: string; materials?: string; meshes?: string } = {
115
- nodes: string
116
- materials: string
117
- meshes: string
118
- },
119
- > {
120
- nodes: Record<T['nodes'] extends string ? T['nodes'] : string, THREE$1.Object3D>
121
- materials: Record<T['materials'] extends string ? T['materials'] : string, THREE$1.Material>
122
- meshes: Record<T['meshes'] extends string ? T['meshes'] : string, THREE$1.Mesh>
123
- }
124
-
125
- //* Equality Config ==============================
126
-
127
- interface EquConfig {
128
- /** Compare arrays by reference equality a === b (default), or by shallow equality */
129
- arrays?: 'reference' | 'shallow'
130
- /** Compare objects by reference equality a === b (default), or by shallow equality */
131
- objects?: 'reference' | 'shallow'
132
- /** If true the keys in both a and b must match 1:1 (default), if false a's keys must intersect b's */
133
- strict?: boolean
134
- }
135
-
136
- //* Disposable Type ==============================
137
-
138
- interface Disposable {
139
- type?: string
140
- dispose?: () => void
141
- }
142
-
143
- //* Event-related Types =====================================
144
-
145
- interface Intersection extends THREE$1.Intersection {
146
- /** The event source (the object which registered the handler) */
147
- eventObject: THREE$1.Object3D
148
- }
149
-
150
- type Camera = THREE$1.OrthographicCamera | THREE$1.PerspectiveCamera
151
-
152
- interface IntersectionEvent<TSourceEvent> extends Intersection {
153
- /** The event source (the object which registered the handler) */
154
- eventObject: THREE$1.Object3D
155
- /** An array of intersections */
156
- intersections: Intersection[]
157
- /** vec3.set(pointer.x, pointer.y, 0).unproject(camera) */
158
- unprojectedPoint: THREE$1.Vector3
159
- /** Normalized event coordinates */
160
- pointer: THREE$1.Vector2
161
- /** pointerId of the original event for multiple pointer events */
162
- pointerId: number
163
- /** Delta between first click and this event */
164
- delta: number
165
- /** The ray that pierced it */
166
- ray: THREE$1.Ray
167
- /** The camera that was used by the raycaster */
168
- camera: Camera
169
- /** stopPropagation will stop underlying handlers from firing */
170
- stopPropagation: () => void
171
- /** The original host event */
172
- nativeEvent: TSourceEvent
173
- /** If the event was stopped by calling stopPropagation */
174
- stopped: boolean
175
- }
176
-
177
- type ThreeEvent<TEvent> = IntersectionEvent<TEvent> & Properties<TEvent>
178
- type DomEvent = PointerEvent | MouseEvent | WheelEvent
179
-
180
- /** DOM event handlers registered on the canvas element */
181
- interface Events {
182
- onClick: EventListener
183
- onContextMenu: EventListener
184
- onDoubleClick: EventListener
185
- onWheel: EventListener
186
- onPointerDown: EventListener
187
- onPointerUp: EventListener
188
- onPointerLeave: EventListener
189
- onPointerMove: EventListener
190
- onPointerCancel: EventListener
191
- onLostPointerCapture: EventListener
192
- onDragEnter: EventListener
193
- onDragLeave: EventListener
194
- onDragOver: EventListener
195
- onDrop: EventListener
196
- }
197
-
198
- /** Event handlers that can be attached to R3F objects (meshes, groups, etc.) */
199
- interface EventHandlers {
200
- onClick?: (event: ThreeEvent<MouseEvent>) => void
201
- onContextMenu?: (event: ThreeEvent<MouseEvent>) => void
202
- onDoubleClick?: (event: ThreeEvent<MouseEvent>) => void
203
- /** Fires continuously while dragging over the object */
204
- onDragOver?: (event: ThreeEvent<DragEvent>) => void
205
- /** Fires once when drag enters the object */
206
- onDragOverEnter?: (event: ThreeEvent<DragEvent>) => void
207
- /** Fires once when drag leaves the object */
208
- onDragOverLeave?: (event: ThreeEvent<DragEvent>) => void
209
- /** Fires when drag misses this object (for objects that have drag handlers) */
210
- onDragOverMissed?: (event: DragEvent) => void
211
- /** Fires when a drop occurs on this object */
212
- onDrop?: (event: ThreeEvent<DragEvent>) => void
213
- /** Fires when a drop misses this object (for objects that have drop handlers) */
214
- onDropMissed?: (event: DragEvent) => void
215
- onPointerUp?: (event: ThreeEvent<PointerEvent>) => void
216
- onPointerDown?: (event: ThreeEvent<PointerEvent>) => void
217
- onPointerOver?: (event: ThreeEvent<PointerEvent>) => void
218
- onPointerOut?: (event: ThreeEvent<PointerEvent>) => void
219
- onPointerEnter?: (event: ThreeEvent<PointerEvent>) => void
220
- onPointerLeave?: (event: ThreeEvent<PointerEvent>) => void
221
- onPointerMove?: (event: ThreeEvent<PointerEvent>) => void
222
- onPointerMissed?: (event: MouseEvent) => void
223
- onPointerCancel?: (event: ThreeEvent<PointerEvent>) => void
224
- onWheel?: (event: ThreeEvent<WheelEvent>) => void
225
- onLostPointerCapture?: (event: ThreeEvent<PointerEvent>) => void
226
-
227
- //* Visibility Events --------------------------------
228
- /** Fires when object enters/exits camera frustum. Receives true when in view, false when out. */
229
- onFramed?: (inView: boolean) => void
230
- /** Fires when object occlusion state changes (WebGPU only, requires occlusionTest=true on object) */
231
- onOccluded?: (occluded: boolean) => void
232
- /** Fires when combined visibility changes (frustum + occlusion + visible prop) */
233
- onVisible?: (visible: boolean) => void
234
- }
235
-
236
- type FilterFunction = (items: THREE$1.Intersection[], state: RootState) => THREE$1.Intersection[]
237
- type ComputeFunction = (event: DomEvent, root: RootState, previous?: RootState) => void
238
-
239
- /** Configuration for XR pointer registration (controllers/hands) */
240
- interface XRPointerConfig {
241
- /** Ray origin (updated each frame by XR system) */
242
- ray: THREE$1.Ray
243
- /** Optional: custom compute function for this pointer */
244
- compute?: (state: RootState) => void
245
- /** Pointer type identifier */
246
- type: 'controller' | 'hand' | 'gaze'
247
- /** Which hand (for controller/hand types) */
248
- handedness?: 'left' | 'right'
249
- }
250
-
251
- interface EventManager<TTarget> {
252
- /** Determines if the event layer is active */
253
- enabled: boolean
254
- /** Event layer priority, higher prioritized layers come first and may stop(-propagate) lower layer */
255
- priority: number
256
- /** The compute function needs to set up the raycaster and an xy- pointer */
257
- compute?: ComputeFunction
258
- /** The filter can re-order or re-structure the intersections */
259
- filter?: FilterFunction
260
- /** The target node the event layer is tied to */
261
- connected?: TTarget
262
- /** All the pointer event handlers through which the host forwards native events */
263
- handlers?: Events
264
- /** Allows re-connecting to another target */
265
- connect?: (target: TTarget) => void
266
- /** Removes all existing events handlers from the target */
267
- disconnect?: () => void
268
- /** Triggers a onPointerMove with the last known event. This can be useful to enable raycasting without
269
- * explicit user interaction, for instance when the camera moves a hoverable object underneath the cursor.
270
- * @param pointerId - Optional pointer ID to update specific pointer only
271
- */
272
- update?: (pointerId?: number) => void
273
- /** Defer pointer move raycasting to frame start (default: true) */
274
- frameTimedRaycasts?: boolean
275
- /** Always fire raycaster immediately on scroll events (default: true) */
276
- alwaysFireOnScroll?: boolean
277
- /** Automatically re-raycast every frame to detect hover changes from moving objects/camera (default: false) */
278
- updateOnFrame?: boolean
279
- /** Flush deferred pointer raycasts. Called by scheduler at frame start (input phase). */
280
- flush?: () => void
281
- /** Register an XR pointer (controller/hand). Returns assigned pointerId */
282
- registerPointer?: (config: XRPointerConfig) => number
283
- /** Unregister an XR pointer */
284
- unregisterPointer?: (pointerId: number) => void
285
- }
286
-
287
- interface PointerCaptureTarget {
288
- intersection: Intersection
289
- target: Element
290
- }
291
-
292
- //* Visibility System Types =====================================
293
-
294
- /** Entry in the visibility registry for tracking object visibility state */
295
- interface VisibilityEntry {
296
- object: THREE$1.Object3D
297
- handlers: Pick<EventHandlers, 'onFramed' | 'onOccluded' | 'onVisible'>
298
- lastFramedState: boolean | null
299
- lastOccludedState: boolean | null
300
- lastVisibleState: boolean | null
4
+ import { M as MutableOrReadonlyParameters$1, a as MathRepresentation$1, V as VectorRepresentation$1, b as MathTypes$1, c as MathType$1, d as MathProps$1, e as Vector2$1, f as Vector3$1, g as Vector4$1, C as Color$1, L as Layers$1, Q as Quaternion$1, E as Euler$1, h as Matrix3$1, i as Matrix4$1, R as RaycastableRepresentation$1, j as EventProps$1, G as GeometryTransformProps$1, k as GeometryProps$1, T as TSLNodeInput$1, N as NodeProps$1, l as ReactProps$1, m as ConstructorRepresentation, n as ElementProps$1, o as ThreeElement$1, p as ThreeToJSXElements$1, O as Object3DMethod$1, q as ThreeElementsOf$1, r as ElementOf$1, v as RenderTargetOptions, u as ReconcilerRoot, s as CanvasProps } from './shared/fiber.Ddgoyqql.mjs';
5
+ export { a7 as Args, a8 as ArgsProp, a4 as AttachFnType, a5 as AttachType, ae as BackgroundConfig, af as BackgroundProp, I as BaseRendererProps, b8 as Block, $ as CameraProps, Y as CanvasSchedulerConfig, a6 as Catalogue, P as ColorManagementConfig, S as DefaultGLProps, X as DefaultRendererProps, aO as DisposeOptions, ay as Environment, aw as EnvironmentCube, aR as EnvironmentLoaderProps, av as EnvironmentMap, ax as EnvironmentPortal, au as EnvironmentProps, b9 as ErrorBoundary, am as Extensions, bD as FROM_REF, a2 as FiberRoot, bE as FromRefMarker, U as GLProps, ai as GLTFLike, ad as GlobalEffectType, ac as GlobalRenderCallback, ab as HostConfig, ak as InferLoadResult, a1 as InjectState, ag as InputLike, aa as Instance, a9 as InstanceProps, aH as IsObject, x as LegacyInternalState, y as LegacyRenderer, t as LegacyRootState, aj as LoaderInstance, ah as LoaderLike, al as LoaderResult, aI as MappedTextureType, bH as ONCE, H as OffscreenCanvas, bJ as OnceValue, b2 as Portal, aA as PresetsType, an as PrimaryCanvasEntry, ba as REACT_INTERNAL_PROPS, bi as RESERVED_PROPS, a0 as RenderProps, K as Renderer, Z as RendererConfigExtended, J as RendererFactory, _ as RendererProps, a3 as Root, aL as Texture, aM as TextureInput, aN as TextureResult, aJ as UseTextureOptions, aP as UseTexturesReturn, z as WebGLDefaultProps, W as WebGLProps, A as WebGLShadowConfig, a$ as _roots, aU as addAfterEffect, aT as addEffect, aV as addTail, aX as advance, bn as applyProps, bk as attach, bd as buildGraph, bo as calculateDpr, aD as createEvents, w as createPointerEvents, b1 as createPortal, b4 as createStore, bl as detach, bm as diffProps, be as dispose, w as events, aY as extend, bb as findInitialRoot, b3 as flushSync, bF as fromRef, bf as getInstanceProps, ap as getPrimary, at as getPrimaryIds, bc as getRootState, B as getThree, bp as getUuidPrefix, bC as hasConstructor, ar as hasPrimary, D as hasThree, aW as invalidate, bh as invalidateInstance, bs as is, bv as isColorRepresentation, bB as isCopyable, bG as isFromRef, by as isLayers, bw as isObject3D, bK as isOnce, bt as isOrthographicCamera, bu as isRef, a_ as isRenderer, bx as isTexture, bz as isUniform, bA as isVectorLike, bI as once, bg as prepare, az as presetsObj, aZ as reconciler, ao as registerPrimary, aC as removeInteractivity, bj as resolve, aB as swapInteractivity, b0 as unmountComponentAtNode, as as unregisterPrimary, bq as updateCamera, br as updateFrustum, b7 as useBridge, aS as useEnvironment, aF as useGraph, aE as useInstanceHandle, b5 as useIsomorphicLayoutEffect, aG as useLoader, b6 as useMutableCallback, aK as useTexture, aQ as useTextures, aq as waitForPrimary, F as whenThree } from './shared/fiber.Ddgoyqql.mjs';
6
+ import { a0 as R3FRenderTarget } from './shared/fiber.Bw8YnGg5.mjs';
7
+ export { A as Act, B as Bridge, C as Camera, i as ComputeFunction, w as Disposable, f as DomEvent, D as Dpr, v as EquConfig, g as EventHandlers, k as EventManager, E as Events, h as FilterFunction, $ as ForRegisteredRenderer, G as FrameCallback, z as FrameNextCallback, x as FrameNextState, y as FrameState, F as Frameloop, a5 as InternalState, I as Intersection, e as IntersectionEvent, p as IsAllOptional, o as IsOptional, M as Mutable, N as NonFunctionKeys, u as ObjectMap, K as OcclusionSupport, O as Overwrite, c as Performance, l as PointerCaptureTarget, P as PointerState, n as Properties, a4 as R3FRenderer, a1 as R3FRendererSupport, Z as Register, _ as RegisteredRenderer, b as RenderCallback, Y as RendererProvider, Q as RendererSupport, R as RootExtension, a6 as RootState, d as RootStore, t as SetBlock, a as Size, S as Subscription, q as ThreeCamera, J as ThreeCore, T as ThreeEvent, H as ThreeNamespace, U as UnblockProps, V as Viewport, m as VisibilityEntry, W as WebGLSupport, L as WebGPUSupport, X as XRManager, j as XRPointerConfig, a3 as context, r as registerRootExtension, s as setRenderOverride, a2 as useStore, a7 as useThree } from './shared/fiber.Bw8YnGg5.mjs';
8
+ export { AddPhaseOptions, FrameControls, FrameNextControls, FrameTimingState, RootOptions, Scheduler, SchedulerApi, UseFrameNextOptions, UseFrameOptions, getScheduler } from '@pmndrs/scheduler';
9
+ export { useFrame } from './extension.mjs';
10
+ import 'react';
11
+ import 'react-use-measure';
12
+ import 'zustand';
13
+ import 'zustand/traditional';
14
+ import 'three/tsl';
15
+
16
+ /**
17
+ * The `ReactThreeFiber` namespace of the default entry: the shared element types plus this entry's JSX map.
18
+ *
19
+ * Explicit aliases, not `export type *`: rollup-dts otherwise re-exports the types as namespace values
20
+ * and the built declaration fails to compile for consumers.
21
+ */
22
+
23
+
24
+ type MutableOrReadonlyParameters<T extends (...args: any) => any> = MutableOrReadonlyParameters$1<T>
25
+ type MathRepresentation = MathRepresentation$1
26
+ type VectorRepresentation = VectorRepresentation$1
27
+ type MathTypes = MathTypes$1
28
+ type MathType<T extends MathTypes$1> = MathType$1<T>
29
+ type MathProps<P> = MathProps$1<P>
30
+ type Vector2 = Vector2$1
31
+ type Vector3 = Vector3$1
32
+ type Vector4 = Vector4$1
33
+ type Color = Color$1
34
+ type Layers = Layers$1
35
+ type Quaternion = Quaternion$1
36
+ type Euler = Euler$1
37
+ type Matrix3 = Matrix3$1
38
+ type Matrix4 = Matrix4$1
39
+ type RaycastableRepresentation = RaycastableRepresentation$1
40
+ type EventProps<P> = EventProps$1<P>
41
+ type GeometryTransformProps = GeometryTransformProps$1
42
+ type GeometryProps<P> = GeometryProps$1<P>
43
+ type TSLNodeInput = TSLNodeInput$1
44
+ type NodeProps<P> = NodeProps$1<P>
45
+ type ReactProps<P> = ReactProps$1<P>
46
+ type ElementProps<T extends ConstructorRepresentation, P = InstanceType<T>> = ElementProps$1<T, P>
47
+ type ThreeElement<T extends ConstructorRepresentation> = ThreeElement$1<T>
48
+ type ThreeToJSXElements<T extends Record<string, any>> = ThreeToJSXElements$1<T>
49
+ type Object3DMethod = Object3DMethod$1
50
+ type ThreeElementsOf<T extends Record<string, any>> = ThreeElementsOf$1<T>
51
+ type ElementOf<E, K extends string> = ElementOf$1<E, K>
52
+
53
+ type default_d_Color = Color;
54
+ type default_d_ElementOf<E, K extends string> = ElementOf<E, K>;
55
+ type default_d_ElementProps<T extends ConstructorRepresentation, P = InstanceType<T>> = ElementProps<T, P>;
56
+ type default_d_Euler = Euler;
57
+ type default_d_EventProps<P> = EventProps<P>;
58
+ type default_d_GeometryProps<P> = GeometryProps<P>;
59
+ type default_d_GeometryTransformProps = GeometryTransformProps;
60
+ type default_d_Layers = Layers;
61
+ type default_d_MathProps<P> = MathProps<P>;
62
+ type default_d_MathRepresentation = MathRepresentation;
63
+ type default_d_MathType<T extends MathTypes$1> = MathType<T>;
64
+ type default_d_MathTypes = MathTypes;
65
+ type default_d_Matrix3 = Matrix3;
66
+ type default_d_Matrix4 = Matrix4;
67
+ type default_d_MutableOrReadonlyParameters<T extends (...args: any) => any> = MutableOrReadonlyParameters<T>;
68
+ type default_d_NodeProps<P> = NodeProps<P>;
69
+ type default_d_Object3DMethod = Object3DMethod;
70
+ type default_d_Quaternion = Quaternion;
71
+ type default_d_RaycastableRepresentation = RaycastableRepresentation;
72
+ type default_d_ReactProps<P> = ReactProps<P>;
73
+ type default_d_TSLNodeInput = TSLNodeInput;
74
+ type default_d_ThreeElement<T extends ConstructorRepresentation> = ThreeElement<T>;
75
+ type default_d_ThreeElements = ThreeElements;
76
+ type default_d_ThreeElementsOf<T extends Record<string, any>> = ThreeElementsOf<T>;
77
+ type default_d_ThreeExports = ThreeExports;
78
+ type default_d_ThreeToJSXElements<T extends Record<string, any>> = ThreeToJSXElements<T>;
79
+ type default_d_Vector2 = Vector2;
80
+ type default_d_Vector3 = Vector3;
81
+ type default_d_Vector4 = Vector4;
82
+ type default_d_VectorRepresentation = VectorRepresentation;
83
+ declare namespace default_d {
84
+ export type { default_d_Color as Color, default_d_ElementOf as ElementOf, default_d_ElementProps as ElementProps, default_d_Euler as Euler, default_d_EventProps as EventProps, default_d_GeometryProps as GeometryProps, default_d_GeometryTransformProps as GeometryTransformProps, default_d_Layers as Layers, default_d_MathProps as MathProps, default_d_MathRepresentation as MathRepresentation, default_d_MathType as MathType, default_d_MathTypes as MathTypes, default_d_Matrix3 as Matrix3, default_d_Matrix4 as Matrix4, default_d_MutableOrReadonlyParameters as MutableOrReadonlyParameters, default_d_NodeProps as NodeProps, default_d_Object3DMethod as Object3DMethod, default_d_Quaternion as Quaternion, default_d_RaycastableRepresentation as RaycastableRepresentation, default_d_ReactProps as ReactProps, default_d_TSLNodeInput as TSLNodeInput, default_d_ThreeElement as ThreeElement, default_d_ThreeElements as ThreeElements, default_d_ThreeElementsOf as ThreeElementsOf, default_d_ThreeExports as ThreeExports, default_d_ThreeToJSXElements as ThreeToJSXElements, default_d_Vector2 as Vector2, default_d_Vector3 as Vector3, default_d_Vector4 as Vector4, default_d_VectorRepresentation as VectorRepresentation };
301
85
  }
302
86
 
303
- //* Scheduler Types (useFrame) ==============================
304
- //
305
- // The generic, framework-agnostic scheduler types now live in @pmndrs/scheduler.
306
- // This file re-exports them and layers r3f's RootState-aware frame state on top,
307
- // so existing `#types` imports across the codebase keep resolving unchanged.
308
-
309
-
310
-
311
- // Frame State (r3f-specific) --------------------------------
312
-
313
- /**
314
- * State passed to useFrame callbacks (extends RootState with timing).
315
- */
316
- interface FrameNextState extends RootState, FrameTimingState {}
317
-
318
- /** Alias for FrameNextState */
319
- type FrameState = FrameNextState
320
-
321
- // Callback Types (r3f-specific) --------------------------------
322
-
323
- /**
324
- * Callback function for useFrame. Receives the full r3f RootState plus timing.
325
- */
326
- type FrameNextCallback = FrameCallback$1<RootState>
327
-
328
- /** Alias for FrameNextCallback */
329
- type FrameCallback = FrameNextCallback
330
-
331
- //* Buffer Types (useBuffers) ========================================
332
-
333
87
  /**
334
- * Buffer-like types for GPU compute and storage operations.
335
- * Includes raw CPU arrays, Three.js buffer attributes, and TSL buffer nodes.
88
+ * Creates a render target compatible with the current renderer.
336
89
  *
337
- * @example
338
- * ```tsx
339
- * const { positions, velocities } = useBuffers(() => ({
340
- * positions: instancedArray(count, 'vec3'), // StorageBufferNode
341
- * velocities: new Float32Array(count * 3), // TypedArray
342
- * }), 'particles')
343
- * ```
344
- */
345
- type BufferLike =
346
- | Float32Array
347
- | Uint32Array
348
- | Int32Array
349
- | Float64Array
350
- | Uint8Array
351
- | Int8Array
352
- | Uint16Array
353
- | Int16Array
354
- | THREE$1.BufferAttribute // Base class for all buffer attributes
355
- | Node // TSL buffer nodes (instancedArray, storage)
356
-
357
- /** Flat record of buffer-like values (no nested scopes) */
358
- type BufferRecord = Record<string, BufferLike>
359
-
360
- /**
361
- * Buffer store that can contain both root-level buffers and scoped buffer objects.
362
- * Structure: { positions: Float32Array, particles: { vel: StorageBufferNode } }
363
- */
364
- type BufferStore = Record<string, BufferLike | BufferRecord>
365
-
366
- //* Storage Types (useGPUStorage) ========================================
367
-
368
- /**
369
- * GPU storage types for texture-based storage operations.
370
- * Includes Three.js storage textures and TSL storage texture nodes.
90
+ * Both classes live in three's shared core; which one you get follows the renderer this root
91
+ * loaded: a `WebGLRenderTarget` on WebGL, a `RenderTarget` on WebGPU. The return type is the
92
+ * union unless the app registered a renderer (`Register`) or the entry decides it (`/legacy`,
93
+ * `/webgpu`).
371
94
  *
372
95
  * @example
373
96
  * ```tsx
374
- * const { heightMap } = useGPUStorage(() => ({
375
- * heightMap: new StorageTexture(512, 512),
376
- * }), 'terrain')
377
- * ```
378
- */
379
- type StorageLike =
380
- | StorageTexture // GPU storage texture
381
- | Data3DTexture // 3D texture (can be used as storage)
382
- | Node // TSL storage texture nodes (storageTexture)
383
-
384
- /** Flat record of storage-like values (no nested scopes) */
385
- type StorageRecord = Record<string, StorageLike>
386
-
387
- /**
388
- * Storage store that can contain both root-level storage and scoped storage objects.
389
- * Structure: { heightMap: StorageTexture, terrain: { normal: StorageTextureNode } }
390
- */
391
- type StorageStore = Record<string, StorageLike | StorageRecord>
392
-
393
- //* Renderer Types ========================================
394
-
395
- /** Default renderer type - union of WebGL and WebGPU renderers */
396
- type R3FRenderer = THREE$1.WebGLRenderer | WebGPURenderer
397
-
398
- //* Core Store Types ========================================
399
-
400
- type Subscription = {
401
- ref: React$1.RefObject<RenderCallback>
402
- priority: number
403
- store: RootStore
404
- }
405
-
406
- /** Per-pointer state for multi-touch and XR support */
407
- type PointerState = {
408
- /** Objects currently hovered by this pointer */
409
- hovered: Map<string, ThreeEvent<DomEvent>>
410
- /** Objects capturing this pointer */
411
- captured: Map<THREE$1.Object3D, PointerCaptureTarget>
412
- /** Initial click position [x, y] */
413
- initialClick: [x: number, y: number]
414
- /** Objects hit on initial click */
415
- initialHits: THREE$1.Object3D[]
416
- }
417
-
418
- type Dpr = number | [min: number, max: number]
419
-
420
- interface Size {
421
- width: number
422
- height: number
423
- top: number
424
- left: number
425
- }
426
-
427
- type Frameloop = 'always' | 'demand' | 'never'
428
-
429
- interface Viewport extends Size {
430
- /** The initial pixel ratio */
431
- initialDpr: number
432
- /** Current pixel ratio */
433
- dpr: number
434
- /** size.width / viewport.width */
435
- factor: number
436
- /** Camera distance */
437
- distance: number
438
- /** Camera aspect ratio: width / height */
439
- aspect: number
440
- }
441
-
442
- type RenderCallback = (state: RootState, delta: number, frame?: XRFrame) => void
443
-
444
- interface Performance {
445
- /** Current performance normal, between min and max */
446
- current: number
447
- /** How low the performance can go, between 0 and max */
448
- min: number
449
- /** How high the performance can go, between min and max */
450
- max: number
451
- /** Time until current returns to max in ms */
452
- debounce: number
453
- /** Sets current to min, puts the system in regression */
454
- regress: () => void
455
- }
456
-
457
- interface InternalState {
458
- interaction: THREE$1.Object3D[]
459
- subscribers: Subscription[]
460
- /** Per-pointer state (hover, capture, click tracking) - replaces hovered, capturedMap, initialClick, initialHits */
461
- pointerMap: Map<number, PointerState>
462
- /** Pointers needing raycast this frame (used with frameTimedRaycasts) */
463
- pointerDirty: Map<number, DomEvent>
464
- /** Last event received (for events.update() compatibility) */
465
- lastEvent: React$1.RefObject<DomEvent | null>
466
- /** @deprecated Use pointerMap.get(pointerId).hovered instead */
467
- hovered: Map<string, ThreeEvent<DomEvent>>
468
- /** @deprecated Use pointerMap.get(pointerId).captured instead */
469
- capturedMap: Map<number, Map<THREE$1.Object3D, PointerCaptureTarget>>
470
- /** @deprecated Use pointerMap.get(pointerId).initialClick instead */
471
- initialClick: [x: number, y: number]
472
- /** @deprecated Use pointerMap.get(pointerId).initialHits instead */
473
- initialHits: THREE$1.Object3D[]
474
- /** Visibility event registry (onFramed, onOccluded, onVisible) */
475
- visibilityRegistry: Map<string, VisibilityEntry>
476
- /** Whether occlusion queries are enabled (WebGPU only) */
477
- occlusionEnabled: boolean
478
- /** Reference to the invisible occlusion observer mesh */
479
- occlusionObserver: THREE$1.Mesh | null
480
- /** Cached occlusion results from render pass - keyed by Object3D */
481
- occlusionCache: Map<THREE$1.Object3D, boolean | null>
482
- /** Internal helper group for R3F system objects (occlusion observer, etc.) */
483
- helperGroup: THREE$1.Group | null
484
- active: boolean
485
- priority: number
486
- frames: number
487
- subscribe: (callback: React$1.RefObject<RenderCallback>, priority: number, store: RootStore) => () => void
488
- /** Internal renderer storage - use state.renderer or state.gl to access */
489
- actualRenderer: R3FRenderer
490
- /** Global scheduler reference (for useFrame hook) */
491
- scheduler: SchedulerApi | null
492
- /** This root's unique ID in the global scheduler */
493
- rootId?: string
494
- /** Function to unregister this root from the global scheduler */
495
- unregisterRoot?: () => void
496
- /** Container for child attachment (scene for root, original container for portals) */
497
- container?: THREE$1.Object3D
498
- /**
499
- * CanvasTarget for multi-canvas WebGPU rendering.
500
- * Created for all WebGPU canvases to support renderer sharing.
501
- * @see https://threejs.org/docs/#api/en/renderers/common/CanvasTarget
502
- */
503
- canvasTarget?: CanvasTarget
504
- /**
505
- * Set when this root's canvas target has been resized and the backend's cached render pass
506
- * descriptor (which holds a depth-stencil view built once per canvas) is therefore stale.
507
- *
508
- * Flushed by the canvas-target job in the `start` phase, which is the only place this root's
509
- * target is guaranteed to be the renderer's active one — `backend.updateSize()` operates on
510
- * whatever `getCanvasTarget()` returns, so calling it from the resize subscription would
511
- * invalidate some other canvas's descriptor instead.
512
- *
513
- * @see https://github.com/pmndrs/react-three-fiber/issues/3847
514
- */
515
- canvasTargetSizeDirty?: boolean
516
- /**
517
- * Whether multi-canvas rendering is active.
518
- * True when any canvas uses `renderer={{ primaryCanvas: 'id' }}` to share a renderer.
519
- * When true, setCanvasTarget is called before each render.
520
- */
521
- isMultiCanvas?: boolean
522
- /**
523
- * Whether this canvas is a secondary canvas sharing another's renderer.
524
- * True when `target` prop is used.
525
- */
526
- isSecondary?: boolean
527
- /**
528
- * The id of the primary canvas this secondary canvas targets.
529
- * Only set when isSecondary is true.
530
- */
531
- targetId?: string
532
- /**
533
- * Function to unregister this primary canvas from the registry.
534
- * Only set when this canvas has an `id` prop.
535
- */
536
- unregisterPrimary?: () => void
537
- /** Whether canvas dimensions are forced to even numbers */
538
- forceEven?: boolean
539
- }
540
-
541
- interface XRManager {
542
- connect: () => void
543
- disconnect: () => void
544
- }
545
-
546
- //* Root State Interface ====================================
547
-
548
- interface RootState {
549
- /** Set current state */
550
- set: StoreApi<RootState>['setState']
551
- /** Get current state */
552
- get: StoreApi<RootState>['getState']
553
- /**
554
- * Reference to the authoritative store for shared TSL resources (uniforms, nodes, etc).
555
- * - For primary/independent canvases: points to its own store (self-reference)
556
- * - For secondary canvases: points to the primary canvas's store
557
- *
558
- * Hooks like useNodes/useUniforms should read from primaryStore to ensure
559
- * consistent shared state across all canvases sharing a renderer.
560
- */
561
- primaryStore: RootStore
562
- /** @deprecated Use `renderer` instead. The instance of the renderer (typed as WebGLRenderer for backwards compat) */
563
- gl: THREE$1.WebGLRenderer
564
- /** The renderer instance - type depends on entry point (WebGPU, Legacy, or union for default) */
565
- renderer: R3FRenderer
566
- /** Inspector of the webGPU Renderer. Init in the canvas */
567
- inspector: any // Inspector type from three/webgpu
568
-
569
- /** Default camera */
570
- camera: ThreeCamera
571
- /** Camera frustum for visibility checks - auto-updated each frame when autoUpdateFrustum is true */
572
- frustum: THREE$1.Frustum
573
- /** Whether to automatically update the frustum each frame (default: true) */
574
- autoUpdateFrustum: boolean
575
- /** Default scene (may be overridden in portals to point to the portal container) */
576
- scene: THREE$1.Scene
577
- /** The actual root THREE.Scene - always points to the true scene, even inside portals */
578
- rootScene: THREE$1.Scene
579
- /** Default raycaster */
580
- raycaster: THREE$1.Raycaster
581
- /** Event layer interface, contains the event handler and the node they're connected to */
582
- events: EventManager<any>
583
- /** XR interface */
584
- xr: XRManager
585
- /** Currently used controls */
586
- controls: THREE$1.EventDispatcher | null
587
- /** Normalized event coordinates */
588
- pointer: THREE$1.Vector2
589
- /** @deprecated Normalized event coordinates, use "pointer" instead! */
590
- mouse: THREE$1.Vector2
591
- /** Color space assigned to 8-bit input textures (color maps). Most textures are authored in sRGB. */
592
- textureColorSpace: THREE$1.ColorSpace
593
- /** Render loop flags */
594
- frameloop: Frameloop
595
- performance: Performance
596
- /** Reactive pixel-size of the canvas */
597
- size: Size
598
- /** Reactive size of the viewport in threejs units */
599
- viewport: Viewport & {
600
- getCurrentViewport: (
601
- camera?: ThreeCamera,
602
- target?: THREE$1.Vector3 | Parameters<THREE$1.Vector3['set']>,
603
- size?: Size,
604
- ) => Omit<Viewport, 'dpr' | 'initialDpr'>
605
- }
606
- /** Flags the canvas for render, but doesn't render in itself */
607
- invalidate: (frames?: number, stackFrames?: boolean) => void
608
- /** Advance (render) one step */
609
- advance: (timestamp: number, runGlobalEffects?: boolean) => void
610
- /** Shortcut to setting the event layer */
611
- setEvents: (events: Partial<EventManager<any>>) => void
612
- /** Shortcut to manual sizing. No args resets to props/container. Single arg creates square. */
613
- setSize: (width?: number, height?: number, top?: number, left?: number) => void
614
- /** Shortcut to manual setting the pixel ratio */
615
- setDpr: (dpr: Dpr) => void
616
- /** Shortcut to setting frameloop flags. No args resets to 'always'. */
617
- setFrameloop: (frameloop?: Frameloop) => void
618
- /** Set error state to propagate to error boundary */
619
- setError: (error: Error | null) => void
620
- /** Current error state (null when no error) */
621
- error: Error | null
622
- /** Global TSL uniform nodes - root-level uniforms + scoped sub-objects. Use useUniforms() hook */
623
- uniforms: UniformStore
624
- /** Global TSL nodes - root-level nodes + scoped sub-objects. Use useNodes() hook */
625
- nodes: Record<string, any>
626
- /** Global TSL buffer nodes - root-level buffers + scoped sub-objects. Use useBuffers() hook */
627
- buffers: BufferStore
628
- /** Global GPU storage (textures, etc.) - root-level storage + scoped sub-objects. Use useGPUStorage() hook */
629
- gpuStorage: StorageStore
630
- /** Global Texture registry (key → Texture, usually keyed by URL) - use useTextures() hook for access + lifecycle */
631
- textures: Map<string, THREE$1.Texture>
632
- /** Internal: refcount per texture key, driven by mounted useTexture consumers (registry enrollment is on by default) */
633
- _textureRefs: Map<string, number>
634
- /** WebGPU RenderPipeline instance - use useRenderPipeline() hook */
635
- renderPipeline: ThreeRenderPipeline | null
636
- /** Global TSL pass nodes for render pipeline - use useRenderPipeline() hook */
637
- passes: Record<string, any>
638
- /** Internal version counter for HMR - incremented by rebuildNodes/rebuildUniforms to bust memoization */
639
- _hmrVersion: number
640
- /** Internal: whether setSize() has taken ownership of canvas dimensions */
641
- _sizeImperative: boolean
642
- /** Internal: stored size props from Canvas for reset functionality */
643
- _sizeProps: { width?: number; height?: number } | null
644
- /** When the canvas was clicked but nothing was hit */
645
- onPointerMissed?: (event: MouseEvent) => void
646
- /** When a dragover event has missed any target */
647
- onDragOverMissed?: (event: DragEvent) => void
648
- /** When a drop event has missed any target */
649
- onDropMissed?: (event: DragEvent) => void
650
- /** If this state model is layered (via createPortal) then this contains the previous layer */
651
- previousRoot?: RootStore
652
- /** Internals */
653
- internal: InternalState
654
- // flags for triggers
655
- // if we are using the webGl renderer, this will be true
656
- isLegacy: boolean
657
- // regardless of renderer, if the system supports webGpu, this will be true
658
- webGPUSupported: boolean
659
- //if we are on native
660
- isNative: boolean
661
- }
662
-
663
- type RootStore = UseBoundStoreWithEqualityFn<StoreApi<RootState>>
664
-
665
- //* Base Renderer Types =====================================
666
-
667
- // Shim for OffscreenCanvas since it was removed from DOM types
668
- interface OffscreenCanvas$1 extends EventTarget {}
669
-
670
- interface BaseRendererProps {
671
- canvas: HTMLCanvasElement | OffscreenCanvas$1
672
- powerPreference?: 'high-performance' | 'low-power' | 'default'
673
- antialias?: boolean
674
- alpha?: boolean
675
- }
676
-
677
- type RendererFactory<TRenderer, TParams> =
678
- | TRenderer
679
- | ((defaultProps: TParams) => TRenderer)
680
- | ((defaultProps: TParams) => Promise<TRenderer>)
681
-
682
- interface Renderer {
683
- render: (scene: THREE$1.Scene, camera: THREE$1.Camera) => any
684
- }
685
-
686
- //* Color Management Config ==============================
687
-
688
- /**
689
- * Color management configuration shared by both WebGL and WebGPU renderers.
690
- */
691
- interface ColorManagementConfig {
692
- /**
693
- * Color space assigned to 8-bit input textures (color maps).
694
- * Defaults to sRGB. Most textures are authored in sRGB.
695
- * @default THREE.SRGBColorSpace
696
- */
697
- textureColorSpace?: THREE$1.ColorSpace
698
- }
699
-
700
- //* WebGL Renderer Props ==============================
701
-
702
- type DefaultGLProps = Omit<THREE$1.WebGLRendererParameters, 'canvas'> & {
703
- canvas: HTMLCanvasElement | OffscreenCanvas$1
704
- }
705
-
706
- type GLProps =
707
- | Renderer
708
- | ((defaultProps: DefaultGLProps) => Renderer)
709
- | ((defaultProps: DefaultGLProps) => Promise<Renderer>)
710
- | (Partial<Properties<THREE$1.WebGLRenderer> | THREE$1.WebGLRendererParameters> & ColorManagementConfig)
711
-
712
- //* WebGPU Renderer Props ==============================
713
-
714
- type DefaultRendererProps = {
715
- canvas: HTMLCanvasElement | OffscreenCanvas$1
716
- [key: string]: any
717
- }
718
-
719
- /**
720
- * Canvas-level scheduler configuration.
721
- * Controls render timing relative to other canvases.
722
- */
723
- interface CanvasSchedulerConfig {
724
- /**
725
- * Render this canvas after another canvas completes.
726
- * Pass the `id` of another canvas.
727
- */
728
- after?: string
729
- /**
730
- * Limit this canvas's render rate (frames per second).
731
- */
732
- fps?: number
733
- }
734
-
735
- /**
736
- * Extended renderer configuration for multi-canvas support and color management.
737
- */
738
- interface RendererConfigExtended extends ColorManagementConfig {
739
- /** Share renderer from another canvas (WebGPU only) */
740
- primaryCanvas?: string
741
- /** Canvas-level scheduler options */
742
- scheduler?: CanvasSchedulerConfig
743
- }
744
-
745
- type RendererProps =
746
- | any // WebGPURenderer
747
- | ((defaultProps: DefaultRendererProps) => any)
748
- | ((defaultProps: DefaultRendererProps) => Promise<any>)
749
- | (Partial<Properties<any> | Record<string, any>> & RendererConfigExtended)
750
-
751
- //* Camera Props ==============================
752
-
753
- type CameraProps = (
754
- | THREE$1.Camera
755
- | Partial<
756
- ThreeElement<typeof THREE$1.Camera> &
757
- ThreeElement<typeof THREE$1.PerspectiveCamera> &
758
- ThreeElement<typeof THREE$1.OrthographicCamera>
759
- >
760
- ) & {
761
- /** Flags the camera as manual, putting projection into your own hands */
762
- manual?: boolean
763
- }
764
-
765
- //* Render Props ==============================
766
-
767
- interface RenderProps<TCanvas extends HTMLCanvasElement | OffscreenCanvas$1> {
768
- /**
769
- * Unique identifier for multi-canvas renderer sharing.
770
- * Makes this canvas targetable by other canvases using the `primaryCanvas` prop.
771
- * Also sets the HTML `id` attribute on the canvas element.
772
- * @example <Canvas id="main-viewer">...</Canvas>
773
- */
774
- id?: string
775
- /**
776
- * Share the renderer from another canvas instead of creating a new one.
777
- * Pass the `id` of the primary canvas to share its WebGPURenderer.
778
- * Only available with WebGPU (not legacy WebGL).
779
- *
780
- * Note: This is extracted from `renderer={{ primaryCanvas: "id" }}` by Canvas.
781
- * @internal
782
- */
783
- primaryCanvas?: string
784
- /**
785
- * Canvas-level scheduler options. Controls render timing relative to other canvases.
786
- *
787
- * Note: This is extracted from `renderer={{ scheduler: {...} }}` by Canvas.
788
- * @internal
789
- */
790
- scheduler?: CanvasSchedulerConfig
791
- /** A threejs renderer instance or props that go into the default renderer */
792
- gl?: GLProps
793
- /** A WebGPU renderer instance or props that go into the default renderer */
794
- renderer?: RendererProps
795
- /** Dimensions to fit the renderer to. Will measure canvas dimensions if omitted */
796
- size?: Size
797
- /**
798
- * Enables shadows (by default PCFsoft). Can accept `gl.shadowMap` options for fine-tuning,
799
- * but also strings: 'basic' | 'percentage' | 'soft' | 'variance'.
800
- * @see https://threejs.org/docs/#api/en/renderers/WebGLRenderer.shadowMap
801
- */
802
- shadows?: boolean | 'basic' | 'percentage' | 'soft' | 'variance' | Partial<THREE$1.WebGLShadowMap>
803
- /** Creates an orthographic camera */
804
- orthographic?: boolean
805
- /**
806
- * R3F's render mode. Set to `demand` to only render on state change or `never` to take control.
807
- * @see https://docs.pmnd.rs/react-three-fiber/advanced/scaling-performance#on-demand-rendering
808
- */
809
- frameloop?: Frameloop
810
- /**
811
- * R3F performance options for adaptive performance.
812
- * @see https://docs.pmnd.rs/react-three-fiber/advanced/scaling-performance#movement-regression
813
- */
814
- performance?: Partial<Omit<Performance, 'regress'>>
815
- /** Target pixel ratio. Can clamp between a range: `[min, max]` */
816
- dpr?: Dpr
817
- /** Props that go into the default raycaster */
818
- raycaster?: Partial<THREE$1.Raycaster>
819
- /** A `THREE.Scene` instance or props that go into the default scene */
820
- scene?: THREE$1.Scene | Partial<THREE$1.Scene>
821
- /** A `THREE.Camera` instance or props that go into the default camera */
822
- camera?: CameraProps
823
- /** An R3F event manager to manage elements' pointer events */
824
- events?: (store: RootStore) => EventManager<HTMLElement>
825
- /** Callback after the canvas has rendered (but not yet committed) */
826
- onCreated?: (state: RootState) => void
827
- /** Response for pointer clicks that have missed any target */
828
- onPointerMissed?: (event: MouseEvent) => void
829
- /** Response for dragover events that have missed any target */
830
- onDragOverMissed?: (event: DragEvent) => void
831
- /** Response for drop events that have missed any target */
832
- onDropMissed?: (event: DragEvent) => void
833
- /** Whether to automatically update the frustum each frame (default: true) */
834
- autoUpdateFrustum?: boolean
835
- /**
836
- * Enable WebGPU occlusion queries for onOccluded/onVisible events.
837
- * Auto-enabled when any object uses onOccluded or onVisible handlers.
838
- * Only works with WebGPU renderer - WebGL will log a warning.
839
- */
840
- occlusion?: boolean
841
- /** Internal: stored size props from Canvas for reset functionality */
842
- _sizeProps?: { width?: number; height?: number } | null
843
- /** Force canvas dimensions to even numbers (fixes Safari rendering issues with odd/fractional sizes) */
844
- forceEven?: boolean
845
- }
846
-
847
- //* Reconciler Root ==============================
848
-
849
- interface ReconcilerRoot<TCanvas extends HTMLCanvasElement | OffscreenCanvas$1> {
850
- configure: (config?: RenderProps<TCanvas>) => Promise<ReconcilerRoot<TCanvas>>
851
- render: (element: ReactNode) => RootStore
852
- unmount: () => void
853
- }
854
-
855
- //* Inject State ==============================
856
-
857
- type InjectState = Partial<
858
- Omit<RootState, 'events'> & {
859
- events?: {
860
- enabled?: boolean
861
- priority?: number
862
- compute?: ComputeFunction
863
- connected?: any
864
- }
865
- /**
866
- * When true (default), injects a THREE.Scene between container and children if container isn't already a Scene.
867
- * This ensures state.scene is always a real THREE.Scene with proper properties (background, environment, fog).
868
- * Set to false to use the container directly as scene (anti-pattern, but supported for edge cases).
869
- */
870
- injectScene?: boolean
871
- }
872
- >
873
-
874
- //* Reconciler Types ==============================
875
-
876
- // FiberRoot is an opaque internal React type - we define it locally
877
- // to avoid bundling @types/react-reconciler which causes absolute path issues
878
- type FiberRoot = any
879
-
880
- interface Root {
881
- fiber: FiberRoot
882
- store: RootStore
883
- }
884
-
885
- type AttachFnType<O = any> = (parent: any, self: O) => () => void
886
- type AttachType<O = any> = string | AttachFnType<O>
887
-
888
- type ConstructorRepresentation<T = any> = new (...args: any[]) => T
889
-
890
- interface Catalogue {
891
- [name: string]: ConstructorRepresentation
892
- }
893
-
894
- // TODO: handle constructor overloads
895
- // https://github.com/pmndrs/react-three-fiber/pull/2931
896
- // https://github.com/microsoft/TypeScript/issues/37079
897
- type Args<T> = T extends ConstructorRepresentation
898
- ? T extends typeof Color$1
899
- ? [r: number, g: number, b: number] | [color: ColorRepresentation]
900
- : ConstructorParameters<T>
901
- : any[]
902
-
903
- type ArgsProp<P> = P extends ConstructorRepresentation
904
- ? IsAllOptional<ConstructorParameters<P>> extends true
905
- ? { args?: Args<P> }
906
- : { args: Args<P> }
907
- : { args: unknown[] }
908
-
909
- type InstanceProps<T = any, P = any> = ArgsProp<P> & {
910
- object?: T
911
- dispose?: null
912
- attach?: AttachType<T>
913
- onUpdate?: (self: T) => void
914
- }
915
-
916
- interface Instance<O = any> {
917
- root: RootStore
918
- type: string
919
- parent: Instance | null
920
- children: Instance[]
921
- props: InstanceProps<O> & Record<string, unknown>
922
- object: O & { __r3f?: Instance<O> }
923
- eventCount: number
924
- handlers: Partial<EventHandlers>
925
- attach?: AttachType<O>
926
- previousAttach?: any
927
- isHidden: boolean
928
- /** Set of props that have been applied via once() */
929
- appliedOnce?: Set<string>
930
- }
931
-
932
- interface HostConfig {
933
- type: string
934
- props: Instance['props']
935
- container: RootStore
936
- instance: Instance
937
- textInstance: void
938
- suspenseInstance: Instance
939
- hydratableInstance: never
940
- formInstance: never
941
- publicInstance: Instance['object']
942
- hostContext: {}
943
- childSet: never
944
- timeoutHandle: number | undefined
945
- noTimeout: -1
946
- TransitionStatus: null
947
- }
948
- declare global {
949
- var IS_REACT_ACT_ENVIRONMENT: boolean | undefined
950
- }
951
-
952
- //* Loop Types ==============================
953
-
954
- type GlobalRenderCallback = (timestamp: number) => void
955
-
956
- type GlobalEffectType = 'before' | 'after' | 'tail'
957
-
958
- declare const presetsObj: {
959
- apartment: string;
960
- city: string;
961
- dawn: string;
962
- forest: string;
963
- lobby: string;
964
- night: string;
965
- park: string;
966
- studio: string;
967
- sunset: string;
968
- warehouse: string;
969
- };
970
- type PresetsType = keyof typeof presetsObj;
971
-
972
- //* Background Types ==============================
973
-
974
- /**
975
- * Expanded object form for background configuration.
976
- * Allows separate textures for background (visual backdrop) and environment (PBR lighting).
977
- */
978
- interface BackgroundConfig {
979
- /** HDRI preset name: 'apartment', 'city', 'dawn', 'forest', 'lobby', 'night', 'park', 'studio', 'sunset', 'warehouse' */
980
- preset?: PresetsType
981
- /** Files for cube texture (6 faces) or single HDR/EXR */
982
- files?: string | string[]
983
- /** Separate files for scene.background (visual backdrop) */
984
- backgroundMap?: string | string[]
985
- backgroundRotation?: Euler$1 | [number, number, number]
986
- backgroundBlurriness?: number
987
- backgroundIntensity?: number
988
- /** Separate files for scene.environment (PBR lighting/reflections) */
989
- envMap?: string | string[]
990
- environmentRotation?: Euler$1 | [number, number, number]
991
- environmentIntensity?: number
992
- path?: string
993
- extensions?: (loader: Loader) => void
994
- }
995
-
996
- /**
997
- * Background prop type for Canvas.
97
+ * // Use canvas size
98
+ * const fbo = useRenderTarget()
998
99
  *
999
- * String detection priority:
1000
- * 1. Preset - exact match against known presets (apartment, city, dawn, forest, lobby, night, park, studio, sunset, warehouse)
1001
- * 2. URL - starts with /, ./, ../, http://, https://, OR has image extension
1002
- * 3. Color - default fallback (CSS color names, hex values, rgb(), etc.)
100
+ * // Use canvas size with options
101
+ * const fbo = useRenderTarget({ samples: 4 })
1003
102
  *
1004
- * @example Color
1005
- * ```tsx
1006
- * <Canvas background="red" />
1007
- * <Canvas background="#ff0000" />
1008
- * <Canvas background={0xff0000} />
1009
- * ```
103
+ * // Square render target
104
+ * const fbo = useRenderTarget(512)
1010
105
  *
1011
- * @example Preset
1012
- * ```tsx
1013
- * <Canvas background="city" />
1014
- * ```
106
+ * // Square render target with options
107
+ * const fbo = useRenderTarget(512, { depthBuffer: true })
1015
108
  *
1016
- * @example URL
1017
- * ```tsx
1018
- * <Canvas background="/path/to/env.hdr" />
1019
- * <Canvas background="./sky.jpg" />
1020
- * ```
109
+ * // Explicit dimensions
110
+ * const fbo = useRenderTarget(512, 256)
1021
111
  *
1022
- * @example Object form
1023
- * ```tsx
1024
- * <Canvas background={{
1025
- * files: ['px.png', 'nx.png', 'py.png', 'ny.png', 'pz.png', 'nz.png'],
1026
- * backgroundMap: 'path/to/sky.jpg',
1027
- * envMap: 'path/to/lighting.hdr',
1028
- * backgroundBlurriness: 0.5,
1029
- * }} />
112
+ * // Explicit dimensions with options
113
+ * const fbo = useRenderTarget(512, 256, { samples: 4 })
1030
114
  * ```
1031
115
  */
1032
- type BackgroundProp =
1033
- | ColorRepresentation // "red", "#ff0000", 0xff0000
1034
- | string // URL or preset
1035
- | BackgroundConfig // Expanded object form
1036
-
1037
- //* Canvas Types ==============================
1038
-
1039
- interface CanvasProps
1040
- extends
1041
- Omit<RenderProps<HTMLCanvasElement>, 'size' | 'primaryCanvas' | 'scheduler'>,
1042
- React$1.HTMLAttributes<HTMLDivElement> {
1043
- children?: React$1.ReactNode
1044
- ref?: React$1.Ref<HTMLCanvasElement>
1045
- /** Canvas fallback content, similar to img's alt prop */
1046
- fallback?: React$1.ReactNode
1047
- /**
1048
- * Options to pass to useMeasure.
1049
- * @see https://github.com/pmndrs/react-use-measure#api
1050
- */
1051
- resize?: Options
1052
- /** The target where events are being subscribed to, default: the div that wraps canvas */
1053
- eventSource?: HTMLElement | React$1.RefObject<HTMLElement | null>
1054
- /** The event prefix that is cast into canvas pointer x/y events, default: "offset" */
1055
- eventPrefix?: 'offset' | 'client' | 'page' | 'layer' | 'screen'
1056
- /** Enable/disable automatic HMR refresh for TSL nodes and uniforms, default: true in dev */
1057
- hmr?: boolean
1058
- /** Canvas resolution width in pixels. If omitted, uses container width. */
1059
- width?: number
1060
- /** Canvas resolution height in pixels. If omitted, uses container height. */
1061
- height?: number
1062
- /** Force canvas dimensions to even numbers (fixes Safari rendering issues with odd/fractional sizes) */
1063
- forceEven?: boolean
1064
- /**
1065
- * Scene background configuration.
1066
- * Accepts colors, URLs, presets, or an expanded object for separate background/environment.
1067
- * @see BackgroundProp for full documentation and examples
1068
- */
1069
- background?: BackgroundProp
1070
- }
1071
-
1072
- //* Loader Types ==============================
1073
-
1074
- type InputLike = string | string[] | string[][] | Readonly<string | string[] | string[][]>
1075
-
1076
- // Define a loader-like interface that matches THREE.Loader's load signature
1077
- // This works for both generic and non-generic THREE.Loader instances
1078
- interface LoaderLike {
1079
- load(
1080
- url: InputLike,
1081
- onLoad?: (result: any) => void,
1082
- onProgress?: (event: ProgressEvent<EventTarget>) => void,
1083
- onError?: (error: unknown) => void,
1084
- ): any
1085
- }
1086
-
1087
- type GLTFLike = { scene: THREE$1.Object3D }
1088
-
1089
- type LoaderInstance<T extends LoaderLike | ConstructorRepresentation<LoaderLike>> =
1090
- T extends ConstructorRepresentation<LoaderLike> ? InstanceType<T> : T
1091
-
1092
- // Infer result type from the load method's callback parameter
1093
- type InferLoadResult<T> = T extends {
1094
- load(url: any, onLoad?: (result: infer R) => void, ...args: any[]): any
1095
- }
1096
- ? R
1097
- : T extends ConstructorRepresentation<any>
1098
- ? InstanceType<T> extends {
1099
- load(url: any, onLoad?: (result: infer R) => void, ...args: any[]): any
1100
- }
1101
- ? R
1102
- : any
1103
- : any
1104
-
1105
- type LoaderResult<T extends LoaderLike | ConstructorRepresentation<LoaderLike>> =
1106
- InferLoadResult<LoaderInstance<T>> extends infer R ? (R extends GLTFLike ? R & ObjectMap : R) : never
1107
-
1108
- type Extensions<T extends LoaderLike | ConstructorRepresentation<LoaderLike>> = (
1109
- loader: LoaderInstance<T>,
1110
- ) => void
1111
-
1112
- //* Renderer Props ========================================
1113
-
1114
- type WebGLDefaultProps = Omit<THREE$1.WebGLRendererParameters, 'canvas'> & BaseRendererProps
1115
-
1116
- type WebGLProps =
1117
- | RendererFactory<THREE$1.WebGLRenderer, WebGLDefaultProps>
1118
- | Partial<Properties<THREE$1.WebGLRenderer> | THREE$1.WebGLRendererParameters>
1119
-
1120
- interface WebGLShadowConfig {
1121
- shadows?: boolean | 'basic' | 'percentage' | 'soft' | 'variance' | Partial<THREE$1.WebGLShadowMap>
1122
- }
1123
-
1124
- //* Legacy-specific Types ========================================
1125
-
1126
- /** Legacy (WebGL) renderer type - re-exported as R3FRenderer from @react-three/fiber/legacy */
1127
- type LegacyRenderer = THREE$1.WebGLRenderer
1128
-
1129
- /** Legacy internal state with narrowed renderer type */
1130
- interface LegacyInternalState extends Omit<InternalState, 'actualRenderer'> {
1131
- actualRenderer: THREE$1.WebGLRenderer
1132
- }
116
+ declare function useRenderTarget(options?: RenderTargetOptions): R3FRenderTarget;
117
+ declare function useRenderTarget(size: number, options?: RenderTargetOptions): R3FRenderTarget;
118
+ declare function useRenderTarget(width: number, height: number, options?: RenderTargetOptions): R3FRenderTarget;
1133
119
 
120
+ declare const R3F_BUILD_LEGACY = true;
121
+ declare const R3F_BUILD_WEBGPU = true;
1134
122
  /**
1135
- * Legacy-specific RootState with narrowed renderer type.
1136
- * Automatically used when importing from `@react-three/fiber/legacy`.
1137
- *
1138
- * @example
1139
- * ```tsx
1140
- * import { useThree } from '@react-three/fiber/legacy'
1141
- *
1142
- * function MyComponent() {
1143
- * const { renderer } = useThree()
1144
- * // renderer is typed as THREE.WebGLRenderer
1145
- * renderer.shadowMap.enabled = true
1146
- * }
1147
- * ```
123
+ * Create a root on a canvas. Renders with WebGL unless `configure({ renderer })` asks for WebGPU.
1148
124
  */
1149
- interface LegacyRootState extends Omit<RootState, 'renderer' | 'internal'> {
1150
- /** The WebGL renderer instance */
1151
- renderer: THREE$1.WebGLRenderer
1152
- /** Internals with WebGL renderer */
1153
- internal: LegacyInternalState
1154
- }
1155
-
1156
- //* RenderTarget Types ==============================
1157
-
1158
-
1159
- type RenderTargetOptions = RenderTargetOptions$1
1160
-
1161
- //* Global Types ==============================
1162
-
1163
- declare global {
1164
- /**
1165
- * Uniform node type.
1166
- *
1167
- * This is three's own `UniformNode`, not a re-declaration of it. It previously was a
1168
- * hand-rolled `interface UniformNode<T> extends Node { value: T }`, which shadowed the real
1169
- * exported type globally — so R3F's ~58 references resolved to an approximation that was
1170
- * missing members three actually ships (`setName` among them) and had drifted to the wrong
1171
- * arity when three made `UniformNode` two-parameter.
1172
- *
1173
- * three's signature is `UniformNode<TNodeType, TValue>`. R3F only ever varies the value type,
1174
- * so the node type is fixed to `unknown` and the single parameter is kept for call-site
1175
- * ergonomics. The result is three's structural type, so members stay in sync with the
1176
- * installed three instead of needing to be mirrored by hand.
1177
- */
1178
- type UniformNode<T = unknown> = three_webgpu.UniformNode<unknown, T>
1179
-
1180
- /**
1181
- * ShaderCallable - the return type of Fn()
1182
- * A callable shader function node that can be invoked with parameters.
1183
- * The function returns a ShaderNodeObject when called.
1184
- *
1185
- * @example
1186
- * ```tsx
1187
- * // Define a shader function
1188
- * const blendColorFn = Fn(([color1, color2, factor]) => {
1189
- * return mix(color1, color2, factor)
1190
- * })
1191
- *
1192
- * // Type when retrieving from nodes store
1193
- * const { blendColorFn } = nodes as { blendColorFn: ShaderCallable }
1194
- *
1195
- * // Or with specific return type
1196
- * const { myFn } = nodes as { myFn: ShaderCallable<THREE.Node> }
1197
- * ```
1198
- */
1199
- type ShaderCallable<R extends Node = Node> = ((...params: unknown[]) => ShaderNodeObject<R>) & Node
1200
-
1201
- /**
1202
- * ShaderNodeRef - a ShaderNodeObject wrapper around a Node
1203
- * This is the common return type for TSL operations (add, mul, sin, etc.)
1204
- *
1205
- * @example
1206
- * ```tsx
1207
- * const { wobble } = nodes as { wobble: ShaderNodeRef }
1208
- * ```
1209
- */
1210
- type ShaderNodeRef<T extends Node = Node> = ShaderNodeObject<T>
1211
-
1212
- /**
1213
- * TSLNodeType - Union of all common TSL node types
1214
- * Used by ScopedStore to properly type node access from the store.
1215
- *
1216
- * Includes:
1217
- * - Node: base Three.js node type
1218
- * - ShaderCallable: function nodes created with Fn()
1219
- * - ShaderNodeObject: wrapped nodes from TSL operations (sin, mul, mix, etc.)
1220
- *
1221
- * @example
1222
- * ```tsx
1223
- * // In useLocalNodes, nodes are typed as TSLNodeType
1224
- * const { positionNode, blendColorFn } = useLocalNodes(({ nodes }) => ({
1225
- * positionNode: nodes.myPosition, // Works - Node is in union
1226
- * blendColorFn: nodes.myFn, // Works - ShaderCallable is in union
1227
- * }))
1228
- *
1229
- * // Can narrow with type guard or assertion when needed
1230
- * if (typeof blendColorFn === 'function') {
1231
- * blendColorFn(someColor, 0.5)
1232
- * }
1233
- * ```
1234
- */
1235
- type TSLNodeType = Node | ShaderCallable<Node> | ShaderNodeObject<Node>
1236
-
1237
- /** Flat record of uniform nodes (no nested scopes) */
1238
- type UniformRecord<T extends UniformNode = UniformNode> = Record<string, T>
1239
-
1240
- /**
1241
- * Uniform store that can contain both root-level uniforms and scoped uniform objects
1242
- * Used by state.uniforms which has structure like:
1243
- * { uTime: UniformNode, player: { uHealth: UniformNode }, enemy: { uHealth: UniformNode } }
1244
- */
1245
- type UniformStore = Record<string, UniformNode | UniformRecord>
1246
-
1247
- /**
1248
- * Helper to safely access a uniform node from the store.
1249
- * Use this when accessing state.uniforms to get proper typing.
1250
- * @example
1251
- * const uTime = uniforms.uTime as UniformNode<number>
1252
- * const uColor = uniforms.uColor as UniformNode<import('three/webgpu').Color>
1253
- */
1254
- type GetUniform<T = unknown> = UniformNode<T>
1255
-
1256
- /**
1257
- * Acceptable input values for useUniforms - raw values that get converted to UniformNodes
1258
- * Supports:
1259
- * - Primitives: number, string (color), boolean
1260
- * - Three.js types: Color, Vector2/3/4, Matrix3/4, Euler, Quaternion
1261
- * - Plain objects: { x, y, z, w } converted to vectors
1262
- * - TSL nodes: color(), vec3(), float() for type casting
1263
- * - UniformNode: existing uniforms (reused as-is)
1264
- */
1265
- type UniformValue =
1266
- | number
1267
- | string
1268
- | boolean
1269
- | three_webgpu.Color
1270
- | three_webgpu.Vector2
1271
- | three_webgpu.Vector3
1272
- | three_webgpu.Vector4
1273
- | three_webgpu.Matrix3
1274
- | three_webgpu.Matrix4
1275
- | three_webgpu.Euler
1276
- | three_webgpu.Quaternion
1277
- | { x: number; y?: number; z?: number; w?: number } // Plain objects converted to vectors
1278
- | { r: number; g: number; b: number; a?: number } // Plain objects converted to Color
1279
- | Node // TSL nodes like color(), vec3(), float() for type casting
1280
- | UniformNode
1281
-
1282
- /** Input record for useUniforms - accepts raw values or UniformNodes */
1283
- type UniformInputRecord = Record<string, UniformValue>
125
+ declare function createRoot<TCanvas extends HTMLCanvasElement | OffscreenCanvas>(canvas: TCanvas): ReconcilerRoot<TCanvas>;
126
+ /**
127
+ * A DOM canvas which accepts threejs elements as children. Renders with WebGL by default and with
128
+ * WebGPU when given the `renderer` prop.
129
+ * @see https://docs.pmnd.rs/react-three-fiber/api/canvas
130
+ */
131
+ declare function Canvas(props: CanvasProps): react_jsx_runtime.JSX.Element;
132
+ /** Three.js constructors available as JSX elements on this entry. */
133
+ type ThreeExports = typeof THREE & typeof ThreeWebGPU;
134
+ interface ThreeElements extends ThreeElementsOf$1<ThreeExports> {
1284
135
  }
1285
-
1286
- //* Module Augmentation ==============================
1287
-
1288
- declare module 'three/tsl' {
1289
- /**
1290
- * Fn with array parameter destructuring
1291
- * @example Fn(([uv, skew]) => { ... })
1292
- */
1293
- export function Fn<R extends Node = Node>(
1294
- jsFunc: (inputs: ShaderNodeObject<Node>[]) => ShaderNodeObject<R>,
1295
- ): ShaderCallable<R>
1296
-
1297
- /**
1298
- * Fn with object parameter destructuring
1299
- * @example Fn(({ color, intensity }) => { ... })
1300
- */
1301
- export function Fn<T extends Record<string, unknown>, R extends Node = Node>(
1302
- jsFunc: (inputs: T) => ShaderNodeObject<R>,
1303
- ): ShaderCallable<R>
1304
-
1305
- /**
1306
- * Fn with array params + layout
1307
- * @example Fn(([a, b]) => { ... }, { layout: [...] })
1308
- */
1309
- export function Fn<R extends Node = Node>(
1310
- jsFunc: (inputs: ShaderNodeObject<Node>[]) => ShaderNodeObject<R>,
1311
- layout: { layout?: unknown },
1312
- ): ShaderCallable<R>
1313
-
1314
- /**
1315
- * Fn with object params + layout
1316
- */
1317
- export function Fn<T extends Record<string, unknown>, R extends Node = Node>(
1318
- jsFunc: (inputs: T) => ShaderNodeObject<R>,
1319
- layout: { layout?: unknown },
1320
- ): ShaderCallable<R>
136
+ declare module 'react' {
137
+ namespace JSX {
138
+ interface IntrinsicElements extends ThreeElements {
139
+ }
140
+ }
1321
141
  }
1322
142
 
1323
- declare global {
1324
- /**
1325
- * three's own render pipeline type. Named here so the rest of R3F refers to three's shape
1326
- * rather than `any`. three r183 renamed `PostProcessing` to `RenderPipeline`; our peer floor
1327
- * is r185, so the new name is the only one.
1328
- */
1329
- type ThreeRenderPipeline = three_webgpu.RenderPipeline
1330
-
1331
- /** Pass record - stores TSL pass nodes for render pipeline */
1332
- type PassRecord = Record<string, any>
1333
-
1334
- /** Setup callback - runs first to configure MRT, create additional passes */
1335
- type RenderPipelineSetupCallback = (state: RootState) => PassRecord | void
1336
-
1337
- /** Main callback - runs second to configure outputNode, create effect passes */
1338
- type RenderPipelineMainCallback = (state: RootState) => PassRecord | void
1339
-
1340
- /** Return type for useRenderPipeline hook */
1341
- interface UseRenderPipelineReturn {
1342
- /** Current passes from state */
1343
- passes: PassRecord
1344
- /** RenderPipeline instance (null if not initialized) */
1345
- renderPipeline: ThreeRenderPipeline | null
1346
- /** Clear all passes from state */
1347
- clearPasses: () => void
1348
- /** Reset RenderPipeline entirely (clears PP + passes) */
1349
- reset: () => void
1350
- /** Re-run setup/main callbacks with current closure values */
1351
- rebuild: () => void
1352
- /** True when RenderPipeline is configured and ready */
1353
- isReady: boolean
1354
- }
1355
- }
1356
-
1357
- type MutableOrReadonlyParameters<T extends (...args: any) => any> = Parameters<T> | Readonly<Parameters<T>>
1358
-
1359
- interface MathRepresentation {
1360
- set(...args: number[]): any
1361
- }
1362
- interface VectorRepresentation extends MathRepresentation {
1363
- setScalar(value: number): any
1364
- }
1365
- type MathTypes = MathRepresentation | Euler$2 | Color$2
1366
-
1367
- type MathType<T extends MathTypes> = T extends Color$2
1368
- ? Args<typeof Color$2> | ColorRepresentation$1
1369
- : T extends VectorRepresentation | Layers$1 | Euler$2
1370
- ? T | MutableOrReadonlyParameters<T['set']> | number
1371
- : T | MutableOrReadonlyParameters<T['set']>
1372
-
1373
- type MathProps<P> = {
1374
- [K in keyof P as P[K] extends MathTypes ? K : never]: P[K] extends MathTypes ? MathType<P[K]> : never
1375
- }
1376
-
1377
- type Vector2 = MathType<Vector2$1>
1378
- type Vector3 = MathType<Vector3$1>
1379
- type Vector4 = MathType<Vector4$1>
1380
- type Color = MathType<Color$2>
1381
- type Layers = MathType<Layers$1>
1382
- type Quaternion = MathType<Quaternion$1>
1383
- type Euler = MathType<Euler$2>
1384
- type Matrix3 = MathType<Matrix3$1>
1385
- type Matrix4 = MathType<Matrix4$1>
1386
-
1387
- interface RaycastableRepresentation {
1388
- raycast(raycaster: Raycaster, intersects: Intersection$1[]): void
1389
- }
1390
- type EventProps<P> = P extends RaycastableRepresentation ? Partial<EventHandlers> : {}
1391
-
1392
- /**
1393
- * Props for geometry transform methods that can be called with `once()`.
1394
- * These methods modify the geometry in-place and only make sense to call once on mount.
1395
- *
1396
- * @example
1397
- * import { once } from '@react-three/fiber'
1398
- *
1399
- * <boxGeometry args={[1, 1, 1]} rotateX={once(Math.PI / 2)} />
1400
- * <planeGeometry args={[10, 10]} translate={once(0, 0, 5)} />
1401
- * <bufferGeometry applyMatrix4={once(matrix)} center={once()} />
1402
- */
1403
- interface GeometryTransformProps {
1404
- /** Rotate the geometry about the X axis (radians). Use with once(). */
1405
- rotateX?: number
1406
- /** Rotate the geometry about the Y axis (radians). Use with once(). */
1407
- rotateY?: number
1408
- /** Rotate the geometry about the Z axis (radians). Use with once(). */
1409
- rotateZ?: number
1410
- /** Translate the geometry (x, y, z). Use with once(). */
1411
- translate?: [x: number, y: number, z: number]
1412
- /** Scale the geometry (x, y, z). Use with once(). */
1413
- scale?: [x: number, y: number, z: number]
1414
- /** Center the geometry based on bounding box. Use with once(). */
1415
- center?: true
1416
- /** Apply a Matrix4 transformation. Use with once(). */
1417
- applyMatrix4?: Matrix4$1
1418
- /** Apply a Quaternion rotation. Use with once(). */
1419
- applyQuaternion?: Quaternion$1
1420
- }
1421
-
1422
- type GeometryProps<P> = P extends BufferGeometry ? GeometryTransformProps : {}
1423
-
1424
- /**
1425
- * Workaround for @types/three TSL node type issues.
1426
- * The Node base class has properties that subclasses (OperatorNode, ConstNode, etc.) don't inherit.
1427
- * This transforms `Node | null` properties to accept any object with node-like shape.
1428
- */
1429
- type TSLNodeInput = { nodeType?: string | null; uuid?: string } | null
1430
-
1431
- /**
1432
- * For node material properties (colorNode, positionNode, etc.), accept broader types
1433
- * since @types/three has broken inheritance for TSL node subclasses.
1434
- */
1435
- type NodeProps<P> = {
1436
- [K in keyof P as P[K] extends Node | null ? K : never]?: TSLNodeInput
1437
- }
1438
-
1439
- interface ReactProps<P> {
1440
- children?: React.ReactNode
1441
- ref?: React.Ref<P>
1442
- key?: React.Key
1443
- }
1444
-
1445
- type ElementProps<T extends ConstructorRepresentation, P = InstanceType<T>> = Partial<
1446
- Overwrite<P, MathProps<P> & ReactProps<P> & EventProps<P> & GeometryProps<P> & NodeProps<P>>
1447
- >
1448
-
1449
- type ThreeElement<T extends ConstructorRepresentation> = Mutable<
1450
- Overwrite<ElementProps<T>, Omit<InstanceProps<InstanceType<T>, T>, 'object'>>
1451
- >
1452
-
1453
- type ThreeToJSXElements<T extends Record<string, any>> = {
1454
- [K in keyof T & string as Uncapitalize<K>]: T[K] extends ConstructorRepresentation ? ThreeElement<T[K]> : never
1455
- }
1456
-
1457
- type ThreeExports = typeof THREE
1458
- type ThreeElementsImpl = ThreeToJSXElements<ThreeExports>
1459
-
1460
- interface ThreeElements extends Omit<ThreeElementsImpl, 'audio' | 'source' | 'line' | 'path'> {
1461
- primitive: Omit<ThreeElement<any>, 'args'> & { object: object }
1462
- // Conflicts with DOM types can be accessed through a three* prefix
1463
- threeAudio: ThreeElementsImpl['audio']
1464
- threeSource: ThreeElementsImpl['source']
1465
- threeLine: ThreeElementsImpl['line']
1466
- threePath: ThreeElementsImpl['path']
1467
- }
1468
-
1469
- declare module 'react' {
1470
- namespace JSX {
1471
- interface IntrinsicElements extends ThreeElements {}
1472
- }
1473
- }
1474
-
1475
- declare module 'react/jsx-runtime' {
1476
- namespace JSX {
1477
- interface IntrinsicElements extends ThreeElements {}
1478
- }
1479
- }
1480
-
1481
- declare module 'react/jsx-dev-runtime' {
1482
- namespace JSX {
1483
- interface IntrinsicElements extends ThreeElements {}
1484
- }
1485
- }
1486
-
1487
- type three_d_Color = Color;
1488
- type three_d_ElementProps<T extends ConstructorRepresentation, P = InstanceType<T>> = ElementProps<T, P>;
1489
- type three_d_Euler = Euler;
1490
- type three_d_EventProps<P> = EventProps<P>;
1491
- type three_d_GeometryProps<P> = GeometryProps<P>;
1492
- type three_d_GeometryTransformProps = GeometryTransformProps;
1493
- type three_d_Layers = Layers;
1494
- type three_d_MathProps<P> = MathProps<P>;
1495
- type three_d_MathRepresentation = MathRepresentation;
1496
- type three_d_MathType<T extends MathTypes> = MathType<T>;
1497
- type three_d_MathTypes = MathTypes;
1498
- type three_d_Matrix3 = Matrix3;
1499
- type three_d_Matrix4 = Matrix4;
1500
- type three_d_MutableOrReadonlyParameters<T extends (...args: any) => any> = MutableOrReadonlyParameters<T>;
1501
- type three_d_NodeProps<P> = NodeProps<P>;
1502
- type three_d_Quaternion = Quaternion;
1503
- type three_d_RaycastableRepresentation = RaycastableRepresentation;
1504
- type three_d_ReactProps<P> = ReactProps<P>;
1505
- type three_d_TSLNodeInput = TSLNodeInput;
1506
- type three_d_ThreeElement<T extends ConstructorRepresentation> = ThreeElement<T>;
1507
- type three_d_ThreeElements = ThreeElements;
1508
- type three_d_ThreeElementsImpl = ThreeElementsImpl;
1509
- type three_d_ThreeExports = ThreeExports;
1510
- type three_d_ThreeToJSXElements<T extends Record<string, any>> = ThreeToJSXElements<T>;
1511
- type three_d_Vector2 = Vector2;
1512
- type three_d_Vector3 = Vector3;
1513
- type three_d_Vector4 = Vector4;
1514
- type three_d_VectorRepresentation = VectorRepresentation;
1515
- declare namespace three_d {
1516
- export type { three_d_Color as Color, three_d_ElementProps as ElementProps, three_d_Euler as Euler, three_d_EventProps as EventProps, three_d_GeometryProps as GeometryProps, three_d_GeometryTransformProps as GeometryTransformProps, three_d_Layers as Layers, three_d_MathProps as MathProps, three_d_MathRepresentation as MathRepresentation, three_d_MathType as MathType, three_d_MathTypes as MathTypes, three_d_Matrix3 as Matrix3, three_d_Matrix4 as Matrix4, three_d_MutableOrReadonlyParameters as MutableOrReadonlyParameters, three_d_NodeProps as NodeProps, three_d_Quaternion as Quaternion, three_d_RaycastableRepresentation as RaycastableRepresentation, three_d_ReactProps as ReactProps, three_d_TSLNodeInput as TSLNodeInput, three_d_ThreeElement as ThreeElement, three_d_ThreeElements as ThreeElements, three_d_ThreeElementsImpl as ThreeElementsImpl, three_d_ThreeExports as ThreeExports, three_d_ThreeToJSXElements as ThreeToJSXElements, three_d_Vector2 as Vector2, three_d_Vector3 as Vector3, three_d_Vector4 as Vector4, three_d_VectorRepresentation as VectorRepresentation };
1517
- }
1518
-
1519
- /**
1520
- * @fileoverview Registry for primary canvases that can be targeted by secondary canvases
1521
- *
1522
- * Enables multi-canvas WebGPU rendering where multiple Canvas components share
1523
- * a single WebGPURenderer using Three.js CanvasTarget API.
1524
- *
1525
- * Primary canvas: Has `id` prop, creates its own renderer, registers here
1526
- * Secondary canvas: Has `renderer={{ primaryCanvas: 'id' }}`, shares primary's renderer via CanvasTarget
1527
- */
1528
-
1529
- interface PrimaryCanvasEntry {
1530
- /** The WebGPURenderer instance owned by this primary canvas */
1531
- renderer: WebGPURenderer;
1532
- /** The zustand store for this canvas */
1533
- store: RootStore;
1534
- }
1535
- /**
1536
- * Register a primary canvas that can be targeted by secondary canvases.
1537
- *
1538
- * @param id - Unique identifier for this primary canvas
1539
- * @param renderer - The WebGPURenderer owned by this canvas
1540
- * @param store - The zustand store for this canvas
1541
- * @returns Cleanup function to unregister on unmount
1542
- */
1543
- declare function registerPrimary(id: string, renderer: WebGPURenderer, store: RootStore): () => void;
1544
- /**
1545
- * Get a registered primary canvas by id.
1546
- *
1547
- * @param id - The id of the primary canvas to look up
1548
- * @returns The primary canvas entry or undefined if not found
1549
- */
1550
- declare function getPrimary(id: string): PrimaryCanvasEntry | undefined;
1551
- /**
1552
- * Wait for a primary canvas to be registered.
1553
- * Returns immediately if already registered, otherwise waits.
1554
- *
1555
- * @param id - The id of the primary canvas to wait for
1556
- * @param timeout - Optional timeout in ms (default: 5000)
1557
- * @returns Promise that resolves with the primary canvas entry
1558
- */
1559
- declare function waitForPrimary(id: string, timeout?: number): Promise<PrimaryCanvasEntry>;
1560
- /**
1561
- * Check if a primary canvas with the given id exists.
1562
- *
1563
- * @param id - The id to check
1564
- * @returns True if a primary canvas with this id is registered
1565
- */
1566
- declare function hasPrimary(id: string): boolean;
1567
- /**
1568
- * Unregister a primary canvas. Called on unmount.
1569
- *
1570
- * @param id - The id of the primary canvas to unregister
1571
- */
1572
- declare function unregisterPrimary(id: string): void;
1573
- /**
1574
- * Get all registered primary canvas ids. Useful for debugging.
1575
- */
1576
- declare function getPrimaryIds(): string[];
1577
-
1578
- type EnvironmentLoaderProps = {
1579
- files?: string | string[];
1580
- path?: string;
1581
- preset?: PresetsType;
1582
- extensions?: (loader: Loader$1) => void;
1583
- colorSpace?: ColorSpace;
1584
- };
1585
- /**
1586
- * Loads environment textures for reflections and lighting.
1587
- * Supports HDR files, presets, and cubemaps.
1588
- *
1589
- * @example Basic usage
1590
- * ```jsx
1591
- * const texture = useEnvironment({ preset: 'sunset' })
1592
- * ```
1593
- */
1594
- declare function useEnvironment({ files, path, preset, colorSpace, extensions, }?: Partial<EnvironmentLoaderProps>): Texture$1<unknown, THREE$1.TextureEventMap> | CubeTexture<unknown>;
1595
- declare namespace useEnvironment {
1596
- var preload: (preloadOptions?: EnvironmentLoaderPreloadOptions) => void;
1597
- var clear: (clearOptions?: EnvironmentLoaderClearOptions) => void;
1598
- }
1599
- /**
1600
- * Options accepted by `useEnvironment.preload`.
1601
- *
1602
- * `colorSpace` is deliberately omitted: preload only warms the loader cache, and colorSpace is
1603
- * applied to the texture by `useEnvironment()` at use time, per consumer. Accepting it here would
1604
- * advertise an option this function silently ignores.
1605
- *
1606
- * This previously read `Omit<…, 'encoding'>` — omitting a key that does not exist on
1607
- * `EnvironmentLoaderProps`, a leftover from three's pre-`colorSpace` `encoding` API. That made the
1608
- * type equivalent to the full props, so `colorSpace` was accepted and then dropped on the floor.
1609
- */
1610
- type EnvironmentLoaderPreloadOptions = Omit<EnvironmentLoaderProps, 'colorSpace'>;
1611
- type EnvironmentLoaderClearOptions = Pick<EnvironmentLoaderProps, 'files' | 'preset'>;
1612
-
1613
- /**
1614
- * Props for Environment component that sets up global cubemap for PBR materials and backgrounds.
1615
- *
1616
- * @property children - React children to render into custom environment portal
1617
- * @property frames - Number of frames to render the environment. Use 1 for static, Infinity for animated (default: 1)
1618
- * @property near - Near clipping plane for cube camera (default: 0.1)
1619
- * @property far - Far clipping plane for cube camera (default: 1000)
1620
- * @property resolution - Resolution of the cube render target (default: 256)
1621
- * @property background - Whether to set scene.background. Can be true, false, or "only" (which only sets background) (default: false)
1622
- *
1623
- * @property blur - @deprecated Use backgroundBlurriness instead
1624
- * @property backgroundBlurriness - Blur factor between 0 and 1 for background (default: 0, requires three.js 0.146+)
1625
- * @property backgroundIntensity - Intensity factor for background (default: 1, requires three.js 0.163+)
1626
- * @property backgroundRotation - Rotation for background as Euler angles (default: [0,0,0], requires three.js 0.163+)
1627
- * @property environmentIntensity - Intensity factor for environment lighting (default: 1, requires three.js 0.163+)
1628
- * @property environmentRotation - Rotation for environment as Euler angles (default: [0,0,0], requires three.js 0.163+)
1629
- *
1630
- * @property map - Pre-existing texture to use as environment map
1631
- * @property preset - HDRI Haven preset: 'apartment', 'city', 'dawn', 'forest', 'lobby', 'night', 'park', 'studio', 'sunset', 'warehouse'. Not for production use.
1632
- * @property scene - Custom THREE.Scene or ref to apply environment to (default: uses default scene)
1633
- * @property ground - Ground projection settings. Use true for defaults or object with:
1634
- * - height: Height of camera used to create env map (default: 15)
1635
- * - radius: Radius of the world (default: 60)
1636
- * - scale: Scale of backside projected sphere (default: 1000)
1637
- *
1638
- * Additional loader props:
1639
- * @property files - File path(s) for environment. Supports .hdr, .exr, gainmap .jpg/.webp, or array of 6 cube faces
1640
- * @property path - Base path for file loading
1641
- * @property extensions - Texture extensions override
1642
- */
1643
- type EnvironmentProps = {
1644
- children?: React$1.ReactNode;
1645
- frames?: number;
1646
- near?: number;
1647
- far?: number;
1648
- resolution?: number;
1649
- background?: boolean | 'only';
1650
- /** deprecated, use backgroundBlurriness */
1651
- blur?: number;
1652
- backgroundBlurriness?: number;
1653
- backgroundIntensity?: number;
1654
- backgroundRotation?: Euler;
1655
- environmentIntensity?: number;
1656
- environmentRotation?: Euler;
1657
- map?: Texture$1;
1658
- preset?: PresetsType;
1659
- scene?: Scene | React$1.RefObject<Scene>;
1660
- ground?: boolean | {
1661
- radius?: number;
1662
- height?: number;
1663
- scale?: number;
1664
- };
1665
- /** Solid color for background (alternative to files/preset) */
1666
- color?: ColorRepresentation$1;
1667
- /** Separate files for background (when different from environment files) */
1668
- backgroundFiles?: string | string[];
1669
- } & EnvironmentLoaderProps;
1670
- /**
1671
- * Internal component that applies a pre-existing texture as environment map.
1672
- * Sets scene.environment and optionally scene.background.
1673
- *
1674
- * @example
1675
- * ```jsx
1676
- * <CubeCamera>{(texture) => <EnvironmentMap map={texture} />}</CubeCamera>
1677
- * ```
1678
- */
1679
- declare function EnvironmentMap({ scene, background, map, ...config }: EnvironmentProps): null;
1680
- /**
1681
- * Internal component that loads environment textures from files or presets.
1682
- * Uses HDRLoader for .hdr, EXRLoader for .exr, UltraHDRLoader for .jpg/.jpeg HDR,
1683
- * GainMapLoader for gainmap .webp, or CubeTextureLoader for arrays of images.
1684
- *
1685
- * @example With preset
1686
- * ```jsx
1687
- * <EnvironmentCube preset="sunset" />
1688
- * ```
1689
- *
1690
- * @example From HDR file
1691
- * ```jsx
1692
- * <EnvironmentCube files="environment.hdr" />
1693
- * ```
1694
- *
1695
- * @example From gainmap (smallest footprint)
1696
- * ```jsx
1697
- * <EnvironmentCube files={['file.webp', 'file-gainmap.webp', 'file.json']} />
1698
- * ```
1699
- *
1700
- * @example From cube faces
1701
- * ```jsx
1702
- * <EnvironmentCube files={['px.png', 'nx.png', 'py.png', 'ny.png', 'pz.png', 'nz.png']} />
1703
- * ```
1704
- */
1705
- declare function EnvironmentCube({ background, scene, blur, backgroundBlurriness, backgroundIntensity, backgroundRotation, environmentIntensity, environmentRotation, ...rest }: EnvironmentProps): null;
1706
- /**
1707
- * Internal component that renders custom environment using a portal and cube camera.
1708
- * Renders children into an off-buffer and films with a cube camera to create environment map.
1709
- * Can be static (frames=1) or animated (frames=Infinity).
1710
- *
1711
- * @example Custom environment with sphere
1712
- * ```jsx
1713
- * <EnvironmentPortal background near={1} far={1000} resolution={256}>
1714
- * <mesh scale={100}>
1715
- * <sphereGeometry args={[1, 64, 64]} />
1716
- * <meshBasicMaterial map={texture} side={THREE.BackSide} />
1717
- * </mesh>
1718
- * </EnvironmentPortal>
1719
- * ```
1720
- *
1721
- * @example Animated environment
1722
- * ```jsx
1723
- * <EnvironmentPortal frames={Infinity} resolution={256}>
1724
- * <Float>
1725
- * <mesh />
1726
- * </Float>
1727
- * </EnvironmentPortal>
1728
- * ```
1729
- *
1730
- * @example Mixed with preset
1731
- * ```jsx
1732
- * <EnvironmentPortal preset="warehouse">
1733
- * <mesh />
1734
- * </EnvironmentPortal>
1735
- * ```
1736
- */
1737
- declare function EnvironmentPortal({ children, near, far, resolution, frames, map, background, blur, backgroundBlurriness, backgroundIntensity, backgroundRotation, environmentIntensity, environmentRotation, scene, files, path, preset, extensions, }: EnvironmentProps): react_jsx_runtime.JSX.Element;
1738
- declare module '@react-three/fiber' {
1739
- interface ThreeElements {
1740
- groundProjectedEnvImpl: ThreeElement<typeof GroundedSkybox>;
1741
- }
1742
- }
1743
- /**
1744
- * Sets up a global environment map for PBR materials and backgrounds.
1745
- * Affects scene.environment and optionally scene.background unless a custom scene is passed.
1746
- *
1747
- * Supports multiple input methods:
1748
- * - **Presets**: Selection of HDRI Haven assets (apartment, city, dawn, forest, lobby, night, park, studio, sunset, warehouse)
1749
- * - **Files**: HDR (.hdr), EXR (.exr), gainmap JPEG (.jpg), gainmap WebP (.webp), or cube faces (array of 6 images)
1750
- * - **Texture**: Pre-existing cube texture via `map` prop
1751
- * - **Custom Scene**: Render children into environment using portal and cube camera
1752
- * - **Ground Projection**: Project environment onto ground plane
1753
- *
1754
- * @remarks
1755
- * - Preset property is NOT meant for production and may fail (relies on CDNs)
1756
- * - Gainmap format has the smallest file footprint
1757
- * - Use `frames={Infinity}` for animated environments with low resolution for performance
1758
- * - Ground projection places models on the "ground" within the environment map
1759
- * - Supports self-hosting with @pmndrs/assets using dynamic imports
1760
- *
1761
- * @example Basic preset usage
1762
- * ```jsx
1763
- * <Environment preset="sunset" />
1764
- * ```
1765
- *
1766
- * @example From HDR file
1767
- * ```jsx
1768
- * <Environment files="/hdr/environment.hdr" />
1769
- * ```
1770
- *
1771
- * @example From gainmap (smallest footprint)
1772
- * ```jsx
1773
- * <Environment files={['file.webp', 'file-gainmap.webp', 'file.json']} />
1774
- * ```
1775
- *
1776
- * @example With self-hosted assets
1777
- * ```jsx
1778
- * import { suspend } from 'suspend-react'
1779
- * const city = import('@pmndrs/assets/hdri/city.exr').then(m => m.default)
1780
- *
1781
- * <Environment files={suspend(city)} />
1782
- * ```
1783
- *
1784
- * @example From existing texture
1785
- * ```jsx
1786
- * <CubeCamera>{(texture) => <Environment map={texture} />}</CubeCamera>
1787
- * ```
1788
- *
1789
- * @example Custom environment scene
1790
- * ```jsx
1791
- * <Environment background near={1} far={1000} resolution={256}>
1792
- * <mesh scale={100}>
1793
- * <sphereGeometry args={[1, 64, 64]} />
1794
- * <meshBasicMaterial map={texture} side={THREE.BackSide} />
1795
- * </mesh>
1796
- * </Environment>
1797
- * ```
1798
- *
1799
- * @example Animated environment
1800
- * ```jsx
1801
- * <Environment frames={Infinity} resolution={256}>
1802
- * <Float>
1803
- * <mesh />
1804
- * </Float>
1805
- * </Environment>
1806
- * ```
1807
- *
1808
- * @example Mixed custom scene with preset
1809
- * ```jsx
1810
- * <Environment background preset="warehouse">
1811
- * <mesh />
1812
- * </Environment>
1813
- * ```
1814
- *
1815
- * @example With ground projection
1816
- * ```jsx
1817
- * <Environment ground={{ height: 15, radius: 60 }} preset="city" />
1818
- * ```
1819
- *
1820
- * @example As background only
1821
- * ```jsx
1822
- * <Environment background="only" preset="sunset" />
1823
- * ```
1824
- *
1825
- * @example With rotation and intensity
1826
- * ```jsx
1827
- * <Environment
1828
- * background
1829
- * backgroundBlurriness={0.5}
1830
- * backgroundIntensity={0.8}
1831
- * backgroundRotation={[0, Math.PI / 2, 0]}
1832
- * environmentIntensity={1.2}
1833
- * environmentRotation={[0, Math.PI / 4, 0]}
1834
- * preset="studio"
1835
- * />
1836
- * ```
1837
- */
1838
- declare function Environment(props: EnvironmentProps): react_jsx_runtime.JSX.Element;
1839
-
1840
- /**
1841
- * Moves every trace of interactivity from one object to its replacement, for reconstruction.
1842
- *
1843
- * When `args` or a `primitive`'s `object` changes, R3F builds a new three object and keeps the same
1844
- * instance. Removing the old object from the interaction state and registering the new one from
1845
- * scratch makes events *work* again (#3778), but it forgets what was in flight: a pointer resting on
1846
- * the object fires a second `onPointerEnter` without ever having left, and an active pointer capture
1847
- * is dropped mid-drag. Rewriting the references instead keeps the interaction continuous across a
1848
- * swap the user never asked to see (#3744).
1849
- *
1850
- * Captures are re-keyed rather than released, so the DOM-level capture on `captureData.target` is
1851
- * left alone — releasing and re-acquiring it is precisely the glitch being avoided.
1852
- *
1853
- * Visibility handlers are deliberately not transferred: that registry is keyed by `object.uuid`, so
1854
- * the replacement re-registers itself through `applyProps`. The old entry is dropped here so it
1855
- * cannot outlive the object it described.
1856
- */
1857
- declare function swapInteractivity(store: RootStore, object: Object3D, newObject: Object3D): void;
1858
- declare function removeInteractivity(store: RootStore, object: Object3D): void;
1859
- declare function createEvents(store: RootStore): {
1860
- handlePointer: (name: string) => (event: DomEvent) => void;
1861
- flushDeferredPointers: () => void;
1862
- processDeferredPointer: (event: DomEvent, pointerId: number) => void;
1863
- };
1864
- /** Default R3F event manager for web */
1865
- declare function createPointerEvents(store: RootStore): EventManager<HTMLElement>;
1866
-
1867
- /**
1868
- * Gets or creates a memoized loader instance from a loader constructor or returns the loader if it's already an instance.
1869
- * This allows external code to access loader methods like abort().
1870
- */
1871
- declare function getLoader<L extends LoaderLike | ConstructorRepresentation<LoaderLike>>(Proto: L): L extends ConstructorRepresentation<infer T> ? T : L;
1872
- /**
1873
- * Synchronously loads and caches assets with a three loader.
1874
- *
1875
- * Note: this hook's caller must be wrapped with `React.Suspense`
1876
- * @see https://docs.pmnd.rs/react-three-fiber/api/hooks#useloader
1877
- */
1878
- declare function useLoader<I extends InputLike, L extends LoaderLike | ConstructorRepresentation<LoaderLike>>(loader: L, input: I, extensions?: Extensions<L>, onProgress?: (event: ProgressEvent<EventTarget>) => void, cacheKey?: InputLike): I extends any[] ? LoaderResult<L>[] : LoaderResult<L>;
1879
- declare namespace useLoader {
1880
- var preload: <I extends InputLike, L extends LoaderLike | ConstructorRepresentation<LoaderLike>>(loader: L, input: I, extensions?: Extensions<L>, onProgress?: (event: ProgressEvent<EventTarget>) => void, cacheKey?: InputLike) => void;
1881
- var clear: <I extends InputLike, L extends LoaderLike | ConstructorRepresentation<LoaderLike>>(loader: L, input: I, cacheKey?: InputLike) => void;
1882
- var loader: typeof getLoader;
1883
- }
1884
-
1885
- /**
1886
- * Frame hook with phase-based ordering, priority, and FPS throttling.
1887
- *
1888
- * Always delivers full RootState — works both inside and outside Canvas context:
1889
- * - Inside Canvas: Full RootState (renderer, scene, camera, etc.)
1890
- * - Outside Canvas: The job registers immediately but the callback is held until a
1891
- * Canvas adopts it, then runs with full RootState. For hostless / standalone
1892
- * frame loops with no Canvas, use `@pmndrs/scheduler` directly.
1893
- *
1894
- * Returns a controls object for manual stepping, pausing, and resuming.
1895
- *
1896
- * @param callback - Function called each frame with (state, delta). Optional if you only need scheduler access.
1897
- * @param priorityOrOptions - Either a priority number (backwards compat) or options object
1898
- * @returns Controls object with step(), stepAll(), pause(), resume(), isPaused, id, scheduler
1899
- *
1900
- * @example
1901
- * // Simple priority (backwards compat)
1902
- * useFrame((state, delta) => { ... }, 5)
1903
- *
1904
- * @example
1905
- * // With phase-based ordering
1906
- * useFrame((state, delta) => { ... }, { phase: 'physics' })
1907
- *
1908
- * @example
1909
- * // Outside Canvas - callback waits for a Canvas, then always has full state
1910
- * function UI() {
1911
- * useFrame((state, delta) => { syncUI(state.camera) });
1912
- * return <button>...</button>;
1913
- * }
1914
- *
1915
- * @example
1916
- * // Hostless / standalone loop (no Canvas) - use @pmndrs/scheduler directly
1917
- * import { getScheduler } from '@pmndrs/scheduler'
1918
- * getScheduler().register((state, delta) => { updateGame(delta) })
1919
- *
1920
- * @example
1921
- * // Scheduler-only access (no callback)
1922
- * const { scheduler } = useFrame()
1923
- * scheduler.pauseJob('some-job-id')
1924
- *
1925
- * @see https://docs.pmnd.rs/react-three-fiber/api/hooks#useframe
1926
- */
1927
- declare function useFrame(callback?: FrameNextCallback, priorityOrOptions?: number | UseFrameNextOptions): FrameNextControls;
1928
-
1929
- declare const IsObject: (url: unknown) => url is Record<string, string>;
1930
- type TextureArray<T> = T extends string[] ? Texture$1[] : never;
1931
- type TextureRecord<T> = T extends Record<string, string> ? {
1932
- [key in keyof T]: Texture$1;
1933
- } : never;
1934
- type SingleTexture<T> = T extends string ? Texture$1 : never;
1935
- type MappedTextureType<T extends string[] | string | Record<string, string>> = TextureArray<T> | TextureRecord<T> | SingleTexture<T>;
1936
- /** Options for useTexture hook */
1937
- type UseTextureOptions<Url extends string[] | string | Record<string, string>> = {
1938
- /** Callback when texture(s) finish loading */
1939
- onLoad?: (texture: MappedTextureType<Url>) => void;
1940
- /**
1941
- * Register the texture(s) in R3F's global texture registry for access via useTextures().
1942
- * When true (the default):
1943
- * - Textures persist until explicitly disposed
1944
- * - On mount, returns existing registered textures if available (preserving modifications like colorSpace)
1945
- *
1946
- * Reads are taken once at mount — a mounted `useTexture` does not re-render when the registry
1947
- * changes. To react to registry swaps, use `useTextures(s => s.get(key))` instead.
1948
- *
1949
- * Pass `false` to opt out of registry enrollment entirely.
1950
- * @default true
1951
- */
1952
- cache?: boolean;
1953
- };
1954
- /**
1955
- * Load texture(s) using Three's TextureLoader with Suspense support.
1956
- *
1957
- * @param input - URL string, array of URLs, or object mapping keys to URLs
1958
- * @param optionsOrOnLoad - Options object or legacy onLoad callback
1959
- *
1960
- * @example
1961
- * ```tsx
1962
- * // Single texture
1963
- * const diffuse = useTexture('/textures/diffuse.png')
1964
- *
1965
- * // Multiple textures (array)
1966
- * const [diffuse, normal] = useTexture(['/diffuse.png', '/normal.png'])
1967
- *
1968
- * // Named textures (object)
1969
- * const { diffuse, normal } = useTexture({
1970
- * diffuse: '/diffuse.png',
1971
- * normal: '/normal.png'
1972
- * })
1973
- *
1974
- * // Textures are registered in the global registry by default — the same texture
1975
- * // object is shared across components and modifications (colorSpace, wrapS, etc.) are preserved
1976
- * const diffuse = useTexture('/diffuse.png')
1977
- * diffuse.colorSpace = THREE.SRGBColorSpace
1978
- *
1979
- * // Another component gets the SAME texture with colorSpace already set
1980
- * const sameDiffuse = useTexture('/diffuse.png')
1981
- *
1982
- * // Opt out of registry enrollment for a one-off texture
1983
- * const scratch = useTexture('/scratch.png', { cache: false })
1984
- *
1985
- * // Access the registry directly
1986
- * const { get } = useTextures()
1987
- * const cached = get('/diffuse.png')
1988
- * ```
1989
- */
1990
- declare function useTexture<Url extends string[] | string | Record<string, string>>(input: Url, optionsOrOnLoad?: UseTextureOptions<Url> | ((texture: MappedTextureType<Url>) => void)): MappedTextureType<Url>;
1991
- declare namespace useTexture {
1992
- var preload: (url: string | string[]) => void;
1993
- var clear: (input: string | string[]) => void;
1994
- }
1995
- declare const Texture: ({ children, input, onLoad, cache, }: {
1996
- children?: (texture: ReturnType<typeof useTexture>) => ReactNode;
1997
- input: Parameters<typeof useTexture>[0];
1998
- onLoad?: Parameters<typeof useTexture>[1];
1999
- cache?: boolean;
2000
- }) => react_jsx_runtime.JSX.Element;
2001
-
2002
- /** Accepted shapes for a registry read: a single key, a list of keys, or a name→key map. */
2003
- type TextureInput = string | string[] | Record<string, string>;
2004
- /** Result of a `get()` read, mirroring the input shape. */
2005
- type TextureResult<Input extends TextureInput> = Input extends string ? Texture$1 | undefined : Input extends string[] ? (Texture$1 | undefined)[] : {
2006
- [K in keyof Input]: Texture$1 | undefined;
2007
- };
2008
- /** Options for `dispose()`. */
2009
- interface DisposeOptions {
2010
- /** Dispose even if the texture still has active references (default false). */
2011
- force?: boolean;
2012
- }
2013
- interface UseTexturesReturn {
2014
- /** The live registry Map (key → Texture). Treat as read-only. */
2015
- readonly all: Map<string, Texture$1>;
2016
- /** Read one texture, an array of textures, or a name→texture record (mirrors the input shape). */
2017
- get<Input extends TextureInput>(input: Input): TextureResult<Input>;
2018
- /** Check whether a key exists in the registry. */
2019
- has(key: string): boolean;
2020
- /**
2021
- * Register a texture (or a record of textures) that has no URL — e.g. a render
2022
- * target or procedural texture. URL-loaded textures are registered automatically
2023
- * by `useTexture` (registry enrollment is on by default).
2024
- */
2025
- add(key: string, texture: Texture$1): void;
2026
- add(record: Record<string, Texture$1>): void;
2027
- /**
2028
- * Dispose a texture's GPU resources and remove it from the registry.
2029
- * Refcount-aware: if the key is still in use by a mounted `useTexture` consumer it is
2030
- * skipped (with a warning) unless `{ force: true }` is passed.
2031
- * @returns true if disposed, false if skipped.
2032
- */
2033
- dispose(key: string, options?: DisposeOptions): boolean;
2034
- /** Dispose every texture in the registry and clear it. Use on scene teardown. */
2035
- disposeAll(): void;
2036
- }
2037
- /**
2038
- * Reactive Texture registry — load once with `useTexture`, reach the textures from anywhere.
2039
- *
2040
- * This is a registry of plain `Texture` objects (not TSL nodes), so the same texture can feed
2041
- * a material map, a heightmap sampler, or anything else. It does **not** load — pair it with
2042
- * `useTexture` for loading (registry enrollment is on by default); `useTextures` is for access and lifecycle.
2043
- *
2044
- * The returned handle is **reactive**: the calling component re-renders when the registry
2045
- * changes. Pass a selector to scope the subscription to a single read.
2046
- *
2047
- * @example
2048
- * ```tsx
2049
- * // Load + register once (anywhere in the tree) — registered by default
2050
- * useTexture({ map: '/diffuse.jpg', normalMap: '/normal.jpg' })
2051
- *
2052
- * // Reach them from another component — record form lands straight into a material
2053
- * const { map, normalMap } = useTextures().get({ map: '/diffuse.jpg', normalMap: '/normal.jpg' })
2054
- * return <meshStandardMaterial map={map} normalMap={normalMap} />
2055
- *
2056
- * // A set of heightmaps at once
2057
- * const [a, b, c] = useTextures().get(['/h0.png', '/h1.png', '/h2.png'])
2058
- *
2059
- * // Register a non-URL texture (render target / procedural)
2060
- * useTextures().add('rt-main', renderTarget.texture)
2061
- *
2062
- * // Deliberate GPU cleanup (refcount-aware; force to override)
2063
- * useTextures().dispose('/diffuse.jpg')
2064
- * useTextures().disposeAll() // scene teardown
2065
- * ```
2066
- *
2067
- * @remarks
2068
- * **Future expansion:** an imperative async loader (e.g. `await useTextures().load('/x.jpg')`) is
2069
- * intentionally not included yet. It would let non-React code (loading screens, dynamic streaming)
2070
- * populate the registry without Suspense, at the cost of putting loading back into this hook. It
2071
- * will be added only if a concrete consumer needs imperative loading; for now, loading lives in
2072
- * `useTexture`.
2073
- */
2074
- declare function useTextures(): UseTexturesReturn;
2075
- declare function useTextures<T>(selector: (registry: UseTexturesReturn) => T): T;
2076
-
2077
- /**
2078
- * Creates a render target compatible with the current renderer.
2079
- *
2080
- * - Legacy build: Returns WebGLRenderTarget
2081
- * - WebGPU build: Returns RenderTarget
2082
- * - Default build: Returns whichever matches the active renderer
2083
- *
2084
- * @example
2085
- * ```tsx
2086
- * // Use canvas size
2087
- * const fbo = useRenderTarget()
2088
- *
2089
- * // Use canvas size with options
2090
- * const fbo = useRenderTarget({ samples: 4 })
2091
- *
2092
- * // Square render target
2093
- * const fbo = useRenderTarget(512)
2094
- *
2095
- * // Square render target with options
2096
- * const fbo = useRenderTarget(512, { depthBuffer: true })
2097
- *
2098
- * // Explicit dimensions
2099
- * const fbo = useRenderTarget(512, 256)
2100
- *
2101
- * // Explicit dimensions with options
2102
- * const fbo = useRenderTarget(512, 256, { samples: 4 })
2103
- * ```
2104
- */
2105
- declare function useRenderTarget(options?: RenderTargetOptions): RenderTarget;
2106
- declare function useRenderTarget(size: number, options?: RenderTargetOptions): RenderTarget;
2107
- declare function useRenderTarget(width: number, height: number, options?: RenderTargetOptions): RenderTarget;
2108
-
2109
- /**
2110
- * Returns the R3F Canvas' Zustand store. Useful for [transient updates](https://github.com/pmndrs/zustand#transient-updates-for-often-occurring-state-changes).
2111
- * @see https://docs.pmnd.rs/react-three-fiber/api/hooks#usestore
2112
- */
2113
- declare function useStore(): RootStore;
2114
- /**
2115
- * Accesses R3F's internal state, containing renderer, canvas, scene, etc.
2116
- * @see https://docs.pmnd.rs/react-three-fiber/api/hooks#usethree
2117
- */
2118
- declare function useThree<T = RootState>(selector?: (state: RootState) => T, equalityFn?: <T>(state: T, newState: T) => boolean): T;
2119
- /**
2120
- * Exposes an object's {@link Instance}.
2121
- * @see https://docs.pmnd.rs/react-three-fiber/api/additional-exports#useInstanceHandle
2122
- *
2123
- * **Note**: this is an escape hatch to react-internal fields. Expect this to change significantly between versions.
2124
- */
2125
- declare function useInstanceHandle<T>(ref: React.RefObject<T>): React.RefObject<Instance<T>>;
2126
- /**
2127
- * Returns a node graph of an object with named nodes & materials.
2128
- * @see https://docs.pmnd.rs/react-three-fiber/api/hooks#usegraph
2129
- */
2130
- declare function useGraph(object: Object3D): ObjectMap;
2131
-
2132
- /**
2133
- * Adds a global render callback which is called each frame BEFORE rendering.
2134
- *
2135
- * @deprecated Use `useFrame(callback, { phase: 'start' })` instead.
2136
- * This function will be removed in a future version.
2137
- *
2138
- * @param callback - Function called each frame with timestamp
2139
- * @returns Unsubscribe function
2140
- *
2141
- * @example
2142
- * // OLD (deprecated)
2143
- * const unsub = addEffect((timestamp) => { ... })
2144
- *
2145
- * // NEW
2146
- * useFrame((state, delta) => { ... }, { phase: 'start' })
2147
- *
2148
- * @see https://docs.pmnd.rs/react-three-fiber/api/additional-exports#addEffect
2149
- */
2150
- declare function addEffect(callback: GlobalRenderCallback): () => void;
2151
- /**
2152
- * Adds a global after-render callback which is called each frame AFTER rendering.
2153
- *
2154
- * @deprecated Use `useFrame(callback, { phase: 'finish' })` instead.
2155
- * This function will be removed in a future version.
2156
- *
2157
- * @param callback - Function called each frame with timestamp
2158
- * @returns Unsubscribe function
2159
- *
2160
- * @example
2161
- * // OLD (deprecated)
2162
- * const unsub = addAfterEffect((timestamp) => { ... })
2163
- *
2164
- * // NEW
2165
- * useFrame((state, delta) => { ... }, { phase: 'finish' })
2166
- *
2167
- * @see https://docs.pmnd.rs/react-three-fiber/api/additional-exports#addAfterEffect
2168
- */
2169
- declare function addAfterEffect(callback: GlobalRenderCallback): () => void;
2170
- /**
2171
- * Adds a global callback which is called when rendering stops.
2172
- *
2173
- * @deprecated Use `scheduler.onIdle(callback)` instead.
2174
- * This function will be removed in a future version.
2175
- *
2176
- * @param callback - Function called when rendering stops
2177
- * @returns Unsubscribe function
2178
- *
2179
- * @example
2180
- * // OLD (deprecated)
2181
- * const unsub = addTail((timestamp) => { ... })
2182
- *
2183
- * // NEW
2184
- * const { scheduler } = useFrame()
2185
- * const unsub = scheduler.onIdle((timestamp) => { ... })
2186
- *
2187
- * @see https://docs.pmnd.rs/react-three-fiber/api/additional-exports#addTail
2188
- */
2189
- declare function addTail(callback: GlobalRenderCallback): () => void;
2190
- /**
2191
- * Invalidates the view, requesting a frame to be rendered.
2192
- * In demand mode, this triggers the scheduler to run frames.
2193
- *
2194
- * @param state - Optional root state (ignored in new scheduler, kept for backwards compat)
2195
- * @param frames - Number of frames to request (default: 1)
2196
- * @param stackFrames - If false, sets pendingFrames to frames. If true, adds to existing pendingFrames (default: false)
2197
- *
2198
- * @see https://docs.pmnd.rs/react-three-fiber/api/additional-exports#invalidate
2199
- */
2200
- declare function invalidate(state?: RootState, frames?: number, stackFrames?: boolean): void;
2201
- /**
2202
- * Advances the frameloop and runs render effects.
2203
- * Useful for when manually rendering via `frameloop="never"`.
2204
- *
2205
- * @param timestamp - The timestamp to use for this frame
2206
- * @param runGlobalEffects - Ignored (kept for backwards compat, global effects always run)
2207
- * @param state - Ignored (kept for backwards compat)
2208
- * @param frame - Ignored (kept for backwards compat)
2209
- *
2210
- * @see https://docs.pmnd.rs/react-three-fiber/api/additional-exports#advance
2211
- */
2212
- declare function advance(timestamp: number): void;
2213
-
2214
- /* eslint-disable @definitelytyped/no-unnecessary-generics */
2215
- declare function ReactReconciler<
2216
- Type,
2217
- Props,
2218
- Container,
2219
- Instance,
2220
- TextInstance,
2221
- SuspenseInstance,
2222
- HydratableInstance,
2223
- FormInstance,
2224
- PublicInstance,
2225
- HostContext,
2226
- ChildSet,
2227
- TimeoutHandle,
2228
- NoTimeout,
2229
- TransitionStatus,
2230
- >(
2231
- /* eslint-enable @definitelytyped/no-unnecessary-generics */
2232
- config: ReactReconciler.HostConfig<
2233
- Type,
2234
- Props,
2235
- Container,
2236
- Instance,
2237
- TextInstance,
2238
- SuspenseInstance,
2239
- HydratableInstance,
2240
- FormInstance,
2241
- PublicInstance,
2242
- HostContext,
2243
- ChildSet,
2244
- TimeoutHandle,
2245
- NoTimeout,
2246
- TransitionStatus
2247
- >,
2248
- ): ReactReconciler.Reconciler<Container, Instance, TextInstance, SuspenseInstance, FormInstance, PublicInstance>;
2249
-
2250
- declare namespace ReactReconciler {
2251
- interface HostConfig<
2252
- Type,
2253
- Props,
2254
- Container,
2255
- Instance,
2256
- TextInstance,
2257
- SuspenseInstance,
2258
- HydratableInstance,
2259
- FormInstance,
2260
- PublicInstance,
2261
- HostContext,
2262
- ChildSet,
2263
- TimeoutHandle,
2264
- NoTimeout,
2265
- TransitionStatus,
2266
- > {
2267
- // -------------------
2268
- // Modes
2269
- // -------------------
2270
- /**
2271
- * The reconciler has two modes: mutation mode and persistent mode. You must specify one of them.
2272
- *
2273
- * If your target platform is similar to the DOM and has methods similar to `appendChild`, `removeChild`, and so on, you'll want to use the **mutation mode**. This is the same mode used by React DOM, React ART, and the classic React Native renderer.
2274
- *
2275
- * ```js
2276
- * const HostConfig = {
2277
- * // ...
2278
- * supportsMutation: true,
2279
- * // ...
2280
- * }
2281
- * ```
2282
- *
2283
- * Depending on the mode, the reconciler will call different methods on your host config.
2284
- *
2285
- * If you're not sure which one you want, you likely need the mutation mode.
2286
- */
2287
- supportsMutation: boolean;
2288
-
2289
- /**
2290
- * The reconciler has two modes: mutation mode and persistent mode. You must specify one of them.
2291
- *
2292
- * If your target platform has immutable trees, you'll want the **persistent mode** instead. In that mode, existing nodes are never mutated, and instead every change clones the parent tree and then replaces the whole parent tree at the root. This is the node used by the new React Native renderer, codenamed "Fabric".
2293
- *
2294
- * ```js
2295
- * const HostConfig = {
2296
- * // ...
2297
- * supportsPersistence: true,
2298
- * // ...
2299
- * }
2300
- * ```
2301
- *
2302
- * Depending on the mode, the reconciler will call different methods on your host config.
2303
- *
2304
- * If you're not sure which one you want, you likely need the mutation mode.
2305
- */
2306
- supportsPersistence: boolean;
2307
-
2308
- // -------------------
2309
- // Core Methods
2310
- // -------------------
2311
-
2312
- /**
2313
- * This method should return a newly created node. For example, the DOM renderer would call `document.createElement(type)` here and then set the properties from `props`.
2314
- *
2315
- * You can use `rootContainer` to access the root container associated with that tree. For example, in the DOM renderer, this is useful to get the correct `document` reference that the root belongs to.
2316
- *
2317
- * The `hostContext` parameter lets you keep track of some information about your current place in the tree. To learn more about it, see `getChildHostContext` below.
2318
- *
2319
- * The `internalHandle` data structure is meant to be opaque. If you bend the rules and rely on its internal fields, be aware that it may change significantly between versions. You're taking on additional maintenance risk by reading from it, and giving up all guarantees if you write something to it.
2320
- *
2321
- * This method happens **in the render phase**. It can (and usually should) mutate the node it has just created before returning it, but it must not modify any other nodes. It must not register any event handlers on the parent tree. This is because an instance being created doesn't guarantee it would be placed in the tree — it could be left unused and later collected by GC. If you need to do something when an instance is definitely in the tree, look at `commitMount` instead.
2322
- */
2323
- createInstance(
2324
- type: Type,
2325
- props: Props,
2326
- rootContainer: Container,
2327
- hostContext: HostContext,
2328
- internalHandle: OpaqueHandle,
2329
- ): Instance;
2330
-
2331
- /**
2332
- * Same as `createInstance`, but for text nodes. If your renderer doesn't support text nodes, you can throw here.
2333
- */
2334
- createTextInstance(
2335
- text: string,
2336
- rootContainer: Container,
2337
- hostContext: HostContext,
2338
- internalHandle: OpaqueHandle,
2339
- ): TextInstance;
2340
-
2341
- /**
2342
- * This method should mutate the `parentInstance` and add the child to its list of children. For example, in the DOM this would translate to a `parentInstance.appendChild(child)` call.
2343
- *
2344
- * This method happens **in the render phase**. It can mutate `parentInstance` and `child`, but it must not modify any other nodes. It's called while the tree is still being built up and not connected to the actual tree on the screen.
2345
- */
2346
- appendInitialChild(parentInstance: Instance, child: Instance | TextInstance): void;
2347
-
2348
- /**
2349
- * In this method, you can perform some final mutations on the `instance`. Unlike with `createInstance`, by the time `finalizeInitialChildren` is called, all the initial children have already been added to the `instance`, but the instance itself has not yet been connected to the tree on the screen.
2350
- *
2351
- * This method happens **in the render phase**. It can mutate `instance`, but it must not modify any other nodes. It's called while the tree is still being built up and not connected to the actual tree on the screen.
2352
- *
2353
- * There is a second purpose to this method. It lets you specify whether there is some work that needs to happen when the node is connected to the tree on the screen. If you return `true`, the instance will receive a `commitMount` call later. See its documentation below.
2354
- *
2355
- * If you don't want to do anything here, you should return `false`.
2356
- */
2357
- finalizeInitialChildren(
2358
- instance: Instance,
2359
- type: Type,
2360
- props: Props,
2361
- rootContainer: Container,
2362
- hostContext: HostContext,
2363
- ): boolean;
2364
-
2365
- /**
2366
- * Some target platforms support setting an instance's text content without manually creating a text node. For example, in the DOM, you can set `node.textContent` instead of creating a text node and appending it.
2367
- *
2368
- * If you return `true` from this method, React will assume that this node's children are text, and will not create nodes for them. It will instead rely on you to have filled that text during `createInstance`. This is a performance optimization. For example, the DOM renderer returns `true` only if `type` is a known text-only parent (like `'textarea'`) or if `props.children` has a `'string'` type. If you return `true`, you will need to implement `resetTextContent` too.
2369
- *
2370
- * If you don't want to do anything here, you should return `false`.
2371
- *
2372
- * This method happens **in the render phase**. Do not mutate the tree from it.
2373
- */
2374
- shouldSetTextContent(type: Type, props: Props): boolean;
2375
-
2376
- /**
2377
- * This method lets you return the initial host context from the root of the tree. See `getChildHostContext` for the explanation of host context.
2378
- *
2379
- * If you don't intend to use host context, you can return `null`.
2380
- *
2381
- * This method happens **in the render phase**. Do not mutate the tree from it.
2382
- */
2383
- getRootHostContext(rootContainer: Container): HostContext | null;
2384
-
2385
- /**
2386
- * Host context lets you track some information about where you are in the tree so that it's available inside `createInstance` as the `hostContext` parameter. For example, the DOM renderer uses it to track whether it's inside an HTML or an SVG tree, because `createInstance` implementation needs to be different for them.
2387
- *
2388
- * If the node of this `type` does not influence the context you want to pass down, you can return `parentHostContext`. Alternatively, you can return any custom object representing the information you want to pass down.
2389
- *
2390
- * If you don't want to do anything here, return `parentHostContext`.
2391
- *
2392
- * This method happens **in the render phase**. Do not mutate the tree from it.
2393
- */
2394
- getChildHostContext(parentHostContext: HostContext, type: Type, rootContainer: Container): HostContext;
2395
-
2396
- /**
2397
- * Determines what object gets exposed as a ref. You'll likely want to return the `instance` itself. But in some cases it might make sense to only expose some part of it.
2398
- *
2399
- * If you don't want to do anything here, return `instance`.
2400
- */
2401
- getPublicInstance(instance: Instance | TextInstance): PublicInstance;
2402
-
2403
- /**
2404
- * This method lets you store some information before React starts making changes to the tree on the screen. For example, the DOM renderer stores the current text selection so that it can later restore it. This method is mirrored by `resetAfterCommit`.
2405
- *
2406
- * Even if you don't want to do anything here, you need to return `null` from it.
2407
- */
2408
- prepareForCommit(containerInfo: Container): Record<string, any> | null;
2409
-
2410
- /**
2411
- * This method is called right after React has performed the tree mutations. You can use it to restore something you've stored in `prepareForCommit` — for example, text selection.
2412
- *
2413
- * You can leave it empty.
2414
- */
2415
- resetAfterCommit(containerInfo: Container): void;
2416
-
2417
- /**
2418
- * This method is called for a container that's used as a portal target. Usually you can leave it empty.
2419
- */
2420
- preparePortalMount(containerInfo: Container): void;
2421
-
2422
- /**
2423
- * You can proxy this to `setTimeout` or its equivalent in your environment.
2424
- */
2425
- scheduleTimeout(fn: (...args: unknown[]) => unknown, delay?: number): TimeoutHandle;
2426
-
2427
- /**
2428
- * You can proxy this to `clearTimeout` or its equivalent in your environment.
2429
- */
2430
- cancelTimeout(id: TimeoutHandle): void;
2431
-
2432
- /**
2433
- * This is a property (not a function) that should be set to something that can never be a valid timeout ID. For example, you can set it to `-1`.
2434
- */
2435
- noTimeout: NoTimeout;
2436
-
2437
- /**
2438
- * Set this to true to indicate that your renderer supports `scheduleMicrotask`. We use microtasks as part of our discrete event implementation in React DOM. If you're not sure if your renderer should support this, you probably should. The option to not implement `scheduleMicrotask` exists so that platforms with more control over user events, like React Native, can choose to use a different mechanism.
2439
- */
2440
- supportsMicrotasks?: boolean;
2441
-
2442
- /**
2443
- * Optional. You can proxy this to `queueMicrotask` or its equivalent in your environment.
2444
- */
2445
- scheduleMicrotask?(fn: () => unknown): void;
2446
-
2447
- /**
2448
- * This is a property (not a function) that should be set to `true` if your renderer is the main one on the page. For example, if you're writing a renderer for the Terminal, it makes sense to set it to `true`, but if your renderer is used *on top of* React DOM or some other existing renderer, set it to `false`.
2449
- */
2450
- isPrimaryRenderer: boolean;
2451
-
2452
- /**
2453
- * Whether the renderer shouldn't trigger missing `act()` warnings
2454
- */
2455
- warnsIfNotActing?: boolean;
2456
-
2457
- getInstanceFromNode(node: any): Fiber | null | undefined;
2458
-
2459
- beforeActiveInstanceBlur(): void;
2460
-
2461
- afterActiveInstanceBlur(): void;
2462
-
2463
- prepareScopeUpdate(scopeInstance: any, instance: any): void;
2464
-
2465
- getInstanceFromScope(scopeInstance: any): null | Instance;
2466
-
2467
- detachDeletedInstance(node: Instance): void;
2468
-
2469
- // -------------------
2470
- // Mutation Methods
2471
- // (optional)
2472
- // If you're using React in mutation mode (you probably do), you'll need to implement a few more methods.
2473
- // -------------------
2474
-
2475
- /**
2476
- * This method should mutate the `parentInstance` and add the child to its list of children. For example, in the DOM this would translate to a `parentInstance.appendChild(child)` call.
2477
- *
2478
- * Although this method currently runs in the commit phase, you still should not mutate any other nodes in it. If you need to do some additional work when a node is definitely connected to the visible tree, look at `commitMount`.
2479
- */
2480
- appendChild?(parentInstance: Instance, child: Instance | TextInstance): void;
2481
-
2482
- /**
2483
- * Same as `appendChild`, but for when a node is attached to the root container. This is useful if attaching to the root has a slightly different implementation, or if the root container nodes are of a different type than the rest of the tree.
2484
- */
2485
- appendChildToContainer?(container: Container, child: Instance | TextInstance): void;
2486
-
2487
- /**
2488
- * This method should mutate the `parentInstance` and place the `child` before `beforeChild` in the list of its children. For example, in the DOM this would translate to a `parentInstance.insertBefore(child, beforeChild)` call.
2489
- *
2490
- * Note that React uses this method both for insertions and for reordering nodes. Similar to DOM, it is expected that you can call `insertBefore` to reposition an existing child. Do not mutate any other parts of the tree from it.
2491
- */
2492
- insertBefore?(
2493
- parentInstance: Instance,
2494
- child: Instance | TextInstance,
2495
- beforeChild: Instance | TextInstance | SuspenseInstance,
2496
- ): void;
2497
-
2498
- /**
2499
- * Same as `insertBefore`, but for when a node is attached to the root container. This is useful if attaching to the root has a slightly different implementation, or if the root container nodes are of a different type than the rest of the tree.
2500
- */
2501
- insertInContainerBefore?(
2502
- container: Container,
2503
- child: Instance | TextInstance,
2504
- beforeChild: Instance | TextInstance | SuspenseInstance,
2505
- ): void;
2506
-
2507
- /**
2508
- * This method should mutate the `parentInstance` to remove the `child` from the list of its children.
2509
- *
2510
- * React will only call it for the top-level node that is being removed. It is expected that garbage collection would take care of the whole subtree. You are not expected to traverse the child tree in it.
2511
- */
2512
- removeChild?(parentInstance: Instance, child: Instance | TextInstance | SuspenseInstance): void;
2513
-
2514
- /**
2515
- * Same as `removeChild`, but for when a node is detached from the root container. This is useful if attaching to the root has a slightly different implementation, or if the root container nodes are of a different type than the rest of the tree.
2516
- */
2517
- removeChildFromContainer?(container: Container, child: Instance | TextInstance | SuspenseInstance): void;
2518
-
2519
- /**
2520
- * If you returned `true` from `shouldSetTextContent` for the previous props, but returned `false` from `shouldSetTextContent` for the next props, React will call this method so that you can clear the text content you were managing manually. For example, in the DOM you could set `node.textContent = ''`.
2521
- *
2522
- * If you never return `true` from `shouldSetTextContent`, you can leave it empty.
2523
- */
2524
- resetTextContent?(instance: Instance): void;
2525
-
2526
- /**
2527
- * This method should mutate the `textInstance` and update its text content to `nextText`.
2528
- *
2529
- * Here, `textInstance` is a node created by `createTextInstance`.
2530
- */
2531
- commitTextUpdate?(textInstance: TextInstance, oldText: string, newText: string): void;
2532
-
2533
- /**
2534
- * This method is only called if you returned `true` from `finalizeInitialChildren` for this instance.
2535
- *
2536
- * It lets you do some additional work after the node is actually attached to the tree on the screen for the first time. For example, the DOM renderer uses it to trigger focus on nodes with the `autoFocus` attribute.
2537
- *
2538
- * Note that `commitMount` does not mirror `removeChild` one to one because `removeChild` is only called for the top-level removed node. This is why ideally `commitMount` should not mutate any nodes other than the `instance` itself. For example, if it registers some events on some node above, it will be your responsibility to traverse the tree in `removeChild` and clean them up, which is not ideal.
2539
- *
2540
- * The `internalHandle` data structure is meant to be opaque. If you bend the rules and rely on its internal fields, be aware that it may change significantly between versions. You're taking on additional maintenance risk by reading from it, and giving up all guarantees if you write something to it.
2541
- *
2542
- * If you never return `true` from `finalizeInitialChildren`, you can leave it empty.
2543
- */
2544
- commitMount?(instance: Instance, type: Type, props: Props, internalInstanceHandle: OpaqueHandle): void;
2545
-
2546
- /**
2547
- * This method should mutate the instance to match nextProps.
2548
- *
2549
- * The internalHandle data structure is meant to be opaque. If you bend the rules and rely on its internal fields, be aware that it may change significantly between versions. You're taking on additional maintenance risk by reading from it, and giving up all guarantees if you write something to it.
2550
- */
2551
- commitUpdate?(
2552
- instance: Instance,
2553
- type: Type,
2554
- prevProps: Props,
2555
- nextProps: Props,
2556
- internalHandle: OpaqueHandle,
2557
- ): void;
2558
-
2559
- /**
2560
- * This method should make the `instance` invisible without removing it from the tree. For example, it can apply visual styling to hide it. It is used by Suspense to hide the tree while the fallback is visible.
2561
- */
2562
- hideInstance?(instance: Instance): void;
2563
-
2564
- /**
2565
- * Same as `hideInstance`, but for nodes created by `createTextInstance`.
2566
- */
2567
- hideTextInstance?(textInstance: TextInstance): void;
2568
-
2569
- /**
2570
- * This method should make the `instance` visible, undoing what `hideInstance` did.
2571
- */
2572
- unhideInstance?(instance: Instance, props: Props): void;
2573
-
2574
- /**
2575
- * Same as `unhideInstance`, but for nodes created by `createTextInstance`.
2576
- */
2577
- unhideTextInstance?(textInstance: TextInstance, text: string): void;
2578
-
2579
- /**
2580
- * This method should mutate the `container` root node and remove all children from it.
2581
- */
2582
- clearContainer?(container: Container): void;
2583
-
2584
- // -------------------
2585
- // Persistence Methods
2586
- // (optional)
2587
- // If you use the persistent mode instead of the mutation mode, you would still need the "Core Methods". However, instead of the Mutation Methods above you will implement a different set of methods that performs cloning nodes and replacing them at the root level. You can find a list of them in the "Persistence" section [listed in this file](https://github.com/facebook/react/blob/master/packages/react-reconciler/src/forks/ReactFiberConfig.custom.js). File an issue if you need help.
2588
- // -------------------
2589
- cloneInstance?(
2590
- instance: Instance,
2591
- type: Type,
2592
- oldProps: Props,
2593
- newProps: Props,
2594
- keepChildren: boolean,
2595
- recyclableInstance: null | Instance,
2596
- ): Instance;
2597
- createContainerChildSet?(container: Container): ChildSet;
2598
- appendChildToContainerChildSet?(childSet: ChildSet, child: Instance | TextInstance): void;
2599
- finalizeContainerChildren?(container: Container, newChildren: ChildSet): void;
2600
- replaceContainerChildren?(container: Container, newChildren: ChildSet): void;
2601
- cloneHiddenInstance?(
2602
- instance: Instance,
2603
- type: Type,
2604
- props: Props,
2605
- internalInstanceHandle: OpaqueHandle,
2606
- ): Instance;
2607
- cloneHiddenTextInstance?(instance: Instance, text: Type, internalInstanceHandle: OpaqueHandle): TextInstance;
2608
-
2609
- // -------------------
2610
- // Hydration Methods
2611
- // (optional)
2612
- // You can optionally implement hydration to "attach" to the existing tree during the initial render instead of creating it from scratch. For example, the DOM renderer uses this to attach to an HTML markup.
2613
- //
2614
- // To support hydration, you need to declare `supportsHydration: true` and then implement the methods in the "Hydration" section [listed in this file](https://github.com/facebook/react/blob/master/packages/react-reconciler/src/forks/ReactFiberConfig.custom.js). File an issue if you need help.
2615
- // -------------------
2616
- supportsHydration: boolean;
2617
-
2618
- canHydrateInstance?(instance: HydratableInstance, type: Type, props: Props): null | Instance;
2619
-
2620
- canHydrateTextInstance?(instance: HydratableInstance, text: string): null | TextInstance;
2621
-
2622
- canHydrateSuspenseInstance?(instance: HydratableInstance): null | SuspenseInstance;
2623
-
2624
- isSuspenseInstancePending?(instance: SuspenseInstance): boolean;
2625
-
2626
- isSuspenseInstanceFallback?(instance: SuspenseInstance): boolean;
2627
-
2628
- registerSuspenseInstanceRetry?(instance: SuspenseInstance, callback: () => void): void;
2629
-
2630
- getNextHydratableSibling?(instance: HydratableInstance): null | HydratableInstance;
2631
-
2632
- getFirstHydratableChild?(parentInstance: Container | Instance): null | HydratableInstance;
2633
-
2634
- hydrateInstance?(
2635
- instance: Instance,
2636
- type: Type,
2637
- props: Props,
2638
- rootContainerInstance: Container,
2639
- hostContext: HostContext,
2640
- internalInstanceHandle: any,
2641
- ): null | any[];
2642
-
2643
- hydrateTextInstance?(textInstance: TextInstance, text: string, internalInstanceHandle: any): boolean;
2644
-
2645
- hydrateSuspenseInstance?(suspenseInstance: SuspenseInstance, internalInstanceHandle: any): void;
2646
-
2647
- getNextHydratableInstanceAfterSuspenseInstance?(suspenseInstance: SuspenseInstance): null | HydratableInstance;
2648
-
2649
- // Returns the SuspenseInstance if this node is a direct child of a
2650
- // SuspenseInstance. I.e. if its previous sibling is a Comment with
2651
- // SUSPENSE_x_START_DATA. Otherwise, null.
2652
- getParentSuspenseInstance?(targetInstance: any): null | SuspenseInstance;
2653
-
2654
- commitHydratedContainer?(container: Container): void;
2655
-
2656
- commitHydratedSuspenseInstance?(suspenseInstance: SuspenseInstance): void;
2657
-
2658
- didNotMatchHydratedContainerTextInstance?(
2659
- parentContainer: Container,
2660
- textInstance: TextInstance,
2661
- text: string,
2662
- ): void;
2663
-
2664
- didNotMatchHydratedTextInstance?(
2665
- parentType: Type,
2666
- parentProps: Props,
2667
- parentInstance: Instance,
2668
- textInstance: TextInstance,
2669
- text: string,
2670
- ): void;
2671
-
2672
- didNotHydrateContainerInstance?(parentContainer: Container, instance: HydratableInstance): void;
2673
-
2674
- didNotHydrateInstance?(
2675
- parentType: Type,
2676
- parentProps: Props,
2677
- parentInstance: Instance,
2678
- instance: HydratableInstance,
2679
- ): void;
2680
-
2681
- didNotFindHydratableContainerInstance?(parentContainer: Container, type: Type, props: Props): void;
2682
-
2683
- didNotFindHydratableContainerTextInstance?(parentContainer: Container, text: string): void;
2684
-
2685
- didNotFindHydratableContainerSuspenseInstance?(parentContainer: Container): void;
2686
-
2687
- didNotFindHydratableInstance?(
2688
- parentType: Type,
2689
- parentProps: Props,
2690
- parentInstance: Instance,
2691
- type: Type,
2692
- props: Props,
2693
- ): void;
2694
-
2695
- didNotFindHydratableTextInstance?(
2696
- parentType: Type,
2697
- parentProps: Props,
2698
- parentInstance: Instance,
2699
- text: string,
2700
- ): void;
2701
-
2702
- didNotFindHydratableSuspenseInstance?(parentType: Type, parentProps: Props, parentInstance: Instance): void;
2703
-
2704
- errorHydratingContainer?(parentContainer: Container): void;
2705
-
2706
- // Undocumented
2707
- // https://github.com/facebook/react/pull/26722
2708
- NotPendingTransition: TransitionStatus | null;
2709
- HostTransitionContext: ReactContext<TransitionStatus>;
2710
-
2711
- // https://github.com/facebook/react/pull/28751
2712
- setCurrentUpdatePriority(newPriority: EventPriority): void;
2713
- getCurrentUpdatePriority(): EventPriority;
2714
- resolveUpdatePriority(): EventPriority;
2715
-
2716
- // https://github.com/facebook/react/pull/28804
2717
- resetFormInstance(form: FormInstance): void;
2718
-
2719
- // https://github.com/facebook/react/pull/25105
2720
- requestPostPaintCallback(callback: (time: number) => void): void;
2721
-
2722
- // https://github.com/facebook/react/pull/26025
2723
- shouldAttemptEagerTransition(): boolean;
2724
-
2725
- // https://github.com/facebook/react/pull/31528
2726
- trackSchedulerEvent(): void;
2727
-
2728
- // https://github.com/facebook/react/pull/31008
2729
- resolveEventType(): null | string;
2730
- resolveEventTimeStamp(): number;
2731
-
2732
- /**
2733
- * This method is called during render to determine if the Host Component type and props require some kind of loading process to complete before committing an update.
2734
- */
2735
- maySuspendCommit(type: Type, props: Props): boolean;
2736
-
2737
- /**
2738
- * This method may be called during render if the Host Component type and props might suspend a commit. It can be used to initiate any work that might shorten the duration of a suspended commit.
2739
- */
2740
- preloadInstance(type: Type, props: Props): boolean;
2741
-
2742
- /**
2743
- * This method is called just before the commit phase. Use it to set up any necessary state while any Host Components that might suspend this commit are evaluated to determine if the commit must be suspended.
2744
- */
2745
- startSuspendingCommit(): void;
2746
-
2747
- /**
2748
- * This method is called after `startSuspendingCommit` for each Host Component that indicated it might suspend a commit.
2749
- */
2750
- suspendInstance(type: Type, props: Props): void;
2751
-
2752
- /**
2753
- * This method is called after all `suspendInstance` calls are complete.
2754
- *
2755
- * Return `null` if the commit can happen immediately.
2756
- *
2757
- * Return `(initiateCommit: Function) => Function` if the commit must be suspended. The argument to this callback will initiate the commit when called. The return value is a cancellation function that the Reconciler can use to abort the commit.
2758
- */
2759
- waitForCommitToBeReady():
2760
- | ((initiateCommit: (...args: unknown[]) => unknown) => (...args: unknown[]) => unknown)
2761
- | null;
2762
- }
2763
-
2764
- interface Thenable<T> {
2765
- then(resolve: () => T, reject?: () => T): T;
2766
- }
2767
-
2768
- type RootTag = 0 | 1 | 2;
2769
-
2770
- type WorkTag =
2771
- | 0
2772
- | 1
2773
- | 2
2774
- | 3
2775
- | 4
2776
- | 5
2777
- | 6
2778
- | 7
2779
- | 8
2780
- | 9
2781
- | 10
2782
- | 11
2783
- | 12
2784
- | 13
2785
- | 14
2786
- | 15
2787
- | 16
2788
- | 17
2789
- | 18
2790
- | 19
2791
- | 20
2792
- | 21
2793
- | 22
2794
- | 23
2795
- | 24;
2796
-
2797
- type HookType =
2798
- | "useState"
2799
- | "useReducer"
2800
- | "useContext"
2801
- | "useRef"
2802
- | "useEffect"
2803
- | "useLayoutEffect"
2804
- | "useCallback"
2805
- | "useMemo"
2806
- | "useImperativeHandle"
2807
- | "useDebugValue"
2808
- | "useDeferredValue"
2809
- | "useTransition"
2810
- | "useMutableSource"
2811
- | "useOpaqueIdentifier"
2812
- | "useCacheRefresh";
2813
-
2814
- interface Source {
2815
- fileName: string;
2816
- lineNumber: number;
2817
- }
2818
-
2819
- // TODO: Ideally these types would be opaque but that doesn't work well with
2820
- // our reconciler fork infra, since these leak into non-reconciler packages.
2821
- type LanePriority = 0 | 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 | 14 | 15 | 16 | 17;
2822
-
2823
- type Lanes = number;
2824
- type Lane = number;
2825
-
2826
- type Flags = number;
2827
-
2828
- type TypeOfMode = number;
2829
-
2830
- type EventPriority = number;
2831
-
2832
- interface ReactProvider<T> {
2833
- $$typeof: symbol | number;
2834
- type: ReactProviderType<T>;
2835
- key: null | string;
2836
- ref: null;
2837
- props: {
2838
- value: T;
2839
- children?: ReactNode;
2840
- };
2841
- }
2842
-
2843
- interface ReactProviderType<T> {
2844
- $$typeof: symbol | number;
2845
- _context: ReactContext<T>;
2846
- }
2847
-
2848
- interface ReactConsumer<T> {
2849
- $$typeof: symbol | number;
2850
- type: ReactContext<T>;
2851
- key: null | string;
2852
- ref: null;
2853
- props: {
2854
- children: (value: T) => ReactNode;
2855
- unstable_observedBits?: number;
2856
- };
2857
- }
2858
-
2859
- interface ReactContext<T> {
2860
- $$typeof: symbol | number;
2861
- Consumer: ReactContext<T>;
2862
- Provider: ReactProviderType<T>;
2863
- _currentValue: T;
2864
- _currentValue2: T;
2865
- _threadCount: number;
2866
- // DEV only
2867
- _currentRenderer?: {
2868
- [key: string]: any;
2869
- } | null;
2870
- _currentRenderer2?: {
2871
- [key: string]: any;
2872
- } | null;
2873
- // This value may be added by application code
2874
- // to improve DEV tooling display names
2875
- displayName?: string;
2876
- }
2877
-
2878
- interface ReactPortal {
2879
- $$typeof: symbol | number;
2880
- key: null | string;
2881
- containerInfo: any;
2882
- children: ReactNode;
2883
- // TODO: figure out the API for cross-renderer implementation.
2884
- implementation: any;
2885
- }
2886
-
2887
- interface RefObject {
2888
- current: any;
2889
- }
2890
-
2891
- interface ContextDependency<T> {
2892
- context: ReactContext<T>;
2893
- observedBits: number;
2894
- next: ContextDependency<unknown> | null;
2895
- }
2896
-
2897
- interface Dependencies {
2898
- lanes: Lanes;
2899
- firstContext: ContextDependency<unknown> | null;
2900
- }
2901
-
2902
- interface Fiber {
2903
- // These first fields are conceptually members of an Instance. This used to
2904
- // be split into a separate type and intersected with the other Fiber fields,
2905
- // but until Flow fixes its intersection bugs, we've merged them into a
2906
- // single type.
2907
-
2908
- // An Instance is shared between all versions of a component. We can easily
2909
- // break this out into a separate object to avoid copying so much to the
2910
- // alternate versions of the tree. We put this on a single object for now to
2911
- // minimize the number of objects created during the initial render.
2912
-
2913
- // Tag identifying the type of fiber.
2914
- tag: WorkTag;
2915
-
2916
- // Unique identifier of this child.
2917
- key: null | string;
2918
-
2919
- // The value of element.type which is used to preserve the identity during
2920
- // reconciliation of this child.
2921
- elementType: any;
2922
-
2923
- // The resolved function/class/ associated with this fiber.
2924
- type: any;
2925
-
2926
- // The local state associated with this fiber.
2927
- stateNode: any;
2928
-
2929
- // Conceptual aliases
2930
- // parent : Instance -> return The parent happens to be the same as the
2931
- // return fiber since we've merged the fiber and instance.
2932
-
2933
- // Remaining fields belong to Fiber
2934
-
2935
- // The Fiber to return to after finishing processing this one.
2936
- // This is effectively the parent, but there can be multiple parents (two)
2937
- // so this is only the parent of the thing we're currently processing.
2938
- // It is conceptually the same as the return address of a stack frame.
2939
- return: Fiber | null;
2940
-
2941
- // Singly Linked List Tree Structure.
2942
- child: Fiber | null;
2943
- sibling: Fiber | null;
2944
- index: number;
2945
-
2946
- // The ref last used to attach this node.
2947
- // I'll avoid adding an owner field for prod and model that as functions.
2948
- ref:
2949
- | null
2950
- | (((handle: unknown) => void) & {
2951
- _stringRef?: string | null;
2952
- })
2953
- | RefObject;
2954
-
2955
- // Input is the data coming into process this fiber. Arguments. Props.
2956
- pendingProps: any; // This type will be more specific once we overload the tag.
2957
- memoizedProps: any; // The props used to create the output.
2958
-
2959
- // A queue of state updates and callbacks.
2960
- updateQueue: unknown;
2961
-
2962
- // The state used to create the output
2963
- memoizedState: any;
2964
-
2965
- // Dependencies (contexts, events) for this fiber, if it has any
2966
- dependencies: Dependencies | null;
2967
-
2968
- // Bitfield that describes properties about the fiber and its subtree. E.g.
2969
- // the ConcurrentMode flag indicates whether the subtree should be async-by-
2970
- // default. When a fiber is created, it inherits the mode of its
2971
- // parent. Additional flags can be set at creation time, but after that the
2972
- // value should remain unchanged throughout the fiber's lifetime, particularly
2973
- // before its child fibers are created.
2974
- mode: TypeOfMode;
2975
-
2976
- // Effect
2977
- flags: Flags;
2978
- subtreeFlags: Flags;
2979
- deletions: Fiber[] | null;
2980
-
2981
- // Singly linked list fast path to the next fiber with side-effects.
2982
- nextEffect: Fiber | null;
2983
-
2984
- // The first and last fiber with side-effect within this subtree. This allows
2985
- // us to reuse a slice of the linked list when we reuse the work done within
2986
- // this fiber.
2987
- firstEffect: Fiber | null;
2988
- lastEffect: Fiber | null;
2989
-
2990
- lanes: Lanes;
2991
- childLanes: Lanes;
2992
-
2993
- // This is a pooled version of a Fiber. Every fiber that gets updated will
2994
- // eventually have a pair. There are cases when we can clean up pairs to save
2995
- // memory if we need to.
2996
- alternate: Fiber | null;
2997
-
2998
- // Time spent rendering this Fiber and its descendants for the current update.
2999
- // This tells us how well the tree makes use of sCU for memoization.
3000
- // It is reset to 0 each time we render and only updated when we don't bailout.
3001
- // This field is only set when the enableProfilerTimer flag is enabled.
3002
- actualDuration?: number;
3003
-
3004
- // If the Fiber is currently active in the "render" phase,
3005
- // This marks the time at which the work began.
3006
- // This field is only set when the enableProfilerTimer flag is enabled.
3007
- actualStartTime?: number;
3008
-
3009
- // Duration of the most recent render time for this Fiber.
3010
- // This value is not updated when we bailout for memoization purposes.
3011
- // This field is only set when the enableProfilerTimer flag is enabled.
3012
- selfBaseDuration?: number;
3013
-
3014
- // Sum of base times for all descendants of this Fiber.
3015
- // This value bubbles up during the "complete" phase.
3016
- // This field is only set when the enableProfilerTimer flag is enabled.
3017
- treeBaseDuration?: number;
3018
-
3019
- // Conceptual aliases
3020
- // workInProgress : Fiber -> alternate The alternate used for reuse happens
3021
- // to be the same as work in progress.
3022
- // __DEV__ only
3023
- _debugID?: number;
3024
- _debugSource?: Source | null;
3025
- _debugOwner?: Fiber | null;
3026
- _debugIsCurrentlyTiming?: boolean;
3027
- _debugNeedsRemount?: boolean;
3028
-
3029
- // Used to verify that the order of hooks does not change between renders.
3030
- _debugHookTypes?: HookType[] | null;
3031
- }
3032
-
3033
- type FiberRoot = any;
3034
-
3035
- // Concurrent related struct
3036
- type MutableSource = any;
3037
-
3038
- type OpaqueHandle = any;
3039
- type OpaqueRoot = any;
3040
-
3041
- // 0 is PROD, 1 is DEV.
3042
- // Might add PROFILE later.
3043
- type BundleType = 0 | 1;
3044
-
3045
- interface DevToolsConfig<Instance, TextInstance, RendererInspectionConfig> {
3046
- bundleType: BundleType;
3047
- version: string;
3048
- rendererPackageName: string;
3049
- // Note: this actually *does* depend on Fiber internal fields.
3050
- // Used by "inspect clicked DOM element" in React DevTools.
3051
- findFiberByHostInstance?: (instance: Instance | TextInstance) => Fiber | null;
3052
- rendererConfig?: RendererInspectionConfig;
3053
- }
3054
-
3055
- interface SuspenseHydrationCallbacks<SuspenseInstance> {
3056
- onHydrated?: (suspenseInstance: SuspenseInstance) => void;
3057
- onDeleted?: (suspenseInstance: SuspenseInstance) => void;
3058
- }
3059
-
3060
- interface TransitionTracingCallbacks {
3061
- onTransitionStart?: (transitionName: string, startTime: number) => void;
3062
- onTransitionProgress?: (
3063
- transitionName: string,
3064
- startTime: number,
3065
- currentTime: number,
3066
- pending: Array<{ name: null | string }>,
3067
- ) => void;
3068
- onTransitionIncomplete?: (
3069
- transitionName: string,
3070
- startTime: number,
3071
- deletions: Array<{
3072
- type: string;
3073
- name?: string;
3074
- newName?: string;
3075
- endTime: number;
3076
- }>,
3077
- ) => void;
3078
- onTransitionComplete?: (transitionName: string, startTime: number, endTime: number) => void;
3079
- onMarkerProgress?: (
3080
- transitionName: string,
3081
- marker: string,
3082
- startTime: number,
3083
- currentTime: number,
3084
- pending: Array<{ name: null | string }>,
3085
- ) => void;
3086
- onMarkerIncomplete?: (
3087
- transitionName: string,
3088
- marker: string,
3089
- startTime: number,
3090
- deletions: Array<{
3091
- type: string;
3092
- name?: string;
3093
- newName?: string;
3094
- endTime: number;
3095
- }>,
3096
- ) => void;
3097
- onMarkerComplete?: (transitionName: string, marker: string, startTime: number, endTime: number) => void;
3098
- }
3099
-
3100
- interface ComponentSelector {
3101
- $$typeof: symbol | number;
3102
- value: React$AbstractComponent<never, unknown>;
3103
- }
3104
-
3105
- interface HasPseudoClassSelector {
3106
- $$typeof: symbol | number;
3107
- value: Selector[];
3108
- }
3109
-
3110
- interface RoleSelector {
3111
- $$typeof: symbol | number;
3112
- value: string;
3113
- }
3114
-
3115
- interface TextSelector {
3116
- $$typeof: symbol | number;
3117
- value: string;
3118
- }
3119
-
3120
- interface TestNameSelector {
3121
- $$typeof: symbol | number;
3122
- value: string;
3123
- }
3124
-
3125
- type Selector = ComponentSelector | HasPseudoClassSelector | RoleSelector | TextSelector | TestNameSelector;
3126
-
3127
- // TODO can not find React$AbstractComponent def
3128
- type React$AbstractComponent<Config, Instance = any> = any;
3129
-
3130
- interface BoundingRect {
3131
- x: number;
3132
- y: number;
3133
- width: number;
3134
- height: number;
3135
- }
3136
-
3137
- type IntersectionObserverOptions = any;
3138
-
3139
- interface BaseErrorInfo {
3140
- componentStack?: string;
3141
- }
3142
-
3143
- interface Reconciler<Container, Instance, TextInstance, SuspenseInstance, FormInstance, PublicInstance> {
3144
- createContainer(
3145
- containerInfo: Container,
3146
- tag: RootTag,
3147
- hydrationCallbacks: null | SuspenseHydrationCallbacks<SuspenseInstance>,
3148
- isStrictMode: boolean,
3149
- concurrentUpdatesByDefaultOverride: null | boolean,
3150
- identifierPrefix: string,
3151
- onUncaughtError: (error: Error, info: BaseErrorInfo & { errorBoundary?: Component }) => void,
3152
- onCaughtError: (error: Error, info: BaseErrorInfo) => void,
3153
- onRecoverableError: (error: Error, info: BaseErrorInfo) => void,
3154
- onDefaultTransitionIndicator: () => void,
3155
- transitionCallbacks: null | TransitionTracingCallbacks,
3156
- ): OpaqueRoot;
3157
-
3158
- createPortal(
3159
- children: ReactNode,
3160
- containerInfo: any, // TODO: figure out the API for cross-renderer implementation.
3161
- implementation: any,
3162
- key?: string | null,
3163
- ): ReactPortal;
3164
-
3165
- registerMutableSourceForHydration(root: FiberRoot, mutableSource: MutableSource): void;
3166
-
3167
- createComponentSelector(component: React$AbstractComponent<never, unknown>): ComponentSelector;
3168
-
3169
- createHasPseudoClassSelector(selectors: Selector[]): HasPseudoClassSelector;
3170
-
3171
- createRoleSelector(role: string): RoleSelector;
3172
-
3173
- createTextSelector(text: string): TextSelector;
3174
-
3175
- createTestNameSelector(id: string): TestNameSelector;
3176
-
3177
- getFindAllNodesFailureDescription(hostRoot: Instance, selectors: Selector[]): string | null;
3178
-
3179
- findAllNodes(hostRoot: Instance, selectors: Selector[]): Instance[];
3180
-
3181
- findBoundingRects(hostRoot: Instance, selectors: Selector[]): BoundingRect[];
3182
-
3183
- focusWithin(hostRoot: Instance, selectors: Selector[]): boolean;
3184
-
3185
- observeVisibleRects(
3186
- hostRoot: Instance,
3187
- selectors: Selector[],
3188
- callback: (intersections: Array<{ ratio: number; rect: BoundingRect }>) => void,
3189
- options?: IntersectionObserverOptions,
3190
- ): { disconnect: () => void };
3191
-
3192
- createHydrationContainer(
3193
- initialChildren: ReactNode,
3194
- callback: (() => void) | null | undefined,
3195
- containerInfo: Container,
3196
- tag: RootTag,
3197
- hydrationCallbacks: null | SuspenseHydrationCallbacks<SuspenseInstance>,
3198
- isStrictMode: boolean,
3199
- concurrentUpdatesByDefaultOverride: null | boolean,
3200
- identifierPrefix: string,
3201
- onRecoverableError: (error: Error) => void,
3202
- transitionCallbacks: null | TransitionTracingCallbacks,
3203
- ): OpaqueRoot;
3204
-
3205
- updateContainer(
3206
- element: ReactNode,
3207
- container: OpaqueRoot,
3208
- parentComponent?: Component<any, any> | null,
3209
- callback?: (() => void) | null,
3210
- ): Lane;
3211
-
3212
- batchedUpdates<A, R>(fn: (a: A) => R, a: A): R;
3213
-
3214
- deferredUpdates<A>(fn: () => A): A;
3215
-
3216
- discreteUpdates<A, B, C, D, R>(fn: (arg0: A, arg1: B, arg2: C, arg3: D) => R, a: A, b: B, c: C, d: D): R;
3217
-
3218
- flushControlled(fn: () => any): void;
3219
-
3220
- flushSync(): void;
3221
- flushSync<R>(fn: () => R): R;
3222
-
3223
- isAlreadyRendering(): boolean;
3224
-
3225
- flushPassiveEffects(): boolean;
3226
-
3227
- getPublicRootInstance(container: OpaqueRoot): Component<any, any> | PublicInstance | null;
3228
-
3229
- attemptSynchronousHydration(fiber: Fiber): void;
3230
-
3231
- attemptDiscreteHydration(fiber: Fiber): void;
3232
-
3233
- attemptContinuousHydration(fiber: Fiber): void;
3234
-
3235
- attemptHydrationAtCurrentPriority(fiber: Fiber): void;
3236
-
3237
- getCurrentUpdatePriority(): LanePriority;
3238
-
3239
- runWithPriority<T>(priority: LanePriority, fn: () => T): T;
3240
-
3241
- findHostInstance(component: any): PublicInstance | null;
3242
-
3243
- findHostInstanceWithWarning(component: any, methodName: string): PublicInstance | null;
3244
-
3245
- findHostInstanceWithNoPortals(fiber: Fiber): PublicInstance | null;
3246
-
3247
- shouldError(fiber: Fiber): boolean | undefined;
3248
-
3249
- shouldSuspend(fiber: Fiber): boolean;
3250
-
3251
- injectIntoDevTools(devToolsConfig: DevToolsConfig<Instance, TextInstance, any>): boolean;
3252
- }
3253
- }
3254
-
3255
- declare function extend<T extends ConstructorRepresentation>(objects: T): React$1.ExoticComponent<ThreeElement<T>>;
3256
- declare function extend<T extends Catalogue>(objects: T): void;
3257
- declare const reconciler: ReactReconciler.Reconciler<RootStore, Instance<any>, void, Instance<any>, never, any>;
3258
-
3259
- declare const isRenderer: (def: any) => boolean;
3260
- interface OffscreenCanvas extends EventTarget {
3261
- }
3262
- declare const _roots: Map<HTMLCanvasElement | OffscreenCanvas, Root>;
3263
- declare function createRoot<TCanvas extends HTMLCanvasElement | OffscreenCanvas>(canvas: TCanvas): ReconcilerRoot<TCanvas>;
3264
- declare function unmountComponentAtNode<TCanvas extends HTMLCanvasElement | OffscreenCanvas>(canvas: TCanvas, callback?: (canvas: TCanvas) => void): void;
3265
- declare function createPortal(children: ReactNode, container: Object3D | RefObject<Object3D | null> | RefObject<Object3D>, state?: InjectState): JSX.Element;
3266
- interface PortalProps {
3267
- children: ReactNode;
3268
- state?: InjectState;
3269
- container: Object3D | RefObject<Object3D | null> | RefObject<Object3D>;
3270
- }
3271
- declare function Portal({ children, container, state }: PortalProps): JSX.Element;
3272
- /**
3273
- * Force React to flush any updates inside the provided callback synchronously and immediately.
3274
- * All the same caveats documented for react-dom's `flushSync` apply here (see https://react.dev/reference/react-dom/flushSync).
3275
- * Nevertheless, sometimes one needs to render synchronously, for example to keep DOM and 3D changes in lock-step without
3276
- * having to revert to a non-React solution. Note: this will only flush updates within the `Canvas` root.
3277
- */
3278
- declare function flushSync<R>(fn: () => R): R;
3279
-
3280
- declare const context: React$1.Context<RootStore>;
3281
- declare const createStore: (invalidate: (state?: RootState, frames?: number, stackFrames?: boolean) => void, advance: (timestamp: number, runGlobalEffects?: boolean, state?: RootState, frame?: XRFrame) => void) => RootStore;
3282
-
3283
- /**
3284
- * An SSR-friendly useLayoutEffect.
3285
- *
3286
- * React currently throws a warning when using useLayoutEffect on the server.
3287
- * To get around it, we can conditionally useEffect on the server (no-op) and
3288
- * useLayoutEffect elsewhere.
3289
- *
3290
- * @see https://github.com/facebook/react/issues/14927
3291
- */
3292
- declare const useIsomorphicLayoutEffect: typeof React$1.useLayoutEffect;
3293
- /**
3294
- * Creates a stable ref that always contains the latest callback.
3295
- * Useful for avoiding dependency arrays while ensuring the latest closure is called.
3296
- *
3297
- * @param fn - The callback function to wrap
3298
- * @returns A ref containing the current callback
3299
- */
3300
- declare function useMutableCallback<T>(fn: T): React$1.RefObject<T>;
3301
- /**
3302
- * Bridges renderer Context and StrictMode from a primary renderer.
3303
- * Used to maintain React context when rendering into portals or secondary canvases.
3304
- *
3305
- * @returns A Bridge component that wraps children with the parent renderer's context
3306
- */
3307
- declare function useBridge(): Bridge;
3308
- /**
3309
- * Internal component that blocks rendering until a promise resolves.
3310
- * Used for suspense-like blocking behavior.
3311
- *
3312
- * @param set - Function to set the blocking promise
3313
- */
3314
- declare function Block({ set }: Omit<UnblockProps, 'children'>): null;
3315
- /**
3316
- * Error boundary component for catching and handling errors in the React tree.
3317
- * Forwards errors to a state setter for external handling.
3318
- *
3319
- * NOTE: static members get down-level transpiled to mutations which break tree-shaking
3320
- */
3321
- declare const ErrorBoundary: {
3322
- new (props: {
3323
- set: React$1.Dispatch<Error | undefined>;
3324
- children: React$1.ReactNode;
3325
- }): {
3326
- state: {
3327
- error: boolean;
3328
- };
3329
- componentDidCatch(err: Error): void;
3330
- render(): React$1.ReactNode;
3331
- context: unknown;
3332
- setState<K extends "error">(state: {
3333
- error: boolean;
3334
- } | ((prevState: Readonly<{
3335
- error: boolean;
3336
- }>, props: Readonly<{
3337
- set: React$1.Dispatch<Error | undefined>;
3338
- children: React$1.ReactNode;
3339
- }>) => {
3340
- error: boolean;
3341
- } | Pick<{
3342
- error: boolean;
3343
- }, K> | null) | Pick<{
3344
- error: boolean;
3345
- }, K> | null, callback?: (() => void) | undefined): void;
3346
- forceUpdate(callback?: (() => void) | undefined): void;
3347
- readonly props: Readonly<{
3348
- set: React$1.Dispatch<Error | undefined>;
3349
- children: React$1.ReactNode;
3350
- }>;
3351
- componentDidMount?(): void;
3352
- shouldComponentUpdate?(nextProps: Readonly<{
3353
- set: React$1.Dispatch<Error | undefined>;
3354
- children: React$1.ReactNode;
3355
- }>, nextState: Readonly<{
3356
- error: boolean;
3357
- }>, nextContext: any): boolean;
3358
- componentWillUnmount?(): void;
3359
- getSnapshotBeforeUpdate?(prevProps: Readonly<{
3360
- set: React$1.Dispatch<Error | undefined>;
3361
- children: React$1.ReactNode;
3362
- }>, prevState: Readonly<{
3363
- error: boolean;
3364
- }>): any;
3365
- componentDidUpdate?(prevProps: Readonly<{
3366
- set: React$1.Dispatch<Error | undefined>;
3367
- children: React$1.ReactNode;
3368
- }>, prevState: Readonly<{
3369
- error: boolean;
3370
- }>, snapshot?: any): void;
3371
- componentWillMount?(): void;
3372
- UNSAFE_componentWillMount?(): void;
3373
- componentWillReceiveProps?(nextProps: Readonly<{
3374
- set: React$1.Dispatch<Error | undefined>;
3375
- children: React$1.ReactNode;
3376
- }>, nextContext: any): void;
3377
- UNSAFE_componentWillReceiveProps?(nextProps: Readonly<{
3378
- set: React$1.Dispatch<Error | undefined>;
3379
- children: React$1.ReactNode;
3380
- }>, nextContext: any): void;
3381
- componentWillUpdate?(nextProps: Readonly<{
3382
- set: React$1.Dispatch<Error | undefined>;
3383
- children: React$1.ReactNode;
3384
- }>, nextState: Readonly<{
3385
- error: boolean;
3386
- }>, nextContext: any): void;
3387
- UNSAFE_componentWillUpdate?(nextProps: Readonly<{
3388
- set: React$1.Dispatch<Error | undefined>;
3389
- children: React$1.ReactNode;
3390
- }>, nextState: Readonly<{
3391
- error: boolean;
3392
- }>, nextContext: any): void;
3393
- };
3394
- new (props: {
3395
- set: React$1.Dispatch<Error | undefined>;
3396
- children: React$1.ReactNode;
3397
- }, context: any): {
3398
- state: {
3399
- error: boolean;
3400
- };
3401
- componentDidCatch(err: Error): void;
3402
- render(): React$1.ReactNode;
3403
- context: unknown;
3404
- setState<K extends "error">(state: {
3405
- error: boolean;
3406
- } | ((prevState: Readonly<{
3407
- error: boolean;
3408
- }>, props: Readonly<{
3409
- set: React$1.Dispatch<Error | undefined>;
3410
- children: React$1.ReactNode;
3411
- }>) => {
3412
- error: boolean;
3413
- } | Pick<{
3414
- error: boolean;
3415
- }, K> | null) | Pick<{
3416
- error: boolean;
3417
- }, K> | null, callback?: (() => void) | undefined): void;
3418
- forceUpdate(callback?: (() => void) | undefined): void;
3419
- readonly props: Readonly<{
3420
- set: React$1.Dispatch<Error | undefined>;
3421
- children: React$1.ReactNode;
3422
- }>;
3423
- componentDidMount?(): void;
3424
- shouldComponentUpdate?(nextProps: Readonly<{
3425
- set: React$1.Dispatch<Error | undefined>;
3426
- children: React$1.ReactNode;
3427
- }>, nextState: Readonly<{
3428
- error: boolean;
3429
- }>, nextContext: any): boolean;
3430
- componentWillUnmount?(): void;
3431
- getSnapshotBeforeUpdate?(prevProps: Readonly<{
3432
- set: React$1.Dispatch<Error | undefined>;
3433
- children: React$1.ReactNode;
3434
- }>, prevState: Readonly<{
3435
- error: boolean;
3436
- }>): any;
3437
- componentDidUpdate?(prevProps: Readonly<{
3438
- set: React$1.Dispatch<Error | undefined>;
3439
- children: React$1.ReactNode;
3440
- }>, prevState: Readonly<{
3441
- error: boolean;
3442
- }>, snapshot?: any): void;
3443
- componentWillMount?(): void;
3444
- UNSAFE_componentWillMount?(): void;
3445
- componentWillReceiveProps?(nextProps: Readonly<{
3446
- set: React$1.Dispatch<Error | undefined>;
3447
- children: React$1.ReactNode;
3448
- }>, nextContext: any): void;
3449
- UNSAFE_componentWillReceiveProps?(nextProps: Readonly<{
3450
- set: React$1.Dispatch<Error | undefined>;
3451
- children: React$1.ReactNode;
3452
- }>, nextContext: any): void;
3453
- componentWillUpdate?(nextProps: Readonly<{
3454
- set: React$1.Dispatch<Error | undefined>;
3455
- children: React$1.ReactNode;
3456
- }>, nextState: Readonly<{
3457
- error: boolean;
3458
- }>, nextContext: any): void;
3459
- UNSAFE_componentWillUpdate?(nextProps: Readonly<{
3460
- set: React$1.Dispatch<Error | undefined>;
3461
- children: React$1.ReactNode;
3462
- }>, nextState: Readonly<{
3463
- error: boolean;
3464
- }>, nextContext: any): void;
3465
- };
3466
- getDerivedStateFromError: () => {
3467
- error: boolean;
3468
- };
3469
- contextType?: React$1.Context<any> | undefined;
3470
- propTypes?: any;
3471
- };
3472
-
3473
- /**
3474
- * React internal props that should not be passed to Three.js objects.
3475
- */
3476
- declare const REACT_INTERNAL_PROPS: string[];
3477
- /**
3478
- * Returns the instance's initial (outermost) root.
3479
- * Traverses through previousRoot links to find the original root store.
3480
- *
3481
- * @param instance - R3F instance to find root for
3482
- * @returns The outermost root store
3483
- */
3484
- declare function findInitialRoot<T>(instance: Instance<T>): RootStore;
3485
- /**
3486
- * Returns instance root state.
3487
- * If the object doesn't have __r3f (e.g., child meshes in primitives/GLTFs),
3488
- * traverses ancestors to find the nearest managed parent.
3489
- *
3490
- * @param obj - Three.js object to get root state for
3491
- * @returns Root state if found, undefined otherwise
3492
- */
3493
- declare function getRootState<T extends Object3D = Object3D>(obj: T): RootState | undefined;
3494
- /**
3495
- * Collects nodes, materials, and meshes from a Three.js Object3D hierarchy.
3496
- * Handles duplicate material names by appending UUID prefixes.
3497
- *
3498
- * @param object - Root object to traverse
3499
- * @returns ObjectMap containing named nodes, materials, and meshes
3500
- *
3501
- * @example
3502
- * const { nodes, materials, meshes } = buildGraph(gltf.scene)
3503
- * // Access by name: nodes.Head, materials.Metal, meshes.Body
3504
- */
3505
- declare function buildGraph(object: Object3D): ObjectMap;
3506
- /**
3507
- * Disposes an object and all its disposable properties.
3508
- * Skips Scene objects as they should not be disposed automatically.
3509
- *
3510
- * @param obj - Object to dispose
3511
- */
3512
- declare function dispose<T extends Disposable>(obj: T): void;
3513
- /**
3514
- * Extracts instance props from React reconciler fiber props.
3515
- * Filters out React-internal props (children, key, ref).
3516
- *
3517
- * @param queue - Pending props from reconciler fiber
3518
- * @returns Props object without React-internal keys
3519
- */
3520
- declare function getInstanceProps<T = any>(pendingProps: Record<string, unknown>): Instance<T>['props'];
3521
- /**
3522
- * Creates or retrieves an R3F instance descriptor for a Three.js object.
3523
- * Each object in the scene carries a LocalState descriptor (__r3f).
3524
- *
3525
- * @param target - Target object to prepare
3526
- * @param root - Root store for this instance
3527
- * @param type - String identifier for the object type
3528
- * @param props - Initial props for the instance
3529
- * @returns Instance descriptor
3530
- */
3531
- declare function prepare<T = any>(target: T, root: RootStore, type: string, props: Instance<T>['props']): Instance<T>;
3532
- /**
3533
- * Triggers an update for an instance.
3534
- * Calls onUpdate callback and invalidates the frame if necessary.
3535
- *
3536
- * @param instance - Instance to invalidate
3537
- */
3538
- declare function invalidateInstance(instance: Instance): void;
3539
-
3540
- /**
3541
- * Reserved prop names that should not be applied to Three.js objects.
3542
- */
3543
- declare const RESERVED_PROPS: string[];
3544
- /**
3545
- * Resolves a potentially pierced property key (e.g., 'material-color' → material.color).
3546
- * First tries the entire key as a single property, then attempts piercing.
3547
- *
3548
- * @param root - Root object to resolve from
3549
- * @param key - Property key (may contain dashes for piercing)
3550
- * @returns Object containing root, key, and target value
3551
- *
3552
- * @example
3553
- * resolve(mesh, 'material-color')
3554
- * // => { root: mesh.material, key: 'color', target: mesh.material.color }
3555
- */
3556
- declare function resolve(root: any, key: string): {
3557
- root: any;
3558
- key: string;
3559
- target: any;
3560
- };
3561
- /**
3562
- * Attaches a child instance to a parent instance.
3563
- * Handles both string-based attachment (e.g., 'geometry', 'material-map')
3564
- * and function-based attachment for custom logic.
3565
- *
3566
- * @param parent - Parent instance
3567
- * @param child - Child instance to attach
3568
- *
3569
- * @example
3570
- * // String attachment
3571
- * <bufferGeometry attach="geometry" />
3572
- * // Array attachment
3573
- * <light attach="lights-0" />
3574
- * // Function attachment
3575
- * <thing attach={(parent, self) => { parent.customProp = self }} />
3576
- */
3577
- declare function attach(parent: Instance, child: Instance): void;
3578
- /**
3579
- * Detaches a child instance from a parent instance.
3580
- * Restores the previous value or deletes the property if it was never set.
3581
- *
3582
- * @param parent - Parent instance
3583
- * @param child - Child instance to detach
3584
- */
3585
- declare function detach(parent: Instance, child: Instance): void;
3586
- /**
3587
- * Compares old and new props to determine which properties have changed.
3588
- * Also handles resetting removed props for HMR/fast-refresh.
3589
- *
3590
- * @param instance - Instance to diff props for
3591
- * @param newProps - New props to compare against
3592
- * @returns Object containing only changed props
3593
- *
3594
- * @example
3595
- * const changes = diffProps(instance, { position: [1, 2, 3], color: 'red' })
3596
- * // => { position: [1, 2, 3] } (only if position changed)
3597
- */
3598
- declare function diffProps<T = any>(instance: Instance<T>, newProps: Instance<T>['props']): Instance<T>['props'];
3599
- /**
3600
- * Applies a set of props to a Three.js object.
3601
- * Handles special cases like colors, vectors, textures, events, and pierced props.
3602
- *
3603
- * @param object - Three.js object to apply props to
3604
- * @param props - Props to apply
3605
- * @returns The object with props applied
3606
- *
3607
- * @example
3608
- * applyProps(mesh, { position: [0, 1, 0], 'material-color': 'red' })
3609
- */
3610
- declare function applyProps<T = any>(object: Instance<T>['object'], props: Instance<T>['props']): Instance<T>['object'];
3611
-
3612
- /**
3613
- * Calculates the device pixel ratio for rendering.
3614
- * Handles array DPR ranges [min, max] to clamp devicePixelRatio.
3615
- *
3616
- * @param dpr - Target DPR value or [min, max] range
3617
- * @returns Calculated DPR value
3618
- *
3619
- * @example
3620
- * calculateDpr(2) // => 2
3621
- * calculateDpr([1, 2]) // => clamps window.devicePixelRatio between 1 and 2
3622
- */
3623
- declare function calculateDpr(dpr: Dpr): number;
3624
- /**
3625
- * Extracts the first segment of a UUID string (before the first hyphen).
3626
- * Used for creating unique material names when duplicates exist.
3627
- *
3628
- * @param uuid - UUID string to extract prefix from
3629
- * @returns First segment of the UUID
3630
- *
3631
- * @example
3632
- * getUuidPrefix('a1b2c3d4-e5f6-g7h8-i9j0') // => 'a1b2c3d4'
3633
- */
3634
- declare function getUuidPrefix(uuid: string): string;
3635
- /**
3636
- * Updates camera projection based on viewport size.
3637
- * Adjusts aspect ratio for perspective cameras or bounds for orthographic cameras.
3638
- * Respects camera.manual flag - manual cameras are not modified.
3639
- *
3640
- * @param camera - Camera to update
3641
- * @param size - Current viewport size
3642
- */
3643
- declare function updateCamera(camera: ThreeCamera, size: Size): void;
3644
- /**
3645
- * Updates a frustum from a camera's projection and world matrices.
3646
- * If no target frustum is provided, creates and returns a new one.
3647
- *
3648
- * @param camera - Camera to extract frustum from
3649
- * @param frustum - Optional existing frustum to update (creates new if not provided)
3650
- * @returns The updated or newly created frustum
3651
- *
3652
- * @example
3653
- * // Create new frustum
3654
- * const frustum = updateFrustum(camera)
3655
- *
3656
- * // Update existing frustum (no allocation)
3657
- * updateFrustum(camera, existingFrustum)
3658
- *
3659
- * // Use for visibility checks
3660
- * if (frustum.containsPoint(point)) { ... }
3661
- * if (frustum.intersectsObject(mesh)) { ... }
3662
- */
3663
- declare function updateFrustum(camera: ThreeCamera, frustum?: Frustum): Frustum;
3664
-
3665
- declare const is: {
3666
- obj: (a: any) => boolean;
3667
- fun: (a: any) => a is Function;
3668
- str: (a: any) => a is string;
3669
- num: (a: any) => a is number;
3670
- boo: (a: any) => a is boolean;
3671
- und: (a: any) => boolean;
3672
- nul: (a: any) => boolean;
3673
- arr: (a: any) => a is any[];
3674
- equ(a: any, b: any, { arrays, objects, strict }?: EquConfig): boolean;
3675
- };
3676
- declare const isOrthographicCamera: (def: ThreeCamera) => def is OrthographicCamera;
3677
- declare const isRef: (obj: unknown) => obj is React.RefObject<unknown>;
3678
- declare const isColorRepresentation: (value: unknown) => value is ColorRepresentation$1;
3679
- declare const isObject3D: (object: any) => object is Object3D;
3680
- declare const isTexture: (value: unknown) => value is Texture$1;
3681
- type VectorLike = {
3682
- set: (...args: any[]) => void;
3683
- constructor?: Function;
3684
- };
3685
- declare const isVectorLike: (object: unknown) => object is VectorLike;
3686
- type Copyable = {
3687
- copy: (...args: any[]) => void;
3688
- constructor?: Function;
3689
- };
3690
- declare const isCopyable: (object: unknown) => object is Copyable;
3691
- declare const hasConstructor: (object: unknown) => object is {
3692
- constructor?: Function;
3693
- };
3694
-
3695
- /**
3696
- * Symbol marker for deferred ref resolution.
3697
- * Used to identify values that should be resolved from refs after mount.
3698
- */
3699
- declare const FROM_REF: unique symbol;
3700
- /**
3701
- * Defers prop application until the referenced object is available.
3702
- * Useful for props like `target` that need sibling refs to be populated.
3703
- *
3704
- * @param ref - React ref object to resolve at mount time
3705
- * @returns A marker value that applyProps will resolve after mount
3706
- *
3707
- * @example
3708
- * const targetRef = useRef<THREE.Object3D>(null)
3709
- *
3710
- * <group ref={targetRef} position={[-3, -2, -15]} />
3711
- * <spotLight target={fromRef(targetRef)} intensity={100} />
3712
- */
3713
- declare function fromRef<T>(ref: React$1.RefObject<T | null>): T;
3714
- /**
3715
- * Type guard to check if a value is a fromRef marker.
3716
- *
3717
- * @param value - Value to check
3718
- * @returns True if value is a fromRef marker
3719
- */
3720
- declare function isFromRef(value: unknown): value is {
3721
- [FROM_REF]: React$1.RefObject<any>;
3722
- };
3723
-
3724
- /**
3725
- * Symbol marker for mount-only method calls.
3726
- * Used to identify methods that should only be called once on initial mount.
3727
- */
3728
- declare const ONCE: unique symbol;
3729
- /**
3730
- * Marks a method call to be executed only on initial mount.
3731
- * Useful for geometry transforms that should not be reapplied on every render.
3732
- *
3733
- * When `args` prop changes (triggering reconstruction), the method will be
3734
- * called again on the new instance since appliedOnce is not carried over.
3735
- *
3736
- * @param args - Arguments to pass to the method
3737
- * @returns A marker value that applyProps will execute once
3738
- *
3739
- * @example
3740
- * // Rotate geometry on mount
3741
- * <boxGeometry args={[1, 1, 1]} rotateX={once(Math.PI / 2)} />
3742
- *
3743
- * // Multiple arguments
3744
- * <bufferGeometry applyMatrix4={once(matrix)} />
3745
- *
3746
- * // No arguments
3747
- * <geometry center={once()} />
3748
- */
3749
- declare function once<T>(...args: T[]): T;
3750
- /**
3751
- * Type guard to check if a value is a once marker.
3752
- *
3753
- * @param value - Value to check
3754
- * @returns True if value is a once marker
3755
- */
3756
- declare function isOnce(value: unknown): value is {
3757
- [ONCE]: any[] | true;
3758
- };
3759
-
3760
- /**
3761
- * A DOM canvas which accepts threejs elements as children.
3762
- * @see https://docs.pmnd.rs/react-three-fiber/api/canvas
3763
- */
3764
- declare function Canvas(props: CanvasProps): react_jsx_runtime.JSX.Element;
3765
-
3766
- export { Block, Canvas, Environment, EnvironmentCube, EnvironmentMap, EnvironmentPortal, ErrorBoundary, FROM_REF, IsObject, ONCE, Portal, R3F_BUILD_LEGACY, R3F_BUILD_WEBGPU, REACT_INTERNAL_PROPS, RESERVED_PROPS, three_d as ReactThreeFiber, Texture, _roots, addAfterEffect, addEffect, addTail, advance, applyProps, attach, buildGraph, calculateDpr, context, createEvents, createPointerEvents, createPortal, createRoot, createStore, detach, diffProps, dispose, createPointerEvents as events, extend, findInitialRoot, flushSync, fromRef, getInstanceProps, getPrimary, getPrimaryIds, getRootState, getUuidPrefix, hasConstructor, hasPrimary, invalidate, invalidateInstance, is, isColorRepresentation, isCopyable, isFromRef, isObject3D, isOnce, isOrthographicCamera, isRef, isRenderer, isTexture, isVectorLike, once, prepare, presetsObj, reconciler, registerPrimary, removeInteractivity, resolve, swapInteractivity, unmountComponentAtNode, unregisterPrimary, updateCamera, updateFrustum, useBridge, useEnvironment, useFrame, useGraph, useInstanceHandle, useIsomorphicLayoutEffect, useLoader, useMutableCallback, useRenderTarget, useStore, useTexture, useTextures, useThree, waitForPrimary };
3767
- export type { Act, Args, ArgsProp, AttachFnType, AttachType, BackgroundConfig, BackgroundProp, BaseRendererProps, Bridge, BufferLike, BufferRecord, BufferStore, Camera, CameraProps, CanvasProps, CanvasSchedulerConfig, Catalogue, Color, ColorManagementConfig, ComputeFunction, ConstructorRepresentation, DefaultGLProps, DefaultRendererProps, Disposable, DisposeOptions, DomEvent, Dpr, ElementProps, EnvironmentLoaderProps, EnvironmentProps, EquConfig, Euler, EventHandlers, EventManager, EventProps, Events, Extensions, FiberRoot, FilterFunction, FrameCallback, FrameNextCallback, FrameNextState, FrameState, Frameloop, GLProps, GLTFLike, GeometryProps, GeometryTransformProps, GlobalEffectType, GlobalRenderCallback, HostConfig, InferLoadResult, InjectState, InputLike, Instance, InstanceProps, InternalState, Intersection, IntersectionEvent, IsAllOptional, IsOptional, Layers, LegacyInternalState, LegacyRenderer, LegacyRootState, LoaderInstance, LoaderLike, LoaderResult, MappedTextureType, MathProps, MathRepresentation, MathType, MathTypes, Matrix3, Matrix4, Mutable, MutableOrReadonlyParameters, NodeProps, NonFunctionKeys, ObjectMap, OffscreenCanvas$1 as OffscreenCanvas, Overwrite, Performance, PointerCaptureTarget, PointerState, PresetsType, PrimaryCanvasEntry, Properties, Quaternion, R3FRenderer, RaycastableRepresentation, ReactProps, ReconcilerRoot, RenderCallback, RenderProps, RenderTargetOptions, Renderer, RendererConfigExtended, RendererFactory, RendererProps, Root, RootState, RootStore, SetBlock, Size, StorageLike, StorageRecord, StorageStore, Subscription, TSLNodeInput, TextureInput, TextureResult, ThreeCamera, ThreeElement, ThreeElements, ThreeElementsImpl, ThreeEvent, ThreeExports, ThreeToJSXElements, UnblockProps, UseTextureOptions, UseTexturesReturn, Vector2, Vector3, Vector4, VectorRepresentation, Viewport, VisibilityEntry, WebGLDefaultProps, WebGLProps, WebGLShadowConfig, XRManager, XRPointerConfig };
143
+ export { Canvas, CanvasProps, Color$1 as Color, ConstructorRepresentation, ElementOf$1 as ElementOf, ElementProps$1 as ElementProps, Euler$1 as Euler, EventProps$1 as EventProps, GeometryProps$1 as GeometryProps, GeometryTransformProps$1 as GeometryTransformProps, Layers$1 as Layers, MathProps$1 as MathProps, MathRepresentation$1 as MathRepresentation, MathType$1 as MathType, MathTypes$1 as MathTypes, Matrix3$1 as Matrix3, Matrix4$1 as Matrix4, MutableOrReadonlyParameters$1 as MutableOrReadonlyParameters, NodeProps$1 as NodeProps, Object3DMethod$1 as Object3DMethod, Quaternion$1 as Quaternion, R3FRenderTarget, R3F_BUILD_LEGACY, R3F_BUILD_WEBGPU, RaycastableRepresentation$1 as RaycastableRepresentation, ReactProps$1 as ReactProps, default_d as ReactThreeFiber, ReconcilerRoot, RenderTargetOptions, TSLNodeInput$1 as TSLNodeInput, ThreeElement$1 as ThreeElement, ThreeElementsOf$1 as ThreeElementsOf, ThreeToJSXElements$1 as ThreeToJSXElements, Vector2$1 as Vector2, Vector3$1 as Vector3, Vector4$1 as Vector4, VectorRepresentation$1 as VectorRepresentation, createRoot, useRenderTarget };
144
+ export type { ThreeElements, ThreeExports };