feat: Headless router - queue recording booking response (#21805)

* Add queued booking response table

* Create `RoutingFormResponseRepository`

* Pass `queueFormResponse` param

* Queue up form response if param is passed

* Forward queued form response parma to booker

* Pass `queuedFormResponse` from booker to `handleNewBooking`

* Write queued routing form response

* Type fixes

* Clean up

* Allow dry run to work which wont have any QueuedFormResponse or FormResponse

* Support passing the time when the modal was actually shown to the user and consider that time as the time of form submission

* fix ts error

* Queue -> Response through separate endpoint that would be triggered by
embed

* Make queueResponseId a non-guessable uid

* Change queueFormResponse query param

* fix ts error

* Support useQueuedResponse to record new response data

* revert handleNewBooking

* Remove dead code formResponse

* Refactor use repository

* Unify migration files

* refactor: moved api endpoint to app dir

Signed-off-by: Omar López <[email protected]>

* Update formResponse.ts

* Refactor use-queued-response for test

* Add tests

* Fix ts error and unit test. recordFormResponse cant return nullish response

* fix schema

* feat: Support full reuse of preloaded iframe (#21803)

* feat: support updating cal video settings in API v2 (#21784)

* feat: support updating cal video settings in API v2

* chore: update descriptio

* feat: support create event type

* test: add test for updating event type

* test: add test for create event type

* chore: undo openapi

* chore: bump libraries

* Revert "chore: bump libraries"

This reverts commit bdf36d09b021fc531497a7b7ea66ab9c52b7d136.

* chore: bump libraries

---------

Co-authored-by: Lauris Skraucis <[email protected]>
Co-authored-by: supalarry <[email protected]>

* fix tests and ts

* Fix tests

* wip-useQueuedResponseEndpoint

* Add one more test

* Change queueFormResponse query param

* wip

* Support useQueuedResponse to record new response data

* Use the update useQueuedResponse endpoint

* self-review addressed

* Use queuedResponse if available in slots/utils

* Add documentation

* Remove use-queued-response from critical-path

---------

Co-authored-by: Udit Takkar <[email protected]>
Co-authored-by: Lauris Skraucis <[email protected]>
Co-authored-by: supalarry <[email protected]>

* Update schema.prisma

* refactor: renamed to avoid react hooks confusion

Signed-off-by: Omar López <[email protected]>

---------

Signed-off-by: Omar López <[email protected]>
Co-authored-by: Hariom Balhara <[email protected]>
Co-authored-by: Omar López <[email protected]>
Co-authored-by: Udit Takkar <[email protected]>
Co-authored-by: Lauris Skraucis <[email protected]>
Co-authored-by: supalarry <[email protected]>
Co-authored-by: Peer Richelsen <[email protected]>
This commit is contained in:
authored and GitHub committed 2025-06-17 12:11:49 -03:00
1 parent 9a40e54159
commit 22f136d19b
28 files changed
+1408 -424

No files matched your search

+6 -29
View File
@@ -1,13 +1,8 @@
<html>
<head>
<title>Embed Playground</title>
<!-- <link rel="prerender" href="http://localhost:3000/free"> -->
<!-- <script src="./src/embed.ts" type="module"></script> -->
<script type="text/javascript" src="./playground/lib/playground-init.ts"></script>
<script>
const url = new URL(document.URL);
window.only = url.searchParams.get("only")
window.calOrigin = url.searchParams.get("calOrigin") || "http://localhost:3000";
let popupRescheduleUid = null;
let calLink = null;
const initialNamespace = (url.searchParams.get("only") || "").split("ns:")[1] || "";
@@ -16,29 +11,11 @@
popupRescheduleUid = searchParams.get("popupRescheduleUid") || "qm3kwt3aTnVD7vmP9tiT2f";
calLink = searchParams.get("calLink");
})()
function generateRandomHexColor() {
// Generate a random integer between 0 and 16777215 (FFFFFF in hex)
const randomInt = Math.floor(Math.random() * 16777216);
// Convert the integer to a hex string with 6 digits and add leading zeros if necessary
const hexString = randomInt.toString(16).padStart(6, "0");
// Return the hex string with a '#' prefix
return `#${hexString}`;
}
if (!location.search.includes("nonResponsive")) {
document.write('<meta name="viewport" content="width=device-width"/>');
}
function scrollToIframeInPlayground() {
const url = new URL(document.URL);
// Only run the example specified by only=, avoids distraction and faster to test.
const only = (window.only = url.searchParams.get("only") || '');
const elementIdentifier = only !== "all" ? only.replace("ns:", "") : null;
if (elementIdentifier) {
location.hash = "#cal-booking-place-" + elementIdentifier + "-iframe";
}
}
function addInlineEmbedInNewNamespaceWithoutReload(selector) {
Cal("init", "withoutReloadNamespace", {
debug: true,
@@ -377,10 +354,10 @@
</button>
<button
onclick="(function () {Cal.ns.second('ui', {styles:{enabledDateButton: {
backgroundColor: generateRandomHexColor(),
backgroundColor: window.generateRandomHexColor(),
},
disabledDateButton: {
backgroundColor: generateRandomHexColor(),
backgroundColor: window.generateRandomHexColor(),
},}})})()">
Change 'enabledDateButton` and `disabledDateButton` background Color[Deprecated]
</button>
@@ -474,7 +451,7 @@
</div>
</div>
</div>
<script type="module" src="./playground.ts"></script>
<script type="module" src="./playground/lib/playground.ts"></script>
<script>
if (initialNamespace.startsWith("skeletonDemo")) {
document.getElementById("misc-embeds").style.display = "none";
@@ -0,0 +1,21 @@
const url = new URL(document.URL);
window.only = url.searchParams.get("only");
window.calOrigin = url.searchParams.get("calOrigin") || "http://localhost:3000";
window.calLink = url.searchParams.get("calLink");
// We ensure that email is passed as param.email and not email so that autoforwarding of params plus explicit passing of email param doesn't make it an array of emails
const emailQueryParam = url.searchParams.get("param.email");
window.params = {
email: emailQueryParam,
formId: url.searchParams.get("param.formId"),
};
window.generateRandomHexColor = function generateRandomHexColor() {
// Generate a random integer between 0 and 16777215 (FFFFFF in hex)
const randomInt = Math.floor(Math.random() * 16777216);
// Convert the integer to a hex string with 6 digits and add leading zeros if necessary
const hexString = randomInt.toString(16).padStart(6, "0");
// Return the hex string with a '#' prefix
return `#${hexString}`;
};
@@ -1,4 +1,4 @@
import type { GlobalCal, EmbedEvent } from "./src/embed";
import type { GlobalCal, EmbedEvent } from "../../src/embed";
const Cal = window.Cal as GlobalCal;
Cal.config = Cal.config || {};
@@ -2,14 +2,8 @@
<head>
<title>Embed Playground - Routing Form</title>
<!-- <link rel="prerender" href="http://localhost:3000/free"> -->
<!-- <script src="./src/embed.ts" type="module"></script> -->
<script type="text/javascript" src="./playground/lib/playground-init.ts"></script>
<script>
const url = new URL(document.URL);
window.only = url.searchParams.get("only")
window.calOrigin = url.searchParams.get("calOrigin") || "http://localhost:3000";
window.calLink = url.searchParams.get("calLink");
if (!location.search.includes("nonResponsive")) {
document.write('<meta name="viewport" content="width=device-width"/>');
}
@@ -103,12 +97,38 @@
<body>
<div style="display: flex; flex-direction: column; gap: 10px;">
<div id="cal-booking-place-routingFormWithoutPrerender">
<a href="?only=ns:routingFormWithoutPrerender">Routing Form Without Prerender Demo</a>
<form id="cal-booking-place-routingFormWithoutPrerender-form">
<input type="text" name="name" placeholder="John Doe" />
<input type="email" name="email" placeholder="[email protected]" />
<select name="skills" placeholder="JavaScript, Node.js">
<option value="JavaScript">JavaScript</option>
<option value="Sales">Sales</option>
</select>
</form>
<button id="cal-booking-place-routingFormWithoutPrerender-submit" data-cal-namespace="routingFormWithoutPrerender" data-cal-config='{"cal.embed.pageType":"team.event.booking.slots", "guests":["[email protected]", "[email protected]"]}'>Submit</button>
<script>
requestAnimationFrame(function updateSubmitButtonLink() {
const seededFormAcmeId = "948ae412-d995-4865-885a-48302588de03";
const form = document.getElementById("cal-booking-place-routingFormWithoutPrerender-form");
const name = form.querySelector("input[name='name']").value;
const email = form.querySelector("input[name='email']").value;
const skills = form.querySelector("select[name='skills']").value;
if (name && email) {
document.getElementById("cal-booking-place-routingFormWithoutPrerender-submit").setAttribute("data-cal-link", `router?form=${seededFormAcmeId}&email=${email}&name=${name}&Location=London&Department=Engineering&Manager=John Doe&Rating=5&skills=${skills}&Email=${email}`);
}
requestAnimationFrame(updateSubmitButtonLink);
});
</script>
</div>
<div id="cal-booking-place-routingFormPrerender">
<a href="?only=ns:routingFormPrerender">Routing Form Prerender Demo</a>
<hr/>
<a href="?only=ns:routingFormPrerender">Routing Form Prerender Team Booking Page - Demo</a>
<p>1. As soon as you start typing in the form, the form will prerender the booking page(where redirect is supposed to happen)</p>
<p>2. Clicking on submit will open the prerendered/being prerendered iframe in the modal</p>
<p>2. Clicking on submit will open the prerendered/being prerendered iframe in the modal, sending fresh request for headless router, followed by fetching the slots</p>
<p>3. Changing the form response and clicking submit, will re-submit the response and reopen the modal with the updated data(update slots call, updated prefill fields)</p>
<p>4. Clicking submit again without changing the form response will just re-show the hidden modal(as long as threshold of 1 min since last time the modal was shown is met). But, in case of an error it iframe always tries to rerender. Trying adding an invalid email to see the error</p>
<p>4. Clicking submit again without changing the form response will just re-show the hidden modal(as long as slotsStaleTimeMs threshold is not breached). But, in case of an error it iframe always tries to rerender. Trying adding an invalid email to see the error</p>
<form id="cal-booking-place-routingFormPrerender-form">
<input type="text" name="name" placeholder="John Doe" />
<input type="email" name="email" placeholder="[email protected]" />
@@ -143,33 +163,80 @@
});
</script>
</div>
<div id="cal-booking-place-routingFormWithoutPrerender">
<a href="?only=ns:routingFormWithoutPrerender">Routing Form Without Prerender Demo</a>
<form id="cal-booking-place-routingFormWithoutPrerender-form">
<input type="text" name="name" placeholder="John Doe" />
<input type="email" name="email" placeholder="[email protected]" />
<select name="skills" placeholder="JavaScript, Node.js">
<option value="JavaScript">JavaScript</option>
<option value="Sales">Sales</option>
</select>
</form>
<button id="cal-booking-place-routingFormWithoutPrerender-submit" data-cal-namespace="routingFormWithoutPrerender" data-cal-config='{"cal.embed.pageType":"team.event.booking.slots", "guests":["[email protected]", "[email protected]"]}'>Submit</button>
<script>
requestAnimationFrame(function updateSubmitButtonLink() {
const seededFormAcmeId = "948ae412-d995-4865-885a-48302588de03";
const form = document.getElementById("cal-booking-place-routingFormWithoutPrerender-form");
const name = form.querySelector("input[name='name']").value;
const email = form.querySelector("input[name='email']").value;
const skills = form.querySelector("select[name='skills']").value;
if (name && email) {
document.getElementById("cal-booking-place-routingFormWithoutPrerender-submit").setAttribute("data-cal-link", `router?form=${seededFormAcmeId}&email=${email}&name=${name}&Location=London&Department=Engineering&Manager=John Doe&Rating=5&skills=${skills}&Email=${email}`);
<div id="cal-booking-routing-full-prerender">
<hr/>
<a href="?only=ns:routing-full-prerender&debug=1&[email protected]">Routing Form - Prerender Headless Router itself queuing the form response</a>
<p>1. As page is loading, we prerender the headless router for the email passed as param.email</p>
<p>2. Whenever email changes and onblur happens, the prerender is triggered for the new email and previous prerendered modal is removed</p>
<p>3. The prerender of the headless router queues the form response and doesn't really record it. When the actual booking is made, the form response is recorded from the queue</p>
<p>4. If the CTA click happens before the slots are considered stale(configurable via options.slotsStaleTimeMs), then it will open the prerendered modal without fetching the slots, otherwise it will fetch the slots(for the routedTeamMembers/contactOwner only) and till then skeleton will be shown</p>
<p>5. If the CTA click happens after iframeForceReloadThresholdMs has passed, then fresh headless router request is sent which could be really slow. It is important to do force reload after a certain time because the Routing Form itself could have changed in the meantime or Salesforce ownership might be available or some other change might have occured in Cal.com's side</p>
<p>6. slotsStaleTimeMs is set to 10 seconds(default is 1 minute) and iframeForceReloadThresholdMs is set to 30 seconds(default is 15 minutes) and they are considered from the time when the prerender/modal call was made</p>
<p>7. To avoid reaching the iframeForceReloadThresholdMs, user could prerender the router again and again judiciously</p>
</p>
<script>
window.buildRouterUrl = ({email, formId}) => {
return `router?form=${formId}&email=${email}`;
}
requestAnimationFrame(updateSubmitButtonLink);
});
</script>
</script>
<div class="inline-embed-container">
<div id="cal-booking-place-routing-full-prerender">
<div class="place"></div>
<label for="cal-booking-place-routing-full-prerender-input-email">Email</label>
<script>
document.write(`<input style="width: 400px" type="email" id="cal-booking-place-routing-full-prerender-input-email" value="${window.params.email ?? ''}" />`)
</script>
</div>
</div>
<h3><script>
document.write(`<button id="cta-routing-full-prerender" data-cal-namespace="routingFormFullPrerender" data-cal-origin="${window.calOrigin}" data-cal-link="${window.buildRouterUrl({email:document.getElementById('cal-booking-place-routing-full-prerender-input-email').value, formId:window.params.formId})}" data-cal-config='{"cal.embed.pageType":"team.event.booking.slots"}'>Demo</button>`)
</script></h3>
<script>
(()=>{
if (window.only !== "ns:routing-full-prerender") {
return;
}
Cal("init", "routingFormFullPrerender", {
debug: true,
calOrigin: window.calOrigin,
});
const prerender = ({email, formId}) => {
Cal.ns.routingFormFullPrerender("prerender", {
// Email will be automatically passed as query param
calLink: window.buildRouterUrl({email, formId}),
type: "modal",
pageType: "team.event.booking.slots",
options: {
slotsStaleTimeMs: 10 * 1000,
iframeForceReloadThresholdMs: 30 * 1000,
},
});
}
document.getElementById('cal-booking-place-routing-full-prerender-input-email').onchange = function onEmailChange(e) {
const element = e.target;
const email = element.validity.valid ? element.value : null;
if (!email) {
return;
}
function updateCtaLink(email) {
const element = document.getElementById('cta-routing-full-prerender');
const currentLink = element.getAttribute('data-cal-link');
const currentLinkObject = new URL(currentLink, 'https://example.com');
currentLinkObject.searchParams.set('email', email);
element.setAttribute('data-cal-link', currentLinkObject.pathname + currentLinkObject.search);
}
updateCtaLink(email);
prerender({email, formId:window.params.formId});
}
if (!window.params.email || !window.params.formId) {
alert('Pass param.email and param.formId query params')
}
prerender({email:window.params.email, formId:window.params.formId});
})();
</script>
</div>
</div>
<script type="module" src="./playground.ts"></script>
<script type="module" src="./playground/lib/playground.ts"></script>
</script>
</body>
@@ -1,7 +1,5 @@
import { describe, it, expect, vi, beforeEach, afterEach } from "vitest";
import { embedStore, getEmbedBookerState } from "../embed-iframe";
// Test helper functions
type fakeCurrentDocumentUrlParams = {
origin?: string;
@@ -25,25 +23,25 @@ function mockDocumentUrl(url: URL | string) {
return vi.spyOn(document, "URL", "get").mockReturnValue(url.toString());
}
function createSearchParams(params: Record<string, string>) {
const searchParams = new URLSearchParams();
Object.entries(params).forEach(([key, value]) => {
searchParams.set(key, value);
});
return searchParams;
afterEach(() => {
vi.clearAllMocks();
vi.resetModules();
vi.useRealTimers();
});
function nextTick() {
vi.advanceTimersByTime(100);
}
describe("embedStore.router.ensureQueryParamsInUrl", () => {
// Mock window.history and URL
describe("embedStore.router.ensureQueryParamsInUrl", async () => {
let embedStore: typeof import("../embed-iframe/lib/embedStore").embedStore;
const originalHistory = window.history;
const originalURL = window.URL;
function nextTick() {
vi.advanceTimersByTime(100);
}
beforeEach(async () => {
// Mock window.history and URL
({ embedStore } = await import("../embed-iframe/lib/embedStore"));
beforeEach(() => {
vi.useFakeTimers();
// Mock requestAnimationFrame and cancelAnimationFrame
window.requestAnimationFrame = vi.fn((callback: FrameRequestCallback) => {
@@ -75,7 +73,6 @@ describe("embedStore.router.ensureQueryParamsInUrl", () => {
it("should add missing parameters to URL", async () => {
// Setup
fakeCurrentDocumentUrl();
// Execute
const { stopEnsuringQueryParamsInUrl } = embedStore.router.ensureQueryParamsInUrl({
toBeThereParams: {
@@ -163,7 +160,13 @@ describe("embedStore.router.ensureQueryParamsInUrl", () => {
});
});
describe("getEmbedBookerState", () => {
describe("getEmbedBookerState", async () => {
let getEmbedBookerState: typeof import("../embed-iframe").getEmbedBookerState;
beforeEach(async () => {
fakeCurrentDocumentUrl();
({ getEmbedBookerState } = await import("../embed-iframe"));
});
it("should return 'initializing' when bookerState is 'loading'", () => {
const result = getEmbedBookerState({
bookerState: "loading",
@@ -242,3 +245,138 @@ describe("getEmbedBookerState", () => {
expect(result).toBe("slotsPending");
});
});
describe("methods", async () => {
let methods: typeof import("../embed-iframe").methods;
let embedStore: typeof import("../embed-iframe/lib/embedStore").embedStore;
let isLinkReadyMock: ReturnType<typeof vi.fn> | undefined;
let isBookerReadyMock: ReturnType<typeof vi.fn> | undefined;
let ensureQueryParamsInUrlMock: ReturnType<typeof vi.fn> | undefined;
let recordResponseIfQueuedMock: ReturnType<typeof vi.fn> | undefined;
beforeEach(async () => {
vi.useRealTimers();
fakeCurrentDocumentUrl();
vi.doMock("../embed-iframe/lib/utils", async (importOriginal) => {
const actual = await importOriginal<typeof import("../embed-iframe/lib/utils")>();
return {
...actual,
isLinkReady: isLinkReadyMock,
isBookerReady: isBookerReadyMock,
recordResponseIfQueued: recordResponseIfQueuedMock,
};
});
vi.doMock("../embed-iframe/lib/embedStore", async (importOriginal) => {
const actual = await importOriginal<typeof import("../embed-iframe/lib/embedStore")>();
return {
...actual,
embedStore: {
...actual.embedStore,
router: {
ensureQueryParamsInUrl: ensureQueryParamsInUrlMock,
},
},
};
});
isLinkReadyMock = vi.fn();
isBookerReadyMock = vi.fn();
ensureQueryParamsInUrlMock = vi.fn().mockImplementation(() => {
console.log("Fake ensureQueryParamsInUrl called");
return {
stopEnsuringQueryParamsInUrl: vi.fn(),
};
});
recordResponseIfQueuedMock = vi.fn().mockResolvedValue(1);
({ methods } = await import("../embed-iframe"));
({ embedStore } = await import("../embed-iframe/lib/embedStore"));
});
describe("methods.connect", async () => {
it("should ensure that 'cal.embed.connectVersion' is incremented in query params", async () => {
embedStore.renderState = "completed";
const currentConnectVersion = 1;
embedStore.connectVersion = currentConnectVersion;
fakeCurrentDocumentUrl({ params: { "cal.embed.connectVersion": "1" } });
isLinkReadyMock?.mockReturnValue(true);
isBookerReadyMock?.mockReturnValue(true);
await methods.connect({
config: {},
params: {},
});
expect(ensureQueryParamsInUrlMock).toHaveBeenCalledWith({
toBeThereParams: {
"cal.embed.connectVersion": (currentConnectVersion + 1).toString(),
},
toRemoveParams: ["preload", "prerender", "cal.skipSlotsFetch"],
});
});
it("should ensure that 'cal.embed.connectVersion' is not incremented in query params when 'cal.embed.noSlotsFetchOnConnect' is true", async () => {
embedStore.renderState = "completed";
const currentConnectVersion = 1;
embedStore.connectVersion = currentConnectVersion;
fakeCurrentDocumentUrl({ params: { "cal.embed.connectVersion": "1" } });
isLinkReadyMock?.mockReturnValue(true);
isBookerReadyMock?.mockReturnValue(true);
await methods.connect({
config: {
"cal.embed.noSlotsFetchOnConnect": "true",
},
params: {},
});
expect(embedStore.router.ensureQueryParamsInUrl).toHaveBeenCalledWith({
toBeThereParams: {
"cal.embed.connectVersion": currentConnectVersion.toString(),
},
toRemoveParams: ["preload", "prerender", "cal.skipSlotsFetch"],
});
});
it("should set/update 'cal.routingFormResponseId' if the current iframe has 'cal.queuedFormResponse' in the query params", async () => {
embedStore.renderState = "completed";
const currentConnectVersion = 1;
embedStore.connectVersion = currentConnectVersion;
fakeCurrentDocumentUrl({
params: {
"cal.queuedFormResponse": "true",
"cal.routingFormResponseId": "1",
"cal.embed.connectVersion": currentConnectVersion.toString(),
},
});
const convertedRoutingFormResponseId = 101;
recordResponseIfQueuedMock?.mockResolvedValue(convertedRoutingFormResponseId);
isLinkReadyMock?.mockReturnValue(true);
isBookerReadyMock?.mockReturnValue(true);
await methods.connect({
config: {},
params: {},
});
expect(ensureQueryParamsInUrlMock).toHaveBeenCalledWith({
toBeThereParams: {
"cal.embed.connectVersion": (currentConnectVersion + 1).toString(),
"cal.routingFormResponseId": convertedRoutingFormResponseId.toString(),
},
toRemoveParams: ["preload", "prerender", "cal.skipSlotsFetch"],
});
});
});
describe("methods.parentKnowsIframeReady", () => {
beforeEach(() => {
vi.useFakeTimers();
});
afterEach(() => {
vi.useRealTimers();
});
it("should set renderState to 'completed' on link ready", () => {
isLinkReadyMock?.mockReturnValue(true);
methods.parentKnowsIframeReady({});
expect(embedStore.renderState).not.toBe("completed");
nextTick();
expect(embedStore.renderState).toBe("completed");
});
});
});
+5 -3
View File
@@ -1,7 +1,9 @@
// We can't keep it too high because that might cause stale content to be shown
// TODO: We should introduce a slotRefresh mechanism
export const EMBED_MODAL_IFRAME_SLOT_STALE_TIME = 10 * 1000; // 1 minute
export const EMBED_MODAL_IFRAME_FORCE_RELOAD_THRESHOLD_MS = 2 * 60 * 1000; // 2 minutes
// Configurable via options.slotsStaleTimeMs. We could keep it at a lower end as the impact would be refetch of availability only.
export const EMBED_MODAL_IFRAME_SLOT_STALE_TIME = 60 * 1000; // 1 minute
// Keep it high by default to avoid impact on loading time as it would cause a full reload of the iframe user can configure it via options.iframeForceReloadThresholdMs
// Also full reload means that response would be resubmitted.
export const EMBED_MODAL_IFRAME_FORCE_RELOAD_THRESHOLD_MS = 15 * 60 * 1000; // 15 minutes
if (EMBED_MODAL_IFRAME_SLOT_STALE_TIME > EMBED_MODAL_IFRAME_FORCE_RELOAD_THRESHOLD_MS) {
throw new Error(
+103 -182
View File
@@ -3,9 +3,10 @@
import { useEffect, useRef, useState, useCallback } from "react";
import type { Message } from "./embed";
import { embedStore, EMBED_IFRAME_STATE } from "./embed-iframe/lib/embedStore";
import { runAsap, isBookerReady, isLinkReady, recordResponseIfQueued } from "./embed-iframe/lib/utils";
import { sdkActionManager } from "./sdk-event";
import type {
EmbedThemeConfig,
UiConfig,
EmbedNonStylesConfig,
BookerLayouts,
@@ -13,9 +14,10 @@ import type {
EmbedBookerState,
SlotsQuery,
PrefillAndIframeAttrsConfig,
SetStyles,
setNonStylesConfig,
} from "./types";
import { useCompatSearchParams } from "./useCompatSearchParams";
import { isParamValuePresentInUrlSearchParams } from "./utils";
// We don't import it from Booker/types because the types from this module are published to npm and we can't import packages that aren't published
type BookerState = "loading" | "selecting_date" | "selecting_time" | "booking";
@@ -27,16 +29,12 @@ const eventsAllowedInPrerendering = [
// so that iframe height is adjusted according to the content, and iframe is ready to be shown when needed
"__dimensionChanged",
// When this event is fired, the iframe is still in prerender state but is going to be moved out of prerender state
"__connectInitiated",
// For other events, we should consider introducing prerender specific events and not reuse existing events
];
type SetStyles = React.Dispatch<React.SetStateAction<EmbedStyles>>;
type setNonStylesConfig = React.Dispatch<React.SetStateAction<EmbedNonStylesConfig>>;
const enum EMBED_IFRAME_STATE {
NOT_INITIALIZED,
INITIALIZED,
}
declare global {
interface Window {
CalEmbed: {
@@ -49,110 +47,6 @@ declare global {
}
}
/**
* This is in-memory persistence needed so that when user browses through the embed, the configurations from the instructions aren't lost.
*/
export const embedStore = {
connectVersion: 0 as number,
/**
* Tracks whether the prerender has been completed or not.
* NOTE: prerenderState would be "completed" even after the iframe was switched from isPrerendering=true to not Prerendering(which happens after connect)
*/
prerenderState: null as null | "inProgress" | "completed",
// Handles the commands of routing received from parent even when React hasn't initialized and nextRouter isn't available
router: {
/**
* When we do the history push, it is possible that
* - React might revert that change depending on in what state React is in while initializing
* - So, we use a declarative approach to ensure that our requirement is continuously met
*/
ensureQueryParamsInUrl({
toBeThereParams,
toRemoveParams,
}: {
toBeThereParams: Record<string, string | string[]>;
toRemoveParams: string[];
}) {
let stopUpdating = false;
function updateIfNeeded() {
if (stopUpdating) {
return { hasChanged: false };
}
const currentUrl = new URL(document.URL);
let hasChanged = false;
// Ensuring toBeThereSearchParams
for (const [key, newValue] of Object.entries(toBeThereParams)) {
// It checks that the value must be present and if an array no other item should be there except those in newValue
hasChanged = !isParamValuePresentInUrlSearchParams({
param: key,
value: newValue,
container: currentUrl.searchParams,
});
if (hasChanged) {
setParamInUrl({ key, value: newValue, url: currentUrl });
}
}
removeParamsFromUrl({ keys: toRemoveParams, url: currentUrl });
hasChanged = hasChanged || toRemoveParams.length > 0;
if (hasChanged) {
// Avoid unnecessary history push
window.history.replaceState({}, "", currentUrl.toString());
}
runAsap(updateIfNeeded);
return {
hasChanged,
};
}
const { hasChanged } = updateIfNeeded();
return {
stopEnsuringQueryParamsInUrl: () => {
stopUpdating = true;
},
hasChanged,
};
function removeParamsFromUrl({ keys, url }: { keys: string[]; url: URL }) {
for (const key of keys) {
url.searchParams.delete(key);
}
}
function setParamInUrl({ key, value, url }: { key: string; value: string | string[]; url: URL }) {
// Reset and then set the new value, to ensure nothing else remains in value
url.searchParams.delete(key);
const newValueArray = Array.isArray(value) ? value : [value];
newValueArray.forEach((val) => {
url.searchParams.append(key, val);
});
}
},
},
state: EMBED_IFRAME_STATE.NOT_INITIALIZED,
// Store all embed styles here so that as and when new elements are mounted, styles can be applied to it.
styles: {} as EmbedStyles | undefined,
nonStyles: {} as EmbedNonStylesConfig | undefined,
namespace: null as string | null,
embedType: undefined as undefined | null | string,
// Store all React State setters here.
reactStylesStateSetters: {} as Record<keyof EmbedStyles, SetStyles>,
reactNonStylesStateSetters: {} as Record<keyof EmbedNonStylesConfig, setNonStylesConfig>,
// Embed can show itself only after this is set to true
parentInformedAboutContentHeight: false,
windowLoadEventFired: false,
setTheme: undefined as ((arg0: EmbedThemeConfig) => void) | undefined,
theme: undefined as UiConfig["theme"],
uiConfig: undefined as Omit<UiConfig, "styles" | "theme"> | undefined,
/**
* We maintain a list of all setUiConfig setters that are in use at the moment so that we can update all those components.
*/
setUiConfig: [] as ((arg0: UiConfig) => void)[],
};
let isSafariBrowser = false;
const isBrowser = typeof window !== "undefined";
@@ -166,11 +60,6 @@ if (isBrowser) {
}
}
function runAsap(fn: (...arg: unknown[]) => void) {
// We don't use rAF because it runs slower in Safari plus doesn't run if the iframe is hidden sometimes
return setTimeout(fn, 50);
}
function log(...args: unknown[]) {
if (isBrowser) {
const namespace = getNamespace();
@@ -366,31 +255,6 @@ function getEmbedType() {
}
}
/**
* It is important to be able to check realtime(instead of storing isLinkReady as a variable) if the link is ready, because there is a possibility that booker might have moved to non-ready state from ready state
*/
function isLinkReady() {
if (!embedStore.parentInformedAboutContentHeight) {
return false;
}
if (isBookerPage()) {
// Let's wait for Booker to be ready before showing the embed
// It means that booker has loaded all its data and is ready to show
// TODO: We could try to mark the embed as ready earlier in this case not relying on document.readyState
return isBookerReady();
}
return true;
}
function isBookerReady() {
return window._embedBookerState === "slotsDone";
}
function isBookerPage() {
return !!window._embedBookerState;
}
export const useIsEmbed = (embedSsr?: boolean) => {
const [isEmbed, setIsEmbed] = useState(embedSsr);
useEffect(() => {
@@ -441,8 +305,44 @@ function showPageAsNonEmbed() {
}
}
async function ensureRoutingFormResponseIdInUrl({
newlyRecordedResponseId,
toBeThereParams,
toRemoveParams,
}: {
newlyRecordedResponseId: number;
toBeThereParams: Record<string, string | string[]>;
toRemoveParams: string[];
}) {
// Update routingFormResponseId in url only after connect is completed, to keep things simple
// Adding cal.routingFormResponseId in query param later shouldn't change anything in UI plus no slot request would go again due ot this.
const { stopEnsuringQueryParamsInUrl } = embedStore.router.ensureQueryParamsInUrl({
toBeThereParams: {
...toBeThereParams,
"cal.routingFormResponseId": newlyRecordedResponseId.toString(),
},
toRemoveParams,
});
// Immediately stop ensuring query params in url as the page is already ready
// We could think about doing it after some time if needed later.
stopEnsuringQueryParamsInUrl();
}
async function waitForRenderStateToBeCompleted() {
return new Promise<void>((resolve) => {
(function tryToConnect() {
if (embedStore.renderState !== "completed") {
runAsap(tryToConnect);
return;
}
resolve();
})();
});
}
// It is a map of methods that can be called by parent using doInIframe({method: "methodName", arg: "argument"})
const methods = {
export const methods = {
ui: function style(uiConfig: UiConfig) {
// TODO: Create automatic logger for all methods. Useful for debugging.
log("Method: ui called", uiConfig);
@@ -490,27 +390,24 @@ const methods = {
// eslint-disable-next-line @typescript-eslint/no-unused-vars
parentKnowsIframeReady: (_unused: unknown) => {
log("Method: `parentKnowsIframeReady` called");
// No UI change should happen in sight. Let the parent height adjust and in next cycle show it.
// Embed background must still remain transparent
runAsap(function tryInformingLinkReady() {
if (!isLinkReady()) {
if (!isLinkReady({ embedStore })) {
runAsap(tryInformingLinkReady);
return;
}
// No UI change should happen in sight. Let the parent height adjust and in next cycle show it.
// Embed background must still remain transparent
makeBodyVisible();
if (isPrerendering()) {
log("prerenderState is 'completed'");
embedStore.prerenderState = "completed";
}
log("renderState is 'completed'");
embedStore.renderState = "completed";
sdkActionManager?.fire("linkReady", {});
});
},
/**
* Connects new config to prerendered page
*/
connect: function connect({
connect: async function connect({
config,
params,
}: {
@@ -520,12 +417,23 @@ const methods = {
// We can't accept URLSearchParams as it isn't cloneable and thus postMessage doesn't support it
params: Record<string, string | string[]>;
}) {
sdkActionManager?.fire("__connectInitiated", {});
log("Method: connect, requested with params", { config, params });
const { iframeAttrs: _1, ...queryParamsFromConfig } = config;
const connectVersion = (embedStore.connectVersion = embedStore.connectVersion + 1);
const {
iframeAttrs: _1,
"cal.embed.noSlotsFetchOnConnect": noSlotsFetchOnConnect,
...queryParamsFromConfig
} = config;
// We reset it to allow informing parent again through `__dimensionChanged` event about possibly updated dimensions with changes in config
embedStore.parentInformedAboutContentHeight = false;
if (noSlotsFetchOnConnect !== "true") {
log("Method: connect, noSlotsFetchOnConnect is false. Requesting slots re-fetch");
// Incrementing the version forces the slots call to be made again
embedStore.connectVersion = embedStore.connectVersion + 1;
}
const connectVersion = embedStore.connectVersion;
// Config is just a typed and more declarative way to pass the query params from the parent(except iframeAttrs which is meant to be consumed by parent and not supposed to passed to child)
// So, query params can come directly by providing them to calLink or through config
const toBeThereParams = {
@@ -535,19 +443,26 @@ const methods = {
"cal.embed.connectVersion": connectVersion.toString(),
};
(function tryToConnect() {
if (embedStore.prerenderState !== "completed") {
runAsap(tryToConnect);
return;
}
const toRemoveParams = ["preload", "prerender", "cal.skipSlotsFetch"];
await waitForRenderStateToBeCompleted();
log("Method: connect, prerenderState is completed. Connecting");
connectPreloadedEmbed({
// We know after removing iframeAttrs, that it is of this type
toBeThereParams,
toRemoveParams: ["preload", "prerender", "cal.skipSlotsFetch"],
});
})();
log("Method: connect, renderState is completed. Connecting");
await connectPreloadedEmbed({
// We know after removing iframeAttrs, that it is of this type
toBeThereParams,
toRemoveParams,
});
// We now record the response to routingFormResponse and connect that with queuedResponse, as the user actually opened the modal which is confirmed by this connect method call
const newlyRecordedResponseId = await recordResponseIfQueued(params);
if (!newlyRecordedResponseId) {
return;
}
await ensureRoutingFormResponseIdInUrl({
newlyRecordedResponseId,
toBeThereParams,
toRemoveParams,
});
},
};
@@ -723,9 +638,7 @@ function initializeAndSetupEmbed() {
isPrerendering: isPrerendering(),
});
if (isPrerendering()) {
embedStore.prerenderState = "inProgress";
}
embedStore.renderState = "inProgress";
// Only NOT_INITIALIZED -> INITIALIZED transition is allowed
if (embedStore.state !== EMBED_IFRAME_STATE.NOT_INITIALIZED) {
@@ -766,7 +679,7 @@ function actOnColorScheme(colorScheme: string | null | undefined) {
* Apply configurations to the preloaded page and then ask parent to show the embed
* url has the config as params
*/
function connectPreloadedEmbed({
async function connectPreloadedEmbed({
toBeThereParams,
toRemoveParams,
}: {
@@ -782,7 +695,7 @@ function connectPreloadedEmbed({
if (isBookerReady() && hasChanged) {
// Give some time for react to update state that might lead booker to go to slotsLoading state
waitForFrames = 5;
waitForFrames = 2;
}
// Booker might alreadyu be in slotsDone state. But we don't know if new getTeamSchedule request would intitiate or not. It would initiate when React updates the state but it might not go depending on if there is no actual state change in useSchedule components
@@ -790,17 +703,25 @@ function connectPreloadedEmbed({
// Firing this event would stop the loader and show the embed
// This causes loader to go away later.
runAsap(function tryToFireLinkReady() {
if (!isLinkReady() || waitForFrames > 0) {
waitForFrames--;
runAsap(tryToFireLinkReady);
return;
}
// link is ready now, so we could stop doing it.
// Also the page is visible to user now.
stopEnsuringQueryParamsInUrl();
sdkActionManager?.fire("linkReady", {});
await new Promise<void>((resolve) => {
runAsap(function tryToFireLinkReady() {
if (!isLinkReady({ embedStore }) || waitForFrames > 0) {
waitForFrames--;
runAsap(tryToFireLinkReady);
return;
}
// link is ready now, so we could stop doing it.
// Also the page is visible to user now.
stopEnsuringQueryParamsInUrl();
sdkActionManager?.fire("__connectCompleted", {});
sdkActionManager?.fire("linkReady", {});
resolve();
});
});
return {
stopEnsuringQueryParamsInUrl,
};
}
const isPrerendering = () => {
@@ -0,0 +1,118 @@
import type {
EmbedThemeConfig,
UiConfig,
EmbedNonStylesConfig,
EmbedStyles,
SetStyles,
setNonStylesConfig,
} from "../../types";
import { isParamValuePresentInUrlSearchParams } from "../../utils";
import { runAsap } from "./utils";
export const enum EMBED_IFRAME_STATE {
NOT_INITIALIZED,
INITIALIZED,
}
/**
* This is in-memory persistence needed so that when user browses through the embed, the configurations from the instructions aren't lost.
*/
export const embedStore = {
connectVersion: 0 as number,
/**
* Tracks whether the iframe is fully rendered or in progress of rendering.
* In case of prerendering as well as non-prerendering, it would be "completed" after the iframe is fully rendered.
*/
renderState: null as null | "inProgress" | "completed",
// Handles the commands of routing received from parent even when React hasn't initialized and nextRouter isn't available
router: {
/**
* When we do the history push, it is possible that
* - React might revert that change depending on in what state React is in while initializing
* - So, we use a declarative approach to ensure that our requirement is continuously met
*/
ensureQueryParamsInUrl({
toBeThereParams,
toRemoveParams,
}: {
toBeThereParams: Record<string, string | string[]>;
toRemoveParams: string[];
}) {
let stopUpdating = false;
function updateIfNeeded() {
if (stopUpdating) {
return { hasChanged: false };
}
const currentUrl = new URL(document.URL);
let hasChanged = false;
// Ensuring toBeThereSearchParams
for (const [key, newValue] of Object.entries(toBeThereParams)) {
// It checks that the value must be present and if an array no other item should be there except those in newValue
hasChanged = !isParamValuePresentInUrlSearchParams({
param: key,
value: newValue,
container: currentUrl.searchParams,
});
if (hasChanged) {
setParamInUrl({ key, value: newValue, url: currentUrl });
}
}
removeParamsFromUrl({ keys: toRemoveParams, url: currentUrl });
hasChanged = hasChanged || toRemoveParams.length > 0;
if (hasChanged) {
// Avoid unnecessary history push
window.history.replaceState({}, "", currentUrl.toString());
}
runAsap(updateIfNeeded);
return {
hasChanged,
};
}
const { hasChanged } = updateIfNeeded();
return {
stopEnsuringQueryParamsInUrl: () => {
stopUpdating = true;
},
hasChanged,
};
function removeParamsFromUrl({ keys, url }: { keys: string[]; url: URL }) {
for (const key of keys) {
url.searchParams.delete(key);
}
}
function setParamInUrl({ key, value, url }: { key: string; value: string | string[]; url: URL }) {
// Reset and then set the new value, to ensure nothing else remains in value
url.searchParams.delete(key);
const newValueArray = Array.isArray(value) ? value : [value];
newValueArray.forEach((val) => {
url.searchParams.append(key, val);
});
}
},
},
state: EMBED_IFRAME_STATE.NOT_INITIALIZED,
// Store all embed styles here so that as and when new elements are mounted, styles can be applied to it.
styles: {} as EmbedStyles | undefined,
nonStyles: {} as EmbedNonStylesConfig | undefined,
namespace: null as string | null,
embedType: undefined as undefined | null | string,
// Store all React State setters here.
reactStylesStateSetters: {} as Record<keyof EmbedStyles, SetStyles>,
reactNonStylesStateSetters: {} as Record<keyof EmbedNonStylesConfig, setNonStylesConfig>,
// Embed can show itself only after this is set to true
parentInformedAboutContentHeight: false,
windowLoadEventFired: false,
setTheme: undefined as ((arg0: EmbedThemeConfig) => void) | undefined,
theme: undefined as UiConfig["theme"],
uiConfig: undefined as Omit<UiConfig, "styles" | "theme"> | undefined,
/**
* We maintain a list of all setUiConfig setters that are in use at the moment so that we can update all those components.
*/
setUiConfig: [] as ((arg0: UiConfig) => void)[],
};
@@ -0,0 +1,58 @@
export function runAsap(fn: (...arg: unknown[]) => void) {
// We don't use rAF because it runs slower in Safari plus doesn't run if the iframe is hidden sometimes
return setTimeout(fn, 50);
}
export function isBookerPage() {
return !!window._embedBookerState;
}
export function isBookerReady() {
return window._embedBookerState === "slotsDone";
}
/**
* It is important to be able to check realtime(instead of storing isLinkReady as a variable) if the link is ready, because there is a possibility that booker might have moved to non-ready state from ready state
*/
export function isLinkReady({ embedStore }: { embedStore: typeof import("./embedStore").embedStore }) {
if (!embedStore.parentInformedAboutContentHeight) {
return false;
}
if (isBookerPage()) {
// Let's wait for Booker to be ready before showing the embed
// It means that booker has loaded all its data and is ready to show
// TODO: We could try to mark the embed as ready earlier in this case not relying on document.readyState
return isBookerReady();
}
return true;
}
/**
* Moves the queuedFormResponse to the routingFormResponse record to mark it as an actual response now.
*/
export const recordResponseIfQueued = async (params: Record<string, string | string[]>) => {
const url = new URL(document.URL);
let routingFormResponseId: number | null = null;
const queuedFormResponseIdParam = url.searchParams.get("cal.queuedFormResponseId");
const queuedFormResponseId = queuedFormResponseIdParam;
if (!queuedFormResponseId) {
return null;
}
// form is formId and isn't acutal Form data
const { form: _1, ...actualFormData } = params;
const res = await fetch(`/api/routing-forms/queued-response`, {
method: "POST",
body: JSON.stringify({ queuedFormResponseId, params: actualFormData }),
});
if (!res.ok) {
return null;
}
const response = await res.json();
const formResponseId = response.data.formResponseId;
if (formResponseId) {
// Now we have the actual routingFormResponseId.
routingFormResponseId = formResponseId;
}
return routingFormResponseId;
};
+91 -7
View File
@@ -2,6 +2,10 @@ import "../test/__mocks__/windowMatchMedia";
import { describe, it, expect, beforeEach, vi, beforeAll } from "vitest";
import {
EMBED_MODAL_IFRAME_SLOT_STALE_TIME,
EMBED_MODAL_IFRAME_FORCE_RELOAD_THRESHOLD_MS,
} from "./constants";
import { submitResponseAndGetRoutingResult } from "./utils";
vi.mock("./tailwindCss", () => ({
@@ -339,6 +343,10 @@ describe("Cal", () => {
layout: modalArg.config.layout,
});
// Verify that the embedRenderStartTime and embedConfig are set, which are used by getNextActionForModal to decide if the modal should be reused or not
expect(calInstance.embedRenderStartTime).toBeGreaterThan(0);
expect(calInstance.embedConfig).toBeDefined();
expectIframeToHaveMatchingUrl({
element: modalBox,
expectedIframeUrlObject: {
@@ -347,6 +355,44 @@ describe("Cal", () => {
...modalArg.config,
prerender: "true",
embedType: "modal",
"cal.skipSlotsFetch": "true",
}),
origin: null,
},
});
});
it("should create modal having iframe with queueFormResponse=true param when prerendering headless router", () => {
const modalArg = {
...baseModalArgs,
calLink: "router?form=123&[email protected]",
config: {
...baseModalArgs.config,
"cal.embed.pageType": "doesntmatter",
},
calOrigin: null,
__prerender: true,
};
calInstance.api.modal(modalArg);
const modalBox = expectCalModalBoxToBeInDocument({
state: "prerendering",
pageType: modalArg.config["cal.embed.pageType"],
theme: modalArg.config.theme,
layout: modalArg.config.layout,
});
expectIframeToHaveMatchingUrl({
element: modalBox,
expectedIframeUrlObject: {
pathname: `${new URL(modalArg.calLink, "http://example.com").pathname}`,
searchParams: new URLSearchParams({
...modalArg.config,
prerender: "true",
embedType: "modal",
"cal.queueFormResponse": "true",
email: "[email protected]",
form: "123",
}),
origin: null,
},
@@ -433,7 +479,9 @@ describe("Cal", () => {
expect(calInstance.doInIframe).toHaveBeenCalledWith({
method: "connect",
arg: {
config: expectedConfigAfterPrefilling,
config: {
...expectedConfigAfterPrefilling,
},
params: {},
},
});
@@ -543,7 +591,7 @@ describe("Cal", () => {
pathname: `/${modalArg.calLink}`,
searchParams: new URLSearchParams({
...expectedConfig,
// It remains because internally we remove prerender=true in iframe
// It remains because internally we remove prerender=true in iframe - through connect flow
prerender: "true",
"cal.skipSlotsFetch": "true",
}),
@@ -554,7 +602,9 @@ describe("Cal", () => {
expect(calInstance.doInIframe).toHaveBeenCalledWith({
method: "connect",
arg: {
config: expectedConfigAfterPrefilling,
config: {
...expectedConfigAfterPrefilling,
},
params: {},
},
});
@@ -587,7 +637,9 @@ describe("Cal", () => {
},
expectedIframeUrlObject: {
pathname: `/${modalArg.calLink}`,
searchParams: new URLSearchParams(expectedConfigAfterPrefilling),
searchParams: new URLSearchParams({
...expectedConfigAfterPrefilling,
}),
origin: null,
},
});
@@ -683,7 +735,9 @@ describe("Cal", () => {
expect.objectContaining({
method: "connect",
arg: {
config: configWithPrefilledValues,
config: {
...configWithPrefilledValues,
},
params: {},
},
})
@@ -768,7 +822,9 @@ describe("Cal", () => {
},
expectedIframeUrlObject: {
pathname: headlessRouterRedirectUrlWithPathOnly,
searchParams: new URLSearchParams(configWithPrefilledValuesAndHeadlessRouterRedirectParams),
searchParams: new URLSearchParams({
...configWithPrefilledValuesAndHeadlessRouterRedirectParams,
}),
origin: null,
},
});
@@ -1062,7 +1118,7 @@ describe("Cal", () => {
...baseArgs,
stateData: {
...baseArgs.stateData,
previousEmbedRenderStartTime: Date.now() - 1000000, // Much older timestamp
previousEmbedRenderStartTime: Date.now() - EMBED_MODAL_IFRAME_FORCE_RELOAD_THRESHOLD_MS - 1, // Much older timestamp
embedRenderStartTime: Date.now(),
},
});
@@ -1158,5 +1214,33 @@ describe("Cal", () => {
const result = calInstance.getNextActionForModal(baseArgs);
expect(result).toBe("noAction");
});
it("should return connect-no-slots-fetch when reuseFully is true and slots are not stale", () => {
const result = calInstance.getNextActionForModal({
...baseArgs,
stateData: {
...baseArgs.stateData,
prerenderOptions: {
reuseFully: true,
},
},
});
expect(result).toBe("connect-no-slots-fetch");
});
it("should return connect when reuseFully is true but slots are stale", () => {
const result = calInstance.getNextActionForModal({
...baseArgs,
stateData: {
...baseArgs.stateData,
prerenderOptions: {
reuseFully: true,
},
previousEmbedRenderStartTime: Date.now() - EMBED_MODAL_IFRAME_SLOT_STALE_TIME - 1,
embedRenderStartTime: Date.now(),
},
});
expect(result).toBe("connect");
});
});
});
+146 -61
View File
@@ -51,6 +51,21 @@ type CalConfig = {
uiDebug?: boolean;
};
type ModalPrerenderOptions = {
slotsStaleTimeMs?: number;
iframeForceReloadThresholdMs?: number;
reuseFully?: boolean;
};
type ModalStateData = {
embedConfig: PrefillAndIframeAttrsConfigWithGuestAndColorScheme;
previousEmbedConfig: PrefillAndIframeAttrsConfigWithGuestAndColorScheme | null;
embedRenderStartTime: number;
previousEmbedRenderStartTime: number | null;
isConnectionInitiated: boolean;
prerenderOptions: ModalPrerenderOptions | null;
};
type InitArgConfig = Partial<CalConfig> & {
origin?: string;
};
@@ -309,7 +324,7 @@ export class Cal {
config?: PrefillAndIframeAttrsConfig;
calOrigin: string | null;
}) {
log("Loading in iframe", calLink);
log("Loading in iframe", calLink, "with config", JSON.stringify(config));
iframe.dataset.calLink = calLink;
const calConfig = this.getCalConfig();
const { iframeAttrs, ...queryParamsFromConfig } = config;
@@ -522,13 +537,7 @@ export class Cal {
}: {
modal: { uid: string };
pathWithQueryToLoad: string;
stateData: {
embedConfig: PrefillAndIframeAttrsConfig;
previousEmbedConfig: PrefillAndIframeAttrsConfig | null;
isConnectionInitiated: boolean;
previousEmbedRenderStartTime: number | null;
embedRenderStartTime: number;
};
stateData: ModalStateData;
}) {
const {
embedConfig,
@@ -536,6 +545,7 @@ export class Cal {
isConnectionInitiated,
previousEmbedRenderStartTime,
embedRenderStartTime,
prerenderOptions,
} = stateData;
const calConfig = this.getCalConfig();
const lastLoadedUrlInIframeObject = this.getLastLoadedLinkInframe();
@@ -570,43 +580,59 @@ export class Cal {
? embedRenderStartTime - previousEmbedRenderStartTime
: 0;
const crossedReloadThreshold = previousEmbedRenderStartTime
? timeSinceLastRender > EMBED_MODAL_IFRAME_FORCE_RELOAD_THRESHOLD_MS
? timeSinceLastRender >
(prerenderOptions?.iframeForceReloadThresholdMs ?? EMBED_MODAL_IFRAME_FORCE_RELOAD_THRESHOLD_MS)
: false;
const areSlotsStale = previousEmbedRenderStartTime
? timeSinceLastRender > EMBED_MODAL_IFRAME_SLOT_STALE_TIME
? timeSinceLastRender > (prerenderOptions?.slotsStaleTimeMs ?? EMBED_MODAL_IFRAME_SLOT_STALE_TIME)
: false;
// Note that we don't worry about change in embed config because that is passed on as query params to the iframe and that is already supported by "connect" flow
const isResetNeeded = !isSameCalLink || isInFailedState || crossedReloadThreshold;
const actionToTake = isResetNeeded
? "fullReload"
: !isSameConfig || !areSameQueryParams || !isConnectionInitiated || areSlotsStale
? "connect"
: "noAction";
const getActionToTake = () => {
if (isResetNeeded) {
return "fullReload";
}
log("Next Modal Action:", actionToTake, {
path: {
isSame: isSameCalLink,
urlToLoadPath,
lastLoadedPathInIframe,
},
config: {
isSame: isSameConfig,
previousEmbedConfig,
embedConfig,
},
queryParams: {
isSame: areSameQueryParams,
lastLoadedUrlInIframeObjectSearchParams,
urlToLoadObjectSearchParams,
},
areSlotsStale,
crossedReloadThreshold,
isInFailedState,
isConnectionInitiated,
});
if (prerenderOptions?.reuseFully && !areSlotsStale) {
return "connect-no-slots-fetch";
}
if (!isSameConfig || !areSameQueryParams || !isConnectionInitiated || areSlotsStale) {
return "connect";
}
return "noAction";
};
const actionToTake = getActionToTake();
log(
"Next Modal Action:",
{ actionToTake, prerenderOptions },
{
path: {
isSame: isSameCalLink,
urlToLoadPath,
lastLoadedPathInIframe,
},
config: {
isSame: isSameConfig,
previousEmbedConfig,
embedConfig,
},
queryParams: {
isSame: areSameQueryParams,
lastLoadedUrlInIframeObjectSearchParams,
urlToLoadObjectSearchParams,
},
areSlotsStale,
crossedReloadThreshold,
isInFailedState,
isConnectionInitiated,
}
);
return actionToTake;
@@ -665,13 +691,7 @@ export class Cal {
}: {
modal: { uid: string; element: Element; calOrigin: string | null };
calLinkUrlObject: URL;
stateData: {
embedConfig: PrefillAndIframeAttrsConfigWithGuestAndColorScheme;
previousEmbedConfig: PrefillAndIframeAttrsConfigWithGuestAndColorScheme | null;
embedRenderStartTime: number;
previousEmbedRenderStartTime: number | null;
isConnectionInitiated: boolean;
};
stateData: ModalStateData;
}) {
const { uid: modalBoxUid, element: modalEl, calOrigin: _calOrigin } = modal;
const { embedConfig } = stateData;
@@ -755,6 +775,7 @@ class CalApi {
static initializedNamespaces = [] as string[];
modalUid?: string;
prerenderedModalUid?: string;
prerenderOptions?: ModalPrerenderOptions;
constructor(cal: Cal) {
this.cal = cal;
}
@@ -946,12 +967,27 @@ class CalApi {
config = {},
calOrigin,
__prerender = false,
prerenderOptions = {},
}: {
calLink: string;
config?: PrefillAndIframeAttrsConfig;
calOrigin?: string;
__prerender?: boolean;
prerenderOptions?: ModalPrerenderOptions;
}) {
const calConfig = this.cal.getCalConfig();
// Clone so that it doesn't mutate the original config
config = { ...config };
// calOrigin could have been passed as empty string by the user
calOrigin = calOrigin || calConfig.calOrigin;
const calLinkUrlObject = new URL(calLink, calOrigin);
const isHeadlessRouterPath = calLinkUrlObject ? isRouterPath(calLinkUrlObject.toString()) : false;
if (__prerender && this.cal.modalBox) {
// If we are re-prerendering, we destroy the previous modalbox, allowing user to prerender as many times as they want
this.cal.modalBox.remove();
}
// `this.modalUid` is set in non-preload case(Temporarily not being-set)
// `this.prerenderedModalUid` is set for a modal created through "prerender"
const uid = this.modalUid || this.prerenderedModalUid || String(Date.now()) || "0";
@@ -959,15 +995,24 @@ class CalApi {
const isConnectionInitiated = !!(this.modalUid && this.prerenderedModalUid);
const containerEl = document.body;
this.cal.isPrerendering = !!__prerender;
if (__prerender) {
// TODO: Make `reuseFully` a configurable param as well later.
// If someone's preloading the headless router path, we must reuse the iframe fully as is as Router would redirect to a Booking Page and that should be shown as is
this.prerenderOptions = { ...prerenderOptions, reuseFully: isHeadlessRouterPath };
// Add prerender query param
config.prerender = "true";
// When prerendering, we don't want to preload slots as they might be outdated anyway by the time they are used
// Also, when used with Headless Router attributes setup, we might endup fetching slots for a lot of people, which would be a waste and unnecessary load on Cal.com resources
config["cal.skipSlotsFetch"] = "true";
// If we are prerendering a headless router path, we don't want to record the response immediately.
if (isHeadlessRouterPath) {
config["cal.queueFormResponse"] = "true";
}
if (!this.prerenderOptions?.reuseFully) {
// When prerendering, we don't want to preload slots as they might be outdated anyway by the time they are used
// Also, when used with Headless Router attributes setup, we might endup fetching slots for a lot of people, which would be a waste and unnecessary load on Cal.com resources
config["cal.skipSlotsFetch"] = "true";
}
}
const configWithGuestKeyAndColorScheme = withColorScheme(
@@ -978,22 +1023,17 @@ class CalApi {
containerEl
);
const calConfig = this.cal.getCalConfig();
// calOrigin could have been passed as empty string by the user
calOrigin = calOrigin || calConfig.calOrigin;
const previousEmbedRenderStartTime = this.cal.embedRenderStartTime;
const previousEmbedConfig = this.cal.embedConfig;
const embedRenderStartTime = Date.now();
const previousEmbedConfig = this.cal.embedConfig;
const previousEmbedRenderStartTime = this.cal.embedRenderStartTime;
this.cal.embedRenderStartTime = embedRenderStartTime;
this.cal.embedConfig = configWithGuestKeyAndColorScheme;
const existingModalEl = document.querySelector(`cal-modal-box[uid="${uid}"]`);
// isConnectionPossible
if (!!existingModalEl && !!this.cal.iframe) {
const calLinkUrlObject = new URL(calLink, calOrigin);
const isHeadlessRouterPath = calLinkUrlObject ? isRouterPath(calLinkUrlObject.toString()) : false;
log(`Trying to reuse modal ${uid}`);
const stateData = {
embedConfig: configWithGuestKeyAndColorScheme,
@@ -1001,8 +1041,11 @@ class CalApi {
embedRenderStartTime,
previousEmbedRenderStartTime,
isConnectionInitiated,
prerenderOptions: this.prerenderOptions ?? null,
};
if (isHeadlessRouterPath) {
// If we want to reuse fully then we shouldn't submit response again
if (isHeadlessRouterPath && !this.prerenderOptions?.reuseFully) {
// Immediately take it to loading state. Either through connect or through loadInIframe, it would later be updated
existingModalEl.setAttribute("state", "loading");
@@ -1021,6 +1064,10 @@ class CalApi {
});
if (actionToTake === "noAction") {
if (__prerender) {
// A prerender instruction can never show the modal
return;
}
log(`Reopening modal without any other action needed ${uid}`);
// Reopen the modal, nothing else to do
existingModalEl.setAttribute("state", "reopened");
@@ -1039,11 +1086,18 @@ class CalApi {
iframe: this.cal.iframe,
config: configWithGuestKeyAndColorScheme,
});
} else if (actionToTake === "connect") {
} else if (actionToTake === "connect" || actionToTake === "connect-no-slots-fetch") {
this.cal.doInIframe({
method: "connect",
arg: {
config: configWithGuestKeyAndColorScheme,
config: {
...configWithGuestKeyAndColorScheme,
...(actionToTake === "connect-no-slots-fetch"
? {
"cal.embed.noSlotsFetchOnConnect": "true",
}
: {}),
},
params: fromEntriesWithDuplicateKeys(calLinkUrlObject.searchParams.entries()),
},
});
@@ -1052,7 +1106,6 @@ class CalApi {
// We reach here in case of connect or fullReload
this.modalUid = uid;
this.cal.embedRenderStartTime = embedRenderStartTime;
return;
}
@@ -1165,6 +1218,8 @@ class CalApi {
type?: "modal" | "floatingButton";
options?: {
prerenderIframe?: boolean;
slotsStaleTimeMs?: number;
iframeForceReloadThresholdMs?: number;
};
pageType?: EmbedPageType;
calOrigin?: string;
@@ -1198,7 +1253,8 @@ class CalApi {
}
const config = this.cal.getCalConfig();
let prerenderIframe = options.prerenderIframe;
const { prerenderIframe: prerenderIframeOption, ...prerenderOptions } = options;
let prerenderIframe = prerenderIframeOption;
if (type && prerenderIframe === undefined) {
prerenderIframe = true;
}
@@ -1214,6 +1270,7 @@ class CalApi {
calLink,
calOrigin: calOrigin || config.calOrigin,
__prerender: true,
prerenderOptions,
...(pageType ? { config: { "cal.embed.pageType": pageType } } : {}),
});
} else {
@@ -1225,22 +1282,50 @@ class CalApi {
}
}
/**
* Usecase - Prerender headless router path(i.e. `/router?form={FORM_ID}&param1=value1&......`)
*
* - Loads the headless router path in iframe hidden behind the scenes
* - Stores the response in a temporary queue at backend.
* - Redirects to appropriate booking page based on the Routing Rules
* - Loads the availability as per the team members identified by Routing - Attribute Rules
* - At this point, the booking page is ready to be used but is hidden behind the scenes
*
* A call to `modal` instruction(which automatically happens when an element with `data-cal-link` attribute is clicked) would then show this prerendered booking page sending a request `queued-response` that records the field values now as a response and connect it to the queued-response
*/
prerender({
calLink,
type,
pageType,
calOrigin,
options = {},
}: {
calLink: string;
type: "modal" | "floatingButton";
pageType?: EmbedPageType;
calOrigin?: string;
options?: {
/**
* Time in milliseconds after which the prerendered slots/availability should be considered stale and would be requested again when the modal is opened. This could slow down the booking page load by the time taken by slots loading request which shouldn't be too high
*
* Default value is 1 min
*/
slotsStaleTimeMs?: number;
/**
* Time in milliseconds after which the iframe would be forcefully reloaded when the modal is opened and thus booking page load could slow down drastically showing the skeleton loader in the meantime
* To avoid reaching this threshold, the user could prerender before this time is reached in usecases where prerender has been done long time ago.
*
* Default value is 15 mins
*/
iframeForceReloadThresholdMs?: number;
};
}) {
this.preload({
calLink,
type,
pageType,
calOrigin,
options,
});
}
@@ -22,6 +22,8 @@ export type EventDataMap = {
};
};
linkReady: Record<string, never>;
__connectInitiated: Record<string, never>;
__connectCompleted: Record<string, never>;
bookingSuccessfulV2: {
uid: string | undefined;
title: string | undefined;
+5
View File
@@ -67,6 +67,8 @@ export type KnownConfig = {
// Prefixing with cal.embed because there could be more query params that aren't required by embed and are used for things like prefilling booking form, configuring dry run, and some other params simply to be forwarded to the booking success redirect URL.
// There are some cal. prefixed query params as well, not meant for embed specifically, but in general for cal.com
"cal.embed.pageType"?: EmbedPageType;
// If true, then when doing a "connect" with pre-rendered iframe, we won't fetch slots. This is useful when we are reusing the iframe fully as is.
"cal.embed.noSlotsFetchOnConnect"?: "true" | "false";
};
export type EmbedBookerState =
@@ -97,3 +99,6 @@ export type PrefillAndIframeAttrsConfig = Record<string, string | string[] | Rec
id?: string;
};
} & KnownConfig;
export type SetStyles = React.Dispatch<React.SetStateAction<EmbedStyles>>;
export type setNonStylesConfig = React.Dispatch<React.SetStateAction<EmbedNonStylesConfig>>;