@hozo/three 0.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (91) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +389 -0
  3. package/conformance.md +335 -0
  4. package/dist/accessible-controls.d.ts +55 -0
  5. package/dist/accessible-controls.d.ts.map +1 -0
  6. package/dist/accessible-controls.js +82 -0
  7. package/dist/accessible-controls.js.map +1 -0
  8. package/dist/conformance-scenes.d.ts +39 -0
  9. package/dist/conformance-scenes.d.ts.map +1 -0
  10. package/dist/conformance-scenes.js +443 -0
  11. package/dist/conformance-scenes.js.map +1 -0
  12. package/dist/index.d.ts +4 -0
  13. package/dist/index.d.ts.map +1 -0
  14. package/dist/index.js +3 -0
  15. package/dist/index.js.map +1 -0
  16. package/dist/line-gradient.d.ts +13 -0
  17. package/dist/line-gradient.d.ts.map +1 -0
  18. package/dist/line-gradient.js +104 -0
  19. package/dist/line-gradient.js.map +1 -0
  20. package/dist/project.d.ts +23 -0
  21. package/dist/project.d.ts.map +1 -0
  22. package/dist/project.js +2298 -0
  23. package/dist/project.js.map +1 -0
  24. package/dist/r3f-accessibility.d.ts +30 -0
  25. package/dist/r3f-accessibility.d.ts.map +1 -0
  26. package/dist/r3f-accessibility.js +4 -0
  27. package/dist/r3f-accessibility.js.map +1 -0
  28. package/dist/r3f-native-unavailable.d.ts +5 -0
  29. package/dist/r3f-native-unavailable.d.ts.map +1 -0
  30. package/dist/r3f-native-unavailable.js +5 -0
  31. package/dist/r3f-native-unavailable.js.map +1 -0
  32. package/dist/r3f-native.d.ts +23 -0
  33. package/dist/r3f-native.d.ts.map +1 -0
  34. package/dist/r3f-native.js +66 -0
  35. package/dist/r3f-native.js.map +1 -0
  36. package/dist/r3f-react-native.d.ts +5 -0
  37. package/dist/r3f-react-native.d.ts.map +1 -0
  38. package/dist/r3f-react-native.js +5 -0
  39. package/dist/r3f-react-native.js.map +1 -0
  40. package/dist/r3f.d.ts +39 -0
  41. package/dist/r3f.d.ts.map +1 -0
  42. package/dist/r3f.js +41 -0
  43. package/dist/r3f.js.map +1 -0
  44. package/dist/surface.d.ts +81 -0
  45. package/dist/surface.d.ts.map +1 -0
  46. package/dist/surface.js +79 -0
  47. package/dist/surface.js.map +1 -0
  48. package/dist/three-canvas.d.ts +42 -0
  49. package/dist/three-canvas.d.ts.map +1 -0
  50. package/dist/three-canvas.js +91 -0
  51. package/dist/three-canvas.js.map +1 -0
  52. package/dist/web-surface.d.ts +55 -0
  53. package/dist/web-surface.d.ts.map +1 -0
  54. package/dist/web-surface.js +285 -0
  55. package/dist/web-surface.js.map +1 -0
  56. package/dist/webgl-react-native.d.ts +5 -0
  57. package/dist/webgl-react-native.d.ts.map +1 -0
  58. package/dist/webgl-react-native.js +5 -0
  59. package/dist/webgl-react-native.js.map +1 -0
  60. package/dist/webgl-renderer.d.ts +14 -0
  61. package/dist/webgl-renderer.d.ts.map +1 -0
  62. package/dist/webgl-renderer.js +13 -0
  63. package/dist/webgl-renderer.js.map +1 -0
  64. package/dist/webgpu-react-native.d.ts +5 -0
  65. package/dist/webgpu-react-native.d.ts.map +1 -0
  66. package/dist/webgpu-react-native.js +5 -0
  67. package/dist/webgpu-react-native.js.map +1 -0
  68. package/dist/webgpu.d.ts +18 -0
  69. package/dist/webgpu.d.ts.map +1 -0
  70. package/dist/webgpu.js +29 -0
  71. package/dist/webgpu.js.map +1 -0
  72. package/package.json +122 -0
  73. package/scene-conformance.json +244 -0
  74. package/scene-conformance.md +31 -0
  75. package/src/accessible-controls.ts +84 -0
  76. package/src/conformance-scenes.ts +529 -0
  77. package/src/index.ts +24 -0
  78. package/src/line-gradient.ts +134 -0
  79. package/src/project.ts +2742 -0
  80. package/src/r3f-accessibility.ts +37 -0
  81. package/src/r3f-native-unavailable.tsx +15 -0
  82. package/src/r3f-native.tsx +187 -0
  83. package/src/r3f-react-native.tsx +17 -0
  84. package/src/r3f.tsx +159 -0
  85. package/src/surface.ts +178 -0
  86. package/src/three-canvas.tsx +215 -0
  87. package/src/web-surface.tsx +475 -0
  88. package/src/webgl-react-native.tsx +17 -0
  89. package/src/webgl-renderer.tsx +56 -0
  90. package/src/webgpu-react-native.tsx +17 -0
  91. package/src/webgpu.tsx +71 -0
