260813_01_FST: First Commit
This commit is contained in:
220
src/components/common/multi-select/MultiSelect.tsx
Normal file
220
src/components/common/multi-select/MultiSelect.tsx
Normal file
@@ -0,0 +1,220 @@
|
||||
'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<T>(
|
||||
{
|
||||
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',
|
||||
defaultSearchValue = '',
|
||||
onSearchValueChange,
|
||||
emptyIndicator = '검색 결과가 없습니다.',
|
||||
autoSize = false,
|
||||
singleLine = false,
|
||||
popoverClassName,
|
||||
disabled = false,
|
||||
responsive,
|
||||
minWidth,
|
||||
maxWidth,
|
||||
deduplicateOptions: shouldDeduplicate = false,
|
||||
resetOnDefaultValueChange = true,
|
||||
closeOnSelect = false,
|
||||
preventDeselect = false,
|
||||
hideOptionCheck = false,
|
||||
style,
|
||||
...buttonProps
|
||||
}: MultiSelectProps<T>,
|
||||
ref: React.ForwardedRef<MultiSelectRef>,
|
||||
) {
|
||||
const [selectedValues, setSelectedValues] = React.useState<string[]>(defaultValue)
|
||||
const [searchValue, setSearchValue] = React.useState(defaultSearchValue)
|
||||
const [open, setOpen] = React.useState(false)
|
||||
const buttonRef = React.useRef<HTMLButtonElement>(null)
|
||||
const [triggerWidth, setTriggerWidth] = React.useState<number>()
|
||||
|
||||
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<string, MultiSelectOption<T>>()
|
||||
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<T> => 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<T>) => {
|
||||
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 (
|
||||
<Popover open={open} onOpenChange={setOpen} modal={modalPopover}>
|
||||
<PopoverTrigger asChild>
|
||||
<MultiSelectTrigger
|
||||
ref={buttonRef}
|
||||
selectedOptions={selectedOptions}
|
||||
placeholder={placeholder}
|
||||
maxCount={responsiveSettings.maxCount}
|
||||
compactMode={responsiveSettings.compactMode}
|
||||
hideIcons={responsiveSettings.hideIcons}
|
||||
singleLine={singleLine}
|
||||
preventDeselect={preventDeselect}
|
||||
variant={variant}
|
||||
spanClassName={spanClassName}
|
||||
badgeClassName={badgeClassName}
|
||||
onRemove={(value) => emit(selectedValues.filter((selected) => selected !== value))}
|
||||
onClear={() => emit([])}
|
||||
className={cn(autoSize && 'w-auto', className)}
|
||||
disabled={disabled}
|
||||
style={{ minWidth, maxWidth, ...style }}
|
||||
{...buttonProps}
|
||||
/>
|
||||
</PopoverTrigger>
|
||||
<PopoverContent
|
||||
align="start"
|
||||
className={cn('w-[var(--radix-popover-trigger-width)] min-w-64 p-0', popoverClassName)}
|
||||
style={{ width: triggerWidth ? `${triggerWidth}px` : undefined }}
|
||||
>
|
||||
<MultiSelectContent
|
||||
options={options}
|
||||
selectedValues={selectedValues}
|
||||
searchable={searchable}
|
||||
searchMode={searchMode}
|
||||
searchValue={searchValue}
|
||||
onSearchValueChange={handleSearchChange}
|
||||
hideSelectAll={hideSelectAll}
|
||||
hideOptionCheck={hideOptionCheck}
|
||||
selectionMode={selectionMode}
|
||||
emptyIndicator={emptyIndicator}
|
||||
onToggleOption={toggleOption}
|
||||
onToggleAll={toggleAll}
|
||||
/>
|
||||
</PopoverContent>
|
||||
</Popover>
|
||||
)
|
||||
}
|
||||
|
||||
const ForwardedMultiSelect = React.forwardRef(MultiSelectInner) as <T = unknown>(
|
||||
props: MultiSelectProps<T> & { ref?: React.ForwardedRef<MultiSelectRef> },
|
||||
) => React.ReactElement
|
||||
|
||||
export const MultiSelect = ForwardedMultiSelect
|
||||
Reference in New Issue
Block a user