ScheduleGrid: drag to pan, scale fills the viewport
Mouse drag scrolls the grid (grab cursor), a drag doesn't trigger event or slot clicks. A short day extends the time scale to the bottom of the viewport instead of leaving empty space. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
parent
b7c038c9d7
commit
9bdaec0fbd
|
|
@ -84,6 +84,8 @@ const clock = (m: number) => `${String(Math.floor(m / 60)).padStart(2, "0")}:${S
|
||||||
* Сетка дня: колонки — врачи (кабинеты, аппараты), строки — время.
|
* Сетка дня: колонки — врачи (кабинеты, аппараты), строки — время.
|
||||||
* Записи — плашки цвета статуса, свободные слоты кликабельны, линия «сейчас».
|
* Записи — плашки цвета статуса, свободные слоты кликабельны, линия «сейчас».
|
||||||
* Шапка и шкала времени липкие; при открытии сетка прокручивается к первой записи или к текущему времени.
|
* Шапка и шкала времени липкие; при открытии сетка прокручивается к первой записи или к текущему времени.
|
||||||
|
* Короткий день шкала дотягивает до низа окна — дальше штриховка нерабочего времени, без пустоты под сеткой.
|
||||||
|
* Мышью сетку можно таскать: зажать и вести в сторону.
|
||||||
*/
|
*/
|
||||||
export function ScheduleGrid({
|
export function ScheduleGrid({
|
||||||
resources,
|
resources,
|
||||||
|
|
@ -101,7 +103,7 @@ export function ScheduleGrid({
|
||||||
}: {
|
}: {
|
||||||
resources: readonly ScheduleGridResource[]
|
resources: readonly ScheduleGridResource[]
|
||||||
events: readonly ScheduleGridEvent[]
|
events: readonly ScheduleGridEvent[]
|
||||||
/** Начало и конец шкалы; по умолчанию — по рабочим часам и записям. */
|
/** Начало и конец шкалы; по умолчанию — по рабочим часам и записям. Если окно выше, шкала продолжается до низа. */
|
||||||
from?: Clock
|
from?: Clock
|
||||||
to?: Clock
|
to?: Clock
|
||||||
/** Высота минуты в пикселях. */
|
/** Высота минуты в пикселях. */
|
||||||
|
|
@ -117,9 +119,25 @@ export function ScheduleGrid({
|
||||||
empty?: React.ReactNode
|
empty?: React.ReactNode
|
||||||
className?: string
|
className?: string
|
||||||
}) {
|
}) {
|
||||||
|
const grid = React.useRef<HTMLDivElement>(null)
|
||||||
|
const viewportOf = () => grid.current?.closest<HTMLElement>('[data-slot="scroll-area-viewport"]')
|
||||||
|
// Сколько минут шкалы помещается в окне под шапкой: короткий день дотягиваем до низа, без пустоты под сеткой.
|
||||||
|
const [fitMinutes, setFitMinutes] = React.useState(0)
|
||||||
|
const hasResources = resources.length > 0
|
||||||
|
React.useLayoutEffect(() => {
|
||||||
|
const viewport = viewportOf()
|
||||||
|
const head = grid.current?.firstElementChild as HTMLElement | null
|
||||||
|
if (!viewport || !head) return
|
||||||
|
const measure = () => setFitMinutes(Math.floor((viewport.clientHeight - head.offsetHeight) / minuteHeight))
|
||||||
|
const observer = new ResizeObserver(measure)
|
||||||
|
observer.observe(viewport)
|
||||||
|
measure()
|
||||||
|
return () => observer.disconnect()
|
||||||
|
}, [minuteHeight, hasResources])
|
||||||
|
|
||||||
const auto = gridBounds(resources, events)
|
const auto = gridBounds(resources, events)
|
||||||
const start = from ? minutes(from) : auto.from
|
const start = from ? minutes(from) : auto.from
|
||||||
const end = to ? minutes(to) : auto.to
|
const end = Math.min(24 * 60, Math.max(to ? minutes(to) : auto.to, start + fitMinutes))
|
||||||
const height = (end - start) * minuteHeight
|
const height = (end - start) * minuteHeight
|
||||||
const y = (t: Clock) => (minutes(t) - start) * minuteHeight
|
const y = (t: Clock) => (minutes(t) - start) * minuteHeight
|
||||||
// Дорожки считаются по каждой колонке отдельно.
|
// Дорожки считаются по каждой колонке отдельно.
|
||||||
|
|
@ -130,17 +148,54 @@ export function ScheduleGrid({
|
||||||
const hours = Array.from({ length: Math.floor((end - start) / 60) + 1 }, (_, i) => start + i * 60)
|
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 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 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 focus = nowY != null ? minutes(now!) - 45 : firstEvent != null ? firstEvent - 30 : start
|
||||||
const focusTop = Math.max(0, (focus - start) * minuteHeight)
|
const focusTop = Math.max(0, (focus - start) * minuteHeight)
|
||||||
// Крутим только свой вьюпорт: scrollIntoView сдвинул бы и каркас окна.
|
// Крутим только свой вьюпорт: scrollIntoView сдвинул бы и каркас окна.
|
||||||
React.useLayoutEffect(() => {
|
React.useLayoutEffect(() => {
|
||||||
const viewport = grid.current?.closest<HTMLElement>('[data-slot="scroll-area-viewport"]')
|
const viewport = viewportOf()
|
||||||
if (viewport) viewport.scrollTop = focusTop
|
if (viewport) viewport.scrollTop = focusTop
|
||||||
// eslint-disable-next-line react-hooks/exhaustive-deps -- только при смене дня
|
// eslint-disable-next-line react-hooks/exhaustive-deps -- только при смене дня
|
||||||
}, [scrollKey])
|
}, [scrollKey])
|
||||||
|
|
||||||
|
// Перетаскивание мышью: зажал и тянешь — сетка едет за курсором.
|
||||||
|
// Пока сдвиг меньше порога, это обычный клик по записи или слоту; после перетаскивания клик гасим.
|
||||||
|
const drag = React.useRef<{ x: number; y: number; left: number; top: number; moved: boolean } | null>(null)
|
||||||
|
const dragged = React.useRef(false)
|
||||||
|
const [dragging, setDragging] = React.useState(false)
|
||||||
|
|
||||||
|
const onPointerDown = (e: React.PointerEvent<HTMLDivElement>) => {
|
||||||
|
const viewport = viewportOf()
|
||||||
|
if (e.pointerType !== "mouse" || e.button !== 0 || !viewport) return
|
||||||
|
if ((e.target as Element).closest('[data-slot="scroll-area-scrollbar"]')) return
|
||||||
|
drag.current = { x: e.clientX, y: e.clientY, left: viewport.scrollLeft, top: viewport.scrollTop, moved: false }
|
||||||
|
}
|
||||||
|
const onPointerMove = (e: React.PointerEvent<HTMLDivElement>) => {
|
||||||
|
const d = drag.current
|
||||||
|
const viewport = viewportOf()
|
||||||
|
if (!d || !viewport) return
|
||||||
|
const dx = e.clientX - d.x
|
||||||
|
const dy = e.clientY - d.y
|
||||||
|
if (!d.moved) {
|
||||||
|
if (Math.hypot(dx, dy) < 5) return
|
||||||
|
d.moved = true
|
||||||
|
setDragging(true)
|
||||||
|
e.currentTarget.setPointerCapture(e.pointerId)
|
||||||
|
window.getSelection()?.removeAllRanges()
|
||||||
|
}
|
||||||
|
viewport.scrollLeft = d.left - dx
|
||||||
|
viewport.scrollTop = d.top - dy
|
||||||
|
}
|
||||||
|
const onPointerUp = () => {
|
||||||
|
if (drag.current?.moved) {
|
||||||
|
dragged.current = true
|
||||||
|
// click приходит сразу после pointerup — к следующему кадру флаг уже не нужен
|
||||||
|
requestAnimationFrame(() => (dragged.current = false))
|
||||||
|
}
|
||||||
|
drag.current = null
|
||||||
|
setDragging(false)
|
||||||
|
}
|
||||||
|
|
||||||
if (!resources.length) return <>{empty}</>
|
if (!resources.length) return <>{empty}</>
|
||||||
|
|
||||||
// Линии сетки: час — сплошная, полчаса — бледная.
|
// Линии сетки: час — сплошная, полчаса — бледная.
|
||||||
|
|
@ -150,7 +205,24 @@ export function ScheduleGrid({
|
||||||
}
|
}
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<ScrollArea horizontal className={cn("min-h-0 flex-1", className)}>
|
// Таскать можно и за пустое место под сеткой — обработчики на всей области, кроме полос прокрутки.
|
||||||
|
<ScrollArea
|
||||||
|
horizontal
|
||||||
|
onPointerDown={onPointerDown}
|
||||||
|
onPointerMove={onPointerMove}
|
||||||
|
onPointerUp={onPointerUp}
|
||||||
|
onPointerCancel={onPointerUp}
|
||||||
|
onClickCapture={(e) => {
|
||||||
|
if (!dragged.current) return
|
||||||
|
e.preventDefault()
|
||||||
|
e.stopPropagation()
|
||||||
|
}}
|
||||||
|
className={cn(
|
||||||
|
"min-h-0 flex-1 [&_[data-slot=scroll-area-viewport]]:cursor-grab",
|
||||||
|
dragging && "select-none [&_*]:cursor-grabbing!",
|
||||||
|
className,
|
||||||
|
)}
|
||||||
|
>
|
||||||
<div
|
<div
|
||||||
ref={grid}
|
ref={grid}
|
||||||
className="grid min-w-full"
|
className="grid min-w-full"
|
||||||
|
|
@ -213,7 +285,7 @@ export function ScheduleGrid({
|
||||||
type="button"
|
type="button"
|
||||||
disabled={!onSlotClick}
|
disabled={!onSlotClick}
|
||||||
onClick={() => onSlotClick?.(r, s)}
|
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"
|
className="group/slot absolute inset-x-1 flex cursor-pointer 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 }}
|
style={{ top: y(s.start) + 1, height: (minutes(s.end) - minutes(s.start)) * minuteHeight - 2 }}
|
||||||
aria-label={`Записать на ${s.start}`}
|
aria-label={`Записать на ${s.start}`}
|
||||||
>
|
>
|
||||||
|
|
@ -235,7 +307,7 @@ export function ScheduleGrid({
|
||||||
type="button"
|
type="button"
|
||||||
onClick={() => onEventClick?.(e)}
|
onClick={() => onEventClick?.(e)}
|
||||||
className={cn(
|
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",
|
"absolute cursor-pointer 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"],
|
toneClass[e.tone ?? "neutral"],
|
||||||
e.muted && "opacity-55",
|
e.muted && "opacity-55",
|
||||||
e.id === selectedId && "z-10 ring-2 ring-primary",
|
e.id === selectedId && "z-10 ring-2 ring-primary",
|
||||||
|
|
|
||||||
Loading…
Reference in New Issue