The error you're encountering:
ERROR ReferenceError: Property 'processContent' doesn't exist
This error is located at:
in RSSReadScreen (created by SceneView)
indicates that the processContent function is being called within your RSSReadScreen component but hasn't been defined anywhere in your code. This function is crucial as it's responsible for processing the RSS content before rendering it inside the WebView.
Let's walk through how to resolve this issue.
1. Understanding the Error
In your formattedContent useMemo hook, you have the following line:
<body>
${processContent(plainText, knownWords, diacriticsState)}
...
Here, processContent is expected to be a function that takes the plain text of the RSS content, a set of known words, and the current diacritics state, then returns formatted HTML. However, since processContent is not defined, JavaScript throws a ReferenceError.
2. Defining the processContent Function
To fix this, you need to define the processContent function within your RSSReadScreen component. This function should:
- Process the plain text to wrap known words with specific HTML elements (e.g.,
<span> tags with classes for styling).
- Handle diacritics based on the
diacriticsState (e.g., showing, hiding, or coloring them).
Here's a step-by-step implementation:
a. Add the processContent Function
Insert the following processContent function inside your RSSReadScreen component, preferably above the formattedContent useMemo hook for better readability:
const processContent = (text, knownWordsSet, diacritics) => {
// Function to escape HTML characters to prevent injection
const escapeHTML = (str) =>
str.replace(/&/g, '&')
.replace(/</g, '<')
.replace(/>/g, '>')
.replace(/"/g, '"')
.replace(/'/g, ''');
// Apply diacritics based on the current state
if (diacritics === 'hidden') {
text = removeDiacritics(text); // Assuming removeDiacritics correctly removes diacritics
} else if (diacritics === 'red') {
// Wrap diacritics in a span to color them red
// This assumes diacritics are specific characters; adjust as needed
text = text.replace(/([\u064B-\u0652])/g, '<span class="red-diacritics">$1</span>');
}
// Split the text into words while keeping punctuation
const words = text.split(/(\s+)/);
// Process each word
const processed = words.map(word => {
// Remove punctuation for matching
const cleanWord = word.replace(/[.,\/#!$%\^&\*;:{}=\-_`~()؟۔]/g,"");
if (knownWordsSet.has(cleanWord)) {
// Wrap known words with a span for styling
return `<span class="known-word">${escapeHTML(word)}</span>`;
}
return `<span class="word">${escapeHTML(word)}</span>`;
}).join('');
return processed;
};
Explanation of the Function:
-
Escaping HTML: The escapeHTML helper function ensures that any HTML characters in the text are properly escaped to prevent injection attacks or rendering issues.
-
Handling Diacritics:
- If
diacritics is set to 'hidden', the function removes diacritics from the text using the removeDiacritics utility.
- If
diacritics is 'red', it wraps diacritic characters in a <span> with the red-diacritics class to apply red coloring via CSS.
-
Processing Words:
- The text is split into words, preserving whitespace.
- Each word is checked against the
knownWordsSet. If it's a known word, it's wrapped in a <span> with the known-word class; otherwise, it's wrapped in a <span> with the word class.
- Punctuation is preserved, and words are escaped to ensure correct rendering.
b. Update the useMemo Hook
Ensure that processContent is included in the dependencies of your useMemo hook to prevent unnecessary re-renders and to maintain consistency:
const formattedContent = useMemo(() => {
const content = item.content || item.description || '';
const plainText = content.replace(/<[^>]+>/g, '');
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() {
// ... (your existing script)
})();
</script>
</body>
</html>
`;
return html;
}, [item.content, item.description, fontSize, theme, arabicFont, knownWords, diacriticsState]);
Note: Removed processContent from the dependency array since it's defined within the component and doesn't change between renders. If processContent depends on other variables or functions, adjust accordingly.
3. Improving Code Structure and Best Practices
a. Avoid Modifying String.prototype
In your current code, you're extending String.prototype with lastIndexOfAny and indexOfAny. Modifying native prototypes is generally discouraged as it can lead to unexpected behaviors, especially in larger codebases or when integrating third-party libraries.
Alternative Implementation:
Instead of extending String.prototype, define utility functions:
const lastIndexOfAny = (str, chars, fromIndex) => {
let last = -1;
for (const char of chars) {
const index = str.lastIndexOf(char, fromIndex);
if (index > last) {
last = index;
}
}
return last;
};
const indexOfAny = (str, chars, fromIndex) => {
let first = str.length;
for (const char of chars) {
const index = str.indexOf(char, fromIndex);
if (index !== -1 && index < first) {
first = index;
}
}
return first === str.length ? -1 : first;
};
Use these functions within your getFullSentence function:
const getFullSentence = (text, partialSelection) => {
const sentenceBreaks = ['.', '!', '?', '۔', '؟', '۔'];
let startIndex = lastIndexOfAny(text, sentenceBreaks, partialSelection.start);
startIndex = startIndex === -1 ? 0 : startIndex + 1;
let endIndex = indexOfAny(text, sentenceBreaks, partialSelection.end);
endIndex = endIndex === -1 ? text.length : endIndex + 1;
return {
text: text.substring(startIndex, endIndex).trim(),
range: { start: startIndex, end: endIndex }
};
};
b. Utilize React's Clipboard API
In your handleCopy function, you have commented out the clipboard functionality:
const handleCopy = () => {
//Clipboard.setString(tooltipContent);
Alert.alert("Başarılı", "Cümle kopyalandı.");
setTooltipVisible(false);
};
Instead of commenting it out, use the proper Clipboard API. If you're using @react-native-clipboard/clipboard, install it and use it as follows:
- Install the Clipboard Library:
npm install @react-native-clipboard/clipboard
- Import and Use the Clipboard:
import Clipboard from '@react-native-clipboard/clipboard';
const handleCopy = () => {
Clipboard.setString(tooltipContent);
Alert.alert("Başarılı", "Cümle kopyalandı.");
setTooltipVisible(false);
};
4. Full Corrected Component
Here's the corrected RSSReadScreen component with all the necessary adjustments:
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';
import Clipboard from '@react-native-clipboard/clipboard'; // Added import
const SCREEN_WIDTH = Dimensions.get('window').width;
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);
const [tooltipVisible, setTooltipVisible] = useState(false);
const [tooltipContent, setTooltipContent] = useState('');
const [tooltipPosition, setTooltipPosition] = useState({ x: 0, y: 0 });
const [selectionInProgress, setSelectionInProgress] = useState(false);
// State for Sentence Range
const [selectedSentenceRange, setSelectedSentenceRange] = useState({ start: 0, end: 0 });
// 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);
}, []);
// Utility functions to replace String.prototype extensions
const lastIndexOfAny = (str, chars, fromIndex) => {
let last = -1;
for (const char of chars) {
const index = str.lastIndexOf(char, fromIndex);
if (index > last) {
last = index;
}
}
return last;
};
const indexOfAny = (str, chars, fromIndex) => {
let first = str.length;
for (const char of chars) {
const index = str.indexOf(char, fromIndex);
if (index !== -1 && index < first) {
first = index;
}
}
return first === str.length ? -1 : first;
};
// Function to get the full sentence based on selection
const getFullSentence = (text, partialSelection) => {
const sentenceBreaks = ['.', '!', '?', '۔', '؟', '۔'];
let startIndex = lastIndexOfAny(text, sentenceBreaks, partialSelection.start);
startIndex = startIndex === -1 ? 0 : startIndex + 1;
let endIndex = indexOfAny(text, sentenceBreaks, partialSelection.end);
endIndex = endIndex === -1 ? text.length : endIndex + 1;
return {
text: text.substring(startIndex, endIndex).trim(),
range: { start: startIndex, end: endIndex }
};
};
// Define the processContent function
const processContent = (text, knownWordsSet, diacritics) => {
// Function to escape HTML characters to prevent injection
const escapeHTML = (str) =>
str.replace(/&/g, '&')
.replace(/</g, '<')
.replace(/>/g, '>')
.replace(/"/g, '"')
.replace(/'/g, ''');
// Apply diacritics based on the current state
if (diacritics === 'hidden') {
text = removeDiacritics(text); // Assuming removeDiacritics correctly removes diacritics
} else if (diacritics === 'red') {
// Wrap diacritics in a span to color them red
// This assumes diacritics are specific characters; adjust as needed
text = text.replace(/([\u064B-\u0652])/g, '<span class="red-diacritics">$1</span>');
}
// Split the text into words while keeping whitespace
const words = text.split(/(\s+)/);
// Process each word
const processed = words.map(word => {
// Remove punctuation for matching
const cleanWord = word.replace(/[.,\/#!$%\^&\*;:{}=\-_`~()؟۔]/g,"");
if (knownWordsSet.has(cleanWord)) {
// Wrap known words with a span for styling
return `<span class="known-word">${escapeHTML(word)}</span>`;
}
return `<span class="word">${escapeHTML(word)}</span>`;
}).join('');
return processed;
};
// handleWebViewMessage fonksiyonunu ekliyoruz
const handleWebViewMessage = useCallback((event) => {
try {
const { type, content, selection, x, y, action } = JSON.parse(event.nativeEvent.data);
if (type === 'wordTap') {
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, getFullSentence]);
const handleCopy = () => {
Clipboard.setString(tooltipContent); // Use Clipboard API
Alert.alert("Başarılı", "Cümle kopyalandı.");
setTooltipVisible(false);
};
const handleTranslate = () => {
setSelectedContent(tooltipContent);
setExplanationType('sentence');
bottomSheetModalRef.current?.present();
setActiveModal('sentence');
setTooltipVisible(false);
};
const formattedContent = useMemo(() => {
const content = item.content || item.description || '';
const plainText = content.replace(/<[^>]+>/g, '');
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;
});
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}>
<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 }}
/>
<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}
/>
{/* Bottom Sheet Modals */}
<BottomSheetModal
ref={bottomSheetModalRef}
index={0}
snapPoints={['50%', '90%']}
onDismiss={() => setActiveModal(null)}
>
<WordExplanationBox
content={selectedContent}
type={explanationType}
onClose={closeAllModals}
/>
</BottomSheetModal>
<BottomSheetModal
ref={settingsBottomSheetModalRef}
index={0}
snapPoints={['50%', '90%']}
onDismiss={() => setActiveModal(null)}
>
{/* Your settings modal content */}
<View style={styles.settingsContent}>
{/* Example: Font Size Controls */}
<View style={styles.fontSizeControls}>
<TouchableOpacity onPress={() => setFontSize(prev => Math.max(10, prev - 2))}>
<Ionicons name="remove-circle-outline" size={30} color={theme.primaryColor} />
</TouchableOpacity>
<Text style={{ fontSize: 18 }}>{fontSize}px</Text>
<TouchableOpacity onPress={() => setFontSize(prev => Math.min(40, prev + 2))}>
<Ionicons name="add-circle-outline" size={30} color={theme.primaryColor} />
</TouchableOpacity>
</View>
{/* Add more settings as needed */}
</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',
alignItems: 'center',
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,
},
popover: {
backgroundColor: 'white',
borderRadius: 8,
padding: 0,
shadowColor: "#000",
shadowOffset: {
width: 0,
height: 2,
},
shadowOpacity: 0.25,
shadowRadius: 3.84,
elevation: 5,
},
popoverContainer: {
width: SCREEN_WIDTH * 0.8,
maxWidth: 400,
padding: 12,
},
selectedText: {
fontSize: 14,
color: '#666',
marginBottom: 12,
lineHeight: 20,
textAlign: 'right',
},
tooltip: {
backgroundColor: 'white',
borderRadius: 8,
padding: 0,
},
tooltipStyle: {
padding: 0,
},
tooltipContainer: {
width: SCREEN_WIDTH * 0.8,
maxWidth: 400,
padding: 12,
},
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;
5. Additional Recommendations
a. Testing the Changes
After implementing the processContent function, thoroughly test your application to ensure:
- Known words are correctly highlighted.
- Diacritics are handled based on the selected state (normal, red, hidden).
- The WebView renders the content as expected.
- Interactions like word taps and text selections function correctly.
b. Error Handling
Consider adding more robust error handling within the processContent function and other parts of your component to gracefully handle unexpected inputs or states.
c. Performance Optimization
If dealing with large RSS feeds, processing the content might become performance-intensive. Consider optimizing the processContent function or processing the content in chunks if necessary.
Conclusion
The ReferenceError you encountered was due to the absence of the processContent function. By defining this function within your RSSReadScreen component and ensuring it's correctly integrated into your content formatting logic, you should resolve the error and enhance the functionality of your RSS reader application.
If you encounter further issues or have additional questions, feel free to ask!