207 lines
7.8 KiB
TypeScript
207 lines
7.8 KiB
TypeScript
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<HTMLInputElement>) => {
|
||
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<HTMLDivElement>(null)
|
||
React.useEffect(() => {
|
||
if (!popover.open) return
|
||
// Не scrollIntoView: тот прокрутил бы и страницу под попапом.
|
||
requestAnimationFrame(() =>
|
||
columns.current?.querySelectorAll<HTMLElement>("[data-anchor=true]").forEach((el) => {
|
||
const list = el.parentElement!
|
||
list.scrollTop = el.offsetTop - (list.clientHeight - el.offsetHeight) / 2
|
||
}),
|
||
)
|
||
}, [popover.open])
|
||
|
||
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="чч:мм"
|
||
disabled={disabled}
|
||
aria-label={ariaLabel}
|
||
value={text}
|
||
aria-invalid={invalid || Boolean(shownError)}
|
||
onChange={change}
|
||
onBlur={() => setTouched(true)}
|
||
onKeyDown={popover.onKeyDown}
|
||
className="tabular"
|
||
/>
|
||
<InputGroupAddon align="inline-end">
|
||
<InputGroupButton
|
||
size="icon-xs"
|
||
aria-label="Выбрать время"
|
||
disabled={disabled}
|
||
ref={popover.toggleRef}
|
||
onClick={popover.toggle}
|
||
>
|
||
<ClockIcon />
|
||
</InputGroupButton>
|
||
</InputGroupAddon>
|
||
</InputGroup>
|
||
</PopoverAnchor>
|
||
<PopoverContent align="end" collisionPadding={8} className="w-44 p-0" {...popover.contentProps}>
|
||
<div className="grid grid-cols-2 border-b text-center text-xs text-muted-foreground">
|
||
<span className="py-1.5">Часы</span>
|
||
<span className="py-1.5">Минуты</span>
|
||
</div>
|
||
<div ref={columns} className="grid h-52 grid-cols-2 divide-x">
|
||
<Column label="Часы" items={HOURS} selected={hour} anchor={hour || nowHour} onPick={(h) => set(`${h}:${minute || "00"}`, false)} />
|
||
<Column
|
||
label="Минуты"
|
||
items={minutes}
|
||
selected={minute}
|
||
anchor={minute || nowMinute}
|
||
onPick={(m) => set(`${hour || nowTime(step).slice(0, 2)}:${m}`, true)}
|
||
/>
|
||
</div>
|
||
<div className="grid grid-cols-2 gap-1 border-t p-1.5">
|
||
<Button size="sm" variant="ghost" onClick={() => set("", true)} disabled={!value && !text}>
|
||
Очистить
|
||
</Button>
|
||
<Button size="sm" variant="secondary" onClick={() => set(nowTime(step), true)}>
|
||
Сейчас
|
||
</Button>
|
||
</div>
|
||
</PopoverContent>
|
||
</Popover>
|
||
)
|
||
}
|
||
|
||
/** Колонка часов или минут; края затухают, чтобы обрезанные строки не выглядели оборванными. */
|
||
function Column({
|
||
label,
|
||
items,
|
||
selected,
|
||
anchor,
|
||
onPick,
|
||
}: {
|
||
label: string
|
||
items: readonly string[]
|
||
selected: string
|
||
/** Строка, которая встаёт в середину при открытии. */
|
||
anchor: string
|
||
onPick: (item: string) => void
|
||
}) {
|
||
return (
|
||
<div
|
||
role="listbox"
|
||
aria-label={label}
|
||
// Поля сверху и снизу на полколонки: в середину встаёт любая строка, даже 00 и 23.
|
||
className="scrollbar-none relative flex flex-col gap-px overflow-y-auto px-1 py-[90px] [mask-image:linear-gradient(to_bottom,transparent,black_16px,black_calc(100%-16px),transparent)]"
|
||
>
|
||
{items.map((item) => (
|
||
<button
|
||
key={item}
|
||
type="button"
|
||
role="option"
|
||
aria-selected={item === selected}
|
||
data-selected={item === selected}
|
||
data-anchor={item === anchor}
|
||
onClick={() => onPick(item)}
|
||
className={cn(
|
||
"h-7 shrink-0 rounded-md text-sm tabular transition outline-none hover:bg-accent focus-visible:ring-[3px] focus-visible:ring-ring/50",
|
||
item === selected && "bg-primary font-medium text-primary-foreground hover:bg-primary",
|
||
)}
|
||
>
|
||
{item}
|
||
</button>
|
||
))}
|
||
</div>
|
||
)
|
||
}
|