refactor: move timezone-select, settings, and insights components from packages/features to apps/web/modules (#27227)
* refactor: move timezone-select, settings, and insights components from packages/features to apps/web/modules Co-Authored-By: [email protected] <[email protected]> * fix * fix * fix * wip * wip * wip * wip * wip * wip * wip --------- Co-authored-by: Devin AI <158243242+devin-ai-integration[bot]@users.noreply.github.com>
This commit is contained in:
1 parent
216e871b22
commit
15268bcfb4
31 files changed
+103
-98
No files matched your search
@@ -4,7 +4,7 @@ import { TrpcProvider } from "app/_trpc/trpc-provider";
|
||||
import { SessionProvider } from "next-auth/react";
|
||||
import CacheProvider from "react-inlinesvg/provider";
|
||||
|
||||
import { WebPushProvider } from "@calcom/features/notifications/WebPushContext";
|
||||
import { WebPushProvider } from "@calcom/web/modules/notifications/components/WebPushContext";
|
||||
import { NotificationSoundHandler } from "@calcom/web/components/notification-sound-handler";
|
||||
|
||||
import useIsBookingPage from "@lib/hooks/useIsBookingPage";
|
||||
|
||||
@@ -6,7 +6,7 @@ import { z } from "zod";
|
||||
|
||||
import dayjs from "@calcom/dayjs";
|
||||
import { useTimePreferences } from "@calcom/features/bookings/lib";
|
||||
import { TimezoneSelect } from "@calcom/features/components/timezone-select";
|
||||
import { TimezoneSelect } from "@calcom/web/modules/timezone/components/TimezoneSelect";
|
||||
import { FULL_NAME_LENGTH_MAX_LIMIT } from "@calcom/lib/constants";
|
||||
import { useLocale } from "@calcom/lib/hooks/useLocale";
|
||||
import { trpc } from "@calcom/trpc/react";
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
import dayjs from "@calcom/dayjs";
|
||||
import { useTimePreferences } from "@calcom/features/bookings/lib/timePreferences";
|
||||
import { TimezoneSelect } from "@calcom/features/components/timezone-select";
|
||||
import { TimezoneSelect } from "@calcom/web/modules/timezone/components/TimezoneSelect";
|
||||
import { useLocale } from "@calcom/lib/hooks/useLocale";
|
||||
import { DatePicker, SettingsToggle } from "@calcom/ui/components/form";
|
||||
import { DatePickerWithRange as DateRangePicker } from "@calcom/ui/components/form/date-range-picker/DateRangePicker";
|
||||
|
||||
@@ -24,7 +24,7 @@ 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),
|
||||
() => import("@calcom/web/modules/timezone/components/TimezoneSelect").then((mod) => mod.TimezoneSelect),
|
||||
{
|
||||
ssr: false,
|
||||
}
|
||||
|
||||
@@ -22,7 +22,7 @@ const LoadingState = () => {
|
||||
|
||||
const WebTimezoneSelect = dynamic(
|
||||
() =>
|
||||
import("@calcom/features/components/timezone-select").then(
|
||||
import("@calcom/web/modules/timezone/components/TimezoneSelect").then(
|
||||
(mod) => mod.TimezoneSelect
|
||||
),
|
||||
{
|
||||
|
||||
@@ -5,7 +5,7 @@ import { useRouter } from "next/navigation";
|
||||
import { useEffect } from "react";
|
||||
import { Controller, useForm } from "react-hook-form";
|
||||
|
||||
import { TimezoneSelect } from "@calcom/features/components/timezone-select";
|
||||
import { TimezoneSelect } from "@calcom/web/modules/timezone/components/TimezoneSelect";
|
||||
import LicenseRequired from "~/ee/common/components/LicenseRequired";
|
||||
import { DisableAutofillOnBookingPageSwitch } from "~/ee/organizations/components/DisableAutofillOnBookingPageSwitch";
|
||||
import { DisablePhoneOnlySMSNotificationsSwitch } from "~/ee/organizations/components/DisablePhoneOnlySMSNotificationsSwitch";
|
||||
|
||||
@@ -1,8 +1,8 @@
|
||||
import { useEffect, useState } from "react";
|
||||
|
||||
import dayjs from "@calcom/dayjs";
|
||||
import { TimezoneSelect } from "@calcom/features/components/timezone-select";
|
||||
import type { ITimezone } from "@calcom/features/components/timezone-select";
|
||||
import { TimezoneSelect } from "@calcom/web/modules/timezone/components/TimezoneSelect";
|
||||
import type { ITimezone } from "@calcom/features/timezone/components/TimezoneSelectComponent";
|
||||
import LicenseRequired from "~/ee/common/components/LicenseRequired";
|
||||
import { WEBAPP_URL } from "@calcom/lib/constants";
|
||||
import { useLocale } from "@calcom/lib/hooks/useLocale";
|
||||
|
||||
@@ -3,7 +3,7 @@
|
||||
import { noop } from "lodash";
|
||||
import { Controller, useForm } from "react-hook-form";
|
||||
|
||||
import { TimezoneSelect } from "@calcom/features/components/timezone-select";
|
||||
import { TimezoneSelect } from "@calcom/web/modules/timezone/components/TimezoneSelect";
|
||||
import { formatToLocalizedDate } from "@calcom/lib/dayjs";
|
||||
import { getUserAvatarUrl } from "@calcom/lib/getAvatarUrl";
|
||||
import { useLocale } from "@calcom/lib/hooks/useLocale";
|
||||
|
||||
@@ -24,7 +24,7 @@ import {
|
||||
} from "@calcom/features/bookings/Booker/utils/event";
|
||||
import DatePicker from "@calcom/features/calendars/DatePicker";
|
||||
import { Dialog } from "@calcom/features/components/controlled-dialog";
|
||||
import { TimezoneSelect } from "@calcom/features/components/timezone-select";
|
||||
import { TimezoneSelect } from "@calcom/web/modules/timezone/components/TimezoneSelect";
|
||||
import type { Slot } from "@calcom/features/schedules/lib/use-schedule/types";
|
||||
import { useNonEmptyScheduleDays } from "@calcom/features/schedules/lib/use-schedule/useNonEmptyScheduleDays";
|
||||
import { useSlotsForDate } from "@calcom/features/schedules/lib/use-schedule/useSlotsForDate";
|
||||
|
||||
@@ -14,7 +14,7 @@ import {
|
||||
import { Timezone as PlatformTimzoneSelect } from "@calcom/atoms/timezone";
|
||||
import getLocationsOptionsForSelect from "@calcom/features/bookings/lib/getLocationOptionsForSelect";
|
||||
import DestinationCalendarSelector from "@calcom/features/calendars/DestinationCalendarSelector";
|
||||
import { TimezoneSelect as WebTimezoneSelect } from "@calcom/features/components/timezone-select";
|
||||
import { TimezoneSelect as WebTimezoneSelect } from "@calcom/web/modules/timezone/components/TimezoneSelect";
|
||||
import useLockedFieldsManager from "@calcom/features/ee/managed-event-types/hooks/useLockedFieldsManager";
|
||||
import {
|
||||
allowDisablingAttendeeConfirmationEmails,
|
||||
|
||||
@@ -4,7 +4,7 @@ import { useLocale } from "@calcom/lib/hooks/useLocale";
|
||||
import { Badge } from "@calcom/ui/components/badge";
|
||||
import { Tooltip } from "@calcom/ui/components/tooltip";
|
||||
|
||||
import type { RoutingFormTableRow } from "@calcom/features/insights/lib/types";
|
||||
import type { RoutingFormTableRow } from "@calcom/web/modules/insights/lib/types";
|
||||
import { CellWithOverflowX } from "./CellWithOverflowX";
|
||||
|
||||
export function BookedByCell({
|
||||
|
||||
@@ -15,7 +15,7 @@ import {
|
||||
} from "@calcom/ui/components/hover-card";
|
||||
import { Icon } from "@calcom/ui/components/icon";
|
||||
|
||||
import type { RoutingFormTableRow } from "@calcom/features/insights/lib/types";
|
||||
import type { RoutingFormTableRow } from "@calcom/web/modules/insights/lib/types";
|
||||
import { BookingStatusBadge } from "./BookingStatusBadge";
|
||||
|
||||
export function BookingAtCell({ row, rowId }: { row: RoutingFormTableRow; rowId: number }) {
|
||||
|
||||
@@ -24,7 +24,7 @@ import { OrgTeamsFilter } from "../filters/OrgTeamsFilter";
|
||||
import { useInsightsColumns } from "@calcom/web/modules/insights/hooks/useInsightsColumns";
|
||||
import { useInsightsOrgTeams } from "@calcom/web/modules/insights/hooks/useInsightsOrgTeams";
|
||||
import { useInsightsRoutingFacetedUniqueValues } from "@calcom/web/modules/insights/hooks/useInsightsRoutingFacetedUniqueValues";
|
||||
import type { RoutingFormTableRow } from "@calcom/features/insights/lib/types";
|
||||
import type { RoutingFormTableRow } from "@calcom/web/modules/insights/lib/types";
|
||||
import { RoutingKPICards } from "./RoutingKPICards";
|
||||
import { EmptyScreen } from "@calcom/ui/components/empty-screen";
|
||||
import { useLocale } from "@calcom/lib/hooks/useLocale";
|
||||
|
||||
@@ -16,13 +16,13 @@ import { BookedByCell } from "../components/BookedByCell";
|
||||
import { BookingAtCell } from "../components/BookingAtCell";
|
||||
import { BookingStatusBadge } from "../components/BookingStatusBadge";
|
||||
import { ResponseValueCell } from "../components/ResponseValueCell";
|
||||
import type { HeaderRow, RoutingFormTableRow } from "@calcom/features/insights/lib/types";
|
||||
import type { HeaderRow, RoutingFormTableRow } from "@calcom/web/modules/insights/lib/types";
|
||||
import {
|
||||
ZResponseMultipleValues,
|
||||
ZResponseSingleValue,
|
||||
ZResponseTextValue,
|
||||
ZResponseNumericValue,
|
||||
} from "@calcom/features/insights/lib/types";
|
||||
} from "@calcom/web/modules/insights/lib/types";
|
||||
|
||||
export const useInsightsColumns = ({
|
||||
headers,
|
||||
|
||||
@@ -6,7 +6,7 @@ import { BookingStatus } from "@calcom/prisma/enums";
|
||||
import { trpc } from "@calcom/trpc/react";
|
||||
|
||||
import { bookingStatusToText } from "@calcom/features/insights/lib/bookingStatusToText";
|
||||
import type { HeaderRow } from "@calcom/features/insights/lib/types";
|
||||
import type { HeaderRow } from "@calcom/web/modules/insights/lib/types";
|
||||
|
||||
const statusOrder: Record<BookingStatus, number> = {
|
||||
[BookingStatus.ACCEPTED]: 1,
|
||||
|
||||
@@ -0,0 +1,26 @@
|
||||
import { z } from "zod";
|
||||
|
||||
import type { RouterOutputs } from "@calcom/trpc/react";
|
||||
|
||||
export type RoutingFormTableRow = RouterOutputs["viewer"]["insights"]["routingFormResponses"]["data"][number];
|
||||
|
||||
export type HeaderRow = RouterOutputs["viewer"]["insights"]["routingFormResponsesHeaders"][number];
|
||||
|
||||
export const ZResponseMultipleValues = z.array(z.string());
|
||||
|
||||
export const ZResponseSingleValue = z.string();
|
||||
|
||||
export const ZResponseTextValue = z.string();
|
||||
|
||||
export const ZResponseNumericValue = z.number();
|
||||
|
||||
export const ZResponseValue = z.union([
|
||||
ZResponseMultipleValues,
|
||||
ZResponseSingleValue,
|
||||
ZResponseTextValue,
|
||||
ZResponseNumericValue,
|
||||
]);
|
||||
|
||||
export type ResponseValue = z.infer<typeof ZResponseValue>;
|
||||
|
||||
export const ZResponse = z.record(z.string(), ZResponseValue);
|
||||
@@ -0,0 +1,122 @@
|
||||
"use client";
|
||||
|
||||
import { createContext, useContext, useEffect, useMemo, useState } from "react";
|
||||
|
||||
import { trpc } from "@calcom/trpc/react";
|
||||
import { showToast } from "@calcom/ui/components/toast";
|
||||
|
||||
interface WebPushContextProps {
|
||||
permission: NotificationPermission;
|
||||
isLoading: boolean;
|
||||
isSubscribed: boolean;
|
||||
subscribe: () => Promise<void>;
|
||||
unsubscribe: () => Promise<void>;
|
||||
}
|
||||
|
||||
export const WebPushContext = createContext<WebPushContextProps | null>(null);
|
||||
|
||||
interface ProviderProps {
|
||||
children: React.ReactNode;
|
||||
}
|
||||
|
||||
export function WebPushProvider({ children }: ProviderProps) {
|
||||
const [permission, setPermission] = useState<NotificationPermission>(() =>
|
||||
typeof window !== "undefined" && "Notification" in window ? Notification.permission : "denied"
|
||||
);
|
||||
const [pushManager, setPushManager] = useState<PushManager | null>(null);
|
||||
const [isLoading, setIsLoading] = useState(false);
|
||||
const [isSubscribed, setIsSubscribed] = useState(false);
|
||||
|
||||
const { mutate: addSubscription } =
|
||||
trpc.viewer.loggedInViewerRouter.addNotificationsSubscription.useMutation();
|
||||
const { mutate: removeSubscription } =
|
||||
trpc.viewer.loggedInViewerRouter.removeNotificationsSubscription.useMutation();
|
||||
|
||||
useEffect(() => {
|
||||
if (!("serviceWorker" in navigator)) return;
|
||||
|
||||
navigator.serviceWorker
|
||||
.register("/service-worker.js")
|
||||
.then(async (registration) => {
|
||||
if ("pushManager" in registration) {
|
||||
setPushManager(registration.pushManager);
|
||||
const subscription = await registration.pushManager.getSubscription();
|
||||
setIsSubscribed(!!subscription);
|
||||
}
|
||||
})
|
||||
.catch((error) => {
|
||||
console.error("Service Worker registration failed:", error);
|
||||
});
|
||||
}, []);
|
||||
|
||||
const contextValue = useMemo(
|
||||
() => ({
|
||||
permission,
|
||||
isLoading,
|
||||
isSubscribed,
|
||||
subscribe: async () => {
|
||||
try {
|
||||
setIsLoading(true);
|
||||
const newPermission = await Notification.requestPermission();
|
||||
setPermission(newPermission);
|
||||
|
||||
if (newPermission === "granted" && pushManager) {
|
||||
const subscription = await pushManager.subscribe({
|
||||
userVisibleOnly: true,
|
||||
applicationServerKey: urlB64ToUint8Array(process.env.NEXT_PUBLIC_VAPID_PUBLIC_KEY || ""),
|
||||
});
|
||||
addSubscription({ subscription: JSON.stringify(subscription) });
|
||||
setIsSubscribed(true);
|
||||
showToast("Notifications enabled successfully", "success");
|
||||
}
|
||||
} catch (error) {
|
||||
console.error("Failed to subscribe:", error);
|
||||
if (
|
||||
error instanceof DOMException &&
|
||||
error.name === "InvalidAccessError" &&
|
||||
error.message.includes("applicationServerKey")
|
||||
) {
|
||||
showToast("Please enable Google services for push messaging and try again", "error");
|
||||
} else {
|
||||
showToast("Failed to enable notifications", "error");
|
||||
}
|
||||
} finally {
|
||||
setIsLoading(false);
|
||||
}
|
||||
},
|
||||
unsubscribe: async () => {
|
||||
if (!pushManager) return;
|
||||
try {
|
||||
setIsLoading(true);
|
||||
const subscription = await pushManager.getSubscription();
|
||||
if (subscription) {
|
||||
const subscriptionJson = JSON.stringify(subscription);
|
||||
await subscription.unsubscribe();
|
||||
removeSubscription({ subscription: subscriptionJson });
|
||||
setIsSubscribed(false);
|
||||
showToast("Notifications disabled successfully", "success");
|
||||
}
|
||||
} catch (error) {
|
||||
console.error("Failed to unsubscribe:", error);
|
||||
showToast("Failed to disable notifications", "error");
|
||||
} finally {
|
||||
setIsLoading(false);
|
||||
}
|
||||
},
|
||||
}),
|
||||
[permission, isLoading, isSubscribed, pushManager, addSubscription, removeSubscription]
|
||||
);
|
||||
|
||||
return <WebPushContext.Provider value={contextValue}>{children}</WebPushContext.Provider>;
|
||||
}
|
||||
|
||||
const urlB64ToUint8Array = (base64String: string) => {
|
||||
const padding = "=".repeat((4 - (base64String.length % 4)) % 4);
|
||||
const base64 = (base64String + padding).replace(/\-/g, "+").replace(/_/g, "/");
|
||||
const rawData = window.atob(base64);
|
||||
const outputArray = new Uint8Array(rawData.length);
|
||||
for (let i = 0; i < rawData.length; ++i) {
|
||||
outputArray[i] = rawData.charCodeAt(i);
|
||||
}
|
||||
return outputArray;
|
||||
};
|
||||
@@ -0,0 +1,11 @@
|
||||
import { useContext } from "react";
|
||||
|
||||
import { WebPushContext } from "../components/WebPushContext";
|
||||
|
||||
export function useWebPush() {
|
||||
const context = useContext(WebPushContext);
|
||||
if (!context) {
|
||||
throw new Error("useWebPush must be used within a WebPushProvider");
|
||||
}
|
||||
return context;
|
||||
}
|
||||
@@ -0,0 +1,134 @@
|
||||
"use client";
|
||||
|
||||
import type { ManipulateType as DayjsManipulateType } from "dayjs";
|
||||
import { useSession } from "next-auth/react";
|
||||
import { useEffect, useState } from "react";
|
||||
|
||||
import dayjs from "@calcom/dayjs";
|
||||
import { Dialog } from "@calcom/features/components/controlled-dialog";
|
||||
import { useLocale } from "@calcom/lib/hooks/useLocale";
|
||||
import { CURRENT_TIMEZONE } from "@calcom/lib/timezoneConstants";
|
||||
import { trpc } from "@calcom/trpc/react";
|
||||
import { DialogContent, DialogFooter, DialogHeader, DialogClose } from "@calcom/ui/components/dialog";
|
||||
import { showToast } from "@calcom/ui/components/toast";
|
||||
|
||||
function hideDialogFor(hideFor: [number, DayjsManipulateType], toastContent: string) {
|
||||
document.cookie = `calcom-timezone-dialog=1;max-age=${
|
||||
dayjs().add(hideFor[0], hideFor[1]).unix() - dayjs().unix()
|
||||
}`;
|
||||
if (toastContent) showToast(toastContent, "success");
|
||||
}
|
||||
|
||||
const TimezoneChangeDialogContent = () => {
|
||||
const { t, isLocaleReady } = useLocale();
|
||||
if (!isLocaleReady) return null;
|
||||
|
||||
const utils = trpc.useUtils();
|
||||
|
||||
const formattedCurrentTz = CURRENT_TIMEZONE.replace("_", " ");
|
||||
|
||||
const onMutationSuccess = async () => {
|
||||
showToast(
|
||||
t("updated_timezone_to", { formattedCurrentTz, interpolation: { escapeValue: false } }),
|
||||
"success"
|
||||
);
|
||||
await utils.viewer.me.invalidate();
|
||||
};
|
||||
|
||||
const onMutationError = () => {
|
||||
showToast(t("couldnt_update_timezone"), "error");
|
||||
};
|
||||
|
||||
// update timezone in db
|
||||
const mutation = trpc.viewer.me.updateProfile.useMutation({
|
||||
onSuccess: onMutationSuccess,
|
||||
onError: onMutationError,
|
||||
});
|
||||
|
||||
const updateTimezone = () => {
|
||||
mutation.mutate({
|
||||
timeZone: CURRENT_TIMEZONE,
|
||||
});
|
||||
};
|
||||
|
||||
return (
|
||||
<>
|
||||
<DialogHeader
|
||||
title={t("update_timezone_question")}
|
||||
subtitle={t("update_timezone_description", {
|
||||
formattedCurrentTz,
|
||||
interpolation: { escapeValue: false },
|
||||
})}
|
||||
/>
|
||||
{/* todo: save this in db and auto-update when timezone changes (be able to disable??? if yes, /settings)
|
||||
<Checkbox description="Always update timezone" />
|
||||
*/}
|
||||
<div className="mb-8" />
|
||||
<DialogFooter showDivider>
|
||||
<DialogClose onClick={() => hideDialogFor([3, "months"], t("we_wont_show_again"))} color="secondary">
|
||||
{t("dont_update")}
|
||||
</DialogClose>
|
||||
<DialogClose onClick={() => updateTimezone()} color="primary">
|
||||
{t("update_timezone")}
|
||||
</DialogClose>
|
||||
</DialogFooter>
|
||||
</>
|
||||
);
|
||||
};
|
||||
|
||||
export function useOpenTimezoneDialog() {
|
||||
const { data: user } = trpc.viewer.me.get.useQuery();
|
||||
const [showDialog, setShowDialog] = useState(false);
|
||||
const { data: userSession, status } = useSession();
|
||||
|
||||
useEffect(() => {
|
||||
if (!user?.timeZone || status !== "authenticated" || userSession?.user?.impersonatedBy) {
|
||||
return;
|
||||
}
|
||||
|
||||
if (
|
||||
dayjs.tz(undefined, CURRENT_TIMEZONE).utcOffset() !== dayjs.tz(undefined, user.timeZone).utcOffset()
|
||||
) {
|
||||
setShowDialog(true);
|
||||
}
|
||||
}, [user?.timeZone, status, userSession?.user?.impersonatedBy]);
|
||||
|
||||
return { open: showDialog, setOpen: setShowDialog };
|
||||
}
|
||||
|
||||
function TimezoneChangeDialogContainer() {
|
||||
const { open, setOpen } = useOpenTimezoneDialog();
|
||||
const { t } = useLocale();
|
||||
|
||||
const handleInteractOutside = () => {
|
||||
hideDialogFor([1, "day"], t("we_wont_show_again"));
|
||||
};
|
||||
|
||||
return (
|
||||
<Dialog open={open} onOpenChange={setOpen}>
|
||||
{/* Dismiss dialog for a day on outside interaction */}
|
||||
<DialogContent type="creation" onInteractOutside={handleInteractOutside}>
|
||||
<TimezoneChangeDialogContent />
|
||||
</DialogContent>
|
||||
</Dialog>
|
||||
);
|
||||
}
|
||||
|
||||
export default function TimezoneChangeDialog() {
|
||||
const [renderDialog, setRenderDialog] = useState(false);
|
||||
useEffect(() => {
|
||||
if (typeof window !== "undefined" && document) {
|
||||
const cookie = document.cookie
|
||||
.split(";")
|
||||
.find((cookie) => cookie.trim().startsWith("calcom-timezone-dialog"));
|
||||
if (!cookie) {
|
||||
setRenderDialog(true);
|
||||
}
|
||||
}
|
||||
}, []);
|
||||
// bail if the cookie exists or window/document is not available
|
||||
if (!renderDialog) {
|
||||
return null;
|
||||
}
|
||||
return <TimezoneChangeDialogContainer />;
|
||||
}
|
||||
@@ -5,7 +5,7 @@ import { useSession } from "next-auth/react";
|
||||
import { useState } from "react";
|
||||
import { Controller, useForm } from "react-hook-form";
|
||||
|
||||
import { TimezoneSelect } from "@calcom/features/components/timezone-select";
|
||||
import { TimezoneSelect } from "@calcom/web/modules/timezone/components/TimezoneSelect";
|
||||
import SectionBottomActions from "@calcom/features/settings/SectionBottomActions";
|
||||
import SettingsHeader from "@calcom/features/settings/appDir/SettingsHeader";
|
||||
import { formatLocalizedDateTime } from "@calcom/lib/dayjs";
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
"use client";
|
||||
|
||||
import { useWebPush } from "@calcom/features/notifications/WebPushContext";
|
||||
import { useWebPush } from "@calcom/web/modules/notifications/hooks/useWebPush";
|
||||
import SettingsHeader from "@calcom/features/settings/appDir/SettingsHeader";
|
||||
import { useLocale } from "@calcom/lib/hooks/useLocale";
|
||||
import { Button } from "@calcom/ui/components/button";
|
||||
|
||||
@@ -3,13 +3,14 @@
|
||||
import { useSession } from "next-auth/react";
|
||||
import { useRouter } from "next/navigation";
|
||||
import type { Dispatch, ReactElement, ReactNode, SetStateAction } from "react";
|
||||
import React, { cloneElement } from "react";
|
||||
import type React from "react";
|
||||
import { cloneElement } from "react";
|
||||
import { Toaster } from "sonner";
|
||||
|
||||
import { useRedirectToLoginIfUnauthenticated } from "@calcom/features/auth/lib/hooks/useRedirectToLoginIfUnauthenticated";
|
||||
import { useRedirectToOnboardingIfNeeded } from "@calcom/features/auth/lib/hooks/useRedirectToOnboardingIfNeeded";
|
||||
import { useFormbricks } from "@calcom/features/formbricks/formbricks-client";
|
||||
import TimezoneChangeDialog from "@calcom/features/settings/TimezoneChangeDialog";
|
||||
import TimezoneChangeDialog from "@calcom/web/modules/settings/components/TimezoneChangeDialog";
|
||||
import { useLocale } from "@calcom/lib/hooks/useLocale";
|
||||
import classNames from "@calcom/ui/classNames";
|
||||
import { Button } from "@calcom/ui/components/button";
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
import { useFieldArray, useForm, useFormContext } from "react-hook-form";
|
||||
|
||||
import dayjs from "@calcom/dayjs";
|
||||
import { TimezoneSelect } from "@calcom/features/components/timezone-select";
|
||||
import { TimezoneSelect } from "@calcom/web/modules/timezone/components/TimezoneSelect";
|
||||
import DateOverrideInputDialog from "@calcom/features/schedules/components/DateOverrideInputDialog";
|
||||
import DateOverrideList from "@calcom/features/schedules/components/DateOverrideList";
|
||||
import Schedule from "@calcom/features/schedules/components/Schedule";
|
||||
|
||||
@@ -0,0 +1,194 @@
|
||||
/* eslint-disable playwright/missing-playwright-await */
|
||||
import { render, screen, waitFor, fireEvent } from "@testing-library/react";
|
||||
import type { Props as SelectProps } from "react-timezone-select";
|
||||
import { vi } from "vitest";
|
||||
|
||||
import dayjs from "@calcom/dayjs";
|
||||
|
||||
import { TimezoneSelect } from "./TimezoneSelect";
|
||||
|
||||
const cityTimezonesMock = [
|
||||
{ city: "Dawson City", timezone: "America/Dawson" },
|
||||
{ city: "Honolulu", timezone: "Pacific/Honolulu" },
|
||||
{ city: "Juneau", timezone: "America/Juneau" },
|
||||
{ city: "Toronto", timezone: "America/Toronto" },
|
||||
];
|
||||
|
||||
const runtimeMock = async (isPending: boolean) => {
|
||||
const updatedTrcp = {
|
||||
viewer: {
|
||||
timezones: {
|
||||
cityTimezones: {
|
||||
useQuery() {
|
||||
return {
|
||||
data: cityTimezonesMock,
|
||||
isPending,
|
||||
};
|
||||
},
|
||||
},
|
||||
},
|
||||
},
|
||||
};
|
||||
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
||||
const mockedLib = (await import("@calcom/trpc/react")) as any;
|
||||
mockedLib.trpc = updatedTrcp;
|
||||
};
|
||||
|
||||
const formatOffset = (offset: string) =>
|
||||
offset.replace(/^([-+])(0)(\d):00$/, (_, sign, _zero, hour) => `${sign}${hour}:00`);
|
||||
const formatTimeZoneWithOffset = (timeZone: string) =>
|
||||
`${timeZone} GMT ${formatOffset(dayjs.tz(undefined, timeZone).format("Z"))}`;
|
||||
|
||||
const timezoneMockValues = ["America/Dawson", "Pacific/Honolulu", "America/Juneau", "America/Toronto"];
|
||||
const optionMockValues = timezoneMockValues.map(formatTimeZoneWithOffset);
|
||||
|
||||
const classNames = {
|
||||
singleValue: () => "test1",
|
||||
valueContainer: () => "test2",
|
||||
control: () => "test3",
|
||||
input: () => "test4",
|
||||
option: () => "test5",
|
||||
menuList: () => "test6",
|
||||
menu: () => "test7",
|
||||
multiValue: () => "test8",
|
||||
};
|
||||
|
||||
const onChangeMock = vi.fn();
|
||||
|
||||
const renderSelect = (newProps: SelectProps & { variant?: "default" | "minimal" }) => {
|
||||
render(
|
||||
<form aria-label="test-form">
|
||||
<label htmlFor="test">Test</label>
|
||||
<TimezoneSelect {...newProps} inputId="test" />
|
||||
</form>
|
||||
);
|
||||
};
|
||||
|
||||
const openMenu = async () => {
|
||||
await waitFor(async () => {
|
||||
const element = screen.getByLabelText("Test");
|
||||
element.focus();
|
||||
fireEvent.keyDown(element, { key: "ArrowDown", code: "ArrowDown" });
|
||||
screen.getByText(optionMockValues[0]);
|
||||
});
|
||||
};
|
||||
|
||||
describe("Test TimezoneSelect", () => {
|
||||
afterEach(() => {
|
||||
vi.clearAllMocks();
|
||||
vi.resetAllMocks();
|
||||
});
|
||||
|
||||
describe("Test TimezoneSelect with isPending = false", () => {
|
||||
beforeAll(async () => {
|
||||
// INFO: This needs to be here before the other calls to runtimeMock. For some reason,
|
||||
// when we moved this file from @calcom/ui, the imports started breaking, resulting in
|
||||
// errors of "Cannot set property 'trpc' of [object Module] which has only a getter"
|
||||
// TODO: Update this pattern to be more consistent. Using this direct mocking in the
|
||||
// functions below breaks some tests.
|
||||
vi.mock("@calcom/trpc/react", () => ({
|
||||
trpc: {
|
||||
viewer: {
|
||||
timezones: {
|
||||
cityTimezones: {
|
||||
useQuery() {
|
||||
return {
|
||||
data: cityTimezonesMock,
|
||||
isPending: false,
|
||||
};
|
||||
},
|
||||
},
|
||||
},
|
||||
},
|
||||
},
|
||||
}));
|
||||
});
|
||||
test("Should render with the correct CSS when provided with classNames prop", async () => {
|
||||
renderSelect({ value: timezoneMockValues[0], classNames });
|
||||
openMenu();
|
||||
|
||||
const dawsonEl = screen.getByText(timezoneMockValues[0]);
|
||||
|
||||
expect(dawsonEl).toBeInTheDocument();
|
||||
|
||||
const singleValueEl = dawsonEl.parentElement;
|
||||
const valueContainerEl = singleValueEl?.parentElement;
|
||||
const controlEl = valueContainerEl?.parentElement;
|
||||
const inputEl = screen.getByRole("combobox", { hidden: true }).parentElement;
|
||||
const optionEl = screen.getByText(optionMockValues[0]).parentElement?.parentElement;
|
||||
const menuListEl = optionEl?.parentElement;
|
||||
const menuEl = menuListEl?.parentElement;
|
||||
|
||||
expect(singleValueEl).toHaveClass(classNames.singleValue());
|
||||
expect(valueContainerEl).toHaveClass(classNames.valueContainer());
|
||||
expect(controlEl).toHaveClass(classNames.control());
|
||||
expect(inputEl).toHaveClass(classNames.input());
|
||||
expect(optionEl).toHaveClass(classNames.option());
|
||||
expect(menuListEl).toHaveClass(classNames.menuList());
|
||||
expect(menuEl).toHaveClass(classNames.menu());
|
||||
|
||||
for (const mockText of optionMockValues) {
|
||||
expect(screen.getByText(mockText)).toBeInTheDocument();
|
||||
}
|
||||
});
|
||||
|
||||
test("Should render with the correct CSS when provided with className prop", async () => {
|
||||
renderSelect({ value: timezoneMockValues[0], className: "test-css" });
|
||||
openMenu();
|
||||
const labelTest = screen.getByText("Test");
|
||||
const timezoneEl = labelTest.nextSibling;
|
||||
expect(timezoneEl).toHaveClass("test-css");
|
||||
});
|
||||
|
||||
test("Should render with the correct CSS when isMulti is enabled", async () => {
|
||||
renderSelect({ value: timezoneMockValues[0], isMulti: true, classNames });
|
||||
openMenu();
|
||||
|
||||
const dawsonEl = screen.getByText(timezoneMockValues[0]);
|
||||
const multiValueEl = dawsonEl.parentElement?.parentElement;
|
||||
expect(multiValueEl).toHaveClass(classNames.multiValue());
|
||||
|
||||
const inputEl = screen.getByRole("combobox", { hidden: true }).parentElement;
|
||||
const menuIsOpenEl = inputEl?.parentElement?.nextSibling;
|
||||
expect(menuIsOpenEl).toHaveClass("[&>*:last-child]:rotate-180 [&>*:last-child]:transition-transform ");
|
||||
});
|
||||
|
||||
test("Should render with the correct CSS when menu is open and onChange is called", async () => {
|
||||
renderSelect({ value: timezoneMockValues[0], onChange: onChangeMock });
|
||||
await waitFor(async () => {
|
||||
const element = screen.getByLabelText("Test");
|
||||
element.focus();
|
||||
fireEvent.keyDown(element, { key: "ArrowDown", code: "ArrowDown" });
|
||||
screen.getByText(optionMockValues[3]);
|
||||
|
||||
const inputEl = screen.getByRole("combobox", { hidden: true }).parentElement;
|
||||
const menuIsOpenEl = inputEl?.parentElement?.nextSibling;
|
||||
expect(menuIsOpenEl).toHaveClass("rotate-180 transition-transform ");
|
||||
const opt = screen.getByText(optionMockValues[3]);
|
||||
fireEvent.click(opt);
|
||||
fireEvent.keyDown(element, { key: "ArrowDown", code: "ArrowDown" });
|
||||
});
|
||||
|
||||
expect(onChangeMock).toBeCalled();
|
||||
});
|
||||
});
|
||||
|
||||
describe("Test TimezoneSelect with isPending = true", () => {
|
||||
beforeAll(async () => {
|
||||
await runtimeMock(true);
|
||||
});
|
||||
test("Should have no options when isPending is true", async () => {
|
||||
renderSelect({ value: timezoneMockValues[0] });
|
||||
await waitFor(async () => {
|
||||
const element = screen.getByLabelText("Test");
|
||||
element.focus();
|
||||
fireEvent.keyDown(element, { key: "ArrowDown", code: "ArrowDown" });
|
||||
});
|
||||
|
||||
for (const mockText of optionMockValues) {
|
||||
const optionEl = screen.queryByText(mockText);
|
||||
expect(optionEl).toBeNull();
|
||||
}
|
||||
});
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,60 @@
|
||||
"use client";
|
||||
|
||||
import type { Timezones } from "@calcom/lib/timezone";
|
||||
import { TimezoneSelectComponent } from "@calcom/features/timezone/components/TimezoneSelectComponent";
|
||||
import { CALCOM_VERSION } from "@calcom/lib/constants";
|
||||
import { trpc } from "@calcom/trpc/react";
|
||||
import { useMemo } from "react";
|
||||
import type { Props as SelectProps } from "react-timezone-select";
|
||||
|
||||
const SELECT_SEARCH_DATA: Timezones = [
|
||||
{ label: "San Francisco", timezone: "America/Los_Angeles" },
|
||||
{ label: "Sao Francisco do Sul", timezone: "America/Sao_Paulo" },
|
||||
{ label: "San Francisco de Macoris", timezone: "America/Santo_Domingo" },
|
||||
{ label: "San Francisco Gotera", timezone: "America/El_Salvador" },
|
||||
{ label: "Eastern Time - US & Canada", timezone: "America/New_York" },
|
||||
{ label: "Pacific Time - US & Canada", timezone: "America/Los_Angeles" },
|
||||
{ label: "Central Time - US & Canada", timezone: "America/Chicago" },
|
||||
{ label: "Mountain Time - US & Canada", timezone: "America/Denver" },
|
||||
{ label: "Atlantic Time - Canada", timezone: "America/Halifax" },
|
||||
{ label: "Eastern European Time", timezone: "Europe/Bucharest" },
|
||||
{ label: "Central European Time", timezone: "Europe/Berlin" },
|
||||
{ label: "Western European Time", timezone: "Europe/London" },
|
||||
{ label: "Australian Eastern Time", timezone: "Australia/Sydney" },
|
||||
{ label: "Japan Standard Time", timezone: "Asia/Tokyo" },
|
||||
{ label: "India Standard Time", timezone: "Asia/Kolkata" },
|
||||
{ label: "Gulf Standard Time", timezone: "Asia/Dubai" },
|
||||
{ label: "South Africa Standard Time", timezone: "Africa/Johannesburg" },
|
||||
{ label: "Brazil Time", timezone: "America/Sao_Paulo" },
|
||||
{ label: "Hawaii-Aleutian Standard Time", timezone: "Pacific/Honolulu" },
|
||||
];
|
||||
|
||||
export type TimezoneSelectProps = SelectProps & {
|
||||
variant?: "default" | "minimal";
|
||||
timezoneSelectCustomClassname?: string;
|
||||
size?: "sm" | "md";
|
||||
grow?: boolean;
|
||||
};
|
||||
|
||||
export function TimezoneSelect(props: TimezoneSelectProps) {
|
||||
const { data = [], isPending } = trpc.viewer.timezones.cityTimezones.useQuery(
|
||||
{
|
||||
CalComVersion: CALCOM_VERSION,
|
||||
},
|
||||
{
|
||||
trpc: { context: { skipBatch: true } },
|
||||
}
|
||||
);
|
||||
|
||||
const cityTimezonesFormatted = useMemo(
|
||||
() => data.map(({ city, timezone }) => ({ label: city, timezone })),
|
||||
[data]
|
||||
);
|
||||
|
||||
const combinedData = useMemo(
|
||||
() => [...cityTimezonesFormatted, ...SELECT_SEARCH_DATA],
|
||||
[cityTimezonesFormatted]
|
||||
);
|
||||
|
||||
return <TimezoneSelectComponent data={combinedData} isPending={isPending} {...props} />;
|
||||
}
|
||||
@@ -5,7 +5,7 @@ import { useMemo, useState } from "react";
|
||||
import { Controller, useForm, useFormContext } from "react-hook-form";
|
||||
import { z } from "zod";
|
||||
|
||||
import { TimezoneSelect } from "@calcom/features/components/timezone-select";
|
||||
import { TimezoneSelect } from "@calcom/web/modules/timezone/components/TimezoneSelect";
|
||||
import { timeZoneSchema } from "@calcom/lib/dayjs/timeZone.schema";
|
||||
import { emailSchema } from "@calcom/lib/emailSchema";
|
||||
import { useLocale } from "@calcom/lib/hooks/useLocale";
|
||||
|
||||
@@ -4,7 +4,7 @@ import { SessionProvider } from "next-auth/react";
|
||||
import React from "react";
|
||||
import CacheProvider from "react-inlinesvg/provider";
|
||||
|
||||
import { WebPushProvider } from "@calcom/features/notifications/WebPushContext";
|
||||
import { WebPushProvider } from "@calcom/web/modules/notifications/components/WebPushContext";
|
||||
import { trpc } from "@calcom/trpc/react";
|
||||
|
||||
import type { AppProps } from "@lib/app-providers";
|
||||
|
||||
Reference in new issue
Block a user