tahamajs/IE / Projects /front /src /components /article /ArticleSelector.tsx
tahamajs's picture
download
raw
10.2 kB
// src/components/article/ArticleSelector.tsx
import { useState, useEffect, useRef, useMemo, useCallback } from "react";
import api from "@/lib/api";
import { Search, X, BookOpen, Loader2, ChevronDown, Check } from "lucide-react";
interface Article {
id: number;
title: string;
authorUsername: string;
}
interface ArticleSelectorProps {
selectedIds: number[];
onChange: (ids: number[]) => void;
placeholder?: string;
maxItems?: number;
enableServerSearch?: boolean; // if true, searches via API on input
debounceMs?: number;
}
export function ArticleSelector({
selectedIds,
onChange,
placeholder = "Select reference articles...",
maxItems,
enableServerSearch = false,
debounceMs = 300,
}: ArticleSelectorProps) {
const [articles, setArticles] = useState<Article[]>([]);
const [loading, setLoading] = useState(true);
const [search, setSearch] = useState("");
const [open, setOpen] = useState(false);
const [searching, setSearching] = useState(false);
const [error, setError] = useState<string | null>(null);
const containerRef = useRef<HTMLDivElement>(null);
const searchInputRef = useRef<HTMLInputElement>(null);
const listboxRef = useRef<HTMLDivElement>(null);
const [highlightedIndex, setHighlightedIndex] = useState<number>(-1);
// Fetch all articles initially (if not server search mode)
const fetchArticles = useCallback(async (query?: string) => {
setError(null);
try {
if (query) setSearching(true);
else setLoading(true);
const url = query ? `/articles/search?q=${encodeURIComponent(query)}&limit=20` : "/articles";
const res = await api.get(url);
const data = res.data?.articles || res.data?.results || res.data?.result || res.data || [];
setArticles(Array.isArray(data) ? data : []);
} catch (err) {
console.error("Failed to fetch articles", err);
setError("Could not load articles");
} finally {
setLoading(false);
setSearching(false);
}
}, []);
useEffect(() => {
if (!enableServerSearch) fetchArticles();
}, [fetchArticles, enableServerSearch]);
// Debounced search for server mode
useEffect(() => {
if (!enableServerSearch) return;
const timer = setTimeout(() => {
if (search.trim()) fetchArticles(search);
else fetchArticles();
}, debounceMs);
return () => clearTimeout(timer);
}, [search, enableServerSearch, fetchArticles, debounceMs]);
// Client-side filtering
const filteredArticles = useMemo(() => {
if (enableServerSearch) return articles;
const term = search.toLowerCase();
return articles.filter(
(a) =>
a.title.toLowerCase().includes(term) ||
a.authorUsername.toLowerCase().includes(term)
);
}, [articles, search, enableServerSearch]);
// Close on outside click
useEffect(() => {
const handleClickOutside = (event: MouseEvent) => {
if (containerRef.current && !containerRef.current.contains(event.target as Node)) {
setOpen(false);
setHighlightedIndex(-1);
}
};
document.addEventListener("mousedown", handleClickOutside);
return () => document.removeEventListener("mousedown", handleClickOutside);
}, []);
// Keyboard navigation
const handleKeyDown = (e: React.KeyboardEvent) => {
if (!open) {
if (e.key === "ArrowDown" || e.key === "Enter") {
e.preventDefault();
setOpen(true);
setHighlightedIndex(0);
setTimeout(() => searchInputRef.current?.focus(), 10);
}
return;
}
switch (e.key) {
case "Escape":
setOpen(false);
setHighlightedIndex(-1);
break;
case "ArrowDown":
e.preventDefault();
setHighlightedIndex((prev) => Math.min(prev + 1, filteredArticles.length - 1));
break;
case "ArrowUp":
e.preventDefault();
setHighlightedIndex((prev) => Math.max(prev - 1, -1));
break;
case "Enter":
e.preventDefault();
if (highlightedIndex >= 0 && filteredArticles[highlightedIndex]) {
toggleSelect(filteredArticles[highlightedIndex].id);
}
break;
}
};
const toggleSelect = (id: number) => {
if (selectedIds.includes(id)) {
onChange(selectedIds.filter((i) => i !== id));
} else {
if (maxItems && selectedIds.length >= maxItems) return;
onChange([...selectedIds, id]);
}
};
const clearAll = () => {
if (selectedIds.length === 0) return;
onChange([]);
};
const getTitle = (id: number) =>
articles.find((a) => a.id === id)?.title || `Article #${id}`;
const isMaxReached = maxItems ? selectedIds.length >= maxItems : false;
return (
<div ref={containerRef} className="relative w-full" onKeyDown={handleKeyDown}>
{/* Trigger / selected chips */}
<div
onClick={() => {
setOpen(!open);
if (!open) setTimeout(() => searchInputRef.current?.focus(), 10);
}}
className={`flex flex-wrap gap-1 items-center min-h-[42px] p-2 border rounded-xl cursor-pointer transition ${
open
? "border-primary ring-2 ring-primary/20"
: "border-gray-200 dark:border-gray-700 hover:border-primary/50"
} bg-white dark:bg-gray-800`}
role="combobox"
aria-expanded={open}
aria-haspopup="listbox"
aria-label="Select reference articles"
>
{selectedIds.length === 0 && (
<span className="text-sm text-gray-400 pl-2">{placeholder}</span>
)}
{selectedIds.map((id) => (
<span
key={id}
className="inline-flex items-center gap-1 bg-primary/10 text-primary px-2 py-0.5 rounded-full text-sm"
>
{getTitle(id)}
<button
type="button"
onClick={(e) => {
e.stopPropagation();
toggleSelect(id);
}}
className="hover:text-red-500 focus:outline-none"
aria-label={`Remove ${getTitle(id)}`}
>
<X className="w-3 h-3" />
</button>
</span>
))}
{maxItems && selectedIds.length > 0 && (
<span className="text-xs text-gray-400 ml-auto">
{selectedIds.length}/{maxItems}
</span>
)}
<ChevronDown className="w-4 h-4 text-gray-400 ml-auto" />
</div>
{/* Dropdown list */}
{open && (
<div className="absolute z-20 mt-1 w-full bg-white dark:bg-gray-800 border border-gray-200 dark:border-gray-700 rounded-xl shadow-xl overflow-hidden">
<div className="flex items-center border-b px-3">
<Search className="w-4 h-4 text-gray-400" />
<input
ref={searchInputRef}
type="text"
className="flex-1 p-2 text-sm bg-transparent focus:outline-none text-gray-700 dark:text-gray-200"
placeholder="Search by title or author..."
value={search}
onChange={(e) => setSearch(e.target.value)}
onClick={(e) => e.stopPropagation()}
aria-label="Search articles"
/>
{search && (
<button
onClick={() => setSearch("")}
className="text-gray-400 hover:text-gray-600"
>
<X className="w-4 h-4" />
</button>
)}
</div>
<div
ref={listboxRef}
className="max-h-56 overflow-y-auto"
role="listbox"
aria-multiselectable="true"
>
{(loading || searching) && (
<div className="flex items-center justify-center p-6 text-gray-400">
<Loader2 className="animate-spin w-5 h-5 mr-2" />
{searching ? "Searching..." : "Loading articles..."}
</div>
)}
{error && (
<div className="p-4 text-center text-sm text-red-500">{error}</div>
)}
{!loading && !searching && !error && filteredArticles.length === 0 && (
<div className="p-4 text-center text-sm text-gray-400">
{search ? "No articles match your search" : "No articles available"}
</div>
)}
{filteredArticles.map((article, idx) => {
const isSelected = selectedIds.includes(article.id);
const isHighlighted = idx === highlightedIndex;
return (
<div
key={article.id}
onClick={() => toggleSelect(article.id)}
className={`flex items-start gap-3 p-3 cursor-pointer transition ${
isSelected
? "bg-blue-50 dark:bg-blue-900/20"
: "hover:bg-gray-50 dark:hover:bg-gray-700/50"
} ${isHighlighted ? "bg-gray-100 dark:bg-gray-700" : ""}`}
role="option"
aria-selected={isSelected}
aria-label={`${article.title} by ${article.authorUsername}${
isSelected ? ", selected" : ""
}`}
>
<BookOpen className="w-5 h-5 mt-0.5 text-gray-400 flex-shrink-0" />
<div className="flex-1 min-w-0">
<div className="text-sm font-medium text-gray-800 dark:text-gray-200 truncate">
{article.title}
</div>
<div className="text-xs text-gray-400">by {article.authorUsername}</div>
</div>
{isSelected && <Check className="w-5 h-5 text-primary flex-shrink-0" />}
</div>
);
})}
</div>
{selectedIds.length > 0 && (
<div className="border-t p-2 flex justify-end">
<button
onClick={clearAll}
className="text-xs text-red-500 hover:text-red-600 flex items-center gap-1"
>
<X className="w-3 h-3" /> Clear all
</button>
</div>
)}
</div>
)}
</div>
);
}

Xet Storage Details

Size:
10.2 kB
·
Xet hash:
c63cff35887a6f82a1b3c6d4db884ef4734dd763ad719f1a25e064bca353b02e

Xet efficiently stores files, intelligently splitting them into unique chunks and accelerating uploads and downloads. More info.