@chipmobilesdk/rn-camera 0.2.0 → 0.2.1

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.
@@ -1,129 +1,129 @@
1
- /**
2
- * Bidirectional coordinate mapping between preview space and captured-image
3
- * space (FR-036, SC-012).
4
- *
5
- * Pure functions with no native involvement (research R5). Everything needed is
6
- * already known in JavaScript, so keeping this pure is what makes the 2-pixel
7
- * round-trip tolerance verifiable in CI rather than only on a device.
8
- *
9
- * Composition order, preview -> image: undo mirror, undo letterbox/crop offset,
10
- * undo scale, undo orientation. Image -> preview reverses it exactly.
11
- */
12
-
13
- import type { Point, PreviewGeometry, Rect } from '../config/types';
14
-
15
- /** Orientation rotates the image for display, swapping dimensions at 90/270. */
16
- function isQuarterTurn(orientation: number): boolean {
17
- const normalized = ((orientation % 360) + 360) % 360;
18
- return normalized === 90 || normalized === 270;
19
- }
20
-
21
- function normalizeOrientation(orientation: number): 0 | 90 | 180 | 270 {
22
- const normalized = ((Math.round(orientation / 90) * 90) % 360 + 360) % 360;
23
- return normalized as 0 | 90 | 180 | 270;
24
- }
25
-
26
- interface Projection {
27
- readonly scale: number;
28
- readonly offsetX: number;
29
- readonly offsetY: number;
30
- /** Image dimensions as displayed, after orientation. */
31
- readonly displayWidth: number;
32
- readonly displayHeight: number;
33
- }
34
-
35
- function projection(geometry: PreviewGeometry): Projection {
36
- const swap = isQuarterTurn(geometry.orientation);
37
- const displayWidth = swap ? geometry.imageHeight : geometry.imageWidth;
38
- const displayHeight = swap ? geometry.imageWidth : geometry.imageHeight;
39
-
40
- const scaleX = geometry.previewWidth / displayWidth;
41
- const scaleY = geometry.previewHeight / displayHeight;
42
- // `cover` fills and crops the overflow; `contain` fits and letterboxes.
43
- const scale =
44
- geometry.resizeMode === 'cover' ? Math.max(scaleX, scaleY) : Math.min(scaleX, scaleY);
45
-
46
- return {
47
- scale,
48
- // Negative under `cover` (cropped away), positive under `contain`
49
- // (letterbox bands). The same arithmetic covers both.
50
- offsetX: (geometry.previewWidth - displayWidth * scale) / 2,
51
- offsetY: (geometry.previewHeight - displayHeight * scale) / 2,
52
- displayWidth,
53
- displayHeight,
54
- };
55
- }
56
-
57
- /** Display-space point -> original image point, undoing the rotation. */
58
- function unrotate(point: Point, geometry: PreviewGeometry): Point {
59
- switch (normalizeOrientation(geometry.orientation)) {
60
- case 90:
61
- return { x: point.y, y: geometry.imageHeight - point.x };
62
- case 180:
63
- return { x: geometry.imageWidth - point.x, y: geometry.imageHeight - point.y };
64
- case 270:
65
- return { x: geometry.imageWidth - point.y, y: point.x };
66
- default:
67
- return point;
68
- }
69
- }
70
-
71
- /** Original image point -> display-space point, applying the rotation. */
72
- function rotate(point: Point, geometry: PreviewGeometry): Point {
73
- switch (normalizeOrientation(geometry.orientation)) {
74
- case 90:
75
- return { x: geometry.imageHeight - point.y, y: point.x };
76
- case 180:
77
- return { x: geometry.imageWidth - point.x, y: geometry.imageHeight - point.y };
78
- case 270:
79
- return { x: point.y, y: geometry.imageWidth - point.x };
80
- default:
81
- return point;
82
- }
83
- }
84
-
85
- /**
86
- * Maps a preview-space point into captured-image space. Points outside the
87
- * visible region stay representable (they fall outside the image bounds) rather
88
- * than being clamped to an edge, so callers can detect an out-of-frame overlay.
89
- */
90
- export function mapPointToImage(point: Point, geometry: PreviewGeometry): Point {
91
- const { scale, offsetX, offsetY } = projection(geometry);
92
- const x = geometry.isMirrored ? geometry.previewWidth - point.x : point.x;
93
- return unrotate({ x: (x - offsetX) / scale, y: (point.y - offsetY) / scale }, geometry);
94
- }
95
-
96
- /** Maps a captured-image point into preview space. Exact inverse of the above. */
97
- export function mapPointToPreview(point: Point, geometry: PreviewGeometry): Point {
98
- const { scale, offsetX, offsetY } = projection(geometry);
99
- const rotated = rotate(point, geometry);
100
- const x = rotated.x * scale + offsetX;
101
- return {
102
- x: geometry.isMirrored ? geometry.previewWidth - x : x,
103
- y: rotated.y * scale + offsetY,
104
- };
105
- }
106
-
107
- /** Axis-aligned bounding box of the mapped corners — exact for quarter turns. */
108
- function boundsOf(a: Point, b: Point): Rect {
109
- return {
110
- x: Math.min(a.x, b.x),
111
- y: Math.min(a.y, b.y),
112
- width: Math.abs(b.x - a.x),
113
- height: Math.abs(b.y - a.y),
114
- };
115
- }
116
-
117
- export function mapRectToImage(rect: Rect, geometry: PreviewGeometry): Rect {
118
- return boundsOf(
119
- mapPointToImage({ x: rect.x, y: rect.y }, geometry),
120
- mapPointToImage({ x: rect.x + rect.width, y: rect.y + rect.height }, geometry),
121
- );
122
- }
123
-
124
- export function mapRectToPreview(rect: Rect, geometry: PreviewGeometry): Rect {
125
- return boundsOf(
126
- mapPointToPreview({ x: rect.x, y: rect.y }, geometry),
127
- mapPointToPreview({ x: rect.x + rect.width, y: rect.y + rect.height }, geometry),
128
- );
129
- }
1
+ /**
2
+ * Bidirectional coordinate mapping between preview space and captured-image
3
+ * space (FR-036, SC-012).
4
+ *
5
+ * Pure functions with no native involvement (research R5). Everything needed is
6
+ * already known in JavaScript, so keeping this pure is what makes the 2-pixel
7
+ * round-trip tolerance verifiable in CI rather than only on a device.
8
+ *
9
+ * Composition order, preview -> image: undo mirror, undo letterbox/crop offset,
10
+ * undo scale, undo orientation. Image -> preview reverses it exactly.
11
+ */
12
+
13
+ import type { Point, PreviewGeometry, Rect } from '../config/types';
14
+
15
+ /** Orientation rotates the image for display, swapping dimensions at 90/270. */
16
+ function isQuarterTurn(orientation: number): boolean {
17
+ const normalized = ((orientation % 360) + 360) % 360;
18
+ return normalized === 90 || normalized === 270;
19
+ }
20
+
21
+ function normalizeOrientation(orientation: number): 0 | 90 | 180 | 270 {
22
+ const normalized = (((Math.round(orientation / 90) * 90) % 360) + 360) % 360;
23
+ return normalized as 0 | 90 | 180 | 270;
24
+ }
25
+
26
+ interface Projection {
27
+ readonly scale: number;
28
+ readonly offsetX: number;
29
+ readonly offsetY: number;
30
+ /** Image dimensions as displayed, after orientation. */
31
+ readonly displayWidth: number;
32
+ readonly displayHeight: number;
33
+ }
34
+
35
+ function projection(geometry: PreviewGeometry): Projection {
36
+ const swap = isQuarterTurn(geometry.orientation);
37
+ const displayWidth = swap ? geometry.imageHeight : geometry.imageWidth;
38
+ const displayHeight = swap ? geometry.imageWidth : geometry.imageHeight;
39
+
40
+ const scaleX = geometry.previewWidth / displayWidth;
41
+ const scaleY = geometry.previewHeight / displayHeight;
42
+ // `cover` fills and crops the overflow; `contain` fits and letterboxes.
43
+ const scale =
44
+ geometry.resizeMode === 'cover' ? Math.max(scaleX, scaleY) : Math.min(scaleX, scaleY);
45
+
46
+ return {
47
+ scale,
48
+ // Negative under `cover` (cropped away), positive under `contain`
49
+ // (letterbox bands). The same arithmetic covers both.
50
+ offsetX: (geometry.previewWidth - displayWidth * scale) / 2,
51
+ offsetY: (geometry.previewHeight - displayHeight * scale) / 2,
52
+ displayWidth,
53
+ displayHeight,
54
+ };
55
+ }
56
+
57
+ /** Display-space point -> original image point, undoing the rotation. */
58
+ function unrotate(point: Point, geometry: PreviewGeometry): Point {
59
+ switch (normalizeOrientation(geometry.orientation)) {
60
+ case 90:
61
+ return { x: point.y, y: geometry.imageHeight - point.x };
62
+ case 180:
63
+ return { x: geometry.imageWidth - point.x, y: geometry.imageHeight - point.y };
64
+ case 270:
65
+ return { x: geometry.imageWidth - point.y, y: point.x };
66
+ default:
67
+ return point;
68
+ }
69
+ }
70
+
71
+ /** Original image point -> display-space point, applying the rotation. */
72
+ function rotate(point: Point, geometry: PreviewGeometry): Point {
73
+ switch (normalizeOrientation(geometry.orientation)) {
74
+ case 90:
75
+ return { x: geometry.imageHeight - point.y, y: point.x };
76
+ case 180:
77
+ return { x: geometry.imageWidth - point.x, y: geometry.imageHeight - point.y };
78
+ case 270:
79
+ return { x: point.y, y: geometry.imageWidth - point.x };
80
+ default:
81
+ return point;
82
+ }
83
+ }
84
+
85
+ /**
86
+ * Maps a preview-space point into captured-image space. Points outside the
87
+ * visible region stay representable (they fall outside the image bounds) rather
88
+ * than being clamped to an edge, so callers can detect an out-of-frame overlay.
89
+ */
90
+ export function mapPointToImage(point: Point, geometry: PreviewGeometry): Point {
91
+ const { scale, offsetX, offsetY } = projection(geometry);
92
+ const x = geometry.isMirrored ? geometry.previewWidth - point.x : point.x;
93
+ return unrotate({ x: (x - offsetX) / scale, y: (point.y - offsetY) / scale }, geometry);
94
+ }
95
+
96
+ /** Maps a captured-image point into preview space. Exact inverse of the above. */
97
+ export function mapPointToPreview(point: Point, geometry: PreviewGeometry): Point {
98
+ const { scale, offsetX, offsetY } = projection(geometry);
99
+ const rotated = rotate(point, geometry);
100
+ const x = rotated.x * scale + offsetX;
101
+ return {
102
+ x: geometry.isMirrored ? geometry.previewWidth - x : x,
103
+ y: rotated.y * scale + offsetY,
104
+ };
105
+ }
106
+
107
+ /** Axis-aligned bounding box of the mapped corners — exact for quarter turns. */
108
+ function boundsOf(a: Point, b: Point): Rect {
109
+ return {
110
+ x: Math.min(a.x, b.x),
111
+ y: Math.min(a.y, b.y),
112
+ width: Math.abs(b.x - a.x),
113
+ height: Math.abs(b.y - a.y),
114
+ };
115
+ }
116
+
117
+ export function mapRectToImage(rect: Rect, geometry: PreviewGeometry): Rect {
118
+ return boundsOf(
119
+ mapPointToImage({ x: rect.x, y: rect.y }, geometry),
120
+ mapPointToImage({ x: rect.x + rect.width, y: rect.y + rect.height }, geometry),
121
+ );
122
+ }
123
+
124
+ export function mapRectToPreview(rect: Rect, geometry: PreviewGeometry): Rect {
125
+ return boundsOf(
126
+ mapPointToPreview({ x: rect.x, y: rect.y }, geometry),
127
+ mapPointToPreview({ x: rect.x + rect.width, y: rect.y + rect.height }, geometry),
128
+ );
129
+ }
package/src/index.ts CHANGED
@@ -1,78 +1,78 @@
1
- /**
2
- * @chipmobilesdk/rn-camera — reusable camera infrastructure for
3
- * ChipMobileSdk-family React Native apps.
4
- *
5
- * This is the single public entrypoint (LIB-003). Modules under `core/`,
6
- * `native/`, `permissions/`, `storage/`, `geometry/`, `diagnostics/`, and
7
- * `testing/` are private; import them only through this file.
8
- *
9
- * The package contains no business logic, sends nothing over the network, and
10
- * writes nothing to the device gallery. Phase one runs no on-device inference —
11
- * see the reserved frame-processing extension point in the README.
12
- */
13
-
14
- // Public types
15
- export type {
16
- ArtifactOwnership,
17
- CameraErrorLike,
18
- CameraPermissionState,
19
- CameraPosition,
20
- CameraState,
21
- CapabilityProfile,
22
- CapturedImage,
23
- CaptureRequest,
24
- FlashMode,
25
- Known,
26
- Maybe,
27
- Point,
28
- PreviewGeometry,
29
- Rect,
30
- ResizeMode,
31
- SessionStatus,
32
- StartOptions,
33
- Unavailable,
34
- } from './config/types';
35
- export { known, unavailable } from './config/types';
36
-
37
- // Controller
38
- export { createCameraController, DEFAULT_TEMPORARY_TTL_MS } from './core/controller';
39
- export type {
40
- AppStatus,
41
- CameraController,
42
- CameraControllerOptions,
43
- } from './core/controller';
44
-
45
- // Ports + default adapters
46
- export type { CameraEngine, EngineOptions } from './native/cameraEngine';
47
- export { createVisionCameraEngine } from './native/cameraEngine';
48
- export type { PermissionPort } from './permissions/permissionPort';
49
- export { createVisionCameraPermissions } from './permissions/permissionPort';
50
- export type { ArtifactStore, FileSystemBridge, StoreOptions } from './storage/artifactStore';
51
- export { createArtifactStore, createCacheArtifactStore } from './storage/artifactStore';
52
-
53
- // React surface
54
- export { CameraPreview } from './react/CameraPreview';
55
- export type { CameraPreviewProps } from './react/CameraPreview';
56
- export { useCameraController, useCameraState } from './react/hooks';
57
-
58
- // Coordinate mapping (pure)
59
- export {
60
- mapPointToImage,
61
- mapPointToPreview,
62
- mapRectToImage,
63
- mapRectToPreview,
64
- } from './geometry/coordinateMapping';
65
-
66
- // Diagnostics
67
- export { CameraError, isCameraError, redact } from './diagnostics/errors';
68
- export type { CameraErrorCode } from './diagnostics/errors';
69
- export type { CameraLogEvent, CameraLogEventType, CameraLogger } from './diagnostics/logger';
70
-
71
- // Test adapter (FR-041) — exported from the single entrypoint so consumer tests
72
- // exercise the same published ports the real adapters implement.
73
- export { createTestCamera, createMemoryFileSystem, DEFAULT_TEST_CAPABILITIES } from './testing/testCameraAdapter';
74
- export type {
75
- MemoryFileSystem,
76
- TestCameraConfig,
77
- TestCameraHandles,
78
- } from './testing/testCameraAdapter';
1
+ /**
2
+ * @chipmobilesdk/rn-camera — reusable camera infrastructure for
3
+ * ChipMobileSdk-family React Native apps.
4
+ *
5
+ * This is the single public entrypoint (LIB-003). Modules under `core/`,
6
+ * `native/`, `permissions/`, `storage/`, `geometry/`, `diagnostics/`, and
7
+ * `testing/` are private; import them only through this file.
8
+ *
9
+ * The package contains no business logic, sends nothing over the network, and
10
+ * writes nothing to the device gallery. Phase one runs no on-device inference —
11
+ * see the reserved frame-processing extension point in the README.
12
+ */
13
+
14
+ // Public types
15
+ export type {
16
+ ArtifactOwnership,
17
+ CameraErrorLike,
18
+ CameraPermissionState,
19
+ CameraPosition,
20
+ CameraState,
21
+ CapabilityProfile,
22
+ CapturedImage,
23
+ CaptureRequest,
24
+ FlashMode,
25
+ Known,
26
+ Maybe,
27
+ Point,
28
+ PreviewGeometry,
29
+ Rect,
30
+ ResizeMode,
31
+ SessionStatus,
32
+ StartOptions,
33
+ Unavailable,
34
+ } from './config/types';
35
+ export { known, unavailable } from './config/types';
36
+
37
+ // Controller
38
+ export { createCameraController, DEFAULT_TEMPORARY_TTL_MS } from './core/controller';
39
+ export type { AppStatus, CameraController, CameraControllerOptions } from './core/controller';
40
+
41
+ // Ports + default adapters
42
+ export type { CameraEngine, EngineOptions } from './native/cameraEngine';
43
+ export { createVisionCameraEngine } from './native/cameraEngine';
44
+ export type { PermissionPort } from './permissions/permissionPort';
45
+ export { createVisionCameraPermissions } from './permissions/permissionPort';
46
+ export type { ArtifactStore, FileSystemBridge, StoreOptions } from './storage/artifactStore';
47
+ export { createArtifactStore, createCacheArtifactStore } from './storage/artifactStore';
48
+
49
+ // React surface
50
+ export { CameraPreview } from './react/CameraPreview';
51
+ export type { CameraPreviewProps } from './react/CameraPreview';
52
+ export { useCameraController, useCameraState } from './react/hooks';
53
+
54
+ // Coordinate mapping (pure)
55
+ export {
56
+ mapPointToImage,
57
+ mapPointToPreview,
58
+ mapRectToImage,
59
+ mapRectToPreview,
60
+ } from './geometry/coordinateMapping';
61
+
62
+ // Diagnostics
63
+ export { CameraError, isCameraError, redact } from './diagnostics/errors';
64
+ export type { CameraErrorCode } from './diagnostics/errors';
65
+ export type { CameraLogEvent, CameraLogEventType, CameraLogger } from './diagnostics/logger';
66
+
67
+ // Test adapter (FR-041) — exported from the single entrypoint so consumer tests
68
+ // exercise the same published ports the real adapters implement.
69
+ export {
70
+ createTestCamera,
71
+ createMemoryFileSystem,
72
+ DEFAULT_TEST_CAPABILITIES,
73
+ } from './testing/testCameraAdapter';
74
+ export type {
75
+ MemoryFileSystem,
76
+ TestCameraConfig,
77
+ TestCameraHandles,
78
+ } from './testing/testCameraAdapter';
@@ -1,125 +1,126 @@
1
- /**
2
- * Camera preview surface (FR-009..FR-013, UX-001, UX-003).
3
- *
4
- * Renders the camera feed and nothing else: no shutter button, no permission
5
- * copy, no error text, and no theme dependency. Consuming apps draw their own
6
- * controls and overlays through `children`, positioned with the geometry
7
- * reported by `onGeometryChange`.
8
- */
9
-
10
- import React, { useCallback, useEffect, useMemo, useState } from 'react';
11
- import {
12
- View,
13
- type AccessibilityRole,
14
- type LayoutChangeEvent,
15
- type StyleProp,
16
- type ViewStyle,
17
- } from 'react-native';
18
-
19
- import type { PreviewGeometry, ResizeMode } from '../config/types';
20
- import type { CameraController } from '../core/controller';
21
- import { useCameraState } from './hooks';
22
- import type { VisionCameraFeedProps } from './VisionCameraFeed';
23
-
24
- export interface CameraPreviewProps {
25
- readonly controller: CameraController;
26
- readonly resizeMode?: ResizeMode;
27
- readonly style?: StyleProp<ViewStyle>;
28
- readonly onGeometryChange?: (geometry: PreviewGeometry) => void;
29
- /** Forwarded untouched; the package never overrides consumer a11y (UX-003). */
30
- readonly accessibilityLabel?: string;
31
- readonly accessibilityRole?: AccessibilityRole;
32
- /** Overlay layer rendered above the feed. */
33
- readonly children?: React.ReactNode;
34
- }
35
-
36
- /** Nominal capture dimensions until the engine reports the real format. */
37
- const DEFAULT_IMAGE_WIDTH = 1920;
38
- const DEFAULT_IMAGE_HEIGHT = 1080;
39
-
40
- export const CameraPreview: React.FC<CameraPreviewProps> = ({
41
- controller,
42
- resizeMode = 'cover',
43
- style,
44
- onGeometryChange,
45
- accessibilityLabel,
46
- accessibilityRole,
47
- children,
48
- }) => {
49
- const [layout, setLayout] = useState<{ width: number; height: number } | null>(null);
50
- // Subscribed, not read once: a plain `controller.state` read only refreshed
51
- // when the parent happened to re-render, so the feed could stay unmounted
52
- // after the session became active (or stay mounted after it stopped).
53
- const state = useCameraState(controller);
54
-
55
- // Tell the controller a surface exists so foregrounding can restart the
56
- // session, and clear it on unmount so the camera is released (FR-016). Both
57
- // calls are no-ops on an idle or disposed controller.
58
- useEffect(() => {
59
- controller.setSurfaceMounted(true);
60
- return () => {
61
- controller.setSurfaceMounted(false);
62
- controller.stop().catch(() => undefined);
63
- };
64
- }, [controller]);
65
-
66
- const onLayout = useCallback((event: LayoutChangeEvent) => {
67
- const { width, height } = event.nativeEvent.layout;
68
- setLayout({ width, height });
69
- }, []);
70
-
71
- const geometry = useMemo<PreviewGeometry | null>(() => {
72
- if (!layout || layout.width === 0 || layout.height === 0) {
73
- return null;
74
- }
75
- return {
76
- imageWidth: DEFAULT_IMAGE_WIDTH,
77
- imageHeight: DEFAULT_IMAGE_HEIGHT,
78
- previewWidth: layout.width,
79
- previewHeight: layout.height,
80
- resizeMode,
81
- orientation: 0,
82
- isMirrored: state.cameraPosition === 'front',
83
- };
84
- }, [layout, resizeMode, state.cameraPosition]);
85
-
86
- useEffect(() => {
87
- if (geometry && onGeometryChange) {
88
- onGeometryChange(geometry);
89
- }
90
- }, [geometry, onGeometryChange]);
91
-
92
- const feedRequested = state.session === 'active' && state.permission === 'granted';
93
-
94
- // Lazy require so importing this package never pulls in the native module
95
- // for consumers that only use the pure utilities or the test adapter.
96
- const Feed = useMemo(() => {
97
- if (!feedRequested) {
98
- return null;
99
- }
100
- try {
101
- return require('./VisionCameraFeed')
102
- .VisionCameraFeed as React.ComponentType<VisionCameraFeedProps>;
103
- } catch {
104
- return null;
105
- }
106
- }, [feedRequested]);
107
-
108
- return (
109
- <View
110
- style={style}
111
- onLayout={onLayout}
112
- accessibilityLabel={accessibilityLabel}
113
- accessibilityRole={accessibilityRole}
114
- testID="rn-camera-preview">
115
- {Feed ? (
116
- <Feed
117
- cameraPosition={state.cameraPosition}
118
- resizeMode={resizeMode}
119
- torchEnabled={state.torchEnabled}
120
- />
121
- ) : null}
122
- {children}
123
- </View>
124
- );
125
- };
1
+ /**
2
+ * Camera preview surface (FR-009..FR-013, UX-001, UX-003).
3
+ *
4
+ * Renders the camera feed and nothing else: no shutter button, no permission
5
+ * copy, no error text, and no theme dependency. Consuming apps draw their own
6
+ * controls and overlays through `children`, positioned with the geometry
7
+ * reported by `onGeometryChange`.
8
+ */
9
+
10
+ import React, { useCallback, useEffect, useMemo, useState } from 'react';
11
+ import {
12
+ View,
13
+ type AccessibilityRole,
14
+ type LayoutChangeEvent,
15
+ type StyleProp,
16
+ type ViewStyle,
17
+ } from 'react-native';
18
+
19
+ import type { PreviewGeometry, ResizeMode } from '../config/types';
20
+ import type { CameraController } from '../core/controller';
21
+ import { useCameraState } from './hooks';
22
+ import type { VisionCameraFeedProps } from './VisionCameraFeed';
23
+
24
+ export interface CameraPreviewProps {
25
+ readonly controller: CameraController;
26
+ readonly resizeMode?: ResizeMode;
27
+ readonly style?: StyleProp<ViewStyle>;
28
+ readonly onGeometryChange?: (geometry: PreviewGeometry) => void;
29
+ /** Forwarded untouched; the package never overrides consumer a11y (UX-003). */
30
+ readonly accessibilityLabel?: string;
31
+ readonly accessibilityRole?: AccessibilityRole;
32
+ /** Overlay layer rendered above the feed. */
33
+ readonly children?: React.ReactNode;
34
+ }
35
+
36
+ /** Nominal capture dimensions until the engine reports the real format. */
37
+ const DEFAULT_IMAGE_WIDTH = 1920;
38
+ const DEFAULT_IMAGE_HEIGHT = 1080;
39
+
40
+ export const CameraPreview: React.FC<CameraPreviewProps> = ({
41
+ controller,
42
+ resizeMode = 'cover',
43
+ style,
44
+ onGeometryChange,
45
+ accessibilityLabel,
46
+ accessibilityRole,
47
+ children,
48
+ }) => {
49
+ const [layout, setLayout] = useState<{ width: number; height: number } | null>(null);
50
+ // Subscribed, not read once: a plain `controller.state` read only refreshed
51
+ // when the parent happened to re-render, so the feed could stay unmounted
52
+ // after the session became active (or stay mounted after it stopped).
53
+ const state = useCameraState(controller);
54
+
55
+ // Tell the controller a surface exists so foregrounding can restart the
56
+ // session, and clear it on unmount so the camera is released (FR-016). Both
57
+ // calls are no-ops on an idle or disposed controller.
58
+ useEffect(() => {
59
+ controller.setSurfaceMounted(true);
60
+ return () => {
61
+ controller.setSurfaceMounted(false);
62
+ controller.stop().catch(() => undefined);
63
+ };
64
+ }, [controller]);
65
+
66
+ const onLayout = useCallback((event: LayoutChangeEvent) => {
67
+ const { width, height } = event.nativeEvent.layout;
68
+ setLayout({ width, height });
69
+ }, []);
70
+
71
+ const geometry = useMemo<PreviewGeometry | null>(() => {
72
+ if (!layout || layout.width === 0 || layout.height === 0) {
73
+ return null;
74
+ }
75
+ return {
76
+ imageWidth: DEFAULT_IMAGE_WIDTH,
77
+ imageHeight: DEFAULT_IMAGE_HEIGHT,
78
+ previewWidth: layout.width,
79
+ previewHeight: layout.height,
80
+ resizeMode,
81
+ orientation: 0,
82
+ isMirrored: state.cameraPosition === 'front',
83
+ };
84
+ }, [layout, resizeMode, state.cameraPosition]);
85
+
86
+ useEffect(() => {
87
+ if (geometry && onGeometryChange) {
88
+ onGeometryChange(geometry);
89
+ }
90
+ }, [geometry, onGeometryChange]);
91
+
92
+ const feedRequested = state.session === 'active' && state.permission === 'granted';
93
+
94
+ // Lazy require so importing this package never pulls in the native module
95
+ // for consumers that only use the pure utilities or the test adapter.
96
+ const Feed = useMemo(() => {
97
+ if (!feedRequested) {
98
+ return null;
99
+ }
100
+ try {
101
+ return require('./VisionCameraFeed')
102
+ .VisionCameraFeed as React.ComponentType<VisionCameraFeedProps>;
103
+ } catch {
104
+ return null;
105
+ }
106
+ }, [feedRequested]);
107
+
108
+ return (
109
+ <View
110
+ style={style}
111
+ onLayout={onLayout}
112
+ accessibilityLabel={accessibilityLabel}
113
+ accessibilityRole={accessibilityRole}
114
+ testID="rn-camera-preview"
115
+ >
116
+ {Feed ? (
117
+ <Feed
118
+ cameraPosition={state.cameraPosition}
119
+ resizeMode={resizeMode}
120
+ torchEnabled={state.torchEnabled}
121
+ />
122
+ ) : null}
123
+ {children}
124
+ </View>
125
+ );
126
+ };