EmptyState, FilterBar, ScheduleGrid, type scale, release 0.7.0

- EmptyState: icon tile, title, description and action; DataTable turns a
  string `empty` into one.
- FilterBar: filters wrap inside their own block, secondary toggles fold into
  an "Ещё" popover, "Сбросить" with a counter stays on the first row.
- ScheduleGrid: day grid by resource with status-coloured events, lanes for
  overlaps, off-hours hatching, clickable free slots and a "now" line.
- DataTable: `loading` skeleton rows and `renderCard` for narrow screens.
- Type scale tokens text-ui (13px), text-2xs (11px), text-3xs (10px) replace
  arbitrary text-[Npx] across the kit.
- Window shell, sidebar and frames use overflow-clip, so scrollIntoView and
  focus can no longer shift them; dark theme frame gets a faint ring.
- PatientPanel actions wrap on phones, pill ContentTabs cap at full width,
  DateRangeInput no longer shrinks in a flex row.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
Ilya Mukhortov 2026-10-25 16:57:30 +10:00
parent 1d9c935b1e
commit 8945b16425
26 changed files with 545 additions and 40 deletions

View File

@ -18,7 +18,7 @@ src/styles.css тема (токены, шрифты, тёмный режим)
Пакет ставится прямо из git, версии — теги `vX.Y.Z`:
```bash
npm i "git+https://git.med-logic.ru/medlogic/medkit.git#semver:^0.6.0"
npm i "git+https://git.med-logic.ru/medlogic/medkit.git#semver:^0.7.0"
```
`package-lock.json` фиксирует коммит; обновиться до свежего тега — `npm update @medkit/ui`. В medicine-ui kit подключён git-submodule в `packages/medkit` (npm workspace) — правки видны сразу.

View File

