Files
contact-front/src/components/common/KriSelect.tsx

123 lines
3.1 KiB
TypeScript

'use client'
import * as React from 'react'
import type { CSSProperties } from 'react'
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from '@/components/ui/select'
import { cn } from '@/lib/utils'
export type KriSelectItem = {
value: string
label: string
}
export type KriSelectRef = {
focus: () => void
}
export type KriSelectProps<T> = {
items: T[]
value: string
onChange?: (value: string) => void
onChangeOption?: (option: T) => void
placeholder?: string
className?: string
heightClassName?: string
triggerTextClassName?: string
contentClassName?: string
itemClassName?: string
getValue?: (item: T) => string
getLabel?: (item: T) => string
useAll?: boolean
disabled?: boolean
'aria-invalid'?: boolean
}
const HEIGHT_CLASS_VALUE: Record<string, CSSProperties['height']> = {
'h-6': '1.5rem',
'h-7': '1.75rem',
'h-8': '2rem',
'h-9': '2.25rem',
'h-10': '2.5rem',
}
function KriSelectInner<T>(
{
items,
value,
onChange,
onChangeOption,
placeholder,
className,
heightClassName,
triggerTextClassName,
contentClassName,
itemClassName,
getValue,
getLabel,
useAll = true,
disabled,
'aria-invalid': ariaInvalid,
}: KriSelectProps<T>,
forwardedRef: React.ForwardedRef<KriSelectRef>,
) {
const triggerRef = React.useRef<HTMLButtonElement>(null)
React.useImperativeHandle(
forwardedRef,
() => ({
focus: () => triggerRef.current?.focus(),
}),
[],
)
const extractValue = (item: T) => (getValue ? getValue(item) : String(item))
const extractLabel = (item: T) => (getLabel ? getLabel(item) : String(item))
const triggerStyle: CSSProperties | undefined = heightClassName
? { height: HEIGHT_CLASS_VALUE[heightClassName] ?? undefined }
: undefined
return (
<Select
value={value}
disabled={disabled}
onValueChange={(selectedValue) => {
onChange?.(selectedValue)
const selected = items.find((item) => extractValue(item) === selectedValue)
if (selected) {
onChangeOption?.(selected)
}
}}
>
<SelectTrigger
ref={triggerRef}
className={cn('w-fit whitespace-nowrap bg-white', triggerTextClassName, heightClassName, className)}
style={triggerStyle}
aria-label={placeholder ?? 'select'}
aria-invalid={ariaInvalid}
>
<SelectValue placeholder={placeholder} />
</SelectTrigger>
<SelectContent className={contentClassName}>
{useAll ? (
<SelectItem value="ALL" className={itemClassName}>
전체
</SelectItem>
) : null}
{items.map((item, index) => {
const itemValue = extractValue(item)
const label = extractLabel(item)
return (
<SelectItem key={itemValue || index} value={itemValue} className={itemClassName}>
{label}
</SelectItem>
)
})}
</SelectContent>
</Select>
)
}
export const KriSelect = React.forwardRef(KriSelectInner) as <T = unknown>(
props: KriSelectProps<T> & { ref?: React.ForwardedRef<KriSelectRef> },
) => React.ReactElement