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:
1 parent
3d73238c00
commit
404d46c991
390 files changed
+645
-667
No files matched your search
@@ -3,7 +3,7 @@
|
||||
import { useParams } from "next/navigation";
|
||||
|
||||
import dayjs from "@calcom/dayjs";
|
||||
import { DecoyBookingSuccessCard } from "@calcom/features/bookings/Booker/components/DecoyBookingSuccessCard";
|
||||
import { DecoyBookingSuccessCard } from "~/bookings/components/DecoyBookingSuccessCard";
|
||||
import { useDecoyBooking } from "@calcom/features/bookings/Booker/components/hooks/useDecoyBooking";
|
||||
|
||||
export default function BookingSuccessful() {
|
||||
|
||||
@@ -2,7 +2,7 @@
|
||||
|
||||
import { ShellMainAppDir } from "app/(use-page-wrapper)/(main-nav)/ShellMainAppDir";
|
||||
|
||||
import { EventTypesSkeletonLoader } from "@calcom/features/eventtypes/components/SkeletonLoader";
|
||||
import { EventTypesSkeletonLoader } from "@calcom/web/modules/event-types/components/SkeletonLoader";
|
||||
import { useLocale } from "@calcom/lib/hooks/useLocale";
|
||||
|
||||
export function EventTypesSkeleton() {
|
||||
|
||||
@@ -7,7 +7,7 @@ import { useFormContext } from "react-hook-form";
|
||||
|
||||
import { isFallbackRoute } from "@calcom/app-store/routing-forms/lib/isFallbackRoute";
|
||||
import type { RoutingFormWithResponseCount } from "@calcom/app-store/routing-forms/types/types";
|
||||
import LicenseRequired from "@calcom/features/ee/common/components/LicenseRequired";
|
||||
import LicenseRequired from "~/ee/common/components/LicenseRequired";
|
||||
import { FilterResults } from "@calcom/features/filters/components/FilterResults";
|
||||
import { TeamsFilter } from "@calcom/features/filters/components/TeamsFilter";
|
||||
import { getTeamsFiltersFromQuery } from "@calcom/features/filters/lib/getTeamsFiltersFromQuery";
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
import { _generateMetadata } from "app/_utils";
|
||||
|
||||
import LicenseRequired from "@calcom/features/ee/common/components/LicenseRequired";
|
||||
import LicenseRequired from "~/ee/common/components/LicenseRequired";
|
||||
|
||||
import LegacyPage from "~/connect-and-join/connect-and-join-view";
|
||||
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
import { _generateMetadata } from "app/_utils";
|
||||
|
||||
import InsightsCallHistoryPage from "~/insights/insights-call-history-view";
|
||||
import InsightsCallHistoryPage from "~/insights/views/insights-call-history-view";
|
||||
|
||||
import { checkInsightsPagePermission } from "../checkInsightsPagePermission";
|
||||
|
||||
|
||||
@@ -2,7 +2,7 @@ import { _generateMetadata } from "app/_utils";
|
||||
|
||||
import prisma from "@calcom/prisma";
|
||||
|
||||
import InsightsPage from "~/insights/insights-view";
|
||||
import InsightsPage from "~/insights/views/insights-view";
|
||||
|
||||
import { checkInsightsPagePermission } from "./checkInsightsPagePermission";
|
||||
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
import { _generateMetadata } from "app/_utils";
|
||||
|
||||
import InsightsVirtualQueuesPage from "~/insights/insights-virtual-queues-view";
|
||||
import InsightsVirtualQueuesPage from "~/insights/views/insights-virtual-queues-view";
|
||||
|
||||
import { checkInsightsPagePermission } from "../checkInsightsPagePermission";
|
||||
|
||||
|
||||
@@ -2,7 +2,7 @@ import { _generateMetadata } from "app/_utils";
|
||||
|
||||
import { prisma } from "@calcom/prisma";
|
||||
|
||||
import InsightsRoutingPage from "~/insights/insights-routing-view";
|
||||
import InsightsRoutingPage from "~/insights/views/insights-routing-view";
|
||||
|
||||
import { checkInsightsPagePermission } from "../checkInsightsPagePermission";
|
||||
|
||||
|
||||
@@ -9,8 +9,8 @@ import { getPaymentAppData } from "@calcom/app-store/_utils/payments/getPaymentA
|
||||
import { getSuccessPageLocationMessage } from "@calcom/app-store/locations";
|
||||
import dayjs from "@calcom/dayjs";
|
||||
import { sdkActionManager, useIsEmbed } from "@calcom/embed-core/embed-iframe";
|
||||
import { PayIcon } from "@calcom/features/bookings/components/event-meta/PayIcon";
|
||||
import { Price } from "@calcom/features/bookings/components/event-meta/Price";
|
||||
import { PayIcon } from "@calcom/web/modules/bookings/components/event-meta/PayIcon";
|
||||
import { Price } from "@calcom/web/modules/bookings/components/event-meta/Price";
|
||||
import type { PaymentPageProps } from "@calcom/features/ee/payments/pages/payment";
|
||||
import { APP_NAME, WEBSITE_URL } from "@calcom/lib/constants";
|
||||
import { useLocale } from "@calcom/lib/hooks/useLocale";
|
||||
|
||||
+1
-1
@@ -1,7 +1,7 @@
|
||||
import { _generateMetadata } from "app/_utils";
|
||||
import { getTranslate } from "app/_utils";
|
||||
|
||||
import AdminAppsList from "@calcom/features/apps/AdminAppsList";
|
||||
import AdminAppsList from "~/apps/components/AdminAppsList";
|
||||
import SettingsHeader from "@calcom/features/settings/appDir/SettingsHeader";
|
||||
|
||||
export const generateMetadata = async ({ params }: { params: Promise<{ category: string }> }) =>
|
||||
|
||||
+1
-1
@@ -2,7 +2,7 @@ import { type Params } from "app/_types";
|
||||
import { _generateMetadata, getTranslate } from "app/_utils";
|
||||
import { z } from "zod";
|
||||
|
||||
import LicenseRequired from "@calcom/features/ee/common/components/LicenseRequired";
|
||||
import LicenseRequired from "~/ee/common/components/LicenseRequired";
|
||||
import { OrgForm } from "~/ee/organizations/admin/AdminOrgEditPage";
|
||||
import { getOrganizationRepository } from "@calcom/features/ee/organizations/di/OrganizationRepository.container";
|
||||
import SettingsHeader from "@calcom/features/settings/appDir/SettingsHeader";
|
||||
|
||||
+1
-1
@@ -1,7 +1,7 @@
|
||||
import { _generateMetadata } from "app/_utils";
|
||||
import { getTranslate } from "app/_utils";
|
||||
|
||||
import LicenseRequired from "@calcom/features/ee/common/components/LicenseRequired";
|
||||
import LicenseRequired from "~/ee/common/components/LicenseRequired";
|
||||
import AdminOrgTable from "~/ee/organizations/admin/AdminOrgPage";
|
||||
import SettingsHeader from "@calcom/features/settings/appDir/SettingsHeader";
|
||||
|
||||
|
||||
+2
-2
@@ -1,7 +1,7 @@
|
||||
"use client";
|
||||
|
||||
import { ChartCard } from "@calcom/features/insights/components/ChartCard";
|
||||
import { BookingsByHourChartContent } from "@calcom/features/insights/components/booking/BookingsByHourChart";
|
||||
import { ChartCard } from "@calcom/web/modules/insights/components/ChartCard";
|
||||
import { BookingsByHourChartContent } from "@calcom/web/modules/insights/components/booking/BookingsByHourChart";
|
||||
import { useLocale } from "@calcom/lib/hooks/useLocale";
|
||||
|
||||
// Sample data for playground testing
|
||||
|
||||
+2
-1
@@ -3,8 +3,9 @@
|
||||
import { useReactTable, getCoreRowModel, createColumnHelper } from "@tanstack/react-table";
|
||||
import { useMemo } from "react";
|
||||
|
||||
import { ColumnFilterType, DateRangeFilter, DataTableProvider } from "@calcom/features/data-table";
|
||||
import { ColumnFilterType, DataTableProvider } from "@calcom/features/data-table";
|
||||
import type { DateRangeFilterOptions } from "@calcom/features/data-table/lib/types";
|
||||
import { DateRangeFilter } from "~/data-table/components/filters/DateRangeFilter";
|
||||
|
||||
type DemoRow = {
|
||||
id: number;
|
||||
|
||||
+2
-2
@@ -1,10 +1,10 @@
|
||||
"use client";
|
||||
|
||||
import { ChartCard } from "@calcom/features/insights/components/ChartCard";
|
||||
import { ChartCard } from "@calcom/web/modules/insights/components/ChartCard";
|
||||
import {
|
||||
RoutingFunnelContent,
|
||||
legend,
|
||||
} from "@calcom/features/insights/components/routing/RoutingFunnelContent";
|
||||
} from "@calcom/web/modules/insights/components/routing/RoutingFunnelContent";
|
||||
import { useLocale } from "@calcom/lib/hooks/useLocale";
|
||||
|
||||
// Random sample data for playground testing
|
||||
|
||||
+2
-2
@@ -2,8 +2,8 @@ import { type Params } from "app/_types";
|
||||
import { _generateMetadata, getTranslate } from "app/_utils";
|
||||
import { z } from "zod";
|
||||
|
||||
import LicenseRequired from "@calcom/features/ee/common/components/LicenseRequired";
|
||||
import { UsersEditView } from "@calcom/features/ee/users/pages/users-edit-view";
|
||||
import LicenseRequired from "~/ee/common/components/LicenseRequired";
|
||||
import { UsersEditView } from "~/ee/users/views/users-edit-view";
|
||||
import SettingsHeader from "@calcom/features/settings/appDir/SettingsHeader";
|
||||
import { UserRepository } from "@calcom/features/users/repositories/UserRepository";
|
||||
import { prisma } from "@calcom/prisma";
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
import { _generateMetadata, getTranslate } from "app/_utils";
|
||||
|
||||
import UsersAddView from "@calcom/features/ee/users/pages/users-add-view";
|
||||
import UsersAddView from "~/ee/users/views/users-add-view";
|
||||
import SettingsHeader from "@calcom/features/settings/appDir/SettingsHeader";
|
||||
|
||||
export const generateMetadata = async () =>
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
import { _generateMetadata, getTranslate } from "app/_utils";
|
||||
|
||||
import UsersListingView from "@calcom/features/ee/users/pages/users-listing-view";
|
||||
import UsersListingView from "~/ee/users/views/users-listing-view";
|
||||
import SettingsHeader from "@calcom/features/settings/appDir/SettingsHeader";
|
||||
import { Button } from "@calcom/ui/components/button";
|
||||
|
||||
|
||||
+1
-1
@@ -1,6 +1,6 @@
|
||||
import { _generateMetadata, getTranslate } from "app/_utils";
|
||||
|
||||
import LicenseRequired from "@calcom/features/ee/common/components/LicenseRequired";
|
||||
import LicenseRequired from "~/ee/common/components/LicenseRequired";
|
||||
import WorkspacePlatformsPage from "~/ee/organizations/admin/WorkspacePlatformPage";
|
||||
import SettingsHeader from "@calcom/features/settings/appDir/SettingsHeader";
|
||||
|
||||
|
||||
+1
-1
@@ -1,6 +1,6 @@
|
||||
import { _generateMetadata, getTranslate } from "app/_utils";
|
||||
|
||||
import DirectorySyncTeamView from "@calcom/features/ee/dsync/page/team-dsync-view";
|
||||
import DirectorySyncTeamView from "~/ee/dsync/views/team-dsync-view";
|
||||
import { Resource } from "@calcom/features/pbac/domain/types/permission-registry";
|
||||
import { getResourcePermissions } from "@calcom/features/pbac/lib/resource-permissions";
|
||||
import SettingsHeader from "@calcom/features/settings/appDir/SettingsHeader";
|
||||
|
||||
+1
-1
@@ -1,7 +1,7 @@
|
||||
import { _generateMetadata, getTranslate } from "app/_utils";
|
||||
import { redirect } from "next/navigation";
|
||||
|
||||
import OrgSSOView from "@calcom/features/ee/sso/page/orgs-sso-view";
|
||||
import OrgSSOView from "~/ee/sso/views/orgs-sso-view";
|
||||
import { Resource } from "@calcom/features/pbac/domain/types/permission-registry";
|
||||
import { getResourcePermissions } from "@calcom/features/pbac/lib/resource-permissions";
|
||||
import SettingsHeader from "@calcom/features/settings/appDir/SettingsHeader";
|
||||
|
||||
+1
-1
@@ -1,7 +1,7 @@
|
||||
import { _generateMetadata, getTranslate } from "app/_utils";
|
||||
import { redirect } from "next/navigation";
|
||||
|
||||
import { OtherTeamsListing } from "@calcom/features/ee/organizations/pages/components/OtherTeamsListing";
|
||||
import { OtherTeamsListing } from "~/ee/organizations/components/OtherTeamsListing";
|
||||
import { getOrganizationRepository } from "@calcom/features/ee/organizations/di/OrganizationRepository.container";
|
||||
import SettingsHeader from "@calcom/features/settings/appDir/SettingsHeader";
|
||||
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
import { _generateMetadata } from "app/_utils";
|
||||
import { getTranslate } from "app/_utils";
|
||||
|
||||
import SAMLSSO from "@calcom/features/ee/sso/page/user-sso-view";
|
||||
import SAMLSSO from "~/ee/sso/views/user-sso-view";
|
||||
import SettingsHeader from "@calcom/features/settings/appDir/SettingsHeader";
|
||||
|
||||
export const generateMetadata = async () =>
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
import { _generateMetadata } from "app/_utils";
|
||||
|
||||
import LicenseRequired from "@calcom/features/ee/common/components/LicenseRequired";
|
||||
import LicenseRequired from "~/ee/common/components/LicenseRequired";
|
||||
|
||||
import LegacyPage, { LayoutWrapper } from "~/ee/organizations/new/create-new-view";
|
||||
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
import { createRouterCaller } from "app/_trpc/context";
|
||||
import { _generateMetadata } from "app/_utils";
|
||||
|
||||
import PlatformMembersView from "@calcom/features/ee/platform/pages/settings/members";
|
||||
import PlatformMembersView from "~/ee/platform/views/members";
|
||||
import { viewerOrganizationsRouter } from "@calcom/trpc/server/routers/viewer/organizations/_router";
|
||||
|
||||
export const generateMetadata = async () =>
|
||||
|
||||
@@ -3,7 +3,7 @@ import { cookies, headers } from "next/headers";
|
||||
import { redirect } from "next/navigation";
|
||||
|
||||
import { getServerSession } from "@calcom/features/auth/lib/getServerSession";
|
||||
import LicenseRequired from "@calcom/features/ee/common/components/LicenseRequired";
|
||||
import LicenseRequired from "~/ee/common/components/LicenseRequired";
|
||||
import { WEBAPP_URL } from "@calcom/lib/constants";
|
||||
|
||||
import { buildLegacyRequest } from "@lib/buildLegacyCtx";
|
||||
|
||||
@@ -16,7 +16,7 @@ import Head from "next/head";
|
||||
import Script from "next/script";
|
||||
|
||||
import "@calcom/embed-core/src/embed-iframe";
|
||||
import LicenseRequired from "@calcom/features/ee/common/components/LicenseRequired";
|
||||
import LicenseRequired from "~/ee/common/components/LicenseRequired";
|
||||
import { IS_CALCOM, WEBAPP_URL } from "@calcom/lib/constants";
|
||||
import { getCalcomUrl } from "@calcom/lib/getCalcomUrl";
|
||||
import { buildCanonical } from "@calcom/lib/next-seo.config";
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
"use client";
|
||||
|
||||
import "@calcom/embed-core/src/embed-iframe";
|
||||
import LicenseRequired from "@calcom/features/ee/common/components/LicenseRequired";
|
||||
import LicenseRequired from "~/ee/common/components/LicenseRequired";
|
||||
|
||||
import AppProviders from "@lib/app-providers-app-dir";
|
||||
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
import LicenseRequired from "@calcom/features/ee/common/components/LicenseRequired";
|
||||
import LicenseRequired from "~/ee/common/components/LicenseRequired";
|
||||
import { useLocale } from "@calcom/lib/hooks/useLocale";
|
||||
|
||||
import Shell from "~/shell/Shell";
|
||||
|
||||
@@ -8,7 +8,7 @@ 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 DisconnectIntegration from "@calcom/features/apps/components/DisconnectIntegration";
|
||||
import DisconnectIntegration from "@calcom/web/modules/apps/components/DisconnectIntegration";
|
||||
import { AppOnboardingSteps } from "@calcom/lib/apps/appOnboardingSteps";
|
||||
import { getAppOnboardingUrl } from "@calcom/lib/apps/getAppOnboardingUrl";
|
||||
import { APP_NAME, COMPANY_NAME, SUPPORT_MAIL_ADDRESS, WEBAPP_URL } from "@calcom/lib/constants";
|
||||
|
||||
@@ -5,8 +5,8 @@ import { useEffect, Suspense } from "react";
|
||||
import { InstallAppButton } from "@calcom/app-store/InstallAppButton";
|
||||
import { DestinationCalendarSettingsWebWrapper } from "@calcom/atoms/destination-calendar/wrappers/DestinationCalendarSettingsWebWrapper";
|
||||
import { SelectedCalendarsSettingsWebWrapper } from "@calcom/atoms/selected-calendars/wrappers/SelectedCalendarsSettingsWebWrapper";
|
||||
import AppListCard from "@calcom/features/apps/components/AppListCard";
|
||||
import { SkeletonLoader } from "@calcom/features/apps/components/SkeletonLoader";
|
||||
import AppListCard from "@calcom/web/modules/apps/components/AppListCard";
|
||||
import { SkeletonLoader } from "@calcom/web/modules/apps/components/SkeletonLoader";
|
||||
import SettingsHeader from "@calcom/features/settings/appDir/SettingsHeader";
|
||||
import { useLocale } from "@calcom/lib/hooks/useLocale";
|
||||
import { trpc } from "@calcom/trpc/react";
|
||||
|
||||
@@ -8,7 +8,7 @@ import { Dialog } from "@calcom/features/components/controlled-dialog";
|
||||
import { dataTableQueryParamsSerializer } from "@calcom/features/data-table/lib/serializers";
|
||||
import { ColumnFilterType } from "@calcom/features/data-table/lib/types";
|
||||
import { useOrgBranding } from "@calcom/features/ee/organizations/context/provider";
|
||||
import { RoutingFormEmbedButton, RoutingFormEmbedDialog } from "@calcom/features/embed/RoutingFormEmbed";
|
||||
import { RoutingFormEmbedButton, RoutingFormEmbedDialog } from "@calcom/web/modules/embed/components/RoutingFormEmbed";
|
||||
import { EmbedDialogProvider } from "@calcom/features/embed/lib/hooks/useEmbedDialogCtx";
|
||||
import { WEBSITE_URL } from "@calcom/lib/constants";
|
||||
import { useLocale } from "@calcom/lib/hooks/useLocale";
|
||||
|
||||
@@ -7,7 +7,7 @@ import type { UseFormReturn } from "react-hook-form";
|
||||
|
||||
import { InfoLostWarningDialog } from "@calcom/app-store/routing-forms/components/InfoLostWarningDialog";
|
||||
import type { RoutingFormWithResponseCount } from "@calcom/app-store/routing-forms/types/types";
|
||||
import LicenseRequired from "@calcom/features/ee/common/components/LicenseRequired";
|
||||
import LicenseRequired from "~/ee/common/components/LicenseRequired";
|
||||
import { useLocale } from "@calcom/lib/hooks/useLocale";
|
||||
import { trpc } from "@calcom/trpc/react";
|
||||
import type { inferSSRProps } from "@calcom/types/inferSSRProps";
|
||||
|
||||
@@ -1,8 +1,8 @@
|
||||
import { useState } from "react";
|
||||
import type { z } from "zod";
|
||||
|
||||
import { MeetingSessionDetailsDialog } from "@calcom/features/ee/video/MeetingSessionDetailsDialog";
|
||||
import ViewRecordingsDialog from "~/ee/video/ViewRecordingsDialog";
|
||||
import { MeetingSessionDetailsDialog } from "@calcom/web/modules/ee/video/components/MeetingSessionDetailsDialog";
|
||||
import ViewRecordingsDialog from "~/ee/video/components/ViewRecordingsDialog";
|
||||
import { useLocale } from "@calcom/lib/hooks/useLocale";
|
||||
import type { bookingMetadataSchema } from "@calcom/prisma/zod-utils";
|
||||
import { trpc } from "@calcom/trpc/react";
|
||||
|
||||
@@ -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";
|
||||
|
||||
@@ -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>
|
||||
</>
|
||||
);
|
||||
}
|
||||
+147
@@ -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>
|
||||
);
|
||||
},
|
||||
}));
|
||||
Loaded 100 of 390 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user