@react-three/fiber 10.0.0-canary.dc0ec15 → 10.0.0-canary.e53bd54

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.
@@ -0,0 +1,2852 @@
1
+ import * as React$1 from 'react';
2
+ import { ReactNode, Component, RefObject, JSX } from 'react';
3
+ import { Options } from 'react-use-measure';
4
+ import * as THREE from 'three';
5
+ import { Color as Color$1, ColorRepresentation, Euler as Euler$1, Loader, RenderTargetOptions as RenderTargetOptions$1, ColorSpace, Texture as Texture$1, CubeTexture, Scene, Object3D } from 'three';
6
+ import { n as Properties, a as Size, F as Frameloop, c as Performance, D as Dpr, d as RootStore, k as EventManager, a6 as RootState, i as ComputeFunction, p as IsAllOptional, g as EventHandlers, u as ObjectMap, a5 as InternalState, M as Mutable, O as Overwrite, f as DomEvent, J as ThreeCore, B as Bridge, U as UnblockProps, w as Disposable, q as ThreeCamera, v as EquConfig } from './fiber.Bw8YnGg5.cjs';
7
+ import { WebGPURenderer, WebGPURendererParameters } from 'three/webgpu';
8
+ import * as react_jsx_runtime from 'react/jsx-runtime';
9
+
10
+ //* Base Renderer Types =====================================
11
+
12
+ // Shim for OffscreenCanvas since it was removed from DOM types
13
+ interface OffscreenCanvas$1 extends EventTarget {}
14
+
15
+ interface BaseRendererProps {
16
+ canvas: HTMLCanvasElement | OffscreenCanvas$1
17
+ powerPreference?: 'high-performance' | 'low-power' | 'default'
18
+ antialias?: boolean
19
+ alpha?: boolean
20
+ }
21
+
22
+ type RendererFactory<TRenderer, TParams> =
23
+ | TRenderer
24
+ | ((defaultProps: TParams) => TRenderer)
25
+ | ((defaultProps: TParams) => Promise<TRenderer>)
26
+
27
+ interface Renderer {
28
+ render: (scene: THREE.Scene, camera: THREE.Camera) => any
29
+ }
30
+
31
+ //* Color Management Config ==============================
32
+
33
+ /**
34
+ * Color management configuration shared by both WebGL and WebGPU renderers.
35
+ */
36
+ interface ColorManagementConfig {
37
+ /**
38
+ * Color space assigned to 8-bit input textures (color maps).
39
+ * Defaults to sRGB. Most textures are authored in sRGB.
40
+ * @default THREE.SRGBColorSpace
41
+ */
42
+ textureColorSpace?: THREE.ColorSpace
43
+ }
44
+
45
+ //* WebGL Renderer Props ==============================
46
+
47
+ type DefaultGLProps = Omit<THREE.WebGLRendererParameters, 'canvas'> & {
48
+ canvas: HTMLCanvasElement | OffscreenCanvas$1
49
+ }
50
+
51
+ type GLProps =
52
+ | Renderer
53
+ | ((defaultProps: DefaultGLProps) => Renderer)
54
+ | ((defaultProps: DefaultGLProps) => Promise<Renderer>)
55
+ | (Partial<Properties<THREE.WebGLRenderer> | THREE.WebGLRendererParameters> & ColorManagementConfig)
56
+
57
+ //* WebGPU Renderer Props ==============================
58
+
59
+ type DefaultRendererProps = {
60
+ canvas: HTMLCanvasElement | OffscreenCanvas$1
61
+ [key: string]: any
62
+ }
63
+
64
+ /**
65
+ * Canvas-level scheduler configuration.
66
+ * Controls render timing relative to other canvases.
67
+ */
68
+ interface CanvasSchedulerConfig {
69
+ /**
70
+ * Run this Canvas root before the referenced Canvas root id(s).
71
+ */
72
+ before?: string | string[]
73
+ /**
74
+ * Run this Canvas root after the referenced Canvas root id(s).
75
+ */
76
+ after?: string | string[]
77
+ /**
78
+ * Numeric root order. Lower values run first.
79
+ */
80
+ order?: number
81
+ /**
82
+ * Limit this Canvas's default render job (frames per second).
83
+ */
84
+ fps?: number
85
+ }
86
+
87
+ /**
88
+ * Extended renderer configuration for multi-canvas support and color management.
89
+ */
90
+ interface RendererConfigExtended extends ColorManagementConfig {
91
+ /** Share renderer from another canvas (WebGPU only) */
92
+ primaryCanvas?: string
93
+ /** Canvas-level scheduler options */
94
+ scheduler?: CanvasSchedulerConfig
95
+ }
96
+
97
+ /**
98
+ * The `renderer` prop: opt into three's WebGPU renderer.
99
+ * - `true` (the `<Canvas renderer>` shorthand) or `{}`: a default `WebGPURenderer`
100
+ * - a props bag: constructor parameters (`antialias`, `forceWebGL`, ...) and renderer properties
101
+ * (`toneMapping`, ...), plus `textureColorSpace`, `primaryCanvas` and `scheduler`
102
+ * - a renderer instance, or a sync/async factory receiving the default props. Structural, like
103
+ * the `gl` prop: anything with `render()`, so a wrapped or mocked renderer is accepted.
104
+ */
105
+ type RendererProps =
106
+ | boolean
107
+ | Renderer
108
+ | ((defaultProps: DefaultRendererProps) => Renderer)
109
+ | ((defaultProps: DefaultRendererProps) => Promise<Renderer>)
110
+ | (Partial<Properties<WebGPURenderer> & WebGPURendererParameters> & RendererConfigExtended)
111
+
112
+ //* Camera Props ==============================
113
+
114
+ type CameraProps = (
115
+ | THREE.Camera
116
+ | Partial<
117
+ ThreeElement<typeof THREE.Camera> &
118
+ ThreeElement<typeof THREE.PerspectiveCamera> &
119
+ ThreeElement<typeof THREE.OrthographicCamera>
120
+ >
121
+ ) & {
122
+ /** Flags the camera as manual, putting projection into your own hands */
123
+ manual?: boolean
124
+ }
125
+
126
+ //* Render Props ==============================
127
+
128
+ interface RenderProps<TCanvas extends HTMLCanvasElement | OffscreenCanvas$1> {
129
+ /**
130
+ * Unique identifier for multi-canvas renderer sharing.
131
+ * Makes this canvas targetable by other canvases using the `primaryCanvas` prop.
132
+ * Also sets the HTML `id` attribute on the canvas element.
133
+ * @example <Canvas id="main-viewer">...</Canvas>
134
+ */
135
+ id?: string
136
+ /**
137
+ * Share the renderer from another canvas instead of creating a new one.
138
+ * Pass the `id` of the primary canvas to share its WebGPURenderer.
139
+ * Only available with WebGPU (not legacy WebGL).
140
+ *
141
+ * Note: This is extracted from `renderer={{ primaryCanvas: "id" }}` by Canvas.
142
+ * @internal
143
+ */
144
+ primaryCanvas?: string
145
+ /**
146
+ * Canvas-level scheduler options. Controls render timing relative to other canvases.
147
+ *
148
+ * Note: This is extracted from `renderer={{ scheduler: {...} }}` by Canvas.
149
+ * @internal
150
+ */
151
+ scheduler?: CanvasSchedulerConfig
152
+ /** A threejs renderer instance or props that go into the default renderer */
153
+ gl?: GLProps
154
+ /** A WebGPU renderer instance or props that go into the default renderer */
155
+ renderer?: RendererProps
156
+ /** Dimensions to fit the renderer to. Will measure canvas dimensions if omitted */
157
+ size?: Size
158
+ /**
159
+ * Enables shadows (by default PCFsoft). Can accept `gl.shadowMap` options for fine-tuning,
160
+ * but also strings: 'basic' | 'percentage' | 'soft' | 'variance'.
161
+ * @see https://threejs.org/docs/#api/en/renderers/WebGLRenderer.shadowMap
162
+ */
163
+ shadows?: boolean | 'basic' | 'percentage' | 'soft' | 'variance' | Partial<THREE.WebGLShadowMap>
164
+ /** Creates an orthographic camera */
165
+ orthographic?: boolean
166
+ /**
167
+ * R3F's render mode. Set to `demand` to only render on state change or `never` to take control.
168
+ * @see https://docs.pmnd.rs/react-three-fiber/advanced/scaling-performance#on-demand-rendering
169
+ */
170
+ frameloop?: Frameloop
171
+ /**
172
+ * R3F performance options for adaptive performance.
173
+ * @see https://docs.pmnd.rs/react-three-fiber/advanced/scaling-performance#movement-regression
174
+ */
175
+ performance?: Partial<Omit<Performance, 'regress'>>
176
+ /** Target pixel ratio. Can clamp between a range: `[min, max]` */
177
+ dpr?: Dpr
178
+ /**
179
+ * Props that go into the default raycaster. `params` is merged into the raycaster's defaults,
180
+ * so a single threshold can be set: `raycaster={{ params: { Points: { threshold: 0.2 } } }}`.
181
+ */
182
+ raycaster?: Partial<Omit<THREE.Raycaster, 'params'>> & { params?: Partial<THREE.RaycasterParameters> }
183
+ /** A `THREE.Scene` instance or props that go into the default scene */
184
+ scene?: THREE.Scene | Partial<THREE.Scene>
185
+ /** A `THREE.Camera` instance or props that go into the default camera */
186
+ camera?: CameraProps
187
+ /** An R3F event manager to manage elements' pointer events */
188
+ events?: (store: RootStore) => EventManager<Element>
189
+ /** Callback after the canvas has rendered (but not yet committed) */
190
+ onCreated?: (state: RootState) => void
191
+ /** Response for pointer clicks that have missed any target */
192
+ onPointerMissed?: (event: MouseEvent) => void
193
+ /** Response for dragover events that have missed any target */
194
+ onDragOverMissed?: (event: DragEvent) => void
195
+ /** Response for drop events that have missed any target */
196
+ onDropMissed?: (event: DragEvent) => void
197
+ /** Whether to automatically update the frustum each frame (default: true) */
198
+ autoUpdateFrustum?: boolean
199
+ /**
200
+ * Enable WebGPU occlusion queries for onOccluded/onVisible events.
201
+ * Auto-enabled when any object uses onOccluded or onVisible handlers.
202
+ * Only works with WebGPU renderer - WebGL will log a warning.
203
+ */
204
+ occlusion?: boolean
205
+ /** Internal: stored size props from Canvas for reset functionality */
206
+ _sizeProps?: { width?: number; height?: number } | null
207
+ /** Force canvas dimensions to even numbers (fixes Safari rendering issues with odd/fractional sizes) */
208
+ forceEven?: boolean
209
+ }
210
+
211
+ //* Reconciler Root ==============================
212
+
213
+ interface ReconcilerRoot<TCanvas extends HTMLCanvasElement | OffscreenCanvas$1> {
214
+ configure: (config?: RenderProps<TCanvas>) => Promise<ReconcilerRoot<TCanvas>>
215
+ render: (element: ReactNode) => RootStore
216
+ unmount: () => void
217
+ }
218
+
219
+ //* Inject State ==============================
220
+
221
+ type InjectState = Partial<
222
+ Omit<RootState, 'events'> & {
223
+ events?: {
224
+ enabled?: boolean
225
+ priority?: number
226
+ compute?: ComputeFunction
227
+ connected?: any
228
+ }
229
+ /**
230
+ * When true (default), injects a THREE.Scene between container and children if container isn't already a Scene.
231
+ * This ensures state.scene is always a real THREE.Scene with proper properties (background, environment, fog).
232
+ * Set to false to use the container directly as scene (anti-pattern, but supported for edge cases).
233
+ */
234
+ injectScene?: boolean
235
+ }
236
+ >
237
+
238
+ //* Reconciler Types ==============================
239
+
240
+ // FiberRoot is an opaque internal React type - we define it locally
241
+ // to avoid bundling @types/react-reconciler which causes absolute path issues
242
+ type FiberRoot = any
243
+
244
+ interface Root {
245
+ fiber: FiberRoot
246
+ store: RootStore
247
+ }
248
+
249
+ type AttachFnType<O = any> = (parent: any, self: O) => () => void
250
+ type AttachType<O = any> = string | AttachFnType<O>
251
+
252
+ type ConstructorRepresentation<T = any> = new (...args: any[]) => T
253
+
254
+ interface Catalogue {
255
+ [name: string]: ConstructorRepresentation
256
+ }
257
+
258
+ // TODO: handle constructor overloads
259
+ // https://github.com/pmndrs/react-three-fiber/pull/2931
260
+ // https://github.com/microsoft/TypeScript/issues/37079
261
+ type Args<T> = T extends ConstructorRepresentation
262
+ ? T extends typeof Color$1
263
+ ? [r: number, g: number, b: number] | [color: ColorRepresentation]
264
+ : ConstructorParameters<T>
265
+ : any[]
266
+
267
+ type ArgsProp<P> = P extends ConstructorRepresentation
268
+ ? IsAllOptional<ConstructorParameters<P>> extends true
269
+ ? { args?: Args<P> }
270
+ : { args: Args<P> }
271
+ : { args: unknown[] }
272
+
273
+ type InstanceProps<T = any, P = any> = ArgsProp<P> & {
274
+ object?: T
275
+ dispose?: null
276
+ attach?: AttachType<T>
277
+ }
278
+
279
+ interface Instance<O = any> {
280
+ root: RootStore
281
+ type: string
282
+ parent: Instance | null
283
+ children: Instance[]
284
+ props: InstanceProps<O> & Record<string, unknown>
285
+ object: O & { __r3f?: Instance<O> }
286
+ eventCount: number
287
+ handlers: Partial<EventHandlers>
288
+ attach?: AttachType<O>
289
+ previousAttach?: any
290
+ isHidden: boolean
291
+ /** Set of props that have been applied via once() */
292
+ appliedOnce?: Set<string>
293
+ }
294
+
295
+ interface HostConfig {
296
+ type: string
297
+ props: Instance['props']
298
+ container: RootStore
299
+ instance: Instance
300
+ textInstance: void
301
+ suspenseInstance: Instance
302
+ hydratableInstance: never
303
+ formInstance: never
304
+ publicInstance: Instance['object']
305
+ hostContext: {}
306
+ childSet: never
307
+ timeoutHandle: number | undefined
308
+ noTimeout: -1
309
+ TransitionStatus: null
310
+ }
311
+ declare global {
312
+ var IS_REACT_ACT_ENVIRONMENT: boolean | undefined
313
+ }
314
+
315
+ //* Loop Types ==============================
316
+
317
+ type GlobalRenderCallback = (timestamp: number) => void
318
+
319
+ type GlobalEffectType = 'before' | 'after' | 'tail'
320
+
321
+ declare const presetsObj: {
322
+ apartment: string;
323
+ city: string;
324
+ dawn: string;
325
+ forest: string;
326
+ lobby: string;
327
+ night: string;
328
+ park: string;
329
+ studio: string;
330
+ sunset: string;
331
+ warehouse: string;
332
+ };
333
+ type PresetsType = keyof typeof presetsObj;
334
+
335
+ //* Background Types ==============================
336
+
337
+ /**
338
+ * Expanded object form for background configuration.
339
+ * Allows separate textures for background (visual backdrop) and environment (PBR lighting).
340
+ */
341
+ interface BackgroundConfig {
342
+ /** HDRI preset name: 'apartment', 'city', 'dawn', 'forest', 'lobby', 'night', 'park', 'studio', 'sunset', 'warehouse' */
343
+ preset?: PresetsType
344
+ /** Files for cube texture (6 faces) or single HDR/EXR */
345
+ files?: string | string[]
346
+ /** Separate files for scene.background (visual backdrop) */
347
+ backgroundMap?: string | string[]
348
+ backgroundRotation?: Euler$1 | [number, number, number]
349
+ backgroundBlurriness?: number
350
+ backgroundIntensity?: number
351
+ /** Separate files for scene.environment (PBR lighting/reflections) */
352
+ envMap?: string | string[]
353
+ environmentRotation?: Euler$1 | [number, number, number]
354
+ environmentIntensity?: number
355
+ path?: string
356
+ extensions?: (loader: Loader) => void
357
+ }
358
+
359
+ /**
360
+ * Background prop type for Canvas.
361
+ *
362
+ * String detection priority:
363
+ * 1. Preset - exact match against known presets (apartment, city, dawn, forest, lobby, night, park, studio, sunset, warehouse)
364
+ * 2. URL - starts with /, ./, ../, http://, https://, OR has image extension
365
+ * 3. Color - default fallback (CSS color names, hex values, rgb(), etc.)
366
+ *
367
+ * @example Color
368
+ * ```tsx
369
+ * <Canvas background="red" />
370
+ * <Canvas background="#ff0000" />
371
+ * <Canvas background={0xff0000} />
372
+ * ```
373
+ *
374
+ * @example Preset
375
+ * ```tsx
376
+ * <Canvas background="city" />
377
+ * ```
378
+ *
379
+ * @example URL
380
+ * ```tsx
381
+ * <Canvas background="/path/to/env.hdr" />
382
+ * <Canvas background="./sky.jpg" />
383
+ * ```
384
+ *
385
+ * @example Object form
386
+ * ```tsx
387
+ * <Canvas background={{
388
+ * files: ['px.png', 'nx.png', 'py.png', 'ny.png', 'pz.png', 'nz.png'],
389
+ * backgroundMap: 'path/to/sky.jpg',
390
+ * envMap: 'path/to/lighting.hdr',
391
+ * backgroundBlurriness: 0.5,
392
+ * }} />
393
+ * ```
394
+ */
395
+ type BackgroundProp =
396
+ | ColorRepresentation // "red", "#ff0000", 0xff0000
397
+ | string // URL or preset
398
+ | BackgroundConfig // Expanded object form
399
+
400
+ //* Canvas Types ==============================
401
+
402
+ interface CanvasProps
403
+ extends
404
+ Omit<RenderProps<HTMLCanvasElement>, 'size' | 'primaryCanvas' | 'scheduler'>,
405
+ React$1.HTMLAttributes<HTMLDivElement> {
406
+ children?: React$1.ReactNode
407
+ ref?: React$1.Ref<HTMLCanvasElement>
408
+ /** Canvas fallback content, similar to img's alt prop */
409
+ fallback?: React$1.ReactNode
410
+ /**
411
+ * Options to pass to useMeasure.
412
+ * @see https://github.com/pmndrs/react-use-measure#api
413
+ */
414
+ resize?: Options
415
+ /** The target where events are being subscribed to, default: the div that wraps canvas */
416
+ eventSource?: Element | React$1.RefObject<Element | null>
417
+ /** The event prefix that is cast into canvas pointer x/y events, default: "offset" */
418
+ eventPrefix?: 'offset' | 'client' | 'page' | 'layer' | 'screen'
419
+ /** Enable/disable automatic HMR refresh for TSL nodes and uniforms, default: true in dev */
420
+ hmr?: boolean
421
+ /** Canvas resolution width in pixels. If omitted, uses container width. */
422
+ width?: number
423
+ /** Canvas resolution height in pixels. If omitted, uses container height. */
424
+ height?: number
425
+ /** Force canvas dimensions to even numbers (fixes Safari rendering issues with odd/fractional sizes) */
426
+ forceEven?: boolean
427
+ /**
428
+ * Scene background configuration.
429
+ * Accepts colors, URLs, presets, or an expanded object for separate background/environment.
430
+ * @see BackgroundProp for full documentation and examples
431
+ */
432
+ background?: BackgroundProp
433
+ }
434
+
435
+ //* Loader Types ==============================
436
+
437
+ type InputLike = string | string[] | string[][] | Readonly<string | string[] | string[][]>
438
+
439
+ // Define a loader-like interface that matches THREE.Loader's load signature
440
+ // This works for both generic and non-generic THREE.Loader instances
441
+ interface LoaderLike {
442
+ load(
443
+ url: InputLike,
444
+ onLoad?: (result: any) => void,
445
+ onProgress?: (event: ProgressEvent<EventTarget>) => void,
446
+ onError?: (error: unknown) => void,
447
+ ): any
448
+ }
449
+
450
+ type GLTFLike = { scene: THREE.Object3D }
451
+
452
+ type LoaderInstance<T extends LoaderLike | ConstructorRepresentation<LoaderLike>> =
453
+ T extends ConstructorRepresentation<LoaderLike> ? InstanceType<T> : T
454
+
455
+ // Infer result type from the load method's callback parameter
456
+ type InferLoadResult<T> = T extends {
457
+ load(url: any, onLoad?: (result: infer R) => void, ...args: any[]): any
458
+ }
459
+ ? R
460
+ : T extends ConstructorRepresentation<any>
461
+ ? InstanceType<T> extends {
462
+ load(url: any, onLoad?: (result: infer R) => void, ...args: any[]): any
463
+ }
464
+ ? R
465
+ : any
466
+ : any
467
+
468
+ type LoaderResult<T extends LoaderLike | ConstructorRepresentation<LoaderLike>> =
469
+ InferLoadResult<LoaderInstance<T>> extends infer R ? (R extends GLTFLike ? R & ObjectMap : R) : never
470
+
471
+ type Extensions<T extends LoaderLike | ConstructorRepresentation<LoaderLike>> = (
472
+ loader: LoaderInstance<T>,
473
+ ) => void
474
+
475
+ //* Renderer Props ========================================
476
+
477
+ type WebGLDefaultProps = Omit<THREE.WebGLRendererParameters, 'canvas'> & BaseRendererProps
478
+
479
+ type WebGLProps =
480
+ | RendererFactory<THREE.WebGLRenderer, WebGLDefaultProps>
481
+ | Partial<Properties<THREE.WebGLRenderer> | THREE.WebGLRendererParameters>
482
+
483
+ interface WebGLShadowConfig {
484
+ shadows?: boolean | 'basic' | 'percentage' | 'soft' | 'variance' | Partial<THREE.WebGLShadowMap>
485
+ }
486
+
487
+ //* Legacy-specific Types ========================================
488
+
489
+ /** Legacy (WebGL) renderer type - re-exported as R3FRenderer from @react-three/fiber/legacy */
490
+ type LegacyRenderer = THREE.WebGLRenderer
491
+
492
+ /** Legacy internal state with narrowed renderer type */
493
+ interface LegacyInternalState extends Omit<InternalState, 'actualRenderer'> {
494
+ actualRenderer: THREE.WebGLRenderer
495
+ }
496
+
497
+ /**
498
+ * Legacy-specific RootState with narrowed renderer type.
499
+ * Automatically used when importing from `@react-three/fiber/legacy`.
500
+ *
501
+ * @example
502
+ * ```tsx
503
+ * import { useThree } from '@react-three/fiber/legacy'
504
+ *
505
+ * function MyComponent() {
506
+ * const { renderer } = useThree()
507
+ * // renderer is typed as THREE.WebGLRenderer
508
+ * renderer.shadowMap.enabled = true
509
+ * }
510
+ * ```
511
+ */
512
+ interface LegacyRootState extends Omit<RootState, 'renderer' | 'internal'> {
513
+ /** The WebGL renderer instance */
514
+ renderer: THREE.WebGLRenderer
515
+ /** Internals with WebGL renderer */
516
+ internal: LegacyInternalState
517
+ }
518
+
519
+ //* RenderTarget Types ==============================
520
+
521
+
522
+ type RenderTargetOptions = RenderTargetOptions$1
523
+
524
+ type MutableOrReadonlyParameters<T extends (...args: any) => any> = Parameters<T> | Readonly<Parameters<T>>
525
+
526
+ interface MathRepresentation {
527
+ set(...args: number[]): any
528
+ }
529
+ interface VectorRepresentation extends MathRepresentation {
530
+ setScalar(value: number): any
531
+ }
532
+ type MathTypes = MathRepresentation | THREE.Euler | THREE.Color
533
+
534
+ type MathType<T extends MathTypes> = T extends THREE.Color
535
+ ? Args<typeof THREE.Color> | THREE.ColorRepresentation
536
+ : T extends VectorRepresentation | THREE.Layers | THREE.Euler
537
+ ? T | MutableOrReadonlyParameters<T['set']> | number
538
+ : T | MutableOrReadonlyParameters<T['set']>
539
+
540
+ type MathProps<P> = {
541
+ [K in keyof P as P[K] extends MathTypes ? K : never]: P[K] extends MathTypes ? MathType<P[K]> : never
542
+ }
543
+
544
+ type Vector2 = MathType<THREE.Vector2>
545
+ type Vector3 = MathType<THREE.Vector3>
546
+ type Vector4 = MathType<THREE.Vector4>
547
+ type Color = MathType<THREE.Color>
548
+ type Layers = MathType<THREE.Layers>
549
+ type Quaternion = MathType<THREE.Quaternion>
550
+ type Euler = MathType<THREE.Euler>
551
+ type Matrix3 = MathType<THREE.Matrix3>
552
+ type Matrix4 = MathType<THREE.Matrix4>
553
+
554
+ interface RaycastableRepresentation {
555
+ raycast(raycaster: THREE.Raycaster, intersects: THREE.Intersection[]): void
556
+ }
557
+ type EventProps<P> = P extends RaycastableRepresentation ? Partial<EventHandlers> : {}
558
+
559
+ /**
560
+ * Props for geometry transform methods that can be called with `once()`.
561
+ * These methods modify the geometry in-place and only make sense to call once on mount.
562
+ *
563
+ * @example
564
+ * import { once } from '@react-three/fiber'
565
+ *
566
+ * <boxGeometry args={[1, 1, 1]} rotateX={once(Math.PI / 2)} />
567
+ * <planeGeometry args={[10, 10]} translate={once(0, 0, 5)} />
568
+ * <bufferGeometry applyMatrix4={once(matrix)} center={once()} />
569
+ */
570
+ interface GeometryTransformProps {
571
+ /** Rotate the geometry about the X axis (radians). Use with once(). */
572
+ rotateX?: number
573
+ /** Rotate the geometry about the Y axis (radians). Use with once(). */
574
+ rotateY?: number
575
+ /** Rotate the geometry about the Z axis (radians). Use with once(). */
576
+ rotateZ?: number
577
+ /** Translate the geometry (x, y, z). Use with once(). */
578
+ translate?: [x: number, y: number, z: number]
579
+ /** Scale the geometry (x, y, z). Use with once(). */
580
+ scale?: [x: number, y: number, z: number]
581
+ /** Center the geometry based on bounding box. Use with once(). */
582
+ center?: true
583
+ /** Apply a Matrix4 transformation. Use with once(). */
584
+ applyMatrix4?: THREE.Matrix4
585
+ /** Apply a Quaternion rotation. Use with once(). */
586
+ applyQuaternion?: THREE.Quaternion
587
+ }
588
+
589
+ type GeometryProps<P> = P extends THREE.BufferGeometry ? GeometryTransformProps : {}
590
+
591
+ /**
592
+ * Workaround for @types/three TSL node type issues.
593
+ * The Node base class has properties that subclasses (OperatorNode, ConstNode, etc.) don't inherit.
594
+ * This transforms `Node | null` properties to accept any object with node-like shape.
595
+ */
596
+ type TSLNodeInput = { nodeType?: string | null; uuid?: string } | null
597
+
598
+ /**
599
+ * For node material properties (colorNode, positionNode, etc.), accept broader types
600
+ * since @types/three has broken inheritance for TSL node subclasses. NodeClass requires
601
+ * `nodeType`, so this structural key test remains neutral to the selected Three entry.
602
+ */
603
+ type NodeProps<P> = {
604
+ [K in keyof P as NonNullable<P[K]> extends { nodeType: string | null } ? K : never]?: TSLNodeInput
605
+ }
606
+
607
+ interface ReactProps<P> {
608
+ children?: React.ReactNode
609
+ ref?: React.Ref<P>
610
+ key?: React.Key
611
+ }
612
+
613
+ type ElementProps<T extends ConstructorRepresentation, P = InstanceType<T>> = Partial<
614
+ Overwrite<P, MathProps<P> & ReactProps<P> & EventProps<P> & GeometryProps<P> & NodeProps<P>>
615
+ >
616
+
617
+ type ThreeElement<T extends ConstructorRepresentation> = Mutable<
618
+ Overwrite<ElementProps<T>, Omit<InstanceProps<InstanceType<T>, T>, 'object'>>
619
+ >
620
+
621
+ type ThreeToJSXElements<T extends Record<string, any>> = {
622
+ [K in keyof T & string as Uncapitalize<K>]: T[K] extends ConstructorRepresentation ? ThreeElement<T[K]> : never
623
+ }
624
+
625
+ /** Method names of Object3D, excluded from the `primitive` element's typed props. */
626
+ type Object3DMethod = NonNullable<
627
+ {
628
+ [K in keyof THREE.Object3D]-?: THREE.Object3D[K] extends (...args: any[]) => any ? K : never
629
+ }[keyof THREE.Object3D]
630
+ >
631
+
632
+ /** Look up a key present in a generic element map. */
633
+ type ElementOf<E, K extends string> = E[Extract<keyof E, K>]
634
+
635
+ /**
636
+ * The JSX element map derived from an entry's Three.js exports. Each entry declares its own
637
+ * `ThreeElements` from this (`src/index.tsx`, `src/legacy.tsx`, `src/webgpu/index.tsx`) and augments
638
+ * react's `IntrinsicElements` with it, so `/legacy` never advertises node materials and `/webgpu`
639
+ * never advertises a `<webGLRenderer>`.
640
+ */
641
+ type ThreeElementsOf<T extends Record<string, any>> = Omit<
642
+ ThreeToJSXElements<T>,
643
+ 'audio' | 'source' | 'line' | 'path'
644
+ > & {
645
+ /**
646
+ * `primitive` wraps a pre-existing object, so its props cannot be derived from one class.
647
+ * Events are typed from `EventHandlers` (`onClick={(e) => ...}` infers `e`), the ref is
648
+ * untyped, and any other prop is accepted and applied to the object by name. Object3D's own
649
+ * methods are left out of the typed surface: they return `this`, so a subclass element's
650
+ * props (`ThreeElements['group']`) could not be spread onto a primitive otherwise.
651
+ */
652
+ primitive: Omit<ThreeElement<typeof THREE.Object3D>, 'args' | 'object' | 'ref' | Object3DMethod> & {
653
+ object: object
654
+ ref?: React.Ref<any>
655
+ [prop: string]: unknown
656
+ }
657
+ // Conflicts with DOM types can be accessed through a three* prefix
658
+ threeAudio: ElementOf<ThreeToJSXElements<T>, 'audio'>
659
+ threeSource: ElementOf<ThreeToJSXElements<T>, 'source'>
660
+ threeLine: ElementOf<ThreeToJSXElements<T>, 'line'>
661
+ threePath: ElementOf<ThreeToJSXElements<T>, 'path'>
662
+ }
663
+
664
+ /**
665
+ * @fileoverview Registry for primary canvases that can be targeted by secondary canvases
666
+ *
667
+ * Enables multi-canvas WebGPU rendering where multiple Canvas components share
668
+ * a single WebGPURenderer using Three.js CanvasTarget API.
669
+ *
670
+ * Primary canvas: Has `id` prop, creates its own renderer, registers here
671
+ * Secondary canvas: Has `renderer={{ primaryCanvas: 'id' }}`, shares primary's renderer via CanvasTarget
672
+ */
673
+
674
+ interface PrimaryCanvasEntry {
675
+ /** The WebGPURenderer instance owned by this primary canvas */
676
+ renderer: WebGPURenderer;
677
+ /** The zustand store for this canvas */
678
+ store: RootStore;
679
+ }
680
+ /**
681
+ * Register a primary canvas that can be targeted by secondary canvases.
682
+ *
683
+ * @param id - Unique identifier for this primary canvas
684
+ * @param renderer - The WebGPURenderer owned by this canvas
685
+ * @param store - The zustand store for this canvas
686
+ * @returns Cleanup function to unregister on unmount
687
+ */
688
+ declare function registerPrimary(id: string, renderer: WebGPURenderer, store: RootStore): () => void;
689
+ /**
690
+ * Get a registered primary canvas by id.
691
+ *
692
+ * @param id - The id of the primary canvas to look up
693
+ * @returns The primary canvas entry or undefined if not found
694
+ */
695
+ declare function getPrimary(id: string): PrimaryCanvasEntry | undefined;
696
+ /**
697
+ * Wait for a primary canvas to be registered.
698
+ * Returns immediately if already registered, otherwise waits.
699
+ *
700
+ * @param id - The id of the primary canvas to wait for
701
+ * @param timeout - Optional timeout in ms (default: 5000)
702
+ * @returns Promise that resolves with the primary canvas entry
703
+ */
704
+ declare function waitForPrimary(id: string, timeout?: number): Promise<PrimaryCanvasEntry>;
705
+ /**
706
+ * Check if a primary canvas with the given id exists.
707
+ *
708
+ * @param id - The id to check
709
+ * @returns True if a primary canvas with this id is registered
710
+ */
711
+ declare function hasPrimary(id: string): boolean;
712
+ /**
713
+ * Unregister a primary canvas. Called on unmount.
714
+ *
715
+ * @param id - The id of the primary canvas to unregister
716
+ */
717
+ declare function unregisterPrimary(id: string): void;
718
+ /**
719
+ * Get all registered primary canvas ids. Useful for debugging.
720
+ */
721
+ declare function getPrimaryIds(): string[];
722
+
723
+ type EnvironmentLoaderProps = {
724
+ files?: string | string[];
725
+ path?: string;
726
+ preset?: PresetsType;
727
+ extensions?: (loader: Loader) => void;
728
+ colorSpace?: ColorSpace;
729
+ };
730
+ /**
731
+ * Loads environment textures for reflections and lighting.
732
+ * Supports HDR files, presets, and cubemaps.
733
+ *
734
+ * @example Basic usage
735
+ * ```jsx
736
+ * const texture = useEnvironment({ preset: 'sunset' })
737
+ * ```
738
+ */
739
+ declare function useEnvironment({ files, path, preset, colorSpace, extensions, }?: Partial<EnvironmentLoaderProps>): Texture$1<unknown, THREE.TextureEventMap> | CubeTexture<unknown>;
740
+ declare namespace useEnvironment {
741
+ var preload: (preloadOptions?: EnvironmentLoaderPreloadOptions) => void;
742
+ var clear: (clearOptions?: EnvironmentLoaderClearOptions) => void;
743
+ }
744
+ /**
745
+ * Options accepted by `useEnvironment.preload`.
746
+ *
747
+ * `colorSpace` is deliberately omitted: preload only warms the loader cache, and colorSpace is
748
+ * applied to the texture by `useEnvironment()` at use time, per consumer. Accepting it here would
749
+ * advertise an option this function silently ignores.
750
+ */
751
+ type EnvironmentLoaderPreloadOptions = Omit<EnvironmentLoaderProps, 'colorSpace'>;
752
+ type EnvironmentLoaderClearOptions = Pick<EnvironmentLoaderProps, 'files' | 'preset'>;
753
+
754
+ /**
755
+ * Props for Environment component that sets up global cubemap for PBR materials and backgrounds.
756
+ *
757
+ * @property children - React children to render into custom environment portal
758
+ * @property frames - Number of frames to render the environment. Use 1 for static, Infinity for animated (default: 1)
759
+ * @property near - Near clipping plane for cube camera (default: 0.1)
760
+ * @property far - Far clipping plane for cube camera (default: 1000)
761
+ * @property resolution - Resolution of the cube render target (default: 256)
762
+ * @property background - Whether to set scene.background. Can be true, false, or "only" (which only sets background) (default: false)
763
+ *
764
+ * @property blur - @deprecated Use backgroundBlurriness instead
765
+ * @property backgroundBlurriness - Blur factor between 0 and 1 for background (default: 0, requires three.js 0.146+)
766
+ * @property backgroundIntensity - Intensity factor for background (default: 1, requires three.js 0.163+)
767
+ * @property backgroundRotation - Rotation for background as Euler angles (default: [0,0,0], requires three.js 0.163+)
768
+ * @property environmentIntensity - Intensity factor for environment lighting (default: 1, requires three.js 0.163+)
769
+ * @property environmentRotation - Rotation for environment as Euler angles (default: [0,0,0], requires three.js 0.163+)
770
+ *
771
+ * @property map - Pre-existing texture to use as environment map
772
+ * @property preset - HDRI Haven preset: 'apartment', 'city', 'dawn', 'forest', 'lobby', 'night', 'park', 'studio', 'sunset', 'warehouse'. Not for production use.
773
+ * @property scene - Custom THREE.Scene or ref to apply environment to (default: uses default scene)
774
+ * @property ground - Ground projection settings. Use true for defaults or object with:
775
+ * - height: Height of camera used to create env map (default: 15)
776
+ * - radius: Radius of the world (default: 60)
777
+ * - scale: Scale of backside projected sphere (default: 1000)
778
+ *
779
+ * Additional loader props:
780
+ * @property files - File path(s) for environment. Supports .hdr, .exr, Ultra HDR .jpg, or array of 6 cube faces
781
+ * @property path - Base path for file loading
782
+ * @property extensions - Texture extensions override
783
+ */
784
+ type EnvironmentProps = {
785
+ children?: React$1.ReactNode;
786
+ frames?: number;
787
+ near?: number;
788
+ far?: number;
789
+ resolution?: number;
790
+ background?: boolean | 'only';
791
+ /** deprecated, use backgroundBlurriness */
792
+ blur?: number;
793
+ backgroundBlurriness?: number;
794
+ backgroundIntensity?: number;
795
+ backgroundRotation?: Euler;
796
+ environmentIntensity?: number;
797
+ environmentRotation?: Euler;
798
+ map?: Texture$1;
799
+ preset?: PresetsType;
800
+ scene?: Scene | React$1.RefObject<Scene>;
801
+ ground?: boolean | {
802
+ radius?: number;
803
+ height?: number;
804
+ scale?: number;
805
+ };
806
+ /** Solid color for background (alternative to files/preset) */
807
+ color?: ColorRepresentation;
808
+ /** Separate files for background (when different from environment files) */
809
+ backgroundFiles?: string | string[];
810
+ } & EnvironmentLoaderProps;
811
+ /**
812
+ * Internal component that applies a pre-existing texture as environment map.
813
+ * Sets scene.environment and optionally scene.background.
814
+ *
815
+ * @example
816
+ * ```jsx
817
+ * <CubeCamera>{(texture) => <EnvironmentMap map={texture} />}</CubeCamera>
818
+ * ```
819
+ */
820
+ declare function EnvironmentMap({ scene, background, map, ...config }: EnvironmentProps): null;
821
+ /**
822
+ * Internal component that loads environment textures from files or presets.
823
+ * Uses HDRLoader for .hdr, EXRLoader for .exr, UltraHDRLoader for .jpg/.jpeg Ultra HDR,
824
+ * or CubeTextureLoader for arrays of images.
825
+ *
826
+ * @example With preset
827
+ * ```jsx
828
+ * <EnvironmentCube preset="sunset" />
829
+ * ```
830
+ *
831
+ * @example From HDR file
832
+ * ```jsx
833
+ * <EnvironmentCube files="environment.hdr" />
834
+ * ```
835
+ *
836
+ * @example From an Ultra HDR JPEG (smallest footprint)
837
+ * ```jsx
838
+ * <EnvironmentCube files="file.jpg" />
839
+ * ```
840
+ *
841
+ * @example From cube faces
842
+ * ```jsx
843
+ * <EnvironmentCube files={['px.png', 'nx.png', 'py.png', 'ny.png', 'pz.png', 'nz.png']} />
844
+ * ```
845
+ */
846
+ declare function EnvironmentCube({ background, scene, blur, backgroundBlurriness, backgroundIntensity, backgroundRotation, environmentIntensity, environmentRotation, ...rest }: EnvironmentProps): null;
847
+ /**
848
+ * Internal component that renders custom environment using a portal and cube camera.
849
+ * Renders children into an off-buffer and films with a cube camera to create environment map.
850
+ * Can be static (frames=1) or animated (frames=Infinity).
851
+ *
852
+ * @example Custom environment with sphere
853
+ * ```jsx
854
+ * <EnvironmentPortal background near={1} far={1000} resolution={256}>
855
+ * <mesh scale={100}>
856
+ * <sphereGeometry args={[1, 64, 64]} />
857
+ * <meshBasicMaterial map={texture} side={THREE.BackSide} />
858
+ * </mesh>
859
+ * </EnvironmentPortal>
860
+ * ```
861
+ *
862
+ * @example Animated environment
863
+ * ```jsx
864
+ * <EnvironmentPortal frames={Infinity} resolution={256}>
865
+ * <Float>
866
+ * <mesh />
867
+ * </Float>
868
+ * </EnvironmentPortal>
869
+ * ```
870
+ *
871
+ * @example Mixed with preset
872
+ * ```jsx
873
+ * <EnvironmentPortal preset="warehouse">
874
+ * <mesh />
875
+ * </EnvironmentPortal>
876
+ * ```
877
+ */
878
+ 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;
879
+ /**
880
+ * Sets up a global environment map for PBR materials and backgrounds.
881
+ * Affects scene.environment and optionally scene.background unless a custom scene is passed.
882
+ *
883
+ * Supports multiple input methods:
884
+ * - **Presets**: Selection of HDRI Haven assets (apartment, city, dawn, forest, lobby, night, park, studio, sunset, warehouse)
885
+ * - **Files**: HDR (.hdr), EXR (.exr), Ultra HDR JPEG (.jpg), or cube faces (array of 6 images)
886
+ * - **Texture**: Pre-existing cube texture via `map` prop
887
+ * - **Custom Scene**: Render children into environment using portal and cube camera
888
+ * - **Ground Projection**: Project environment onto ground plane
889
+ *
890
+ * @remarks
891
+ * - Preset property is NOT meant for production and may fail (relies on CDNs)
892
+ * - Ultra HDR JPEG has the smallest file footprint
893
+ * - Use `frames={Infinity}` for animated environments with low resolution for performance
894
+ * - Ground projection places models on the "ground" within the environment map
895
+ * - Supports self-hosting with @pmndrs/assets using dynamic imports
896
+ *
897
+ * @example Basic preset usage
898
+ * ```jsx
899
+ * <Environment preset="sunset" />
900
+ * ```
901
+ *
902
+ * @example From HDR file
903
+ * ```jsx
904
+ * <Environment files="/hdr/environment.hdr" />
905
+ * ```
906
+ *
907
+ * @example From an Ultra HDR JPEG (smallest footprint)
908
+ * ```jsx
909
+ * <Environment files="file.jpg" />
910
+ * ```
911
+ *
912
+ * @example With self-hosted assets
913
+ * ```jsx
914
+ * import { suspend } from 'suspend-react'
915
+ * const city = import('@pmndrs/assets/hdri/city.exr').then(m => m.default)
916
+ *
917
+ * <Environment files={suspend(city)} />
918
+ * ```
919
+ *
920
+ * @example From existing texture
921
+ * ```jsx
922
+ * <CubeCamera>{(texture) => <Environment map={texture} />}</CubeCamera>
923
+ * ```
924
+ *
925
+ * @example Custom environment scene
926
+ * ```jsx
927
+ * <Environment background near={1} far={1000} resolution={256}>
928
+ * <mesh scale={100}>
929
+ * <sphereGeometry args={[1, 64, 64]} />
930
+ * <meshBasicMaterial map={texture} side={THREE.BackSide} />
931
+ * </mesh>
932
+ * </Environment>
933
+ * ```
934
+ *
935
+ * @example Animated environment
936
+ * ```jsx
937
+ * <Environment frames={Infinity} resolution={256}>
938
+ * <Float>
939
+ * <mesh />
940
+ * </Float>
941
+ * </Environment>
942
+ * ```
943
+ *
944
+ * @example Mixed custom scene with preset
945
+ * ```jsx
946
+ * <Environment background preset="warehouse">
947
+ * <mesh />
948
+ * </Environment>
949
+ * ```
950
+ *
951
+ * @example With ground projection
952
+ * ```jsx
953
+ * <Environment ground={{ height: 15, radius: 60 }} preset="city" />
954
+ * ```
955
+ *
956
+ * @example As background only
957
+ * ```jsx
958
+ * <Environment background="only" preset="sunset" />
959
+ * ```
960
+ *
961
+ * @example With rotation and intensity
962
+ * ```jsx
963
+ * <Environment
964
+ * background
965
+ * backgroundBlurriness={0.5}
966
+ * backgroundIntensity={0.8}
967
+ * backgroundRotation={[0, Math.PI / 2, 0]}
968
+ * environmentIntensity={1.2}
969
+ * environmentRotation={[0, Math.PI / 4, 0]}
970
+ * preset="studio"
971
+ * />
972
+ * ```
973
+ */
974
+ declare function Environment(props: EnvironmentProps): react_jsx_runtime.JSX.Element;
975
+
976
+ /**
977
+ * Moves every trace of interactivity from one object to its replacement, for reconstruction.
978
+ *
979
+ * When `args` or a `primitive`'s `object` changes, R3F builds a new three object and keeps the same
980
+ * instance. Removing the old object from the interaction state and registering the new one from
981
+ * scratch makes events *work* again (#3778), but it forgets what was in flight: a pointer resting on
982
+ * the object fires a second `onPointerEnter` without ever having left, and an active pointer capture
983
+ * is dropped mid-drag. Rewriting the references instead keeps the interaction continuous across a
984
+ * swap the user never asked to see (#3744).
985
+ *
986
+ * Captures are re-keyed rather than released, so the DOM-level capture on `captureData.target` is
987
+ * left alone — releasing and re-acquiring it is precisely the glitch being avoided.
988
+ *
989
+ * Visibility handlers are deliberately not transferred: that registry is keyed by `object.uuid`, so
990
+ * the replacement re-registers itself through `applyProps`. The old entry is dropped here so it
991
+ * cannot outlive the object it described.
992
+ */
993
+ declare function swapInteractivity(store: RootStore, object: THREE.Object3D, newObject: THREE.Object3D): void;
994
+ declare function removeInteractivity(store: RootStore, object: THREE.Object3D): void;
995
+ declare function createEvents(store: RootStore): {
996
+ handlePointer: (name: string) => (event: DomEvent) => void;
997
+ flushDeferredPointers: () => void;
998
+ processDeferredPointer: (event: DomEvent, pointerId: number) => void;
999
+ };
1000
+ /** Default R3F event manager for web */
1001
+ declare function createPointerEvents(store: RootStore): EventManager<Element>;
1002
+
1003
+ /**
1004
+ * Gets or creates a memoized loader instance from a loader constructor or returns the loader if it's already an instance.
1005
+ * This allows external code to access loader methods like abort().
1006
+ */
1007
+ declare function getLoader<L extends LoaderLike | ConstructorRepresentation<LoaderLike>>(Proto: L): L extends ConstructorRepresentation<infer T> ? T : L;
1008
+ /**
1009
+ * Synchronously loads and caches assets with a three loader.
1010
+ *
1011
+ * Note: this hook's caller must be wrapped with `React.Suspense`
1012
+ * @see https://docs.pmnd.rs/react-three-fiber/api/hooks#useloader
1013
+ */
1014
+ 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>;
1015
+ declare namespace useLoader {
1016
+ 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;
1017
+ var clear: <I extends InputLike, L extends LoaderLike | ConstructorRepresentation<LoaderLike>>(loader: L, input: I, cacheKey?: InputLike) => void;
1018
+ var loader: typeof getLoader;
1019
+ }
1020
+
1021
+ declare const IsObject: (url: unknown) => url is Record<string, string>;
1022
+ type TextureArray<T> = T extends string[] ? Texture$1[] : never;
1023
+ type TextureRecord<T> = T extends Record<string, string> ? {
1024
+ [key in keyof T]: Texture$1;
1025
+ } : never;
1026
+ type SingleTexture<T> = T extends string ? Texture$1 : never;
1027
+ type MappedTextureType<T extends string[] | string | Record<string, string>> = TextureArray<T> | TextureRecord<T> | SingleTexture<T>;
1028
+ /** Options for useTexture hook */
1029
+ type UseTextureOptions<Url extends string[] | string | Record<string, string>> = {
1030
+ /** Callback when texture(s) finish loading */
1031
+ onLoad?: (texture: MappedTextureType<Url>) => void;
1032
+ /**
1033
+ * Register the texture(s) in R3F's global texture registry for access via useTextures().
1034
+ * When true (the default):
1035
+ * - Textures persist until explicitly disposed
1036
+ * - On mount, returns existing registered textures if available (preserving modifications like colorSpace)
1037
+ *
1038
+ * Reads are taken once at mount — a mounted `useTexture` does not re-render when the registry
1039
+ * changes. To react to registry swaps, use `useTextures(s => s.get(key))` instead.
1040
+ *
1041
+ * Pass `false` to opt out of registry enrollment entirely.
1042
+ * @default true
1043
+ */
1044
+ cache?: boolean;
1045
+ };
1046
+ /**
1047
+ * Load texture(s) using Three's TextureLoader with Suspense support.
1048
+ *
1049
+ * @param input - URL string, array of URLs, or object mapping keys to URLs
1050
+ * @param optionsOrOnLoad - Options object or legacy onLoad callback
1051
+ *
1052
+ * @example
1053
+ * ```tsx
1054
+ * // Single texture
1055
+ * const diffuse = useTexture('/textures/diffuse.png')
1056
+ *
1057
+ * // Multiple textures (array)
1058
+ * const [diffuse, normal] = useTexture(['/diffuse.png', '/normal.png'])
1059
+ *
1060
+ * // Named textures (object)
1061
+ * const { diffuse, normal } = useTexture({
1062
+ * diffuse: '/diffuse.png',
1063
+ * normal: '/normal.png'
1064
+ * })
1065
+ *
1066
+ * // Textures are registered in the global registry by default — the same texture
1067
+ * // object is shared across components and modifications (colorSpace, wrapS, etc.) are preserved
1068
+ * const diffuse = useTexture('/diffuse.png')
1069
+ * diffuse.colorSpace = THREE.SRGBColorSpace
1070
+ *
1071
+ * // Another component gets the SAME texture with colorSpace already set
1072
+ * const sameDiffuse = useTexture('/diffuse.png')
1073
+ *
1074
+ * // Opt out of registry enrollment for a one-off texture
1075
+ * const scratch = useTexture('/scratch.png', { cache: false })
1076
+ *
1077
+ * // Access the registry directly
1078
+ * const { get } = useTextures()
1079
+ * const cached = get('/diffuse.png')
1080
+ * ```
1081
+ */
1082
+ declare function useTexture<Url extends string[] | string | Record<string, string>>(input: Url, optionsOrOnLoad?: UseTextureOptions<Url> | ((texture: MappedTextureType<Url>) => void)): MappedTextureType<Url>;
1083
+ declare namespace useTexture {
1084
+ var preload: (url: string | string[]) => void;
1085
+ var clear: (input: string | string[]) => void;
1086
+ }
1087
+ declare const Texture: ({ children, input, onLoad, cache, }: {
1088
+ children?: (texture: ReturnType<typeof useTexture>) => ReactNode;
1089
+ input: Parameters<typeof useTexture>[0];
1090
+ onLoad?: Parameters<typeof useTexture>[1];
1091
+ cache?: boolean;
1092
+ }) => react_jsx_runtime.JSX.Element;
1093
+
1094
+ /** Accepted shapes for a registry read: a single key, a list of keys, or a name→key map. */
1095
+ type TextureInput = string | string[] | Record<string, string>;
1096
+ /** Result of a `get()` read, mirroring the input shape. */
1097
+ type TextureResult<Input extends TextureInput> = Input extends string ? Texture$1 | undefined : Input extends string[] ? (Texture$1 | undefined)[] : {
1098
+ [K in keyof Input]: Texture$1 | undefined;
1099
+ };
1100
+ /** Options for `dispose()`. */
1101
+ interface DisposeOptions {
1102
+ /** Dispose even if the texture still has active references (default false). */
1103
+ force?: boolean;
1104
+ }
1105
+ interface UseTexturesReturn {
1106
+ /** The live registry Map (key → Texture). Treat as read-only. */
1107
+ readonly all: Map<string, Texture$1>;
1108
+ /** Read one texture, an array of textures, or a name→texture record (mirrors the input shape). */
1109
+ get<Input extends TextureInput>(input: Input): TextureResult<Input>;
1110
+ /** Check whether a key exists in the registry. */
1111
+ has(key: string): boolean;
1112
+ /**
1113
+ * Register a texture (or a record of textures) that has no URL — e.g. a render
1114
+ * target or procedural texture. URL-loaded textures are registered automatically
1115
+ * by `useTexture` (registry enrollment is on by default).
1116
+ */
1117
+ add(key: string, texture: Texture$1): void;
1118
+ add(record: Record<string, Texture$1>): void;
1119
+ /**
1120
+ * Dispose a texture's GPU resources and remove it from the registry.
1121
+ * Refcount-aware: if the key is still in use by a mounted `useTexture` consumer it is
1122
+ * skipped (with a warning) unless `{ force: true }` is passed.
1123
+ * @returns true if disposed, false if skipped.
1124
+ */
1125
+ dispose(key: string, options?: DisposeOptions): boolean;
1126
+ /** Dispose every texture in the registry and clear it. Use on scene teardown. */
1127
+ disposeAll(): void;
1128
+ }
1129
+ /**
1130
+ * Reactive Texture registry — load once with `useTexture`, reach the textures from anywhere.
1131
+ *
1132
+ * This is a registry of plain `Texture` objects (not TSL nodes), so the same texture can feed
1133
+ * a material map, a heightmap sampler, or anything else. It does **not** load — pair it with
1134
+ * `useTexture` for loading (registry enrollment is on by default); `useTextures` is for access and lifecycle.
1135
+ *
1136
+ * The returned handle is **reactive**: the calling component re-renders when the registry
1137
+ * changes. Pass a selector to scope the subscription to a single read.
1138
+ *
1139
+ * @example
1140
+ * ```tsx
1141
+ * // Load + register once (anywhere in the tree) — registered by default
1142
+ * useTexture({ map: '/diffuse.jpg', normalMap: '/normal.jpg' })
1143
+ *
1144
+ * // Reach them from another component — record form lands straight into a material
1145
+ * const { map, normalMap } = useTextures().get({ map: '/diffuse.jpg', normalMap: '/normal.jpg' })
1146
+ * return <meshStandardMaterial map={map} normalMap={normalMap} />
1147
+ *
1148
+ * // A set of heightmaps at once
1149
+ * const [a, b, c] = useTextures().get(['/h0.png', '/h1.png', '/h2.png'])
1150
+ *
1151
+ * // Register a non-URL texture (render target / procedural)
1152
+ * useTextures().add('rt-main', renderTarget.texture)
1153
+ *
1154
+ * // Deliberate GPU cleanup (refcount-aware; force to override)
1155
+ * useTextures().dispose('/diffuse.jpg')
1156
+ * useTextures().disposeAll() // scene teardown
1157
+ * ```
1158
+ *
1159
+ * @remarks
1160
+ * **Future expansion:** an imperative async loader (e.g. `await useTextures().load('/x.jpg')`) is
1161
+ * intentionally not included yet. It would let non-React code (loading screens, dynamic streaming)
1162
+ * populate the registry without Suspense, at the cost of putting loading back into this hook. It
1163
+ * will be added only if a concrete consumer needs imperative loading; for now, loading lives in
1164
+ * `useTexture`.
1165
+ */
1166
+ declare function useTextures(): UseTexturesReturn;
1167
+ declare function useTextures<T>(selector: (registry: UseTexturesReturn) => T): T;
1168
+
1169
+ /**
1170
+ * Exposes an object's {@link Instance}.
1171
+ * @see https://docs.pmnd.rs/react-three-fiber/api/additional-exports#useInstanceHandle
1172
+ *
1173
+ * **Note**: this is an escape hatch to react-internal fields. Expect this to change significantly between versions.
1174
+ */
1175
+ declare function useInstanceHandle<T>(ref: React.RefObject<T>): React.RefObject<Instance<T>>;
1176
+ /**
1177
+ * Returns a node graph of an object with named nodes & materials.
1178
+ * @see https://docs.pmnd.rs/react-three-fiber/api/hooks#usegraph
1179
+ */
1180
+ declare function useGraph(object: Object3D): ObjectMap;
1181
+
1182
+ /**
1183
+ * Adds a global render callback which is called each frame BEFORE rendering.
1184
+ *
1185
+ * @deprecated Use `useFrame(callback, { phase: 'start' })` instead.
1186
+ * This function will be removed in a future version.
1187
+ *
1188
+ * @param callback - Function called each frame with timestamp
1189
+ * @returns Unsubscribe function
1190
+ *
1191
+ * @example
1192
+ * // OLD (deprecated)
1193
+ * const unsub = addEffect((timestamp) => { ... })
1194
+ *
1195
+ * // NEW
1196
+ * useFrame((state, delta) => { ... }, { phase: 'start' })
1197
+ *
1198
+ * @see https://docs.pmnd.rs/react-three-fiber/api/additional-exports#addEffect
1199
+ */
1200
+ declare function addEffect(callback: GlobalRenderCallback): () => void;
1201
+ /**
1202
+ * Adds a global after-render callback which is called each frame AFTER rendering.
1203
+ *
1204
+ * @deprecated Use `useFrame(callback, { phase: 'finish' })` instead.
1205
+ * This function will be removed in a future version.
1206
+ *
1207
+ * @param callback - Function called each frame with timestamp
1208
+ * @returns Unsubscribe function
1209
+ *
1210
+ * @example
1211
+ * // OLD (deprecated)
1212
+ * const unsub = addAfterEffect((timestamp) => { ... })
1213
+ *
1214
+ * // NEW
1215
+ * useFrame((state, delta) => { ... }, { phase: 'finish' })
1216
+ *
1217
+ * @see https://docs.pmnd.rs/react-three-fiber/api/additional-exports#addAfterEffect
1218
+ */
1219
+ declare function addAfterEffect(callback: GlobalRenderCallback): () => void;
1220
+ /**
1221
+ * Adds a global callback which is called when rendering stops.
1222
+ *
1223
+ * @deprecated Use `scheduler.onIdle(callback)` instead.
1224
+ * This function will be removed in a future version.
1225
+ *
1226
+ * @param callback - Function called when rendering stops
1227
+ * @returns Unsubscribe function
1228
+ *
1229
+ * @example
1230
+ * // OLD (deprecated)
1231
+ * const unsub = addTail((timestamp) => { ... })
1232
+ *
1233
+ * // NEW
1234
+ * const { scheduler } = useFrame()
1235
+ * const unsub = scheduler.onIdle((timestamp) => { ... })
1236
+ *
1237
+ * @see https://docs.pmnd.rs/react-three-fiber/api/additional-exports#addTail
1238
+ */
1239
+ declare function addTail(callback: GlobalRenderCallback): () => void;
1240
+ /**
1241
+ * Invalidates the view, requesting a frame to be rendered.
1242
+ * In demand mode, this triggers the scheduler to run frames.
1243
+ *
1244
+ * With a state argument, only that root's jobs run on the requested frames; other
1245
+ * roots on 'demand' stay idle. Without one, every registered root is invalidated.
1246
+ *
1247
+ * @param state - Optional root state; targets the invalidation at that root
1248
+ * @param frames - Number of frames to request (default: 1)
1249
+ * @param stackFrames - If false, sets pendingFrames to frames. If true, adds to existing pendingFrames (default: false)
1250
+ *
1251
+ * @see https://docs.pmnd.rs/react-three-fiber/api/additional-exports#invalidate
1252
+ */
1253
+ declare function invalidate(state?: RootState, frames?: number, stackFrames?: boolean): void;
1254
+ /**
1255
+ * Advances the frameloop and runs render effects.
1256
+ * Useful for when manually rendering via `frameloop="never"`.
1257
+ *
1258
+ * With a state argument, only that root is stepped. Without one, every
1259
+ * registered root is stepped for backwards compatibility.
1260
+ *
1261
+ * @param timestamp - The timestamp to use for this frame
1262
+ * @param runGlobalEffects - Ignored (kept for backwards compat, global effects always run)
1263
+ * @param state - Optional root state; targets the manual step at that root
1264
+ *
1265
+ * @see https://docs.pmnd.rs/react-three-fiber/api/additional-exports#advance
1266
+ */
1267
+ declare function advance(timestamp: number, runGlobalEffects?: boolean, state?: RootState): void;
1268
+
1269
+ /* eslint-disable @definitelytyped/no-unnecessary-generics */
1270
+ declare function ReactReconciler<
1271
+ Type,
1272
+ Props,
1273
+ Container,
1274
+ Instance,
1275
+ TextInstance,
1276
+ SuspenseInstance,
1277
+ HydratableInstance,
1278
+ FormInstance,
1279
+ PublicInstance,
1280
+ HostContext,
1281
+ ChildSet,
1282
+ TimeoutHandle,
1283
+ NoTimeout,
1284
+ TransitionStatus,
1285
+ >(
1286
+ /* eslint-enable @definitelytyped/no-unnecessary-generics */
1287
+ config: ReactReconciler.HostConfig<
1288
+ Type,
1289
+ Props,
1290
+ Container,
1291
+ Instance,
1292
+ TextInstance,
1293
+ SuspenseInstance,
1294
+ HydratableInstance,
1295
+ FormInstance,
1296
+ PublicInstance,
1297
+ HostContext,
1298
+ ChildSet,
1299
+ TimeoutHandle,
1300
+ NoTimeout,
1301
+ TransitionStatus
1302
+ >,
1303
+ ): ReactReconciler.Reconciler<Container, Instance, TextInstance, SuspenseInstance, FormInstance, PublicInstance>;
1304
+
1305
+ declare namespace ReactReconciler {
1306
+ interface HostConfig<
1307
+ Type,
1308
+ Props,
1309
+ Container,
1310
+ Instance,
1311
+ TextInstance,
1312
+ SuspenseInstance,
1313
+ HydratableInstance,
1314
+ FormInstance,
1315
+ PublicInstance,
1316
+ HostContext,
1317
+ ChildSet,
1318
+ TimeoutHandle,
1319
+ NoTimeout,
1320
+ TransitionStatus,
1321
+ > {
1322
+ // -------------------
1323
+ // Modes
1324
+ // -------------------
1325
+ /**
1326
+ * The reconciler has two modes: mutation mode and persistent mode. You must specify one of them.
1327
+ *
1328
+ * 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.
1329
+ *
1330
+ * ```js
1331
+ * const HostConfig = {
1332
+ * // ...
1333
+ * supportsMutation: true,
1334
+ * // ...
1335
+ * }
1336
+ * ```
1337
+ *
1338
+ * Depending on the mode, the reconciler will call different methods on your host config.
1339
+ *
1340
+ * If you're not sure which one you want, you likely need the mutation mode.
1341
+ */
1342
+ supportsMutation: boolean;
1343
+
1344
+ /**
1345
+ * The reconciler has two modes: mutation mode and persistent mode. You must specify one of them.
1346
+ *
1347
+ * 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".
1348
+ *
1349
+ * ```js
1350
+ * const HostConfig = {
1351
+ * // ...
1352
+ * supportsPersistence: true,
1353
+ * // ...
1354
+ * }
1355
+ * ```
1356
+ *
1357
+ * Depending on the mode, the reconciler will call different methods on your host config.
1358
+ *
1359
+ * If you're not sure which one you want, you likely need the mutation mode.
1360
+ */
1361
+ supportsPersistence: boolean;
1362
+
1363
+ // -------------------
1364
+ // Core Methods
1365
+ // -------------------
1366
+
1367
+ /**
1368
+ * 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`.
1369
+ *
1370
+ * 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.
1371
+ *
1372
+ * 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.
1373
+ *
1374
+ * 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.
1375
+ *
1376
+ * 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.
1377
+ */
1378
+ createInstance(
1379
+ type: Type,
1380
+ props: Props,
1381
+ rootContainer: Container,
1382
+ hostContext: HostContext,
1383
+ internalHandle: OpaqueHandle,
1384
+ ): Instance;
1385
+
1386
+ /**
1387
+ * Same as `createInstance`, but for text nodes. If your renderer doesn't support text nodes, you can throw here.
1388
+ */
1389
+ createTextInstance(
1390
+ text: string,
1391
+ rootContainer: Container,
1392
+ hostContext: HostContext,
1393
+ internalHandle: OpaqueHandle,
1394
+ ): TextInstance;
1395
+
1396
+ /**
1397
+ * 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.
1398
+ *
1399
+ * 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.
1400
+ */
1401
+ appendInitialChild(parentInstance: Instance, child: Instance | TextInstance): void;
1402
+
1403
+ /**
1404
+ * 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.
1405
+ *
1406
+ * 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.
1407
+ *
1408
+ * 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.
1409
+ *
1410
+ * If you don't want to do anything here, you should return `false`.
1411
+ */
1412
+ finalizeInitialChildren(
1413
+ instance: Instance,
1414
+ type: Type,
1415
+ props: Props,
1416
+ rootContainer: Container,
1417
+ hostContext: HostContext,
1418
+ ): boolean;
1419
+
1420
+ /**
1421
+ * 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.
1422
+ *
1423
+ * 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.
1424
+ *
1425
+ * If you don't want to do anything here, you should return `false`.
1426
+ *
1427
+ * This method happens **in the render phase**. Do not mutate the tree from it.
1428
+ */
1429
+ shouldSetTextContent(type: Type, props: Props): boolean;
1430
+
1431
+ /**
1432
+ * This method lets you return the initial host context from the root of the tree. See `getChildHostContext` for the explanation of host context.
1433
+ *
1434
+ * If you don't intend to use host context, you can return `null`.
1435
+ *
1436
+ * This method happens **in the render phase**. Do not mutate the tree from it.
1437
+ */
1438
+ getRootHostContext(rootContainer: Container): HostContext | null;
1439
+
1440
+ /**
1441
+ * 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.
1442
+ *
1443
+ * 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.
1444
+ *
1445
+ * If you don't want to do anything here, return `parentHostContext`.
1446
+ *
1447
+ * This method happens **in the render phase**. Do not mutate the tree from it.
1448
+ */
1449
+ getChildHostContext(parentHostContext: HostContext, type: Type, rootContainer: Container): HostContext;
1450
+
1451
+ /**
1452
+ * 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.
1453
+ *
1454
+ * If you don't want to do anything here, return `instance`.
1455
+ */
1456
+ getPublicInstance(instance: Instance | TextInstance): PublicInstance;
1457
+
1458
+ /**
1459
+ * 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`.
1460
+ *
1461
+ * Even if you don't want to do anything here, you need to return `null` from it.
1462
+ */
1463
+ prepareForCommit(containerInfo: Container): Record<string, any> | null;
1464
+
1465
+ /**
1466
+ * 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.
1467
+ *
1468
+ * You can leave it empty.
1469
+ */
1470
+ resetAfterCommit(containerInfo: Container): void;
1471
+
1472
+ /**
1473
+ * This method is called for a container that's used as a portal target. Usually you can leave it empty.
1474
+ */
1475
+ preparePortalMount(containerInfo: Container): void;
1476
+
1477
+ /**
1478
+ * You can proxy this to `setTimeout` or its equivalent in your environment.
1479
+ */
1480
+ scheduleTimeout(fn: (...args: unknown[]) => unknown, delay?: number): TimeoutHandle;
1481
+
1482
+ /**
1483
+ * You can proxy this to `clearTimeout` or its equivalent in your environment.
1484
+ */
1485
+ cancelTimeout(id: TimeoutHandle): void;
1486
+
1487
+ /**
1488
+ * 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`.
1489
+ */
1490
+ noTimeout: NoTimeout;
1491
+
1492
+ /**
1493
+ * 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.
1494
+ */
1495
+ supportsMicrotasks?: boolean;
1496
+
1497
+ /**
1498
+ * Optional. You can proxy this to `queueMicrotask` or its equivalent in your environment.
1499
+ */
1500
+ scheduleMicrotask?(fn: () => unknown): void;
1501
+
1502
+ /**
1503
+ * 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`.
1504
+ */
1505
+ isPrimaryRenderer: boolean;
1506
+
1507
+ /**
1508
+ * Whether the renderer shouldn't trigger missing `act()` warnings
1509
+ */
1510
+ warnsIfNotActing?: boolean;
1511
+
1512
+ getInstanceFromNode(node: any): Fiber | null | undefined;
1513
+
1514
+ beforeActiveInstanceBlur(): void;
1515
+
1516
+ afterActiveInstanceBlur(): void;
1517
+
1518
+ prepareScopeUpdate(scopeInstance: any, instance: any): void;
1519
+
1520
+ getInstanceFromScope(scopeInstance: any): null | Instance;
1521
+
1522
+ detachDeletedInstance(node: Instance): void;
1523
+
1524
+ // -------------------
1525
+ // Mutation Methods
1526
+ // (optional)
1527
+ // If you're using React in mutation mode (you probably do), you'll need to implement a few more methods.
1528
+ // -------------------
1529
+
1530
+ /**
1531
+ * 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.
1532
+ *
1533
+ * 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`.
1534
+ */
1535
+ appendChild?(parentInstance: Instance, child: Instance | TextInstance): void;
1536
+
1537
+ /**
1538
+ * 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.
1539
+ */
1540
+ appendChildToContainer?(container: Container, child: Instance | TextInstance): void;
1541
+
1542
+ /**
1543
+ * 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.
1544
+ *
1545
+ * 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.
1546
+ */
1547
+ insertBefore?(
1548
+ parentInstance: Instance,
1549
+ child: Instance | TextInstance,
1550
+ beforeChild: Instance | TextInstance | SuspenseInstance,
1551
+ ): void;
1552
+
1553
+ /**
1554
+ * 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.
1555
+ */
1556
+ insertInContainerBefore?(
1557
+ container: Container,
1558
+ child: Instance | TextInstance,
1559
+ beforeChild: Instance | TextInstance | SuspenseInstance,
1560
+ ): void;
1561
+
1562
+ /**
1563
+ * This method should mutate the `parentInstance` to remove the `child` from the list of its children.
1564
+ *
1565
+ * 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.
1566
+ */
1567
+ removeChild?(parentInstance: Instance, child: Instance | TextInstance | SuspenseInstance): void;
1568
+
1569
+ /**
1570
+ * 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.
1571
+ */
1572
+ removeChildFromContainer?(container: Container, child: Instance | TextInstance | SuspenseInstance): void;
1573
+
1574
+ /**
1575
+ * 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 = ''`.
1576
+ *
1577
+ * If you never return `true` from `shouldSetTextContent`, you can leave it empty.
1578
+ */
1579
+ resetTextContent?(instance: Instance): void;
1580
+
1581
+ /**
1582
+ * This method should mutate the `textInstance` and update its text content to `nextText`.
1583
+ *
1584
+ * Here, `textInstance` is a node created by `createTextInstance`.
1585
+ */
1586
+ commitTextUpdate?(textInstance: TextInstance, oldText: string, newText: string): void;
1587
+
1588
+ /**
1589
+ * This method is only called if you returned `true` from `finalizeInitialChildren` for this instance.
1590
+ *
1591
+ * 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.
1592
+ *
1593
+ * 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.
1594
+ *
1595
+ * 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.
1596
+ *
1597
+ * If you never return `true` from `finalizeInitialChildren`, you can leave it empty.
1598
+ */
1599
+ commitMount?(instance: Instance, type: Type, props: Props, internalInstanceHandle: OpaqueHandle): void;
1600
+
1601
+ /**
1602
+ * This method should mutate the instance to match nextProps.
1603
+ *
1604
+ * 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.
1605
+ */
1606
+ commitUpdate?(
1607
+ instance: Instance,
1608
+ type: Type,
1609
+ prevProps: Props,
1610
+ nextProps: Props,
1611
+ internalHandle: OpaqueHandle,
1612
+ ): void;
1613
+
1614
+ /**
1615
+ * 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.
1616
+ */
1617
+ hideInstance?(instance: Instance): void;
1618
+
1619
+ /**
1620
+ * Same as `hideInstance`, but for nodes created by `createTextInstance`.
1621
+ */
1622
+ hideTextInstance?(textInstance: TextInstance): void;
1623
+
1624
+ /**
1625
+ * This method should make the `instance` visible, undoing what `hideInstance` did.
1626
+ */
1627
+ unhideInstance?(instance: Instance, props: Props): void;
1628
+
1629
+ /**
1630
+ * Same as `unhideInstance`, but for nodes created by `createTextInstance`.
1631
+ */
1632
+ unhideTextInstance?(textInstance: TextInstance, text: string): void;
1633
+
1634
+ /**
1635
+ * This method should mutate the `container` root node and remove all children from it.
1636
+ */
1637
+ clearContainer?(container: Container): void;
1638
+
1639
+ // -------------------
1640
+ // Persistence Methods
1641
+ // (optional)
1642
+ // 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.
1643
+ // -------------------
1644
+ cloneInstance?(
1645
+ instance: Instance,
1646
+ type: Type,
1647
+ oldProps: Props,
1648
+ newProps: Props,
1649
+ keepChildren: boolean,
1650
+ recyclableInstance: null | Instance,
1651
+ ): Instance;
1652
+ createContainerChildSet?(container: Container): ChildSet;
1653
+ appendChildToContainerChildSet?(childSet: ChildSet, child: Instance | TextInstance): void;
1654
+ finalizeContainerChildren?(container: Container, newChildren: ChildSet): void;
1655
+ replaceContainerChildren?(container: Container, newChildren: ChildSet): void;
1656
+ cloneHiddenInstance?(
1657
+ instance: Instance,
1658
+ type: Type,
1659
+ props: Props,
1660
+ internalInstanceHandle: OpaqueHandle,
1661
+ ): Instance;
1662
+ cloneHiddenTextInstance?(instance: Instance, text: Type, internalInstanceHandle: OpaqueHandle): TextInstance;
1663
+
1664
+ // -------------------
1665
+ // Hydration Methods
1666
+ // (optional)
1667
+ // 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.
1668
+ //
1669
+ // 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.
1670
+ // -------------------
1671
+ supportsHydration: boolean;
1672
+
1673
+ canHydrateInstance?(instance: HydratableInstance, type: Type, props: Props): null | Instance;
1674
+
1675
+ canHydrateTextInstance?(instance: HydratableInstance, text: string): null | TextInstance;
1676
+
1677
+ canHydrateSuspenseInstance?(instance: HydratableInstance): null | SuspenseInstance;
1678
+
1679
+ isSuspenseInstancePending?(instance: SuspenseInstance): boolean;
1680
+
1681
+ isSuspenseInstanceFallback?(instance: SuspenseInstance): boolean;
1682
+
1683
+ registerSuspenseInstanceRetry?(instance: SuspenseInstance, callback: () => void): void;
1684
+
1685
+ getNextHydratableSibling?(instance: HydratableInstance): null | HydratableInstance;
1686
+
1687
+ getFirstHydratableChild?(parentInstance: Container | Instance): null | HydratableInstance;
1688
+
1689
+ hydrateInstance?(
1690
+ instance: Instance,
1691
+ type: Type,
1692
+ props: Props,
1693
+ rootContainerInstance: Container,
1694
+ hostContext: HostContext,
1695
+ internalInstanceHandle: any,
1696
+ ): null | any[];
1697
+
1698
+ hydrateTextInstance?(textInstance: TextInstance, text: string, internalInstanceHandle: any): boolean;
1699
+
1700
+ hydrateSuspenseInstance?(suspenseInstance: SuspenseInstance, internalInstanceHandle: any): void;
1701
+
1702
+ getNextHydratableInstanceAfterSuspenseInstance?(suspenseInstance: SuspenseInstance): null | HydratableInstance;
1703
+
1704
+ // Returns the SuspenseInstance if this node is a direct child of a
1705
+ // SuspenseInstance. I.e. if its previous sibling is a Comment with
1706
+ // SUSPENSE_x_START_DATA. Otherwise, null.
1707
+ getParentSuspenseInstance?(targetInstance: any): null | SuspenseInstance;
1708
+
1709
+ commitHydratedContainer?(container: Container): void;
1710
+
1711
+ commitHydratedSuspenseInstance?(suspenseInstance: SuspenseInstance): void;
1712
+
1713
+ didNotMatchHydratedContainerTextInstance?(
1714
+ parentContainer: Container,
1715
+ textInstance: TextInstance,
1716
+ text: string,
1717
+ ): void;
1718
+
1719
+ didNotMatchHydratedTextInstance?(
1720
+ parentType: Type,
1721
+ parentProps: Props,
1722
+ parentInstance: Instance,
1723
+ textInstance: TextInstance,
1724
+ text: string,
1725
+ ): void;
1726
+
1727
+ didNotHydrateContainerInstance?(parentContainer: Container, instance: HydratableInstance): void;
1728
+
1729
+ didNotHydrateInstance?(
1730
+ parentType: Type,
1731
+ parentProps: Props,
1732
+ parentInstance: Instance,
1733
+ instance: HydratableInstance,
1734
+ ): void;
1735
+
1736
+ didNotFindHydratableContainerInstance?(parentContainer: Container, type: Type, props: Props): void;
1737
+
1738
+ didNotFindHydratableContainerTextInstance?(parentContainer: Container, text: string): void;
1739
+
1740
+ didNotFindHydratableContainerSuspenseInstance?(parentContainer: Container): void;
1741
+
1742
+ didNotFindHydratableInstance?(
1743
+ parentType: Type,
1744
+ parentProps: Props,
1745
+ parentInstance: Instance,
1746
+ type: Type,
1747
+ props: Props,
1748
+ ): void;
1749
+
1750
+ didNotFindHydratableTextInstance?(
1751
+ parentType: Type,
1752
+ parentProps: Props,
1753
+ parentInstance: Instance,
1754
+ text: string,
1755
+ ): void;
1756
+
1757
+ didNotFindHydratableSuspenseInstance?(parentType: Type, parentProps: Props, parentInstance: Instance): void;
1758
+
1759
+ errorHydratingContainer?(parentContainer: Container): void;
1760
+
1761
+ // Undocumented
1762
+ // https://github.com/facebook/react/pull/26722
1763
+ NotPendingTransition: TransitionStatus | null;
1764
+ HostTransitionContext: ReactContext<TransitionStatus>;
1765
+
1766
+ // https://github.com/facebook/react/pull/28751
1767
+ setCurrentUpdatePriority(newPriority: EventPriority): void;
1768
+ getCurrentUpdatePriority(): EventPriority;
1769
+ resolveUpdatePriority(): EventPriority;
1770
+
1771
+ // https://github.com/facebook/react/pull/28804
1772
+ resetFormInstance(form: FormInstance): void;
1773
+
1774
+ // https://github.com/facebook/react/pull/25105
1775
+ requestPostPaintCallback(callback: (time: number) => void): void;
1776
+
1777
+ // https://github.com/facebook/react/pull/26025
1778
+ shouldAttemptEagerTransition(): boolean;
1779
+
1780
+ // https://github.com/facebook/react/pull/31528
1781
+ trackSchedulerEvent(): void;
1782
+
1783
+ // https://github.com/facebook/react/pull/31008
1784
+ resolveEventType(): null | string;
1785
+ resolveEventTimeStamp(): number;
1786
+
1787
+ /**
1788
+ * 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.
1789
+ */
1790
+ maySuspendCommit(type: Type, props: Props): boolean;
1791
+
1792
+ /**
1793
+ * 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.
1794
+ */
1795
+ preloadInstance(type: Type, props: Props): boolean;
1796
+
1797
+ /**
1798
+ * 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.
1799
+ */
1800
+ startSuspendingCommit(): void;
1801
+
1802
+ /**
1803
+ * This method is called after `startSuspendingCommit` for each Host Component that indicated it might suspend a commit.
1804
+ */
1805
+ suspendInstance(type: Type, props: Props): void;
1806
+
1807
+ /**
1808
+ * This method is called after all `suspendInstance` calls are complete.
1809
+ *
1810
+ * Return `null` if the commit can happen immediately.
1811
+ *
1812
+ * 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.
1813
+ */
1814
+ waitForCommitToBeReady():
1815
+ | ((initiateCommit: (...args: unknown[]) => unknown) => (...args: unknown[]) => unknown)
1816
+ | null;
1817
+ }
1818
+
1819
+ interface Thenable<T> {
1820
+ then(resolve: () => T, reject?: () => T): T;
1821
+ }
1822
+
1823
+ type RootTag = 0 | 1 | 2;
1824
+
1825
+ type WorkTag =
1826
+ | 0
1827
+ | 1
1828
+ | 2
1829
+ | 3
1830
+ | 4
1831
+ | 5
1832
+ | 6
1833
+ | 7
1834
+ | 8
1835
+ | 9
1836
+ | 10
1837
+ | 11
1838
+ | 12
1839
+ | 13
1840
+ | 14
1841
+ | 15
1842
+ | 16
1843
+ | 17
1844
+ | 18
1845
+ | 19
1846
+ | 20
1847
+ | 21
1848
+ | 22
1849
+ | 23
1850
+ | 24;
1851
+
1852
+ type HookType =
1853
+ | "useState"
1854
+ | "useReducer"
1855
+ | "useContext"
1856
+ | "useRef"
1857
+ | "useEffect"
1858
+ | "useLayoutEffect"
1859
+ | "useCallback"
1860
+ | "useMemo"
1861
+ | "useImperativeHandle"
1862
+ | "useDebugValue"
1863
+ | "useDeferredValue"
1864
+ | "useTransition"
1865
+ | "useMutableSource"
1866
+ | "useOpaqueIdentifier"
1867
+ | "useCacheRefresh";
1868
+
1869
+ interface Source {
1870
+ fileName: string;
1871
+ lineNumber: number;
1872
+ }
1873
+
1874
+ // TODO: Ideally these types would be opaque but that doesn't work well with
1875
+ // our reconciler fork infra, since these leak into non-reconciler packages.
1876
+ type LanePriority = 0 | 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 | 14 | 15 | 16 | 17;
1877
+
1878
+ type Lanes = number;
1879
+ type Lane = number;
1880
+
1881
+ type Flags = number;
1882
+
1883
+ type TypeOfMode = number;
1884
+
1885
+ type EventPriority = number;
1886
+
1887
+ interface ReactProvider<T> {
1888
+ $$typeof: symbol | number;
1889
+ type: ReactProviderType<T>;
1890
+ key: null | string;
1891
+ ref: null;
1892
+ props: {
1893
+ value: T;
1894
+ children?: ReactNode;
1895
+ };
1896
+ }
1897
+
1898
+ interface ReactProviderType<T> {
1899
+ $$typeof: symbol | number;
1900
+ _context: ReactContext<T>;
1901
+ }
1902
+
1903
+ interface ReactConsumer<T> {
1904
+ $$typeof: symbol | number;
1905
+ type: ReactContext<T>;
1906
+ key: null | string;
1907
+ ref: null;
1908
+ props: {
1909
+ children: (value: T) => ReactNode;
1910
+ unstable_observedBits?: number;
1911
+ };
1912
+ }
1913
+
1914
+ interface ReactContext<T> {
1915
+ $$typeof: symbol | number;
1916
+ Consumer: ReactContext<T>;
1917
+ Provider: ReactProviderType<T>;
1918
+ _currentValue: T;
1919
+ _currentValue2: T;
1920
+ _threadCount: number;
1921
+ // DEV only
1922
+ _currentRenderer?: {
1923
+ [key: string]: any;
1924
+ } | null;
1925
+ _currentRenderer2?: {
1926
+ [key: string]: any;
1927
+ } | null;
1928
+ // This value may be added by application code
1929
+ // to improve DEV tooling display names
1930
+ displayName?: string;
1931
+ }
1932
+
1933
+ interface ReactPortal {
1934
+ $$typeof: symbol | number;
1935
+ key: null | string;
1936
+ containerInfo: any;
1937
+ children: ReactNode;
1938
+ // TODO: figure out the API for cross-renderer implementation.
1939
+ implementation: any;
1940
+ }
1941
+
1942
+ interface RefObject {
1943
+ current: any;
1944
+ }
1945
+
1946
+ interface ContextDependency<T> {
1947
+ context: ReactContext<T>;
1948
+ observedBits: number;
1949
+ next: ContextDependency<unknown> | null;
1950
+ }
1951
+
1952
+ interface Dependencies {
1953
+ lanes: Lanes;
1954
+ firstContext: ContextDependency<unknown> | null;
1955
+ }
1956
+
1957
+ interface Fiber {
1958
+ // These first fields are conceptually members of an Instance. This used to
1959
+ // be split into a separate type and intersected with the other Fiber fields,
1960
+ // but until Flow fixes its intersection bugs, we've merged them into a
1961
+ // single type.
1962
+
1963
+ // An Instance is shared between all versions of a component. We can easily
1964
+ // break this out into a separate object to avoid copying so much to the
1965
+ // alternate versions of the tree. We put this on a single object for now to
1966
+ // minimize the number of objects created during the initial render.
1967
+
1968
+ // Tag identifying the type of fiber.
1969
+ tag: WorkTag;
1970
+
1971
+ // Unique identifier of this child.
1972
+ key: null | string;
1973
+
1974
+ // The value of element.type which is used to preserve the identity during
1975
+ // reconciliation of this child.
1976
+ elementType: any;
1977
+
1978
+ // The resolved function/class/ associated with this fiber.
1979
+ type: any;
1980
+
1981
+ // The local state associated with this fiber.
1982
+ stateNode: any;
1983
+
1984
+ // Conceptual aliases
1985
+ // parent : Instance -> return The parent happens to be the same as the
1986
+ // return fiber since we've merged the fiber and instance.
1987
+
1988
+ // Remaining fields belong to Fiber
1989
+
1990
+ // The Fiber to return to after finishing processing this one.
1991
+ // This is effectively the parent, but there can be multiple parents (two)
1992
+ // so this is only the parent of the thing we're currently processing.
1993
+ // It is conceptually the same as the return address of a stack frame.
1994
+ return: Fiber | null;
1995
+
1996
+ // Singly Linked List Tree Structure.
1997
+ child: Fiber | null;
1998
+ sibling: Fiber | null;
1999
+ index: number;
2000
+
2001
+ // The ref last used to attach this node.
2002
+ // I'll avoid adding an owner field for prod and model that as functions.
2003
+ ref:
2004
+ | null
2005
+ | (((handle: unknown) => void) & {
2006
+ _stringRef?: string | null;
2007
+ })
2008
+ | RefObject;
2009
+
2010
+ // Input is the data coming into process this fiber. Arguments. Props.
2011
+ pendingProps: any; // This type will be more specific once we overload the tag.
2012
+ memoizedProps: any; // The props used to create the output.
2013
+
2014
+ // A queue of state updates and callbacks.
2015
+ updateQueue: unknown;
2016
+
2017
+ // The state used to create the output
2018
+ memoizedState: any;
2019
+
2020
+ // Dependencies (contexts, events) for this fiber, if it has any
2021
+ dependencies: Dependencies | null;
2022
+
2023
+ // Bitfield that describes properties about the fiber and its subtree. E.g.
2024
+ // the ConcurrentMode flag indicates whether the subtree should be async-by-
2025
+ // default. When a fiber is created, it inherits the mode of its
2026
+ // parent. Additional flags can be set at creation time, but after that the
2027
+ // value should remain unchanged throughout the fiber's lifetime, particularly
2028
+ // before its child fibers are created.
2029
+ mode: TypeOfMode;
2030
+
2031
+ // Effect
2032
+ flags: Flags;
2033
+ subtreeFlags: Flags;
2034
+ deletions: Fiber[] | null;
2035
+
2036
+ // Singly linked list fast path to the next fiber with side-effects.
2037
+ nextEffect: Fiber | null;
2038
+
2039
+ // The first and last fiber with side-effect within this subtree. This allows
2040
+ // us to reuse a slice of the linked list when we reuse the work done within
2041
+ // this fiber.
2042
+ firstEffect: Fiber | null;
2043
+ lastEffect: Fiber | null;
2044
+
2045
+ lanes: Lanes;
2046
+ childLanes: Lanes;
2047
+
2048
+ // This is a pooled version of a Fiber. Every fiber that gets updated will
2049
+ // eventually have a pair. There are cases when we can clean up pairs to save
2050
+ // memory if we need to.
2051
+ alternate: Fiber | null;
2052
+
2053
+ // Time spent rendering this Fiber and its descendants for the current update.
2054
+ // This tells us how well the tree makes use of sCU for memoization.
2055
+ // It is reset to 0 each time we render and only updated when we don't bailout.
2056
+ // This field is only set when the enableProfilerTimer flag is enabled.
2057
+ actualDuration?: number;
2058
+
2059
+ // If the Fiber is currently active in the "render" phase,
2060
+ // This marks the time at which the work began.
2061
+ // This field is only set when the enableProfilerTimer flag is enabled.
2062
+ actualStartTime?: number;
2063
+
2064
+ // Duration of the most recent render time for this Fiber.
2065
+ // This value is not updated when we bailout for memoization purposes.
2066
+ // This field is only set when the enableProfilerTimer flag is enabled.
2067
+ selfBaseDuration?: number;
2068
+
2069
+ // Sum of base times for all descendants of this Fiber.
2070
+ // This value bubbles up during the "complete" phase.
2071
+ // This field is only set when the enableProfilerTimer flag is enabled.
2072
+ treeBaseDuration?: number;
2073
+
2074
+ // Conceptual aliases
2075
+ // workInProgress : Fiber -> alternate The alternate used for reuse happens
2076
+ // to be the same as work in progress.
2077
+ // __DEV__ only
2078
+ _debugID?: number;
2079
+ _debugSource?: Source | null;
2080
+ _debugOwner?: Fiber | null;
2081
+ _debugIsCurrentlyTiming?: boolean;
2082
+ _debugNeedsRemount?: boolean;
2083
+
2084
+ // Used to verify that the order of hooks does not change between renders.
2085
+ _debugHookTypes?: HookType[] | null;
2086
+ }
2087
+
2088
+ type FiberRoot = any;
2089
+
2090
+ // Concurrent related struct
2091
+ type MutableSource = any;
2092
+
2093
+ type OpaqueHandle = any;
2094
+ type OpaqueRoot = any;
2095
+
2096
+ // 0 is PROD, 1 is DEV.
2097
+ // Might add PROFILE later.
2098
+ type BundleType = 0 | 1;
2099
+
2100
+ interface DevToolsConfig<Instance, TextInstance, RendererInspectionConfig> {
2101
+ bundleType: BundleType;
2102
+ version: string;
2103
+ rendererPackageName: string;
2104
+ // Note: this actually *does* depend on Fiber internal fields.
2105
+ // Used by "inspect clicked DOM element" in React DevTools.
2106
+ findFiberByHostInstance?: (instance: Instance | TextInstance) => Fiber | null;
2107
+ rendererConfig?: RendererInspectionConfig;
2108
+ }
2109
+
2110
+ interface SuspenseHydrationCallbacks<SuspenseInstance> {
2111
+ onHydrated?: (suspenseInstance: SuspenseInstance) => void;
2112
+ onDeleted?: (suspenseInstance: SuspenseInstance) => void;
2113
+ }
2114
+
2115
+ interface TransitionTracingCallbacks {
2116
+ onTransitionStart?: (transitionName: string, startTime: number) => void;
2117
+ onTransitionProgress?: (
2118
+ transitionName: string,
2119
+ startTime: number,
2120
+ currentTime: number,
2121
+ pending: Array<{ name: null | string }>,
2122
+ ) => void;
2123
+ onTransitionIncomplete?: (
2124
+ transitionName: string,
2125
+ startTime: number,
2126
+ deletions: Array<{
2127
+ type: string;
2128
+ name?: string;
2129
+ newName?: string;
2130
+ endTime: number;
2131
+ }>,
2132
+ ) => void;
2133
+ onTransitionComplete?: (transitionName: string, startTime: number, endTime: number) => void;
2134
+ onMarkerProgress?: (
2135
+ transitionName: string,
2136
+ marker: string,
2137
+ startTime: number,
2138
+ currentTime: number,
2139
+ pending: Array<{ name: null | string }>,
2140
+ ) => void;
2141
+ onMarkerIncomplete?: (
2142
+ transitionName: string,
2143
+ marker: string,
2144
+ startTime: number,
2145
+ deletions: Array<{
2146
+ type: string;
2147
+ name?: string;
2148
+ newName?: string;
2149
+ endTime: number;
2150
+ }>,
2151
+ ) => void;
2152
+ onMarkerComplete?: (transitionName: string, marker: string, startTime: number, endTime: number) => void;
2153
+ }
2154
+
2155
+ interface ComponentSelector {
2156
+ $$typeof: symbol | number;
2157
+ value: React$AbstractComponent<never, unknown>;
2158
+ }
2159
+
2160
+ interface HasPseudoClassSelector {
2161
+ $$typeof: symbol | number;
2162
+ value: Selector[];
2163
+ }
2164
+
2165
+ interface RoleSelector {
2166
+ $$typeof: symbol | number;
2167
+ value: string;
2168
+ }
2169
+
2170
+ interface TextSelector {
2171
+ $$typeof: symbol | number;
2172
+ value: string;
2173
+ }
2174
+
2175
+ interface TestNameSelector {
2176
+ $$typeof: symbol | number;
2177
+ value: string;
2178
+ }
2179
+
2180
+ type Selector = ComponentSelector | HasPseudoClassSelector | RoleSelector | TextSelector | TestNameSelector;
2181
+
2182
+ // TODO can not find React$AbstractComponent def
2183
+ type React$AbstractComponent<Config, Instance = any> = any;
2184
+
2185
+ interface BoundingRect {
2186
+ x: number;
2187
+ y: number;
2188
+ width: number;
2189
+ height: number;
2190
+ }
2191
+
2192
+ type IntersectionObserverOptions = any;
2193
+
2194
+ interface BaseErrorInfo {
2195
+ componentStack?: string;
2196
+ }
2197
+
2198
+ interface Reconciler<Container, Instance, TextInstance, SuspenseInstance, FormInstance, PublicInstance> {
2199
+ createContainer(
2200
+ containerInfo: Container,
2201
+ tag: RootTag,
2202
+ hydrationCallbacks: null | SuspenseHydrationCallbacks<SuspenseInstance>,
2203
+ isStrictMode: boolean,
2204
+ concurrentUpdatesByDefaultOverride: null | boolean,
2205
+ identifierPrefix: string,
2206
+ onUncaughtError: (error: Error, info: BaseErrorInfo & { errorBoundary?: Component }) => void,
2207
+ onCaughtError: (error: Error, info: BaseErrorInfo) => void,
2208
+ onRecoverableError: (error: Error, info: BaseErrorInfo) => void,
2209
+ onDefaultTransitionIndicator: () => void,
2210
+ transitionCallbacks: null | TransitionTracingCallbacks,
2211
+ ): OpaqueRoot;
2212
+
2213
+ createPortal(
2214
+ children: ReactNode,
2215
+ containerInfo: any, // TODO: figure out the API for cross-renderer implementation.
2216
+ implementation: any,
2217
+ key?: string | null,
2218
+ ): ReactPortal;
2219
+
2220
+ registerMutableSourceForHydration(root: FiberRoot, mutableSource: MutableSource): void;
2221
+
2222
+ createComponentSelector(component: React$AbstractComponent<never, unknown>): ComponentSelector;
2223
+
2224
+ createHasPseudoClassSelector(selectors: Selector[]): HasPseudoClassSelector;
2225
+
2226
+ createRoleSelector(role: string): RoleSelector;
2227
+
2228
+ createTextSelector(text: string): TextSelector;
2229
+
2230
+ createTestNameSelector(id: string): TestNameSelector;
2231
+
2232
+ getFindAllNodesFailureDescription(hostRoot: Instance, selectors: Selector[]): string | null;
2233
+
2234
+ findAllNodes(hostRoot: Instance, selectors: Selector[]): Instance[];
2235
+
2236
+ findBoundingRects(hostRoot: Instance, selectors: Selector[]): BoundingRect[];
2237
+
2238
+ focusWithin(hostRoot: Instance, selectors: Selector[]): boolean;
2239
+
2240
+ observeVisibleRects(
2241
+ hostRoot: Instance,
2242
+ selectors: Selector[],
2243
+ callback: (intersections: Array<{ ratio: number; rect: BoundingRect }>) => void,
2244
+ options?: IntersectionObserverOptions,
2245
+ ): { disconnect: () => void };
2246
+
2247
+ createHydrationContainer(
2248
+ initialChildren: ReactNode,
2249
+ callback: (() => void) | null | undefined,
2250
+ containerInfo: Container,
2251
+ tag: RootTag,
2252
+ hydrationCallbacks: null | SuspenseHydrationCallbacks<SuspenseInstance>,
2253
+ isStrictMode: boolean,
2254
+ concurrentUpdatesByDefaultOverride: null | boolean,
2255
+ identifierPrefix: string,
2256
+ onRecoverableError: (error: Error) => void,
2257
+ transitionCallbacks: null | TransitionTracingCallbacks,
2258
+ ): OpaqueRoot;
2259
+
2260
+ updateContainer(
2261
+ element: ReactNode,
2262
+ container: OpaqueRoot,
2263
+ parentComponent?: Component<any, any> | null,
2264
+ callback?: (() => void) | null,
2265
+ ): Lane;
2266
+
2267
+ batchedUpdates<A, R>(fn: (a: A) => R, a: A): R;
2268
+
2269
+ deferredUpdates<A>(fn: () => A): A;
2270
+
2271
+ 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;
2272
+
2273
+ flushControlled(fn: () => any): void;
2274
+
2275
+ flushSync(): void;
2276
+ flushSync<R>(fn: () => R): R;
2277
+
2278
+ isAlreadyRendering(): boolean;
2279
+
2280
+ flushPassiveEffects(): boolean;
2281
+
2282
+ getPublicRootInstance(container: OpaqueRoot): Component<any, any> | PublicInstance | null;
2283
+
2284
+ attemptSynchronousHydration(fiber: Fiber): void;
2285
+
2286
+ attemptDiscreteHydration(fiber: Fiber): void;
2287
+
2288
+ attemptContinuousHydration(fiber: Fiber): void;
2289
+
2290
+ attemptHydrationAtCurrentPriority(fiber: Fiber): void;
2291
+
2292
+ getCurrentUpdatePriority(): LanePriority;
2293
+
2294
+ runWithPriority<T>(priority: LanePriority, fn: () => T): T;
2295
+
2296
+ findHostInstance(component: any): PublicInstance | null;
2297
+
2298
+ findHostInstanceWithWarning(component: any, methodName: string): PublicInstance | null;
2299
+
2300
+ findHostInstanceWithNoPortals(fiber: Fiber): PublicInstance | null;
2301
+
2302
+ shouldError(fiber: Fiber): boolean | undefined;
2303
+
2304
+ shouldSuspend(fiber: Fiber): boolean;
2305
+
2306
+ injectIntoDevTools(devToolsConfig: DevToolsConfig<Instance, TextInstance, any>): boolean;
2307
+ }
2308
+ }
2309
+
2310
+ declare function extend<T extends ConstructorRepresentation>(objects: T): React$1.ExoticComponent<ThreeElement<T>>;
2311
+ declare function extend<T extends Catalogue>(objects: T): void;
2312
+ declare function extend(objects: Record<string, unknown>): void;
2313
+
2314
+ declare const reconciler: ReactReconciler.Reconciler<RootStore, Instance<any>, void, Instance<any>, never, any>;
2315
+
2316
+ declare const isRenderer: (def: any) => boolean;
2317
+ interface OffscreenCanvas extends EventTarget {
2318
+ }
2319
+ declare const _roots: Map<HTMLCanvasElement | OffscreenCanvas, Root>;
2320
+ declare function unmountComponentAtNode<TCanvas extends HTMLCanvasElement | OffscreenCanvas>(canvas: TCanvas, callback?: (canvas: TCanvas) => void): void;
2321
+ declare function createPortal(children: ReactNode, container: THREE.Object3D | RefObject<THREE.Object3D | null> | RefObject<THREE.Object3D>, state?: InjectState): JSX.Element;
2322
+ interface PortalProps {
2323
+ children: ReactNode;
2324
+ state?: InjectState;
2325
+ container: Object3D | RefObject<Object3D | null> | RefObject<Object3D>;
2326
+ }
2327
+ declare function Portal({ children, container, state }: PortalProps): JSX.Element;
2328
+ /**
2329
+ * Force React to flush any updates inside the provided callback synchronously and immediately.
2330
+ * All the same caveats documented for react-dom's `flushSync` apply here (see https://react.dev/reference/react-dom/flushSync).
2331
+ * Nevertheless, sometimes one needs to render synchronously, for example to keep DOM and 3D changes in lock-step without
2332
+ * having to revert to a non-React solution. Note: this will only flush updates within the `Canvas` root.
2333
+ */
2334
+ declare function flushSync<R>(fn: () => R): R;
2335
+
2336
+ declare const createStore: (invalidate: (state?: RootState, frames?: number, stackFrames?: boolean) => void, advance: (timestamp: number, runGlobalEffects?: boolean, state?: RootState, frame?: XRFrame) => void) => RootStore;
2337
+
2338
+ /** Whether any root has loaded a renderer yet. */
2339
+ declare function hasThree(): boolean;
2340
+ /**
2341
+ * Three's shared core: the classes and constants `three` and `three/webgpu` have in common.
2342
+ * Available once the first root's renderer support is loaded (during `configure()`), which is
2343
+ * before any element renders, any hook runs, or `onCreated` fires.
2344
+ */
2345
+ declare function getThree(): ThreeCore;
2346
+ /** Resolves with three's shared core as soon as a root has loaded one. */
2347
+ declare function whenThree(): Promise<ThreeCore>;
2348
+
2349
+ /**
2350
+ * An SSR-friendly useLayoutEffect.
2351
+ *
2352
+ * React currently throws a warning when using useLayoutEffect on the server.
2353
+ * To get around it, we can conditionally useEffect on the server (no-op) and
2354
+ * useLayoutEffect elsewhere.
2355
+ *
2356
+ * @see https://github.com/facebook/react/issues/14927
2357
+ */
2358
+ declare const useIsomorphicLayoutEffect: typeof React$1.useLayoutEffect;
2359
+ /**
2360
+ * Creates a stable ref that always contains the latest callback.
2361
+ * Useful for avoiding dependency arrays while ensuring the latest closure is called.
2362
+ *
2363
+ * @param fn - The callback function to wrap
2364
+ * @returns A ref containing the current callback
2365
+ */
2366
+ declare function useMutableCallback<T>(fn: T): React$1.RefObject<T>;
2367
+ /**
2368
+ * Bridges renderer Context and StrictMode from a primary renderer.
2369
+ * Used to maintain React context when rendering into portals or secondary canvases.
2370
+ *
2371
+ * @returns A Bridge component that wraps children with the parent renderer's context
2372
+ */
2373
+ declare function useBridge(): Bridge;
2374
+ /**
2375
+ * Internal component that blocks rendering until a promise resolves.
2376
+ * Used for suspense-like blocking behavior.
2377
+ *
2378
+ * @param set - Function to set the blocking promise
2379
+ */
2380
+ declare function Block({ set }: Omit<UnblockProps, 'children'>): null;
2381
+ /**
2382
+ * Error boundary component for catching and handling errors in the React tree.
2383
+ * Forwards errors to a state setter for external handling.
2384
+ *
2385
+ * NOTE: static members get down-level transpiled to mutations which break tree-shaking
2386
+ */
2387
+ declare const ErrorBoundary: {
2388
+ new (props: {
2389
+ set: React$1.Dispatch<Error | undefined>;
2390
+ children: React$1.ReactNode;
2391
+ }): {
2392
+ state: {
2393
+ error: boolean;
2394
+ };
2395
+ componentDidCatch(err: Error): void;
2396
+ render(): React$1.ReactNode;
2397
+ context: unknown;
2398
+ setState<K extends "error">(state: {
2399
+ error: boolean;
2400
+ } | ((prevState: Readonly<{
2401
+ error: boolean;
2402
+ }>, props: Readonly<{
2403
+ set: React$1.Dispatch<Error | undefined>;
2404
+ children: React$1.ReactNode;
2405
+ }>) => {
2406
+ error: boolean;
2407
+ } | Pick<{
2408
+ error: boolean;
2409
+ }, K> | null) | Pick<{
2410
+ error: boolean;
2411
+ }, K> | null, callback?: (() => void) | undefined): void;
2412
+ forceUpdate(callback?: (() => void) | undefined): void;
2413
+ readonly props: Readonly<{
2414
+ set: React$1.Dispatch<Error | undefined>;
2415
+ children: React$1.ReactNode;
2416
+ }>;
2417
+ componentDidMount?(): void;
2418
+ shouldComponentUpdate?(nextProps: Readonly<{
2419
+ set: React$1.Dispatch<Error | undefined>;
2420
+ children: React$1.ReactNode;
2421
+ }>, nextState: Readonly<{
2422
+ error: boolean;
2423
+ }>, nextContext: any): boolean;
2424
+ componentWillUnmount?(): void;
2425
+ getSnapshotBeforeUpdate?(prevProps: Readonly<{
2426
+ set: React$1.Dispatch<Error | undefined>;
2427
+ children: React$1.ReactNode;
2428
+ }>, prevState: Readonly<{
2429
+ error: boolean;
2430
+ }>): any;
2431
+ componentDidUpdate?(prevProps: Readonly<{
2432
+ set: React$1.Dispatch<Error | undefined>;
2433
+ children: React$1.ReactNode;
2434
+ }>, prevState: Readonly<{
2435
+ error: boolean;
2436
+ }>, snapshot?: any): void;
2437
+ componentWillMount?(): void;
2438
+ UNSAFE_componentWillMount?(): void;
2439
+ componentWillReceiveProps?(nextProps: Readonly<{
2440
+ set: React$1.Dispatch<Error | undefined>;
2441
+ children: React$1.ReactNode;
2442
+ }>, nextContext: any): void;
2443
+ UNSAFE_componentWillReceiveProps?(nextProps: Readonly<{
2444
+ set: React$1.Dispatch<Error | undefined>;
2445
+ children: React$1.ReactNode;
2446
+ }>, nextContext: any): void;
2447
+ componentWillUpdate?(nextProps: Readonly<{
2448
+ set: React$1.Dispatch<Error | undefined>;
2449
+ children: React$1.ReactNode;
2450
+ }>, nextState: Readonly<{
2451
+ error: boolean;
2452
+ }>, nextContext: any): void;
2453
+ UNSAFE_componentWillUpdate?(nextProps: Readonly<{
2454
+ set: React$1.Dispatch<Error | undefined>;
2455
+ children: React$1.ReactNode;
2456
+ }>, nextState: Readonly<{
2457
+ error: boolean;
2458
+ }>, nextContext: any): void;
2459
+ };
2460
+ new (props: {
2461
+ set: React$1.Dispatch<Error | undefined>;
2462
+ children: React$1.ReactNode;
2463
+ }, context: any): {
2464
+ state: {
2465
+ error: boolean;
2466
+ };
2467
+ componentDidCatch(err: Error): void;
2468
+ render(): React$1.ReactNode;
2469
+ context: unknown;
2470
+ setState<K extends "error">(state: {
2471
+ error: boolean;
2472
+ } | ((prevState: Readonly<{
2473
+ error: boolean;
2474
+ }>, props: Readonly<{
2475
+ set: React$1.Dispatch<Error | undefined>;
2476
+ children: React$1.ReactNode;
2477
+ }>) => {
2478
+ error: boolean;
2479
+ } | Pick<{
2480
+ error: boolean;
2481
+ }, K> | null) | Pick<{
2482
+ error: boolean;
2483
+ }, K> | null, callback?: (() => void) | undefined): void;
2484
+ forceUpdate(callback?: (() => void) | undefined): void;
2485
+ readonly props: Readonly<{
2486
+ set: React$1.Dispatch<Error | undefined>;
2487
+ children: React$1.ReactNode;
2488
+ }>;
2489
+ componentDidMount?(): void;
2490
+ shouldComponentUpdate?(nextProps: Readonly<{
2491
+ set: React$1.Dispatch<Error | undefined>;
2492
+ children: React$1.ReactNode;
2493
+ }>, nextState: Readonly<{
2494
+ error: boolean;
2495
+ }>, nextContext: any): boolean;
2496
+ componentWillUnmount?(): void;
2497
+ getSnapshotBeforeUpdate?(prevProps: Readonly<{
2498
+ set: React$1.Dispatch<Error | undefined>;
2499
+ children: React$1.ReactNode;
2500
+ }>, prevState: Readonly<{
2501
+ error: boolean;
2502
+ }>): any;
2503
+ componentDidUpdate?(prevProps: Readonly<{
2504
+ set: React$1.Dispatch<Error | undefined>;
2505
+ children: React$1.ReactNode;
2506
+ }>, prevState: Readonly<{
2507
+ error: boolean;
2508
+ }>, snapshot?: any): void;
2509
+ componentWillMount?(): void;
2510
+ UNSAFE_componentWillMount?(): void;
2511
+ componentWillReceiveProps?(nextProps: Readonly<{
2512
+ set: React$1.Dispatch<Error | undefined>;
2513
+ children: React$1.ReactNode;
2514
+ }>, nextContext: any): void;
2515
+ UNSAFE_componentWillReceiveProps?(nextProps: Readonly<{
2516
+ set: React$1.Dispatch<Error | undefined>;
2517
+ children: React$1.ReactNode;
2518
+ }>, nextContext: any): void;
2519
+ componentWillUpdate?(nextProps: Readonly<{
2520
+ set: React$1.Dispatch<Error | undefined>;
2521
+ children: React$1.ReactNode;
2522
+ }>, nextState: Readonly<{
2523
+ error: boolean;
2524
+ }>, nextContext: any): void;
2525
+ UNSAFE_componentWillUpdate?(nextProps: Readonly<{
2526
+ set: React$1.Dispatch<Error | undefined>;
2527
+ children: React$1.ReactNode;
2528
+ }>, nextState: Readonly<{
2529
+ error: boolean;
2530
+ }>, nextContext: any): void;
2531
+ };
2532
+ getDerivedStateFromError: () => {
2533
+ error: boolean;
2534
+ };
2535
+ contextType?: React$1.Context<any> | undefined;
2536
+ propTypes?: any;
2537
+ };
2538
+
2539
+ /**
2540
+ * React internal props that should not be passed to Three.js objects.
2541
+ */
2542
+ declare const REACT_INTERNAL_PROPS: string[];
2543
+ /**
2544
+ * Returns the instance's initial (outermost) root.
2545
+ * Traverses through previousRoot links to find the original root store.
2546
+ *
2547
+ * @param instance - R3F instance to find root for
2548
+ * @returns The outermost root store
2549
+ */
2550
+ declare function findInitialRoot<T>(instance: Instance<T>): RootStore;
2551
+ /**
2552
+ * Returns instance root state.
2553
+ * If the object doesn't have __r3f (e.g., child meshes in primitives/GLTFs),
2554
+ * traverses ancestors to find the nearest managed parent.
2555
+ *
2556
+ * @param obj - Three.js object to get root state for
2557
+ * @returns Root state if found, undefined otherwise
2558
+ */
2559
+ declare function getRootState<T extends THREE.Object3D = THREE.Object3D>(obj: T): RootState | undefined;
2560
+ /**
2561
+ * Collects nodes, materials, and meshes from a Three.js Object3D hierarchy.
2562
+ * Handles duplicate material names by appending UUID prefixes.
2563
+ *
2564
+ * @param object - Root object to traverse
2565
+ * @returns ObjectMap containing named nodes, materials, and meshes
2566
+ *
2567
+ * @example
2568
+ * const { nodes, materials, meshes } = buildGraph(gltf.scene)
2569
+ * // Access by name: nodes.Head, materials.Metal, meshes.Body
2570
+ */
2571
+ declare function buildGraph(object: THREE.Object3D): ObjectMap;
2572
+ /**
2573
+ * Disposes an object and all its disposable properties.
2574
+ * Skips Scene objects as they should not be disposed automatically.
2575
+ *
2576
+ * @param obj - Object to dispose
2577
+ */
2578
+ declare function dispose<T extends Disposable>(obj: T): void;
2579
+ /**
2580
+ * Extracts instance props from React reconciler fiber props.
2581
+ * Filters out React-internal props (children, key, ref).
2582
+ *
2583
+ * @param queue - Pending props from reconciler fiber
2584
+ * @returns Props object without React-internal keys
2585
+ */
2586
+ declare function getInstanceProps<T = any>(pendingProps: Record<string, unknown>): Instance<T>['props'];
2587
+ /**
2588
+ * Creates or retrieves an R3F instance descriptor for a Three.js object.
2589
+ * Each object in the scene carries a LocalState descriptor (__r3f).
2590
+ *
2591
+ * @param target - Target object to prepare
2592
+ * @param root - Root store for this instance
2593
+ * @param type - String identifier for the object type
2594
+ * @param props - Initial props for the instance
2595
+ * @returns Instance descriptor
2596
+ */
2597
+ declare function prepare<T = any>(target: T, root: RootStore, type: string, props: Instance<T>['props']): Instance<T>;
2598
+ /**
2599
+ * Triggers an update for an instance.
2600
+ * Invalidates the frame if the root is in demand mode.
2601
+ *
2602
+ * @param instance - Instance to invalidate
2603
+ */
2604
+ declare function invalidateInstance(instance: Instance): void;
2605
+
2606
+ /**
2607
+ * Reserved prop names that should not be applied to Three.js objects.
2608
+ */
2609
+ declare const RESERVED_PROPS: string[];
2610
+ /**
2611
+ * Resolves a potentially pierced property key (e.g., 'material-color' → material.color).
2612
+ * First tries the entire key as a single property, then attempts piercing.
2613
+ *
2614
+ * @param root - Root object to resolve from
2615
+ * @param key - Property key (may contain dashes for piercing)
2616
+ * @returns Object containing root, key, and target value
2617
+ *
2618
+ * @example
2619
+ * resolve(mesh, 'material-color')
2620
+ * // => { root: mesh.material, key: 'color', target: mesh.material.color }
2621
+ */
2622
+ declare function resolve(root: any, key: string): {
2623
+ root: any;
2624
+ key: string;
2625
+ target: any;
2626
+ };
2627
+ /**
2628
+ * Attaches a child instance to a parent instance.
2629
+ * Handles both string-based attachment (e.g., 'geometry', 'material-map')
2630
+ * and function-based attachment for custom logic.
2631
+ *
2632
+ * @param parent - Parent instance
2633
+ * @param child - Child instance to attach
2634
+ *
2635
+ * @example
2636
+ * // String attachment
2637
+ * <bufferGeometry attach="geometry" />
2638
+ * // Array attachment
2639
+ * <light attach="lights-0" />
2640
+ * // Function attachment
2641
+ * <thing attach={(parent, self) => { parent.customProp = self }} />
2642
+ */
2643
+ declare function attach(parent: Instance, child: Instance): void;
2644
+ /**
2645
+ * Detaches a child instance from a parent instance.
2646
+ * Restores the previous value or deletes the property if it was never set.
2647
+ *
2648
+ * @param parent - Parent instance
2649
+ * @param child - Child instance to detach
2650
+ */
2651
+ declare function detach(parent: Instance, child: Instance): void;
2652
+ /**
2653
+ * Compares old and new props to determine which properties have changed.
2654
+ * Also handles resetting removed props for HMR/fast-refresh.
2655
+ *
2656
+ * @param instance - Instance to diff props for
2657
+ * @param newProps - New props to compare against
2658
+ * @returns Object containing only changed props
2659
+ *
2660
+ * @example
2661
+ * const changes = diffProps(instance, { position: [1, 2, 3], color: 'red' })
2662
+ * // => { position: [1, 2, 3] } (only if position changed)
2663
+ */
2664
+ declare function diffProps<T = any>(instance: Instance<T>, newProps: Instance<T>['props']): Instance<T>['props'];
2665
+ /**
2666
+ * Applies a set of props to a Three.js object.
2667
+ * Handles special cases like colors, vectors, textures, events, and pierced props.
2668
+ *
2669
+ * @param object - Three.js object to apply props to
2670
+ * @param props - Props to apply
2671
+ * @returns The object with props applied
2672
+ *
2673
+ * @example
2674
+ * applyProps(mesh, { position: [0, 1, 0], 'material-color': 'red' })
2675
+ */
2676
+ declare function applyProps<T = any>(object: Instance<T>['object'], props: Instance<T>['props']): Instance<T>['object'];
2677
+
2678
+ /**
2679
+ * Calculates the device pixel ratio for rendering.
2680
+ * Handles array DPR ranges [min, max] to clamp devicePixelRatio.
2681
+ *
2682
+ * @param dpr - Target DPR value or [min, max] range
2683
+ * @returns Calculated DPR value
2684
+ *
2685
+ * @example
2686
+ * calculateDpr(2) // => 2
2687
+ * calculateDpr([1, 2]) // => clamps window.devicePixelRatio between 1 and 2
2688
+ */
2689
+ declare function calculateDpr(dpr: Dpr): number;
2690
+ /**
2691
+ * Extracts the first segment of a UUID string (before the first hyphen).
2692
+ * Used for creating unique material names when duplicates exist.
2693
+ *
2694
+ * @param uuid - UUID string to extract prefix from
2695
+ * @returns First segment of the UUID
2696
+ *
2697
+ * @example
2698
+ * getUuidPrefix('a1b2c3d4-e5f6-g7h8-i9j0') // => 'a1b2c3d4'
2699
+ */
2700
+ declare function getUuidPrefix(uuid: string): string;
2701
+ /**
2702
+ * Updates camera projection based on viewport size.
2703
+ * Adjusts aspect ratio for perspective cameras or bounds for orthographic cameras.
2704
+ * Respects camera.manual flag - manual cameras are not modified.
2705
+ *
2706
+ * @param camera - Camera to update
2707
+ * @param size - Current viewport size
2708
+ */
2709
+ declare function updateCamera(camera: ThreeCamera, size: Size): void;
2710
+ /**
2711
+ * Updates a frustum from a camera's projection and world matrices.
2712
+ * If no target frustum is provided, creates and returns a new one.
2713
+ *
2714
+ * @param camera - Camera to extract frustum from
2715
+ * @param frustum - Optional existing frustum to update (creates new if not provided)
2716
+ * @returns The updated or newly created frustum
2717
+ *
2718
+ * @example
2719
+ * // Create new frustum
2720
+ * const frustum = updateFrustum(camera)
2721
+ *
2722
+ * // Update existing frustum (no allocation)
2723
+ * updateFrustum(camera, existingFrustum)
2724
+ *
2725
+ * // Use for visibility checks
2726
+ * if (frustum.containsPoint(point)) { ... }
2727
+ * if (frustum.intersectsObject(mesh)) { ... }
2728
+ */
2729
+ declare function updateFrustum(camera: ThreeCamera, frustum?: THREE.Frustum): THREE.Frustum;
2730
+
2731
+ declare const is: {
2732
+ obj: (a: any) => boolean;
2733
+ fun: (a: any) => a is Function;
2734
+ str: (a: any) => a is string;
2735
+ num: (a: any) => a is number;
2736
+ boo: (a: any) => a is boolean;
2737
+ und: (a: any) => boolean;
2738
+ nul: (a: any) => boolean;
2739
+ arr: (a: any) => a is any[];
2740
+ equ(a: any, b: any, { arrays, objects, strict }?: EquConfig): boolean;
2741
+ };
2742
+ declare const isOrthographicCamera: (def: ThreeCamera) => def is THREE.OrthographicCamera;
2743
+ declare const isRef: (obj: unknown) => obj is React.RefObject<unknown>;
2744
+ declare const isColorRepresentation: (value: unknown) => value is THREE.ColorRepresentation;
2745
+ declare const isObject3D: (object: any) => object is THREE.Object3D;
2746
+ declare const isTexture: (value: unknown) => value is THREE.Texture;
2747
+ declare const isLayers: (value: unknown) => value is THREE.Layers;
2748
+ declare const isUniform: (value: unknown) => value is THREE.Uniform;
2749
+ type VectorLike = {
2750
+ set: (...args: any[]) => void;
2751
+ constructor?: Function;
2752
+ };
2753
+ declare const isVectorLike: (object: unknown) => object is VectorLike;
2754
+ type Copyable = {
2755
+ copy: (...args: any[]) => void;
2756
+ constructor?: Function;
2757
+ };
2758
+ declare const isCopyable: (object: unknown) => object is Copyable;
2759
+ declare const hasConstructor: (object: unknown) => object is {
2760
+ constructor?: Function;
2761
+ };
2762
+
2763
+ /**
2764
+ * Symbol marker for deferred ref resolution.
2765
+ * Used to identify values that should be resolved from refs after mount.
2766
+ */
2767
+ declare const FROM_REF: unique symbol;
2768
+ /** The marker `fromRef()` returns; resolved by the reconciler in `commitMount`. */
2769
+ interface FromRefMarker<T = unknown, R = T> {
2770
+ [FROM_REF]: React$1.RefObject<T | null>;
2771
+ /** Optional transform applied to the resolved ref before assignment. */
2772
+ transform?: (value: T) => R;
2773
+ }
2774
+ /**
2775
+ * Defers prop application until the referenced object is available.
2776
+ * Useful for props like `target` that need sibling refs to be populated.
2777
+ *
2778
+ * Only top-level props on a three element are resolved: a marker nested inside another value
2779
+ * (an array, an options object) is never seen. When the prop needs the sibling *wrapped* rather
2780
+ * than assigned as-is, pass a `transform`; it runs once the ref is populated and its result is
2781
+ * what gets assigned.
2782
+ *
2783
+ * @param ref - React ref object to resolve at mount time
2784
+ * @param transform - Optional mapping from the resolved object to the value the prop expects
2785
+ * @returns A marker value that the reconciler resolves after mount
2786
+ *
2787
+ * @example
2788
+ * const targetRef = useRef<THREE.Object3D>(null)
2789
+ *
2790
+ * <group ref={targetRef} position={[-3, -2, -15]} />
2791
+ * <spotLight target={fromRef(targetRef)} intensity={100} />
2792
+ *
2793
+ * @example
2794
+ * // Wrap the sibling: a node material's lightsNode needs a LightsNode, not the light itself
2795
+ * <meshPhongNodeMaterial lightsNode={fromRef(lightRef, (light) => lights([light]))} />
2796
+ */
2797
+ declare function fromRef<T>(ref: React$1.RefObject<T | null>): T;
2798
+ declare function fromRef<T, R>(ref: React$1.RefObject<T | null>, transform: (value: T) => R): R;
2799
+ /**
2800
+ * Type guard to check if a value is a fromRef marker.
2801
+ *
2802
+ * @param value - Value to check
2803
+ * @returns True if value is a fromRef marker
2804
+ */
2805
+ declare function isFromRef(value: unknown): value is FromRefMarker<any, unknown>;
2806
+
2807
+ /**
2808
+ * Symbol marker for mount-only method calls.
2809
+ * Used to identify methods that should only be called once on initial mount.
2810
+ */
2811
+ declare const ONCE: unique symbol;
2812
+ /**
2813
+ * Marks a method call to be executed only on initial mount.
2814
+ * Useful for geometry transforms that should not be reapplied on every render.
2815
+ *
2816
+ * When `args` prop changes (triggering reconstruction), the method will be
2817
+ * called again on the new instance since appliedOnce is not carried over.
2818
+ *
2819
+ * @param args - Arguments to pass to the method
2820
+ * @returns A marker value that applyProps will execute once
2821
+ *
2822
+ * @example
2823
+ * // Rotate geometry on mount
2824
+ * <boxGeometry args={[1, 1, 1]} rotateX={once(Math.PI / 2)} />
2825
+ *
2826
+ * // Multiple arguments
2827
+ * <bufferGeometry applyMatrix4={once(matrix)} />
2828
+ *
2829
+ * // No arguments
2830
+ * <geometry center={once()} />
2831
+ */
2832
+ declare function once<A extends unknown[]>(...args: A): OnceValue<A>;
2833
+ /**
2834
+ * What `once(...args)` is typed as, so the marker is assignable to the prop it targets:
2835
+ * the single argument itself (`rotateX={once(angle)}`), the argument tuple for multi-argument
2836
+ * methods (`translate={once(x, y, z)}`), or `true` for a bare call (`center={once()}`).
2837
+ *
2838
+ * The runtime value is always the marker object; only the declared type follows the prop.
2839
+ */
2840
+ type OnceValue<A extends unknown[]> = A extends [] ? true : A extends [infer Single] ? Single : A;
2841
+ /**
2842
+ * Type guard to check if a value is a once marker.
2843
+ *
2844
+ * @param value - Value to check
2845
+ * @returns True if value is a once marker
2846
+ */
2847
+ declare function isOnce(value: unknown): value is {
2848
+ [ONCE]: any[] | true;
2849
+ };
2850
+
2851
+ export { getThree as B, hasThree as D, whenThree as F, _roots as a$, swapInteractivity as aB, removeInteractivity as aC, createEvents as aD, useInstanceHandle as aE, useGraph as aF, useLoader as aG, IsObject as aH, useTexture as aK, Texture as aL, useTextures as aQ, useEnvironment as aS, addEffect as aT, addAfterEffect as aU, addTail as aV, invalidate as aW, advance as aX, extend as aY, reconciler as aZ, isRenderer as a_, registerPrimary as ao, getPrimary as ap, waitForPrimary as aq, hasPrimary as ar, unregisterPrimary as as, getPrimaryIds as at, EnvironmentMap as av, EnvironmentCube as aw, EnvironmentPortal as ax, Environment as ay, presetsObj as az, unmountComponentAtNode as b0, createPortal as b1, Portal as b2, flushSync as b3, createStore as b4, useIsomorphicLayoutEffect as b5, useMutableCallback as b6, useBridge as b7, Block as b8, ErrorBoundary as b9, isVectorLike as bA, isCopyable as bB, hasConstructor as bC, FROM_REF as bD, fromRef as bF, isFromRef as bG, ONCE as bH, once as bI, isOnce as bK, REACT_INTERNAL_PROPS as ba, findInitialRoot as bb, getRootState as bc, buildGraph as bd, dispose as be, getInstanceProps as bf, prepare as bg, invalidateInstance as bh, RESERVED_PROPS as bi, resolve as bj, attach as bk, detach as bl, diffProps as bm, applyProps as bn, calculateDpr as bo, getUuidPrefix as bp, updateCamera as bq, updateFrustum as br, is as bs, isOrthographicCamera as bt, isRef as bu, isColorRepresentation as bv, isObject3D as bw, isTexture as bx, isLayers as by, isUniform as bz, createPointerEvents as w };
2852
+ export type { CameraProps as $, WebGLShadowConfig as A, Color as C, Euler as E, GeometryTransformProps as G, OffscreenCanvas$1 as H, BaseRendererProps as I, RendererFactory as J, Renderer as K, Layers as L, MutableOrReadonlyParameters as M, NodeProps as N, Object3DMethod as O, ColorManagementConfig as P, Quaternion as Q, RaycastableRepresentation as R, DefaultGLProps as S, TSLNodeInput as T, GLProps as U, VectorRepresentation as V, WebGLProps as W, DefaultRendererProps as X, CanvasSchedulerConfig as Y, RendererConfigExtended as Z, RendererProps as _, MathRepresentation as a, RenderProps as a0, InjectState as a1, FiberRoot as a2, Root as a3, AttachFnType as a4, AttachType as a5, Catalogue as a6, Args as a7, ArgsProp as a8, InstanceProps as a9, PresetsType as aA, MappedTextureType as aI, UseTextureOptions as aJ, TextureInput as aM, TextureResult as aN, DisposeOptions as aO, UseTexturesReturn as aP, EnvironmentLoaderProps as aR, Instance as aa, HostConfig as ab, GlobalRenderCallback as ac, GlobalEffectType as ad, BackgroundConfig as ae, BackgroundProp as af, InputLike as ag, LoaderLike as ah, GLTFLike as ai, LoaderInstance as aj, InferLoadResult as ak, LoaderResult as al, Extensions as am, PrimaryCanvasEntry as an, EnvironmentProps as au, MathTypes as b, FromRefMarker as bE, OnceValue as bJ, MathType as c, MathProps as d, Vector2 as e, Vector3 as f, Vector4 as g, Matrix3 as h, Matrix4 as i, EventProps as j, GeometryProps as k, ReactProps as l, ConstructorRepresentation as m, ElementProps as n, ThreeElement as o, ThreeToJSXElements as p, ThreeElementsOf as q, ElementOf as r, CanvasProps as s, LegacyRootState as t, ReconcilerRoot as u, RenderTargetOptions as v, LegacyInternalState as x, LegacyRenderer as y, WebGLDefaultProps as z };