Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Cache measured sizes in ThumbnailImage #40643

Merged
merged 1 commit into from
Apr 22, 2024
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
Loading