|
| 1 | +import { useState } from 'react' |
| 2 | + |
| 3 | +import { IcCaretDown, IcCaretUp } from '@/assets/IconList' |
| 4 | +import clsx from 'clsx' |
| 5 | + |
| 6 | +import { Box } from '@/components/common/containers' |
| 7 | +import { Dropdown, useDropdownContext } from '@/components/common/dropdown' |
| 8 | + |
| 9 | +type Options = { |
| 10 | + label: string |
| 11 | + value: string |
| 12 | +} |
| 13 | + |
| 14 | +interface SelectProps { |
| 15 | + options: Options[] |
| 16 | + value: string |
| 17 | + onChange: (value: string) => void |
| 18 | + placeholder?: string |
| 19 | + disabled?: boolean |
| 20 | +} |
| 21 | +export const Select = ({ |
| 22 | + options, |
| 23 | + value, |
| 24 | + onChange, |
| 25 | + placeholder = 'Select an option', |
| 26 | + disabled = false, |
| 27 | +}: SelectProps): JSX.Element => { |
| 28 | + const [selectedLabel, setSelectedLabel] = useState( |
| 29 | + options.find(option => option.value === value)?.label || '' |
| 30 | + ) |
| 31 | + |
| 32 | + const handleSelect = (value: string, label: string) => { |
| 33 | + onChange(value) |
| 34 | + setSelectedLabel(label) |
| 35 | + } |
| 36 | + |
| 37 | + return ( |
| 38 | + <Dropdown> |
| 39 | + <Dropdown.Trigger |
| 40 | + className={clsx('w-210', { |
| 41 | + 'pointer-events-none cursor-not-allowed': disabled, |
| 42 | + })} |
| 43 | + aria-disabled={disabled} |
| 44 | + > |
| 45 | + <DropdownTriggerBox |
| 46 | + selectedLabel={selectedLabel || placeholder} |
| 47 | + selected={!!selectedLabel} |
| 48 | + disabled={disabled} |
| 49 | + /> |
| 50 | + </Dropdown.Trigger> |
| 51 | + <Dropdown.Menu> |
| 52 | + {options.map(option => ( |
| 53 | + <Dropdown.Item |
| 54 | + key={option.value} |
| 55 | + onClick={() => handleSelect(option.value, option.label)} |
| 56 | + > |
| 57 | + {option.label} |
| 58 | + </Dropdown.Item> |
| 59 | + ))} |
| 60 | + </Dropdown.Menu> |
| 61 | + </Dropdown> |
| 62 | + ) |
| 63 | +} |
| 64 | + |
| 65 | +const DropdownTriggerBox = ({ |
| 66 | + selectedLabel, |
| 67 | + disabled, |
| 68 | + selected, |
| 69 | +}: { |
| 70 | + selectedLabel: string |
| 71 | + disabled: boolean |
| 72 | + selected: boolean |
| 73 | +}) => { |
| 74 | + const { isOpen } = useDropdownContext() |
| 75 | + return ( |
| 76 | + <Box |
| 77 | + className={clsx( |
| 78 | + 'h-48 justify-between p-12 text-body1 font-medium text-gray-500 focus:border-primary-normal', |
| 79 | + { 'text-gray-800': selected }, |
| 80 | + { 'bg-gray-200 text-gray-400': disabled } |
| 81 | + )} |
| 82 | + rounded={8} |
| 83 | + > |
| 84 | + {selectedLabel} |
| 85 | + {isOpen ? <IcCaretUp /> : <IcCaretDown />} |
| 86 | + </Box> |
| 87 | + ) |
| 88 | +} |
0 commit comments