@ -1,6 +1,6 @@
{
"name": "@medkit/ui",
"version": "0.6.0",
"version": "0.7.0",
"private": true,
"description": "Medkit — UI kit МИС «Медицина»: React 19 + Tailwind 4 + Radix (shadcn/ui)",
"repository": {

View File

@ -71,7 +71,7 @@ export function ColumnChart({
return (
<div ref={ref} data-chart-root className={cn("relative select-none", className)} style={{ height }}>
{width > 0 && (
<svg width={width} height={height} className="block overflow-visible text-[10px]">
<svg width={width} height={height} className="block overflow-visible text-3xs">
{ticks.map((t) => (
<g key={t}>
<line x1={pad.left} x2={width - pad.right} y1={y(t)} y2={y(t)} stroke="var(--chart-grid)" />

View File

@ -45,12 +45,12 @@ export function AppShell({
return (
<div
className={cn(
"flex h-svh overflow-hidden bg-sidebar print:block print:h-auto print:overflow-visible print:bg-transparent",
"flex h-svh overflow-clip bg-sidebar print:block print:h-auto print:overflow-visible print:bg-transparent",
className,
)}
>
<AppSidebar {...sidebar} collapsed={collapsed || narrow} onToggle={toggle} />
<main className="flex min-h-0 min-w-0 flex-1 flex-col overflow-hidden bg-background lg:my-2 lg:mr-2 lg:rounded-2xl print:m-0 print:block print:overflow-visible print:rounded-none print:bg-transparent">
<main className="flex min-h-0 min-w-0 flex-1 flex-col overflow-clip bg-background lg:my-2 lg:mr-2 lg:rounded-2xl dark:lg:ring-1 dark:lg:ring-white/6 print:m-0 print:block print:overflow-visible print:rounded-none print:bg-transparent">
{children}
</main>
</div>

View File

@ -92,7 +92,7 @@ export function AppSidebar({
return (
<aside
className={cn(
"flex h-svh shrink-0 flex-col overflow-hidden bg-sidebar text-sidebar-foreground transition-[width] duration-200 print:hidden",
"flex h-svh shrink-0 flex-col overflow-clip bg-sidebar text-sidebar-foreground transition-[width] duration-200 print:hidden",
collapsed ? "w-[60px]" : "w-56",
className,
)}
@ -135,7 +135,7 @@ export function AppSidebar({
{collapsed ? (
<div className="mx-auto mb-1.5 h-px w-6 bg-sidebar-border group-first/nav:hidden" />
) : (
<div className="mb-1 px-3 text-[10px] font-semibold tracking-[0.14em] text-sidebar-muted uppercase">
<div className="mb-1 px-3 text-3xs font-semibold tracking-[0.14em] text-sidebar-muted uppercase">
{group.label}
</div>
)}
@ -227,8 +227,8 @@ function SidebarLink({ item, collapsed }: { item: SidebarNavItem; collapsed: boo
"grid place-items-center rounded-full font-semibold tabular-nums",
item.badgeTone === "warning" ? "bg-warning text-sidebar" : "bg-coral text-white",
collapsed
? "absolute top-0.5 right-1 min-w-4 px-1 text-[10px] leading-4 ring-2 ring-sidebar"
: "ml-auto min-w-5 px-1.5 text-[11px] leading-5",
? "absolute top-0.5 right-1 min-w-4 px-1 text-3xs leading-4 ring-2 ring-sidebar"
: "ml-auto min-w-5 px-1.5 text-2xs leading-5",
)}
>
{count > 999 ? "999+" : count}
@ -237,7 +237,7 @@ function SidebarLink({ item, collapsed }: { item: SidebarNavItem; collapsed: boo
collapsed ? (
<span className="absolute top-1 right-1.5 size-2 rounded-full bg-sidebar-primary ring-2 ring-sidebar" />
) : (
<span className="ml-auto rounded-md bg-white/10 px-1.5 text-[11px] leading-5 font-semibold text-sidebar-foreground">
<span className="ml-auto rounded-md bg-white/10 px-1.5 text-2xs leading-5 font-semibold text-sidebar-foreground">
{tabs.length}
</span>
)
@ -254,7 +254,7 @@ function SidebarLink({ item, collapsed }: { item: SidebarNavItem; collapsed: boo
<li
key={tab.id}
className={cn(
"group/item flex h-7 items-center rounded-md text-[13px] transition-colors",
"group/item flex h-7 items-center rounded-md text-ui transition-colors",
here ? "bg-white/[0.06] text-white" : "text-sidebar-muted hover:bg-white/[0.03] hover:text-sidebar-foreground",
)}
>
@ -289,7 +289,7 @@ function SidebarLink({ item, collapsed }: { item: SidebarNavItem; collapsed: boo
<DropdownMenuTrigger asChild>
<button
type="button"
className="flex h-6 w-full items-center gap-1.5 rounded-md px-2 text-[11px] text-sidebar-muted transition hover:bg-white/[0.03] hover:text-sidebar-foreground data-[state=open]:text-sidebar-foreground"
className="flex h-6 w-full items-center gap-1.5 rounded-md px-2 text-2xs text-sidebar-muted transition hover:bg-white/[0.03] hover:text-sidebar-foreground data-[state=open]:text-sidebar-foreground"
>
ещё {hidden.length}
{hidden.some((t) => t.alert) && <span className="size-1.5 rounded-full bg-coral" />}

View File

@ -47,7 +47,7 @@ const toneClass: Record<ChipTone, Record<ChipVariant | "hover", string>> = {
}
const sizeClass = {
sm: { root: "h-5 gap-1 px-1.5 text-[11px]", remove: "pr-0.5", x: "size-4" },
sm: { root: "h-5 gap-1 px-1.5 text-2xs", remove: "pr-0.5", x: "size-4" },
md: { root: "h-6 gap-1.5 px-2.5 text-xs", remove: "pr-1", x: "size-4.5" },
}
@ -100,7 +100,7 @@ export function Chip({
<>
{icon}
{children}
{count != null && <span className="font-mono text-[11px] tabular-nums opacity-70">{count}</span>}
{count != null && <span className="font-mono text-2xs tabular-nums opacity-70">{count}</span>}
</>
)

View File

@ -7,7 +7,7 @@ import { copyToClipboard } from "../lib/clipboard"
export function CodeBlock({ code, className }: { code: string; className?: string }) {
return (
<div className={cn("group relative", className)}>
<pre className="overflow-x-auto rounded-xl bg-muted/70 p-4 font-mono text-[13px] leading-relaxed text-foreground/90">
<pre className="overflow-x-auto rounded-xl bg-muted/70 p-4 font-mono text-ui leading-relaxed text-foreground/90">
<code>{code}</code>
</pre>
<button

View File

@ -38,7 +38,7 @@ export function ContentTabs<T extends string>({
className={cn(
"scrollbar-none flex shrink-0 items-center gap-1 overflow-x-auto",
variant === "line" && "border-b px-3",
variant === "pill" && "w-fit rounded-xl bg-muted/70 p-1",
variant === "pill" && "w-fit max-w-full rounded-xl bg-muted/70 p-1",
className,
)}
>
@ -68,7 +68,7 @@ export function ContentTabs<T extends string>({
{tab.count !== undefined && (
<span
className={cn(
"rounded-md px-1.5 text-[11px] leading-5 font-semibold tabular",
"rounded-md px-1.5 text-2xs leading-5 font-semibold tabular",
active ? "bg-primary/10 text-primary" : "bg-muted text-muted-foreground",
)}
>

View File

@ -2,6 +2,9 @@ import * as React from "react"
import { ArrowDownIcon, ArrowUpIcon, ChevronsUpDownIcon } from "lucide-react"
import { cn } from "../lib/utils"
import { useMediaQuery } from "../hooks/use-media-query"
import { Skeleton } from "../ui/skeleton"
import { EmptyState } from "./empty-state"
export type SortDirection = "asc" | "desc"
@ -48,6 +51,8 @@ export function nextSort(current: SortState | null, id: string): SortState | nul
* Таблица кита: липкая шапка, сортировка по клику на заголовок,
* кликабельные строки. Строки передаются уже отсортированными/порезанными
* (см. sortRows) — так таблица одинаково работает с пагинацией и без неё.
* `empty` — строка (станет EmptyState) или свой EmptyState; `loading` без строк — скелетоны;
* `renderCard` — на узком экране (< 768px) строки показываются карточками.
*/
export function DataTable<T>({
columns,
@ -59,6 +64,8 @@ export function DataTable<T>({
rowProps,
rowClassName,
empty,
loading,
renderCard,
className,
}: {
columns: readonly DataColumn<T>[]
@ -70,8 +77,49 @@ export function DataTable<T>({
rowProps?: (row: T, index: number) => React.HTMLAttributes<HTMLTableRowElement>
rowClassName?: (row: T, index: number) => string | false | undefined
empty?: React.ReactNode
/** Первая загрузка: вместо пустого состояния — строки-скелетоны. */
loading?: boolean
/** Карточка строки для узкого экрана; без неё таблица остаётся таблицей. */
renderCard?: (row: T, index: number) => React.ReactNode
className?: string
}) {
const narrow = useMediaQuery("(max-width: 767px)")
const skeleton = loading && !rows.length
const emptyNode =
typeof empty === "string" ? <EmptyState size="sm" title={empty} /> : empty
if (renderCard && narrow) {
return (
<ul className={cn("divide-y divide-border/60 text-sm", className)}>
{skeleton &&
Array.from({ length: 5 }, (_, i) => (
<li key={i} className="space-y-2 px-4 py-3">
<Skeleton className="h-4 w-2/3" />
<Skeleton className="h-3 w-1/2" />
</li>
))}
{rows.map((row, i) => {
const extra = rowProps?.(row, i)
return (
<li
key={getRowId(row)}
onClick={onRowClick ? (e) => onRowClick(row, e) : undefined}
className={cn(
"px-4 py-3 transition-colors",
onRowClick && "cursor-pointer active:bg-muted/60",
rowClassName?.(row, i),
extra?.className,
)}
>
{renderCard(row, i)}
</li>
)
})}
{!rows.length && !skeleton && emptyNode && <li>{emptyNode}</li>}
</ul>
)
}
return (
<table className={cn("w-full text-sm", className)}>
<thead className="sticky top-0 z-10 border-b bg-card/95 backdrop-blur">
@ -128,11 +176,19 @@ export function DataTable<T>({
</tr>
)
})}
{!rows.length && empty && (
{skeleton &&
Array.from({ length: 6 }, (_, i) => (
<tr key={i} className="border-b border-border/60 last:border-b-0">
{columns.map((col, c) => (
<td key={col.id} className="px-3 py-3.5 first:pl-5 last:pr-5">
<Skeleton className={cn("h-3.5", c === 0 ? "w-12" : c % 2 ? "w-3/4" : "w-1/2")} />
</td>
))}
</tr>
))}
{!rows.length && !skeleton && emptyNode && (
<tr>
<td colSpan={columns.length} className="py-12 text-center text-sm text-muted-foreground">
{empty}
</td>
<td colSpan={columns.length}>{emptyNode}</td>
</tr>
)}
</tbody>

View File

@ -17,14 +17,14 @@ export function DateLeaf({ date, upcoming }: { date: string; upcoming?: boolean
>
<div
className={cn(
"w-full py-1 text-[10px] font-semibold uppercase",
"w-full py-1 text-3xs font-semibold uppercase",
upcoming ? "bg-primary text-primary-foreground" : "bg-muted text-muted-foreground",
)}
>
{weekday}
</div>
<div className="pt-1.5 text-lg font-semibold tabular">{d}</div>
<div className="pb-1.5 text-[10px] text-muted-foreground">
<div className="pb-1.5 text-3xs text-muted-foreground">
{MONTHS[m - 1]} {String(y).slice(2)}
</div>
</div>

View File

@ -97,7 +97,7 @@ export function DateRangeInput({
return (
<Popover open={popover.open} onOpenChange={popover.setOpen}>
<PopoverAnchor asChild>
<InputGroup data-disabled={disabled} className={cn("w-fit", className)}>
<InputGroup data-disabled={disabled} className={cn("w-fit shrink-0", className)}>
<InputGroupInput
ref={popover.returnFocus}
aria-label="С"

76
src/kit/empty-state.tsx Normal file
View File

@ -0,0 +1,76 @@
import * as React from "react"
import type { LucideIcon } from "lucide-react"
import { cn } from "../lib/utils"
/**
* Пустое состояние: иконка в плитке, заголовок, пояснение, действия.
* `tone="primary"` — приглашение начать (поиск, первый объект), `muted` — «ничего нет / не нашли».
* `size="sm"` — внутри таблицы, списка или InfoSection; `md` — на всю область раздела.
*/
export function EmptyState({
icon: Icon,
badge: Badge,
title,
description,
action,
tone = "muted",
size = "md",
className,
children,
}: {
icon?: LucideIcon
/** Маленькая иконка в углу плитки — уточняет смысл («пациент» + «поиск»). */
badge?: LucideIcon
title: React.ReactNode
description?: React.ReactNode
/** Кнопки под текстом. */
action?: React.ReactNode
tone?: "primary" | "muted"
size?: "sm" | "md"
className?: string
/** Дополнительное содержимое между пояснением и действиями: примеры, подсказки. */
children?: React.ReactNode
}) {
const sm = size === "sm"
return (
<div
data-slot="empty-state"
className={cn(
"mx-auto flex w-full flex-col items-center text-center text-balance",
sm ? "max-w-sm px-4 py-8" : "max-w-xl px-6 py-12",
className,
)}
>
{Icon && (
<div
className={cn(
"relative grid shrink-0 place-items-center",
sm ? "mb-3 size-10 rounded-xl" : "mb-5 size-16 rounded-2xl",
tone === "primary" ? "bg-accent text-primary" : "bg-muted text-muted-foreground",
)}
>
<Icon className={sm ? "size-5" : "size-7"} />
{Badge && (
<span
className={cn(
"absolute grid place-items-center rounded-lg border-card bg-primary text-primary-foreground",
sm ? "-right-1.5 -bottom-1.5 size-5 border-2" : "-right-1 -bottom-1 size-7 border-4",
)}
>
<Badge className={sm ? "size-2.5" : "size-3"} />
</span>
)}
</div>
)}
<div className={cn("font-semibold text-foreground", sm ? "text-sm" : "text-lg")}>{title}</div>
{description && (
<div className={cn("mt-1 text-muted-foreground", sm ? "text-xs" : "text-sm")}>{description}</div>
)}
{children && <div className={sm ? "mt-3" : "mt-5"}>{children}</div>}
{action && (
<div className={cn("flex flex-wrap items-center justify-center gap-2", sm ? "mt-3" : "mt-6")}>{action}</div>
)}
</div>
)
}

View File

@ -177,7 +177,7 @@ function FileTile({
<span className="grid size-full place-items-center text-muted-foreground">
<span className="flex flex-col items-center gap-1.5">
<Icon className={cn(size === "sm" ? "size-5" : "size-7")} />
<span className="text-[10px] font-semibold tracking-wider">{extension(file)}</span>
<span className="text-3xs font-semibold tracking-wider">{extension(file)}</span>
</span>
</span>
)}
@ -191,7 +191,7 @@ function FileTile({
<div className="truncate text-xs text-muted-foreground" title={file.name}>
{file.name}
</div>
<div className="mt-0.5 flex items-center justify-between text-[11px] text-muted-foreground tabular">
<div className="mt-0.5 flex items-center justify-between text-2xs text-muted-foreground tabular">
{formatBytes(file.size)}
{file.src && (
<a

91
src/kit/filter-bar.tsx Normal file
View File

@ -0,0 +1,91 @@
import * as React from "react"
import { RotateCwIcon, SlidersHorizontalIcon } from "lucide-react"
import { cn } from "../lib/utils"
import { Button } from "../ui/button"
import { Popover, PopoverContent, PopoverTrigger } from "../ui/popover"
/** Ширина элемента; меряется до отрисовки, чтобы панель не мигала при первом показе. */
function useWidth(ref: React.RefObject<HTMLElement | null>) {
const [width, setWidth] = React.useState<number | null>(null)
React.useLayoutEffect(() => {
const el = ref.current
if (!el) return
setWidth(el.clientWidth)
const observer = new ResizeObserver(([entry]) => setWidth(entry.contentRect.width))
observer.observe(el)
return () => observer.disconnect()
}, [ref])
return width
}
/**
* Панель фильтров списка: основные фильтры в строку, второстепенные (`more`) —
* в строку на широкой панели и в поповер «Ещё» на узкой, «Сбросить» — всегда последней.
* Поиску внутри дают `className="min-w-40 flex-1"` — он забирает свободное место.
*/
export function FilterBar({
more,
moreCount = 0,
collapseAt = 1100,
activeCount = 0,
onReset,
className,
children,
}: {
/** Второстепенные фильтры: переключатели «Онлайн», «Мои задачи»… */
more?: React.ReactNode
/** Сколько из `more` включено — счётчик на кнопке «Ещё». */
moreCount?: number
/** Ширина панели (px), ниже которой `more` уходит в поповер. */
collapseAt?: number
/** Сколько фильтров отличается от умолчания — счётчик и доступность «Сбросить». */
activeCount?: number
/** Без него кнопки «Сбросить» нет. */
onReset?: () => void
className?: string
children: React.ReactNode
}) {
const ref = React.useRef<HTMLDivElement>(null)
const width = useWidth(ref)
const collapsed = more != null && width != null && width < collapseAt
return (
<div ref={ref} data-slot="filter-bar" className={cn("flex items-start gap-2.5", className)}>
{/* Фильтры переносятся внутри своего блока — «Сбросить» не уезжает одна на вторую строку. */}
<div className="flex min-w-0 flex-1 flex-wrap items-center gap-2.5">
{children}
{more != null && !collapsed && <div className="flex items-center gap-4 px-1">{more}</div>}
{collapsed && (
<Popover>
<PopoverTrigger asChild>
<Button variant="outline" size="sm" className="shrink-0">
<SlidersHorizontalIcon /> Ещё
{moreCount > 0 && <Count value={moreCount} />}
</Button>
</PopoverTrigger>
<PopoverContent align="end" className="flex w-auto min-w-52 flex-col items-start gap-3 p-3">
{more}
</PopoverContent>
</Popover>
)}
</div>
{onReset && (
<div className="flex h-9 shrink-0 items-center">
<Button variant="ghost" size="sm" disabled={!activeCount} onClick={onReset} className="text-muted-foreground">
<RotateCwIcon /> Сбросить
{activeCount > 0 && <Count value={activeCount} />}
</Button>
</div>
)}
</div>
)
}
function Count({ value }: { value: number }) {
return (
<span className="grid min-w-4.5 place-items-center rounded-full bg-primary px-1 text-2xs font-semibold text-primary-foreground tabular">
{value}
</span>
)
}

View File

@ -13,8 +13,10 @@ export * from "./date-input"
export * from "./date-leaf"
export * from "./date-range-input"
export * from "./edit-dialog"
export * from "./empty-state"
export * from "./file-drop"
export * from "./file-gallery"
export * from "./filter-bar"
export * from "./form-field"
export * from "./info-section"
export * from "./loading-bar"
@ -30,6 +32,7 @@ export * from "./patient-panel"
export * from "./patient-picker"
export * from "./person-chip"
export * from "./save-bar"
export * from "./schedule-grid"
export * from "./search-field"
export * from "./search-input"
export * from "./section-frame"

View File

@ -29,7 +29,7 @@ export function PageFrame({
}) {
return (
<div className="flex min-h-0 flex-1 flex-col p-2 lg:p-3">
<div className="flex min-h-0 flex-1 flex-col overflow-hidden rounded-xl border bg-card shadow-[0_1px_2px_rgba(15,40,60,0.04)]">
<div className="flex min-h-0 flex-1 flex-col overflow-clip rounded-xl border bg-card shadow-[0_1px_2px_rgba(15,40,60,0.04)]">
<header className="flex h-12 shrink-0 items-center gap-2 border-b px-4">
{Icon && <Icon className="size-4 text-primary" />}
<h1 className="text-sm font-semibold">{title}</h1>

View File

@ -38,9 +38,9 @@ const toneClass: Record<PageTabTone, string> = {
export const MAX_VISIBLE_TABS = 4
const CHIP_CLASS =
"group/tab relative flex h-8 max-w-56 shrink-0 cursor-pointer items-center gap-2 rounded-lg px-2.5 text-[13px] font-medium outline-none select-none"
"group/tab relative flex h-8 max-w-56 shrink-0 cursor-pointer items-center gap-2 rounded-lg px-2.5 text-ui font-medium outline-none select-none"
const MORE_CLASS =
"flex h-8 shrink-0 items-center gap-1 rounded-lg px-2.5 text-[13px] font-medium text-muted-foreground transition-colors outline-none hover:bg-muted hover:text-foreground focus-visible:ring-2 focus-visible:ring-ring/60 data-[state=open]:bg-muted data-[state=open]:text-foreground"
"flex h-8 shrink-0 items-center gap-1 rounded-lg px-2.5 text-ui font-medium text-muted-foreground transition-colors outline-none hover:bg-muted hover:text-foreground focus-visible:ring-2 focus-visible:ring-ring/60 data-[state=open]:bg-muted data-[state=open]:text-foreground"
// Должны совпадать с разметкой: gap-1 между чипами, разделитель mx-1 w-px после закреплённых.
const GAP = 4
const SEPARATOR = 9
@ -267,7 +267,7 @@ function TabFace({
) : (
<span
className={cn(
"relative grid size-5 shrink-0 place-items-center rounded-md text-[11px] font-semibold",
"relative grid size-5 shrink-0 place-items-center rounded-md text-2xs font-semibold",
toneClass[tab.tone ?? "neutral"],
)}
>
@ -352,7 +352,7 @@ function OverflowTabs({
) : (
<span
className={cn(
"relative grid size-5 shrink-0 place-items-center rounded-md text-[11px] font-semibold",
"relative grid size-5 shrink-0 place-items-center rounded-md text-2xs font-semibold",
toneClass[tab.tone ?? "neutral"],
)}
>

View File

@ -77,7 +77,7 @@ export function PatientPanel<T extends string>({
</span>
</div>
<div className="mt-0.5 flex flex-wrap items-center gap-x-4 text-[13px] text-muted-foreground">
<div className="mt-0.5 flex flex-wrap items-center gap-x-4 text-ui text-muted-foreground">
{p.phone && (
<a href={`tel:${p.phone}`} className="inline-flex items-center gap-1.5 text-primary hover:underline">
<PhoneIcon className="size-3.5" />
@ -115,7 +115,7 @@ export function PatientPanel<T extends string>({
</div>
</div>
{actions && <div className="flex items-center gap-2">{actions}</div>}
{actions && <div className="flex min-w-0 flex-wrap items-center gap-2 max-sm:w-full">{actions}</div>}
</div>
</header>

View File

@ -44,7 +44,7 @@ export function PersonChip({
className,
)}
>
<PersonAvatar name={name} className="size-6 text-[10px]" />
<PersonAvatar name={name} className="size-6 text-3xs" />
{name}
{onRemove && (
<button

267
src/kit/schedule-grid.tsx Normal file
View File

@ -0,0 +1,267 @@
import * as React from "react"
import { PlusIcon } from "lucide-react"
import { cn } from "../lib/utils"
import { ScrollArea } from "../ui/scroll-area"
import type { StatusTone } from "./status-badge"
/** Время «ЧЧ:ММ». */
type Clock = string
export interface ScheduleGridResource {
readonly id: string | number
readonly title: React.ReactNode
readonly subtitle?: React.ReactNode
/** Рабочие часы; вне них колонка заштрихована. */
readonly hours?: readonly { readonly from: Clock; readonly to: Clock }[]
/** Свободные слоты — по клику `onSlotClick`. */
readonly slots?: readonly { readonly start: Clock; readonly end: Clock }[]
/** Отметка вместо рабочих часов: «Отпуск», «Не работает». */
readonly note?: React.ReactNode
}
export interface ScheduleGridEvent {
readonly id: React.Key
readonly resourceId: string | number
readonly start: Clock
readonly end: Clock
readonly title: React.ReactNode
readonly subtitle?: React.ReactNode
readonly tone?: StatusTone
/** Отменённая запись: бледная и зачёркнутая. */
readonly muted?: boolean
}
const toneClass: Record<StatusTone, string> = {
positive: "border-l-success bg-success-soft",
info: "border-l-info bg-info-soft",
warning: "border-l-warning bg-warning-soft",
negative: "border-l-coral bg-coral-soft",
neutral: "border-l-muted-foreground/50 bg-muted",
}
const minutes = (t: Clock) => Number(t.slice(0, 2)) * 60 + Number(t.slice(3, 5))
/** Раскладка пересекающихся записей одного врача по дорожкам: `lane` из `lanes`. */
function layoutLanes(events: readonly ScheduleGridEvent[]) {
const sorted = events.toSorted((a, b) => minutes(a.start) - minutes(b.start) || minutes(b.end) - minutes(a.end))
const result = new Map<React.Key, { lane: number; lanes: number }>()
let cluster: ScheduleGridEvent[] = []
let laneEnds: number[] = []
let clusterEnd = -1
const flush = () => {
for (const e of cluster) result.set(e.id, { lane: result.get(e.id)!.lane, lanes: laneEnds.length })
cluster = []
laneEnds = []
}
for (const e of sorted) {
const start = minutes(e.start)
if (start >= clusterEnd) flush()
let lane = laneEnds.findIndex((end) => end <= start)
if (lane < 0) lane = laneEnds.push(0) - 1
laneEnds[lane] = minutes(e.end)
clusterEnd = Math.max(clusterEnd, minutes(e.end))
cluster.push(e)
result.set(e.id, { lane, lanes: 0 })
}
flush()
return result
}
/** Границы сетки: от первого рабочего часа/записи до последнего, с округлением до часа. */
function gridBounds(resources: readonly ScheduleGridResource[], events: readonly ScheduleGridEvent[]) {
const starts = [...resources.flatMap((r) => r.hours?.map((h) => minutes(h.from)) ?? []), ...events.map((e) => minutes(e.start))]
const ends = [...resources.flatMap((r) => r.hours?.map((h) => minutes(h.to)) ?? []), ...events.map((e) => minutes(e.end))]
if (!starts.length) return { from: 8 * 60, to: 20 * 60 }
return { from: Math.floor(Math.min(...starts) / 60) * 60, to: Math.ceil(Math.max(...ends) / 60) * 60 }
}
const clock = (m: number) => `${String(Math.floor(m / 60)).padStart(2, "0")}:${String(m % 60).padStart(2, "0")}`
/**
* Сетка дня: колонки — врачи (кабинеты, аппараты), строки — время.
* Записи — плашки цвета статуса, свободные слоты кликабельны, линия «сейчас».
* Шапка и шкала времени липкие; при открытии сетка прокручивается к первой записи или к текущему времени.
*/
export function ScheduleGrid({
resources,
events,
from,
to,
minuteHeight = 1.8,
now,
selectedId,
onEventClick,
onSlotClick,
scrollKey,
empty,
className,
}: {
resources: readonly ScheduleGridResource[]
events: readonly ScheduleGridEvent[]
/** Начало и конец шкалы; по умолчанию — по рабочим часам и записям. */
from?: Clock
to?: Clock
/** Высота минуты в пикселях. */
minuteHeight?: number
/** Текущее время — красная линия; только для сегодняшнего дня. */
now?: Clock
selectedId?: React.Key | null
onEventClick?: (event: ScheduleGridEvent) => void
onSlotClick?: (resource: ScheduleGridResource, slot: { start: Clock; end: Clock }) => void
/** Смена ключа (дата) — заново прокрутить к первой записи. */
scrollKey?: React.Key
/** Нет ни одной колонки. */
empty?: React.ReactNode
className?: string
}) {
const auto = gridBounds(resources, events)
const start = from ? minutes(from) : auto.from
const end = to ? minutes(to) : auto.to
const height = (end - start) * minuteHeight
const y = (t: Clock) => (minutes(t) - start) * minuteHeight
// Дорожки считаются по каждой колонке отдельно.
const lanes = React.useMemo(() => {
const ids = [...new Set(events.map((e) => e.resourceId))]
return new Map(ids.flatMap((id) => [...layoutLanes(events.filter((e) => e.resourceId === id))]))
}, [events])
const hours = Array.from({ length: Math.floor((end - start) / 60) + 1 }, (_, i) => start + i * 60)
const nowY = now && minutes(now) >= start && minutes(now) <= end ? y(now) : null
const grid = React.useRef<HTMLDivElement>(null)
const firstEvent = events.length ? Math.min(...events.map((e) => minutes(e.start))) : null
const focus = nowY != null ? minutes(now!) - 45 : firstEvent != null ? firstEvent - 30 : start
const focusTop = Math.max(0, (focus - start) * minuteHeight)
// Крутим только свой вьюпорт: scrollIntoView сдвинул бы и каркас окна.
React.useLayoutEffect(() => {
const viewport = grid.current?.closest<HTMLElement>('[data-slot="scroll-area-viewport"]')
if (viewport) viewport.scrollTop = focusTop
// eslint-disable-next-line react-hooks/exhaustive-deps -- только при смене дня
}, [scrollKey])
if (!resources.length) return <>{empty}</>
// Линии сетки: час — сплошная, полчаса — бледная.
const lines = {
backgroundImage: `linear-gradient(to bottom, var(--border) 1px, transparent 1px), linear-gradient(to bottom, color-mix(in oklab, var(--border) 45%, transparent) 1px, transparent 1px)`,
backgroundSize: `100% ${60 * minuteHeight}px, 100% ${30 * minuteHeight}px`,
}
return (
<ScrollArea horizontal className={cn("min-h-0 flex-1", className)}>
<div
ref={grid}
className="grid min-w-full"
style={{ gridTemplateColumns: `3.5rem repeat(${resources.length}, minmax(11rem, 1fr))` }}
>
<div className="sticky top-0 left-0 z-30 border-r border-b bg-card" />
{resources.map((r) => (
<div key={r.id} className="sticky top-0 z-20 min-w-0 border-r border-b bg-card/95 px-3 py-2 backdrop-blur last:border-r-0">
<div className="truncate text-sm font-semibold">{r.title}</div>
{r.subtitle && <div className="truncate text-xs text-muted-foreground">{r.subtitle}</div>}
</div>
))}
<div className="sticky left-0 z-10 border-r bg-card" style={{ height }}>
{hours.map((m, i) => (
<span
key={m}
className={cn(
"absolute right-2 font-mono text-2xs text-muted-foreground tabular",
i > 0 && "-translate-y-1/2",
)}
style={{ top: (m - start) * minuteHeight + (i === 0 ? 2 : 0) }}
>
{clock(m)}
</span>
))}
{nowY != null && (
<span
className="absolute right-1 z-10 -translate-y-1/2 rounded bg-coral px-1 font-mono text-2xs font-semibold text-white tabular"
style={{ top: nowY }}
>
{now}
</span>
)}
</div>
{resources.map((r) => (
<div
key={r.id}
className="relative border-r bg-[repeating-linear-gradient(135deg,var(--muted)_0_6px,transparent_6px_12px)] last:border-r-0"
style={{ height }}
>
{r.hours?.map((h) => (
<div
key={`${h.from}-${h.to}`}
className="absolute inset-x-0 bg-card"
style={{ top: y(h.from), height: (minutes(h.to) - minutes(h.from)) * minuteHeight }}
/>
))}
<div className="pointer-events-none absolute inset-0" style={lines} />
{r.note && (
<div className="sticky top-16 z-[1] mx-2 mt-3 rounded-md bg-card/90 px-2 py-1 text-center text-xs text-muted-foreground shadow-sm">
{r.note}
</div>
)}
{r.slots?.map((s) => (
<button
key={s.start}
type="button"
disabled={!onSlotClick}
onClick={() => onSlotClick?.(r, s)}
className="group/slot absolute inset-x-1 flex items-center gap-1 rounded-md border border-dashed border-transparent px-1.5 text-2xs font-medium text-primary transition-colors hover:border-primary/40 hover:bg-accent/70 focus-visible:border-primary focus-visible:outline-none disabled:pointer-events-none"
style={{ top: y(s.start) + 1, height: (minutes(s.end) - minutes(s.start)) * minuteHeight - 2 }}
aria-label={`Записать на ${s.start}`}
>
<span className="flex items-center gap-1 opacity-0 transition-opacity group-hover/slot:opacity-100 group-focus-visible/slot:opacity-100">
<PlusIcon className="size-3" />
<span className="font-mono tabular">{s.start}</span>
</span>
</button>
))}
{events
.filter((e) => e.resourceId === r.id)
.map((e) => {
const place = lanes.get(e.id) ?? { lane: 0, lanes: 1 }
const h = (minutes(e.end) - minutes(e.start)) * minuteHeight
return (
<button
key={e.id}
type="button"
onClick={() => onEventClick?.(e)}
className={cn(
"absolute overflow-hidden rounded-md border-l-[3px] px-1.5 text-left text-xs leading-tight shadow-[0_1px_2px_rgba(15,40,60,0.06)] transition hover:z-10 hover:shadow-md focus-visible:z-10 focus-visible:ring-[3px] focus-visible:ring-ring/50 focus-visible:outline-none",
toneClass[e.tone ?? "neutral"],
e.muted && "opacity-55",
e.id === selectedId && "z-10 ring-2 ring-primary",
)}
style={{
top: y(e.start) + 1,
height: Math.max(h - 2, 14),
left: `calc(${(place.lane / place.lanes) * 100}% + 4px)`,
width: `calc(${100 / place.lanes}% - 8px)`,
}}
>
<div className={cn("flex min-w-0 items-baseline gap-1.5", h >= 30 ? "pt-1" : "pt-px")}>
<span className="shrink-0 font-mono text-2xs text-muted-foreground tabular">{e.start}</span>
<span className={cn("truncate font-semibold", e.muted && "line-through")}>{e.title}</span>
</div>
{e.subtitle && h >= 40 && <div className="truncate text-2xs text-muted-foreground">{e.subtitle}</div>}
</button>
)
})}
{nowY != null && (
<div className="pointer-events-none absolute inset-x-0 z-[5] h-0.5 bg-coral" style={{ top: nowY - 1 }} />
)}
</div>
))}
</div>
</ScrollArea>
)
}

View File

@ -48,7 +48,7 @@ export function SectionFrame({ bar, children }: { bar: React.ReactNode; children
>
<div
className={cn(
"flex min-h-0 flex-1 flex-col overflow-hidden rounded-xl border bg-card shadow-[0_1px_2px_rgba(15,40,60,0.04)]",
"flex min-h-0 flex-1 flex-col overflow-clip rounded-xl border bg-card shadow-[0_1px_2px_rgba(15,40,60,0.04)]",
maximized && "duration-200 animate-in zoom-in-[0.98]",
)}
>

View File

@ -85,7 +85,7 @@ export function ServiceLinesTable({
<div className={cn(struck && "line-through decoration-muted-foreground/50")}>
<span className="font-mono text-xs text-muted-foreground">{line.code}</span> {line.name}
</div>
<span className="mt-1 inline-block rounded bg-muted px-1.5 py-px text-[11px] font-medium text-muted-foreground">
<span className="mt-1 inline-block rounded bg-muted px-1.5 py-px text-2xs font-medium text-muted-foreground">
{line.category}
</span>
{compact && line.price > 0 && (
@ -126,7 +126,7 @@ export function ServiceLinesTable({
<td className="text-right whitespace-nowrap">
<div className="font-medium tabular">{line.price ? formatMoney(line.price * line.quantity) : "ОМС"}</div>
{showStatus && line.price > 0 && (
<StatusBadge tone={SERVICE_LINE_STATUS[status].tone} dot={false} className="mt-1 px-1.5 text-[11px]">
<StatusBadge tone={SERVICE_LINE_STATUS[status].tone} dot={false} className="mt-1 px-1.5 text-2xs">
{SERVICE_LINE_STATUS[status].label}
</StatusBadge>
)}

View File

@ -181,7 +181,7 @@ export function ServicePicker<T extends ServiceOption>({
<span className="font-medium">{item.name}</span>
<span className="mt-0.5 flex flex-wrap items-center gap-1.5 text-xs text-muted-foreground">
{item.funding}
<span className="rounded bg-muted px-1.5 py-px text-[11px] font-medium">{item.category}</span>
<span className="rounded bg-muted px-1.5 py-px text-2xs font-medium">{item.category}</span>
{already && (
<span className="inline-flex items-center gap-0.5 text-primary">
<CheckIcon className="size-3" /> уже добавлена

View File

@ -47,7 +47,7 @@ export function Stepper({
</span>
<span className="min-w-0 leading-tight">
<span className={cn("block text-sm font-medium", !done && !active && "text-muted-foreground")}>{step.label}</span>
{step.hint && <span className="block truncate text-[11px] text-muted-foreground">{step.hint}</span>}
{step.hint && <span className="block truncate text-2xs text-muted-foreground">{step.hint}</span>}
</span>
</button>
</li>

View File

@ -40,7 +40,7 @@ export function TimeRangeInput({
onChange={(e) => onChange({ ...value, from: e.target.value })}
className={input}
/>
<span className="text-[11px] text-muted-foreground">–</span>
<span className="text-2xs text-muted-foreground">–</span>
<input
type="time"
aria-label="По"

View File

@ -120,6 +120,18 @@
--font-sans: "Onest Variable", ui-sans-serif, system-ui, sans-serif;
--font-mono: "JetBrains Mono Variable", ui-monospace, monospace;
/*
* Мелкие размеры между шагами Tailwind — вместо text-[Npx] в разметке:
* text-ui (13px) — вкладки, пункты меню, мета-строки под заголовком;
* text-2xs (11px) — счётчики, подписи осей, бейджи; text-3xs (10px) — метки в плотных сетках.
*/
--text-ui: 0.8125rem;
--text-ui--line-height: 1.125rem;
--text-2xs: 0.6875rem;
--text-2xs--line-height: 1rem;
--text-3xs: 0.625rem;
--text-3xs--line-height: 0.875rem;
--radius-sm: calc(var(--radius) - 4px);
--radius-md: calc(var(--radius) - 2px);
--radius-lg: var(--radius);