// ReadStoryScreen.js import React, { useEffect, useState… · The Chat Archive
Explore / Programming // ReadStoryScreen.js import React, { useEffect, useState, useRef, useCallback, useMemo… Save Share Download ▾ Report// ReadStoryScreen.js
import React, { useEffect, useState, useRef, useCallback, useMemo } from 'react';
import {
View,
StyleSheet,
Text,
FlatList,
Image,
TouchableOpacity,
ActivityIndicator,
BackHandler
} from 'react-native';
import { Ionicons } from '@expo/vector-icons';
import WordExplanationBox from './WordExplanationBox';
import AsyncStorage from '@react-native-async-storage/async-storage';
import * as Font from 'expo-font';
import { useThemeAndLanguage } from '../utils/ThemeAndLanguageContext';
import {
BottomSheetModal,
BottomSheetModalProvider,
BottomSheetScrollView
} from '@gorhom/bottom-sheet';
import QuizScreen from './QuizScreen';
import { doc, getDoc } from 'firebase/firestore';
import { db } from '../utils/firebase';
import { useFocusEffect } from '@react-navigation/native';
import { useVocabulary } from './VocabularyContext';
import ToggleHeartButton from './heart';
import { CustomTextR, CustomTextB } from '../components/CustomText'; // CustomText bileşenlerini import edin
import DiacriticsToggleButton from '../components/DiacriticsToggleButton'; // DiacriticsToggleButton bileşenini import edin
import { removeDiacritics } from '../utils/arabicUtils'; // Diakritik kaldırma fonksiyonunu import edin
const ARABIC_FONTS = {
'Mirza': require('../../assets/fonts/mirza.ttf'),
'NotoSansArabic': require('../../assets/fonts/NotoSansArabic-Regular.ttf'),
'Amiri': require('../../assets/fonts/amiri.ttf'),
'NotoNaskhArabic': require('../../assets/fonts/noto.ttf'),
};
const STORAGE_KEY = '@user_words';
// Word bileşenini ReadStoryScreen içinde tanımlayarak diacriticsState'e erişimini sağlıyoruz
const ReadStoryScreen = ({ route, navigation }) => {
const { story, storyId } = route.params;
const [fontSize, setFontSize] = useState(20);
const [selectedWord, setSelectedWord] = useState(null);
const [selectedSentence, setSelectedSentence] = useState(null);
const [loading, setLoading] = useState(true);
const [cachedStory, setCachedStory] = useState(null);
const [hasQuiz, setHasQuiz] = useState(false);
const bottomSheetModalRef = useRef(null);
const settingsBottomSheetModalRef = useRef(null);
const quizBottomSheetModalRef = useRef(null);
const { locale, theme, arabicFont, arabicFontBold, setFontFamily, t } = useThemeAndLanguage();
const [activeModal, setActiveModal] = useState(null);
const [knownWords, setKnownWords] = useState(new Set());
const { vocabulary, isLoggedIn, userId } = useVocabulary();
const [diacriticsState, setDiacriticsState] = useState('normal'); // 'normal', 'red', 'hidden'
const increaseFontSize = useCallback(() => setFontSize(prevSize => prevSize + 2), []);
const decreaseFontSize = useCallback(() => setFontSize(prevSize => prevSize - 2), []);
const closeAllModals = useCallback(() => {
bottomSheetModalRef.current?.dismiss();
settingsBottomSheetModalRef.current?.dismiss();
quizBottomSheetModalRef.current?.dismiss();
setActiveModal(null);
}, []);
const openSettingsModal = useCallback(() => {
settingsBottomSheetModalRef.current?.present();
setActiveModal('settings');
}, []);
Assistant2024-11-17 00:18 UTC Copy response
Copy first prompt
Details
Provider OpenAI
Model provenance As recorded by source dataset
Turns 1 (2 messages)
Language tr
Conversation date Nov 17, 2024
Added to archive Nov 16, 2026
ID 01m7h4294gdkgehjy318ezhgffSource & license Imported from WildChat-4.8M (AI2) (source ). Imported records earn no Research Points.
Upstream record: e246a0cbf718f75b63688b72bbddbd54
Zhao et al., WildChat: 1M ChatGPT Interaction Logs in the Wild (ICLR 2024). Contains information from WildChat-4.8M, made available under the ODC Attribution License.
License: ODC-BY-1.0
const openQuizModal = useCallback(() => {
quizBottomSheetModalRef.current?.present();
setActiveModal('quiz');
}, []);
const toggleDiacritics = useCallback(() => {
setDiacriticsState(prevState => {
if (prevState === 'normal') return 'red';
if (prevState === 'red') return 'hidden';
return 'normal';
});
}, []);
const handleWordPress = useCallback((word) => {
setSelectedWord(word); // Her zaman orijinal kelimeyi sakla
setSelectedSentence(null);
bottomSheetModalRef.current?.present();
setActiveModal('word');
}, []);
const handleSentenceButtonPress = useCallback((sentence) => {
setSelectedSentence(sentence);
setSelectedWord(null);
bottomSheetModalRef.current?.present();
setActiveModal('sentence');
}, []);
const loadFonts = useCallback(async () => {
await Font.loadAsync(ARABIC_FONTS);
}, []);
const fetchStoryFromFirestore = useCallback(async (id) => {
const storyDocRef = doc(db, 'stories', id);
const storyDoc = await getDoc(storyDocRef);
return storyDoc.exists() ? { id: storyDoc.id, ...storyDoc.data() } : null;
}, []);
const fetchStory = useCallback(async () => {
try {
let storyData;
if (story) {
storyData = story;
} else if (storyId) {
const cachedData = await AsyncStorage.getItem(story-${storyId});
if (cachedData) {
storyData = JSON.parse(cachedData);
} else {
storyData = await fetchStoryFromFirestore(storyId);
if (storyData) {
await AsyncStorage.setItem(story-${storyId}, JSON.stringify(storyData));
}
}
}
if (storyData) {
setCachedStory(storyData);
setHasQuiz(storyData.test_questions && storyData.test_questions.length > 0);
}
} catch (error) {
console.error('Error fetching story:', error);
} finally {
setLoading(false);
}
}, [story, storyId, fetchStoryFromFirestore]);
const fetchKnownWords = useCallback(async () => {
if (!isLoggedIn) {
setKnownWords(new Set());
return;
}
try {
const cachedWords = await AsyncStorage.getItem(STORAGE_KEY);
if (cachedWords) {
const wordsArray = JSON.parse(cachedWords);
setKnownWords(new Set(wordsArray.map(word => word.word)));
}
} catch (error) {
console.error('Error fetching known words:', error);
}
useEffect(() => {
const initialize = async () => {
await loadFonts();
await fetchStory();
await fetchKnownWords();
};
}, [loadFonts, fetchStory, fetchKnownWords]);
useEffect(() => {
if (cachedStory) {
const storyTitle = locale === 'tr' ? cachedStory.storytitleturkish : cachedStory.storytitleenglish;
navigation.setOptions({
headerTitle: () => (
<View style={{ flex: 1, justifyContent: 'center', alignItems: 'center' }}>
<Text
style={{
color: theme.textColor,
fontWeight: 'bold',
fontSize: 17,
maxWidth: '85%', // Genişlik sınırlaması
textAlign: 'center', // Başlığı ortalıyoruz
}}
numberOfLines={2} // İki satıra kadar yazı yazılmasına izin veriyoruz
ellipsizeMode="tail" // Taşarsa sonuna üç nokta ekle
>
{storyTitle}
</Text>
</View>
),
headerStyle: { backgroundColor: theme.lighterCardBackgroundColor },
headerTintColor: theme.textColor,
headerRight: () => (
<View style={styles.headerRight}>
<ToggleHeartButton storyId={cachedStory.id} initialHeartCount={cachedStory.hearts} />
<DiacriticsToggleButton
diacriticsState={diacriticsState} // Yeni prop eklendi
onToggle={toggleDiacritics} // Yeni toggle işlevi eklendi
color={theme.textColor}
/>
<TouchableOpacity onPress={openSettingsModal} style={styles.fontSizeControl}>
<Ionicons name="text" size={24} color={theme.textColor} />
</TouchableOpacity>
</View>
),
});
}
}, [navigation, cachedStory, theme, locale, openSettingsModal, diacriticsState, toggleDiacritics]);
useFocusEffect(
useCallback(() => {
const onBackPress = () => {
if (activeModal) {
closeAllModals();
return true;
}
return false;
};
BackHandler.addEventListener('hardwareBackPress', onBackPress);
return () => BackHandler.removeEventListener('hardwareBackPress', onBackPress);
}, [activeModal, closeAllModals])
// Group sentences into blocks based on type
const groupSentencesIntoBlocks = useCallback((sentences) => {
const blocks = [];
let currentBlock = [];
sentences.forEach((sentence) => {
if (sentence.type === 'header' || sentence.type === 'subheader' || sentence.type === 'image') {
if (currentBlock.length > 0) {
blocks.push(currentBlock);
currentBlock = [];
}
blocks.push([sentence]);
} else {
currentBlock.push(sentence);
}
});
if (currentBlock.length > 0) {
blocks.push(currentBlock);
}
return blocks;
const Word = React.memo(({ word, onPress, style, isKnown, diacriticsState }) => {
return (
<TouchableOpacity onPress={() => onPress(word)}>
<Text style={[style, isKnown && styles.knownWord]}>
{word.split('').map((char, index) => {
const isDiacritic = removeDiacritics(char) !== char;
if (isDiacritic) {
if (diacriticsState === 'hidden') {
return null;
} else if (diacriticsState === 'red') {
return (
<Text key={index} style={{ color: 'red' }}>
{char}
);
}
}
return char;
})}
);
});
const ContentBlock = React.memo(({
sentences,
handleWordPress,
fontSize,
theme,
arabicFont,
knownWords,
handleSentenceButtonPress,
selectedSentence,
diacriticsState
}) => {
if (sentences.length === 0) return null;
if (sentences[0].type === 'image') {
return (
<Image
source={{ uri: sentences[0].content }}
style={styles.imageStyle}
/>
);
}
if (sentences[0].type === 'header' || sentences[0].type === 'subheader') {
const isHeader = sentences[0].type === 'header';
return (
<View style={[
styles.sentenceContainer,
selectedSentence === sentences[0].content && styles.selectedSentence,
isHeader ? styles.headerContainer : styles.subHeaderContainer,
{
borderRightColor: isHeader ? theme.primaryColor : theme.secondaryColor
}
]}>
<View style={styles.arabicTextWrapper}>
<View style={{
flex: 1,
flexDirection: 'row-reverse',
flexWrap: 'wrap',
justifyContent: 'flex-start',
alignItems: 'center', // Dikeyde ortalar
}}>
{sentences[0].content.split(' ').map((word, wordIndex) => (
<Word
key={`${sentences[0].id}-${wordIndex}`}
word={word}
onPress={handleWordPress}
style={[
styles.descriptionArabic,
{
fontSize: fontSize * (isHeader ? 1.6 : 1.4),
color: theme.textColor,
fontFamily: arabicFont,
}
]}
isKnown={knownWords.has(word)}
diacriticsState={diacriticsState} // Yeni prop eklendi
/>
))}
</View>
<TouchableOpacity
onPress={() => handleSentenceButtonPress(sentences[0].content)}
style={{
padding:3,
alignItems: 'center',
justifyContent: 'center',
}}
>
<Image
source={require('../../assets/translate2.png')}
style={{
width: fontSize * 1.2,
height: fontSize * 1.2,
}}
/>
</TouchableOpacity>
</View>
</View>
);
}
// Normal paragraphs - all sentences in one wrapper
return (
<View style={styles.paragraphContainer}>
<View style={styles.arabicTextWrapper}>
{sentences.map((sentence, sentenceIndex) => (
<React.Fragment key={sentence.id}>
{sentence.content.split(' ').map((word, wordIndex) => (
<Word
key={`${sentence.id}-${wordIndex}`}
word={word}
onPress={handleWordPress}
style={[
styles.descriptionArabic,
{
fontSize: fontSize * 1.4,
color: theme.textColor,
fontFamily: arabicFont,
}
]}
isKnown={knownWords.has(word)}
diacriticsState={diacriticsState} // Yeni prop eklendi
/>
))}
<TouchableOpacity
onPress={() => handleSentenceButtonPress(sentence.content)}
style={{
padding:3,
alignItems: 'center',
justifyContent: 'center'
}}
>
<Image
source={require('../../assets/translate2.png')}
style={{
width: fontSize * 1.2,
height: fontSize * 1.2,
}}
/>
</TouchableOpacity>
{sentenceIndex < sentences.length - 1 && (
<Text style={[
styles.descriptionArabic,
{
fontSize: fontSize * 1.4,
color: theme.textColor,
fontFamily: arabicFont,
}
]}> </Text>
)}
</React.Fragment>
))}
</View>
</View>
);
const renderBlock = useCallback(({ item: sentences }) => (
<ContentBlock
sentences={sentences}
handleWordPress={handleWordPress}
fontSize={fontSize}
theme={theme}
arabicFont={arabicFont}
arabicFontBold={arabicFontBold}
knownWords={knownWords}
handleSentenceButtonPress={handleSentenceButtonPress}
selectedSentence={selectedSentence}
diacriticsState={diacriticsState} // Yeni prop eklendi
/>
), [
handleWordPress,
fontSize,
theme,
arabicFont,
arabicFontBold,
knownWords,
handleSentenceButtonPress,
selectedSentence,
diacriticsState
]);
const memoizedBlocks = useMemo(() => {
if (!cachedStory?.sentences) return [];
return groupSentencesIntoBlocks(cachedStory.sentences);
}, [cachedStory, groupSentencesIntoBlocks]);
const keyExtractor = useCallback((item, index) => block-${index}, []);
useEffect(() => {
const updatedKnownWords = new Set(vocabulary.map(word => word.word));
setKnownWords(updatedKnownWords);
}, [vocabulary]);
if (loading) {
return (
<View style={[styles.loadingContainer, { backgroundColor: theme.backgroundColorForWordBox }]}>
);
}
if (!cachedStory) {
return (
<View style={[styles.loadingContainer, { backgroundColor: theme.backgroundColorForWordBox }]}>
<Text style={{ color: theme.textColor }}>{t('storyNotFound')}
);
}
return (
<View style={[styles.container, { backgroundColor: theme.backgroundColorForWordBox }]}>
<FlatList
data={memoizedBlocks}
renderItem={renderBlock}
keyExtractor={keyExtractor}
ListHeaderComponent={() => (
<>
<Image source={{ uri: cachedStory.thumbnail }} style={styles.thumbnail} />
<Text style={[styles.titleArabic, { color: theme.textColor, fontFamily: arabicFontBold }]}>
{cachedStory.storytitlearabic}
<CustomTextR style={[styles.titleTurkish, { color: theme.secondaryColor }]}>
{locale === 'tr' ? cachedStory.storytitleturkish : cachedStory.storytitleenglish}
</>
)}
initialNumToRender={10}
maxToRenderPerBatch={5}
windowSize={10}
/>
{hasQuiz && (
<TouchableOpacity
style={[styles.quizButton, { backgroundColor: theme.primaryColor }]}
onPress={openQuizModal}
>
<CustomTextR style={styles.quizButtonText}>{t('startQuiz')}</CustomTextR>
</TouchableOpacity>
)}
<BottomSheetModal
ref={bottomSheetModalRef}
index={0}
snapPoints={['45%', '90%']}
handleStyle={{ backgroundColor: theme.backgroundColorForWordBox }}
onDismiss={() => setActiveModal(null)}
>
<BottomSheetScrollView contentContainerStyle={styles.bottomSheetContent}>
<WordExplanationBox
word={selectedWord || selectedSentence}
storyId={cachedStory.id}
onClose={() => bottomSheetModalRef.current?.dismiss()}
/>
</BottomSheetScrollView>
</BottomSheetModal>
<BottomSheetModal
ref={settingsBottomSheetModalRef}
index={0}
snapPoints={['85%']}
handleStyle={{ backgroundColor: theme.backgroundColorForWordBox }}
onDismiss={() => setActiveModal(null)}
>
<BottomSheetScrollView
contentContainerStyle={[
styles.settingsContent,
{ backgroundColor: theme.backgroundColorForWordBox }
]}
>
<View style={styles.exampleCard}>
<Text style={[styles.exampleText, { fontSize: fontSize * 1.4, fontFamily: arabicFont }]}>
(هذا مثال على الكتابة بالعربية)
</Text>
</View>
<View style={styles.fontSizeControls}>
<TouchableOpacity onPress={increaseFontSize} style={styles.fontSizeButton}>
<Ionicons name="add-circle-outline" size={40} color={theme.primaryColor} />
<Text style={styles.fontSizeButtonText}>{t('increaseFontSize')}</Text>
</TouchableOpacity>
<TouchableOpacity onPress={decreaseFontSize} style={styles.fontSizeButton}>
<Ionicons name="remove-circle-outline" size={40} color={theme.primaryColor} />
<Text style={styles.fontSizeButtonText}>{t('decreaseFontSize')}</Text>
</TouchableOpacity>
</View>
<View style={styles.fontOptionsContainer}>
{Object.keys(ARABIC_FONTS).map((font) => (
<TouchableOpacity
key={font}
style={styles.fontOption}
onPress={() => setFontFamily(font)}
>
<Text style={styles.fontOptionText}>{font}</Text>
<Text style={[styles.fontOptionSample, { fontFamily: font }]}>
(اقرأ العربية)
</Text>
</TouchableOpacity>
))}
</View>
</BottomSheetScrollView>
</BottomSheetModal>
{hasQuiz && (
<BottomSheetModal
ref={quizBottomSheetModalRef}
index={0}
snapPoints={['90%']}
handleStyle={{ backgroundColor: theme.backgroundColorForWordBox }}
onDismiss={() => setActiveModal(null)}
>
<QuizScreen
story={cachedStory}
onClose={() => {
quizBottomSheetModalRef.current?.dismiss();
setActiveModal(null);
}}
/>
</BottomSheetModal>
)}
</View>
</BottomSheetModalProvider>
const styles = StyleSheet.create({
container: {
flex: 1,
},
knownWord: {
backgroundColor: 'rgba(0, 255, 0, 0.1)',
borderRadius: 10,
},
loadingContainer: {
flex: 1,
justifyContent: 'center',
alignItems: 'center',
},
thumbnail: {
width: '100%',
aspectRatio: 1/1,
},
content: {
padding: 5,
},
header: {
flexDirection: 'column',
alignItems: 'center',
justifyContent: 'center',
paddingTop:20,
},
titleArabic: {
fontSize: 32,
},
titleTurkish: {
fontSize: 17,
marginTop: 4,
textAlign: 'center',
},
headerRight: {
flexDirection: 'row',
alignItems: 'center',
marginRight: 10,
},
fontSizeControl: {
marginHorizontal: 5,
},
paragraphContainer: {
flexDirection: 'row',
alignItems: 'flex-start',
marginBottom: 10,
},
arabicTextWrapper: {
flex: 1,
flexDirection: 'row-reverse', // Metni sağdan sola yasla
flexWrap: 'wrap',
paddingHorizontal: 25,
justifyContent: 'space-between', // Boşlukları eşit dağıtır
textAlign: 'justify', // Metin içindeki satırları iki yana yaslar
},
descriptionArabic: {
padding: 3,
textAlign: 'justify',
},
selectedSentence: {
backgroundColor: 'rgba(255, 215, 0, 0.3)',
},
settingsContent: {
flexGrow: 1,
paddingBottom: 20,
},
exampleCard: {
backgroundColor: 'white',
borderRadius: 10,
padding: 15,
marginVertical: 20,
width: '90%',
alignItems: 'center',
elevation: 4,
shadowColor: '#000',
shadowOffset: { width: 0, height: 2 },
shadowOpacity: 0.25,
shadowRadius: 3.84,
},
exampleText: {
textAlign: 'center',
},
fontSizeControls: {
flexDirection: 'row',
justifyContent: 'space-around',
width: '100%',
marginBottom: 20,
},
fontSizeButton: {
alignItems: 'center',
},
fontSizeButtonText: {
marginTop: 5,
fontSize: 12,
color: 'gray',
textAlign: 'center',
},
fontOptionsContainer: {
flexDirection: 'row',
flexWrap: 'wrap',
justifyContent: 'space-around',
marginTop: 20,
width: '80%',
alignSelf: 'center',
},
fontOption: {
width: '45%',
backgroundColor: 'white',
borderRadius: 10,
padding: 10,
marginBottom: 20,
alignItems: 'center',
elevation: 4,
shadowColor: '#000',
shadowOffset: { width: 0, height: 1 },
shadowOpacity: 0.22,
shadowRadius: 2.22,
},
fontOptionText: {
fontSize: 16,
marginBottom: 5,
textAlign: 'center',
},
fontOptionSample: {
fontSize: 18,
},
headerContainer: {
marginVertical: 10,
backgroundColor: 'rgba(0, 0, 0, 0.03)',
borderRightWidth: 5,
width: '97%',
},
subHeaderContainer: {
marginVertical: 10,
backgroundColor: 'rgba(0, 0, 0, 0.03)',
borderRightWidth: 3,
width: '97%',
},
imageStyle: {
width: "90%",
alignSelf: "center",
marginBottom: 10,
aspectRatio: 1 / 1,
elevation: 1,
borderRadius: 15,
},
quizButton: {
display: 'flex',
justifyContent: 'center',
alignItems: 'center',
padding: 10,
},
quizButtonText: {
color: 'white',
fontWeight: 'bold',
},
bottomSheetContent: {
flexGrow: 1,
}
});
export default ReadStoryScreen; hacı böyle bir sayfam var. burada belli arapça yazıları çekiyorum ve cümle olarak ve kelime olarak bunların çevirisini kullanıcılarıma sağlıyorum ve benzeri bir çok iş yapıyoruz. şimdi bunu iyi incele, birde bunu da incele:
import React, { useState, useEffect, useCallback, useMemo, useContext } from 'react';
import {
View,
ScrollView,
Text,
StyleSheet,
FlatList,
Image,
RefreshControl,
TouchableOpacity,
Dimensions,
ActivityIndicator
} from 'react-native';
import { collection, getDocs, query, where, doc, getDoc } from 'firebase/firestore';
import AsyncStorage from '@react-native-async-storage/async-storage';
import { db, auth } from '../utils/firebase';
import { useThemeAndLanguage } from '../utils/ThemeAndLanguageContext';
import { useNavigation } from '@react-navigation/native';
import Carousel from 'react-native-reanimated-carousel';
import useInternetStatus from '../utils/useInternetStatus';
import InternetStatusAlert from '../components/InternetStatusAlert';
import { Ionicons } from '@expo/vector-icons';
import { HeartContext } from './HeartContext';
import { CustomTextR, CustomTextB } from '../components/CustomText';
const { width: screenWidth } = Dimensions.get('window');
const NewsTab = () => {
const { theme, t, locale, arabicFont, arabicFontBold } = useThemeAndLanguage();
const [news, setNews] = useState([]);
const [readStories, setReadStories] = useState(new Set());
const [refreshing, setRefreshing] = useState(false);
const [loading, setLoading] = useState(true);
const [error, setError] = useState(null);
const [categories, setCategories] = useState([]);
const [selectedCategory, setSelectedCategory] = useState('All');
const [showInternetAlert, setShowInternetAlert] = useState(false);
const [initialLoad, setInitialLoad] = useState(true);
const navigation = useNavigation();
const { isConnected } = useInternetStatus();
const loadReadStories = useCallback(async () => {
try {
const readStoriesString = await AsyncStorage.getItem('readStories');
if (readStoriesString) {
setReadStories(new Set(JSON.parse(readStoriesString)));
}
} catch (error) {
console.error('Error loading read stories:', error);
}
}, []);
const markStoryAsRead = useCallback(async (storyId) => {
try {
const newReadStories = new Set(readStories);
newReadStories.add(storyId);
setReadStories(newReadStories);
await AsyncStorage.setItem('readStories', JSON.stringify(Array.from(newReadStories)));
} catch (error) {
console.error('Error saving read story:', error);
}
}, [readStories]);
const handleStoryPress = useCallback((story) => {
markStoryAsRead(story.id);
navigation.navigate('ReadStoryScreen', { story });
}, [navigation, markStoryAsRead]);
const categoryField = useMemo(() => locale === 'tr' ? 'categoryturkish' : 'categoryenglish', [locale]);
const loadCachedData = useCallback(async () => {
const cachedNews = await AsyncStorage.getItem('news');
if (cachedNews) {
const parsedNews = JSON.parse(cachedNews);
const newsWithDates = parsedNews.map(item => ({
...item,
formattedDate: item.formattedDate ? new Date(item.formattedDate) : null
}));
setNews(newsWithDates);
updateCategories(newsWithDates);
}
}, [updateCategories]);
const updateCategories = useCallback((newsData) => {
const categoriesSet = new Set(newsData.map(item => item[categoryField]));
setCategories(['All', ...Array.from(categoriesSet)]);
}, [categoryField]);
const getTimeAgo = useCallback((dateString) => {
if (!dateString) {
return t('noDate');
}
const date = new Date(dateString);
if (isNaN(date.getTime())) {
return t('invalidDate');
}
const now = new Date();
const diffInSeconds = Math.floor((now - date) / 1000);
if (diffInSeconds < 60) return t('justNow');
if (diffInSeconds < 3600) return `${Math.floor(diffInSeconds / 60)} ${t('minutesAgo')}`;
if (diffInSeconds < 86400) return `${Math.floor(diffInSeconds / 3600)} ${t('hoursAgo')}`;
if (diffInSeconds < 2592000) return `${Math.floor(diffInSeconds / 86400)} ${t('daysAgo')}`;
if (diffInSeconds < 31536000) return `${Math.floor(diffInSeconds / 2592000)} ${t('monthsAgo')}`;
return `${Math.floor(diffInSeconds / 31536000)} ${t('yearsAgo')}`;
const fetchNews = useCallback(async () => {
if (!isConnected) {
setError(t('noInternetError'));
return;
}
setError(null);
setLoading(true);
try {
const storiesCollection = collection(db, 'stories');
const newsQuery = query(storiesCollection, where("news", "==", 1));
const newsSnapshot = await getDocs(newsQuery);
const newsData = newsSnapshot.docs.map(doc => {
const data = doc.data();
return {
id: doc.id,
...data,
formattedDate: data.date ? new Date(data.date).toISOString() : null,
hearts: data.hearts || 0
};
});
// Sort news: unread first, then randomly within each group
const sortedNewsData = newsData.sort((a, b) => {
const aRead = readStories.has(a.id);
const bRead = readStories.has(b.id);
if (aRead === bRead) {
return Math.random() - 0.5; // Random sorting within same read status
}
return aRead ? 1 : -1; // Unread stories first
});
await AsyncStorage.setItem('news', JSON.stringify(sortedNewsData));
await AsyncStorage.setItem('lastNewsFetch', new Date().toISOString().split('T')[0]);
setNews(sortedNewsData);
updateCategories(sortedNewsData);
} catch (error) {
console.error('Error fetching news:', error);
setError(t('fetchNewsError'));
await loadCachedData();
} finally {
setLoading(false);
setInitialLoad(false);
}
}, [updateCategories, isConnected, t, loadCachedData, readStories]);
const { heartsCounts, userHearts } = useContext(HeartContext);
useEffect(() => {
loadReadStories();
}, [loadReadStories]);
useEffect(() => {
setNews(prevNews =>
prevNews.map(story => ({
...story,
hearts: heartsCounts[story.id] !== undefined ? heartsCounts[story.id] : story.hearts
}))
);
}, [heartsCounts]);
useEffect(() => {
const loadData = async () => {
const lastFetch = await AsyncStorage.getItem('lastNewsFetch');
const currentDate = new Date().toISOString().split('T')[0];
if (lastFetch === currentDate) {
await loadCachedData();
setLoading(false);
} else {
if (isConnected) {
await fetchNews();
} else {
await loadCachedData();
setLoading(false);
}
}
};
loadData();
}, [isConnected, loadCachedData, fetchNews]);
useEffect(() => {
if (!isConnected && !initialLoad) {
setShowInternetAlert(true);
} else {
setShowInternetAlert(false);
}
}, [isConnected, initialLoad]);
const onRefresh = useCallback(async () => {
if (!isConnected) {
setShowInternetAlert(true);
return;
}
setRefreshing(true);
await fetchNews();
setRefreshing(false);
}, [fetchNews, isConnected]);
const renderCategoryItem = useCallback((item) => (
<TouchableOpacity
key={item}
style={[
styles.categoryLabel,
selectedCategory === item && { backgroundColor: theme.primaryColor }
]}
onPress={() => setSelectedCategory(item)}
>
<CustomTextB style={[
styles.categoryText,
selectedCategory === item && { color: theme.backgroundColor }
]}>
{item === 'All' ? t('all') : item}
), [selectedCategory, theme, t]);
const renderCarouselItem = useCallback(({ item }) => (
<TouchableOpacity
style={styles.carouselItem}
onPress={() => handleStoryPress(item)}
>
<Image
source={{ uri: item.thumbnail }}
style={[
styles.carouselThumbnail,
readStories.has(item.id) && styles.readStoryImage
]}
/>
<Text style={[styles.carouselTitleArabic, { fontFamily: arabicFontBold }]}>
{item.storytitlearabic}
{item[storytitle${locale === 'tr' ? 'turkish' : 'english'}]}
), [handleStoryPress, locale, arabicFontBold, readStories]);
const renderRegularNews = useCallback(({ item }) => {
const isHearted = !!userHearts[item.id];
const heartCount = heartsCounts[item.id] || item.hearts;
const isRead = readStories.has(item.id);
return (
<TouchableOpacity
style={[styles.regularNewsItem, { backgroundColor: theme.lighterCardBackgroundColor }]}
onPress={() => handleStoryPress(item)}
>
<Image
source={{ uri: item.thumbnail }}
style={[
styles.thumbnail,
isRead && styles.readStoryImage
]}
resizeMode="cover"
/>
<View style={styles.regularTextContainer}>
<Text style={[styles.regularTitleArabic, { color: theme.textColor, fontFamily: arabicFontBold }]}>
{item.storytitlearabic}
</Text>
<CustomTextR style={[styles.regularTitleTurkish, { color: theme.textColor, textAlign:'center' }]}>
{item[`storytitle${locale === 'tr' ? 'turkish' : 'english'}`]}
</CustomTextR>
<View style={styles.infoContainer}>
<CustomTextB style={[styles.infoText, { color: theme.textColor, borderColor: theme.textColor }]}>
{item[categoryField]}
</CustomTextB>
<CustomTextB style={[styles.infoText, { color: theme.textColor, borderColor: theme.textColor }]}>
{item.langlevel}
</CustomTextB>
<CustomTextB style={[styles.infoText, { color: theme.textColor, borderColor: theme.textColor }]}>
{getTimeAgo(item.formattedDate)}
</CustomTextB>
<View style={[styles.infoText, { color: theme.textColor, borderColor: theme.textColor }]}>
<Ionicons
name={isHearted ? 'heart' : 'heart-outline'}
color={isHearted ? 'red' : theme.textColor}
size={8}
/>
<CustomTextB style={[styles.heartCount, { color: theme.textColor, marginLeft: 4 }]}>
{heartCount}
</CustomTextB>
</View>
</View>
</View>
</TouchableOpacity>
);
}, [theme, categoryField, locale, arabicFontBold, handleStoryPress, getTimeAgo, userHearts, heartsCounts, readStories]);
const filteredNews = useMemo(() =>
news.filter(item => selectedCategory === 'All' || item[categoryField] === selectedCategory),
[news, selectedCategory, categoryField]
);
const carouselData = useMemo(() => news.slice(0, 4), [news]);
const regularNewsData = useMemo(() =>
selectedCategory === 'All' ? filteredNews.slice(4) : filteredNews,
[selectedCategory, filteredNews]
);
const ListHeaderComponent = useCallback(() => (
<>
{error && <Text style={[styles.errorText, { color: theme.errorColor }]}>{error}}
{selectedCategory === 'All' && (
<Carousel
style={[styles.carousel, { aspectRatio: 3 / 2 }]}
width={screenWidth}
data={carouselData}
renderItem={renderCarouselItem}
loop
autoPlay
autoPlayInterval={5000}
mode="parallax"
modeConfig={{
parallaxScrollingScale: 0.9,
parallaxScrollingOffset: 50,
}}
/>
)}
{categories.map(renderCategoryItem)}
</>
), [error, selectedCategory, carouselData, renderCarouselItem, categories, renderCategoryItem, theme.errorColor]);
if (loading) {
return (
<View style={[styles.loadingContainer, { backgroundColor: theme.backgroundColor }]}>
);
}
return (
<View style={[styles.container, { backgroundColor: theme.backgroundColor }]}>
<InternetStatusAlert
visible={showInternetAlert}
onDismiss={() => setShowInternetAlert(false)}
/>
<FlatList
data={regularNewsData}
keyExtractor={item => item.id}
renderItem={renderRegularNews}
ListHeaderComponent={ListHeaderComponent}
refreshControl={
}
initialNumToRender={5}
maxToRenderPerBatch={5}
windowSize={11}
/>
);
};
const styles = StyleSheet.create({
container: {
flex: 1,
},
loadingContainer: {
flex: 1,
justifyContent: 'center',
alignItems: 'center',
},
readStoryImage: {
opacity: 0.5,
filter: 'grayscale(100%)',
},
errorText: {
textAlign: 'center',
marginTop: 10,
marginBottom: 10,
},
categoryContainer: {
flexDirection: 'row',
flexWrap: 'wrap',
justifyContent: 'center',
marginVertical: 5,
},
categoryLabel: {
backgroundColor: 'white',
borderRadius: 7,
paddingVertical: 2,
paddingHorizontal: 2,
marginHorizontal: 3,
marginBottom: 5,
shadowColor: '#000',
shadowOffset: { width: 0, height: 2 },
shadowOpacity: 0.1,
shadowRadius: 2,
elevation: 2,
},
categoryText: {
fontSize: 11,
padding: 6,
textTransform: 'uppercase',
},
carousel: {
aspectRatio: 3 / 2,
width: "100%",
},
carouselItem: {
flex: 1,
justifyContent: 'center',
alignItems: 'center',
borderRadius: 10,
overflow: 'hidden',
},
carouselThumbnail: {
width: '100%',
height: '100%',
resizeMode: 'cover',
},
carouselTitleContainer: {
position: 'absolute',
bottom: 10,
left: 10,
right: 10,
padding: 5,
backgroundColor: 'rgba(255, 255, 255, 0.8)',
borderRadius: 10,
},
carouselTitleArabic: {
fontSize: 22,
textAlign: 'center',
color: '#000',
},
carouselTitleTurkish: {
fontSize: 16,
marginTop: 5,
textAlign: 'center',
color: '#000',
},
regularNewsItem: {
flexDirection: 'row',
marginBottom: 10,
borderRadius: 10,
overflow: 'hidden',
elevation: 3,
marginHorizontal: 10,
},
thumbnail: {
width: '40%',
height: '100%',
resizeMode: 'center',
},
regularTextContainer: {
padding: 10,
flex: 1,
justifyContent: 'space-between',
},
regularTitleArabic: {
fontSize: 22,
textAlign: 'center',
},
regularTitleTurkish: {
fontSize: 15,
},
infoContainer: {
paddingTop: 10,
flexDirection: 'row',
flexWrap: 'wrap',
justifyContent: 'center',
alignItems: 'center',
},
infoText: {
fontSize: 8,
textAlign: 'center',
marginRight: 4,
marginBottom: 2,
paddingVertical: 4,
paddingHorizontal: 5,
borderWidth:0.3,
borderRadius: 4,
backgroundColor: 'transparent',
textTransform: 'uppercase',
fontWeight: 'bold',
flexDirection: 'row',
},
heartCount: {
fontSize: 8,
fontWeight: 'bold',
},
});
export default React.memo(NewsTab);
mesela diyorum ki, bu newstab gibi rsstab oluşturayım ve örneğin https://www.dostor.org/rss.aspx adresindeki rss bilgilerini çekelim ve readstoryscreende yaptığımız gibi haberleri kullanıcıların okumasını sağlayalım ve dil öğrenmek için bunların çevirilerini aynı şekilde kelime ve cümle bazında görebilmelerini sağlayalım. örneğin bu bahsettiğim sitedeki rss kaynağı böyle devam ediyor:
buradaki bilgileri çekelim ve rssreadscreen oluşturalım. burada da bu haberleri tek tek göstertelim. daha kolay olur dersen webview kullanarak da bunları yapabilirsin.
Creating an RSSTab similar to your existing NewsTab involves several steps, including fetching and parsing RSS feeds, displaying the news items, and integrating translation features similar to your ReadStoryScreen. Below is a comprehensive guide to help you implement this functionality in your React Native application.
Overview of Steps
Install Necessary Libraries
Create the RSSTab Component
Create the RSSReadScreen Component
Integrate Navigation
Handle Caching and Offline Support
Enhance User Experience with Translations
Let's go through each step in detail.
1. Install Necessary Libraries
To parse RSS feeds effectively, it's recommended to use a dedicated library. We'll use react-native-rss-parser for parsing RSS feeds.
Install Dependencies
npm install react-native-rss-parser
# or
yarn add react-native-rss-parser
Additionally, ensure you have the following dependencies installed, which you likely already have based on your provided code:
react-native-async-storage/async-storage
@react-navigation/native
@gorhom/bottom-sheet
Any other dependencies your project currently uses.
2. Create the RSSTab Component
This component will fetch the RSS feed, parse it, display the news items in a list, and handle user interactions.
RSSTab.js
// RSSTab.js
import React, { useState, useEffect, useCallback, useMemo, useContext } from 'react';
import {
View,
Text,
StyleSheet,
FlatList,
Image,
TouchableOpacity,
ActivityIndicator,
RefreshControl,
} from 'react-native';
import { useThemeAndLanguage } from '../utils/ThemeAndLanguageContext';
import { useNavigation } from '@react-navigation/native';
import * as rssParser from 'react-native-rss-parser';
import AsyncStorage from '@react-native-async-storage/async-storage';
import { Ionicons } from '@expo/vector-icons';
import { CustomTextR, CustomTextB } from '../components/CustomText';
import { HeartContext } from './HeartContext'; // Assuming you have a HeartContext similar to NewsTab
import useInternetStatus from '../utils/useInternetStatus';
import InternetStatusAlert from '../components/InternetStatusAlert';
const RSS_URL = 'https://www.dostor.org/rss.aspx';
const STORAGE_KEY = '@rss_news';
const RSSTab = () => {
const { theme, t, locale } = useThemeAndLanguage();
const [rssItems, setRssItems] = useState([]);
const [loading, setLoading] = useState(true);
const [refreshing, setRefreshing] = useState(false);
const [error, setError] = useState(null);
const [readStories, setReadStories] = useState(new Set());
const [showInternetAlert, setShowInternetAlert] = useState(false);
const { isConnected } = useInternetStatus();
const navigation = useNavigation();
const { heartsCounts, userHearts } = useContext(HeartContext);
// Load read stories from AsyncStorage
const loadReadStories = useCallback(async () => {
try {
const readStoriesString = await AsyncStorage.getItem('readRSSStories');
if (readStoriesString) {
setReadStories(new Set(JSON.parse(readStoriesString)));
}
} catch (err) {
console.error('Error loading read RSS stories:', err);
}
}, []);
// Mark story as read
const markStoryAsRead = useCallback(async (storyId) => {
try {
const newReadStories = new Set(readStories);
newReadStories.add(storyId);
setReadStories(newReadStories);
await AsyncStorage.setItem('readRSSStories', JSON.stringify(Array.from(newReadStories)));
} catch (err) {
console.error('Error saving read RSS story:', err);
}
}, [readStories]);
// Handle story press
const handleStoryPress = useCallback((item) => {
markStoryAsRead(item.id);
navigation.navigate('RSSReadScreen', { item });
}, [navigation, markStoryAsRead]);
// Fetch and parse RSS feed
const fetchRSS = useCallback(async () => {
if (!isConnected) {
setError(t('noInternetError'));
setLoading(false);
return;
}
setError(null);
setLoading(true);
try {
const response = await fetch(RSS_URL);
const responseData = await response.text();
const parsed = await rssParser.parse(responseData);
const items = parsed.items.map(item => ({
id: item.id || item.link, // Use link as a fallback ID
title: item.title,
description: item.description,
content: item.content,
link: item.links[0]?.url || item.link,
pubDate: item.published || item.updated,
image: item.image?.url || (item.enclosure && item.enclosure.url) || null,
}));
setRssItems(items);
await AsyncStorage.setItem(STORAGE_KEY, JSON.stringify(items));
} catch (err) {
console.error('Error fetching RSS feed:', err);
setError(t('fetchRSSError'));
// Attempt to load cached data
const cachedRSS = await AsyncStorage.getItem(STORAGE_KEY);
if (cachedRSS) {
setRssItems(JSON.parse(cachedRSS));
}
} finally {
setLoading(false);
}
}, [isConnected, t]);
// Load cached RSS data
const loadCachedData = useCallback(async () => {
try {
const cachedRSS = await AsyncStorage.getItem(STORAGE_KEY);
if (cachedRSS) {
setRssItems(JSON.parse(cachedRSS));
}
} catch (err) {
console.error('Error loading cached RSS:', err);
}
}, []);
// Initial load
useEffect(() => {
const loadData = async () => {
await loadReadStories();
const lastFetch = await AsyncStorage.getItem('lastRSSFetch');
const currentDate = new Date().toISOString().split('T')[0];
if (lastFetch === currentDate) {
await loadCachedData();
setLoading(false);
} else {
if (isConnected) {
await fetchRSS();
await AsyncStorage.setItem('lastRSSFetch', currentDate);
} else {
await loadCachedData();
setLoading(false);
}
}
};
loadData();
}, [fetchRSS, isConnected, loadCachedData, loadReadStories]);
// Refresh handler
const onRefresh = useCallback(async () => {
if (!isConnected) {
setShowInternetAlert(true);
return;
}
setRefreshing(true);
await fetchRSS();
setRefreshing(false);
}, [fetchRSS, isConnected]);
// Update RSS items when heart counts change
useEffect(() => {
// If you have heart counts specific to RSS items, update them here
// For simplicity, assuming heartsCounts covers RSS items as well
setRssItems(prevItems =>
prevItems.map(item => ({
...item,
hearts: heartsCounts[item.id] !== undefined ? heartsCounts[item.id] : 0,
}))
);
}, [heartsCounts]);
// Show Internet Alert if not connected
useEffect(() => {
if (!isConnected) {
setShowInternetAlert(true);
} else {
setShowInternetAlert(false);
}
}, [isConnected]);
// Render individual RSS item
const renderRSSItem = useCallback(({ item }) => {
const isHearted = !!userHearts[item.id];
const heartCount = item.hearts || 0;
const isRead = readStories.has(item.id);
return (
<TouchableOpacity
style={[styles.itemContainer, { backgroundColor: theme.lighterCardBackgroundColor }]}
onPress={() => handleStoryPress(item)}
>
{item.image ? (
<Image
source={{ uri: item.image }}
style={[
styles.thumbnail,
isRead && styles.readStoryImage
]}
resizeMode="cover"
/>
) : (
<View style={[styles.thumbnail, styles.noImage]}>
<Ionicons name="image-outline" size={40} color="gray" />
</View>
)}
<View style={styles.textContainer}>
<Text style={[styles.titleArabic, { color: theme.textColor, fontFamily: 'NotoSansArabic' }]}>
{item.title}
</Text>
<CustomTextR style={[styles.titleDescription, { color: theme.textColor }]}>
{item.description ? item.description.replace(/<[^>]+>/g, '').substring(0, 100) + '...' : ''}
</CustomTextR>
<View style={styles.infoContainer}>
<CustomTextB style={[styles.infoText, { color: theme.textColor, borderColor: theme.textColor }]}>
{new Date(item.pubDate).toLocaleDateString(locale)}
</CustomTextB>
<TouchableOpacity style={styles.heartContainer}>
<Ionicons
name={isHearted ? 'heart' : 'heart-outline'}
color={isHearted ? 'red' : theme.textColor}
size={16}
/>
<CustomTextB style={[styles.heartCount, { color: theme.textColor, marginLeft: 4 }]}>
{heartCount}
</CustomTextB>
</TouchableOpacity>
</View>
</View>
</TouchableOpacity>
);
}, [handleStoryPress, theme, readStories, userHearts]);
if (loading) {
return (
<View style={[styles.loadingContainer, { backgroundColor: theme.backgroundColor }]}>
<ActivityIndicator size="large" color={theme.primaryColor} />
</View>
);
}
return (
<View style={[styles.container, { backgroundColor: theme.backgroundColor }]}>
<InternetStatusAlert
visible={showInternetAlert}
onDismiss={() => setShowInternetAlert(false)}
/>
{error && <Text style={[styles.errorText, { color: theme.errorColor }]}>{error}</Text>}
<FlatList
data={rssItems}
keyExtractor={item => item.id}
renderItem={renderRSSItem}
refreshControl={
<RefreshControl
refreshing={refreshing}
onRefresh={onRefresh}
colors={[theme.primaryColor]}
/>
}
initialNumToRender={5}
maxToRenderPerBatch={5}
windowSize={11}
/>
</View>
);
};
const styles = StyleSheet.create({
container: {
flex: 1,
},
loadingContainer: {
flex: 1,
justifyContent: 'center',
alignItems: 'center',
},
errorText: {
textAlign: 'center',
margin: 10,
},
itemContainer: {
flexDirection: 'row',
margin: 10,
borderRadius: 10,
overflow: 'hidden',
elevation: 2,
},
thumbnail: {
width: 100,
height: 100,
},
noImage: {
justifyContent: 'center',
alignItems: 'center',
backgroundColor: '#ccc',
},
readStoryImage: {
opacity: 0.5,
},
textContainer: {
flex: 1,
padding: 10,
justifyContent: 'space-between',
},
titleArabic: {
fontSize: 16,
fontWeight: 'bold',
},
titleDescription: {
fontSize: 12,
},
infoContainer: {
flexDirection: 'row',
justifyContent: 'space-between',
alignItems: 'center',
},
infoText: {
fontSize: 10,
borderWidth: 0.5,
borderRadius: 4,
padding: 2,
textAlign: 'center',
},
heartContainer: {
flexDirection: 'row',
alignItems: 'center',
},
heartCount: {
fontSize: 10,
fontWeight: 'bold',
},
});
export default RSSTab;
Explanation
Fetching RSS Feed : The fetchRSS function fetches the RSS XML from the provided URL, parses it using react-native-rss-parser, and updates the state.
Caching : RSS items are cached using AsyncStorage to allow offline access.
Read Stories : Similar to NewsTab, read stories are tracked using AsyncStorage.
Display : RSS items are displayed in a FlatList with thumbnails, titles, descriptions, publication dates, and heart icons.
Error Handling : Errors during fetching are handled gracefully, displaying error messages and attempting to load cached data.
3. Create the RSSReadScreen Component
This screen displays the full content of an RSS item and allows users to interact with words and sentences for translations, similar to your ReadStoryScreen.
RSSReadScreen.js
// RSSReadScreen.js
import React, { useEffect, useState, useRef, useCallback, useMemo } from 'react';
import {
View,
StyleSheet,
Text,
ScrollView,
Image,
TouchableOpacity,
ActivityIndicator,
BackHandler
} from 'react-native';
import { Ionicons } from '@expo/vector-icons';
import WordExplanationBox from './WordExplanationBox'; // Reuse your existing component
import AsyncStorage from '@react-native-async-storage/async-storage';
import * as Font from 'expo-font';
import { useThemeAndLanguage } from '../utils/ThemeAndLanguageContext';
import {
BottomSheetModal,
BottomSheetModalProvider,
BottomSheetScrollView
} from '@gorhom/bottom-sheet';
import { useFocusEffect } from '@react-navigation/native';
import { useVocabulary } from './VocabularyContext';
import ToggleHeartButton from './heart';
import { CustomTextR, CustomTextB } from '../components/CustomText';
import DiacriticsToggleButton from '../components/DiacriticsToggleButton';
import { removeDiacritics } from '../utils/arabicUtils';
const ARABIC_FONTS = {
'Mirza': require('../../assets/fonts/mirza.ttf'),
'NotoSansArabic': require('../../assets/fonts/NotoSansArabic-Regular.ttf'),
'Amiri': require('../../assets/fonts/amiri.ttf'),
'NotoNaskhArabic': require('../../assets/fonts/noto.ttf'),
};
const STORAGE_KEY = '@user_words';
const RSSReadScreen = ({ route, navigation }) => {
const { item } = route.params; // RSS item
const [fontSize, setFontSize] = useState(20);
const [selectedWord, setSelectedWord] = useState(null);
const [loading, setLoading] = useState(true);
const [hasContent, setHasContent] = useState(false);
const bottomSheetModalRef = useRef(null);
const { locale, theme, arabicFont, arabicFontBold, setFontFamily, t } = useThemeAndLanguage();
const [activeModal, setActiveModal] = useState(null);
const [knownWords, setKnownWords] = useState(new Set());
const { vocabulary, isLoggedIn, userId } = useVocabulary();
const [diacriticsState, setDiacriticsState] = useState('normal'); // 'normal', 'red', 'hidden'
const loadFonts = useCallback(async () => {
await Font.loadAsync(ARABIC_FONTS);
}, []);
const fetchKnownWords = useCallback(async () => {
if (!isLoggedIn) {
setKnownWords(new Set());
return;
}
try {
const cachedWords = await AsyncStorage.getItem(STORAGE_KEY);
if (cachedWords) {
const wordsArray = JSON.parse(cachedWords);
setKnownWords(new Set(wordsArray.map(word => word.word)));
}
} catch (error) {
console.error('Error fetching known words:', error);
}
}, [isLoggedIn]);
useEffect(() => {
const initialize = async () => {
await loadFonts();
await fetchKnownWords();
setLoading(false);
};
initialize();
}, [loadFonts, fetchKnownWords]);
useFocusEffect(
useCallback(() => {
const onBackPress = () => {
if (activeModal) {
bottomSheetModalRef.current?.dismiss();
setActiveModal(null);
return true;
}
return false;
};
BackHandler.addEventListener('hardwareBackPress', onBackPress);
return () => BackHandler.removeEventListener('hardwareBackPress', onBackPress);
}, [activeModal])
);
const toggleDiacritics = useCallback(() => {
setDiacriticsState(prevState => {
if (prevState === 'normal') return 'red';
if (prevState === 'red') return 'hidden';
return 'normal';
});
}, []);
const handleWordPress = useCallback((word) => {
setSelectedWord(word);
bottomSheetModalRef.current?.present();
setActiveModal('word');
}, []);
// Split content into words for display and interaction
const formattedContent = useMemo(() => {
if (!item.content) return '';
// Remove HTML tags
const plainText = item.content.replace(/<[^>]+>/g, '');
return plainText;
}, [item.content]);
// Word component
const Word = React.memo(({ word, onPress, style, isKnown, diacriticsState }) => {
return (
<TouchableOpacity onPress={() => onPress(word)}>
<Text style={[style, isKnown && styles.knownWord]}>
{word.split('').map((char, index) => {
const isDiacritic = removeDiacritics(char) !== char;
if (isDiacritic) {
if (diacriticsState === 'hidden') {
return null;
} else if (diacriticsState === 'red') {
return (
<Text key={index} style={{ color: 'red' }}>
{char}
</Text>
);
}
}
return char;
})}
</Text>
</TouchableOpacity>
);
});
// Render content with word interactions
const renderContent = useCallback(() => {
return formattedContent.split(' ').map((word, index) => (
<Word
key={`${index}-${word}`}
word={word}
onPress={handleWordPress}
style={[
styles.contentText,
{
fontSize: fontSize,
color: theme.textColor,
fontFamily: arabicFont,
}
]}
isKnown={knownWords.has(word)}
diacriticsState={diacriticsState}
/>
));
}, [formattedContent, handleWordPress, fontSize, theme, arabicFont, knownWords, diacriticsState]);
if (loading) {
return (
<View style={[styles.loadingContainer, { backgroundColor: theme.backgroundColorForWordBox }]}>
<ActivityIndicator size="large" color={theme.primaryColor} />
</View>
);
}
return (
<BottomSheetModalProvider>
<View style={[styles.container, { backgroundColor: theme.backgroundColorForWordBox }]}>
<ScrollView contentContainerStyle={styles.scrollContent}>
{item.image && (
<Image
source={{ uri: item.image }}
style={styles.imageStyle}
resizeMode="cover"
/>
)}
<View style={styles.header}>
<Text style={[styles.titleArabic, { color: theme.textColor, fontFamily: arabicFontBold }]}>
{item.title}
</Text>
<CustomTextR style={[styles.titleDescription, { color: theme.secondaryColor }]}>
{new Date(item.pubDate).toLocaleDateString(locale)}
</CustomTextR>
</View>
<View style={styles.content}>
{renderContent()}
</View>
</ScrollView>
<View style={styles.headerRight}>
<ToggleHeartButton storyId={item.id} initialHeartCount={item.hearts} />
<DiacriticsToggleButton
diacriticsState={diacriticsState}
onToggle={toggleDiacritics}
color={theme.textColor}
/>
<TouchableOpacity onPress={() => { /* Add font size controls if needed */ }} style={styles.fontSizeControl}>
<Ionicons name="text" size={24} color={theme.textColor} />
</TouchableOpacity>
</View>
<BottomSheetModal
ref={bottomSheetModalRef}
index={0}
snapPoints={['45%', '90%']}
handleStyle={{ backgroundColor: theme.backgroundColorForWordBox }}
onDismiss={() => setActiveModal(null)}
>
<BottomSheetScrollView contentContainerStyle={styles.bottomSheetContent}>
<WordExplanationBox
word={selectedWord}
storyId={item.id}
onClose={() => bottomSheetModalRef.current?.dismiss()}
/>
</BottomSheetScrollView>
</BottomSheetModal>
</View>
</BottomSheetModalProvider>
);
};
const styles = StyleSheet.create({
container: {
flex: 1,
},
scrollContent: {
padding: 10,
},
loadingContainer: {
flex: 1,
justifyContent: 'center',
alignItems: 'center',
},
imageStyle: {
width: '100%',
height: 200,
borderRadius: 10,
marginBottom: 10,
},
header: {
marginBottom: 10,
},
titleArabic: {
fontSize: 24,
textAlign: 'center',
},
titleDescription: {
fontSize: 14,
textAlign: 'center',
marginTop: 5,
},
content: {
flexDirection: 'row',
flexWrap: 'wrap',
justifyContent: 'flex-start',
alignItems: 'center',
},
contentText: {
padding: 2,
textAlign: 'justify',
},
knownWord: {
backgroundColor: 'rgba(0, 255, 0, 0.1)',
borderRadius: 5,
},
headerRight: {
position: 'absolute',
top: 10,
right: 10,
flexDirection: 'row',
alignItems: 'center',
},
fontSizeControl: {
marginHorizontal: 5,
},
bottomSheetContent: {
flexGrow: 1,
},
});
export default RSSReadScreen;
Explanation
Displaying Content : The RSSReadScreen takes an RSS item as a parameter and displays its title, image, publication date, and content. The content is split into words, and each word is interactive, allowing users to tap and view translations or explanations.
Word Interactions : The Word component handles the display of individual words, managing diacritics based on user preferences.
Heart Functionality : Users can heart the RSS items similarly to how they interact with news items in NewsTab.
Bottom Sheet : Reuses the WordExplanationBox component to show explanations or translations of selected words.
4. Integrate Navigation
Ensure that your navigation setup includes the new RSSTab and RSSReadScreen. Assuming you are using React Navigation, update your navigator accordingly.
Example: AppNavigator.js
// AppNavigator.js
import React from 'react';
import { createBottomTabNavigator } from '@react-navigation/bottom-tabs';
import NewsTab from './NewsTab';
import RSSTab from './RSSTab'; // Import RSSTab
import { Ionicons } from '@expo/vector-icons';
const Tab = createBottomTabNavigator();
const AppNavigator = () => {
return (
<Tab.Navigator
screenOptions={({ route }) => ({
tabBarIcon: ({ color, size }) => {
let iconName;
if (route.name === 'News') {
iconName = 'newspaper-outline';
} else if (route.name === 'RSS') {
iconName = 'rss-outline';
}
return <Ionicons name={iconName} size={size} color={color} />;
},
})}
>
<Tab.Screen name="News" component={NewsTab} />
<Tab.Screen name="RSS" component={RSSTab} /> {/* Add RSSTab */}
</Tab.Navigator>
);
};
export default AppNavigator;
Example: StackNavigator.js
Add the RSSReadScreen to your stack navigator.
// StackNavigator.js
import React from 'react';
import { createStackNavigator } from '@react-navigation/stack';
import ReadStoryScreen from './ReadStoryScreen';
import RSSReadScreen from './RSSReadScreen'; // Import RSSReadScreen
// Import other screens as needed
const Stack = createStackNavigator();
const StackNavigator = () => {
return (
<Stack.Navigator>
{/* Your existing screens */}
<Stack.Screen name="ReadStoryScreen" component={ReadStoryScreen} />
<Stack.Screen name="RSSReadScreen" component={RSSReadScreen} /> {/* Add RSSReadScreen */}
</Stack.Navigator>
);
};
export default StackNavigator;
5. Handle Caching and Offline Support
The provided RSSTab component already includes caching using AsyncStorage. It attempts to load cached data when offline and caches fresh data when online. This ensures users can access RSS content even without an internet connection.
6. Enhance User Experience with Translations
To provide word and sentence-level translations in RSSReadScreen, you can leverage the existing WordExplanationBox component or enhance it further. Here's how you can integrate it effectively:
Word Explanation : When a user taps on a word, the WordExplanationBox can display the translation, definition, or any other relevant information.
Sentence Explanation : If you want to add sentence-level translations, consider adding another interactive element (like tapping on the background of a sentence) that triggers the explanation.
Example Enhancement for Sentence Translation
Modify RSSReadScreen.js to handle sentence selections.
// Add new state
const [selectedSentence, setSelectedSentence] = useState(null);
// Handle sentence press
const handleSentencePress = useCallback((sentence) => {
setSelectedSentence(sentence);
bottomSheetModalRef.current?.present();
setActiveModal('sentence');
}, []);
// Modify renderContent to include sentence buttons
const renderContent = useCallback(() => {
const sentences = formattedContent.split('. ');
return sentences.map((sentence, index) => (
<View key={index} style={styles.sentenceContainer}>
{sentence.split(' ').map((word, wordIndex) => (
<Word
key={`${index}-${wordIndex}`}
word={word}
onPress={handleWordPress}
style={[
styles.contentText,
{
fontSize: fontSize,
color: theme.textColor,
fontFamily: arabicFont,
}
]}
isKnown={knownWords.has(word)}
diacriticsState={diacriticsState}
/>
))}
<TouchableOpacity onPress={() => handleSentencePress(sentence)} style={styles.sentenceButton}>
<Ionicons name="help-circle-outline" size={20} color={theme.primaryColor} />
</TouchableOpacity>
</View>
));
}, [formattedContent, handleWordPress, fontSize, theme, arabicFont, knownWords, diacriticsState, handleSentencePress]);
// Update WordExplanationBox usage
<WordExplanationBox
word={selectedWord}
sentence={selectedSentence} // Pass the selected sentence
storyId={item.id}
onClose={() => bottomSheetModalRef.current?.dismiss()}
/>
Update WordExplanationBox.js to handle both word and sentence explanations.
// WordExplanationBox.js
import React from 'react';
import { View, Text, StyleSheet } from 'react-native';
import { useThemeAndLanguage } from '../utils/ThemeAndLanguageContext';
import { CustomTextR } from '../components/CustomText';
const WordExplanationBox = ({ word, sentence, storyId, onClose }) => {
const { theme, t } = useThemeAndLanguage();
return (
<View style={[styles.container, { backgroundColor: theme.backgroundColor }]}>
{word && (
<>
<Text style={[styles.header, { color: theme.textColor }]}>{t('wordExplanation')}</Text>
<CustomTextR style={[styles.content, { color: theme.textColor }]}>
{/* Replace with actual word explanation logic */}
{`Definition and translation for "${word}"`}
</CustomTextR>
</>
)}
{sentence && (
<>
<Text style={[styles.header, { color: theme.textColor }]}>{t('sentenceExplanation')}</Text>
<CustomTextR style={[styles.content, { color: theme.textColor }]}>
{/* Replace with actual sentence translation logic */}
{`Translation for the sentence: "${sentence}"`}
</CustomTextR>
</>
)}
</View>
);
};
const styles = StyleSheet.create({
container: {
padding: 20,
},
header: {
fontSize: 18,
fontWeight: 'bold',
marginBottom: 10,
},
content: {
fontSize: 16,
},
});
export default WordExplanationBox;
Explanation
Sentence Handling : By splitting the content into sentences and adding a button (help-circle-outline icon) next to each sentence, users can tap to get translations or explanations for the entire sentence.
Word and Sentence Explanations : The WordExplanationBox now can handle both word-level and sentence-level explanations based on what the user interacts with.
Additional Recommendations
Optimize Performance :
Use React.memo and useCallback effectively to prevent unnecessary re-renders.
Utilize initialNumToRender, maxToRenderPerBatch, and windowSize in FlatList for performance optimization.
Enhance UI/UX :
Implement better loading placeholders for images.
Add animations for the bottom sheets to enhance user experience.
Error Handling :
Provide more granular error messages based on different failure scenarios.
Implement retry mechanisms for failed network requests.
Accessibility :
Ensure that all interactive elements are accessible via screen readers.
Use appropriate contrast ratios and font sizes for better readability.
Testing :
Test the RSS fetching and parsing with various RSS feeds to ensure compatibility.
Ensure that caching works correctly and data is loaded when offline.
By following the above steps and integrating the provided code snippets into your project, you can effectively create an RSSTab that fetches, displays, and allows interaction with RSS feed items, enhancing your application's functionality and providing users with a rich content experience.
Copy first response
Not yet included in a published release.