Skip to content

armgit / Cap

Public Imported from GitHub
0

Open source Loom alternative. Beautiful, shareable screen recordings.

perf(web): add dependency-light share page modules

Richie McIlroyc7a08afa06ad
diff --git a/apps/web/__tests__/unit/from-now.test.ts b/apps/web/__tests__/unit/from-now.test.ts
new file mode 100644
index 000000000..617a6dcc1
--- /dev/null
+++ b/apps/web/__tests__/unit/from-now.test.ts
@@ -0,0 +1,70 @@
+import moment from "moment";
+import { describe, expect, it } from "vitest";
+import { fromNow } from "../../app/s/[videoId]/_components/utils/from-now";
+
+// `fromNow` replaced the share header's `moment(date).fromNow()` so the page
+// stops shipping moment; moment itself (still installed for other routes) is
+// the oracle that the replacement's bucket boundaries match exactly.
+describe("fromNow", () => {
+ const now = new Date("2026-08-07T12:00:00.000Z");
+
+ const offsetsSeconds = [
+ 0,
+ 1,
+ 44,
+ 45,
+ 89,
+ 90,
+ 91,
+ 60 * 44,
+ 60 * 45,
+ 60 * 89,
+ 60 * 90,
+ 60 * 91,
+ 3600 * 21,
+ 3600 * 22,
+ 3600 * 35,
+ 3600 * 36,
+ 3600 * 37,
+ 86400 * 25,
+ 86400 * 26,
+ 86400 * 44,
+ 86400 * 45,
+ 86400 * 46,
+ 86400 * 100,
+ 86400 * 319,
+ 86400 * 320,
+ 86400 * 547,
+ 86400 * 548,
+ 86400 * 549,
+ 86400 * 1000,
+ 86400 * 3650,
+ ];
+
+ it("matches moment.fromNow for past dates across every bucket boundary", () => {
+ for (const seconds of offsetsSeconds) {
+ const date = new Date(now.getTime() - seconds * 1000);
+ expect(fromNow(date, now), `offset -${seconds}s`).toBe(
+ moment(date).from(moment(now)),
+ );
+ }
+ });
+
+ it("matches moment.fromNow for future dates", () => {
+ for (const seconds of offsetsSeconds) {
+ const date = new Date(now.getTime() + seconds * 1000);
+ expect(fromNow(date, now), `offset +${seconds}s`).toBe(
+ moment(date).from(moment(now)),
+ );
+ }
+ });
+
+ it("sweeps four years of offsets against moment", () => {
+ for (let hours = 0; hours < 24 * 365 * 4; hours += 7) {
+ const date = new Date(now.getTime() - hours * 3600 * 1000);
+ expect(fromNow(date, now), `offset -${hours}h`).toBe(
+ moment(date).from(moment(now)),
+ );
+ }
+ });
+});
diff --git a/apps/web/app/(org)/dashboard/DashboardContext.ts b/apps/web/app/(org)/dashboard/DashboardContext.ts
new file mode 100644
index 000000000..b4c0e6e7a
--- /dev/null
+++ b/apps/web/app/(org)/dashboard/DashboardContext.ts
@@ -0,0 +1,64 @@
+"use client";
+
+import { createContext, useContext } from "react";
+import type { CurrentUser } from "@/app/Layout/AuthContext";
+import type {
+ Organization,
+ OrganizationSettings,
+ Spaces,
+ UserPreferences,
+} from "./dashboard-data";
+import type { DeveloperApp } from "./developers/developer-data";
+
+/**
+ * The context objects and hooks, split from `Contexts.tsx` so consumers
+ * outside the dashboard (the share page header reads it for shared spaces)
+ * don't drag the provider's dialog imports — InviteDialog, UpgradeModal and
+ * its Rive runtime — into their bundle.
+ */
+
+export type SharedContext = {
+ organizationData: Organization[] | null;
+ activeOrganization: Organization | null;
+ organizationSettings: OrganizationSettings | null;
+ spacesData: Spaces[] | null;
+ userSpaces: Spaces[] | null;
+ sharedSpaces: Spaces[] | null;
+ activeSpace: Spaces | null;
+ user: CurrentUser;
+ userCapsCount: number | null;
+ toggleSidebarCollapsed: () => void;
+ anyNewNotifications: boolean;
+ userPreferences: UserPreferences;
+ sidebarCollapsed: boolean;
+ upgradeModalOpen: boolean;
+ setUpgradeModalOpen: (open: boolean) => void;
+ inviteDialogOpen: boolean;
+ setInviteDialogOpen: (open: boolean) => void;
+ referClickedState: boolean;
+ setReferClickedStateHandler: (referClicked: boolean) => void;
+ isDeveloperSection: boolean;
+ developerApps: DeveloperApp[] | null;
+ setDeveloperApps: (apps: DeveloperApp[] | null) => void;
+};
+
+export type ITheme = "light" | "dark";
+export type SetThemeOptions = {
+ persist?: boolean;
+};
+
+export const DashboardContext = createContext<SharedContext>(
+ {} as SharedContext,
+);
+
+export const ThemeContext = createContext<{
+ theme: ITheme;
+ setThemeHandler: (newTheme: ITheme, options?: SetThemeOptions) => void;
+}>({
+ theme: "light",
+ setThemeHandler: () => {},
+});
+
+export const useTheme = () => useContext(ThemeContext);
+
+export const useDashboardContext = () => useContext(DashboardContext);
diff --git a/apps/web/app/s/[videoId]/_components/AuthOverlayLazy.tsx b/apps/web/app/s/[videoId]/_components/AuthOverlayLazy.tsx
new file mode 100644
index 000000000..a933d20b3
--- /dev/null
+++ b/apps/web/app/s/[videoId]/_components/AuthOverlayLazy.tsx
@@ -0,0 +1,25 @@
+"use client";
+
+import dynamic from "next/dynamic";
+import { useEffect, useState } from "react";
+
+const AuthOverlayInner = dynamic(
+ () => import("./AuthOverlay").then((m) => m.AuthOverlay),
+ { ssr: false },
+);
+
+/**
+ * Drop-in for `AuthOverlay` that keeps its chunk (next-auth, the OTP form) off
+ * the wire until a signed-out viewer actually hits an auth wall. Latched on
+ * first open so closing still plays the dialog's exit animation.
+ */
+export function AuthOverlay(props: { isOpen: boolean; onClose: () => void }) {
+ const [mounted, setMounted] = useState(props.isOpen);
+
+ useEffect(() => {
+ if (props.isOpen) setMounted(true);
+ }, [props.isOpen]);
+
+ if (!mounted) return null;
+ return <AuthOverlayInner {...props} />;
+}
diff --git a/apps/web/app/s/[videoId]/_components/DeleteCapDialog.tsx b/apps/web/app/s/[videoId]/_components/DeleteCapDialog.tsx
new file mode 100644
index 000000000..e3acd28cc
--- /dev/null
+++ b/apps/web/app/s/[videoId]/_components/DeleteCapDialog.tsx
@@ -0,0 +1,57 @@
+"use client";
+
+import type { Video } from "@cap/web-domain";
+import { faVideo } from "@fortawesome/free-solid-svg-icons";
+import { FontAwesomeIcon } from "@fortawesome/react-fontawesome";
+import { useRouter } from "next/navigation";
+import { toast } from "sonner";
+import { ConfirmationDialog } from "@/app/(org)/dashboard/_components/ConfirmationDialog";
+import { useEffectMutation, useRpcClient } from "@/lib/EffectRuntime";
+
+/**
+ * The owner's delete confirmation, self-contained so its RPC mutation — and
+ * the Effect runtime it drags along — loads only once deletion is actually
+ * requested, not on every share-page view.
+ */
+export default function DeleteCapDialog({
+ open,
+ videoId,
+ videoTitle,
+ onClose,
+}: {
+ open: boolean;
+ videoId: Video.VideoId;
+ videoTitle: string;
+ onClose: () => void;
+}) {
+ const { push } = useRouter();
+ const rpc = useRpcClient();
+
+ const deleteMutation = useEffectMutation({
+ mutationFn: () => rpc.VideoDelete(videoId),
+ onSuccess: () => {
+ toast.success("Cap deleted successfully");
+ push("/dashboard/caps?page=1");
+ },
+ onError: () => {
+ toast.error("Failed to delete Cap");
+ },
+ onSettled: () => {
+ onClose();
+ },
+ });
+
+ return (
+ <ConfirmationDialog
+ open={open}
+ icon={<FontAwesomeIcon icon={faVideo} />}
+ title="Delete Cap"
+ description={`Are you sure you want to delete the cap "${videoTitle}"? This action cannot be undone.`}
+ confirmLabel={deleteMutation.isPending ? "Deleting..." : "Delete"}
+ confirmVariant="destructive"
+ loading={deleteMutation.isPending}
+ onConfirm={() => deleteMutation.mutate()}
+ onCancel={onClose}
+ />
+ );
+}
diff --git a/apps/web/app/s/[videoId]/_components/DuplicateCapMenuItem.tsx b/apps/web/app/s/[videoId]/_components/DuplicateCapMenuItem.tsx
new file mode 100644
index 000000000..168cda894
--- /dev/null
+++ b/apps/web/app/s/[videoId]/_components/DuplicateCapMenuItem.tsx
@@ -0,0 +1,53 @@
+"use client";
+
+import { DropdownMenuItem } from "@cap/ui";
+import type { Video } from "@cap/web-domain";
+import { faCopy } from "@fortawesome/free-solid-svg-icons";
+import { FontAwesomeIcon } from "@fortawesome/react-fontawesome";
+import { useIsMutating } from "@tanstack/react-query";
+import { toast } from "sonner";
+import { useEffectMutation, useRpcClient } from "@/lib/EffectRuntime";
+
+/**
+ * The "Duplicate Cap" row of the owner menu, self-contained so its RPC
+ * mutation — and the Effect runtime it drags along — loads only when the menu
+ * is actually opened, not on every share-page view.
+ */
+export default function DuplicateCapMenuItem({
+ videoId,
+ disabled,
+}: {
+ videoId: Video.VideoId;
+ disabled?: boolean;
+}) {
+ const rpc = useRpcClient();
+
+ const duplicateMutation = useEffectMutation({
+ mutationKey: ["videoDuplicate", videoId],
+ mutationFn: () => rpc.VideoDuplicate(videoId),
+ onSuccess: () => {
+ toast.success("Cap duplicated successfully");
+ },
+ onError: () => {
+ toast.error("Failed to duplicate Cap");
+ },
+ });
+ // Read pending state through the cache, not the hook instance: the menu
+ // content remounts every time it opens, and a fresh instance would forget
+ // an in-flight duplication and allow a second one.
+ const isDuplicating =
+ useIsMutating({ mutationKey: ["videoDuplicate", videoId] }) > 0;
+
+ return (
+ <DropdownMenuItem
+ onClick={() => duplicateMutation.mutate()}
+ disabled={isDuplicating || disabled}
+ className="flex items-center gap-2 rounded-lg"
+ >
+ <FontAwesomeIcon className="size-3" icon={faCopy} />
+ <p className="text-sm text-gray-12">
+ {isDuplicating ? "Duplicating..." : "Duplicate Cap"}
+ </p>
+ </DropdownMenuItem>
+ );
+}
diff --git a/apps/web/app/s/[videoId]/_components/UploadProgressTracker.tsx b/apps/web/app/s/[videoId]/_components/UploadProgressTracker.tsx
new file mode 100644
index 000000000..3f28b9b1c
--- /dev/null
+++ b/apps/web/app/s/[videoId]/_components/UploadProgressTracker.tsx
@@ -0,0 +1,28 @@
+"use client";
+
+import type { Video } from "@cap/web-domain";
+import { useEffect } from "react";
+import { useUploadProgress } from "./ProgressCircle";
+import type { UploadProgress } from "./upload-progress";
+
+/**
+ * Headless bridge around `useUploadProgress`. The hook's RPC client pulls the
+ * Effect runtime with it, so the players mount this (dynamically imported)
+ * only while a video actually has a live upload — every finished video skips
+ * the chunk entirely.
+ */
+export default function UploadProgressTracker({
+ videoId,
+ onChange,
+}: {
+ videoId: Video.VideoId;
+ onChange: (progress: UploadProgress | null) => void;
+}) {
+ const progress = useUploadProgress(videoId, true);
+
+ useEffect(() => {
+ onChange(progress);
+ }, [progress, onChange]);
+
+ return null;
+}
diff --git a/apps/web/app/s/[videoId]/_components/upload-progress.ts b/apps/web/app/s/[videoId]/_components/upload-progress.ts
new file mode 100644
index 000000000..4a51bdbba
--- /dev/null
+++ b/apps/web/app/s/[videoId]/_components/upload-progress.ts
@@ -0,0 +1,123 @@
+/**
+ * Pure upload-progress state helpers, split from `ProgressCircle.tsx` so the
+ * players can reason about upload state without importing `useUploadProgress`
+ * — whose RPC client drags the whole Effect runtime into the bundle. Only
+ * `UploadProgressTracker` (mounted while an upload is actually live) pays for
+ * that chunk.
+ */
+
+export type UploadProgress =
+ | { status: "fetching" }
+ | {
+ status: "uploading";
+ lastUpdated: Date;
+ progress: number;
+ }
+ | {
+ status: "processing";
+ lastUpdated: Date;
+ progress: number;
+ message: string | null;
+ }
+ | {
+ status: "generating_thumbnail";
+ lastUpdated: Date;
+ progress: number;
+ }
+ | {
+ status: "error";
+ lastUpdated: Date;
+ errorMessage: string | null;
+ hasRawFallback: boolean;
+ }
+ | {
+ status: "failed";
+ lastUpdated: Date;
+ };
+
+export function shouldDeferPlaybackSource(
+ uploadProgress: UploadProgress | null,
+): boolean {
+ return (
+ uploadProgress?.status === "fetching" ||
+ uploadProgress?.status === "uploading"
+ );
+}
+
+export function shouldReloadPlaybackAfterUploadCompletes(
+ previousUploadProgress: UploadProgress | null,
+ uploadProgress: UploadProgress | null,
+ options: { includeFetching?: boolean } = {},
+): boolean {
+ return (
+ previousUploadProgress !== null &&
+ (options.includeFetching || previousUploadProgress.status !== "fetching") &&
+ uploadProgress === null
+ );
+}
+
+export function canRetryFailedProcessing(
+ uploadProgress: UploadProgress | null,
+ canRetryProcessing: boolean,
+): boolean {
+ return canRetryProcessing && uploadProgress?.status === "error";
+}
+
+export function getUploadFailureMessage(
+ uploadProgress: UploadProgress | null,
+ canRetryProcessing: boolean,
+): string {
+ if (uploadProgress?.status === "error") {
+ if (canRetryFailedProcessing(uploadProgress, canRetryProcessing)) {
+ return uploadProgress.errorMessage || "Processing failed.";
+ }
+
+ return (
+ uploadProgress.errorMessage ||
+ "Processing failed. Ask the owner to retry processing or re-upload the recording."
+ );
+ }
+
+ return "Upload stalled before processing finished. Re-upload the recording to continue.";
+}
+
+export const SECOND = 1000;
+export const MINUTE = 60 * SECOND;
+export const HOUR = 60 * 60 * SECOND;
+export const DAY = 24 * HOUR;
+const STALE_PROCESSING_START_MS = 90 * SECOND;
+const STALE_PROCESSING_PROGRESS_MS = 10 * MINUTE;
+const STALE_THUMBNAIL_MS = 5 * MINUTE;
+
+export function getStalledProcessingMessage(input: {
+ phase:
+ | "uploading"
+ | "processing"
+ | "generating_thumbnail"
+ | "complete"
+ | "error";
+ updatedAt: Date;
+ processingProgress: number;
+}): string | null {
+ const ageMs = Date.now() - input.updatedAt.getTime();
+
+ if (input.phase === "processing") {
+ if (input.processingProgress === 0 && ageMs > STALE_PROCESSING_START_MS) {
+ return "Video processing did not start. Retry processing.";
+ }
+
+ if (ageMs > STALE_PROCESSING_PROGRESS_MS) {
+ return "Video processing stalled. Retry processing.";
+ }
+ }
+
+ if (input.phase === "generating_thumbnail" && ageMs > STALE_THUMBNAIL_MS) {
+ return "Video finishing stalled. Retry processing.";
+ }
+
+ if (input.phase === "complete" && ageMs > STALE_THUMBNAIL_MS) {
+ return "Video finishing stalled. Retry processing.";
+ }
+
+ return null;
+}
diff --git a/apps/web/app/s/[videoId]/_components/utils/from-now.ts b/apps/web/app/s/[videoId]/_components/utils/from-now.ts
new file mode 100644
index 000000000..5f358de8c
--- /dev/null
+++ b/apps/web/app/s/[videoId]/_components/utils/from-now.ts
@@ -0,0 +1,85 @@
+/**
+ * Drop-in replacement for `moment(date).fromNow()` (en locale), which was the
+ * share page's only moment call — and shipped all of moment plus every locale
+ * (~75 KB gzipped) to say "3 days ago".
+ *
+ * Replicates moment's actual pipeline for `a.from(b)`: the difference is
+ * split into whole calendar months plus a millisecond remainder
+ * (`positiveMomentsDifference`), then each unit is independently rounded the
+ * way `duration.humanize()` does — months convert to days at moment's
+ * 30.436875-day Gregorian average, thresholds are s=44, m=45, h=22, d=26,
+ * M=11. Parity is pinned by `__tests__/unit/from-now.test.ts`, which sweeps
+ * the boundaries with moment itself as the oracle.
+ */
+
+const MS_PER_SECOND = 1000;
+const MS_PER_MINUTE = 60 * MS_PER_SECOND;
+const MS_PER_HOUR = 60 * MS_PER_MINUTE;
+const MS_PER_DAY = 24 * MS_PER_HOUR;
+// Days per month averaged over the 400-year Gregorian cycle (146097 / 4800).
+const DAYS_PER_MONTH = 146097 / 4800;
+
+const daysInMonth = (year: number, month: number) =>
+ new Date(year, month + 1, 0).getDate();
+
+/** Month addition with moment's semantics: day-of-month clamps to month end. */
+const addMonths = (date: Date, months: number): Date => {
+ const result = new Date(date.getTime());
+ const day = result.getDate();
+ result.setDate(1);
+ result.setMonth(result.getMonth() + months);
+ result.setDate(
+ Math.min(day, daysInMonth(result.getFullYear(), result.getMonth())),
+ );
+ return result;
+};
+
+export function fromNow(date: Date, now: Date = new Date()): string {
+ const inPast = now.getTime() - date.getTime() >= 0;
+ const [from, to] = inPast ? [date, now] : [now, date];
+
+ // moment's positiveMomentsDifference: whole calendar months + remainder ms.
+ let wholeMonths =
+ (to.getFullYear() - from.getFullYear()) * 12 +
+ (to.getMonth() - from.getMonth());
+ if (addMonths(from, wholeMonths).getTime() > to.getTime()) wholeMonths--;
+ const remainderMs = to.getTime() - addMonths(from, wholeMonths).getTime();
+
+ // For second/minute/hour/day units, moment first converts the month part
+ // to a WHOLE number of average-length days.
+ const smallUnitsMs =
+ remainderMs + Math.round(wholeMonths * DAYS_PER_MONTH) * MS_PER_DAY;
+ const seconds = Math.round(smallUnitsMs / MS_PER_SECOND);
+ const minutes = Math.round(smallUnitsMs / MS_PER_MINUTE);
+ const hours = Math.round(smallUnitsMs / MS_PER_HOUR);
+ const days = Math.round(smallUnitsMs / MS_PER_DAY);
+ // For month/year units, the remainder converts to fractional months.
+ const monthsExact = wholeMonths + remainderMs / MS_PER_DAY / DAYS_PER_MONTH;
+ const months = Math.round(monthsExact);
+ const years = Math.round(monthsExact / 12);
+
+ const phrase =
+ seconds <= 44
+ ? "a few seconds"
+ : minutes <= 1
+ ? "a minute"
+ : minutes < 45
+ ? `${minutes} minutes`
+ : hours <= 1
+ ? "an hour"
+ : hours < 22
+ ? `${hours} hours`
+ : days <= 1
+ ? "a day"
+ : days < 26
+ ? `${days} days`
+ : months <= 1
+ ? "a month"
+ : months < 11
+ ? `${months} months`
+ : years <= 1
+ ? "a year"
+ : `${years} years`;
+
+ return inPast ? `${phrase} ago` : `in ${phrase}`;
+}