"use client" import * as React from "react" import { CalendarIcon } from "lucide-react" import type { Matcher } from "react-day-picker" import { Button } from "@/app/components/ui/button" import { Calendar } from "@/app/components/ui/calendar" import { Input } from "@/app/components/ui/input" import { Popover, PopoverAnchor, PopoverContent, PopoverTrigger } from "@/app/components/ui/popover" import { dateToIso, formatDmy, isoToDate } from "@/app/lib/date-input" import { cn } from "@/app/lib/utils" import { useT } from "@/app/lib/i18n/MessagesProvider" type DmyInputProps = Omit, "value" | "onChange" | "type" | "readOnly"> & { value: string onOpen: () => void } const OPEN_KEYS = new Set(["Enter", " ", "ArrowDown"]) /** Read-only box showing DD/MM/YYYY; the calendar is the only way to change the value. */ function DmyInput({ value, onOpen, placeholder, className, ...props }: DmyInputProps) { const t = useT() // text-sm at every width: Input's mobile text-base cut "DD/MM/YYYY" in the 120px range boxes; read-only, so no iOS zoom. return ( { if (!props.disabled && OPEN_KEYS.has(e.key)) { e.preventDefault() onOpen() } }} /> ) } /** Year-dropdown range and disabled days for a min/max pair ("yyyy-MM-dd"). */ function calendarBounds(min?: string, max?: string) { const minDate = min ? isoToDate(min) : undefined const maxDate = max ? isoToDate(max) : undefined const disabled: Matcher[] = [] if (minDate) disabled.push({ before: minDate }) if (maxDate) disabled.push({ after: maxDate }) return { startMonth: minDate ?? new Date(1920, 0), endMonth: maxDate ?? new Date(new Date().getFullYear() + 10, 11), disabled, } } interface DatePickerProps { value: string onChange: (iso: string) => void id?: string "aria-label"?: string "aria-labelledby"?: string "aria-invalid"?: boolean "aria-describedby"?: string required?: boolean disabled?: boolean min?: string max?: string placeholder?: string className?: string } function DatePicker({ value, onChange, required, min, max, className, ...inputProps }: DatePickerProps) { const t = useT() const [open, setOpen] = React.useState(false) const anchorRef = React.useRef(null) const selected = isoToDate(value) const bounds = calendarBounds(min, max) const label = inputProps["aria-label"] const labelledby = inputProps["aria-labelledby"] const buttonId = React.useId() return (
setOpen(true)} className="h-full pr-12" />
{ // The boxes sit in PopoverAnchor, outside the content, so radix treats a click on them // as outside and closes; keep it open (the box re-opens, the icon still toggles). if (anchorRef.current?.contains(e.target as Node)) e.preventDefault() }}> { if (!d) return // clicking the selected day again deselects; keep the value onChange(dateToIso(d)) setOpen(false) }} /> {!required ? (
) : null}
) } export { DatePicker, DmyInput, calendarBounds } export type { DatePickerProps }