refactor: remove circular dependencies from CalendarView atom (#27850)

* fix: decouple large calendar from features

* fix: move calendar to features since this is the better approach

* chore: move OOO slots to features

* feat: add DefaultOutOfOfficeSlot fallback for calendar OOO rendering

Co-Authored-By: [email protected] <[email protected]>

* chore: cleanup unused LargeCalendar component

---------

Co-authored-by: Devin AI <158243242+devin-ai-integration[bot]@users.noreply.github.com>
This commit is contained in:
authored and GitHub committed 2026-02-17 08:14:33 +00:00
1 parent 9603831def
commit 38b43f75ba
26 files changed
+155 -58

No files matched your search

@@ -0,0 +1,217 @@
import {
CalendarStoreContext,
createCalendarStore,
useCalendarStore,
} from "@calcom/features/calendars/weeklyview/state/store";
import classNames from "@calcom/ui/classNames";
import type React from "react";
import { useEffect, useMemo, useRef } from "react";
import "@calcom/features/calendars/weeklyview/styles/styles.css";
import type { CalendarComponentProps } from "@calcom/features/calendars/weeklyview/types/state";
import { getDaysBetweenDates, getHoursToDisplay } from "@calcom/features/calendars/weeklyview/utils";
import { CurrentTime } from "./currentTime";
import { DateValues } from "./DateValues";
import { AvailableCellsForDay, EmptyCell } from "./event/Empty";
import { EventList } from "./event/EventList";
import { SchedulerColumns } from "./grid";
import { SchedulerHeading } from "./heading/SchedulerHeading";
import { HorizontalLines } from "./horizontalLines";
import { Spinner } from "./spinner/Spinner";
import { VerticalLines } from "./verticalLines";
function CalendarInner(props: CalendarComponentProps) {
const container = useRef<HTMLDivElement | null>(null);
const containerNav = useRef<HTMLDivElement | null>(null);
const containerOffset = useRef<HTMLDivElement | null>(null);
const schedulerGrid = useRef<HTMLOListElement | null>(null);
const initialState = useCalendarStore((state) => state.initState);
const startDate = useCalendarStore((state) => state.startDate);
const endDate = useCalendarStore((state) => state.endDate);
const startHour = useCalendarStore((state) => state.startHour || 0);
const endHour = useCalendarStore((state) => state.endHour || 23);
const usersCellsStopsPerHour = useCalendarStore((state) => state.gridCellsPerHour || 4);
const availableTimeslots = useCalendarStore((state) => state.availableTimeslots);
const hideHeader = useCalendarStore((state) => state.hideHeader);
const timezone = useCalendarStore((state) => state.timezone);
const showBackgroundPattern = useCalendarStore((state) => state.showBackgroundPattern);
const showBorder = useCalendarStore((state) => state.showBorder ?? true);
const borderColor = useCalendarStore((state) => state.borderColor ?? "default");
const scrollToCurrentTime = useCalendarStore((state) => state.scrollToCurrentTime ?? true);
const updateCurrentTimeOnFocus = useCalendarStore((state) => state.updateCurrentTimeOnFocus ?? false);
const renderOutOfOffice = useCalendarStore((state) => state.renderOutOfOffice);
const days = useMemo(() => getDaysBetweenDates(startDate, endDate), [startDate, endDate]);
const hours = useMemo(
() => getHoursToDisplay(startHour || 0, endHour || 23, timezone),
[startHour, endHour, timezone]
);
const numberOfGridStopsPerDay = hours.length * usersCellsStopsPerHour;
const hourSize = 58;
// Initalise State on initial mount and when props change
useEffect(() => {
initialState(props);
}, [props, initialState]);
return (
<MobileNotSupported>
<div
className={classNames("scheduler-wrapper flex h-full w-full flex-col")}
style={
{
"--one-minute-height": `calc(${hourSize}px/60)`,
"--gridDefaultSize": `${hourSize}px`,
} as React.CSSProperties // This can't live in the css file because it's a dynamic value and css variable gets super
}>
{hideHeader !== true && <SchedulerHeading />}
{props.isPending && <Spinner />}
<div
ref={container}
className="bg-default dark:bg-cal-muted relative isolate flex h-full flex-auto flex-col">
<div
style={{ width: "165%" }}
className="flex max-w-full flex-none flex-col sm:max-w-none md:max-w-full">
<DateValues
containerNavRef={containerNav}
days={days}
showBorder={showBorder}
borderColor={borderColor}
/>
<div className="relative flex flex-auto">
<CurrentTime
timezone={timezone}
scrollToCurrentTime={scrollToCurrentTime}
updateOnFocus={updateCurrentTimeOnFocus}
/>
<div
className={classNames(
"bg-default dark:bg-cal-muted ring-muted sticky left-0 z-10 w-16 flex-none ring-1",
showBorder &&
(borderColor === "subtle"
? "border-subtle border-l border-r"
: "border-default border-l border-r")
)}
/>
<div
className="grid flex-auto grid-cols-1 grid-rows-1 [--disabled-gradient-background:#F8F9FB] [--disabled-gradient-foreground:#E6E7EB] dark:[--disabled-gradient-background:#262626] dark:[--disabled-gradient-foreground:#393939]"
style={
showBackgroundPattern === false
? undefined
: {
backgroundColor: "var(--disabled-gradient-background)",
background:
"repeating-linear-gradient(-45deg, var(--disabled-gradient-background), var(--disabled-gradient-background) 2.5px, var(--disabled-gradient-foreground) 2.5px, var(--disabled-gradient-foreground) 5px)",
}
}>
<HorizontalLines
hours={hours}
numberOfGridStopsPerCell={usersCellsStopsPerHour}
containerOffsetRef={containerOffset}
borderColor={borderColor}
/>
<VerticalLines days={days} borderColor={borderColor} />
<SchedulerColumns
offsetHeight={containerOffset.current?.offsetHeight}
gridStopsPerDay={numberOfGridStopsPerDay}>
{/*Loop over events per day */}
{days.map((day, i) => {
return (
<li key={day.toISOString()} className="relative" style={{ gridColumnStart: i + 1 }}>
<EventList day={day} />
{/* <BlockedList day={day} containerRef={container} /> */}
</li>
);
})}
</SchedulerColumns>
{/* Empty Cells */}
<SchedulerColumns
ref={schedulerGrid}
offsetHeight={containerOffset.current?.offsetHeight}
gridStopsPerDay={numberOfGridStopsPerDay}>
<>
{[...Array(days.length)].map((_, i) => (
<li
className="relative"
key={i}
style={{
gridColumnStart: i + 1,
gridRow: `1 / span ${numberOfGridStopsPerDay}`,
}}>
{/* While startDate < endDate: */}
{availableTimeslots ? (
<AvailableCellsForDay
key={days[i].toISOString()}
timezone={timezone}
day={days[i]}
startHour={startHour}
availableSlots={availableTimeslots}
renderOutOfOffice={renderOutOfOffice}
/>
) : (
<>
{[...Array(numberOfGridStopsPerDay)].map((_, j) => {
const key = `${i}-${j}`;
return (
<EmptyCell
key={key}
day={days[i]}
gridCellIdx={j}
totalGridCells={numberOfGridStopsPerDay}
selectionLength={endHour - startHour}
startHour={startHour}
timezone={timezone}
/>
);
})}
</>
)}
</li>
))}
</>
</SchedulerColumns>
</div>
</div>
</div>
</div>
</div>
</MobileNotSupported>
);
}
export function Calendar(props: CalendarComponentProps) {
const storeRef = useRef<ReturnType<typeof createCalendarStore> | null>(null);
if (!storeRef.current) {
storeRef.current = createCalendarStore();
storeRef.current.getState().initState(props);
}
useEffect(() => {
if (storeRef.current) {
storeRef.current.getState().initState(props);
}
}, [props]);
return (
<CalendarStoreContext.Provider value={storeRef.current}>
<CalendarInner {...props} />
</CalendarStoreContext.Provider>
);
}
/** @todo Will be removed once we have mobile support */
const MobileNotSupported = ({ children }: { children: React.ReactNode }) => {
return (
<>
<div className="flex h-full flex-col items-center justify-center sm:hidden">
<h1 className="text-2xl font-bold">Mobile not supported yet </h1>
<p className="text-subtle">Please use a desktop browser to view this page</p>
</div>
<div className="hidden h-full sm:block">{children}</div>
</>
);
};
@@ -0,0 +1,113 @@
import dayjs from "@calcom/dayjs";
import { useCalendarStore } from "@calcom/features/calendars/weeklyview/state/store";
import type { BorderColor } from "@calcom/features/calendars/weeklyview/types/common";
import { useLocale } from "@calcom/lib/hooks/useLocale";
import classNames from "@calcom/ui/classNames";
import type React from "react";
type Props = {
showBorder: boolean;
borderColor: BorderColor;
days: dayjs.Dayjs[];
containerNavRef: React.RefObject<HTMLDivElement>;
};
export function DateValues({ showBorder, borderColor, days, containerNavRef }: Props) {
const { i18n } = useLocale();
const timezone = useCalendarStore((state) => state.timezone);
const showTimezone = useCalendarStore((state) => state.showTimezone ?? false);
const formatDate = (date: dayjs.Dayjs): string => {
return new Intl.DateTimeFormat(i18n.language, { weekday: "short" }).format(date.toDate());
};
const getTimezoneDisplay = () => {
if (!showTimezone || !timezone) return null;
try {
const timeRaw = dayjs().tz(timezone);
const utcOffsetInMinutes = timeRaw.utcOffset();
// Convert offset to decimal hours
const offsetInHours = Math.abs(utcOffsetInMinutes / 60);
const sign = utcOffsetInMinutes < 0 ? "-" : "+";
// If offset is 0, just return "GMT"
if (utcOffsetInMinutes === 0) {
return "GMT";
}
// Format as decimal (e.g., 1.5 for 1:30, 1 for 1:00)
const offsetFormatted = `${sign}${offsetInHours}`;
return `GMT ${offsetFormatted}`;
} catch {
// Fallback to showing the timezone name if formatting fails
return timezone.split("/").pop()?.replace(/_/g, " ") || timezone;
}
};
return (
<div
ref={containerNavRef}
className={classNames(
"bg-default dark:bg-cal-muted top-(--calendar-dates-sticky-offset,0px) z-80 sticky flex-none border-b",
borderColor === "subtle" ? "border-b-subtle" : "border-b-default",
showBorder && (borderColor === "subtle" ? "border-r-subtle border-r" : "border-r-default border-r")
)}>
<div className="text-subtle flex leading-6 sm:hidden" data-dayslength={days.length}>
{days.map((day) => {
const isToday = dayjs().isSame(day, "day");
return (
<button
key={day.toString()}
type="button"
className="flex flex-1 flex-col items-center pb-3 pt-2">
{day.format("dd")}{" "}
<span
className={classNames(
"text-emphasis mt-1 flex h-8 w-8 items-center justify-center font-medium",
isToday && "bg-inverted text-inverted rounded-sm"
)}>
{day.format("D")}
</span>
</button>
);
})}
</div>
<div className="text-subtle -mr-px hidden auto-cols-fr leading-6 sm:flex">
<div
className={classNames(
"col-end-1 flex w-16 items-center justify-center",
showBorder &&
(borderColor === "subtle" ? "border-l-subtle border-l" : "border-l-default border-l")
)}>
{showTimezone && timezone && (
<span className="text-muted text-xs font-medium">{getTimezoneDisplay()}</span>
)}
</div>
{days.map((day) => {
const isToday = dayjs().isSame(day, "day");
return (
<div
key={day.toString()}
className={classNames(
"flex flex-1 items-center justify-center py-3 text-xs font-medium uppercase",
isToday && "text-default"
)}>
<span>
{formatDate(day)}{" "}
<span
className={classNames(
"items-center justify-center p-1",
isToday && "bg-brand-default text-brand ml-1 rounded-md"
)}>
{day.format("DD")}
</span>
</span>
</div>
);
})}
</div>
</div>
);
}
@@ -0,0 +1,67 @@
import type { OutOfOfficeRenderProps } from "@calcom/features/calendars/weeklyview/types/state";
import ServerTrans from "@calcom/lib/components/ServerTrans";
import { useLocale } from "@calcom/lib/hooks/useLocale";
import classNames from "@calcom/ui/classNames";
export function DefaultOutOfOfficeSlot(props: OutOfOfficeRenderProps) {
const { t } = useLocale();
const {
fromUser,
toUser,
emoji = "\u{1F3DD}\uFE0F",
reason,
borderDashed = true,
className,
notes,
showNotePublicly,
} = props;
const isHoliday = !fromUser && reason;
if (!isHoliday && !fromUser) return null;
return (
<div className={classNames("relative h-full pb-5", className)}>
<div
className={classNames(
"flex h-full flex-col items-center justify-start rounded-md border bg-white px-4 py-4 font-normal dark:bg-transparent",
borderDashed && "border-dashed"
)}>
<div className="bg-emphasis flex h-14 w-14 flex-col items-center justify-center rounded-full">
<span className="m-auto text-center text-lg">{emoji}</span>
</div>
<div className="stack-y-2 max-h-[300px] w-full overflow-y-auto text-center">
{isHoliday ? (
<>
<p className="mt-2 text-base font-bold">{reason}</p>
<p className="text-subtle text-center text-sm">{t("holiday_no_availability")}</p>
</>
) : (
<>
<p className="mt-2 text-base font-bold">
{t("ooo_user_is_ooo", { displayName: fromUser?.displayName })}
</p>
{notes && showNotePublicly && (
<p className="text-subtle mt-2 max-h-[120px] overflow-y-auto break-words px-2 text-center text-sm italic">
{notes}
</p>
)}
{fromUser?.displayName && toUser?.displayName && (
<p className="text-center text-sm">
<ServerTrans
t={t}
i18nKey="ooo_slots_returning"
values={{ displayName: toUser.displayName }}
components={[<strong key="username">username</strong>]}
/>
</p>
)}
</>
)}
</div>
</div>
</div>
);
}
@@ -0,0 +1,127 @@
import dayjs from "@calcom/dayjs";
import { useCalendarStore } from "@calcom/features/calendars/weeklyview/state/store";
import { useMemo } from "react";
import { shallow } from "zustand/shallow";
import { BlockedTimeCell } from "./BlockedTimeCell";
type Props = {
day: dayjs.Dayjs;
containerRef: React.RefObject<HTMLDivElement>;
};
function roundX(x: number, roundBy: number) {
return Math.round(x / roundBy) * roundBy;
}
type BlockedDayProps = {
startHour: number;
endHour: number;
day: dayjs.Dayjs;
};
function BlockedBeforeToday({ day, startHour, endHour }: BlockedDayProps) {
return (
<>
{day.isBefore(dayjs(), "day") && (
<div
key={day.format("YYYY-MM-DD")}
className="absolute z-40 w-full"
style={{
top: `var(--one-minute-height)`,
zIndex: 60,
height: `calc(${(endHour + 1 - startHour) * 60} * var(--one-minute-height))`, // Add 1 to endHour to include the last hour that we add to display the last vertical line
}}>
<BlockedTimeCell />
</div>
)}
</>
);
}
function BlockedToday({
day,
startHour,
gridCellsPerHour,
endHour,
}: BlockedDayProps & { gridCellsPerHour: number }) {
const dayStart = useMemo(() => day.startOf("day").hour(startHour), [day, startHour]);
const dayEnd = useMemo(() => day.startOf("day").hour(endHour), [day, endHour]);
const dayEndInMinutes = useMemo(() => dayEnd.diff(dayStart, "minutes"), [dayEnd, dayStart]);
let nowComparedToDayStart = useMemo(() => dayjs().diff(dayStart, "minutes"), [dayStart]);
if (nowComparedToDayStart > dayEndInMinutes) nowComparedToDayStart = dayEndInMinutes;
return (
<>
{day.isToday() && (
<div
key={day.format("YYYY-MM-DD")}
className="absolute z-40 w-full"
style={{
top: `var(--one-minute-height)`, // Still need this as this var takes into consideration the offset of the "AllDayEvents" bar
zIndex: 60,
height: `calc(${roundX(
nowComparedToDayStart,
60 / gridCellsPerHour
)} * var(--one-minute-height) - 2px)`, // We minus the border width to make it 🧹
}}>
<BlockedTimeCell />
</div>
)}
</>
);
}
export function BlockedList({ day }: Props) {
const { startHour, blockingDates, endHour, gridCellsPerHour } = useCalendarStore(
(state) => ({
startHour: state.startHour || 0,
endHour: state.endHour || 23,
blockingDates: state.blockingDates,
gridCellsPerHour: state.gridCellsPerHour || 4,
}),
shallow
);
return (
<>
<BlockedBeforeToday day={day} startHour={startHour} endHour={endHour} />
<BlockedToday gridCellsPerHour={gridCellsPerHour} day={day} startHour={startHour} endHour={endHour} />
{blockingDates &&
blockingDates.map((event, i) => {
const dayStart = day.startOf("day").hour(startHour);
const blockingStart = dayjs(event.start);
const eventEnd = dayjs(event.end);
const eventStart = dayStart.isAfter(blockingStart) ? dayStart : blockingStart;
if (!eventStart.isSame(day, "day")) {
return null;
}
if (eventStart.isBefore(dayjs())) {
if (eventEnd.isBefore(dayjs())) {
return null;
}
}
const eventDuration = eventEnd.diff(eventStart, "minutes");
const eventStartHour = eventStart.hour();
const eventStartDiff = (eventStartHour - (startHour || 0)) * 60;
return (
<div
key={`${eventStart.toISOString()}-${i}`}
className="absolute w-full"
style={{
zIndex: 60,
top: `calc(${eventStartDiff}*var(--one-minute-height))`,
height: `calc(${eventDuration}*var(--one-minute-height))`,
}}>
<BlockedTimeCell />
</div>
);
})}
</>
);
}
@@ -0,0 +1,17 @@
import classNames from "@calcom/ui/classNames";
export function BlockedTimeCell() {
return (
<div
className={classNames(
"group absolute inset-0 flex h-full flex-col hover:cursor-not-allowed",
"[--disabled-gradient-background:#E5E7EB] [--disabled-gradient-foreground:#D1D5DB] dark:[--disabled-gradient-background:#262626] dark:[--disabled-gradient-foreground:#393939]"
)}
style={{
backgroundColor: "#D1D5DB",
background:
"repeating-linear-gradient( -45deg, var(--disabled-gradient-background), var(--disabled-gradient-background) 2.5px, var(--disabled-gradient-foreground) 2.5px, var(--disabled-gradient-foreground) 6.5px )",
}}
/>
);
}
@@ -0,0 +1,83 @@
import dayjs from "@calcom/dayjs";
import { useTimePreferences } from "@calcom/features/bookings/lib";
import { useCalendarStore } from "@calcom/features/calendars/weeklyview/state/store";
import { useCallback, useEffect, useRef, useState } from "react";
function calculateMinutesFromStart(startHour: number, currentHour: number, currentMinute: number) {
const startMinute = startHour * 60;
const currentMinuteOfDay = currentHour * 60 + currentMinute;
return currentMinuteOfDay - startMinute;
}
export function CurrentTime({
timezone,
scrollToCurrentTime = true,
updateOnFocus = false,
}: {
timezone: string;
scrollToCurrentTime?: boolean;
updateOnFocus?: boolean;
}) {
const { timeFormat } = useTimePreferences();
const currentTimeRef = useRef<HTMLDivElement>(null);
const [scrolledIntoView, setScrolledIntoView] = useState(false);
const [currentTimePos, setCurrentTimePos] = useState<number | null>(null);
const { startHour, endHour } = useCalendarStore((state) => ({
startHour: state.startHour || 0,
endHour: state.endHour || 23,
}));
const updateCurrentTimePosition = useCallback(() => {
const currentDateTime = dayjs().tz(timezone);
const currentHour = currentDateTime.hour();
const currentMinute = currentDateTime.minute();
if (currentHour > endHour || currentHour < startHour) {
setCurrentTimePos(null);
return;
}
const minutesFromStart = calculateMinutesFromStart(startHour, currentHour, currentMinute);
setCurrentTimePos(minutesFromStart);
}, [timezone, startHour, endHour]);
useEffect(() => {
updateCurrentTimePosition();
if (!scrollToCurrentTime || !currentTimeRef.current || scrolledIntoView) return;
setTimeout(() => {
currentTimeRef?.current?.scrollIntoView({ block: "center" });
setScrolledIntoView(true);
}, 100);
}, [updateCurrentTimePosition, scrolledIntoView, scrollToCurrentTime]);
useEffect(() => {
if (!updateOnFocus) return;
const handleVisibilityChange = () => {
if (document.visibilityState === "visible") {
updateCurrentTimePosition();
}
};
document.addEventListener("visibilitychange", handleVisibilityChange);
return () => {
document.removeEventListener("visibilitychange", handleVisibilityChange);
};
}, [updateOnFocus, updateCurrentTimePosition]);
return (
<div
ref={currentTimeRef}
className="absolute top-0 z-40 flex h-px items-center justify-center text-xs"
aria-hidden="true"
style={{
top: `calc(${currentTimePos}*var(--one-minute-height) + var(--calendar-offset-top))`,
zIndex: 70,
}}>
<div className="w-16 pr-2 text-right">{dayjs().tz(timezone).format(timeFormat)}</div>
<div className="bg-inverted h-3 w-px" />
<div className="bg-inverted h-px w-screen" />
</div>
);
}
@@ -0,0 +1,229 @@
import type { Dayjs } from "@calcom/dayjs";
import dayjs from "@calcom/dayjs";
import { useTimePreferences } from "@calcom/features/bookings/lib";
import { DefaultOutOfOfficeSlot } from "@calcom/features/calendars/weeklyview/components/DefaultOutOfOfficeSlot";
import { useCalendarStore } from "@calcom/features/calendars/weeklyview/state/store";
import type {
CalendarAvailableTimeslots,
OutOfOfficeRenderProps,
} from "@calcom/features/calendars/weeklyview/types/state";
import type { GridCellToDateProps } from "@calcom/features/calendars/weeklyview/utils";
import { gridCellToDateTime } from "@calcom/features/calendars/weeklyview/utils";
import classNames from "@calcom/ui/classNames";
import type { ReactNode } from "react";
import { useMemo } from "react";
import { shallow } from "zustand/shallow";
type EmptyCellProps = GridCellToDateProps & {
isDisabled?: boolean;
topOffsetMinutes?: number;
};
export function EmptyCell(props: EmptyCellProps) {
const cellToDate = gridCellToDateTime({
day: props.day,
gridCellIdx: props.gridCellIdx,
totalGridCells: props.totalGridCells,
selectionLength: props.selectionLength,
startHour: props.startHour,
timezone: props.timezone,
});
const minutesFromStart = (cellToDate.hour() - props.startHour) * 60 + cellToDate.minute();
return <Cell topOffsetMinutes={minutesFromStart} timeSlot={dayjs(cellToDate).tz(props.timezone)} />;
}
type AvailableCellProps = {
timezone: string;
availableSlots: CalendarAvailableTimeslots;
day: GridCellToDateProps["day"];
startHour: GridCellToDateProps["startHour"];
renderOutOfOffice?: (props: OutOfOfficeRenderProps) => ReactNode;
};
export function AvailableCellsForDay({
timezone,
availableSlots,
day,
startHour,
renderOutOfOffice,
}: AvailableCellProps) {
const date = dayjs(day);
const dateFormatted = date.format("YYYY-MM-DD");
const slotsForToday = availableSlots && availableSlots[dateFormatted];
const slots = useMemo(() => {
const calculatedSlots: {
slot: CalendarAvailableTimeslots[string][number];
topOffsetMinutes: number;
firstSlot?: CalendarAvailableTimeslots[string][number];
timezone?: string;
}[] = [];
// first and last slot for ooo to display range correctly in week view
let firstSlotIndex = -1;
let lastSlotIndex = -1;
let areAllSlotsAway = true;
let startEndTimeDuration = 0;
slotsForToday?.forEach((slot, index) => {
const startTime = dayjs(slot.start).tz(timezone);
const topOffsetMinutes = (startTime.hour() - startHour) * 60 + startTime.minute();
calculatedSlots.push({ slot, topOffsetMinutes });
if (!slot.away) {
areAllSlotsAway = false;
} else {
if (firstSlotIndex === -1) {
firstSlotIndex = index;
}
lastSlotIndex = index;
}
});
if (areAllSlotsAway && firstSlotIndex !== -1) {
const firstSlot = slotsForToday[firstSlotIndex];
const lastSlot = slotsForToday[lastSlotIndex];
startEndTimeDuration = dayjs(lastSlot.end).diff(dayjs(firstSlot.start), "minutes");
if (firstSlot.toUser == null && !firstSlot.showNotePublicly) {
return null;
}
// This will return null if all slots are away and the first slot has no user
return {
slots: calculatedSlots,
startEndTimeDuration,
firstSlot,
timezone,
};
}
return { slots: calculatedSlots, startEndTimeDuration };
}, [slotsForToday, startHour, timezone]);
if (slots === null) return null;
if (slots.startEndTimeDuration) {
const { firstSlot, startEndTimeDuration } = slots;
const renderOOO = renderOutOfOffice ?? ((p: OutOfOfficeRenderProps) => <DefaultOutOfOfficeSlot {...p} />);
return (
<CustomCell
timeSlot={dayjs(firstSlot?.start).tz(slots.timezone)}
topOffsetMinutes={slots.slots[0]?.topOffsetMinutes}
startEndTimeDuration={startEndTimeDuration}>
{renderOOO({
fromUser: firstSlot?.fromUser,
toUser: firstSlot?.toUser,
reason: firstSlot?.reason,
emoji: firstSlot?.emoji,
notes: firstSlot?.notes,
showNotePublicly: firstSlot?.showNotePublicly,
borderDashed: false,
date: dateFormatted,
className: "pb-0",
})}
</CustomCell>
);
}
return (
<>
{slots.slots.map((slot, index) => (
<Cell
key={index}
timeSlot={dayjs(slot.slot.start).tz(timezone)}
topOffsetMinutes={slot.topOffsetMinutes}
/>
))}
</>
);
}
type CellProps = {
isDisabled?: boolean;
topOffsetMinutes?: number;
timeSlot: Dayjs;
};
function Cell({ isDisabled, topOffsetMinutes, timeSlot }: CellProps) {
const { timeFormat } = useTimePreferences();
const { onEmptyCellClick, hoverEventDuration } = useCalendarStore(
(state) => ({
onEmptyCellClick: state.onEmptyCellClick,
hoverEventDuration: state.hoverEventDuration,
}),
shallow
);
return (
<div
className={classNames(
"group flex w-[calc(100%-1px)] items-center justify-center",
isDisabled && "pointer-events-none",
!isDisabled && "bg-default dark:bg-cal-muted",
topOffsetMinutes && "absolute"
)}
data-disabled={isDisabled}
data-slot={timeSlot.toISOString()}
data-testid="calendar-empty-cell"
style={{
height: `calc(${hoverEventDuration}*var(--one-minute-height))`,
overflow: "visible",
top: topOffsetMinutes ? `calc(${topOffsetMinutes}*var(--one-minute-height))` : undefined,
}}
onClick={() => {
onEmptyCellClick?.(timeSlot.toDate());
}}>
{!isDisabled && hoverEventDuration !== 0 && (
<div
className={classNames(
"bg-brand-default hover:bg-brand-default text-brand dark:border-emphasis absolute hidden rounded-[4px] p-[6px] text-xs font-semibold leading-5 group-hover:flex group-hover:cursor-pointer",
hoverEventDuration && hoverEventDuration > 15 && "items-start pt-3",
hoverEventDuration && hoverEventDuration < 15 && "items-center"
)}
style={{
height: `calc(${hoverEventDuration}*var(--one-minute-height) - 2px)`,
zIndex: 80,
// @TODO: This used to be 90% as per Sean's work. I think this was needed when
// multiple events are stacked next to each other. We might need to add this back later.
width: "calc(100% - 2px)",
}}>
<div className="text-ellipsis leading-0">{timeSlot.format(timeFormat)}</div>
</div>
)}
</div>
);
}
function CustomCell({
timeSlot,
children,
topOffsetMinutes,
startEndTimeDuration,
}: CellProps & { children: React.ReactNode; startEndTimeDuration?: number }) {
return (
<div
className={classNames(
"bg-default dark:bg-cal-muted group absolute z-65 flex w-[calc(100%-1px)] items-center justify-center"
)}
data-slot={timeSlot.toISOString()}
style={{
top: topOffsetMinutes ? `calc(${topOffsetMinutes}*var(--one-minute-height))` : undefined,
overflow: "visible",
}}>
<div
className={classNames(
"dark:border-emphasis bg-default dark:bg-cal-muted cursor-pointer rounded-[4px] p-[6px] text-xs font-semibold dark:text-white"
)}
style={{
height: `calc(${startEndTimeDuration}*var(--one-minute-height) - 2px)`,
width: "calc(100% - 2px)",
}}>
{children}
</div>
</div>
);
}
@@ -0,0 +1,162 @@
import dayjs from "@calcom/dayjs";
import type { CalendarEvent } from "@calcom/features/calendars/weeklyview/types/events";
import type { BookingStatus } from "@calcom/prisma/enums";
import classNames from "@calcom/ui/classNames";
import { Tooltip } from "@calcom/ui/components/tooltip";
import { cva } from "class-variance-authority";
type EventProps = {
event: CalendarEvent;
currentlySelectedEventId?: number;
eventDuration: number;
onEventClick?: (event: CalendarEvent) => void;
disabled?: boolean;
isHovered?: boolean;
};
const eventClasses = cva(
"group flex h-full w-full overflow-hidden rounded-[6px] px-[6px] text-xs leading-5 border-default font-medium",
{
variants: {
status: {
ACCEPTED: "bg-subtle hover:bg-emphasis text-emphasis border-[1px] border-default",
PENDING: "bg-subtle text-subtle border-[1px] border-dashed border-default",
REJECTED: "bg-subtle border-[1px] border-dashed text-subtle line-through",
CANCELLED: "bg-subtle border-[1px] border-dashed text-subtle line-through",
AWAITING_HOST: "bg-subtle text-emphasis border-[1px] border-dashed border-default",
},
disabled: {
true: "hover:cursor-default",
false: "hover:cursor-pointer",
},
selected: {
true: "",
false: "",
},
borderOnly: {
true: "bg-transparent border-[1.5px] border-subtle border-dashed opacity-60",
false: "",
},
},
}
);
const STATUS_COLOR_MAP: Record<BookingStatus, string> = {
ACCEPTED: "bg-green-500",
PENDING: "bg-orange-500",
REJECTED: "bg-red-500",
CANCELLED: "bg-red-500",
AWAITING_HOST: "bg-blue-500",
};
// Maps booking status to color classes for the color bar
// Follows the same pattern as BookingDetailsSheet badge variants
const getStatusColorClass = (status?: BookingStatus): string | undefined => {
if (!status) return undefined;
return STATUS_COLOR_MAP[status];
};
export function Event({
event,
currentlySelectedEventId,
eventDuration,
disabled,
onEventClick,
isHovered = false,
}: EventProps) {
const selected = currentlySelectedEventId === event.id;
const { options } = event;
// Use custom color if provided, otherwise derive from status
const colorClass = !options?.color ? getStatusColorClass(options?.status) : undefined;
const Component = onEventClick ? "button" : "div";
const dayOfWeek = dayjs(event.start).day();
const tooltipSide = dayOfWeek >= 1 && dayOfWeek <= 4 ? "right" : "left";
const tooltipContent = (
<div className="flex min-w-[200px] max-w-[300px] flex-col gap-1 py-1">
<div className="flex items-start gap-2">
{(options?.color || colorClass) && (
<div
className={classNames("mt-1 h-3 w-1 shrink-0 rounded-sm", colorClass)}
style={options?.color ? { backgroundColor: options.color } : undefined}></div>
)}
<div className="flex-1">
<div className="font-semibold leading-tight">{event.title}</div>
{!event.options?.hideTime && (
<div className="text-inverted-muted mt-1 text-xs">
{dayjs(event.start).format("HH:mm")} - {dayjs(event.end).format("HH:mm")}
</div>
)}
{event.description && (
<div className="text-inverted-muted mt-1 text-xs leading-snug">{event.description}</div>
)}
{options?.status && options.status !== "ACCEPTED" && (
<div className="text-inverted-muted mt-1 text-xs capitalize">
{options.status.toLowerCase().replace("_", " ")}
</div>
)}
</div>
</div>
</div>
);
const displayType = eventDuration < 40 ? "single-line" : eventDuration < 45 ? "multi-line" : "full";
return (
<Tooltip content={tooltipContent} className="max-w-none" side={tooltipSide}>
<Component
data-booking-calendar-event="true"
onClick={() => onEventClick?.(event)} // Note this is not the button event. It is the calendar event.
className={classNames(
eventClasses({
status: options?.status,
disabled,
selected,
borderOnly: options?.borderOnly ?? false,
}),
options?.className,
(isHovered || selected) && "ring-brand-default shadow-lg ring-2 ring-offset-0"
)}
style={{
transition: "all 100ms ease-out",
}}>
{(options?.color || colorClass) && (
<div
className={classNames("-ml-1.5 mr-1.5 h-full w-[3px] shrink-0", colorClass)}
style={options?.color ? { backgroundColor: options.color } : undefined}></div>
)}
<div className={classNames("flex w-full", displayType !== "single-line" && "flex-col py-1")}>
{displayType === "single-line" && (
<div
className={classNames(
"flex w-full shrink-0 gap-2 overflow-hidden text-ellipsis whitespace-nowrap text-left leading-4",
"items-center"
)}>
<span>{event.title}</span>
{!event.options?.hideTime && (
<p className="text-subtle mt-1 w-full whitespace-nowrap text-left text-[10px] leading-none">
{dayjs(event.start).format("HH:mm")} - {dayjs(event.end).format("HH:mm")}
</p>
)}
</div>
)}
{displayType !== "single-line" && (
<p className={classNames("shrink-0 whitespace-nowrap text-left leading-4")}>{event.title}</p>
)}
{displayType !== "single-line" && !event.options?.hideTime && (
<p className="text-subtle mt-1 whitespace-nowrap text-left text-[10px] leading-none">
{dayjs(event.start).format("HH:mm")} - {dayjs(event.end).format("HH:mm")}
</p>
)}
{displayType === "full" && event.description && (
<p className="text-subtle mt-1 text-left text-[10px] leading-none">{event.description}</p>
)}
</div>
</Component>
</Tooltip>
);
}
@@ -0,0 +1,133 @@
import dayjs from "@calcom/dayjs";
import { useCalendarStore } from "@calcom/features/calendars/weeklyview/state/store";
import { calculateEventLayouts, createLayoutMap } from "@calcom/features/calendars/weeklyview/utils/overlap";
import classNames from "@calcom/ui/classNames";
import { useEffect, useMemo, useState } from "react";
import { shallow } from "zustand/shallow";
import { Event } from "./Event";
type Props = {
day: dayjs.Dayjs;
};
export function EventList({ day }: Props) {
const { startHour, events, eventOnClick, selectedBookingUid } = useCalendarStore(
(state) => ({
startHour: state.startHour,
events: state.events,
eventOnClick: state.onEventClick,
selectedBookingUid: state.selectedBookingUid,
}),
shallow
);
const [hoveredEventId, setHoveredEventId] = useState<number | null>(null);
const dayEvents = useMemo(() => {
return events.filter((event) => {
return dayjs(event.start).isSame(day, "day") && !event.options?.allDay;
});
}, [events, day]);
const layoutMap = useMemo(() => {
const layouts = calculateEventLayouts(dayEvents);
return createLayoutMap(layouts);
}, [dayEvents]);
const eventCalculations = useMemo(() => {
return new Map(
dayEvents.map((event) => {
const eventStart = dayjs(event.start);
const eventEnd = dayjs(event.end);
const eventDuration = eventEnd.diff(eventStart, "minutes");
const eventStartHour = eventStart.hour();
const eventStartDiff = (eventStartHour - (startHour || 0)) * 60 + eventStart.minute();
return [
event.id,
{
eventStart,
eventDuration,
eventStartDiff,
},
];
})
);
}, [dayEvents, startHour]);
// Find which overlap group the hovered event belongs to
const hoveredEventLayout = hoveredEventId ? layoutMap.get(hoveredEventId) : null;
const hoveredGroupIndex = hoveredEventLayout?.groupIndex ?? null;
// Find the event ID that matches the selected booking UID (only for events on this day)
const selectedEventId = useMemo(() => {
if (!selectedBookingUid) return undefined;
const matchingEvent = dayEvents.find((event) => event.options?.bookingUid === selectedBookingUid);
return matchingEvent?.id;
}, [dayEvents, selectedBookingUid]);
// Scroll to the selected event when it changes
useEffect(() => {
if (selectedEventId === undefined) return;
// Use requestAnimationFrame to ensure the DOM has updated
requestAnimationFrame(() => {
const eventElement = document.querySelector(`[data-calendar-event-id="${selectedEventId}"]`);
if (eventElement) {
eventElement.scrollIntoView({
behavior: "smooth",
block: "nearest",
});
}
});
}, [selectedEventId]);
return (
<>
{dayEvents.map((event) => {
const layout = layoutMap.get(event.id);
if (!layout) return null;
const calc = eventCalculations.get(event.id);
if (!calc) return null;
const { eventStart, eventDuration, eventStartDiff } = calc;
const isHovered = hoveredEventId === event.id;
const isSelected = selectedEventId === event.id;
const isInHoveredGroup = hoveredGroupIndex !== null && layout.groupIndex === hoveredGroupIndex;
const zIndex = isHovered || isSelected ? 79 : layout.baseZIndex;
return (
<div
key={`${event.id}-${eventStart.toISOString()}`}
className={classNames(
"absolute transition-all duration-100 ease-out",
event.options?.borderOnly && "pointer-events-none"
)}
data-testid={event.options?.["data-test-id"]}
data-calendar-event-id={event.id}
onMouseEnter={() => setHoveredEventId(event.id)}
onMouseLeave={() => setHoveredEventId(null)}
style={{
left: `${layout.leftOffsetPercent}%`,
width: `${layout.widthPercent}%`,
zIndex,
top: `calc(${eventStartDiff}*var(--one-minute-height))`,
height: `max(15px, calc(${eventDuration}*var(--one-minute-height)))`,
transform: isHovered || isSelected ? "scale(1.02)" : "scale(1)",
opacity: hoveredGroupIndex !== null && !isHovered && isInHoveredGroup ? 0.6 : 1,
}}>
<Event
event={event}
eventDuration={eventDuration}
onEventClick={eventOnClick}
isHovered={isHovered}
currentlySelectedEventId={selectedEventId}
/>
</div>
);
})}
</>
);
}
@@ -0,0 +1 @@
export { Event } from "./Event";
@@ -0,0 +1,23 @@
import React from "react";
type Props = {
offsetHeight: number | undefined;
gridStopsPerDay: number;
children: React.ReactNode;
zIndex?: number;
};
export const SchedulerColumns = React.forwardRef<HTMLOListElement, Props>(function SchedulerColumns(
{ offsetHeight, gridStopsPerDay, children, zIndex },
ref
) {
return (
<ol
ref={ref}
className="scheduler-grid-row-template col-start-1 col-end-2 row-start-1 grid auto-cols-auto text-[0px] scheduler-wrapper"
style={{ marginTop: offsetHeight || "var(--gridDefaultSize)", zIndex }}
data-gridstopsperday={gridStopsPerDay}>
{children}
</ol>
);
});
@@ -0,0 +1,53 @@
import dayjs from "@calcom/dayjs";
import { useCalendarStore } from "@calcom/features/calendars/weeklyview/state/store";
import { Button } from "@calcom/ui/components/button";
import { ButtonGroup } from "@calcom/ui/components/buttonGroup";
export function SchedulerHeading() {
const { startDate, endDate, handleDateChange } = useCalendarStore((state) => ({
startDate: dayjs(state.startDate),
endDate: dayjs(state.endDate),
handleDateChange: state.handleDateChange,
}));
return (
<header className="flex flex-none flex-col justify-between py-4 sm:flex-row sm:items-center">
<h1 className="text-emphasis text-xl font-semibold">
{startDate.format("MMM DD")}-{endDate.format("DD")}
<span className="text-subtle">,{startDate.format("YYYY")}</span>
</h1>
<div className="flex items-center space-x-2 rtl:space-x-reverse">
{/* TODO: Renable when we have daily/mobile support */}
{/* <ToggleGroup
options={[
{ label: "Daily", value: "day", disabled: false },
{ label: "Weekly", value: "week", disabled: isSm },
]}
defaultValue={view === "day" ? "day" : "week"}
/> */}
<ButtonGroup combined>
{/* TODO: i18n label with correct view */}
<Button
StartIcon="chevron-left"
variant="icon"
color="secondary"
aria-label="Previous Week"
onClick={() => {
handleDateChange("DECREMENT");
}}
/>
<Button
StartIcon="chevron-right"
variant="icon"
color="secondary"
aria-label="Next Week"
onClick={() => {
handleDateChange("INCREMENT");
}}
/>
</ButtonGroup>
</div>
</header>
);
}
@@ -0,0 +1 @@
export { SchedulerHeading } from "./SchedulerHeading";
@@ -0,0 +1,47 @@
import type dayjs from "@calcom/dayjs";
import { useTimePreferences } from "@calcom/features/bookings/lib";
import type { BorderColor } from "@calcom/features/calendars/weeklyview/types/common";
import classNames from "@calcom/ui/classNames";
import { useId } from "react";
export const HorizontalLines = ({
hours,
containerOffsetRef,
borderColor,
}: {
hours: dayjs.Dayjs[];
numberOfGridStopsPerCell: number;
containerOffsetRef: React.RefObject<HTMLDivElement>;
borderColor: BorderColor;
}) => {
const { timeFormat } = useTimePreferences();
// We need to force the minute to zero, because otherwise in ex GMT+5.5, it would show :30 minute times (but at the positino of :00)
const finalHour = hours[hours.length - 1].add(1, "hour").minute(0).format(timeFormat);
const id = useId();
return (
<div
className={classNames(
"pointer-events-none relative z-60 col-start-1 col-end-2 row-start-1 grid divide-y",
borderColor === "subtle" ? "divide-subtle" : "divide-default"
)}
style={{
gridTemplateRows: `repeat(${hours.length}, minmax(var(--gridDefaultSize),1fr)`,
}}>
<div className="row-end-1 h-(--calendar-offset-top) " ref={containerOffsetRef} />
{hours.map((hour) => (
<div key={`${id}-${hour.get("hour")}`}>
<div className="text-muted sticky left-0 z-20 -ml-14 -mt-2.5 w-14 pr-2 text-right text-xs leading-5 rtl:-mr-14">
{/* We need to force the minute to zero, because otherwise in ex GMT+5.5, it would show :30 minute times (but at the positino of :00) */}
{hour.minute(0).format(timeFormat)}
</div>
</div>
))}
<div key={`${id}-${finalHour}`}>
<div className="text-muted sticky left-0 z-20 -ml-14 -mt-2.5 w-14 pr-2 text-right text-xs leading-5 rtl:-mr-14">
{finalHour}
</div>
</div>
</div>
);
};
@@ -0,0 +1 @@
export { Calendar } from "./Calendar";
@@ -0,0 +1,21 @@
import classNames from "@calcom/ui/classNames";
export const Spinner = ({ className }: { className?: string }) => (
<div
className={classNames(
"fixed left-[calc(50%+calc(var(--booker-meta-width,0px)/2))] top-1/2 z-80 h-10 w-10 -translate-x-1/2 -translate-y-1/2",
className
)}>
<svg className="h-10 w-10" viewBox="0 0 24 24" xmlns="http://www.w3.org/2000/svg">
<path
className="fill-default"
d="M12,1A11,11,0,1,0,23,12,11,11,0,0,0,12,1Zm0,19a8,8,0,1,1,8-8A8,8,0,0,1,12,20Z"
opacity=".25"
/>
<path
className="animate-spinning fill-emphasis origin-center"
d="M10.14,1.16a11,11,0,0,0-9,8.92A1.59,1.59,0,0,0,2.46,12,1.52,1.52,0,0,0,4.11,10.7a8,8,0,0,1,6.66-6.61A1.42,1.42,0,0,0,12,2.69h0A1.57,1.57,0,0,0,10.14,1.16Z"
/>
</svg>
</div>
);
@@ -0,0 +1,39 @@
import type dayjs from "@calcom/dayjs";
import type { BorderColor } from "@calcom/features/calendars/weeklyview/types/common";
import classNames from "@calcom/ui/classNames";
export const VerticalLines = ({ days, borderColor }: { days: dayjs.Dayjs[]; borderColor: BorderColor }) => {
const isRTL = () => {
let userLanguage = "en"; // Default to 'en' if navigator is not defined
if (typeof window !== "undefined" && typeof navigator !== "undefined") {
const userLocale = navigator.language;
userLanguage = new Intl.Locale(userLocale).language;
}
return ["ar", "he", "fa", "ur"].includes(userLanguage);
};
const direction = isRTL() ? "rtl" : "ltr";
return (
<div
className={classNames(
"pointer-events-none relative z-60 col-start-1 col-end-2 row-start-1 grid auto-cols-auto grid-rows-1 divide-x",
borderColor === "subtle" ? "divide-subtle" : "divide-default"
)}
dir={direction}
style={{
direction: direction,
}}>
{days.map((_, i) => (
<div
key={`Key_vertical_${i}`}
className="row-span-full"
style={{
gridColumnStart: isRTL() ? days.length - i : i + 1,
}}
/>
))}
</div>
);
};
@@ -1,8 +1,23 @@
import type { ReactNode } from "react";
import type { IFromUser, IToUser } from "@calcom/features/availability/lib/getUserAvailability";
import type { TimeRange } from "@calcom/types/schedule";
import type { BorderColor } from "./common";
import type { CalendarEvent } from "./events";
export type OutOfOfficeRenderProps = {
date: string;
fromUser?: IFromUser;
toUser?: IToUser;
emoji?: string;
reason?: string;
notes?: string | null;
showNotePublicly?: boolean;
borderDashed?: boolean;
className?: string;
};
export type View = "month" | "week" | "day";
export type Hours =
| 0
@@ -162,6 +177,11 @@ export type CalendarState = {
* @default false
*/
updateCurrentTimeOnFocus?: boolean;
/**
* Render function for out-of-office slots.
* Web consumers pass OutOfOfficeInSlots, atoms/platform can pass their own or null.
*/
renderOutOfOffice?: (props: OutOfOfficeRenderProps) => ReactNode;
};
export type CalendarComponentProps = CalendarPublicActions & CalendarState & { isPending?: boolean };
@@ -1,6 +1,6 @@
import { Header } from "@calcom/features/bookings/components/Header";
import { BookerSection } from "@calcom/features/bookings/components/Section";
import { LargeCalendar } from "@calcom/web/modules/calendar-view/components/LargeCalendar";
import { LargeCalendar } from "./components/LargeCalendar";
import { bookerLayoutOptions } from "@calcom/prisma/zod-utils";
import { AtomsWrapper } from "../src/components/atoms-wrapper";
@@ -10,7 +10,7 @@ import { BookerSection } from "@calcom/features/bookings/components/Section";
import { useAvailableTimeSlots } from "@calcom/features/bookings/Booker/hooks/useAvailableTimeSlots";
import { useBookerLayout } from "@calcom/features/bookings/Booker/hooks/useBookerLayout";
import { useTimePreferences } from "@calcom/features/bookings/lib";
import { LargeCalendar } from "@calcom/web/modules/calendar-view/components/LargeCalendar";
import { LargeCalendar } from "./components/LargeCalendar";
import { getUsernameList } from "@calcom/features/eventtypes/lib/defaultEvents";
import { useTimesForSchedule } from "@calcom/features/schedules/hooks/useTimesForSchedule";
@@ -0,0 +1,160 @@
import { useEffect, useMemo } from "react";
import dayjs from "@calcom/dayjs";
import { useBookerStoreContext } from "@calcom/features/bookings/Booker/BookerStoreProvider";
import { useBookerTime } from "@calcom/features/bookings/Booker/hooks/useBookerTime";
import type { BookerEvent } from "@calcom/features/bookings/types";
import { Calendar } from "@calcom/features/calendars/weeklyview/components/Calendar";
import type { CalendarAvailableTimeslots } from "@calcom/features/calendars/weeklyview/types/state";
import { localStorage } from "@calcom/lib/webstorage";
import type { BookingStatus } from "@calcom/prisma/enums";
import { useBookings } from "../../hooks/bookings/useBookings";
import { useCalendarsBusyTimes } from "../../hooks/useCalendarsBusyTimes";
import { useConnectedCalendars } from "../../hooks/useConnectedCalendars";
import { getQueryParam } from "@calcom/features/bookings/Booker/utils/query-param";
export const LargeCalendar = ({
extraDays,
availableTimeslots,
isLoading,
event,
}: {
extraDays: number;
availableTimeslots?: CalendarAvailableTimeslots | undefined;
isLoading: boolean;
event?: {
data?: Pick<BookerEvent, "length" | "id"> | null;
};
}) => {
const selectedDate = useBookerStoreContext((state) => state.selectedDate);
const selectedEventDuration = useBookerStoreContext((state) => state.selectedDuration);
const displayOverlay =
getQueryParam("overlayCalendar") === "true" || localStorage?.getItem("overlayCalendarSwitchDefault");
const { timezone } = useBookerTime();
const eventDuration = selectedEventDuration || event?.data?.length || 30;
const availableSlots = availableTimeslots !== undefined ? availableTimeslots : undefined;
const startDate = selectedDate ? dayjs(selectedDate).toDate() : dayjs().toDate();
const endDate = dayjs(startDate)
.add(extraDays - 1, "day")
.toDate();
const { data: bookings, isPending: _isFetchingBookings } = useBookings({
take: 150,
skip: 0,
eventTypeId: event?.data?.id,
afterStart: startDate.toISOString(),
beforeEnd: endDate.toISOString(),
status: ["upcoming", "past", "recurring"],
});
const { data: connectedCalendars, isPending: isFetchingConnectedCalendars } = useConnectedCalendars({
enabled: true,
});
const calendarsToLoad = connectedCalendars?.connectedCalendars.flatMap((connectedCalendar) => {
return (
connectedCalendar.calendars
?.filter((calendar) => calendar.isSelected === true)
.map((cal) => ({
credentialId: cal.credentialId,
externalId: cal.externalId,
})) ?? []
);
});
const { data: overlayBusyDates } = useCalendarsBusyTimes({
loggedInUsersTz: timezone,
dateFrom: startDate.toISOString(),
dateTo: endDate.toISOString(),
calendarsToLoad: calendarsToLoad ?? [],
enabled: Boolean(!isFetchingConnectedCalendars && !!calendarsToLoad?.length),
});
// HACK: force rerender when overlay events change
// Sine we dont use react router here we need to force rerender (ATOM SUPPORT)
useEffect(() => {}, [displayOverlay]);
const sortedBookingRanges = useMemo(
() =>
(bookings ?? [])
.map((booking) => ({
booking,
startTime: dayjs(booking.start).valueOf(),
endTime: dayjs(booking.end).valueOf(),
}))
.sort((a, b) => a.startTime - b.startTime),
[bookings]
);
const filteredBusyDates = useMemo(() => {
const overlay = overlayBusyDates?.data ?? [];
if (!sortedBookingRanges.length) return overlay;
return overlay.filter((busy) => {
const busyStart = dayjs(busy.start).valueOf();
const busyEnd = dayjs(busy.end).valueOf();
for (const { startTime, endTime } of sortedBookingRanges) {
if (startTime >= busyEnd) break;
if (endTime <= busyStart) continue;
return false;
}
return true;
});
}, [overlayBusyDates?.data, sortedBookingRanges]);
const overlayEventsForDate = useMemo(() => {
const allBookings = bookings ?? [];
// since busy dates comes straight from the calendar, it contains slots have bookings and also slots that are marked as busy by user but are not bookings
// hence we filter overlayBusyDates to exclude anything that overlaps with bookings
const busyEvents = filteredBusyDates.map((busyData, index) => ({
id: index,
title: `Busy`,
start: new Date(busyData.start),
end: new Date(busyData.end),
options: {
status: "ACCEPTED" as BookingStatus,
"data-test-id": "troubleshooter-busy-event",
className: "border-[1.5px]",
},
}));
const bookingEvents = allBookings.map((booking) => ({
id: booking.id,
title: booking.title ?? `Busy`,
start: new Date(booking.start),
end: new Date(booking.end),
options: {
status: booking.status.toUpperCase() as BookingStatus,
"data-test-id": "troubleshooter-busy-event",
className: "border-[1.5px]",
},
}));
return [...bookingEvents, ...busyEvents];
}, [bookings, filteredBusyDates]);
return (
<div className="h-full [--calendar-dates-sticky-offset:66px]">
<Calendar
isPending={isLoading}
availableTimeslots={availableSlots}
startHour={0}
endHour={23}
events={overlayEventsForDate}
startDate={startDate}
endDate={endDate}
gridCellsPerHour={60 / eventDuration}
hoverEventDuration={eventDuration}
hideHeader
timezone={timezone}
/>
</div>
);
};