From 7ebaac8e1a8d819d08f351311a1f8af914687952 Mon Sep 17 00:00:00 2001 From: Ilya Mukhortov Date: Sat, 24 Oct 2026 08:23:26 +1000 Subject: [PATCH] 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 --- src/hooks/use-caret.ts | 24 ++++ src/kit/combobox.tsx | 117 ++++++++++++++++++ src/kit/date-input.tsx | 233 +++++++++++++++++++++++++++++++++++ src/kit/date-range-input.tsx | 205 ++++++++++++++++++++++++++++++ src/kit/index.ts | 5 + src/kit/notify.tsx | 113 +++++++++++++++++ src/kit/snils-input.tsx | 55 +++++++++ src/lib/masks.ts | 153 +++++++++++++++++++++++ src/ui/calendar.tsx | 222 +++++++++++++++++++++++++++++++++ 9 files changed, 1127 insertions(+) create mode 100644 src/hooks/use-caret.ts create mode 100644 src/kit/combobox.tsx create mode 100644 src/kit/date-input.tsx create mode 100644 src/kit/date-range-input.tsx create mode 100644 src/kit/notify.tsx create mode 100644 src/kit/snils-input.tsx create mode 100644 src/lib/masks.ts create mode 100644 src/ui/calendar.tsx diff --git a/src/hooks/use-caret.ts b/src/hooks/use-caret.ts new file mode 100644 index 0000000..7d486a2 --- /dev/null +++ b/src/hooks/use-caret.ts @@ -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) + }) + }, []) +} diff --git a/src/kit/combobox.tsx b/src/kit/combobox.tsx new file mode 100644 index 0000000..926594a --- /dev/null +++ b/src/kit/combobox.tsx @@ -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 ( + !disabled && setOpen(v)}> + +
{ + 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, + )} + > + {value || placeholder} + {value && !disabled && ( + + )} + +
+
+ + + + + {!canCreate && !filtered.length && Ничего не найдено} + + {filtered.map((o) => ( + pick(o)}> + + {o} + + ))} + {canCreate && ( + pick(custom)}> + + Указать «{custom}» + + )} + + + + +
+ ) +} diff --git a/src/kit/date-input.tsx b/src/kit/date-input.tsx new file mode 100644 index 0000000..f6bf9d8 --- /dev/null +++ b/src/kit/date-input.tsx @@ -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) => { + 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(null) + const toggleRef = React.useRef(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) => { + 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 ( + + + + + + + + + + + + + +
+ + +
+
+
+ ) +} diff --git a/src/kit/date-range-input.tsx b/src/kit/date-range-input.tsx new file mode 100644 index 0000000..760d17a --- /dev/null +++ b/src/kit/date-range-input.tsx @@ -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) => { + popover.returnFocus.current = e.currentTarget + } + + return ( + + + + + — + + + + + + + + + + {presets.length > 0 && ( +
+ {presets.map((preset) => { + const range = preset.range(today) + const active = isSameDay(range.from, value.from) && isSameDay(range.to, value.to) + return ( + + ) + })} +
+ )} +
+ pickDay(startOfDay(day))} + {...calendarBounds(limits, "label")} + /> +
+ + {value.from && !value.to ? "Выберите дату окончания" : rangeLength(value)} + + +
+
+
+
+ ) +} + +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}` +} diff --git a/src/kit/index.ts b/src/kit/index.ts index a7544e4..0a9e043 100644 --- a/src/kit/index.ts +++ b/src/kit/index.ts @@ -1,14 +1,18 @@ // Переиспользуемые компоненты МИС «Медицина». Витрина — /ui (src/pages/ui/ui-page.tsx). export * from "./code-block" +export * from "./combobox" export * from "./confirm-dialog" export * from "./content-tabs" export * from "./data-table" +export * from "./date-input" export * from "./date-leaf" +export * from "./date-range-input" export * from "./file-drop" export * from "./file-gallery" export * from "./form-field" export * from "./info-section" export * from "./multi-select" +export * from "./notify" export * from "./page-frame" export * from "./page-tabs" export * from "./pagination" @@ -20,6 +24,7 @@ export * from "./save-bar" export * from "./search-input" export * from "./service-lines" export * from "./service-picker" +export * from "./snils-input" export * from "./stat-tile" export * from "./status-badge" export * from "./stepper" diff --git a/src/kit/notify.tsx b/src/kit/notify.tsx new file mode 100644 index 0000000..d58c1f1 --- /dev/null +++ b/src/kit/notify.tsx @@ -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 = { + 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) => , { + toasterId: TOASTER_ID, + duration: duration ?? typeMeta[type].duration, + }) +} + +notify.success = (o: Omit) => notify({ ...o, type: "success" }) +notify.info = (o: Omit) => notify({ ...o, type: "info" }) +notify.warning = (o: Omit) => notify({ ...o, type: "warning" }) +notify.error = (o: Omit) => notify({ ...o, type: "error" }) +notify.dismiss = (id?: string | number) => toast.dismiss(id) + +/** Контейнер уведомлений. Монтируется один раз внутри BrowserRouter — карточке нужен роутер для «Перейти». */ +export function NotifyToaster() { + return ( + + ) +} + +function NotifyCard({ + id, + type, + title, + description, + href, + actionLabel = "Перейти", +}: Omit & { id: string | number; type: NotifyType }) { + const navigate = useNavigate() + const { icon: Icon, tile, bar } = typeMeta[type] + + return ( +
+ +
+ +
+
+
{title}
+ {description &&
{description}
} + {href && ( + + )} +
+ +
+ ) +} diff --git a/src/kit/snils-input.tsx b/src/kit/snils-input.tsx new file mode 100644 index 0000000..122ebc6 --- /dev/null +++ b/src/kit/snils-input.tsx @@ -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, "value" | "onChange"> & { + value: string + onChange: (value: string) => void + invalid?: boolean +}) { + const valid = isSnilsValid(value) + const setCaret = useCaret() + + return ( + + { + 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 && ( + + + + )} + + ) +} diff --git a/src/lib/masks.ts b/src/lib/masks.ts new file mode 100644 index 0000000..46058d2 --- /dev/null +++ b/src/lib/masks.ts @@ -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 } +} diff --git a/src/ui/calendar.tsx b/src/ui/calendar.tsx new file mode 100644 index 0000000..1663b09 --- /dev/null +++ b/src/ui/calendar.tsx @@ -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 & { + buttonVariant?: React.ComponentProps["variant"] +}) { + const defaultClassNames = getDefaultClassNames() + + return ( + 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 ( +
+ ) + }, + Chevron: ({ className, orientation, ...props }) => { + if (orientation === "left") { + return ( + + ) + } + + if (orientation === "right") { + return ( + + ) + } + + return ( + + ) + }, + DayButton: CalendarDayButton, + WeekNumber: ({ children, ...props }) => { + return ( + +
+ {children} +
+ + ) + }, + ...components, + }} + {...props} + /> + ) +} + +function CalendarDayButton({ + className, + day, + modifiers, + ...props +}: React.ComponentProps) { + const defaultClassNames = getDefaultClassNames() + + const ref = React.useRef(null) + React.useEffect(() => { + if (modifiers.focused) ref.current?.focus() + }, [modifiers.focused]) + + return ( +