panelui-native 0.113.0 → 0.114.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 (44) hide show
  1. package/lib/module/components/bottom-sheet/index.js +11 -0
  2. package/lib/module/components/bottom-sheet/index.js.map +1 -1
  3. package/lib/module/components/camera/camera-model.js +142 -0
  4. package/lib/module/components/camera/camera-model.js.map +1 -0
  5. package/lib/module/components/camera/index.js +1547 -0
  6. package/lib/module/components/camera/index.js.map +1 -0
  7. package/lib/module/components/image-viewer/image-viewer-geometry.js +15 -0
  8. package/lib/module/components/image-viewer/image-viewer-geometry.js.map +1 -1
  9. package/lib/module/components/image-viewer/index.js +107 -38
  10. package/lib/module/components/image-viewer/index.js.map +1 -1
  11. package/lib/module/icons/index.js +20 -0
  12. package/lib/module/icons/index.js.map +1 -1
  13. package/lib/module/index.js +2 -1
  14. package/lib/module/index.js.map +1 -1
  15. package/lib/module/primitives/portal-store.js +79 -0
  16. package/lib/module/primitives/portal-store.js.map +1 -0
  17. package/lib/module/primitives/portal.js +21 -30
  18. package/lib/module/primitives/portal.js.map +1 -1
  19. package/lib/typescript/src/components/bottom-sheet/index.d.ts.map +1 -1
  20. package/lib/typescript/src/components/camera/camera-model.d.ts +79 -0
  21. package/lib/typescript/src/components/camera/camera-model.d.ts.map +1 -0
  22. package/lib/typescript/src/components/camera/index.d.ts +481 -0
  23. package/lib/typescript/src/components/camera/index.d.ts.map +1 -0
  24. package/lib/typescript/src/components/image-viewer/image-viewer-geometry.d.ts +9 -0
  25. package/lib/typescript/src/components/image-viewer/image-viewer-geometry.d.ts.map +1 -1
  26. package/lib/typescript/src/components/image-viewer/index.d.ts +10 -3
  27. package/lib/typescript/src/components/image-viewer/index.d.ts.map +1 -1
  28. package/lib/typescript/src/icons/index.d.ts +4 -0
  29. package/lib/typescript/src/icons/index.d.ts.map +1 -1
  30. package/lib/typescript/src/index.d.ts +2 -1
  31. package/lib/typescript/src/index.d.ts.map +1 -1
  32. package/lib/typescript/src/primitives/portal-store.d.ts +40 -0
  33. package/lib/typescript/src/primitives/portal-store.d.ts.map +1 -0
  34. package/lib/typescript/src/primitives/portal.d.ts.map +1 -1
  35. package/package.json +5 -1
  36. package/src/components/bottom-sheet/index.tsx +22 -1
  37. package/src/components/camera/camera-model.ts +140 -0
  38. package/src/components/camera/index.tsx +1881 -0
  39. package/src/components/image-viewer/image-viewer-geometry.ts +15 -0
  40. package/src/components/image-viewer/index.tsx +126 -43
  41. package/src/icons/index.tsx +8 -0
  42. package/src/index.ts +36 -0
  43. package/src/primitives/portal-store.ts +94 -0
  44. package/src/primitives/portal.tsx +21 -36
