All files / packages/components/src autocomplete.web.tsx

100% Statements 6/6
66.66% Branches 4/6
100% Functions 4/4
100% Lines 6/6

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94                                                                        698x               768x                   768x                                 55x               1049x   1604x                        
import {
	AutocompleteItem,
	Autocomplete as AutocompleteRaw,
	AutocompleteSection,
} from "@heroui/autocomplete";
import { useInfiniteScroll } from "@heroui/use-infinite-scroll";
 
import { cn } from "~components/utils";
import type { ViewReactNode } from "~components/view.web";
 
export type Props = Pick<
	React.ComponentProps<typeof AutocompleteRaw>,
	"inputValue" | "onInputChange" | "placeholder" | "isDisabled"
> & {
	children: {
		key: string;
		title?: string;
		items: {
			key: string;
			className?: string;
			textValue: string;
			children?: ViewReactNode;
		}[];
	}[];
	label?: string;
	endContent?: ViewReactNode;
	selectedKey: string | null;
	onSelectionChange: (nextKey: string | null) => void;
	emptyContent: string;
	onClear?: () => void;
	scroll?: {
		loadMore: () => void;
		hasMore: boolean;
		isDisabled?: boolean;
	};
};
export const Autocomplete: React.FC<Props> = ({
	children,
	emptyContent,
	onClear,
	onSelectionChange,
	scroll,
	...rest
}) => {
	const [, scrollRef] = useInfiniteScroll(
		scroll
			? {
					hasMore: scroll.hasMore,
					isEnabled: !scroll.isDisabled,
					onLoadMore: scroll.loadMore,
					shouldUseLoader: false,
				}
			: {},
	);
	return (
		<AutocompleteRaw
			labelPlacement="outside"
			variant="bordered"
			listboxProps={{
				classNames: { list: "m-0" },
				emptyContent,
			}}
			clearButtonProps={
				onClear
					? {
							onPress: onClear,
						}
					: undefined
			}
			items={[]}
			onSelectionChange={(nextSelection) =>
				onSelectionChange(
					nextSelection === null ? null : nextSelection.toString(),
				)
			}
			scrollRef={scrollRef}
			{...rest}
		>
			{children.map(({ items, key, ...section }) => (
				<AutocompleteSection key={key} {...section}>
					{items.map(({ key: itemKey, className, ...item }) => (
						<AutocompleteItem
							key={itemKey}
							{...item}
							classNames={{ title: "flex" }}
							className={cn("p-1", className)}
						/>
					))}
				</AutocompleteSection>
			))}
		</AutocompleteRaw>
	);
};