@react-three/fiber 10.0.0-canary.b6c54f2 → 10.0.0-canary.b86abaa

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