Skip to content
Open
Show file tree
Hide file tree
Changes from 3 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
12 changes: 6 additions & 6 deletions app/components/block_renderer/mm_blocks_image.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@
// See LICENSE.txt for license information.

import {type ImageLoadEventData} from 'expo-image';
import React, {useCallback, useContext, useMemo, useRef, useState} from 'react';

Check failure on line 5 in app/components/block_renderer/mm_blocks_image.tsx

View workflow job for this annotation

GitHub Actions / lint-typecheck

'useRef' is defined but never used
import {Pressable, View} from 'react-native';
import Animated from 'react-native-reanimated';
import {SvgUri} from 'react-native-svg';
Expand Down Expand Up @@ -86,7 +86,7 @@
return computeMmBlocksImageLayout(caps, layoutWidth, imageMetadata, viewPortWidth);
}, [caps, imageMetadata, intrinsicSize, layoutWidth, viewPortWidth]);

const fileId = useRef(`uid-mm-blocks-image-${urlSafeBase64Encode(imageUrl)}`);
const fileId = useMemo(() => `uid-mm-blocks-image-${urlSafeBase64Encode(imageUrl)}`, [imageUrl]);

const dimensionsStyle = useMemo(() => ({
width: layout.width,
Expand All @@ -97,7 +97,7 @@

const onPress = useCallback(() => {
const item: GalleryItemType = {
id: fileId.current,
id: fileId,
postId,
uri: displaySrc,
width: layout.galleryWidth,
Expand All @@ -106,10 +106,10 @@
mime_type: lookupMimeType(imageUrl) || 'image/png',
type: 'image',
lastPictureUpdate: 0,
cacheKey: fileId.current,
cacheKey: fileId,
};
openGalleryAtIndex(galleryIdentifier, 0, [item]);
}, [altText, displaySrc, galleryIdentifier, imageUrl, layout.galleryHeight, layout.galleryWidth, postId]);
}, [altText, displaySrc, fileId, galleryIdentifier, imageUrl, layout.galleryHeight, layout.galleryWidth, postId]);

const {ref, onGestureEvent, styles: galleryStyles} = useGalleryItem(
galleryIdentifier,
Expand Down Expand Up @@ -159,9 +159,9 @@

return (
<ExpoImage
id={fileId.current}
id={fileId}
ref={ref}
nativeID={`MmBlocksImage-${fileId.current}`}
nativeID={`MmBlocksImage-${fileId}`}
source={{uri: displaySrc}}
style={[dimensionsStyle, {borderRadius: imageBorderRadius}]}
contentFit={imageStyle === 'person' ? 'cover' : 'contain'}
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,132 @@
// Copyright (c) 2015-present Mattermost, Inc. All Rights Reserved.
// See LICENSE.txt for license information.

import React from 'react';

import ProgressiveImage from '@components/progressive_image';
import {Screens, Preferences} from '@constants';
import {renderWithIntlAndTheme} from '@test/intl-test-helper';
import {openGalleryAtIndex} from '@utils/gallery';
import {urlSafeBase64Encode} from '@utils/security';

import AttachmentImage from './index';

jest.mock('@components/progressive_image', () => ({
__esModule: true,
default: jest.fn(() => null),
}));

jest.mock('@context/gallery', () => ({
GalleryInit: ({children}: {children: React.ReactNode}) => children,
}));

jest.mock('@hooks/device', () => ({
useIsTablet: () => false,
}));

jest.mock('@hooks/gallery', () => ({
useGalleryItem: jest.fn((_galleryIdentifier, _index, onPress) => ({
ref: {current: null},
onGestureEvent: onPress,
styles: {},
})),
}));

jest.mock('@utils/gallery', () => ({
openGalleryAtIndex: jest.fn(),
}));

jest.mock('@utils/url', () => ({
...jest.requireActual('@utils/url'),
isValidUrl: (url: string) => url.startsWith('https://'),
}));

const IMAGE_URL = 'https://example.com/quotes/image/AAPL_day.png';
const IMAGE_URL_2 = 'https://example.com/quotes/image/AAPL_week.png';
const IMAGE_METADATA = {width: 700, height: 300, format: 'png', frame_count: 0} as PostImage;

describe('AttachmentImage', () => {
const theme = Preferences.THEMES.denim;

beforeEach(() => {
jest.clearAllMocks();
});

function buildElement(props: Partial<React.ComponentProps<typeof AttachmentImage>> = {}) {
return (
<AttachmentImage
imageUrl={IMAGE_URL}
imageMetadata={IMAGE_METADATA}
layoutWidth={400}
location={Screens.CHANNEL}
postId='post-id'
theme={theme}
{...props}
/>
);
}

function renderImage(props: Partial<React.ComponentProps<typeof AttachmentImage>> = {}) {
return renderWithIntlAndTheme(buildElement(props));
}

function lastProgressiveImageId() {
const calls = jest.mocked(ProgressiveImage).mock.calls;
return calls[calls.length - 1][0].id;
}

it('should render ProgressiveImage with the image and a cache id derived from imageUrl', () => {
renderImage();

expect(ProgressiveImage).toHaveBeenCalledWith(
expect.objectContaining({
imageUri: IMAGE_URL,
id: `uid-${urlSafeBase64Encode(IMAGE_URL)}`,
}),
undefined,
);
});

// Regression test for the stale-image bug: when the same post is edited in place
// to a new image URL, the cache id must follow imageUrl. Previously it was frozen
// via useRef, so the new image rendered under the old cache key and stayed stale.
it('should update the cache id when imageUrl changes on re-render', () => {
const {rerender} = renderImage({imageUrl: IMAGE_URL});
const firstId = lastProgressiveImageId();
expect(firstId).toBe(`uid-${urlSafeBase64Encode(IMAGE_URL)}`);

rerender(buildElement({imageUrl: IMAGE_URL_2}));
const secondId = lastProgressiveImageId();

expect(secondId).toBe(`uid-${urlSafeBase64Encode(IMAGE_URL_2)}`);
expect(secondId).not.toBe(firstId);
});

it('should open the gallery with a cacheKey matching the current imageUrl', () => {
renderImage();

// Trigger the gallery open via the captured gesture handler.
const {useGalleryItem} = jest.requireMock('@hooks/gallery');
const onGestureEvent = jest.mocked(useGalleryItem).mock.results.at(-1)!.value.onGestureEvent;
onGestureEvent();

const galleryItems = jest.mocked(openGalleryAtIndex).mock.calls[0][2];
expect(galleryItems).toHaveLength(1);
expect(openGalleryAtIndex).toHaveBeenCalledWith(
`post-id-AttachmentImage-${Screens.CHANNEL}`,
0,
expect.arrayContaining([
expect.objectContaining({
id: `uid-${urlSafeBase64Encode(IMAGE_URL)}`,
cacheKey: `uid-${urlSafeBase64Encode(IMAGE_URL)}`,
uri: IMAGE_URL,
}),
]),
);
});
Comment thread
coderabbitai[bot] marked this conversation as resolved.

it('should render an error frame for an invalid url and skip ProgressiveImage', () => {
renderImage({imageUrl: 'not-a-url'});
expect(ProgressiveImage).not.toHaveBeenCalled();
});
});
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
// Copyright (c) 2015-present Mattermost, Inc. All Rights Reserved.
// See LICENSE.txt for license information.

import React, {useCallback, useMemo, useRef, useState} from 'react';
import React, {useCallback, useMemo, useState} from 'react';
import {TouchableWithoutFeedback, View} from 'react-native';
import Animated from 'react-native-reanimated';

Expand Down Expand Up @@ -55,10 +55,7 @@ export type Props = {
const AttachmentImage = ({imageUrl, imageMetadata, layoutWidth, location, postId, theme}: Props) => {
const galleryIdentifier = `${postId}-AttachmentImage-${location}`;
const [error, setError] = useState(false);
const fileId = useRef<string | null>(null);
if (fileId.current === null) {
fileId.current = `uid-${urlSafeBase64Encode(imageUrl)}`;
}
const fileId = useMemo(() => `uid-${urlSafeBase64Encode(imageUrl)}`, [imageUrl]);
const isTablet = useIsTablet();
const {height, width} = calculateDimensions(imageMetadata.height, imageMetadata.width, layoutWidth || getViewPortWidth(false, isTablet, true));
const style = getStyleSheet(theme);
Expand All @@ -70,7 +67,7 @@ const AttachmentImage = ({imageUrl, imageMetadata, layoutWidth, location, postId

const onPress = () => {
const item: GalleryItemType = {
id: fileId.current || '',
id: fileId || '',
postId,
uri: imageUrl,
width: imageMetadata.width,
Expand All @@ -79,7 +76,7 @@ const AttachmentImage = ({imageUrl, imageMetadata, layoutWidth, location, postId
mime_type: lookupMimeType(imageUrl) || 'image/png',
type: 'image',
lastPictureUpdate: 0,
cacheKey: fileId.current || '',
cacheKey: fileId || '',
};
openGalleryAtIndex(galleryIdentifier, 0, [item]);
};
Expand Down Expand Up @@ -109,7 +106,7 @@ const AttachmentImage = ({imageUrl, imageMetadata, layoutWidth, location, postId
<Animated.View testID={`attachmentImage-${fileId}`}>
<ProgressiveImage
forwardRef={ref}
id={fileId.current}
id={fileId}
imageStyle={style.attachmentMargin}
imageUri={imageUrl}
onError={onError}
Expand Down
Loading