// src/components/CustomText.tsx import React, {… · The Chat Archive
Explore / Programming // src/components/CustomText.tsx import React, { useContext } from 'react'; import {… Save Share Download ▾ Report// src/components/CustomText.tsx
import React, { useContext } from 'react';
import { Text, TextProps, StyleSheet, View, ActivityIndicator } from 'react-native';
import { useFonts, Poppins_400Regular, Poppins_700Bold } from '@expo-google-fonts/poppins';
import { ThemeContext } from '../theme/ThemeContext';
interface CustomTextProps extends TextProps {
bold?: boolean;
}
const CustomText: React.FC = ({ children, bold, style, ...props }) => {
const { themeObject } = useContext(ThemeContext);
const [fontsLoaded] = useFonts({
Poppins_400Regular,
Poppins_700Bold,
});
if (!fontsLoaded) {
return (
);
}
return (
<Text
style={[
bold ? styles.bold : styles.regular,
{ color: themeObject.text },
style,
]}
{...props}
>
{children}
);
};
const styles = StyleSheet.create({
loadingContainer: {
justifyContent: 'center',
alignItems: 'center',
},
regular: {
fontFamily: 'Poppins_400Regular',
},
bold: {
fontFamily: 'Poppins_700Bold',
},
});
export default CustomText; // src/screens/ChatListScreen.tsx
import React, { useContext, useEffect, useState, useCallback } from 'react';
import {
View,
FlatList,
Image,
TouchableOpacity,
StyleSheet,
ActivityIndicator,
Alert,
Dimensions,
SafeAreaView,
Platform,
StatusBar as RNStatusBar
} from 'react-native';
import { useNavigation, useIsFocused } from '@react-navigation/native';
import { Ionicons } from '@expo/vector-icons';
import { ChatContext, ChatWithLastMessage } from '../context/ChatContext'; // Import ChatContext
import CustomText from '../components/CustomText';
const ChatListScreen = () => {
const navigation = useNavigation();
const { chats, deleteChat, deleteAllChats } = useContext(ChatContext); // Consume context
const [sortedChats, setSortedChats] = useState<ChatWithLastMessage[]>([]);
const [loading, setLoading] = useState(true);
const isFocused = useIsFocused();
useEffect(() => {
const sortChats = () => {
const sorted = [...chats].sort(
(a, b) => (b.lastMessageTimestamp || 0) - (a.lastMessageTimestamp || 0)
);
setSortedChats(sorted);
setLoading(false);
};
sortChats();
}, [chats, isFocused]);
const handleDeleteChat = useCallback(
(chatId: string) => {
deleteChat(chatId);
},
[deleteChat]
);
const renderChatItem = useCallback(
({ item }: { item: ChatWithLastMessage }) => (
<TouchableOpacity
style={styles.chatItem}
onPress={() =>
navigation.navigate('Chat', { chatId: item.id, figure: item.figure })
}
>
<Image source={{ uri: item.figure.image }} style={styles.avatar} />
{item.figure.name}
{item.lastMessage}
{timeAgo(item.lastMessageTimestamp)}
<TouchableOpacity onPress={() => handleDeleteChat(item.id)} style={styles.deleteButton}>
),
[navigation, handleDeleteChat]
);
const keyExtractor = useCallback((item: ChatWithLastMessage) => item.id, []);
const timeAgo = (timestamp: number | undefined) => {
if (!timestamp) return '';
const now = Date.now();
const diff = Math.floor((now - timestamp) / 60000); // difference in minutes
if (diff < 1) return ;
if (diff < 60) return ;
const hours = Math.floor(diff / 60);
if (hours < 24) return ;
const days = Math.floor(hours / 24);
return ;
};
Assistant2024-10-06 23:58 UTC Copy response
Copy first prompt
Details
Provider OpenAI
Model provenance As recorded by source dataset
Turns 1 (2 messages)
Language —
Conversation date Oct 6, 2024
Added to archive Nov 16, 2026
ID 01m7h41wnd433q065w0g08z7c5Source & license Imported from WildChat-4.8M (AI2) (source ). Imported records earn no Research Points.
Upstream record: 2f673271484d48da24318279a34d6fde
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
Şimdi
${diff} dk önce
${hours} saat önce
${days} gün önce
if (loading) {
return (
);
}
return (
Sohbetlerim
{chats.length > 0 && (
)}
{sortedChats.length === 0 ? (
Hiç sohbetiniz yok! Yeni bir sohbet başlatın.
) : (
)}
<TouchableOpacity
style={styles.fab}
onPress={() => navigation.navigate('Home')}
>
);
};
const { width, height } = Dimensions.get('window');
const styles = StyleSheet.create({
safeArea: {
flex: 1,
backgroundColor: '#F8F8F8',
paddingTop: Platform.OS === 'android' ? RNStatusBar.currentHeight : 0,
},
container: {
flex: 1,
backgroundColor: '#F8F8F8',
paddingHorizontal: 15,
},
loadingContainer: {
flex: 1,
justifyContent: 'center',
alignItems: 'center',
backgroundColor: '#F8F8F8',
},
header: {
flexDirection: 'row',
justifyContent: 'space-between',
alignItems: 'center',
paddingVertical: 20,
borderBottomWidth: 1,
borderBottomColor: '#E0E0E0',
},
title: {
fontSize: 28,
color: '#333',
fontFamily: 'Poppins_400Regular',
},
deleteAllButton: {
padding: 5,
},
chatList: {
paddingTop: 10,
paddingBottom: 80,
},
chatItem: {
flexDirection: 'row',
alignItems: 'center',
backgroundColor: '#FFFFFF',
borderRadius: 12,
marginBottom: 12,
marginHorizontal: 3,
shadowColor: "#000",
shadowOffset: { width: 0, height: 2 },
shadowOpacity: 0.1,
shadowRadius: 4,
elevation: 3,
padding: 20,
},
avatar: {
width: 60,
height: 60,
borderRadius: 30,
marginRight: 16,
},
chatInfo: {
flex: 1,
},
chatName: {
fontSize: 18,
color: '#333',
fontFamily: 'Poppins_700Bold',
},
chatLastMessage: {
fontSize: 14,
color: '#666',
marginTop: 4,
fontFamily: 'Poppins_400Regular',
},
chatDate: {
fontSize: 12,
color: '#999',
marginTop: 4,
fontFamily: 'Poppins_400Regular',
},
deleteButton: {
padding: 8,
},
fab: {
position: 'absolute',
width: 56,
height: 56,
backgroundColor: '#007AFF',
borderRadius: 28,
justifyContent: 'center',
alignItems: 'center',
right: 16,
bottom: 16,
shadowColor: "#000",
shadowOffset: { width: 0, height: 2 },
shadowOpacity: 0.25,
shadowRadius: 3.84,
elevation: 5,
},
emptyContainer: {
flex: 1,
justifyContent: 'center',
alignItems: 'center',
paddingHorizontal: 32,
},
emptyText: {
fontSize: 16,
color: '#666',
textAlign: 'center',
fontFamily: 'Poppins_400Regular',
},
});
export default ChatListScreen; // src/context/ChatContext.tsx
import React, { createContext, useState, useEffect, useCallback } from 'react';
import AsyncStorage from '@react-native-async-storage/async-storage';
import { Chat, Message } from '../types/types';
interface ChatWithLastMessage extends Chat {
lastMessage?: string;
lastMessageTimestamp?: number;
}
interface ChatContextProps {
chats: ChatWithLastMessage[];
addChat: (chat: Chat, message: Message) => Promise;
updateChat: (chatId: string, message: Message) => Promise;
deleteChat: (chatId: string) => Promise;
deleteAllChats: () => Promise;
}
export const ChatContext = createContext({
chats: [],
addChat: async () => {},
updateChat: async () => {},
deleteChat: async () => {},
deleteAllChats: async () => {},
});
export const ChatProvider: React.FC = ({ children }) => {
const [chats, setChats] = useState<ChatWithLastMessage[]>([]);
// Load chats from AsyncStorage on mount
useEffect(() => {
const loadChats = async () => {
try {
const chatsData = await AsyncStorage.getItem('chats');
const chatsList: Chat[] = chatsData ? JSON.parse(chatsData) : [];
const chatsWithMessages: ChatWithLastMessage[] = await Promise.all(
chatsList.map(async (chat) => {
const messagesData = await AsyncStorage.getItem(`chat_${chat.id}_messages`);
const messages: Message[] = messagesData ? JSON.parse(messagesData) : [];
const lastMessage = messages[messages.length - 1]?.text || '';
const lastTimestamp = messages[messages.length - 1]?.timestamp || chat.createdAt;
return {
...chat,
lastMessage,
lastMessageTimestamp: lastTimestamp,
};
})
);
const sortedChats = chatsWithMessages.sort(
(a, b) => (b.lastMessageTimestamp || 0) - (a.lastMessageTimestamp || 0)
);
setChats(sortedChats);
} catch (error) {
console.error('Error loading chats:', error);
}
};
loadChats();
// Add a new chat
const addChat = useCallback(async (chat: Chat, message: Message) => {
try {
const newChat: ChatWithLastMessage = {
...chat,
lastMessage: message.text,
lastMessageTimestamp: message.timestamp,
};
const updatedChats = [...chats, newChat];
setChats(updatedChats);
await AsyncStorage.setItem('chats', JSON.stringify(updatedChats));
await AsyncStorage.setItem(chat_${chat.id}_messages, JSON.stringify([message]));
} catch (error) {
console.error('Error adding chat:', error);
}
}, [chats]);
// Update an existing chat with a new message
const updateChat = useCallback(async (chatId: string, message: Message) => {
try {
// Retrieve existing messages
const messagesData = await AsyncStorage.getItem(chat_${chatId}_messages);
const messages: Message[] = messagesData ? JSON.parse(messagesData) : [];
const updatedMessages = [...messages, message];
await AsyncStorage.setItem(chat_${chatId}_messages, JSON.stringify(updatedMessages));
// Update chat's last message and timestamp
setChats((prevChats) => {
const updatedChats = prevChats.map((chat) => {
if (chat.id === chatId) {
return {
...chat,
lastMessage: message.text,
lastMessageTimestamp: message.timestamp,
};
}
return chat;
}).sort((a, b) => (b.lastMessageTimestamp || 0) - (a.lastMessageTimestamp || 0));
// Persist updated chats
AsyncStorage.setItem('chats', JSON.stringify(updatedChats)).catch((err) =>
console.error('Error updating chats in AsyncStorage:', err)
);
return updatedChats;
});
} catch (error) {
console.error('Error updating chat:', error);
}
// Delete a specific chat
const deleteChat = useCallback(async (chatId: string) => {
try {
const updatedChats = chats.filter((chat) => chat.id !== chatId);
setChats(updatedChats);
await AsyncStorage.setItem('chats', JSON.stringify(updatedChats));
await AsyncStorage.removeItem(chat_${chatId}_messages);
} catch (error) {
console.error('Error deleting chat:', error);
}
}, [chats]);
// Delete all chats
const deleteAllChats = useCallback(async () => {
try {
setChats([]);
await AsyncStorage.removeItem('chats');
const keys = await AsyncStorage.getAllKeys();
const chatMessageKeys = keys.filter(
(key) => key.startsWith('chat_') && key.endsWith('_messages')
);
await AsyncStorage.multiRemove(chatMessageKeys);
} catch (error) {
console.error('Error deleting all chats:', error);
}
}, []);
return (
<ChatContext.Provider value={{ chats, addChat, updateChat, deleteChat, deleteAllChats }}>
{children} {/* Ensure only children are rendered */}
</ChatContext.Provider>
);
}; // src/screens/ChatScreen.tsx
import React, { useState, useEffect, useRef, useCallback, useContext } from 'react';
import {
View,
FlatList,
Image,
TouchableOpacity,
TextInput,
StyleSheet,
KeyboardAvoidingView,
Platform,
Dimensions,
ScrollView,
Alert,
ActivityIndicator,
} from 'react-native';
import { useNavigation, useRoute } from '@react-navigation/native';
import LottieView from 'lottie-react-native';
import Markdown from 'react-native-markdown-display';
import { HistoricalFigure, Message } from '../types/types';
import { fetchAIResponse } from '../services/openaiService';
import uuid from 'react-native-uuid';
import MessageItem from '../components/MessageItem';
import { Ionicons } from '@expo/vector-icons';
import CustomText from '../components/CustomText';
import * as Clipboard from 'expo-clipboard';
import { ChatContext } from '../context/ChatContext';
interface RouteParams {
chatId: string;
figure: HistoricalFigure;
}
interface APIMessage {
role: 'system' | 'user' | 'assistant';
content: string;
}
const { width, height } = Dimensions.get('window');
const ChatScreen = () => {
const navigation = useNavigation();
const route = useRoute();
const { chatId, figure } = route.params as RouteParams;
const { updateChat, addChat, chats } = useContext(ChatContext);
const [messages, setMessages] = useState<Message[]>([]);
const [inputText, setInputText] = useState('');
const [isTyping, setIsTyping] = useState(false);
const [followUpQuestions, setFollowUpQuestions] = useState<string[]>([]);
const [isLoading, setIsLoading] = useState(false);
const flatListRef = useRef(null);
// Fallback follow-up questions
const sampleFollowUpQuestions = [
'Bu konuda daha fazla detay öğrenmek ister misiniz?',
'Başka ne hakkında konuşmak istersiniz?',
'Farklı bir perspektif mi istiyorsunuz?',
];
useEffect(() => {
const loadMessages = async () => {
try {
setIsLoading(true);
setMessages([]);
setFollowUpQuestions([]);
setIsTyping(false);
const messagesData = await AsyncStorage.getItem(`chat_${chatId}_messages`);
let msgs: Message[] = messagesData ? JSON.parse(messagesData) : [];
if (msgs.length === 0) {
const conversationStarters = [
'Merhaba! Bugün nasıl yardımcı olabilirim?',
`${figure.name} hakkında ne öğrenmek istersiniz?`,
`${figure.name} ile ilgili herhangi bir sorunuz var mı?`,
];
const starterMessages = conversationStarters.map((starter) => ({
id: uuid.v4().toString(),
text: starter,
isUser: false,
timestamp: Date.now(),
}));
msgs = starterMessages;
// Initialize the chat in context if it's new
const newChat = {
id: chatId,
figure: figure, // Assuming `figure` includes necessary details
createdAt: Date.now(),
};
await addChat(newChat, starterMessages[0]); // Add the first starter message
}
setMessages(msgs);
setIsLoading(false);
// Scroll to latest message
setTimeout(() => {
flatListRef.current?.scrollToOffset({ animated: true, offset: 0 });
}, 100);
} catch (error) {
console.error('Error loading messages:', error);
setIsLoading(false);
}
};
loadMessages();
}, [chatId, figure.name, addChat, figure]);
const saveMessages = useCallback(async (updatedMessages: Message[]) => {
try {
await AsyncStorage.setItem(chat_${chatId}_messages, JSON.stringify(updatedMessages));
} catch (error) {
console.error('Error saving messages:', error);
}
}, [chatId]);
const generateFollowUpQuestions = useCallback(async (aiResponse: string) => {
try {
const prompt = Yapay zekanın aşağıdaki yanıtına dayanarak sadece üç tane takip sorusu oluştur. Sadece sorular olmalı, açıklayıcı metin veya ek bilgiler eklemeyin.\n\nYanıt: "${aiResponse}"\n\nTakip Soruları:;
const aiMessages: APIMessage[] = [
{
role: 'system',
content: 'Sen, yardımsever ve bilgilendirici bir yapay zeka asistanısın.',
},
{
role: 'user',
content: prompt,
},
];
const followUpResponse = await fetchAIResponse(aiMessages);
const rawQuestions = followUpResponse
.split('\n')
.map((q) => q.trim())
.filter((q) => q.length > 0)
.slice(0, 3);
const cleanQuestion = (question: string) => {
return question.replace(/^\d+\.\s*/, '');
};
const cleanedQuestions = rawQuestions.map(cleanQuestion);
if (cleanedQuestions.length < 3) {
setFollowUpQuestions([
...cleanedQuestions,
...sampleFollowUpQuestions.slice(0, 3 - cleanedQuestions.length),
]);
} else {
setFollowUpQuestions(cleanedQuestions);
}
} catch (error) {
console.error('Error generating follow-up questions:', error);
setFollowUpQuestions(sampleFollowUpQuestions);
}
const sendMessage = useCallback(
async (text?: string) => {
const messageText = text !== undefined ? text : inputText;
if (messageText.trim() === '') return;
const userMessage: Message = {
id: uuid.v4().toString(),
text: messageText,
isUser: true,
timestamp: Date.now(),
};
const updatedMessages = [userMessage, ...messages];
setMessages(updatedMessages);
setInputText('');
setIsTyping(true);
setFollowUpQuestions([]); // Clear follow-up questions
await saveMessages(updatedMessages);
// Update the chat's last message and timestamp via context
await updateChat(chatId, userMessage);
const apiMessages: APIMessage[] = [
{
role: 'system',
content: figure.systemPrompt,
},
...updatedMessages
.slice()
.reverse()
.map((msg) => ({
role: msg.isUser ? 'user' : 'assistant',
content: msg.text,
})),
];
console.log('==== Sending Messages to AI ====');
apiMessages.forEach((msg, index) => {
console.log(`Message ${index + 1}: [${msg.role}] ${msg.content}`);
});
console.log('===============================');
try {
const aiResponse = await fetchAIResponse(apiMessages);
const aiMessage: Message = {
id: uuid.v4().toString(),
text: aiResponse,
isUser: false,
timestamp: Date.now(),
};
const newMessages = [aiMessage, ...updatedMessages];
setMessages(newMessages);
await saveMessages(newMessages);
// Update chat's last message and timestamp via context
await updateChat(chatId, aiMessage);
await generateFollowUpQuestions(aiResponse);
} catch (error) {
console.error('Error fetching AI response:', error);
Alert.alert('Hata', 'Yapay zeka yanıtı alınırken bir hata oluştu. Lütfen daha sonra tekrar deneyin.');
} finally {
setIsTyping(false);
// Scroll to the latest message
flatListRef.current?.scrollToOffset({ animated: true, offset: 0 });
}
},
[
inputText,
messages,
figure.systemPrompt,
saveMessages,
generateFollowUpQuestions,
updateChat,
chatId,
]
const handleFollowUpPress = (question: string) => {
sendMessage(question);
};
const renderMessageItem = useCallback(
({ item }: { item: Message }) => (
<MessageItem
message={item}
onLongPress={() => {
Clipboard.setString(item.text);
Alert.alert('Kopyalandı', 'Mesaj panoya kopyalandı!');
}}
/>
),
[]
);
const keyExtractor = useCallback((item: Message) => item.id, []);
useEffect(() => {
if (messages.length > 0) {
flatListRef.current?.scrollToOffset({ animated: true, offset: 0 });
}
}, [messages]);
return (
<KeyboardAvoidingView
style={styles.container}
behavior={Platform.OS === 'ios' ? 'padding' : undefined}
keyboardVerticalOffset={Platform.OS === 'ios' ? 60 : 0}
>
<TouchableOpacity onPress={() => navigation.goBack()} style={styles.backButton}>
<Image source={{ uri: figure.image }} style={styles.headerAvatar} />
{figure.name}
{figure.description}
{isLoading ? (
<View style={styles.loadingContainer}>
<ActivityIndicator size="large" color="#007AFF" />
</View>
) : (
<FlatList
ref={flatListRef}
data={messages}
renderItem={renderMessageItem}
keyExtractor={keyExtractor}
style={styles.messageList}
contentContainerStyle={styles.messageListContent}
inverted
/>
)}
{isTyping && (
<View style={styles.typingIndicator}>
<LottieView
source={require('../../assets/typing-animation.json')}
autoPlay
loop
style={styles.typingAnimation}
/>
</View>
)}
{followUpQuestions.length > 0 && (
<View style={styles.followUpContainer}>
<CustomText bold style={styles.followUpTitle}>
Takip Soruları:
</CustomText>
<ScrollView horizontal showsHorizontalScrollIndicator={false}>
{followUpQuestions.map((question, index) => (
<TouchableOpacity
key={index}
style={styles.followUpButton}
onPress={() => handleFollowUpPress(question)}
>
<CustomText style={styles.followUpText}>{question}</CustomText>
</TouchableOpacity>
))}
</ScrollView>
</View>
)}
<View style={styles.inputContainer}>
<TextInput
style={styles.input}
value={inputText}
onChangeText={setInputText}
placeholder="Mesajınızı yazın..."
onSubmitEditing={() => sendMessage()}
returnKeyType="send"
/>
<TouchableOpacity onPress={() => sendMessage()} style={styles.sendButton}>
<Ionicons name="send" size={24} color="#fff" />
</TouchableOpacity>
</View>
</KeyboardAvoidingView>
const styles = StyleSheet.create({
container: {
flex: 1,
backgroundColor: '#F5F5F5',
},
header: {
flexDirection: 'row',
alignItems: 'center',
padding: 15,
paddingTop: Platform.OS === 'ios' ? 50 : 30,
borderBottomWidth: 1,
borderBottomColor: '#E0E0E0',
backgroundColor: '#FFFFFF',
},
backButton: {
marginRight: 10,
},
headerAvatar: {
width: 40,
height: 40,
borderRadius: 20,
marginRight: 10,
},
headerInfo: {
flex: 1,
},
headerName: {
fontSize: 18,
color: '#000000',
fontFamily: 'Poppins_700Bold',
},
headerDescription: {
fontSize: 14,
color: '#666666',
marginTop: 2,
fontFamily: 'Poppins_400Regular',
},
messageList: {
flex: 1,
backgroundColor: '#F5F5F5',
},
messageListContent: {
paddingVertical: 10, // Reduced vertical padding
paddingHorizontal: 15,
},
typingIndicator: {
position: 'absolute',
bottom: 70,
left: 20,
},
typingAnimation: {
width: 80,
height: 40,
},
followUpContainer: {
padding: 10,
backgroundColor: '#FFFFFF',
borderTopWidth: 1,
borderTopColor: '#E0E0E0',
},
followUpTitle: {
fontSize: 16,
marginBottom: 5,
fontFamily: 'Poppins_700Bold',
color: '#000',
},
followUpButton: {
backgroundColor: '#E0E0E0',
borderRadius: 15,
paddingVertical: 8,
paddingHorizontal: 12,
marginRight: 10,
},
followUpText: {
fontFamily: 'Poppins_400Regular',
color: '#000',
},
inputContainer: {
flexDirection: 'row',
alignItems: 'center',
padding: 10,
backgroundColor: '#FFFFFF',
borderTopWidth: 1,
borderTopColor: '#E0E0E0',
},
input: {
flex: 1,
height: 40,
borderRadius: 20,
backgroundColor: '#F0F0F0',
paddingHorizontal: 15,
marginRight: 10,
fontFamily: 'Poppins_400Regular',
},
sendButton: {
backgroundColor: '#007AFF',
borderRadius: 20,
padding: 10,
},
loadingContainer: {
flex: 1,
alignItems: 'center',
justifyContent: 'center',
},
});
export default ChatScreen; hatayı bul bakalım ERROR Warning: Error: Text strings must be rendered within a component.
This error is located at:
in ChatProvider (created by App)
in App (created by withDevTools(App))
in withDevTools(App)
in RCTView (created by View)
in View (created by AppContainer)
in RCTView (created by View)
in View (created by AppContainer)
in AppContainer
in main(RootComponent), js engine: hermes
// src/screens/HomeScreen.tsx
import React, { useEffect, useState, useCallback } from 'react';
import {
View,
FlatList,
Image,
TouchableOpacity,
StyleSheet,
Alert,
SafeAreaView,
Platform,
StatusBar as RNStatusBar
} from 'react-native';
import { StatusBar } from 'expo-status-bar';
import { useNavigation } from '@react-navigation/native';
import { HistoricalFigure, Chat, Message } from '../types/types';
import { db } from '../services/firebaseConfig';
import { collection, getDocs } from 'firebase/firestore';
import AsyncStorage from '@react-native-async-storage/async-storage';
import uuid from 'react-native-uuid';
import CustomText from '../components/CustomText';
import { Ionicons } from '@expo/vector-icons';
const HomeScreen = () => {
const navigation = useNavigation();
const [historicalFigures, setHistoricalFigures] = useState<HistoricalFigure[]>([]);
const [loading, setLoading] = useState(true); // Initially loading
useEffect(() => {
const fetchFigures = async () => {
try {
const figuresCollection = collection(db, 'figures');
const figuresSnapshot = await getDocs(figuresCollection);
const figuresList: HistoricalFigure[] = figuresSnapshot.docs.map(doc => {
const data = doc.data();
return {
id: doc.id,
name: data.name,
image: data.image,
systemPrompt: data.systemPrompt,
description: data.description || "",
} as HistoricalFigure;
});
setHistoricalFigures(figuresList);
} catch (error) {
console.error('Error fetching figures:', error);
Alert.alert("Hata", "Figürler yüklenirken bir hata oluştu.");
} finally {
setLoading(false); // Stop loading after fetch
}
};
}, []); // Ensures it runs only once
const renderFigureItem = useCallback(({ item }: { item: HistoricalFigure }) => (
<TouchableOpacity
style={styles.figureItem}
onPress={() => startChat(item)}
>
<Image source={{ uri: item.image }} style={styles.avatar} />
{item.name}
{item.description}
), []);
const startChat = async (figure: HistoricalFigure) => {
const chatId = uuid.v4().toString();
const newChat: Chat = {
id: chatId,
figure: {
...figure,
description: figure.description || "",
},
createdAt: Date.now(),
};
const initialMessage: Message = {
id: uuid.v4().toString(),
text: figure.description || "Açıklama mevcut değil.",
isUser: false,
timestamp: Date.now(),
};
try {
const existingChats = await AsyncStorage.getItem('chats');
const chats: Chat[] = existingChats ? JSON.parse(existingChats) : [];
const updatedChats = [...chats, newChat];
await AsyncStorage.setItem('chats', JSON.stringify(updatedChats));
const existingMessages = await AsyncStorage.getItem(`chat_${chatId}_messages`);
const messages: Message[] = existingMessages ? JSON.parse(existingMessages) : [];
const updatedMessages = [...messages, initialMessage];
await AsyncStorage.setItem(`chat_${chatId}_messages`, JSON.stringify(updatedMessages));
navigation.navigate('Chat', { chatId, figure });
} catch (error) {
console.error('Error starting chat:', error);
Alert.alert("Hata", "Sohbet başlatılırken bir hata oluştu.");
}
const keyExtractor = useCallback((item: HistoricalFigure) => item.id, []);
return (
Tarihi Karakterler
{loading ? (
// Optional: Replace with a different loading UI or remove entirely
// For this example, we'll remove the loader
) : (
)}
);
};
const styles = StyleSheet.create({
safeArea: {
flex: 1,
backgroundColor: '#F5F5F5',
paddingTop: Platform.OS === 'android' ? RNStatusBar.currentHeight : 0,
},
container: {
flex: 1,
backgroundColor: '#F5F5F5',
paddingHorizontal: 15,
},
loadingContainer: {
flex: 1,
justifyContent: 'center',
alignItems: 'center',
backgroundColor: '#F5F5F5',
},
loadingPlaceholder: {
flex: 1,
// Optional styling for placeholder
},
header: {
flexDirection: 'row',
justifyContent: 'space-between',
alignItems: 'center',
paddingVertical: 20,
borderBottomWidth: 1,
borderBottomColor: '#E0E0E0',
},
title: {
fontSize: 28,
color: '#333',
fontFamily: 'Poppins_700Bold',
},
infoButton: {
padding: 5,
},
figureList: {
paddingTop: 10,
},
figureItem: {
flexDirection: 'row',
alignItems: 'center',
backgroundColor: '#FFFFFF',
borderRadius: 12,
marginBottom: 15,
padding: 20,
shadowColor: "#000",
shadowOffset: {
width: 0,
height: 2,
},
shadowOpacity: 0.1,
shadowRadius: 3.84,
elevation: 5,
marginHorizontal:3,
},
avatar: {
width: 60,
height: 60,
borderRadius: 30,
marginRight: 15,
},
figureInfo: {
flex: 1,
},
figureName: {
fontSize: 18,
color: '#333',
fontFamily: 'Poppins_700Bold',
},
figureDescription: {
fontSize: 14,
color: '#666',
marginTop: 4,
fontFamily: 'Poppins_400Regular',
},
});
export default HomeScreen; // App.tsx
import React from 'react';
import { NavigationContainer, CommonActions } from '@react-navigation/native';
import { createStackNavigator } from '@react-navigation/stack';
import { createBottomTabNavigator } from '@react-navigation/bottom-tabs';
import { View, StyleSheet, Platform, TouchableOpacity, Keyboard } from 'react-native';
import HomeScreen from './src/screens/HomeScreen';
import ChatListScreen from './src/screens/ChatListScreen';
import ChatScreen from './src/screens/ChatScreen';
import { Ionicons } from '@expo/vector-icons';
import CustomText from './src/components/CustomText';
import { ChatProvider } from './src/context/ChatContext'; // Import ChatProvider
const Stack = createStackNavigator();
const Tab = createBottomTabNavigator();
const ChatStack = () => (
<Stack.Navigator
initialRouteName="ChatList"
screenOptions={{
headerShown: false,
}}
<Stack.Screen name="ChatList" component={ChatListScreen} />
<Stack.Screen name="Chat" component={ChatScreen} />
const FiguresStack = () => (
<Stack.Navigator
initialRouteName="Home"
screenOptions={{
headerShown: false,
}}
<Stack.Screen name="Home" component={HomeScreen} />
const TabBar = ({ state, descriptors, navigation }) => {
const [isKeyboardVisible, setKeyboardVisible] = React.useState(false);
React.useEffect(() => {
const showSubscription = Keyboard.addListener('keyboardDidShow', () => {
setKeyboardVisible(true);
});
const hideSubscription = Keyboard.addListener('keyboardDidHide', () => {
setKeyboardVisible(false);
});
return () => {
showSubscription.remove();
hideSubscription.remove();
};
if (isKeyboardVisible) {
return null; // Hide the TabBar when the keyboard is visible
}
return (
{state.routes.map((route, index) => {
const { options } = descriptors[route.key];
const label =
options.tabBarLabel !== undefined
? options.tabBarLabel
: options.title !== undefined
? options.title
: route.name;
const isFocused = state.index === index;
const onPress = () => {
const event = navigation.emit({
type: 'tabPress',
target: route.key,
canPreventDefault: true,
});
if (!isFocused && !event.defaultPrevented) {
navigation.navigate(route.name);
}
};
// Render the icon directly without extracting 'name'
const icon = options.tabBarIcon
? options.tabBarIcon({
focused: isFocused,
color: isFocused ? '#007AFF' : '#8E8E93',
size: 24,
})
: null;
return (
<TouchableOpacity
key={route.key}
accessibilityRole="button"
accessibilityState={isFocused ? { selected: true } : {}}
accessibilityLabel={options.tabBarAccessibilityLabel}
testID={options.tabBarTestID}
onPress={onPress}
style={styles.tabItem}
>
{icon}
<CustomText style={[styles.tabLabel, { color: isFocused ? '#007AFF' : '#8E8E93' }]}>
{label}
</CustomText>
</TouchableOpacity>
);
})}
</View>
const App = () => {
return (
{/* Wrap NavigationContainer with ChatProvider */}
<Tab.Navigator
initialRouteName="Figures"
tabBar={(props) => <TabBar {...props} />}
screenOptions={({ route }) => ({
headerShown: false,
tabBarIcon: ({ focused, color, size }) => {
let iconName = '';
if (route.name === 'Figures') {
iconName = focused ? 'people' : 'people-outline';
} else if (route.name === 'Chats') {
iconName = focused ? 'chatbubbles' : 'chatbubbles-outline';
}
return ;
},
})}
>
<Tab.Screen
name="Figures"
component={FiguresStack}
options={{
tabBarLabel: 'Karakterler',
}}
/>
<Tab.Screen
name="Chats"
component={ChatStack}
options={{
tabBarLabel: 'Sohbetler',
}}
listeners={({ navigation, route }) => ({
tabPress: e => {
// Prevent default behavior
e.preventDefault();
// Reset the navigation stack to ChatList
navigation.dispatch(
CommonActions.reset({
index: 0,
routes: [{ name: 'Chats', state: { routes: [{ name: 'ChatList' }] } }],
})
);
},
})}
/>
</Tab.Navigator>
</NavigationContainer>
</ChatProvider>
const styles = StyleSheet.create({
tabContainer: {
flexDirection: 'row',
backgroundColor: '#F8F8F8',
borderTopWidth: 1,
borderTopColor: '#E0E0E0',
paddingBottom: Platform.OS === 'ios' ? 20 : 10,
paddingTop: 10,
},
tabItem: {
flex: 1,
alignItems: 'center',
justifyContent: 'center',
},
tabLabel: {
fontSize: 12,
marginTop: 3,
fontFamily: 'Poppins_400Regular',
},
});
The error message you're encountering:
Warning: Error: Text strings must be rendered within a <Text> component.
indicates that somewhere in your component tree, a text string is being rendered directly without being wrapped inside a <Text> component. Given that the error location points to ChatProvider, we need to inspect components associated with it meticulously.
Potential Causes and Solutions
Inspect All Child Components of ChatProvider
Since the error points to ChatProvider, it's essential to ensure that none of its child components are rendering text strings directly. Common places to check include:
MessageItem Component:
While you didn't provide the code for MessageItem, it's a common place where such errors can occur. Ensure that any text within MessageItem is wrapped inside a <Text> or your custom <CustomText> component.
Example Correction:
// src/components/MessageItem.tsx
import React from 'react';
import { View, TouchableOpacity, StyleSheet } from 'react-native';
import CustomText from './CustomText';
interface MessageItemProps {
message: Message;
onLongPress: () => void;
}
const MessageItem: React.FC<MessageItemProps> = ({ message, onLongPress }) => {
return (
<TouchableOpacity onLongPress={onLongPress} style={styles.messageContainer}>
<CustomText style={message.isUser ? styles.userText : styles.aiText}>
{message.text}
</CustomText>
</TouchableOpacity>
);
};
const styles = StyleSheet.create({
messageContainer: {
marginVertical: 5,
padding: 10,
borderRadius: 10,
backgroundColor: '#e1ffc7',
},
userText: {
color: '#000',
},
aiText: {
color: '#555',
},
});
export default MessageItem;
Other Custom Components:
Ensure that all custom components used within ChatProvider (like CustomText, headers, footers, etc.) correctly encapsulate text within <Text> or <CustomText> components.
Review ChatProvider Implementation
Ensure that ChatProvider doesn't unintentionally render any text directly. Based on the provided code, ChatProvider seems correctly implemented:
export const ChatProvider: React.FC = ({ children }) => {
const [chats, setChats] = useState<ChatWithLastMessage[]>([]);
// ... other logic
return (
<ChatContext.Provider value={{ chats, addChat, updateChat, deleteChat, deleteAllChats }}>
{children}
</ChatContext.Provider>
);
};
Ensure No Direct Text Rendering:
Make sure there are no accidental text strings inside ChatProvider, such as:
return (
<ChatContext.Provider value={{...}}>
"Some text" {/* This should be wrapped inside a <Text> component */}
{children}
</ChatContext.Provider>
);
Check All JSX Elements for Proper Text Wrapping
Go through all your JSX return statements to ensure that any text is enclosed within <Text> or <CustomText> components. Common pitfalls include:
Directly placing text inside <View>, <TouchableOpacity>, or any other non-text components.
Missing closing tags that might inadvertently cause plain text to be rendered.
Example of an Incorrect Implementation:
<View>
Hello World!
</View>
Correct Implementation:
<View>
<Text>Hello World!</Text>
</View>
Verify CustomText Component
Your CustomText component seems correctly implemented by wrapping its children inside a <Text> component. However, ensure that:
No Direct Strings in Props: When using CustomText, avoid passing strings as props that aren't meant to be rendered.
Example of Correct Usage:
<CustomText bold style={styles.title}>Sohbetlerim</CustomText>
Check Navigation and Tab Setup
Ensure that your navigation setup doesn't inadvertently render strings directly. In your App.tsx, the custom TabBar correctly wraps labels inside CustomText. However, double-check for any unintended string rendering.
Example of Potential Issue in TabBar:
return (
<TouchableOpacity>
{icon}
Some Label {/* This should be wrapped inside a <Text> or <CustomText> */}
</TouchableOpacity>
);
Correction:
return (
<TouchableOpacity>
{icon}
<CustomText style={styles.tabLabel}>{label}</CustomText>
</TouchableOpacity>
);
Auxiliary Components and Services
If you have other components or services (like openaiService, firebaseConfig, etc.), ensure they don't inadvertently return or render strings directly within JSX.
Use Debugging Tools
React Native Debugger: Use debugging tools to inspect the component tree and identify where the string is being rendered directly.
Error Boundaries: Implement error boundaries to catch and provide more context around rendering errors.
Final Steps
If after thorough inspection the issue persists:
Isolate Components: Temporarily remove or comment out components within ChatProvider to isolate which one is causing the issue.
Incremental Testing: Gradually add components back to identify the culprit.
Review Recent Changes: If this error started after recent code changes, revisit those parts for potential mistakes.
Conclusion
The error arises because a text string is being rendered outside of a <Text> component within the ChatProvider's component tree. By meticulously inspecting each component, especially custom ones like MessageItem, and ensuring all text is properly encapsulated within <Text> or <CustomText>, you can resolve this issue.
If you continue to face challenges, consider providing the code for all custom components (like MessageItem) and any other parts of the app that might be involved in the rendering process. This will allow for a more targeted diagnosis and solution.
Copy first response
Not yet included in a published release.