The Gantt chart is a powerful tool for visualizing project schedules and tracking the progress of tasks. It provides a clear, hierarchical view of tasks, allowing you to easily identify manage project timelines.
1"use client";
2
3import {
4 DndContext,
5 MouseSensor,
6 useDraggable,
7 useSensor,
8} from "@dnd-kit/core";
9import { restrictToHorizontalAxis } from "@dnd-kit/modifiers";
10import { useMouse, useThrottle, useWindowScroll } from "@uidotdev/usehooks";
11import {
12 addDays,
13 addMonths,
14 differenceInDays,
15 differenceInHours,
16 differenceInMonths,
17 endOfDay,
18 endOfMonth,
19 format,
20 formatDate,
21 formatDistance,
22 getDate,
23 getDaysInMonth,
24 isSameDay,
25 startOfDay,
26 startOfMonth,
27} from "date-fns";
28import { atom, useAtom } from "jotai";
29import throttle from "lodash.throttle";
30import { PlusIcon, TrashIcon } from "lucide-react";
31import type {
32 CSSProperties,
33 FC,
34 KeyboardEventHandler,
35 MouseEventHandler,
36 ReactNode,
37 RefObject,
38} from "react";
39import {
40 createContext,
41 memo,
42 useCallback,
43 useContext,
44 useEffect,
45 useId,
46 useMemo,
47 useRef,
48 useState,
49} from "react";
50import { Card } from "@/components/ui/card";
51import {
52 ContextMenu,
53 ContextMenuContent,
54 ContextMenuItem,
55 ContextMenuTrigger,
56} from "@/components/ui/context-menu";
57import { cn } from "@/lib/utils";
58
59const draggingAtom = atom(false);
60const scrollXAtom = atom(0);
61
62export const useGanttDragging = () => useAtom(draggingAtom);
63export const useGanttScrollX = () => useAtom(scrollXAtom);
64
65export type GanttStatus = {
66 id: string;
67 name: string;
68 color: string;
69};
70
71export type GanttFeature = {
72 id: string;
73 name: string;
74 startAt: Date;
75 endAt: Date;
76 status: GanttStatus;
77 lane?: string; // Optional: features with the same lane will share a row
78};
79
80export type GanttMarkerProps = {
81 id: string;
82 date: Date;
83 label: string;
84};
85
86export type Range = "daily" | "monthly" | "quarterly";
87
88export type TimelineData = {
89 year: number;
90 quarters: {
91 months: {
92 days: number;
93 }[];
94 }[];
95}[];
96
97export type GanttContextProps = {
98 zoom: number;
99 range: Range;
100 columnWidth: number;
101 sidebarWidth: number;
102 headerHeight: number;
103 rowHeight: number;
104 onAddItem: ((date: Date) => void) | undefined;
105 placeholderLength: number;
106 timelineData: TimelineData;
107 ref: RefObject<HTMLDivElement | null> | null;
108 scrollToFeature?: (feature: GanttFeature) => void;
109};
110
111const getsDaysIn = (range: Range) => {
112 // For when range is daily
113 let fn = (_date: Date) => 1;
114
115 if (range === "monthly" || range === "quarterly") {
116 fn = getDaysInMonth;
117 }
118
119 return fn;
120};
121
122const getDifferenceIn = (range: Range) => {
123 let fn = differenceInDays;
124
125 if (range === "monthly" || range === "quarterly") {
126 fn = differenceInMonths;
127 }
128
129 return fn;
130};
131
132const getInnerDifferenceIn = (range: Range) => {
133 let fn = differenceInHours;
134
135 if (range === "monthly" || range === "quarterly") {
136 fn = differenceInDays;
137 }
138
139 return fn;
140};
141
142const getStartOf = (range: Range) => {
143 let fn = startOfDay;
144
145 if (range === "monthly" || range === "quarterly") {
146 fn = startOfMonth;
147 }
148
149 return fn;
150};
151
152const getEndOf = (range: Range) => {
153 let fn = endOfDay;
154
155 if (range === "monthly" || range === "quarterly") {
156 fn = endOfMonth;
157 }
158
159 return fn;
160};
161
162const getAddRange = (range: Range) => {
163 let fn = addDays;
164
165 if (range === "monthly" || range === "quarterly") {
166 fn = addMonths;
167 }
168
169 return fn;
170};
171
172const getDateByMousePosition = (context: GanttContextProps, mouseX: number) => {
173 const timelineStartDate = new Date(context.timelineData[0].year, 0, 1);
174 const columnWidth = (context.columnWidth * context.zoom) / 100;
175 const offset = Math.floor(mouseX / columnWidth);
176 const daysIn = getsDaysIn(context.range);
177 const addRange = getAddRange(context.range);
178 const month = addRange(timelineStartDate, offset);
179 const daysInMonth = daysIn(month);
180 const pixelsPerDay = Math.round(columnWidth / daysInMonth);
181 const dayOffset = Math.floor((mouseX % columnWidth) / pixelsPerDay);
182 const actualDate = addDays(month, dayOffset);
183
184 return actualDate;
185};
186
187const createInitialTimelineData = (today: Date) => {
188 const data: TimelineData = [];
189
190 data.push(
191 { year: today.getFullYear() - 1, quarters: new Array(4).fill(null) },
192 { year: today.getFullYear(), quarters: new Array(4).fill(null) },
193 { year: today.getFullYear() + 1, quarters: new Array(4).fill(null) }
194 );
195
196 for (const yearObj of data) {
197 yearObj.quarters = new Array(4).fill(null).map((_, quarterIndex) => ({
198 months: new Array(3).fill(null).map((_, monthIndex) => {
199 const month = quarterIndex * 3 + monthIndex;
200 return {
201 days: getDaysInMonth(new Date(yearObj.year, month, 1)),
202 };
203 }),
204 }));
205 }
206
207 return data;
208};
209
210const getOffset = (
211 date: Date,
212 timelineStartDate: Date,
213 context: GanttContextProps
214) => {
215 const parsedColumnWidth = (context.columnWidth * context.zoom) / 100;
216 const differenceIn = getDifferenceIn(context.range);
217 const startOf = getStartOf(context.range);
218 const fullColumns = differenceIn(startOf(date), timelineStartDate);
219
220 if (context.range === "daily") {
221 return parsedColumnWidth * fullColumns;
222 }
223
224 const partialColumns = date.getDate();
225 const daysInMonth = getDaysInMonth(date);
226 const pixelsPerDay = parsedColumnWidth / daysInMonth;
227
228 return fullColumns * parsedColumnWidth + partialColumns * pixelsPerDay;
229};
230
231const getWidth = (
232 startAt: Date,
233 endAt: Date | null,
234 context: GanttContextProps
235) => {
236 const parsedColumnWidth = (context.columnWidth * context.zoom) / 100;
237
238 if (!endAt) {
239 return parsedColumnWidth * 2;
240 }
241
242 const differenceIn = getDifferenceIn(context.range);
243
244 if (context.range === "daily") {
245 const delta = differenceIn(endAt, startAt);
246
247 return parsedColumnWidth * (delta ? delta : 1);
248 }
249
250 const daysInStartMonth = getDaysInMonth(startAt);
251 const pixelsPerDayInStartMonth = parsedColumnWidth / daysInStartMonth;
252
253 if (isSameDay(startAt, endAt)) {
254 return pixelsPerDayInStartMonth;
255 }
256
257 const innerDifferenceIn = getInnerDifferenceIn(context.range);
258 const startOf = getStartOf(context.range);
259
260 if (isSameDay(startOf(startAt), startOf(endAt))) {
261 return innerDifferenceIn(endAt, startAt) * pixelsPerDayInStartMonth;
262 }
263
264 const startRangeOffset = daysInStartMonth - getDate(startAt);
265 const endRangeOffset = getDate(endAt);
266 const fullRangeOffset = differenceIn(startOf(endAt), startOf(startAt));
267 const daysInEndMonth = getDaysInMonth(endAt);
268 const pixelsPerDayInEndMonth = parsedColumnWidth / daysInEndMonth;
269
270 return (
271 (fullRangeOffset - 1) * parsedColumnWidth +
272 startRangeOffset * pixelsPerDayInStartMonth +
273 endRangeOffset * pixelsPerDayInEndMonth
274 );
275};
276
277const calculateInnerOffset = (
278 date: Date,
279 range: Range,
280 columnWidth: number
281) => {
282 const startOf = getStartOf(range);
283 const endOf = getEndOf(range);
284 const differenceIn = getInnerDifferenceIn(range);
285 const startOfRange = startOf(date);
286 const endOfRange = endOf(date);
287 const totalRangeDays = differenceIn(endOfRange, startOfRange);
288 const dayOfMonth = date.getDate();
289
290 return (dayOfMonth / totalRangeDays) * columnWidth;
291};
292
293const GanttContext = createContext<GanttContextProps>({
294 zoom: 100,
295 range: "monthly",
296 columnWidth: 50,
297 headerHeight: 60,
298 sidebarWidth: 300,
299 rowHeight: 36,
300 onAddItem: undefined,
301 placeholderLength: 2,
302 timelineData: [],
303 ref: null,
304 scrollToFeature: undefined,
305});
306
307export type GanttContentHeaderProps = {
308 renderHeaderItem: (index: number) => ReactNode;
309 title: string;
310 columns: number;
311};
312
313export const GanttContentHeader: FC<GanttContentHeaderProps> = ({
314 title,
315 columns,
316 renderHeaderItem,
317}) => {
318 const id = useId();
319
320 return (
321 <div
322 className="sticky top-0 z-20 grid w-full shrink-0 bg-backdrop/90 backdrop-blur-sm"
323 style={{ height: "var(--gantt-header-height)" }}
324 >
325 <div>
326 <div
327 className="sticky inline-flex whitespace-nowrap px-3 py-2 text-muted-foreground text-xs"
328 style={{
329 left: "var(--gantt-sidebar-width)",
330 }}
331 >
332 <p>{title}</p>
333 </div>
334 </div>
335 <div
336 className="grid w-full"
337 style={{
338 gridTemplateColumns: `repeat(${columns}, var(--gantt-column-width))`,
339 }}
340 >
341 {Array.from({ length: columns }).map((_, index) => (
342 <div
343 className="shrink-0 border-border/50 border-b py-1 text-center text-xs"
344 key={`${id}-${index}`}
345 >
346 {renderHeaderItem(index)}
347 </div>
348 ))}
349 </div>
350 </div>
351 );
352};
353
354const DailyHeader: FC = () => {
355 const gantt = useContext(GanttContext);
356
357 return gantt.timelineData.map((year) =>
358 year.quarters
359 .flatMap((quarter) => quarter.months)
360 .map((month, index) => (
361 <div className="relative flex flex-col" key={`${year.year}-${index}`}>
362 <GanttContentHeader
363 columns={month.days}
364 renderHeaderItem={(item: number) => (
365 <div className="flex items-center justify-center gap-1">
366 <p>
367 {format(addDays(new Date(year.year, index, 1), item), "d")}
368 </p>
369 <p className="text-muted-foreground">
370 {format(
371 addDays(new Date(year.year, index, 1), item),
372 "EEEEE"
373 )}
374 </p>
375 </div>
376 )}
377 title={format(new Date(year.year, index, 1), "MMMM yyyy")}
378 />
379 <GanttColumns
380 columns={month.days}
381 isColumnSecondary={(item: number) =>
382 [0, 6].includes(
383 addDays(new Date(year.year, index, 1), item).getDay()
384 )
385 }
386 />
387 </div>
388 ))
389 );
390};
391
392const MonthlyHeader: FC = () => {
393 const gantt = useContext(GanttContext);
394
395 return gantt.timelineData.map((year) => (
396 <div className="relative flex flex-col" key={year.year}>
397 <GanttContentHeader
398 columns={year.quarters.flatMap((quarter) => quarter.months).length}
399 renderHeaderItem={(item: number) => (
400 <p>{format(new Date(year.year, item, 1), "MMM")}</p>
401 )}
402 title={`${year.year}`}
403 />
404 <GanttColumns
405 columns={year.quarters.flatMap((quarter) => quarter.months).length}
406 />
407 </div>
408 ));
409};
410
411const QuarterlyHeader: FC = () => {
412 const gantt = useContext(GanttContext);
413
414 return gantt.timelineData.map((year) =>
415 year.quarters.map((quarter, quarterIndex) => (
416 <div
417 className="relative flex flex-col"
418 key={`${year.year}-${quarterIndex}`}
419 >
420 <GanttContentHeader
421 columns={quarter.months.length}
422 renderHeaderItem={(item: number) => (
423 <p>
424 {format(new Date(year.year, quarterIndex * 3 + item, 1), "MMM")}
425 </p>
426 )}
427 title={`Q${quarterIndex + 1} ${year.year}`}
428 />
429 <GanttColumns columns={quarter.months.length} />
430 </div>
431 ))
432 );
433};
434
435const headers: Record<Range, FC> = {
436 daily: DailyHeader,
437 monthly: MonthlyHeader,
438 quarterly: QuarterlyHeader,
439};
440
441export type GanttHeaderProps = {
442 className?: string;
443};
444
445export const GanttHeader: FC<GanttHeaderProps> = ({ className }) => {
446 const gantt = useContext(GanttContext);
447 const Header = headers[gantt.range];
448
449 return (
450 <div
451 className={cn(
452 "-space-x-px flex h-full w-max divide-x divide-border/50",
453 className
454 )}
455 >
456 <Header />
457 </div>
458 );
459};
460
461export type GanttSidebarItemProps = {
462 feature: GanttFeature;
463 onSelectItem?: (id: string) => void;
464 className?: string;
465};
466
467export const GanttSidebarItem: FC<GanttSidebarItemProps> = ({
468 feature,
469 onSelectItem,
470 className,
471}) => {
472 const gantt = useContext(GanttContext);
473 const tempEndAt =
474 feature.endAt && isSameDay(feature.startAt, feature.endAt)
475 ? addDays(feature.endAt, 1)
476 : feature.endAt;
477 const duration = tempEndAt
478 ? formatDistance(feature.startAt, tempEndAt)
479 : `${formatDistance(feature.startAt, new Date())} so far`;
480
481 const handleClick: MouseEventHandler<HTMLDivElement> = (event) => {
482 if (event.target === event.currentTarget) {
483 // Scroll to the feature in the timeline
484 gantt.scrollToFeature?.(feature);
485 // Call the original onSelectItem callback
486 onSelectItem?.(feature.id);
487 }
488 };
489
490 const handleKeyDown: KeyboardEventHandler<HTMLDivElement> = (event) => {
491 if (event.key === "Enter") {
492 // Scroll to the feature in the timeline
493 gantt.scrollToFeature?.(feature);
494 // Call the original onSelectItem callback
495 onSelectItem?.(feature.id);
496 }
497 };
498
499 return (
500 <div
501 className={cn(
502 "relative flex items-center gap-2.5 p-2.5 text-xs hover:bg-secondary",
503 className
504 )}
505 key={feature.id}
506 onClick={handleClick}
507 onKeyDown={handleKeyDown}
508 // biome-ignore lint/a11y/useSemanticElements: "This is a clickable item"
509 role="button"
510 style={{
511 height: "var(--gantt-row-height)",
512 }}
513 tabIndex={0}
514 >
515 {/* <Checkbox onCheckedChange={handleCheck} className="shrink-0" /> */}
516 <div
517 className="pointer-events-none h-2 w-2 shrink-0 rounded-full"
518 style={{
519 backgroundColor: feature.status.color,
520 }}
521 />
522 <p className="pointer-events-none flex-1 truncate text-left font-medium">
523 {feature.name}
524 </p>
525 <p className="pointer-events-none text-muted-foreground">{duration}</p>
526 </div>
527 );
528};
529
530export const GanttSidebarHeader: FC = () => (
531 <div
532 className="sticky top-0 z-10 flex shrink-0 items-end justify-between gap-2.5 border-border/50 border-b bg-backdrop/90 p-2.5 font-medium text-muted-foreground text-xs backdrop-blur-sm"
533 style={{ height: "var(--gantt-header-height)" }}
534 >
535 {/* <Checkbox className="shrink-0" /> */}
536 <p className="flex-1 truncate text-left">Issues</p>
537 <p className="shrink-0">Duration</p>
538 </div>
539);
540
541export type GanttSidebarGroupProps = {
542 children: ReactNode;
543 name: string;
544 className?: string;
545};
546
547export const GanttSidebarGroup: FC<GanttSidebarGroupProps> = ({
548 children,
549 name,
550 className,
551}) => (
552 <div className={className}>
553 <p
554 className="w-full truncate p-2.5 text-left font-medium text-muted-foreground text-xs"
555 style={{ height: "var(--gantt-row-height)" }}
556 >
557 {name}
558 </p>
559 <div className="divide-y divide-border/50">{children}</div>
560 </div>
561);
562
563export type GanttSidebarProps = {
564 children: ReactNode;
565 className?: string;
566};
567
568export const GanttSidebar: FC<GanttSidebarProps> = ({
569 children,
570 className,
571}) => (
572 <div
573 className={cn(
574 "sticky left-0 z-30 h-max min-h-full overflow-clip border-border/50 border-r bg-background/90 backdrop-blur-md",
575 className
576 )}
577 data-roadmap-ui="gantt-sidebar"
578 >
579 <GanttSidebarHeader />
580 <div className="space-y-4">{children}</div>
581 </div>
582);
583
584export type GanttAddFeatureHelperProps = {
585 top: number;
586 className?: string;
587};
588
589export const GanttAddFeatureHelper: FC<GanttAddFeatureHelperProps> = ({
590 top,
591 className,
592}) => {
593 const [scrollX] = useGanttScrollX();
594 const gantt = useContext(GanttContext);
595 const [mousePosition, mouseRef] = useMouse<HTMLDivElement>();
596
597 const handleClick = () => {
598 const ganttRect = gantt.ref?.current?.getBoundingClientRect();
599 const x =
600 mousePosition.x - (ganttRect?.left ?? 0) + scrollX - gantt.sidebarWidth;
601 const currentDate = getDateByMousePosition(gantt, x);
602
603 gantt.onAddItem?.(currentDate);
604 };
605
606 return (
607 <div
608 className={cn("absolute top-0 w-full px-0.5", className)}
609 ref={mouseRef}
610 style={{
611 marginTop: -gantt.rowHeight / 2,
612 transform: `translateY(${top}px)`,
613 }}
614 >
615 <button
616 className="flex h-full w-full items-center justify-center rounded-md border border-dashed p-2"
617 onClick={handleClick}
618 type="button"
619 >
620 <PlusIcon
621 className="pointer-events-none select-none text-muted-foreground"
622 size={16}
623 />
624 </button>
625 </div>
626 );
627};
628
629export type GanttColumnProps = {
630 index: number;
631 isColumnSecondary?: (item: number) => boolean;
632};
633
634export const GanttColumn: FC<GanttColumnProps> = ({
635 index,
636 isColumnSecondary,
637}) => {
638 const gantt = useContext(GanttContext);
639 const [dragging] = useGanttDragging();
640 const [mousePosition, mouseRef] = useMouse<HTMLDivElement>();
641 const [hovering, setHovering] = useState(false);
642 const [windowScroll] = useWindowScroll();
643
644 const handleMouseEnter = () => setHovering(true);
645 const handleMouseLeave = () => setHovering(false);
646
647 const top = useThrottle(
648 mousePosition.y -
649 (mouseRef.current?.getBoundingClientRect().y ?? 0) -
650 (windowScroll.y ?? 0),
651 10
652 );
653
654 return (
655 // biome-ignore lint/a11y/noStaticElementInteractions: "This is a clickable column"
656 // biome-ignore lint/nursery/noNoninteractiveElementInteractions: "This is a clickable column"
657 <div
658 className={cn(
659 "group relative h-full overflow-hidden",
660 isColumnSecondary?.(index) ? "bg-secondary" : ""
661 )}
662 onMouseEnter={handleMouseEnter}
663 onMouseLeave={handleMouseLeave}
664 ref={mouseRef}
665 >
666 {!dragging && hovering && gantt.onAddItem ? (
667 <GanttAddFeatureHelper top={top} />
668 ) : null}
669 </div>
670 );
671};
672
673export type GanttColumnsProps = {
674 columns: number;
675 isColumnSecondary?: (item: number) => boolean;
676};
677
678export const GanttColumns: FC<GanttColumnsProps> = ({
679 columns,
680 isColumnSecondary,
681}) => {
682 const id = useId();
683
684 return (
685 <div
686 className="divide grid h-full w-full divide-x divide-border/50"
687 style={{
688 gridTemplateColumns: `repeat(${columns}, var(--gantt-column-width))`,
689 }}
690 >
691 {Array.from({ length: columns }).map((_, index) => (
692 <GanttColumn
693 index={index}
694 isColumnSecondary={isColumnSecondary}
695 key={`${id}-${index}`}
696 />
697 ))}
698 </div>
699 );
700};
701
702export type GanttCreateMarkerTriggerProps = {
703 onCreateMarker: (date: Date) => void;
704 className?: string;
705};
706
707export const GanttCreateMarkerTrigger: FC<GanttCreateMarkerTriggerProps> = ({
708 onCreateMarker,
709 className,
710}) => {
711 const gantt = useContext(GanttContext);
712 const [mousePosition, mouseRef] = useMouse<HTMLDivElement>();
713 const [windowScroll] = useWindowScroll();
714 const x = useThrottle(
715 mousePosition.x -
716 (mouseRef.current?.getBoundingClientRect().x ?? 0) -
717 (windowScroll.x ?? 0),
718 10
719 );
720
721 const date = getDateByMousePosition(gantt, x);
722
723 const handleClick = () => onCreateMarker(date);
724
725 return (
726 <div
727 className={cn(
728 "group pointer-events-none absolute top-0 left-0 h-full w-full select-none overflow-visible",
729 className
730 )}
731 ref={mouseRef}
732 >
733 <div
734 className="-ml-2 pointer-events-auto sticky top-6 z-20 flex w-4 flex-col items-center justify-center gap-1 overflow-visible opacity-0 group-hover:opacity-100"
735 style={{ transform: `translateX(${x}px)` }}
736 >
737 <button
738 className="z-50 inline-flex h-4 w-4 items-center justify-center rounded-full bg-card"
739 onClick={handleClick}
740 type="button"
741 >
742 <PlusIcon className="text-muted-foreground" size={12} />
743 </button>
744 <div className="whitespace-nowrap rounded-full border border-border/50 bg-background/90 px-2 py-1 text-foreground text-xs backdrop-blur-lg">
745 {formatDate(date, "MMM dd, yyyy")}
746 </div>
747 </div>
748 </div>
749 );
750};
751
752export type GanttFeatureDragHelperProps = {
753 featureId: GanttFeature["id"];
754 direction: "left" | "right";
755 date: Date | null;
756};
757
758export const GanttFeatureDragHelper: FC<GanttFeatureDragHelperProps> = ({
759 direction,
760 featureId,
761 date,
762}) => {
763 const [, setDragging] = useGanttDragging();
764 const { attributes, listeners, setNodeRef } = useDraggable({
765 id: `feature-drag-helper-${featureId}`,
766 });
767
768 const isPressed = Boolean(attributes["aria-pressed"]);
769
770 useEffect(() => setDragging(isPressed), [isPressed, setDragging]);
771
772 return (
773 <div
774 className={cn(
775 "group -translate-y-1/2 !cursor-col-resize absolute top-1/2 z-[3] h-full w-6 rounded-md outline-none",
776 direction === "left" ? "-left-2.5" : "-right-2.5"
777 )}
778 ref={setNodeRef}
779 {...attributes}
780 {...listeners}
781 >
782 <div
783 className={cn(
784 "-translate-y-1/2 absolute top-1/2 h-[80%] w-1 rounded-sm bg-muted-foreground opacity-0 transition-all",
785 direction === "left" ? "left-2.5" : "right-2.5",
786 direction === "left" ? "group-hover:left-0" : "group-hover:right-0",
787 isPressed && (direction === "left" ? "left-0" : "right-0"),
788 "group-hover:opacity-100",
789 isPressed && "opacity-100"
790 )}
791 />
792 {date && (
793 <div
794 className={cn(
795 "-translate-x-1/2 absolute top-10 hidden whitespace-nowrap rounded-lg border border-border/50 bg-background/90 px-2 py-1 text-foreground text-xs backdrop-blur-lg group-hover:block",
796 isPressed && "block"
797 )}
798 >
799 {format(date, "MMM dd, yyyy")}
800 </div>
801 )}
802 </div>
803 );
804};
805
806export type GanttFeatureItemCardProps = Pick<GanttFeature, "id"> & {
807 children?: ReactNode;
808};
809
810export const GanttFeatureItemCard: FC<GanttFeatureItemCardProps> = ({
811 id,
812 children,
813}) => {
814 const [, setDragging] = useGanttDragging();
815 const { attributes, listeners, setNodeRef } = useDraggable({ id });
816 const isPressed = Boolean(attributes["aria-pressed"]);
817
818 useEffect(() => setDragging(isPressed), [isPressed, setDragging]);
819
820 return (
821 <Card className="h-full w-full rounded-md bg-background p-2 text-xs shadow-sm">
822 <div
823 className={cn(
824 "flex h-full w-full items-center justify-between gap-2 text-left",
825 isPressed && "cursor-grabbing"
826 )}
827 {...attributes}
828 {...listeners}
829 ref={setNodeRef}
830 >
831 {children}
832 </div>
833 </Card>
834 );
835};
836
837export type GanttFeatureItemProps = GanttFeature & {
838 onMove?: (id: string, startDate: Date, endDate: Date | null) => void;
839 children?: ReactNode;
840 className?: string;
841};
842
843export const GanttFeatureItem: FC<GanttFeatureItemProps> = ({
844 onMove,
845 children,
846 className,
847 ...feature
848}) => {
849 const [scrollX] = useGanttScrollX();
850 const gantt = useContext(GanttContext);
851 const timelineStartDate = useMemo(
852 () => new Date(gantt.timelineData.at(0)?.year ?? 0, 0, 1),
853 [gantt.timelineData]
854 );
855 const [startAt, setStartAt] = useState<Date>(feature.startAt);
856 const [endAt, setEndAt] = useState<Date | null>(feature.endAt);
857
858 // Memoize expensive calculations
859 const width = useMemo(
860 () => getWidth(startAt, endAt, gantt),
861 [startAt, endAt, gantt]
862 );
863 const offset = useMemo(
864 () => getOffset(startAt, timelineStartDate, gantt),
865 [startAt, timelineStartDate, gantt]
866 );
867
868 const addRange = useMemo(() => getAddRange(gantt.range), [gantt.range]);
869 const [mousePosition] = useMouse<HTMLDivElement>();
870
871 const [previousMouseX, setPreviousMouseX] = useState(0);
872 const [previousStartAt, setPreviousStartAt] = useState(startAt);
873 const [previousEndAt, setPreviousEndAt] = useState(endAt);
874
875 const mouseSensor = useSensor(MouseSensor, {
876 activationConstraint: {
877 distance: 10,
878 },
879 });
880
881 const handleItemDragStart = useCallback(() => {
882 setPreviousMouseX(mousePosition.x);
883 setPreviousStartAt(startAt);
884 setPreviousEndAt(endAt);
885 }, [mousePosition.x, startAt, endAt]);
886
887 const handleItemDragMove = useCallback(() => {
888 const currentDate = getDateByMousePosition(gantt, mousePosition.x);
889 const originalDate = getDateByMousePosition(gantt, previousMouseX);
890 const delta =
891 gantt.range === "daily"
892 ? getDifferenceIn(gantt.range)(currentDate, originalDate)
893 : getInnerDifferenceIn(gantt.range)(currentDate, originalDate);
894 const newStartDate = addDays(previousStartAt, delta);
895 const newEndDate = previousEndAt ? addDays(previousEndAt, delta) : null;
896
897 setStartAt(newStartDate);
898 setEndAt(newEndDate);
899 }, [gantt, mousePosition.x, previousMouseX, previousStartAt, previousEndAt]);
900
901 const onDragEnd = useCallback(
902 () => onMove?.(feature.id, startAt, endAt),
903 [onMove, feature.id, startAt, endAt]
904 );
905
906 const handleLeftDragMove = useCallback(() => {
907 const ganttRect = gantt.ref?.current?.getBoundingClientRect();
908 const x =
909 mousePosition.x - (ganttRect?.left ?? 0) + scrollX - gantt.sidebarWidth;
910 const newStartAt = getDateByMousePosition(gantt, x);
911
912 setStartAt(newStartAt);
913 }, [gantt, mousePosition.x, scrollX]);
914
915 const handleRightDragMove = useCallback(() => {
916 const ganttRect = gantt.ref?.current?.getBoundingClientRect();
917 const x =
918 mousePosition.x - (ganttRect?.left ?? 0) + scrollX - gantt.sidebarWidth;
919 const newEndAt = getDateByMousePosition(gantt, x);
920
921 setEndAt(newEndAt);
922 }, [gantt, mousePosition.x, scrollX]);
923
924 return (
925 <div
926 className={cn("relative flex w-max min-w-full py-0.5", className)}
927 style={{ height: "var(--gantt-row-height)" }}
928 >
929 <div
930 className="pointer-events-auto absolute top-0.5"
931 style={{
932 height: "calc(var(--gantt-row-height) - 4px)",
933 width: Math.round(width),
934 left: Math.round(offset),
935 }}
936 >
937 {onMove && (
938 <DndContext
939 modifiers={[restrictToHorizontalAxis]}
940 onDragEnd={onDragEnd}
941 onDragMove={handleLeftDragMove}
942 sensors={[mouseSensor]}
943 >
944 <GanttFeatureDragHelper
945 date={startAt}
946 direction="left"
947 featureId={feature.id}
948 />
949 </DndContext>
950 )}
951 <DndContext
952 modifiers={[restrictToHorizontalAxis]}
953 onDragEnd={onDragEnd}
954 onDragMove={handleItemDragMove}
955 onDragStart={handleItemDragStart}
956 sensors={[mouseSensor]}
957 >
958 <GanttFeatureItemCard id={feature.id}>
959 {children ?? (
960 <p className="flex-1 truncate text-xs">{feature.name}</p>
961 )}
962 </GanttFeatureItemCard>
963 </DndContext>
964 {onMove && (
965 <DndContext
966 modifiers={[restrictToHorizontalAxis]}
967 onDragEnd={onDragEnd}
968 onDragMove={handleRightDragMove}
969 sensors={[mouseSensor]}
970 >
971 <GanttFeatureDragHelper
972 date={endAt ?? addRange(startAt, 2)}
973 direction="right"
974 featureId={feature.id}
975 />
976 </DndContext>
977 )}
978 </div>
979 </div>
980 );
981};
982
983export type GanttFeatureListGroupProps = {
984 children: ReactNode;
985 className?: string;
986};
987
988export const GanttFeatureListGroup: FC<GanttFeatureListGroupProps> = ({
989 children,
990 className,
991}) => (
992 <div className={className} style={{ paddingTop: "var(--gantt-row-height)" }}>
993 {children}
994 </div>
995);
996
997export type GanttFeatureRowProps = {
998 features: GanttFeature[];
999 onMove?: (id: string, startAt: Date, endAt: Date | null) => void;
1000 children?: (feature: GanttFeature) => ReactNode;
1001 className?: string;
1002};
1003
1004export const GanttFeatureRow: FC<GanttFeatureRowProps> = ({
1005 features,
1006 onMove,
1007 children,
1008 className,
1009}) => {
1010 // Sort features by start date to handle potential overlaps
1011 const sortedFeatures = [...features].sort(
1012 (a, b) => a.startAt.getTime() - b.startAt.getTime()
1013 );
1014
1015 // Calculate sub-row positions for overlapping features using a proper algorithm
1016 const featureWithPositions = [];
1017 const subRowEndTimes: Date[] = []; // Track when each sub-row becomes free
1018
1019 for (const feature of sortedFeatures) {
1020 let subRow = 0;
1021
1022 // Find the first sub-row that's free (doesn't overlap)
1023 while (
1024 subRow < subRowEndTimes.length &&
1025 subRowEndTimes[subRow] > feature.startAt
1026 ) {
1027 subRow++;
1028 }
1029
1030 // Update the end time for this sub-row
1031 if (subRow === subRowEndTimes.length) {
1032 subRowEndTimes.push(feature.endAt);
1033 } else {
1034 subRowEndTimes[subRow] = feature.endAt;
1035 }
1036
1037 featureWithPositions.push({ ...feature, subRow });
1038 }
1039
1040 const maxSubRows = Math.max(1, subRowEndTimes.length);
1041 const subRowHeight = 36; // Base row height
1042
1043 return (
1044 <div
1045 className={cn("relative", className)}
1046 style={{
1047 height: `${maxSubRows * subRowHeight}px`,
1048 minHeight: "var(--gantt-row-height)",
1049 }}
1050 >
1051 {featureWithPositions.map((feature) => (
1052 <div
1053 className="absolute w-full"
1054 key={feature.id}
1055 style={{
1056 top: `${feature.subRow * subRowHeight}px`,
1057 height: `${subRowHeight}px`,
1058 }}
1059 >
1060 <GanttFeatureItem {...feature} onMove={onMove}>
1061 {children ? (
1062 children(feature)
1063 ) : (
1064 <p className="flex-1 truncate text-xs">{feature.name}</p>
1065 )}
1066 </GanttFeatureItem>
1067 </div>
1068 ))}
1069 </div>
1070 );
1071};
1072
1073export type GanttFeatureListProps = {
1074 className?: string;
1075 children: ReactNode;
1076};
1077
1078export const GanttFeatureList: FC<GanttFeatureListProps> = ({
1079 className,
1080 children,
1081}) => (
1082 <div
1083 className={cn("absolute top-0 left-0 h-full w-max space-y-4", className)}
1084 style={{ marginTop: "var(--gantt-header-height)" }}
1085 >
1086 {children}
1087 </div>
1088);
1089
1090export const GanttMarker: FC<
1091 GanttMarkerProps & {
1092 onRemove?: (id: string) => void;
1093 className?: string;
1094 }
1095> = memo(({ label, date, id, onRemove, className }) => {
1096 const gantt = useContext(GanttContext);
1097 const differenceIn = useMemo(
1098 () => getDifferenceIn(gantt.range),
1099 [gantt.range]
1100 );
1101 const timelineStartDate = useMemo(
1102 () => new Date(gantt.timelineData.at(0)?.year ?? 0, 0, 1),
1103 [gantt.timelineData]
1104 );
1105
1106 // Memoize expensive calculations
1107 const offset = useMemo(
1108 () => differenceIn(date, timelineStartDate),
1109 [differenceIn, date, timelineStartDate]
1110 );
1111 const innerOffset = useMemo(
1112 () =>
1113 calculateInnerOffset(
1114 date,
1115 gantt.range,
1116 (gantt.columnWidth * gantt.zoom) / 100
1117 ),
1118 [date, gantt.range, gantt.columnWidth, gantt.zoom]
1119 );
1120
1121 const handleRemove = useCallback(() => onRemove?.(id), [onRemove, id]);
1122
1123 return (
1124 <div
1125 className="pointer-events-none absolute top-0 left-0 z-20 flex h-full select-none flex-col items-center justify-center overflow-visible"
1126 style={{
1127 width: 0,
1128 transform: `translateX(calc(var(--gantt-column-width) * ${offset} + ${innerOffset}px))`,
1129 }}
1130 >
1131 <ContextMenu>
1132 <ContextMenuTrigger asChild>
1133 <div
1134 className={cn(
1135 "group pointer-events-auto sticky top-0 flex select-auto flex-col flex-nowrap items-center justify-center whitespace-nowrap rounded-b-md bg-card px-2 py-1 text-foreground text-xs",
1136 className
1137 )}
1138 >
1139 {label}
1140 <span className="max-h-[0] overflow-hidden opacity-80 transition-all group-hover:max-h-[2rem]">
1141 {formatDate(date, "MMM dd, yyyy")}
1142 </span>
1143 </div>
1144 </ContextMenuTrigger>
1145 <ContextMenuContent>
1146 {onRemove ? (
1147 <ContextMenuItem
1148 className="flex items-center gap-2 text-destructive"
1149 onClick={handleRemove}
1150 >
1151 <TrashIcon size={16} />
1152 Remove marker
1153 </ContextMenuItem>
1154 ) : null}
1155 </ContextMenuContent>
1156 </ContextMenu>
1157 <div className={cn("h-full w-px bg-card", className)} />
1158 </div>
1159 );
1160});
1161
1162GanttMarker.displayName = "GanttMarker";
1163
1164export type GanttProviderProps = {
1165 range?: Range;
1166 zoom?: number;
1167 onAddItem?: (date: Date) => void;
1168 children: ReactNode;
1169 className?: string;
1170};
1171
1172export const GanttProvider: FC<GanttProviderProps> = ({
1173 zoom = 100,
1174 range = "monthly",
1175 onAddItem,
1176 children,
1177 className,
1178}) => {
1179 const scrollRef = useRef<HTMLDivElement>(null);
1180 const [timelineData, setTimelineData] = useState<TimelineData>(
1181 createInitialTimelineData(new Date())
1182 );
1183 const [, setScrollX] = useGanttScrollX();
1184 const [sidebarWidth, setSidebarWidth] = useState(0);
1185
1186 const headerHeight = 60;
1187 const rowHeight = 36;
1188 let columnWidth = 50;
1189
1190 if (range === "monthly") {
1191 columnWidth = 150;
1192 } else if (range === "quarterly") {
1193 columnWidth = 100;
1194 }
1195
1196 // Memoize CSS variables to prevent unnecessary re-renders
1197 const cssVariables = useMemo(
1198 () =>
1199 ({
1200 "--gantt-zoom": `${zoom}`,
1201 "--gantt-column-width": `${(zoom / 100) * columnWidth}px`,
1202 "--gantt-header-height": `${headerHeight}px`,
1203 "--gantt-row-height": `${rowHeight}px`,
1204 "--gantt-sidebar-width": `${sidebarWidth}px`,
1205 }) as CSSProperties,
1206 [zoom, columnWidth, sidebarWidth]
1207 );
1208
1209 useEffect(() => {
1210 if (scrollRef.current) {
1211 scrollRef.current.scrollLeft =
1212 scrollRef.current.scrollWidth / 2 - scrollRef.current.clientWidth / 2;
1213 setScrollX(scrollRef.current.scrollLeft);
1214 }
1215 }, [setScrollX]);
1216
1217 // Update sidebar width when DOM is ready
1218 useEffect(() => {
1219 const updateSidebarWidth = () => {
1220 const sidebarElement = scrollRef.current?.querySelector(
1221 '[data-roadmap-ui="gantt-sidebar"]'
1222 );
1223 const newWidth = sidebarElement ? 300 : 0;
1224 setSidebarWidth(newWidth);
1225 };
1226
1227 // Update immediately
1228 updateSidebarWidth();
1229
1230 // Also update on resize or when children change
1231 const observer = new MutationObserver(updateSidebarWidth);
1232 if (scrollRef.current) {
1233 observer.observe(scrollRef.current, {
1234 childList: true,
1235 subtree: true,
1236 });
1237 }
1238
1239 return () => {
1240 observer.disconnect();
1241 };
1242 }, []);
1243
1244 // Fix the useCallback to include all dependencies
1245 const handleScroll = useCallback(
1246 throttle(() => {
1247 const scrollElement = scrollRef.current;
1248 if (!scrollElement) {
1249 return;
1250 }
1251
1252 const { scrollLeft, scrollWidth, clientWidth } = scrollElement;
1253 setScrollX(scrollLeft);
1254
1255 if (scrollLeft === 0) {
1256 // Extend timelineData to the past
1257 const firstYear = timelineData[0]?.year;
1258
1259 if (!firstYear) {
1260 return;
1261 }
1262
1263 const newTimelineData: TimelineData = [...timelineData];
1264 newTimelineData.unshift({
1265 year: firstYear - 1,
1266 quarters: new Array(4).fill(null).map((_, quarterIndex) => ({
1267 months: new Array(3).fill(null).map((_, monthIndex) => {
1268 const month = quarterIndex * 3 + monthIndex;
1269 return {
1270 days: getDaysInMonth(new Date(firstYear, month, 1)),
1271 };
1272 }),
1273 })),
1274 });
1275
1276 setTimelineData(newTimelineData);
1277
1278 // Scroll a bit forward so it's not at the very start
1279 scrollElement.scrollLeft = scrollElement.clientWidth;
1280 setScrollX(scrollElement.scrollLeft);
1281 } else if (scrollLeft + clientWidth >= scrollWidth) {
1282 // Extend timelineData to the future
1283 const lastYear = timelineData.at(-1)?.year;
1284
1285 if (!lastYear) {
1286 return;
1287 }
1288
1289 const newTimelineData: TimelineData = [...timelineData];
1290 newTimelineData.push({
1291 year: lastYear + 1,
1292 quarters: new Array(4).fill(null).map((_, quarterIndex) => ({
1293 months: new Array(3).fill(null).map((_, monthIndex) => {
1294 const month = quarterIndex * 3 + monthIndex;
1295 return {
1296 days: getDaysInMonth(new Date(lastYear, month, 1)),
1297 };
1298 }),
1299 })),
1300 });
1301
1302 setTimelineData(newTimelineData);
1303
1304 // Scroll a bit back so it's not at the very end
1305 scrollElement.scrollLeft =
1306 scrollElement.scrollWidth - scrollElement.clientWidth;
1307 setScrollX(scrollElement.scrollLeft);
1308 }
1309 }, 100),
1310 []
1311 );
1312
1313 useEffect(() => {
1314 const scrollElement = scrollRef.current;
1315 if (scrollElement) {
1316 scrollElement.addEventListener("scroll", handleScroll);
1317 }
1318
1319 return () => {
1320 // Fix memory leak by properly referencing the scroll element
1321 if (scrollElement) {
1322 scrollElement.removeEventListener("scroll", handleScroll);
1323 }
1324 };
1325 }, [handleScroll]);
1326
1327 const scrollToFeature = useCallback(
1328 (feature: GanttFeature) => {
1329 const scrollElement = scrollRef.current;
1330 if (!scrollElement) {
1331 return;
1332 }
1333
1334 // Calculate timeline start date from timelineData
1335 const timelineStartDate = new Date(timelineData[0].year, 0, 1);
1336
1337 // Calculate the horizontal offset for the feature's start date
1338 const offset = getOffset(feature.startAt, timelineStartDate, {
1339 zoom,
1340 range,
1341 columnWidth,
1342 sidebarWidth,
1343 headerHeight,
1344 rowHeight,
1345 onAddItem,
1346 placeholderLength: 2,
1347 timelineData,
1348 ref: scrollRef,
1349 });
1350
1351 // Scroll to align the feature's start with the right side of the sidebar
1352 const targetScrollLeft = Math.max(0, offset);
1353
1354 scrollElement.scrollTo({
1355 left: targetScrollLeft,
1356 behavior: "smooth",
1357 });
1358 },
1359 [timelineData, zoom, range, columnWidth, sidebarWidth, onAddItem]
1360 );
1361
1362 return (
1363 <GanttContext.Provider
1364 value={{
1365 zoom,
1366 range,
1367 headerHeight,
1368 columnWidth,
1369 sidebarWidth,
1370 rowHeight,
1371 onAddItem,
1372 timelineData,
1373 placeholderLength: 2,
1374 ref: scrollRef,
1375 scrollToFeature,
1376 }}
1377 >
1378 <div
1379 className={cn(
1380 "gantt relative isolate grid h-full w-full flex-none select-none overflow-auto rounded-sm bg-secondary",
1381 range,
1382 className
1383 )}
1384 ref={scrollRef}
1385 style={{
1386 ...cssVariables,
1387 gridTemplateColumns: "var(--gantt-sidebar-width) 1fr",
1388 }}
1389 >
1390 {children}
1391 </div>
1392 </GanttContext.Provider>
1393 );
1394};
1395
1396export type GanttTimelineProps = {
1397 children: ReactNode;
1398 className?: string;
1399};
1400
1401export const GanttTimeline: FC<GanttTimelineProps> = ({
1402 children,
1403 className,
1404}) => (
1405 <div
1406 className={cn(
1407 "relative flex h-full w-max flex-none overflow-clip",
1408 className
1409 )}
1410 >
1411 {children}
1412 </div>
1413);
1414
1415export type GanttTodayProps = {
1416 className?: string;
1417};
1418
1419export const GanttToday: FC<GanttTodayProps> = ({ className }) => {
1420 const label = "Today";
1421 const date = useMemo(() => new Date(), []);
1422 const gantt = useContext(GanttContext);
1423 const differenceIn = useMemo(
1424 () => getDifferenceIn(gantt.range),
1425 [gantt.range]
1426 );
1427 const timelineStartDate = useMemo(
1428 () => new Date(gantt.timelineData.at(0)?.year ?? 0, 0, 1),
1429 [gantt.timelineData]
1430 );
1431
1432 // Memoize expensive calculations
1433 const offset = useMemo(
1434 () => differenceIn(date, timelineStartDate),
1435 [differenceIn, date, timelineStartDate]
1436 );
1437 const innerOffset = useMemo(
1438 () =>
1439 calculateInnerOffset(
1440 date,
1441 gantt.range,
1442 (gantt.columnWidth * gantt.zoom) / 100
1443 ),
1444 [date, gantt.range, gantt.columnWidth, gantt.zoom]
1445 );
1446
1447 return (
1448 <div
1449 className="pointer-events-none absolute top-0 left-0 z-20 flex h-full select-none flex-col items-center justify-center overflow-visible"
1450 style={{
1451 width: 0,
1452 transform: `translateX(calc(var(--gantt-column-width) * ${offset} + ${innerOffset}px))`,
1453 }}
1454 >
1455 <div
1456 className={cn(
1457 "group pointer-events-auto sticky top-0 flex select-auto flex-col flex-nowrap items-center justify-center whitespace-nowrap rounded-b-md bg-card px-2 py-1 text-foreground text-xs",
1458 className
1459 )}
1460 >
1461 {label}
1462 <span className="max-h-[0] overflow-hidden opacity-80 transition-all group-hover:max-h-[2rem]">
1463 {formatDate(date, "MMM dd, yyyy")}
1464 </span>
1465 </div>
1466 <div className={cn("h-full w-px bg-card", className)} />
1467 </div>
1468 );
1469};
1470