// Get router variables import { ArrowLeftIcon, ChevronDownIcon, ChevronUpIcon, ClipboardCheckIcon, ClockIcon, CreditCardIcon, GlobeIcon, InformationCircleIcon, LocationMarkerIcon, RefreshIcon, VideoCameraIcon, } from "@heroicons/react/solid"; import { EventType } from "@prisma/client"; import * as Collapsible from "@radix-ui/react-collapsible"; import { useContracts } from "contexts/contractsContext"; import dayjs, { Dayjs } from "dayjs"; import customParseFormat from "dayjs/plugin/customParseFormat"; import timeZone from "dayjs/plugin/timezone"; import utc from "dayjs/plugin/utc"; import { TFunction } from "next-i18next"; import { useRouter } from "next/router"; import { useEffect, useMemo, useState } from "react"; import { FormattedNumber, IntlProvider } from "react-intl"; import { z } from "zod"; import { AppStoreLocationType, LocationObject, LocationType } from "@calcom/app-store/locations"; import { useEmbedNonStylesConfig, useEmbedStyles, useIsBackgroundTransparent, useIsEmbed, } from "@calcom/embed-core/embed-iframe"; import classNames from "@calcom/lib/classNames"; import { CAL_URL, WEBAPP_URL } from "@calcom/lib/constants"; import { yyyymmdd } from "@calcom/lib/date-fns"; import { useLocale } from "@calcom/lib/hooks/useLocale"; import { getRecurringFreq } from "@calcom/lib/recurringStrings"; import { localStorage } from "@calcom/lib/webstorage"; import DatePicker from "@calcom/ui/booker/DatePicker"; import { timeZone as localStorageTimeZone } from "@lib/clock"; // import { timeZone } from "@lib/clock"; import { useExposePlanGlobally } from "@lib/hooks/useExposePlanGlobally"; import useTheme from "@lib/hooks/useTheme"; import { isBrandingHidden } from "@lib/isBrandingHidden"; import { collectPageParameters, telemetryEventTypes, useTelemetry } from "@lib/telemetry"; import { detectBrowserTimeFormat } from "@lib/timeFormat"; import { trpc } from "@lib/trpc"; import CustomBranding from "@components/CustomBranding"; import AvailableTimes from "@components/booking/AvailableTimes"; import TimeOptions from "@components/booking/TimeOptions"; import { HeadSeo } from "@components/seo/head-seo"; import AvatarGroup from "@components/ui/AvatarGroup"; import PoweredByCal from "@components/ui/PoweredByCal"; import type { AvailabilityPageProps } from "../../../pages/[user]/[type]"; import type { DynamicAvailabilityPageProps } from "../../../pages/d/[link]/[slug]"; import type { AvailabilityTeamPageProps } from "../../../pages/team/[slug]/[type]"; dayjs.extend(utc); dayjs.extend(timeZone); dayjs.extend(customParseFormat); type Props = AvailabilityTeamPageProps | AvailabilityPageProps | DynamicAvailabilityPageProps; export const locationKeyToString = (location: LocationObject, t: TFunction) => { switch (location.type) { case LocationType.InPerson: return location.address || "In Person"; // If disabled address won't exist on the object case LocationType.Link: return location.link || "Link"; // If disabled link won't exist on the object case LocationType.Phone: return t("your_number"); case LocationType.UserPhone: return t("phone_call"); case LocationType.GoogleMeet: return "Google Meet"; case LocationType.Zoom: return "Zoom"; case LocationType.Daily: return "Cal Video"; case LocationType.Jitsi: return "Jitsi"; case LocationType.Huddle01: return "Huddle Video"; case LocationType.Tandem: return "Tandem"; case LocationType.Teams: return "Microsoft Teams"; default: return null; } }; const GoBackToPreviousPage = ({ slug }: { slug: string }) => { const router = useRouter(); const [previousPage, setPreviousPage] = useState(); useEffect(() => { setPreviousPage(document.referrer); }, []); return previousPage === `${WEBAPP_URL}/${slug}` ? (
router.back()} />

