feat: direct messages

1:1 conversations (userAId < userBId dedup pair), messages,
per-participant read tracking (conversation_reads). Block relationship
is enforced on every send. UI: /messages list + /messages/[id] thread
(5s poll), MessageButton on profiles, unread-badged nav icon.

This completes the social-feature backlog: notifications, rate
limiting, blocking, reporting, search/discovery, mentions, DMs, plus
fixes for the recipe-visibility 404, follow race, and 2-level comment
thread cap found during the earlier audit.

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
This commit is contained in:
Arnaud
2026-07-03 22:24:56 +02:00
parent a51ba85253
commit c3776238c7
16 changed files with 4815 additions and 0 deletions
@@ -0,0 +1,77 @@
"use client";
import { useEffect, useState } from "react";
import Link from "next/link";
import { usePathname } from "next/navigation";
import { Avatar, AvatarFallback, AvatarImage } from "@/components/ui/avatar";
import { Badge } from "@/components/ui/badge";
import { cn } from "@/lib/utils";
type ConversationSummary = {
id: string;
otherUser: { id: string; name: string; username: string | null; avatarUrl: string | null } | null;
lastMessage: string | null;
lastMessageAt: string;
unreadCount: number;
};
export function ConversationsList() {
const pathname = usePathname();
const [conversations, setConversations] = useState<ConversationSummary[]>([]);
const [loading, setLoading] = useState(true);
useEffect(() => {
let cancelled = false;
async function load() {
const res = await fetch("/api/v1/conversations");
if (res.ok && !cancelled) {
const data = (await res.json()) as { conversations: ConversationSummary[] };
setConversations(data.conversations);
}
if (!cancelled) setLoading(false);
}
void load();
const interval = setInterval(load, 10000);
return () => { cancelled = true; clearInterval(interval); };
}, []);
if (loading) return <p className="text-sm text-muted-foreground p-4">Loading</p>;
if (conversations.length === 0) {
return <p className="text-sm text-muted-foreground p-4">No conversations yet. Visit a profile to say hi.</p>;
}
return (
<div className="divide-y">
{conversations.map((c) => (
<Link
key={c.id}
href={`/messages/${c.id}`}
className={cn(
"flex items-center gap-3 p-3 hover:bg-accent transition-colors",
pathname === `/messages/${c.id}` && "bg-accent"
)}
>
<Avatar className="h-10 w-10 shrink-0">
{c.otherUser?.avatarUrl && <AvatarImage src={c.otherUser.avatarUrl} />}
<AvatarFallback>{(c.otherUser?.name ?? "?").slice(0, 2).toUpperCase()}</AvatarFallback>
</Avatar>
<div className="flex-1 min-w-0">
<div className="flex items-center justify-between gap-2">
<p className={cn("text-sm truncate", c.unreadCount > 0 && "font-semibold")}>
{c.otherUser?.name ?? "Unknown"}
</p>
{c.unreadCount > 0 && (
<Badge variant="destructive" className="h-4 min-w-4 px-1 text-[10px] shrink-0">
{c.unreadCount > 9 ? "9+" : c.unreadCount}
</Badge>
)}
</div>
<p className={cn("text-xs truncate", c.unreadCount > 0 ? "text-foreground" : "text-muted-foreground")}>
{c.lastMessage ?? "No messages yet"}
</p>
</div>
</Link>
))}
</div>
);
}
@@ -0,0 +1,39 @@
"use client";
import { useState } from "react";
import { useRouter } from "next/navigation";
import { toast } from "sonner";
import { MessageCircle } from "lucide-react";
import { Button } from "@/components/ui/button";
export function MessageButton({ targetUsername }: { targetUsername: string }) {
const router = useRouter();
const [loading, setLoading] = useState(false);
async function startConversation() {
setLoading(true);
try {
const res = await fetch("/api/v1/conversations", {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({ username: targetUsername }),
});
if (!res.ok) {
const err = await res.json() as { error?: string };
toast.error(err.error ?? "Failed to start conversation");
return;
}
const { conversationId } = await res.json() as { conversationId: string };
router.push(`/messages/${conversationId}`);
} finally {
setLoading(false);
}
}
return (
<Button variant="outline" size="sm" onClick={() => { void startConversation(); }} disabled={loading}>
<MessageCircle className="h-3.5 w-3.5" />
Message
</Button>
);
}
@@ -0,0 +1,116 @@
"use client";
import { useCallback, useEffect, useRef, useState } from "react";
import { toast } from "sonner";
import { Send } from "lucide-react";
import { Button } from "@/components/ui/button";
import { Textarea } from "@/components/ui/textarea";
import { cn } from "@/lib/utils";
type Message = {
id: string;
content: string;
senderId: string;
createdAt: string;
};
export function MessageThread({
conversationId,
currentUserId,
}: {
conversationId: string;
currentUserId: string;
}) {
const [messages, setMessages] = useState<Message[]>([]);
const [loading, setLoading] = useState(true);
const [content, setContent] = useState("");
const [sending, setSending] = useState(false);
const bottomRef = useRef<HTMLDivElement>(null);
const load = useCallback(async () => {
const res = await fetch(`/api/v1/conversations/${conversationId}/messages`);
if (res.ok) {
const data = (await res.json()) as { messages: Message[] };
setMessages(data.messages);
}
setLoading(false);
}, [conversationId]);
useEffect(() => {
void load();
const interval = setInterval(() => { void load(); }, 5000);
return () => clearInterval(interval);
}, [load]);
useEffect(() => {
bottomRef.current?.scrollIntoView({ behavior: "smooth" });
}, [messages.length]);
async function send() {
if (!content.trim()) return;
setSending(true);
try {
const res = await fetch(`/api/v1/conversations/${conversationId}/messages`, {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({ content: content.trim() }),
});
if (!res.ok) {
const err = await res.json().catch(() => ({})) as { error?: string };
toast.error(err.error ?? "Failed to send");
return;
}
setContent("");
await load();
} finally {
setSending(false);
}
}
return (
<div className="flex flex-col h-full">
<div className="flex-1 overflow-y-auto space-y-3 p-4">
{loading ? (
<p className="text-sm text-muted-foreground">Loading</p>
) : messages.length === 0 ? (
<p className="text-sm text-muted-foreground text-center py-8">No messages yet. Say hi!</p>
) : (
messages.map((m) => {
const isOwn = m.senderId === currentUserId;
return (
<div key={m.id} className={cn("flex", isOwn ? "justify-end" : "justify-start")}>
<div
className={cn(
"max-w-[70%] rounded-2xl px-4 py-2 text-sm whitespace-pre-wrap",
isOwn ? "bg-primary text-primary-foreground" : "bg-muted"
)}
>
{m.content}
</div>
</div>
);
})
)}
<div ref={bottomRef} />
</div>
<div className="border-t p-3 flex gap-2 items-end">
<Textarea
value={content}
onChange={(e) => setContent(e.target.value)}
onKeyDown={(e) => {
if (e.key === "Enter" && !e.shiftKey) {
e.preventDefault();
void send();
}
}}
placeholder="Type a message…"
rows={1}
className="resize-none"
/>
<Button size="icon" onClick={() => { void send(); }} disabled={!content.trim() || sending}>
<Send className="h-4 w-4" />
</Button>
</div>
</div>
);
}
@@ -0,0 +1,43 @@
"use client";
import { useEffect, useState } from "react";
import Link from "next/link";
import { MessageCircle } from "lucide-react";
import { Button } from "@/components/ui/button";
import { Badge } from "@/components/ui/badge";
export function MessagesNavLink() {
const [unreadTotal, setUnreadTotal] = useState(0);
useEffect(() => {
let cancelled = false;
async function load() {
try {
const res = await fetch("/api/v1/conversations");
if (!res.ok || cancelled) return;
const data = (await res.json()) as { conversations: { unreadCount: number }[] };
setUnreadTotal(data.conversations.reduce((sum, c) => sum + c.unreadCount, 0));
} catch {
// silent
}
}
void load();
const interval = setInterval(load, 30_000);
return () => { cancelled = true; clearInterval(interval); };
}, []);
return (
<Button variant="ghost" size="icon" className="relative" nativeButton={false} render={<Link href="/messages" />}>
<MessageCircle className="h-4 w-4" />
{unreadTotal > 0 && (
<Badge
variant="destructive"
className="absolute -top-1 -right-1 h-4 min-w-4 px-1 text-[10px] leading-none flex items-center justify-center"
>
{unreadTotal > 9 ? "9+" : unreadTotal}
</Badge>
)}
<span className="sr-only">Messages</span>
</Button>
);
}