Press n or j to go to the next uncovered block, b, p or k for the previous block.
| 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 | 'use client' import { useCallback, useEffect, useRef, useState } from 'react' export interface UsePhoneCameraOptions { /** Initial facing mode (default: "environment" for back camera) */ initialFacingMode?: 'user' | 'environment' /** Whether to attempt enabling torch when available */ enableTorch?: boolean } export interface UsePhoneCameraReturn { /** The video stream */ stream: MediaStream | null /** Whether the camera is loading */ isLoading: boolean /** Error message if camera failed */ error: string | null /** Current facing mode */ facingMode: 'user' | 'environment' /** Whether torch is currently on */ isTorchOn: boolean /** Whether torch is available on this device */ isTorchAvailable: boolean /** Available camera devices */ availableDevices: MediaDeviceInfo[] /** Start the camera */ start: () => Promise<void> /** Stop the camera */ stop: () => void /** Flip between front and back camera */ flipCamera: () => Promise<void> /** Toggle torch on/off */ toggleTorch: () => Promise<void> /** Set torch state explicitly */ setTorch: (on: boolean) => Promise<void> } /** * Hook for managing phone camera with flip and torch support * * Designed for mobile devices, defaults to back-facing camera. */ export function usePhoneCamera(options: UsePhoneCameraOptions = {}): UsePhoneCameraReturn { const { initialFacingMode = 'environment', enableTorch = false } = options const [stream, setStream] = useState<MediaStream | null>(null) const [isLoading, setIsLoading] = useState(false) const [error, setError] = useState<string | null>(null) const [facingMode, setFacingMode] = useState<'user' | 'environment'>(initialFacingMode) const [isTorchOn, setIsTorchOn] = useState(false) const [isTorchAvailable, setIsTorchAvailable] = useState(false) const [availableDevices, setAvailableDevices] = useState<MediaDeviceInfo[]>([]) // Track if component is mounted const isMountedRef = useRef(true) useEffect(() => { isMountedRef.current = true return () => { isMountedRef.current = false } }, []) /** * Stop all tracks in the current stream */ const stopStream = useCallback(() => { if (stream) { stream.getTracks().forEach((track) => track.stop()) setStream(null) setIsTorchOn(false) } }, [stream]) /** * Check if torch is available on the current track */ const checkTorchAvailability = useCallback((track: MediaStreamTrack): boolean => { try { const capabilities = track.getCapabilities() as MediaTrackCapabilities & { torch?: boolean } return capabilities.torch === true } catch { return false } }, []) /** * Apply torch setting to track */ const applyTorch = useCallback(async (track: MediaStreamTrack, on: boolean): Promise<boolean> => { try { await track.applyConstraints({ advanced: [{ torch: on } as MediaTrackConstraintSet], }) return true } catch (err) { console.warn('[usePhoneCamera] Failed to apply torch:', err) return false } }, []) /** * Start camera with specified facing mode */ const startCamera = useCallback( async (targetFacingMode: 'user' | 'environment') => { setIsLoading(true) setError(null) try { // Stop any existing stream if (stream) { stream.getTracks().forEach((track) => track.stop()) } // Request camera with specified facing mode // Prefer widest angle lens (zoom: 1 = no zoom = widest) const constraints: MediaStreamConstraints = { video: { facingMode: { ideal: targetFacingMode }, width: { ideal: 1280 }, height: { ideal: 720 }, // @ts-expect-error - zoom is valid but not in TS types zoom: { ideal: 1 }, }, audio: false, } const newStream = await navigator.mediaDevices.getUserMedia(constraints) if (!isMountedRef.current) { newStream.getTracks().forEach((track) => track.stop()) return } // Check torch availability const videoTrack = newStream.getVideoTracks()[0] const torchAvailable = videoTrack ? checkTorchAvailability(videoTrack) : false setIsTorchAvailable(torchAvailable) // Apply initial torch setting if requested and available if (enableTorch && torchAvailable && videoTrack) { const success = await applyTorch(videoTrack, true) setIsTorchOn(success) } else { setIsTorchOn(false) } // Enumerate devices for UI const devices = await navigator.mediaDevices.enumerateDevices() const videoDevices = devices.filter((device) => device.kind === 'videoinput') setAvailableDevices(videoDevices) setStream(newStream) setFacingMode(targetFacingMode) setError(null) } catch (err) { console.error('[usePhoneCamera] Failed to start camera:', err) if (!isMountedRef.current) return if (err instanceof Error) { if (err.name === 'NotAllowedError' || err.name === 'PermissionDeniedError') { setError('Camera permission denied. Please allow camera access.') } else if (err.name === 'NotFoundError' || err.name === 'DevicesNotFoundError') { setError('No camera found on this device.') } else if (err.name === 'NotReadableError' || err.name === 'TrackStartError') { setError('Camera is in use by another application.') } else if (err.name === 'OverconstrainedError') { // If the facing mode constraint failed, try without it try { const fallbackStream = await navigator.mediaDevices.getUserMedia({ video: true, audio: false, }) if (!isMountedRef.current) { fallbackStream.getTracks().forEach((track) => track.stop()) return } const videoTrack = fallbackStream.getVideoTracks()[0] const torchAvailable = videoTrack ? checkTorchAvailability(videoTrack) : false setIsTorchAvailable(torchAvailable) setStream(fallbackStream) setError(null) return } catch { setError('Could not access any camera.') } } else { setError(`Camera error: ${err.message}`) } } else { setError('Unknown camera error occurred.') } } finally { if (isMountedRef.current) { setIsLoading(false) } } }, [stream, checkTorchAvailability, applyTorch, enableTorch] ) /** * Start the camera with current facing mode */ const start = useCallback(async () => { await startCamera(facingMode) }, [startCamera, facingMode]) /** * Stop the camera */ const stop = useCallback(() => { stopStream() setError(null) }, [stopStream]) /** * Flip between front and back camera */ const flipCamera = useCallback(async () => { const newFacingMode = facingMode === 'user' ? 'environment' : 'user' await startCamera(newFacingMode) }, [facingMode, startCamera]) /** * Toggle torch on/off */ const toggleTorch = useCallback(async () => { if (!stream || !isTorchAvailable) return const videoTrack = stream.getVideoTracks()[0] if (!videoTrack) return const newState = !isTorchOn const success = await applyTorch(videoTrack, newState) if (success) { setIsTorchOn(newState) } }, [stream, isTorchAvailable, isTorchOn, applyTorch]) /** * Set torch state explicitly */ const setTorch = useCallback( async (on: boolean) => { if (!stream || !isTorchAvailable) return const videoTrack = stream.getVideoTracks()[0] if (!videoTrack) return const success = await applyTorch(videoTrack, on) if (success) { setIsTorchOn(on) } }, [stream, isTorchAvailable, applyTorch] ) // Cleanup on unmount useEffect(() => { return () => { if (stream) { stream.getTracks().forEach((track) => track.stop()) } } }, [stream]) return { stream, isLoading, error, facingMode, isTorchOn, isTorchAvailable, availableDevices, start, stop, flipCamera, toggleTorch, setTorch, } } |