feat: Event Type Atom base pr (#16831)

* feat: Event Type Atom base pr

* fixup! Merge branch 'main' into chore-event-type-atom-platform-wrapper-base-pr

* Update EventTypeWebWrapper.tsx

---------

Co-authored-by: Somay Chauhan <[email protected]>
This commit is contained in:
MorganandSomay Chauhan authored and GitHub committed 2024-09-30 13:44:11 +03:00
1 parent ac300ff670
commit ad347cb59f
29 files changed
+1148 -357

No files matched your search

@@ -3,8 +3,6 @@
/* eslint-disable @typescript-eslint/no-empty-function */
import { useAutoAnimate } from "@formkit/auto-animate/react";
import type { UseFormReturn } from "react-hook-form";
// eslint-disable-next-line @calcom/eslint/deprecated-imports-next-router
import { z } from "zod";
import type { Workflow } from "@calcom/features/ee/workflows/lib/types";
import type { ChildrenEventType } from "@calcom/features/eventtypes/components/ChildrenEventTypeSelect";
@@ -14,9 +12,9 @@ import type {
FormValues,
EventTypeApps,
} from "@calcom/features/eventtypes/lib/types";
import { useTypedQuery } from "@calcom/lib/hooks/useTypedQuery";
import type { customInputSchema } from "@calcom/prisma/zod-utils";
import type { RouterOutputs } from "@calcom/trpc/react";
import type { VerticalTabItemProps } from "@calcom/ui";
import { Form } from "@calcom/ui";
import { EventTypeSingleLayout } from "./EventTypeLayout";
@@ -31,24 +29,19 @@ export type Host = {
export type CustomInputParsed = typeof customInputSchema._output;
const querySchema = z.object({
tabName: z
.enum([
"setup",
"availability",
"apps",
"limits",
"instant",
"recurring",
"team",
"advanced",
"workflows",
"webhooks",
"ai",
])
.optional()
.default("setup"),
});
const tabs = [
"setup",
"availability",
"team",
"limits",
"advanced",
"instant",
"recurring",
"apps",
"workflows",
"webhooks",
"ai",
] as const;
export type EventTypeSetup = RouterOutputs["viewer"]["eventTypes"]["get"]["eventType"];
export type EventTypeAssignedUsers = RouterOutputs["viewer"]["eventTypes"]["get"]["eventType"]["children"];
@@ -58,47 +51,29 @@ export const EventType = (
props: EventTypeSetupProps & {
allActiveWorkflows?: Workflow[];
tabMap: TabMap;
onDelete: () => void;
onDelete: (id: number) => void;
isDeleting?: boolean;
onConflict: (eventTypes: ChildrenEventType[]) => void;
children?: React.ReactNode;
handleSubmit: (values: FormValues) => void;
formMethods: UseFormReturn<FormValues>;
eventTypeApps?: EventTypeApps;
isUpdating: boolean;
isPlatform?: boolean;
tabName: (typeof tabs)[number];
tabsNavigation: VerticalTabItemProps[];
}
) => {
const {
data: { tabName },
} = useTypedQuery(querySchema);
const { formMethods, eventTypeApps } = props;
const { formMethods, isPlatform, tabName } = props;
const { eventType, team, currentUserMembership, tabMap, isUpdating } = props;
const [animationParentRef] = useAutoAnimate<HTMLDivElement>();
const appsMetadata = formMethods.getValues("metadata")?.apps;
const availability = formMethods.watch("availability");
let numberOfActiveApps = 0;
if (appsMetadata) {
numberOfActiveApps = Object.entries(appsMetadata).filter(
([appId, appData]) =>
eventTypeApps?.items.find((app) => app.slug === appId)?.isInstalled && appData.enabled
).length;
}
// Optional prerender all tabs after 300 ms on mount
return (
<>
<EventTypeSingleLayout
enabledAppsNumber={numberOfActiveApps}
installedAppsNumber={eventTypeApps?.items.length || 0}
enabledWorkflowsNumber={props.allActiveWorkflows ? props.allActiveWorkflows.length : 0}
eventType={eventType}
activeWebhooksNumber={eventType.webhooks.filter((webhook) => webhook.active).length}
team={team}
availability={availability}
isUpdateMutationLoading={isUpdating}
formMethods={formMethods}
// disableBorder={tabName === "apps" || tabName === "workflows" || tabName === "webhooks"}
@@ -106,7 +81,10 @@ export const EventType = (
currentUserMembership={currentUserMembership}
bookerUrl={eventType.bookerUrl}
isUserOrganizationAdmin={props.isUserOrganizationAdmin}
onDelete={props.onDelete}>
onDelete={props.onDelete}
isDeleting={props.isDeleting}
isPlatform={isPlatform}
tabsNavigation={props.tabsNavigation}>
<Form form={formMethods} id="event-type-form" handleSubmit={props.handleSubmit}>
<div ref={animationParentRef}>{tabMap[tabName]}</div>
</Form>
@@ -1,14 +1,13 @@
import type { TFunction } from "next-i18next";
import { useMemo, useState, Suspense } from "react";
import type { UseFormReturn } from "react-hook-form";
import { Shell as PlatformShell } from "@calcom/atoms/monorepo";
import useLockedFieldsManager from "@calcom/features/ee/managed-event-types/hooks/useLockedFieldsManager";
import { EventTypeEmbedButton, EventTypeEmbedDialog } from "@calcom/features/embed/EventTypeEmbed";
import type { FormValues, AvailabilityOption } from "@calcom/features/eventtypes/lib/types";
import type { FormValues } from "@calcom/features/eventtypes/lib/types";
import type { EventTypeSetupProps } from "@calcom/features/eventtypes/lib/types";
import Shell from "@calcom/features/shell/Shell";
import WebShell from "@calcom/features/shell/Shell";
import { classNames } from "@calcom/lib";
import getPaymentAppData from "@calcom/lib/getPaymentAppData";
import { useLocale } from "@calcom/lib/hooks/useLocale";
import { SchedulingType } from "@calcom/prisma/enums";
import type { VerticalTabItemProps } from "@calcom/ui";
@@ -40,91 +39,30 @@ type Props = {
currentUserMembership: EventTypeSetupProps["currentUserMembership"];
team: EventTypeSetupProps["team"];
disableBorder?: boolean;
enabledAppsNumber: number;
installedAppsNumber: number;
enabledWorkflowsNumber: number;
formMethods: UseFormReturn<FormValues>;
isUpdateMutationLoading?: boolean;
availability?: AvailabilityOption;
isUserOrganizationAdmin: boolean;
bookerUrl: string;
activeWebhooksNumber: number;
onDelete: () => void;
onDelete: (id: number) => void;
isDeleting?: boolean;
isPlatform?: boolean;
tabsNavigation: VerticalTabItemProps[];
};
type getNavigationProps = {
t: TFunction;
length: number;
id: number;
multipleDuration?: EventTypeSetupProps["eventType"]["metadata"]["multipleDuration"];
enabledAppsNumber: number;
enabledWorkflowsNumber: number;
installedAppsNumber: number;
availability: AvailabilityOption | undefined;
};
function getNavigation({
length,
id,
multipleDuration,
t,
enabledAppsNumber,
installedAppsNumber,
enabledWorkflowsNumber,
}: getNavigationProps) {
const duration = multipleDuration?.map((duration) => ` ${duration}`) || length;
return [
{
name: "event_setup_tab_title",
href: `/event-types/${id}?tabName=setup`,
icon: "link",
info: `${duration} ${t("minute_timeUnit")}`, // TODO: Get this from props
},
{
name: "event_limit_tab_title",
href: `/event-types/${id}?tabName=limits`,
icon: "clock",
info: `event_limit_tab_description`,
},
{
name: "event_advanced_tab_title",
href: `/event-types/${id}?tabName=advanced`,
icon: "sliders-vertical",
info: `event_advanced_tab_description`,
},
{
name: "apps",
href: `/event-types/${id}?tabName=apps`,
icon: "grid-3x3",
//TODO: Handle proper translation with count handling
info: `${installedAppsNumber} apps, ${enabledAppsNumber} ${t("active")}`,
},
{
name: "workflows",
href: `/event-types/${id}?tabName=workflows`,
icon: "zap",
info: `${enabledWorkflowsNumber} ${t("active")}`,
},
] satisfies VerticalTabItemProps[];
}
function EventTypeSingleLayout({
children,
eventType,
currentUserMembership,
team,
disableBorder,
enabledAppsNumber,
installedAppsNumber,
enabledWorkflowsNumber,
isUpdateMutationLoading,
formMethods,
availability,
isUserOrganizationAdmin,
bookerUrl,
activeWebhooksNumber,
onDelete,
isDeleting,
isPlatform,
tabsNavigation,
}: Props) {
const { t } = useLocale();
const eventTypesLockedByOrg = eventType.team?.parent?.organizationSettings?.lockEventTypeCreationForUsers;
@@ -142,110 +80,7 @@ function EventTypeSingleLayout({
translate: t,
formMethods,
});
const length = formMethods.watch("length");
const multipleDuration = formMethods.watch("metadata")?.multipleDuration;
const watchSchedulingType = formMethods.watch("schedulingType");
const watchChildrenCount = formMethods.watch("children").length;
const paymentAppData = getPaymentAppData(eventType);
const requirePayment = paymentAppData.price > 0;
// Define tab navigation here
const EventTypeTabs = useMemo(() => {
const navigation: VerticalTabItemProps[] = getNavigation({
t,
length,
multipleDuration,
id: formMethods.getValues("id"),
enabledAppsNumber,
installedAppsNumber,
enabledWorkflowsNumber,
availability,
});
if (!requirePayment) {
navigation.splice(3, 0, {
name: "recurring",
href: `/event-types/${formMethods.getValues("id")}?tabName=recurring`,
icon: "repeat",
info: `recurring_event_tab_description`,
});
}
navigation.splice(1, 0, {
name: "availability",
href: `/event-types/${formMethods.getValues("id")}?tabName=availability`,
icon: "calendar",
info:
isManagedEventType || isChildrenManagedEventType
? formMethods.getValues("schedule") === null
? "members_default_schedule"
: isChildrenManagedEventType
? `${
formMethods.getValues("scheduleName")
? `${formMethods.getValues("scheduleName")} - ${t("managed")}`
: `default_schedule_name`
}`
: formMethods.getValues("scheduleName") ?? `default_schedule_name`
: formMethods.getValues("scheduleName") ?? `default_schedule_name`,
});
// If there is a team put this navigation item within the tabs
if (team) {
navigation.splice(2, 0, {
name: "assignment",
href: `/event-types/${formMethods.getValues("id")}?tabName=team`,
icon: "users",
info: `${t(watchSchedulingType?.toLowerCase() ?? "")}${
isManagedEventType ? ` - ${t("number_member", { count: watchChildrenCount || 0 })}` : ""
}`,
});
}
const showWebhooks = !(isManagedEventType || isChildrenManagedEventType);
if (showWebhooks) {
if (team) {
navigation.push({
name: "instant_tab_title",
href: `/event-types/${eventType.id}?tabName=instant`,
icon: "phone-call",
info: `instant_event_tab_description`,
});
}
navigation.push({
name: "webhooks",
href: `/event-types/${formMethods.getValues("id")}?tabName=webhooks`,
icon: "webhook",
info: `${activeWebhooksNumber} ${t("active")}`,
});
}
const hidden = true; // hidden while in alpha trial. you can access it with tabName=ai
if (team && hidden) {
navigation.push({
name: "Cal.ai",
href: `/event-types/${eventType.id}?tabName=ai`,
icon: "sparkles",
info: "cal_ai_event_tab_description", // todo `cal_ai_event_tab_description`,
});
}
return navigation;
}, [
t,
enabledAppsNumber,
installedAppsNumber,
enabledWorkflowsNumber,
availability,
isManagedEventType,
isChildrenManagedEventType,
team,
length,
requirePayment,
multipleDuration,
formMethods.getValues("id"),
watchSchedulingType,
watchChildrenCount,
activeWebhooksNumber,
]);
const EventTypeTabs = tabsNavigation;
const permalink = `${bookerUrl}/${
team ? `${!team.parentId ? "team/" : ""}${team.slug}` : formMethods.getValues("users")[0].username
}/${eventType.slug}`;
@@ -254,7 +89,11 @@ function EventTypeSingleLayout({
team ? `team/${team.slug}` : formMethods.getValues("users")[0].username
}/${formMethods.getValues("slug")}`;
const isManagedEvent = formMethods.getValues("schedulingType") === SchedulingType.MANAGED ? "_managed" : "";
// const title = formMethods.watch("title");
const [Shell] = useMemo(() => {
return isPlatform ? [PlatformShell] : [WebShell];
}, [isPlatform]);
return (
<Shell
backPath="/event-types"
@@ -305,41 +144,47 @@ function EventTypeSingleLayout({
{!isManagedEventType && (
<>
{/* We have to warp this in tooltip as it has a href which disabels the tooltip on buttons */}
<Tooltip content={t("preview")} side="bottom" sideOffset={4}>
{!isPlatform && (
<Tooltip content={t("preview")} side="bottom" sideOffset={4}>
<Button
color="secondary"
data-testid="preview-button"
target="_blank"
variant="icon"
href={permalink}
rel="noreferrer"
StartIcon="external-link"
/>
</Tooltip>
)}
{!isPlatform && (
<Button
color="secondary"
data-testid="preview-button"
target="_blank"
variant="icon"
href={permalink}
rel="noreferrer"
StartIcon="external-link"
StartIcon="link"
tooltip={t("copy_link")}
tooltipSide="bottom"
tooltipOffset={4}
onClick={() => {
navigator.clipboard.writeText(permalink);
showToast("Link copied!", "success");
}}
/>
</Tooltip>
<Button
color="secondary"
variant="icon"
StartIcon="link"
tooltip={t("copy_link")}
tooltipSide="bottom"
tooltipOffset={4}
onClick={() => {
navigator.clipboard.writeText(permalink);
showToast("Link copied!", "success");
}}
/>
<EventTypeEmbedButton
embedUrl={encodeURIComponent(embedLink)}
StartIcon="code"
color="secondary"
variant="icon"
namespace={eventType.slug}
tooltip={t("embed")}
tooltipSide="bottom"
tooltipOffset={4}
eventId={formMethods.getValues("id")}
/>
)}
{!isPlatform && (
<EventTypeEmbedButton
embedUrl={encodeURIComponent(embedLink)}
StartIcon="code"
color="secondary"
variant="icon"
namespace={eventType.slug}
tooltip={t("embed")}
tooltipSide="bottom"
tooltipOffset={4}
eventId={formMethods.getValues("id")}
/>
)}
</>
)}
{!isChildrenManagedEventType && (
@@ -455,9 +300,10 @@ function EventTypeSingleLayout({
open={deleteDialogOpen}
onOpenChange={setDeleteDialogOpen}
onDelete={onDelete}
isDeleting={isDeleting}
/>
<EventTypeEmbedDialog />
{!isPlatform && <EventTypeEmbedDialog />}
</Shell>
);
}
@@ -8,6 +8,7 @@ import type { UseFormGetValues, UseFormSetValue, Control, FormState } from "reac
import type { EventLocationType } from "@calcom/app-store/locations";
import { getEventLocationType, MeetLocationType } from "@calcom/app-store/locations";
import { useIsPlatform } from "@calcom/atoms/monorepo";
import type { LocationFormValues, EventTypeSetupProps } from "@calcom/features/eventtypes/lib/types";
import CheckboxField from "@calcom/features/form/components/CheckboxField";
import type { SingleValueLocationOption } from "@calcom/features/form/components/LocationSelect";
@@ -209,6 +210,8 @@ const Locations: React.FC<LocationsProps> = ({
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [prefillLocation, seatsEnabled]);
const isPlatorm = useIsPlatform();
return (
<div className="w-full">
<ul ref={animationRef} className="space-y-2">
@@ -417,7 +420,7 @@ const Locations: React.FC<LocationsProps> = ({
</li>
)}
</ul>
{props.showAppStoreLink && (
{props.showAppStoreLink && !isPlatorm && (
<p className="text-default mt-2 text-sm">
<Trans i18nKey="cant_find_the_right_conferencing_app_visit_our_app_store">
Can&apos;t find the right conferencing app? Visit our
@@ -1,11 +1,8 @@
import { Trans } from "next-i18next";
import { useRouter } from "next/navigation";
import { useLocale } from "@calcom/lib/hooks/useLocale";
import { HttpError } from "@calcom/lib/http-error";
import { trpc, TRPCClientError } from "@calcom/trpc/react";
import type { DialogProps } from "@calcom/ui";
import { ConfirmationDialogContent, Dialog, showToast } from "@calcom/ui";
import { ConfirmationDialogContent, Dialog } from "@calcom/ui";
export function DeleteDialog({
isManagedEvent,
@@ -13,44 +10,26 @@ export function DeleteDialog({
open,
onOpenChange,
onDelete,
isDeleting,
}: {
isManagedEvent: string;
eventTypeId: number;
onDelete: () => void;
onDelete: (id: number) => void;
isDeleting?: boolean;
} & Pick<DialogProps, "open" | "onOpenChange">) {
const utils = trpc.useUtils();
const { t } = useLocale();
const router = useRouter();
const deleteMutation = trpc.viewer.eventTypes.delete.useMutation({
onSuccess: async () => {
await utils.viewer.eventTypes.invalidate();
showToast(t("event_type_deleted_successfully"), "success");
onDelete();
router.push("/event-types");
onOpenChange?.(false);
},
onError: (err) => {
if (err instanceof HttpError) {
const message = `${err.statusCode}: ${err.message}`;
showToast(message, "error");
onOpenChange?.(false);
} else if (err instanceof TRPCClientError) {
showToast(err.message, "error");
}
},
});
return (
<Dialog open={open} onOpenChange={onOpenChange}>
<ConfirmationDialogContent
isPending={deleteMutation.isPending}
isPending={isDeleting}
variety="danger"
title={t(`delete${isManagedEvent}_event_type`)}
confirmBtnText={t(`confirm_delete_event_type`)}
loadingText={t(`confirm_delete_event_type`)}
onConfirm={(e) => {
e.preventDefault();
deleteMutation.mutate({ id: eventTypeId });
onDelete(eventTypeId);
}}>
<p className="mt-5">
<Trans
@@ -4,11 +4,9 @@ import type { UseFormGetValues, UseFormSetValue, Control, FormState } from "reac
import type { MultiValue } from "react-select";
import useLockedFieldsManager from "@calcom/features/ee/managed-event-types/hooks/useLockedFieldsManager";
import { useOrgBranding } from "@calcom/features/ee/organizations/context/provider";
import Locations from "@calcom/features/eventtypes/components/Locations";
import type { EventTypeSetupProps } from "@calcom/features/eventtypes/lib/types";
import type { FormValues, LocationFormValues } from "@calcom/features/eventtypes/lib/types";
import { WEBSITE_URL } from "@calcom/lib/constants";
import { useLocale } from "@calcom/lib/hooks/useLocale";
import { md } from "@calcom/lib/markdownIt";
import { slugify } from "@calcom/lib/slugify";
@@ -19,15 +17,15 @@ export type EventSetupTabProps = Pick<
EventTypeSetupProps,
"eventType" | "locationOptions" | "team" | "teamMembers" | "destinationCalendar"
>;
export const EventSetupTab = (props: EventSetupTabProps) => {
export const EventSetupTab = (props: EventSetupTabProps & { urlPrefix: string; hasOrgBranding: boolean }) => {
const { t } = useLocale();
const formMethods = useFormContext<FormValues>();
const { eventType, team } = props;
const { eventType, team, urlPrefix, hasOrgBranding } = props;
const [multipleDuration, setMultipleDuration] = useState(
formMethods.getValues("metadata")?.multipleDuration
);
const [firstRender, setFirstRender] = useState(true);
const orgBranding = useOrgBranding();
const seatsEnabled = formMethods.watch("seatsPerTimeSlotEnabled");
const multipleDurationOptions = [
@@ -54,9 +52,6 @@ export const EventSetupTab = (props: EventSetupTabProps) => {
const descriptionLockedProps = shouldLockDisableProps("description");
const urlLockedProps = shouldLockDisableProps("slug");
const titleLockedProps = shouldLockDisableProps("title");
const urlPrefix = orgBranding
? orgBranding?.fullDomain.replace(/^(https?:|)\/\//, "")
: `${WEBSITE_URL?.replace(/^(https?:|)\/\//, "")}`;
return (
<div>
@@ -98,7 +93,7 @@ export const EventSetupTab = (props: EventSetupTabProps) => {
{urlPrefix}/
{!isManagedEventType
? team
? (orgBranding ? "" : "team/") + team.slug
? (hasOrgBranding ? "" : "team/") + team.slug
: formMethods.getValues("users")[0].username
: t("username_placeholder")}
/
@@ -2,9 +2,10 @@ import type { GroupBase, Props, SingleValue } from "react-select";
import { components } from "react-select";
import type { EventLocationType } from "@calcom/app-store/locations";
import { useIsPlatform } from "@calcom/atoms/monorepo";
import { classNames } from "@calcom/lib";
import invertLogoOnDark from "@calcom/lib/invertLogoOnDark";
import { Select } from "@calcom/ui";
import { Select, Icon } from "@calcom/ui";
export type LocationOption = {
label: string;
@@ -20,7 +21,37 @@ export type SingleValueLocationOption = SingleValue<LocationOption>;
export type GroupOptionType = GroupBase<LocationOption>;
const OptionWithIcon = ({ icon, label }: { icon?: string; label: string }) => {
const OptionWithIcon = ({ icon, label, value }: { icon?: string; label: string; value: string }) => {
const isPlatform = useIsPlatform();
const getIconFromValue = (value: string) => {
switch (value) {
case "phone":
return <Icon name="phone" className="h-3.5 w-3.5" />;
case "userPhone":
return <Icon name="phone" className="h-3.5 w-3.5" />;
case "inPerson":
return <Icon name="map-pin" className="h-3.5 w-3.5" />;
case "attendeeInPerson":
return <Icon name="map-pin" className="h-3.5 w-3.5" />;
case "link":
return <Icon name="link" className="h-3.5 w-3.5" />;
case "somewhereElse":
return <Icon name="map" className="h-3.5 w-3.5" />;
default:
return <Icon name="video" className="h-3.5 w-3.5" />;
}
};
if (isPlatform) {
return (
<div className="flex items-center gap-3">
{getIconFromValue(value)}
<span className={classNames("text-sm font-medium")}>{label}</span>
</div>
);
}
return (
<div className="flex items-center gap-3">
{icon && <img src={icon} alt="cover" className={classNames("h-3.5 w-3.5", invertLogoOnDark(icon))} />}
@@ -30,6 +61,7 @@ const OptionWithIcon = ({ icon, label }: { icon?: string; label: string }) => {
};
export default function LocationSelect(props: Props<LocationOption, false, GroupOptionType>) {
const isPlatform = useIsPlatform();
return (
<Select<LocationOption>
name="location"
@@ -40,22 +72,24 @@ export default function LocationSelect(props: Props<LocationOption, false, Group
return (
<components.Option {...props}>
<div data-testid={`location-select-item-${props.data.value}`}>
<OptionWithIcon icon={props.data.icon} label={props.data.label} />
<OptionWithIcon icon={props.data.icon} label={props.data.label} value={props.data.value} />
</div>
</components.Option>
);
},
SingleValue: (props) => (
<components.SingleValue {...props}>
<div data-testid={`location-select-item-${props.data.value}`}>
<OptionWithIcon icon={props.data.icon} label={props.data.label} />
</div>
</components.SingleValue>
),
SingleValue: (props) => {
return (
<components.SingleValue {...props}>
<div data-testid={`location-select-item-${props.data.value}`}>
<OptionWithIcon icon={props.data.icon} label={props.data.label} value={props.data.value} />
</div>
</components.SingleValue>
);
},
}}
formatOptionLabel={(e) => (
formatOptionLabel={(e, d) => (
<div className="flex items-center gap-3">
{e.icon && (
{e.icon && !isPlatform && (
<img
src={e.icon}
alt="app-icon"