import { useCallback, useRef, useState } from "react"; import { useIsFocused, useLivingRef } from "../../utils"; import type { SelectProps } from "."; export const useSelect = ({ value, onValueChange, defaultValue, options, }: Pick) => { const contentRef = useLivingRef(null); const [localUncontrolledValue, setLocalValue] = useState(defaultValue); const theValue = value ?? localUncontrolledValue; const triggerRef = useRef(null); const { isFocused } = useIsFocused(triggerRef); const isFilled = isFocused || Boolean(theValue); const handleOnValChange = useCallback( (val: string) => { if (value == null) { setLocalValue(val); } onValueChange?.(val); }, [onValueChange, value] ); const selectedOption = options.find((option) => option.value === theValue); return { handleOnValChange, isFilled, triggerRef, selectedOption, contentRef }; };