Documentation menu
Getting Started
Components
Primitives
- Agent Thinking
- Alert
- Alert Dialog
- Avatar
- Badge
- Breadcrumb
- Button
- Button Group
- Calendar
- Card
- Checkbox
- Command
- Command Palette
- Context Menu
- Data Table
- Dialog
- Dropdown Menu
- Empty
- Field
- Glow Cloud
- Input
- Label
- Medication Schedule
- Period Tabs
- Popover
- Rainbow Button
- Scroll Area
- Select
- Selectable Card
- Separator
- Sheet
- Sidebar
- Skeleton
- Slider
- Sonner
- Spinner
- Switch
- Table
- Tabs
- Tag
- Textarea
- Timeline
- Tooltip
- Use Count Up
Charts and metrics
Patterns
- Confirm Button
- Date Picker
- Embedded
- Empty State
- Entity Drawer
- Error Boundary
- Field Row
- File Dropzone
- Form Dialog
- Kv
- List Editor
- List Page
- Live Time
- Mini Table
- Money
- Note Field
- Note Text
- Page Card
- Page Header
- Page Tabs
- Page Toolbar
- Person Cell
- Picture Field
- Print Card
- Range Switcher
- Row Actions
- Search Input
- Search Select
- Selected Box
- Signature Pad
- Status Badge
- Sub Nav Layout
- Suggest Input
- Tab Icons
- Table Footer
- Theme Accent Picker
- Time Picker
- View All Link
Dashboard cards
Advanced
Device frames
Website widgets
Website screens
Website panels
Advanced
Gantt
A Gantt chart with dependencies, drag to move and resize, and recurring tasks.
import { addDays, startOfWeek } from "date-fns"
import { Gantt } from "@/registry/vcare/ui/gantt/gantt"
import { GanttNav, GanttToolbar } from "@/registry/vcare/ui/gantt/gantt-nav"
import { GanttView } from "@/registry/vcare/ui/gantt/gantt-view"
const start = startOfWeek(new Date(), { weekStartsOn: 1 })
const d = (n: number) => addDays(start, n)
const resources = [
{ id: "purchase", title: "Purchase" },
{ id: "civil", title: "Civil and electrical" },
{ id: "people", title: "People" },
{ id: "launch", title: "Launch" },
]
const events = [
{ id: "1", title: "Choose equipment", start: d(-2), end: d(2), progress: 100, color: "var(--chart-1)", resourceId: "purchase" },
{ id: "2", title: "Install X-ray room", start: d(2), end: d(9), progress: 40, color: "var(--chart-2)", resourceId: "civil", dependencies: ["1"] },
{ id: "3", title: "Staff training", start: d(7), end: d(12), progress: 10, color: "var(--chart-3)", resourceId: "people" },
{ id: "4", title: "Go live", start: d(13), end: d(14), color: "var(--success)", resourceId: "launch", dependencies: ["2", "3"] },
]
export default function GanttDemo() {
return (
<div className="h-[420px] w-full">
<Gantt defaultEvents={events} resources={resources} defaultScale="month" className="flex h-full flex-col">
<GanttNav />
<GanttToolbar />
<GanttView className="min-h-0 flex-1" />
</Gantt>
</div>
)
}Installation
npx shadcn@latest add @vcare/ganttOr install directly from the URL: https://ui.vcarehms.com/r/gantt.json
- Install the dependencies:
npm i @base-ui/react @date-fns/tz date-fns lucide-react - Add the registry items it uses: button, calendar, checkbox, context-menu, dropdown-menu, popover, tooltip, utils.
- Copy these 10 files into your project and change the
@/registry/vcare/…imports to your own paths.
components/ui/gantt/gantt-bar.tsx
'use client';
import { createContext, useContext, useMemo, useState, type CSSProperties, type ReactNode } from 'react';
import { useGantt, useGanttSelector, useGanttViewConfig } from '@/registry/vcare/ui/gantt/gantt';
import { useGanttGestures, wasRecentDrag } from '@/registry/vcare/ui/gantt/gantt-dnd';
import { flattenResources, getBaselineVariance, resolveEventBaseline, toZoned } from '@/registry/vcare/ui/gantt/gantt-lib';
import type { GanttOccurrence, GanttSegment } from '@/registry/vcare/ui/gantt/gantt-types';
import { mergeProps } from '@base-ui/react/merge-props';
import { useRender } from '@base-ui/react/use-render';
import { cn } from '@/registry/vcare/lib/utils';
import { ContextMenu, ContextMenuContent, ContextMenuTrigger } from '@/registry/vcare/ui/context-menu';
import { Tooltip, TooltipContent, TooltipProvider, TooltipTrigger } from '@/registry/vcare/ui/tooltip';
import { RepeatIcon, CheckIcon } from 'lucide-react';
/**
* Effective Tailwind palette presets for bar colors; every entry works on
* light and dark surfaces through the bar's alpha background + accent border.
*/
const GANTT_COLORS: Array<{ name: string; value: string }> = [
{ name: 'Blue', value: 'var(--color-blue-500)' },
{ name: 'Emerald', value: 'var(--color-emerald-500)' },
{ name: 'Violet', value: 'var(--color-violet-500)' },
{ name: 'Rose', value: 'var(--color-rose-500)' },
{ name: 'Amber', value: 'var(--color-amber-500)' },
{ name: 'Cyan', value: 'var(--color-cyan-500)' },
{ name: 'Orange', value: 'var(--color-orange-500)' },
{ name: 'Pink', value: 'var(--color-pink-500)' },
{ name: 'Teal', value: 'var(--color-teal-500)' },
{ name: 'Indigo', value: 'var(--color-indigo-500)' },
];
interface GanttBarContextValue<TData = unknown> {
occurrence: GanttOccurrence<TData>;
segment: GanttSegment<TData>;
isDragging: boolean;
isSelected: boolean;
}
const GanttBarContext =
// eslint-disable-next-line @typescript-eslint/no-explicit-any
createContext<GanttBarContextValue<any> | null>(null);
/** The bar's subject; usable inside renderEvent content and bar children. */
function useGanttBarContext<TData = unknown>(): GanttBarContextValue<TData> {
const ctx = useContext(GanttBarContext);
if (!ctx) {
throw new Error('useGanttBarContext must be used within <GanttBar>');
}
return ctx as GanttBarContextValue<TData>;
}
interface GanttBarProps<TData = unknown> extends Omit<useRender.ComponentProps<'button'>, 'children'> {
segment: GanttSegment<TData>;
/** Replaces the default bar CONTENT; the wrapper stays gantt-owned. */
children?: ReactNode;
/**
* The title renders beside the bar (view-owned), so the default inner
* content is suppressed. Explicit children and renderEvent still win.
*/
labelOutside?: boolean;
/**
* The owning row's title for the aria-label. Pass it when the row is in
* scope (the internal view does); omitting falls back to a tree lookup.
*/
rowTitle?: string;
}
/**
* The one interactive bar element. The wrapper owns positioning hooks, a11y,
* selection, drag/resize listeners, and data attributes; content comes from
* children, the root renderEvent override, or the built-in default.
*/
function GanttBar<TData = unknown>({ segment, className, render, children, labelOutside, rowTitle: rowTitleProp, ...props }: GanttBarProps<TData>) {
const instance = useGantt<TData>();
const viewConfig = useGanttViewConfig<TData>();
const gestures = useGanttGestures<TData>();
const { settings } = instance;
const occurrence = segment.occurrence;
const event = occurrence.event;
const isSelected = useGanttSelector<TData, boolean>((state) => state.selection.eventKeys.includes(occurrence.key), {
calendar: instance,
});
const isDragging = useGanttSelector<TData, boolean>((state) => state.drag?.occurrence.key === occurrence.key, {
calendar: instance,
});
// Which gesture owns this bar: a move hides the original (the smooth clone
// stands in for it); a resize keeps it as a faint placeholder behind the
// dashed preview so you can see the original extent.
const dragKind = useGanttSelector<TData, string | null>((state) => (state.drag?.occurrence.key === occurrence.key ? state.drag.kind : null), {
calendar: instance,
});
// Hover-only range tooltip. Focus opens are ignored (the known button+
// tooltip flash: clicking a bar opens a dialog, focus returns, and a
// focus-triggered tooltip would pop). Hidden while dragging/resizing.
const [tipOpen, setTipOpen] = useState(false);
// Gated on tipOpen: with the tooltip closed the selector returns a stable
// false, so gesture start/end doesn't re-render every mounted bar.
const anyInteracting = useGanttSelector<TData, boolean>((state) => tipOpen && (state.drag !== null || state.slotDraft !== null), {
calendar: instance,
});
const progress = typeof event.progress === 'number' ? Math.min(Math.max(Math.round(event.progress), 0), 100) : null;
// A zero-duration occurrence is a MILESTONE: the button stays the
// interactive shell (click, select, menu, move), the diamond replaces the
// tinted bar body, and the view keeps the title outside.
const milestone = occurrence.end.getTime() === occurrence.start.getTime();
// The bar only LABELS its baseline (attributes, tooltip, aria); the ghost
// itself is view-owned chrome, because its range differs from this bar's.
const baseline = viewConfig.baselineBars ? resolveEventBaseline(event) : null;
const baselineVariance = baseline ? getBaselineVariance(event) : null;
const defaultContent = (
<>
{occurrence.isRecurring && <RepeatIcon className="size-2.5 shrink-0 opacity-70" aria-hidden="true" />}
<span className="truncate font-medium">{event.title}</span>
{!occurrence.allDay && segment.isStart && (
<span className="text-muted-foreground hidden truncate @[8rem]:inline">
{settings.i18n.functions.formatEventTime(
toZoned(occurrence.start, settings.timeZone),
toZoned(occurrence.end, settings.timeZone),
occurrence.allDay,
settings.locale,
)}
</span>
)}
</>
);
const renderProps = { occurrence, segment, isDragging, isSelected };
const content = children ?? viewConfig.renderEvent?.(renderProps) ?? (labelOutside || milestone ? null : defaultContent);
// Consumer-owned content owns the WHOLE inner visualization: the built-in
// progress fill and done mark yield so custom bars start from a blank
// canvas (progress stays readable via data-progress/data-completed).
const consumerOwnsContent = children !== undefined || !!viewConfig.renderEvent;
const timeLabel = settings.i18n.functions.formatEventTime(
toZoned(occurrence.start, settings.timeZone),
toZoned(occurrence.end, settings.timeZone),
occurrence.allDay,
settings.locale,
);
// Memoized: a second full formatEventTime per render would double the
// bar's formatting cost, and it cannot wait for the tooltip because the
// label also feeds aria-label. Keyed on the instants, not the baseline
// object - resolveEventBaseline allocates a fresh one every render.
const baselineStartMs = baseline?.start.getTime();
const baselineEndMs = baseline?.end.getTime();
const plannedLabel = useMemo(
() =>
baselineStartMs === undefined || baselineEndMs === undefined
? undefined
: settings.i18n.labels.planned(
settings.i18n.functions.formatEventTime(
toZoned(new Date(baselineStartMs), settings.timeZone),
toZoned(new Date(baselineEndMs), settings.timeZone),
occurrence.allDay,
settings.locale,
),
),
[baselineStartMs, baselineEndMs, occurrence.allDay, settings.i18n, settings.timeZone, settings.locale],
);
// name the row too: the split-pane layout carries no grid semantics.
// The prop path is O(1); the lookup fallback is memoized so external
// GanttBar usage never flattens the tree per render.
const fallbackRowTitle = useMemo(
() =>
rowTitleProp === undefined && event.resourceId
? flattenResources(settings.resources).find(({ resource }) => resource.id === event.resourceId)?.resource.title
: undefined,
[rowTitleProp, event.resourceId, settings.resources],
);
const rowTitle = rowTitleProp ?? fallbackRowTitle;
const showResize = gestures.canResize(segment);
const resizeHandles = showResize && (
<>
{segment.isStart && (
<span
data-slot="gantt-resize-handle"
data-edge="start"
// grip hugs the start edge (justify-start + tight inset) so the
// indicator reads as "resize this end", not a centered pill.
// pointer-coarse keeps it visible on touch, where hover never fires
className="absolute inset-y-0 start-0.5 flex w-2 cursor-ew-resize items-center justify-start opacity-0 group-hover/gantt-bar-group:opacity-100 pointer-coarse:opacity-100"
onPointerDown={(e) => gestures.beginResize(e, segment, 'start')}
>
<span aria-hidden className="bg-foreground/40 h-2.5 w-0.5 rounded-full" />
</span>
)}
{segment.isEnd && (
<span
data-slot="gantt-resize-handle"
data-edge="end"
// grip hugs the end edge (justify-end + tight inset) so the
// indicator reads as "resize this end", not a centered pill.
// pointer-coarse keeps it visible on touch, where hover never fires
className="absolute inset-y-0 end-0.5 flex w-2 cursor-ew-resize items-center justify-end opacity-0 group-hover/gantt-bar-group:opacity-100 pointer-coarse:opacity-100"
onPointerDown={(e) => gestures.beginResize(e, segment, 'end')}
>
<span aria-hidden className="bg-foreground/40 h-2.5 w-0.5 rounded-full" />
</span>
)}
</>
);
const defaultProps = {
type: 'button' as const,
'data-slot': 'gantt-bar',
'data-milestone': milestone || undefined,
'data-all-day': occurrence.allDay || undefined,
'data-recurring': occurrence.isRecurring || undefined,
'data-selected': isSelected || undefined,
'data-dragging': isDragging || undefined,
'data-drag-kind': dragKind ?? undefined,
'data-past': occurrence.end.getTime() < Date.now() || undefined,
'data-label-outside': labelOutside || undefined,
'data-progress': progress ?? undefined,
'data-completed': progress === 100 || undefined,
'data-baseline': !!baseline || undefined,
'data-baseline-variance': baselineVariance ?? undefined,
'aria-label': settings.i18n.functions.formatEventAriaLabel({
title: event.title,
timeLabel,
milestoneLabel: milestone ? settings.i18n.labels.milestone : undefined,
rowTitle,
progressLabel: progress !== null ? settings.i18n.labels.progress(progress) : undefined,
plannedLabel,
continues: segment.continuesBefore || segment.continuesAfter,
}),
style: {
'--gantt-event-color': event.color ?? 'var(--color-primary)',
} as CSSProperties,
onPointerDown: (e: React.PointerEvent) => {
e.stopPropagation();
gestures.beginMove(e, segment);
},
onClick: (e: React.MouseEvent) => {
e.stopPropagation();
if (wasRecentDrag()) return;
instance.api.selectEvent(occurrence.key);
settings.onEventClick?.(occurrence, e);
},
onDoubleClick: (e: React.MouseEvent) => {
e.stopPropagation();
settings.onEventDoubleClick?.(occurrence, e);
},
className: cn(
'group/gantt-bar-group text-foreground @container relative flex w-full min-w-0 cursor-pointer touch-none items-center gap-1.5 overflow-hidden rounded-sm px-1.5 py-0.5 text-start leading-normal select-none',
'focus-visible:ring-ring/50 outline-none focus-visible:ring-2',
// the unfilled remainder has to be legible on its own - at /12 a bar
// with a progress fill read as a floating segment with no basement
'bg-(--gantt-event-color)/20 hover:bg-(--gantt-event-color)/30',
// move: hide the original (the smooth cursor clone represents it)
'data-[drag-kind=move]:opacity-0',
// resize: keep the original event exactly, just fade it to a soft
// placeholder behind the dashed preview - no dramatic restyle
'data-[drag-kind=resize-start]:opacity-40 data-[drag-kind=resize-end]:opacity-40',
'data-selected:bg-(--gantt-event-color)/30',
/* the diamond is the milestone's body, so the shell sheds its own
tinted fill and centers the glyph on the instant */
milestone && 'justify-center bg-transparent px-0 hover:bg-transparent data-selected:bg-transparent',
segment.continuesBefore && 'rounded-s-none',
segment.continuesAfter && 'rounded-e-none',
viewConfig.classNames?.event,
className,
),
children: (
<>
{milestone && !consumerOwnsContent && (
// the filled diamond IS the milestone's body - chrome, so a custom
// renderEvent still starts from a blank canvas (data-milestone
// keeps the fact readable there)
<span
aria-hidden
data-slot="gantt-bar-milestone"
className={cn(
'size-2.5 shrink-0 rotate-45 rounded-[2px] border border-(--gantt-event-color) bg-(--gantt-event-color)/80',
isSelected && 'ring-ring/50 ring-2',
)}
/>
)}
{progress !== null && !milestone && (
// Chrome, not content: it is an absolutely-positioned layer BEHIND
// whatever the bar renders, so a consumer bar (renderEvent) keeps
// its completion fill instead of silently losing it. The inline
// done-mark below stays gated, because that one really is content.
<span
aria-hidden
data-slot="gantt-bar-progress"
className="pointer-events-none absolute inset-y-0 start-0 border-e border-(--gantt-event-color)/65 bg-(--gantt-event-color)/40 data-full:border-e-0"
data-full={progress === 100 || undefined}
style={{ width: `${progress}%` }}
/>
)}
{progress === 100 && !consumerOwnsContent && !milestone && (
// done mark: completion chrome like the fill itself, so it shows
// for outside-label bars too (where the inner content is empty)
<CheckIcon className="relative size-2.5 shrink-0 opacity-80" aria-hidden="true" />
)}
{content}
{resizeHandles}
</>
),
};
const barButton = useRender({
defaultTagName: 'button',
render,
props: mergeProps<'button'>(defaultProps, props),
});
// Consumer-owned right-click menu (headless): the primitive only wires the
// ContextMenu; the items and their handlers come entirely from the block.
const menu = viewConfig.renderEventMenu?.(renderProps);
// The bar is simultaneously the tooltip trigger and (when a menu exists)
// the context-menu trigger; Base UI composes both via render props.
const trigger = menu ? <ContextMenuTrigger render={<TooltipTrigger render={barButton} />} /> : <TooltipTrigger render={barButton} />;
const barTree = (
<TooltipProvider delay={500} closeDelay={0} timeout={300}>
<Tooltip
open={tipOpen && !anyInteracting}
onOpenChange={(next: boolean, details: { reason?: string }) => {
// opens only on hover; focus/press opens are dropped
if (next && details?.reason !== 'trigger-hover') return;
setTipOpen(next);
}}
>
{trigger}
{tipOpen && !anyInteracting && (
<TooltipContent side="top" className="pointer-events-none">
<div className="font-medium">{event.title}</div>
<div className="opacity-80">{timeLabel}</div>
{plannedLabel && <div className="opacity-80">{plannedLabel}</div>}
</TooltipContent>
)}
</Tooltip>
</TooltipProvider>
);
return (
<GanttBarContext.Provider value={{ occurrence, segment, isDragging, isSelected }}>
{menu ? (
<ContextMenu>
{barTree}
<ContextMenuContent data-slot="gantt-bar-menu" className="min-w-44">
{menu}
</ContextMenuContent>
</ContextMenu>
) : (
barTree
)}
</GanttBarContext.Provider>
);
}
export { GANTT_COLORS, GanttBar, useGanttBarContext };
export type { GanttBarContextValue, GanttBarProps };components/ui/gantt/gantt-dnd.tsx
import { useCallback, useEffect } from 'react';
import { resolveScheduleMode, useGantt, useGanttViewConfig, type GanttInstance } from '@/registry/vcare/ui/gantt/gantt';
import { findResource, snapMinutes, toZoned, zonedStartOfDay } from '@/registry/vcare/ui/gantt/gantt-lib';
import type { GanttProposedUpdate, GanttScheduleMode, GanttSegment } from '@/registry/vcare/ui/gantt/gantt-types';
import { addDays, differenceInCalendarDays } from 'date-fns';
/**
* Activation policy (dnd-kit parity where proven):
* mouse move 5px before a drag starts (below = click), create 4px;
* touch long-press 250ms with 5px tolerance (movement past tolerance
* before the delay cancels the drag so taps stay taps).
*/
const GANTT_ACTIVATION = {
moveDistancePx: 5,
createDistancePx: 4,
touchDelayMs: 250,
touchTolerancePx: 5,
} as const;
type GestureKind = 'move' | 'resize-start' | 'resize-end' | 'create';
interface GanttSurface {
rect: DOMRect;
rangeStart: number;
rangeEnd: number;
snapMin: number;
/** Mirrored axis: in RTL the range START sits at the rect's RIGHT edge. */
isRtl: boolean;
rows: Array<{ resourceId: string; rect: DOMRect }>;
}
/**
* Pointer x (viewport px) to minutes from the range start, clamped to the
* track. The single place the horizontal axis direction is resolved: every
* gesture mapping (move, both resizes, create, grab offset) goes through it.
*/
function surfaceMinutesAt(tl: GanttSurface, x: number): number {
const clamped = Math.min(Math.max(x, tl.rect.left), tl.rect.right);
const traveled = tl.isRtl ? tl.rect.right - clamped : clamped - tl.rect.left;
return (traveled / tl.rect.width) * ((tl.rangeEnd - tl.rangeStart) / 60000);
}
/** Module flag so bar onClick can ignore the click that ends a drag. */
let lastGestureEndedAt = 0;
function wasRecentDrag(): boolean {
return performance.now() - lastGestureEndedAt < 250;
}
/** Mark a non-dnd gesture (e.g. a timeline pan) so the click it ends is ignored. */
function markGestureEnd(): void {
lastGestureEndedAt = performance.now();
}
/**
* Registry of in-flight gesture cancels. A gesture measures its surface
* (axis + row rects) once at activation, so the VIEW - not the bar, bars
* legitimately unmount mid-gesture - must be able to abort gestures when it
* unmounts or when the measured geometry changes under them (zoom, scale,
* range growth, splitter). Cancel fully reverts: listeners, overlays and the
* body drag state all clear, and no update is committed.
*/
const activeGestureCancels = new Set<() => void>();
/** Cancel (and fully revert) every in-flight gantt pointer gesture. */
function cancelActiveGanttGestures(): void {
for (const cancel of [...activeGestureCancels]) cancel();
}
/**
* View-level teardown, mounted once by GanttView: aborts any in-flight
* gesture on unmount so window listeners, body-appended overlays and the
* gantt-dragging body class never outlive the gantt.
*/
function useGanttGestureTeardown(): void {
useEffect(() => cancelActiveGanttGestures, []);
}
/**
* Snap a translate offset to the device pixel grid. The cursor-following
* overlays (the move clone and the resize indicator) are their own
* `will-change: transform` compositing layers: the GPU rasterizes their text
* once and repositions that texture each frame, so a subpixel translate
* (getBoundingClientRect and raw clientX/Y are routinely fractional) resamples
* the texture and blurs the text. Rounding each offset to a whole device pixel
* lands the layer on the grid so glyphs stay crisp, without giving up the
* per-frame GPU transform.
*/
function snapToPixel(value: number): number {
const dpr = typeof window !== 'undefined' ? window.devicePixelRatio || 1 : 1;
return Math.round(value * dpr) / dpr;
}
function collectSurface(root: HTMLElement | null): GanttSurface | null {
if (!root) return null;
const axis = root.querySelector<HTMLElement>('[data-gantt-axis]');
if (!axis) return null;
return {
rect: axis.getBoundingClientRect(),
rangeStart: Number(axis.dataset.ganttRangeStart),
rangeEnd: Number(axis.dataset.ganttRangeEnd),
snapMin: Number(axis.dataset.ganttSnap) || 15,
isRtl: getComputedStyle(axis).direction === 'rtl',
rows: [...root.querySelectorAll<HTMLElement>('[data-gantt-row]')]
// static rows (parents that aggregate their subtree) take no drops
.filter((row) => row.dataset.ganttRowStatic === undefined)
.map((row) => ({
resourceId: row.dataset.ganttResource ?? '',
rect: row.getBoundingClientRect(),
})),
};
}
interface BeginGestureConfig<TData> {
instance: GanttInstance<TData>;
kind: GestureKind;
origin: HTMLElement;
startEvent: PointerEvent;
segment?: GanttSegment<TData>;
/** Consumer renders the move preview (renderDragPreview); the engine only positions it. */
customMoveOverlay?: boolean;
/** Consumer renders the resize indicator; the engine only positions it. */
customResizeOverlay?: boolean;
/** View-level cardinality default; a node's own scheduleMode wins. */
scheduleMode?: GanttScheduleMode;
}
function beginGesture<TData>(config: BeginGestureConfig<TData>) {
const { instance, kind, origin, startEvent, segment, customMoveOverlay, customResizeOverlay } = config;
const { settings, internals, api } = instance;
const activation = { ...GANTT_ACTIVATION, ...settings.activation };
const startX = startEvent.clientX;
const startY = startEvent.clientY;
const pointerId = startEvent.pointerId;
// stable ancestors: bar nodes may be replaced by re-renders mid-gesture
const viewRoot = origin.closest<HTMLElement>('[data-slot=gantt-view]');
const ganttRoot = origin.closest<HTMLElement>('[data-slot=gantt]');
const announcer = ganttRoot?.querySelector<HTMLElement>('[data-slot=gantt-announcer]');
/**
* The cursor-following overlays are appended to document.body so no ancestor
* transform or overflow can clip them - which also cuts them off from the
* gantt root, and the root is what OWNS the type scale (its `text-xs` is
* what every resting label inherits). Without this the clone's label jumps
* to the document default and reads visibly bigger than the bar it left.
* Copying the ROOT's resolved metrics - rather than hardcoding a size -
* keeps the documented contract that one class on the root (e.g.
* className="text-sm") rescales the whole gantt, drag clone included.
*/
const adoptRootTypography = (el: HTMLElement) => {
if (!ganttRoot) return;
const rootStyle = getComputedStyle(ganttRoot);
el.style.fontSize = rootStyle.fontSize;
el.style.lineHeight = rootStyle.lineHeight;
el.style.fontFamily = rootStyle.fontFamily;
el.style.letterSpacing = rootStyle.letterSpacing;
// physical positioning, logical content: the flex row mirrors so the
// label lands on the same side of the bar as the resting one in RTL
el.style.direction = rootStyle.direction;
};
const isTouch = startEvent.pointerType === 'touch';
// resize activates immediately on precise pointers; on touch it waits for
// the same long-press as a move, so a stray brush over a bar edge can
// never start an accidental resize
let active = kind.startsWith('resize') && !isTouch;
let surface: GanttSurface | null = active ? collectSurface(viewRoot) : null;
let lastProposalKey = '';
let touchTimer: ReturnType<typeof setTimeout> | null = null;
let lastPointer: PointerEvent = startEvent;
const occurrence = segment?.occurrence;
// ----- neighbour awareness: the other schedules in the SAME node -----
// A node in "single" mode rejects any concurrency regardless of the
// overlap option; otherwise the option decides. "allow" short-circuits
// everything below, so the default gesture path is untouched.
const nodeId = occurrence?.event.resourceId;
const nodeMode = resolveScheduleMode(nodeId === undefined ? null : findResource(settings.resources, nodeId), config.scheduleMode);
const overlapPolicy = nodeMode === 'single' ? ('reject' as const) : settings.overlap;
// Read once per gesture: the gantt never mutates events mid-drag, so the
// neighbours cannot move under us.
let neighbourCache: Array<{ start: number; end: number }> | null = null;
const getNeighbours = () => {
if (neighbourCache) return neighbourCache;
neighbourCache =
!occurrence || nodeId === undefined || overlapPolicy === 'allow'
? []
: api
.getOccurrences()
.filter((other) => other.event.resourceId === nodeId && other.key !== occurrence.key)
.map((other) => ({
start: other.start.getTime(),
end: other.end.getTime(),
}));
return neighbourCache;
};
const overlapsNeighbour = (start: Date, end: Date) => getNeighbours().some((other) => other.start < end.getTime() && other.end > start.getTime());
/**
* Stop the gesture at the neighbour's edge. Runs AFTER snapping so the
* clamp always wins, and only against neighbours that sit clear of the
* bar's CURRENT span - a pre-existing overlap has no edge to stop at.
*/
const clampToNeighbours = (start: Date, end: Date): { start: Date; end: Date } => {
if (overlapPolicy !== 'clamp' || !occurrence) return { start, end };
const anchorStart = occurrence.start.getTime();
const anchorEnd = occurrence.end.getTime();
let floor = -Infinity;
let ceiling = Infinity;
for (const other of getNeighbours()) {
if (other.end <= anchorStart) floor = Math.max(floor, other.end);
else if (other.start >= anchorEnd) ceiling = Math.min(ceiling, other.start);
}
if (floor === -Infinity && ceiling === Infinity) return { start, end };
let from = start.getTime();
let to = end.getTime();
if (kind === 'resize-start') {
from = Math.min(Math.max(from, floor), to);
} else if (kind === 'resize-end') {
to = Math.max(Math.min(to, ceiling), from);
} else {
// a move keeps its duration and parks against whichever edge it meets
const duration = to - from;
if (from < floor) {
from = floor;
to = from + duration;
}
if (to > ceiling) {
to = ceiling;
from = to - duration;
}
// window narrower than the bar itself: park at the earlier edge
if (from < floor) {
from = floor;
to = from + duration;
}
}
return { start: new Date(from), end: new Date(to) };
};
// Set by applyProposal when a "reject" policy refuses the current proposal;
// read on pointerup so the commit is actually blocked, not merely styled.
let overlapRejected = false;
// Preserve the grab offset so the bar does not jump to the pointer
let grabOffsetMin = 0;
// Smooth cursor-following clone for a move: a real-looking bar that tracks
// the pointer's x via transform (no per-frame React), lifted with a shadow.
let overlay: HTMLDivElement | null = null;
let grabOffsetPx = 0;
let barTop = 0;
let barWidth = 0;
let barHeight = 0;
const createMoveOverlay = () => {
if (kind !== 'move' || !occurrence || overlay || barWidth === 0) return;
// consumer-rendered preview (renderDragPreview): the view mounts it from
// drag state; positionOverlay adopts it lazily and only writes transforms
if (customMoveOverlay) return;
const color = occurrence.event.color ?? 'var(--color-primary)';
overlay = document.createElement('div');
overlay.setAttribute('data-slot', 'gantt-drag-overlay');
// container: the bar + its label ride together; the label stays OUTSIDE
// the bar (to the right), matching the resting look - no in-bar text
overlay.className =
// physical left-0 anchor: the clone is positioned by translate3d from
// raw clientX, which is physical - a logical start-0 anchor would pin
// it to the RIGHT edge in RTL and fling the clone off screen
'pointer-events-none fixed top-0 left-0 z-100 flex items-center gap-2 will-change-transform';
adoptRootTypography(overlay);
overlay.style.height = `${barHeight}px`;
const barEl = document.createElement('div');
if (occurrence.end.getTime() === occurrence.start.getTime()) {
// a MILESTONE stays a diamond while it travels: the resting glyph,
// lifted with a shadow - a rectangle here reads as a different object
barEl.className = 'flex shrink-0 items-center justify-center';
barEl.style.width = `${barWidth}px`;
barEl.style.height = '100%';
const diamond = document.createElement('span');
diamond.className = 'rotate-45 rounded-[2px] shadow-lg';
diamond.style.width = '10px';
diamond.style.height = '10px';
diamond.style.background = `color-mix(in oklab, ${color} 80%, var(--color-background))`;
diamond.style.border = `1px solid ${color}`;
barEl.appendChild(diamond);
} else {
barEl.className = 'shrink-0 rounded-sm shadow-lg';
barEl.style.width = `${barWidth}px`;
barEl.style.height = '100%';
barEl.style.background = `color-mix(in oklab, ${color} 22%, var(--color-background))`;
barEl.style.outline = `1px solid color-mix(in oklab, ${color} 55%, transparent)`;
}
overlay.appendChild(barEl);
const label = document.createElement('span');
label.className = 'text-foreground truncate font-medium whitespace-nowrap';
label.textContent = occurrence.event.title;
overlay.appendChild(label);
document.body.appendChild(overlay);
positionOverlay(lastPointer);
};
const positionOverlay = (e: PointerEvent) => {
if (!overlay && customMoveOverlay && active && kind === 'move') {
overlay = document.querySelector<HTMLDivElement>('[data-slot=gantt-drag-overlay][data-custom]');
if (overlay) overlay.style.visibility = 'visible';
}
if (!overlay) return;
// x follows the pointer freely (smooth); y stays on the bar's own row
overlay.style.transform = `translate3d(${snapToPixel(e.clientX - grabOffsetPx)}px, ${snapToPixel(barTop)}px, 0)`;
};
// Resize status indicator: a smooth cursor-following edge line plus a live
// range + duration chip. The dashed ghost still shows the SNAPPED landing;
// this overlay is the continuous feedback between snap steps.
let resizeOverlay: HTMLDivElement | null = null;
let resizeLine: HTMLDivElement | null = null;
let resizeRange: HTMLSpanElement | null = null;
let resizeDot: HTMLSpanElement | null = null;
let resizeDuration: HTMLSpanElement | null = null;
const positionResizeOverlay = (e: PointerEvent) => {
if (!resizeOverlay && customResizeOverlay && kind.startsWith('resize')) {
resizeOverlay = document.querySelector<HTMLDivElement>('[data-slot=gantt-resize-indicator][data-custom]');
if (resizeOverlay) resizeOverlay.style.visibility = 'visible';
}
if (!resizeOverlay || !surface) return;
// x follows the pointer freely (clamped to the track); y stays on the bar
const x = Math.min(Math.max(e.clientX, surface.rect.left), surface.rect.right);
resizeOverlay.style.transform = `translate3d(${snapToPixel(x)}px, ${snapToPixel(barTop)}px, 0)`;
};
const createResizeOverlay = () => {
if (!kind.startsWith('resize') || !occurrence || resizeOverlay) return;
const barEl = origin.closest<HTMLElement>('[data-slot=gantt-bar]');
const rect = (barEl ?? origin).getBoundingClientRect();
barTop = rect.top;
barHeight = rect.height;
// consumer-rendered indicator: rect capture above still runs (the engine
// positions the consumer's wrapper), only the default DOM is skipped
if (customResizeOverlay) return;
const color = occurrence.event.color ?? 'var(--color-primary)';
resizeOverlay = document.createElement('div');
resizeOverlay.setAttribute('data-slot', 'gantt-resize-indicator');
resizeOverlay.className =
// physical left-0 anchor, same reason as the move clone above
'pointer-events-none fixed top-0 left-0 z-100 will-change-transform';
adoptRootTypography(resizeOverlay);
resizeOverlay.style.height = `${barHeight}px`;
resizeLine = document.createElement('div');
resizeLine.className = 'h-full w-0.5 -translate-x-1/2 rounded-full';
resizeLine.style.background = color;
resizeOverlay.appendChild(resizeLine);
const chip = document.createElement('div');
chip.className =
// physical left-0: centered with a physical translate on a physical anchor
// no text size of its own: it inherits the root scale adopted above, so
// the chip tracks a consumer rescale instead of pinning itself to 12px
'bg-foreground text-background absolute bottom-full left-0 mb-1.5 flex -translate-x-1/2 items-center gap-1.5 rounded-md px-2 py-1 font-medium whitespace-nowrap';
resizeRange = document.createElement('span');
chip.appendChild(resizeRange);
resizeDot = document.createElement('span');
resizeDot.className = 'bg-background/40 size-1 shrink-0 rounded-full';
resizeDot.setAttribute('aria-hidden', 'true');
chip.appendChild(resizeDot);
resizeDuration = document.createElement('span');
chip.appendChild(resizeDuration);
// The arrow. Every other bubble in the gantt has one pointing at what it
// describes; this chip had none, so a resize looked like a different
// component from the hover hint. Physical left-1/2 to match the chip's own
// physical anchor, and out of flow so the chip's flex gap ignores it.
const chipArrow = document.createElement('span');
chipArrow.setAttribute('aria-hidden', 'true');
chipArrow.className = 'bg-foreground absolute -bottom-1 left-1/2 size-2.5 -translate-x-1/2 rotate-45 rounded-[2px]';
chip.appendChild(chipArrow);
resizeOverlay.appendChild(chip);
document.body.appendChild(resizeOverlay);
// seed the chip with the CURRENT range so it never flashes empty;
// zoned so the label names the same day the grid shows
resizeRange.textContent = settings.i18n.functions.formatEventTime(
toZoned(occurrence.start, settings.timeZone),
toZoned(occurrence.end, settings.timeZone),
occurrence.allDay ?? false,
settings.locale,
);
const days = Math.round((occurrence.end.getTime() - occurrence.start.getTime()) / 86_400_000);
if (days >= 1) {
resizeDuration.textContent = settings.i18n.labels.durationDays(days);
} else {
resizeDot.style.display = 'none';
resizeDuration.style.display = 'none';
}
positionResizeOverlay(startEvent);
};
// resize activates immediately, so its indicator mounts with the gesture
if (active) createResizeOverlay();
const activationDistance = kind === 'create' ? activation.createDistancePx : activation.moveDistancePx;
// Each gesture keeps its own cursor: a resize must stay ew-resize for the
// whole drag (flipping to grabbing reads as a move), a move grabs.
const gestureCursor = kind.startsWith('resize') ? 'ew-resize' : 'grabbing';
const setBodyDragging = (on: boolean, invalid = false) => {
document.body.classList.toggle('gantt-dragging', on);
document.body.style.cursor = on ? (invalid ? 'not-allowed' : gestureCursor) : '';
document.body.style.userSelect = on ? 'none' : '';
if (!on) document.body.style.removeProperty('-webkit-user-select');
};
const activate = () => {
if (active) return;
active = true;
surface = collectSurface(viewRoot);
// touch resize activates here (long-press) instead of at gesture start,
// so its indicator mounts now; the guard inside makes this a no-op for
// every other path
createResizeOverlay();
if (kind === 'move' && occurrence && surface) {
const pointerMin = surfaceMinutesAt(surface, startX);
// TRUE start, never clamped to the range: a bar that begins before the
// visible window (negative minutes) must keep its real grab offset, or
// the first snapped proposal teleports its start to the range edge
const occStartMin = (occurrence.start.getTime() - surface.rangeStart) / 60000;
grabOffsetMin = pointerMin - occStartMin;
const rect = origin.getBoundingClientRect();
barTop = rect.top;
barWidth = rect.width;
barHeight = rect.height;
grabOffsetPx = startX - rect.left;
createMoveOverlay();
}
setBodyDragging(true);
};
const computeProposal = (
e: PointerEvent,
): {
start: Date;
end: Date;
allDay: boolean;
resourceId?: string;
} | null => {
if (!surface) return null;
const tl = surface;
const rangeMinutes = (tl.rangeEnd - tl.rangeStart) / 60000;
const minutesAt = (x: number) => surfaceMinutesAt(tl, x);
// Day-grid scales snap to real zoned midnights, not 1440-minute
// multiples from the range start - those drift by an hour across DST
const snapMin = (minutes: number) => {
if (tl.snapMin < 24 * 60) return snapMinutes(minutes, tl.snapMin);
const ms = tl.rangeStart + minutes * 60000;
const dayStart = zonedStartOfDay(new Date(ms), settings.timeZone);
const dayEnd = zonedStartOfDay(addDays(toZoned(new Date(ms), settings.timeZone), 1), settings.timeZone);
const snapped = ms - dayStart.getTime() < dayEnd.getTime() - ms ? dayStart : dayEnd;
return (snapped.getTime() - tl.rangeStart) / 60000;
};
const rowAt = (y: number) => {
let best = tl.rows[0];
for (const row of tl.rows) {
if (y >= row.rect.top && y < row.rect.bottom) return row;
if (best && Math.abs(y - (row.rect.top + row.rect.height / 2)) < Math.abs(y - (best.rect.top + best.rect.height / 2))) {
best = row;
}
}
return best;
};
const at = (minutes: number) => new Date(tl.rangeStart + minutes * 60000);
if (kind === 'create') {
const anchorMin = snapMin(minutesAt(startX));
const curMin = snapMin(minutesAt(e.clientX));
const lo = Math.min(anchorMin, curMin);
// a bare click still yields a usable slot: at least slotDuration long
const hi = Math.max(anchorMin, curMin, lo + Math.max(tl.snapMin, settings.slotDuration));
return {
start: at(lo),
end: at(hi),
allDay: false,
resourceId: rowAt(startY)?.resourceId,
};
}
if (!occurrence) return null;
const midnightAligned = (d: Date) => zonedStartOfDay(d, settings.timeZone).getTime() === d.getTime();
if (kind === 'move') {
// x-axis only: the bar slides along its OWN row, never across rows.
// The proposal preserves the pointer DELTA - no clamping to the visible
// range, or bars crossing the window edge would teleport to it.
const start = at(snapMin(minutesAt(e.clientX) - grabOffsetMin));
// Day-snapped scales preserve the CALENDAR span for day-aligned bars:
// a 3-day bar dragged across a DST change stays midnight-to-midnight
// (72h +/- 1h), never drifting to a 23:00 end. Sub-day events keep
// their exact ms duration.
let end: Date;
if (occurrence.end.getTime() === occurrence.start.getTime()) {
// a milestone is an instant: moving it moves the point - the
// day-span branch below would silently stretch it to a full day
end = start;
} else if (tl.snapMin >= 24 * 60 && (occurrence.allDay || (midnightAligned(occurrence.start) && midnightAligned(occurrence.end)))) {
const daySpan = Math.max(
differenceInCalendarDays(toZoned(occurrence.end, settings.timeZone), toZoned(occurrence.start, settings.timeZone)),
1,
);
end = zonedStartOfDay(addDays(toZoned(start, settings.timeZone), daySpan), settings.timeZone);
} else {
end = new Date(start.getTime() + (occurrence.end.getTime() - occurrence.start.getTime()));
}
const bounded = clampToNeighbours(start, end);
return {
start: bounded.start,
end: bounded.end,
allDay: occurrence.allDay,
resourceId: occurrence.event.resourceId,
};
}
const min = snapMin(minutesAt(e.clientX));
if (kind === 'resize-start') {
const endMin = (occurrence.end.getTime() - tl.rangeStart) / 60000;
// Minimum length = one snap unit; on day grids that unit is the LAST
// zoned midnight before the end (raw 1440-minute arithmetic lands off
// the midnight grid across DST changes).
const maxStartMin =
tl.snapMin >= 24 * 60
? (zonedStartOfDay(
midnightAligned(occurrence.end) ? addDays(toZoned(occurrence.end, settings.timeZone), -1) : occurrence.end,
settings.timeZone,
).getTime() -
tl.rangeStart) /
60000
: endMin - tl.snapMin;
const clamped = Math.min(Math.max(min, 0), maxStartMin);
const bounded = clampToNeighbours(at(clamped), occurrence.end);
return {
start: bounded.start,
end: bounded.end,
allDay: occurrence.allDay,
resourceId: occurrence.event.resourceId,
};
}
const startMin = (occurrence.start.getTime() - tl.rangeStart) / 60000;
// Mirror of the resize-start bound: the FIRST zoned midnight after the
// start on day grids, plain snap arithmetic otherwise.
const minEndMin =
tl.snapMin >= 24 * 60
? (zonedStartOfDay(addDays(toZoned(occurrence.start, settings.timeZone), 1), settings.timeZone).getTime() - tl.rangeStart) / 60000
: startMin + tl.snapMin;
const clamped = Math.max(Math.min(min, rangeMinutes), minEndMin);
const bounded = clampToNeighbours(occurrence.start, at(clamped));
return {
start: bounded.start,
end: bounded.end,
allDay: occurrence.allDay,
resourceId: occurrence.event.resourceId,
};
};
const applyProposal = (e: PointerEvent) => {
const proposal = computeProposal(e);
if (!proposal) return;
const key = `${proposal.start.getTime()}-${proposal.end.getTime()}-${proposal.allDay}-${proposal.resourceId ?? ''}`;
if (key === lastProposalKey) return;
lastProposalKey = key;
if (kind === 'create') {
const draft = { ...proposal };
if (settings.canSelectSlot && !settings.canSelectSlot(draft)) return;
internals.setSlotDraft(draft);
return;
}
const update: GanttProposedUpdate<TData> = {
event: occurrence!.event,
occurrence: occurrence!,
...proposal,
source: kind === 'move' ? 'drag' : (kind as 'resize-start' | 'resize-end'),
};
// "reject" is the one veto the engine owns: it both styles the ghost AND
// blocks the commit below. canDropEvent stays advisory unless the
// consumer opts into enforceCanDrop, which is checked at release.
overlapRejected = overlapPolicy === 'reject' && overlapsNeighbour(proposal.start, proposal.end);
const valid = !overlapRejected && (settings.canDropEvent ? settings.canDropEvent(update) : true);
// live status: the indicator chip always names the CURRENT proposed
// range; the edge line flips to destructive on an invalid drop
if (resizeRange && resizeDot && resizeDuration) {
resizeRange.textContent = settings.i18n.functions.formatEventTime(
toZoned(proposal.start, settings.timeZone),
toZoned(proposal.end, settings.timeZone),
proposal.allDay,
settings.locale,
);
const days = Math.round((proposal.end.getTime() - proposal.start.getTime()) / 86_400_000);
const showDays = days >= 1;
resizeDot.style.display = showDays ? '' : 'none';
resizeDuration.style.display = showDays ? '' : 'none';
if (showDays) {
resizeDuration.textContent = settings.i18n.labels.durationDays(days);
}
}
if (resizeLine) {
resizeLine.style.background = valid ? (occurrence!.event.color ?? 'var(--color-primary)') : 'var(--color-destructive)';
}
setBodyDragging(true, !valid);
internals.setDrag({
kind: kind === 'move' ? 'move' : (kind as 'resize-start' | 'resize-end'),
occurrence: occurrence!,
proposedStart: proposal.start,
proposedEnd: proposal.end,
proposedAllDay: proposal.allDay,
proposedResourceId: proposal.resourceId,
valid,
});
};
// ----- edge auto-scroll: pan the timeline while dragging near its edge -----
// The pointer is clamped to the visible track, so without this a bar can
// never travel past the window. Holding the pointer inside the edge zone
// scrolls the viewport (speed eased by proximity), refreshes the track rect
// (the axis moved under the pointer) and re-derives the proposal from the
// same pointer position. Programmatic scrolls never mark user intent, so
// this can never trigger infinite-range growth mid-gesture.
const AUTO_SCROLL_EDGE_PX = 24;
const AUTO_SCROLL_MAX_SPEED = 14;
let autoScrollRaf = 0;
const timelineViewport = viewRoot?.querySelector<HTMLElement>('[data-slot=gantt-timeline-pane] [data-slot=scroll-area-viewport]');
const autoScrollTick = () => {
autoScrollRaf = 0;
if (finished || !active || !surface || !timelineViewport) return;
const paneRect = timelineViewport.getBoundingClientRect();
const x = lastPointer.clientX;
let speed = 0;
if (x < paneRect.left + AUTO_SCROLL_EDGE_PX) {
speed = -((paneRect.left + AUTO_SCROLL_EDGE_PX - x) / AUTO_SCROLL_EDGE_PX) * AUTO_SCROLL_MAX_SPEED;
} else if (x > paneRect.right - AUTO_SCROLL_EDGE_PX) {
speed = ((x - (paneRect.right - AUTO_SCROLL_EDGE_PX)) / AUTO_SCROLL_EDGE_PX) * AUTO_SCROLL_MAX_SPEED;
}
if (speed === 0) return;
const before = timelineViewport.scrollLeft;
timelineViewport.scrollLeft = before + speed;
if (timelineViewport.scrollLeft === before) return; // parked on the end
const axis = viewRoot?.querySelector<HTMLElement>('[data-gantt-axis]');
if (axis) surface.rect = axis.getBoundingClientRect();
applyProposal(lastPointer);
positionResizeOverlay(lastPointer);
scheduleAutoScroll();
};
const scheduleAutoScroll = () => {
if (!autoScrollRaf) autoScrollRaf = requestAnimationFrame(autoScrollTick);
};
// idempotent: pointerup, pointercancel, Escape, blur and the view-level
// teardown can race; whichever lands first wins and the rest no-op
let finished = false;
const cleanup = () => {
if (finished) return;
finished = true;
activeGestureCancels.delete(cancel);
if (autoScrollRaf) cancelAnimationFrame(autoScrollRaf);
try {
origin.releasePointerCapture(pointerId);
} catch {
// capture already released (pointer gone or origin detached)
}
window.removeEventListener('pointermove', onPointerMove);
window.removeEventListener('pointerup', onPointerUp);
window.removeEventListener('pointercancel', onCancel);
window.removeEventListener('blur', onWindowBlur);
window.removeEventListener('keydown', onKeyDown, true);
if (touchTimer) clearTimeout(touchTimer);
// consumer-rendered overlays are React-owned: they unmount when the drag
// state clears, so the engine must never removeChild them itself
if (!customMoveOverlay) overlay?.remove();
overlay = null;
if (!customResizeOverlay) resizeOverlay?.remove();
resizeOverlay = null;
setBodyDragging(false);
};
const cancel = () => {
cleanup();
if (active) {
lastGestureEndedAt = performance.now();
internals.setDrag(null);
internals.setSlotDraft(null);
}
};
const onKeyDown = (e: KeyboardEvent) => {
if (e.key === 'Escape') {
e.stopPropagation();
cancel();
}
};
// focus loss mid-gesture (alt-tab, OS dialogs) means the release may never
// be delivered; treat it as a cancel so the gesture cannot get stuck
const onWindowBlur = () => cancel();
const onPointerMove = (e: PointerEvent) => {
if (e.pointerId !== pointerId) return;
lastPointer = e;
if (!active) {
const distance = Math.hypot(e.clientX - startX, e.clientY - startY);
if (isTouch) {
// Long-press pending: moving past tolerance means scroll, not drag
if (distance > activation.touchTolerancePx) cancel();
return;
}
if (distance < activationDistance) return;
activate();
}
applyProposal(e);
positionOverlay(e);
positionResizeOverlay(e);
scheduleAutoScroll();
};
const onPointerUp = (e: PointerEvent) => {
if (e.pointerId !== pointerId) return;
cleanup();
if (!active) return;
lastGestureEndedAt = performance.now();
const state = instance.getState();
if (kind === 'create') {
const draft = state.slotDraft;
internals.setSlotDraft(null);
if (draft) {
api.select({
slot: { start: draft.start, end: draft.end, allDay: draft.allDay },
});
settings.onSelectSlot?.(draft);
}
return;
}
const drag = state.drag;
internals.setDrag(null);
if (!drag || !occurrence) return;
// the node refuses concurrency: revert instead of committing an overlap
if (overlapRejected) return;
// enforceCanDrop makes the advisory verdict binding: a release whose
// last canDropEvent answer was false reverts exactly like "reject" -
// the red ghost becomes a promise instead of a suggestion
if (settings.enforceCanDrop && !drag.valid) return;
const unchanged =
drag.proposedStart.getTime() === occurrence.start.getTime() &&
drag.proposedEnd.getTime() === occurrence.end.getTime() &&
(drag.proposedResourceId === undefined || drag.proposedResourceId === occurrence.event.resourceId);
if (unchanged) return;
// Commit through the one validation funnel; consumer reject = automatic
// revert because the gantt never mutated during the gesture.
const accepted = internals.applyProposedUpdate({
event: occurrence.event,
occurrence,
start: drag.proposedStart,
end: drag.proposedEnd,
allDay: drag.proposedAllDay,
resourceId: drag.proposedResourceId,
source: kind === 'move' ? 'drag' : (kind as 'resize-start' | 'resize-end'),
});
if (accepted && announcer) {
announcer.textContent = `${occurrence.event.title}, ${settings.i18n.functions.formatEventTime(
toZoned(drag.proposedStart, settings.timeZone),
toZoned(drag.proposedEnd, settings.timeZone),
drag.proposedAllDay,
settings.locale,
)}`;
}
};
const onCancel = (e: PointerEvent) => {
if (e.pointerId !== pointerId) return;
cancel();
};
window.addEventListener('pointermove', onPointerMove);
window.addEventListener('pointerup', onPointerUp);
window.addEventListener('pointercancel', onCancel);
window.addEventListener('blur', onWindowBlur);
window.addEventListener('keydown', onKeyDown, true);
activeGestureCancels.add(cancel);
// Capture the pointer so a release OUTSIDE the OS window still delivers
// pointerup here instead of leaving the gesture stuck. Captured events keep
// bubbling to the window listeners above, and if the origin node is removed
// mid-gesture the capture auto-releases - behavior then degrades to plain
// window listeners, never worse than before. Guarded: the pointer can
// already be gone by now (fast flicks, synthetic events).
try {
origin.setPointerCapture(pointerId);
} catch {
// capture is an enhancement, never a requirement
}
// Touch: long-press activation (movement past tolerance cancels above)
if (isTouch && !active) {
touchTimer = setTimeout(() => {
activate();
applyProposal(lastPointer);
}, activation.touchDelayMs);
}
}
/** Per-bar / per-row pointer gesture wiring. */
function useGanttGestures<TData = unknown>() {
const instance = useGantt<TData>();
const viewConfig = useGanttViewConfig<TData>();
// presence flags only: the engine skips its default overlay DOM and
// positions the consumer-rendered node instead
const customMoveOverlay = !!viewConfig.renderDragPreview;
const customResizeOverlay = !!viewConfig.renderResizeIndicator;
const canDrag = useCallback(
(segment: GanttSegment<TData>) => {
const { interactions } = instance.getState();
const event = segment.occurrence.event;
return interactions.drag && !event.readOnly && event.draggable !== false;
},
[instance],
);
const beginMove = useCallback(
(e: React.PointerEvent, segment: GanttSegment<TData>) => {
if (e.button !== 0 || !canDrag(segment)) return;
beginGesture({
instance,
kind: 'move',
origin: e.currentTarget as HTMLElement,
startEvent: e.nativeEvent,
segment,
customMoveOverlay,
scheduleMode: viewConfig.scheduleMode,
});
},
[instance, canDrag, customMoveOverlay, viewConfig.scheduleMode],
);
const canResize = useCallback(
(segment: GanttSegment<TData>) => {
const { interactions } = instance.getState();
const event = segment.occurrence.event;
return (
interactions.resize &&
!event.readOnly &&
event.resizable !== false &&
// a milestone is an instant: it has no edges to resize
segment.occurrence.end.getTime() > segment.occurrence.start.getTime()
);
},
[instance],
);
const beginResize = useCallback(
(e: React.PointerEvent, segment: GanttSegment<TData>, edge: 'start' | 'end') => {
if (e.button !== 0 || !canResize(segment)) return;
e.stopPropagation();
e.preventDefault();
beginGesture({
instance,
kind: edge === 'start' ? 'resize-start' : 'resize-end',
origin: e.currentTarget as HTMLElement,
startEvent: e.nativeEvent,
segment,
customResizeOverlay,
scheduleMode: viewConfig.scheduleMode,
});
},
[instance, canResize, customResizeOverlay, viewConfig.scheduleMode],
);
const beginCreate = useCallback(
(e: React.PointerEvent) => {
if (e.button !== 0) return;
if (!instance.getState().interactions.selectSlot) return;
beginGesture({
instance,
kind: 'create',
origin: e.currentTarget as HTMLElement,
startEvent: e.nativeEvent,
});
},
[instance],
);
return { beginMove, beginResize, beginCreate, canDrag, canResize };
}
export { cancelActiveGanttGestures, GANTT_ACTIVATION, markGestureEnd, useGanttGestures, useGanttGestureTeardown, wasRecentDrag };components/ui/gantt/gantt-i18n.tsx
import type { GanttDateRange, GanttScale } from '@/registry/vcare/ui/gantt/gantt-types';
import { format, isSameMonth, isSameYear, subMilliseconds, type Locale } from 'date-fns';
interface GanttI18nConfig {
labels: {
today: string;
previous: string;
next: string;
addEvent: string;
/** "Add task" hint at the foot of the tree. */
addTask: string;
allDay: string;
loading: string;
event: string;
events: (count: number) => string;
week: (weekNumber: number) => string;
resources: string;
goToDate: string;
/** Hover hint over empty row space, click-only create. */
scheduleHint: string;
/** Same hint where dragCreate is on and a drag paints a range. */
scheduleHintDrag: string;
reorder: string;
/** Scale switcher label ("Timeline scale"). */
selectView: string;
zoomIn: string;
zoomOut: string;
/** Aria-label of the tree/timeline splitter. */
resizePanel: string;
/** Aria-label of the off-screen bar chips. */
jumpToBar: (title: string) => string;
/** Read to screen readers as part of the bar label. */
progress: (percent: number) => string;
/** Live duration readout on the resize indicator. */
durationDays: (days: number) => string;
/** Appended to the bar aria-label when its segment is clipped by the range. */
continues: string;
/** Names the planned (baseline) range in the bar tooltip and aria-label. */
planned: (rangeLabel: string) => string;
/** Read to screen readers on a zero-duration (milestone) bar. */
milestone: string;
scales: {
day: string;
week: string;
month: string;
quarter: string;
year: string;
};
};
/** date-fns format strings, applied with the gantt `locale`. */
formats: {
monthTitle: string;
dayTitle: string;
timeGutter: string;
eventTime: string;
};
functions: {
formatTitle: (
scale: GanttScale,
ctx: {
date: Date;
activeRange: GanttDateRange;
visibleRange: GanttDateRange;
locale?: Locale;
},
) => string;
formatEventTime: (start: Date, end: Date, allDay: boolean, locale?: Locale) => string;
formatDayRange: (range: GanttDateRange, locale?: Locale) => string;
/** Composes the bar's screen-reader label from its localized parts. */
formatEventAriaLabel: (parts: {
title: string;
timeLabel: string;
/** Localized milestone clause, from `labels.milestone`. */
milestoneLabel?: string;
rowTitle?: string;
progressLabel?: string;
/** Localized planned-range clause, from `labels.planned`. */
plannedLabel?: string;
continues: boolean;
}) => string;
};
}
const DEFAULT_LABELS: GanttI18nConfig['labels'] = {
today: 'Today',
previous: 'Previous',
next: 'Next',
addEvent: 'Add event',
addTask: 'Add task',
allDay: 'All day',
loading: 'Loading events',
event: 'event',
events: (count) => (count === 1 ? '1 event' : `${count} events`),
week: (weekNumber) => `W${weekNumber}`,
resources: 'Resources',
goToDate: 'Go to date',
scheduleHint: 'Click to add a schedule',
scheduleHintDrag: 'Click or drag to add a schedule',
reorder: 'Reorder',
selectView: 'Select view',
zoomIn: 'Zoom in',
zoomOut: 'Zoom out',
resizePanel: 'Resize panel',
jumpToBar: (title) => `Scroll to "${title}"`,
progress: (percent) => `${percent}% complete`,
durationDays: (days) => (days === 1 ? '1 day' : `${days} days`),
continues: 'continues',
planned: (rangeLabel) => `Planned ${rangeLabel}`,
milestone: 'milestone',
scales: {
day: 'Day',
week: 'Week',
month: 'Month',
quarter: 'Quarter',
year: 'Year',
},
};
const DEFAULT_FORMATS: GanttI18nConfig['formats'] = {
monthTitle: 'MMMM yyyy',
dayTitle: 'EEEE, MMMM d, yyyy',
timeGutter: 'h a',
eventTime: 'h:mm a',
};
/**
* Default formatting functions BOUND to a config's labels/formats, so that
* `formats` overrides flow into the default renderers (a consumer overriding
* formats.eventTime without replacing formatEventTime still sees it applied).
*/
function makeDefaultGanttFunctions(cfg: Pick<GanttI18nConfig, 'labels' | 'formats'>): GanttI18nConfig['functions'] {
return {
formatTitle: (scale, { date, activeRange, locale }) => {
const opts = { locale };
if (scale === 'day') {
return format(date, cfg.formats.dayTitle, opts);
}
if (scale === 'month') {
return format(date, cfg.formats.monthTitle, opts);
}
if (scale === 'quarter') {
return format(date, 'QQQ yyyy', opts);
}
if (scale === 'year') {
return format(date, 'yyyy', opts);
}
// week: smart range label, last day is activeRange.end - 1ms.
// subMilliseconds keeps the zoned date type (a plain new Date(ms)
// would flip the label to the machine zone near midnight)
const rangeEnd = subMilliseconds(activeRange.end, 1);
const start = activeRange.start;
if (isSameMonth(start, rangeEnd)) {
return `${format(start, 'MMMM d', opts)} - ${format(rangeEnd, 'd, yyyy', opts)}`;
}
if (isSameYear(start, rangeEnd)) {
return `${format(start, 'MMM d', opts)} - ${format(rangeEnd, 'MMM d, yyyy', opts)}`;
}
return `${format(start, 'MMM d, yyyy', opts)} - ${format(rangeEnd, 'MMM d, yyyy', opts)}`;
},
formatEventTime: (start, end, allDay, locale) => {
const opts = { locale };
if (end.getTime() === start.getTime()) {
// a milestone is an instant, not a range - "9:00 AM - 9:00 AM" reads
// like a data bug
return allDay ? format(start, 'MMM d, yyyy', opts) : format(start, `MMM d, ${cfg.formats.eventTime}`, opts);
}
if (allDay) {
// a gantt bar is a DATE RANGE: show it, never a bare "All day".
// Ends are exclusive midnights, so the last shown day is end - 1ms;
// subMilliseconds keeps the caller's zoned date type intact.
const last = end.getTime() - 1 >= start.getTime() ? subMilliseconds(end, 1) : start;
const sameDay = format(start, 'yyyy-MM-dd') === format(last, 'yyyy-MM-dd');
if (sameDay) return format(start, 'MMM d, yyyy', opts);
if (isSameYear(start, last)) {
return `${format(start, 'MMM d', opts)} - ${format(last, 'MMM d, yyyy', opts)}`;
}
return `${format(start, 'MMM d, yyyy', opts)} - ${format(last, 'MMM d, yyyy', opts)}`;
}
const fmt = cfg.formats.eventTime;
// Multi-day timed events carry the date on both sides. Compare calendar
// days off the last rendered instant (end is exclusive, so a 14:00 to
// midnight bar still ends on the start day). Elapsed ms would miss an
// exactly-24h bar and a DST day that only runs 23 hours.
const lastInstant = end.getTime() - 1 >= start.getTime() ? subMilliseconds(end, 1) : start;
if (format(start, 'yyyy-MM-dd') !== format(lastInstant, 'yyyy-MM-dd')) {
return `${format(start, `MMM d, ${fmt}`, opts)} - ${format(end, `MMM d, ${fmt}`, opts)}`;
}
return `${format(start, fmt, opts)} - ${format(end, fmt, opts)}`;
},
formatDayRange: (range, locale) => {
const opts = { locale };
const rangeEnd = subMilliseconds(range.end, 1);
return `${format(range.start, 'MMM d', opts)} - ${format(rangeEnd, 'MMM d', opts)}`;
},
formatEventAriaLabel: ({ title, timeLabel, milestoneLabel, rowTitle, progressLabel, plannedLabel, continues }) =>
[title, timeLabel, milestoneLabel, rowTitle, progressLabel, plannedLabel, continues ? cfg.labels.continues : undefined]
.filter(Boolean)
.join(', '),
};
}
const DEFAULT_GANTT_I18N: GanttI18nConfig = {
labels: DEFAULT_LABELS,
formats: DEFAULT_FORMATS,
functions: makeDefaultGanttFunctions({
labels: DEFAULT_LABELS,
formats: DEFAULT_FORMATS,
}),
};
/** Deep-partial override shape: replace individual keys, never sections. */
interface GanttI18nOverrides {
labels?: Partial<Omit<GanttI18nConfig['labels'], 'scales'>> & {
scales?: Partial<GanttI18nConfig['labels']['scales']>;
};
formats?: Partial<GanttI18nConfig['formats']>;
functions?: Partial<GanttI18nConfig['functions']>;
}
/**
* Shallow merge per nested object, matching the filters.tsx i18n contract:
* a partial override replaces individual keys, never whole sections. Default
* functions are re-bound to the MERGED labels/formats so a `formats` (or
* `labels.continues`) override reaches the default renderers; explicit
* `functions` overrides still win.
*/
function mergeGanttI18n(overrides?: GanttI18nOverrides): GanttI18nConfig {
if (!overrides) return DEFAULT_GANTT_I18N;
const labels = {
...DEFAULT_LABELS,
...overrides.labels,
// nested section: replace individual scale names, never the whole set
scales: {
...DEFAULT_LABELS.scales,
...overrides.labels?.scales,
},
};
const formats = { ...DEFAULT_FORMATS, ...overrides.formats };
return {
labels,
formats,
functions: {
...makeDefaultGanttFunctions({ labels, formats }),
...overrides.functions,
},
};
}
export { DEFAULT_GANTT_I18N, mergeGanttI18n };
export type { GanttI18nConfig, GanttI18nOverrides };components/ui/gantt/gantt-lib.tsx
import { expandRecurrence } from '@/registry/vcare/ui/gantt/gantt-recurrence';
import type {
GanttBaseline,
GanttBaselineVariance,
GanttDateRange,
GanttEvent,
GanttOccurrence,
GanttOffDaysConfig,
GanttRecurrenceRule,
GanttResource,
GanttScale,
GanttSegment,
} from '@/registry/vcare/ui/gantt/gantt-types';
import { TZDate } from '@date-fns/tz';
import {
addDays,
addMonths,
addWeeks,
addYears,
differenceInMinutes,
format,
startOfDay,
startOfMonth,
startOfQuarter,
startOfWeek,
startOfYear,
} from 'date-fns';
type WeekStartsOn = 0 | 1 | 2 | 3 | 4 | 5 | 6;
/**
* Packing-effective minimum in minutes so tiny events do not stack invisibly.
* It is a packing FOOTPRINT, not a render size: two schedules less than this
* apart are treated as concurrent and split into separate lanes even though
* their real ranges do not touch.
*/
const MIN_PACK_SLOT = 30;
/** The instant re-expressed in the display time zone (TZDate extends Date). */
function toZoned(date: Date, timeZone: string): TZDate {
return new TZDate(date.getTime(), timeZone);
}
/** Zoned midnight of the day containing the instant. */
function zonedStartOfDay(date: Date, timeZone: string): TZDate {
return startOfDay(toZoned(date, timeZone));
}
/** Stable per-day key in the display time zone. */
function getDayKey(date: Date, timeZone: string): string {
return format(toZoned(date, timeZone), 'yyyy-MM-dd');
}
/** Day length in minutes; 1380/1500 on DST transition days - never assume 1440. */
function getDayTotalMinutes(dayStart: Date, timeZone: string): number {
const next = zonedStartOfDay(addDays(toZoned(dayStart, timeZone), 1), timeZone);
return differenceInMinutes(next, dayStart);
}
function snapMinutes(minutes: number, snap: number): number {
return Math.round(minutes / snap) * snap;
}
interface ViewRangeOptions {
timeZone: string;
weekStartsOn: WeekStartsOn;
}
interface ViewDateRanges {
visibleRange: GanttDateRange;
activeRange: GanttDateRange;
}
/** Axis range for the anchor date at the given scale. */
function getGanttDateRange(scale: GanttScale, date: Date, opts: ViewRangeOptions): ViewDateRanges {
const { timeZone, weekStartsOn } = opts;
const zoned = toZoned(date, timeZone);
if (scale === 'week') {
const start = startOfWeek(zoned, { weekStartsOn });
const range = { start, end: addWeeks(start, 1) };
return { activeRange: range, visibleRange: range };
}
if (scale === 'month') {
// exact month: no outside days on the horizontal axis
const start = startOfMonth(zoned);
const range = { start, end: startOfMonth(addMonths(zoned, 1)) };
return { activeRange: range, visibleRange: range };
}
if (scale === 'quarter') {
// week-aligned so the axis partitions into uniform week units
const quarterStart = startOfQuarter(zoned);
const quarterEnd = startOfQuarter(addMonths(zoned, 3));
const start = startOfWeek(quarterStart, { weekStartsOn });
let end = startOfWeek(quarterEnd, { weekStartsOn });
if (end < quarterEnd) end = addWeeks(end, 1);
return {
activeRange: { start: quarterStart, end: quarterEnd },
visibleRange: { start, end },
};
}
if (scale === 'year') {
const start = startOfYear(zoned);
const range = { start, end: startOfYear(addYears(zoned, 1)) };
return { activeRange: range, visibleRange: range };
}
const start = startOfDay(zoned);
const range = { start, end: addDays(start, 1) };
return { activeRange: range, visibleRange: range };
}
/** The anchor date stepped one period forward or backward for the scale. */
function stepGanttDate(scale: GanttScale, date: Date, direction: 1 | -1, opts: Pick<ViewRangeOptions, 'timeZone'>): Date {
const zoned = toZoned(date, opts.timeZone);
if (scale === 'week') return addWeeks(zoned, direction);
if (scale === 'month') return addMonths(zoned, direction);
if (scale === 'quarter') return addMonths(zoned, direction * 3);
if (scale === 'year') return addYears(zoned, direction);
return addDays(zoned, direction);
}
function rangesIntersect(a: GanttDateRange, b: GanttDateRange): boolean {
return a.start < b.end && a.end > b.start;
}
function eventsOverlap(a: { start: Date; end: Date }, b: { start: Date; end: Date }): boolean {
return a.start < b.end && a.end > b.start;
}
/**
* Range visibility for an occurrence: half-open like rangesIntersect, except
* a zero-length occurrence (a milestone). The plain test can never admit an
* instant sitting exactly on the range start, so milestones compare the
* start closed; the end stays exclusive - an instant on the range end
* belongs to the next period. gantt-recurrence inlines this same rule
* (importing it back here would cycle the modules).
*/
function occurrenceIntersects(occ: { start: Date; end: Date }, range: GanttDateRange): boolean {
if (occ.end.getTime() === occ.start.getTime()) {
return occ.start >= range.start && occ.start < range.end;
}
return rangesIntersect(occ, range);
}
function spansMultipleDays(occ: { start: Date; end: Date }): boolean {
// An event ending exactly at the next midnight is still single-day
// (exclusive end), so compare against a strictly-later instant.
return occ.end.getTime() - occ.start.getTime() > 24 * 60 * 60 * 1000;
}
/**
* The subject's validated planned window, or null: both instants present,
* end not before start, and (for events) non-recurring - a series has no
* single planned window. An edited single occurrence (recurringEventId
* without its own rule) is a plain event here and keeps its baseline.
* Structural on purpose: a GanttResource node's own baseline pair resolves
* through the same rule.
*/
function resolveEventBaseline(subject: {
baselineStart?: Date;
baselineEnd?: Date;
recurrence?: GanttRecurrenceRule | string;
}): GanttBaseline | null {
if (!subject.baselineStart || !subject.baselineEnd || subject.recurrence) {
return null;
}
const startMs = subject.baselineStart.getTime();
const endMs = subject.baselineEnd.getTime();
if (endMs < startMs) return null;
return {
start: subject.baselineStart,
end: subject.baselineEnd,
milestone: endMs === startMs,
};
}
interface GanttDependencyGeometry {
/** Orthogonal elbow path for the connector line, in the caller's units. */
line: string;
/** Filled arrowhead at the target anchor, pointing along +x. */
arrow: string;
}
/**
* Finish-to-start connector geometry from a predecessor's END anchor to a
* successor's START anchor, in whatever units the caller works in (the view
* passes rem). A target with room ahead takes the classic Z route: out by
* `clearance`, across to the target lane, in. A target at or behind the
* source's exit loops instead: out, hop `laneStep` toward the target's side
* (down when level - below reads as "later"), back past the target, in.
* The line stops `arrowSize` short of the anchor so it never pokes through
* the head. The exit stub can sit under an outside-after bar label; a
* consumer that shows those widens the label's start margin instead of the
* routing changing shape (a drop-first exit was tried and read worse
* everywhere else).
*/
function buildDependencyPath(
from: { x: number; y: number },
to: { x: number; y: number },
opts: { clearance: number; laneStep: number; arrowSize: number },
): GanttDependencyGeometry {
const { clearance, laneStep, arrowSize } = opts;
const lineEndX = to.x - arrowSize;
const arrow = `M ${to.x} ${to.y} L ${lineEndX} ${to.y - arrowSize * 0.6} L ${lineEndX} ${to.y + arrowSize * 0.6} Z`;
if (lineEndX >= from.x + clearance) {
return {
line: `M ${from.x} ${from.y} H ${from.x + clearance} V ${to.y} H ${lineEndX}`,
arrow,
};
}
const midY = to.y >= from.y ? from.y + laneStep : from.y - laneStep;
return {
line: `M ${from.x} ${from.y} H ${from.x + clearance} V ${midY} H ${to.x - clearance} V ${to.y} H ${lineEndX}`,
arrow,
};
}
/** Actual end against the planned end; null when no valid baseline exists. */
function getBaselineVariance<TData>(event: GanttEvent<TData>): GanttBaselineVariance | null {
const baseline = resolveEventBaseline(event);
if (!baseline) return null;
const deltaMs = event.end.getTime() - baseline.end.getTime();
return deltaMs > 0 ? 'late' : deltaMs < 0 ? 'early' : 'on-time';
}
interface PackedPosition {
column: number;
columnCount: number;
columnSpan: number;
}
/**
* Identity of a schedule ACROSS time edits. `occurrence.key` embeds the start
* instant, so it changes the moment a schedule is moved or start-resized -
* useless as lane memory. This key survives the edit: the event id plus, for a
* recurring series, the occurrence's position in it.
*/
function getLaneKey(occurrence: { eventId: string; recurrenceIndex?: number }): string {
return `${occurrence.eventId}::${occurrence.recurrenceIndex ?? 0}`;
}
/**
* What one schedule held on the previous layout pass. The TIMES are what make
* this more than a lane number: they are how the packer tells the schedule the
* user just edited apart from the ones that merely sat still.
*/
interface GanttLaneMemo {
lane: number;
startMs: number;
endMs: number;
}
interface PackOptions {
/**
* Where each schedule sat on the previous pass, by getLaneKey.
*
* A schedule whose times are UNCHANGED keeps its lane if that lane is still
* free, so editing one schedule never re-indexes the ones around it. A
* schedule whose times CHANGED - the one the user just dragged or resized -
* deliberately forfeits its pin and re-seeks the lowest free lane. That is
* what makes the arrangement live rather than frozen: a schedule dragged
* onto its neighbours stacks DOWN into the first free lane, and one dragged
* clear of them comes back UP inline. Only the edited schedule moves.
*/
preferredLanes?: Map<string, GanttLaneMemo>;
/** "single" collapses the row to one track; see GanttScheduleMode. */
mode?: 'single' | 'multiple';
}
/**
* Overlap packing for one row's timed segments.
* Mutates column/columnCount/columnSpan on the segments, in place.
* z resolution happens at render: event.zIndex verbatim, else 10 + column.
*/
function packTimedSegments<TData>(segments: GanttSegment<TData>[], options: PackOptions = {}): void {
if (segments.length === 0) return;
if (options.mode === 'single') {
// one track: every schedule shares lane 0 and the row never grows
for (const seg of segments) {
seg.column = 0;
seg.columnCount = 1;
seg.columnSpan = 1;
}
return;
}
const preferredLanes = options.preferredLanes;
type Working = {
seg: GanttSegment<TData>;
startMin: number;
effEnd: number;
lane: number;
/** The occupancy entry this item added, so a settle can take it back. */
interval?: { from: number; to: number };
};
const items: Working[] = segments
.map((seg) => {
const startMin = seg.startMin ?? 0;
const endMin = seg.endMin ?? startMin;
return {
seg,
startMin,
effEnd: Math.max(endMin, startMin + MIN_PACK_SLOT),
lane: -1,
};
})
.sort(
(a, b) =>
a.startMin - b.startMin || b.effEnd - b.startMin - (a.effEnd - a.startMin) || a.seg.occurrence.key.localeCompare(b.seg.occurrence.key),
);
// Sweep into connected clusters
const clusters: Working[][] = [];
let current: Working[] = [];
let clusterEnd = -Infinity;
for (const item of items) {
if (item.startMin >= clusterEnd) {
current = [];
clusters.push(current);
clusterEnd = -Infinity;
}
current.push(item);
clusterEnd = Math.max(clusterEnd, item.effEnd);
}
for (const cluster of clusters) {
// Per-lane occupancy INTERVALS, not a single running end: pass 1 claims
// remembered lanes out of time order, so a lane can be free before an
// occupant and busy after it.
const laneIntervals: Array<Array<{ from: number; to: number }>> = [];
const isFree = (lane: number, item: Working) => !(laneIntervals[lane] ?? []).some((iv) => iv.from < item.effEnd && iv.to > item.startMin);
const claim = (lane: number, item: Working) => {
while (laneIntervals.length <= lane) laneIntervals.push([]);
const interval = { from: item.startMin, to: item.effEnd };
laneIntervals[lane].push(interval);
item.lane = lane;
item.interval = interval;
};
const release = (item: Working) => {
const occupants = laneIntervals[item.lane] ?? [];
const at = occupants.indexOf(item.interval!);
if (at >= 0) occupants.splice(at, 1);
};
// pass 1: schedules that did not move keep the lane they had. The one the
// user just edited is NOT pinned - its times differ from the memo, so it
// falls through to pass 2 and re-seeks a lane against its new span.
const pending: Working[] = [];
for (const item of cluster) {
const memo = preferredLanes?.get(getLaneKey(item.seg.occurrence));
const untouched =
memo !== undefined && memo.startMs === item.seg.occurrence.start.getTime() && memo.endMs === item.seg.occurrence.end.getTime();
if (untouched && memo.lane >= 0 && isFree(memo.lane, item)) {
claim(memo.lane, item);
} else {
pending.push(item);
}
}
// pass 2: the rest take the lowest free lane - overlapping goes DOWN into
// the first lane with room, fitting comes back UP to lane 0
for (const item of pending) {
let lane = 0;
while (!isFree(lane, item)) lane++;
claim(lane, item);
}
// pass 3: nothing floats above an empty lane. A pin only survives while
// something above it still needs the space - once the schedule that was
// there moves away or is deleted, its neighbour settles down into the
// gap. Without this a row keeps a permanently blank top lane and never
// shrinks back. Settling in lane order, and only ever DOWNWARD into space
// that is genuinely free, means two schedules can never trade places -
// so an edit still moves at most the schedule it touched.
const byLane = [...cluster].sort((a, b) => a.lane - b.lane || a.startMin - b.startMin);
for (const item of byLane) {
if (item.lane === 0) continue;
let lane = 0;
while (lane < item.lane && !isFree(lane, item)) lane++;
if (lane < item.lane) {
release(item);
claim(lane, item);
}
}
}
// Lane memory can leave holes (the schedule that held lane 0 was deleted or
// moved away). Collapse the row's USED lanes onto 0..n-1: relative stacking
// order survives, so nothing reshuffles, but the row cannot creep taller
// than the lanes it actually needs.
const used = [...new Set(items.map((item) => item.lane))].sort((a, b) => a - b);
const compacted = new Map(used.map((lane, index) => [lane, index]));
const columnCount = used.length;
for (const item of items) {
item.lane = compacted.get(item.lane) ?? 0;
item.seg.column = item.lane;
item.seg.columnCount = columnCount;
}
// Partial-overlap expansion: widen rightward into free lanes
for (const cluster of clusters) {
for (const item of cluster) {
let span = 1;
while (item.lane + span < columnCount) {
const blocked = cluster.some(
(other) => other !== item && other.lane === item.lane + span && other.startMin < item.effEnd && other.effEnd > item.startMin,
);
if (blocked) break;
span++;
}
item.seg.columnSpan = span;
}
}
}
function defaultEventOrder(a: GanttOccurrence, b: GanttOccurrence): number {
return (
a.start.getTime() - b.start.getTime() || b.end.getTime() - b.start.getTime() - (a.end.getTime() - a.start.getTime()) || a.key.localeCompare(b.key)
);
}
interface BuildIndexOptions<TData = unknown> {
timeZone: string;
/** Escape hatch for exotic recurrence: return the expanded occurrences. */
getOccurrences?: (
event: GanttEvent<TData>,
range: GanttDateRange,
ctx: { timeZone: string },
) => Array<{ start: Date; end: Date }> | null | undefined;
eventOrder?: (a: GanttOccurrence<TData>, b: GanttOccurrence<TData>) => number;
}
interface GanttIndex<TData = unknown> {
occurrences: GanttOccurrence<TData>[];
}
function buildEventIndex<TData>(events: GanttEvent<TData>[], visibleRange: GanttDateRange, opts: BuildIndexOptions<TData>): GanttIndex<TData> {
const { timeZone } = opts;
const order = opts.eventOrder ?? defaultEventOrder;
// RECURRENCE-ID override replacement: an event carrying recurringEventId +
// originalStart is an edited single occurrence of that series. The parent's
// expansion drops the replaced instant; the override renders as its own
// occurrence through the normal path below.
const overrideTimes = new Map<string, Set<number>>();
for (const event of events) {
if (!event.recurringEventId || !event.originalStart) continue;
let times = overrideTimes.get(event.recurringEventId);
if (!times) overrideTimes.set(event.recurringEventId, (times = new Set()));
times.add(event.originalStart.getTime());
}
const occurrences: GanttOccurrence<TData>[] = [];
for (const event of events) {
const replaced = overrideTimes.get(event.id);
const custom = opts.getOccurrences?.(event, visibleRange, { timeZone });
if (custom) {
custom.forEach((occ, i) => {
if (replaced?.has(occ.start.getTime())) return;
if (!occurrenceIntersects({ start: occ.start, end: occ.end }, visibleRange)) return;
occurrences.push({
key: `${event.id}::${occ.start.toISOString()}`,
eventId: event.id,
event,
start: occ.start,
end: occ.end,
allDay: event.allDay ?? false,
isRecurring: true,
recurrenceIndex: i,
});
});
continue;
}
const expanded = expandRecurrence(event, visibleRange, { timeZone });
occurrences.push(...(replaced ? expanded.filter((occ) => !replaced.has(occ.start.getTime())) : expanded));
}
occurrences.sort(order);
return { occurrences };
}
/** Cache key for index memoization; cheap string compare. */
function getRangeKey(range: GanttDateRange): string {
return `${range.start.getTime()}-${range.end.getTime()}`;
}
/** Depth-first flatten of the resource tree (parents included). */
function flattenResources(resources: GanttResource[], depth = 0): Array<{ resource: GanttResource; depth: number }> {
const rows: Array<{ resource: GanttResource; depth: number }> = [];
for (const resource of resources) {
rows.push({ resource, depth });
if (resource.children?.length) {
rows.push(...flattenResources(resource.children, depth + 1));
}
}
return rows;
}
/** Depth-first lookup of one node in the tree. */
function findResource(resources: GanttResource[], id: string): GanttResource | null {
for (const resource of resources) {
if (resource.id === id) return resource;
const found = resource.children?.length ? findResource(resource.children, id) : null;
if (found) return found;
}
return null;
}
/**
* Pure tree move: removes `resourceId` from wherever it sits and reinserts it
* under `parentId` (null = root) at `index`. Returns a new tree; the original
* is untouched. Returns null for impossible moves (unknown ids, or dropping a
* node into its own subtree).
*/
function reorderResources(resources: GanttResource[], resourceId: string, parentId: string | null, index: number): GanttResource[] | null {
let moved: GanttResource | null = null;
const strip = (nodes: GanttResource[]): GanttResource[] =>
nodes.flatMap((node) => {
if (node.id === resourceId) {
moved = node;
return [];
}
if (!node.children?.length) return [node];
return [{ ...node, children: strip(node.children) }];
});
const stripped = strip(resources);
if (!moved) return null;
const contains = (node: GanttResource, id: string): boolean => node.id === id || !!node.children?.some((child) => contains(child, id));
if (parentId !== null && contains(moved, parentId)) return null;
const insert = (nodes: GanttResource[]): GanttResource[] => {
if (parentId === null) {
const next = [...nodes];
next.splice(Math.min(Math.max(index, 0), next.length), 0, moved!);
return next;
}
return nodes.map((node) => {
if (node.id === parentId) {
const children = [...(node.children ?? [])];
children.splice(Math.min(Math.max(index, 0), children.length), 0, moved!);
return { ...node, children };
}
if (!node.children?.length) return node;
return { ...node, children: insert(node.children) };
});
};
const next = insert(stripped);
// unknown parentId: the node vanished - reject
if (parentId !== null) {
const flat = flattenResources(next);
if (!flat.some(({ resource }) => resource.id === resourceId)) return null;
}
return next;
}
const DEFAULT_WEEKEND_DAYS = [0, 6];
/** Resolves whether a day is an off day (non-working) in the display zone. */
function resolveOffDay(day: Date, timeZone: string, config: boolean | GanttOffDaysConfig | undefined): boolean {
if (!config) return false;
const resolved: GanttOffDaysConfig = config === true ? {} : config;
const weekendDays = resolved.weekendDays ?? DEFAULT_WEEKEND_DAYS;
const zoned = toZoned(day, timeZone);
if (weekendDays.includes(zoned.getDay())) return true;
if (resolved.dates?.length) {
const key = getDayKey(day, timeZone);
if (resolved.dates.some((date) => getDayKey(date, timeZone) === key)) {
return true;
}
}
return resolved.isOffDay?.(day) ?? false;
}
export {
buildDependencyPath,
buildEventIndex,
defaultEventOrder,
eventsOverlap,
findResource,
flattenResources,
getBaselineVariance,
getDayKey,
getDayTotalMinutes,
getGanttDateRange,
getLaneKey,
getRangeKey,
MIN_PACK_SLOT,
occurrenceIntersects,
packTimedSegments,
rangesIntersect,
reorderResources,
resolveEventBaseline,
resolveOffDay,
snapMinutes,
spansMultipleDays,
stepGanttDate,
toZoned,
zonedStartOfDay,
};
export type { BuildIndexOptions, GanttDependencyGeometry, GanttIndex, GanttLaneMemo, PackOptions, ViewDateRanges, ViewRangeOptions, WeekStartsOn };components/ui/gantt/gantt-nav.tsx
'use client';
import { useState, type ReactNode } from 'react';
import { useGanttNavigation, useGanttScale, useGanttSettings, useGanttViewConfig } from '@/registry/vcare/ui/gantt/gantt';
import { toZoned } from '@/registry/vcare/ui/gantt/gantt-lib';
import type { GanttScale } from '@/registry/vcare/ui/gantt/gantt-types';
import { mergeProps } from '@base-ui/react/merge-props';
import { useRender } from '@base-ui/react/use-render';
import { format } from 'date-fns';
import { cn } from '@/registry/vcare/lib/utils';
import { Button } from '@/registry/vcare/ui/button';
import { Calendar } from '@/registry/vcare/ui/calendar';
import {
DropdownMenu,
DropdownMenuContent,
DropdownMenuGroup,
DropdownMenuItem,
DropdownMenuLabel,
DropdownMenuTrigger,
} from '@/registry/vcare/ui/dropdown-menu';
import { Popover, PopoverContent, PopoverTrigger } from '@/registry/vcare/ui/popover';
import { Tooltip, TooltipContent, TooltipProvider, TooltipTrigger } from '@/registry/vcare/ui/tooltip';
import { ChevronLeftIcon, ChevronRightIcon, ChevronDownIcon, CalendarIcon } from 'lucide-react';
const GANTT_SCALES: GanttScale[] = ['day', 'week', 'month', 'quarter', 'year'];
/** Configured nav button variant/size (viewConfig.navButtonVariant/Size). */
function useNavButtonProps(): {
variant: 'ghost' | 'outline' | 'secondary' | 'default';
size: 'sm' | 'default';
iconSize: 'icon-sm' | 'icon';
} {
const viewConfig = useGanttViewConfig();
return {
variant: viewConfig.navButtonVariant,
size: viewConfig.navButtonSize,
iconSize: viewConfig.navButtonSize === 'sm' ? 'icon-sm' : 'icon',
};
}
type NavButtonProps = Omit<useRender.ComponentProps<'button'>, 'children'> & {
children?: ReactNode;
/**
* Tooltip policy (the part that usually goes wrong on clickable elements):
* tooltips appear ONLY on hover or keyboard focus-visible - a pointer click
* never re-triggers them, and buttons that open overlays (the period
* selector, consumer dialog buttons) get NO tooltip at all so nothing
* flashes when focus returns. Icon-only buttons default to their accessible
* label; Today defaults to the actual current date. Pass null to disable.
*/
tooltip?: ReactNode | null;
};
/** Hover/focus-visible tooltip wrapper; renders the bare button when disabled. */
function NavTooltip({ content, children }: { content: ReactNode | null; children: React.ReactElement }) {
if (content === null || content === undefined) return children;
return (
<Tooltip>
<TooltipTrigger render={children} />
<TooltipContent side="bottom">{content}</TooltipContent>
</Tooltip>
);
}
function GanttNavToday({ className, render, children, tooltip, ...props }: NavButtonProps) {
const { today, isToday } = useGanttNavigation();
const settings = useGanttSettings();
const nav = useNavButtonProps();
// zoned: a system-zone new Date() can name a different day than Today opens
const defaultTooltip = format(toZoned(new Date(), settings.timeZone), settings.i18n.formats.dayTitle, {
locale: settings.locale,
});
return (
<NavTooltip content={tooltip === undefined ? defaultTooltip : tooltip}>
<Button
variant={nav.variant}
size={nav.size}
data-slot="gantt-nav-today"
data-active={isToday || undefined}
className={cn(className)}
onClick={today}
render={render}
{...props}
>
{children ?? settings.i18n.labels.today}
</Button>
</NavTooltip>
);
}
function GanttNavPrev({ className, render, children, tooltip, ...props }: NavButtonProps) {
const { prev } = useGanttNavigation();
const settings = useGanttSettings();
const nav = useNavButtonProps();
return (
<NavTooltip content={tooltip === undefined ? settings.i18n.labels.previous : tooltip}>
<Button
variant={nav.variant}
size={nav.iconSize}
data-slot="gantt-nav-prev"
aria-label={settings.i18n.labels.previous}
className={cn(className)}
onClick={prev}
render={render}
{...props}
>
{children ?? <ChevronLeftIcon className="size-4" aria-hidden="true" />}
</Button>
</NavTooltip>
);
}
function GanttNavNext({ className, render, children, tooltip, ...props }: NavButtonProps) {
const { next } = useGanttNavigation();
const settings = useGanttSettings();
const nav = useNavButtonProps();
return (
<NavTooltip content={tooltip === undefined ? settings.i18n.labels.next : tooltip}>
<Button
variant={nav.variant}
size={nav.iconSize}
data-slot="gantt-nav-next"
aria-label={settings.i18n.labels.next}
className={cn(className)}
onClick={next}
render={render}
{...props}
>
{children ?? <ChevronRightIcon className="size-4" aria-hidden="true" />}
</Button>
</NavTooltip>
);
}
interface GanttTitleProps extends useRender.ComponentProps<'div'> {
format?: (ctx: { title: string }) => ReactNode;
}
function GanttTitle({ className, render, format: formatTitle, ...props }: GanttTitleProps) {
const { title } = useGanttNavigation();
const defaultProps = {
'data-slot': 'gantt-title',
'aria-live': 'polite' as const,
className: cn('min-w-0 truncate text-sm font-semibold', className),
children: formatTitle?.({ title }) ?? title,
};
return useRender({
defaultTagName: 'div',
render,
props: mergeProps<'div'>(defaultProps, props),
});
}
interface GanttScaleSwitcherProps extends Omit<useRender.ComponentProps<'button'>, 'children'> {
children?: ReactNode;
/** Hover/focus-visible hint; defaults to the "Select view" label. Pass
* null to disable (overlay-opener policy). */
tooltip?: ReactNode | null;
/** The offered scales, in menu order. Default: all five. */
scales?: GanttScale[];
}
/**
* Scale switcher ("Select view"): Day / Week / Month / Quarter / Year, a ghost
* dropdown button (same shape as the event-calendar view switcher).
*/
function GanttScaleSwitcher({ className, render, children, tooltip, scales = GANTT_SCALES, ...props }: GanttScaleSwitcherProps) {
const { scale, setScale } = useGanttScale();
const settings = useGanttSettings();
const nav = useNavButtonProps();
const labels = settings.i18n.labels;
// Controlled open: selecting a scale swaps the whole track subtree in the
// same click, so closing must not depend on the menu's internal handler.
const [open, setOpen] = useState(false);
// Hover-only tooltip: when the menu closes, Base UI focuses the trigger
// again and a focus-opened tooltip would flash - ignore focus opens.
const [tipOpen, setTipOpen] = useState(false);
const selectScale = (next: GanttScale) => {
setOpen(false);
setScale(next);
};
return (
<DropdownMenu
open={open}
onOpenChange={(next: boolean) => {
setOpen(next);
if (next) setTipOpen(false);
}}
>
{/* Tooltip on an overlay-opener: hover-only (focus opens ignored) and
force-closed while the menu is up, so it never lingers or flashes
when focus returns on close. */}
<Tooltip
open={tipOpen && !open}
onOpenChange={(next: boolean, details: { reason?: string }) => {
// opens are hover-only; the trigger-focus open that follows a
// menu close is ignored, closes always land
if (next && details?.reason !== 'trigger-hover') return;
setTipOpen(next);
}}
>
<DropdownMenuTrigger
render={
<TooltipTrigger
render={
<Button
variant={nav.variant}
size={nav.size}
data-slot="gantt-scale-switcher"
aria-label={labels.selectView}
className={cn('gap-1', className)}
/>
}
/>
}
{...props}
>
{children ?? (
<>
{labels.scales[scale]}
<ChevronDownIcon className="size-4 opacity-60" aria-hidden="true" />
</>
)}
</DropdownMenuTrigger>
{tipOpen && !open && tooltip !== null && <TooltipContent side="bottom">{tooltip ?? labels.selectView}</TooltipContent>}
</Tooltip>
<DropdownMenuContent align="start" className="min-w-36">
{/* Base UI contract: GroupLabel must live inside Menu.Group */}
<DropdownMenuGroup>
<DropdownMenuLabel className="text-muted-foreground font-normal">{labels.selectView}</DropdownMenuLabel>
{scales.map((value) => (
<DropdownMenuItem key={value} data-active={scale === value || undefined} onClick={() => selectScale(value)}>
{labels.scales[value]}
</DropdownMenuItem>
))}
</DropdownMenuGroup>
</DropdownMenuContent>
</DropdownMenu>
);
}
interface GanttDatePickerProps {
className?: string;
}
/**
* Compact go-to-date picker (shadcn Calendar in a popover). No tooltip by
* design: it opens an overlay (see the NavButtonProps tooltip policy).
*/
function GanttDatePicker({ className }: GanttDatePickerProps) {
const { date, goTo } = useGanttNavigation();
const settings = useGanttSettings();
const nav = useNavButtonProps();
const [open, setOpen] = useState(false);
const zoned = toZoned(date, settings.timeZone);
return (
<Popover open={open} onOpenChange={setOpen}>
<PopoverTrigger
render={
<Button
variant={nav.variant}
size={nav.iconSize}
data-slot="gantt-date-picker"
aria-label={settings.i18n.labels.goToDate}
className={cn(className)}
/>
}
>
<CalendarIcon className="size-4" aria-hidden="true" />
</PopoverTrigger>
<PopoverContent align="start" className="w-auto p-0!">
<Calendar
mode="single"
selected={zoned}
defaultMonth={zoned}
locale={settings.locale}
weekStartsOn={settings.weekStartsOn}
onSelect={(next: Date | undefined) => {
if (next) {
goTo(next);
setOpen(false);
}
}}
/>
</PopoverContent>
</Popover>
);
}
type GanttToolbarProps = useRender.ComponentProps<'div'>;
/** Free slot for consumer toolbar buttons; pure layout shell. */
function GanttToolbar({ className, render, ...props }: GanttToolbarProps) {
const viewConfig = useGanttViewConfig();
const defaultProps = {
'data-slot': 'gantt-toolbar',
className: cn('flex items-center gap-2', viewConfig.classNames?.toolbar, className),
children: props.children,
};
return useRender({
defaultTagName: 'div',
render,
props: mergeProps<'div'>(defaultProps, props),
});
}
type GanttNavProps = useRender.ComponentProps<'div'>;
/**
* Default composed nav (event-calendar parity): Today, time-period switcher,
* prev/next, title, spacer. GanttDatePicker stays available for custom
* compositions. Pass children to use it as a pure layout shell instead.
*/
function GanttNav({ className, render, children, ...props }: GanttNavProps) {
const viewConfig = useGanttViewConfig();
const defaultProps = {
'data-slot': 'gantt-nav',
className: cn(
// px so the toolbar controls do not hug the container edge; border-b
// separates the toolbar from the column header below it
'flex min-w-0 flex-wrap items-center gap-2 border-b px-3 py-2',
viewConfig.stickyNav && 'bg-background sticky top-0 z-30',
viewConfig.classNames?.nav,
className,
),
children: children ?? (
// Shared provider: first tooltip waits, moving between buttons is instant
<TooltipProvider delay={600} closeDelay={0} timeout={300}>
<GanttNavToday />
<GanttScaleSwitcher />
<div className="flex items-center">
<GanttNavPrev />
<GanttNavNext />
</div>
<GanttTitle />
<div className="grow" />
</TooltipProvider>
),
};
return useRender({
defaultTagName: 'div',
render,
props: mergeProps<'div'>(defaultProps, props),
});
}
export { GANTT_SCALES, GanttDatePicker, GanttNav, GanttNavNext, GanttNavPrev, GanttNavToday, GanttScaleSwitcher, GanttTitle, GanttToolbar };
export type { GanttNavProps, GanttScaleSwitcherProps, GanttTitleProps, GanttToolbarProps };components/ui/gantt/gantt-recurrence.tsx
import type { GanttDateRange, GanttEvent, GanttOccurrence, GanttRecurrenceRule, GanttWeekday } from '@/registry/vcare/ui/gantt/gantt-types';
import { TZDate } from '@date-fns/tz';
import { addDays, addMonths, addWeeks, addYears } from 'date-fns';
/** Guard: max occurrences per event per expansion. */
const MAX_OCCURRENCES = 1000;
const WEEKDAYS: GanttWeekday[] = ['SU', 'MO', 'TU', 'WE', 'TH', 'FR', 'SA'];
class GanttRecurrenceError extends Error {
constructor(part: string) {
super(`Unsupported recurrence part: ${part}. Use the getOccurrences prop to plug a full RRULE engine for exotic rules.`);
this.name = 'GanttRecurrenceError';
}
}
/**
* Parses a raw RRULE line (with or without the "RRULE:" prefix) into the
* structured subset. Pass the display time zone so a floating UNTIL
* (no trailing Z) resolves there instead of in the runtime's local zone.
*/
function parseRRuleString(input: string, timeZone?: string): GanttRecurrenceRule {
const body = input.trim().replace(/^RRULE:/i, '');
const rule: Partial<GanttRecurrenceRule> = {};
for (const pair of body.split(';')) {
if (!pair) continue;
const [rawKey, rawValue] = pair.split('=');
const key = rawKey?.toUpperCase();
const value = rawValue ?? '';
switch (key) {
case 'FREQ': {
const freq = value.toLowerCase();
if (freq !== 'daily' && freq !== 'weekly' && freq !== 'monthly' && freq !== 'yearly') {
throw new GanttRecurrenceError(`FREQ=${value}`);
}
rule.freq = freq;
break;
}
case 'INTERVAL':
rule.interval = Math.max(1, parseInt(value, 10) || 1);
break;
case 'COUNT':
rule.count = Math.max(1, parseInt(value, 10) || 1);
break;
case 'UNTIL':
rule.until = parseRRuleDate(value, timeZone);
break;
case 'BYDAY':
rule.byWeekday = value.split(',').map((token) => {
const match = /^(-?\d+)?(SU|MO|TU|WE|TH|FR|SA)$/.exec(token.trim());
if (!match) throw new GanttRecurrenceError(`BYDAY=${token}`);
const day = match[2] as GanttWeekday;
return match[1] ? { day, ordinal: parseInt(match[1], 10) } : day;
});
break;
case 'BYMONTHDAY':
rule.byMonthDay = value.split(',').map((v) => parseInt(v, 10));
break;
case 'BYMONTH':
rule.byMonth = value.split(',').map((v) => parseInt(v, 10));
break;
case 'WKST': {
if (!WEEKDAYS.includes(value as GanttWeekday)) {
throw new GanttRecurrenceError(`WKST=${value}`);
}
rule.weekStart = value as GanttWeekday;
break;
}
default:
throw new GanttRecurrenceError(key ?? pair);
}
}
if (!rule.freq) throw new GanttRecurrenceError('missing FREQ');
return rule as GanttRecurrenceRule;
}
function parseRRuleDate(value: string, timeZone?: string): Date {
// RFC 5545 basic formats: YYYYMMDD or YYYYMMDDTHHMMSS(Z)
const match = /^(\d{4})(\d{2})(\d{2})(?:T(\d{2})(\d{2})(\d{2})(Z)?)?$/.exec(value);
if (!match) throw new GanttRecurrenceError(`UNTIL=${value}`);
const [, y, m, d, hh = '23', mm = '59', ss = '59', z] = match;
// Floating (non-Z) boundaries resolve in the DISPLAY zone when known -
// local-zone parsing would shift the series end per visitor machine.
const date = !z && timeZone ? new TZDate(+y, +m - 1, +d, +hh, +mm, +ss, timeZone) : new Date(`${y}-${m}-${d}T${hh}:${mm}:${ss}${z ? 'Z' : ''}`);
if (Number.isNaN(date.getTime())) {
throw new GanttRecurrenceError(`UNTIL=${value}`);
}
return new Date(date.getTime());
}
/** Serializes the structured subset back to an RRULE line (without prefix). */
function formatRRuleString(rule: GanttRecurrenceRule): string {
const parts: string[] = [`FREQ=${rule.freq.toUpperCase()}`];
if (rule.interval && rule.interval > 1) parts.push(`INTERVAL=${rule.interval}`);
if (rule.count) parts.push(`COUNT=${rule.count}`);
if (rule.until) {
const u = rule.until;
const pad = (n: number) => String(n).padStart(2, '0');
parts.push(
`UNTIL=${u.getUTCFullYear()}${pad(u.getUTCMonth() + 1)}${pad(u.getUTCDate())}T${pad(u.getUTCHours())}${pad(u.getUTCMinutes())}${pad(u.getUTCSeconds())}Z`,
);
}
if (rule.byWeekday?.length) {
parts.push(`BYDAY=${rule.byWeekday.map((d) => (typeof d === 'string' ? d : `${d.ordinal}${d.day}`)).join(',')}`);
}
if (rule.byMonthDay?.length) parts.push(`BYMONTHDAY=${rule.byMonthDay.join(',')}`);
if (rule.byMonth?.length) parts.push(`BYMONTH=${rule.byMonth.join(',')}`);
if (rule.weekStart) parts.push(`WKST=${rule.weekStart}`);
return parts.join(';');
}
function resolveRule(recurrence: GanttRecurrenceRule | string, timeZone?: string): GanttRecurrenceRule {
return typeof recurrence === 'string' ? parseRRuleString(recurrence, timeZone) : recurrence;
}
/**
* Expands one event into its occurrences intersecting the range.
* Non-recurring events yield at most one occurrence. Recurrence iteration is
* wall-time based in the display zone (DST-safe day/week/month steps).
*
* Supported subset: FREQ daily/weekly/monthly/yearly, INTERVAL, COUNT, UNTIL,
* weekly BYDAY (no ordinals). Parsed-but-unimplemented filters (BYMONTHDAY,
* BYMONTH, BYDAY outside weekly) throw a GanttRecurrenceError instead of
* silently mis-expanding; plug the getOccurrences prop for a full engine.
* WKST parses and round-trips; week emission is Sunday-anchored.
*
* exDates remove exactly-matching instants (after COUNT numbering,
* Google-style: an exception still consumes its COUNT slot); rDates add extra
* instants with the same duration. RECURRENCE-ID override replacement lives
* in buildEventIndex, where the override event and its parent series meet.
*/
function expandRecurrence<TData>(event: GanttEvent<TData>, range: GanttDateRange, ctx: { timeZone: string }): GanttOccurrence<TData>[] {
const allDay = event.allDay ?? false;
if (!event.recurrence) {
// Same rule as occurrenceIntersects in gantt-lib, inlined (importing it
// back would cycle the modules): half-open, except a zero-length
// milestone sitting exactly on the range start stays visible.
const visible =
event.end.getTime() === event.start.getTime()
? event.start >= range.start && event.start < range.end
: event.start < range.end && event.end > range.start;
if (visible) {
return [
{
key: `${event.id}::${event.start.toISOString()}`,
eventId: event.id,
event,
start: event.start,
end: event.end,
allDay,
isRecurring: false,
},
];
}
return [];
}
const rule = resolveRule(event.recurrence, ctx.timeZone);
// Loud contract: silently ignoring a filter would emit WRONG occurrences.
if (rule.byMonthDay?.length) throw new GanttRecurrenceError('BYMONTHDAY');
if (rule.byMonth?.length) throw new GanttRecurrenceError('BYMONTH');
if (rule.byWeekday?.length && rule.freq !== 'weekly') {
throw new GanttRecurrenceError('BYDAY outside FREQ=WEEKLY');
}
const interval = Math.max(1, rule.interval ?? 1);
const durationMs = event.end.getTime() - event.start.getTime();
const zonedStart = new TZDate(event.start.getTime(), ctx.timeZone);
// Excluded instants matched exactly; filtering happens at push time so an
// exception still consumes its COUNT slot (Google-style numbering).
const exTimes = new Set((rule.exDates ?? []).map((d) => d.getTime()));
const weeklyDays: number[] | null =
rule.freq === 'weekly' && rule.byWeekday?.length
? rule.byWeekday.map((d) => {
if (typeof d !== 'string') {
throw new GanttRecurrenceError('BYDAY ordinal outside monthly/yearly');
}
return WEEKDAYS.indexOf(d);
})
: null;
const occurrences: GanttOccurrence<TData>[] = [];
let produced = 0;
let index = 0;
let cursor = zonedStart;
const advance = (from: TZDate, steps: number): TZDate =>
rule.freq === 'daily'
? addDays(from, steps * interval)
: rule.freq === 'weekly'
? addWeeks(from, steps * interval)
: rule.freq === 'monthly'
? addMonths(from, steps * interval)
: addYears(from, steps * interval);
// Fast-forward past periods entirely before the range: they produce
// nothing and must not consume the occurrence cap (an old-enough daily
// series would otherwise exhaust MAX_OCCURRENCES before reaching the
// window and silently vanish). COUNT rules jump too: the skipped periods
// are credited to `index`, which is what terminates the series, so the
// count still ends it on exactly the right instant. Leaving them on full
// iteration would hide any series whose count exceeds MAX_OCCURRENCES.
//
// Daily and weekly ONLY. Their step is a fixed wall-time length, so one jump
// of N steps lands exactly where N single steps land. addMonths/addYears
// CLAMP instead: a Jan 31 monthly anchor steps to Feb 28 and never returns to
// the 31st, while a single jump from the anchor clamps at most once. Jumping
// those would make the same occurrence render on a different day depending on
// which window the viewer scrolled in from, so they always iterate.
const canFastForward = rule.freq === 'daily' || rule.freq === 'weekly';
// weekly BYDAY emits across the cursor's whole Sunday week
const weekSlackMs = weeklyDays ? 6 * 86_400_000 : 0;
// divide by the LONGEST possible step so the jump can never overshoot
const maxStepMs =
(rule.freq === 'daily' ? 24 : rule.freq === 'weekly' ? 7 * 24 : rule.freq === 'monthly' ? 31 * 24 : 366 * 24) * 3_600_000 * interval + 3_600_000;
for (let pass = 0; canFastForward && pass < 2; pass++) {
const gap = range.start.getTime() - durationMs - weekSlackMs - cursor.getTime();
const skip = Math.floor(gap / maxStepMs);
if (skip <= 0) break;
cursor = advance(cursor, skip);
index += skip * (weeklyDays ? weeklyDays.length : 1);
}
// close the remainder step by step (bounded by the jump math)
let guard = 0;
while (
guard++ < 10_000 &&
!(rule.until && cursor.getTime() > rule.until.getTime()) &&
cursor.getTime() + durationMs + weekSlackMs < range.start.getTime()
) {
cursor = advance(cursor, 1);
index += weeklyDays ? weeklyDays.length : 1;
}
// The jump credits a whole week of selected days per skipped week, but full
// iteration never counts the selected days that fall BEFORE the anchor
// inside the anchor's own week. Drop them once so both paths number the
// same instant identically (index counts occurrences at or after the
// anchor, and only those).
if (weeklyDays && index > 0) {
index -= weeklyDays.filter((day) => day < zonedStart.getDay()).length;
}
const pushIfVisible = (rawStart: Date) => {
// normalize to a plain instant so consumers never receive zone-carrying
// TZDate instances (mixed-zone formatting bugs)
const start = new Date(rawStart.getTime());
if (exTimes.has(start.getTime())) return;
const end = new Date(start.getTime() + durationMs);
// zero-length instances (milestones) keep the closed-start visibility
// rule; see the non-recurring branch above
const visible = durationMs === 0 ? start >= range.start && start < range.end : start < range.end && end > range.start;
if (visible) {
occurrences.push({
key: `${event.id}::${start.toISOString()}`,
eventId: event.id,
event,
start,
end,
allDay,
isRecurring: true,
recurrenceIndex: index,
});
}
};
while (produced < MAX_OCCURRENCES) {
if (rule.until && cursor.getTime() > rule.until.getTime()) break;
// COUNT is series-absolute, so it reads `index` (the position in the
// series, fast-forward included) rather than `produced` (emissions in
// this loop, which MAX_OCCURRENCES caps).
if (rule.count !== undefined && index >= rule.count) break;
// Past the visible window with no count to honor - stop iterating. For
// weekly BYDAY the WEEK START decides: selected days earlier in the
// anchor's week can still fall before range.end.
const horizonMs = weeklyDays ? addDays(cursor, -cursor.getDay()).getTime() : cursor.getTime();
if (horizonMs >= range.end.getTime() && rule.count === undefined) {
break;
}
if (rule.freq === 'weekly' && weeklyDays) {
// Emit each selected weekday within the cursor's week
for (let d = 0; d < 7; d++) {
const candidate = addDays(cursor, d - cursor.getDay());
if (!weeklyDays.includes(candidate.getDay())) continue;
if (candidate.getTime() < zonedStart.getTime()) continue;
if (rule.until && candidate.getTime() > rule.until.getTime()) continue;
// the cap is checked here too, or a week that crosses it mid-loop
// still emits its remaining selected days
if (produced >= MAX_OCCURRENCES) break;
if (rule.count !== undefined && index >= rule.count) break;
pushIfVisible(candidate);
produced++;
index++;
}
} else {
pushIfVisible(cursor);
produced++;
index++;
}
cursor = advance(cursor, 1);
}
// RDATE: extra instants join the set (deduped against generated starts and
// exclusions) with the same wall-time duration. Sorted so direct consumers
// still receive chronological order (buildEventIndex re-sorts regardless).
if (rule.rDates?.length) {
const seen = new Set(occurrences.map((o) => o.start.getTime()));
for (const rDate of rule.rDates) {
const start = new Date(rDate.getTime());
if (seen.has(start.getTime()) || exTimes.has(start.getTime())) continue;
const end = new Date(start.getTime() + durationMs);
// mirrored visibility rule: zero-length RDATEs stay closed at the start
const hidden = durationMs === 0 ? start < range.start || start >= range.end : start >= range.end || end <= range.start;
if (hidden) continue;
seen.add(start.getTime());
occurrences.push({
key: `${event.id}::${start.toISOString()}`,
eventId: event.id,
event,
start,
end,
allDay,
isRecurring: true,
// keep counting past the generated instants: an RDATE with no index
// would fall back to 0 and collide with the series' first occurrence
// in any consumer that identifies an instance by its position
recurrenceIndex: index++,
});
}
occurrences.sort((a, b) => a.start.getTime() - b.start.getTime());
}
return occurrences;
}
export { GanttRecurrenceError, expandRecurrence, formatRRuleString, MAX_OCCURRENCES, parseRRuleString };components/ui/gantt/gantt-scroll-area.tsx
'use client';
import * as React from 'react';
import { ScrollArea as ScrollAreaPrimitive } from '@base-ui/react/scroll-area';
import { cn } from '@/registry/vcare/lib/utils';
/** The Base UI scroll area the Gantt panes need: they put a ScrollArea.Content inside the viewport so the bars stay measured. */
function ScrollArea({ className, children, ...props }: ScrollAreaPrimitive.Root.Props) {
return (
<ScrollAreaPrimitive.Root data-slot="scroll-area" className={cn('relative overflow-hidden', className)} {...props}>
<ScrollAreaPrimitive.Viewport
data-slot="scroll-area-viewport"
className="size-full overscroll-contain rounded-[inherit] outline-none focus-visible:ring-[3px] focus-visible:ring-ring/50"
>
{children}
</ScrollAreaPrimitive.Viewport>
<ScrollBar orientation="vertical" />
<ScrollAreaPrimitive.Corner />
</ScrollAreaPrimitive.Root>
);
}
function ScrollBar({ className, orientation = 'vertical', ...props }: ScrollAreaPrimitive.Scrollbar.Props) {
return (
<ScrollAreaPrimitive.Scrollbar
data-slot="scroll-area-scrollbar"
data-orientation={orientation}
orientation={orientation}
className={cn(
'flex touch-none p-px transition-colors select-none',
orientation === 'vertical' && 'h-full w-2.5 border-s border-s-transparent',
orientation === 'horizontal' && 'h-2.5 flex-col border-t border-t-transparent',
className,
)}
{...props}
>
<ScrollAreaPrimitive.Thumb data-slot="scroll-area-thumb" className="relative flex-1 rounded-full bg-border" />
</ScrollAreaPrimitive.Scrollbar>
);
}
export { ScrollArea, ScrollBar };components/ui/gantt/gantt-types.tsx
type GanttBarId = string;
type GanttScale = 'day' | 'week' | 'month' | 'quarter' | 'year';
/** Row drag-reorder proposal: `parentId` null is root, `resources` is the tree with the move applied. */
interface GanttResourceReorder {
resourceId: string;
parentId: string | null;
/** Position among the new parent's children, the moved row excluded. */
index: number;
resources: GanttResource[];
}
/**
* "single" keeps the node on one track and refuses any gesture that would
* create a concurrent schedule; "multiple" stacks them into stable lanes.
*/
type GanttScheduleMode = 'single' | 'multiple';
/**
* Drop policy for a gesture overlapping another schedule in the SAME node.
* Policy only - overlapping data always renders. "allow" (default) commits as
* proposed, "clamp" stops at the neighbour's edge, "reject" never commits.
*/
type GanttOverlapPolicy = 'allow' | 'reject' | 'clamp';
/** Vertical placement of row content when the node holds several lanes; "start" pins it to the first lane. */
type GanttRowAlign = 'start' | 'center';
/** One tree node, not domain-bound: a task (one schedule) or a resource lane (many). Children nest as collapsible groups. */
interface GanttResource {
id: string;
title: string;
color?: string;
/** Per-node cardinality; falls back to the view-level default. */
scheduleMode?: GanttScheduleMode;
/**
* Planned (as-built baseline) window for the WHOLE node, ghosted as a
* band behind its lanes - independent of any per-event baselines. Half
* open; set both or neither. Equal instants mark a planned milestone.
*/
baselineStart?: Date;
baselineEnd?: Date;
children?: GanttResource[];
}
/** Preferred name for a tree node; `GanttResource` is the legacy alias. */
type GanttNode = GanttResource;
/** Half-open: `start` inclusive, `end` exclusive. */
interface GanttDateRange {
start: Date;
end: Date;
}
type GanttWeekday = 'MO' | 'TU' | 'WE' | 'TH' | 'FR' | 'SA' | 'SU';
interface GanttRecurrenceRule {
freq: 'daily' | 'weekly' | 'monthly' | 'yearly';
interval?: number;
count?: number;
/** Inclusive, unlike the exclusive `end` of a range. */
until?: Date;
byWeekday?: Array<GanttWeekday | { day: GanttWeekday; ordinal: number }>;
byMonthDay?: number[];
byMonth?: number[];
weekStart?: GanttWeekday;
exDates?: Date[];
rDates?: Date[];
}
interface GanttEvent<TData = unknown> {
id: GanttBarId;
title: string;
/** Plain instants, not ISO strings. `end` is exclusive and must be >= start. */
start: Date;
end: Date;
allDay?: boolean;
/** Structured rule or a raw "RRULE:..." line. */
recurrence?: GanttRecurrenceRule | string;
/** An edited single occurrence of that series; `originalStart` is the RECURRENCE-ID it replaces. */
recurringEventId?: GanttBarId;
originalStart?: Date;
/** Token or css color; flows to the --gantt-event-color css var. */
color?: string;
/** Vetoes only, ANDed with interactions.drag / .resize: readOnly blocks both, draggable/resizable one each. */
readOnly?: boolean;
draggable?: boolean;
resizable?: boolean;
/** Feeds the default getEventPriority; higher orders and packs first. */
priority?: number;
/** Completion 0-100, not 0-1. */
progress?: number;
/**
* Planned (as-built baseline) window, drawn behind the bar so the actual
* start/end read against it. Half-open like start/end; set both or
* neither. Equal instants mark a planned milestone. A recurring series
* has no single planned window, so events with `recurrence` render none.
*/
baselineStart?: Date;
baselineEnd?: Date;
/** Explicit stacking override; wins over the computed z. */
zIndex?: number;
resourceId?: string;
/**
* Ids of the events this one waits on (finish-to-start). The view draws an
* elbow arrow from each named event's end into this one's start; unknown
* ids, recurring series, and endpoints on hidden rows are skipped.
* Rendering only - the gantt never reschedules dependents; enforcement
* stays consumer territory (canDropEvent/onEventUpdate).
*/
dependencies?: GanttBarId[];
data?: TData;
}
interface GanttOccurrence<TData = unknown> {
/** Stable per instance: `${event.id}::${startISO}`. */
key: string;
eventId: GanttBarId;
event: GanttEvent<TData>;
start: Date;
end: Date;
allDay: boolean;
isRecurring: boolean;
recurrenceIndex?: number;
}
interface GanttSegment<TData = unknown> {
occurrence: GanttOccurrence<TData>;
/** Range-start reference instant of the segment's timeline slice. */
day: Date;
isStart: boolean;
isEnd: boolean;
continuesBefore: boolean;
continuesAfter: boolean;
/** Minutes from the visible range start, clamped to the range. */
startMin?: number;
endMin?: number;
/** Lane packing: 0-based lane index, then the lanes the node's row resolved to. */
column?: number;
columnCount?: number;
columnSpan?: number;
}
/** A validated planned window; `milestone` when start and end coincide. */
interface GanttBaseline {
start: Date;
end: Date;
milestone: boolean;
}
/** Actual end against the planned end: before it, after it, or exactly on it. */
type GanttBaselineVariance = 'early' | 'late' | 'on-time';
interface GanttSelection {
eventKeys: string[];
slot: { start: Date; end: Date; allDay: boolean } | null;
}
interface GanttInteractions {
/** Horizontal move within the bar's own row; never across rows. */
drag: boolean;
resize: boolean;
selectSlot: boolean;
}
interface GanttDragState<TData = unknown> {
kind: 'move' | 'resize-start' | 'resize-end';
occurrence: GanttOccurrence<TData>;
proposedStart: Date;
proposedEnd: Date;
proposedAllDay: boolean;
proposedResourceId?: string;
/** Last canDropEvent verdict; drives data-drop-invalid styling. */
valid: boolean;
}
/** The in-gesture drag-create rectangle only; the committed slot is GanttSelection.slot. */
interface GanttSlotDraft {
start: Date;
end: Date;
allDay: boolean;
resourceId?: string;
}
interface GanttState<TData = unknown> {
scale: GanttScale;
date: Date;
/** Full rendered axis range - fetch remote data for THIS, not for activeRange (the logical month/week). */
visibleRange: GanttDateRange;
activeRange: GanttDateRange;
events: GanttEvent<TData>[];
selection: GanttSelection;
interactions: GanttInteractions;
loading: boolean;
drag: GanttDragState<TData> | null;
slotDraft: GanttSlotDraft | null;
/** Center of the scrolled viewport; the nav title follows it. null falls back to the anchor date. */
viewportCenter: Date | null;
}
interface GanttRangeInfo {
range: GanttDateRange;
activeRange: GanttDateRange;
scale: GanttScale;
date: Date;
timeZone: string;
}
interface GanttProposedUpdate<TData = unknown> {
event: GanttEvent<TData>;
/** null when source === "api". */
occurrence: GanttOccurrence<TData> | null;
start: Date;
end: Date;
allDay: boolean;
resourceId?: string;
source: 'drag' | 'resize-start' | 'resize-end' | 'keyboard' | 'api';
}
/** false = reject/revert; void or true = accept; object = accept with adjustment. */
type GanttUpdateResult = boolean | void | { start?: Date; end?: Date; allDay?: boolean };
/** A click is a point, not a range; `end` is reserved for future gestures. */
interface GanttSlotInfo {
date: Date;
end?: Date;
allDay: boolean;
resourceId?: string;
}
/** Off-day marking; `true` takes the defaults. Marked cells carry `data-off` for CSS customization. */
interface GanttOffDaysConfig {
/** Weekday numbers treated as off (0 = Sunday). Default [0, 6]. */
weekendDays?: number[];
/** Extra off dates compared by day in the display zone. */
dates?: Date[];
/** Runs in addition to weekendDays and dates, not instead; any match marks the day off. */
isOffDay?: (day: Date) => boolean;
/** Marker classes; default "bg-muted/40". */
className?: string;
}
/** External-data contract; OAuth, tokens, and sync loops are application backend territory. */
interface GanttDataAdapter<TData = unknown> {
getEvents(range: GanttDateRange, signal?: AbortSignal): Promise<GanttEvent<TData>[]>;
}
export type {
GanttBaseline,
GanttBaselineVariance,
GanttEvent,
GanttDataAdapter,
GanttDateRange,
GanttDragState,
GanttBarId,
GanttInteractions,
GanttNode,
GanttOccurrence,
GanttOffDaysConfig,
GanttOverlapPolicy,
GanttProposedUpdate,
GanttRangeInfo,
GanttRecurrenceRule,
GanttResource,
GanttRowAlign,
GanttScheduleMode,
GanttSegment,
GanttSelection,
GanttSlotDraft,
GanttSlotInfo,
GanttState,
GanttResourceReorder,
GanttScale,
GanttUpdateResult,
GanttWeekday,
};components/ui/gantt/gantt-view.tsx
import { memo, useCallback, useEffect, useLayoutEffect, useMemo, useRef, useState, type CSSProperties, type RefObject } from 'react';
import {
DEFAULT_ROW_ALIGN,
resolveScheduleMode,
resolveTimelineLines,
useGantt,
useGanttSelector,
useGanttSettings,
useGanttViewConfig,
type GanttColumn,
} from '@/registry/vcare/ui/gantt/gantt';
import { GanttBar } from '@/registry/vcare/ui/gantt/gantt-bar';
import {
cancelActiveGanttGestures,
markGestureEnd,
useGanttGestures,
useGanttGestureTeardown,
wasRecentDrag,
} from '@/registry/vcare/ui/gantt/gantt-dnd';
import {
buildDependencyPath,
getBaselineVariance,
getDayKey,
getLaneKey,
getRangeKey,
MIN_PACK_SLOT,
packTimedSegments,
reorderResources,
resolveEventBaseline,
resolveOffDay,
toZoned,
zonedStartOfDay,
type GanttLaneMemo,
} from '@/registry/vcare/ui/gantt/gantt-lib';
import type {
GanttBaseline,
GanttBaselineVariance,
GanttDateRange,
GanttEvent,
GanttOccurrence,
GanttResource,
GanttResourceReorder,
GanttSegment,
} from '@/registry/vcare/ui/gantt/gantt-types';
import { mergeProps } from '@base-ui/react/merge-props';
// Base UI's ScrollArea re-measures its thumb + overflow on mount, viewport
// resize and scroll, but NOT on a content-size change unless the content sits
// in a ScrollArea.Content (which carries the content ResizeObserver). ReUI's
// ScrollArea puts children straight in the Viewport, so the tree/timeline
// panes wrap their scroll content in this Content to keep the scrollbar in
// sync when rows expand/collapse or tree columns show/hide. (Radix observes
// content automatically, so its twin needs no equivalent.)
import { ScrollArea as ScrollAreaPrimitive } from '@base-ui/react/scroll-area';
import { useRender } from '@base-ui/react/use-render';
import { addDays, addMinutes, addMonths, format, getWeek, startOfMonth, startOfQuarter, startOfWeek, type Locale } from 'date-fns';
import { cn } from '@/registry/vcare/lib/utils';
import { Button } from '@/registry/vcare/ui/button';
import { Checkbox } from '@/registry/vcare/ui/checkbox';
import { ContextMenu, ContextMenuContent, ContextMenuTrigger } from '@/registry/vcare/ui/context-menu';
import { ScrollArea, ScrollBar } from '@/registry/vcare/ui/gantt/gantt-scroll-area';
import { Tooltip, TooltipContent, TooltipProvider, TooltipTrigger } from '@/registry/vcare/ui/tooltip';
import { PlusIcon, MinusIcon, GripVerticalIcon, ChevronRightIcon, ChevronLeftIcon } from 'lucide-react';
/** Current time, refreshed on an interval and on tab focus. */
function useNow(intervalMs = 30_000): Date {
const [now, setNow] = useState(() => new Date());
useEffect(() => {
const tick = () => setNow(new Date());
const id = setInterval(tick, intervalMs);
document.addEventListener('visibilitychange', tick);
window.addEventListener('focus', tick);
return () => {
clearInterval(id);
document.removeEventListener('visibilitychange', tick);
window.removeEventListener('focus', tick);
};
}, [intervalMs]);
return now;
}
/**
* Today's zoned day key, re-rendering only at the midnight rollover (and on
* focus/visibility) - the grid needs day granularity, not the 30s now tick.
*/
function useTodayKey(timeZone: string): string {
const [key, setKey] = useState(() => getDayKey(new Date(), timeZone));
useEffect(() => {
const tick = () =>
setKey((prev) => {
const next = getDayKey(new Date(), timeZone);
return next === prev ? prev : next;
});
tick();
const id = setInterval(tick, 60_000);
document.addEventListener('visibilitychange', tick);
window.addEventListener('focus', tick);
return () => {
clearInterval(id);
document.removeEventListener('visibilitychange', tick);
window.removeEventListener('focus', tick);
};
}, [timeZone]);
return key;
}
/**
* Lowest lane free for [startMs, endMs) among a row's segments, padded by
* MIN_PACK_SLOT exactly as packTimedSegments pads its own occupancy test.
* Comparing raw instants instead lets a sub-slot bar read as clear, so an
* affordance would promise a lane the packer then refuses.
*
* Shared by the hover hint and the drag placeholder on purpose: two copies of
* this is how the ring and the range it paints end up on different tracks.
*/
function lowestFreeLane(segments: GanttSegment[], startMs: number, endMs: number): number {
const padMs = MIN_PACK_SLOT * 60000;
const to = Math.max(endMs, startMs + padMs);
const busy = new Set<number>();
for (const segment of segments) {
const segStart = segment.occurrence.start.getTime();
const segEnd = Math.max(segment.occurrence.end.getTime(), segStart + padMs);
if (segStart < to && segEnd > startMs) busy.add(segment.column ?? 0);
}
let lane = 0;
while (busy.has(lane)) lane += 1;
return lane;
}
/**
* Pointer x resolved against the element's TIME axis: the 0..1 fraction and
* the same measurement in CSS pixels from the axis start. Mirrored in RTL,
* where the range start renders at the element's right edge. One rect read
* and one style read, because this runs on every pointer move.
*/
function trackPoint(el: HTMLElement, clientX: number): { fraction: number; offset: number } {
const rect = el.getBoundingClientRect();
const rtl = getComputedStyle(el).direction === 'rtl';
const offset = rtl ? rect.right - clientX : clientX - rect.left;
// `offset` is exact and drives the time maths. `snapped` is the same value
// biased so that rect start + snapped lands on a WHOLE viewport pixel: the
// row's own edge routinely sits on a half pixel, so rounding the offset
// alone still puts anything placed at it between two pixels.
const snapped = rtl ? rect.right - Math.round(clientX) : Math.round(clientX) - rect.left;
return {
fraction: rect.width > 0 ? offset / rect.width : 0,
offset: snapped,
};
}
/** Fraction only, for the call sites that do not place anything. */
function trackFraction(el: HTMLElement, clientX: number): number {
return trackPoint(el, clientX).fraction;
}
/**
* Row geometry is three numbers: a bar is LANE_HEIGHT_REM tall, stacked bars
* are separated by LANE_GAP_REM, and the block as a whole is inset from the
* row's edges by ROW_PADDING_REM. Padding and gap are deliberately NOT the
* same value - schedules in one node belong together, so they sit tight, while
* the row still needs real breathing room above and below. Every inter-lane
* gap is identical, which is what keeps a stacked row reading evenly.
*/
const LANE_HEIGHT_REM = 1.25;
const LANE_GAP_REM = 0.1875;
const ROW_PADDING_REM = 0.5;
/** Default drop-indicator height, centered inside its lane band; a consumer
* overrides it with metrics.ghostHeight (published as --gantt-ghost-height). */
const GHOST_HEIGHT_REM = 1.25;
/**
* The ONE lane-pitch formula: top of lane `lane` inside a row. Every overlay
* that rides a lane (bar, baseline ghost, drag ghost, hint ring, slot draft)
* reads it, so their vertical positions can never drift apart.
*/
function laneTopRem(laneOffsetRem: number, lane: number, laneHeightRem: number, laneGapRem: number): number {
return laneOffsetRem + lane * (laneHeightRem + laneGapRem);
}
/** Height of a stack of `count` lanes, inter-lane gaps included. */
function laneBlockRem(count: number, laneHeightRem: number, laneGapRem: number): number {
return count * laneHeightRem + (count - 1) * laneGapRem;
}
/** Bars narrower than this flip their title outside in barLabel "auto". */
const AUTO_LABEL_MIN_REM = 7;
const DEFAULT_TREE_PANEL = {
width: 288,
minWidth: 180,
maxWidth: 640,
resizable: true,
nameColumnWidth: 208,
};
const DEFAULT_COLUMN_WIDTH = 96;
const DEFAULT_ZOOM_RANGE = { min: 0.5, max: 3 };
/** Timeline pane never shrinks below this so it stays usable on narrow screens. */
const MIN_TIMELINE_WIDTH = 200;
/** Scroll distance from an edge that triggers infinite-range growth. */
const INFINITE_EDGE_PX = 160;
interface TimelineUnit {
key: string;
label: string;
ms: number;
/** Relative width share; uniform scales use 1 (year: days per month). */
weight: number;
isToday?: boolean;
isOff?: boolean;
}
interface TimelineGroup {
key: string;
label: string;
span: number;
}
interface TimelineRow {
resource: GanttResource;
parentId: string | null;
depth: number;
isGroup: boolean;
collapsed: boolean;
}
/** One planned window resolved against the visible range, ready to position. */
interface RowBaseline {
event: GanttEvent;
baseline: GanttBaseline;
/** Minutes from the range start, clamped to the range like segment minutes. */
startMin: number;
endMin: number;
/** The lane of the event's own bar, so the ghost sits under it. An orphan
* (its bar slipped out of the range) takes the lowest lane free for its
* window instead; the layout pass drops it when the row has none. */
lane: number;
variance: GanttBaselineVariance;
}
/** The NODE's own planned window, resolved against the visible range. */
interface RowLevelBaseline {
baseline: GanttBaseline;
startMin: number;
endMin: number;
/** Latest actual end (subtree included for groups) vs the planned end;
* null when the node has no events to compare. */
variance: GanttBaselineVariance | null;
}
/** Per-row packed bars plus the extents the off-screen chips need. */
interface TimelineRowBars {
segments: GanttSegment[];
laneCount: number;
/**
* Planned windows ghosted behind this row's bars. Derived from EVENTS, not
* occurrences, so a bar that slipped entirely out of the visible range
* still shows the plan it missed. Empty when baselineBars is off. Never an
* input to packing or row height - a baseline changes no geometry.
*/
baselines: RowBaseline[];
/** The node's own planned window band; null without one (or with
* baselineBars off). Same no-geometry rule as the per-event ghosts. */
rowBaseline: RowLevelBaseline | null;
/**
* Lane a drag-create in flight would land on, or null when none is aimed at
* this row. The row reserves the track, so it grows exactly as it will on
* commit and the placeholder never has to overlap the bar it is going under.
* Computed here, once, because BOTH panes size themselves from this object -
* deriving it a second time in the timeline row is how the two would drift.
*/
draftLane: number | null;
/** Mode this row was packed under; the draft overlay must honour it. */
scheduleMode: 'single' | 'multiple';
heightRem: number;
/** Gap above the first bar; equal to every other gap in the row. */
laneOffsetRem: number;
/**
* The band the FIRST schedule occupies, its gaps included. The tree cell
* sizes its label box to exactly this, so the label and the first bar share
* a centerline however many lanes the node grew.
*/
bandRem: number;
/** Envelope of all bars, as track fractions; null when the row is empty. */
extent: {
from: number;
to: number;
color?: string;
label: string;
/** First bar start, for the jump-chip tooltip. */
startMs: number;
} | null;
/**
* Parent rollup: descendant-bar envelope + duration-weighted progress,
* present only on group rows without bars of their own.
*/
summary: { from: number; to: number; progress: number | null } | null;
}
interface TimelineReorderState {
resourceId: string;
/** Insertion offset (px) within the tree pane. */
top: number;
valid: boolean;
proposal: GanttResourceReorder | null;
}
/** Shared empty set so rows without dependency data never churn on identity. */
const EMPTY_ID_SET: ReadonlySet<string> = new Set();
/** One finish-to-start arrow, both anchors in track rem coordinates. */
interface DependencyEdge {
key: string;
/** Predecessor and dependent event ids, so a gesture can re-anchor its own
* endpoints live. */
fromId: string;
toId: string;
fromX: number;
fromY: number;
toX: number;
toY: number;
}
interface GanttViewProps extends useRender.ComponentProps<'div'> {
/** Day-scale unit interval in minutes; defaults to the interval view config. */
interval?: number;
}
/** The pane's scrollable viewport (custom ScrollArea or native host). */
function getPaneViewport(pane: HTMLElement | null): HTMLElement | null {
return pane?.querySelector<HTMLElement>('[data-slot=scroll-area-viewport]') ?? null;
}
/** Distance scrolled from the inline-start edge (RTL reports negative). */
function getScrollStart(viewport: HTMLElement): number {
return Math.abs(viewport.scrollLeft);
}
/** Write a distance-from-inline-start back as a signed scrollLeft. */
function setScrollStart(viewport: HTMLElement, value: number) {
viewport.scrollLeft = getComputedStyle(viewport).direction === 'rtl' ? -value : value;
}
function GanttView({ className, render, interval: intervalProp, ...props }: GanttViewProps) {
const instance = useGantt();
const settings = useGanttSettings();
const viewConfig = useGanttViewConfig();
const range = useGanttSelector<unknown, GanttDateRange>((state) => state.visibleRange, {
isEqual: (a, b) => getRangeKey(a) === getRangeKey(b),
});
const occurrences = useGanttSelector<unknown, GanttOccurrence[]>(() => instance.api.getOccurrences(), {
calendar: instance,
isEqual: (a, b) =>
a.length === b.length &&
a.every(
(occ, i) =>
occ.key === b[i]?.key &&
occ.start.getTime() === b[i]?.start.getTime() &&
occ.end.getTime() === b[i]?.end.getTime() &&
occ.event === b[i]?.event,
),
});
// Tree expand/collapse: controlled (collapsedGroups/onCollapsedGroupsChange)
// or uncontrolled (defaultCollapsedGroups) - same pattern as selectedRows.
const [internalCollapsed, setInternalCollapsed] = useState<string[]>(() => viewConfig.defaultCollapsedGroups ?? []);
const collapsedIds = viewConfig.collapsedGroups ?? internalCollapsed;
const collapsedGroups = useMemo(() => new Set(collapsedIds), [collapsedIds]);
const scale = useGanttSelector((state) => state.scale);
const interval = Math.min(Math.max(intervalProp ?? viewConfig.interval, 15), 240);
// Every layout metric is consumer-overridable; unset keys keep defaults.
const metrics = viewConfig.metrics;
const laneHeightRem = metrics?.laneHeight ?? LANE_HEIGHT_REM;
const rowPaddingRem = metrics?.rowPadding ?? ROW_PADDING_REM;
const laneGapRem = metrics?.laneGap ?? LANE_GAP_REM;
const minRowRem = metrics?.minRowHeight ?? 2.5;
const ghostHeightRem = metrics?.ghostHeight ?? GHOST_HEIGHT_REM;
const minTimelineWidth = metrics?.minTimelineWidth ?? MIN_TIMELINE_WIDTH;
const infiniteEdgePx = metrics?.infiniteScrollEdge ?? INFINITE_EDGE_PX;
const timeZone = settings.timeZone;
const rangeStartMs = range.start.getTime();
const rangeEndMs = range.end.getTime();
const rangeKey = getRangeKey(range);
const snapMin = scale === 'day' ? settings.snapDuration : 24 * 60;
// day-granular time input so the today highlight rolls over at midnight
// without the whole grid re-rendering on the 30s now tick
const todayDayKey = useTodayKey(timeZone);
const rows = useMemo(() => {
const result: TimelineRow[] = [];
const walk = (resources: GanttResource[], depth: number, parentId: string | null) => {
for (const resource of resources) {
const isGroup = !!resource.children?.length;
const collapsed = collapsedGroups.has(resource.id);
result.push({ resource, parentId, depth, isGroup, collapsed });
if (isGroup && !collapsed) walk(resource.children!, depth + 1, resource.id);
}
};
walk(settings.resources, 0, null);
return result;
}, [settings.resources, collapsedGroups]);
// Header model: bottom row = units, top row = grouping sectors.
// Weights are proportional to REAL duration (a 23h/25h DST day differs from
// its siblings), so weight-driven gridlines, ms-fraction bar geometry, and
// the dnd pointer math all share one coordinate system.
const { units, groups, unitWidthRem } = useMemo(() => {
const units: TimelineUnit[] = [];
const groups: TimelineGroup[] = [];
// day-start ms for the today window checks; recomputed when the day key
// rolls over (this memo depends on todayDayKey)
const todayStartMs = zonedStartOfDay(new Date(), timeZone).getTime();
if (scale === 'day') {
const labelFormat = interval % 60 === 0 ? settings.i18n.formats.timeGutter : 'h:mm';
// walk whole days: infinite scroll can extend the range past one day
let dayCursor = zonedStartOfDay(range.start, timeZone);
while (dayCursor.getTime() < rangeEndMs) {
const zonedDay = toZoned(dayCursor, timeZone);
const nextDay = zonedStartOfDay(addDays(zonedDay, 1), timeZone);
const dayMinutes = (nextDay.getTime() - dayCursor.getTime()) / 60000;
const dayOff = resolveOffDay(dayCursor, timeZone, viewConfig.offDays ?? true);
let span = 0;
for (let m = 0; m < dayMinutes; m += interval) {
const time = addMinutes(zonedDay, m);
// a DST day whose minutes don't divide evenly leaves a short
// final unit; its weight must be its REAL share or bars drift
const weight = Math.min(interval, dayMinutes - m) / interval;
units.push({
key: `${getDayKey(dayCursor, timeZone)}-m${m}`,
label: format(time, labelFormat, { locale: settings.locale }),
ms: time.getTime(),
weight,
isOff: dayOff,
});
span += weight;
}
groups.push({
key: getDayKey(dayCursor, timeZone),
label: format(zonedDay, settings.i18n.formats.dayTitle, {
locale: settings.locale,
}),
span,
});
dayCursor = nextDay;
}
return {
units,
groups,
unitWidthRem: metrics?.unitWidths?.day ?? Math.max(2.5, 5 * (interval / 60)),
};
}
if (scale === 'quarter') {
// units are week-aligned weeks (lib aligns the range), groups are months
let cursor = zonedStartOfDay(range.start, timeZone);
while (cursor.getTime() < rangeEndMs) {
const zoned = toZoned(cursor, timeZone);
const next = zonedStartOfDay(addDays(zoned, 7), timeZone);
// real week duration / nominal week: 1 except across DST changes
const weight = (next.getTime() - cursor.getTime()) / (7 * 24 * 60 * 60000);
units.push({
key: getDayKey(cursor, timeZone),
label: format(zoned, 'MMM d', { locale: settings.locale }),
ms: cursor.getTime(),
weight,
isToday: todayStartMs >= cursor.getTime() && todayStartMs < next.getTime(),
});
const monthKey = format(zoned, 'yyyy-MM');
const lastGroup = groups[groups.length - 1];
if (lastGroup && lastGroup.key === monthKey) {
lastGroup.span += weight;
} else {
groups.push({
key: monthKey,
label: format(zoned, 'MMMM', { locale: settings.locale }),
span: weight,
});
}
cursor = next;
}
return { units, groups, unitWidthRem: metrics?.unitWidths?.quarter ?? 8 };
}
if (scale === 'year') {
// units are calendar months (weight = real duration), groups are quarters
let cursor: Date = startOfMonth(toZoned(range.start, timeZone));
while (cursor.getTime() < rangeEndMs) {
const next = startOfMonth(addMonths(cursor, 1));
// nominal-day units so a month reads ~30 wide; real ms keeps DST months true
const weight = (next.getTime() - cursor.getTime()) / (24 * 60 * 60000);
units.push({
key: format(cursor, 'yyyy-MM'),
label: format(cursor, 'MMM', { locale: settings.locale }),
ms: cursor.getTime(),
weight,
isToday: todayStartMs >= cursor.getTime() && todayStartMs < next.getTime(),
});
const quarterStart = startOfQuarter(cursor);
const quarterKey = format(quarterStart, 'yyyy-QQQ');
const lastGroup = groups[groups.length - 1];
if (lastGroup && lastGroup.key === quarterKey) {
lastGroup.span += weight;
} else {
groups.push({
key: quarterKey,
label: format(quarterStart, 'QQQ yyyy', {
locale: settings.locale,
}),
span: weight,
});
}
cursor = next;
}
return { units, groups, unitWidthRem: metrics?.unitWidths?.year ?? 10 };
}
// week/month: units are days, groups are ISO-ish weeks
let cursor = zonedStartOfDay(range.start, timeZone);
while (cursor.getTime() < rangeEndMs) {
const zoned = toZoned(cursor, timeZone);
const nextDay = zonedStartOfDay(addDays(zoned, 1), timeZone);
// real day duration / 24h: 1 except the 23h/25h DST days
const weight = (nextDay.getTime() - cursor.getTime()) / (24 * 60 * 60000);
units.push({
key: getDayKey(cursor, timeZone),
label: format(zoned, 'EEE d', { locale: settings.locale }),
ms: cursor.getTime(),
weight,
isToday: getDayKey(cursor, timeZone) === todayDayKey,
isOff: resolveOffDay(cursor, timeZone, viewConfig.offDays ?? true),
});
// locale supplies firstWeekContainsDate so W-numbers match the locale's
// week numbering (ISO in de/fr, US-style otherwise); the explicit
// weekStartsOn keeps the number aligned with the rendered grid
const weekNumber = getWeek(zoned, {
locale: settings.locale,
weekStartsOn: settings.weekStartsOn,
});
// key + label from the true week start: a range that begins midweek
// must not split or mislabel its first group (incl. the Jan 1 week)
const weekStart = startOfWeek(zoned, {
weekStartsOn: settings.weekStartsOn,
});
const weekKey = `w-${format(weekStart, 'yyyy-MM-dd')}`;
const lastGroup = groups[groups.length - 1];
if (lastGroup && lastGroup.key === weekKey) {
lastGroup.span += weight;
} else {
groups.push({
key: weekKey,
label: `${settings.i18n.labels.week(weekNumber)} ${format(weekStart, 'MMM d', { locale: settings.locale })} - ${format(addDays(weekStart, 6), 'd', { locale: settings.locale })}`,
span: weight,
});
}
cursor = nextDay;
}
return {
units,
groups,
unitWidthRem: metrics?.unitWidths?.[scale] ?? (scale === 'week' ? 10 : 4),
};
}, [
scale,
interval,
range.start,
rangeEndMs,
timeZone,
settings.i18n,
settings.locale,
settings.weekStartsOn,
viewConfig.offDays,
todayDayKey,
metrics,
]);
// Zoom multiplies the minimum unit width; the flex track still fills when
// the zoomed width is narrower than the pane. Controlled (zoom/onZoomChange)
// or uncontrolled (defaultZoom) - same pattern as selectedRows.
const zoomRange = { ...DEFAULT_ZOOM_RANGE, ...viewConfig.zoomRange };
const clampZoom = (value: number) => Math.min(Math.max(value, zoomRange.min), zoomRange.max);
const [internalZoom, setInternalZoom] = useState(() => viewConfig.defaultZoom ?? 1);
const zoom = clampZoom(viewConfig.zoom ?? internalZoom);
const setZoomValue = (next: number) => {
const clamped = clampZoom(next);
if (viewConfig.zoom === undefined) setInternalZoom(clamped);
viewConfig.onZoomChange?.(clamped);
};
const canZoomIn = zoom < zoomRange.max - 1e-9;
const canZoomOut = zoom > zoomRange.min + 1e-9;
const trackRemWidth = units.length * unitWidthRem * zoom;
const trackWidth = `${trackRemWidth}rem`;
// unequal weights (year months, DST-containing day/week ranges) draw
// boundaries from weight fractions instead of the uniform gradient
const uniform = units.every((unit) => Math.abs(unit.weight - units[0].weight) < 1e-9);
const totalWeight = units.reduce((sum, unit) => sum + unit.weight, 0);
/** Cumulative start/width fractions per unit, for backdrop stripes/lines. */
const unitFractions = useMemo(() => {
let acc = 0;
return units.map((unit) => {
const start = acc / totalWeight;
acc += unit.weight;
return { unit, start, width: unit.weight / totalWeight };
});
}, [units, totalWeight]);
/** Snap a track fraction to its unit (hint preview target). */
const resolveHintStop = useMemo(() => {
return (fraction: number): { index: number; center: number; ms: number; endMs: number } | null => {
for (let i = 0; i < unitFractions.length; i++) {
const { unit, start, width } = unitFractions[i];
if (fraction < start + width || i === unitFractions.length - 1) {
return {
index: i,
center: start + width / 2,
ms: unit.ms,
endMs: unitFractions[i + 1]?.unit.ms ?? unit.ms,
};
}
}
return null;
};
}, [unitFractions]);
/** Group boundary fractions; spans are in unit-weight terms everywhere. */
const groupBoundaries = useMemo(() => {
const fractions: number[] = [];
let acc = 0;
for (let i = 0; i < groups.length - 1; i++) {
acc += groups[i].span;
fractions.push(acc / totalWeight);
}
return fractions;
}, [groups, totalWeight]);
/** Resource id -> every descendant id, for parent rollups. */
const descendantIds = useMemo(() => {
const map = new Map<string, string[]>();
const walk = (resource: GanttResource): string[] => {
const ids = (resource.children ?? []).flatMap((child) => [child.id, ...walk(child)]);
map.set(resource.id, ids);
return ids;
};
settings.resources.forEach(walk);
return map;
}, [settings.resources]);
// All events (not just visible occurrences) so parent rollup progress is
// all-time and matches a consumer's own tree rollup, independent of scroll.
const allEvents = useGanttSelector<unknown, GanttEvent[]>((state) => state.events);
const subtreeProgress = useMemo(() => {
// consumer-owned rollup math: hand each group its descendant events
if (viewConfig.getSummaryProgress) {
const byResource = new Map<string, GanttEvent[]>();
for (const ev of allEvents) {
if (!ev.resourceId) continue;
const list = byResource.get(ev.resourceId);
if (list) list.push(ev);
else byResource.set(ev.resourceId, [ev]);
}
const map = new Map<string, number | null>();
for (const row of rows) {
if (!row.isGroup) continue;
const events: GanttEvent[] = [];
for (const id of descendantIds.get(row.resource.id) ?? []) {
const list = byResource.get(id);
if (list) events.push(...list);
}
map.set(row.resource.id, viewConfig.getSummaryProgress({ resource: row.resource, events }));
}
return map;
}
// default: one pass over events -> per-resource aggregates, then a cheap
// descendant sum per group; never O(rows x events)
const perResource = new Map<string, { weighted: number; total: number; saw: boolean }>();
for (const ev of allEvents) {
if (!ev.resourceId) continue;
let agg = perResource.get(ev.resourceId);
if (!agg) {
agg = { weighted: 0, total: 0, saw: false };
perResource.set(ev.resourceId, agg);
}
const dur = Math.max(ev.end.getTime() - ev.start.getTime(), 1);
agg.total += dur;
if (typeof ev.progress === 'number') {
agg.saw = true;
agg.weighted += ev.progress * dur;
}
}
const map = new Map<string, number | null>();
for (const row of rows) {
if (!row.isGroup) continue;
let weighted = 0;
let weightTotal = 0;
let saw = false;
for (const id of descendantIds.get(row.resource.id) ?? []) {
const agg = perResource.get(id);
if (!agg) continue;
weightTotal += agg.total;
if (agg.saw) {
saw = true;
weighted += agg.weighted;
}
}
map.set(row.resource.id, saw && weightTotal > 0 ? Math.min(Math.max(Math.round(weighted / weightTotal), 0), 100) : null);
}
return map;
}, [rows, allEvents, descendantIds, viewConfig.getSummaryProgress]);
// Lane memory across layout passes, keyed by getLaneKey (event identity,
// NOT the time-stamped occurrence key). It stores the TIMES alongside the
// lane so the packer can tell the schedule the user just edited apart from
// the ones that sat still: untouched schedules keep their lane, the edited
// one re-seeks. Written during the memo below on purpose: the pass is
// idempotent - feeding its own output back in produces the same assignment -
// so a StrictMode double render is a no-op.
const laneMemory = useRef(new Map<string, GanttLaneMemo>());
const scheduleMode = viewConfig.scheduleMode;
// Per-row packed bars, hoisted so the tree and timeline rows share heights
// A drag-create in flight. Reduced to the three fields the layout needs, and
// compared by value, so this re-runs only when the SNAPPED range moves - the
// gesture engine already gates setSlotDraft on exactly that, so it is a
// handful of recomputes per drag rather than one per frame.
const draftLayout = useGanttSelector<unknown, { resourceId: string; startMs: number; endMs: number } | null>(
(state) => {
const slotDraft = state.slotDraft;
if (!slotDraft?.resourceId) return null;
return {
resourceId: slotDraft.resourceId,
startMs: slotDraft.start.getTime(),
endMs: slotDraft.end.getTime(),
};
},
{
isEqual: (a, b) => a === b || (a !== null && b !== null && a.resourceId === b.resourceId && a.startMs === b.startMs && a.endMs === b.endMs),
},
);
const baseRowBars = useMemo(() => {
const map = new Map<string, TimelineRowBars>();
// read the lanes the previous pass settled on, write the ones this pass
// settles on; rebuilding (not mutating) prunes schedules that are gone
const previousLanes = laneMemory.current;
const nextLanes = new Map<string, GanttLaneMemo>();
const totalMin = (rangeEndMs - rangeStartMs) / 60000;
// one pass: occurrences grouped by resource, plus per-resource envelopes
// for the parent rollups (never O(rows x occurrences))
const byResource = new Map<string, GanttOccurrence[]>();
const envelopes = new Map<string, { fromMin: number; toMin: number }>();
for (const occ of occurrences) {
const rid = occ.event.resourceId;
if (!rid) continue;
const list = byResource.get(rid);
if (list) list.push(occ);
else byResource.set(rid, [occ]);
const fromMin = Math.max((occ.start.getTime() - rangeStartMs) / 60000, 0);
const toMin = Math.min((occ.end.getTime() - rangeStartMs) / 60000, totalMin);
const env = envelopes.get(rid);
if (!env) {
envelopes.set(rid, { fromMin, toMin });
} else {
env.fromMin = Math.min(env.fromMin, fromMin);
env.toMin = Math.max(env.toMin, toMin);
}
}
// Planned windows group by node in a pass of their own, over EVENTS: an
// event whose actual bar slipped clear of the range has no occurrence
// above, but its plan should still show where it was missed. The same
// pass records each node's latest actual end (all-time, like the summary
// rollup) for the row-baseline variance readout.
const baselinesByResource = new Map<string, Array<{ event: GanttEvent; baseline: GanttBaseline }>>();
const latestEndByResource = new Map<string, number>();
if (viewConfig.baselineBars) {
for (const event of allEvents) {
if (!event.resourceId) continue;
const endMsActual = event.end.getTime();
const prev = latestEndByResource.get(event.resourceId);
if (prev === undefined || endMsActual > prev) {
latestEndByResource.set(event.resourceId, endMsActual);
}
const baseline = resolveEventBaseline(event);
if (!baseline) continue;
const startMs = baseline.start.getTime();
const endMs = baseline.end.getTime();
// half-open like the bars; the closed compare keeps a planned
// milestone sitting exactly on a range edge visible
const visible = baseline.milestone ? startMs >= rangeStartMs && startMs <= rangeEndMs : startMs < rangeEndMs && endMs > rangeStartMs;
if (!visible) continue;
const list = baselinesByResource.get(event.resourceId);
const entry = { event, baseline };
if (list) list.push(entry);
else baselinesByResource.set(event.resourceId, [entry]);
}
}
for (const row of rows) {
const mine = byResource.get(row.resource.id) ?? [];
const segments: GanttSegment[] = mine.map((occurrence) => ({
occurrence,
day: new Date(rangeStartMs),
isStart: occurrence.start.getTime() >= rangeStartMs,
isEnd: occurrence.end.getTime() <= rangeEndMs,
continuesBefore: occurrence.start.getTime() < rangeStartMs,
continuesAfter: occurrence.end.getTime() > rangeEndMs,
startMin: Math.max((occurrence.start.getTime() - rangeStartMs) / 60000, 0),
endMin: Math.min((occurrence.end.getTime() - rangeStartMs) / 60000, totalMin),
}));
const mode = resolveScheduleMode(row.resource, scheduleMode);
packTimedSegments(segments, { mode, preferredLanes: previousLanes });
for (const segment of segments) {
nextLanes.set(getLaneKey(segment.occurrence), {
lane: segment.column ?? 0,
startMs: segment.occurrence.start.getTime(),
endMs: segment.occurrence.end.getTime(),
});
}
const laneCount = segments.reduce((max, segment) => Math.max(max, (segment.column ?? 0) + 1), 1);
// The ghost rides its bar's settled lane so plan and actual read as one
// task; pure overlay geometry, never an input to packing or laneCount.
const plans = baselinesByResource.get(row.resource.id);
const laneByEvent = plans ? new Map(segments.map((segment) => [segment.occurrence.eventId, segment.column ?? 0])) : null;
const baselines: RowBaseline[] = plans
? plans.flatMap(({ event, baseline }) => {
// An ORPHAN plan (its bar slipped clear of the range) cannot ride
// its bar's lane. Lane 0 would pin it under whatever unrelated bar
// sits there, silently mis-attributing the plan, so it takes the
// lowest lane that is FREE for its window - and when the row has
// no free lane, it is omitted: absence beats a false attribution.
// "single" keeps one shared track, so 0 is honest there.
let lane = laneByEvent?.get(event.id);
if (lane === undefined) {
if (mode === 'single' || segments.length === 0) {
lane = 0;
} else {
const free = lowestFreeLane(segments, baseline.start.getTime(), baseline.end.getTime());
if (free >= laneCount) return [];
lane = free;
}
}
return [
{
event,
baseline,
startMin: Math.max((baseline.start.getTime() - rangeStartMs) / 60000, 0),
endMin: Math.min((baseline.end.getTime() - rangeStartMs) / 60000, totalMin),
lane,
variance: getBaselineVariance(event) ?? 'on-time',
},
];
})
: [];
let from = Infinity;
let to = -Infinity;
for (const segment of segments) {
from = Math.min(from, (segment.startMin ?? 0) / totalMin);
to = Math.max(to, (segment.endMin ?? 0) / totalMin);
}
// Parent rollup from the subtree's bars: envelope clamped to the range,
// progress weighted by each bar's full duration
let summary: TimelineRowBars['summary'] = null;
if (row.isGroup && segments.length === 0 && viewConfig.summaryBars) {
let sumFrom = Infinity;
let sumTo = -Infinity;
for (const id of descendantIds.get(row.resource.id) ?? []) {
const env = envelopes.get(id);
if (!env) continue;
sumFrom = Math.min(sumFrom, env.fromMin / totalMin);
sumTo = Math.max(sumTo, env.toMin / totalMin);
}
if (sumTo > sumFrom) {
summary = {
from: sumFrom,
to: sumTo,
// all-time completion (matches a consumer's tree rollup), not the
// visible-range slice - task progress is independent of scroll
progress: subtreeProgress.get(row.resource.id) ?? null,
};
}
}
// The node's OWN planned window: a band behind all of its lanes.
// Variance reads the latest actual end - the subtree's for a group,
// matching the summary rollup's all-time philosophy.
let rowBaseline: RowLevelBaseline | null = null;
if (viewConfig.baselineBars) {
const plan = resolveEventBaseline(row.resource);
if (plan) {
const planStartMs = plan.start.getTime();
const planEndMs = plan.end.getTime();
const planVisible = plan.milestone
? planStartMs >= rangeStartMs && planStartMs <= rangeEndMs
: planStartMs < rangeEndMs && planEndMs > rangeStartMs;
if (planVisible) {
const ids = row.isGroup ? [row.resource.id, ...(descendantIds.get(row.resource.id) ?? [])] : [row.resource.id];
let latest: number | undefined;
for (const id of ids) {
const end = latestEndByResource.get(id);
if (end !== undefined && (latest === undefined || end > latest)) {
latest = end;
}
}
rowBaseline = {
baseline: plan,
startMin: Math.max((planStartMs - rangeStartMs) / 60000, 0),
endMin: Math.min((planEndMs - rangeStartMs) / 60000, totalMin),
variance: latest === undefined ? null : latest > planEndMs ? 'late' : latest < planEndMs ? 'early' : 'on-time',
};
}
}
}
// The stack, then the row's own padding around it. Centering the block
// in the resulting height gives an equal inset top and bottom, and it
// is also what keeps a lone bar on the tree label's centerline when a
// short row is held open by minRowHeight.
const blockRem = laneBlockRem(laneCount, laneHeightRem, laneGapRem);
const heightRem = Math.max(minRowRem, blockRem + 2 * rowPaddingRem);
const laneOffsetRem = (heightRem - blockRem) / 2;
map.set(row.resource.id, {
segments,
laneCount,
baselines,
rowBaseline,
draftLane: null,
scheduleMode: mode,
heightRem,
laneOffsetRem,
bandRem: laneHeightRem + laneOffsetRem * 2,
extent:
segments.length > 0
? {
from,
to,
color: segments[0].occurrence.event.color,
label: segments.length === 1 ? segments[0].occurrence.event.title : settings.i18n.labels.events(segments.length),
startMs: Math.min(...segments.map((s) => s.occurrence.start.getTime())),
}
: summary
? {
from: summary.from,
to: summary.to,
label: row.resource.title,
startMs: rangeStartMs + summary.from * (rangeEndMs - rangeStartMs),
}
: null,
summary,
});
}
laneMemory.current = nextLanes;
return map;
}, [
rows,
occurrences,
allEvents,
rangeStartMs,
rangeEndMs,
settings.i18n,
viewConfig.summaryBars,
viewConfig.baselineBars,
descendantIds,
subtreeProgress,
laneHeightRem,
rowPaddingRem,
laneGapRem,
minRowRem,
scheduleMode,
]);
// ----- split panes: width state, splitter drag/keyboard, scroll sync -----
const treeConfig = { ...DEFAULT_TREE_PANEL, ...viewConfig.treePanel };
const clampTree = (width: number) => Math.min(Math.max(width, treeConfig.minWidth), treeConfig.maxWidth);
const [treeWidth, setTreeWidth] = useState(treeConfig.width);
const configuredTreeWidth = clampTree(treeWidth);
const columns = viewConfig.columns ?? [];
// "Add task" hint at the foot of the tree, gated by validation
/**
* Reserve the track a drag-create in flight will land on - as a THIN overlay
* over the layout above, never as an input to it. Rebuilding the whole map
* per snapped step would hand every row a new `bars` object and defeat
* GanttTimelineRow's memo across the entire grid, so only the drafted row's
* entry is replaced; every other row keeps its identity and never re-renders.
*
* `laneOffsetRem` and `bandRem` are deliberately carried over UNCHANGED.
* Deriving them from the grown track count re-centres the row, which drags
* the settled bars and the tree label box with it - a 2px wobble by default
* and, under a consumer `metrics.minRowHeight` big enough to swallow the
* growth, an 11.5px jerk that snaps back on release. Growing a row must add
* space BELOW what is already there and move nothing.
*/
const rowBars = useMemo(() => {
if (!draftLayout) return baseRowBars;
const base = baseRowBars.get(draftLayout.resourceId);
if (!base) return baseRowBars;
const next = new Map(baseRowBars);
// "single" packs every bar onto lane 0, so that is where the draft goes
// too and the row never grows. Recorded rather than left null so the
// placeholder's data-lane still names a real destination.
if (base.scheduleMode === 'single') {
next.set(draftLayout.resourceId, { ...base, draftLane: 0 });
return next;
}
const draftLane = lowestFreeLane(base.segments, draftLayout.startMs, draftLayout.endMs);
const trackCount = Math.max(base.laneCount, draftLane + 1);
const draftBlockRem = laneBlockRem(trackCount, laneHeightRem, laneGapRem);
next.set(draftLayout.resourceId, {
...base,
draftLane,
heightRem: Math.max(base.heightRem, base.laneOffsetRem * 2 + draftBlockRem),
});
return next;
}, [baseRowBars, draftLayout, laneHeightRem, laneGapRem]);
// Dependency arrows: resolve every visible bar's anchors in track
// coordinates (x rem from the range start, y rem from the rows-block top).
// Row heights come from rowBars, so transient draft growth shifts the
// arrows with the rows; endpoints without a visible bar are skipped -
// an arrow to a hidden row would point at nothing.
// Which events an arrow DEPARTS from (something else lists them as a
// predecessor). Feeds label spacing only, and membership is data-driven
// rather than render-driven on purpose: a temporarily hidden dependent
// still reserves the gap, so the label never jumps when its arrow scrolls
// back into range. Stable across gestures - it only changes with events.
const dependencySourceIds = useMemo(() => {
if (!viewConfig.dependencyLines) return EMPTY_ID_SET;
let ids: Set<string> | null = null;
for (const event of allEvents) {
if (!event.dependencies?.length) continue;
for (const id of event.dependencies) {
if (!ids) ids = new Set();
ids.add(id);
}
}
return ids ?? EMPTY_ID_SET;
}, [allEvents, viewConfig.dependencyLines]);
const dependencyEdges = useMemo(() => {
const none = { edges: [] as DependencyEdge[], totalRem: 0 };
if (!viewConfig.dependencyLines) return none;
const totalMin = (rangeEndMs - rangeStartMs) / 60000;
if (totalMin <= 0) return none;
type Pending = {
id: string;
dependencies: string[];
startX: number;
y: number;
};
const anchors = new Map<string, { endX: number; y: number }>();
const pending: Pending[] = [];
let topRem = 0;
for (const row of rows) {
const bars = rowBars.get(row.resource.id);
if (bars) {
for (const segment of bars.segments) {
const occ = segment.occurrence;
// a recurring instance has no single edge to anchor a plan on
if (occ.isRecurring) continue;
const lane = segment.column ?? 0;
const y = topRem + laneTopRem(bars.laneOffsetRem, lane, laneHeightRem, laneGapRem) + laneHeightRem / 2;
const startX = ((segment.startMin ?? 0) / totalMin) * trackRemWidth;
const endX = ((segment.endMin ?? 0) / totalMin) * trackRemWidth;
anchors.set(occ.eventId, { endX, y });
if (occ.event.dependencies?.length) {
pending.push({
id: occ.eventId,
dependencies: occ.event.dependencies,
startX,
y,
});
}
}
}
topRem += bars?.heightRem ?? minRowRem;
}
if (pending.length === 0) return none;
const edges: DependencyEdge[] = [];
for (const item of pending) {
for (const depId of item.dependencies) {
if (depId === item.id) continue;
const from = anchors.get(depId);
if (!from) continue;
edges.push({
key: `${depId}->${item.id}`,
fromId: depId,
toId: item.id,
fromX: from.endX,
fromY: from.y,
toX: item.startX,
toY: item.y,
});
}
}
return { edges, totalRem: topRem };
}, [rows, rowBars, rangeStartMs, rangeEndMs, trackRemWidth, laneHeightRem, laneGapRem, minRowRem, viewConfig.dependencyLines]);
const showCreateTask = viewConfig.displayCreateTaskHint && !!settings.onCreateTask && (settings.canCreateTask?.({ parentId: null }) ?? true);
// Responsive guard: the timeline must always keep a usable width, so on
// narrow containers the tree pane yields down toward its minWidth. Measured
// (not media-queried) because the gantt can live in any column. The -1
// reserves the splitter hairline so the timeline truly keeps MIN width.
const [containerWidth, setContainerWidth] = useState(0);
const clampContainer = (width: number, container: number) => {
if (container <= 0) return width;
const ceiling = container - minTimelineWidth - 1;
// The tree's own minWidth is a PREFERENCE, not a licence to squeeze the
// timeline out of existence: cap it by what the container can actually
// spare. Without this cap a consumer minWidth wider than the container
// wins outright and the timeline collapses below minTimelineWidth with
// the splitter already pinned, so the space cannot be dragged back.
const floor = Math.min(treeConfig.minWidth, Math.max(ceiling, 0));
return Math.max(Math.min(width, ceiling), Math.min(floor, container - 1));
};
const clampedTreeWidth = clampContainer(configuredTreeWidth, containerWidth);
/** Live width while the splitter is dragging; render reads it so a
mid-drag re-render can't snap the pane back to stale state. */
const liveTreeWidthRef = useRef<number | null>(null);
// In-flight gestures must never outlive the view (leaked window listeners,
// body overlays and the drag cursor), and must never keep running against
// geometry they measured before it changed - a gesture snapshots the axis
// and row rects once at activation, so any of these invalidates it.
// Cancel-and-revert is the safe contract; all of this is a no-op in normal
// flows (none of these values can change during an ordinary pointer drag).
useGanttGestureTeardown();
useEffect(() => {
cancelActiveGanttGestures();
}, [zoom, scale, rangeKey, clampedTreeWidth, rows.length]);
// Leaf-row checkbox selection: uncontrolled unless selectedRows is passed
const [internalSelected, setInternalSelected] = useState<string[]>([]);
const selectedRows = viewConfig.selectedRows ?? internalSelected;
const selectedSet = useMemo(() => new Set(selectedRows), [selectedRows]);
// Latest-value refs so the row handlers keep ONE identity across renders -
// the row components are memoized and must not re-render per state change
const viewConfigRef = useRef(viewConfig);
viewConfigRef.current = viewConfig;
const selectedRowsRef = useRef(selectedRows);
selectedRowsRef.current = selectedRows;
const toggleRowSelected = useCallback((id: string, checked: boolean) => {
const current = selectedRowsRef.current;
const next = checked ? [...current.filter((rowId) => rowId !== id), id] : current.filter((rowId) => rowId !== id);
if (viewConfigRef.current.selectedRows === undefined) {
setInternalSelected(next);
}
viewConfigRef.current.onSelectedRowsChange?.(next);
}, []);
const bodyRef = useRef<HTMLDivElement | null>(null);
const treePaneRef = useRef<HTMLDivElement | null>(null);
const timelinePaneRef = useRef<HTMLDivElement | null>(null);
const treeRowsRef = useRef<HTMLDivElement | null>(null);
// Track the body width so the tree pane can yield on narrow containers.
// Layout effect, not effect: the first measure must flush BEFORE the first
// paint so a clamped tree width never paints wide for a frame and then
// snaps - the panes are laid out final from the very first displayed frame.
useLayoutEffect(() => {
const body = bodyRef.current;
if (!body) return;
const update = () => setContainerWidth(body.clientWidth);
update();
const observer = new ResizeObserver(update);
observer.observe(body);
return () => observer.disconnect();
}, []);
const beginSplit = (e: React.PointerEvent) => {
if (e.button !== 0) return;
e.preventDefault();
const pointerId = e.pointerId;
const startX = e.clientX;
const startWidth = clampedTreeWidth;
const splitter = e.currentTarget as HTMLElement;
// in RTL the tree pane sits on the right: pointer deltas invert
const dir = getComputedStyle(splitter).direction === 'rtl' ? -1 : 1;
splitter.setAttribute('data-resizing', '');
document.body.style.cursor = 'col-resize';
document.body.style.userSelect = 'none';
// Live width goes straight to the DOM: a React state write here would
// re-render every row and bar per pointermove. State commits on release.
// The container clamp applies live too - the timeline must not collapse
// below its minimum mid-drag only to snap back on release.
let liveWidth = startWidth;
const onMove = (ev: PointerEvent) => {
if (ev.pointerId !== pointerId) return;
liveWidth = clampContainer(clampTree(startWidth + (ev.clientX - startX) * dir), bodyRef.current?.clientWidth ?? 0);
liveTreeWidthRef.current = liveWidth;
if (treePaneRef.current) {
treePaneRef.current.style.width = `${liveWidth}px`;
}
};
const finish = (ev?: PointerEvent) => {
if (ev && ev.pointerId !== pointerId) return;
window.removeEventListener('pointermove', onMove);
window.removeEventListener('pointerup', finish);
window.removeEventListener('pointercancel', finish);
splitter.removeAttribute('data-resizing');
document.body.style.cursor = '';
document.body.style.userSelect = '';
liveTreeWidthRef.current = null;
if (liveWidth !== startWidth) {
setTreeWidth(liveWidth);
viewConfigRef.current.treePanel?.onWidthChange?.(liveWidth);
}
};
window.addEventListener('pointermove', onMove);
window.addEventListener('pointerup', finish);
window.addEventListener('pointercancel', finish);
};
// Both panes scroll vertically; whichever moves drives the other.
useEffect(() => {
const treeViewport = getPaneViewport(treePaneRef.current);
const timelineViewport = getPaneViewport(timelinePaneRef.current);
if (!treeViewport || !timelineViewport) return;
const link = (source: HTMLElement, target: HTMLElement) => {
// Mirror only when the source's own vertical position changed -
// horizontal-only scroll events must not replay a stale scrollTop over
// the other pane. Assign only on drift: the mirrored handler then
// no-ops, so no loop.
let lastTop = source.scrollTop;
const onScroll = () => {
if (source.scrollTop === lastTop) return;
lastTop = source.scrollTop;
if (target.scrollTop !== source.scrollTop) {
target.scrollTop = source.scrollTop;
}
};
source.addEventListener('scroll', onScroll);
return () => source.removeEventListener('scroll', onScroll);
};
const unlinkTree = link(treeViewport, timelineViewport);
const unlinkTimeline = link(timelineViewport, treeViewport);
let unforward: (() => void) | null = null;
if (treeViewport.hasAttribute('data-gantt-native-scroll')) {
// Native mode: the tree's vertical axis is overflow-hidden (its bar
// would duplicate the timeline's), so vertical wheel intent forwards to
// the timeline, which mirrors back through the link above. Horizontal
// wheel intent stays native for the tree's own columns.
const onWheel = (e: WheelEvent) => {
// ctrl/cmd (and trackpad pinch, which sets ctrlKey) is the zoom
// gesture; scrolling as well would move the rows out from under it
if (e.ctrlKey || e.metaKey) return;
if (Math.abs(e.deltaY) <= Math.abs(e.deltaX)) return;
const dy = e.deltaMode === 1 ? e.deltaY * 16 : e.deltaY;
timelineViewport.scrollTop += dy;
e.preventDefault();
};
treeViewport.addEventListener('wheel', onWheel, { passive: false });
unforward = () => treeViewport.removeEventListener('wheel', onWheel);
} else {
// Custom scrollbars: both panes are real vertical scrollers. The links
// above mirror on the scroll event, which fires only AFTER the source
// has already painted - so with compositor momentum (wheel/trackpad) the
// active pane runs a frame ahead of the mirror and the two visibly drift
// (the flicker). Fix: drive BOTH viewports from one wheel handler so they
// move in the same frame, perfectly locked. Horizontal intent stays
// native for each pane's own axis; the links still cover scrollbar drags,
// keyboard, touch and programmatic scrolls; touch has no wheel events,
// so flick-scrolling syncs through the (frame-lagged) link - accepted,
// pointer drags are the gantt's primary touch interaction.
const onWheel = (e: WheelEvent) => {
// ctrl/cmd (and trackpad pinch, which sets ctrlKey) is the zoom
// gesture; scrolling as well would move the rows out from under it
if (e.ctrlKey || e.metaKey) return;
if (Math.abs(e.deltaY) <= Math.abs(e.deltaX)) return;
const max = timelineViewport.scrollHeight - timelineViewport.clientHeight;
if (max <= 0) return;
const unit = e.deltaMode === 1 ? 16 : e.deltaMode === 2 ? timelineViewport.clientHeight : 1;
const next = Math.max(0, Math.min(max, timelineViewport.scrollTop + e.deltaY * unit));
e.preventDefault();
timelineViewport.scrollTop = next;
treeViewport.scrollTop = next;
};
treeViewport.addEventListener('wheel', onWheel, { passive: false });
timelineViewport.addEventListener('wheel', onWheel, { passive: false });
unforward = () => {
treeViewport.removeEventListener('wheel', onWheel);
timelineViewport.removeEventListener('wheel', onWheel);
};
}
return () => {
unlinkTree();
unlinkTimeline();
unforward?.();
};
}, [scale, viewConfig.scrollbars]);
// Linked row hover: mirror data-hover onto the row's twin in the other pane
useEffect(() => {
const body = bodyRef.current;
if (!body) return;
let current: string | null = null;
const apply = (id: string | null) => {
if (id === current) return;
if (current) {
body.querySelectorAll(`[data-gantt-row-id="${CSS.escape(current)}"]`).forEach((el) => el.removeAttribute('data-hover'));
}
if (id) {
body.querySelectorAll(`[data-gantt-row-id="${CSS.escape(id)}"]`).forEach((el) => el.setAttribute('data-hover', ''));
}
current = id;
};
const onOver = (e: PointerEvent) => {
const row = (e.target as HTMLElement | null)?.closest?.('[data-gantt-row-id]');
apply(row?.getAttribute('data-gantt-row-id') ?? null);
};
const onLeave = () => apply(null);
body.addEventListener('pointerover', onOver);
body.addEventListener('pointerleave', onLeave);
return () => {
body.removeEventListener('pointerover', onOver);
body.removeEventListener('pointerleave', onLeave);
apply(null);
};
}, []);
// Auto-manage the horizontal position for the current anchor until the user
// scrolls: pre-buffer one period per side (so infinite scroll never resizes
// the scrollbar on the first gesture), then center the target instant.
// Idempotent - re-running just re-centers the same instant - so React
// StrictMode's double-invoke and range-growth re-renders are both safe.
const anchorMs = useGanttSelector((state) => state.date.getTime());
// flattened to a primitive so an inline `initialCenter={new Date(...)}`
// cannot re-run the centring effect on every render
const initialCenter = viewConfig.initialCenter instanceof Date ? viewConfig.initialCenter.getTime() : viewConfig.initialCenter;
const manageRef = useRef({ key: '', buffered: false, userTook: false });
useLayoutEffect(() => {
const key = `${scale}:${anchorMs}:${viewConfig.scrollbars}`;
if (manageRef.current.key !== key) {
// An anchor change from an extendRange window SLIDE continues the
// user's own travel: the guard survives, or the pre-buffer branch
// would re-extend and cascade further slides at the window cap.
const slideContinuation = manageRef.current.userTook && instance.internals.didAnchorSlide();
manageRef.current = slideContinuation
? { key, buffered: manageRef.current.buffered, userTook: true }
: { key, buffered: false, userTook: false };
}
if (manageRef.current.userTook) return;
// Deferred-mount wait: when the viewport is not measurable yet (hidden
// tab, display:none ancestor), a ResizeObserver resumes positioning on
// the exact frame it gains a size - RO callbacks run in the rendering
// steps BEFORE that frame paints, so no uncentered frame is ever shown.
// (An rAF retry here would paint the range start first and then snap.)
let waiter: ResizeObserver | null = null;
const run = () => {
waiter?.disconnect();
waiter = null;
const viewport = getPaneViewport(timelinePaneRef.current);
const axis = viewport?.querySelector<HTMLElement>('[data-gantt-axis]');
if (!viewport || !axis) return;
if (viewport.clientWidth === 0) {
waiter = new ResizeObserver(() => {
if (viewport.clientWidth > 0) run();
});
waiter.observe(viewport);
return;
}
// pre-buffer once; the re-run after the range grows lands the center
if (viewConfig.infiniteScroll && !manageRef.current.buffered) {
manageRef.current.buffered = true;
extendLockRef.current = true;
instance.internals.extendRange('before');
instance.internals.extendRange('after');
return;
}
extendLockRef.current = false;
if (viewport.scrollWidth <= viewport.clientWidth) return;
// read the clock at run time - the effect must not depend on a
// reactive now that re-runs it (and the whole grid) every 30s.
// Target now ONLY when the anchor period itself contains it: keying
// on the whole (buffered) visible range would re-center prev/next
// navigation right back onto today.
const active = instance.getState().activeRange;
let target: number;
if (typeof initialCenter === 'number') {
target = initialCenter;
} else if (initialCenter === 'anchor') {
target = anchorMs;
} else {
const nowMs = Date.now();
target = nowMs >= active.start.getTime() && nowMs < active.end.getTime() ? nowMs : anchorMs;
}
const fraction = Math.min(Math.max((target - rangeStartMs) / (rangeEndMs - rangeStartMs), 0), 1);
setScrollStart(viewport, Math.max(0, fraction * viewport.scrollWidth - viewport.clientWidth / 2));
};
run();
return () => {
waiter?.disconnect();
};
}, [scale, anchorMs, initialCenter, viewConfig.scrollbars, viewConfig.infiniteScroll, rangeKey, rangeStartMs, rangeEndMs, instance]);
// ----- infinite scroll: grow the range near an edge, keep the position -----
// Restoration is anchored to a TIMESTAMP, not pixel deltas: it survives
// growth, window slides, and zoom changes alike.
const pendingRestoreRef = useRef<{
ms: number;
align: 'start' | 'center';
/**
* Park the anchored instant this many pixels from the viewport's inline
* start instead of at the edge or the middle. Wheel zoom needs it so the
* instant under the cursor stays under the cursor.
*/
offsetPx?: number;
} | null>(null);
const extendLockRef = useRef(false);
const lastUserScrollRef = useRef(0);
/** Fine-grained viewport-center instant, for controlled-zoom anchoring. */
const fineCenterRef = useRef<number | null>(null);
const lastZoomRef = useRef<number | null>(null);
// Only user gestures may extend the range - programmatic scrolls (chip
// jumps, auto-center, zoom clamping) must never grow it.
useEffect(() => {
const pane = timelinePaneRef.current;
if (!pane) return;
const markIntent = () => {
lastUserScrollRef.current = performance.now();
};
// zooming is not scroll intent - the re-seat it triggers must not be
// mistaken for the user reaching an edge and asking to grow the range
const markWheelIntent = (e: WheelEvent) => {
if (e.ctrlKey || e.metaKey) return;
markIntent();
};
// pointerdown counts only where pressing can scroll: the scrollbars,
// the pan header, or a native-scroll host - NOT bars, chips, or zoom
const onPointerDown = (e: PointerEvent) => {
const target = e.target as HTMLElement | null;
if (target?.closest('[data-slot=scroll-area-scrollbar], [data-slot=gantt-timeline-header], [data-gantt-native-scroll]')) {
markIntent();
}
};
pane.addEventListener('wheel', markWheelIntent, { passive: true });
pane.addEventListener('pointerdown', onPointerDown);
pane.addEventListener('touchstart', markIntent, { passive: true });
pane.addEventListener('keydown', markIntent);
return () => {
pane.removeEventListener('wheel', markWheelIntent);
pane.removeEventListener('pointerdown', onPointerDown);
pane.removeEventListener('touchstart', markIntent);
pane.removeEventListener('keydown', markIntent);
};
}, []);
useEffect(() => {
if (!viewConfig.infiniteScroll) return;
const viewport = getPaneViewport(timelinePaneRef.current);
if (!viewport) return;
const tryExtend = (direction: 'before' | 'after') => {
// anchor the left edge as an instant, from the LIVE axis range
const axis = viewport.querySelector<HTMLElement>('[data-gantt-axis]');
const liveStart = Number(axis?.dataset.ganttRangeStart);
const liveEnd = Number(axis?.dataset.ganttRangeEnd);
if (!axis || Number.isNaN(liveStart) || Number.isNaN(liveEnd)) return;
extendLockRef.current = true;
manageRef.current.userTook = true;
pendingRestoreRef.current = {
ms: liveStart + (getScrollStart(viewport) / viewport.scrollWidth) * (liveEnd - liveStart),
align: 'start',
};
if (!instance.internals.extendRange(direction)) {
pendingRestoreRef.current = null;
extendLockRef.current = false;
}
};
// scrollLeft is signed by direction; all edge math runs on the
// distance-from-inline-start so RTL panes behave identically
const isRtl = getComputedStyle(viewport).direction === 'rtl';
const onScroll = () => {
if (extendLockRef.current) return;
if (performance.now() - lastUserScrollRef.current > 1200) return;
// a track that fits the pane has no scroll gesture to extend from
if (viewport.scrollWidth <= viewport.clientWidth + 8) return;
const fromStart = getScrollStart(viewport);
const fromEnd = viewport.scrollWidth - fromStart - viewport.clientWidth;
const direction = fromStart < infiniteEdgePx ? ('before' as const) : fromEnd < infiniteEdgePx ? ('after' as const) : null;
if (!direction) return;
tryExtend(direction);
};
// parked exactly on an edge, further wheeling emits no scroll event -
// the wheel itself is the growth gesture then
const onWheel = (e: WheelEvent) => {
// a zoom gesture must never grow the range: the track is rescaling
// under the pointer, so an edge reading mid-gesture is meaningless
if (e.ctrlKey || e.metaKey) return;
if (extendLockRef.current || e.deltaX === 0) return;
if (viewport.scrollWidth <= viewport.clientWidth + 8) return;
const towardStart = isRtl ? e.deltaX > 0 : e.deltaX < 0;
if (towardStart && getScrollStart(viewport) <= 0) {
tryExtend('before');
} else if (!towardStart && getScrollStart(viewport) + viewport.clientWidth >= viewport.scrollWidth - 1) {
tryExtend('after');
}
};
viewport.addEventListener('scroll', onScroll);
viewport.addEventListener('wheel', onWheel, { passive: true });
return () => {
viewport.removeEventListener('scroll', onScroll);
viewport.removeEventListener('wheel', onWheel);
};
}, [instance, viewConfig.infiniteScroll, scale, viewConfig.scrollbars, infiniteEdgePx]);
// Report the visible-center instant so the nav title names what you are
// looking at. Throttled to period boundaries (a coarse key) so scrolling
// within a period never re-renders the grid.
useEffect(() => {
const viewport = getPaneViewport(timelinePaneRef.current);
if (!viewport) return;
const keyFmt =
scale === 'day' ? 'yyyy-MM-dd' : scale === 'week' ? "RRRR-'W'II" : scale === 'month' ? 'yyyy-MM' : scale === 'quarter' ? 'yyyy-qqq' : 'yyyy';
let raf = 0;
let lastKey = '';
const measure = () => {
raf = 0;
const axis = viewport.querySelector<HTMLElement>('[data-gantt-axis]');
const liveStart = Number(axis?.dataset.ganttRangeStart);
const liveEnd = Number(axis?.dataset.ganttRangeEnd);
if (!axis || Number.isNaN(liveStart) || Number.isNaN(liveEnd)) return;
const fraction = (getScrollStart(viewport) + viewport.clientWidth / 2) / Math.max(1, viewport.scrollWidth);
const centerMs = liveStart + fraction * (liveEnd - liveStart);
// fine center first (controlled-zoom anchor), then the coarse-keyed
// store report that drives the nav title
fineCenterRef.current = centerMs;
const center = new Date(centerMs);
const key = format(toZoned(center, timeZone), keyFmt);
if (key === lastKey) return;
lastKey = key;
instance.internals.setViewportCenter(center);
};
const schedule = () => {
if (!raf) raf = requestAnimationFrame(measure);
};
viewport.addEventListener('scroll', schedule);
schedule();
return () => {
viewport.removeEventListener('scroll', schedule);
if (raf) cancelAnimationFrame(raf);
};
}, [instance, scale, timeZone, viewConfig.scrollbars, rangeKey]);
// Re-seat the viewport on its anchored instant before paint. Runs for range
// growth, window slides, and zoom changes; a slide moves the anchor date,
// so pre-mark auto-centering as done for the new key.
useLayoutEffect(() => {
// Consumer-driven (controlled) zoom changes carry no anchorZoomCenter
// call; anchor them to the last known viewport center so the view does
// not drift. Built-in buttons set pendingRestore first and win.
if (lastZoomRef.current !== null && lastZoomRef.current !== zoom && !pendingRestoreRef.current && fineCenterRef.current !== null) {
pendingRestoreRef.current = {
ms: fineCenterRef.current,
align: 'center',
};
}
lastZoomRef.current = zoom;
let raf: number | null = null;
let attempts = 0;
const seat = () => {
raf = null;
const viewport = getPaneViewport(timelinePaneRef.current);
if (viewport && pendingRestoreRef.current) {
// Not laid out yet (0-width on first mount): centering with a 0 offset
// parks the view a half-pane off. Defer until the pane is measured so
// "center" lands the anchored instant in the middle on initial load.
if (viewport.clientWidth === 0 && attempts++ < 20) {
raf = requestAnimationFrame(seat);
return;
}
const { ms, align, offsetPx } = pendingRestoreRef.current;
pendingRestoreRef.current = null;
// clamp: a stale anchor (e.g. an ignored controlled-zoom proposal)
// must never park the view outside the track
const fraction = Math.min(Math.max((ms - rangeStartMs) / (rangeEndMs - rangeStartMs), 0), 1);
const offset = offsetPx ?? (align === 'center' ? viewport.clientWidth / 2 : 0);
setScrollStart(viewport, Math.max(0, fraction * viewport.scrollWidth - offset));
}
extendLockRef.current = false;
};
seat();
return () => {
if (raf !== null) cancelAnimationFrame(raf);
};
}, [rangeKey, zoom, rangeStartMs, rangeEndMs, scale, viewConfig.scrollbars, instance]);
/** Keep the view centered on the same instant across a zoom step. */
const anchorZoomCenter = () => {
const viewport = getPaneViewport(timelinePaneRef.current);
const axis = viewport?.querySelector<HTMLElement>('[data-gantt-axis]');
if (!viewport || !axis) return;
const liveStart = Number(axis.dataset.ganttRangeStart);
const liveEnd = Number(axis.dataset.ganttRangeEnd);
if (Number.isNaN(liveStart) || Number.isNaN(liveEnd)) return;
pendingRestoreRef.current = {
ms: liveStart + ((getScrollStart(viewport) + viewport.clientWidth / 2) / viewport.scrollWidth) * (liveEnd - liveStart),
align: 'center',
};
};
/**
* Keep the instant under the POINTER pinned across a zoom step. The buttons
* anchor the viewport center, but a wheel or pinch gesture points at
* something - zooming away from it reads as the content sliding out from
* under the cursor.
*/
const anchorZoomPointer = (clientX: number) => {
const viewport = getPaneViewport(timelinePaneRef.current);
const axis = viewport?.querySelector<HTMLElement>('[data-gantt-axis]');
if (!viewport || !axis) return;
const liveStart = Number(axis.dataset.ganttRangeStart);
const liveEnd = Number(axis.dataset.ganttRangeEnd);
if (Number.isNaN(liveStart) || Number.isNaN(liveEnd)) return;
// trackPoint mirrors in RTL, where the range start is the right edge
const offsetPx = trackPoint(viewport, clientX).offset;
pendingRestoreRef.current = {
ms: liveStart + ((getScrollStart(viewport) + offsetPx) / viewport.scrollWidth) * (liveEnd - liveStart),
align: 'start',
offsetPx,
};
};
// ----- ctrl/cmd + wheel (and trackpad pinch) zooms the time range -----
// The listener is manual and non-passive because it must preventDefault:
// React's synthetic wheel handler cannot. It attaches once and reads the
// live logic through a ref, so a zoom step never re-binds mid-gesture.
const wheelZoomRef = useRef<((e: WheelEvent) => void) | null>(null);
useEffect(() => {
wheelZoomRef.current = (e: WheelEvent) => {
if (!viewConfig.wheelZoom) return;
// Browsers deliver a trackpad pinch as wheel + ctrlKey on every
// platform; metaKey is the Mac keyboard idiom the same gesture implies.
if (!e.ctrlKey && !e.metaKey) return;
const lines = e.deltaMode === 1 ? 16 : e.deltaMode === 2 ? 400 : 1;
// Continuous, not stepped: a pinch emits dozens of small deltas per
// second, so the button's 0.25 step would slam to a limit instantly.
// Exponential keeps each notch proportional at any zoom level.
const next = clampZoom(zoom * Math.exp(-e.deltaY * lines * 0.002));
// Already clamped: hand the gesture back so the browser's own page
// zoom still works for anyone who relies on it.
if (Math.abs(next - zoom) < 1e-4) return;
e.preventDefault();
// Controlled zoom anchors via fineCenterRef when the parent adopts;
// pre-setting an anchor would leak stale if the parent ignores it.
if (viewConfig.zoom === undefined) anchorZoomPointer(e.clientX);
setZoomValue(+next.toFixed(4));
};
});
useEffect(() => {
const viewport = getPaneViewport(timelinePaneRef.current);
if (!viewport) return;
const onWheel = (e: WheelEvent) => wheelZoomRef.current?.(e);
viewport.addEventListener('wheel', onWheel, { passive: false });
return () => viewport.removeEventListener('wheel', onWheel);
}, [viewConfig.scrollbars, scale]);
// Drag-to-pan from the header (intent-based: activates after 4px)
const beginHeaderPan = (e: React.PointerEvent) => {
if (e.button !== 0) return;
const viewport = getPaneViewport(timelinePaneRef.current);
if (!viewport) return;
const pointerId = e.pointerId;
const startX = e.clientX;
const startLeft = viewport.scrollLeft;
let active = false;
const onMove = (ev: PointerEvent) => {
if (ev.pointerId !== pointerId) return;
const dx = ev.clientX - startX;
if (!active && Math.abs(dx) < 4) return;
if (!active) {
markGestureEnd();
setIsPanning(true);
}
active = true;
// panning is a user scroll: keep the infinite-scroll gate open
lastUserScrollRef.current = performance.now();
document.body.style.cursor = 'grabbing';
document.body.style.userSelect = 'none';
viewport.scrollLeft = startLeft - dx;
};
const finish = (ev?: PointerEvent) => {
if (ev && ev.pointerId !== pointerId) return;
window.removeEventListener('pointermove', onMove);
window.removeEventListener('pointerup', finish);
window.removeEventListener('pointercancel', finish);
document.body.style.cursor = '';
document.body.style.userSelect = '';
if (active) setIsPanning(false);
};
window.addEventListener('pointermove', onMove);
window.addEventListener('pointerup', finish);
window.addEventListener('pointercancel', finish);
};
// Panning suppresses the placement hints (scroll intent, not create intent)
const [isPanning, setIsPanning] = useState(false);
// ----- tree-row drag reorder (mirrors the event engine: live validity,
// destructive styling when invalid, Esc cancel, commit via callback) -----
const [reorder, setReorder] = useState<TimelineReorderState | null>(null);
const reorderEnabled = !!settings.onResourceReorder;
const settingsRef = useRef(settings);
settingsRef.current = settings;
const rowsRef = useRef(rows);
rowsRef.current = rows;
const beginRowReorder = useCallback((e: React.PointerEvent, dragRow: TimelineRow) => {
const settings = settingsRef.current;
const rows = rowsRef.current;
if (e.button !== 0 || !settings.onResourceReorder) return;
e.preventDefault();
e.stopPropagation();
const container = treeRowsRef.current;
const pane = treePaneRef.current;
if (!container || !pane) return;
const rowEls = Array.from(container.querySelectorAll<HTMLElement>('[data-slot=gantt-row-group]'));
document.body.style.cursor = 'grabbing';
document.body.style.userSelect = 'none';
let current: TimelineReorderState | null = null;
let lastBoundary = -1;
// Carry overlay: clone the WHOLE row (name + detail columns), flat -
// it reads as the row itself moving, not a separate card
const pointerId = e.pointerId;
const rowEl = (e.currentTarget as HTMLElement).closest<HTMLElement>('[data-slot=gantt-row-group]');
const overlay = document.createElement('div');
overlay.setAttribute('data-slot', 'gantt-drag-overlay');
overlay.className = 'bg-background pointer-events-none fixed overflow-hidden opacity-95';
overlay.style.zIndex = '100';
// body-appended, so it is outside the gantt root that owns the type
// scale: without adopting the root's resolved metrics the carried row
// renders at the document default and reads bigger than the row it left
const ganttRoot = pane.closest<HTMLElement>('[data-slot=gantt]');
if (ganttRoot) {
const rootStyle = getComputedStyle(ganttRoot);
overlay.style.fontSize = rootStyle.fontSize;
overlay.style.lineHeight = rootStyle.lineHeight;
overlay.style.fontFamily = rootStyle.fontFamily;
overlay.style.letterSpacing = rootStyle.letterSpacing;
overlay.style.direction = rootStyle.direction;
}
if (rowEl) {
const rowRect = rowEl.getBoundingClientRect();
overlay.style.width = `${rowRect.width}px`;
overlay.style.height = `${rowRect.height}px`;
const clone = rowEl.cloneNode(true) as HTMLElement;
clone.removeAttribute('data-gantt-row-id');
clone.classList.remove('border-b');
clone.style.height = '100%';
overlay.appendChild(clone);
}
document.body.appendChild(overlay);
const grabRect = rowEl?.getBoundingClientRect();
const grabDY = grabRect ? e.clientY - grabRect.top : 8;
// vertical-only carry, locked to the tree panel like a list row drag
const lockedX = grabRect?.left ?? pane.getBoundingClientRect().left;
const paneRect = pane.getBoundingClientRect();
const rowH = grabRect?.height ?? 40;
// Rows do not move during the gesture (the carry is a fixed overlay), so
// rects are measured ONCE - per-move full-row rect scans forced a
// synchronous reflow after every overlay style write.
const rects = rowEls.map((el) => el.getBoundingClientRect());
const place = (y: number) => {
const top = Math.min(Math.max(y - grabDY, paneRect.top), paneRect.bottom - rowH);
overlay.style.left = `${lockedX}px`;
overlay.style.top = `${top}px`;
};
place(e.clientY);
const propose = (boundary: number): TimelineReorderState => {
const below = rows[boundary];
const parentId = below?.parentId ?? rows[rows.length - 1]?.parentId ?? null;
let index = 0;
for (let i = 0; i < boundary; i++) {
if (rows[i].parentId === parentId && rows[i].resource.id !== dragRow.resource.id) {
index++;
}
}
const next = reorderResources(settings.resources, dragRow.resource.id, parentId, index);
const proposal: GanttResourceReorder | null = next
? {
resourceId: dragRow.resource.id,
parentId,
index,
resources: next,
}
: null;
const valid = !!proposal && (settings.canReorderResource?.(proposal) ?? true);
const top = boundary < rects.length ? rects[boundary].top - paneRect.top : (rects[rects.length - 1]?.bottom ?? paneRect.top) - paneRect.top;
return { resourceId: dragRow.resource.id, top, valid, proposal };
};
const onMove = (ev: PointerEvent) => {
if (ev.pointerId !== pointerId) return;
place(ev.clientY);
let boundary = rects.length;
for (let i = 0; i < rects.length; i++) {
if (ev.clientY < rects[i].top + rects[i].height / 2) {
boundary = i;
break;
}
}
// the immutable tree clone + validity check run only when the pointer
// crosses into another slot, not per pointermove
if (boundary === lastBoundary) return;
lastBoundary = boundary;
const nextState = propose(boundary);
if (current && current.top === nextState.top && current.valid === nextState.valid) {
return;
}
current = nextState;
document.body.style.cursor = nextState.valid ? 'grabbing' : 'not-allowed';
setReorder(nextState);
};
const finish = (commit: boolean) => {
window.removeEventListener('pointermove', onMove);
window.removeEventListener('pointerup', onUp);
window.removeEventListener('pointercancel', onCancelEvent);
window.removeEventListener('keydown', onKey);
overlay.remove();
document.body.style.cursor = '';
document.body.style.userSelect = '';
if (commit && current?.proposal && !current.valid) {
// released on a rejected position (e.g. a pinned row): let the
// consumer explain it - the destructive indicator already showed live
settings.onResourceReorderReject?.(current.proposal);
} else if (commit && current?.valid && current.proposal) {
settings.onResourceReorder?.(current.proposal);
const announcer = pane.closest<HTMLElement>('[data-slot=gantt]')?.querySelector<HTMLElement>('[data-slot=gantt-announcer]');
if (announcer) {
announcer.textContent = `${dragRow.resource.title}: ${settings.i18n.labels.reorder}`;
}
}
setReorder(null);
};
const onUp = (ev: PointerEvent) => {
if (ev.pointerId !== pointerId) return;
finish(true);
};
const onCancelEvent = (ev: PointerEvent) => {
if (ev.pointerId !== pointerId) return;
finish(false);
};
const onKey = (ev: KeyboardEvent) => {
if (ev.key === 'Escape') finish(false);
};
window.addEventListener('pointermove', onMove);
window.addEventListener('pointerup', onUp);
window.addEventListener('pointercancel', onCancelEvent);
window.addEventListener('keydown', onKey);
}, []);
const collapsedIdsRef = useRef(collapsedIds);
collapsedIdsRef.current = collapsedIds;
// Stable identity (reads through refs) so memoized rows survive re-renders
const onToggleRow = useCallback((row: TimelineRow) => {
const current = collapsedIdsRef.current;
const next = current.includes(row.resource.id) ? current.filter((id) => id !== row.resource.id) : [...current, row.resource.id];
if (viewConfigRef.current.collapsedGroups === undefined) {
setInternalCollapsed(next);
}
viewConfigRef.current.onCollapsedGroupsChange?.(next);
}, []);
const loading = useGanttSelector<unknown, boolean>((state) => state.loading);
const customScrollbars = viewConfig.scrollbars !== 'native';
const gridLines = resolveTimelineLines(viewConfig.timelineLines);
const showVerticalLines = gridLines.vertical !== null;
const offDayClassName = (typeof viewConfig.offDays === 'object' && viewConfig.offDays.className) || 'bg-muted/40';
// Body texture: default off-days carry a whisper-faint diagonal hatch over
// a lighter wash (header cells stay flat). A custom offDays.className
// replaces both surfaces verbatim.
const offDayBodyClassName =
(typeof viewConfig.offDays === 'object' && viewConfig.offDays.className) ||
'bg-muted/25 bg-[repeating-linear-gradient(135deg,transparent,transparent_5px,color-mix(in_oklab,var(--color-border)_35%,transparent)_5px,color-mix(in_oklab,var(--color-border)_35%,transparent)_6px)]';
// Header-only unit lines, and ONE mechanism for every vertical line in the
// header: positioned spans at calc(fraction% - 1px). A background gradient
// rasterizes stripe positions differently from element layout at fractional
// unit widths, which shifted the group-row boundaries 1px off the unit
// lines below them mid-track - identical span formulas snap identically.
// The body stays bare - rows separate by whitespace, never vertical borders.
const showUnitLines = !uniform || showVerticalLines;
// ----- tree pane content -----
// Header label offset = the row cell's ps-3 (0.75rem) left gutter + the
// toggle/checkbox gutter (w-5 + me-1 = 1.5rem) + the reorder grip (0.875rem)
// when present, so "Resources" lines up with the row titles below it.
const namePaddingStart = reorderEnabled ? '3.125rem' : '2.25rem';
const treeContent = (
<div
className={cn(
'flex min-h-full w-max min-w-full flex-col',
// clearance for the pinned horizontal scrollbar strip
customScrollbars && 'pb-2.5',
)}
>
{/* Same 65px height as the two-row timeline header so the panes align.
The head keeps its own bottom rule (under the Resources label), but
the header/body boundary line is transparent so the first tree node
has no rule directly above it - the 1px is kept only to preserve the
65px height, matching the timeline. */}
<div data-slot="gantt-tree-header" className="bg-background sticky top-0 z-30 box-content h-16 shrink-0 border-b border-b-transparent">
<div className="flex h-8 border-b">
<div className="flex h-full min-w-0 flex-1">
<div
className="flex h-full shrink-0 items-center"
style={{
width: treeConfig.nameColumnWidth,
paddingInlineStart: namePaddingStart,
}}
>
<span className="text-muted-foreground truncate font-medium">{settings.i18n.labels.resources}</span>
</div>
{columns.map((column) => (
<div
key={column.id}
data-slot="gantt-column-header"
data-column={column.id}
className={cn(
'text-muted-foreground flex h-full shrink-0 items-center px-2 font-medium',
column.align === 'center' && 'justify-center',
column.align === 'end' && 'justify-end',
column.className,
)}
style={{ width: column.width ?? DEFAULT_COLUMN_WIDTH }}
>
<span className="truncate">{column.title ?? column.id}</span>
</div>
))}
<div className="min-w-0 flex-1" />
</div>
{viewConfig.columnsMenu && (
<div
data-slot="gantt-columns-menu"
// gradient lead-in: scrolled column headers dissolve into this
// sticky control instead of hard-clipping against its background
className="bg-background before:from-background sticky end-0 z-10 flex h-full shrink-0 items-center ps-1.5 pe-2.5 before:pointer-events-none before:absolute before:inset-y-0 before:-start-5 before:w-5 before:bg-linear-to-l before:to-transparent rtl:before:bg-linear-to-r"
>
{viewConfig.columnsMenu}
</div>
)}
</div>
</div>
<div ref={treeRowsRef} className="flex flex-col">
{rows.map((row) => (
<GanttTreeRow
key={row.resource.id}
row={row}
heightRem={rowBars.get(row.resource.id)?.heightRem ?? minRowRem}
bandRem={rowBars.get(row.resource.id)?.bandRem ?? minRowRem}
columns={columns}
nameWidth={treeConfig.nameColumnWidth}
dimmed={reorder?.resourceId === row.resource.id}
selected={selectedSet.has(row.resource.id)}
onSelectedChange={row.isGroup ? undefined : toggleRowSelected}
onGripPointerDown={reorderEnabled ? beginRowReorder : undefined}
onToggle={onToggleRow}
/>
))}
{showCreateTask && (
<button
type="button"
data-slot="gantt-create-task"
// mirror the tree row's left structure so the + lands in the same
// column as the row toggle chevrons, and the label lines up with
// the task titles above
className="text-muted-foreground hover:text-foreground hover:bg-muted/40 flex h-10 w-full shrink-0 items-center border-b ps-3 pe-3"
onClick={() =>
settings.onCreateTask?.({
parentId: null,
index: settings.resources.length,
})
}
>
<span className="flex h-full w-full items-center">
{reorderEnabled && <span aria-hidden className="w-3.5 shrink-0" />}
{/* group chevrons sit centered in a size-5 button that fills
this w-5 gutter, so the + must center here too */}
<span className="me-1 flex w-5 shrink-0 items-center justify-center">
<PlusIcon className="size-3.5" aria-hidden="true" />
</span>
<span>{settings.i18n.labels.addTask}</span>
</span>
</button>
)}
</div>
</div>
);
// ----- timeline pane content -----
const timelineContent = (
<div
className={cn(
// grow (not just min-h-full) so the body reaches the bottom of the
// pane: the columns then run the full height and the empty space
// below the last row becomes pannable canvas instead of dead area
'flex min-h-full w-max min-w-full grow flex-col',
customScrollbars && 'pb-2.5',
)}
>
{/* Two-row grouped header; also the drag-to-pan surface */}
<div
data-slot="gantt-timeline-header"
className="bg-background sticky top-0 z-30 shrink-0 border-b"
style={{ minWidth: trackWidth }}
onPointerDown={beginHeaderPan}
>
{/* group sectors; boundaries painted like the body lines */}
<div className="relative h-8 border-b">
<div className="flex h-full">
{groups.map((group) => (
<div
key={group.key}
data-slot="gantt-axis-group"
// no `truncate` here: overflow-hidden would make this the
// sticky label's scrollport and the stick would never fire
className="text-muted-foreground flex min-w-0 items-center ps-3 pe-2"
style={{ flex: `${group.span} 0 0px` }}
>
{/* Pure-CSS sticky: the label rides the leading edge for as
long as its own band is on screen, then the next band pushes
it out - so the day you are looking at always names itself.
The browser composites this; a scroll listener would run JS
on every frame to do worse. start-3 matches the cell's ps-3
so the gutter is identical parked or pinned. */}
<span data-slot="gantt-axis-group-label" className="sticky start-3 max-w-full truncate">
{group.label}
</span>
</div>
))}
</div>
{/* same span formula as the unit lines below: equal fractions get
equal layout rounding, so the two rows' lines never drift apart */}
{groupBoundaries.map((fraction) => (
<span
key={fraction}
aria-hidden
className="bg-border absolute inset-y-0 w-px"
style={{ insetInlineStart: `calc(${fraction * 100}% - 1px)` }}
/>
))}
</div>
{/* units, engine axis = this row */}
<div
data-gantt-axis=""
data-gantt-range-start={rangeStartMs}
data-gantt-range-end={rangeEndMs}
data-gantt-snap={snapMin}
className="relative h-8"
>
{/* chrome underlay: off-day washes under the label layer */}
<div aria-hidden className="absolute inset-0">
{unitFractions.map(
({ unit, start, width }) =>
unit.isOff && (
<span
key={unit.key}
className={cn('absolute inset-y-0', offDayClassName)}
style={{
insetInlineStart: `${start * 100}%`,
width: `${width * 100}%`,
}}
/>
),
)}
</div>
<div className="flex h-full">
{units.map((unit) => (
<div
key={unit.key}
data-today={unit.isToday || undefined}
data-off={unit.isOff || undefined}
className={cn(
'flex min-w-0 items-center justify-center truncate px-1.5 text-center',
'text-muted-foreground',
unit.isToday && 'text-primary font-medium',
)}
style={{ flex: `${unit.weight} 0 0px` }}
>
{/* today reads as a soft pill, not just tinted text */}
{unit.isToday ? <span className="bg-primary/10 truncate rounded-full px-1.5 py-px">{unit.label}</span> : unit.label}
</div>
))}
</div>
{showUnitLines &&
unitFractions.slice(1).map(({ unit, start }) => (
<span
key={unit.key}
aria-hidden
data-slot="gantt-grid-line"
data-axis="vertical"
className={cn(
'absolute inset-y-0 w-px',
// a dashed rule is a repeating gradient, not a border: the
// line is a 1px span, and border-dashed on a zero-width box
// paints nothing
gridLines.vertical === 'dashed'
? 'bg-[repeating-linear-gradient(to_bottom,var(--color-border)_0,var(--color-border)_3px,transparent_3px,transparent_6px)]'
: 'bg-border',
)}
style={{ insetInlineStart: `calc(${start * 100}% - 1px)` }}
/>
))}
{viewConfig.nowIndicator && <GanttNowDot rangeStartMs={rangeStartMs} rangeEndMs={rangeEndMs} />}
</div>
</div>
{/* Rows over a shared backdrop (off days, today, boundaries, now);
grows so the columns run to the bottom of the pane. Pressing anywhere
here that is not a bar or a hint tile begins a scroll pan - the whole
panel is a draggable canvas, not just the rows. */}
<div className="relative flex min-h-0 grow flex-col" onPointerDown={beginHeaderPan}>
{/* off-day / today / now backdrop only; vertical gridlines are
per-row and reveal on selection, not painted here */}
<div aria-hidden data-slot="gantt-timeline-backdrop" className="pointer-events-none absolute inset-0">
{unitFractions.map(({ unit, start, width }) => (
<span key={unit.key} className="contents">
{unit.isOff && (
<span
data-off=""
className={cn('absolute inset-y-0', offDayBodyClassName)}
style={{
insetInlineStart: `${start * 100}%`,
width: `${width * 100}%`,
}}
/>
)}
{unit.isToday && scale !== 'day' && (
<span
data-today=""
className="bg-primary/5 absolute inset-y-0"
style={{
insetInlineStart: `${start * 100}%`,
width: `${width * 100}%`,
}}
/>
)}
</span>
))}
{/* one layer for the whole body, not per row: the unit boundaries
have to line up with the header's spans exactly, so both use the
same fraction formula */}
{gridLines.vertical !== null &&
unitFractions
.slice(1)
.map(({ unit, start }) => (
<span
key={`grid-${unit.key}`}
data-slot="gantt-grid-line"
data-axis="vertical"
className={cn(
'absolute inset-y-0 w-px',
gridLines.vertical === 'dashed'
? 'bg-[repeating-linear-gradient(to_bottom,var(--color-border)_0,var(--color-border)_3px,transparent_3px,transparent_6px)]'
: 'bg-border',
)}
style={{ insetInlineStart: `calc(${start * 100}% - 1px)` }}
/>
))}
{viewConfig.nowIndicator && <GanttNowLine rangeStartMs={rangeStartMs} rangeEndMs={rangeEndMs} />}
</div>
{/* Dependency arrows: after the backdrop, before the rows, so they
run above the off-day wash but under every bar. Its own component
because it follows drags per snap step, and that subscription must
re-render a few paths, never this whole view. */}
{dependencyEdges.edges.length > 0 && (
<GanttDependencyLayer
edges={dependencyEdges.edges}
totalRem={dependencyEdges.totalRem}
trackRemWidth={trackRemWidth}
rangeStartMs={rangeStartMs}
rangeEndMs={rangeEndMs}
laneHeightRem={laneHeightRem}
laneGapRem={laneGapRem}
/>
)}
{rows.map((row, rowIndex) => (
<GanttTimelineRow
key={row.resource.id}
row={row}
rowIndex={rowIndex}
bars={rowBars.get(row.resource.id)}
rangeStartMs={rangeStartMs}
rangeEndMs={rangeEndMs}
trackWidth={trackWidth}
trackRemWidth={trackRemWidth}
rowBorder={gridLines.horizontal}
selected={selectedSet.has(row.resource.id)}
resolveHintStop={resolveHintStop}
isPanning={isPanning}
laneHeightRem={laneHeightRem}
laneGapRem={laneGapRem}
minRowRem={minRowRem}
ghostHeightRem={ghostHeightRem}
dependencySourceIds={dependencySourceIds}
/>
))}
{rows.length === 0 && viewConfig.renderNoResources && (
<div data-slot="gantt-no-resources" className="text-muted-foreground flex grow items-center justify-center p-6 text-sm">
{viewConfig.renderNoResources()}
</div>
)}
{showCreateTask && <div aria-hidden data-slot="gantt-create-task-spacer" className="h-10 border-b" style={{ minWidth: trackWidth }} />}
</div>
</div>
);
const horizontalScrollbar = (
<ScrollBar
orientation="horizontal"
// taller strip with vertical padding so the thumb is not crowded.
// end-0 runs the strip (bg + top border) to the pane's right edge instead
// of stopping short by the corner width - the vertical scrollbar is inset
// to end above this strip, so nothing collides in the bottom-right corner.
className="bg-background border-t-border! end-0! z-40 h-4! rounded-none py-1"
/>
);
const defaultProps = {
'data-slot': 'gantt-view',
'data-scale': scale,
'aria-busy': loading || undefined,
className: cn('flex min-h-0 flex-1 flex-col overflow-hidden', viewConfig.classNames?.view, className),
children: (
<div ref={bodyRef} className="relative flex min-h-0 flex-1">
{/* Tree pane */}
<div
ref={treePaneRef}
data-slot="gantt-tree-pane"
className="relative h-full shrink-0"
style={{ width: liveTreeWidthRef.current ?? clampedTreeWidth }}
>
{customScrollbars ? (
// keyed by scale: Base UI measures overflow once per mount, and a
// scale switch changes content without resizing the viewport
<ScrollArea key={scale} className="h-full [&>[data-orientation=vertical]]:hidden">
<ScrollAreaPrimitive.Content>{treeContent}</ScrollAreaPrimitive.Content>
{horizontalScrollbar}
</ScrollArea>
) : (
<div
data-slot="scroll-area-viewport"
data-gantt-native-scroll=""
// vertical axis is DISPLAY-ONLY: the position is always
// mirrored from the timeline, so no vertical scrollbar can
// ever appear (overlay platforms included). Wheel deltas
// forward to the timeline (see the sync effect); horizontal
// column scrolling stays fully native.
className="h-full overflow-x-auto overflow-y-hidden overscroll-contain"
>
{treeContent}
</div>
)}
{/* Reserved horizontal-scrollbar rail: the tree usually has no
horizontal overflow, so its real scrollbar never mounts and its
bottom edge would sit higher than the timeline's pinned strip.
This static rail fills that gutter (same 1rem height + top border)
so the bottom strip reads as one continuous band across both
panes; a real tree scrollbar (with columns) draws over it. */}
{customScrollbars && (
<div
aria-hidden
data-slot="gantt-tree-scrollbar-rail"
className="bg-background border-t-border pointer-events-none absolute inset-x-0 bottom-0 h-4 border-t"
/>
)}
{/* Reorder insertion indicator, pinned to the visible pane */}
{reorder && (
<div
data-slot="gantt-reorder-indicator"
data-invalid={!reorder.valid || undefined}
className="pointer-events-none absolute inset-x-0 flex items-center"
style={{ top: reorder.top - 4, zIndex: 110 }}
>
{/* caret head pointing along the insertion line; the whole
indicator sits above the row carry overlay (z 100) */}
<span
className={cn(
'ms-0.5 size-0 shrink-0 border-y-4 border-s-8 border-y-transparent',
reorder.valid ? 'border-s-primary' : 'border-s-destructive',
)}
/>
<span className={cn('h-px min-w-0 flex-1', reorder.valid ? 'bg-primary' : 'bg-destructive')} />
</div>
)}
</div>
{/* Splitter */}
{treeConfig.resizable ? (
<div
role="separator"
aria-orientation="vertical"
aria-label={settings.i18n.labels.resizePanel}
aria-valuenow={Math.round(clampedTreeWidth)}
// the EFFECTIVE floor, not the configured one: on a narrow
// container the tree yields below its own minWidth to keep the
// timeline usable, and valuenow must never fall outside the range
aria-valuemin={Math.round(Math.min(treeConfig.minWidth, clampedTreeWidth))}
aria-valuemax={Math.round(Math.max(treeConfig.maxWidth, clampedTreeWidth))}
tabIndex={0}
data-slot="gantt-splitter"
className={cn(
'group/gantt-splitter bg-border hover:bg-primary/60 data-resizing:bg-primary relative z-30 w-px shrink-0 cursor-col-resize touch-none outline-none',
'focus-visible:ring-ring/50 focus-visible:ring-2',
'after:absolute after:inset-y-0 after:-start-1 after:-end-1',
)}
onPointerDown={beginSplit}
onDoubleClick={() => {
setTreeWidth(treeConfig.width);
treeConfig.onWidthChange?.(treeConfig.width);
}}
onKeyDown={(e) => {
if (e.key === 'ArrowLeft' || e.key === 'ArrowRight') {
e.preventDefault();
const dir = getComputedStyle(e.currentTarget).direction === 'rtl' ? -1 : 1;
const delta = (e.key === 'ArrowLeft' ? -16 : 16) * dir;
const next = clampTree(clampedTreeWidth + delta);
setTreeWidth(next);
treeConfig.onWidthChange?.(next);
}
}}
>
{/* grip pill: makes the hairline read as draggable on approach */}
<span
aria-hidden
data-slot="gantt-splitter-grip"
className="bg-primary/60 group-data-resizing/gantt-splitter:bg-primary absolute top-1/2 left-1/2 h-6 w-0.75 -translate-x-1/2 -translate-y-1/2 rounded-full opacity-0 transition-opacity duration-150 group-hover/gantt-splitter:opacity-100 group-focus-visible/gantt-splitter:opacity-100 group-data-resizing/gantt-splitter:opacity-100"
/>
</div>
) : (
<div aria-hidden className="bg-border w-px shrink-0" />
)}
{/* Timeline pane */}
<div ref={timelinePaneRef} data-slot="gantt-timeline-pane" className="relative h-full min-w-0 flex-1">
{viewConfig.zoomControl && (
<div
data-slot="gantt-zoom"
/* --gantt-zoom-shift comes from the offscreen-chips measure
pass: the control glides inward while a chip occupies its
band, because the chips' position IS their meaning and this
corner spot is merely a habit */
className="bg-background absolute end-[calc(0.75rem+var(--gantt-zoom-shift,0px))] bottom-5 z-40 flex flex-col rounded-md border shadow-sm transition-[inset-inline-end] duration-200"
>
{/* aria-disabled instead of disabled: the not-allowed cursor
must still show at the zoom limits */}
<TooltipProvider delay={600} closeDelay={0} timeout={300}>
<Tooltip>
<TooltipTrigger
render={
<Button
variant="ghost"
size="icon-xs"
aria-label={settings.i18n.labels.zoomIn}
aria-disabled={!canZoomIn || undefined}
className="text-muted-foreground hover:text-foreground size-5! rounded-b-none aria-disabled:cursor-not-allowed aria-disabled:opacity-50 aria-disabled:hover:bg-transparent"
onClick={() => {
if (!canZoomIn) return;
// controlled zoom anchors via fineCenterRef when
// the parent adopts; a pre-set anchor would leak
// stale if the parent ignores the proposal
if (viewConfig.zoom === undefined) anchorZoomCenter();
setZoomValue(+(zoom + (zoomRange.step ?? 0.25)).toFixed(2));
}}
/>
}
>
<PlusIcon className="size-3" aria-hidden="true" />
</TooltipTrigger>
<TooltipContent side="left">{settings.i18n.labels.zoomIn}</TooltipContent>
</Tooltip>
<Tooltip>
<TooltipTrigger
render={
<Button
variant="ghost"
size="icon-xs"
aria-label={settings.i18n.labels.zoomOut}
aria-disabled={!canZoomOut || undefined}
className="text-muted-foreground hover:text-foreground size-5! rounded-t-none border-t aria-disabled:cursor-not-allowed aria-disabled:opacity-50 aria-disabled:hover:bg-transparent"
onClick={() => {
if (!canZoomOut) return;
if (viewConfig.zoom === undefined) anchorZoomCenter();
setZoomValue(+(zoom - (zoomRange.step ?? 0.25)).toFixed(2));
}}
/>
}
>
<MinusIcon className="size-3" aria-hidden="true" />
</TooltipTrigger>
<TooltipContent side="left">{settings.i18n.labels.zoomOut}</TooltipContent>
</Tooltip>
</TooltipProvider>
</div>
)}
{customScrollbars ? (
// The vertical scrollbar is inset into the body lane: it starts
// below the sticky 65px two-row header (otherwise its top slides
// behind the header and the thumb is clipped) and stops above the
// pinned 16px horizontal strip. `!` overrides Base UI's inline
// top/bottom; h-auto lets top+bottom define the track height so
// the thumb is measured against the visible lane, not the full pane.
<ScrollArea
key={scale}
className="h-full [&>[data-orientation=vertical]]:top-[65px]! [&>[data-orientation=vertical]]:bottom-4! [&>[data-orientation=vertical]]:h-auto!"
>
{/* A FLEX column, not a percentage: the content's own
min-h-full would resolve against this box's auto height and
collapse to nothing, which is why the columns used to stop at
the last row and leave the rest of the pane dead space. As a
flex parent it can hand the leftover height down instead. */}
<ScrollAreaPrimitive.Content className="flex min-h-full flex-col">{timelineContent}</ScrollAreaPrimitive.Content>
{horizontalScrollbar}
</ScrollArea>
) : (
<div data-slot="scroll-area-viewport" data-gantt-native-scroll="" className="h-full overflow-auto overscroll-contain">
{timelineContent}
</div>
)}
{/* Reserved scrollbar rail - the twin of the tree rail. Keeps the
bottom gutter present even when the real horizontal scrollbar is
hidden (e.g. hover-reveal scrollbars at rest), so the strip reads
as one continuous reserved band across both panes; the real
scrollbar (z-40) draws over it when active. */}
{customScrollbars && (
<div
aria-hidden
data-slot="gantt-timeline-scrollbar-rail"
className="bg-background border-t-border pointer-events-none absolute inset-x-0 bottom-0 h-4 border-t"
/>
)}
{viewConfig.offscreenIndicators && (
<GanttOffscreenChips
paneRef={timelinePaneRef}
occurrences={occurrences}
locale={settings.locale}
refreshKey={`${scale}:${rangeKey}:${zoom}:${rows.length}:${clampedTreeWidth}:${viewConfig.scrollbars}`}
/>
)}
</div>
{loading && (
<div data-slot="gantt-loading" className="bg-background/60 absolute inset-0 z-50 flex items-center justify-center">
<span className="text-muted-foreground animate-pulse text-sm">{settings.i18n.labels.loading}</span>
</div>
)}
{(viewConfig.renderDragPreview || viewConfig.renderResizeIndicator) && <GanttCustomDragLayer />}
</div>
),
};
return useRender({
defaultTagName: 'div',
render,
props: mergeProps<'div'>(defaultProps, props),
});
}
/**
* The red now-line, self-ticking: only this component re-renders on the 30s
* clock, never the grid around it. z-10 keeps it above row content but UNDER
* the sticky header (z-30) - vertical scrolling slides it beneath, never over.
*/
function GanttNowLine({ rangeStartMs, rangeEndMs }: { rangeStartMs: number; rangeEndMs: number }) {
const now = useNow();
const ms = now.getTime();
if (ms < rangeStartMs || ms >= rangeEndMs) return null;
const fraction = (ms - rangeStartMs) / (rangeEndMs - rangeStartMs);
return (
<div
data-slot="gantt-now-indicator"
// comet tail: solid at the cap, dissolving toward the bottom -
// present without ruling a hard line through every row
className="from-destructive/80 via-destructive/45 to-destructive/15 absolute inset-y-0 z-10 w-px bg-linear-to-b"
style={{ insetInlineStart: `${fraction * 100}%` }}
/>
);
}
/**
* The now-line's dot cap, pinned INSIDE the sticky header at the header/body
* boundary: it stays put while the line scrolls beneath the header.
*/
function GanttNowDot({ rangeStartMs, rangeEndMs }: { rangeStartMs: number; rangeEndMs: number }) {
const now = useNow();
const ms = now.getTime();
if (ms < rangeStartMs || ms >= rangeEndMs) return null;
const fraction = (ms - rangeStartMs) / (rangeEndMs - rangeStartMs);
return (
<span
aria-hidden
data-slot="gantt-now-dot"
className="bg-destructive absolute -bottom-0.75 z-10 size-1.5 -translate-x-1/2 rounded-full"
style={{ insetInlineStart: `${fraction * 100}%` }}
/>
);
}
/**
* Consumer-owned drag/resize indicators (renderDragPreview /
* renderResizeIndicator): content is React and re-renders per snap step from
* drag state; the dnd engine adopts this wrapper and writes its
* cursor-tracking transform imperatively, flipping visibility on the first
* positioned frame so nothing flashes at the viewport origin.
*/
function GanttCustomDragLayer() {
const viewConfig = useGanttViewConfig();
const drag = useGanttSelector((state) => state.drag);
if (!drag) return null;
const render = drag.kind === 'move' ? viewConfig.renderDragPreview : viewConfig.renderResizeIndicator;
if (!render) return null;
return (
<div
data-slot={drag.kind === 'move' ? 'gantt-drag-overlay' : 'gantt-resize-indicator'}
data-custom=""
// physical left-0 anchor: positioned by the engine's translate3d from
// raw clientX (physical); a logical start-0 would break in RTL
className="pointer-events-none fixed top-0 left-0 z-100 will-change-transform"
style={{ visibility: 'hidden' }}
>
{render({
occurrence: drag.occurrence,
kind: drag.kind,
start: drag.proposedStart,
end: drag.proposedEnd,
valid: drag.valid,
// the plan rides along so a custom overlay can keep drawing it
// mid-gesture (the resting ghost is hidden with the original bar)
baseline: resolveEventBaseline(drag.occurrence.event),
})}
</div>
);
}
/**
* The dependency-arrow overlay: one SVG whose user unit is 1rem at the
* track's natural width (the viewBox mirrors it), stretched to w-full so its
* mapping tracks the bars' percentage positions when the zoomed track is
* narrower than the pane. While a gesture is in flight the dragged event's
* own endpoints re-derive from the proposed range and its edges go dashed -
* the arrows point at the drop indicator's landing, never at stale data.
* A component of its own so the per-snap drag subscription re-renders a few
* paths instead of the whole view.
*/
const GanttDependencyLayer = memo(function GanttDependencyLayer({
edges,
totalRem,
trackRemWidth,
rangeStartMs,
rangeEndMs,
laneHeightRem,
laneGapRem,
}: {
edges: DependencyEdge[];
totalRem: number;
trackRemWidth: number;
rangeStartMs: number;
rangeEndMs: number;
laneHeightRem: number;
laneGapRem: number;
}) {
const viewConfig = useGanttViewConfig();
// one snapshot per SNAP STEP (the engine already gates setDrag on those);
// value-equal at rest, so resting renders never repeat
const dragLink = useGanttSelector<unknown, { eventId: string; startMs: number; endMs: number } | null>(
(state) =>
state.drag
? {
eventId: state.drag.occurrence.eventId,
startMs: state.drag.proposedStart.getTime(),
endMs: state.drag.proposedEnd.getTime(),
}
: null,
{
isEqual: (a, b) => a === b || (a !== null && b !== null && a.eventId === b.eventId && a.startMs === b.startMs && a.endMs === b.endMs),
},
);
const totalMin = (rangeEndMs - rangeStartMs) / 60000;
// clamped exactly like segment minutes, so a live anchor can never leave
// the coordinate space the resting anchors were computed in
const liveX = (ms: number) => (Math.min(Math.max((ms - rangeStartMs) / 60000, 0), totalMin) / totalMin) * trackRemWidth;
return (
<svg
aria-hidden
data-slot="gantt-dependencies"
// w-full, NOT the track's rem width: rows fill the pane when the
// zoomed track is narrower (min-w-full), and bars position as a
// percentage of that STRETCHED box - so the viewBox mapping must
// stretch with them or every arrow drifts off its bar. The
// non-uniform scale is neutralized on strokes below; arrowheads
// lengthen slightly with the fill, which tracks the bars.
className={cn(
'text-muted-foreground/70 pointer-events-none absolute start-0 top-0 w-full overflow-visible rtl:-scale-x-100',
viewConfig.classNames?.dependencies,
)}
style={{ height: `${totalRem}rem` }}
viewBox={`0 0 ${trackRemWidth} ${totalRem}`}
preserveAspectRatio="none"
>
{edges.map((edge) => {
// y never moves: a gesture stays on its own row and lane
const dragged = dragLink !== null && (edge.fromId === dragLink.eventId || edge.toId === dragLink.eventId);
const fromX = dragged && edge.fromId === dragLink.eventId ? liveX(dragLink.endMs) : edge.fromX;
const toX = dragged && edge.toId === dragLink.eventId ? liveX(dragLink.startMs) : edge.toX;
const geometry = buildDependencyPath(
{ x: fromX, y: edge.fromY },
{ x: toX, y: edge.toY },
{
clearance: 0.625,
// the loop route hops just past the lane edge
laneStep: laneHeightRem / 2 + laneGapRem,
arrowSize: 0.375,
},
);
return (
<g
key={edge.key}
data-slot="gantt-dependency"
data-dragging={dragged || undefined}
// in-flight edges stay SOLID - they still describe a real link -
// and drop to a lower tone, arrowhead included, while the
// endpoint is provisional
className={dragged ? 'opacity-50' : undefined}
>
<path
d={geometry.line}
fill="none"
stroke="currentColor"
// screen-space px via non-scaling-stroke, matching the
// view's 1px gridlines; a viewBox-unit width would fatten
// vertical runs whenever the track stretches
strokeWidth={1.5}
vectorEffect="non-scaling-stroke"
/>
<path d={geometry.arrow} fill="currentColor" />
</g>
);
})}
</svg>
);
});
/** Memoized: only rows whose props actually changed re-render. */
const GanttTreeRow = memo(function GanttTreeRow({
row,
heightRem,
bandRem,
columns,
nameWidth,
dimmed,
selected,
onSelectedChange,
onGripPointerDown,
onToggle,
}: {
row: TimelineRow;
heightRem: number;
bandRem: number;
columns: GanttColumn[];
nameWidth: number;
dimmed: boolean;
selected: boolean;
onSelectedChange?: (id: string, checked: boolean) => void;
onGripPointerDown?: (e: React.PointerEvent, row: TimelineRow) => void;
onToggle: (row: TimelineRow) => void;
}) {
const settings = useGanttSettings();
const viewConfig = useGanttViewConfig();
const ctx = {
resource: row.resource,
depth: row.depth,
isGroup: row.isGroup,
collapsed: row.collapsed,
};
// consumer-owned right-click menu, same contract as the bar menu
const menu = viewConfig.renderResourceMenu?.(ctx);
// A node with several schedules grows its row; "start" keeps the label and
// its columns on the FIRST schedule's baseline instead of floating them to
// the middle of a tall row. Every cell's inner box is minRowHeight tall, so
// a single-lane row renders identically either way.
const alignStart = (viewConfig.rowAlign ?? DEFAULT_ROW_ALIGN) === 'start';
const rowNode = (
<div
data-slot="gantt-row-group"
data-gantt-row-id={row.resource.id}
data-selected={selected || undefined}
className={cn(
'group/gantt-row data-hover:bg-muted/40 data-selected:bg-primary/5 data-selected:data-hover:bg-primary/5 flex border-b',
dimmed && 'opacity-50',
)}
style={{ height: `${heightRem}rem` }}
onClick={
settings.onResourceClick
? (e: React.MouseEvent) => {
// chrome clicks (chevron, checkbox, grip) are their own actions
if ((e.target as HTMLElement).closest('button, [role=checkbox]')) return;
settings.onResourceClick?.(ctx, e);
}
: undefined
}
onDoubleClick={
settings.onResourceDoubleClick
? (e: React.MouseEvent) => {
if ((e.target as HTMLElement).closest('button, [role=checkbox]')) return;
settings.onResourceDoubleClick?.(ctx, e);
}
: undefined
}
>
<div className="flex h-full w-full min-w-0">
{/* In-flow name cell: the whole tree row scrolls horizontally as one;
row-level hover/selected tints show through the transparent cell */}
<div
data-slot="gantt-tree-cell"
className={cn(
// ps-3 keeps the row toggles off the left edge (kept in sync with
// namePaddingStart above so headers stay aligned with row titles)
'flex shrink-0 ps-3 pe-3',
alignStart ? 'items-start' : 'items-center',
row.isGroup && 'font-medium',
)}
style={{ width: nameWidth }}
>
{/* exactly the band the first schedule occupies: same height, both
top-anchored, so the label and that schedule share a centerline */}
<div className="flex w-full min-w-0 items-center" style={{ height: `${bandRem}rem` }}>
{onGripPointerDown && (
<button
type="button"
data-slot="gantt-row-grip"
aria-label={settings.i18n.labels.reorder}
// pointer-coarse keeps the grip visible on touch (no hover there).
// -ms-1.5/me-1.5 nudge the grip toward the row edge and open a
// gap before the checkbox so it's easy to grab without catching
// the checkbox; the equal start/end margins keep the grip's
// footprint net-zero, so the title stays aligned with the header.
className="text-muted-foreground/60 hover:text-foreground -ms-1.5 me-1.5 flex w-3.5 shrink-0 cursor-grab touch-none items-center justify-center opacity-0 group-hover/gantt-row:opacity-100 group-data-hover/gantt-row:opacity-100 focus-visible:opacity-100 pointer-coarse:opacity-100"
onPointerDown={(e) => onGripPointerDown(e, row)}
onClick={(e) => e.stopPropagation()}
>
<GripVerticalIcon className="size-3" aria-hidden="true" />
</button>
)}
{/* per-level indent keeps sibling titles on one x */}
<span aria-hidden className="shrink-0" style={{ width: `${row.depth * 0.875}rem` }} />
{/* fixed gutter: groups toggle here, leaves carry the checkbox -
titles of one level share the same x either way */}
<span className="me-1 flex w-5 shrink-0 items-center justify-start">
{row.isGroup ? (
<Button
variant="ghost"
size="icon-xs"
aria-expanded={!row.collapsed}
aria-label={row.resource.title}
className={cn(
'size-5! aria-expanded:bg-transparent!',
row.collapsed ? 'text-foreground' : 'text-muted-foreground aria-expanded:text-muted-foreground! hover:text-foreground!',
)}
onClick={() => onToggle(row)}
>
<ChevronRightIcon className={cn('size-3.5 transition-transform', !row.collapsed && 'rotate-90')} aria-hidden="true" />
</Button>
) : (
viewConfig.rowCheckboxes &&
onSelectedChange && (
<Checkbox
data-slot="gantt-row-checkbox"
checked={selected}
onCheckedChange={(checked: boolean) => onSelectedChange(row.resource.id, checked)}
aria-label={row.resource.title}
className={cn(
'size-3.5 opacity-0 transition-opacity group-hover/gantt-row:opacity-100 group-data-hover/gantt-row:opacity-100 focus-visible:opacity-100',
selected && 'opacity-100',
)}
/>
)
)}
</span>
{viewConfig.renderResourceLabel?.(ctx) ?? <span className="truncate">{row.resource.title}</span>}
</div>
</div>
{columns.map((column) => (
<div
key={column.id}
data-slot="gantt-tree-column-cell"
data-column={column.id}
className={cn('flex shrink-0 px-2', alignStart ? 'items-start' : 'items-center', column.className)}
style={{ width: column.width ?? DEFAULT_COLUMN_WIDTH }}
>
<div
className={cn(
'flex w-full min-w-0 items-center',
column.align === 'center' && 'justify-center',
column.align === 'end' && 'justify-end',
)}
style={{ height: `${bandRem}rem` }}
>
{column.render?.(ctx)}
</div>
</div>
))}
<div className="min-w-0 flex-1" />
</div>
</div>
);
if (!menu) return rowNode;
return (
<ContextMenu>
<ContextMenuTrigger render={rowNode} />
<ContextMenuContent data-slot="gantt-resource-menu" className="min-w-44">
{menu}
</ContextMenuContent>
</ContextMenu>
);
});
const GanttTimelineRow = memo(function GanttTimelineRow({
row,
rowIndex,
bars,
rangeStartMs,
rangeEndMs,
trackWidth,
trackRemWidth,
rowBorder,
selected,
resolveHintStop,
isPanning,
laneHeightRem,
laneGapRem,
minRowRem,
ghostHeightRem,
dependencySourceIds,
}: {
row: TimelineRow;
rowIndex: number;
bars: TimelineRowBars | undefined;
rangeStartMs: number;
rangeEndMs: number;
trackWidth: string;
trackRemWidth: number;
rowBorder: 'solid' | 'dashed' | null;
selected: boolean;
resolveHintStop: (fraction: number) => { index: number; center: number; ms: number; endMs: number } | null;
isPanning: boolean;
laneHeightRem: number;
laneGapRem: number;
minRowRem: number;
ghostHeightRem: number;
dependencySourceIds: ReadonlySet<string>;
}) {
const instance = useGantt();
const settings = useGanttSettings();
const viewConfig = useGanttViewConfig();
const gestures = useGanttGestures();
const segments = bars?.segments ?? [];
// parents aggregate their subtree; they take no direct scheduling gestures
const schedulable = !row.isGroup || viewConfig.parentScheduling;
const heightRem = bars?.heightRem ?? minRowRem;
const laneCount = bars?.laneCount ?? 1;
const singleTrack = resolveScheduleMode(row.resource, viewConfig.scheduleMode) === 'single';
// shared with the tree pane so the two can never drift apart
const laneOffsetRem = bars?.laneOffsetRem ?? (minRowRem - laneHeightRem) / 2;
// Hover affordance over empty track space: the ghost tile snaps to the
// unit under the cursor, so the (real) tooltip re-anchors per unit
const [hintStop, setHintStop] = useState<{
index: number;
center: number;
ms: number;
endMs: number;
} | null>(null);
// Gated on an active hint: rows without one read a stable false, so a
// gesture starting/ending anywhere doesn't re-render every row.
const hintSuppressed = useGanttSelector<unknown, boolean>((state) => hintStop !== null && (state.drag !== null || state.slotDraft !== null));
const canSchedule = useGanttSelector<unknown, boolean>((state) => state.interactions.selectSlot);
// The affordance is offered ANYWHERE on a schedulable row - over bare track
// and over existing bars alike - because a row can always take another
// schedule on a free lane. The primitive deliberately owns NO opinion about
// what may land where: that is `canSelectSlot`, the consumer's call. (It
// used to withhold the hint on a one-track row that already held a
// schedule, which also blocked adding a second NON-overlapping one.)
// The lowest track FREE at the hovered time. Two jobs, kept separate on
// purpose:
// - VISIBILITY: `hintFreeLane < laneCount` is what proves an empty track
// actually exists to draw on. It is computed regardless of mode, because
// a "single" row whose only track is booked has nowhere free either, and
// pinning the placement to 0 there would put the ring straight on the bar.
// - PLACEMENT: "single" packs everything onto track 0, so that is where its
// ring belongs; otherwise the ring sits on the track the schedule will
// actually land on. Lane is a function of TIME only, so moving the pointer
// down onto the ring never moves it away from you.
const hintFreeLane = hintStop ? lowestFreeLane(segments, hintStop.ms, hintStop.endMs) : 0;
const hintLane = bars?.scheduleMode === 'single' ? 0 : hintFreeLane;
const hintTopRem = Math.min(
laneTopRem(laneOffsetRem, hintLane, laneHeightRem, laneGapRem) + laneHeightRem / 2,
Math.max(heightRem - laneHeightRem / 2, laneHeightRem / 2),
);
// Single source of truth for "the add affordance is live at this spot". The
// ring renders on it AND the row takes its cursor from it, so the pointer can
// never promise something the ring is not offering.
const hintVisible = hintStop !== null && hintFreeLane < laneCount && !hintSuppressed && !isPanning;
// name the gesture that is actually wired, not a generic one
const hintLabel = viewConfig.dragCreate ? settings.i18n.labels.scheduleHintDrag : settings.i18n.labels.scheduleHint;
const showHint = viewConfig.displayScheduleHint && schedulable && canSchedule && !isPanning && !!(settings.onSelectSlot || settings.onSlotClick);
const fractionOf = (ms: number) => Math.min(Math.max((ms - rangeStartMs) / (rangeEndMs - rangeStartMs), 0), 1);
const dragTarget = useGanttSelector<unknown, 'valid' | 'invalid' | null>((state) => {
const drag = state.drag;
if (!drag || drag.proposedResourceId !== row.resource.id) return null;
return drag.valid ? 'valid' : 'invalid';
});
const ghost = useGanttSelector<
unknown,
{
from: number;
to: number;
color?: string;
valid: boolean;
title: string;
kind: string;
occurrenceKey: string;
milestone: boolean;
} | null
>(
(state) => {
const drag = state.drag;
if (!drag || drag.proposedResourceId !== row.resource.id) return null;
return {
from: fractionOf(drag.proposedStart.getTime()),
to: fractionOf(drag.proposedEnd.getTime()),
color: drag.occurrence.event.color,
valid: drag.valid,
title: drag.occurrence.event.title,
kind: drag.kind,
occurrenceKey: drag.occurrence.key,
// real zero duration, not from==to: clamped fractions also coincide
// for a bar dragged clear past a range edge
milestone: drag.proposedEnd.getTime() === drag.proposedStart.getTime(),
};
},
{
isEqual: (a, b) => a === b || (a !== null && b !== null && a.from === b.from && a.to === b.to && a.valid === b.valid),
},
);
const draft = useGanttSelector<
unknown,
{
from: number;
to: number;
startMs: number;
endMs: number;
} | null
>(
(state) => {
const slotDraft = state.slotDraft;
if (!slotDraft || slotDraft.resourceId !== row.resource.id) return null;
const startMs = slotDraft.start.getTime();
const endMs = slotDraft.end.getTime();
return {
from: fractionOf(startMs),
to: fractionOf(endMs),
startMs,
endMs,
};
},
{
// from/to as well as the instants: they are derived through fractionOf,
// which closes over the range. An extendRange mid-gesture moves every
// bar while an instants-only compare serves the cached (stale) fractions,
// leaving the placeholder pinned to where the range used to be.
isEqual: (a, b) =>
a === b || (a !== null && b !== null && a.startMs === b.startMs && a.endMs === b.endMs && a.from === b.from && a.to === b.to),
},
);
/**
* Where the schedule being painted will land - resolved in the shared layout
* memo, which also RESERVES that track, so the row has already grown to hold
* it. The clamp is only a backstop for the frame between a draft appearing
* and the layout catching up.
*/
const draftLane = bars?.draftLane ?? 0;
const draftTopRem = Math.min(laneTopRem(laneOffsetRem, draftLane, laneHeightRem, laneGapRem), Math.max(heightRem - laneHeightRem, 0));
// the range you are painting, named while you paint it - a drag that shows
// no times asks you to guess where you let go
const draftLabel = draft
? settings.i18n.functions.formatEventTime(
toZoned(new Date(draft.startMs), settings.timeZone),
toZoned(new Date(draft.endMs), settings.timeZone),
false,
settings.locale,
)
: '';
/**
* The row's create contract, in one place: onSlotClick if the consumer
* wired it, else a ready-made slot draft. Both the hint tile and a plain
* click on bare track go through this, so clicking anywhere placeable
* behaves the same as clicking the tile.
*/
const createAt = (stop: { ms: number; endMs: number }, e: React.MouseEvent) => {
if (settings.onSlotClick) {
settings.onSlotClick({ date: new Date(stop.ms), allDay: false, resourceId: row.resource.id }, e);
} else {
settings.onSelectSlot?.({
start: new Date(stop.ms),
end: new Date(Math.max(stop.endMs, stop.ms + 1)),
allDay: false,
resourceId: row.resource.id,
});
}
};
// The drop indicator belongs on the lane the dragged schedule actually
// occupies. The gesture has not committed, so the segment is still packed
// under its pre-drag key - no second packing pass, just a lookup.
const ghostLane = ghost ? (segments.find((segment) => segment.occurrence.key === ghost.occurrenceKey)?.column ?? 0) : 0;
const ghostLaneOffsetRem = laneTopRem(laneOffsetRem, ghostLane, laneHeightRem, laneGapRem) + (laneHeightRem - ghostHeightRem) / 2;
return (
<div
data-gantt-row=""
data-gantt-resource={row.resource.id}
data-gantt-row-id={row.resource.id}
data-gantt-row-static={!schedulable || undefined}
data-gantt-bar-min={bars?.extent?.from}
data-gantt-bar-max={bars?.extent?.to}
data-gantt-bar-color={bars?.extent?.color}
data-gantt-bar-label={bars?.extent?.label}
data-gantt-bar-start-ms={bars?.extent?.startMs}
data-drop-target={dragTarget ?? undefined}
data-selected={selected || undefined}
className={cn(
'data-hover:bg-muted/30 data-selected:bg-primary/5 data-selected:data-hover:bg-primary/5 relative w-full min-w-0',
// The ring is pointer-events-none, so a cursor set on IT can never be
// reached - the row is the element actually under the pointer, so the
// cursor belongs here. Gated on the same flag as the ring: wherever the
// add affordance shows, the pointer says "add", and nowhere else.
hintVisible && 'cursor-crosshair',
// horizontal separators mirror the tree node borders across panes.
// No special case for the last row: the columns run the full height of
// the pane, so the grid closes on the container edge on its own.
rowBorder !== null && 'border-b',
rowBorder === 'dashed' && 'border-dashed',
dragTarget === 'valid' && 'bg-muted/40',
dragTarget === 'invalid' && 'bg-destructive/10',
)}
style={{
height: `${heightRem}rem`,
minWidth: trackWidth,
}}
onPointerDown={(e) => {
// Opt-in drag-create owns presses on empty schedulable track (the
// onSelectSlot contract); otherwise the press bubbles to the
// container and pans the timeline.
if (
viewConfig.dragCreate &&
e.button === 0 &&
schedulable &&
canSchedule &&
// the bare track, or the hint tile that spawns under the cursor -
// a sub-threshold press still ends as the tile's own click
(e.target === e.currentTarget || !!(e.target as HTMLElement).closest?.('[data-slot=gantt-schedule-hint]')) &&
!!settings.onSelectSlot
) {
// validate BEFORE claiming the press: on a vetoed slot (e.g. the
// one-schedule-per-task rule) the press falls through to the pan
const stop = resolveHintStop(trackFraction(e.currentTarget, e.clientX));
const allowed =
stop !== null &&
(settings.canSelectSlot?.({
start: new Date(stop.ms),
end: new Date(Math.max(stop.endMs, stop.ms + 1)),
allDay: false,
resourceId: row.resource.id,
}) ??
true);
if (!allowed) return;
e.stopPropagation();
gestures.beginCreate(e);
}
}}
onPointerMove={(e) => {
// read interaction state imperatively - a subscription here would
// re-render the row for every gesture anywhere on the grid
const interacting = instance.getState().drag !== null || instance.getState().slotDraft !== null;
if (!showHint || e.pointerType !== 'mouse' || interacting) {
if (hintStop) setHintStop(null);
return;
}
// EMPTY TRACK ONLY. A bar under the pointer means the pointer is not
// on an empty slot, so the affordance goes away entirely rather than
// hovering over booked time - and the bar is left completely alone,
// hover and click both. (No "pointer is over the tile" bail: the ring
// is pointer-events-none, so it is never the target; a bail on it would
// freeze it on the spot, since it rides under the cursor.)
if (e.target !== e.currentTarget) {
if (hintStop) setHintStop(null);
return;
}
const { fraction, offset } = trackPoint(e.currentTarget, e.clientX);
// The dot follows the pointer FREELY - it is a cursor, not a cell, so
// it is never quantised to the interval grid. Its position is written
// as a CSS custom property straight onto the row: the cursor moves
// every frame and a state update per frame would re-render the row and
// every bar in it. React state still owns WHICH slot is offered, and
// that changes only once per interval.
//
// In pixels rather than a percentage, pre-snapped by trackPoint to the
// viewport pixel grid: a fractional inset makes the browser antialias
// the ring and the glyph across two device pixels, which reads as a
// furry, smudged dot. -translate-x-1/2 of an even-sized box keeps it on
// the grid, so the result is crisp.
e.currentTarget.style.setProperty('--gantt-hint-x', `${offset}px`);
const stop = resolveHintStop(fraction);
// validate placement before offering it: a consumer canSelectSlot
// veto (e.g. a locked span) hides the hint entirely
const allowed =
stop !== null &&
(settings.canSelectSlot?.({
start: new Date(stop.ms),
end: new Date(Math.max(stop.endMs, stop.ms + 1)),
allDay: false,
resourceId: row.resource.id,
}) ??
true);
const next = allowed ? stop : null;
// state changes only when the cursor crosses into another unit
if (next?.index !== hintStop?.index) setHintStop(next);
}}
onPointerLeave={() => {
if (hintStop) setHintStop(null);
}}
onClick={(e) => {
// With dragCreate the press belongs to the create GESTURE, which only
// activates past its movement threshold - so a click that never moved
// committed nothing and the row felt dead. Treat it as a create at the
// hovered slot, using the same validation the hint tile uses.
if (!viewConfig.dragCreate || e.target !== e.currentTarget) return;
if (!schedulable || !canSchedule) return;
if (wasRecentDrag()) return;
if (!settings.onSlotClick && !settings.onSelectSlot) return;
const stop = resolveHintStop(trackFraction(e.currentTarget, e.clientX));
if (!stop) return;
const allowed =
settings.canSelectSlot?.({
start: new Date(stop.ms),
end: new Date(Math.max(stop.endMs, stop.ms + 1)),
allDay: false,
resourceId: row.resource.id,
}) ?? true;
if (!allowed) return;
createAt(stop, e);
setHintStop(null);
}}
>
{/* row CONTENT (bars, labels, ghosts). Pointer-transparent so
empty-track presses still hit the row itself.
content-visibility lets the browser skip rendering this layer for
rows scrolled out of view (large trees stay cheap on low-end
devices). Safe here: the layer is absolute inset-0 (geometry comes
from the row, never from content), its paint containment keeps it
a stacking context, and nothing inside escapes the row box - the
schedule hint deliberately lives OUTSIDE this layer. Browsers
without support simply ignore it. */}
<div className="pointer-events-none absolute inset-0" style={{ contentVisibility: 'auto' }}>
{/* The node's own planned window: a band behind ALL of its lanes,
first in the layer so even the per-event ghosts paint over it. */}
{bars?.rowBaseline &&
(() => {
const plan = bars.rowBaseline;
const from = fractionOf(rangeStartMs + plan.startMin * 60000);
const to = fractionOf(rangeStartMs + plan.endMin * 60000);
const bandRemHeight = laneBlockRem(laneCount, laneHeightRem, laneGapRem);
const content = viewConfig.renderRowBaseline?.({
resource: row.resource,
start: plan.baseline.start,
end: plan.baseline.end,
milestone: plan.baseline.milestone,
variance: plan.variance,
});
return (
<div
data-slot="gantt-row-baseline"
data-milestone={plan.baseline.milestone || undefined}
data-variance={plan.variance ?? undefined}
aria-hidden
className={cn('absolute', plan.baseline.milestone ? 'flex items-center justify-center' : 'px-px', viewConfig.classNames?.baseline)}
style={
{
'--gantt-event-color': row.resource.color ?? 'var(--color-primary)',
insetInlineStart: plan.baseline.milestone
? `clamp(0rem, ${from * 100}% - ${laneHeightRem / 2}rem, 100% - ${laneHeightRem}rem)`
: `${from * 100}%`,
width: plan.baseline.milestone ? `${laneHeightRem}rem` : `${Math.max((to - from) * 100, 0.5)}%`,
top: `${laneOffsetRem}rem`,
height: `${bandRemHeight}rem`,
} as CSSProperties
}
>
{content ??
(plan.baseline.milestone ? (
// hollow diamond marking the node's planned instant
<span className="size-2.5 rotate-45 rounded-[2px] border border-(--gantt-event-color)/60 bg-(--gantt-event-color)/15" />
) : (
// fainter than a per-event ghost: a whole-row context
// band must never compete with the bars on it
<span className="relative block h-full w-full rounded-sm border border-(--gantt-event-color)/25 bg-(--gantt-event-color)/6" />
))}
</div>
);
})()}
{/* Baseline ghosts BEFORE the bars, with no z-index: DOM order keeps
them painting under every bar (z 10+), and the layer's pointer
transparency means they can never catch a press or a drop. */}
{bars?.baselines.map((plan) => {
const from = fractionOf(rangeStartMs + plan.startMin * 60000);
const to = fractionOf(rangeStartMs + plan.endMin * 60000);
const content = viewConfig.renderBaseline?.({
event: plan.event,
start: plan.baseline.start,
end: plan.baseline.end,
milestone: plan.baseline.milestone,
variance: plan.variance,
});
return (
<div
key={`baseline-${plan.event.id}`}
data-slot="gantt-baseline"
data-milestone={plan.baseline.milestone || undefined}
data-variance={plan.variance}
aria-hidden
// a milestone is a POINT: the wrapper centers on the instant
// (flex centering, so RTL needs no translate gymnastics), while
// a window mirrors the bar wrapper's px-px breathing room
className={cn('absolute', plan.baseline.milestone ? 'flex items-center justify-center' : 'px-px', viewConfig.classNames?.baseline)}
style={
{
'--gantt-event-color': plan.event.color ?? 'var(--color-primary)',
/* clamped into the row box: the layer's paint containment
slices anything that overhangs it, which would cut an
edge milestone's diamond in half - so it nudges inward
instead, at most half a lane off its instant */
insetInlineStart: plan.baseline.milestone
? `clamp(0rem, ${from * 100}% - ${laneHeightRem / 2}rem, 100% - ${laneHeightRem}rem)`
: `${from * 100}%`,
width: plan.baseline.milestone ? `${laneHeightRem}rem` : `${Math.max((to - from) * 100, 0.5)}%`,
top: `${laneTopRem(laneOffsetRem, plan.lane, laneHeightRem, laneGapRem)}rem`,
height: `${laneHeightRem}rem`,
} as CSSProperties
}
>
{content ??
(plan.baseline.milestone ? (
// hollow diamond marking the planned instant
<span className="size-2 rotate-45 rounded-[2px] border border-(--gantt-event-color)/60 bg-(--gantt-event-color)/15" />
) : (
// block child (not inset-0) so the px-px padding holds and
// the outline lands exactly on the bar's own box
<span className="relative block h-full w-full rounded-sm border border-(--gantt-event-color)/40 bg-(--gantt-event-color)/10" />
))}
</div>
);
})}
{segments.map((segment, segmentIndex) => {
const from = fractionOf(rangeStartMs + (segment.startMin ?? 0) * 60000);
const to = fractionOf(rangeStartMs + (segment.endMin ?? 0) * 60000);
// Zero duration = an actual MILESTONE: it renders as a diamond
// centered on its instant instead of a zero-width (invisible) bar.
const milestone = segment.occurrence.end.getTime() === segment.occurrence.start.getTime();
if (to <= from && !milestone) return null;
const lane = segment.column ?? 0;
// Title placement: outside beside the bar when configured (or too
// short in "auto"), flipped before the bar near the range end, and
// back inside when the bar spans the whole view. A milestone has
// no room inside its diamond, so its title is always outside.
const barRemWidth = milestone ? laneHeightRem : (to - from) * trackRemWidth;
const wantsOutside =
milestone ||
viewConfig.barLabel === 'outside' ||
(viewConfig.barLabel === 'auto' && barRemWidth < (viewConfig.metrics?.autoLabelMin ?? AUTO_LABEL_MIN_REM));
const placement = !wantsOutside ? 'inside' : to <= 0.92 ? 'after' : from >= 0.08 ? 'before' : 'inside';
// the wrapper carries the drag kind itself (from the row's ghost
// state, same notify as the bar's own attribute) so the hide rules
// below use plain attribute selectors instead of :has(), which
// older Firefox (<121) does not support
const segDragKind = ghost && ghost.occurrenceKey === segment.occurrence.key ? ghost.kind : undefined;
return (
<div
key={segment.occurrence.key}
data-drag-kind={segDragKind}
data-milestone={milestone || undefined}
// lane position is headless state: a consumer can read it to
// label the bar ("2 of 4") or drive its own manage UI
data-lane={lane}
data-lane-count={laneCount}
// during a MOVE the whole thing (bar + its outside label) hides so
// the smooth clone carries both; resize keeps the BAR as a faint
// placeholder but its label yields to the ghost's outside label.
// pointer-events-auto: the parent mask layer is pointer-
// transparent so empty-track presses reach the row.
// px-px keeps back-to-back bars off each other; the vertical
// breathing room is the lane gap itself, not padding here, so
// the bar is exactly laneHeight tall
className="group/gantt-seg pointer-events-auto absolute px-px data-[drag-kind=move]:opacity-0"
// insetInlineStart, not left: in RTL the axis mirrors and bars
// must mirror with it (fractions measure from the range start)
style={{
/* a milestone wrapper is a lane-height square centered on the
instant, clamped into the row box exactly like the planned
milestone diamond */
insetInlineStart: milestone ? `clamp(0rem, ${from * 100}% - ${laneHeightRem / 2}rem, 100% - ${laneHeightRem}rem)` : `${from * 100}%`,
width: milestone ? `${laneHeightRem}rem` : `${Math.max((to - from) * 100, 0.5)}%`,
top: `${laneTopRem(laneOffsetRem, lane, laneHeightRem, laneGapRem)}rem`,
height: `${laneHeightRem}rem`,
// one track means every lane is 0, so paint order (not the
// lane) is what keeps overlapping bars individually reachable
zIndex: segment.occurrence.event.zIndex ?? 10 + (singleTrack ? segmentIndex : lane),
}}
>
<GanttBar segment={segment} labelOutside={placement !== 'inside'} rowTitle={row.resource.title} className="h-full" />
{placement !== 'inside' && (
<span
data-slot="gantt-bar-label"
data-placement={placement}
className={cn(
'text-foreground pointer-events-none absolute top-1/2 z-10 max-w-60 -translate-y-1/2 truncate font-medium',
// one label at a time: the resize ghost carries it while
// this bar is the faded placeholder
'group-data-[drag-kind^=resize]/gantt-seg:opacity-0',
/* a departing dependency arrow drops its corner just past
the bar's end, so exactly those labels reserve extra
room; everything else keeps the tight default */
placement === 'after'
? dependencySourceIds.has(segment.occurrence.eventId)
? 'start-full ms-4'
: 'start-full ms-2'
: 'end-full me-2',
)}
>
{segment.occurrence.event.title}
</span>
)}
</div>
);
})}
{bars?.summary && segments.length === 0 && (
<div
data-slot="gantt-summary"
aria-hidden
className="pointer-events-none absolute top-1/2 -translate-y-1/2"
style={{
insetInlineStart: `${bars.summary.from * 100}%`,
width: `${Math.max((bars.summary.to - bars.summary.from) * 100, 0.5)}%`,
}}
>
{viewConfig.renderSummary ? (
// consumer-owned rollup: the positioned envelope wrapper stays
viewConfig.renderSummary({
resource: row.resource,
start: new Date(rangeStartMs + bars.summary.from * (rangeEndMs - rangeStartMs)),
end: new Date(rangeStartMs + bars.summary.to * (rangeEndMs - rangeStartMs)),
progress: bars.summary.progress,
})
) : (
<>
{/* envelope end caps: the classic PM rollup silhouette, muted */}
<span aria-hidden className="bg-muted-foreground/50 absolute start-0 top-1/2 h-3 w-0.5 -translate-y-1/2 rounded-full" />
<span aria-hidden className="bg-muted-foreground/50 absolute end-0 top-1/2 h-3 w-0.5 -translate-y-1/2 rounded-full" />
<div className="bg-muted-foreground/20 relative h-1.5 overflow-hidden rounded-full">
{bars.summary.progress !== null && (
<div
data-slot="gantt-summary-progress"
className="bg-muted-foreground/50 absolute inset-y-0 start-0 rounded-full"
style={{ width: `${bars.summary.progress}%` }}
/>
)}
</div>
{bars.summary.progress !== null && (
<span className="text-muted-foreground absolute start-full top-1/2 ms-2 -translate-y-1/2 whitespace-nowrap">
{bars.summary.progress}%
</span>
)}
</>
)}
</div>
)}
{ghost && (
<div
data-slot="gantt-drag-ghost"
data-kind={ghost.kind}
data-milestone={ghost.milestone || undefined}
data-drop-invalid={!ghost.valid || undefined}
className={cn(
// Slight dashed indicator, never a dramatic restyle. Move shows a
// faint drop-target placeholder (the smooth cursor clone carries
// the visual); resize shows the event at its new size in its own
// color with just a dashed border.
/* height via the class, not an inline style, so a consumer's
own selector can still outrank it */
'pointer-events-none absolute z-40 h-(--gantt-ghost-height) rounded-sm border border-dashed font-medium',
!ghost.valid && 'border-destructive bg-destructive/10 text-destructive',
ghost.valid && ghost.kind === 'move' && 'border-(--gantt-event-color)/50 bg-(--gantt-event-color)/8',
ghost.valid && ghost.kind !== 'move' && 'text-foreground border-(--gantt-event-color)/70 bg-(--gantt-event-color)/22',
/* a milestone's landing marker keeps the milestone's SHAPE: the
wrapper sheds its own dashed box and centers a dashed diamond
instead - a dashed rectangle read as a different object */
ghost.milestone && 'flex items-center justify-center rounded-none border-0 bg-transparent',
)}
style={
{
/* a milestone drop lands as a lane-height square CENTERED on
the instant (same clamp as the diamond); the generic 0.5%
floor would anchor a sliver at the instant's left instead */
insetInlineStart: ghost.milestone
? `clamp(0rem, ${ghost.from * 100}% - ${laneHeightRem / 2}rem, 100% - ${laneHeightRem}rem)`
: `${ghost.from * 100}%`,
width: ghost.milestone ? `${laneHeightRem}rem` : `${Math.max((ghost.to - ghost.from) * 100, 0.5)}%`,
// sit on the dragged schedule's OWN lane. Centering the ghost
// in the row put it on no lane at all once a node stacked, so
// a 3-lane row showed the drop target floating in the middle.
top: `${ghostLaneOffsetRem}rem`,
/* metrics-driven, and published so a consumer can size
against the SAME number instead of hardcoding 1.25 */
'--gantt-ghost-height': `${ghostHeightRem}rem`,
'--gantt-event-color': ghost.color ?? 'var(--color-primary)',
} as CSSProperties
}
>
{ghost.milestone && (
<span
className={cn(
'size-2.5 rotate-45 rounded-[2px] border border-dashed',
ghost.valid ? 'border-(--gantt-event-color)/70 bg-(--gantt-event-color)/10' : 'border-destructive bg-destructive/10',
)}
/>
)}
{ghost.kind !== 'move' && (
// label rides OUTSIDE after the bar, exactly like the resting
// outside placement - never inside the schedule
<span className="pointer-events-none absolute start-full top-1/2 ms-2 max-w-60 -translate-y-1/2 truncate whitespace-nowrap">
{ghost.title}
</span>
)}
</div>
)}
{draft && (
<div
data-slot="gantt-slot-draft"
data-lane={draftLane}
// OPAQUE. When the destination lane does not exist yet the row has
// not grown, so the placeholder rides the bottom edge and overlaps
// the bar it is going under - as a tint that read as a smudge over
// the bar's own label. Punched out of the backdrop it reads as a
// distinct object sliding underneath, which is what it is.
className="border-primary bg-background pointer-events-none absolute z-40 overflow-hidden rounded-sm border border-dashed"
style={{
insetInlineStart: `${draft.from * 100}%`,
width: `${Math.max((draft.to - draft.from) * 100, 0.5)}%`,
// the destination lane, not the row's middle (which on a stacked
// row is the GAP between two lanes), and the real lane height
// rather than a hardcoded h-5 a consumer's metrics would break
top: `${draftTopRem}rem`,
height: `${laneHeightRem}rem`,
}}
>
{/* the accent tint, over the opaque base rather than over whatever
happens to be beneath the row */}
<span aria-hidden className="bg-primary/15 absolute inset-0" />
</div>
)}
</div>
{/* OUTSIDE the content layer for the same reason as the hint bubble: the
layer's paint containment would CLIP a chip that overhangs the row.
Centred on the range being painted, so the times track the drag. */}
{draft && draftLabel && (
<div
data-slot="gantt-slot-draft-label"
className="pointer-events-none absolute z-40"
style={{
// anchored to the range's END and riding after it, exactly like the
// drag ghost's own label. Centred above the placeholder it covered
// the schedule on the track above - and the one thing a create
// gesture must never hide is what is already booked.
insetInlineStart: `${draft.to * 100}%`,
top: `${draftTopRem}rem`,
height: `${laneHeightRem}rem`,
}}
>
<span className="bg-foreground text-background absolute start-full top-1/2 ms-2 inline-flex w-max -translate-y-1/2 items-center rounded-md px-2 py-1 text-xs font-medium whitespace-nowrap">
{draftLabel}
{/* Same arrow as every other bubble, one size down. A 45-degree
square is symmetric, so size-2.5 spans ~14px whichever edge it
straddles: a small nub under a ~120px-wide chip, but most of the
short edge of a ~26px-TALL one. size-1.5 spans ~8.5px and
protrudes ~4px, the usual tooltip-arrow proportion, so the side
arrow reads the same weight as the ones above and below. */}
<span aria-hidden className="bg-foreground absolute start-0 top-1/2 size-1.5 -translate-x-1/2 -translate-y-1/2 rotate-45 rounded-[1px]" />
</span>
</div>
)}
{/* OUTSIDE the content layer: its paint containment creates a stacking
context that would trap the bubble's z-index under neighboring rows.
As a direct row child its z-30 stacks above every row in the pane. */}
{/* `hintLane < laneCount` is the second half of "empty slots only": the
pointer being on bare track can still mean the row's own padding above
a column that is booked on every track. There is no free track to
draw on there, so the clamp would park the ring on top of a bar -
exactly what must never happen. Booking such an instant is a drag from
a free point, not a click. */}
{hintVisible && hintStop && (
<div
data-slot="gantt-schedule-hint"
// rtl flips the translate sign: insetInlineStart anchors the box's
// inline-start edge, which is the RIGHT edge under rtl, so centring
// on the anchor shifts the opposite way there
className="pointer-events-none absolute z-30 -translate-x-1/2 -translate-y-1/2 rtl:translate-x-1/2"
style={{
// the live cursor position, written without React (see onPointerMove)
insetInlineStart: 'var(--gantt-hint-x, 50%)',
// first track, centred on it - z-30 on this wrapper keeps the dot
// above every bar, so a busy span still offers the affordance
top: `${hintTopRem}rem`,
}}
>
{viewConfig.renderScheduleHint ? (
// consumer-owned hint: the wrapper stays snapped + validated;
// the content drives its own create flow
viewConfig.renderScheduleHint({
start: new Date(hintStop.ms),
end: new Date(Math.max(hintStop.endMs, hintStop.ms + 1)),
resource: row.resource,
})
) : (
<>
{/* the band IS the placement affordance: it covers the interval
under the pointer, so what you see is the slot you get. Clicking
books it; pressing and dragging paints a longer range. The bubble
mirrors the tooltip theme, arrow included. */}
{/* The dot IS the cursor: an open ring, so whatever it is standing
on stays readable through it. The outer background ring is what
keeps it visible on a dark bar - an outline, not a fill.
The GLYPH is the native cursor rather than an icon: `cell` is the
range-select cursor every spreadsheet uses, which is exactly the
drag-a-range gesture, and `copy` carries a plus for the
click-to-add case. Clicking books the interval it is standing in;
pressing and dragging paints a range whose ends snap to the
nearest boundary. */}
<button
type="button"
data-slot="gantt-schedule-hint-tile"
aria-label={hintLabel}
// pointer-events-NONE: the ring rides under the cursor, so any
// press it accepts is a press stolen from whatever it is
// standing on - which is how it swallowed every click meant for
// a bar. Passing pointers straight through makes the element
// physically underneath the thing you click: a bar opens its
// job, bare track creates (the row's own handlers, which the
// ring merely previews). The button and its onClick stay for
// KEYBOARD use - pointer-events never blocks Enter/Space.
// No cursor class here: pointer-events-none makes it unreachable.
// The row carries it (see `hintVisible`).
className="border-primary ring-background/80 pointer-events-none block size-5 rounded-full border-2 bg-transparent ring-1"
onPointerDown={(e) => {
// with drag-create on the press belongs to the row's create
// gesture; a sub-threshold press still ends as this click
if (!viewConfig.dragCreate) e.stopPropagation();
}}
onClick={(e) => {
e.stopPropagation();
// a completed drag-create already committed via onSelectSlot
if (wasRecentDrag()) return;
createAt(hintStop, e);
setHintStop(null);
}}
/>
<span
data-slot="gantt-schedule-hint-bubble"
className={cn(
'bg-foreground text-background absolute start-1/2 inline-flex w-max -translate-x-1/2 items-center rounded-md px-2 py-1 text-xs font-medium whitespace-nowrap',
rowIndex === 0 ? 'top-full mt-2' : 'bottom-full mb-2',
)}
>
{hintLabel}
<span
aria-hidden
className={cn(
'bg-foreground absolute start-1/2 size-2.5 -translate-x-1/2 rotate-45 rounded-[2px]',
rowIndex === 0 ? '-top-1' : '-bottom-1',
)}
/>
</span>
</>
)}
</div>
)}
</div>
);
});
interface OffscreenChip {
id: string;
side: 'start' | 'end';
top: number;
color?: string;
label: string;
/** First bar start, shown in the chip tooltip. */
startMs: number | null;
/** scrollLeft that brings the bar back into view. */
target: number;
}
function sameChips(a: OffscreenChip[], b: OffscreenChip[]): boolean {
return (
a.length === b.length &&
a.every((chip, i) => chip.id === b[i].id && chip.side === b[i].side && chip.top === b[i].top && chip.target === b[i].target)
);
}
/**
* Edge chips for rows whose bars sit entirely outside the visible timeline;
* clicking scrolls the bar back into view. Reads geometry straight from the
* DOM (row data attributes), so scrolling never re-renders the grid.
*/
function GanttOffscreenChips({
paneRef,
occurrences,
locale,
refreshKey,
}: {
paneRef: RefObject<HTMLDivElement | null>;
occurrences: GanttOccurrence[];
locale?: Locale;
refreshKey: string;
}) {
const settings = useGanttSettings();
const [chips, setChips] = useState<OffscreenChip[]>([]);
useEffect(() => {
const pane = paneRef.current;
const viewport = getPaneViewport(pane);
if (!pane || !viewport) return;
let raf = 0;
const measure = () => {
raf = 0;
const paneRect = pane.getBoundingClientRect();
const header = viewport.querySelector<HTMLElement>('[data-slot=gantt-timeline-header]');
const headerBottom = header ? header.getBoundingClientRect().bottom - paneRect.top : 0;
const trackW = viewport.scrollWidth;
const visibleStart = getScrollStart(viewport);
const visibleEnd = visibleStart + viewport.clientWidth;
// The floating zoom control shares the right edge. The chips stay in
// their column - a shifted chip reads as misaligned, and its position
// IS its meaning - so it is the ZOOM CONTROL that glides inward while
// any end chip occupies its band (published as --gantt-zoom-shift,
// written imperatively like the rest of this measure pass). The band
// test uses the control's VERTICAL extent only, which a horizontal
// dodge never changes, so the loop cannot oscillate.
const zoomEl = pane.querySelector<HTMLElement>('[data-slot=gantt-zoom]');
const zoom = zoomEl
? {
top: zoomEl.getBoundingClientRect().top - paneRect.top - 8,
bottom: zoomEl.getBoundingClientRect().bottom - paneRect.top + 8,
}
: null;
let chipInZoomBand = false;
const next: OffscreenChip[] = [];
for (const rowEl of viewport.querySelectorAll<HTMLElement>('[data-gantt-row]')) {
const from = parseFloat(rowEl.dataset.ganttBarMin ?? '');
const to = parseFloat(rowEl.dataset.ganttBarMax ?? '');
if (Number.isNaN(from) || Number.isNaN(to)) continue;
const rect = rowEl.getBoundingClientRect();
const top = rect.top - paneRect.top + rect.height / 2;
if (top < headerBottom + 10 || top > paneRect.height - 16) continue;
const startPx = from * trackW;
const endPx = to * trackW;
const startMs = parseFloat(rowEl.dataset.ganttBarStartMs ?? '');
const base = {
id: rowEl.dataset.ganttRowId ?? '',
top: Math.round(top),
color: rowEl.dataset.ganttBarColor,
label: rowEl.dataset.ganttBarLabel ?? '',
startMs: Number.isNaN(startMs) ? null : startMs,
};
if (endPx <= visibleStart + 2) {
next.push({
...base,
side: 'start',
target: startPx - 24,
});
} else if (startPx >= visibleEnd - 2) {
if (zoom && top >= zoom.top && top <= zoom.bottom) {
chipInZoomBand = true;
}
next.push({
...base,
side: 'end',
target: endPx - viewport.clientWidth + 24,
});
}
}
// 28px clears the 20px chip column plus breathing room on both sides
zoomEl?.style.setProperty('--gantt-zoom-shift', chipInZoomBand ? '28px' : '0px');
setChips((prev) => (sameChips(prev, next) ? prev : next));
};
const schedule = () => {
if (!raf) raf = requestAnimationFrame(measure);
};
viewport.addEventListener('scroll', schedule);
const observer = new ResizeObserver(schedule);
observer.observe(viewport);
schedule();
return () => {
viewport.removeEventListener('scroll', schedule);
observer.disconnect();
if (raf) cancelAnimationFrame(raf);
// the zoom control returns to its corner once no chip can collide
pane.querySelector<HTMLElement>('[data-slot=gantt-zoom]')?.style.removeProperty('--gantt-zoom-shift');
};
}, [paneRef, occurrences, refreshKey]);
if (chips.length === 0) return null;
const scrollTo = (chip: OffscreenChip) => {
const viewport = getPaneViewport(paneRef.current);
if (!viewport) return;
const target = Math.max(0, chip.target);
viewport.scrollTo({
// chip targets are distances from the inline start; RTL signs them
left: getComputedStyle(viewport).direction === 'rtl' ? -target : target,
behavior: 'smooth',
});
// hand keyboard focus to the bar the chip promised (the chip unmounts)
const bar = viewport.querySelector<HTMLElement>(`[data-gantt-row-id="${CSS.escape(chip.id)}"] [data-slot=gantt-bar]`);
bar?.focus({ preventScroll: true });
};
return (
<div data-slot="gantt-offscreen-chips" className="pointer-events-none absolute inset-0 z-30 overflow-hidden">
<TooltipProvider delay={600} closeDelay={0} timeout={300}>
{chips.map((chip) => (
<Tooltip key={`${chip.id}-${chip.side}`}>
<TooltipTrigger
render={
<button
type="button"
data-slot="gantt-offscreen-chip"
data-side={chip.side}
aria-label={settings.i18n.labels.jumpToBar(chip.label)}
className="bg-background text-muted-foreground hover:text-foreground pointer-events-auto absolute flex size-5 -translate-y-1/2 cursor-pointer items-center justify-center rounded-full border shadow-xs"
style={{
top: chip.top,
...(chip.side === 'start' ? { insetInlineStart: '0.5rem' } : { insetInlineEnd: '0.875rem' }),
}}
onClick={() => scrollTo(chip)}
/>
}
>
{chip.side === 'start' ? (
<ChevronLeftIcon className="size-3" aria-hidden="true" />
) : (
<ChevronRightIcon className="size-3" aria-hidden="true" />
)}
<span
aria-hidden
className="ring-background absolute -end-px -top-px size-1.5 rounded-full ring-1"
style={{ background: chip.color ?? 'var(--color-primary)' }}
/>
</TooltipTrigger>
<TooltipContent side={chip.side === 'start' ? 'right' : 'left'}>
<div className="font-medium">{chip.label}</div>
{chip.startMs !== null && (
<div className="opacity-80">
{/* zoned: the chip must name the same day the grid shows */}
{format(toZoned(new Date(chip.startMs), settings.timeZone), 'MMM d, yyyy', { locale })}
</div>
)}
</TooltipContent>
</Tooltip>
))}
</TooltipProvider>
</div>
);
}
export { GanttView };
export type { GanttViewProps };components/ui/gantt/gantt.tsx
'use client';
import {
createContext,
useContext,
useEffect,
useLayoutEffect,
useRef,
useState,
useSyncExternalStore,
type ComponentType,
type ReactNode,
type RefObject,
} from 'react';
import { mergeGanttI18n, type GanttI18nConfig, type GanttI18nOverrides } from '@/registry/vcare/ui/gantt/gantt-i18n';
import {
buildEventIndex,
defaultEventOrder,
eventsOverlap,
findResource,
getGanttDateRange,
getRangeKey,
stepGanttDate,
toZoned,
type GanttIndex,
type WeekStartsOn,
} from '@/registry/vcare/ui/gantt/gantt-lib';
import type {
GanttBarId,
GanttBaseline,
GanttBaselineVariance,
GanttDateRange,
GanttDragState,
GanttEvent,
GanttInteractions,
GanttOccurrence,
GanttOffDaysConfig,
GanttOverlapPolicy,
GanttProposedUpdate,
GanttRangeInfo,
GanttResource,
GanttResourceReorder,
GanttRowAlign,
GanttScale,
GanttScheduleMode,
GanttSegment,
GanttSelection,
GanttSlotDraft,
GanttSlotInfo,
GanttState,
GanttUpdateResult,
} from '@/registry/vcare/ui/gantt/gantt-types';
import { mergeProps } from '@base-ui/react/merge-props';
import { useRender } from '@base-ui/react/use-render';
import type { Locale } from 'date-fns';
import { cn } from '@/registry/vcare/lib/utils';
const DEFAULT_INTERACTIONS: GanttInteractions = {
drag: true,
resize: true,
selectSlot: true,
};
/** Infinite-scroll growth cap, in whole periods per side. */
const MAX_RANGE_WINDOW = 12;
/** A node holds as many concurrent schedules as it needs unless told otherwise. */
const DEFAULT_SCHEDULE_MODE: GanttScheduleMode = 'multiple';
/** Tree label sits on the first schedule's baseline, not the grown row's middle. */
const DEFAULT_ROW_ALIGN: GanttRowAlign = 'start';
/**
* A node's cardinality: its own override wins over the view-level default.
* Shared by the layout pass and the gesture engine so both read one rule.
*/
function resolveScheduleMode(node: GanttResource | null | undefined, scheduleMode: GanttScheduleMode | undefined): GanttScheduleMode {
return node?.scheduleMode ?? scheduleMode ?? DEFAULT_SCHEDULE_MODE;
}
const EMPTY_SELECTION: GanttSelection = { eventKeys: [], slot: null };
interface GanttCallbacks<TData = unknown> {
onEventClick?: (occurrence: GanttOccurrence<TData>, e: React.MouseEvent) => void;
onEventDoubleClick?: (occurrence: GanttOccurrence<TData>, e: React.MouseEvent) => void;
onEventUpdate?: (update: GanttProposedUpdate<TData>) => GanttUpdateResult;
canDropEvent?: (update: GanttProposedUpdate<TData>) => boolean;
onSlotClick?: (slot: GanttSlotInfo, e: React.MouseEvent) => void;
onSelectSlot?: (slot: GanttSlotDraft) => void;
canSelectSlot?: (slot: GanttSlotDraft) => boolean;
/** Fires when the "add task" hint is activated; create a new tree row. */
onCreateTask?: (ctx: { parentId: string | null; index: number }) => void;
/**
* Gates the "add task" hint. The shipped view offers root-level creation
* only (parentId = null); parentId stays in the contract for group-level
* affordances a consumer builds via its own UI + onCreateTask.
*/
canCreateTask?: (ctx: { parentId: string | null }) => boolean;
/** Click on a tree row's surface (chevron/checkbox/grip clicks excluded). */
onResourceClick?: (ctx: GanttColumnContext, e: React.MouseEvent) => void;
onResourceDoubleClick?: (ctx: GanttColumnContext, e: React.MouseEvent) => void;
onRangeChange?: (info: GanttRangeInfo) => void;
onScaleChange?: (scale: GanttScale) => void;
onDateChange?: (date: Date) => void;
onSelectionChange?: (selection: GanttSelection) => void;
onInteractionsChange?: (interactions: GanttInteractions) => void;
onEventsChange?: (events: GanttEvent<TData>[]) => void;
/**
* Commit gate for timeline resource-row drag reorder. Return false to
* reject; apply the move by adopting proposal.resources into your
* `resources` state (controlled - the calendar never self-mutates).
*/
onResourceReorder?: (proposal: GanttResourceReorder) => void | false;
/** Live validity predicate while a resource row is being dragged. */
canReorderResource?: (proposal: GanttResourceReorder) => boolean;
/**
* Fires when a reorder gesture is released on a position rejected by
* `canReorderResource` (e.g. a pinned row). Use it to explain the rejection
* (a toast) - the destructive drop indicator already shows it live.
*/
onResourceReorderReject?: (proposal: GanttResourceReorder) => void;
}
interface UseGanttStateOptions<TData = unknown> extends GanttCallbacks<TData> {
events?: GanttEvent<TData>[];
defaultEvents?: GanttEvent<TData>[];
scale?: GanttScale;
defaultScale?: GanttScale;
date?: Date;
defaultDate?: Date;
selection?: GanttSelection;
defaultSelection?: GanttSelection;
interactions?: Partial<GanttInteractions>;
defaultInteractions?: Partial<GanttInteractions>;
loading?: boolean;
timeZone?: string;
locale?: Locale;
weekStartsOn?: WeekStartsOn;
slotDuration?: number;
snapDuration?: number;
i18n?: GanttI18nOverrides;
/**
* Hard travel bounds for infinite scrolling; either side may be omitted
* for unlimited travel in that direction.
*/
rangeBounds?: { min?: Date; max?: Date };
/** Pointer-activation threshold overrides for drag/resize/create. */
activation?: GanttActivationConfig;
/**
* Infinite-scroll growth cap in whole periods per side; past it the
* anchor slides instead (DOM stays bounded). Default 12.
*/
maxRangeWindow?: number;
/** Tree nodes of the gantt (GanttNode is the preferred type name). */
resources?: GanttResource[];
/**
* What a gesture may do when it would overlap another schedule in the SAME
* node: "allow" (default), "clamp" to the neighbour's edge, or "reject".
* Policy only - overlapping data always renders. A node in "single"
* scheduleMode rejects regardless.
*/
overlap?: GanttOverlapPolicy;
/**
* Make canDropEvent binding: releasing a gesture whose last verdict was
* invalid reverts it, like the "reject" overlap policy, instead of
* committing anyway. Default false - canDropEvent alone stays advisory
* (it styles the ghost; onEventUpdate is the commit gate).
*/
enforceCanDrop?: boolean;
getEventPriority?: (event: GanttEvent<TData>) => number;
eventOrder?: (a: GanttOccurrence<TData>, b: GanttOccurrence<TData>) => number;
getOccurrences?: (event: GanttEvent<TData>, range: GanttDateRange, ctx: { timeZone: string }) => Array<{ start: Date; end: Date }> | null;
}
/**
* Resolved configuration: every UseGanttStateOptions field except the
* controlled/uncontrolled state pairs, with defaults applied and i18n merged.
* Read via ref semantics - callback identity changes never re-render the grid.
*/
interface GanttSettings<TData = unknown> extends GanttCallbacks<TData> {
timeZone: string;
locale?: Locale;
weekStartsOn: WeekStartsOn;
slotDuration: number;
snapDuration: number;
i18n: GanttI18nConfig;
rangeBounds?: { min?: Date; max?: Date };
activation?: GanttActivationConfig;
maxRangeWindow?: number;
resources: GanttResource[];
overlap: GanttOverlapPolicy;
enforceCanDrop?: boolean;
getEventPriority: (event: GanttEvent<TData>) => number;
eventOrder: (a: GanttOccurrence<TData>, b: GanttOccurrence<TData>) => number;
getOccurrences?: (event: GanttEvent<TData>, range: GanttDateRange, ctx: { timeZone: string }) => Array<{ start: Date; end: Date }> | null;
}
interface GanttApi<TData = unknown> {
next(): void;
prev(): void;
today(): void;
goTo(date: Date): void;
setScale(scale: GanttScale): void;
getEvents(): GanttEvent<TData>[];
getEvent(id: GanttBarId): GanttEvent<TData> | undefined;
setEvents(events: GanttEvent<TData>[]): void;
addEvent(event: GanttEvent<TData>): void;
updateEvent(id: GanttBarId, patch: Partial<GanttEvent<TData>>): void;
removeEvent(id: GanttBarId): void;
getOccurrences(range?: GanttDateRange): GanttOccurrence<TData>[];
findOverlapping(candidate: { start: Date; end: Date; excludeEventId?: string }): GanttOccurrence<TData>[];
select(selection: Partial<GanttSelection>): void;
selectEvent(key: string, opts?: { additive?: boolean }): void;
clearSelection(): void;
setInteractions(patch: Partial<GanttInteractions>): void;
getVisibleRange(): GanttDateRange;
getActiveRange(): GanttDateRange;
/** TZDate in the gantt's display time zone. */
toZoned(date: Date): Date;
}
/** Cross-file plumbing for sibling view/interaction modules; not public API. */
interface GanttInternals<TData = unknown> {
getIndex(): GanttIndex<TData>;
setDrag(drag: GanttDragState<TData> | null): void;
setSlotDraft(draft: GanttSlotDraft | null): void;
applyProposedUpdate(update: GanttProposedUpdate<TData>): boolean;
getSettingsVersion(): number;
/**
* Grow visibleRange by whole periods for infinite scrolling; resets on
* date/scale changes. Returns false once the growth cap is reached.
*/
extendRange(direction: 'before' | 'after'): boolean;
/**
* True when the LAST anchor-date change was an extendRange window slide
* (not a navigation) - the view keeps its scroll guard across slides.
*/
didAnchorSlide(): boolean;
/** View reports the visible-center instant (or null) for the nav title. */
setViewportCenter(date: Date | null): void;
}
interface GanttInstance<TData = unknown> {
getState(): GanttState<TData>;
subscribe(listener: () => void): () => void;
api: GanttApi<TData>;
settings: GanttSettings<TData>;
internals: GanttInternals<TData>;
}
function resolveSettings<TData>(options: UseGanttStateOptions<TData>): GanttSettings<TData> {
const {
// strip state pairs; the rest flows into settings
events: _e,
defaultEvents: _de,
scale: _v,
defaultScale: _dv,
date: _d,
defaultDate: _dd,
selection: _s,
defaultSelection: _ds,
interactions: _i,
defaultInteractions: _di,
loading: _l,
...rest
} = options;
const getEventPriority = options.getEventPriority ?? ((event: GanttEvent<TData>) => event.priority ?? 0);
return {
...rest,
timeZone: options.timeZone ?? Intl.DateTimeFormat().resolvedOptions().timeZone,
locale: options.locale,
// locale-first default: a de/fr locale gets Monday weeks without also
// having to set weekStartsOn; an explicit weekStartsOn always wins
weekStartsOn: options.weekStartsOn ?? options.locale?.options?.weekStartsOn ?? 0,
slotDuration: options.slotDuration ?? 30,
snapDuration: options.snapDuration ?? 15,
i18n: mergeGanttI18n(options.i18n),
rangeBounds: options.rangeBounds,
resources: options.resources ?? [],
overlap: options.overlap ?? 'allow',
getEventPriority,
// priority-aware default: higher getEventPriority packs/orders first
eventOrder: options.eventOrder ?? ((a, b) => getEventPriority(b.event) - getEventPriority(a.event) || defaultEventOrder(a, b)),
getOccurrences: options.getOccurrences,
};
}
const warned = new Set<string>();
function warnOnce(key: string, message: string) {
if (process.env.NODE_ENV !== 'production' && !warned.has(key)) {
warned.add(key);
console.warn(`[gantt] ${message}`);
}
}
interface GanttStore<TData> {
instance: GanttInstance<TData>;
setOptions(next: UseGanttStateOptions<TData>): boolean;
notify(): void;
emitRangeIfChanged(): void;
}
function createGanttStore<TData>(initial: UseGanttStateOptions<TData>): GanttStore<TData> {
let options = initial;
let settings = resolveSettings(initial);
let settingsVersion = 0;
const listeners = new Set<() => void>();
const internal = {
scale: initial.defaultScale ?? 'day',
date: initial.defaultDate ?? new Date(),
events: initial.defaultEvents ?? [],
selection: initial.defaultSelection ?? EMPTY_SELECTION,
interactions: { ...DEFAULT_INTERACTIONS, ...initial.defaultInteractions },
drag: null as GanttDragState<TData> | null,
slotDraft: null as GanttSlotDraft | null,
/** Whole extra periods rendered on each side (infinite scroll). */
rangeWindow: { before: 0, after: 0 },
/** Visible-center instant reported by the view; drives the nav title. */
viewportCenter: null as Date | null,
};
let snapshot: GanttState<TData> | null = null;
let indexCache: {
events: GanttEvent<TData>[];
rangeKey: string;
timeZone: string;
index: GanttIndex<TData>;
} | null = null;
let lastEmittedRangeKey: string | null = null;
/** Whether the last anchor change came from an extendRange window slide. */
let lastAnchorChangeWasSlide = false;
const invalidate = () => {
snapshot = null;
};
const notify = () => {
listeners.forEach((listener) => listener());
emitRangeIfChanged();
};
const getState = (): GanttState<TData> => {
if (snapshot) return snapshot;
const scale = options.scale ?? internal.scale;
const date = options.date ?? internal.date;
const rangeOpts = {
timeZone: settings.timeZone,
weekStartsOn: settings.weekStartsOn,
};
const { visibleRange: baseRange, activeRange } = getGanttDateRange(scale, date, rangeOpts);
// Infinite scroll: widen by whole periods; the anchor period stays put
const { before, after } = internal.rangeWindow;
let visibleRange = baseRange;
if (before > 0 || after > 0) {
let earlier = date;
for (let i = 0; i < before; i++) {
earlier = stepGanttDate(scale, earlier, -1, rangeOpts);
}
let later = date;
for (let i = 0; i < after; i++) {
later = stepGanttDate(scale, later, 1, rangeOpts);
}
visibleRange = {
start: getGanttDateRange(scale, earlier, rangeOpts).visibleRange.start,
end: getGanttDateRange(scale, later, rangeOpts).visibleRange.end,
};
}
snapshot = {
scale,
date,
visibleRange,
activeRange,
events: options.events ?? internal.events,
selection: options.selection ?? internal.selection,
interactions: options.interactions ? { ...DEFAULT_INTERACTIONS, ...options.interactions } : internal.interactions,
loading: options.loading ?? false,
drag: internal.drag,
slotDraft: internal.slotDraft,
viewportCenter: internal.viewportCenter,
};
return snapshot;
};
const emitRangeIfChanged = () => {
if (!settings.onRangeChange) return;
const state = getState();
const key = `${state.scale}:${getRangeKey(state.visibleRange)}:${settings.timeZone}`;
if (key === lastEmittedRangeKey) return;
lastEmittedRangeKey = key;
settings.onRangeChange({
range: state.visibleRange,
activeRange: state.activeRange,
scale: state.scale,
date: state.date,
timeZone: settings.timeZone,
});
};
type ControlledKey = 'scale' | 'date' | 'events' | 'selection' | 'interactions';
const setField = <K extends ControlledKey>(key: K, value: GanttState<TData>[K extends 'events' ? 'events' : K]) => {
const controlled = options[key] !== undefined;
if (key === 'date' || key === 'scale') {
// value-equal sets are no-ops: they must not touch store state (the
// controlled path would mutate without notify) nor drop infinite-
// scroll growth for a navigation that never happened
const current = getState()[key];
const same = key === 'date' ? (current as Date).getTime() === (value as Date).getTime() : current === value;
if (same) return;
// navigating re-anchors the axis; drop any infinite-scroll growth and
// let the title follow the anchor again until the user scrolls
internal.rangeWindow = { before: 0, after: 0 };
internal.viewportCenter = null;
lastAnchorChangeWasSlide = false;
invalidate();
}
if (!controlled) {
// eslint-disable-next-line @typescript-eslint/no-explicit-any
(internal as any)[key] = value;
invalidate();
}
const callbacks: Record<ControlledKey, ((v: never) => void) | undefined> = {
scale: settings.onScaleChange as never,
date: settings.onDateChange as never,
events: settings.onEventsChange as never,
selection: settings.onSelectionChange as never,
interactions: settings.onInteractionsChange as never,
};
callbacks[key]?.(value as never);
if (!controlled) notify();
};
const applyProposedUpdate = (
update: GanttProposedUpdate<TData>,
// extra non-timing fields committed in the SAME events emission: a second
// setField pass would read stale controlled options.events and emit an
// array without the timing change
extra?: Partial<GanttEvent<TData>>,
): boolean => {
const result = settings.onEventUpdate?.(update);
if (result === false) return false;
const adjusted: Partial<GanttEvent<TData>> =
result && typeof result === 'object'
? {
start: result.start ?? update.start,
end: result.end ?? update.end,
allDay: result.allDay ?? update.allDay,
}
: { start: update.start, end: update.end, allDay: update.allDay };
if (update.resourceId !== undefined) adjusted.resourceId = update.resourceId;
const merged = extra ? { ...extra, ...adjusted } : adjusted;
const events = getState().events;
const next = events.map((event) => (event.id === update.event.id ? { ...event, ...merged } : event));
setField('events', next);
return true;
};
const getIndex = (): GanttIndex<TData> => {
const state = getState();
const rangeKey = getRangeKey(state.visibleRange);
if (indexCache && indexCache.events === state.events && indexCache.rangeKey === rangeKey && indexCache.timeZone === settings.timeZone) {
return indexCache.index;
}
const index = buildEventIndex(state.events, state.visibleRange, {
timeZone: settings.timeZone,
eventOrder: settings.eventOrder,
getOccurrences: settings.getOccurrences,
});
indexCache = {
events: state.events,
rangeKey,
timeZone: settings.timeZone,
index,
};
return index;
};
/** Anchor clamp: navigation may never leave the configured bounds. */
const clampToBounds = (date: Date): Date => {
const bounds = settings.rangeBounds;
if (!bounds) return date;
if (bounds.min && date.getTime() < bounds.min.getTime()) return bounds.min;
if (bounds.max && date.getTime() > bounds.max.getTime()) return bounds.max;
return date;
};
const api: GanttApi<TData> = {
next() {
const state = getState();
setField(
'date',
clampToBounds(
stepGanttDate(state.scale, state.date, 1, {
timeZone: settings.timeZone,
}),
),
);
},
prev() {
const state = getState();
setField(
'date',
clampToBounds(
stepGanttDate(state.scale, state.date, -1, {
timeZone: settings.timeZone,
}),
),
);
},
today() {
setField('date', clampToBounds(new Date()));
},
goTo(date) {
setField('date', clampToBounds(date));
},
setScale(scale) {
setField('scale', scale);
},
getEvents() {
return getState().events;
},
getEvent(id) {
return getState().events.find((event) => event.id === id);
},
setEvents(events) {
setField('events', events);
},
addEvent(event) {
setField('events', [...getState().events, event]);
},
updateEvent(id, patch) {
const event = api.getEvent(id);
if (!event) return;
const merged = { ...event, ...patch };
const timingChanged = patch.start !== undefined || patch.end !== undefined || patch.allDay !== undefined;
if (timingChanged && settings.onEventUpdate) {
// timing + rest commit as ONE events emission (a rejected update
// drops the whole patch, same as before)
const rest = { ...patch };
delete rest.start;
delete rest.end;
delete rest.allDay;
applyProposedUpdate(
{
event: merged,
occurrence: null,
start: merged.start,
end: merged.end,
allDay: merged.allDay ?? false,
source: 'api',
},
Object.keys(rest).length > 0 ? rest : undefined,
);
return;
}
setField(
'events',
getState().events.map((e) => (e.id === id ? merged : e)),
);
},
removeEvent(id) {
setField(
'events',
getState().events.filter((event) => event.id !== id),
);
},
getOccurrences(range) {
if (!range) return getIndex().occurrences;
const state = getState();
const within = range.start >= state.visibleRange.start && range.end <= state.visibleRange.end;
if (within) {
return getIndex().occurrences.filter((occ) => eventsOverlap(occ, range));
}
return buildEventIndex(state.events, range, {
timeZone: settings.timeZone,
eventOrder: settings.eventOrder,
getOccurrences: settings.getOccurrences,
}).occurrences;
},
findOverlapping({ start, end, excludeEventId }) {
return api.getOccurrences({ start, end }).filter((occ) => occ.eventId !== excludeEventId);
},
select(partial) {
const current = getState().selection;
setField('selection', {
eventKeys: partial.eventKeys ?? current.eventKeys,
slot: partial.slot !== undefined ? partial.slot : current.slot,
});
},
selectEvent(key, opts) {
const current = getState().selection;
const eventKeys = opts?.additive
? current.eventKeys.includes(key)
? current.eventKeys.filter((k) => k !== key)
: [...current.eventKeys, key]
: [key];
setField('selection', { ...current, eventKeys });
},
clearSelection() {
setField('selection', EMPTY_SELECTION);
},
setInteractions(patch) {
setField('interactions', { ...getState().interactions, ...patch });
},
getVisibleRange() {
return getState().visibleRange;
},
getActiveRange() {
return getState().activeRange;
},
toZoned(date) {
return toZoned(date, settings.timeZone);
},
};
const internals: GanttInternals<TData> = {
getIndex,
setDrag(drag) {
internal.drag = drag;
invalidate();
notify();
},
setSlotDraft(draft) {
internal.slotDraft = draft;
invalidate();
notify();
},
setViewportCenter(date) {
const prev = internal.viewportCenter;
if (prev?.getTime() === date?.getTime()) return;
internal.viewportCenter = date;
invalidate();
notify();
},
applyProposedUpdate,
getSettingsVersion() {
return settingsVersion;
},
extendRange(direction) {
const state = getState();
const bounds = settings.rangeBounds;
if (direction === 'before' && bounds?.min && state.visibleRange.start.getTime() <= bounds.min.getTime()) {
return false;
}
if (direction === 'after' && bounds?.max && state.visibleRange.end.getTime() >= bounds.max.getTime()) {
return false;
}
const cap = Math.max(1, settings.maxRangeWindow ?? MAX_RANGE_WINDOW);
const { before, after } = internal.rangeWindow;
const grow = direction === 'before' ? before < cap : after < cap;
if (grow) {
internal.rangeWindow = direction === 'before' ? { before: before + 1, after } : { before, after: after + 1 };
} else {
// window is at capacity: SLIDE the anchor one period instead, so
// travel stays unbounded while the DOM stays bounded
const next = stepGanttDate(state.scale, state.date, direction === 'before' ? -1 : 1, {
timeZone: settings.timeZone,
});
if (options.date !== undefined) {
// controlled anchor: propose the slide; nothing changes until the
// parent adopts it
settings.onDateChange?.(next);
return false;
}
internal.date = next;
lastAnchorChangeWasSlide = true;
settings.onDateChange?.(next);
}
invalidate();
notify();
return true;
},
didAnchorSlide() {
return lastAnchorChangeWasSlide;
},
};
const instance: GanttInstance<TData> = {
getState,
subscribe(listener) {
listeners.add(listener);
return () => listeners.delete(listener);
},
api,
get settings() {
return settings;
},
internals,
};
const STATE_KEYS = ['events', 'scale', 'date', 'selection', 'interactions', 'loading'] as const;
const SETTINGS_KEYS = [
'timeZone',
'locale',
'weekStartsOn',
'slotDuration',
'snapDuration',
'i18n',
'rangeBounds',
'activation',
'maxRangeWindow',
'resources',
'overlap',
'enforceCanDrop',
'getEventPriority',
'eventOrder',
'getOccurrences',
] as const;
return {
instance,
setOptions(next) {
const prev = options;
options = next;
// compare by value: a freshly constructed but equal controlled date
// must not wipe infinite-scroll growth on every parent re-render
if (prev.date?.getTime() !== next.date?.getTime() || prev.scale !== next.scale) {
internal.rangeWindow = { before: 0, after: 0 };
lastAnchorChangeWasSlide = false;
}
let changed = false;
for (const key of STATE_KEYS) {
if (prev[key] !== next[key]) {
changed = true;
break;
}
}
let settingsChanged = false;
for (const key of SETTINGS_KEYS) {
if (prev[key] !== next[key]) {
settingsChanged = true;
break;
}
}
settings = resolveSettings(next);
if (settingsChanged) {
settingsVersion++;
changed = true;
}
if (changed) invalidate();
return changed;
},
notify,
emitRangeIfChanged,
};
}
/**
* Headless root hook - the full calendar engine without any markup.
* Pass the returned instance to <Gantt calendar={instance}> or drive
* fully custom UI from instance.getState()/subscribe/api.
*/
function useGanttState<TData = unknown>(options: UseGanttStateOptions<TData> = {}): GanttInstance<TData> {
const [store] = useState(() => createGanttStore<TData>(options));
const changed = store.setOptions(options);
const changedRef = useRef(false);
if (changed) changedRef.current = true;
useLayoutEffect(() => {
if (changedRef.current) {
changedRef.current = false;
store.notify();
}
});
useEffect(() => {
store.emitRangeIfChanged();
// mount-only: onRangeChange fires once for the initial range
// eslint-disable-next-line react-hooks/exhaustive-deps
}, []);
return store.instance;
}
const GanttContext =
// eslint-disable-next-line @typescript-eslint/no-explicit-any
createContext<GanttInstance<any> | null>(null);
/** The stable calendar instance; throws outside <Gantt>. */
function useGantt<TData = unknown>(): GanttInstance<TData> {
const instance = useContext(GanttContext);
if (!instance) {
throw new Error('useGantt must be used within <Gantt>');
}
return instance as GanttInstance<TData>;
}
interface UseGanttSelectorOptions<TData, TSelected> {
calendar?: GanttInstance<TData>;
isEqual?: (a: TSelected, b: TSelected) => boolean;
}
/** Fine-grained subscription with equality memoization (Object.is default). */
function useGanttSelector<TData = unknown, TSelected = unknown>(
selector: (state: GanttState<TData>) => TSelected,
options?: UseGanttSelectorOptions<TData, TSelected>,
): TSelected {
const contextInstance = useContext(GanttContext);
const instance = options?.calendar ?? contextInstance;
if (!instance) {
throw new Error('useGanttSelector needs an <Gantt> ancestor or an explicit `calendar` option');
}
const isEqual = options?.isEqual ?? Object.is;
const lastRef = useRef<{ value: TSelected } | null>(null);
const selectorRef = useRef(selector);
selectorRef.current = selector;
const getSnapshot = () => {
const next = selectorRef.current(instance.getState() as GanttState<TData>);
if (lastRef.current && isEqual(lastRef.current.value, next)) {
return lastRef.current.value;
}
lastRef.current = { value: next };
return next;
};
return useSyncExternalStore(instance.subscribe, getSnapshot, getSnapshot);
}
function useGanttScale(): {
scale: GanttScale;
setScale: (scale: GanttScale) => void;
} {
const instance = useGantt();
const scale = useGanttSelector((state) => state.scale);
return { scale, setScale: instance.api.setScale };
}
function useGanttNavigation(): {
date: Date;
/** i18n.functions.formatTitle output for the current view. */
title: string;
visibleRange: GanttDateRange;
activeRange: GanttDateRange;
next: () => void;
prev: () => void;
today: () => void;
goTo: (date: Date) => void;
/** True when the anchor period contains now in the display time zone. */
isToday: boolean;
} {
const instance = useGantt();
const { settings } = instance;
const slice = useGanttSelector(
(state) => ({
date: state.date,
scale: state.scale,
visibleRange: state.visibleRange,
activeRange: state.activeRange,
viewportCenter: state.viewportCenter,
}),
{
isEqual: (a, b) =>
a.date.getTime() === b.date.getTime() &&
a.scale === b.scale &&
a.viewportCenter?.getTime() === b.viewportCenter?.getTime() &&
getRangeKey(a.visibleRange) === getRangeKey(b.visibleRange),
},
);
useGanttSettingsVersion(instance);
const now = new Date();
// The title names what you are LOOKING at: the visible-center period when
// the view reports one, otherwise the anchor period.
const titleDate = slice.viewportCenter ?? slice.date;
const titleActive = slice.viewportCenter
? getGanttDateRange(slice.scale, slice.viewportCenter, {
timeZone: settings.timeZone,
weekStartsOn: settings.weekStartsOn,
}).activeRange
: slice.activeRange;
return {
date: slice.date,
title: settings.i18n.functions.formatTitle(slice.scale, {
date: toZoned(titleDate, settings.timeZone),
activeRange: titleActive,
visibleRange: slice.visibleRange,
locale: settings.locale,
}),
visibleRange: slice.visibleRange,
activeRange: slice.activeRange,
next: instance.api.next,
prev: instance.api.prev,
today: instance.api.today,
goTo: instance.api.goTo,
isToday: now >= slice.activeRange.start && now < slice.activeRange.end,
};
}
function useGanttSelection(): {
selection: GanttSelection;
select: (selection: Partial<GanttSelection>) => void;
selectEvent: (key: string, opts?: { additive?: boolean }) => void;
clearSelection: () => void;
} {
const instance = useGantt();
const selection = useGanttSelector((state) => state.selection);
return {
selection,
select: instance.api.select,
selectEvent: instance.api.selectEvent,
clearSelection: instance.api.clearSelection,
};
}
function useGanttInteractions(): {
interactions: GanttInteractions;
setInteractions: (patch: Partial<GanttInteractions>) => void;
} {
const instance = useGantt();
const interactions = useGanttSelector((state) => state.interactions);
return { interactions, setInteractions: instance.api.setInteractions };
}
/** Expanded, sorted occurrences; defaults to the visible range. */
function useGanttOccurrences<TData = unknown>(range?: GanttDateRange): GanttOccurrence<TData>[] {
const instance = useGantt<TData>();
return useGanttSelector<TData, GanttOccurrence<TData>[]>(() => instance.api.getOccurrences(range), {
calendar: instance,
// keys encode id + start only, so end edits (resize-end) and payload
// changes (title, color, progress) must be compared explicitly
isEqual: (a, b) =>
a.length === b.length && a.every((occ, i) => occ.key === b[i]?.key && occ.end.getTime() === b[i].end.getTime() && occ.event === b[i].event),
});
}
interface GanttNodeSchedules<TData = unknown> {
/** The node itself, or null when the id is not in the tree. */
node: GanttResource | null;
/** Cardinality in force for this node (its own override, else the default). */
scheduleMode: GanttScheduleMode;
/** The node's occurrences in the visible range, in axis order. */
schedules: GanttOccurrence<TData>[];
/** Pairs of the node's schedules that overlap in time. */
conflicts: Array<[GanttOccurrence<TData>, GanttOccurrence<TData>]>;
}
/**
* Everything a consumer needs to MANAGE one node's schedules without
* re-deriving layout: the node, its resolved cardinality, its schedules in
* order, and the pairs that collide. Pure state - it renders nothing, so a
* "manage schedules" panel is entirely the consumer's design.
*/
function useGanttNodeSchedules<TData = unknown>(nodeId: string): GanttNodeSchedules<TData> {
const settings = useGanttSettings<TData>();
const viewConfig = useGanttViewConfig<TData>();
const occurrences = useGanttOccurrences<TData>();
const node = findResource(settings.resources, nodeId);
const schedules = occurrences.filter((occurrence) => occurrence.event.resourceId === nodeId);
const conflicts: Array<[GanttOccurrence<TData>, GanttOccurrence<TData>]> = [];
for (let i = 0; i < schedules.length; i++) {
for (let j = i + 1; j < schedules.length; j++) {
if (eventsOverlap(schedules[i], schedules[j])) {
conflicts.push([schedules[i], schedules[j]]);
}
}
}
return {
node,
scheduleMode: resolveScheduleMode(node, viewConfig.scheduleMode),
schedules,
conflicts,
};
}
/** Subscribes to settings changes only (version counter, not state). */
function useGanttSettingsVersion<TData>(instance: GanttInstance<TData>): number {
return useSyncExternalStore(instance.subscribe, instance.internals.getSettingsVersion, instance.internals.getSettingsVersion);
}
/** Resolved settings incl. merged i18n; re-renders only when settings change. */
function useGanttSettings<TData = unknown>(): GanttSettings<TData> {
const instance = useGantt<TData>();
useGanttSettingsVersion(instance);
return instance.settings;
}
interface GanttClassNames {
nav?: string;
toolbar?: string;
/** The gantt body (tree + track). */
view?: string;
event?: string;
/** The planned-window (baseline) ghost drawn behind a bar. */
baseline?: string;
/** The dependency-arrow layer (an SVG; color flows from currentColor). */
dependencies?: string;
}
/** Row context handed to tree-panel column and label renderers. */
interface GanttColumnContext {
resource: GanttResource;
depth: number;
isGroup: boolean;
collapsed: boolean;
}
/** One extra tree-panel column after the built-in name column. */
interface GanttColumn {
/** Stable id; doubles as the default header label. */
id: string;
/** Header label. */
title?: ReactNode;
/** Fixed column width in px. Default 96. */
width?: number;
/** Cell content alignment. Default "start". */
align?: 'start' | 'center' | 'end';
/** Cell content per row; omit or return null for an empty cell. */
render?: (ctx: GanttColumnContext) => ReactNode;
/** Extra classes on every cell of this column (header included). */
className?: string;
}
/** Pointer-activation thresholds; unset keys keep the dnd-kit parity defaults. */
interface GanttActivationConfig {
/** Mouse travel (px) before a bar move starts. Default 5. */
moveDistancePx?: number;
/** Mouse travel (px) before a drag-create starts. Default 4. */
createDistancePx?: number;
/** Touch long-press delay in ms. Default 250. */
touchDelayMs?: number;
/** Touch movement tolerance (px) during the long-press. Default 5. */
touchTolerancePx?: number;
}
/** Layout metrics (rem unless noted); every knob falls back to its default. */
/** A gridline: false to hide it, true for the default solid stroke, or a style. */
type GanttGridLine = boolean | 'solid' | 'dashed';
interface GanttTimelineLines {
/** Unit boundary lines running down the timeline. Default solid. */
vertical?: GanttGridLine;
/** Row separator lines running across the timeline. Default solid. */
horizontal?: GanttGridLine;
}
/** Resolved stroke per axis; null means the axis draws nothing. */
interface GanttResolvedLines {
vertical: 'solid' | 'dashed' | null;
horizontal: 'solid' | 'dashed' | null;
}
/**
* One place decides what the grid draws, so the header lines, the body lines
* and the row separators can never disagree.
*/
function resolveTimelineLines(value: GanttTimelineLines | 'vertical' | 'both' | 'none' | undefined): GanttResolvedLines {
if (value === 'none') return { vertical: null, horizontal: null };
if (value === 'vertical') return { vertical: 'solid', horizontal: null };
if (value === 'both' || value === undefined) {
return { vertical: 'solid', horizontal: 'solid' };
}
const stroke = (line: GanttGridLine | undefined) => (line === false ? null : line === true || line === undefined ? 'solid' : line);
return {
vertical: stroke(value.vertical),
horizontal: stroke(value.horizontal),
};
}
interface GanttMetrics {
/** Height of one schedule bar. Default 1.25. */
laneHeight?: number;
/** Gap between stacked schedules in one node. Default 0.1875. */
laneGap?: number;
/**
* Vertical inset between the row's edges and its block of schedules - the
* breathing room around the stack, kept separate from laneGap so schedules
* in one node can sit tight without cramping the row. Default 0.5.
*/
rowPadding?: number;
/** Minimum row height. Default 2.5. */
minRowHeight?: number;
/**
* Drag-drop indicator height, centered in its lane band and published on
* the ghost as --gantt-ghost-height so consumer styling can read the same
* number. Default 1.25.
*/
ghostHeight?: number;
/** barLabel "auto" flips the title outside below this bar width. Default 7. */
autoLabelMin?: number;
/** Unit width at zoom 1, per scale. Day scale = width per interval unit. */
unitWidths?: Partial<Record<GanttScale, number>>;
/** Minimum timeline pane width in px. Default 200. */
minTimelineWidth?: number;
/** Scroll distance (px) from an edge that grows the range. Default 160. */
infiniteScrollEdge?: number;
}
/** Live gesture snapshot handed to the drag/resize indicator render props. */
interface GanttDragIndicatorProps<TData = unknown> {
occurrence: GanttOccurrence<TData>;
kind: 'move' | 'resize-start' | 'resize-end';
/** Proposed (snapped) range of the current gesture step. */
start: Date;
end: Date;
valid: boolean;
/** The event's planned (baseline) window, so a custom overlay can keep
* drawing it mid-gesture; null when the event carries none. */
baseline: GanttBaseline | null;
}
/** Slot handed to a custom schedule-hint renderer. */
interface GanttScheduleHintProps {
start: Date;
end: Date;
resource: GanttResource;
}
/** Parent rollup handed to a custom summary renderer. */
interface GanttSummaryProps {
resource: GanttResource;
start: Date;
end: Date;
progress: number | null;
}
/** Planned window handed to a custom baseline renderer. */
interface GanttBaselineProps<TData = unknown> {
event: GanttEvent<TData>;
start: Date;
end: Date;
/** Planned start and end coincide: a point in the plan, not a window. */
milestone: boolean;
variance: GanttBaselineVariance;
}
/** Planned NODE window handed to a custom row-baseline renderer. */
interface GanttRowBaselineProps {
resource: GanttResource;
start: Date;
end: Date;
/** Planned start and end coincide: a point in the plan, not a window. */
milestone: boolean;
/** Latest actual end across the node's (and, for a group, its subtree's)
* events against the planned end; null when there is nothing to compare. */
variance: GanttBaselineVariance | null;
}
/** Left tree-panel sizing and splitter behavior. */
interface GanttTreePanelConfig {
/** Initial panel width in px. Default 288. */
width?: number;
/** Splitter lower bound in px. Default 180. */
minWidth?: number;
/** Splitter upper bound in px. Default 640. */
maxWidth?: number;
/** Drag/keyboard splitter between the panels. Default true. */
resizable?: boolean;
/** Width of the sticky name column in px. Default 208. */
nameColumnWidth?: number;
/** Fires after any user resize (drag release, keyboard, double-click reset). */
onWidthChange?: (width: number) => void;
}
interface GanttRenderEventProps<TData = unknown> {
occurrence: GanttOccurrence<TData>;
segment: GanttSegment<TData>;
isDragging: boolean;
isSelected: boolean;
}
/**
* View-layer configuration: display props and render overrides. These live on
* <Gantt> (and per-view components), never in the headless options.
*/
interface GanttViewConfig<TData = unknown> {
/** Red now-line on the axis. */
nowIndicator: boolean;
/**
* Day-scale unit interval in minutes: axis units and gridlines follow it.
*/
interval: number;
/**
* Scroll implementation for the gantt body: "custom" (default, shadcn
* ScrollArea) or "native" (browser scrollbars via overflow auto).
*/
scrollbars: 'custom' | 'native';
/**
* Placement hint over empty timeline track: a validated, snapped tile that
* opens the schedule flow (onSlotClick, else onSelectSlot) at that day.
* Works on every scale. Default off.
*/
displayScheduleHint: boolean;
/**
* Where the viewport opens. `"now"` (default) centres the current instant
* when the anchor period contains it and falls back to the anchor; `"anchor"`
* always centres the anchor; a Date centres that instant.
*
* Only `"now"` follows the wall clock - which is right for a live board and
* wrong for a demo or a report, whose opening composition must not depend on
* the hour it is viewed at. Those pass an explicit instant.
*/
initialCenter: 'now' | 'anchor' | Date;
/**
* Empty-track presses on schedulable rows start a drag-create gesture that
* commits through onSelectSlot. Default off: the whole panel drags-to-pan
* instead, and scheduling flows through the hint tile / onSlotClick.
*/
dragCreate: boolean;
/**
* "Add task" affordance at the foot of the tree that opens the create-task
* flow (onCreateTask). Shown only when canCreateTask allows it. Default off.
*/
displayCreateTaskHint: boolean;
/** Floating zoom in/out control over the track. Default on. */
zoomControl: boolean;
/**
* Ctrl/Cmd + wheel over the timeline zooms the time range, anchored on the
* pointer. Trackpad pinch arrives as the same event (browsers set ctrlKey
* on it), so this is also the pinch-to-zoom switch. Default on. The gesture
* is handed back to the browser at the zoom limits, so page zoom still
* works there.
*/
wheelZoom: boolean;
/** Nav button variant; all nav buttons follow it. Default "ghost". */
navButtonVariant: 'ghost' | 'outline' | 'secondary' | 'default';
/** Nav button size; icon buttons use the icon twin. Default "sm". */
navButtonSize: 'sm' | 'default';
/**
* Off-day (non-working day) marking on day/week/month scales. true =
* weekends with a muted background; a config object customizes weekdays,
* explicit dates, a predicate, and the marker class.
*/
offDays?: boolean | GanttOffDaysConfig;
/**
* Extra tree-panel columns after the built-in name column. The tree panel
* scrolls horizontally when the columns outgrow it; the name column stays
* pinned.
*/
columns?: GanttColumn[];
/**
* Consumer slot pinned at the end of the tree-panel header - the intended
* home for an add/remove-columns dropdown menu.
*/
columnsMenu?: ReactNode;
/** Tree-panel width, splitter bounds, and resizability. */
treePanel?: GanttTreePanelConfig;
/**
* Timeline gridlines. The object form controls the two axes independently
* and gives each its own stroke: `{ vertical: "dashed", horizontal: true }`.
* An omitted axis stays on and solid. `true` means solid.
*
* The three legacy shorthands still work: "none" (bare), "vertical" (unit
* boundaries only, rows separated by whitespace) and "both" (adds row
* separators).
*/
timelineLines: GanttTimelineLines | 'vertical' | 'both' | 'none';
/**
* Bar title placement: "inside" (default) renders it in the bar, "outside"
* beside the bar, "auto" moves it outside only when the bar is too short.
*/
barLabel: 'inside' | 'outside' | 'auto';
/** Edge chips that scroll to bars outside the visible timeline. Default true. */
offscreenIndicators: boolean;
/**
* Extend the timeline into the past/future while scrolling near an edge
* (the anchor period stays the nav title). Default true.
*/
infiniteScroll: boolean;
/** Zoom bounds and button step for the floating control. Default 0.5 - 3, step 0.25. */
zoomRange?: { min?: number; max?: number; step?: number };
/** Layout metric overrides (row/lane/unit geometry, thresholds). */
metrics?: GanttMetrics;
/** Sticky nav bar (same contract as the event calendar). Default false. */
stickyNav: boolean;
/**
* Leaf-row selection checkboxes in the tree panel. Default true;
* uncontrolled unless selectedRows is passed.
*/
rowCheckboxes: boolean;
/** Controlled selected row ids; pairs with onSelectedRowsChange. */
selectedRows?: string[];
onSelectedRowsChange?: (ids: string[]) => void;
/** Controlled collapsed group ids; pairs with onCollapsedGroupsChange. */
collapsedGroups?: string[];
/** Initial collapsed group ids (uncontrolled). */
defaultCollapsedGroups?: string[];
onCollapsedGroupsChange?: (ids: string[]) => void;
/** Controlled zoom multiplier; pairs with onZoomChange. */
zoom?: number;
/** Initial zoom multiplier (uncontrolled). Default 1. */
defaultZoom?: number;
onZoomChange?: (zoom: number) => void;
/**
* Allow drag-create and slot clicks on rows that have children. Default
* false: parents aggregate their subtree instead of owning bars.
*/
parentScheduling: boolean;
/**
* Rollup strips on parent rows without bars of their own: the envelope of
* descendant bars with duration-weighted progress. Default true.
*/
summaryBars: boolean;
/**
* As-built comparison: the planned window of every bar carrying
* baselineStart/baselineEnd, ghosted behind it on its own lane (equal
* instants draw a planned milestone diamond), and of every NODE whose
* GanttResource carries the same pair, drawn as a band behind its lanes.
* Display only - dragging a bar moves the actual dates and never its
* baseline. Default true; rows and events without baseline data draw
* nothing.
*/
baselineBars: boolean;
/**
* Finish-to-start arrows between bars whose events name `dependencies`.
* Drawn from the predecessor's end into the dependent's start, under the
* bars; endpoints on hidden rows are skipped. Default true; nothing
* renders when no visible event names a dependency.
*/
dependencyLines: boolean;
/**
* How many schedules a tree node may hold. "multiple" (default) stacks
* concurrent schedules into stable lanes and grows the row; "single" keeps
* one track per node - the task-gantt shape. Any node can override it with
* its own `scheduleMode`.
*/
scheduleMode: GanttScheduleMode;
/**
* Vertical placement of a row's content once a node holds several lanes.
* "start" (default) keeps the tree label on the baseline of the FIRST
* schedule; "center" centers both against the grown row.
*/
rowAlign: GanttRowAlign;
classNames?: GanttClassNames;
renderEvent?: (props: GanttRenderEventProps<TData>) => ReactNode;
/**
* Right-click menu for a bar: return shadcn ContextMenu items (the primitive
* wraps every bar in a ContextMenu and renders this as its content). Read
* the occurrence for the subject and drive actions through the gantt api
* (useGantt) or your own state - fully headless. Omit for no menu.
*/
renderEventMenu?: (props: GanttRenderEventProps<TData>) => ReactNode;
/**
* Tree-node label. Receives the resource with its tree position; return
* any rich content (icons, badges). Default is the plain title.
*/
renderResourceLabel?: (props: { resource: GanttResource; depth: number; isGroup: boolean; collapsed: boolean }) => ReactNode;
/**
* Right-click menu for a tree row (same contract as renderEventMenu):
* return shadcn ContextMenu items and drive actions through your own state.
*/
renderResourceMenu?: (ctx: GanttColumnContext) => ReactNode;
/** Rendered in the timeline body when there are no resources. */
renderNoResources?: () => ReactNode;
/**
* Replaces the smooth cursor-following MOVE clone. Content is React and
* re-renders per snap step; the gantt owns the fixed wrapper and writes
* its position imperatively per pointermove (no per-frame React).
*/
renderDragPreview?: (props: GanttDragIndicatorProps<TData>) => ReactNode;
/**
* Replaces the RESIZE edge line + status chip. Same positioning contract
* as renderDragPreview: your content, gantt-owned cursor tracking.
*/
renderResizeIndicator?: (props: GanttDragIndicatorProps<TData>) => ReactNode;
/**
* Replaces the schedule-hint tile + bubble. Rendered inside the snapped,
* validated, pointer-transparent wrapper: set pointer-events-auto on your
* clickable parts and drive your own create flow from the slot.
*/
renderScheduleHint?: (props: GanttScheduleHintProps) => ReactNode;
/** Replaces the parent rollup strip (the positioned wrapper stays gantt-owned). */
renderSummary?: (props: GanttSummaryProps) => ReactNode;
/**
* Replaces the baseline ghost's content, the milestone diamond included
* (props.milestone forks the two). The positioned, pointer-transparent
* wrapper stays gantt-owned.
*/
renderBaseline?: (props: GanttBaselineProps<TData>) => ReactNode;
/**
* Replaces the ROW baseline band's content (same wrapper contract as
* renderBaseline).
*/
renderRowBaseline?: (props: GanttRowBaselineProps) => ReactNode;
/**
* Replaces the rollup MATH: return 0-100 (or null to hide) for a group
* from its descendant events. Default: duration-weighted mean progress.
*/
getSummaryProgress?: (ctx: { resource: GanttResource; events: GanttEvent<TData>[] }) => number | null;
}
const DEFAULT_VIEW_CONFIG: GanttViewConfig = {
nowIndicator: true,
interval: 60,
scrollbars: 'custom',
displayScheduleHint: false,
initialCenter: 'now',
displayCreateTaskHint: false,
dragCreate: false,
zoomControl: true,
wheelZoom: true,
navButtonVariant: 'ghost',
navButtonSize: 'sm',
timelineLines: 'vertical',
barLabel: 'inside',
offscreenIndicators: true,
infiniteScroll: true,
stickyNav: false,
rowCheckboxes: true,
parentScheduling: false,
summaryBars: true,
baselineBars: true,
dependencyLines: true,
scheduleMode: 'multiple',
rowAlign: 'start',
};
const GanttViewConfigContext = createContext<
// eslint-disable-next-line @typescript-eslint/no-explicit-any
GanttViewConfig<any>
>(DEFAULT_VIEW_CONFIG);
/** Root-level display props + render overrides, for view components. */
function useGanttViewConfig<TData = unknown>(): GanttViewConfig<TData> {
return useContext(GanttViewConfigContext);
}
const VIEW_CONFIG_KEYS: Array<keyof GanttViewConfig> = [
'nowIndicator',
'interval',
'scrollbars',
'displayScheduleHint',
'initialCenter',
'displayCreateTaskHint',
'dragCreate',
'zoomControl',
'wheelZoom',
'navButtonVariant',
'navButtonSize',
'offDays',
'columns',
'columnsMenu',
'treePanel',
'metrics',
'timelineLines',
'barLabel',
'offscreenIndicators',
'infiniteScroll',
'zoomRange',
'stickyNav',
'rowCheckboxes',
'selectedRows',
'onSelectedRowsChange',
'collapsedGroups',
'defaultCollapsedGroups',
'onCollapsedGroupsChange',
'zoom',
'defaultZoom',
'onZoomChange',
'parentScheduling',
'summaryBars',
'baselineBars',
'dependencyLines',
'scheduleMode',
'rowAlign',
'classNames',
'renderEvent',
'renderEventMenu',
'renderResourceLabel',
'renderResourceMenu',
'renderNoResources',
'renderDragPreview',
'renderResizeIndicator',
'renderScheduleHint',
'renderSummary',
'renderBaseline',
'renderRowBaseline',
'getSummaryProgress',
];
interface GanttProps<TData = unknown>
extends UseGanttStateOptions<TData>, Partial<GanttViewConfig<TData>>, Omit<useRender.ComponentProps<'div'>, 'children' | 'defaultValue'> {
/** Adopt a hoisted useGanttState instance; option props are then ignored. */
calendar?: GanttInstance<TData>;
/** Imperative escape hatch usable from outside the tree. */
apiRef?: RefObject<GanttApi<TData> | null>;
children?: ReactNode;
}
const OPTION_KEYS: Array<keyof UseGanttStateOptions> = [
'events',
'defaultEvents',
'scale',
'defaultScale',
'date',
'defaultDate',
'selection',
'defaultSelection',
'interactions',
'defaultInteractions',
'loading',
'timeZone',
'locale',
'weekStartsOn',
'slotDuration',
'snapDuration',
'i18n',
'rangeBounds',
'activation',
'maxRangeWindow',
'resources',
'overlap',
'enforceCanDrop',
'getEventPriority',
'eventOrder',
'getOccurrences',
'onEventClick',
'onEventDoubleClick',
'onEventUpdate',
'canDropEvent',
'onSlotClick',
'onSelectSlot',
'canSelectSlot',
'onCreateTask',
'canCreateTask',
'onResourceClick',
'onResourceDoubleClick',
'onRangeChange',
'onScaleChange',
'onDateChange',
'onSelectionChange',
'onInteractionsChange',
'onEventsChange',
'onResourceReorder',
'onResourceReorderReject',
'canReorderResource',
];
function shallowEqualRecord(a: Record<string, unknown>, b: Record<string, unknown>): boolean {
const aKeys = Object.keys(a);
if (aKeys.length !== Object.keys(b).length) return false;
for (const key of aKeys) {
if (!Object.is(a[key], b[key])) return false;
}
return true;
}
function splitOptions<TData>(props: Record<string, unknown>): {
options: UseGanttStateOptions<TData>;
viewConfig: GanttViewConfig<TData>;
rest: Record<string, unknown>;
} {
const options: Record<string, unknown> = {};
const viewConfig: Record<string, unknown> = { ...DEFAULT_VIEW_CONFIG };
const rest: Record<string, unknown> = {};
for (const [key, value] of Object.entries(props)) {
if ((OPTION_KEYS as string[]).includes(key)) options[key] = value;
else if ((VIEW_CONFIG_KEYS as string[]).includes(key)) {
if (value !== undefined) viewConfig[key] = value;
} else rest[key] = value;
}
return {
options: options as UseGanttStateOptions<TData>,
viewConfig: viewConfig as unknown as GanttViewConfig<TData>,
rest,
};
}
/**
* Root provider + container. Composition contract:
* <Gantt><GanttNav/><GanttToolbar/><GanttView/></Gantt>
*/
function Gantt<TData = unknown>({ calendar, apiRef, className, render, children, ...props }: GanttProps<TData>) {
const { options, viewConfig, rest } = splitOptions<TData>(props as Record<string, unknown>);
// Stable context identity: splitOptions builds a fresh object per render,
// and every row subscribes to this context - hand out the previous object
// unless a config value actually changed.
const viewConfigRef = useRef(viewConfig);
if (!shallowEqualRecord(viewConfigRef.current as unknown as Record<string, unknown>, viewConfig as unknown as Record<string, unknown>)) {
viewConfigRef.current = viewConfig;
}
const stableViewConfig = viewConfigRef.current;
if (calendar && Object.keys(options).length > 0) {
warnOnce('calendar-and-options', 'both `calendar` and option props were passed; option props are ignored when adopting an instance.');
}
const own = useGanttState<TData>(calendar ? {} : options);
const instance = calendar ?? own;
useEffect(() => {
if (apiRef) apiRef.current = instance.api;
}, [apiRef, instance]);
const defaultProps = {
'data-slot': 'gantt',
// own the foreground (previews and consumer shells may not set body
// color) and the type scale: every gantt label inherits the root's text
// size, so one class here (or on the consumer's className) rescales the
// whole component - e.g. className="text-sm" for a roomier grid
className: cn('text-foreground flex min-h-0 min-w-0 flex-col text-xs', className),
children: (
<>
{children}
<div data-slot="gantt-announcer" aria-live="polite" className="sr-only" />
</>
),
};
return (
<GanttContext.Provider value={instance}>
<GanttViewConfigContext.Provider value={stableViewConfig}>
{useRender({
defaultTagName: 'div',
render,
props: mergeProps<'div'>(defaultProps, rest),
})}
</GanttViewConfigContext.Provider>
</GanttContext.Provider>
);
}
export {
DEFAULT_ROW_ALIGN,
DEFAULT_SCHEDULE_MODE,
DEFAULT_VIEW_CONFIG,
Gantt,
GanttContext,
GanttViewConfigContext,
resolveScheduleMode,
resolveTimelineLines,
useGantt,
useGanttInteractions,
useGanttNavigation,
useGanttNodeSchedules,
useGanttOccurrences,
useGanttScale,
useGanttSelection,
useGanttSelector,
useGanttSettings,
useGanttSettingsVersion,
useGanttState,
useGanttViewConfig,
};
export type {
GanttActivationConfig,
GanttApi,
GanttBaselineProps,
GanttCallbacks,
GanttClassNames,
GanttColumn,
GanttColumnContext,
GanttDragIndicatorProps,
GanttGridLine,
GanttInstance,
GanttInternals,
GanttMetrics,
GanttNodeSchedules,
GanttProps,
GanttRenderEventProps,
GanttResolvedLines,
GanttRowBaselineProps,
GanttScheduleHintProps,
GanttSettings,
GanttSummaryProps,
GanttTimelineLines,
GanttTreePanelConfig,
GanttViewConfig,
UseGanttStateOptions,
};Usage
import { DEFAULT_ROW_ALIGN, DEFAULT_SCHEDULE_MODE, DEFAULT_VIEW_CONFIG, Gantt, GanttContext, GanttViewConfigContext } from "@/components/ui/gantt/gantt"Exports
DEFAULT_ROW_ALIGN, DEFAULT_SCHEDULE_MODE, DEFAULT_VIEW_CONFIG, Gantt, GanttContext, GanttViewConfigContext, useGantt, useGanttInteractions, useGanttNavigation, useGanttNodeSchedules, useGanttOccurrences, useGanttScale, useGanttSelection, useGanttSelector, useGanttSettings, useGanttSettingsVersion, useGanttState, useGanttViewConfig
Dependencies
@base-ui/react@^1.9.0(npm)@date-fns/tz@^1.5.0(npm)date-fns@^4.4.0(npm)lucide-react@^1.80.0(npm)@vcare/button(registry)@vcare/calendar(registry)@vcare/checkbox(registry)@vcare/context-menu(registry)@vcare/dropdown-menu(registry)@vcare/popover(registry)@vcare/tooltip(registry)@vcare/utils(registry)
Raw item: /r/gantt.json