'use client' import * as React from 'react' import { Popover, PopoverContent, PopoverTrigger } from '@/components/ui/popover' import { cn } from '@/lib/utils' import { MultiSelectContent } from './MultiSelectContent' import { MultiSelectTrigger } from './MultiSelectTrigger' import type { MultiSelectOption, MultiSelectProps, MultiSelectRef } from './types' import { arraysEqual, deduplicateOptions, flattenOptions } from './utils' import { useResponsiveSettings } from './use-responsive-settings' function MultiSelectInner( { options: rawOptions, onValueChange, onOptionChange, onInfoChange, defaultValue = [], stickySelectedOptions = [], onStickySelectedOptionsChange, placeholder = 'Select options', maxCount = 3, maxSelected, selectionMode = 'multiple', modalPopover = false, variant = 'default', className, spanClassName, badgeClassName, hideSelectAll = false, searchable = true, searchMode = 'filter', resetScrollOnSearch = false, defaultSearchValue = '', onSearchValueChange, emptyIndicator = '검색 결과가 없습니다.', autoSize = false, singleLine = false, popoverClassName, disabled = false, responsive, minWidth, maxWidth, deduplicateOptions: shouldDeduplicate = false, resetOnDefaultValueChange = true, closeOnSelect = false, preventDeselect = false, hideOptionCheck = false, optionTooltip, optionTooltipClassName, style, ...buttonProps }: MultiSelectProps, ref: React.ForwardedRef, ) { const [selectedValues, setSelectedValues] = React.useState(defaultValue) const [searchValue, setSearchValue] = React.useState(defaultSearchValue) const [open, setOpen] = React.useState(false) const buttonRef = React.useRef(null) const [triggerWidth, setTriggerWidth] = React.useState() const options = React.useMemo( () => (shouldDeduplicate ? deduplicateOptions(rawOptions) : rawOptions), [rawOptions, shouldDeduplicate], ) const flatOptions = React.useMemo(() => flattenOptions(options), [options]) const responsiveSettings = useResponsiveSettings(responsive, maxCount) const optionMap = React.useMemo(() => { const map = new Map>() for (const option of stickySelectedOptions) map.set(option.value, option) for (const option of flatOptions) map.set(option.value, option) return map }, [flatOptions, stickySelectedOptions]) const selectedOptions = React.useMemo( () => selectedValues.map((value) => optionMap.get(value) ?? { value, label: value }), [optionMap, selectedValues], ) const emit = React.useCallback( (next: string[]) => { setSelectedValues(next) onValueChange(next) const nextOptions = next.map((value) => optionMap.get(value) ?? { value, label: value }) onOptionChange?.(nextOptions) onInfoChange?.( nextOptions.flatMap((option) => (option.info === undefined ? [] : [option.info])), ) }, [onInfoChange, onOptionChange, onValueChange, optionMap], ) React.useEffect(() => { if (!resetOnDefaultValueChange || arraysEqual(defaultValue, selectedValues)) return setSelectedValues(defaultValue) }, [defaultValue, resetOnDefaultValueChange, selectedValues]) React.useEffect(() => { if (!onStickySelectedOptionsChange) return const refreshed = selectedValues .map((value) => optionMap.get(value)) .filter((option): option is MultiSelectOption => Boolean(option)) onStickySelectedOptionsChange(refreshed) }, [onStickySelectedOptionsChange, optionMap, selectedValues]) React.useEffect(() => { const element = buttonRef.current if (!element || !('ResizeObserver' in window)) return const update = () => setTriggerWidth(Math.round(element.getBoundingClientRect().width)) update() const observer = new ResizeObserver(update) observer.observe(element) return () => observer.disconnect() }, []) React.useImperativeHandle( ref, () => ({ reset: () => { emit(defaultValue) setSearchValue(defaultSearchValue) setOpen(false) }, getSelectedValues: () => selectedValues, setSelectedValues: emit, clear: () => emit([]), focus: () => buttonRef.current?.focus(), }), [defaultSearchValue, defaultValue, emit, selectedValues], ) const toggleOption = React.useCallback( (option: MultiSelectOption) => { if (option.disabled) return const selected = selectedValues.includes(option.value) if (selected) { if (preventDeselect) return emit(selectedValues.filter((value) => value !== option.value)) return } if (selectionMode === 'single') { emit([option.value]) if (closeOnSelect) setOpen(false) return } if (maxSelected !== undefined && selectedValues.length >= maxSelected) return emit([...selectedValues, option.value]) if (closeOnSelect) setOpen(false) }, [closeOnSelect, emit, maxSelected, preventDeselect, selectedValues, selectionMode], ) const toggleAll = React.useCallback(() => { const values = flatOptions.filter((option) => !option.disabled).map((option) => option.value) const allSelected = values.length > 0 && values.every((value) => selectedValues.includes(value)) if (allSelected) { if (!preventDeselect) emit([]) return } emit(maxSelected === undefined ? values : values.slice(0, maxSelected)) }, [emit, flatOptions, maxSelected, preventDeselect, selectedValues]) const handleSearchChange = (value: string) => { setSearchValue(value) onSearchValueChange?.(value) } return ( emit(selectedValues.filter((selected) => selected !== value))} onClear={() => emit([])} className={cn(autoSize && 'w-auto', className)} disabled={disabled} style={{ minWidth, maxWidth, ...style }} {...buttonProps} /> ) } const ForwardedMultiSelect = React.forwardRef(MultiSelectInner) as ( props: MultiSelectProps & { ref?: React.ForwardedRef }, ) => React.ReactElement export const MultiSelect = ForwardedMultiSelect