@@ -0,0 +1,37 @@
1
+ import type { RefObject } from 'react'
2
+ import type { Object3D } from 'three'
3
+
4
+ export type R3FAccessibleObjectTarget = Object3D | RefObject<Object3D | null>
5
+
6
+ interface R3FAccessibleObjectBase {
7
+ /** Stable identity and semantic-control order are owned by the application. */
8
+ id: string
9
+ label: string
10
+ object: R3FAccessibleObjectTarget
11
+ disabled?: boolean
12
+ /** Stable selector for Native device automation and Web accessibility tests. */
13
+ testID?: string
14
+ }
15
+
16
+ export interface R3FAccessibleObjectEvent {
17
+ id: string
18
+ object: Object3D
19
+ }
20
+
21
+ export type R3FAccessibleObject =
22
+ | (R3FAccessibleObjectBase & {
23
+ href?: never
24
+ external?: never
25
+ replace?: never
26
+ onPress: (event: R3FAccessibleObjectEvent) => void
27
+ })
28
+ | (R3FAccessibleObjectBase & {
29
+ href: string
30
+ external?: boolean
31
+ replace?: boolean
32
+ onPress?: never
33
+ })
34
+
35
+ export function resolveR3FAccessibleObject(target: R3FAccessibleObjectTarget) {
36
+ return 'current' in target ? target.current : target
37
+ }
@@ -0,0 +1,15 @@
1
+ import type { ThreeCanvasProps } from './r3f-native.tsx'
2
+
3
+ export type {
4
+ R3FAccessibleObject,
5
+ R3FAccessibleObjectEvent,
6
+ R3FAccessibleObjectTarget,
7
+ ThreeCanvasProps,
8
+ } from './r3f-native.tsx'
9
+
10
+ /** The Expo GL host is deliberately available only to React Native resolution. */
11
+ export function ThreeCanvas(_props: ThreeCanvasProps): never {
12
+ throw new Error(
13
+ '@hozo/three/r3f-native requires React Native with Expo GL. Web applications should import @hozo/three/r3f, @hozo/three/webgl, or @hozo/three/webgpu.',
14
+ )
15
+ }
@@ -0,0 +1,187 @@
1
+ import type { CanvasAccessibilityProps } from '@hozo/canvas'
2
+ import { activateHozoNavigation, useHozoNavigation } from '@hozo/engine/navigation'
3
+ import {
4
+ Canvas as FiberCanvas,
5
+ type CanvasProps as FiberCanvasProps,
6
+ } from '@react-three/fiber/native'
7
+ import type { ReactNode } from 'react'
8
+ import {
9
+ Linking,
10
+ Pressable,
11
+ type StyleProp,
12
+ StyleSheet,
13
+ Text,
14
+ View,
15
+ type ViewStyle,
16
+ } from 'react-native'
17
+
18
+ import {
19
+ type R3FAccessibleObject,
20
+ type R3FAccessibleObjectEvent,
21
+ resolveR3FAccessibleObject,
22
+ } from './r3f-accessibility.ts'
23
+
24
+ export type {
25
+ R3FAccessibleObject,
26
+ R3FAccessibleObjectEvent,
27
+ R3FAccessibleObjectTarget,
28
+ } from './r3f-accessibility.ts'
29
+
30
+ type NativeFiberCanvasProps = Omit<
31
+ FiberCanvasProps,
32
+ | 'accessibilityElementsHidden'
33
+ | 'accessibilityLabel'
34
+ | 'accessibilityRole'
35
+ | 'accessible'
36
+ | 'children'
37
+ | 'collapsable'
38
+ | 'importantForAccessibility'
39
+ | 'style'
40
+ >
41
+
42
+ export type ThreeCanvasProps = CanvasAccessibilityProps &
43
+ NativeFiberCanvasProps & {
44
+ /** Explicit public bridge from R3F objects to screen-reader controls. */
45
+ accessibleObjects?: readonly R3FAccessibleObject[]
46
+ children?: ReactNode
47
+ /** Reports semantic-control focus without competing with R3F pointer events. */
48
+ onObjectActiveChange?: (event: R3FAccessibleObjectEvent | undefined) => void
49
+ style?: StyleProp<ViewStyle>
50
+ }
51
+
52
+ /**
53
+ * Experimental Expo GL host for React Three Fiber Native.
54
+ *
55
+ * R3F owns the GL context, reconciler, frame loop, and pointer raycasting.
56
+ * Hozo adds one explicit accessibility envelope and public semantic controls.
57
+ */
58
+ export function ThreeCanvas({
59
+ accessibilityLabel,
60
+ accessibleFallback,
61
+ accessibleObjects = [],
62
+ children,
63
+ decorative,
64
+ onObjectActiveChange,
65
+ style,
66
+ ...fiberProps
67
+ }: ThreeCanvasProps) {
68
+ const navigation = useHozoNavigation()
69
+ const hasFallback = accessibleFallback !== undefined
70
+ const labelled = !decorative && !hasFallback
71
+ const controls = accessibleObjects.filter(({ disabled }) => !disabled)
72
+ const fallbackContent =
73
+ typeof accessibleFallback === 'string' ||
74
+ typeof accessibleFallback === 'number' ||
75
+ typeof accessibleFallback === 'bigint' ? (
76
+ <Text>{String(accessibleFallback)}</Text>
77
+ ) : (
78
+ accessibleFallback
79
+ )
80
+
81
+ return (
82
+ <View
83
+ collapsable={false}
84
+ style={[styles.root, style]}
85
+ accessible={labelled && controls.length === 0}
86
+ accessibilityRole={labelled && controls.length === 0 ? 'image' : undefined}
87
+ accessibilityLabel={labelled && controls.length === 0 ? accessibilityLabel : undefined}
88
+ accessibilityElementsHidden={decorative || undefined}
89
+ importantForAccessibility={decorative ? 'no-hide-descendants' : undefined}
90
+ >
91
+ <View
92
+ collapsable={false}
93
+ style={StyleSheet.absoluteFill}
94
+ accessible={false}
95
+ accessibilityElementsHidden
96
+ importantForAccessibility="no-hide-descendants"
97
+ >
98
+ {/* Fabric flattening can detach/reparent GLView as R3F installs its
99
+ responder handlers. Expo GL destroys its context on detachment;
100
+ preserve the native host even when its current props are layout-only.
101
+ See expo/expo#37725. This does not change the frame loop. */}
102
+ <FiberCanvas {...fiberProps} collapsable={false} style={StyleSheet.absoluteFill}>
103
+ {children}
104
+ </FiberCanvas>
105
+ </View>
106
+ {labelled && controls.length > 0 ? (
107
+ <View
108
+ style={styles.accessibilityDescription}
109
+ accessible
110
+ accessibilityRole="image"
111
+ accessibilityLabel={accessibilityLabel}
112
+ />
113
+ ) : null}
114
+ {controls.length > 0 ? (
115
+ <View style={styles.accessibilityLayer} pointerEvents="box-none">
116
+ {controls.map((control, index) => {
117
+ const focus = () => {
118
+ const object = resolveR3FAccessibleObject(control.object)
119
+ if (object) onObjectActiveChange?.({ id: control.id, object })
120
+ }
121
+ return (
122
+ <Pressable
123
+ key={control.id}
124
+ style={[styles.accessibilityControl, { top: index * 44 }]}
125
+ pointerEvents="box-none"
126
+ accessible
127
+ accessibilityRole={control.href === undefined ? 'button' : 'link'}
128
+ accessibilityLabel={control.label}
129
+ testID={control.testID}
130
+ onFocus={focus}
131
+ onBlur={() => onObjectActiveChange?.(undefined)}
132
+ onPress={() => {
133
+ const object = resolveR3FAccessibleObject(control.object)
134
+ if (!object) return
135
+ if (control.href === undefined) {
136
+ control.onPress({ id: control.id, object })
137
+ return
138
+ }
139
+ void activateHozoNavigation(
140
+ navigation,
141
+ {
142
+ href: control.href,
143
+ external: control.external,
144
+ replace: control.replace,
145
+ },
146
+ Linking.openURL,
147
+ )
148
+ }}
149
+ />
150
+ )
151
+ })}
152
+ </View>
153
+ ) : null}
154
+ {hasFallback ? (
155
+ <View style={styles.accessibleFallback} accessible={false} pointerEvents="none">
156
+ {accessibilityLabel ? <Text>{accessibilityLabel}</Text> : null}
157
+ {fallbackContent}
158
+ </View>
159
+ ) : null}
160
+ </View>
161
+ )
162
+ }
163
+
164
+ const styles = StyleSheet.create({
165
+ // FiberCanvas is absolutely positioned inside this accessibility envelope,
166
+ // so the envelope must claim its parent's available space itself. Without
167
+ // flex the wrapper collapses to zero height and Expo GL never creates a
168
+ // rendering context.
169
+ root: { flex: 1, position: 'relative', overflow: 'hidden' },
170
+ accessibilityLayer: {
171
+ position: 'absolute',
172
+ top: 0,
173
+ right: 0,
174
+ bottom: 0,
175
+ left: 0,
176
+ },
177
+ accessibilityDescription: { position: 'absolute', width: 1, height: 1 },
178
+ accessibilityControl: { position: 'absolute', left: 0, width: 44, height: 44 },
179
+ accessibleFallback: {
180
+ position: 'absolute',
181
+ width: 1,
182
+ height: 1,
183
+ padding: 0,
184
+ margin: -1,
185
+ overflow: 'hidden',
186
+ },
187
+ })
@@ -0,0 +1,17 @@
1
+ import type { ThreeCanvasProps } from './r3f.tsx'
2
+
3
+ export type {
4
+ R3FAccessibleObject,
5
+ R3FAccessibleObjectEvent,
6
+ R3FAccessibleObjectTarget,
7
+ R3FRendererFactory,
8
+ R3FRendererFactoryProps,
9
+ ThreeCanvasProps,
10
+ } from './r3f.tsx'
11
+
12
+ /** Native R3F hosting uses the explicit, separately shipped r3f-native entry. */
13
+ export function ThreeCanvas(_props: ThreeCanvasProps): never {
14
+ throw new Error(
15
+ '@hozo/three/r3f is Web-only. Use portable @hozo/three on React Native, or import the experimental Expo GL host from @hozo/three/r3f-native.',
16
+ )
17
+ }
package/src/r3f.tsx ADDED
@@ -0,0 +1,159 @@
1
+ import type { CanvasAccessibilityProps } from '@hozo/canvas'
2
+ import { Canvas as FiberCanvas, type CanvasProps as FiberCanvasProps } from '@react-three/fiber'
3
+ import { type CSSProperties, type ReactNode, useState } from 'react'
4
+
5
+ import { accessibleOnlyStyle, focusLeft, revealedControlsStyle } from './accessible-controls.ts'
6
+ import {
7
+ type R3FAccessibleObject,
8
+ type R3FAccessibleObjectEvent,
9
+ resolveR3FAccessibleObject,
10
+ } from './r3f-accessibility.ts'
11
+
12
+ export type {
13
+ R3FAccessibleObject,
14
+ R3FAccessibleObjectEvent,
15
+ R3FAccessibleObjectTarget,
16
+ } from './r3f-accessibility.ts'
17
+
18
+ type R3FCanvasProps = Omit<
19
+ FiberCanvasProps,
20
+ 'aria-hidden' | 'aria-label' | 'children' | 'className' | 'role' | 'style'
21
+ >
22
+
23
+ type FunctionMember<T> = T extends (...args: never[]) => unknown ? T : never
24
+
25
+ /** The sync or async renderer factory accepted by R3F's public `gl` prop. */
26
+ export type R3FRendererFactory = FunctionMember<NonNullable<FiberCanvasProps['gl']>>
27
+ export type R3FRendererFactoryProps = Parameters<R3FRendererFactory>[0]
28
+
29
+ export type ThreeCanvasProps = CanvasAccessibilityProps &
30
+ R3FCanvasProps & {
31
+ /** Explicit public bridge from R3F objects to keyboard and screen-reader controls. */
32
+ accessibleObjects?: readonly R3FAccessibleObject[]
33
+ children?: ReactNode
34
+ className?: string
35
+ /**
36
+ * On each accessible control, which is the element a keyboard reaches.
37
+ *
38
+ * The strip they live in is clipped at rest and revealed while focus is
39
+ * inside it, with the user agent's own colours -- so a control is visible
40
+ * and readable without this. It is here because the package's colours are
41
+ * the two a user agent guarantees and nothing more, and a scene is somebody
42
+ * else's design. #689 asked for it after `check-appearance.mjs` found the
43
+ * control with nothing an application could reach.
44
+ */
45
+ controlClassName?: string
46
+ /** Reports semantic-control focus without competing with R3F pointer events. */
47
+ onObjectActiveChange?: (event: R3FAccessibleObjectEvent | undefined) => void
48
+ style?: CSSProperties
49
+ }
50
+
51
+ /**
52
+ * An accessibility and layout envelope around React Three Fiber's Web Canvas.
53
+ *
54
+ * R3F retains ownership of its reconciler, renderer, events, and scene. Hozo
55
+ * contributes the same mutually exclusive surface semantics as its direct
56
+ * Three.js adapters without reaching into R3F's private instance metadata.
57
+ */
58
+ export function ThreeCanvas({
59
+ accessibilityLabel,
60
+ accessibleFallback,
61
+ accessibleObjects = [],
62
+ children,
63
+ className,
64
+ controlClassName,
65
+ decorative,
66
+ onObjectActiveChange,
67
+ style,
68
+ ...fiberProps
69
+ }: ThreeCanvasProps) {
70
+ const hasFallback = accessibleFallback !== undefined
71
+ const labelled = !decorative && !hasFallback
72
+ // Whether the control strip is showing. State rather than `:focus-within`,
73
+ // because this package ships no stylesheet to put a pseudo-class in -- the
74
+ // clip it is replacing is an inline style for the same reason.
75
+ const [reached, setReached] = useState(false)
76
+ return (
77
+ <div
78
+ className={className}
79
+ style={{ position: 'relative', width: 300, height: 150, ...style }}
80
+ aria-hidden={decorative ? true : undefined}
81
+ data-hozo-three-r3f=""
82
+ >
83
+ <div
84
+ aria-hidden={labelled ? undefined : true}
85
+ aria-label={labelled ? accessibilityLabel : undefined}
86
+ role={labelled ? 'img' : undefined}
87
+ style={{ width: '100%', height: '100%' }}
88
+ data-hozo-three-surface=""
89
+ >
90
+ <FiberCanvas {...fiberProps} aria-hidden style={{ width: '100%', height: '100%' }}>
91
+ {children}
92
+ </FiberCanvas>
93
+ </div>
94
+ {accessibleObjects.some(({ disabled }) => !disabled) ? (
95
+ // biome-ignore lint/a11y/noStaticElementInteractions: focus events on a container are how :focus-within is answered without a stylesheet, and the controls inside are real buttons
96
+ <div
97
+ style={reached ? revealedControlsStyle : accessibleOnlyStyle}
98
+ data-hozo-three-controls=""
99
+ data-hozo-three-reached={reached ? '' : undefined}
100
+ onFocus={() => setReached(true)}
101
+ onBlur={(event) => {
102
+ if (focusLeft(event)) setReached(false)
103
+ }}
104
+ >
105
+ {accessibleObjects.map((control) => {
106
+ if (control.disabled) return null
107
+ const focus = () => {
108
+ const object = resolveR3FAccessibleObject(control.object)
109
+ if (object) onObjectActiveChange?.({ id: control.id, object })
110
+ }
111
+ if (control.href !== undefined) {
112
+ return (
113
+ <a
114
+ key={control.id}
115
+ className={controlClassName}
116
+ data-testid={control.testID}
117
+ href={control.href}
118
+ target={control.external ? '_blank' : undefined}
119
+ rel={control.external ? 'noreferrer noopener' : undefined}
120
+ data-hozo-navigation-replace={control.replace ? '' : undefined}
121
+ onFocus={focus}
122
+ onBlur={() => onObjectActiveChange?.(undefined)}
123
+ >
124
+ {control.label}
125
+ </a>
126
+ )
127
+ }
128
+ return (
129
+ <button
130
+ key={control.id}
131
+ className={controlClassName}
132
+ data-testid={control.testID}
133
+ type="button"
134
+ onClick={() => {
135
+ const object = resolveR3FAccessibleObject(control.object)
136
+ if (object) control.onPress({ id: control.id, object })
137
+ }}
138
+ onFocus={focus}
139
+ onBlur={() => onObjectActiveChange?.(undefined)}
140
+ >
141
+ {control.label}
142
+ </button>
143
+ )
144
+ })}
145
+ </div>
146
+ ) : null}
147
+ {hasFallback ? (
148
+ <div
149
+ style={accessibleOnlyStyle}
150
+ role={accessibilityLabel ? 'group' : undefined}
151
+ aria-label={accessibilityLabel}
152
+ data-hozo-three-fallback=""
153
+ >
154
+ {accessibleFallback}
155
+ </div>
156
+ ) : null}
157
+ </div>
158
+ )
159
+ }
package/src/surface.ts ADDED
@@ -0,0 +1,178 @@
1
+ import {
2
+ type Ref,
3
+ useCallback,
4
+ useEffect,
5
+ useImperativeHandle,
6
+ useMemo,
7
+ useReducer,
8
+ useRef,
9
+ useState,
10
+ } from 'react'
11
+ import type { Camera, Scene } from 'three'
12
+
13
+ export type ThreeSurfaceFrameloop = 'demand' | 'always'
14
+
15
+ export interface ThreeSurfaceFrame<TCamera extends Camera = Camera> {
16
+ camera: TCamera
17
+ /** Seconds since the preceding frame. Zero on the first frame. */
18
+ delta: number
19
+ /** Seconds since this animation loop started. */
20
+ elapsed: number
21
+ scene: Scene
22
+ }
23
+
24
+ export interface ThreeSurfaceHandle {
25
+ /** Render mutations made to the same Three.js scene and camera objects. */
26
+ invalidate(): void
27
+ }
28
+
29
+ export interface ThreeSurfaceSize {
30
+ /** Layout pixels (CSS pixels on Web, density-independent pixels on Native). */
31
+ width: number
32
+ /** Layout pixels (CSS pixels on Web, density-independent pixels on Native). */
33
+ height: number
34
+ /** Physical pixels per layout pixel. */
35
+ pixelRatio: number
36
+ }
37
+
38
+ export type ThreeSurfaceCameraResize = 'auto' | 'manual'
39
+
40
+ export interface ThreeSurfaceProps<TCamera extends Camera = Camera> {
41
+ camera: TCamera
42
+ /** Update a PerspectiveCamera's aspect on resize. Orthographic cameras remain application-owned. */
43
+ cameraResize?: ThreeSurfaceCameraResize
44
+ frameloop?: ThreeSurfaceFrameloop
45
+ /** Fixed layout height. Omit it to follow the mounted surface. */
46
+ height?: number
47
+ onFrame?: (frame: ThreeSurfaceFrame<TCamera>) => void
48
+ onResize?: (size: ThreeSurfaceSize) => void
49
+ ref?: Ref<ThreeSurfaceHandle>
50
+ /**
51
+ * An application-owned value that invalidates demand rendering when it
52
+ * changes. Useful when an imperative ref is inconvenient.
53
+ */
54
+ revision?: unknown
55
+ scene: Scene
56
+ /** Fixed layout width. Omit it to follow the mounted surface. */
57
+ width?: number
58
+ }
59
+
60
+ interface ThreeSurfaceSizeOptions {
61
+ height?: number
62
+ onResize?: (size: ThreeSurfaceSize) => void
63
+ pixelRatio?: number
64
+ width?: number
65
+ }
66
+
67
+ /** Shared SSR fallback and measured-size state for every renderer family. */
68
+ export function useThreeSurfaceSize({
69
+ height,
70
+ onResize,
71
+ pixelRatio,
72
+ width,
73
+ }: ThreeSurfaceSizeOptions) {
74
+ const [measured, setMeasured] = useState<ThreeSurfaceSize>({
75
+ width: width ?? 300,
76
+ height: height ?? 150,
77
+ pixelRatio: pixelRatio ?? 1,
78
+ })
79
+ const callback = useRef(onResize)
80
+ callback.current = onResize
81
+ const size = useMemo(
82
+ () => ({
83
+ width: width ?? measured.width,
84
+ height: height ?? measured.height,
85
+ pixelRatio: pixelRatio ?? measured.pixelRatio,
86
+ }),
87
+ [height, measured, pixelRatio, width],
88
+ )
89
+ const measure = useCallback((next: ThreeSurfaceSize) => {
90
+ setMeasured((current) =>
91
+ current.width === next.width &&
92
+ current.height === next.height &&
93
+ current.pixelRatio === next.pixelRatio
94
+ ? current
95
+ : next,
96
+ )
97
+ }, [])
98
+ useEffect(() => {
99
+ callback.current?.(size)
100
+ }, [size])
101
+ return { measure, size } as const
102
+ }
103
+
104
+ /** Apply the only camera resize rule whose intent is unambiguous. */
105
+ export function resizeThreeCamera(
106
+ camera: Camera,
107
+ size: Pick<ThreeSurfaceSize, 'height' | 'width'>,
108
+ policy: ThreeSurfaceCameraResize = 'auto',
109
+ ) {
110
+ const perspective = camera as Camera & {
111
+ aspect?: number
112
+ isPerspectiveCamera?: boolean
113
+ updateProjectionMatrix?: () => void
114
+ }
115
+ if (policy === 'manual' || !perspective.isPerspectiveCamera || size.height <= 0) return
116
+ const aspect = size.width / size.height
117
+ if (perspective.aspect === aspect) return
118
+ perspective.aspect = aspect
119
+ perspective.updateProjectionMatrix?.()
120
+ }
121
+
122
+ interface ThreeSurfaceLifecycleOptions<TCamera extends Camera> {
123
+ camera: TCamera
124
+ frameloop: ThreeSurfaceFrameloop
125
+ /** Optional renderer-owned fast path for continuous frames. */
126
+ onAnimationFrame?: () => void
127
+ onFrame?: (frame: ThreeSurfaceFrame<TCamera>) => void
128
+ ref?: Ref<ThreeSurfaceHandle>
129
+ scene: Scene
130
+ }
131
+
132
+ /**
133
+ * Renderer-independent demand invalidation and animation lifecycle.
134
+ *
135
+ * Renderer adapters consume `frameRevision` as an explicit render token. The
136
+ * hook deliberately does not schedule or perform a draw itself.
137
+ */
138
+ export function useThreeSurfaceLifecycle<TCamera extends Camera>({
139
+ camera,
140
+ frameloop,
141
+ onAnimationFrame,
142
+ onFrame,
143
+ ref,
144
+ scene,
145
+ }: ThreeSurfaceLifecycleOptions<TCamera>) {
146
+ const [frameRevision, invalidateReducer] = useReducer((value: number) => value + 1, 0)
147
+ const invalidate = useCallback(() => invalidateReducer(), [])
148
+ const frameCallback = useRef(onFrame)
149
+ const animationCallback = useRef(onAnimationFrame)
150
+ frameCallback.current = onFrame
151
+ animationCallback.current = onAnimationFrame
152
+
153
+ useImperativeHandle(ref, () => ({ invalidate }), [invalidate])
154
+
155
+ useEffect(() => {
156
+ if (frameloop !== 'always') return
157
+ let request = 0
158
+ let first: number | undefined
159
+ let previous: number | undefined
160
+ const frame = (timestamp: number) => {
161
+ first ??= timestamp
162
+ frameCallback.current?.({
163
+ camera,
164
+ delta: previous === undefined ? 0 : (timestamp - previous) / 1000,
165
+ elapsed: (timestamp - first) / 1000,
166
+ scene,
167
+ })
168
+ previous = timestamp
169
+ if (animationCallback.current) animationCallback.current()
170
+ else invalidate()
171
+ request = requestAnimationFrame(frame)
172
+ }
173
+ request = requestAnimationFrame(frame)
174
+ return () => cancelAnimationFrame(request)
175
+ }, [camera, frameloop, invalidate, scene])
176
+
177
+ return { frameRevision, invalidate } as const
178
+ }