feat: social graph features

This commit is contained in:
gosangam
2026-06-04 19:30:50 +05:30
parent 0f433c5708
commit 684ea2ae97
16 changed files with 2504 additions and 119 deletions
+853
View File
@@ -0,0 +1,853 @@
"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 {
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 items-center gap-2">
{primary}
{/* 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>
);
}
+205 -12
View File
@@ -18,12 +18,40 @@
import { useRef, useState } from "react";
import Image from "next/image";
import { ImagePlus, Save, X } from "lucide-react";
import { toast } from "sonner";
import { useAuth } from "@/components/auth/auth-provider";
import { auth, AuthError, type User } from "@/lib/auth";
import { COUNTRIES } from "@/lib/countries";
import { SAMPRADAYAS } from "@/lib/sampradayas";
import { compressImage } from "@/lib/compress-image";
import { Button } from "@/components/ui/button";
import { Input } from "@/components/ui/input";
import { Label } from "@/components/ui/label";
import { Combobox, type ComboboxOption } from "@/components/ui/combobox";
import { DatePicker } from "@/components/ui/date-picker";
/** Normalises a stored date/timestamp to the "YYYY-MM-DD" an
* <input type="date"> expects. Returns "" for null. */
function dateInput(s: string | null): string {
return s ? s.slice(0, 10) : "";
}
// Option lists for the comboboxes. "" is a real, selectable value meaning
// "not specified" for the optional fields.
const COUNTRY_OPTIONS: ComboboxOption[] = [
{ value: "", label: "Not specified" },
...COUNTRIES.map((c) => ({ value: c.code, label: c.name })),
];
const SAMPRADAYA_OPTIONS: ComboboxOption[] = [
{ value: "", label: "Not specified" },
...SAMPRADAYAS.map((s) => ({ value: s.code, label: s.name })),
];
const GENDER_OPTIONS: ComboboxOption[] = [
{ value: "", label: "Prefer not to say" },
{ value: "male", label: "Male" },
{ value: "female", label: "Female" },
{ value: "other", label: "Other" },
];
export function ProfileEditForm({
user,
@@ -38,29 +66,81 @@ export function ProfileEditForm({
const [name, setName] = useState(user.name);
const [handle, setHandle] = useState(user.handle);
const [avatarUrl, setAvatarUrl] = useState<string | null>(user.avatar_url);
const [country, setCountry] = useState<string>(user.country ?? "");
// Devotional details. Each "" means "not specified".
const [sampradaya, setSampradaya] = useState<string>(user.sampradaya ?? "");
const [gender, setGender] = useState<string>(user.gender ?? "");
// `?? false` guards against a cached user object from before this field
// existed (undefined → uncontrolled checkbox → React warning).
const [initiated, setInitiated] = useState<boolean>(user.initiated ?? false);
const [initiatedAt, setInitiatedAt] = useState<string>(
dateInput(user.initiated_at),
);
const [rounds, setRounds] = useState<string>(
user.daily_chanting_rounds != null ? String(user.daily_chanting_rounds) : "",
);
const [saving, setSaving] = useState(false);
const [uploading, setUploading] = useState(false);
const [error, setError] = useState<string | null>(null);
// Originals normalised for comparison. The initiation date only counts
// when the devotee is marked initiated — un-checking it clears the date.
const origRounds =
user.daily_chanting_rounds != null ? String(user.daily_chanting_rounds) : "";
const effInitiatedAt = initiated ? initiatedAt : "";
const dirty =
name.trim() !== user.name ||
handle.trim() !== user.handle ||
avatarUrl !== user.avatar_url;
avatarUrl !== user.avatar_url ||
country !== (user.country ?? "") ||
sampradaya !== (user.sampradaya ?? "") ||
gender !== (user.gender ?? "") ||
initiated !== (user.initiated ?? false) ||
effInitiatedAt !== dateInput(user.initiated_at) ||
rounds !== origRounds;
async function onSubmit(e: React.SyntheticEvent) {
e.preventDefault();
setError(null);
// Client-side guard for the round count (the BFF re-checks 1–1008).
if (rounds !== "") {
const n = Number(rounds);
if (!Number.isInteger(n) || n < 1 || n > 1008) {
setError("Daily chanting rounds must be a whole number between 1 and 1008.");
return;
}
}
setSaving(true);
try {
// Patch only what's changed — keeps the audit log tidy and avoids
// bumping updated_at when the user just clicked "Save" without edits.
const updated = await auth.updateProfile(
name.trim() !== user.name ? name.trim() : undefined,
avatarUrl === user.avatar_url ? undefined : (avatarUrl ?? ""),
handle.trim() !== user.handle ? handle.trim() : undefined,
);
// Empty strings clear the nullable fields; 0 clears the round count.
const patch: Parameters<typeof auth.updateProfile>[0] = {};
if (name.trim() !== user.name) patch.name = name.trim();
if (avatarUrl !== user.avatar_url) patch.avatar_url = avatarUrl ?? "";
if (handle.trim() !== user.handle) patch.handle = handle.trim();
if (country !== (user.country ?? "")) patch.country = country;
// "" clears the lineage; a code sets it.
if (sampradaya !== (user.sampradaya ?? "")) patch.sampradaya = sampradaya;
if (gender !== (user.gender ?? "")) patch.gender = gender;
if (initiated !== (user.initiated ?? false)) patch.initiated = initiated;
if (effInitiatedAt !== dateInput(user.initiated_at)) {
patch.initiated_at = effInitiatedAt;
}
if (rounds !== origRounds) {
patch.daily_chanting_rounds = rounds === "" ? 0 : Number(rounds);
}
const updated = await auth.updateProfile(patch);
// Update the cached user in place and STAY on the edit form. The
// form's fields re-baseline against the new `user` prop (so it's no
// longer "dirty"), and we keep the ?edit=1 URL rather than bouncing
// back to the profile view. Exit is via Cancel/✕.
setUser(updated);
onDone();
toast.success("Profile saved");
} catch (err) {
setError(err instanceof AuthError ? err.message : "Could not save.");
} finally {
@@ -89,7 +169,7 @@ export function ProfileEditForm({
}
return (
<form onSubmit={onSubmit} className="space-y-6 rounded-2xl bg-card ring-1 ring-foreground/10 p-5 sm:p-6">
<form onSubmit={onSubmit} className="space-y-8 rounded-2xl bg-card ring-1 ring-foreground/10 p-5 sm:p-6">
<div className="flex items-center justify-between">
<h2 className="font-[family-name:var(--font-title)] text-xl sm:text-2xl font-semibold text-foreground">
Edit profile
@@ -139,7 +219,10 @@ export function ProfileEditForm({
</div>
</section>
<div className="space-y-4">
<div className="space-y-4 pt-6 border-t border-border">
<h3 className="text-sm font-semibold uppercase tracking-wide text-muted-foreground">
Account
</h3>
<div className="space-y-1.5">
<Label htmlFor="profile-name">Display name</Label>
<Input
@@ -153,8 +236,17 @@ export function ProfileEditForm({
<div className="space-y-1.5">
<Label htmlFor="profile-handle">Handle</Label>
<div className="flex items-center gap-2">
<span className="text-sm text-muted-foreground">@</span>
{/* "@" sits inside the field as a fixed, non-editable prefix —
pointer-events-none lets clicks fall through to the input, and
the input is padded so the text never overlaps it. The stored
value is still just the handle (no leading @). */}
<div className="relative">
<span
aria-hidden
className="pointer-events-none absolute left-3 top-1/2 -translate-y-1/2 text-sm text-muted-foreground"
>
@
</span>
<Input
id="profile-handle"
value={handle}
@@ -162,6 +254,7 @@ export function ProfileEditForm({
maxLength={32}
pattern="[a-zA-Z0-9._-]+"
required
className="pl-7"
/>
</div>
<p className="text-xs text-muted-foreground">
@@ -169,6 +262,23 @@ export function ProfileEditForm({
</p>
</div>
<div className="space-y-1.5">
<Label htmlFor="profile-country">Country</Label>
<Combobox
id="profile-country"
ariaLabel="Country"
options={COUNTRY_OPTIONS}
value={country}
onChange={setCountry}
placeholder="Not specified"
searchPlaceholder="Search countries…"
emptyText="No matching country."
/>
<p className="text-xs text-muted-foreground">
Shown on your profile&apos;s “About this account” panel.
</p>
</div>
<div className="space-y-1.5">
<Label htmlFor="profile-email">Email</Label>
{user.email ? (
@@ -184,9 +294,92 @@ export function ProfileEditForm({
</div>
</div>
<div className="space-y-4 pt-6 border-t border-border">
<h3 className="text-sm font-semibold uppercase tracking-wide text-muted-foreground">
Devotional details
</h3>
<div className="space-y-1.5">
<Label htmlFor="profile-sampradaya">Sampradāya</Label>
<Combobox
id="profile-sampradaya"
ariaLabel="Sampradāya"
options={SAMPRADAYA_OPTIONS}
value={sampradaya}
onChange={setSampradaya}
placeholder="Not specified"
searchPlaceholder="Search sampradāya…"
emptyText="No matching sampradāya."
/>
<p className="text-xs text-muted-foreground">
Optional. Leave blank if you&apos;d rather not say.
</p>
</div>
<div className="space-y-1.5">
<Label htmlFor="profile-gender">Gender</Label>
<Combobox
id="profile-gender"
ariaLabel="Gender"
options={GENDER_OPTIONS}
value={gender}
onChange={setGender}
searchable={false}
placeholder="Prefer not to say"
/>
</div>
<div className="flex items-center justify-between gap-3">
<div className="min-w-0">
<Label htmlFor="profile-initiated">Initiated</Label>
<p className="text-xs text-muted-foreground">
Have you received initiation (dīkṣā)?
</p>
</div>
<input
id="profile-initiated"
type="checkbox"
checked={initiated}
onChange={(e) => setInitiated(e.target.checked)}
className="size-5 shrink-0 accent-primary"
/>
</div>
{initiated ? (
<div className="space-y-1.5">
<Label htmlFor="profile-initiated-at">Initiation date</Label>
<DatePicker
id="profile-initiated-at"
ariaLabel="Initiation date"
value={initiatedAt}
onChange={setInitiatedAt}
max={new Date().toISOString().slice(0, 10)}
placeholder="Select initiation date"
/>
</div>
) : null}
<div className="space-y-1.5">
<Label htmlFor="profile-rounds">Daily chanting rounds</Label>
<Input
id="profile-rounds"
type="number"
inputMode="numeric"
min={1}
max={1008}
value={rounds}
onChange={(e) => setRounds(e.target.value)}
placeholder="e.g. 16"
/>
<p className="text-xs text-muted-foreground">
Your daily japa vow (1–1008). Leave blank if you&apos;d rather not say.
</p>
</div>
</div>
{error ? <p className="text-sm text-destructive">{error}</p> : null}
<div className="flex items-center justify-end gap-2 pt-2 border-t border-border">
<div className="flex items-center justify-end gap-2 pt-6 border-t border-border">
<Button
type="button"
variant="ghost"
+99 -46
View File
@@ -32,6 +32,8 @@ import Image from "next/image";
import Link from "next/link";
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";
export function ProfileHeader({
avatarURL,
@@ -40,25 +42,57 @@ export function ProfileHeader({
postCount,
joinedAt,
editHref,
followerCount,
followingCount,
relationship,
enableActions = false,
country,
}: {
avatarURL: string | null;
name: string;
handle: string;
postCount?: number;
joinedAt?: string;
/** ISO-2 account country, surfaced in the "More info" modal. */
country?: string | null;
/** When provided, shows an "Edit profile" CTA below the handle AND
* the reading-settings gear. Acts as the canonical "this is my own
* profile" signal across the action row. */
editHref?: string;
/** Accepted-follower / accepted-following totals for the stat line.
* Omit to hide those two stats. */
followerCount?: number;
followingCount?: number;
/** The viewer's relationship to this profile (null for anonymous
* viewers). Only consumed when `enableActions` is set. */
relationship?: RelationshipState | null;
/** Render the follow / block / report action row — set on OTHER users'
* profiles (not the owner's /u/me, which shows Edit/Settings). Mount
* this header with key={handle} so the live count + relationship state
* below re-seeds cleanly when navigating between profiles. */
enableActions?: boolean;
}) {
// Both action-row affordances are owner-only and ride on the same
// `editHref` signal — when it's absent we render no action row at
// all, which keeps visitor profile views clean.
const showReadingSettings = !!editHref;
const showActions = !!editHref;
// Owner affordances ride on `editHref`; the follow-action row rides on
// `enableActions`. Mutually exclusive by construction.
const showOwnerControls = !!editHref;
const [zoomOpen, setZoomOpen] = useState(false);
// Live counts + relationship — seeded from props, updated in place after
// a follow/accept/block action so the stat line and buttons stay in sync
// without a refetch. Re-seeds per profile via the call-site key.
const [followers, setFollowers] = useState(followerCount ?? 0);
const [following, setFollowing] = useState(followingCount ?? 0);
const [rel, setRel] = useState<RelationshipState | null>(relationship ?? null);
const handleResult = (r: RelationshipResult) => {
setRel(r.relationship);
setFollowers(r.follower_count);
setFollowing(r.following_count);
};
const showCounts = typeof followerCount === "number";
return (
<>
<header className="flex flex-col items-center text-center gap-4 pt-4 pb-6 sm:pt-6 sm:pb-8">
@@ -67,50 +101,59 @@ export function ProfileHeader({
name={name}
onZoom={avatarURL ? () => setZoomOpen(true) : undefined}
/>
<div className="space-y-1">
<h1 className="font-[family-name:var(--font-title)] font-semibold text-xl sm:text-2xl text-foreground leading-tight">
{name}
</h1>
<p className="text-sm text-muted-foreground">@{handle}</p>
{typeof postCount === "number" || joinedAt ? (
<p className="text-xs text-muted-foreground">
{typeof postCount === "number" ? (
<>
<span className="tabular-nums">{postCount}</span> post
{postCount === 1 ? "" : "s"}
</>
) : null}
{typeof postCount === "number" && joinedAt ? " · " : null}
{joinedAt ? <>Joined {new Date(joinedAt).toLocaleDateString()}</> : null}
</p>
) : null}
</div>
{showActions ? (
<div className="flex items-center gap-2">
{editHref ? (
<Link
href={editHref}
className="inline-flex items-center justify-center h-9 px-5 rounded-lg border border-border text-sm font-medium text-foreground hover:bg-muted transition-colors"
>
Edit profile
</Link>
<div className="space-y-2">
<div className="space-y-1">
<h1 className="font-[family-name:var(--font-title)] font-semibold text-xl sm:text-2xl text-foreground leading-tight">
{name}
</h1>
<p className="text-sm text-muted-foreground">@{handle}</p>
</div>
{/* Stat line: posts · followers · following */}
<div className="flex items-center justify-center gap-5 sm:gap-7 pt-1 my-4">
{typeof postCount === "number" ? (
<Stat n={postCount} label={postCount === 1 ? "post" : "posts"} />
) : null}
{showReadingSettings ? (
<Link
href="/settings"
aria-label="Settings"
title="Settings"
className={cn(
"size-9 inline-flex items-center justify-center rounded-lg",
"border border-border text-foreground hover:bg-muted",
"transition-colors outline-none",
"focus-visible:ring-2 focus-visible:ring-ring",
)}
>
<Settings className="size-4" />
</Link>
{showCounts ? (
<>
<Stat n={followers} label="followers" />
<Stat n={following} label="following" />
</>
) : null}
</div>
</div>
{showOwnerControls ? (
<div className="flex items-center gap-2">
<Link
href={editHref!}
className="inline-flex items-center justify-center h-9 px-5 rounded-lg border border-border text-sm font-medium text-foreground hover:bg-muted transition-colors"
>
Edit profile
</Link>
<Link
href="/settings"
aria-label="Settings"
title="Settings"
className={cn(
"size-9 inline-flex items-center justify-center rounded-lg",
"border border-border text-foreground hover:bg-muted",
"transition-colors outline-none",
"focus-visible:ring-2 focus-visible:ring-ring",
)}
>
<Settings className="size-4" />
</Link>
</div>
) : enableActions ? (
<ProfileActions
handle={handle}
name={name}
joinedAt={joinedAt}
country={country}
relationship={rel}
onResult={handleResult}
/>
) : null}
</header>
{avatarURL ? (
@@ -125,6 +168,16 @@ export function ProfileHeader({
);
}
/** One inline profile stat — bold count over a muted label. */
function Stat({ n, label }: { n: number; label: string }) {
return (
<div className="flex flex-col items-center leading-tight">
<span className="font-semibold text-lg text-foreground tabular-nums">{n}</span>
<span className="text-sm text-muted-foreground">{label}</span>
</div>
);
}
function Avatar({
src,
name,