"use client"; import React, { Children, type CSSProperties, type ReactElement, type ReactNode, forwardRef, useId, useState, useRef, useCallback, memo, useImperativeHandle, useEffect, useLayoutEffect, useMemo, } from "react"; import { useClickOutside } from "../../../hooks"; import { useTranslation } from "../../../contexts/MessagesContext"; import { SelectInputView } from "./SelectInput.view"; import type { SelectInputProps, SelectOptionData } from "./SelectInput.types"; /** * Figma: "Control / SelectInput". Custom-styled select dropdown * with a labelled trigger button and floating option menu. */ const SelectInputContainer = forwardRef( ( { id, labelText, showLabel, labelVariant: labelVariantProp, size: sizeProp, state: externalStateProp = "default", asterisk = false, iconHelp = true, textOptional = false, textData = true, iconRight = true, textHint = false, disabled = false, error = false, placeholder, className = "", children, value, onChange, options, ...props }, ref, ) => { const t = useTranslation("controlsChrome"); const resolvedPlaceholder = placeholder ?? t("selectPlaceholder"); // Determine if label should be shown const shouldShowLabel = showLabel !== undefined ? showLabel : labelText !== undefined; let normalizedState = externalStateProp; if (normalizedState === "state5" || normalizedState === "State5") { normalizedState = "default"; } const externalState = normalizedState; const _labelVariant = labelVariantProp; const _size = sizeProp; void _labelVariant; void _size; const generatedId = useId(); const selectId = id || `select-input-${generatedId}`; const labelId = `${selectId}-label`; const listboxId = `${selectId}-listbox`; const [isOpen, setIsOpen] = useState(false); const [selectedValue, setSelectedValue] = useState(value || ""); const [highlightedIndex, setHighlightedIndex] = useState(0); const [menuStyle, setMenuStyle] = useState(null); const selectRef = useRef(null); const menuRef = useRef(null); const optionItems = useMemo((): SelectOptionData[] => { if (options && Array.isArray(options)) return options; return Children.toArray(children).flatMap((child) => { if (!React.isValidElement(child) || child.type !== "option") return []; const optionProps = child.props as { value: string; children: ReactNode; }; return [ { value: optionProps.value, label: String(optionProps.children), }, ]; }); }, [options, children]); // Internal state management: track if focused and how (mouse vs keyboard) const [isFocused, setIsFocused] = useState(false); const [focusMethod, setFocusMethod] = useState<"mouse" | "keyboard" | null>( null, ); const wasMouseDownRef = useRef(false); // Determine if we should auto-manage focus (only when state is "default" or undefined) const shouldAutoManageFocus = externalState === "default" || externalState === undefined; // Sync internal state with external value prop useEffect(() => { if (value !== undefined && value !== selectedValue) { setSelectedValue(value); } // eslint-disable-next-line react-hooks/exhaustive-deps }, [value]); useImperativeHandle( ref, () => selectRef.current as HTMLButtonElement | null, ); const closeMenu = useCallback(() => { setIsOpen(false); setMenuStyle(null); }, []); // Handle click outside to close menu useClickOutside([menuRef, selectRef], closeMenu, isOpen); const indexForValue = useCallback( (current: string) => { const index = optionItems.findIndex((option) => option.value === current); return index >= 0 ? index : 0; }, [optionItems], ); const openMenu = useCallback(() => { const trigger = selectRef.current?.getBoundingClientRect(); setMenuStyle({ top: (trigger?.bottom ?? 0) + 4, left: trigger?.left ?? 0, width: Math.max(trigger?.width ?? 0, 200), }); setHighlightedIndex(indexForValue(selectedValue)); setIsOpen(true); }, [indexForValue, selectedValue]); useLayoutEffect(() => { if (!isOpen) { setMenuStyle(null); return; } const update = () => { const trigger = selectRef.current; if (!trigger) return; const rect = trigger.getBoundingClientRect(); const menuHeight = menuRef.current?.offsetHeight ?? optionItems.length * 44 + 8; const gap = 4; const openUp = rect.bottom + gap + menuHeight > window.innerHeight && rect.top > menuHeight + gap; setMenuStyle({ top: openUp ? Math.max(8, rect.top - menuHeight - gap) : rect.bottom + gap, left: rect.left, width: Math.max(rect.width, 200), }); }; update(); window.addEventListener("resize", update); window.addEventListener("scroll", update, true); return () => { window.removeEventListener("resize", update); window.removeEventListener("scroll", update, true); }; }, [isOpen, optionItems.length, highlightedIndex]); // Handle option selection const handleOptionSelect = useCallback( (optionValue: string, optionText: string) => { setSelectedValue(optionValue); closeMenu(); if (onChange) { onChange({ target: { value: optionValue, text: optionText } }); } if (selectRef.current) { selectRef.current.focus(); } }, [closeMenu, onChange], ); // Handle mouse down to detect mouse clicks const handleMouseDown = useCallback(() => { if (!disabled && shouldAutoManageFocus) { wasMouseDownRef.current = true; } }, [disabled, shouldAutoManageFocus]); // Handle select button click const handleSelectClick = useCallback(() => { if (disabled) return; if (isOpen) { closeMenu(); return; } openMenu(); }, [closeMenu, disabled, isOpen, openMenu]); // Handle keyboard navigation const handleKeyDown = useCallback( (e: React.KeyboardEvent) => { if (disabled) return; if (e.key === "ArrowDown") { e.preventDefault(); if (!isOpen) { openMenu(); return; } setHighlightedIndex((index) => Math.min(index + 1, Math.max(optionItems.length - 1, 0)), ); return; } if (e.key === "ArrowUp") { e.preventDefault(); if (!isOpen) { openMenu(); return; } setHighlightedIndex((index) => Math.max(index - 1, 0)); return; } if (e.key === "Home" && isOpen) { e.preventDefault(); setHighlightedIndex(0); return; } if (e.key === "End" && isOpen) { e.preventDefault(); setHighlightedIndex(Math.max(optionItems.length - 1, 0)); return; } if (e.key === "Enter" || e.key === " ") { e.preventDefault(); if (!isOpen) { openMenu(); return; } const option = optionItems[highlightedIndex]; if (option) { handleOptionSelect(option.value, option.label); } return; } if (e.key === "Escape") { closeMenu(); } }, [ closeMenu, disabled, handleOptionSelect, highlightedIndex, isOpen, openMenu, optionItems, ], ); // Handle focus to detect mouse vs keyboard const handleFocus = useCallback(() => { if (disabled) return; const method = wasMouseDownRef.current ? "mouse" : "keyboard"; if (shouldAutoManageFocus) { setIsFocused(true); setFocusMethod(method); wasMouseDownRef.current = false; } }, [disabled, shouldAutoManageFocus]); // Handle blur const handleBlur = useCallback(() => { if (shouldAutoManageFocus) { setIsFocused(false); setFocusMethod(null); wasMouseDownRef.current = false; } }, [shouldAutoManageFocus]); // Determine actual state: // - Active: when clicked (mouse focus) or when dropdown is open // - Focus: when tabbed (keyboard focus) // - Default: when not focused const actualState = shouldAutoManageFocus ? isOpen || isFocused ? focusMethod === "mouse" || isOpen ? "active" : "focus" : "default" : externalState; // Determine if select is filled (has selected value) const isFilled = Boolean(selectedValue && selectedValue.trim().length > 0); // Get display text for selected value const getDisplayText = (): string => { if (!selectedValue) return resolvedPlaceholder; if (options && Array.isArray(options)) { const selectedOption = options.find( (option) => option.value === selectedValue, ); return selectedOption ? selectedOption.label : resolvedPlaceholder; } const selectedOption = Children.toArray(children).find( ( child, ): child is ReactElement<{ value: string; children: ReactNode; }> => { if (!React.isValidElement(child)) return false; const props = child.props as { value?: string; children?: ReactNode; }; return props.value === selectedValue; }, ); return selectedOption ? String(selectedOption.props.children) : resolvedPlaceholder; }; return ( ); }, ); SelectInputContainer.displayName = "SelectInput"; export default memo(SelectInputContainer);