Skip to content
Merged
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
21 changes: 18 additions & 3 deletions src/components/ThumbnailImage.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,11 @@ import Icon from './Icon';
import * as Expensicons from './Icon/Expensicons';
import ImageWithSizeCalculation from './ImageWithSizeCalculation';

// Cache for the dimensions of the thumbnails to avoid flickering incorrect size when the
// image has already been loaded once. This caches the dimensions based on the URL of
// the image.
const thumbnailDimensionsCache = new Map<string, {width: number; height: number}>();

type ThumbnailImageProps = {
/** Source URL for the preview image */
previewSourceURL: string | ImageSourcePropType;
Expand Down Expand Up @@ -56,7 +61,8 @@ function ThumbnailImage({
const theme = useTheme();
const {isOffline} = useNetwork();
const [failedToLoad, setFailedToLoad] = useState(false);
const [imageDimensions, setImageDimensions] = useState({width: imageWidth, height: imageHeight});
const cachedDimensions = shouldDynamicallyResize && typeof previewSourceURL === 'string' ? thumbnailDimensionsCache.get(previewSourceURL) : null;
const [imageDimensions, setImageDimensions] = useState({width: cachedDimensions?.width ?? imageWidth, height: cachedDimensions?.height ?? imageHeight});
const {thumbnailDimensionsStyles} = useThumbnailDimensions(imageDimensions.width, imageDimensions.height);

useEffect(() => {
Expand All @@ -69,12 +75,21 @@ function ThumbnailImage({
*/
const updateImageSize = useCallback(
({width, height}: UpdateImageSizeParams) => {
if (!shouldDynamicallyResize) {
if (
!shouldDynamicallyResize ||
// If the provided dimensions are good avoid caching them and updating state.
(imageDimensions.width === width && imageDimensions.height === height)
) {
return;
}

if (typeof previewSourceURL === 'string') {
thumbnailDimensionsCache.set(previewSourceURL, {width, height});
}

setImageDimensions({width, height});
},
[shouldDynamicallyResize],
[previewSourceURL, imageDimensions, shouldDynamicallyResize],
);

const sizeStyles = shouldDynamicallyResize ? [thumbnailDimensionsStyles] : [styles.w100, styles.h100];
Expand Down