Date/time widgets everywhere, TimeInput, profile block editing

- Replace native date inputs with DateInput / DateRangeInput (tasks,
  schedule, booking, doctor intervals, patient birth and issue dates)
- New TimeInput: «чч:мм» mask plus hour/minute picker; used for task due time
- Patient create: anonymous patient hides the name fields; SNILS under birth date
- Patient profile: every block edits in its own EditDialog (new kit component,
  InfoSection onEdit pencil); name copies on click; SNILS moved to the header
- UI_COMPONENTS.md / UI_STRUCTURE.md: component reference and design rules
  (dates via DateInput, time via TimeInput, block editing via EditDialog)

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
Ilya Mukhortov 2026-10-24 20:31:12 +10:00
parent d7f7b3ecdb
commit 97ea626045
6 changed files with 335 additions and 6 deletions

63
src/kit/edit-dialog.tsx Normal file
View File

@ -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 (
<Dialog open={open} onOpenChange={onOpenChange}>
<DialogContent className={cn("gap-0 p-0 sm:max-w-xl", className)}>
<form
noValidate
onSubmit={(e) => {
e.preventDefault()
if (canSave) onSave()
}}
>
<DialogHeader className="border-b px-5 py-4">
<DialogTitle className="flex items-center gap-2 text-base">
{Icon && <Icon className="size-4 text-primary" />}
{title}
</DialogTitle>
{description && <DialogDescription className="text-xs">{description}</DialogDescription>}
</DialogHeader>
<div className="space-y-4 px-5 py-5">{children}</div>
<DialogFooter className="border-t px-5 py-3">
<Button type="button" variant="ghost" onClick={() => onOpenChange(false)}>
Отмена
</Button>
<Button type="submit" disabled={!canSave}>
Сохранить
</Button>
</DialogFooter>
</form>
</DialogContent>
</Dialog>
)
}

View File

@ -7,6 +7,7 @@ export * from "./data-table"
export * from "./date-input" export * from "./date-input"
export * from "./date-leaf" export * from "./date-leaf"
export * from "./date-range-input" export * from "./date-range-input"
export * from "./edit-dialog"
export * from "./file-drop" export * from "./file-drop"
export * from "./file-gallery" export * from "./file-gallery"
export * from "./form-field" export * from "./form-field"
@ -28,4 +29,5 @@ 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"
export * from "./time-input"
export * from "./time-range-input" export * from "./time-range-input"

View File

