feat: vitual lazy load on combobox
This commit is contained in:
156
src/components/async-combobox/AsyncCombobox.tsx
Normal file
156
src/components/async-combobox/AsyncCombobox.tsx
Normal file
@@ -0,0 +1,156 @@
|
||||
'use client';
|
||||
|
||||
import { useCallback, useRef, useState } from 'react';
|
||||
import { Loader2 } from 'lucide-react';
|
||||
import type { Virtualizer } from '@tanstack/react-virtual';
|
||||
|
||||
import { Button } from '@/components/ui/button';
|
||||
import {
|
||||
Combobox,
|
||||
ComboboxContent,
|
||||
ComboboxEmpty,
|
||||
ComboboxInput,
|
||||
ComboboxList,
|
||||
ComboboxTrigger,
|
||||
ComboboxValue,
|
||||
} from '@/components/ui/combobox';
|
||||
|
||||
import type { AsyncComboboxOption, AsyncComboboxProps } from './AsyncCombobox.types';
|
||||
import { VirtualComboboxList } from './VirtualComboboxList';
|
||||
|
||||
type VirtualizerHandle = Virtualizer<HTMLDivElement, Element>;
|
||||
|
||||
export function AsyncCombobox({
|
||||
lookup,
|
||||
onValueChange,
|
||||
placeholder = 'Select option',
|
||||
searchPlaceholder = 'Search...',
|
||||
emptyMessage = 'No items found.',
|
||||
disabled = false,
|
||||
portalContainer,
|
||||
}: AsyncComboboxProps) {
|
||||
const [open, setOpen] = useState(false);
|
||||
const virtualizerRef = useRef<VirtualizerHandle | null>(null);
|
||||
const {
|
||||
options,
|
||||
selectedOption,
|
||||
search,
|
||||
setSearch,
|
||||
isLoading,
|
||||
isFetchingNextPage,
|
||||
isError,
|
||||
errorMessage,
|
||||
hasNextPage,
|
||||
fetchNextPage,
|
||||
} = lookup;
|
||||
|
||||
const handleOpenChange = useCallback(
|
||||
(nextOpen: boolean) => {
|
||||
setOpen(nextOpen);
|
||||
if (!nextOpen) {
|
||||
setSearch('');
|
||||
}
|
||||
},
|
||||
[setSearch],
|
||||
);
|
||||
|
||||
const handleValueChange = useCallback(
|
||||
(item: AsyncComboboxOption | null) => {
|
||||
if (item?.value) {
|
||||
onValueChange(item.value);
|
||||
}
|
||||
},
|
||||
[onValueChange],
|
||||
);
|
||||
|
||||
const handleItemHighlighted = useCallback(
|
||||
(
|
||||
_item: AsyncComboboxOption | undefined,
|
||||
event: { reason: string; index: number },
|
||||
) => {
|
||||
const virtualizer = virtualizerRef.current;
|
||||
if (!virtualizer) {
|
||||
return;
|
||||
}
|
||||
|
||||
const { reason, index } = event;
|
||||
const isStart = index === 0;
|
||||
const isEnd = index === virtualizer.options.count - 1;
|
||||
const shouldScroll =
|
||||
reason === 'none' || (reason === 'keyboard' && (isStart || isEnd));
|
||||
|
||||
if (shouldScroll) {
|
||||
queueMicrotask(() => {
|
||||
virtualizer.scrollToIndex(index, { align: isEnd ? 'start' : 'end' });
|
||||
});
|
||||
}
|
||||
},
|
||||
[],
|
||||
);
|
||||
|
||||
const handleLoadMore = useCallback(() => {
|
||||
void fetchNextPage();
|
||||
}, [fetchNextPage]);
|
||||
|
||||
const isDisabled = disabled || isLoading;
|
||||
const triggerPlaceholder = isLoading ? 'Loading...' : placeholder;
|
||||
|
||||
return (
|
||||
<Combobox
|
||||
virtualized
|
||||
items={options}
|
||||
value={selectedOption}
|
||||
onValueChange={handleValueChange}
|
||||
open={open}
|
||||
onOpenChange={handleOpenChange}
|
||||
inputValue={search}
|
||||
onInputValueChange={setSearch}
|
||||
filter={null}
|
||||
disabled={isDisabled}
|
||||
itemToStringLabel={(item) => item.label}
|
||||
isItemEqualToValue={(item, currentValue) => item.value === currentValue.value}
|
||||
onItemHighlighted={handleItemHighlighted}
|
||||
>
|
||||
<ComboboxTrigger
|
||||
render={
|
||||
<Button
|
||||
type="button"
|
||||
variant="outline"
|
||||
className="w-full justify-between font-normal"
|
||||
disabled={isDisabled}
|
||||
>
|
||||
{isLoading && !selectedOption ? (
|
||||
<span className="flex items-center gap-2 text-muted-foreground">
|
||||
<Loader2 className="size-4 animate-spin" />
|
||||
Loading...
|
||||
</span>
|
||||
) : (
|
||||
<ComboboxValue placeholder={triggerPlaceholder} />
|
||||
)}
|
||||
</Button>
|
||||
}
|
||||
/>
|
||||
<ComboboxContent container={portalContainer}>
|
||||
<ComboboxInput showTrigger={false} placeholder={searchPlaceholder} disabled={isDisabled} />
|
||||
{isError ? (
|
||||
<div className="px-3 py-2 text-sm text-destructive">
|
||||
{errorMessage || 'Unable to load options.'}
|
||||
</div>
|
||||
) : (
|
||||
<>
|
||||
<ComboboxEmpty>{emptyMessage}</ComboboxEmpty>
|
||||
<ComboboxList className="p-0">
|
||||
<VirtualComboboxList
|
||||
open={open}
|
||||
virtualizerRef={virtualizerRef}
|
||||
hasNextPage={hasNextPage}
|
||||
isFetchingNextPage={isFetchingNextPage}
|
||||
onLoadMore={handleLoadMore}
|
||||
/>
|
||||
</ComboboxList>
|
||||
</>
|
||||
)}
|
||||
</ComboboxContent>
|
||||
</Combobox>
|
||||
);
|
||||
}
|
||||
50
src/components/async-combobox/AsyncCombobox.types.ts
Normal file
50
src/components/async-combobox/AsyncCombobox.types.ts
Normal file
@@ -0,0 +1,50 @@
|
||||
import type { RefObject } from 'react';
|
||||
|
||||
export type AsyncComboboxOption = {
|
||||
value: string;
|
||||
label: string;
|
||||
};
|
||||
|
||||
export type PaginatedResult<T> = {
|
||||
items: T[];
|
||||
total: number;
|
||||
};
|
||||
|
||||
export type PaginatedLookupConfig<T> = {
|
||||
enabled?: boolean;
|
||||
pageSize?: number;
|
||||
debounceMs?: number;
|
||||
selectedValue?: string;
|
||||
queryKey: (searchTerm: string) => readonly unknown[];
|
||||
queryFn: (args: {
|
||||
searchTerm: string;
|
||||
skip: number;
|
||||
limit: number;
|
||||
}) => Promise<PaginatedResult<T>>;
|
||||
mapOption: (item: T) => AsyncComboboxOption;
|
||||
resolveSelected?: (value: string) => Promise<T | null>;
|
||||
resolveSelectedQueryKey?: (value: string) => readonly unknown[];
|
||||
};
|
||||
|
||||
export interface PaginatedLookupState {
|
||||
options: AsyncComboboxOption[];
|
||||
selectedOption: AsyncComboboxOption | null;
|
||||
search: string;
|
||||
setSearch: (value: string) => void;
|
||||
isLoading: boolean;
|
||||
isFetchingNextPage: boolean;
|
||||
isError: boolean;
|
||||
errorMessage?: string;
|
||||
hasNextPage: boolean;
|
||||
fetchNextPage: () => void | Promise<unknown>;
|
||||
}
|
||||
|
||||
export interface AsyncComboboxProps {
|
||||
lookup: PaginatedLookupState;
|
||||
onValueChange: (value: string) => void;
|
||||
placeholder?: string;
|
||||
searchPlaceholder?: string;
|
||||
emptyMessage?: string;
|
||||
disabled?: boolean;
|
||||
portalContainer?: RefObject<HTMLDivElement | null>;
|
||||
}
|
||||
125
src/components/async-combobox/VirtualComboboxList.tsx
Normal file
125
src/components/async-combobox/VirtualComboboxList.tsx
Normal file
@@ -0,0 +1,125 @@
|
||||
'use client';
|
||||
|
||||
import { useCallback, useEffect, useImperativeHandle, useRef, type RefObject } from 'react';
|
||||
import { Combobox } from '@base-ui/react/combobox';
|
||||
import { useVirtualizer, type Virtualizer } from '@tanstack/react-virtual';
|
||||
import { Loader2 } from 'lucide-react';
|
||||
|
||||
import { ComboboxItem } from '@/components/ui/combobox';
|
||||
import { cn } from '@/lib/utils';
|
||||
|
||||
import type { AsyncComboboxOption } from './AsyncCombobox.types';
|
||||
|
||||
type VirtualizerHandle = Virtualizer<HTMLDivElement, Element>;
|
||||
const LOAD_MORE_THRESHOLD = 3;
|
||||
|
||||
interface VirtualComboboxListProps {
|
||||
open: boolean;
|
||||
virtualizerRef: RefObject<VirtualizerHandle | null>;
|
||||
hasNextPage: boolean;
|
||||
isFetchingNextPage: boolean;
|
||||
onLoadMore: () => void;
|
||||
estimateSize?: number;
|
||||
}
|
||||
|
||||
export function VirtualComboboxList({
|
||||
open,
|
||||
virtualizerRef,
|
||||
hasNextPage,
|
||||
isFetchingNextPage,
|
||||
onLoadMore,
|
||||
estimateSize = 36,
|
||||
}: VirtualComboboxListProps) {
|
||||
const filteredItems = Combobox.useFilteredItems<AsyncComboboxOption>();
|
||||
const scrollElementRef = useRef<HTMLDivElement | null>(null);
|
||||
const itemCount = filteredItems.length + (hasNextPage ? 1 : 0);
|
||||
|
||||
const virtualizer = useVirtualizer({
|
||||
enabled: open,
|
||||
count: itemCount,
|
||||
getScrollElement: () => scrollElementRef.current,
|
||||
estimateSize: () => estimateSize,
|
||||
overscan: 8,
|
||||
paddingStart: 4,
|
||||
paddingEnd: 4,
|
||||
});
|
||||
|
||||
useImperativeHandle(virtualizerRef, () => virtualizer, [virtualizer]);
|
||||
|
||||
const handleScrollElementRef = useCallback(
|
||||
(element: HTMLDivElement | null) => {
|
||||
scrollElementRef.current = element;
|
||||
if (element) {
|
||||
virtualizer.measure();
|
||||
}
|
||||
},
|
||||
[virtualizer],
|
||||
);
|
||||
|
||||
const virtualItems = virtualizer.getVirtualItems();
|
||||
const totalSize = virtualizer.getTotalSize();
|
||||
const lastVirtualIndex = virtualItems[virtualItems.length - 1]?.index ?? -1;
|
||||
|
||||
useEffect(() => {
|
||||
if (lastVirtualIndex < 0) {
|
||||
return;
|
||||
}
|
||||
|
||||
if (
|
||||
lastVirtualIndex >= filteredItems.length - LOAD_MORE_THRESHOLD &&
|
||||
hasNextPage &&
|
||||
!isFetchingNextPage
|
||||
) {
|
||||
onLoadMore();
|
||||
}
|
||||
}, [filteredItems.length, hasNextPage, isFetchingNextPage, lastVirtualIndex, onLoadMore]);
|
||||
|
||||
if (!filteredItems.length && !hasNextPage) {
|
||||
return null;
|
||||
}
|
||||
|
||||
return (
|
||||
<div
|
||||
ref={handleScrollElementRef}
|
||||
className={cn(
|
||||
'max-h-[min(21.75rem,calc(var(--available-height)-2.25rem))] overflow-y-auto overscroll-contain p-1',
|
||||
)}
|
||||
style={{ height: Math.min(totalSize + 8, 348) }}
|
||||
>
|
||||
<div className="relative w-full" style={{ height: totalSize }}>
|
||||
{virtualItems.map((virtualItem) => {
|
||||
const isLoaderRow = virtualItem.index >= filteredItems.length;
|
||||
const item = filteredItems[virtualItem.index];
|
||||
|
||||
return (
|
||||
<div
|
||||
key={virtualItem.key}
|
||||
data-index={virtualItem.index}
|
||||
ref={virtualizer.measureElement}
|
||||
className="absolute top-0 left-0 w-full"
|
||||
style={{
|
||||
height: virtualItem.size,
|
||||
transform: `translateY(${virtualItem.start}px)`,
|
||||
}}
|
||||
>
|
||||
{isLoaderRow ? (
|
||||
<div className="flex items-center justify-center py-2 text-muted-foreground">
|
||||
<Loader2 className="size-4 animate-spin" />
|
||||
</div>
|
||||
) : (
|
||||
<ComboboxItem
|
||||
value={item}
|
||||
index={virtualItem.index}
|
||||
aria-setsize={filteredItems.length}
|
||||
aria-posinset={virtualItem.index + 1}
|
||||
>
|
||||
{item.label}
|
||||
</ComboboxItem>
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
})}
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
9
src/components/async-combobox/index.ts
Normal file
9
src/components/async-combobox/index.ts
Normal file
@@ -0,0 +1,9 @@
|
||||
export { AsyncCombobox } from './AsyncCombobox';
|
||||
export { usePaginatedLookup } from './usePaginatedLookup';
|
||||
export type {
|
||||
AsyncComboboxProps,
|
||||
AsyncComboboxOption,
|
||||
PaginatedLookupState,
|
||||
PaginatedLookupConfig,
|
||||
PaginatedResult,
|
||||
} from './AsyncCombobox.types';
|
||||
94
src/components/async-combobox/usePaginatedLookup.ts
Normal file
94
src/components/async-combobox/usePaginatedLookup.ts
Normal file
@@ -0,0 +1,94 @@
|
||||
'use client';
|
||||
|
||||
import { useMemo, useState } from 'react';
|
||||
import { useInfiniteQuery, useQuery } from '@tanstack/react-query';
|
||||
|
||||
import { useDebounce } from '@/hooks/useDebounce';
|
||||
|
||||
import type { AsyncComboboxOption, PaginatedLookupConfig } from './AsyncCombobox.types';
|
||||
|
||||
export function usePaginatedLookup<T>({
|
||||
enabled = true,
|
||||
pageSize = 20,
|
||||
debounceMs = 400,
|
||||
selectedValue = '',
|
||||
queryKey,
|
||||
queryFn,
|
||||
mapOption,
|
||||
resolveSelected,
|
||||
resolveSelectedQueryKey,
|
||||
}: PaginatedLookupConfig<T>) {
|
||||
const [search, setSearch] = useState('');
|
||||
const debouncedSearch = useDebounce(search.trim(), debounceMs);
|
||||
|
||||
const infiniteQuery = useInfiniteQuery({
|
||||
queryKey: queryKey(debouncedSearch),
|
||||
queryFn: ({ pageParam }) =>
|
||||
queryFn({
|
||||
searchTerm: debouncedSearch,
|
||||
skip: pageParam,
|
||||
limit: pageSize,
|
||||
}),
|
||||
initialPageParam: 0,
|
||||
getNextPageParam: (lastPage, allPages) => {
|
||||
if (lastPage.items.length === 0) {
|
||||
return undefined;
|
||||
}
|
||||
|
||||
const loadedCount = allPages.reduce((count, page) => count + page.items.length, 0);
|
||||
return loadedCount < lastPage.total ? loadedCount : undefined;
|
||||
},
|
||||
enabled,
|
||||
staleTime: 5 * 60 * 1000,
|
||||
gcTime: 30 * 60 * 1000,
|
||||
});
|
||||
|
||||
const options = useMemo<AsyncComboboxOption[]>(() => {
|
||||
const items = infiniteQuery.data?.pages.flatMap((page) => page.items) ?? [];
|
||||
return items.map(mapOption);
|
||||
}, [infiniteQuery.data?.pages, mapOption]);
|
||||
|
||||
const selectedInList = useMemo(
|
||||
() => options.find((option) => option.value === selectedValue) ?? null,
|
||||
[options, selectedValue],
|
||||
);
|
||||
|
||||
const resolvedSelectedQuery = useQuery({
|
||||
queryKey: resolveSelectedQueryKey?.(selectedValue) ?? [
|
||||
...queryKey(''),
|
||||
'selected',
|
||||
selectedValue,
|
||||
],
|
||||
queryFn: async () => {
|
||||
if (!selectedValue || !resolveSelected) {
|
||||
return null;
|
||||
}
|
||||
|
||||
const item = await resolveSelected(selectedValue);
|
||||
return item ? mapOption(item) : null;
|
||||
},
|
||||
enabled: enabled && Boolean(selectedValue) && !selectedInList && Boolean(resolveSelected),
|
||||
staleTime: 5 * 60 * 1000,
|
||||
gcTime: 30 * 60 * 1000,
|
||||
});
|
||||
|
||||
const selectedOption = selectedInList ?? resolvedSelectedQuery.data ?? null;
|
||||
|
||||
return {
|
||||
search,
|
||||
setSearch,
|
||||
options,
|
||||
selectedOption,
|
||||
isLoading: infiniteQuery.isLoading,
|
||||
isError: infiniteQuery.isError || resolvedSelectedQuery.isError,
|
||||
errorMessage:
|
||||
infiniteQuery.error instanceof Error
|
||||
? infiniteQuery.error.message
|
||||
: resolvedSelectedQuery.error instanceof Error
|
||||
? resolvedSelectedQuery.error.message
|
||||
: undefined,
|
||||
isFetchingNextPage: infiniteQuery.isFetchingNextPage,
|
||||
hasNextPage: infiniteQuery.hasNextPage ?? false,
|
||||
fetchNextPage: infiniteQuery.fetchNextPage,
|
||||
};
|
||||
}
|
||||
74
src/components/lookups/RoleCombobox.tsx
Normal file
74
src/components/lookups/RoleCombobox.tsx
Normal file
@@ -0,0 +1,74 @@
|
||||
'use client';
|
||||
|
||||
import { AsyncCombobox, usePaginatedLookup } from '@/components/async-combobox';
|
||||
import type { AsyncComboboxOption } from '@/components/async-combobox';
|
||||
import { roleService } from '@/services/api';
|
||||
import type { Role } from '@/types';
|
||||
|
||||
import { roleKeys } from '@/app/(modules)/roles/queries/roleKeys';
|
||||
import type { RoleComboboxProps } from './RoleCombobox.types';
|
||||
|
||||
const ROLE_PAGE_SIZE = 20;
|
||||
|
||||
function parseRoleId(value: string) {
|
||||
const roleId = Number(value);
|
||||
return Number.isFinite(roleId) ? roleId : null;
|
||||
}
|
||||
|
||||
function mapRoleOption(role: Role): AsyncComboboxOption {
|
||||
return {
|
||||
value: String(role.id),
|
||||
label: role.display_name || role.name,
|
||||
};
|
||||
}
|
||||
|
||||
export function RoleCombobox({
|
||||
value,
|
||||
onValueChange,
|
||||
enabled = true,
|
||||
disabled = false,
|
||||
portalContainer,
|
||||
}: RoleComboboxProps) {
|
||||
const lookup = usePaginatedLookup<Role>({
|
||||
enabled,
|
||||
selectedValue: value,
|
||||
pageSize: ROLE_PAGE_SIZE,
|
||||
queryKey: (searchTerm) =>
|
||||
[
|
||||
...roleKeys.lists(),
|
||||
'async-lookup',
|
||||
searchTerm,
|
||||
ROLE_PAGE_SIZE,
|
||||
] as const,
|
||||
queryFn: ({ searchTerm, skip, limit }) =>
|
||||
roleService.getRoles({
|
||||
search_term: searchTerm || undefined,
|
||||
skip,
|
||||
limit,
|
||||
effective_status: true,
|
||||
sort_by: 'display_name',
|
||||
sort_order: 'asc',
|
||||
}),
|
||||
mapOption: mapRoleOption,
|
||||
resolveSelected: (roleId) => {
|
||||
const numericRoleId = parseRoleId(roleId);
|
||||
return numericRoleId ? roleService.getRoleById(numericRoleId) : Promise.resolve(null);
|
||||
},
|
||||
resolveSelectedQueryKey: (roleId) => {
|
||||
const numericRoleId = parseRoleId(roleId);
|
||||
return numericRoleId ? roleKeys.detail(numericRoleId) : [...roleKeys.details(), 'invalid', roleId];
|
||||
},
|
||||
});
|
||||
|
||||
return (
|
||||
<AsyncCombobox
|
||||
lookup={lookup}
|
||||
onValueChange={onValueChange}
|
||||
disabled={disabled}
|
||||
placeholder="Select role"
|
||||
searchPlaceholder="Search roles..."
|
||||
emptyMessage="No roles found."
|
||||
portalContainer={portalContainer}
|
||||
/>
|
||||
);
|
||||
}
|
||||
9
src/components/lookups/RoleCombobox.types.ts
Normal file
9
src/components/lookups/RoleCombobox.types.ts
Normal file
@@ -0,0 +1,9 @@
|
||||
import type { RefObject } from 'react';
|
||||
|
||||
export interface RoleComboboxProps {
|
||||
value: string;
|
||||
onValueChange: (value: string) => void;
|
||||
enabled?: boolean;
|
||||
disabled?: boolean;
|
||||
portalContainer?: RefObject<HTMLDivElement | null>;
|
||||
}
|
||||
Reference in New Issue
Block a user