Open source Loom alternative. Beautiful, shareable screen recordings.
Rust appcapcossloommacnextjsnextjs15open-sourceossreactrecordrustscreen-capturescreen-recorderscreenshotsolidjstauritauri-apptypescriptvite
feat(web): add share audience and social embed helpers
Richie McIlroy047fc25bfab4
diff --git a/apps/web/__tests__/unit/share-audience.test.ts b/apps/web/__tests__/unit/share-audience.test.tsnew file mode 100644index 000000000..4daa5816d--- /dev/null+++ b/apps/web/__tests__/unit/share-audience.test.ts@@ -0,0 +1,102 @@+import { describe, expect, it } from "vitest";+import { describeShareAudience } from "@/app/s/[videoId]/_components/share-audience";++describe("describeShareAudience", () => {+ it("names the public link as the widest audience, even when spaces are attached", () => {+ const audience = describeShareAudience({+ isPublic: true,+ passwordProtected: false,+ audienceNames: ["Design"],+ });++ expect(audience.kind).toBe("public");+ expect(audience.label).toBe("Anyone with the link");+ expect(audience.tooltip).toContain("outside your organization");+ });++ it("says a password is required when the public link is locked", () => {+ const audience = describeShareAudience({+ isPublic: true,+ passwordProtected: true,+ audienceNames: [],+ });++ expect(audience.label).toBe("Anyone with the password");+ });++ it("names a single space", () => {+ const audience = describeShareAudience({+ isPublic: false,+ passwordProtected: false,+ audienceNames: ["Design"],+ });++ expect(audience.kind).toBe("spaces");+ expect(audience.label).toBe("Shared with Design");+ expect(audience.tooltip).toContain("Only members of Design");+ });++ it("names both when there are two", () => {+ const audience = describeShareAudience({+ isPublic: false,+ passwordProtected: false,+ audienceNames: ["Design", "Marketing"],+ });++ expect(audience.label).toBe("Shared with Design and Marketing");+ });++ it("counts the rest past two, without claiming they are all spaces", () => {+ const audience = describeShareAudience({+ isPublic: false,+ passwordProtected: false,+ audienceNames: ["Acme Inc", "Design", "Marketing", "Support"],+ });++ expect(audience.label).toBe("Shared with Acme Inc and 3 others");+ expect(audience.tooltip).toContain("Design and 2 more");+ });++ it("uses the singular for exactly one other", () => {+ const audience = describeShareAudience({+ isPublic: false,+ passwordProtected: false,+ audienceNames: ["Design", null],+ });++ expect(audience.label).toBe("Shared with Design and 1 other");+ });++ it("still counts entries whose name never arrived", () => {+ const audience = describeShareAudience({+ isPublic: false,+ passwordProtected: false,+ audienceNames: ["Design", null, undefined],+ });++ expect(audience.label).toBe("Shared with Design and 2 others");+ });++ it("falls back to a count when no name came through", () => {+ const audience = describeShareAudience({+ isPublic: false,+ passwordProtected: false,+ audienceNames: [null, ""],+ });++ expect(audience.label).toBe("Shared with 2 spaces");+ expect(audience.tooltip).toContain("the spaces this is shared with");+ });++ it("says nobody can see it when it is shared nowhere", () => {+ const audience = describeShareAudience({+ isPublic: false,+ passwordProtected: false,+ audienceNames: [],+ });++ expect(audience.kind).toBe("private");+ expect(audience.label).toBe("Only you");+ expect(audience.tooltip).toContain("Click to share it");+ });+});diff --git a/apps/web/__tests__/unit/social-share.test.ts b/apps/web/__tests__/unit/social-share.test.tsnew file mode 100644index 000000000..73a8bb5c7--- /dev/null+++ b/apps/web/__tests__/unit/social-share.test.ts@@ -0,0 +1,123 @@+import { describe, expect, it } from "vitest";+import {+ shareTargetHref,+ shareUrlWithTimestamp,+ socialShareUrl,+} from "@/lib/social-share";++const URL_UNDER_TEST = "https://cap.so/s/abc123";++/**+ * These assert the exact third-party contracts. A share intent with a wrong+ * parameter name doesn't error — it opens an empty composer — so nothing else+ * in the stack catches a typo here.+ */+describe("shareTargetHref", () => {+ it("points LinkedIn at share-offsite with the encoded url", () => {+ expect(+ shareTargetHref({+ target: "linkedin",+ url: URL_UNDER_TEST,+ title: "My Cap",+ }),+ ).toBe(+ "https://www.linkedin.com/sharing/share-offsite/?url=https%3A%2F%2Fcap.so%2Fs%2Fabc123",+ );+ });++ it("posts to X with both url and text", () => {+ expect(+ shareTargetHref({ target: "x", url: URL_UNDER_TEST, title: "My Cap" }),+ ).toBe(+ "https://x.com/intent/post?url=https%3A%2F%2Fcap.so%2Fs%2Fabc123&text=My%20Cap",+ );+ });++ it("uses the Facebook sharer `u` parameter", () => {+ expect(+ shareTargetHref({+ target: "facebook",+ url: URL_UNDER_TEST,+ title: "My Cap",+ }),+ ).toBe(+ "https://www.facebook.com/sharer/sharer.php?u=https%3A%2F%2Fcap.so%2Fs%2Fabc123",+ );+ });++ it("opens a Gmail compose window with the link in the body", () => {+ const href = shareTargetHref({+ target: "gmail",+ url: URL_UNDER_TEST,+ title: "My Cap",+ });+ expect(href.startsWith("https://mail.google.com/mail/?view=cm&fs=1&")).toBe(+ true,+ );+ expect(href).toContain("su=My%20Cap");+ // Gmail only unfurls a preview when the URL is in the body.+ expect(href).toContain(encodeURIComponent(URL_UNDER_TEST));+ });++ it("escapes titles that would otherwise break the query string", () => {+ const href = shareTargetHref({+ target: "x",+ url: URL_UNDER_TEST,+ title: "Q3 review & retro?",+ });+ expect(href).toContain("text=Q3%20review%20%26%20retro%3F");+ });+});++describe("shareUrlWithTimestamp", () => {+ it("adds `t` in seconds", () => {+ expect(shareUrlWithTimestamp(URL_UNDER_TEST, 83)).toBe(+ "https://cap.so/s/abc123?t=83",+ );+ });++ it("floors fractional positions", () => {+ expect(shareUrlWithTimestamp(URL_UNDER_TEST, 83.94)).toBe(+ "https://cap.so/s/abc123?t=83",+ );+ });++ it("keeps existing query params and replaces an existing `t`", () => {+ expect(+ shareUrlWithTimestamp("https://cap.so/s/abc123?t=5&autoplay=true", 42),+ ).toBe("https://cap.so/s/abc123?t=42&autoplay=true");+ });++ it("clamps negative and non-finite positions to zero", () => {+ expect(shareUrlWithTimestamp(URL_UNDER_TEST, -12)).toBe(+ "https://cap.so/s/abc123?t=0",+ );+ expect(shareUrlWithTimestamp(URL_UNDER_TEST, Number.NaN)).toBe(+ "https://cap.so/s/abc123?t=0",+ );+ });+});++describe("socialShareUrl", () => {+ it("leaves the url alone without a timestamp", () => {+ expect(socialShareUrl({ url: URL_UNDER_TEST })).toBe(URL_UNDER_TEST);+ });++ it("rewrites cap.link short links to their crawlable canonical form", () => {+ expect(socialShareUrl({ url: "https://cap.link/abc123" })).toBe(+ "https://cap.so/s/abc123",+ );+ });++ it("applies the timestamp after canonicalising", () => {+ expect(+ socialShareUrl({ url: "https://cap.link/abc123", timestamp: 7 }),+ ).toBe("https://cap.so/s/abc123?t=7");+ });++ it("preserves custom domains", () => {+ expect(+ socialShareUrl({ url: "https://videos.acme.com/s/abc123", timestamp: 9 }),+ ).toBe("https://videos.acme.com/s/abc123?t=9");+ });+});diff --git a/apps/web/app/s/[videoId]/_components/share-audience.ts b/apps/web/app/s/[videoId]/_components/share-audience.tsnew file mode 100644index 000000000..1cc3a05a4--- /dev/null+++ b/apps/web/app/s/[videoId]/_components/share-audience.ts@@ -0,0 +1,83 @@+/**+ * Who can watch a Cap, in words.+ *+ * The header used to say "Shared" or "Not shared", which told the owner+ * nothing: not whether the public link was on, not who a share reached. This+ * names the widest audience the video currently has, and the tooltip spells+ * out what that means for the link.+ */++export type ShareAudienceKind = "public" | "spaces" | "private";++export interface ShareAudience {+ kind: ShareAudienceKind;+ label: string;+ tooltip: string;+}++export interface ShareAudienceInput {+ isPublic: boolean;+ /** Includes an inherited password from a space or organization. */+ passwordProtected: boolean;+ /**+ * Names of the spaces and organizations this is shared into. Unnamed+ * entries are counted but not listed, so a missing name degrades to+ * "Shared with 2 spaces" rather than printing an empty one.+ */+ audienceNames: (string | null | undefined)[];+}++const listNames = (names: string[], total: number): string => {+ if (names.length === 1 && total === 1) return `Shared with ${names[0]}`;+ if (names.length === 2 && total === 2)+ return `Shared with ${names[0]} and ${names[1]}`;+ if (names.length >= 1)+ return `Shared with ${names[0]} and ${total - 1} ${+ total - 1 === 1 ? "other" : "others"+ }`;+ return `Shared with ${total} ${total === 1 ? "space" : "spaces"}`;+};++export const describeShareAudience = ({+ isPublic,+ passwordProtected,+ audienceNames,+}: ShareAudienceInput): ShareAudience => {+ if (isPublic) {+ return {+ kind: "public",+ label: passwordProtected+ ? "Anyone with the password"+ : "Anyone with the link",+ tooltip: passwordProtected+ ? "Anyone who has this link and the password can watch this Cap."+ : "Anyone who has this link can watch this Cap, including people outside your organization.",+ };+ }++ const named = audienceNames.filter(+ (name): name is string => typeof name === "string" && name.trim() !== "",+ );+ const total = audienceNames.length;++ if (total > 0) {+ const listed = named.slice(0, 2);+ const remainder = total - listed.length;+ return {+ kind: "spaces",+ label: listNames(listed, total),+ tooltip: listed.length+ ? `Only members of ${listed.join(", ")}${+ remainder > 0 ? ` and ${remainder} more` : ""+ } can watch this Cap. The link won't work for anyone else.`+ : "Only members of the spaces this is shared with can watch this Cap. The link won't work for anyone else.",+ };+ }++ return {+ kind: "private",+ label: "Only you",+ tooltip:+ "Nobody else can watch this Cap yet. Click to share it with a space or turn on the public link.",+ };+};diff --git a/apps/web/components/icons/Social.tsx b/apps/web/components/icons/Social.tsxnew file mode 100644index 000000000..b5ca9a1ee--- /dev/null+++ b/apps/web/components/icons/Social.tsx@@ -0,0 +1,92 @@+/**+ * Official brand marks for the share targets.+ *+ * Inlined rather than served from `public/` so opening the share dialog costs+ * zero network requests, and so they inherit the surrounding size/colour+ * classes. Path data is the vendors' own artwork — the brand colours are+ * hard-coded on purpose (a recoloured Google "G" reads as broken, and every one+ * of these companies' brand guidelines forbids it). X is the exception: its+ * mark is monochrome, so it follows `currentColor` and survives dark mode.+ */++interface SocialIconProps {+ className?: string;+}++export const LinkedInIcon = ({ className }: SocialIconProps) => (+ <svg+ xmlns="http://www.w3.org/2000/svg"+ viewBox="0 0 24 24"+ aria-hidden="true"+ focusable="false"+ className={className}+ >+ <path+ fill="#0A66C2"+ d="M20.447 20.452h-3.554v-5.569c0-1.328-.027-3.037-1.852-3.037-1.853 0-2.136 1.445-2.136 2.939v5.667H9.351V9h3.414v1.561h.046c.477-.9 1.637-1.85 3.37-1.85 3.601 0 4.267 2.37 4.267 5.455v6.286zM5.337 7.433a2.062 2.062 0 1 1 0-4.125 2.062 2.062 0 0 1 0 4.125zm1.782 13.019H3.555V9h3.564v11.452zM22.225 0H1.771C.792 0 0 .774 0 1.729v20.542C0 23.227.792 24 1.771 24h20.451C23.2 24 24 23.227 24 22.271V1.729C24 .774 23.2 0 22.222 0h.003z"+ />+ </svg>+);++export const XIcon = ({ className }: SocialIconProps) => (+ <svg+ xmlns="http://www.w3.org/2000/svg"+ viewBox="0 0 1200 1227"+ aria-hidden="true"+ focusable="false"+ className={className}+ >+ <path+ fill="currentColor"+ d="M714.163 519.284 1160.89 0h-105.86L667.137 450.887 357.328 0H0l468.492 681.821L0 1226.37h105.866l409.625-476.152 327.181 476.152H1200L714.137 519.284h.026zM569.165 687.828l-47.468-67.894-377.686-540.24h162.604l304.797 435.991 47.468 67.894 396.2 566.721H892.476L569.165 687.854v-.026z"+ />+ </svg>+);++export const FacebookIcon = ({ className }: SocialIconProps) => (+ <svg+ xmlns="http://www.w3.org/2000/svg"+ viewBox="0 0 24 24"+ aria-hidden="true"+ focusable="false"+ className={className}+ >+ <path+ fill="#1877F2"+ d="M24 12.073C24 5.446 18.627 0 12 0S0 5.446 0 12.073c0 5.99 4.388 10.954 10.125 11.854v-8.385H7.078v-3.469h3.047V9.43c0-3.007 1.792-4.669 4.533-4.669 1.312 0 2.686.235 2.686.235v2.953H15.83c-1.491 0-1.956.925-1.956 1.874v2.25h3.328l-.532 3.469h-2.796v8.385C19.612 23.027 24 18.062 24 12.073z"+ />+ </svg>+);++/**+ * The Google "G" — four flat colours, no gradients. Used for the Gmail target+ * because Gmail's own mark is the envelope, and the "G" is what Google's own+ * "share to Gmail" surfaces use.+ */+export const GoogleIcon = ({ className }: SocialIconProps) => (+ <svg+ xmlns="http://www.w3.org/2000/svg"+ viewBox="-3 0 262 262"+ preserveAspectRatio="xMidYMid"+ aria-hidden="true"+ focusable="false"+ className={className}+ >+ <path+ fill="#4285F4"+ d="M255.878 133.451c0-10.734-.871-18.567-2.756-26.69H130.55v48.448h71.947c-1.45 12.04-9.283 30.172-26.69 42.356l-.244 1.622 38.755 30.023 2.685.268c24.659-22.774 38.875-56.282 38.875-96.027"+ />+ <path+ fill="#34A853"+ d="M130.55 261.1c35.248 0 64.839-11.605 86.453-31.622l-41.196-31.913c-11.024 7.688-25.82 13.055-45.257 13.055-34.523 0-63.824-22.773-74.269-54.25l-1.531.13-40.298 31.187-.527 1.465C35.393 231.798 79.49 261.1 130.55 261.1"+ />+ <path+ fill="#FBBC05"+ d="M56.281 156.37c-2.756-8.123-4.351-16.827-4.351-25.82 0-8.994 1.595-17.697 4.206-25.82l-.073-1.73L15.26 71.312l-1.335.635C5.077 89.644 0 109.517 0 130.55s5.077 40.905 13.925 58.602l42.356-32.782"+ />+ <path+ fill="#EB4335"+ d="M130.55 50.479c24.514 0 41.05 10.589 50.479 19.438l36.844-35.974C195.245 12.91 165.798 0 130.55 0 79.49 0 35.393 29.301 13.925 71.947l42.211 32.783c10.59-31.477 39.891-54.251 74.414-54.251"+ />+ </svg>+);diff --git a/apps/web/lib/embed-code.ts b/apps/web/lib/embed-code.tsnew file mode 100644index 000000000..1b9bc4112--- /dev/null+++ b/apps/web/lib/embed-code.ts@@ -0,0 +1,38 @@+/**+ * The `<iframe>` snippet handed out by every "Embed" surface. Shared so the+ * dashboard's sharing dialog and the share page's share dialog can't drift+ * apart — an embed that works in one place and not the other is the kind of+ * bug nobody reports, they just stop embedding.+ */+export const buildEmbedCode = ({+ webUrl,+ videoId,+ startTime,+}: {+ webUrl: string;+ videoId: string;+ /** Seconds to start playback at, if the sharer picked a moment. */+ startTime?: number | null;+}): string => {+ const start =+ typeof startTime === "number" && Number.isFinite(startTime) && startTime > 0+ ? `?t=${Math.floor(startTime)}`+ : "";++ return `+ <div style="position: relative; padding-bottom: 56.25%; height: 0;">+ <iframe+ src="${webUrl}/embed/${videoId}${start}"+ frameborder="0"+ webkitallowfullscreen+ mozallowfullscreen+ allowfullscreen+ style="position: absolute; top: 0; left: 0; width: 100%; height: 100%;"+ ></iframe>+ </div>+`+ .trim()+ .replace(/[\n\t]+/g, " ")+ .replace(/>\s+</g, "><")+ .replace(/"\s+>/g, '">');+};diff --git a/apps/web/lib/social-share.ts b/apps/web/lib/social-share.tsnew file mode 100644index 000000000..1b85a92ea--- /dev/null+++ b/apps/web/lib/social-share.ts@@ -0,0 +1,80 @@+/**+ * Share-target URL builders for the video share dialog.+ *+ * Deliberately React-free so the shapes can be unit tested. Every one of these+ * is a third-party contract that fails *silently* in the UI — a mistyped+ * parameter name doesn't throw, it just opens an empty composer on the other+ * end — so the tests are the only thing standing between a typo and a broken+ * share button.+ */++import { canonicalVideoShareUrl } from "./video-share-clipboard";++export type ShareTargetId = "linkedin" | "x" | "facebook" | "gmail";++/**+ * Adds (or replaces) the `?t=` start offset the share page reads on load.+ * Seconds are floored to an integer because that's what `Share.tsx` parses.+ */+export const shareUrlWithTimestamp = (url: string, seconds: number): string => {+ const start =+ Number.isFinite(seconds) && seconds > 0 ? Math.floor(seconds) : 0;+ try {+ const parsed = new URL(url);+ parsed.searchParams.set("t", String(start));+ return parsed.toString();+ } catch {+ // Not absolute (shouldn't happen for share links, but never break copy).+ const separator = url.includes("?") ? "&" : "?";+ return `${url}${separator}t=${start}`;+ }+};++/**+ * The URL handed to third parties. `cap.link` short links are rewritten to+ * their `cap.so` canonical form: the crawlers behind these previews follow+ * redirects inconsistently, and an unfurl that resolves to nothing is worse+ * than a longer URL.+ */+export const socialShareUrl = ({+ url,+ timestamp,+}: {+ url: string;+ timestamp?: number | null;+}): string => {+ const canonical = canonicalVideoShareUrl(url);+ return typeof timestamp === "number"+ ? shareUrlWithTimestamp(canonical, timestamp)+ : canonical;+};++export const shareTargetHref = ({+ target,+ url,+ title,+}: {+ target: ShareTargetId;+ url: string;+ title: string;+}): string => {+ const link = encodeURIComponent(url);++ switch (target) {+ case "linkedin":+ // share-offsite takes the URL only — LinkedIn dropped support for+ // prefilled text years ago and silently ignores any `title`/`summary`.+ return `https://www.linkedin.com/sharing/share-offsite/?url=${link}`;+ case "x":+ return `https://x.com/intent/post?url=${link}&text=${encodeURIComponent(title)}`;+ case "facebook":+ return `https://www.facebook.com/sharer/sharer.php?u=${link}`;+ case "gmail":+ // `view=cm&fs=1` is Gmail's compose deep link. Sending the URL in the+ // body (rather than only the subject) is what makes Gmail unfurl it+ // into a preview card.+ return `https://mail.google.com/mail/?view=cm&fs=1&su=${encodeURIComponent(+ title,+ )}&body=${encodeURIComponent(`${title}\n\n${url}`)}`;+ }+};