's'
This commit is contained in:
268
app/[locale]/discuss/[id]/page.tsx
Normal file
268
app/[locale]/discuss/[id]/page.tsx
Normal file
@@ -0,0 +1,268 @@
|
||||
"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>
|
||||
);
|
||||
}
|
||||
@@ -1,9 +1,10 @@
|
||||
"use client";
|
||||
|
||||
import { useEffect, useMemo, useState } from "react";
|
||||
import { useTranslation } from "@/i18n/navigation";
|
||||
import { Link, useTranslation } from "@/i18n/navigation";
|
||||
import Footer from "@/app/components/Footer";
|
||||
import { apiFetch } from "@/app/lib/api-client";
|
||||
import { apiFetch, fetchAuthMe } from "@/app/lib/api-client";
|
||||
import { toggleDiscussionLike } from "@/app/lib/social";
|
||||
import { mediaUrl } from "@/app/lib/media";
|
||||
import { avatarForIndex, avatarForName } from "@/app/data/avatars";
|
||||
|
||||
@@ -19,6 +20,7 @@ interface Topic {
|
||||
lastActive: string;
|
||||
pinned: boolean;
|
||||
excerpt?: string;
|
||||
likedByMe?: boolean;
|
||||
}
|
||||
|
||||
interface DiscussionRecord {
|
||||
@@ -30,6 +32,9 @@ interface DiscussionRecord {
|
||||
excerpt?: string;
|
||||
replies?: number;
|
||||
views?: number;
|
||||
likes?: number;
|
||||
pinned?: boolean;
|
||||
likedByMe?: boolean;
|
||||
created?: string;
|
||||
}
|
||||
|
||||
@@ -143,7 +148,7 @@ const CATEGORIES = [
|
||||
{ key: "目的地", zh: "目的地", en: "Destinations" },
|
||||
];
|
||||
|
||||
function mapDiscussion(topic: DiscussionRecord, index: number): Topic {
|
||||
function mapDiscussion(topic: DiscussionRecord): Topic {
|
||||
const author = topic.author || "NomadCNA";
|
||||
const tags = Array.isArray(topic.tags) ? topic.tags : [];
|
||||
return {
|
||||
@@ -153,11 +158,12 @@ function mapDiscussion(topic: DiscussionRecord, index: number): Topic {
|
||||
avatar: avatarForName(author),
|
||||
views: Number(topic.views || 0),
|
||||
replies: Number(topic.replies || 0),
|
||||
likes: Math.max(3, Math.round(Number(topic.views || 0) / 30) + Number(topic.replies || 0)),
|
||||
likes: Number(topic.likes || 0),
|
||||
category: tags[0] || topic.city || "资源分享",
|
||||
lastActive: topic.created ? new Date(topic.created).toLocaleDateString("zh-CN") : "刚刚",
|
||||
pinned: index < 2,
|
||||
pinned: Boolean(topic.pinned),
|
||||
excerpt: topic.excerpt,
|
||||
likedByMe: Boolean(topic.likedByMe),
|
||||
};
|
||||
}
|
||||
|
||||
@@ -169,6 +175,12 @@ export default function DiscussPage() {
|
||||
const [showComposer, setShowComposer] = useState(false);
|
||||
const [posting, setPosting] = useState(false);
|
||||
const [draft, setDraft] = useState({ title: "", city: "", excerpt: "" });
|
||||
const [isLoggedIn, setIsLoggedIn] = useState(false);
|
||||
const [likingId, setLikingId] = useState<string | null>(null);
|
||||
|
||||
useEffect(() => {
|
||||
fetchAuthMe().then((data) => setIsLoggedIn(Boolean(data?.user?.id)));
|
||||
}, []);
|
||||
|
||||
useEffect(() => {
|
||||
apiFetch<{ items: DiscussionRecord[] }>("/api/discussions")
|
||||
@@ -180,6 +192,25 @@ export default function DiscussPage() {
|
||||
.catch(() => setTopics(FALLBACK_TOPICS));
|
||||
}, []);
|
||||
|
||||
const handleLike = async (topicId: string, event: React.MouseEvent) => {
|
||||
event.preventDefault();
|
||||
event.stopPropagation();
|
||||
if (!isLoggedIn) return;
|
||||
setLikingId(topicId);
|
||||
try {
|
||||
const result = await toggleDiscussionLike(topicId);
|
||||
setTopics((current) =>
|
||||
current.map((topic) =>
|
||||
topic.id === topicId
|
||||
? { ...topic, likes: result.likes, likedByMe: result.liked }
|
||||
: topic
|
||||
)
|
||||
);
|
||||
} finally {
|
||||
setLikingId(null);
|
||||
}
|
||||
};
|
||||
|
||||
const filteredTopics = useMemo(() => topics.filter((topic) => {
|
||||
const matchesCategory = activeCategory === "all" || topic.category === activeCategory;
|
||||
const matchesSearch = topic.title.toLowerCase().includes(searchQuery.toLowerCase());
|
||||
@@ -201,7 +232,7 @@ export default function DiscussPage() {
|
||||
excerpt: draft.excerpt.trim(),
|
||||
}),
|
||||
});
|
||||
setTopics((current) => [mapDiscussion(data.record, 0), ...current]);
|
||||
setTopics((current) => [mapDiscussion(data.record), ...current]);
|
||||
setDraft({ title: "", city: "", excerpt: "" });
|
||||
setShowComposer(false);
|
||||
} finally {
|
||||
@@ -292,9 +323,10 @@ export default function DiscussPage() {
|
||||
|
||||
<div className="space-y-3 sm:space-y-4">
|
||||
{filteredTopics.map((topic) => (
|
||||
<div
|
||||
<Link
|
||||
key={topic.id}
|
||||
className="bg-white dark:bg-gray-900 rounded-xl p-4 sm:p-5 shadow-sm border border-gray-100 dark:border-gray-800 hover:shadow-md transition-shadow cursor-pointer"
|
||||
href={`/discuss/${topic.id}`}
|
||||
className="block bg-white dark:bg-gray-900 rounded-xl p-4 sm:p-5 shadow-sm border border-gray-100 dark:border-gray-800 hover:shadow-md transition-shadow"
|
||||
>
|
||||
<div className="flex items-start gap-3 sm:gap-4">
|
||||
<img
|
||||
@@ -324,11 +356,20 @@ export default function DiscussPage() {
|
||||
<span className="hidden sm:inline">·</span>
|
||||
<span>👁 {topic.views}</span>
|
||||
<span>💬 {topic.replies}</span>
|
||||
<span>❤️ {topic.likes}</span>
|
||||
<button
|
||||
type="button"
|
||||
onClick={(event) => handleLike(topic.id, event)}
|
||||
disabled={likingId === topic.id}
|
||||
className={`inline-flex items-center gap-1 rounded-full px-2 py-0.5 transition ${
|
||||
topic.likedByMe ? "bg-red-50 text-[#ff4d4f] dark:bg-red-950/30" : "hover:bg-gray-100 dark:hover:bg-gray-800"
|
||||
}`}
|
||||
>
|
||||
{topic.likedByMe ? "❤️" : "🤍"} {topic.likes}
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</Link>
|
||||
))}
|
||||
</div>
|
||||
|
||||
|
||||
Reference in New Issue
Block a user