73 lines
2.7 KiB
TypeScript
73 lines
2.7 KiB
TypeScript
import { XIcon } from "lucide-react"
|
||
|
||
import { cn } from "../lib/utils"
|
||
|
||
export interface TimeRangeValue {
|
||
from: string
|
||
to: string
|
||
}
|
||
|
||
/**
|
||
* Диапазон времени «с–по» в одну строку; подсвечивается, если «по» не позже «с».
|
||
* С `overnight` «по» раньше «с» — переход через полночь (21:00–00:00), ошибка только при «с» = «по».
|
||
*/
|
||
export function TimeRangeInput({
|
||
value,
|
||
onChange,
|
||
onRemove,
|
||
overnight = false,
|
||
className,
|
||
}: {
|
||
value: TimeRangeValue
|
||
onChange: (value: TimeRangeValue) => void
|
||
onRemove?: () => void
|
||
/** Разрешить интервал через полночь: «по» раньше «с» не считается ошибкой. */
|
||
overnight?: boolean
|
||
className?: string
|
||
}) {
|
||
const invalid = Boolean(
|
||
value.from && value.to && (overnight ? value.to === value.from : value.to <= value.from),
|
||
)
|
||
// Ширина ровно под «ЧЧ:ММ»: моноширинный шрифт, без иконки часов и внутренних отступов браузера.
|
||
const input =
|
||
"h-6 w-[calc(5ch+12px)] rounded bg-transparent px-[3px] font-mono text-xs tabular outline-none focus:bg-accent/60 [&::-webkit-calendar-picker-indicator]:hidden [&::-webkit-datetime-edit]:p-0 [&::-webkit-datetime-edit-fields-wrapper]:p-0"
|
||
|
||
return (
|
||
<div
|
||
aria-invalid={invalid}
|
||
className={cn(
|
||
"group relative inline-flex w-fit items-center rounded-md border bg-card px-0.5 transition focus-within:border-primary/50",
|
||
invalid && "border-destructive/60 bg-destructive/5",
|
||
className,
|
||
)}
|
||
>
|
||
<input
|
||
type="time"
|
||
aria-label="С"
|
||
value={value.from}
|
||
onChange={(e) => onChange({ ...value, from: e.target.value })}
|
||
className={input}
|
||
/>
|
||
<span className="text-2xs text-muted-foreground">–</span>
|
||
<input
|
||
type="time"
|
||
aria-label="По"
|
||
value={value.to}
|
||
onChange={(e) => onChange({ ...value, to: e.target.value })}
|
||
className={input}
|
||
/>
|
||
{onRemove && (
|
||
<button
|
||
type="button"
|
||
aria-label="Удалить время"
|
||
onClick={onRemove}
|
||
// Крестик не занимает места: появляется поверх правого верхнего угла при наведении.
|
||
className="absolute -top-1.5 -right-1.5 grid size-4 place-items-center rounded-full border bg-card text-muted-foreground opacity-0 shadow-xs transition group-hover:opacity-100 hover:text-destructive focus-visible:opacity-100"
|
||
>
|
||
<XIcon className="size-2.5" />
|
||
</button>
|
||
)}
|
||
</div>
|
||
)
|
||
}
|