feat: implement booking calendar view with weekly layout (#24563)

* feat: implement booking calendar view with weekly layout

- Create reusable WeekCalendarView component that displays bookings in a weekly calendar format
- Replace EmptyScreen in BookingsCalendar with the new calendar view
- Calendar view includes:
  - Week navigation with Today, Previous, and Next buttons
  - 7-day week view with time slots from 12 AM to 11 PM
  - Bookings displayed as colored blocks positioned by time
  - Support for event type colors and status-based colors
  - Responsive design that fills the viewport
  - Hover tooltips showing booking details
- Filters remain functional at the top of the view

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

* refactor: use existing Calendar component from weeklyview

- Replace custom calendar implementation with the existing Calendar component
- Use parseEventTypeColor to properly handle event type colors
- Simplify implementation by leveraging existing calendar infrastructure
- Maintain week navigation and filtering functionality

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

* fix imports

* fix: replace isSameOrAfter with isAfter || isSame

- isSameOrAfter method does not exist in dayjs
- Use combination of isAfter and isSame instead

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

* remove useBookerTime dependency from weekly calendar view

* modify date range filters

* initial callback

* sort events

* clean up FilterBar

* add showBackgroundPattern

* update styles

* update style

* update styles

* fix type error

* fix error

* update styles

* update styles

* update event colors

* rename component

* persist weekStart on the url

* use FilterBar

* apply feedback

* extract BorderColor type

* use client

* clean up

* adjust styles

* color-code events

* rename borderColor to color

* restore class name

* add feature flag

* update class name

---------

Co-authored-by: Devin AI <158243242+devin-ai-integration[bot]@users.noreply.github.com>
This commit is contained in:
Eunjae LeeandDevin AI authored and GitHub committed 2025-10-31 11:13:41 +00:00
1 parent 8d4dd0241a
commit f00c14d0c1
26 files changed
+421 -120

No files matched your search

@@ -6,7 +6,9 @@ import { redirect } from "next/navigation";
import { z } from "zod";
import { getServerSession } from "@calcom/features/auth/lib/getServerSession";
import { FeaturesRepository } from "@calcom/features/flags/features.repository";
import { PermissionCheckService } from "@calcom/features/pbac/services/permission-check.service";
import { prisma } from "@calcom/prisma";
import { MembershipRole } from "@calcom/prisma/enums";
import { buildLegacyRequest } from "@lib/buildLegacyCtx";
@@ -52,12 +54,18 @@ const Page = async ({ params }: PageProps) => {
canReadOthersBookings = teamIdsWithPermission.length > 0;
}
const featuresRepository = new FeaturesRepository(prisma);
const isCalendarViewEnabled = await featuresRepository.checkIfFeatureIsEnabledGlobally(
"booking-calendar-view"
);
return (
<ShellMainAppDir heading={t("bookings")} subtitle={t("bookings_description")}>
<BookingsList
status={parsed.data.status}
userId={session?.user?.id}
permissions={{ canReadOthersBookings }}
isCalendarViewEnabled={isCalendarViewEnabled}
/>
</ShellMainAppDir>
);
@@ -1,23 +1,96 @@
"use client";
import type { Table as ReactTable } from "@tanstack/react-table";
import { createParser, useQueryState } from "nuqs";
import { useMemo, useCallback } from "react";
import { DataTableFilters, DataTableSegment } from "@calcom/features/data-table";
import { EmptyScreen } from "@calcom/ui/components/empty-screen";
import dayjs from "@calcom/dayjs";
import {
DataTableFilters,
DataTableSegment,
useDataTable,
useFilterValue,
ZDateRangeFilterValue,
ColumnFilterType,
} from "@calcom/features/data-table";
import { CUSTOM_PRESET } from "@calcom/features/data-table/lib/dateRange";
import type { RowData, BookingListingStatus } from "../types";
import { BookingsCalendarView } from "./BookingsCalendarView";
type BookingsCalendarViewProps = {
status: BookingListingStatus;
table: ReactTable<RowData>;
};
const COLUMN_IDS_TO_HIDE = ["dateRange"];
const weekStartParser = createParser({
parse: (value: string) => {
const parsed = dayjs(value);
return parsed.isValid() ? parsed.startOf("week") : dayjs().startOf("week");
},
serialize: (value: dayjs.Dayjs) => value.format("YYYY-MM-DD"),
});
export function BookingsCalendar({ table }: BookingsCalendarViewProps) {
const { rows } = table.getRowModel();
const { updateFilter } = useDataTable();
const dateRange = useFilterValue("dateRange", ZDateRangeFilterValue)?.data;
const [currentWeekStart, setCurrentWeekStart] = useQueryState(
"weekStart",
weekStartParser.withDefault(dayjs().startOf("week"))
);
const bookings = useMemo(() => {
return rows
.filter((row) => row.original.type === "data")
.map((row) => (row.original.type === "data" ? row.original.booking : null))
.filter((booking): booking is NonNullable<typeof booking> => booking !== null);
}, [rows]);
const handleWeekStartChange = useCallback(
(newWeekStart: dayjs.Dayjs) => {
setCurrentWeekStart(newWeekStart);
const startDate = newWeekStart.toDate();
const endDate = newWeekStart.add(6, "day").toDate();
if (!dateRange) {
return;
}
const rangeStart = dateRange.startDate ? new Date(dateRange.startDate) : null;
const rangeEnd = dateRange.endDate ? new Date(dateRange.endDate) : null;
const needsStartUpdate = !rangeStart || startDate < rangeStart;
const needsEndUpdate = !rangeEnd || endDate > rangeEnd;
if (!needsStartUpdate && !needsEndUpdate) {
return;
}
const newStartDate = needsStartUpdate ? startDate : rangeStart;
const newEndDate = needsEndUpdate ? endDate : rangeEnd;
updateFilter("dateRange", {
type: ColumnFilterType.DATE_RANGE,
data: {
startDate: newStartDate.toISOString(),
endDate: newEndDate.toISOString(),
preset: CUSTOM_PRESET.value,
},
});
},
[dateRange, updateFilter, setCurrentWeekStart]
);
return (
<>
<div className="mb-4 flex items-center justify-between">
<div className="flex items-center gap-2">
<DataTableFilters.FilterBar table={table} />
<DataTableFilters.FilterBar table={table} columnIdsToHide={COLUMN_IDS_TO_HIDE} />
</div>
<div className="flex items-center gap-2">
@@ -26,9 +99,11 @@ export function BookingsCalendar({ table }: BookingsCalendarViewProps) {
<DataTableSegment.Select />
</div>
</div>
<div className="flex items-center justify-center pt-2 xl:pt-0">
<EmptyScreen Icon="calendar" headline="Calendar view" description="Calendar view is coming soon." />
</div>
<BookingsCalendarView
bookings={bookings}
currentWeekStart={currentWeekStart}
onWeekStartChange={handleWeekStartChange}
/>
</>
);
}
@@ -0,0 +1,150 @@
"use client";
import { useMemo, useEffect } from "react";
import dayjs from "@calcom/dayjs";
import { useTimePreferences } from "@calcom/features/bookings/lib";
import { Calendar } from "@calcom/features/calendars/weeklyview";
import type { CalendarEvent } from "@calcom/features/calendars/weeklyview/types/events";
import { useLocale } from "@calcom/lib/hooks/useLocale";
import { useGetTheme } from "@calcom/lib/hooks/useTheme";
import { Button } from "@calcom/ui/components/button";
import { ButtonGroup } from "@calcom/ui/components/buttonGroup";
import { Icon } from "@calcom/ui/components/icon";
import type { BookingOutput } from "../types";
type BookingsCalendarViewProps = {
bookings: BookingOutput[];
currentWeekStart: dayjs.Dayjs;
onWeekStartChange: (weekStart: dayjs.Dayjs) => void;
};
export function BookingsCalendarView({
bookings,
currentWeekStart,
onWeekStartChange,
}: BookingsCalendarViewProps) {
const { t } = useLocale();
const { timezone } = useTimePreferences();
const { resolvedTheme, forcedTheme } = useGetTheme();
const goToPreviousWeek = () => {
onWeekStartChange(currentWeekStart.subtract(1, "week"));
};
const goToNextWeek = () => {
onWeekStartChange(currentWeekStart.add(1, "week"));
};
const goToToday = () => {
onWeekStartChange(dayjs().startOf("week"));
};
const startDate = useMemo(() => currentWeekStart.toDate(), [currentWeekStart]);
const endDate = useMemo(() => currentWeekStart.add(6, "day").toDate(), [currentWeekStart]);
useEffect(() => {
onWeekStartChange(currentWeekStart);
}, []);
const events = useMemo<CalendarEvent[]>(() => {
const hasDarkTheme = !forcedTheme && resolvedTheme === "dark";
return bookings
.filter((booking) => {
const bookingStart = dayjs(booking.startTime);
return (
(bookingStart.isAfter(currentWeekStart) || bookingStart.isSame(currentWeekStart)) &&
bookingStart.isBefore(currentWeekStart.add(7, "day"))
);
})
.sort((a, b) => {
const startDiff = new Date(a.startTime).getTime() - new Date(b.startTime).getTime();
if (startDiff !== 0) return startDiff;
return new Date(a.endTime).getTime() - new Date(b.endTime).getTime();
})
.map((booking, idx) => {
// Parse eventTypeColor and extract the appropriate color based on theme
const eventTypeColor =
booking.eventType?.eventTypeColor &&
booking.eventType.eventTypeColor[hasDarkTheme ? "darkEventTypeColor" : "lightEventTypeColor"];
return {
id: idx,
title: booking.title,
start: new Date(booking.startTime),
end: new Date(booking.endTime),
options: {
status: booking.status,
...(eventTypeColor && { color: eventTypeColor }),
},
};
});
}, [bookings, currentWeekStart, resolvedTheme, forcedTheme]);
const weekStart = currentWeekStart;
const weekEnd = currentWeekStart.add(6, "day");
const startMonth = weekStart.format("MMM");
const endMonth = weekEnd.format("MMM");
const year = weekEnd.format("YYYY");
const weekRange =
startMonth === endMonth ? (
<>
<span className="text-emphasis">{`${startMonth} ${weekStart.format("D")} - ${weekEnd.format(
"D"
)}`}</span>
<span className="text-muted">, {year}</span>
</>
) : (
<>
<span className="text-emphasis">{`${weekStart.format("MMM D")} - ${weekEnd.format("MMM D")}`}</span>
<span className="text-muted">, {year}</span>
</>
);
return (
<div className="border-subtle flex h-[calc(100vh-260px)] min-h-[600px] flex-col rounded-2xl border">
<div className="mx-4 mt-4 flex items-center justify-between py-1.5">
<div className="flex items-center gap-2">
<h2 className="text-xl font-semibold">{weekRange}</h2>
</div>
<div className="flex items-center gap-2">
<Button color="secondary" onClick={goToToday} className="capitalize leading-4">
{t("today")}
</Button>
<ButtonGroup combined>
<Button color="secondary" onClick={goToPreviousWeek}>
<span className="sr-only">{t("view_previous_week")}</span>
<Icon name="chevron-left" className="h-4 w-4" />
</Button>
<Button color="secondary" onClick={goToNextWeek}>
<span className="sr-only">{t("view_next_week")}</span>
<Icon name="chevron-right" className="h-4 w-4" />
</Button>
</ButtonGroup>
</div>
</div>
<div className="flex-1 overflow-y-auto overflow-x-hidden rounded-2xl">
<Calendar
timezone={timezone}
sortEvents
startHour={0}
endHour={23}
events={events}
startDate={startDate}
endDate={endDate}
gridCellsPerHour={4}
hoverEventDuration={0}
showBackgroundPattern={false}
showBorder={false}
borderColor="subtle"
onEventClick={(_event) => {}}
hideHeader
/>
</div>
</div>
);
}
@@ -40,6 +40,7 @@ type BookingsProps = {
permissions: {
canReadOthersBookings: boolean;
};
isCalendarViewEnabled: boolean;
};
function useSystemSegments(userId?: number) {
@@ -89,8 +90,10 @@ const viewParser = createParser({
serialize: (value: "list" | "calendar") => value,
});
function BookingsContent({ status, permissions }: BookingsProps) {
const [view] = useQueryState("view", viewParser.withDefault("list"));
function BookingsContent({ status, permissions, isCalendarViewEnabled }: BookingsProps) {
const [_view] = useQueryState("view", viewParser.withDefault("list"));
// Force view to be "list" if calendar view is disabled
const view = isCalendarViewEnabled ? _view : "list";
const { t } = useLocale();
const user = useMeQuery().data;
const searchParams = useSearchParams();
+1 -3
View File
@@ -86,9 +86,7 @@ function InsightsPageContent() {
className="flex flex-wrap items-center gap-2"
data-testid={`insights-filters-${isAll}-${teamId}-${userId}`}>
<OrgTeamsFilter />
<DataTableFilters.AddFilterButton table={table} hideWhenFilterApplied />
<DataTableFilters.ActiveFilters table={table} />
<DataTableFilters.AddFilterButton table={table} variant="sm" showWhenFilterApplied />
<DataTableFilters.FilterBar table={table} />
<DataTableFilters.ClearFiltersButton exclude={["startTime", "createdAt"]} />
<div className="grow" />
<Download />
@@ -3903,6 +3903,8 @@
"onboarding_plan_team_badge": "$15/user/mo",
"onboarding_plan_organization_badge": "$37/user/mo",
"onboarding_plan_organization_description": "Robust scheduling for larger teams looking to have more control, privacy, and security.",
"view_previous_week": "View previous week",
"view_next_week": "View next week",
"invite_teammates": "Invite Teammates",
"organization_brand": "Organization Brand",
"organization_details": "Organization Details",