Explore / Programming selamun aleyküm // src/screens/HomeScreen.tsx import React, { useCallback, useContext,… Save Share Download ▾ Reportselamun aleyküm // src/screens/HomeScreen.tsx
import React, { useCallback, useContext, useEffect, useState } from 'react';
import {
View,
FlatList,
Image,
TouchableOpacity,
StyleSheet,
Alert,
SafeAreaView,
ActivityIndicator,
useWindowDimensions,
RefreshControl
} from 'react-native';
import { StatusBar } from 'expo-status-bar';
import { useNavigation } from '@react-navigation/native';
import { HistoricalFigure, Chat, Message } from '../types/types';
import uuid from 'react-native-uuid';
import CustomText from '../components/CustomText';
import { Ionicons } from '@expo/vector-icons';
import { useApp } from '../context/AppContext';
import { ChatContext } from '../context/ChatContext';
const HomeScreen = () => {
const navigation = useNavigation();
const {
historicalFigures,
loading,
refreshing,
t,
currentTheme,
refreshFigures
} = useApp();
const { width } = useWindowDimensions();
const { addChat } = useContext(ChatContext);
const numColumns = 2;
// Yeni bir sohbet başlatan fonksiyon
const startChat = async (figure: HistoricalFigure) => {
const chatId = uuid.v4().toString();
const newChat: Chat = {
id: chatId,
figure: {
...figure,
description: figure.description || "",
},
createdAt: Date.now(),
};
code Copy code
const initialMessage: Message = {
id: uuid.v4().toString(),
text: figure.description || t('noDescriptionAvailable'),
isUser: false,
timestamp: Date.now(),
};
try {
await addChat(newChat, [initialMessage]);
console.log('Chat added:', newChat);
console.log('Initial message added:', initialMessage);
navigation.navigate('Chat', { chatId, figure });
} catch (error) {
console.error('Error starting chat:', error);
Alert.alert(t('error'), t('errorStartingChat'));
}
};
// Her bir figürü render eden fonksiyon
const renderFigureItem = useCallback(({ item }: { item: HistoricalFigure }) => (
<TouchableOpacity
style={[styles.figureItem, { backgroundColor: currentTheme.cardBackground }]}
onPress={() => startChat(item)}
>
<Image source={{ uri: item.image }} style={styles.avatar} />
<CustomText bold style={[styles.figureName, { color: currentTheme.textColor }]}>
{item.name}
<CustomText
style={[styles.figureDescription, { color: currentTheme.secondaryTextColor }]}
numberOfLines={2}
>
{item.description}
<CustomText style={[styles.popularity, { color: currentTheme.accentColor }]}>
{t('popularity')} {item.popularity || 0}
), [currentTheme, startChat, t]);
const keyExtractor = useCallback((item: HistoricalFigure) => item.id, []);
Show full message · 933 lines Assistant2024-10-18 19:36 UTC Copy response
Copy first prompt
Details
Provider OpenAI
Model provenance As recorded by source dataset
Turns 1 (2 messages)
Language tr
Conversation date Oct 18, 2024
Added to archive Nov 16, 2026
ID 01m7h41yw3n960qahk1e2sd8jxSource & license Imported from WildChat-4.8M (AI2) (source ). Imported records earn no Research Points.
Upstream record: 05845295c389dd34d138c16471b9638d
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
// Pull-to-refresh fonksiyonu
const onRefresh = useCallback(async () => {
try {
await refreshFigures();
} catch (error) {
console.error('Error refreshing figures:', error);
Alert.alert(t('error'), t('errorLoadingFigures'));
}
}, [refreshFigures, t]);
return (
<SafeAreaView style={[styles.safeArea, { backgroundColor: currentTheme.backgroundColor }]}>
<CustomText bold style={[styles.title, { color: currentTheme.textColor }]}>
{t('historicalFigures')}
<TouchableOpacity
style={styles.settingsButton}
onPress={() => navigation.navigate('Settings')}
>
{loading ? (
) : (
<FlatList
data={historicalFigures} // historicalFigures zaten popularity'ye göre sıralı
renderItem={renderFigureItem}
keyExtractor={keyExtractor}
contentContainerStyle={styles.figureList}
numColumns={numColumns}
key={numColumns.toString()}
showsVerticalScrollIndicator={false}
refreshControl={
}
/>
)}
);
};
const styles = StyleSheet.create({
avatar: {
borderRadius: 30,
height: 100,
width: 100,
alignSelf: 'center',
marginBottom: 10,
},
container: {
flex: 1,
paddingHorizontal: 10,
},
figureDescription: {
fontFamily: 'Poppins_400Regular',
fontSize: 12,
marginTop: 4,
textAlign: 'center',
},
figureInfo: {
alignItems: 'center',
flex: 1,
paddingHorizontal: 5,
},
figureItem: {
borderRadius: 12,
elevation: 3,
flex: 1,
margin: 5,
padding: 10,
shadowOffset: {
width: 0,
height: 1,
},
shadowOpacity: 0.22,
shadowRadius: 2.22,
shadowColor: '#000',
},
figureList: {
paddingVertical: 10,
},
figureName: {
fontFamily: 'Poppins_700Bold',
fontSize: 14,
textAlign: 'center',
},
header: {
alignItems: 'center',
code Copy code
flexDirection: 'row',
justifyContent: 'space-between',
paddingVertical: 15,
paddingHorizontal: 15,
},
loadingContainer: {
flex: 1,
justifyContent: 'center',
alignItems: 'center',
},
safeArea: {
flex: 1,
},
settingsButton: {
padding: 5,
},
title: {
fontFamily: 'Poppins_700Bold',
fontSize: 24,
},
popularity: {
fontSize: 14,
marginTop: 4,
},
});
export default HomeScreen; bu projemde şimdi belli karakterler var. bunları kategorilere ayırdım, category isminde bir yer oluşturdum firebasede. bu karakterleri bu categorye göre gösterme işlevi eklemeni istiyorum.
bu types.ts dosyamı da düzenlersin herhalde:
// src/types/types.ts
export interface HistoricalFigure {
id: string;
name: string;
image: string;
systemPrompt: string;
description?: string; // Opsiyonel alan
ai?: string; // Opsiyonel AI alanı
starterQuestions?: string[]; // Yeni eklenen starterQuestions alanı
}
export interface Message {
id: string;
text: string;
isUser: boolean;
timestamp: number;
status?: 'pending' | 'completed'; // New field to track message status
}
export interface Chat {
id: string;
figure: HistoricalFigure;
createdAt: number;
}
export type TabParamList = {
Figures: undefined;
Chats: undefined;
};
export type RootStackParamList = {
Home: undefined;
ChatList: undefined;
Chat: { chatId: string; figure: HistoricalFigure };
Settings: undefined;
hacım aynı zamanda şunu istiyorum ana sayfadaki karakterlerin açıklamaları biraz daha fazla gözüksün şimdi çok kısa görünüyor. aynı zamanda const { coins, deductCoins, showRewardedAd } = useContext(CoinContext);
böyle bir contextimiz var. buradan kullanıcının coin sayısını çekip göstertireceğiz homescreen de header de. bak bir örneğini atıyorum:
<CustomText style={[styles.coinText, { color: currentTheme.textColor }]}>{coins}
{/* Yeni Reklam İzle Butonu */}
bu şekilde butonları homescreene de ekle. header de settingsin yanında görünecek. bunların kullanıldığı sayfayı da atayım da bak:
// src/screens/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 FollowUpBubble from '../components/FollowUpBubble';
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('');
const [followUpQuestions, setFollowUpQuestions] = useState<string[]>([]);
const [isLoading, setIsLoading] = useState(false);
const flatListRef = useRef(null);
const isInitialLoad = useRef(false);
const { coins, deductCoins, showRewardedAd } = useContext(CoinContext);
// Keyboard visibility state
const [isKeyboardVisible, setKeyboardVisible] = useState(false);
// User's choice to hide follow-up questions
const [isFollowUpHiddenByUser, setFollowUpHidden] = useState(false);
// Example 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?',
];
// AI Models
const aiModel = figure.ai ? figure.ai : 'openai';
const followUpAiModel = '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
}
);
code Copy code
return () => {
keyboardDidShowListener.remove();
keyboardDidHideListener.remove();
};
// Load messages on mount
useEffect(() => {
if (isInitialLoad.current) return;
code Copy code
const loadMessages = async () => {
try {
setIsLoading(true);
setMessages([]);
setFollowUpQuestions([]);
setFollowUpHidden(false); // Show follow-up questions for a new chat
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);
setFollowUpQuestions(figure.starterQuestions || []);
}
// 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);
code Copy code
await AsyncStorage.setItem(`chat_${chatId}_messages`, JSON.stringify(uniqueMsgs));
} catch (error) {
console.error('Mesajlar kaydedilirken hata oluştu:', error);
}
},
[chatId]
// 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,
},
];
code Copy code
const followUpResponse = await fetchAIResponse(aiMessages, followUpAiModel);
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);
}
console.debug('Takip Soruları Oluşturuldu:', cleanedQuestions);
// If user hasn't hidden follow-up questions, animate their appearance
if (!isFollowUpHiddenByUser) {
LayoutAnimation.configureNext(LayoutAnimation.Presets.easeInEaseOut);
// FollowUpBubble handles its own visibility
}
} catch (error) {
console.error('Takip soruları oluşturulurken hata oluştu:', error);
setFollowUpQuestions(sampleFollowUpQuestions);
}
},
[followUpAiModel, sampleFollowUpQuestions, isFollowUpHiddenByUser]
// 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
code Copy code
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;
code Copy code
// 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('');
setFollowUpQuestions([]); // Clear follow-up questions
setFollowUpHidden(false); // Show follow-up questions again
// 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);
await generateFollowUpQuestions(aiResponse);
} 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,
generateFollowUpQuestions,
updateChat,
chatId,
aiModel,
figure,
t,
incrementPopularity,
]
);
// Handle follow-up question press
const handleFollowUpPress = (question: string) => {
sendMessage(question);
};
// Handle follow-up close
const handleFollowUpClose = () => {
setFollowUpHidden(true);
};
// 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}>
<Image source={{ uri: figure.image }} style={styles.headerAvatar} />
<CustomText bold style={[styles.headerName, { color: currentTheme.textColor }]}>
{figure.name}
<CustomText style={[styles.headerDescription, { color: currentTheme.secondaryTextColor }]} numberOfLines={1}>
{figure.description || t('noDescriptionAvailable')}
<CustomText style={[styles.coinText, { color: currentTheme.textColor }]}>{coins}
{/ Yeni Reklam İzle Butonu */}
code Copy code
{/* Message List and Follow-Up Questions */}
<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
/>
)}
{/* Follow-Up Questions */}
{!isKeyboardVisible && followUpQuestions.length > 0 && !isFollowUpHiddenByUser && (
<FollowUpBubble
questions={followUpQuestions}
onPress={handleFollowUpPress}
onClose={handleFollowUpClose}
/>
)}
</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,
},
followUpHidden: {
display: 'none',
},
// Yeni Reklam İzle Butonu Stili
adButton: {
marginLeft: 10,
padding: 5,
},
});
export default ChatScreen;
aynı video izleme butonu falan da olacak. homescreene bunu taşıyacaksın yani. kategori işini de güzel hallet hadi göreyim seni koç
Aleyküm selam!
Projenizdeki HomeScreen ve types.ts dosyalarını istediğiniz şekilde güncelleyerek, karakterlerin kategorilere göre filtrelenmesini, açıklamaların daha geniş görünmesini ve kullanıcı coin'lerinin header'da görüntülenmesini sağlayabiliriz. Aşağıda bu değişikliklerin adım adım nasıl yapılacağını ve gerekli kod örneklerini bulabilirsiniz.
1. types.ts Dosyasını Güncelleme
Öncelikle, HistoricalFigure arayüzüne category alanını ekleyerek her tarihi figürün bir kategoriye sahip olmasını sağlayacağız.
typescript Copy code
// src/types/types.ts
export interface HistoricalFigure {
id: string;
name: string;
image: string;
systemPrompt: string;
description?: string; // Opsiyonel alan
ai?: string; // Opsiyonel AI alanı
starterQuestions?: string[]; // Yeni eklenen starterQuestions alanı
category: string; // Yeni eklenen kategori alanı
}
export interface Message {
id: string;
text: string;
isUser: boolean;
timestamp: number;
status?: 'pending' | 'completed'; // Mesaj durumu takibi için yeni alan
}
export interface Chat {
id: string;
figure: HistoricalFigure;
createdAt: number;
}
export type TabParamList = {
Figures: undefined;
Chats: undefined;
};
export type RootStackParamList = {
Home: undefined;
ChatList: undefined;
Chat: { chatId: string; figure: HistoricalFigure };
Settings: undefined;
};
Açıklama:
category : Her HistoricalFigure nesnesine ait kategoriyi belirtir. Bu alan Firebase'de de mevcut olmalıdır.
2. HomeScreen.tsx Dosyasını Güncelleme
HomeScreen.tsx dosyanızı, kategorileri filtreleyebilme, açıklamaları daha uzun gösterebilme ve header'a coin display ve reklam izleme butonunu ekleyebilme özelliklerini içerecek şekilde güncelleyeceğiz.
Adımlar:
Gerekli İmportları Ekleyin:
CoinContext ve diğer gerekli komponentleri içeri aktarın.
Kategorileri seçmek için Picker veya FlatList gibi bir UI komponenti kullanabilirsiniz. Bu örnekte Picker kullanacağız.
State Yönetimi:
Seçilen kategoriyi tutmak için bir state ekleyin.
Tüm kategorileri dinamik olarak almak için gerekli işlemleri yapın.
Kategori Filtreleme:
Kullanıcının seçtiği kategoriye göre historicalFigures listesini filtreleyin.
Açıklamaların Görünürlüğünü Artırma:
figureDescription stilini güncelleyerek daha fazla metin göstermesini sağlayın.
Header'a Coin Display ve Reklam İzleme Butonu Ekleyin:
Header kısmına coin sayısını ve reklam izleme butonunu ekleyin.
Güncellenmiş HomeScreen.tsx:
Açıklamalar:
Coin Display ve Reklam İzleme Butonu:
CoinContext'ten coins ve showRewardedAd'yi alıyoruz.
Header'da coinContainer içinde coin sayısını ve reklam izleme butonunu ekliyoruz.
Kategori Seçici:
Picker komponentini kullanarak kullanıcıların kategoriyi seçmesini sağlıyoruz.
categories state'inde tüm kategorileri topluyoruz. İlk olarak 'All' kategorisini ekleyerek tüm figürleri gösterebilme seçeneği sunuyoruz.
Figürlerin Filtrelenmesi:
Kullanıcının seçtiği kategoriye göre historicalFigures listesini filtreleyerek filteredFigures elde ediyoruz.
Eğer 'All' seçildiyse tüm figürleri gösteriyoruz. Aksi takdirde, seçilen kategoriye ait figürleri filtreliyoruz.
Açıklamaların Görünürlüğünü Artırma:
CustomText komponentinde numberOfLines prop'unu 3 olarak ayarlayarak daha fazla satır gösteriyoruz.
Ayrıca figureDescription stilinde fontSize'ı artırarak metnin daha okunaklı olmasını sağlıyoruz.
Kategorilerin Dinamik Olarak Yüklenmesi:
useEffect içinde historicalFigures listesinden benzersiz kategorileri çıkararak categories state'ini güncelliyoruz.
Bu, yeni kategoriler eklendiğinde otomatik olarak güncellenmesini sağlar.
Notlar:
Picker Kullanımı: Picker bileşeni, kullanıcıların kategoriyi seçebilmeleri için basit bir çözüm sunar. Alternatif olarak yatay bir FlatList veya özel bir dropdown komponenti de kullanabilirsiniz.
Stil Ayarları: Kendi temanızın renklerine uygun olarak stilleri currentTheme ile uyumlu hale getirdik.
3. Firebase'de Kategorilerin Bulunduğundan Emin Olun
Firebase'de her HistoricalFigure belgesinin bir category alanına sahip olduğundan emin olun. Örneğin:
json Copy code
{
"id": "1",
"name": "Albert Einstein",
"image": "https://example.com/einstein.jpg",
"systemPrompt": "Sen, yardımsever ve bilgilendirici bir yapay zeka asistanısın.",
"description": "Albert Einstein, 20. yüzyılın en etkili fizikçilerinden biridir...",
"category": "Bilim İnsanları"
}
Kategorilerin Yönetimi:
Kategorileri dinamik olarak yönetmek istiyorsanız, ayrı bir koleksiyonda kategorileri saklayabilir ve oradan çekebilirsiniz.
Ancak bu örnekte, kategorilerin historicalFigures koleksiyonunda bulunmaktadır.
4. AppContext veya Veri Çekme İşlemlerini Güncelleme
Eğer useApp() hook'unuz historicalFigures verisini Firebase'den çekiyorsa, çekim işlemlerinizin category alanını da içerdiğinden emin olun. Örneğin:
typescript Copy code
// src/context/AppContext.tsx
import React, { createContext, useContext, useEffect, useState } from 'react';
import { HistoricalFigure } from '../types/types';
import { firestore } from '../services/firebaseConfig';
import { collection, getDocs, query, orderBy } from 'firebase/firestore';
interface AppContextProps {
historicalFigures: HistoricalFigure[];
loading: boolean;
refreshing: boolean;
t: (key: string) => string;
currentTheme: any;
refreshFigures: () => Promise<void>;
}
const AppContext = createContext<AppContextProps>({} as AppContextProps);
export const useApp = () => useContext(AppContext);
export const AppProvider: React.FC = ({ children }) => {
const [historicalFigures, setHistoricalFigures] = useState<HistoricalFigure[]>([]);
const [loading, setLoading] = useState<boolean>(false);
const [refreshing, setRefreshing] = useState<boolean>(false);
const [currentTheme, setCurrentTheme] = useState<any>({}); // Tema yönetimi
const t = (key: string) => key; // Basit çeviri fonksiyonu
const fetchFigures = async () => {
setLoading(true);
try {
const q = query(collection(firestore, 'historicalFigures'), orderBy('popularity', 'desc'));
const querySnapshot = await getDocs(q);
const figures: HistoricalFigure[] = [];
querySnapshot.forEach((doc) => {
figures.push(doc.data() as HistoricalFigure);
});
setHistoricalFigures(figures);
} catch (error) {
console.error('Error fetching historical figures:', error);
} finally {
setLoading(false);
}
};
useEffect(() => {
fetchFigures();
}, []);
const refreshFigures = async () => {
setRefreshing(true);
await fetchFigures();
setRefreshing(false);
};
return (
<AppContext.Provider value={{ historicalFigures, loading, refreshing, t, currentTheme, refreshFigures }}>
{children}
</AppContext.Provider>
);
};
Açıklama:
Firestore'dan Veri Çekme: category alanını da içererek verileri çekiyoruz.
Sıralama: Örnek olarak popularity alanına göre sıralama yaptık. İhtiyacınıza göre değiştirebilirsiniz.
5. Ekstra: Kullanıcı Deneyimini Artırmak İçin Ek İpuçları
Kategori Seçimini Geliştirme: Picker yerine daha görsel bir kategori seçici kullanmak kullanıcı deneyimini artırabilir.
Optimize Edilmiş FlatList Kullanımı: Özellikle kategorilere göre filtreleme yapıldığında, FlatList performans optimizasyonları düşünebilirsiniz.
Empty State: Seçilen kategoride hiç figür yoksa kullanıcıya bilgilendirici bir mesaj gösterebilirsiniz.
Örnek Empty State:
typescript Copy code
{!loading && filteredFigures.length === 0 && (
<View style={styles.emptyContainer}>
<CustomText style={[styles.emptyText, { color: currentTheme.textColor }]}>
{t('noFiguresInThisCategory')}
</CustomText>
</View>
)}
Stil:
typescript Copy code
emptyContainer: {
flex: 1,
justifyContent: 'center',
alignItems: 'center',
padding: 20,
},
emptyText: {
fontSize: 16,
textAlign: 'center',
},
Bu yapıyı ekleyerek kategoride figür olmadığında kullanıcıyı bilgilendirebilirsiniz.
Sonuç
Yukarıdaki adımları takip ederek projenizdeki HomeScreen'i kategori bazlı filtreleme, daha geniş açıklamalar ve kullanıcı coin'lerinin header'da görüntülenmesini sağlayacak şekilde başarıyla güncelleyebilirsiniz. Herhangi bir sorun yaşarsanız veya ek yardım isterseniz lütfen bana bildirin!
Başarılar dilerim!
Show full message · 543 lines Copy first response
Not yet included in a published release.
// src/screens/HomeScreen.tsx
import React, { useCallback, useContext, useEffect, useState } from 'react';
import {
View,
FlatList,
Image,
TouchableOpacity,
StyleSheet,
Alert,
SafeAreaView,
ActivityIndicator,
useWindowDimensions,
RefreshControl,
Picker, // Import Picker
} from 'react-native';
import { StatusBar } from 'expo-status-bar';
import { useNavigation } from '@react-navigation/native';
import { HistoricalFigure, Chat, Message } from '../types/types';
import uuid from 'react-native-uuid';
import CustomText from '../components/CustomText';
import { Ionicons } from '@expo/vector-icons';
import { useApp } from '../context/AppContext';
import { ChatContext } from '../context/ChatContext';
import { CoinContext } from '../context/CoinContext'; // Import CoinContext
const HomeScreen = () => {
const navigation = useNavigation();
const {
historicalFigures,
loading,
refreshing,
t,
currentTheme,
refreshFigures
} = useApp();
const { width } = useWindowDimensions();
const { addChat } = useContext(ChatContext);
const { coins, showRewardedAd } = useContext(CoinContext); // Destructure coins and showRewardedAd
const [selectedCategory, setSelectedCategory] = useState<string>('All'); // State for selected category
const [categories, setCategories] = useState<string[]>([]); // State for all categories
const numColumns = 2;
// Yeni bir sohbet başlatan fonksiyon
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 || t('noDescriptionAvailable'),
isUser: false,
timestamp: Date.now(),
};
try {
await addChat(newChat, [initialMessage]);
console.log('Chat added:', newChat);
console.log('Initial message added:', initialMessage);
navigation.navigate('Chat', { chatId, figure });
} catch (error) {
console.error('Error starting chat:', error);
Alert.alert(t('error'), t('errorStartingChat'));
}
};
// Her bir figürü render eden fonksiyon
const renderFigureItem = useCallback(({ item }: { item: HistoricalFigure }) => (
<TouchableOpacity
style={[styles.figureItem, { backgroundColor: currentTheme.cardBackground }]}
onPress={() => startChat(item)}
>
<Image source={{ uri: item.image }} style={styles.avatar} />
<View style={styles.figureInfo}>
<CustomText bold style={[styles.figureName, { color: currentTheme.textColor }]}>
{item.name}
</CustomText>
<CustomText
style={[styles.figureDescription, { color: currentTheme.secondaryTextColor }]}
numberOfLines={3} // Artırılmış satır sayısı
>
{item.description}
</CustomText>
<CustomText style={[styles.popularity, { color: currentTheme.accentColor }]}>
{t('popularity')} {item.popularity || 0}
</CustomText>
</View>
</TouchableOpacity>
), [currentTheme, startChat, t]);
const keyExtractor = useCallback((item: HistoricalFigure) => item.id, []);
// Pull-to-refresh fonksiyonu
const onRefresh = useCallback(async () => {
try {
await refreshFigures();
} catch (error) {
console.error('Error refreshing figures:', error);
Alert.alert(t('error'), t('errorLoadingFigures'));
}
}, [refreshFigures, t]);
// Kategorileri yükleme
useEffect(() => {
const loadCategories = () => {
const allCategories = Array.from(new Set(historicalFigures.map(fig => fig.category)));
setCategories(['All', ...allCategories]);
};
loadCategories();
}, [historicalFigures]);
// Kategorilere göre filtrelenmiş figürler
const filteredFigures = selectedCategory === 'All'
? historicalFigures
: historicalFigures.filter(fig => fig.category === selectedCategory);
return (
<SafeAreaView style={[styles.safeArea, { backgroundColor: currentTheme.backgroundColor }]}>
<StatusBar style={currentTheme.statusBarStyle} />
<View style={styles.container}>
{/* Header */}
<View style={styles.header}>
<CustomText bold style={[styles.title, { color: currentTheme.textColor }]}>
{t('historicalFigures')}
</CustomText>
<View style={styles.headerRight}>
{/* Coin Display */}
<View style={styles.coinContainer}>
<Ionicons name="flash" size={20} color={currentTheme.accentColor} />
<CustomText style={[styles.coinText, { color: currentTheme.textColor }]}>{coins}</CustomText>
{/* Reklam İzle Butonu */}
<TouchableOpacity
onPress={showRewardedAd}
style={styles.adButton}
>
<Ionicons name="videocam" size={24} color={currentTheme.accentColor} />
</TouchableOpacity>
</View>
{/* Ayarlar Butonu */}
<TouchableOpacity
style={styles.settingsButton}
onPress={() => navigation.navigate('Settings')}
>
<Ionicons name="settings-outline" size={24} color={currentTheme.accentColor} />
</TouchableOpacity>
</View>
</View>
{/* Kategori Seçici */}
<View style={styles.categoryContainer}>
<Picker
selectedValue={selectedCategory}
style={[styles.picker, { color: currentTheme.textColor, backgroundColor: currentTheme.cardBackground }]}
onValueChange={(itemValue) => setSelectedCategory(itemValue)}
mode="dropdown"
>
{categories.map(category => (
<Picker.Item label={category} value={category} key={category} />
))}
</Picker>
</View>
{/* İçerik */}
{loading ? (
<View style={styles.loadingContainer}>
<ActivityIndicator size="large" color={currentTheme.accentColor} />
</View>
) : (
<FlatList
data={filteredFigures} // Filtrelenmiş figürler
renderItem={renderFigureItem}
keyExtractor={keyExtractor}
contentContainerStyle={styles.figureList}
numColumns={numColumns}
key={numColumns.toString()}
showsVerticalScrollIndicator={false}
refreshControl={
<RefreshControl
refreshing={refreshing}
onRefresh={onRefresh}
colors={[currentTheme.accentColor]}
tintColor={currentTheme.accentColor}
/>
}
/>
)}
</View>
</SafeAreaView>
);
};
const styles = StyleSheet.create({
avatar: {
borderRadius: 30,
height: 100,
width: 100,
alignSelf: 'center',
marginBottom: 10,
},
container: {
flex: 1,
paddingHorizontal: 10,
},
figureDescription: {
fontFamily: 'Poppins_400Regular',
fontSize: 14, // Artırılmış font size
marginTop: 4,
textAlign: 'center',
},
figureInfo: {
alignItems: 'center',
flex: 1,
paddingHorizontal: 5,
},
figureItem: {
borderRadius: 12,
elevation: 3,
flex: 1,
margin: 5,
padding: 10,
shadowOffset: {
width: 0,
height: 1,
},
shadowOpacity: 0.22,
shadowRadius: 2.22,
shadowColor: '#000',
},
figureList: {
paddingVertical: 10,
},
figureName: {
fontFamily: 'Poppins_700Bold',
fontSize: 16, // Artırılmış font size
textAlign: 'center',
},
header: {
flexDirection: 'row',
justifyContent: 'space-between',
alignItems: 'center',
paddingVertical: 15,
paddingHorizontal: 15,
},
headerRight: {
flexDirection: 'row',
alignItems: 'center',
},
settingsButton: {
padding: 5,
marginLeft: 10, // Aşağıdaki coinContainer ile spacing
},
title: {
fontFamily: 'Poppins_700Bold',
fontSize: 24,
},
loadingContainer: {
flex: 1,
justifyContent: 'center',
alignItems: 'center',
},
safeArea: {
flex: 1,
},
figureDescription: {
fontFamily: 'Poppins_400Regular',
fontSize: 14, // Daha büyük font size
marginTop: 4,
textAlign: 'center',
},
popularity: {
fontSize: 14,
marginTop: 4,
},
coinContainer: {
flexDirection: 'row',
alignItems: 'center',
},
coinText: {
fontFamily: 'Poppins_700Bold',
fontSize: 18,
marginLeft: 5,
},
adButton: {
marginLeft: 10,
padding: 5,
},
categoryContainer: {
paddingHorizontal: 15,
paddingVertical: 10,
},
picker: {
height: 50,
width: '100%',
},
});
export default HomeScreen;