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 = ({ value, options, onChange, ariaLabel, disabled = false, variant = 'default' }) => { const triggerRef = useRef(null); const menuRef = useRef(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('button[role="option"]')[highlight]?.focus(); }, [highlight, open, position]); return <> {open && position && createPortal(<> )} , document.body)} ; };