Files
spsays-training/components/chat/new-group-dialog.tsx
T
2026-08-29 03:49:58 +05:30

189 lines
6.7 KiB
TypeScript

"use client";
/**
* Create a group: name it, pick people, done.
*
* Members are named by handle, matching the member-management API — search
* results already identify people that way, so nothing needs id plumbing.
*/
import { useEffect, useState } from "react";
import { useRouter } from "next/navigation";
import { Check, Search, X } from "lucide-react";
import { toast } from "sonner";
import { useAuth } from "@/components/auth/auth-provider";
import { UserAvatar } from "@/components/ui/user-avatar";
import { Button } from "@/components/ui/button";
import { chat } from "@/lib/chat";
type Candidate = { handle: string; name: string; avatar_url: string | null };
export function NewGroupDialog({ onClose }: { onClose: () => void }) {
const router = useRouter();
const { user } = useAuth();
const [title, setTitle] = useState("");
const [query, setQuery] = useState("");
// Results are stored with the query they belong to, so what's displayed can
// be derived: a stale page from a previous query simply stops matching, and
// nothing has to be cleared from an effect.
const [results, setResults] = useState<{ q: string; rows: Candidate[] }>({
q: "",
rows: [],
});
const [picked, setPicked] = useState<Map<string, Candidate>>(new Map());
const [busy, setBusy] = useState(false);
const q = query.trim();
const searchable = q.length >= 2;
// Never offer yourself: you're the group's creator, and the BFF drops the
// caller from the member list anyway — so picking yourself would look like it
// worked and then silently do nothing.
const visible =
results.q === q
? results.rows.filter((u) => u.handle !== user?.handle)
: [];
useEffect(() => {
if (!searchable) return;
const timer = setTimeout(() => {
fetch(`/api/search/users?q=${encodeURIComponent(q)}&limit=15`)
.then((r) => r.json())
.then((d: { results?: Candidate[] }) =>
setResults({ q, rows: d.results ?? [] }),
)
.catch(() => setResults({ q, rows: [] }));
}, 300);
return () => clearTimeout(timer);
}, [q, searchable]);
useEffect(() => {
const onKey = (e: KeyboardEvent) => e.key === "Escape" && onClose();
window.addEventListener("keydown", onKey);
return () => window.removeEventListener("keydown", onKey);
}, [onClose]);
const toggle = (u: Candidate) =>
setPicked((prev) => {
const next = new Map(prev);
if (next.has(u.handle)) next.delete(u.handle);
else next.set(u.handle, u);
return next;
});
const create = async () => {
const name = title.trim();
if (!name) return;
setBusy(true);
try {
const conv = await chat.createGroup(name, [...picked.keys()]);
toast.success("Group created");
router.push(`/chats/${conv.id}`);
} catch {
toast.error("Could not create the group");
setBusy(false);
}
};
return (
<div className="fixed inset-0 z-50 flex items-end justify-center bg-black/40 sm:items-center">
<div className="absolute inset-0" onClick={onClose} aria-hidden />
<div className="relative z-10 flex max-h-[80vh] w-full max-w-md flex-col overflow-hidden rounded-t-2xl border border-border bg-background sm:rounded-2xl">
<div className="flex items-center justify-between border-b border-border px-4 py-3">
<h2 className="text-sm font-semibold text-foreground">New group</h2>
<button
type="button"
onClick={onClose}
aria-label="Close"
className="rounded-md p-1 text-muted-foreground hover:text-foreground"
>
<X className="size-4" />
</button>
</div>
<div className="space-y-3 border-b border-border p-3">
<input
autoFocus
value={title}
onChange={(e) => setTitle(e.target.value)}
maxLength={120}
placeholder="Group name"
className="w-full rounded-lg border border-border bg-muted/40 px-3 py-2 text-sm outline-none focus:ring-1 focus:ring-primary/40"
/>
<div className="flex items-center gap-2 rounded-lg bg-muted/40 px-3 py-2">
<Search className="size-4 shrink-0 text-muted-foreground" />
<input
value={query}
onChange={(e) => setQuery(e.target.value)}
placeholder="Add people"
className="flex-1 bg-transparent text-sm outline-none placeholder:text-muted-foreground"
/>
</div>
{picked.size > 0 && (
<div className="flex flex-wrap gap-1.5">
{[...picked.values()].map((u) => (
<button
key={u.handle}
type="button"
onClick={() => toggle(u)}
className="inline-flex items-center gap-1 rounded-full bg-primary/10 px-2 py-1 text-xs text-primary"
>
{u.name}
<X className="size-3" />
</button>
))}
</div>
)}
</div>
<div className="flex-1 overflow-y-auto">
{!searchable ? (
<p className="p-4 text-sm text-muted-foreground">
Search to add people. You can also add them later.
</p>
) : visible.length === 0 ? (
<p className="p-4 text-sm text-muted-foreground">No one found.</p>
) : (
<ul className="divide-y divide-border">
{visible.map((u) => (
<li key={u.handle}>
<button
type="button"
onClick={() => toggle(u)}
className="flex w-full items-center gap-3 px-4 py-3 text-left hover:bg-muted/60"
>
<UserAvatar
src={u.avatar_url}
name={u.name}
className="size-9 shrink-0"
/>
<div className="min-w-0 flex-1">
<p className="truncate text-sm text-foreground">{u.name}</p>
<p className="truncate text-xs text-muted-foreground">
@{u.handle}
</p>
</div>
{picked.has(u.handle) && (
<Check className="size-4 shrink-0 text-primary" />
)}
</button>
</li>
))}
</ul>
)}
</div>
<div className="border-t border-border p-3">
<Button
className="w-full"
disabled={title.trim() === "" || busy}
onClick={create}
>
Create group
</Button>
</div>
</div>
</div>
);
}