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
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
import {useFocusEffect} from '@react-navigation/native';
import {FlashList} from '@shopify/flash-list';
import type {FlashListRef, ListRenderItemInfo} from '@shopify/flash-list';
import React, {useCallback, useDeferredValue, useEffect, useMemo, useRef, useState} from 'react';
Expand Down Expand Up @@ -104,6 +105,7 @@ const reportAttributesSelector = (c: OnyxEntry<ReportAttributesDerivedValue>) =>

function MoneyRequestReportPreviewContent({
iouReportID,
newTransactionIDs,
chatReportID,
action,
containerStyles,
Expand Down Expand Up @@ -453,7 +455,7 @@ function MoneyRequestReportPreviewContent({
thumbsUpScale.set(isApprovedAnimationRunning ? withDelay(CONST.ANIMATION_THUMBS_UP_DELAY, withSpring(1, {duration: CONST.ANIMATION_THUMBS_UP_DURATION})) : 1);
}, [isApproved, isApprovedAnimationRunning, thumbsUpScale]);

const carouselTransactions = shouldShowAccessPlaceHolder ? [] : transactions.slice(0, 11);
const carouselTransactions = useMemo(() => (shouldShowAccessPlaceHolder ? [] : transactions.slice(0, 11)), [shouldShowAccessPlaceHolder, transactions]);
const prevCarouselTransactionLength = useRef(0);

useEffect(() => {
Expand All @@ -480,6 +482,34 @@ function MoneyRequestReportPreviewContent({
return {itemVisiblePercentThreshold: 100};
}, []);

const carouselTransactionsRef = useRef(carouselTransactions);

useEffect(() => {
carouselTransactionsRef.current = carouselTransactions;
}, [carouselTransactions]);

useFocusEffect(
useCallback(() => {

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-2 (docs)

The findIndex callback performs an expensive operation (array lookup with .includes()) for every transaction without any early filtering. This could be optimized by converting newTransactionIDs to a Set for O(1) lookup instead of O(n) lookup with array .includes().

Fix: Convert to a Set for faster lookups:

useFocusEffect(
    useCallback(() => {
        const newTransactionIDsSet = new Set(newTransactionIDs);
        const index = carouselTransactions.findIndex((transaction) => newTransactionIDsSet.has(transaction.transactionID));

        if (index < 0) {
            return;
        }
        // ... rest of the code
    }, [newTransactionIDs]),
);

Please rate this suggestion with 👍 or 👎 to help us improve! Reactions are used to monitor reviewer efficiency.

const index = carouselTransactions.findIndex((transaction) => newTransactionIDs?.has(transaction.transactionID));

if (index < 0) {
return;
}
const newTransaction = carouselTransactions.at(index);

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.

❌ PERFORMANCE-12 (docs)

The setTimeout call inside useFocusEffect is not cleared when the component loses focus or unmounts, which can cause memory leaks and potential crashes if the component is unmounted before the timeout fires.

Fix: Return a cleanup function from the callback that clears the timeout:

useFocusEffect(
    useCallback(() => {
        const index = carouselTransactions.findIndex((transaction) => newTransactionIDs?.includes(transaction.transactionID));

        if (index < 0) {
            return;
        }
        const newTransaction = carouselTransactions.at(index);
        const timeoutId = setTimeout(() => {
            if (newTransaction?.transactionID !== carouselTransactionsRef.current.at(index)?.transactionID) {
                return;
            }
            numberOfScrollToIndexFailed.current = 0;
            carouselRef.current?.scrollToIndex({index, viewOffset: 2 * styles.gap2.gap, animated: true});
        }, CONST.ANIMATED_TRANSITION);

        return () => {
            clearTimeout(timeoutId);
        };
    }, [newTransactionIDs]),
);

Please rate this suggestion with 👍 or 👎 to help us improve! Reactions are used to monitor reviewer efficiency.

setTimeout(() => {
Comment thread
FitseTLT marked this conversation as resolved.
Resolved
// If the new transaction is not available at the index it was on before the delay, avoid the scrolling
// because we are scrolling to either a wrong or unavailable transaction (which can cause crash).
if (newTransaction?.transactionID !== carouselTransactionsRef.current.at(index)?.transactionID) {
return;
}

carouselRef.current?.scrollToIndex({index, viewOffset: -2 * styles.gap2.gap, animated: true});
}, CONST.ANIMATED_TRANSITION);

// eslint-disable-next-line react-hooks/exhaustive-deps
}, [newTransactionIDs]),
);

const onViewableItemsChanged = useRef(({viewableItems}: {viewableItems: ViewToken[]; changed: ViewToken[]}) => {
const newIndex = viewableItems.at(0)?.index;
if (typeof newIndex === 'number') {
Expand Down
Original file line number Diff line number Diff line change
@@ -1,8 +1,10 @@
import {useIsFocused} from '@react-navigation/native';
import type {ListRenderItem} from '@shopify/flash-list';
import React, {useCallback, useMemo, useRef, useState} from 'react';
import type {LayoutChangeEvent} from 'react-native';
import {usePersonalDetails} from '@components/OnyxListItemProvider';
import TransactionPreview from '@components/ReportActionItem/TransactionPreview';
import useNewTransactions from '@hooks/useNewTransactions';
import useOnyx from '@hooks/useOnyx';
import usePolicy from '@hooks/usePolicy';
import useReportWithTransactionsAndViolations from '@hooks/useReportWithTransactionsAndViolations';
Expand All @@ -18,6 +20,7 @@ import {contextMenuRef} from '@pages/inbox/report/ContextMenu/ReportActionContex
import CONST from '@src/CONST';
import ONYXKEYS from '@src/ONYXKEYS';
import ROUTES from '@src/ROUTES';
import {hasOnceLoadedReportActionsSelector} from '@src/selectors/ReportMetaData';
import type {Transaction} from '@src/types/onyx';
import MoneyRequestReportPreviewContent from './MoneyRequestReportPreviewContent';
import type {MoneyRequestReportPreviewProps} from './types';
Expand Down Expand Up @@ -115,6 +118,13 @@ function MoneyRequestReportPreview({
Navigation.navigate(ROUTES.EXPENSE_REPORT_RHP.getRoute({reportID: iouReportID, backTo: Navigation.getActiveRoute()}));
}
}, [iouReportID, isSmallScreenWidth]);
const [hasOnceLoadedReportActions] = useOnyx(`${ONYXKEYS.COLLECTION.REPORT_METADATA}${chatReportID}`, {
selector: hasOnceLoadedReportActionsSelector,
});
Comment thread
FitseTLT marked this conversation as resolved.
Resolved
const newTransactions = useNewTransactions(hasOnceLoadedReportActions, transactions);
const isFocused = useIsFocused();
// We only want to highlight the new expenses if the screen is focused.
const newTransactionIDs = isFocused ? new Set(newTransactions.map((transaction) => transaction.transactionID)) : undefined;

const renderItem: ListRenderItem<Transaction> = ({item}) => (
<TransactionPreview
Expand All @@ -135,11 +145,13 @@ function MoneyRequestReportPreview({
reportPreviewAction={action}
onPreviewPressed={openReportFromPreview}
shouldShowPayerAndReceiver={shouldShowPayerAndReceiver}
shouldHighlight={newTransactionIDs?.has(item.transactionID)}
/>
);

return (
<MoneyRequestReportPreviewContent
newTransactionIDs={newTransactionIDs}
iouReportID={iouReportID}
chatReportID={chatReportID}
iouReport={iouReport}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -98,6 +98,9 @@ type MoneyRequestReportPreviewContentProps = MoneyRequestReportPreviewContentOny

/** Callback called when the whole preview is pressed */
onPress: () => void;

/** IDs of newly added transactions */
newTransactionIDs?: Set<string>;
};

export type {MoneyRequestReportPreviewContentProps, MoneyRequestReportPreviewProps, MoneyRequestReportPreviewStyleType};
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
import truncate from 'lodash/truncate';
import React, {useMemo} from 'react';
import {View} from 'react-native';
import Animated from 'react-native-reanimated';
import Button from '@components/Button';
import Icon from '@components/Icon';
// eslint-disable-next-line no-restricted-imports
Expand All @@ -11,6 +12,7 @@ import ReportActionItemImages from '@components/ReportActionItem/ReportActionIte
import UserInfoCellsWithArrow from '@components/SelectionListWithSections/Search/UserInfoCellsWithArrow';
import Text from '@components/Text';
import TransactionPreviewSkeletonView from '@components/TransactionPreviewSkeletonView';
import useAnimatedHighlightStyle from '@hooks/useAnimatedHighlightStyle';
import useCardFeedErrors from '@hooks/useCardFeedErrors';
import useCurrentUserPersonalDetails from '@hooks/useCurrentUserPersonalDetails';
import useEnvironment from '@hooks/useEnvironment';
Expand Down Expand Up @@ -65,6 +67,7 @@ function TransactionPreviewContent({
shouldShowPayerAndReceiver,
navigateToReviewFields,
isReviewDuplicateTransactionPage = false,
shouldHighlight = false,
}: TransactionPreviewContentProps) {
const icons = useMemoizedLazyExpensifyIcons(['Folder', 'Tag']);
const theme = useTheme();
Expand Down Expand Up @@ -236,10 +239,17 @@ function TransactionPreviewContent({
const previewTextViewGap = (shouldShowCategoryOrTag || !shouldWrapDisplayAmount) && styles.gap2;
const previewTextMargin = shouldShowIOUHeader && shouldShowMerchantOrDescription && !isBillSplit && !shouldShowCategoryOrTag && styles.mbn1;

const animatedHighlightStyle = useAnimatedHighlightStyle({
shouldHighlight,
highlightColor: theme.messageHighlightBG,
backgroundColor: theme.cardBG,
shouldApplyOtherStyles: false,
});

const transactionWrapperStyles = [styles.border, styles.moneyRequestPreviewBox, (isIOUSettled || isApproved) && isSettlementOrApprovalPartial && styles.offlineFeedbackPending];

return (
<View style={[transactionWrapperStyles, containerStyles]}>
<Animated.View style={[transactionWrapperStyles, containerStyles, animatedHighlightStyle]}>
<OfflineWithFeedback
errors={walletTermsErrors}
onClose={() => offlineWithFeedbackOnClose}
Expand All @@ -250,7 +260,7 @@ function TransactionPreviewContent({
shouldDisableOpacity={isDeleted}
shouldHideOnDelete={shouldHideOnDelete}
>
<View style={[(isTransactionScanning || isWhisper) && [styles.reportPreviewBoxHoverBorder, styles.reportContainerBorderRadius]]}>
<View style={[(isTransactionScanning || isWhisper) && [styles.reportPreviewBoxHoverBorderColor, styles.reportContainerBorderRadius]]}>
<ReportActionItemImages
images={receiptImages}
// eslint-disable-next-line @typescript-eslint/prefer-nullish-coalescing
Expand Down Expand Up @@ -415,7 +425,7 @@ function TransactionPreviewContent({
)}
</View>
</OfflineWithFeedback>
</View>
</Animated.View>
);
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -40,6 +40,7 @@ function TransactionPreview(props: TransactionPreviewProps) {
iouReportID,
transactionID: transactionIDFromProps,
onPreviewPressed,
shouldHighlight,
reportPreviewAction,
contextAction,
} = props;
Expand Down Expand Up @@ -131,6 +132,7 @@ function TransactionPreview(props: TransactionPreviewProps) {
walletTermsErrors={walletTerms?.errors}
routeName={route.name}
isReviewDuplicateTransactionPage={isReviewDuplicateTransactionPage}
shouldHighlight={shouldHighlight}
/>
</PressableWithoutFeedback>
);
Expand All @@ -155,6 +157,7 @@ function TransactionPreview(props: TransactionPreviewProps) {
walletTermsErrors={walletTerms?.errors}
routeName={route.name}
reportPreviewAction={reportPreviewAction}
shouldHighlight={shouldHighlight}
isReviewDuplicateTransactionPage={isReviewDuplicateTransactionPage}
/>
);
Expand Down
6 changes: 6 additions & 0 deletions src/components/ReportActionItem/TransactionPreview/types.ts
Original file line number Diff line number Diff line change
Expand Up @@ -69,6 +69,9 @@ type TransactionPreviewProps = {

/** In case we want to override context menu action */
contextAction?: OnyxEntry<ReportAction>;

/** Whether the item should be highlighted */
shouldHighlight?: boolean;
};

type TransactionPreviewContentProps = {
Expand Down Expand Up @@ -138,6 +141,9 @@ type TransactionPreviewContentProps = {

/** Is this component used during duplicate review flow */
isReviewDuplicateTransactionPage?: boolean;

/** Whether the item should be highlighted */
shouldHighlight?: boolean;
};

export type {TransactionPreviewContentProps, TransactionPreviewProps, TransactionPreviewStyleType};
Original file line number Diff line number Diff line change
Expand Up @@ -27,7 +27,7 @@ import {isViolationDismissed, shouldShowViolation} from '@libs/TransactionUtils'
import variables from '@styles/variables';
import CONST from '@src/CONST';
import ONYXKEYS from '@src/ONYXKEYS';
import isActionLoadingSelector from '@src/selectors/ReportMetaData';
import {isActionLoadingSelector} from '@src/selectors/ReportMetaData';
import type {Policy, Report} from '@src/types/onyx';
import ExpenseReportListItemRow from './ExpenseReportListItemRow';

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,7 @@ import useThemeStyles from '@hooks/useThemeStyles';
import {handleActionButtonPress} from '@userActions/Search';
import CONST from '@src/CONST';
import ONYXKEYS from '@src/ONYXKEYS';
import isActionLoadingSelector from '@src/selectors/ReportMetaData';
import {isActionLoadingSelector} from '@src/selectors/ReportMetaData';
import type {Policy, Report} from '@src/types/onyx';
import ActionCell from './ActionCell';
import TotalCell from './TotalCell';
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -28,7 +28,7 @@ import {isViolationDismissed, mergeProhibitedViolations, shouldShowViolation} fr
import variables from '@styles/variables';
import CONST from '@src/CONST';
import ONYXKEYS from '@src/ONYXKEYS';
import isActionLoadingSelector from '@src/selectors/ReportMetaData';
import {isActionLoadingSelector} from '@src/selectors/ReportMetaData';
import type {Policy, Report, ReportAction, ReportActions} from '@src/types/onyx';
import type {TransactionViolation} from '@src/types/onyx/TransactionViolation';
import UserInfoAndActionButtonRow from './UserInfoAndActionButtonRow';
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,7 @@ import {isCorrectSearchUserName} from '@libs/SearchUIUtils';
import variables from '@styles/variables';
import CONST from '@src/CONST';
import ONYXKEYS from '@src/ONYXKEYS';
import isActionLoadingSelector from '@src/selectors/ReportMetaData';
import {isActionLoadingSelector} from '@src/selectors/ReportMetaData';
import ActionCell from './ActionCell';
import UserInfoCellsWithArrow from './UserInfoCellsWithArrow';

Expand Down
7 changes: 5 additions & 2 deletions src/hooks/useAnimatedHighlightStyle/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -33,6 +33,9 @@ type Props = {
/** Whether the item should be highlighted */
shouldHighlight: boolean;

/** Whether it should return height and border radius styles */
shouldApplyOtherStyles?: boolean;

/** The base backgroundColor used for the highlight animation, defaults to theme.appBG
* @default theme.appBG
*/
Expand Down Expand Up @@ -63,6 +66,7 @@ export default function useAnimatedHighlightStyle({
height,
highlightColor,
backgroundColor,
shouldApplyOtherStyles = true,
skipInitialFade = false,
}: Props) {
const [startHighlight, setStartHighlight] = useState(false);
Expand All @@ -80,9 +84,8 @@ export default function useAnimatedHighlightStyle({

return {
backgroundColor: interpolateColor(repeatableValue, [0, 1], [backgroundColor ?? theme.appBG, highlightColor ?? theme.border]),
height: height ? interpolate(nonRepeatableValue, [0, 1], [0, height]) : 'auto',
opacity: interpolate(nonRepeatableValue, [0, 1], [0, 1]),
borderRadius,
...(shouldApplyOtherStyles && {height: height ? interpolate(nonRepeatableValue, [0, 1], [0, height]) : 'auto', borderRadius}),
};
}, [borderRadius, height, backgroundColor, highlightColor, theme.appBG, theme.border]);

Expand Down
4 changes: 1 addition & 3 deletions src/hooks/useNewTransactions.ts
Original file line number Diff line number Diff line change
Expand Up @@ -23,9 +23,7 @@ function useNewTransactions(hasOnceLoadedReportActions: boolean | undefined, tra
return CONST.EMPTY_ARRAY as unknown as Transaction[];
}
return transactions.filter((transaction) => !prevTransactions?.some((prevTransaction) => prevTransaction.transactionID === transaction.transactionID));
// Depending only on transactions is enough because prevTransactions is a helper object.
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [transactions]);
}, [transactions, prevTransactions]);

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.

Does this fix something?

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.

Yes. Without prevTransactions the newTransactions data will remain the same until transactions changes and this will cause the scroll and highlight to happen when we go back to the chat screen from the iou report. So we only want to set newTransactions briefly to trigger the scroll and highlight if the current screen is focused.


// In case when we have loaded the report, but there were no transactions in it, then we need to explicitly set skipFirstTransactionsChange to false, as it will be not set in the useMemo above.
useEffect(() => {
Expand Down
4 changes: 3 additions & 1 deletion src/selectors/ReportMetaData.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,4 +3,6 @@ import type {ReportMetadata} from '@src/types/onyx';

const isActionLoadingSelector = (reportMetadata: OnyxEntry<ReportMetadata>) => reportMetadata?.isActionLoading ?? false;

export default isActionLoadingSelector;
const hasOnceLoadedReportActionsSelector = (reportMetadata: OnyxEntry<ReportMetadata>) => reportMetadata?.hasOnceLoadedReportActions;

export {isActionLoadingSelector, hasOnceLoadedReportActionsSelector};
4 changes: 4 additions & 0 deletions src/styles/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4374,6 +4374,10 @@ const staticStyles = (theme: ThemeColors) =>
backgroundColor: theme.cardBG,
},

reportPreviewBoxHoverBorderColor: {
borderColor: theme.cardBG,
},

reportContainerBorderRadius: {
borderRadius: variables.componentBorderRadiusLarge,
},
Expand Down
Loading