's'
This commit is contained in:
243
app/[locale]/chat/[id]/page.tsx
Normal file
243
app/[locale]/chat/[id]/page.tsx
Normal file
@@ -0,0 +1,243 @@
|
||||
"use client";
|
||||
|
||||
import { FormEvent, useCallback, useEffect, useRef, useState } from "react";
|
||||
import { Link } from "@/i18n/navigation";
|
||||
import { useLocale, useTranslation } from "@/i18n/navigation";
|
||||
import { useParams } from "next/navigation";
|
||||
import Footer from "@/app/components/Footer";
|
||||
import { fetchAuthMe } from "@/app/lib/api-client";
|
||||
import {
|
||||
fetchConversation,
|
||||
fetchMessages,
|
||||
sendChatMessage,
|
||||
type ChatMessage,
|
||||
type ConversationItem,
|
||||
} from "@/app/lib/chat";
|
||||
import { mediaUrl } from "@/app/lib/media";
|
||||
|
||||
const POLL_MS = 4000;
|
||||
|
||||
function formatMessageTime(value?: string, locale = "zh"): string {
|
||||
if (!value) return "";
|
||||
const date = new Date(value);
|
||||
if (Number.isNaN(date.getTime())) return "";
|
||||
return date.toLocaleTimeString(locale === "zh" ? "zh-CN" : "en-US", {
|
||||
hour: "2-digit",
|
||||
minute: "2-digit",
|
||||
});
|
||||
}
|
||||
|
||||
export default function ChatThreadPage() {
|
||||
const params = useParams();
|
||||
const conversationId = String(params?.id || "");
|
||||
const { t } = useTranslation("chat");
|
||||
const locale = useLocale();
|
||||
|
||||
const [conversation, setConversation] = useState<ConversationItem | null>(null);
|
||||
const [messages, setMessages] = useState<ChatMessage[]>([]);
|
||||
const [draft, setDraft] = useState("");
|
||||
const [loading, setLoading] = useState(true);
|
||||
const [sending, setSending] = useState(false);
|
||||
const [error, setError] = useState("");
|
||||
const [isLoggedIn, setIsLoggedIn] = useState(false);
|
||||
const bottomRef = useRef<HTMLDivElement | null>(null);
|
||||
const listRef = useRef<HTMLDivElement | null>(null);
|
||||
|
||||
const scrollToBottom = useCallback(() => {
|
||||
bottomRef.current?.scrollIntoView({ behavior: "smooth" });
|
||||
}, []);
|
||||
|
||||
const loadThread = useCallback(async () => {
|
||||
if (!conversationId) return;
|
||||
try {
|
||||
const [meta, items] = await Promise.all([
|
||||
fetchConversation(conversationId),
|
||||
fetchMessages(conversationId),
|
||||
]);
|
||||
setConversation(meta);
|
||||
setMessages(items);
|
||||
setError("");
|
||||
} catch (err) {
|
||||
setError(err instanceof Error ? err.message : t("loadError"));
|
||||
} finally {
|
||||
setLoading(false);
|
||||
}
|
||||
}, [conversationId, t]);
|
||||
|
||||
useEffect(() => {
|
||||
fetchAuthMe().then((data) => setIsLoggedIn(Boolean(data?.user?.id)));
|
||||
}, []);
|
||||
|
||||
useEffect(() => {
|
||||
loadThread();
|
||||
}, [loadThread]);
|
||||
|
||||
useEffect(() => {
|
||||
if (!conversationId || !isLoggedIn) return undefined;
|
||||
const timer = window.setInterval(() => {
|
||||
fetchMessages(conversationId)
|
||||
.then((items) => setMessages(items))
|
||||
.catch(() => undefined);
|
||||
}, POLL_MS);
|
||||
return () => window.clearInterval(timer);
|
||||
}, [conversationId, isLoggedIn]);
|
||||
|
||||
useEffect(() => {
|
||||
scrollToBottom();
|
||||
}, [messages, scrollToBottom]);
|
||||
|
||||
const handleSend = async (event: FormEvent) => {
|
||||
event.preventDefault();
|
||||
const body = draft.trim();
|
||||
if (!body || sending || !conversationId) return;
|
||||
setSending(true);
|
||||
setError("");
|
||||
try {
|
||||
const message = await sendChatMessage(conversationId, body);
|
||||
setMessages((prev) => [...prev, message]);
|
||||
setDraft("");
|
||||
setConversation((prev) =>
|
||||
prev
|
||||
? {
|
||||
...prev,
|
||||
lastMessagePreview: body.replace(/\n/g, " ").slice(0, 180),
|
||||
lastMessageAt: message.created || prev.lastMessageAt,
|
||||
}
|
||||
: prev
|
||||
);
|
||||
} catch (err) {
|
||||
setError(err instanceof Error ? err.message : t("sendError"));
|
||||
} finally {
|
||||
setSending(false);
|
||||
}
|
||||
};
|
||||
|
||||
const peerName = conversation?.peer?.name || (locale === "zh" ? "成员" : "Member");
|
||||
|
||||
return (
|
||||
<div className="flex min-h-screen flex-col bg-[#f6f7f9] dark:bg-gray-950">
|
||||
<header className="sticky top-0 z-20 border-b border-gray-200 bg-white/95 backdrop-blur dark:border-gray-800 dark:bg-gray-950/95">
|
||||
<div className="mx-auto flex max-w-3xl items-center gap-3 px-4 py-3 sm:px-6">
|
||||
<Link
|
||||
href="/chat"
|
||||
className="rounded-full border border-gray-200 px-3 py-1.5 text-sm text-gray-600 hover:bg-gray-50 dark:border-gray-700 dark:text-gray-300 dark:hover:bg-gray-900"
|
||||
>
|
||||
← {t("back")}
|
||||
</Link>
|
||||
{conversation?.peer ? (
|
||||
<div className="flex min-w-0 flex-1 items-center gap-3">
|
||||
<img
|
||||
src={mediaUrl(conversation.peer.photo)}
|
||||
alt={peerName}
|
||||
className="h-10 w-10 rounded-full object-cover"
|
||||
/>
|
||||
<div className="min-w-0">
|
||||
<p className="truncate font-semibold text-gray-900 dark:text-gray-100">{peerName}</p>
|
||||
{conversation.peer.location ? (
|
||||
<p className="truncate text-xs text-gray-500 dark:text-gray-400">📍 {conversation.peer.location}</p>
|
||||
) : null}
|
||||
</div>
|
||||
</div>
|
||||
) : (
|
||||
<p className="flex-1 font-semibold text-gray-900 dark:text-gray-100">{t("title")}</p>
|
||||
)}
|
||||
</div>
|
||||
</header>
|
||||
|
||||
<main className="mx-auto flex w-full max-w-3xl flex-1 flex-col px-4 py-4 sm:px-6">
|
||||
{!isLoggedIn ? (
|
||||
<div className="flex flex-1 items-center justify-center rounded-2xl border border-dashed border-gray-200 bg-white p-8 text-center dark:border-gray-800 dark:bg-gray-900">
|
||||
<div>
|
||||
<p className="text-gray-700 dark:text-gray-200">{t("loginRequired")}</p>
|
||||
<Link href="/join" className="mt-4 inline-flex text-sm font-semibold text-[#ff4d4f] hover:underline">
|
||||
{t("loginAction")}
|
||||
</Link>
|
||||
</div>
|
||||
</div>
|
||||
) : loading ? (
|
||||
<div className="flex flex-1 items-center justify-center">
|
||||
<div className="h-10 w-10 animate-spin rounded-full border-2 border-[#ff4d4f] border-t-transparent" />
|
||||
</div>
|
||||
) : error && !messages.length ? (
|
||||
<div className="flex flex-1 items-center justify-center text-center">
|
||||
<div>
|
||||
<p className="text-gray-700 dark:text-gray-200">{error}</p>
|
||||
<Link href="/chat" className="mt-3 inline-flex text-sm font-semibold text-[#ff4d4f] hover:underline">
|
||||
{t("back")}
|
||||
</Link>
|
||||
</div>
|
||||
</div>
|
||||
) : (
|
||||
<div
|
||||
ref={listRef}
|
||||
className="flex-1 space-y-3 overflow-y-auto rounded-2xl border border-gray-100 bg-white p-4 dark:border-gray-800 dark:bg-gray-900"
|
||||
style={{ minHeight: "50vh" }}
|
||||
>
|
||||
{!messages.length ? (
|
||||
<div className="flex h-full min-h-[40vh] flex-col items-center justify-center text-center text-sm text-gray-500 dark:text-gray-400">
|
||||
<p>{t("emptyThread")}</p>
|
||||
</div>
|
||||
) : (
|
||||
messages.map((message) => (
|
||||
<div
|
||||
key={message.id}
|
||||
className={`flex ${message.mine ? "justify-end" : "justify-start"}`}
|
||||
>
|
||||
<div
|
||||
className={`max-w-[85%] rounded-2xl px-4 py-2.5 text-sm shadow-sm ${
|
||||
message.mine
|
||||
? "rounded-br-md bg-[#ff4d4f] text-white"
|
||||
: "rounded-bl-md bg-gray-100 text-gray-900 dark:bg-gray-800 dark:text-gray-100"
|
||||
}`}
|
||||
>
|
||||
<p className="whitespace-pre-wrap break-words">{message.body}</p>
|
||||
<p
|
||||
className={`mt-1 text-[10px] ${
|
||||
message.mine ? "text-white/70" : "text-gray-400 dark:text-gray-500"
|
||||
}`}
|
||||
>
|
||||
{formatMessageTime(message.created, locale)}
|
||||
</p>
|
||||
</div>
|
||||
</div>
|
||||
))
|
||||
)}
|
||||
<div ref={bottomRef} />
|
||||
</div>
|
||||
)}
|
||||
|
||||
{isLoggedIn && !loading ? (
|
||||
<form onSubmit={handleSend} className="sticky bottom-0 mt-4 pb-4">
|
||||
{error && messages.length ? (
|
||||
<p className="mb-2 text-center text-xs text-red-500">{error}</p>
|
||||
) : null}
|
||||
<div className="flex gap-2 rounded-2xl border border-gray-200 bg-white p-2 shadow-sm dark:border-gray-800 dark:bg-gray-900">
|
||||
<textarea
|
||||
value={draft}
|
||||
onChange={(event) => setDraft(event.target.value)}
|
||||
rows={1}
|
||||
maxLength={2000}
|
||||
placeholder={t("inputPlaceholder")}
|
||||
className="max-h-32 min-h-[44px] flex-1 resize-none bg-transparent px-3 py-2.5 text-sm text-gray-900 outline-none dark:text-gray-100"
|
||||
onKeyDown={(event) => {
|
||||
if (event.key === "Enter" && !event.shiftKey) {
|
||||
event.preventDefault();
|
||||
void handleSend(event as unknown as FormEvent);
|
||||
}
|
||||
}}
|
||||
/>
|
||||
<button
|
||||
type="submit"
|
||||
disabled={!draft.trim() || sending}
|
||||
className="self-end rounded-xl bg-[#ff4d4f] px-4 py-2.5 text-sm font-semibold text-white transition hover:bg-red-600 disabled:cursor-not-allowed disabled:opacity-50"
|
||||
>
|
||||
{sending ? t("sending") : t("send")}
|
||||
</button>
|
||||
</div>
|
||||
</form>
|
||||
) : null}
|
||||
</main>
|
||||
<Footer />
|
||||
</div>
|
||||
);
|
||||
}
|
||||
Reference in New Issue
Block a user