Embed Miscellaneous Improvements and Fixes (#2499)

This commit is contained in:
Hariom Balhara authored and GitHub committed 2022-04-25 10:03:00 +05:30
1 parent 53d7e57142
commit 93c75b5fef
83 files changed
+1139 -746

No files matched your search

+32 -26
View File
@@ -9,8 +9,8 @@ The Embed allows your website visitors to book a meeting with you directly from
## Install on any website
- _Step-1._ Install the Vanilla JS Snippet
```javascript
```html
<script>
(function (C, A, L) {
let p = function (a, ar) {
a.q.push(ar);
@@ -38,14 +38,10 @@ The Embed allows your website visitors to book a meeting with you directly from
}
p(cal, ar);
};
})(window, "https://cal.com/embed.js", "init");
```
- _Step-2_. Initialize it
```javascript
Cal("init")
```
})(window, "https://cal.com/embed.js", "init");
Cal("init")
</script>
```
## Install with a Framework
@@ -72,18 +68,20 @@ Show the embed inline inside a container element. It would take the width and he
<details>
<summary>_Vanilla JS_</summary>
```javascript
Cal("inline", {
elementOrSelector: "Your Embed Container Selector Path", // You can also provide an element directly
calLink: "jane", // The link that you want to embed. It would open https://cal.com/jane in embed
config: {
name: "John Doe", // Prefill Name
email: "john[email protected]", // Prefill Email
notes: "Test Meeting", // Prefill Notes
guests: ["[email protected]", "[email protected]"], // Prefill Guests
theme: "dark", // "dark" or "light" theme
},
});
```html
<script>
Cal("inline", {
elementOrSelector: "Your Embed Container Selector Path", // You can also provide an element directly
calLink: "jane", // The link that you want to embed. It would open https://cal.com/jane in embed
config: {
name: "John Doe", // Prefill Name
email: "[email protected]", // Prefill Email
notes: "Test Meeting", // Prefill Notes
guests: ["[email protected]", "[email protected]"], // Prefill Guests
theme: "dark", // "dark" or "light" theme
},
});
</script>
```
</details>
@@ -146,8 +144,10 @@ Consider an instruction as a function with that name and that would be called wi
Appends embed inline as the child of the element.
```javascript
```html
<script>
Cal("inline", { elementOrSelector, calLink });
</script>
````
- `elementOrSelector` - Give it either a valid CSS selector or an HTMLElement instance directly
@@ -158,8 +158,10 @@ Cal("inline", { elementOrSelector, calLink });
Configure UI for embed. Make it look part of your webpage.
```javascript
```html
<script>
Cal("inline", { styles });
</script>
```
- `styles` - It supports styling for `body` and `eventTypeListItem`. Right now we support just background on these two.
@@ -170,15 +172,18 @@ Usage:
If you want to open cal link on some action. Make it pop open instantly by preloading it.
```javascript
```html
<script>
Cal("preload", { calLink });
</script>
```
- `calLink` - Cal Link that you want to embed e.g. john. Just give the username. No need to give the full URL [https://cal.com/john]()
## Actions
You can listen to an action that occurs in embedded cal link as follows. You can think of them as DOM events. We are avoiding the term "events" to not confuse it with Cal Events.
```javascript
```html
<script>
Cal("on", {
action: "ANY_ACTION_NAME",
callback: (e)=>{
@@ -188,6 +193,7 @@ Cal("on", {
const {data, type, namespace} = e.detail;
}
})
</script>
```
Following are the list of supported actions.
@@ -18,7 +18,14 @@ import { useRouter } from "next/router";
import { useEffect, useMemo, useState } from "react";
import { FormattedNumber, IntlProvider } from "react-intl";
import { useEmbedStyles, useIsEmbed, useIsBackgroundTransparent, sdkActionManager } from "@calcom/embed-core";
import {
useEmbedStyles,
useIsEmbed,
useIsBackgroundTransparent,
sdkActionManager,
useEmbedType,
useEmbedNonStylesConfig,
} from "@calcom/embed-core";
import classNames from "@calcom/lib/classNames";
import { useLocale } from "@calcom/lib/hooks/useLocale";
@@ -56,6 +63,8 @@ const AvailabilityPage = ({ profile, plan, eventType, workingHours, previousPage
const { t, i18n } = useLocale();
const { contracts } = useContracts();
const availabilityDatePickerEmbedStyles = useEmbedStyles("availabilityDatePicker");
const shouldAlignCentrallyInEmbed = useEmbedNonStylesConfig("align") !== "left";
const shouldAlignCentrally = !isEmbed || shouldAlignCentrallyInEmbed;
let isBackgroundTransparent = useIsBackgroundTransparent();
useExposePlanGlobally(plan);
useEffect(() => {
@@ -146,18 +155,19 @@ const AvailabilityPage = ({ profile, plan, eventType, workingHours, previousPage
<CustomBranding lightVal={profile.brandColor} darkVal={profile.darkBrandColor} />
<div>
<main
className={
className={classNames(
shouldAlignCentrally ? "mx-auto" : "",
isEmbed
? classNames("m-auto", selectedDate ? "max-w-5xl" : "max-w-3xl")
? classNames(selectedDate ? "max-w-5xl" : "max-w-3xl")
: "transition-max-width mx-auto my-0 duration-500 ease-in-out md:my-24 " +
(selectedDate ? "max-w-5xl" : "max-w-3xl")
}>
(selectedDate ? "max-w-5xl" : "max-w-3xl")
)}>
{isReady && (
<div
style={availabilityDatePickerEmbedStyles}
className={classNames(
isBackgroundTransparent ? "" : "bg-white dark:bg-gray-800 sm:dark:border-gray-600",
"border-bookinglightest rounded-sm md:border",
"border-bookinglightest rounded-md md:border",
isEmbed ? "mx-auto" : selectedDate ? "max-w-5xl" : "max-w-3xl"
)}>
{/* mobile: details */}
@@ -18,7 +18,13 @@ import { FormattedNumber, IntlProvider } from "react-intl";
import { ReactMultiEmail } from "react-multi-email";
import { useMutation } from "react-query";
import { useIsEmbed, useIsBackgroundTransparent } from "@calcom/embed-core";
import {
useIsEmbed,
useEmbedStyles,
useIsBackgroundTransparent,
useEmbedType,
useEmbedNonStylesConfig,
} from "@calcom/embed-core";
import classNames from "@calcom/lib/classNames";
import { useLocale } from "@calcom/lib/hooks/useLocale";
import { HttpError } from "@calcom/lib/http-error";
@@ -71,6 +77,8 @@ const BookingPage = ({
}: BookingPageProps) => {
const { t, i18n } = useLocale();
const isEmbed = useIsEmbed();
const shouldAlignCentrallyInEmbed = useEmbedNonStylesConfig("align") !== "left";
const shouldAlignCentrally = !isEmbed || shouldAlignCentrallyInEmbed;
const router = useRouter();
const { contracts } = useContracts();
const { data: session } = useSession();
@@ -298,16 +306,17 @@ const BookingPage = ({
<CustomBranding lightVal={profile.brandColor} darkVal={profile.darkBrandColor} />
<main
className={classNames(
isEmbed ? "mx-auto" : "mx-auto my-0 rounded-sm sm:my-24",
"max-w-3xl sm:border sm:dark:border-gray-600"
shouldAlignCentrally ? "mx-auto" : "",
isEmbed ? "" : "sm:my-24",
"my-0 max-w-3xl "
)}>
{isReady && (
<div
className={classNames(
"overflow-hidden",
"main overflow-hidden",
isEmbed ? "" : "border border-gray-200",
isBackgroundTransparent ? "" : "bg-white dark:border-0 dark:bg-gray-800",
"sm:rounded-sm"
isBackgroundTransparent ? "" : "dark:border-1 bg-white dark:bg-gray-800",
"rounded-md sm:border sm:dark:border-gray-600"
)}>
<div className="px-4 py-5 sm:flex sm:p-4">
<div className="sm:w-1/2 sm:border-r sm:dark:border-gray-700">
+26 -4
View File
@@ -1,5 +1,6 @@
import { CreditCardIcon } from "@heroicons/react/solid";
import { Elements } from "@stripe/react-stripe-js";
import classNames from "classnames";
import dayjs from "dayjs";
import timezone from "dayjs/plugin/timezone";
import toArray from "dayjs/plugin/toArray";
@@ -8,6 +9,7 @@ import Head from "next/head";
import React, { FC, useEffect, useState } from "react";
import { FormattedNumber, IntlProvider } from "react-intl";
import { sdkActionManager, useIsEmbed } from "@calcom/embed-core";
import getStripe from "@calcom/stripe/client";
import PaymentComponent from "@ee/components/stripe/Payment";
import { PaymentPageProps } from "@ee/pages/payment/[uid]";
@@ -26,16 +28,33 @@ const PaymentPage: FC<PaymentPageProps> = (props) => {
const [is24h, setIs24h] = useState(isBrowserLocale24h());
const [date, setDate] = useState(dayjs.utc(props.booking.startTime));
const { isReady, Theme } = useTheme(props.profile.theme);
const isEmbed = useIsEmbed();
useEffect(() => {
let embedIframeWidth = 0;
setDate(date.tz(localStorage.getItem("timeOption.preferredTimeZone") || dayjs.tz.guess()));
setIs24h(!!localStorage.getItem("timeOption.is24hClock"));
}, []);
if (isEmbed) {
requestAnimationFrame(function fixStripeIframe() {
// HACK: Look for stripe iframe and center position it just above the embed content
const stripeIframeWrapper = document.querySelector(
'iframe[src*="https://js.stripe.com/v3/authorize-with-url-inner"]'
)?.parentElement;
if (stripeIframeWrapper) {
stripeIframeWrapper.style.margin = "0 auto";
stripeIframeWrapper.style.width = embedIframeWidth + "px";
}
requestAnimationFrame(fixStripeIframe);
});
sdkActionManager?.on("__dimensionChanged", (e) => {
embedIframeWidth = e.detail.data.iframeWidth as number;
});
}
}, [isEmbed]);
const eventName = props.booking.title;
return isReady ? (
<div className="h-screen bg-neutral-50 dark:bg-neutral-900">
<div className="h-screen">
<Theme />
<Head>
<title>
@@ -51,7 +70,10 @@ const PaymentPage: FC<PaymentPageProps> = (props) => {
&#8203;
</span>
<div
className="inline-block transform overflow-hidden rounded-sm border border-neutral-200 bg-white px-8 pt-5 pb-4 text-left align-bottom transition-all dark:border-neutral-700 dark:bg-gray-800 sm:my-8 sm:w-full sm:max-w-lg sm:py-6 sm:align-middle"
className={classNames(
"main inline-block transform overflow-hidden rounded-lg border border-neutral-200 bg-white px-8 pt-5 pb-4 text-left align-bottom transition-all dark:border-neutral-700 dark:bg-gray-800 sm:w-full sm:max-w-lg sm:py-6 sm:align-middle",
isEmbed ? "" : "sm:my-8"
)}
role="dialog"
aria-modal="true"
aria-labelledby="modal-headline">
+5 -2
View File
@@ -18,6 +18,8 @@ function applyThemeAndAddListener(theme: string) {
document.documentElement.classList.remove("dark");
}
} else {
document.documentElement.classList.remove("dark");
document.documentElement.classList.remove("light");
document.documentElement.classList.add(theme);
}
};
@@ -33,15 +35,16 @@ export default function useTheme(theme?: Maybe<string>) {
const embedTheme = useEmbedTheme();
// Embed UI configuration takes more precedence over App Configuration
theme = embedTheme || theme;
const [_theme, setTheme] = useState<Maybe<string>>(null);
useEffect(() => {
// TODO: isReady doesn't seem required now. This is also impacting PSI Score for pages which are using isReady.
setIsReady(true);
setTheme(theme);
}, []);
function Theme() {
const code = applyThemeAndAddListener.toString();
const themeStr = theme ? `"${theme}"` : null;
const themeStr = _theme ? `"${_theme}"` : null;
return (
<Head>
<script dangerouslySetInnerHTML={{ __html: `(${code})(${themeStr})` }}></script>
+49 -6
View File
@@ -1,6 +1,7 @@
import { ArrowRightIcon } from "@heroicons/react/outline";
import { BadgeCheckIcon } from "@heroicons/react/solid";
import { UserPlan } from "@prisma/client";
import classNames from "classnames";
import { GetServerSidePropsContext } from "next";
import dynamic from "next/dynamic";
import Link from "next/link";
@@ -9,9 +10,10 @@ import React, { useEffect, useState } from "react";
import { Toaster } from "react-hot-toast";
import { JSONObject } from "superjson/dist/types";
import { sdkActionManager, useEmbedStyles, useIsEmbed } from "@calcom/embed-core";
import { sdkActionManager, useEmbedNonStylesConfig, useEmbedStyles, useIsEmbed } from "@calcom/embed-core";
import defaultEvents, {
getDynamicEventDescription,
getGroupName,
getUsernameList,
getUsernameSlugLink,
} from "@calcom/lib/defaultEvents";
@@ -23,6 +25,7 @@ import prisma from "@lib/prisma";
import { collectPageParameters, telemetryEventTypes, useTelemetry } from "@lib/telemetry";
import { inferSSRProps } from "@lib/types/inferSSRProps";
import CustomBranding from "@components/CustomBranding";
import AvatarGroup from "@components/ui/AvatarGroup";
import { AvatarSSR } from "@components/ui/AvatarSSR";
@@ -37,7 +40,7 @@ interface EvtsToVerify {
}
export default function User(props: inferSSRProps<typeof getServerSideProps>) {
const { users } = props;
const { users, profile } = props;
const [user] = users; //To be used when we only have a single user, not dynamic group
const { Theme } = useTheme(user.theme);
const { t } = useLocale();
@@ -102,13 +105,15 @@ export default function User(props: inferSSRProps<typeof getServerSideProps>) {
))}
</ul>
);
const isEmbed = useIsEmbed();
const eventTypeListItemEmbedStyles = useEmbedStyles("eventTypeListItem");
const shouldAlignCentrallyInEmbed = useEmbedNonStylesConfig("align") !== "left";
const shouldAlignCentrally = !isEmbed || shouldAlignCentrallyInEmbed;
const query = { ...router.query };
delete query.user; // So it doesn't display in the Link (and make tests fail)
useExposePlanGlobally("PRO");
const nameOrUsername = user.name || user.username || "";
const [evtsToVerify, setEvtsToVerify] = useState<EvtsToVerify>({});
const isEmbed = useIsEmbed();
const telemetry = useTelemetry();
useEffect(() => {
@@ -128,8 +133,17 @@ export default function User(props: inferSSRProps<typeof getServerSideProps>) {
username={isDynamicGroup ? dynamicUsernames.join(", ") : (user.username as string) || ""}
// avatar={user.avatar || undefined}
/>
<div className={"h-screen dark:bg-neutral-900" + isEmbed ? " bg:white m-auto max-w-3xl" : ""}>
<main className="mx-auto max-w-3xl px-4 py-24">
<CustomBranding lightVal={profile.brandColor} darkVal={profile.darkBrandColor} />
<div className={classNames(shouldAlignCentrally ? "mx-auto" : "", isEmbed ? "max-w-3xl" : "")}>
<main
className={classNames(
shouldAlignCentrally ? "mx-auto" : "",
isEmbed
? " border-bookinglightest rounded-md border bg-white dark:bg-neutral-900 sm:dark:border-gray-600"
: "",
"max-w-3xl py-24 px-4"
)}>
{isSingleUser && ( // When we deal with a single user, not dynamic group
<div className="mb-8 text-center">
<AvatarSSR user={user} className="mx-auto mb-4 h-24 w-24" alt={nameOrUsername}></AvatarSSR>
@@ -284,6 +298,8 @@ export const getServerSideProps = async (context: GetServerSidePropsContext) =>
email: true,
name: true,
bio: true,
brandColor: true,
darkBrandColor: true,
avatar: true,
theme: true,
plan: true,
@@ -298,10 +314,36 @@ export const getServerSideProps = async (context: GetServerSidePropsContext) =>
notFound: true,
};
}
const isDynamicGroup = users.length > 1;
const dynamicNames = isDynamicGroup
? users.map((user) => {
return user.name || "";
})
: [];
const [user] = users; //to be used when dealing with single user, not dynamic group
const profile = isDynamicGroup
? {
name: getGroupName(dynamicNames),
image: null,
theme: null,
weekStart: "Sunday",
brandColor: "",
darkBrandColor: "",
allowDynamicBooking: users.some((user) => {
return !user.allowDynamicBooking;
})
? false
: true,
}
: {
name: user.name || user.username,
image: user.avatar,
theme: user.theme,
brandColor: user.brandColor,
darkBrandColor: user.darkBrandColor,
};
const usersIds = users.map((user) => user.id);
const credentials = await prisma.credential.findMany({
where: {
@@ -337,6 +379,7 @@ export const getServerSideProps = async (context: GetServerSidePropsContext) =>
return {
props: {
users,
profile,
user: {
emailMd5: crypto.createHash("md5").update(user.email).digest("hex"),
},
+4 -2
View File
@@ -5,7 +5,7 @@ type Props = Record<string, unknown> & DocumentProps;
class MyDocument extends Document<Props> {
static async getInitialProps(ctx: DocumentContext) {
const initialProps = await Document.getInitialProps(ctx);
const isEmbed = ctx.req?.url?.includes("embed");
const isEmbed = ctx.req?.url?.includes("embed=");
return { ...initialProps, isEmbed };
}
@@ -27,7 +27,9 @@ class MyDocument extends Document<Props> {
</Head>
{/* Keep the embed hidden till parent initializes and gives it the appropriate styles */}
<body className="bg-gray-100 dark:bg-neutral-900" style={props.isEmbed ? { display: "none" } : {}}>
<body
className={props.isEmbed ? "bg-transparent" : "bg-gray-100 dark:bg-neutral-900"}
style={props.isEmbed ? { display: "none" } : {}}>
<Main />
<NextScript />
</body>
+20 -9
View File
@@ -12,7 +12,12 @@ import Link from "next/link";
import { useRouter } from "next/router";
import { useEffect, useState, useRef } from "react";
import { useIsEmbed, useEmbedStyles, useIsBackgroundTransparent } from "@calcom/embed-core";
import {
useIsEmbed,
useEmbedStyles,
useIsBackgroundTransparent,
useEmbedNonStylesConfig,
} from "@calcom/embed-core";
import { sdkActionManager } from "@calcom/embed-core";
import { getDefaultEvent } from "@calcom/lib/defaultEvents";
import { useLocale } from "@calcom/lib/hooks/useLocale";
@@ -88,7 +93,7 @@ function RedirectionToast({ url }: { url: string }) {
return (
<>
<div className="relative inset-x-0 top-0 z-[60] pb-2 sm:fixed sm:top-2 sm:pb-5">
<div className="relative z-[60] pb-2 sm:pb-5">
<div className="mx-auto w-full sm:max-w-7xl sm:px-2 lg:px-8">
<div className="border border-green-600 bg-green-500 p-2 sm:p-3">
<div className="flex flex-wrap items-center justify-between">
@@ -142,6 +147,9 @@ export default function Success(props: inferSSRProps<typeof getServerSideProps>)
const isBackgroundTransparent = useIsBackgroundTransparent();
const isEmbed = useIsEmbed();
const shouldAlignCentrallyInEmbed = useEmbedNonStylesConfig("align") !== "left";
const shouldAlignCentrally = !isEmbed || shouldAlignCentrallyInEmbed;
const attendeeName = typeof name === "string" ? name : "Nameless";
const eventNameObject = {
@@ -214,19 +222,22 @@ export default function Success(props: inferSSRProps<typeof getServerSideProps>)
description={needsConfirmation ? t("booking_submitted") : t("booking_confirmed")}
/>
<CustomBranding lightVal={props.profile.brandColor} darkVal={props.profile.darkBrandColor} />
<main className={classNames("mx-auto", isEmbed ? "" : "max-w-3xl py-24")}>
<div className={classNames("overflow-y-auto", isEmbed ? "" : "fixed inset-0 z-50 ")}>
<main className={classNames(shouldAlignCentrally ? "mx-auto" : "", isEmbed ? "" : "max-w-3xl")}>
<div className={classNames("overflow-y-auto", isEmbed ? "" : "z-50 ")}>
{isSuccessRedirectAvailable(eventType) && eventType.successRedirectUrl ? (
<RedirectionToast url={eventType.successRedirectUrl}></RedirectionToast>
) : null}{" "}
<div className="flex min-h-screen items-end justify-center px-4 pt-4 pb-20 text-center sm:block sm:p-0">
<div
className={classNames(
shouldAlignCentrally ? "text-center" : "",
"flex items-end justify-center px-4 pt-4 pb-20 sm:block sm:p-0"
)}>
<div
className={classNames("my-4 transition-opacity sm:my-0", isEmbed ? "" : "fixed inset-0")}
className={classNames("my-4 transition-opacity sm:my-0", isEmbed ? "" : " inset-0")}
aria-hidden="true">
<div
className={classNames(
"inline-block transform overflow-hidden rounded-sm",
isEmbed ? "" : "border sm:my-8 sm:max-w-lg ",
"inline-block transform overflow-hidden rounded-md border sm:my-8 sm:max-w-lg",
isBackgroundTransparent ? "" : "bg-white dark:border-neutral-700 dark:bg-gray-800",
"px-8 pt-5 pb-4 text-left align-bottom transition-all sm:w-full sm:py-6 sm:align-middle"
)}
@@ -404,7 +415,7 @@ export default function Success(props: inferSSRProps<typeof getServerSideProps>)
</form>
</div>
)}
{userIsOwner && (
{userIsOwner && !isEmbed && (
<div className="mt-4">
<Link href="/bookings">
<a className="flex items-center text-black dark:text-white">
+1 -1
View File
@@ -86,7 +86,7 @@ function TeamPage({ team }: TeamPageProps) {
<div>
<Theme />
<HeadSeo title={teamName} description={teamName} />
<div className="px-4 pt-24 pb-12">
<div className="rounded-md bg-white px-4 pt-24 pb-12 dark:bg-gray-800 md:border">
<div className="max-w-96 mx-auto mb-8 text-center">
<Avatar
alt={teamName}