Files
gitlab-instance-0a899031_cn…/app/[locale]/discuss/[id]/page.tsx
2026-06-08 06:05:31 -05:00

269 lines
10 KiB
TypeScript

"use client";
import { FormEvent, useEffect, useState } from "react";
import { Link, useLocale } from "@/i18n/navigation";
import { useParams } from "next/navigation";
import Footer from "@/app/components/Footer";
import { fetchAuthMe } from "@/app/lib/api-client";
import {
fetchDiscussion,
fetchDiscussionReplies,
postDiscussionReply,
toggleDiscussionLike,
toggleDiscussionPin,
type DiscussionReply,
} from "@/app/lib/social";
export default function DiscussThreadPage() {
const params = useParams();
const discussionId = String(params?.id || "");
const locale = useLocale();
const [topic, setTopic] = useState<Record<string, unknown> | null>(null);
const [replies, setReplies] = useState<DiscussionReply[]>([]);
const [draft, setDraft] = useState("");
const [loading, setLoading] = useState(true);
const [posting, setPosting] = useState(false);
const [isLoggedIn, setIsLoggedIn] = useState(false);
const [currentUserId, setCurrentUserId] = useState("");
const [liking, setLiking] = useState(false);
const [pinning, setPinning] = useState(false);
const [error, setError] = useState("");
useEffect(() => {
fetchAuthMe().then((data) => {
const userId = String(data?.user?.id || "");
setIsLoggedIn(Boolean(userId));
setCurrentUserId(userId);
});
}, []);
useEffect(() => {
if (!discussionId) return;
let cancelled = false;
Promise.all([fetchDiscussion(discussionId), fetchDiscussionReplies(discussionId)])
.then(([topicData, replyItems]) => {
if (cancelled) return;
setTopic(topicData.item);
setReplies(replyItems);
})
.catch(() => {
if (!cancelled) setError(locale === "zh" ? "加载失败" : "Failed to load");
})
.finally(() => {
if (!cancelled) setLoading(false);
});
return () => {
cancelled = true;
};
}, [discussionId, locale]);
const handleLike = async () => {
if (!isLoggedIn || !discussionId) return;
setLiking(true);
setError("");
try {
const result = await toggleDiscussionLike(discussionId);
setTopic((current) =>
current
? {
...current,
likes: result.likes,
likedByMe: result.liked,
}
: current
);
} catch (err) {
setError(err instanceof Error ? err.message : locale === "zh" ? "点赞失败" : "Like failed");
} finally {
setLiking(false);
}
};
const handlePin = async () => {
if (!isLoggedIn || !discussionId) return;
setPinning(true);
setError("");
try {
const result = await toggleDiscussionPin(discussionId);
setTopic((current) =>
current
? {
...current,
pinned: result.pinned,
}
: current
);
} catch (err) {
setError(err instanceof Error ? err.message : locale === "zh" ? "置顶失败" : "Pin failed");
} finally {
setPinning(false);
}
};
const handleSubmit = async (event: FormEvent) => {
event.preventDefault();
const body = draft.trim();
if (!body || !discussionId) return;
if (!isLoggedIn) {
setError(locale === "zh" ? "请先登录后再回复" : "Please log in to reply");
return;
}
setPosting(true);
setError("");
try {
const reply = await postDiscussionReply(discussionId, body);
setReplies((current) => [...current, reply]);
setDraft("");
setTopic((current) =>
current ? { ...current, replies: Number(current.replies || 0) + 1 } : current
);
} catch (err) {
setError(err instanceof Error ? err.message : locale === "zh" ? "回复失败" : "Reply failed");
} finally {
setPosting(false);
}
};
if (loading) {
return (
<div className="min-h-screen bg-[#fafafa] dark:bg-gray-950">
<div className="mx-auto max-w-3xl animate-pulse px-4 py-10">
<div className="h-40 rounded-2xl bg-gray-200 dark:bg-gray-800" />
</div>
</div>
);
}
if (!topic) {
return (
<div className="flex min-h-screen items-center justify-center bg-[#fafafa] px-4 dark:bg-gray-950">
<div className="text-center">
<p className="text-gray-500 dark:text-gray-400">{error || (locale === "zh" ? "话题不存在" : "Topic not found")}</p>
<Link href="/discuss" className="mt-4 inline-block text-[#ff4d4f]">
{locale === "zh" ? "返回讨论区" : "Back to discussions"}
</Link>
</div>
</div>
);
}
const tags = Array.isArray(topic.tags) ? topic.tags.map(String) : [];
const likedByMe = Boolean(topic.likedByMe);
const likes = Number(topic.likes || 0);
const pinned = Boolean(topic.pinned);
const isAuthor = Boolean(currentUserId && String(topic.authorUserId || "") === currentUserId);
return (
<div className="min-h-screen bg-[#fafafa] dark:bg-gray-950">
<main className="mx-auto max-w-3xl px-4 py-8 sm:px-6">
<Link href="/discuss" className="text-sm text-gray-500 hover:text-[#ff4d4f] dark:text-gray-400">
← {locale === "zh" ? "返回讨论区" : "Back"}
</Link>
<article className="mt-4 rounded-2xl border border-gray-100 bg-white p-6 shadow-sm dark:border-gray-800 dark:bg-gray-900">
<div className="flex flex-wrap gap-2">
{tags.map((tag) => (
<span key={tag} className="rounded-full bg-red-50 px-2.5 py-0.5 text-xs text-[#ff4d4f] dark:bg-red-950/30">
{tag}
</span>
))}
</div>
<div className="mt-3 flex flex-wrap items-start justify-between gap-3">
<h1 className="text-2xl font-bold text-gray-900 dark:text-gray-100">{String(topic.title || "")}</h1>
{pinned ? (
<span className="rounded-full bg-amber-50 px-2.5 py-1 text-xs font-semibold text-amber-700 dark:bg-amber-950/30 dark:text-amber-300">
📌 {locale === "zh" ? "置顶" : "Pinned"}
</span>
) : null}
</div>
<p className="mt-2 text-sm text-gray-500 dark:text-gray-400">
{String(topic.author || "社区成员")}
{topic.city ? ` · ${String(topic.city)}` : ""}
{` · 👁 ${Number(topic.views || 0)} · 💬 ${Number(topic.replies || 0)}`}
</p>
<div className="mt-4 flex flex-wrap items-center gap-2">
<button
type="button"
onClick={handleLike}
disabled={!isLoggedIn || liking}
className={`inline-flex items-center gap-1.5 rounded-full px-3 py-1.5 text-sm font-medium transition ${
likedByMe
? "bg-red-50 text-[#ff4d4f] dark:bg-red-950/30"
: "bg-gray-100 text-gray-600 hover:bg-gray-200 dark:bg-gray-800 dark:text-gray-300 dark:hover:bg-gray-700"
} disabled:opacity-50`}
>
{likedByMe ? "❤️" : "🤍"} {likes}
</button>
{isAuthor ? (
<button
type="button"
onClick={handlePin}
disabled={pinning}
className={`inline-flex items-center gap-1.5 rounded-full px-3 py-1.5 text-sm font-medium transition ${
pinned
? "bg-amber-50 text-amber-700 dark:bg-amber-950/30 dark:text-amber-300"
: "bg-gray-100 text-gray-600 hover:bg-gray-200 dark:bg-gray-800 dark:text-gray-300 dark:hover:bg-gray-700"
} disabled:opacity-50`}
>
📌 {pinned ? (locale === "zh" ? "取消置顶" : "Unpin") : locale === "zh" ? "置顶话题" : "Pin topic"}
</button>
) : null}
</div>
{topic.excerpt ? (
<p className="mt-4 whitespace-pre-wrap text-sm leading-7 text-gray-700 dark:text-gray-300">
{String(topic.excerpt)}
</p>
) : null}
</article>
<section className="mt-6 space-y-3">
<h2 className="text-lg font-semibold text-gray-900 dark:text-gray-100">
{locale === "zh" ? "回复" : "Replies"} ({replies.length})
</h2>
{replies.length ? (
replies.map((reply) => (
<div
key={reply.id}
className="rounded-xl border border-gray-100 bg-white p-4 dark:border-gray-800 dark:bg-gray-900"
>
<div className="flex items-center justify-between gap-3">
<span className="text-sm font-semibold text-gray-900 dark:text-gray-100">
{reply.author || (locale === "zh" ? "成员" : "Member")}
</span>
<span className="text-xs text-gray-400">{reply.created ? new Date(reply.created).toLocaleString() : ""}</span>
</div>
<p className="mt-2 whitespace-pre-wrap text-sm leading-6 text-gray-700 dark:text-gray-300">{reply.body}</p>
</div>
))
) : (
<p className="rounded-xl border border-dashed border-gray-200 p-6 text-center text-sm text-gray-500 dark:border-gray-700 dark:text-gray-400">
{locale === "zh" ? "还没有回复,来抢沙发吧" : "No replies yet"}
</p>
)}
</section>
<form onSubmit={handleSubmit} className="mt-6 rounded-2xl border border-gray-100 bg-white p-4 dark:border-gray-800 dark:bg-gray-900">
<textarea
value={draft}
onChange={(event) => setDraft(event.target.value)}
rows={4}
placeholder={locale === "zh" ? "写下你的经验、建议或提问..." : "Share your thoughts..."}
className="w-full resize-none rounded-xl border border-gray-200 bg-white px-4 py-3 text-sm text-gray-900 focus:border-[#ff4d4f] focus:outline-none dark:border-gray-700 dark:bg-gray-800 dark:text-gray-100"
/>
{error ? <p className="mt-2 text-sm text-red-500">{error}</p> : null}
<div className="mt-3 flex justify-end">
<button
type="submit"
disabled={posting || !draft.trim()}
className="rounded-full bg-[#ff4d4f] px-5 py-2 text-sm font-semibold text-white disabled:opacity-50"
>
{posting ? (locale === "zh" ? "发送中..." : "Posting...") : locale === "zh" ? "发表回复" : "Reply"}
</button>
</div>
</form>
</main>
<Footer />
</div>
);
}