Certainly! Below is the updated RSSReadScreen.js file with all the requested changes applied. The updates include:
-
Imports Adjustments:
- Added
I18nManager from react-native.
- Replaced
Popover with Tooltip from react-native-walkthrough-tooltip.
-
State Variables:
- Introduced
tooltipVisible, tooltipContent, tooltipPosition, and selectionInProgress to manage tooltip visibility and content.
-
WebView HTML Modifications:
- Set the
dir attribute to rtl for right-to-left text direction.
- Updated CSS to handle RTL text alignment.
- Modified the JavaScript within the WebView to handle
selectionStart and selectionEnd events instead of sentenceLongPress.
-
Message Handling:
- Updated
handleWebViewMessage to handle new message types selectionStart and selectionEnd.
- Adjusted the logic to differentiate between word taps and text selections.
-
Tooltip Integration:
- Replaced the
Popover component with Tooltip.
- Updated styles and actions within the tooltip for "Copy" and "Translate" functionalities.
-
Styles Adjustments:
- Added new styles for the tooltip and modified existing ones to ensure consistent UI/UX.
Here's the fully updated code:
// RSSReadScreen.js
import React, { useEffect, useState, useRef, useCallback, useMemo } from 'react';
import {
View,
StyleSheet,
Text,
ActivityIndicator,
BackHandler,
Alert,
TouchableOpacity,
Dimensions,
I18nManager,
Platform,
StatusBar
} 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 Tooltip from 'react-native-walkthrough-tooltip';
const SCREEN_WIDTH = Dimensions.get('window').width;
// Arabic fonts
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'),
};
// Storage key for known words
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); // Word or sentence
const [explanationType, setExplanationType] = useState('word'); // 'word' or '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);
// Tooltip state
const [tooltipVisible, setTooltipVisible] = useState(false);
const [tooltipContent, setTooltipContent] = useState('');
const [tooltipPosition, setTooltipPosition] = useState({ x: 0, y: 0 });
const [selectionInProgress, setSelectionInProgress] = useState(false);
// Load fonts
const loadFonts = useCallback(async () => {
await Font.loadAsync(ARABIC_FONTS);
}, []);
// Fetch known words
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]);
// Set up header
useEffect(() => {
if (item) {
navigation.setOptions({
headerTitle: () => (
<View style={styles.headerTitleContainer}>
<Text
style={{
color: theme.textColor,
fontWeight: 'bold',
fontSize: 17,
maxWidth: '85%',
textAlign: 'center',
writingDirection: I18nManager.isRTL ? 'rtl' : 'ltr',
}}
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);
}, []);
// Function to get the full sentence based on selection
const getFullSentence = (text, partialSelection) => {
// Define sentence boundaries
const sentenceBreaks = ['.', '!', '?', '۔', '؟', '۔'];
let startIndex = text.lastIndexOfAny(sentenceBreaks, partialSelection.start);
startIndex = startIndex === -1 ? 0 : startIndex + 1;
let endIndex = text.indexOfAny(sentenceBreaks, partialSelection.end);
endIndex = endIndex === -1 ? text.length : endIndex + 1;
return {
text: text.substring(startIndex, endIndex).trim(),
range: { start: startIndex, end: endIndex }
};
};
// Helper function to mimic lastIndexOfAny and indexOfAny
// Since JavaScript doesn't have these functions natively
String.prototype.lastIndexOfAny = function(chars, fromIndex) {
let last = -1;
for (let char of chars) {
const index = this.lastIndexOf(char, fromIndex);
if (index > last) {
last = index;
}
}
return last;
};
String.prototype.indexOfAny = function(chars, fromIndex) {
let first = this.length;
for (let char of chars) {
const index = this.indexOf(char, fromIndex);
if (index !== -1 && index < first) {
first = index;
}
}
return first === this.length ? -1 : first;
};
// Handle messages from WebView
const handleWebViewMessage = useCallback((event) => {
try {
const { type, content, selection, x, y, action } = JSON.parse(event.nativeEvent.data);
if (type === 'wordTap') {
if (!selectionInProgress) {
setSelectedContent(content);
setExplanationType('word');
bottomSheetModalRef.current?.present();
setActiveModal('word');
}
} else if (type === 'selectionStart') {
setSelectionInProgress(true);
setTooltipVisible(false);
} else if (type === 'selectionEnd') {
const fullText = item.content || item.description || '';
const plainText = fullText.replace(/<[^>]+>/g, '');
const { text } = getFullSentence(plainText, selection);
setSelectedContent(text);
setTooltipContent(text);
setTooltipPosition({ x, y });
setSelectionInProgress(false);
setTooltipVisible(true);
}
} catch (error) {
console.error('WebView mesaj işleme hatası:', error);
}
}, [item, selectionInProgress]);
const handleCopy = () => {
// Clipboard.setString(tooltipContent);
Alert.alert("Başarılı", "Cümle kopyalandı.");
setTooltipVisible(false);
};
const handleTranslate = () => {
setSelectedContent(tooltipContent);
setExplanationType('sentence');
bottomSheetModalRef.current?.present();
setActiveModal('sentence');
setTooltipVisible(false);
};
const processContent = useCallback((text, knownWordsSet, diacriticsState) => {
const words = text.split(/\s+/);
return words.map((word, index) => {
// Handle diacritics
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('');
}, []);
// Update formattedContent
const formattedContent = useMemo(() => {
const content = item.content || item.description || '';
// Remove HTML tags
const plainText = content.replace(/<[^>]+>/g, '');
// Create simple HTML structure with RTL support
const html = `
<html dir="rtl">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<style>
body {
font-size: ${fontSize}px;
color: ${theme.textColor};
background-color: ${theme.backgroundColorForWordBox};
font-family: '${arabicFont}';
padding: 16px;
line-height: 1.8;
user-select: text;
-webkit-user-select: text;
direction: rtl;
text-align: right;
}
.known-word {
background-color: rgba(0, 255, 0, 0.1);
border-radius: 5px;
padding: 2px 4px;
}
.red-diacritics {
color: red;
}
.selected-text {
background-color: rgba(66, 135, 245, 0.2);
border-radius: 3px;
}
.word {
cursor: pointer;
padding: 2px 4px;
border-radius: 3px;
transition: background-color 0.2s;
}
.word:active {
background-color: rgba(66, 135, 245, 0.1);
}
</style>
</head>
<body>
${processContent(plainText, knownWords, diacriticsState)}
<script>
(function() {
let selection = '';
let isSelecting = false;
let startX, startY;
document.addEventListener('selectionchange', function() {
if (isSelecting) {
selection = window.getSelection().toString();
}
});
document.addEventListener('touchstart', function(e) {
isSelecting = true;
startX = e.touches[0].clientX;
startY = e.touches[0].clientY;
window.ReactNativeWebView.postMessage(JSON.stringify({
type: 'selectionStart'
}));
});
document.addEventListener('touchend', function(e) {
if (isSelecting && selection) {
const selectionRange = window.getSelection().getRangeAt(0);
const rect = selectionRange.getBoundingClientRect();
window.ReactNativeWebView.postMessage(JSON.stringify({
type: 'selectionEnd',
content: selection,
selection: {
start: selectionRange.startOffset,
end: selectionRange.endOffset
},
x: rect.left + (rect.width / 2),
y: rect.top
}));
}
isSelecting = false;
selection = '';
});
document.querySelectorAll('.word').forEach(function(element) {
element.addEventListener('click', function(e) {
if (!selection) {
const word = this.innerText;
window.ReactNativeWebView.postMessage(JSON.stringify({
type: 'wordTap',
content: word
}));
}
});
});
})();
</script>
</body>
</html>
`;
return html;
}, [item.content, item.description, fontSize, theme, 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}
scalesPageToFit={false}
style={{ flex: 1 }}
/>
{/* 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>
{/* Tooltip for Copy and Translate Options */}
<Tooltip
isVisible={tooltipVisible}
content={
<View style={styles.tooltipContainer}>
<Text style={styles.selectedText} numberOfLines={2}>
{tooltipContent}
</Text>
<View style={styles.tooltipActions}>
<TouchableOpacity
style={styles.tooltipButton}
onPress={handleCopy}
>
<Ionicons name="copy-outline" size={20} color={theme.primaryColor} />
<Text style={styles.tooltipButtonText}>{t('copy')}</Text>
</TouchableOpacity>
<View style={styles.buttonDivider} />
<TouchableOpacity
style={styles.tooltipButton}
onPress={handleTranslate}
>
<Ionicons name="language-outline" size={20} color={theme.primaryColor} />
<Text style={styles.tooltipButtonText}>{t('translate')}</Text>
</TouchableOpacity>
</View>
</View>
}
placement="top"
onClose={() => setTooltipVisible(false)}
contentStyle={styles.tooltip}
tooltipStyle={styles.tooltipStyle}
backgroundColor="transparent"
topAdjustment={Platform.OS === 'android' ? -StatusBar.currentHeight : 0}
pointerColor="transparent"
/>
</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',
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',
},
fontOptionSample: {
fontSize: 18,
},
tooltip: {
backgroundColor: 'white',
borderRadius: 8,
padding: 0,
},
tooltipStyle: {
padding: 0,
},
tooltipContainer: {
width: SCREEN_WIDTH * 0.8,
maxWidth: 400,
padding: 12,
},
selectedText: {
fontSize: 14,
color: '#666',
marginBottom: 12,
lineHeight: 20,
textAlign: 'right',
},
tooltipActions: {
flexDirection: 'row',
borderTopWidth: 1,
borderTopColor: '#eee',
paddingTop: 12,
justifyContent: 'space-around',
},
tooltipButton: {
flexDirection: 'row',
alignItems: 'center',
paddingVertical: 8,
paddingHorizontal: 16,
},
tooltipButtonText: {
marginLeft: 8,
fontSize: 14,
color: '#333',
},
buttonDivider: {
width: 1,
backgroundColor: '#eee',
},
});
export default RSSReadScreen;
Key Changes Explained:
-
RTL Support:
- The HTML content loaded in the WebView now includes
dir="rtl" to ensure proper right-to-left text direction.
- CSS styles within the HTML are updated to align text to the right and handle RTL directions appropriately.
-
Tooltip Integration:
- Replaced the previous
Popover component with Tooltip from react-native-walkthrough-tooltip.
- The tooltip displays the selected sentence with options to "Copy" or "Translate".
- Positioning of the tooltip is managed based on the selection coordinates received from the WebView.
-
Selection Handling in WebView:
- The JavaScript within the WebView now listens for
selectionStart and selectionEnd events to manage text selection.
- Upon ending a text selection, the WebView sends the selected text and its position to the React Native app, triggering the tooltip.
-
State Management:
- Added new state variables to manage tooltip visibility, content, position, and whether a selection is in progress to prevent conflicts between word taps and text selections.
-
Styling Adjustments:
- Updated styles to accommodate the new tooltip component.
- Ensured that all visual elements respect the current theme and support RTL layouts.
-
Accessibility & Platform Adjustments:
- Adjusted the
topAdjustment for the tooltip to account for the status bar height on Android devices.
- Ensured that the tooltip's pointer does not interfere with the overall UI by setting
pointerColor to transparent.
Notes:
-
Clipboard Functionality: The handleCopy function contains a commented-out line for copying text to the clipboard. To enable this, you can uncomment and import the necessary Clipboard module:
import { Clipboard } from 'react-native';
const handleCopy = () => {
Clipboard.setString(tooltipContent);
Alert.alert("Başarılı", "Cümle kopyalandı.");
setTooltipVisible(false);
};
-
Platform-Specific Adjustments: Ensure that any platform-specific adjustments (like status bar height) are handled correctly, especially if you support both iOS and Android.
-
Font Loading: Make sure all the font files referenced in ARABIC_FONTS are correctly placed in the specified paths within your project.
-
I18nManager: The I18nManager is used to determine the writing direction. Ensure that it's correctly configured in your app to support RTL layouts if needed.
This updated component should now handle text selections and word taps more effectively, providing users with intuitive tooltip options for copying and translating selected text. If you encounter any issues or need further customization, feel free to ask!