Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
168 changes: 85 additions & 83 deletions src/pages/iou/request/step/IOURequestStepScan/index.native.tsx
Original file line number Diff line number Diff line change
@@ -1,13 +1,12 @@
import {useFocusEffect} from '@react-navigation/core';
import React, {useCallback, useEffect, useRef, useState} from 'react';
import {Alert, AppState, StyleSheet, View} from 'react-native';
import type {LayoutRectangle} from 'react-native';
import ReactNativeBlobUtil from 'react-native-blob-util';
import {Gesture, GestureDetector} from 'react-native-gesture-handler';
import {RESULTS} from 'react-native-permissions';
import Animated, {useAnimatedStyle, useSharedValue, withDelay, withSequence, withSpring, withTiming} from 'react-native-reanimated';
import type {Camera, PhotoFile, Point} from 'react-native-vision-camera';
import {useCameraDevice} from 'react-native-vision-camera';
import {useCameraDevice, useCameraFormat} from 'react-native-vision-camera';
import {scheduleOnRN} from 'react-native-worklets';
import ActivityIndicator from '@components/ActivityIndicator';
import AttachmentPicker from '@components/AttachmentPicker';
Expand All @@ -24,6 +23,7 @@ import {useMemoizedLazyExpensifyIcons, useMemoizedLazyIllustrations} from '@hook
import useLocalize from '@hooks/useLocalize';
import useOnyx from '@hooks/useOnyx';
import usePolicy from '@hooks/usePolicy';
import useStyleUtils from '@hooks/useStyleUtils';
import useTheme from '@hooks/useTheme';
import useThemeStyles from '@hooks/useThemeStyles';
import {showCameraPermissionsAlert} from '@libs/fileDownload/FileUtils';
Expand All @@ -47,8 +47,6 @@ import ROUTES from '@src/ROUTES';
import type {FileObject} from '@src/types/utils/Attachment';
import {getEmptyObject} from '@src/types/utils/EmptyObject';
import CameraPermission from './CameraPermission';
import {cropImageToAspectRatio} from './cropImageToAspectRatio';
import type {ImageObject} from './cropImageToAspectRatio';
import NavigationAwareCamera from './NavigationAwareCamera/Camera';
import ReceiptPreviews from './ReceiptPreviews';
import type IOURequestStepScanProps from './types';
Expand All @@ -68,12 +66,16 @@ function IOURequestStepScan({
}: IOURequestStepScanProps) {
const theme = useTheme();
const styles = useThemeStyles();
const StyleUtils = useStyleUtils();
const {translate} = useLocalize();
const {isLoaderVisible} = useFullScreenLoaderState();
const {setIsLoaderVisible} = useFullScreenLoaderActions();
const device = useCameraDevice('back', {
physicalDevices: ['wide-angle-camera', 'ultra-wide-angle-camera'],
});
const format = useCameraFormat(device, [{photoAspectRatio: 4 / 3}, {videoResolution: 'max'}, {photoResolution: 'max'}]);
// Format dimensions are in landscape orientation, so height/width gives portrait aspect ratio
const cameraAspectRatio = format ? format.photoHeight / format.photoWidth : undefined;

const navigateBack = () => {
Navigation.goBack();
Expand All @@ -97,6 +99,9 @@ function IOURequestStepScan({
const cameraInitSpanStarted = useRef(false);
const cameraInitialized = useRef(false);

// Ref for double-tap protection (doesn't trigger re-render)
const isCapturingPhoto = useRef(false);

// Start camera init span when permission is granted and camera is ready
useEffect(() => {
if (cameraInitSpanStarted.current || cameraPermissionStatus !== RESULTS.GRANTED || device == null) {
Expand Down Expand Up @@ -144,6 +149,22 @@ function IOURequestStepScan({
endSpan(CONST.TELEMETRY.SPAN_CAMERA_INIT);
}
endSpan(CONST.TELEMETRY.SPAN_OPEN_CREATE_EXPENSE);

// Pre-create upload directory to avoid latency during capture
const path = getReceiptsUploadFolderPath();
ReactNativeBlobUtil.fs
.isDir(path)
.then((isDir) => {
if (isDir) {
return;
}
ReactNativeBlobUtil.fs.mkdir(path).catch((error: string) => {
Log.warn('Error creating the receipts upload directory', error);
});
})
.catch((error: string) => {
Log.warn('Error checking if the upload directory exists', error);
});
}, []);

const askForPermissions = useCallback(() => {
Expand Down Expand Up @@ -200,6 +221,7 @@ function IOURequestStepScan({
useFocusEffect(
useCallback(() => {
setDidCapturePhoto(false);
isCapturingPhoto.current = false;
const refreshCameraPermissionStatus = () => {
CameraPermission?.getCameraPermissionStatus?.()
.then(setCameraPermissionStatus)
Expand All @@ -219,6 +241,7 @@ function IOURequestStepScan({

return () => {
subscription.remove();
cancelSpan(CONST.TELEMETRY.SPAN_RECEIPT_CAPTURE);
cancelSpan(CONST.TELEMETRY.SPAN_SHUTTER_TO_CONFIRMATION);

if (isLoaderVisible) {
Expand Down Expand Up @@ -288,15 +311,13 @@ function IOURequestStepScan({
setIsMultiScanEnabled,
});

const viewfinderLayout = useRef<LayoutRectangle>(null);

const maybeCancelShutterSpan = useCallback(() => {
if (isMultiScanEnabled) {
return;
}

cancelSpan(CONST.TELEMETRY.SPAN_SHUTTER_TO_CONFIRMATION);
cancelSpan(CONST.TELEMETRY.SPAN_RECEIPT_CAPTURE);
cancelSpan(CONST.TELEMETRY.SPAN_SHUTTER_TO_CONFIRMATION);
}, [isMultiScanEnabled]);

const capturePhoto = useCallback(() => {
Expand All @@ -307,6 +328,7 @@ function IOURequestStepScan({
attributes: {[CONST.TELEMETRY.ATTRIBUTE_PLATFORM]: 'native'},
});
}

if (!camera.current && (cameraPermissionStatus === RESULTS.DENIED || cameraPermissionStatus === RESULTS.BLOCKED)) {
maybeCancelShutterSpan();
askForPermissions();
Expand All @@ -323,100 +345,80 @@ function IOURequestStepScan({
return;
}

if (didCapturePhoto) {
if (isCapturingPhoto.current) {
maybeCancelShutterSpan();
return;
}

// Start receipt capture span only after all guards pass
startSpan(CONST.TELEMETRY.SPAN_RECEIPT_CAPTURE, {
name: CONST.TELEMETRY.SPAN_RECEIPT_CAPTURE,
op: CONST.TELEMETRY.SPAN_RECEIPT_CAPTURE,
parentSpan: getSpan(CONST.TELEMETRY.SPAN_SHUTTER_TO_CONFIRMATION),
attributes: {[CONST.TELEMETRY.ATTRIBUTE_PLATFORM]: 'native'},
});

if (isMultiScanEnabled) {
showBlink();
}

setDidCapturePhoto(true);
isCapturingPhoto.current = true;
showBlink();

const path = getReceiptsUploadFolderPath();

ReactNativeBlobUtil.fs
.isDir(path)
.then((isDir) => {
if (isDir) {
camera?.current
?.takePhoto({
flash: flash && hasFlash ? 'on' : 'off',
enableShutterSound: !isPlatformMuted,
path,
})
.then((photo: PhotoFile) => {
setDidCapturePhoto(true);

const transaction =
isMultiScanEnabled && initialTransaction?.receipt?.source
? buildOptimisticTransactionAndCreateDraft({
initialTransaction,
currentUserPersonalDetails,
reportID,
})
: initialTransaction;
const transactionID = transaction?.transactionID ?? initialTransactionID;
const source = getPhotoSource(photo.path);
const filename = photo.path;
endSpan(CONST.TELEMETRY.SPAN_RECEIPT_CAPTURE);

const cameraFile = {
uri: source,
name: filename,
type: 'image/jpeg',
source,
};

setMoneyRequestReceipt(transactionID, source, filename, !isEditing, 'image/jpeg');

if (isEditing) {
updateScanAndNavigate(cameraFile as FileObject, source);
return;
}

ReactNativeBlobUtil.fs.mkdir(path).catch((error: string) => {
Log.warn('Error creating the directory', error);
});
const newReceiptFiles = [...receiptFiles, {file: cameraFile as FileObject, source, transactionID}];
setReceiptFiles(newReceiptFiles);

if (isMultiScanEnabled) {
setDidCapturePhoto(false);
isCapturingPhoto.current = false;
Comment on lines +404 to +406

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P1 Badge Keep freeze state active for multi-scan captures

didCapturePhoto is set to true when takePhoto() resolves, but in the multi-scan branch it is synchronously reset to false in the same callback. With React Native/React's automatic batching, the camera can skip rendering an intermediate true state, so forceInactive={... || didCapturePhoto} never takes effect and the preview does not visibly freeze for multi-scan shots. This regresses the intended UX feedback in the exact mode this change targets.

Useful? React with 👍 / 👎.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The lack of a freeze in multi-scan is intentional as the camera should stay active between shots. This feedback is wrong to say there was a regression as we just implemented this. I tested to be sure and everything looks fine IMO.

return;
}

submitReceipts(newReceiptFiles);
})
.catch((error: string) => {
Log.warn('Error checking if the directory exists', error);
})
.then(() => {
camera?.current
?.takePhoto({
flash: flash && hasFlash ? 'on' : 'off',
enableShutterSound: !isPlatformMuted,
path,
})
.then((photo: PhotoFile) => {
// Store the receipt on the transaction object in Onyx
const transaction =
isMultiScanEnabled && initialTransaction?.receipt?.source
? buildOptimisticTransactionAndCreateDraft({
initialTransaction,
currentUserPersonalDetails,
reportID,
})
: initialTransaction;
const transactionID = transaction?.transactionID ?? initialTransactionID;
const imageObject: ImageObject = {file: photo, filename: photo.path, source: getPhotoSource(photo.path)};
cropImageToAspectRatio(imageObject, viewfinderLayout.current?.width, viewfinderLayout.current?.height, undefined, photo.orientation).then(

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Unrelated to changes, are there other places where we could benifit from this improvement?

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Only the odometer capture flow - but want to do that as a follow up.

({file, filename, source}) => {
endSpan(CONST.TELEMETRY.SPAN_RECEIPT_CAPTURE);
// Add source property to file for prepareRequestPayload compatibility
const cameraFile = {
...file,
source,
};

setMoneyRequestReceipt(transactionID, source, filename, !isEditing, file.type);

if (isEditing) {
updateScanAndNavigate(cameraFile as FileObject, source);
return;
}

const newReceiptFiles = [...receiptFiles, {file: cameraFile as FileObject, source, transactionID}];
setReceiptFiles(newReceiptFiles);

if (isMultiScanEnabled) {
setDidCapturePhoto(false);
return;
}

submitReceipts(newReceiptFiles);
},
);
})
.catch((error: string) => {
setDidCapturePhoto(false);
cancelSpan(CONST.TELEMETRY.SPAN_RECEIPT_CAPTURE);
maybeCancelShutterSpan();
showCameraAlert();
Log.warn('Error taking photo', error);
});
isCapturingPhoto.current = false;
cancelSpan(CONST.TELEMETRY.SPAN_RECEIPT_CAPTURE);
maybeCancelShutterSpan();
showCameraAlert();
Log.warn('Error taking photo', error);
});
// eslint-disable-next-line react-hooks/exhaustive-deps -- askForPermissions is not needed
}, [
cameraPermissionStatus,
didCapturePhoto,
isMultiScanEnabled,
translate,
showBlink,
Expand Down Expand Up @@ -490,24 +492,24 @@ function IOURequestStepScan({
</View>
)}
{cameraPermissionStatus === RESULTS.GRANTED && device != null && (
<View style={[styles.cameraView]}>
<View style={[styles.cameraView, styles.alignItemsCenter]}>
<GestureDetector gesture={tapGesture}>
<View style={styles.flex1}>
<View style={StyleUtils.getCameraViewfinderStyle(cameraAspectRatio)}>
<NavigationAwareCamera
ref={camera}
device={device}
format={format}
style={styles.flex1}
zoom={device.neutralZoom}
photo
cameraTabIndex={1}
onLayout={(e) => (viewfinderLayout.current = e.nativeEvent.layout)}
forceInactive={isAttachmentPickerActive}
forceInactive={isAttachmentPickerActive || didCapturePhoto}
onInitialized={handleCameraInitialized}
/>
<Animated.View style={[styles.cameraFocusIndicator, cameraFocusIndicatorAnimatedStyle]} />
<Animated.View
pointerEvents="none"
style={[StyleSheet.absoluteFillObject, styles.backgroundWhite, blinkStyle, styles.zIndex10]}
style={[StyleSheet.absoluteFillObject, StyleUtils.getBackgroundColorStyle(theme.appBG), blinkStyle, styles.zIndex10]}
/>
</View>
</GestureDetector>
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -120,8 +120,8 @@ function useReceiptScan({

function showBlink() {
blinkOpacity.set(
withTiming(0.4, {duration: 10}, () => {
blinkOpacity.set(withTiming(0, {duration: 50}));
withTiming(1, {duration: 50}, () => {
blinkOpacity.set(withTiming(0, {duration: 150}));
}),
);
HapticFeedback.press();
Expand Down
8 changes: 8 additions & 0 deletions src/styles/utils/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -478,6 +478,13 @@ function getBackgroundColorStyle(backgroundColor: ColorValue): ViewStyle {
};
}

function getCameraViewfinderStyle(aspectRatio: number | undefined): ViewStyle {
if (aspectRatio) {
return {aspectRatio, minWidth: '100%', minHeight: '100%'};
}
return {flex: 1};
}

/**
* Returns a style for text color
*/
Expand Down Expand Up @@ -1297,6 +1304,7 @@ const staticStyleUtils = {
getBackgroundAndBorderStyle,
getBackgroundColorStyle,
getBackgroundColorWithOpacityStyle,
getCameraViewfinderStyle,
getPaddingLeft,
getPaddingRight,
getPaddingBottom,
Expand Down
1 change: 1 addition & 0 deletions tests/ui/IOURequestStepScanTest.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -52,6 +52,7 @@ jest.mock('@hooks/useFilesValidation', () => {

jest.mock('react-native-vision-camera', () => ({
useCameraDevice: jest.fn(() => null),
useCameraFormat: jest.fn(() => null),
}));

function createMinimalReport(reportID: string, policyID: string): Report {
Expand Down
Loading