@react-three/fiber 10.0.0-canary.ea31ccd → 10.0.0-canary.ee5a08a

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