Skip to content

Scheduling infrastructure for absolutely everyone.

refactor: Booker Component (#13176)

Morgan313bb8978976
diff --git a/packages/features/bookings/Booker/Booker.tsx b/packages/features/bookings/Booker/Booker.tsx
index 1164e057caf..244f799d489 100644
--- a/packages/features/bookings/Booker/Booker.tsx
+++ b/packages/features/bookings/Booker/Booker.tsx
@@ -1,35 +1,42 @@
import { LazyMotion, m, AnimatePresence } from "framer-motion";
import dynamic from "next/dynamic";
-import { usePathname, useRouter, useSearchParams } from "next/navigation";
-import { useEffect, useRef } from "react";
+import { useSearchParams } from "next/navigation";
+import { usePathname, useRouter } from "next/navigation";
+import { useEffect, useRef, useMemo } from "react";
import StickyBox from "react-sticky-box";
import { shallow } from "zustand/shallow";
import BookingPageTagManager from "@calcom/app-store/BookingPageTagManager";
import dayjs from "@calcom/dayjs";
-import { useEmbedType, useEmbedUiConfig, useIsEmbed } from "@calcom/embed-core/embed-iframe";
+import { getQueryParam } from "@calcom/features/bookings/Booker/utils/query-param";
import { useNonEmptyScheduleDays } from "@calcom/features/schedules";
import classNames from "@calcom/lib/classNames";
import { DEFAULT_LIGHT_BRAND_COLOR, DEFAULT_DARK_BRAND_COLOR } from "@calcom/lib/constants";
import { useLocale } from "@calcom/lib/hooks/useLocale";
-import useMediaQuery from "@calcom/lib/hooks/useMediaQuery";
-import { BookerLayouts, defaultBookerLayoutSettings } from "@calcom/prisma/zod-utils";
-import { Button } from "@calcom/ui";
+import { BookerLayouts } from "@calcom/prisma/zod-utils";
+import { VerifyCodeDialog } from "../components/VerifyCodeDialog";
import { AvailableTimeSlots } from "./components/AvailableTimeSlots";
import { BookEventForm } from "./components/BookEventForm";
import { BookFormAsModal } from "./components/BookEventForm/BookFormAsModal";
import { EventMeta } from "./components/EventMeta";
import { Header } from "./components/Header";
+import { InstantBooking } from "./components/InstantBooking";
import { LargeCalendar } from "./components/LargeCalendar";
+import { OverlayCalendar } from "./components/OverlayCalendar/OverlayCalendar";
+import { RedirectToInstantMeetingModal } from "./components/RedirectToInstantMeetingModal";
import { BookerSection } from "./components/Section";
import { Away, NotFound } from "./components/Unavailable";
-import { extraDaysConfig, fadeInLeft, getBookerSizeClassNames, useBookerResizeAnimation } from "./config";
+import { useBookerLayout } from "./components/hooks/useBookerLayout";
+import { useBookingForm } from "./components/hooks/useBookingForm";
+import { useBookings } from "./components/hooks/useBookings";
+import { useCalendars } from "./components/hooks/useCalendars";
+import { useSlots } from "./components/hooks/useSlots";
+import { useVerifyEmail } from "./components/hooks/useVerifyEmail";
+import { fadeInLeft, getBookerSizeClassNames, useBookerResizeAnimation } from "./config";
import { useBookerStore, useInitializeBookerStore } from "./store";
-import type { BookerLayout, BookerProps } from "./types";
+import type { BookerProps } from "./types";
import { useEvent, useScheduleForEvent } from "./utils/event";
-import { validateLayout } from "./utils/layout";
-import { getQueryParam } from "./utils/query-param";
import { useBrandColors } from "./utils/use-brand-colors";
const loadFramerFeatures = () => import("./framer-features").then((res) => res.default);
@@ -54,68 +61,61 @@ const BookerComponent = ({
hashedLink,
isInstantMeeting = false,
}: BookerProps) => {
+ const router = useRouter();
+ const pathname = usePathname();
+ const [bookerState, setBookerState] = useBookerStore((state) => [state.state, state.setState], shallow);
+ const selectedDate = useBookerStore((state) => state.selectedDate);
+ const [seatedEventData, setSeatedEventData] = useBookerStore(
+ (state) => [state.seatedEventData, state.setSeatedEventData],
+ shallow
+ );
+ const event = useEvent();
+ const { selectedTimeslot, setSelectedTimeslot } = useSlots(event);
+
+ const {
+ shouldShowFormInDialog,
+ hasDarkBackground,
+ extraDays,
+ columnViewExtraDays,
+ isMobile,
+ layout,
+ defaultLayout,
+ hideEventTypeDetails,
+ isEmbed,
+ bookerLayouts,
+ } = useBookerLayout(event.data);
+ const date = dayjs(selectedDate).format("YYYY-MM-DD");
+
+ const prefetchNextMonth =
+ (layout === BookerLayouts.WEEK_VIEW &&
+ !!extraDays &&
+ dayjs(date).month() !== dayjs(date).add(extraDays, "day").month()) ||
+ (layout === BookerLayouts.COLUMN_VIEW &&
+ dayjs(date).month() !== dayjs(date).add(columnViewExtraDays.current, "day").month());
+
+ const monthCount =
+ ((layout !== BookerLayouts.WEEK_VIEW && bookerState === "selecting_time") ||
+ layout === BookerLayouts.COLUMN_VIEW) &&
+ dayjs(date).add(1, "month").month() !== dayjs(date).add(columnViewExtraDays.current, "day").month()
+ ? 2
+ : undefined;
+
/**
* Prioritize dateSchedule load
* Component will render but use data already fetched from here, and no duplicate requests will be made
* */
const schedule = useScheduleForEvent({
- prefetchNextMonth: false,
+ prefetchNextMonth,
username,
+ monthCount,
eventSlug,
month,
duration,
});
- const isMobile = useMediaQuery("(max-width: 768px)");
- const isTablet = useMediaQuery("(max-width: 1024px)");
- const timeslotsRef = useRef<HTMLDivElement>(null);
- const StickyOnDesktop = isMobile ? "div" : StickyBox;
- const rescheduleUid =
- typeof window !== "undefined" ? new URLSearchParams(window.location.search).get("rescheduleUid") : null;
- const bookingUid =
- typeof window !== "undefined" ? new URLSearchParams(window.location.search).get("bookingUid") : null;
- const event = useEvent();
- const [_layout, setLayout] = useBookerStore((state) => [state.layout, state.setLayout], shallow);
-
- const isEmbed = useIsEmbed();
- const embedType = useEmbedType();
- // Floating Button and Element Click both are modal and thus have dark background
- const hasDarkBackground = isEmbed && embedType !== "inline";
- const embedUiConfig = useEmbedUiConfig();
-
- const { t } = useLocale();
-
- const searchParams = useSearchParams();
- const isRedirect = searchParams?.get("redirected") === "true" || false;
- const fromUserNameRedirected = searchParams?.get("username") || "";
-
- // In Embed we give preference to embed configuration for the layout.If that's not set, we use the App configuration for the event layout
- // But if it's mobile view, there is only one layout supported which is 'mobile'
- const layout = isEmbed ? (isMobile ? "mobile" : validateLayout(embedUiConfig.layout) || _layout) : _layout;
- const columnViewExtraDays = useRef<number>(
- isTablet ? extraDaysConfig[layout].tablet : extraDaysConfig[layout].desktop
- );
-
- const [bookerState, setBookerState] = useBookerStore((state) => [state.state, state.setState], shallow);
- const selectedDate = useBookerStore((state) => state.selectedDate);
- const [selectedTimeslot, setSelectedTimeslot] = useBookerStore(
- (state) => [state.selectedTimeslot, state.setSelectedTimeslot],
- shallow
- );
- // const seatedEventData = useBookerStore((state) => state.seatedEventData);
- const [seatedEventData, setSeatedEventData] = useBookerStore(
- (state) => [state.seatedEventData, state.setSeatedEventData],
- shallow
- );
-
- const date = dayjs(selectedDate).format("YYYY-MM-DD");
const nonEmptyScheduleDays = useNonEmptyScheduleDays(schedule?.data?.slots).filter(
(slot) => dayjs(selectedDate).diff(slot, "day") <= 0
);
-
- const extraDays = isTablet ? extraDaysConfig[layout].tablet : extraDaysConfig[layout].desktop;
- const bookerLayouts = event.data?.profile?.bookerLayouts || defaultBookerLayoutSettings;
- const animationScope = useBookerResizeAnimation(layout, bookerState);
const totalWeekDays = 7;
const addonDays =
nonEmptyScheduleDays.length < extraDays
@@ -123,26 +123,28 @@ const BookerComponent = ({
: nonEmptyScheduleDays.length === extraDays
? totalWeekDays
: 0;
-
// Taking one more available slot(extraDays + 1) to calculate the no of days in between, that next and prev button need to shift.
const availableSlots = nonEmptyScheduleDays.slice(0, extraDays + 1);
if (nonEmptyScheduleDays.length !== 0)
columnViewExtraDays.current =
Math.abs(dayjs(selectedDate).diff(availableSlots[availableSlots.length - 2], "day")) + addonDays;
- const prefetchNextMonth =
- layout === BookerLayouts.COLUMN_VIEW &&
- dayjs(date).month() !== dayjs(date).add(columnViewExtraDays.current, "day").month();
- const monthCount =
- dayjs(date).add(1, "month").month() !== dayjs(date).add(columnViewExtraDays.current, "day").month()
- ? 2
- : undefined;
const nextSlots =
Math.abs(dayjs(selectedDate).diff(availableSlots[availableSlots.length - 1], "day")) + addonDays;
- // I would expect isEmbed to be not needed here as it's handled in derived variable layout, but somehow removing it breaks the views.
- const defaultLayout = isEmbed
- ? validateLayout(embedUiConfig.layout) || bookerLayouts.defaultLayout
- : bookerLayouts.defaultLayout;
+ const animationScope = useBookerResizeAnimation(layout, bookerState);
+
+ const timeslotsRef = useRef<HTMLDivElement>(null);
+ const StickyOnDesktop = isMobile ? "div" : StickyBox;
+ const rescheduleUid =
+ typeof window !== "undefined" ? new URLSearchParams(window.location.search).get("rescheduleUid") : null;
+ const bookingUid =
+ typeof window !== "undefined" ? new URLSearchParams(window.location.search).get("bookingUid") : null;
+
+ const { t } = useLocale();
+
+ const searchParams = useSearchParams();
+ const isRedirect = searchParams?.get("redirected") === "true" || false;
+ const fromUserNameRedirected = searchParams?.get("username") || "";
useBrandColors({
brandColor: event.data?.profile.brandColor ?? DEFAULT_LIGHT_BRAND_COLOR,
@@ -165,28 +167,44 @@ const BookerComponent = ({
isInstantMeeting,
});
- useEffect(() => {
- if (isMobile && layout !== "mobile") {
- setLayout("mobile");
- } else if (!isMobile && layout === "mobile") {
- setLayout(defaultLayout);
- }
- }, [isMobile, setLayout, layout, defaultLayout]);
-
- //setting layout from query param
- useEffect(() => {
- const layout = getQueryParam("layout") as BookerLayouts;
- if (
- !isMobile &&
- !isEmbed &&
- validateLayout(layout) &&
- bookerLayouts?.enabledLayouts?.length &&
- layout !== _layout
- ) {
- const validLayout = bookerLayouts.enabledLayouts.find((userLayout) => userLayout === layout);
- validLayout && setLayout(validLayout);
- }
- }, [bookerLayouts, validateLayout, setLayout, _layout]);
+ const {
+ bookerFormErrorRef,
+ key,
+ formEmail,
+ formName,
+ bookingForm,
+ beforeVerifyEmail,
+ errors: formErrors,
+ } = useBookingForm({
+ event,
+ });
+
+ const { handleBookEvent, hasInstantMeetingTokenExpired, errors, loadingStates } = useBookings({
+ event,
+ hashedLink,
+ bookingForm,
+ });
+
+ const {
+ isEmailVerificationModalVisible,
+ setEmailVerificationModalVisible,
+ handleVerifyEmail,
+ setVerifiedEmail,
+ renderConfirmNotVerifyEmailButtonCond,
+ } = useVerifyEmail({
+ email: formEmail,
+ name: formName,
+ requiresBookerEmailVerification: event?.data?.requiresBookerEmailVerification,
+ onVerifyEmail: beforeVerifyEmail,
+ });
+
+ const {
+ overlayBusyDates,
+ isOverlayCalendarEnabled,
+ connectedCalendars,
+ loadingConnectedCalendar,
+ onToggleCalendar,
+ } = useCalendars();
useEffect(() => {
if (event.isLoading) return setBookerState("loading");
@@ -195,7 +213,74 @@ const BookerComponent = ({
return setBookerState("booking");
}, [event, selectedDate, selectedTimeslot, setBookerState]);
- const hideEventTypeDetails = isEmbed ? embedUiConfig.hideEventTypeDetails : false;
+ const EventBooker = useMemo(
+ () =>
+ bookerState === "booking" ? (
+ <BookEventForm
+ key={key}
+ onCancel={() => {
+ setSelectedTimeslot(null);
+ if (seatedEventData.bookingUid) {
+ setSeatedEventData({ ...seatedEventData, bookingUid: undefined, attendees: undefined });
+ }
+ }}
+ onSubmit={renderConfirmNotVerifyEmailButtonCond ? handleBookEvent : handleVerifyEmail}
+ errorRef={bookerFormErrorRef}
+ errors={{ ...formErrors, ...errors }}
+ loadingStates={loadingStates}
+ renderConfirmNotVerifyEmailButtonCond={renderConfirmNotVerifyEmailButtonCond}
+ bookingForm={bookingForm}
+ eventQuery={event}
+ rescheduleUid={rescheduleUid}>
+ <>
+ <VerifyCodeDialog
+ isOpenDialog={isEmailVerificationModalVisible}
+ setIsOpenDialog={setEmailVerificationModalVisible}
+ email={formEmail}
+ onSuccess={() => {
+ setVerifiedEmail(formEmail);
+ setEmailVerificationModalVisible(false);
+ handleBookEvent();
+ }}
+ isUserSessionRequiredToVerify={false}
+ />
+ <RedirectToInstantMeetingModal
+ hasInstantMeetingTokenExpired={hasInstantMeetingTokenExpired}
+ bookingId={parseInt(getQueryParam("bookingId") || "0")}
+ onGoBack={() => {
+ // Prevent null on app directory
+ if (pathname) window.location.href = pathname;
+ }}
+ />
+ </>
+ </BookEventForm>
+ ) : (
+ <></>
+ ),
+ [
+ bookerFormErrorRef,
+ bookerState,
+ bookingForm,
+ errors,
+ event,
+ formEmail,
+ formErrors,
+ handleBookEvent,
+ handleVerifyEmail,
+ hasInstantMeetingTokenExpired,
+ isEmailVerificationModalVisible,
+ key,
+ loadingStates,
+ pathname,
+ renderConfirmNotVerifyEmailButtonCond,
+ rescheduleUid,
+ seatedEventData,
+ setEmailVerificationModalVisible,
+ setSeatedEventData,
+ setSelectedTimeslot,
+ setVerifiedEmail,
+ ]
+ );
if (entity.isUnpublished) {
return <UnpublishedEntity {...entity} />;
@@ -205,22 +290,6 @@ const BookerComponent = ({
return <NotFound />;
}
- // In Embed, a Dialog doesn't look good, we disable it intentionally for the layouts that support showing Form without Dialog(i.e. no-dialog Form)
- const shouldShowFormInDialogMap: Record<BookerLayout, boolean> = {
- // mobile supports showing the Form without Dialog
- mobile: !isEmbed,
- // We don't show Dialog in month_view currently. Can be easily toggled though as it supports no-dialog Form
- month_view: false,
- // week_view doesn't support no-dialog Form
- // When it's supported, disable it for embed
- week_view: true,
- // column_view doesn't support no-dialog Form
- // When it's supported, disable it for embed
- column_view: true,
- };
-
- const shouldShowFormInDialog = shouldShowFormInDialogMap[layout];
-
if (bookerState === "loading") {
return null;
}
@@ -233,7 +302,12 @@ const BookerComponent = ({
<div
className="animate-fade-in-up fixed bottom-2 z-40 my-2 opacity-0"
style={{ animationDelay: "2s" }}>
- <InstantBooking />
+ <InstantBooking
+ onConnectNow={() => {
+ const newPath = `${pathname}?isInstantMeeting=true`;
+ router.push(newPath);
+ }}
+ />
</div>
)}
<div
@@ -285,12 +359,30 @@ const BookerComponent = ({
"bg-default dark:bg-muted sticky top-0 z-10"
)}>
<Header
- username={username}
+ isMyLink={Boolean(username === event?.data?.owner?.username)}
eventSlug={eventSlug}
enabledLayouts={bookerLayouts.enabledLayouts}
extraDays={layout === BookerLayouts.COLUMN_VIEW ? columnViewExtraDays.current : extraDays}
isMobile={isMobile}
nextSlots={nextSlots}
+ renderOverlay={() =>
+ isEmbed ? (
+ <></>
+ ) : (
+ <>
+ <OverlayCalendar
+ isOverlayCalendarEnabled={isOverlayCalendarEnabled}
+ connectedCalendars={connectedCalendars}
+ loadingConnectedCalendar={loadingConnectedCalendar}
+ overlayBusyDates={overlayBusyDates}
+ onToggleCalendar={onToggleCalendar}
+ handleClickNoCalendar={() => {
+ router.push("/apps/categories/calendar");
+ }}
+ />
+ </>
+ )
+ }
/>
</BookerSection>
)}
@@ -304,11 +396,11 @@ const BookerComponent = ({
<BookerSection
area="meta"
className="max-w-screen flex w-full flex-col md:w-[var(--booker-meta-width)]">
- <EventMeta />
+ <EventMeta event={event.data} isLoading={event.isLoading} />
{layout !== BookerLayouts.MONTH_VIEW &&
!(layout === "mobile" && bookerState === "booking") && (
<div className="mt-auto px-5 py-3 ">
- <DatePicker />
+ <DatePicker event={event} schedule={schedule} />
</div>
)}
</BookerSection>
@@ -320,15 +412,7 @@ const BookerComponent = ({
className="border-subtle sticky top-0 ml-[-1px] h-full p-6 md:w-[var(--booker-main-width)] md:border-l"
{...fadeInLeft}
visible={bookerState === "booking" && !shouldShowFormInDialog}>
- <BookEventForm
- onCancel={() => {
- setSelectedTimeslot(null);
- if (seatedEventData.bookingUid) {
- setSeatedEventData({ ...seatedEventData, bookingUid: undefined, attendees: undefined });
- }
- }}
- hashedLink={hashedLink}
- />
+ {EventBooker}
</BookerSection>
<BookerSection
@@ -338,7 +422,7 @@ const BookerComponent = ({
{...fadeInLeft}
initial="visible"
className="md:border-subtle ml-[-1px] h-full flex-shrink px-5 py-3 md:border-l lg:w-[var(--booker-main-width)]">
- <DatePicker />
+ <DatePicker event={event} schedule={schedule} />
</BookerSection>
<BookerSection
@@ -347,7 +431,7 @@ const BookerComponent = ({
visible={layout === BookerLayouts.WEEK_VIEW}
className="border-subtle sticky top-0 ml-[-1px] h-full md:border-l"
{...fadeInLeft}>
- <LargeCalendar extraDays={extraDays} />
+ <LargeCalendar extraDays={extraDays} schedule={schedule.data} isLoading={schedule.isLoading} />
</BookerSection>
<BookerSection
@@ -368,8 +452,8 @@ const BookerComponent = ({
<AvailableTimeSlots
extraDays={extraDays}
limitHeight={layout === BookerLayouts.MONTH_VIEW}
- prefetchNextMonth={prefetchNextMonth}
- monthCount={monthCount}
+ schedule={schedule?.data}
+ isLoading={schedule.isLoading}
seatsPerTimeSlot={event.data?.seatsPerTimeSlot}
showAvailableSeatsCount={event.data?.seatsShowAvailabilityCount}
/>
@@ -389,9 +473,10 @@ const BookerComponent = ({
</div>
<BookFormAsModal
- visible={bookerState === "booking" && shouldShowFormInDialog}
onCancel={() => setSelectedTimeslot(null)}
- />
+ visible={bookerState === "booking" && shouldShowFormInDialog}>
+ {EventBooker}
+ </BookFormAsModal>
</>
);
};
@@ -405,54 +490,3 @@ export const Booker = (props: BookerProps) => {
</LazyMotion>
);
};
-
-export const InstantBooking = () => {
- const { t } = useLocale();
- const router = useRouter();
- const pathname = usePathname();
-
- return (
- <div className=" bg-default border-subtle mx-2 block items-center gap-3 rounded-xl border p-[6px] text-sm shadow-sm delay-1000 sm:flex">
- <div className="flex items-center gap-3 ps-1">
- {/* TODO: max. show 4 people here */}
- <div className="relative">
- {/* <AvatarGroup
- size="sm"
- className="relative"
- items={[
- {
- image: "https://cal.com/stakeholder/peer.jpg",
- alt: "Peer",
- title: "Peer Richelsen",
- },
- {
- image: "https://cal.com/stakeholder/bailey.jpg",
- alt: "Bailey",
- title: "Bailey Pumfleet",
- },
- {
- image: "https://cal.com/stakeholder/alex-van-andel.jpg",
- alt: "Alex",
- title: "Alex Van Andel",
- },
- ]}
- /> */}
- <div className="border-muted absolute -bottom-0.5 -right-1 h-2 w-2 rounded-full border bg-green-500" />
- </div>
- <div>{t("dont_want_to_wait")}</div>
- </div>
- <div className="mt-2 sm:mt-0">
- <Button
- color="primary"
- onClick={() => {
- const newPath = `${pathname}?isInstantMeeting=true`;
- router.push(newPath);
- }}
- size="sm"
- className="w-full justify-center rounded-lg sm:w-auto">
- {t("connect_now")}
- </Button>
- </div>
- </div>
- );
-};
diff --git a/packages/features/bookings/Booker/components/AvailableTimeSlots.tsx b/packages/features/bookings/Booker/components/AvailableTimeSlots.tsx
index e01b40ef1e9..f308ce22f89 100644
--- a/packages/features/bookings/Booker/components/AvailableTimeSlots.tsx
+++ b/packages/features/bookings/Booker/components/AvailableTimeSlots.tsx
@@ -1,24 +1,21 @@
import { useRef } from "react";
import dayjs from "@calcom/dayjs";
-import { useIsEmbed } from "@calcom/embed-core/embed-iframe";
import { AvailableTimes, AvailableTimesSkeleton } from "@calcom/features/bookings";
import { useNonEmptyScheduleDays } from "@calcom/features/schedules";
import { useSlotsForAvailableDates } from "@calcom/features/schedules/lib/use-schedule/useSlotsForDate";
import { classNames } from "@calcom/lib";
-import useMediaQuery from "@calcom/lib/hooks/useMediaQuery";
import { BookerLayouts } from "@calcom/prisma/zod-utils";
-import { trpc } from "@calcom/trpc";
import { AvailableTimesHeader } from "../../components/AvailableTimesHeader";
import { useBookerStore } from "../store";
-import { useEvent, useScheduleForEvent } from "../utils/event";
+import type { useScheduleForEventReturnType } from "../utils/event";
type AvailableTimeSlotsProps = {
extraDays?: number;
limitHeight?: boolean;
- prefetchNextMonth: boolean;
- monthCount: number | undefined;
+ schedule?: useScheduleForEventReturnType["data"];
+ isLoading: boolean;
seatsPerTimeSlot?: number | null;
showAvailableSeatsCount?: boolean | null;
};
@@ -35,16 +32,12 @@ export const AvailableTimeSlots = ({
limitHeight,
seatsPerTimeSlot,
showAvailableSeatsCount,
- prefetchNextMonth,
- monthCount,
+ schedule,
+ isLoading,
}: AvailableTimeSlotsProps) => {
- const reserveSlotMutation = trpc.viewer.public.slots.reserveSlot.useMutation();
- const isMobile = useMediaQuery("(max-width: 768px)");
const selectedDate = useBookerStore((state) => state.selectedDate);
const setSelectedTimeslot = useBookerStore((state) => state.setSelectedTimeslot);
const setSeatedEventData = useBookerStore((state) => state.setSeatedEventData);
- const isEmbed = useIsEmbed();
- const event = useEvent();
const date = selectedDate || dayjs().format("YYYY-MM-DD");
const [layout] = useBookerStore((state) => [state.layout]);
const isColumnView = layout === BookerLayouts.COLUMN_VIEW;
@@ -57,7 +50,6 @@ export const AvailableTimeSlots = ({
bookingUid?: string
) => {
setSelectedTimeslot(time);
-
if (seatsPerTimeSlot) {
setSeatedEventData({
seatsPerTimeSlot,
@@ -65,20 +57,11 @@ export const AvailableTimeSlots = ({
bookingUid,
showAvailableSeatsCount,
});
-
- if (seatsPerTimeSlot && seatsPerTimeSlot - attendees > 1) {
- return;
- }
}
-
- if (!event.data) return;
+ return;
};
- const schedule = useScheduleForEvent({
- prefetchNextMonth,
- monthCount,
- });
- const nonEmptyScheduleDays = useNonEmptyScheduleDays(schedule?.data?.slots);
+ const nonEmptyScheduleDays = useNonEmptyScheduleDays(schedule?.slots);
const nonEmptyScheduleDaysFromSelectedDate = nonEmptyScheduleDays.filter(
(slot) => dayjs(selectedDate).diff(slot, "day") <= 0
);
@@ -91,12 +74,12 @@ export const AvailableTimeSlots = ({
? nonEmptyScheduleDaysFromSelectedDate.slice(0, extraDays)
: [];
- const slotsPerDay = useSlotsForAvailableDates(dates, schedule?.data?.slots);
+ const slotsPerDay = useSlotsForAvailableDates(dates, schedule?.slots);
return (
<>
<div className="flex">
- {schedule.isLoading ? (
+ {isLoading ? (
<div className="mb-3 h-8" />
) : (
slotsPerDay.length > 0 &&
@@ -120,7 +103,7 @@ export const AvailableTimeSlots = ({
limitHeight && "scroll-bar flex-grow overflow-auto md:h-[400px]",
!limitHeight && "flex h-full w-full flex-row gap-4"
)}>
- {schedule.isLoading
+ {isLoading
? // Shows exact amount of days as skeleton.
Array.from({ length: 1 + (extraDays ?? 0) }).map((_, i) => <AvailableTimesSkeleton key={i} />)
: slotsPerDay.length > 0 &&
diff --git a/packages/features/bookings/Booker/components/BookEventForm/BookEventForm.tsx b/packages/features/bookings/Booker/components/BookEventForm/BookEventForm.tsx
index 53b2054ab0d..56047cdff24 100644
--- a/packages/features/bookings/Booker/components/BookEventForm/BookEventForm.tsx
+++ b/packages/features/bookings/Booker/components/BookEventForm/BookEventForm.tsx
@@ -1,182 +1,59 @@
-import { zodResolver } from "@hookform/resolvers/zod";
-import type { UseMutationResult } from "@tanstack/react-query";
-import { useMutation } from "@tanstack/react-query";
-import { useSession } from "next-auth/react";
import type { TFunction } from "next-i18next";
import { Trans } from "next-i18next";
import Link from "next/link";
-import { useRouter, useSearchParams, usePathname } from "next/navigation";
-import { useEffect, useRef, useState, useMemo } from "react";
+import { useState, useMemo } from "react";
import type { FieldError } from "react-hook-form";
-import { useForm } from "react-hook-form";
-import { z } from "zod";
-import type { EventLocationType } from "@calcom/app-store/locations";
-import { createPaymentLink } from "@calcom/app-store/stripepayment/lib/client";
-import dayjs from "@calcom/dayjs";
-import { updateQueryParam, getQueryParam } from "@calcom/features/bookings/Booker/utils/query-param";
-import { VerifyCodeDialog } from "@calcom/features/bookings/components/VerifyCodeDialog";
-import {
- createBooking,
- createRecurringBooking,
- mapBookingToMutationInput,
- mapRecurringBookingToMutationInput,
- useTimePreferences,
- createInstantBooking,
-} from "@calcom/features/bookings/lib";
-import getBookingResponsesSchema, {
- getBookingResponsesPartialSchema,
-} from "@calcom/features/bookings/lib/getBookingResponsesSchema";
-import { getFullName } from "@calcom/features/form-builder/utils";
-import { useBookingSuccessRedirect } from "@calcom/lib/bookingSuccessRedirect";
import { WEBSITE_URL } from "@calcom/lib/constants";
-import { MINUTES_TO_BOOK } from "@calcom/lib/constants";
import getPaymentAppData from "@calcom/lib/getPaymentAppData";
import { useLocale } from "@calcom/lib/hooks/useLocale";
import { useRouterQuery } from "@calcom/lib/hooks/useRouterQuery";
-import { bookingMetadataSchema } from "@calcom/prisma/zod-utils";
-import { trpc } from "@calcom/trpc";
-import { Dialog, DialogContent } from "@calcom/ui";
-import { Alert, Button, EmptyScreen, Form, showToast } from "@calcom/ui";
+import { Alert, Button, EmptyScreen, Form } from "@calcom/ui";
import { Calendar } from "@calcom/ui/components/icon";
import { useBookerStore } from "../../store";
-import { useSlotReservationId } from "../../useSlotReservationId";
-import { useEvent } from "../../utils/event";
+import type { useEventReturnType } from "../../utils/event";
+import type { useBookingFormReturnType } from "../hooks/useBookingForm";
+import type { IUseBookingErrors, IUseBookingLoadingStates } from "../hooks/useBookings";
import { BookingFields } from "./BookingFields";
import { FormSkeleton } from "./Skeleton";
type BookEventFormProps = {
onCancel?: () => void;
- hashedLink?: string | null;
+ onSubmit: () => void;
+ errorRef: React.RefObject<HTMLDivElement>;
+ errors: useBookingFormReturnType["errors"] & IUseBookingErrors;
+ loadingStates: IUseBookingLoadingStates;
+ children?: React.ReactNode;
+ bookingForm: useBookingFormReturnType["bookingForm"];
+ renderConfirmNotVerifyEmailButtonCond: boolean;
};
-type DefaultValues = Record<string, unknown>;
-
-export const BookEventForm = ({ onCancel, hashedLink }: BookEventFormProps) => {
- const [slotReservationId, setSlotReservationId] = useSlotReservationId();
- const reserveSlotMutation = trpc.viewer.public.slots.reserveSlot.useMutation({
- trpc: {
- context: {
- skipBatch: true,
- },
- },
- onSuccess: (data) => {
- setSlotReservationId(data.uid);
- },
- });
- const removeSelectedSlot = trpc.viewer.public.slots.removeSelectedSlotMark.useMutation({
- trpc: { context: { skipBatch: true } },
- });
-
- const rescheduleUid = useBookerStore((state) => state.rescheduleUid);
- const bookingData = useBookerStore((state) => state.bookingData);
- const duration = useBookerStore((state) => state.selectedDuration);
- const timeslot = useBookerStore((state) => state.selectedTimeslot);
- const isInstantMeeting = useBookerStore((state) => state.isInstantMeeting);
- const isRescheduling = !!rescheduleUid && !!bookingData;
- const eventQuery = useEvent();
- const eventType = eventQuery.data;
-
- const reserveSlot = () => {
- if (eventType?.id && timeslot && (duration || eventType?.length)) {
- reserveSlotMutation.mutate({
- slotUtcStartDate: dayjs(timeslot).utc().format(),
- eventTypeId: eventType?.id,
- slotUtcEndDate: dayjs(timeslot)
- .utc()
- .add(duration || eventType?.length, "minutes")
- .format(),
- });
- }
- };
-
- useEffect(() => {
- reserveSlot();
-
- const interval = setInterval(() => {
- reserveSlot();
- }, parseInt(MINUTES_TO_BOOK) * 60 * 1000 - 2000);
-
- return () => {
- if (eventType) {
- removeSelectedSlot.mutate({ uid: slotReservationId });
- }
- clearInterval(interval);
- };
- // eslint-disable-next-line react-hooks/exhaustive-deps
- }, [eventType?.id, timeslot]);
-
- const { initialValues, key } = useInitialFormValues({
- eventType,
- rescheduleUid,
- isRescheduling,
- });
-
- return (
- <BookEventFormChild
- // initialValues would be null initially as the async schema parsing is happening. Let's show the form in first render without any prefill values
- // But ensure that when initialValues is available, the form is reset and rerendered with the prefill values
- key={key}
- onCancel={onCancel}
- initialValues={initialValues}
- isRescheduling={isRescheduling}
- eventQuery={eventQuery}
- rescheduleUid={rescheduleUid}
- hashedLink={hashedLink}
- isInstantMeeting={isInstantMeeting}
- />
- );
-};
-
-export const BookEventFormChild = ({
+export const BookEventForm = ({
onCancel,
- initialValues,
- isRescheduling,
eventQuery,
rescheduleUid,
- hashedLink,
- isInstantMeeting,
-}: BookEventFormProps & {
- initialValues: DefaultValues;
- isRescheduling: boolean;
- eventQuery: ReturnType<typeof useEvent>;
+ onSubmit,
+ errorRef,
+ errors,
+ loadingStates,
+ renderConfirmNotVerifyEmailButtonCond,
+ bookingForm,
+ children,
+}: Omit<BookEventFormProps, "event"> & {
+ eventQuery: useEventReturnType;
rescheduleUid: string | null;
- hashedLink?: string | null;
- isInstantMeeting?: boolean;
}) => {
const eventType = eventQuery.data;
- const bookingFormSchema = z
- .object({
- responses: eventQuery?.data
- ? getBookingResponsesSchema({
- eventType: eventQuery?.data,
- view: rescheduleUid ? "reschedule" : "booking",
- })
- : // Fallback until event is loaded.
- z.object({}),
- })
- .passthrough();
- const searchParams = useSearchParams();
const routerQuery = useRouterQuery();
const setFormValues = useBookerStore((state) => state.setFormValues);
- const seatedEventData = useBookerStore((state) => state.seatedEventData);
- const verifiedEmail = useBookerStore((state) => state.verifiedEmail);
- const setVerifiedEmail = useBookerStore((state) => state.setVerifiedEmail);
- const bookingSuccessRedirect = useBookingSuccessRedirect();
- const [responseVercelIdHeader, setResponseVercelIdHeader] = useState<string | null>(null);
-
- const router = useRouter();
- const { t, i18n } = useLocale();
- const { timezone } = useTimePreferences();
- const errorRef = useRef<HTMLDivElement>(null);
const bookingData = useBookerStore((state) => state.bookingData);
- const eventSlug = useBookerStore((state) => state.eventSlug);
- const duration = useBookerStore((state) => state.selectedDuration);
const timeslot = useBookerStore((state) => state.selectedTimeslot);
- const recurringEventCount = useBookerStore((state) => state.recurringEventCount);
const username = useBookerStore((state) => state.username);
- const [expiryTime, setExpiryTime] = useState<Date | undefined>();
+ const isInstantMeeting = useBookerStore((state) => state.isInstantMeeting);
+
+ const [responseVercelIdHeader] = useState<string | null>(null);
+ const { t } = useLocale();
const isPaidEvent = useMemo(() => {
if (!eventType?.price) return false;
@@ -184,143 +61,6 @@ export const BookEventFormChild = ({
return eventType?.price > 0 || paymentAppData.price > 0;
}, [eventType]);
- type BookingFormValues = {
- locationType?: EventLocationType["type"];
- responses: z.infer<typeof bookingFormSchema>["responses"] | null;
- // Key is not really part of form values, but only used to have a key
- // to set generic error messages on. Needed until RHF has implemented root error keys.
- globalError: undefined;
- };
-
- const bookingForm = useForm<BookingFormValues>({
- defaultValues: initialValues,
- resolver: zodResolver(
- // Since this isn't set to strict we only validate the fields in the schema
- bookingFormSchema,
- {},
- {
- // bookingFormSchema is an async schema, so inform RHF to do async validation.
- mode: "async",
- }
- ),
- });
- const createBookingMutation = useMutation(createBooking, {
- onSuccess: (responseData) => {
- const { uid, paymentUid } = responseData;
- const fullName = getFullName(bookingForm.getValues("responses.name"));
- if (paymentUid) {
- router.push(
- createPaymentLink({
- paymentUid,
- date: timeslot,
- name: fullName,
- email: bookingForm.getValues("responses.email"),
- absolute: false,
- })
- );
- return;
- }
-
- if (!uid) {
- console.error("No uid returned from createBookingMutation");
- return;
- }
-
- const query = {
- isSuccessBookingPage: true,
- email: bookingForm.getValues("responses.email"),
- eventTypeSlug: eventSlug,
- seatReferenceUid: "seatReferenceUid" in responseData ? responseData.seatReferenceUid : null,
- formerTime:
- isRescheduling && bookingData?.startTime ? dayjs(bookingData.startTime).toString() : undefined,
- };
-
- bookingSuccessRedirect({
- successRedirectUrl: eventType?.successRedirectUrl || "",
- query,
- booking: responseData,
- });
- },
- onError: (err, _, ctx) => {
- // TODO:
- // const vercelId = ctx?.meta?.headers?.get("x-vercel-id");
- // if (vercelId) {
- // setResponseVercelIdHeader(vercelId);
- // }
- errorRef && errorRef.current?.scrollIntoView({ behavior: "smooth" });
- },
- });
-
- const createInstantBookingMutation = useMutation(createInstantBooking, {
- onSuccess: (responseData) => {
- updateQueryParam("bookingId", responseData.bookingId);
- setExpiryTime(responseData.expires);
- },
- onError: (err, _, ctx) => {
- console.error("Error creating instant booking", err);
-
- errorRef && errorRef.current?.scrollIntoView({ behavior: "smooth" });
- },
- });
-
- const createRecurringBookingMutation = useMutation(createRecurringBooking, {
- onSuccess: async (responseData) => {
- const booking = responseData[0] || {};
- const { uid } = booking;
-
- if (!uid) {
- console.error("No uid returned from createRecurringBookingMutation");
- return;
- }
-
- const query = {
- isSuccessBookingPage: true,
- allRemainingBookings: true,
- email: bookingForm.getValues("responses.email"),
- eventTypeSlug: eventSlug,
- formerTime:
- isRescheduling && bookingData?.startTime ? dayjs(bookingData.startTime).toString() : undefined,
- };
-
- bookingSuccessRedirect({
- successRedirectUrl: eventType?.successRedirectUrl || "",
- query,
- booking,
- });
- },
- });
-
- const [isEmailVerificationModalVisible, setEmailVerificationModalVisible] = useState(false);
- const email = bookingForm.watch("responses.email");
-
- const sendEmailVerificationByCodeMutation = trpc.viewer.auth.sendVerifyEmailCode.useMutation({
- onSuccess() {
- showToast(t("email_sent"), "success");
- },
- onError() {
- showToast(t("email_not_sent"), "error");
- },
- });
-
- const verifyEmail = () => {
- bookingForm.clearErrors();
-
- // It shouldn't be possible that this method is fired without having event data,
- // but since in theory (looking at the types) it is possible, we still handle that case.
- if (!eventQuery?.data) {
- bookingForm.setError("globalError", { message: t("error_booking_event") });
- return;
- }
-
- const name = bookingForm.getValues("responses.name");
-
- sendEmailVerificationByCodeMutation.mutate({
- email,
- username: typeof name === "string" ? name : name.firstName,
- });
- setEmailVerificationModalVisible(true);
- };
-
if (eventQuery.isError) return <Alert severity="warning" message={t("error_booking_event")} />;
if (eventQuery.isLoading || !eventQuery.data) return <FormSkeleton />;
if (!timeslot)
@@ -334,66 +74,11 @@ export const BookEventFormChild = ({
/>
);
- const bookEvent = (values: BookingFormValues) => {
- // It shouldn't be possible that this method is fired without having eventQuery data,
- // but since in theory (looking at the types) it is possible, we still handle that case.
- if (!eventQuery?.data) {
- bookingForm.setError("globalError", { message: t("error_booking_event") });
- return;
- }
-
- // Ensures that duration is an allowed value, if not it defaults to the
- // default eventQuery duration.
- const validDuration = eventQuery.data.isDynamic
- ? duration || eventQuery.data.length
- : duration && eventQuery.data.metadata?.multipleDuration?.includes(duration)
- ? duration
- : eventQuery.data.length;
-
- const bookingInput = {
- values,
- duration: validDuration,
- event: eventQuery.data,
- date: timeslot,
- timeZone: timezone,
- language: i18n.language,
- rescheduleUid: rescheduleUid || undefined,
- bookingUid: (bookingData && bookingData.uid) || seatedEventData?.bookingUid || undefined,
- username: username || "",
- metadata: Object.keys(routerQuery)
- .filter((key) => key.startsWith("metadata"))
- .reduce(
- (metadata, key) => ({
- ...metadata,
- [key.substring("metadata[".length, key.length - 1)]: searchParams?.get(key),
- }),
- {}
- ),
- hashedLink,
- };
-
- if (isInstantMeeting) {
- createInstantBookingMutation.mutate(mapBookingToMutationInput(bookingInput));
- } else if (eventQuery.data?.recurringEvent?.freq && recurringEventCount && !rescheduleUid) {
- createRecurringBookingMutation.mutate(
- mapRecurringBookingToMutationInput(bookingInput, recurringEventCount)
- );
- } else {
- createBookingMutation.mutate(mapBookingToMutationInput(bookingInput));
- }
- // Clears form values stored in store, so old values won't stick around.
- setFormValues({});
- bookingForm.clearErrors();
- };
-
if (!eventType) {
console.warn("No event type found for event", routerQuery);
return <Alert severity="warning" message={t("error_booking_event")} />;
}
- const renderConfirmNotVerifyEmailButtonCond =
- !eventType?.requiresBookerEmailVerification || (email && verifiedEmail && verifiedEmail === email);
-
return (
<div className="flex h-full flex-col">
<Form
@@ -406,7 +91,7 @@ export const BookEventFormChild = ({
setFormValues(values);
}}
form={bookingForm}
- handleSubmit={renderConfirmNotVerifyEmailButtonCond ? bookEvent : verifyEmail}
+ handleSubmit={onSubmit}
noValidate>
<BookingFields
isDynamicGroupBooking={!!(username && username.indexOf("+") > -1)}
@@ -415,24 +100,14 @@ export const BookEventFormChild = ({
rescheduleUid={rescheduleUid || undefined}
bookingData={bookingData}
/>
- {(createBookingMutation.isError ||
- createRecurringBookingMutation.isError ||
- createInstantBookingMutation.isError ||
- bookingForm.formState.errors["globalError"]) && (
+ {(errors.hasFormErrors || errors.hasDataErrors) && (
<div data-testid="booking-fail">
<Alert
ref={errorRef}
className="my-2"
severity="info"
title={rescheduleUid ? t("reschedule_fail") : t("booking_fail")}
- message={getError(
- bookingForm.formState.errors["globalError"],
- createBookingMutation,
- createRecurringBookingMutation,
- createInstantBookingMutation,
- t,
- responseVercelIdHeader
- )}
+ message={getError(errors.formErrors, errors.dataErrors, t, responseVercelIdHeader)}
/>
</div>
)}
@@ -451,7 +126,7 @@ export const BookEventFormChild = ({
</div>
<div className="modalsticky mt-auto flex justify-end space-x-2 rtl:space-x-reverse">
{isInstantMeeting ? (
- <Button type="submit" color="primary" loading={createInstantBookingMutation.isLoading}>
+ <Button type="submit" color="primary" loading={loadingStates.creatingInstantBooking}>
{isPaidEvent ? t("pay_and_book") : t("confirm")}
</Button>
) : (
@@ -464,14 +139,7 @@ export const BookEventFormChild = ({
<Button
type="submit"
color="primary"
- loading={
- bookingForm.formState.isSubmitting ||
- createBookingMutation.isLoading ||
- createRecurringBookingMutation.isLoading ||
- // A redirect is triggered on mutation success, so keep the button disabled as this is happening.
- createBookingMutation.isSuccess ||
- createRecurringBookingMutation.isSuccess
- }
+ loading={loadingStates.creatingBooking || loadingStates.creatingRecurringBooking}
data-testid={
rescheduleUid && bookingData ? "confirm-reschedule-button" : "confirm-book-button"
}>
@@ -487,114 +155,24 @@ export const BookEventFormChild = ({
)}
</div>
</Form>
- <VerifyCodeDialog
- isOpenDialog={isEmailVerificationModalVisible}
- setIsOpenDialog={setEmailVerificationModalVisible}
- email={email}
- onSuccess={() => {
- setVerifiedEmail(email);
- setEmailVerificationModalVisible(false);
- bookEvent(bookingForm.getValues());
- }}
- isUserSessionRequiredToVerify={false}
- />
- <RedirectToInstantMeetingModal expiryTime={expiryTime} />
+ {children}
</div>
);
};
-const RedirectToInstantMeetingModal = ({ expiryTime }: { expiryTime?: Date }) => {
- const { t } = useLocale();
- const router = useRouter();
- const pathname = usePathname();
- const bookingId = parseInt(getQueryParam("bookingId") || "0");
- const hasInstantMeetingTokenExpired = expiryTime && new Date(expiryTime) < new Date();
-
- const instantBooking = trpc.viewer.bookings.getInstantBookingLocation.useQuery(
- {
- bookingId: bookingId,
- },
- {
- enabled: !!bookingId && !hasInstantMeetingTokenExpired,
- refetchInterval: 2000,
- onSuccess: (data) => {
- try {
- showToast(t("something_went_wrong_on_our_end"), "error");
-
- const locationVideoCallUrl: string | undefined = bookingMetadataSchema.parse(
- data.booking?.metadata || {}
- )?.videoCallUrl;
-
- if (locationVideoCallUrl) {
- router.push(locationVideoCallUrl);
- } else {
- showToast(t("something_went_wrong_on_our_end"), "error");
- }
- } catch (err) {
- showToast(t("something_went_wrong_on_our_end"), "error");
- }
- },
- }
- );
-
- return (
- <Dialog open={!!bookingId}>
- <DialogContent enableOverflow className="py-8">
- <div>
- {hasInstantMeetingTokenExpired ? (
- <div>
- <p className="font-medium">{t("please_book_a_time_sometime_later")}</p>
- <Button
- className="mt-4"
- onClick={() => {
- // Prevent null on app directory
- if (pathname) window.location.href = pathname;
- }}
- color="primary">
- {t("go_back")}
- </Button>
- </div>
- ) : (
- <div className="text-center">
- <p className="font-medium">{t("connecting_you_to_someone")}</p>
- {/* TODO: Add countdown from 60 seconds
- We are connecting you!
- Please schedule a future call if we're not available in XX seconds.
- */}
-
- {/* Once countdown ends:
- Oops, we couldn't connect you this time.
- Please schedule a future call instead. We value your time.
- */}
-
- <p className="font-medium">{t("please_do_not_close_this_tab")}</p>
- <div className="h-[414px]">
- <iframe className="mx-auto h-full w-[276px] rounded-lg" src="https://cal.games/" />
- </div>
- </div>
- )}
- </div>
- </DialogContent>
- </Dialog>
- );
-};
-
const getError = (
globalError: FieldError | undefined,
// It feels like an implementation detail to reimplement the types of useMutation here.
// Since they don't matter for this function, I'd rather disable them then giving you
// the cognitive overload of thinking to update them here when anything changes.
// eslint-disable-next-line @typescript-eslint/no-explicit-any
- bookingMutation: UseMutationResult<any, any, any, any>,
- // eslint-disable-next-line @typescript-eslint/no-explicit-any
- recurringBookingMutation: UseMutationResult<any, any, any, any>,
- createInstantBookingMutation: UseMutationResult<any, any, any, any>,
+ dataError: any,
t: TFunction,
responseVercelIdHeader: string | null
) => {
if (globalError) return globalError.message;
- const error = bookingMutation.error || recurringBookingMutation.error || createInstantBookingMutation.error;
+ const error = dataError;
return error.message ? (
<>
@@ -604,117 +182,3 @@ const getError = (
<>{t("can_you_try_again")}</>
);
};
-
-function useInitialFormValues({
- eventType,
- rescheduleUid,
- isRescheduling,
-}: {
- eventType: ReturnType<typeof useEvent>["data"];
- rescheduleUid: string | null;
- isRescheduling: boolean;
-}) {
- const [initialValues, setDefaultValues] = useState<DefaultValues>({});
- const bookingData = useBookerStore((state) => state.bookingData);
- const formValues = useBookerStore((state) => state.formValues);
- const searchParams = useSearchParams();
- const routerQuery = useRouterQuery();
- const session = useSession();
- useEffect(() => {
- (async function () {
- if (Object.keys(formValues).length) {
- setDefaultValues(formValues);
- return;
- }
-
- if (!eventType?.bookingFields) {
- return {};
- }
- const querySchema = getBookingResponsesPartialSchema({
- eventType: {
- bookingFields: eventType.bookingFields,
- },
- view: rescheduleUid ? "reschedule" : "booking",
- });
-
- // Routing Forms don't support Split full name(because no Form Builder in there), so user needs to create two fields in there themselves. If they name these fields, `firstName` and `lastName`, we can prefill the Booking Form with them
- // Once we support formBuilder in Routing Forms, we should be able to forward JSON form of name field value to Booking Form and prefill it there without having these two query params separately.
- const firstNameQueryParam = searchParams?.get("firstName");
- const lastNameQueryParam = searchParams?.get("lastName");
-
- const parsedQuery = await querySchema.parseAsync({
- ...routerQuery,
- name:
- searchParams?.get("name") ||
- (firstNameQueryParam ? `${firstNameQueryParam} ${lastNameQueryParam}` : null),
- // `guest` because we need to support legacy URL with `guest` query param support
- // `guests` because the `name` of the corresponding bookingField is `guests`
- guests: searchParams?.getAll("guests") || searchParams?.getAll("guest"),
- });
-
- const defaultUserValues = {
- email:
- rescheduleUid && bookingData && bookingData.attendees.length > 0
- ? bookingData?.attendees[0].email
- : !!parsedQuery["email"]
- ? parsedQuery["email"]
- : session.data?.user?.email ?? "",
- name:
- rescheduleUid && bookingData && bookingData.attendees.length > 0
- ? bookingData?.attendees[0].name
- : !!parsedQuery["name"]
- ? parsedQuery["name"]
- : session.data?.user?.name ?? session.data?.user?.username ?? "",
- };
-
- if (!isRescheduling) {
- const defaults = {
- responses: {} as Partial<z.infer<ReturnType<typeof getBookingResponsesSchema>>>,
- };
-
- const responses = eventType.bookingFields.reduce((responses, field) => {
- return {
- ...responses,
- [field.name]: parsedQuery[field.name] || undefined,
- };
- }, {});
-
- defaults.responses = {
- ...responses,
- name: defaultUserValues.name,
- email: defaultUserValues.email,
- };
-
- setDefaultValues(defaults);
- }
-
- if (!rescheduleUid && !bookingData) {
- return {};
- }
-
- // We should allow current session user as default values for booking form
-
- const defaults = {
- responses: {} as Partial<z.infer<ReturnType<typeof getBookingResponsesSchema>>>,
- };
-
- const responses = eventType.bookingFields.reduce((responses, field) => {
- return {
- ...responses,
- [field.name]: bookingData?.responses[field.name],
- };
- }, {});
- defaults.responses = {
- ...responses,
- name: defaultUserValues.name,
- email: defaultUserValues.email,
- };
- setDefaultValues(defaults);
- })();
- }, [eventType?.bookingFields, formValues, isRescheduling, bookingData, rescheduleUid]);
-
- // When initialValues is available(after doing async schema parsing) or session is available(so that we can prefill logged-in user email and name), we need to reset the form with the initialValues
- const key = `${Object.keys(initialValues).length}_${session ? 1 : 0}`;
-
- return { initialValues, key };
-}
diff --git a/packages/features/bookings/Booker/components/BookEventForm/BookFormAsModal.tsx b/packages/features/bookings/Booker/components/BookEventForm/BookFormAsModal.tsx
index a43f58eb3b7..97849df1707 100644
--- a/packages/features/bookings/Booker/components/BookEventForm/BookFormAsModal.tsx
+++ b/packages/features/bookings/Booker/components/BookEventForm/BookFormAsModal.tsx
@@ -1,4 +1,5 @@
import { Calendar, Clock } from "lucide-react";
+import type { ReactNode } from "react";
import dayjs from "@calcom/dayjs";
import { useLocale } from "@calcom/lib/hooks/useLocale";
@@ -7,9 +8,8 @@ import { Badge, Dialog, DialogContent } from "@calcom/ui";
import { useTimePreferences } from "../../../lib";
import { useBookerStore } from "../../store";
import { useEvent } from "../../utils/event";
-import { BookEventForm } from "./BookEventForm";
-const BookEventFormWrapper = ({ onCancel }: { onCancel: () => void }) => {
+const BookEventFormWrapper = ({ children }: { onCancel: () => void; children: ReactNode }) => {
const { t } = useLocale();
const selectedTimeslot = useBookerStore((state) => state.selectedTimeslot);
const selectedDuration = useBookerStore((state) => state.selectedDuration);
@@ -31,19 +31,27 @@ const BookEventFormWrapper = ({ onCancel }: { onCancel: () => void }) => {
</Badge>
)}
</div>
- <BookEventForm onCancel={onCancel} />
+ {children}
</>
);
};
-export const BookFormAsModal = ({ visible, onCancel }: { visible: boolean; onCancel: () => void }) => {
+export const BookFormAsModal = ({
+ visible,
+ onCancel,
+ children,
+}: {
+ visible: boolean;
+ onCancel: () => void;
+ children: ReactNode;
+}) => {
return (
<Dialog open={visible} onOpenChange={onCancel}>
<DialogContent
type={undefined}
enableOverflow
className="[&_.modalsticky]:border-t-subtle [&_.modalsticky]:bg-default max-h-[80vh] pb-0 [&_.modalsticky]:sticky [&_.modalsticky]:bottom-0 [&_.modalsticky]:left-0 [&_.modalsticky]:right-0 [&_.modalsticky]:-mx-8 [&_.modalsticky]:border-t [&_.modalsticky]:px-8 [&_.modalsticky]:py-4">
- <BookEventFormWrapper onCancel={onCancel} />
+ <BookEventFormWrapper onCancel={onCancel}>{children}</BookEventFormWrapper>
</DialogContent>
</Dialog>
);
diff --git a/packages/features/bookings/Booker/components/DatePicker.tsx b/packages/features/bookings/Booker/components/DatePicker.tsx
index 82eea45a4a6..dcd97aeeef9 100644
--- a/packages/features/bookings/Booker/components/DatePicker.tsx
+++ b/packages/features/bookings/Booker/components/DatePicker.tsx
@@ -8,17 +8,21 @@ import { weekdayToWeekIndex } from "@calcom/lib/date-fns";
import { useLocale } from "@calcom/lib/hooks/useLocale";
import { useBookerStore } from "../store";
-import { useEvent, useScheduleForEvent } from "../utils/event";
+import type { useEventReturnType, useScheduleForEventReturnType } from "../utils/event";
-export const DatePicker = () => {
+export const DatePicker = ({
+ event,
+ schedule,
+}: {
+ event: useEventReturnType;
+ schedule: useScheduleForEventReturnType;
+}) => {
const { i18n } = useLocale();
const [month, selectedDate] = useBookerStore((state) => [state.month, state.selectedDate], shallow);
const [setSelectedDate, setMonth] = useBookerStore(
(state) => [state.setSelectedDate, state.setMonth],
shallow
);
- const event = useEvent();
- const schedule = useScheduleForEvent();
const nonEmptyScheduleDays = useNonEmptyScheduleDays(schedule?.data?.slots);
return (
diff --git a/packages/features/bookings/Booker/components/EventMeta.tsx b/packages/features/bookings/Booker/components/EventMeta.tsx
index 3cb6dab61ba..1b13fb320c3 100644
--- a/packages/features/bookings/Booker/components/EventMeta.tsx
+++ b/packages/features/bookings/Booker/components/EventMeta.tsx
@@ -13,7 +13,7 @@ import { Calendar, Globe, User } from "@calcom/ui/components/icon";
import { fadeInUp } from "../config";
import { useBookerStore } from "../store";
import { FromToTime } from "../utils/dates";
-import { useEvent } from "../utils/event";
+import type { useEventReturnType } from "../utils/event";
const TimezoneSelect = dynamic(
() => import("@calcom/ui/components/form/timezone-select/TimezoneSelect").then((mod) => mod.TimezoneSelect),
@@ -22,10 +22,15 @@ const TimezoneSelect = dynamic(
}
);
-export const EventMeta = () => {
+export const EventMeta = ({
+ event,
+ isLoading,
+}: {
+ event: useEventReturnType["data"];
+ isLoading: useEventReturnType["isLoading"];
+}) => {
const { setTimezone, timeFormat, timezone } = useTimePreferences();
const selectedDuration = useBookerStore((state) => state.selectedDuration);
- const setSelectedDuration = useBookerStore((state) => state.setSelectedDuration);
const selectedTimeslot = useBookerStore((state) => state.selectedTimeslot);
const bookerState = useBookerStore((state) => state.state);
const bookingData = useBookerStore((state) => state.bookingData);
@@ -35,7 +40,7 @@ export const EventMeta = () => {
shallow
);
const { i18n, t } = useLocale();
- const { data: event, isLoading } = useEvent();
+
const embedUiConfig = useEmbedUiConfig();
const isEmbed = useIsEmbed();
const hideEventTypeDetails = isEmbed ? embedUiConfig.hideEventTypeDetails : false;
diff --git a/packages/features/bookings/Booker/components/Header.tsx b/packages/features/bookings/Booker/components/Header.tsx
index 1caf102f2a5..eb7dc45f02d 100644
--- a/packages/features/bookings/Booker/components/Header.tsx
+++ b/packages/features/bookings/Booker/components/Header.tsx
@@ -1,5 +1,4 @@
import { ChevronLeft, ChevronRight } from "lucide-react";
-import { useSession } from "next-auth/react";
import { useCallback, useMemo } from "react";
import { shallow } from "zustand/shallow";
@@ -14,25 +13,25 @@ import { Calendar, Columns, Grid } from "@calcom/ui/components/icon";
import { TimeFormatToggle } from "../../components/TimeFormatToggle";
import { useBookerStore } from "../store";
import type { BookerLayout } from "../types";
-import { OverlayCalendarContainer } from "./OverlayCalendar/OverlayCalendarContainer";
export function Header({
extraDays,
isMobile,
enabledLayouts,
nextSlots,
- username,
eventSlug,
+ isMyLink,
+ renderOverlay,
}: {
extraDays: number;
isMobile: boolean;
enabledLayouts: BookerLayouts[];
nextSlots: number;
- username: string;
eventSlug: string;
+ isMyLink: boolean;
+ renderOverlay?: () => JSX.Element | null;
}) {
const { t, i18n } = useLocale();
- const session = useSession();
const isEmbed = useIsEmbed();
const [layout, setLayout] = useBookerStore((state) => [state.layout, state.setLayout], shallow);
const selectedDateString = useBookerStore((state) => state.selectedDate);
@@ -63,8 +62,6 @@ export function Header({
<LayoutToggle onLayoutToggle={onLayoutToggle} layout={layout} enabledLayouts={enabledLayouts} />
);
};
- const isMyLink = username === session?.data?.user.username; // TODO: check for if the user is the owner of the link
-
// In month view we only show the layout toggle.
if (isMonthView) {
return (
@@ -79,7 +76,7 @@ export function Header({
</Button>
</Tooltip>
) : (
- <OverlayCalendarContainer />
+ renderOverlay?.()
)}
<LayoutToggleWithData />
</div>
@@ -140,7 +137,7 @@ export function Header({
</ButtonGroup>
</div>
<div className="ml-auto flex gap-2">
- <OverlayCalendarContainer />
+ {renderOverlay?.()}
<TimeFormatToggle />
<div className="fixed top-4 ltr:right-4 rtl:left-4">
<LayoutToggleWithData />
diff --git a/packages/features/bookings/Booker/components/InstantBooking.tsx b/packages/features/bookings/Booker/components/InstantBooking.tsx
new file mode 100644
index 00000000000..ff93fb4c4dc
--- /dev/null
+++ b/packages/features/bookings/Booker/components/InstantBooking.tsx
@@ -0,0 +1,36 @@
+import { useLocale } from "@calcom/lib/hooks/useLocale";
+import { Button } from "@calcom/ui";
+
+interface IInstantBookingProps {
+ onConnectNow: () => void;
+}
+{
+ /* TODO: max. show 4 people here */
+ /* use AvatarGroup */
+}
+
+export const InstantBooking = ({ onConnectNow }: IInstantBookingProps) => {
+ const { t } = useLocale();
+
+ return (
+ <div className=" bg-default border-subtle mx-2 block items-center gap-3 rounded-xl border p-[6px] text-sm shadow-sm delay-1000 sm:flex">
+ <div className="flex items-center gap-3 ps-1">
+ <div className="relative">
+ <div className="border-muted absolute -bottom-0.5 -right-1 h-2 w-2 rounded-full border bg-green-500" />
+ </div>
+ <div>{t("dont_want_to_wait")}</div>
+ </div>
+ <div className="mt-2 sm:mt-0">
+ <Button
+ color="primary"
+ onClick={() => {
+ onConnectNow();
+ }}
+ size="sm"
+ className="w-full justify-center rounded-lg sm:w-auto">
+ {t("connect_now")}
+ </Button>
+ </div>
+ </div>
+ );
+};
diff --git a/packages/features/bookings/Booker/components/LargeCalendar.tsx b/packages/features/bookings/Booker/components/LargeCalendar.tsx
index 8efab29b066..e73ff6303bf 100644
--- a/packages/features/bookings/Booker/components/LargeCalendar.tsx
+++ b/packages/features/bookings/Booker/components/LargeCalendar.tsx
@@ -7,19 +7,24 @@ import type { CalendarAvailableTimeslots } from "@calcom/features/calendars/week
import { localStorage } from "@calcom/lib/webstorage";
import { useBookerStore } from "../store";
-import { useEvent, useScheduleForEvent } from "../utils/event";
+import type { useScheduleForEventReturnType } from "../utils/event";
+import { useEvent } from "../utils/event";
import { getQueryParam } from "../utils/query-param";
import { useOverlayCalendarStore } from "./OverlayCalendar/store";
-export const LargeCalendar = ({ extraDays }: { extraDays: number }) => {
+export const LargeCalendar = ({
+ extraDays,
+ schedule,
+ isLoading,
+}: {
+ extraDays: number;
+ schedule?: useScheduleForEventReturnType["data"];
+ isLoading: boolean;
+}) => {
const selectedDate = useBookerStore((state) => state.selectedDate);
- const date = selectedDate || dayjs().format("YYYY-MM-DD");
const setSelectedTimeslot = useBookerStore((state) => state.setSelectedTimeslot);
const selectedEventDuration = useBookerStore((state) => state.selectedDuration);
const overlayEvents = useOverlayCalendarStore((state) => state.overlayBusyDates);
- const schedule = useScheduleForEvent({
- prefetchNextMonth: !!extraDays && dayjs(date).month() !== dayjs(date).add(extraDays, "day").month(),
- });
const displayOverlay =
getQueryParam("overlayCalendar") === "true" || localStorage.getItem("overlayCalendarSwitchDefault");
@@ -28,11 +33,11 @@ export const LargeCalendar = ({ extraDays }: { extraDays: number }) => {
const availableSlots = useMemo(() => {
const availableTimeslots: CalendarAvailableTimeslots = {};
- if (!schedule.data) return availableTimeslots;
- if (!schedule.data.slots) return availableTimeslots;
+ if (!schedule) return availableTimeslots;
+ if (!schedule.slots) return availableTimeslots;
- for (const day in schedule.data.slots) {
- availableTimeslots[day] = schedule.data.slots[day].map((slot) => ({
+ for (const day in schedule.slots) {
+ availableTimeslots[day] = schedule.slots[day].map((slot) => ({
start: dayjs(slot.time).toDate(),
end: dayjs(slot.time).add(eventDuration, "minutes").toDate(),
}));
@@ -69,7 +74,7 @@ export const LargeCalendar = ({ extraDays }: { extraDays: number }) => {
return (
<div className="h-full [--calendar-dates-sticky-offset:66px]">
<Calendar
- isLoading={schedule.isLoading}
+ isLoading={isLoading}
availableTimeslots={availableSlots}
startHour={0}
endHour={23}
diff --git a/packages/features/bookings/Booker/components/OverlayCalendar/OverlayCalendar.tsx b/packages/features/bookings/Booker/components/OverlayCalendar/OverlayCalendar.tsx
new file mode 100644
index 00000000000..f67323315fb
--- /dev/null
+++ b/packages/features/bookings/Booker/components/OverlayCalendar/OverlayCalendar.tsx
@@ -0,0 +1,49 @@
+import type { UseCalendarsReturnType } from "../hooks/useCalendars";
+import { useOverlayCalendar } from "../hooks/useOverlayCalendar";
+import { OverlayCalendarContinueModal } from "./OverlayCalendarContinueModal";
+import { OverlayCalendarSettingsModal } from "./OverlayCalendarSettingsModal";
+import { OverlayCalendarSwitch } from "./OverlayCalendarSwitch";
+
+type OverlayCalendarProps = Pick<
+ UseCalendarsReturnType,
+ | "connectedCalendars"
+ | "overlayBusyDates"
+ | "onToggleCalendar"
+ | "loadingConnectedCalendar"
+ | "isOverlayCalendarEnabled"
+> & { handleClickNoCalendar: () => void };
+
+export const OverlayCalendar = ({
+ connectedCalendars,
+ overlayBusyDates,
+ onToggleCalendar,
+ isOverlayCalendarEnabled,
+ loadingConnectedCalendar,
+ handleClickNoCalendar,
+}: OverlayCalendarProps) => {
+ const {
+ handleCloseContinueModal,
+ handleCloseSettingsModal,
+ isOpenOverlayContinueModal,
+ isOpenOverlaySettingsModal,
+ handleToggleConnectedCalendar,
+ checkIsCalendarToggled,
+ } = useOverlayCalendar({ connectedCalendars, overlayBusyDates, onToggleCalendar });
+ return (
+ <>
+ <OverlayCalendarSwitch enabled={isOverlayCalendarEnabled} />
+ <OverlayCalendarContinueModal open={isOpenOverlayContinueModal} onClose={handleCloseContinueModal} />
+ <OverlayCalendarSettingsModal
+ connectedCalendars={connectedCalendars}
+ open={isOpenOverlaySettingsModal}
+ onClose={handleCloseSettingsModal}
+ isLoading={loadingConnectedCalendar}
+ onToggleConnectedCalendar={handleToggleConnectedCalendar}
+ onClickNoCalendar={() => {
+ handleClickNoCalendar();
+ }}
+ checkIsCalendarToggled={checkIsCalendarToggled}
+ />
+ </>
+ );
+};
diff --git a/packages/features/bookings/Booker/components/OverlayCalendar/OverlayCalendarSettingsModal.tsx b/packages/features/bookings/Booker/components/OverlayCalendar/OverlayCalendarSettingsModal.tsx
index f5731fd17d4..216cc573b1c 100644
--- a/packages/features/bookings/Booker/components/OverlayCalendar/OverlayCalendarSettingsModal.tsx
+++ b/packages/features/bookings/Booker/components/OverlayCalendar/OverlayCalendarSettingsModal.tsx
@@ -1,10 +1,8 @@
import Link from "next/link";
-import { useRouter, useSearchParams } from "next/navigation";
-import { Fragment, useEffect, useState } from "react";
+import { Fragment } from "react";
import { classNames } from "@calcom/lib";
import { useLocale } from "@calcom/lib/hooks/useLocale";
-import { trpc } from "@calcom/trpc/react";
import {
Alert,
Dialog,
@@ -20,12 +18,16 @@ import {
} from "@calcom/ui";
import { Calendar } from "@calcom/ui/components/icon";
-import { useLocalSet } from "../hooks/useLocalSet";
-import { useOverlayCalendarStore } from "./store";
+import type { UseCalendarsReturnType } from "../hooks/useCalendars";
-interface IOverlayCalendarContinueModalProps {
+interface IOverlayCalendarSettingsModalProps {
open?: boolean;
onClose?: (state: boolean) => void;
+ onClickNoCalendar?: () => void;
+ isLoading: boolean;
+ connectedCalendars: UseCalendarsReturnType["connectedCalendars"];
+ onToggleConnectedCalendar: (externalCalendarId: string, credentialId: number) => void;
+ checkIsCalendarToggled: (externalCalendarId: string, credentialId: number) => boolean;
}
const SkeletonLoader = () => {
@@ -41,40 +43,20 @@ const SkeletonLoader = () => {
);
};
-export function OverlayCalendarSettingsModal(props: IOverlayCalendarContinueModalProps) {
- const utils = trpc.useContext();
- const [initalised, setInitalised] = useState(false);
- const searchParams = useSearchParams();
- const setOverlayBusyDates = useOverlayCalendarStore((state) => state.setOverlayBusyDates);
- const { data, isLoading } = trpc.viewer.connectedCalendars.useQuery(undefined, {
- enabled: !!props.open || Boolean(searchParams?.get("overlayCalendar")),
- });
- const { toggleValue, hasItem, set } = useLocalSet<{
- credentialId: number;
- externalId: string;
- }>("toggledConnectedCalendars", []);
-
- const router = useRouter();
+export function OverlayCalendarSettingsModal({
+ connectedCalendars,
+ isLoading,
+ open,
+ onClose,
+ onClickNoCalendar,
+ onToggleConnectedCalendar,
+ checkIsCalendarToggled,
+}: IOverlayCalendarSettingsModalProps) {
const { t } = useLocale();
- useEffect(() => {
- if (data?.connectedCalendars && set.size === 0 && !initalised) {
- data?.connectedCalendars.forEach((item) => {
- item.calendars?.forEach((cal) => {
- const id = { credentialId: item.credentialId, externalId: cal.externalId };
- if (cal.primary) {
- toggleValue(id);
- }
- });
- });
- setInitalised(true);
- }
- // eslint-disable-next-line react-hooks/exhaustive-deps
- }, [data, hasItem, set, initalised]);
-
return (
<>
- <Dialog open={props.open} onOpenChange={props.onClose}>
+ <Dialog open={open} onOpenChange={onClose}>
<DialogContent
enableOverflow
type="creation"
@@ -86,17 +68,17 @@ export function OverlayCalendarSettingsModal(props: IOverlayCalendarContinueModa
<SkeletonLoader />
) : (
<>
- {data?.connectedCalendars.length === 0 ? (
+ {connectedCalendars.length === 0 ? (
<EmptyScreen
Icon={Calendar}
headline={t("no_calendar_installed")}
description={t("no_calendar_installed_description")}
buttonText={t("add_a_calendar")}
- buttonOnClick={() => router.push("/apps/categories/calendar")}
+ buttonOnClick={onClickNoCalendar}
/>
) : (
<>
- {data?.connectedCalendars.map((item) => (
+ {connectedCalendars.map((item) => (
<Fragment key={item.credentialId}>
{item.error && !item.calendars && (
<Alert severity="error" title={item.error.message} />
@@ -134,17 +116,9 @@ export function OverlayCalendarSettingsModal(props: IOverlayCalendarContinueModa
<li className="flex gap-3" key={id}>
<Switch
id={id}
- checked={hasItem({
- credentialId: item.credentialId,
- externalId: cal.externalId,
- })}
+ checked={checkIsCalendarToggled(cal.externalId, item.credentialId)}
onCheckedChange={() => {
- toggleValue({
- credentialId: item.credentialId,
- externalId: cal.externalId,
- });
- setOverlayBusyDates([]);
- utils.viewer.availability.calendarOverlay.reset();
+ onToggleConnectedCalendar(cal.externalId, item.credentialId);
}}
/>
<label htmlFor={id}>{cal.name}</label>
diff --git a/packages/features/bookings/Booker/components/OverlayCalendar/OverlayCalendarContainer.tsx b/packages/features/bookings/Booker/components/OverlayCalendar/OverlayCalendarSwitch.tsx
similarity index 50%
rename from packages/features/bookings/Booker/components/OverlayCalendar/OverlayCalendarContainer.tsx
rename to packages/features/bookings/Booker/components/OverlayCalendar/OverlayCalendarSwitch.tsx
index 23df7257e26..b9d5ef81b95 100644
--- a/packages/features/bookings/Booker/components/OverlayCalendar/OverlayCalendarContainer.tsx
+++ b/packages/features/bookings/Booker/components/OverlayCalendar/OverlayCalendarSwitch.tsx
@@ -1,29 +1,21 @@
import { useSession } from "next-auth/react";
import { useSearchParams, useRouter, usePathname } from "next/navigation";
import { useCallback, useEffect } from "react";
-import { shallow } from "zustand/shallow";
-import dayjs from "@calcom/dayjs";
-import { useIsEmbed } from "@calcom/embed-core/embed-iframe";
-import { useTimePreferences } from "@calcom/features/bookings/lib";
import { classNames } from "@calcom/lib";
import { useLocale } from "@calcom/lib/hooks/useLocale";
import { localStorage } from "@calcom/lib/webstorage";
-import { trpc } from "@calcom/trpc/react";
import { Button, Switch } from "@calcom/ui";
import { Settings } from "@calcom/ui/components/icon";
import { useBookerStore } from "../../store";
-import { OverlayCalendarContinueModal } from "../OverlayCalendar/OverlayCalendarContinueModal";
-import { OverlayCalendarSettingsModal } from "../OverlayCalendar/OverlayCalendarSettingsModal";
-import { useLocalSet } from "../hooks/useLocalSet";
import { useOverlayCalendarStore } from "./store";
interface OverlayCalendarSwitchProps {
enabled?: boolean;
}
-function OverlayCalendarSwitch({ enabled }: OverlayCalendarSwitchProps) {
+export function OverlayCalendarSwitch({ enabled }: OverlayCalendarSwitchProps) {
const { t } = useLocale();
const setContinueWithProvider = useOverlayCalendarStore((state) => state.setContinueWithProviderModal);
const setCalendarSettingsOverlay = useOverlayCalendarStore(
@@ -106,90 +98,3 @@ function OverlayCalendarSwitch({ enabled }: OverlayCalendarSwitchProps) {
</div>
);
}
-
-export function OverlayCalendarContainer() {
- const isEmbed = useIsEmbed();
- const searchParams = useSearchParams();
- const [continueWithProvider, setContinueWithProvider] = useOverlayCalendarStore(
- (state) => [state.continueWithProviderModal, state.setContinueWithProviderModal],
- shallow
- );
- const [calendarSettingsOverlay, setCalendarSettingsOverlay] = useOverlayCalendarStore(
- (state) => [state.calendarSettingsOverlayModal, state.setCalendarSettingsOverlayModal],
- shallow
- );
-
- const { data: session, status: sessionStatus } = useSession();
- const setOverlayBusyDates = useOverlayCalendarStore((state) => state.setOverlayBusyDates);
- const switchEnabled =
- searchParams?.get("overlayCalendar") === "true" ||
- localStorage.getItem("overlayCalendarSwitchDefault") === "true";
-
- const selectedDate = useBookerStore((state) => state.selectedDate);
- const { timezone } = useTimePreferences();
-
- // Move this to a hook
- const { set, clearSet } = useLocalSet<{
- credentialId: number;
- externalId: string;
- }>("toggledConnectedCalendars", []);
-
- const { data: overlayBusyDates } = trpc.viewer.availability.calendarOverlay.useQuery(
- {
- loggedInUsersTz: timezone || "Europe/London",
- dateFrom: selectedDate,
- dateTo: selectedDate,
- calendarsToLoad: Array.from(set).map((item) => ({
- credentialId: item.credentialId,
- externalId: item.externalId,
- })),
- },
- {
- enabled: !!session && set.size > 0 && switchEnabled,
- onError: () => {
- clearSet();
- },
- }
- );
-
- useEffect(() => {
- if (overlayBusyDates) {
- const nowDate = dayjs();
- const usersTimezoneDate = nowDate.tz(timezone);
-
- const offset = (usersTimezoneDate.utcOffset() - nowDate.utcOffset()) / 60;
-
- const offsettedArray = overlayBusyDates.map((item) => {
- return {
- ...item,
- start: dayjs(item.start).add(offset, "hours").toDate(),
- end: dayjs(item.end).add(offset, "hours").toDate(),
- };
- });
- setOverlayBusyDates(offsettedArray);
- }
- // eslint-disable-next-line react-hooks/exhaustive-deps
- }, [overlayBusyDates]);
-
- if (isEmbed) {
- return null;
- }
-
- return (
- <>
- <OverlayCalendarSwitch enabled={switchEnabled} />
- <OverlayCalendarContinueModal
- open={continueWithProvider}
- onClose={(val) => {
- setContinueWithProvider(val);
- }}
- />
- <OverlayCalendarSettingsModal
- open={calendarSettingsOverlay}
- onClose={(val) => {
- setCalendarSettingsOverlay(val);
- }}
- />
- </>
- );
-}
diff --git a/packages/features/bookings/Booker/components/RedirectToInstantMeetingModal.tsx b/packages/features/bookings/Booker/components/RedirectToInstantMeetingModal.tsx
new file mode 100644
index 00000000000..51db3c650d9
--- /dev/null
+++ b/packages/features/bookings/Booker/components/RedirectToInstantMeetingModal.tsx
@@ -0,0 +1,55 @@
+import { useLocale } from "@calcom/lib/hooks/useLocale";
+import { Dialog, DialogContent } from "@calcom/ui";
+import { Button } from "@calcom/ui";
+
+export const RedirectToInstantMeetingModal = ({
+ hasInstantMeetingTokenExpired,
+ bookingId,
+ onGoBack,
+}: {
+ hasInstantMeetingTokenExpired: boolean;
+ bookingId: number;
+ onGoBack: () => void;
+}) => {
+ const { t } = useLocale();
+
+ return (
+ <Dialog open={!!bookingId}>
+ <DialogContent enableOverflow className="py-8">
+ <div>
+ {hasInstantMeetingTokenExpired ? (
+ <div>
+ <p className="font-medium">{t("please_book_a_time_sometime_later")}</p>
+ <Button
+ className="mt-4"
+ onClick={() => {
+ onGoBack();
+ }}
+ color="primary">
+ {t("go_back")}
+ </Button>
+ </div>
+ ) : (
+ <div className="text-center">
+ <p className="font-medium">{t("connecting_you_to_someone")}</p>
+ {/* TODO: Add countdown from 60 seconds
+ We are connecting you!
+ Please schedule a future call if we're not available in XX seconds.
+ */}
+
+ {/* Once countdown ends:
+ Oops, we couldn't connect you this time.
+ Please schedule a future call instead. We value your time.
+ */}
+
+ <p className="font-medium">{t("please_do_not_close_this_tab")}</p>
+ <div className="h-[414px]">
+ <iframe className="mx-auto h-full w-[276px] rounded-lg" src="https://cal.games/" />
+ </div>
+ </div>
+ )}
+ </div>
+ </DialogContent>
+ </Dialog>
+ );
+};
diff --git a/packages/features/bookings/Booker/components/hooks/useBookerLayout.ts b/packages/features/bookings/Booker/components/hooks/useBookerLayout.ts
new file mode 100644
index 00000000000..1864a35c36d
--- /dev/null
+++ b/packages/features/bookings/Booker/components/hooks/useBookerLayout.ts
@@ -0,0 +1,90 @@
+import { useEffect, useRef } from "react";
+import { shallow } from "zustand/shallow";
+
+import { useEmbedType, useEmbedUiConfig, useIsEmbed } from "@calcom/embed-core/embed-iframe";
+import useMediaQuery from "@calcom/lib/hooks/useMediaQuery";
+import type { BookerLayouts } from "@calcom/prisma/zod-utils";
+import { defaultBookerLayoutSettings } from "@calcom/prisma/zod-utils";
+
+import { extraDaysConfig } from "../../config";
+import { useBookerStore } from "../../store";
+import type { BookerLayout } from "../../types";
+import type { useEventReturnType } from "../../utils/event";
+import { validateLayout } from "../../utils/layout";
+import { getQueryParam } from "../../utils/query-param";
+
+export const useBookerLayout = (event: useEventReturnType["data"]) => {
+ const [_layout, setLayout] = useBookerStore((state) => [state.layout, state.setLayout], shallow);
+ const isEmbed = useIsEmbed();
+ const isMobile = useMediaQuery("(max-width: 768px)");
+ const isTablet = useMediaQuery("(max-width: 1024px)");
+ const embedUiConfig = useEmbedUiConfig();
+ // In Embed we give preference to embed configuration for the layout.If that's not set, we use the App configuration for the event layout
+ // But if it's mobile view, there is only one layout supported which is 'mobile'
+ const layout = isEmbed ? (isMobile ? "mobile" : validateLayout(embedUiConfig.layout) || _layout) : _layout;
+ const extraDays = isTablet ? extraDaysConfig[layout].tablet : extraDaysConfig[layout].desktop;
+ const embedType = useEmbedType();
+ // Floating Button and Element Click both are modal and thus have dark background
+ const hasDarkBackground = isEmbed && embedType !== "inline";
+ const columnViewExtraDays = useRef<number>(
+ isTablet ? extraDaysConfig[layout].tablet : extraDaysConfig[layout].desktop
+ );
+ const bookerLayouts = event?.profile?.bookerLayouts || defaultBookerLayoutSettings;
+ const defaultLayout = isEmbed
+ ? validateLayout(embedUiConfig.layout) || bookerLayouts.defaultLayout
+ : bookerLayouts.defaultLayout;
+
+ useEffect(() => {
+ if (isMobile && layout !== "mobile") {
+ setLayout("mobile");
+ } else if (!isMobile && layout === "mobile") {
+ setLayout(defaultLayout);
+ }
+ }, [isMobile, setLayout, layout, defaultLayout]);
+ //setting layout from query param
+ useEffect(() => {
+ const layout = getQueryParam("layout") as BookerLayouts;
+ if (
+ !isMobile &&
+ !isEmbed &&
+ validateLayout(layout) &&
+ bookerLayouts?.enabledLayouts?.length &&
+ layout !== _layout
+ ) {
+ const validLayout = bookerLayouts.enabledLayouts.find((userLayout) => userLayout === layout);
+ validLayout && setLayout(validLayout);
+ }
+ }, [bookerLayouts, setLayout, _layout, isEmbed, isMobile]);
+
+ // In Embed, a Dialog doesn't look good, we disable it intentionally for the layouts that support showing Form without Dialog(i.e. no-dialog Form)
+ const shouldShowFormInDialogMap: Record<BookerLayout, boolean> = {
+ // mobile supports showing the Form without Dialog
+ mobile: !isEmbed,
+ // We don't show Dialog in month_view currently. Can be easily toggled though as it supports no-dialog Form
+ month_view: false,
+ // week_view doesn't support no-dialog Form
+ // When it's supported, disable it for embed
+ week_view: true,
+ // column_view doesn't support no-dialog Form
+ // When it's supported, disable it for embed
+ column_view: true,
+ };
+
+ const shouldShowFormInDialog = shouldShowFormInDialogMap[layout];
+
+ const hideEventTypeDetails = isEmbed ? embedUiConfig.hideEventTypeDetails : false;
+
+ return {
+ shouldShowFormInDialog,
+ hasDarkBackground,
+ extraDays,
+ columnViewExtraDays,
+ isMobile,
+ isEmbed,
+ isTablet,
+ layout,
+ defaultLayout,
+ hideEventTypeDetails,
+ bookerLayouts,
+ };
+};
diff --git a/packages/features/bookings/Booker/components/hooks/useBookingForm.ts b/packages/features/bookings/Booker/components/hooks/useBookingForm.ts
new file mode 100644
index 00000000000..ae67d73b200
--- /dev/null
+++ b/packages/features/bookings/Booker/components/hooks/useBookingForm.ts
@@ -0,0 +1,102 @@
+import { zodResolver } from "@hookform/resolvers/zod";
+import { useRef, useEffect } from "react";
+import { useForm } from "react-hook-form";
+import { z } from "zod";
+
+import type { EventLocationType } from "@calcom/app-store/locations";
+import { useBookerStore } from "@calcom/features/bookings/Booker/store";
+import type { useEventReturnType } from "@calcom/features/bookings/Booker/utils/event";
+import getBookingResponsesSchema from "@calcom/features/bookings/lib/getBookingResponsesSchema";
+import { useLocale } from "@calcom/lib/hooks/useLocale";
+
+import { useInitialFormValues } from "./useInitialFormValues";
+
+export interface IUseBookingForm {
+ event: useEventReturnType;
+}
+
+export type useBookingFormReturnType = ReturnType<typeof useBookingForm>;
+
+export const useBookingForm = ({ event }: IUseBookingForm) => {
+ const rescheduleUid = useBookerStore((state) => state.rescheduleUid);
+ const bookingData = useBookerStore((state) => state.bookingData);
+ const { t } = useLocale();
+ const bookerFormErrorRef = useRef<HTMLDivElement>(null);
+
+ const bookingFormSchema = z
+ .object({
+ responses: event?.data
+ ? getBookingResponsesSchema({
+ eventType: event?.data,
+ view: rescheduleUid ? "reschedule" : "booking",
+ })
+ : // Fallback until event is loaded.
+ z.object({}),
+ })
+ .passthrough();
+
+ type BookingFormValues = {
+ locationType?: EventLocationType["type"];
+ responses: z.infer<typeof bookingFormSchema>["responses"] | null;
+ // Key is not really part of form values, but only used to have a key
+ // to set generic error messages on. Needed until RHF has implemented root error keys.
+ globalError: undefined;
+ };
+ const isRescheduling = !!rescheduleUid && !!bookingData;
+
+ const { initialValues, key } = useInitialFormValues({
+ eventType: event.data,
+ rescheduleUid,
+ isRescheduling,
+ });
+
+ const bookingForm = useForm<BookingFormValues>({
+ defaultValues: initialValues,
+ resolver: zodResolver(
+ // Since this isn't set to strict we only validate the fields in the schema
+ bookingFormSchema,
+ {},
+ {
+ // bookingFormSchema is an async schema, so inform RHF to do async validation.
+ mode: "async",
+ }
+ ),
+ });
+
+ useEffect(() => {
+ // initialValues would be null initially as the async schema parsing is happening. Let's show the form in first render without any prefill values
+ // But ensure that when initialValues is available, the form is reset and rerendered with the prefill values
+ bookingForm.reset(initialValues);
+ // eslint-disable-next-line react-hooks/exhaustive-deps
+ }, [key]);
+
+ const email = bookingForm.watch("responses.email");
+ const name = bookingForm.watch("responses.name");
+
+ const beforeVerifyEmail = () => {
+ bookingForm.clearErrors();
+
+ // It shouldn't be possible that this method is fired without having event data,
+ // but since in theory (looking at the types) it is possible, we still handle that case.
+ if (!event?.data) {
+ bookingForm.setError("globalError", { message: t("error_booking_event") });
+ return;
+ }
+ };
+
+ const errors = {
+ hasFormErrors: Boolean(bookingForm.formState.errors["globalError"]),
+ formErrors: bookingForm.formState.errors["globalError"],
+ };
+
+ return {
+ bookingForm,
+ bookerFormErrorRef,
+ key,
+ formEmail: email,
+ formName: name,
+ beforeVerifyEmail,
+ formErrors: errors,
+ errors,
+ };
+};
diff --git a/packages/features/bookings/Booker/components/hooks/useBookings.ts b/packages/features/bookings/Booker/components/hooks/useBookings.ts
new file mode 100644
index 00000000000..36c3c023455
--- /dev/null
+++ b/packages/features/bookings/Booker/components/hooks/useBookings.ts
@@ -0,0 +1,270 @@
+import { useMutation } from "@tanstack/react-query";
+import { useRouter, useSearchParams } from "next/navigation";
+import { useRef, useState } from "react";
+
+import { createPaymentLink } from "@calcom/app-store/stripepayment/lib/client";
+import dayjs from "@calcom/dayjs";
+import { useBookerStore } from "@calcom/features/bookings/Booker/store";
+import type { useEventReturnType } from "@calcom/features/bookings/Booker/utils/event";
+import { updateQueryParam, getQueryParam } from "@calcom/features/bookings/Booker/utils/query-param";
+import {
+ createBooking,
+ createRecurringBooking,
+ mapBookingToMutationInput,
+ mapRecurringBookingToMutationInput,
+ createInstantBooking,
+ useTimePreferences,
+} from "@calcom/features/bookings/lib";
+import { getFullName } from "@calcom/features/form-builder/utils";
+import { useBookingSuccessRedirect } from "@calcom/lib/bookingSuccessRedirect";
+import { useLocale } from "@calcom/lib/hooks/useLocale";
+import { useRouterQuery } from "@calcom/lib/hooks/useRouterQuery";
+import { bookingMetadataSchema } from "@calcom/prisma/zod-utils";
+import { trpc } from "@calcom/trpc";
+import { showToast } from "@calcom/ui";
+
+import type { useBookingFormReturnType } from "./useBookingForm";
+
+export interface IUseBookings {
+ event: useEventReturnType;
+ hashedLink?: string | null;
+ bookingForm: useBookingFormReturnType["bookingForm"];
+}
+
+export interface IUseBookingLoadingStates {
+ creatingBooking: boolean;
+ creatingRecurringBooking: boolean;
+ creatingInstantBooking: boolean;
+}
+
+export interface IUseBookingErrors {
+ hasDataErrors: boolean;
+ dataErrors: unknown;
+}
+
+export const useBookings = ({ event, hashedLink, bookingForm }: IUseBookings) => {
+ const router = useRouter();
+ const eventSlug = useBookerStore((state) => state.eventSlug);
+ const setFormValues = useBookerStore((state) => state.setFormValues);
+ const rescheduleUid = useBookerStore((state) => state.rescheduleUid);
+ const bookingData = useBookerStore((state) => state.bookingData);
+ const timeslot = useBookerStore((state) => state.selectedTimeslot);
+ const seatedEventData = useBookerStore((state) => state.seatedEventData);
+ const { t, i18n } = useLocale();
+ const bookingSuccessRedirect = useBookingSuccessRedirect();
+ const bookerFormErrorRef = useRef<HTMLDivElement>(null);
+ const [expiryTime, setExpiryTime] = useState<Date | undefined>();
+ const recurringEventCount = useBookerStore((state) => state.recurringEventCount);
+ const isInstantMeeting = useBookerStore((state) => state.isInstantMeeting);
+ const duration = useBookerStore((state) => state.selectedDuration);
+ const { timezone } = useTimePreferences();
+ const username = useBookerStore((state) => state.username);
+ const routerQuery = useRouterQuery();
+ const searchParams = useSearchParams();
+
+ const isRescheduling = !!rescheduleUid && !!bookingData;
+
+ const bookingId = parseInt(getQueryParam("bookingId") || "0");
+ const hasInstantMeetingTokenExpired = expiryTime && new Date(expiryTime) < new Date();
+ const _instantBooking = trpc.viewer.bookings.getInstantBookingLocation.useQuery(
+ {
+ bookingId: bookingId,
+ },
+ {
+ enabled: !!bookingId && !hasInstantMeetingTokenExpired,
+ refetchInterval: 2000,
+ onSuccess: (data) => {
+ try {
+ showToast(t("something_went_wrong_on_our_end"), "error");
+
+ const locationVideoCallUrl: string | undefined = bookingMetadataSchema.parse(
+ data.booking?.metadata || {}
+ )?.videoCallUrl;
+
+ if (locationVideoCallUrl) {
+ router.push(locationVideoCallUrl);
+ } else {
+ showToast(t("something_went_wrong_on_our_end"), "error");
+ }
+ } catch (err) {
+ showToast(t("something_went_wrong_on_our_end"), "error");
+ }
+ },
+ }
+ );
+
+ const createBookingMutation = useMutation(createBooking, {
+ onSuccess: (responseData) => {
+ const { uid, paymentUid } = responseData;
+ const fullName = getFullName(bookingForm.getValues("responses.name"));
+ if (paymentUid) {
+ router.push(
+ createPaymentLink({
+ paymentUid,
+ date: timeslot,
+ name: fullName,
+ email: bookingForm.getValues("responses.email"),
+ absolute: false,
+ })
+ );
+ return;
+ }
+
+ if (!uid) {
+ console.error("No uid returned from createBookingMutation");
+ return;
+ }
+
+ const query = {
+ isSuccessBookingPage: true,
+ email: bookingForm.getValues("responses.email"),
+ eventTypeSlug: eventSlug,
+ seatReferenceUid: "seatReferenceUid" in responseData ? responseData.seatReferenceUid : null,
+ formerTime:
+ isRescheduling && bookingData?.startTime ? dayjs(bookingData.startTime).toString() : undefined,
+ };
+
+ bookingSuccessRedirect({
+ successRedirectUrl: event?.data?.successRedirectUrl || "",
+ query,
+ booking: responseData,
+ });
+ },
+ onError: (err, _, ctx) => {
+ // TODO:
+ // const vercelId = ctx?.meta?.headers?.get("x-vercel-id");
+ // if (vercelId) {
+ // setResponseVercelIdHeader(vercelId);
+ // }
+ bookerFormErrorRef && bookerFormErrorRef.current?.scrollIntoView({ behavior: "smooth" });
+ },
+ });
+
+ const createInstantBookingMutation = useMutation(createInstantBooking, {
+ onSuccess: (responseData) => {
+ updateQueryParam("bookingId", responseData.bookingId);
+ setExpiryTime(responseData.expires);
+ },
+ onError: (err, _, ctx) => {
+ console.error("Error creating instant booking", err);
+
+ bookerFormErrorRef && bookerFormErrorRef.current?.scrollIntoView({ behavior: "smooth" });
+ },
+ });
+
+ const createRecurringBookingMutation = useMutation(createRecurringBooking, {
+ onSuccess: async (responseData) => {
+ const booking = responseData[0] || {};
+ const { uid } = booking;
+
+ if (!uid) {
+ console.error("No uid returned from createRecurringBookingMutation");
+ return;
+ }
+
+ const query = {
+ isSuccessBookingPage: true,
+ allRemainingBookings: true,
+ email: bookingForm.getValues("responses.email"),
+ eventTypeSlug: eventSlug,
+ formerTime:
+ isRescheduling && bookingData?.startTime ? dayjs(bookingData.startTime).toString() : undefined,
+ };
+
+ bookingSuccessRedirect({
+ successRedirectUrl: event?.data?.successRedirectUrl || "",
+ query,
+ booking,
+ });
+ },
+ });
+
+ const handleBookEvent = () => {
+ const values = bookingForm.getValues();
+ if (timeslot) {
+ // Clears form values stored in store, so old values won't stick around.
+ setFormValues({});
+ bookingForm.clearErrors();
+
+ // It shouldn't be possible that this method is fired without having event data,
+ // but since in theory (looking at the types) it is possible, we still handle that case.
+ if (!event?.data) {
+ bookingForm.setError("globalError", { message: t("error_booking_event") });
+ return;
+ }
+
+ // Ensures that duration is an allowed value, if not it defaults to the
+ // default event duration.
+ const validDuration = event.data.isDynamic
+ ? duration || event.data.length
+ : duration && event.data.metadata?.multipleDuration?.includes(duration)
+ ? duration
+ : event.data.length;
+
+ const bookingInput = {
+ values,
+ duration: validDuration,
+ event: event.data,
+ date: timeslot,
+ timeZone: timezone,
+ language: i18n.language,
+ rescheduleUid: rescheduleUid || undefined,
+ bookingUid: (bookingData && bookingData.uid) || seatedEventData?.bookingUid || undefined,
+ username: username || "",
+ metadata: Object.keys(routerQuery)
+ .filter((key) => key.startsWith("metadata"))
+ .reduce(
+ (metadata, key) => ({
+ ...metadata,
+ [key.substring("metadata[".length, key.length - 1)]: searchParams?.get(key),
+ }),
+ {}
+ ),
+ hashedLink,
+ };
+
+ if (isInstantMeeting) {
+ createInstantBookingMutation.mutate(mapBookingToMutationInput(bookingInput));
+ } else if (event.data?.recurringEvent?.freq && recurringEventCount && !rescheduleUid) {
+ createRecurringBookingMutation.mutate(
+ mapRecurringBookingToMutationInput(bookingInput, recurringEventCount)
+ );
+ } else {
+ createBookingMutation.mutate(mapBookingToMutationInput(bookingInput));
+ }
+ // Clears form values stored in store, so old values won't stick around.
+ setFormValues({});
+ bookingForm.clearErrors();
+ }
+ };
+
+ const errors = {
+ hasDataErrors: Boolean(
+ createBookingMutation.isError ||
+ createRecurringBookingMutation.isError ||
+ createInstantBookingMutation.isError
+ ),
+ dataErrors:
+ createBookingMutation.error ||
+ createRecurringBookingMutation.error ||
+ createInstantBookingMutation.error,
+ };
+
+ // A redirect is triggered on mutation success, so keep the loading state while it is happening.
+ const loadingStates = {
+ creatingBooking: createBookingMutation.isLoading || createBookingMutation.isSuccess,
+ creatingRecurringBooking:
+ createRecurringBookingMutation.isLoading || createRecurringBookingMutation.isSuccess,
+ creatingInstantBooking: createInstantBookingMutation.isLoading,
+ };
+
+ return {
+ handleBookEvent,
+ expiryTime,
+ bookingForm,
+ bookerFormErrorRef,
+ errors,
+ loadingStates,
+ hasInstantMeetingTokenExpired: Boolean(hasInstantMeetingTokenExpired),
+ };
+};
diff --git a/packages/features/bookings/Booker/components/hooks/useCalendars.ts b/packages/features/bookings/Booker/components/hooks/useCalendars.ts
new file mode 100644
index 00000000000..babf7cde5a8
--- /dev/null
+++ b/packages/features/bookings/Booker/components/hooks/useCalendars.ts
@@ -0,0 +1,64 @@
+import { useSession } from "next-auth/react";
+import { useSearchParams } from "next/navigation";
+import { shallow } from "zustand/shallow";
+
+import { useTimePreferences } from "@calcom/features/bookings/lib";
+import { localStorage } from "@calcom/lib/webstorage";
+import { trpc } from "@calcom/trpc/react";
+
+import { useBookerStore } from "../../store";
+import { useOverlayCalendarStore } from "../OverlayCalendar/store";
+import { useLocalSet } from "./useLocalSet";
+
+export type UseCalendarsReturnType = ReturnType<typeof useCalendars>;
+export const useCalendars = () => {
+ const searchParams = useSearchParams();
+ const selectedDate = useBookerStore((state) => state.selectedDate);
+ const { timezone } = useTimePreferences();
+ const switchEnabled =
+ searchParams?.get("overlayCalendar") === "true" ||
+ localStorage?.getItem("overlayCalendarSwitchDefault") === "true";
+ const { set, clearSet } = useLocalSet<{
+ credentialId: number;
+ externalId: string;
+ }>("toggledConnectedCalendars", []);
+ const utils = trpc.useContext();
+ const { data: session } = useSession();
+
+ const [calendarSettingsOverlay] = useOverlayCalendarStore(
+ (state) => [state.calendarSettingsOverlayModal, state.setCalendarSettingsOverlayModal],
+ shallow
+ );
+
+ const { data: overlayBusyDates } = trpc.viewer.availability.calendarOverlay.useQuery(
+ {
+ loggedInUsersTz: timezone || "Europe/London",
+ dateFrom: selectedDate,
+ dateTo: selectedDate,
+ calendarsToLoad: Array.from(set).map((item) => ({
+ credentialId: item.credentialId,
+ externalId: item.externalId,
+ })),
+ },
+ {
+ enabled: !!session && set.size > 0 && switchEnabled,
+ onError: () => {
+ clearSet();
+ },
+ }
+ );
+
+ const { data, isLoading } = trpc.viewer.connectedCalendars.useQuery(undefined, {
+ enabled: !!calendarSettingsOverlay || Boolean(searchParams?.get("overlayCalendar")),
+ });
+
+ return {
+ overlayBusyDates,
+ isOverlayCalendarEnabled: switchEnabled,
+ connectedCalendars: data?.connectedCalendars || [],
+ loadingConnectedCalendar: isLoading,
+ onToggleCalendar: () => {
+ utils.viewer.availability.calendarOverlay.reset();
+ },
+ };
+};
diff --git a/packages/features/bookings/Booker/components/hooks/useInitialFormValues.ts b/packages/features/bookings/Booker/components/hooks/useInitialFormValues.ts
new file mode 100644
index 00000000000..839f2c97207
--- /dev/null
+++ b/packages/features/bookings/Booker/components/hooks/useInitialFormValues.ts
@@ -0,0 +1,138 @@
+import { useSession } from "next-auth/react";
+import { useSearchParams } from "next/navigation";
+import { useEffect, useState } from "react";
+import type { z } from "zod";
+
+import { useBookerStore } from "@calcom/features/bookings/Booker/store";
+import type { useEvent } from "@calcom/features/bookings/Booker/utils/event";
+import type getBookingResponsesSchema from "@calcom/features/bookings/lib/getBookingResponsesSchema";
+import { getBookingResponsesPartialSchema } from "@calcom/features/bookings/lib/getBookingResponsesSchema";
+import { useRouterQuery } from "@calcom/lib/hooks/useRouterQuery";
+
+export type useInitialFormValuesReturnType = ReturnType<typeof useInitialFormValues>;
+
+export function useInitialFormValues({
+ eventType,
+ rescheduleUid,
+ isRescheduling,
+}: {
+ eventType: ReturnType<typeof useEvent>["data"];
+ rescheduleUid: string | null;
+ isRescheduling: boolean;
+}) {
+ const [initialValues, setDefaultValues] = useState<Record<string, unknown>>({});
+ const bookingData = useBookerStore((state) => state.bookingData);
+ const formValues = useBookerStore((state) => state.formValues);
+ const searchParams = useSearchParams();
+ const routerQuery = useRouterQuery();
+ const session = useSession();
+ useEffect(() => {
+ (async function () {
+ if (Object.keys(formValues).length) {
+ setDefaultValues(formValues);
+ return;
+ }
+
+ if (!eventType?.bookingFields) {
+ return {};
+ }
+ const querySchema = getBookingResponsesPartialSchema({
+ eventType: {
+ bookingFields: eventType.bookingFields,
+ },
+ view: rescheduleUid ? "reschedule" : "booking",
+ });
+
+ // Routing Forms don't support Split full name(because no Form Builder in there), so user needs to create two fields in there themselves. If they name these fields, `firstName` and `lastName`, we can prefill the Booking Form with them
+ // Once we support formBuilder in Routing Forms, we should be able to forward JSON form of name field value to Booking Form and prefill it there without having these two query params separately.
+ const firstNameQueryParam = searchParams?.get("firstName");
+ const lastNameQueryParam = searchParams?.get("lastName");
+
+ const parsedQuery = await querySchema.parseAsync({
+ ...routerQuery,
+ name:
+ searchParams?.get("name") ||
+ (firstNameQueryParam ? `${firstNameQueryParam} ${lastNameQueryParam}` : null),
+ // `guest` because we need to support legacy URL with `guest` query param support
+ // `guests` because the `name` of the corresponding bookingField is `guests`
+ guests: searchParams?.getAll("guests") || searchParams?.getAll("guest"),
+ });
+
+ const defaultUserValues = {
+ email:
+ rescheduleUid && bookingData && bookingData.attendees.length > 0
+ ? bookingData?.attendees[0].email
+ : !!parsedQuery["email"]
+ ? parsedQuery["email"]
+ : session.data?.user?.email ?? "",
+ name:
+ rescheduleUid && bookingData && bookingData.attendees.length > 0
+ ? bookingData?.attendees[0].name
+ : !!parsedQuery["name"]
+ ? parsedQuery["name"]
+ : session.data?.user?.name ?? session.data?.user?.username ?? "",
+ };
+
+ if (!isRescheduling) {
+ const defaults = {
+ responses: {} as Partial<z.infer<ReturnType<typeof getBookingResponsesSchema>>>,
+ };
+
+ const responses = eventType.bookingFields.reduce((responses, field) => {
+ return {
+ ...responses,
+ [field.name]: parsedQuery[field.name] || undefined,
+ };
+ }, {});
+
+ defaults.responses = {
+ ...responses,
+ name: defaultUserValues.name,
+ email: defaultUserValues.email,
+ };
+
+ setDefaultValues(defaults);
+ }
+
+ if (!rescheduleUid && !bookingData) {
+ return {};
+ }
+
+ // We should allow current session user as default values for booking form
+
+ const defaults = {
+ responses: {} as Partial<z.infer<ReturnType<typeof getBookingResponsesSchema>>>,
+ };
+
+ const responses = eventType.bookingFields.reduce((responses, field) => {
+ return {
+ ...responses,
+ [field.name]: bookingData?.responses[field.name],
+ };
+ }, {});
+ defaults.responses = {
+ ...responses,
+ name: defaultUserValues.name,
+ email: defaultUserValues.email,
+ };
+ setDefaultValues(defaults);
+ })();
+ // do not add routerQuery as a dependency, it will cause infinite loop
+ // eslint-disable-next-line react-hooks/exhaustive-deps
+ }, [
+ eventType?.bookingFields,
+ formValues,
+ isRescheduling,
+ bookingData,
+ rescheduleUid,
+ searchParams,
+ session.data?.user?.email,
+ session.data?.user?.name,
+ session.data?.user?.username,
+ ]);
+
+ // When initialValues is available(after doing async schema parsing) or session is available(so that we can prefill logged-in user email and name), we need to reset the form with the initialValues
+ const key = `${Object.keys(initialValues).length}_${session ? 1 : 0}`;
+
+ return { initialValues, key };
+}
diff --git a/packages/features/bookings/Booker/components/hooks/useOverlayCalendar.ts b/packages/features/bookings/Booker/components/hooks/useOverlayCalendar.ts
new file mode 100644
index 00000000000..5208b2fdd5f
--- /dev/null
+++ b/packages/features/bookings/Booker/components/hooks/useOverlayCalendar.ts
@@ -0,0 +1,88 @@
+import { useEffect, useState } from "react";
+import { shallow } from "zustand/shallow";
+
+import dayjs from "@calcom/dayjs";
+import { useTimePreferences } from "@calcom/features/bookings/lib";
+
+import { useOverlayCalendarStore } from "../OverlayCalendar/store";
+import type { UseCalendarsReturnType } from "./useCalendars";
+import { useLocalSet } from "./useLocalSet";
+
+export const useOverlayCalendar = ({
+ connectedCalendars,
+ overlayBusyDates,
+ onToggleCalendar,
+}: Pick<UseCalendarsReturnType, "connectedCalendars" | "overlayBusyDates" | "onToggleCalendar">) => {
+ const { set, toggleValue, hasItem } = useLocalSet<{
+ credentialId: number;
+ externalId: string;
+ }>("toggledConnectedCalendars", []);
+ const [initalised, setInitalised] = useState(false);
+ const [continueWithProvider, setContinueWithProvider] = useOverlayCalendarStore(
+ (state) => [state.continueWithProviderModal, state.setContinueWithProviderModal],
+ shallow
+ );
+ const [calendarSettingsOverlay, setCalendarSettingsOverlay] = useOverlayCalendarStore(
+ (state) => [state.calendarSettingsOverlayModal, state.setCalendarSettingsOverlayModal],
+ shallow
+ );
+ const setOverlayBusyDates = useOverlayCalendarStore((state) => state.setOverlayBusyDates);
+ const { timezone } = useTimePreferences();
+
+ useEffect(() => {
+ if (overlayBusyDates) {
+ const nowDate = dayjs();
+ const usersTimezoneDate = nowDate.tz(timezone);
+
+ const offset = (usersTimezoneDate.utcOffset() - nowDate.utcOffset()) / 60;
+
+ const offsettedArray = overlayBusyDates.map((item) => {
+ return {
+ ...item,
+ start: dayjs(item.start).add(offset, "hours").toDate(),
+ end: dayjs(item.end).add(offset, "hours").toDate(),
+ };
+ });
+ setOverlayBusyDates(offsettedArray);
+ }
+ // eslint-disable-next-line react-hooks/exhaustive-deps
+ }, [overlayBusyDates]);
+
+ useEffect(() => {
+ if (connectedCalendars && set.size === 0 && !initalised) {
+ connectedCalendars.forEach((item) => {
+ item.calendars?.forEach((cal) => {
+ const id = { credentialId: item.credentialId, externalId: cal.externalId };
+ if (cal.primary) {
+ toggleValue(id);
+ }
+ });
+ });
+ setInitalised(true);
+ }
+ // eslint-disable-next-line react-hooks/exhaustive-deps
+ }, [hasItem, set, initalised]);
+
+ const handleToggleConnectedCalendar = (externalCalendarId: string, credentialId: number) => {
+ toggleValue({
+ credentialId: credentialId,
+ externalId: externalCalendarId,
+ });
+ setOverlayBusyDates([]);
+ onToggleCalendar();
+ };
+
+ return {
+ isOpenOverlayContinueModal: continueWithProvider,
+ isOpenOverlaySettingsModal: calendarSettingsOverlay,
+ handleCloseContinueModal: (val: boolean) => setContinueWithProvider(val),
+ handleCloseSettingsModal: (val: boolean) => setCalendarSettingsOverlay(val),
+ handleToggleConnectedCalendar,
+ checkIsCalendarToggled: (externalId: string, credentialId: number) => {
+ return hasItem({
+ credentialId: credentialId,
+ externalId: externalId,
+ });
+ },
+ };
+};
diff --git a/packages/features/bookings/Booker/components/hooks/useSlots.ts b/packages/features/bookings/Booker/components/hooks/useSlots.ts
new file mode 100644
index 00000000000..d66cda272fd
--- /dev/null
+++ b/packages/features/bookings/Booker/components/hooks/useSlots.ts
@@ -0,0 +1,74 @@
+import { useEffect } from "react";
+import { shallow } from "zustand/shallow";
+
+import dayjs from "@calcom/dayjs";
+import { useBookerStore } from "@calcom/features/bookings/Booker/store";
+import { useSlotReservationId } from "@calcom/features/bookings/Booker/useSlotReservationId";
+import type { useEventReturnType } from "@calcom/features/bookings/Booker/utils/event";
+import { MINUTES_TO_BOOK } from "@calcom/lib/constants";
+import { trpc } from "@calcom/trpc";
+
+export const useSlots = (event: useEventReturnType) => {
+ const selectedDuration = useBookerStore((state) => state.selectedDuration);
+ const [selectedTimeslot, setSelectedTimeslot] = useBookerStore(
+ (state) => [state.selectedTimeslot, state.setSelectedTimeslot],
+ shallow
+ );
+ const [slotReservationId, setSlotReservationId] = useSlotReservationId();
+ const reserveSlotMutation = trpc.viewer.public.slots.reserveSlot.useMutation({
+ trpc: {
+ context: {
+ skipBatch: true,
+ },
+ },
+ onSuccess: (data) => {
+ setSlotReservationId(data.uid);
+ },
+ });
+ const removeSelectedSlot = trpc.viewer.public.slots.removeSelectedSlotMark.useMutation({
+ trpc: { context: { skipBatch: true } },
+ });
+
+ const handleRemoveSlot = () => {
+ if (event?.data) {
+ removeSelectedSlot.mutate({ uid: slotReservationId });
+ }
+ };
+ const handleReserveSlot = () => {
+ if (event?.data?.id && selectedTimeslot && (selectedDuration || event?.data?.length)) {
+ reserveSlotMutation.mutate({
+ slotUtcStartDate: dayjs(selectedTimeslot).utc().format(),
+ eventTypeId: event.data.id,
+ slotUtcEndDate: dayjs(selectedTimeslot)
+ .utc()
+ .add(selectedDuration || event.data.length, "minutes")
+ .format(),
+ });
+ }
+ };
+
+ const timeslot = useBookerStore((state) => state.selectedTimeslot);
+
+ useEffect(() => {
+ handleReserveSlot();
+
+ const interval = setInterval(() => {
+ handleReserveSlot();
+ }, parseInt(MINUTES_TO_BOOK) * 60 * 1000 - 2000);
+
+ return () => {
+ handleRemoveSlot();
+ clearInterval(interval);
+ };
+ // eslint-disable-next-line react-hooks/exhaustive-deps
+ }, [event?.data?.id, timeslot]);
+
+ return {
+ selectedTimeslot,
+ setSelectedTimeslot,
+ setSlotReservationId,
+ slotReservationId,
+ handleReserveSlot,
+ handleRemoveSlot,
+ };
+};
diff --git a/packages/features/bookings/Booker/components/hooks/useVerifyEmail.ts b/packages/features/bookings/Booker/components/hooks/useVerifyEmail.ts
new file mode 100644
index 00000000000..fd370484689
--- /dev/null
+++ b/packages/features/bookings/Booker/components/hooks/useVerifyEmail.ts
@@ -0,0 +1,55 @@
+import { useState } from "react";
+
+import { useBookerStore } from "@calcom/features/bookings/Booker/store";
+import { useLocale } from "@calcom/lib/hooks/useLocale";
+import { trpc } from "@calcom/trpc";
+import { showToast } from "@calcom/ui";
+
+export interface IUseVerifyEmailProps {
+ email: string;
+ onVerifyEmail?: () => void;
+ name?: string | { firstName: string; lastname?: string };
+ requiresBookerEmailVerification?: boolean;
+}
+
+export const useVerifyEmail = ({
+ email,
+ name,
+ requiresBookerEmailVerification,
+ onVerifyEmail,
+}: IUseVerifyEmailProps) => {
+ const [isEmailVerificationModalVisible, setEmailVerificationModalVisible] = useState(false);
+ const verifiedEmail = useBookerStore((state) => state.verifiedEmail);
+ const setVerifiedEmail = useBookerStore((state) => state.setVerifiedEmail);
+
+ const { t } = useLocale();
+ const sendEmailVerificationByCodeMutation = trpc.viewer.auth.sendVerifyEmailCode.useMutation({
+ onSuccess() {
+ showToast(t("email_sent"), "success");
+ },
+ onError() {
+ showToast(t("email_not_sent"), "error");
+ },
+ });
+
+ const handleVerifyEmail = () => {
+ onVerifyEmail?.();
+
+ sendEmailVerificationByCodeMutation.mutate({
+ email,
+ username: typeof name === "string" ? name : name?.firstName,
+ });
+ setEmailVerificationModalVisible(true);
+ };
+
+ const renderConfirmNotVerifyEmailButtonCond =
+ !requiresBookerEmailVerification || (email && verifiedEmail && verifiedEmail === email);
+
+ return {
+ handleVerifyEmail,
+ isEmailVerificationModalVisible,
+ setEmailVerificationModalVisible,
+ setVerifiedEmail,
+ renderConfirmNotVerifyEmailButtonCond: Boolean(renderConfirmNotVerifyEmailButtonCond),
+ };
+};
diff --git a/packages/features/bookings/Booker/utils/event.ts b/packages/features/bookings/Booker/utils/event.ts
index dc6eb24be1a..b88645fdbd3 100644
--- a/packages/features/bookings/Booker/utils/event.ts
+++ b/packages/features/bookings/Booker/utils/event.ts
@@ -8,6 +8,9 @@ import { trpc } from "@calcom/trpc/react";
import { useTimePreferences } from "../../lib/timePreferences";
import { useBookerStore } from "../store";
+export type useEventReturnType = ReturnType<typeof useEvent>;
+export type useScheduleForEventReturnType = ReturnType<typeof useScheduleForEvent>;
+
/**
* Wrapper hook around the trpc query that fetches
* the event curently viewed in the booker. It will get
diff --git a/packages/features/bookings/lib/book-event-form/booking-to-mutation-input-mapper.tsx b/packages/features/bookings/lib/book-event-form/booking-to-mutation-input-mapper.tsx
index 2abed190987..cf400c54b0b 100644
--- a/packages/features/bookings/lib/book-event-form/booking-to-mutation-input-mapper.tsx
+++ b/packages/features/bookings/lib/book-event-form/booking-to-mutation-input-mapper.tsx
@@ -5,7 +5,7 @@ import { parseRecurringDates } from "@calcom/lib/parse-dates";
import type { PublicEvent, BookingCreateBody, RecurringBookingCreateBody } from "../../types";
-type BookingOptions = {
+export type BookingOptions = {
values: Record<string, unknown>;
event: PublicEvent;
date: string;
diff --git a/packages/features/bookings/lib/create-instant-booking.ts b/packages/features/bookings/lib/create-instant-booking.ts
index 1431e2ef5e1..e8036f5ae4e 100644
--- a/packages/features/bookings/lib/create-instant-booking.ts
+++ b/packages/features/bookings/lib/create-instant-booking.ts
@@ -1,8 +1,8 @@
import { post } from "@calcom/lib/fetch-wrapper";
-import type { BookingCreateBody, InstatBookingResponse } from "../types";
+import type { BookingCreateBody, InstantBookingResponse } from "../types";
export const createInstantBooking = async (data: BookingCreateBody) => {
- const response = await post<BookingCreateBody, InstatBookingResponse>("/api/book/instant-event", data);
+ const response = await post<BookingCreateBody, InstantBookingResponse>("/api/book/instant-event", data);
return response;
};
diff --git a/packages/features/bookings/types.ts b/packages/features/bookings/types.ts
index 1b413c9e6ac..849ea14de74 100644
--- a/packages/features/bookings/types.ts
+++ b/packages/features/bookings/types.ts
@@ -33,6 +33,6 @@ export type BookingResponse = Awaited<
ReturnType<typeof import("@calcom/features/bookings/lib/handleNewBooking").default>
>;
-export type InstatBookingResponse = Awaited<
+export type InstantBookingResponse = Awaited<
ReturnType<typeof import("@calcom/features/instant-meeting/handleInstantMeeting").default>
>;