Repository navigation
Scan Receipt UX/perf improvements #83470
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Changes from all commits
999dd46
beddf86
d55c5f7
dcf18ee
b11a8d3
e8a21d3
b0a8dd7
55cc60b
296c517
4c5d2cd
e6142a6
28b35aa
957a285
6c23289
2c8824c
b097233
File filter
Filter by extension
Conversations
Jump to
Diff view
Diff view
There are no files selected for viewing
| 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'; | ||
|
|
@@ -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'; | ||
|
|
@@ -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'; | ||
|
|
@@ -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(); | ||
|
|
@@ -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) { | ||
|
|
@@ -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(() => { | ||
|
|
@@ -200,6 +221,7 @@ function IOURequestStepScan({ | |
| useFocusEffect( | ||
| useCallback(() => { | ||
| setDidCapturePhoto(false); | ||
| isCapturingPhoto.current = false; | ||
| const refreshCameraPermissionStatus = () => { | ||
| CameraPermission?.getCameraPermissionStatus?.() | ||
| .then(setCameraPermissionStatus) | ||
|
|
@@ -219,6 +241,7 @@ function IOURequestStepScan({ | |
|
|
||
| return () => { | ||
| subscription.remove(); | ||
| cancelSpan(CONST.TELEMETRY.SPAN_RECEIPT_CAPTURE); | ||
| cancelSpan(CONST.TELEMETRY.SPAN_SHUTTER_TO_CONFIRMATION); | ||
|
|
||
| if (isLoaderVisible) { | ||
|
|
@@ -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(() => { | ||
|
|
@@ -307,6 +328,7 @@ function IOURequestStepScan({ | |
| attributes: {[CONST.TELEMETRY.ATTRIBUTE_PLATFORM]: 'native'}, | ||
| }); | ||
| } | ||
|
|
||
| if (!camera.current && (cameraPermissionStatus === RESULTS.DENIED || cameraPermissionStatus === RESULTS.BLOCKED)) { | ||
| maybeCancelShutterSpan(); | ||
| askForPermissions(); | ||
|
|
@@ -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; | ||
| 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( | ||
|
Contributor
There was a problem hiding this comment. Choose a reason for hiding this commentThe 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?
Contributor
Author
There was a problem hiding this comment. Choose a reason for hiding this commentThe 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, | ||
|
|
@@ -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> | ||
|
|
||
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
didCapturePhotois set totruewhentakePhoto()resolves, but in the multi-scan branch it is synchronously reset tofalsein the same callback. With React Native/React's automatic batching, the camera can skip rendering an intermediatetruestate, soforceInactive={... || 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 👍 / 👎.
There was a problem hiding this comment.
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.