Untitled
Anonymous
Plain Text
11/01/2025 5:59 PM
18.1 KB
14
Indexable
Never
// ChatMessagesScreen.tsx
import React, { useState, useEffect, useRef } from "react";
import useCurrentUserId from "~/hooks/useCurrentUserId";
import {
View,
FlatList,
KeyboardAvoidingView,
Platform,
Text,
TouchableOpacity,
Modal,
Keyboard,
TouchableWithoutFeedback,
useWindowDimensions,
ActivityIndicator, // Added for loading state
} from "react-native";
import { StatusBar } from "expo-status-bar";
import { SafeAreaView } from "react-native-safe-area-context";
import { useLocalSearchParams } from "expo-router";
import { Ionicons } from "@expo/vector-icons";
import ChatHeader from "~/components/social-feature/chat/ChatHeader";
import MessageBubble from "~/components/social-feature/chat/MessageBubble";
import InputBar from "~/components/social-feature/chat/InputBar";
import { useMessagesStore } from "./zustand/messagesStore";
import useUsers from "~/hooks/useUsers";
// Remove unused User import
import { supabase } from "~/utils/supabase";
import useOfflineSync from "~/hooks/useOfflineSync"; // Import the offline sync hook
import { useLayoutEffect } from "react";
import { useNavigation } from "expo-router";
type Message = {
id: string;
conversation_id: string;
sender_id: string;
text: string;
created_at: string;
// Added fields from chat_messages table
message_id?: string;
message_content?: string;
message_type?: string;
media_url?: string;
is_one_time?: boolean;
viewed_by?: string[];
caption?: string;
type?: string;
count?: number;
};
const ChatMessagesScreen = () => {
const { height } = useWindowDimensions();
console.log("Screen height:", height); // Debug log for screen height
const getMessages = useMessagesStore((s) => s.getMessages);
const sendMessage = useMessagesStore((s) => s.sendMessage);
const deleteMessage = useMessagesStore((s) => s.deleteMessage);
const markMessagesAsRead = useMessagesStore((s) => s.markMessagesAsRead);
const [messages, setMessages] = useState<Message[]>([]);
const [loading, setLoading] = useState(true); // Added loading state
const [inputText, setInputText] = useState("");
const [selectedMessages, setSelectedMessages] = useState<string[]>([]);
const [isSelectionMode, setSelectionMode] = useState(false);
const [pinnedMessage, setPinnedMessage] = useState<Message | null>(null);
const [isDeleteDialogVisible, setDeleteDialogVisible] = useState(false);
const [highlightedMessageId, setHighlightedMessageId] = useState<
string | null
>(null);
const [visibleTimestampId, setVisibleTimestampId] = useState<string | null>(
null
);
const flatListRef = useRef<FlatList>(null);
const { width } = useWindowDimensions();
const params = useLocalSearchParams();
const { name, conversation_id } = params;
const currentUserId = useCurrentUserId();
const { users } = useUsers();
interface UserType {
user_id: string;
fullname: string;
avatar_url?: string;
// add more fields if needed
}
const [otherUser, setOtherUser] = useState<UserType | null>(null);
// Get offline sync state and methods
const {
isOnline,
saveMessages,
messages: offlineMessages,
} = useOfflineSync();
const navigation = useNavigation();
useLayoutEffect(() => {
navigation.setOptions({
// tabBarStyle: {
// backgroundColor: "#fff", // tab bar white
// borderTopColor: "#ddd", // khad yar sare
// },
tabBarActiveTintColor: "#000", // icon/text active black
tabBarInactiveTintColor: "#666", // icon/text inactive gray
});
}, [navigation]);
// Fetch conversation messages and handle offline mode
useEffect(() => {
const fetchAndSetMessages = async () => {
if (!conversation_id) {
setLoading(false);
return;
}
setLoading(true);
if (isOnline) {
// Online: Fetch from Supabase
const { data, error } = await getMessages(conversation_id as string);
if (!error && data) {
setMessages(data);
await saveMessages(data); // Save to AsyncStorage
} else if (error) {
// If fetch fails, try loading from cache
const conversationMessages = offlineMessages.filter(
(msg) => msg.conversation_id === conversation_id
);
setMessages(conversationMessages);
}
} else {
// Offline: Load from AsyncStorage
const conversationMessages = offlineMessages.filter(
(msg) => msg.conversation_id === conversation_id
);
setMessages(conversationMessages);
}
setLoading(false);
};
fetchAndSetMessages();
// Mark messages as read when the component mounts or conversation changes
const markAsRead = async () => {
if (conversation_id && currentUserId) {
await markMessagesAsRead(conversation_id as string, currentUserId);
}
};
markAsRead();
}, [conversation_id, isOnline, currentUserId]); // Rerun on network change or user change
// Real-time subscription for new messages
useEffect(() => {
if (!isOnline || !conversation_id) return;
const handleInserts = (payload: any) => {
const newMessage = payload.new as Message;
setMessages((prevMessages) => {
// Avoid duplicates
if (
prevMessages.some(
(msg) =>
msg.id === newMessage.id ||
msg.message_id === newMessage.message_id
)
) {
return prevMessages;
}
const updatedMessages = [...prevMessages, newMessage];
saveMessages(updatedMessages); // Update cache
return updatedMessages;
});
};
const handleDeletes = (payload: any) => {
setMessages((prevMessages) => {
const updatedMessages = prevMessages.filter(
(message) =>
(message.id || message.message_id) !==
(payload.old.id || payload.old.message_id)
);
saveMessages(updatedMessages); // Update cache
return updatedMessages;
});
};
const subscription = supabase
.channel(`chat_messages_realtime_${conversation_id}`)
.on(
"postgres_changes",
{
event: "INSERT",
schema: "public",
table: "chat_messages",
filter: `conversation_id=eq.${conversation_id}`,
},
handleInserts
)
.on(
"postgres_changes",
{
event: "DELETE",
schema: "public",
table: "chat_messages",
filter: `conversation_id=eq.${conversation_id}`,
},
handleDeletes
)
.subscribe();
return () => {
supabase.removeChannel(subscription);
};
}, [conversation_id, isOnline, saveMessages]);
// Fetch other participant info
useEffect(() => {
const fetchOtherParticipant = async () => {
if (!conversation_id || !Array.isArray(users) || users.length === 0)
return;
const { data, error } = await supabase
.from("conversation_participants")
.select("user_id")
.eq("conversation_id", conversation_id);
if (error) return console.error(error);
const participantIds = data.map((p) => p.user_id);
const otherParticipantId = participantIds.find(
(id) => id !== currentUserId
);
if (otherParticipantId) {
const foundUser = users.find((u) => u.user_id === otherParticipantId);
setOtherUser(foundUser || null);
}
};
fetchOtherParticipant();
}, [conversation_id, users]);
// Send message
const handleSend = async () => {
if (!inputText.trim() || !conversation_id || !otherUser?.user_id) return;
if (!isOnline) {
alert("You are offline. Message cannot be sent.");
return;
}
// Use object argument for sendMessage
const { data, error } = await sendMessage({
conversationId: conversation_id as string,
senderId: currentUserId,
text: inputText,
receiverId: otherUser.user_id,
messageType: "text",
mediaUrl: "",
isOneTime: false,
caption: ""
});
if (!error && data) {
setInputText("");
Keyboard.dismiss();
// Immediately fetch messages after sending
const { data: newMessages, error: fetchErr } = await getMessages(
conversation_id as string
);
if (!fetchErr && newMessages) {
setMessages(newMessages);
}
}
};
// Delete messages
const deleteMessagesHandler = async (forEveryone: boolean) => {
if (forEveryone) {
// Online: tirtir DB-ga
for (const id of selectedMessages) {
await supabase.from("chat_messages").delete().eq("message_id", id);
}
if (pinnedMessage && selectedMessages.includes(pinnedMessage.id))
setPinnedMessage(null);
} else {
// Delete for me: kaliya ka saar messages state-ka hadda jira
setMessages((prev) =>
prev.filter(
(msg) =>
!selectedMessages.includes(msg.id ?? "") &&
!selectedMessages.includes(msg.message_id ?? "")
)
);
if (pinnedMessage && selectedMessages.includes(pinnedMessage.id))
setPinnedMessage(null);
}
setDeleteDialogVisible(false);
setSelectedMessages([]);
setSelectionMode(false);
};
// Keyboard scroll
useEffect(() => {
const keyboardListener = Keyboard.addListener("keyboardDidShow", () => {
flatListRef.current?.scrollToEnd({ animated: true });
});
return () => keyboardListener.remove();
}, []);
useEffect(() => {
if (messages.length > 0)
setTimeout(
() => flatListRef.current?.scrollToEnd({ animated: true }),
100
);
}, [messages]);
const handleLongPress = (id: string, messageId?: string) => {
const actualId = messageId || id;
setSelectionMode(true);
setSelectedMessages([actualId]);
};
const handlePress = (id: string) => {
if (isSelectionMode) {
const newSelected = selectedMessages.includes(id)
? selectedMessages.filter((msg) => msg !== id)
: [...selectedMessages, id];
setSelectedMessages(newSelected);
if (newSelected.length === 0) setSelectionMode(false);
} else {
setVisibleTimestampId(visibleTimestampId === id ? null : id);
}
};
const scrollToMessage = (messageId: string) => {
const index = messages.findIndex((msg) => msg.id === messageId);
if (index !== -1) {
flatListRef.current?.scrollToIndex({
index,
animated: true,
viewPosition: 0.5,
});
setHighlightedMessageId(messageId);
setTimeout(() => setHighlightedMessageId(null), 2000);
}
};
const PinnedMessageView = () => {
if (!pinnedMessage) return null;
return (
<TouchableOpacity
onPress={() => scrollToMessage(pinnedMessage.id)}
className="p-3 bg-blue-100 border-b border-blue-200 flex-row items-center justify-between shadow-md"
>
<View className="flex-1">
<Text className="font-bold text-blue-800">Pinned Message</Text>
<Text className="text-gray-700" numberOfLines={1}>
{pinnedMessage.text}
</Text>
</View>
<TouchableOpacity
onPress={() => setPinnedMessage(null)}
className="p-1"
>
<Ionicons name="close-circle" size={22} color="#555" />
</TouchableOpacity>
</TouchableOpacity>
);
};
const DeleteDialog = () => {
const canDeleteForEveryone = selectedMessages.every((selId) => {
const msg = messages.find(
(m) => m.id === selId || m.message_id === selId
);
return msg?.sender_id === currentUserId;
});
return (
<Modal
transparent
visible={isDeleteDialogVisible}
onRequestClose={() => setDeleteDialogVisible(false)}
>
<TouchableWithoutFeedback onPress={() => setDeleteDialogVisible(false)}>
<View className="flex-1 justify-center items-center bg-black/60">
<View className="bg-white rounded-xl p-4 w-4/5 max-w-sm shadow-xl">
<Text className="text-xl font-bold mb-4 text-gray-800">
Delete message?
</Text>
{canDeleteForEveryone && (
<TouchableOpacity
className="p-3"
onPress={() => deleteMessagesHandler(true)}
>
<Text className="text-red-500 text-lg">
Delete for everyone
</Text>
</TouchableOpacity>
)}
<TouchableOpacity
className="p-3"
onPress={() => deleteMessagesHandler(false)}
>
<Text className="text-red-500 text-lg">Delete for me</Text>
</TouchableOpacity>
<TouchableOpacity
className="p-3 mt-2"
onPress={() => setDeleteDialogVisible(false)}
>
<Text className="text-center text-gray-600 text-lg">
Cancel
</Text>
</TouchableOpacity>
</View>
</View>
</TouchableWithoutFeedback>
</Modal>
);
};
if (loading) {
return (
<SafeAreaView
style={{ flex: 1 }}
className="bg-[#E3EDFF] justify-center items-center"
>
<ActivityIndicator size="large" color="#00246B" />
</SafeAreaView>
);
}
return (
<SafeAreaView style={{ flex: 1 }} className="bg-[#E3EDFF]">
<StatusBar style="dark" />
<ChatHeader
name={otherUser?.fullname || (name as string)}
avatarUrl={otherUser?.avatar_url}
isSelectionMode={isSelectionMode}
selectedCount={selectedMessages.length}
onClearSelection={() => {
setSelectionMode(false);
setSelectedMessages([]);
}}
onPin={() => (pinnedMessage ? setPinnedMessage(null) : pinnedMessage)}
onDelete={() => setDeleteDialogVisible(true)}
onCall={() => alert("Call pressed")}
/>
<PinnedMessageView />
<KeyboardAvoidingView
behavior={Platform.OS === "ios" ? "padding" : "height"}
style={{ flex: 1 }}
keyboardVerticalOffset={Platform.OS === "ios" ? 60 : 0}
>
<FlatList
ref={flatListRef}
data={messages}
renderItem={({ item }) => {
// Debug log to catch malformed message objects
if (
typeof item.text !== "string" &&
typeof item.message_content !== "string"
) {
console.warn("Malformed message object:", item);
}
// Defensive mapping: always pass strings
const safeText = typeof item.text === "string" ? item.text : "";
const safeContent =
typeof item.message_content === "string"
? item.message_content
: "";
// Find sender's avatar
const senderUser = users?.find((u) => u.user_id === item.sender_id);
const avatarUrl = senderUser?.avatar_url ?? undefined;
// Debug log for viewed_by and currentUserId/receiverId
console.log('Message:', {
id: item.message_id || item.id,
sender_id: item.sender_id,
viewed_by: item.viewed_by,
currentUserId,
receiverId: otherUser?.user_id
});
return (
<MessageBubble
item={{
id: item.message_id || item.id,
sender_id: item.sender_id,
text: safeContent || safeText,
message_content: item.message_content,
message_type: item.message_type,
media_url: item.media_url,
is_one_time: item.is_one_time,
viewed_by: item.viewed_by,
caption: item.caption,
type: item.type,
count: item.count,
time: item.created_at,
avatar_url: avatarUrl ?? undefined,
}}
avatarUrl={avatarUrl}
receiverId={otherUser?.user_id}
onLongPress={(id) => handleLongPress(id, item.message_id)}
onPress={async (id) => {
// Find the message object
const message = messages.find(m => (m.message_id || m.id) === id);
if (!message) return handlePress(id);
// One-time view logic for media
if (message.is_one_time && message.sender_id !== currentUserId) {
const alreadyViewed = message.viewed_by?.includes(currentUserId);
if (!alreadyViewed) {
const updatedViewedBy = [...(message.viewed_by || []), currentUserId];
await supabase
.from("chat_messages")
.update({ viewed_by: updatedViewedBy })
.eq("id", message.id);
setMessages((prev) =>
prev.map((m) =>
m.id === message.id ? { ...m, viewed_by: updatedViewedBy } : m
)
);
}
}
// TODO: Show full screen preview modal here
handlePress(id);
}}
isSelected={selectedMessages.includes(
item.message_id || item.id
)}
isHighlighted={
highlightedMessageId === (item.message_id || item.id)
}
isTimestampVisible={
visibleTimestampId === (item.message_id || item.id)
}
currentUserId={currentUserId}
/>
);
}}
keyExtractor={(item) => item.message_id || item.id}
showsVerticalScrollIndicator={false}
contentContainerStyle={{
flexGrow: 1,
padding: 10,
justifyContent: "flex-start",
}}
/>
<InputBar
value={inputText}
onChangeText={setInputText}
onSend={handleSend}
onSendVoice={(uri) => console.log("Voice message URI:", uri)}
showSend={!!inputText.trim()}
/>
</KeyboardAvoidingView>
<DeleteDialog />
</SafeAreaView>
);
};
export default ChatMessagesScreen;
Editor is loading...
Leave a Comment