chore: App-router-migration(/availability) add pages / extract components into /module (#16404)

* migrate availability/[schedule]

* add use client directive

* migrate main availability page

* migrate availability/troubleshoot page

* add env var

* extract AvailabilitySettingsWebWrapper into /modules

* fix build

* add missing default

* add missing export

* fix troubleshoot

* use params, not searchParams in generateMetadata

* fix schedule page in app router
This commit is contained in:
Benny Joo authored and GitHub committed 2024-09-05 12:37:18 +00:00
1 parent fabcf2055b
commit 963d22648b
18 files changed
+416 -276

No files matched your search

@@ -38,12 +38,29 @@ export const getEmbedIframe = async ({
page: Page;
pathname: string;
}) => {
const handleFrameErrors = (frame: Frame) => {
frame.on("pageerror", (error) => {
console.error(`Iframe error (${frame.url()}): ${error.message}`);
});
frame.on("requestfailed", (request) => {
console.error(
`Iframe failed request (${frame.url()}): ${request.url()}, ${request.failure()?.errorText}`
);
});
};
// We can't seem to access page.frame till contentWindow is available. So wait for that.
const iframeReady = await page.evaluate(
(hardTimeout) => {
return new Promise((resolve) => {
const interval = setInterval(() => {
const iframe = document.querySelector<HTMLIFrameElement>(".cal-embed");
if (iframe) {
console.log("Iframe found");
}
if (iframe?.contentWindow) {
console.log("Iframe contentWindow found");
}
// eslint-disable-next-line @typescript-eslint/ban-ts-comment
// @ts-ignore
if (iframe && iframe.contentWindow && window.iframeReady) {
@@ -74,9 +91,12 @@ export const getEmbedIframe = async ({
return null;
}
page.on("frameattached", handleFrameErrors);
// We just verified that iframeReady is true here, so obviously embedIframe is not null
// eslint-disable-next-line @typescript-eslint/no-non-null-assertion
const embedIframe = page.frame(`cal-embed=${calNamespace}`)!;
handleFrameErrors(embedIframe);
const u = new URL(embedIframe.url());
if (u.pathname === `${pathname}/embed`) {
return embedIframe;
+19 -4
View File
@@ -2,11 +2,12 @@ import type { EventType } from "@prisma/client";
import { useRouter } from "next/navigation";
import type { PaymentPageProps } from "@calcom/ee/payments/pages/payment";
import { useIsEmbed } from "@calcom/embed-core/embed-iframe";
import type { BookingResponse } from "@calcom/features/bookings/types";
import { useCompatSearchParams } from "@calcom/lib/hooks/useCompatSearchParams";
import { navigateInTopWindow } from "@calcom/lib/navigateInTopWindow";
function getNewSeachParams(args: {
function getNewSearchParams(args: {
query: Record<string, string | null | undefined | boolean>;
searchParams?: URLSearchParams;
}) {
@@ -44,6 +45,7 @@ export const getBookingRedirectExtraParams = (booking: SuccessRedirectBookingTyp
export const useBookingSuccessRedirect = () => {
const router = useRouter();
const searchParams = useCompatSearchParams();
const isEmbed = useIsEmbed();
const bookingSuccessRedirect = ({
successRedirectUrl,
query,
@@ -63,7 +65,7 @@ export const useBookingSuccessRedirect = () => {
return;
}
const bookingExtraParams = getBookingRedirectExtraParams(booking);
const newSearchParams = getNewSeachParams({
const newSearchParams = getNewSearchParams({
query: {
...query,
...bookingExtraParams,
@@ -78,8 +80,21 @@ export const useBookingSuccessRedirect = () => {
navigateInTopWindow(url.toString());
return;
}
const newSearchParams = getNewSeachParams({ query });
return router.push(`/booking/${booking.uid}?${newSearchParams.toString()}`);
// TODO: Abstract it out and reuse at other places where we navigate within the embed. Though this is needed only in case of hard navigation happening but we aren't sure where hard navigation happens and where a soft navigation
// This is specially true after App Router it seems
const headersRelatedSearchParams = searchParams
? {
"flag.coep": searchParams.get("flag.coep") ?? "false",
}
: undefined;
// We don't want to forward all search params, as they could possibly break the booking page.
const newSearchParams = getNewSearchParams({
query,
searchParams: new URLSearchParams(headersRelatedSearchParams),
});
return router.push(`/booking/${booking.uid}${isEmbed ? "/embed" : ""}?${newSearchParams.toString()}`);
};
return bookingSuccessRedirect;
@@ -0,0 +1,20 @@
import prisma from "@calcom/prisma";
export class ScheduleRepository {
static async findScheduleById({ id }: { id: number }) {
const schedule = await prisma.schedule.findUnique({
where: {
id,
},
select: {
id: true,
userId: true,
name: true,
availability: true,
timeZone: true,
},
});
return schedule;
}
}
@@ -1,123 +0,0 @@
import { useRouter } from "next/navigation";
import { useState } from "react";
import { withErrorFromUnknown } from "@calcom/lib/getClientErrorFromUnknown";
import { useCompatSearchParams } from "@calcom/lib/hooks/useCompatSearchParams";
import { useLocale } from "@calcom/lib/hooks/useLocale";
import { HttpError } from "@calcom/lib/http-error";
import { trpc } from "@calcom/trpc/react";
import useMeQuery from "@calcom/trpc/react/hooks/useMeQuery";
import { showToast } from "@calcom/ui";
import { AvailabilitySettings } from "../AvailabilitySettings";
export const AvailabilitySettingsWebWrapper = () => {
const searchParams = useCompatSearchParams();
const { t } = useLocale();
const router = useRouter();
const utils = trpc.useUtils();
const me = useMeQuery();
const scheduleId = searchParams?.get("schedule") ? Number(searchParams.get("schedule")) : -1;
const fromEventType = searchParams?.get("fromEventType");
const { timeFormat } = me.data || { timeFormat: null };
const { data: schedule, isPending } = trpc.viewer.availability.schedule.get.useQuery(
{ scheduleId },
{
enabled: !!scheduleId,
}
);
const { data: travelSchedules, isPending: isPendingTravelSchedules } =
trpc.viewer.getTravelSchedules.useQuery();
const [isBulkUpdateModalOpen, setIsBulkUpdateModalOpen] = useState(false);
const bulkUpdateDefaultAvailabilityMutation =
trpc.viewer.availability.schedule.bulkUpdateToDefaultAvailability.useMutation({
onSuccess: () => {
utils.viewer.availability.list.invalidate();
setIsBulkUpdateModalOpen(false);
showToast(t("success"), "success");
},
});
const isDefaultSchedule = me.data?.defaultScheduleId === scheduleId;
const updateMutation = trpc.viewer.availability.schedule.update.useMutation({
onSuccess: async ({ prevDefaultId, currentDefaultId, ...data }) => {
if (prevDefaultId && currentDefaultId) {
// check weather the default schedule has been changed by comparing previous default schedule id and current default schedule id.
if (prevDefaultId !== currentDefaultId) {
// if not equal, invalidate previous default schedule id and refetch previous default schedule id.
utils.viewer.availability.schedule.get.invalidate({ scheduleId: prevDefaultId });
utils.viewer.availability.schedule.get.refetch({ scheduleId: prevDefaultId });
}
}
utils.viewer.availability.schedule.get.invalidate({ scheduleId: data.schedule.id });
utils.viewer.availability.list.invalidate();
showToast(
t("availability_updated_successfully", {
scheduleName: data.schedule.name,
}),
"success"
);
},
onError: (err) => {
if (err instanceof HttpError) {
const message = `${err.statusCode}: ${err.message}`;
showToast(message, "error");
}
},
});
const deleteMutation = trpc.viewer.availability.schedule.delete.useMutation({
onError: withErrorFromUnknown((err) => {
showToast(err.message, "error");
}),
onSettled: () => {
utils.viewer.availability.list.invalidate();
},
onSuccess: () => {
showToast(t("schedule_deleted_successfully"), "success");
router.push("/availability");
},
});
// TODO: reimplement Skeletons for this page in here
if (isPending) return null;
// We wait for the schedule to be loaded before rendering the form inside AvailabilitySettings
// since `defaultValues` cannot be redeclared after first render and using `values` will
// trigger a form reset when revalidating. Introducing flaky behavior.
if (!schedule) return null;
return (
<AvailabilitySettings
schedule={schedule}
travelSchedules={isDefaultSchedule ? travelSchedules || [] : []}
isDeleting={deleteMutation.isPending}
isLoading={isPending}
isSaving={updateMutation.isPending}
enableOverrides={true}
timeFormat={timeFormat}
weekStart={me.data?.weekStart || "Sunday"}
backPath={fromEventType ? true : "/availability"}
handleDelete={() => {
scheduleId && deleteMutation.mutate({ scheduleId });
}}
handleSubmit={async ({ dateOverrides, ...values }) => {
scheduleId &&
updateMutation.mutate({
scheduleId,
dateOverrides: dateOverrides.flatMap((override) => override.ranges),
...values,
});
}}
bulkUpdateModalProps={{
isOpen: isBulkUpdateModalOpen,
setIsOpen: setIsBulkUpdateModalOpen,
save: bulkUpdateDefaultAvailabilityMutation.mutate,
isSaving: bulkUpdateDefaultAvailabilityMutation.isPending,
}}
/>
);
};
+1 -1
View File
@@ -1,5 +1,4 @@
export { BookerWebWrapper as Booker } from "./booker";
export { AvailabilitySettingsWebWrapper as AvailabilitySettings } from "./availability/wrappers/AvailabilitySettingsWebWrapper";
export { CalProvider } from "./cal-provider/CalProvider";
export { useIsPlatform } from "./hooks/useIsPlatform";
export { useAtomsContext } from "./hooks/useAtomsContext";
@@ -9,3 +8,4 @@ export * as Dialog from "./src/components/ui/dialog";
export { Timezone } from "./timezone";
export { SelectedCalendarsSettingsWebWrapper } from "./selected-calendars/wrappers/SelectedCalendarsSettingsWebWrapper";
export { DestinationCalendarSettingsWebWrapper } from "./destination-calendar/wrappers/DestinationCalendarSettingsWebWrapper";
export * from "./availability";