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

83 lines
2.3 KiB
TypeScript

"use client";
import {CalendarIcon, X} from "lucide-react";
import {Button} from "@/components/ui/button";
import {Calendar} from "@/components/ui/calendar";
import {Popover, PopoverContent, PopoverTrigger} from "@/components/ui/popover";
import {cn} from "@/lib/utils";
const parseDate = (value: string) => {
if (!value) return undefined
const [year, month, day] = value.split('-').map(Number)
if (!year || !month || !day) return undefined
const date = new Date(year, month - 1, day)
if (date.getFullYear() !== year || date.getMonth() !== month - 1 || date.getDate() !== day) {
return undefined
}
return date
}
const formatDate = (date: Date | undefined) => {
if (!date) return ''
const year = date.getFullYear()
const month = String(date.getMonth() + 1).padStart(2, '0')
const day = String(date.getDate()).padStart(2, '0')
return `${year}-${month}-${day}`
}
export function KriDatePicker({
value,
onChange,
placeholder = "날짜 선택",
className,
}: {
value: string;
onChange: (value: string) => void;
placeholder?: string;
className?: string;
}) {
const selected = parseDate(value);
return (
<div className={cn("relative", className)}>
<Popover>
<PopoverTrigger asChild>
<Button
type="button"
variant="outline"
className={cn("h-9 w-full justify-start bg-white pr-8 text-left font-normal", !value && "text-muted-foreground")}
>
<CalendarIcon className="h-4 w-4" />
{selected ? formatDate(selected) : placeholder}
</Button>
</PopoverTrigger>
<PopoverContent className="w-auto p-0" align="start">
<Calendar
mode="single"
selected={selected}
onSelect={(date) => onChange(date ? formatDate(date) : "")}
/>
</PopoverContent>
</Popover>
{value && (
<button
type="button"
className="absolute right-2 top-1/2 inline-flex h-5 w-5 -translate-y-1/2 items-center justify-center rounded-full text-muted-foreground hover:bg-muted hover:text-foreground"
onClick={(event) => {
event.stopPropagation();
onChange("");
}}
aria-label="날짜 초기화"
>
<X className="h-3.5 w-3.5" />
</button>
)}
</div>
);
}