Here is the updated RSSReadScreen.js file with the requested modifications applied. The changes include the addition of the handleWebViewMessage function, updating the WebView component to handle messages from the WebView, and incorporating the necessary alert dialogs for user interactions. The Clipboard functionality remains commented out, as per your instructions.
// RSSReadScreen.js
import React, { useEffect, useState, useRef, useCallback, useMemo } from 'react';
import {
View,
StyleSheet,
Text,
ActivityIndicator,
BackHandler,
Alert,
TouchableOpacity // Added for font options
} 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,
} from '@gorhom/bottom-sheet';
import { useFocusEffect } from '@react-navigation/native';
import { useVocabulary } from './VocabularyContext';
import ToggleHeartButton from './heart';
import DiacriticsToggleButton from '../components/DiacriticsToggleButton';
import { removeDiacritics } from '../utils/arabicUtils';
import { WebView } from 'react-native-webview';
//import Clipboard from '@react-native-clipboard/clipboard'; // Yeni eklenen
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 [selectedContent, setSelectedContent] = useState(null); // Hem kelime hem de cümle
const [explanationType, setExplanationType] = useState('word'); // 'word' veya 'sentence'
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'
const settingsBottomSheetModalRef = useRef(null);
// 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}
/>
<Ionicons name="text" size={24} color={theme.textColor} style={styles.fontSizeControl} onPress={openSettingsModal} />
</View>
),
});
}
}, [navigation, item, theme, diacriticsState, toggleDiacritics, openSettingsModal]);
useFocusEffect(
useCallback(() => {
const onBackPress = () => {
if (activeModal) {
bottomSheetModalRef.current?.dismiss();
settingsBottomSheetModalRef.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 openSettingsModal = useCallback(() => {
settingsBottomSheetModalRef.current?.present();
setActiveModal('settings');
}, []);
const closeAllModals = useCallback(() => {
bottomSheetModalRef.current?.dismiss();
settingsBottomSheetModalRef.current?.dismiss();
setActiveModal(null);
}, []);
// handleWebViewMessage fonksiyonunu ekliyoruz
const handleWebViewMessage = useCallback((event) => {
try {
const { type, content } = JSON.parse(event.nativeEvent.data);
if (type === 'wordTap') {
setSelectedContent(content);
setExplanationType('word');
bottomSheetModalRef.current?.present();
setActiveModal('word');
} else if (type === 'sentenceLongPress') {
Alert.alert(
"Seçenekler",
"Cümleyi kopyalamak veya çevirisini yapmak ister misiniz?",
[
{
text: "İptal",
style: "cancel"
},
{
text: "Kopyala",
onPress: () => {
//Clipboard.setString(content);
Alert.alert("Başarılı", "Cümle kopyalandı.");
}
},
{
text: "Çevir",
onPress: () => {
setSelectedContent(content);
setExplanationType('sentence');
bottomSheetModalRef.current?.present();
setActiveModal('sentence');
}
}
],
{ cancelable: true }
);
}
} catch (error) {
console.error('WebView mesaj işleme hatası:', error);
}
}, []);
const processContent = useCallback((text, knownWordsSet, diacriticsState) => {
const words = text.split(/\s+/);
return words.map((word, index) => {
// Diacritics handling
let processedWord = word;
if (diacriticsState === 'hidden') {
processedWord = removeDiacritics(word);
} else if (diacriticsState === 'red') {
processedWord = word.split('').map(char => {
return removeDiacritics(char) === char ? char : `<span class="red-diacritics">${char}</span>`;
}).join('');
}
const isKnown = knownWordsSet.has(word);
const className = isKnown ? 'known-word word' : 'word';
return `<span class="${className}">${processedWord}</span> `;
}).join('');
}, []);
// formattedContent'i güncelliyoruz
const formattedContent = useMemo(() => {
const content = item.content || item.description || '';
// HTML etiketlerini kaldırıyoruz
const plainText = content.replace(/<[^>]+>/g, '');
// Basit HTML yapısı oluşturuyoruz
const html = `
<html>
<head>
<meta charset="utf-8">
<style>
body {
font-size: ${fontSize}px;
color: ${theme.textColor};
background-color: ${theme.backgroundColorForWordBox};
font-family: '${arabicFont}';
padding: 10px;
}
.known-word {
background-color: rgba(0, 255, 0, 0.1);
border-radius: 5px;
}
.red-diacritics {
color: red;
}
/* Diacritics hidden */
.hidden-diacritics {
display: none;
}
</style>
</head>
<body>
${processContent(plainText, knownWords, diacriticsState)}
<script>
(function() {
let timer;
const threshold = 500; // 500ms uzun basma eşiği
document.querySelectorAll('.word').forEach(function(element) {
// Kısa tıklama
element.addEventListener('click', function() {
const word = this.innerText;
window.ReactNativeWebView.postMessage(JSON.stringify({ type: 'wordTap', content: word }));
});
// Uzun basma (mobil için touch olayları)
element.addEventListener('touchstart', function(e) {
timer = setTimeout(() => {
const sentence = getSentence(this);
window.ReactNativeWebView.postMessage(JSON.stringify({ type: 'sentenceLongPress', content: sentence }));
}, threshold);
});
element.addEventListener('touchend', function(e) {
clearTimeout(timer);
});
// Masaüstü için mouse olayları
element.addEventListener('mousedown', function(e) {
timer = setTimeout(() => {
const sentence = getSentence(this);
window.ReactNativeWebView.postMessage(JSON.stringify({ type: 'sentenceLongPress', content: sentence }));
}, threshold);
});
element.addEventListener('mouseup', function(e) {
clearTimeout(timer);
});
});
function getSentence(element) {
let sentence = '';
let parent = element.parentElement;
while (parent) {
if (parent.tagName.toLowerCase() === 'p') {
sentence = parent.innerText;
break;
}
parent = parent.parentElement;
}
return sentence;
}
})();
</script>
</body>
</html>
`;
return html;
}, [item.content, item.description, fontSize, theme.textColor, theme.backgroundColorForWordBox, arabicFont, knownWords, diacriticsState, processContent]);
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 }]}>
<WebView
originWhitelist={['*']}
source={{ html: formattedContent }}
onMessage={handleWebViewMessage}
javaScriptEnabled={true}
domStorageEnabled={true}
/>
{/* Word & Sentence Explanation Bottom Sheet */}
<BottomSheetModal
ref={bottomSheetModalRef}
index={0}
snapPoints={['30%', '90%']}
handleStyle={{ backgroundColor: theme.backgroundColorForWordBox }}
onDismiss={() => setActiveModal(null)}
>
<WordExplanationBox
content={selectedContent}
type={explanationType}
storyId={item.id}
onClose={() => bottomSheetModalRef.current?.dismiss()}
/>
</BottomSheetModal>
{/* Settings Bottom Sheet */}
<BottomSheetModal
ref={settingsBottomSheetModalRef}
index={0}
snapPoints={['85%']}
handleStyle={{ backgroundColor: theme.backgroundColorForWordBox }}
onDismiss={() => setActiveModal(null)}
>
<View style={styles.settingsContent}>
<Text style={{ fontSize: 18, marginBottom: 10, color: theme.textColor }}>{t('fontSettings')}</Text>
<View style={styles.fontSizeControls}>
<Ionicons name="add-circle-outline" size={40} color={theme.primaryColor} onPress={() => setFontSize(prev => prev + 2)} />
<Ionicons name="remove-circle-outline" size={40} color={theme.primaryColor} onPress={() => setFontSize(prev => prev - 2)} />
</View>
<Text style={{ fontSize: 16, marginVertical: 10, color: theme.textColor }}>{t('selectFont')}</Text>
<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>
</View>
</BottomSheetModal>
</View>
</BottomSheetModalProvider>
);
};
const styles = StyleSheet.create({
container: {
flex: 1,
},
loadingContainer: {
flex: 1,
justifyContent: 'center',
alignItems: 'center',
},
headerTitleContainer: {
flex: 1,
justifyContent: 'center',
alignItems: 'center',
},
headerRight: {
flexDirection: 'row',
alignItems: 'center',
},
fontSizeControl: {
marginLeft: 10,
},
settingsContent: {
flex: 1,
padding: 20,
},
fontSizeControls: {
flexDirection: 'row',
justifyContent: 'space-around',
marginVertical: 20,
},
fontOptionsContainer: {
flexDirection: 'row',
flexWrap: 'wrap',
justifyContent: 'space-around',
},
fontOption: {
width: '45%',
backgroundColor: '#fff', // Changed to hex for consistency
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',
color: '#000', // Ensuring text is visible
},
fontOptionSample: {
fontSize: 18,
},
});
export default RSSReadScreen;
Summary of Changes:
-
Added handleWebViewMessage Function:
- This function handles messages sent from the WebView. It differentiates between a word tap and a sentence long press.
- On a word tap, it sets the selected content and opens the word explanation bottom sheet.
- On a sentence long press, it presents an alert with options to copy the sentence or translate it. Currently, the copy functionality is commented out and replaced with an alert confirmation.
-
Updated WebView Component:
- The
onMessage prop of the WebView is now set to the handleWebViewMessage function to handle incoming messages from the WebView content.
-
Maintained Commented-out Clipboard Functionality:
- The import statement for
Clipboard and its usage remain commented out. This allows for future implementation if desired.
-
Preserved Existing Functionality:
- All other functionalities, including font loading, known words fetching, theme handling, and bottom sheet modals, remain intact and operational.
Additional Notes:
-
Clipboard Functionality:
- If you intend to enable the clipboard functionality in the future, you can uncomment the
Clipboard import and the Clipboard.setString(content); line within the onPress handler for the "Kopyala" option in the alert.
-
Localization:
- The alert titles and messages are currently in Turkish. Ensure that the localization (
t function) is appropriately used if you plan to support multiple languages.
-
Error Handling:
- The
handleWebViewMessage function includes a try-catch block to handle any unexpected errors during message processing, ensuring that your app remains stable.
-
Styling:
- The styles have been maintained as per your original code. Feel free to adjust them to better fit the overall design of your application.
If you have any further modifications or need additional features integrated, feel free to ask!