// src/components/ui/Select.jsx // Fully-styled custom select — replaces the native ) // placeholder — shown when value is empty (default: 'Select…') // disabled — boolean // className — extra classes on the trigger button // id — forwarded for label association // name — forwarded (unused visually, kept for form semantics) import { useState, useRef, useEffect, Children, isValidElement } from 'react' import { createPortal } from 'react-dom' import { computeFloatingMenuPosition } from '@/lib/floatingMenuPosition' // Parse React for now — could be added later }) return opts } export default function Select({ value, onChange, children, placeholder = 'Select…', disabled = false, className = '', id, name, ...props }) { const [open, setOpen] = useState(false) const [menuPos, setMenuPos] = useState({ top: 0, left: 0, width: 0, maxHeight: 280 }) const triggerRef = useRef(null) const menuRef = useRef(null) const options = parseOptions(children) const selected = options.find(o => o.value === String(value ?? '')) // ── Close on outside click / scroll ──────────────────────────────────────── useEffect(() => { if (!open) return function close(e) { if (triggerRef.current?.contains(e.target)) return if (menuRef.current?.contains(e.target)) return setOpen(false) } function closeOnScroll(e) { if (menuRef.current?.contains(e.target)) return if (triggerRef.current?.contains(e.target)) return setOpen(false) } document.addEventListener('mousedown', close) document.addEventListener('scroll', closeOnScroll, true) return () => { document.removeEventListener('mousedown', close) document.removeEventListener('scroll', closeOnScroll, true) } }, [open]) // ── Keyboard navigation ──────────────────────────────────────────────────── function handleKeyDown(e) { if (disabled) return const curr = options.findIndex(o => o.value === String(value ?? '')) if (e.key === 'Enter' || e.key === ' ') { e.preventDefault() if (!open) { openMenu() } else { setOpen(false) } } else if (e.key === 'Escape') { setOpen(false) triggerRef.current?.focus() } else if (e.key === 'ArrowDown' || e.key === 'ArrowUp') { e.preventDefault() const dir = e.key === 'ArrowDown' ? 1 : -1 let next = curr + dir // Skip disabled while (next >= 0 && next < options.length && options[next].disabled) { next += dir } if (next >= 0 && next < options.length) { onChange?.({ target: { value: options[next].value, name } }) } } } function openMenu() { if (disabled) return if (triggerRef.current) { setMenuPos(computeFloatingMenuPosition(triggerRef.current.getBoundingClientRect())) } setOpen(true) } function handleToggle() { if (open) { setOpen(false) } else { openMenu() } } function handleSelect(opt) { if (opt.disabled) return onChange?.({ target: { value: opt.value, name } }) setOpen(false) triggerRef.current?.focus() } const menu = open && createPortal(
{options.map(opt => (
{ e.preventDefault(); handleSelect(opt) }} > {opt.value === String(value ?? '') && ( )} {opt.label}
))}
, document.body ) return ( <> {menu} ) }