diff --git a/src/kit/edit-dialog.tsx b/src/kit/edit-dialog.tsx new file mode 100644 index 0000000..d485e8b --- /dev/null +++ b/src/kit/edit-dialog.tsx @@ -0,0 +1,63 @@ +import * as React from "react" +import type { LucideIcon } from "lucide-react" + +import { Button } from "@/components/ui/button" +import { Dialog, DialogContent, DialogDescription, DialogFooter, DialogHeader, DialogTitle } from "@/components/ui/dialog" +import { cn } from "@/lib/utils" + +/** + * Модальное редактирование одного смыслового блока (InfoSection): форма, «Отмена» / «Сохранить». + * Enter в поле сохраняет; пока `canSave` ложно, сохранить нельзя. + */ +export function EditDialog({ + open, + onOpenChange, + icon: Icon, + title, + description, + canSave = true, + onSave, + className, + children, +}: { + open: boolean + onOpenChange: (open: boolean) => void + icon?: LucideIcon + title: string + description?: React.ReactNode + canSave?: boolean + onSave: () => void + className?: string + children: React.ReactNode +}) { + return ( + + + { + e.preventDefault() + if (canSave) onSave() + }} + > + + + {Icon && } + {title} + + {description && {description}} + + {children} + + onOpenChange(false)}> + Отмена + + + Сохранить + + + + + + ) +} diff --git a/src/kit/index.ts b/src/kit/index.ts index 0a9e043..8f79dfd 100644 --- a/src/kit/index.ts +++ b/src/kit/index.ts @@ -7,6 +7,7 @@ export * from "./data-table" export * from "./date-input" export * from "./date-leaf" export * from "./date-range-input" +export * from "./edit-dialog" export * from "./file-drop" export * from "./file-gallery" export * from "./form-field" @@ -28,4 +29,5 @@ export * from "./snils-input" export * from "./stat-tile" export * from "./status-badge" export * from "./stepper" +export * from "./time-input" export * from "./time-range-input" diff --git a/src/kit/info-section.tsx b/src/kit/info-section.tsx index 9571080..9abe850 100644 --- a/src/kit/info-section.tsx +++ b/src/kit/info-section.tsx @@ -1,29 +1,46 @@ import * as React from "react" -import { CopyIcon, type LucideIcon } from "lucide-react" +import { CopyIcon, PencilIcon, type LucideIcon } from "lucide-react" import { cn } from "@/lib/utils" import { copyToClipboard } from "@/lib/clipboard" -/** Смысловой блок на мягкой подложке: иконка + заголовок, справа — действие. */ +/** Смысловой блок на мягкой подложке: иконка + заголовок, справа — действие; с `onEdit` — карандаш при наведении. */ export function InfoSection({ icon: Icon, title, action, + onEdit, className, children, }: { icon?: LucideIcon title: React.ReactNode action?: React.ReactNode + /** Редактирование блока — обычно открывает EditDialog. */ + onEdit?: () => void className?: string children: React.ReactNode }) { return ( - - + + {Icon && } {title} - {action && {action}} + {(action || onEdit) && ( + + {action} + {onEdit && ( + + + + )} + + )} {children} diff --git a/src/kit/patient-panel.tsx b/src/kit/patient-panel.tsx index 31819de..ab6e780 100644 --- a/src/kit/patient-panel.tsx +++ b/src/kit/patient-panel.tsx @@ -13,6 +13,7 @@ export interface PatientPanelPerson extends AvatarPerson { readonly age: number readonly phone?: string readonly cardNumber?: string + readonly snils?: string readonly doctor?: string } @@ -36,6 +37,7 @@ export function PatientPanel({ className?: string }) { const female = p.gender === "female" + const fullName = [p.lastName, p.firstName, p.middleName].filter(Boolean).join(" ") return ( @@ -55,7 +57,15 @@ export function PatientPanel({ - {p.lastName} {p.firstName} {p.middleName} + copyToClipboard(fullName, "ФИО скопировано")} + className="group inline-flex items-baseline gap-1.5 rounded-sm text-left hover:text-primary focus-visible:ring-[3px] focus-visible:ring-ring/50 focus-visible:outline-none" + > + {fullName} + + @@ -81,6 +91,17 @@ export function PatientPanel({ )} + {p.snils && ( + copyToClipboard(p.snils!, "СНИЛС скопирован")} + className="group inline-flex items-center gap-1.5 hover:text-foreground" + > + СНИЛС + {p.snils} + + + )} {p.doctor && ( diff --git a/src/kit/time-input.tsx b/src/kit/time-input.tsx new file mode 100644 index 0000000..16de449 --- /dev/null +++ b/src/kit/time-input.tsx @@ -0,0 +1,206 @@ +import * as React from "react" +import { ClockIcon } from "lucide-react" + +import { Button } from "@/components/ui/button" +import { InputGroup, InputGroupAddon, InputGroupButton, InputGroupInput } from "@/components/ui/input-group" +import { Popover, PopoverAnchor, PopoverContent } from "@/components/ui/popover" +import { isTimePrefixValid, maskTime, maskWithCaret } from "@/lib/masks" +import { useCaret } from "@/hooks/use-caret" +import { cn } from "@/lib/utils" + +import { useCalendarPopover } from "./date-input" + +const pad = (n: number) => String(n).padStart(2, "0") +const HOURS = Array.from({ length: 24 }, (_, h) => pad(h)) + +/** Сейчас, округлённое вниз до шага минут. */ +function nowTime(step: number) { + const d = new Date() + return `${pad(d.getHours())}:${pad(Math.floor(d.getMinutes() / step) * step)}` +} + +/** + * Время «чч:мм»: ввод вручную по маске или выбор часа и минут в двух колонках (кнопка, Alt+↓). + * Наружу уходит только полное время или пустая строка — недописанное остаётся в поле. + */ +export function TimeInput({ + value, + onChange, + step = 5, + invalid, + onErrorChange, + id, + disabled, + className, + "aria-label": ariaLabel, +}: { + /** «чч:мм» или "". */ + value: string + onChange: (value: string) => void + /** Шаг минут в списке; вручную можно ввести любые. */ + step?: number + /** Подсветить извне (ошибка формы), вдобавок к собственной проверке. */ + invalid?: boolean + /** Сообщение о недописанном времени — чтобы показать его в FormField. */ + onErrorChange?: (error: string | undefined) => void + id?: string + disabled?: boolean + className?: string + "aria-label"?: string +}) { + const [text, setText] = React.useState(value) + const [prev, setPrev] = React.useState(value) + const [touched, setTouched] = React.useState(false) + const setCaret = useCaret() + const popover = useCalendarPopover(() => new Date()) + + if (prev !== value) { + setPrev(value) + const typed = text.length === 5 ? text : "" + if (typed !== value) setText(value) + } + + const error = text && text.length < 5 ? "Время в формате чч:мм" : undefined + const shownError = error && touched ? error : undefined + const reportError = React.useEffectEvent((message: string | undefined) => onErrorChange?.(message)) + React.useEffect(() => reportError(shownError), [shownError]) + + const change = (e: React.ChangeEvent) => { + const next = maskWithCaret(e.target, (e.nativeEvent as InputEvent).inputType, text, maskTime, isTimePrefixValid) + setText(next.value) + setCaret(e.target, next.caret) + const time = next.value.length === 5 ? next.value : "" + if (time !== value) onChange(time) + } + + const set = (time: string, close: boolean) => { + setText(time) + setTouched(false) + if (time !== value) onChange(time) + if (close) popover.setOpen(false) + } + + const [hour, minute] = value ? value.split(":") : ["", ""] + const minutes = Array.from({ length: Math.ceil(60 / step) }, (_, i) => pad(i * step)) + // Введённые вручную минуты не по шагу тоже видны в списке — выбранными. + if (minute && !minutes.includes(minute)) { + minutes.push(minute) + minutes.sort() + } + + // При открытии выбранные час и минута — в середине колонок; без значения — текущее время. + const [nowHour, nowMinute] = nowTime(step).split(":") + const columns = React.useRef(null) + React.useEffect(() => { + if (!popover.open) return + // Не scrollIntoView: тот прокрутил бы и страницу под попапом. + requestAnimationFrame(() => + columns.current?.querySelectorAll("[data-anchor=true]").forEach((el) => { + const list = el.parentElement! + list.scrollTop = el.offsetTop - (list.clientHeight - el.offsetHeight) / 2 + }), + ) + }, [popover.open]) + + return ( + + + + setTouched(true)} + onKeyDown={popover.onKeyDown} + className="tabular" + /> + + + + + + + + + + Часы + Минуты + + + set(`${h}:${minute || "00"}`, false)} /> + set(`${hour || nowTime(step).slice(0, 2)}:${m}`, true)} + /> + + + set("", true)} disabled={!value && !text}> + Очистить + + set(nowTime(step), true)}> + Сейчас + + + + + ) +} + +/** Колонка часов или минут; края затухают, чтобы обрезанные строки не выглядели оборванными. */ +function Column({ + label, + items, + selected, + anchor, + onPick, +}: { + label: string + items: readonly string[] + selected: string + /** Строка, которая встаёт в середину при открытии. */ + anchor: string + onPick: (item: string) => void +}) { + return ( + + {items.map((item) => ( + 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} + + ))} + + ) +} diff --git a/src/lib/masks.ts b/src/lib/masks.ts index 46058d2..11fe0e3 100644 --- a/src/lib/masks.ts +++ b/src/lib/masks.ts @@ -73,6 +73,26 @@ export function isDatePrefixValid(value: string) { return true } +/** «чч:мм». Первая цифра часа больше 2 или минут больше 5 однозначна — дописываем ноль: «9» → «09». */ +export function maskTime(value: string) { + let d = "" + for (const ch of onlyDigits(value)) { + if ((d.length === 0 && ch > "2") || (d.length === 2 && ch > "5")) d += "0" + d += ch + } + d = d.slice(0, 4) + return d.length > 2 ? `${d.slice(0, 2)}:${d.slice(2)}` : d +} + +/** Может ли введённое начало стать временем: «2», «23:5» — да; «24», «12:6» — нет. */ +export function isTimePrefixValid(value: string) { + const d = onlyDigits(value) + if (d.length >= 1 && d[0] > "2") return false + if (d.length >= 2 && Number(d.slice(0, 2)) > 23) return false + if (d.length >= 3 && d[2] > "5") return false + return true +} + /** Разбор «дд.мм.гггг» в дату; null, если дата неполная или несуществующая. */ export function parseRuDate(value: string): Date | null { const m = /^(\d{2})\.(\d{2})\.(\d{4})$/.exec(value)