Skip to content

armgit / Cap

Public Imported from GitHub
0

Open source Loom alternative. Beautiful, shareable screen recordings.

14.0 KB
Raw Blame
"use client";

import type { userSelectProps } from "@cap/database/auth/session";
import type { comments as commentsSchema, videos } from "@cap/database/schema";
import { NODE_ENV } from "@cap/env";
import { Avatar, Logo } from "@cap/ui";
import type { ViewerSettings } from "@cap/web-backend";
import { useTranscript } from "hooks/use-transcript";
import { AnimatePresence, motion } from "motion/react";
import dynamic from "next/dynamic";
import Image from "next/image";
import {
	forwardRef,
	useCallback,
	useEffect,
	useImperativeHandle,
	useRef,
	useState,
} from "react";
import {
	PreparingVideoOverlay,
	RecordingInProgressOverlay,
} from "@/app/s/[videoId]/_components/RecordingInProgress";
import type { UploadProgress } from "@/app/s/[videoId]/_components/upload-progress";
import {
	formatChaptersAsVTT,
	formatTranscriptAsVTT,
	parseVTT,
	type TranscriptEntry,
} from "@/app/s/[videoId]/_components/utils/transcript-utils";
import { formatPlayerTime } from "@/lib/player-time";
import type { SharePageBranding } from "@/lib/share-branding";
import type { ShareCallToAction } from "@/lib/share-call-to-action";
import { usePlayerJsReceiver } from "./use-player-js-receiver";

const CapVideoPlayer = dynamic(() =>
	import("@/app/s/[videoId]/_components/CapVideoPlayer").then(
		(m) => m.CapVideoPlayer,
	),
);
const UploadProgressTracker = dynamic(
	() => import("@/app/s/[videoId]/_components/UploadProgressTracker"),
	{ ssr: false },
);
const HLSVideoPlayer = dynamic(() =>
	import("@/app/s/[videoId]/_components/HLSVideoPlayer").then(
		(m) => m.HLSVideoPlayer,
	),
);

declare global {
	interface Window {
		MSStream: unknown;
	}
}

type CommentWithAuthor = typeof commentsSchema.$inferSelect & {
	authorName: string | null;
};

export const EmbedVideo = forwardRef<
	HTMLVideoElement,
	{
		data: Omit<typeof videos.$inferSelect, "password"> & {
			hasActiveUpload: boolean | undefined;
		};
		branding: SharePageBranding | null;
		user: typeof userSelectProps | null;
		comments: CommentWithAuthor[];
		chapters?: { title: string; start: number }[];
		ownerName?: string | null;
		ownerImageUrl?: string | null;
		autoplay?: boolean;
		/** Seconds to open at, from the embed URL's `?t=`. */
		startTime?: number | null;
		minimal?: boolean;
		defaultPlaybackSpeed?: number;
		viewerSettings?: ViewerSettings | null;
		showPlaybackStatusBadge?: boolean;
		callToAction?: ShareCallToAction | null;
	}
