mattermost-mobile-upstream/app/screens/edit_post/edit_post.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

477 lines
18 KiB
TypeScript

// Copyright (c) 2015-present Mattermost, Inc. All Rights Reserved.
// See LICENSE.txt for license information.
import {useNavigation} from 'expo-router';
import React, {useCallback, useEffect, useRef, useState} from 'react';
import {useIntl} from 'react-intl';
import {Alert, type LayoutChangeEvent, View, StyleSheet} from 'react-native';
import {KeyboardAvoidingView} from 'react-native-keyboard-controller';
import {SafeAreaView, type Edge} from 'react-native-safe-area-context';
import {deletePost, editPost} from '@actions/remote/post';
import Autocomplete from '@components/autocomplete';
import Loading from '@components/loading';
import NavigationButton from '@components/navigation_button';
import {QUICK_ACTIONS_HEIGHT} from '@components/post_draft/quick_actions/quick_actions';
import {Screens} from '@constants';
import {EditPostProvider} from '@context/edit_post';
import {useServerUrl} from '@context/server';
import {useTheme} from '@context/theme';
import useAndroidHardwareBackHandler from '@hooks/android_back_handler';
import {useAutocompleteDefaultAnimatedValues} from '@hooks/autocomplete';
import {useKeyboardOverlap} from '@hooks/device';
import DraftEditPostUploadManager from '@managers/draft_upload_manager';
import PostError from '@screens/edit_post/post_error';
import {navigateBack} from '@screens/navigation';
import {fileMaxWarning, fileSizeWarning, getUploadErrorMessage, uploadDisabledWarning} from '@utils/file';
import {dismissKeyboard} from '@utils/keyboard';
import EditPostInput from './edit_post_input';
import type {PasteTextInputInstance} from '@mattermost/react-native-paste-input';
import type {ErrorHandlers} from '@typings/components/upload_error_handlers';
import type PostModel from '@typings/database/models/servers/post';
type EditPostProps = {
post: PostModel;
maxPostSize: number;
canDelete: boolean;
files?: FileInfo[];
maxFileCount: number;
maxFileSize: number;
canUploadFiles: boolean;
}
const AUTOCOMPLETE_SEPARATION = 8;
const styles = StyleSheet.create({
body: {
flex: 1,
},
container: {
flex: 1,
},
loader: {
flex: 1,
alignItems: 'center',
justifyContent: 'center',
},
inputContainer: {
flex: 1,
},
});
const safeAreaEdges: Edge[] = ['left', 'right', 'bottom'];
const EditPost = ({
maxPostSize,
post,
canDelete,
files,
maxFileCount,
maxFileSize,
canUploadFiles,
}: EditPostProps) => {
const editingMessage = post.messageSource || post.message;
const navigation = useNavigation();
const [postMessage, setPostMessage] = useState(editingMessage);
const [cursorPosition, setCursorPosition] = useState(editingMessage.length);
const [errorLine, setErrorLine] = useState<string | undefined>();
const [errorExtra, setErrorExtra] = useState<string | undefined>();
const [isUpdating, setIsUpdating] = useState(false);
const [containerHeight, setContainerHeight] = useState(0);
const [postFiles, setPostFiles] = useState<FileInfo[]>(files || []);
const [canSave, setCanSave] = useState(false);
const mainView = useRef<View>(null);
const uploadErrorHandlers = useRef<ErrorHandlers>({});
const postInputRef = useRef<PasteTextInputInstance | null>(null);
const theme = useTheme();
const intl = useIntl();
const serverUrl = useServerUrl();
const hasNoCurrentFiles = postFiles.length === 0;
const shouldDeleteOnSave = !postMessage && canDelete && hasNoCurrentFiles;
const shouldEnableSaveButton = useCallback(() => {
const loadingFiles = postFiles.filter((v) => v.clientId && DraftEditPostUploadManager.isUploading(v.clientId));
const hasUploadingFiles = loadingFiles.length > 0;
const tooLong = postMessage.length > maxPostSize;
const messageChanged = editingMessage !== postMessage;
const originalFiles = files || [];
const originalFileIds = originalFiles.map((f) => f.id).sort();
const currentFileIds = postFiles.map((f) => f.id).filter((id) => id).sort();
const filesChanged = JSON.stringify(originalFileIds) !== JSON.stringify(currentFileIds);
// Enable save button if:
// 1. No files are uploading AND
// 2. No message length error AND
// 3. (Message changed OR files changed)
return !hasUploadingFiles && !tooLong && (messageChanged || filesChanged);
}, [postMessage, postFiles, editingMessage, maxPostSize, files]);
useEffect(() => {
const t = setTimeout(() => {
postInputRef.current?.focus();
}, 320);
return () => {
clearTimeout(t);
};
}, []);
const onClose = useCallback(() => {
dismissKeyboard();
navigateBack();
}, []);
const onTextSelectionChange = useCallback((curPos: number = cursorPosition) => {
setCursorPosition(curPos);
}, [cursorPosition]);
const updateFileInPostFiles = useCallback((updatedFile: FileInfo) => {
const hasSameClientId = (file: FileInfo) => {
return file.clientId === updatedFile.clientId;
};
setPostFiles((prevFiles) => {
const fileIndex = prevFiles.findIndex(hasSameClientId);
if (fileIndex >= 0) {
const newFiles = [...prevFiles];
newFiles[fileIndex] = updatedFile;
return newFiles;
}
return prevFiles;
});
}, []);
const handleUploadError = useCallback((errorMessage: string, errorName?: string) => {
setErrorLine(getUploadErrorMessage(intl, errorMessage, errorName));
}, [intl]);
const addFiles = useCallback((newFiles: FileInfo[]) => {
if (!newFiles.length) {
return;
}
if (!canUploadFiles) {
setErrorLine(uploadDisabledWarning(intl));
return;
}
const currentFileCount = postFiles?.length || 0;
const availableCount = maxFileCount - currentFileCount;
if (newFiles.length > availableCount) {
setErrorLine(fileMaxWarning(intl, maxFileCount));
return;
}
const largeFile = newFiles.find((file) => file.size > maxFileSize);
if (largeFile) {
setErrorLine(fileSizeWarning(intl, maxFileSize));
return;
}
setPostFiles((prevFiles) => [...prevFiles, ...newFiles]);
// Start uploads for new files using the upload manager
for (const file of newFiles) {
DraftEditPostUploadManager.prepareUpload(
serverUrl,
file,
post.channelId,
post.rootId,
0,
true, // isEditPost = true
updateFileInPostFiles,
);
uploadErrorHandlers.current[file.clientId!] = DraftEditPostUploadManager.registerErrorHandler(file.clientId!, handleUploadError);
}
const currentMessageTooLong = postMessage.length > maxPostSize;
if (!currentMessageTooLong) {
setErrorLine(undefined);
}
}, [canUploadFiles, postFiles?.length, maxFileCount, setErrorLine, intl, maxFileSize, serverUrl, post.channelId, post.rootId, updateFileInPostFiles, postMessage, maxPostSize, handleUploadError]);
const handleFileRemoval = useCallback((id: string) => {
const fileToRemove = postFiles?.find((file) => {
if (file.id && id) {
return file.id === id;
}
if (file.clientId && id) {
return file.clientId === id;
}
return false;
});
if (!fileToRemove) {
return;
}
const shouldKeepFile = (file: FileInfo) => {
if (fileToRemove.id && file.id) {
return file.id !== fileToRemove.id;
}
if (fileToRemove.clientId && file.clientId) {
return file.clientId !== fileToRemove.clientId;
}
return file !== fileToRemove;
};
const removeFileAction = () => {
if (fileToRemove.clientId && DraftEditPostUploadManager.isUploading(fileToRemove.clientId)) {
DraftEditPostUploadManager.cancel(fileToRemove.clientId);
if (uploadErrorHandlers.current[fileToRemove.clientId]) {
uploadErrorHandlers.current[fileToRemove.clientId]?.();
delete uploadErrorHandlers.current[fileToRemove.clientId];
}
}
// Remove the specific file by using a unique identifier combination
setPostFiles((prevFiles) => prevFiles?.filter(shouldKeepFile) || []);
};
const originalFiles = files || [];
const isNewlyUploadedFile = !originalFiles.some((originalFile) => {
return originalFile.id === fileToRemove.id;
});
if (isNewlyUploadedFile) {
removeFileAction();
} else {
Alert.alert(
intl.formatMessage({
id: 'edit_post.delete_file.title',
defaultMessage: 'Delete attachment',
}),
intl.formatMessage({
id: 'edit_post.delete_file.confirmation',
defaultMessage: 'Are you sure you want to remove {filename}?',
}, {
filename: fileToRemove.name || '',
}),
[
{
text: intl.formatMessage({
id: 'edit_post.delete_file.cancel',
defaultMessage: 'Cancel',
}),
style: 'cancel',
},
{
text: intl.formatMessage({
id: 'edit_post.delete_file.confirm',
defaultMessage: 'Delete',
}),
style: 'destructive',
onPress: removeFileAction,
},
],
);
}
}, [intl, postFiles, files]);
useEffect(() => {
let loadingFiles: FileInfo[] = [];
if (postFiles) {
loadingFiles = postFiles.filter((v) => v.clientId && DraftEditPostUploadManager.isUploading(v.clientId));
}
setCanSave(shouldEnableSaveButton());
for (const key of Object.keys(uploadErrorHandlers.current)) {
if (!loadingFiles.find((v) => v.clientId === key)) {
uploadErrorHandlers.current[key]?.();
delete uploadErrorHandlers.current[key];
}
}
for (const file of loadingFiles) {
if (file.clientId && !uploadErrorHandlers.current[file.clientId]) {
uploadErrorHandlers.current[file.clientId] = DraftEditPostUploadManager.registerErrorHandler(file.clientId, handleUploadError);
}
}
}, [handleUploadError, postFiles, postMessage, setErrorLine, shouldEnableSaveButton]);
const onChangeTextCommon = useCallback((message: string) => {
const tooLong = message.length > maxPostSize;
setErrorExtra(undefined);
if (tooLong) {
const line = intl.formatMessage({id: 'mobile.message_length.message_split_left', defaultMessage: 'Message exceeds the character limit'});
const extra = `${message.length} / ${maxPostSize}`;
setErrorLine(line);
setErrorExtra(extra);
} else {
// Clear any error when message is valid
setErrorLine(undefined);
}
}, [intl, maxPostSize]);
const onAutocompleteChangeText = useCallback((message: string) => {
setPostMessage(message);
onChangeTextCommon(message);
}, [onChangeTextCommon]);
const onInputChangeText = useCallback((message: string) => {
setPostMessage(message);
onChangeTextCommon(message);
}, [onChangeTextCommon]);
const handleUIUpdates = useCallback((res: {error?: unknown}) => {
if (res.error) {
setIsUpdating(false);
const errorMessage = intl.formatMessage({id: 'mobile.edit_post.error', defaultMessage: 'There was a problem editing this message. Please try again.'});
setErrorLine(errorMessage);
postInputRef?.current?.focus();
} else {
setIsUpdating(false);
onClose();
}
}, [intl, onClose]);
const handleDeletePost = useCallback(async () => {
Alert.alert(
intl.formatMessage({id: 'mobile.edit_post.delete_title', defaultMessage: 'Confirm Post Delete'}),
intl.formatMessage({
id: 'mobile.edit_post.delete_question',
defaultMessage: 'Are you sure you want to delete this Post?',
}),
[{
text: intl.formatMessage({id: 'mobile.post.cancel', defaultMessage: 'Cancel'}),
style: 'cancel',
onPress: () => {
setIsUpdating(false);
setCanSave(false);
setPostMessage(editingMessage);
},
}, {
text: intl.formatMessage({id: 'post_info.del', defaultMessage: 'Delete'}),
style: 'destructive',
onPress: async () => {
const res = await deletePost(serverUrl, post);
handleUIUpdates(res);
},
}],
);
}, [intl, editingMessage, serverUrl, post, handleUIUpdates]);
const onSavePostMessage = useCallback(async () => {
setIsUpdating(true);
setErrorLine(undefined);
setErrorExtra(undefined);
setCanSave(false);
if (shouldDeleteOnSave) {
handleDeletePost();
return;
}
const currentFileIds = postFiles.map((file) => file.id).filter((id): id is string => Boolean(id));
const originalFiles = post.metadata?.files || [];
const originalFileIds = originalFiles.map((file) => file.id).filter((id): id is string => Boolean(id));
const currentFileIdSet = new Set(currentFileIds);
const removedFileIds = originalFileIds.filter((id) => !currentFileIdSet.has(id));
const res = await editPost(serverUrl, post.id, postMessage, currentFileIds, removedFileIds);
handleUIUpdates(res);
}, [shouldDeleteOnSave, post.metadata?.files, post.id, serverUrl, postMessage, handleUIUpdates, handleDeletePost, postFiles]);
useEffect(() => {
navigation.setOptions({
headerRight: () => (
<NavigationButton
onPress={onSavePostMessage}
disabled={!canSave}
testID={'edit_post.save.button'}
text={intl.formatMessage({id: 'mobile.edit_post.save', defaultMessage: 'Save'})}
/>
),
});
}, [navigation, onSavePostMessage, theme.sidebarHeaderTextColor, canSave, intl]);
const onLayout = useCallback((e: LayoutChangeEvent) => {
setContainerHeight(e.nativeEvent.layout.height);
}, []);
useAndroidHardwareBackHandler(Screens.EDIT_POST, onClose);
const overlap = useKeyboardOverlap();
const autocompletePosition = overlap + AUTOCOMPLETE_SEPARATION + QUICK_ACTIONS_HEIGHT;
const autocompleteAvailableSpace = containerHeight - autocompletePosition;
const [animatedAutocompletePosition, animatedAutocompleteAvailableSpace] = useAutocompleteDefaultAnimatedValues(autocompletePosition, autocompleteAvailableSpace);
if (isUpdating) {
return (
<View style={styles.loader}>
<Loading color={theme.buttonBg}/>
</View>
);
}
return (
<EditPostProvider
onFileRemove={handleFileRemoval}
updateFileCallback={updateFileInPostFiles}
isEditMode={true}
>
<SafeAreaView
testID='edit_post.screen'
style={styles.container}
edges={safeAreaEdges}
onLayout={onLayout}
>
<KeyboardAvoidingView
behavior={'padding'}
automaticOffset={true}
style={styles.inputContainer}
>
<View
style={styles.body}
ref={mainView}
>
{Boolean((errorLine || errorExtra)) &&
<PostError
errorExtra={errorExtra}
errorLine={errorLine}
/>
}
<View style={styles.inputContainer}>
<EditPostInput
hasError={Boolean(errorLine || errorExtra)}
message={postMessage}
onChangeText={onInputChangeText}
onTextSelectionChange={onTextSelectionChange}
updateCursorPosition={setCursorPosition}
updateValue={setPostMessage}
inputRef={postInputRef}
post={post}
postFiles={postFiles}
addFiles={addFiles}
/>
</View>
</View>
</KeyboardAvoidingView>
</SafeAreaView>
<Autocomplete
channelId={post.channelId}
shouldDirectlyReact={false}
nestedScrollEnabled={true}
rootId={post.rootId}
updateValue={onAutocompleteChangeText}
value={postMessage}
cursorPosition={cursorPosition}
position={animatedAutocompletePosition}
availableSpace={animatedAutocompleteAvailableSpace}
serverUrl={serverUrl}
/>
</EditPostProvider>
);
};
export default EditPost;