feat: implement threaded replies and enhance feed layout with ThoughtThread component
This commit is contained in:
@@ -1,11 +1,13 @@
|
||||
// app/page.tsx
|
||||
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 { PostThoughtForm } from "@/components/post-thought-form";
|
||||
import { Button } from "@/components/ui/button";
|
||||
import Link from "next/link";
|
||||
import { PopularTags } from "@/components/popular-tags";
|
||||
import { ThoughtThread } from "@/components/thought-thread";
|
||||
import { buildThoughtThreads } from "@/lib/utils";
|
||||
|
||||
// This is now an async Server Component
|
||||
export default async function Home() {
|
||||
@@ -32,6 +34,10 @@ async function FeedPage({ token }: { token: string }) {
|
||||
.map((user) => [user!.username, { avatarUrl: user!.avatarUrl }])
|
||||
);
|
||||
|
||||
const allThoughts = feedData.thoughts;
|
||||
const { topLevelThoughts, repliesByParentId } =
|
||||
buildThoughtThreads(allThoughts);
|
||||
|
||||
return (
|
||||
<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">
|
||||
@@ -39,23 +45,23 @@ async function FeedPage({ token }: { token: string }) {
|
||||
<h1 className="text-3xl font-bold">Your Feed</h1>
|
||||
</header>
|
||||
<PostThoughtForm />
|
||||
{feedData.thoughts.map((thought) => (
|
||||
<ThoughtCard
|
||||
<main className="space-y-6">
|
||||
{topLevelThoughts.map((thought) => (
|
||||
<ThoughtThread
|
||||
key={thought.id}
|
||||
thought={thought}
|
||||
author={{
|
||||
username: thought.authorUsername,
|
||||
avatarUrl: authorDetails.get(thought.authorUsername)?.avatarUrl,
|
||||
}}
|
||||
repliesByParentId={repliesByParentId}
|
||||
authorDetails={authorDetails}
|
||||
currentUser={me}
|
||||
/>
|
||||
))}
|
||||
{feedData.thoughts.length === 0 && (
|
||||
{topLevelThoughts.length === 0 && (
|
||||
<p className="text-center text-muted-foreground pt-8">
|
||||
Your feed is empty. Follow some users to see their thoughts here!
|
||||
</p>
|
||||
)}
|
||||
</main>
|
||||
</main>
|
||||
<aside className="md:col-span-1 space-y-6 pt-20">
|
||||
<PopularTags />
|
||||
</aside>
|
||||
|
@@ -1,12 +1,13 @@
|
||||
import { getMe, getUserProfile, getUserThoughts, Me } from "@/lib/api";
|
||||
import { UserAvatar } from "@/components/user-avatar";
|
||||
import { ThoughtCard } from "@/components/thought-card";
|
||||
import { Calendar } from "lucide-react";
|
||||
import { Card } from "@/components/ui/card";
|
||||
import { notFound } from "next/navigation";
|
||||
import { cookies } from "next/headers";
|
||||
import { FollowButton } from "@/components/follow-button";
|
||||
import { TopFriends } from "@/components/top-friends";
|
||||
import { buildThoughtThreads } from "@/lib/utils";
|
||||
import { ThoughtThread } from "@/components/thought-thread";
|
||||
|
||||
interface ProfilePageProps {
|
||||
params: { username: string };
|
||||
@@ -16,10 +17,8 @@ export default async function ProfilePage({ params }: ProfilePageProps) {
|
||||
const { username } = params;
|
||||
const token = (await cookies()).get("auth_token")?.value ?? null;
|
||||
|
||||
// Fetch data in parallel
|
||||
const userProfilePromise = getUserProfile(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 [userResult, thoughtsResult, meResult] = await Promise.allSettled([
|
||||
@@ -33,26 +32,27 @@ export default async function ProfilePage({ params }: ProfilePageProps) {
|
||||
}
|
||||
|
||||
const user = userResult.value;
|
||||
const thoughts =
|
||||
thoughtsResult.status === "fulfilled" ? thoughtsResult.value.thoughts : [];
|
||||
const me = meResult.status === "fulfilled" ? (meResult.value as Me) : null;
|
||||
|
||||
// *** SIMPLIFIED LOGIC ***
|
||||
// The follow status is now directly available from the `me` object.
|
||||
const thoughts =
|
||||
thoughtsResult.status === "fulfilled" ? thoughtsResult.value.thoughts : [];
|
||||
const { topLevelThoughts, repliesByParentId } = buildThoughtThreads(thoughts);
|
||||
|
||||
const isOwnProfile = me?.username === user.username;
|
||||
const isFollowing =
|
||||
me?.following?.some(
|
||||
(followedUser) => followedUser.username === user.username
|
||||
) || false;
|
||||
|
||||
const authorDetails = new Map<string, { avatarUrl?: string | null }>();
|
||||
authorDetails.set(user.username, { avatarUrl: user.avatarUrl });
|
||||
|
||||
return (
|
||||
<div>
|
||||
{/* Custom CSS Injection */}
|
||||
{user.customCss && (
|
||||
<style dangerouslySetInnerHTML={{ __html: user.customCss }} />
|
||||
)}
|
||||
|
||||
{/* Header Image */}
|
||||
<div
|
||||
className="h-48 bg-gray-200 bg-cover bg-center"
|
||||
style={{
|
||||
@@ -81,7 +81,6 @@ export default async function ProfilePage({ params }: ProfilePageProps) {
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* Render the FollowButton if it's not the user's own profile */}
|
||||
{!isOwnProfile && token && (
|
||||
<FollowButton
|
||||
username={user.username}
|
||||
@@ -99,17 +98,19 @@ export default async function ProfilePage({ params }: ProfilePageProps) {
|
||||
|
||||
{/* Thoughts Feed */}
|
||||
<div className="mt-8 space-y-4">
|
||||
{thoughts.map((thought) => (
|
||||
<ThoughtCard
|
||||
{topLevelThoughts.map((thought) => (
|
||||
<ThoughtThread
|
||||
key={thought.id}
|
||||
thought={thought}
|
||||
author={{ username: user.username, avatarUrl: user.avatarUrl }}
|
||||
currentUser={me || null}
|
||||
repliesByParentId={repliesByParentId}
|
||||
authorDetails={authorDetails}
|
||||
currentUser={me}
|
||||
/>
|
||||
))}
|
||||
{thoughts.length === 0 && (
|
||||
<p className="text-center text-muted-foreground">
|
||||
This user hasn't posted any thoughts yet.
|
||||
{topLevelThoughts.length === 0 && (
|
||||
<p className="text-center text-muted-foreground pt-8">
|
||||
Your feed is empty. Follow some users to see their thoughts
|
||||
here!
|
||||
</p>
|
||||
)}
|
||||
</div>
|
||||
|
90
thoughts-frontend/components/reply-form.tsx
Normal file
90
thoughts-frontend/components/reply-form.tsx
Normal 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>
|
||||
);
|
||||
}
|
@@ -1,6 +1,11 @@
|
||||
"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 { deleteThought, Me, Thought } from "@/lib/api";
|
||||
import { formatDistanceToNow } from "date-fns";
|
||||
@@ -14,6 +19,7 @@ import {
|
||||
DropdownMenuItem,
|
||||
DropdownMenuTrigger,
|
||||
} from "@/components/ui/dropdown-menu";
|
||||
import { Button } from "@/components/ui/button";
|
||||
import {
|
||||
AlertDialog,
|
||||
AlertDialogAction,
|
||||
@@ -24,7 +30,14 @@ import {
|
||||
AlertDialogHeader,
|
||||
AlertDialogTitle,
|
||||
} 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 {
|
||||
thought: Thought;
|
||||
@@ -33,14 +46,17 @@ interface ThoughtCardProps {
|
||||
avatarUrl?: string | null;
|
||||
};
|
||||
currentUser: Me | null;
|
||||
isReply?: boolean;
|
||||
}
|
||||
|
||||
export function ThoughtCard({
|
||||
thought,
|
||||
author,
|
||||
currentUser,
|
||||
isReply = false,
|
||||
}: ThoughtCardProps) {
|
||||
const [isAlertOpen, setIsAlertOpen] = useState(false);
|
||||
const [isReplyOpen, setIsReplyOpen] = useState(false);
|
||||
const { token } = useAuth();
|
||||
const router = useRouter();
|
||||
const timeAgo = formatDistanceToNow(new Date(thought.createdAt), {
|
||||
@@ -64,6 +80,25 @@ export function ThoughtCard({
|
||||
|
||||
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>
|
||||
<CardHeader className="flex flex-row items-center justify-between space-y-0">
|
||||
<div className="flex items-center gap-4">
|
||||
@@ -95,6 +130,26 @@ export function ThoughtCard({
|
||||
<CardContent>
|
||||
<p className="whitespace-pre-wrap break-words">{thought.content}</p>
|
||||
</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>
|
||||
<AlertDialog open={isAlertOpen} onOpenChange={setIsAlertOpen}>
|
||||
<AlertDialogContent>
|
||||
|
52
thoughts-frontend/components/thought-thread.tsx
Normal file
52
thoughts-frontend/components/thought-thread.tsx
Normal 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>
|
||||
);
|
||||
}
|
@@ -1,6 +1,35 @@
|
||||
import { clsx, type ClassValue } from "clsx"
|
||||
import { twMerge } from "tailwind-merge"
|
||||
import { Thought } from "./api";
|
||||
|
||||
export function cn(...inputs: ClassValue[]) {
|
||||
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 };
|
||||
}
|
Reference in New Issue
Block a user