diff --git a/src/CONST/index.ts b/src/CONST/index.ts index 570a411d03fc..c766e8b5929b 100755 --- a/src/CONST/index.ts +++ b/src/CONST/index.ts @@ -2314,6 +2314,12 @@ const CONST = { INITIAL: 'initial', }, + IMAGE_LOADING_PRIORITY: { + LOW: 'low', + NORMAL: 'normal', + HIGH: 'high', + }, + FILE_TYPE_REGEX: { // Image MimeTypes allowed by iOS photos app. IMAGE: /\.(jpg|jpeg|png|webp|gif|tiff|bmp|heic|heif)$/, diff --git a/src/components/Image/types.ts b/src/components/Image/types.ts index 7a57250b9848..5dc10f1b90be 100644 --- a/src/components/Image/types.ts +++ b/src/components/Image/types.ts @@ -27,6 +27,11 @@ type BaseImageProps = { /** The image cache policy */ cachePolicy?: ImagePrefetchOptions['cachePolicy']; + + /** Priorities for completing loads. If more than one load is queued at a time, + * the load with the higher priority will be started first. + * Maps to SDWebImageHighPriority (iOS) and Glide.Priority.IMMEDIATE (Android). */ + priority?: ValueOf | null; }; type ImageOwnProps = BaseImageProps & { diff --git a/src/components/Lightbox/index.tsx b/src/components/Lightbox/index.tsx index 102cb935f77a..d4b2a828cd34 100644 --- a/src/components/Lightbox/index.tsx +++ b/src/components/Lightbox/index.tsx @@ -20,8 +20,20 @@ import CONST from '@src/CONST'; import type {Dimensions} from '@src/types/utils/Layout'; import NUMBER_OF_CONCURRENT_LIGHTBOXES from './numberOfConcurrentLightboxes'; +const FALLBACK_OFFSET = 2; + const cachedImageDimensions = new Map(); +function getImagePriority(isActive: boolean, isLightboxVisible: boolean) { + if (isActive) { + return CONST.IMAGE_LOADING_PRIORITY.HIGH; + } + if (isLightboxVisible) { + return CONST.IMAGE_LOADING_PRIORITY.NORMAL; + } + return CONST.IMAGE_LOADING_PRIORITY.LOW; +} + type LightboxProps = Pick & { /** Whether source url requires authentication */ isAuthTokenRequired?: boolean; @@ -89,15 +101,16 @@ function Lightbox({attachmentID, isAuthTokenRequired = false, uri, onScaleChange }; } - const foundPage = state.pagerItems.findIndex((item) => item.attachmentID === attachmentID); + const identifier = attachmentID ?? uri; + const foundPage = state.pagerItems.findIndex((item) => (item.attachmentID ?? item.source) === identifier); return { ...state, ...actions, isUsedInCarousel: !!state.pagerRef, isSingleCarouselItem: state.pagerItems.length === 1, - page: foundPage, + page: foundPage === -1 ? 0 : foundPage, }; - }, [attachmentID, state, actions, isPagerScrollingFallback, isScrollingEnabledFallback]); + }, [attachmentID, uri, state, actions, isPagerScrollingFallback, isScrollingEnabledFallback]); /** Whether the Lightbox is used within an attachment carousel and there are more than one page in the carousel */ const hasSiblingCarouselItems = isUsedInCarousel && !isSingleCarouselItem; @@ -146,10 +159,16 @@ function Lightbox({attachmentID, isAuthTokenRequired = false, uri, onScaleChange const indexOutOfRange = page > activePage + indexCanvasOffset || page < activePage - indexCanvasOffset; return !indexOutOfRange; }, [activePage, hasSiblingCarouselItems, page]); + + // Limits fallback image rendering to only a few pages around the active page. + // This prevents distant carousel items from queuing unnecessary image downloads, + // which would starve the active image of network bandwidth. + const isFallbackInRange = !hasSiblingCarouselItems || Math.abs(page - activePage) <= FALLBACK_OFFSET; + const [isLightboxImageLoaded, setLightboxImageLoaded] = useState(false); const [isLoading, setIsLoading] = useState(true); - const [isFallbackVisible, setFallbackVisible] = useState(!isLightboxVisible); + const [isFallbackVisible, setFallbackVisible] = useState(!isLightboxVisible && isFallbackInRange); const [isFallbackImageLoaded, setFallbackImageLoaded] = useState(false); const previousUri = usePrevious(uri); @@ -216,10 +235,11 @@ function Lightbox({attachmentID, isAuthTokenRequired = false, uri, onScaleChange } // If the carousel item has become inactive and the lightbox is not continued to be rendered, we want to show the fallback image + // but only if the page is within the fallback range to avoid unnecessary image downloads if (!isActive && !isLightboxVisible) { - setFallbackVisible(true); + setFallbackVisible(isFallbackInRange); } - }, [hasSiblingCarouselItems, isActive, isFallbackVisible, isLightboxImageLoaded, isLightboxVisible]); + }, [hasSiblingCarouselItems, isActive, isFallbackInRange, isFallbackVisible, isLightboxImageLoaded, isLightboxVisible]); const scaleChange = useCallback( (scale: number) => { @@ -229,11 +249,14 @@ function Lightbox({attachmentID, isAuthTokenRequired = false, uri, onScaleChange [onScaleChangedContext, onScaleChangedProp], ); + const imagePriority = getImagePriority(isActive, isLightboxVisible); + const isALocalFile = isLocalFile(uri); const shouldShowOfflineIndicator = isOffline && !isLoading && !isALocalFile; return ( @@ -259,6 +282,7 @@ function Lightbox({attachmentID, isAuthTokenRequired = false, uri, onScaleChange source={{uri}} style={[contentSize ?? styles.invisibleImage]} isAuthTokenRequired={isAuthTokenRequired} + priority={imagePriority} onError={onError} onLoad={(e) => { updateContentSize(e); @@ -281,13 +305,14 @@ function Lightbox({attachmentID, isAuthTokenRequired = false, uri, onScaleChange )} {/* Keep rendering the image without gestures as fallback if the carousel item is not active and while the lightbox is loading the image */} - {isFallbackVisible && ( + {isFallbackVisible && isFallbackInRange && ( { updateContentSize(e); setFallbackImageLoaded(true); diff --git a/src/pages/media/AttachmentModalScreen/routes/report/ReportAddAttachmentModalContent/AddAttachmentModalCarouselView.tsx b/src/pages/media/AttachmentModalScreen/routes/report/ReportAddAttachmentModalContent/AddAttachmentModalCarouselView.tsx index 93e5ba877f7f..b7333efaeb02 100644 --- a/src/pages/media/AttachmentModalScreen/routes/report/ReportAddAttachmentModalContent/AddAttachmentModalCarouselView.tsx +++ b/src/pages/media/AttachmentModalScreen/routes/report/ReportAddAttachmentModalContent/AddAttachmentModalCarouselView.tsx @@ -6,7 +6,7 @@ import type {Attachment} from '@components/Attachments/types'; import type {AttachmentContentProps} from '@pages/media/AttachmentModalScreen/AttachmentModalBaseContent/types'; import type {FileObject} from '@src/types/utils/Attachment'; -const convertFileToAttachment = (file: FileObject | undefined): Attachment => { +const convertFileToAttachment = (file: FileObject | undefined, index: number): Attachment => { if (!file) { return {source: ''}; } @@ -14,6 +14,7 @@ const convertFileToAttachment = (file: FileObject | undefined): Attachment => { return { file, source: file.uri ?? '', + attachmentID: file.uri ?? `local-${index}`, }; }; @@ -24,16 +25,22 @@ function AddAttachmentModalCarouselView({fileToDisplay, files}: AttachmentConten const [page, setPage] = useState(0); const attachments = useMemo(() => { if (Array.isArray(files)) { - return files?.map((file) => convertFileToAttachment(file)) ?? []; + return files?.map((file, index) => convertFileToAttachment(file, index)) ?? []; } if (!files) { return []; } - return [convertFileToAttachment(files)]; + return [convertFileToAttachment(files, 0)]; }, [files]); - const currentAttachment = useMemo(() => convertFileToAttachment(fileToDisplay), [fileToDisplay]); + const currentAttachment = useMemo(() => { + if (!fileToDisplay) { + return convertFileToAttachment(undefined, 0); + } + const idx = Array.isArray(files) ? files.indexOf(fileToDisplay) : 0; + return convertFileToAttachment(fileToDisplay, idx >= 0 ? idx : 0); + }, [fileToDisplay, files]); useEffect(() => { clearAttachmentErrors(); diff --git a/tests/unit/LightboxTest.tsx b/tests/unit/LightboxTest.tsx new file mode 100644 index 000000000000..b48b700c0169 --- /dev/null +++ b/tests/unit/LightboxTest.tsx @@ -0,0 +1,223 @@ +import {fireEvent, render, screen} from '@testing-library/react-native'; +import React from 'react'; +import type {View as RNView} from 'react-native'; +import type {SharedValue} from 'react-native-reanimated'; +import {AttachmentCarouselPagerActionsContext, AttachmentCarouselPagerStateContext} from '@components/Attachments/AttachmentCarousel/Pager/AttachmentCarouselPagerContext'; +import type {AttachmentCarouselPagerActionsContextType, AttachmentCarouselPagerStateContextType} from '@components/Attachments/AttachmentCarousel/Pager/types'; +import Lightbox from '@components/Lightbox'; +import CONST from '@src/CONST'; +import waitForBatchedUpdatesWithAct from '../utils/waitForBatchedUpdatesWithAct'; + +// eslint-disable-next-line @typescript-eslint/no-unsafe-assignment -- __esModule is required by Jest to properly mock ES modules with default exports +jest.mock('@components/Image', () => { + const MockReact = require('react') as typeof React; + const {View} = require('react-native') as {View: typeof RNView}; + function MockImage({priority, testID, ...props}: {priority?: string; testID?: string}) { + return MockReact.createElement(View, { + testID: testID ?? 'image', + accessibilityHint: priority ?? 'none', + ...props, + }); + } + return { + // eslint-disable-next-line @typescript-eslint/naming-convention -- __esModule is required by Jest to properly mock ES modules with default exports + __esModule: true, + default: MockReact.memo(MockImage), + }; +}); + +// eslint-disable-next-line @typescript-eslint/no-unsafe-assignment -- __esModule is required by Jest to properly mock ES modules with default exports +jest.mock('@components/Lightbox/numberOfConcurrentLightboxes', () => ({ + // eslint-disable-next-line @typescript-eslint/naming-convention -- __esModule is required by Jest to properly mock ES modules with default exports + __esModule: true, + default: 3, +})); + +// eslint-disable-next-line @typescript-eslint/no-unsafe-assignment -- __esModule is required by Jest to properly mock ES modules with default exports +jest.mock('@components/MultiGestureCanvas', () => { + const MockReact = require('react') as typeof React; + const {View} = require('react-native') as {View: typeof RNView}; + return { + // eslint-disable-next-line @typescript-eslint/naming-convention -- __esModule is required by Jest to properly mock ES modules with default exports + __esModule: true, + default: ({children}: {children: React.ReactNode}) => MockReact.createElement(View, {testID: 'multi-gesture-canvas'}, children), + DEFAULT_ZOOM_RANGE: {min: 1, max: 5}, + }; +}); + +function createSharedValue(value: T): SharedValue { + return { + value, + get: jest.fn(() => value), + set: jest.fn(), + addListener: jest.fn(), + removeListener: jest.fn(), + modify: jest.fn(), + } as unknown as SharedValue; +} + +function createPagerItems(count: number) { + return Array.from({length: count}, (_, i) => ({ + source: `https://example.com/image-${i}.png`, + previewSource: `https://example.com/image-${i}-preview.png`, + index: i, + isActive: false, + attachmentID: `attachment-${i}`, + })); +} + +function createStateValue(activePage: number, itemCount: number): AttachmentCarouselPagerStateContextType { + return { + pagerItems: createPagerItems(itemCount), + activePage, + isPagerScrolling: createSharedValue(false), + isScrollEnabled: createSharedValue(true), + pagerRef: {current: null}, + }; +} + +function createActionsValue(): AttachmentCarouselPagerActionsContextType { + return { + onTap: jest.fn(), + onScaleChanged: jest.fn(), + onSwipeDown: jest.fn(), + }; +} + +async function renderLightboxInCarousel( + attachmentID: string | undefined, + uri: string, + stateValue: AttachmentCarouselPagerStateContextType, + actionsValue: AttachmentCarouselPagerActionsContextType, +) { + render( + + + + + , + ); + + await waitForBatchedUpdatesWithAct(); + + fireEvent(screen.getByTestId('lightbox-wrapper'), 'onLayout', { + nativeEvent: {layout: {width: 400, height: 800}}, + }); + + await waitForBatchedUpdatesWithAct(); +} + +describe('Lightbox', () => { + describe('page resolution with missing attachmentID', () => { + it('should resolve page correctly using source fallback when attachmentID is undefined', async () => { + const stateValue: AttachmentCarouselPagerStateContextType = { + pagerItems: [ + {source: 'https://example.com/a.png', index: 0, isActive: false, attachmentID: undefined}, + {source: 'https://example.com/b.png', index: 1, isActive: false, attachmentID: undefined}, + {source: 'https://example.com/c.png', index: 2, isActive: true, attachmentID: undefined}, + ], + activePage: 2, + isPagerScrolling: createSharedValue(false), + isScrollEnabled: createSharedValue(true), + pagerRef: {current: null}, + }; + const actionsValue = createActionsValue(); + + // Lightbox for the 3rd image (index 2) should resolve to page 2, not page 0 + await renderLightboxInCarousel(undefined, 'https://example.com/c.png', stateValue, actionsValue); + + // The active page lightbox should render the multi-gesture-canvas + expect(screen.getByTestId('multi-gesture-canvas')).toBeTruthy(); + }); + }); + + describe('page resolution when attachment is not found in pagerItems', () => { + it('should fall back to page 0 and still render when findIndex returns -1', async () => { + const stateValue = createStateValue(0, 5); + const actionsValue = createActionsValue(); + + // Use an attachmentID and uri that don't match any pagerItem — findIndex returns -1, should fallback to page 0 + await renderLightboxInCarousel('non-existent-id', 'https://example.com/unknown.png', stateValue, actionsValue); + + // Page 0 === activePage 0, so this should be active and render the lightbox + expect(screen.getByTestId('multi-gesture-canvas')).toBeTruthy(); + expect(screen.getAllByTestId('image').length).toBeGreaterThan(0); + }); + }); + + describe('fallback rendering range', () => { + it('should not render any image for distant pages outside FALLBACK_OFFSET range', async () => { + const stateValue = createStateValue(15, 30); + const actionsValue = createActionsValue(); + + await renderLightboxInCarousel('attachment-0', 'https://example.com/image-0.png', stateValue, actionsValue); + + expect(screen.queryAllByTestId('image')).toHaveLength(0); + }); + + it('should render fallback image for pages within FALLBACK_OFFSET range', async () => { + const stateValue = createStateValue(15, 30); + const actionsValue = createActionsValue(); + + await renderLightboxInCarousel('attachment-13', 'https://example.com/image-13.png', stateValue, actionsValue); + + expect(screen.getAllByTestId('image').length).toBeGreaterThan(0); + }); + + it('should render lightbox image for the active page', async () => { + const stateValue = createStateValue(15, 30); + const actionsValue = createActionsValue(); + + await renderLightboxInCarousel('attachment-15', 'https://example.com/image-15.png', stateValue, actionsValue); + + expect(screen.getByTestId('multi-gesture-canvas')).toBeTruthy(); + expect(screen.getAllByTestId('image').length).toBeGreaterThan(0); + }); + }); + + describe('image priority', () => { + it('should assign HIGH priority to the active page image', async () => { + const stateValue = createStateValue(5, 30); + const actionsValue = createActionsValue(); + + await renderLightboxInCarousel('attachment-5', 'https://example.com/image-5.png', stateValue, actionsValue); + + const images = screen.getAllByTestId('image'); + expect(images.length).toBeGreaterThan(0); + for (const image of images) { + expect(image.props.accessibilityHint).toBe(CONST.IMAGE_LOADING_PRIORITY.HIGH); + } + }); + + it('should assign NORMAL priority to non-active pages within the lightbox visible range', async () => { + const stateValue = createStateValue(5, 30); + const actionsValue = createActionsValue(); + + // attachment-4 is one page before active (5), within lightbox window (NUMBER_OF_CONCURRENT_LIGHTBOXES=3, offset=1) + await renderLightboxInCarousel('attachment-4', 'https://example.com/image-4.png', stateValue, actionsValue); + + const images = screen.getAllByTestId('image'); + expect(images.length).toBeGreaterThan(0); + for (const image of images) { + expect(image.props.accessibilityHint).toBe(CONST.IMAGE_LOADING_PRIORITY.NORMAL); + } + }); + + it('should assign LOW priority to fallback images outside the lightbox window', async () => { + const stateValue = createStateValue(15, 30); + const actionsValue = createActionsValue(); + + // attachment-13 is 2 pages away from active (15), within FALLBACK_OFFSET but outside lightbox window (offset=1) + await renderLightboxInCarousel('attachment-13', 'https://example.com/image-13.png', stateValue, actionsValue); + + const images = screen.getAllByTestId('image'); + expect(images.length).toBeGreaterThan(0); + for (const image of images) { + expect(image.props.accessibilityHint).toBe(CONST.IMAGE_LOADING_PRIORITY.LOW); + } + }); + }); +});