Files

209 lines
6.7 KiB
TypeScript

"use client";
/**
* MentionAutocomplete — a search field for tagging users. Results render
* INLINE (in normal flow) directly below the input, not as a floating
* popover. This is deliberate: a floating popover inside a drawer/modal
* overflows the sheet and its outside-click listener fights the drawer's own
* dismiss. Inline results:
* • never resize/overflow the drawer (the container scrolls them),
* • close on blur (no document listener → outside clicks don't close the
* drawer),
* • only appear once the user types (no suggestions on bare focus).
*
* Suggestions come from the backend prioritised (following → followers →
* others), 20 per page, infinite-scrolling. Already-selected users are
* filtered out. Selecting a user adds it (via onSelect) and closes the list.
*/
import { useEffect, useRef, useState } from "react";
import Image from "next/image";
import { Loader2 } from "lucide-react";
import { posts, type UserSummary } from "@/lib/social";
const PAGE = 20;
export function MentionAutocomplete({
excludeIds = [],
onSelect,
placeholder = "Search people to mention…",
autoFocus = false,
}: {
excludeIds?: string[];
onSelect: (user: UserSummary) => void;
placeholder?: string;
autoFocus?: boolean;
}) {
const [q, setQ] = useState("");
const [open, setOpen] = useState(false);
const [items, setItems] = useState<UserSummary[]>([]);
const [loading, setLoading] = useState(false);
const [hasMore, setHasMore] = useState(false);
const reqRef = useRef(0);
const busyRef = useRef(false);
const blurTimer = useRef<number | null>(null);
const query = q.trim();
const showResults = open && query !== "";
// (Re)load page 0 when the query changes — debounced, only when non-empty.
// No fetch on bare focus, so suggestions appear "while typing" only.
useEffect(() => {
if (query === "") return;
const t = window.setTimeout(() => {
const token = ++reqRef.current;
busyRef.current = true;
setLoading(true);
posts
.mentionSuggest(query, { limit: PAGE, offset: 0 })
.then((res) => {
if (reqRef.current !== token) return;
setItems(res);
setHasMore(res.length === PAGE);
})
.catch(() => {
if (reqRef.current === token) {
setItems([]);
setHasMore(false);
}
})
.finally(() => {
if (reqRef.current === token) {
setLoading(false);
busyRef.current = false;
}
});
}, 200);
return () => window.clearTimeout(t);
}, [query]);
function loadMore() {
if (busyRef.current || !hasMore) return;
const token = reqRef.current;
busyRef.current = true;
setLoading(true);
posts
.mentionSuggest(query, { limit: PAGE, offset: items.length })
.then((res) => {
if (reqRef.current !== token) return;
setItems((prev) => [...prev, ...res]);
setHasMore(res.length === PAGE);
})
.catch(() => {})
.finally(() => {
if (reqRef.current === token) {
setLoading(false);
busyRef.current = false;
}
});
}
const excluded = new Set(excludeIds);
const visible = items.filter((u) => !u.id || !excluded.has(u.id));
return (
<div>
<input
type="text"
value={q}
autoFocus={autoFocus}
onFocus={() => setOpen(true)}
onChange={(e) => {
setQ(e.target.value);
setOpen(true);
}}
onBlur={() => {
// Defer so a result tap (which fires onMouseDown→onClick) isn't
// pre-empted by the list closing. Plain blur (tapping elsewhere)
// just closes the inline list — the drawer is unaffected.
blurTimer.current = window.setTimeout(() => setOpen(false), 120);
}}
placeholder={placeholder}
autoComplete="off"
// 16px on mobile so iOS Safari doesn't auto-zoom on focus.
className="w-full rounded-lg border border-border bg-background px-3 py-2 text-base sm:text-sm text-foreground outline-none placeholder:text-muted-foreground focus-visible:ring-2 focus-visible:ring-ring"
/>
{showResults ? (
<div
onScroll={(e) => {
const el = e.currentTarget;
if (el.scrollHeight - el.scrollTop - el.clientHeight < 80) {
loadMore();
}
}}
className="mt-2 max-h-56 overflow-y-auto overscroll-contain rounded-lg border border-border bg-card"
>
{visible.length === 0 && !loading ? (
<p className="px-3 py-3 text-sm text-muted-foreground">
No people found.
</p>
) : (
visible.map((u) => (
<button
key={u.id ?? u.handle}
type="button"
// Keep focus + cancel the pending blur-close so the click
// registers before the list would otherwise close.
onMouseDown={(e) => {
e.preventDefault();
if (blurTimer.current) window.clearTimeout(blurTimer.current);
}}
onClick={() => {
onSelect(u);
setQ("");
setOpen(false);
}}
className="flex w-full items-center gap-2.5 px-3 py-2 text-left transition-colors hover:bg-muted/60"
>
<RowAvatar src={u.avatar_url} name={u.name} />
<span className="min-w-0">
<span className="block truncate text-sm font-medium text-foreground">
{u.name}
</span>
<span className="block truncate text-xs text-muted-foreground">
@{u.handle}
</span>
</span>
</button>
))
)}
{loading ? (
<div className="flex justify-center py-2">
<Loader2 className="size-4 animate-spin text-muted-foreground" />
</div>
) : null}
</div>
) : null}
</div>
);
}
function RowAvatar({ src, name }: { src: string | null; name: string }) {
if (src) {
return (
<Image
src={src}
alt={name}
width={32}
height={32}
className="size-8 shrink-0 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 (
<span className="flex size-8 shrink-0 items-center justify-center rounded-full bg-primary/15 text-xs font-semibold text-primary ring-1 ring-foreground/10">
{initials}
</span>
);
}