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
4 changes: 4 additions & 0 deletions src/CONST/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -1479,6 +1479,10 @@ const CONST = {
SHUTTER_SIZE: 90,
MAX_REPORT_PREVIEW_RECEIPTS: 3,
FLASH_DELAY_MS: 2000,
// Maximum magnification applied while hover-zooming a receipt (see ReceiptHoverZoom).
// Remote PDFs are rendered at this multiple of their on-screen size so the magnified
// view shows real pixels instead of an upscaled low-resolution raster.
HOVER_ZOOM_SCALE: 2.5,
},
RECEIPT_PREVIEW_TOP_BOTTOM_MARGIN: 120,
REPORT: {
Expand Down
3 changes: 2 additions & 1 deletion src/components/ReceiptHoverZoom/index.web.tsx
Original file line number Diff line number Diff line change
@@ -1,8 +1,9 @@
import React from 'react';
import CONST from '@src/CONST';
import type ReceiptHoverZoomProps from './types';
import useReceiptHoverZoom from './useReceiptHoverZoom';

const DEFAULT_SCALE = 2.5;
const DEFAULT_SCALE = CONST.RECEIPT.HOVER_ZOOM_SCALE;

const wrapperStyle: React.CSSProperties = {position: 'relative', overflow: 'hidden', width: '100%', height: '100%'};
const innerStyle: React.CSSProperties = {width: '100%', height: '100%', transition: 'transform 80ms ease-out', willChange: 'transform'};
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -269,7 +269,7 @@ function MoneyRequestReceiptView({
receiptURIs = getThumbnailAndImageURIs(displayedTransaction);
}
const isEReceiptTransaction = !!displayedTransaction && !hasReceiptSource(displayedTransaction) && hasEReceipt(displayedTransaction);
const canZoomReceipt = hasReceipt && !isLoading && !isTransactionScanning && !isEReceiptTransaction && !!receiptURIs?.image;
const canZoomReceipt = hasReceipt && !isLoading && !isEReceiptTransaction && !!receiptURIs?.image;
const pendingAction = transaction?.pendingAction;
// Need to return undefined when we have pendingAction to avoid the duplicate pending action
const getPendingFieldAction = (fieldPath: TransactionPendingFieldsKey) => {
Expand Down Expand Up @@ -645,6 +645,7 @@ function MoneyRequestReceiptView({
<ReportActionItemImage
shouldUseThumbnailImage={!fillSpace}
shouldUseFullHeight={fillSpace}
canZoomReceipt={canZoomReceipt}
thumbnail={receiptURIs?.thumbnail}
fileExtension={receiptURIs?.fileExtension}
isThumbnail={receiptURIs?.isThumbnail}
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
import type ReceiptPDFOverlayProps from './types';

/**
* Hover-zoom is a web-only interaction, so on native there is no high-resolution PDF overlay to render.
* Callers only mount this component when hover is supported, so this fallback should never actually render.
*/
// eslint-disable-next-line @typescript-eslint/no-unused-vars
function ReceiptPDFOverlay(props: ReceiptPDFOverlayProps) {
return null;
}

export default ReceiptPDFOverlay;
87 changes: 87 additions & 0 deletions src/components/ReportActionItem/ReceiptPDFOverlay/index.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,87 @@
import React, {useEffect, useState} from 'react';
import {PDFPreviewer} from 'react-fast-pdf';
import {View} from 'react-native';
import useOnyx from '@hooks/useOnyx';
import useThemeStyles from '@hooks/useThemeStyles';
import addEncryptedAuthTokenToURL from '@libs/addEncryptedAuthTokenToURL';
import variables from '@styles/variables';
import {retrieveMaxCanvasArea, retrieveMaxCanvasHeight, retrieveMaxCanvasWidth} from '@userActions/CanvasSize';
import CONST from '@src/CONST';
import ONYXKEYS from '@src/ONYXKEYS';
import type ReceiptPDFOverlayProps from './types';

const oversamplePercent = `${CONST.RECEIPT.HOVER_ZOOM_SCALE * 100}%`;
const oversampleContainerStyle = {
position: 'absolute' as const,
top: 0,
left: 0,
width: oversamplePercent,
height: oversamplePercent,
transform: `scale(${1 / CONST.RECEIPT.HOVER_ZOOM_SCALE})`,
transformOrigin: 'top left',
};

function ReceiptPDFOverlay({sourceURL, isAuthTokenRequired = true, onLoadFailure}: ReceiptPDFOverlayProps) {
const styles = useThemeStyles();
const [session] = useOnyx(ONYXKEYS.SESSION);
const [maxCanvasArea] = useOnyx(ONYXKEYS.MAX_CANVAS_AREA);
const [maxCanvasHeight] = useOnyx(ONYXKEYS.MAX_CANVAS_HEIGHT);
const [maxCanvasWidth] = useOnyx(ONYXKEYS.MAX_CANVAS_WIDTH);

useEffect(() => {
// Verify the per-browser canvas limits have been calculated, mirroring PDFView.
if (!maxCanvasArea) {
retrieveMaxCanvasArea();
}
if (!maxCanvasHeight) {
retrieveMaxCanvasHeight();
}
if (!maxCanvasWidth) {
retrieveMaxCanvasWidth();
}
// eslint-disable-next-line react-hooks/exhaustive-deps -- Run once on mount; canvas limits are one-time browser measurements that don't change
}, []);

Comment thread
WojtekBoman marked this conversation as resolved.
Resolved
const fileURL = isAuthTokenRequired ? addEncryptedAuthTokenToURL(sourceURL, session?.encryptedAuthToken ?? '') : sourceURL;

// Track which URL failed so hasFailed resets automatically when fileURL changes (e.g. after auth token refresh),
// mirroring the pattern in ThumbnailImage. No useEffect needed — the comparison runs synchronously during render.
const [failedURL, setFailedURL] = useState<string | null>(null);
const hasFailed = failedURL !== null && failedURL === fileURL;

// If the PDF can't be rendered, fall back to the thumbnail underneath by rendering nothing.
if (hasFailed) {
return null;
Comment thread
WojtekBoman marked this conversation as resolved.
Resolved
}

return (
<View
style={[styles.w100, styles.h100, styles.overflowHidden]}
pointerEvents="none"
>
{/* <div> is required here because `transformOrigin` is a CSS-only property unsupported by React Native's
View. The oversample-then-scale technique relies on it to anchor the downscale to the top-left corner. */}
<div style={oversampleContainerStyle}>
Comment thread
WojtekBoman marked this conversation as resolved.
Resolved
<PDFPreviewer
file={fileURL}
pageMaxWidth={variables.pdfPageMaxWidth}
// Fit the page to the full width of the (oversized) container, matching the thumbnail framing.
isSmallScreen
maxCanvasWidth={maxCanvasWidth}
maxCanvasHeight={maxCanvasHeight}
maxCanvasArea={maxCanvasArea}
containerStyle={styles.bgTransparent}
contentContainerStyle={styles.bgTransparent}
shouldShowErrorComponent={false}
LoadingComponent={null}
onLoadError={() => {
setFailedURL(fileURL);
onLoadFailure?.();
}}
/>
</div>
</View>
);
}

export default ReceiptPDFOverlay;
12 changes: 12 additions & 0 deletions src/components/ReportActionItem/ReceiptPDFOverlay/types.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
type ReceiptPDFOverlayProps = {
/** Resolved URL of the source PDF. The encrypted auth token is appended internally when required. */
sourceURL: string;

/** Whether the source requires an encrypted auth token */
isAuthTokenRequired?: boolean;

/** Called when the PDF fails to load so the caller can fall back to the thumbnail */
onLoadFailure?: () => void;
};

export default ReceiptPDFOverlayProps;
65 changes: 54 additions & 11 deletions src/components/ReportActionItem/ReportActionItemImage.tsx
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
import {Str} from 'expensify-common';
import React from 'react';
import type {ViewStyle} from 'react-native';
import {View} from 'react-native';
import {StyleSheet, View} from 'react-native';
import type {OnyxEntry} from 'react-native-onyx';
import ConfirmedRoute from '@components/ConfirmedRoute';
import type {IconSize} from '@components/EReceiptThumbnail';
Expand All @@ -12,16 +12,26 @@ import {useShowContextMenuState} from '@components/ShowContextMenuContext';
import {useMemoizedLazyExpensifyIcons} from '@hooks/useLazyAsset';
import useLocalize from '@hooks/useLocalize';
import useThemeStyles from '@hooks/useThemeStyles';
import {hasHoverSupport} from '@libs/DeviceCapabilities';
import {getReportIDForExpense} from '@libs/MergeTransactionUtils';
import Navigation from '@libs/Navigation/Navigation';
import {getThumbnailAndImageURIs} from '@libs/ReceiptUtils';
import {hasEReceipt, hasPendingDistanceReceiptRegeneration, hasReceiptSource, isDistanceRequest, isManualDistanceRequest, isPerDiemRequest} from '@libs/TransactionUtils';
import {
hasEReceipt,
hasPendingDistanceReceiptRegeneration,
hasReceiptSource,
isDistanceRequest,
isManualDistanceRequest,
isMapBasedDistanceRequest,
isPerDiemRequest,
} from '@libs/TransactionUtils';
import tryResolveUrlFromApiRoot from '@libs/tryResolveUrlFromApiRoot';
import variables from '@styles/variables';
import CONST from '@src/CONST';
import ROUTES from '@src/ROUTES';
import type {Report, Transaction} from '@src/types/onyx';
import {isEmptyObject} from '@src/types/utils/EmptyObject';
import ReceiptPDFOverlay from './ReceiptPDFOverlay';

type ReportActionItemImageProps = {
/** thumbnail URI for the image */
Expand Down Expand Up @@ -77,6 +87,9 @@ type ReportActionItemImageProps = {
/** Whether to use the thumbnail image instead of the full image */
shouldUseThumbnailImage?: boolean;

/** Whether the receipt can be hover-zoomed. When true, remote PDFs render the actual PDF on top of the thumbnail so magnification stays sharp (web only). */
canZoomReceipt?: boolean;

/** Callback to be called when the image loads */
onLoad?: (event?: {nativeEvent: {width: number; height: number}}) => void;

Expand Down Expand Up @@ -108,6 +121,7 @@ function ReportActionItemImage({
shouldUseFullHeight,
report: reportProp,
shouldUseThumbnailImage,
canZoomReceipt = false,
onLoad,
onLoadFailure,
}: ReportActionItemImageProps) {
Expand Down Expand Up @@ -183,6 +197,33 @@ function ReportActionItemImage({

propsObj.isPerDiemRequest = isPerDiemRequest(transaction);

// A remote PDF is shown as the server's low-resolution JPG thumbnail, which blurs when hover-zoomed.
// Where zooming is available (web only), render the actual PDF on top of the thumbnail so the magnified
// view stays sharp. The thumbnail stays underneath as an instant preview and as a fallback if the PDF fails.
// Map/route distance requests are excluded: their hover overlay is a DistanceEReceipt card, not the PDF.
// isMapBasedDistanceRequest covers map, GPS, and manual-typed transactions that still carry waypoints.
const pdfSourceURL = typeof originalImageSource === 'string' && !!originalImageSource ? originalImageSource : undefined;
const isRemotePDF = !!isPDF && !effectiveIsLocalFile && !isEReceipt && !isMapBasedDistanceRequest(transaction) && !!pdfSourceURL;
const shouldOverlayHighResPDF = canZoomReceipt && isRemotePDF && hasHoverSupport();

const renderReceiptContent = (receiptImage: React.ReactNode) =>
shouldOverlayHighResPDF ? (
<View style={[styles.w100, styles.h100]}>
{receiptImage}
<View
style={StyleSheet.absoluteFill}
pointerEvents="none"
>
<ReceiptPDFOverlay
sourceURL={pdfSourceURL}
onLoadFailure={onLoadFailure}
/>
</View>
</View>
) : (
receiptImage
);

if (enablePreviewModal) {
return (
<PressableWithoutFocus
Expand All @@ -201,26 +242,28 @@ function ReportActionItemImage({
accessibilityRole={CONST.ROLE.BUTTON}
sentryLabel={CONST.SENTRY_LABEL.RECEIPT.IMAGE}
>
<ReceiptImage
{...propsObj}
onLoad={onLoad}
shouldUseFullHeight={shouldUseFullHeight}
onLoadFailure={onLoadFailure}
previewUri={previewUriSource}
/>
{renderReceiptContent(
<ReceiptImage
{...propsObj}
onLoad={onLoad}
shouldUseFullHeight={shouldUseFullHeight}
onLoadFailure={onLoadFailure}
previewUri={previewUriSource}
/>,
)}
</PressableWithoutFocus>
);
}

return (
return renderReceiptContent(
<ReceiptImage
{...propsObj}
shouldUseFullHeight={shouldUseFullHeight}
thumbnailContainerStyles={styles.thumbnailImageContainerHover}
onLoad={onLoad}
onLoadFailure={onLoadFailure}
previewUri={previewUriSource}
/>
/>,
);
}

Expand Down
42 changes: 42 additions & 0 deletions tests/unit/TransactionUtilsTest.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3584,4 +3584,46 @@ describe('TransactionUtils', () => {
});
});
});

describe('isMapBasedDistanceRequest', () => {
it('returns false for undefined transaction', () => {
expect(TransactionUtils.isMapBasedDistanceRequest(undefined)).toBe(false);
});

it('returns false for a non-distance (scan) request', () => {
const transaction = generateTransaction({iouRequestType: CONST.IOU.REQUEST_TYPE.SCAN});
expect(TransactionUtils.isMapBasedDistanceRequest(transaction)).toBe(false);
});

it('returns false for an odometer distance request', () => {
const transaction = generateTransaction({iouRequestType: CONST.IOU.REQUEST_TYPE.DISTANCE_ODOMETER});
expect(TransactionUtils.isMapBasedDistanceRequest(transaction)).toBe(false);
});

it('returns true for a map distance request', () => {
const transaction = generateTransaction({iouRequestType: CONST.IOU.REQUEST_TYPE.DISTANCE_MAP});
expect(TransactionUtils.isMapBasedDistanceRequest(transaction)).toBe(true);
});

it('returns true for a GPS distance request', () => {
const transaction = generateTransaction({iouRequestType: CONST.IOU.REQUEST_TYPE.DISTANCE_GPS});
expect(TransactionUtils.isMapBasedDistanceRequest(transaction)).toBe(true);
});

it('returns true for a manual distance request that carries waypoints', () => {
const transaction = generateTransaction({
iouRequestType: CONST.IOU.REQUEST_TYPE.DISTANCE_MANUAL,
comment: {waypoints: {waypoint0: {lat: 0, lng: 0}, waypoint1: {lat: 1, lng: 1}}},
});
expect(TransactionUtils.isMapBasedDistanceRequest(transaction)).toBe(true);
});

it('returns false for a manual distance request with no waypoints', () => {
const transaction = generateTransaction({
iouRequestType: CONST.IOU.REQUEST_TYPE.DISTANCE_MANUAL,
comment: {waypoints: {}},
});
expect(TransactionUtils.isMapBasedDistanceRequest(transaction)).toBe(false);
});
});
});
Loading