add virtual list for combobox

This commit is contained in:
Carl-Gerhard Lindesvärd
2024-07-12 00:01:31 +02:00
parent c14de56325
commit 01ed4acce2
4 changed files with 113 additions and 46 deletions

View File

@@ -1,13 +1,9 @@
import * as React from 'react';
import { Badge } from '@/components/ui/badge';
import {
Command,
CommandGroup,
CommandInput,
CommandItem,
CommandList,
} from '@/components/ui/command';
import { Command, CommandInput, CommandItem } from '@/components/ui/command';
import { cn } from '@/utils/cn';
import { ChevronsUpDownIcon } from 'lucide-react';
import VirtualList from 'rc-virtual-list';
import { useOnClickOutside } from 'usehooks-ts';
import { Button } from './button';
@@ -71,10 +67,31 @@ export function ComboboxAdvanced({
);
};
const renderUnknownItem = (value: IValue) => {
const item = items.find((item) => item.value === value);
return item ? renderItem(item) : renderItem({ value, label: value });
};
const data = React.useMemo(() => {
return [
...(inputValue === ''
? []
: [
{
value: inputValue,
label: `Pick '${inputValue}'`,
},
]),
...value.map((val) => {
const item = items.find((item) => item.value === val);
return item
? {
value: val,
label: item.label,
}
: {
value: val,
label: val,
};
}),
...selectables,
].filter((item) => item.value);
}, [inputValue, selectables, items]);
return (
<Popover open={open} onOpenChange={setOpen}>
@@ -82,7 +99,7 @@ export function ComboboxAdvanced({
<Button
variant={'outline'}
onClick={() => setOpen((prev) => !prev)}
className={className}
className={cn('h-min-10 h-auto', className)}
>
<div className="flex w-full flex-wrap gap-1">
{value.length === 0 && placeholder}
@@ -104,15 +121,9 @@ export function ComboboxAdvanced({
value={inputValue}
onValueChange={setInputValue}
/>
<CommandList>
{inputValue !== '' &&
renderItem({
value: inputValue,
label: `Pick '${inputValue}'`,
})}
{value.map(renderUnknownItem)}
{selectables.map(renderItem)}
</CommandList>
<VirtualList height={300} data={data} itemHeight={32} itemKey="value">
{renderItem}
</VirtualList>
</Command>
</PopoverContent>
</Popover>