Skip to content

#1 PDF Application on GitHub that lets you edit PDFs on any device anywhere

Fix Calendly scheduler: blank on first open + slow load (#7075)

ConnorYoh50c0f2bcb512
diff --git a/frontend/editor/public/locales/en-US/translation.toml b/frontend/editor/public/locales/en-US/translation.toml
index 4bacc1b22a..d1fc247e2f 100644
--- a/frontend/editor/public/locales/en-US/translation.toml
+++ b/frontend/editor/public/locales/en-US/translation.toml
@@ -7837,6 +7837,7 @@ viewInvoice = "View & pay invoice"
[portal.procurement.schedule]
fallback = "Couldn't load the scheduler."
fallbackLink = "Open scheduling in a new tab"
+loading = "Loading scheduler..."
subtitle = "Your solutions engineer will walk your team through the rollout. Pick a time that suits you."
title = "Schedule a call"
diff --git a/frontend/editor/src/core/utils/scriptLoader.test.ts b/frontend/editor/src/core/utils/scriptLoader.test.ts
new file mode 100644
index 0000000000..9fce749d56
--- /dev/null
+++ b/frontend/editor/src/core/utils/scriptLoader.test.ts
@@ -0,0 +1,86 @@
+import { describe, it, expect } from "vitest";
+import { loadScript, isScriptLoaded } from "@app/utils/scriptLoader";
+
+/** jsdom doesn't fetch external scripts, so we drive the load/error events ourselves. */
+function scriptEl(id: string): HTMLScriptElement {
+ const el = document.getElementById(id) as HTMLScriptElement | null;
+ if (!el) throw new Error(`no script tag #${id}`);
+ return el;
+}
+
+describe("loadScript", () => {
+ it("overlapping loads share one tag and resolve only after the script actually loads", async () => {
+ const id = "test-script-overlap";
+ const src = "https://example.test/overlap.js";
+
+ let firstResolved = false;
+ let secondResolved = false;
+ const p1 = loadScript({ src, id }).then(() => {
+ firstResolved = true;
+ });
+ // Second, overlapping call (e.g. a StrictMode double-effect or a remount before the
+ // first load settled). It must reuse the in-flight load, not resolve on tag existence.
+ const p2 = loadScript({ src, id }).then(() => {
+ secondResolved = true;
+ });
+
+ // Only one tag despite two calls.
+ expect(document.querySelectorAll(`#${id}`)).toHaveLength(1);
+
+ // Regression guard: before the script executes, neither promise resolves — previously
+ // the second call resolved immediately because the tag existed, so callers ran before
+ // the script's globals were defined (the "blank until you reopen" bug).
+ await Promise.resolve();
+ expect(firstResolved).toBe(false);
+ expect(secondResolved).toBe(false);
+ expect(isScriptLoaded(id)).toBe(false);
+
+ scriptEl(id).dispatchEvent(new Event("load"));
+ await Promise.all([p1, p2]);
+ expect(firstResolved).toBe(true);
+ expect(secondResolved).toBe(true);
+ expect(isScriptLoaded(id)).toBe(true);
+ });
+
+ it("resolves immediately once the script has already loaded", async () => {
+ const id = "test-script-cached";
+ const src = "https://example.test/cached.js";
+
+ const first = loadScript({ src, id });
+ scriptEl(id).dispatchEvent(new Event("load"));
+ await first;
+
+ // A later call must resolve from cache without waiting for a fresh load event (which
+ // would never come) and without adding a second tag.
+ await loadScript({ src, id });
+ expect(document.querySelectorAll(`#${id}`)).toHaveLength(1);
+ });
+
+ it("rejects when the script fails to load", async () => {
+ const id = "test-script-error";
+ const src = "https://example.test/error.js";
+
+ const p = loadScript({ src, id });
+ scriptEl(id).dispatchEvent(new Event("error"));
+ await expect(p).rejects.toThrow(/Failed to load script/);
+ });
+
+ it("drops the failed tag so a retry re-attempts instead of hanging", async () => {
+ const id = "test-script-retry";
+ const src = "https://example.test/retry.js";
+
+ // First attempt (e.g. a warm-up) fails.
+ const first = loadScript({ src, id });
+ scriptEl(id).dispatchEvent(new Event("error"));
+ await expect(first).rejects.toThrow(/Failed to load script/);
+ // The poisoned tag must be gone — otherwise a retry would attach to a dead tag.
+ expect(document.querySelectorAll(`#${id}`)).toHaveLength(0);
+
+ // Retry (e.g. the modal opening) creates a fresh tag and can now succeed.
+ const second = loadScript({ src, id });
+ expect(document.querySelectorAll(`#${id}`)).toHaveLength(1);
+ scriptEl(id).dispatchEvent(new Event("load"));
+ await expect(second).resolves.toBeUndefined();
+ expect(isScriptLoaded(id)).toBe(true);
+ });
+});
diff --git a/frontend/editor/src/core/utils/scriptLoader.ts b/frontend/editor/src/core/utils/scriptLoader.ts
index 60c9c02ec8..58179c4b91 100644
--- a/frontend/editor/src/core/utils/scriptLoader.ts
+++ b/frontend/editor/src/core/utils/scriptLoader.ts
@@ -11,6 +11,11 @@ interface ScriptLoadOptions {
}
const loadedScripts = new Set<string>();
+// Loads that have started but not yet finished, keyed by script id/src. Overlapping
+// callers (e.g. a React StrictMode double-effect, or a component that remounts before
+// the previous load settled) reuse the same promise so they all resolve only when the
+// script has actually executed — never on tag existence alone.
+const pendingScripts = new Map<string, Promise<void>>();
export function loadScript({
src,
@@ -19,43 +24,75 @@ export function loadScript({
defer = false,
onLoad,
}: ScriptLoadOptions): Promise<void> {
- return new Promise((resolve, reject) => {
- // Check if already loaded
- const scriptId = id || src;
- if (loadedScripts.has(scriptId)) {
- resolve();
- return;
- }
+ const scriptId = id || src;
+
+ // Already fully loaded and executed.
+ if (loadedScripts.has(scriptId)) {
+ onLoad?.();
+ return Promise.resolve();
+ }
+
+ // A load for the same script is already in flight — wait for it rather than kicking
+ // off a second one (and, critically, don't resolve just because the tag is present).
+ const inFlight = pendingScripts.get(scriptId);
+ if (inFlight) {
+ return onLoad ? inFlight.then(() => onLoad()) : inFlight;
+ }
- // Check if script already exists in DOM
- const existingScript = id
- ? document.getElementById(id)
- : document.querySelector(`script[src="${src}"]`);
- if (existingScript) {
+ const promise = new Promise<void>((resolve, reject) => {
+ const settleLoaded = (script: HTMLScriptElement) => {
+ script.dataset.loaded = "true";
loadedScripts.add(scriptId);
+ pendingScripts.delete(scriptId);
+ onLoad?.();
resolve();
+ };
+ const settleError = (el: HTMLScriptElement) => {
+ pendingScripts.delete(scriptId);
+ // Drop the failed tag so a later retry (e.g. the modal after a warm-up that was
+ // blocked by an extension) creates a fresh one and re-attempts, rather than
+ // attaching to a dead tag whose error event won't fire again and hanging forever.
+ el.remove();
+ reject(new Error(`Failed to load script: ${src}`));
+ };
+
+ // A matching tag may already be in the DOM (added by an earlier load whose Set/Map
+ // state was lost, or injected elsewhere). If our own loader finished it, the
+ // data-loaded flag is set and we can resolve immediately; otherwise attach to its
+ // load lifecycle instead of assuming it is ready.
+ const existing = (
+ id
+ ? document.getElementById(id)
+ : document.querySelector(`script[src="${src}"]`)
+ ) as HTMLScriptElement | null;
+ if (existing) {
+ if (existing.dataset.loaded === "true") {
+ loadedScripts.add(scriptId);
+ onLoad?.();
+ resolve();
+ return;
+ }
+ existing.addEventListener("load", () => settleLoaded(existing), {
+ once: true,
+ });
+ existing.addEventListener("error", () => settleError(existing), {
+ once: true,
+ });
return;
}
- // Create and append script
const script = document.createElement("script");
script.src = src;
if (id) script.id = id;
script.async = async;
script.defer = defer;
-
- script.onload = () => {
- loadedScripts.add(scriptId);
- if (onLoad) onLoad();
- resolve();
- };
-
- script.onerror = () => {
- reject(new Error(`Failed to load script: ${src}`));
- };
-
+ script.addEventListener("load", () => settleLoaded(script), { once: true });
+ script.addEventListener("error", () => settleError(script), { once: true });
document.head.appendChild(script);
});
+
+ pendingScripts.set(scriptId, promise);
+ return promise;
}
export function isScriptLoaded(idOrSrc: string): boolean {
diff --git a/frontend/editor/src/portal/components/procurement/CalendlyInline.tsx b/frontend/editor/src/portal/components/procurement/CalendlyInline.tsx
index 3cac3750fb..794cadac9a 100644
--- a/frontend/editor/src/portal/components/procurement/CalendlyInline.tsx
+++ b/frontend/editor/src/portal/components/procurement/CalendlyInline.tsx
@@ -1,11 +1,15 @@
import { useEffect, useRef, useState } from "react";
import { useTranslation } from "react-i18next";
+import { Spinner } from "@app/ui";
import { loadScript } from "@app/utils/scriptLoader";
/**
* Inline Calendly scheduler. Lazily loads Calendly's widget.js (only once the embed mounts, i.e. when
- * the modal opens) and initialises an inline widget. Falls back to a plain "open in a new tab" link if
- * the script can't load (offline, blocked, etc.).
+ * the modal opens) and initialises an inline widget. Shows a spinner while the (external, sometimes
+ * slow) script loads, and falls back to a plain "open in a new tab" link if the script can't load
+ * (offline, blocked, etc.). A real load failure fires the script's error event, so the fallback is
+ * shown immediately rather than after a fixed timeout — a slow-but-working connection is never
+ * abandoned, it just spins until the widget arrives.
*/
const CALENDLY_SCRIPT = "https://assets.calendly.com/assets/external/widget.js";
@@ -40,6 +44,36 @@ function buildUrl(base: string): string {
return `${base}${sep}hide_event_type_details=1&background_color=${WIDGET_COLORS.background}&text_color=${WIDGET_COLORS.text}&primary_color=${WIDGET_COLORS.primary}`;
}
+// Origins the embed fetches from: the widget script, then the scheduler iframe.
+const CALENDLY_ORIGINS = [
+ "https://assets.calendly.com",
+ "https://calendly.com",
+];
+
+function preconnect(origin: string): void {
+ if (typeof document === "undefined") return;
+ if (document.querySelector(`link[rel="preconnect"][href="${origin}"]`))
+ return;
+ const link = document.createElement("link");
+ link.rel = "preconnect";
+ link.href = origin;
+ link.crossOrigin = "anonymous";
+ document.head.appendChild(link);
+}
+
+/**
+ * Warm the Calendly embed ahead of use: open connections to its origins and start fetching
+ * widget.js, so opening the scheduler initialises near-instantly instead of paying a cold
+ * script + iframe fetch on click. Idempotent and safe to call repeatedly; failures are left
+ * for the modal's own load to surface as the fallback link.
+ */
+export function warmCalendly(): void {
+ CALENDLY_ORIGINS.forEach(preconnect);
+ void loadScript({ src: CALENDLY_SCRIPT, id: "calendly-widget-script" }).catch(
+ () => {},
+ );
+}
+
export function CalendlyInline({
url = CALENDLY_URL,
height = 760,
@@ -53,17 +87,25 @@ export function CalendlyInline({
const { t } = useTranslation();
const containerRef = useRef<HTMLDivElement>(null);
const [failed, setFailed] = useState(false);
+ const [loading, setLoading] = useState(true);
const fullUrl = buildUrl(url);
useEffect(() => {
let cancelled = false;
setFailed(false);
+ setLoading(true);
loadScript({ src: CALENDLY_SCRIPT, id: "calendly-widget-script" })
.then(() => {
const el = containerRef.current;
const calendly = (window as CalendlyWindow).Calendly;
- if (cancelled || !el || !calendly) return;
+ if (cancelled || !el) return;
+ // Script resolved but the global never materialised (blocked/altered by an
+ // extension, etc.) — show the fallback link rather than an empty modal.
+ if (!calendly) {
+ setFailed(true);
+ return;
+ }
// Re-init explicitly (rather than relying on widget.js auto-scan) so the widget rebuilds on
// reopen and whenever the URL or prefill changes.
el.innerHTML = "";
@@ -72,6 +114,7 @@ export function CalendlyInline({
parentElement: el,
prefill: email ? { email } : undefined,
});
+ setLoading(false);
})
.catch(() => !cancelled && setFailed(true));
return () => {
@@ -91,10 +134,14 @@ export function CalendlyInline({
}
return (
- <div
- ref={containerRef}
- className="portal-calendly"
- style={{ minWidth: 320, height }}
- />
+ <div className="portal-calendly" style={{ minWidth: 320, height }}>
+ {loading && (
+ <div className="portal-calendly__loading">
+ <Spinner size="lg" label={t("portal.procurement.schedule.loading")} />
+ </div>
+ )}
+ {/* Calendly injects its iframe here; the spinner overlays until the widget is initialised. */}
+ <div ref={containerRef} className="portal-calendly__embed" />
+ </div>
);
}
diff --git a/frontend/editor/src/portal/components/procurement/DealStatusHero.tsx b/frontend/editor/src/portal/components/procurement/DealStatusHero.tsx
index e2a3e19687..092e259bb3 100644
--- a/frontend/editor/src/portal/components/procurement/DealStatusHero.tsx
+++ b/frontend/editor/src/portal/components/procurement/DealStatusHero.tsx
@@ -1,3 +1,4 @@
+import { useEffect } from "react";
import { useTranslation } from "react-i18next";
import { Button } from "@app/ui";
import type { ViewId } from "@portal/contexts/ViewContext";
@@ -6,6 +7,7 @@ import {
type ProcurementSnapshot,
} from "@portal/api/procurement";
import { StageStepper } from "@portal/components/procurement/StageStepper";
+import { warmCalendly } from "@portal/components/procurement/CalendlyInline";
import "@portal/views/Procurement.css";
/**
@@ -38,6 +40,13 @@ export function DealStatusHero({
onNavigate: (view: ViewId) => void;
}) {
const { t } = useTranslation();
+
+ // Warm Calendly's connections + widget script as soon as the "Schedule a call" action is
+ // available, so opening the scheduler initialises quickly instead of paying a cold fetch.
+ useEffect(() => {
+ if (canSchedule) warmCalendly();
+ }, [canSchedule]);
+
const stage = snapshot.stage ?? "trial";
const inTrial = stage === "trial";
const cta =
diff --git a/frontend/editor/src/portal/views/Procurement.css b/frontend/editor/src/portal/views/Procurement.css
index adc21fd79a..f733b2c5a3 100644
--- a/frontend/editor/src/portal/views/Procurement.css
+++ b/frontend/editor/src/portal/views/Procurement.css
@@ -1396,11 +1396,27 @@
/* Calendly scheduler embed (Schedule a call). The widget is always light (Calendly renders inputs on
white), so give it a white surface — it reads as a clean card even inside the dark-mode modal. */
.portal-calendly {
+ position: relative;
border-radius: 10px;
overflow: hidden;
background: #ffffff;
}
+/* Fills the surface; Calendly injects its iframe in here. */
+.portal-calendly__embed {
+ height: 100%;
+}
+
+/* Centred spinner shown over the white surface until the widget initialises. */
+.portal-calendly__loading {
+ position: absolute;
+ inset: 0;
+ display: flex;
+ align-items: center;
+ justify-content: center;
+ pointer-events: none;
+}
+
/* ── Agreement (security) step ────────────────────────────────────────────── */
.portal-agreement__doc {
margin: 1rem 0;