feat(social): follows, favorites, comments, reactions, collections, public profiles

Follow/unfollow users. Recipe favorites. Threaded comments with emoji reactions.
Collections (public/private) with shared member invite. Activity feed.
Public profile pages at /u/[username].
This commit is contained in:
Arnaud
2026-07-01 08:10:30 +02:00
parent d9d58fd01a
commit 9d02a69250
23 changed files with 1825 additions and 0 deletions
@@ -0,0 +1,114 @@
"use client";
import { useState } from "react";
import { toast } from "sonner";
const REACTIONS: Record<string, string> = {
like: "👍",
love: "❤️",
laugh: "😂",
wow: "😮",
sad: "😢",
fire: "🔥",
};
type Props = {
recipeId: string;
commentId: string;
initialCounts?: Record<string, number>;
initialUserReactions?: string[];
};
export function CommentReactions({ recipeId, commentId, initialCounts = {}, initialUserReactions = [] }: Props) {
const [counts, setCounts] = useState<Record<string, number>>(initialCounts);
const [userReactions, setUserReactions] = useState<string[]>(initialUserReactions);
const [pending, setPending] = useState<string | null>(null);
async function toggle(type: string) {
if (pending) return;
setPending(type);
// Optimistic update
const hasReacted = userReactions.includes(type);
setUserReactions((prev) =>
hasReacted ? prev.filter((r) => r !== type) : [...prev, type],
);
setCounts((prev) => ({
...prev,
[type]: Math.max(0, (prev[type] ?? 0) + (hasReacted ? -1 : 1)),
}));
try {
const res = await fetch(`/api/v1/recipes/${recipeId}/comments/${commentId}/reactions`, {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({ type }),
});
if (!res.ok) {
// Revert optimistic update
setUserReactions((prev) =>
hasReacted ? [...prev, type] : prev.filter((r) => r !== type),
);
setCounts((prev) => ({
...prev,
[type]: Math.max(0, (prev[type] ?? 0) + (hasReacted ? 1 : -1)),
}));
if (res.status === 401) {
toast.error("Sign in to react to comments");
} else {
toast.error("Failed to update reaction");
}
return;
}
const data = await res.json() as { counts: Record<string, number>; added: boolean };
setCounts(data.counts);
setUserReactions((prev) => {
if (data.added && !prev.includes(type)) return [...prev, type];
if (!data.added && prev.includes(type)) return prev.filter((r) => r !== type);
return prev;
});
} catch {
// Revert on network error
setUserReactions((prev) =>
hasReacted ? [...prev, type] : prev.filter((r) => r !== type),
);
setCounts((prev) => ({
...prev,
[type]: Math.max(0, (prev[type] ?? 0) + (hasReacted ? 1 : -1)),
}));
toast.error("Failed to update reaction");
} finally {
setPending(null);
}
}
return (
<div className="flex flex-wrap gap-1">
{Object.entries(REACTIONS).map(([type, emoji]) => {
const reacted = userReactions.includes(type);
const cnt = counts[type] ?? 0;
return (
<button
key={type}
onClick={() => void toggle(type)}
disabled={pending === type}
className={[
"inline-flex items-center gap-0.5 rounded-full border px-2 py-0.5 text-xs transition-colors",
reacted
? "border-primary bg-primary/10 text-primary"
: "border-border bg-transparent text-muted-foreground hover:border-primary/50 hover:text-foreground",
pending === type ? "opacity-60 cursor-not-allowed" : "cursor-pointer",
].join(" ")}
aria-label={`${reacted ? "Remove" : "Add"} ${type} reaction`}
aria-pressed={reacted}
>
<span>{emoji}</span>
{cnt > 0 && <span>{cnt}</span>}
</button>
);
})}
</div>
);
}
@@ -0,0 +1,240 @@
"use client";
import { useState, useEffect, useCallback } from "react";
import { MessageCircle, Reply, Trash2 } from "lucide-react";
import { toast } from "sonner";
import { Button } from "@/components/ui/button";
import { Textarea } from "@/components/ui/textarea";
import { Avatar, AvatarFallback, AvatarImage } from "@/components/ui/avatar";
import { Separator } from "@/components/ui/separator";
import { CommentReactions } from "@/components/social/comment-reactions";
type Comment = {
id: string;
content: string;
parentId: string | null;
createdAt: string;
userId: string;
userName: string;
userUsername: string | null;
userAvatarUrl: string | null;
};
function timeAgo(dateStr: string) {
const diff = Date.now() - new Date(dateStr).getTime();
const mins = Math.floor(diff / 60000);
if (mins < 1) return "just now";
if (mins < 60) return `${mins}m ago`;
const hours = Math.floor(mins / 60);
if (hours < 24) return `${hours}h ago`;
return `${Math.floor(hours / 24)}d ago`;
}
function CommentForm({
recipeId,
parentId,
onSubmit,
placeholder = "Add a comment…",
onCancel,
}: {
recipeId: string;
parentId?: string;
onSubmit: () => void;
placeholder?: string;
onCancel?: () => void;
}) {
const [content, setContent] = useState("");
const [submitting, setSubmitting] = useState(false);
async function submit() {
if (!content.trim()) return;
setSubmitting(true);
try {
const res = await fetch(`/api/v1/recipes/${recipeId}/comments`, {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({ content: content.trim(), parentId }),
});
if (!res.ok) { toast.error("Failed to post comment"); return; }
setContent("");
onSubmit();
} finally {
setSubmitting(false);
}
}
return (
<div className="space-y-2">
<Textarea
value={content}
onChange={(e) => setContent(e.target.value)}
placeholder={placeholder}
rows={2}
disabled={submitting}
/>
<div className="flex gap-2">
<Button size="sm" onClick={submit} disabled={!content.trim() || submitting}>
{submitting ? "Posting…" : "Post"}
</Button>
{onCancel && <Button size="sm" variant="ghost" onClick={onCancel}>Cancel</Button>}
</div>
</div>
);
}
function CommentItem({
comment,
replies,
currentUserId,
recipeId,
onRefresh,
}: {
comment: Comment;
replies: Comment[];
currentUserId?: string;
recipeId: string;
onRefresh: () => void;
}) {
const [showReply, setShowReply] = useState(false);
const isOwn = comment.userId === currentUserId;
async function deleteComment() {
const res = await fetch(`/api/v1/comments/${comment.id}`, { method: "DELETE" });
if (res.ok) { toast.success("Deleted"); onRefresh(); }
else toast.error("Failed to delete");
}
return (
<div className="space-y-3">
<div className="flex gap-3">
<Avatar className="h-7 w-7 shrink-0 mt-0.5">
<AvatarImage src={comment.userAvatarUrl ?? ""} />
<AvatarFallback className="text-xs">{comment.userName.slice(0, 2).toUpperCase()}</AvatarFallback>
</Avatar>
<div className="flex-1 min-w-0 space-y-1">
<div className="flex items-baseline gap-2">
<span className="font-medium text-sm">{comment.userName}</span>
<span className="text-xs text-muted-foreground">{timeAgo(comment.createdAt)}</span>
</div>
<p className="text-sm leading-relaxed whitespace-pre-wrap">{comment.content}</p>
<CommentReactions recipeId={recipeId} commentId={comment.id} initialCounts={{}} initialUserReactions={[]} />
<div className="flex items-center gap-2">
{currentUserId && (
<button
onClick={() => setShowReply(!showReply)}
className="text-xs text-muted-foreground hover:text-foreground flex items-center gap-1"
>
<Reply className="h-3 w-3" /> Reply
</button>
)}
{isOwn && (
<button
onClick={deleteComment}
className="text-xs text-muted-foreground hover:text-destructive flex items-center gap-1"
>
<Trash2 className="h-3 w-3" /> Delete
</button>
)}
</div>
{showReply && (
<CommentForm
recipeId={recipeId}
parentId={comment.id}
onSubmit={() => { setShowReply(false); onRefresh(); }}
placeholder="Reply…"
onCancel={() => setShowReply(false)}
/>
)}
</div>
</div>
{replies.length > 0 && (
<div className="ml-10 space-y-3 border-l pl-4">
{replies.map((reply) => (
<div key={reply.id} className="flex gap-3">
<Avatar className="h-6 w-6 shrink-0 mt-0.5">
<AvatarImage src={reply.userAvatarUrl ?? ""} />
<AvatarFallback className="text-xs">{reply.userName.slice(0, 2).toUpperCase()}</AvatarFallback>
</Avatar>
<div className="flex-1 min-w-0 space-y-1">
<div className="flex items-baseline gap-2">
<span className="font-medium text-sm">{reply.userName}</span>
<span className="text-xs text-muted-foreground">{timeAgo(reply.createdAt)}</span>
</div>
<p className="text-sm leading-relaxed">{reply.content}</p>
{reply.userId === currentUserId && (
<button
onClick={async () => {
const res = await fetch(`/api/v1/comments/${reply.id}`, { method: "DELETE" });
if (res.ok) { toast.success("Deleted"); onRefresh(); }
}}
className="text-xs text-muted-foreground hover:text-destructive flex items-center gap-1"
>
<Trash2 className="h-3 w-3" /> Delete
</button>
)}
</div>
</div>
))}
</div>
)}
</div>
);
}
export function CommentsSection({
recipeId,
currentUserId,
}: {
recipeId: string;
currentUserId?: string;
}) {
const [comments, setComments] = useState<Comment[]>([]);
const [loading, setLoading] = useState(true);
const load = useCallback(async () => {
const res = await fetch(`/api/v1/recipes/${recipeId}/comments`);
if (res.ok) setComments(await res.json() as Comment[]);
setLoading(false);
}, [recipeId]);
useEffect(() => { void load(); }, [load]);
const topLevel = comments.filter((c) => !c.parentId);
const replies = (parentId: string) => comments.filter((c) => c.parentId === parentId);
return (
<div className="space-y-6">
<div className="flex items-center gap-2">
<MessageCircle className="h-5 w-5" />
<h2 className="text-xl font-semibold">Comments</h2>
{!loading && <span className="text-muted-foreground text-sm">({comments.length})</span>}
</div>
{currentUserId && (
<CommentForm recipeId={recipeId} onSubmit={load} placeholder="Share your thoughts…" />
)}
{loading ? (
<p className="text-sm text-muted-foreground">Loading</p>
) : topLevel.length === 0 ? (
<p className="text-sm text-muted-foreground">No comments yet. Be the first!</p>
) : (
<div className="space-y-6">
{topLevel.map((comment, i) => (
<div key={comment.id}>
{i > 0 && <Separator className="mb-6" />}
<CommentItem
comment={comment}
replies={replies(comment.id)}
currentUserId={currentUserId}
recipeId={recipeId}
onRefresh={load}
/>
</div>
))}
</div>
)}
</div>
);
}
@@ -0,0 +1,38 @@
"use client";
import { useState } from "react";
import { Heart } from "lucide-react";
import { toast } from "sonner";
import { Button } from "@/components/ui/button";
import { cn } from "@/lib/utils";
export function FavoriteButton({
recipeId,
initialFavorited = false,
}: {
recipeId: string;
initialFavorited?: boolean;
}) {
const [favorited, setFavorited] = useState(initialFavorited);
const [loading, setLoading] = useState(false);
async function toggle() {
setLoading(true);
try {
const res = await fetch(`/api/v1/recipes/${recipeId}/favorite`, {
method: favorited ? "DELETE" : "POST",
});
if (!res.ok) return;
setFavorited(!favorited);
} finally {
setLoading(false);
}
}
return (
<Button variant="ghost" size="sm" onClick={toggle} disabled={loading} className="gap-1.5">
<Heart className={cn("h-4 w-4", favorited && "fill-red-500 text-red-500")} />
{favorited ? "Saved" : "Save"}
</Button>
);
}
@@ -0,0 +1,42 @@
"use client";
import { useState } from "react";
import { toast } from "sonner";
import { Button } from "@/components/ui/button";
export function FollowButton({
targetUserId: _targetUserId,
targetUsername,
initialFollowing = false,
}: {
targetUserId: string;
targetUsername: string;
initialFollowing?: boolean;
}) {
const [following, setFollowing] = useState(initialFollowing);
const [loading, setLoading] = useState(false);
async function toggle() {
setLoading(true);
try {
const res = await fetch(`/api/v1/users/${targetUsername}/follow`, {
method: following ? "DELETE" : "POST",
});
if (!res.ok) {
const err = await res.json() as { error?: string };
toast.error(err.error ?? "Failed");
return;
}
setFollowing(!following);
toast.success(following ? "Unfollowed" : "Following");
} finally {
setLoading(false);
}
}
return (
<Button variant={following ? "outline" : "default"} size="sm" onClick={toggle} disabled={loading}>
{loading ? "…" : following ? "Following" : "Follow"}
</Button>
);
}
@@ -0,0 +1,72 @@
"use client";
import { useState } from "react";
import { Plus } from "lucide-react";
import { useRouter } from "next/navigation";
import { toast } from "sonner";
import { Button } from "@/components/ui/button";
import { Dialog, DialogContent, DialogHeader, DialogTitle } from "@/components/ui/dialog";
import { Input } from "@/components/ui/input";
import { Textarea } from "@/components/ui/textarea";
import { Label } from "@/components/ui/label";
export function NewCollectionButton() {
const router = useRouter();
const [open, setOpen] = useState(false);
const [name, setName] = useState("");
const [description, setDescription] = useState("");
const [isPublic, setIsPublic] = useState(false);
const [saving, setSaving] = useState(false);
async function create() {
if (!name.trim()) return;
setSaving(true);
try {
const res = await fetch("/api/v1/collections", {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({ name: name.trim(), description: description.trim() || undefined, isPublic }),
});
if (!res.ok) { toast.error("Failed to create"); return; }
const { id } = await res.json() as { id: string };
toast.success("Collection created");
setOpen(false);
setName(""); setDescription(""); setIsPublic(false);
router.push(`/collections/${id}`);
router.refresh();
} finally {
setSaving(false);
}
}
return (
<>
<Button size="sm" onClick={() => setOpen(true)}>
<Plus className="h-4 w-4" /> New collection
</Button>
<Dialog open={open} onOpenChange={setOpen}>
<DialogContent className="max-w-md">
<DialogHeader><DialogTitle>New collection</DialogTitle></DialogHeader>
<div className="space-y-4">
<div className="space-y-2">
<Label htmlFor="col-name">Name</Label>
<Input id="col-name" value={name} onChange={(e) => setName(e.target.value)} placeholder="Weekend dinners" />
</div>
<div className="space-y-2">
<Label htmlFor="col-desc">Description</Label>
<Textarea id="col-desc" value={description} onChange={(e) => setDescription(e.target.value)} rows={2} placeholder="Optional…" />
</div>
<label className="flex items-center gap-2 text-sm cursor-pointer">
<input type="checkbox" checked={isPublic} onChange={(e) => setIsPublic(e.target.checked)} className="rounded" />
Make public
</label>
<div className="flex gap-2 justify-end">
<Button variant="outline" onClick={() => setOpen(false)}>Cancel</Button>
<Button onClick={create} disabled={!name.trim() || saving}>{saving ? "Creating…" : "Create"}</Button>
</div>
</div>
</DialogContent>
</Dialog>
</>
);
}
@@ -0,0 +1,69 @@
"use client";
import { useState } from "react";
import { Star } from "lucide-react";
import { toast } from "sonner";
import { cn } from "@/lib/utils";
export function RatingStars({
recipeId,
initialScore = 0,
readonly = false,
size = "default",
}: {
recipeId: string;
initialScore?: number;
readonly?: boolean;
size?: "sm" | "default";
}) {
const [score, setScore] = useState(initialScore);
const [hovered, setHovered] = useState(0);
const [saving, setSaving] = useState(false);
async function rate(value: number) {
if (readonly || saving) return;
setSaving(true);
try {
const res = await fetch(`/api/v1/recipes/${recipeId}/rate`, {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({ score: value }),
});
if (!res.ok) {
const err = await res.json() as { error?: string };
toast.error(err.error ?? "Failed to rate");
return;
}
setScore(value);
toast.success("Rating saved");
} finally {
setSaving(false);
}
}
const iconSize = size === "sm" ? "h-3.5 w-3.5" : "h-5 w-5";
const display = hovered || score;
return (
<div className={cn("flex items-center gap-0.5", readonly && "pointer-events-none")}>
{[1, 2, 3, 4, 5].map((i) => (
<button
key={i}
type="button"
disabled={readonly || saving}
onMouseEnter={() => !readonly && setHovered(i)}
onMouseLeave={() => !readonly && setHovered(0)}
onClick={() => rate(i)}
className={cn("transition-colors", !readonly && "hover:scale-110")}
>
<Star
className={cn(
iconSize,
i <= display ? "fill-yellow-400 text-yellow-400" : "text-muted-foreground/30"
)}
/>
</button>
))}
</div>
);
}