Skip to content
Merged
6 changes: 6 additions & 0 deletions src/CONST/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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)$/,
Expand Down
5 changes: 5 additions & 0 deletions src/components/Image/types.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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<typeof CONST.IMAGE_LOADING_PRIORITY> | null;
};

type ImageOwnProps = BaseImageProps & {
Expand Down
39 changes: 32 additions & 7 deletions src/components/Lightbox/index.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -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<string, Dimensions | undefined>();

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<Attachment, 'attachmentID'> & {
/** Whether source url requires authentication */
isAuthTokenRequired?: boolean;
Expand Down Expand Up @@ -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);

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Badge Guard missing pager matches before setting page index

findIndex can return -1 here when the current attachment is not present in pagerItems (for example on web carousels where the context only provides a single source entry). In that case this component treats the visible item as inactive, and isImageLoaded short-circuits to true, so the loading indicator is skipped and users can see a blank frame until the image finishes loading. Please handle the -1 case explicitly (e.g., fallback to activePage/0) before deriving active/loading state.

Useful? React with 👍 / 👎.

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;
Expand Down Expand Up @@ -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);

Expand Down Expand Up @@ -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) => {
Expand All @@ -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 (
<View
testID="lightbox-wrapper"
style={[StyleSheet.absoluteFill, style]}
onLayout={updateCanvasSize}
>
Expand All @@ -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);
Expand All @@ -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 && (
<View style={StyleUtils.getFullscreenCenteredContentStyles()}>
<Image
source={{uri}}
resizeMode="contain"
style={[fallbackSize ?? styles.invisibleImage]}
isAuthTokenRequired={isAuthTokenRequired}
priority={imagePriority}
onLoad={(e) => {
updateContentSize(e);
setFallbackImageLoaded(true);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -6,14 +6,15 @@ 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: ''};
}

return {
file,
source: file.uri ?? '',
attachmentID: file.uri ?? `local-${index}`,
};
};

Expand All @@ -24,16 +25,22 @@ function AddAttachmentModalCarouselView({fileToDisplay, files}: AttachmentConten
const [page, setPage] = useState<number>(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();
Expand Down
Loading
Loading