// Example follow-up questions (move this outside to prevent recreation on renders)
const sampleFollowUpQuestions = [
'Bu konuda daha fazla detay öğrenmek ister misiniz?',
'Başka ne hakkında konuşmak istersiniz?',
'Farklı bir perspektif mi istiyorsunuz?',
];
// Generate follow-up questions based on AI response
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,
},
];
export default ChatScreen; follow up questions özelliğini tamamıyla kaldıralım.
Certainly! To completely remove the Follow-Up Questions feature from your ChatScreen.tsx, we'll eliminate all related state variables, functions, and UI components. Below is the revised ChatScreen.tsx with the Follow-Up Questions functionality entirely removed.
Summary of Changes:
Removed State Variables:
followUpQuestions
isFollowUpHiddenByUser
sampleFollowUpQuestions
Removed Functions:
generateFollowUpQuestions
handleFollowUpPress
handleFollowUpClose
Removed Related UI Components:
FollowUpBubble component and its related conditional rendering.
Cleaned Up Dependencies:
Removed imports related to follow-up questions (FollowUpBubble and any other unused imports resulting from the removal).
Updated ChatScreen.tsx:
typescript
// ChatScreen.tsx
import React, { useState, useEffect, useRef, useCallback, useContext } from 'react';
import {
View,
FlatList,
Image,
TouchableOpacity,
TextInput,
StyleSheet,
KeyboardAvoidingView,
Platform,
Dimensions,
Alert,
ActivityIndicator,
LayoutAnimation,
UIManager,
Keyboard,
} from 'react-native';
import { useNavigation, useRoute } from '@react-navigation/native';
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';
import AsyncStorage from '@react-native-async-storage/async-storage';
import { useApp } from '../context/AppContext';
import { doc, updateDoc, increment } from 'firebase/firestore';
import { db } from '../services/firebaseConfig';
import { CoinContext } from '../context/CoinContext';
interface RouteParams {
chatId: string;
figure: HistoricalFigure;
}
interface APIMessage {
role: 'system' | 'user' | 'assistant';
content: string;
}
const { width, height } = Dimensions.get('window');
// Enable LayoutAnimation on Android
if (
Platform.OS === 'android' &&
UIManager.setLayoutAnimationEnabledExperimental
) {
UIManager.setLayoutAnimationEnabledExperimental(true);
}
const ChatScreen = () => {
const navigation = useNavigation();
const route = useRoute();
const { chatId, figure } = route.params as RouteParams;
const { updateChat, addChat } = useContext(ChatContext);
const { t, currentTheme, incrementPopularity } = useApp();
const [messages, setMessages] = useState<Message[]>([]);
const [inputText, setInputText] = useState<string>('');
const [isLoading, setIsLoading] = useState<boolean>(false);
const flatListRef = useRef<FlatList>(null);
const isInitialLoad = useRef<boolean>(false);
const { coins, deductCoins, showRewardedAd } = useContext(CoinContext);
// Keyboard visibility state
const [isKeyboardVisible, setKeyboardVisible] = useState<boolean>(false);
// AI Models
const aiModel = figure.ai ? figure.ai : 'openai';
// Ref to track pending AI message IDs
const pendingAIMessageIdsRef = useRef<string[]>([]);
// Listen to keyboard events
useEffect(() => {
const keyboardDidShowListener = Keyboard.addListener(
'keyboardDidShow',
() => {
setKeyboardVisible(true); // Keyboard is visible
}
);
const keyboardDidHideListener = Keyboard.addListener(
'keyboardDidHide',
() => {
setKeyboardVisible(false); // Keyboard is hidden
}
);
return () => {
keyboardDidShowListener.remove();
keyboardDidHideListener.remove();
};
}, []);
// Load messages on mount
useEffect(() => {
if (isInitialLoad.current) return;
const loadMessages = async () => {
try {
setIsLoading(true);
setMessages([]);
const messagesData = await AsyncStorage.getItem(`chat_${chatId}_messages`);
let msgs: Message[] = messagesData ? JSON.parse(messagesData) : [];
if (msgs.length === 0) {
const aiDescription: Message = {
id: uuid.v4().toString(),
text: figure.description || t('noDescriptionAvailable'),
isUser: false,
timestamp: Date.now(),
status: 'completed',
};
msgs = [aiDescription];
const newChat = {
id: chatId,
figure: figure,
createdAt: Date.now(),
};
await addChat(newChat, msgs);
}
// Ensure messages are unique and sorted as [new, ...old]
const uniqueMsgsMap = new Map<string, Message>();
msgs.forEach(msg => {
uniqueMsgsMap.set(msg.id, msg);
});
const uniqueMsgs = Array.from(uniqueMsgsMap.values()).sort((a, b) => b.timestamp - a.timestamp);
setMessages(uniqueMsgs);
setIsLoading(false);
// Scroll to the latest message
setTimeout(() => {
flatListRef.current?.scrollToOffset({ animated: true, offset: 0 });
}, 100);
} catch (error) {
console.error('Mesajlar yüklenirken hata oluştu:', error);
setIsLoading(false);
}
};
loadMessages();
isInitialLoad.current = true;
}, [chatId, figure, addChat, t]);
// Save messages to AsyncStorage
const saveMessages = useCallback(
async (updatedMessages: Message[]) => {
try {
// Ensure messages are unique and sorted as [new, ...old]
const uniqueMsgsMap = new Map<string, Message>();
updatedMessages.forEach(msg => {
uniqueMsgsMap.set(msg.id, msg);
});
const uniqueMsgs = Array.from(uniqueMsgsMap.values()).sort((a, b) => b.timestamp - a.timestamp);
await AsyncStorage.setItem(`chat_${chatId}_messages`, JSON.stringify(uniqueMsgs));
} catch (error) {
console.error('Mesajlar kaydedilirken hata oluştu:', error);
}
},
[chatId]
);
// Add a unique pending AI message
const addPendingAIMessage = () => {
const pendingId = uuid.v4().toString(); // Generate unique ID
pendingAIMessageIdsRef.current.push(pendingId); // Track pending AI message ID
const pendingMessage: Message = {
id: pendingId,
text: '💬 Gelen yanıt bekleniyor...', // Placeholder text
isUser: false,
timestamp: Date.now(),
status: 'pending',
};
LayoutAnimation.configureNext(LayoutAnimation.Presets.easeInEaseOut);
setMessages(prevMessages => [pendingMessage, ...prevMessages]); // Prepend pending message
};
// Send message function
const sendMessage = useCallback(
async (text?: string) => {
const messageText = text !== undefined ? text : inputText;
if (messageText.trim() === '') return;
// Coin kontrolü
if (coins <= 0) {
Alert.alert(
'Yetersiz Coin',
'Coin\'unuz tükenmiş. Daha fazla coin kazanmak için bir reklam izlemek ister misiniz?',
[
{ text: 'İptal', style: 'cancel' },
{ text: 'Reklam İzle', onPress: showRewardedAd },
]
);
return;
}
const userMessage: Message = {
id: uuid.v4().toString(),
text: messageText,
isUser: true,
timestamp: Date.now(),
};
LayoutAnimation.configureNext(LayoutAnimation.Presets.easeInEaseOut);
// Update messages state using functional updater to ensure latest state
setMessages(prevMessages => {
const updatedMessages = [userMessage, ...prevMessages];
saveMessages(updatedMessages);
return updatedMessages;
});
setInputText('');
// Update chat and increment popularity
await updateChat(chatId, userMessage);
try {
const figureDocRef = doc(db, 'figures', figure.id);
await updateDoc(figureDocRef, {
popularity: increment(1),
});
await incrementPopularity(figure.id);
} catch (error) {
console.error('Popülerlik güncellenirken hata oluştu:', error);
}
// Add pending AI message
addPendingAIMessage();
// Get the current messages including the new user message
// Since setMessages is async, it's safer to get them from AsyncStorage
const messagesData = await AsyncStorage.getItem(`chat_${chatId}_messages`);
let currentMessages: Message[] = messagesData ? JSON.parse(messagesData) : [];
// currentMessages are [new,...old], so to get all messages including pending ones
// It would be better to use the latest state. But for safety, re-fetch.
const apiMessages: APIMessage[] = [
{
role: 'system',
content: figure.systemPrompt || 'Sen, yardımsever ve bilgilendirici bir yapay zeka asistanısın.',
},
...currentMessages
.reverse() // Reverse to be [old, ...new]
.map((msg) => ({
role: msg.isUser ? 'user' : 'assistant',
content: msg.text,
})),
];
console.log('==== AI\'a Gönderilen Mesajlar ====');
apiMessages.forEach((msg, index) => {
console.log(`Mesaj ${index + 1}: [${msg.role}] ${msg.content}`);
});
console.log('===============================');
try {
const aiResponse = await fetchAIResponse(apiMessages, aiModel);
const aiMessage: Message = {
id: uuid.v4().toString(),
text: aiResponse,
isUser: false,
timestamp: Date.now(),
status: 'completed',
};
// Coin düşürme işlemi
if (!text) {
deductCoins(1);
}
// Replace the oldest pending AI message with the actual AI message
setMessages(prevMessages => {
const pendingId = pendingAIMessageIdsRef.current.shift(); // Get the first pending AI message ID
if (!pendingId) {
// No pending AI message found, cannot replace
return prevMessages;
}
const updatedMessages = prevMessages.map(msg =>
msg.id === pendingId && msg.status === 'pending'
? aiMessage
: msg
);
saveMessages(updatedMessages);
return updatedMessages;
});
await updateChat(chatId, aiMessage);
} catch (error) {
console.error('AI yanıtı alınırken hata oluştu:', error);
Alert.alert(t('error'), t('errorFetchingAIResponse'));
// Remove the pending AI message on error
setMessages(prevMessages => {
const pendingId = pendingAIMessageIdsRef.current.shift(); // Get the first pending AI message ID
if (!pendingId) {
// No pending AI message found, nothing to remove
return prevMessages;
}
const filteredMessages = prevMessages.filter(msg => msg.id !== pendingId);
saveMessages(filteredMessages);
return filteredMessages;
});
} finally {
// Scroll to the latest message
flatListRef.current?.scrollToOffset({ animated: true, offset: 0 });
}
},
[
inputText,
coins,
showRewardedAd,
deductCoins,
saveMessages,
updateChat,
chatId,
aiModel,
figure,
t,
incrementPopularity,
]
);
// Render each message
const renderMessageItem = useCallback(
({ item }: { item: Message }) => (
<MessageItem
message={item}
onLongPress={() => {
Clipboard.setString(item.text);
Alert.alert(t('copied'), t('messageCopied'));
}}
/>
),
[t]
);
const keyExtractor = useCallback((item: Message) => item.id, []);
// Scroll to the latest message when messages change
useEffect(() => {
if (messages.length > 0) {
flatListRef.current?.scrollToOffset({ animated: true, offset: 0 });
}
}, [messages]);
return (
<KeyboardAvoidingView
style={[styles.container, { backgroundColor: currentTheme.backgroundColor }]}
behavior={Platform.OS === 'ios' ? 'padding' : undefined}
keyboardVerticalOffset={Platform.OS === 'ios' ? 60 : 0}
>
{/* Header */}
<View
style={[
styles.header,
{
backgroundColor: currentTheme.cardBackground,
borderBottomColor: currentTheme.borderColor,
paddingTop: Platform.OS === 'ios' ? 20 : 10,
},
]}
>
<TouchableOpacity onPress={() => navigation.goBack()} style={styles.backButton}>
<Ionicons name="arrow-back" size={28} color={currentTheme.textColor} />
</TouchableOpacity>
<Image source={{ uri: figure.image }} style={styles.headerAvatar} />
<View style={styles.headerInfo}>
<CustomText bold style={[styles.headerName, { color: currentTheme.textColor }]}>
{figure.name}
</CustomText>
<CustomText style={[styles.headerDescription, { color: currentTheme.secondaryTextColor }]} numberOfLines={1}>
{figure.description || t('noDescriptionAvailable')}
</CustomText>
</View>
<View style={styles.coinContainer}>
<Ionicons name="flash" size={20} color={currentTheme.accentColor} />
<CustomText style={[styles.coinText, { color: currentTheme.textColor }]}>{coins}</CustomText>
{/* Yeni Reklam İzle Butonu */}
<TouchableOpacity
onPress={showRewardedAd}
style={styles.adButton}
>
<Ionicons name="videocam" size={24} color={currentTheme.accentColor} />
</TouchableOpacity>
</View>
</View>
{/* Message List */}
<View style={styles.chatContainer}>
{/* Message List or Loading */}
{isLoading ? (
<View style={styles.loadingContainer}>
<ActivityIndicator size="large" color={currentTheme.accentColor} />
</View>
) : (
<FlatList
ref={flatListRef}
data={messages}
renderItem={renderMessageItem}
keyExtractor={keyExtractor}
style={styles.messageList}
contentContainerStyle={styles.messageListContent}
inverted
/>
)}
</View>
{/* Input Field */}
<View
style={[
styles.inputContainer,
{
backgroundColor: currentTheme.cardBackground,
borderTopColor: currentTheme.borderColor,
paddingHorizontal: 15,
paddingVertical: 10,
},
]}
>
<TextInput
style={[
styles.input,
{
backgroundColor: currentTheme.inputBackground,
color: currentTheme.textColor,
borderColor: currentTheme.borderColor,
},
]}
value={inputText}
onChangeText={setInputText}
placeholder={t('writeYourMessage')}
placeholderTextColor={currentTheme.placeholderTextColor}
onSubmitEditing={() => sendMessage()}
returnKeyType="send"
multiline={true}
/>
<TouchableOpacity
onPress={() => sendMessage()}
style={[
styles.sendButton,
{ backgroundColor: currentTheme.accentColor },
{ shadowColor: currentTheme.shadowColor },
]}
>
<Ionicons name="send" size={24} color="#fff" />
</TouchableOpacity>
</View>
</KeyboardAvoidingView>
);
};
const styles = StyleSheet.create({
backButton: {
marginRight: 10,
},
container: {
flex: 1,
},
header: {
alignItems: 'center',
borderBottomWidth: 1,
flexDirection: 'row',
padding: 15,
},
headerAvatar: {
borderRadius: 20,
height: 48,
marginRight: 10,
width: 48,
},
headerDescription: {
fontFamily: 'Poppins_400Regular',
fontSize: 14,
marginTop: 2,
},
headerInfo: {
flex: 1,
},
coinContainer: {
flexDirection: 'row',
alignItems: 'center',
marginLeft: 'auto',
},
coinText: {
fontFamily: 'Poppins_700Bold',
fontSize: 18,
marginLeft: 5,
},
headerName: {
fontFamily: 'Poppins_700Bold',
fontSize: 18,
},
chatContainer: {
flex: 1,
},
messageList: {
flex: 1,
paddingTop: 10,
},
messageListContent: {
paddingVertical: 10,
paddingHorizontal: 15,
},
loadingContainer: {
alignItems: 'center',
flex: 1,
justifyContent: 'center',
},
input: {
borderRadius: 20,
flex: 1,
fontFamily: 'Poppins_400Regular',
minHeight: 40,
maxHeight: 100,
marginRight: 10,
paddingHorizontal: 15,
paddingVertical: 10,
borderWidth: 1,
},
inputContainer: {
alignItems: 'center',
borderTopWidth: 1,
flexDirection: 'row',
},
sendButton: {
borderRadius: 20,
padding: 10,
shadowOffset: {
width: 0,
height: 1,
},
shadowOpacity: 0.3,
shadowRadius: 1.41,
elevation: 2,
},
// Yeni Reklam İzle Butonu Stili
adButton: {
marginLeft: 10,
padding: 5,
},
});
export default ChatScreen;
Detailed Overview of Changes:
State Variables Removed:
followUpQuestions: This state managed the list of follow-up questions.
isFollowUpHiddenByUser: This state tracked whether the user chose to hide the follow-up questions.
sampleFollowUpQuestions: An array of default follow-up questions which is no longer necessary.
Functions Removed:
generateFollowUpQuestions: Responsible for generating follow-up questions based on AI responses.
handleFollowUpPress: Handled user interactions when a follow-up question was pressed.
handleFollowUpClose: Managed the event when a user chose to hide follow-up questions.
UI Components Removed:
FollowUpBubble: This custom component displayed the follow-up questions. All its references and conditional renderings have been removed.
Adjustments in sendMessage Function:
Removed the parts where follow-up questions were being set or cleared (setFollowUpQuestions and setFollowUpHidden).
Imports Cleaned:
Removed: FollowUpBubble import and any other imports related to follow-up questions.
Retained: All other necessary imports related to core functionalities like messages, navigation, themes, coins, etc.
UI Adjustments:
The section that conditionally rendered the FollowUpBubble based on followUpQuestions and isFollowUpHiddenByUser has been removed to streamline the UI.
Final Notes:
Testing: After implementing these changes, thoroughly test the chat functionality to ensure that removing the follow-up questions hasn't introduced any unintended side effects.
Cleanup: Ensure that any other parts of your application that depended on the follow-up questions feature are also updated accordingly to prevent potential errors or warnings.
By following the above modifications, your ChatScreen.tsx will no longer include the follow-up questions feature, resulting in a cleaner and more streamlined chat interface.