@react-three/fiber 10.0.0-canary.8f5b4d3 → 10.0.0-canary.975e1e7

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