Files
tbbank-frontend/src/components/infiniteSelect.tsx
2026-09-30 20:36:17 +05:00

269 lines
9.5 KiB
TypeScript

import { useEffect, useRef, useState } from "react";
import * as PopoverPrimitive from "@radix-ui/react-popover";
import { Check, ChevronsUpDown, Search, X, Loader2 } from "lucide-react";
import { cn } from "@/lib/utils";
// ─── Types ────────────────────────────────────────────────────────────────────
export interface InfiniteSelectOption {
value: string;
label: string;
}
export interface InfiniteSelectProps {
value?: string;
onChange?: (value: string) => void;
options?: InfiniteSelectOption[];
placeholder?: string;
searchPlaceholder?: string;
label?: string;
required?: boolean;
error?: string;
disabled?: boolean;
loading?: boolean;
isLoadingMore?: boolean;
hasNextPage?: boolean;
onLoadMore?: () => void;
searchValue?: string;
onSearchChange?: (value: string) => void;
onOpenChange?: (open: boolean) => void;
}
/**
* Searchable select with infinite scroll.
*
* The consumer owns the data fetching (e.g. TanStack Query `useInfiniteQuery`):
* it passes the flattened options, and `hasNextPage`/`onLoadMore` drive loading
* additional pages when the list bottom is reached.
*/
export function InfiniteSelect({
value = "",
onChange,
options = [],
placeholder = "Saýlamak üçin basyň",
searchPlaceholder = "Gözle...",
label,
required,
error,
disabled,
loading = false,
isLoadingMore = false,
hasNextPage = false,
onLoadMore,
searchValue,
onSearchChange,
onOpenChange,
}: InfiniteSelectProps) {
const [open, setOpen] = useState(false);
const containerRef = useRef<HTMLDivElement>(null);
const scrollContainerRef = useRef<HTMLDivElement>(null);
const sentinelRef = useRef<HTMLDivElement>(null);
const [portalContainer, setPortalContainer] = useState<HTMLElement | undefined>(undefined);
useEffect(() => {
if (containerRef.current) {
const dialog = containerRef.current.closest<HTMLElement>(
'[role="dialog"], [role="alertdialog"], [data-slot="alert-dialog-content"], [data-slot="dialog-content"]',
);
if (dialog) {
setPortalContainer(dialog);
}
}
}, []);
useEffect(() => {
const el = scrollContainerRef.current;
if (!el || !open) return;
const handleWheel = (e: WheelEvent) => {
e.stopPropagation();
};
el.addEventListener("wheel", handleWheel, { passive: true });
return () => el.removeEventListener("wheel", handleWheel);
}, [open]);
const selected = options.find((o) => o.value === value);
const handleSelect = (val: string) => {
onChange?.(val);
setOpen(false);
};
const handleClear = (e: React.MouseEvent) => {
e.preventDefault();
e.stopPropagation();
onChange?.("");
};
const loadingRef = useRef(false);
useEffect(() => {
if (!isLoadingMore) {
loadingRef.current = false;
}
}, [isLoadingMore]);
useEffect(() => {
if (!open || !sentinelRef.current || !hasNextPage || isLoadingMore) return;
const el = sentinelRef.current;
const observer = new IntersectionObserver(
(entries) => {
if (entries[0]?.isIntersecting && hasNextPage && !isLoadingMore && !loadingRef.current) {
loadingRef.current = true;
onLoadMore?.();
}
},
{ rootMargin: "120px" },
);
observer.observe(el);
return () => observer.disconnect();
}, [open, hasNextPage, isLoadingMore, onLoadMore]);
return (
<div ref={containerRef} className="relative">
{label && (
<label className="block text-xs font-semibold text-muted-foreground uppercase tracking-wider mb-1.5 select-none">
{label}
{required && <span className="text-destructive ml-0.5">*</span>}
</label>
)}
<PopoverPrimitive.Root
open={open}
onOpenChange={(next) => {
if (!disabled) {
setOpen(next);
onOpenChange?.(next);
}
}}
>
<PopoverPrimitive.Trigger asChild>
<button
type="button"
disabled={disabled}
className={cn(
"flex h-8 w-full items-center justify-between rounded-md border border-input bg-transparent dark:bg-input/30 px-3 py-2",
"text-sm ring-offset-background transition-colors duration-150",
"focus-visible:outline-none focus-visible:ring-1 focus-visible:ring-ring focus-visible:ring-offset-0",
"disabled:cursor-not-allowed disabled:opacity-50",
error ? "border-destructive" : "border-input",
open && !error && "ring-2 ring-ring ring-offset-0 border-transparent",
)}
>
<span className={cn("truncate text-left", !selected && "text-muted-foreground")}>
{selected ? selected.label : placeholder}
</span>
<div className="flex items-center gap-1 shrink-0 ml-2">
{selected && !disabled && (
<span
role="button"
tabIndex={-1}
onMouseDown={handleClear}
className="p-0.5 rounded text-muted-foreground hover:text-foreground transition-colors"
>
<X size={12} />
</span>
)}
<ChevronsUpDown
size={14}
className={cn("text-muted-foreground transition-transform duration-200 shrink-0", open && "text-foreground")}
/>
</div>
</button>
</PopoverPrimitive.Trigger>
<PopoverPrimitive.Portal container={portalContainer}>
<PopoverPrimitive.Content
align="start"
side="bottom"
sideOffset={4}
collisionPadding={16}
avoidCollisions
style={{ width: "var(--radix-popover-trigger-width)" }}
className="z-50 rounded-md border border-border bg-card shadow-lg overflow-hidden max-h-[var(--radix-popover-content-available-height)] flex flex-col"
onWheel={(e) => e.stopPropagation()}
onTouchMove={(e) => e.stopPropagation()}
>
{onSearchChange && (
<div className="flex items-center gap-2 px-3 py-2 border-b border-border bg-muted/20 shrink-0">
<Search size={13} className="text-muted-foreground shrink-0" />
<input
type="text"
value={searchValue ?? ""}
onChange={(e) => onSearchChange(e.target.value)}
placeholder={searchPlaceholder}
className="flex-1 bg-transparent text-sm text-foreground placeholder:text-muted-foreground/50 focus:outline-none"
/>
{searchValue && (
<button
type="button"
tabIndex={-1}
onMouseDown={() => onSearchChange?.("")}
className="text-muted-foreground hover:text-foreground transition-colors"
>
<X size={12} />
</button>
)}
</div>
)}
<div
ref={scrollContainerRef}
onWheel={(e) => e.stopPropagation()}
onTouchMove={(e) => e.stopPropagation()}
className="max-h-60 overflow-y-auto overscroll-contain scrollbar-thin py-1"
>
{loading && options.length === 0 ? (
<p className="px-3 py-4 text-sm text-muted-foreground text-center flex items-center justify-center gap-2">
<Loader2 size={14} className="animate-spin" /> Loading...
</p>
) : options.length === 0 ? (
<p className="px-3 py-4 text-sm text-muted-foreground text-center">Netije tapylmady</p>
) : (
options.map((opt) => {
const isSelected = opt.value === value;
return (
<button
key={opt.value}
type="button"
onMouseDown={(e) => {
e.preventDefault();
handleSelect(opt.value);
}}
className={cn(
"flex items-center justify-between w-full text-left px-3 py-2 text-sm transition-colors",
"hover:bg-accent hover:text-accent-foreground",
isSelected && "text-primary font-medium bg-primary/10",
)}
>
<span>{opt.label}</span>
{isSelected && <Check size={13} className="text-primary shrink-0" />}
</button>
);
})
)}
{hasNextPage && (
<div ref={sentinelRef} className="px-3 py-2 text-xs text-muted-foreground text-center">
{isLoadingMore && (
<span className="inline-flex items-center gap-1.5">
<Loader2 size={12} className="animate-spin" /> Loading...
</span>
)}
</div>
)}
</div>
</PopoverPrimitive.Content>
</PopoverPrimitive.Portal>
</PopoverPrimitive.Root>
{error && (
<p className="mt-1.5 text-xs text-destructive font-medium flex items-center gap-1.5">
<span className="inline-block w-1 h-1 rounded-full bg-destructive shrink-0" />
{error}
</p>
)}
</div>
);
}