mojmajstor/app/chat/[id].tsx
echo 723cf7e8e3 feat: Phase 5 - in-app chat with real-time messages
- Chat list: auth-gated, shows all conversations for current user
  with other participant's avatar/name, last message preview,
  and relative time in Macedonian (пред X мин/ч/д)
- Chat conversation: FlatList with inverted scroll, message bubbles
  aligned left (other) and right (self), colored backgrounds,
  timestamps, KeyboardAvoidingView send bar
- Chat mutations: getOrCreate finds or creates a 1:1 chat,
  send creates message and updates lastMessageAt
- Message queries: listByChat with participant auth check
- Wired ad detail 'Започни разговор' button to create/open chat
- ChatListItem component with avatar, preview, time, link to detail

All UI text in Macedonian. TypeScript clean, Convex functions deployed.
2026-05-29 18:38:16 +02:00

279 lines
7.8 KiB
TypeScript
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

import { useState } from "react";
import {
View,
Text,
FlatList,
TextInput,
Pressable,
KeyboardAvoidingView,
Platform,
type ListRenderItemInfo,
} from "react-native";
import { useLocalSearchParams, Stack, useRouter } from "expo-router";
import { useQuery, useMutation } from "convex/react";
import { api } from "../../convex/_generated/api";
import { useAuth } from "../_layout";
import { useTheme } from "../../components/theme";
import { Button } from "../../components/ui/button";
import { Loading } from "../../components/ui/loading";
function formatMessageTime(timestamp: number): string {
return new Date(timestamp).toLocaleTimeString("mk-MK", {
hour: "2-digit",
minute: "2-digit",
});
}
export default function ChatDetailScreen() {
const { id } = useLocalSearchParams<{ id: string }>();
const theme = useTheme();
const router = useRouter();
const { token, userId, isAuthenticated } = useAuth();
const chat = useQuery(
api.chats.getById,
isAuthenticated && token && id ? { token, chatId: id as any } : "skip"
);
const messages = useQuery(
api.messages.listByChat,
isAuthenticated && token && id ? { token, chatId: id as any } : "skip"
);
const sendMessage = useMutation(api.messages.send);
const [text, setText] = useState("");
const [sending, setSending] = useState(false);
async function handleSend() {
const content = text.trim();
if (!content || !token || !id) return;
setText("");
setSending(true);
try {
await sendMessage({ token, chatId: id as any, content });
} catch {
setText(content);
} finally {
setSending(false);
}
}
if (!isAuthenticated) {
return (
<>
<Stack.Screen
options={{
title: "Разговор",
headerShown: true,
headerBackButtonDisplayMode: "minimal",
}}
/>
<View
style={{
flex: 1,
justifyContent: "center",
alignItems: "center",
padding: 24,
backgroundColor: theme.colors.background,
}}
>
<Text
style={{
fontSize: 16,
color: theme.colors.text,
marginBottom: 16,
textAlign: "center",
}}
>
Најавете се за да ги видите пораките.
</Text>
<Button onPress={() => router.push("/(auth)/login")}>
Најави се
</Button>
</View>
</>
);
}
if (!chat || !messages) {
return (
<>
<Stack.Screen
options={{
title: "Разговор",
headerShown: true,
headerBackButtonDisplayMode: "minimal",
}}
/>
<View
style={{
flex: 1,
justifyContent: "center",
alignItems: "center",
backgroundColor: theme.colors.background,
}}
>
<Loading />
</View>
</>
);
}
const otherUserName = chat.otherUser?.name ?? "Непознат";
return (
<>
<Stack.Screen
options={{
title: otherUserName,
headerShown: true,
headerBackButtonDisplayMode: "minimal",
}}
/>
<KeyboardAvoidingView
behavior={Platform.OS === "ios" ? "padding" : undefined}
style={{ flex: 1, backgroundColor: theme.colors.background }}
keyboardVerticalOffset={90}
>
{messages.length === 0 ? (
<View
style={{
flex: 1,
justifyContent: "center",
alignItems: "center",
padding: 24,
}}
>
<Text style={{ fontSize: 48, marginBottom: 16 }}>
{"\uD83D\uDCAC"}
</Text>
<Text
style={{
fontSize: 16,
fontWeight: "600",
color: theme.colors.text,
marginBottom: 8,
}}
>
Започнете разговор
</Text>
<Text
style={{
color: theme.colors.textSecondary,
textAlign: "center",
}}
>
Испратете порака за да започнете разговор.
</Text>
</View>
) : (
<FlatList
data={messages}
keyExtractor={(item) => item._id}
inverted
contentContainerStyle={{
paddingVertical: 16,
paddingHorizontal: 16,
}}
ItemSeparatorComponent={() => <View style={{ height: 8 }} />}
renderItem={({
item,
}: ListRenderItemInfo<typeof messages[number]>) => {
const isSelf = item.senderId === userId;
return (
<View
style={{
alignItems: isSelf ? "flex-end" : "flex-start",
}}
>
<View
style={{
maxWidth: "80%",
backgroundColor: isSelf
? theme.colors.primary
: theme.colors.surface,
borderRadius: 16,
paddingHorizontal: 14,
paddingVertical: 10,
borderWidth: isSelf ? 0 : 1,
borderColor: theme.colors.border,
}}
>
<Text
style={{
color: isSelf ? "#FFFFFF" : theme.colors.text,
fontSize: 15,
lineHeight: 20,
}}
>
{item.content}
</Text>
</View>
<Text
style={{
fontSize: 11,
color: theme.colors.textTertiary,
marginTop: 4,
}}
>
{formatMessageTime(item.createdAt)}
</Text>
</View>
);
}}
style={{ flex: 1 }}
/>
)}
<View
style={{
flexDirection: "row",
alignItems: "flex-end",
paddingHorizontal: 16,
paddingVertical: 12,
borderTopWidth: 1,
borderTopColor: theme.colors.border,
backgroundColor: theme.colors.card,
gap: 8,
}}
>
<TextInput
value={text}
onChangeText={setText}
placeholder="Напишете порака..."
placeholderTextColor={theme.colors.textTertiary}
style={{
flex: 1,
backgroundColor: theme.colors.surface,
borderWidth: 1,
borderColor: theme.colors.border,
borderRadius: 20,
paddingHorizontal: 16,
paddingVertical: 10,
fontSize: 16,
color: theme.colors.text,
maxHeight: 100,
}}
multiline
maxLength={1000}
/>
<Pressable
onPress={handleSend}
disabled={!text.trim() || sending}
style={{
backgroundColor: text.trim()
? theme.colors.primary
: theme.colors.border,
width: 40,
height: 40,
borderRadius: 20,
alignItems: "center",
justifyContent: "center",
opacity: sending ? 0.5 : 1,
}}
>
<Text style={{ color: "#FFFFFF", fontSize: 18 }}>{"\u27A4"}</Text>
</Pressable>
</View>
</KeyboardAvoidingView>
</>
);
}