Go Back

) : ( <> ); }; const useSlots = ({ eventTypeId, startTime, endTime, timeZone, }: { eventTypeId: number; startTime?: Dayjs; endTime?: Dayjs; timeZone: string; }) => { const { data, isLoading } = trpc.useQuery( [ "viewer.public.slots.getSchedule", { eventTypeId, startTime: startTime?.toISOString() || "", timeZone, endTime: endTime?.toISOString() || "", }, ], { enabled: !!startTime && !!endTime } ); const [cachedSlots, setCachedSlots] = useState["slots"]>({}); useEffect(() => { if (data?.slots) { setCachedSlots((c) => ({ ...c, ...data?.slots })); } }, [data]); return { slots: cachedSlots, isLoading }; }; const SlotPicker = ({ eventType, timeFormat, timeZone, recurringEventCount, seatsPerTimeSlot, weekStart = 0, }: { eventType: Pick; timeFormat: string; timeZone: string; seatsPerTimeSlot?: number; recurringEventCount?: number; weekStart?: 0 | 1 | 2 | 3 | 4 | 5 | 6; }) => { const [selectedDate, setSelectedDate] = useState(); const [browsingDate, setBrowsingDate] = useState(); const { date, setQuery: setDate } = useRouterQuery("date"); const { month, setQuery: setMonth } = useRouterQuery("month"); const router = useRouter(); useEffect(() => { if (!router.isReady) return; // Etc/GMT is not actually a timeZone, so handle this select option explicitly to prevent a hard crash. if (timeZone === "Etc/GMT") { setBrowsingDate(dayjs.utc(month).startOf("month")); if (date) { setSelectedDate(dayjs.utc(date)); } } else { setBrowsingDate(dayjs(month).tz(timeZone, true).startOf("month")); if (date) { setSelectedDate(dayjs(date).tz(timeZone, true)); } } }, [router.isReady, month, date, timeZone]); const { i18n, isLocaleReady } = useLocale(); const { slots: _1 } = useSlots({ eventTypeId: eventType.id, startTime: selectedDate?.startOf("month"), endTime: selectedDate?.endOf("month"), timeZone, }); const { slots: _2, isLoading } = useSlots({ eventTypeId: eventType.id, startTime: browsingDate?.startOf("month"), endTime: browsingDate?.endOf("month"), timeZone, }); const slots = useMemo(() => ({ ..._1, ..._2 }), [_1, _2]); return ( <> slots[k].length > 0)} locale={isLocaleReady ? i18n.language : "en"} selected={selectedDate} onChange={(newDate) => { setDate(newDate.format("YYYY-MM-DD")); }} onMonthChange={(newMonth) => { setMonth(newMonth.format("YYYY-MM")); }} browsingDate={browsingDate} weekStart={weekStart} /> {selectedDate && ( )} ); }; function TimezoneDropdown({ onChangeTimeFormat, onChangeTimeZone, timeZone, }: { onChangeTimeFormat: (newTimeFormat: string) => void; onChangeTimeZone: (newTimeZone: string) => void; timeZone?: string; }) { const [isTimeOptionsOpen, setIsTimeOptionsOpen] = useState(false); useEffect(() => { handleToggle24hClock(localStorage.getItem("timeOption.is24hClock") === "true"); // eslint-disable-next-line react-hooks/exhaustive-deps }, []); const handleSelectTimeZone = (newTimeZone: string) => { onChangeTimeZone(newTimeZone); localStorageTimeZone(newTimeZone); setIsTimeOptionsOpen(false); }; const handleToggle24hClock = (is24hClock: boolean) => { onChangeTimeFormat(is24hClock ? "HH:mm" : "h:mma"); }; return ( {timeZone || dayjs.tz.guess()} {isTimeOptionsOpen ? ( ) : ( )} ); } const dateQuerySchema = z.object({ rescheduleUid: z.string().optional().default(""), date: z.string().optional().default(""), timeZone: z.string().optional().default(""), }); const useRouterQuery = (name: T) => { const router = useRouter(); const query = z.object({ [name]: z.string().optional() }).parse(router.query); const setQuery = (newValue: string | number | null | undefined) => { router.replace({ query: { ...router.query, [name]: newValue } }, undefined, { shallow: true }); }; return { [name]: query[name], setQuery } as { [K in T]: string | undefined; } & { setQuery: typeof setQuery }; }; const AvailabilityPage = ({ profile, eventType }: Props) => { const router = useRouter(); const isEmbed = useIsEmbed(); const query = dateQuerySchema.parse(router.query); const { rescheduleUid } = query; const { Theme } = useTheme(profile.theme); const { t } = useLocale(); const { contracts } = useContracts(); const availabilityDatePickerEmbedStyles = useEmbedStyles("availabilityDatePicker"); const shouldAlignCentrallyInEmbed = useEmbedNonStylesConfig("align") !== "left"; const shouldAlignCentrally = !isEmbed || shouldAlignCentrallyInEmbed; const isBackgroundTransparent = useIsBackgroundTransparent(); const [timeZone, setTimeZone] = useState(); const [timeFormat, setTimeFormat] = useState(detectBrowserTimeFormat); const [isAvailableTimesVisible, setIsAvailableTimesVisible] = useState(); useEffect(() => { setTimeZone(localStorageTimeZone() || dayjs.tz.guess()); }, []); useEffect(() => { setIsAvailableTimesVisible(!!query.date); }, [query.date]); // TODO: Improve this; useExposePlanGlobally(eventType.users.length === 1 ? eventType.users[0].plan : "PRO"); // TODO: this needs to be extracted elsewhere useEffect(() => { if (eventType.metadata.smartContractAddress) { const eventOwner = eventType.users[0]; if (!contracts[(eventType.metadata.smartContractAddress || null) as number]) router.replace(`/${eventOwner.username}`); } }, [contracts, eventType.metadata.smartContractAddress, eventType.users, router]); const [recurringEventCount, setRecurringEventCount] = useState(eventType.recurringEvent?.count); const telemetry = useTelemetry(); useEffect(() => { if (top !== window) { //page_view will be collected automatically by _middleware.ts telemetry.event( telemetryEventTypes.embedView, collectPageParameters("/availability", { isTeamBooking: document.URL.includes("team/") }) ); } }, [telemetry]); // Recurring event sidebar requires more space const maxWidth = isAvailableTimesVisible ? recurringEventCount ? "max-w-6xl" : "max-w-5xl" : recurringEventCount ? "max-w-4xl" : "max-w-3xl"; const timezoneDropdown = useMemo( () => ( ), [timeZone] ); return ( <>
{/* mobile: details */}
user.name !== profile.name) .map((user) => ({ title: user.name, image: `${CAL_URL}/${user.username}/avatar.png`, alt: user.name || undefined, })), ].filter((item) => !!item.image) as { image: string; alt?: string; title?: string }[] } size={9} truncateAfter={5} />