@@ -0,0 +1,1881 @@
1
+ /**
2
+ * Camera — a full-screen camera assembled from parts: the viewfinder, the
3
+ * shutter, zoom, flash, a self-timer, the recording clock, front and back, and
4
+ * the button into the library.
5
+ *
6
+ * ```tsx
7
+ * <Camera onCapture={keep}>
8
+ * <Camera.Preview />
9
+ * <Camera.Header>
10
+ * <Camera.Flash />
11
+ * <Camera.Duration />
12
+ * <Camera.Timer />
13
+ * </Camera.Header>
14
+ * <Camera.Footer>
15
+ * <Camera.Zoom />
16
+ * <Camera.Modes />
17
+ * <Camera.Controls>
18
+ * <Camera.Library source={last} onPress={openLibrary} />
19
+ * <Camera.Shutter />
20
+ * <Camera.Flip />
21
+ * </Camera.Controls>
22
+ * </Camera.Footer>
23
+ * </Camera>
24
+ * ```
25
+ *
26
+ * ## The result is the app's
27
+ *
28
+ * A photo or a clip is handed to `onCapture` as the file the camera wrote, and
29
+ * nothing else happens to it here. Saving it to the photo library, holding it
30
+ * in memory for a preview, uploading it: each app wants a different one, and a
31
+ * component that picked would be wrong for most of them. The library button is
32
+ * the same — it draws the thumbnail it is given and calls `onPress`.
33
+ *
34
+ * ## Every part reads one state
35
+ *
36
+ * The root owns facing, mode, flash, zoom and the timer, each controlled or
37
+ * not, and every part reads them through context. `useCamera()` hands the same
38
+ * state and actions to anything else, so a part that does not suit can be
39
+ * swapped for a control of the app's own without losing the behaviour behind
40
+ * it. Leave a part out and its feature is simply not offered.
41
+ *
42
+ * ## Built on expo-camera
43
+ *
44
+ * The preview, the capture and the recording are expo-camera's, which runs in
45
+ * Expo Go. It is an optional dependency: without it the preview says so, and
46
+ * `hasCamera` is false.
47
+ *
48
+ * Its zoom is a fraction of the device's maximum, and that maximum is not
49
+ * exposed — on iOS the fraction is an exponent of it, on Android a multiple —
50
+ * so the same zoom is a different magnification on every phone. That is why
51
+ * nothing here labels a zoom "2×" on its own: the stops are the app's to name,
52
+ * and between them a bar shows where in the range the lens is.
53
+ *
54
+ * There is no way to focus on a point either, so a tap on the preview does
55
+ * nothing rather than draw a square over a focus that never moved.
56
+ *
57
+ * ## Over a black viewfinder
58
+ *
59
+ * The viewfinder is black in every theme and the picture on it is whatever
60
+ * the lens sees, so the chrome over it is white on a dark glaze in every theme.
61
+ * An active control is drawn inverted, white with a black glyph, which reads on
62
+ * any picture; recording is the destructive colour.
63
+ *
64
+ * Switching cameras hides the swap under a brief dark cover rather than
65
+ * turning the preview: on Android the preview is a surface that ignores view
66
+ * transforms, and the frame where one session hands over to the other is not
67
+ * something to show.
68
+ */
69
+ import {
70
+ createContext,
71
+ forwardRef,
72
+ useCallback,
73
+ useContext,
74
+ useEffect,
75
+ useImperativeHandle,
76
+ useMemo,
77
+ useRef,
78
+ useState,
79
+ type ComponentType,
80
+ type ReactNode,
81
+ type Ref,
82
+ type RefAttributes,
83
+ type RefObject,
84
+ } from 'react';
85
+ import {
86
+ AccessibilityInfo,
87
+ Image,
88
+ Linking,
89
+ Pressable,
90
+ StyleSheet,
91
+ View,
92
+ type AccessibilityActionEvent,
93
+ type ImageSourcePropType,
94
+ type LayoutChangeEvent,
95
+ type PressableProps,
96
+ type ViewProps,
97
+ } from 'react-native';
98
+ import { Gesture, GestureDetector } from 'react-native-gesture-handler';
99
+ import Animated, {
100
+ Easing,
101
+ FadeIn,
102
+ cancelAnimation,
103
+ runOnJS,
104
+ useAnimatedProps,
105
+ useAnimatedStyle,
106
+ useReducedMotion,
107
+ useSharedValue,
108
+ withDelay,
109
+ withSequence,
110
+ withSpring,
111
+ withTiming,
112
+ type SharedValue,
113
+ } from 'react-native-reanimated';
114
+ import { useSafeAreaInsets } from 'react-native-safe-area-context';
115
+ import Svg, { Circle } from 'react-native-svg';
116
+ import { tv } from 'tailwind-variants';
117
+ import { useCSSVariable } from 'uniwind';
118
+ import {
119
+ CameraIcon,
120
+ CameraSwitchIcon,
121
+ FlashIcon,
122
+ FlashOffIcon,
123
+ IconColorProvider,
124
+ ImageIcon,
125
+ TimerIcon,
126
+ } from '../../icons';
127
+ import { AnimatedPressable } from '../../primitives/animated-pressable';
128
+ import { useControllableState } from '../../primitives/controllable-state';
129
+ import { Text } from '../../primitives/text';
130
+ import { cn } from '../../utils/cn';
131
+ import { impactKnock, selectionTick } from '../../utils/haptics';
132
+ import {
133
+ activeStop,
134
+ clampZoom,
135
+ flashIn,
136
+ formatDuration,
137
+ nextFlash,
138
+ nextTimer,
139
+ stepZoom,
140
+ stillFlash,
141
+ torchFor,
142
+ zoomFromPinch,
143
+ zoomFromTrack,
144
+ type CameraFacing,
145
+ type CameraFlashMode,
146
+ type CameraMode,
147
+ type CameraTimerDelay,
148
+ } from './camera-model';
149
+
150
+ export type { CameraFacing, CameraFlashMode, CameraMode, CameraTimerDelay } from './camera-model';
151
+
152
+ /** Glyphs over the viewfinder, which is black in every theme. */
153
+ const ON_GLASS = '#ffffff';
154
+ /** Glyphs on an active control, which is drawn white. */
155
+ const ON_ACTIVE = '#000000';
156
+
157
+ /** The shutter's outer diameter, its ring, and the disc inside it. */
158
+ const SHUTTER = 78;
159
+ const SHUTTER_RING = 4;
160
+ const SHUTTER_DISC = 62;
161
+ /** The disc while recording: a rounded square, so stopping reads as a stop. */
162
+ const SHUTTER_STOP = 28;
163
+ const RING_RADIUS = SHUTTER / 2 - SHUTTER_RING / 2;
164
+ const RING_LENGTH = 2 * Math.PI * RING_RADIUS;
165
+
166
+ /** How long the shutter has to be held, in video, before holding records. */
167
+ const HOLD_TO_RECORD_MS = 300;
168
+
169
+ /** The flip cover: out, a hold while the native session swaps, and back. */
170
+ const FLIP_OUT_MS = 140;
171
+ const FLIP_HOLD_MS = 220;
172
+ const FLIP_IN_MS = 200;
173
+
174
+ /** A stop that lands as a recording starts can be dropped natively; it is sent again after this. */
175
+ const STOP_RETRY_MS = 500;
176
+
177
+ /**
178
+ * How long a press made before the camera has reported it started waits for that
179
+ * report before trying anyway. The report can reach JavaScript late, so a press is
180
+ * held rather than dropped.
181
+ */
182
+ const READY_GRACE_MS = 1500;
183
+
184
+ const ZOOM_BAR_WIDTH = 200;
185
+ const ZOOM_TICKS = 21;
186
+
187
+ const DEFAULT_ZOOM_STOPS: CameraZoomStop[] = [{ value: 0, label: '1×' }];
188
+
189
+ const FLASH_LABELS: Record<CameraFlashMode, string> = { off: 'Off', auto: 'Auto', on: 'On' };
190
+ const MODE_LABELS: Record<CameraMode, string> = { photo: 'Photo', video: 'Video' };
191
+ const MODE_ORDER: CameraMode[] = ['video', 'photo'];
192
+
193
+ const AnimatedCircle = Animated.createAnimatedComponent(Circle);
194
+
195
+ const cameraVariants = tv({
196
+ slots: {
197
+ root: 'flex-1 overflow-hidden bg-black',
198
+ header: 'flex-row items-center justify-between px-4',
199
+ footer: 'items-center gap-4 px-6',
200
+ controls: 'w-full flex-row items-center justify-between',
201
+ },
202
+ });
203
+
204
+ const chromeButton = tv({
205
+ base: 'h-10 min-w-10 flex-row items-center justify-center gap-1 rounded-full px-2.5',
206
+ variants: {
207
+ active: { true: 'bg-white', false: 'bg-black/40' },
208
+ // Both values are written: a removed opacity class can leave the last one on the view.
209
+ disabled: { true: 'opacity-40', false: 'opacity-100' },
210
+ },
211
+ defaultVariants: { active: false, disabled: false },
212
+ });
213
+
214
+ const chromeText = tv({
215
+ base: 'font-semibold',
216
+ variants: { active: { true: 'text-black', false: 'text-white' } },
217
+ defaultVariants: { active: false },
218
+ });
219
+
220
+ const durationPill = tv({
221
+ base: 'h-8 flex-row items-center gap-1.5 rounded-full px-3',
222
+ variants: { recording: { true: 'bg-destructive', false: 'bg-black/40' } },
223
+ defaultVariants: { recording: false },
224
+ });
225
+
226
+ /* -------------------------------------------------------------------------- */
227
+ /* expo-camera, loaded if it is there */
228
+ /* -------------------------------------------------------------------------- */
229
+
230
+ interface PermissionState {
231
+ granted: boolean;
232
+ canAskAgain: boolean;
233
+ }
234
+
235
+ /** The picture expo-camera returns. */
236
+ interface CapturedPicture {
237
+ uri: string;
238
+ width: number;
239
+ height: number;
240
+ base64?: string;
241
+ exif?: Record<string, unknown>;
242
+ }
243
+
244
+ /**
245
+ * The methods of expo-camera's `CameraView` this component calls, and the ones
246
+ * an app is likeliest to reach for through `CameraHandle.view`.
247
+ */
248
+ export interface CameraViewHandle {
249
+ takePictureAsync(options?: object): Promise<CapturedPicture | undefined>;
250
+ recordAsync(options?: object): Promise<{ uri: string } | undefined>;
251
+ stopRecording(): void;
252
+ pausePreview(): Promise<void>;
253
+ resumePreview(): Promise<void>;
254
+ }
255
+
256
+ type PermissionHook = () => readonly [PermissionState | null, () => Promise<PermissionState>, ...unknown[]];
257
+
258
+ interface ExpoCameraModule {
259
+ CameraView: ComponentType<Record<string, unknown> & RefAttributes<CameraViewHandle>>;
260
+ useCameraPermissions: PermissionHook;
261
+ Camera: {
262
+ getMicrophonePermissionsAsync(): Promise<PermissionState>;
263
+ requestMicrophonePermissionsAsync(): Promise<PermissionState>;
264
+ };
265
+ }
266
+
267
+ /**
268
+ * `expo-camera`, or null when it is not installed or its native module is
269
+ * missing from the build. The `require` sits directly in its `try` block, which
270
+ * is what lets Metro bundle an app that does not have the package.
271
+ */
272
+ function loadExpoCamera(): ExpoCameraModule | null {
273
+ try {
274
+ // eslint-disable-next-line @typescript-eslint/no-require-imports
275
+ return require('expo-camera') as ExpoCameraModule;
276
+ } catch {
277
+ return null;
278
+ }
279
+ }
280
+
281
+ const expoCamera = loadExpoCamera();
282
+
283
+ /**
284
+ * True when the camera can be shown, because `expo-camera` is installed and its
285
+ * native module is in the build. Expo Go has it.
286
+ */
287
+ export const hasCamera = expoCamera !== null;
288
+
289
+ const NO_PERMISSION = [null, async () => ({ granted: false, canAskAgain: false })] as const;
290
+ function useMissingPermission() {
291
+ return NO_PERMISSION;
292
+ }
293
+ /** Chosen once: whether the package is there cannot change while the app runs. */
294
+ const useCameraPermission: PermissionHook = expoCamera?.useCameraPermissions ?? useMissingPermission;
295
+
296
+ /* -------------------------------------------------------------------------- */
297
+ /* Types */
298
+ /* -------------------------------------------------------------------------- */
299
+
300
+ /** A photo, as the camera wrote it. */
301
+ export interface CameraPhoto {
302
+ type: 'photo';
303
+ /** A local file. */
304
+ uri: string;
305
+ width: number;
306
+ height: number;
307
+ /** Present when `pictureOptions.base64` is set. */
308
+ base64?: string;
309
+ /** Present when `pictureOptions.exif` is set. */
310
+ exif?: Record<string, unknown>;
311
+ }
312
+
313
+ /** A clip, as the camera wrote it. */
314
+ export interface CameraVideo {
315
+ type: 'video';
316
+ /** A local file. */
317
+ uri: string;
318
+ /** How long it ran, in milliseconds, measured from when recording started. */
319
+ duration: number;
320
+ }
321
+
322
+ export type CameraCapture = CameraPhoto | CameraVideo;
323
+
324
+ /** Options for each photo, passed to expo-camera's `takePictureAsync`. */
325
+ export interface CameraPictureOptions {
326
+ /** JPEG quality, 0–1. Default 1. */
327
+ quality?: number;
328
+ /** Also return the image as base64. */
329
+ base64?: boolean;
330
+ /** Also return its EXIF data. */
331
+ exif?: boolean;
332
+ /** Skip orientation and quality processing, for speed. */
333
+ skipProcessing?: boolean;
334
+ /** Play the shutter sound. Default true; some regions require it. */
335
+ shutterSound?: boolean;
336
+ }
337
+
338
+ /**
339
+ * Props passed straight to expo-camera's `CameraView`, for what the parts do not
340
+ * cover. The parts' own state wins over the same prop here.
341
+ */
342
+ export interface CameraViewOptions {
343
+ videoQuality?: '2160p' | '1080p' | '720p' | '480p' | '4:3';
344
+ videoStabilizationMode?: 'off' | 'standard' | 'cinematic' | 'auto';
345
+ /** Android only: the preview's aspect ratio. */
346
+ ratio?: '4:3' | '16:9' | '1:1';
347
+ /** iOS only: which lens, from `getAvailableLensesAsync`. */
348
+ selectedLens?: string;
349
+ pictureSize?: string;
350
+ animateShutter?: boolean;
351
+ [key: string]: unknown;
352
+ }
353
+
354
+ /** One zoom stop: a value in expo-camera's range, and the label the app gives it. */
355
+ export interface CameraZoomStop {
356
+ /** 0–1, a fraction of the device's maximum zoom. */
357
+ value: number;
358
+ /** What the chip says, such as `1×` or `2`. */
359
+ label: string;
360
+ /** Read out instead of `Zoom <label>`. */
361
+ accessibilityLabel?: string;
362
+ }
363
+
364
+ /** What `useCamera()` returns: the camera's state, and what can be done with it. */
365
+ export interface CameraState {
366
+ facing: CameraFacing;
367
+ mode: CameraMode;
368
+ /** The setting as chosen. In video, `auto` acts as off. */
369
+ flash: CameraFlashMode;
370
+ /** 0–1, a fraction of the device's maximum. */
371
+ zoom: number;
372
+ timer: CameraTimerDelay;
373
+ /** The camera has started and can capture. */
374
+ ready: boolean;
375
+ /** Camera access, or null until it is known. */
376
+ permission: { granted: boolean; canAskAgain: boolean } | null;
377
+ recording: boolean;
378
+ /** When recording started, as `Date.now()`, or null. */
379
+ recordingSince: number | null;
380
+ /** A photo is being taken. */
381
+ capturing: boolean;
382
+ /** Seconds left on the self-timer, or null when it is not counting. */
383
+ countdown: number | null;
384
+ /** The recording cap, in seconds, when there is one. */
385
+ maxDuration?: number;
386
+ setMode: (mode: CameraMode) => void;
387
+ setFlash: (flash: CameraFlashMode) => void;
388
+ setZoom: (zoom: number) => void;
389
+ setTimer: (timer: CameraTimerDelay) => void;
390
+ /** Swap front and back. Ignored while recording. */
391
+ flip: () => void;
392
+ /** What a press on the shutter does in the current mode. */
393
+ press: () => void;
394
+ takePhoto: () => Promise<CameraPhoto | null>;
395
+ startRecording: () => Promise<void>;
396
+ stopRecording: () => void;
397
+ cancelCountdown: () => void;
398
+ requestPermission: () => void;
399
+ }
400
+
401
+ /** A ref on `Camera`. */
402
+ export interface CameraHandle {
403
+ /** Takes a photo now, ignoring the timer, and resolves to it, or null if it failed. */
404
+ takePhoto: () => Promise<CameraPhoto | null>;
405
+ /** Starts recording; resolves once the clip has been handed to `onCapture`. */
406
+ startRecording: () => Promise<void>;
407
+ stopRecording: () => void;
408
+ flip: () => void;
409
+ /** expo-camera's `CameraView`, for anything this component does not wrap. */
410
+ readonly view: CameraViewHandle | null;
411
+ }
412
+
413
+ interface CameraContextValue extends CameraState {
414
+ available: boolean;
415
+ canCapture: boolean;
416
+ viewRef: RefObject<CameraViewHandle | null>;
417
+ onReady: () => void;
418
+ onMountError: (event: { message?: string }) => void;
419
+ cover: SharedValue<number>;
420
+ turn: SharedValue<number>;
421
+ haptics: boolean;
422
+ safeArea: boolean;
423
+ mute: boolean;
424
+ mirror: boolean;
425
+ cameraProps?: CameraViewOptions;
426
+ }
427
+
428
+ const CameraContext = createContext<CameraContextValue | null>(null);
429
+
430
+ function useCameraContext(part: string): CameraContextValue {
431
+ const context = useContext(CameraContext);
432
+ if (!context) throw new Error(`${part} must be rendered inside <Camera>.`);
433
+ return context;
434
+ }
435
+
436
+ /**
437
+ * The camera's state and actions, for a control of the app's own inside
438
+ * `<Camera>` — a shutter drawn differently, a timer in a menu.
439
+ */
440
+ export function useCamera(): CameraState {
441
+ return useCameraContext('useCamera()');
442
+ }
443
+
444
+ function toError(error: unknown): Error {
445
+ if (error instanceof Error) return error;
446
+ return new Error(typeof error === 'string' ? error : 'The camera failed.');
447
+ }
448
+
449
+ /* -------------------------------------------------------------------------- */
450
+ /* Root */
451
+ /* -------------------------------------------------------------------------- */
452
+
453
+ export interface CameraProps extends ViewProps {
454
+ /** Classes on the root, which fills its parent and is black. */
455
+ className?: string;
456
+ /** The parts. Put `Camera.Preview` first, so everything after it is drawn over the picture. */
457
+ children?: ReactNode;
458
+ /** Which camera, controlled. */
459
+ facing?: CameraFacing;
460
+ /** Which camera it opens on. */
461
+ defaultFacing?: CameraFacing;
462
+ /** Called when the camera switches between front and back. */
463
+ onFacingChange?: (facing: CameraFacing) => void;
464
+ /** Photo or video, controlled. */
465
+ mode?: CameraMode;
466
+ /** Photo or video to start in. */
467
+ defaultMode?: CameraMode;
468
+ /** Called when the mode changes. */
469
+ onModeChange?: (mode: CameraMode) => void;
470
+ /** The flash setting, controlled. In video, `on` lights the torch while recording. */
471
+ flash?: CameraFlashMode;
472
+ /** The flash setting to start with. */
473
+ defaultFlash?: CameraFlashMode;
474
+ /** Called when the flash setting changes. */
475
+ onFlashChange?: (flash: CameraFlashMode) => void;
476
+ /**
477
+ * Zoom, controlled: 0–1, a fraction of the device's maximum zoom, which is a
478
+ * different magnification on every phone. Reset to 0 when the camera flips.
479
+ */
480
+ zoom?: number;
481
+ /** The zoom to start at. */
482
+ defaultZoom?: number;
483
+ /** Called as the zoom changes, many times during a pinch. */
484
+ onZoomChange?: (zoom: number) => void;
485
+ /** The self-timer, in seconds, controlled. Photos only. */
486
+ timer?: CameraTimerDelay;
487
+ /** The self-timer to start with. */
488
+ defaultTimer?: CameraTimerDelay;
489
+ /** Called when the self-timer setting changes. */
490
+ onTimerChange?: (timer: CameraTimerDelay) => void;
491
+ /**
492
+ * Called with each photo and clip. Nothing is saved: the file is where the
493
+ * camera wrote it, and keeping it, saving it or uploading it is up to you.
494
+ */
495
+ onCapture?: (capture: CameraCapture) => void;
496
+ /**
497
+ * Called when the camera fails to start, a capture fails, or microphone
498
+ * access is refused. Without it, these are logged in development.
499
+ */
500
+ onError?: (error: Error) => void;
501
+ /** Stops a recording after this many seconds, and fills the shutter's ring towards it. */
502
+ maxDuration?: number;
503
+ /** Record without sound, and without asking for the microphone. */
504
+ mute?: boolean;
505
+ /**
506
+ * Save front-camera photos and clips mirrored, the way the preview shows
507
+ * them. Off, they are saved the way other people see you.
508
+ */
509
+ mirror?: boolean;
510
+ /** Options for every photo. */
511
+ pictureOptions?: CameraPictureOptions;
512
+ /** Passed to expo-camera's `CameraView`. */
513
+ cameraProps?: CameraViewOptions;
514
+ /** A tick on the shutter, the flip and each setting change. */
515
+ haptics?: boolean;
516
+ /** Keep the header and footer clear of the notch and the home indicator. */
517
+ safeArea?: boolean;
518
+ }
519
+
520
+ function CameraRoot(
521
+ {
522
+ facing: facingProp,
523
+ defaultFacing = 'back',
524
+ onFacingChange,
525
+ mode: modeProp,
526
+ defaultMode = 'photo',
527
+ onModeChange,
528
+ flash: flashProp,
529
+ defaultFlash = 'off',
530
+ onFlashChange,
531
+ zoom: zoomProp,
532
+ defaultZoom = 0,
533
+ onZoomChange,
534
+ timer: timerProp,
535
+ defaultTimer = 0,
536
+ onTimerChange,
537
+ onCapture,
538
+ onError,
539
+ maxDuration,
540
+ mute = false,
541
+ mirror = false,
542
+ pictureOptions,
543
+ cameraProps,
544
+ haptics = true,
545
+ safeArea = true,
546
+ className,
547
+ children,
548
+ ...props
549
+ }: CameraProps,
550
+ ref: Ref<CameraHandle>
551
+ ) {
552
+ const reduced = useReducedMotion();
553
+ const { value: facing, setValue: setFacing } = useControllableState({
554
+ value: facingProp,
555
+ defaultValue: defaultFacing,
556
+ onChange: onFacingChange,
557
+ });
558
+ const { value: mode, setValue: setModeState } = useControllableState({
559
+ value: modeProp,
560
+ defaultValue: defaultMode,
561
+ onChange: onModeChange,
562
+ });
563
+ const { value: flash, setValue: setFlashState } = useControllableState({
564
+ value: flashProp,
565
+ defaultValue: defaultFlash,
566
+ onChange: onFlashChange,
567
+ });
568
+ const { value: zoom, setValue: setZoomState } = useControllableState({
569
+ value: zoomProp,
570
+ defaultValue: defaultZoom,
571
+ onChange: onZoomChange,
572
+ normalize: clampZoom,
573
+ });
574
+ const { value: timer, setValue: setTimerState } = useControllableState({
575
+ value: timerProp,
576
+ defaultValue: defaultTimer,
577
+ onChange: onTimerChange,
578
+ });
579
+
580
+ const [permission, requestPermissionAsync] = useCameraPermission();
581
+ const [ready, setReady] = useState(false);
582
+ const [capturing, setCapturing] = useState(false);
583
+ const [recordingSince, setRecordingSince] = useState<number | null>(null);
584
+ const [countdown, setCountdown] = useState<number | null>(null);
585
+
586
+ const viewRef = useRef<CameraViewHandle | null>(null);
587
+ const cover = useSharedValue(0);
588
+ const turn = useSharedValue(0);
589
+
590
+ // The latest of everything an async capture reads after it has started.
591
+ const latest = useRef({ onCapture, onError, pictureOptions, maxDuration, mute, haptics });
592
+ latest.current = { onCapture, onError, pictureOptions, maxDuration, mute, haptics };
593
+ const facingRef = useRef(facing);
594
+ facingRef.current = facing;
595
+
596
+ const capturingRef = useRef(false);
597
+ const recordingRef = useRef(false);
598
+ const generationRef = useRef(0);
599
+ const cancelStartRef = useRef(false);
600
+ const flippingRef = useRef(false);
601
+ const readyRef = useRef(false);
602
+ const pendingRef = useRef<{ run: () => void; drop: () => void } | null>(null);
603
+ const countdownRef = useRef<ReturnType<typeof setInterval> | null>(null);
604
+
605
+ const report = useCallback((error: unknown) => {
606
+ const failure = toError(error);
607
+ if (latest.current.onError) latest.current.onError(failure);
608
+ else if (__DEV__) console.warn(`[Camera] ${failure.message}`);
609
+ }, []);
610
+
611
+ const requestPermission = useCallback(() => {
612
+ requestPermissionAsync().catch(report);
613
+ }, [report, requestPermissionAsync]);
614
+
615
+ const setZoom = useCallback((next: number) => setZoomState(clampZoom(next)), [setZoomState]);
616
+ const setFlash = useCallback((next: CameraFlashMode) => setFlashState(next), [setFlashState]);
617
+ const setTimer = useCallback((next: CameraTimerDelay) => setTimerState(next), [setTimerState]);
618
+
619
+ const clearCountdown = useCallback(() => {
620
+ if (countdownRef.current) clearInterval(countdownRef.current);
621
+ countdownRef.current = null;
622
+ setCountdown(null);
623
+ }, []);
624
+
625
+ const capturePhoto = useCallback(async (): Promise<CameraPhoto | null> => {
626
+ const view = viewRef.current;
627
+ if (!view || capturingRef.current || recordingRef.current) return null;
628
+ capturingRef.current = true;
629
+ setCapturing(true);
630
+ if (latest.current.haptics) impactKnock();
631
+ try {
632
+ const picture = await view.takePictureAsync({ quality: 1, ...latest.current.pictureOptions });
633
+ if (!picture) return null;
634
+ const photo: CameraPhoto = {
635
+ type: 'photo',
636
+ uri: picture.uri,
637
+ width: picture.width,
638
+ height: picture.height,
639
+ ...(picture.base64 ? { base64: picture.base64 } : null),
640
+ ...(picture.exif ? { exif: picture.exif } : null),
641
+ };
642
+ latest.current.onCapture?.(photo);
643
+ return photo;
644
+ } catch (error) {
645
+ report(error);
646
+ return null;
647
+ } finally {
648
+ capturingRef.current = false;
649
+ setCapturing(false);
650
+ }
651
+ }, [report]);
652
+
653
+ const record = useCallback(async () => {
654
+ const view = viewRef.current;
655
+ if (!view || recordingRef.current || capturingRef.current) return;
656
+ recordingRef.current = true;
657
+ cancelStartRef.current = false;
658
+ const generation = ++generationRef.current;
659
+ let since: number | null = null;
660
+ try {
661
+ if (!latest.current.mute && expoCamera) {
662
+ let microphone = await expoCamera.Camera.getMicrophonePermissionsAsync();
663
+ if (!microphone.granted && microphone.canAskAgain) {
664
+ microphone = await expoCamera.Camera.requestMicrophonePermissionsAsync();
665
+ }
666
+ if (!microphone.granted) {
667
+ throw new Error(
668
+ 'Recording with sound needs microphone access. Allow it in Settings, or pass `mute` to record without sound.'
669
+ );
670
+ }
671
+ }
672
+ // Let go of the shutter while the microphone was being asked for: no recording.
673
+ if (cancelStartRef.current) return;
674
+ since = Date.now();
675
+ setRecordingSince(since);
676
+ if (latest.current.haptics) impactKnock();
677
+ AccessibilityInfo.announceForAccessibility('Recording');
678
+ const cap = latest.current.maxDuration;
679
+ const result = await view.recordAsync(cap ? { maxDuration: cap } : {});
680
+ if (result?.uri) {
681
+ latest.current.onCapture?.({ type: 'video', uri: result.uri, duration: Date.now() - since });
682
+ }
683
+ } catch (error) {
684
+ report(error);
685
+ } finally {
686
+ if (generationRef.current === generation) {
687
+ recordingRef.current = false;
688
+ setRecordingSince(null);
689
+ if (since !== null) AccessibilityInfo.announceForAccessibility('Recording stopped');
690
+ }
691
+ }
692
+ }, [report]);
693
+
694
+ /**
695
+ * Runs a capture now if the camera has started, or once it has. Only one waits
696
+ * at a time: a newer press replaces it, and the replaced one resolves to the
697
+ * fallback.
698
+ */
699
+ const whenReady = useCallback(<T,>(action: () => Promise<T>, fallback: T): Promise<T> => {
700
+ if (readyRef.current) return action();
701
+ return new Promise<T>((resolve) => {
702
+ pendingRef.current?.drop();
703
+ const pending = {
704
+ run: () => {
705
+ pendingRef.current = null;
706
+ action().then(resolve, () => resolve(fallback));
707
+ },
708
+ drop: () => {
709
+ pendingRef.current = null;
710
+ resolve(fallback);
711
+ },
712
+ };
713
+ pendingRef.current = pending;
714
+ setTimeout(() => {
715
+ if (pendingRef.current === pending) pending.run();
716
+ }, READY_GRACE_MS);
717
+ });
718
+ }, []);
719
+
720
+ const takePhoto = useCallback(() => whenReady(capturePhoto, null), [capturePhoto, whenReady]);
721
+ const startRecording = useCallback(
722
+ () => whenReady(record, undefined),
723
+ [record, whenReady]
724
+ );
725
+
726
+ const stopRecording = useCallback(() => {
727
+ // A recording still waiting for the camera to start is simply not started.
728
+ if (pendingRef.current) {
729
+ pendingRef.current.drop();
730
+ return;
731
+ }
732
+ if (!recordingRef.current) return;
733
+ cancelStartRef.current = true;
734
+ const generation = generationRef.current;
735
+ viewRef.current?.stopRecording();
736
+ setTimeout(() => {
737
+ if (recordingRef.current && generationRef.current === generation) {
738
+ viewRef.current?.stopRecording();
739
+ }
740
+ }, STOP_RETRY_MS);
741
+ }, []);
742
+
743
+ const startCountdown = useCallback(
744
+ (seconds: number) => {
745
+ let left = seconds;
746
+ setCountdown(left);
747
+ if (latest.current.haptics) selectionTick();
748
+ countdownRef.current = setInterval(() => {
749
+ left -= 1;
750
+ if (left > 0) {
751
+ setCountdown(left);
752
+ if (latest.current.haptics) selectionTick();
753
+ return;
754
+ }
755
+ clearCountdown();
756
+ void capturePhoto();
757
+ }, 1000);
758
+ },
759
+ [capturePhoto, clearCountdown]
760
+ );
761
+
762
+ const setMode = useCallback(
763
+ (next: CameraMode) => {
764
+ if (recordingRef.current) return;
765
+ clearCountdown();
766
+ if (latest.current.haptics) selectionTick();
767
+ setModeState(next);
768
+ },
769
+ [clearCountdown, setModeState]
770
+ );
771
+
772
+ const commitFlip = useCallback(() => {
773
+ setFacing(facingRef.current === 'back' ? 'front' : 'back');
774
+ // Zoom belongs to one camera; carried across it would be a different view on the other.
775
+ setZoomState(0);
776
+ }, [setFacing, setZoomState]);
777
+
778
+ const endFlip = useCallback(() => {
779
+ flippingRef.current = false;
780
+ }, []);
781
+
782
+ const flip = useCallback(() => {
783
+ if (flippingRef.current || recordingRef.current) return;
784
+ if (latest.current.haptics) selectionTick();
785
+ turn.value = withTiming(Math.round(turn.value) + 1, {
786
+ duration: reduced ? 0 : 320,
787
+ easing: Easing.out(Easing.cubic),
788
+ });
789
+ if (reduced || !permission?.granted) {
790
+ commitFlip();
791
+ return;
792
+ }
793
+ flippingRef.current = true;
794
+ cover.value = withSequence(
795
+ withTiming(1, { duration: FLIP_OUT_MS, easing: Easing.in(Easing.quad) }, (finished) => {
796
+ 'worklet';
797
+ if (finished) runOnJS(commitFlip)();
798
+ }),
799
+ // A delay rather than a second timing to 1: the hold is what gives the
800
+ // native session time to swap before the cover lifts.
801
+ withDelay(
802
+ FLIP_HOLD_MS,
803
+ withTiming(0, { duration: FLIP_IN_MS, easing: Easing.out(Easing.quad) }, () => {
804
+ 'worklet';
805
+ runOnJS(endFlip)();
806
+ })
807
+ )
808
+ );
809
+ }, [commitFlip, cover, endFlip, permission?.granted, reduced, turn]);
810
+
811
+ const press = useCallback(() => {
812
+ if (mode === 'video') {
813
+ if (recordingRef.current || pendingRef.current) stopRecording();
814
+ else void startRecording();
815
+ return;
816
+ }
817
+ if (countdownRef.current) {
818
+ clearCountdown();
819
+ return;
820
+ }
821
+ if (timer > 0) startCountdown(timer);
822
+ else void takePhoto();
823
+ }, [clearCountdown, mode, startCountdown, startRecording, stopRecording, takePhoto, timer]);
824
+
825
+ const onReady = useCallback(() => {
826
+ readyRef.current = true;
827
+ setReady(true);
828
+ pendingRef.current?.run();
829
+ }, []);
830
+ const onMountError = useCallback(
831
+ (event: { message?: string }) => report(new Error(event?.message ?? 'The camera could not start.')),
832
+ [report]
833
+ );
834
+
835
+ // Leaving the screen ends whatever was in flight.
836
+ useEffect(
837
+ () => () => {
838
+ if (countdownRef.current) clearInterval(countdownRef.current);
839
+ pendingRef.current?.drop();
840
+ if (recordingRef.current) viewRef.current?.stopRecording();
841
+ },
842
+ []
843
+ );
844
+
845
+ useImperativeHandle(
846
+ ref,
847
+ () => ({
848
+ takePhoto,
849
+ startRecording,
850
+ stopRecording,
851
+ flip,
852
+ get view() {
853
+ return viewRef.current;
854
+ },
855
+ }),
856
+ [flip, startRecording, stopRecording, takePhoto]
857
+ );
858
+
859
+ const recording = recordingSince !== null;
860
+ const available = expoCamera !== null;
861
+ // Not gated on `ready`: the shutter is usable as soon as there is a camera, and a
862
+ // press that comes before it has started waits for it (see `whenReady`).
863
+ const canCapture = available && !!permission?.granted && !capturing;
864
+
865
+ const context = useMemo<CameraContextValue>(
866
+ () => ({
867
+ facing,
868
+ mode,
869
+ flash,
870
+ zoom,
871
+ timer,
872
+ ready,
873
+ permission,
874
+ recording,
875
+ recordingSince,
876
+ capturing,
877
+ countdown,
878
+ maxDuration,
879
+ setMode,
880
+ setFlash,
881
+ setZoom,
882
+ setTimer,
883
+ flip,
884
+ press,
885
+ takePhoto,
886
+ startRecording,
887
+ stopRecording,
888
+ cancelCountdown: clearCountdown,
889
+ requestPermission,
890
+ available,
891
+ canCapture,
892
+ viewRef,
893
+ onReady,
894
+ onMountError,
895
+ cover,
896
+ turn,
897
+ haptics,
898
+ safeArea,
899
+ mute,
900
+ mirror,
901
+ cameraProps,
902
+ }),
903
+ [
904
+ available,
905
+ cameraProps,
906
+ canCapture,
907
+ capturing,
908
+ clearCountdown,
909
+ countdown,
910
+ cover,
911
+ facing,
912
+ flash,
913
+ flip,
914
+ haptics,
915
+ maxDuration,
916
+ mirror,
917
+ mode,
918
+ mute,
919
+ onMountError,
920
+ onReady,
921
+ permission,
922
+ press,
923
+ ready,
924
+ recording,
925
+ recordingSince,
926
+ requestPermission,
927
+ safeArea,
928
+ setFlash,
929
+ setMode,
930
+ setTimer,
931
+ setZoom,
932
+ startRecording,
933
+ stopRecording,
934
+ takePhoto,
935
+ timer,
936
+ turn,
937
+ zoom,
938
+ ]
939
+ );
940
+
941
+ const { root } = cameraVariants();
942
+
943
+ return (
944
+ <CameraContext.Provider value={context}>
945
+ <View {...props} className={root({ className })}>
946
+ {children}
947
+ </View>
948
+ </CameraContext.Provider>
949
+ );
950
+ }
951
+
952
+ const CameraForwarded = forwardRef<CameraHandle, CameraProps>(CameraRoot);
953
+ CameraForwarded.displayName = 'Camera';
954
+
955
+ /* -------------------------------------------------------------------------- */
956
+ /* Preview */
957
+ /* -------------------------------------------------------------------------- */
958
+
959
+ export interface CameraPreviewProps extends ViewProps {
960
+ className?: string;
961
+ /** Drawn over the picture, under the header and footer: a grid, a guide, a frame. */
962
+ children?: ReactNode;
963
+ /** Two fingers zoom. */
964
+ pinchToZoom?: boolean;
965
+ /** A double tap swaps front and back. */
966
+ doubleTapToFlip?: boolean;
967
+ /** Shown while camera access has not been given. */
968
+ permissionTitle?: string;
969
+ permissionDescription?: string;
970
+ /** The button that asks for access. */
971
+ permissionAction?: string;
972
+ /** The button once access has been refused for good, which opens Settings. */
973
+ settingsAction?: string;
974
+ /** Read out for the viewfinder, which a screen reader adjusts to zoom. */
975
+ accessibilityLabel?: string;
976
+ }
977
+
978
+ /**
979
+ * The live picture, filling the camera. Until camera access is given it asks
980
+ * for it in place, and once access is refused for good its button opens
981
+ * Settings, since asking again would do nothing.
982
+ */
983
+ function CameraPreview({
984
+ className,
985
+ children,
986
+ pinchToZoom = true,
987
+ doubleTapToFlip = true,
988
+ permissionTitle = 'Camera access',
989
+ permissionDescription = 'Allow access to the camera to take photos and record video.',
990
+ permissionAction = 'Allow camera',
991
+ settingsAction = 'Open Settings',
992
+ accessibilityLabel = 'Camera viewfinder',
993
+ style,
994
+ ...props
995
+ }: CameraPreviewProps) {
996
+ const camera = useCameraContext('Camera.Preview');
997
+ const { setZoom, flip, cover } = camera;
998
+
999
+ const zoomShared = useSharedValue(camera.zoom);
1000
+ const pinchStart = useSharedValue(0);
1001
+ useEffect(() => {
1002
+ zoomShared.value = camera.zoom;
1003
+ }, [camera.zoom, zoomShared]);
1004
+
1005
+ const gesture = useMemo(() => {
1006
+ const pinch = Gesture.Pinch()
1007
+ .onStart(() => {
1008
+ 'worklet';
1009
+ pinchStart.value = zoomShared.value;
1010
+ })
1011
+ .onUpdate((event) => {
1012
+ 'worklet';
1013
+ const next = zoomFromPinch(pinchStart.value, event.scale);
1014
+ if (Math.abs(next - zoomShared.value) < 0.002) return;
1015
+ zoomShared.value = next;
1016
+ runOnJS(setZoom)(next);
1017
+ })
1018
+ .enabled(pinchToZoom);
1019
+ const doubleTap = Gesture.Tap()
1020
+ .numberOfTaps(2)
1021
+ .maxDelay(250)
1022
+ .onEnd((_event, success) => {
1023
+ 'worklet';
1024
+ if (success) runOnJS(flip)();
1025
+ })
1026
+ .enabled(doubleTapToFlip);
1027
+ return Gesture.Simultaneous(pinch, doubleTap);
1028
+ }, [doubleTapToFlip, flip, pinchStart, pinchToZoom, setZoom, zoomShared]);
1029
+
1030
+ const coverStyle = useAnimatedStyle(() => ({ opacity: cover.value }));
1031
+
1032
+ const onAccessibilityAction = useCallback(
1033
+ (event: AccessibilityActionEvent) => {
1034
+ if (event.nativeEvent.actionName === 'increment') setZoom(stepZoom(camera.zoom, 1));
1035
+ else if (event.nativeEvent.actionName === 'decrement') setZoom(stepZoom(camera.zoom, -1));
1036
+ },
1037
+ [camera.zoom, setZoom]
1038
+ );
1039
+
1040
+ let content: ReactNode = null;
1041
+ if (!expoCamera) {
1042
+ content = (
1043
+ <Notice
1044
+ title="Camera unavailable"
1045
+ description="Install expo-camera to show the camera: npx expo install expo-camera"
1046
+ />
1047
+ );
1048
+ } else if (camera.permission && !camera.permission.granted) {
1049
+ const settings = !camera.permission.canAskAgain;
1050
+ content = (
1051
+ <Notice
1052
+ title={permissionTitle}
1053
+ description={permissionDescription}
1054
+ action={settings ? settingsAction : permissionAction}
1055
+ onAction={settings ? () => void Linking.openSettings() : camera.requestPermission}
1056
+ />
1057
+ );
1058
+ } else if (camera.permission?.granted) {
1059
+ const { CameraView } = expoCamera;
1060
+ content = (
1061
+ <>
1062
+ <GestureDetector gesture={gesture}>
1063
+ <View
1064
+ style={StyleSheet.absoluteFill}
1065
+ accessible
1066
+ accessibilityRole="adjustable"
1067
+ accessibilityLabel={accessibilityLabel}
1068
+ accessibilityValue={{ min: 0, max: 100, now: Math.round(camera.zoom * 100) }}
1069
+ accessibilityActions={[{ name: 'increment' }, { name: 'decrement' }]}
1070
+ onAccessibilityAction={onAccessibilityAction}
1071
+ >
1072
+ <CameraView
1073
+ {...camera.cameraProps}
1074
+ ref={camera.viewRef}
1075
+ style={StyleSheet.absoluteFill}
1076
+ facing={camera.facing}
1077
+ mode={camera.mode === 'video' ? 'video' : 'picture'}
1078
+ flash={stillFlash(camera.mode, camera.flash)}
1079
+ enableTorch={torchFor(camera.mode, flashIn(camera.mode, camera.flash), camera.recording)}
1080
+ zoom={camera.zoom}
1081
+ mute={camera.mute}
1082
+ mirror={camera.mirror}
1083
+ onCameraReady={camera.onReady}
1084
+ onMountError={camera.onMountError}
1085
+ />
1086
+ </View>
1087
+ </GestureDetector>
1088
+ {children ? (
1089
+ <View pointerEvents="box-none" style={StyleSheet.absoluteFill}>
1090
+ {children}
1091
+ </View>
1092
+ ) : null}
1093
+ {camera.countdown !== null ? <Countdown value={camera.countdown} /> : null}
1094
+ <Animated.View
1095
+ pointerEvents="none"
1096
+ style={[StyleSheet.absoluteFill, coverStyle]}
1097
+ className="bg-black"
1098
+ />
1099
+ </>
1100
+ );
1101
+ }
1102
+
1103
+ return (
1104
+ <View {...props} style={[StyleSheet.absoluteFill, style]} className={cn('bg-black', className)}>
1105
+ {content}
1106
+ </View>
1107
+ );
1108
+ }
1109
+ CameraPreview.displayName = 'Camera.Preview';
1110
+
1111
+ function Countdown({ value }: { value: number }) {
1112
+ return (
1113
+ <Animated.View
1114
+ key={value}
1115
+ entering={FadeIn.duration(120)}
1116
+ pointerEvents="none"
1117
+ style={StyleSheet.absoluteFill}
1118
+ className="items-center justify-center"
1119
+ accessibilityLiveRegion="polite"
1120
+ >
1121
+ <Text
1122
+ weight="semibold"
1123
+ className="text-white"
1124
+ style={{ fontSize: 120, lineHeight: 132, fontVariant: ['tabular-nums'] }}
1125
+ >
1126
+ {value}
1127
+ </Text>
1128
+ </Animated.View>
1129
+ );
1130
+ }
1131
+
1132
+ function Notice({
1133
+ title,
1134
+ description,
1135
+ action,
1136
+ onAction,
1137
+ }: {
1138
+ title: string;
1139
+ description: string;
1140
+ action?: string;
1141
+ onAction?: () => void;
1142
+ }) {
1143
+ return (
1144
+ <View style={StyleSheet.absoluteFill} className="items-center justify-center gap-3 px-10">
1145
+ <View className="opacity-60">
1146
+ <CameraIcon size={32} color={ON_GLASS} />
1147
+ </View>
1148
+ <Text size="lg" weight="semibold" className="text-center text-white">
1149
+ {title}
1150
+ </Text>
1151
+ <Text size="sm" className="text-center text-white/70">
1152
+ {description}
1153
+ </Text>
1154
+ {action && onAction ? (
1155
+ <AnimatedPressable
1156
+ onPress={onAction}
1157
+ accessibilityRole="button"
1158
+ className="mt-2 h-11 items-center justify-center rounded-full bg-white px-5"
1159
+ >
1160
+ <Text size="sm" weight="semibold" className="text-black">
1161
+ {action}
1162
+ </Text>
1163
+ </AnimatedPressable>
1164
+ ) : null}
1165
+ </View>
1166
+ );
1167
+ }
1168
+
1169
+ /* -------------------------------------------------------------------------- */
1170
+ /* Header, footer, controls */
1171
+ /* -------------------------------------------------------------------------- */
1172
+
1173
+ export interface CameraHeaderProps extends ViewProps {
1174
+ className?: string;
1175
+ children?: ReactNode;
1176
+ }
1177
+
1178
+ /** The band along the top, over the picture: flash, the clock, the timer. */
1179
+ function CameraHeader({ className, children, style, ...props }: CameraHeaderProps) {
1180
+ const camera = useCameraContext('Camera.Header');
1181
+ const insets = useSafeAreaInsets();
1182
+ const { header } = cameraVariants();
1183
+ return (
1184
+ <View
1185
+ {...props}
1186
+ pointerEvents="box-none"
1187
+ style={[
1188
+ { position: 'absolute', left: 0, right: 0, top: (camera.safeArea ? insets.top : 0) + 8 },
1189
+ style,
1190
+ ]}
1191
+ className={header({ className })}
1192
+ >
1193
+ {children}
1194
+ </View>
1195
+ );
1196
+ }
1197
+ CameraHeader.displayName = 'Camera.Header';
1198
+
1199
+ export interface CameraFooterProps extends ViewProps {
1200
+ className?: string;
1201
+ children?: ReactNode;
1202
+ }
1203
+
1204
+ /** The band along the bottom, over the picture: zoom, the modes, the shutter row. */
1205
+ function CameraFooter({ className, children, style, ...props }: CameraFooterProps) {
1206
+ const camera = useCameraContext('Camera.Footer');
1207
+ const insets = useSafeAreaInsets();
1208
+ const { footer } = cameraVariants();
1209
+ return (
1210
+ <View
1211
+ {...props}
1212
+ pointerEvents="box-none"
1213
+ style={[
1214
+ {
1215
+ position: 'absolute',
1216
+ left: 0,
1217
+ right: 0,
1218
+ bottom: (camera.safeArea ? insets.bottom : 0) + 16,
1219
+ },
1220
+ style,
1221
+ ]}
1222
+ className={footer({ className })}
1223
+ >
1224
+ {children}
1225
+ </View>
1226
+ );
1227
+ }
1228
+ CameraFooter.displayName = 'Camera.Footer';
1229
+
1230
+ export interface CameraControlsProps extends ViewProps {
1231
+ className?: string;
1232
+ children?: ReactNode;
1233
+ }
1234
+
1235
+ /**
1236
+ * The row the shutter sits in, with what goes either side of it. Library and
1237
+ * Flip are the same size, so the shutter lands in the middle.
1238
+ */
1239
+ function CameraControls({ className, children, ...props }: CameraControlsProps) {
1240
+ useCameraContext('Camera.Controls');
1241
+ const { controls } = cameraVariants();
1242
+ return (
1243
+ <View {...props} pointerEvents="box-none" className={controls({ className })}>
1244
+ {children}
1245
+ </View>
1246
+ );
1247
+ }
1248
+ CameraControls.displayName = 'Camera.Controls';
1249
+
1250
+ /* -------------------------------------------------------------------------- */
1251
+ /* Settings over the picture */
1252
+ /* -------------------------------------------------------------------------- */
1253
+
1254
+ interface ChromeButtonProps extends Omit<PressableProps, 'children'> {
1255
+ active?: boolean;
1256
+ className?: string;
1257
+ children: ReactNode;
1258
+ }
1259
+
1260
+ function ChromeButton({ active = false, disabled, className, children, ...props }: ChromeButtonProps) {
1261
+ return (
1262
+ <AnimatedPressable
1263
+ {...props}
1264
+ disabled={disabled}
1265
+ hitSlop={6}
1266
+ pressScale={0.92}
1267
+ accessibilityRole="button"
1268
+ accessibilityState={{ disabled: !!disabled, selected: active }}
1269
+ className={chromeButton({ active, disabled: !!disabled, className })}
1270
+ >
1271
+ {children}
1272
+ </AnimatedPressable>
1273
+ );
1274
+ }
1275
+
1276
+ export interface CameraButtonProps extends Omit<PressableProps, 'children'> {
1277
+ className?: string;
1278
+ /** Drawn inverted, white with a black glyph, for a setting that is on. */
1279
+ active?: boolean;
1280
+ /** An icon. It is drawn white, or black when `active`, unless it is given a colour of its own. */
1281
+ children: ReactNode;
1282
+ }
1283
+
1284
+ /**
1285
+ * A round control over the picture for an action of your own: closing the
1286
+ * camera, a grid, a setting. It is drawn like Flash and Timer, so a row of
1287
+ * them reads as one set. Give it an `accessibilityLabel`; an icon has nothing
1288
+ * to read out.
1289
+ */
1290
+ function CameraButton({ className, active = false, children, ...props }: CameraButtonProps) {
1291
+ useCameraContext('Camera.Button');
1292
+ return (
1293
+ <ChromeButton {...props} active={active} className={className}>
1294
+ <IconColorProvider color={active ? ON_ACTIVE : ON_GLASS}>{children}</IconColorProvider>
1295
+ </ChromeButton>
1296
+ );
1297
+ }
1298
+ CameraButton.displayName = 'Camera.Button';
1299
+
1300
+ export interface CameraFlashProps extends Omit<PressableProps, 'children' | 'onPress'> {
1301
+ className?: string;
1302
+ /** What each setting is read out as; `auto`'s is also shown beside the icon. */
1303
+ labels?: Partial<Record<CameraFlashMode, string>>;
1304
+ accessibilityLabel?: string;
1305
+ }
1306
+
1307
+ /**
1308
+ * The flash. For a photo it steps off, auto, on; for a video, off and on, and
1309
+ * on lights the torch while recording.
1310
+ */
1311
+ function CameraFlashControl({
1312
+ className,
1313
+ labels,
1314
+ accessibilityLabel = 'Flash',
1315
+ ...props
1316
+ }: CameraFlashProps) {
1317
+ const camera = useCameraContext('Camera.Flash');
1318
+ const shown = flashIn(camera.mode, camera.flash);
1319
+ const label = { ...FLASH_LABELS, ...labels }[shown];
1320
+ const active = shown === 'on';
1321
+ const color = active ? ON_ACTIVE : ON_GLASS;
1322
+ return (
1323
+ <ChromeButton
1324
+ {...props}
1325
+ active={active}
1326
+ onPress={() => {
1327
+ if (camera.haptics) selectionTick();
1328
+ camera.setFlash(nextFlash(camera.mode, camera.flash));
1329
+ }}
1330
+ accessibilityLabel={accessibilityLabel}
1331
+ accessibilityValue={{ text: label }}
1332
+ className={className}
1333
+ >
1334
+ {shown === 'off' ? <FlashOffIcon size={20} color={color} /> : <FlashIcon size={20} color={color} />}
1335
+ {shown === 'auto' ? (
1336
+ <Text size="xs" className={chromeText({ active })}>
1337
+ {label}
1338
+ </Text>
1339
+ ) : null}
1340
+ </ChromeButton>
1341
+ );
1342
+ }
1343
+ CameraFlashControl.displayName = 'Camera.Flash';
1344
+
1345
+ export interface CameraTimerProps extends Omit<PressableProps, 'children' | 'onPress'> {
1346
+ className?: string;
1347
+ /** What off is read out as. */
1348
+ offLabel?: string;
1349
+ accessibilityLabel?: string;
1350
+ }
1351
+
1352
+ /**
1353
+ * The self-timer: off, 3 s, 10 s. While it counts, the seconds left fill the
1354
+ * preview, and a press on the shutter cancels. Photos only, so it is dimmed in
1355
+ * video.
1356
+ */
1357
+ function CameraTimerControl({
1358
+ className,
1359
+ offLabel = 'Off',
1360
+ accessibilityLabel = 'Timer',
1361
+ ...props
1362
+ }: CameraTimerProps) {
1363
+ const camera = useCameraContext('Camera.Timer');
1364
+ const active = camera.timer > 0;
1365
+ const disabled = camera.mode === 'video' || camera.countdown !== null;
1366
+ const color = active ? ON_ACTIVE : ON_GLASS;
1367
+ return (
1368
+ <ChromeButton
1369
+ {...props}
1370
+ active={active}
1371
+ disabled={disabled}
1372
+ onPress={() => {
1373
+ if (camera.haptics) selectionTick();
1374
+ camera.setTimer(nextTimer(camera.timer));
1375
+ }}
1376
+ accessibilityLabel={accessibilityLabel}
1377
+ accessibilityValue={{ text: active ? `${camera.timer} seconds` : offLabel }}
1378
+ className={className}
1379
+ >
1380
+ <TimerIcon size={20} color={color} />
1381
+ {active ? (
1382
+ <Text size="xs" className={chromeText({ active })}>
1383
+ {`${camera.timer}s`}
1384
+ </Text>
1385
+ ) : null}
1386
+ </ChromeButton>
1387
+ );
1388
+ }
1389
+ CameraTimerControl.displayName = 'Camera.Timer';
1390
+
1391
+ export interface CameraDurationProps extends ViewProps {
1392
+ className?: string;
1393
+ /** Show it in photo mode too, at `00:00`. By default it appears in video only. */
1394
+ always?: boolean;
1395
+ }
1396
+
1397
+ /**
1398
+ * The recording clock, `mm:ss`. It reads `00:00` in video before recording,
1399
+ * and turns red with a dot while it runs. Hidden in photo mode.
1400
+ */
1401
+ function CameraDuration({ className, always = false, ...props }: CameraDurationProps) {
1402
+ const camera = useCameraContext('Camera.Duration');
1403
+ const since = camera.recordingSince;
1404
+ const [now, setNow] = useState(() => Date.now());
1405
+
1406
+ useEffect(() => {
1407
+ if (since === null) return;
1408
+ setNow(Date.now());
1409
+ const id = setInterval(() => setNow(Date.now()), 250);
1410
+ return () => clearInterval(id);
1411
+ }, [since]);
1412
+
1413
+ if (!always && camera.mode !== 'video' && since === null) return null;
1414
+ const recording = since !== null;
1415
+ const clock = formatDuration(recording ? now - since : 0);
1416
+
1417
+ return (
1418
+ <View
1419
+ {...props}
1420
+ accessible
1421
+ accessibilityRole="text"
1422
+ accessibilityLabel={recording ? `Recording, ${clock}` : clock}
1423
+ className={durationPill({ recording, className })}
1424
+ >
1425
+ {recording ? <View className="h-2 w-2 rounded-full bg-white" /> : null}
1426
+ <Text size="sm" weight="semibold" className="text-white" style={{ fontVariant: ['tabular-nums'] }}>
1427
+ {clock}
1428
+ </Text>
1429
+ </View>
1430
+ );
1431
+ }
1432
+ CameraDuration.displayName = 'Camera.Duration';
1433
+
1434
+ export interface CameraZoomProps extends ViewProps {
1435
+ className?: string;
1436
+ /**
1437
+ * The chips to show, each a value in expo-camera's 0–1 range with the label
1438
+ * you give it. Left out, one `1×` chip that undoes any zoom. The values that
1439
+ * match a given magnification differ from phone to phone, so measure them on
1440
+ * the devices you target before labelling them as one.
1441
+ */
1442
+ stops?: CameraZoomStop[];
1443
+ /** Show a bar of where the zoom sits in the range, which can be dragged, while zoomed in. */
1444
+ bar?: boolean;
1445
+ }
1446
+
1447
+ /**
1448
+ * Zoom stops above the shutter, and a bar that shows how far in the zoom is
1449
+ * once it is past the first.
1450
+ */
1451
+ function CameraZoom({ className, stops, bar = true, ...props }: CameraZoomProps) {
1452
+ const camera = useCameraContext('Camera.Zoom');
1453
+ const chips = stops ?? DEFAULT_ZOOM_STOPS;
1454
+ const active = activeStop(camera.zoom, chips);
1455
+ const [dragging, setDragging] = useState(false);
1456
+ const showBar = bar && (camera.zoom > 0.005 || dragging);
1457
+
1458
+ return (
1459
+ <View {...props} pointerEvents="box-none" className={cn('items-center gap-2', className)}>
1460
+ {showBar ? (
1461
+ <ZoomBar zoom={camera.zoom} onChange={camera.setZoom} onDragging={setDragging} />
1462
+ ) : null}
1463
+ <View className="flex-row items-center gap-1 rounded-full bg-black/40 p-1">
1464
+ {chips.map((stop, index) => {
1465
+ const selected = index === active;
1466
+ return (
1467
+ <AnimatedPressable
1468
+ key={`${stop.label}-${index}`}
1469
+ onPress={() => {
1470
+ if (camera.haptics) selectionTick();
1471
+ camera.setZoom(stop.value);
1472
+ }}
1473
+ hitSlop={4}
1474
+ pressScale={0.92}
1475
+ accessibilityRole="button"
1476
+ accessibilityLabel={stop.accessibilityLabel ?? `Zoom ${stop.label}`}
1477
+ accessibilityState={{ selected }}
1478
+ className={cn(
1479
+ 'h-8 min-w-8 items-center justify-center rounded-full px-2',
1480
+ selected && 'bg-white'
1481
+ )}
1482
+ >
1483
+ <Text size="xs" className={chromeText({ active: selected })}>
1484
+ {stop.label}
1485
+ </Text>
1486
+ </AnimatedPressable>
1487
+ );
1488
+ })}
1489
+ </View>
1490
+ </View>
1491
+ );
1492
+ }
1493
+ CameraZoom.displayName = 'Camera.Zoom';
1494
+
1495
+ function ZoomBar({
1496
+ zoom,
1497
+ onChange,
1498
+ onDragging,
1499
+ }: {
1500
+ zoom: number;
1501
+ onChange: (zoom: number) => void;
1502
+ onDragging: (dragging: boolean) => void;
1503
+ }) {
1504
+ const gesture = useMemo(
1505
+ () =>
1506
+ Gesture.Pan()
1507
+ .minDistance(0)
1508
+ .onBegin((event) => {
1509
+ 'worklet';
1510
+ runOnJS(onDragging)(true);
1511
+ runOnJS(onChange)(zoomFromTrack(event.x, ZOOM_BAR_WIDTH));
1512
+ })
1513
+ .onUpdate((event) => {
1514
+ 'worklet';
1515
+ runOnJS(onChange)(zoomFromTrack(event.x, ZOOM_BAR_WIDTH));
1516
+ })
1517
+ .onFinalize(() => {
1518
+ 'worklet';
1519
+ runOnJS(onDragging)(false);
1520
+ }),
1521
+ [onChange, onDragging]
1522
+ );
1523
+
1524
+ const onAccessibilityAction = (event: AccessibilityActionEvent) => {
1525
+ if (event.nativeEvent.actionName === 'increment') onChange(stepZoom(zoom, 1));
1526
+ else if (event.nativeEvent.actionName === 'decrement') onChange(stepZoom(zoom, -1));
1527
+ };
1528
+
1529
+ return (
1530
+ <GestureDetector gesture={gesture}>
1531
+ <View
1532
+ accessible
1533
+ accessibilityRole="adjustable"
1534
+ accessibilityLabel="Zoom"
1535
+ accessibilityValue={{ min: 0, max: 100, now: Math.round(zoom * 100) }}
1536
+ accessibilityActions={[{ name: 'increment' }, { name: 'decrement' }]}
1537
+ onAccessibilityAction={onAccessibilityAction}
1538
+ style={{ width: ZOOM_BAR_WIDTH, height: 28 }}
1539
+ className="flex-row items-center justify-between"
1540
+ >
1541
+ {Array.from({ length: ZOOM_TICKS }, (_, index) => (
1542
+ <View
1543
+ key={index}
1544
+ className={index % 5 === 0 ? 'h-3 w-px bg-white/80' : 'h-2 w-px bg-white/40'}
1545
+ />
1546
+ ))}
1547
+ <View
1548
+ pointerEvents="none"
1549
+ style={{ position: 'absolute', left: zoom * ZOOM_BAR_WIDTH - 1, top: 2, bottom: 2 }}
1550
+ className="w-0.5 rounded-full bg-white"
1551
+ />
1552
+ </View>
1553
+ </GestureDetector>
1554
+ );
1555
+ }
1556
+
1557
+ export interface CameraModesProps extends ViewProps {
1558
+ className?: string;
1559
+ /** What each mode is called. */
1560
+ labels?: Partial<Record<CameraMode, string>>;
1561
+ }
1562
+
1563
+ /** Video or photo, as a pill with a thumb that slides between them. Locked while recording. */
1564
+ function CameraModes({ className, labels, ...props }: CameraModesProps) {
1565
+ const camera = useCameraContext('Camera.Modes');
1566
+ const reduced = useReducedMotion();
1567
+ const [layouts, setLayouts] = useState<Partial<Record<CameraMode, { x: number; width: number }>>>({});
1568
+ const thumbX = useSharedValue(0);
1569
+ const thumbWidth = useSharedValue(0);
1570
+ const placed = useRef(false);
1571
+
1572
+ useEffect(() => {
1573
+ const target = layouts[camera.mode];
1574
+ if (!target) return;
1575
+ if (!placed.current || reduced) {
1576
+ placed.current = true;
1577
+ thumbX.value = target.x;
1578
+ thumbWidth.value = target.width;
1579
+ return;
1580
+ }
1581
+ const spring = { damping: 22, stiffness: 260, mass: 0.8 };
1582
+ thumbX.value = withSpring(target.x, spring);
1583
+ thumbWidth.value = withSpring(target.width, spring);
1584
+ }, [camera.mode, layouts, reduced, thumbWidth, thumbX]);
1585
+
1586
+ const thumbStyle = useAnimatedStyle(() => ({
1587
+ width: thumbWidth.value,
1588
+ transform: [{ translateX: thumbX.value }],
1589
+ }));
1590
+
1591
+ const names = { ...MODE_LABELS, ...labels };
1592
+
1593
+ return (
1594
+ <View
1595
+ {...props}
1596
+ accessibilityRole="tablist"
1597
+ className={cn('flex-row items-center rounded-full bg-black/40 p-1', className)}
1598
+ >
1599
+ <Animated.View
1600
+ pointerEvents="none"
1601
+ style={[{ position: 'absolute', left: 0, top: 4, bottom: 4 }, thumbStyle]}
1602
+ className="rounded-full bg-white"
1603
+ />
1604
+ {MODE_ORDER.map((item) => {
1605
+ const selected = camera.mode === item;
1606
+ return (
1607
+ <Pressable
1608
+ key={item}
1609
+ onLayout={(event: LayoutChangeEvent) => {
1610
+ const { x, width } = event.nativeEvent.layout;
1611
+ setLayouts((current) =>
1612
+ current[item]?.x === x && current[item]?.width === width
1613
+ ? current
1614
+ : { ...current, [item]: { x, width } }
1615
+ );
1616
+ }}
1617
+ onPress={() => {
1618
+ if (!selected) camera.setMode(item);
1619
+ }}
1620
+ disabled={camera.recording}
1621
+ accessibilityRole="tab"
1622
+ accessibilityLabel={names[item]}
1623
+ accessibilityState={{ selected, disabled: camera.recording }}
1624
+ className="h-8 items-center justify-center rounded-full px-4"
1625
+ >
1626
+ <Text
1627
+ size="xs"
1628
+ className={cn('uppercase tracking-widest', chromeText({ active: selected }))}
1629
+ >
1630
+ {names[item]}
1631
+ </Text>
1632
+ </Pressable>
1633
+ );
1634
+ })}
1635
+ </View>
1636
+ );
1637
+ }
1638
+ CameraModes.displayName = 'Camera.Modes';
1639
+
1640
+ /* -------------------------------------------------------------------------- */
1641
+ /* The shutter row */
1642
+ /* -------------------------------------------------------------------------- */
1643
+
1644
+ export interface CameraLibraryProps extends Omit<PressableProps, 'children'> {
1645
+ className?: string;
1646
+ /** The thumbnail: the last capture, or the newest photo in the library. An icon without one. */
1647
+ source?: ImageSourcePropType;
1648
+ accessibilityLabel?: string;
1649
+ }
1650
+
1651
+ /** The way into the photos. What it opens is `onPress`'s to decide. */
1652
+ function CameraLibrary({
1653
+ className,
1654
+ source,
1655
+ accessibilityLabel = 'Photos',
1656
+ ...props
1657
+ }: CameraLibraryProps) {
1658
+ useCameraContext('Camera.Library');
1659
+ return (
1660
+ <AnimatedPressable
1661
+ {...props}
1662
+ pressScale={0.94}
1663
+ accessibilityRole="button"
1664
+ accessibilityLabel={accessibilityLabel}
1665
+ className={cn(
1666
+ 'h-12 w-12 items-center justify-center overflow-hidden rounded-full border-2 border-white/80 bg-white/15',
1667
+ className
1668
+ )}
1669
+ >
1670
+ {source ? (
1671
+ <Image
1672
+ source={source}
1673
+ style={StyleSheet.absoluteFill}
1674
+ resizeMode="cover"
1675
+ accessibilityIgnoresInvertColors
1676
+ />
1677
+ ) : (
1678
+ <ImageIcon size={22} color={ON_GLASS} />
1679
+ )}
1680
+ </AnimatedPressable>
1681
+ );
1682
+ }
1683
+ CameraLibrary.displayName = 'Camera.Library';
1684
+
1685
+ export interface CameraFlipProps extends Omit<PressableProps, 'children' | 'onPress'> {
1686
+ className?: string;
1687
+ accessibilityLabel?: string;
1688
+ }
1689
+
1690
+ /** Front and back. Not while recording: the clip would cut between two cameras. */
1691
+ function CameraFlip({ className, accessibilityLabel = 'Switch camera', ...props }: CameraFlipProps) {
1692
+ const camera = useCameraContext('Camera.Flip');
1693
+ const { turn } = camera;
1694
+ const iconStyle = useAnimatedStyle(() => ({
1695
+ transform: [{ rotate: `${turn.value * 360}deg` }],
1696
+ }));
1697
+ const disabled = camera.recording;
1698
+ return (
1699
+ <AnimatedPressable
1700
+ {...props}
1701
+ onPress={camera.flip}
1702
+ disabled={disabled}
1703
+ pressScale={0.92}
1704
+ accessibilityRole="button"
1705
+ accessibilityLabel={accessibilityLabel}
1706
+ accessibilityValue={{ text: camera.facing === 'back' ? 'Back camera' : 'Front camera' }}
1707
+ accessibilityState={{ disabled }}
1708
+ className={cn(
1709
+ 'h-12 w-12 items-center justify-center rounded-full bg-black/40',
1710
+ disabled ? 'opacity-40' : 'opacity-100',
1711
+ className
1712
+ )}
1713
+ >
1714
+ <Animated.View style={iconStyle}>
1715
+ <CameraSwitchIcon size={24} color={ON_GLASS} />
1716
+ </Animated.View>
1717
+ </AnimatedPressable>
1718
+ );
1719
+ }
1720
+ CameraFlip.displayName = 'Camera.Flip';
1721
+
1722
+ export interface CameraShutterProps extends Omit<PressableProps, 'children' | 'onPress'> {
1723
+ className?: string;
1724
+ /** In video, holding the shutter records until it is let go. A tap still starts and stops. */
1725
+ holdToRecord?: boolean;
1726
+ /** Replaces what a press does. The shutter still draws the camera's state. */
1727
+ onPress?: () => void;
1728
+ /**
1729
+ * Read out instead of the label it gives itself, which says what a press
1730
+ * will do: take a photo, cancel the timer, record or stop.
1731
+ */
1732
+ accessibilityLabel?: string;
1733
+ }
1734
+
1735
+ /**
1736
+ * The shutter. A tap takes a photo, after the timer if one is set; in video a
1737
+ * tap starts and stops, and a hold records for as long as it is held. The disc
1738
+ * is white for a photo and red for a video, and squares off while recording. A
1739
+ * ring fills towards `maxDuration` when there is one.
1740
+ */
1741
+ function CameraShutter({
1742
+ className,
1743
+ holdToRecord = true,
1744
+ onPress,
1745
+ accessibilityLabel,
1746
+ ...props
1747
+ }: CameraShutterProps) {
1748
+ const camera = useCameraContext('Camera.Shutter');
1749
+ const reduced = useReducedMotion();
1750
+ const destructive = useCSSVariable('--color-destructive');
1751
+ const video = camera.mode === 'video';
1752
+ const recording = camera.recording;
1753
+
1754
+ const pressed = useSharedValue(0);
1755
+ const stop = useSharedValue(recording ? 1 : 0);
1756
+ const progress = useSharedValue(0);
1757
+ const holding = useRef(false);
1758
+
1759
+ useEffect(() => {
1760
+ const target = recording ? 1 : 0;
1761
+ stop.value = reduced ? target : withTiming(target, { duration: 220 });
1762
+ }, [recording, reduced, stop]);
1763
+
1764
+ useEffect(() => {
1765
+ cancelAnimation(progress);
1766
+ progress.value = 0;
1767
+ if (recording && camera.maxDuration) {
1768
+ progress.value = withTiming(1, { duration: camera.maxDuration * 1000, easing: Easing.linear });
1769
+ }
1770
+ }, [camera.maxDuration, progress, recording]);
1771
+
1772
+ const discStyle = useAnimatedStyle(() => {
1773
+ const size = SHUTTER_DISC + (SHUTTER_STOP - SHUTTER_DISC) * stop.value;
1774
+ const radius = size / 2 + (8 - size / 2) * stop.value;
1775
+ return {
1776
+ width: size,
1777
+ height: size,
1778
+ borderRadius: radius,
1779
+ transform: [{ scale: 1 - pressed.value * 0.08 }],
1780
+ };
1781
+ });
1782
+
1783
+ const ringProps = useAnimatedProps(() => ({
1784
+ strokeDashoffset: RING_LENGTH * (1 - progress.value),
1785
+ }));
1786
+
1787
+ // Stopping is always allowed; starting waits for the camera.
1788
+ const disabled = !recording && !camera.canCapture;
1789
+ const label =
1790
+ accessibilityLabel ??
1791
+ (video
1792
+ ? recording
1793
+ ? 'Stop recording'
1794
+ : 'Record video'
1795
+ : camera.countdown !== null
1796
+ ? 'Cancel timer'
1797
+ : 'Take photo');
1798
+
1799
+ return (
1800
+ <Pressable
1801
+ {...props}
1802
+ disabled={disabled}
1803
+ onPress={onPress ?? camera.press}
1804
+ onLongPress={
1805
+ video && holdToRecord && !onPress
1806
+ ? () => {
1807
+ if (camera.recording) return;
1808
+ holding.current = true;
1809
+ void camera.startRecording();
1810
+ }
1811
+ : undefined
1812
+ }
1813
+ delayLongPress={HOLD_TO_RECORD_MS}
1814
+ onPressIn={() => {
1815
+ pressed.value = withTiming(1, { duration: 90 });
1816
+ }}
1817
+ onPressOut={() => {
1818
+ pressed.value = withTiming(0, { duration: 160 });
1819
+ if (holding.current) {
1820
+ holding.current = false;
1821
+ camera.stopRecording();
1822
+ }
1823
+ }}
1824
+ accessibilityRole="button"
1825
+ accessibilityLabel={label}
1826
+ accessibilityHint={
1827
+ video && holdToRecord && !recording ? 'Hold to record for as long as you hold it' : undefined
1828
+ }
1829
+ accessibilityState={{ disabled, busy: camera.capturing }}
1830
+ // Opacity as a style, written every render: a class that comes and goes can leave
1831
+ // the last value on the native view.
1832
+ style={{ width: SHUTTER, height: SHUTTER, opacity: disabled ? 0.6 : 1 }}
1833
+ className={cn('items-center justify-center', className)}
1834
+ >
1835
+ <View
1836
+ pointerEvents="none"
1837
+ style={[StyleSheet.absoluteFill, { borderRadius: SHUTTER / 2, borderWidth: SHUTTER_RING }]}
1838
+ className="border-white"
1839
+ />
1840
+ {camera.maxDuration ? (
1841
+ <Svg pointerEvents="none" width={SHUTTER} height={SHUTTER} style={StyleSheet.absoluteFill}>
1842
+ <AnimatedCircle
1843
+ cx={SHUTTER / 2}
1844
+ cy={SHUTTER / 2}
1845
+ r={RING_RADIUS}
1846
+ fill="none"
1847
+ stroke={typeof destructive === 'string' ? destructive : undefined}
1848
+ strokeWidth={SHUTTER_RING}
1849
+ strokeLinecap="round"
1850
+ strokeDasharray={RING_LENGTH}
1851
+ animatedProps={ringProps}
1852
+ rotation={-90}
1853
+ origin={`${SHUTTER / 2}, ${SHUTTER / 2}`}
1854
+ />
1855
+ </Svg>
1856
+ ) : null}
1857
+ <Animated.View
1858
+ pointerEvents="none"
1859
+ style={discStyle}
1860
+ className={video ? 'bg-destructive' : 'bg-white'}
1861
+ />
1862
+ </Pressable>
1863
+ );
1864
+ }
1865
+ CameraShutter.displayName = 'Camera.Shutter';
1866
+
1867
+ export const Camera = Object.assign(CameraForwarded, {
1868
+ Preview: CameraPreview,
1869
+ Header: CameraHeader,
1870
+ Footer: CameraFooter,
1871
+ Controls: CameraControls,
1872
+ Button: CameraButton,
1873
+ Flash: CameraFlashControl,
1874
+ Timer: CameraTimerControl,
1875
+ Duration: CameraDuration,
1876
+ Zoom: CameraZoom,
1877
+ Modes: CameraModes,
1878
+ Library: CameraLibrary,
1879
+ Flip: CameraFlip,
1880
+ Shutter: CameraShutter,
1881
+ });