Patient create form, /ui-form page with date and SNILS inputs, notify toasts
- Patients: create form with masks and validation, patients store - Kit: SnilsInput, DateInput (manual entry + calendar), DateRangeInput (two months, presets), Combobox, notify toasts - Date mask rejects impossible dates as you type (40.33, 31.04, 29.02.2027), pads 4 -> 04, overwrites digits in a full field, keeps the caret in place - shadcn Calendar on react-day-picker 9 with Russian locale - /ui-form showcase page, shared Showcase block, notify demo on /ui - Logo heartbeat animation on hover and click - .claude/launch.json with dev server configs Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
parent
13960689fd
commit
7ebaac8e1a
|
|
@ -0,0 +1,24 @@
|
||||||
|
import * as React from "react"
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Курсор для поля с маской: ставится сразу после того, как React применит новое значение
|
||||||
|
* (до отрисовки), и ещё раз в следующем кадре — на случай, если значение не изменилось
|
||||||
|
* и React просто вернул старое, уведя курсор в конец.
|
||||||
|
*/
|
||||||
|
export function useCaret() {
|
||||||
|
const pending = React.useRef<{ input: HTMLInputElement; caret: number } | null>(null)
|
||||||
|
|
||||||
|
React.useLayoutEffect(() => {
|
||||||
|
const p = pending.current
|
||||||
|
if (!p) return
|
||||||
|
pending.current = null
|
||||||
|
if (document.activeElement === p.input) p.input.setSelectionRange(p.caret, p.caret)
|
||||||
|
})
|
||||||
|
|
||||||
|
return React.useCallback((input: HTMLInputElement, caret: number) => {
|
||||||
|
pending.current = { input, caret }
|
||||||
|
requestAnimationFrame(() => {
|
||||||
|
if (document.activeElement === input && input.selectionStart !== caret) input.setSelectionRange(caret, caret)
|
||||||
|
})
|
||||||
|
}, [])
|
||||||
|
}
|
||||||
|
|
@ -0,0 +1,117 @@
|
||||||
|
import * as React from "react"
|
||||||
|
import { CheckIcon, ChevronDownIcon, PlusIcon, XIcon } from "lucide-react"
|
||||||
|
|
||||||
|
import { cn } from "@/lib/utils"
|
||||||
|
import { Command, CommandEmpty, CommandGroup, CommandInput, CommandItem, CommandList } from "@/components/ui/command"
|
||||||
|
import { Popover, PopoverContent, PopoverTrigger } from "@/components/ui/popover"
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Одиночный выбор из справочника с поиском и очисткой (как tui-combo-box).
|
||||||
|
* `creatable` — можно оставить своё значение, если в справочнике его нет.
|
||||||
|
*/
|
||||||
|
export function Combobox({
|
||||||
|
options,
|
||||||
|
value,
|
||||||
|
onChange,
|
||||||
|
placeholder = "Выберите",
|
||||||
|
searchPlaceholder = "Поиск…",
|
||||||
|
creatable = false,
|
||||||
|
disabled,
|
||||||
|
id,
|
||||||
|
className,
|
||||||
|
"aria-label": ariaLabel,
|
||||||
|
"aria-invalid": invalid,
|
||||||
|
}: {
|
||||||
|
options: readonly string[]
|
||||||
|
value: string
|
||||||
|
onChange: (value: string) => void
|
||||||
|
placeholder?: string
|
||||||
|
searchPlaceholder?: string
|
||||||
|
creatable?: boolean
|
||||||
|
disabled?: boolean
|
||||||
|
id?: string
|
||||||
|
className?: string
|
||||||
|
"aria-label"?: string
|
||||||
|
"aria-invalid"?: boolean
|
||||||
|
}) {
|
||||||
|
const [open, setOpen] = React.useState(false)
|
||||||
|
const [search, setSearch] = React.useState("")
|
||||||
|
const custom = search.trim()
|
||||||
|
const norm = (v: string) => v.toLowerCase().replace(/ё/g, "е")
|
||||||
|
// Фильтруем сами: так «Указать …» всегда последним, а Enter берёт первое совпадение из справочника.
|
||||||
|
const filtered = custom ? options.filter((o) => norm(o).includes(norm(custom))) : options
|
||||||
|
const canCreate = creatable && custom && !options.some((o) => norm(o) === norm(custom))
|
||||||
|
|
||||||
|
const pick = (next: string) => {
|
||||||
|
onChange(next)
|
||||||
|
setOpen(false)
|
||||||
|
setSearch("")
|
||||||
|
}
|
||||||
|
|
||||||
|
return (
|
||||||
|
<Popover open={open} onOpenChange={(v) => !disabled && setOpen(v)}>
|
||||||
|
<PopoverTrigger asChild>
|
||||||
|
<div
|
||||||
|
id={id}
|
||||||
|
role="combobox"
|
||||||
|
tabIndex={disabled ? -1 : 0}
|
||||||
|
aria-expanded={open}
|
||||||
|
aria-disabled={disabled}
|
||||||
|
aria-label={ariaLabel ?? placeholder}
|
||||||
|
aria-invalid={invalid}
|
||||||
|
onKeyDown={(e) => {
|
||||||
|
if (e.key === "Enter" || e.key === " " || e.key === "ArrowDown") {
|
||||||
|
e.preventDefault()
|
||||||
|
setOpen(true)
|
||||||
|
}
|
||||||
|
}}
|
||||||
|
className={cn(
|
||||||
|
"flex h-9 w-full cursor-pointer items-center gap-1.5 rounded-md border border-input bg-transparent px-3 text-sm shadow-xs transition-[color,box-shadow] outline-none dark:bg-input/30",
|
||||||
|
"focus-visible:border-ring focus-visible:ring-[3px] focus-visible:ring-ring/50 aria-invalid:border-destructive",
|
||||||
|
"aria-disabled:cursor-not-allowed aria-disabled:opacity-50",
|
||||||
|
open && "border-ring ring-[3px] ring-ring/50",
|
||||||
|
className,
|
||||||
|
)}
|
||||||
|
>
|
||||||
|
<span className={cn("min-w-0 flex-1 truncate", !value && "text-muted-foreground")}>{value || placeholder}</span>
|
||||||
|
{value && !disabled && (
|
||||||
|
<button
|
||||||
|
type="button"
|
||||||
|
aria-label="Очистить"
|
||||||
|
onClick={(e) => {
|
||||||
|
e.stopPropagation()
|
||||||
|
onChange("")
|
||||||
|
}}
|
||||||
|
className="grid size-5 place-items-center rounded text-muted-foreground hover:bg-muted hover:text-foreground"
|
||||||
|
>
|
||||||
|
<XIcon className="size-3.5" />
|
||||||
|
</button>
|
||||||
|
)}
|
||||||
|
<ChevronDownIcon className={cn("size-4 shrink-0 text-muted-foreground transition", open && "rotate-180")} />
|
||||||
|
</div>
|
||||||
|
</PopoverTrigger>
|
||||||
|
<PopoverContent align="start" className="w-(--radix-popover-trigger-width) min-w-56 p-0">
|
||||||
|
<Command shouldFilter={false}>
|
||||||
|
<CommandInput placeholder={searchPlaceholder} value={search} onValueChange={setSearch} />
|
||||||
|
<CommandList>
|
||||||
|
{!canCreate && !filtered.length && <CommandEmpty>Ничего не найдено</CommandEmpty>}
|
||||||
|
<CommandGroup>
|
||||||
|
{filtered.map((o) => (
|
||||||
|
<CommandItem key={o} value={o} onSelect={() => pick(o)}>
|
||||||
|
<CheckIcon className={cn("size-4", o === value ? "text-primary" : "invisible")} />
|
||||||
|
{o}
|
||||||
|
</CommandItem>
|
||||||
|
))}
|
||||||
|
{canCreate && (
|
||||||
|
<CommandItem value={`__create ${custom}`} onSelect={() => pick(custom)}>
|
||||||
|
<PlusIcon className="size-4 text-primary" />
|
||||||
|
Указать «{custom}»
|
||||||
|
</CommandItem>
|
||||||
|
)}
|
||||||
|
</CommandGroup>
|
||||||
|
</CommandList>
|
||||||
|
</Command>
|
||||||
|
</PopoverContent>
|
||||||
|
</Popover>
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
@ -0,0 +1,233 @@
|
||||||
|
import * as React from "react"
|
||||||
|
import { CalendarIcon } from "lucide-react"
|
||||||
|
|
||||||
|
import { Button } from "@/components/ui/button"
|
||||||
|
import { Calendar } from "@/components/ui/calendar"
|
||||||
|
import { InputGroup, InputGroupAddon, InputGroupButton, InputGroupInput } from "@/components/ui/input-group"
|
||||||
|
import { Popover, PopoverAnchor, PopoverContent } from "@/components/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>
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
@ -0,0 +1,205 @@
|
||||||
|
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}`
|
||||||
|
}
|
||||||
|
|
@ -1,14 +1,18 @@
|
||||||
// Переиспользуемые компоненты МИС «Медицина». Витрина — /ui (src/pages/ui/ui-page.tsx).
|
// Переиспользуемые компоненты МИС «Медицина». Витрина — /ui (src/pages/ui/ui-page.tsx).
|
||||||
export * from "./code-block"
|
export * from "./code-block"
|
||||||
|
export * from "./combobox"
|
||||||
export * from "./confirm-dialog"
|
export * from "./confirm-dialog"
|
||||||
export * from "./content-tabs"
|
export * from "./content-tabs"
|
||||||
export * from "./data-table"
|
export * from "./data-table"
|
||||||
|
export * from "./date-input"
|
||||||
export * from "./date-leaf"
|
export * from "./date-leaf"
|
||||||
|
export * from "./date-range-input"
|
||||||
export * from "./file-drop"
|
export * from "./file-drop"
|
||||||
export * from "./file-gallery"
|
export * from "./file-gallery"
|
||||||
export * from "./form-field"
|
export * from "./form-field"
|
||||||
export * from "./info-section"
|
export * from "./info-section"
|
||||||
export * from "./multi-select"
|
export * from "./multi-select"
|
||||||
|
export * from "./notify"
|
||||||
export * from "./page-frame"
|
export * from "./page-frame"
|
||||||
export * from "./page-tabs"
|
export * from "./page-tabs"
|
||||||
export * from "./pagination"
|
export * from "./pagination"
|
||||||
|
|
@ -20,6 +24,7 @@ export * from "./save-bar"
|
||||||
export * from "./search-input"
|
export * from "./search-input"
|
||||||
export * from "./service-lines"
|
export * from "./service-lines"
|
||||||
export * from "./service-picker"
|
export * from "./service-picker"
|
||||||
|
export * from "./snils-input"
|
||||||
export * from "./stat-tile"
|
export * from "./stat-tile"
|
||||||
export * from "./status-badge"
|
export * from "./status-badge"
|
||||||
export * from "./stepper"
|
export * from "./stepper"
|
||||||
|
|
|
||||||
|
|
@ -0,0 +1,113 @@
|
||||||
|
import {
|
||||||
|
ArrowRightIcon,
|
||||||
|
CircleCheckIcon,
|
||||||
|
InfoIcon,
|
||||||
|
OctagonXIcon,
|
||||||
|
TriangleAlertIcon,
|
||||||
|
XIcon,
|
||||||
|
type LucideIcon,
|
||||||
|
} from "lucide-react"
|
||||||
|
import { useNavigate } from "react-router-dom"
|
||||||
|
import { toast, Toaster } from "sonner"
|
||||||
|
|
||||||
|
import { cn } from "@/lib/utils"
|
||||||
|
|
||||||
|
export type NotifyType = "success" | "info" | "warning" | "error"
|
||||||
|
|
||||||
|
const TOASTER_ID = "notify"
|
||||||
|
|
||||||
|
const typeMeta: Record<NotifyType, { icon: LucideIcon; tile: string; bar: string; duration: number }> = {
|
||||||
|
success: { icon: CircleCheckIcon, tile: "bg-success-soft text-success", bar: "bg-success", duration: 5000 },
|
||||||
|
info: { icon: InfoIcon, tile: "bg-info-soft text-info", bar: "bg-info", duration: 6000 },
|
||||||
|
warning: { icon: TriangleAlertIcon, tile: "bg-warning-soft text-warning", bar: "bg-warning", duration: 8000 },
|
||||||
|
error: { icon: OctagonXIcon, tile: "bg-coral-soft text-coral", bar: "bg-coral", duration: 10000 },
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface NotifyOptions {
|
||||||
|
type?: NotifyType
|
||||||
|
title: string
|
||||||
|
description?: React.ReactNode
|
||||||
|
/** Маршрут для кнопки «Перейти». */
|
||||||
|
href?: string
|
||||||
|
/** Текст кнопки перехода, по умолчанию «Перейти». */
|
||||||
|
actionLabel?: string
|
||||||
|
/** Мс до автозакрытия; Infinity — висит до закрытия руками. */
|
||||||
|
duration?: number
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Всплывающее уведомление справа сверху. Возвращает id для notify.dismiss(id). */
|
||||||
|
export function notify({ type = "info", duration, ...rest }: NotifyOptions) {
|
||||||
|
return toast.custom((id) => <NotifyCard id={id} type={type} {...rest} />, {
|
||||||
|
toasterId: TOASTER_ID,
|
||||||
|
duration: duration ?? typeMeta[type].duration,
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
notify.success = (o: Omit<NotifyOptions, "type">) => notify({ ...o, type: "success" })
|
||||||
|
notify.info = (o: Omit<NotifyOptions, "type">) => notify({ ...o, type: "info" })
|
||||||
|
notify.warning = (o: Omit<NotifyOptions, "type">) => notify({ ...o, type: "warning" })
|
||||||
|
notify.error = (o: Omit<NotifyOptions, "type">) => notify({ ...o, type: "error" })
|
||||||
|
notify.dismiss = (id?: string | number) => toast.dismiss(id)
|
||||||
|
|
||||||
|
/** Контейнер уведомлений. Монтируется один раз внутри BrowserRouter — карточке нужен роутер для «Перейти». */
|
||||||
|
export function NotifyToaster() {
|
||||||
|
return (
|
||||||
|
<Toaster
|
||||||
|
id={TOASTER_ID}
|
||||||
|
position="top-right"
|
||||||
|
visibleToasts={5}
|
||||||
|
gap={10}
|
||||||
|
offset={{ top: 64, right: 16 }}
|
||||||
|
toastOptions={{ unstyled: true, className: "w-full" }}
|
||||||
|
/>
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
function NotifyCard({
|
||||||
|
id,
|
||||||
|
type,
|
||||||
|
title,
|
||||||
|
description,
|
||||||
|
href,
|
||||||
|
actionLabel = "Перейти",
|
||||||
|
}: Omit<NotifyOptions, "duration"> & { id: string | number; type: NotifyType }) {
|
||||||
|
const navigate = useNavigate()
|
||||||
|
const { icon: Icon, tile, bar } = typeMeta[type]
|
||||||
|
|
||||||
|
return (
|
||||||
|
<div
|
||||||
|
role={type === "error" ? "alert" : "status"}
|
||||||
|
className="relative flex w-[356px] max-w-[calc(100vw-2rem)] gap-3 overflow-hidden rounded-xl border bg-popover p-3 pl-4 text-popover-foreground shadow-lg"
|
||||||
|
>
|
||||||
|
<span className={cn("absolute inset-y-0 left-0 w-1", bar)} />
|
||||||
|
<div className={cn("grid size-8 shrink-0 place-items-center rounded-lg", tile)}>
|
||||||
|
<Icon className="size-4" />
|
||||||
|
</div>
|
||||||
|
<div className="min-w-0 flex-1 pt-0.5">
|
||||||
|
<div className="text-sm font-semibold leading-snug">{title}</div>
|
||||||
|
{description && <div className="mt-0.5 text-sm text-muted-foreground">{description}</div>}
|
||||||
|
{href && (
|
||||||
|
<button
|
||||||
|
type="button"
|
||||||
|
onClick={() => {
|
||||||
|
navigate(href)
|
||||||
|
toast.dismiss(id)
|
||||||
|
}}
|
||||||
|
className="mt-2 inline-flex items-center gap-1 text-sm font-medium text-primary hover:underline"
|
||||||
|
>
|
||||||
|
{actionLabel}
|
||||||
|
<ArrowRightIcon className="size-3.5" />
|
||||||
|
</button>
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
<button
|
||||||
|
type="button"
|
||||||
|
aria-label="Закрыть"
|
||||||
|
onClick={() => toast.dismiss(id)}
|
||||||
|
className="-mt-0.5 -mr-0.5 grid size-6 shrink-0 place-items-center rounded-md text-muted-foreground hover:bg-muted hover:text-foreground"
|
||||||
|
>
|
||||||
|
<XIcon className="size-4" />
|
||||||
|
</button>
|
||||||
|
</div>
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
@ -0,0 +1,55 @@
|
||||||
|
import * as React from "react"
|
||||||
|
import { CircleCheckIcon } from "lucide-react"
|
||||||
|
|
||||||
|
import { InputGroup, InputGroupAddon, InputGroupInput } from "@/components/ui/input-group"
|
||||||
|
import { isSnilsValid, maskSnils, maskWithCaret, onlyDigits } from "@/lib/masks"
|
||||||
|
import { useCaret } from "@/hooks/use-caret"
|
||||||
|
import { cn } from "@/lib/utils"
|
||||||
|
|
||||||
|
/** Текст ошибки для СНИЛС; пустое значение ошибкой не считается. */
|
||||||
|
export function snilsError(value: string) {
|
||||||
|
const digits = onlyDigits(value)
|
||||||
|
if (!digits) return undefined
|
||||||
|
if (digits.length < 11) return "Нужно 11 цифр"
|
||||||
|
return isSnilsValid(value) ? undefined : "Не сходится контрольное число"
|
||||||
|
}
|
||||||
|
|
||||||
|
/** СНИЛС с маской «000-000-000 00»; зелёная галочка, когда номер полный и контрольное число сходится. */
|
||||||
|
export function SnilsInput({
|
||||||
|
value,
|
||||||
|
onChange,
|
||||||
|
invalid,
|
||||||
|
className,
|
||||||
|
...props
|
||||||
|
}: Omit<React.ComponentProps<"input">, "value" | "onChange"> & {
|
||||||
|
value: string
|
||||||
|
onChange: (value: string) => void
|
||||||
|
invalid?: boolean
|
||||||
|
}) {
|
||||||
|
const valid = isSnilsValid(value)
|
||||||
|
const setCaret = useCaret()
|
||||||
|
|
||||||
|
return (
|
||||||
|
<InputGroup className={cn("w-full", className)}>
|
||||||
|
<InputGroupInput
|
||||||
|
inputMode="numeric"
|
||||||
|
autoComplete="off"
|
||||||
|
placeholder="000-000-000 00"
|
||||||
|
{...props}
|
||||||
|
value={value}
|
||||||
|
aria-invalid={invalid}
|
||||||
|
onChange={(e) => {
|
||||||
|
const next = maskWithCaret(e.target, (e.nativeEvent as InputEvent).inputType, value, maskSnils)
|
||||||
|
onChange(next.value)
|
||||||
|
setCaret(e.target, next.caret)
|
||||||
|
}}
|
||||||
|
className="font-mono tabular"
|
||||||
|
/>
|
||||||
|
{valid && (
|
||||||
|
<InputGroupAddon align="inline-end">
|
||||||
|
<CircleCheckIcon className="text-emerald-600 dark:text-emerald-400" aria-label="Номер корректен" />
|
||||||
|
</InputGroupAddon>
|
||||||
|
)}
|
||||||
|
</InputGroup>
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
@ -0,0 +1,153 @@
|
||||||
|
/** Маски ввода для форм: принимают что угодно, возвращают отформатированную строку. */
|
||||||
|
|
||||||
|
export function onlyDigits(value: string) {
|
||||||
|
return value.replace(/\D/g, "")
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Мобильный без +7: «(914) 123-12-12». */
|
||||||
|
export function maskPhone(value: string) {
|
||||||
|
let d = onlyDigits(value)
|
||||||
|
if (d.length === 11 && (d[0] === "7" || d[0] === "8")) d = d.slice(1)
|
||||||
|
d = d.slice(0, 10)
|
||||||
|
if (!d) return ""
|
||||||
|
let out = `(${d.slice(0, 3)}`
|
||||||
|
if (d.length > 3) out += `) ${d.slice(3, 6)}`
|
||||||
|
if (d.length > 6) out += `-${d.slice(6, 8)}`
|
||||||
|
if (d.length > 8) out += `-${d.slice(8, 10)}`
|
||||||
|
return out
|
||||||
|
}
|
||||||
|
|
||||||
|
/** «123-456-789 01». */
|
||||||
|
export function maskSnils(value: string) {
|
||||||
|
const d = onlyDigits(value).slice(0, 11)
|
||||||
|
let out = d.slice(0, 3)
|
||||||
|
if (d.length > 3) out += `-${d.slice(3, 6)}`
|
||||||
|
if (d.length > 6) out += `-${d.slice(6, 9)}`
|
||||||
|
if (d.length > 9) out += ` ${d.slice(9, 11)}`
|
||||||
|
return out
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Контрольное число СНИЛС (проверяется для номеров больше 001-001-998). */
|
||||||
|
export function isSnilsValid(value: string) {
|
||||||
|
const d = onlyDigits(value)
|
||||||
|
if (d.length !== 11) return false
|
||||||
|
if (Number(d.slice(0, 9)) <= 1001998) return true
|
||||||
|
const sum = [...d.slice(0, 9)].reduce((acc, ch, i) => acc + Number(ch) * (9 - i), 0)
|
||||||
|
const control = sum < 100 ? sum : sum % 101 === 100 ? 0 : sum % 101
|
||||||
|
return control === Number(d.slice(9))
|
||||||
|
}
|
||||||
|
|
||||||
|
/** «дд.мм.гггг». Первая цифра дня больше 3 или месяца больше 1 однозначна — дописываем ноль: «4» → «04». */
|
||||||
|
export function maskDate(value: string) {
|
||||||
|
let d = ""
|
||||||
|
for (const ch of onlyDigits(value)) {
|
||||||
|
if ((d.length === 0 && ch > "3") || (d.length === 2 && ch > "1")) d += "0"
|
||||||
|
d += ch
|
||||||
|
}
|
||||||
|
d = d.slice(0, 8)
|
||||||
|
let out = d.slice(0, 2)
|
||||||
|
if (d.length > 2) out += `.${d.slice(2, 4)}`
|
||||||
|
if (d.length > 4) out += `.${d.slice(4, 8)}`
|
||||||
|
return out
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Может ли введённое начало стать настоящей датой: «3», «31.1», «29.02.20» — да;
|
||||||
|
* «40», «31.04», «12.13», «29.02.2023» — нет. Годы — 1900–2099.
|
||||||
|
*/
|
||||||
|
export function isDatePrefixValid(value: string) {
|
||||||
|
const d = onlyDigits(value)
|
||||||
|
const num = (from: number, to: number) => Number(d.slice(from, to))
|
||||||
|
if (d.length >= 1 && d[0] > "3") return false
|
||||||
|
if (d.length >= 2 && (num(0, 2) < 1 || num(0, 2) > 31)) return false
|
||||||
|
if (d.length >= 3 && d[2] > "1") return false
|
||||||
|
if (d.length >= 4) {
|
||||||
|
const month = num(2, 4)
|
||||||
|
if (month < 1 || month > 12) return false
|
||||||
|
// Пока года нет, считаем его високосным — 29.02 допустимо.
|
||||||
|
if (num(0, 2) > new Date(2000, month, 0).getDate()) return false
|
||||||
|
}
|
||||||
|
if (d.length >= 5 && d[4] !== "1" && d[4] !== "2") return false
|
||||||
|
if (d.length >= 6 && d.slice(4, 6) !== "19" && d.slice(4, 6) !== "20") return false
|
||||||
|
if (d.length >= 8 && num(0, 2) > new Date(num(4, 8), num(2, 4), 0).getDate()) return false
|
||||||
|
return true
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Разбор «дд.мм.гггг» в дату; null, если дата неполная или несуществующая. */
|
||||||
|
export function parseRuDate(value: string): Date | null {
|
||||||
|
const m = /^(\d{2})\.(\d{2})\.(\d{4})$/.exec(value)
|
||||||
|
if (!m) return null
|
||||||
|
const [day, month, year] = [Number(m[1]), Number(m[2]), Number(m[3])]
|
||||||
|
const date = new Date(year, month - 1, day)
|
||||||
|
return date.getDate() === day && date.getMonth() === month - 1 ? date : null
|
||||||
|
}
|
||||||
|
|
||||||
|
export function ageAt(birth: Date, now = new Date()) {
|
||||||
|
let age = now.getFullYear() - birth.getFullYear()
|
||||||
|
const m = now.getMonth() - birth.getMonth()
|
||||||
|
if (m < 0 || (m === 0 && now.getDate() < birth.getDate())) age--
|
||||||
|
return age
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Дата → «дд.мм.гггг». */
|
||||||
|
export function formatRuDate(date: Date | null | undefined) {
|
||||||
|
if (!date) return ""
|
||||||
|
const dd = String(date.getDate()).padStart(2, "0")
|
||||||
|
const mm = String(date.getMonth() + 1).padStart(2, "0")
|
||||||
|
return `${dd}.${mm}.${date.getFullYear()}`
|
||||||
|
}
|
||||||
|
|
||||||
|
export function isSameDay(a: Date | null | undefined, b: Date | null | undefined) {
|
||||||
|
if (!a || !b) return !a && !b
|
||||||
|
return a.getFullYear() === b.getFullYear() && a.getMonth() === b.getMonth() && a.getDate() === b.getDate()
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Применить маску к полю, не теряя курсор: правка в середине не уводит каретку в конец,
|
||||||
|
* а удаление разделителя стирает соседнюю цифру (иначе маска сразу вернула бы его обратно).
|
||||||
|
* Возвращает новое значение и позицию курсора в нём.
|
||||||
|
*/
|
||||||
|
export function maskWithCaret(
|
||||||
|
input: HTMLInputElement,
|
||||||
|
inputType: string | undefined,
|
||||||
|
previous: string,
|
||||||
|
mask: (value: string) => string,
|
||||||
|
/** Проверка набранного (не удаления): неподходящие символы просто не попадают в поле. */
|
||||||
|
accept?: (value: string) => boolean,
|
||||||
|
) {
|
||||||
|
let raw = input.value
|
||||||
|
let caret = input.selectionStart ?? raw.length
|
||||||
|
const removedSeparator = raw.length === previous.length - 1 && onlyDigits(raw) === onlyDigits(previous)
|
||||||
|
if (removedSeparator && inputType === "deleteContentBackward" && caret > 0) {
|
||||||
|
raw = raw.slice(0, caret - 1) + raw.slice(caret)
|
||||||
|
caret -= 1
|
||||||
|
} else if (removedSeparator && inputType === "deleteContentForward") {
|
||||||
|
raw = raw.slice(0, caret) + raw.slice(caret + 1)
|
||||||
|
}
|
||||||
|
if (accept && inputType?.startsWith("insert")) {
|
||||||
|
// Вставленный кусок лежит перед курсором; хвост после курсора не менялся.
|
||||||
|
let tail = raw.slice(caret)
|
||||||
|
const head = previous.slice(0, previous.length - tail.length)
|
||||||
|
let common = 0
|
||||||
|
while (common < caret && common < head.length && raw[common] === head[common]) common++
|
||||||
|
// Поле было заполнено — набор в середине заменяет следующие цифры, а не сдвигает их.
|
||||||
|
const full = mask(previous + "0") === previous
|
||||||
|
// Символы проверяем по одному, как при наборе: «40.33.6566» → «04.03».
|
||||||
|
let kept = raw.slice(0, common)
|
||||||
|
for (const ch of raw.slice(common, caret)) {
|
||||||
|
const rest = full ? tail.replace(/^\D*\d/, "") : tail
|
||||||
|
if (accept(mask(kept + ch + rest))) {
|
||||||
|
kept += ch
|
||||||
|
tail = rest
|
||||||
|
}
|
||||||
|
}
|
||||||
|
raw = kept + tail
|
||||||
|
caret = kept.length
|
||||||
|
}
|
||||||
|
const value = mask(raw)
|
||||||
|
// Маска идёт слева направо, поэтому цифры до курсора — это маска того, что до курсора (с дописанными нулями).
|
||||||
|
const digitsBefore = onlyDigits(mask(raw.slice(0, caret))).length
|
||||||
|
let pos = 0
|
||||||
|
for (let seen = 0; pos < value.length && seen < digitsBefore; pos++) if (/\d/.test(value[pos])) seen++
|
||||||
|
return { value, caret: pos }
|
||||||
|
}
|
||||||
|
|
@ -0,0 +1,222 @@
|
||||||
|
|
||||||
|
import * as React from "react"
|
||||||
|
import { cn } from "@/lib/utils"
|
||||||
|
import {
|
||||||
|
ChevronDownIcon,
|
||||||
|
ChevronLeftIcon,
|
||||||
|
ChevronRightIcon,
|
||||||
|
} from "lucide-react"
|
||||||
|
import {
|
||||||
|
DayPicker,
|
||||||
|
getDefaultClassNames,
|
||||||
|
type DayButton,
|
||||||
|
} from "react-day-picker"
|
||||||
|
import { ru } from "react-day-picker/locale"
|
||||||
|
|
||||||
|
import { Button, buttonVariants } from "@/components/ui/button"
|
||||||
|
|
||||||
|
function Calendar({
|
||||||
|
className,
|
||||||
|
classNames,
|
||||||
|
showOutsideDays = true,
|
||||||
|
captionLayout = "label",
|
||||||
|
buttonVariant = "ghost",
|
||||||
|
formatters,
|
||||||
|
components,
|
||||||
|
locale = ru,
|
||||||
|
...props
|
||||||
|
}: React.ComponentProps<typeof DayPicker> & {
|
||||||
|
buttonVariant?: React.ComponentProps<typeof Button>["variant"]
|
||||||
|
}) {
|
||||||
|
const defaultClassNames = getDefaultClassNames()
|
||||||
|
|
||||||
|
return (
|
||||||
|
<DayPicker
|
||||||
|
showOutsideDays={showOutsideDays}
|
||||||
|
className={cn(
|
||||||
|
"group/calendar bg-background p-3 [--cell-size:--spacing(8)] [[data-slot=card-content]_&]:bg-transparent [[data-slot=popover-content]_&]:bg-transparent",
|
||||||
|
String.raw`rtl:**:[.rdp-button\_next>svg]:rotate-180`,
|
||||||
|
String.raw`rtl:**:[.rdp-button\_previous>svg]:rotate-180`,
|
||||||
|
className
|
||||||
|
)}
|
||||||
|
captionLayout={captionLayout}
|
||||||
|
locale={locale}
|
||||||
|
formatters={{
|
||||||
|
formatMonthDropdown: (date) =>
|
||||||
|
date.toLocaleString("ru-RU", { month: "long" }),
|
||||||
|
...formatters,
|
||||||
|
}}
|
||||||
|
classNames={{
|
||||||
|
root: cn("w-fit", defaultClassNames.root),
|
||||||
|
months: cn(
|
||||||
|
"relative flex flex-col gap-4 md:flex-row",
|
||||||
|
defaultClassNames.months
|
||||||
|
),
|
||||||
|
month: cn("flex w-full flex-col gap-4", defaultClassNames.month),
|
||||||
|
nav: cn(
|
||||||
|
"absolute inset-x-0 top-0 flex w-full items-center justify-between gap-1",
|
||||||
|
defaultClassNames.nav
|
||||||
|
),
|
||||||
|
button_previous: cn(
|
||||||
|
buttonVariants({ variant: buttonVariant }),
|
||||||
|
"size-(--cell-size) p-0 select-none aria-disabled:opacity-50",
|
||||||
|
defaultClassNames.button_previous
|
||||||
|
),
|
||||||
|
button_next: cn(
|
||||||
|
buttonVariants({ variant: buttonVariant }),
|
||||||
|
"size-(--cell-size) p-0 select-none aria-disabled:opacity-50",
|
||||||
|
defaultClassNames.button_next
|
||||||
|
),
|
||||||
|
month_caption: cn(
|
||||||
|
"flex h-(--cell-size) w-full items-center justify-center px-(--cell-size)",
|
||||||
|
defaultClassNames.month_caption
|
||||||
|
),
|
||||||
|
dropdowns: cn(
|
||||||
|
"flex h-(--cell-size) w-full items-center justify-center gap-1.5 text-sm font-medium",
|
||||||
|
defaultClassNames.dropdowns
|
||||||
|
),
|
||||||
|
dropdown_root: cn(
|
||||||
|
"relative rounded-md border border-input shadow-xs has-focus:border-ring has-focus:ring-[3px] has-focus:ring-ring/50",
|
||||||
|
defaultClassNames.dropdown_root
|
||||||
|
),
|
||||||
|
dropdown: cn(
|
||||||
|
"absolute inset-0 bg-popover opacity-0",
|
||||||
|
defaultClassNames.dropdown
|
||||||
|
),
|
||||||
|
caption_label: cn(
|
||||||
|
"font-medium select-none",
|
||||||
|
captionLayout === "label"
|
||||||
|
? "text-sm"
|
||||||
|
: "flex h-8 items-center gap-1 rounded-md pr-1 pl-2 text-sm [&>svg]:size-3.5 [&>svg]:text-muted-foreground",
|
||||||
|
defaultClassNames.caption_label
|
||||||
|
),
|
||||||
|
month_grid: cn("w-full border-collapse", defaultClassNames.month_grid),
|
||||||
|
weekdays: cn("flex", defaultClassNames.weekdays),
|
||||||
|
weekday: cn(
|
||||||
|
"flex-1 rounded-md text-[0.8rem] font-normal text-muted-foreground select-none",
|
||||||
|
defaultClassNames.weekday
|
||||||
|
),
|
||||||
|
week: cn("mt-2 flex w-full", defaultClassNames.week),
|
||||||
|
week_number_header: cn(
|
||||||
|
"w-(--cell-size) select-none",
|
||||||
|
defaultClassNames.week_number_header
|
||||||
|
),
|
||||||
|
week_number: cn(
|
||||||
|
"text-[0.8rem] text-muted-foreground select-none",
|
||||||
|
defaultClassNames.week_number
|
||||||
|
),
|
||||||
|
day: cn(
|
||||||
|
"group/day relative aspect-square h-full w-full p-0 text-center select-none [&:last-child[data-selected=true]_button]:rounded-r-md",
|
||||||
|
props.showWeekNumber
|
||||||
|
? "[&:nth-child(2)[data-selected=true]_button]:rounded-l-md"
|
||||||
|
: "[&:first-child[data-selected=true]_button]:rounded-l-md",
|
||||||
|
defaultClassNames.day
|
||||||
|
),
|
||||||
|
range_start: cn(
|
||||||
|
"rounded-l-md bg-accent",
|
||||||
|
defaultClassNames.range_start
|
||||||
|
),
|
||||||
|
range_middle: cn("rounded-none", defaultClassNames.range_middle),
|
||||||
|
range_end: cn("rounded-r-md bg-accent", defaultClassNames.range_end),
|
||||||
|
today: cn(
|
||||||
|
"rounded-md bg-accent text-accent-foreground data-[selected=true]:rounded-none",
|
||||||
|
defaultClassNames.today
|
||||||
|
),
|
||||||
|
outside: cn(
|
||||||
|
"text-muted-foreground aria-selected:text-muted-foreground",
|
||||||
|
defaultClassNames.outside
|
||||||
|
),
|
||||||
|
disabled: cn(
|
||||||
|
"text-muted-foreground opacity-50",
|
||||||
|
defaultClassNames.disabled
|
||||||
|
),
|
||||||
|
hidden: cn("invisible", defaultClassNames.hidden),
|
||||||
|
...classNames,
|
||||||
|
}}
|
||||||
|
components={{
|
||||||
|
Root: ({ className, rootRef, ...props }) => {
|
||||||
|
return (
|
||||||
|
<div
|
||||||
|
data-slot="calendar"
|
||||||
|
ref={rootRef}
|
||||||
|
className={cn(className)}
|
||||||
|
{...props}
|
||||||
|
/>
|
||||||
|
)
|
||||||
|
},
|
||||||
|
Chevron: ({ className, orientation, ...props }) => {
|
||||||
|
if (orientation === "left") {
|
||||||
|
return (
|
||||||
|
<ChevronLeftIcon className={cn("size-4", className)} {...props} />
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
if (orientation === "right") {
|
||||||
|
return (
|
||||||
|
<ChevronRightIcon
|
||||||
|
className={cn("size-4", className)}
|
||||||
|
{...props}
|
||||||
|
/>
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
return (
|
||||||
|
<ChevronDownIcon className={cn("size-4", className)} {...props} />
|
||||||
|
)
|
||||||
|
},
|
||||||
|
DayButton: CalendarDayButton,
|
||||||
|
WeekNumber: ({ children, ...props }) => {
|
||||||
|
return (
|
||||||
|
<td {...props}>
|
||||||
|
<div className="flex size-(--cell-size) items-center justify-center text-center">
|
||||||
|
{children}
|
||||||
|
</div>
|
||||||
|
</td>
|
||||||
|
)
|
||||||
|
},
|
||||||
|
...components,
|
||||||
|
}}
|
||||||
|
{...props}
|
||||||
|
/>
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
function CalendarDayButton({
|
||||||
|
className,
|
||||||
|
day,
|
||||||
|
modifiers,
|
||||||
|
...props
|
||||||
|
}: React.ComponentProps<typeof DayButton>) {
|
||||||
|
const defaultClassNames = getDefaultClassNames()
|
||||||
|
|
||||||
|
const ref = React.useRef<HTMLButtonElement>(null)
|
||||||
|
React.useEffect(() => {
|
||||||
|
if (modifiers.focused) ref.current?.focus()
|
||||||
|
}, [modifiers.focused])
|
||||||
|
|
||||||
|
return (
|
||||||
|
<Button
|
||||||
|
ref={ref}
|
||||||
|
variant="ghost"
|
||||||
|
size="icon"
|
||||||
|
data-day={day.date.toLocaleDateString()}
|
||||||
|
data-selected-single={
|
||||||
|
modifiers.selected &&
|
||||||
|
!modifiers.range_start &&
|
||||||
|
!modifiers.range_end &&
|
||||||
|
!modifiers.range_middle
|
||||||
|
}
|
||||||
|
data-range-start={modifiers.range_start}
|
||||||
|
data-range-end={modifiers.range_end}
|
||||||
|
data-range-middle={modifiers.range_middle}
|
||||||
|
className={cn(
|
||||||
|
"flex aspect-square size-auto w-full min-w-(--cell-size) flex-col gap-1 leading-none font-normal group-data-[focused=true]/day:relative group-data-[focused=true]/day:z-10 group-data-[focused=true]/day:border-ring group-data-[focused=true]/day:ring-[3px] group-data-[focused=true]/day:ring-ring/50 data-[range-end=true]:rounded-md data-[range-end=true]:rounded-r-md data-[range-end=true]:bg-primary data-[range-end=true]:text-primary-foreground data-[range-middle=true]:rounded-none data-[range-middle=true]:bg-accent data-[range-middle=true]:text-accent-foreground data-[range-start=true]:rounded-md data-[range-start=true]:rounded-l-md data-[range-start=true]:bg-primary data-[range-start=true]:text-primary-foreground data-[selected-single=true]:bg-primary data-[selected-single=true]:text-primary-foreground dark:hover:text-accent-foreground [&>span]:text-xs [&>span]:opacity-70",
|
||||||
|
defaultClassNames.day,
|
||||||
|
className
|
||||||
|
)}
|
||||||
|
{...props}
|
||||||
|
/>
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
export { Calendar, CalendarDayButton }
|
||||||
Loading…
Reference in New Issue