Files
spsays-training/components/profile/profile-actions.tsx
T
2026-08-29 03:49:58 +05:30

858 lines
26 KiB
TypeScript

"use client";
/**
* ProfileActions — the action row on someone else's profile header.
*
* Renders a primary follow button whose label/behaviour is derived from
* the viewer's RelationshipState toward the target, plus a shield
* overflow button opening a menu (Remove from followers / Block / Report).
*
* Follows are REQUEST-BASED: pressing "Follow" sends a request that the
* target accepts or rejects later, so the button flips to "Requested"
* (tap again to cancel) rather than straight to "Following".
*
* Primary button by state (viewer → target):
* • they've requested you → "Accept" + "Reject"
* • you follow them → "Unfollow"
* • you've requested them → "Requested" (tap = cancel)
* • they follow you → "Follow back"
* • no edge → "Follow"
* • you blocked / they blocked → no primary button (menu only)
*
* Overflow menu:
* • "Remove from followers" — only when they currently follow you
* • "Block user" / "Unblock user"
* • "Report user"
*
* Block confirms in a dialog (desktop) / drawer (mobile); Report collects
* a category + reason in the same responsive container. Each successful
* action calls onResult so the header can refresh its live counts.
*/
import { useCallback, useEffect, useRef, useState } from "react";
import { createPortal } from "react-dom";
import {
Ban,
CalendarDays,
Check,
Clock,
Flag,
Globe,
Info,
Loader2,
Shield,
UserCheck,
UserMinus,
UserPlus,
X,
} from "lucide-react";
import { toast } from "sonner";
import {
relationships,
SocialError,
type ReportCategory,
type RelationshipResult,
type RelationshipState,
} from "@/lib/social";
import { countryName } from "@/lib/countries";
import { useAuth } from "@/components/auth/auth-provider";
import { useAuthGate } from "@/components/auth/auth-gate";
import { useMediaQuery } from "@/components/selection-toolbar/shared";
import { MessageButton } from "@/components/profile/message-button";
import {
Drawer,
DrawerContent,
DrawerDescription,
DrawerHeader,
DrawerTitle,
} from "@/components/ui/drawer";
import { Button } from "@/components/ui/button";
import { cn } from "@/lib/utils";
export function ProfileActions({
handle,
name,
joinedAt,
country,
relationship,
onResult,
}: {
handle: string;
/** Display name for menu labels / dialog copy. */
name: string;
/** ISO timestamp the account was created — shown in the "About this
* account" (More info) modal. */
joinedAt?: string;
/** ISO-2 account country, shown in the "About this account" modal. */
country?: string | null;
relationship: RelationshipState | null;
/** Called after any successful mutation with the recomputed result so
* the parent header can update its follower/following counts and the
* relationship it passes back in. */
onResult: (r: RelationshipResult) => void;
}) {
const { user } = useAuth();
const { requireAuth } = useAuthGate();
const [busy, setBusy] = useState(false);
const [blockOpen, setBlockOpen] = useState(false);
const [reportOpen, setReportOpen] = useState(false);
const [aboutOpen, setAboutOpen] = useState(false);
const rel = relationship;
const display = `@${handle}`;
// Run a relationship mutation behind the auth gate, with a busy guard
// and toast on failure. `label` describes the action for error copy.
async function run(
fn: () => Promise<RelationshipResult>,
onDone?: (r: RelationshipResult) => void,
) {
if (busy) return;
if (!(await requireAuth())) return;
setBusy(true);
try {
const r = await fn();
onResult(r);
onDone?.(r);
} catch (err) {
const msg =
err instanceof SocialError
? err.message
: "Something went wrong. Please try again.";
toast.error(msg);
} finally {
setBusy(false);
}
}
const follow = () =>
run(
() => relationships.follow(handle),
() => toast(`Follow request sent to ${display}`, { duration: 2500 }),
);
const unfollow = () => run(() => relationships.unfollow(handle));
const accept = () =>
run(
() => relationships.accept(handle),
() => toast(`${display} now follows you`, { duration: 2500 }),
);
const reject = () => run(() => relationships.reject(handle));
const removeFollower = () =>
run(
() => relationships.removeFollower(handle),
() => toast(`Removed ${display} from your followers`, { duration: 2500 }),
);
const unblock = () =>
run(
() => relationships.unblock(handle),
() => toast(`Unblocked ${display}`, { duration: 2500 }),
);
// ── Primary button ───────────────────────────────────────────────────
const blocked = !!rel?.blocked;
const blockedBy = !!rel?.blocked_by;
let primary: React.ReactNode = null;
if (blocked) {
primary = (
<Button variant="outline" onClick={unblock} disabled={busy} className="min-w-32">
{busy ? <Spinner /> : null}
Unblock
</Button>
);
} else if (blockedBy) {
// They blocked the viewer — nothing to do but report (menu).
primary = null;
} else if (rel?.requests_you) {
primary = (
<div className="flex items-center gap-2">
<Button onClick={accept} disabled={busy} className="min-w-24">
{busy ? <Spinner /> : <Check className="size-4" />}
Accept
</Button>
<Button variant="outline" onClick={reject} disabled={busy}>
Reject
</Button>
</div>
);
} else if (rel?.following) {
primary = (
<Button variant="outline" onClick={unfollow} disabled={busy} className="min-w-32">
{busy ? <Spinner /> : <UserCheck className="size-4" />}
Unfollow
</Button>
);
} else if (rel?.follow_requested) {
primary = (
<Button variant="outline" onClick={unfollow} disabled={busy} className="min-w-32">
{busy ? <Spinner /> : <Clock className="size-4" />}
Requested
</Button>
);
} else if (rel?.follows_you) {
primary = (
<Button onClick={follow} disabled={busy} className="min-w-32">
{busy ? <Spinner /> : <UserPlus className="size-4" />}
Follow back
</Button>
);
} else {
primary = (
<Button onClick={follow} disabled={busy} className="min-w-32">
{busy ? <Spinner /> : <UserPlus className="size-4" />}
Follow
</Button>
);
}
return (
<>
<div className="flex flex-wrap items-center gap-2">
{primary}
{/* Offered only when the target's settings allow it — see
MessageButton. */}
<MessageButton handle={handle} name={name} relationship={rel} />
{/* Block / Report / Remove are signed-in-only (their BFF routes
require auth) and only appear when `authed`. "More info" is
public, so the menu always renders with at least that item. */}
<OverflowMenu
name={name}
display={display}
rel={rel}
busy={busy}
authed={!!user}
onRemoveFollower={removeFollower}
onBlock={() => setBlockOpen(true)}
onUnblock={unblock}
onReport={() => setReportOpen(true)}
onAbout={() => setAboutOpen(true)}
/>
</div>
<BlockModal
open={blockOpen}
onClose={() => setBlockOpen(false)}
display={display}
onConfirm={async () => {
const r = await relationships.block(handle);
onResult(r);
toast(`Blocked ${display}`, { duration: 2500 });
}}
/>
<ReportModal
open={reportOpen}
onClose={() => setReportOpen(false)}
display={display}
onSubmit={async (category, reason) => {
await relationships.report(handle, category, reason);
toast(`Thanks — your report about ${display} was submitted`, {
duration: 3000,
});
}}
/>
<AboutModal
open={aboutOpen}
onClose={() => setAboutOpen(false)}
display={display}
joinedAt={joinedAt}
country={country}
/>
</>
);
}
function Spinner() {
return <Loader2 className="size-4 animate-spin" />;
}
// ───────────────────────────────────────────────────────────────────────────
// Overflow (shield) menu — desktop popover / mobile drawer.
// ───────────────────────────────────────────────────────────────────────────
type MenuAction = {
key: string;
label: string;
icon: React.ReactNode;
onClick: () => void;
danger?: boolean;
};
function OverflowMenu({
name,
display,
rel,
busy,
authed,
onRemoveFollower,
onBlock,
onUnblock,
onReport,
onAbout,
}: {
name: string;
display: string;
rel: RelationshipState | null;
busy: boolean;
/** Whether a viewer is signed in. Block/Report/Remove are gated on
* this; "More info" is shown to everyone. */
authed: boolean;
onRemoveFollower: () => void;
onBlock: () => void;
onUnblock: () => void;
onReport: () => void;
onAbout: () => void;
}) {
const isMobile = useMediaQuery("(max-width: 767px)");
const [open, setOpen] = useState(false);
const triggerRef = useRef<HTMLButtonElement>(null);
const popoverRef = useRef<HTMLDivElement>(null);
const [popPos, setPopPos] = useState<{ top: number; left: number } | null>(
null,
);
// Desktop popover position — right-aligned under the trigger. We measure
// in event handlers (the open click + resize/scroll), never synchronously
// inside an effect body, so opening the menu can't trigger a cascading
// render. The effect below only wires the resize/scroll listeners.
const recompute = useCallback(() => {
const btn = triggerRef.current;
if (!btn) return;
const rect = btn.getBoundingClientRect();
const w = 240;
const pad = 8;
let left = rect.right - w;
if (left < pad) left = pad;
if (left + w > window.innerWidth - pad) left = window.innerWidth - w - pad;
setPopPos({ top: rect.bottom + 6, left });
}, []);
useEffect(() => {
if (!open || isMobile) return;
window.addEventListener("resize", recompute);
window.addEventListener("scroll", recompute, true);
return () => {
window.removeEventListener("resize", recompute);
window.removeEventListener("scroll", recompute, true);
};
}, [open, isMobile, recompute]);
// Click-outside + Escape (desktop only).
useEffect(() => {
if (!open || isMobile) return;
function onPointer(e: PointerEvent) {
if (popoverRef.current?.contains(e.target as Node)) return;
if (triggerRef.current?.contains(e.target as Node)) return;
setOpen(false);
}
function onKey(e: KeyboardEvent) {
if (e.key === "Escape") setOpen(false);
}
const t = setTimeout(() => {
document.addEventListener("pointerdown", onPointer);
document.addEventListener("keydown", onKey);
}, 0);
return () => {
clearTimeout(t);
document.removeEventListener("pointerdown", onPointer);
document.removeEventListener("keydown", onKey);
};
}, [open, isMobile]);
const blocked = !!rel?.blocked;
const items: MenuAction[] = [];
// Signed-in-only moderation actions.
if (authed) {
if (rel?.follows_you && !blocked && !rel?.blocked_by) {
items.push({
key: "remove",
label: "Remove from followers",
icon: <UserMinus className="size-4" />,
onClick: () => {
setOpen(false);
onRemoveFollower();
},
});
}
items.push(
blocked
? {
key: "unblock",
label: "Unblock user",
icon: <Shield className="size-4" />,
onClick: () => {
setOpen(false);
onUnblock();
},
}
: {
key: "block",
label: "Block user",
icon: <Ban className="size-4" />,
danger: true,
onClick: () => {
setOpen(false);
onBlock();
},
},
);
items.push({
key: "report",
label: "Report user",
icon: <Flag className="size-4" />,
danger: true,
onClick: () => {
setOpen(false);
onReport();
},
});
}
// Public — always at the bottom.
items.push({
key: "about",
label: "More info",
icon: <Info className="size-4" />,
onClick: () => {
setOpen(false);
onAbout();
},
});
const trigger = (
<button
ref={triggerRef}
type="button"
onClick={() => {
// Measure synchronously in the click (an event handler — safe),
// so the popover renders at the right spot on first paint.
if (!open && !isMobile) recompute();
setOpen((v) => !v);
}}
disabled={busy}
aria-label={`More options for ${name}`}
aria-haspopup="menu"
aria-expanded={open}
className={cn(
"size-9 inline-flex items-center justify-center rounded-lg shrink-0",
"border border-border text-foreground hover:bg-muted",
"transition-colors outline-none focus-visible:ring-2 focus-visible:ring-ring",
"disabled:opacity-50",
)}
>
<Shield className="size-4" />
</button>
);
if (isMobile) {
return (
<>
{trigger}
<Drawer open={open} onOpenChange={setOpen}>
<DrawerContent className="bg-card">
<DrawerHeader className="text-left border-b border-border pb-3">
<DrawerTitle>{display}</DrawerTitle>
</DrawerHeader>
<div className="p-3 space-y-1 pb-6">
{items.map((it) => (
<MenuButton key={it.key} item={it} mobile />
))}
</div>
</DrawerContent>
</Drawer>
</>
);
}
return (
<>
{trigger}
{open && popPos
? createPortal(
<div
ref={popoverRef}
role="menu"
style={{ position: "fixed", top: popPos.top, left: popPos.left, zIndex: 60 }}
className={cn(
"w-60 rounded-lg border border-border bg-card shadow-lg py-1",
"animate-in fade-in-0 zoom-in-95",
)}
>
{items.map((it) => (
<MenuButton key={it.key} item={it} />
))}
</div>,
document.body,
)
: null}
</>
);
}
function MenuButton({ item, mobile = false }: { item: MenuAction; mobile?: boolean }) {
return (
<button
type="button"
role="menuitem"
onClick={item.onClick}
className={cn(
"w-full flex items-center gap-3 text-left transition-colors rounded-md",
mobile ? "px-3 py-3" : "px-3 py-2",
item.danger
? "text-destructive hover:bg-destructive/10"
: "text-foreground hover:bg-muted",
)}
>
<span className={cn("shrink-0", item.danger ? "text-destructive" : "text-muted-foreground")}>
{item.icon}
</span>
<span className="text-sm font-medium truncate">{item.label}</span>
</button>
);
}
// ───────────────────────────────────────────────────────────────────────────
// ResponsiveModal — dialog on desktop, bottom drawer on mobile.
// ───────────────────────────────────────────────────────────────────────────
function ResponsiveModal({
open,
onClose,
title,
description,
children,
}: {
open: boolean;
onClose: () => void;
title: string;
description?: string;
children: React.ReactNode;
}) {
const isMobile = useMediaQuery("(max-width: 767px)");
// Desktop: Escape + body-scroll lock (the drawer handles its own).
useEffect(() => {
if (!open || isMobile) return;
function onKey(e: KeyboardEvent) {
if (e.key === "Escape") onClose();
}
document.addEventListener("keydown", onKey);
const prev = document.body.style.overflow;
document.body.style.overflow = "hidden";
return () => {
document.removeEventListener("keydown", onKey);
document.body.style.overflow = prev;
};
}, [open, isMobile, onClose]);
if (!open) return null;
if (isMobile) {
return (
<Drawer open={open} onOpenChange={(o) => !o && onClose()}>
<DrawerContent className="bg-card">
<DrawerHeader className="text-left">
<DrawerTitle>{title}</DrawerTitle>
{description ? <DrawerDescription>{description}</DrawerDescription> : null}
</DrawerHeader>
<div className="px-4 pb-6">{children}</div>
</DrawerContent>
</Drawer>
);
}
if (typeof document === "undefined") return null;
return createPortal(
<>
<div
className="fixed inset-0 z-100 bg-foreground/40 backdrop-blur-sm animate-in fade-in-0"
onClick={onClose}
aria-hidden
/>
<div
role="dialog"
aria-modal="true"
className="fixed left-1/2 top-1/2 z-101 w-full max-w-md -translate-x-1/2 -translate-y-1/2 px-4"
>
<div className="rounded-2xl border border-border bg-card shadow-xl overflow-hidden">
<div className="flex items-start gap-3 px-5 pt-5 pb-1">
<div className="flex-1 min-w-0">
<h2 className="font-[family-name:var(--font-title)] font-semibold text-lg text-foreground">
{title}
</h2>
{description ? (
<p className="mt-1 text-sm text-muted-foreground leading-relaxed">
{description}
</p>
) : null}
</div>
<button
type="button"
onClick={onClose}
aria-label="Close"
className="shrink-0 size-8 rounded-lg text-muted-foreground hover:text-foreground hover:bg-muted inline-flex items-center justify-center"
>
<X className="size-4" />
</button>
</div>
<div className="px-5 pb-5 pt-2">{children}</div>
</div>
</div>
</>,
document.body,
);
}
// ───────────────────────────────────────────────────────────────────────────
// Block confirm
// ───────────────────────────────────────────────────────────────────────────
function BlockModal({
open,
onClose,
display,
onConfirm,
}: {
open: boolean;
onClose: () => void;
display: string;
onConfirm: () => Promise<void>;
}) {
const [working, setWorking] = useState(false);
const [error, setError] = useState<string | null>(null);
useEffect(() => {
if (open) {
setWorking(false);
setError(null);
}
}, [open]);
async function confirm() {
setWorking(true);
setError(null);
try {
await onConfirm();
onClose();
} catch (err) {
setError(
err instanceof Error ? err.message : "Something went wrong.",
);
} finally {
setWorking(false);
}
}
return (
<ResponsiveModal
open={open}
onClose={() => !working && onClose()}
title={`Block ${display}?`}
description={`They won't be able to follow you or see that you follow them. Any existing follow between you will be removed. You can unblock them later.`}
>
{error ? <p className="mb-3 text-sm text-destructive">{error}</p> : null}
<div className="flex items-center justify-end gap-2">
<Button variant="ghost" onClick={onClose} disabled={working}>
Cancel
</Button>
<Button variant="destructive" onClick={confirm} disabled={working}>
{working ? <Spinner /> : null}
Block
</Button>
</div>
</ResponsiveModal>
);
}
// ───────────────────────────────────────────────────────────────────────────
// Report form
// ───────────────────────────────────────────────────────────────────────────
const REPORT_CATEGORIES: { value: ReportCategory; label: string }[] = [
{ value: "spam", label: "Spam or misleading" },
{ value: "harassment", label: "Harassment or bullying" },
{ value: "impersonation", label: "Impersonation" },
{ value: "inappropriate", label: "Inappropriate content" },
{ value: "other", label: "Something else" },
];
function ReportModal({
open,
onClose,
display,
onSubmit,
}: {
open: boolean;
onClose: () => void;
display: string;
onSubmit: (category: ReportCategory, reason: string) => Promise<void>;
}) {
const [category, setCategory] = useState<ReportCategory>("spam");
const [reason, setReason] = useState("");
const [working, setWorking] = useState(false);
const [error, setError] = useState<string | null>(null);
useEffect(() => {
if (open) {
setCategory("spam");
setReason("");
setWorking(false);
setError(null);
}
}, [open]);
async function submit() {
if (reason.trim() === "") {
setError("Please add a brief reason.");
return;
}
setWorking(true);
setError(null);
try {
await onSubmit(category, reason.trim());
onClose();
} catch (err) {
setError(
err instanceof Error ? err.message : "Something went wrong.",
);
} finally {
setWorking(false);
}
}
return (
<ResponsiveModal
open={open}
onClose={() => !working && onClose()}
title={`Report ${display}`}
description="Reports are private and reviewed by our team."
>
<div className="space-y-4">
<div className="space-y-2">
<label className="block text-sm font-medium text-foreground">
Reason
</label>
<div className="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.5 cursor-pointer transition-colors",
category === c.value
? "border-primary bg-primary/5"
: "border-border hover:bg-muted",
)}
>
<input
type="radio"
name="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>
</div>
<div className="space-y-2">
<label htmlFor="report-reason" className="block text-sm font-medium text-foreground">
Details
</label>
<textarea
id="report-reason"
value={reason}
onChange={(e) => setReason(e.target.value)}
rows={3}
maxLength={2000}
placeholder="Tell us what's happening"
className="w-full bg-background text-foreground text-sm rounded-md border border-border px-3 py-2 outline-none focus-visible:ring-2 focus-visible:ring-primary/40"
/>
</div>
{error ? <p className="text-sm text-destructive">{error}</p> : null}
<div className="flex items-center justify-end gap-2 pt-1">
<Button variant="ghost" onClick={onClose} disabled={working}>
Cancel
</Button>
<Button variant="destructive" onClick={submit} disabled={working}>
{working ? <Spinner /> : null}
Submit report
</Button>
</div>
</div>
</ResponsiveModal>
);
}
// ───────────────────────────────────────────────────────────────────────────
// About this account ("More info")
// ───────────────────────────────────────────────────────────────────────────
function AboutModal({
open,
onClose,
display,
joinedAt,
country,
}: {
open: boolean;
onClose: () => void;
display: string;
joinedAt?: string;
country?: string | null;
}) {
const joined = joinedAt
? new Date(joinedAt).toLocaleDateString(undefined, {
year: "numeric",
month: "long",
day: "numeric",
})
: "Unknown";
const basedIn = countryName(country) ?? "—";
return (
<ResponsiveModal
open={open}
onClose={onClose}
title="About this account"
description={`Public details about ${display}.`}
>
<dl className="space-y-2.5">
<InfoRow
icon={<CalendarDays className="size-4" />}
label="Joined"
value={joined}
/>
<InfoRow
icon={<Globe className="size-4" />}
label="Based in"
value={basedIn}
/>
</dl>
</ResponsiveModal>
);
}
function InfoRow({
icon,
label,
value,
}: {
icon: React.ReactNode;
label: string;
value: string;
}) {
return (
<div className="flex items-start gap-3 px-3 py-2.5">
<span className="shrink-0 mt-0.5 text-muted-foreground">{icon}</span>
<div className="min-w-0">
<dt className="text-xs uppercase tracking-wide text-muted-foreground">
{label}
</dt>
<dd className="text-sm text-foreground wrap-break-word">{value}</dd>
</div>
</div>
);
}