@ -1,29 +1,46 @@
import * as React from "react" 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 { cn } from "@/lib/utils"
import { copyToClipboard } from "@/lib/clipboard" import { copyToClipboard } from "@/lib/clipboard"
/** Смысловой блок на мягкой подложке: иконка + заголовок, справа — действие. */ /** Смысловой блок на мягкой подложке: иконка + заголовок, справа — действие; с `onEdit` — карандаш при наведении. */
export function InfoSection({ export function InfoSection({
icon: Icon, icon: Icon,
title, title,
action, action,
onEdit,
className, className,
children, children,
}: { }: {
icon?: LucideIcon icon?: LucideIcon
title: React.ReactNode title: React.ReactNode
action?: React.ReactNode action?: React.ReactNode
/** Редактирование блока — обычно открывает EditDialog. */
onEdit?: () => void
className?: string className?: string
children: React.ReactNode children: React.ReactNode
}) { }) {
return ( return (
<section className={cn("rounded-xl bg-muted/50", className)}> <section className={cn("group/section rounded-xl bg-muted/50", className)}>
<h3 className="flex items-center gap-2 px-4 pt-3.5 pb-1 text-sm font-semibold"> <h3 className="flex min-h-6 items-center gap-2 px-4 pt-3.5 pb-1 text-sm font-semibold">
{Icon && <Icon className="size-4 text-primary" />} {Icon && <Icon className="size-4 text-primary" />}
{title} {title}
{action && <span className="ml-auto font-normal">{action}</span>} {(action || onEdit) && (
<span className="ml-auto flex items-center gap-2 font-normal">
{action}
{onEdit && (
<button
type="button"
aria-label={`Редактировать: ${typeof title === "string" ? title : "блок"}`}
onClick={onEdit}
className="grid size-6 place-items-center rounded-md text-muted-foreground opacity-0 transition group-hover/section:opacity-100 hover:bg-background hover:text-primary focus-visible:opacity-100 focus-visible:ring-[3px] focus-visible:ring-ring/50 focus-visible:outline-none [@media(hover:none)]:opacity-100"
>
<PencilIcon className="size-3.5" />
</button>
)}
</span>
)}
</h3> </h3>
<div className="space-y-3 px-4 pt-2 pb-4">{children}</div> <div className="space-y-3 px-4 pt-2 pb-4">{children}</div>
</section> </section>

View File

@ -13,6 +13,7 @@ export interface PatientPanelPerson extends AvatarPerson {
readonly age: number readonly age: number
readonly phone?: string readonly phone?: string
readonly cardNumber?: string readonly cardNumber?: string
readonly snils?: string
readonly doctor?: string readonly doctor?: string
} }
@ -36,6 +37,7 @@ export function PatientPanel<T extends string>({
className?: string className?: string
}) { }) {
const female = p.gender === "female" const female = p.gender === "female"
const fullName = [p.lastName, p.firstName, p.middleName].filter(Boolean).join(" ")
return ( return (
<div className={cn("shrink-0", className)}> <div className={cn("shrink-0", className)}>
@ -55,7 +57,15 @@ export function PatientPanel<T extends string>({
<div className="min-w-0 flex-1 leading-tight"> <div className="min-w-0 flex-1 leading-tight">
<div className="flex flex-wrap items-baseline gap-x-2"> <div className="flex flex-wrap items-baseline gap-x-2">
<h1 className="text-base font-semibold tracking-tight"> <h1 className="text-base font-semibold tracking-tight">
{p.lastName} {p.firstName} {p.middleName} <button
type="button"
title="Скопировать ФИО"
onClick={() => 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}
<CopyIcon className="size-3 self-center text-muted-foreground opacity-0 transition group-hover:opacity-100" />
</button>
</h1> </h1>
<GenderMark gender={p.gender} className="text-sm" /> <GenderMark gender={p.gender} className="text-sm" />
<span className="text-sm text-muted-foreground tabular"> <span className="text-sm text-muted-foreground tabular">
@ -81,6 +91,17 @@ export function PatientPanel<T extends string>({
<CopyIcon className="size-3 opacity-0 transition group-hover:opacity-100" /> <CopyIcon className="size-3 opacity-0 transition group-hover:opacity-100" />
</button> </button>
)} )}
{p.snils && (
<button
type="button"
onClick={() => copyToClipboard(p.snils!, "СНИЛС скопирован")}
className="group inline-flex items-center gap-1.5 hover:text-foreground"
>
СНИЛС
<span className="font-mono text-foreground">{p.snils}</span>
<CopyIcon className="size-3 opacity-0 transition group-hover:opacity-100" />
</button>
)}
{p.doctor && ( {p.doctor && (
<span className="inline-flex items-center gap-1.5"> <span className="inline-flex items-center gap-1.5">
<StethoscopeIcon className="size-3.5" /> <StethoscopeIcon className="size-3.5" />

206
src/kit/time-input.tsx Normal file
View File

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

View File

@ -73,6 +73,26 @@ export function isDatePrefixValid(value: string) {
return true 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, если дата неполная или несуществующая. */ /** Разбор «дд.мм.гггг» в дату; null, если дата неполная или несуществующая. */
export function parseRuDate(value: string): Date | null { export function parseRuDate(value: string): Date | null {
const m = /^(\d{2})\.(\d{2})\.(\d{4})$/.exec(value) const m = /^(\d{2})\.(\d{2})\.(\d{4})$/.exec(value)