// src/screens/ChatScreen.tsx import React, { useState… · The Chat Archive
Explore / Programming // src/screens/ChatScreen.tsx import React, { useState, useEffect, useRef, useCallback }… Save Share Download ▾ Report// src/screens/ChatScreen.tsx
import React, { useState, useEffect, useRef, useCallback } from 'react';
import {
View,
FlatList,
Image,
TouchableOpacity,
TextInput,
StyleSheet,
KeyboardAvoidingView,
Platform,
Dimensions,
ScrollView,
Alert,
ActivityIndicator, // For loading indicator
} from 'react-native';
import { useNavigation, useRoute } from '@react-navigation/native';
import LottieView from 'lottie-react-native';
import Markdown from 'react-native-markdown-display'; // Markdown support
import { HistoricalFigure, Message } from '../types/types';
import { fetchAIResponse } from '../services/openaiService';
import AsyncStorage from '@react-native-async-storage/async-storage';
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';
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 [messages, setMessages] = useState<Message[]>([]);
const [inputText, setInputText] = useState('');
const [isTyping, setIsTyping] = useState(false);
const [followUpQuestions, setFollowUpQuestions] = useState<string[]>([]);
const [isLoading, setIsLoading] = useState(false); // Loading state
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);
// Clear previous messages and follow-up questions
setMessages([]);
setFollowUpQuestions([]);
setIsTyping(false);
Show full message · 839 lines Assistant2024-10-06 23:43 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 01m7h41wndv6s777nq945493rxSource & license Imported from WildChat-4.8M (AI2) (source ). Imported records earn no Research Points.
Upstream record: cc226cc485234f3f1a96a4448b25c71f
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
const messagesData = await AsyncStorage.getItem(`chat_${chatId}_messages`);
let msgs: Message[] = messagesData ? JSON.parse(messagesData) : [];
// If no messages, add initial messages
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, // Initial messages are from AI
timestamp: Date.now(),
}));
msgs = starterMessages;
await AsyncStorage.setItem(`chat_${chatId}_messages`, JSON.stringify(msgs));
}
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]);
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
}
];
code Copy code
const followUpResponse = await fetchAIResponse(aiMessages);
// Assume each question is on a new line
const rawQuestions = followUpResponse.split('\n').map(q => q.trim()).filter(q => q.length > 0).slice(0, 3);
// Function to remove leading numbers and punctuation
const cleanQuestion = (question: string) => {
return question.replace(/^\d+\.\s*/, '');
};
const cleanedQuestions = rawQuestions.map(cleanQuestion);
// If AI fails to provide enough questions, use fallback
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);
// Use fallback questions on error
setFollowUpQuestions(sampleFollowUpQuestions);
}
const sendMessage = useCallback(async (text?: string) => {
const messageText = text !== undefined ? text : inputText;
if (messageText.trim() === '') return;
code Copy code
// Create user message
const userMessage: Message = {
id: uuid.v4().toString(),
text: messageText,
isUser: true,
timestamp: Date.now(),
};
// Update messages state
const updatedMessages = [userMessage, ...messages];
setMessages(updatedMessages);
setInputText('');
setIsTyping(true);
setFollowUpQuestions([]); // Clear follow-up questions
// Save messages to AsyncStorage
await saveMessages(updatedMessages);
// Prepare API messages in chronological order
const apiMessages: APIMessage[] = [
{
role: 'system',
content: figure.systemPrompt,
},
...updatedMessages
.slice() // Create a shallow copy
.reverse() // Reverse to chronological order
.map(msg => ({
role: msg.isUser ? 'user' : 'assistant',
content: msg.text,
})),
];
// **Logging the API Messages**
console.log('==== Sending Messages to AI ====');
apiMessages.forEach((msg, index) => {
console.log(`Message ${index + 1}: [${msg.role}] ${msg.content}`);
});
console.log('==============================='); // Separator for clarity
try {
const aiResponse = await fetchAIResponse(apiMessages);
// Create AI message
const aiMessage: Message = {
id: uuid.v4().toString(),
text: aiResponse,
isUser: false,
timestamp: Date.now(),
};
// Update messages with AI response
const newMessages = [aiMessage, ...updatedMessages];
setMessages(newMessages);
await saveMessages(newMessages);
// Generate follow-up questions based on the AI's response
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]);
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, []);
// Scroll to latest message when messages change
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}
code Copy code
{/* Loading Indicator */}
{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>
)}
{/* Follow-Up Questions */}
{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; burada bir mesaj gittiğinde yeni bir mesaj geldiğinde anında burada gösterilen chatların güncellenmesini, en yeni mesaj atılanların en üstte gösterilmesini istiyorum. bunu ayarla. import React, { 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 { HistoricalFigure, Chat, Message } from '../types/types';
import AsyncStorage from '@react-native-async-storage/async-storage';
import { Ionicons } from '@expo/vector-icons';
import { StatusBar } from 'expo-status-bar';
import CustomText from '../components/CustomText';
interface ChatWithLastMessage extends Chat {
lastMessage?: string;
lastMessageTimestamp?: number;
}
const ChatListScreen = () => {
const navigation = useNavigation();
const [chats, setChats] = useState<ChatWithLastMessage[]>([]);
const [loading, setLoading] = useState(true);
const isFocused = useIsFocused();
useEffect(() => {
const fetchChats = async () => {
try {
const chatsData = await AsyncStorage.getItem('chats');
const chatsList: Chat[] = chatsData ? JSON.parse(chatsData) : [];
code Copy code
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 fetching chats:', error);
Alert.alert("Hata", "Sohbetler yüklenirken bir hata oluştu.");
} finally {
setLoading(false);
}
};
fetchChats();
const deleteChat = useCallback(async (chatId: string) => {
Alert.alert(
"Sohbeti Sil",
"Bu sohbeti silmek istediğinizden emin misiniz?",
[
{ text: "İptal", style: "cancel" },
{
text: "Sil",
style: "destructive",
onPress: async () => {
try {
const updatedChats = chats.filter(chat => chat.id !== chatId);
await AsyncStorage.setItem('chats', JSON.stringify(updatedChats));
await AsyncStorage.removeItem(chat_${chatId}_messages);
setChats(updatedChats);
} catch (error) {
console.error('Error deleting chat:', error);
Alert.alert("Hata", "Sohbet silinirken bir hata oluştu.");
}
}
}
]
);
}, [chats]);
const deleteAllChats = useCallback(async () => {
Alert.alert(
"Tüm Sohbetleri Sil",
${chats.length} sohbet silinecek. Emin misiniz?,
[
{ text: "İptal", style: "cancel" },
{
text: "Sil",
style: "destructive",
onPress: async () => {
try {
await AsyncStorage.removeItem('chats');
for (const chat of chats) {
await AsyncStorage.removeItem(chat_${chat.id}_messages);
}
setChats([]);
} catch (error) {
console.error('Error deleting all chats:', error);
Alert.alert("Hata", "Sohbetler silinirken bir hata oluştu.");
}
}
}
]
);
}, [chats]);
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={() => deleteChat(item.id)} style={styles.deleteButton}>
), [deleteChat]);
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);
if (diff < 1) return Şimdi;
if (diff < 60) return ${diff} dk önce;
const hours = Math.floor(diff / 60);
if (hours < 24) return ${hours} saat önce;
const days = Math.floor(hours / 24);
return ${days} gün önce;
};
if (loading) {
return (
);
}
return (
Sohbetlerim
{chats.length > 0 && (
)}
{chats.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; şöyle bir dosyam var bu dosyayı kullanmadım ama gerekirse kullanalım:
// 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 ChatContextProps {
chats: Chat[];
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<Chat[]>([]);
useEffect(() => {
const loadChats = async () => {
try {
const chatsData = await AsyncStorage.getItem('chats');
const chatsList: Chat[] = chatsData ? JSON.parse(chatsData) : [];
setChats(chatsList);
} catch (error) {
console.error('Error loading chats:', error);
}
};
loadChats();
}, []);
const addChat = useCallback(async (chat: Chat, message: Message) => {
try {
const updatedChats = [...chats, chat];
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]);
const updateChat = useCallback(async (chatId: string, message: Message) => {
try {
const chat = chats.find(c => c.id === chatId);
if (chat) {
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));
// Optionally, update chat's last message timestamp
const updatedChats = chats.map(c =>
c.id === chatId ? { ...c, createdAt: message.timestamp } : c
);
setChats(updatedChats);
await AsyncStorage.setItem('chats', JSON.stringify(updatedChats));
}
} catch (error) {
console.error('Error updating chat:', error);
}
}, [chats]);
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]);
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}
</ChatContext.Provider>
);
};
To ensure that your chat interface updates instantly when new messages are sent or received, and that the latest messages are displayed at the top, it's essential to implement a robust state management strategy. Leveraging React's Context API for global state management will help synchronize your ChatScreen and ChatListScreen effectively. Below, I'll guide you through enhancing your current setup to achieve the desired functionality.
Overview
Implement a Global Chat Context: Use React's Context API to manage chat data globally, allowing both ChatScreen and ChatListScreen to access and modify chat states seamlessly.
Update Chat Context to Handle Messages: Ensure that the context not only stores chats but also manages the addition and updating of messages within each chat.
Refactor ChatListScreen and ChatScreen to Use Context: Modify both screens to interact with the global context instead of directly using AsyncStorage.
Ensure Immediate UI Updates: Optimize the FlatList to reflect new messages instantly, maintaining the correct order with the latest messages on top.
Let's dive into each step in detail.
1. Implement a Global Chat Context
Purpose: Centralize the management of chats and messages, ensuring that any update in one part of the app is immediately reflected elsewhere.
a. Create the Chat Context
You've already started creating a ChatContext.tsx. Let's refine it to handle the addition and updating of messages, ensuring synchronization across your app.
tsx Copy code
// 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 ChatContextProps {
chats: ChatWithLastMessage[];
addChat: (chat: Chat, message: Message) => Promise<void>;
updateChat: (chatId: string, message: Message) => Promise<void>;
deleteChat: (chatId: string) => Promise<void>;
deleteAllChats: () => Promise<void>;
}
export interface ChatWithLastMessage extends Chat {
lastMessage?: string;
lastMessageTimestamp?: number;
}
export const ChatContext = createContext<ChatContextProps>({
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 updatedChats = [...chats, chat];
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}
</ChatContext.Provider>
);
};
b. Wrap Your App with the Chat Provider
Ensure that all components have access to the chat context by wrapping your root component with the ChatProvider.
tsx Copy code
// App.tsx or your main entry point
import React from 'react';
import { ChatProvider } from './src/context/ChatContext';
import Navigation from './src/navigation'; // Your navigation setup
const App = () => {
return (
<ChatProvider>
<Navigation />
</ChatProvider>
);
};
export default App;
2. Refactor ChatListScreen to Use Chat Context
Now that you have a global context, modify ChatListScreen to consume this context instead of directly interacting with AsyncStorage.
Key Changes:
Context Consumption: Instead of fetching chats from AsyncStorage, ChatListScreen now consumes the ChatContext to access and manage chat data.
Sorting Chats: Chats are sorted based on the lastMessageTimestamp to ensure the latest chats appear at the top.
Deletion Methods: The deleteChat and deleteAllChats methods are now invoked from the context, ensuring updates are centralized.
3. Refactor ChatScreen to Use Chat Context
Now, adjust ChatScreen.tsx to interact with the global context, ensuring that any new messages update the chat's state universally.
Key Changes:
Context Consumption: ChatScreen now consumes ChatContext to access updateChat and addChat methods.
Updating Chats via Context: After sending or receiving a message, ChatScreen invokes updateChat to update the global chat state. This ensures that ChatListScreen is aware of the latest message and can reorder the chats accordingly.
Initializing New Chats: If a chat is new (no existing messages), it initializes the chat in the context by calling addChat.
Streamlined AsyncStorage Usage: With the context handling most of the state persistence, ChatScreen minimizes direct interactions with AsyncStorage, reducing redundancy.
4. Ensure Immediate UI Updates with FlatList
Your FlatList in both screens is set up correctly to handle inverted data, ensuring that the newest messages appear at the top. However, ensure that the data prop of FlatList is always sorted appropriately by the context.
In ChatScreen:
Data Ordering: Messages are prepended to the messages state, which, combined with the inverted prop, ensures that the latest messages appear at the top.
Scrolling Behavior: After adding a new message, FlatList scrolls to the top, showcasing the newest message immediately.
In ChatListScreen:
Sorting Chats: Chats are sorted based on the lastMessageTimestamp, ensuring that the most recently active chats appear at the top.
Reactivity: Since ChatListScreen listens to the chats array from the context, any update via ChatContext triggers a re-render, reflecting the latest state instantly.
Additional Recommendations
Optimize Context Performance:
Memoization: Consider using useMemo or useCallback within your context to prevent unnecessary re-renders and optimize performance.
Handle Edge Cases:
Error Handling: Ensure that all asynchronous operations have robust error handling to manage potential failures gracefully.
Empty States: Provide meaningful UI feedback when there are no chats or messages, enhancing user experience.
Enhance User Experience:
Typing Indicators: You've implemented a typing indicator using LottieView. Ensure the animation is smooth and appropriately positioned.
Follow-Up Questions: The follow-up questions feature is a great addition. Ensure that the questions are contextually relevant and enhance the conversation flow.
Testing:
Unit Tests: Implement unit tests for your context and components to ensure reliability.
User Testing: Conduct user testing to gather feedback on the chat experience and make iterative improvements.
Conclusion
By implementing a global ChatContext, you've centralized the management of chats and messages, ensuring synchronization across your app's components. This approach not only enhances the responsiveness of your UI but also simplifies state management, making your codebase more maintainable and scalable.
Should you encounter any further challenges or have additional requirements, feel free to ask!
Happy Coding! 🚀
Show full message · 981 lines Copy first response
Not yet included in a published release.
// 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 { ChatWithLastMessage } from '../context/ChatContext';
import { ChatContext } from '../context/ChatContext';
import { Ionicons } from '@expo/vector-icons';
import CustomText from '../components/CustomText';
const ChatListScreen = () => {
const navigation = useNavigation();
const { chats, deleteChat, deleteAllChats } = useContext(ChatContext);
const [sortedChats, setSortedChats] = useState<ChatWithLastMessage[]>([]);
const [loading, setLoading] = useState<boolean>(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} />
<View style={styles.chatInfo}>
<CustomText bold style={styles.chatName}>
{item.figure.name}
</CustomText>
<CustomText style={styles.chatLastMessage} numberOfLines={1}>
{item.lastMessage}
</CustomText>
<CustomText style={styles.chatDate}>
{timeAgo(item.lastMessageTimestamp)}
</CustomText>
</View>
<TouchableOpacity onPress={() => handleDeleteChat(item.id)} style={styles.deleteButton}>
<Ionicons name="trash-outline" size={24} />
</TouchableOpacity>
</TouchableOpacity>
),
[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 `Şimdi`;
if (diff < 60) return `${diff} dk önce`;
const hours = Math.floor(diff / 60);
if (hours < 24) return `${hours} saat önce`;
const days = Math.floor(hours / 24);
return `${days} gün önce`;
};
if (loading) {
return (
<View style={styles.loadingContainer}>
<ActivityIndicator size="large" color="#007AFF" />
</View>
);
}
return (
<SafeAreaView style={styles.safeArea}>
<View style={styles.container}>
<View style={styles.header}>
<CustomText bold style={styles.title}>
Sohbetlerim
</CustomText>
{chats.length > 0 && (
<TouchableOpacity onPress={deleteAllChats} style={styles.deleteAllButton}>
<Ionicons name="trash-outline" size={24} color="#FF3B30" />
</TouchableOpacity>
)}
</View>
{sortedChats.length === 0 ? (
<View style={styles.emptyContainer}>
<CustomText style={styles.emptyText}>
Hiç sohbetiniz yok! Yeni bir sohbet başlatın.
</CustomText>
</View>
) : (
<FlatList
data={sortedChats}
renderItem={renderChatItem}
keyExtractor={keyExtractor}
contentContainerStyle={styles.chatList}
/>
)}
<TouchableOpacity
style={styles.fab}
onPress={() => navigation.navigate('Home')}
>
<Ionicons name="add" size={30} color="#fff" />
</TouchableOpacity>
</View>
</SafeAreaView>
);
};
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/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<string>('');
const [isTyping, setIsTyping] = useState<boolean>(false);
const [followUpQuestions, setFollowUpQuestions] = useState<string[]>([]);
const [isLoading, setIsLoading] = useState<boolean>(false);
const flatListRef = useRef<FlatList>(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}
>
<View style={styles.header}>
<TouchableOpacity onPress={() => navigation.goBack()} style={styles.backButton}>
<Ionicons name="arrow-back" size={28} color="#000" />
</TouchableOpacity>
<Image source={{ uri: figure.image }} style={styles.headerAvatar} />
<View style={styles.headerInfo}>
<CustomText bold style={styles.headerName}>
{figure.name}
</CustomText>
<CustomText style={styles.headerDescription} numberOfLines={1}>
{figure.description}
</CustomText>
</View>
</View>
{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;