Improve media code and add tumbnails to slideshow

This commit is contained in:
Adolfo Reyna
2024-10-05 21:30:34 -04:00
parent cd78742d15
commit d349598981
2 changed files with 208 additions and 161 deletions

View File

@@ -1,7 +1,7 @@
import React, { useRef } from 'react'; import React, { useRef } from 'react';
import { StyleSheet, View, Text, Animated, PanResponder, Dimensions, TouchableOpacity } from 'react-native'; import { StyleSheet, View, Text, Animated, PanResponder, Dimensions, FlatList, TouchableOpacity } from 'react-native';
import { Image } from 'expo-image'; // Import Image from expo-image import { Image } from 'expo-image'; // Import Image from expo-image
import { Button, Card, Chip } from 'react-native-paper'; import { Button } from 'react-native-paper';
import * as Sharing from 'expo-sharing'; import * as Sharing from 'expo-sharing';
import * as FileSystem from 'expo-file-system'; import * as FileSystem from 'expo-file-system';
@@ -9,6 +9,7 @@ const { width: SCREEN_WIDTH } = Dimensions.get('window');
let Slideshow = (props) => { let Slideshow = (props) => {
const images = props.route.params.images; const images = props.route.params.images;
const imagesTumb = images.map((imageUrl) => imageUrl[1] + '?width=100&height=100`');
const [imageIndex, setImageIndex] = React.useState(props.route.params.startIndex); const [imageIndex, setImageIndex] = React.useState(props.route.params.startIndex);
// Animated value for horizontal translation // Animated value for horizontal translation
@@ -47,8 +48,7 @@ let Slideshow = (props) => {
if (prevIndex > 0) if (prevIndex > 0)
return prevIndex - 1 return prevIndex - 1
return prevIndex return prevIndex
} });
);
translateX.setValue(0); translateX.setValue(0);
}); });
} else { } else {
@@ -68,30 +68,16 @@ let Slideshow = (props) => {
const { uri } = await FileSystem.downloadAsync(images[imageIndex][1], fileUri); const { uri } = await FileSystem.downloadAsync(images[imageIndex][1], fileUri);
await Sharing.shareAsync(uri); await Sharing.shareAsync(uri);
} catch (error) { } catch (error) {
//Alert.alert('Error', 'Failed to share image. Please try again later.');
console.error(error) console.error(error)
} }
}; };
const repostImage = () => { const repostImage = () => {
// Repost logic goes here (for now, just showing an alert)
//Alert.alert('Repost', 'Repost functionality is not yet implemented.');
props.navigation.navigate('NewPost', { intialContent: '@image:' + images[imageIndex][1] }); props.navigation.navigate('NewPost', { intialContent: '@image:' + images[imageIndex][1] });
}; };
return ( return (
<View style={styles.container}> <View style={styles.container}>
<Text style={styles.countText}>{imageIndex + 1}/{images.length}</Text> <Text style={styles.countText}>{imageIndex + 1}/{images.length}</Text>
{/* Left arrow */}
{(imageIndex > 0) && (
<Text style={[styles.arrow, styles.leftArrow]}>{'|'}</Text>
)}
{/* Right arrow */}
{imageIndex < images.length - 1 && (
<Text style={[styles.arrow, styles.rightArrow]}>{'|'}</Text>
)}
<Animated.View <Animated.View
style={[ style={[
styles.imageContainer, styles.imageContainer,
@@ -108,15 +94,38 @@ let Slideshow = (props) => {
</Animated.View> </Animated.View>
{/* Share and Repost Buttons */} {/* Share and Repost Buttons */}
<View style={styles.buttonsContainer}> <View style={styles.buttonsContainer}>
<Button icon="ios-share" labelStyle={{ fontSize: 25 }} style={{ flow: 1 }} <Button icon="ios-share" labelStyle={{ fontSize: 25 }} style={{ margin:10 }}
onPress={shareImage} onPress={shareImage}
color="#555" color="#555"
></Button> ></Button>
<Button icon="send" labelStyle={{ fontSize: 25 }} style={{ flow: 1 }} <Button icon="send" labelStyle={{ fontSize: 25 }} style={{ }}
onPress={repostImage} onPress={repostImage}
color="#555" color="#555"
></Button> ></Button>
</View> </View>
{/* Thumbnails */}
<FlatList
data={imagesTumb}
horizontal
keyExtractor={(item, index) => index.toString()}
renderItem={({ item, index }) => (
<TouchableOpacity onPress={() => {
setImageIndex(index);
}}>
<Image
source={{ uri: item }}
style={[
styles.thumbnail,
imageIndex === index && styles.currentThumbnail
]}
cachePolicy="memory-disk"
/>
</TouchableOpacity>
)}
initialNumToRender={6}
style={styles.thumbnailList}
showsHorizontalScrollIndicator={false}
/>
</View> </View>
); );
}; };
@@ -148,36 +157,30 @@ const styles = StyleSheet.create({
backgroundColor: 'rgba(255, 255, 255, 0.5)', backgroundColor: 'rgba(255, 255, 255, 0.5)',
padding: 10, padding: 10,
}, },
arrow: {
position: 'absolute',
top: '45%',
fontSize: 40,
color: 'rgba(255, 255, 255, 0.7)',
zIndex: 1,
},
leftArrow: {
left: 10,
},
rightArrow: {
right: 10,
},
buttonsContainer: { buttonsContainer: {
flexDirection: 'row', flexDirection: 'column',
justifyContent: 'space-around', justifyContent: 'space-around',
position: 'absolute', position: 'absolute',
bottom: 20, right: -20,
bottom: 90,
paddingHorizontal: 10,
},
thumbnailList: {
position: 'absolute',
bottom: 15,
width: '100%', width: '100%',
paddingHorizontal: 20, paddingHorizontal: 10,
}, },
button: { thumbnail: {
paddingVertical: 10, width: 60,
paddingHorizontal: 20, height: 60,
backgroundColor: 'rgba(255, 255, 255, 0.7)', marginHorizontal: 5,
borderRadius: 5, borderRadius: 10,
borderWidth: 2,
borderColor: 'white',
}, },
buttonText: { currentThumbnail: {
color: '#fff', borderColor: 'rgba(50,255,50,0.8)',
fontSize: 16,
}, },
}); });

