feat: implement threaded replies and enhance feed layout with ThoughtThread component

This commit is contained in:
2025-09-06 21:02:46 +02:00
parent 8a4c07b3f6
commit bf2e280cdd
6 changed files with 269 additions and 36 deletions

View File

@@ -1,11 +1,13 @@
// app/page.tsx // app/page.tsx
import { cookies } from "next/headers"; import { cookies } from "next/headers";
import { getFeed, getMe, getUserProfile, Me } from "@/lib/api"; import { getFeed, getMe, getUserProfile, Me, Thought } from "@/lib/api";
import { ThoughtCard } from "@/components/thought-card"; import { ThoughtCard } from "@/components/thought-card";
import { PostThoughtForm } from "@/components/post-thought-form"; import { PostThoughtForm } from "@/components/post-thought-form";
import { Button } from "@/components/ui/button"; import { Button } from "@/components/ui/button";
import Link from "next/link"; import Link from "next/link";
import { PopularTags } from "@/components/popular-tags"; import { PopularTags } from "@/components/popular-tags";
import { ThoughtThread } from "@/components/thought-thread";
import { buildThoughtThreads } from "@/lib/utils";
// This is now an async Server Component // This is now an async Server Component
export default async function Home() { export default async function Home() {
@@ -32,6 +34,10 @@ async function FeedPage({ token }: { token: string }) {
.map((user) => [user!.username, { avatarUrl: user!.avatarUrl }]) .map((user) => [user!.username, { avatarUrl: user!.avatarUrl }])
); );
const allThoughts = feedData.thoughts;
const { topLevelThoughts, repliesByParentId } =
buildThoughtThreads(allThoughts);
return ( return (
<div className="container mx-auto max-w-4xl p-4 sm:p-6 grid grid-cols-1 md:grid-cols-3 gap-8"> <div className="container mx-auto max-w-4xl p-4 sm:p-6 grid grid-cols-1 md:grid-cols-3 gap-8">
<main className="md:col-span-2 space-y-6"> <main className="md:col-span-2 space-y-6">
@@ -39,23 +45,23 @@ async function FeedPage({ token }: { token: string }) {
<h1 className="text-3xl font-bold">Your Feed</h1> <h1 className="text-3xl font-bold">Your Feed</h1>
</header> </header>
<PostThoughtForm /> <PostThoughtForm />
{feedData.thoughts.map((thought) => ( <main className="space-y-6">
<ThoughtCard {topLevelThoughts.map((thought) => (
<ThoughtThread
key={thought.id} key={thought.id}
thought={thought} thought={thought}
author={{ repliesByParentId={repliesByParentId}
username: thought.authorUsername, authorDetails={authorDetails}
avatarUrl: authorDetails.get(thought.authorUsername)?.avatarUrl,
}}
currentUser={me} currentUser={me}
/> />
))} ))}
{feedData.thoughts.length === 0 && ( {topLevelThoughts.length === 0 && (
<p className="text-center text-muted-foreground pt-8"> <p className="text-center text-muted-foreground pt-8">
Your feed is empty. Follow some users to see their thoughts here! Your feed is empty. Follow some users to see their thoughts here!
</p> </p>
)} )}
</main> </main>
</main>
<aside className="md:col-span-1 space-y-6 pt-20"> <aside className="md:col-span-1 space-y-6 pt-20">
<PopularTags /> <PopularTags />
</aside> </aside>

View File

@@ -1,12 +1,13 @@
import { getMe, getUserProfile, getUserThoughts, Me } from "@/lib/api"; import { getMe, getUserProfile, getUserThoughts, Me } from "@/lib/api";
import { UserAvatar } from "@/components/user-avatar"; import { UserAvatar } from "@/components/user-avatar";
import { ThoughtCard } from "@/components/thought-card";
import { Calendar } from "lucide-react"; import { Calendar } from "lucide-react";
import { Card } from "@/components/ui/card"; import { Card } from "@/components/ui/card";
import { notFound } from "next/navigation"; import { notFound } from "next/navigation";
import { cookies } from "next/headers"; import { cookies } from "next/headers";
import { FollowButton } from "@/components/follow-button"; import { FollowButton } from "@/components/follow-button";
import { TopFriends } from "@/components/top-friends"; import { TopFriends } from "@/components/top-friends";
import { buildThoughtThreads } from "@/lib/utils";
import { ThoughtThread } from "@/components/thought-thread";
interface ProfilePageProps { interface ProfilePageProps {
params: { username: string }; params: { username: string };
@@ -16,10 +17,8 @@ export default async function ProfilePage({ params }: ProfilePageProps) {
const { username } = params; const { username } = params;
const token = (await cookies()).get("auth_token")?.value ?? null; const token = (await cookies()).get("auth_token")?.value ?? null;
// Fetch data in parallel
const userProfilePromise = getUserProfile(username, token); const userProfilePromise = getUserProfile(username, token);
const thoughtsPromise = getUserThoughts(username, token); const thoughtsPromise = getUserThoughts(username, token);
// Fetch the logged-in user's data (if they exist)
const mePromise = token ? getMe(token) : Promise.resolve(null); const mePromise = token ? getMe(token) : Promise.resolve(null);
const [userResult, thoughtsResult, meResult] = await Promise.allSettled([ const [userResult, thoughtsResult, meResult] = await Promise.allSettled([
@@ -33,26 +32,27 @@ export default async function ProfilePage({ params }: ProfilePageProps) {
} }
const user = userResult.value; const user = userResult.value;
const thoughts =
thoughtsResult.status === "fulfilled" ? thoughtsResult.value.thoughts : [];
const me = meResult.status === "fulfilled" ? (meResult.value as Me) : null; const me = meResult.status === "fulfilled" ? (meResult.value as Me) : null;
// *** SIMPLIFIED LOGIC *** const thoughts =
// The follow status is now directly available from the `me` object. thoughtsResult.status === "fulfilled" ? thoughtsResult.value.thoughts : [];
const { topLevelThoughts, repliesByParentId } = buildThoughtThreads(thoughts);
const isOwnProfile = me?.username === user.username; const isOwnProfile = me?.username === user.username;
const isFollowing = const isFollowing =
me?.following?.some( me?.following?.some(
(followedUser) => followedUser.username === user.username (followedUser) => followedUser.username === user.username
) || false; ) || false;
const authorDetails = new Map<string, { avatarUrl?: string | null }>();
authorDetails.set(user.username, { avatarUrl: user.avatarUrl });
return ( return (
<div> <div>
{/* Custom CSS Injection */}
{user.customCss && ( {user.customCss && (
<style dangerouslySetInnerHTML={{ __html: user.customCss }} /> <style dangerouslySetInnerHTML={{ __html: user.customCss }} />
)} )}
{/* Header Image */}
<div <div
className="h-48 bg-gray-200 bg-cover bg-center" className="h-48 bg-gray-200 bg-cover bg-center"
style={{ style={{
@@ -81,7 +81,6 @@ export default async function ProfilePage({ params }: ProfilePageProps) {
</div> </div>
</div> </div>
{/* Render the FollowButton if it's not the user's own profile */}
{!isOwnProfile && token && ( {!isOwnProfile && token && (
<FollowButton <FollowButton
username={user.username} username={user.username}
@@ -99,17 +98,19 @@ export default async function ProfilePage({ params }: ProfilePageProps) {
{/* Thoughts Feed */} {/* Thoughts Feed */}
<div className="mt-8 space-y-4"> <div className="mt-8 space-y-4">
{thoughts.map((thought) => ( {topLevelThoughts.map((thought) => (
<ThoughtCard <ThoughtThread
key={thought.id} key={thought.id}
thought={thought} thought={thought}
author={{ username: user.username, avatarUrl: user.avatarUrl }} repliesByParentId={repliesByParentId}
currentUser={me || null} authorDetails={authorDetails}
currentUser={me}
/> />
))} ))}
{thoughts.length === 0 && ( {topLevelThoughts.length === 0 && (
<p className="text-center text-muted-foreground"> <p className="text-center text-muted-foreground pt-8">
This user hasn&apos;t posted any thoughts yet. Your feed is empty. Follow some users to see their thoughts
here!
</p> </p>
)} )}
</div> </div>

View File

@@ -0,0 +1,90 @@
// components/reply-form.tsx
"use client";
import { useForm } from "react-hook-form";
import { zodResolver } from "@hookform/resolvers/zod";
import { z } from "zod";
import { useRouter } from "next/navigation";
import { Button } from "@/components/ui/button";
import {
Form,
FormField,
FormItem,
FormControl,
FormMessage,
} from "@/components/ui/form";
import { Textarea } from "@/components/ui/textarea";
import { CreateThoughtSchema, createThought } from "@/lib/api";
import { useAuth } from "@/hooks/use-auth";
import { toast } from "sonner";
interface ReplyFormProps {
parentThoughtId: string;
onReplySuccess: () => void; // A callback to close the form after success
}
export function ReplyForm({ parentThoughtId, onReplySuccess }: ReplyFormProps) {
const router = useRouter();
const { token } = useAuth();
const form = useForm<z.infer<typeof CreateThoughtSchema>>({
resolver: zodResolver(CreateThoughtSchema),
defaultValues: {
content: "",
replyToId: parentThoughtId,
visibility: "Public", // Replies default to Public
},
});
async function onSubmit(values: z.infer<typeof CreateThoughtSchema>) {
if (!token) {
toast.error("You must be logged in to reply.");
return;
}
try {
await createThought(values, token);
toast.success("Your reply has been posted!");
form.reset();
onReplySuccess(); // Call the callback
router.refresh(); // Refresh the page to show the new reply
} catch (err) {
toast.error("Failed to post reply. Please try again.");
}
}
return (
<Form {...form}>
<form onSubmit={form.handleSubmit(onSubmit)} className="space-y-2 pt-4">
<FormField
control={form.control}
name="content"
render={({ field }) => (
<FormItem>
<FormControl>
<Textarea
placeholder="Post your reply..."
className="resize-none"
{...field}
/>
</FormControl>
<FormMessage />
</FormItem>
)}
/>
<div className="flex justify-end gap-2">
<Button
type="button"
variant="ghost"
onClick={onReplySuccess} // Close button
>
Cancel
</Button>
<Button type="submit" disabled={form.formState.isSubmitting}>
{form.formState.isSubmitting ? "Replying..." : "Reply"}
</Button>
</div>
</form>
</Form>
);
}

View File

@@ -1,6 +1,11 @@
"use client"; "use client";
import { Card, CardContent, CardHeader } from "@/components/ui/card"; import {
Card,
CardContent,
CardFooter,
CardHeader,
} from "@/components/ui/card";
import { UserAvatar } from "./user-avatar"; import { UserAvatar } from "./user-avatar";
import { deleteThought, Me, Thought } from "@/lib/api"; import { deleteThought, Me, Thought } from "@/lib/api";
import { formatDistanceToNow } from "date-fns"; import { formatDistanceToNow } from "date-fns";
@@ -14,6 +19,7 @@ import {
DropdownMenuItem, DropdownMenuItem,
DropdownMenuTrigger, DropdownMenuTrigger,
} from "@/components/ui/dropdown-menu"; } from "@/components/ui/dropdown-menu";
import { Button } from "@/components/ui/button";
import { import {
AlertDialog, AlertDialog,
AlertDialogAction, AlertDialogAction,
@@ -24,7 +30,14 @@ import {
AlertDialogHeader, AlertDialogHeader,
AlertDialogTitle, AlertDialogTitle,
} from "@/components/ui/alert-dialog"; } from "@/components/ui/alert-dialog";
import { MoreHorizontal, Trash2 } from "lucide-react"; import {
CornerUpLeft,
MessageSquare,
MoreHorizontal,
Trash2,
} from "lucide-react";
import { ReplyForm } from "@/components/reply-form";
import Link from "next/link";
interface ThoughtCardProps { interface ThoughtCardProps {
thought: Thought; thought: Thought;
@@ -33,14 +46,17 @@ interface ThoughtCardProps {
avatarUrl?: string | null; avatarUrl?: string | null;
}; };
currentUser: Me | null; currentUser: Me | null;
isReply?: boolean;
} }
export function ThoughtCard({ export function ThoughtCard({
thought, thought,
author, author,
currentUser, currentUser,
isReply = false,
}: ThoughtCardProps) { }: ThoughtCardProps) {
const [isAlertOpen, setIsAlertOpen] = useState(false); const [isAlertOpen, setIsAlertOpen] = useState(false);
const [isReplyOpen, setIsReplyOpen] = useState(false);
const { token } = useAuth(); const { token } = useAuth();
const router = useRouter(); const router = useRouter();
const timeAgo = formatDistanceToNow(new Date(thought.createdAt), { const timeAgo = formatDistanceToNow(new Date(thought.createdAt), {
@@ -64,6 +80,25 @@ export function ThoughtCard({
return ( return (
<> <>
<div
id={thought.id}
className={!isReply ? "bg-card rounded-xl border shadow-sm" : ""}
>
{thought.replyToId && isReply && (
<div className="px-4 pt-2 text-sm text-muted-foreground flex items-center gap-2">
<CornerUpLeft className="h-4 w-4" />
<span>
Replying to{" "}
<Link
href={`#${thought.replyToId}`}
className="hover:underline text-primary"
>
parent thought
</Link>
</span>
</div>
)}
</div>
<Card> <Card>
<CardHeader className="flex flex-row items-center justify-between space-y-0"> <CardHeader className="flex flex-row items-center justify-between space-y-0">
<div className="flex items-center gap-4"> <div className="flex items-center gap-4">
@@ -95,6 +130,26 @@ export function ThoughtCard({
<CardContent> <CardContent>
<p className="whitespace-pre-wrap break-words">{thought.content}</p> <p className="whitespace-pre-wrap break-words">{thought.content}</p>
</CardContent> </CardContent>
<CardFooter className="border-t px-4 pt-2 pb-2">
<Button
variant="ghost"
size="sm"
onClick={() => setIsReplyOpen(!isReplyOpen)}
>
<MessageSquare className="mr-2 h-4 w-4" />
Reply
</Button>
</CardFooter>
{isReplyOpen && (
<div className="border-t p-4">
<ReplyForm
parentThoughtId={thought.id}
onReplySuccess={() => setIsReplyOpen(false)}
/>
</div>
)}
</Card> </Card>
<AlertDialog open={isAlertOpen} onOpenChange={setIsAlertOpen}> <AlertDialog open={isAlertOpen} onOpenChange={setIsAlertOpen}>
<AlertDialogContent> <AlertDialogContent>

View File

@@ -0,0 +1,52 @@
import { Me, Thought } from "@/lib/api";
import { ThoughtCard } from "./thought-card";
interface ThoughtThreadProps {
thought: Thought;
repliesByParentId: Map<string, Thought[]>;
authorDetails: Map<string, { avatarUrl?: string | null }>;
currentUser: Me | null;
isReply?: boolean;
}
export function ThoughtThread({
thought,
repliesByParentId,
authorDetails,
currentUser,
isReply = false,
}: ThoughtThreadProps) {
const author = {
username: thought.authorUsername,
avatarUrl: null,
...authorDetails.get(thought.authorUsername),
};
const directReplies = repliesByParentId.get(thought.id) || [];
return (
<div className="flex flex-col gap-0">
<ThoughtCard
thought={thought}
author={author}
currentUser={currentUser}
isReply={isReply}
/>
{directReplies.length > 0 && (
<div className="pl-6 border-l-2 border-dashed ml-6 flex flex-col gap-4 pt-4">
{directReplies.map((reply) => (
<ThoughtThread // RECURSIVE CALL
key={reply.id}
thought={reply}
repliesByParentId={repliesByParentId} // Pass the full map down
authorDetails={authorDetails}
currentUser={currentUser}
isReply={true}
/>
))}
</div>
)}
</div>
);
}

View File

@@ -1,6 +1,35 @@
import { clsx, type ClassValue } from "clsx" import { clsx, type ClassValue } from "clsx"
import { twMerge } from "tailwind-merge" import { twMerge } from "tailwind-merge"
import { Thought } from "./api";
export function cn(...inputs: ClassValue[]) { export function cn(...inputs: ClassValue[]) {
return twMerge(clsx(inputs)) return twMerge(clsx(inputs))
} }
export function buildThoughtThreads(allThoughts: Thought[]) {
const repliesByParentId = new Map<string, Thought[]>();
const topLevelThoughts: Thought[] = [];
// 1. Group all thoughts into top-level posts or replies
for (const thought of allThoughts) {
if (thought.replyToId) {
// It's a reply, group it with its parent
const replies = repliesByParentId.get(thought.replyToId) || [];
replies.push(thought);
repliesByParentId.set(thought.replyToId, replies);
} else {
// It's a top-level thought
topLevelThoughts.push(thought);
}
}
// 2. Sort top-level thoughts by date, newest first
topLevelThoughts.sort((a, b) => new Date(b.createdAt).getTime() - new Date(a.createdAt).getTime());
// 3. Sort replies within each thread by date, oldest first for conversational flow
for (const replies of repliesByParentId.values()) {
replies.sort((a, b) => new Date(a.createdAt).getTime() - new Date(b.createdAt).getTime());
}
return { topLevelThoughts, repliesByParentId };
}