Skip to content

Decompose scan pr2 camera multiscan#87883

Open
rinej wants to merge 3 commits intoExpensify:mainfrom
callstack-internal:decompose-scan-pr2-camera-multiscan
Open

Decompose scan pr2 camera multiscan#87883
rinej wants to merge 3 commits intoExpensify:mainfrom
callstack-internal:decompose-scan-pr2-camera-multiscan

Conversation

@rinej
Copy link
Copy Markdown
Contributor

@rinej rinej commented Apr 14, 2026

Explanation of Change

This is PR 2 of 5 in the IOURequestStepScan decomposition series (see #85571 for the full split plan).
PR 1 (#87083) and PR 2 can land in parallel - they have no shared files
On the PR we extract a unified Camera component with platform variants and MultiScan infrastructure. All new files - no existing code is modified (except adding the ScanRoute type to types.ts).

New files:

  • Camera/index.tsx - web entry point: dispatches mobile → CameraCapture, desktop → FileUpload
  • Camera/index.native.tsx - native: VisionCamera viewfinder with shutter, flash toggle, gallery picker
  • Camera/CameraCapture.tsx - mobile web: webcam capture with viewfinder
  • Camera/FileUpload.tsx - desktop web: drag-and-drop upload area
  • Camera/types.ts - shared CameraProps interface
  • MultiScanContext.tsx - context provider, gate, and hooks for multi-scan state management
  • MultiScanEducationalModal.tsx - educational modal for the multi-scan feature
  • hooks/useScanRouteParams.ts - typed route params for scan screen flows

These components are not yet consumed - they will be wired up in PR 3

Fixed Issues

$ #85583 (comment)
PROPOSAL:

Tests

  • Log in to the app
  • Tap the FAB (+) button → Request money → Scan → verify the existing camera/upload flow works unchanged on all platforms

Offline tests

QA Steps

PR Author Checklist

  • I linked the correct issue in the ### Fixed Issues section above
  • I wrote clear testing steps that cover the changes made in this PR
    • I added steps for local testing in the Tests section
    • I added steps for the expected offline behavior in the Offline steps section
    • I added steps for Staging and/or Production testing in the QA steps section
    • I added steps to cover failure scenarios (i.e. verify an input displays the correct error message if the entered data is not correct)
    • I turned off my network connection and tested it while offline to ensure it matches the expected behavior (i.e. verify the default avatar icon is displayed if app is offline)
    • I tested this PR with a High Traffic account against the staging or production API to ensure there are no regressions (e.g. long loading states that impact usability).
  • I included screenshots or videos for tests on all platforms
  • I ran the tests on all platforms & verified they passed on:
    • Android: Native
    • Android: mWeb Chrome
    • iOS: Native
    • iOS: mWeb Safari
    • MacOS: Chrome / Safari
  • I verified there are no console errors (if there's a console error not related to the PR, report it or open an issue for it to be fixed)
  • I followed proper code patterns (see Reviewing the code)
    • I verified that any callback methods that were added or modified are named for what the method does and never what callback they handle (i.e. toggleReport and not onIconClick)
    • I verified that comments were added to code that is not self explanatory
    • I verified that any new or modified comments were clear, correct English, and explained "why" the code was doing something instead of only explaining "what" the code was doing.
    • I verified any copy / text shown in the product is localized by adding it to src/languages/* files and using the translation method
      • If any non-english text was added/modified, I used JaimeGPT to get English > Spanish translation. I then posted it in #expensify-open-source and it was approved by an internal Expensify engineer. Link to Slack message:
    • I verified all numbers, amounts, dates and phone numbers shown in the product are using the localization methods
    • I verified any copy / text that was added to the app is grammatically correct in English. It adheres to proper capitalization guidelines (note: only the first word of header/labels should be capitalized), and is either coming verbatim from figma or has been approved by marketing (in order to get marketing approval, ask the Bug Zero team member to add the Waiting for copy label to the issue)
    • I verified proper file naming conventions were followed for any new files or renamed files. All non-platform specific files are named after what they export and are not named "index.js". All platform-specific files are named for the platform the code supports as outlined in the README.
    • I verified the JSDocs style guidelines (in STYLE.md) were followed
  • If a new code pattern is added I verified it was agreed to be used by multiple Expensify engineers
  • I followed the guidelines as stated in the Review Guidelines
  • I tested other components that can be impacted by my changes (i.e. if the PR modifies a shared library or component like Avatar, I verified the components using Avatar are working as expected)
  • I verified all code is DRY (the PR doesn't include any logic written more than once, with the exception of tests)
  • I verified any variables that can be defined as constants (ie. in CONST.ts or at the top of the file that uses the constant) are defined as such
  • I verified that if a function's arguments changed that all usages have also been updated correctly
  • If any new file was added I verified that:
    • The file has a description of what it does and/or why is needed at the top of the file if the code is not self explanatory
  • If a new CSS style is added I verified that:
    • A similar style doesn't already exist
    • The style can't be created with an existing StyleUtils function (i.e. StyleUtils.getBackgroundAndBorderStyle(theme.componentBG))
  • If new assets were added or existing ones were modified, I verified that:
    • The assets are optimized and compressed (for SVG files, run npm run compress-svg)
    • The assets load correctly across all supported platforms.
  • If the PR modifies code that runs when editing or sending messages, I tested and verified there is no unexpected behavior for all supported markdown - URLs, single line code, code blocks, quotes, headings, bold, strikethrough, and italic.
  • If the PR modifies a generic component, I tested and verified that those changes do not break usages of that component in the rest of the App (i.e. if a shared library or component like Avatar is modified, I verified that Avatar is working as expected in all cases)
  • If the PR modifies a component related to any of the existing Storybook stories, I tested and verified all stories for that component are still working as expected.
  • If the PR modifies a component or page that can be accessed by a direct deeplink, I verified that the code functions as expected when the deeplink is used - from a logged in and logged out account.
  • If the PR modifies the UI (e.g. new buttons, new UI components, changing the padding/spacing/sizing, moving components, etc) or modifies the form input styles:
    • I verified that all the inputs inside a form are aligned with each other.
    • I added Design label and/or tagged @Expensify/design so the design team can review the changes.
  • If a new page is added, I verified it's using the ScrollView component to make it scrollable when more elements are added to the page.
  • I added unit tests for any new feature or bug fix in this PR to help automatically prevent regressions in this user flow.
  • If the main branch was merged into this PR after a review, I tested again and verified the outcome was still expected according to the Test steps.

Screenshots/Videos

Android: Native
Android: mWeb Chrome
iOS: Native
iOS: mWeb Safari
MacOS: Chrome / Safari

@codecov
Copy link
Copy Markdown

codecov Bot commented Apr 14, 2026

@bernhardoj
Copy link
Copy Markdown
Contributor

I have a few concerns with the new components.

FileUpload is almost identical to DesktopWebUploadView, while CameraCapture is almost identical to MobileWebCameraView. However, there are a few differences between the old and new components that I think are worth considering.

  1. We have useWebCamera, useNativeCamera, useReceiptScan, and useMobileReceiptScan hooks that are created to DRY up the code, but it looks like we don't use them in the new components
  2. Both FileUpload and CameraCapture aren't wrapped with a screen wrapper. DesktopWebUploadView is wrapped with a StepScreenDragAndDropWrapper because it uses isDraggingOverWrapper, while MobileWebCameraView is wrapped with a StepScreenWrapper because mobile web doesn't need a drag and drop context provider.
  3. I assume both FileUpload and CameraCapture are reusable components that will be used for each scan variant, but both components remove some important code, for example:

In FileUpload, we don't have the isReplacingReceipt prop, which means we can't conditionally render the icon and title for the drop zone.

<DropZoneUI
icon={isReplacingReceipt ? lazyIcons.ReplaceReceipt : lazyIcons.SmartScan}
dropStyles={styles.receiptDropOverlay(true)}
dropTitle={isReplacingReceipt ? translate('dropzone.replaceReceipt') : translate(shouldAcceptMultipleFiles ? 'dropzone.scanReceipts' : 'quickAction.scanReceipt')}

We always show blink, even though we only show it when multi-scan is enabled. (maybe expected)

PDFValidationComponent is removed from both files. (maybe expected too because we can put it in the parents)

ReceiptPreviews is removed in CameraCapture.

etc.

From what I understand, we want to create a more focused component (Variant) to reduce unnecessary onyx subscription, which we currently subscribe to many data in useReceiptScan/useMobileReceiptScan, but I think we can create a similar hook that keeps some of the reusable variables that will be used for all variants (if any).

For example, showBlink and blinkStyle for mobile view.

@rinej
Copy link
Copy Markdown
Contributor Author

rinej commented Apr 15, 2026

Thanks for review! These are all intentional and will make more sense once PR 3a/3b land.
The Camera component is meant to be a pure capture/upload primitive with a clean onCapture(file, source) interface. Everything else lives at the variant level

Existing hooks
useReceiptScan / useMobileReceiptScan are the “huge hooks” that cause ~15 unnecessary Onyx subscriptions per mount. They get deleted in PR 4.
Instead of reusing them, each variant co-locates only the logic it needs.

Screen wrappers
Each variant (PR 3b) wraps Camera with the appropriate screen wrapper. Camera itself remains wrapper-agnostic.

That it the main idea - Camera handles capture, variants handle business logic + layout.

Also here is the full plan for the split, for reference -> #85583 (comment)

Do you see any capture/upload logic that should remain inside Camera instead of moving to variants?
And or any edge cases in current scan flows that might get lost in this decomposition?

@rinej rinej marked this pull request as ready for review April 15, 2026 13:15
@rinej rinej requested review from a team as code owners April 15, 2026 13:15
@melvin-bot melvin-bot Bot requested review from bernhardoj and trjExpensify and removed request for a team April 15, 2026 13:16
@melvin-bot
Copy link
Copy Markdown

melvin-bot Bot commented Apr 15, 2026

@bernhardoj Please copy/paste the Reviewer Checklist from here into a new comment on this PR and complete it. If you have the K2 extension, you can simply click: [this button]

@melvin-bot melvin-bot Bot removed the request for review from a team April 15, 2026 13:16
@rinej
Copy link
Copy Markdown
Contributor Author

rinej commented Apr 15, 2026

@bernhardoj also please note, I am going be OOO for a week, but someone from the team will jump to answers all concerns and move it forward

return;
}
queryCameraPermission()
.then((state) => {
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.

❌ PERF-15 (docs)

This useEffect performs async work via queryCameraPermission().then(...) which calls setCameraPermissionState and setIsQueriedPermissionState, but has no cleanup mechanism to discard stale responses. When isTabActive toggles rapidly (e.g., quick tab switches), a slow earlier promise can resolve after a faster later one and overwrite the correct permission state.

Add an ignore flag to prevent stale responses from updating state:

useEffect(() => {
    if (!isTabActive) {
        return;
    }
    let ignore = false;
    queryCameraPermission()
        .then((state) => {
            if (ignore) return;
            setCameraPermissionState(state);
            if (state === 'granted') {
                requestCameraPermission();
            }
        })
        .catch(() => {
            if (ignore) return;
            setCameraPermissionState('denied');
        })
        .finally(() => {
            if (ignore) return;
            setIsQueriedPermissionState(true);
        });
    return () => { ignore = true; };
    // eslint-disable-next-line react-hooks/exhaustive-deps
}, [isTabActive]);

Reviewed at: 81d47b7 | Please rate this suggestion with 👍 or 👎 to help us improve! Reactions are used to monitor reviewer efficiency.

fill={isFlashLightOn ? theme.white : theme.icon}
/>
</PressableWithFeedback>
</View>
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.

❌ CONSISTENCY-2 (docs)

Hardcoded icon sizes 16 and 32 are used throughout this file (lines 362, 395, 426, 442) instead of the named constants already defined in the codebase: variables.iconSizeSmall (16) and variables.iconSizeMenuItem (32).

Replace the magic numbers with the existing named constants:

import variables from '@styles/variables';

// Instead of height={16} width={16}
height={variables.iconSizeSmall}
width={variables.iconSizeSmall}

// Instead of height={32} width={32}
height={variables.iconSizeMenuItem}
width={variables.iconSizeMenuItem}

Reviewed at: 81d47b7 | Please rate this suggestion with 👍 or 👎 to help us improve! Reactions are used to monitor reviewer efficiency.

onPress={() => setFlash((prevFlash) => !prevFlash)}
>
<Icon
height={16}
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.

❌ CONSISTENCY-2 (docs)

Same as in CameraCapture.tsx: hardcoded icon sizes 16 and 32 are used throughout this file (lines ~394, ~429, ~461, ~477) instead of the named constants variables.iconSizeSmall (16) and variables.iconSizeMenuItem (32).

Replace with the existing named constants:

import variables from '@styles/variables';

height={variables.iconSizeSmall}
width={variables.iconSizeSmall}

height={variables.iconSizeMenuItem}
width={variables.iconSizeMenuItem}

Reviewed at: 81d47b7 | Please rate this suggestion with 👍 or 👎 to help us improve! Reactions are used to monitor reviewer efficiency.

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.

We previously used variables.iconSizeSmall here

<View
style={[styles.uploadFileViewTextContainer, styles.userSelectNone]}
// eslint-disable-next-line react/jsx-props-no-spreading, react-hooks/refs
{...panResponderRef.current.panHandlers}
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.

❌ CONSISTENCY-5 (docs)

The eslint-disable-next-line react/jsx-props-no-spreading, react-hooks/refs comment lacks a justification explaining why these rules are disabled.

Add a comment explaining the reason, for example:

{/* PanResponder handlers must be spread onto the View for gesture recognition */}
{/* eslint-disable-next-line react/jsx-props-no-spreading, react-hooks/refs */}
{...panResponderRef.current.panHandlers}

Reviewed at: 81d47b7 | Please rate this suggestion with 👍 or 👎 to help us improve! Reactions are used to monitor reviewer efficiency.

* Camera — web entry point.
* On mobile browsers renders a camera viewfinder (CameraCapture).
* On desktop browsers renders a drag-and-drop / file-picker upload area (FileUpload).
*/
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.

❌ CONSISTENCY-5 (docs)

The eslint-disable-next-line react/jsx-props-no-spreading comments at lines 11 and 19 lack justification explaining why the rule is disabled.

Add a comment explaining the reason, for example:

{/* Props are forwarded as-is to the platform-specific variant */}
{/* eslint-disable-next-line react/jsx-props-no-spreading */}
{...props}

Reviewed at: 81d47b7 | Please rate this suggestion with 👍 or 👎 to help us improve! Reactions are used to monitor reviewer efficiency.

Copy link
Copy Markdown

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Choose a reason for hiding this comment

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

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: 81d47b7aa4

ℹ️ About Codex in GitHub

Codex has been enabled to automatically review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

When you sign up for Codex through ChatGPT, Codex can also answer questions or update the PR, like "@codex address that feedback".

* Multi-scan is a camera-based mobile interaction; desktop uses file picker with shouldAcceptMultipleFiles instead.
*/
function MultiScanGate({children}: MultiScanProviderProps) {
if (isMobile()) {
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 Gate multi-scan provider for native builds

MultiScanGate currently uses isMobile() to decide whether to mount MultiScanProvider, but in native bundles @libs/Browser/index.ts returns false for isMobile(). That means native screens will bypass the provider and useMultiScanState()/useMultiScanActions() fall back to defaults, so multi-scan never becomes available once this component is wired in. Please switch this gate to a platform check that includes native (not only mobile web).

Useful? React with 👍 / 👎.

const [dismissedProductTrainingResult] = useOnyx(ONYXKEYS.NVP_DISMISSED_PRODUCT_TRAINING);
const [draftTransactionIDs] = useOnyx(ONYXKEYS.COLLECTION.TRANSACTION_DRAFT, {selector: validTransactionDraftIDsSelector});

const canUseMultiScan = iouType !== CONST.IOU.TYPE.SPLIT;
Copy link
Copy Markdown

Choose a reason for hiding this comment

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

P2 Badge Restrict multi-scan to create-scan flow

canUseMultiScan now only checks iouType !== SPLIT, but existing scan logic (hooks/useMobileReceiptScan.ts) also requires the CREATE/start-scan context. With this condition, STEP_SCAN edit/replace flows can incorrectly show the multi-scan toggle, and toggling it calls removeTransactionReceipt/removeDraftTransactionsByIDs, which can clear draft receipt state unexpectedly during edit flows. Preserve the previous start-flow guard when deriving canUseMultiScan.

Useful? React with 👍 / 👎.

setDeviceConstraints(defaultConstraints);
return;
}
navigator.mediaDevices.enumerateDevices().then((devices) => {
Copy link
Copy Markdown

Choose a reason for hiding this comment

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

P2 Badge Handle enumerateDevices rejection in camera setup

In requestCameraPermission, enumerateDevices() is called without a rejection handler. If the browser rejects enumeration (which can happen on some permission/device states), deviceConstraints is never set and the UI can stay in the loading state (cameraPermissionState === 'granted' while constraints remain empty). Add a .catch fallback to defaultConstraints as done in the existing useWebCamera implementation.

Useful? React with 👍 / 👎.

@bernhardoj
Copy link
Copy Markdown
Contributor

Do you see any capture/upload logic that should remain inside Camera instead of moving to variants?

I think we should keep using both useWebCamera and useNativeCamera. We are currently duplicating the code from the hook in CameraCapture, FileUpload, and Camera/index.native.tsx.

return (
<View
style={styles.flex1}
onLayout={() => onLayout?.()}
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.

I think we can just do

Suggested change
onLayout={() => onLayout?.()}
onLayout={onLayout}

>
<View style={[styles.flex1]}>
{cameraPermissionStatus !== RESULTS.GRANTED && (
<View style={[styles.cameraView, styles.permissionView, styles.userSelectNone]}>
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.

In main, we have a conditional style for landscape mode.

<View style={[styles.cameraView, isInLandscapeMode ? styles.permissionViewLandscape : styles.permissionView, styles.userSelectNone]}>

>
<Icon
height={32}
width={32}
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.

Let's use variables.iconSizeMenuItem here

>
<Icon
height={32}
width={32}
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.

Let's use variables.iconSizeMenuItem here

>
<Icon
height={32}
width={32}
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.

Let's use variables.iconSizeMenuItem here

<View style={[styles.flexRow, styles.justifyContentAround, styles.alignItemsCenter, styles.pv3]}>
<AttachmentPicker
onOpenPicker={() => {
setIsAttachmentPickerActive(true);
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.

Looks like we removed setIsLoaderVisible from here. I see that this loader context is used for attachment-related features. I think at least we should add a callback here so each variant can call setIsLoaderVisible (it'll be duplicated code though).

</View>
<DragAndDropConsumer onDrop={handleDrop}>
<DropZoneUI
icon={lazyIcons.SmartScan}
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.

What's the plan for the "replace" case here?

icon={isReplacingReceipt ? lazyIcons.ReplaceReceipt : lazyIcons.SmartScan}

Maybe we can pass the icon and dropTitle as props?

style={[styles.flex1, styles.chooseFilesView(false)]}
>
<View style={[styles.flex1, styles.alignItemsCenter, styles.justifyContentCenter]}>
{!isDraggingOver && (
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.

We previously also used isDraggingOverWrapper from the StepScreenDragAndDropWrapper.

{!(isDraggingOver ?? isDraggingOverWrapper) && (

So, in prod, we get the isDraggingOver state from 2 providers.

1 from IOURequestStartPage, and 1 from the StepScreenDragAndDropWrapper. In this PR, we only get it from IOURequestStartPage.


return (
<View
onLayout={() => onLayout?.()}
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.

Suggested change
onLayout={() => onLayout?.()}
onLayout={onLayout}

size={CONST.ACTIVITY_INDICATOR_SIZE.LARGE}
style={[styles.flex1]}
color={theme.textSupporting}
reasonAttributes={{context: 'CameraCapture', cameraPermissionState, videoConstraintsReady: !isEmptyObject(videoConstraints)}}
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.

Looks like the last attribute is different than what we had before (I think we should use both though)

reasonAttributes={
{
context: 'MobileWebCameraView',
cameraPermissionState,
isQueriedPermissionState,
} satisfies SkeletonSpanReasonAttributes

@trjExpensify trjExpensify removed their request for review April 16, 2026 22:21
@trjExpensify
Copy link
Copy Markdown
Contributor

PR doesn’t need product input as a refactor PR. Unassigning and unsubscribing myself.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants