268 lines
12 KiB
TypeScript
268 lines
12 KiB
TypeScript
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 px-3 py-2 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>
|
||
)
|
||
}
|