129 lines
4.8 KiB
TypeScript
129 lines
4.8 KiB
TypeScript
import React, { useEffect, useRef, useState } from 'react';
|
|
import { createPortal } from 'react-dom';
|
|
import { CheckMockIcon, ChevronDownMockIcon } from './MockupIcons';
|
|
|
|
export type SelectOption = { value: string; label: string };
|
|
|
|
interface SelectProps {
|
|
value: string;
|
|
options: SelectOption[];
|
|
onChange: (value: string) => void;
|
|
ariaLabel: string;
|
|
disabled?: boolean;
|
|
variant?: 'default' | 'field' | 'mobile';
|
|
}
|
|
|
|
/** Custom listbox used instead of the browser's native select. */
|
|
export const Select: React.FC<SelectProps> = ({ value, options, onChange, ariaLabel, disabled = false, variant = 'default' }) => {
|
|
const triggerRef = useRef<HTMLButtonElement>(null);
|
|
const menuRef = useRef<HTMLDivElement>(null);
|
|
const [open, setOpen] = useState(false);
|
|
const [position, setPosition] = useState<{ top: number; left: number; width: number } | null>(null);
|
|
const selected = options.find((option) => option.value === value);
|
|
const selectedIndex = Math.max(0, options.findIndex((option) => option.value === value));
|
|
const [highlight, setHighlight] = useState(selectedIndex);
|
|
|
|
const move = (delta: number) => {
|
|
if (!options.length) return;
|
|
setHighlight((current) => (current + delta + options.length) % options.length);
|
|
};
|
|
|
|
const closeMenu = (restoreFocus = false) => {
|
|
setOpen(false);
|
|
if (restoreFocus) triggerRef.current?.focus();
|
|
};
|
|
|
|
const place = () => {
|
|
const trigger = triggerRef.current;
|
|
if (!trigger) return;
|
|
const rect = trigger.getBoundingClientRect();
|
|
const width = Math.max(rect.width, 160);
|
|
const height = Math.min(options.length * 40 + 12, 260);
|
|
setPosition({
|
|
top: Math.max(12, Math.min(rect.bottom + 6, window.innerHeight - height - 12)),
|
|
left: Math.max(12, Math.min(rect.left, window.innerWidth - width - 12)),
|
|
width,
|
|
});
|
|
};
|
|
|
|
const toggle = () => {
|
|
if (disabled) return;
|
|
if (!open) {
|
|
place();
|
|
setHighlight(selectedIndex);
|
|
}
|
|
setOpen((current) => !current);
|
|
};
|
|
|
|
useEffect(() => {
|
|
if (!open) return;
|
|
const close = () => closeMenu();
|
|
const onKey = (event: KeyboardEvent) => { if (event.key === 'Escape') closeMenu(true); };
|
|
window.addEventListener('resize', close);
|
|
window.addEventListener('scroll', close, true);
|
|
document.addEventListener('keydown', onKey);
|
|
return () => {
|
|
window.removeEventListener('resize', close);
|
|
window.removeEventListener('scroll', close, true);
|
|
document.removeEventListener('keydown', onKey);
|
|
};
|
|
}, [open]);
|
|
|
|
useEffect(() => {
|
|
if (!open || !position) return;
|
|
menuRef.current?.querySelectorAll<HTMLButtonElement>('button[role="option"]')[highlight]?.focus();
|
|
}, [highlight, open, position]);
|
|
|
|
return <>
|
|
<button
|
|
ref={triggerRef}
|
|
type="button"
|
|
className={`select-trigger${variant !== 'default' ? ` ${variant}` : ''}`}
|
|
disabled={disabled}
|
|
aria-haspopup="listbox"
|
|
aria-expanded={open}
|
|
aria-label={ariaLabel}
|
|
onClick={toggle}
|
|
onKeyDown={(event) => {
|
|
if (event.key === 'ArrowDown' || event.key === 'ArrowUp') {
|
|
event.preventDefault();
|
|
if (!open) {
|
|
place();
|
|
setHighlight(selectedIndex);
|
|
setOpen(true);
|
|
} else {
|
|
move(event.key === 'ArrowDown' ? 1 : -1);
|
|
}
|
|
}
|
|
if (event.key === 'Escape' && open) {
|
|
event.preventDefault();
|
|
closeMenu();
|
|
}
|
|
}}
|
|
>
|
|
<span className="select-value">{selected?.label ?? ''}</span>
|
|
<ChevronDownMockIcon className="ph" />
|
|
</button>
|
|
{open && position && createPortal(<>
|
|
<button type="button" className="menu-scrim" aria-label="Fechar lista" onClick={() => closeMenu(true)} />
|
|
<div
|
|
ref={menuRef}
|
|
className="select-menu"
|
|
role="listbox"
|
|
aria-label={ariaLabel}
|
|
style={{ top: position.top, left: position.left, width: position.width }}
|
|
onKeyDown={(event) => {
|
|
if (event.key === 'ArrowDown') { event.preventDefault(); move(1); }
|
|
else if (event.key === 'ArrowUp') { event.preventDefault(); move(-1); }
|
|
else if (event.key === 'Home') { event.preventDefault(); setHighlight(0); }
|
|
else if (event.key === 'End') { event.preventDefault(); setHighlight(options.length - 1); }
|
|
else if (event.key === 'Escape') { event.preventDefault(); event.stopPropagation(); closeMenu(true); }
|
|
else if (event.key === 'Tab') { closeMenu(); }
|
|
}}
|
|
>
|
|
{options.map((option, index) => <button key={option.value} type="button" role="option" aria-selected={option.value === value} tabIndex={-1} onFocus={() => setHighlight(index)} onClick={() => { onChange(option.value); closeMenu(true); }}><span>{option.label}</span>{option.value === value && <CheckMockIcon className="ph" />}</button>)}
|
|
</div>
|
|
</>, document.body)}
|
|
</>;
|
|
};
|