refactor: Move trpc-dependent components from features to web [2] (#26420)

* fix

* move event types components to web

* update import paths

* mv apps components

* migrate form builder

* fix

* mv sso

* fix

* mv

* update import paths

* update import paths

* mv

* mv

* mv

* fix

* update Booker

* fix

* fix

* fix

* fix

* mv video

* mv embed components to web

* update import paths

* mv calendar weekly view components

* update import paths

* fix

* fixp

* fix

* fix

* fix

* fix: update FormBuilder imports to use @calcom/features/form-builder

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

* fix: update broken import paths after file migrations

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

* fix: correct import paths for platform atoms and moved components

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

* fix: apply CSS type fixes and add missing atoms exports

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

* fix: resolve type errors in test files after component migrations

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

* fix: resolve remaining type errors in test files

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

* fix

* migrate

* fix: resolve type errors in test and mock files

- Add missing bookingForm, bookerFormErrorRef, instantConnectCooldownMs to Booker.test.tsx bookings prop
- Add all required BookerEvent properties to event.mock.ts
- Add vi import from vitest to all mock files
- Fix date parameter types in packages/dayjs/__mocks__/index.ts
- Add verificationCode and setVerificationCode to test-utils.tsx mock store
- Remove children.type access in Section.tsx mock to fix type error
- Fix lint issues: remove unused React imports, use import type where needed, add return types
- Add biome-ignore comments for pre-existing lint warnings in test files

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

* migrate

* migrate

* migrate

* update import paths

* update import paths

* update import paths

* fix

* migrate data table

* migrate data table

* fix

* fix

* fix

* migrate insights components

* migrate insights components

* fix

* mv

* update import paths

* fix

* fix

* fix

* fix

* fix

* fix: resolve type errors in test mocks

- Booker.test.tsx: Add all required UseFormReturn methods to bookingForm mock
- event.mock.ts: Fix entity, subsetOfHosts, instantMeetingParameters, fieldTranslations, image types
- dayjs/__mocks__/index.ts: Use Object.assign for proper typing of mock properties
- Section.tsx: Change 'class' to 'className' in JSX with biome-ignore comment

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

* fix: add missing hasDataErrors and dataErrors to bookings.errors mock

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

* fix: add missing loadingStates properties to bookings mock

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

* fix: add missing slots properties (setTentativeSelectedTimeslots, tentativeSelectedTimeslots, slotReservationId)

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

* fix: update quickAvailabilityChecks to include utcEndIso and use valid status type

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

* fix: add missing bookerForm properties (formName, beforeVerifyEmail, formErrors)

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

* fix: add missing UseFormReturn properties to bookerForm.bookingForm mock

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

* fix: add hasFormErrors and formErrors to bookerForm.formErrors mock

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

* fix: add hasFormErrors and formErrors to bookerForm.errors mock

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

* fix: add missing isError property to mockEvent

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

* fix: use complete BookerEvent mock in Booker.test.tsx

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

* fix: use branded bookingFields type in event mock

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

* fix: add missing schedule mock properties (isError, isSuccess, isLoading, dataUpdatedAt)

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

* revert

* fix

* fix

* fix

* fix build

* fix

* fix

* fix

* fix: correct AddMembersWithSwitch test wrapper to use initial assignAllTeamMembers value

- Fixed test wrapper to initialize useState with componentProps.assignAllTeamMembers
  instead of hardcoded false, allowing tests to properly test different states
- Updated test expectations for ALL_TEAM_MEMBERS_ENABLED_AND_SEGMENT_NOT_APPLICABLE
  state to match actual component behavior (toggle should be present and checked)
- Fixed 'should show Segment when toggled on' test to start with assignAllTeamMembers: false
  to properly test the flow of enabling it
- Added explicit types to satisfy biome lint requirements

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

* fix: use JSX.Element instead of React.JSX.Element for type compatibility

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

---------

Co-authored-by: Devin AI <158243242+devin-ai-integration[bot]@users.noreply.github.com>
This commit is contained in:
Benny JooandDevin AI authored and GitHub committed 2026-01-05 12:53:51 -03:00
1 parent 3d73238c00
commit 404d46c991
390 files changed
+645 -667

No files matched your search

+4 -4
View File
@@ -3,10 +3,10 @@
import type { ChangeEventHandler } from "react";
import { useState } from "react";
import { AllApps } from "@calcom/features/apps/components/AllApps";
import { AppStoreCategories } from "@calcom/features/apps/components/Categories";
import { PopularAppsSlider } from "@calcom/features/apps/components/PopularAppsSlider";
import { RecentAppsSlider } from "@calcom/features/apps/components/RecentAppsSlider";
import { AllApps } from "@calcom/web/modules/apps/components/AllApps";
import { AppStoreCategories } from "@calcom/web/modules/apps/components/Categories";
import { PopularAppsSlider } from "@calcom/web/modules/apps/components/PopularAppsSlider";
import { RecentAppsSlider } from "@calcom/web/modules/apps/components/RecentAppsSlider";
import { useLocale } from "@calcom/lib/hooks/useLocale";
import type { AppCategories } from "@calcom/prisma/enums";
import type { AppFrontendPayload } from "@calcom/types/App";
@@ -2,7 +2,7 @@
import Link from "next/link";
import { AppCard } from "@calcom/features/apps/components/AppCard";
import { AppCard } from "@calcom/web/modules/apps/components/AppCard";
import { useLocale } from "@calcom/lib/hooks/useLocale";
import { SkeletonText } from "@calcom/ui/components/skeleton";
@@ -0,0 +1,362 @@
"use client";
import { zodResolver } from "@hookform/resolvers/zod";
// eslint-disable-next-line no-restricted-imports
import { noop } from "lodash";
import type { FC } from "react";
import { useReducer, useState } from "react";
import { Controller, useForm } from "react-hook-form";
import { z } from "zod";
import AppCategoryNavigation from "@calcom/app-store/_components/AppCategoryNavigation";
import { appKeysSchemas } from "@calcom/app-store/apps.keys-schemas.generated";
import AppListCard from "@calcom/web/modules/apps/components/AppListCard";
import { Dialog } from "@calcom/features/components/controlled-dialog";
import { useCompatSearchParams } from "@calcom/lib/hooks/useCompatSearchParams";
import { useLocale } from "@calcom/lib/hooks/useLocale";
import { AppCategories } from "@calcom/prisma/enums";
import type { RouterOutputs } from "@calcom/trpc/react";
import { trpc } from "@calcom/trpc/react";
import cs from "@calcom/ui/classNames";
import { Button } from "@calcom/ui/components/button";
import {
DialogContent,
DialogFooter,
DialogClose,
ConfirmationDialogContent,
} from "@calcom/ui/components/dialog";
import { EmptyScreen } from "@calcom/ui/components/empty-screen";
import { Form } from "@calcom/ui/components/form";
import { TextField } from "@calcom/ui/components/form";
import { Switch } from "@calcom/ui/components/form";
import { Icon } from "@calcom/ui/components/icon";
import { List } from "@calcom/ui/components/list";
import { SkeletonButton, SkeletonContainer, SkeletonText } from "@calcom/ui/components/skeleton";
import { showToast } from "@calcom/ui/components/toast";
type App = RouterOutputs["viewer"]["apps"]["listLocal"][number];
const IntegrationContainer = ({
app,
category,
handleModelOpen,
}: {
app: App;
category: string;
handleModelOpen: (data: EditModalState) => void;
}) => {
const { t } = useLocale();
const utils = trpc.useUtils();
const [disableDialog, setDisableDialog] = useState(false);
const showKeyModal = (fromEnabled?: boolean) => {
// FIXME: This is preventing the modal from opening for apps that has null keys
if (app.keys) {
handleModelOpen({
dirName: app.dirName,
keys: app.keys,
slug: app.slug,
type: app.type,
isOpen: "editKeys",
fromEnabled,
appName: app.name,
});
}
};
const enableAppMutation = trpc.viewer.apps.toggle.useMutation({
onSuccess: (enabled) => {
utils.viewer.apps.listLocal.invalidate({ category });
setDisableDialog(false);
showToast(
enabled ? t("app_is_enabled", { appName: app.name }) : t("app_is_disabled", { appName: app.name }),
"success"
);
if (enabled) {
showKeyModal();
}
},
onError: (error) => {
showToast(error.message, "error");
},
});
return (
<li>
<AppListCard
logo={app.logo}
description={app.description}
title={app.name}
isTemplate={app.isTemplate}
actions={
<div className="flex items-center justify-self-end">
{app.keys && (
<Button color="secondary" className="mr-2" onClick={() => showKeyModal()}>
<Icon name="pencil" />
</Button>
)}
<Switch
checked={app.enabled}
onClick={() => {
if (app.enabled) {
setDisableDialog(true);
} else if (app.keys) {
showKeyModal(true);
} else {
enableAppMutation.mutate({ slug: app.slug, enabled: !app.enabled });
}
}}
/>
</div>
}
/>
<Dialog open={disableDialog} onOpenChange={setDisableDialog}>
<ConfirmationDialogContent
title={t("disable_app")}
variety="danger"
onConfirm={() => {
enableAppMutation.mutate({ slug: app.slug, enabled: !app.enabled });
}}>
{t("disable_app_description")}
</ConfirmationDialogContent>
</Dialog>
</li>
);
};
const querySchema = z.object({
category: z
.nativeEnum({ ...AppCategories, conferencing: "conferencing" })
.optional()
.default(AppCategories.calendar),
});
const AdminAppsList = ({
baseURL,
className,
useQueryParam = false,
classNames,
onSubmit = noop,
nav,
...rest
}: {
baseURL: string;
classNames?: {
form?: string;
appCategoryNavigationRoot?: string;
appCategoryNavigationContainer?: string;
verticalTabsItem?: string;
};
className?: string;
useQueryParam?: boolean;
onSubmit?: () => void;
nav?: { onNext: () => void; onPrev: () => void };
} & Omit<JSX.IntrinsicElements["form"], "onSubmit">) => {
const { t } = useLocale();
return (
<form
{...rest}
className={
classNames?.form ?? "bg-default max-w-80 mb-4 rounded-md px-0 pt-0 md:max-w-full md:px-8 md:pt-10"
}
onSubmit={(e) => {
e.preventDefault();
onSubmit();
nav?.onNext();
}}>
<AppCategoryNavigation
baseURL={baseURL}
useQueryParam={useQueryParam}
classNames={{
root: className,
verticalTabsItem: classNames?.verticalTabsItem,
container: cs("min-w-0 w-full", classNames?.appCategoryNavigationContainer ?? "max-w-[500px]"),
}}>
<AdminAppsListContainer />
</AppCategoryNavigation>
<div className="flex justify-end gap-2 px-4 py-4">
{nav && (
<Button type="button" color="secondary" onClick={nav.onPrev}>
{t("prev_step")}
</Button>
)}
<Button type="submit" color="primary">
{t("finish")}
</Button>
</div>
</form>
);
};
const EditKeysModal: FC<{
dirName: string;
slug: string;
type: string;
isOpen: boolean;
keys: App["keys"];
handleModelClose: () => void;
fromEnabled?: boolean;
appName?: string;
}> = (props) => {
const utils = trpc.useUtils();
const { t } = useLocale();
const { dirName, slug, type, isOpen, keys, handleModelClose, fromEnabled, appName } = props;
const appKeySchema = appKeysSchemas[dirName as keyof typeof appKeysSchemas];
const formMethods = useForm({
resolver: zodResolver(appKeySchema),
});
const saveKeysMutation = trpc.viewer.apps.saveKeys.useMutation({
onSuccess: () => {
showToast(fromEnabled ? t("app_is_enabled", { appName }) : t("keys_have_been_saved"), "success");
utils.viewer.apps.listLocal.invalidate();
handleModelClose();
},
onError: (error) => {
showToast(error.message, "error");
},
});
return (
<Dialog open={isOpen} onOpenChange={handleModelClose}>
<DialogContent title={t("edit_keys")} type="creation">
{!!keys && typeof keys === "object" && (
<Form
id="edit-keys"
form={formMethods}
handleSubmit={(values) =>
saveKeysMutation.mutate({
slug,
type,
keys: values,
dirName,
fromEnabled,
})
}
className="px-4 pb-4">
{Object.keys(keys).map((key) => (
<Controller
name={key}
key={key}
control={formMethods.control}
defaultValue={keys && keys[key] ? keys?.[key] : ""}
render={({ field: { value } }) => (
<TextField
label={key}
key={key}
name={key}
value={value}
onChange={(e) => {
formMethods.setValue(key, e?.target.value);
}}
/>
)}
/>
))}
</Form>
)}
<DialogFooter showDivider className="mt-8">
<DialogClose onClick={handleModelClose} />
<Button form="edit-keys" type="submit">
{t("save")}
</Button>
</DialogFooter>
</DialogContent>
</Dialog>
);
};
interface EditModalState extends Pick<App, "keys"> {
isOpen: "none" | "editKeys" | "disableKeys";
dirName: string;
type: string;
slug: string;
fromEnabled?: boolean;
appName?: string;
}
const AdminAppsListContainer = () => {
const searchParams = useCompatSearchParams();
const { t } = useLocale();
const category = searchParams?.get("category") || AppCategories.calendar;
const { data: apps, isPending } = trpc.viewer.apps.listLocal.useQuery(
{ category },
{ enabled: searchParams !== null }
);
const [modalState, setModalState] = useReducer(
(data: EditModalState, partialData: Partial<EditModalState>) => ({ ...data, ...partialData }),
{
keys: null,
isOpen: "none",
dirName: "",
type: "",
slug: "",
}
);
const handleModelClose = () =>
setModalState({ keys: null, isOpen: "none", dirName: "", slug: "", type: "" });
const handleModelOpen = (data: EditModalState) => setModalState({ ...data });
if (isPending) return <SkeletonLoader />;
if (!apps || apps.length === 0) {
return (
<EmptyScreen
Icon="circle-alert"
headline={t("no_available_apps")}
description={t("no_available_apps_description")}
/>
);
}
return (
<>
<List>
{apps.map((app) => (
<IntegrationContainer
handleModelOpen={handleModelOpen}
app={app}
key={app.name}
category={category}
/>
))}
</List>
{modalState.isOpen === "editKeys" && (
<EditKeysModal
keys={modalState.keys}
dirName={modalState.dirName}
handleModelClose={handleModelClose}
isOpen={modalState.isOpen === "editKeys"}
slug={modalState.slug}
type={modalState.type}
fromEnabled={modalState.fromEnabled}
appName={modalState.appName}
/>
)}
</>
);
};
export default AdminAppsList;
const SkeletonLoader = () => {
return (
<SkeletonContainer className="w-120 pr-10">
<div className="mb-8 mt-6 stack-y-6">
<SkeletonText className="h-8 w-full" />
<SkeletonText className="h-8 w-full" />
<SkeletonText className="h-8 w-full" />
<SkeletonText className="h-8 w-full" />
<SkeletonButton className="mr-6 h-8 w-20 rounded-md p-5" />
</div>
</SkeletonContainer>
);
};
@@ -0,0 +1,199 @@
"use client";
import { useAutoAnimate } from "@formkit/auto-animate/react";
import type { UIEvent } from "react";
import { useEffect, useRef, useState } from "react";
import type { UserAdminTeams } from "@calcom/features/users/repositories/UserRepository";
import { useLocale } from "@calcom/lib/hooks/useLocale";
import type { AppCategories } from "@calcom/prisma/client";
import type { AppFrontendPayload as App } from "@calcom/types/App";
import type { CredentialFrontendPayload as Credential } from "@calcom/types/Credential";
import classNames from "@calcom/ui/classNames";
import { EmptyScreen } from "@calcom/ui/components/empty-screen";
import { Icon } from "@calcom/ui/components/icon";
import { AppCard } from "./AppCard";
export function useShouldShowArrows() {
const ref = useRef<HTMLUListElement>(null);
const [showArrowScroll, setShowArrowScroll] = useState({
left: false,
right: false,
});
useEffect(() => {
const appCategoryList = ref.current;
if (appCategoryList) {
const isAtStart = appCategoryList.scrollLeft <= 0;
const isAtEnd = appCategoryList.scrollWidth <= appCategoryList.clientWidth + appCategoryList.scrollLeft;
setShowArrowScroll({
left: !isAtStart,
right: !isAtEnd,
});
}
}, [ref.current?.scrollWidth, ref.current?.clientWidth]);
const calculateScroll = (e: UIEvent<HTMLUListElement>) => {
const target = e.currentTarget;
const isAtEnd = target.scrollWidth <= target.clientWidth + target.scrollLeft + 1;
setShowArrowScroll({
left: target.scrollLeft > 0,
right: !isAtEnd,
});
};
return { ref, calculateScroll, leftVisible: showArrowScroll.left, rightVisible: showArrowScroll.right };
}
type AllAppsPropsType = {
apps: (App & { credentials?: Credential[] })[];
searchText?: string;
categories: string[];
userAdminTeams?: UserAdminTeams;
};
interface CategoryTabProps {
selectedCategory: string | null;
categories: string[];
searchText?: string;
onCategoryChange: (category: string | null) => void;
}
function CategoryTab({ selectedCategory, categories, searchText, onCategoryChange }: CategoryTabProps) {
const { t } = useLocale();
const { ref, calculateScroll, leftVisible, rightVisible } = useShouldShowArrows();
const handleLeft = () => {
if (ref.current) {
ref.current.scrollLeft -= 100;
}
};
const handleRight = () => {
if (ref.current) {
ref.current.scrollLeft += 100;
}
};
return (
<div className="relative mb-4 flex flex-col justify-between lg:flex-row lg:items-center">
<h2 className="text-emphasis hidden text-base font-semibold leading-none sm:block">
{searchText
? t("search")
: t("category_apps", {
category:
(selectedCategory && selectedCategory[0].toUpperCase() + selectedCategory.slice(1)) ||
t("all"),
})}
</h2>
{leftVisible && (
<button onClick={handleLeft} className="absolute bottom-0 flex lg:left-1/2">
<div className="bg-default flex h-12 w-5 items-center justify-end">
<Icon name="chevron-left" className="text-subtle h-4 w-4" />
</div>
<div className="to-default flex h-12 w-5 bg-linear-to-l from-transparent" />
</button>
)}
<ul
className="no-scrollbar mt-3 flex max-w-full space-x-1 overflow-x-auto lg:mt-0 lg:max-w-[50%]"
onScroll={(e) => calculateScroll(e)}
ref={ref}>
<li
onClick={() => {
onCategoryChange(null);
}}
className={classNames(
selectedCategory === null ? "bg-emphasis text-default" : "bg-cal-muted text-emphasis",
"hover:bg-emphasis min-w-max rounded-md px-4 py-2.5 text-sm font-medium transition hover:cursor-pointer"
)}>
{t("all")}
</li>
{categories.map((cat, pos) => (
<li
key={pos}
onClick={() => {
if (selectedCategory === cat) {
onCategoryChange(null);
} else {
onCategoryChange(cat);
}
}}
className={classNames(
selectedCategory === cat ? "bg-emphasis text-default" : "bg-cal-muted text-emphasis",
"hover:bg-emphasis rounded-md px-4 py-2.5 text-sm font-medium transition hover:cursor-pointer"
)}>
{cat === "crm" ? cat.toUpperCase() : cat[0].toUpperCase() + cat.slice(1)}
</li>
))}
</ul>
{rightVisible && (
<button onClick={handleRight} className="absolute bottom-0 right-0 flex ">
<div className="to-default flex h-12 w-5 bg-linear-to-r from-transparent" />
<div className="bg-default flex h-12 w-5 items-center justify-end">
<Icon name="chevron-right" className="text-subtle h-4 w-4" />
</div>
</button>
)}
</div>
);
}
export function AllApps({ apps, searchText, categories, userAdminTeams }: AllAppsPropsType) {
const { t } = useLocale();
const [selectedCategory, setSelectedCategory] = useState<string | null>(null);
const [appsContainerRef, enableAnimation] = useAutoAnimate<HTMLDivElement>();
const handleCategoryChange = (category: string | null) => {
const validCategory =
category && typeof category === "string" && categories.includes(category) ? category : null;
setSelectedCategory(validCategory);
};
const filteredApps = apps
.filter((app) =>
selectedCategory !== null
? app.categories
? app.categories.includes(selectedCategory as AppCategories)
: app.category === selectedCategory
: true
)
.filter((app) => (searchText ? app.name.toLowerCase().includes(searchText.toLowerCase()) : true))
.sort(function (a, b) {
if (a.name < b.name) return -1;
else if (a.name > b.name) return 1;
return 0;
});
return (
<div>
<CategoryTab
selectedCategory={selectedCategory}
searchText={searchText}
categories={categories}
onCategoryChange={handleCategoryChange}
/>
{filteredApps.length ? (
<div
className="grid gap-3 lg:grid-cols-4 [@media(max-width:1270px)]:grid-cols-3 [@media(max-width:500px)]:grid-cols-1 [@media(max-width:730px)]:grid-cols-1"
ref={appsContainerRef}>
{filteredApps.map((app) => (
<AppCard
key={app.name}
app={app}
searchText={searchText}
credentials={app.credentials}
userAdminTeams={userAdminTeams}
/>
))}{" "}
</div>
) : (
<EmptyScreen
Icon="search"
headline={t("no_results")}
description={searchText ? searchText?.toString() : ""}
/>
)}
</div>
);
}
@@ -0,0 +1,292 @@
"use client";
import { useRouter } from "next/navigation";
import { useEffect, useState } from "react";
import posthog from "posthog-js";
import { InstallAppButton } from "@calcom/app-store/InstallAppButton";
import { isRedirectApp } from "@calcom/app-store/_utils/redirectApps";
import useAddAppMutation from "@calcom/app-store/_utils/useAddAppMutation";
import { doesAppSupportTeamInstall, isConferencing } from "@calcom/app-store/utils";
import type { UserAdminTeams } from "@calcom/features/users/repositories/UserRepository";
import { AppOnboardingSteps } from "@calcom/lib/apps/appOnboardingSteps";
import { getAppOnboardingUrl } from "@calcom/lib/apps/getAppOnboardingUrl";
import { WEBAPP_URL } from "@calcom/lib/constants";
import { useLocale } from "@calcom/lib/hooks/useLocale";
import { markdownToSafeHTML } from "@calcom/lib/markdownToSafeHTML";
import type { AppFrontendPayload as App } from "@calcom/types/App";
import type { CredentialFrontendPayload as Credential } from "@calcom/types/Credential";
import classNames from "@calcom/ui/classNames";
import { Badge } from "@calcom/ui/components/badge";
import { Button } from "@calcom/ui/components/button";
import type { ButtonProps } from "@calcom/ui/components/button";
import { showToast } from "@calcom/ui/components/toast";
interface AppCardProps {
app: App;
credentials?: Credential[];
searchText?: string;
userAdminTeams?: UserAdminTeams;
}
export function AppCard({ app, credentials, searchText, userAdminTeams }: AppCardProps) {
const { t } = useLocale();
const router = useRouter();
const allowedMultipleInstalls = app.categories && app.categories.indexOf("calendar") > -1;
const appAdded = (credentials && credentials.length) || 0;
const enabledOnTeams = doesAppSupportTeamInstall({
appCategories: app.categories,
concurrentMeetings: app.concurrentMeetings,
isPaid: !!app.paid,
});
const appInstalled = enabledOnTeams && userAdminTeams ? userAdminTeams.length < appAdded : appAdded > 0;
const mutation = useAddAppMutation(null, {
onSuccess: (data) => {
if (data?.setupPending) return;
showToast(t("app_successfully_installed"), "success");
},
onError: (error) => {
if (error instanceof Error) showToast(error.message || t("app_could_not_be_installed"), "error");
},
});
const [searchTextIndex, setSearchTextIndex] = useState<number | undefined>(undefined);
useEffect(() => {
setSearchTextIndex(searchText ? app.name.toLowerCase().indexOf(searchText.toLowerCase()) : undefined);
}, [app.name, searchText]);
const handleAppInstall = () => {
posthog.capture("app_install_button_clicked", {
slug: app.slug,
app_type: app.type,
is_redirect: isRedirectApp(app.slug),
is_conferencing: isConferencing(app.categories || []),
});
if (isRedirectApp(app.slug)) {
// For redirect apps, open the external URL directly
if (app.url) window.open(app.url, "_blank", "noopener,noreferrer");
return;
}
if (isConferencing(app.categories) && !app.concurrentMeetings) {
mutation.mutate({
type: app.type,
variant: app.variant,
slug: app.slug,
returnTo:
WEBAPP_URL +
getAppOnboardingUrl({
slug: app.slug,
step: AppOnboardingSteps.EVENT_TYPES_STEP,
}),
});
} else if (
!doesAppSupportTeamInstall({
appCategories: app.categories,
concurrentMeetings: app.concurrentMeetings,
isPaid: !!app.paid,
})
) {
mutation.mutate({ type: app.type });
} else {
router.push(getAppOnboardingUrl({ slug: app.slug, step: AppOnboardingSteps.ACCOUNTS_STEP }));
}
};
return (
<div className="border-subtle relative flex h-64 flex-col rounded-md border p-5">
<div className="flex">
<img
src={app.logo}
alt={`${app.name} Logo`}
className={classNames(
app.logo.includes("-dark") && "dark:invert",
"mb-4 h-12 w-12 rounded-sm" // TODO: Maybe find a better way to handle this @Hariom?
)}
/>
</div>
<div className="flex items-center">
<h3 className="text-emphasis font-medium">
{searchTextIndex != undefined && searchText ? (
<>
{app.name.substring(0, searchTextIndex)}
<span className="bg-yellow-300" data-testid="highlighted-text">
{app.name.substring(searchTextIndex, searchTextIndex + searchText.length)}
</span>
{app.name.substring(searchTextIndex + searchText.length)}
</>
) : (
app.name
)}
</h3>
</div>
{/* TODO: add reviews <div className="flex text-sm text-default">
<span>{props.rating} stars</span> <Icon name="star" className="ml-1 mt-0.5 h-4 w-4 text-yellow-600" />
<span className="pl-1 text-subtle">{props.reviews} reviews</span>
</div> */}
<p
className="text-default mt-2 grow text-sm"
dangerouslySetInnerHTML={{ __html: markdownToSafeHTML(app.description) }}
style={{
overflow: "hidden",
display: "-webkit-box",
WebkitBoxOrient: "vertical",
WebkitLineClamp: "3",
}}
/>
<div className="mt-5 flex max-w-full flex-row justify-between gap-2">
<Button
color="secondary"
className="flex w-32 grow justify-center"
href={`/apps/${app.slug}`}
onClick={() => { posthog.capture("app_card_details_clicked", { slug: app.slug }) }}
data-testid={`app-store-app-card-${app.slug}`}>
{t("details")}
</Button>
{app.isGlobal ||
(credentials && credentials.length > 0 && allowedMultipleInstalls) ||
(credentials && credentials.length > 0 && isRedirectApp(app.slug))
? !app.isGlobal && (
<InstallAppButton
type={app.type}
teamsPlanRequired={app.teamsPlanRequired}
disableInstall={!!app.dependencies && !app.dependencyData?.some((data) => !data.installed)}
wrapperClassName="[@media(max-width:260px)]:w-full"
render={({ useDefaultComponent, ...props }) => {
if (useDefaultComponent) {
props = {
...props,
onClick: () => {
handleAppInstall();
},
loading: mutation.isPending,
};
} else {
const originalOnClick = props.onClick;
props = {
...props,
onClick: (e) => {
posthog.capture("app_install_button_clicked", {
slug: app.slug,
app_type: app.type,
is_redirect: isRedirectApp(app.slug),
is_conferencing: isConferencing(app.categories || []),
});
originalOnClick?.(e);
},
};
}
return (
<InstallAppButtonChild paid={app.paid} isRedirect={isRedirectApp(app.slug)} {...props} />
);
}}
/>
)
: credentials &&
!appInstalled && (
<InstallAppButton
type={app.type}
wrapperClassName="[@media(max-width:260px)]:w-full"
disableInstall={!!app.dependencies && app.dependencyData?.some((data) => !data.installed)}
teamsPlanRequired={app.teamsPlanRequired}
render={({ useDefaultComponent, ...props }) => {
if (useDefaultComponent) {
props = {
...props,
disabled: !!props.disabled,
onClick: () => {
handleAppInstall();
},
loading: mutation.isPending,
};
} else {
const originalOnClick = props.onClick;
props = {
...props,
onClick: (e) => {
posthog.capture("app_install_button_clicked", {
slug: app.slug,
app_type: app.type,
is_redirect: isRedirectApp(app.slug),
is_conferencing: isConferencing(app.categories || []),
});
originalOnClick?.(e);
},
};
}
return (
<InstallAppButtonChild paid={app.paid} isRedirect={isRedirectApp(app.slug)} {...props} />
);
}}
/>
)}
</div>
<div className="max-w-44 absolute right-0 mr-4 flex flex-wrap justify-end gap-1">
{appAdded > 0 && !isRedirectApp(app.slug) ? (
<Badge variant="green">{t("installed", { count: appAdded })}</Badge>
) : null}
{app.isTemplate && (
<span className="bg-error rounded-md px-2 py-1 text-sm font-normal text-red-800">Template</span>
)}
{(app.isDefault || (!app.isDefault && app.isGlobal)) && (
<span className="bg-subtle text-emphasis flex items-center rounded-md px-2 py-1 text-sm font-normal">
{t("default")}
</span>
)}
</div>
</div>
);
}
const InstallAppButtonChild = ({
paid,
isRedirect = false,
...props
}: {
paid: App["paid"];
isRedirect?: boolean;
} & ButtonProps) => {
const { t } = useLocale();
if (isRedirect) {
return (
<Button
color="secondary"
className="[@media(max-width:260px)]:w-full [@media(max-width:260px)]:justify-center"
StartIcon="external-link"
{...props}
size="base">
{t("visit")}
</Button>
);
}
// Paid apps don't support team installs at the moment
// Also, cal.ai(the only paid app at the moment) doesn't support team install either
if (paid) {
return (
<Button
color="secondary"
className="[@media(max-width:260px)]:w-full [@media(max-width:260px)]:justify-center"
StartIcon="plus"
data-testid="install-app-button"
{...props}>
{paid.trial ? t("start_paid_trial") : t("subscribe")}
</Button>
);
}
return (
<Button
color="secondary"
className="[@media(max-width:260px)]:w-full [@media(max-width:260px)]:justify-center"
StartIcon="plus"
data-testid="install-app-button"
{...props}
size="base">
{t("install")}
</Button>
);
};
@@ -0,0 +1,254 @@
import { useCallback, useState } from "react";
import { InstallAppButton } from "@calcom/app-store/InstallAppButton";
import { AppSettings } from "@calcom/app-store/_components/AppSettings";
import { getLocationFromApp, type EventLocationType } from "@calcom/app-store/locations";
import type { AppCardApp } from "@calcom/app-store/types";
import AppListCard from "@calcom/web/modules/apps/components/AppListCard";
import type { UpdateUsersDefaultConferencingAppParams } from "@calcom/web/modules/apps/components/AppSetDefaultLinkDialog";
import { AppSetDefaultLinkDialog } from "@calcom/web/modules/apps/components/AppSetDefaultLinkDialog";
import type {
BulkUpdatParams,
EventTypes,
} from "@calcom/web/modules/event-types/components/BulkEditDefaultForEventsModal";
import { BulkEditDefaultForEventsModal } from "@calcom/web/modules/event-types/components/BulkEditDefaultForEventsModal";
import { isDelegationCredential } from "@calcom/lib/delegationCredential";
import { useLocale } from "@calcom/lib/hooks/useLocale";
import type { AppCategories } from "@calcom/prisma/enums";
import { type RouterOutputs } from "@calcom/trpc/react";
import type { App } from "@calcom/types/App";
import { Alert } from "@calcom/ui/components/alert";
import { Button } from "@calcom/ui/components/button";
import {
Dropdown,
DropdownItem,
DropdownMenuContent,
DropdownMenuItem,
DropdownMenuTrigger,
} from "@calcom/ui/components/dropdown";
import { List } from "@calcom/ui/components/list";
import { showToast } from "@calcom/ui/components/toast";
export type HandleDisconnect = (credentialId: number, app: App["slug"], teamId?: number) => void;
interface AppListProps {
variant?: AppCategories;
data: RouterOutputs["viewer"]["apps"]["integrations"];
handleDisconnect: HandleDisconnect;
listClassName?: string;
defaultConferencingApp: RouterOutputs["viewer"]["apps"]["getUsersDefaultConferencingApp"];
handleUpdateUserDefaultConferencingApp: (params: UpdateUsersDefaultConferencingAppParams) => void;
handleBulkUpdateDefaultLocation: (params: BulkUpdatParams) => void;
isBulkUpdateDefaultLocationPending: boolean;
eventTypes?: EventTypes;
isEventTypesFetching?: boolean;
handleConnectDisconnectIntegrationMenuToggle: () => void;
handleBulkEditDialogToggle: () => void;
}
export const AppList = ({
data,
handleDisconnect,
variant,
listClassName,
defaultConferencingApp,
handleUpdateUserDefaultConferencingApp,
handleBulkUpdateDefaultLocation,
isBulkUpdateDefaultLocationPending,
eventTypes,
isEventTypesFetching,
handleConnectDisconnectIntegrationMenuToggle,
handleBulkEditDialogToggle,
}: AppListProps) => {
const [bulkUpdateModal, setBulkUpdateModal] = useState(false);
const [locationType, setLocationType] = useState<(EventLocationType & { slug: string }) | undefined>(
undefined
);
const onSuccessCallback = useCallback(() => {
setBulkUpdateModal(true);
showToast("Default app updated successfully", "success");
}, []);
const ChildAppCard = ({ item }: { item: AppCardApp }) => {
const appSlug = item?.slug;
const appIsDefault =
appSlug === defaultConferencingApp?.appSlug ||
(appSlug === "daily-video" && !defaultConferencingApp?.appSlug);
return (
<AppListCard
key={item.name}
description={item.description}
title={item.name}
logo={item.logo}
isDefault={appIsDefault}
shouldHighlight
slug={item.slug}
invalidCredential={item?.invalidCredentialIds ? item.invalidCredentialIds.length > 0 : false}
credentialOwner={item?.credentialOwner}
actions={
!item.credentialOwner?.readOnly ? (
<div className="flex justify-end">
<Dropdown modal={false}>
<DropdownMenuTrigger asChild>
<Button StartIcon="ellipsis" variant="icon" color="secondary" />
</DropdownMenuTrigger>
<DropdownMenuContent>
{!appIsDefault && variant === "conferencing" && (
<DropdownMenuItem>
<DropdownItem
type="button"
color="secondary"
StartIcon="video"
onClick={() => {
const locationType = getLocationFromApp(item?.locationOption?.value ?? "");
if (locationType?.linkType === "static") {
setLocationType({ ...locationType, slug: appSlug });
} else {
handleUpdateUserDefaultConferencingApp({
appSlug,
onSuccessCallback: () => setBulkUpdateModal(true),
onErrorCallback: () => {
return;
},
});
}
}}>
{t("set_as_default")}
</DropdownItem>
</DropdownMenuItem>
)}
<ConnectOrDisconnectIntegrationMenuItem
credentialId={item.credentialOwner?.credentialId || item.userCredentialIds[0]}
type={item.type}
app={item.slug}
isGlobal={item.isGlobal}
installed
invalidCredentialIds={item.invalidCredentialIds}
handleDisconnect={handleDisconnect}
teamId={item.credentialOwner ? item.credentialOwner?.teamId : undefined}
handleConnectDisconnectIntegrationMenuToggle={
handleConnectDisconnectIntegrationMenuToggle
}
/>
</DropdownMenuContent>
</Dropdown>
</div>
) : null
}>
<AppSettings slug={item.slug} />
</AppListCard>
);
};
const appsWithTeamCredentials = data.items.filter((app) => app.teams.length);
const cardsForAppsWithTeams = appsWithTeamCredentials.map((app) => {
const appCards = [];
if (app.userCredentialIds.length) {
appCards.push(<ChildAppCard item={app} />);
}
for (const team of app.teams) {
if (team) {
appCards.push(
<ChildAppCard
item={{
...app,
credentialOwner: {
name: team.name,
avatar: team.logoUrl,
teamId: team.teamId,
credentialId: team.credentialId,
readOnly: !team.isAdmin,
},
}}
/>
);
}
}
return appCards;
});
const { t } = useLocale();
return (
<>
<List className={listClassName}>
{cardsForAppsWithTeams.map((apps) => apps.map((cards) => cards))}
{data.items
.filter((item) => item.invalidCredentialIds)
.map((item, i) => {
if (!item.teams.length) return <ChildAppCard key={i} item={item} />;
})}
</List>
{locationType && (
<AppSetDefaultLinkDialog
locationType={locationType}
setLocationType={() => setLocationType(undefined)}
onSuccess={onSuccessCallback}
handleUpdateUserDefaultConferencingApp={handleUpdateUserDefaultConferencingApp}
/>
)}
{bulkUpdateModal && (
<BulkEditDefaultForEventsModal
bulkUpdateFunction={handleBulkUpdateDefaultLocation}
open={bulkUpdateModal}
setOpen={setBulkUpdateModal}
isPending={isBulkUpdateDefaultLocationPending}
description={t("default_conferencing_bulk_description")}
eventTypes={eventTypes}
isEventTypesFetching={isEventTypesFetching}
handleBulkEditDialogToggle={handleBulkEditDialogToggle}
/>
)}
</>
);
};
function ConnectOrDisconnectIntegrationMenuItem(props: {
credentialId: number;
type: App["type"];
isGlobal?: boolean;
installed?: boolean;
invalidCredentialIds?: number[];
teamId?: number;
app: App["slug"];
handleDisconnect: HandleDisconnect;
handleConnectDisconnectIntegrationMenuToggle: () => void;
}) {
const { type, credentialId, isGlobal, installed, handleDisconnect, teamId, app } = props;
const { t } = useLocale();
if (credentialId || type === "stripe_payment" || isGlobal) {
return (
<DropdownMenuItem>
<DropdownItem
color="destructive"
onClick={() => handleDisconnect(credentialId, app, teamId)}
disabled={isGlobal || isDelegationCredential({ credentialId })}
StartIcon="trash">
{t("remove_app")}
</DropdownItem>
</DropdownMenuItem>
);
}
if (!installed) {
return (
<div className="flex items-center truncate">
<Alert severity="warning" title={t("not_installed")} />
</div>
);
}
return (
<InstallAppButton
type={type}
render={(buttonProps) => (
<Button color="secondary" {...buttonProps} data-testid="integration-connection-button">
{t("install")}
</Button>
)}
onChanged={props.handleConnectDisconnectIntegrationMenuToggle}
/>
);
}
@@ -0,0 +1,25 @@
"use client";
import dynamic from "next/dynamic";
import { useMemo } from "react";
import { useIsPlatform } from "@calcom/atoms/hooks/useIsPlatform";
import type { AppListCardProps } from "@calcom/ui/components/app-list-card";
export default function AppListCard(props: AppListCardProps) {
const isPlatform = useIsPlatform();
// Dynamically import the correct wrapper
const AppListCardWrapper = useMemo(
() =>
dynamic(
() => (isPlatform ? import("./AppListCardPlatformWrapper") : import("./AppListCardWebWrapper")),
{
ssr: false, // Prevents SSR issues if needed
}
),
[isPlatform]
);
return <AppListCardWrapper {...props} />;
}
@@ -0,0 +1,7 @@
import { AppListCard } from "@calcom/ui/components/app-list-card";
import type { AppListCardProps } from "@calcom/ui/components/app-list-card";
export default function AppListCardPlatformWrapper(props: AppListCardProps) {
const logo = `https://app.cal.com${props.logo}`;
return <AppListCard {...props} logo={logo} />;
}
@@ -0,0 +1,48 @@
"use client";
import { usePathname, useRouter } from "next/navigation";
import { useEffect, useRef, useState } from "react";
import { z } from "zod";
import { useCompatSearchParams } from "@calcom/lib/hooks/useCompatSearchParams";
import { useTypedQuery } from "@calcom/lib/hooks/useTypedQuery";
import { AppListCard } from "@calcom/ui/components/app-list-card";
import type { AppListCardProps } from "@calcom/ui/components/app-list-card";
const schema = z.object({ hl: z.string().optional() });
export default function AppListCardWebWrapper(props: AppListCardProps) {
const { slug, shouldHighlight } = props;
const {
data: { hl },
} = useTypedQuery(schema);
const router = useRouter();
const [highlight, setHighlight] = useState(shouldHighlight && hl === slug);
const timeoutRef = useRef<NodeJS.Timeout | null>(null);
const searchParams = useCompatSearchParams();
const pathname = usePathname();
useEffect(() => {
if (shouldHighlight && highlight && searchParams !== null && pathname !== null) {
timeoutRef.current = setTimeout(() => {
const _searchParams = new URLSearchParams(searchParams.toString());
_searchParams.delete("hl");
_searchParams.delete("category"); // this comes from params, not from search params
setHighlight(false);
const stringifiedSearchParams = _searchParams.toString();
router.replace(`${pathname}${stringifiedSearchParams !== "" ? `?${stringifiedSearchParams}` : ""}`);
}, 3000);
}
return () => {
if (timeoutRef.current) {
clearTimeout(timeoutRef.current);
timeoutRef.current = null;
}
};
}, [highlight, pathname, router, searchParams, shouldHighlight]);
return <AppListCard {...props} />;
}
@@ -0,0 +1,90 @@
import { zodResolver } from "@hookform/resolvers/zod";
import type { Dispatch, SetStateAction } from "react";
import { useForm } from "react-hook-form";
import { z } from "zod";
import type { EventLocationType } from "@calcom/app-store/locations";
import { getEventLocationType } from "@calcom/app-store/locations";
import { Dialog } from "@calcom/features/components/controlled-dialog";
import { useLocale } from "@calcom/lib/hooks/useLocale";
import { Button } from "@calcom/ui/components/button";
import { DialogContent, DialogFooter, DialogClose } from "@calcom/ui/components/dialog";
import { Form } from "@calcom/ui/components/form";
import { TextField } from "@calcom/ui/components/form";
import { showToast } from "@calcom/ui/components/toast";
export type UpdateUsersDefaultConferencingAppParams = {
appSlug: string;
appLink?: string;
onSuccessCallback: () => void;
onErrorCallback: () => void;
};
type LocationTypeSetLinkDialogFormProps = {
link?: string;
type: EventLocationType["type"];
};
export function AppSetDefaultLinkDialog({
locationType,
setLocationType,
onSuccess,
handleUpdateUserDefaultConferencingApp,
}: {
locationType: EventLocationType & { slug: string };
setLocationType: Dispatch<SetStateAction<(EventLocationType & { slug: string }) | undefined>>;
onSuccess: () => void;
handleUpdateUserDefaultConferencingApp: (params: UpdateUsersDefaultConferencingAppParams) => void;
}) {
const { t } = useLocale();
const eventLocationTypeOptions = getEventLocationType(locationType.type);
const form = useForm<LocationTypeSetLinkDialogFormProps>({
resolver: zodResolver(
z.object({ link: z.string().regex(new RegExp(eventLocationTypeOptions?.urlRegExp ?? "")) })
),
});
return (
<Dialog open={!!locationType} onOpenChange={() => setLocationType(undefined)}>
<DialogContent
title={t("default_app_link_title")}
description={t("default_app_link_description")}
type="creation"
Icon="circle-alert">
<Form
form={form}
handleSubmit={(values) => {
handleUpdateUserDefaultConferencingApp({
appSlug: locationType.slug,
appLink: values.link,
onSuccessCallback: () => {
onSuccess();
},
onErrorCallback: () => {
showToast(`Invalid App Link Format`, "error");
},
});
setLocationType(undefined);
}}>
<>
<TextField
type="text"
required
{...form.register("link")}
placeholder={locationType.organizerInputPlaceholder ?? ""}
label={locationType.label ?? ""}
/>
<DialogFooter showDivider className="mt-8">
<DialogClose />
<Button color="primary" type="submit">
{t("save")}
</Button>
</DialogFooter>
</>
</Form>
</DialogContent>
</Dialog>
);
}
@@ -0,0 +1,63 @@
import Image from "next/image";
import Link from "next/link";
import { useLocale } from "@calcom/lib/hooks/useLocale";
import { Icon } from "@calcom/ui/components/icon";
import { SkeletonText } from "@calcom/ui/components/skeleton";
import { Slider } from "./Slider";
export function AppStoreCategories({
categories,
}: {
categories: {
name: string;
count: number;
}[];
}) {
const { t, isLocaleReady } = useLocale();
return (
<div>
<Slider
title={t("featured_categories")}
items={categories}
itemKey={(category) => category.name}
options={{
perView: 5,
breakpoints: {
768 /* and below */: {
perView: 2,
},
},
}}
renderItem={(category) => (
<Link
key={category.name}
href={`/apps/categories/${category.name}`}
data-testid={`app-store-category-${category.name}`}
className="relative flex rounded-md"
style={{ background: "radial-gradient(farthest-side at top right, #a2abbe 0%, #E3E3E3 100%)" }}>
<div className="dark:bg-cal-muted light:bg-[url('/noise.svg')] dark:from-subtle dark:to-muted w-full self-center bg-cover bg-center bg-no-repeat px-6 py-4 dark:bg-linear-to-tr">
<Image
src={`/app-categories/${category.name}.svg`}
width={100}
height={100}
alt={category.name}
className="dark:invert"
/>
{isLocaleReady ? (
<h3 className="text-emphasis text-sm font-semibold capitalize">{category.name}</h3>
) : (
<SkeletonText invisible />
)}
<p className="text-subtle pt-2 text-sm font-medium">
{isLocaleReady ? t("number_apps", { count: category.count }) : <SkeletonText invisible />}{" "}
<Icon name="arrow-right" className="inline-block h-4 w-4" />
</p>
</div>
</Link>
)}
/>
</div>
);
}
@@ -0,0 +1,95 @@
"use client";
import { useState } from "react";
import { useLocale } from "@calcom/lib/hooks/useLocale";
import { trpc } from "@calcom/trpc/react";
import { Button } from "@calcom/ui/components/button";
import { ConfirmationDialogContent } from "@calcom/ui/components/dialog";
import { Dialog } from "@calcom/ui/components/dialog";
import {
Dropdown,
DropdownItem,
DropdownMenuContent,
DropdownMenuItem,
DropdownMenuTrigger,
} from "@calcom/ui/components/dropdown";
import { showToast } from "@calcom/ui/components/toast";
interface CredentialActionsDropdownProps {
credentialId: number;
onSuccess?: () => void;
delegationCredentialId?: string | null;
disableConnectionModification?: boolean;
}
export default function CredentialActionsDropdown({
credentialId,
onSuccess,
delegationCredentialId,
disableConnectionModification,
}: CredentialActionsDropdownProps) {
const { t } = useLocale();
const [dropdownOpen, setDropdownOpen] = useState(false);
const [disconnectModalOpen, setDisconnectModalOpen] = useState(false);
const utils = trpc.useUtils();
const disconnectMutation = trpc.viewer.credentials.delete.useMutation({
onSuccess: () => {
showToast(t("app_removed_successfully"), "success");
onSuccess?.();
},
onError: () => {
showToast(t("error_removing_app"), "error");
},
async onSettled() {
await utils.viewer.calendars.connectedCalendars.invalidate();
await utils.viewer.apps.integrations.invalidate();
},
});
const canDisconnect = !delegationCredentialId && !disableConnectionModification;
if (!canDisconnect) {
return null;
}
return (
<>
<Dropdown open={dropdownOpen} onOpenChange={setDropdownOpen}>
<DropdownMenuTrigger asChild>
<Button type="button" variant="icon" color="secondary" StartIcon="ellipsis" />
</DropdownMenuTrigger>
<DropdownMenuContent>
{canDisconnect && (
<DropdownMenuItem className="outline-none">
<DropdownItem
type="button"
color="destructive"
StartIcon="trash"
onClick={() => {
setDisconnectModalOpen(true);
setDropdownOpen(false);
}}>
{t("remove_app")}
</DropdownItem>
</DropdownMenuItem>
)}
</DropdownMenuContent>
</Dropdown>
<Dialog open={disconnectModalOpen} onOpenChange={setDisconnectModalOpen}>
<ConfirmationDialogContent
variety="danger"
title={t("remove_app")}
confirmBtnText={t("yes_remove_app")}
onConfirm={() => {
disconnectMutation.mutate({ id: credentialId });
setDisconnectModalOpen(false);
}}>
{t("are_you_sure_you_want_to_remove_this_app")}
</ConfirmationDialogContent>
</Dialog>
</>
);
}
@@ -0,0 +1,53 @@
"use client";
import { useState } from "react";
import { isDelegationCredential } from "@calcom/lib/delegationCredential";
import { useLocale } from "@calcom/lib/hooks/useLocale";
import { trpc } from "@calcom/trpc/react";
import type { ButtonProps } from "@calcom/ui/components/button";
import { DisconnectIntegrationComponent } from "@calcom/ui/components/disconnect-calendar-integration";
import { showToast } from "@calcom/ui/components/toast";
export default function DisconnectIntegration(props: {
credentialId: number;
teamId?: number | null;
label?: string;
trashIcon?: boolean;
isGlobal?: boolean;
onSuccess?: () => void;
buttonProps?: ButtonProps;
}) {
const { t } = useLocale();
const { onSuccess, credentialId, teamId } = props;
const [modalOpen, setModalOpen] = useState(false);
const utils = trpc.useUtils();
const mutation = trpc.viewer.credentials.delete.useMutation({
onSuccess: () => {
showToast(t("app_removed_successfully"), "success");
setModalOpen(false);
onSuccess && onSuccess();
},
onError: () => {
showToast(t("error_removing_app"), "error");
setModalOpen(false);
},
async onSettled() {
await utils.viewer.calendars.connectedCalendars.invalidate();
await utils.viewer.apps.integrations.invalidate();
},
});
// Such a credential is added in-memory and removed when Delegation credential is disabled.
const disableDisconnect = isDelegationCredential({ credentialId });
return (
<DisconnectIntegrationComponent
onDeletionConfirmation={() => mutation.mutate({ id: credentialId, ...(teamId ? { teamId } : {}) })}
isModalOpen={modalOpen}
onModalOpen={() => setModalOpen((prevValue) => !prevValue)}
disabled={disableDisconnect}
{...props}
/>
);
}
@@ -0,0 +1,49 @@
import { useIsPlatform } from "@calcom/atoms/hooks/useIsPlatform";
import { Dialog } from "@calcom/features/components/controlled-dialog";
import { useLocale } from "@calcom/lib/hooks/useLocale";
import type { App } from "@calcom/types/App";
import { ConfirmationDialogContent } from "@calcom/ui/components/dialog";
export type RemoveAppParams = {
credentialId: number;
app?: App["slug"];
teamId?: number;
callback: () => void;
};
interface DisconnectIntegrationModalProps {
credentialId: number | null;
isOpen: boolean;
handleModelClose: () => void;
teamId?: number;
handleRemoveApp: (params: RemoveAppParams) => void;
app?: App["slug"] | null;
}
export default function DisconnectIntegrationModal({
credentialId,
app,
isOpen,
handleModelClose,
teamId,
handleRemoveApp,
}: DisconnectIntegrationModalProps) {
const { t } = useLocale();
const isPlatform = useIsPlatform();
return (
<Dialog open={isOpen} onOpenChange={handleModelClose}>
<ConfirmationDialogContent
variety="danger"
title={t("remove_app")}
confirmBtnText={t("yes_remove_app")}
onConfirm={() => {
if (isPlatform && app && credentialId) {
handleRemoveApp({ credentialId, app, teamId, callback: () => handleModelClose() });
} else if (credentialId) {
handleRemoveApp({ credentialId, teamId, callback: () => handleModelClose() });
}
}}>
<p className="mt-5">{t("are_you_sure_you_want_to_remove_this_app")}</p>
</ConfirmationDialogContent>
</Dialog>
);
}
@@ -0,0 +1,26 @@
import { useLocale } from "@calcom/lib/hooks/useLocale";
import type { AppFrontendPayload as App } from "@calcom/types/App";
import { AppCard } from "./AppCard";
import { Slider } from "./Slider";
export const PopularAppsSlider = <T extends App>({ items }: { items: T[] }) => {
const { t } = useLocale();
return (
<Slider<T>
title={t("most_popular")}
items={items.sort((a, b) => (b.installCount || 0) - (a.installCount || 0))}
itemKey={(app) => app.name}
options={{
perView: 3,
breakpoints: {
768 /* and below */: {
perView: 1,
},
},
}}
renderItem={(app) => <AppCard app={app} />}
/>
);
};
@@ -0,0 +1,28 @@
import { useLocale } from "@calcom/lib/hooks/useLocale";
import type { AppFrontendPayload as App } from "@calcom/types/App";
import { AppCard } from "./AppCard";
import { Slider } from "./Slider";
export const RecentAppsSlider = <T extends App>({ items }: { items: T[] }) => {
const { t } = useLocale();
return (
<Slider<T>
title={t("recently_added")}
items={items.sort(
(a, b) => new Date(b?.createdAt || 0).valueOf() - new Date(a?.createdAt || 0).valueOf()
)}
itemKey={(app) => app.name}
options={{
perView: 3,
breakpoints: {
768 /* and below */: {
perView: 1,
},
},
}}
renderItem={(app) => <AppCard app={app} />}
/>
);
};
@@ -0,0 +1,40 @@
import { ShellSubHeading } from "@calcom/ui/components/layout";
import { SkeletonText } from "@calcom/ui/components/skeleton";
export function SkeletonLoader({ className }: { className?: string }) {
return (
<>
<ShellSubHeading title={<div className="bg-subtle h-6 w-32" />} {...{ className }} />
<ul className="bg-default border-subtle divide-subtle -mx-4 animate-pulse divide-y rounded-md border sm:mx-0 sm:overflow-hidden">
<SkeletonItem />
<SkeletonItem />
<SkeletonItem />
</ul>
</>
);
}
function SkeletonItem() {
return (
<li className="group flex w-full items-center justify-between p-3">
<div className="grow truncate text-sm">
<div className="flex justify-start space-x-2 rtl:space-x-reverse">
<SkeletonText className="h-10 w-10" />
<div className="stack-y-1">
<div>
<SkeletonText className="h-4 w-16" />
</div>
<div>
<SkeletonText className="h-4 w-32" />
</div>
</div>
</div>
</div>
<div className="mt-4 hidden shrink-0 sm:ml-5 sm:mt-0 lg:flex">
<div className="flex justify-between space-x-2 rtl:space-x-reverse">
<SkeletonText className="h-11 w-32" />
</div>
</div>
</li>
);
}
@@ -0,0 +1,89 @@
"use client";
import type { Options } from "@glidejs/glide";
import Glide from "@glidejs/glide";
import "@glidejs/glide/dist/css/glide.core.min.css";
import "@glidejs/glide/dist/css/glide.theme.min.css";
import type { ComponentProps, FC } from "react";
import { useEffect, useRef } from "react";
import { useLocale } from "@calcom/lib/hooks/useLocale";
import { Icon } from "@calcom/ui/components/icon";
import { SkeletonText } from "@calcom/ui/components/skeleton";
const SliderButton: FC<ComponentProps<"button">> = (props) => {
const { children, ...rest } = props;
return (
<button className="hover:bg-subtle text-default rounded p-2.5 transition" {...rest}>
{children}
</button>
);
};
export const Slider = <T extends string | unknown>({
title = "",
className = "",
items,
itemKey = (item) => `${item}`,
renderItem,
options = {},
}: {
title?: string;
className?: string;
items: T[];
itemKey?: (item: T) => string;
renderItem?: (item: T) => JSX.Element;
options?: Options;
}) => {
const glide = useRef(null);
const slider = useRef<Glide.Properties | null>(null);
const { isLocaleReady } = useLocale();
useEffect(() => {
if (glide.current) {
slider.current = new Glide(glide.current, {
type: "carousel",
...options,
}).mount();
}
return () => slider.current?.destroy();
}, [options]);
return (
<div className={`mb-2 ${className}`}>
<div className="glide" ref={glide}>
<div className="flex cursor-default items-center pb-3">
{isLocaleReady ? (
title && (
<div>
<h2 className="text-emphasis mt-0 text-base font-semibold leading-none">{title}</h2>
</div>
)
) : (
<SkeletonText className="h-4 w-24" />
)}
<div className="glide__arrows ml-auto flex items-center gap-x-1" data-glide-el="controls">
<SliderButton data-glide-dir="<">
<Icon name="arrow-left" className="h-5 w-5" />
</SliderButton>
<SliderButton data-glide-dir=">">
<Icon name="arrow-right" className="h-5 w-5" />
</SliderButton>
</div>
</div>
<div className="glide__track" data-glide-el="track">
<ul className="glide__slides">
{items.map((item) => {
if (typeof renderItem !== "function") return null;
return (
<li key={itemKey(item)} className="glide__slide h-auto pl-0">
{renderItem(item)}
</li>
);
})}
</ul>
</div>
</div>
</div>
);
};
@@ -0,0 +1,54 @@
import type { AppFrontendPayload as App } from "@calcom/types/App";
export const _SBApps: App[] = [
{
name: "Google Calendar",
description: "Google Calendar",
installed: true,
type: "google_calendar",
title: "Google Calendar",
variant: "calendar",
category: "calendar",
categories: ["calendar"],
logo: "/api/app-store/googlecalendar/icon.svg",
publisher: "Cal.com",
slug: "google-calendar",
url: "https://cal.com/",
email: "[email protected]",
dirName: "googlecalendar",
},
{
name: "Zoom Video",
description: "Zoom Video",
type: "zoom_video",
categories: ["video"],
variant: "conferencing",
logo: "/api/app-store/zoomvideo/icon.svg",
publisher: "Cal.com",
url: "https://zoom.us/",
category: "video",
slug: "zoom",
title: "Zoom Video",
email: "[email protected]",
appData: {
location: {
default: false,
linkType: "dynamic",
type: "integrations:zoom",
label: "Zoom Video",
},
},
dirName: "zoomvideo",
},
];
export const _SBAppCategoryList = [
{
name: "Calendar",
count: 1,
},
{
name: "Video",
count: 5,
},
];
@@ -0,0 +1,81 @@
/* eslint-disable playwright/missing-playwright-await */
import { QueryClient, QueryClientProvider } from "@tanstack/react-query";
import { render, screen } from "@testing-library/react";
import { vi, describe, expect } from "vitest";
import type { AppFrontendPayload } from "@calcom/types/App";
import { AppCard } from "./AppCard";
vi.mock("next/navigation", () => ({
useRouter: vi.fn().mockReturnValue({
push: vi.fn(),
}),
usePathname: vi.fn(),
}));
describe("Tests for AppCard component", () => {
const mockApp: AppFrontendPayload = {
logo: "/path/to/logo.png",
name: "Test App",
slug: "test-app",
description: "Test description for the app.",
categories: ["calendar"],
concurrentMeetings: true,
teamsPlanRequired: { upgradeUrl: "test" },
type: "test_calendar",
variant: "calendar",
publisher: "test",
url: "test",
email: "test",
};
// Abstracted render function
const renderAppCard = (appProps = {}, appCardProps = {}) => {
const appData = { ...mockApp, ...appProps };
const queryClient = new QueryClient();
render(
<QueryClientProvider client={queryClient}>
<AppCard app={appData} {...appCardProps} />;
</QueryClientProvider>
);
};
describe("Tests for app description", () => {
it("Should render the app name correctly and display app logo with correct alt text", () => {
renderAppCard();
const appLogo = screen.getByAltText("Test App Logo");
const appName = screen.getByText("Test App");
expect(appLogo).toBeInTheDocument();
expect(appLogo.getAttribute("src")).toBe("/path/to/logo.png");
expect(appName).toBeInTheDocument();
});
it("Should render details button with correct href", () => {
renderAppCard();
const detailsButton = screen.getByText("details");
expect(detailsButton).toBeInTheDocument();
expect(detailsButton.closest("a")).toHaveAttribute("href", "/apps/test-app");
});
it("Should highlight the app name based on searchText", () => {
renderAppCard({}, { searchText: "test" });
const highlightedText = screen.getByTestId("highlighted-text");
expect(highlightedText).toBeInTheDocument();
});
});
describe("Tests for app categories", () => {
it("Should show 'Template' badge if app is a template", () => {
renderAppCard({ isTemplate: true });
const templateBadge = screen.getByText("Template");
expect(templateBadge).toBeInTheDocument();
});
it("Should show 'default' badge if app is default or global", () => {
renderAppCard({ isDefault: true });
const defaultBadge = screen.getByText("default");
expect(defaultBadge).toBeInTheDocument();
});
});
});
@@ -0,0 +1,7 @@
export { useShouldShowArrows, AllApps } from "./AllApps";
export { AppCard } from "./AppCard";
export { Slider } from "./Slider";
export { SkeletonLoader } from "./SkeletonLoader";
export { PopularAppsSlider } from "./PopularAppsSlider";
export { RecentAppsSlider } from "./RecentAppsSlider";
export { AppStoreCategories } from "./Categories";
@@ -3,12 +3,12 @@
import { useReducer } from "react";
import getAppCategoryTitle from "@calcom/app-store/_utils/getAppCategoryTitle";
import { AppList, type HandleDisconnect } from "@calcom/features/apps/components/AppList";
import type { UpdateUsersDefaultConferencingAppParams } from "@calcom/features/apps/components/AppSetDefaultLinkDialog";
import DisconnectIntegrationModal from "@calcom/features/apps/components/DisconnectIntegrationModal";
import type { RemoveAppParams } from "@calcom/features/apps/components/DisconnectIntegrationModal";
import { SkeletonLoader } from "@calcom/features/apps/components/SkeletonLoader";
import type { BulkUpdatParams } from "@calcom/features/eventtypes/components/BulkEditDefaultForEventsModal";
import { AppList, type HandleDisconnect } from "@calcom/web/modules/apps/components/AppList";
import type { UpdateUsersDefaultConferencingAppParams } from "@calcom/web/modules/apps/components/AppSetDefaultLinkDialog";
import DisconnectIntegrationModal from "@calcom/web/modules/apps/components/DisconnectIntegrationModal";
import type { RemoveAppParams } from "@calcom/web/modules/apps/components/DisconnectIntegrationModal";
import { SkeletonLoader } from "@calcom/web/modules/apps/components/SkeletonLoader";
import type { BulkUpdatParams } from "@calcom/web/modules/event-types/components/BulkEditDefaultForEventsModal";
import { useLocale } from "@calcom/lib/hooks/useLocale";
import { AppCategories } from "@calcom/prisma/enums";
import { trpc } from "@calcom/trpc/react";
+1 -1
View File
@@ -3,7 +3,7 @@
import { useRouter } from "next/navigation";
import { useMemo, useState } from "react";
import AdminAppsList from "@calcom/features/apps/AdminAppsList";
import AdminAppsList from "~/apps/components/AdminAppsList";
import { APP_NAME } from "@calcom/lib/constants";
import { useLocale } from "@calcom/lib/hooks/useLocale";
import type { inferSSRProps } from "@calcom/types/inferSSRProps";
@@ -6,7 +6,7 @@ import { useRouter, useSearchParams } from "next/navigation";
import { useState } from "react";
import { AvailabilitySettings } from "@calcom/atoms/availability/AvailabilitySettings";
import type { BulkUpdatParams } from "@calcom/features/eventtypes/components/BulkEditDefaultForEventsModal";
import type { BulkUpdatParams } from "@calcom/web/modules/event-types/components/BulkEditDefaultForEventsModal";
import { withErrorFromUnknown } from "@calcom/lib/getClientErrorFromUnknown";
import { useLocale } from "@calcom/lib/hooks/useLocale";
import { HttpError } from "@calcom/lib/http-error";
@@ -7,8 +7,8 @@ import { useRouter, usePathname } from "next/navigation";
import { useCallback, useState } from "react";
import posthog from "posthog-js";
import { BulkEditDefaultForEventsModal } from "@calcom/features/eventtypes/components/BulkEditDefaultForEventsModal";
import type { BulkUpdatParams } from "@calcom/features/eventtypes/components/BulkEditDefaultForEventsModal";
import { BulkEditDefaultForEventsModal } from "@calcom/web/modules/event-types/components/BulkEditDefaultForEventsModal";
import type { BulkUpdatParams } from "@calcom/web/modules/event-types/components/BulkEditDefaultForEventsModal";
import { NewScheduleButton } from "@calcom/features/schedules/components/NewScheduleButton";
import { ScheduleListItem } from "@calcom/features/schedules/components/ScheduleListItem";
import { useCompatSearchParams } from "@calcom/lib/hooks/useCompatSearchParams";
@@ -0,0 +1,252 @@
import { useCallback, useMemo, useRef } from "react";
import dayjs from "@calcom/dayjs";
import { AvailableTimes, AvailableTimesSkeleton } from "@calcom/web/modules/bookings/components/AvailableTimes";
import { useBookerStoreContext } from "@calcom/features/bookings/Booker/BookerStoreProvider";
import type { IUseBookingLoadingStates } from "@calcom/features/bookings/Booker/components/hooks/useBookings";
import type { BookerEvent } from "@calcom/features/bookings/types";
import type { Slot } from "@calcom/features/schedules/lib/use-schedule/types";
import { useNonEmptyScheduleDays } from "@calcom/features/schedules/lib/use-schedule/useNonEmptyScheduleDays";
import { useSlotsForAvailableDates } from "@calcom/features/schedules/lib/use-schedule/useSlotsForDate";
import { PUBLIC_INVALIDATE_AVAILABLE_SLOTS_ON_BOOKING_FORM } from "@calcom/lib/constants";
import { localStorage } from "@calcom/lib/webstorage";
import { BookerLayouts } from "@calcom/prisma/zod-utils";
import classNames from "@calcom/ui/classNames";
import { AvailableTimesHeader } from "@calcom/web/modules/bookings/components/AvailableTimesHeader";
import type { useScheduleForEventReturnType } from "@calcom/features/bookings/Booker/utils/event";
import { getQueryParam } from "@calcom/features/bookings/Booker/utils/query-param";
type AvailableTimeSlotsProps = {
extraDays?: number;
limitHeight?: boolean;
schedule?: useScheduleForEventReturnType;
isLoading: boolean;
seatsPerTimeSlot?: number | null;
showAvailableSeatsCount?: boolean | null;
event: {
data?: Pick<BookerEvent, "length" | "bookingFields" | "price" | "currency" | "metadata"> | null;
};
customClassNames?: {
availableTimeSlotsContainer?: string;
availableTimeSlotsTitle?: string;
availableTimeSlotsHeaderContainer?: string;
availableTimeSlotsTimeFormatToggle?: string;
availableTimes?: string;
};
confirmStepClassNames?: {
confirmButton?: string;
};
loadingStates: IUseBookingLoadingStates;
isVerificationCodeSending: boolean;
renderConfirmNotVerifyEmailButtonCond: boolean;
onSubmit: (timeSlot?: string) => void;
skipConfirmStep: boolean;
shouldRenderCaptcha?: boolean;
watchedCfToken?: string;
/**
* This is the list of time slots that are unavailable to book
*/
unavailableTimeSlots: string[];
confirmButtonDisabled?: boolean;
onAvailableTimeSlotSelect: (time: string) => void;
};
/**
* Renders available time slots for a given date.
* It will extract the date from the booker store.
* Next to that you can also pass in the `extraDays` prop, this
* will also fetch the next `extraDays` days and show multiple days
* in columns next to each other.
*/
export const AvailableTimeSlots = ({
extraDays,
limitHeight,
showAvailableSeatsCount,
schedule,
isLoading,
customClassNames,
skipConfirmStep,
seatsPerTimeSlot,
onSubmit,
unavailableTimeSlots,
confirmButtonDisabled,
confirmStepClassNames,
onAvailableTimeSlotSelect,
...props
}: AvailableTimeSlotsProps) => {
const selectedDate = useBookerStoreContext((state) => state.selectedDate);
const setSeatedEventData = useBookerStoreContext((state) => state.setSeatedEventData);
const date = selectedDate || dayjs().format("YYYY-MM-DD");
const [layout] = useBookerStoreContext((state) => [state.layout]);
const isColumnView = layout === BookerLayouts.COLUMN_VIEW;
const containerRef = useRef<HTMLDivElement | null>(null);
const { setTentativeSelectedTimeslots, tentativeSelectedTimeslots } = useBookerStoreContext((state) => ({
setTentativeSelectedTimeslots: state.setTentativeSelectedTimeslots,
tentativeSelectedTimeslots: state.tentativeSelectedTimeslots,
}));
const onTentativeTimeSelect = ({
time,
attendees: _attendees,
seatsPerTimeSlot: _seatsPerTimeSlot,
bookingUid: _bookingUid,
}: {
time: string;
attendees: number;
seatsPerTimeSlot?: number | null;
bookingUid?: string;
}) => {
// We don't intentionally invalidate schedule here because that could remove the slot itself that was clicked, causing a bad UX.
// We could start doing that after we fix this behaviour.
// schedule?.invalidate();
// Earlier we had multiple tentative slots, but now we can only have one tentative slot.
setTentativeSelectedTimeslots([time]);
};
const scheduleData = schedule?.data;
const nonEmptyScheduleDays = useNonEmptyScheduleDays(scheduleData?.slots);
const nonEmptyScheduleDaysFromSelectedDate = nonEmptyScheduleDays.filter(
(slot) => dayjs(selectedDate).diff(slot, "day") <= 0
);
// Creates an array of dates to fetch slots for.
// If `extraDays` is passed in, we will extend the array with the next `extraDays` days.
const dates = useMemo(() => {
if (!extraDays) return [date];
if (nonEmptyScheduleDaysFromSelectedDate.length > 0) {
return nonEmptyScheduleDaysFromSelectedDate.slice(0, extraDays);
}
return [];
}, [date, extraDays, nonEmptyScheduleDaysFromSelectedDate]);
const { slotsPerDay, toggleConfirmButton } = useSlotsForAvailableDates(dates, scheduleData?.slots);
const overlayCalendarToggled =
getQueryParam("overlayCalendar") === "true" || localStorage.getItem("overlayCalendarSwitchDefault");
const onTimeSelect = useCallback(
(time: string, attendees: number, seatsPerTimeSlot?: number | null, bookingUid?: string) => {
// Temporarily allow disabling it, till we are sure that it doesn't cause any significant load on the system
if (PUBLIC_INVALIDATE_AVAILABLE_SLOTS_ON_BOOKING_FORM) {
// Ensures that user has latest available slots when they are about to confirm the booking by filling up the details
schedule?.invalidate();
}
setTentativeSelectedTimeslots([]);
// note(Lauris): setting setSeatedEventData before setSelectedTimeslot so that in useSlots we have seated event data available
// and only then we invoke handleReserveSlot that is triggered by the changes in setSelectedTimeslot.
if (seatsPerTimeSlot) {
setSeatedEventData({
seatsPerTimeSlot,
attendees,
bookingUid,
showAvailableSeatsCount,
});
}
onAvailableTimeSlotSelect(time);
const isTimeSlotAvailable = !unavailableTimeSlots.includes(time);
if (skipConfirmStep && isTimeSlotAvailable) {
onSubmit(time);
}
return;
},
[
onSubmit,
setSeatedEventData,
skipConfirmStep,
showAvailableSeatsCount,
unavailableTimeSlots,
schedule,
setTentativeSelectedTimeslots,
onAvailableTimeSlotSelect,
]
);
const handleSlotClick = useCallback(
(selectedSlot: Slot, isOverlapping: boolean) => {
if ((overlayCalendarToggled && isOverlapping) || skipConfirmStep) {
toggleConfirmButton(selectedSlot);
} else {
onTimeSelect(
selectedSlot.time,
selectedSlot?.attendees || 0,
seatsPerTimeSlot,
selectedSlot.bookingUid
);
}
},
[overlayCalendarToggled, onTimeSelect, seatsPerTimeSlot, skipConfirmStep, toggleConfirmButton]
);
return (
<>
<div className={classNames(`flex`, `${customClassNames?.availableTimeSlotsContainer}`)}>
{isLoading ? (
<div className="mb-3 h-8" />
) : (
slotsPerDay.length > 0 &&
slotsPerDay.map((slots) => {
// Check if this day is OOO - since OOO is date-level, just check the first slot
const isOOODay = slots.slots.length > 0 && slots.slots[0]?.away;
return (
<AvailableTimesHeader
customClassNames={{
availableTimeSlotsHeaderContainer: customClassNames?.availableTimeSlotsHeaderContainer,
availableTimeSlotsTitle: customClassNames?.availableTimeSlotsTitle,
availableTimeSlotsTimeFormatToggle: customClassNames?.availableTimeSlotsTimeFormatToggle,
}}
key={slots.date}
date={dayjs(slots.date)}
showTimeFormatToggle={!isColumnView && !isOOODay}
availableMonth={
dayjs(selectedDate).format("MM") !== dayjs(slots.date).format("MM")
? dayjs(slots.date).format("MMM")
: undefined
}
/>
);
})
)}
</div>
<div
ref={containerRef}
className={classNames(
limitHeight && "no-scrollbar grow overflow-auto md:h-[400px]",
!limitHeight && "flex h-full w-full flex-row gap-4",
`${customClassNames?.availableTimeSlotsContainer}`
)}>
{isLoading && // Shows exact amount of days as skeleton.
Array.from({ length: 1 + (extraDays ?? 0) }).map((_, i) => <AvailableTimesSkeleton key={i} />)}
{!isLoading &&
slotsPerDay.length > 0 &&
slotsPerDay.map((slots) => (
<div key={slots.date} className="no-scrollbar overflow-x-hidden! h-full w-full overflow-y-auto">
<AvailableTimes
className={customClassNames?.availableTimeSlotsContainer}
customClassNames={customClassNames?.availableTimes}
showTimeFormatToggle={!isColumnView}
onTimeSelect={onTimeSelect}
onTentativeTimeSelect={onTentativeTimeSelect}
unavailableTimeSlots={unavailableTimeSlots}
slots={slots.slots}
showAvailableSeatsCount={showAvailableSeatsCount}
skipConfirmStep={skipConfirmStep}
seatsPerTimeSlot={seatsPerTimeSlot}
handleSlotClick={handleSlotClick}
confirmButtonDisabled={confirmButtonDisabled}
confirmStepClassNames={confirmStepClassNames}
{...props}
/>
</div>
))}
</div>
</>
);
};
@@ -0,0 +1,342 @@
// We do not need to worry about importing framer-motion here as it is lazy imported in Booker.
import * as HoverCard from "@radix-ui/react-hover-card";
import { AnimatePresence, m } from "framer-motion";
import { useMemo } from "react";
import { getPaymentAppData } from "@calcom/app-store/_utils/payments/getPaymentAppData";
import { useIsPlatform } from "@calcom/atoms/hooks/useIsPlatform";
import dayjs from "@calcom/dayjs";
import type { IOutOfOfficeData } from "@calcom/features/availability/lib/getUserAvailability";
import { useBookerStoreContext } from "@calcom/features/bookings/Booker/BookerStoreProvider";
import { OutOfOfficeInSlots } from "./OutOfOfficeInSlots";
import type { IUseBookingLoadingStates } from "@calcom/features/bookings/Booker/components/hooks/useBookings";
import type { BookerEvent } from "@calcom/features/bookings/types";
import type { Slot } from "@calcom/features/schedules/lib/use-schedule/types";
import { useLocale } from "@calcom/lib/hooks/useLocale";
import { localStorage } from "@calcom/lib/webstorage";
import classNames from "@calcom/ui/classNames";
import { Button } from "@calcom/ui/components/button";
import { Icon } from "@calcom/ui/components/icon";
import { SkeletonText } from "@calcom/ui/components/skeleton";
import { useBookerTime } from "@calcom/features/bookings/Booker/components/hooks/useBookerTime";
import { getQueryParam } from "@calcom/features/bookings/Booker/utils/query-param";
import { useCheckOverlapWithOverlay } from "@calcom/features/bookings/lib/useCheckOverlapWithOverlay";
import type { Slots } from "@calcom/features/bookings/types";
import { SeatsAvailabilityText } from "./SeatsAvailabilityText";
type TOnTimeSelect = (
time: string,
attendees: number,
seatsPerTimeSlot?: number | null,
bookingUid?: string
) => void;
type TOnTentativeTimeSelect = ({
time,
attendees,
seatsPerTimeSlot,
bookingUid,
}: {
time: string;
attendees: number;
seatsPerTimeSlot?: number | null;
bookingUid?: string;
}) => void;
export type AvailableTimesProps = {
slots: Slots[string];
showTimeFormatToggle?: boolean;
className?: string;
// It is called when a slot is selected, but it is not a confirmation and a confirm button will be shown besides it.
onTentativeTimeSelect?: TOnTentativeTimeSelect;
unavailableTimeSlots?: string[];
} & Omit<SlotItemProps, "slot">;
type SlotItemProps = {
slot: Slot;
seatsPerTimeSlot?: number | null;
selectedSlots?: string[];
onTimeSelect?: TOnTimeSelect;
onTentativeTimeSelect?: TOnTentativeTimeSelect;
showAvailableSeatsCount?: boolean | null;
event: {
data?: Pick<BookerEvent, "length" | "bookingFields" | "price" | "currency" | "metadata"> | null;
};
customClassNames?: string;
confirmStepClassNames?: {
confirmButton?: string;
};
loadingStates?: IUseBookingLoadingStates;
isVerificationCodeSending?: boolean;
renderConfirmNotVerifyEmailButtonCond?: boolean;
skipConfirmStep?: boolean;
shouldRenderCaptcha?: boolean;
watchedCfToken?: string;
unavailableTimeSlots?: string[];
confirmButtonDisabled?: boolean;
handleSlotClick?: (slot: Slot, isOverlapping: boolean) => void;
};
const SlotItem = ({
slot,
seatsPerTimeSlot,
selectedSlots,
onTimeSelect,
showAvailableSeatsCount,
event,
customClassNames,
loadingStates,
renderConfirmNotVerifyEmailButtonCond,
isVerificationCodeSending,
skipConfirmStep,
shouldRenderCaptcha,
watchedCfToken,
handleSlotClick,
onTentativeTimeSelect,
unavailableTimeSlots = [],
confirmButtonDisabled,
confirmStepClassNames,
}: SlotItemProps) => {
const { t } = useLocale();
const { data: eventData } = event;
const isPaidEvent = useMemo(() => {
if (!eventData?.price) return false;
const paymentAppData = getPaymentAppData(eventData);
return eventData?.price > 0 && !Number.isNaN(paymentAppData.price) && paymentAppData.price > 0;
}, [eventData]);
const overlayCalendarToggled =
getQueryParam("overlayCalendar") === "true" || localStorage.getItem("overlayCalendarSwitchDefault");
const { timeFormat, timezone } = useBookerTime();
const bookingData = useBookerStoreContext((state) => state.bookingData);
const layout = useBookerStoreContext((state) => state.layout);
const hasTimeSlots = !!seatsPerTimeSlot;
const computedDateWithUsersTimezone = dayjs.utc(slot.time).tz(timezone);
const bookingFull = !!(hasTimeSlots && slot.attendees && slot.attendees >= seatsPerTimeSlot);
const isHalfFull = slot.attendees && seatsPerTimeSlot && slot.attendees / seatsPerTimeSlot >= 0.5;
const isNearlyFull = slot.attendees && seatsPerTimeSlot && slot.attendees / seatsPerTimeSlot >= 0.83;
const colorClass = isNearlyFull ? "bg-rose-600" : isHalfFull ? "bg-yellow-500" : "bg-emerald-400";
const nowDate = dayjs();
const usersTimezoneDate = nowDate.tz(timezone);
const offset = (usersTimezoneDate.utcOffset() - nowDate.utcOffset()) / 60;
const selectedTimeslot = useBookerStoreContext((state) => state.selectedTimeslot);
const { isOverlapping, overlappingTimeEnd, overlappingTimeStart } = useCheckOverlapWithOverlay({
start: computedDateWithUsersTimezone,
selectedDuration: eventData?.length ?? 0,
offset,
});
const onButtonClick = () => {
if (handleSlotClick) {
handleSlotClick(slot, isOverlapping);
}
if (onTentativeTimeSelect) {
onTentativeTimeSelect({
time: slot.time,
attendees: slot.attendees || 0,
seatsPerTimeSlot,
});
}
};
const isTimeslotUnavailable = unavailableTimeSlots.includes(slot.time);
return (
<AnimatePresence>
<div className="flex gap-2">
<Button
key={slot.time}
disabled={
bookingFull ||
!!(slot.bookingUid && slot.bookingUid === bookingData?.uid) ||
loadingStates?.creatingBooking ||
loadingStates?.creatingRecurringBooking ||
isVerificationCodeSending ||
loadingStates?.creatingInstantBooking ||
(skipConfirmStep && !!shouldRenderCaptcha && !watchedCfToken) ||
isTimeslotUnavailable
}
data-testid="time"
data-disabled={bookingFull}
data-time={slot.time}
onClick={onButtonClick}
className={classNames(
`hover:border-brand-default min-h-9 mb-2 flex h-auto w-full grow flex-col justify-center py-2`,
selectedSlots?.includes(slot.time) && "border-brand-default",
`${customClassNames}`
)}
color="secondary">
<div className="flex items-center gap-2">
{!hasTimeSlots && overlayCalendarToggled && (
<span
className={classNames(
"inline-block h-2 w-2 rounded-full",
isOverlapping ? "bg-rose-600" : "bg-emerald-400"
)}
/>
)}
{computedDateWithUsersTimezone.format(timeFormat)}
</div>
{bookingFull && <p className="text-sm">{t("booking_full")}</p>}
{hasTimeSlots && !bookingFull && (
<p className="flex items-center text-sm">
<span
className={classNames(colorClass, "mr-1 inline-block h-2 w-2 rounded-full")}
aria-hidden
/>
<SeatsAvailabilityText
showExact={!!showAvailableSeatsCount}
totalSeats={seatsPerTimeSlot}
bookedSeats={slot.attendees || 0}
/>
</p>
)}
</Button>
{!!slot.showConfirmButton && (
<HoverCard.Root>
<HoverCard.Trigger asChild>
<m.div key={slot.time} initial={{ width: 0 }} animate={{ width: "auto" }} exit={{ width: 0 }}>
<Button
variant={layout === "column_view" ? "icon" : "button"}
StartIcon={layout === "column_view" ? "chevron-right" : undefined}
type="button"
className={confirmStepClassNames?.confirmButton}
onClick={() =>
onTimeSelect &&
onTimeSelect(slot.time, slot?.attendees || 0, seatsPerTimeSlot, slot.bookingUid)
}
data-testid="skip-confirm-book-button"
disabled={
isTimeslotUnavailable ||
(!!shouldRenderCaptcha && !watchedCfToken) ||
loadingStates?.creatingBooking ||
loadingStates?.creatingRecurringBooking ||
isVerificationCodeSending ||
loadingStates?.creatingInstantBooking ||
confirmButtonDisabled
}
color="primary"
loading={
(selectedTimeslot === slot.time && loadingStates?.creatingBooking) ||
loadingStates?.creatingRecurringBooking ||
isVerificationCodeSending ||
loadingStates?.creatingInstantBooking
}>
{(() => {
if (layout === "column_view") return "";
if (isTimeslotUnavailable) return t("timeslot_unavailable_short");
if (!renderConfirmNotVerifyEmailButtonCond) return t("verify_email_button");
return isPaidEvent ? t("pay_and_book") : t("confirm");
})()}
</Button>
</m.div>
</HoverCard.Trigger>
{isOverlapping && (
<HoverCard.Portal>
<HoverCard.Content side="top" align="end" sideOffset={2}>
<div className="text-emphasis bg-inverted w-(--booker-timeslots-width) rounded-md p-3">
<div className="flex items-center gap-2">
<p>Busy</p>
</div>
<p className="text-muted">
{overlappingTimeStart} - {overlappingTimeEnd}
</p>
</div>
</HoverCard.Content>
</HoverCard.Portal>
)}
</HoverCard.Root>
)}
</div>
</AnimatePresence>
);
};
export const AvailableTimes = ({
slots,
showTimeFormatToggle = true,
className,
...props
}: AvailableTimesProps) => {
const { t } = useLocale();
const oooAllDay = slots.every((slot) => slot.away);
if (oooAllDay) {
return <OOOSlot {...slots[0]} />;
}
// Display ooo in slots once but after or before slots
const oooBeforeSlots = slots[0] && slots[0].away;
const oooAfterSlots = slots[slots.length - 1] && slots[slots.length - 1].away;
return (
<div className={classNames("text-default flex flex-col", className)}>
<div className="h-full pb-4">
{!slots.length && (
<div
data-testId="no-slots-available"
className="bg-subtle border-subtle flex h-full flex-col items-center rounded-md border p-6 dark:bg-transparent">
<Icon name="calendar-x-2" className="text-muted mb-2 h-4 w-4" />
<p className={classNames("text-muted", showTimeFormatToggle ? "-mt-1 text-lg" : "text-sm")}>
{t("all_booked_today")}
</p>
</div>
)}
{oooBeforeSlots && !oooAfterSlots && <OOOSlot {...slots[0]} />}
{slots.map((slot) => {
if (slot.away) return null;
return <SlotItem key={slot.time} slot={slot} {...props} />;
})}
{oooAfterSlots && !oooBeforeSlots && <OOOSlot {...slots[slots.length - 1]} className="pb-0" />}
</div>
</div>
);
};
interface IOOOSlotProps {
fromUser?: IOutOfOfficeData["anyDate"]["fromUser"];
toUser?: IOutOfOfficeData["anyDate"]["toUser"];
reason?: string;
emoji?: string;
notes?: string | null;
showNotePublicly?: boolean;
time?: string;
className?: string;
}
const OOOSlot: React.FC<IOOOSlotProps> = (props) => {
const isPlatform = useIsPlatform();
const { fromUser, toUser, reason, emoji, notes, showNotePublicly, time, className = "" } = props;
if (isPlatform) return <></>;
return (
<OutOfOfficeInSlots
fromUser={fromUser}
toUser={toUser}
date={dayjs(time).format("YYYY-MM-DD")}
reason={reason}
emoji={emoji}
notes={notes}
showNotePublicly={showNotePublicly}
borderDashed
className={className}
/>
);
};
export const AvailableTimesSkeleton = () => (
<div className="flex w-[20%] flex-col only:w-full">
{/* Random number of elements between 1 and 6. */}
{Array.from({ length: Math.floor(Math.random() * 6) + 1 }).map((_, i) => (
<SkeletonText className="mb-4 h-6 w-full" key={i} />
))}
</div>
);
@@ -0,0 +1,75 @@
import { shallow } from "zustand/shallow";
import type { Dayjs } from "@calcom/dayjs";
import dayjs from "@calcom/dayjs";
import { useBookerStoreContext } from "@calcom/features/bookings/Booker/BookerStoreProvider";
import { useLocale } from "@calcom/lib/hooks/useLocale";
import { nameOfDay } from "@calcom/lib/weekday";
import { BookerLayouts } from "@calcom/prisma/zod-utils";
import classNames from "@calcom/ui/classNames";
import { TimeFormatToggle } from "./TimeFormatToggle";
type AvailableTimesHeaderProps = {
date: Dayjs;
showTimeFormatToggle?: boolean;
availableMonth?: string | undefined;
customClassNames?: {
availableTimeSlotsHeaderContainer?: string;
availableTimeSlotsTitle?: string;
availableTimeSlotsTimeFormatToggle?: string;
};
};
export const AvailableTimesHeader = ({
date,
showTimeFormatToggle = true,
availableMonth,
customClassNames,
}: AvailableTimesHeaderProps) => {
const { t, i18n } = useLocale();
const [layout] = useBookerStoreContext((state) => [state.layout], shallow);
const isColumnView = layout === BookerLayouts.COLUMN_VIEW;
const isMonthView = layout === BookerLayouts.MONTH_VIEW;
const isToday = dayjs().isSame(date, "day");
return (
<header
className={classNames(
`dark:bg-cal-muted dark:before:bg-cal-muted mb-3 flex w-full flex-row items-center font-medium`,
"bg-default before:bg-default",
customClassNames?.availableTimeSlotsHeaderContainer
)}>
<span
className={classNames(
isColumnView && "w-full text-center",
isColumnView ? "text-subtle text-xs uppercase" : "text-emphasis font-semibold"
)}>
<span
className={classNames(
isToday && !customClassNames?.availableTimeSlotsTitle && "!text-default",
customClassNames?.availableTimeSlotsTitle
)}>
{nameOfDay(i18n.language, Number(date.format("d")), "short")}
</span>
<span
className={classNames(
isColumnView && isToday && "bg-brand-default text-brand ml-2",
"inline-flex items-center justify-center rounded-3xl px-1 pt-0.5 font-medium",
isMonthView
? `text-default text-sm ${customClassNames?.availableTimeSlotsTitle}`
: `text-xs ${customClassNames?.availableTimeSlotsTitle}`
)}>
{date.format("DD")}
{availableMonth && `, ${availableMonth}`}
</span>
</span>
{showTimeFormatToggle && (
<div className="ml-auto rtl:mr-auto">
<TimeFormatToggle customClassName={customClassNames?.availableTimeSlotsTimeFormatToggle} />
</div>
)}
</header>
);
};
@@ -0,0 +1,336 @@
import type { TFunction } from "i18next";
import Link from "next/link";
import { useMemo, useState } from "react";
import type { FieldError } from "react-hook-form";
import { getPaymentAppData } from "@calcom/app-store/_utils/payments/getPaymentAppData";
import { useIsPlatformBookerEmbed } from "@calcom/atoms/hooks/useIsPlatformBookerEmbed";
import { useBookerStoreContext } from "@calcom/features/bookings/Booker/BookerStoreProvider";
import type { BookerEvent } from "@calcom/features/bookings/types";
import ServerTrans from "@calcom/lib/components/ServerTrans";
import { WEBSITE_PRIVACY_POLICY_URL, WEBSITE_TERMS_URL } from "@calcom/lib/constants";
import { ErrorCode } from "@calcom/lib/errorCodes";
import { useLocale } from "@calcom/lib/hooks/useLocale";
import type { TimeFormat } from "@calcom/lib/timeFormat";
import { Alert } from "@calcom/ui/components/alert";
import { Button } from "@calcom/ui/components/button";
import { EmptyScreen } from "@calcom/ui/components/empty-screen";
import { Form } from "@calcom/ui/components/form";
import { formatEventFromTime } from "@calcom/features/bookings/Booker/utils/dates";
import { useBookerTime } from "@calcom/features/bookings/Booker/components/hooks/useBookerTime";
import type { UseBookingFormReturnType } from "@calcom/features/bookings/Booker/components/hooks/useBookingForm";
import type { IUseBookingErrors, IUseBookingLoadingStates } from "@calcom/features/bookings/Booker/components/hooks/useBookings";
import { BookingFields } from "./BookingFields";
import { FormSkeleton } from "./Skeleton";
type BookEventFormProps = {
onCancel?: () => void;
onSubmit: () => void;
errorRef: React.RefObject<HTMLDivElement>;
errors: UseBookingFormReturnType["errors"] & IUseBookingErrors;
loadingStates: IUseBookingLoadingStates;
children?: React.ReactNode;
bookingForm: UseBookingFormReturnType["bookingForm"];
renderConfirmNotVerifyEmailButtonCond: boolean;
extraOptions: Record<string, string | string[]>;
isPlatform?: boolean;
isVerificationCodeSending: boolean;
isTimeslotUnavailable: boolean;
shouldRenderCaptcha?: boolean;
confirmButtonDisabled?: boolean;
classNames?: {
confirmButton?: string;
backButton?: string;
};
timeslot: string | null;
};
export const BookEventForm = ({
onCancel,
eventQuery,
onSubmit,
errorRef,
errors,
loadingStates,
renderConfirmNotVerifyEmailButtonCond,
bookingForm,
children,
extraOptions,
isVerificationCodeSending,
isPlatform = false,
isTimeslotUnavailable,
shouldRenderCaptcha,
confirmButtonDisabled,
classNames,
timeslot,
}: Omit<BookEventFormProps, "event"> & {
eventQuery: {
isError: boolean;
isPending: boolean;
data?: Pick<BookerEvent, "price" | "currency" | "metadata" | "bookingFields" | "locations"> | null;
};
}) => {
const eventType = eventQuery.data;
const setFormValues = useBookerStoreContext((state) => state.setFormValues);
const bookingData = useBookerStoreContext((state) => state.bookingData);
const rescheduleUid = useBookerStoreContext((state) => state.rescheduleUid);
const username = useBookerStoreContext((state) => state.username);
const isInstantMeeting = useBookerStoreContext((state) => state.isInstantMeeting);
const isPlatformBookerEmbed = useIsPlatformBookerEmbed();
const { timeFormat, timezone } = useBookerTime();
const [responseVercelIdHeader] = useState<string | null>(null);
const { t, i18n } = useLocale();
const isPaidEvent = useMemo(() => {
if (!eventType?.price) return false;
const paymentAppData = getPaymentAppData(eventType);
return eventType?.price > 0 && !Number.isNaN(paymentAppData.price) && paymentAppData.price > 0;
}, [eventType]);
const paymentCurrency = useMemo(() => {
if (!eventType) return "USD";
return getPaymentAppData(eventType)?.currency || "USD";
}, [eventType]);
if (eventQuery.isError) return <Alert severity="warning" message={t("error_booking_event")} />;
if (eventQuery.isPending || !eventQuery.data) return <FormSkeleton />;
if (!timeslot)
return (
<EmptyScreen
headline={t("timeslot_missing_title")}
description={t("timeslot_missing_description")}
Icon="calendar"
buttonText={t("timeslot_missing_cta")}
buttonOnClick={onCancel}
/>
);
if (!eventType) {
console.warn("No event type found for event", extraOptions);
return <Alert severity="warning" message={t("error_booking_event")} />;
}
const watchedCfToken = bookingForm.watch("cfToken");
return (
<div className="flex h-full flex-col">
<Form
className="flex h-full flex-col"
onChange={() => {
// Form data is saved in store. This way when user navigates back to
// still change the timeslot, and comes back to the form, all their values
// still exist. This gets cleared when the form is submitted.
const values = bookingForm.getValues();
setFormValues(values);
}}
form={bookingForm}
handleSubmit={onSubmit}
noValidate>
<BookingFields
isDynamicGroupBooking={!!(username && username.indexOf("+") > -1)}
fields={eventType.bookingFields}
locations={eventType.locations}
rescheduleUid={rescheduleUid || undefined}
bookingData={bookingData}
isPaidEvent={isPaidEvent}
paymentCurrency={paymentCurrency}
/>
{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({
globalError: errors.formErrors,
dataError: errors.dataErrors,
t,
responseVercelIdHeader,
timeFormat,
timezone,
language: i18n.language,
})}
/>
</div>
) : isTimeslotUnavailable ? (
<div data-testid="slot-not-allowed-to-book">
<Alert
severity="info"
title={t("unavailable_timeslot_title")}
message={
<ServerTrans
t={t}
i18nKey="timeslot_unavailable_book_a_new_time"
components={[
<button
key="please-select-a-new-time-button"
type="button"
className="underline"
onClick={onCancel}>
Please select a new time
</button>,
]}
/>
}
/>
</div>
) : null}
{!isPlatform && (
<div className="text-subtle my-3 w-full text-xs">
<ServerTrans
t={t}
i18nKey="signing_up_terms"
components={[
<Link
className="text-emphasis hover:underline"
key="terms"
href={`${WEBSITE_TERMS_URL}`}
target="_blank">
Terms
</Link>,
<Link
className="text-emphasis hover:underline"
key="privacy"
href={`${WEBSITE_PRIVACY_POLICY_URL}`}
target="_blank">
Privacy Policy.
</Link>,
]}
/>
</div>
)}
{isPlatformBookerEmbed && (
<div className="text-subtle my-3 w-full text-xs">
{t("proceeding_agreement")}{" "}
<Link
className="text-emphasis hover:underline"
key="terms"
href={`${WEBSITE_TERMS_URL}`}
target="_blank">
{t("terms")}
</Link>{" "}
{t("and")}{" "}
<Link
className="text-emphasis hover:underline"
key="privacy"
href={`${WEBSITE_PRIVACY_POLICY_URL}`}
target="_blank">
{t("privacy_policy")}
</Link>
.
</div>
)}
<div className="modalsticky mt-auto flex justify-end space-x-2 rtl:space-x-reverse">
{isInstantMeeting ? (
<Button type="submit" color="primary" loading={loadingStates.creatingInstantBooking}>
{isPaidEvent ? t("pay_and_book") : t("confirm")}
</Button>
) : (
<>
{!!onCancel && (
<Button
color="minimal"
type="button"
onClick={onCancel}
data-testid="back"
className={classNames?.backButton}>
{t("back")}
</Button>
)}
<Button
type="submit"
color="primary"
disabled={
(!!shouldRenderCaptcha && !watchedCfToken) || isTimeslotUnavailable || confirmButtonDisabled
}
loading={
loadingStates.creatingBooking ||
loadingStates.creatingRecurringBooking ||
isVerificationCodeSending
}
className={classNames?.confirmButton}
data-testid={
rescheduleUid && bookingData ? "confirm-reschedule-button" : "confirm-book-button"
}>
{rescheduleUid && bookingData
? t("reschedule")
: renderConfirmNotVerifyEmailButtonCond
? isPaidEvent
? t("pay_and_book")
: t("confirm")
: t("verify_email_button")}
</Button>
</>
)}
</div>
</Form>
{children}
</div>
);
};
const getError = ({
globalError,
dataError,
t,
responseVercelIdHeader,
timeFormat,
timezone,
language,
}: {
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
dataError: any;
t: TFunction;
responseVercelIdHeader: string | null;
timeFormat: TimeFormat;
timezone: string;
language: string;
}) => {
if (globalError) return globalError?.message;
const error = dataError;
let date = "";
let count = 0;
if (error.message === ErrorCode.BookerLimitExceededReschedule) {
const formattedDate = formatEventFromTime({
date: error.data.startTime,
timeFormat,
timeZone: timezone,
language,
});
date = `${formattedDate.date} ${formattedDate.time}`;
}
if (error.message === ErrorCode.BookerLimitExceeded && error.data?.count) {
count = error.data.count;
}
const messageKey =
error.message === ErrorCode.BookerLimitExceeded ? "booker_upcoming_limit_reached" : error.message;
return error?.message ? (
<>
{responseVercelIdHeader ?? ""} {t(messageKey, { date, count })}
{error.data?.traceId && (
<div className="text-subtle mt-2 text-xs">
<span className="font-medium">{t("trace_reference_id")}:</span>
<code className="ml-1 select-all break-all font-mono">{error.data.traceId}</code>
</div>
)}
</>
) : (
<>{t("can_you_try_again")}</>
);
};
@@ -0,0 +1,112 @@
import type { ReactNode } from "react";
import React from "react";
import { useEventTypeById } from "@calcom/atoms/hooks/event-types/private/useEventTypeById";
import { useIsPlatform } from "@calcom/atoms/hooks/useIsPlatform";
import { useBookerStoreContext } from "@calcom/features/bookings/Booker/BookerStoreProvider";
import { Dialog } from "@calcom/features/components/controlled-dialog";
import { useLocale } from "@calcom/lib/hooks/useLocale";
import { Badge } from "@calcom/ui/components/badge";
import { DialogContent } from "@calcom/ui/components/dialog";
import { getDurationFormatted } from "../event-meta/Duration";
import { FromTime } from "@calcom/features/bookings/Booker/utils/dates";
import { useEvent } from "@calcom/features/bookings/Booker/utils/event";
import { useBookerTime } from "@calcom/features/bookings/Booker/components/hooks/useBookerTime";
const BookEventFormWrapper = ({ children, onCancel }: { onCancel: () => void; children: ReactNode }) => {
const { data } = useEvent();
return <BookEventFormWrapperComponent child={children} eventLength={data?.length} onCancel={onCancel} />;
};
const PlatformBookEventFormWrapper = ({
children,
onCancel,
}: {
onCancel: () => void;
children: ReactNode;
}) => {
const eventId = useBookerStoreContext((state) => state.eventId);
const { data } = useEventTypeById(eventId);
return (
<BookEventFormWrapperComponent child={children} eventLength={data?.lengthInMinutes} onCancel={onCancel} />
);
};
export const BookEventFormWrapperComponent = ({
child,
eventLength,
}: {
onCancel: () => void;
child: ReactNode;
eventLength?: number;
}) => {
const { i18n, t } = useLocale();
const selectedTimeslot = useBookerStoreContext((state) => state.selectedTimeslot);
const selectedDuration = useBookerStoreContext((state) => state.selectedDuration);
const recurringEventCount = useBookerStoreContext((state) => state.recurringEventCount);
const { timeFormat, timezone } = useBookerTime();
if (!selectedTimeslot) {
return null;
}
return (
<>
<h1 className="font-cal text-emphasis text-xl leading-5">{t("confirm_your_details")} </h1>
<div className="my-4 flex flex-wrap gap-2 rounded-md leading-none">
<Badge variant="grayWithoutHover" startIcon="calendar" size="lg">
<FromTime
date={selectedTimeslot}
timeFormat={timeFormat}
timeZone={timezone}
language={i18n.language}
/>
</Badge>
{(selectedDuration || eventLength) && (
<Badge variant="grayWithoutHover" startIcon="clock" size="lg">
<span>{getDurationFormatted(selectedDuration || eventLength, t)}</span>
</Badge>
)}
{recurringEventCount && recurringEventCount > 1 && (
<Badge variant="grayWithoutHover" startIcon="refresh-ccw" size="lg">
<span>
{t("repeats_num_times", {
count: recurringEventCount,
})}
</span>
</Badge>
)}
</div>
{child}
</>
);
};
export const BookFormAsModal = ({
visible,
onCancel,
children,
}: {
visible: boolean;
onCancel: () => void;
children: ReactNode;
}) => {
const isPlatform = useIsPlatform();
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">
{!isPlatform ? (
<BookEventFormWrapper onCancel={onCancel}>{children}</BookEventFormWrapper>
) : (
<PlatformBookEventFormWrapper onCancel={onCancel}>{children}</PlatformBookEventFormWrapper>
)}
</DialogContent>
</Dialog>
);
};
@@ -0,0 +1,263 @@
import { useMemo, useRef } from "react";
import { useFormContext } from "react-hook-form";
import { z } from "zod";
import type { LocationObject } from "@calcom/app-store/locations";
import { getOrganizerInputLocationTypes } from "@calcom/app-store/locations";
import { DefaultEventLocationTypeEnum } from "@calcom/app-store/locations";
import { useBookerStore } from "@calcom/features/bookings/Booker/store";
import type { GetBookingType } from "@calcom/features/bookings/lib/get-booking";
import getLocationOptionsForSelect from "@calcom/features/bookings/lib/getLocationOptionsForSelect";
import { FormBuilderField } from "@calcom/features/form-builder/FormBuilderField";
import { fieldTypesConfigMap } from "@calcom/features/form-builder/fieldTypes";
import { fieldsThatSupportLabelAsSafeHtml } from "@calcom/features/form-builder/fieldsThatSupportLabelAsSafeHtml";
import { SystemField } from "@calcom/lib/bookings/SystemField";
import { useLocale } from "@calcom/lib/hooks/useLocale";
import { markdownToSafeHTML } from "@calcom/lib/markdownToSafeHTML";
import type { RouterOutputs } from "@calcom/trpc/react";
type TouchedFields = {
responses?: Record<string, boolean>;
};
type Fields = NonNullable<RouterOutputs["viewer"]["public"]["event"]>["bookingFields"];
const PhoneLocationSchema = z.object({
value: z.literal(DefaultEventLocationTypeEnum.Phone),
optionValue: z.string().optional(),
});
export const BookingFields = ({
fields,
locations,
rescheduleUid,
isDynamicGroupBooking,
bookingData,
isPaidEvent,
paymentCurrency = "USD",
}: {
fields: Fields;
locations: LocationObject[];
rescheduleUid?: string;
bookingData?: GetBookingType | null;
isDynamicGroupBooking: boolean;
isPaidEvent?: boolean;
paymentCurrency?: string;
}) => {
const { t, i18n } = useLocale();
const { watch, setValue, formState } = useFormContext();
const locationResponse = watch("responses.location");
const currentView = rescheduleUid ? "reschedule" : "";
const isInstantMeeting = useBookerStore((state) => state.isInstantMeeting);
// Identify all phone fields (except location field)
const otherPhoneFieldNames = useMemo(
() => fields.filter((f) => f.type === "phone" && f.name !== SystemField.Enum.location).map((f) => f.name),
[fields]
);
// Track last synced value to avoid redundant updates
const lastSyncedPhoneRef = useRef<string | null>(null);
// Event-driven sync function
const syncPhoneFields = (locationValue: unknown) => {
const parsed = PhoneLocationSchema.safeParse(locationValue);
if (!parsed.success) return;
const { optionValue } = parsed.data;
const phone = (optionValue ?? "").trim();
// Skip if empty or same as last sync (avoid redundant updates during typing)
if (!phone || phone === lastSyncedPhoneRef.current) return;
// Copy phone to other phone fields (only if user hasn't manually touched them)
otherPhoneFieldNames.forEach((name) => {
const targetTouched = !!(formState.touchedFields as TouchedFields)?.responses?.[name];
if (!targetTouched) {
setValue(`responses.${name}`, phone, {
shouldDirty: false,
shouldValidate: false,
});
}
});
lastSyncedPhoneRef.current = phone;
};
const getPriceFormattedLabel = (label: string, price: number) =>
`${label} (${Intl.NumberFormat(i18n.language, {
style: "currency",
currency: paymentCurrency,
}).format(price)})`;
const getFieldWithDirectPricing = (field: Fields[number]) => {
if (!fieldTypesConfigMap[field.type]?.supportsPricing || !field.label || !field.price) {
return field;
}
const price = typeof field.price === "string" ? parseFloat(field.price) : field.price;
const label = getPriceFormattedLabel(field.label, price);
return {
...field,
label,
...(fieldsThatSupportLabelAsSafeHtml.includes(field.type) && field.labelAsSafeHtml
? { labelAsSafeHtml: markdownToSafeHTML(label) }
: { labelAsSafeHtml: undefined }),
};
};
const getFieldWithOptionLevelPrices = (field: Fields[number]) => {
if (!fieldTypesConfigMap[field.type]?.optionsSupportPricing || !field.options) return field;
return {
...field,
options: field.options.map((opt) => {
const option = opt as { value: string; label: string; price?: number };
const optionPrice = option.price;
// Only add price to label if there's a price
if (!optionPrice) return option;
return {
...option,
label: getPriceFormattedLabel(option.label, optionPrice),
};
}),
};
};
return (
// TODO: It might make sense to extract this logic into BookingFields config, that would allow to quickly configure system fields and their editability in fresh booking and reschedule booking view
// The logic here intends to make modifications to booking fields based on the way we want to specifically show Booking Form
<div>
{fields.map((field, index) => {
// Don't Display Location field in case of instant meeting as only Cal Video is supported
if (isInstantMeeting && field.name === "location") return null;
// During reschedule by default all system fields are readOnly. Make them editable on case by case basis.
// Allowing a system field to be edited might require sending emails to attendees, so we need to be careful
const rescheduleReadOnly =
(field.editable === "system" || field.editable === "system-but-optional") &&
!!rescheduleUid &&
bookingData !== null;
const bookingReadOnly = field.editable === "user-readonly";
let readOnly = bookingReadOnly || rescheduleReadOnly;
let hidden = !!field.hidden;
const fieldViews = field.views;
if (fieldViews && !fieldViews.find((view) => view.id === currentView)) {
return null;
}
if (field.name === SystemField.Enum.rescheduleReason) {
if (bookingData === null) {
return null;
}
// rescheduleReason is a reschedule specific field and thus should be editable during reschedule
readOnly = false;
}
if (field.name === SystemField.Enum.smsReminderNumber) {
// `smsReminderNumber` and location.optionValue when location.value===phone are the same data point. We should solve it in a better way in the Form Builder itself.
// I think we should have a way to connect 2 fields together and have them share the same value in Form Builder
if (locationResponse?.value === "phone") {
setValue(`responses.${SystemField.Enum.smsReminderNumber}`, locationResponse?.optionValue);
// Just don't render the field now, as the value is already connected to attendee phone location
return null;
}
// `smsReminderNumber` can be edited during reschedule even though it's a system field
readOnly = false;
}
if (field.name === SystemField.Enum.guests) {
readOnly = false;
// No matter what user configured for Guests field, we don't show it for dynamic group booking as that doesn't support guests
hidden = isDynamicGroupBooking ? true : !!field.hidden;
}
// We don't show `notes` field during reschedule but since it's a query param we better valid if rescheduleUid brought any bookingData
if (field.name === SystemField.Enum.notes && bookingData !== null) {
return null;
}
if (field.name === SystemField.Enum.location) {
readOnly = false;
}
// Dynamically populate location field options
if (field.name === SystemField.Enum.location && field.type === "radioInput") {
if (!field.optionsInputs) {
throw new Error("radioInput must have optionsInputs");
}
const optionsInputs = field.optionsInputs;
// TODO: Instead of `getLocationOptionsForSelect` options should be retrieved from dataStore[field.getOptionsAt]. It would make it agnostic of the `name` of the field.
const options = getLocationOptionsForSelect(locations, t);
options.forEach((option) => {
const optionInput = optionsInputs[option.value as keyof typeof optionsInputs];
if (optionInput) {
optionInput.placeholder = option.inputPlaceholder;
}
});
field.options = options.filter(
(location): location is NonNullable<(typeof options)[number]> => !!location
);
}
if (field?.options) {
const organizerInputTypes = getOrganizerInputLocationTypes();
const organizerInputObj: Record<string, number> = {};
field.options.forEach((f) => {
if (f.value in organizerInputObj) {
organizerInputObj[f.value]++;
} else {
organizerInputObj[f.value] = 1;
}
});
field.options = field.options.map((field) => {
return {
...field,
value:
organizerInputTypes.includes(field.value) && organizerInputObj[field.value] > 1
? field.label
: field.value,
};
});
}
// Add price display for custom inputs with prices
let fieldWithPrice = field;
if (isPaidEvent) {
// Handle number fields and boolean (single checkbox) fields
if (fieldTypesConfigMap[field.type]?.supportsPricing) {
fieldWithPrice = getFieldWithDirectPricing(field);
}
// Handle fields with option-level prices (select, multiselect, and checkbox group)
if (fieldTypesConfigMap[field.type]?.optionsSupportPricing) {
fieldWithPrice = getFieldWithOptionLevelPrices(fieldWithPrice);
}
}
return (
<FormBuilderField
className="mb-4"
field={{ ...fieldWithPrice, hidden }}
readOnly={readOnly}
key={index}
{...(field.name === SystemField.Enum.location && {
onValueChange: ({ value }) => {
syncPhoneFields(value);
},
})}
/>
);
})}
</div>
);
};
@@ -0,0 +1,29 @@
import { SkeletonText } from "@calcom/ui/components/skeleton";
export const FormSkeleton = () => (
<div className="flex flex-col">
<SkeletonText className="h-7 w-32" />
<SkeletonText className="mt-2 h-7 w-full" />
<SkeletonText className="mt-4 h-7 w-28" />
<SkeletonText className="mt-2 h-7 w-full" />
<div className="mt-12 flex h-7 w-full flex-row items-center gap-4">
<SkeletonText className="inline h-4 w-4 rounded-full" />
<SkeletonText className="inline h-7 w-32" />
</div>
<div className="mt-2 flex h-7 w-full flex-row items-center gap-4">
<SkeletonText className="inline h-4 w-4 rounded-full" />
<SkeletonText className="inline h-7 w-28" />
</div>
<SkeletonText className="mt-8 h-7 w-32" />
<SkeletonText className="mt-2 h-7 w-full" />
<SkeletonText className="mt-4 h-7 w-28" />
<SkeletonText className="mt-2 h-7 w-full" />
<div className="mt-6 flex flex-row gap-3">
<SkeletonText className="ml-auto h-8 w-20" />
<SkeletonText className="h-8 w-20" />
</div>
</div>
);
@@ -0,0 +1 @@
export { BookEventForm } from "./BookEventForm";
@@ -0,0 +1,250 @@
import "@calcom/features/bookings/Booker/__mocks__/config";
import "./__mocks__/OverlayCalendar";
import "./__mocks__/AvailableTimeSlots";
import "./__mocks__/DatePicker";
import "./__mocks__/DryRunMessage";
import "./__mocks__/EventMeta";
import "./__mocks__/Header";
import "./__mocks__/LargeCalendar";
import "./__mocks__/Section";
import { constantsScenarios } from "@calcom/lib/__mocks__/constants";
import "@calcom/lib/__mocks__/logger";
import React from "react";
import { vi } from "vitest";
import "@calcom/dayjs/__mocks__";
import "@calcom/features/auth/Turnstile";
import { Booker } from "./Booker";
import { render, screen } from "@calcom/features/bookings/Booker/__tests__/test-utils";
import type { BookerProps, WrappedBookerProps } from "@calcom/features/bookings/Booker/types";
vi.mock("framer-motion", async (importOriginal) => {
const actual = (await importOriginal()) as any;
return {
...actual,
};
});
// Mock components that we don't want to test
vi.mock("./BookEventForm", () => ({
BookEventForm: ({
isTimeslotUnavailable,
onCancel,
}: {
isTimeslotUnavailable: boolean;
onCancel: () => void;
}) => {
console.log("BookEventForm Called", { isTimeslotUnavailable, onCancel });
return (
<div data-testid="book-event-form" data-unavailable={isTimeslotUnavailable}>
Mock Book Event Form
<button onClick={onCancel}>cancel</button>
</div>
);
},
}));
vi.mock("./BookEventForm/BookFormAsModal", () => ({
BookFormAsModal: () => {
return <div data-testid="book-form-as-modal">Mock Book Form As Modal</div>;
},
}));
const mockEvent = {
data: {
id: 1,
title: "Test Event",
seatsPerTimeSlot: 1,
seatsShowAvailabilityCount: true,
},
isSuccess: true,
isPending: false,
};
vi.mock("@calcom/features/calendars/NoAvailabilityDialog", () => ({
default: () => {
return null;
},
}));
const mockSchedule = {
data: {
slots: {
"2024-01-01": [{ time: "2024-01-01T10:00:00Z" }, { time: "2024-01-01T11:00:00Z" }],
},
},
isPending: false,
invalidate: vi.fn(),
};
vi.mock("@calcom/atoms/hooks/useIsPlatformBookerEmbed", () => ({
useIsPlatformBookerEmbed: () => false,
}));
vi.mock("@calcom/atoms/hooks/useIsPlatform", () => ({
useIsPlatform: () => false,
}));
// Update defaultProps to include missing required props
const defaultProps = {
username: "testuser",
eventSlug: "test-event",
entity: { considerUnpublished: false },
event: mockEvent,
schedule: mockSchedule,
slots: {
selectedTimeslot: "2024-01-01T10:00:00Z",
setSelectedTimeslot: vi.fn(),
allSelectedTimeslots: ["2024-01-01T10:00:00Z"],
quickAvailabilityChecks: [],
},
bookerForm: {
key: "form-key",
bookerFormErrorRef: { current: null },
formEmail: "",
bookingForm: {
watch: vi.fn(),
setValue: vi.fn(),
getValues: vi.fn().mockReturnValue({ responses: {} }),
},
errors: {},
},
bookings: {
handleBookEvent: vi.fn(),
errors: {},
loadingStates: {},
expiryTime: 0,
instantVideoMeetingUrl: "",
},
verifyEmail: {
isEmailVerificationModalVisible: false,
setEmailVerificationModalVisible: vi.fn(),
handleVerifyEmail: vi.fn(),
renderConfirmNotVerifyEmailButtonCond: true,
isVerificationCodeSending: false,
},
calendars: {
overlayBusyDates: [],
isOverlayCalendarEnabled: false,
connectedCalendars: [],
loadingConnectedCalendar: false,
onToggleCalendar: vi.fn(),
},
bookerLayout: {
shouldShowFormInDialog: false,
extraDays: 7,
columnViewExtraDays: { current: 7 },
isMobile: false,
layout: "MONTH_VIEW",
hideEventTypeDetails: false,
isEmbed: false,
bookerLayouts: { enabledLayouts: [] },
hasDarkBackground: false,
},
verifyCode: null,
isPlatform: false,
orgBannerUrl: null,
customClassNames: {},
areInstantMeetingParametersSet: false,
userLocale: "en",
hasValidLicense: true,
isBookingDryRun: false,
renderCaptcha: false,
onConnectNowInstantMeeting: vi.fn(),
onGoBackInstantMeeting: vi.fn(),
onOverlayClickNoCalendar: vi.fn(),
onClickOverlayContinue: vi.fn(),
onOverlaySwitchStateChange: vi.fn(),
extraOptions: {},
sessionUsername: null,
rescheduleUid: null,
hasSession: false,
isInstantMeeting: false,
};
describe("Booker", () => {
beforeEach(() => {
constantsScenarios.set({
PUBLIC_QUICK_AVAILABILITY_ROLLOUT: "100",
POWERED_BY_URL: "https://go.cal.com/booking",
APP_NAME: "Cal.com",
});
vi.clearAllMocks();
});
it("should render null when in loading state", () => {
const { container } = render(<Booker {...defaultProps as unknown as BookerProps & WrappedBookerProps} />, {
mockStore: { state: "loading" },
});
expect(container).toBeEmptyDOMElement();
});
it("should render DryRunMessage when in dry run mode", () => {
const propsWithDryRun = {
...defaultProps,
isBookingDryRun: true,
event: {
...mockEvent,
data: {
...mockEvent.data,
isDynamic: false,
},
},
};
render(<Booker {...propsWithDryRun as unknown as BookerProps & WrappedBookerProps} />, {
mockStore: {
state: "selecting_time",
selectedDate: "2024-01-01",
selectedTimeslot: "2024-01-01T10:00:00Z",
tentativeSelectedTimeslots: ["2024-01-01T10:00:00Z"],
},
});
expect(screen.getByTestId("dry-run-message")).toBeInTheDocument();
});
it("should invalidate schedule when cancelling booking form", () => {
const mockInvalidate = vi.fn();
constantsScenarios.set({
PUBLIC_INVALIDATE_AVAILABLE_SLOTS_ON_BOOKING_FORM: "true",
});
const propsWithInvalidate = {
...defaultProps,
schedule: {
...mockSchedule,
invalidate: mockInvalidate,
},
};
render(<Booker {...propsWithInvalidate as unknown as BookerProps & WrappedBookerProps} />, {
mockStore: { state: "booking" },
});
screen.logTestingPlaygroundURL();
// Trigger form cancel
const cancelButton = screen.getByRole("button", { name: /cancel/i });
cancelButton.click();
expect(mockInvalidate).toHaveBeenCalled();
expect(defaultProps.slots.setSelectedTimeslot).toHaveBeenCalledWith(null);
});
describe("Schedule and Availability Check", () => {
it("should mark timeslot as unavailable based on quick availability checks", async () => {
const propsWithQuickChecks = {
...defaultProps,
slots: {
...defaultProps.slots,
quickAvailabilityChecks: [{ utcStartIso: "2024-01-01T10:00:00Z", status: "unavailable" }],
},
};
render(<Booker {...propsWithQuickChecks as unknown as BookerProps & WrappedBookerProps} />, {
mockStore: { state: "booking" },
});
const bookEventForm = screen.getByTestId("book-event-form");
await expect(bookEventForm).toHaveAttribute("data-unavailable", "true");
});
});
});
@@ -0,0 +1,618 @@
import { AnimatePresence, LazyMotion, m } from "framer-motion";
import { useEffect, useMemo, useRef } from "react";
import StickyBox from "react-sticky-box";
import { Toaster } from "sonner";
import { shallow } from "zustand/shallow";
import BookingPageTagManager from "@calcom/app-store/BookingPageTagManager";
import { useIsPlatformBookerEmbed } from "@calcom/atoms/hooks/useIsPlatformBookerEmbed";
import dayjs from "@calcom/dayjs";
import PoweredBy from "@calcom/web/modules/ee/common/components/PoweredBy";
import { useEmbedUiConfig } from "@calcom/embed-core/embed-iframe";
import { updateEmbedBookerState } from "@calcom/embed-core/src/embed-iframe";
import TurnstileCaptcha from "@calcom/features/auth/Turnstile";
import { useBookerStoreContext } from "@calcom/features/bookings/Booker/BookerStoreProvider";
import useSkipConfirmStep from "@calcom/features/bookings/Booker/components/hooks/useSkipConfirmStep";
import { getQueryParam } from "@calcom/features/bookings/Booker/utils/query-param";
import { useNonEmptyScheduleDays } from "@calcom/features/schedules/lib/use-schedule/useNonEmptyScheduleDays";
import { scrollIntoViewSmooth } from "@calcom/lib/browser/browser.utils";
import { PUBLIC_INVALIDATE_AVAILABLE_SLOTS_ON_BOOKING_FORM } from "@calcom/lib/constants";
import { CLOUDFLARE_SITE_ID, CLOUDFLARE_USE_TURNSTILE_IN_BOOKER } from "@calcom/lib/constants";
import { useCompatSearchParams } from "@calcom/lib/hooks/useCompatSearchParams";
import { BookerLayouts } from "@calcom/prisma/zod-utils";
import classNames from "@calcom/ui/classNames";
import { UnpublishedEntity } from "@calcom/ui/components/unpublished-entity";
import { VerifyCodeDialog } from "./VerifyCodeDialog";
import { AvailableTimeSlots } from "./AvailableTimeSlots";
import { BookEventForm } from "./BookEventForm";
import { BookFormAsModal } from "./BookEventForm/BookFormAsModal";
import { DatePicker } from "./DatePicker";
import { DryRunMessage } from "./DryRunMessage";
import { EventMeta } from "./EventMeta";
import { HavingTroubleFindingTime } from "./HavingTroubleFindingTime";
import { Header } from "./Header";
import { InstantBooking } from "./InstantBooking";
import { LargeCalendar } from "./LargeCalendar";
import { OverlayCalendar } from "./OverlayCalendar/OverlayCalendar";
import { RedirectToInstantMeetingModal } from "./RedirectToInstantMeetingModal";
import { BookerSection } from "./Section";
import { NotFound } from "./Unavailable";
import { useIsQuickAvailabilityCheckFeatureEnabled } from "@calcom/features/bookings/Booker/components/hooks/useIsQuickAvailabilityCheckFeatureEnabled";
import { fadeInLeft, getBookerSizeClassNames, useBookerResizeAnimation } from "@calcom/features/bookings/Booker/config";
import framerFeatures from "@calcom/features/bookings/Booker/framer-features";
import type { BookerProps, WrappedBookerProps } from "@calcom/features/bookings/Booker/types";
import { isBookingDryRun } from "@calcom/features/bookings/Booker/utils/isBookingDryRun";
import { isTimeSlotAvailable } from "@calcom/features/bookings/Booker/utils/isTimeslotAvailable";
const BookerComponent = ({
username,
eventSlug,
hideBranding = false,
entity,
isInstantMeeting = false,
onGoBackInstantMeeting,
onConnectNowInstantMeeting,
onOverlayClickNoCalendar,
onClickOverlayContinue,
onOverlaySwitchStateChange,
sessionUsername,
rescheduleUid,
hasSession,
extraOptions,
bookings,
verifyEmail,
slots,
calendars,
bookerForm,
event,
bookerLayout,
schedule,
verifyCode,
isPlatform,
orgBannerUrl,
customClassNames,
areInstantMeetingParametersSet = false,
userLocale,
hasValidLicense,
isBookingDryRun: isBookingDryRunProp,
renderCaptcha,
hashedLink,
confirmButtonDisabled,
timeZones,
eventMetaChildren,
roundRobinHideOrgAndTeam,
showNoAvailabilityDialog,
}: BookerProps & WrappedBookerProps) => {
const searchParams = useCompatSearchParams();
const isPlatformBookerEmbed = useIsPlatformBookerEmbed();
const [bookerState, setBookerState] = useBookerStoreContext(
(state) => [state.state, state.setState],
shallow
);
const selectedDate = useBookerStoreContext((state) => state.selectedDate);
const {
shouldShowFormInDialog,
hasDarkBackground,
extraDays,
columnViewExtraDays,
isMobile,
layout,
hideEventTypeDetails,
isEmbed,
bookerLayouts,
} = bookerLayout;
const [seatedEventData, setSeatedEventData] = useBookerStoreContext(
(state) => [state.seatedEventData, state.setSeatedEventData],
shallow
);
const { selectedTimeslot, setSelectedTimeslot, allSelectedTimeslots } = slots;
const [dayCount, setDayCount] = useBookerStoreContext(
(state) => [state.dayCount, state.setDayCount],
shallow
);
const nonEmptyScheduleDays = useNonEmptyScheduleDays(schedule?.data?.slots).filter(
(slot) => dayjs(selectedDate).diff(slot, "day") <= 0
);
const totalWeekDays = 7;
const addonDays =
nonEmptyScheduleDays.length < extraDays
? (extraDays - nonEmptyScheduleDays.length + 1) * 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) {
const slotIndex =
availableSlots.length === extraDays + 1 ? availableSlots.length - 2 : availableSlots.length - 1;
columnViewExtraDays.current =
Math.abs(dayjs(selectedDate).diff(availableSlots[slotIndex], "day")) + addonDays;
}
const nextSlots =
Math.abs(dayjs(selectedDate).diff(availableSlots[availableSlots.length - 1], "day")) + addonDays;
const animationScope = useBookerResizeAnimation(layout, bookerState);
const timeslotsRef = useRef<HTMLDivElement>(null);
const isQuickAvailabilityCheckFeatureEnabled = useIsQuickAvailabilityCheckFeatureEnabled();
const StickyOnDesktop = isMobile ? "div" : StickyBox;
const { bookerFormErrorRef, key, formEmail, bookingForm, errors: formErrors } = bookerForm;
const {
handleBookEvent,
errors,
loadingStates,
expiryTime,
instantVideoMeetingUrl,
instantConnectCooldownMs,
} = bookings;
const watchedCfToken = bookingForm.watch("cfToken");
const {
isEmailVerificationModalVisible,
setEmailVerificationModalVisible,
handleVerifyEmail,
renderConfirmNotVerifyEmailButtonCond,
isVerificationCodeSending,
} = verifyEmail;
const {
overlayBusyDates,
isOverlayCalendarEnabled,
connectedCalendars,
loadingConnectedCalendar,
onToggleCalendar,
} = calendars;
const scrolledToTimeslotsOnce = useRef(false);
const embedUiConfig = useEmbedUiConfig();
const scrollToTimeSlots = () => {
if (
isMobile &&
!scrolledToTimeslotsOnce.current &&
timeslotsRef.current &&
!embedUiConfig.disableAutoScroll
) {
// eslint-disable-next-line @calcom/eslint/no-scroll-into-view-embed -- We are allowing it here because scrollToTimeSlots is called on explicit user action where it makes sense to scroll, remember that the goal is to not do auto-scroll on embed load because that ends up scrolling the embedding webpage too
scrollIntoViewSmooth(timeslotsRef.current, isEmbed);
scrolledToTimeslotsOnce.current = true;
}
};
const skipConfirmStep = useSkipConfirmStep(
bookingForm,
bookerState,
isInstantMeeting,
layout == BookerLayouts.WEEK_VIEW,
event?.data?.bookingFields,
event?.data?.locations
);
// Cloudflare Turnstile Captcha
const shouldRenderCaptcha = !!(
!process.env.NEXT_PUBLIC_IS_E2E &&
renderCaptcha &&
CLOUDFLARE_SITE_ID &&
CLOUDFLARE_USE_TURNSTILE_IN_BOOKER === "1" &&
(bookerState === "booking" || (bookerState === "selecting_time" && skipConfirmStep))
);
const onAvailableTimeSlotSelect = (time: string) => {
setSelectedTimeslot(time);
};
updateEmbedBookerState({ bookerState, slotsQuery: schedule });
useEffect(() => {
if (event.isPending) return setBookerState("loading");
if (!selectedDate) return setBookerState("selecting_date");
if (!selectedTimeslot) return setBookerState("selecting_time");
const isSkipConfirmStepSupported = !isInstantMeeting && layout !== BookerLayouts.WEEK_VIEW;
if (selectedTimeslot && skipConfirmStep && isSkipConfirmStepSupported)
return setBookerState("selecting_time");
return setBookerState("booking");
}, [event, selectedDate, selectedTimeslot, setBookerState, skipConfirmStep, layout, isInstantMeeting]);
const unavailableTimeSlots = isQuickAvailabilityCheckFeatureEnabled
? allSelectedTimeslots.filter((slot) => {
return !isTimeSlotAvailable({
scheduleData: schedule?.data ?? null,
slotToCheckInIso: slot,
quickAvailabilityChecks: slots.quickAvailabilityChecks,
});
})
: [];
const slot = getQueryParam("slot");
useEffect(() => {
setSelectedTimeslot(slot || null);
}, [slot, setSelectedTimeslot]);
const onSubmit = (timeSlot?: string) =>
renderConfirmNotVerifyEmailButtonCond ? handleBookEvent(timeSlot) : handleVerifyEmail();
const EventBooker = useMemo(() => {
return bookerState === "booking" ? (
<BookEventForm
key={key}
timeslot={selectedTimeslot}
shouldRenderCaptcha={shouldRenderCaptcha}
onCancel={() => {
setSelectedTimeslot(null);
// Temporarily allow disabling it, till we are sure that it doesn't cause any significant load on the system
if (PUBLIC_INVALIDATE_AVAILABLE_SLOTS_ON_BOOKING_FORM) {
// Ensures that user has latest available slots when they want to re-choose from the slots
schedule?.invalidate();
}
if (seatedEventData.bookingUid) {
setSeatedEventData({ ...seatedEventData, bookingUid: undefined, attendees: undefined });
}
}}
onSubmit={() => (renderConfirmNotVerifyEmailButtonCond ? handleBookEvent() : handleVerifyEmail())}
errorRef={bookerFormErrorRef}
errors={{ ...formErrors, ...errors }}
isTimeslotUnavailable={!isInstantMeeting && unavailableTimeSlots.includes(selectedTimeslot || "")}
loadingStates={loadingStates}
renderConfirmNotVerifyEmailButtonCond={renderConfirmNotVerifyEmailButtonCond}
bookingForm={bookingForm}
eventQuery={event}
extraOptions={extraOptions}
isVerificationCodeSending={isVerificationCodeSending}
confirmButtonDisabled={confirmButtonDisabled}
classNames={{
confirmButton: customClassNames?.confirmStep?.confirmButton,
backButton: customClassNames?.confirmStep?.backButton,
}}
isPlatform={isPlatform}>
<>
{!isPlatform && (
<RedirectToInstantMeetingModal
expiryTime={expiryTime}
bookingId={parseInt(getQueryParam("bookingId") || "0")}
instantVideoMeetingUrl={instantVideoMeetingUrl}
onGoBack={() => {
onGoBackInstantMeeting();
}}
orgName={event.data?.entity?.name}
/>
)}
</>
</BookEventForm>
) : (
<></>
);
}, [
bookerFormErrorRef,
instantVideoMeetingUrl,
bookerState,
bookingForm,
errors,
event,
expiryTime,
extraOptions,
formErrors,
handleBookEvent,
handleVerifyEmail,
key,
loadingStates,
onGoBackInstantMeeting,
renderConfirmNotVerifyEmailButtonCond,
seatedEventData,
setSeatedEventData,
setSelectedTimeslot,
isPlatform,
shouldRenderCaptcha,
isVerificationCodeSending,
unavailableTimeSlots,
]);
/**
* Unpublished organization handling - Below
* - Reschedule links in email are of the organization event for an unpublished org, so we need to allow rescheduling unpublished event
* - Ideally, we should allow rescheduling only for the event that has an old link(non-org link) but that's a bit complex and we are fine showing all reschedule links on unpublished organization
*/
const considerUnpublished = entity.considerUnpublished && !rescheduleUid;
if (considerUnpublished) {
return <UnpublishedEntity {...entity} />;
}
if (event.isSuccess && !event.data) {
return <NotFound />;
}
if (bookerState === "loading") {
return null;
}
return (
<>
{event.data && !isPlatform ? <BookingPageTagManager eventType={event.data} /> : <></>}
{(isBookingDryRunProp || isBookingDryRun(searchParams)) && <DryRunMessage isEmbed={isEmbed} />}
<div
className={classNames(
// In a popup embed, if someone clicks outside the main(having main class or main tag), it closes the embed
"main",
"text-default flex min-h-full w-full flex-col items-center",
layout === BookerLayouts.MONTH_VIEW && !isEmbed && "my-20 ",
layout === BookerLayouts.MONTH_VIEW ? "overflow-visible" : "overflow-clip",
`${customClassNames?.bookerWrapper}`
)}>
<div
ref={animationScope}
data-testid="booker-container"
className={classNames(
...getBookerSizeClassNames(layout, bookerState, hideEventTypeDetails),
`bg-default dark:bg-cal-muted grid max-w-full items-start dark:scheme-dark sm:transition-[width] sm:duration-300 sm:motion-reduce:transition-none md:flex-row`,
// We remove border only when the content covers entire viewport. Because in embed, it can almost never be the case that it covers entire viewport, we show the border there
(layout === BookerLayouts.MONTH_VIEW || isEmbed) && "border-subtle rounded-md",
!isEmbed && "sm:transition-[width] sm:duration-300",
isEmbed && layout === BookerLayouts.MONTH_VIEW && "border-booker sm:border-booker-width",
!isEmbed && layout === BookerLayouts.MONTH_VIEW && `border-subtle border`,
`${customClassNames?.bookerContainer}`
)}>
<AnimatePresence>
{!isInstantMeeting && (
<BookerSection
area="header"
className={classNames(
layout === BookerLayouts.MONTH_VIEW && "fixed top-4 z-10 ltr:right-4 rtl:left-4",
(layout === BookerLayouts.COLUMN_VIEW || layout === BookerLayouts.WEEK_VIEW) &&
"bg-default dark:bg-cal-muted sticky top-0 z-10"
)}>
{isPlatform && layout === BookerLayouts.MONTH_VIEW ? (
<></>
) : (
<Header
isMyLink={Boolean(username === sessionUsername)}
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}
hasSession={hasSession}
handleClickContinue={onClickOverlayContinue}
handleSwitchStateChange={onOverlaySwitchStateChange}
handleClickNoCalendar={() => {
onOverlayClickNoCalendar();
}}
/>
</>
)
}
/>
)}
</BookerSection>
)}
<StickyOnDesktop key="meta" className={classNames("relative z-10 flex [grid-area:meta]")}>
<BookerSection
area="meta"
className="max-w-screen flex w-full flex-col md:w-(--booker-meta-width)">
{!hideEventTypeDetails && orgBannerUrl && (
<img
loading="eager"
className="-mb-9 h-auto w-full object-contain object-top ltr:rounded-tl-md rtl:rounded-tr-md sm:h-16 sm:object-cover"
alt="org banner"
src={orgBannerUrl}
/>
)}
{!hideEventTypeDetails && (
<EventMeta
selectedTimeslot={selectedTimeslot}
classNames={{
eventMetaContainer: customClassNames?.eventMetaCustomClassNames?.eventMetaContainer,
eventMetaTitle: customClassNames?.eventMetaCustomClassNames?.eventMetaTitle,
eventMetaTimezoneSelect:
customClassNames?.eventMetaCustomClassNames?.eventMetaTimezoneSelect,
}}
event={event.data}
isPending={event.isPending}
isPlatform={isPlatform}
isPrivateLink={!!hashedLink}
locale={userLocale}
timeZones={timeZones}
roundRobinHideOrgAndTeam={roundRobinHideOrgAndTeam}
hideEventTypeDetails={hideEventTypeDetails}>
{eventMetaChildren}
</EventMeta>
)}
{layout !== BookerLayouts.MONTH_VIEW &&
!(layout === "mobile" && bookerState === "booking") && (
<div className="mt-auto px-5 py-3">
<DatePicker
classNames={customClassNames?.datePickerCustomClassNames}
event={event}
slots={schedule?.data?.slots}
isLoading={schedule.isPending}
scrollToTimeSlots={scrollToTimeSlots}
showNoAvailabilityDialog={showNoAvailabilityDialog}
/>
</div>
)}
</BookerSection>
</StickyOnDesktop>
<BookerSection
key="book-event-form"
area="main"
className="sticky top-0 -ml-px h-full p-6 md:w-(--booker-main-width) md:border-l"
{...fadeInLeft}
visible={bookerState === "booking" && !shouldShowFormInDialog}>
{EventBooker}
</BookerSection>
<BookerSection
key="datepicker"
area="main"
visible={bookerState !== "booking" && layout === BookerLayouts.MONTH_VIEW}
{...fadeInLeft}
initial="visible"
className="md:border-subtle -ml-px h-full shrink px-5 py-3 md:border-l lg:w-(--booker-main-width)">
<DatePicker
classNames={customClassNames?.datePickerCustomClassNames}
event={event}
slots={schedule?.data?.slots}
isLoading={schedule.isPending}
scrollToTimeSlots={scrollToTimeSlots}
showNoAvailabilityDialog={showNoAvailabilityDialog}
/>
</BookerSection>
<BookerSection
key="large-calendar"
area="main"
visible={layout === BookerLayouts.WEEK_VIEW}
className="border-subtle sticky top-0 -ml-px h-full md:border-l"
{...fadeInLeft}>
<LargeCalendar
extraDays={extraDays}
schedule={schedule.data}
isLoading={schedule.isPending}
event={event}
/>
</BookerSection>
<BookerSection
key="timeslots"
area={{ default: "main", month_view: "timeslots" }}
visible={
(layout !== BookerLayouts.WEEK_VIEW && bookerState === "selecting_time") ||
layout === BookerLayouts.COLUMN_VIEW
}
className={classNames(
"border-subtle rtl:border-default flex h-full w-full flex-col overflow-x-auto px-5 py-3 pb-0 rtl:border-r ltr:md:border-l",
layout === BookerLayouts.MONTH_VIEW &&
"h-full overflow-hidden md:w-(--booker-timeslots-width)",
layout !== BookerLayouts.MONTH_VIEW && "sticky top-0"
)}
ref={timeslotsRef}
{...fadeInLeft}>
<AvailableTimeSlots
onAvailableTimeSlotSelect={onAvailableTimeSlotSelect}
customClassNames={customClassNames?.availableTimeSlotsCustomClassNames}
extraDays={extraDays}
limitHeight={layout === BookerLayouts.MONTH_VIEW}
schedule={schedule}
isLoading={schedule.isPending}
seatsPerTimeSlot={event.data?.seatsPerTimeSlot}
unavailableTimeSlots={unavailableTimeSlots}
showAvailableSeatsCount={event.data?.seatsShowAvailabilityCount}
event={event}
loadingStates={loadingStates}
renderConfirmNotVerifyEmailButtonCond={renderConfirmNotVerifyEmailButtonCond}
isVerificationCodeSending={isVerificationCodeSending}
onSubmit={onSubmit}
skipConfirmStep={skipConfirmStep}
shouldRenderCaptcha={shouldRenderCaptcha}
watchedCfToken={watchedCfToken}
confirmButtonDisabled={confirmButtonDisabled}
confirmStepClassNames={customClassNames?.confirmStep}
/>
</BookerSection>
</AnimatePresence>
</div>
<HavingTroubleFindingTime
visible={bookerState !== "booking" && layout === BookerLayouts.MONTH_VIEW && !isMobile}
dayCount={dayCount}
isScheduleLoading={schedule.isLoading}
onButtonClick={() => {
setDayCount(null);
}}
/>
{bookerState !== "booking" &&
event.data?.showInstantEventConnectNowModal &&
areInstantMeetingParametersSet && (
<div
className={classNames(
"animate-fade-in-up z-40 my-2 opacity-0",
layout === BookerLayouts.MONTH_VIEW && isEmbed ? "" : "fixed bottom-2"
)}
style={{ animationDelay: "1s" }}>
<InstantBooking
event={event.data}
cooldownMs={instantConnectCooldownMs}
onConnectNow={() => {
onConnectNowInstantMeeting();
}}
/>
</div>
)}
{shouldRenderCaptcha && (
<div className="mb-6 mt-auto pt-6">
<TurnstileCaptcha
appearance="interaction-only"
onVerify={(token) => {
bookingForm.setValue("cfToken", token);
}}
/>
</div>
)}
{!hideBranding && (!isPlatform || isPlatformBookerEmbed) && !shouldRenderCaptcha && (
<m.span
key="logo"
className={classNames(
"mb-6 mt-auto pt-6 [&_img]:h-[15px]",
hasDarkBackground ? "dark" : "",
layout === BookerLayouts.MONTH_VIEW ? "block" : "hidden"
)}>
<PoweredBy logoOnly hasValidLicense={hasValidLicense} />
</m.span>
)}
</div>
<>
{verifyCode && formEmail ? (
<VerifyCodeDialog
isOpenDialog={isEmailVerificationModalVisible}
setIsOpenDialog={setEmailVerificationModalVisible}
email={formEmail}
isUserSessionRequiredToVerify={false}
verifyCodeWithSessionNotRequired={verifyCode.verifyCodeWithSessionNotRequired}
verifyCodeWithSessionRequired={verifyCode.verifyCodeWithSessionRequired}
error={verifyCode.error}
resetErrors={verifyCode.resetErrors}
isPending={verifyCode.isPending}
setIsPending={verifyCode.setIsPending}
/>
) : (
<></>
)}
</>
<BookFormAsModal
onCancel={() => setSelectedTimeslot(null)}
visible={bookerState === "booking" && shouldShowFormInDialog}>
{EventBooker}
</BookFormAsModal>
<Toaster position="bottom-right" />
</>
);
};
export const Booker = (props: BookerProps & WrappedBookerProps) => {
return (
<LazyMotion strict features={framerFeatures}>
<BookerComponent {...props} />
</LazyMotion>
);
};
@@ -4,7 +4,7 @@ import { useReactTable, getCoreRowModel, getSortedRowModel } from "@tanstack/rea
import React, { useMemo, useEffect } from "react";
import dayjs from "@calcom/dayjs";
import { DataTableFilters } from "@calcom/features/data-table";
import { DataTableFilters } from "~/data-table/components/filters";
import { useLocale } from "@calcom/lib/hooks/useLocale";
import { trpc } from "@calcom/trpc/react";
import useMeQuery from "@calcom/trpc/react/hooks/useMeQuery";
@@ -2,7 +2,7 @@
import type { Table as ReactTable } from "@tanstack/react-table";
import { DataTableWrapper } from "@calcom/features/data-table";
import { DataTableWrapper } from "~/data-table/components";
import { useLocale } from "@calcom/lib/hooks/useLocale";
import { EmptyScreen } from "@calcom/ui/components/empty-screen";
@@ -7,10 +7,9 @@ import React, { useState, useMemo, useEffect, useCallback } from "react";
import dayjs from "@calcom/dayjs";
import {
useDataTable,
DataTableFilters,
DataTableSegment,
useDisplayedFilterCount,
} from "@calcom/features/data-table";
import { DataTableSegment, DataTableFilters } from "~/data-table/components";
import { useLocale } from "@calcom/lib/hooks/useLocale";
import { trpc } from "@calcom/trpc/react";
import useMeQuery from "@calcom/trpc/react/hooks/useMeQuery";
@@ -0,0 +1,114 @@
import { useLocale } from "@calcom/lib/hooks/useLocale";
import { Badge } from "@calcom/ui/components/badge";
import { Icon } from "@calcom/ui/components/icon";
export interface BookingSuccessCardProps {
title: string;
formattedDate: string;
formattedTime: string;
endTime: string;
formattedTimeZone: string;
hostName: string | null;
hostEmail: string | null;
attendeeName: string | null;
attendeeEmail: string | null;
location: string | null;
}
export function BookingSuccessCard({
title,
formattedDate,
formattedTime,
endTime,
formattedTimeZone,
hostName,
hostEmail,
attendeeName,
attendeeEmail,
location,
}: BookingSuccessCardProps) {
const { t } = useLocale();
return (
<div className="h-screen">
<main className="mx-auto max-w-3xl">
<div className="overflow-y-auto">
<div className="flex items-end justify-center px-4 pb-20 pt-4 text-center sm:flex sm:p-0">
<div className="main inset-0 my-4 flex flex-col transition-opacity sm:my-0" aria-hidden="true">
<div
className="bg-default dark:bg-cal-muted border-booker border-booker-width inline-block transform overflow-hidden rounded-lg px-8 pb-4 pt-5 text-left align-bottom transition-all sm:my-8 sm:w-full sm:max-w-xl sm:py-8 sm:align-middle"
role="dialog"
aria-modal="true"
aria-labelledby="modal-headline">
<div>
<div className="bg-cal-success mx-auto flex h-12 w-12 items-center justify-center rounded-full">
<Icon name="check" className="h-5 w-5 text-green-600 dark:text-green-400" />
</div>
</div>
<div className="mb-8 mt-6 text-center last:mb-0">
<h3 className="text-emphasis text-2xl font-semibold leading-6" id="modal-headline">
{t("meeting_is_scheduled")}
</h3>
<div className="mt-3">
<p className="text-default">{t("emailed_you_and_any_other_attendees")}</p>
</div>
<div className="border-subtle text-default mt-8 grid grid-cols-3 gap-x-4 border-t pt-8 text-left rtl:text-right sm:gap-x-0">
<div className="font-medium">{t("what")}</div>
<div className="col-span-2 mb-6 last:mb-0">{title}</div>
{formattedDate && (
<>
<div className="font-medium">{t("when")}</div>
<div className="col-span-2 mb-6 last:mb-0">
{formattedDate}
{formattedTime && (
<>
<br />
{formattedTime}
{endTime && ` - ${endTime}`}
{formattedTimeZone && (
<span className="text-bookinglight"> ({formattedTimeZone})</span>
)}
</>
)}
</div>
</>
)}
<div className="font-medium">{t("who")}</div>
<div className="col-span-2 last:mb-0">
{hostName && (
<div className="mb-3">
<div>
<span className="mr-2">{hostName}</span>
<Badge variant="blue">{t("Host")}</Badge>
</div>
{hostEmail && <p className="text-default">{hostEmail}</p>}
</div>
)}
{attendeeName && (
<div className="mb-3 last:mb-0">
<p>{attendeeName}</p>
{attendeeEmail && <p>{attendeeEmail}</p>}
</div>
)}
</div>
{location && (
<>
<div className="mt-3 font-medium">{t("where")}</div>
<div className="col-span-2 mt-3">{t("web_conferencing_details_to_follow")}</div>
</>
)}
</div>
</div>
</div>
</div>
</div>
</div>
</main>
</div>
);
}
@@ -0,0 +1,119 @@
import React from "react";
import { vi, afterEach } from "vitest";
import dayjs from "@calcom/dayjs";
import { DatePicker as DatePickerComponent } from "@calcom/features/calendars/DatePicker";
import { render } from "@calcom/features/bookings/Booker/__tests__/test-utils";
import { DatePicker } from "./DatePicker";
vi.mock("@calcom/features/calendars/DatePicker", () => {
return {
DatePicker: vi.fn(() => <div data-testid="mock-date-picker" />),
};
});
const noop = () => {
/* noop */
};
describe("Tests for DatePicker Component", () => {
afterEach(() => {
vi.clearAllMocks();
});
test("It passes the loading prop to the DatePicker component", async () => {
render(<DatePicker event={{}} isLoading={true} />);
expect(DatePickerComponent).toHaveBeenCalledWith(
expect.objectContaining({
isLoading: true,
}),
expect.anything()
);
});
test("happy path, slots in current month", async () => {
// today current time.
const testDate = dayjs();
render(
<DatePicker
event={{}}
slots={{
[`${testDate.format("YYYY-MM-DD")}`]: [
{
time: testDate.format("YYYY-MM-DDTHH:mm:ss"),
},
],
}}
isLoading={false}
/>
);
// slot date is next month, so it'll have skipped the current month
// by setting the browsingDate to the next month.
expect(DatePickerComponent).toHaveBeenCalledWith(
expect.objectContaining({
browsingDate: dayjs().startOf("month"),
}),
expect.anything()
);
});
test("when there are only slots in the next month, skip the current month", async () => {
// there'll be one slot open on this day, next month.
const slotDate = dayjs().add(1, "month");
render(
<DatePicker
event={{}}
slots={{
[`${slotDate.format("YYYY-MM-DD")}`]: [
{
time: slotDate.format("YYYY-MM-DDTHH:mm:ss"),
},
],
}}
isLoading={false}
/>,
{
mockStore: {
month: slotDate.format("YYYY-MM"), // Start with next month to simulate the auto-advance
},
}
);
// slot date is next month, so it'll have skipped the current month
// by setting the browsingDate to the next month.
expect(DatePickerComponent).toHaveBeenCalledWith(
expect.objectContaining({
browsingDate: slotDate.startOf("month"),
}),
expect.anything()
);
});
test("when there are no slots, check for infinite loop (skip only 1 month)", async () => {
render(
<DatePicker
event={{}}
slots={
{
/* no slots given at all, but not loading */
}
}
isLoading={false}
/>,
{
mockStore: {
month: dayjs().add(1, "month").format("YYYY-MM"), // Start with next month to simulate the auto-advance
},
}
);
// slot date is next month, so it'll have skipped the current month
// by setting the browsingDate to the next month.
expect(DatePickerComponent).toHaveBeenCalledWith(
expect.objectContaining({
browsingDate: dayjs().add(1, "month").startOf("month"),
}),
expect.anything()
);
});
});
@@ -0,0 +1,156 @@
import { shallow } from "zustand/shallow";
import type { Dayjs } from "@calcom/dayjs";
import dayjs from "@calcom/dayjs";
import { useBookerStoreContext } from "@calcom/features/bookings/Booker/BookerStoreProvider";
import type { DatePickerClassNames } from "@calcom/features/bookings/Booker/types";
import { DatePicker as DatePickerComponent } from "@calcom/features/calendars/DatePicker";
import { useNonEmptyScheduleDays } from "@calcom/features/schedules/lib/use-schedule/useNonEmptyScheduleDays";
import { weekdayToWeekIndex } from "@calcom/lib/dayjs";
import { useLocale } from "@calcom/lib/hooks/useLocale";
import type { User } from "@calcom/prisma/client";
import type { PeriodData } from "@calcom/types/Event";
import type { Slots } from "@calcom/features/bookings/types";
const useMoveToNextMonthOnNoAvailability = ({
browsingDate,
nonEmptyScheduleDays,
onMonthChange,
isLoading,
}: {
browsingDate: Dayjs;
nonEmptyScheduleDays: string[];
isLoading: boolean;
onMonthChange: (date: Dayjs) => void;
}) => {
if (isLoading) {
return {
moveToNextMonthOnNoAvailability: () => {
/* return noop until ready */
},
};
}
const nonEmptyScheduleDaysInBrowsingMonth = nonEmptyScheduleDays.filter((date) =>
dayjs(date).isSame(browsingDate, "month")
);
const moveToNextMonthOnNoAvailability = () => {
const currentMonth = dayjs().startOf("month").format("YYYY-MM");
const browsingMonth = browsingDate.format("YYYY-MM");
// Not meeting the criteria to move to next month
// Has to be currentMonth and it must have all days unbookable
if (currentMonth != browsingMonth || nonEmptyScheduleDaysInBrowsingMonth.length) {
return;
}
onMonthChange(browsingDate.add(1, "month"));
};
return {
moveToNextMonthOnNoAvailability,
};
};
export const DatePicker = ({
event,
slots = {},
isLoading,
classNames,
scrollToTimeSlots,
showNoAvailabilityDialog,
}: {
event: {
data?: {
subsetOfUsers: Pick<User, "weekStart">[];
periodType?: PeriodData["periodType"];
periodStartDate?: PeriodData["periodStartDate"];
periodEndDate?: PeriodData["periodEndDate"];
periodDays?: PeriodData["periodDays"];
periodCountCalendarDays?: PeriodData["periodCountCalendarDays"];
} | null;
};
slots?: Slots;
isLoading?: boolean;
classNames?: DatePickerClassNames;
scrollToTimeSlots?: () => void;
showNoAvailabilityDialog?: boolean;
}) => {
const { i18n } = useLocale();
const [month, selectedDate, layout] = useBookerStoreContext(
(state) => [state.month, state.selectedDate, state.layout],
shallow
);
const [setSelectedDate, setMonth, setDayCount] = useBookerStoreContext(
(state) => [state.setSelectedDate, state.setMonth, state.setDayCount],
shallow
);
const onMonthChange = (date: Dayjs) => {
setMonth(date.format("YYYY-MM"));
setSelectedDate({ date: date.format("YYYY-MM-DD") });
setDayCount(null); // Whenever the month is changed, we nullify getting X days
};
const nonEmptyScheduleDays = useNonEmptyScheduleDays(slots);
const browsingDate = month ? dayjs(month) : dayjs().startOf("month");
const { moveToNextMonthOnNoAvailability } = useMoveToNextMonthOnNoAvailability({
browsingDate,
nonEmptyScheduleDays,
onMonthChange,
isLoading: isLoading ?? true,
});
moveToNextMonthOnNoAvailability();
// Determine if this is a compact sidebar view based on layout
const isCompact = layout !== "month_view" && layout !== "mobile";
const periodData: PeriodData = {
...{
periodType: "UNLIMITED",
periodStartDate: null,
periodEndDate: null,
periodDays: null,
periodCountCalendarDays: false,
},
...(event?.data && {
periodType: event.data.periodType,
periodStartDate: event.data.periodStartDate,
periodEndDate: event.data.periodEndDate,
periodDays: event.data.periodDays,
periodCountCalendarDays: event.data.periodCountCalendarDays,
}),
};
return (
<DatePickerComponent
customClassNames={{
datePickerTitle: classNames?.datePickerTitle,
datePickerDays: classNames?.datePickerDays,
datePickersDates: classNames?.datePickerDate,
datePickerDatesActive: classNames?.datePickerDatesActive,
datePickerToggle: classNames?.datePickerToggle,
}}
className={classNames?.datePickerContainer}
isLoading={isLoading}
onChange={(date: Dayjs | null, omitUpdatingParams?: boolean) => {
setSelectedDate({
date: date === null ? date : date.format("YYYY-MM-DD"),
omitUpdatingParams,
preventMonthSwitching: !isCompact, // Prevent month switching when in monthly view
});
}}
onMonthChange={onMonthChange}
includedDates={nonEmptyScheduleDays}
locale={i18n.language}
browsingDate={month ? dayjs(month) : undefined}
selected={dayjs(selectedDate)}
weekStart={weekdayToWeekIndex(event?.data?.subsetOfUsers?.[0]?.weekStart)}
slots={slots}
scrollToTimeSlots={scrollToTimeSlots}
periodData={periodData}
isCompact={isCompact}
showNoAvailabilityDialog={showNoAvailabilityDialog}
/>
);
};
@@ -0,0 +1,114 @@
import { useLocale } from "@calcom/lib/hooks/useLocale";
import { Badge } from "@calcom/ui/components/badge";
import { Icon } from "@calcom/ui/components/icon";
export interface DecoyBookingSuccessCardProps {
title: string;
formattedDate: string;
formattedTime: string;
endTime: string;
formattedTimeZone: string;
hostName: string | null;
hostEmail: string | null;
attendeeName: string | null;
attendeeEmail: string | null;
location: string | null;
}
export function DecoyBookingSuccessCard({
title,
formattedDate,
formattedTime,
endTime,
formattedTimeZone,
hostName,
hostEmail,
attendeeName,
attendeeEmail,
location,
}: DecoyBookingSuccessCardProps) {
const { t } = useLocale();
return (
<div className="h-screen">
<main className="mx-auto max-w-3xl">
<div className="overflow-y-auto">
<div className="flex items-end justify-center px-4 pb-20 pt-4 text-center sm:flex sm:p-0">
<div className="main inset-0 my-4 flex flex-col transition-opacity sm:my-0" aria-hidden="true">
<div
className="bg-default dark:bg-cal-muted border-booker border-booker-width inline-block transform overflow-hidden rounded-lg px-8 pb-4 pt-5 text-left align-bottom transition-all sm:my-8 sm:w-full sm:max-w-xl sm:py-8 sm:align-middle"
role="dialog"
aria-modal="true"
aria-labelledby="modal-headline">
<div>
<div className="bg-cal-success mx-auto flex h-12 w-12 items-center justify-center rounded-full">
<Icon name="check" className="h-5 w-5 text-green-600 dark:text-green-400" />
</div>
</div>
<div className="mb-8 mt-6 text-center last:mb-0">
<h3 className="text-emphasis text-2xl font-semibold leading-6" id="modal-headline">
{t("meeting_is_scheduled")}
</h3>
<div className="mt-3">
<p className="text-default">{t("emailed_you_and_any_other_attendees")}</p>
</div>
<div className="border-subtle text-default mt-8 grid grid-cols-3 gap-x-4 border-t pt-8 text-left rtl:text-right sm:gap-x-0">
<div className="font-medium">{t("what")}</div>
<div className="col-span-2 mb-6 last:mb-0">{title}</div>
{formattedDate && (
<>
<div className="font-medium">{t("when")}</div>
<div className="col-span-2 mb-6 last:mb-0">
{formattedDate}
{formattedTime && (
<>
<br />
{formattedTime}
{endTime && ` - ${endTime}`}
{formattedTimeZone && (
<span className="text-bookinglight"> ({formattedTimeZone})</span>
)}
</>
)}
</div>
</>
)}
<div className="font-medium">{t("who")}</div>
<div className="col-span-2 last:mb-0">
{hostName && (
<div className="mb-3">
<div>
<span className="mr-2">{hostName}</span>
<Badge variant="blue">{t("Host")}</Badge>
</div>
{hostEmail && <p className="text-default">{hostEmail}</p>}
</div>
)}
{attendeeName && (
<div className="mb-3 last:mb-0">
<p>{attendeeName}</p>
{attendeeEmail && <p>{attendeeEmail}</p>}
</div>
)}
</div>
{location && (
<>
<div className="mt-3 font-medium">{t("where")}</div>
<div className="col-span-2 mt-3">{t("web_conferencing_details_to_follow")}</div>
</>
)}
</div>
</div>
</div>
</div>
</div>
</div>
</main>
</div>
);
}
@@ -0,0 +1,28 @@
import { useState } from "react";
import { useLocale } from "@calcom/lib/hooks/useLocale";
import { Icon } from "@calcom/ui/components/icon";
export const DryRunMessage = ({ isEmbed }: { isEmbed?: boolean }) => {
const { t } = useLocale();
const [isVisible, setIsVisible] = useState(true);
if (!isVisible) return null;
return (
<div
onClick={() => setIsVisible(false)}
className={`bg-default border-subtle fixed left-1/2 ${
!isEmbed ? "top-4" : "top-0"
} z-50 -translate-x-1/2 transform cursor-pointer items-center gap-3 rounded-xl border p-3 text-sm shadow-md`}>
<div className="flex items-center gap-3">
<div className="relative">
<Icon name="info" className="h-5 w-5 text-orange-500" />
</div>
<div className="text-emphasis font-medium" data-testid="dry-run-msg">
{t("dry_run_mode_active")}
</div>
</div>
</div>
);
};
@@ -0,0 +1,276 @@
import { m } from "framer-motion";
import dynamic from "next/dynamic";
import { useEffect, useMemo } from "react";
import { shallow } from "zustand/shallow";
import { Timezone as PlatformTimezoneSelect } from "@calcom/atoms/timezone";
import { EventDetails, EventMembers, EventMetaSkeleton, EventTitle } from "./event-meta";
import { useBookerStoreContext } from "@calcom/features/bookings/Booker/BookerStoreProvider";
import type { Timezone } from "@calcom/features/bookings/Booker/types";
import { SeatsAvailabilityText } from "@calcom/web/modules/bookings/components/SeatsAvailabilityText";
import { EventMetaBlock } from "@calcom/web/modules/bookings/components/event-meta/Details";
import { useTimePreferences } from "@calcom/features/bookings/lib";
import type { BookerEvent } from "@calcom/features/bookings/types";
import { useLocale } from "@calcom/lib/hooks/useLocale";
import { markdownToSafeHTMLClient } from "@calcom/lib/markdownToSafeHTMLClient";
import { CURRENT_TIMEZONE } from "@calcom/lib/timezoneConstants";
import type { EventTypeTranslation } from "@calcom/prisma/client";
import { EventTypeAutoTranslatedField } from "@calcom/prisma/enums";
import i18nConfigration from "../../../../../i18n.json";
import { fadeInUp } from "@calcom/features/bookings/Booker/config";
import { FromToTime } from "@calcom/features/bookings/Booker/utils/dates";
import { ScrollableWithGradients } from "./ScrollableWithGradients";
import { useBookerTime } from "@calcom/features/bookings/Booker/components/hooks/useBookerTime";
const WebTimezoneSelect = dynamic(
() => import("@calcom/features/components/timezone-select").then((mod) => mod.TimezoneSelect),
{
ssr: false,
}
);
const getTranslatedField = (
translations: Array<Pick<EventTypeTranslation, "field" | "targetLocale" | "translatedText">>,
field: EventTypeAutoTranslatedField,
userLocale: string
) => {
const i18nLocales = i18nConfigration.locale.targets.concat([i18nConfigration.locale.source]);
return translations?.find(
(trans) =>
trans.field === field &&
i18nLocales.includes(trans.targetLocale) &&
(userLocale === trans.targetLocale || userLocale.split("-")[0] === trans.targetLocale)
)?.translatedText;
};
export const EventMeta = ({
event,
isPending,
isPlatform = true,
isPrivateLink,
classNames,
locale,
timeZones,
children,
selectedTimeslot,
roundRobinHideOrgAndTeam,
hideEventTypeDetails = false,
}: {
event?: Pick<
BookerEvent,
| "lockTimeZoneToggleOnBookingPage"
| "lockedTimeZone"
| "schedule"
| "seatsPerTimeSlot"
| "subsetOfUsers"
| "length"
| "schedulingType"
| "profile"
| "entity"
| "description"
| "title"
| "metadata"
| "locations"
| "currency"
| "requiresConfirmation"
| "recurringEvent"
| "price"
| "isDynamic"
| "fieldTranslations"
| "autoTranslateDescriptionEnabled"
> | null;
isPending: boolean;
isPrivateLink: boolean;
isPlatform?: boolean;
classNames?: {
eventMetaContainer?: string;
eventMetaTitle?: string;
eventMetaTimezoneSelect?: string;
eventMetaChildren?: string;
};
locale?: string | null;
timeZones?: Timezone[];
children?: React.ReactNode;
selectedTimeslot: string | null;
roundRobinHideOrgAndTeam?: boolean;
hideEventTypeDetails?: boolean;
}) => {
const { timeFormat, timezone } = useBookerTime();
const [setTimezone] = useTimePreferences((state) => [state.setTimezone]);
const [setBookerStoreTimezone] = useBookerStoreContext((state) => [state.setTimezone], shallow);
const selectedDuration = useBookerStoreContext((state) => state.selectedDuration);
const bookerState = useBookerStoreContext((state) => state.state);
const bookingData = useBookerStoreContext((state) => state.bookingData);
const rescheduleUid = useBookerStoreContext((state) => state.rescheduleUid);
const [seatedEventData, setSeatedEventData] = useBookerStoreContext(
(state) => [state.seatedEventData, state.setSeatedEventData],
shallow
);
const { i18n, t } = useLocale();
const [TimezoneSelect] = useMemo(
() => (isPlatform ? [PlatformTimezoneSelect] : [WebTimezoneSelect]),
[isPlatform]
);
useEffect(() => {
//In case the event has lockTimeZone enabled ,set the timezone to event's locked timezone
if (event?.lockTimeZoneToggleOnBookingPage) {
const timezone = event.lockedTimeZone || event.schedule?.timeZone;
if (timezone) {
setTimezone(timezone);
}
}
}, [event, setTimezone]);
if (hideEventTypeDetails) {
return null;
}
// If we didn't pick a time slot yet, we load bookingData via SSR so bookingData should be set
// Otherwise we load seatedEventData from useBookerStore
const bookingSeatAttendeesQty = seatedEventData?.attendees || bookingData?.attendees.length;
const eventTotalSeats = seatedEventData?.seatsPerTimeSlot || event?.seatsPerTimeSlot;
const isHalfFull =
bookingSeatAttendeesQty && eventTotalSeats && bookingSeatAttendeesQty / eventTotalSeats >= 0.5;
const isNearlyFull =
bookingSeatAttendeesQty && eventTotalSeats && bookingSeatAttendeesQty / eventTotalSeats >= 0.83;
const colorClass = isNearlyFull
? "text-rose-600"
: isHalfFull
? "text-yellow-500"
: "text-bookinghighlight";
const userLocale = locale ?? navigator.language;
const translatedDescription = getTranslatedField(
event?.fieldTranslations ?? [],
EventTypeAutoTranslatedField.DESCRIPTION,
userLocale
);
const translatedTitle = getTranslatedField(
event?.fieldTranslations ?? [],
EventTypeAutoTranslatedField.TITLE,
userLocale
);
return (
<div className={`${classNames?.eventMetaContainer || ""} relative z-10 p-6`} data-testid="event-meta">
{isPending && (
<m.div {...fadeInUp} initial="visible" layout>
<EventMetaSkeleton />
</m.div>
)}
{!isPending && !!event && (
<m.div {...fadeInUp} layout transition={{ ...fadeInUp.transition, delay: 0.3 }}>
<EventMembers
schedulingType={event.schedulingType}
users={event.subsetOfUsers}
profile={event.profile}
entity={event.entity}
isPrivateLink={isPrivateLink}
roundRobinHideOrgAndTeam={roundRobinHideOrgAndTeam}
/>
<EventTitle className={`${classNames?.eventMetaTitle} my-2`}>
{translatedTitle ?? event?.title}
</EventTitle>
{(event.description || translatedDescription) && (
<EventMetaBlock data-testid="event-meta-description" contentClassName="mb-8">
<ScrollableWithGradients
className="wrap-break-word scroll-bar max-h-[180px] max-w-full overflow-y-auto pr-4"
ariaLabel={t("description")}>
<div
dangerouslySetInnerHTML={{
__html: markdownToSafeHTMLClient(translatedDescription ?? event.description),
}}
/>
</ScrollableWithGradients>
</EventMetaBlock>
)}
<div className="stack-y-4 font-medium rtl:-mr-2">
{rescheduleUid && bookingData && (
<EventMetaBlock icon="calendar">
{t("former_time")}
<br />
<span className="line-through" data-testid="former_time_p">
<FromToTime
date={bookingData.startTime.toString()}
duration={null}
timeFormat={timeFormat}
timeZone={timezone}
language={i18n.language}
/>
</span>
</EventMetaBlock>
)}
{selectedTimeslot && (
<EventMetaBlock icon="calendar">
<FromToTime
date={selectedTimeslot}
duration={selectedDuration || event.length}
timeFormat={timeFormat}
timeZone={timezone}
language={i18n.language}
/>
</EventMetaBlock>
)}
<EventDetails event={event} />
<EventMetaBlock
className="cursor-pointer [&_.current-timezone:before]:focus-within:opacity-100 [&_.current-timezone:before]:hover:opacity-100"
contentClassName="relative max-w-[90%]"
icon="globe">
{bookerState === "booking" ? (
<>{timezone}</>
) : (
<span
className={`current-timezone before:bg-subtle min-w-32 -mt-[2px] flex h-6 max-w-full items-center justify-start before:absolute before:inset-0 before:bottom-[-3px] before:left-[-30px] before:top-[-3px] before:w-[calc(100%+35px)] before:rounded-md before:py-3 before:opacity-0 before:transition-opacity ${
event.lockTimeZoneToggleOnBookingPage ? "cursor-not-allowed" : ""
}`}
data-testid="event-meta-current-timezone">
<TimezoneSelect
timeZones={timeZones}
menuPosition="absolute"
timezoneSelectCustomClassname={classNames?.eventMetaTimezoneSelect}
classNames={{
control: () =>
"min-h-0! p-0 w-full border-0 bg-transparent focus-within:ring-0 shadow-none!",
menu: () => "w-64! max-w-[90vw] mb-1 ",
singleValue: () => "text-text py-1",
indicatorsContainer: () => "ml-auto",
container: () => "max-w-full",
}}
value={
event.lockTimeZoneToggleOnBookingPage
? event.lockedTimeZone || CURRENT_TIMEZONE
: timezone
}
onChange={({ value }) => {
setTimezone(value);
setBookerStoreTimezone(value);
}}
isDisabled={event.lockTimeZoneToggleOnBookingPage}
/>
</span>
)}
</EventMetaBlock>
{bookerState === "booking" && eventTotalSeats && bookingSeatAttendeesQty ? (
<EventMetaBlock icon="user" className={`${colorClass}`}>
<div className="text-bookinghighlight flex items-start text-sm">
<p>
<SeatsAvailabilityText
showExact={!!seatedEventData.showAvailableSeatsCount}
totalSeats={eventTotalSeats}
bookedSeats={bookingSeatAttendeesQty || 0}
variant="fraction"
/>
</p>
</div>
</EventMetaBlock>
) : null}
</div>
{children && <div className={classNames?.eventMetaChildren}>{children}</div>}
</m.div>
)}
</div>
);
};
@@ -0,0 +1,48 @@
import { useState } from "react";
import { BOOKER_NUMBER_OF_DAYS_TO_LOAD } from "@calcom/lib/constants";
import { useLocale } from "@calcom/lib/hooks/useLocale";
import { Icon } from "@calcom/ui/components/icon";
type Props = {
onButtonClick: () => void;
dayCount: number | null;
visible: boolean;
isScheduleLoading: boolean;
};
export function HavingTroubleFindingTime(props: Props) {
const { t } = useLocale();
const [internalClick, setInternalClick] = useState(false);
if (!props.visible) return null;
// Easiest way to detect if its not enabled
if (
(process.env.NEXT_PUBLIC_BOOKER_NUMBER_OF_DAYS_TO_LOAD == "0" && BOOKER_NUMBER_OF_DAYS_TO_LOAD == 0) ||
!process.env.NEXT_PUBLIC_BOOKER_NUMBER_OF_DAYS_TO_LOAD
)
return null;
// If we have clicked this internally - and the schedule above is not loading - hide this banner as there is no use of being able to go backwards
if (internalClick && !props.isScheduleLoading) return null;
if (props.isScheduleLoading || !props.dayCount) return null;
return (
<div className="bg-default border-subtle mt-6 flex w-1/2 min-w-0 items-center justify-between rounded-[32px] border p-3 text-sm leading-none shadow-sm lg:w-1/3">
<div className="flex items-center gap-2 overflow-x-hidden">
<Icon name="info" className="text-default h-4 w-4" />
<p className="w-full leading-none">{t("having_trouble_finding_time")}</p>
</div>
{/* TODO: we should give this more of a touch target on mobile */}
<button
className="inline-flex items-center gap-2 font-medium"
onClick={(e) => {
e.preventDefault();
props.onButtonClick();
setInternalClick(true);
}}>
{t("show_more")} <Icon name="arrow-right" className="h-4 w-4" />
</button>
</div>
);
}
@@ -0,0 +1,251 @@
import { useCallback, useMemo } from "react";
import { shallow } from "zustand/shallow";
import { useIsPlatform } from "@calcom/atoms/hooks/useIsPlatform";
import dayjs from "@calcom/dayjs";
import { useIsEmbed } from "@calcom/embed-core/embed-iframe";
import { useBookerStoreContext } from "@calcom/features/bookings/Booker/BookerStoreProvider";
import { useInitializeWeekStart } from "@calcom/features/bookings/Booker/components/hooks/useInitializeWeekStart";
import { WEBAPP_URL } from "@calcom/lib/constants";
import { useLocale } from "@calcom/lib/hooks/useLocale";
import { BookerLayouts } from "@calcom/prisma/zod-utils";
import { Button } from "@calcom/ui/components/button";
import { ButtonGroup } from "@calcom/ui/components/buttonGroup";
import { ToggleGroup } from "@calcom/ui/components/form";
import { Icon } from "@calcom/ui/components/icon";
import { Tooltip } from "@calcom/ui/components/tooltip";
import { TimeFormatToggle } from "@calcom/web/modules/bookings/components/TimeFormatToggle";
import type { BookerLayout } from "@calcom/features/bookings/Booker/types";
export function Header({
extraDays,
isMobile,
enabledLayouts,
nextSlots,
eventSlug,
isMyLink,
renderOverlay,
isCalendarView,
}: {
extraDays: number;
isMobile: boolean;
enabledLayouts: BookerLayouts[];
nextSlots: number;
eventSlug: string;
isMyLink: boolean;
renderOverlay?: () => JSX.Element | null;
isCalendarView?: boolean;
}) {
const { t, i18n } = useLocale();
const isEmbed = useIsEmbed();
const isPlatform = useIsPlatform();
const [layout, setLayout] = useBookerStoreContext((state) => [state.layout, state.setLayout], shallow);
const selectedDateString = useBookerStoreContext((state) => state.selectedDate);
const setSelectedDate = useBookerStoreContext((state) => state.setSelectedDate);
const addToSelectedDate = useBookerStoreContext((state) => state.addToSelectedDate);
const isMonthView = isCalendarView !== undefined ? !isCalendarView : layout === BookerLayouts.MONTH_VIEW;
const today = dayjs();
const selectedDate = selectedDateString ? dayjs(selectedDateString) : today;
const selectedDateMin3DaysDifference = useMemo(() => {
const diff = today.diff(selectedDate, "days");
return diff > 3 || diff < -3;
}, [today, selectedDate]);
useInitializeWeekStart(isPlatform, isCalendarView ?? false);
const onLayoutToggle = useCallback(
(newLayout: string) => {
if (layout === newLayout || !newLayout) return;
setLayout(newLayout as BookerLayout);
},
[setLayout, layout]
);
if (isMobile || !enabledLayouts) return null;
// In month view we only show the layout toggle.
if (isMonthView) {
return (
<div className="flex gap-2">
{isMyLink && !isEmbed ? (
<Tooltip content={t("troubleshooter_tooltip")} side="bottom">
<Button
color="primary"
target="_blank"
href={`${WEBAPP_URL}/availability/troubleshoot?eventType=${eventSlug}`}>
{t("need_help")}
</Button>
</Tooltip>
) : (
renderOverlay?.()
)}
<LayoutToggleWithData
layout={layout}
enabledLayouts={enabledLayouts}
onLayoutToggle={onLayoutToggle}
/>
</div>
);
}
const endDate = selectedDate.add(layout === BookerLayouts.COLUMN_VIEW ? extraDays : extraDays - 1, "days");
const isSameMonth = () => {
return selectedDate.format("MMM") === endDate.format("MMM");
};
const isSameYear = () => {
return selectedDate.format("YYYY") === endDate.format("YYYY");
};
const formattedMonth = new Intl.DateTimeFormat(i18n.language ?? "en", { month: "short" });
const FormattedSelectedDateRange = () => {
return (
<h3 className="min-w-[150px] text-base font-semibold leading-4">
{formattedMonth.format(selectedDate.toDate())} {selectedDate.format("D")}
{!isSameYear() && <span className="text-subtle">, {selectedDate.format("YYYY")} </span>}-{" "}
{!isSameMonth() && formattedMonth.format(endDate.toDate())} {endDate.format("D")},{" "}
<span className="text-subtle">
{isSameYear() ? selectedDate.format("YYYY") : endDate.format("YYYY")}
</span>
</h3>
);
};
return (
<div className="border-default relative z-10 flex border-b px-5 py-4 ltr:border-l rtl:border-r">
<div className="flex items-center gap-5 rtl:grow">
<FormattedSelectedDateRange />
<ButtonGroup>
<Button
className="group rtl:ml-1 rtl:rotate-180"
variant="icon"
color="minimal"
StartIcon="chevron-left"
aria-label="Previous Day"
onClick={() => addToSelectedDate(layout === BookerLayouts.COLUMN_VIEW ? -nextSlots : -extraDays)}
/>
<Button
className="group rtl:mr-1 rtl:rotate-180"
variant="icon"
color="minimal"
StartIcon="chevron-right"
aria-label="Next Day"
onClick={() => addToSelectedDate(layout === BookerLayouts.COLUMN_VIEW ? nextSlots : extraDays)}
/>
{selectedDateMin3DaysDifference && (
<Button
className="capitalize ltr:ml-2 rtl:mr-2"
color="secondary"
onClick={() => {
const selectedDate = (isCalendarView ? today.startOf("week") : today).format("YYYY-MM-DD");
setSelectedDate({ date: selectedDate });
}}>
{t("today")}
</Button>
)}
</ButtonGroup>
</div>
<div className="ml-auto flex gap-2">
{renderOverlay?.()}
<TimeFormatToggle />
<div className="fixed top-4 ltr:right-4 rtl:left-4">
<LayoutToggleWithData
layout={layout}
enabledLayouts={enabledLayouts}
onLayoutToggle={onLayoutToggle}
/>
</div>
{/*
This second layout toggle is hidden, but needed to reserve the correct spot in the DIV
for the fixed toggle above to fit into. If we wouldn't make it fixed in this view, the transition
would be really weird, because the element is positioned fixed in the month view, and then
when switching layouts wouldn't anymore, causing it to animate from the center to the top right,
while it actually already was on place. That's why we have this element twice.
*/}
<div className="pointer-events-none opacity-0" aria-hidden>
<LayoutToggleWithData
layout={layout}
enabledLayouts={enabledLayouts}
onLayoutToggle={onLayoutToggle}
/>
</div>
</div>
</div>
);
}
const LayoutToggle = ({
onLayoutToggle,
layout,
enabledLayouts,
}: {
onLayoutToggle: (layout: string) => void;
layout: string;
enabledLayouts?: BookerLayouts[];
}) => {
const isEmbed = useIsEmbed();
const isPlatform = useIsPlatform();
const { t } = useLocale();
const layoutOptions = useMemo(() => {
return [
{
value: BookerLayouts.MONTH_VIEW,
label: (
<>
<Icon name="calendar" width="16" height="16" />
<span className="sr-only">${t("switch_monthly")}</span>
</>
),
tooltip: t("switch_monthly"),
},
{
value: BookerLayouts.WEEK_VIEW,
label: (
<>
<Icon name="grid-3x3" width="16" height="16" />
<span className="sr-only">${t("switch_weekly")}</span>
</>
),
tooltip: t("switch_weekly"),
},
{
value: BookerLayouts.COLUMN_VIEW,
label: (
<>
<Icon name="columns-3" width="16" height="16" />
<span className="sr-only">${t("switch_columnview")}</span>
</>
),
tooltip: t("switch_columnview"),
},
].filter((layout) => enabledLayouts?.includes(layout.value as BookerLayouts));
}, [t, enabledLayouts]);
// We don't want to show the layout toggle in embed mode as of now as it doesn't look rightly placed when embedded.
// There is a Embed API to control the layout toggle from outside of the iframe.
if (isEmbed) {
return null;
}
// just like embed the layout toggle doesn't look rightly placed in platform
// the layout can be toggled via props in the booker atom
if (isPlatform) return null;
return <ToggleGroup onValueChange={onLayoutToggle} defaultValue={layout} options={layoutOptions} />;
};
const LayoutToggleWithData = ({
enabledLayouts,
onLayoutToggle,
layout,
}: {
enabledLayouts: BookerLayouts[];
onLayoutToggle: (layout: string) => void;
layout: string;
}) => {
return enabledLayouts.length <= 1 ? null : (
<LayoutToggle onLayoutToggle={onLayoutToggle} layout={layout} enabledLayouts={enabledLayouts} />
);
};
@@ -0,0 +1,69 @@
import type { BookerEvent } from "@calcom/features/bookings/types";
import { useLocale } from "@calcom/lib/hooks/useLocale";
import type { User } from "@calcom/prisma/client";
import { UserAvatarGroupWithOrg } from "@calcom/ui/components/avatar";
import { Button } from "@calcom/ui/components/button";
import { Tooltip } from "@calcom/ui/components/tooltip";
interface IInstantBookingProps {
onConnectNow: () => void;
event: Pick<BookerEvent, "entity" | "schedulingType"> & {
subsetOfUsers: (Pick<User, "name" | "username" | "avatarUrl"> & { bookerUrl: string })[];
};
cooldownMs?: number;
}
export const InstantBooking = ({ onConnectNow, event, cooldownMs = 0 }: IInstantBookingProps) => {
const { t } = useLocale();
const disabled = cooldownMs > 0;
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">
<UserAvatarGroupWithOrg
size="sm"
className="border-muted"
organization={{
slug: event.entity.orgSlug,
name: event.entity.name || "",
logoUrl: event.entity.logoUrl ?? null,
}}
users={event.subsetOfUsers.slice(0, 2)}
disableHref
/>
<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 flex items-center gap-3 sm:mt-0">
{disabled ? (
<Tooltip content={t("just_connected_description")}>
<span className="inline-flex">
<Button
disabled={disabled}
color="primary"
onClick={() => {
onConnectNow();
}}
size="sm"
className="w-full justify-center rounded-lg sm:w-auto">
{t("connect_now")}
</Button>
</span>
</Tooltip>
) : (
<Button
color="primary"
onClick={() => {
onConnectNow();
}}
size="sm"
className="w-full justify-center rounded-lg sm:w-auto">
{t("connect_now")}
</Button>
)}
</div>
</div>
);
};
@@ -0,0 +1,84 @@
import { useMemo, useEffect } from "react";
import dayjs from "@calcom/dayjs";
import { useBookerStoreContext } from "@calcom/features/bookings/Booker/BookerStoreProvider";
import { useAvailableTimeSlots } from "@calcom/features/bookings/Booker/components/hooks/useAvailableTimeSlots";
import { useBookerTime } from "@calcom/features/bookings/Booker/components/hooks/useBookerTime";
import type { BookerEvent } from "@calcom/features/bookings/types";
import { Calendar } from "@calcom/features/calendars/weeklyview";
import type { CalendarEvent } from "@calcom/features/calendars/weeklyview/types/events";
import { localStorage } from "@calcom/lib/webstorage";
import type { useScheduleForEventReturnType } from "@calcom/features/bookings/Booker/utils/event";
import { getQueryParam } from "@calcom/features/bookings/Booker/utils/query-param";
import { useOverlayCalendarStore } from "@calcom/features/bookings/Booker/components/OverlayCalendar/store";
export const LargeCalendar = ({
extraDays,
schedule,
isLoading,
event,
}: {
extraDays: number;
schedule?: useScheduleForEventReturnType["data"];
isLoading: boolean;
event: {
data?: Pick<BookerEvent, "length"> | null;
};
}) => {
const selectedDate = useBookerStoreContext((state) => state.selectedDate);
const setSelectedTimeslot = useBookerStoreContext((state) => state.setSelectedTimeslot);
const selectedEventDuration = useBookerStoreContext((state) => state.selectedDuration);
const overlayEvents = useOverlayCalendarStore((state) => state.overlayBusyDates);
const displayOverlay =
getQueryParam("overlayCalendar") === "true" || localStorage?.getItem("overlayCalendarSwitchDefault");
const { timezone } = useBookerTime();
const eventDuration = selectedEventDuration || event?.data?.length || 30;
const availableSlots = useAvailableTimeSlots({ schedule, eventDuration });
const startDate = selectedDate ? dayjs(selectedDate).toDate() : dayjs().toDate();
const endDate = dayjs(startDate)
.add(extraDays - 1, "day")
.toDate();
// HACK: force rerender when overlay events change
// Sine we dont use react router here we need to force rerender (ATOM SUPPORT)
useEffect(() => { }, [displayOverlay]);
const overlayEventsForDate = useMemo(() => {
if (!overlayEvents || !displayOverlay) return [];
return overlayEvents.map((event, id) => {
return {
id,
start: dayjs(event.start).toDate(),
end: dayjs(event.end).toDate(),
title: "Busy",
options: {
status: "ACCEPTED",
borderOnly: true,
},
} as CalendarEvent;
});
}, [overlayEvents, displayOverlay]);
return (
<div className="h-full [--calendar-dates-sticky-offset:66px]">
<Calendar
isPending={isLoading}
availableTimeslots={availableSlots}
startHour={0}
endHour={23}
events={overlayEventsForDate}
startDate={startDate}
endDate={endDate}
onEmptyCellClick={(date) => setSelectedTimeslot(date.toISOString())}
gridCellsPerHour={60 / eventDuration}
hoverEventDuration={eventDuration}
hideHeader
timezone={timezone}
/>
</div>
);
};
@@ -0,0 +1,113 @@
import { useRouter } from "next/navigation";
import type { IOutOfOfficeData } from "@calcom/features/availability/lib/getUserAvailability";
import ServerTrans from "@calcom/lib/components/ServerTrans";
import { useCompatSearchParams } from "@calcom/lib/hooks/useCompatSearchParams";
import { useLocale } from "@calcom/lib/hooks/useLocale";
import classNames from "@calcom/ui/classNames";
import { Button } from "@calcom/ui/components/button";
interface IOutOfOfficeInSlotsProps {
date: string;
fromUser?: IOutOfOfficeData["anyDate"]["fromUser"];
toUser?: IOutOfOfficeData["anyDate"]["toUser"];
emoji?: string;
reason?: string;
notes?: string | null;
showNotePublicly?: boolean;
borderDashed?: boolean;
className?: string;
}
export const OutOfOfficeInSlots = (props: IOutOfOfficeInSlotsProps) => {
const { t } = useLocale();
const {
fromUser,
toUser,
emoji = "🏝️",
reason,
borderDashed = true,
date,
className,
notes,
showNotePublicly,
} = props;
const searchParams = useCompatSearchParams();
const router = useRouter();
// Check if this is a holiday (no fromUser but has reason)
const isHoliday = !fromUser && reason;
// For regular OOO, require fromUser (toUser is optional for redirect)
// For holidays, we just need the reason
if (!isHoliday && !fromUser) return null;
return (
<div className={classNames("relative h-full pb-5", className)}>
<div
className={classNames(
"flex h-full flex-col items-center justify-start rounded-md border bg-white px-4 py-4 font-normal dark:bg-transparent",
borderDashed && "border-dashed"
)}>
<div className="bg-emphasis flex h-14 w-14 flex-col items-center justify-center rounded-full">
<span className="m-auto text-center text-lg">{emoji}</span>
</div>
<div className="stack-y-2 max-h-[300px] w-full overflow-y-auto text-center">
{isHoliday ? (
<>
<p className="mt-2 text-base font-bold">{reason}</p>
<p className="text-subtle text-center text-sm">{t("holiday_no_availability")}</p>
</>
) : (
<>
<p className="mt-2 text-base font-bold">
{t("ooo_user_is_ooo", { displayName: fromUser?.displayName })}
</p>
{notes && showNotePublicly && (
<p className="text-subtle mt-2 max-h-[120px] overflow-y-auto break-words px-2 text-center text-sm italic">
{notes}
</p>
)}
{fromUser?.displayName && toUser?.displayName && (
<p className="text-center text-sm">
<ServerTrans
t={t}
i18nKey="ooo_slots_returning"
values={{ displayName: toUser.displayName }}
components={[<strong key="username">username</strong>]}
/>
</p>
)}
</>
)}
</div>
{!isHoliday && toUser?.id && (
<Button
className="mt-8 max-w-[90%]"
variant="button"
color="secondary"
onClick={() => {
// grab current dates and query params from URL
const month = searchParams.get("month");
const layout = searchParams.get("layout");
const targetDate = searchParams.get("date") || date;
// go to the booking page with the selected user and correct search param
// While being an org push will maintain the org context and just change the user in params
router.push(
`/${toUser.username}?${month ? `month=${month}&` : ""}date=${targetDate}${
layout ? `&layout=${layout}` : ""
}`
);
}}>
<span className="block overflow-hidden text-ellipsis whitespace-nowrap">
{t("ooo_slots_book_with", { displayName: toUser.displayName })}
</span>
</Button>
)}
</div>
</div>
);
};
@@ -0,0 +1,85 @@
import { useEffect } from "react";
import { useIsPlatform } from "@calcom/atoms/hooks/useIsPlatform";
import type { UseCalendarsReturnType } from "@calcom/features/bookings/Booker/components/hooks/useCalendars";
import { useOverlayCalendar } from "@calcom/features/bookings/Booker/components/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;
hasSession: boolean;
handleClickContinue: () => void;
handleSwitchStateChange: (state: boolean) => void;
};
export const OverlayCalendar = ({
connectedCalendars,
overlayBusyDates,
onToggleCalendar,
isOverlayCalendarEnabled,
loadingConnectedCalendar,
handleClickNoCalendar,
handleSwitchStateChange,
handleClickContinue,
hasSession,
}: OverlayCalendarProps) => {
const isPlatform = useIsPlatform();
const {
handleCloseContinueModal,
handleCloseSettingsModal,
isOpenOverlayContinueModal,
isOpenOverlaySettingsModal,
handleToggleConnectedCalendar,
checkIsCalendarToggled,
} = useOverlayCalendar({ connectedCalendars, overlayBusyDates, onToggleCalendar });
// Adding to avoid flickering of continue modal due to stale state
useEffect(() => {
if (isOverlayCalendarEnabled) {
handleCloseContinueModal(false);
}
}, [isOverlayCalendarEnabled, handleCloseContinueModal]);
// on platform we don't handle connecting to third party calendar via booker yet
if (isPlatform && connectedCalendars?.length === 0) {
return null;
}
return (
<>
<OverlayCalendarSwitch
enabled={isOverlayCalendarEnabled}
hasSession={hasSession}
onStateChange={handleSwitchStateChange}
/>
{!isPlatform && (
<OverlayCalendarContinueModal
open={isOpenOverlayContinueModal && !isOverlayCalendarEnabled}
onClose={handleCloseContinueModal}
onContinue={handleClickContinue}
/>
)}
<OverlayCalendarSettingsModal
connectedCalendars={connectedCalendars}
open={isOpenOverlaySettingsModal}
onClose={handleCloseSettingsModal}
isLoading={loadingConnectedCalendar}
onToggleConnectedCalendar={handleToggleConnectedCalendar}
onClickNoCalendar={() => {
handleClickNoCalendar();
}}
checkIsCalendarToggled={checkIsCalendarToggled}
/>
</>
);
};
@@ -0,0 +1,41 @@
import { Dialog } from "@calcom/features/components/controlled-dialog";
import { APP_NAME } from "@calcom/lib/constants";
import { useLocale } from "@calcom/lib/hooks/useLocale";
import { Button } from "@calcom/ui/components/button";
import { DialogContent, DialogFooter } from "@calcom/ui/components/dialog";
interface IOverlayCalendarContinueModalProps {
open?: boolean;
onClose?: (state: boolean) => void;
onContinue: () => void;
}
export function OverlayCalendarContinueModal(props: IOverlayCalendarContinueModalProps) {
const { t } = useLocale();
return (
<>
<Dialog open={props.open} onOpenChange={props.onClose}>
<DialogContent
type="creation"
title={t("overlay_my_calendar")}
description={t("overlay_my_calendar_toc")}>
<div className="flex flex-col gap-2">
<Button
data-testid="overlay-calendar-continue-button"
onClick={() => {
props.onContinue();
}}
className="gap w-full items-center justify-center font-semibold"
StartIcon="calendar-search">
{t("continue_with", { appName: APP_NAME })}
</Button>
</div>
<DialogFooter>
{/* Agh modal hacks */}
<></>
</DialogFooter>
</DialogContent>
</Dialog>
</>
);
}
@@ -0,0 +1,147 @@
import Link from "next/link";
import { Fragment } from "react";
import { useIsPlatform } from "@calcom/atoms/hooks/useIsPlatform";
import { Dialog } from "@calcom/features/components/controlled-dialog";
import { useLocale } from "@calcom/lib/hooks/useLocale";
import classNames from "@calcom/ui/classNames";
import { Alert } from "@calcom/ui/components/alert";
import { DialogContent, DialogClose } from "@calcom/ui/components/dialog";
import { EmptyScreen } from "@calcom/ui/components/empty-screen";
import { Switch } from "@calcom/ui/components/form";
import { ListItem, ListItemText, ListItemTitle } from "@calcom/ui/components/list";
import { SkeletonContainer } from "@calcom/ui/components/skeleton";
import { SkeletonText } from "@calcom/ui/components/skeleton";
import type { UseCalendarsReturnType } from "@calcom/features/bookings/Booker/components/hooks/useCalendars";
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 = () => {
return (
<SkeletonContainer>
<div className="border-subtle mt-3 stack-y-4 rounded-xl border px-4 py-4 ">
<SkeletonText className="h-4 w-full" />
<SkeletonText className="h-4 w-full" />
<SkeletonText className="h-4 w-full" />
<SkeletonText className="h-4 w-full" />
</div>
</SkeletonContainer>
);
};
export function OverlayCalendarSettingsModal({
connectedCalendars,
isLoading,
open,
onClose,
onClickNoCalendar,
onToggleConnectedCalendar,
checkIsCalendarToggled,
}: IOverlayCalendarSettingsModalProps) {
const { t } = useLocale();
const isPlatform = useIsPlatform();
return (
<>
<Dialog open={open} onOpenChange={onClose}>
<DialogContent
enableOverflow
type="creation"
title="Calendar Settings"
className="pb-4"
description={t("view_overlay_calendar_events")}>
<div className="no-scrollbar max-h-full overflow-y-scroll ">
{isLoading ? (
<SkeletonLoader />
) : (
<>
{connectedCalendars.length === 0 ? (
<EmptyScreen
Icon="calendar"
headline={t("no_calendar_installed")}
description={t("no_calendar_installed_description")}
buttonText={t("add_a_calendar")}
buttonOnClick={onClickNoCalendar}
/>
) : (
<>
{connectedCalendars.map((item) => (
<Fragment key={item.credentialId}>
{item.error && !item.calendars && (
<Alert severity="error" title={item.error.message} />
)}
{item?.error === undefined && item.calendars && (
<ListItem className="flex-col rounded-md">
<div className="flex w-full flex-1 items-center space-x-3 pb-4 rtl:space-x-reverse">
{
// eslint-disable-next-line @next/next/no-img-element
item.integration.logo && (
<img
className={classNames(
"h-10 w-10",
item.integration.logo.includes("-dark") && "dark:invert"
)}
src={
isPlatform
? `https://app.cal.com${item.integration.logo}`
: item.integration.logo
}
alt={`${item.integration.title} logo`}
/>
)
}
<div className="grow truncate pl-2">
<ListItemTitle component="h3" className="space-x-2 rtl:space-x-reverse">
<Link href={`/apps/${item.integration.slug}`}>
{item.integration.name || item.integration.title}
</Link>
</ListItemTitle>
<ListItemText component="p">{item.primary.email}</ListItemText>
</div>
</div>
<div className="border-subtle w-full border-t pt-4">
<ul className="stack-y-4">
{item.calendars.map((cal, index) => {
const id = cal.integrationTitle ?? `calendar-switch-${index}`;
return (
<li className="flex gap-3" key={id}>
<Switch
id={id}
checked={checkIsCalendarToggled(cal.externalId, item.credentialId)}
onCheckedChange={() => {
onToggleConnectedCalendar(cal.externalId, item.credentialId);
}}
/>
<label htmlFor={id}>{cal.name}</label>
</li>
);
})}
</ul>
</div>
</ListItem>
)}
</Fragment>
))}
</>
)}
</>
)}
</div>
<div className="mt-4 flex gap-2 self-end">
<DialogClose>{t("done")}</DialogClose>
</div>
</DialogContent>
</Dialog>
</>
);
}
@@ -0,0 +1,76 @@
import { useEffect } from "react";
import { useBookerStoreContext } from "@calcom/features/bookings/Booker/BookerStoreProvider";
import { useLocale } from "@calcom/lib/hooks/useLocale";
import classNames from "@calcom/ui/classNames";
import { Button } from "@calcom/ui/components/button";
import { Switch } from "@calcom/ui/components/form";
import { useOverlayCalendarStore } from "@calcom/features/bookings/Booker/components/OverlayCalendar/store";
interface OverlayCalendarSwitchProps {
enabled?: boolean;
hasSession: boolean;
onStateChange: (state: boolean) => void;
}
export function OverlayCalendarSwitch({ enabled, hasSession, onStateChange }: OverlayCalendarSwitchProps) {
const { t } = useLocale();
const setContinueWithProvider = useOverlayCalendarStore((state) => state.setContinueWithProviderModal);
const setCalendarSettingsOverlay = useOverlayCalendarStore(
(state) => state.setCalendarSettingsOverlayModal
);
const layout = useBookerStoreContext((state) => state.layout);
const switchEnabled = enabled;
/**
* If a user is not logged in and the overlay calendar query param is true,
* show the continue modal so they can login / create an account
*/
useEffect(() => {
if (!hasSession && switchEnabled) {
onStateChange(false);
setContinueWithProvider(true);
}
}, [hasSession, switchEnabled, setContinueWithProvider, onStateChange]);
return (
<div
className={classNames(
"hidden gap-2",
layout === "week_view" || layout === "column_view" ? "xl:flex" : "md:flex"
)}>
<div className="flex items-center gap-2 pr-2">
<Switch
data-testid="overlay-calendar-switch"
checked={switchEnabled}
id="overlayCalendar"
onCheckedChange={(state) => {
if (!hasSession) {
setContinueWithProvider(state);
} else {
onStateChange(state);
}
}}
/>
<label
htmlFor="overlayCalendar"
className="text-emphasis text-sm font-medium leading-none hover:cursor-pointer">
{t("overlay_my_calendar")}
</label>
</div>
{hasSession && (
<Button
size="base"
data-testid="overlay-calendar-settings-button"
variant="icon"
color="secondary"
StartIcon="settings"
onClick={() => {
setCalendarSettingsOverlay(true);
}}
/>
)}
</div>
);
}
@@ -0,0 +1,116 @@
import { useRouter } from "next/navigation";
import { useState, useEffect } from "react";
import dayjs from "@calcom/dayjs";
import { Dialog } from "@calcom/features/components/controlled-dialog";
import { useLocale } from "@calcom/lib/hooks/useLocale";
import { Button } from "@calcom/ui/components/button";
import { DialogContent } from "@calcom/ui/components/dialog";
const handleBeforeUnload = (event: BeforeUnloadEvent) => {
const message = "/o";
event.returnValue = message; // Standard for most browsers
return message; // For some older browsers
};
export const RedirectToInstantMeetingModal = ({
bookingId,
onGoBack,
expiryTime,
instantVideoMeetingUrl,
orgName,
}: {
bookingId: number;
onGoBack: () => void;
expiryTime?: Date;
instantVideoMeetingUrl?: string;
orgName?: string | null;
}) => {
const { t } = useLocale();
const [timeRemaining, setTimeRemaining] = useState(calculateTimeRemaining());
const [hasInstantMeetingTokenExpired, setHasInstantMeetingTokenExpired] = useState(false);
const router = useRouter();
function calculateTimeRemaining() {
const now = dayjs();
const expiration = dayjs(expiryTime);
const duration = expiration.diff(now);
return Math.max(duration, 0);
}
useEffect(() => {
if (!expiryTime) return;
const timer = setInterval(() => {
setTimeRemaining(calculateTimeRemaining());
setHasInstantMeetingTokenExpired(expiryTime && new Date(expiryTime) < new Date());
}, 1000);
return () => {
clearInterval(timer);
};
}, [expiryTime]);
const formatTime = (milliseconds: number) => {
const duration = dayjs.duration(milliseconds);
const seconds = duration.seconds();
const minutes = duration.minutes();
return `${minutes}m ${seconds}s`;
};
useEffect(() => {
if (!expiryTime || hasInstantMeetingTokenExpired || !!instantVideoMeetingUrl) {
window.removeEventListener("beforeunload", handleBeforeUnload);
return;
}
window.addEventListener("beforeunload", handleBeforeUnload);
return () => {
window.removeEventListener("beforeunload", handleBeforeUnload);
};
}, [expiryTime, hasInstantMeetingTokenExpired, instantVideoMeetingUrl]);
useEffect(() => {
if (!!instantVideoMeetingUrl) {
window.removeEventListener("beforeunload", handleBeforeUnload);
router.push(instantVideoMeetingUrl);
}
}, [instantVideoMeetingUrl]);
return (
<Dialog open={!!bookingId && !!expiryTime}>
<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("schedule_instead")}
</Button>
</div>
) : (
<div className="text-center">
<p className="font-medium">{t("connecting_you_to_someone", { orgName })}</p>
<p className="font-bold">{t("please_do_not_close_this_tab")}</p>
<p className="mt-2 font-medium">
{t("please_schedule_future_call", {
seconds: formatTime(timeRemaining),
})}
</p>
<div className="mt-4 h-[414px]">
<iframe className="mx-auto h-full w-[276px] rounded-lg" src="https://cal.games/" />
</div>
</div>
)}
</div>
</DialogContent>
</Dialog>
);
};
@@ -0,0 +1,75 @@
import { useCallback, useEffect, useRef, useState, type ReactNode } from "react";
interface ScrollGradients {
top: boolean;
bottom: boolean;
}
interface ScrollableWithGradientsProps {
children: ReactNode;
className?: string;
ariaLabel?: string;
}
const SCROLL_THRESHOLD = 5; // Pixels before showing gradient
export function ScrollableWithGradients({ children, className, ariaLabel }: ScrollableWithGradientsProps) {
const [gradients, setGradients] = useState<ScrollGradients>({ top: false, bottom: false });
const scrollRef = useRef<HTMLDivElement | null>(null);
const updateGradients = useCallback(() => {
const node = scrollRef.current;
if (!node) return;
const { scrollTop, scrollHeight, clientHeight } = node;
const top = scrollTop > SCROLL_THRESHOLD;
const bottom = scrollTop + clientHeight < scrollHeight - SCROLL_THRESHOLD;
setGradients((prev) => (prev.top === top && prev.bottom === bottom ? prev : { top, bottom }));
}, []);
const setRef = useCallback(
(node: HTMLDivElement | null) => {
scrollRef.current = node;
updateGradients();
},
[updateGradients]
);
// Handle resize events (window resize, font load, etc.)
useEffect(() => {
const node = scrollRef.current;
if (!node) return;
const resizeObserver = new ResizeObserver(updateGradients);
resizeObserver.observe(node);
return () => resizeObserver.disconnect();
}, [updateGradients]);
return (
<div className="relative">
<div
ref={setRef}
onScroll={updateGradients}
className={className}
tabIndex={0}
role="region"
aria-label={ariaLabel}>
{children}
</div>
{gradients.top && (
<div
className="from-default pointer-events-none absolute left-0 right-0 top-0 h-8 bg-gradient-to-b to-transparent dark:from-[var(--cal-bg-muted)]"
aria-hidden="true"
/>
)}
{gradients.bottom && (
<div
className="from-default pointer-events-none absolute bottom-0 left-0 right-0 h-8 bg-gradient-to-t to-transparent dark:from-[var(--cal-bg-muted)]"
aria-hidden="true"
/>
)}
</div>
);
}
@@ -0,0 +1,50 @@
import { useLocale } from "@calcom/lib/hooks/useLocale";
type Props = {
/**
* Whether to show the exact number of seats available or not
*
* @default true
*/
showExact: boolean;
/**
* Shows available seats count as either whole number or fraction.
*
* Applies only when `showExact` is `true`
*
* @default "whole"
*/
variant?: "whole" | "fraction";
/** Number of seats booked in the event */
bookedSeats: number;
/** Total number of seats in the event */
totalSeats: number;
};
export const SeatsAvailabilityText = ({
showExact = true,
bookedSeats,
totalSeats,
variant = "whole",
}: Props) => {
const { t } = useLocale();
const availableSeats = totalSeats - bookedSeats;
const isHalfFull = bookedSeats / totalSeats >= 0.5;
const isNearlyFull = bookedSeats / totalSeats >= 0.83;
return (
<span className="truncate">
{showExact
? `${availableSeats}${variant === "fraction" ? ` / ${totalSeats}` : ""} ${t("seats_available", {
count: availableSeats,
})}`
: isNearlyFull
? t("seats_nearly_full")
: isHalfFull
? t("seats_half_full")
: t("seats_available", {
count: availableSeats,
})}
</span>
);
};
@@ -0,0 +1,63 @@
import type { MotionProps } from "framer-motion";
import { m } from "framer-motion";
import { forwardRef } from "react";
import { useBookerStoreContext } from "@calcom/features/bookings/Booker/BookerStoreProvider";
import classNames from "@calcom/ui/classNames";
import type { BookerAreas, BookerLayout } from "@calcom/features/bookings/Booker/types";
/**
* Define what grid area a section should be in.
* Value is either a string (in case it's always the same area), or an object
* looking like:
* {
* // Where default is the required default area.
* default: "calendar",
* // Any optional overrides for different layouts by their layout name.
* week_view: "main",
* }
*/
type GridArea = BookerAreas | ({ [key in BookerLayout]?: BookerAreas } & { default: BookerAreas });
type BookerSectionProps = {
children: React.ReactNode;
area: GridArea;
visible?: boolean;
className?: string;
} & MotionProps;
// This map with strings is needed so Tailwind generates all classnames,
// If we would concatenate them with JS, Tailwind would not generate them.
const gridAreaClassNameMap: { [key in BookerAreas]: string } = {
calendar: "[grid-area:calendar]",
main: "[grid-area:main]",
meta: "[grid-area:meta]",
timeslots: "[grid-area:timeslots]",
header: "[grid-area:header]",
};
/**
* Small helper component that renders a booker section in a specific grid area.
*/
export const BookerSection = forwardRef<HTMLDivElement, BookerSectionProps>(function BookerSection(
{ children, area, visible, className, ...props },
ref
) {
const layout = useBookerStoreContext((state) => state.layout);
let gridClassName: string;
if (typeof area === "string") {
gridClassName = gridAreaClassNameMap[area];
} else {
gridClassName = gridAreaClassNameMap[area[layout] || area.default];
}
if (!visible && typeof visible !== "undefined") return null;
return (
<m.div ref={ref} className={classNames(gridClassName, className)} layout {...props}>
{children}
</m.div>
);
});
@@ -0,0 +1,26 @@
import { useLocale } from "@calcom/lib/hooks/useLocale";
import { TimeFormat } from "@calcom/lib/timeFormat";
import { ToggleGroup } from "@calcom/ui/components/form";
import { useTimePreferences } from "@calcom/features/bookings/lib";
export const TimeFormatToggle = ({ customClassName }: { customClassName?: string }) => {
const timeFormat = useTimePreferences((state) => state.timeFormat);
const setTimeFormat = useTimePreferences((state) => state.setTimeFormat);
const { t } = useLocale();
return (
<ToggleGroup
customClassNames={customClassName}
onValueChange={(newFormat) => {
if (newFormat && newFormat !== timeFormat) setTimeFormat(newFormat as TimeFormat);
}}
defaultValue={timeFormat}
value={timeFormat}
options={[
{ value: TimeFormat.TWELVE_HOUR, label: t("12_hour_short") },
{ value: TimeFormat.TWENTY_FOUR_HOUR, label: t("24_hour_short") },
]}
/>
);
};
@@ -0,0 +1,30 @@
import { useLocale } from "@calcom/lib/hooks/useLocale";
const UnAvailableMessage = ({ children, title }: { children: React.ReactNode; title: string }) => (
<div className="mx-auto w-full max-w-2xl">
<div className="border-subtle bg-default dark:bg-cal-muted overflow-hidden rounded-lg border p-10">
<h2 className="font-cal mb-4 text-3xl">{title}</h2>
{children}
</div>
</div>
);
export const Away = () => {
const { t } = useLocale();
return (
<UnAvailableMessage title={`😴 ${t("user_away")}`}>
<p className="max-w-[50ch]">{t("user_away_description")}</p>
</UnAvailableMessage>
);
};
export const NotFound = () => {
const { t } = useLocale();
return (
<UnAvailableMessage title={t("404_page_not_found")}>
<p className="max-w-[50ch]">{t("booker_event_not_found")}</p>
</UnAvailableMessage>
);
};
@@ -0,0 +1,132 @@
import type { Dispatch, SetStateAction } from "react";
import { useCallback, useEffect, useState } from "react";
import useDigitInput from "react-digit-input";
import { useBookerStoreContext } from "@calcom/features/bookings/Booker/BookerStoreProvider";
import { Dialog } from "@calcom/features/components/controlled-dialog";
import { useLocale } from "@calcom/lib/hooks/useLocale";
import { Button } from "@calcom/ui/components/button";
import { DialogContent, DialogFooter, DialogHeader, DialogClose } from "@calcom/ui/components/dialog";
import { Input } from "@calcom/ui/components/form";
import { Label } from "@calcom/ui/components/form";
import { Icon } from "@calcom/ui/components/icon";
export const VerifyCodeDialog = ({
isOpenDialog,
setIsOpenDialog,
email,
isUserSessionRequiredToVerify = true,
verifyCodeWithSessionNotRequired,
verifyCodeWithSessionRequired,
resetErrors,
setIsPending,
isPending,
error,
}: {
isOpenDialog: boolean;
setIsOpenDialog: Dispatch<SetStateAction<boolean>>;
email: string;
isUserSessionRequiredToVerify?: boolean;
verifyCodeWithSessionNotRequired: (code: string, email: string) => void;
verifyCodeWithSessionRequired: (code: string, email: string) => void;
resetErrors: () => void;
isPending: boolean;
setIsPending: (status: boolean) => void;
error: string;
}) => {
const { t } = useLocale();
const [value, setValue] = useState("");
const [hasVerified, setHasVerified] = useState(false);
const setVerificationCode = useBookerStoreContext((state) => state.setVerificationCode);
const digits = useDigitInput({
acceptedCharacters: /^[0-9]$/,
length: 6,
value,
onChange: useCallback((value: string) => {
// whenever there's a change in the input, we reset the error value.
resetErrors();
setValue(value);
}, []),
});
const verifyCode = useCallback(() => {
resetErrors();
setIsPending(true);
if (isUserSessionRequiredToVerify) {
verifyCodeWithSessionRequired(value, email);
} else {
verifyCodeWithSessionNotRequired(value, email);
}
setVerificationCode(value);
setHasVerified(true);
}, [
resetErrors,
setIsPending,
isUserSessionRequiredToVerify,
verifyCodeWithSessionRequired,
value,
email,
verifyCodeWithSessionNotRequired,
setVerificationCode,
]);
useEffect(() => {
// trim the input value because "react-digit-input" creates a string of the given length,
// even when some digits are missing. And finally we use regex to check if the value consists
// of 6 non-empty digits.
if (hasVerified || error || isPending || !/^\d{6}$/.test(value.trim())) return;
verifyCode();
}, [error, isPending, value, hasVerified]);
useEffect(() => setValue(""), [isOpenDialog]);
const digitClassName = "h-12 w-12 text-xl! text-center";
return (
<Dialog
open={isOpenDialog}
onOpenChange={() => {
resetErrors();
}}>
<DialogContent className="sm:max-w-md">
<div className="flex flex-row">
<div className="w-full">
<DialogHeader title={t("verify_your_email")} subtitle={t("enter_digit_code", { email })} />
<Label htmlFor="code">{t("code")}</Label>
<div className="flex flex-row justify-between">
<Input
className={digitClassName}
name="2fa1"
inputMode="decimal"
{...digits[0]}
autoFocus
autoComplete="one-time-code"
/>
<Input className={digitClassName} name="2fa2" inputMode="decimal" {...digits[1]} />
<Input className={digitClassName} name="2fa3" inputMode="decimal" {...digits[2]} />
<Input className={digitClassName} name="2fa4" inputMode="decimal" {...digits[3]} />
<Input className={digitClassName} name="2fa5" inputMode="decimal" {...digits[4]} />
<Input className={digitClassName} name="2fa6" inputMode="decimal" {...digits[5]} />
</div>
{error && (
<div className="mt-2 flex items-center gap-x-2 text-sm text-red-700">
<div>
<Icon name="info" className="h-3 w-3" />
</div>
<p>{error}</p>
</div>
)}
<DialogFooter noSticky>
<DialogClose onClick={() => setIsOpenDialog(false)} />
<Button type="submit" onClick={verifyCode} loading={isPending}>
{t("submit")}
</Button>
</DialogFooter>
</div>
</div>
</DialogContent>
</Dialog>
);
};
@@ -0,0 +1,6 @@
import { vi } from "vitest";
vi.mock("../AvailableTimeSlots", () => ({
AvailableTimeSlots: ({ children }: { children: React.ReactNode }) => (
<div data-testid="available-time-slots">{children}</div>
),
}));
@@ -0,0 +1,4 @@
import { vi } from "vitest";
vi.mock("../DatePicker", () => ({
DatePicker: () => <div data-testid="date-picker">Mock Date Picker</div>,
}));
@@ -0,0 +1,6 @@
import { vi } from "vitest";
vi.mock("../DryRunMessage", () => ({
DryRunMessage: ({ isEmbed }: { isEmbed: boolean }) => (
<div data-testid="dry-run-message">Mock Dry Run Message</div>
),
}));
@@ -0,0 +1,16 @@
import { vi } from "vitest";
vi.mock("../EventMeta", () => ({
EventMeta: () => {
return (
<div>
<h2>Test Event</h2>
<p>Test Description</p>
<div>
<span>30 minutes</span>
<span>Free</span>
</div>
</div>
);
},
}));
@@ -0,0 +1,5 @@
import { vi } from "vitest";
// Mock layout components
vi.mock("../Header", () => ({
Header: ({ children }: { children: React.ReactNode }) => <div data-testid="header">{children}</div>,
}));
@@ -0,0 +1,13 @@
import { vi } from "vitest";
vi.mock("../LargeCalendar", () => ({
LargeCalendar: ({ extraDays, schedule }: { extraDays: number; schedule: any }) => {
return (
<div>
<h2>Test Large Calendar</h2>
<p>Extra Days: {extraDays}</p>
<p>Schedule: {JSON.stringify(schedule)}</p>
</div>
);
},
}));
@@ -0,0 +1,21 @@
import { vi } from "vitest";
const mockOverlayCalendar = vi.fn(() => {
return {
connectedCalendars: [],
overlayBusyDates: [],
onToggleCalendar: vi.fn(),
isOverlayCalendarEnabled: false,
loadingConnectedCalendar: false,
handleClickNoCalendar: vi.fn(),
handleSwitchStateChange: vi.fn(),
handleClickContinue: vi.fn(),
hasSession: false,
};
});
vi.mock("../OverlayCalendar/OverlayCalendar", () => ({
OverlayCalendar: mockOverlayCalendar,
}));
export default mockOverlayCalendar;
@@ -0,0 +1,28 @@
import type React from "react";
import { vi } from "vitest";
vi.mock("../Section", () => {
const BookerSection = ({
children,
className = "",
area,
}: {
children: React.ReactNode;
className?: string;
area?: string | { default: string; month_view: string };
}): React.ReactElement => {
let areaValue: string | undefined;
if (typeof area === "string") {
areaValue = area;
} else {
areaValue = area?.default;
}
return (
// biome-ignore lint/suspicious/noReactSpecificProps: This is a React component that requires className
<div data-testid="booker-section" className={className} data-area={areaValue}>
{children}
</div>
);
};
return { BookerSection };
});
@@ -0,0 +1,122 @@
import type {
DefaultEventLocationType,
EventLocationTypeFromApp,
LocationObject,
} from "@calcom/app-store/locations";
import { getEventLocationType, getTranslatedLocation } from "@calcom/app-store/locations";
import { useIsPlatform } from "@calcom/atoms/hooks/useIsPlatform";
import { useLocale } from "@calcom/lib/hooks/useLocale";
import invertLogoOnDark from "@calcom/lib/invertLogoOnDark";
import classNames from "@calcom/ui/classNames";
import { Icon } from "@calcom/ui/components/icon";
import { Tooltip } from "@calcom/ui/components/tooltip";
const excludeNullValues = (value: unknown) => !!value;
function RenderIcon({
eventLocationType,
isTooltip,
}: {
eventLocationType: DefaultEventLocationType | EventLocationTypeFromApp;
isTooltip: boolean;
}) {
const isPlatform = useIsPlatform();
return (
<img
src={`${isPlatform ? process.env.NEXT_PUBLIC_WEBAPP_URL : ""}${eventLocationType.iconUrl}`}
className={classNames(invertLogoOnDark(eventLocationType?.iconUrl, isTooltip), "me-[10px] h-4 w-4")}
alt={`${eventLocationType.label} icon`}
/>
);
}
function RenderLocationTooltip({ locations }: { locations: LocationObject[] }) {
const { t } = useLocale();
return (
<div className="my-2 me-2 flex w-full flex-col stack-y-3 wrap-break-word">
<p>{t("select_on_next_step")}</p>
{locations.map(
(
location: Pick<Partial<LocationObject>, "link" | "address"> &
Omit<LocationObject, "link" | "address">,
index: number
) => {
const eventLocationType = getEventLocationType(location.type);
if (!eventLocationType) {
return null;
}
const translatedLocation =
location.customLabel || getTranslatedLocation(location, eventLocationType, t);
return (
<div key={`${location.type}-${index}`} className="font-sm flex flex-row items-center">
<RenderIcon eventLocationType={eventLocationType} isTooltip />
<p className="line-clamp-1">{translatedLocation}</p>
</div>
);
}
)}
</div>
);
}
export function AvailableEventLocations({ locations }: { locations: LocationObject[] }) {
const { t } = useLocale();
const isPlatform = useIsPlatform();
const renderLocations = locations.map(
(
location: Pick<Partial<LocationObject>, "link" | "address"> & Omit<LocationObject, "link" | "address">,
index: number
) => {
const eventLocationType = getEventLocationType(location.type);
if (!eventLocationType) {
// It's possible that the location app got uninstalled
return null;
}
const locationName = location?.customLabel || getTranslatedLocation(location, eventLocationType, t);
return (
<div key={`${location.type}-${index}`} className="flex flex-row items-center text-sm font-medium">
{eventLocationType.iconUrl === "/link.svg" ? (
<Icon name="link" className="text-default h-4 w-4 ltr:mr-[10px] rtl:ml-[10px]" />
) : (
<RenderIcon eventLocationType={eventLocationType} isTooltip={false} />
)}
<Tooltip content={locationName}>
<p className="line-clamp-1">{locationName}</p>
</Tooltip>
</div>
);
}
);
const filteredLocations = renderLocations.filter(excludeNullValues) as JSX.Element[];
return filteredLocations.length > 1 ? (
<div className="flex flex-row items-center text-sm font-medium">
{isPlatform ? (
<Icon name="map-pin" className={classNames("me-[10px] h-4 w-4 opacity-70 dark:invert")} />
) : (
<img
src="/map-pin-dark.svg"
className={classNames("me-[10px] h-4 w-4 opacity-70 dark:invert")}
alt="map-pin"
/>
)}
<Tooltip content={<RenderLocationTooltip locations={locations} />}>
<p className="line-clamp-1">
{t("location_options", {
locationCount: filteredLocations.length,
})}
</p>
</Tooltip>
</div>
) : filteredLocations.length === 1 ? (
<div className="text-default mr-6 flex w-full flex-col stack-y-4 wrap-break-word text-sm rtl:mr-2">
{filteredLocations}
</div>
) : null;
}
@@ -0,0 +1,201 @@
import React, { Fragment } from "react";
import { getPaymentAppData } from "@calcom/app-store/_utils/payments/getPaymentAppData";
import { useBookerStore } from "@calcom/features/bookings/Booker/store";
import { PriceIcon } from "@calcom/web/modules/bookings/components/event-meta/PriceIcon";
import type { BookerEvent } from "@calcom/features/bookings/types";
import { useLocale } from "@calcom/lib/hooks/useLocale";
import classNames from "@calcom/ui/classNames";
import { Icon } from "@calcom/ui/components/icon";
import { type IconName } from "@calcom/ui/components/icon";
import { EventDetailBlocks } from "@calcom/features/bookings/types";
import { AvailableEventLocations } from "./AvailableEventLocations";
import { EventDuration } from "./Duration";
import { EventOccurences } from "./Occurences";
import { Price } from "./Price";
type EventDetailsPropsBase = {
event: Pick<
BookerEvent,
| "currency"
| "price"
| "locations"
| "requiresConfirmation"
| "recurringEvent"
| "length"
| "metadata"
| "isDynamic"
>;
className?: string;
};
type EventDetailDefaultBlock = {
blocks?: EventDetailBlocks[];
};
// Rendering a custom block requires passing a name prop,
// which is used as a key for the block.
type EventDetailCustomBlock = {
blocks?: React.FC[];
name: string;
};
type EventDetailsProps = EventDetailsPropsBase & (EventDetailDefaultBlock | EventDetailCustomBlock);
interface EventMetaProps extends React.HTMLAttributes<HTMLDivElement> {
customIcon?: React.ReactNode;
icon?: IconName;
iconUrl?: string;
// Emphasises the text in the block. For now only
// applying in dark mode.
highlight?: boolean;
contentClassName?: string;
isDark?: boolean;
}
/**
* Default order in which the event details will be rendered.
*/
const defaultEventDetailsBlocks = [
EventDetailBlocks.REQUIRES_CONFIRMATION,
EventDetailBlocks.DURATION,
EventDetailBlocks.OCCURENCES,
EventDetailBlocks.LOCATION,
EventDetailBlocks.PRICE,
];
/**
* Helper component that ensures the meta data of an event is
* rendered in a consistent way — adds an icon and children (text usually).
*/
export const EventMetaBlock = ({
customIcon,
icon,
iconUrl,
children,
highlight,
contentClassName,
className,
isDark,
...rest
}: EventMetaProps) => {
if (!React.Children.count(children)) return null;
return (
<div
className={classNames(
"flex items-start justify-start text-sm",
highlight ? "text-emphasis" : "text-text",
className
)}
{...rest}>
{iconUrl ? (
<img
src={iconUrl}
alt=""
// @TODO: Use SVG's instead of images, so we can get rid of the filter.
className={classNames(
"mr-2 mt-[2px] h-4 w-4 shrink-0",
isDark === undefined && "filter-[invert(0.5)_brightness(0.5)]",
(isDark === undefined || isDark) && "dark:filter-[invert(0.65)_brightness(0.9)]"
)}
/>
) : (
<>
{customIcon ||
(!!icon && (
<Icon name={icon} className="relative z-20 mr-2 mt-[2px] h-4 w-4 shrink-0 rtl:ml-2" />
))}
</>
)}
<div className={classNames("relative z-10 max-w-full wrap-break-word", contentClassName)}>{children}</div>
</div>
);
};
/**
* Component that renders event meta data in a structured way, with icons and labels.
* The component can be configured to show only specific blocks by overriding the
* `blocks` prop. The blocks prop takes in an array of block names, defined
* in the `EventDetailBlocks` enum. See the `defaultEventDetailsBlocks` const
* for the default order in which the blocks will be rendered.
*
* As part of the blocks array you can also decide to render a custom React Component,
* which will then also be rendered.
*
* Example:
* const MyCustomBlock = () => <div>Something nice</div>;
* <EventDetails event={event} blocks={[EventDetailBlocks.LOCATION, MyCustomBlock]} />
*/
export const EventDetails = ({ event, blocks = defaultEventDetailsBlocks }: EventDetailsProps) => {
const { t } = useLocale();
const rescheduleUid = useBookerStore((state) => state.rescheduleUid);
const isInstantMeeting = useBookerStore((store) => store.isInstantMeeting);
return (
<>
{blocks.map((block) => {
if (typeof block === "function") {
return <Fragment key={block.name}>{block(event)}</Fragment>;
}
switch (block) {
case EventDetailBlocks.DURATION:
return (
<EventMetaBlock key={block} icon="clock" className="items-center">
<EventDuration event={event} />
</EventMetaBlock>
);
case EventDetailBlocks.LOCATION:
if (!event?.locations?.length || isInstantMeeting) return null;
return (
<EventMetaBlock key={block}>
<AvailableEventLocations locations={event.locations} />
</EventMetaBlock>
);
case EventDetailBlocks.REQUIRES_CONFIRMATION:
if (!event.requiresConfirmation) return null;
return (
<EventMetaBlock key={block} icon="square-check">
{t("requires_confirmation")}
</EventMetaBlock>
);
case EventDetailBlocks.OCCURENCES:
if (!event.recurringEvent || rescheduleUid) return null;
return (
<EventMetaBlock key={block} icon="refresh-ccw">
<EventOccurences event={event} />
</EventMetaBlock>
);
case EventDetailBlocks.PRICE:
const paymentAppData = getPaymentAppData(event);
if (event.price <= 0 || paymentAppData.price <= 0) return null;
return (
<EventMetaBlock
key={block}
customIcon={
<PriceIcon
className="relative z-20 mr-2 mt-[2px] h-4 w-4 shrink-0 rtl:ml-2"
currency={event.currency}
/>
}>
<Price
price={paymentAppData.price}
currency={event.currency}
displayAlternateSymbol={false}
/>
</EventMetaBlock>
);
}
})}
</>
);
};
@@ -0,0 +1,138 @@
import type { TFunction } from "i18next";
import { useEffect, useRef } from "react";
import { useIsPlatform } from "@calcom/atoms/hooks/useIsPlatform";
import { useIsEmbed } from "@calcom/embed-core/embed-iframe";
import { useShouldShowArrows } from "@calcom/web/modules/apps/components/AllApps";
import { useBookerStoreContext } from "@calcom/features/bookings/Booker/BookerStoreProvider";
import type { BookerEvent } from "@calcom/features/bookings/types";
import { useLocale } from "@calcom/lib/hooks/useLocale";
import classNames from "@calcom/ui/classNames";
import { Icon } from "@calcom/ui/components/icon";
/** Render X mins as X hours or X hours Y mins instead of in minutes once >= 60 minutes */
export const getDurationFormatted = (mins: number | undefined, t: TFunction) => {
if (!mins) return null;
const hours = Math.floor(mins / 60);
mins %= 60;
// format minutes string
let minStr = "";
if (mins > 0) {
minStr =
mins === 1
? t("minute_one_short", { count: 1 })
: t("multiple_duration_timeUnit_short", { count: mins, unit: "minute" });
}
// format hours string
let hourStr = "";
if (hours > 0) {
hourStr =
hours === 1
? t("hour_one_short", { count: 1 })
: t("multiple_duration_timeUnit_short", { count: hours, unit: "hour" });
}
if (hourStr && minStr) return `${hourStr} ${minStr}`;
return hourStr || minStr;
};
export const EventDuration = ({
event,
}: {
event: Pick<BookerEvent, "length" | "metadata" | "isDynamic">;
}) => {
const { t } = useLocale();
const itemRefs = useRef<(HTMLLIElement | null)[]>([]);
const isPlatform = useIsPlatform();
const [selectedDuration, setSelectedDuration, state] = useBookerStoreContext((state) => [
state.selectedDuration,
state.setSelectedDuration,
state.state,
]);
const { ref, calculateScroll, leftVisible, rightVisible } = useShouldShowArrows();
const handleLeft = () => {
if (ref.current) {
ref.current.scrollLeft -= 100;
}
};
const handleRight = () => {
if (ref.current) {
ref.current.scrollLeft += 100;
}
};
const isDynamicEvent = "isDynamic" in event && event.isDynamic;
const isEmbed = useIsEmbed();
// Sets initial value of selected duration to the default duration.
useEffect(() => {
// Only store event duration in url if event has multiple durations.
if (!selectedDuration && (event.metadata?.multipleDuration || isDynamicEvent))
setSelectedDuration(event.length);
}, [selectedDuration, setSelectedDuration, event.metadata?.multipleDuration, event.length, isDynamicEvent]);
useEffect(() => {
const timeout = setTimeout(() => {
if (isEmbed) return;
if (selectedDuration && itemRefs.current[selectedDuration]) {
// eslint-disable-next-line @calcom/eslint/no-scroll-into-view-embed -- Called on !isEmbed case
itemRefs.current[selectedDuration]?.scrollIntoView({
behavior: "smooth",
block: "center",
inline: "center",
});
}
}, 100);
return () => clearTimeout(timeout);
}, [selectedDuration, isEmbed]);
if (!event?.metadata?.multipleDuration && !isDynamicEvent)
return <>{getDurationFormatted(event.length, t)}</>;
const durations = event?.metadata?.multipleDuration || [15, 30, 60, 90];
return selectedDuration ? (
<div className="border-default relative mr-5 flex flex-row items-center justify-between rounded-md border">
{leftVisible && (
<button onClick={handleLeft} className="absolute bottom-0 left-0 flex">
<div className="bg-default flex h-9 w-5 items-center justify-end rounded-md">
<Icon name="chevron-left" className="text-subtle h-4 w-4" />
</div>
<div className="to-default flex h-9 w-5 bg-linear-to-l from-transparent" />
</button>
)}
<ul
className="bg-default no-scrollbar flex max-w-full items-center gap-0.5 overflow-x-auto rounded-md p-1"
onScroll={(e) => calculateScroll(e)}
ref={ref}>
{durations
.filter((dur) => state !== "booking" || dur === selectedDuration)
.map((duration, index) => (
<li
data-testId={`multiple-choice-${duration}mins`}
data-active={selectedDuration === duration ? "true" : "false"}
key={index}
onClick={() => setSelectedDuration(duration)}
ref={(el) => (itemRefs.current[duration] = el)}
className={classNames(
selectedDuration === duration ? "bg-emphasis" : "hover:text-emphasis",
"text-default cursor-pointer rounded-[4px] px-3 py-1.5 text-sm leading-tight transition"
)}>
<div className="w-max">{getDurationFormatted(duration, t)}</div>
</li>
))}
</ul>
{rightVisible && (
<button onClick={handleRight} className="absolute bottom-0 right-0 flex">
<div className="to-default flex h-9 w-5 bg-linear-to-r from-transparent" />
<div className="bg-default flex h-9 w-5 items-center justify-end rounded-md">
<Icon name="chevron-right" className="text-subtle h-4 w-4" />
</div>
</button>
)}
</div>
) : null;
};
@@ -0,0 +1,69 @@
import { getEventLocationType, getTranslatedLocation } from "@calcom/app-store/locations";
import type { BookerEvent } from "@calcom/features/bookings/types";
import { useLocale } from "@calcom/lib/hooks/useLocale";
import { Tooltip } from "@calcom/ui/components/tooltip";
import classNames from "@calcom/ui/classNames";
import { EventMetaBlock } from "./Details";
export const EventLocations = ({ event }: { event: BookerEvent }) => {
const { t } = useLocale();
const locations = event.locations;
if (!locations?.length) return null;
const getLocationToDisplay = (location: BookerEvent["locations"][number]) => {
const eventLocationType = getEventLocationType(location.type);
const translatedLocation = getTranslatedLocation(location, eventLocationType, t);
return translatedLocation;
};
const eventLocationType = getEventLocationType(locations[0].type);
const iconUrl = locations.length > 1 || !eventLocationType?.iconUrl ? undefined : eventLocationType.iconUrl;
const icon = locations.length > 1 || !eventLocationType?.iconUrl ? "map-pin" : undefined;
return (
<EventMetaBlock iconUrl={iconUrl} icon={icon} isDark={eventLocationType?.iconUrl?.includes("-dark")}>
{locations.length === 1 && (
<Tooltip content={getLocationToDisplay(locations[0])}>
<div className="" key={locations[0].type}>
{getLocationToDisplay(locations[0])}
</div>
</Tooltip>
)}
{locations.length > 1 && (
<div
key={locations[0].type}
className="before:bg-subtle relative before:pointer-events-none before:absolute before:inset-0 before:bottom-[-5px] before:left-[-30px] before:top-[-5px] before:w-[calc(100%+35px)] before:rounded-md before:py-3 before:opacity-0 before:transition-opacity hover:before:opacity-100">
<Tooltip
content={
<>
<p className="mb-2">{t("select_on_next_step")}</p>
<ul className="pl-1">
{locations.map((location, index) => (
<li key={`${location.type}-${index}`} className="mt-1">
<div className="flex flex-row items-center">
<img
src={getEventLocationType(location.type)?.iconUrl}
className={classNames(
"h-3 w-3 opacity-70 ltr:mr-[10px] rtl:ml-[10px] dark:opacity-100 ",
!getEventLocationType(location.type)?.iconUrl?.startsWith("/app-store")
? "dark:invert-[.65]"
: ""
)}
alt={`${getEventLocationType(location.type)?.label} icon`}
/>
<span>{getLocationToDisplay(location)}</span>
</div>
</li>
))}
</ul>
</>
}>
<span className="relative z-2 py-2">{t("num_locations", { num: locations.length })}</span>
</Tooltip>
</div>
)}
</EventMetaBlock>
);
};
@@ -0,0 +1,98 @@
import { useIsPlatform } from "@calcom/atoms/hooks/useIsPlatform";
import { useIsEmbed } from "@calcom/embed-core/embed-iframe";
import { useBookerStore } from "@calcom/features/bookings/Booker/store";
import type { BookerEvent } from "@calcom/features/bookings/types";
import { getBookerBaseUrlSync } from "@calcom/features/ee/organizations/lib/getBookerBaseUrlSync";
import { getTeamUrlSync } from "@calcom/features/ee/organizations/lib/getTeamUrlSync";
import { getUserAvatarUrl } from "@calcom/lib/getAvatarUrl";
import { SchedulingType } from "@calcom/prisma/enums";
import { AvatarGroup } from "@calcom/ui/components/avatar";
export interface EventMembersProps {
/**
* Used to determine whether all members should be shown or not.
* In case of Round Robin type, members aren't shown.
*/
schedulingType: BookerEvent["schedulingType"];
users: BookerEvent["subsetOfUsers"];
profile: BookerEvent["profile"];
entity: BookerEvent["entity"];
isPrivateLink: boolean;
roundRobinHideOrgAndTeam?: boolean;
}
export const EventMembers = ({
schedulingType,
users,
profile,
entity,
isPrivateLink,
roundRobinHideOrgAndTeam,
}: EventMembersProps) => {
const username = useBookerStore((state) => state.username);
const isDynamic = !!(username && username.indexOf("+") > -1);
const isEmbed = useIsEmbed();
const isPlatform = useIsPlatform();
const showMembers = schedulingType !== SchedulingType.ROUND_ROBIN;
const shownUsers = showMembers ? users : [];
// In some cases we don't show the user's names, but only show the profile name.
const showOnlyProfileName =
(profile.name && schedulingType === SchedulingType.ROUND_ROBIN) ||
!users.length ||
(profile.name !== users[0].name && schedulingType === SchedulingType.COLLECTIVE);
if (schedulingType === SchedulingType.ROUND_ROBIN && roundRobinHideOrgAndTeam) {
return <div className="h-6" />;
}
const orgOrTeamAvatarItem =
isDynamic || (!profile.image && !entity.logoUrl) || !entity.teamSlug
? []
: [
{
// We don't want booker to be able to see the list of other users or teams inside the embed
href:
isEmbed || isPlatform || isPrivateLink || entity.hideProfileLink
? null
: entity.teamSlug
? getTeamUrlSync({ orgSlug: entity.orgSlug, teamSlug: entity.teamSlug })
: getBookerBaseUrlSync(entity.orgSlug),
image: entity.logoUrl ?? profile.image ?? "",
alt: entity.name ?? profile.name ?? "",
title: entity.name ?? profile.name ?? "",
},
];
return (
<>
<AvatarGroup
size="sm"
className="border-muted"
items={[
...orgOrTeamAvatarItem,
...shownUsers.map((user) => ({
href:
isPlatform || isPrivateLink || entity.hideProfileLink
? null
: `${getBookerBaseUrlSync(user.profile?.organization?.slug ?? null)}/${
user.profile?.username
}?redirect=false`,
alt: user.name || "",
title: user.name || "",
image: getUserAvatarUrl(user),
})),
]}
/>
<p className="text-subtle mt-2 text-sm font-semibold">
{showOnlyProfileName
? profile.name
: shownUsers
.map((user) => user.name)
.filter((name) => name)
.join(", ")}
</p>
</>
);
};
@@ -0,0 +1,139 @@
import { useEffect, useState } from "react";
import { useBookerStoreContext } from "@calcom/features/bookings/Booker/BookerStoreProvider";
import type { BookerEvent } from "@calcom/features/bookings/types";
import { useLocale } from "@calcom/lib/hooks/useLocale";
import { parseRecurringDates } from "@calcom/lib/parse-dates";
import { getRecurringFreq } from "@calcom/lib/recurringStrings";
import { getTimeShiftFlags, getFirstShiftFlags } from "@calcom/lib/timeShift";
import { Alert } from "@calcom/ui/components/alert";
import { Badge } from "@calcom/ui/components/badge";
import { Input } from "@calcom/ui/components/form";
import { Tooltip } from "@calcom/ui/components/tooltip";
import { useBookerTime } from "@calcom/features/bookings/Booker/components/hooks/useBookerTime";
export const EventOccurences = ({ event }: { event: Pick<BookerEvent, "recurringEvent"> }) => {
const maxOccurences = event.recurringEvent?.count || null;
const { t, i18n } = useLocale();
const [
setRecurringEventCount,
recurringEventCount,
setRecurringEventCountQueryParam,
recurringEventCountQueryParam,
] = useBookerStoreContext((state) => [
state.setRecurringEventCount,
state.recurringEventCount,
state.setRecurringEventCountQueryParam,
state.recurringEventCountQueryParam,
]);
const selectedTimeslot = useBookerStoreContext((state) => state.selectedTimeslot);
const bookerState = useBookerStoreContext((state) => state.state);
const { timezone, timeFormat } = useBookerTime();
const [warning, setWarning] = useState(false);
const validateAndSetRecurringEventCount = (value: number | string) => {
const inputValue = parseInt(value as string);
const isValid =
!isNaN(inputValue) && inputValue >= 1 && maxOccurences !== null && inputValue <= maxOccurences;
if (isValid) {
setRecurringEventCount(inputValue);
setWarning(false);
} else {
setRecurringEventCount(maxOccurences);
setWarning(true);
}
};
useEffect(() => {
if (!event.recurringEvent?.count) return;
if (recurringEventCountQueryParam) {
validateAndSetRecurringEventCount(recurringEventCountQueryParam);
} else {
setRecurringEventCount(maxOccurences);
setRecurringEventCountQueryParam(maxOccurences);
}
}, [setRecurringEventCount, event.recurringEvent, recurringEventCount, recurringEventCountQueryParam]);
if (!event.recurringEvent) return null;
if (bookerState === "booking" && recurringEventCount && selectedTimeslot) {
const [recurringStrings, recurringDates] = parseRecurringDates(
{
startDate: selectedTimeslot,
timeZone: timezone,
recurringEvent: event.recurringEvent,
recurringCount: recurringEventCount,
selectedTimeFormat: timeFormat,
},
i18n.language
);
const shiftFlags = getTimeShiftFlags({ dates: recurringDates, timezone });
const displayFlags = getFirstShiftFlags(shiftFlags);
return (
<div data-testid="recurring-dates">
{recurringStrings.slice(0, 5).map((timeFormatted, key) => (
<p key={key}>
{timeFormatted}
{displayFlags[key] && (
<>
{" "}
<Badge variant="orange" size="sm">
{t("time_shift")}
</Badge>
</>
)}
</p>
))}
{recurringStrings.length > 5 && (
<Tooltip
content={recurringStrings.slice(5).map((timeFormatted, key) => (
<p key={key}>
{timeFormatted}
{displayFlags[key + 5] && (
<>
{" "}
<Badge variant="orange" size="sm">
{t("time_shift")}
</Badge>
</>
)}
</p>
))}>
<p className=" text-sm">+ {t("plus_more", { count: recurringStrings.length - 5 })}</p>
</Tooltip>
)}
</div>
);
}
return (
<>
{getRecurringFreq({ t, recurringEvent: event.recurringEvent })}
<br />
<Input
className="my-1 mr-3 inline-flex h-[26px] w-[46px] px-1 py-0"
type="number"
min="1"
max={event.recurringEvent.count}
defaultValue={recurringEventCountQueryParam || event.recurringEvent.count}
data-testid="occurrence-input"
onChange={(event) => {
const inputValue = parseInt(event.target.value);
setRecurringEventCountQueryParam(inputValue);
validateAndSetRecurringEventCount(event.target.value);
}}
/>
{t("occurrence", {
count: recurringEventCount || event.recurringEvent.count,
})}
{warning && (
<div className="-ml-4 mr-4 mt-2 flex">
<Alert severity="warning" title={t("enter_number_between_range", { maxOccurences })} />
</div>
)}
</>
);
};
@@ -0,0 +1,6 @@
import { Icon } from "@calcom/ui/components/icon";
export function PayIcon(props: { currency: string; className?: string }) {
const { className, currency } = props;
return <Icon name={currency !== "BTC" ? "credit-card" : "zap"} className={className} />;
}
@@ -0,0 +1,28 @@
import dynamic from "next/dynamic";
import { formatPrice } from "@calcom/lib/currencyConversions";
import type { EventPrice } from "@calcom/features/bookings/types";
const AlbyPriceComponent = dynamic(
() => import("@calcom/app-store/alby/components/AlbyPriceComponent").then((m) => m.AlbyPriceComponent),
{
ssr: false,
}
);
export const Price = ({ price, currency, displayAlternateSymbol = true }: EventPrice) => {
if (price === 0) return null;
const formattedPrice = formatPrice(price, currency);
return currency !== "BTC" ? (
<>{formattedPrice}</>
) : (
<AlbyPriceComponent
displaySymbol={displayAlternateSymbol}
price={price}
formattedPrice={formattedPrice}
/>
);
};
@@ -0,0 +1,8 @@
import { Icon } from "@calcom/ui/components/icon";
import { SatSymbol } from "@calcom/ui/components/icon";
export function PriceIcon(props: { currency: string; className?: string }) {
const { className, currency } = props;
if (currency !== "BTC") return <Icon name="credit-card" className={className} />;
return <SatSymbol className={className} />;
}
@@ -0,0 +1,19 @@
import { SkeletonText } from "@calcom/ui/components/skeleton";
import classNames from "@calcom/ui/classNames";
export const EventMetaSkeleton = () => (
<div className="flex flex-col">
<SkeletonText className="h-6 w-6 rounded-full" />
<SkeletonText className="mt-2 h-5 w-32" />
<SkeletonText className="mt-2 h-8 w-48" />
<div className="mt-8">
{Array.from({ length: 4 }).map((_, i) => (
<div className="mb-2 flex flex-row items-center" key={i}>
<SkeletonText className="mr-3 h-5 w-5 rounded-full" />
<SkeletonText className={classNames("h-6", i > 1 ? "w-24" : "w-32")} />
</div>
))}
</div>
</div>
);
@@ -0,0 +1,21 @@
import classNames from "@calcom/ui/classNames";
interface EventTitleProps {
children: React.ReactNode;
/**
* Option to override the default h1 tag.
*/
as?: "h1" | "h2" | "h3" | "h4" | "h5" | "h6" | "p" | "span";
className?: string;
}
export const EventTitle = ({ children, as, className }: EventTitleProps) => {
const El = as || "h1";
return (
<El
data-testid="event-title"
className={classNames("text-text break-words text-xl font-semibold", className)}>
{children}
</El>
);
};
@@ -0,0 +1,6 @@
export { EventDetails, EventMetaBlock } from "./Details";
export { EventTitle } from "./Title";
export { EventMetaSkeleton } from "./Skeleton";
export { EventMembers } from "./Members";
export { PriceIcon } from "./PriceIcon";
export { PayIcon } from "./PayIcon";
@@ -21,7 +21,7 @@ import {
useIsBackgroundTransparent,
useIsEmbed,
} from "@calcom/embed-core/embed-iframe";
import { Price } from "@calcom/features/bookings/components/event-meta/Price";
import { Price } from "@calcom/web/modules/bookings/components/event-meta/Price";
import { getCalendarLinks, CalendarLinkType } from "@calcom/features/bookings/lib/getCalendarLinks";
import { RATING_OPTIONS, validateRating } from "@calcom/features/bookings/lib/rating";
import { isWithinMinimumRescheduleNotice as isWithinMinimumRescheduleNoticeUtil } from "@calcom/features/bookings/lib/reschedule/isWithinMinimumRescheduleNotice";
@@ -0,0 +1,207 @@
import React, { useEffect, useMemo, useRef } from "react";
import classNames from "@calcom/ui/classNames";
import { CalendarStoreContext, createCalendarStore, useCalendarStore } from "@calcom/features/calendars/weeklyview/state/store";
import "@calcom/features/calendars/weeklyview/styles/styles.css";
import type { CalendarComponentProps } from "@calcom/features/calendars/weeklyview/types/state";
import { getDaysBetweenDates, getHoursToDisplay } from "@calcom/features/calendars/weeklyview/utils";
import { DateValues } from "./DateValues";
import { CurrentTime } from "./currentTime";
import { AvailableCellsForDay, EmptyCell } from "./event/Empty";
import { EventList } from "./event/EventList";
import { SchedulerColumns } from "./grid";
import { SchedulerHeading } from "./heading/SchedulerHeading";
import { HorizontalLines } from "./horizontalLines";
import { Spinner } from "./spinner/Spinner";
import { VerticalLines } from "./verticalLines";
function CalendarInner(props: CalendarComponentProps) {
const container = useRef<HTMLDivElement | null>(null);
const containerNav = useRef<HTMLDivElement | null>(null);
const containerOffset = useRef<HTMLDivElement | null>(null);
const schedulerGrid = useRef<HTMLOListElement | null>(null);
const initialState = useCalendarStore((state) => state.initState);
const startDate = useCalendarStore((state) => state.startDate);
const endDate = useCalendarStore((state) => state.endDate);
const startHour = useCalendarStore((state) => state.startHour || 0);
const endHour = useCalendarStore((state) => state.endHour || 23);
const usersCellsStopsPerHour = useCalendarStore((state) => state.gridCellsPerHour || 4);
const availableTimeslots = useCalendarStore((state) => state.availableTimeslots);
const hideHeader = useCalendarStore((state) => state.hideHeader);
const timezone = useCalendarStore((state) => state.timezone);
const showBackgroundPattern = useCalendarStore((state) => state.showBackgroundPattern);
const showBorder = useCalendarStore((state) => state.showBorder ?? true);
const borderColor = useCalendarStore((state) => state.borderColor ?? "default");
const scrollToCurrentTime = useCalendarStore((state) => state.scrollToCurrentTime ?? true);
const days = useMemo(() => getDaysBetweenDates(startDate, endDate), [startDate, endDate]);
const hours = useMemo(
() => getHoursToDisplay(startHour || 0, endHour || 23, timezone),
[startHour, endHour, timezone]
);
const numberOfGridStopsPerDay = hours.length * usersCellsStopsPerHour;
const hourSize = 58;
// Initalise State on initial mount and when props change
useEffect(() => {
initialState(props);
}, [props, initialState]);
return (
<MobileNotSupported>
<div
className={classNames("scheduler-wrapper flex h-full w-full flex-col")}
style={
{
"--one-minute-height": `calc(${hourSize}px/60)`,
"--gridDefaultSize": `${hourSize}px`,
} as React.CSSProperties // This can't live in the css file because it's a dynamic value and css variable gets super
}>
{hideHeader !== true && <SchedulerHeading />}
{props.isPending && <Spinner />}
<div
ref={container}
className="bg-default dark:bg-cal-muted relative isolate flex h-full flex-auto flex-col">
<div
style={{ width: "165%" }}
className="flex max-w-full flex-none flex-col sm:max-w-none md:max-w-full">
<DateValues
containerNavRef={containerNav}
days={days}
showBorder={showBorder}
borderColor={borderColor}
/>
<div className="relative flex flex-auto">
<CurrentTime timezone={timezone} scrollToCurrentTime={scrollToCurrentTime} />
<div
className={classNames(
"bg-default dark:bg-cal-muted ring-muted sticky left-0 z-10 w-16 flex-none ring-1",
showBorder &&
(borderColor === "subtle"
? "border-subtle border-l border-r"
: "border-default border-l border-r")
)}
/>
<div
className="grid flex-auto grid-cols-1 grid-rows-1 [--disabled-gradient-background:#F8F9FB] [--disabled-gradient-foreground:#E6E7EB] dark:[--disabled-gradient-background:#262626] dark:[--disabled-gradient-foreground:#393939]"
style={
showBackgroundPattern === false
? undefined
: {
backgroundColor: "var(--disabled-gradient-background)",
background:
"repeating-linear-gradient(-45deg, var(--disabled-gradient-background), var(--disabled-gradient-background) 2.5px, var(--disabled-gradient-foreground) 2.5px, var(--disabled-gradient-foreground) 5px)",
}
}>
<HorizontalLines
hours={hours}
numberOfGridStopsPerCell={usersCellsStopsPerHour}
containerOffsetRef={containerOffset}
borderColor={borderColor}
/>
<VerticalLines days={days} borderColor={borderColor} />
<SchedulerColumns
offsetHeight={containerOffset.current?.offsetHeight}
gridStopsPerDay={numberOfGridStopsPerDay}>
{/*Loop over events per day */}
{days.map((day, i) => {
return (
<li key={day.toISOString()} className="relative" style={{ gridColumnStart: i + 1 }}>
<EventList day={day} />
{/* <BlockedList day={day} containerRef={container} /> */}
</li>
);
})}
</SchedulerColumns>
{/* Empty Cells */}
<SchedulerColumns
ref={schedulerGrid}
offsetHeight={containerOffset.current?.offsetHeight}
gridStopsPerDay={numberOfGridStopsPerDay}>
<>
{[...Array(days.length)].map((_, i) => (
<li
className="relative"
key={i}
style={{
gridColumnStart: i + 1,
gridRow: `1 / span ${numberOfGridStopsPerDay}`,
}}>
{/* While startDate < endDate: */}
{availableTimeslots ? (
<AvailableCellsForDay
key={days[i].toISOString()}
timezone={timezone}
day={days[i]}
startHour={startHour}
availableSlots={availableTimeslots}
/>
) : (
<>
{[...Array(numberOfGridStopsPerDay)].map((_, j) => {
const key = `${i}-${j}`;
return (
<EmptyCell
key={key}
day={days[i]}
gridCellIdx={j}
totalGridCells={numberOfGridStopsPerDay}
selectionLength={endHour - startHour}
startHour={startHour}
timezone={timezone}
/>
);
})}
</>
)}
</li>
))}
</>
</SchedulerColumns>
</div>
</div>
</div>
</div>
</div>
</MobileNotSupported>
);
}
export function Calendar(props: CalendarComponentProps) {
const storeRef = useRef<ReturnType<typeof createCalendarStore> | null>(null);
if (!storeRef.current) {
storeRef.current = createCalendarStore();
storeRef.current.getState().initState(props);
}
useEffect(() => {
if (storeRef.current) {
storeRef.current.getState().initState(props);
}
}, [props]);
return (
<CalendarStoreContext.Provider value={storeRef.current}>
<CalendarInner {...props} />
</CalendarStoreContext.Provider>
);
}
/** @todo Will be removed once we have mobile support */
const MobileNotSupported = ({ children }: { children: React.ReactNode }) => {
return (
<>
<div className="flex h-full flex-col items-center justify-center sm:hidden">
<h1 className="text-2xl font-bold">Mobile not supported yet </h1>
<p className="text-subtle">Please use a desktop browser to view this page</p>
</div>
<div className="hidden h-full sm:block">{children}</div>
</>
);
};
@@ -0,0 +1,115 @@
import React from "react";
import dayjs from "@calcom/dayjs";
import { useLocale } from "@calcom/lib/hooks/useLocale";
import classNames from "@calcom/ui/classNames";
import { useCalendarStore } from "@calcom/features/calendars/weeklyview/state/store";
import type { BorderColor } from "@calcom/features/calendars/weeklyview/types/common";
type Props = {
showBorder: boolean;
borderColor: BorderColor;
days: dayjs.Dayjs[];
containerNavRef: React.RefObject<HTMLDivElement>;
};
export function DateValues({ showBorder, borderColor, days, containerNavRef }: Props) {
const { i18n } = useLocale();
const timezone = useCalendarStore((state) => state.timezone);
const showTimezone = useCalendarStore((state) => state.showTimezone ?? false);
const formatDate = (date: dayjs.Dayjs): string => {
return new Intl.DateTimeFormat(i18n.language, { weekday: "short" }).format(date.toDate());
};
const getTimezoneDisplay = () => {
if (!showTimezone || !timezone) return null;
try {
const timeRaw = dayjs().tz(timezone);
const utcOffsetInMinutes = timeRaw.utcOffset();
// Convert offset to decimal hours
const offsetInHours = Math.abs(utcOffsetInMinutes / 60);
const sign = utcOffsetInMinutes < 0 ? "-" : "+";
// If offset is 0, just return "GMT"
if (utcOffsetInMinutes === 0) {
return "GMT";
}
// Format as decimal (e.g., 1.5 for 1:30, 1 for 1:00)
const offsetFormatted = `${sign}${offsetInHours}`;
return `GMT ${offsetFormatted}`;
} catch {
// Fallback to showing the timezone name if formatting fails
return timezone.split("/").pop()?.replace(/_/g, " ") || timezone;
}
};
return (
<div
ref={containerNavRef}
className={classNames(
"bg-default dark:bg-cal-muted top-(--calendar-dates-sticky-offset,0px) z-80 sticky flex-none border-b",
borderColor === "subtle" ? "border-b-subtle" : "border-b-default",
showBorder && (borderColor === "subtle" ? "border-r-subtle border-r" : "border-r-default border-r")
)}>
<div className="text-subtle flex leading-6 sm:hidden" data-dayslength={days.length}>
{days.map((day) => {
const isToday = dayjs().isSame(day, "day");
return (
<button
key={day.toString()}
type="button"
className="flex flex-1 flex-col items-center pb-3 pt-2">
{day.format("dd")}{" "}
<span
className={classNames(
"text-emphasis mt-1 flex h-8 w-8 items-center justify-center font-medium",
isToday && "bg-inverted text-inverted rounded-sm"
)}>
{day.format("D")}
</span>
</button>
);
})}
</div>
<div className="text-subtle -mr-px hidden auto-cols-fr leading-6 sm:flex">
<div
className={classNames(
"col-end-1 flex w-16 items-center justify-center",
showBorder &&
(borderColor === "subtle" ? "border-l-subtle border-l" : "border-l-default border-l")
)}>
{showTimezone && timezone && (
<span className="text-muted text-xs font-medium">{getTimezoneDisplay()}</span>
)}
</div>
{days.map((day) => {
const isToday = dayjs().isSame(day, "day");
return (
<div
key={day.toString()}
className={classNames(
"flex flex-1 items-center justify-center py-3 text-xs font-medium uppercase",
isToday && "text-default"
)}>
<span>
{formatDate(day)}{" "}
<span
className={classNames(
"items-center justify-center p-1",
isToday && "bg-brand-default text-brand ml-1 rounded-md"
)}>
{day.format("DD")}
</span>
</span>
</div>
);
})}
</div>
</div>
);
}
@@ -0,0 +1,129 @@
import { useMemo } from "react";
import { shallow } from "zustand/shallow";
import dayjs from "@calcom/dayjs";
import { useCalendarStore } from "@calcom/features/calendars/weeklyview/state/store";
import { BlockedTimeCell } from "./BlockedTimeCell";
type Props = {
day: dayjs.Dayjs;
containerRef: React.RefObject<HTMLDivElement>;
};
function roundX(x: number, roundBy: number) {
return Math.round(x / roundBy) * roundBy;
}
type BlockedDayProps = {
startHour: number;
endHour: number;
day: dayjs.Dayjs;
};
function BlockedBeforeToday({ day, startHour, endHour }: BlockedDayProps) {
return (
<>
{day.isBefore(dayjs(), "day") && (
<div
key={day.format("YYYY-MM-DD")}
className="absolute z-40 w-full"
style={{
top: `var(--one-minute-height)`,
zIndex: 60,
height: `calc(${(endHour + 1 - startHour) * 60} * var(--one-minute-height))`, // Add 1 to endHour to include the last hour that we add to display the last vertical line
}}>
<BlockedTimeCell />
</div>
)}
</>
);
}
function BlockedToday({
day,
startHour,
gridCellsPerHour,
endHour,
}: BlockedDayProps & { gridCellsPerHour: number }) {
const dayStart = useMemo(() => day.startOf("day").hour(startHour), [day, startHour]);
const dayEnd = useMemo(() => day.startOf("day").hour(endHour), [day, endHour]);
const dayEndInMinutes = useMemo(() => dayEnd.diff(dayStart, "minutes"), [dayEnd, dayStart]);
let nowComparedToDayStart = useMemo(() => dayjs().diff(dayStart, "minutes"), [dayStart]);
if (nowComparedToDayStart > dayEndInMinutes) nowComparedToDayStart = dayEndInMinutes;
return (
<>
{day.isToday() && (
<div
key={day.format("YYYY-MM-DD")}
className="absolute z-40 w-full"
style={{
top: `var(--one-minute-height)`, // Still need this as this var takes into consideration the offset of the "AllDayEvents" bar
zIndex: 60,
height: `calc(${roundX(
nowComparedToDayStart,
60 / gridCellsPerHour
)} * var(--one-minute-height) - 2px)`, // We minus the border width to make it 🧹
}}>
<BlockedTimeCell />
</div>
)}
</>
);
}
export function BlockedList({ day }: Props) {
const { startHour, blockingDates, endHour, gridCellsPerHour } = useCalendarStore(
(state) => ({
startHour: state.startHour || 0,
endHour: state.endHour || 23,
blockingDates: state.blockingDates,
gridCellsPerHour: state.gridCellsPerHour || 4,
}),
shallow
);
return (
<>
<BlockedBeforeToday day={day} startHour={startHour} endHour={endHour} />
<BlockedToday gridCellsPerHour={gridCellsPerHour} day={day} startHour={startHour} endHour={endHour} />
{blockingDates &&
blockingDates.map((event, i) => {
const dayStart = day.startOf("day").hour(startHour);
const blockingStart = dayjs(event.start);
const eventEnd = dayjs(event.end);
const eventStart = dayStart.isAfter(blockingStart) ? dayStart : blockingStart;
if (!eventStart.isSame(day, "day")) {
return null;
}
if (eventStart.isBefore(dayjs())) {
if (eventEnd.isBefore(dayjs())) {
return null;
}
}
const eventDuration = eventEnd.diff(eventStart, "minutes");
const eventStartHour = eventStart.hour();
const eventStartDiff = (eventStartHour - (startHour || 0)) * 60;
return (
<div
key={`${eventStart.toISOString()}-${i}`}
className="absolute w-full"
style={{
zIndex: 60,
top: `calc(${eventStartDiff}*var(--one-minute-height))`,
height: `calc(${eventDuration}*var(--one-minute-height))`,
}}>
<BlockedTimeCell />
</div>
);
})}
</>
);
}
@@ -0,0 +1,17 @@
import classNames from "@calcom/ui/classNames";
export function BlockedTimeCell() {
return (
<div
className={classNames(
"group absolute inset-0 flex h-full flex-col hover:cursor-not-allowed",
"[--disabled-gradient-background:#E5E7EB] [--disabled-gradient-foreground:#D1D5DB] dark:[--disabled-gradient-background:#262626] dark:[--disabled-gradient-foreground:#393939]"
)}
style={{
backgroundColor: "#D1D5DB",
background:
"repeating-linear-gradient( -45deg, var(--disabled-gradient-background), var(--disabled-gradient-background) 2.5px, var(--disabled-gradient-foreground) 2.5px, var(--disabled-gradient-foreground) 6.5px )",
}}
/>
);
}
@@ -0,0 +1,68 @@
import { useEffect, useState, useRef } from "react";
import dayjs from "@calcom/dayjs";
import { useTimePreferences } from "@calcom/features/bookings/lib";
import { useCalendarStore } from "@calcom/features/calendars/weeklyview/state/store";
function calculateMinutesFromStart(startHour: number, currentHour: number, currentMinute: number) {
const startMinute = startHour * 60;
const currentMinuteOfDay = currentHour * 60 + currentMinute;
return currentMinuteOfDay - startMinute;
}
export function CurrentTime({
timezone,
scrollToCurrentTime = true,
}: {
timezone: string;
scrollToCurrentTime?: boolean;
}) {
const { timeFormat } = useTimePreferences();
const currentTimeRef = useRef<HTMLDivElement>(null);
const [scrolledIntoView, setScrolledIntoView] = useState(false);
const [currentTimePos, setCurrentTimePos] = useState<number | null>(null);
const { startHour, endHour } = useCalendarStore((state) => ({
startHour: state.startHour || 0,
endHour: state.endHour || 23,
}));
useEffect(() => {
// Set the container scroll position based on the current time.
const currentDateTime = dayjs().tz(timezone); // Get current date and time in the specified timezone
const currentHour = currentDateTime.hour();
const currentMinute = currentDateTime.minute();
if (currentHour > endHour || currentHour < startHour) {
setCurrentTimePos(null);
}
const minutesFromStart = calculateMinutesFromStart(startHour, currentHour, currentMinute);
setCurrentTimePos(minutesFromStart);
if (!scrollToCurrentTime || !currentTimeRef.current || scrolledIntoView) return;
// Within a small timeout so element has time to render.
setTimeout(() => {
// Doesn't seem to cause any issue. Put it under condition if needed
currentTimeRef?.current?.scrollIntoView({ block: "center" });
setScrolledIntoView(true);
}, 100);
}, [startHour, endHour, scrolledIntoView, timezone, scrollToCurrentTime]);
return (
<div
ref={currentTimeRef}
className="absolute top-0 z-40 flex h-px items-center justify-center text-xs"
aria-hidden="true"
style={{
top: `calc(${currentTimePos}*var(--one-minute-height) + var(--calendar-offset-top))`,
zIndex: 70,
}}>
<div className="w-16 pr-2 text-right">{dayjs().tz(timezone).format(timeFormat)}</div>
<div className="bg-inverted h-3 w-px" />
<div className="bg-inverted h-px w-screen" />
</div>
);
}
@@ -0,0 +1,219 @@
import { useMemo } from "react";
import { shallow } from "zustand/shallow";
import type { Dayjs } from "@calcom/dayjs";
import dayjs from "@calcom/dayjs";
import { useTimePreferences } from "@calcom/features/bookings/lib";
import classNames from "@calcom/ui/classNames";
import { OutOfOfficeInSlots } from "@calcom/web/modules/bookings/components/OutOfOfficeInSlots";
import { useCalendarStore } from "@calcom/features/calendars/weeklyview/state/store";
import type { CalendarAvailableTimeslots } from "@calcom/features/calendars/weeklyview/types/state";
import type { GridCellToDateProps } from "@calcom/features/calendars/weeklyview/utils";
import { gridCellToDateTime } from "@calcom/features/calendars/weeklyview/utils";
type EmptyCellProps = GridCellToDateProps & {
isDisabled?: boolean;
topOffsetMinutes?: number;
};
export function EmptyCell(props: EmptyCellProps) {
const cellToDate = gridCellToDateTime({
day: props.day,
gridCellIdx: props.gridCellIdx,
totalGridCells: props.totalGridCells,
selectionLength: props.selectionLength,
startHour: props.startHour,
timezone: props.timezone,
});
const minutesFromStart = (cellToDate.hour() - props.startHour) * 60 + cellToDate.minute();
return <Cell topOffsetMinutes={minutesFromStart} timeSlot={dayjs(cellToDate).tz(props.timezone)} />;
}
type AvailableCellProps = {
timezone: string;
availableSlots: CalendarAvailableTimeslots;
day: GridCellToDateProps["day"];
startHour: GridCellToDateProps["startHour"];
};
export function AvailableCellsForDay({ timezone, availableSlots, day, startHour }: AvailableCellProps) {
const date = dayjs(day);
const dateFormatted = date.format("YYYY-MM-DD");
const slotsForToday = availableSlots && availableSlots[dateFormatted];
const slots = useMemo(() => {
const calculatedSlots: {
slot: CalendarAvailableTimeslots[string][number];
topOffsetMinutes: number;
firstSlot?: CalendarAvailableTimeslots[string][number];
timezone?: string;
}[] = [];
// first and last slot for ooo to display range correctly in week view
let firstSlotIndex = -1;
let lastSlotIndex = -1;
let areAllSlotsAway = true;
let startEndTimeDuration = 0;
slotsForToday?.forEach((slot, index) => {
const startTime = dayjs(slot.start).tz(timezone);
const topOffsetMinutes = (startTime.hour() - startHour) * 60 + startTime.minute();
calculatedSlots.push({ slot, topOffsetMinutes });
if (!slot.away) {
areAllSlotsAway = false;
} else {
if (firstSlotIndex === -1) {
firstSlotIndex = index;
}
lastSlotIndex = index;
}
});
if (areAllSlotsAway && firstSlotIndex !== -1) {
const firstSlot = slotsForToday[firstSlotIndex];
const lastSlot = slotsForToday[lastSlotIndex];
startEndTimeDuration = dayjs(lastSlot.end).diff(dayjs(firstSlot.start), "minutes");
if (firstSlot.toUser == null && !firstSlot.showNotePublicly) {
return null;
}
// This will return null if all slots are away and the first slot has no user
return {
slots: calculatedSlots,
startEndTimeDuration,
firstSlot,
timezone,
};
}
return { slots: calculatedSlots, startEndTimeDuration };
}, [slotsForToday, startHour, timezone]);
if (slots === null) return null;
if (slots.startEndTimeDuration) {
const { firstSlot, startEndTimeDuration } = slots;
return (
<CustomCell
timeSlot={dayjs(firstSlot?.start).tz(slots.timezone)}
topOffsetMinutes={slots.slots[0]?.topOffsetMinutes}
startEndTimeDuration={startEndTimeDuration}>
<OutOfOfficeInSlots
fromUser={firstSlot?.fromUser}
toUser={firstSlot?.toUser}
reason={firstSlot?.reason}
emoji={firstSlot?.emoji}
notes={firstSlot?.notes}
showNotePublicly={firstSlot?.showNotePublicly}
borderDashed={false}
date={dateFormatted}
className="pb-0"
/>
</CustomCell>
);
}
return (
<>
{slots.slots.map((slot, index) => (
<Cell
key={index}
timeSlot={dayjs(slot.slot.start).tz(timezone)}
topOffsetMinutes={slot.topOffsetMinutes}
/>
))}
</>
);
}
type CellProps = {
isDisabled?: boolean;
topOffsetMinutes?: number;
timeSlot: Dayjs;
};
function Cell({ isDisabled, topOffsetMinutes, timeSlot }: CellProps) {
const { timeFormat } = useTimePreferences();
const { onEmptyCellClick, hoverEventDuration } = useCalendarStore(
(state) => ({
onEmptyCellClick: state.onEmptyCellClick,
hoverEventDuration: state.hoverEventDuration,
}),
shallow
);
return (
<div
className={classNames(
"group flex w-[calc(100%-1px)] items-center justify-center",
isDisabled && "pointer-events-none",
!isDisabled && "bg-default dark:bg-cal-muted",
topOffsetMinutes && "absolute"
)}
data-disabled={isDisabled}
data-slot={timeSlot.toISOString()}
data-testid="calendar-empty-cell"
style={{
height: `calc(${hoverEventDuration}*var(--one-minute-height))`,
overflow: "visible",
top: topOffsetMinutes ? `calc(${topOffsetMinutes}*var(--one-minute-height))` : undefined,
}}
onClick={() => {
onEmptyCellClick?.(timeSlot.toDate());
}}>
{!isDisabled && hoverEventDuration !== 0 && (
<div
className={classNames(
"bg-brand-default hover:bg-brand-default text-brand dark:border-emphasis absolute hidden rounded-[4px] p-[6px] text-xs font-semibold leading-5 group-hover:flex group-hover:cursor-pointer",
hoverEventDuration && hoverEventDuration > 15 && "items-start pt-3",
hoverEventDuration && hoverEventDuration < 15 && "items-center"
)}
style={{
height: `calc(${hoverEventDuration}*var(--one-minute-height) - 2px)`,
zIndex: 80,
// @TODO: This used to be 90% as per Sean's work. I think this was needed when
// multiple events are stacked next to each other. We might need to add this back later.
width: "calc(100% - 2px)",
}}>
<div className="text-ellipsis leading-0">{timeSlot.format(timeFormat)}</div>
</div>
)}
</div>
);
}
function CustomCell({
timeSlot,
children,
topOffsetMinutes,
startEndTimeDuration,
}: CellProps & { children: React.ReactNode; startEndTimeDuration?: number }) {
return (
<div
className={classNames(
"bg-default dark:bg-cal-muted group absolute z-65 flex w-[calc(100%-1px)] items-center justify-center"
)}
data-slot={timeSlot.toISOString()}
style={{
top: topOffsetMinutes ? `calc(${topOffsetMinutes}*var(--one-minute-height))` : undefined,
overflow: "visible",
}}>
<div
className={classNames(
"dark:border-emphasis bg-default dark:bg-cal-muted cursor-pointer rounded-[4px] p-[6px] text-xs font-semibold dark:text-white"
)}
style={{
height: `calc(${startEndTimeDuration}*var(--one-minute-height) - 2px)`,
width: "calc(100% - 2px)",
}}>
{children}
</div>
</div>
);
}
@@ -0,0 +1,163 @@
import { cva } from "class-variance-authority";
import dayjs from "@calcom/dayjs";
import type { BookingStatus } from "@calcom/prisma/enums";
import classNames from "@calcom/ui/classNames";
import { Tooltip } from "@calcom/ui/components/tooltip";
import type { CalendarEvent } from "@calcom/features/calendars/weeklyview/types/events";
type EventProps = {
event: CalendarEvent;
currentlySelectedEventId?: number;
eventDuration: number;
onEventClick?: (event: CalendarEvent) => void;
disabled?: boolean;
isHovered?: boolean;
};
const eventClasses = cva(
"group flex h-full w-full overflow-hidden rounded-[6px] px-[6px] text-xs leading-5 border-default font-medium",
{
variants: {
status: {
ACCEPTED: "bg-subtle hover:bg-emphasis text-emphasis border-[1px] border-default",
PENDING: "bg-subtle text-subtle border-[1px] border-dashed border-default",
REJECTED: "bg-subtle border-[1px] border-dashed text-subtle line-through",
CANCELLED: "bg-subtle border-[1px] border-dashed text-subtle line-through",
AWAITING_HOST: "bg-subtle text-emphasis border-[1px] border-dashed border-default",
},
disabled: {
true: "hover:cursor-default",
false: "hover:cursor-pointer",
},
selected: {
true: "",
false: "",
},
borderOnly: {
true: "bg-transparent border-[1.5px] border-subtle border-dashed opacity-60",
false: "",
},
},
}
);
const STATUS_COLOR_MAP: Record<BookingStatus, string> = {
ACCEPTED: "bg-green-500",
PENDING: "bg-orange-500",
REJECTED: "bg-red-500",
CANCELLED: "bg-red-500",
AWAITING_HOST: "bg-blue-500",
};
// Maps booking status to color classes for the color bar
// Follows the same pattern as BookingDetailsSheet badge variants
const getStatusColorClass = (status?: BookingStatus): string | undefined => {
if (!status) return undefined;
return STATUS_COLOR_MAP[status];
};
export function Event({
event,
currentlySelectedEventId,
eventDuration,
disabled,
onEventClick,
isHovered = false,
}: EventProps) {
const selected = currentlySelectedEventId === event.id;
const { options } = event;
// Use custom color if provided, otherwise derive from status
const colorClass = !options?.color ? getStatusColorClass(options?.status) : undefined;
const Component = onEventClick ? "button" : "div";
const dayOfWeek = dayjs(event.start).day();
const tooltipSide = dayOfWeek >= 1 && dayOfWeek <= 4 ? "right" : "left";
const tooltipContent = (
<div className="flex min-w-[200px] max-w-[300px] flex-col gap-1 py-1">
<div className="flex items-start gap-2">
{(options?.color || colorClass) && (
<div
className={classNames("mt-1 h-3 w-1 shrink-0 rounded-sm", colorClass)}
style={options?.color ? { backgroundColor: options.color } : undefined}></div>
)}
<div className="flex-1">
<div className="font-semibold leading-tight">{event.title}</div>
{!event.options?.hideTime && (
<div className="text-inverted-muted mt-1 text-xs">
{dayjs(event.start).format("HH:mm")} - {dayjs(event.end).format("HH:mm")}
</div>
)}
{event.description && (
<div className="text-inverted-muted mt-1 text-xs leading-snug">{event.description}</div>
)}
{options?.status && options.status !== "ACCEPTED" && (
<div className="text-inverted-muted mt-1 text-xs capitalize">
{options.status.toLowerCase().replace("_", " ")}
</div>
)}
</div>
</div>
</div>
);
const displayType = eventDuration < 40 ? "single-line" : eventDuration < 45 ? "multi-line" : "full";
return (
<Tooltip content={tooltipContent} className="max-w-none" side={tooltipSide}>
<Component
onClick={() => onEventClick?.(event)} // Note this is not the button event. It is the calendar event.
className={classNames(
eventClasses({
status: options?.status,
disabled,
selected,
borderOnly: options?.borderOnly ?? false,
}),
options?.className,
(isHovered || selected) && "ring-brand-default shadow-lg ring-2 ring-offset-0"
)}
style={{
transition: "all 100ms ease-out",
}}>
{(options?.color || colorClass) && (
<div
className={classNames("-ml-1.5 mr-1.5 h-full w-[3px] shrink-0", colorClass)}
style={options?.color ? { backgroundColor: options.color } : undefined}></div>
)}
<div className={classNames("flex w-full", displayType !== "single-line" && "flex-col py-1")}>
{displayType === "single-line" && (
<div
className={classNames(
"flex w-full shrink-0 gap-2 overflow-hidden text-ellipsis whitespace-nowrap text-left leading-4",
"items-center"
)}>
<span>{event.title}</span>
{!event.options?.hideTime && (
<p className="text-subtle mt-1 w-full whitespace-nowrap text-left text-[10px] leading-none">
{dayjs(event.start).format("HH:mm")} - {dayjs(event.end).format("HH:mm")}
</p>
)}
</div>
)}
{displayType !== "single-line" && (
<p className={classNames("shrink-0 whitespace-nowrap text-left leading-4")}>{event.title}</p>
)}
{displayType !== "single-line" && !event.options?.hideTime && (
<p className="text-subtle mt-1 whitespace-nowrap text-left text-[10px] leading-none">
{dayjs(event.start).format("HH:mm")} - {dayjs(event.end).format("HH:mm")}
</p>
)}
{displayType === "full" && event.description && (
<p className="text-subtle mt-1 text-left text-[10px] leading-none">{event.description}</p>
)}
</div>
</Component>
</Tooltip>
);
}
@@ -0,0 +1,135 @@
import { useEffect, useMemo, useState } from "react";
import { shallow } from "zustand/shallow";
import dayjs from "@calcom/dayjs";
import classNames from "@calcom/ui/classNames";
import { useCalendarStore } from "@calcom/features/calendars/weeklyview/state/store";
import { calculateEventLayouts, createLayoutMap } from "@calcom/features/calendars/weeklyview/utils/overlap";
import { Event } from "./Event";
type Props = {
day: dayjs.Dayjs;
};
export function EventList({ day }: Props) {
const { startHour, events, eventOnClick, selectedBookingUid } = useCalendarStore(
(state) => ({
startHour: state.startHour,
events: state.events,
eventOnClick: state.onEventClick,
selectedBookingUid: state.selectedBookingUid,
}),
shallow
);
const [hoveredEventId, setHoveredEventId] = useState<number | null>(null);
const dayEvents = useMemo(() => {
return events.filter((event) => {
return dayjs(event.start).isSame(day, "day") && !event.options?.allDay;
});
}, [events, day]);
const layoutMap = useMemo(() => {
const layouts = calculateEventLayouts(dayEvents);
return createLayoutMap(layouts);
}, [dayEvents]);
const eventCalculations = useMemo(() => {
return new Map(
dayEvents.map((event) => {
const eventStart = dayjs(event.start);
const eventEnd = dayjs(event.end);
const eventDuration = eventEnd.diff(eventStart, "minutes");
const eventStartHour = eventStart.hour();
const eventStartDiff = (eventStartHour - (startHour || 0)) * 60 + eventStart.minute();
return [
event.id,
{
eventStart,
eventDuration,
eventStartDiff,
},
];
})
);
}, [dayEvents, startHour]);
// Find which overlap group the hovered event belongs to
const hoveredEventLayout = hoveredEventId ? layoutMap.get(hoveredEventId) : null;
const hoveredGroupIndex = hoveredEventLayout?.groupIndex ?? null;
// Find the event ID that matches the selected booking UID (only for events on this day)
const selectedEventId = useMemo(() => {
if (!selectedBookingUid) return undefined;
const matchingEvent = dayEvents.find((event) => event.options?.bookingUid === selectedBookingUid);
return matchingEvent?.id;
}, [dayEvents, selectedBookingUid]);
// Scroll to the selected event when it changes
useEffect(() => {
if (selectedEventId === undefined) return;
// Use requestAnimationFrame to ensure the DOM has updated
requestAnimationFrame(() => {
const eventElement = document.querySelector(`[data-calendar-event-id="${selectedEventId}"]`);
if (eventElement) {
eventElement.scrollIntoView({
behavior: "smooth",
block: "nearest",
});
}
});
}, [selectedEventId]);
return (
<>
{dayEvents.map((event) => {
const layout = layoutMap.get(event.id);
if (!layout) return null;
const calc = eventCalculations.get(event.id);
if (!calc) return null;
const { eventStart, eventDuration, eventStartDiff } = calc;
const isHovered = hoveredEventId === event.id;
const isSelected = selectedEventId === event.id;
const isInHoveredGroup = hoveredGroupIndex !== null && layout.groupIndex === hoveredGroupIndex;
const zIndex = isHovered || isSelected ? 79 : layout.baseZIndex;
return (
<div
key={`${event.id}-${eventStart.toISOString()}`}
className={classNames(
"absolute transition-all duration-100 ease-out",
event.options?.borderOnly && "pointer-events-none"
)}
data-testid={event.options?.["data-test-id"]}
data-calendar-event-id={event.id}
onMouseEnter={() => setHoveredEventId(event.id)}
onMouseLeave={() => setHoveredEventId(null)}
style={{
left: `${layout.leftOffsetPercent}%`,
width: `${layout.widthPercent}%`,
zIndex,
top: `calc(${eventStartDiff}*var(--one-minute-height))`,
height: `max(15px, calc(${eventDuration}*var(--one-minute-height)))`,
transform: isHovered || isSelected ? "scale(1.02)" : "scale(1)",
opacity: hoveredGroupIndex !== null && !isHovered && isInHoveredGroup ? 0.6 : 1,
}}>
<Event
event={event}
eventDuration={eventDuration}
onEventClick={eventOnClick}
isHovered={isHovered}
currentlySelectedEventId={selectedEventId}
/>
</div>
);
})}
</>
);
}
@@ -0,0 +1 @@
export { Event } from "./Event";
@@ -0,0 +1,23 @@
import React from "react";
type Props = {
offsetHeight: number | undefined;
gridStopsPerDay: number;
children: React.ReactNode;
zIndex?: number;
};
export const SchedulerColumns = React.forwardRef<HTMLOListElement, Props>(function SchedulerColumns(
{ offsetHeight, gridStopsPerDay, children, zIndex },
ref
) {
return (
<ol
ref={ref}
className="scheduler-grid-row-template col-start-1 col-end-2 row-start-1 grid auto-cols-auto text-[0px]"
style={{ marginTop: offsetHeight || "var(--gridDefaultSize)", zIndex }}
data-gridstopsperday={gridStopsPerDay}>
{children}
</ol>
);
});
@@ -0,0 +1,54 @@
import dayjs from "@calcom/dayjs";
import { Button } from "@calcom/ui/components/button";
import { ButtonGroup } from "@calcom/ui/components/buttonGroup";
import { useCalendarStore } from "@calcom/features/calendars/weeklyview/state/store";
export function SchedulerHeading() {
const { startDate, endDate, handleDateChange } = useCalendarStore((state) => ({
startDate: dayjs(state.startDate),
endDate: dayjs(state.endDate),
handleDateChange: state.handleDateChange,
}));
return (
<header className="flex flex-none flex-col justify-between py-4 sm:flex-row sm:items-center">
<h1 className="text-emphasis text-xl font-semibold">
{startDate.format("MMM DD")}-{endDate.format("DD")}
<span className="text-subtle">,{startDate.format("YYYY")}</span>
</h1>
<div className="flex items-center space-x-2 rtl:space-x-reverse">
{/* TODO: Renable when we have daily/mobile support */}
{/* <ToggleGroup
options={[
{ label: "Daily", value: "day", disabled: false },
{ label: "Weekly", value: "week", disabled: isSm },
]}
defaultValue={view === "day" ? "day" : "week"}
/> */}
<ButtonGroup combined>
{/* TODO: i18n label with correct view */}
<Button
StartIcon="chevron-left"
variant="icon"
color="secondary"
aria-label="Previous Week"
onClick={() => {
handleDateChange("DECREMENT");
}}
/>
<Button
StartIcon="chevron-right"
variant="icon"
color="secondary"
aria-label="Next Week"
onClick={() => {
handleDateChange("INCREMENT");
}}
/>
</ButtonGroup>
</div>
</header>
);
}
@@ -0,0 +1 @@
export { SchedulerHeading } from "./SchedulerHeading";
@@ -0,0 +1,49 @@
import { useId } from "react";
import type dayjs from "@calcom/dayjs";
import { useTimePreferences } from "@calcom/features/bookings/lib";
import classNames from "@calcom/ui/classNames";
import type { BorderColor } from "@calcom/features/calendars/weeklyview/types/common";
export const HorizontalLines = ({
hours,
containerOffsetRef,
borderColor,
}: {
hours: dayjs.Dayjs[];
numberOfGridStopsPerCell: number;
containerOffsetRef: React.RefObject<HTMLDivElement>;
borderColor: BorderColor;
}) => {
const { timeFormat } = useTimePreferences();
// We need to force the minute to zero, because otherwise in ex GMT+5.5, it would show :30 minute times (but at the positino of :00)
const finalHour = hours[hours.length - 1].add(1, "hour").minute(0).format(timeFormat);
const id = useId();
return (
<div
className={classNames(
"pointer-events-none relative z-60 col-start-1 col-end-2 row-start-1 grid divide-y",
borderColor === "subtle" ? "divide-subtle" : "divide-default"
)}
style={{
gridTemplateRows: `repeat(${hours.length}, minmax(var(--gridDefaultSize),1fr)`,
}}>
<div className="row-end-1 h-(--calendar-offset-top) " ref={containerOffsetRef} />
{hours.map((hour) => (
<div key={`${id}-${hour.get("hour")}`}>
<div className="text-muted sticky left-0 z-20 -ml-14 -mt-2.5 w-14 pr-2 text-right text-xs leading-5 rtl:-mr-14">
{/* We need to force the minute to zero, because otherwise in ex GMT+5.5, it would show :30 minute times (but at the positino of :00) */}
{hour.minute(0).format(timeFormat)}
</div>
</div>
))}
<div key={`${id}-${finalHour}`}>
<div className="text-muted sticky left-0 z-20 -ml-14 -mt-2.5 w-14 pr-2 text-right text-xs leading-5 rtl:-mr-14">
{finalHour}
</div>
</div>
</div>
);
};
@@ -0,0 +1 @@
export { Calendar } from "./Calendar";
@@ -0,0 +1,21 @@
import classNames from "@calcom/ui/classNames";
export const Spinner = ({ className }: { className?: string }) => (
<div
className={classNames(
"fixed left-[calc(50%+calc(var(--booker-meta-width,0px)/2))] top-1/2 z-80 h-10 w-10 -translate-x-1/2 -translate-y-1/2",
className
)}>
<svg className="h-10 w-10" viewBox="0 0 24 24" xmlns="http://www.w3.org/2000/svg">
<path
className="fill-default"
d="M12,1A11,11,0,1,0,23,12,11,11,0,0,0,12,1Zm0,19a8,8,0,1,1,8-8A8,8,0,0,1,12,20Z"
opacity=".25"
/>
<path
className="animate-spinning fill-emphasis origin-center"
d="M10.14,1.16a11,11,0,0,0-9,8.92A1.59,1.59,0,0,0,2.46,12,1.52,1.52,0,0,0,4.11,10.7a8,8,0,0,1,6.66-6.61A1.42,1.42,0,0,0,12,2.69h0A1.57,1.57,0,0,0,10.14,1.16Z"
/>
</svg>
</div>
);
@@ -0,0 +1,40 @@
import type dayjs from "@calcom/dayjs";
import classNames from "@calcom/ui/classNames";
import type { BorderColor } from "@calcom/features/calendars/weeklyview/types/common";
export const VerticalLines = ({ days, borderColor }: { days: dayjs.Dayjs[]; borderColor: BorderColor }) => {
const isRTL = () => {
let userLanguage = "en"; // Default to 'en' if navigator is not defined
if (typeof window !== "undefined" && typeof navigator !== "undefined") {
const userLocale = navigator.language;
userLanguage = new Intl.Locale(userLocale).language;
}
return ["ar", "he", "fa", "ur"].includes(userLanguage);
};
const direction = isRTL() ? "rtl" : "ltr";
return (
<div
className={classNames(
"pointer-events-none relative z-60 col-start-1 col-end-2 row-start-1 grid auto-cols-auto grid-rows-1 divide-x",
borderColor === "subtle" ? "divide-subtle" : "divide-default"
)}
dir={direction}
style={{
direction: direction,
}}>
{days.map((_, i) => (
<div
key={`Key_vertical_${i}`}
className="row-span-full"
style={{
gridColumnStart: isRTL() ? days.length - i : i + 1,
}}
/>
))}
</div>
);
};
@@ -0,0 +1,546 @@
"use client";
import type { Row } from "@tanstack/react-table";
import { flexRender } from "@tanstack/react-table";
import type { Table as ReactTableType, Header, HeaderGroup } from "@tanstack/react-table";
import { useVirtualizer, type Virtualizer, type VirtualItem } from "@tanstack/react-virtual";
import kebabCase from "lodash/kebabCase";
import { useEffect, useState, memo, useMemo } from "react";
import { useLocale } from "@calcom/lib/hooks/useLocale";
import classNames from "@calcom/ui/classNames";
import { Command, CommandList, CommandItem } from "@calcom/ui/components/command";
import { Icon } from "@calcom/ui/components/icon";
import { Popover, PopoverTrigger, PopoverContent } from "@calcom/ui/components/popover";
import {
TableNew,
TableBody,
TableCell,
TableHead,
TableHeader,
TableRow,
} from "@calcom/ui/components/table";
import { useColumnSizingVars } from "@calcom/features/data-table/hooks";
import { useColumnResizing } from "@calcom/features/data-table/hooks/useColumnResizing";
import type { SeparatorRow } from "@calcom/features/data-table/lib/separator";
import { isSeparatorRow } from "@calcom/features/data-table/lib/separator";
export type DataTablePropsFromWrapper<TData> = {
table: ReactTableType<TData>;
tableContainerRef: React.RefObject<HTMLDivElement>;
isPending?: boolean;
variant?: "default" | "compact";
testId?: string;
bodyTestId?: string;
children?: React.ReactNode;
enableColumnResizing?: boolean;
className?: string;
containerClassName?: string;
headerClassName?: string;
rowClassName?: string | ((row: Row<TData>) => string);
rowTestId?: string | ((row: Row<TData>) => string | undefined);
rowDataAttributes?: (row: Row<TData>) => Record<string, string> | undefined;
paginationMode?: "infinite" | "standard";
hasWrapperContext?: boolean;
hideSeparatorsOnSort?: boolean;
hideSeparatorsOnFilter?: boolean;
separatorClassName?: string;
};
export type DataTableProps<TData> = DataTablePropsFromWrapper<TData> & {
onRowMouseclick?: (row: Row<TData>) => void;
onScroll?: (e: Pick<React.UIEvent<HTMLDivElement, UIEvent>, "target">) => void;
tableOverlay?: React.ReactNode;
enableColumnResizing?: boolean;
};
export function DataTable<TData>({
table,
tableContainerRef,
isPending,
variant,
onRowMouseclick,
onScroll,
children,
enableColumnResizing,
testId,
bodyTestId,
className,
containerClassName,
headerClassName,
rowClassName,
rowTestId,
rowDataAttributes,
paginationMode = "infinite",
hasWrapperContext = false,
hideSeparatorsOnSort = true,
hideSeparatorsOnFilter = false,
separatorClassName,
...rest
}: DataTableProps<TData> & React.ComponentPropsWithoutRef<"div">) {
const { rows } = table.getRowModel();
const rowVirtualizer = useVirtualizer({
count: rows.length,
estimateSize: () => 100,
getScrollElement: () => tableContainerRef.current,
measureElement:
typeof window !== "undefined" && navigator.userAgent.indexOf("Firefox") === -1
? (element) => element?.getBoundingClientRect().height
: undefined,
overscan: 10,
});
const virtualItemsCount = rowVirtualizer.getVirtualItems().length;
useEffect(() => {
if (paginationMode === "infinite" && virtualItemsCount >= rows.length && tableContainerRef.current) {
const target = tableContainerRef.current;
// Right after the last row is rendered, tableContainer's scrollHeight is
// temporarily larger than the actual height of the table, so we need to
// wait for a short time before calling onScroll to ensure the scrollHeight
// is correct.
setTimeout(() => {
onScroll?.({ target });
}, 100);
}
}, [virtualItemsCount, rows.length, tableContainerRef.current, paginationMode, onScroll]);
const columnSizingVars = useColumnSizingVars({ table });
useColumnResizing({
enabled: Boolean(enableColumnResizing),
table,
tableContainerRef,
});
return (
<div
className={classNames(
!hasWrapperContext ? "grid" : "bg-cal-muted grid rounded-xl px-0.5 pb-0.5",
className
)}
style={{
gridTemplateRows: "auto 1fr auto",
gridTemplateAreas: "'header' 'body' 'footer'",
...rest.style,
}}
data-testid={testId ?? "data-table"}>
{/*
Invalidate left & right properties for <= sm screen size,
because we pin columns only for >= sm screen sizes.
*/}
<style jsx global>{`
@media (max-width: 640px) {
.data-table th,
.data-table td {
left: initial !important;
right: initial !important;
}
}
`}</style>
<div
ref={tableContainerRef}
onScroll={onScroll}
className={classNames(
"relative overflow-auto",
"scrollbar-thin relative rounded-md ",
paginationMode === "infinite" && "h-[80dvh]", // Set a fixed height for the container
containerClassName
)}
style={{ gridArea: "body" }}>
<TableNew
className={classNames(
"data-table grid border-0",
!hasWrapperContext && "bg-cal-muted rounded-xl px-0.5 pb-0.5"
)}
style={{
...columnSizingVars,
...(Boolean(enableColumnResizing) && { width: table.getTotalSize() }),
}}>
<TableHeader className={classNames("sticky top-0 z-10", headerClassName)}>
{table.getHeaderGroups().map((headerGroup: HeaderGroup<TData>) => (
<TableRow key={headerGroup.id} className="hover:bg-subtle flex w-full border-none">
{headerGroup.headers.map((header: Header<TData, unknown>) => {
const { column } = header;
return (
<TableHead
key={header.id}
style={{
...(column.getIsPinned() === "left" && { left: `${column.getStart("left")}px` }),
...(column.getIsPinned() === "right" && { right: `${column.getStart("right")}px` }),
width: `var(--header-${kebabCase(header?.id)}-size)`,
}}
className={classNames(
"relative flex shrink-0 items-center",
"bg-cal-muted",
column.getIsPinned() && "top-0 z-20 sm:sticky"
)}>
<TableHeadLabel header={header} />
{Boolean(enableColumnResizing) && header.column.getCanResize() && (
<div
onMouseDown={header.getResizeHandler()}
onTouchStart={header.getResizeHandler()}
className={classNames(
"group absolute right-0 top-0 h-full w-[5px] cursor-col-resize touch-none select-none opacity-0 hover:opacity-50",
header.column.getIsResizing() && "opacity-75!"
)}>
<div className="bg-inverted mx-auto h-full w-px" />
</div>
)}
</TableHead>
);
})}
</TableRow>
))}
</TableHeader>
{/* When resizing any column we will render this special memoized version of our table body */}
{table.getState().columnSizingInfo.isResizingColumn ? (
<MemoizedTableBody
table={table}
rowVirtualizer={rowVirtualizer}
rows={rows}
testId={bodyTestId}
variant={variant}
isPending={isPending}
onRowMouseclick={onRowMouseclick}
paginationMode={paginationMode}
rowClassName={rowClassName}
rowTestId={rowTestId}
rowDataAttributes={rowDataAttributes}
hideSeparatorsOnSort={hideSeparatorsOnSort}
hideSeparatorsOnFilter={hideSeparatorsOnFilter}
separatorClassName={separatorClassName}
tableContainerRef={tableContainerRef}
/>
) : (
<DataTableBody
table={table}
rowVirtualizer={rowVirtualizer}
rows={rows}
testId={bodyTestId}
variant={variant}
isPending={isPending}
onRowMouseclick={onRowMouseclick}
paginationMode={paginationMode}
rowClassName={rowClassName}
rowTestId={rowTestId}
rowDataAttributes={rowDataAttributes}
hideSeparatorsOnSort={hideSeparatorsOnSort}
hideSeparatorsOnFilter={hideSeparatorsOnFilter}
separatorClassName={separatorClassName}
tableContainerRef={tableContainerRef}
/>
)}
</TableNew>
</div>
{children}
</div>
);
}
const MemoizedTableBody = memo(
DataTableBody,
(prev, next) =>
prev.table.options.data === next.table.options.data &&
prev.rowVirtualizer === next.rowVirtualizer &&
prev.rows === next.rows &&
prev.testId === next.testId &&
prev.variant === next.variant &&
prev.isPending === next.isPending &&
prev.onRowMouseclick === next.onRowMouseclick &&
prev.paginationMode === next.paginationMode &&
prev.rowClassName === next.rowClassName &&
prev.rowTestId === next.rowTestId &&
prev.rowDataAttributes === next.rowDataAttributes &&
prev.hideSeparatorsOnSort === next.hideSeparatorsOnSort &&
prev.hideSeparatorsOnFilter === next.hideSeparatorsOnFilter &&
prev.separatorClassName === next.separatorClassName &&
prev.tableContainerRef === next.tableContainerRef
) as typeof DataTableBody;
type DataTableBodyProps<TData> = {
table: ReactTableType<TData>;
rowVirtualizer: Virtualizer<HTMLDivElement, Element>;
rows: Row<TData>[];
testId?: string;
variant?: "default" | "compact";
isPending?: boolean;
onRowMouseclick?: (row: Row<TData>) => void;
paginationMode?: "infinite" | "standard";
rowClassName?: string | ((row: Row<TData>) => string);
rowTestId?: string | ((row: Row<TData>) => string | undefined);
rowDataAttributes?: (row: Row<TData>) => Record<string, string> | undefined;
hideSeparatorsOnSort?: boolean;
hideSeparatorsOnFilter?: boolean;
separatorClassName?: string;
tableContainerRef: React.RefObject<HTMLDivElement>;
};
type RowToRender<TData> = {
row: Row<TData>;
virtualItem?: VirtualItem;
};
function SeparatorRowRenderer({ separator, className }: { separator: SeparatorRow; className?: string }) {
return (
<div
className={classNames(
"bg-cal-muted text-emphasis w-full px-3 py-2 font-semibold",
separator.className,
className
)}>
{separator.label}
</div>
);
}
function DataTableBody<TData>({
table,
rowVirtualizer: _rowVirtualizer,
rows,
testId,
variant,
isPending,
onRowMouseclick,
paginationMode,
rowClassName,
rowTestId,
rowDataAttributes,
hideSeparatorsOnSort = true,
hideSeparatorsOnFilter = false,
separatorClassName,
tableContainerRef,
}: DataTableBodyProps<TData> & { paginationMode?: "infinite" | "standard" }) {
const { t } = useLocale();
const hasActiveSorting = table.getState().sorting.length > 0;
const hasActiveFilters = table.getState().columnFilters.length > 0;
const filteredRows = useMemo(() => {
if ((hideSeparatorsOnSort && hasActiveSorting) || (hideSeparatorsOnFilter && hasActiveFilters)) {
return rows.filter((row) => !isSeparatorRow(row.original));
}
return rows;
}, [rows, hideSeparatorsOnSort, hideSeparatorsOnFilter, hasActiveSorting, hasActiveFilters]);
const filteredRowVirtualizer = useVirtualizer({
count: filteredRows.length,
estimateSize: () => 100,
getScrollElement: () => tableContainerRef.current,
measureElement:
typeof window !== "undefined" && navigator.userAgent.indexOf("Firefox") === -1
? (element) => element?.getBoundingClientRect().height
: undefined,
overscan: 10,
});
const virtualItems = filteredRowVirtualizer.getVirtualItems();
const tableHeight = paginationMode === "infinite" ? filteredRowVirtualizer.getTotalSize() : "auto";
const rowsToRender = useMemo<RowToRender<TData>[]>(() => {
return paginationMode === "infinite"
? virtualItems.map((virtualItem) => ({
row: filteredRows[virtualItem.index] as Row<TData>,
virtualItem,
}))
: filteredRows.map((row) => ({ row }));
}, [paginationMode, virtualItems, filteredRows]);
if (!isPending && rowsToRender.length === 0) {
return (
<TableBody className="relative grid" data-testid={testId} style={{ height: tableHeight }}>
<TableRow>
<TableCell colSpan={table.getAllColumns().length} className="h-24 text-center">
{t("no_results")}
</TableCell>
</TableRow>
</TableBody>
);
}
return (
<TableBody
className="border-muted relative grid border-t"
data-testid={testId}
style={{ height: tableHeight }}>
{rowsToRender.map(({ row, virtualItem }) => {
const isSeparator = isSeparatorRow(row.original);
if (isSeparator) {
return (
<TableRow
ref={virtualItem ? (node) => filteredRowVirtualizer.measureElement(node) : undefined}
key={row.id}
data-index={virtualItem?.index}
style={{
display: "flex",
width: "100%",
...(virtualItem && {
position: "absolute",
transform: `translateY(${virtualItem.start}px)`,
}),
}}
className="hover:bg-subtle border-muted flex w-full border-b">
<SeparatorRowRenderer separator={row.original as SeparatorRow} className={separatorClassName} />
</TableRow>
);
}
const computedRowTestId = typeof rowTestId === "function" ? rowTestId(row) : rowTestId;
const computedRowClassName = typeof rowClassName === "function" ? rowClassName(row) : rowClassName;
const computedDataAttributes = rowDataAttributes?.(row);
return (
<TableRow
ref={virtualItem ? (node) => filteredRowVirtualizer.measureElement(node) : undefined}
key={row.id}
data-testid={computedRowTestId}
{...computedDataAttributes}
data-index={virtualItem?.index} // needed for dynamic row height measurement
data-state={row.getIsSelected() && "selected"}
onClick={(e) => {
if (!onRowMouseclick) return;
const target = e.target as Node | null;
const current = e.currentTarget as HTMLElement | null;
// Only invoke the handler when the event target is inside the row element.
if (!target || !current || !current.contains(target)) return;
onRowMouseclick(row);
}}
style={{
display: "flex",
...(virtualItem && {
position: "absolute",
transform: `translateY(${virtualItem.start}px)`,
width: "100%",
}),
}}
className={classNames(onRowMouseclick && "hover:cursor-pointer", "group", computedRowClassName)}>
{row.getVisibleCells().map((cell) => {
const column = cell.column;
return (
<TableCell
key={cell.id}
data-testid={`data-table-td-${cell.column.id}`}
style={{
...(column.getIsPinned() === "left" && { left: `${column.getStart("left")}px` }),
...(column.getIsPinned() === "right" && { right: `${column.getStart("right")}px` }),
width: `var(--col-${kebabCase(cell.column.id)}-size)`,
}}
className={classNames(
"bg-default group-hover:!bg-cal-muted group-data-[state=selected]:bg-subtle flex shrink-0 items-center overflow-hidden",
variant === "compact" && "p-0",
column.getIsPinned() &&
"bg-default group-hover:!bg-cal-muted group-data-[state=selected]:bg-subtle sm:sticky"
)}>
{flexRender(cell.column.columnDef.cell, cell.getContext())}
</TableCell>
);
})}
</TableRow>
);
})}
</TableBody>
);
}
const TableHeadLabel = <TData,>({ header }: { header: Header<TData, unknown> }) => {
const [open, setOpen] = useState(false);
const { t } = useLocale();
const canHide = header.column.getCanHide();
const canSort = header.column.getCanSort();
if (!canSort && !canHide) {
if (typeof header.column.columnDef.header === "string") {
return (
<div className="truncate" title={header.column.columnDef.header}>
{header.isPlaceholder ? null : flexRender(header.column.columnDef.header, header.getContext())}
</div>
);
} else {
return header.isPlaceholder ? null : flexRender(header.column.columnDef.header, header.getContext());
}
}
return (
<Popover open={open} onOpenChange={setOpen}>
<PopoverTrigger asChild>
<button
type="button"
className={classNames(
"group mr-1 flex w-full items-center gap-2 rounded-md px-2 py-1",
open && "bg-cal-muted"
)}>
<div
className="text-default truncate text-sm leading-none"
title={
typeof header.column.columnDef.header === "string" ? header.column.columnDef.header : undefined
}>
{header.isPlaceholder ? null : flexRender(header.column.columnDef.header, header.getContext())}
</div>
{header.column.getIsSorted() === "asc" && <Icon name="arrow-up" className="h-4 w-4 shrink-0" />}
{header.column.getIsSorted() === "desc" && <Icon name="arrow-down" className="h-4 w-4 shrink-0" />}
<div className="grow" />
<Icon
name="chevrons-up-down"
className={classNames(
"text-subtle h-4 w-4 shrink-0",
!open && "opacity-0 group-hover:opacity-100"
)}
/>
</button>
</PopoverTrigger>
<PopoverContent align="start" className="w-32 p-0">
<Command>
<CommandList>
{canSort && (
<>
<CommandItem
className="flex cursor-pointer items-center gap-2 px-3 py-2"
onSelect={() => {
if (header.column.getIsSorted() === "asc") {
header.column.clearSorting();
} else {
header.column.toggleSorting(false, true);
}
}}>
<Icon name="arrow-up" className="h-4 w-4" />
{t("asc")}
<div className="flex-1" />
{header.column.getIsSorted() === "asc" && <Icon name="check" className="h-4 w-4" />}
</CommandItem>
<CommandItem
className="flex cursor-pointer items-center gap-2 px-3 py-2"
onSelect={() => {
if (header.column.getIsSorted() === "desc") {
header.column.clearSorting();
} else {
header.column.toggleSorting(true, true);
}
}}>
<Icon name="arrow-down" className="h-4 w-4" />
{t("desc")}
<div className="flex-1" />
{header.column.getIsSorted() === "desc" && <Icon name="check" className="h-4 w-4" />}
</CommandItem>
</>
)}
{canHide && (
<CommandItem
className="flex cursor-pointer items-center gap-2 px-3 py-2"
onSelect={() => {
header.column.toggleVisibility(false);
setOpen(false);
}}>
<Icon name="eye-off" className="h-4 w-4" />
{t("hide")}
</CommandItem>
)}
</CommandList>
</Command>
</PopoverContent>
</Popover>
);
};
@@ -0,0 +1,46 @@
"use client";
import { type Table } from "@tanstack/react-table";
import { Pagination } from "@calcom/ui/components/pagination";
import { useDataTable } from "@calcom/features/data-table/hooks";
interface DataTablePaginationProps<TData> {
table: Table<TData>;
totalRowCount?: number;
paginationMode?: "infinite" | "standard";
}
export function DataTablePagination<TData>({
table,
totalRowCount,
paginationMode = "infinite",
}: DataTablePaginationProps<TData>) {
const { pageIndex, pageSize, setPageIndex, setPageSize } = useDataTable();
if (!totalRowCount) {
return null;
}
if (paginationMode === "infinite") {
const loadedCount = table.getRowModel().rows.length;
return (
<p className="text-subtle text-sm tabular-nums">
Loaded <span className="text-default font-medium">{loadedCount}</span> of{" "}
<span className="text-default font-medium">{totalRowCount}</span>
</p>
);
} else if (paginationMode === "standard") {
return (
<Pagination
currentPage={pageIndex + 1}
pageSize={pageSize}
totalItems={totalRowCount}
onPageSizeChange={(newSize) => setPageSize(newSize)}
onPageChange={(page) => setPageIndex(page - 1)}
/>
);
} else {
return null;
}
}
@@ -0,0 +1,71 @@
"use client";
import type { Table } from "@tanstack/react-table";
import { forwardRef } from "react";
import { createPortal } from "react-dom";
import classNames from "@calcom/ui/classNames";
import { Button, type ButtonProps } from "@calcom/ui/components/button";
import { Icon, type IconName } from "@calcom/ui/components/icon";
export type ActionItem<TData> =
| {
type: "action";
label: string;
onClick: () => void;
icon?: IconName;
needsXSelected?: number;
}
| {
type: "render";
render: (table: Table<TData>) => React.ReactNode;
needsXSelected?: number;
};
type ResponsiveButtonProps = {
className?: string;
icon: IconName;
onClick?: () => void;
children: string;
} & ButtonProps;
const ResponsiveButton = forwardRef<HTMLButtonElement, ResponsiveButtonProps>(
({ icon, onClick, children, ...rest }, ref) => {
return (
<Button ref={ref} onClick={onClick} title={children} {...rest}>
<Icon name={icon} size={18} className="sm:hidden" />
<Icon name={icon} size={16} className="mr-2 hidden shrink-0 sm:inline" />
<span className="sr-only shrink-0 md:not-sr-only">{children}</span>
</Button>
);
}
);
ResponsiveButton.displayName = "ResponsiveButton";
const Root = forwardRef<
HTMLDivElement,
React.HTMLAttributes<HTMLDivElement> & { showSelectionCount?: boolean }
>(({ children, ...props }, ref) => {
const { className, style, ...rest } = props;
return createPortal(
<div
ref={ref}
className={classNames(
"bg-default text-emphasis shadow-outline-gray-rested border-subtle fixed left-0 right-0 flex items-center space-x-1 overflow-x-auto border px-2 py-2 sm:space-x-2 md:left-1/2 md:z-auto md:w-fit md:-translate-x-1/2 md:transform md:space-x-3 md:overflow-x-hidden md:rounded-lg md:px-4",
className
)}
style={{ ...style }}
{...rest}>
{children}
</div>,
document.body
);
});
Root.displayName = "Root";
export const DataTableSelectionBar = {
Root,
Button: ResponsiveButton,
};
Loaded 100 of 390 files, more files were not shown because too many files have changed in this diff. Show more