medkit/src/kit/date-range-input.tsx

206 lines
8.4 KiB
TypeScript
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

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<HTMLInputElement>) => {
popover.returnFocus.current = e.currentTarget
}
return (
<Popover open={popover.open} onOpenChange={popover.setOpen}>
<PopoverAnchor asChild>
<InputGroup data-disabled={disabled} className={cn("w-fit", className)}>
<InputGroupInput
ref={popover.returnFocus}
aria-label="С"
inputMode="numeric"
autoComplete="off"
placeholder="дд.мм.гггг"
disabled={disabled}
value={fromField.text}
aria-invalid={invalid || reversed || Boolean(fromField.shownError)}
onChange={fromField.change}
onBlur={fromField.onBlur}
onFocus={remember}
onKeyDown={popover.onKeyDown}
className={input}
/>
<InputGroupText className="px-0.5">—</InputGroupText>
<InputGroupInput
aria-label="По"
inputMode="numeric"
autoComplete="off"
placeholder="дд.мм.гггг"
disabled={disabled}
value={toField.text}
aria-invalid={invalid || reversed || Boolean(toField.shownError)}
onChange={toField.change}
onBlur={toField.onBlur}
onFocus={remember}
onKeyDown={popover.onKeyDown}
className={input}
/>
<InputGroupAddon align="inline-end">
<InputGroupButton
size="icon-xs"
aria-label="Открыть календарь"
disabled={disabled}
ref={popover.toggleRef}
onClick={popover.toggle}
>
<CalendarRangeIcon />
</InputGroupButton>
</InputGroupAddon>
</InputGroup>
</PopoverAnchor>
<PopoverContent align="start" collisionPadding={8} className="flex w-auto max-w-[calc(100vw-1rem)] flex-col p-0 md:flex-row" {...popover.contentProps}>
{presets.length > 0 && (
<div className="flex gap-1 overflow-x-auto border-b p-2 md:w-44 md:flex-col md:border-r md:border-b-0">
{presets.map((preset) => {
const range = preset.range(today)
const active = isSameDay(range.from, value.from) && isSameDay(range.to, value.to)
return (
<Button
key={preset.label}
size="sm"
variant={active ? "secondary" : "ghost"}
className="shrink-0 justify-start font-normal"
onClick={() => {
apply(range)
popover.setOpen(false)
}}
>
{preset.label}
</Button>
)
})}
</div>
)}
<div className="flex flex-col">
<Calendar
mode="range"
autoFocus
numberOfMonths={wide ? 2 : 1}
showOutsideDays={!wide}
selected={{ from: value.from ?? undefined, to: value.to ?? undefined }}
month={popover.month}
onMonthChange={popover.setMonth}
onSelect={(_, day) => pickDay(startOfDay(day))}
{...calendarBounds(limits, "label")}
/>
<div className="flex items-center justify-between gap-2 border-t p-2">
<span className="px-2 text-xs text-muted-foreground">
{value.from && !value.to ? "Выберите дату окончания" : rangeLength(value)}
</span>
<Button
size="sm"
variant="ghost"
onClick={() => apply({ from: null, to: null })}
disabled={!value.from && !value.to && !fromField.text && !toField.text}
>
Очистить
</Button>
</div>
</div>
</PopoverContent>
</Popover>
)
}
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}`
}