Repository navigation
Perf - lazy mount NavigateGlobalCreateProvider for faster scan camera #94693
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
Merged
Julesssss
merged 10 commits into
Expensify:main
from
callstack-internal:perf-scan-camera-lazy-mount
Jul 6, 2026
Merged
Changes from all commits
Commits
Show all changes
10 commits
Select commit
Hold shift + click to select a range
0964835
perf-scan-global-create-refactor
rinej ea8bebb
chore: remove redundant type export
rinej ae6a923
perf: defer post-capture Onyx reads off scan camera mount path
rinej 1da59d5
fix comments
rinej 5d7b23c
Merge branch 'main' into perf-scan-camera-lazy-mount
rinej 908f88a
add unit tests, fix docs
rinej f464c77
adjust testts
rinej 596e3ad
Merge branch 'main' into perf-scan-camera-lazy-mount
rinej d6b7972
Merge branch 'main' into perf-scan-camera-lazy-mount
rinej 37157b4
chore: Oxfmt changnes
rinej File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
143 changes: 143 additions & 0 deletions
143
src/pages/iou/request/step/IOURequestStepScan/components/NavigateGlobalCreateContext.tsx
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,143 @@ | ||
| import type {WithCurrentUserPersonalDetailsProps} from '@components/withCurrentUserPersonalDetails'; | ||
|
|
||
| import useDefaultExpensePolicy from '@hooks/useDefaultExpensePolicy'; | ||
| import useOnyx from '@hooks/useOnyx'; | ||
| import usePersonalPolicy from '@hooks/usePersonalPolicy'; | ||
| import useSelfDMReport from '@hooks/useSelfDMReport'; | ||
|
|
||
| import {navigateToConfirmationPage, navigateToParticipantPage} from '@libs/IOUUtils'; | ||
| import Navigation from '@libs/Navigation/Navigation'; | ||
| import {getPolicyExpenseChat, isSelfDM} from '@libs/ReportUtils'; | ||
| import shouldUseDefaultExpensePolicy from '@libs/shouldUseDefaultExpensePolicy'; | ||
| import {endSpan} from '@libs/telemetry/activeSpans'; | ||
|
|
||
| import startScanProcessSpan from '@pages/iou/request/step/IOURequestStepScan/utils/startScanProcessSpan'; | ||
|
|
||
| import {setMoneyRequestParticipants, setMoneyRequestParticipantsFromReport} from '@userActions/IOU/MoneyRequest'; | ||
| import {setTransactionReport} from '@userActions/Transaction'; | ||
|
|
||
| import CONST from '@src/CONST'; | ||
| import type {IOUType} from '@src/CONST'; | ||
| import ONYXKEYS from '@src/ONYXKEYS'; | ||
| import ROUTES from '@src/ROUTES'; | ||
| import type Transaction from '@src/types/onyx/Transaction'; | ||
|
|
||
| import type {RefObject} from 'react'; | ||
| import type {OnyxEntry} from 'react-native-onyx'; | ||
|
|
||
| /** | ||
| * Owns the post-capture-only Onyx reads used by navigateGlobalCreate. | ||
| * | ||
| * The Provider's root element type stays the same across renders, so the | ||
| * camera isn't torn down when subscriptions become ready. useNavigateGlobalCreate() | ||
| * returns a stable callable. | ||
| */ | ||
| import React, {createContext, useCallback, useContext, useEffect, useRef, useState} from 'react'; | ||
|
|
||
| type NavigateGlobalCreateFn = (transactionIDs: string[], isMultiScanEnabled: boolean) => void; | ||
|
|
||
| type ProviderProps = WithCurrentUserPersonalDetailsProps & { | ||
| iouType: IOUType; | ||
| reportID: string; | ||
| transactionID: string; | ||
| transaction: OnyxEntry<Transaction>; | ||
| backToReport: string | undefined; | ||
| children: React.ReactNode; | ||
| }; | ||
|
|
||
| type SubscriberProps = Omit<ProviderProps, 'children'> & { | ||
| fnRef: RefObject<NavigateGlobalCreateFn>; | ||
| }; | ||
|
|
||
| const NO_OP: NavigateGlobalCreateFn = () => {}; | ||
| const NavigateGlobalCreateContext = createContext<NavigateGlobalCreateFn>(NO_OP); | ||
|
|
||
| function useNavigateGlobalCreate(): NavigateGlobalCreateFn { | ||
| return useContext(NavigateGlobalCreateContext); | ||
| } | ||
|
|
||
| function NavigateGlobalCreateProvider({children, ...rest}: ProviderProps) { | ||
| const fnRef = useRef<NavigateGlobalCreateFn>(NO_OP); | ||
| const [isReady, setIsReady] = useState(false); | ||
|
|
||
| // Stable dispatch — context value identity never changes, so consumers | ||
| // don't re-render on Onyx ticks. Late-binds to fnRef.current at call time. | ||
| const dispatch = useCallback((transactionIDs: string[], isMultiScanEnabled: boolean) => { | ||
| fnRef.current(transactionIDs, isMultiScanEnabled); | ||
| }, []); | ||
|
|
||
| useEffect(() => { | ||
| // eslint-disable-next-line react-hooks/set-state-in-effect -- intentional one-tick defer to keep heavy Onyx subscriptions off the camera-mount critical path | ||
| setIsReady(true); | ||
| }, []); | ||
|
|
||
| return ( | ||
| <NavigateGlobalCreateContext.Provider value={dispatch}> | ||
| {isReady && ( | ||
| <NavigateGlobalCreateSubscriber | ||
| fnRef={fnRef} | ||
| {...rest} | ||
| /> | ||
| )} | ||
| {children} | ||
| </NavigateGlobalCreateContext.Provider> | ||
| ); | ||
| } | ||
|
|
||
| function NavigateGlobalCreateSubscriber({fnRef, iouType, reportID, transactionID, transaction, backToReport, currentUserPersonalDetails}: SubscriberProps) { | ||
| const defaultExpensePolicy = useDefaultExpensePolicy(); | ||
| const personalPolicy = usePersonalPolicy(); | ||
| const selfDMReport = useSelfDMReport(); | ||
| const [amountOwed] = useOnyx(ONYXKEYS.NVP_PRIVATE_AMOUNT_OWED); | ||
| const [userBillingGracePeriodEnds] = useOnyx(ONYXKEYS.COLLECTION.SHARED_NVP_PRIVATE_USER_BILLING_GRACE_PERIOD_END); | ||
| const [ownerBillingGracePeriodEnd] = useOnyx(ONYXKEYS.NVP_PRIVATE_OWNER_BILLING_GRACE_PERIOD_END); | ||
|
|
||
| const navigateGlobalCreate: NavigateGlobalCreateFn = (transactionIDs, isMultiScanEnabled) => { | ||
| startScanProcessSpan(isMultiScanEnabled); | ||
| if (shouldUseDefaultExpensePolicy(iouType, defaultExpensePolicy, amountOwed, userBillingGracePeriodEnds, ownerBillingGracePeriodEnd, currentUserPersonalDetails.accountID)) { | ||
| const shouldAutoReport = !!defaultExpensePolicy?.autoReporting || !!personalPolicy?.autoReporting; | ||
| const targetReport = shouldAutoReport ? getPolicyExpenseChat(currentUserPersonalDetails.accountID, defaultExpensePolicy?.id) : selfDMReport; | ||
| const transactionReportID = isSelfDM(targetReport) ? CONST.REPORT.UNREPORTED_REPORT_ID : targetReport?.reportID; | ||
| const iouTypeTrackOrSubmit = transactionReportID === CONST.REPORT.UNREPORTED_REPORT_ID ? CONST.IOU.TYPE.TRACK : CONST.IOU.TYPE.SUBMIT; | ||
|
|
||
| // If the user previously selected different participants in confirmation, preserve that choice | ||
| if (transaction?.participants && transaction.participants.at(0)?.reportID !== targetReport?.reportID) { | ||
| const isTrackExpense = transaction.participants.at(0)?.reportID === selfDMReport?.reportID; | ||
|
|
||
| const setParticipantsPromises = transactionIDs.map((tid) => setMoneyRequestParticipants(tid, transaction.participants)); | ||
| Promise.all(setParticipantsPromises).then(() => { | ||
| if (isTrackExpense) { | ||
| endSpan(CONST.TELEMETRY.SPAN_SCAN_PROCESS_AND_NAVIGATE); | ||
| Navigation.navigate(ROUTES.MONEY_REQUEST_STEP_CONFIRMATION.getRoute(CONST.IOU.ACTION.CREATE, CONST.IOU.TYPE.TRACK, transactionID, selfDMReport?.reportID)); | ||
| } else { | ||
| navigateToConfirmationPage(iouType, transactionID, reportID, backToReport, iouType === CONST.IOU.TYPE.CREATE, transaction.reportID); | ||
| } | ||
| }); | ||
| return; | ||
| } | ||
|
|
||
| const setParticipantsPromises = transactionIDs.map((tid) => { | ||
| setTransactionReport(tid, {reportID: transactionReportID}, true); | ||
| return setMoneyRequestParticipantsFromReport(tid, targetReport, currentUserPersonalDetails.accountID); | ||
| }); | ||
| Promise.all(setParticipantsPromises).then(() => { | ||
| endSpan(CONST.TELEMETRY.SPAN_SCAN_PROCESS_AND_NAVIGATE); | ||
| Navigation.navigate(ROUTES.MONEY_REQUEST_STEP_CONFIRMATION.getRoute(CONST.IOU.ACTION.CREATE, iouTypeTrackOrSubmit, transactionID, targetReport?.reportID)); | ||
| }); | ||
| } else { | ||
| endSpan(CONST.TELEMETRY.SPAN_SCAN_PROCESS_AND_NAVIGATE); | ||
| navigateToParticipantPage(iouType, transactionID, reportID); | ||
| } | ||
| }; | ||
|
|
||
| useEffect(() => { | ||
| // eslint-disable-next-line no-param-reassign -- publish navigate fn through ref so the context value identity stays stable across Onyx ticks | ||
| fnRef.current = navigateGlobalCreate; | ||
| }); | ||
|
|
||
| return null; | ||
| } | ||
|
|
||
| NavigateGlobalCreateProvider.displayName = 'NavigateGlobalCreateProvider'; | ||
|
|
||
| export {NavigateGlobalCreateProvider, useNavigateGlobalCreate}; | ||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,63 @@ | ||
| /* eslint-disable @typescript-eslint/no-unsafe-type-assertion -- baseProps is a minimal test fixture; casting via `as unknown` keeps the test focused on mount-stability instead of dragging in every field of WithCurrentUserPersonalDetailsProps */ | ||
| import {render} from '@testing-library/react-native'; | ||
|
|
||
| import type {WithCurrentUserPersonalDetailsProps} from '@components/withCurrentUserPersonalDetails'; | ||
|
|
||
| import {NavigateGlobalCreateProvider} from '@pages/iou/request/step/IOURequestStepScan/components/NavigateGlobalCreateContext'; | ||
|
|
||
| import CONST from '@src/CONST'; | ||
|
|
||
| import React, {useEffect} from 'react'; | ||
|
|
||
| import waitForBatchedUpdates from '../utils/waitForBatchedUpdates'; | ||
|
|
||
| // Stub the heavy hooks the Subscriber pulls in — this test only cares about | ||
| // mount stability of the children subtree across the isReady transition. | ||
| jest.mock('@hooks/useDefaultExpensePolicy', () => ({__esModule: true, default: () => undefined})); | ||
| jest.mock('@hooks/usePersonalPolicy', () => ({__esModule: true, default: () => undefined})); | ||
| jest.mock('@hooks/useSelfDMReport', () => ({__esModule: true, default: () => undefined})); | ||
| jest.mock('@hooks/useOnyx', () => ({__esModule: true, default: () => [undefined]})); | ||
|
|
||
| const baseProps = { | ||
| iouType: CONST.IOU.TYPE.CREATE, | ||
| reportID: '1', | ||
| transactionID: 't1', | ||
| transaction: undefined, | ||
| backToReport: undefined, | ||
| currentUserPersonalDetails: {accountID: 1, login: 'a@b.com'}, | ||
| } as unknown as WithCurrentUserPersonalDetailsProps & { | ||
| iouType: typeof CONST.IOU.TYPE.CREATE; | ||
| reportID: string; | ||
| transactionID: string; | ||
| transaction: undefined; | ||
| backToReport: undefined; | ||
| }; | ||
|
|
||
| describe('NavigateGlobalCreateProvider', () => { | ||
| it('does not remount children across the isReady transition', async () => { | ||
| const onMount = jest.fn(); | ||
|
|
||
| function Child() { | ||
| useEffect(() => { | ||
| onMount(); | ||
| }, []); | ||
| return null; | ||
| } | ||
|
|
||
| render( | ||
| <NavigateGlobalCreateProvider {...baseProps}> | ||
| <Child /> | ||
| </NavigateGlobalCreateProvider>, | ||
| ); | ||
|
|
||
| // Wait for the Provider's one-tick useEffect (setIsReady) + the | ||
| // Subscriber to mount and its own useEffect (fnRef publish) to fire. | ||
| await waitForBatchedUpdates(); | ||
| await waitForBatchedUpdates(); | ||
|
|
||
| // If the Provider's root element type ever changes across the isReady | ||
| // flip, React would tear down and rebuild the children subtree — the | ||
| // Camera would remount, and onMount would fire a second time. | ||
| expect(onMount).toHaveBeenCalledTimes(1); | ||
| }); | ||
| }); |
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
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.
NAB: does it make sense to add a small render test here? The tricky part is the
isReadyflip +fnRefpublish, and it could regress silently later. Something that checks the camera subtree stays mounted across the flip, and thatnavigateGlobalCreatestill works once the subscriber is ready. Not blocking.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.
sure, it makes sense, I added tests