>(
	(
		{
			data,
			branding,
			user: _user,
			comments: _comments,
			chapters = [],
			ownerName,
			ownerImageUrl,
			autoplay = false,
			startTime = null,
			minimal = false,
			defaultPlaybackSpeed,
			viewerSettings,
			showPlaybackStatusBadge = false,
			callToAction = null,
		},
		ref,
	) => {
		const videoRef = useRef<HTMLVideoElement>(null);
		const seekedToStart = useRef(false);
		const playerContainerRef = useRef<HTMLDivElement>(null);
		useImperativeHandle(ref, () => videoRef.current as HTMLVideoElement);
		usePlayerJsReceiver({ playerContainerRef, videoRef });

		const [transcriptData, setTranscriptData] = useState<TranscriptEntry[]>([]);
		const [longestDuration, setLongestDuration] = useState<number>(
			data.duration ?? 0,
		);
		const [isPlaying, setIsPlaying] = useState(false);
		const [userConfirmedStopped, setUserConfirmedStopped] = useState(false);
		const trackUploadProgress =
			data.source.type === "desktopSegments" && (data.hasActiveUpload ?? false);
		const [segmentUploadProgress, setSegmentUploadProgress] =
			useState<UploadProgress | null>(
				trackUploadProgress ? { status: "fetching" } : null,
			);
		useEffect(() => {
			setSegmentUploadProgress(
				trackUploadProgress ? { status: "fetching" } : null,
			);
		}, [trackUploadProgress]);
		const [subtitleUrl, setSubtitleUrl] = useState<string | null>(null);
		const [chaptersUrl, setChaptersUrl] = useState<string | null>(null);
		const captionsDisabled = viewerSettings?.disableCaptions ?? false;
		const chaptersDisabled = viewerSettings?.disableChapters ?? false;

		const { data: transcriptContent, error: transcriptError } = useTranscript(
			data.id,
			captionsDisabled ? null : data.transcriptionStatus,
		);

		useEffect(() => {
			if (transcriptContent) {
				const parsed = parseVTT(transcriptContent);
				setTranscriptData(parsed);
			} else if (transcriptError) {
				console.error(
					"[Transcript] Transcript error from React Query:",
					transcriptError.message,
				);
			}
		}, [transcriptContent, transcriptError]);

		useEffect(() => {
			if (
				!captionsDisabled &&
				data.transcriptionStatus === "COMPLETE" &&
				transcriptData &&
				transcriptData.length > 0
			) {
				const vttContent = formatTranscriptAsVTT(transcriptData);
				const blob = new Blob([vttContent], { type: "text/vtt" });
				const newUrl = URL.createObjectURL(blob);
				setSubtitleUrl((prev) => {
					if (prev) URL.revokeObjectURL(prev);
					return newUrl;
				});
				return () => {
					URL.revokeObjectURL(newUrl);
				};
			}
			setSubtitleUrl((prev) => {
				if (prev) URL.revokeObjectURL(prev);
				return null;
			});
		}, [captionsDisabled, data.transcriptionStatus, transcriptData]);

		useEffect(() => {
			if (!chaptersDisabled && chapters?.length > 0) {
				const vttContent = formatChaptersAsVTT(chapters);
				const blob = new Blob([vttContent], { type: "text/vtt" });
				const newUrl = URL.createObjectURL(blob);
				setChaptersUrl((prev) => {
					if (prev) URL.revokeObjectURL(prev);
					return newUrl;
				});
				return () => {
					URL.revokeObjectURL(newUrl);
				};
			}
			setChaptersUrl((prev) => {
				if (prev) URL.revokeObjectURL(prev);
				return null;
			});
		}, [chapters, chaptersDisabled]);

		const isMp4Source =
			data.source.type === "desktopMP4" || data.source.type === "webMP4";
		const isSegmentsSource = data.source.type === "desktopSegments";
		const isActivelyRecording =
			isSegmentsSource &&
			(data.hasActiveUpload ?? false) &&
			!userConfirmedStopped &&
			(segmentUploadProgress?.status === "fetching" ||
				segmentUploadProgress?.status === "uploading");

		const wasRecordingRef = useRef(false);
		const [isTransitioning, setIsTransitioning] = useState(false);

		useEffect(() => {
			if (isActivelyRecording) {
				wasRecordingRef.current = true;
			} else if (wasRecordingRef.current) {
				wasRecordingRef.current = false;
				setIsTransitioning(true);
				const timer = setTimeout(() => setIsTransitioning(false), 1500);
				return () => clearTimeout(timer);
			}
		}, [isActivelyRecording]);

		let videoSrc: string;
		const rawFallbackSrc =
			data.source.type === "webMP4"
				? `/api/playlist?userId=${data.ownerId}&videoId=${data.id}&videoType=raw-preview`
				: undefined;
		let enableCrossOrigin = false;

		if (isSegmentsSource) {
			videoSrc = `/api/playlist?userId=${data.ownerId}&videoId=${data.id}&videoType=segments-master`;
		} else if (isMp4Source) {
			videoSrc = `/api/playlist?userId=${data.ownerId}&videoId=${data.id}&videoType=mp4`;
			enableCrossOrigin = true;
		} else if (
			NODE_ENV === "development" ||
			((data.skipProcessing === true || data.jobStatus !== "COMPLETE") &&
				data.source.type === "MediaConvert")
		) {
			videoSrc = `/api/playlist?userId=${data.ownerId}&videoId=${data.id}&videoType=master`;
		} else if (data.source.type === "MediaConvert") {
			videoSrc = `/api/playlist?userId=${data.ownerId}&videoId=${data.id}&videoType=video`;
		} else {
			videoSrc = `/api/playlist?userId=${data.ownerId}&videoId=${data.id}&videoType=video`;
		}

		const handleLoadedMetadata = useCallback(
			(player: HTMLVideoElement) => {
				setLongestDuration(player.duration);

				// Once only. HLS level switches and source swaps fire this again, and
				// yanking a viewer who has since scrubbed back to the start offset
				// would be worse than ignoring the deep link.
				if (startTime === null || seekedToStart.current) return;
				seekedToStart.current = true;
				const limit = Number.isFinite(player.duration)
					? Math.max(player.duration - 0.001, 0)
					: startTime;
				try {
					player.currentTime = Math.min(startTime, limit);
				} catch (error) {
					console.warn("Failed to seek embed to start time", error);
				}
			},
			[startTime],
		);

		useEffect(() => {
			const container = playerContainerRef.current;
			if (!container) return;
			let currentPlayer: HTMLVideoElement | null = null;
			const syncMetadata = () => {
				const player = container.querySelector("video");
				if (player === currentPlayer) return;
				currentPlayer = player;
				if (player && player.readyState >= 1) handleLoadedMetadata(player);
			};
			const observer = new MutationObserver(syncMetadata);
			observer.observe(container, { childList: true, subtree: true });
			syncMetadata();
			return () => observer.disconnect();
		}, [handleLoadedMetadata]);

		return (
			<>
				<div
					ref={playerContainerRef}
					className="relative w-screen h-screen rounded-xl"
					onPlayCapture={() => setIsPlaying(true)}
					onPauseCapture={() => setIsPlaying(false)}
					onEndedCapture={() => setIsPlaying(false)}
					onLoadedMetadataCapture={(event) => {
						if (event.target instanceof HTMLVideoElement) {
							handleLoadedMetadata(event.target);
						}
					}}
				>
					{isActivelyRecording ? (
						<RecordingInProgressOverlay
							onConfirmStopped={() => setUserConfirmedStopped(true)}
							className="w-full h-full"
						/>
					) : isTransitioning ? (
						<PreparingVideoOverlay className="w-full h-full" />
					) : isMp4Source ? (
						<CapVideoPlayer
							videoId={data.id}
							mediaPlayerClassName="w-full h-full"
							videoSrc={videoSrc}
							rawFallbackSrc={rawFallbackSrc}
							duration={data.duration}
							showPlaybackStatusBadge={showPlaybackStatusBadge}
							disableCaptions={captionsDisabled}
							chaptersSrc={chaptersDisabled ? "" : chaptersUrl || ""}
							captionsSrc={captionsDisabled ? "" : subtitleUrl || ""}
							videoRef={videoRef}
							autoplay={autoplay}
							defaultPlaybackSpeed={defaultPlaybackSpeed}
							enableCrossOrigin={enableCrossOrigin}
							hasActiveUpload={data.hasActiveUpload}
							callToAction={callToAction}
						/>
					) : (
						<HLSVideoPlayer
							videoId={data.id}
							mediaPlayerClassName="w-full h-full"
							videoSrc={videoSrc}
							duration={data.duration}
							disableCaptions={captionsDisabled}
							chaptersSrc={chaptersDisabled ? "" : chaptersUrl || ""}
							captionsSrc={captionsDisabled ? "" : subtitleUrl || ""}
							videoRef={videoRef}
							autoplay={autoplay}
							defaultPlaybackSpeed={defaultPlaybackSpeed}
							hasActiveUpload={data.hasActiveUpload}
							isLiveSegments={isSegmentsSource}
							callToAction={callToAction}
						/>
					)}
				</div>

				{!minimal && (
					<AnimatePresence>
						{!isPlaying && (
							<div className="absolute top-3 left-3 z-10 space-y-2">
								<motion.div
									initial={{ opacity: 0, y: 10 }}
									animate={{ opacity: 1, y: 0 }}
									exit={{ opacity: 0, y: 10 }}
									transition={{ duration: 0.3, delay: 0.2 }}
									className="z-10 bg-black/50 backdrop-blur-md rounded-lg sm:rounded-xl px-2 py-1.5 sm:px-4 sm:py-3 border border-white/10 shadow-2xl"
								>
									<div className="flex gap-2 items-center sm:gap-3">
										{ownerName && (
											<Avatar
												name={ownerName}
												imageUrl={ownerImageUrl}
												className="hidden flex-shrink-0 xs:flex xs:size-10"
												letterClass="xs:text-base font-medium"
											/>
										)}
										<div className="flex-1 min-w-0">
											<a
												href={`/s/${data.id}`}
												target="_blank"
												rel="noopener noreferrer"
												className="block"
												onClick={(e) => e.stopPropagation()}
											>
												<h1 className="text-xs max-w-[175px] xs:max-w-[300px] sm:max-w-[400px] font-semibold md:max-w-[500px] leading-tight text-white truncate transition-all duration-200 cursor-pointer sm:text-xl md:text-2xl hover:underline">
													{data.name}
												</h1>
											</a>
											<div className="flex items-center gap-1 sm:gap-2 mt-0.5 sm:mt-1">
												{ownerName && (
													<p className="text-xs font-medium text-gray-300 truncate sm:text-sm">
														{ownerName}
													</p>
												)}
												{ownerName && longestDuration > 0 && (
													<>
														<span className="text-xs text-gray-400">•</span>
														<p className="text-xs text-gray-300 sm:text-sm">
															{formatPlayerTime(longestDuration)}
														</p>
													</>
												)}
											</div>
										</div>
									</div>
								</motion.div>
								{branding?.type === "custom" ? (
									<motion.div
										initial={{ opacity: 0, y: 10 }}
										animate={{ opacity: 1, y: 0 }}
										exit={{ opacity: 0, y: 10 }}
										transition={{ duration: 0.3, delay: 0.1 }}
										className="w-fit rounded-lg border border-white/10 bg-black/50 px-3 py-2 backdrop-blur-sm"
									>
										<Image
											src={branding.imageUrl}
											alt={`${branding.name} logo`}
											width={160}
											height={32}
											unoptimized
											className="h-8 w-auto max-w-40 object-contain"
										/>
									</motion.div>
								) : branding?.type === "cap" ? (
									<motion.button
										initial={{ opacity: 0, y: 10 }}
										animate={{ opacity: 1, y: 0 }}
										exit={{ opacity: 0, y: 10 }}
										transition={{ duration: 0.3, delay: 0.1 }}
										onClick={(e) => {
											e.stopPropagation();
											window.open("https://cap.so", "_blank");
										}}
										className="hidden z-10 gap-2 items-center px-3 py-2 text-sm rounded-full border backdrop-blur-sm transition-colors duration-200 sm:flex border-white/10 w-fit text-white/80 hover:text-white bg-black/50"
										aria-label="Powered by Cap"
									>
										<span className="text-xs md:text-sm text-white/80">
											Powered by
										</span>
										<Logo className="w-auto h-4" white={true} />
									</motion.button>
								) : null}
							</div>
						)}
					</AnimatePresence>
				)}
				{trackUploadProgress && (
					<UploadProgressTracker
						videoId={data.id}
						onChange={setSegmentUploadProgress}
					/>
				)}
			</>
		);
	},
);