Skip to content

armgit / Cap

Public Imported from GitHub
0

Open source Loom alternative. Beautiful, shareable screen recordings.

feat: add Pro call to action buttons to shareable videos (#2349)

Richie McIlroyb2b6ae45d4ca
diff --git a/apps/web/__tests__/unit/embed-playback-speed.test.ts b/apps/web/__tests__/unit/embed-playback-speed.test.ts
index ef1b41d2a..c6a497733 100644
--- a/apps/web/__tests__/unit/embed-playback-speed.test.ts
+++ b/apps/web/__tests__/unit/embed-playback-speed.test.ts
@@ -1,8 +1,8 @@
import { Context, Effect } from "effect";
import { isValidElement, type ReactElement } from "react";
-import { describe, expect, it, vi } from "vitest";
+import { beforeEach, describe, expect, it, vi } from "vitest";
-const mocks = vi.hoisted(() => ({ select: vi.fn() }));
+const mocks = vi.hoisted(() => ({ select: vi.fn(), ownerIsPro: true }));
vi.mock("@cap/database", () => ({ db: () => ({ select: mocks.select }) }));
vi.mock("@cap/database/auth/session", () => ({
@@ -12,8 +12,9 @@ vi.mock("@cap/env", () => ({
buildEnv: { NEXT_PUBLIC_WEB_URL: "https://cap.so" },
}));
vi.mock("@cap/ui", () => ({ Logo: () => null }));
-vi.mock("@cap/utils", () => ({ userIsPro: () => true }));
+vi.mock("@cap/utils", () => ({ userIsPro: () => mocks.ownerIsPro }));
vi.mock("@cap/web-backend", () => ({
+ ImageUploads: Context.GenericTag("EmbedTestImages"),
VideosPolicy: Context.GenericTag("EmbedTestPolicy"),
provideOptionalAuth: <A, E, R>(effect: Effect.Effect<A, E, R>) => effect,
resolveEffectiveVideoRules: () => ({ settings: {} }),
@@ -21,6 +22,9 @@ vi.mock("@cap/web-backend", () => ({
vi.mock("@/lib/server", () => ({
runPromise: <A, E>(effect: Effect.Effect<A, E, unknown>) =>
effect.pipe(
+ Effect.provideService(Context.GenericTag("EmbedTestImages"), {
+ resolveImageUrl: (url: string) => Effect.succeed(url),
+ }),
Effect.provideService(Context.GenericTag("EmbedTestPolicy"), {
canView: () => Effect.void,
}),
@@ -49,8 +53,10 @@ async function renderEmbed(
const video = {
id: "video",
ownerId: "owner",
- settings:
- videoSpeed === undefined ? null : { defaultPlaybackSpeed: videoSpeed },
+ settings: {
+ defaultPlaybackSpeed: videoSpeed,
+ callToAction: { label: "Book a call", url: "https://example.com/" },
+ },
orgSettings:
orgSpeed === undefined ? null : { defaultPlaybackSpeed: orgSpeed },
transcriptionStatus: "COMPLETE",
@@ -81,10 +87,35 @@ async function renderEmbed(
}
return (await (content.type as (props: unknown) => Promise<unknown>)(
content.props,
- )) as ReactElement<{ defaultPlaybackSpeed?: number; minimal: boolean }>;
+ )) as ReactElement<{
+ defaultPlaybackSpeed?: number;
+ minimal: boolean;
+ callToAction: { label: string; url: string } | null;
+ }>;
}
describe("embed default playback speed", () => {
+ beforeEach(() => {
+ mocks.ownerIsPro = true;
+ });
+
+ it.each([
+ { ownerIsPro: false, minimal: false },
+ { ownerIsPro: true, minimal: false },
+ { ownerIsPro: true, minimal: true },
+ ])("gates saved calls to action: %j", async ({ ownerIsPro, minimal }) => {
+ mocks.ownerIsPro = ownerIsPro;
+ const embed = await renderEmbed(undefined, undefined, minimal);
+ if (ownerIsPro && !minimal) {
+ expect(embed.props.callToAction).toMatchObject({
+ label: "Book a call",
+ url: "https://example.com/",
+ });
+ } else {
+ expect(embed.props.callToAction).toBeNull();
+ }
+ });
+
it.each([
{ name: "organization 1×", video: undefined, org: 1, expected: 1 },
{ name: "video override", video: 1.5, org: 1, expected: 1.5 },
diff --git a/apps/web/__tests__/unit/share-call-to-action.test.ts b/apps/web/__tests__/unit/share-call-to-action.test.ts
new file mode 100644
index 000000000..7570eec0c
--- /dev/null
+++ b/apps/web/__tests__/unit/share-call-to-action.test.ts
@@ -0,0 +1,283 @@
+import { describe, expect, it } from "vitest";
+import {
+ CORNER_CARD_MIN_WIDTH,
+ callToActionDestinationLabel,
+ DEFAULT_CTA_COLOR,
+ normalizeCallToActionUrl,
+ normalizeHexColor,
+ parseShareCallToAction,
+ readableTextColor,
+ type ShareCallToAction,
+ shouldShowCornerCard,
+ toStoredCallToAction,
+ validateCallToAction,
+} from "@/lib/share-call-to-action";
+
+describe("normalizeCallToActionUrl", () => {
+ it("adds https to bare domains", () => {
+ expect(normalizeCallToActionUrl("cal.com/demo")).toBe(
+ "https://cal.com/demo",
+ );
+ expect(normalizeCallToActionUrl(" example.com ")).toBe(
+ "https://example.com/",
+ );
+ });
+
+ it("treats a bare host with a port as a web link", () => {
+ expect(normalizeCallToActionUrl("cap.so:8080/demo")).toBe(
+ "https://cap.so:8080/demo",
+ );
+ });
+
+ it("keeps explicit http and https links", () => {
+ expect(normalizeCallToActionUrl("http://example.com/a?b=1#c")).toBe(
+ "http://example.com/a?b=1#c",
+ );
+ expect(normalizeCallToActionUrl("https://example.com/demo")).toBe(
+ "https://example.com/demo",
+ );
+ });
+
+ it("accepts mailto links with a real address", () => {
+ expect(normalizeCallToActionUrl("mailto:[email protected]")).toBe(
+ "mailto:[email protected]",
+ );
+ expect(normalizeCallToActionUrl("mailto:nobody")).toBeNull();
+ expect(normalizeCallToActionUrl("mailto:hello%[email protected]")).toBeNull();
+ });
+
+ it("rejects script and data schemes", () => {
+ expect(normalizeCallToActionUrl("javascript:alert(1)")).toBeNull();
+ expect(normalizeCallToActionUrl("JavaScript:alert(1)")).toBeNull();
+ expect(
+ normalizeCallToActionUrl("data:text/html,<script>1</script>"),
+ ).toBeNull();
+ expect(normalizeCallToActionUrl("vbscript:msgbox")).toBeNull();
+ expect(normalizeCallToActionUrl("file:///etc/passwd")).toBeNull();
+ });
+
+ it("rejects hosts without a dot, whitespace and embedded credentials", () => {
+ expect(normalizeCallToActionUrl("book")).toBeNull();
+ expect(normalizeCallToActionUrl("https://localhost:3000")).toBeNull();
+ expect(normalizeCallToActionUrl("example .com")).toBeNull();
+ expect(normalizeCallToActionUrl("https://user:[email protected]")).toBeNull();
+ expect(normalizeCallToActionUrl("")).toBeNull();
+ });
+
+ it("rejects links over the length limit", () => {
+ expect(
+ normalizeCallToActionUrl(`https://example.com/${"a".repeat(2100)}`),
+ ).toBeNull();
+ });
+});
+
+describe("normalizeHexColor", () => {
+ it("normalizes short and long hex values", () => {
+ expect(normalizeHexColor("#abc")).toBe("#AABBCC");
+ expect(normalizeHexColor("12a150")).toBe("#12A150");
+ expect(normalizeHexColor(" #7a4dff ")).toBe("#7A4DFF");
+ });
+
+ it("rejects anything that is not a hex color", () => {
+ expect(normalizeHexColor("red")).toBeNull();
+ expect(normalizeHexColor("#12345")).toBeNull();
+ expect(normalizeHexColor("url(evil)")).toBeNull();
+ expect(normalizeHexColor(42)).toBeNull();
+ });
+});
+
+describe("validateCallToAction", () => {
+ it("returns a normalized call to action", () => {
+ expect(
+ validateCallToAction({
+ label: " Book a call ",
+ url: "cal.com/demo",
+ headline: " Want a walkthrough? ",
+ color: "#12a150",
+ showWhilePlaying: false,
+ }),
+ ).toEqual({
+ ok: true,
+ value: {
+ label: "Book a call",
+ url: "https://cal.com/demo",
+ headline: "Want a walkthrough?",
+ color: "#12A150",
+ showWhilePlaying: false,
+ },
+ });
+ });
+
+ it("defaults the optional fields", () => {
+ const result = validateCallToAction({
+ label: "Try it",
+ url: "example.com",
+ });
+ expect(result).toEqual({
+ ok: true,
+ value: {
+ label: "Try it",
+ url: "https://example.com/",
+ headline: null,
+ color: DEFAULT_CTA_COLOR,
+ showWhilePlaying: true,
+ },
+ });
+ });
+
+ it("reports every invalid field", () => {
+ const result = validateCallToAction({
+ label: " ",
+ url: "javascript:alert(1)",
+ headline: "x".repeat(81),
+ });
+ expect(result.ok).toBe(false);
+ if (result.ok) return;
+ expect(Object.keys(result.errors).sort()).toEqual([
+ "headline",
+ "label",
+ "url",
+ ]);
+ });
+
+ it("rejects labels over the limit and missing links", () => {
+ const result = validateCallToAction({ label: "x".repeat(41), url: "" });
+ expect(result.ok).toBe(false);
+ if (result.ok) return;
+ expect(result.errors.label).toBeDefined();
+ expect(result.errors.url).toBeDefined();
+ });
+});
+
+describe("parseShareCallToAction", () => {
+ it("reads a stored call to action from video settings", () => {
+ expect(
+ parseShareCallToAction({
+ disableComments: true,
+ callToAction: {
+ label: "Book a call",
+ url: "https://cal.com/demo",
+ color: "#2F6BFF",
+ showWhilePlaying: true,
+ },
+ }),
+ ).toEqual({
+ label: "Book a call",
+ url: "https://cal.com/demo",
+ headline: null,
+ color: "#2F6BFF",
+ showWhilePlaying: true,
+ });
+ });
+
+ it("ignores missing, malformed and unsafe stored values", () => {
+ expect(parseShareCallToAction(null)).toBeNull();
+ expect(parseShareCallToAction({})).toBeNull();
+ expect(parseShareCallToAction({ callToAction: "Book" })).toBeNull();
+ expect(
+ parseShareCallToAction({ callToAction: { label: "Go", url: 5 } }),
+ ).toBeNull();
+ expect(
+ parseShareCallToAction({
+ callToAction: { label: "Go", url: "javascript:alert(1)" },
+ }),
+ ).toBeNull();
+ });
+
+ it("round-trips through the stored shape", () => {
+ const result = validateCallToAction({
+ label: "Reply to me",
+ url: "mailto:[email protected]",
+ headline: "Questions?",
+ color: "#E5337A",
+ showWhilePlaying: false,
+ });
+ if (!result.ok) throw new Error("expected valid input");
+ expect(
+ parseShareCallToAction({
+ callToAction: toStoredCallToAction(result.value),
+ }),
+ ).toEqual(result.value);
+ });
+
+ it("omits an empty headline from the stored shape", () => {
+ const stored = toStoredCallToAction({
+ label: "Go",
+ url: "https://example.com/",
+ headline: null,
+ color: DEFAULT_CTA_COLOR,
+ showWhilePlaying: true,
+ });
+ expect(stored).not.toHaveProperty("headline");
+ });
+});
+
+describe("readableTextColor", () => {
+ it("picks white on dark colors and ink on light colors", () => {
+ expect(readableTextColor("#2F6BFF")).toBe("#FFFFFF");
+ expect(readableTextColor("#111113")).toBe("#FFFFFF");
+ expect(readableTextColor("#FFE14D")).toBe("#111113");
+ expect(readableTextColor("#FFFFFF")).toBe("#111113");
+ });
+});
+
+describe("callToActionDestinationLabel", () => {
+ it("shows the host or email address", () => {
+ expect(callToActionDestinationLabel("https://www.cal.com/demo")).toBe(
+ "cal.com",
+ );
+ expect(callToActionDestinationLabel("mailto:[email protected]")).toBe(
+ );
+ });
+});
+
+describe("shouldShowCornerCard", () => {
+ const cta: ShareCallToAction = {
+ label: "Book a call",
+ url: "https://cal.com/demo",
+ headline: null,
+ color: DEFAULT_CTA_COLOR,
+ showWhilePlaying: true,
+ };
+ const visible = {
+ cta,
+ width: 960,
+ height: 540,
+ dismissed: false,
+ pastIntro: true,
+ ended: false,
+ };
+
+ it("shows on a large player once playback is underway", () => {
+ expect(shouldShowCornerCard(visible)).toBe(true);
+ });
+
+ it("stays hidden on small players", () => {
+ expect(
+ shouldShowCornerCard({
+ ...visible,
+ width: CORNER_CARD_MIN_WIDTH - 1,
+ }),
+ ).toBe(false);
+ expect(shouldShowCornerCard({ ...visible, width: 390, height: 219 })).toBe(
+ false,
+ );
+ expect(shouldShowCornerCard({ ...visible, height: 200 })).toBe(false);
+ });
+
+ it("stays hidden before the intro, after dismissal and at the end", () => {
+ expect(shouldShowCornerCard({ ...visible, pastIntro: false })).toBe(false);
+ expect(shouldShowCornerCard({ ...visible, dismissed: true })).toBe(false);
+ expect(shouldShowCornerCard({ ...visible, ended: true })).toBe(false);
+ });
+
+ it("respects the owner turning the corner card off", () => {
+ expect(
+ shouldShowCornerCard({
+ ...visible,
+ cta: { ...cta, showWhilePlaying: false },
+ }),
+ ).toBe(false);
+ });
+});
diff --git a/apps/web/__tests__/unit/share-page-loading.test.ts b/apps/web/__tests__/unit/share-page-loading.test.ts
index ecae39305..30dd23513 100644
--- a/apps/web/__tests__/unit/share-page-loading.test.ts
+++ b/apps/web/__tests__/unit/share-page-loading.test.ts
@@ -10,6 +10,7 @@ const mocks = vi.hoisted(() => ({
quota: vi.fn(),
user: vi.fn(),
authenticated: false,
+ ownerIsPro: false,
sharedOrganizations: [] as {
id: string;
name: string;
@@ -24,7 +25,7 @@ vi.mock("@cap/env", () => ({
serverEnv: () => ({}),
}));
vi.mock("@cap/ui", () => ({ Logo: () => null }));
-vi.mock("@cap/utils", () => ({ userIsPro: () => false }));
+vi.mock("@cap/utils", () => ({ userIsPro: () => mocks.ownerIsPro }));
vi.mock("@cap/web-backend", () => ({
Database: Context.GenericTag("ShareTestDatabase"),
ImageUploads: Context.GenericTag("ShareTestImages"),
@@ -120,6 +121,9 @@ const createVideo = () => ({
activeUploadRawFileKey: null as string | null,
organizationTombstoneAt: null as Date | null,
metadata: null,
+ videoSettings: {
+ callToAction: { label: "Book a call", url: "https://example.com/" },
+ },
transcriptionStatus: "COMPLETE",
createdAt: new Date("2026-09-01T00:00:00.000Z"),
updatedAt: new Date("2026-09-01T00:00:00.000Z"),
@@ -161,7 +165,11 @@ async function renderAuthorizedContent() {
children: ReactElement<{
initialPlaybackUrl?: Promise<string | null>;
screenshotImageUrl?: string | null;
- data: { sharedOrganizations: unknown[]; ownerIsOverShareLimit: boolean };
+ data: {
+ sharedOrganizations: unknown[];
+ ownerIsOverShareLimit: boolean;
+ callToAction: { label: string; url: string } | null;
+ };
}>;
}>;
}
@@ -176,10 +184,27 @@ describe("share page loading", () => {
mocks.quota.mockResolvedValue(false);
mocks.user.mockResolvedValue(null);
mocks.authenticated = false;
+ mocks.ownerIsPro = false;
mocks.sharedOrganizations = [];
arrangeRows([createVideo()]);
});
+ it.each([false, true])(
+ "serves a saved call to action only when the owner has Pro: %s",
+ async (ownerIsPro) => {
+ mocks.ownerIsPro = ownerIsPro;
+ const content = await renderAuthorizedContent();
+ const callToAction = content.props.children.props.data.callToAction;
+ if (ownerIsPro) {
+ expect(callToAction).toMatchObject(
+ createVideo().videoSettings.callToAction,
+ );
+ } else {
+ expect(callToAction).toBeNull();
+ }
+ },
+ );
+
it("reuses the organization sharing query for the header and video data", async () => {
mocks.sharedOrganizations = [
{ id: "shared", organizationId: "shared", name: "Shared team" },
diff --git a/apps/web/__tests__/unit/video-call-to-action-action.test.ts b/apps/web/__tests__/unit/video-call-to-action-action.test.ts
new file mode 100644
index 000000000..eaa2fb05c
--- /dev/null
+++ b/apps/web/__tests__/unit/video-call-to-action-action.test.ts
@@ -0,0 +1,158 @@
+import { beforeEach, describe, expect, it, vi } from "vitest";
+
+const mocks = vi.hoisted(() => ({
+ user: null as {
+ id: string;
+ stripeSubscriptionStatus?: string | null;
+ thirdPartyStripeSubscriptionId?: string | null;
+ } | null,
+ video: null as { ownerId: string } | null,
+ updates: [] as unknown[],
+}));
+
+vi.mock("@cap/env", () => ({
+ buildEnv: { NEXT_PUBLIC_IS_CAP: true },
+}));
+
+vi.mock("@cap/database/auth/session", () => ({
+ getCurrentUser: async () => mocks.user,
+}));
+
+vi.mock("@cap/database", () => ({
+ db: () => ({
+ select: () => ({
+ from: () => ({
+ where: async () => (mocks.video ? [mocks.video] : []),
+ }),
+ }),
+ update: () => ({
+ set: (values: unknown) => ({
+ where: async () => {
+ mocks.updates.push(values);
+ },
+ }),
+ }),
+ }),
+}));
+
+import type { Video } from "@cap/web-domain";
+import { updateVideoCallToAction } from "@/actions/videos/call-to-action";
+
+const videoId = "video123" as Video.VideoId;
+
+const sqlText = (value: unknown): string => {
+ const chunks = (value as { queryChunks?: unknown[] }).queryChunks ?? [];
+ return chunks
+ .map((chunk) => {
+ if (typeof chunk === "string") return chunk;
+ if (chunk && typeof chunk === "object" && "value" in chunk) {
+ const inner = (chunk as { value: unknown }).value;
+ return Array.isArray(inner) ? inner.join("") : String(inner);
+ }
+ return "?";
+ })
+ .join("");
+};
+
+describe("updateVideoCallToAction", () => {
+ beforeEach(() => {
+ mocks.user = { id: "owner", stripeSubscriptionStatus: "active" };
+ mocks.video = { ownerId: "owner" };
+ mocks.updates = [];
+ });
+
+ it("requires a signed-in user", async () => {
+ mocks.user = null;
+ await expect(
+ updateVideoCallToAction(videoId, { label: "Go", url: "example.com" }),
+ ).rejects.toThrow("Unauthorized");
+ expect(mocks.updates).toHaveLength(0);
+ });
+
+ it("only lets the owner change the call to action", async () => {
+ mocks.user = { id: "someone-else" };
+ await expect(
+ updateVideoCallToAction(videoId, { label: "Go", url: "example.com" }),
+ ).rejects.toThrow("permission");
+ expect(mocks.updates).toHaveLength(0);
+ });
+
+ it("returns field errors without writing invalid input", async () => {
+ const result = await updateVideoCallToAction(videoId, {
+ label: "",
+ url: "javascript:alert(1)",
+ });
+ expect(result.success).toBe(false);
+ if (result.success) return;
+ expect(result.errors.label).toBeDefined();
+ expect(result.errors.url).toBeDefined();
+ expect(mocks.updates).toHaveLength(0);
+ });
+
+ it.each([null, "canceled", "unpaid", "incomplete_expired"])(
+ "requires an upgrade for an owner with subscription status %s",
+ async (stripeSubscriptionStatus) => {
+ mocks.user = { id: "owner", stripeSubscriptionStatus };
+ for (const input of [{ label: "Go", url: "example.com" }, null]) {
+ await expect(updateVideoCallToAction(videoId, input)).resolves.toEqual({
+ success: false,
+ errors: {},
+ upgradeRequired: true,
+ });
+ }
+ expect(mocks.updates).toHaveLength(0);
+ },
+ );
+
+ it.each([
+ { stripeSubscriptionStatus: "active" },
+ { stripeSubscriptionStatus: "trialing" },
+ { stripeSubscriptionStatus: "past_due" },
+ { thirdPartyStripeSubscriptionId: "sub_example_seat" },
+ ])("allows an entitled Pro owner: %j", async (entitlement) => {
+ mocks.user = { id: "owner", ...entitlement };
+ const result = await updateVideoCallToAction(videoId, {
+ label: "Go",
+ url: "example.com",
+ });
+ expect(result.success).toBe(true);
+ expect(mocks.updates).toHaveLength(1);
+ });
+
+ it("stores the normalized call to action under settings", async () => {
+ const result = await updateVideoCallToAction(videoId, {
+ label: "Book a call",
+ url: "cal.com/demo",
+ color: "#12a150",
+ showWhilePlaying: false,
+ });
+ expect(result).toEqual({
+ success: true,
+ callToAction: {
+ label: "Book a call",
+ url: "https://cal.com/demo",
+ headline: null,
+ color: "#12A150",
+ showWhilePlaying: false,
+ },
+ });
+ expect(mocks.updates).toHaveLength(1);
+ const settings = sqlText(
+ (mocks.updates[0] as { settings: unknown }).settings,
+ );
+ expect(settings).toContain("JSON_MERGE_PATCH(");
+ expect(settings).toContain('"callToAction":null');
+ expect(settings).toContain('"url":"https://cal.com/demo"');
+ });
+
+ it("removes only the call to action key", async () => {
+ const result = await updateVideoCallToAction(videoId, null);
+ expect(result).toEqual({ success: true, callToAction: null });
+ const settings = sqlText(
+ (mocks.updates[0] as { settings: unknown }).settings,
+ );
+ expect(settings).toContain("JSON_MERGE_PATCH(");
+ expect(settings).toContain('{"callToAction":null}');
+ expect(settings).not.toContain('"url"');
+ });
+});
diff --git a/apps/web/__tests__/unit/video-settings-action.test.ts b/apps/web/__tests__/unit/video-settings-action.test.ts
new file mode 100644
index 000000000..abe6195df
--- /dev/null
+++ b/apps/web/__tests__/unit/video-settings-action.test.ts
@@ -0,0 +1,61 @@
+import { beforeEach, describe, expect, it, vi } from "vitest";
+
+const mocks = vi.hoisted(() => ({
+ updates: [] as unknown[],
+}));
+
+vi.mock("@cap/database/auth/session", () => ({
+ getCurrentUser: async () => ({ id: "owner" }),
+}));
+
+vi.mock("@cap/database", () => ({
+ db: () => ({
+ select: () => ({
+ from: () => ({
+ where: async () => [{ ownerId: "owner" }],
+ }),
+ }),
+ update: () => ({
+ set: (values: unknown) => ({
+ where: async () => {
+ mocks.updates.push(values);
+ },
+ }),
+ }),
+ }),
+}));
+
+import type { Video } from "@cap/web-domain";
+import { updateVideoSettings } from "@/actions/videos/settings";
+
+const patchOf = (value: unknown): Record<string, unknown> => {
+ const chunks = (value as { queryChunks?: unknown[] }).queryChunks ?? [];
+ const json = chunks.find(
+ (chunk): chunk is string =>
+ typeof chunk === "string" && chunk.startsWith("{"),
+ );
+ return JSON.parse(json ?? "{}");
+};
+
+describe("updateVideoSettings", () => {
+ beforeEach(() => {
+ mocks.updates = [];
+ });
+
+ it("merges only known viewer settings", async () => {
+ await updateVideoSettings(
+ "video" as Video.VideoId,
+ {
+ disableComments: true,
+ defaultPlaybackSpeed: 1.49,
+ callToAction: { label: "x", url: "javascript:alert(1)" },
+ } as Parameters<typeof updateVideoSettings>[1],
+ );
+
+ const settings = (mocks.updates[0] as { settings: unknown }).settings;
+ expect(patchOf(settings)).toEqual({
+ disableComments: true,
+ defaultPlaybackSpeed: 1.5,
+ });
+ });
+});
diff --git a/apps/web/actions/videos/call-to-action.ts b/apps/web/actions/videos/call-to-action.ts
new file mode 100644
index 000000000..e24c4b5ec
--- /dev/null
+++ b/apps/web/actions/videos/call-to-action.ts
@@ -0,0 +1,63 @@
+"use server";
+
+import { db } from "@cap/database";
+import { getCurrentUser } from "@cap/database/auth/session";
+import { videos } from "@cap/database/schema";
+import { userIsPro } from "@cap/utils";
+import type { Video } from "@cap/web-domain";
+import { and, eq, sql } from "drizzle-orm";
+import {
+ type CallToActionErrors,
+ type CallToActionInput,
+ type ShareCallToAction,
+ toStoredCallToAction,
+ validateCallToAction,
+} from "@/lib/share-call-to-action";
+
+export type UpdateVideoCallToActionResult =
+ | { success: true; callToAction: ShareCallToAction | null }
+ | { success: false; errors: CallToActionErrors; upgradeRequired?: true };
+
+export async function updateVideoCallToAction(
+ videoId: Video.VideoId,
+ input: CallToActionInput | null,
+): Promise<UpdateVideoCallToActionResult> {
+ const user = await getCurrentUser();
+ if (!user) throw new Error("Unauthorized");
+ if (!videoId) throw new Error("Missing video");
+
+ const [video] = await db()
+ .select({ ownerId: videos.ownerId })
+ .from(videos)
+ .where(eq(videos.id, videoId));
+
+ if (!video) throw new Error("Video not found");
+ if (video.ownerId !== user.id) {
+ throw new Error("You don't have permission to update this video");
+ }
+ if (!userIsPro(user)) {
+ return { success: false, errors: {}, upgradeRequired: true };
+ }
+
+ if (input === null) {
+ await db()
+ .update(videos)
+ .set({
+ settings: sql`JSON_MERGE_PATCH(COALESCE(${videos.settings}, JSON_OBJECT()), CAST('{"callToAction":null}' AS JSON))`,
+ })
+ .where(and(eq(videos.id, videoId), eq(videos.ownerId, user.id)));
+ return { success: true, callToAction: null };
+ }
+
+ const result = validateCallToAction(input);
+ if (!result.ok) return { success: false, errors: result.errors };
+
+ await db()
+ .update(videos)
+ .set({
+ settings: sql`JSON_MERGE_PATCH(JSON_MERGE_PATCH(COALESCE(${videos.settings}, JSON_OBJECT()), CAST('{"callToAction":null}' AS JSON)), CAST(${JSON.stringify({ callToAction: toStoredCallToAction(result.value) })} AS JSON))`,
+ })
+ .where(and(eq(videos.id, videoId), eq(videos.ownerId, user.id)));
+
+ return { success: true, callToAction: result.value };
+}
diff --git a/apps/web/actions/videos/settings.ts b/apps/web/actions/videos/settings.ts
index 05991069d..45bf6015e 100644
--- a/apps/web/actions/videos/settings.ts
+++ b/apps/web/actions/videos/settings.ts
@@ -4,9 +4,18 @@ import { db } from "@cap/database";
import { getCurrentUser } from "@cap/database/auth/session";
import { videos } from "@cap/database/schema";
import type { Video } from "@cap/web-domain";
-import { eq } from "drizzle-orm";
+import { eq, sql } from "drizzle-orm";
import { normalizePlaybackSpeed } from "@/lib/playback-speed";
+const VIEWER_SETTING_KEYS = [
+ "disableSummary",
+ "disableCaptions",
+ "disableChapters",
+ "disableReactions",
+ "disableTranscript",
+ "disableComments",
+] as const;
+
export async function updateVideoSettings(
videoId: Video.VideoId,
videoSettings: {
@@ -38,19 +47,22 @@ export async function updateVideoSettings(
throw new Error("You don't have permission to update this video settings");
}
- const settingsToSave =
- videoSettings.defaultPlaybackSpeed !== undefined
- ? {
- ...videoSettings,
- defaultPlaybackSpeed: normalizePlaybackSpeed(
- videoSettings.defaultPlaybackSpeed,
- ),
- }
- : videoSettings;
+ const settingsToSave: Record<string, boolean | number> = {};
+ for (const key of VIEWER_SETTING_KEYS) {
+ const value = videoSettings[key];
+ if (typeof value === "boolean") settingsToSave[key] = value;
+ }
+ if (videoSettings.defaultPlaybackSpeed !== undefined) {
+ settingsToSave.defaultPlaybackSpeed = normalizePlaybackSpeed(
+ videoSettings.defaultPlaybackSpeed,
+ );
+ }
await db()
.update(videos)
- .set({ settings: settingsToSave })
+ .set({
+ settings: sql`JSON_MERGE_PATCH(COALESCE(${videos.settings}, JSON_OBJECT()), CAST(${JSON.stringify(settingsToSave)} AS JSON))`,
+ })
.where(eq(videos.id, videoId));
return { success: true };
diff --git a/apps/web/app/embed/[videoId]/_components/EmbedVideo.tsx b/apps/web/app/embed/[videoId]/_components/EmbedVideo.tsx
index 1de2d817c..4339c337f 100644
--- a/apps/web/app/embed/[videoId]/_components/EmbedVideo.tsx
+++ b/apps/web/app/embed/[videoId]/_components/EmbedVideo.tsx
@@ -29,6 +29,7 @@ import {
type TranscriptEntry,
} from "@/app/s/[videoId]/_components/utils/transcript-utils";
import type { SharePageBranding } from "@/lib/share-branding";
+import type { ShareCallToAction } from "@/lib/share-call-to-action";
import { usePlayerJsReceiver } from "./use-player-js-receiver";
declare global {
@@ -68,6 +69,7 @@ export const EmbedVideo = forwardRef<
defaultPlaybackSpeed?: number;
viewerSettings?: ViewerSettings | null;
showPlaybackStatusBadge?: boolean;
+ callToAction?: ShareCallToAction | null;
}
>(
(
@@ -85,6 +87,7 @@ export const EmbedVideo = forwardRef<
defaultPlaybackSpeed,
viewerSettings,
showPlaybackStatusBadge = false,
+ callToAction = null,
},
ref,
) => {
@@ -281,6 +284,7 @@ export const EmbedVideo = forwardRef<
defaultPlaybackSpeed={defaultPlaybackSpeed}
enableCrossOrigin={enableCrossOrigin}
hasActiveUpload={data.hasActiveUpload}
+ callToAction={callToAction}
/>
) : (
<HLSVideoPlayer
@@ -296,6 +300,7 @@ export const EmbedVideo = forwardRef<
defaultPlaybackSpeed={defaultPlaybackSpeed}
hasActiveUpload={data.hasActiveUpload}
isLiveSegments={isSegmentsSource}
+ callToAction={callToAction}
/>
)}
</div>
diff --git a/apps/web/app/embed/[videoId]/page.tsx b/apps/web/app/embed/[videoId]/page.tsx
index 0361e5d59..bb19036f3 100644
--- a/apps/web/app/embed/[videoId]/page.tsx
+++ b/apps/web/app/embed/[videoId]/page.tsx
@@ -30,6 +30,7 @@ import { notFound } from "next/navigation";
import { resolveDefaultPlaybackSpeed } from "@/lib/playback-speed";
import * as EffectRuntime from "@/lib/server";
import { getSharePageBranding } from "@/lib/share-branding";
+import { parseShareCallToAction } from "@/lib/share-call-to-action";
import { buildShareVideoMetadata } from "@/lib/share-video-metadata";
import { isVideoOverShareableLinkLimit } from "@/lib/shareable-link-quota";
import { transcribeVideo } from "@/lib/transcribe";
@@ -410,6 +411,11 @@ async function EmbedContent({
)}
viewerSettings={rules.settings}
showPlaybackStatusBadge={user?.id === video.ownerId}
+ callToAction={
+ ownerIsProUser && !minimal
+ ? parseShareCallToAction(video.settings)
+ : null
+ }
/>
);
}
diff --git a/apps/web/app/s/[videoId]/Share.tsx b/apps/web/app/s/[videoId]/Share.tsx
index 70cb174d8..23b690293 100644
--- a/apps/web/app/s/[videoId]/Share.tsx
+++ b/apps/web/app/s/[videoId]/Share.tsx
@@ -1001,6 +1001,7 @@ export const Share = ({
recordingStopped={recordingStopped}
defaultPlaybackSpeed={defaultPlaybackSpeed}
viewerIsOwner={viewerId === data.owner.id}
+ callToAction={data.callToAction}
ref={playerRef}
/>
)}
diff --git a/apps/web/app/s/[videoId]/_components/CapVideoPlayer.tsx b/apps/web/app/s/[videoId]/_components/CapVideoPlayer.tsx
index 64f24887d..8c2ea4628 100644
--- a/apps/web/app/s/[videoId]/_components/CapVideoPlayer.tsx
+++ b/apps/web/app/s/[videoId]/_components/CapVideoPlayer.tsx
@@ -14,7 +14,9 @@ import { useCallback, useEffect, useRef, useState } from "react";
import { createPortal } from "react-dom";
import { toast } from "sonner";
import { retryVideoProcessing } from "@/actions/video/retry-processing";
+import type { ShareCallToAction } from "@/lib/share-call-to-action";
import CommentStamp from "./CommentStamp";
+import { CallToActionOverlay } from "./call-to-action/CallToActionOverlay";
import { bindCaptionTrackCueText } from "./caption-tracks";
import { resolveInitialPlaybackUrl } from "./initial-playback-url";
import {
@@ -140,6 +142,7 @@ interface Props {
showPlaybackStatusBadge?: boolean;
showFloatingVolumeControl?: boolean;
onUploadComplete?: () => void;
+ callToAction?: ShareCallToAction | null;
}
export function CapVideoPlayer({
@@ -178,6 +181,7 @@ export function CapVideoPlayer({
showPlaybackStatusBadge = false,
showFloatingVolumeControl = false,
onUploadComplete,
+ callToAction = null,
}: Props) {
const [currentCue, setCurrentCue] = useState<string>("");
const [controlsVisible, setControlsVisible] = useState(false);
@@ -885,6 +889,17 @@ export function CapVideoPlayer({
!showUploadFailureOverlay &&
!showPlaybackResolutionError && <MediaPlayerError />}
<MediaPlayerVolumeIndicator />
+ {callToAction &&
+ videoLoaded &&
+ !hasActiveProgress &&
+ !showUploadFailureOverlay &&
+ !showPlaybackResolutionError && (
+ <CallToActionOverlay
+ cta={callToAction}
+ videoId={videoId}
+ controlsDocked={externalTimeline && controlsPortalEl !== null}
+ />
+ )}
{showFloatingVolumeControl &&
videoLoaded &&
!showUploadFailureOverlay &&
diff --git a/apps/web/app/s/[videoId]/_components/HLSVideoPlayer.tsx b/apps/web/app/s/[videoId]/_components/HLSVideoPlayer.tsx
index b3acd0863..1917ddb3c 100644
--- a/apps/web/app/s/[videoId]/_components/HLSVideoPlayer.tsx
+++ b/apps/web/app/s/[videoId]/_components/HLSVideoPlayer.tsx
@@ -16,6 +16,8 @@ import { useCallback, useEffect, useRef, useState } from "react";
import { createPortal } from "react-dom";
import { toast } from "sonner";
import { retryVideoProcessing } from "@/actions/video/retry-processing";
+import type { ShareCallToAction } from "@/lib/share-call-to-action";
+import { CallToActionOverlay } from "./call-to-action/CallToActionOverlay";
import { bindCaptionTrackCueText } from "./caption-tracks";
import { scheduleReadyRefresh } from "./deferred-ready-refresh";
import { waitForSegmentPlayback } from "./segment-playback-probe";
@@ -124,6 +126,7 @@ interface Props {
* timeline strip replaces the seek slider, everything else comes along.
*/
controlsPortalEl?: HTMLElement | null;
+ callToAction?: ShareCallToAction | null;
}
export function HLSVideoPlayer({
@@ -153,6 +156,7 @@ export function HLSVideoPlayer({
previewMode,
externalTimeline = false,
controlsPortalEl = null,
+ callToAction = null,
}: Props) {
const hlsInstance = useRef<Hls | null>(null);
const [currentCue, setCurrentCue] = useState<string>("");
@@ -823,6 +827,18 @@ export function HLSVideoPlayer({
<MediaPlayerLoading />
<MediaPlayerError />
<MediaPlayerVolumeIndicator />
+ {callToAction &&
+ videoLoaded &&
+ !hasActiveProgress &&
+ !hasFailedOrError &&
+ !hlsInitFailed &&
+ !isBackgroundPreview && (
+ <CallToActionOverlay
+ cta={callToAction}
+ videoId={videoId}
+ controlsDocked={externalTimeline && controlsPortalEl !== null}
+ />
+ )}
{(() => {
// Docked: the bar renders into the timeline deck's slot through a
// portal. Same tree, same store; only where it paints changes. The
diff --git a/apps/web/app/s/[videoId]/_components/ShareHeader.tsx b/apps/web/app/s/[videoId]/_components/ShareHeader.tsx
index 37d76f03b..bdaee84ae 100644
--- a/apps/web/app/s/[videoId]/_components/ShareHeader.tsx
+++ b/apps/web/app/s/[videoId]/_components/ShareHeader.tsx
@@ -32,6 +32,7 @@ import {
Globe2,
LayoutDashboard,
Lock,
+ MousePointer2,
Pencil,
Scissors,
Users,
@@ -106,6 +107,13 @@ const PasswordDialog = dynamic(
const DeleteCapDialog = dynamic(() => import("./DeleteCapDialog"), {
ssr: false,
});
+const CallToActionDialog = dynamic(
+ () =>
+ import("./call-to-action/CallToActionDialog").then(
+ (m) => m.CallToActionDialog,
+ ),
+ { ssr: false },
+);
const DuplicateCapMenuItem = dynamic(() => import("./DuplicateCapMenuItem"), {
ssr: false,
});
@@ -203,6 +211,8 @@ export const ShareHeader = ({
const [settingsDialogMounted, setSettingsDialogMounted] = useState(false);
const [passwordDialogMounted, setPasswordDialogMounted] = useState(false);
const [deleteDialogMounted, setDeleteDialogMounted] = useState(false);
+ const [ctaDialogMounted, setCtaDialogMounted] = useState(false);
+ const [isCtaDialogOpen, setIsCtaDialogOpenRaw] = useState(false);
const [isSettingsDialogOpen, setIsSettingsDialogOpenRaw] = useState(false);
const [isPasswordDialogOpen, setIsPasswordDialogOpenRaw] = useState(false);
const [isDeleteDialogOpen, setIsDeleteDialogOpenRaw] = useState(false);
@@ -226,6 +236,10 @@ export const ShareHeader = ({
if (open) setDeleteDialogMounted(true);
setIsDeleteDialogOpenRaw(open);
};
+ const setIsCtaDialogOpen = (open: boolean) => {
+ if (open) setCtaDialogMounted(true);
+ setIsCtaDialogOpenRaw(open);
+ };
const [passwordProtected, setPasswordProtected] = useState(
Boolean(data.hasPassword),
);
@@ -805,6 +819,16 @@ export const ShareHeader = ({
onPasswordUpdated={handlePasswordUpdated}
/>
)}
+ {ctaDialogMounted && (
+ <CallToActionDialog
+ open={isCtaDialogOpen}
+ onOpenChange={setIsCtaDialogOpen}
+ videoId={data.id}
+ callToAction={data.callToAction ?? null}
+ onSaved={refresh}
+ onUpgradeRequest={() => setUpgradeModalOpen(true)}
+ />
+ )}
{deleteDialogMounted && (
<DeleteCapDialog
open={isDeleteDialogOpen}
@@ -1108,6 +1132,29 @@ export const ShareHeader = ({
<FontAwesomeIcon className="size-3" icon={faGear} />
<p className="text-sm text-gray-12">Video settings</p>
</DropdownMenuItem>
+ <DropdownMenuItem
+ onClick={() => {
+ if (!data.owner.isPro) setUpgradeModalOpen(true);
+ else setIsCtaDialogOpen(true);
+ }}
+ className="flex items-center gap-2 rounded-lg"
+ >
+ <MousePointer2 className="size-3.5" />
+ <p className="text-sm text-gray-12">
+ {data.callToAction
+ ? "Edit call to action"
+ : "Add call to action"}
+ </p>
+ {!data.owner.isPro ? (
+ <span className="ml-auto pl-3 text-xs text-gray-10">
+ Pro
+ </span>
+ ) : data.callToAction ? (
+ <span className="ml-auto pl-3 text-xs text-gray-10">
+ On
+ </span>
+ ) : null}
+ </DropdownMenuItem>
<DropdownMenuItem
onClick={() => {
if (!user.isPro) setUpgradeModalOpen(true);
diff --git a/apps/web/app/s/[videoId]/_components/ShareVideo.tsx b/apps/web/app/s/[videoId]/_components/ShareVideo.tsx
index 5f6dd0ab8..ac4e0917a 100644
--- a/apps/web/app/s/[videoId]/_components/ShareVideo.tsx
+++ b/apps/web/app/s/[videoId]/_components/ShareVideo.tsx
@@ -21,6 +21,7 @@ import {
import { finalizeDesktopSegmentsRecording } from "@/actions/video/finalize-desktop-segments";
import { Tooltip } from "@/components/Tooltip";
import { isRetryableDesktopSegmentsFinalizationError } from "@/lib/desktop-segments-retryable-errors";
+import type { ShareCallToAction } from "@/lib/share-call-to-action";
import type { VideoData } from "../types";
import { type CaptionLanguage, useCaptionContext } from "./CaptionContext";
import {
@@ -99,6 +100,7 @@ export const ShareVideo = forwardRef<
recordingStopped?: boolean;
defaultPlaybackSpeed?: number;
viewerIsOwner?: boolean;
+ callToAction?: ShareCallToAction | null;
}
>(
(
@@ -121,6 +123,7 @@ export const ShareVideo = forwardRef<
recordingStopped = false,
defaultPlaybackSpeed,
viewerIsOwner = false,
+ callToAction = null,
},
ref,
) => {
@@ -578,6 +581,7 @@ export const ShareVideo = forwardRef<
liveVttContent != null
}
canRetryProcessing={canRetryProcessing}
+ callToAction={callToAction}
/>
) : (
<HLSVideoPlayer
@@ -611,6 +615,7 @@ export const ShareVideo = forwardRef<
liveVttContent != null
}
canRetryProcessing={canRetryProcessing}
+ callToAction={callToAction}
/>
)}
{showFinalizeRecordingControl && (
diff --git a/apps/web/app/s/[videoId]/_components/call-to-action/CallToActionDialog.tsx b/apps/web/app/s/[videoId]/_components/call-to-action/CallToActionDialog.tsx
new file mode 100644
index 000000000..fc891fdfb
--- /dev/null
+++ b/apps/web/app/s/[videoId]/_components/call-to-action/CallToActionDialog.tsx
@@ -0,0 +1,767 @@
+"use client";
+
+import { Dialog, DialogContent, DialogTitle, Switch } from "@cap/ui";
+import type { Video } from "@cap/web-domain";
+import clsx from "clsx";
+import { Check, Link2, MousePointer2, Pipette, Play, X } from "lucide-react";
+import { AnimatePresence, motion } from "motion/react";
+import {
+ type ReactNode,
+ useEffect,
+ useId,
+ useMemo,
+ useRef,
+ useState,
+} from "react";
+import { toast } from "sonner";
+import { updateVideoCallToAction } from "@/actions/videos/call-to-action";
+import {
+ type CallToActionErrors,
+ CTA_COLOR_PRESETS,
+ CTA_HEADLINE_MAX_LENGTH,
+ CTA_LABEL_MAX_LENGTH,
+ CTA_LABEL_SUGGESTIONS,
+ DEFAULT_CTA_COLOR,
+ normalizeCallToActionUrl,
+ normalizeHexColor,
+ type ShareCallToAction,
+ validateCallToAction,
+} from "@/lib/share-call-to-action";
+import {
+ CallToActionCornerCard,
+ CallToActionEndScreen,
+} from "./CallToActionSurfaces";
+
+type PreviewMode = "end" | "playing";
+
+type FormState = {
+ label: string;
+ url: string;
+ headline: string;
+ color: string;
+ showWhilePlaying: boolean;
+};
+
+const EMPTY_FORM: FormState = {
+ label: "",
+ url: "",
+ headline: "",
+ color: DEFAULT_CTA_COLOR,
+ showWhilePlaying: true,
+};
+
+const PREVIEW_PLACEHOLDER_LABEL = "Book a call";
+
+function formFromCallToAction(cta: ShareCallToAction | null): FormState {
+ if (!cta) return EMPTY_FORM;
+ return {
+ label: cta.label,
+ url: cta.url,
+ headline: cta.headline ?? "",
+ color: cta.color,
+ showWhilePlaying: cta.showWhilePlaying,
+ };
+}
+
+function useVideoThumbnail(videoId: Video.VideoId, enabled: boolean) {
+ const [thumbnail, setThumbnail] = useState<string | null>(null);
+
+ useEffect(() => {
+ if (!enabled) return;
+ const controller = new AbortController();
+ fetch(`/api/thumbnail?videoId=${encodeURIComponent(videoId)}`, {
+ signal: controller.signal,
+ })
+ .then((response) => (response.ok ? response.json() : null))
+ .then((body: unknown) => {
+ if (
+ body &&
+ typeof body === "object" &&
+ "screen" in body &&
+ typeof body.screen === "string"
+ ) {
+ setThumbnail(body.screen);
+ }
+ })
+ .catch(() => {});
+ return () => controller.abort();
+ }, [enabled, videoId]);
+
+ return thumbnail;
+}
+
+export function CallToActionDialog({
+ open,
+ onOpenChange,
+ videoId,
+ callToAction,
+ onSaved,
+ onUpgradeRequest,
+}: {
+ open: boolean;
+ onOpenChange: (open: boolean) => void;
+ videoId: Video.VideoId;
+ callToAction: ShareCallToAction | null;
+ onSaved?: (callToAction: ShareCallToAction | null) => void;
+ onUpgradeRequest: () => void;
+}) {
+ const [form, setForm] = useState<FormState>(() =>
+ formFromCallToAction(callToAction),
+ );
+ const [errors, setErrors] = useState<CallToActionErrors>({});
+ const [touched, setTouched] = useState<Record<string, boolean>>({});
+ const [previewMode, setPreviewMode] = useState<PreviewMode>("end");
+ const [pending, setPending] = useState<"save" | "remove" | null>(null);
+ const labelInputRef = useRef<HTMLInputElement>(null);
+ const thumbnail = useVideoThumbnail(videoId, open);
+ const ids = {
+ label: useId(),
+ url: useId(),
+ headline: useId(),
+ playing: useId(),
+ form: useId(),
+ };
+
+ const wasOpenRef = useRef(false);
+ useEffect(() => {
+ const opening = open && !wasOpenRef.current;
+ wasOpenRef.current = open;
+ if (!opening) return;
+ setForm(formFromCallToAction(callToAction));
+ setErrors({});
+ setTouched({});
+ setPreviewMode("end");
+ setPending(null);
+ }, [open, callToAction]);
+
+ const liveErrors = useMemo(() => {
+ const result = validateCallToAction(form);
+ return result.ok ? {} : result.errors;
+ }, [form]);
+
+ const visibleError = (field: keyof CallToActionErrors) =>
+ errors[field] ?? (touched[field] ? liveErrors[field] : undefined);
+
+ const previewCta: ShareCallToAction = {
+ label: form.label.trim() || PREVIEW_PLACEHOLDER_LABEL,
+ url: normalizeCallToActionUrl(form.url) ?? "https://cap.so",
+ headline: form.headline.trim() || null,
+ color: normalizeHexColor(form.color) ?? DEFAULT_CTA_COLOR,
+ showWhilePlaying: form.showWhilePlaying,
+ };
+
+ const update = <K extends keyof FormState>(key: K, value: FormState[K]) => {
+ setForm((previous) => ({ ...previous, [key]: value }));
+ if (key in errors) {
+ setErrors((previous) => ({ ...previous, [key]: undefined }));
+ }
+ };
+
+ const markTouched = (field: string) =>
+ setTouched((previous) => ({ ...previous, [field]: true }));
+
+ const isEditing = callToAction !== null;
+ const busy = pending !== null;
+
+ const handleSave = async () => {
+ const result = validateCallToAction(form);
+ if (!result.ok) {
+ setErrors(result.errors);
+ setTouched({ label: true, url: true, headline: true });
+ return;
+ }
+ setPending("save");
+ try {
+ const response = await updateVideoCallToAction(videoId, form);
+ if (!response.success) {
+ if (response.upgradeRequired) {
+ onOpenChange(false);
+ onUpgradeRequest();
+ return;
+ }
+ setErrors(response.errors);
+ return;
+ }
+ toast.success(
+ isEditing ? "Call to action updated" : "Call to action added",
+ );
+ onSaved?.(response.callToAction);
+ onOpenChange(false);
+ } catch {
+ toast.error("Couldn't save your call to action");
+ } finally {
+ setPending(null);
+ }
+ };
+
+ const handleRemove = async () => {
+ setPending("remove");
+ try {
+ const response = await updateVideoCallToAction(videoId, null);
+ if (!response.success) {
+ if (response.upgradeRequired) {
+ onOpenChange(false);
+ onUpgradeRequest();
+ } else {
+ toast.error("Couldn't remove your call to action");
+ }
+ return;
+ }
+ toast.success("Call to action removed");
+ onSaved?.(null);
+ onOpenChange(false);
+ } catch {
+ toast.error("Couldn't remove your call to action");
+ } finally {
+ setPending(null);
+ }
+ };
+
+ return (
+ <Dialog open={open} onOpenChange={(next) => !busy && onOpenChange(next)}>
+ <DialogContent
+ hideCloseButton
+ aria-describedby={undefined}
+ onOpenAutoFocus={(event) => {
+ event.preventDefault();
+ labelInputRef.current?.focus();
+ }}
+ className="flex max-h-[calc(100dvh-2rem)] w-[calc(100vw-2rem)] max-w-[920px] flex-col overflow-hidden rounded-2xl border border-gray-4 bg-gray-1 md:flex-row"
+ >
+ <section className="relative flex shrink-0 flex-col gap-4 border-b border-gray-4 bg-gray-2 p-5 md:w-[54%] md:border-b-0 md:border-r md:p-6">
+ <div className="flex items-center justify-between gap-3">
+ <p className="text-xs font-medium text-gray-10">Preview</p>
+ <div
+ role="tablist"
+ aria-label="Preview"
+ className="flex items-center gap-0.5 rounded-full border border-gray-4 bg-gray-1 p-0.5"
+ >
+ {(
+ [
+ { id: "end", label: "End of video" },
+ { id: "playing", label: "While playing" },
+ ] as const
+ ).map((mode) => (
+ <button
+ key={mode.id}
+ type="button"
+ role="tab"
+ aria-selected={previewMode === mode.id}
+ onClick={() => setPreviewMode(mode.id)}
+ className={clsx(
+ "relative rounded-full px-3 py-1 text-xs font-medium transition-colors",
+ previewMode === mode.id
+ ? "text-gray-12"
+ : "text-gray-10 hover:text-gray-12",
+ )}
+ >
+ {previewMode === mode.id && (
+ <motion.span
+ layoutId="cta-preview-mode"
+ className="absolute inset-0 rounded-full bg-gray-4"
+ transition={{
+ type: "spring",
+ stiffness: 500,
+ damping: 38,
+ }}
+ />
+ )}
+ <span className="relative">{mode.label}</span>
+ </button>
+ ))}
+ </div>
+ </div>
+
+ <div className="flex flex-1 flex-col justify-center gap-4">
+ <PreviewStage
+ cta={previewCta}
+ mode={previewMode}
+ thumbnail={thumbnail}
+ onEnableWhilePlaying={() => update("showWhilePlaying", true)}
+ />
+
+ <p className="min-h-[2.5rem] text-[13px] leading-relaxed text-gray-10">
+ {previewMode === "end"
+ ? "Shown over the last frame when your video finishes. Viewers can click through or replay."
+ : form.showWhilePlaying
+ ? "Slides into the corner a few seconds in, on screens wide enough to fit it. Viewers can close it."
+ : "Only the end screen is on. Turn on “Show while playing” to add the corner card."}
+ </p>
+ </div>
+ </section>
+
+ <section className="flex min-h-0 flex-1 flex-col">
+ <header className="flex items-start gap-3 px-6 pb-4 pt-6">
+ <span className="flex size-9 shrink-0 items-center justify-center rounded-xl bg-blue-3 text-blue-11">
+ <MousePointer2 className="size-[18px]" strokeWidth={2} />
+ </span>
+ <div className="min-w-0 flex-1">
+ <DialogTitle className="text-lg font-semibold leading-tight text-gray-12">
+ Call to action
+ </DialogTitle>
+ <p className="mt-0.5 text-[13px] text-gray-10">
+ Give viewers a next step, right on your video.
+ </p>
+ </div>
+ <button
+ type="button"
+ onClick={() => onOpenChange(false)}
+ disabled={busy}
+ aria-label="Close"
+ className="-mr-1 rounded-lg p-1 text-gray-10 transition-colors hover:bg-gray-3 hover:text-gray-12 focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-blue-9"
+ >
+ <X className="size-5" />
+ </button>
+ </header>
+
+ <form
+ id={ids.form}
+ className="flex min-h-0 flex-1 flex-col gap-5 overflow-y-auto px-6 pb-6"
+ onSubmit={(event) => {
+ event.preventDefault();
+ void handleSave();
+ }}
+ >
+ <Field
+ id={ids.label}
+ label="Button text"
+ error={visibleError("label")}
+ counter={
+ form.label.length > CTA_LABEL_MAX_LENGTH - 10
+ ? `${form.label.length}/${CTA_LABEL_MAX_LENGTH}`
+ : undefined
+ }
+ >
+ <TextInput
+ ref={labelInputRef}
+ id={ids.label}
+ value={form.label}
+ placeholder="Book a call"
+ maxLength={CTA_LABEL_MAX_LENGTH + 10}
+ invalid={Boolean(visibleError("label"))}
+ onChange={(value) => update("label", value)}
+ onBlur={() => form.label && markTouched("label")}
+ />
+ <div className="flex flex-wrap gap-1.5 pt-0.5">
+ {CTA_LABEL_SUGGESTIONS.map((suggestion) => (
+ <button
+ key={suggestion}
+ type="button"
+ onClick={() => update("label", suggestion)}
+ className={clsx(
+ "rounded-full border px-2.5 py-1 text-xs font-medium transition-colors focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-blue-9",
+ form.label === suggestion
+ ? "border-blue-7 bg-blue-3 text-blue-11"
+ : "border-gray-4 bg-gray-1 text-gray-11 hover:border-gray-6 hover:bg-gray-3 hover:text-gray-12",
+ )}
+ >
+ {suggestion}
+ </button>
+ ))}
+ </div>
+ </Field>
+
+ <Field id={ids.url} label="Link" error={visibleError("url")}>
+ <TextInput
+ id={ids.url}
+ value={form.url}
+ placeholder="cal.com/you"
+ inputMode="url"
+ autoComplete="url"
+ spellCheck={false}
+ icon={<Link2 className="size-4" />}
+ invalid={Boolean(visibleError("url"))}
+ onChange={(value) => update("url", value)}
+ onBlur={() => {
+ if (!form.url.trim()) return;
+ markTouched("url");
+ const normalized = normalizeCallToActionUrl(form.url);
+ if (normalized) update("url", normalized);
+ }}
+ />
+ </Field>
+
+ <Field
+ id={ids.headline}
+ label="Headline"
+ optional
+ error={visibleError("headline")}
+ counter={
+ form.headline.length > CTA_HEADLINE_MAX_LENGTH - 15
+ ? `${form.headline.length}/${CTA_HEADLINE_MAX_LENGTH}`
+ : undefined
+ }
+ >
+ <TextInput
+ id={ids.headline}
+ value={form.headline}
+ placeholder="Want to see it in action?"
+ maxLength={CTA_HEADLINE_MAX_LENGTH + 20}
+ invalid={Boolean(visibleError("headline"))}
+ onChange={(value) => update("headline", value)}
+ onBlur={() => markTouched("headline")}
+ />
+ </Field>
+
+ <div className="flex flex-col gap-2">
+ <p className="text-[13px] font-medium text-gray-12">
+ Button color
+ </p>
+ <ColorPicker
+ value={form.color}
+ onChange={(color) => update("color", color)}
+ />
+ </div>
+
+ <label
+ htmlFor={ids.playing}
+ className="flex cursor-pointer items-start gap-4 rounded-xl border border-gray-4 bg-gray-2 p-4 transition-colors hover:border-gray-5"
+ onPointerEnter={() => setPreviewMode("playing")}
+ >
+ <span className="flex min-w-0 flex-1 flex-col gap-0.5">
+ <span className="text-[13px] font-medium text-gray-12">
+ Show while playing
+ </span>
+ <span className="text-xs leading-relaxed text-gray-10">
+ A small card in the corner on larger screens. Viewers can
+ close it.
+ </span>
+ </span>
+ <Switch
+ id={ids.playing}
+ checked={form.showWhilePlaying}
+ onCheckedChange={(checked) => {
+ update("showWhilePlaying", checked);
+ setPreviewMode("playing");
+ }}
+ />
+ </label>
+ </form>
+
+ <footer className="flex items-center gap-2 border-t border-gray-4 px-6 py-4">
+ {isEditing && (
+ <button
+ type="button"
+ onClick={() => void handleRemove()}
+ disabled={busy}
+ className="rounded-lg px-2 py-1.5 text-[13px] font-medium text-red-600 transition-colors hover:bg-red-50 disabled:opacity-50 dark:text-red-400 dark:hover:bg-red-500/10"
+ >
+ {pending === "remove" ? "Removing…" : "Remove"}
+ </button>
+ )}
+ <div className="ml-auto flex items-center gap-2">
+ <button
+ type="button"
+ onClick={() => onOpenChange(false)}
+ disabled={busy}
+ className="h-9 rounded-full px-4 text-[13px] font-medium text-gray-11 transition-colors hover:bg-gray-3 hover:text-gray-12 disabled:opacity-50"
+ >
+ Cancel
+ </button>
+ <button
+ type="submit"
+ form={ids.form}
+ disabled={busy}
+ className="inline-flex h-9 items-center gap-1.5 rounded-full bg-gray-12 px-4 text-[13px] font-semibold text-gray-1 transition-[opacity,transform] hover:opacity-90 active:scale-[0.98] disabled:opacity-60"
+ >
+ {pending === "save"
+ ? "Saving…"
+ : isEditing
+ ? "Save changes"
+ : "Add to video"}
+ </button>
+ </div>
+ </footer>
+ </section>
+ </DialogContent>
+ </Dialog>
+ );
+}
+
+function PreviewStage({
+ cta,
+ mode,
+ thumbnail,
+ onEnableWhilePlaying,
+}: {
+ cta: ShareCallToAction;
+ mode: PreviewMode;
+ thumbnail: string | null;
+ onEnableWhilePlaying: () => void;
+}) {
+ return (
+ <div
+ className="relative aspect-video w-full overflow-hidden rounded-xl bg-[#0c0d10] shadow-[0_24px_48px_-24px_rgba(0,0,0,0.45)] ring-1 ring-black/5"
+ aria-hidden
+ >
+ {thumbnail ? (
+ <div
+ className="absolute inset-0 bg-cover bg-center"
+ style={{ backgroundImage: `url(${JSON.stringify(thumbnail)})` }}
+ />
+ ) : (
+ <div className="absolute inset-0 bg-[radial-gradient(120%_90%_at_20%_10%,#2a3140_0%,#12151b_55%,#0b0c0f_100%)]">
+ <div className="absolute left-[8%] top-[12%] h-[8%] w-[34%] rounded-md bg-white/[0.07]" />
+ <div className="absolute left-[8%] top-[26%] h-[5%] w-[52%] rounded-md bg-white/[0.05]" />
+ <div className="absolute left-[8%] top-[35%] h-[5%] w-[44%] rounded-md bg-white/[0.05]" />
+ <div className="absolute bottom-[14%] left-[8%] right-[8%] top-[48%] rounded-lg bg-white/[0.04]" />
+ </div>
+ )}
+
+ <AnimatePresence mode="wait" initial={false}>
+ {mode === "end" ? (
+ <motion.div
+ key="end"
+ className="absolute inset-0"
+ initial={{ opacity: 0 }}
+ animate={{ opacity: 1 }}
+ exit={{ opacity: 0 }}
+ transition={{ duration: 0.2 }}
+ >
+ <CallToActionEndScreen
+ cta={cta}
+ scale="regular"
+ interactive={false}
+ onReplay={() => {}}
+ />
+ </motion.div>
+ ) : (
+ <motion.div
+ key="playing"
+ className="absolute inset-0"
+ initial={{ opacity: 0 }}
+ animate={{ opacity: 1 }}
+ exit={{ opacity: 0 }}
+ transition={{ duration: 0.2 }}
+ >
+ <div className="absolute inset-x-0 bottom-0 h-1/3 bg-gradient-to-t from-black/70 to-transparent" />
+ <div className="absolute inset-x-3 bottom-3 flex flex-col gap-2">
+ <div className="h-1 overflow-hidden rounded-full bg-white/25">
+ <div className="h-full w-[38%] rounded-full bg-white" />
+ </div>
+ <div className="flex items-center gap-2 text-white">
+ <Play className="size-3.5 fill-current" />
+ <span className="text-[10px] font-medium tabular-nums text-white/80">
+ 0:42 / 1:52
+ </span>
+ </div>
+ </div>
+ <AnimatePresence>
+ {cta.showWhilePlaying ? (
+ <motion.div
+ key="card"
+ exit={{ opacity: 0, y: 6 }}
+ transition={{ duration: 0.15 }}
+ className="absolute bottom-12 right-3 origin-bottom-right scale-[0.82]"
+ >
+ <CallToActionCornerCard cta={cta} interactive={false} />
+ </motion.div>
+ ) : (
+ <motion.div
+ key="off"
+ initial={{ opacity: 0, y: 4 }}
+ animate={{ opacity: 1, y: 0 }}
+ exit={{ opacity: 0 }}
+ className="pointer-events-auto absolute inset-0 flex items-center justify-center"
+ >
+ <button
+ type="button"
+ tabIndex={-1}
+ onClick={onEnableWhilePlaying}
+ className="rounded-full bg-black/55 px-3 py-1.5 text-xs font-medium text-white/85 backdrop-blur-md transition-colors hover:bg-black/70"
+ >
+ Corner card is off · Turn on
+ </button>
+ </motion.div>
+ )}
+ </AnimatePresence>
+ </motion.div>
+ )}
+ </AnimatePresence>
+ </div>
+ );
+}
+
+function Field({
+ id,
+ label,
+ optional = false,
+ error,
+ counter,
+ children,
+}: {
+ id: string;
+ label: string;
+ optional?: boolean;
+ error?: string;
+ counter?: string;
+ children: ReactNode;
+}) {
+ return (
+ <div className="flex flex-col gap-2">
+ <div className="flex items-baseline justify-between gap-2">
+ <label htmlFor={id} className="text-[13px] font-medium text-gray-12">
+ {label}
+ {optional && (
+ <span className="ml-1.5 font-normal text-gray-9">Optional</span>
+ )}
+ </label>
+ {counter && (
+ <span className="text-[11px] tabular-nums text-gray-9">
+ {counter}
+ </span>
+ )}
+ </div>
+ {children}
+ <AnimatePresence initial={false}>
+ {error && (
+ <motion.p
+ key={error}
+ initial={{ opacity: 0, height: 0 }}
+ animate={{ opacity: 1, height: "auto" }}
+ exit={{ opacity: 0, height: 0 }}
+ transition={{ duration: 0.15 }}
+ role="alert"
+ className="text-xs text-red-600 dark:text-red-400"
+ >
+ {error}
+ </motion.p>
+ )}
+ </AnimatePresence>
+ </div>
+ );
+}
+
+type TextInputProps = {
+ id: string;
+ value: string;
+ placeholder?: string;
+ maxLength?: number;
+ invalid?: boolean;
+ icon?: ReactNode;
+ inputMode?: "url" | "text";
+ autoComplete?: string;
+ spellCheck?: boolean;
+ onChange: (value: string) => void;
+ onBlur?: () => void;
+ ref?: React.Ref<HTMLInputElement>;
+};
+
+function TextInput({
+ id,
+ value,
+ placeholder,
+ maxLength,
+ invalid = false,
+ icon,
+ inputMode,
+ autoComplete = "off",
+ spellCheck,
+ onChange,
+ onBlur,
+ ref,
+}: TextInputProps) {
+ return (
+ <div className="relative">
+ {icon && (
+ <span className="pointer-events-none absolute left-3 top-1/2 -translate-y-1/2 text-gray-9">
+ {icon}
+ </span>
+ )}
+ <input
+ ref={ref}
+ id={id}
+ type="text"
+ value={value}
+ placeholder={placeholder}
+ maxLength={maxLength}
+ inputMode={inputMode}
+ autoComplete={autoComplete}
+ spellCheck={spellCheck}
+ aria-invalid={invalid || undefined}
+ onChange={(event) => onChange(event.target.value)}
+ onBlur={onBlur}
+ className={clsx(
+ "h-10 w-full rounded-xl border bg-gray-1 text-[14px] text-gray-12 outline-none transition-[border-color,box-shadow] placeholder:text-gray-8",
+ icon ? "pl-9 pr-3" : "px-3",
+ invalid
+ ? "border-red-400 focus:border-red-500 focus:shadow-[0_0_0_3px_rgba(239,68,68,0.15)]"
+ : "border-gray-4 hover:border-gray-6 focus:border-blue-8 focus:shadow-[0_0_0_3px_rgba(47,107,255,0.15)]",
+ )}
+ />
+ </div>
+ );
+}
+
+function ColorPicker({
+ value,
+ onChange,
+}: {
+ value: string;
+ onChange: (color: string) => void;
+}) {
+ const normalized = normalizeHexColor(value) ?? DEFAULT_CTA_COLOR;
+ const isCustom = !CTA_COLOR_PRESETS.some(
+ (preset) => preset.value === normalized,
+ );
+
+ return (
+ <div className="flex flex-wrap items-center gap-2">
+ {CTA_COLOR_PRESETS.map((preset) => {
+ const selected = preset.value === normalized;
+ return (
+ <button
+ key={preset.value}
+ type="button"
+ aria-label={preset.name}
+ aria-pressed={selected}
+ title={preset.name}
+ onClick={() => onChange(preset.value)}
+ className={clsx(
+ "relative flex size-8 items-center justify-center rounded-full transition-transform hover:scale-105 focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-blue-9 focus-visible:ring-offset-2 focus-visible:ring-offset-gray-1",
+ selected &&
+ "ring-2 ring-gray-12 ring-offset-2 ring-offset-gray-1",
+ )}
+ style={{ background: preset.value }}
+ >
+ {selected && (
+ <Check
+ className="size-4 text-white drop-shadow"
+ strokeWidth={3}
+ />
+ )}
+ </button>
+ );
+ })}
+ <label
+ title="Custom color"
+ className={clsx(
+ "relative flex size-8 cursor-pointer items-center justify-center rounded-full transition-transform hover:scale-105 focus-within:ring-2 focus-within:ring-blue-9 focus-within:ring-offset-2 focus-within:ring-offset-gray-1",
+ isCustom && "ring-2 ring-gray-12 ring-offset-2 ring-offset-gray-1",
+ )}
+ style={{
+ background: isCustom
+ ? normalized
+ : "conic-gradient(from 180deg, #ff5f6d, #ffc371, #47e891, #3fa7ff, #a86bff, #ff5f6d)",
+ }}
+ >
+ <span className="sr-only">Custom color</span>
+ <Pipette
+ className="size-3.5 text-white drop-shadow"
+ strokeWidth={2.5}
+ />
+ <input
+ type="color"
+ value={normalized.toLowerCase()}
+ onChange={(event) =>
+ onChange(normalizeHexColor(event.target.value) ?? normalized)
+ }
+ className="absolute inset-0 cursor-pointer opacity-0"
+ />
+ </label>
+ <span className="ml-1 font-mono text-xs uppercase text-gray-10">
+ {normalized}
+ </span>
+ </div>
+ );
+}
diff --git a/apps/web/app/s/[videoId]/_components/call-to-action/CallToActionOverlay.tsx b/apps/web/app/s/[videoId]/_components/call-to-action/CallToActionOverlay.tsx
new file mode 100644
index 000000000..e5e641669
--- /dev/null
+++ b/apps/web/app/s/[videoId]/_components/call-to-action/CallToActionOverlay.tsx
@@ -0,0 +1,155 @@
+"use client";
+
+import type { MediaState } from "media-chrome/react/media-store";
+import { AnimatePresence } from "motion/react";
+import { useCallback, useEffect, useRef, useState } from "react";
+import {
+ CORNER_CARD_DELAY_SECONDS,
+ type ShareCallToAction,
+ shouldShowCornerCard,
+} from "@/lib/share-call-to-action";
+import { useMediaPlayer, useMediaPlayerStore } from "../video/media-player";
+import {
+ CallToActionCornerCard,
+ CallToActionEndScreen,
+ type CallToActionScale,
+} from "./CallToActionSurfaces";
+
+type MediaSnapshot = Partial<MediaState>;
+
+const selectEnded = (state: MediaSnapshot) => state.mediaEnded ?? false;
+const selectPastIntro = (state: MediaSnapshot) =>
+ (state.mediaCurrentTime ?? 0) >= CORNER_CARD_DELAY_SECONDS;
+
+const dismissedKey = (videoId: string) => `cap:cta-dismissed:${videoId}`;
+
+function readDismissed(videoId: string) {
+ try {
+ return window.sessionStorage.getItem(dismissedKey(videoId)) === "1";
+ } catch {
+ return false;
+ }
+}
+
+function writeDismissed(videoId: string) {
+ try {
+ window.sessionStorage.setItem(dismissedKey(videoId), "1");
+ } catch {}
+}
+
+function scaleForWidth(width: number): CallToActionScale {
+ if (width < 480) return "compact";
+ if (width < 960) return "regular";
+ return "large";
+}
+
+export function CallToActionOverlay({
+ cta,
+ videoId,
+ controlsDocked = false,
+}: {
+ cta: ShareCallToAction;
+ videoId: string;
+ controlsDocked?: boolean;
+}) {
+ const rootRef = useRef<HTMLDivElement>(null);
+ const [size, setSize] = useState({ width: 0, height: 0 });
+ const [dismissed, setDismissed] = useState(false);
+ const ended = useMediaPlayer(selectEnded);
+ const pastIntro = useMediaPlayer(selectPastIntro);
+ const controlsVisible = useMediaPlayerStore((state) => state.controlsVisible);
+
+ useEffect(() => {
+ setDismissed(readDismissed(videoId));
+ }, [videoId]);
+
+ useEffect(() => {
+ const element = rootRef.current;
+ if (!element) return;
+ const update = () => {
+ const rect = element.getBoundingClientRect();
+ setSize((previous) =>
+ previous.width === rect.width && previous.height === rect.height
+ ? previous
+ : { width: rect.width, height: rect.height },
+ );
+ };
+ update();
+ const observer = new ResizeObserver(update);
+ observer.observe(element);
+ return () => observer.disconnect();
+ }, []);
+
+ const findVideo = useCallback(
+ () =>
+ rootRef.current?.parentElement?.querySelector<HTMLVideoElement>(
+ "video",
+ ) ?? null,
+ [],
+ );
+
+ const handleReplay = useCallback(() => {
+ const video = findVideo();
+ if (!video) return;
+ video.currentTime = 0;
+ void video.play().catch(() => {});
+ }, [findVideo]);
+
+ const handleOpen = useCallback(() => {
+ const video = findVideo();
+ if (video && !video.paused) video.pause();
+ }, [findVideo]);
+
+ const handleDismiss = useCallback(() => {
+ setDismissed(true);
+ writeDismissed(videoId);
+ }, [videoId]);
+
+ const showCornerCard = shouldShowCornerCard({
+ cta,
+ width: size.width,
+ height: size.height,
+ dismissed,
+ pastIntro,
+ ended,
+ });
+ const liftAboveControls = controlsVisible && !controlsDocked;
+
+ return (
+ <div
+ ref={rootRef}
+ data-slot="cta-overlay"
+ className="pointer-events-none absolute inset-0 z-[45] rounded-[inherit]"
+ >
+ <AnimatePresence>
+ {ended && size.width > 0 && (
+ <div key="end" className="pointer-events-auto absolute inset-0">
+ <CallToActionEndScreen
+ cta={cta}
+ scale={scaleForWidth(size.width)}
+ controlsInset={!controlsDocked}
+ onReplay={handleReplay}
+ onOpen={handleOpen}
+ />
+ </div>
+ )}
+ </AnimatePresence>
+ <div
+ className="absolute right-4 transition-[bottom] duration-300 ease-out"
+ style={{ bottom: liftAboveControls ? 92 : 16 }}
+ >
+ <AnimatePresence>
+ {showCornerCard && (
+ <CallToActionCornerCard
+ key="corner"
+ cta={cta}
+ className="pointer-events-auto"
+ onDismiss={handleDismiss}
+ onOpen={handleOpen}
+ />
+ )}
+ </AnimatePresence>
+ </div>
+ </div>
+ );
+}
diff --git a/apps/web/app/s/[videoId]/_components/call-to-action/CallToActionSurfaces.tsx b/apps/web/app/s/[videoId]/_components/call-to-action/CallToActionSurfaces.tsx
new file mode 100644
index 000000000..eced8b6dc
--- /dev/null
+++ b/apps/web/app/s/[videoId]/_components/call-to-action/CallToActionSurfaces.tsx
@@ -0,0 +1,279 @@
+"use client";
+
+import clsx from "clsx";
+import { ArrowUpRight, RotateCcw, X } from "lucide-react";
+import { motion } from "motion/react";
+import type { CSSProperties, MouseEvent } from "react";
+import {
+ callToActionDestinationLabel,
+ readableTextColor,
+ type ShareCallToAction,
+} from "@/lib/share-call-to-action";
+
+export type CallToActionScale = "compact" | "regular" | "large";
+
+type ButtonProps = {
+ cta: ShareCallToAction;
+ scale: CallToActionScale;
+ fullWidth?: boolean;
+ interactive?: boolean;
+ onOpen?: () => void;
+};
+
+export function CallToActionButton({
+ cta,
+ scale,
+ fullWidth = false,
+ interactive = true,
+ onOpen,
+}: ButtonProps) {
+ const style = {
+ "--cta-color": cta.color,
+ color: readableTextColor(cta.color),
+ } as CSSProperties;
+
+ const className = clsx(
+ "group/cta relative inline-flex max-w-full items-center justify-center gap-1.5 overflow-hidden rounded-full font-semibold tracking-[-0.01em]",
+ "bg-[var(--cta-color)] shadow-[0_1px_0_rgba(255,255,255,0.25)_inset,0_10px_28px_-12px_var(--cta-color)] transition-[transform,filter] duration-200",
+ interactive &&
+ "hover:-translate-y-px hover:brightness-110 active:translate-y-0 active:brightness-95 focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-white focus-visible:ring-offset-2 focus-visible:ring-offset-black/40",
+ scale === "compact" && "h-9 px-4 text-[13px]",
+ scale === "regular" && "h-10 px-5 text-sm",
+ scale === "large" && "h-12 px-6 text-base",
+ fullWidth && "w-full",
+ );
+
+ const content = (
+ <>
+ <span className="truncate">{cta.label}</span>
+ <ArrowUpRight
+ aria-hidden
+ className={clsx(
+ "shrink-0 transition-transform duration-200",
+ interactive &&
+ "group-hover/cta:-translate-y-px group-hover/cta:translate-x-px",
+ scale === "large" ? "size-[18px]" : "size-4",
+ )}
+ strokeWidth={2.25}
+ />
+ </>
+ );
+
+ if (!interactive) {
+ return (
+ <span className={className} style={style}>
+ {content}
+ </span>
+ );
+ }
+
+ return (
+ <a
+ href={cta.url}
+ target="_blank"
+ rel="noopener noreferrer nofollow"
+ className={className}
+ style={style}
+ onClick={(event: MouseEvent) => {
+ event.stopPropagation();
+ onOpen?.();
+ }}
+ >
+ {content}
+ </a>
+ );
+}
+
+type EndScreenProps = {
+ cta: ShareCallToAction;
+ scale: CallToActionScale;
+ interactive?: boolean;
+ controlsInset?: boolean;
+ onReplay?: () => void;
+ onOpen?: () => void;
+};
+
+export function CallToActionEndScreen({
+ cta,
+ scale,
+ interactive = true,
+ controlsInset = false,
+ onReplay,
+ onOpen,
+}: EndScreenProps) {
+ const destination = callToActionDestinationLabel(cta.url);
+ const compact = scale === "compact";
+ const replayButton = onReplay && (
+ <button
+ type="button"
+ aria-label={compact ? "Replay" : undefined}
+ tabIndex={interactive ? undefined : -1}
+ onClick={(event) => {
+ event.stopPropagation();
+ onReplay();
+ }}
+ className={clsx(
+ "inline-flex shrink-0 items-center justify-center gap-1.5 rounded-full font-medium text-white/70 transition-colors hover:bg-white/10 hover:text-white focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-white/70",
+ compact ? "size-9 bg-white/10" : "h-8 px-3 text-[13px]",
+ )}
+ >
+ <RotateCcw aria-hidden className="size-3.5" strokeWidth={2.25} />
+ {!compact && "Replay"}
+ </button>
+ );
+
+ return (
+ <motion.div
+ data-slot="cta-end-screen"
+ initial={{ opacity: 0 }}
+ animate={{ opacity: 1 }}
+ exit={{ opacity: 0 }}
+ transition={{ duration: 0.3, ease: "easeOut" }}
+ className={clsx(
+ "absolute inset-0 flex items-center justify-center overflow-hidden rounded-[inherit] bg-black/60 backdrop-blur-md",
+ controlsInset &&
+ (compact ? "pb-14" : scale === "regular" ? "pb-16" : "pb-20"),
+ )}
+ onClick={(event) => event.stopPropagation()}
+ onDoubleClick={(event) => event.stopPropagation()}
+ >
+ <div
+ aria-hidden
+ className="pointer-events-none absolute left-1/2 top-1/2 aspect-square w-[70%] -translate-x-1/2 -translate-y-1/2 rounded-full opacity-25 blur-3xl"
+ style={{ background: cta.color }}
+ />
+ <motion.div
+ initial={{ opacity: 0, y: 10, scale: 0.98 }}
+ animate={{ opacity: 1, y: 0, scale: 1 }}
+ transition={{ duration: 0.45, ease: [0.22, 1, 0.36, 1], delay: 0.05 }}
+ className={clsx(
+ "relative flex max-w-[86%] flex-col items-center text-center",
+ compact ? "gap-3" : scale === "regular" ? "gap-4" : "gap-5",
+ )}
+ >
+ {cta.headline && (
+ <p
+ className={clsx(
+ "text-balance font-semibold leading-tight tracking-[-0.02em] text-white",
+ compact && "text-base",
+ scale === "regular" && "text-xl",
+ scale === "large" && "text-3xl",
+ )}
+ >
+ {cta.headline}
+ </p>
+ )}
+ {compact ? (
+ <div className="flex max-w-full items-center gap-2">
+ <CallToActionButton
+ cta={cta}
+ scale={scale}
+ interactive={interactive}
+ onOpen={onOpen}
+ />
+ {replayButton}
+ </div>
+ ) : (
+ <>
+ <div className="flex max-w-full flex-col items-center gap-2">
+ <CallToActionButton
+ cta={cta}
+ scale={scale}
+ interactive={interactive}
+ onOpen={onOpen}
+ />
+ <span className="max-w-full truncate text-xs font-medium text-white/55">
+ {destination}
+ </span>
+ </div>
+ {replayButton}
+ </>
+ )}
+ </motion.div>
+ </motion.div>
+ );
+}
+
+type CornerCardProps = {
+ cta: ShareCallToAction;
+ interactive?: boolean;
+ onDismiss?: () => void;
+ onOpen?: () => void;
+ className?: string;
+ style?: CSSProperties;
+};
+
+export function CallToActionCornerCard({
+ cta,
+ interactive = true,
+ onDismiss,
+ onOpen,
+ className,
+ style,
+}: CornerCardProps) {
+ const dismissButton = (
+ <button
+ type="button"
+ aria-label="Dismiss"
+ tabIndex={interactive ? undefined : -1}
+ onClick={(event) => {
+ event.stopPropagation();
+ onDismiss?.();
+ }}
+ className="flex size-6 shrink-0 items-center justify-center rounded-full text-white/55 transition-colors hover:bg-white/10 hover:text-white focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-white/70"
+ >
+ <X aria-hidden className="size-3.5" strokeWidth={2.5} />
+ </button>
+ );
+
+ return (
+ <motion.div
+ data-slot="cta-corner-card"
+ initial={{ opacity: 0, y: 12, scale: 0.97 }}
+ animate={{ opacity: 1, y: 0, scale: 1 }}
+ exit={{ opacity: 0, y: 8, scale: 0.97 }}
+ transition={{ type: "spring", stiffness: 420, damping: 34 }}
+ className={clsx(
+ "rounded-2xl border border-white/10 bg-[rgba(18,18,20,0.78)] text-white shadow-[0_18px_40px_-16px_rgba(0,0,0,0.65)] backdrop-blur-xl",
+ cta.headline ? "w-[264px] p-3" : "flex items-center gap-1 p-1.5",
+ className,
+ )}
+ style={style}
+ onClick={(event) => event.stopPropagation()}
+ onDoubleClick={(event) => event.stopPropagation()}
+ >
+ {cta.headline ? (
+ <div className="flex flex-col gap-3">
+ <div className="flex items-start gap-2">
+ <div className="flex min-w-0 flex-1 flex-col gap-0.5 pl-0.5 pt-0.5">
+ <p className="line-clamp-2 text-[13px] font-semibold leading-snug tracking-[-0.01em]">
+ {cta.headline}
+ </p>
+ <p className="truncate text-[11px] font-medium text-white/50">
+ {callToActionDestinationLabel(cta.url)}
+ </p>
+ </div>
+ {dismissButton}
+ </div>
+ <CallToActionButton
+ cta={cta}
+ scale="compact"
+ fullWidth
+ interactive={interactive}
+ onOpen={onOpen}
+ />
+ </div>
+ ) : (
+ <>
+ <CallToActionButton
+ cta={cta}
+ scale="compact"
+ interactive={interactive}
+ onOpen={onOpen}
+ />
+ {dismissButton}
+ </>
+ )}
+ </motion.div>
+ );
+}
diff --git a/apps/web/app/s/[videoId]/page.tsx b/apps/web/app/s/[videoId]/page.tsx
index ed5442a1e..af173516c 100644
--- a/apps/web/app/s/[videoId]/page.tsx
+++ b/apps/web/app/s/[videoId]/page.tsx
@@ -57,6 +57,7 @@ import { getPublicShareVideo } from "@/lib/public-share-video";
import * as EffectRuntime from "@/lib/server";
import { runPromise } from "@/lib/server";
import { getSharePageBranding } from "@/lib/share-branding";
+import { parseShareCallToAction } from "@/lib/share-call-to-action";
import { getSharePlaybackUrl } from "@/lib/share-playback";
import { buildShareVideoMetadata } from "@/lib/share-video-metadata";
import { resolveShareWebUrl } from "@/lib/share-web-url";
@@ -887,6 +888,9 @@ async function AuthorizedContent({
hasInheritedPassword: rules.hasInheritedPassword,
inheritedPasswordSources: rules.inheritedPasswordSources,
inheritedSpaceSettings: rules.inheritedSettings,
+ callToAction: ownerIsPro
+ ? parseShareCallToAction(video.videoSettings)
+ : null,
};
const isEditProcessing =
isEditSourceKey({
diff --git a/apps/web/app/s/[videoId]/types.ts b/apps/web/app/s/[videoId]/types.ts
index f013595ba..76ff1323a 100644
--- a/apps/web/app/s/[videoId]/types.ts
+++ b/apps/web/app/s/[videoId]/types.ts
@@ -2,6 +2,7 @@ import type { videos } from "@cap/database/schema";
import type { SpaceRuleSource, ViewerSettingKey } from "@cap/web-backend";
import type { ImageUpload, Organisation, User } from "@cap/web-domain";
import type { OrganizationSettings } from "@/app/(org)/dashboard/dashboard-data";
+import type { ShareCallToAction } from "@/lib/share-call-to-action";
export type VideoData = Omit<typeof videos.$inferSelect, "ownerId"> & {
owner: VideoOwner;
@@ -20,6 +21,7 @@ export type VideoData = Omit<typeof videos.$inferSelect, "ownerId"> & {
hasActiveUpload?: boolean;
activeUploadRawFileKey?: string | null;
ownerIsOverShareLimit?: boolean;
+ callToAction?: ShareCallToAction | null;
};
export type VideoOwner = {
diff --git a/apps/web/lib/share-call-to-action.ts b/apps/web/lib/share-call-to-action.ts
new file mode 100644
index 000000000..1109eccc2
--- /dev/null
+++ b/apps/web/lib/share-call-to-action.ts
@@ -0,0 +1,241 @@
+import type { VideoCallToAction } from "@cap/database/types";
+
+export const CTA_LABEL_MAX_LENGTH = 40;
+export const CTA_HEADLINE_MAX_LENGTH = 80;
+export const CTA_URL_MAX_LENGTH = 2048;
+
+export const CORNER_CARD_DELAY_SECONDS = 3;
+export const CORNER_CARD_MIN_WIDTH = 640;
+export const CORNER_CARD_MIN_HEIGHT = 300;
+
+export const CTA_COLOR_PRESETS = [
+ { name: "Blue", value: "#2F6BFF" },
+ { name: "Ink", value: "#111113" },
+ { name: "Green", value: "#12A150" },
+ { name: "Violet", value: "#7A4DFF" },
+ { name: "Pink", value: "#E5337A" },
+ { name: "Orange", value: "#F26B1D" },
+] as const;
+
+export const DEFAULT_CTA_COLOR = CTA_COLOR_PRESETS[0].value;
+
+export const CTA_LABEL_SUGGESTIONS = [
+ "Book a call",
+ "Try it free",
+ "Learn more",
+ "Get started",
+ "Reply to me",
+] as const;
+
+export type ShareCallToAction = {
+ label: string;
+ url: string;
+ headline: string | null;
+ color: string;
+ showWhilePlaying: boolean;
+};
+
+export type CallToActionInput = {
+ label: string;
+ url: string;
+ headline?: string | null;
+ color?: string | null;
+ showWhilePlaying?: boolean;
+};
+
+export type CallToActionErrors = Partial<
+ Record<"label" | "url" | "headline", string>
+>;
+
+export type CallToActionValidation =
+ | { ok: true; value: ShareCallToAction }
+ | { ok: false; errors: CallToActionErrors };
+
+const collapseWhitespace = (value: string) => value.replace(/\s+/g, " ").trim();
+
+const HAS_SCHEME = /^[a-z][a-z0-9+.-]*:(?!\d)/i;
+
+const safeDecode = (value: string) => {
+ try {
+ return decodeURIComponent(value);
+ } catch {
+ return null;
+ }
+};
+
+export function normalizeCallToActionUrl(input: string): string | null {
+ const trimmed = input.trim();
+ if (!trimmed || /\s/.test(trimmed)) return null;
+
+ const candidate = HAS_SCHEME.test(trimmed) ? trimmed : `https://${trimmed}`;
+
+ let url: URL;
+ try {
+ url = new URL(candidate);
+ } catch {
+ return null;
+ }
+
+ if (url.protocol === "mailto:") {
+ const address = safeDecode(url.pathname);
+ if (!address || !/^[^@\s]+@[^@\s]+\.[^@\s]+$/.test(address)) {
+ return null;
+ }
+ } else if (url.protocol === "http:" || url.protocol === "https:") {
+ if (url.username || url.password) return null;
+ const host = url.hostname;
+ if (!host.includes(".") || host.startsWith(".") || host.endsWith(".")) {
+ return null;
+ }
+ } else {
+ return null;
+ }
+
+ const normalized = url.toString();
+ return normalized.length > CTA_URL_MAX_LENGTH ? null : normalized;
+}
+
+export function normalizeHexColor(input: unknown): string | null {
+ if (typeof input !== "string") return null;
+ const match = /^#?([0-9a-f]{3}|[0-9a-f]{6})$/i.exec(input.trim());
+ if (!match?.[1]) return null;
+ const hex =
+ match[1].length === 3
+ ? match[1]
+ .split("")
+ .map((char) => char + char)
+ .join("")
+ : match[1];
+ return `#${hex.toUpperCase()}`;
+}
+
+export function validateCallToAction(
+ input: CallToActionInput,
+): CallToActionValidation {
+ const errors: CallToActionErrors = {};
+
+ const label = collapseWhitespace(input.label ?? "");
+ if (!label) errors.label = "Add the text for your button";
+ else if (label.length > CTA_LABEL_MAX_LENGTH)
+ errors.label = `Keep it under ${CTA_LABEL_MAX_LENGTH} characters`;
+
+ const url = (input.url ?? "").trim();
+ const normalizedUrl = url ? normalizeCallToActionUrl(url) : null;
+ if (!url) errors.url = "Add where the button should go";
+ else if (!normalizedUrl) errors.url = "Enter a valid link, like cap.so/demo";
+
+ const headline = collapseWhitespace(input.headline ?? "");
+ if (headline.length > CTA_HEADLINE_MAX_LENGTH)
+ errors.headline = `Keep it under ${CTA_HEADLINE_MAX_LENGTH} characters`;
+
+ if (Object.keys(errors).length > 0 || !normalizedUrl) {
+ return { ok: false, errors };
+ }
+
+ return {
+ ok: true,
+ value: {
+ label,
+ url: normalizedUrl,
+ headline: headline || null,
+ color: normalizeHexColor(input.color) ?? DEFAULT_CTA_COLOR,
+ showWhilePlaying: input.showWhilePlaying ?? true,
+ },
+ };
+}
+
+export function toStoredCallToAction(
+ value: ShareCallToAction,
+): VideoCallToAction {
+ return {
+ label: value.label,
+ url: value.url,
+ ...(value.headline ? { headline: value.headline } : {}),
+ color: value.color,
+ showWhilePlaying: value.showWhilePlaying,
+ };
+}
+
+const isRecord = (value: unknown): value is Record<string, unknown> =>
+ typeof value === "object" && value !== null && !Array.isArray(value);
+
+export function parseShareCallToAction(
+ settings: unknown,
+): ShareCallToAction | null {
+ if (!isRecord(settings)) return null;
+ const stored = settings.callToAction;
+ if (!isRecord(stored)) return null;
+ if (typeof stored.label !== "string" || typeof stored.url !== "string") {
+ return null;
+ }
+
+ const result = validateCallToAction({
+ label: stored.label,
+ url: stored.url,
+ headline: typeof stored.headline === "string" ? stored.headline : null,
+ color: typeof stored.color === "string" ? stored.color : null,
+ showWhilePlaying:
+ typeof stored.showWhilePlaying === "boolean"
+ ? stored.showWhilePlaying
+ : undefined,
+ });
+ return result.ok ? result.value : null;
+}
+
+const channelToLinear = (channel: number) => {
+ const value = channel / 255;
+ return value <= 0.03928 ? value / 12.92 : ((value + 0.055) / 1.055) ** 2.4;
+};
+
+const relativeLuminance = (hex: string) => {
+ const value = Number.parseInt(hex.slice(1), 16);
+ const r = channelToLinear((value >> 16) & 0xff);
+ const g = channelToLinear((value >> 8) & 0xff);
+ const b = channelToLinear(value & 0xff);
+ return 0.2126 * r + 0.7152 * g + 0.0722 * b;
+};
+
+export function readableTextColor(color: string): "#FFFFFF" | "#111113" {
+ const hex = normalizeHexColor(color) ?? DEFAULT_CTA_COLOR;
+ const luminance = relativeLuminance(hex);
+ const contrastWithWhite = 1.05 / (luminance + 0.05);
+ const contrastWithInk = (luminance + 0.05) / 0.0555;
+ return contrastWithWhite >= contrastWithInk ? "#FFFFFF" : "#111113";
+}
+
+export function callToActionDestinationLabel(url: string): string {
+ try {
+ const parsed = new URL(url);
+ if (parsed.protocol === "mailto:") {
+ return decodeURIComponent(parsed.pathname);
+ }
+ return parsed.hostname.replace(/^www\./, "");
+ } catch {
+ return url;
+ }
+}
+
+export function shouldShowCornerCard({
+ cta,
+ width,
+ height,
+ dismissed,
+ pastIntro,
+ ended,
+}: {
+ cta: ShareCallToAction;
+ width: number;
+ height: number;
+ dismissed: boolean;
+ pastIntro: boolean;
+ ended: boolean;
+}) {
+ return (
+ cta.showWhilePlaying &&
+ !dismissed &&
+ !ended &&
+ pastIntro &&
+ width >= CORNER_CARD_MIN_WIDTH &&
+ height >= CORNER_CARD_MIN_HEIGHT
+ );
+}
diff --git a/packages/database/schema.ts b/packages/database/schema.ts
index 779e23725..8c19b1fd2 100644
--- a/packages/database/schema.ts
+++ b/packages/database/schema.ts
@@ -35,7 +35,11 @@ import {
import { relations } from "drizzle-orm/relations";
import { nanoIdLength } from "./helpers.ts";
-import type { VideoEditSpec, VideoMetadata } from "./types/index.ts";
+import type {
+ VideoCallToAction,
+ VideoEditSpec,
+ VideoMetadata,
+} from "./types/index.ts";
export type AuthApiKeySource = "desktop" | "extension" | "mobile" | "unknown";
@@ -442,6 +446,7 @@ export const videos = mysqlTable(
disableTranscript?: boolean;
disableComments?: boolean;
defaultPlaybackSpeed?: number;
+ callToAction?: VideoCallToAction;
}>(),
transcriptionStatus: varchar("transcriptionStatus", { length: 255 }).$type<
"PROCESSING" | "COMPLETE" | "ERROR" | "SKIPPED" | "NO_AUDIO"
diff --git a/packages/database/types/metadata.ts b/packages/database/types/metadata.ts
index b8e4c1df9..9712ba202 100644
--- a/packages/database/types/metadata.ts
+++ b/packages/database/types/metadata.ts
@@ -105,6 +105,14 @@ export interface VideoMetadata {
};
}
+export interface VideoCallToAction {
+ label: string;
+ url: string;
+ headline?: string;
+ color?: string;
+ showWhilePlaying?: boolean;
+}
+
export type VideoEditRange = {
start: number;
end: number;