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
Expand Up @@ -115,7 +115,11 @@ function MoneyRequestReportPreviewContent({
const shouldShowSkeleton = shouldShowLoading && transactions.length === 0;
const shouldShowAccessPlaceHolder = !iouReport && !shouldShowLoading;
const shouldShowEmptyPlaceholder = transactions.length === 0 && !shouldShowLoading;
const shouldShowPreviewPlaceholder = shouldShowAccessPlaceHolder || shouldShowEmptyPlaceholder;
const showStatusAndSkeleton = !shouldShowEmptyPlaceholder;
// Empty/access placeholders do not depend on measured carousel width, so we can show them immediately
// once the report data is ready instead of keeping the taller loading state around and causing the preview to reflow.
const shouldShowPreviewLoading = shouldShowLoading || shouldShowLoadingDeferred || (!currentWidth && !shouldShowPreviewPlaceholder);
const skeletonReasonAttributes: SkeletonSpanReasonAttributes = {
context: 'MoneyRequestReportPreviewContent',
hasOnceLoadedReportActions: chatReportMetadata?.hasOnceLoadedReportActions,
Expand All @@ -134,6 +138,7 @@ function MoneyRequestReportPreviewContent({
const {translate, formatPhoneNumber} = useLocalize();
// eslint-disable-next-line rulesdir/prefer-shouldUseNarrowLayout-instead-of-isSmallScreenWidth
const {shouldUseNarrowLayout, isSmallScreenWidth} = useResponsiveLayout();
const previewCarouselMinWidth = shouldUseNarrowLayout ? CONST.REPORT.TRANSACTION_PREVIEW.CAROUSEL.MIN_NARROW_WIDTH : CONST.REPORT.TRANSACTION_PREVIEW.CAROUSEL.MIN_WIDE_WIDTH;
const expensifyIcons = useMemoizedLazyExpensifyIcons(['ArrowRight', 'BackArrow']);

const {areAllRequestsBeingSmartScanned, hasNonReimbursableTransactions} = useMemo(
Expand Down Expand Up @@ -507,6 +512,61 @@ function MoneyRequestReportPreviewContent({
return index === MAX_PREVIEWS_NUMBER ? ITEM_LAYOUT_TYPE.SHOW_MORE : ITEM_LAYOUT_TYPE.PREVIEW;
};

let previewContent: React.ReactNode;

if (shouldShowPreviewLoading) {
previewContent = (
<View
style={[
{
height: CONST.REPORT.TRANSACTION_PREVIEW.CAROUSEL.WIDE_HEIGHT,
minWidth: previewCarouselMinWidth,
},
styles.justifyContentCenter,
styles.mtn1,
]}
>
<ActivityIndicator
size={40}
reasonAttributes={carouselReasonAttributes}
/>
</View>
);
} else if (shouldShowAccessPlaceHolder) {
previewContent = <AccessMoneyRequestReportPreviewPlaceHolder />;
} else if (shouldShowEmptyPlaceholder) {
previewContent = <EmptyMoneyRequestReportPreview />;
} else {
previewContent = (
<View style={[styles.flex1, styles.flexColumn, styles.overflowVisible, styles.minHeight42]}>
<FlashList
key={carouselKey}
snapToAlignment="start"
decelerationRate="fast"
snapToOffsets={snapOffsets}
horizontal
ItemSeparatorComponent={renderSeparator}
data={carouselTransactions}
ref={carouselRef}
nestedScrollEnabled
bounces={false}
keyExtractor={(item) => `${item.transactionID}_${reportPreviewStyles.transactionPreviewCarouselStyle.width}`}
contentContainerStyle={styles.ph2}
style={reportPreviewStyles.flatListStyle}
showsHorizontalScrollIndicator={false}
renderItem={renderItem}
getItemType={getItemType}
onViewableItemsChanged={onViewableItemsChanged}
onEndReached={adjustScroll}
viewabilityConfig={viewabilityConfig}
ListFooterComponent={<View style={styles.pl2} />}
ListHeaderComponent={<View style={styles.pr2} />}
drawDistance={1000}
/>
</View>
);
}

return (
<View
onLayout={onWrapperLayout}
Expand Down Expand Up @@ -633,54 +693,7 @@ function MoneyRequestReportPreviewContent({
)}
</View>
</View>
{!currentWidth || shouldShowLoading || shouldShowLoadingDeferred ? (
<View
style={[
{
height: CONST.REPORT.TRANSACTION_PREVIEW.CAROUSEL.WIDE_HEIGHT,
minWidth: shouldUseNarrowLayout
? CONST.REPORT.TRANSACTION_PREVIEW.CAROUSEL.MIN_NARROW_WIDTH
: CONST.REPORT.TRANSACTION_PREVIEW.CAROUSEL.MIN_WIDE_WIDTH,
},
styles.justifyContentCenter,
styles.mtn1,
]}
>
<ActivityIndicator
size={40}
reasonAttributes={carouselReasonAttributes}
/>
</View>
) : (
<View style={[styles.flex1, styles.flexColumn, styles.overflowVisible, styles.minHeight42]}>
<FlashList
key={carouselKey}
snapToAlignment="start"
decelerationRate="fast"
snapToOffsets={snapOffsets}
horizontal
ItemSeparatorComponent={renderSeparator}
data={carouselTransactions}
ref={carouselRef}
nestedScrollEnabled
bounces={false}
keyExtractor={(item) => `${item.transactionID}_${reportPreviewStyles.transactionPreviewCarouselStyle.width}`}
contentContainerStyle={styles.ph2}
style={reportPreviewStyles.flatListStyle}
showsHorizontalScrollIndicator={false}
renderItem={renderItem}
getItemType={getItemType}
onViewableItemsChanged={onViewableItemsChanged}
onEndReached={adjustScroll}
viewabilityConfig={viewabilityConfig}
ListFooterComponent={<View style={styles.pl2} />}
ListHeaderComponent={<View style={styles.pr2} />}
drawDistance={1000}
/>
{shouldShowAccessPlaceHolder && <AccessMoneyRequestReportPreviewPlaceHolder />}
{shouldShowEmptyPlaceholder && !shouldShowAccessPlaceHolder && <EmptyMoneyRequestReportPreview />}
</View>
)}
{previewContent}
<View style={[styles.expenseAndReportPreviewTextContainer]}>
<View style={[totalAmountStyle, styles.justifyContentBetween, styles.gap4, StyleUtils.getMinimumHeight(variables.h28)]}>
<ReportPreviewActionButton
Expand Down
92 changes: 87 additions & 5 deletions tests/ui/MoneyRequestReportPreview.test.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -27,6 +27,24 @@ import * as TestHelper from '../utils/TestHelper';
import waitForBatchedUpdatesWithAct from '../utils/waitForBatchedUpdatesWithAct';

const mockSecondTransactionID = `${mockTransaction.transactionID}2`;
const defaultPreviewTransactions = [mockTransaction, {...mockTransaction, transactionID: mockSecondTransactionID}];
const defaultReportWithTransactionsAndViolations: [OnyxEntry<Report>, Transaction[], OnyxCollection<TransactionViolation[]>] = [
mockIOUReport,
defaultPreviewTransactions,
{violations: mockViolations},
];
let mockDeferredValueOverride: boolean | undefined;

jest.mock('react', () => {
// eslint-disable-next-line @typescript-eslint/no-unsafe-assignment -- jest.requireActual() returns the real React module for partial mocking
const actualReact = jest.requireActual('react');

// eslint-disable-next-line @typescript-eslint/no-unsafe-return -- returning the real React module plus one overridden hook is the standard Jest partial-mock pattern
return {
...actualReact,
useDeferredValue: (value: boolean) => mockDeferredValueOverride ?? value,
};
});

jest.mock('@react-navigation/native');

Expand All @@ -38,11 +56,13 @@ jest.mock('@rnmapbox/maps', () => {
};
});

jest.mock('@src/hooks/useReportWithTransactionsAndViolations', () =>
jest.fn((): [OnyxEntry<Report>, Transaction[], OnyxCollection<TransactionViolation[]>] => {
return [mockIOUReport, [mockTransaction, {...mockTransaction, transactionID: mockSecondTransactionID}], {violations: mockViolations}];
}),
);
const mockUseReportWithTransactionsAndViolations = jest.fn(() => defaultReportWithTransactionsAndViolations);

jest.mock('@src/hooks/useReportWithTransactionsAndViolations', () => ({
// eslint-disable-next-line @typescript-eslint/naming-convention -- __esModule is required by Jest to properly mock ES modules with default exports
__esModule: true,
default: (...args: Parameters<typeof mockUseReportWithTransactionsAndViolations>) => mockUseReportWithTransactionsAndViolations(...args),
}));

const getIOUActionForReportID = (reportID: string | undefined, transactionID: string | undefined) => {
if (!reportID || !transactionID) {
Expand Down Expand Up @@ -121,6 +141,29 @@ const mockOnyxViolations: Record<`${typeof ONYXKEYS.COLLECTION.TRANSACTION_VIOLA

const arrayOfTransactions = Object.values(mockOnyxTransactions);

const setReportPreviewData = (
overrides: {
iouReport?: OnyxEntry<Report>;
transactions?: Transaction[];
violations?: OnyxCollection<TransactionViolation[]>;
} = {},
) => {
const {iouReport, transactions, violations} = overrides;
const hasIouReportOverride = Object.prototype.hasOwnProperty.call(overrides, 'iouReport');

mockUseReportWithTransactionsAndViolations.mockImplementation(() => [
hasIouReportOverride ? iouReport : mockIOUReport,
transactions ?? defaultPreviewTransactions,
violations ?? {violations: mockViolations},
]);
};

const setHasOnceLoadedReportActions = async (hasOnceLoadedReportActions: boolean) => {
await Onyx.merge(`${ONYXKEYS.COLLECTION.REPORT_METADATA}${mockChatReport.chatReportID}`, {
hasOnceLoadedReportActions,
});
};

TestHelper.setupApp();
TestHelper.setupGlobalFetchMock();

Expand All @@ -137,6 +180,8 @@ describe('MoneyRequestReportPreview', () => {

beforeEach(() => {
jest.clearAllMocks();
mockDeferredValueOverride = undefined;
setReportPreviewData();
return act(async () => {
await Onyx.clear();
await waitForBatchedUpdatesWithAct();
Expand Down Expand Up @@ -188,4 +233,41 @@ describe('MoneyRequestReportPreview', () => {

expect(screen.getAllByTestId('TransactionPreviewSkeletonView')).toHaveLength(2);
});

it('renders the empty placeholder immediately without waiting for width', async () => {
setReportPreviewData({transactions: []});

renderPage({});
await act(async () => {
await setHasOnceLoadedReportActions(true);
await waitForBatchedUpdatesWithAct();
});

expect(screen.getByText(TestHelper.translateLocal('search.moneyRequestReport.emptyStateTitle'))).toBeOnTheScreen();
});

it('renders the access placeholder immediately without waiting for width', async () => {
setReportPreviewData({iouReport: undefined, transactions: []});

renderPage({});
await act(async () => {
await setHasOnceLoadedReportActions(true);
await waitForBatchedUpdatesWithAct();
});

expect(screen.getByText(TestHelper.translateLocal('search.moneyRequestReport.accessPlaceHolder'))).toBeOnTheScreen();
});

it('keeps showing loading during the deferred transition before transactions populate', async () => {
setReportPreviewData({transactions: []});
mockDeferredValueOverride = true;

renderPage({});
await act(async () => {
await setHasOnceLoadedReportActions(true);
await waitForBatchedUpdatesWithAct();
});

expect(screen.queryByText(TestHelper.translateLocal('search.moneyRequestReport.emptyStateTitle'))).not.toBeOnTheScreen();
});
});
Loading