234 lines
8.9 KiB
TypeScript
234 lines
8.9 KiB
TypeScript
import * as React from "react"
|
||
import { CalendarIcon } from "lucide-react"
|
||
|
||
import { Button } from "../ui/button"
|
||
import { Calendar } from "../ui/calendar"
|
||
import { InputGroup, InputGroupAddon, InputGroupButton, InputGroupInput } from "../ui/input-group"
|
||
import { Popover, PopoverAnchor, PopoverContent } from "../ui/popover"
|
||
import { formatRuDate, isDatePrefixValid, isSameDay, maskDate, maskWithCaret, parseRuDate } from "../lib/masks"
|
||
import { useCaret } from "../hooks/use-caret"
|
||
import { cn } from "../lib/utils"
|
||
|
||
export interface DateLimits {
|
||
min?: Date
|
||
max?: Date
|
||
}
|
||
|
||
/** Почему введённый текст не стал датой; undefined — всё в порядке (или поле пустое). */
|
||
export function dateTextError(text: string, { min, max }: DateLimits = {}) {
|
||
if (!text) return undefined
|
||
if (text.length < 10) return "Дата в формате дд.мм.гггг"
|
||
const date = parseRuDate(text)
|
||
if (!date) return "Такой даты нет"
|
||
if (min && date < startOfDay(min)) return `Не раньше ${formatRuDate(min)}`
|
||
if (max && date > startOfDay(max)) return `Не позже ${formatRuDate(max)}`
|
||
return undefined
|
||
}
|
||
|
||
export function startOfDay(date: Date) {
|
||
return new Date(date.getFullYear(), date.getMonth(), date.getDate())
|
||
}
|
||
|
||
/**
|
||
* Текст поля даты, связанный со значением: наружу уходит только допустимая дата
|
||
* (или null), а недописанный текст остаётся в поле, пока внешнее значение его не перебьёт.
|
||
*/
|
||
export function useDateText(value: Date | null, onChange: (date: Date | null) => void, limits: DateLimits = {}) {
|
||
const [text, setText] = React.useState(() => formatRuDate(value))
|
||
const [prev, setPrev] = React.useState(value)
|
||
const [touched, setTouched] = React.useState(false)
|
||
const setCaret = useCaret()
|
||
|
||
if (!isSameDay(prev, value)) {
|
||
setPrev(value)
|
||
const typed = dateTextError(text, limits) ? null : parseRuDate(text)
|
||
if (!isSameDay(typed, value)) setText(formatRuDate(value))
|
||
}
|
||
|
||
const change = (e: React.ChangeEvent<HTMLInputElement>) => {
|
||
const { value: next, caret } = maskWithCaret(
|
||
e.target,
|
||
(e.nativeEvent as InputEvent).inputType,
|
||
text,
|
||
maskDate,
|
||
isDatePrefixValid,
|
||
)
|
||
setText(next)
|
||
setCaret(e.target, caret)
|
||
const date = dateTextError(next, limits) ? null : parseRuDate(next)
|
||
if (!isSameDay(date, value)) onChange(date)
|
||
}
|
||
|
||
/** Выбор в календаре или очистка: текст переписывается сразу, даже если значение не изменилось. */
|
||
const set = (date: Date | null, emit = true) => {
|
||
setText(formatRuDate(date))
|
||
setTouched(false)
|
||
if (emit && !isSameDay(date, value)) onChange(date)
|
||
}
|
||
|
||
const error = dateTextError(text, limits)
|
||
// Неполную дату не ругаем, пока человек печатает.
|
||
const shownError = error && (touched || text.length === 10) ? error : undefined
|
||
|
||
return { text, change, set, error, shownError, onBlur: () => setTouched(true) }
|
||
}
|
||
|
||
/**
|
||
* Состояние попапа с календарём у поля ввода: при каждом открытии календарь показывает
|
||
* месяц текущего значения, а после закрытия (выбор, Esc, кнопка) фокус возвращается в поле —
|
||
* если только человек не кликнул куда-то ещё.
|
||
*/
|
||
export function useCalendarPopover(initialMonth: () => Date) {
|
||
const [open, setOpenState] = React.useState(false)
|
||
const [month, setMonth] = React.useState(initialMonth)
|
||
const returnFocus = React.useRef<HTMLInputElement>(null)
|
||
const toggleRef = React.useRef<HTMLButtonElement>(null)
|
||
const clickedOutside = React.useRef(false)
|
||
|
||
const setOpen = (next: boolean) => {
|
||
if (next && !open) {
|
||
setMonth(initialMonth())
|
||
clickedOutside.current = false
|
||
}
|
||
setOpenState(next)
|
||
}
|
||
|
||
const contentProps = {
|
||
onInteractOutside: (e: Event) => {
|
||
// Кнопка календаря сама закроет попап своим кликом, иначе он тут же откроется снова.
|
||
if (toggleRef.current?.contains(e.target as Node)) e.preventDefault()
|
||
else clickedOutside.current = true
|
||
},
|
||
onCloseAutoFocus: (e: Event) => {
|
||
e.preventDefault()
|
||
if (!clickedOutside.current) returnFocus.current?.focus()
|
||
},
|
||
}
|
||
|
||
const toggle = () => setOpen(!open)
|
||
|
||
/** Alt+↓ в поле открывает календарь. */
|
||
const onKeyDown = (e: React.KeyboardEvent<HTMLInputElement>) => {
|
||
if (e.altKey && e.key === "ArrowDown") {
|
||
e.preventDefault()
|
||
returnFocus.current = e.currentTarget
|
||
setOpen(true)
|
||
}
|
||
}
|
||
|
||
return { open, setOpen, toggle, toggleRef, month, setMonth, returnFocus, contentProps, onKeyDown }
|
||
}
|
||
|
||
export function calendarBounds({ min, max }: DateLimits, captionLayout: "label" | "dropdown") {
|
||
const disabled = [...(min ? [{ before: min }] : []), ...(max ? [{ after: max }] : [])]
|
||
return {
|
||
disabled: disabled.length ? disabled : undefined,
|
||
// В выпадающих списках годов нужны границы, иначе их не из чего строить.
|
||
startMonth: min ?? (captionLayout === "dropdown" ? new Date(1900, 0) : undefined),
|
||
endMonth: max ?? (captionLayout === "dropdown" ? new Date(new Date().getFullYear() + 10, 11) : undefined),
|
||
}
|
||
}
|
||
|
||
/**
|
||
* Дата: ввод вручную по маске «дд.мм.гггг» или выбор в календаре (кнопка, Alt+↓).
|
||
* captionLayout="dropdown" — месяц и год списками, удобно для даты рождения.
|
||
*/
|
||
export function DateInput({
|
||
value,
|
||
onChange,
|
||
min,
|
||
max,
|
||
invalid,
|
||
captionLayout = "label",
|
||
onErrorChange,
|
||
id,
|
||
disabled,
|
||
placeholder = "дд.мм.гггг",
|
||
className,
|
||
"aria-label": ariaLabel,
|
||
}: DateLimits & {
|
||
value: Date | null
|
||
onChange: (date: Date | null) => void
|
||
/** Подсветить извне (ошибка формы), вдобавок к собственной проверке. */
|
||
invalid?: boolean
|
||
captionLayout?: "label" | "dropdown"
|
||
/** Сообщение о неправильном вводе — чтобы показать его в FormField. */
|
||
onErrorChange?: (error: string | undefined) => void
|
||
id?: string
|
||
disabled?: boolean
|
||
placeholder?: string
|
||
className?: string
|
||
"aria-label"?: string
|
||
}) {
|
||
const field = useDateText(value, onChange, { min, max })
|
||
const bounds = calendarBounds({ min, max }, captionLayout)
|
||
const today = new Date()
|
||
const popover = useCalendarPopover(() => value ?? (max && max < today ? max : today))
|
||
|
||
const reportError = React.useEffectEvent((error: string | undefined) => onErrorChange?.(error))
|
||
React.useEffect(() => reportError(field.shownError), [field.shownError])
|
||
|
||
const pick = (date: Date | null) => {
|
||
field.set(date)
|
||
popover.setOpen(false)
|
||
}
|
||
|
||
const todayAllowed = !dateTextError(formatRuDate(today), { min, max })
|
||
|
||
return (
|
||
<Popover open={popover.open} onOpenChange={popover.setOpen}>
|
||
<PopoverAnchor asChild>
|
||
<InputGroup data-disabled={disabled} className={cn("w-full", className)}>
|
||
<InputGroupInput
|
||
ref={popover.returnFocus}
|
||
id={id}
|
||
inputMode="numeric"
|
||
autoComplete="off"
|
||
placeholder={placeholder}
|
||
disabled={disabled}
|
||
aria-label={ariaLabel}
|
||
value={field.text}
|
||
aria-invalid={invalid || Boolean(field.shownError)}
|
||
onChange={field.change}
|
||
onBlur={field.onBlur}
|
||
onKeyDown={popover.onKeyDown}
|
||
className="tabular"
|
||
/>
|
||
<InputGroupAddon align="inline-end">
|
||
<InputGroupButton
|
||
size="icon-xs"
|
||
aria-label="Открыть календарь"
|
||
disabled={disabled}
|
||
ref={popover.toggleRef}
|
||
onClick={popover.toggle}
|
||
>
|
||
<CalendarIcon />
|
||
</InputGroupButton>
|
||
</InputGroupAddon>
|
||
</InputGroup>
|
||
</PopoverAnchor>
|
||
<PopoverContent align="end" collisionPadding={8} className="w-auto p-0" {...popover.contentProps}>
|
||
<Calendar
|
||
mode="single"
|
||
required
|
||
autoFocus
|
||
captionLayout={captionLayout}
|
||
selected={value ?? undefined}
|
||
month={popover.month}
|
||
onMonthChange={popover.setMonth}
|
||
onSelect={pick}
|
||
{...bounds}
|
||
/>
|
||
<div className="flex justify-between gap-2 border-t p-2">
|
||
<Button size="sm" variant="ghost" onClick={() => pick(null)} disabled={!value && !field.text}>
|
||
Очистить
|
||
</Button>
|
||
<Button size="sm" variant="secondary" onClick={() => pick(startOfDay(today))} disabled={!todayAllowed}>
|
||
Сегодня
|
||
</Button>
|
||
</div>
|
||
</PopoverContent>
|
||
</Popover>
|
||
)
|
||
}
|