// RSSReadScreen.js import React, { useEffect, useState… · The Chat Archive
Explore / Programming o1-mini-2024-09-12 · OpenAI WildChat-4.8M (AI2)// RSSReadScreen.js import React, { useEffect, useState, useRef, useCallback, useMemo }… Save Share Download ▾ Report// 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';
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 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'
// Fonları yüklüyoruz
const loadFonts = useCallback(async () => {
await Font.loadAsync(ARABIC_FONTS);
}, []);
// Kullanıcının bilinen kelimelerini yüklüyoruz
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]);
// Header ayarlarını yapıyoruz
useEffect(() => {
if (item) {
navigation.setOptions({
headerTitle: () => (
<Text
style={{
color: theme.textColor,
fontWeight: 'bold',
fontSize: 17,
maxWidth: '85%',
textAlign: 'center',
}}
numberOfLines={2}
ellipsizeMode="tail"
>
{item.title}
),
headerStyle: { backgroundColor: theme.lighterCardBackgroundColor },
headerTintColor: theme.textColor,
headerRight: () => (
),
});
}
}, [navigation, item, theme, diacriticsState, toggleDiacritics]);
Assistant2024-11-17 00:44 UTC Copy response
Copy first prompt
Details
Model o1-mini-2024-09-12
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 01m7h4294gx9zev0rtp1n5b47bSource & license Imported from WildChat-4.8M (AI2) (source ). Imported records earn no Research Points.
Upstream record: b0d649f7f46de7a7d2c1aff06f2d9dc7
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
Dataset releases Not yet included in a published release.
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');
}, []);
// Ayarlara modal açma fonksiyonu ekleyelim
const settingsBottomSheetModalRef = useRef(null);
const openSettingsModal = useCallback(() => {
settingsBottomSheetModalRef.current?.present();
setActiveModal('settings');
}, []);
const closeAllModals = useCallback(() => {
bottomSheetModalRef.current?.dismiss();
settingsBottomSheetModalRef.current?.dismiss();
setActiveModal(null);
}, []);
// İçeriği kelimelere ayırıp render ediyoruz
const formattedContent = useMemo(() => {
if (!item.content) return '';
// HTML etiketlerini kaldırıyoruz
const plainText = item.content.replace(/<[^>]+>/g, '');
return plainText;
}, [item.content]);
// Word bileşeni
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;
})}
);
});
// İçeriği kelime etkileşimleri ile render ediyoruz
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 }]}>
);
}
return (
<View style={[styles.container, { backgroundColor: theme.backgroundColorForWordBox }]}>
{item.image && (
<Image
source={{ uri: item.image }}
style={styles.imageStyle}
resizeMode="cover"
/>
)}
<Text style={[styles.titleArabic, { color: theme.textColor, fontFamily: arabicFontBold }]}>
{item.title}
<CustomTextR style={[styles.titleDescription, { color: theme.secondaryColor }]}>
{new Date(item.pubDate).toLocaleDateString(locale)}
{renderContent()}
<View style={styles.headerRight}>
<ToggleHeartButton storyId={item.id} initialHeartCount={item.hearts} />
<DiacriticsToggleButton
diacriticsState={diacriticsState}
onToggle={toggleDiacritics}
color={theme.textColor}
/>
<TouchableOpacity onPress={openSettingsModal} style={styles.fontSizeControl}>
<Ionicons name="text" size={24} color={theme.textColor} />
</TouchableOpacity>
</View>
{/* Word Explanation Bottom Sheet */}
<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>
{/* Settings Bottom Sheet */}
<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={() => setFontSize(prev => prev + 2)} style={styles.fontSizeButton}>
<Ionicons name="add-circle-outline" size={40} color={theme.primaryColor} />
<Text style={styles.fontSizeButtonText}>{t('increaseFontSize')}</Text>
</TouchableOpacity>
<TouchableOpacity onPress={() => setFontSize(prev => prev - 2)} 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>
</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,
},
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,
},
headerTitleContainer: {
flex: 1,
justifyContent: 'center',
alignItems: 'center',
},
headerRight: {
flexDirection: 'row',
alignItems: 'center',
marginRight: 10,
},
});
export default RSSReadScreen; şu dosyayı inceler misin?
örnek bir rssitemi böyle:
bu içeriğin ayıklandığı sayfa da bu:
// RSSTabContent.js
import React, { useState, useEffect, useCallback, useRef, useContext } from 'react';
import {
View,
Text,
StyleSheet,
FlatList,
Image,
TouchableOpacity,
ActivityIndicator,
RefreshControl,
} from 'react-native';
import { useThemeAndLanguage } from '../utils/ThemeAndLanguageContext';
import { Ionicons } from '@expo/vector-icons';
import { useNavigation } from '@react-navigation/native';
import * as rssParser from 'react-native-rss-parser';
import AsyncStorage from '@react-native-async-storage/async-storage';
import { HeartContext } from './HeartContext'; // Kalp butonu için context
import useInternetStatus from '../utils/useInternetStatus';
import InternetStatusAlert from '../components/InternetStatusAlert';
import { CustomTextR, CustomTextB } from '../components/CustomText';
const RSSTabContent = () => {
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);
// Okunan hikayeleri yükle
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);
}
}, []);
// Hikayeyi okunmuş olarak işaretle
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]);
// Hikayeye basıldığında navigate et
const handleStoryPress = useCallback((item) => {
markStoryAsRead(item.id);
navigation.navigate('RSSReadScreen', { item });
}, [navigation, markStoryAsRead]);
// RSS beslemesini çek ve parse et
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, // Link'i alternatif ID olarak kullan
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'));
// Cache'lenmiş veriyi yüklemeyi dene
const cachedRSS = await AsyncStorage.getItem(STORAGE_KEY);
if (cachedRSS) {
setRssItems(JSON.parse(cachedRSS));
}
} finally {
setLoading(false);
}
// Cache'lenmiş RSS verisini yükle
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);
}
}, []);
// İlk yükleme
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]);
// Kalp sayıları değiştiğinde RSS item'larını güncelle
useEffect(() => {
setRssItems(prevItems =>
prevItems.map(item => ({
...item,
hearts: heartsCounts[item.id] !== undefined ? heartsCounts[item.id] : 0,
}))
);
}, [heartsCounts]);
// İnternet bağlantısı durumu değiştiğinde alert göster
useEffect(() => {
if (!isConnected) {
setShowInternetAlert(true);
} else {
setShowInternetAlert(false);
}
}, [isConnected]);
// RSS item render et
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, locale]);
// List Header Component (örn: başlık, hata mesajları vb.)
const ListHeaderComponent = useCallback(() => (
{error && <Text style={[styles.errorText, { color: theme.errorColor }]}>{error}}
), [error, 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={rssItems}
keyExtractor={item => item.id}
renderItem={renderRSSItem}
ListHeaderComponent={ListHeaderComponent}
refreshControl={
}
initialNumToRender={5}
maxToRenderPerBatch={5}
windowSize={11}
/>
);
};
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 RSSTabContent;
sorun şu, okuma ekranında başlık olacak ve altında descriptionda yazan yazı olacak. bu nedense olmuyor. sorunu düzelt. description yazısı görünmüyor.
Sorununuz, RSSReadScreen.js dosyasında RSS öğesinin açıklamasının (description) görünmemesiyle ilgili. Bunun temel sebebi, RSSReadScreen.js içerisindeki içeriği (content) kullanmaya çalışmanız fakat RSS verilerinde bu alanın boş veya tanımlı olmamasıdır. Örnek RSS öğenizde içerik, description etiketi içerisinde yer alıyor.
Aşağıda, bu sorunu çözmek için yapmanız gereken adımları ve ilgili kod değişikliklerini detaylı bir şekilde açıklıyorum.
Sorunun Kaynağı
Veri Yapısı: RSS öğesinde description etiketi içerisinde hem resim (img) hem de metin bulunuyor.
RSSReadScreen.js Kullanımı: Bu dosya, mesajın içeriğini item.content üzerinden almaya çalışıyor. Ancak örnek RSS öğesinde content etiketi bulunmuyor veya boş olabilir.
Sonuç: formattedContent boş kalıyor ve dolayısıyla açıklama görünmüyor.
Çözüm Adımları
RSSReadScreen.js Dosyasını Güncelleme
RSSReadScreen.js dosyasında, içeriği (content) almaya çalıştığınız kısımla ilgili bir değişiklik yaparak description alanını kullanmalısınız. Bu sayede, description alanında bulunan metin doğru şekilde görüntülenecektir.
Mevcut Kod:
const formattedContent = useMemo(() => {
if (!item.content) return '';
// HTML etiketlerini kaldırıyoruz
const plainText = item.content.replace(/<[^>]+>/g, '');
return plainText;
}, [item.content]);
Güncellenmiş Kod:
const formattedContent = useMemo(() => {
const content = item.content || item.description || '';
// HTML etiketlerini kaldırıyoruz
const plainText = content.replace(/<[^>]+>/g, '');
return plainText;
}, [item.content, item.description]);
Açıklama:
item.content boşsa, item.description'ı kullanacak şekilde güncellendi.
Bu, hem content hem de description alanlarından içeriğin doğru şekilde alınmasını sağlar.
RSSReadScreen.js İçinde Render Fonksiyonunu Güncelleme
description alanını kullanarak içeriği kelimelere ayırmak için renderContent fonksiyonunu güncellemek faydalı olabilir.
Mevcut Kod:
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]);
Güncellenmiş Kod:
const renderContent = useCallback(() => {
if (!formattedContent) {
return <Text style={[styles.contentText, { color: theme.textColor }]}>{t('noContentAvailable')}</Text>;
}
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]);
Açıklama:
Eğer formattedContent boşsa, kullanıcıya içerik olmadığını belirten bir mesaj gösterilir.
Bu, kullanıcı deneyimini artırır ve boş içerik durumlarını düzgün şekilde yönetir.
Tam Güncellenmiş RSSReadScreen.js Dosyası
Aşağıda, yukarıdaki değişikliklerin uygulanmış haliyle tamamlanmış RSSReadScreen.js dosyasını bulabilirsiniz:
// 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';
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 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'
// Fonları yüklüyoruz
const loadFonts = useCallback(async () => {
await Font.loadAsync(ARABIC_FONTS);
}, []);
// Kullanıcının bilinen kelimelerini yüklüyoruz
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]);
// Header ayarlarını yapıyoruz
useEffect(() => {
if (item) {
navigation.setOptions({
headerTitle: () => (
<View style={styles.headerTitleContainer}>
<Text
style={{
color: theme.textColor,
fontWeight: 'bold',
fontSize: 17,
maxWidth: '85%',
textAlign: 'center',
}}
numberOfLines={2}
ellipsizeMode="tail"
>
{item.title}
</Text>
</View>
),
headerStyle: { backgroundColor: theme.lighterCardBackgroundColor },
headerTintColor: theme.textColor,
headerRight: () => (
<View style={styles.headerRight}>
<ToggleHeartButton storyId={item.id} initialHeartCount={item.hearts} />
<DiacriticsToggleButton
diacriticsState={diacriticsState}
onToggle={toggleDiacritics}
color={theme.textColor}
/>
<TouchableOpacity onPress={openSettingsModal} style={styles.fontSizeControl}>
<Ionicons name="text" size={24} color={theme.textColor} />
</TouchableOpacity>
</View>
),
});
}
}, [navigation, item, theme, diacriticsState, toggleDiacritics]);
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');
}, []);
// Ayarlara modal açma fonksiyonu ekleyelim
const settingsBottomSheetModalRef = useRef(null);
const openSettingsModal = useCallback(() => {
settingsBottomSheetModalRef.current?.present();
setActiveModal('settings');
}, []);
const closeAllModals = useCallback(() => {
bottomSheetModalRef.current?.dismiss();
settingsBottomSheetModalRef.current?.dismiss();
setActiveModal(null);
}, []);
// İçeriği kelimelere ayırıp render ediyoruz
const formattedContent = useMemo(() => {
const content = item.content || item.description || '';
// HTML etiketlerini kaldırıyoruz
const plainText = content.replace(/<[^>]+>/g, '');
return plainText;
}, [item.content, item.description]);
// Word bileşeni
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>
);
});
// İçeriği kelime etkileşimleri ile render ediyoruz
const renderContent = useCallback(() => {
if (!formattedContent) {
return <Text style={[styles.contentText, { color: theme.textColor }]}>{t('noContentAvailable')}</Text>;
}
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, t]);
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={openSettingsModal} style={styles.fontSizeControl}>
<Ionicons name="text" size={24} color={theme.textColor} />
</TouchableOpacity>
</View>
{/* Word Explanation Bottom Sheet */}
<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>
{/* Settings Bottom Sheet */}
<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={() => setFontSize(prev => prev + 2)} style={styles.fontSizeButton}>
<Ionicons name="add-circle-outline" size={40} color={theme.primaryColor} />
<Text style={styles.fontSizeButtonText}>{t('increaseFontSize')}</Text>
</TouchableOpacity>
<TouchableOpacity onPress={() => setFontSize(prev => prev - 2)} 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>
</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,
},
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,
},
headerTitleContainer: {
flex: 1,
justifyContent: 'center',
alignItems: 'center',
},
headerRight: {
flexDirection: 'row',
alignItems: 'center',
marginRight: 10,
},
});
export default RSSReadScreen;
Ek İyileştirmeler
Boş İçerik Durumu İçin Mesaj:
Kullanıcıya, içerik mevcut değilse bunun belirtildiği bir mesaj gösterilebilir. Bu, kullanıcı deneyimini artırır.
if (!formattedContent) {
return <Text style={[styles.contentText, { color: theme.textColor }]}>{t('noContentAvailable')}</Text>;
}
Türkçe Çeviriler:
Eğer t('noContentAvailable') bir çeviri anahtarıysa, çeviri dosyanıza uygun çeviriyi eklemeyi unutmayın.
// Örnek çeviri dosyası
{
"noContentAvailable": "İçerik mevcut değil."
}
Özet
Sorununuz, RSSReadScreen.js dosyasının içeriği (content) kullanmaya çalışması fakat RSS verilerinde bu alanın boş olması nedeniyle açıklamanın görünmemesiymiş. Bu durumu çözmek için description alanını kullanarak içeriği almanız gerekmekte. Yukarıda belirttiğim adımları takip ederek bu sorunu çözebilirsiniz. Bu değişiklikler, kullanıcıların RSS öğelerini doğru şekilde okuyabilmelerini sağlayacak ve uygulamanızın genel kullanıcı deneyimini artıracaktır.
Eğer daha fazla sorun yaşarsanız veya başka bir konuda yardıma ihtiyaç duyarsanız, lütfen çekinmeden sorun!
Copy first response