Files
front-ui-registry/registry/components/KriDateRangePicker.tsx

121 lines
3.4 KiB
TypeScript

'use client'
import { useRef } from 'react'
import { CalendarDays, X } from 'lucide-react'
import { Button } from '@/components/ui/button'
import { Input } from '@/components/ui/input'
import { Label } from '@/components/ui/label'
import { Popover, PopoverContent, PopoverTrigger } from '@/components/ui/popover'
import { cn } from '@/lib/utils'
export type KriDateRange = {
from: string
to: string
}
export type KriDateRangePickerProps = {
value: KriDateRange
onChange: (value: KriDateRange) => void
placeholder?: string
className?: string
triggerClassName?: string
contentClassName?: string
disabled?: boolean
}
export function KriDateRangePicker({
value,
onChange,
placeholder = '조회 기간 선택',
className,
triggerClassName,
contentClassName,
disabled = false,
}: KriDateRangePickerProps) {
const toInputRef = useRef<HTMLInputElement | null>(null)
const displayText = value.from && value.to
? `${value.from} ~ ${value.to}`
: value.from
? `${value.from} ~`
: value.to
? `~ ${value.to}`
: placeholder
const hasValue = value.from.length > 0 || value.to.length > 0
const invalidRange = value.from.length > 0 && value.to.length > 0 && value.from > value.to
const focusAndOpenToDate = () => {
const input = toInputRef.current
if (!input) return
input.focus()
const inputWithPicker = input as HTMLInputElement & { showPicker?: () => void }
inputWithPicker.showPicker?.()
if (!inputWithPicker.showPicker) {
input.click()
}
}
return (
<div className={cn('flex items-center gap-2', className)}>
<Popover>
<PopoverTrigger asChild>
<Button
type="button"
variant="outline"
disabled={disabled}
className={cn('justify-start min-w-[260px] font-normal', triggerClassName)}
>
<CalendarDays className="w-4 h-4" />
<span className="truncate">{displayText}</span>
</Button>
</PopoverTrigger>
<PopoverContent align="start" className={cn('w-[360px] space-y-3', contentClassName)}>
<Label className="font-semibold">조회 기간</Label>
<div className="flex items-center gap-2">
<Input
type="date"
value={value.from}
onChange={(e) => {
const nextFrom = e.target.value
onChange({ ...value, from: nextFrom })
if (nextFrom) {
requestAnimationFrame(() => {
focusAndOpenToDate()
})
}
}}
/>
<span className="text-sm text-muted-foreground">~</span>
<Input
ref={toInputRef}
type="date"
value={value.to}
onChange={(e) => onChange({ ...value, to: e.target.value })}
/>
</div>
{invalidRange && (
<p className="text-xs text-red-600">조회 시작일은 종료일보다 이후일 수 없습니다.</p>
)}
</PopoverContent>
</Popover>
<Button
type="button"
variant="ghost"
size="icon-sm"
onClick={() => onChange({ from: '', to: '' })}
disabled={disabled || !hasValue}
aria-label="조회 기간 초기화"
>
<X className="w-4 h-4" />
</Button>
</div>
)
}
export default KriDateRangePicker