mattermost-mobile-upstream/app/components/markdown/markdown_image/index.tsx
Elias Nahum b6fc85385e
Migrate from RNN to Expo router (#9402)
* Expo-Router partial migration

* Full migration to ExpoRouter

* i18n

* add tests

* Merge branch 'main' into expo-router

* align package-lock.json

* i18n

* feedback review

* feedback review

* android 16kb patch

* Refactored emoji picker keyboard using a state machine

* set android launch_screen in drawables instead of layout

* no conditional hooks

* remove duplicate call in test

* address feedback

* fix tests and address more feedback

* small corrections

* small corrections

* small corrections

* fix draft test

* fix draft test 2

* remove navigateToScreen in draff test

* fix nit in draft test

* remove doc file

* Feedback review

* fix snapshots

* improve test coverage

* fix i18n

* Upgrade t o RN 0.83, other dependencies and new architecture (#9737)

* library hardware-keyboard android new arch support fix

* library rnshare android new arch support fix

* library rnutils android new arch support fix

* library secure-pdf-viewer add new arch support

* Enable new arch on iOS and Android

* update emm and network client with new-arch

* update intune to use new-arch

* performance improvements

* fix tests

* fixes post input on new-arch

* fix android emoji picker

* remove doc

* run tests in parallel

* upgrade to React Native 0.83.9, Expo 55, React 19, and New Architecture

Bumps core dependencies to their latest versions:
- React Native 0.77.3 → 0.83.9 (New Architecture enabled)
- React 18.3.1 → 19.2.5
- Expo SDK 52 → 55
- TypeScript 5.8.3 → 6.0.3
- Node.js 22.16.0 → 24.15.0
- react-native-reanimated 3.17.3 → 4.3.0
- Various other dependency upgrades

Migrates iOS AppDelegate from Objective-C to Swift, updates Android
build tooling and Gradle wrapper, refreshes all patches and font
assets, and adapts app code, tests, and CI workflows throughout for
API changes introduced by these upgrades.

* remove unecessary dismissKeyboard in notifications

* feedback review

* update intune to use new-arch

* update @mattermost deps

* missing i18n string

* additional fixes

* update fastlane
2026-05-13 17:44:55 +08:00

285 lines
10 KiB
TypeScript

// Copyright (c) 2015-present Mattermost, Inc. All Rights Reserved.
// See LICENSE.txt for license information.
import {useManagedConfig} from '@mattermost/react-native-emm';
import Clipboard from '@react-native-clipboard/clipboard';
import React, {useCallback, useMemo, useRef, useState} from 'react';
import {useIntl} from 'react-intl';
import {Platform, type StyleProp, Text, type TextStyle, TouchableWithoutFeedback, View} from 'react-native';
import Animated from 'react-native-reanimated';
import {SvgUri} from 'react-native-svg';
import parseUrl from 'url-parse';
import CompassIcon from '@components/compass_icon';
import FormattedText from '@components/formatted_text';
import ProgressiveImage from '@components/progressive_image';
import SlideUpPanelItem, {ITEM_HEIGHT} from '@components/slide_up_panel_item';
import TouchableWithFeedback from '@components/touchable_with_feedback';
import {GalleryInit} from '@context/gallery';
import {useServerUrl} from '@context/server';
import {useIsTablet} from '@hooks/device';
import {useGalleryItem} from '@hooks/gallery';
import {bottomSheet, dismissBottomSheet} from '@screens/navigation';
import {lookupMimeType} from '@utils/file';
import {fileToGalleryItem, openGalleryAtIndex} from '@utils/gallery';
import {bottomSheetSnapPoint} from '@utils/helpers';
import {calculateDimensions, getViewPortWidth, isGifTooLarge} from '@utils/images';
import {getMarkdownImageSize, removeImageProxyForKey} from '@utils/markdown';
import {urlSafeBase64Encode} from '@utils/security';
import {changeOpacity, makeStyleSheetFromTheme} from '@utils/theme';
import {secureGetFromRecord} from '@utils/types';
import {normalizeProtocol, safeDecodeURIComponent, tryOpenURL} from '@utils/url';
import {onOpenLinkError} from '@utils/url/links';
import type {GalleryItemType} from '@typings/screens/gallery';
type MarkdownImageProps = {
disabled?: boolean;
errorTextStyle: StyleProp<TextStyle>;
imagesMetadata: Record<string, PostImage | undefined>;
isReplyPost?: boolean;
linkDestination?: string;
layoutHeight?: number;
layoutWidth?: number;
location?: string;
postId: string;
source: string;
sourceSize?: {width?: number; height?: number};
theme: Theme;
}
const ANDROID_MAX_HEIGHT = 4096;
const ANDROID_MAX_WIDTH = 4096;
const getStyleSheet = makeStyleSheetFromTheme((theme: Theme) => ({
bottomSheet: {
flex: 1,
},
brokenImageIcon: {
width: 24,
height: 24,
},
container: {
marginVertical: 5,
top: 5,
},
svg: {
backgroundColor: changeOpacity(theme.centerChannelColor, 0.06),
borderRadius: 8,
flex: 1,
},
}));
const MarkdownImage = ({
disabled,
errorTextStyle,
imagesMetadata,
isReplyPost = false,
layoutWidth,
layoutHeight,
linkDestination,
location,
postId,
source,
sourceSize,
theme,
}: MarkdownImageProps) => {
const intl = useIntl();
const isTablet = useIsTablet();
const style = getStyleSheet(theme);
const managedConfig = useManagedConfig<ManagedConfig>();
const sourceKey = removeImageProxyForKey(source);
// Pattern suggested in https://react.dev/reference/react/useRef#avoiding-recreating-the-ref-contents
const genericFileRef = useRef<string | null>(null);
if (genericFileRef.current === null) {
genericFileRef.current = `uid-${urlSafeBase64Encode(sourceKey)}`;
}
const genericFileId = genericFileRef.current;
const metadata = secureGetFromRecord(imagesMetadata, sourceKey) || Object.values(imagesMetadata || {})[0];
const [failed, setFailed] = useState(() => isGifTooLarge(metadata));
const serverUrl = useServerUrl();
const galleryIdentifier = `${postId}-${genericFileId}-${location}`;
const fileInfo = useMemo(() => {
const uri = source.startsWith('/') ? serverUrl + source : source;
const originalSize = getMarkdownImageSize(isReplyPost, isTablet, sourceSize, metadata, layoutWidth, layoutHeight);
const decodedLink = safeDecodeURIComponent(uri);
let filename = parseUrl(decodedLink.substr(decodedLink.lastIndexOf('/'))).pathname.replace('/', '');
let extension = metadata?.format || filename.split('.').pop();
if (extension === filename) {
const ext = filename.indexOf('.') === -1 ? '.png' : filename.substring(filename.lastIndexOf('.'));
filename = `${filename}${ext}`;
extension = ext;
}
return {
id: genericFileId,
name: filename,
extension,
has_preview_image: true,
mime_type: lookupMimeType(filename),
post_id: postId,
uri,
width: originalSize.width,
height: originalSize.height,
} as FileInfo;
}, [source, serverUrl, isReplyPost, isTablet, sourceSize, metadata, layoutWidth, layoutHeight, genericFileId, postId]);
const handlePreviewImage = useCallback(() => {
const item: GalleryItemType = {
...fileToGalleryItem(fileInfo, undefined, undefined, 0, fileInfo.id),
mime_type: lookupMimeType(fileInfo.name),
type: 'image',
};
openGalleryAtIndex(galleryIdentifier, 0, [item]);
}, [fileInfo, galleryIdentifier]);
const {ref, onGestureEvent, styles} = useGalleryItem(
galleryIdentifier,
0,
handlePreviewImage,
);
const {height, width} = calculateDimensions(fileInfo.height, fileInfo.width, layoutWidth || getViewPortWidth(isReplyPost, isTablet));
const progressiveImageStyle = useMemo(() => ({width, height}), [width, height]);
const handleLinkPress = useCallback(() => {
if (linkDestination) {
const url = normalizeProtocol(linkDestination);
tryOpenURL(url, () => onOpenLinkError(intl));
}
}, [intl, linkDestination]);
const handleLinkLongPress = useCallback(() => {
if (managedConfig?.copyAndPasteProtection !== 'true') {
const renderContent = () => {
return (
<View
testID='at_mention.bottom_sheet'
style={style.bottomSheet}
>
<SlideUpPanelItem
leftIcon='content-copy'
onPress={() => {
dismissBottomSheet();
Clipboard.setString(linkDestination || source);
}}
testID='at_mention.bottom_sheet.copy_url'
text={intl.formatMessage({id: 'mobile.markdown.link.copy_url', defaultMessage: 'Copy URL'})}
/>
<SlideUpPanelItem
destructive={true}
leftIcon='cancel'
onPress={() => {
dismissBottomSheet();
}}
testID='at_mention.bottom_sheet.cancel'
text={intl.formatMessage({id: 'mobile.post.cancel', defaultMessage: 'Cancel'})}
/>
</View>
);
};
bottomSheet(renderContent, [1, bottomSheetSnapPoint(2, ITEM_HEIGHT)]);
}
}, [managedConfig?.copyAndPasteProtection, intl, style.bottomSheet, linkDestination, source]);
const handleOnError = useCallback(() => {
setFailed(true);
}, []);
if (failed) {
return (
<CompassIcon
color={theme.centerChannelColor}
name='file-image-broken-outline-large'
size={24}
/>
);
}
let image;
if (height && width) {
if (Platform.OS === 'android' && (height > ANDROID_MAX_HEIGHT || width > ANDROID_MAX_WIDTH)) {
// Android has a cap on the max image size that can be displayed
return (
<Text style={[errorTextStyle, style.container]}>
<FormattedText
id='mobile.markdown.image.too_large'
defaultMessage='Image exceeds max dimensions of {maxWidth} by {maxHeight}:'
values={{
maxWidth: ANDROID_MAX_WIDTH,
maxHeight: ANDROID_MAX_HEIGHT,
}}
/>
{' '}
</Text>
);
} else if (fileInfo.extension === 'svg') {
image = (
<SvgUri
uri={fileInfo.uri!}
style={{flex: 1, backgroundColor: changeOpacity(theme.centerChannelColor, 0.06), borderRadius: 8}}
width={width}
height={height}
onError={handleOnError}
/>
);
} else {
image = (
<TouchableWithoutFeedback
disabled={disabled}
onLongPress={handleLinkLongPress}
onPress={onGestureEvent}
>
<Animated.View style={[styles, {width, height}, style.container]}>
<ProgressiveImage
forwardRef={ref}
id={fileInfo.id!}
imageUri={fileInfo.uri}
onError={handleOnError}
contentFit='contain'
style={progressiveImageStyle}
theme={theme}
/>
</Animated.View>
</TouchableWithoutFeedback>
);
}
}
if (image && linkDestination && !disabled) {
image = (
<TouchableWithFeedback
onPress={handleLinkPress}
onLongPress={handleLinkLongPress}
style={[{width, height}, style.container]}
>
<ProgressiveImage
id={fileInfo.id!}
imageUri={fileInfo.uri}
onError={handleOnError}
contentFit='contain'
style={progressiveImageStyle}
theme={theme}
/>
</TouchableWithFeedback>
);
}
return (
<GalleryInit galleryIdentifier={galleryIdentifier}>
<Animated.View testID='markdown_image'>
{image}
</Animated.View>
</GalleryInit>
);
};
export default MarkdownImage;