{profile.name}

{eventType.title}

{eventType?.description && (

{eventType.description}

)} {eventType?.requiresConfirmation && (

{t("requires_confirmation")}

)} {eventType.locations.length === 1 && (

{Object.values(AppStoreLocationType).includes( eventType.locations[0].type as unknown as AppStoreLocationType ) ? ( ) : ( )} {locationKeyToString(eventType.locations[0], t)}

)} {eventType.locations.length > 1 && (

{eventType.locations.map((el, i, arr) => { return ( {locationKeyToString(el, t)}{" "} {arr.length - 1 !== i && ( {t("or_lowercase")} )} ); })}

)}

{eventType.length} {t("minutes")}

{eventType.price > 0 && (
)} {!rescheduleUid && eventType.recurringEvent && (

{getRecurringFreq({ t, recurringEvent: eventType.recurringEvent })}

{ setRecurringEventCount(parseInt(event?.target.value)); }} />

{t("occurrence", { count: recurringEventCount, })}

)} {timezoneDropdown}
{/* Temp disabled booking?.startTime && rescheduleUid && (

{t("former_time")}

{typeof booking.startTime === "string" && parseDate(dayjs(booking.startTime), i18n)}

)*/}
user.name !== profile.name) .map((user) => ({ title: user.name, alt: user.name, image: `${CAL_URL}/${user.username}/avatar.png`, })), ].filter((item) => !!item.image) as { image: string; alt?: string; title?: string }[] } size={10} truncateAfter={3} />

{profile.name}

{eventType.title}

{eventType?.description && (

{eventType.description}

)} {eventType?.requiresConfirmation && (
{t("requires_confirmation")}
)} {eventType.locations.length === 1 && (

{Object.values(AppStoreLocationType).includes( eventType.locations[0].type as unknown as AppStoreLocationType ) ? ( ) : ( )} {locationKeyToString(eventType.locations[0], t)}

)} {eventType.locations.length > 1 && (

{eventType.locations.map((el, i, arr) => { return ( {locationKeyToString(el, t)}{" "} {arr.length - 1 !== i && ( {t("or_lowercase")} )} ); })}

)}

{eventType.length} {t("minutes")}

{!rescheduleUid && eventType.recurringEvent && (

{getRecurringFreq({ t, recurringEvent: eventType.recurringEvent })}

{ setRecurringEventCount(parseInt(event?.target.value)); }} />

{t("occurrence", { count: recurringEventCount, })}

)} {eventType.price > 0 && (

)} {timezoneDropdown}
{/* Temporarily disabled - booking?.startTime && rescheduleUid && (

{t("former_time")}

{typeof booking.startTime === "string" && parseDate(dayjs(booking.startTime), i18n)}

)*/}
{timeZone && ( )}
{(!eventType.users[0] || !isBrandingHidden(eventType.users[0])) && !isEmbed && }
); }; export default AvailabilityPage;