import * as React from "react" import { ClockIcon } from "lucide-react" import { Button } from "../ui/button" import { InputGroup, InputGroupAddon, InputGroupButton, InputGroupInput } from "../ui/input-group" import { Popover, PopoverAnchor, PopoverContent } from "../ui/popover" import { isTimePrefixValid, maskTime, maskWithCaret } from "../lib/masks" import { useCaret } from "../hooks/use-caret" import { cn } from "../lib/utils" import { useCalendarPopover } from "./date-input" const pad = (n: number) => String(n).padStart(2, "0") const HOURS = Array.from({ length: 24 }, (_, h) => pad(h)) /** Сейчас, округлённое вниз до шага минут. */ function nowTime(step: number) { const d = new Date() return `${pad(d.getHours())}:${pad(Math.floor(d.getMinutes() / step) * step)}` } /** * Время «чч:мм»: ввод вручную по маске или выбор часа и минут в двух колонках (кнопка, Alt+↓). * Наружу уходит только полное время или пустая строка — недописанное остаётся в поле. */ export function TimeInput({ value, onChange, step = 5, invalid, onErrorChange, id, disabled, className, "aria-label": ariaLabel, }: { /** «чч:мм» или "". */ value: string onChange: (value: string) => void /** Шаг минут в списке; вручную можно ввести любые. */ step?: number /** Подсветить извне (ошибка формы), вдобавок к собственной проверке. */ invalid?: boolean /** Сообщение о недописанном времени — чтобы показать его в FormField. */ onErrorChange?: (error: string | undefined) => void id?: string disabled?: boolean className?: string "aria-label"?: string }) { const [text, setText] = React.useState(value) const [prev, setPrev] = React.useState(value) const [touched, setTouched] = React.useState(false) const setCaret = useCaret() const popover = useCalendarPopover(() => new Date()) if (prev !== value) { setPrev(value) const typed = text.length === 5 ? text : "" if (typed !== value) setText(value) } const error = text && text.length < 5 ? "Время в формате чч:мм" : undefined const shownError = error && touched ? error : undefined const reportError = React.useEffectEvent((message: string | undefined) => onErrorChange?.(message)) React.useEffect(() => reportError(shownError), [shownError]) const change = (e: React.ChangeEvent) => { const next = maskWithCaret(e.target, (e.nativeEvent as InputEvent).inputType, text, maskTime, isTimePrefixValid) setText(next.value) setCaret(e.target, next.caret) const time = next.value.length === 5 ? next.value : "" if (time !== value) onChange(time) } const set = (time: string, close: boolean) => { setText(time) setTouched(false) if (time !== value) onChange(time) if (close) popover.setOpen(false) } const [hour, minute] = value ? value.split(":") : ["", ""] const minutes = Array.from({ length: Math.ceil(60 / step) }, (_, i) => pad(i * step)) // Введённые вручную минуты не по шагу тоже видны в списке — выбранными. if (minute && !minutes.includes(minute)) { minutes.push(minute) minutes.sort() } // При открытии выбранные час и минута — в середине колонок; без значения — текущее время. const [nowHour, nowMinute] = nowTime(step).split(":") const columns = React.useRef(null) React.useEffect(() => { if (!popover.open) return // Не scrollIntoView: тот прокрутил бы и страницу под попапом. requestAnimationFrame(() => columns.current?.querySelectorAll("[data-anchor=true]").forEach((el) => { const list = el.parentElement! list.scrollTop = el.offsetTop - (list.clientHeight - el.offsetHeight) / 2 }), ) }, [popover.open]) return ( setTouched(true)} onKeyDown={popover.onKeyDown} className="tabular" />
Часы Минуты
set(`${h}:${minute || "00"}`, false)} /> set(`${hour || nowTime(step).slice(0, 2)}:${m}`, true)} />
) } /** Колонка часов или минут; края затухают, чтобы обрезанные строки не выглядели оборванными. */ function Column({ label, items, selected, anchor, onPick, }: { label: string items: readonly string[] selected: string /** Строка, которая встаёт в середину при открытии. */ anchor: string onPick: (item: string) => void }) { return (
{items.map((item) => ( ))}
) }