import * as React from "react" import { CalendarRangeIcon } from "lucide-react" import { Button } from "@/components/ui/button" import { Calendar } from "@/components/ui/calendar" import { InputGroup, InputGroupAddon, InputGroupButton, InputGroupInput, InputGroupText } from "@/components/ui/input-group" import { Popover, PopoverAnchor, PopoverContent } from "@/components/ui/popover" import { useMediaQuery } from "@/hooks/use-media-query" import { isSameDay } from "@/lib/masks" import { cn } from "@/lib/utils" import { calendarBounds, startOfDay, useCalendarPopover, useDateText, type DateLimits } from "./date-input" export interface DateRangeValue { from: Date | null to: Date | null } export interface DateRangePreset { label: string range: (today: Date) => DateRangeValue } const shift = (date: Date, days: number) => new Date(date.getFullYear(), date.getMonth(), date.getDate() + days) export const DEFAULT_RANGE_PRESETS: readonly DateRangePreset[] = [ { label: "Сегодня", range: (t) => ({ from: t, to: t }) }, { label: "Вчера", range: (t) => ({ from: shift(t, -1), to: shift(t, -1) }) }, { label: "Последние 7 дней", range: (t) => ({ from: shift(t, -6), to: t }) }, { label: "Последние 30 дней", range: (t) => ({ from: shift(t, -29), to: t }) }, { label: "Этот месяц", range: (t) => ({ from: new Date(t.getFullYear(), t.getMonth(), 1), to: new Date(t.getFullYear(), t.getMonth() + 1, 0) }) }, { label: "Прошлый месяц", range: (t) => ({ from: new Date(t.getFullYear(), t.getMonth() - 1, 1), to: new Date(t.getFullYear(), t.getMonth(), 0) }) }, { label: "Этот год", range: (t) => ({ from: new Date(t.getFullYear(), 0, 1), to: new Date(t.getFullYear(), 11, 31) }) }, ] /** «с» позже «по» — диапазон перевёрнут. */ export function isRangeReversed({ from, to }: DateRangeValue) { return Boolean(from && to && from > to) } /** * Период «с — по»: обе даты вводятся вручную по маске или выбираются в календаре * на два месяца с быстрыми периодами слева. Первый клик — начало, второй — конец. */ export function DateRangeInput({ value, onChange, min, max, presets = DEFAULT_RANGE_PRESETS, invalid, onErrorChange, disabled, className, }: DateLimits & { value: DateRangeValue onChange: (value: DateRangeValue) => void /** Пустой массив — без быстрых периодов. */ presets?: readonly DateRangePreset[] invalid?: boolean /** Сообщение о неправильном вводе (в том числе перевёрнутом диапазоне) — для FormField. */ onErrorChange?: (error: string | undefined) => void disabled?: boolean className?: string }) { const wide = useMediaQuery("(min-width: 768px)") const limits = { min, max } const fromField = useDateText(value.from, (from) => onChange({ ...value, from }), limits) const toField = useDateText(value.to, (to) => onChange({ ...value, to }), limits) const reversed = isRangeReversed(value) const today = startOfDay(new Date()) const popover = useCalendarPopover(() => value.from ?? (wide ? shift(today, -today.getDate()) : today)) const error = fromField.shownError ?? toField.shownError ?? (reversed ? "Дата окончания раньше начала" : undefined) const reportError = React.useEffectEvent((message: string | undefined) => onErrorChange?.(message)) React.useEffect(() => reportError(error), [error]) const apply = (next: DateRangeValue) => { fromField.set(next.from, false) toField.set(next.to, false) onChange(next) } const pickDay = (day: Date) => { const { from, to } = value if (!from || to) return apply({ from: day, to: null }) apply(day < from ? { from: day, to: from } : { from, to: day }) popover.setOpen(false) } const input = "w-[6.6rem] flex-none px-2.5 tabular" // Фокус после закрытия календаря возвращается в то поле, где человек был последним. const remember = (e: React.FocusEvent) => { popover.returnFocus.current = e.currentTarget } return ( — {presets.length > 0 && (
{presets.map((preset) => { const range = preset.range(today) const active = isSameDay(range.from, value.from) && isSameDay(range.to, value.to) return ( ) })}
)}
pickDay(startOfDay(day))} {...calendarBounds(limits, "label")} />
{value.from && !value.to ? "Выберите дату окончания" : rangeLength(value)}
) } function rangeLength({ from, to }: DateRangeValue) { if (!from || !to || from > to) return "" const days = Math.round((to.getTime() - from.getTime()) / 86_400_000) + 1 const mod10 = days % 10 const mod100 = days % 100 const word = mod10 === 1 && mod100 !== 11 ? "день" : mod10 >= 2 && mod10 <= 4 && (mod100 < 12 || mod100 > 14) ? "дня" : "дней" return `${days} ${word}` }