@react-three/fiber 10.0.0-canary.9806389 → 10.0.0-canary.ab9effa

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