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 = { 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() 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(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('[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 (
{resources.map((r) => (
{r.title}
{r.subtitle &&
{r.subtitle}
}
))}
{hours.map((m, i) => ( 0 && "-translate-y-1/2", )} style={{ top: (m - start) * minuteHeight + (i === 0 ? 2 : 0) }} > {clock(m)} ))} {nowY != null && ( {now} )}
{resources.map((r) => (
{r.hours?.map((h) => (
))}
{r.note && (
{r.note}
)} {r.slots?.map((s) => ( ))} {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 ( ) })} {nowY != null && (
)}
))}
) }