chore: code refactor

This commit is contained in:
gosangam
2026-06-13 02:24:42 +05:30
parent cc5633c37a
commit 439664a97d
151 changed files with 1387 additions and 1138 deletions
@@ -24,7 +24,7 @@
import Link from "next/link";
import { ReadingSettings } from "@/components/reading-settings";
import { NotificationBell } from "@/components/notification-bell";
import { NotificationBell } from "@/components/layout/notification-bell";
import { useAuth } from "@/components/auth/auth-provider";
export function SiteHeader() {
+7 -47
View File
@@ -34,6 +34,7 @@ import { Settings, X } from "lucide-react";
import { cn } from "@/lib/utils";
import type { RelationshipResult, RelationshipState } from "@/lib/social";
import { ProfileActions } from "@/components/profile/profile-actions";
import { UserAvatar } from "@/components/ui/user-avatar";
import {
FollowListDrawer,
type FollowMode,
@@ -110,10 +111,14 @@ export function ProfileHeader({
return (
<>
<header className="flex flex-col items-center text-center gap-4 pt-4 pb-6 sm:pt-6 sm:pb-8">
<Avatar
<UserAvatar
src={avatarURL}
name={name}
onZoom={avatarURL ? () => setZoomOpen(true) : undefined}
className="size-24 sm:size-28"
textClassName="text-3xl"
interactive
onClick={avatarURL ? () => setZoomOpen(true) : undefined}
ariaLabel={`View ${name}'s profile picture`}
/>
<div className="space-y-2">
<div className="space-y-1">
@@ -242,51 +247,6 @@ function Stat({
);
}
function Avatar({
src,
name,
onZoom,
}: {
src: string | null;
name: string;
/** Provided when the avatar should be interactive — the parent shows
* the zoom modal on click. Omit (or pass undefined) to render the
* initials placeholder as a plain non-clickable element. */
onZoom?: () => void;
}) {
if (src) {
return (
<button
type="button"
onClick={onZoom}
aria-label={`View ${name}'s profile picture`}
className="rounded-full focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2"
>
<Image
src={src}
alt={name}
width={112}
height={112}
className="size-24 sm:size-28 rounded-full object-cover ring-1 ring-foreground/10 hover:ring-foreground/30 transition"
unoptimized
/>
</button>
);
}
const initials =
name
.split(/\s+/)
.map((p) => p[0])
.slice(0, 2)
.join("")
.toUpperCase() || "?";
return (
<div className="size-24 sm:size-28 rounded-full bg-primary/15 text-primary flex items-center justify-center text-3xl font-semibold ring-1 ring-foreground/10">
{initials}
</div>
);
}
/**
* AvatarZoomModal — portaled full-screen overlay with the avatar shown
* inside a large circular crop. Click the backdrop or press Escape to
+2 -28
View File
@@ -14,9 +14,9 @@
import { useState } from "react";
import Link from "next/link";
import Image from "next/image";
import { usePathname, useRouter } from "next/navigation";
import { User as UserIcon, FolderOpen, Bookmark, LogOut, Menu } from "lucide-react";
import { UserAvatar } from "@/components/ui/user-avatar";
import {
Drawer,
DrawerContent,
@@ -98,7 +98,7 @@ function MobileSidebar({ user }: { user: User }) {
function SidebarHeader({ user }: { user: User }) {
return (
<div className="flex items-center gap-3 px-3 py-3 rounded-lg bg-card ring-1 ring-foreground/10">
<Avatar src={user.avatar_url} name={user.name} />
<UserAvatar src={user.avatar_url} name={user.name} />
<div className="min-w-0">
<p className="text-sm font-semibold text-foreground truncate">
{user.name}
@@ -161,29 +161,3 @@ function SidebarFooter() {
);
}
function Avatar({ src, name }: { src: string | null; name: string }) {
if (src) {
return (
<Image
src={src}
alt={name}
width={40}
height={40}
className="size-10 rounded-full object-cover ring-1 ring-foreground/10 shrink-0"
unoptimized
/>
);
}
const initials =
name
.split(/\s+/)
.map((p) => p[0])
.slice(0, 2)
.join("")
.toUpperCase() || "?";
return (
<div className="size-10 rounded-full bg-primary/15 text-primary flex items-center justify-center text-sm font-semibold ring-1 ring-foreground/10 shrink-0">
{initials}
</div>
);
}
+7 -28
View File
@@ -6,8 +6,8 @@
* thing visitors do, plus an action slot for an "Edit profile" button.
*/
import Image from "next/image";
import type { User } from "@/lib/auth";
import { UserAvatar } from "@/components/ui/user-avatar";
export function ProfileViewHeader({
user,
@@ -20,7 +20,12 @@ export function ProfileViewHeader({
}) {
return (
<header className="flex flex-col sm:flex-row sm:items-center gap-5 sm:gap-6">
<Avatar src={user.avatar_url} name={user.name} />
<UserAvatar
src={user.avatar_url}
name={user.name}
className="size-20 sm:size-22"
textClassName="text-2xl"
/>
<div className="flex-1 min-w-0">
<div className="flex items-start justify-between gap-3">
<div className="min-w-0">
@@ -43,29 +48,3 @@ export function ProfileViewHeader({
);
}
function Avatar({ src, name }: { src: string | null; name: string }) {
if (src) {
return (
<Image
src={src}
alt={name}
width={88}
height={88}
className="size-20 sm:size-22 rounded-full object-cover ring-1 ring-foreground/10"
unoptimized
/>
);
}
const initials =
name
.split(/\s+/)
.map((p) => p[0])
.slice(0, 2)
.join("")
.toUpperCase() || "?";
return (
<div className="size-20 sm:size-22 rounded-full bg-primary/15 text-primary flex items-center justify-center text-2xl font-semibold ring-1 ring-foreground/10">
{initials}
</div>
);
}
@@ -19,7 +19,7 @@ import Link from "next/link";
import { Lock } from "lucide-react";
import { cn } from "@/lib/utils";
import type { Collection } from "@/lib/social";
import { quoteCardBgStyle } from "./post-card-shared";
import { quoteCardBgStyle } from "../post/post-card-shared";
export function CollectionGridCard({
collection: c,
@@ -30,8 +30,8 @@ import {
} from "lucide-react";
import { cn } from "@/lib/utils";
import { collections, type Collection, type Post } from "@/lib/social";
import { PostGridCard } from "./post-grid-card";
import { quoteCardBgStyle } from "./post-card-shared";
import { PostGridCard } from "../post/post-grid-card";
import { quoteCardBgStyle } from "../post/post-card-shared";
type FetchState = "idle" | "loading" | "loaded" | "error";
+144
View File
@@ -0,0 +1,144 @@
"use client";
/**
* CommentMenu — the kebab (⋮) overflow menu on a comment: Pin / Report /
* Delete (each shown only when permitted). Rendered in a portal with a
* transparent full-screen backdrop that swallows the dismiss click, so it
* can't reach (and accidentally close) the surrounding vaul comments drawer.
*/
import { useRef, useState } from "react";
import { createPortal } from "react-dom";
import { Flag, MoreVertical, Pin, PinOff, Trash2 } from "lucide-react";
import { cn } from "@/lib/utils";
export function CommentMenu({
canPin,
isPinned,
canDelete,
canReport,
onPin,
onDelete,
onReport,
}: {
canPin: boolean;
isPinned: boolean;
canDelete: boolean;
canReport: boolean;
onPin: () => void;
onDelete: () => void;
onReport: () => void;
}) {
const [open, setOpen] = useState(false);
const [pos, setPos] = useState<{ top: number; right: number } | null>(null);
const btnRef = useRef<HTMLButtonElement>(null);
// Nothing actionable → no kebab at all.
if (!canPin && !canDelete && !canReport) return null;
function openMenu() {
const r = btnRef.current?.getBoundingClientRect();
if (r) setPos({ top: r.bottom + 4, right: window.innerWidth - r.right });
setOpen(true);
}
return (
<>
<button
ref={btnRef}
type="button"
onClick={openMenu}
aria-label="Comment options"
aria-haspopup="menu"
aria-expanded={open}
className="-mr-1 -mt-0.5 size-7 shrink-0 inline-flex items-center justify-center rounded-md text-muted-foreground hover:text-foreground hover:bg-muted transition-colors"
>
<MoreVertical className="size-4" />
</button>
{open && pos && typeof document !== "undefined"
? createPortal(
<>
<div
className="fixed inset-0 z-[100]"
aria-hidden
onClick={(e) => {
e.stopPropagation();
setOpen(false);
}}
/>
<div
role="menu"
style={{ position: "fixed", top: pos.top, right: pos.right }}
className="z-[101] min-w-40 rounded-lg border border-border bg-card shadow-lg py-1 animate-in fade-in-0 zoom-in-95"
>
{canPin ? (
<MenuItem
icon={isPinned ? <PinOff className="size-4" /> : <Pin className="size-4" />}
onClick={() => {
setOpen(false);
onPin();
}}
>
{isPinned ? "Unpin" : "Pin"}
</MenuItem>
) : null}
{canReport ? (
<MenuItem
icon={<Flag className="size-4" />}
onClick={() => {
setOpen(false);
onReport();
}}
>
Report
</MenuItem>
) : null}
{canDelete ? (
<MenuItem
icon={<Trash2 className="size-4" />}
danger
onClick={() => {
setOpen(false);
onDelete();
}}
>
Delete
</MenuItem>
) : null}
</div>
</>,
document.body,
)
: null}
</>
);
}
function MenuItem({
icon,
children,
onClick,
danger = false,
}: {
icon: React.ReactNode;
children: React.ReactNode;
onClick: () => void;
danger?: boolean;
}) {
return (
<button
type="button"
role="menuitem"
onClick={onClick}
className={cn(
"flex w-full items-center gap-2.5 px-3 py-2 text-left text-sm transition-colors",
danger
? "text-destructive hover:bg-destructive/10"
: "text-foreground hover:bg-muted",
)}
>
<span className="shrink-0">{icon}</span>
{children}
</button>
);
}
@@ -0,0 +1,135 @@
"use client";
/**
* ReportCommentModal — compact category + reason form for reporting a comment.
* Controlled by the parent via `comment` (null = closed). Submits through the
* comments API and toasts the outcome.
*/
import { useEffect, useState } from "react";
import { toast } from "sonner";
import { cn } from "@/lib/utils";
import {
comments as commentsApi,
SocialError,
type Comment,
type PostReportCategory,
} from "@/lib/social";
const REPORT_CATEGORIES: { value: PostReportCategory; label: string }[] = [
{ value: "spam", label: "Spam or misleading" },
{ value: "harassment", label: "Harassment or bullying" },
{ value: "misinformation", label: "Misinformation" },
{ value: "inappropriate", label: "Inappropriate content" },
{ value: "other", label: "Something else" },
];
export function ReportCommentModal({
comment,
onClose,
}: {
comment: Comment | null;
onClose: () => void;
}) {
const [category, setCategory] = useState<PostReportCategory>("spam");
const [reason, setReason] = useState("");
const [working, setWorking] = useState(false);
useEffect(() => {
if (comment) {
setCategory("spam");
setReason("");
setWorking(false);
}
}, [comment]);
if (!comment) return null;
async function submit() {
if (!comment) return;
setWorking(true);
try {
await commentsApi.report(comment.id, category, reason.trim());
toast("Thanks — your report was submitted", { duration: 2500 });
onClose();
} catch (err) {
toast.error(
err instanceof SocialError ? err.message : "Could not submit report",
{ duration: 3000 },
);
} finally {
setWorking(false);
}
}
return (
<div className="fixed inset-0 z-[110] flex items-center justify-center px-4">
<div
className="absolute inset-0 bg-foreground/40 backdrop-blur-sm"
onClick={() => !working && onClose()}
aria-hidden
/>
<div
role="dialog"
aria-modal="true"
className="relative w-full max-w-md rounded-2xl border border-border bg-card shadow-xl p-5"
>
<h2 className="font-[family-name:var(--font-title)] font-semibold text-lg text-foreground">
Report comment
</h2>
<p className="mt-1 text-sm text-muted-foreground">
Reports are private and reviewed by our team.
</p>
<div className="mt-4 space-y-1.5">
{REPORT_CATEGORIES.map((c) => (
<label
key={c.value}
className={cn(
"flex items-center gap-3 rounded-md border px-3 py-2 cursor-pointer transition-colors",
category === c.value
? "border-primary bg-primary/5"
: "border-border hover:bg-muted",
)}
>
<input
type="radio"
name="comment-report-category"
value={c.value}
checked={category === c.value}
onChange={() => setCategory(c.value)}
className="accent-primary"
/>
<span className="text-sm text-foreground">{c.label}</span>
</label>
))}
</div>
<textarea
value={reason}
onChange={(e) => setReason(e.target.value)}
rows={2}
maxLength={2000}
placeholder="Add details (optional)"
className="mt-3 w-full resize-none rounded-md border border-border bg-background px-3 py-2 text-base sm:text-sm text-foreground outline-none focus-visible:ring-2 focus-visible:ring-primary/40"
/>
<div className="mt-4 flex items-center justify-end gap-2">
<button
type="button"
onClick={onClose}
disabled={working}
className="h-10 px-4 rounded-md text-sm font-medium text-foreground hover:bg-muted transition-colors disabled:opacity-50"
>
Cancel
</button>
<button
type="button"
onClick={submit}
disabled={working}
className="h-10 px-4 rounded-md text-sm font-medium bg-destructive text-white hover:bg-destructive/90 transition-colors disabled:opacity-60"
>
{working ? "Submitting…" : "Submit report"}
</button>
</div>
</div>
</div>
);
}
+227
View File
@@ -0,0 +1,227 @@
"use client";
/**
* CommentRow — one comment (top-level or reply) in the comments drawer.
*
* Top-level rows own a lazily-loaded, flat reply thread (one level deep) and
* register a splice hook so the drawer can drop a freshly-posted reply in;
* replies render the "Replying to @handle" prefix. Like is optimistic; the
* kebab (Pin / Delete / Report) lives in CommentMenu; deletes/reports bubble
* up to the drawer's modals via onRequest* callbacks.
*/
import { useEffect, useRef, useState } from "react";
import { HiHeart, HiOutlineHeart } from "react-icons/hi2";
import { Pin } from "lucide-react";
import { toast } from "sonner";
import { cn } from "@/lib/utils";
import { comments as commentsApi, SocialError, type Comment } from "@/lib/social";
import { UserAvatar } from "@/components/ui/user-avatar";
import { timeAgo } from "@/lib/time";
import { CommentMenu } from "./comment-menu";
export function CommentRow({
comment,
viewerId,
isPostAuthor,
onReply,
onLikeChange,
onPinToggle,
onRequestDelete,
onRequestReport,
requireAuth,
registerThread,
isReply = false,
}: {
comment: Comment;
viewerId?: string;
isPostAuthor: boolean;
onReply: (c: Comment) => void;
onLikeChange: (likes: number, liked: boolean) => void;
onPinToggle: () => void;
onRequestDelete: (c: Comment) => void;
onRequestReport: (c: Comment) => void;
requireAuth: () => Promise<boolean>;
/** Top-level rows register a callback so a newly-posted reply can be spliced
* into their open thread. Replies pass nothing. */
registerThread?: (fn: ((c: Comment) => void) | null) => void;
isReply?: boolean;
}) {
const [replies, setReplies] = useState<Comment[]>([]);
const [showReplies, setShowReplies] = useState(false);
const [repliesLoaded, setRepliesLoaded] = useState(false);
const likeBusy = useRef(false);
const canDelete = viewerId === comment.user_id || isPostAuthor;
const canReport = !!viewerId && viewerId !== comment.user_id;
const pinnable = isPostAuthor && !isReply;
// Expose a splice hook so the drawer can append a reply created from the
// composer. Replies created while collapsed still get the count bump; they
// show once expanded (re-fetched) or appended if already open.
useEffect(() => {
if (isReply || !registerThread) return;
registerThread((c: Comment) => {
if (c.body === "__deleted__") {
setReplies((prev) => prev.filter((x) => x.id !== c.id));
return;
}
setRepliesLoaded(true);
setShowReplies(true);
setReplies((prev) =>
prev.some((x) => x.id === c.id) ? prev : [...prev, c],
);
});
return () => registerThread(null);
}, [isReply, registerThread]);
async function toggleReplies() {
if (!showReplies && !repliesLoaded) {
try {
const rows = await commentsApi.replies(comment.id, { limit: 50 });
setReplies(rows ?? []);
setRepliesLoaded(true);
} catch {
/* ignore */
}
}
setShowReplies((v) => !v);
}
async function likeToggle() {
if (likeBusy.current) return;
if (!(await requireAuth())) return;
likeBusy.current = true;
const next = !comment.viewer_has_liked;
// optimistic
onLikeChange(Math.max(0, comment.likes_count + (next ? 1 : -1)), next);
try {
const res = next
? await commentsApi.like(comment.id)
: await commentsApi.unlike(comment.id);
onLikeChange(res.likes_count, next);
} catch (err) {
onLikeChange(comment.likes_count, comment.viewer_has_liked);
toast.error(
err instanceof SocialError ? err.message : "Could not update like",
{ duration: 3000 },
);
} finally {
likeBusy.current = false;
}
}
return (
<li className={cn(isReply && "mt-3")}>
<div className="flex gap-3">
<UserAvatar
src={comment.author_avatar_url}
name={comment.author_name}
className="size-9"
textClassName="text-xs"
/>
<div className="min-w-0 flex-1">
<div className="flex items-start justify-between gap-2">
<div className="flex min-w-0 flex-wrap items-center gap-x-2 gap-y-0.5">
<span className="text-sm font-semibold text-foreground truncate">
{comment.author_name}
</span>
{!isReply && comment.pinned_at ? (
<span className="inline-flex items-center gap-1 rounded-full bg-primary/10 px-1.5 py-0.5 text-[10px] font-medium text-primary">
<Pin className="size-3" /> Pinned
</span>
) : null}
<span className="text-xs text-muted-foreground">
{timeAgo(comment.created_at)}
</span>
</div>
<CommentMenu
canPin={pinnable}
isPinned={!!comment.pinned_at}
canDelete={canDelete}
canReport={canReport}
onPin={onPinToggle}
onDelete={() => onRequestDelete(comment)}
onReport={() => onRequestReport(comment)}
/>
</div>
<p className="mt-0.5 whitespace-pre-wrap break-words text-sm text-foreground">
{comment.reply_to_handle ? (
<span className="font-medium text-primary">
@{comment.reply_to_handle}{" "}
</span>
) : null}
{comment.body}
</p>
{/* Inline action row */}
<div className="mt-1.5 flex items-center gap-4 text-xs text-muted-foreground">
<button
type="button"
onClick={likeToggle}
className="inline-flex items-center gap-1 hover:text-foreground transition-colors"
aria-label={comment.viewer_has_liked ? "Unlike" : "Like"}
>
{comment.viewer_has_liked ? (
<HiHeart className="size-4 text-red-500" />
) : (
<HiOutlineHeart className="size-4" />
)}
{comment.likes_count > 0 ? (
<span className="tabular-nums">{comment.likes_count}</span>
) : null}
</button>
<button
type="button"
onClick={() => onReply(comment)}
className="font-medium hover:text-foreground transition-colors"
>
Reply
</button>
</div>
{/* Replies */}
{!isReply && comment.reply_count > 0 ? (
<button
type="button"
onClick={toggleReplies}
className="mt-2 text-xs font-medium text-primary hover:underline"
>
{showReplies
? "Hide replies"
: `View ${comment.reply_count} ${comment.reply_count === 1 ? "reply" : "replies"}`}
</button>
) : null}
{!isReply && showReplies ? (
<ul className="mt-1 border-l border-border pl-3">
{replies.map((r) => (
<CommentRow
key={r.id}
comment={r}
viewerId={viewerId}
isPostAuthor={isPostAuthor}
onReply={onReply}
onLikeChange={(likes, liked) =>
setReplies((prev) =>
prev.map((x) =>
x.id === r.id
? { ...x, likes_count: likes, viewer_has_liked: liked }
: x,
),
)
}
onPinToggle={() => {}}
onRequestDelete={onRequestDelete}
onRequestReport={onRequestReport}
requireAuth={requireAuth}
isReply
/>
))}
</ul>
) : null}
</div>
</div>
</li>
);
}
@@ -0,0 +1,376 @@
"use client";
/**
* PostCommentsDrawer — the comments sheet for a post.
*
* Right-side on desktop, bottom on mobile (vaul `direction`), with a FULLY
* TRANSPARENT overlay so the post stays visible behind it while reading the
* thread. Anyone signed in can comment; the composer gates anonymous users
* through the auth modal.
*
* Threading is one level deep: top-level comments each own a single flat
* thread of replies. Replying to a reply still lands in that one thread,
* addressed (visually) to whoever was answered. The post author can pin one
* comment (shown first here and in the card footer) and delete any comment;
* a comment's author can delete their own (a thread root takes its replies
* with it — behind a confirm). Likes show a count only.
*
* This file owns the drawer shell, the comment list + pagination, the
* composer (with emoji picker), and the optimistic mutation wiring. The row
* (CommentRow), its kebab menu (CommentMenu), and the report dialog
* (ReportCommentModal) live in sibling files.
*/
import { useCallback, useEffect, useRef, useState } from "react";
import { Loader2, Send, X } from "lucide-react";
import { toast } from "sonner";
import { cn } from "@/lib/utils";
import {
comments as commentsApi,
SocialError,
type Comment,
type Post,
} from "@/lib/social";
import { useAuth } from "@/components/auth/auth-provider";
import { useAuthGate } from "@/components/auth/auth-gate";
import { useMediaQuery } from "@/components/selection-toolbar/shared";
import { Drawer, DrawerContent } from "@/components/ui/drawer";
import { ConfirmModal } from "@/components/ui/confirm-modal";
import { EmojiPicker } from "@/components/ui/emoji-picker";
import { CommentRow } from "./comment-row";
import { ReportCommentModal } from "./comment-report-modal";
const PAGE = 20;
export function PostCommentsDrawer({
open,
post,
onClose,
onPinnedChange,
onCountChange,
}: {
open: boolean;
post: Post;
onClose: () => void;
/** Notifies the parent (the card footer) when the pinned comment changes,
* so the footer's pinned line stays in sync without a refetch. */
onPinnedChange?: (pinned: Comment | null) => void;
/** Notifies the parent of a net change to the post's comment count (+1 on a
* new comment/reply, −N when a comment/thread is deleted) so the footer
* count stays live. */
onCountChange?: (delta: number) => void;
}) {
const { user } = useAuth();
const { requireAuth } = useAuthGate();
const isMobile = useMediaQuery("(max-width: 767px)");
const direction = isMobile ? "bottom" : "right";
const isPostAuthor = !!user && user.id === post.user_id;
const [items, setItems] = useState<Comment[]>([]);
const [loading, setLoading] = useState(true);
const [hasMore, setHasMore] = useState(false);
const [posting, setPosting] = useState(false);
const [draft, setDraft] = useState("");
// The comment being replied to (null = a new top-level comment).
const [replyTo, setReplyTo] = useState<{ id: string; handle: string } | null>(
null,
);
const [toDelete, setToDelete] = useState<Comment | null>(null);
const [toReport, setToReport] = useState<Comment | null>(null);
const inputRef = useRef<HTMLTextAreaElement>(null);
// Load the first page whenever the drawer opens for a post.
useEffect(() => {
if (!open) return;
let cancelled = false;
setLoading(true);
setItems([]);
setReplyTo(null);
commentsApi
.list(post.id, { limit: PAGE, offset: 0 })
.then((rows) => {
if (cancelled) return;
setItems(rows ?? []);
setHasMore((rows?.length ?? 0) === PAGE);
})
.catch(() => {})
.finally(() => !cancelled && setLoading(false));
return () => {
cancelled = true;
};
}, [open, post.id]);
const loadMore = useCallback(async () => {
try {
const rows = await commentsApi.list(post.id, {
limit: PAGE,
offset: items.length,
});
setItems((prev) => [...prev, ...(rows ?? [])]);
setHasMore((rows?.length ?? 0) === PAGE);
} catch {
/* leave the list as-is on error */
}
}, [post.id, items.length]);
// Replace a comment in place (after a like toggle / reply-count bump).
const patch = useCallback((id: string, fn: (c: Comment) => Comment) => {
setItems((prev) => prev.map((c) => (c.id === id ? fn(c) : c)));
}, []);
async function submit() {
const body = draft.trim();
if (!body || posting) return;
if (!(await requireAuth())) return;
setPosting(true);
try {
const created = await commentsApi.create(post.id, body, replyTo?.id);
setDraft("");
onCountChange?.(1);
if (created.parent_id) {
// A reply — bump the root's count and append into its open thread.
bumpReply(created.parent_id, created);
setReplyTo(null);
} else {
// Top-level — drop it in just below any pinned comment.
setItems((prev) => {
const pinnedFirst = prev[0]?.pinned_at ? 1 : 0;
return [
...prev.slice(0, pinnedFirst),
created,
...prev.slice(pinnedFirst),
];
});
}
} catch (err) {
toast.error(
err instanceof SocialError ? err.message : "Could not post comment",
{ duration: 3000 },
);
} finally {
setPosting(false);
}
}
// Append a freshly-created reply into its root thread's open reply list (if
// loaded) and bump the visible reply count.
const repliesRef = useRef<Record<string, (c: Comment) => void>>({});
function bumpReply(rootId: string, reply: Comment) {
patch(rootId, (c) => ({ ...c, reply_count: c.reply_count + 1 }));
repliesRef.current[rootId]?.(reply);
}
function startReply(target: Comment) {
// Reply chip addresses whoever was tapped; the thread is the root.
setReplyTo({ id: target.id, handle: target.author_handle });
inputRef.current?.focus();
}
// Insert an emoji at the caret (or append if the textarea isn't focused),
// then restore the caret just after it so typing can continue.
function insertEmoji(emoji: string) {
const el = inputRef.current;
const start = el?.selectionStart ?? draft.length;
const end = el?.selectionEnd ?? draft.length;
const next = draft.slice(0, start) + emoji + draft.slice(end);
setDraft(next);
requestAnimationFrame(() => {
const node = inputRef.current;
if (!node) return;
node.focus();
const caret = start + emoji.length;
node.setSelectionRange(caret, caret);
});
}
async function pinToggle(c: Comment) {
const pinning = !c.pinned_at;
try {
if (pinning) await commentsApi.pin(c.id);
else await commentsApi.unpin(c.id);
// Reload the first page so pinned-first ordering is authoritative.
const rows = await commentsApi.list(post.id, { limit: PAGE, offset: 0 });
setItems(rows ?? []);
setHasMore((rows?.length ?? 0) === PAGE);
onPinnedChange?.(
pinning ? { ...c, pinned_at: new Date().toISOString() } : null,
);
toast(pinning ? "Comment pinned" : "Comment unpinned", { duration: 1800 });
} catch (err) {
toast.error(
err instanceof SocialError ? err.message : "Could not update pin",
{ duration: 3000 },
);
}
}
async function confirmDelete() {
if (!toDelete) return;
const c = toDelete;
await commentsApi.delete(c.id);
// A thread root takes its replies with it; a reply removes just itself.
onCountChange?.(-(c.parent_id ? 1 : 1 + c.reply_count));
if (c.parent_id) {
// A reply — drop the root's count; the thread list prunes itself.
patch(c.parent_id, (p) => ({
...p,
reply_count: Math.max(0, p.reply_count - 1),
}));
repliesRef.current[c.parent_id]?.({ ...c, body: "__deleted__" });
} else {
setItems((prev) => prev.filter((x) => x.id !== c.id));
if (c.pinned_at) onPinnedChange?.(null);
}
}
return (
<>
<Drawer
open={open}
direction={direction}
repositionInputs={false}
onOpenChange={(o) => {
if (!o) onClose();
}}
>
<DrawerContent
direction={direction}
// Transparent scrim: keep the post visible behind the sheet.
overlayClassName="bg-transparent"
className={cn(
"bg-card flex flex-col shadow-2xl",
isMobile ? "h-[80vh]" : "h-full w-[420px] max-w-[92vw]",
)}
>
<div className="flex items-center justify-between border-b border-border px-4 py-3 shrink-0">
<h2 className="text-base font-semibold text-foreground">Comments</h2>
<button
type="button"
onClick={onClose}
aria-label="Close comments"
className="size-8 inline-flex items-center justify-center rounded-lg text-muted-foreground hover:text-foreground hover:bg-muted transition-colors"
>
<X className="size-4" />
</button>
</div>
<div className="flex-1 overflow-y-auto overscroll-contain px-4 py-3">
{loading ? (
<div className="flex justify-center py-10">
<Loader2 className="size-5 animate-spin text-muted-foreground" />
</div>
) : items.length === 0 ? (
<p className="py-10 text-center text-sm text-muted-foreground">
No comments yet. Be the first to comment.
</p>
) : (
<ul className="space-y-4">
{items.map((c) => (
<CommentRow
key={c.id}
comment={c}
viewerId={user?.id}
isPostAuthor={isPostAuthor}
onReply={startReply}
onLikeChange={(likes, liked) =>
patch(c.id, (x) => ({
...x,
likes_count: likes,
viewer_has_liked: liked,
}))
}
onPinToggle={() => pinToggle(c)}
onRequestDelete={setToDelete}
onRequestReport={setToReport}
requireAuth={requireAuth}
registerThread={(fn) => {
if (fn) repliesRef.current[c.id] = fn;
else delete repliesRef.current[c.id];
}}
/>
))}
{hasMore ? (
<li>
<button
type="button"
onClick={loadMore}
className="text-sm font-medium text-primary hover:underline"
>
Load more comments
</button>
</li>
) : null}
</ul>
)}
</div>
{/* Composer */}
<div className="border-t border-border p-3 shrink-0">
{replyTo ? (
<div className="mb-2 flex items-center justify-between rounded-md bg-muted/60 px-3 py-1.5 text-xs text-muted-foreground">
<span>
Replying to{" "}
<span className="font-medium">@{replyTo.handle}</span>
</span>
<button
type="button"
onClick={() => setReplyTo(null)}
aria-label="Cancel reply"
className="rounded p-0.5 hover:text-foreground"
>
<X className="size-3.5" />
</button>
</div>
) : null}
<div className="flex items-end gap-2">
<EmojiPicker onSelect={insertEmoji} />
<textarea
ref={inputRef}
value={draft}
onChange={(e) => setDraft(e.target.value)}
onKeyDown={(e) => {
if (e.key === "Enter" && !e.shiftKey) {
e.preventDefault();
submit();
}
}}
rows={1}
maxLength={2000}
placeholder={replyTo ? "Write a reply…" : "Add a comment…"}
className="flex-1 resize-none rounded-lg border border-border bg-background px-3 py-2 text-base sm:text-sm text-foreground outline-none focus-visible:ring-2 focus-visible:ring-primary/40 max-h-32"
/>
<button
type="button"
onClick={submit}
disabled={posting || draft.trim() === ""}
aria-label="Post comment"
className="size-10 shrink-0 inline-flex items-center justify-center rounded-lg bg-primary text-primary-foreground hover:bg-primary/90 transition-colors disabled:opacity-50"
>
{posting ? (
<Loader2 className="size-4 animate-spin" />
) : (
<Send className="size-4" />
)}
</button>
</div>
</div>
</DrawerContent>
</Drawer>
<ConfirmModal
open={toDelete !== null}
onClose={() => setToDelete(null)}
title="Delete this comment?"
message={
toDelete && !toDelete.parent_id && toDelete.reply_count > 0
? "Its replies will be deleted too. This can't be undone."
: "This can't be undone."
}
confirmLabel="Delete"
onConfirm={confirmDelete}
/>
<ReportCommentModal comment={toReport} onClose={() => setToReport(null)} />
</>
);
}
-749
View File
@@ -1,749 +0,0 @@
"use client";
/**
* PostCommentsDrawer — the comments sheet for a post.
*
* Right-side on desktop, bottom on mobile (vaul `direction`), with a FULLY
* TRANSPARENT overlay so the post stays visible behind it while reading the
* thread. Anyone signed in can comment; the composer gates anonymous users
* through the auth modal.
*
* Threading is one level deep: top-level comments each own a single flat
* thread of replies. Replying to a reply still lands in that one thread,
* addressed (visually) to whoever was answered. The post author can pin one
* comment (shown first here and in the card footer) and delete any comment;
* a comment's author can delete their own (a thread root takes its replies
* with it — behind a confirm). Likes show a count only.
*/
import { useCallback, useEffect, useRef, useState } from "react";
import Image from "next/image";
import { HiHeart, HiOutlineHeart } from "react-icons/hi2";
import { Loader2, Pin, PinOff, Send, Trash2, X } from "lucide-react";
import { toast } from "sonner";
import { cn } from "@/lib/utils";
import {
comments as commentsApi,
SocialError,
type Comment,
type Post,
type PostReportCategory,
} from "@/lib/social";
import { useAuth } from "@/components/auth/auth-provider";
import { useAuthGate } from "@/components/auth/auth-gate";
import { useMediaQuery } from "@/components/selection-toolbar/shared";
import { Drawer, DrawerContent } from "@/components/ui/drawer";
import { ConfirmModal } from "@/components/ui/confirm-modal";
const PAGE = 20;
export function PostCommentsDrawer({
open,
post,
onClose,
onPinnedChange,
}: {
open: boolean;
post: Post;
onClose: () => void;
/** Notifies the parent (the card footer) when the pinned comment changes,
* so the footer's pinned line stays in sync without a refetch. */
onPinnedChange?: (pinned: Comment | null) => void;
}) {
const { user } = useAuth();
const { requireAuth } = useAuthGate();
const isMobile = useMediaQuery("(max-width: 767px)");
const direction = isMobile ? "bottom" : "right";
const isPostAuthor = !!user && user.id === post.user_id;
const [items, setItems] = useState<Comment[]>([]);
const [loading, setLoading] = useState(true);
const [hasMore, setHasMore] = useState(false);
const [posting, setPosting] = useState(false);
const [draft, setDraft] = useState("");
// The comment being replied to (null = a new top-level comment).
const [replyTo, setReplyTo] = useState<{ id: string; handle: string } | null>(
null,
);
const [toDelete, setToDelete] = useState<Comment | null>(null);
const [toReport, setToReport] = useState<Comment | null>(null);
const inputRef = useRef<HTMLTextAreaElement>(null);
// Load the first page whenever the drawer opens for a post.
useEffect(() => {
if (!open) return;
let cancelled = false;
setLoading(true);
setItems([]);
setReplyTo(null);
commentsApi
.list(post.id, { limit: PAGE, offset: 0 })
.then((rows) => {
if (cancelled) return;
setItems(rows ?? []);
setHasMore((rows?.length ?? 0) === PAGE);
})
.catch(() => {})
.finally(() => !cancelled && setLoading(false));
return () => {
cancelled = true;
};
}, [open, post.id]);
const loadMore = useCallback(async () => {
try {
const rows = await commentsApi.list(post.id, {
limit: PAGE,
offset: items.length,
});
setItems((prev) => [...prev, ...(rows ?? [])]);
setHasMore((rows?.length ?? 0) === PAGE);
} catch {
/* leave the list as-is on error */
}
}, [post.id, items.length]);
// Replace a comment in place (after a like toggle / reply-count bump).
const patch = useCallback((id: string, fn: (c: Comment) => Comment) => {
setItems((prev) => prev.map((c) => (c.id === id ? fn(c) : c)));
}, []);
async function submit() {
const body = draft.trim();
if (!body || posting) return;
if (!(await requireAuth())) return;
setPosting(true);
try {
const created = await commentsApi.create(
post.id,
body,
replyTo?.id,
);
setDraft("");
if (created.parent_id) {
// A reply — bump the root's count and append into its open thread.
bumpReply(created.parent_id, created);
setReplyTo(null);
} else {
// Top-level — drop it in just below any pinned comment.
setItems((prev) => {
const pinnedFirst = prev[0]?.pinned_at ? 1 : 0;
return [
...prev.slice(0, pinnedFirst),
created,
...prev.slice(pinnedFirst),
];
});
}
} catch (err) {
toast.error(
err instanceof SocialError ? err.message : "Could not post comment",
{ duration: 3000 },
);
} finally {
setPosting(false);
}
}
// Append a freshly-created reply into its root thread's open reply list (if
// loaded) and bump the visible reply count.
const repliesRef = useRef<Record<string, (c: Comment) => void>>({});
function bumpReply(rootId: string, reply: Comment) {
patch(rootId, (c) => ({ ...c, reply_count: c.reply_count + 1 }));
repliesRef.current[rootId]?.(reply);
}
function startReply(target: Comment) {
// Reply chip addresses whoever was tapped; the thread is the root.
setReplyTo({ id: target.id, handle: target.author_handle });
inputRef.current?.focus();
}
async function pinToggle(c: Comment) {
const pinning = !c.pinned_at;
try {
if (pinning) await commentsApi.pin(c.id);
else await commentsApi.unpin(c.id);
// Reload the first page so pinned-first ordering is authoritative.
const rows = await commentsApi.list(post.id, { limit: PAGE, offset: 0 });
setItems(rows ?? []);
setHasMore((rows?.length ?? 0) === PAGE);
onPinnedChange?.(pinning ? { ...c, pinned_at: new Date().toISOString() } : null);
toast(pinning ? "Comment pinned" : "Comment unpinned", { duration: 1800 });
} catch (err) {
toast.error(
err instanceof SocialError ? err.message : "Could not update pin",
{ duration: 3000 },
);
}
}
async function confirmDelete() {
if (!toDelete) return;
const c = toDelete;
await commentsApi.delete(c.id);
if (c.parent_id) {
// A reply — drop the root's count; the thread list prunes itself.
patch(c.parent_id, (p) => ({
...p,
reply_count: Math.max(0, p.reply_count - 1),
}));
repliesRef.current[c.parent_id]?.({ ...c, body: "__deleted__" });
} else {
setItems((prev) => prev.filter((x) => x.id !== c.id));
if (c.pinned_at) onPinnedChange?.(null);
}
}
return (
<>
<Drawer
open={open}
direction={direction}
repositionInputs={false}
onOpenChange={(o) => {
if (!o) onClose();
}}
>
<DrawerContent
direction={direction}
// Transparent scrim: keep the post visible behind the sheet.
overlayClassName="bg-transparent"
className={cn(
"bg-card flex flex-col shadow-2xl",
isMobile ? "h-[80vh]" : "h-full w-[420px] max-w-[92vw]",
)}
>
<div className="flex items-center justify-between border-b border-border px-4 py-3 shrink-0">
<h2 className="text-base font-semibold text-foreground">Comments</h2>
<button
type="button"
onClick={onClose}
aria-label="Close comments"
className="size-8 inline-flex items-center justify-center rounded-lg text-muted-foreground hover:text-foreground hover:bg-muted transition-colors"
>
<X className="size-4" />
</button>
</div>
<div className="flex-1 overflow-y-auto overscroll-contain px-4 py-3">
{loading ? (
<div className="flex justify-center py-10">
<Loader2 className="size-5 animate-spin text-muted-foreground" />
</div>
) : items.length === 0 ? (
<p className="py-10 text-center text-sm text-muted-foreground">
No comments yet. Be the first to comment.
</p>
) : (
<ul className="space-y-4">
{items.map((c) => (
<CommentRow
key={c.id}
comment={c}
viewerId={user?.id}
isPostAuthor={isPostAuthor}
onReply={startReply}
onLikeChange={(likes, liked) =>
patch(c.id, (x) => ({
...x,
likes_count: likes,
viewer_has_liked: liked,
}))
}
onPinToggle={() => pinToggle(c)}
onRequestDelete={setToDelete}
onRequestReport={setToReport}
requireAuth={requireAuth}
registerThread={(fn) => {
if (fn) repliesRef.current[c.id] = fn;
else delete repliesRef.current[c.id];
}}
/>
))}
{hasMore ? (
<li>
<button
type="button"
onClick={loadMore}
className="text-sm font-medium text-primary hover:underline"
>
Load more comments
</button>
</li>
) : null}
</ul>
)}
</div>
{/* Composer */}
<div className="border-t border-border p-3 shrink-0">
{replyTo ? (
<div className="mb-2 flex items-center justify-between rounded-md bg-muted/60 px-3 py-1.5 text-xs text-muted-foreground">
<span>
Replying to <span className="font-medium">@{replyTo.handle}</span>
</span>
<button
type="button"
onClick={() => setReplyTo(null)}
aria-label="Cancel reply"
className="rounded p-0.5 hover:text-foreground"
>
<X className="size-3.5" />
</button>
</div>
) : null}
<div className="flex items-end gap-2">
<textarea
ref={inputRef}
value={draft}
onChange={(e) => setDraft(e.target.value)}
onKeyDown={(e) => {
if (e.key === "Enter" && !e.shiftKey) {
e.preventDefault();
submit();
}
}}
rows={1}
maxLength={2000}
placeholder={replyTo ? "Write a reply…" : "Add a comment…"}
className="flex-1 resize-none rounded-lg border border-border bg-background px-3 py-2 text-base sm:text-sm text-foreground outline-none focus-visible:ring-2 focus-visible:ring-primary/40 max-h-32"
/>
<button
type="button"
onClick={submit}
disabled={posting || draft.trim() === ""}
aria-label="Post comment"
className="size-10 shrink-0 inline-flex items-center justify-center rounded-lg bg-primary text-primary-foreground hover:bg-primary/90 transition-colors disabled:opacity-50"
>
{posting ? (
<Loader2 className="size-4 animate-spin" />
) : (
<Send className="size-4" />
)}
</button>
</div>
</div>
</DrawerContent>
</Drawer>
<ConfirmModal
open={toDelete !== null}
onClose={() => setToDelete(null)}
title="Delete this comment?"
message={
toDelete && !toDelete.parent_id && toDelete.reply_count > 0
? "Its replies will be deleted too. This can't be undone."
: "This can't be undone."
}
confirmLabel="Delete"
onConfirm={confirmDelete}
/>
<ReportCommentModal
comment={toReport}
onClose={() => setToReport(null)}
/>
</>
);
}
// ───────────────────────────────────────────────────────────────────────────
// One comment (top-level or reply). Top-level rows own a lazily-loaded reply
// thread; replies render the "Replying to @handle" prefix.
// ───────────────────────────────────────────────────────────────────────────
function CommentRow({
comment,
viewerId,
isPostAuthor,
onReply,
onLikeChange,
onPinToggle,
onRequestDelete,
onRequestReport,
requireAuth,
registerThread,
isReply = false,
}: {
comment: Comment;
viewerId?: string;
isPostAuthor: boolean;
onReply: (c: Comment) => void;
onLikeChange: (likes: number, liked: boolean) => void;
onPinToggle: () => void;
onRequestDelete: (c: Comment) => void;
onRequestReport: (c: Comment) => void;
requireAuth: () => Promise<boolean>;
/** Top-level rows register a callback so a newly-posted reply can be spliced
* into their open thread. Replies pass nothing. */
registerThread?: (fn: ((c: Comment) => void) | null) => void;
isReply?: boolean;
}) {
const [replies, setReplies] = useState<Comment[]>([]);
const [showReplies, setShowReplies] = useState(false);
const [repliesLoaded, setRepliesLoaded] = useState(false);
const likeBusy = useRef(false);
const canDelete = viewerId === comment.user_id || isPostAuthor;
const canReport = !!viewerId && viewerId !== comment.user_id;
const pinnable = isPostAuthor && !isReply;
// Expose a splice hook so the drawer can append a reply created from the
// composer. Replies created while collapsed still get the count bump; they
// show once expanded (re-fetched) or appended if already open.
useEffect(() => {
if (isReply || !registerThread) return;
registerThread((c: Comment) => {
if (c.body === "__deleted__") {
setReplies((prev) => prev.filter((x) => x.id !== c.id));
return;
}
setRepliesLoaded(true);
setShowReplies(true);
setReplies((prev) =>
prev.some((x) => x.id === c.id) ? prev : [...prev, c],
);
});
return () => registerThread(null);
}, [isReply, registerThread]);
async function toggleReplies() {
if (!showReplies && !repliesLoaded) {
try {
const rows = await commentsApi.replies(comment.id, { limit: 50 });
setReplies(rows ?? []);
setRepliesLoaded(true);
} catch {
/* ignore */
}
}
setShowReplies((v) => !v);
}
async function likeToggle() {
if (likeBusy.current) return;
if (!(await requireAuth())) return;
likeBusy.current = true;
const next = !comment.viewer_has_liked;
// optimistic
onLikeChange(
Math.max(0, comment.likes_count + (next ? 1 : -1)),
next,
);
try {
const res = next
? await commentsApi.like(comment.id)
: await commentsApi.unlike(comment.id);
onLikeChange(res.likes_count, next);
} catch (err) {
onLikeChange(comment.likes_count, comment.viewer_has_liked);
toast.error(
err instanceof SocialError ? err.message : "Could not update like",
{ duration: 3000 },
);
} finally {
likeBusy.current = false;
}
}
return (
<li className={cn(isReply && "mt-3")}>
<div className="flex gap-3">
<Avatar src={comment.author_avatar_url ?? null} name={comment.author_name} />
<div className="min-w-0 flex-1">
<div className="flex items-center gap-2">
<span className="text-sm font-semibold text-foreground truncate">
{comment.author_name}
</span>
{!isReply && comment.pinned_at ? (
<span className="inline-flex items-center gap-1 rounded-full bg-primary/10 px-1.5 py-0.5 text-[10px] font-medium text-primary">
<Pin className="size-3" /> Pinned
</span>
) : null}
<span className="text-xs text-muted-foreground">
{timeAgo(comment.created_at)}
</span>
</div>
<p className="mt-0.5 whitespace-pre-wrap break-words text-sm text-foreground">
{comment.reply_to_handle ? (
<span className="font-medium text-primary">
@{comment.reply_to_handle}{" "}
</span>
) : null}
{comment.body}
</p>
{/* Inline action row */}
<div className="mt-1.5 flex items-center gap-4 text-xs text-muted-foreground">
<button
type="button"
onClick={likeToggle}
className="inline-flex items-center gap-1 hover:text-foreground transition-colors"
aria-label={comment.viewer_has_liked ? "Unlike" : "Like"}
>
{comment.viewer_has_liked ? (
<HiHeart className="size-4 text-red-500" />
) : (
<HiOutlineHeart className="size-4" />
)}
{comment.likes_count > 0 ? (
<span className="tabular-nums">{comment.likes_count}</span>
) : null}
</button>
<button
type="button"
onClick={() => onReply(comment)}
className="font-medium hover:text-foreground transition-colors"
>
Reply
</button>
{pinnable ? (
<button
type="button"
onClick={onPinToggle}
className="inline-flex items-center gap-1 hover:text-foreground transition-colors"
>
{comment.pinned_at ? (
<>
<PinOff className="size-3.5" /> Unpin
</>
) : (
<>
<Pin className="size-3.5" /> Pin
</>
)}
</button>
) : null}
{canDelete ? (
<button
type="button"
onClick={() => onRequestDelete(comment)}
className="inline-flex items-center gap-1 hover:text-destructive transition-colors"
>
<Trash2 className="size-3.5" /> Delete
</button>
) : null}
{canReport ? (
<button
type="button"
onClick={() => onRequestReport(comment)}
className="hover:text-foreground transition-colors"
>
Report
</button>
) : null}
</div>
{/* Replies */}
{!isReply && comment.reply_count > 0 ? (
<button
type="button"
onClick={toggleReplies}
className="mt-2 text-xs font-medium text-primary hover:underline"
>
{showReplies
? "Hide replies"
: `View ${comment.reply_count} ${comment.reply_count === 1 ? "reply" : "replies"}`}
</button>
) : null}
{!isReply && showReplies ? (
<ul className="mt-1 border-l border-border pl-3">
{replies.map((r) => (
<CommentRow
key={r.id}
comment={r}
viewerId={viewerId}
isPostAuthor={isPostAuthor}
onReply={onReply}
onLikeChange={(likes, liked) =>
setReplies((prev) =>
prev.map((x) =>
x.id === r.id
? { ...x, likes_count: likes, viewer_has_liked: liked }
: x,
),
)
}
onPinToggle={() => {}}
onRequestDelete={onRequestDelete}
onRequestReport={onRequestReport}
requireAuth={requireAuth}
isReply
/>
))}
</ul>
) : null}
</div>
</div>
</li>
);
}
// ───────────────────────────────────────────────────────────────────────────
// Report modal (compact)
// ───────────────────────────────────────────────────────────────────────────
const REPORT_CATEGORIES: { value: PostReportCategory; label: string }[] = [
{ value: "spam", label: "Spam or misleading" },
{ value: "harassment", label: "Harassment or bullying" },
{ value: "misinformation", label: "Misinformation" },
{ value: "inappropriate", label: "Inappropriate content" },
{ value: "other", label: "Something else" },
];
function ReportCommentModal({
comment,
onClose,
}: {
comment: Comment | null;
onClose: () => void;
}) {
const [category, setCategory] = useState<PostReportCategory>("spam");
const [reason, setReason] = useState("");
const [working, setWorking] = useState(false);
useEffect(() => {
if (comment) {
setCategory("spam");
setReason("");
setWorking(false);
}
}, [comment]);
if (!comment) return null;
async function submit() {
if (!comment) return;
setWorking(true);
try {
await commentsApi.report(comment.id, category, reason.trim());
toast("Thanks — your report was submitted", { duration: 2500 });
onClose();
} catch (err) {
toast.error(
err instanceof SocialError ? err.message : "Could not submit report",
{ duration: 3000 },
);
} finally {
setWorking(false);
}
}
return (
<div className="fixed inset-0 z-[110] flex items-center justify-center px-4">
<div
className="absolute inset-0 bg-foreground/40 backdrop-blur-sm"
onClick={() => !working && onClose()}
aria-hidden
/>
<div
role="dialog"
aria-modal="true"
className="relative w-full max-w-md rounded-2xl border border-border bg-card shadow-xl p-5"
>
<h2 className="font-[family-name:var(--font-title)] font-semibold text-lg text-foreground">
Report comment
</h2>
<p className="mt-1 text-sm text-muted-foreground">
Reports are private and reviewed by our team.
</p>
<div className="mt-4 space-y-1.5">
{REPORT_CATEGORIES.map((c) => (
<label
key={c.value}
className={cn(
"flex items-center gap-3 rounded-md border px-3 py-2 cursor-pointer transition-colors",
category === c.value
? "border-primary bg-primary/5"
: "border-border hover:bg-muted",
)}
>
<input
type="radio"
name="comment-report-category"
value={c.value}
checked={category === c.value}
onChange={() => setCategory(c.value)}
className="accent-primary"
/>
<span className="text-sm text-foreground">{c.label}</span>
</label>
))}
</div>
<textarea
value={reason}
onChange={(e) => setReason(e.target.value)}
rows={2}
maxLength={2000}
placeholder="Add details (optional)"
className="mt-3 w-full resize-none rounded-md border border-border bg-background px-3 py-2 text-base sm:text-sm text-foreground outline-none focus-visible:ring-2 focus-visible:ring-primary/40"
/>
<div className="mt-4 flex items-center justify-end gap-2">
<button
type="button"
onClick={onClose}
disabled={working}
className="h-10 px-4 rounded-md text-sm font-medium text-foreground hover:bg-muted transition-colors disabled:opacity-50"
>
Cancel
</button>
<button
type="button"
onClick={submit}
disabled={working}
className="h-10 px-4 rounded-md text-sm font-medium bg-destructive text-white hover:bg-destructive/90 transition-colors disabled:opacity-60"
>
{working ? "Submitting…" : "Submit report"}
</button>
</div>
</div>
</div>
);
}
// ───────────────────────────────────────────────────────────────────────────
function Avatar({ src, name }: { src: string | null; name: string }) {
if (src) {
return (
<Image
src={src}
alt={name}
width={36}
height={36}
className="size-9 shrink-0 rounded-full object-cover ring-1 ring-foreground/10"
unoptimized
/>
);
}
const initials =
name
.replace(/^@/, "")
.split(/\s+/)
.map((p) => p[0])
.slice(0, 2)
.join("")
.toUpperCase() || "?";
return (
<div className="size-9 shrink-0 rounded-full bg-primary/15 text-primary flex items-center justify-center text-xs font-semibold ring-1 ring-foreground/10">
{initials}
</div>
);
}
/** Compact relative time ("just now", "5m ago", "3h ago", "2d ago"). */
function timeAgo(iso: string): string {
const then = new Date(iso).getTime();
if (Number.isNaN(then)) return "";
const secs = Math.max(0, Math.floor((Date.now() - then) / 1000));
if (secs < 45) return "just now";
const mins = Math.floor(secs / 60);
if (mins < 60) return `${mins}m ago`;
const hours = Math.floor(mins / 60);
if (hours < 24) return `${hours}h ago`;
const days = Math.floor(hours / 24);
if (days < 7) return `${days}d ago`;
return new Date(iso).toLocaleDateString();
}
@@ -43,9 +43,9 @@ import { useAuth } from "@/components/auth/auth-provider";
import { useAuthGate } from "@/components/auth/auth-gate";
import { useMediaQuery } from "@/components/selection-toolbar/shared";
import { CollectionsDrawer } from "@/components/selection-toolbar/collections-drawer";
import { PostLikesDrawer } from "@/components/social/post-likes-drawer";
import { PostCommentsDrawer } from "@/components/social/post-comments-drawer";
import { useSharePost } from "./share-post-provider";
import { PostLikesDrawer } from "./post-likes-drawer";
import { PostCommentsDrawer } from "@/components/social/comment/post-comments-drawer";
import { useSharePost } from "../share-post-provider";
// All icons come from the Heroicons v2 outline family (react-icons
// `hi2` namespace), so they share one design language — uniform stroke
@@ -81,6 +81,9 @@ export function PostActionsFooter({ post }: { post: Post }) {
const [pinned, setPinned] = useState<Comment | null>(
post.pinned_comment ?? null,
);
const [commentCount, setCommentCount] = useState<number>(
post.comments_count ?? 0,
);
const isOwner = !!user && user.id === post.user_id;
// Owners and resharers both see Send — the post is "on their account"
@@ -177,6 +180,16 @@ export function PostActionsFooter({ post }: { post: Post }) {
onClick={() => setCommentsOpen(true)}
icon={<HiOutlineChatBubbleOvalLeft className={ICON_CLASS} />}
/>
{commentCount > 0 ? (
<button
type="button"
onClick={() => setCommentsOpen(true)}
aria-label={`${commentCount} ${commentCount === 1 ? "comment" : "comments"}`}
className="-ml-2 mr-1 rounded px-1 text-sm font-medium tabular-nums text-muted-foreground transition-colors hover:text-foreground outline-none focus-visible:ring-2 focus-visible:ring-ring"
>
{commentCount}
</button>
) : null}
{/* Reshare for posts not yet on your account, Send for posts
that are — authored OR previously reshared. Mutually
exclusive: the row stays three icons regardless of viewer
@@ -250,6 +263,9 @@ export function PostActionsFooter({ post }: { post: Post }) {
post={post}
onClose={() => setCommentsOpen(false)}
onPinnedChange={setPinned}
onCountChange={(delta) =>
setCommentCount((c) => Math.max(0, c + delta))
}
/>
{/* SharePostSheet is mounted globally by SharePostProvider, so
no per-card instance lives here. The provider's
@@ -26,6 +26,7 @@ import { ExternalLink, Repeat2 } from "lucide-react";
import type { Post } from "@/lib/social";
import { displaySourceLabel } from "@/lib/source-reference";
import { appendHighlight, hasHighlight } from "@/lib/text-highlight";
import { UserAvatar } from "@/components/ui/user-avatar";
import { PostActionsFooter } from "./post-actions-footer";
import { PostCardMenu } from "./post-card-menu";
@@ -69,7 +70,11 @@ export function PostCard({
show (delete for owners, block/report for everyone else), so
a view with nothing to expose simply hides the dot. */}
<header className="flex items-center gap-3 mb-4">
<AuthorAvatar src={post.author_avatar_url ?? null} name={authorName} />
<UserAvatar
src={post.author_avatar_url}
name={authorName}
className="size-9"
/>
<div className="min-w-0 flex-1">
{authorHandle ? (
<Link
@@ -144,29 +149,3 @@ export function PostCard({
);
}
function AuthorAvatar({
src,
name,
}: {
src: string | null;
name: string;
}) {
if (src) {
return (
<Image
src={src}
alt={name}
width={36}
height={36}
className="size-9 rounded-full object-cover ring-1 ring-foreground/10 shrink-0"
unoptimized
/>
);
}
const initial = name.charAt(0).toUpperCase() || "?";
return (
<div className="size-9 rounded-full bg-primary/15 text-primary flex items-center justify-center text-sm font-semibold ring-1 ring-foreground/10 shrink-0">
{initial}
</div>
);
}
@@ -23,7 +23,7 @@ import type { Post } from "@/lib/social";
import { displaySourceLabel } from "@/lib/source-reference";
import { useMediaQuery } from "@/components/selection-toolbar/shared";
import { postSourceHref, quoteCardBgStyle, quoteSize } from "./post-card-shared";
import { UpdateBackgroundModal } from "./update-background-modal";
import { UpdateBackgroundModal } from "../update-background-modal";
export function PostGridCard({
post,
@@ -34,12 +34,13 @@ import { cn } from "@/lib/utils";
import type { Post, PostImage } from "@/lib/social";
import { displaySourceLabel } from "@/lib/source-reference";
import { useMediaQuery } from "@/components/selection-toolbar/shared";
import { UserAvatar } from "@/components/ui/user-avatar";
import { useAuth } from "@/components/auth/auth-provider";
import { postSourceHref, quoteCardBgStyle } from "./post-card-shared";
import { PostActionsFooter } from "./post-actions-footer";
import { PostCardMenu } from "./post-card-menu";
import { UpdateBackgroundModal } from "./update-background-modal";
import { MentionsDrawer } from "./mentions-drawer";
import { UpdateBackgroundModal } from "../update-background-modal";
import { MentionsDrawer } from "../mentions-drawer";
export function PostScrollCard({
post,
@@ -115,9 +116,10 @@ export function PostScrollCard({
on the right (Delete for author, Block/Report for everyone
else; PostCardMenu hides itself when there are no items). */}
<header className="flex items-center gap-3 px-4 py-3">
<AuthorAvatar
src={post.author_avatar_url ?? null}
<UserAvatar
src={post.author_avatar_url}
name={post.author_name ?? "Unknown"}
className="size-9"
/>
<div className="min-w-0 flex-1">
<Link
@@ -343,32 +345,6 @@ function Caption({
);
}
function AuthorAvatar({
src,
name,
}: {
src: string | null;
name: string;
}) {
if (src) {
return (
<Image
src={src}
alt={name}
width={36}
height={36}
className="size-9 rounded-full object-cover ring-1 ring-foreground/10"
unoptimized
/>
);
}
const initial = name.charAt(0).toUpperCase() || "?";
return (
<div className="size-9 rounded-full bg-primary/15 text-primary flex items-center justify-center text-sm font-semibold ring-1 ring-foreground/10">
{initial}
</div>
);
}
function OwnerButton({
label,
+161
View File
@@ -0,0 +1,161 @@
"use client";
/**
* EmojiPicker — a tiny, dependency-free emoji popover for text inputs.
*
* Renders just a trigger button; the panel is portaled to <body> with fixed
* positioning and a transparent full-screen backdrop that swallows the
* dismiss click. That keeps it OUTSIDE any surrounding drawer/sheet DOM, so
* opening it can't resize or reposition the host (e.g. the vaul comments
* drawer), and the dismiss click can't leak through and close that drawer.
*
* It stays open after a pick so several emojis can be added in a row; the
* caller decides what to do with each via `onSelect`.
*/
import { useRef, useState } from "react";
import { createPortal } from "react-dom";
import { Smile } from "lucide-react";
import { cn } from "@/lib/utils";
// A curated, broadly-useful set — enough to feel like a picker without
// shipping a full emoji database. Grouped for easy scanning.
const EMOJI_GROUPS: { label: string; emojis: string[] }[] = [
{
label: "Smileys",
emojis: [
"😀", "😃", "😄", "😁", "😅", "😂", "🙂", "😊",
"😇", "😍", "🥰", "😘", "😉", "😌", "😎", "🤗",
"🤔", "😴", "😢", "😭", "😮", "😲", "🥲", "😬",
],
},
{
label: "Gestures & people",
emojis: [
"🙏", "👍", "👎", "👏", "🙌", "🤝", "✌️", "🤞",
"💪", "🫶", "👋", "🙇", "🧘", "🕉️", "☮️", "🤲",
],
},
{
label: "Hearts",
emojis: [
"❤️", "🧡", "💛", "💚", "💙", "💜", "🤍", "🤎",
"🖤", "💖", "💕", "💗", "💓", "💞", "💔", "❣️",
],
},
{
label: "Nature & spirit",
emojis: [
"🌸", "🌺", "🌹", "🪷", "🌻", "🌼", "🍃", "🌿",
"🪔", "🕯️", "🔥", "✨", "🌟", "⭐", "☀️", "🌈",
],
},
{
label: "Symbols",
emojis: [
"🎉", "🎊", "🥳", "💯", "✅", "❗", "❓", "💬",
"📿", "🛕", "🐮", "🦚", "🪈", "🎶", "📖", "🙏🏽",
],
},
];
const PANEL_WIDTH = 300;
export function EmojiPicker({
onSelect,
className,
}: {
onSelect: (emoji: string) => void;
className?: string;
}) {
const [open, setOpen] = useState(false);
const [pos, setPos] = useState<{ bottom: number; left: number } | null>(null);
const btnRef = useRef<HTMLButtonElement>(null);
function toggle() {
if (open) {
setOpen(false);
return;
}
const r = btnRef.current?.getBoundingClientRect();
if (r) {
// Open ABOVE the trigger (the composer sits at the bottom of the sheet),
// clamped so the 300px panel stays on-screen horizontally.
const left = Math.max(
8,
Math.min(r.left, window.innerWidth - PANEL_WIDTH - 8),
);
setPos({ bottom: window.innerHeight - r.top + 6, left });
}
setOpen(true);
}
return (
<>
<button
ref={btnRef}
type="button"
onClick={toggle}
aria-label="Add emoji"
aria-haspopup="dialog"
aria-expanded={open}
className={cn(
"size-10 shrink-0 inline-flex items-center justify-center rounded-lg text-muted-foreground hover:text-foreground hover:bg-muted transition-colors",
className,
)}
>
<Smile className="size-5" />
</button>
{open && pos && typeof document !== "undefined"
? createPortal(
<>
<div
className="fixed inset-0 z-[100]"
aria-hidden
onClick={(e) => {
e.stopPropagation();
setOpen(false);
}}
/>
<div
role="dialog"
aria-label="Emoji picker"
style={{
position: "fixed",
bottom: pos.bottom,
left: pos.left,
width: PANEL_WIDTH,
maxWidth: "calc(100vw - 1rem)",
}}
className="z-[101] rounded-xl border border-border bg-card shadow-xl p-2 animate-in fade-in-0 zoom-in-95"
>
<div className="max-h-60 overflow-y-auto overscroll-contain">
{EMOJI_GROUPS.map((g) => (
<div key={g.label} className="mb-1.5">
<p className="px-1 pb-0.5 pt-1 text-[11px] font-medium uppercase tracking-wide text-muted-foreground">
{g.label}
</p>
<div className="grid grid-cols-8 gap-0.5">
{g.emojis.map((e, i) => (
<button
key={`${e}-${i}`}
type="button"
onClick={() => onSelect(e)}
aria-label={`Emoji ${e}`}
className="flex size-8 items-center justify-center rounded-md text-xl leading-none hover:bg-muted"
>
{e}
</button>
))}
</div>
</div>
))}
</div>
</div>
</>,
document.body,
)
: null}
</>
);
}
+101
View File
@@ -0,0 +1,101 @@
import Image from "next/image";
import { cn } from "@/lib/utils";
/**
* UserAvatar — the one avatar component: shows the user's image, or their
* initials on a tinted disc when there's no image. Used everywhere a user
* thumbnail appears (notification feed, comments, follower lists, and the
* profile header's large zoomable hero).
*
* Sizing is class-driven (`className`) rather than a fixed px, so callers get
* Tailwind's responsive sizes — e.g. `size-10` for a list row or
* `size-24 sm:size-28` for the profile header. `textClassName` scales the
* initials to match. When `onClick` is set, an image avatar becomes a
* focusable button (used by the profile header to open its zoom preview);
* `interactive` adds a hover-ring affordance.
*/
export function UserAvatar({
src,
name,
className,
textClassName = "text-sm",
onClick,
ariaLabel,
interactive = false,
}: {
src?: string | null;
name: string;
/** Box size + extras. Defaults to a 40px (size-10) circle. */
className?: string;
/** Initials font size — match it to the box. Defaults to text-sm. */
textClassName?: string;
/** When set, an image avatar renders as a focusable button (e.g. to open a
* zoom preview or navigate). Initials stay non-interactive. */
onClick?: () => void;
ariaLabel?: string;
/** Add a hover-ring affordance to an image avatar. */
interactive?: boolean;
}) {
const size = className ?? "size-10";
if (src) {
const imgRing = cn(
"rounded-full object-cover ring-1 ring-foreground/10",
interactive && "hover:ring-foreground/30 transition",
);
// width/height satisfy next/image; the rendered size comes from the CSS
// size class (which overrides the intrinsic attributes).
if (onClick) {
return (
<button
type="button"
onClick={onClick}
aria-label={ariaLabel ?? `View ${name}'s picture`}
className={cn(
"shrink-0 rounded-full focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2",
size,
)}
>
<Image
src={src}
alt={name}
width={112}
height={112}
className={cn("size-full", imgRing)}
unoptimized
/>
</button>
);
}
return (
<Image
src={src}
alt={name}
width={112}
height={112}
className={cn("shrink-0", size, imgRing)}
unoptimized
/>
);
}
const initials =
name
.replace(/^@/, "")
.split(/\s+/)
.map((p) => p[0])
.slice(0, 2)
.join("")
.toUpperCase() || "?";
return (
<div
className={cn(
"shrink-0 rounded-full bg-primary/15 text-primary flex items-center justify-center font-semibold ring-1 ring-foreground/10",
size,
textClassName,
)}
>
{initials}
</div>
);
}