feat: add user search

This commit is contained in:
gosangam
2026-05-31 10:43:30 +05:30
parent c20d6bffe8
commit d8de0a18e5
7 changed files with 504 additions and 122 deletions
+232 -9
View File
@@ -2,6 +2,7 @@
import { useState, useEffect, useCallback, useRef, Suspense } from "react";
import { useSearchParams, useRouter } from "next/navigation";
import Image from "next/image";
import Link from "next/link";
import { Input } from "@/components/ui/input";
import { Badge } from "@/components/ui/badge";
@@ -23,8 +24,24 @@ import {
ChevronLeft,
ChevronRight,
WholeWord,
AtSign,
} from "lucide-react";
// ---------------------------------------------------------------------------
// User search types
// ---------------------------------------------------------------------------
interface UserResult {
handle: string;
name: string;
avatar_url?: string | null;
}
interface UserSearchResponse {
query: string;
results: UserResult[];
}
// ---------------------------------------------------------------------------
// Types
// ---------------------------------------------------------------------------
@@ -203,15 +220,33 @@ function SearchInner() {
const urlTypeParam =
selectedTypes.size === 0 ? "all" : Array.from(selectedTypes).join(",");
const [data, setData] = useState<SearchResponse | null>(null);
// Separate state slot for user-search results — keeps the content
// search response shape clean and lets the two branches render
// entirely different cards without a discriminated-union dance.
const [userData, setUserData] = useState<UserSearchResponse | null>(null);
const [isLoading, setIsLoading] = useState(false);
const debouncedQuery = useDebouncedValue(inputValue, 300);
const isQueryEmpty = !debouncedQuery.trim();
// User-search mode is driven entirely by the input — when the query
// starts with "@" we strip it and hit /api/search/users instead of
// the regular content search. The Users chip is a UI shortcut that
// toggles the "@" prefix on / off; it never holds independent state.
const isUserSearch = debouncedQuery.trimStart().startsWith("@");
const userQuery = isUserSearch
? debouncedQuery.trimStart().slice(1).trim()
: "";
const isUserQueryEmpty = isUserSearch && userQuery.length === 0;
// When the query is empty, derive these as "no results" during render
// instead of setting state inside an effect.
const effectiveData = isQueryEmpty ? null : data;
const hasSearched = isQueryEmpty ? false : !!debouncedQuery.trim();
const effectiveData =
isQueryEmpty || isUserSearch ? null : data;
const hasSearched =
isUserSearch
? !isUserQueryEmpty
: !isQueryEmpty;
// Sync URL when state changes
const pushUrl = useCallback(
@@ -244,10 +279,14 @@ function SearchInner() {
setCurrentPage(1);
}
// Fetch search results
// Fetch search results — branches between user search (`@`-prefixed)
// and content search. We clear the *other* state slot on every run
// so the UI doesn't show stale results from a previous mode.
useEffect(() => {
const query = debouncedQuery.trim();
if (!query) {
// Empty query in either mode — push a clean URL and bail.
if (!query || isUserQueryEmpty) {
pushUrl("", urlTypeParam, 1, exactMatch);
return;
}
@@ -257,6 +296,30 @@ function SearchInner() {
const controller = new AbortController();
if (isUserSearch) {
// User-search branch — strip the @ prefix server-side too.
// Clear content data so we don't flash old content results.
setData(null);
const userParams = new URLSearchParams({ q: userQuery, limit: "20" });
fetch(`/api/search/users?${userParams.toString()}`, {
signal: controller.signal,
})
.then((res) => res.json())
.then((json: UserSearchResponse) => {
setUserData({ ...json, results: json.results ?? [] });
setIsLoading(false);
})
.catch((err) => {
if (err.name !== "AbortError") {
setIsLoading(false);
setUserData({ query: userQuery, results: [] });
}
});
return () => controller.abort();
}
// Content-search branch (unchanged from before — verbatim).
setUserData(null);
const params = new URLSearchParams({
q: query,
type: activeTypeParam,
@@ -288,13 +351,40 @@ function SearchInner() {
});
return () => controller.abort();
}, [debouncedQuery, activeTypeParam, urlTypeParam, currentPage, exactMatch, pushUrl]);
}, [
debouncedQuery,
activeTypeParam,
urlTypeParam,
currentPage,
exactMatch,
pushUrl,
isUserSearch,
isUserQueryEmpty,
userQuery,
]);
// Auto-focus the input on mount
useEffect(() => {
inputRef.current?.focus();
}, []);
// Users chip is "active" whenever the live input starts with "@".
// Clicking it toggles the prefix on / off — no separate state slot
// since the input is already the source of truth.
const isUserChipActive = inputValue.trimStart().startsWith("@");
const toggleUsersChip = () => {
const trimmed = inputValue.trimStart();
if (trimmed.startsWith("@")) {
// Strip the @ prefix (and the surrounding whitespace it carried).
setInputValue(trimmed.slice(1));
} else {
// Prepend @ — preserves whatever the user has already typed.
setInputValue("@" + trimmed);
}
// Focus the input so the cursor lands ready for typing.
inputRef.current?.focus();
};
const handleTypeChange = (type: string) => {
if (type === "all") {
// "All" clears all individual selections
@@ -385,17 +475,53 @@ function SearchInner() {
{/* Content Type Tabs */}
<div className="mt-5 flex flex-wrap gap-2">
{/* Users chip — toggles the "@" prefix on the input. Sits at
the start of the row so its at-sign icon reads as a kind
of "search mode" indicator. */}
<button
type="button"
onClick={toggleUsersChip}
aria-pressed={isUserChipActive}
className={cn(
"inline-flex items-center gap-1.5 rounded-lg px-3 py-1.5 text-sm font-medium transition-colors",
isUserChipActive
? "bg-primary text-primary-foreground"
: "bg-muted text-muted-foreground hover:bg-muted/80 hover:text-foreground",
)}
>
<AtSign className="size-4" />
Users
{userData &&
isUserChipActive &&
userData.results.length > 0 && (
<span
className={cn(
"ml-1 inline-flex items-center justify-center rounded-full px-1.5 py-0.5 text-xs font-semibold leading-none",
"bg-primary-foreground/20 text-primary-foreground",
)}
>
{userData.results.length}
</span>
)}
</button>
{CONTENT_TABS.map((tab) => {
const active = isTypeActive(tab.value);
const active = !isUserChipActive && isTypeActive(tab.value);
return (
<button
key={tab.value}
onClick={() => handleTypeChange(tab.value)}
disabled={isUserChipActive}
className={cn(
"inline-flex items-center gap-1.5 rounded-lg px-3 py-1.5 text-sm font-medium transition-colors",
active
? "bg-primary text-primary-foreground"
: "bg-muted text-muted-foreground hover:bg-muted/80 hover:text-foreground",
// When the @ prefix is on, content tabs don't apply —
// grey them out so the chip group reads as "user
// mode is exclusive".
isUserChipActive &&
"opacity-40 cursor-not-allowed hover:bg-muted hover:text-muted-foreground",
)}
>
{tab.label}
@@ -431,8 +557,61 @@ function SearchInner() {
page doubles as the browsing entry point. */}
{!isLoading && !hasSearched && <KnowledgebaseIndex />}
{/* No results */}
{/* User search — empty state (just typed @) */}
{!isLoading && isUserSearch && isUserQueryEmpty && (
<div className="flex flex-col items-center justify-center py-16 text-center">
<AtSign className="size-12 text-muted-foreground/40 mb-4" />
<p className="text-lg text-muted-foreground">
Searching users
<br />
<span className="text-sm">
Type a name or handle after the &ldquo;@&rdquo; to find
someone.
</span>
</p>
</div>
)}
{/* User search — no matches */}
{!isLoading &&
isUserSearch &&
!isUserQueryEmpty &&
userData &&
userData.results.length === 0 && (
<div className="flex flex-col items-center justify-center py-16 text-center">
<AtSign className="size-12 text-muted-foreground/40 mb-4" />
<p className="text-lg text-muted-foreground">
No users found for &ldquo;@{userQuery}&rdquo;.
<br />
<span className="text-sm">
Try a different name or handle.
</span>
</p>
</div>
)}
{/* User search — results */}
{!isLoading &&
isUserSearch &&
userData &&
userData.results.length > 0 && (
<>
<p className="mb-4 text-sm text-muted-foreground">
{userData.results.length}{" "}
{userData.results.length === 1 ? "user" : "users"} matching
&ldquo;@{userQuery}&rdquo;
</p>
<div className="grid grid-cols-1 sm:grid-cols-2 gap-3">
{userData.results.map((u) => (
<UserResultCard key={u.handle} user={u} />
))}
</div>
</>
)}
{/* Content search — no results */}
{!isLoading &&
!isUserSearch &&
hasSearched &&
effectiveData &&
effectiveData.results.length === 0 && (
@@ -448,8 +627,12 @@ function SearchInner() {
</div>
)}
{/* Results */}
{!isLoading && effectiveData && effectiveData.results.length > 0 && (
{/* Results (content search only — user-search has its own
block above with avatar-flavoured cards) */}
{!isLoading &&
!isUserSearch &&
effectiveData &&
effectiveData.results.length > 0 && (
<>
{/* Results count + top pagination */}
<div className="mb-4 flex items-center justify-between flex-wrap gap-3">
@@ -687,6 +870,46 @@ function ResultMeta({ result }: { result: SearchResult }) {
);
}
// ---------------------------------------------------------------------------
// User result card
// ---------------------------------------------------------------------------
function UserResultCard({ user }: { user: UserResult }) {
const initial = user.name?.charAt(0)?.toUpperCase() || "?";
return (
<Link
href={`/u/${user.handle}`}
className={cn(
"flex items-center gap-3 rounded-xl bg-card ring-1 ring-foreground/10 p-4",
"hover:ring-foreground/25 hover:shadow-sm transition-all",
)}
>
{user.avatar_url ? (
<Image
src={user.avatar_url}
alt={user.name}
width={56}
height={56}
className="size-14 rounded-full object-cover ring-1 ring-foreground/10 shrink-0"
unoptimized
/>
) : (
<div className="size-14 rounded-full bg-primary/15 text-primary flex items-center justify-center text-xl font-semibold ring-1 ring-foreground/10 shrink-0">
{initial}
</div>
)}
<div className="min-w-0 flex-1">
<p className="text-sm font-semibold text-foreground truncate">
{user.name}
</p>
<p className="text-xs text-muted-foreground truncate">
@{user.handle}
</p>
</div>
</Link>
);
}
// ---------------------------------------------------------------------------
// Exported wrapper with Suspense boundary
// ---------------------------------------------------------------------------