import { FileType } from "@openchat/types" import { useRef } from "react" import {…
- User
import { FileType } from "@openchat/types" import { useRef } from "react" import { Image, LayoutAnimation, TouchableOpacity, View } from "react-native" import { FlatList } from "react-native-gesture-handler" import Video, { VideoRef } from "react-native-video" import { AppColors } from "../../../app/app.colors" import { Icon } from "../../../ui-components/icon/icon.component" import { StyledText } from "../../../ui-components/styled-text/styled-text" import { useStyles } from "./message-attachment-uploaded-files-preview.style"
export const MessageAttachmentUploadedFilesPreview = ({ files, onFileRemove, screen, isEnabled = false, }: { files: FileType[] onFileRemove: (fileId: string) => void screen?: string isEnabled?: boolean }) => { // ------------------------------------------------------------------------------------ // variables // ------------------------------------------------------------------------------------
const styles = useStyles() const videoRef = useRef(null) const flatListRef = useRef<FlatList>(null) const layoutAnimConfig = { duration: 300, update: { type: LayoutAnimation.Types.easeInEaseOut, }, delete: { duration: 100, type: LayoutAnimation.Types.easeInEaseOut, property: LayoutAnimation.Properties.opacity, }, }
// ------------------------------------------------------------------------------------ // functions // ------------------------------------------------------------------------------------ function formatSizeUnits(bytes: number) { let size if (bytes >= 1073741824) { size = (bytes / 1073741824).toFixed(2) + " GB" } else if (bytes >= 1048576) { size = (bytes / 1048576).toFixed(2) + " MB" } else if (bytes >= 1024) { size = (bytes / 1024).toFixed(2) + " KB" } else if (bytes > 1) { size = bytes + " bytes" } else if (bytes == 1) { size = bytes + " byte" } else { size = "0 byte" } return size }
// ------------------------------------------------------------------------------------ return ( <> <FlatList showsHorizontalScrollIndicator={false} ref={flatListRef} contentContainerStyle={[ styles.scrollWrapper, { gap: screen === "MessageBoardCardInfo" ? 5 : 10 }, ]} horizontal={true} scrollEnabled={isEnabled ? false : true} data={files} keyExtractor={(file) => file.id} renderItem={({ item: file }) => { return ( {file.mimeType.startsWith("image") && ( <Image resizeMode="cover" style={styles.media} source={{ uri: file.data }} /> )} {file.mimeType.startsWith("video") && ( // <Image // resizeMode="cover" // style={styles.media} // source={{ uri: file.data }} // /> <Video // resizeMode="cover" // Can be a URL or a local file. source={{ uri: file.data }} // source={{ uri:
file://${file.data}}} // Store reference ref={videoRef} // Callback when remote video is buffering // onBuffer={onBuffer} // Callback when video cannot be loaded // onError={onError}style={styles.videoPreview} pictureInPicture={true} /> )} {file.mimeType.startsWith("audio") && <></>} {!file.mimeType.startsWith("image") && !file.mimeType.startsWith("video") && !file.mimeType.startsWith("audio") && ( <View style={styles.anotherFiles}> <Icon name="fal fa-file-lines" bald={true} size={25} fill={AppColors.placeholderText} /> <View style={styles.fileInfoWrapper}> <StyledText ellipsizeMode="tail" numberOfLines={1} style={styles.fileName} > {file.name} </StyledText> <StyledText style={styles.fileSize}> {formatSizeUnits(file.size)} </StyledText> </View> </View> )} {screen !== "MessageBoardCardInfo" && ( <TouchableOpacity activeOpacity={0.9} style={styles.xHolder} onPress={() => { onFileRemove(file.id) LayoutAnimation.configureNext(layoutAnimConfig) }} > <Icon name="fal fa-xmark" bald={true} height={14} width={9} /> </TouchableOpacity> )} </View> ) }} /> </>) } I have videos that I'd like to present as thumbnails before a user clicks on them for the full video. They are not local, I only have the url. Is there a RN component to do this? The RN Image component does not take videos urls as sources.
- Assistant
Yes, React Native's
Imagecomponent does not support video URLs as sources. To present videos as thumbnails, you can use a third-party library likereact-native-thumbnail-video. This library supports generating a thumbnail from video URLs (YouTube, Vimeo, etc.) and can be convenient for your use case.Here's an example of how you can use
react-native-thumbnail-videoin your code:- Install the library:
npm install react-native-thumbnail-video # or yarn add react-native-thumbnail-video- Use the library:
First, import the necessary components from the library and use it to generate thumbnails from the video URLs. Here's how you can integrate it into your existing component.
import React, { useRef } from 'react'; import { Image, LayoutAnimation, TouchableOpacity, View } from 'react-native'; import { FlatList } from 'react-native-gesture-handler'; import { AppColors } from '../../../app/app.colors'; import { Icon } from '../../../ui-components/icon/icon.component'; import { StyledText } from '../../../ui-components/styled-text/styled-text'; import { useStyles } from './message-attachment-uploaded-files-preview.style'; import { Thumbnail } from 'react-native-thumbnail-video'; export const MessageAttachmentUploadedFilesPreview = ({ files, onFileRemove, screen, isEnabled = false, }: { files: FileType[]; onFileRemove: (fileId: string) => void; screen?: string; isEnabled?: boolean; }) => { const styles = useStyles(); const flatListRef = useRef<FlatList<FileType>>(null); const layoutAnimConfig = { duration: 300, update: { type: LayoutAnimation.Types.easeInEaseOut, }, delete: { duration: 100, type: LayoutAnimation.Types.easeInEaseOut, property: LayoutAnimation.Properties.opacity, }, }; function formatSizeUnits(bytes: number) { // Your formatSizeUnits implementation } return ( <> <FlatList showsHorizontalScrollIndicator={false} ref={flatListRef} contentContainerStyle={[ styles.scrollWrapper, { gap: screen === 'MessageBoardCardInfo' ? 5 : 10 }, ]} horizontal={true} scrollEnabled={isEnabled ? false : true} data={files} keyExtractor={(file) => file.id} renderItem={({ item: file }) => { return ( <View style={styles.attachmentItem} key={file.id}> {file.mimeType.startsWith('image') && ( <View> <Image resizeMode="cover" style={styles.media} source={{ uri: file.data }} /> </View> )} {file.mimeType.startsWith('video') && ( <View> <Thumbnail url={file.data} imageWidth={200} imageHeight={150} /> </View> )} {file.mimeType.startsWith('audio') && <></>} {!file.mimeType.startsWith('image') && !file.mimeType.startsWith('video') && !file.mimeType.startsWith('audio') && ( <View style={styles.anotherFiles}> <Icon name="fal fa-file-lines" bald={true} size={25} fill={AppColors.placeholderText} /> <View style={styles.fileInfoWrapper}> <StyledText ellipsizeMode="tail" numberOfLines={1} style={styles.fileName} > {file.name} </StyledText> <StyledText style={styles.fileSize}> {formatSizeUnits(file.size)} </StyledText> </View> </View> )} {screen !== 'MessageBoardCardInfo' && ( <TouchableOpacity activeOpacity={0.9} style={styles.xHolder} onPress={() => { onFileRemove(file.id); LayoutAnimation.configureNext(layoutAnimConfig); }} > <Icon name="fal fa-xmark" bald={true} height={14} width={9} /> </TouchableOpacity> )} </View> ); }} /> </> ); };Explanation:
- Thumbnail component: The
Thumbnailcomponent from thereact-native-thumbnail-videolibrary is used to generate and display a thumbnail for the video URL. - imageWidth and imageHeight props: The
imageWidthandimageHeightprops specify the dimensions of the thumbnail.
This approach will allow you to show video thumbnails before the user clicks on them to start playing the full video. If you have your own backend to generate thumbnails, you can also use those URLs to display images instead of using the library.
Make sure you have the necessary permissions and handling in place to ensure smooth playback and error handling for the videos and thumbnails.
- User
I installed react-native-create-thumbnail
- Assistant
Great!
react-native-create-thumbnailis another excellent library for generating thumbnails from video files. Here's how you can integrate it into your component to generate and display video thumbnails.- Install the library:
npm install react-native-create-thumbnail # or yarn add react-native-create-thumbnail- Generate Thumbnails:
You will need to generate the thumbnail using the library and then display it using the
Imagecomponent. Here's an updated version of your component usingreact-native-create-thumbnail:import React, { useEffect, useState, useRef } from 'react'; import { Image, LayoutAnimation, TouchableOpacity, View } from 'react-native'; import { FlatList } from 'react-native-gesture-handler'; import Video from 'react-native-video'; import createThumbnail from 'react-native-create-thumbnail'; import { AppColors } from '../../../app/app.colors'; import { Icon } from '../../../ui-components/icon/icon.component'; import { StyledText } from '../../../ui-components/styled-text/styled-text'; import { useStyles } from './message-attachment-uploaded-files-preview.style'; export const MessageAttachmentUploadedFilesPreview = ({ files, onFileRemove, screen, isEnabled = false, }: { files: FileType[]; onFileRemove: (fileId: string) => void; screen?: string; isEnabled?: boolean; }) => { const styles = useStyles(); const flatListRef = useRef<FlatList<FileType>>(null); const layoutAnimConfig = { duration: 300, update: { type: LayoutAnimation.Types.easeInEaseOut, }, delete: { duration: 100, type: LayoutAnimation.Types.easeInEaseOut, property: LayoutAnimation.Properties.opacity, }, }; const [thumbnails, setThumbnails] = useState<{ [key: string]: string }>({}); useEffect(() => { const generateThumbnails = async () => { const newThumbnails: { [key: string]: string } = {}; for (const file of files) { if (file.mimeType.startsWith('video')) { try { const { path } = await createThumbnail({ url: file.data, // optional, default is 0.0 seconds timeStamp: 1000, }); newThumbnails[file.id] = path; } catch (error) { console.error(`Failed to generate thumbnail for ${file.name}:`, error); } } } setThumbnails(newThumbnails); }; generateThumbnails(); }, [files]); function formatSizeUnits(bytes: number) { // Your formatSizeUnits implementation } return ( <FlatList showsHorizontalScrollIndicator={false} ref={flatListRef} contentContainerStyle={[ styles.scrollWrapper, { gap: screen === 'MessageBoardCardInfo' ? 5 : 10 }, ]} horizontal={true} scrollEnabled={isEnabled ? false : true} data={files} keyExtractor={(file) => file.id} renderItem={({ item: file }) => { return ( <View style={styles.attachmentItem} key={file.id}> {file.mimeType.startsWith('image') && ( <View> <Image resizeMode="cover" style={styles.media} source={{ uri: file.data }} /> </View> )} {file.mimeType.startsWith('video') && ( <View> {thumbnails[file.id] ? ( <Image resizeMode="cover" style={styles.media} source={{ uri: thumbnails[file.id] }} /> ) : ( <StyledText>Loading thumbnail...</StyledText> )} </View> )} {file.mimeType.startsWith('audio') && <></>} {!file.mimeType.startsWith('image') && !file.mimeType.startsWith('video') && !file.mimeType.startsWith('audio') && ( <View style={styles.anotherFiles}> <Icon name="fal fa-file-lines" bald={true} size={25} fill={AppColors.placeholderText} /> <View style={styles.fileInfoWrapper}> <StyledText ellipsizeMode="tail" numberOfLines={1} style={styles.fileName} > {file.name} </StyledText> <StyledText style={styles.fileSize}> {formatSizeUnits(file.size)} </StyledText> </View> </View> )} {screen !== 'MessageBoardCardInfo' && ( <TouchableOpacity activeOpacity={0.9} style={styles.xHolder} onPress={() => { onFileRemove(file.id); LayoutAnimation.configureNext(layoutAnimConfig); }} > <Icon name="fal fa-xmark" bald={true} height={14} width={9} /> </TouchableOpacity> )} </View> ); }} /> ); };Explanation:
-
Thumbnail Generation:
- The
useEffecthook is used to generate thumbnails for video files when thefilesarray changes. createThumbnailgenerates a thumbnail for the video URL and saves it in thethumbnailsstate.- The
thumbnailsstate maps file IDs to thumbnail paths.
- The
-
Displaying Thumbnails:
- If the file is a video and a thumbnail has been generated, it displays the thumbnail using the
Imagecomponent. - If the thumbnail is still being generated, it displays a "Loading thumbnail..." message.
- If the file is a video and a thumbnail has been generated, it displays the thumbnail using the
This approach ensures that your video thumbnails are displayed as soon as they are generated, improving the user experience.
- User
Failed to generate thumbnail for set-ADA88B2C-F8F7-49E2-A76A-7605D9DEB3AE.mp4: [TypeError: Cannot read property 'createThumbnail' of undefined]
- Assistant
The error message
[TypeError: Cannot read property 'createThumbnail' of undefined]suggests that thecreateThumbnailmethod from thereact-native-create-thumbnailpackage is not being properly imported or is not available. Let's go through some steps to resolve this issue:1. Verify Installation
Ensure that the package is correctly installed. You should see
react-native-create-thumbnailin yourpackage.jsonandnode_modulesfolder.npm install react-native-create-thumbnail # or yarn add react-native-create-thumbnail2. Check Import Statement
Ensure that you are importing
createThumbnailcorrectly from the package:import createThumbnail from 'react-native-create-thumbnail';3. Verify Native Linking
If you are not using React Native 0.60+ which has auto-linking, you might need to link the package manually. Check the setup instructions in the react-native-create-thumbnail documentation.
4. Rebuild the Project
After verifying the installation and import, rebuild the project to make sure everything is linked correctly.
npx react-native run-android # or npx react-native run-ios5. Complete Code Example
Ensure your code is correct. Here’s a complete example to highlight potential issues:
import React, { useEffect, useRef, useState } from 'react'; import { Image, LayoutAnimation, TouchableOpacity, View } from 'react-native'; import { FlatList } from 'react-native-gesture-handler'; import createThumbnail from 'react-native-create-thumbnail'; import { AppColors } from '../../../app/app.colors'; import { Icon } from '../../../ui-components/icon/icon.component'; import { StyledText } from '../../../ui-components/styled-text/styled-text'; import { useStyles } from './message-attachment-uploaded-files-preview.style'; export const MessageAttachmentUploadedFilesPreview = ({ files, onFileRemove, screen, isEnabled = false, }: { files: FileType[]; onFileRemove: (fileId: string) => void; screen?: string; isEnabled?: boolean; }) => { const styles = useStyles(); const flatListRef = useRef<FlatList<FileType>>(null); const layoutAnimConfig = { duration: 300, update: { type: LayoutAnimation.Types.easeInEaseOut, }, delete: { duration: 100, type: LayoutAnimation.Types.easeInEaseOut, property: LayoutAnimation.Properties.opacity, }, }; const [thumbnails, setThumbnails] = useState<{ [key: string]: string }>({}); useEffect(() => { const generateThumbnails = async () => { const newThumbnails: { [key: string]: string } = {}; for (const file of files) { if (file.mimeType.startsWith('video')) { try { const { path } = await createThumbnail({ url: file.data, // optional, default is 0.0 seconds timeStamp: 1000, }); newThumbnails[file.id] = path; } catch (error) { console.error(`Failed to generate thumbnail for ${file.name}:`, error); } } } setThumbnails(newThumbnails); }; generateThumbnails(); }, [files]); function formatSizeUnits(bytes: number) { // Your formatSizeUnits implementation } return ( <FlatList showsHorizontalScrollIndicator={false} ref={flatListRef} contentContainerStyle={[ styles.scrollWrapper, { gap: screen === 'MessageBoardCardInfo' ? 5 : 10 }, ]} horizontal={true} scrollEnabled={isEnabled ? false : true} data={files} keyExtractor={(file) => file.id} renderItem={({ item: file }) => { return ( <View style={styles.attachmentItem} key={file.id}> {file.mimeType.startsWith('image') && ( <View> <Image resizeMode="cover" style={styles.media} source={{ uri: file.data }} /> </View> )} {file.mimeType.startsWith('video') && ( <View> {thumbnails[file.id] ? ( <Image resizeMode="cover" style={styles.media} source={{ uri: thumbnails[file.id] }} /> ) : ( <StyledText>Loading thumbnail...</StyledText> )} </View> )} {file.mimeType.startsWith('audio') && <></>} {!file.mimeType.startsWith('image') && !file.mimeType.startsWith('video') && !file.mimeType.startsWith('audio') && ( <View style={styles.anotherFiles}> <Icon name="fal fa-file-lines" bald={true} size={25} fill={AppColors.placeholderText} /> <View style={styles.fileInfoWrapper}> <StyledText ellipsizeMode="tail" numberOfLines={1} style={styles.fileName} > {file.name} </StyledText> <StyledText style={styles.fileSize}> {formatSizeUnits(file.size)} </StyledText> </View> </View> )} {screen !== 'MessageBoardCardInfo' && ( <TouchableOpacity activeOpacity={0.9} style={styles.xHolder} onPress={() => { onFileRemove(file.id); LayoutAnimation.configureNext(layoutAnimConfig); }} > <Icon name="fal fa-xmark" bald={true} height={14} width={9} /> </TouchableOpacity> )} </View> ); }} /> ); };Checklist:
- Ensure proper package installation and linking.
- Correctly import the
createThumbnailfunction. - Rebuild your React Native project to link native modules correctly.
If these steps do not resolve the issue, consider checking the
react-native-create-thumbnailGitHub repository for issues and troubleshooting, or open an issue if you cannot find a solution. - User
const { path } = await createThumbnail({ This expression is not callable. Type 'CreateThumbnail' has no call signatures.ts(2349)
- Assistant
The error message
Type 'CreateThumbnail' has no call signaturessuggests that the importedcreateThumbnailis not recognized as a callable function. This could be due to incorrect type definitions or issues with how the library is being imported.To resolve this issue, let’s ensure everything is correctly set up by verifying the types and import statement. Here's a detailed solution:
1. Verify the Import
Ensure that you are importing the default export correctly:
import createThumbnail from 'react-native-create-thumbnail';If you're using TypeScript, it might be possible that type definitions are incorrect or missing, so you might want to add appropriate types.
2. Check Library's Documentation
Review the official React Native Create Thumbnail documentation for any updates or additional setup instructions.
3. Setting Up Type Definitions
You might have to create or adjust the type definitions if they are not included:
declare module 'react-native-create-thumbnail' { const createThumbnail: (params: { url: string, timeStamp?: number }) => Promise<{ path: string }>; export default createThumbnail; }4. Comprehensive Example
Below is an updated comprehensive example that ensures type definitions and usage are correct:
Step 1: Create or Update your Type Declaration (if not present) Create a file
react-native-create-thumbnail.d.tsin your project's root orsrcdirectory:declare module 'react-native-create-thumbnail' { const createThumbnail: (params: { url: string, timeStamp?: number }) => Promise<{ path: string }>; export default createThumbnail; }Step 2: Update Your Component
Ensure you have the correct imports and parameters:
import React, { useEffect, useState, useRef } from 'react'; import { Image, LayoutAnimation, TouchableOpacity, View } from 'react-native'; import { FlatList } from 'react-native-gesture-handler'; import createThumbnail from 'react-native-create-thumbnail'; // Ensure correct import import { AppColors } from '../../../app/app.colors'; import { Icon } from '../../../ui-components/icon/icon.component'; import { StyledText } from '../../../ui-components/styled-text/styled-text'; import { useStyles } from './message-attachment-uploaded-files-preview.style'; interface FileType { id: string; name: string; data: string; mimeType: string; size: number; } export const MessageAttachmentUploadedFilesPreview = ({ files, onFileRemove, screen, isEnabled = false, }: { files: FileType[]; onFileRemove: (fileId: string) => void; screen?: string; isEnabled?: boolean; }) => { const styles = useStyles(); const flatListRef = useRef<FlatList<FileType>>(null); const layoutAnimConfig = { duration: 300, update: { type: LayoutAnimation.Types.easeInEaseOut, }, delete: { duration: 100, type: LayoutAnimation.Types.easeInEaseOut, property: LayoutAnimation.Properties.opacity, }, }; const [thumbnails, setThumbnails] = useState<{ [key: string]: string }>({}); useEffect(() => { const generateThumbnails = async () => { const newThumbnails: { [key: string]: string } = {}; for (const file of files) { if (file.mimeType.startsWith('video')) { try { const { path } = await createThumbnail({ url: file.data, timeStamp: 1000, }); newThumbnails[file.id] = path; } catch (error) { console.error(`Failed to generate thumbnail for ${file.name}:`, error); } } } setThumbnails(newThumbnails); }; generateThumbnails(); }, [files]); function formatSizeUnits(bytes: number) { // Your formatSizeUnits implementation } return ( <FlatList showsHorizontalScrollIndicator={false} ref={flatListRef} contentContainerStyle={[ styles.scrollWrapper, { gap: screen === 'MessageBoardCardInfo' ? 5 : 10 }, ]} horizontal={true} scrollEnabled={isEnabled ? false : true} data={files} keyExtractor={(file) => file.id} renderItem={({ item: file }) => { return ( <View style={styles.attachmentItem} key={file.id}> {file.mimeType.startsWith('image') && ( <View> <Image resizeMode="cover" style={styles.media} source={{ uri: file.data }} /> </View> )} {file.mimeType.startsWith('video') && ( <View> {thumbnails[file.id] ? ( <Image resizeMode="cover" style={styles.media} source={{ uri: thumbnails[file.id] }} /> ) : ( <StyledText>Loading thumbnail...</StyledText> )} </View> )} {file.mimeType.startsWith('audio') && <></>} {!file.mimeType.startsWith('image') && !file.mimeType.startsWith('video') && !file.mimeType.startsWith('audio') && ( <View style={styles.anotherFiles}> <Icon name="fal fa-file-lines" bald={true} size={25} fill={AppColors.placeholderText} /> <View style={styles.fileInfoWrapper}> <StyledText ellipsizeMode="tail" numberOfLines={1} style={styles.fileName} > {file.name} </StyledText> <StyledText style={styles.fileSize}> {formatSizeUnits(file.size)} </StyledText> </View> </View> )} {screen !== 'MessageBoardCardInfo' && ( <TouchableOpacity activeOpacity={0.9} style={styles.xHolder} onPress={() => { onFileRemove(file.id); LayoutAnimation.configureNext(layoutAnimConfig); }} > <Icon name="fal fa-xmark" bald={true} height={14} width={9} /> </TouchableOpacity> )} </View> ); }} /> ); };By setting up the type definitions correctly and verifying your imports, you ensure that
createThumbnailis treated as a callable function in TypeScript. If you continue to encounter issues, consult the library’s repository for further assistance or potential updates.