All files / src/components/ui multi-select.tsx

97.14% Statements 34/35
91.66% Branches 33/36
100% Functions 16/16
96.77% Lines 30/31

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 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151                                                      1728x 1728x     1728x 3766x       1728x 1278x 56x       56x       1278x 1278x     1728x 9x 4x   7x     7x       1728x 14x     1728x                     28x   2x 2x 2x               1493x 1493x                   11x 11x                                       85x   85x 85x                         9x                            
import { useState, useRef, useEffect, useMemo } from "react";
import { X } from "lucide-react";
import { cn } from "../../lib/utils";
 
type MultiSelectProps = {
	options: { value: string; label: string }[];
	selected: string[];
	onChange: (values: string[]) => void;
	placeholder?: string;
	maxItems?: number;
	id?: string;
	"aria-label"?: string;
	"aria-labelledby"?: string;
	className?: string;
};
 
export function MultiSelect({
	options,
	selected,
	onChange,
	placeholder = "Select options...",
	maxItems,
	id,
	"aria-label": ariaLabel,
	"aria-labelledby": ariaLabelledBy,
	className,
}: MultiSelectProps) {
	const [isOpen, setIsOpen] = useState(false);
	const containerRef = useRef<HTMLDivElement>(null);
 
	// O(1) option lookup by value
	const optionMap = useMemo(
		() => new Map(options.map((opt) => [opt.value, opt])),
		[options],
	);
 
	useEffect(() => {
		const handleClickOutside = (event: MouseEvent) => {
			Eif (
				containerRef.current &&
				!containerRef.current.contains(event.target as Node)
			) {
				setIsOpen(false);
			}
		};
 
		document.addEventListener("mousedown", handleClickOutside);
		return () => document.removeEventListener("mousedown", handleClickOutside);
	}, []);
 
	const handleToggle = (value: string) => {
		if (selected.includes(value)) {
			onChange(selected.filter((v) => v !== value));
		} else {
			Iif (maxItems && selected.length >= maxItems) {
				return;
			}
			onChange([...selected, value]);
		}
	};
 
	const handleRemove = (value: string) => {
		onChange(selected.filter((v) => v !== value));
	};
 
	return (
		<div ref={containerRef} className={cn("relative", className)}>
			<div
				role="combobox"
				tabIndex={0}
				id={id}
				aria-label={ariaLabel}
				aria-labelledby={ariaLabelledBy}
				aria-expanded={isOpen}
				aria-haspopup="listbox"
				className="flex min-h-[40px] w-full flex-wrap gap-2 rounded-md border border-border-default bg-background-elevated px-3 py-2 text-sm text-foreground-default cursor-pointer hover:border-border-strong transition-colors text-left"
				onClick={() => setIsOpen(!isOpen)}
				onKeyDown={(e) => {
					Eif (e.key === "Enter" || e.key === " ") {
						e.preventDefault();
						setIsOpen(!isOpen);
					}
				}}
			>
				{selected.length === 0 ? (
					<span className="text-foreground-subtle">{placeholder}</span>
				) : (
					selected.map((value) => {
						const option = optionMap.get(value);
						return (
							<span
								key={value}
								className="inline-flex items-center gap-1 rounded bg-primary-100 px-2 py-1 text-xs font-medium text-primary-800"
							>
								{option?.label || value}
								<button
									type="button"
									aria-label={`Remove ${option?.label || value}`}
									onClick={(e) => {
										e.stopPropagation();
										handleRemove(value);
									}}
									className="hover:text-primary-900"
								>
									<X className="h-3 w-3" />
								</button>
							</span>
						);
					})
				)}
			</div>
 
			{isOpen && (
				<div className="absolute z-10 mt-1 max-h-60 w-full overflow-auto rounded-md border border-border-default bg-background-elevated shadow-lg">
					{options.length === 0 ? (
						<div className="px-3 py-2 text-sm text-foreground-muted">
							No options available
						</div>
					) : (
						options.map((option) => {
							const isSelected = selected.includes(option.value);
							const isDisabled =
								!isSelected && maxItems && selected.length >= maxItems;
							return (
								<label
									key={option.value}
									className={cn(
										"flex items-center px-3 py-2 text-sm cursor-pointer hover:bg-background-muted",
										isSelected && "bg-primary-50 text-primary-900 font-medium",
										isDisabled &&
											"opacity-50 cursor-not-allowed pointer-events-none",
									)}
								>
									<input
										type="checkbox"
										checked={isSelected}
										onChange={() => !isDisabled && handleToggle(option.value)}
										className="mr-2 accent-primary-500"
										disabled={isDisabled || undefined}
									/>
									{option.label}
								</label>
							);
						})
					)}
				</div>
			)}
		</div>
	);
}