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 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 | 3x 52x 52x 52x 52x 52x 52x 57x 52x 52x 52x 52x 52x 52x 32x 32x 9x 52x 37x 8x 4x 1x 1x 8x 8x 52x 4x 4x 4x 4x 52x 6x 6x 6x 52x 4x 2x 2x 1x 2x 1x 1x 1x 1x 1x 1x 1x 1x 1x 52x 52x 3x 3x 3x 21x 3x 3x | 'use client';
import { useEffect, useId, useMemo, useRef, useState } from 'react';
import type { KeyboardEvent, ReactNode } from 'react';
import { CaretDownIcon } from '@/components/icons';
/**
* Combobox / select field. Shares the text-field chrome (`.field*`, see
* `Input`) so its rest / hover / focus / error states match, and reuses the
* `.dropdown-menu*` styling for the option list.
*
* Clicking or typing opens the menu; typing filters it. Selecting an option
* fills the field and closes the menu. `editable={false}` makes it select-only.
* `error` (a message) switches to the error styling and replaces `supportingText`.
*/
export interface ComboboxOption {
value: string;
label: string;
/** Optional 20px leading icon in the menu row. */
icon?: ReactNode;
}
interface ComboboxProps {
options: ComboboxOption[];
label?: string;
required?: boolean;
/** Help text under the field; hidden when `error` is present. */
supportingText?: ReactNode;
/** Error message; its presence switches the field to the error styling. */
error?: ReactNode;
placeholder?: string;
/** Selected value (uncontrolled). */
defaultValue?: string;
onChange?: (value: string) => void;
disabled?: boolean;
/** When false, the field is select-only (no type-to-filter). */
editable?: boolean;
id?: string;
/** Class for the outer `.field` wrapper. */
containerClassName?: string;
}
export function Combobox({
options,
label,
required,
supportingText,
error,
placeholder = 'Select an option…',
defaultValue,
onChange,
disabled,
editable = true,
id,
containerClassName,
}: ComboboxProps) {
const generatedId = useId();
const inputId = id ?? generatedId;
const listId = `${inputId}-list`;
const describedById = `${inputId}-desc`;
const hasDesc = Boolean(error || supportingText);
const [selected, setSelected] = useState<ComboboxOption | undefined>(() =>
options.find((o) => o.value === defaultValue),
);
const [query, setQuery] = useState(selected?.label ?? '');
const [open, setOpen] = useState(false);
const [activeIndex, setActiveIndex] = useState(0);
const rootRef = useRef<HTMLDivElement>(null);
const inputRef = useRef<HTMLInputElement>(null);
// Filter only while the query differs from the current selection.
const filtered = useMemo(() => {
const q = query.trim().toLowerCase();
if (!editable || q === '' || q === selected?.label.toLowerCase()) return options;
return options.filter((o) => o.label.toLowerCase().includes(q));
}, [options, query, editable, selected]);
// An outside click closes the menu and reverts the query to the selection.
useEffect(() => {
if (!open) return;
const onPointerDown = (e: MouseEvent) => {
if (rootRef.current && !rootRef.current.contains(e.target as Node)) {
setOpen(false);
setQuery(selected?.label ?? '');
}
};
document.addEventListener('mousedown', onPointerDown);
return () => document.removeEventListener('mousedown', onPointerDown);
}, [open, selected]);
const selectOption = (option: ComboboxOption) => {
setSelected(option);
setQuery(option.label);
setOpen(false);
onChange?.(option.value);
};
const openMenu = () => {
Iif (disabled) return;
setOpen(true);
setActiveIndex(0);
};
const handleKeyDown = (e: KeyboardEvent<HTMLInputElement>) => {
switch (e.key) {
case 'ArrowDown':
e.preventDefault();
if (!open) openMenu();
else setActiveIndex((i) => Math.min(filtered.length - 1, i + 1));
break;
case 'ArrowUp':
e.preventDefault();
setActiveIndex((i) => Math.max(0, i - 1));
break;
case 'Enter':
Eif (open && filtered[activeIndex]) {
e.preventDefault();
selectOption(filtered[activeIndex]);
}
break;
case 'Escape':
Eif (open) {
e.preventDefault();
setOpen(false);
setQuery(selected?.label ?? '');
}
break;
case 'Tab':
setOpen(false);
break;
}
};
const activeOptionId = open && filtered[activeIndex] ? `${inputId}-opt-${activeIndex}` : undefined;
return (
<div className={['field', containerClassName].filter(Boolean).join(' ')} ref={rootRef}>
{label && (
<label className="field__label" htmlFor={inputId}>
{label}
{required && (
<span className="field__required" aria-hidden="true">
*
</span>
)}
</label>
)}
<div className={open ? 'combobox is-open' : 'combobox'}>
<div className={error ? 'field__box field__box--error' : 'field__box'}>
<input
id={inputId}
ref={inputRef}
className="field__control"
type="text"
role="combobox"
aria-expanded={open}
aria-controls={listId}
aria-autocomplete={editable ? 'list' : 'none'}
aria-activedescendant={activeOptionId}
aria-invalid={error ? true : undefined}
aria-describedby={hasDesc ? describedById : undefined}
placeholder={placeholder}
value={query}
required={required}
disabled={disabled}
readOnly={!editable}
onClick={openMenu}
onChange={(e) => {
setQuery(e.target.value);
setOpen(true);
setActiveIndex(0);
}}
onKeyDown={handleKeyDown}
/>
<button
type="button"
className="field__adornment combobox__caret"
tabIndex={-1}
aria-label={open ? 'Close options' : 'Open options'}
disabled={disabled}
// Keep focus on the input so the field keeps its focus styling.
onMouseDown={(e) => e.preventDefault()}
onClick={() => {
if (open) {
setOpen(false);
} else {
openMenu();
inputRef.current?.focus();
}
}}
>
<CaretDownIcon />
</button>
</div>
{open && (
<ul className="dropdown-menu combobox__menu" role="listbox" id={listId}>
{filtered.length === 0 && (
<li className="combobox__empty" role="presentation">
No matches
</li>
)}
{filtered.map((option, i) => (
<li
key={option.value}
id={`${inputId}-opt-${i}`}
role="option"
aria-selected={i === activeIndex}
className={i === activeIndex ? 'dropdown-menu__item is-active' : 'dropdown-menu__item'}
onMouseEnter={() => setActiveIndex(i)}
// mousedown (not click) so the selection lands before the input blurs.
onMouseDown={(e) => {
e.preventDefault();
selectOption(option);
}}
>
{option.icon}
<span className="dropdown-menu__label">{option.label}</span>
</li>
))}
</ul>
)}
</div>
{error ? (
<span className="field__supporting field__supporting--error" id={describedById}>
{error}
</span>
) : supportingText ? (
<span className="field__supporting" id={describedById}>
{supportingText}
</span>
) : null}
</div>
);
}
|