import { useEffect, useMemo, useRef, useState, forwardRef, type KeyboardEvent, type FocusEvent as ReactFocusEvent, type ReactNode, } from 'react' import { createPortal } from 'react-dom' import { ChevronDown, ChevronUp, X } from 'lucide-react' import { cn } from '@/lib/cn' import { omit } from '@/lib/omit' import { useClickOutside } from '@/lib/useClickOutside' import { useDropdownPosition, type DropdownPlacement } from '@/lib/useDropdownPosition' import { Spinner } from './Spinner' import { Tooltip } from './Tooltip' import type { SelectOption } from './NativeSelect' import { FLOATING_LABEL_SIZES, LABEL_SIZES, SELECT_SIZES, SELECT_THEME_CLASSES, SELECT_VARIANTS, SELECT_WIDTHS, type SelectSize, type SelectTheme, type SelectVariant, type SelectWidth, } from './select.tokens' /** * Custom select with a portalled dropdown, search, and a floating label. * * Ported from the source app's `Select/components/FeaturedSelect`. * * Two upstream bugs are corrected here, both flagged in comments at the point of * change: the themed classes were built as template strings (so Tailwind emitted * no rules for them), and a "cleared but still matching option" value kept the * control looking filled. */ export type FeaturedSelectProps = Omit< React.HTMLAttributes, 'onChange' | 'onSelect' | 'defaultValue' | 'placeholder' > & { options?: SelectOption[] value?: string onChange?: (value: string) => void label?: string name?: string placeholder?: string size?: SelectSize theme?: SelectTheme variant?: SelectVariant width?: SelectWidth disabled?: boolean required?: boolean error?: string | { message?: string } isLoading?: boolean isClearable?: boolean searchable?: boolean onSearchChange?: (term: string) => void /** Scrolls the selected option to the middle of the open list. */ scrollToSelected?: boolean placement?: DropdownPlacement /** Stored label for a value whose option has not loaded yet. */ initialSearchTerm?: string /** Floats the label even when the control is empty and unfocused. */ shrink?: boolean floatinglabelClass?: string tooltip?: string tooltipIcon?: React.ComponentProps['icon'] helpText?: string actionButton?: { label: string; onClick: () => void; icon?: ReactNode } renderOption?: (opt: SelectOption) => ReactNode onBlur?: (e: ReactFocusEvent) => void } export const FeaturedSelect = forwardRef( function FeaturedSelect( { options = [], value = '', onChange, label, name, placeholder = 'Select an option', size = 'md', theme = 'primary', variant = 'outlined', width = 'full', disabled = false, required = false, error, isLoading = false, isClearable = true, searchable = true, onSearchChange, scrollToSelected = false, placement = 'auto', initialSearchTerm = '', shrink = false, floatinglabelClass = '', tooltip, tooltipIcon, helpText, actionButton, renderOption, className = '', onBlur, ...props }, ref, ) { const htmlProps = omit(props as Record, [ 'shrink', 'hasMore', 'hasMoreKey', 'labelKey', 'valueKey', 'isMulti', 'staticOptions', 'endpoint', 'endpointParams', 'infiniteScroll', 'initialSearch', 'initialSearchTerm', 'initialQuery', 'searchBy', 'control', 'onMenuScroll', 'debounceTime', 'helpText', 'tooltip', 'tooltipIcon', 'isClearable', 'renderOption', 'onBlur', ]) const [isOpen, setIsOpen] = useState(false) const [isFocused, setIsFocused] = useState(false) const [searchTerm, setSearchTerm] = useState(initialSearchTerm) // `initialSearchTerm` is the stored label for the ONE value the field was // seeded with, so it stops being true the moment the user picks something // else. Tracking it beats comparing against `value`, because the seeded value // and its label arrive over several renders. const [hasUserSelected, setHasUserSelected] = useState(false) const containerRef = useRef(null) const dropdownRef = useRef(null) useEffect(() => { if (initialSearchTerm) setSearchTerm(initialSearchTerm) // A new seed means a new record in the same mounted field (the next row // opened in a reused modal): the earlier pick no longer describes it. setHasUserSelected(false) }, [initialSearchTerm]) useEffect(() => { const node = containerRef.current if (typeof ref === 'function') ref(node) else if (ref) ref.current = node }, [ref]) // React's onBlur is focusout and bubbles. Opening the dropdown moves focus to // its autoFocus search input, which would otherwise read as a blur to the // consumer — validating a field the user has only just clicked into. The // dropdown is portalled, so it is not a descendant of containerRef: check // both roots. const handleContainerBlur = (event: ReactFocusEvent) => { if (!onBlur) return const next = event.relatedTarget if ( next instanceof Node && (containerRef.current?.contains(next) || dropdownRef.current?.contains(next)) ) { return } onBlur(event) } const safeOptions = Array.isArray(options) ? options : [] const selectedOption = safeOptions.find((opt) => opt.value === value) const hasSelectedValue = value !== undefined && value !== null && value !== '' // Prefer the resolved option; fall back to the caller-supplied label for a // value whose option has not been fetched yet. const displayLabel = selectedOption?.label || (hasSelectedValue && !hasUserSelected ? initialSearchTerm : '') || '' const filteredOptions = useMemo(() => { // A server-side search hands us the filtered list; don't filter again. if (onSearchChange) return safeOptions return searchable && searchTerm ? safeOptions.filter((opt) => opt.label.toLowerCase().includes(searchTerm.toLowerCase())) : safeOptions }, [safeOptions, searchable, searchTerm, onSearchChange]) // A long list opens at the top, leaving the current value scrolled out of // sight. Centred rather than 'nearest', which would pin the option to the // bottom edge with no surrounding years visible. useEffect(() => { if (!isOpen || !scrollToSelected) return const frame = requestAnimationFrame(() => { const list = dropdownRef.current const selected = list?.querySelector('[data-selected="true"]') selected?.scrollIntoView?.({ block: 'center' }) }) return () => cancelAnimationFrame(frame) }, [isOpen, scrollToSelected]) useClickOutside( [containerRef, dropdownRef], () => { setIsOpen(false) setIsFocused(false) }, isOpen, ) const { dropdownPosition, calculateInitialPosition } = useDropdownPosition( isOpen, containerRef, { placement }, ) const handleToggle = () => { if (disabled) return if (!isOpen) calculateInitialPosition() setIsOpen((open) => !open) } const handleSelect = (val: string) => { onChange?.(val) setHasUserSelected(true) setIsOpen(false) setIsFocused(false) } // Derived from `value` alone. The source OR'd in the matched option, so an // option whose own value is '' (an "All departments" filter) kept the control // looking filled after the value was cleared — the field showed a label and a // clear button while the form held '', so a required field read as answered. const hasValue = hasSelectedValue // `displayLabel`, not `hasValue`: the all-pass option resolves to a label and // renders as text, so floating on hasValue alone left the label sitting on // top of that text. `required` floats too — a mandatory field's label carries // the asterisk and help icon, which read as content inside the box, and an // unfloated one leaves a column of required fields misaligned (Taiga #4140). const isFloating = shrink || hasValue || Boolean(displayLabel) || isFocused || isOpen || Boolean(error) || required const isUnderlined = variant === 'underlined' const themeClasses = SELECT_THEME_CLASSES[theme] ?? SELECT_THEME_CLASSES.primary const errorMessage = typeof error === 'string' ? error : error?.message // The floated label is a chip sitting on the border, which only reads against // a boxed outline. On the underlined variant there is no side border to punch // through, so lift it clear and drop the chip styling. const labelClass = isFloating ? cn( isUnderlined ? '-top-2.5 px-0 bg-transparent z-10' : 'top-[-0.6rem] px-1 bg-white z-10', FLOATING_LABEL_SIZES[size] ?? FLOATING_LABEL_SIZES.md, errorMessage ? 'text-red-500' : themeClasses.label, floatinglabelClass, ) : cn( 'top-1/2 -translate-y-1/2', LABEL_SIZES[size] ?? LABEL_SIZES.md, 'text-slate-400 pointer-events-none', ) const dropdownContent = (
{searchable && (
{ const next = e.target.value setSearchTerm(next) onSearchChange?.(next) }} onClick={(e) => e.stopPropagation()} />
)} {filteredOptions.length > 0 ? ( filteredOptions.map((opt) => { const isSelected = opt.value === value return (
!opt.disabled && handleSelect(opt.value)} > {renderOption ? renderOption(opt) : opt.label}
) }) ) : ( !isLoading && (
No options found
) )} {isLoading && filteredOptions.length > 0 && (
LOADING MORE...
)} {actionButton && (
)}
) return (
) => { if (e.key === 'Enter') handleToggle() if (e.key === 'Escape') setIsOpen(false) }} onBlur={handleContainerBlur} {...htmlProps} >
{/* Options load asynchronously (paginated + server-searched), so a saved value is often absent from `options` on first paint. `initialSearchTerm` carries the stored label for exactly that case — without it the field renders blank even though a value is set. */} {displayLabel || placeholder}
{isLoading && } {isClearable && hasValue && !disabled && ( { e.stopPropagation() // onSearchChange first, so a consumer that sets its own term // inside onChange still wins. onSearchChange?.('') onChange?.('') setSearchTerm('') setHasUserSelected(true) }} /> )} {isOpen ? ( ) : ( )}
{label && ( )}
{isOpen && !disabled && createPortal(dropdownContent, document.body)} {errorMessage && (

{errorMessage}

)}
) }, ) export default FeaturedSelect