mattermost-mobile-upstream/app/components/files/files.tsx
Pablo Vélez 7df4a0ab97
Some checks are pending
ci / lint-typecheck (push) Waiting to run
ci / detox-lint-typecheck (push) Waiting to run
ci / test (push) Waiting to run
Mm 68219 show placeholder for redacted files (#9719)
* MM-68219 - Add redacted files placeholder and related functionality

* add feature flag control and e2e tests

* adjust placeholder design, polish code, fix permalink preview issue

* polish code and add missing test

* use import path with right path

* gate post refetch behind the feature flag, refetch the open thread and avoid observeCount

* restore filesInfo for the permalink files prop added upstream

* fix stale redaction on background servers, consume the flag on every fetch path and share the viewport emitter

* replace the in-memory redaction flag with a persisted per-post epoch so ABAC file decisions survive restarts and stale posts stay hidden

* raise the redaction epoch on every resync, capture the epoch counter, only invalidate channels on role changes, and store the newer epoch when a re-verified post is otherwise unchanged

* store superseded responses unverified instead of dropping them, keep the since-fetch when re-verifying, verify permalink embeds against the linked channel, and capture the websocket epoch on arrival

* nvalidate file decisions when a user attribute field changes or all its values are cleared

* batch channel invalidations, close file viewers only when affected, reset the epoch on unstamped redaction changes, and only  re-verify the newest page's attachment posts

* re-check older channel posts a page at a time instead of one request per post

* skip the unstamped epoch lookup for posts with no files, redacted count or permalink

* keep the attribute-view retry after later invalidations, retry linked posts unless refused for the current epoch, and stop older payloads from rolling back edits via the redaction check

* MM-70905 - disable and grey out the attachment button when an ABAC pe… (#10195)

* MM-70905 - disable and grey out the attachment button when an ABAC permission policy denies uploads in the channel

* only back off render permission fetches when the server request fails, and log other errors without retrying

* remove the disableServer helper and have removeServer do both steps

* split defaultAllowed into allowWhenUnenforced and allowWhenNotEvaluated, and treat render permissions as unenforced  on servers without the decisions API

* MM-69627: Add playbook task requirements support on mobile (#10035)

* MM-69627: Add playbook task requirements support on mobile

Allow filling required task fields when checking off checklist items during
a run, gated by the same Playbooks beta setting used on web.

Co-authored-by: Cursor <cursoragent@cursor.com>

* MM-69627: Address PR review feedback for task requirements

Propagate settings write failures, harden fill-requirements save/title handling, and add missing unit coverage.

Co-authored-by: Cursor <cursoragent@cursor.com>

* MM-69627: Fix TypeScript errors in new unit tests

Co-authored-by: Cursor <cursoragent@cursor.com>

* MM-69627: Use defineMessages for fill requirements titles

Keep i18n extraction able to find the header titles after moving them to the route.

Co-authored-by: Cursor <cursoragent@cursor.com>

* MM-69627: Address review feedback for task requirements

Update checklist items locally when saving requirement values instead of
refetching the run, add missing query/navigation tests, and apply small
callback/reduce cleanups from review.

Co-authored-by: Cursor <cursoragent@cursor.com>

* MM-69627: Fix task requirements review follow-ups

Propagate local checklist write failures, clear a stale task-requirements
flag when playbooks is unsupported, and cap fill values at the desktop/
server max length.

Co-authored-by: Cursor <cursoragent@cursor.com>

* MM-69627: Move requirement field into its own component

Keep one component per file on the fill-requirements screen.

Co-authored-by: Cursor <cursoragent@cursor.com>

---------

Co-authored-by: Cursor <cursoragent@cursor.com>

* MM-69122: Add file element support to interactive dialogs (#9898)

* Implement Interactive Dialog - file upload

* update demo plugin version for e2etests

* fix and add e2etests

* review fixes

* Fix version bump checkout when a tag shares the branch name (#10229)

* Fix Android crashes caused by animated custom emoji (#10030)

* Route GIF decoding through Glide

- Keep APNG4Android for APNG, animated WebP, and animated AVIF support.
- Prepend Glide's GIF decoders to avoid APNG4Android's native GIF overflow.

* Clear Expo image resources with Glide targets

- Detach drawables when Glide clears their custom target.
- Prevent recycled GIF frame resources from remaining attached to Expo image views.

* Preserve foreground image during GIF target recycling

---------

Co-authored-by: Asaad Mahmood <asaadmahmood@users.noreply.github.com>
Co-authored-by: Cursor <cursoragent@cursor.com>
Co-authored-by: Scott Bishel <scott.bishel@mattermost.com>
Co-authored-by: Nuno Simões <nuno.simoes@mattermost.com>
Co-authored-by: MangelSpec <74370284+MangelSpec@users.noreply.github.com>

* detox - fix clobbering of feature flags that cause failures in other suites.  Also small fix of a incorrectly set test-id

---------

Co-authored-by: Asaad Mahmood <asaadmahmood@users.noreply.github.com>
Co-authored-by: Cursor <cursoragent@cursor.com>
Co-authored-by: Scott Bishel <scott.bishel@mattermost.com>
Co-authored-by: Nuno Simões <nuno.simoes@mattermost.com>
Co-authored-by: MangelSpec <74370284+MangelSpec@users.noreply.github.com>
Co-authored-by: Nate Schlossberg <nate.schlossberg@mattermost.com>
2026-10-15 15:59:13 -07:00

242 lines
8.6 KiB
TypeScript

// Copyright (c) 2015-present Mattermost, Inc. All Rights Reserved.
// See LICENSE.txt for license information.
import React, {useCallback, useEffect, useMemo, useReducer, useState} from 'react';
import {DeviceEventEmitter, type StyleProp, StyleSheet, View, type ViewStyle} from 'react-native';
import Animated from 'react-native-reanimated';
import {Events} from '@constants';
import {GalleryInit} from '@context/gallery';
import {usePostConfig} from '@context/post_config';
import {useIsTablet} from '@hooks/device';
import {useImageAttachments} from '@hooks/files';
import {useIsInViewPort} from '@hooks/in_viewport';
import {usePreventDoubleTap} from '@hooks/utils';
import {fileExists, isImage, isVideo} from '@utils/file';
import {fileToGalleryItem, openGalleryAtIndex} from '@utils/gallery';
import {getViewPortWidth} from '@utils/images';
import File from './file';
type FilesProps = {
failed?: boolean;
filesInfo: FileInfo[];
layoutWidth?: number;
location: string;
isReplyPost: boolean;
postId?: string;
postProps?: Record<string, unknown>;
isPermalinkPreview?: boolean;
}
const MAX_VISIBLE_ROW_IMAGES = 4;
const styles = StyleSheet.create({
row: {
flexDirection: 'row',
marginTop: 5,
flexShrink: 0,
},
rowItemContainer: {
flex: 1,
},
gutter: {
marginLeft: 8,
},
failed: {
opacity: 0.5,
},
marginTop: {
marginTop: 10,
},
rowPermalinkPreview: {
marginTop: 0,
},
});
const Files = ({
failed,
filesInfo,
isReplyPost,
layoutWidth,
location,
postId,
postProps,
isPermalinkPreview = false,
}: FilesProps) => {
const galleryIdentifier = `${postId}-fileAttachments-${location}`;
const inViewPort = useIsInViewPort(location, postId ?? '');
const isTablet = useIsTablet();
const {canDownloadFiles, enableSecureFilePreview} = usePostConfig();
// Validate local paths asynchronously after render
const [validatedFilesInfo, setValidatedFilesInfo] = useState(filesInfo);
const {images: imageAttachments, nonImages: nonImageAttachments} = useImageAttachments(validatedFilesInfo);
// Force re-render when a file is rejected (to move it from images to nonImages)
const [, forceUpdate] = useReducer((x: number) => x + 1, 0);
const [filesForGallery, setFilesForGallery] = useState(() => [...imageAttachments, ...nonImageAttachments]);
const attachmentIndex = (fileId: string) => {
return filesForGallery.findIndex((file) => file.id === fileId) || 0;
};
const handlePreviewPress = usePreventDoubleTap(useCallback((idx: number) => {
const items = filesForGallery.map((f) => fileToGalleryItem(f, f.user_id, postProps, 0, f.id));
openGalleryAtIndex(galleryIdentifier, idx, items);
}, [filesForGallery, galleryIdentifier, postProps]));
const updateFileForGallery = useCallback((idx: number, file: FileInfo) => {
const newFilesForGallery = [...filesForGallery];
newFilesForGallery[idx] = file;
setFilesForGallery(newFilesForGallery);
}, [filesForGallery]);
const isSingleImage = useMemo(() => filesInfo.filter((f) => isImage(f) || isVideo(f)).length === 1, [filesInfo]);
const renderItems = (items: FileInfo[], moreImagesCount = 0, includeGutter = false, isImageRow = false) => {
let nonVisibleImagesCount: number;
// Apply flex: 1 for multiple items, except in permalink previews where vertical
// document lists should not use flex to prevent shrinking under maxHeight constraints.
// Horizontal image rows (includeGutter=true) still need flex for space distribution.
const shouldApplyFlex = items.length > 1 && !(isPermalinkPreview && !includeGutter);
let container: StyleProp<ViewStyle> = shouldApplyFlex ? styles.rowItemContainer : undefined;
const containerWithGutter = [container, styles.gutter];
const wrapperWidth = getViewPortWidth(isReplyPost, isTablet) - 6;
return items.map((file, idx) => {
if (moreImagesCount && idx === MAX_VISIBLE_ROW_IMAGES - 1) {
nonVisibleImagesCount = moreImagesCount;
}
if (idx !== 0 && includeGutter) {
container = containerWithGutter;
}
const shouldRemoveMarginTop = isPermalinkPreview && (
(isImageRow) || // Remove marginTop for all images in image row
(!isImageRow && idx === 0 && imageAttachments.length === 0) // Remove marginTop for first non-image only if no images present
);
return (
<View
style={[container, styles.marginTop, shouldRemoveMarginTop && {marginTop: 0}]}
testID={`${file.id}-file-container`}
key={file.id}
>
<File
galleryIdentifier={galleryIdentifier}
key={file.id}
canDownloadFiles={canDownloadFiles}
enableSecureFilePreview={enableSecureFilePreview}
file={file}
index={attachmentIndex(file.id!)}
onPress={handlePreviewPress}
isSingleImage={isSingleImage}
nonVisibleImagesCount={nonVisibleImagesCount}
updateFileForGallery={updateFileForGallery}
wrapperWidth={layoutWidth || wrapperWidth}
inViewPort={inViewPort}
/>
</View>
);
});
};
const renderImageRow = () => {
if (imageAttachments.length === 0) {
return null;
}
const visibleImages = imageAttachments.slice(0, MAX_VISIBLE_ROW_IMAGES);
const portraitPostWidth = layoutWidth || (getViewPortWidth(isReplyPost, isTablet) - 6);
let nonVisibleImagesCount;
if (imageAttachments.length > MAX_VISIBLE_ROW_IMAGES) {
nonVisibleImagesCount = imageAttachments.length - MAX_VISIBLE_ROW_IMAGES;
}
return (
<View
style={[
styles.row,
{width: portraitPostWidth},
isPermalinkPreview && {marginTop: 0},
]}
testID='image-row'
>
{ renderItems(visibleImages, nonVisibleImagesCount, true, true) }
</View>
);
};
useEffect(() => {
setFilesForGallery([...imageAttachments, ...nonImageAttachments]);
}, [imageAttachments, nonImageAttachments]);
// Validate local paths asynchronously in background
useEffect(() => {
let isCancelled = false;
const validateFiles = () => {
// If no files have localPath, skip validation but still update state
const hasLocalPaths = filesInfo.some((f) => f.localPath);
if (!hasLocalPaths) {
if (!isCancelled) {
setValidatedFilesInfo(filesInfo);
}
return;
}
// Validate each file's localPath
const validated = filesInfo.map((file) => {
if (file.localPath && !fileExists(file.localPath)) {
return {...file, localPath: ''};
}
return file;
});
// Only update state if component is still mounted
if (!isCancelled) {
setValidatedFilesInfo(validated);
}
};
validateFiles();
return () => {
isCancelled = true;
};
}, [filesInfo]);
// Listen for file rejection events and re-render if one of our files is rejected
// This handles the race condition where files render before rejection status is known
useEffect(() => {
const fileIds = new Set(filesInfo.map((f) => f.id));
const onFileRejected = ({fileId}: {fileId: string}) => {
if (fileIds.has(fileId)) {
forceUpdate();
}
};
const listener = DeviceEventEmitter.addListener(Events.FILE_REJECTED, onFileRejected);
return () => listener.remove();
}, [filesInfo]);
return (
<GalleryInit galleryIdentifier={galleryIdentifier}>
<Animated.View
testID='files-container'
style={[
failed ? styles.failed : undefined,
isPermalinkPreview && {marginTop: 0},
]}
>
{renderImageRow()}
{renderItems(nonImageAttachments)}
</Animated.View>
</GalleryInit>
);
};
export default React.memo(Files);