View File

@@ -1,3 +1,4 @@
// Import necessary dependencies
import React, { useState, useEffect } from 'react'; import React, { useState, useEffect } from 'react';
import { View, TouchableHighlight, StyleSheet, FlatList, TouchableWithoutFeedback, Share } from 'react-native'; import { View, TouchableHighlight, StyleSheet, FlatList, TouchableWithoutFeedback, Share } from 'react-native';
import { Button, Text, ProgressBar } from 'react-native-paper'; import { Button, Text, ProgressBar } from 'react-native-paper';
@@ -13,6 +14,7 @@ import { Image } from 'expo-image'; // Import Image from expo-image
import * as FileSystem from 'expo-file-system'; import * as FileSystem from 'expo-file-system';
import * as Sharing from 'expo-sharing'; import * as Sharing from 'expo-sharing';
// Extract Vimeo video ID from content string
const videoIdF = (content) => { const videoIdF = (content) => {
let vimeoTag = content.match(/@vimeo:[0-9]+/); let vimeoTag = content.match(/@vimeo:[0-9]+/);
if (!vimeoTag) return []; if (!vimeoTag) return [];
@@ -21,6 +23,7 @@ const videoIdF = (content) => {
return tag.split(':'); return tag.split(':');
}; };
// Extract YouTube video ID from content string
const youtubeIdF = (content) => { const youtubeIdF = (content) => {
let youtubeTag = content.match(/@youtube:[0-z]+/); let youtubeTag = content.match(/@youtube:[0-z]+/);
if (!youtubeTag) return ''; if (!youtubeTag) return '';
@@ -29,6 +32,7 @@ const youtubeIdF = (content) => {
return tag.split(':')[1]; return tag.split(':')[1];
}; };
// Extract HLS URL from content string
const hlsIdF = (content) => { const hlsIdF = (content) => {
let hslTag = content.match(/@hls:.+\w/); let hslTag = content.match(/@hls:.+\w/);
if (!hslTag) return ''; if (!hslTag) return '';
@@ -37,19 +41,21 @@ const hlsIdF = (content) => {
return tag; return tag;
}; };
const imagesTagF = (content) => { // Extract image tags from content string
const imagesTagF = (content, width = 1000, height = 1000) => {
let images = content.match(/@image:[0-z|/|.|]+/g); let images = content.match(/@image:[0-z|/|.|]+/g);
if (!images) return []; if (!images) return [];
let Tags = []; let Tags = [];
images.forEach(i => { images.forEach(i => {
let tag = i.substring(1); let tag = i.substring(1);
let parts = [tag.substring(1, tag.indexOf(":")), tag.substring(tag.indexOf(":") + 1)]; let parts = [tag.substring(1, tag.indexOf(":")), tag.substring(tag.indexOf(":") + 1)];
if (parts[1].substring(0, 4) != "http") parts[1] = "https://social.emmint.com/" + parts[1] + '?width=1000&height=1000'; if (parts[1].substring(0, 4) != "http") parts[1] = `https://social.emmint.com/${parts[1]}?width=${width}&height=${height}`;
Tags.push(parts); Tags.push(parts);
}); });
return Tags; return Tags;
}; };
// Extract iframe source from content string
const iframeTagF = (content) => { const iframeTagF = (content) => {
let iframeMatch = content.match(/@iframe:.+\w/g); let iframeMatch = content.match(/@iframe:.+\w/g);
if (!iframeMatch) return []; if (!iframeMatch) return [];
@@ -58,25 +64,32 @@ const iframeTagF = (content) => {
return parts; return parts;
}; };
// Media Component
let Media = (props) => { let Media = (props) => {
const gState = useSnapshot(GlobalState); const gState = useSnapshot(GlobalState);
const viewer = gState.me; const viewer = gState.me;
const imagesTag = imagesTagF(props.content);
// Extracting tags from content
const imagesTag = imagesTagF(props.content, props.imageWidth || 1000, props.imageHeight || 1000);
const imagesTagLimited = imagesTag.slice(0, 10); const imagesTagLimited = imagesTag.slice(0, 10);
const imageStyle = imagesTag.length == 1 ? styles.image : styles.multipleImage; const imageStyle = imagesTag.length === 1 ? styles.image : styles.multipleImage;
const videosId = videoIdF(props.content); const videosId = videoIdF(props.content);
const hlsUrl = hlsIdF(props.content); const hlsUrl = hlsIdF(props.content);
const iframeSrc = iframeTagF(props.content) || []; const iframeSrc = iframeTagF(props.content) || [];
const youtubeId = youtubeIdF(props.content); const youtubeId = youtubeIdF(props.content);
const [videosFiles, setVideosFiles] = useState([]); const [videosFiles, setVideosFiles] = useState([]);
const [poster, setPoster] = useState(''); const [poster, setPoster] = useState('');
const [loaded, setLoaded] = useState(false); const [loaded, setLoaded] = useState(false);
const navigation = useNavigation(); const navigation = useNavigation();
let interactive = props.interactive || true;
// Fetch video data from API
useEffect(() => { useEffect(() => {
let subscribed = true; let subscribed = true;
let getData = async () => { let getData = async () => {
if (!videosId[1]) return 0; if (!videosId[1]) return;
let videoObj = await API.getVideo(videosId[1]); let videoObj = await API.getVideo(videosId[1]);
if (videoObj && videoObj.files && subscribed) { if (videoObj && videoObj.files && subscribed) {
setVideosFiles(videoObj.files); setVideosFiles(videoObj.files);
@@ -87,69 +100,95 @@ let Media = (props) => {
return () => { return () => {
subscribed = false; subscribed = false;
}; };
}, [props.content]) }, [props.content]);
const video = (videosFiles.length && !props.skiptVideo) ? (
loaded ? <VideoPlayer videosFiles={videosFiles} poster={poster} videoId={videosId[1]} /> : // Render video component
( const renderVideo = () => {
if (videosFiles.length && !props.skiptVideo) {
return loaded ? (
<VideoPlayer videosFiles={videosFiles} poster={poster} videoId={videosId[1]} />
) : (
<TouchableHighlight onPress={() => setLoaded(true)}> <TouchableHighlight onPress={() => setLoaded(true)}>
<Image source={poster ? { uri: poster } : {}} key={poster} style={styles.poster} cachePolicy="memory-disk" /> <Image source={poster ? { uri: poster } : {}} key={poster} style={styles.poster} cachePolicy="memory-disk" />
</TouchableHighlight> </TouchableHighlight>
) );
) : }
(videosId.length ? <VimeoPlayer videoId={videosId[1]} /> : <></>); if (videosId.length) {
const video2 = (hlsUrl && !props.skiptVideo) ? ( return <VimeoPlayer videoId={videosId[1]} />;
loaded ? }
<VideoPlayer videoUrl={hlsUrl} postId={props.postId} /> : return null;
};
// Render HLS video component
const renderHlsVideo = () => {
if (hlsUrl && !props.skiptVideo) {
return loaded ? (
<VideoPlayer videoUrl={hlsUrl} postId={props.postId} />
) : (
<TouchableHighlight onPress={() => { <TouchableHighlight onPress={() => {
//setLoaded(true)
GlobalState.currentMedia = hlsUrl; GlobalState.currentMedia = hlsUrl;
GlobalState.mediaPost = props.post; GlobalState.mediaPost = props.post;
}}> }}>
{poster ? {poster ? (
<Image source={poster ? { uri: poster } : {}} key={poster} style={styles.poster} cachePolicy="memory-disk" /> : <Image source={poster ? { uri: poster } : {}} key={poster} style={styles.poster} cachePolicy="memory-disk" />
) : (
<Button <Button
icon={"subscriptions"} icon={"subscriptions"}
labelStyle={{ fontSize: 58 }} labelStyle={{ fontSize: 58 }}
style={{ flow: 1 }} style={{ flow: 1 }}
></Button> />
} )}
</TouchableHighlight> </TouchableHighlight>
) : <></>; );
const iframe = iframeSrc.length ? }
return null;
};
// Render iframe component
const renderIframe = () => {
if (iframeSrc.length) {
return (
<WebView <WebView
style={styles.iframe} style={styles.iframe}
source={{ uri: iframeSrc[1] }} source={{ uri: iframeSrc[1] }}
/> : <></>; />
const youtubeEmb = youtubeId.length ? );
}
return null;
};
// Render YouTube embed component
const renderYouTubeEmbed = () => {
if (youtubeId.length) {
return (
<WebView <WebView
style={styles.iframe} style={styles.iframe}
source={{ uri: "https://www.youtube.com/embed/" + youtubeId + "?fs=0" }} source={{ uri: "https://www.youtube.com/embed/" + youtubeId + "?fs=0" }}
/> : <></>; />
const renderImages = (({ item, index }) => {
return (
<TouchableWithoutFeedback style={styles.flatlistImages}
onPress={() => {
//alert("hello");
navigation.navigate('Slideshow', { images: imagesTag, startIndex: index });
}}
onLongPress={async () => {
await shareImage(item[1]);
}}>
<Image source={{ uri: item[1] }} style={styles.flatlistImages} cachePolicy="memory-disk" />
</TouchableWithoutFeedback>
); );
}); }
let progress = <></>; return null;
};
// Render progress bar if available
const renderProgressBar = () => {
if (viewer.data && viewer.data[props.postId]) { if (viewer.data && viewer.data[props.postId]) {
const percent = Math.round(viewer.data[props.postId].time / viewer.data[props.postId].duration * 100); const percent = Math.round(viewer.data[props.postId].time / viewer.data[props.postId].duration * 100);
if (percent) if (percent) {
progress = return (
<> <>
<Text>{percent}% {Moment(viewer.data[props.postId].ts).fromNow()}</Text> <Text>{percent}% {Moment(viewer.data[props.postId].ts).fromNow()}</Text>
<ProgressBar progress={viewer.data[props.postId].time / viewer.data[props.postId].duration} /> <ProgressBar progress={viewer.data[props.postId].time / viewer.data[props.postId].duration} />
</>; </>
);
} }
}
return null;
};
// Function to share an image
const shareImage = async (imageUrl) => { const shareImage = async (imageUrl) => {
if (!interactive) return;
try { try {
// Download the image to the device's file system // Download the image to the device's file system
const fileUri = `${FileSystem.cacheDirectory}shared-image.jpg`; const fileUri = `${FileSystem.cacheDirectory}shared-image.jpg`;
@@ -161,64 +200,69 @@ let Media = (props) => {
console.error("Error sharing the image", error); console.error("Error sharing the image", error);
} }
}; };
return (
<View // Function to handle navigation to slideshow
style={{ const navigateToSlideshow = (index) => {
paddingTop: 10, if (!interactive) return;
paddingBottom: 3, navigation.navigate('Slideshow', { images: imagesTag, startIndex: index });
};
// Render images in a FlatList
const renderImages = ({ item, index }) => (
<TouchableWithoutFeedback
style={styles.flatlistImages}
onPress={() => navigateToSlideshow(index)}
onLongPress={async () => {
await shareImage(item[1]);
}} }}
> >
{ <Image source={{ uri: item[1] }} style={styles.flatlistImages} cachePolicy="memory-disk" />
(imagesTag.length > 2) ? </TouchableWithoutFeedback>
);
return (
<View style={{ paddingTop: 10, paddingBottom: 3 }}>
{imagesTag.length > 2 ? (
<FlatList <FlatList
horizontal={true} horizontal
data={imagesTagLimited} data={imagesTagLimited}
renderItem={renderImages} renderItem={renderImages}
keyExtractor={item => item[1]} keyExtractor={(item) => item[1]}
initialNumToRender={2} initialNumToRender={2}
style={{ style={{
transform: [{ transform: [{ scale: 1.1 }],
scale: 1.1
}],
paddingTop: 5, paddingTop: 5,
paddingBottom: 10, paddingBottom: 10,
}} }}
showsHorizontalScrollIndicator={false} showsHorizontalScrollIndicator={false}
/> : />
) : (
<View style={{ flexDirection: "row" }}> <View style={{ flexDirection: "row" }}>
{ {imagesTag.map((image, i) => (
imagesTag.map((image, i) => {
return (
//<Text key={i}>{post.content}</Text>
<TouchableWithoutFeedback <TouchableWithoutFeedback
onPress={() => { key={image[1]}
navigation.navigate('Slideshow', { images: imagesTag, startIndex: i }); onPress={() => navigateToSlideshow(i)}
}}
onLongPress={async () => { onLongPress={async () => {
await shareImage(image[1]); await shareImage(image[1]);
//Share.share({ }}
//message: image[1], >
// url: image[1], <Image source={{ uri: image[1] }} style={imageStyle} cachePolicy="memory-disk" />
//});
}} key={image[1]}>
<Image source={{ uri: image[1] }} key={image[1]} style={imageStyle} cachePolicy="memory-disk" />
</TouchableWithoutFeedback> </TouchableWithoutFeedback>
) ))}
})
}
</View> </View>
} )}
{video} {renderVideo()}
{video2} {renderHlsVideo()}
{iframe} {renderIframe()}
{youtubeEmb} {renderYouTubeEmbed()}
{progress} {renderProgressBar()}
</View> </View>
); );
} };
export default Media; export default Media;
// Styles for different media components
const styles = StyleSheet.create({ const styles = StyleSheet.create({
image: { image: {
width: "100%", width: "100%",