Skip to content

Scheduling infrastructure for absolutely everyone.

fix: Enhance the Robustness of Embed Snippets for Multiple Embeds on a Single Page (#11512)

Hariom Balharaa9fcd900cd24
diff --git a/apps/web/components/eventtype/EventTypeSingleLayout.tsx b/apps/web/components/eventtype/EventTypeSingleLayout.tsx
index ba369f9c801..f802055a013 100644
--- a/apps/web/components/eventtype/EventTypeSingleLayout.tsx
+++ b/apps/web/components/eventtype/EventTypeSingleLayout.tsx
@@ -322,6 +322,7 @@ function EventTypeSingleLayout({
StartIcon={Code}
color="secondary"
variant="icon"
+ namespace={eventType.slug}
tooltip={t("embed")}
tooltipSide="bottom"
tooltipOffset={4}
diff --git a/apps/web/pages/event-types/index.tsx b/apps/web/pages/event-types/index.tsx
index a83b3d2e2e5..312b3d1d895 100644
--- a/apps/web/pages/event-types/index.tsx
+++ b/apps/web/pages/event-types/index.tsx
@@ -507,6 +507,7 @@ export const EventTypeList = ({ group, groupIndex, readOnly, types }: EventTypeL
{!isManagedEventType && (
<DropdownMenuItem className="outline-none">
<EventTypeEmbedButton
+ namespace={type.slug}
as={DropdownItem}
type="button"
StartIcon={Code}
diff --git a/packages/app-store/routing-forms/components/FormActions.tsx b/packages/app-store/routing-forms/components/FormActions.tsx
index 088d374231b..337b8c30d38 100644
--- a/packages/app-store/routing-forms/components/FormActions.tsx
+++ b/packages/app-store/routing-forms/components/FormActions.tsx
@@ -12,6 +12,7 @@ import { CAL_URL } from "@calcom/lib/constants";
import { useCompatSearchParams } from "@calcom/lib/hooks/useCompatSearchParams";
import { useLocale } from "@calcom/lib/hooks/useLocale";
import { useRouterQuery } from "@calcom/lib/hooks/useRouterQuery";
+import slugify from "@calcom/lib/slugify";
import { trpc } from "@calcom/trpc/react";
import type { ButtonProps } from "@calcom/ui";
import {
@@ -434,6 +435,8 @@ export const FormAction = forwardRef(function FormAction<T extends typeof Button
// eslint-disable-next-line @typescript-eslint/ban-ts-comment
//@ts-ignore
embedUrl: embedLink,
+ // We are okay with namespace clashing here if just in case names clash
+ namespace: slugify((routingForm?.name || "").substring(0, 5)),
},
edit: {
href: `${appUrl}/form-edit/${routingForm?.id}`,
diff --git a/packages/embeds/embed-react/src/Cal.tsx b/packages/embeds/embed-react/src/Cal.tsx
index bd409ece418..3c8e06d6cbd 100644
--- a/packages/embeds/embed-react/src/Cal.tsx
+++ b/packages/embeds/embed-react/src/Cal.tsx
@@ -13,12 +13,13 @@ type CalProps = {
debug?: boolean;
uiDebug?: boolean;
};
+ namespace?: string;
config?: PrefillAndIframeAttrsConfig;
embedJsUrl?: string;
} & React.HTMLAttributes<HTMLDivElement>;
const Cal = function Cal(props: CalProps) {
- const { calLink, calOrigin, config, initConfig = {}, embedJsUrl, ...restProps } = props;
+ const { calLink, calOrigin, namespace = "", config, initConfig = {}, embedJsUrl, ...restProps } = props;
if (!calLink) {
throw new Error("calLink is required");
}
@@ -31,16 +32,28 @@ const Cal = function Cal(props: CalProps) {
}
initializedRef.current = true;
const element = ref.current;
- Cal("init", {
- ...initConfig,
- origin: calOrigin,
- });
- Cal("inline", {
- elementOrSelector: element,
- calLink,
- config,
- });
- }, [Cal, calLink, config, calOrigin, initConfig]);
+ if (namespace) {
+ Cal("init", namespace, {
+ ...initConfig,
+ origin: calOrigin,
+ });
+ Cal.ns[namespace]("inline", {
+ elementOrSelector: element,
+ calLink,
+ config,
+ });
+ } else {
+ Cal("init", {
+ ...initConfig,
+ origin: calOrigin,
+ });
+ Cal("inline", {
+ elementOrSelector: element,
+ calLink,
+ config,
+ });
+ }
+ }, [Cal, calLink, config, namespace, calOrigin, initConfig]);
if (!Cal) {
return null;
diff --git a/packages/features/embed/Embed.tsx b/packages/features/embed/Embed.tsx
index 50e023ba76e..fcaa08a4b6b 100644
--- a/packages/features/embed/Embed.tsx
+++ b/packages/features/embed/Embed.tsx
@@ -498,12 +498,14 @@ const EmbedTypeCodeAndPreviewDialogContent = ({
embedType,
embedUrl,
tabs,
+ namespace,
eventTypeHideOptionDisabled,
types,
}: {
embedType: EmbedType;
embedUrl: string;
tabs: EmbedTabs;
+ namespace: string;
eventTypeHideOptionDisabled: boolean;
types: EmbedTypes;
}) => {
@@ -1009,6 +1011,7 @@ const EmbedTypeCodeAndPreviewDialogContent = ({
<div className="flex h-[55vh] flex-grow flex-col">
{tab.type === "code" ? (
<tab.Component
+ namespace={namespace}
embedType={embedType}
calLink={calLink}
previewState={previewState}
@@ -1016,6 +1019,7 @@ const EmbedTypeCodeAndPreviewDialogContent = ({
/>
) : (
<tab.Component
+ namespace={namespace}
embedType={embedType}
calLink={calLink}
previewState={previewState}
@@ -1097,7 +1101,8 @@ export const EmbedDialog = ({
eventTypeHideOptionDisabled: boolean;
}) => {
const searchParams = useCompatSearchParams();
- const embedUrl = searchParams?.get("embedUrl") as string;
+ const embedUrl = (searchParams?.get("embedUrl") || "") as string;
+ const namespace = (searchParams?.get("namespace") || "") as string;
return (
<Dialog name="embed" clearQueryParamsOnClose={queryParamsForDialog}>
{!searchParams?.get("embedType") ? (
@@ -1106,6 +1111,7 @@ export const EmbedDialog = ({
<EmbedTypeCodeAndPreviewDialogContent
embedType={searchParams?.get("embedType") as EmbedType}
embedUrl={embedUrl}
+ namespace={namespace}
tabs={tabs}
types={types}
eventTypeHideOptionDisabled={eventTypeHideOptionDisabled}
@@ -1117,6 +1123,7 @@ export const EmbedDialog = ({
type EmbedButtonProps<T> = {
embedUrl: string;
+ namespace: string;
children?: React.ReactNode;
className?: string;
as?: T;
@@ -1129,6 +1136,7 @@ export const EmbedButton = <T extends React.ElementType>({
className = "",
as,
eventId,
+ namespace,
...props
}: EmbedButtonProps<T> & React.ComponentPropsWithoutRef<T>) => {
const { goto } = useRouterHelpers();
@@ -1137,6 +1145,7 @@ export const EmbedButton = <T extends React.ElementType>({
goto({
dialog: "embed",
eventId: eventId ? eventId.toString() : "",
+ namespace,
embedUrl,
});
};
diff --git a/packages/features/embed/lib/EmbedCodes.tsx b/packages/features/embed/lib/EmbedCodes.tsx
index 53ca519e949..105544ece75 100644
--- a/packages/features/embed/lib/EmbedCodes.tsx
+++ b/packages/features/embed/lib/EmbedCodes.tsx
@@ -2,6 +2,7 @@ import { CAL_URL, IS_SELF_HOSTED, WEBAPP_URL } from "@calcom/lib/constants";
import type { PreviewState } from "../types";
import { embedLibUrl } from "./constants";
+import { getApiName } from "./getApiName";
import { getDimension } from "./getDimension";
export const doWeNeedCalOriginProp = (embedCalOrigin: string) => {
@@ -18,14 +19,17 @@ export const Codes = {
uiInstructionCode,
previewState,
embedCalOrigin,
+ namespace,
}: {
calLink: string;
uiInstructionCode: string;
previewState: PreviewState;
embedCalOrigin: string;
+ namespace: string;
}) => {
const width = getDimension(previewState.inline.width);
const height = getDimension(previewState.inline.height);
+ const namespaceProp = `${namespace ? `namespace="${namespace}"` : ""}`;
return code`
import Cal, { getCalApi } from "@calcom/embed-react";
import { useEffect } from "react";
@@ -36,21 +40,23 @@ export const Codes = {
${uiInstructionCode}
})();
}, [])
- return <Cal
+ return <Cal ${namespaceProp}
calLink="${calLink}"
style={{width:"${width}",height:"${height}",overflow:"scroll"}}
${previewState.layout ? `config={{layout: '${previewState.layout}'}}` : ""}
${doWeNeedCalOriginProp(embedCalOrigin) ? ` calOrigin="${embedCalOrigin}"` : ""}
- ${IS_SELF_HOSTED ? `calJsUrl="${embedLibUrl}"` : ""}
+ ${IS_SELF_HOSTED ? `embedJsUrl="${embedLibUrl}"` : ""}
/>;
};`;
},
"floating-popup": ({
floatingButtonArg,
uiInstructionCode,
+ namespace,
}: {
floatingButtonArg: string;
uiInstructionCode: string;
+ namespace: string;
}) => {
return code`
import { getCalApi } from "@calcom/embed-react";
@@ -59,7 +65,7 @@ export const Codes = {
useEffect(()=>{
(async function () {
const cal = await getCalApi(${IS_SELF_HOSTED ? `"${embedLibUrl}"` : ""});
- cal("floatingButton", ${floatingButtonArg});
+ ${getApiName({ namespace, mainApiName: "cal" })}("floatingButton", ${floatingButtonArg});
${uiInstructionCode}
})();
}, [])
@@ -70,11 +76,13 @@ export const Codes = {
uiInstructionCode,
previewState,
embedCalOrigin,
+ namespace,
}: {
calLink: string;
uiInstructionCode: string;
previewState: PreviewState;
embedCalOrigin: string;
+ namespace: string;
}) => {
return code`
import { getCalApi } from "@calcom/embed-react";
@@ -86,7 +94,7 @@ export const Codes = {
${uiInstructionCode}
})();
}, [])
- return <button
+ return <button data-cal-namespace="${namespace}"
data-cal-link="${calLink}"
${doWeNeedCalOriginProp(embedCalOrigin) ? ` data-cal-origin="${embedCalOrigin}"` : ""}
${`data-cal-config='${JSON.stringify({
@@ -101,12 +109,14 @@ export const Codes = {
calLink,
uiInstructionCode,
previewState,
+ namespace,
}: {
calLink: string;
uiInstructionCode: string;
previewState: PreviewState;
+ namespace: string;
}) => {
- return code`Cal("inline", {
+ return code`${getApiName({ namespace })}("inline", {
elementOrSelector:"#my-cal-inline",
calLink: "${calLink}",
layout: "${previewState.layout}"
@@ -118,25 +128,30 @@ export const Codes = {
"floating-popup": ({
floatingButtonArg,
uiInstructionCode,
+ namespace,
}: {
floatingButtonArg: string;
uiInstructionCode: string;
+ namespace: string;
}) => {
- return code`Cal("floatingButton", ${floatingButtonArg});
+ return code`${getApiName({ namespace, mainApiName: "Cal" })}("floatingButton", ${floatingButtonArg});
${uiInstructionCode}`;
},
"element-click": ({
calLink,
uiInstructionCode,
previewState,
+ namespace,
}: {
calLink: string;
uiInstructionCode: string;
previewState: PreviewState;
+ namespace: string;
}) => {
return code`
- // Important: Please add following attributes to the element you want to open Cal on click
+ // Important: Please add the following attributes to the element that should trigger the calendar to open upon clicking.
// \`data-cal-link="${calLink}"\`
+ // data-cal-namespace="${namespace}"
// \`data-cal-config='${JSON.stringify({
layout: previewState.layout,
})}'\`
diff --git a/packages/features/embed/lib/EmbedTabs.tsx b/packages/features/embed/lib/EmbedTabs.tsx
index 3bcbdfc2628..18b8cf28f63 100644
--- a/packages/features/embed/lib/EmbedTabs.tsx
+++ b/packages/features/embed/lib/EmbedTabs.tsx
@@ -11,6 +11,7 @@ import { Code, Trello } from "@calcom/ui/components/icon";
import type { EmbedType, PreviewState, EmbedFramework } from "../types";
import { Codes, doWeNeedCalOriginProp } from "./EmbedCodes";
import { EMBED_PREVIEW_HTML_URL, embedLibUrl } from "./constants";
+import { getApiName } from "./getApiName";
import { getDimension } from "./getDimension";
import { useEmbedCalOrigin } from "./hooks";
@@ -22,10 +23,10 @@ export const tabs = [
type: "code",
Component: forwardRef<
HTMLTextAreaElement | HTMLIFrameElement | null,
- { embedType: EmbedType; calLink: string; previewState: PreviewState }
- >(function EmbedHtml({ embedType, calLink, previewState }, ref) {
+ { embedType: EmbedType; calLink: string; previewState: PreviewState; namespace: string }
+ >(function EmbedHtml({ embedType, calLink, previewState, namespace }, ref) {
const { t } = useLocale();
- const embedSnippetString = useGetEmbedSnippetString();
+ const embedSnippetString = useGetEmbedSnippetString(namespace);
const embedCalOrigin = useEmbedCalOrigin();
if (ref instanceof Function || !ref) {
return null;
@@ -55,7 +56,14 @@ export const tabs = [
: ""
}<script type="text/javascript">
${embedSnippetString}
- ${getEmbedTypeSpecificString({ embedFramework: "HTML", embedType, calLink, previewState, embedCalOrigin })}
+ ${getEmbedTypeSpecificString({
+ embedFramework: "HTML",
+ embedType,
+ calLink,
+ previewState,
+ embedCalOrigin,
+ namespace,
+ })}
</script>
<!-- Cal ${embedType} embed code ends -->`}
/>
@@ -71,8 +79,8 @@ export const tabs = [
type: "code",
Component: forwardRef<
HTMLTextAreaElement | HTMLIFrameElement | null,
- { embedType: EmbedType; calLink: string; previewState: PreviewState }
- >(function EmbedReact({ embedType, calLink, previewState }, ref) {
+ { embedType: EmbedType; calLink: string; previewState: PreviewState; namespace: string }
+ >(function EmbedReact({ embedType, calLink, previewState, namespace }, ref) {
const { t } = useLocale();
const embedCalOrigin = useEmbedCalOrigin();
@@ -99,7 +107,14 @@ export const tabs = [
/* If you are using npm */
// npm install @calcom/embed-react
- ${getEmbedTypeSpecificString({ embedFramework: "react", embedType, calLink, previewState, embedCalOrigin })}
+ ${getEmbedTypeSpecificString({
+ embedFramework: "react",
+ embedType,
+ calLink,
+ previewState,
+ embedCalOrigin,
+ namespace,
+ })}
`}
/>
</>
@@ -113,7 +128,7 @@ export const tabs = [
type: "iframe",
Component: forwardRef<
HTMLIFrameElement | HTMLTextAreaElement | null,
- { calLink: string; embedType: EmbedType; previewState: PreviewState }
+ { calLink: string; embedType: EmbedType; previewState: PreviewState; namespace: string }
>(function Preview({ calLink, embedType }, ref) {
const bookerUrl = useBookerUrl();
const iframeSrc = `${EMBED_PREVIEW_HTML_URL}?embedType=${embedType}&calLink=${calLink}&embedLibUrl=${embedLibUrl}&bookerUrl=${bookerUrl}`;
@@ -144,12 +159,14 @@ const getEmbedTypeSpecificString = ({
calLink,
embedCalOrigin,
previewState,
+ namespace,
}: {
embedFramework: EmbedFramework;
embedType: EmbedType;
calLink: string;
previewState: PreviewState;
embedCalOrigin: string;
+ namespace: string;
}) => {
const frameworkCodes = Codes[embedFramework];
if (!frameworkCodes) {
@@ -165,7 +182,7 @@ const getEmbedTypeSpecificString = ({
};
if (embedFramework === "react") {
uiInstructionStringArg = {
- apiName: "cal",
+ apiName: getApiName({ namespace, mainApiName: "cal" }),
theme: previewState.theme,
brandColor: previewState.palette.brandColor,
hideEventTypeDetails: previewState.hideEventTypeDetails,
@@ -173,7 +190,7 @@ const getEmbedTypeSpecificString = ({
};
} else {
uiInstructionStringArg = {
- apiName: "Cal",
+ apiName: getApiName({ namespace, mainApiName: "Cal" }),
theme: previewState.theme,
brandColor: previewState.palette.brandColor,
hideEventTypeDetails: previewState.hideEventTypeDetails,
@@ -189,6 +206,7 @@ const getEmbedTypeSpecificString = ({
uiInstructionCode: getEmbedUIInstructionString(uiInstructionStringArg),
previewState,
embedCalOrigin,
+ namespace,
});
} else if (embedType === "floating-popup") {
const floatingButtonArg = {
@@ -197,11 +215,13 @@ const getEmbedTypeSpecificString = ({
...previewState.floatingPopup,
};
return frameworkCodes[embedType]({
+ namespace,
floatingButtonArg: JSON.stringify(floatingButtonArg),
uiInstructionCode: getEmbedUIInstructionString(uiInstructionStringArg),
});
} else if (embedType === "element-click") {
return frameworkCodes[embedType]({
+ namespace,
calLink,
uiInstructionCode: getEmbedUIInstructionString(uiInstructionStringArg),
previewState,
@@ -253,10 +273,10 @@ const getInstructionString = ({
return `${apiName}("${instructionName}", ${JSON.stringify(instructionArg)});`;
};
-function useGetEmbedSnippetString() {
+function useGetEmbedSnippetString(namespace: string | null) {
const bookerUrl = useBookerUrl();
// TODO: Import this string from @calcom/embed-snippet
return `(function (C, A, L) { let p = function (a, ar) { a.q.push(ar); }; let d = C.document; C.Cal = C.Cal || function () { let cal = C.Cal; let ar = arguments; if (!cal.loaded) { cal.ns = {}; cal.q = cal.q || []; d.head.appendChild(d.createElement("script")).src = A; cal.loaded = true; } if (ar[0] === L) { const api = function () { p(api, arguments); }; const namespace = ar[1]; api.q = api.q || []; typeof namespace === "string" ? (cal.ns[namespace] = api) && p(api, ar) : p(cal, ar); return; } p(cal, ar); }; })(window, "${embedLibUrl}", "init");
-Cal("init", {origin:"${bookerUrl}"});
+Cal("init", ${namespace ? `"${namespace}",` : ""} {origin:"${bookerUrl}"});
`;
}
diff --git a/packages/features/embed/lib/getApiName.tsx b/packages/features/embed/lib/getApiName.tsx
new file mode 100644
index 00000000000..17a0013ab4f
--- /dev/null
+++ b/packages/features/embed/lib/getApiName.tsx
@@ -0,0 +1,14 @@
+export function getApiName({
+ namespace,
+ mainApiName = "Cal",
+}: {
+ namespace: string | null;
+ mainApiName?: string;
+}) {
+ if (!namespace) {
+ return mainApiName;
+ }
+ const isAValidVariableName = /^[a-zA-Z_$][a-zA-Z_$0-9]*$/.test(namespace);
+ // Try to use dot notation if possible because it's more readable otherwise use bracket notation
+ return isAValidVariableName ? `${mainApiName}.ns.${namespace}` : `${mainApiName}.ns["${namespace}"]`;
+}