Skip to content

armgit / Cap

Public Imported from GitHub
0

Open source Loom alternative. Beautiful, shareable screen recordings.

improvement: rework video player (#774)

Ameer Al Ashhab9f104fdc459d
diff --git a/apps/web/app/(org)/dashboard/caps/components/CapCard/CapCard.tsx b/apps/web/app/(org)/dashboard/caps/components/CapCard/CapCard.tsx
index 6c40ef6ed..87c2ec337 100644
--- a/apps/web/app/(org)/dashboard/caps/components/CapCard/CapCard.tsx
+++ b/apps/web/app/(org)/dashboard/caps/components/CapCard/CapCard.tsx
@@ -108,10 +108,15 @@ export const CapCard = ({
const confirmRemoveCap = async () => {
if (!onDelete) return;
- setRemoving(true);
- await onDelete();
- setRemoving(false);
- setConfirmOpen(false);
+ try {
+ setRemoving(true);
+ await onDelete();
+ } catch (error) {
+ console.error("Error deleting cap:", error);
+ } finally {
+ setRemoving(false);
+ setConfirmOpen(false);
+ }
};
const handleSharingUpdated = () => {
@@ -345,7 +350,7 @@ export const CapCard = ({
<FontAwesomeIcon
className="size-3"
icon={faCopy}
- />
+ />f
<p className="text-sm text-gray-12">Duplicate</p>
</DropdownMenuItem>
<DropdownMenuItem
diff --git a/apps/web/app/embed/[videoId]/_components/EmbedVideo.tsx b/apps/web/app/embed/[videoId]/_components/EmbedVideo.tsx
index cc29b6986..8faf27311 100644
--- a/apps/web/app/embed/[videoId]/_components/EmbedVideo.tsx
+++ b/apps/web/app/embed/[videoId]/_components/EmbedVideo.tsx
@@ -1,36 +1,19 @@
"use client";
-import { UpgradeModal } from "@/components/UpgradeModal";
import { usePublicEnv } from "@/utils/public-env";
-import { useTranscript } from "hooks/use-transcript";
import { userSelectProps } from "@cap/database/auth/session";
import { comments as commentsSchema, videos } from "@cap/database/schema";
import { NODE_ENV } from "@cap/env";
-import { Avatar, Logo, LogoSpinner } from "@cap/ui";
-import { isUserOnProPlan } from "@cap/utils";
-import { AnimatePresence, motion } from "framer-motion";
import {
- Maximize,
- MessageSquare,
- Pause,
- Play,
- Volume2,
- VolumeX,
-} from "lucide-react";
-import {
- forwardRef,
- useEffect,
- useImperativeHandle,
- useRef,
- useState,
+ forwardRef, useEffect,
+ useImperativeHandle, useRef,
+ useState
} from "react";
-import { Tooltip } from "react-tooltip";
-import { toast } from "sonner";
-import { fromVtt, Subtitle } from "subtitles-parser-vtt";
-import { MP4VideoPlayer } from "../../../s/[videoId]/_components/MP4VideoPlayer";
-import { VideoPlayer } from "../../../s/[videoId]/_components/VideoPlayer";
-import { useQuery } from "@tanstack/react-query";
-import { useSearchParams } from "next/navigation";
+import { formatChaptersAsVTT, formatTranscriptAsVTT, parseVTT, TranscriptEntry } from "@/app/s/[videoId]/_components/utils/transcript-utils";
+import { useTranscript } from "hooks/use-transcript";
+import { AnimatePresence, motion } from "framer-motion";
+import { Logo, Avatar } from "@cap/ui";
+import { CapVideoPlayer } from "@/app/s/[videoId]/_components/CapVideoPlayer";
declare global {
interface Window {
@@ -46,15 +29,6 @@ const formatTime = (time: number) => {
.padStart(2, "0")}`;
};
-const formatTimeWithMilliseconds = (time: number) => {
- const minutes = Math.floor(time / 60);
- const seconds = Math.floor(time % 60);
- const milliseconds = Math.floor((time % 1) * 100);
- return `${minutes.toString().padStart(2, "0")}:${seconds
- .toString()
- .padStart(2, "0")}.${milliseconds.toString().padStart(2, "0")}`;
-};
-
type CommentWithAuthor = typeof commentsSchema.$inferSelect & {
authorName: string | null;
};
@@ -83,248 +57,88 @@ export const EmbedVideo = forwardRef<
},
ref
) => {
+ const videoRef = useRef<HTMLVideoElement>(null);
useImperativeHandle(ref, () => videoRef.current as HTMLVideoElement);
- const searchParams = useSearchParams();
- const hideBranding = searchParams.get("hideBranding") === "true";
-
- const videoRef = useRef<HTMLVideoElement>(null);
+ const [transcriptData, setTranscriptData] = useState<TranscriptEntry[]>([]);
+ const [longestDuration, setLongestDuration] = useState<number>(0);
const [isPlaying, setIsPlaying] = useState(false);
- const [currentTime, setCurrentTime] = useState(0);
- const [isLoading, setIsLoading] = useState(true);
- const [longestDuration, setLongestDuration] = useState(0);
- const [videoMetadataLoaded, setVideoMetadataLoaded] = useState(false);
- const [videoReadyToPlay, setVideoReadyToPlay] = useState(false);
- const [overlayVisible, setOverlayVisible] = useState(true);
- const [subtitlesVisible, setSubtitlesVisible] = useState(true);
- const [upgradeModalOpen, setUpgradeModalOpen] = useState(false);
- const [tempOverlayVisible, setTempOverlayVisible] = useState(false);
- const [showTitleOverlay, setShowTitleOverlay] = useState(true);
+ const [subtitleUrl, setSubtitleUrl] = useState<string | null>(null);
+ const [chaptersUrl, setChaptersUrl] = useState<string | null>(null);
- const [isMP4Source, setIsMP4Source] = useState(false);
-
- const [videoSpeed, setVideoSpeed] = useState(1);
- const [isHoveringVideo, setIsHoveringVideo] = useState(false);
- const [isHoveringControls, setIsHoveringControls] = useState(false);
- const hideControlsTimeoutRef = useRef<NodeJS.Timeout | null>(null);
- const [userMuted, setUserMuted] = useState(false);
-
- const [isDragging, setIsDragging] = useState(false);
- const timelineRef = useRef<HTMLDivElement>(null);
-
- const isLargeScreen = useScreenSize();
-
- const { data: videoSourceData } = useVideoSourceValidation(
- data,
- videoMetadataLoaded
+ const { data: transcriptContent, error: transcriptError } = useTranscript(
+ data.id,
+ data.transcriptionStatus
);
useEffect(() => {
- if (videoSourceData) {
- setIsMP4Source(videoSourceData.isMP4Source);
- } else if (videoMetadataLoaded) {
- setIsMP4Source(data.source.type === "desktopMP4");
- }
- }, [videoSourceData, videoMetadataLoaded, data.source.type]);
-
- useEffect(() => {
- if (videoRef.current) {
- if (typeof ref === "function") {
- ref(videoRef.current);
- } else if (ref) {
- ref.current = videoRef.current;
- }
- }
- }, [ref]);
-
- const showControls = () => {
- setOverlayVisible(true);
- if (!isPlaying) {
- setShowTitleOverlay(true);
- }
- if (hideControlsTimeoutRef.current) {
- clearTimeout(hideControlsTimeoutRef.current);
- hideControlsTimeoutRef.current = null;
- }
- };
-
- const scheduleHideControls = () => {
- if (hideControlsTimeoutRef.current) {
- clearTimeout(hideControlsTimeoutRef.current);
+ if (transcriptContent) {
+ const parsed = parseVTT(transcriptContent);
+ setTranscriptData(parsed);
+ } else if (transcriptError) {
+ console.error(
+ "[Transcript] Transcript error from React Query:",
+ transcriptError.message
+ );
}
+ }, [transcriptContent, transcriptError]);
- if (isPlaying && !isHoveringControls) {
- hideControlsTimeoutRef.current = setTimeout(() => {
- setOverlayVisible(false);
- setShowTitleOverlay(false);
- }, 2000);
- }
- };
-
+ // Handle subtitle URL creation
useEffect(() => {
- const handleMouseMove = () => {
- showControls();
- scheduleHideControls();
- };
-
- const handleMouseEnter = () => {
- setIsHoveringVideo(true);
- showControls();
- };
-
- const handleMouseLeave = () => {
- setIsHoveringVideo(false);
- if (!isHoveringControls) {
- scheduleHideControls();
+ if (data.transcriptionStatus === "COMPLETE" && transcriptData && transcriptData.length > 0) {
+ const vttContent = formatTranscriptAsVTT(transcriptData);
+ const blob = new Blob([vttContent], { type: "text/vtt" });
+ const newUrl = URL.createObjectURL(blob);
+
+ // Clean up previous URL
+ if (subtitleUrl) {
+ URL.revokeObjectURL(subtitleUrl);
}
- };
- const videoContainer = document.getElementById("embed-video-container");
- if (videoContainer) {
- videoContainer.addEventListener("mousemove", handleMouseMove);
- videoContainer.addEventListener("mouseenter", handleMouseEnter);
- videoContainer.addEventListener("mouseleave", handleMouseLeave);
- }
+ setSubtitleUrl(newUrl);
- return () => {
- if (videoContainer) {
- videoContainer.removeEventListener("mousemove", handleMouseMove);
- videoContainer.removeEventListener("mouseenter", handleMouseEnter);
- videoContainer.removeEventListener("mouseleave", handleMouseLeave);
- }
- if (hideControlsTimeoutRef.current) {
- clearTimeout(hideControlsTimeoutRef.current);
- }
- };
- }, [isPlaying, isHoveringControls]);
-
- useEffect(() => {
- if (isPlaying) {
- setShowTitleOverlay(false);
- scheduleHideControls();
+ return () => {
+ URL.revokeObjectURL(newUrl);
+ };
} else {
- showControls();
- setShowTitleOverlay(true);
- }
- }, [isPlaying, isHoveringControls]);
-
- useEffect(() => {
- if (isHoveringControls) {
- showControls();
- if (!isPlaying) {
- setShowTitleOverlay(true);
+ // Clean up if no longer needed
+ if (subtitleUrl) {
+ URL.revokeObjectURL(subtitleUrl);
+ setSubtitleUrl(null);
}
- } else if (isPlaying && !isHoveringVideo) {
- scheduleHideControls();
}
- }, [isHoveringControls, isPlaying, isHoveringVideo]);
-
- useEffect(() => {
- const handleShortcuts = (e: KeyboardEvent) => {
- const target = e.target as HTMLElement;
- const isFormElement =
- target.tagName === "INPUT" ||
- target.tagName === "TEXTAREA" ||
- target.tagName === "SELECT" ||
- target.isContentEditable ||
- target.getAttribute("role") === "textbox";
-
- if (!isFormElement && videoRef.current) {
- if (e.code === "Space") {
- e.preventDefault();
- if (isPlaying) {
- videoRef.current.pause();
- setIsPlaying(false);
- } else {
- videoRef.current.play();
- setIsPlaying(true);
- }
- }
- }
- };
-
- window.addEventListener("keydown", handleShortcuts);
-
- return () => {
- window.removeEventListener("keydown", handleShortcuts);
- };
- }, [isPlaying, videoRef]);
+ }, [data.transcriptionStatus, transcriptData]);
+ // Handle chapters URL creation
useEffect(() => {
- const onVideoLoadedMetadata = () => {
- if (videoRef.current) {
- setLongestDuration(videoRef.current.duration);
- setVideoMetadataLoaded(true);
+ if (chapters?.length > 0) {
+ const vttContent = formatChaptersAsVTT(chapters);
+ const blob = new Blob([vttContent], { type: "text/vtt" });
+ const newUrl = URL.createObjectURL(blob);
+
+ // Clean up previous URL
+ if (chaptersUrl) {
+ URL.revokeObjectURL(chaptersUrl);
}
- };
-
- const onCanPlay = () => {
- setVideoMetadataLoaded(true);
- setVideoReadyToPlay(true);
-
- setTimeout(() => {
- setIsLoading(false);
- }, 100);
- };
-
- const videoElement = videoRef.current;
- if (videoElement) {
- videoElement.addEventListener("loadedmetadata", onVideoLoadedMetadata);
- videoElement.addEventListener("canplay", onCanPlay);
- }
- return () => {
- if (videoElement) {
- videoElement.removeEventListener(
- "loadedmetadata",
- onVideoLoadedMetadata
- );
- videoElement.removeEventListener("canplay", onCanPlay);
- }
- };
- }, []);
+ setChaptersUrl(newUrl);
- useEffect(() => {
- const videoElement = videoRef.current;
- if (!videoElement || !videoReadyToPlay) return;
-
- const handleTimeUpdate = () => {
- setCurrentTime(videoElement.currentTime);
- };
-
- videoElement.addEventListener("timeupdate", handleTimeUpdate);
-
- if (autoplay && !isPlaying) {
- const attemptAutoplay = async () => {
- try {
- videoElement.muted = true;
- await videoElement.play();
- setIsPlaying(true);
- } catch (error) {
- console.log("Autoplay failed:", error);
- }
+ return () => {
+ URL.revokeObjectURL(newUrl);
};
- attemptAutoplay();
+ } else {
+ // Clean up if no longer needed
+ if (chaptersUrl) {
+ URL.revokeObjectURL(chaptersUrl);
+ setChaptersUrl(null);
+ }
}
-
- return () => {
- videoElement.removeEventListener("timeupdate", handleTimeUpdate);
- };
- }, [videoReadyToPlay, autoplay, isPlaying]);
-
- useEffect(() => {
- setTempOverlayVisible(true);
-
- const timer = setTimeout(() => {
- setTempOverlayVisible(false);
- }, 500);
-
- return () => clearTimeout(timer);
- }, [isPlaying]);
+ }, [chapters]);
const publicEnv = usePublicEnv();
let videoSrc: string;
+ let videoType: string = "video/mp4";
if (data.source.type === "desktopMP4") {
videoSrc = `/api/playlist?userId=${data.ownerId}&videoId=${data.id}&videoType=mp4`;
} else if (
@@ -333,910 +147,115 @@ export const EmbedVideo = forwardRef<
data.source.type === "MediaConvert")
) {
videoSrc = `/api/playlist?userId=${data.ownerId}&videoId=${data.id}&videoType=master`;
+ videoType = "application/x-mpegURL";
} else if (data.source.type === "MediaConvert") {
videoSrc = `${publicEnv.s3BucketUrl}/${data.ownerId}/${data.id}/output/video_recording_000.m3u8`;
+ videoType = "application/x-mpegURL";
} else {
videoSrc = `${publicEnv.s3BucketUrl}/${data.ownerId}/${data.id}/combined-source/stream.m3u8`;
+ videoType = "application/x-mpegURL";
}
- const handlePlayPauseClick = async () => {
- const videoElement = videoRef.current;
-
- if (!videoElement) return;
-
- if (isPlaying) {
- videoElement.pause();
- setIsPlaying(false);
- } else {
- try {
- if (!videoReadyToPlay) {
- setIsPlaying(true);
- } else {
- if (!userMuted) {
- videoElement.muted = false;
- }
-
- const currentPosition = videoElement.currentTime;
-
- const playPromise = videoElement.play();
-
- if (playPromise !== undefined) {
- playPromise
- .then(() => {
- setIsPlaying(true);
- if (videoElement.currentTime === 0 && currentPosition > 0) {
- videoElement.currentTime = currentPosition;
- }
- })
- .catch((error) => {
- console.error("Error with playing:", error);
-
- if (error.name === "NotAllowedError") {
- videoElement.muted = true;
- videoElement
- .play()
- .then(() => {
- setIsPlaying(true);
- if (!userMuted) {
- setTimeout(() => {
- videoElement.muted = false;
- }, 100);
- }
-
- if (
- videoElement.currentTime === 0 &&
- currentPosition > 0
- ) {
- videoElement.currentTime = currentPosition;
- }
- })
- .catch((innerError) => {
- console.error(
- "Still can't play even with muted:",
- innerError
- );
- });
- }
- });
- } else {
- setIsPlaying(true);
-
- if (videoElement.currentTime === 0 && currentPosition > 0) {
- videoElement.currentTime = currentPosition;
- }
- }
- }
- } catch (error) {
- console.error("Error with playing:", error);
- }
- }
- };
-
- const handleMuteClick = () => {
- if (videoRef.current) {
- const newMutedState = !videoRef.current.muted;
- videoRef.current.muted = newMutedState;
- setUserMuted(newMutedState);
- }
- };
-
- const handleFullscreenClick = () => {
- const player = document.getElementById("embed-video-container");
- const video = videoRef.current;
-
- if (!video) return;
-
- const isIOS =
- /iPad|iPhone|iPod/.test(navigator.userAgent) && !window.MSStream;
- const isAndroid = /Android/.test(navigator.userAgent);
-
- if (isIOS || isAndroid) {
- if (video.requestFullscreen) {
- video
- .requestFullscreen()
- .catch((err) =>
- console.error(
- `Error attempting to enable full-screen mode on mobile: ${err.message} (${err.name})`
- )
- );
- } else if ("webkitEnterFullscreen" in video) {
- (video as any).webkitEnterFullscreen();
- } else if ("mozRequestFullScreen" in video) {
- (video as any).mozRequestFullScreen();
- } else if ("msRequestFullscreen" in video) {
- (video as any).msRequestFullscreen();
- }
- } else {
- if (!document.fullscreenElement) {
- if (player && player.requestFullscreen) {
- player
- .requestFullscreen()
- .catch((err) =>
- console.error(
- `Error attempting to enable full-screen mode: ${err.message} (${err.name})`
- )
- );
- } else if (player && "webkitRequestFullscreen" in player) {
- (player as any).webkitRequestFullscreen();
- } else if (player && "mozRequestFullScreen" in player) {
- (player as any).mozRequestFullScreen();
- } else if (player && "msRequestFullscreen" in player) {
- (player as any).msRequestFullscreen();
- }
- } else {
- if (document.exitFullscreen) {
- document.exitFullscreen();
- } else if ("webkitExitFullscreen" in document) {
- (document as any).webkitExitFullscreen();
- } else if ("mozCancelFullScreen" in document) {
- (document as any).mozCancelFullScreen();
- } else if ("msExitFullscreen" in document) {
- (document as any).msExitFullscreen();
- }
- }
- }
- };
+ useEffect(() => {
+ if (!videoRef.current) return;
+ const player = videoRef.current;
+ const handleLoadedMetadata = () => {
+ setLongestDuration(player.duration);
+ };
- const handleSpeedChange = () => {
- let newSpeed;
- if (videoSpeed === 1) {
- newSpeed = 1.5;
- } else if (videoSpeed === 1.5) {
- newSpeed = 2;
+ if (player.readyState >= 1) {
+ setLongestDuration(player.duration);
} else {
- newSpeed = 1;
- }
- setVideoSpeed(newSpeed);
- if (videoRef.current) {
- videoRef.current.playbackRate = newSpeed;
+ player.addEventListener('loadedmetadata', handleLoadedMetadata);
}
- };
-
- const handleSeek = (e: React.MouseEvent<HTMLDivElement>) => {
- if (!timelineRef.current || !videoRef.current || longestDuration === 0)
- return;
- const rect = timelineRef.current.getBoundingClientRect();
- const clickX = e.clientX - rect.left;
- const percentage = Math.max(0, Math.min(1, clickX / rect.width));
- const seekTime = percentage * longestDuration;
-
- console.log(seekTime, 'seek time')
-
- videoRef.current.currentTime = seekTime;
- setCurrentTime(seekTime);
- };
-
- const handleMouseDown = (e: React.MouseEvent<HTMLDivElement>) => {
- e.preventDefault();
- setIsDragging(true);
- handleSeek(e);
- };
-
- // Global timeline scrubbing
- useEffect(() => {
- if (!isDragging) return;
- const handleGlobalMouseMove = (e: MouseEvent) => {
- if (!timelineRef.current || !videoRef.current || longestDuration === 0) return;
- const rect = timelineRef.current.getBoundingClientRect();
- const x = e.clientX - rect.left;
- const percentage = Math.max(0, Math.min(1, x / rect.width));
- const seekTime = percentage * longestDuration;
- videoRef.current.currentTime = seekTime;
- setCurrentTime(seekTime);
- };
- const handleGlobalMouseUp = () => {
- setIsDragging(false);
+ const listener = (arg: boolean) => {
+ setIsPlaying(arg);
};
- document.addEventListener("mousemove", handleGlobalMouseMove);
- document.addEventListener("mouseup", handleGlobalMouseUp);
+ player.addEventListener("play", () => listener(true));
+ player.addEventListener("pause", () => listener(false));
return () => {
- document.removeEventListener("mousemove", handleGlobalMouseMove);
- document.removeEventListener("mouseup", handleGlobalMouseUp);
+ player.removeEventListener("play", () => listener(true));
+ player.removeEventListener("pause", () => listener(false));
+ player.removeEventListener('loadedmetadata', handleLoadedMetadata);
};
- }, [isDragging, longestDuration]);
-
- const handleChapterSeek = (chapterStart: number) => {
- if (!videoRef.current) return;
- videoRef.current.currentTime = chapterStart;
- setCurrentTime(chapterStart);
- };
-
- const watchedPercentage =
- longestDuration > 0 ? (currentTime / longestDuration) * 100 : 0;
-
- const { data: transcriptContent, error: transcriptError } = useTranscript(
- data.id,
- data.transcriptionStatus
- );
-
- const { isTranscriptionProcessing, subtitles } = useTranscriptionProcessing(
- data,
- transcriptContent,
- transcriptError
- );
-
- const parseSubTime = (timeString: number) => {
- const timeStr = timeString.toString();
- const timeParts = timeStr.split(":");
-
- const hoursValue = timeParts.length > 2 ? Number(timeParts[0]) || 0 : 0;
- const minutesValue =
- timeParts.length > 1 ? Number(timeParts[timeParts.length - 2]) || 0 : 0;
- const secondsValue = Number(timeParts[timeParts.length - 1]) || 0;
-
- return hoursValue * 3600 + minutesValue * 60 + secondsValue;
- };
-
- const currentSubtitle = subtitles.find(
- (subtitle) =>
- parseSubTime(subtitle.startTime) <= currentTime &&
- parseSubTime(subtitle.endTime) >= currentTime
- );
-
- if (data.jobStatus === "ERROR") {
- return (
- <div className="flex overflow-hidden justify-center items-center w-full h-screen bg-black">
- <p className="text-xl text-white">
- There was an error when processing the video. Please contact
- support.
- </p>
- </div>
- );
- }
+ }, []);
return (
- <div
- id="embed-video-container"
- className="overflow-hidden relative w-screen h-screen bg-black group"
- >
- <div
- className={`absolute inset-0 flex items-center justify-center z-10 bg-black transition-opacity duration-300 ${isLoading ? "opacity-100" : "opacity-0 pointer-events-none"
- }`}
- >
- <LogoSpinner className="w-8 h-auto animate-spin xs:w-10" />
- </div>
- <div className="relative w-full h-full">
- <div className="absolute inset-0 bg-black">
- {data.source.type === "desktopMP4" ? (
- <MP4VideoPlayer ref={videoRef} videoSrc={videoSrc} />
- ) : (
- <VideoPlayer ref={videoRef} videoSrc={videoSrc} />
- )}
- </div>
- {!isLoading && (
- <div
- className={`absolute inset-0 z-20 flex flex-col items-center justify-center transition-opacity duration-300 ${(overlayVisible && isPlaying) ||
- tempOverlayVisible ||
- !isPlaying
- ? "opacity-100"
- : "opacity-0"
- }`}
- >
- <button
- aria-label={isPlaying ? "Pause video" : "Play video"}
- className="flex justify-center items-center w-full h-full"
- onClick={() => {
- if (!videoReadyToPlay) {
- setIsPlaying(true);
- } else {
- handlePlayPauseClick();
- }
- }}
- >
- <div className="flex flex-col gap-4 items-center">
- <AnimatePresence initial={false} mode="popLayout">
- {isPlaying ? (
- <motion.div
- key="pause-button"
- className="flex relative z-30 justify-center items-center bg-black bg-opacity-60 rounded-full size-16 xs:size-20 md:size-24"
- initial={{ opacity: 0, scale: 0 }}
- animate={{
- scale: 1,
- opacity: overlayVisible || tempOverlayVisible ? 1 : 0,
- }}
- style={{ transformOrigin: "center center" }}
- transition={{ duration: 0.4, ease: "easeOut" }}
- >
- <Pause className="w-auto h-6 text-white xs:h-8 md:h-10 lg:h-12" />
- </motion.div>
- ) : (
- <motion.div
- key="play-button"
- className="flex relative z-30 justify-center items-center bg-black bg-opacity-60 rounded-full size-16 xs:size-20 md:size-24"
- initial={{ opacity: 0, scale: 0 }}
- animate={{
- scale: 1,
- opacity: 1,
- }}
- style={{ transformOrigin: "center center" }}
- transition={{ duration: 0.4, ease: "easeOut" }}
- >
- <Play className="w-auto h-6 text-white xs:h-8 md:h-10 lg:h-12 ml-0.5" />
- </motion.div>
- )}
- </AnimatePresence>
+ <>
- {!isPlaying && !hideBranding && (
- <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 gap-2 items-center px-3 py-2 text-sm rounded-full backdrop-blur-sm transition-colors duration-200 xs:flex text-white/80 hover:text-white bg-black/50"
- aria-label="Powered by Cap"
- >
- <span className="text-sm text-white/80">Powered by</span>
- <Logo className="w-auto h-4" white={true} />
- </motion.button>
- )}
- </div>
- </button>
- </div>
- )}
+ <div className="relative w-screen h-screen rounded-xl">
+ <CapVideoPlayer hlsVideo={videoType === "application/x-mpegURL"} mediaPlayerClassName="w-full h-full" videoSrc={videoSrc} chaptersSrc={chaptersUrl || ""} captionsSrc={subtitleUrl || ""} videoRef={videoRef} />
+ </div>
- <AnimatePresence>
- {!isLoading && showTitleOverlay && (
+ <AnimatePresence>
+ {!isPlaying && (
+ <div className="absolute top-3 left-3 z-10 space-y-2">
<motion.div
- initial={{ opacity: 0, y: -20 }}
+ initial={{ opacity: 0, y: 10 }}
animate={{ opacity: 1, y: 0 }}
- exit={{ opacity: 0, y: -20 }}
- transition={{ duration: 0.3 }}
- className="absolute top-2 left-2 xs:top-6 xs:left-6 z-30 max-w-[calc(100%-1rem)] xs:max-w-2xl"
- >
- <div className="bg-gradient-to-r from-black/70 to-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}
- 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-sm font-semibold 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 && (
+ 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}
+ 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>
- )}
- {longestDuration > 0 && (
<p className="text-xs text-gray-300 sm:text-sm">
{formatTime(longestDuration)}
</p>
- )}
- </div>
+ </>
+ )}
</div>
</div>
</div>
</motion.div>
- )}
- </AnimatePresence>
-
- {currentSubtitle && currentSubtitle.text && subtitlesVisible && (
- <div
- className={`absolute z-10 p-2 w-full text-center transition-all duration-300 ease-in-out ${overlayVisible
- ? "bottom-24 xs:bottom-24"
- : "bottom-8 xs:bottom-8"
- }`}
- >
- <div className="inline px-3 py-2 text-base text-white bg-black bg-opacity-75 rounded-xl xs:text-lg md:text-2xl max-w-[90%] xs:max-w-none">
- {currentSubtitle.text
- .replace("- ", "")
- .replace(".", "")
- .replace(",", "")}
- </div>
- </div>
- )}
-
- <AnimatePresence>
- {isPlaying && !showTitleOverlay && !hideBranding && (
- <motion.div
- initial={{ opacity: 0 }}
- animate={{ opacity: 1 }}
- exit={{ opacity: 0 }}
- transition={{ duration: 0.3 }}
- className="hidden absolute top-4 left-4 z-30 xs:flex xs:top-6 xs:left-6"
- >
- <button
- onClick={() => window.open("https://cap.so", "_blank")}
- className="opacity-30 transition-opacity duration-200 cursor-pointer hover:opacity-100"
- aria-label="Powered by Cap"
- >
- <Logo className="w-auto h-6 xs:h-8" white={true} />
- </button>
- </motion.div>
- )}
- </AnimatePresence>
- </div>
-
- <div
- className={`absolute left-0 right-0 z-30 transition-all duration-300 ease-in-out ${overlayVisible ? "bottom-[68px] xs:bottom-[60px]" : "bottom-0"
- }`}
- >
- <div
- ref={timelineRef}
- className="px-4 py-2 h-8 cursor-pointer xs:h-6 xs:py-0 touch-manipulation"
- onMouseDown={handleMouseDown}
- onTouchStart={(e) => {
- const touch = e.touches[0];
- const rect = timelineRef.current?.getBoundingClientRect();
- if (rect && touch) {
- const percentage = Math.max(
- 0,
- Math.min(1, (touch.clientX - rect.left) / rect.width)
- );
- const seekTime = percentage * longestDuration;
- if (videoRef.current) {
- videoRef.current.currentTime = seekTime;
- setCurrentTime(seekTime);
- }
- }
- setIsDragging(true);
- }}
- onTouchMove={(e) => {
- if (isDragging) {
- const touch = e.touches[0];
- const rect = timelineRef.current?.getBoundingClientRect();
- if (rect && touch) {
- const percentage = Math.max(
- 0,
- Math.min(1, (touch.clientX - rect.left) / rect.width)
- );
- const seekTime = percentage * longestDuration;
- if (videoRef.current) {
- videoRef.current.currentTime = seekTime;
- setCurrentTime(seekTime);
- }
- }
- }
- }}
- onTouchEnd={() => {
- setIsDragging(false);
- }}
- >
- {!isLoading && comments && comments.length > 0 && (
- <div className="-mt-6 w-full md:-mt-6">
- {comments.map((comment) => {
- const commentPosition =
- comment.timestamp === null
- ? 0
- : (comment.timestamp / longestDuration) * 100;
-
- let tooltipContent = "";
- if (comment.type === "text") {
- tooltipContent =
- comment.authorId === "anonymous"
- ? `Anonymous: ${comment.content}`
- : `${comment.authorName || "User"}: ${comment.content}`;
- } else {
- tooltipContent =
- comment.authorId === "anonymous"
- ? "Anonymous"
- : comment.authorName || "User";
- }
-
- return (
- <div
- key={comment.id}
- className="absolute z-10 -mt-5 text-sm transition-all hover:scale-125 active:scale-110 md:-mt-5 touch-manipulation"
- style={{
- left: `${commentPosition}%`,
- }}
- data-tooltip-id={comment.id}
- data-tooltip-content={tooltipContent}
- >
- <span>
- {comment.type === "text" ? (
- <MessageSquare
- fill="#646464"
- className="w-auto h-[20px] xs:h-[18px] md:h-[22px] text-white"
- />
- ) : (
- comment.content
- )}
- </span>
- <Tooltip id={comment.id} />
- </div>
- );
- })}
- </div>
- )}
-
- <div className="relative w-full h-full">
- {chapters.length > 0 && longestDuration > 0 ? (
- <div className="absolute top-2.5 xs:top-2.5 w-full h-1.5 xs:h-1.5 z-10 flex">
- {chapters.map((chapter, index) => {
- const nextChapter = chapters[index + 1];
- const chapterStart = chapter.start;
- const chapterEnd = nextChapter
- ? nextChapter.start
- : longestDuration;
- const chapterDuration = chapterEnd - chapterStart;
- const chapterWidth =
- (chapterDuration / longestDuration) * 100;
-
- const isCurrentChapter =
- currentTime >= chapterStart && currentTime < chapterEnd;
-
- return (
- <div
- key={chapter.start}
- className="h-full cursor-pointer group"
- style={{ width: `${chapterWidth}%` }}
- onClick={(e) => {
- e.stopPropagation();
- handleChapterSeek(chapterStart);
- }}
- >
- <div
- className="w-full h-full bg-gray-400 bg-opacity-50 transition-colors group-hover:bg-opacity-70"
- style={{
- boxShadow: "0 0 20px rgba(0,0,0,0.6)",
- borderRight:
- index < chapters.length - 1
- ? "1px solid rgba(255,255,255,0.3)"
- : "none",
- }}
- />
- {isCurrentChapter && (
- <div
- className="absolute top-0 left-0 h-full bg-white"
- style={{ width: `${watchedPercentage}%` }}
- />
- )}
- </div>
- );
- })}
- </div>
- ) : (
- <>
- <div
- style={{ boxShadow: "0 0 20px rgba(0,0,0,0.6)" }}
- className="absolute top-2.5 xs:top-2.5 w-full h-1.5 xs:h-1.5 bg-gray-400 bg-opacity-50 z-10 cursor-pointer"
- onClick={handleSeek}
- />
- <div
- className="absolute top-2.5 xs:top-2.5 h-1.5 xs:h-1.5 bg-white cursor-pointer z-10 pointer-events-none"
- style={{ width: `${watchedPercentage}%` }}
- />
- </>
- )}
-
- <div
- style={{
- boxShadow: "0 0 20px rgba(0,0,0,0.1)",
- left: `${watchedPercentage}%`,
- }}
- className="absolute top-1.5 xs:top-2 z-20 -mt-1.5 -ml-2 xs:-ml-2 w-6 h-6 xs:w-5 xs:h-5 bg-white rounded-full cursor-pointer focus:outline-none border-2 border-gray-5"
- tabIndex={0}
- />
- </div>
- </div>
- </div>
-
- <div
- className={`absolute bottom-0 left-0 right-0 bg-black bg-opacity-60 z-20 transition-transform duration-300 ease-in-out ${overlayVisible ? "translate-y-0" : "translate-y-full"
- }`}
- onMouseEnter={() => {
- setIsHoveringControls(true);
- }}
- onMouseLeave={() => {
- setIsHoveringControls(false);
- }}
- >
- <div className="flex justify-between items-center px-3 py-3 xs:px-4 xs:py-3">
- <div className="flex items-center space-x-2 xs:space-x-3">
- <button
- aria-label="Play video"
- className="inline-flex justify-center items-center px-2 py-2 xs:px-2 xs:py-2 text-sm font-medium text-gray-100 rounded-lg border border-transparent transition duration-150 ease-in-out focus:outline-none hover:text-white focus:border-white hover:bg-gray-100 hover:bg-opacity-10 active:bg-gray-100 active:bg-opacity-10 min-h-[44px] min-w-[44px] xs:min-h-0 xs:min-w-0"
- tabIndex={0}
- type="button"
- onClick={() => handlePlayPauseClick()}
- >
- {isPlaying ? (
- <Pause className="w-auto h-6 xs:h-5 md:h-6" />
- ) : (
- <Play className="w-auto h-6 xs:h-5 md:h-6" />
- )}
- </button>
- <div className="text-xs font-medium text-white select-none xs:text-sm tabular">
- {formatTime(currentTime)} / {formatTime(longestDuration)}
- </div>
- </div>
-
- <div className="flex justify-end space-x-1 xs:space-x-2">
- <button
- aria-label={`Change video speed to ${videoSpeed}x`}
- className="inline-flex min-w-[44px] xs:min-w-[45px] items-center text-xs xs:text-sm font-medium transition ease-in-out duration-150 focus:outline-none border text-gray-100 border-transparent hover:text-white focus:border-white hover:bg-gray-100 hover:bg-opacity-10 active:bg-gray-100 active:bg-opacity-10 px-2 py-2 justify-center rounded-lg min-h-[44px] xs:min-h-0"
- tabIndex={0}
- type="button"
- onClick={handleSpeedChange}
- >
- {videoSpeed}x
- </button>
-
- {isTranscriptionProcessing && subtitles.length === 0 && (
- <button
- aria-label="Transcription is processing"
- className="inline-flex justify-center items-center px-2 py-2 text-sm font-medium text-gray-100 rounded-lg border border-transparent transition duration-150 ease-in-out focus:outline-none hover:text-white focus:border-white hover:bg-gray-100 hover:bg-opacity-10 active:bg-gray-100 active:bg-opacity-10 min-h-[44px] min-w-[44px] xs:min-h-0 xs:min-w-0"
- tabIndex={0}
- type="button"
- onClick={() => {
- toast.error("Transcription is processing");
- }}
- >
- <svg
- xmlns="http://www.w3.org/2000/svg"
- className="w-6 h-6 xs:w-5 xs:h-5 md:w-6 md:h-6"
- viewBox="0 0 24 24"
- >
- <style>
- {"@keyframes spinner_AtaB{to{transform:rotate(360deg)}}"}
- </style>
- <path
- fill="#FFF"
- d="M12 1a11 11 0 1 0 11 11A11 11 0 0 0 12 1Zm0 19a8 8 0 1 1 8-8 8 8 0 0 1-8 8Z"
- opacity={0.25}
- />
- <path
- fill="#FFF"
- d="M10.14 1.16a11 11 0 0 0-9 8.92A1.59 1.59 0 0 0 2.46 12a1.52 1.52 0 0 0 1.65-1.3 8 8 0 0 1 6.66-6.61A1.42 1.42 0 0 0 12 2.69a1.57 1.57 0 0 0-1.86-1.53Z"
- style={{
- transformOrigin: "center",
- animation: "spinner_AtaB .75s infinite linear",
- }}
- />
- </svg>
- </button>
- )}
-
- {aiProcessing && (
- <button
- aria-label="AI summary is processing"
- className="inline-flex justify-center items-center px-2 py-2 text-sm font-medium text-gray-100 rounded-lg border border-transparent transition duration-150 ease-in-out focus:outline-none hover:text-white focus:border-white hover:bg-gray-100 hover:bg-opacity-10 active:bg-gray-100 active:bg-opacity-10 min-h-[44px] min-w-[44px] xs:min-h-0 xs:min-w-0"
- tabIndex={0}
- type="button"
- onClick={() => {
- toast.info("AI summary is being generated");
- }}
- >
- <svg
- xmlns="http://www.w3.org/2000/svg"
- className="w-6 h-6 xs:w-5 xs:h-5 md:w-6 md:h-6"
- viewBox="0 0 24 24"
- >
- <style>
- {"@keyframes spinner_AtaB{to{transform:rotate(360deg)}}"}
- </style>
- <path
- fill="#FFF"
- d="M12 1a11 11 0 1 0 11 11A11 11 0 0 0 12 1Zm0 19a8 8 0 1 1 8-8 8 8 0 0 1-8 8Z"
- opacity={0.25}
- />
- <path
- fill="#FFF"
- d="M10.14 1.16a11 11 0 0 0-9 8.92A1.59 1.59 0 0 0 2.46 12a1.52 1.52 0 0 0 1.65-1.3 8 8 0 0 1 6.66-6.61A1.42 1.42 0 0 0 12 2.69a1.57 1.57 0 0 0-1.86-1.53Z"
- style={{
- transformOrigin: "center",
- animation: "spinner_AtaB .75s infinite linear",
- }}
- />
- </svg>
- </button>
- )}
-
- {subtitles.length > 0 && (
- <button
- aria-label={
- subtitlesVisible ? "Hide subtitles" : "Show subtitles"
- }
- className="inline-flex justify-center items-center px-2 py-2 text-sm font-medium text-gray-100 rounded-lg border border-transparent transition duration-150 ease-in-out focus:outline-none hover:text-white focus:border-white hover:bg-gray-100 hover:bg-opacity-10 active:bg-gray-100 active:bg-opacity-10 min-h-[44px] min-w-[44px] xs:min-h-0 xs:min-w-0"
- tabIndex={0}
- type="button"
- onClick={() => setSubtitlesVisible(!subtitlesVisible)}
- >
- {subtitlesVisible ? (
- <svg
- xmlns="http://www.w3.org/2000/svg"
- fill="none"
- stroke="currentColor"
- strokeLinecap="round"
- strokeLinejoin="round"
- strokeWidth="2"
- className="w-auto h-6 xs:h-5 md:h-6"
- viewBox="0 0 24 24"
- >
- <rect
- width="18"
- height="14"
- x="3"
- y="5"
- rx="2"
- ry="2"
- ></rect>
- <path d="M7 15h4m4 0h2m4 0h2"></path>
- </svg>
- ) : (
- <svg
- xmlns="http://www.w3.org/2000/svg"
- fill="none"
- stroke="currentColor"
- strokeLinecap="round"
- strokeLinejoin="round"
- strokeWidth="2"
- className="w-auto h-6 xs:h-5 md:h-6"
- viewBox="0 0 24 24"
- >
- <path d="M10.5 5H19a2 2 0 012 2v8.5M17 11h-.5M19 19H5a2 2 0 01-2-2V7a2 2 0 012-2M2 2l20 20M7 11h4M7 15h2.5"></path>
- </svg>
- )}
- </button>
- )}
-
- <button
- aria-label={videoRef?.current?.muted ? "Unmute" : "Mute"}
- className="inline-flex justify-center items-center px-2 py-2 text-sm font-medium text-gray-100 rounded-lg border border-transparent transition duration-150 ease-in-out focus:outline-none hover:text-white focus:border-white hover:bg-gray-100 hover:bg-opacity-10 active:bg-gray-100 active:bg-opacity-10 min-h-[44px] min-w-[44px] xs:min-h-0 xs:min-w-0"
- tabIndex={0}
- type="button"
- onClick={() => handleMuteClick()}
- >
- {videoRef?.current?.muted ? (
- <VolumeX className="w-auto h-6 xs:h-5 md:h-6" />
- ) : (
- <Volume2 className="w-auto h-6 xs:h-5 md:h-6" />
- )}
- </button>
-
- <button
- aria-label="Go fullscreen"
- className="inline-flex justify-center items-center px-2 py-2 text-sm font-medium text-gray-100 rounded-lg border border-transparent transition duration-150 ease-in-out focus:outline-none hover:text-white focus:border-white hover:bg-gray-100 hover:bg-opacity-10 active:bg-gray-100 active:bg-opacity-10 min-h-[44px] min-w-[44px] xs:min-h-0 xs:min-w-0"
- tabIndex={0}
- type="button"
- onClick={handleFullscreenClick}
- >
- <Maximize className="w-auto h-6 xs:h-5 md:h-6" />
- </button>
- </div>
- </div>
- </div>
-
- {user &&
- !isUserOnProPlan({
- subscriptionStatus: user.stripeSubscriptionStatus,
- }) && (
- <div
- className={`absolute top-4 z-30 transition-all duration-300 ${showTitleOverlay ? "right-4" : "left-4"
- }`}
- >
- <div
- className="block cursor-pointer"
+ <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();
- setUpgradeModalOpen(true);
+ 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"
>
- <div className="relative">
- <div className="opacity-50 transition-opacity hover:opacity-100 peer">
- <Logo className="w-auto h-4 xs:h-8" white={true} />
- </div>
-
- <div
- className={`absolute top-8 transition-transform duration-300 ease-in-out origin-top scale-y-0 peer-hover:scale-y-100 ${showTitleOverlay ? "right-0" : "left-0"
- }`}
- >
- <p className="text-white text-xs font-medium whitespace-nowrap bg-black bg-opacity-50 px-2 py-0.5 rounded">
- Remove watermark
- </p>
- </div>
- </div>
- </div>
+ <span className="text-xs md:text-sm text-white/80">Powered by</span>
+ <Logo className="w-auto h-4" white={true} />
+ </motion.button>
</div>
)}
-
- <UpgradeModal
- open={upgradeModalOpen}
- onOpenChange={setUpgradeModalOpen}
- />
- </div>
+ </AnimatePresence>
+ </>
);
}
);
-const useVideoSourceValidation = (
- data: typeof videos.$inferSelect,
- videoMetadataLoaded: boolean
-) => {
- return useQuery({
- queryKey: ["video-source-validation", data.id, data.source.type],
- queryFn: async () => {
- if (data.source.type !== "desktopMP4") {
- return { isMP4Source: false };
- }
-
- const thumbUrl = `/api/playlist?userId=${data.ownerId}&videoId=${data.id}&thumbnailTime=0`;
-
- try {
- const response = await fetch(thumbUrl, { method: "HEAD" });
- return { isMP4Source: response.ok };
- } catch (error) {
- console.error("Error checking thumbnails:", error);
- return { isMP4Source: false };
- }
- },
- enabled: videoMetadataLoaded && data.source.type === "desktopMP4",
- staleTime: 5 * 60 * 1000,
- gcTime: 10 * 60 * 1000,
- });
-};
-
-const useScreenSize = () => {
- const [isLargeScreen, setIsLargeScreen] = useState(false);
-
- useEffect(() => {
- const checkScreenSize = () => {
- setIsLargeScreen(window.innerWidth >= 1024);
- };
-
- checkScreenSize();
- window.addEventListener("resize", checkScreenSize);
-
- return () => window.removeEventListener("resize", checkScreenSize);
- }, []);
-
- return isLargeScreen;
-};
-
-const useTranscriptionProcessing = (
- data: typeof videos.$inferSelect,
- transcriptContent: string | undefined,
- transcriptError: any
-) => {
- const [isTranscriptionProcessing, setIsTranscriptionProcessing] = useState(
- data.transcriptionStatus === "PROCESSING"
- );
- const [subtitles, setSubtitles] = useState<Subtitle[]>([]);
-
- useEffect(() => {
- if (transcriptContent) {
- const parsedSubtitles = fromVtt(transcriptContent);
- setSubtitles(parsedSubtitles);
- setIsTranscriptionProcessing(false);
- } else if (transcriptError) {
- console.error(
- "[EmbedVideo] Subtitle error from React Query:",
- transcriptError.message
- );
- if (transcriptError.message === "TRANSCRIPT_NOT_READY") {
- setIsTranscriptionProcessing(true);
- } else {
- setIsTranscriptionProcessing(false);
- }
- } else if (data.transcriptionStatus === "PROCESSING") {
- setIsTranscriptionProcessing(true);
- } else if (data.transcriptionStatus === "ERROR") {
- setIsTranscriptionProcessing(false);
- }
- }, [transcriptContent, transcriptError, data.transcriptionStatus]);
-
- return { isTranscriptionProcessing, subtitles };
-};
diff --git a/apps/web/app/globals.css b/apps/web/app/globals.css
index a90f6a768..b89e108a9 100644
--- a/apps/web/app/globals.css
+++ b/apps/web/app/globals.css
@@ -710,6 +710,33 @@ footer a {
animation: slideUp 0.3s ease-out forwards;
}
+.media-player video::-webkit-media-text-track-display {
+ @apply !bottom-12 !top-auto !mb-0;
+}
+
+.media-player[data-controls-visible] video::-webkit-media-text-track-display {
+ @apply !bottom-20;
+}
+
+.media-player[data-state="fullscreen"][data-controls-visible]
+ video::-webkit-media-text-track-display {
+ @apply !bottom-20;
+}
+
+/* Firefox support */
+.media-player video::cue {
+ position: relative !important;
+ bottom: 64px !important;
+}
+
+.media-player[data-controls-visible] video::cue {
+ bottom: 64px !important;
+}
+
+.media-player[data-state="fullscreen"][data-controls-visible] video::cue {
+ bottom: 64px !important;
+}
+
/* Safari-specific styles using CSS hacks */
@media screen and (-webkit-min-device-pixel-ratio: 0) {
_::-webkit-full-page-media,
@@ -718,3 +745,68 @@ footer a {
height: calc(100% - 1.7rem) !important;
}
}
+
+@layer base {
+ :root {
+ --background: 0 0% 100%;
+ --foreground: 224 71.4% 4.1%;
+ --card: 0 0% 100%;
+ --card-foreground: 224 71.4% 4.1%;
+ --popover: 0 0% 100%;
+ --popover-foreground: 224 71.4% 4.1%;
+ --primary: 220.9 39.3% 11%;
+ --primary-foreground: 210 20% 98%;
+ --secondary: 220 14.3% 95.9%;
+ --secondary-foreground: 220.9 39.3% 11%;
+ --muted: 220 14.3% 95.9%;
+ --muted-foreground: 220 8.9% 46.1%;
+ --accent: 220 14.3% 95.9%;
+ --accent-foreground: 220.9 39.3% 11%;
+ --destructive: 0 84.2% 60.2%;
+ --destructive-foreground: 210 20% 98%;
+ --border: 220 13% 91%;
+ --input: 220 13% 91%;
+ --ring: 224 71.4% 4.1%;
+ --chart-1: 12 76% 61%;
+ --chart-2: 173 58% 39%;
+ --chart-3: 197 37% 24%;
+ --chart-4: 43 74% 66%;
+ --chart-5: 27 87% 67%;
+ --radius: 0.5rem;
+ }
+ .dark {
+ --background: 224 71.4% 4.1%;
+ --foreground: 210 20% 98%;
+ --card: 224 71.4% 4.1%;
+ --card-foreground: 210 20% 98%;
+ --popover: 224 71.4% 4.1%;
+ --popover-foreground: 210 20% 98%;
+ --primary: 210 20% 98%;
+ --primary-foreground: 220.9 39.3% 11%;
+ --secondary: 215 27.9% 16.9%;
+ --secondary-foreground: 210 20% 98%;
+ --muted: 215 27.9% 16.9%;
+ --muted-foreground: 217.9 10.6% 64.9%;
+ --accent: 215 27.9% 16.9%;
+ --accent-foreground: 210 20% 98%;
+ --destructive: 0 62.8% 30.6%;
+ --destructive-foreground: 210 20% 98%;
+ --border: 215 27.9% 16.9%;
+ --input: 215 27.9% 16.9%;
+ --ring: 216 12.2% 83.9%;
+ --chart-1: 220 70% 50%;
+ --chart-2: 160 60% 45%;
+ --chart-3: 30 80% 55%;
+ --chart-4: 280 65% 60%;
+ --chart-5: 340 75% 55%;
+ }
+}
+
+@layer base {
+ * {
+ @apply border-border;
+ }
+ body {
+ @apply bg-background text-foreground;
+ }
+}
diff --git a/apps/web/app/lib/compose-refs.ts b/apps/web/app/lib/compose-refs.ts
new file mode 100644
index 000000000..ef3c01ee9
--- /dev/null
+++ b/apps/web/app/lib/compose-refs.ts
@@ -0,0 +1,62 @@
+import * as React from "react";
+
+type PossibleRef<T> = React.Ref<T> | undefined;
+
+/**
+ * Set a given ref to a given value
+ * This utility takes care of different types of refs: callback refs and RefObject(s)
+ */
+function setRef<T>(ref: PossibleRef<T>, value: T) {
+ if (typeof ref === "function") {
+ return ref(value);
+ }
+
+ if (ref !== null && ref !== undefined) {
+ ref.current = value;
+ }
+}
+
+/**
+ * A utility to compose multiple refs together
+ * Accepts callback refs and RefObject(s)
+ */
+function composeRefs<T>(...refs: PossibleRef<T>[]): React.RefCallback<T> {
+ return (node) => {
+ let hasCleanup = false;
+ const cleanups = refs.map((ref) => {
+ const cleanup = setRef(ref, node);
+ if (!hasCleanup && typeof cleanup === "function") {
+ hasCleanup = true;
+ }
+ return cleanup;
+ });
+
+ // React <19 will log an error to the console if a callback ref returns a
+ // value. We don't use ref cleanups internally so this will only happen if a
+ // user's ref callback returns a value, which we only expect if they are
+ // using the cleanup functionality added in React 19.
+ if (hasCleanup) {
+ return () => {
+ for (let i = 0; i < cleanups.length; i++) {
+ const cleanup = cleanups[i];
+ if (typeof cleanup === "function") {
+ cleanup();
+ } else {
+ setRef(refs[i], null);
+ }
+ }
+ };
+ }
+ };
+}
+
+/**
+ * A custom hook that composes multiple refs
+ * Accepts callback refs and RefObject(s)
+ */
+function useComposedRefs<T>(...refs: PossibleRef<T>[]): React.RefCallback<T> {
+ // eslint-disable-next-line react-hooks/exhaustive-deps
+ return React.useCallback(composeRefs(...refs), refs);
+}
+
+export { composeRefs, useComposedRefs };
diff --git a/apps/web/app/lib/utils.ts b/apps/web/app/lib/utils.ts
new file mode 100644
index 000000000..bd0c391dd
--- /dev/null
+++ b/apps/web/app/lib/utils.ts
@@ -0,0 +1,6 @@
+import { clsx, type ClassValue } from "clsx"
+import { twMerge } from "tailwind-merge"
+
+export function cn(...inputs: ClassValue[]) {
+ return twMerge(clsx(inputs))
+}
diff --git a/apps/web/app/s/[videoId]/Share.tsx b/apps/web/app/s/[videoId]/Share.tsx
index 7032a7d76..3a75c410f 100644
--- a/apps/web/app/s/[videoId]/Share.tsx
+++ b/apps/web/app/s/[videoId]/Share.tsx
@@ -6,7 +6,6 @@ import { userSelectProps } from "@cap/database/auth/session";
import { comments as commentsSchema, videos } from "@cap/database/schema";
import { useQuery } from "@tanstack/react-query";
import { useMemo, useRef } from "react";
-import { ShareHeader } from "./_components/ShareHeader";
import { ShareVideo } from "./_components/ShareVideo";
import { Sidebar } from "./_components/Sidebar";
import { Toolbar } from "./_components/Toolbar";
@@ -67,17 +66,17 @@ const useVideoStatus = (
},
initialData: initialData
? {
- transcriptionStatus: initialData.transcriptionStatus as
- | "PROCESSING"
- | "COMPLETE"
- | "ERROR"
- | null,
- aiProcessing: initialData.aiData?.processing || false,
- aiTitle: initialData.aiData?.title || null,
- summary: initialData.aiData?.summary || null,
- chapters: initialData.aiData?.chapters || null,
- generationError: null,
- }
+ transcriptionStatus: initialData.transcriptionStatus as
+ | "PROCESSING"
+ | "COMPLETE"
+ | "ERROR"
+ | null,
+ aiProcessing: initialData.aiData?.processing || false,
+ aiTitle: initialData.aiData?.title || null,
+ summary: initialData.aiData?.summary || null,
+ chapters: initialData.aiData?.chapters || null,
+ generationError: null,
+ }
: undefined,
refetchInterval: (query) => {
const data = query.state.data;
@@ -146,27 +145,13 @@ export const Share = ({
? new Date(data.metadata.customCreatedAt)
: data.createdAt;
- const videoRef = useRef<HTMLVideoElement>(null);
+ const playerRef = useRef<HTMLVideoElement | null>(null);
const { data: videoStatus } = useVideoStatus(data.id, aiGenerationEnabled, {
transcriptionStatus: data.transcriptionStatus,
aiData: initialAiData,
});
- // const { data: viewCount } = useVideoAnalytics(
- // data.id,
- // initialAnalytics.views
- // );
-
- // const analytics = useMemo(
- // () => ({
- // views: viewCount || 0,
- // comments: 0, // comments.filter((c) => c.type === "text").length,
- // reactions: 0, // comments.filter((c) => c.type === "emoji").length,
- // }),
- // [viewCount, comments]
- // );
-
const transcriptionStatus =
videoStatus?.transcriptionStatus || data.transcriptionStatus;
@@ -212,28 +197,23 @@ export const Share = ({
const aiLoading = shouldShowLoading();
const handleSeek = (time: number) => {
- if (videoRef.current) {
- videoRef.current.currentTime = time;
+ if (playerRef.current) {
+ playerRef.current.currentTime = time;
}
};
- const headerData =
- aiData && aiData.title && !aiData.processing
- ? { ...data, name: aiData.title, createdAt: effectiveDate }
- : { ...data, createdAt: effectiveDate };
-
return (
<div className="mt-4">
<div className="flex flex-col gap-4 lg:flex-row">
<div className="flex-1">
- <div className="overflow-hidden relative p-3 aspect-video new-card-style">
+ <div className="relative p-3 aspect-video new-card-style">
<ShareVideo
data={{ ...data, transcriptionStatus }}
user={user}
comments={comments}
chapters={aiData?.chapters || []}
aiProcessing={aiData?.processing || false}
- ref={videoRef}
+ ref={playerRef}
/>
</div>
<div className="mt-4 lg:hidden">
@@ -263,31 +243,31 @@ export const Share = ({
<Toolbar data={data} user={user} />
</div>
- <div className="mt-4 hidden lg:block">
+ <div className="hidden mt-4 lg:block">
{aiLoading &&
(transcriptionStatus === "PROCESSING" ||
transcriptionStatus === "COMPLETE") && (
- <div className="p-4 new-card-style animate-pulse">
+ <div className="p-4 animate-pulse new-card-style">
<div className="space-y-6">
<div>
- <div className="h-6 w-24 bg-gray-200 rounded mb-3"></div>
- <div className="h-3 w-32 bg-gray-100 rounded mb-4"></div>
+ <div className="mb-3 w-24 h-6 bg-gray-200 rounded"></div>
+ <div className="mb-4 w-32 h-3 bg-gray-100 rounded"></div>
<div className="space-y-3">
- <div className="h-4 bg-gray-200 rounded w-full"></div>
- <div className="h-4 bg-gray-200 rounded w-5/6"></div>
- <div className="h-4 bg-gray-200 rounded w-4/5"></div>
- <div className="h-4 bg-gray-200 rounded w-full"></div>
- <div className="h-4 bg-gray-200 rounded w-3/4"></div>
+ <div className="w-full h-4 bg-gray-200 rounded"></div>
+ <div className="w-5/6 h-4 bg-gray-200 rounded"></div>
+ <div className="w-4/5 h-4 bg-gray-200 rounded"></div>
+ <div className="w-full h-4 bg-gray-200 rounded"></div>
+ <div className="w-3/4 h-4 bg-gray-200 rounded"></div>
</div>
</div>
<div>
- <div className="h-6 w-24 bg-gray-200 rounded mb-4"></div>
+ <div className="mb-4 w-24 h-6 bg-gray-200 rounded"></div>
<div className="space-y-2">
{[1, 2, 3, 4].map((i) => (
<div key={i} className="flex items-center p-2">
- <div className="h-4 w-12 bg-gray-200 rounded mr-3"></div>
- <div className="h-4 bg-gray-200 rounded flex-1"></div>
+ <div className="mr-3 w-12 h-4 bg-gray-200 rounded"></div>
+ <div className="flex-1 h-4 bg-gray-200 rounded"></div>
</div>
))}
</div>
@@ -321,10 +301,10 @@ export const Share = ({
{aiData.chapters.map((chapter) => (
<div
key={chapter.start}
- className="p-2 cursor-pointer hover:bg-gray-100 rounded transition-colors flex items-center"
+ className="flex items-center p-2 rounded transition-colors cursor-pointer hover:bg-gray-100"
onClick={() => handleSeek(chapter.start)}
>
- <span className="text-xs text-gray-500 w-16">
+ <span className="w-16 text-xs text-gray-500">
{formatTime(chapter.start)}
</span>
<span className="ml-2 text-sm">{chapter.title}</span>
diff --git a/apps/web/app/s/[videoId]/_components/CapVideoPlayer.tsx b/apps/web/app/s/[videoId]/_components/CapVideoPlayer.tsx
new file mode 100644
index 000000000..136ad9664
--- /dev/null
+++ b/apps/web/app/s/[videoId]/_components/CapVideoPlayer.tsx
@@ -0,0 +1,368 @@
+"use client"
+
+import {
+ MediaPlayer,
+ MediaPlayerCaptions,
+ MediaPlayerControls,
+ MediaPlayerControlsOverlay,
+ MediaPlayerError,
+ MediaPlayerFullscreen,
+ MediaPlayerLoading,
+ MediaPlayerPiP,
+ MediaPlayerPlay,
+ MediaPlayerSeek,
+ MediaPlayerSeekBackward,
+ MediaPlayerSeekForward,
+ MediaPlayerSettings,
+ MediaPlayerTime,
+ MediaPlayerVideo,
+ MediaPlayerVolume,
+ MediaPlayerVolumeIndicator,
+} from "./video/media-player";
+import { useRef, useEffect, useCallback, useState } from "react";
+import Hls from "hls.js";
+import clsx from "clsx";
+import { faPlay } from "@fortawesome/free-solid-svg-icons";
+import { FontAwesomeIcon } from "@fortawesome/react-fontawesome";
+import { AnimatePresence, motion } from "framer-motion";
+import { LogoSpinner } from "@cap/ui";
+
+interface Props {
+ videoSrc: string;
+ chaptersSrc: string;
+ captionsSrc: string;
+ videoRef: React.RefObject<HTMLVideoElement>;
+ mediaPlayerClassName?: string;
+ autoplay?: boolean;
+ hlsVideo?: boolean;
+}
+
+export function CapVideoPlayer({
+ videoSrc,
+ chaptersSrc,
+ captionsSrc,
+ videoRef,
+ mediaPlayerClassName,
+ autoplay = false,
+ hlsVideo = false
+}: Props) {
+ const hlsInstance = useRef<Hls | null>(null);
+ const [currentCue, setCurrentCue] = useState<string>('');
+ const [controlsVisible, setControlsVisible] = useState(false);
+ const [toggleCaptions, setToggleCaptions] = useState(true);
+ const [showPlayButton, setShowPlayButton] = useState(false);
+ const [videoLoaded, setVideoLoaded] = useState(false);
+ const [hasPlayedOnce, setHasPlayedOnce] = useState(false);
+
+ // Set up video event listeners for better loading detection
+ useEffect(() => {
+ const video = videoRef.current;
+ if (!video) return;
+
+ const handleLoadedData = () => {
+ console.log('Video loadeddata event fired');
+ setVideoLoaded(true);
+ if (!hasPlayedOnce) {
+ setShowPlayButton(true);
+ }
+ };
+
+ const handleCanPlay = () => {
+ setVideoLoaded(true);
+ if (!hasPlayedOnce) {
+ setShowPlayButton(true);
+ }
+ };
+
+ const handleLoadedMetadata = () => {
+ if (!hlsVideo) {
+ setVideoLoaded(true);
+ if (!hasPlayedOnce) {
+ setShowPlayButton(true);
+ }
+ }
+ };
+
+ const handleLoad = () => {
+ setVideoLoaded(true);
+ if (!hasPlayedOnce) {
+ setShowPlayButton(true);
+ }
+ };
+
+ const handlePlay = () => {
+ setShowPlayButton(false);
+ setHasPlayedOnce(true);
+ };
+
+ video.addEventListener('loadeddata', handleLoadedData);
+ video.addEventListener('canplay', handleCanPlay);
+ video.addEventListener('loadedmetadata', handleLoadedMetadata);
+ video.addEventListener('load', handleLoad);
+ video.addEventListener('play', handlePlay);
+
+ if (video.readyState >= 2) {
+ console.log('Video already loaded, readyState:', video.readyState);
+ setVideoLoaded(true);
+ if (!hasPlayedOnce) {
+ setShowPlayButton(true);
+ }
+ }
+
+ return () => {
+ video.removeEventListener('loadeddata', handleLoadedData);
+ video.removeEventListener('canplay', handleCanPlay);
+ video.removeEventListener('loadedmetadata', handleLoadedMetadata);
+ video.removeEventListener('load', handleLoad);
+ video.removeEventListener('play', handlePlay);
+ };
+ }, [hlsVideo, hasPlayedOnce]);
+
+ useEffect(() => {
+ if (!videoRef.current || !hlsVideo) return;
+
+ const videoElement = videoRef.current;
+
+ if (!Hls.isSupported()) {
+ console.warn("HLS is not supported in this browser");
+ return;
+ }
+ const isHlsStream = videoSrc.includes('.m3u8');
+
+ if (!isHlsStream) {
+ console.warn("Video source doesn't appear to be an HLS stream");
+ return;
+ }
+
+ if (hlsInstance.current) {
+ hlsInstance.current.destroy();
+ hlsInstance.current = null;
+ }
+
+ const hls = new Hls({
+ enableWorker: true,
+ lowLatencyMode: false,
+ backBufferLength: 90,
+ });
+ const currentTime = videoElement.currentTime;
+ const wasPaused = videoElement.paused;
+
+ hls.on(Hls.Events.ERROR, (event, data) => {
+ console.error("HLS error:", data);
+
+ if (data.fatal) {
+ switch (data.type) {
+ case Hls.ErrorTypes.NETWORK_ERROR:
+ console.log("Network error, trying to recover...");
+ hls.startLoad();
+ break;
+ case Hls.ErrorTypes.MEDIA_ERROR:
+ console.log("Media error, trying to recover...");
+ hls.recoverMediaError();
+ break;
+ default:
+ console.error("Fatal error, destroying HLS instance");
+ hls.destroy();
+ break;
+ }
+ }
+ });
+
+ hls.on(Hls.Events.MANIFEST_PARSED, () => {
+ console.log("HLS manifest parsed successfully");
+
+ if (currentTime > 0) {
+ videoElement.currentTime = currentTime;
+ }
+
+ if (!wasPaused && autoplay) {
+ videoElement.play().catch(err =>
+ console.error("Error resuming playback:", err)
+ );
+ }
+ });
+
+ // HLS specific events for better loading detection
+ hls.on(Hls.Events.FRAG_LOADED, () => {
+ console.log("HLS fragment loaded");
+ // Set video as loaded when first fragment is loaded
+ if (!videoLoaded) {
+ setVideoLoaded(true);
+ if (!hasPlayedOnce) {
+ setShowPlayButton(true);
+ }
+ }
+ });
+
+ hls.loadSource(videoSrc);
+ hls.attachMedia(videoElement);
+
+ hlsInstance.current = hls;
+ return () => {
+ if (hlsInstance.current) {
+ hlsInstance.current.destroy();
+ hlsInstance.current = null;
+ }
+ };
+ }, [videoSrc, hlsVideo, autoplay, videoLoaded, hasPlayedOnce]);
+
+ const generateVideoFrameThumbnail = useCallback((time: number): string => {
+ const video = videoRef.current;
+
+ if (!video) {
+ return `https://placeholder.pics/svg/224x128/1f2937/ffffff/Loading ${Math.floor(time)}s`;
+ }
+
+ const canvas = document.createElement('canvas');
+ canvas.width = 224;
+ canvas.height = 128;
+ const ctx = canvas.getContext('2d');
+
+ if (ctx) {
+ try {
+ ctx.drawImage(video, 0, 0, canvas.width, canvas.height);
+ return canvas.toDataURL('image/jpeg', 0.8);
+ } catch (error) {
+ console.error('Error capturing video frame:', error);
+ return `https://placeholder.pics/svg/224x128/dc2626/ffffff/Error`;
+ }
+ }
+ return `https://placeholder.pics/svg/224x128/dc2626/ffffff/Error`;
+ }, []);
+
+ useEffect(() => {
+ const video = videoRef.current;
+ if (!video) return;
+
+ let captionTrack: TextTrack | null = null;
+
+ const handleCueChange = (): void => {
+ if (captionTrack && captionTrack.activeCues && captionTrack.activeCues.length > 0) {
+ const cue = captionTrack.activeCues[0] as VTTCue;
+ const plainText = cue.text.replace(/<[^>]*>/g, '');
+ setCurrentCue(plainText);
+ } else {
+ setCurrentCue('');
+ }
+ };
+
+ const setupTracks = (): void => {
+ const tracks = Array.from(video.textTracks);
+
+ for (const track of tracks) {
+ if (track.kind === 'captions' || track.kind === 'subtitles') {
+ captionTrack = track;
+ track.mode = 'hidden';
+ track.addEventListener('cuechange', handleCueChange);
+ break;
+ }
+ }
+ };
+
+ const handleLoadedMetadata = (): void => {
+ setupTracks();
+ };
+
+ video.addEventListener('loadedmetadata', handleLoadedMetadata);
+
+ if (video.readyState >= 1) {
+ setupTracks();
+ }
+
+ return () => {
+ video.removeEventListener('loadedmetadata', handleLoadedMetadata);
+ if (captionTrack) {
+ captionTrack.removeEventListener('cuechange', handleCueChange);
+ }
+ };
+ }, []);
+
+
+ return (
+ <>
+ <MediaPlayer
+ onMouseEnter={() => setControlsVisible(true)}
+ onMouseLeave={() => setControlsVisible(false)}
+ onTouchStart={() => setControlsVisible(true)}
+ onTouchEnd={() => setControlsVisible(false)}
+ className={clsx(mediaPlayerClassName, "[&::-webkit-media-text-track-display]:!hidden")} autoHide>
+ <div
+ className={clsx("flex absolute inset-0 z-10 justify-center items-center bg-black transition-opacity duration-300", videoLoaded ? "opacity-0 pointer-events-none" : "opacity-100")}
+ >
+ <LogoSpinner className="w-8 h-auto animate-spin sm:w-10" />
+ </div>
+ <AnimatePresence>
+ {showPlayButton && videoLoaded && !hasPlayedOnce && (
+ <motion.div
+ whileHover={{ scale: 1.1 }}
+ whileTap={{ scale: 0.9 }}
+ initial={{ opacity: 0, y: 10 }}
+ animate={{ opacity: 1, y: 0 }}
+ exit={{ opacity: 0, y: 10 }}
+ transition={{ duration: 0.2 }}
+ onClick={() => videoRef.current?.play()}
+ className="flex absolute inset-0 z-10 justify-center items-center m-auto bg-blue-500 rounded-full transition-colors transform cursor-pointer hover:bg-blue-600 size-12 xs:size-20 md:size-32">
+ <FontAwesomeIcon icon={faPlay} className="text-white size-4 xs:size-8 md:size-12" />
+ </motion.div>
+ )}
+ </AnimatePresence>
+ <MediaPlayerVideo
+ src={hlsVideo ? undefined : videoSrc}
+ ref={videoRef}
+ onPlay={() => {
+ setShowPlayButton(false);
+ setHasPlayedOnce(true);
+ }}
+ crossOrigin="anonymous"
+ playsInline
+ autoPlay={autoplay}
+ >
+ <track
+ default
+ kind="chapters"
+ src={chaptersSrc}
+ />
+ <track
+ label="English"
+ kind="captions"
+ srcLang="en"
+ src={captionsSrc}
+ default
+ />
+ </MediaPlayerVideo>
+ {currentCue && toggleCaptions && (
+ <div
+ className={clsx(
+ "absolute left-1/2 transform -translate-x-1/2 text-xl z-40 pointer-events-none bg-black/80 text-white px-4 py-2 rounded-md text-center max-w-[80%] transition-all duration-300 ease-in-out",
+ controlsVisible || videoRef.current?.paused ? 'bottom-20' : 'bottom-12'
+ )}
+ >
+ {currentCue}
+ </div>
+ )}
+ <MediaPlayerLoading />
+ <MediaPlayerError />
+ <MediaPlayerVolumeIndicator />
+ <MediaPlayerControls className="flex-col items-start gap-2.5">
+ <MediaPlayerControlsOverlay />
+ <MediaPlayerSeek tooltipThumbnailSrc={generateVideoFrameThumbnail} />
+ <div className="flex gap-2 items-center w-full">
+ <div className="flex flex-1 gap-2 items-center">
+ <MediaPlayerPlay />
+ <MediaPlayerSeekBackward />
+ <MediaPlayerSeekForward />
+ <MediaPlayerVolume expandable />
+ <MediaPlayerTime />
+ </div>
+ <div className="flex gap-2 items-center">
+ <MediaPlayerCaptions setToggleCaptions={setToggleCaptions} toggleCaptions={toggleCaptions} />
+ <MediaPlayerSettings />
+ <MediaPlayerPiP />
+ <MediaPlayerFullscreen />
+ </div>
+ </div>
+ </MediaPlayerControls>
+ </MediaPlayer>
+ </>
+ );
+}
diff --git a/apps/web/app/s/[videoId]/_components/ShareVideo.tsx b/apps/web/app/s/[videoId]/_components/ShareVideo.tsx
index b0de17c76..aa0b4a51a 100644
--- a/apps/web/app/s/[videoId]/_components/ShareVideo.tsx
+++ b/apps/web/app/s/[videoId]/_components/ShareVideo.tsx
@@ -1,37 +1,15 @@
import { UpgradeModal } from "@/components/UpgradeModal";
import { usePublicEnv } from "@/utils/public-env";
-import { useApiClient } from "@/utils/web-api";
-import { useTranscript } from "hooks/use-transcript";
import { userSelectProps } from "@cap/database/auth/session";
import { comments as commentsSchema, videos } from "@cap/database/schema";
import { NODE_ENV } from "@cap/env";
-import { Logo, LogoSpinner } from "@cap/ui";
+import { Logo } from "@cap/ui";
import { isUserOnProPlan } from "@cap/utils";
-import clsx from "clsx";
-import { AnimatePresence, motion } from "framer-motion";
-import {
- Maximize,
- MessageSquare,
- Pause,
- Play,
- Volume2,
- VolumeX,
-} from "lucide-react";
-import {
- forwardRef,
- useEffect,
- useImperativeHandle,
- useRef,
- useState,
- use,
- Suspense,
-} from "react";
-import { Tooltip } from "react-tooltip";
-import { toast } from "sonner";
-import { fromVtt, Subtitle } from "subtitles-parser-vtt";
-import { MP4VideoPlayer } from "./MP4VideoPlayer";
-import { VideoPlayer } from "./VideoPlayer";
-import { useQuery } from "@tanstack/react-query";
+import { forwardRef, useImperativeHandle, useRef, useState, useEffect } from "react";
+import { formatChaptersAsVTT, formatTranscriptAsVTT, TranscriptEntry } from "./utils/transcript-utils";
+import { useTranscript } from "hooks/use-transcript";
+import { parseVTT } from "./utils/transcript-utils";
+import { CapVideoPlayer } from "./CapVideoPlayer";
declare global {
interface Window {
@@ -39,23 +17,6 @@ declare global {
}
}
-const formatTime = (time: number) => {
- const minutes = Math.floor(time / 60);
- const seconds = Math.floor(time % 60);
- return `${minutes.toString().padStart(2, "0")}:${seconds
- .toString()
- .padStart(2, "0")}`;
-};
-
-const formatTimeWithMilliseconds = (time: number) => {
- const minutes = Math.floor(time / 60);
- const seconds = Math.floor(time % 60);
- const milliseconds = Math.floor((time % 1) * 100);
- return `${minutes.toString().padStart(2, "0")}:${seconds
- .toString()
- .padStart(2, "0")}.${milliseconds.toString().padStart(2, "0")}`;
-};
-
type CommentWithAuthor = typeof commentsSchema.$inferSelect & {
authorName: string | null;
};
@@ -70,893 +31,88 @@ export const ShareVideo = forwardRef<
aiProcessing?: boolean;
}
>(({ data, user, comments, chapters = [], aiProcessing = false }, ref) => {
+
+ const videoRef = useRef<HTMLVideoElement | null>(null);
useImperativeHandle(ref, () => videoRef.current as HTMLVideoElement);
- const videoRef = useRef<HTMLVideoElement>(null);
- const previewCanvasRef = useRef<HTMLCanvasElement>(null);
- const [isPlaying, setIsPlaying] = useState(false);
- const [currentTime, setCurrentTime] = useState(0);
- const [isLoading, setIsLoading] = useState(true);
- const [longestDuration, setLongestDuration] = useState(0);
- const [seeking, setSeeking] = useState(false);
- const [videoMetadataLoaded, setVideoMetadataLoaded] = useState(false);
- const [videoReadyToPlay, setVideoReadyToPlay] = useState(false);
- const [overlayVisible, setOverlayVisible] = useState(true);
- const [subtitlesVisible, setSubtitlesVisible] = useState(true);
const [upgradeModalOpen, setUpgradeModalOpen] = useState(false);
- const [tempOverlayVisible, setTempOverlayVisible] = useState(false);
-
- const [showPreview, setShowPreview] = useState(false);
- const [previewTime, setPreviewTime] = useState(0);
- const [previewPosition, setPreviewPosition] = useState(0);
- const [previewLoaded, setPreviewLoaded] = useState(false);
- const [previewWidth, setPreviewWidth] = useState(200);
- const [previewHeight, setPreviewHeight] = useState(112);
- const [isMP4Source, setIsMP4Source] = useState(false);
- const [thumbnailUrl, setThumbnailUrl] = useState<string | null>(null);
-
- const [videoSpeed, setVideoSpeed] = useState(1);
- const [isHoveringVideo, setIsHoveringVideo] = useState(false);
- const [isHoveringControls, setIsHoveringControls] = useState(false);
- const hideControlsTimeoutRef = useRef<NodeJS.Timeout | null>(null);
- const [userMuted, setUserMuted] = useState(false);
+ const [transcriptData, setTranscriptData] = useState<TranscriptEntry[]>([]);
+ const [subtitleUrl, setSubtitleUrl] = useState<string | null>(null);
+ const [chaptersUrl, setChaptersUrl] = useState<string | null>(null);
- const [scrubbingVideo, setScrubbingVideo] = useState<HTMLVideoElement | null>(
- null
- );
-
- const [isPreviewSeeking, setIsPreviewSeeking] = useState(false);
- const lastUpdateTimeRef = useRef<number>(0);
- const lastMousePosRef = useRef<number>(0);
-
- const isLargeScreen = useScreenSize();
-
- // Use TanStack Query for video source validation
- const { data: videoSourceData } = useVideoSourceValidation(
- data,
- videoMetadataLoaded
+ const { data: transcriptContent, error: transcriptError } = useTranscript(
+ data.id,
+ data.transcriptionStatus
);
- // Global timeline seeking (desktop)
- useEffect(() => {
- if (!seeking) return;
- const timeline = document.getElementById("seek");
- if (!timeline) return;
-
- const handleGlobalMouseMove = (e: MouseEvent) => {
- // Synthesize a React-like event for handleSeekMouseMove
- const rect = timeline.getBoundingClientRect();
- const syntheticEvent = {
- ...e,
- currentTarget: timeline,
- clientX: e.clientX,
- } as unknown as React.MouseEvent<HTMLDivElement>;
- handleSeekMouseMove(syntheticEvent);
- };
- const handleGlobalMouseUp = (e: MouseEvent) => {
- // Synthesize a React-like event for handleSeekMouseUp
- const rect = timeline.getBoundingClientRect();
- const syntheticEvent = {
- ...e,
- currentTarget: timeline,
- clientX: e.clientX,
- } as unknown as React.MouseEvent<HTMLDivElement>;
- handleSeekMouseUp(syntheticEvent);
- };
- document.addEventListener("mousemove", handleGlobalMouseMove);
- document.addEventListener("mouseup", handleGlobalMouseUp);
- return () => {
- document.removeEventListener("mousemove", handleGlobalMouseMove);
- document.removeEventListener("mouseup", handleGlobalMouseUp);
- };
- }, [seeking]);
-
- // Update isMP4Source based on query result
useEffect(() => {
- if (videoSourceData) {
- setIsMP4Source(videoSourceData.isMP4Source);
- } else if (videoMetadataLoaded) {
- setIsMP4Source(data.source.type === "desktopMP4");
- }
- }, [videoSourceData, videoMetadataLoaded, data.source.type]);
-
- useEffect(() => {
- if (videoRef.current) {
- if (typeof ref === "function") {
- ref(videoRef.current);
- } else if (ref) {
- ref.current = videoRef.current;
- }
- }
- }, [ref]);
-
- const showControls = () => {
- setOverlayVisible(true);
- if (hideControlsTimeoutRef.current) {
- clearTimeout(hideControlsTimeoutRef.current);
- hideControlsTimeoutRef.current = null;
- }
- };
-
- const scheduleHideControls = () => {
- if (hideControlsTimeoutRef.current) {
- clearTimeout(hideControlsTimeoutRef.current);
- }
-
- if (isPlaying && !isHoveringControls) {
- hideControlsTimeoutRef.current = setTimeout(() => {
- setOverlayVisible(false);
- }, 1000);
+ if (transcriptContent) {
+ const parsed = parseVTT(transcriptContent);
+ setTranscriptData(parsed);
+ } else if (transcriptError) {
+ console.error(
+ "[Transcript] Transcript error from React Query:",
+ transcriptError.message
+ );
}
- };
+ }, [transcriptContent, transcriptError]);
+ // Handle subtitle URL creation
useEffect(() => {
- const handleMouseMove = () => {
- showControls();
- scheduleHideControls();
- };
+ if (data.transcriptionStatus === "COMPLETE" && transcriptData && transcriptData.length > 0) {
+ const vttContent = formatTranscriptAsVTT(transcriptData);
+ const blob = new Blob([vttContent], { type: "text/vtt" });
+ const newUrl = URL.createObjectURL(blob);
- const handleMouseEnter = () => {
- setIsHoveringVideo(true);
- showControls();
- };
-
- const handleMouseLeave = () => {
- setIsHoveringVideo(false);
- if (!isHoveringControls) {
- scheduleHideControls();
+ // Clean up previous URL
+ if (subtitleUrl) {
+ URL.revokeObjectURL(subtitleUrl);
}
- };
-
- const videoContainer = document.getElementById("video-container");
- if (videoContainer) {
- videoContainer.addEventListener("mousemove", handleMouseMove);
- videoContainer.addEventListener("mouseenter", handleMouseEnter);
- videoContainer.addEventListener("mouseleave", handleMouseLeave);
- }
- return () => {
- if (videoContainer) {
- videoContainer.removeEventListener("mousemove", handleMouseMove);
- videoContainer.removeEventListener("mouseenter", handleMouseEnter);
- videoContainer.removeEventListener("mouseleave", handleMouseLeave);
- }
- if (hideControlsTimeoutRef.current) {
- clearTimeout(hideControlsTimeoutRef.current);
- }
- };
- }, [isPlaying, isHoveringControls]);
+ setSubtitleUrl(newUrl);
- useEffect(() => {
- if (isPlaying) {
- scheduleHideControls();
+ return () => {
+ URL.revokeObjectURL(newUrl);
+ };
} else {
- showControls();
- }
- }, [isPlaying, isHoveringControls]);
-
- useEffect(() => {
- if (isHoveringControls) {
- showControls();
- } else if (isPlaying && !isHoveringVideo) {
- scheduleHideControls();
- }
- }, [isHoveringControls, isPlaying, isHoveringVideo]);
-
- useEffect(() => {
- const handleShortcuts = (e: KeyboardEvent) => {
- const target = e.target as HTMLElement;
- const isFormElement =
- target.tagName === "INPUT" ||
- target.tagName === "TEXTAREA" ||
- target.tagName === "SELECT" ||
- target.isContentEditable ||
- target.getAttribute("role") === "textbox";
-
- if (!isFormElement && videoRef.current) {
- if (e.code === "Space") {
- e.preventDefault();
- if (isPlaying) {
- videoRef.current.pause();
- setIsPlaying(false);
- } else {
- videoRef.current.play();
- setIsPlaying(true);
- }
- }
- }
- };
-
- window.addEventListener("keydown", handleShortcuts);
-
- return () => {
- window.removeEventListener("keydown", handleShortcuts);
- };
- }, [isPlaying, videoRef]);
-
- useEffect(() => {
- const onVideoLoadedMetadata = () => {
- if (videoRef.current) {
- setLongestDuration(videoRef.current.duration);
- setVideoMetadataLoaded(true);
+ // Clean up if no longer needed
+ if (subtitleUrl) {
+ URL.revokeObjectURL(subtitleUrl);
+ setSubtitleUrl(null);
}
- };
-
- const onCanPlay = () => {
- setVideoMetadataLoaded(true);
- setVideoReadyToPlay(true);
-
- setTimeout(() => {
- setIsLoading(false);
- }, 100);
- };
-
- const videoElement = videoRef.current;
- if (videoElement) {
- videoElement.addEventListener("loadedmetadata", onVideoLoadedMetadata);
- videoElement.addEventListener("canplay", onCanPlay);
- }
-
- return () => {
- if (videoElement) {
- videoElement.removeEventListener(
- "loadedmetadata",
- onVideoLoadedMetadata
- );
- videoElement.removeEventListener("canplay", onCanPlay);
- }
- };
- }, []);
-
- const handlePlayPauseClick = async (): Promise<void> => {
- const videoElement = videoRef.current;
- if (!videoElement) return;
-
- if (isPlaying) {
- videoElement.pause();
- setIsPlaying(false);
- setTempOverlayVisible(true); // Show overlay briefly on pause
- return;
- }
-
- if (!videoReadyToPlay) {
- console.warn('Video is not ready to play yet.');
- return;
}
+ }, [data.transcriptionStatus, transcriptData]);
- const currentPosition = videoElement.currentTime;
-
- try {
- videoElement.muted = userMuted;
-
- await videoElement.play();
- setIsPlaying(true);
- setTempOverlayVisible(true); // Show overlay briefly on play
- scheduleHideControls(); // Schedule hiding controls after play
-
- if (videoElement.currentTime === 0 && currentPosition > 0) {
- videoElement.currentTime = currentPosition;
- }
-
- if (videoElement.muted !== userMuted) {
- setUserMuted(videoElement.muted);
- }
- } catch (error: unknown) {
- const playError = error as DOMException;
- console.error('Error playing video:', playError);
-
- if (playError.name === 'NotAllowedError') {
- try {
- videoElement.muted = true;
- await videoElement.play();
- setIsPlaying(true);
- setUserMuted(true);
- setTempOverlayVisible(true);
- scheduleHideControls();
-
- if (videoElement.currentTime === 0 && currentPosition > 0) {
- videoElement.currentTime = currentPosition;
- }
-
- if (!userMuted) {
- requestAnimationFrame(() => {
- try {
- videoElement.muted = false;
- setUserMuted(false);
- } catch (err) {
- console.error('Error unmuting video:', err);
- }
- });
- }
- } catch (mutedError: unknown) {
- console.error('Failed to play video even with mute:', mutedError);
- setIsPlaying(false);
- setTempOverlayVisible(true);
- }
- } else {
- setIsPlaying(false);
- setTempOverlayVisible(true);
- }
- }
- };
-
-
- const applyTimeToVideos = (time: number) => {
- if (!Number.isFinite(time)) {
- console.warn("Attempted to set non-finite time:", time);
- return;
- }
- const validTime = Math.max(0, Math.min(time, longestDuration));
-
- if (videoRef.current && videoRef.current.readyState >= 2) {
- try {
- const video = videoRef.current;
- video.currentTime = validTime;
-
- const handleSeeked = () => {
- setCurrentTime(video.currentTime);
- video.removeEventListener("seeked", handleSeeked);
- };
-
- video.addEventListener("seeked", handleSeeked);
-
- setTimeout(() => {
- video.removeEventListener("seeked", handleSeeked);
- }, 1000);
- } catch (error) {
- console.error("Error setting video currentTime:", error);
- }
- }
- };
-
- useEffect(() => {
- const videoElement = videoRef.current;
- if (!videoElement || !videoReadyToPlay) return;
-
- const handleTimeUpdate = () => {
- setCurrentTime(videoElement.currentTime);
- };
-
- videoElement.addEventListener("timeupdate", handleTimeUpdate);
- const handleEnded = () => {
- if (videoRef.current && videoRef.current.currentTime === videoRef.current.duration) {
- setIsPlaying(false);
- }
- };
- videoElement.addEventListener("ended", handleEnded);
-
- return () => {
- videoElement.removeEventListener("timeupdate", handleTimeUpdate);
- videoElement.removeEventListener("ended", handleEnded);
- };
- }, [videoReadyToPlay]);
-
+ // Handle chapters URL creation
useEffect(() => {
- const videoElement = videoRef.current;
- if (!videoElement || !videoReadyToPlay) return;
+ if (chapters?.length > 0) {
+ const vttContent = formatChaptersAsVTT(chapters);
+ const blob = new Blob([vttContent], { type: "text/vtt" });
+ const newUrl = URL.createObjectURL(blob);
- if (isPlaying) {
- if (!seeking) {
- videoElement.play().catch((error) => {
- console.error("Error playing video", error);
- setIsPlaying(false);
- });
+ // Clean up previous URL
+ if (chaptersUrl) {
+ URL.revokeObjectURL(chaptersUrl);
}
- } else {
- videoElement.pause();
- }
- }, [isPlaying, videoReadyToPlay, seeking]);
-
- useEffect(() => {
- const handleSeeking = () => {
- if (seeking && videoRef.current) {
- setCurrentTime(videoRef.current.currentTime);
- }
- };
-
- const preventScroll = (e: TouchEvent) => {
- if (seeking) {
- e.preventDefault();
- }
- };
-
- const videoElement = videoRef.current;
-
- if (!videoElement) return;
-
- videoElement.addEventListener("seeking", handleSeeking);
- window.addEventListener("touchmove", preventScroll, { passive: false });
-
- return () => {
- videoElement.removeEventListener("seeking", handleSeeking);
- window.removeEventListener("touchmove", preventScroll);
- };
- }, [seeking]);
-
- useEffect(() => {
- setTempOverlayVisible(true);
-
- const timer = setTimeout(() => {
- setTempOverlayVisible(false);
- }, 500);
-
- return () => clearTimeout(timer);
- }, [isPlaying]);
-
- useEffect(() => {
- if (isMP4Source && data && isLargeScreen) {
- const scrubVideo = document.createElement("video");
- const mp4Source = `/api/playlist?userId=${data.ownerId}&videoId=${data.id}&videoType=mp4`;
-
- scrubVideo.src = mp4Source;
- scrubVideo.crossOrigin = "anonymous";
- scrubVideo.preload = "auto";
- scrubVideo.muted = true;
- scrubVideo.style.display = "none";
-
- scrubVideo.addEventListener("loadedmetadata", () => {
- scrubVideo.currentTime = 0;
- });
-
- scrubVideo.addEventListener("canplay", () => {
- setScrubbingVideo(scrubVideo);
-
- if (previewCanvasRef.current) {
- const canvas = previewCanvasRef.current;
- const ctx = canvas.getContext("2d");
-
- if (ctx) {
- if (
- canvas.width !== previewWidth ||
- canvas.height !== previewHeight
- ) {
- canvas.width = previewWidth;
- canvas.height = previewHeight;
- }
-
- try {
- ctx.drawImage(scrubVideo, 0, 0, canvas.width, canvas.height);
- setPreviewLoaded(true);
- } catch (err) {
- console.error("Error preloading initial frame:", err);
- }
- }
- }
- });
-
- scrubVideo.addEventListener("error", (e) => {
- console.error("Error loading scrubbing video:", e);
- });
-
- document.body.appendChild(scrubVideo);
+ setChaptersUrl(newUrl);
return () => {
- scrubVideo.remove();
- setScrubbingVideo(null);
+ URL.revokeObjectURL(newUrl);
};
- } else if (!isLargeScreen) {
- setScrubbingVideo(null);
- }
- }, [isMP4Source, data, previewWidth, previewHeight, isLargeScreen]);
-
- const updatePreviewFrame = (time: number) => {
- if (!isLargeScreen || !isMP4Source) return;
-
- setPreviewTime(time);
-
- if (isPreviewSeeking) return;
-
- const drawFrame = () => {
- try {
- if (scrubbingVideo && previewCanvasRef.current) {
- const canvas = previewCanvasRef.current;
- const ctx = canvas.getContext("2d");
-
- if (ctx) {
- // Ensure canvas dimensions match preview size
- if (canvas.width !== previewWidth || canvas.height !== previewHeight) {
- canvas.width = previewWidth;
- canvas.height = previewHeight;
- }
-
- setIsPreviewSeeking(true);
- scrubbingVideo.currentTime = time;
-
- const handleSeeked = () => {
- try {
- // Draw the video frame
- ctx.drawImage(scrubbingVideo, 0, 0, canvas.width, canvas.height);
-
- // Draw time overlay
- ctx.fillStyle = "rgba(0, 0, 0, 0.7)";
- ctx.fillRect(0, canvas.height - 20, canvas.width, 20);
- ctx.fillStyle = "white";
- ctx.font = "12px Arial";
- ctx.textAlign = "center";
- ctx.fillText(formatTime(time), canvas.width / 2, canvas.height - 6);
-
- setPreviewLoaded(true);
- } catch (err) {
- console.error("Error drawing frame:", err);
- } finally {
- setIsPreviewSeeking(false);
- scrubbingVideo.removeEventListener("seeked", handleSeeked);
- }
- };
-
- scrubbingVideo.addEventListener("seeked", handleSeeked);
-
- // Fallback if seeked event doesn't fire within 250ms
- const timeoutId = setTimeout(() => {
- if (isPreviewSeeking) {
- try {
- ctx.drawImage(scrubbingVideo, 0, 0, canvas.width, canvas.height);
- ctx.fillStyle = "rgba(0, 0, 0, 0.7)";
- ctx.fillRect(0, canvas.height - 20, canvas.width, 20);
- ctx.fillStyle = "white";
- ctx.font = "12px Arial";
- ctx.textAlign = "center";
- ctx.fillText(formatTime(time), canvas.width / 2, canvas.height - 6);
- setPreviewLoaded(true);
- } catch (err) {
- console.error("Error drawing frame after timeout:", err);
- } finally {
- setIsPreviewSeeking(false);
- scrubbingVideo.removeEventListener("seeked", handleSeeked);
- }
- }
- }, 250);
-
- return () => clearTimeout(timeoutId);
- }
- } else if (videoRef.current && previewCanvasRef.current) {
- const canvas = previewCanvasRef.current;
- const video = videoRef.current;
- const ctx = canvas.getContext("2d");
-
- if (ctx) {
- try {
- canvas.width = previewWidth;
- canvas.height = previewHeight;
-
- ctx.drawImage(video, 0, 0, canvas.width, canvas.height);
- ctx.fillStyle = "rgba(0, 0, 0, 0.7)";
- ctx.fillRect(0, canvas.height - 20, canvas.width, 20);
- ctx.fillStyle = "white";
- ctx.font = "12px Arial";
- ctx.textAlign = "center";
- ctx.fillText(formatTime(time), canvas.width / 2, canvas.height - 6);
-
- setPreviewLoaded(true);
- } catch (err) {
- console.error("Error in fallback video capture:", err);
- }
- }
- }
- } catch (err) {
- console.error("Error updating preview frame:", err);
- setIsPreviewSeeking(false);
- }
- };
-
- // Schedule the frame drawing with requestAnimationFrame
- const rafId = requestAnimationFrame(drawFrame);
-
- // Cleanup to cancel any pending animation frame
- return () => cancelAnimationFrame(rafId);
- };
-
- const handleTimelineHover = (
- event: React.MouseEvent<HTMLDivElement> | React.TouchEvent<HTMLDivElement>
- ) => {
- if (isLoading) return;
-
- if (!isLargeScreen) return;
-
- const seekBar = event.currentTarget;
- const time = calculateNewTime(event, seekBar);
-
- const rect = seekBar.getBoundingClientRect();
-
- let clientX = 0;
- if ("touches" in event && event.touches && event.touches[0]) {
- clientX = event.touches[0].clientX;
- } else if ("clientX" in event) {
- clientX = event.clientX;
- }
-
- const previewPos = clientX - rect.left - previewWidth / 2;
-
- const maxLeft = rect.width - previewWidth;
- const boundedPos = Math.max(0, Math.min(previewPos, maxLeft));
-
- setPreviewPosition(boundedPos);
-
- if (!showPreview) {
- setShowPreview(true);
- updatePreviewFrame(time);
- lastUpdateTimeRef.current = Date.now();
- return;
- }
-
- const currentMousePos = clientX;
- const lastMousePos = lastMousePosRef.current;
- lastMousePosRef.current = currentMousePos;
-
- const now = Date.now();
- const timeSinceLastUpdate = now - lastUpdateTimeRef.current;
- const significantMouseMove = Math.abs(currentMousePos - lastMousePos) > 10;
-
- if (
- !isPreviewSeeking &&
- (timeSinceLastUpdate >= 500 || significantMouseMove)
- ) {
- updatePreviewFrame(time);
- lastUpdateTimeRef.current = now;
- }
- };
-
- const calculateNewTime = (event: any, seekBar: any) => {
- if (!longestDuration || longestDuration <= 0) {
- return 0;
- }
-
- const rect = seekBar.getBoundingClientRect();
-
- if (rect.width <= 0) {
- return 0;
- }
-
- let clientX = 0;
- if (event.touches && event.touches.length > 0) {
- clientX = event.touches[0].clientX;
- } else if (typeof event.clientX === "number") {
- clientX = event.clientX;
- }
-
- const offsetX = Math.max(0, Math.min(clientX - rect.left, rect.width));
- const relativePosition = offsetX / rect.width;
- const newTime = Math.max(
- 0,
- Math.min(relativePosition * longestDuration, longestDuration)
- );
-
- return newTime;
- };
-
- const handleSeekMouseDown = () => {
- if (videoRef.current && videoRef.current.readyState >= 2) {
- setSeeking(true);
- }
- };
-
- const handleSeekMouseUp = (
- event: React.MouseEvent | React.TouchEvent,
- isTouch = false
- ) => {
- if (!seeking) return;
- setSeeking(false);
- const seekBar = event.currentTarget;
- const seekTo = calculateNewTime(event, seekBar);
-
- applyTimeToVideos(seekTo);
-
- if (isPlaying && videoRef.current) {
- setTimeout(() => {
- videoRef.current?.play().catch((error) => {
- console.error("Error resuming playback after seek:", error);
- });
- }, 100);
- }
- setShowPreview(false);
- };
-
- const handleSeekMouseMove = (event: React.MouseEvent | React.TouchEvent) => {
- if (!seeking) return;
-
- const seekBar = event.currentTarget;
- const seekTo = calculateNewTime(event, seekBar);
-
- if (Math.abs(seekTo - currentTime) > 0.1) {
- applyTimeToVideos(seekTo);
- }
- };
-
- const handleTimelineLeave = () => {
- if (!isLargeScreen) return;
-
- setShowPreview(false);
- lastUpdateTimeRef.current = 0;
- };
-
- const handleMuteClick = () => {
- if (videoRef.current) {
- const newMutedState = !videoRef.current.muted;
- videoRef.current.muted = newMutedState;
- setUserMuted(newMutedState);
- }
- };
-
- const handleFullscreenClick = () => {
- const player = document.getElementById("video-player");
- const video = videoRef.current;
-
- if (!video) return;
-
- const isIOS =
- /iPad|iPhone|iPod/.test(navigator.userAgent) && !window.MSStream;
- const isAndroid = /Android/.test(navigator.userAgent);
-
- if (isIOS || isAndroid) {
- if (video.requestFullscreen) {
- video
- .requestFullscreen()
- .catch((err) =>
- console.error(
- `Error attempting to enable full-screen mode on mobile: ${err.message} (${err.name})`
- )
- );
- } else if ("webkitEnterFullscreen" in video) {
- (video as any).webkitEnterFullscreen();
- } else if ("mozRequestFullScreen" in video) {
- (video as any).mozRequestFullScreen();
- } else if ("msRequestFullscreen" in video) {
- (video as any).msRequestFullscreen();
- }
} else {
- if (!document.fullscreenElement) {
- if (player && player.requestFullscreen) {
- player
- .requestFullscreen()
- .catch((err) =>
- console.error(
- `Error attempting to enable full-screen mode: ${err.message} (${err.name})`
- )
- );
- } else if (player && "webkitRequestFullscreen" in player) {
- (player as any).webkitRequestFullscreen();
- } else if (player && "mozRequestFullScreen" in player) {
- (player as any).mozRequestFullScreen();
- } else if (player && "msRequestFullscreen" in player) {
- (player as any).msRequestFullscreen();
- }
- } else {
- if (document.exitFullscreen) {
- document.exitFullscreen();
- } else if ("webkitExitFullscreen" in document) {
- (document as any).webkitExitFullscreen();
- } else if ("mozCancelFullScreen" in document) {
- (document as any).mozCancelFullScreen();
- } else if ("msExitFullscreen" in document) {
- (document as any).msExitFullscreen();
- }
+ // Clean up if no longer needed
+ if (chaptersUrl) {
+ URL.revokeObjectURL(chaptersUrl);
+ setChaptersUrl(null);
}
}
- };
-
- const handleSpeedChange = () => {
- let newSpeed;
- if (videoSpeed === 1) {
- newSpeed = 1.5;
- } else if (videoSpeed === 1.5) {
- newSpeed = 2;
- } else {
- newSpeed = 1;
- }
- setVideoSpeed(newSpeed);
- if (videoRef.current) {
- videoRef.current.playbackRate = newSpeed;
- }
- };
-
- const watchedPercentage =
- longestDuration > 0 ? (currentTime / longestDuration) * 100 : 0;
-
- useEffect(() => {
- if (!videoRef.current || !videoReadyToPlay) return;
-
- const videoElement = videoRef.current;
-
- if (isPlaying) {
- const playPromise = videoElement.play();
- if (playPromise !== undefined) {
- playPromise.catch((error) => {
- console.error("Error in useEffect play:", error);
- });
- }
- } else {
- videoElement.pause();
- }
- }, [isPlaying, videoReadyToPlay]);
-
- const parseSubTime = (timeString: number) => {
- const timeStr = timeString.toString();
- const timeParts = timeStr.split(":");
-
- const hoursValue = timeParts.length > 2 ? Number(timeParts[0]) || 0 : 0;
- const minutesValue =
- timeParts.length > 1 ? Number(timeParts[timeParts.length - 2]) || 0 : 0;
- const secondsValue = Number(timeParts[timeParts.length - 1]) || 0;
-
- return hoursValue * 3600 + minutesValue * 60 + secondsValue;
- };
+ }, [chapters]);
const publicEnv = usePublicEnv();
- const apiClient = useApiClient();
-
- const { data: transcriptContent, error: transcriptError } = useTranscript(
- data.id,
- data.transcriptionStatus
- );
-
- // Use custom hook for transcription processing
- const { isTranscriptionProcessing, subtitles } = useTranscriptionProcessing(
- data,
- transcriptContent,
- transcriptError
- );
-
- const currentSubtitle = subtitles.find(
- (subtitle) =>
- parseSubTime(subtitle.startTime) <= currentTime &&
- parseSubTime(subtitle.endTime) >= currentTime
- );
-
- useEffect(() => {
- if (previewCanvasRef.current && isLargeScreen) {
- const canvas = previewCanvasRef.current;
- const ctx = canvas.getContext("2d");
-
- if (ctx) {
- canvas.width = previewWidth;
- canvas.height = previewHeight;
-
- ctx.fillStyle = "#000000";
- ctx.fillRect(0, 0, canvas.width, canvas.height);
-
- ctx.fillStyle = "white";
- ctx.font = "12px Arial";
- ctx.textAlign = "center";
- ctx.fillText("Hover to preview", canvas.width / 2, canvas.height / 2);
- }
- }
- }, [previewCanvasRef, previewWidth, previewHeight, isLargeScreen]);
-
- useEffect(() => {
- const detectSafari = () => {
- const isSafari =
- /^((?!chrome|android).)*safari/i.test(navigator.userAgent) ||
- (navigator.userAgent.includes("AppleWebKit") &&
- !navigator.userAgent.includes("Chrome"));
-
- const videoContainer = document.getElementById("video-container");
- if (videoContainer && isSafari) {
- videoContainer.style.height = "calc(100% - 1.75rem)";
- }
- };
-
- detectSafari();
- }, []);
-
- if (data.jobStatus === "ERROR") {
- return (
- <div className="flex overflow-hidden justify-center items-center w-full h-full rounded-lg">
- <div
- style={{ paddingBottom: "min(806px, 56.25%)" }}
- className="flex relative justify-center items-center p-8 w-full h-full bg-black rounded-lg"
- >
- <p className="text-xl text-white">
- There was an error when processing the video. Please contact
- support.
- </p>
- </div>
- </div>
- );
- }
let videoSrc: string;
-
+ let videoType: string = "video/mp4";
if (data.source.type === "desktopMP4") {
videoSrc = `/api/playlist?userId=${data.ownerId}&videoId=${data.id}&videoType=mp4`;
} else if (
@@ -965,469 +121,23 @@ export const ShareVideo = forwardRef<
data.source.type === "MediaConvert")
) {
videoSrc = `/api/playlist?userId=${data.ownerId}&videoId=${data.id}&videoType=master`;
+ videoType = "application/x-mpegURL";
} else if (data.source.type === "MediaConvert") {
videoSrc = `${publicEnv.s3BucketUrl}/${data.ownerId}/${data.id}/output/video_recording_000.m3u8`;
+ videoType = "application/x-mpegURL";
} else {
videoSrc = `${publicEnv.s3BucketUrl}/${data.ownerId}/${data.id}/combined-source/stream.m3u8`;
+ videoType = "application/x-mpegURL";
}
return (
- <div
- id="video-container"
- className="overflow-hidden relative w-full h-full rounded-lg shadow-lg group"
- >
- <div
- className={`absolute inset-0 flex items-center justify-center z-10 bg-black transition-opacity duration-300 ${isLoading ? "opacity-100" : "opacity-0 pointer-events-none"
- }`}
- >
- <LogoSpinner className="w-8 h-auto animate-spin sm:w-10" />
- </div>
- <div className="relative w-full h-full">
- <div className="absolute inset-0 bg-black">
- {data.source.type === "desktopMP4" ? (
- <MP4VideoPlayer ref={videoRef} videoSrc={videoSrc} />
- ) : (
- <VideoPlayer ref={videoRef} videoSrc={videoSrc} />
- )}
- </div>
- {!isLoading && (
- <div
- className={`absolute inset-0 z-20 flex items-center justify-center transition-opacity duration-300 ${(overlayVisible && isPlaying) || tempOverlayVisible || !isPlaying
- ? "opacity-100"
- : "opacity-0"
- }`}
- >
- <button
- aria-label={isPlaying ? "Pause video" : "Play video"}
- className="flex justify-center items-center w-full h-full"
- onClick={() => {
- if (!videoReadyToPlay) {
- setIsPlaying(true);
- } else {
- handlePlayPauseClick();
- }
- }}
- >
- <AnimatePresence initial={false} mode="popLayout">
- {isPlaying ? (
- <motion.div
- key="pause-button"
- className="flex relative z-30 justify-center items-center bg-black bg-opacity-60 rounded-full size-20"
- initial={{ opacity: 0, scale: 0 }}
- animate={{
- scale: 1,
- opacity: overlayVisible || tempOverlayVisible ? 1 : 0,
- }}
- style={{ transformOrigin: "center center" }}
- transition={{ duration: 0.4, ease: "easeOut" }}
- >
- <Pause className="w-auto h-8 text-white sm:h-10 md:h-12" />
- </motion.div>
- ) : (
- <motion.div
- key="play-button"
- className="flex relative z-30 justify-center items-center bg-black bg-opacity-60 rounded-full size-20"
- initial={{ opacity: 0, scale: 0 }}
- animate={{
- scale: 1,
- opacity: 1,
- }}
- style={{ transformOrigin: "center center" }}
- transition={{ duration: 0.4, ease: "easeOut" }}
- >
- <Play className="w-auto h-8 text-white sm:h-10 md:h-12 ml-0.5" />
- </motion.div>
- )}
- </AnimatePresence>
- </button>
- </div>
- )}
- {currentSubtitle && currentSubtitle.text && subtitlesVisible && (
- <div
- className={`absolute z-10 p-2 w-full text-center transition-all duration-300 ease-in-out ${overlayVisible ? "bottom-16 sm:bottom-20" : "bottom-6 sm:bottom-8"
- }`}
- >
- <div className="inline px-2 py-1 text-sm text-white bg-black bg-opacity-75 rounded-xl sm:text-lg md:text-2xl">
- {currentSubtitle.text
- .replace("- ", "")
- .replace(".", "")
- .replace(",", "")}
- </div>
- </div>
- )}
- </div>
-
- {showPreview && !isLoading && isMP4Source && isLargeScreen && (
- <div
- className="hidden absolute z-30 transition-opacity duration-150 xl:block"
- style={{
- left: `${previewPosition}px`,
- bottom: "80px",
- opacity: previewLoaded ? 1 : 0.7,
- }}
- >
- <div className="flex flex-col items-center">
- <div
- style={{ boxShadow: "0 0 100px rgba(0, 0, 0, 0.75)" }}
- className="overflow-hidden bg-black rounded-lg border border-gray-600"
- >
- <div
- className="bg-black"
- style={{
- width: `${previewWidth}px`,
- height: `${previewHeight}px`,
- }}
- >
- {thumbnailUrl ? (
- <img
- src={thumbnailUrl}
- alt={`Preview at ${formatTime(previewTime)}`}
- className="object-contain w-full h-full bg-black"
- onError={() => {
- setThumbnailUrl(null);
- }}
- />
- ) : (
- <canvas
- ref={previewCanvasRef}
- className="object-contain w-full h-full bg-black"
- />
- )}
- </div>
- </div>
- <div className="mt-2 text-center space-y-0.5">
- {chapters.length > 0 && longestDuration > 0 && (
- <div
- className="text-sm font-medium leading-tight text-white"
- style={{ textShadow: "0 0 3px rgba(0, 0, 0, 0.7)" }}
- >
- {(() => {
- const previewChapter = chapters.find((chapter, index) => {
- const nextChapter = chapters[index + 1];
- const chapterStart = chapter.start;
- const chapterEnd = nextChapter
- ? nextChapter.start
- : longestDuration;
- return (
- previewTime >= chapterStart && previewTime < chapterEnd
- );
- });
- return previewChapter ? previewChapter.title : "";
- })()}
- </div>
- )}
- <div
- className="text-sm font-medium text-white"
- style={{ textShadow: "0 0 3px rgba(0, 0, 0, 0.7)" }}
- >
- {formatTimeWithMilliseconds(previewTime)}
- </div>
- </div>
- </div>
- </div>
- )}
-
- <div
- className={`absolute left-0 right-0 z-30 transition-all duration-300 ease-in-out ${overlayVisible ? "bottom-[40px] md:bottom-[60px]" : "bottom-1"
- }`}
- >
- <div
- id="seek"
- className="h-6 cursor-pointer"
- onMouseDown={handleSeekMouseDown}
- onTouchStart={handleSeekMouseDown}
- onTouchMove={(e) => {
- handleSeekMouseMove(e);
- }}
- >
- {!isLoading && (
- <Suspense>
- <CommentIndicators
- className="-mt-6 w-full md:-mt-6"
- comments={comments}
- longestDuration={longestDuration}
- />
- </Suspense>
- )}
-
- <div
- className="relative w-full h-full"
- onMouseMove={handleTimelineHover}
- onMouseLeave={handleTimelineLeave}
- >
- {/* Render chapter backgrounds */}
- {chapters.length > 0 && longestDuration > 0 ? (
- <div className="absolute top-2.5 w-full h-1 sm:h-1.5 z-10 flex">
- {chapters.map((chapter, index) => {
- const nextChapter = chapters[index + 1];
- const chapterStart = chapter.start;
- const chapterEnd = nextChapter ? nextChapter.start : longestDuration;
- const chapterDuration = chapterEnd - chapterStart;
- const chapterWidth = (chapterDuration / longestDuration) * 100;
- return (
- <div
- key={chapter.start}
- className="relative h-full cursor-pointer group"
- style={{
- width: `${chapterWidth}%`,
- background: "rgba(156, 163, 175, 0.5)", // bg-gray-400 bg-opacity-50
- borderRight:
- index < chapters.length - 1
- ? "1px solid rgba(255,255,255,0.3)"
- : "none",
- }}
- onClick={(e) => {
- e.stopPropagation();
- applyTimeToVideos(chapter.start);
- }}
- />
- );
- })}
- </div>
- ) : (
- <div className="absolute top-2.5 w-full h-1 sm:h-1.5 bg-gray-400 bg-opacity-50 z-10" />
- )}
- {/* Render the main progress bar (white) */}
- <div
- className="absolute top-2.5 h-1 sm:h-1.5 bg-white z-20"
- style={{ width: `${Math.max(0, Math.min(watchedPercentage + 0.82, 99.15))}%` }}
- />
- <div
- style={{
- boxShadow: "0 0 20px rgba(0,0,0,0.1)",
- left: `calc(${Math.max(0, Math.min(watchedPercentage + 0.82, 99.15))}% )`,
- }}
- className={clsx(
- "drag-button absolute top-2 z-20 mx-auto -mt-1.5 w-5 h-5 bg-white rounded-full cursor-pointer focus:outline-none border-2 border-gray-5 -translate-x-1/2",
+ <>
- seeking
- ? "scale-125 transition-transform ring-blue-300 ring-offset-2 ring-2"
- : ""
- )}
- tabIndex={0}
- />
- </div>
- </div>
+ <div className="relative h-full">
+ <CapVideoPlayer hlsVideo={videoType === "application/x-mpegURL"} mediaPlayerClassName="w-full rounded-xl h-full"
+ videoSrc={videoSrc} chaptersSrc={chaptersUrl || ""} captionsSrc={subtitleUrl || ""} videoRef={videoRef} />
</div>
- <div
- className={`absolute bottom-0 left-0 right-0 bg-black bg-opacity-60 z-20 transition-transform duration-300 ease-in-out ${overlayVisible ? "translate-y-0" : "translate-y-full"
- }`}
- onMouseEnter={() => {
- setIsHoveringControls(true);
- }}
- onMouseLeave={() => {
- setIsHoveringControls(false);
- }}
- >
- <div className="flex justify-between items-center px-4 py-2">
- <div className="flex items-center mt-2 space-x-2 sm:space-x-3">
- <span className="inline-flex">
- <button
- aria-label="Play video"
- className="inline-flex justify-center items-center px-1 py-1 text-sm font-medium text-gray-100 rounded-lg border border-transparent transition duration-150 ease-in-out focus:outline-none hover:text-white focus:border-white hover:bg-gray-100 hover:bg-opacity-10 active:bg-gray-100 active:bg-opacity-10 sm:px-2 sm:py-2"
- tabIndex={0}
- type="button"
- onClick={() => handlePlayPauseClick()}
- >
- {isPlaying ? (
- <Pause className="w-auto h-5 sm:h-6" />
- ) : (
- <Play className="w-auto h-5 sm:h-6" />
- )}
- </button>
- </span>
- <div className="flex items-center space-x-2">
- <div className="overflow-hidden text-xs font-medium text-white whitespace-nowrap select-none sm:text-sm tabular text-clip">
- {formatTime(currentTime)} - {formatTime(longestDuration)}
- </div>
- {chapters.length > 0 && longestDuration > 0 && (
- <div className="hidden sm:block text-xs sm:text-sm text-gray-200 font-medium select-none text-clip overflow-hidden whitespace-nowrap max-w-[200px]">
- {(() => {
- const currentChapter = chapters.find((chapter, index) => {
- const nextChapter = chapters[index + 1];
- const chapterStart = chapter.start;
- const chapterEnd = nextChapter
- ? nextChapter.start
- : longestDuration;
- return (
- currentTime >= chapterStart && currentTime < chapterEnd
- );
- });
- return currentChapter ? `• ${currentChapter.title}` : "";
- })()}
- </div>
- )}
- </div>
- </div>
- <div className="flex justify-end space-x-1 sm:space-x-2">
- <div className="flex justify-end items-center space-x-1 sm:space-x-2">
- <span className="inline-flex">
- <button
- aria-label={`Change video speed to ${videoSpeed}x`}
- className="inline-flex min-w-[35px] sm:min-w-[45px] items-center text-xs sm:text-sm font-medium transition ease-in-out duration-150 focus:outline-none border text-gray-100 border-transparent hover:text-white focus:border-white hover:bg-gray-100 hover:bg-opacity-10 active:bg-gray-100 active:bg-opacity-10 px-1 sm:px-2 py-1 sm:py-2 justify-center rounded-lg"
- tabIndex={0}
- type="button"
- onClick={handleSpeedChange}
- >
- {videoSpeed}x
- </button>
- </span>
- {isTranscriptionProcessing && subtitles.length === 0 && (
- <span className="inline-flex">
- <button
- aria-label={isPlaying ? "Pause video" : "Play video"}
- className="inline-flex justify-center items-center px-1 py-1 text-sm font-medium text-gray-100 rounded-lg border border-transparent transition duration-150 ease-in-out focus:outline-none hover:text-white focus:border-white hover:bg-gray-100 hover:bg-opacity-10 active:bg-gray-100 active:bg-opacity-10 sm:px-2 sm:py-2"
- tabIndex={0}
- type="button"
- onClick={() => {
- toast.error("Transcription is processing");
- }}
- >
- <svg
- xmlns="http://www.w3.org/2000/svg"
- className="w-5 h-5 sm:w-6 sm:h-6"
- viewBox="0 0 24 24"
- >
- <style>
- {
- "@keyframes spinner_AtaB{to{transform:rotate(360deg)}}"
- }
- </style>
- <path
- fill="#FFF"
- d="M12 1a11 11 0 1 0 11 11A11 11 0 0 0 12 1Zm0 19a8 8 0 1 1 8-8 8 8 0 0 1-8 8Z"
- opacity={0.25}
- />
- <path
- fill="#FFF"
- d="M10.14 1.16a11 11 0 0 0-9 8.92A1.59 1.59 0 0 0 2.46 12a1.52 1.52 0 0 0 1.65-1.3 8 8 0 0 1 6.66-6.61A1.42 1.42 0 0 0 12 2.69a1.57 1.57 0 0 0-1.86-1.53Z"
- style={{
- transformOrigin: "center",
- animation: "spinner_AtaB .75s infinite linear",
- }}
- />
- </svg>
- </button>
- </span>
- )}
- {aiProcessing && (
- <span className="inline-flex">
- <button
- aria-label="AI summary is processing"
- className="inline-flex justify-center items-center px-1 py-1 text-sm font-medium text-gray-100 rounded-lg border border-transparent transition duration-150 ease-in-out focus:outline-none hover:text-white focus:border-white hover:bg-gray-100 hover:bg-opacity-10 active:bg-gray-100 active:bg-opacity-10 sm:px-2 sm:py-2"
- tabIndex={0}
- type="button"
- onClick={() => {
- toast.info("AI summary is being generated");
- }}
- >
- <svg
- xmlns="http://www.w3.org/2000/svg"
- className="w-5 h-5 sm:w-6 sm:h-6"
- viewBox="0 0 24 24"
- >
- <style>
- {
- "@keyframes spinner_AtaB{to{transform:rotate(360deg)}}"
- }
- </style>
- <path
- fill="#FFF"
- d="M12 1a11 11 0 1 0 11 11A11 11 0 0 0 12 1Zm0 19a8 8 0 1 1 8-8 8 8 0 0 1-8 8Z"
- opacity={0.25}
- />
- <path
- fill="#FFF"
- d="M10.14 1.16a11 11 0 0 0-9 8.92A1.59 1.59 0 0 0 2.46 12a1.52 1.52 0 0 0 1.65-1.3 8 8 0 0 1 6.66-6.61A1.42 1.42 0 0 0 12 2.69a1.57 1.57 0 0 0-1.86-1.53Z"
- style={{
- transformOrigin: "center",
- animation: "spinner_AtaB .75s infinite linear",
- }}
- />
- </svg>
- </button>
- </span>
- )}
- {subtitles.length > 0 && (
- <span className="inline-flex">
- <button
- aria-label={
- subtitlesVisible ? "Hide subtitles" : "Show subtitles"
- }
- className="inline-flex justify-center items-center px-1 py-1 text-sm font-medium text-gray-100 rounded-lg border border-transparent transition duration-150 ease-in-out focus:outline-none hover:text-white focus:border-white hover:bg-gray-100 hover:bg-opacity-10 active:bg-gray-100 active:bg-opacity-10 sm:px-2 sm:py-2"
- tabIndex={0}
- type="button"
- onClick={() => setSubtitlesVisible(!subtitlesVisible)}
- >
- {subtitlesVisible ? (
- <svg
- xmlns="http://www.w3.org/2000/svg"
- fill="none"
- stroke="currentColor"
- strokeLinecap="round"
- strokeLinejoin="round"
- strokeWidth="2"
- className="w-auto h-5 sm:h-6"
- viewBox="0 0 24 24"
- >
- <rect
- width="18"
- height="14"
- x="3"
- y="5"
- rx="2"
- ry="2"
- ></rect>
- <path d="M7 15h4m4 0h2m4 0h2"></path>
- </svg>
- ) : (
- <svg
- xmlns="http://www.w3.org/2000/svg"
- fill="none"
- stroke="currentColor"
- strokeLinecap="round"
- strokeLinejoin="round"
- strokeWidth="2"
- className="w-auto h-5 sm:h-6"
- viewBox="0 0 24 24"
- >
- <path d="M10.5 5H19a2 2 0 012 2v8.5M17 11h-.5M19 19H5a2 2 0 01-2-2V7a2 2 0 012-2M2 2l20 20M7 11h4M7 15h2.5"></path>
- </svg>
- )}
- </button>
- </span>
- )}
- <span className="inline-flex">
- <button
- aria-label={videoRef?.current?.muted ? "Unmute" : "Mute"}
- className="inline-flex justify-center items-center px-1 py-1 text-sm font-medium text-gray-100 rounded-lg border border-transparent transition duration-150 ease-in-out focus:outline-none hover:text-white focus:border-white hover:bg-gray-100 hover:bg-opacity-10 active:bg-gray-100 active:bg-opacity-10 sm:px-2 sm:py-2"
- tabIndex={0}
- type="button"
- onClick={() => handleMuteClick()}
- >
- {videoRef?.current?.muted ? (
- <VolumeX className="w-auto h-5 sm:h-6" />
- ) : (
- <Volume2 className="w-auto h-5 sm:h-6" />
- )}
- </button>
- </span>
- <span className="inline-flex">
- <button
- aria-label="Go fullscreen"
- className="inline-flex justify-center items-center px-1 py-1 text-sm font-medium text-gray-100 rounded-lg border border-transparent transition duration-150 ease-in-out focus:outline-none hover:text-white focus:border-white hover:bg-gray-100 hover:bg-opacity-10 active:bg-gray-100 active:bg-opacity-10 sm:px-2 sm:py-2"
- tabIndex={0}
- type="button"
- onClick={handleFullscreenClick}
- >
- <Maximize className="w-auto h-5 sm:h-6" />
- </button>
- </span>
- </div>
- </div>
- </div>
- </div>
{user &&
!isUserOnProPlan({
subscriptionStatus: user.stripeSubscriptionStatus,
@@ -1458,148 +168,6 @@ export const ShareVideo = forwardRef<
open={upgradeModalOpen}
onOpenChange={setUpgradeModalOpen}
/>
- </div>
+ </>
);
});
-
-// Custom hook for video source validation using TanStack Query
-const useVideoSourceValidation = (
- data: typeof videos.$inferSelect,
- videoMetadataLoaded: boolean
-) => {
- return useQuery({
- queryKey: ["video-source-validation", data.id, data.source.type],
- queryFn: async () => {
- if (data.source.type !== "desktopMP4") {
- return { isMP4Source: false };
- }
-
- const thumbUrl = `/api/playlist?userId=${data.ownerId}&videoId=${data.id}&thumbnailTime=0`;
-
- try {
- const response = await fetch(thumbUrl, { method: "HEAD" });
- return { isMP4Source: response.ok };
- } catch (error) {
- console.error("Error checking thumbnails:", error);
- return { isMP4Source: false };
- }
- },
- enabled: videoMetadataLoaded && data.source.type === "desktopMP4",
- staleTime: 5 * 60 * 1000, // 5 minutes
- gcTime: 10 * 60 * 1000, // 10 minutes
- });
-};
-
-// Custom hook for screen size detection
-const useScreenSize = () => {
- const [isLargeScreen, setIsLargeScreen] = useState(false);
-
- useEffect(() => {
- const checkScreenSize = () => {
- setIsLargeScreen(window.innerWidth >= 1024);
- };
-
- checkScreenSize();
- window.addEventListener("resize", checkScreenSize);
-
- return () => window.removeEventListener("resize", checkScreenSize);
- }, []);
-
- return isLargeScreen;
-};
-
-// Custom hook for transcription processing
-const useTranscriptionProcessing = (
- data: typeof videos.$inferSelect,
- transcriptContent: string | undefined,
- transcriptError: any
-) => {
- const [isTranscriptionProcessing, setIsTranscriptionProcessing] = useState(
- data.transcriptionStatus === "PROCESSING"
- );
- const [subtitles, setSubtitles] = useState<Subtitle[]>([]);
-
- useEffect(() => {
- if (!transcriptContent && data.transcriptionStatus === "PROCESSING") {
- return setIsTranscriptionProcessing(false);
- }
- if (transcriptContent) {
- const parsedSubtitles = fromVtt(transcriptContent);
- setSubtitles(parsedSubtitles);
- setIsTranscriptionProcessing(false);
- } else if (transcriptError) {
- console.error(
- "[ShareVideo] Subtitle error from React Query:",
- transcriptError.message
- );
- if (transcriptError.message === "TRANSCRIPT_NOT_READY") {
- setIsTranscriptionProcessing(true);
- } else {
- setIsTranscriptionProcessing(false);
- }
- } else if (data.transcriptionStatus === "PROCESSING") {
- setIsTranscriptionProcessing(true);
- } else if (data.transcriptionStatus === "ERROR") {
- setIsTranscriptionProcessing(false);
- }
- }, [transcriptContent, transcriptError, data.transcriptionStatus]);
-
- return { isTranscriptionProcessing, subtitles };
-};
-
-function CommentIndicators(props: {
- className?: string;
- comments: MaybePromise<CommentWithAuthor[]>;
- longestDuration: number;
-}) {
- const comments =
- props.comments instanceof Promise ? use(props.comments) : props.comments;
-
- return (
- <div className={props.className}>
- {comments.map((comment) => {
- const commentPosition =
- comment.timestamp === null
- ? 0
- : (comment.timestamp / props.longestDuration) * 100;
-
- let tooltipContent = "";
- if (comment.type === "text") {
- tooltipContent =
- comment.authorId === "anonymous"
- ? `Anonymous: ${comment.content}`
- : `${comment.authorName || "User"}: ${comment.content}`;
- } else {
- tooltipContent =
- comment.authorId === "anonymous"
- ? "Anonymous"
- : comment.authorName || "User";
- }
-
- return (
- <div
- key={comment.id}
- className="absolute z-10 -mt-5 text-sm transition-all hover:scale-125 md:-mt-5"
- style={{
- left: `${commentPosition}%`,
- }}
- data-tooltip-id={comment.id}
- data-tooltip-content={tooltipContent}
- >
- <span>
- {comment.type === "text" ? (
- <MessageSquare
- fill="#646464"
- className="w-auto h-[18px] sm:h-[22px] text-white"
- />
- ) : (
- comment.content
- )}
- </span>
- <Tooltip id={comment.id} />
- </div>
- );
- })}
- </div>
- );
-}
diff --git a/apps/web/app/s/[videoId]/_components/VideoJs.tsx b/apps/web/app/s/[videoId]/_components/VideoJs.tsx
new file mode 100644
index 000000000..3ed30f9f5
--- /dev/null
+++ b/apps/web/app/s/[videoId]/_components/VideoJs.tsx
@@ -0,0 +1,96 @@
+"use client";
+
+import { forwardRef, useRef, useEffect, MutableRefObject } from "react";
+import videojs from "video.js";
+import "video.js/dist/video-js.css";
+import Player from "video.js/dist/types/player";
+
+interface Props {
+ onReady?: (player: Player) => void;
+ options: {
+ autoplay: boolean;
+ controls: boolean;
+ responsive: boolean;
+ fluid: boolean;
+ sources: {
+ src: string;
+ type: string;
+ }[];
+ }
+}
+
+export const VideoJS = forwardRef<Player | null, Props>(({ options, onReady }: Props, ref) => {
+ const videoRef = useRef<HTMLDivElement>(null);
+ const playerRef = ref as MutableRefObject<Player | null>;
+
+ useEffect(() => {
+ if (!videoRef.current) return;
+ if (!playerRef.current) {
+ const videoElement = document.createElement("video-js");
+
+ videoElement.classList.add("vjs-big-play-centered", "vjs-cap");
+ videoRef.current.appendChild(videoElement);
+
+ const player = (playerRef.current = videojs(videoElement, options, () => {
+ onReady && onReady(player);
+ }));
+
+ } else {
+ const player = playerRef.current;
+
+ player.autoplay(options.autoplay);
+ player.src(options.sources);
+ }
+ }, [options, videoRef]);
+
+ useEffect(() => {
+ const player = playerRef.current;
+
+ return () => {
+ if (player && !player.isDisposed()) {
+ player.dispose();
+ playerRef.current = null;
+ }
+ };
+ }, [playerRef]);
+
+ useEffect(() => {
+ const player = playerRef.current;
+
+ if (!player) return;
+
+ const handleKeyDown = (event: KeyboardEvent) => {
+ const tag = (event.target as HTMLElement)?.tagName;
+ const isEditable =
+ tag === "INPUT" ||
+ tag === "TEXTAREA" ||
+ tag === "SELECT" ||
+ tag === "BUTTON" ||
+ (event.target as HTMLElement)?.isContentEditable;
+
+ if (isEditable) return;
+ if (event.key === " ") {
+ event.preventDefault();
+ player.paused() ? player.play() : player.pause();
+ }
+ };
+
+ document.addEventListener("keydown", handleKeyDown);
+
+ return () => {
+ document.removeEventListener("keydown", handleKeyDown);
+ };
+ }, [playerRef]);
+
+ return (
+ <div style={{
+ height: "100%"
+ }} data-vjs-player>
+ <div style={{
+ height: "100%"
+ }} ref={videoRef} />
+ </div>
+ );
+});
+
+export default VideoJS;
diff --git a/apps/web/app/s/[videoId]/_components/tabs/Transcript.tsx b/apps/web/app/s/[videoId]/_components/tabs/Transcript.tsx
index 66f697715..31bfddaa2 100644
--- a/apps/web/app/s/[videoId]/_components/tabs/Transcript.tsx
+++ b/apps/web/app/s/[videoId]/_components/tabs/Transcript.tsx
@@ -20,6 +20,7 @@ interface TranscriptEntry {
startTime: number;
}
+
const parseVTT = (vttContent: string): TranscriptEntry[] => {
const lines = vttContent.split("\n");
const entries: TranscriptEntry[] = [];
@@ -118,8 +119,8 @@ const parseVTT = (vttContent: string): TranscriptEntry[] => {
export const Transcript: React.FC<TranscriptProps> = ({
data,
- onSeek,
user,
+ onSeek,
}) => {
const [transcriptData, setTranscriptData] = useState<TranscriptEntry[]>([]);
const [isLoading, setIsLoading] = useState(true);
@@ -134,6 +135,7 @@ export const Transcript: React.FC<TranscriptProps> = ({
const [copyPressed, setCopyPressed] = useState(false);
const [downloadPressed, setDownloadPressed] = useState(false);
+
const {
data: transcriptContent,
isLoading: isTranscriptLoading,
@@ -224,9 +226,7 @@ export const Transcript: React.FC<TranscriptProps> = ({
setSelectedEntry(entry.id);
- if (onSeek) {
- onSeek(entry.startTime);
- }
+ onSeek?.(entry.startTime);
};
const startEditing = (entry: TranscriptEntry) => {
@@ -306,8 +306,8 @@ export const Transcript: React.FC<TranscriptProps> = ({
return `${hours.toString().padStart(2, "0")}:${minutes
.toString()
.padStart(2, "0")}:${secs.toString().padStart(2, "0")}.${milliseconds
- .toString()
- .padStart(3, "0")}`;
+ .toString()
+ .padStart(3, "0")}`;
};
return `${entry.id}\n${formatTime(startSeconds)} --> ${formatTime(
@@ -448,7 +448,7 @@ export const Transcript: React.FC<TranscriptProps> = ({
spinner={isCopying}
>
{!copyPressed ? (
- <Copy className="w-3 h-3 mr-1" />
+ <Copy className="mr-1 w-3 h-3" />
) : (
<svg
xmlns="http://www.w3.org/2000/svg"
@@ -460,7 +460,7 @@ export const Transcript: React.FC<TranscriptProps> = ({
strokeWidth="2"
strokeLinecap="round"
strokeLinejoin="round"
- className="w-3 h-3 mr-1 svgpathanimation"
+ className="mr-1 w-3 h-3 svgpathanimation"
>
<path d="M20 6 9 17l-5-5" />
</svg>
@@ -474,7 +474,7 @@ export const Transcript: React.FC<TranscriptProps> = ({
size="xs"
>
{!downloadPressed ? (
- <Download className="w-3 h-3 mr-1" />
+ <Download className="mr-1 w-3 h-3" />
) : (
<svg
xmlns="http://www.w3.org/2000/svg"
@@ -486,7 +486,7 @@ export const Transcript: React.FC<TranscriptProps> = ({
strokeWidth="2"
strokeLinecap="round"
strokeLinejoin="round"
- className="w-3 h-3 mr-1 svgpathanimation"
+ className="mr-1 w-3 h-3 svgpathanimation"
>
<path d="M20 6 9 17l-5-5" />
</svg>
@@ -501,17 +501,16 @@ export const Transcript: React.FC<TranscriptProps> = ({
{transcriptData.map((entry) => (
<div
key={entry.id}
- className={`group rounded-lg transition-colors ${
- editingEntry === entry.id
- ? "bg-gray-1 border border-gray-4 p-3"
- : selectedEntry === entry.id
+ className={`group rounded-lg transition-colors ${editingEntry === entry.id
+ ? "bg-gray-1 border border-gray-4 p-3"
+ : selectedEntry === entry.id
? "bg-gray-2 p-3"
: "hover:bg-gray-2 p-3"
- } ${editingEntry === entry.id ? "" : "cursor-pointer"}`}
+ } ${editingEntry === entry.id ? "" : "cursor-pointer"}`}
onClick={() => handleTranscriptClick(entry)}
>
<div className="flex justify-between items-start mb-2">
- <div className="text-xs text-gray-8 font-medium">
+ <div className="text-xs font-medium text-gray-8">
{entry.timestamp}
</div>
{canEdit && editingEntry !== entry.id && (
@@ -530,11 +529,11 @@ export const Transcript: React.FC<TranscriptProps> = ({
{editingEntry === entry.id ? (
<div className="space-y-3">
- <div className="rounded-lg bg-gray-1 border border-gray-4 p-3">
+ <div className="p-3 rounded-lg border bg-gray-1 border-gray-4">
<textarea
value={editText}
onChange={(e) => setEditText(e.target.value)}
- className="w-full text-sm leading-relaxed text-gray-12 bg-transparent placeholder:text-gray-8 resize-none focus:outline-none"
+ className="w-full text-sm leading-relaxed bg-transparent resize-none text-gray-12 placeholder:text-gray-8 focus:outline-none"
rows={Math.max(2, Math.ceil(editText.length / 60))}
autoFocus
onClick={(e) => e.stopPropagation()}
@@ -552,7 +551,7 @@ export const Transcript: React.FC<TranscriptProps> = ({
size="xs"
className="min-w-[70px]"
>
- <X className="w-3 h-3 mr-1" />
+ <X className="mr-1 w-3 h-3" />
Cancel
</Button>
<Button
@@ -566,7 +565,7 @@ export const Transcript: React.FC<TranscriptProps> = ({
className="min-w-[70px]"
spinner={isSaving}
>
- <Check className="w-3 h-3 mr-1" />
+ <Check className="mr-1 w-3 h-3" />
Save
</Button>
</div>
diff --git a/apps/web/app/s/[videoId]/_components/utils/transcript-utils.ts b/apps/web/app/s/[videoId]/_components/utils/transcript-utils.ts
new file mode 100644
index 000000000..20f40e1d5
--- /dev/null
+++ b/apps/web/app/s/[videoId]/_components/utils/transcript-utils.ts
@@ -0,0 +1,176 @@
+// Utility functions for transcript formatting
+
+export interface TranscriptEntry {
+ id: number;
+ timestamp: string | number; // Allow both string and number types
+ text: string;
+ startTime: number;
+}
+
+export const formatTime = (seconds: number): string => {
+ const hours = Math.floor(seconds / 3600);
+ const minutes = Math.floor((seconds % 3600) / 60);
+ const secs = Math.floor(seconds % 60);
+ const milliseconds = Math.floor((seconds % 1) * 1000);
+
+ return `${hours.toString().padStart(2, "0")}:${minutes
+ .toString()
+ .padStart(2, "0")}:${secs.toString().padStart(2, "0")}.${milliseconds
+ .toString()
+ .padStart(3, "0")}`;
+};
+
+/**
+ * Formats transcript entries as VTT format for subtitles
+ */
+export const formatTranscriptAsVTT = (entries: TranscriptEntry[]): string => {
+ const vttHeader = "WEBVTT\n\n";
+
+ const vttEntries = entries.map((entry, index) => {
+ const startSeconds = entry.startTime;
+ const nextEntry = entries[index + 1];
+ const endSeconds = nextEntry ? nextEntry.startTime : startSeconds + 3;
+
+ return `${entry.id}\n${formatTime(startSeconds)} --> ${formatTime(
+ endSeconds
+ )}\n${entry.text}\n`;
+ });
+
+ return vttHeader + vttEntries.join("\n");
+};
+
+export function formatChaptersAsVTT(
+ chapters: { title: string; start: number }[]
+): string {
+ if (!chapters || chapters.length === 0) {
+ return "WEBVTT\n\n";
+ }
+
+ // Sort chapters by start time
+ const sortedChapters = [...chapters].sort((a, b) => a.start - b.start);
+
+ // Generate VTT content
+ let vttContent = "WEBVTT\n\n";
+ sortedChapters.forEach((chapter, index) => {
+ const startTime = formatTime(chapter.start);
+ // Check for next chapter explicitly
+ const nextChapter =
+ index < sortedChapters.length - 1 ? sortedChapters[index + 1] : null;
+ const endTime = nextChapter
+ ? formatTime(nextChapter.start)
+ : formatTime(chapter.start + 60);
+
+ vttContent += `${index + 1}\n${startTime} --> ${endTime}\n${
+ chapter.title
+ }\n\n`;
+ });
+
+ return vttContent;
+}
+
+export const parseVTT = (vttContent: string): TranscriptEntry[] => {
+ const lines = vttContent.split("\n");
+ const entries: TranscriptEntry[] = [];
+ let currentEntry: Partial<TranscriptEntry & { startTime: number }> = {};
+ let currentId = 0;
+
+ const timeToSeconds = (timeStr: string): number | null => {
+ const parts = timeStr.split(":");
+ if (parts.length !== 3) return null;
+
+ const [hoursStr, minutesStr, secondsStr] = parts;
+ if (!hoursStr || !minutesStr || !secondsStr) return null;
+
+ const hours = parseInt(hoursStr, 10);
+ const minutes = parseInt(minutesStr, 10);
+ const seconds = parseInt(secondsStr, 10);
+
+ if (isNaN(hours) || isNaN(minutes) || isNaN(seconds)) return null;
+
+ return hours * 3600 + minutes * 60 + seconds;
+ };
+
+ const parseTimestamp = (
+ timestamp: string
+ ): { mm_ss: string; totalSeconds: number } | null => {
+ const parts = timestamp.split(":");
+ if (parts.length !== 3) return null;
+
+ const [hoursStr, minutesStr, secondsWithMs] = parts;
+ if (!hoursStr || !minutesStr || !secondsWithMs) return null;
+
+ const secondsPart = secondsWithMs.split(".")[0];
+ if (!secondsPart) return null;
+
+ const totalSeconds = timeToSeconds(
+ `${hoursStr}:${minutesStr}:${secondsPart}`
+ );
+ if (totalSeconds === null) return null;
+
+ return {
+ mm_ss: `${minutesStr}:${secondsPart}`,
+ totalSeconds,
+ };
+ };
+
+ for (let i = 0; i < lines.length; i++) {
+ const line = lines[i];
+ if (!line?.trim()) continue;
+
+ const trimmedLine = line.trim();
+
+ if (trimmedLine === "WEBVTT") continue;
+
+ if (/^\d+$/.test(trimmedLine)) {
+ currentId = parseInt(trimmedLine, 10);
+ continue;
+ }
+
+ if (trimmedLine.includes("-->")) {
+ const [startTimeStr, endTimeStr] = trimmedLine.split(" --> ");
+ if (!startTimeStr || !endTimeStr) continue;
+
+ const startTimestamp = parseTimestamp(startTimeStr);
+ if (startTimestamp) {
+ currentEntry = {
+ id: currentId,
+ timestamp: startTimestamp.mm_ss,
+ startTime: startTimestamp.totalSeconds,
+ };
+ }
+ continue;
+ }
+
+ if (currentEntry.timestamp && !currentEntry.text) {
+ const textContent =
+ trimmedLine.startsWith('"') && trimmedLine.endsWith('"')
+ ? trimmedLine.slice(1, -1)
+ : trimmedLine;
+
+ currentEntry.text = textContent;
+ if (
+ currentEntry.id !== undefined &&
+ currentEntry.timestamp &&
+ currentEntry.text &&
+ currentEntry.startTime !== undefined
+ ) {
+ entries.push(currentEntry as TranscriptEntry);
+ }
+ currentEntry = {};
+ }
+ }
+
+ const sortedEntries = entries.sort((a, b) => a.startTime - b.startTime);
+ return sortedEntries;
+};
+
+/**
+ * Formats transcript entries for clipboard copying
+ */
+export const formatTranscriptForClipboard = (
+ entries: TranscriptEntry[]
+): string => {
+ return entries
+ .map((entry) => `[${entry.timestamp}] ${entry.text}`)
+ .join("\n\n");
+};
diff --git a/apps/web/app/s/[videoId]/_components/video/badge.tsx b/apps/web/app/s/[videoId]/_components/video/badge.tsx
new file mode 100644
index 000000000..e438fae48
--- /dev/null
+++ b/apps/web/app/s/[videoId]/_components/video/badge.tsx
@@ -0,0 +1,36 @@
+import * as React from "react"
+import { cva, type VariantProps } from "class-variance-authority"
+
+import { cn } from "@/app/lib/utils"
+
+const badgeVariants = cva(
+ "inline-flex items-center rounded-md border px-2.5 py-0.5 text-xs font-semibold transition-colors focus:outline-none focus:ring-2 focus:ring-ring focus:ring-offset-2",
+ {
+ variants: {
+ variant: {
+ default:
+ "border-transparent bg-primary text-primary-foreground shadow hover:bg-primary/80",
+ secondary:
+ "border-transparent bg-secondary text-secondary-foreground hover:bg-secondary/80",
+ destructive:
+ "border-transparent bg-destructive text-destructive-foreground shadow hover:bg-destructive/80",
+ outline: "text-foreground",
+ },
+ },
+ defaultVariants: {
+ variant: "default",
+ },
+ }
+)
+
+export interface BadgeProps
+ extends React.HTMLAttributes<HTMLDivElement>,
+ VariantProps<typeof badgeVariants> {}
+
+function Badge({ className, variant, ...props }: BadgeProps) {
+ return (
+ <div className={cn(badgeVariants({ variant }), className)} {...props} />
+ )
+}
+
+export { Badge, badgeVariants }
diff --git a/apps/web/app/s/[videoId]/_components/video/button.tsx b/apps/web/app/s/[videoId]/_components/video/button.tsx
new file mode 100644
index 000000000..e4ffc5fea
--- /dev/null
+++ b/apps/web/app/s/[videoId]/_components/video/button.tsx
@@ -0,0 +1,57 @@
+import * as React from "react"
+import { Slot } from "@radix-ui/react-slot"
+import { cva, type VariantProps } from "class-variance-authority"
+
+import { cn } from "@/app/lib/utils"
+
+const buttonVariants = cva(
+ "inline-flex items-center justify-center gap-2 whitespace-nowrap rounded-md text-sm font-medium transition-colors focus-visible:outline-none focus-visible:ring-1 focus-visible:ring-ring disabled:pointer-events-none disabled:opacity-50 [&_svg]:pointer-events-none [&_svg]:size-4 [&_svg]:shrink-0",
+ {
+ variants: {
+ variant: {
+ default:
+ "bg-primary text-primary-foreground shadow hover:bg-primary/90",
+ destructive:
+ "bg-destructive text-destructive-foreground shadow-sm hover:bg-destructive/90",
+ outline:
+ "border border-input bg-background shadow-sm hover:bg-white/50 hover:text-white",
+ secondary:
+ "bg-secondary text-secondary-foreground shadow-sm hover:bg-secondary/80",
+ ghost: "hover:bg-white/20 hover:text-white",
+ link: "text-primary underline-offset-4 hover:underline",
+ },
+ size: {
+ default: "h-9 px-4 py-2",
+ sm: "h-8 rounded-md px-3 text-xs",
+ lg: "h-10 rounded-md px-8",
+ icon: "h-9 w-9",
+ },
+ },
+ defaultVariants: {
+ variant: "default",
+ size: "default",
+ },
+ }
+)
+
+export interface ButtonProps
+ extends React.ButtonHTMLAttributes<HTMLButtonElement>,
+ VariantProps<typeof buttonVariants> {
+ asChild?: boolean
+}
+
+const Button = React.forwardRef<HTMLButtonElement, ButtonProps>(
+ ({ className, variant, size, asChild = false, ...props }, ref) => {
+ const Comp = asChild ? Slot : "button"
+ return (
+ <Comp
+ className={cn(buttonVariants({ variant, size, className }))}
+ ref={ref}
+ {...props}
+ />
+ )
+ }
+)
+Button.displayName = "Button"
+
+export { Button, buttonVariants }
diff --git a/apps/web/app/s/[videoId]/_components/video/media-player.tsx b/apps/web/app/s/[videoId]/_components/video/media-player.tsx
new file mode 100644
index 000000000..3dc9a4a63
--- /dev/null
+++ b/apps/web/app/s/[videoId]/_components/video/media-player.tsx
@@ -0,0 +1,3146 @@
+"use client";
+
+import { Badge } from "./badge";
+import { Button } from "@cap/ui";
+import { Button as PlayerButton } from "./button";
+import {
+ DropdownMenu,
+ DropdownMenuContent,
+ DropdownMenuItem,
+ DropdownMenuLabel,
+ DropdownMenuSub,
+ DropdownMenuSubContent,
+ DropdownMenuSubTrigger,
+ DropdownMenuTrigger,
+} from "@cap/ui";
+import {
+ Tooltip,
+ TooltipContent,
+ TooltipTrigger,
+} from "./tooltip";
+import { useComposedRefs } from "@/app/lib/compose-refs";
+import { cn } from "@/app/lib/utils";
+import * as SliderPrimitive from "@radix-ui/react-slider";
+import { Slot } from "@radix-ui/react-slot";
+import {
+ AlertTriangleIcon,
+ CheckIcon,
+ DownloadIcon,
+ FastForwardIcon,
+ Loader2Icon, Maximize2Icon,
+ Minimize2Icon,
+ PauseIcon,
+ PictureInPicture2Icon,
+ PictureInPictureIcon,
+ PlayIcon,
+ RefreshCcwIcon,
+ RepeatIcon,
+ RewindIcon,
+ RotateCcwIcon,
+ SettingsIcon,
+ SubtitlesIcon,
+ Volume1Icon,
+ Volume2Icon,
+ VolumeXIcon,
+ CaptionsOffIcon
+} from "lucide-react";
+import {
+ MediaActionTypes,
+ MediaProvider,
+ timeUtils,
+ useMediaDispatch,
+ useMediaFullscreenRef,
+ useMediaRef,
+ useMediaSelector,
+} from "media-chrome/react/media-store";
+import * as React from "react";
+import * as ReactDOM from "react-dom";
+import { forwardRef } from "react";
+
+const ROOT_NAME = "MediaPlayer";
+const SEEK_NAME = "MediaPlayerSeek";
+const SETTINGS_NAME = "MediaPlayerSettings";
+const VOLUME_NAME = "MediaPlayerVolume";
+const PLAYBACK_SPEED_NAME = "MediaPlayerPlaybackSpeed";
+
+const FLOATING_MENU_SIDE_OFFSET = 10;
+const SPEEDS = [0.5, 0.75, 1, 1.25, 1.5, 1.75, 2];
+
+const SEEK_STEP_SHORT = 5;
+const SEEK_STEP_LONG = 10;
+const SEEK_COLLISION_PADDING = 10;
+const SEEK_TOOLTIP_WIDTH_FALLBACK = 240;
+
+const SEEK_HOVER_PERCENT = "--seek-hover-percent";
+const SEEK_TOOLTIP_X = "--seek-tooltip-x";
+const SEEK_TOOLTIP_Y = "--seek-tooltip-y";
+
+const SPRITE_CONTAINER_WIDTH = 224;
+const SPRITE_CONTAINER_HEIGHT = 128;
+
+type Direction = "ltr" | "rtl";
+
+const DirectionContext = React.createContext<Direction | undefined>(undefined);
+
+function useDirection(dirProp?: Direction): Direction {
+ const contextDir = React.useContext(DirectionContext);
+ return dirProp ?? contextDir ?? "ltr";
+}
+
+function useLazyRef<T>(fn: () => T) {
+ const ref = React.useRef<T | null>(null);
+
+ if (ref.current === null) {
+ ref.current = fn();
+ }
+
+ return ref as React.RefObject<T>;
+}
+
+interface StoreState {
+ controlsVisible: boolean;
+ dragging: boolean;
+ menuOpen: boolean;
+ volumeIndicatorVisible: boolean;
+}
+
+interface Store {
+ subscribe: (cb: () => void) => () => void;
+ getState: () => StoreState;
+ setState: (
+ key: keyof StoreState,
+ value: StoreState[keyof StoreState],
+ ) => void;
+ notify: () => void;
+}
+
+function createStore(
+ listenersRef: React.RefObject<Set<() => void>>,
+ stateRef: React.RefObject<StoreState>,
+ onValueChange?: Partial<{
+ [K in keyof StoreState]: (value: StoreState[K], store: Store) => void;
+ }>,
+): Store {
+ const store: Store = {
+ subscribe: (cb) => {
+ listenersRef.current.add(cb);
+ return () => listenersRef.current.delete(cb);
+ },
+ getState: () => stateRef.current,
+ setState: (key, value) => {
+ if (Object.is(stateRef.current[key], value)) return;
+ stateRef.current[key] = value;
+ onValueChange?.[key]?.(value, store);
+ store.notify();
+ },
+ notify: () => {
+ for (const cb of listenersRef.current) {
+ cb();
+ }
+ },
+ };
+
+ return store;
+}
+
+const StoreContext = React.createContext<Store | null>(null);
+
+function useStoreContext(consumerName: string) {
+ const context = React.useContext(StoreContext);
+ if (!context) {
+ throw new Error(`\`${consumerName}\` must be used within \`${ROOT_NAME}\``);
+ }
+ return context;
+}
+
+function useStoreSelector<U>(selector: (state: StoreState) => U): U {
+ const storeContext = useStoreContext("useStoreSelector");
+
+ const getSnapshot = React.useCallback(
+ () => selector(storeContext.getState()),
+ [storeContext, selector],
+ );
+
+ return React.useSyncExternalStore(
+ storeContext.subscribe,
+ getSnapshot,
+ getSnapshot,
+ );
+}
+
+interface MediaPlayerContextValue {
+ mediaId: string;
+ labelId: string;
+ descriptionId: string;
+ dir: Direction;
+ rootRef: React.RefObject<HTMLDivElement | null>;
+ mediaRef: React.RefObject<HTMLVideoElement | HTMLAudioElement | null>;
+ portalContainer: Element | DocumentFragment | null;
+ tooltipDelayDuration: number;
+ tooltipSideOffset: number;
+ disabled: boolean;
+ isVideo: boolean;
+ withoutTooltip: boolean;
+}
+
+const MediaPlayerContext = React.createContext<MediaPlayerContextValue | null>(
+ null,
+);
+
+function useMediaPlayerContext(consumerName: string) {
+ const context = React.useContext(MediaPlayerContext);
+ if (!context) {
+ throw new Error(`\`${consumerName}\` must be used within \`${ROOT_NAME}\``);
+ }
+ return context;
+}
+
+interface MediaPlayerRootProps
+ extends Omit<React.ComponentProps<"div">, "onTimeUpdate" | "onVolumeChange"> {
+ onPlay?: () => void;
+ onPause?: () => void;
+ onEnded?: () => void;
+ onTimeUpdate?: (time: number) => void;
+ onVolumeChange?: (volume: number) => void;
+ onMuted?: (muted: boolean) => void;
+ onMediaError?: (error: MediaError | null) => void;
+ onPipError?: (error: unknown, state: "enter" | "exit") => void;
+ onFullscreenChange?: (fullscreen: boolean) => void;
+ dir?: Direction;
+ label?: string;
+ tooltipDelayDuration?: number;
+ tooltipSideOffset?: number;
+ asChild?: boolean;
+ autoHide?: boolean;
+ disabled?: boolean;
+ withoutTooltip?: boolean;
+}
+
+function MediaPlayerRoot(props: MediaPlayerRootProps) {
+ const listenersRef = useLazyRef(() => new Set<() => void>());
+ const stateRef = useLazyRef<StoreState>(() => ({
+ controlsVisible: true,
+ dragging: false,
+ menuOpen: false,
+ volumeIndicatorVisible: false,
+ }));
+
+ const store = React.useMemo(
+ () => createStore(listenersRef, stateRef),
+ [listenersRef, stateRef],
+ );
+
+ return (
+ <MediaProvider>
+ <StoreContext.Provider value={store}>
+ <MediaPlayerRootImpl {...props} />
+ </StoreContext.Provider>
+ </MediaProvider>
+ );
+}
+
+function MediaPlayerRootImpl(props: MediaPlayerRootProps) {
+ const {
+ onPlay,
+ onPause,
+ onEnded,
+ onTimeUpdate,
+ onFullscreenChange,
+ onVolumeChange,
+ onMuted,
+ onMediaError,
+ onPipError,
+ dir: dirProp,
+ label,
+ tooltipDelayDuration = 600,
+ tooltipSideOffset = FLOATING_MENU_SIDE_OFFSET,
+ asChild,
+ autoHide = false,
+ disabled = false,
+ withoutTooltip = false,
+ children,
+ className,
+ ref,
+ ...rootImplProps
+ } = props;
+
+ const mediaId = React.useId();
+ const labelId = React.useId();
+ const descriptionId = React.useId();
+
+ const rootRef = React.useRef<HTMLDivElement | null>(null);
+ const fullscreenRef = useMediaFullscreenRef();
+ const composedRef = useComposedRefs(ref, rootRef, fullscreenRef);
+
+ const dir = useDirection(dirProp);
+ const dispatch = useMediaDispatch();
+ const mediaRef = React.useRef<HTMLVideoElement | HTMLAudioElement | null>(
+ null,
+ );
+
+ const store = useStoreContext(ROOT_NAME);
+
+ const controlsVisible = useStoreSelector((state) => state.controlsVisible);
+ const dragging = useStoreSelector((state) => state.dragging);
+ const menuOpen = useStoreSelector((state) => state.menuOpen);
+
+ const hideControlsTimeoutRef = React.useRef<NodeJS.Timeout | null>(null);
+ const lastMouseMoveRef = React.useRef<number>(Date.now());
+ const volumeIndicatorTimeoutRef = React.useRef<NodeJS.Timeout | null>(null);
+
+ const mediaPaused = useMediaSelector((state) => state.mediaPaused ?? true);
+ const isFullscreen = useMediaSelector(
+ (state) => state.mediaIsFullscreen ?? false,
+ );
+
+ const [mounted, setMounted] = React.useState(false);
+ React.useLayoutEffect(() => setMounted(true), []);
+
+ const portalContainer = mounted
+ ? isFullscreen
+ ? rootRef.current
+ : globalThis.document.body
+ : null;
+
+ const isVideo =
+ (typeof HTMLVideoElement !== "undefined" &&
+ mediaRef.current instanceof HTMLVideoElement) ||
+ mediaRef.current?.tagName?.toLowerCase() === "mux-player";
+
+ const onControlsShow = React.useCallback(() => {
+ store.setState("controlsVisible", true);
+ lastMouseMoveRef.current = Date.now();
+
+ if (hideControlsTimeoutRef.current) {
+ clearTimeout(hideControlsTimeoutRef.current);
+ }
+
+ if (autoHide && !mediaPaused && !menuOpen && !dragging) {
+ hideControlsTimeoutRef.current = setTimeout(() => {
+ store.setState("controlsVisible", false);
+ }, 3000);
+ }
+ }, [store.setState, autoHide, mediaPaused, menuOpen, dragging]);
+
+ const onVolumeIndicatorTrigger = React.useCallback(() => {
+ if (menuOpen) return;
+
+ store.setState("volumeIndicatorVisible", true);
+
+ if (volumeIndicatorTimeoutRef.current) {
+ clearTimeout(volumeIndicatorTimeoutRef.current);
+ }
+
+ volumeIndicatorTimeoutRef.current = setTimeout(() => {
+ store.setState("volumeIndicatorVisible", false);
+ }, 2000);
+
+ if (autoHide) {
+ onControlsShow();
+ }
+ }, [store.setState, menuOpen, autoHide, onControlsShow]);
+
+ const onMouseLeave = React.useCallback(
+ (event: React.MouseEvent<HTMLDivElement>) => {
+ rootImplProps.onMouseLeave?.(event);
+
+ if (event.defaultPrevented) return;
+
+ if (autoHide && !mediaPaused && !menuOpen && !dragging) {
+ store.setState("controlsVisible", false);
+ }
+ },
+ [
+ store.setState,
+ rootImplProps.onMouseLeave,
+ autoHide,
+ mediaPaused,
+ menuOpen,
+ dragging,
+ ],
+ );
+
+ const onMouseMove = React.useCallback(
+ (event: React.MouseEvent<HTMLDivElement>) => {
+ rootImplProps.onMouseMove?.(event);
+
+ if (event.defaultPrevented) return;
+
+ if (autoHide) {
+ onControlsShow();
+ }
+ },
+ [autoHide, rootImplProps.onMouseMove, onControlsShow],
+ );
+
+ React.useEffect(() => {
+ if (mediaPaused || menuOpen || dragging) {
+ store.setState("controlsVisible", true);
+ if (hideControlsTimeoutRef.current) {
+ clearTimeout(hideControlsTimeoutRef.current);
+ }
+ return;
+ }
+
+ if (autoHide) {
+ onControlsShow();
+ }
+ }, [
+ store.setState,
+ onControlsShow,
+ autoHide,
+ menuOpen,
+ mediaPaused,
+ dragging,
+ ]);
+
+ const onKeyDown = React.useCallback(
+ (event: React.KeyboardEvent<HTMLDivElement>) => {
+ if (disabled) return;
+
+ rootImplProps.onKeyDown?.(event);
+
+ if (event.defaultPrevented) return;
+
+ const mediaElement = mediaRef.current;
+ if (!mediaElement) return;
+
+ const isMediaFocused = document.activeElement === mediaElement;
+ const isPlayerFocused =
+ document.activeElement?.closest('[data-slot="media-player"]') !== null;
+
+ if (!isMediaFocused && !isPlayerFocused) return;
+
+ if (autoHide) onControlsShow();
+
+ switch (event.key.toLowerCase()) {
+ case " ":
+ case "k":
+ event.preventDefault();
+ dispatch({
+ type: mediaElement.paused
+ ? MediaActionTypes.MEDIA_PLAY_REQUEST
+ : MediaActionTypes.MEDIA_PAUSE_REQUEST,
+ });
+ break;
+
+ case "f":
+ event.preventDefault();
+ dispatch({
+ type: document.fullscreenElement
+ ? MediaActionTypes.MEDIA_EXIT_FULLSCREEN_REQUEST
+ : MediaActionTypes.MEDIA_ENTER_FULLSCREEN_REQUEST,
+ });
+ break;
+
+ case "m": {
+ event.preventDefault();
+ if (isVideo) {
+ onVolumeIndicatorTrigger();
+ }
+ dispatch({
+ type: mediaElement.muted
+ ? MediaActionTypes.MEDIA_UNMUTE_REQUEST
+ : MediaActionTypes.MEDIA_MUTE_REQUEST,
+ });
+ break;
+ }
+
+ case "arrowright":
+ event.preventDefault();
+ if (
+ isVideo ||
+ (mediaElement instanceof HTMLAudioElement && event.shiftKey)
+ ) {
+ dispatch({
+ type: MediaActionTypes.MEDIA_SEEK_REQUEST,
+ detail: Math.min(
+ mediaElement.duration,
+ mediaElement.currentTime + SEEK_STEP_SHORT,
+ ),
+ });
+ }
+ break;
+
+ case "arrowleft":
+ event.preventDefault();
+ if (
+ isVideo ||
+ (mediaElement instanceof HTMLAudioElement && event.shiftKey)
+ ) {
+ dispatch({
+ type: MediaActionTypes.MEDIA_SEEK_REQUEST,
+ detail: Math.max(0, mediaElement.currentTime - SEEK_STEP_SHORT),
+ });
+ }
+ break;
+
+ case "arrowup":
+ event.preventDefault();
+ if (isVideo) {
+ onVolumeIndicatorTrigger();
+ dispatch({
+ type: MediaActionTypes.MEDIA_VOLUME_REQUEST,
+ detail: Math.min(1, mediaElement.volume + 0.1),
+ });
+ }
+ break;
+
+ case "arrowdown":
+ event.preventDefault();
+ if (isVideo) {
+ onVolumeIndicatorTrigger();
+ dispatch({
+ type: MediaActionTypes.MEDIA_VOLUME_REQUEST,
+ detail: Math.max(0, mediaElement.volume - 0.1),
+ });
+ }
+ break;
+
+ case "<": {
+ event.preventDefault();
+ const currentRate = mediaElement.playbackRate;
+ const currentIndex = SPEEDS.indexOf(currentRate);
+ const newIndex = Math.max(0, currentIndex - 1);
+ const newRate = SPEEDS[newIndex] ?? 1;
+ dispatch({
+ type: MediaActionTypes.MEDIA_PLAYBACK_RATE_REQUEST,
+ detail: newRate,
+ });
+ break;
+ }
+
+ case ">": {
+ event.preventDefault();
+ const currentRate = mediaElement.playbackRate;
+ const currentIndex = SPEEDS.indexOf(currentRate);
+ const newIndex = Math.min(SPEEDS.length - 1, currentIndex + 1);
+ const newRate = SPEEDS[newIndex] ?? 1;
+ dispatch({
+ type: MediaActionTypes.MEDIA_PLAYBACK_RATE_REQUEST,
+ detail: newRate,
+ });
+ break;
+ }
+
+ case "c":
+ event.preventDefault();
+ if (isVideo && mediaElement.textTracks.length > 0) {
+ dispatch({
+ type: MediaActionTypes.MEDIA_TOGGLE_SUBTITLES_REQUEST,
+ });
+ }
+ break;
+
+ case "d": {
+ const hasDownload = mediaElement.querySelector(
+ '[data-slot="media-player-download"]',
+ );
+
+ if (!hasDownload) break;
+
+ event.preventDefault();
+ if (mediaElement.currentSrc) {
+ const link = document.createElement("a");
+ link.href = mediaElement.currentSrc;
+ link.download = "";
+ document.body.appendChild(link);
+ link.click();
+ document.body.removeChild(link);
+ }
+ break;
+ }
+
+ case "p": {
+ event.preventDefault();
+ if (isVideo && "requestPictureInPicture" in mediaElement) {
+ const isPip = document.pictureInPictureElement === mediaElement;
+ dispatch({
+ type: isPip
+ ? MediaActionTypes.MEDIA_EXIT_PIP_REQUEST
+ : MediaActionTypes.MEDIA_ENTER_PIP_REQUEST,
+ });
+ if (isPip) {
+ document.exitPictureInPicture().catch((error) => {
+ onPipError?.(error, "exit");
+ });
+ } else {
+ mediaElement.requestPictureInPicture().catch((error) => {
+ onPipError?.(error, "enter");
+ });
+ }
+ }
+ break;
+ }
+
+ case "r": {
+ event.preventDefault();
+ mediaElement.loop = !mediaElement.loop;
+ break;
+ }
+
+ case "j": {
+ event.preventDefault();
+ dispatch({
+ type: MediaActionTypes.MEDIA_SEEK_REQUEST,
+ detail: Math.max(0, mediaElement.currentTime - SEEK_STEP_LONG),
+ });
+ break;
+ }
+
+ case "l": {
+ event.preventDefault();
+ dispatch({
+ type: MediaActionTypes.MEDIA_SEEK_REQUEST,
+ detail: Math.min(
+ mediaElement.duration,
+ mediaElement.currentTime + SEEK_STEP_LONG,
+ ),
+ });
+ break;
+ }
+
+ case "0":
+ case "1":
+ case "2":
+ case "3":
+ case "4":
+ case "5":
+ case "6":
+ case "7":
+ case "8":
+ case "9": {
+ event.preventDefault();
+ const percent = Number.parseInt(event.key) / 10;
+ const seekTime = mediaElement.duration * percent;
+ dispatch({
+ type: MediaActionTypes.MEDIA_SEEK_REQUEST,
+ detail: seekTime,
+ });
+ break;
+ }
+
+ case "home": {
+ event.preventDefault();
+ dispatch({
+ type: MediaActionTypes.MEDIA_SEEK_REQUEST,
+ detail: 0,
+ });
+ break;
+ }
+
+ case "end": {
+ event.preventDefault();
+ dispatch({
+ type: MediaActionTypes.MEDIA_SEEK_REQUEST,
+ detail: mediaElement.duration,
+ });
+ break;
+ }
+ }
+ },
+ [
+ dispatch,
+ rootImplProps.onKeyDown,
+ onVolumeIndicatorTrigger,
+ onPipError,
+ disabled,
+ isVideo,
+ onControlsShow,
+ autoHide,
+ ],
+ );
+
+ const onKeyUp = React.useCallback(
+ (event: React.KeyboardEvent<HTMLDivElement>) => {
+ rootImplProps.onKeyUp?.(event);
+
+ const key = event.key.toLowerCase();
+ if (key === "arrowup" || key === "arrowdown" || key === "m") {
+ onVolumeIndicatorTrigger();
+ }
+ },
+ [rootImplProps.onKeyUp, onVolumeIndicatorTrigger],
+ );
+
+ React.useEffect(() => {
+ const mediaElement = mediaRef.current;
+ if (!mediaElement) return;
+
+ if (onPlay) mediaElement.addEventListener("play", onPlay);
+ if (onPause) mediaElement.addEventListener("pause", onPause);
+ if (onEnded) mediaElement.addEventListener("ended", onEnded);
+ if (onTimeUpdate)
+ mediaElement.addEventListener("timeupdate", () =>
+ onTimeUpdate?.(mediaElement.currentTime),
+ );
+ if (onVolumeChange)
+ mediaElement.addEventListener("volumechange", () => {
+ onVolumeChange?.(mediaElement.volume);
+ onMuted?.(mediaElement.muted);
+ });
+ if (onMediaError)
+ mediaElement.addEventListener("error", () =>
+ onMediaError?.(mediaElement.error),
+ );
+ if (onFullscreenChange) {
+ document.addEventListener("fullscreenchange", () =>
+ onFullscreenChange?.(!!document.fullscreenElement),
+ );
+ }
+
+ return () => {
+ if (onPlay) mediaElement.removeEventListener("play", onPlay);
+ if (onPause) mediaElement.removeEventListener("pause", onPause);
+ if (onEnded) mediaElement.removeEventListener("ended", onEnded);
+ if (onTimeUpdate)
+ mediaElement.removeEventListener("timeupdate", () =>
+ onTimeUpdate?.(mediaElement.currentTime),
+ );
+ if (onVolumeChange)
+ mediaElement.removeEventListener("volumechange", () => {
+ onVolumeChange?.(mediaElement.volume);
+ onMuted?.(mediaElement.muted);
+ });
+ if (onMediaError)
+ mediaElement.removeEventListener("error", () =>
+ onMediaError?.(mediaElement.error),
+ );
+ if (onFullscreenChange) {
+ document.removeEventListener("fullscreenchange", () =>
+ onFullscreenChange?.(!!document.fullscreenElement),
+ );
+ }
+ if (volumeIndicatorTimeoutRef.current) {
+ clearTimeout(volumeIndicatorTimeoutRef.current);
+ }
+ if (hideControlsTimeoutRef.current) {
+ clearTimeout(hideControlsTimeoutRef.current);
+ }
+ };
+ }, [
+ onPlay,
+ onPause,
+ onEnded,
+ onTimeUpdate,
+ onVolumeChange,
+ onMuted,
+ onMediaError,
+ onFullscreenChange,
+ ]);
+
+ const contextValue = React.useMemo<MediaPlayerContextValue>(
+ () => ({
+ mediaId,
+ labelId,
+ descriptionId,
+ dir,
+ rootRef,
+ mediaRef,
+ portalContainer,
+ tooltipDelayDuration,
+ tooltipSideOffset,
+ disabled,
+ isVideo,
+ withoutTooltip,
+ }),
+ [
+ mediaId,
+ labelId,
+ descriptionId,
+ dir,
+ portalContainer,
+ tooltipDelayDuration,
+ tooltipSideOffset,
+ disabled,
+ isVideo,
+ withoutTooltip,
+ ],
+ );
+
+ const RootPrimitive = asChild ? Slot : "div";
+
+ return (
+ <MediaPlayerContext.Provider value={contextValue}>
+ <RootPrimitive
+ aria-labelledby={labelId}
+ aria-describedby={descriptionId}
+ aria-disabled={disabled}
+ data-disabled={disabled ? "" : undefined}
+ data-controls-visible={controlsVisible ? "" : undefined}
+ data-slot="media-player"
+ data-state={isFullscreen ? "fullscreen" : "windowed"}
+ dir={dir}
+ tabIndex={disabled ? undefined : 0}
+ {...rootImplProps}
+ ref={composedRef}
+ onMouseLeave={onMouseLeave}
+ onMouseMove={onMouseMove}
+ onKeyDown={onKeyDown}
+ onKeyUp={onKeyUp}
+ className={cn(
+ "dark relative isolate flex flex-col overflow-hidden bg-background outline-none focus-visible:border-ring focus-visible:ring-[3px] focus-visible:ring-ring/50 data-[disabled]:pointer-events-none data-[disabled]:opacity-50 [&_video]:relative [&_video]:object-contain",
+ "data-[state=fullscreen]:[&_video]:size-full [:fullscreen_&]:flex [:fullscreen_&]:h-full [:fullscreen_&]:max-h-screen [:fullscreen_&]:flex-col [:fullscreen_&]:justify-between",
+ "[&_[data-slider]::before]:-top-4 [&_[data-slider]::before]:-bottom-2 [&_[data-slider]::before]:absolute [&_[data-slider]::before]:inset-x-0 [&_[data-slider]::before]:z-10 [&_[data-slider]::before]:h-8 [&_[data-slider]::before]:cursor-pointer [&_[data-slider]::before]:content-[''] [&_[data-slider]]:relative [&_[data-slot='media-player-seek']:not([data-hovering])::before]:cursor-default",
+ "[&_video::-webkit-media-text-track-display]:top-auto! [&_video::-webkit-media-text-track-display]:bottom-[4%]! [&_video::-webkit-media-text-track-display]:mb-0! data-[state=fullscreen]:data-[controls-visible]:[&_video::-webkit-media-text-track-display]:bottom-[9%]! data-[controls-visible]:[&_video::-webkit-media-text-track-display]:bottom-[13%]! data-[state=fullscreen]:[&_video::-webkit-media-text-track-display]:bottom-[7%]!",
+ className,
+ )}
+ >
+ <span id={labelId} className="sr-only">
+ {label ?? "Media player"}
+ </span>
+ <span id={descriptionId} className="sr-only">
+ {isVideo
+ ? "Video player with custom controls for playback, volume, seeking, and more. Use space bar to play/pause, arrow keys (←/→) to seek, and arrow keys (↑/↓) to adjust volume."
+ : "Audio player with custom controls for playback, volume, seeking, and more. Use space bar to play/pause, Shift + arrow keys (←/→) to seek, and arrow keys (↑/↓) to adjust volume."}
+ </span>
+ {children}
+ <MediaPlayerVolumeIndicator />
+ </RootPrimitive>
+ </MediaPlayerContext.Provider>
+ );
+}
+
+interface MediaPlayerVideoProps extends React.ComponentProps<"video"> {
+ asChild?: boolean;
+}
+
+const MediaPlayerVideo = forwardRef<HTMLVideoElement, MediaPlayerVideoProps>((props: MediaPlayerVideoProps, ref) => {
+ const { asChild, ...videoProps } = props;
+
+ const context = useMediaPlayerContext("MediaPlayerVideo");
+ const dispatch = useMediaDispatch();
+ const mediaRefCallback = useMediaRef();
+ const composedRef = useComposedRefs(ref, context.mediaRef, mediaRefCallback);
+
+
+ const onPlayToggle = React.useCallback(
+ (event: React.MouseEvent<HTMLVideoElement>) => {
+ props.onClick?.(event);
+
+ if (event.defaultPrevented) return;
+
+ const mediaElement = event.currentTarget;
+ if (!mediaElement) return;
+
+ dispatch({
+ type: mediaElement.paused
+ ? MediaActionTypes.MEDIA_PLAY_REQUEST
+ : MediaActionTypes.MEDIA_PAUSE_REQUEST,
+ });
+ },
+ [dispatch, props.onClick],
+ );
+
+ const VideoPrimitive = asChild ? Slot : "video";
+
+ return (
+ <VideoPrimitive
+ aria-describedby={context.descriptionId}
+ aria-labelledby={context.labelId}
+ data-slot="media-player-video"
+ {...videoProps}
+ id={context.mediaId}
+ ref={composedRef}
+ onClick={onPlayToggle}
+ />
+ );
+});
+
+interface MediaPlayerAudioProps extends React.ComponentProps<"audio"> {
+ asChild?: boolean;
+}
+
+function MediaPlayerAudio(props: MediaPlayerAudioProps) {
+ const { asChild, ref, ...audioProps } = props;
+
+ const context = useMediaPlayerContext("MediaPlayerAudio");
+ const mediaRefCallback = useMediaRef();
+ const composedRef = useComposedRefs(ref, context.mediaRef, mediaRefCallback);
+
+ const AudioPrimitive = asChild ? Slot : "audio";
+
+ return (
+ <AudioPrimitive
+ aria-describedby={context.descriptionId}
+ aria-labelledby={context.labelId}
+ data-slot="media-player-audio"
+ {...audioProps}
+ id={context.mediaId}
+ ref={composedRef}
+ />
+ );
+}
+
+interface MediaPlayerControlsProps extends React.ComponentProps<"div"> {
+ asChild?: boolean;
+}
+
+function MediaPlayerControls(props: MediaPlayerControlsProps) {
+ const { asChild, className, ...controlsProps } = props;
+
+ const context = useMediaPlayerContext("MediaPlayerControls");
+ const isFullscreen = useMediaSelector(
+ (state) => state.mediaIsFullscreen ?? false,
+ );
+ const controlsVisible = useStoreSelector((state) => state.controlsVisible);
+
+ const ControlsPrimitive = asChild ? Slot : "div";
+
+ return (
+ <ControlsPrimitive
+ data-disabled={context.disabled ? "" : undefined}
+ data-slot="media-player-controls"
+ data-state={isFullscreen ? "fullscreen" : "windowed"}
+ data-visible={controlsVisible ? "" : undefined}
+ dir={context.dir}
+ className={cn(
+ "dark pointer-events-none absolute right-0 bottom-0 left-0 z-50 flex items-center gap-2 px-4 py-3 opacity-0 transition-opacity duration-200 data-[visible]:pointer-events-auto data-[visible]:opacity-100 [:fullscreen_&]:px-6 [:fullscreen_&]:py-4",
+ className,
+ )}
+ {...controlsProps}
+ />
+ );
+}
+
+interface MediaPlayerLoadingProps extends React.ComponentProps<"div"> {
+ delayMs?: number;
+ asChild?: boolean;
+}
+
+function MediaPlayerLoading(props: MediaPlayerLoadingProps) {
+ const {
+ delayMs = 500,
+ asChild,
+ className,
+ children,
+ ...loadingProps
+ } = props;
+
+ const isLoading = useMediaSelector((state) => state.mediaLoading ?? false);
+ const isPaused = useMediaSelector((state) => state.mediaPaused ?? true);
+ const hasPlayed = useMediaSelector((state) => state.mediaHasPlayed ?? false);
+
+ const shouldShowLoading = isLoading && !isPaused;
+ const shouldUseDelay = hasPlayed && shouldShowLoading;
+ const loadingDelayMs = shouldUseDelay ? delayMs : 0;
+
+ const [shouldRender, setShouldRender] = React.useState(false);
+ const timeoutRef = React.useRef<NodeJS.Timeout | null>(null);
+
+ React.useEffect(() => {
+ if (timeoutRef.current) {
+ clearTimeout(timeoutRef.current);
+ timeoutRef.current = null;
+ }
+
+ if (shouldShowLoading) {
+ if (loadingDelayMs > 0) {
+ timeoutRef.current = setTimeout(() => {
+ setShouldRender(true);
+ timeoutRef.current = null;
+ }, loadingDelayMs);
+ } else {
+ setShouldRender(true);
+ }
+ } else {
+ setShouldRender(false);
+ }
+
+ return () => {
+ if (timeoutRef.current) {
+ clearTimeout(timeoutRef.current);
+ timeoutRef.current = null;
+ }
+ };
+ }, [shouldShowLoading, loadingDelayMs]);
+
+ if (!shouldRender) return null;
+
+ const LoadingPrimitive = asChild ? Slot : "div";
+
+ return (
+ <LoadingPrimitive
+ role="status"
+ aria-live="polite"
+ data-slot="media-player-loading"
+ {...loadingProps}
+ className={cn(
+ "flex absolute inset-0 z-50 justify-center items-center duration-200 pointer-events-none fade-in-0 zoom-in-95 animate-in",
+ className,
+ )}
+ >
+ <Loader2Icon className="size-20 animate-spin stroke-[.0938rem] text-white" />
+ </LoadingPrimitive>
+ );
+}
+
+interface MediaPlayerErrorProps extends React.ComponentProps<"div"> {
+ error?: MediaError | null;
+ label?: string;
+ description?: string;
+ onRetry?: () => void;
+ onReload?: () => void;
+ asChild?: boolean;
+}
+
+function MediaPlayerError(props: MediaPlayerErrorProps) {
+ const {
+ error: errorProp,
+ label,
+ description,
+ onRetry: onRetryProp,
+ onReload: onReloadProp,
+ asChild,
+ className,
+ children,
+ ...errorProps
+ } = props;
+
+ const context = useMediaPlayerContext("MediaPlayerError");
+ const isFullscreen = useMediaSelector(
+ (state) => state.mediaIsFullscreen ?? false,
+ );
+ const mediaError = useMediaSelector((state) => state.mediaError);
+
+ const error = errorProp ?? mediaError;
+
+ const labelId = React.useId();
+ const descriptionId = React.useId();
+
+ const [actionState, setActionState] = React.useState<{
+ retryPending: boolean;
+ reloadPending: boolean;
+ }>({
+ retryPending: false,
+ reloadPending: false,
+ });
+
+ const onRetry = React.useCallback(() => {
+ setActionState((prev) => ({ ...prev, retryPending: true }));
+
+ requestAnimationFrame(() => {
+ const mediaElement = context.mediaRef.current;
+ if (!mediaElement) {
+ setActionState((prev) => ({ ...prev, retryPending: false }));
+ return;
+ }
+
+ if (onRetryProp) {
+ onRetryProp();
+ } else {
+ const currentSrc = mediaElement.currentSrc ?? mediaElement.src;
+ if (currentSrc) {
+ mediaElement.load();
+ }
+ }
+
+ setActionState((prev) => ({ ...prev, retryPending: false }));
+ });
+ }, [context.mediaRef, onRetryProp]);
+
+ const onReload = React.useCallback(() => {
+ setActionState((prev) => ({ ...prev, reloadPending: true }));
+
+ requestAnimationFrame(() => {
+ if (onReloadProp) {
+ onReloadProp();
+ } else {
+ window.location.reload();
+ }
+ });
+ }, [onReloadProp]);
+
+ const errorLabel = React.useMemo(() => {
+ if (label) return label;
+
+ if (!error) return "Playback Error";
+
+ const labelMap: Record<number, string> = {
+ [MediaError.MEDIA_ERR_ABORTED]: "Playback Interrupted",
+ [MediaError.MEDIA_ERR_NETWORK]: "Connection Problem",
+ [MediaError.MEDIA_ERR_DECODE]: "Media Error",
+ [MediaError.MEDIA_ERR_SRC_NOT_SUPPORTED]: "Unsupported Format",
+ };
+
+ return labelMap[error.code] ?? "Playback Error";
+ }, [label, error]);
+
+ const errorDescription = React.useMemo(() => {
+ if (description) return description;
+
+ if (!error) return "An unknown error occurred";
+
+ const descriptionMap: Record<number, string> = {
+ [MediaError.MEDIA_ERR_ABORTED]: "Media playback was aborted",
+ [MediaError.MEDIA_ERR_NETWORK]:
+ "A network error occurred while loading the media",
+ [MediaError.MEDIA_ERR_DECODE]:
+ "An error occurred while decoding the media",
+ [MediaError.MEDIA_ERR_SRC_NOT_SUPPORTED]:
+ "The media format is not supported",
+ };
+
+ return descriptionMap[error.code] ?? "An unknown error occurred";
+ }, [description, error]);
+
+ if (!error) return null;
+
+ const ErrorPrimitive = asChild ? Slot : "div";
+
+ return (
+ <ErrorPrimitive
+ role="alert"
+ aria-describedby={descriptionId}
+ aria-labelledby={labelId}
+ aria-live="assertive"
+ data-slot="media-player-error"
+ data-state={isFullscreen ? "fullscreen" : "windowed"}
+ {...errorProps}
+ className={cn(
+ "flex absolute inset-0 z-50 flex-col justify-center items-center text-white backdrop-blur-sm pointer-events-auto bg-black/80",
+ className,
+ )}
+ >
+ {children ?? (
+ <div className="flex flex-col gap-4 items-center px-6 py-8 max-w-md text-center">
+ <AlertTriangleIcon className="text-red-500 size-12" />
+ <div className="flex flex-col gap-px text-center">
+ <h3 className="text-xl font-semibold tracking-tight">
+ {errorLabel}
+ </h3>
+ <p className="text-sm leading-relaxed text-balance text-gray-11">
+ {errorDescription}
+ </p>
+ </div>
+ <div className="flex gap-2 items-center">
+ <Button
+ variant="primary"
+ size="sm"
+ onClick={onRetry}
+ disabled={actionState.retryPending}
+ >
+ {actionState.retryPending ? (
+ <Loader2Icon className="animate-spin size-3.5" />
+ ) : (
+ <RefreshCcwIcon className="size-3.5" />
+ )}
+ Try again
+ </Button>
+ <Button
+ variant="outline"
+ size="sm"
+ onClick={onReload}
+ disabled={actionState.reloadPending}
+ >
+ {actionState.reloadPending ? (
+ <Loader2Icon className="animate-spin size-3.5" />
+ ) : (
+ <RotateCcwIcon className="size-3.5" />
+ )}
+ Reload page
+ </Button>
+ </div>
+ </div>
+ )}
+ </ErrorPrimitive>
+ );
+}
+
+interface MediaPlayerVolumeIndicatorProps extends React.ComponentProps<"div"> {
+ asChild?: boolean;
+}
+
+function MediaPlayerVolumeIndicator(props: MediaPlayerVolumeIndicatorProps) {
+ const { asChild, className, ...indicatorProps } = props;
+
+ const mediaVolume = useMediaSelector((state) => state.mediaVolume ?? 1);
+ const mediaMuted = useMediaSelector((state) => state.mediaMuted ?? false);
+ const mediaVolumeLevel = useMediaSelector(
+ (state) => state.mediaVolumeLevel ?? "high",
+ );
+ const volumeIndicatorVisible = useStoreSelector(
+ (state) => state.volumeIndicatorVisible,
+ );
+
+ if (!volumeIndicatorVisible) return null;
+
+ const effectiveVolume = mediaMuted ? 0 : mediaVolume;
+ const volumePercentage = Math.round(effectiveVolume * 100);
+ const barCount = 10;
+ const activeBarCount = Math.ceil(effectiveVolume * barCount);
+
+ const VolumeIndicatorPrimitive = asChild ? Slot : "div";
+
+ return (
+ <VolumeIndicatorPrimitive
+ role="status"
+ aria-live="polite"
+ aria-label={`Volume ${mediaMuted ? "muted" : `${volumePercentage}%`}`}
+ data-slot="media-player-volume-indicator"
+ {...indicatorProps}
+ className={cn(
+ "flex absolute inset-0 z-50 justify-center items-center pointer-events-none",
+ className,
+ )}
+ >
+ <div className="flex flex-col gap-3 items-center px-6 py-4 text-white rounded-lg duration-200 fade-in-0 zoom-in-95 animate-in bg-black/30 backdrop-blur-xs">
+ <div className="flex gap-2 items-center">
+ {mediaVolumeLevel === "off" || mediaMuted ? (
+ <VolumeXIcon className="size-6" />
+ ) : mediaVolumeLevel === "high" ? (
+ <Volume2Icon className="size-6" />
+ ) : (
+ <Volume1Icon className="size-6" />
+ )}
+ <span className="text-sm font-medium tabular-nums">
+ {mediaMuted ? "Muted" : `${volumePercentage}%`}
+ </span>
+ </div>
+ <div className="flex gap-1 items-center">
+ {Array.from({ length: barCount }, (_, index) => (
+ <div
+ key={index}
+ className={cn(
+ "w-1.5 rounded-full transition-all duration-150",
+ index < activeBarCount && !mediaMuted
+ ? "scale-100 bg-white"
+ : "scale-90 bg-white/30",
+ )}
+ style={{
+ height: `${12 + index * 2}px`,
+ animationDelay: `${index * 50}ms`,
+ }}
+ />
+ ))}
+ </div>
+ </div>
+ </VolumeIndicatorPrimitive>
+ );
+}
+
+interface MediaPlayerControlsOverlayProps extends React.ComponentProps<"div"> {
+ asChild?: boolean;
+}
+
+function MediaPlayerControlsOverlay(props: MediaPlayerControlsOverlayProps) {
+ const { asChild, className, ...overlayProps } = props;
+
+ const isFullscreen = useMediaSelector(
+ (state) => state.mediaIsFullscreen ?? false,
+ );
+ const controlsVisible = useStoreSelector((state) => state.controlsVisible);
+
+ const OverlayPrimitive = asChild ? Slot : "div";
+
+ return (
+ <OverlayPrimitive
+ data-slot="media-player-controls-overlay"
+ data-state={isFullscreen ? "fullscreen" : "windowed"}
+ data-visible={controlsVisible ? "" : undefined}
+ {...overlayProps}
+ className={cn(
+ "absolute inset-0 bg-gradient-to-t to-transparent opacity-0 transition-opacity duration-200 pointer-events-none -z-10 from-black/80 data-[visible]:opacity-100",
+ className,
+ )}
+ />
+ );
+}
+
+interface MediaPlayerPlayProps extends React.ComponentProps<typeof Button> { }
+
+function MediaPlayerPlay(props: MediaPlayerPlayProps) {
+ const { asChild, children, className, disabled, ...playButtonProps } = props;
+
+ const context = useMediaPlayerContext("MediaPlayerPlay");
+ const dispatch = useMediaDispatch();
+ const mediaPaused = useMediaSelector((state) => state.mediaPaused ?? true);
+
+ const isDisabled = disabled || context.disabled;
+
+ const onPlayToggle = React.useCallback(
+ (event: React.MouseEvent<HTMLButtonElement>) => {
+ props.onClick?.(event);
+
+ if (event.defaultPrevented) return;
+
+ dispatch({
+ type: mediaPaused
+ ? MediaActionTypes.MEDIA_PLAY_REQUEST
+ : MediaActionTypes.MEDIA_PAUSE_REQUEST,
+ });
+ },
+ [dispatch, props.onClick, mediaPaused],
+ );
+
+ return (
+ <MediaPlayerTooltip
+ tooltip={mediaPaused ? "Play" : "Pause"}
+ shortcut="Space"
+ >
+ <PlayerButton
+ type="button"
+ aria-controls={context.mediaId}
+ aria-label={mediaPaused ? "Play" : "Pause"}
+ aria-pressed={!mediaPaused}
+ data-disabled={isDisabled ? "" : undefined}
+ data-slot="media-player-play-button"
+ data-state={mediaPaused ? "off" : "on"}
+ disabled={isDisabled}
+ {...playButtonProps}
+ variant="ghost"
+ size="icon"
+ className={cn(
+ "size-8 [&_svg:not([class*='fill-'])]:fill-current",
+ className,
+ )}
+ onClick={onPlayToggle}
+ >
+ {children ?? (mediaPaused ? <PlayIcon /> : <PauseIcon />)}
+ </PlayerButton>
+ </MediaPlayerTooltip>
+ );
+}
+
+interface MediaPlayerSeekBackwardProps
+ extends React.ComponentProps<typeof Button> {
+ seconds?: number;
+}
+
+function MediaPlayerSeekBackward(props: MediaPlayerSeekBackwardProps) {
+ const {
+ seconds = SEEK_STEP_SHORT,
+ asChild,
+ children,
+ className,
+ disabled,
+ ...seekBackwardProps
+ } = props;
+
+ const context = useMediaPlayerContext("MediaPlayerSeekBackward");
+ const dispatch = useMediaDispatch();
+ const mediaCurrentTime = useMediaSelector(
+ (state) => state.mediaCurrentTime ?? 0,
+ );
+
+ const isDisabled = disabled || context.disabled;
+
+ const onSeekBackward = React.useCallback(
+ (event: React.MouseEvent<HTMLButtonElement>) => {
+ props.onClick?.(event);
+
+ if (event.defaultPrevented) return;
+
+ dispatch({
+ type: MediaActionTypes.MEDIA_SEEK_REQUEST,
+ detail: Math.max(0, mediaCurrentTime - seconds),
+ });
+ },
+ [dispatch, props.onClick, mediaCurrentTime, seconds],
+ );
+
+ return (
+ <MediaPlayerTooltip
+ tooltip={`Back ${seconds}s`}
+ shortcut={context.isVideo ? ["←"] : ["Shift ←"]}
+ >
+ <PlayerButton
+ type="button"
+ aria-controls={context.mediaId}
+ aria-label={`Back ${seconds} seconds`}
+ data-disabled={isDisabled ? "" : undefined}
+ data-slot="media-player-seek-backward"
+ disabled={isDisabled}
+ {...seekBackwardProps}
+ variant="ghost"
+ size="icon"
+ className={cn("size-8", className)}
+ onClick={onSeekBackward}
+ >
+ {children ?? <RewindIcon />}
+ </PlayerButton>
+ </MediaPlayerTooltip>
+ );
+}
+
+interface MediaPlayerSeekForwardProps
+ extends React.ComponentProps<typeof Button> {
+ seconds?: number;
+}
+
+function MediaPlayerSeekForward(props: MediaPlayerSeekForwardProps) {
+ const {
+ seconds = SEEK_STEP_LONG,
+ asChild,
+ children,
+ className,
+ disabled,
+ ...seekForwardProps
+ } = props;
+
+ const context = useMediaPlayerContext("MediaPlayerSeekForward");
+ const dispatch = useMediaDispatch();
+ const mediaCurrentTime = useMediaSelector(
+ (state) => state.mediaCurrentTime ?? 0,
+ );
+ const [, seekableEnd] = useMediaSelector(
+ (state) => state.mediaSeekable ?? [0, 0],
+ );
+ const isDisabled = disabled || context.disabled;
+
+ const onSeekForward = React.useCallback(
+ (event: React.MouseEvent<HTMLButtonElement>) => {
+ props.onClick?.(event);
+
+ if (event.defaultPrevented) return;
+
+ dispatch({
+ type: MediaActionTypes.MEDIA_SEEK_REQUEST,
+ detail: Math.min(
+ seekableEnd ?? Number.POSITIVE_INFINITY,
+ mediaCurrentTime + seconds,
+ ),
+ });
+ },
+ [dispatch, props.onClick, mediaCurrentTime, seekableEnd, seconds],
+ );
+
+ return (
+ <MediaPlayerTooltip
+ tooltip={`Forward ${seconds}s`}
+ shortcut={context.isVideo ? ["→"] : ["Shift →"]}
+ >
+ <PlayerButton
+ type="button"
+ aria-controls={context.mediaId}
+ aria-label={`Forward ${seconds} seconds`}
+ data-disabled={isDisabled ? "" : undefined}
+ data-slot="media-player-seek-forward"
+ disabled={isDisabled}
+ {...seekForwardProps}
+ variant="ghost"
+ size="icon"
+ className={cn("size-8", className)}
+ onClick={onSeekForward}
+ >
+ {children ?? <FastForwardIcon />}
+ </PlayerButton>
+ </MediaPlayerTooltip>
+ );
+}
+
+interface SeekState {
+ isHovering: boolean;
+ pendingSeekTime: number | null;
+ hasInitialPosition: boolean;
+}
+
+interface MediaPlayerSeekProps
+ extends React.ComponentProps<typeof SliderPrimitive.Root> {
+ withTime?: boolean;
+ withoutChapter?: boolean;
+ withoutTooltip?: boolean;
+ tooltipThumbnailSrc?: string | ((time: number) => string);
+ tooltipTimeVariant?: "current" | "progress";
+ tooltipSideOffset?: number;
+ tooltipCollisionBoundary?: Element | Element[];
+ tooltipCollisionPadding?:
+ | number
+ | Partial<Record<"top" | "right" | "bottom" | "left", number>>;
+}
+
+function MediaPlayerSeek(props: MediaPlayerSeekProps) {
+ const {
+ withTime = false,
+ withoutChapter = false,
+ withoutTooltip = false,
+ tooltipTimeVariant = "current",
+ tooltipThumbnailSrc,
+ tooltipSideOffset,
+ tooltipCollisionPadding = SEEK_COLLISION_PADDING,
+ tooltipCollisionBoundary,
+ className,
+ disabled,
+ ...seekProps
+ } = props;
+
+ const context = useMediaPlayerContext(SEEK_NAME);
+ const store = useStoreContext(SEEK_NAME);
+ const dispatch = useMediaDispatch();
+ const mediaCurrentTime = useMediaSelector(
+ (state) => state.mediaCurrentTime ?? 0,
+ );
+ const [seekableStart = 0, seekableEnd = 0] = useMediaSelector(
+ (state) => state.mediaSeekable ?? [0, 0],
+ );
+ const mediaBuffered = useMediaSelector((state) => state.mediaBuffered ?? []);
+ const mediaEnded = useMediaSelector((state) => state.mediaEnded ?? false);
+
+ const chapterCues = useMediaSelector(
+ (state) => state.mediaChaptersCues ?? [],
+ );
+ const mediaPreviewTime = useMediaSelector((state) => state.mediaPreviewTime);
+ const mediaPreviewImage = useMediaSelector(
+ (state) => state.mediaPreviewImage,
+ );
+ const mediaPreviewCoords = useMediaSelector(
+ (state) => state.mediaPreviewCoords,
+ );
+
+ const seekRef = React.useRef<HTMLDivElement>(null);
+ const tooltipRef = React.useRef<HTMLDivElement>(null);
+ const justCommittedRef = React.useRef<boolean>(false);
+
+ const hoverTimeRef = React.useRef(0);
+ const tooltipXRef = React.useRef(0);
+ const tooltipYRef = React.useRef(0);
+ const seekRectRef = React.useRef<DOMRect | null>(null);
+ const collisionDataRef = React.useRef<{
+ padding: { top: number; right: number; bottom: number; left: number };
+ boundaries: Element[];
+ } | null>(null);
+
+ const [seekState, setSeekState] = React.useState<SeekState>({
+ isHovering: false,
+ pendingSeekTime: null,
+ hasInitialPosition: false,
+ });
+
+ const rafIdRef = React.useRef<number | null>(null);
+ const seekThrottleRef = React.useRef<number | null>(null);
+ const hoverTimeoutRef = React.useRef<number | null>(null);
+ const lastPointerXRef = React.useRef<number>(0);
+ const lastPointerYRef = React.useRef<number>(0);
+ const previewDebounceRef = React.useRef<number | null>(null);
+ const pointerEnterTimeRef = React.useRef<number>(0);
+ const horizontalMovementRef = React.useRef<number>(0);
+ const verticalMovementRef = React.useRef<number>(0);
+ const lastSeekCommitTimeRef = React.useRef<number>(0);
+
+ const timeCache = React.useRef<Map<number, string>>(new Map());
+
+ const displayValue = seekState.pendingSeekTime ?? mediaCurrentTime;
+
+ const isDisabled = disabled || context.disabled;
+ const tooltipDisabled =
+ withoutTooltip || context.withoutTooltip || store.getState().menuOpen;
+
+ const currentTooltipSideOffset =
+ tooltipSideOffset ?? context.tooltipSideOffset;
+
+ const getCachedTime = React.useCallback((time: number, duration: number) => {
+ const roundedTime = Math.floor(time);
+ const key = roundedTime + duration * 10000;
+
+ if (timeCache.current.has(key)) {
+ return timeCache.current.get(key) as string;
+ }
+
+ const formatted = timeUtils.formatTime(time, duration);
+ timeCache.current.set(key, formatted);
+
+ if (timeCache.current.size > 100) {
+ timeCache.current.clear();
+ }
+
+ return formatted;
+ }, []);
+
+ const currentTime = getCachedTime(displayValue, seekableEnd);
+ const duration = getCachedTime(seekableEnd, seekableEnd);
+ const remainingTime = getCachedTime(seekableEnd - displayValue, seekableEnd);
+
+ const onCollisionDataUpdate = React.useCallback(() => {
+ if (collisionDataRef.current) return collisionDataRef.current;
+
+ const padding =
+ typeof tooltipCollisionPadding === "number"
+ ? {
+ top: tooltipCollisionPadding,
+ right: tooltipCollisionPadding,
+ bottom: tooltipCollisionPadding,
+ left: tooltipCollisionPadding,
+ }
+ : { top: 0, right: 0, bottom: 0, left: 0, ...tooltipCollisionPadding };
+
+ const boundaries = tooltipCollisionBoundary
+ ? Array.isArray(tooltipCollisionBoundary)
+ ? tooltipCollisionBoundary
+ : [tooltipCollisionBoundary]
+ : ([context.rootRef.current].filter(Boolean) as Element[]);
+
+ collisionDataRef.current = { padding, boundaries };
+ return collisionDataRef.current;
+ }, [tooltipCollisionPadding, tooltipCollisionBoundary, context.rootRef]);
+
+ const getCurrentChapterCue = React.useCallback(
+ (time: number) => {
+ if (withoutChapter || chapterCues.length === 0) return null;
+ return chapterCues.find((c) => time >= c.startTime && time < c.endTime);
+ },
+ [chapterCues, withoutChapter],
+ );
+
+ const getThumbnail = React.useCallback(
+ (time: number) => {
+ if (tooltipDisabled) return null;
+
+ if (tooltipThumbnailSrc) {
+ const src =
+ typeof tooltipThumbnailSrc === "function"
+ ? tooltipThumbnailSrc(time)
+ : tooltipThumbnailSrc;
+ return { src, coords: null };
+ }
+
+ if (
+ mediaPreviewTime !== undefined &&
+ Math.abs(time - mediaPreviewTime) < 0.1 &&
+ mediaPreviewImage
+ ) {
+ return {
+ src: mediaPreviewImage,
+ coords: mediaPreviewCoords ?? null,
+ };
+ }
+
+ return null;
+ },
+ [
+ tooltipThumbnailSrc,
+ mediaPreviewTime,
+ mediaPreviewImage,
+ mediaPreviewCoords,
+ tooltipDisabled,
+ ],
+ );
+
+ const onPreviewUpdate = React.useCallback(
+ (time: number) => {
+ if (tooltipDisabled) return;
+
+ if (previewDebounceRef.current) {
+ cancelAnimationFrame(previewDebounceRef.current);
+ }
+
+ previewDebounceRef.current = requestAnimationFrame(() => {
+ dispatch({
+ type: MediaActionTypes.MEDIA_PREVIEW_REQUEST,
+ detail: time,
+ });
+ previewDebounceRef.current = null;
+ });
+ },
+ [dispatch, tooltipDisabled],
+ );
+
+ const onTooltipPositionUpdate = React.useCallback(
+ (clientX: number) => {
+ if (!seekRef.current) return;
+
+ const tooltipWidth =
+ tooltipRef.current?.offsetWidth ?? SEEK_TOOLTIP_WIDTH_FALLBACK;
+
+ let x = clientX;
+ const y = seekRectRef.current?.top ?? 0;
+
+ const collisionData = onCollisionDataUpdate();
+ const halfTooltipWidth = tooltipWidth / 2;
+
+ let minLeft = 0;
+ let maxRight = window.innerWidth;
+
+ for (const boundary of collisionData.boundaries) {
+ const boundaryRect = boundary.getBoundingClientRect();
+ minLeft = Math.max(
+ minLeft,
+ boundaryRect.left + collisionData.padding.left,
+ );
+ maxRight = Math.min(
+ maxRight,
+ boundaryRect.right - collisionData.padding.right,
+ );
+ }
+
+ if (x - halfTooltipWidth < minLeft) {
+ x = minLeft + halfTooltipWidth;
+ } else if (x + halfTooltipWidth > maxRight) {
+ x = maxRight - halfTooltipWidth;
+ }
+
+ const viewportPadding = SEEK_COLLISION_PADDING;
+ if (x - halfTooltipWidth < viewportPadding) {
+ x = viewportPadding + halfTooltipWidth;
+ } else if (x + halfTooltipWidth > window.innerWidth - viewportPadding) {
+ x = window.innerWidth - viewportPadding - halfTooltipWidth;
+ }
+
+ tooltipXRef.current = x;
+ tooltipYRef.current = y;
+
+ if (tooltipRef.current) {
+ tooltipRef.current.style.setProperty(SEEK_TOOLTIP_X, `${x}px`);
+ tooltipRef.current.style.setProperty(SEEK_TOOLTIP_Y, `${y}px`);
+ }
+
+ if (!seekState.hasInitialPosition) {
+ setSeekState((prev) => ({ ...prev, hasInitialPosition: true }));
+ }
+ },
+ [onCollisionDataUpdate, seekState.hasInitialPosition],
+ );
+
+ const onHoverProgressUpdate = React.useCallback(() => {
+ if (!seekRef.current || seekableEnd <= 0) return;
+
+ const hoverPercent = Math.min(
+ 100,
+ (hoverTimeRef.current / seekableEnd) * 100,
+ );
+ seekRef.current.style.setProperty(
+ SEEK_HOVER_PERCENT,
+ `${hoverPercent.toFixed(4)}%`,
+ );
+ }, [seekableEnd]);
+
+ React.useEffect(() => {
+ if (seekState.pendingSeekTime !== null) {
+ const diff = Math.abs(mediaCurrentTime - seekState.pendingSeekTime);
+ if (diff < 0.5) {
+ setSeekState((prev) => ({ ...prev, pendingSeekTime: null }));
+ }
+ }
+ }, [mediaCurrentTime, seekState.pendingSeekTime]);
+
+ React.useEffect(() => {
+ if (!seekState.isHovering || tooltipDisabled) return;
+
+ function onScroll() {
+ setSeekState((prev) => ({
+ ...prev,
+ isHovering: false,
+ hasInitialPosition: false,
+ }));
+ dispatch({
+ type: MediaActionTypes.MEDIA_PREVIEW_REQUEST,
+ detail: undefined,
+ });
+ }
+
+ document.addEventListener("scroll", onScroll, { passive: true });
+ return () => {
+ document.removeEventListener("scroll", onScroll);
+ };
+ }, [dispatch, seekState.isHovering, tooltipDisabled]);
+
+ const bufferedProgress = React.useMemo(() => {
+ if (mediaBuffered.length === 0 || seekableEnd <= 0) return 0;
+
+ if (mediaEnded) return 1;
+
+ const containingRange = mediaBuffered.find(
+ ([start, end]) => start <= mediaCurrentTime && mediaCurrentTime <= end,
+ );
+
+ if (containingRange) {
+ return Math.min(1, containingRange[1] / seekableEnd);
+ }
+
+ return Math.min(1, seekableStart / seekableEnd);
+ }, [mediaBuffered, mediaCurrentTime, seekableEnd, mediaEnded, seekableStart]);
+
+ const onPointerEnter = React.useCallback(() => {
+ if (seekRef.current) {
+ seekRectRef.current = seekRef.current.getBoundingClientRect();
+ }
+
+ collisionDataRef.current = null;
+ pointerEnterTimeRef.current = Date.now();
+ horizontalMovementRef.current = 0;
+ verticalMovementRef.current = 0;
+
+ if (seekableEnd > 0) {
+ if (hoverTimeoutRef.current) {
+ clearTimeout(hoverTimeoutRef.current);
+ }
+
+ if (!tooltipDisabled) {
+ if (lastPointerXRef.current && seekRectRef.current) {
+ const clientX = Math.max(
+ seekRectRef.current.left,
+ Math.min(lastPointerXRef.current, seekRectRef.current.right),
+ );
+ onTooltipPositionUpdate(clientX);
+ }
+ }
+ }
+ }, [seekableEnd, onTooltipPositionUpdate, tooltipDisabled]);
+
+ const onPointerLeave = React.useCallback(() => {
+ if (hoverTimeoutRef.current) {
+ clearTimeout(hoverTimeoutRef.current);
+ hoverTimeoutRef.current = null;
+ }
+ if (rafIdRef.current) {
+ cancelAnimationFrame(rafIdRef.current);
+ rafIdRef.current = null;
+ }
+ if (previewDebounceRef.current) {
+ cancelAnimationFrame(previewDebounceRef.current);
+ previewDebounceRef.current = null;
+ }
+
+ setSeekState((prev) => ({
+ ...prev,
+ isHovering: false,
+ hasInitialPosition: false,
+ }));
+
+ justCommittedRef.current = false;
+ seekRectRef.current = null;
+ collisionDataRef.current = null;
+
+ pointerEnterTimeRef.current = 0;
+ horizontalMovementRef.current = 0;
+ verticalMovementRef.current = 0;
+ lastPointerXRef.current = 0;
+ lastPointerYRef.current = 0;
+ lastSeekCommitTimeRef.current = 0;
+
+ if (!tooltipDisabled) {
+ dispatch({
+ type: MediaActionTypes.MEDIA_PREVIEW_REQUEST,
+ detail: undefined,
+ });
+ }
+ }, [dispatch, tooltipDisabled]);
+
+ const onPointerMove = React.useCallback(
+ (event: React.PointerEvent<HTMLDivElement>) => {
+ if (seekableEnd <= 0) return;
+
+ if (!seekRectRef.current && seekRef.current) {
+ seekRectRef.current = seekRef.current.getBoundingClientRect();
+ }
+
+ if (!seekRectRef.current) return;
+
+ const currentX = event.clientX;
+ const currentY = event.clientY;
+
+ if (lastPointerXRef.current !== 0 && lastPointerYRef.current !== 0) {
+ const deltaX = Math.abs(currentX - lastPointerXRef.current);
+ const deltaY = Math.abs(currentY - lastPointerYRef.current);
+
+ horizontalMovementRef.current += deltaX;
+ verticalMovementRef.current += deltaY;
+ }
+
+ lastPointerXRef.current = currentX;
+ lastPointerYRef.current = currentY;
+
+ if (rafIdRef.current) {
+ cancelAnimationFrame(rafIdRef.current);
+ }
+
+ rafIdRef.current = requestAnimationFrame(() => {
+ const wasJustCommitted = justCommittedRef.current;
+ if (wasJustCommitted) {
+ justCommittedRef.current = false;
+ }
+
+ const seekRect = seekRectRef.current;
+ if (!seekRect) {
+ rafIdRef.current = null;
+ return;
+ }
+
+ const clientX = lastPointerXRef.current;
+ const offsetXOnSeekBar = Math.max(
+ 0,
+ Math.min(clientX - seekRect.left, seekRect.width),
+ );
+ const relativeX = offsetXOnSeekBar / seekRect.width;
+ const calculatedHoverTime = relativeX * seekableEnd;
+
+ hoverTimeRef.current = calculatedHoverTime;
+
+ onHoverProgressUpdate();
+
+ const wasHovering = seekState.isHovering;
+ const isCurrentlyHovering =
+ clientX >= seekRect.left && clientX <= seekRect.right;
+
+ const timeHovering = Date.now() - pointerEnterTimeRef.current;
+ const totalMovement =
+ horizontalMovementRef.current + verticalMovementRef.current;
+ const horizontalRatio =
+ totalMovement > 0 ? horizontalMovementRef.current / totalMovement : 0;
+
+ const timeSinceSeekCommit = Date.now() - lastSeekCommitTimeRef.current;
+ const isInSeekCooldown = timeSinceSeekCommit < 300;
+
+ const shouldShowTooltip =
+ !wasJustCommitted &&
+ !isInSeekCooldown &&
+ (timeHovering > 150 ||
+ horizontalRatio > 0.6 ||
+ (totalMovement < 10 && timeHovering > 50));
+
+ if (
+ !wasHovering &&
+ isCurrentlyHovering &&
+ shouldShowTooltip &&
+ !tooltipDisabled
+ ) {
+ setSeekState((prev) => ({ ...prev, isHovering: true }));
+ }
+
+ if (!tooltipDisabled) {
+ onPreviewUpdate(calculatedHoverTime);
+
+ if (isCurrentlyHovering && (wasHovering || shouldShowTooltip)) {
+ onTooltipPositionUpdate(clientX);
+ }
+ }
+
+ rafIdRef.current = null;
+ });
+ },
+ [
+ onPreviewUpdate,
+ onTooltipPositionUpdate,
+ onHoverProgressUpdate,
+ seekableEnd,
+ seekState.isHovering,
+ tooltipDisabled,
+ ],
+ );
+
+ const onSeek = React.useCallback(
+ (value: number[]) => {
+ const time = value[0] ?? 0;
+
+ setSeekState((prev) => ({ ...prev, pendingSeekTime: time }));
+
+ if (!store.getState().dragging) {
+ store.setState("dragging", true);
+ }
+
+ if (seekThrottleRef.current) {
+ cancelAnimationFrame(seekThrottleRef.current);
+ }
+
+ seekThrottleRef.current = requestAnimationFrame(() => {
+ dispatch({
+ type: MediaActionTypes.MEDIA_SEEK_REQUEST,
+ detail: time,
+ });
+ seekThrottleRef.current = null;
+ });
+ },
+ [dispatch, store.getState, store.setState],
+ );
+
+ const onSeekCommit = React.useCallback(
+ (value: number[]) => {
+ const time = value[0] ?? 0;
+
+ if (seekThrottleRef.current) {
+ cancelAnimationFrame(seekThrottleRef.current);
+ seekThrottleRef.current = null;
+ }
+
+ if (hoverTimeoutRef.current) {
+ clearTimeout(hoverTimeoutRef.current);
+ hoverTimeoutRef.current = null;
+ }
+ if (rafIdRef.current) {
+ cancelAnimationFrame(rafIdRef.current);
+ rafIdRef.current = null;
+ }
+ if (previewDebounceRef.current) {
+ cancelAnimationFrame(previewDebounceRef.current);
+ previewDebounceRef.current = null;
+ }
+
+ setSeekState((prev) => ({
+ ...prev,
+ pendingSeekTime: time,
+ isHovering: false,
+ hasInitialPosition: false,
+ }));
+
+ justCommittedRef.current = true;
+ collisionDataRef.current = null;
+ lastSeekCommitTimeRef.current = Date.now();
+
+ // Reset movement tracking after seek commit
+ pointerEnterTimeRef.current = Date.now();
+ horizontalMovementRef.current = 0;
+ verticalMovementRef.current = 0;
+
+ if (store.getState().dragging) {
+ store.setState("dragging", false);
+ }
+
+ dispatch({
+ type: MediaActionTypes.MEDIA_SEEK_REQUEST,
+ detail: time,
+ });
+
+ dispatch({
+ type: MediaActionTypes.MEDIA_PREVIEW_REQUEST,
+ detail: undefined,
+ });
+ },
+ [dispatch, store.getState, store.setState],
+ );
+
+ React.useEffect(() => {
+ return () => {
+ if (seekThrottleRef.current) {
+ cancelAnimationFrame(seekThrottleRef.current);
+ }
+ if (hoverTimeoutRef.current) {
+ clearTimeout(hoverTimeoutRef.current);
+ }
+ if (rafIdRef.current) {
+ cancelAnimationFrame(rafIdRef.current);
+ }
+ if (previewDebounceRef.current) {
+ cancelAnimationFrame(previewDebounceRef.current);
+ }
+ };
+ }, []);
+
+ const currentChapterCue = getCurrentChapterCue(hoverTimeRef.current);
+ const thumbnail = getThumbnail(hoverTimeRef.current);
+ const hoverTime = getCachedTime(hoverTimeRef.current, seekableEnd);
+
+ const chapterSeparators = React.useMemo(() => {
+ if (withoutChapter || chapterCues.length <= 1 || seekableEnd <= 0) {
+ return null;
+ }
+
+ return chapterCues.slice(1).map((chapterCue, index) => {
+ const position = (chapterCue.startTime / seekableEnd) * 100;
+
+ return (
+ <div
+ key={`chapter-${index}-${chapterCue.startTime}`}
+ role="presentation"
+ aria-hidden="true"
+ data-slot="media-player-seek-chapter-separator"
+ className="absolute top-0 h-full bg-black"
+ style={{
+ width: ".1563rem",
+ left: `${position}%`,
+ transform: "translateX(-50%)",
+ }}
+ />
+ );
+ });
+ }, [chapterCues, seekableEnd, withoutChapter]);
+
+ const spriteStyle = React.useMemo<React.CSSProperties>(() => {
+ if (!thumbnail?.coords || !thumbnail?.src) {
+ return {};
+ }
+
+ const coordX = thumbnail.coords[0];
+ const coordY = thumbnail.coords[1];
+
+ const spriteWidth = Number.parseFloat(thumbnail.coords[2] ?? "0");
+ const spriteHeight = Number.parseFloat(thumbnail.coords[3] ?? "0");
+
+ const scaleX = spriteWidth > 0 ? SPRITE_CONTAINER_WIDTH / spriteWidth : 1;
+ const scaleY =
+ spriteHeight > 0 ? SPRITE_CONTAINER_HEIGHT / spriteHeight : 1;
+ const scale = Math.min(scaleX, scaleY);
+
+ return {
+ width: `${spriteWidth}px`,
+ height: `${spriteHeight}px`,
+ backgroundImage: `url(${thumbnail.src})`,
+ backgroundPosition: `-${coordX}px -${coordY}px`,
+ backgroundRepeat: "no-repeat",
+ transform: `scale(${scale})`,
+ transformOrigin: "top left",
+ };
+ }, [thumbnail?.coords, thumbnail?.src]);
+
+ const SeekSlider = (
+ <div data-slot="media-player-seek-container" className="relative w-full">
+ <SliderPrimitive.Root
+ aria-controls={context.mediaId}
+ aria-valuetext={`${currentTime} of ${duration}`}
+ data-hovering={seekState.isHovering ? "" : undefined}
+ data-slider=""
+ data-slot="media-player-seek"
+ disabled={isDisabled}
+ {...seekProps}
+ ref={seekRef}
+ min={seekableStart}
+ max={seekableEnd}
+ step={0.01}
+ className={cn(
+ "flex relative items-center w-full select-none touch-none data-[disabled]:pointer-events-none data-[disabled]:opacity-50",
+ className,
+ )}
+ value={[displayValue]}
+ onValueChange={onSeek}
+ onValueCommit={onSeekCommit}
+ onPointerEnter={onPointerEnter}
+ onPointerLeave={onPointerLeave}
+ onPointerMove={onPointerMove}
+ >
+ <SliderPrimitive.Track className="overflow-hidden relative w-full h-1 rounded-full grow bg-white/40">
+ <div
+ data-slot="media-player-seek-buffered"
+ className="absolute h-full bg-white/10 will-change-[width]"
+ style={{
+ width: `${bufferedProgress * 100}%`,
+ }}
+ />
+ <SliderPrimitive.Range className="absolute h-full bg-white will-change-[width]" />
+ {seekState.isHovering && seekableEnd > 0 && (
+ <div
+ data-slot="media-player-seek-hover-range"
+ className="absolute h-full bg-white/70 will-change-[width,opacity]"
+ style={{
+ width: `var(${SEEK_HOVER_PERCENT}, 0%)`,
+ transition: "opacity 150ms ease-out",
+ }}
+ />
+ )}
+ {chapterSeparators}
+ </SliderPrimitive.Track>
+ <SliderPrimitive.Thumb className="relative z-10 block size-3 shrink-0 rounded-full bg-white shadow-sm transition-[color,box-shadow] will-change-transform focus-visible:outline-hidden outline-0 disabled:pointer-events-none disabled:opacity-50" />
+ </SliderPrimitive.Root>
+ {!withoutTooltip &&
+ !context.withoutTooltip &&
+ seekState.isHovering &&
+ seekableEnd > 0 && (
+ <MediaPlayerPortal>
+ <div
+ ref={tooltipRef}
+ className="pointer-events-none z-50 [backface-visibility:hidden] [contain:layout_style] [transition:opacity_150ms_ease-in-out]"
+ style={{
+ position: "fixed" as const,
+ left: `var(${SEEK_TOOLTIP_X}, 0rem)`,
+ top: `var(${SEEK_TOOLTIP_Y}, 0rem)`,
+ transform: `translateX(-50%) translateY(calc(-100% - ${currentTooltipSideOffset}px))`,
+ visibility: seekState.hasInitialPosition ? "visible" : "hidden",
+ opacity: seekState.hasInitialPosition ? 1 : 0,
+ }}
+ >
+ <div
+ className={cn(
+ "flex flex-col items-center gap-1.5 rounded-md border border-white/10 bg-gray-12 text-foreground shadow-sm",
+ thumbnail && "min-h-10",
+ !thumbnail && currentChapterCue && "px-3 py-1.5",
+ )}
+ >
+ {thumbnail?.src && (
+ <div
+ data-slot="media-player-seek-thumbnail"
+ className="overflow-hidden rounded-md rounded-b-none"
+ style={{
+ width: `${SPRITE_CONTAINER_WIDTH}px`,
+ height: `${SPRITE_CONTAINER_HEIGHT}px`,
+ }}
+ >
+ {thumbnail.coords ? (
+ <div style={spriteStyle} />
+ ) : (
+ <img
+ src={thumbnail.src}
+ alt={`Preview at ${hoverTime}`}
+ className="object-cover size-full"
+ />
+ )}
+ </div>
+ )}
+ {currentChapterCue && (
+ <div
+ data-slot="media-player-seek-chapter-title"
+ className="text-xs text-center text-white line-clamp-2 max-w-48"
+ >
+ {currentChapterCue.text}
+ </div>
+ )}
+ <div
+ data-slot="media-player-seek-time"
+ className={cn(
+ "whitespace-nowrap text-center text-xs text-white tabular-nums",
+ thumbnail && "pb-1.5",
+ !(thumbnail || currentChapterCue) && "px-2.5 py-1",
+ )}
+ >
+ {tooltipTimeVariant === "progress"
+ ? `${hoverTime} / ${duration}`
+ : hoverTime}
+ </div>
+ </div>
+ </div>
+ </MediaPlayerPortal>
+ )}
+ </div>
+ );
+
+ if (withTime) {
+ return (
+ <div className="flex gap-2 items-center w-full">
+ <span className="text-sm tabular-nums">{currentTime}</span>
+ {SeekSlider}
+ <span className="text-sm tabular-nums">{remainingTime}</span>
+ </div>
+ );
+ }
+
+ return SeekSlider;
+}
+
+interface MediaPlayerVolumeProps
+ extends React.ComponentProps<typeof SliderPrimitive.Root> {
+ asChild?: boolean;
+ expandable?: boolean;
+}
+
+function MediaPlayerVolume(props: MediaPlayerVolumeProps) {
+ const {
+ asChild,
+ expandable = false,
+ className,
+ disabled,
+ ...volumeProps
+ } = props;
+
+ const context = useMediaPlayerContext(VOLUME_NAME);
+ const store = useStoreContext(VOLUME_NAME);
+ const dispatch = useMediaDispatch();
+ const mediaVolume = useMediaSelector((state) => state.mediaVolume ?? 1);
+ const mediaMuted = useMediaSelector((state) => state.mediaMuted ?? false);
+ const mediaVolumeLevel = useMediaSelector(
+ (state) => state.mediaVolumeLevel ?? "high",
+ );
+
+ const sliderId = React.useId();
+ const volumeTriggerId = React.useId();
+
+ const isDisabled = disabled || context.disabled;
+
+ const onMute = React.useCallback(() => {
+ dispatch({
+ type: mediaMuted
+ ? MediaActionTypes.MEDIA_UNMUTE_REQUEST
+ : MediaActionTypes.MEDIA_MUTE_REQUEST,
+ });
+ }, [dispatch, mediaMuted]);
+
+ const onVolumeChange = React.useCallback(
+ (value: number[]) => {
+ const volume = value[0] ?? 0;
+
+ if (!store.getState().dragging) {
+ store.setState("dragging", true);
+ }
+
+ dispatch({
+ type: MediaActionTypes.MEDIA_VOLUME_REQUEST,
+ detail: volume,
+ });
+ },
+ [dispatch, store.getState, store.setState],
+ );
+
+ const onVolumeCommit = React.useCallback(
+ (value: number[]) => {
+ const volume = value[0] ?? 0;
+
+ if (store.getState().dragging) {
+ store.setState("dragging", false);
+ }
+
+ dispatch({
+ type: MediaActionTypes.MEDIA_VOLUME_REQUEST,
+ detail: volume,
+ });
+ },
+ [dispatch, store],
+ );
+
+ const effectiveVolume = mediaMuted ? 0 : mediaVolume;
+
+ return (
+ <div
+ data-disabled={isDisabled ? "" : undefined}
+ data-slot="media-player-volume-container"
+ className={cn(
+ "group flex items-center",
+ expandable
+ ? "gap-0 group-focus-within:gap-2 group-hover:gap-1.5"
+ : "gap-1.5",
+ className,
+ )}
+ >
+ <MediaPlayerTooltip tooltip="Volume" shortcut="M">
+ <PlayerButton
+ id={volumeTriggerId}
+ type="button"
+ aria-controls={`${context.mediaId} ${sliderId}`}
+ aria-label={mediaMuted ? "Unmute" : "Mute"}
+ aria-pressed={mediaMuted}
+ data-slot="media-player-volume-trigger"
+ data-state={mediaMuted ? "on" : "off"}
+ variant="ghost"
+ size="icon"
+ className="size-8"
+ disabled={isDisabled}
+ onClick={onMute}
+ >
+ {mediaVolumeLevel === "off" || mediaMuted ? (
+ <VolumeXIcon />
+ ) : mediaVolumeLevel === "high" ? (
+ <Volume2Icon />
+ ) : (
+ <Volume1Icon />
+ )}
+ </PlayerButton>
+ </MediaPlayerTooltip>
+ <SliderPrimitive.Root
+ id={sliderId}
+ aria-controls={context.mediaId}
+ aria-valuetext={`${Math.round(effectiveVolume * 100)}% volume`}
+ data-slider=""
+ data-slot="media-player-volume"
+ {...volumeProps}
+ min={0}
+ max={1}
+ step={0.1}
+ className={cn(
+ "flex relative items-center select-none touch-none",
+ expandable
+ ? "w-0 opacity-0 transition-[width,opacity] duration-200 ease-in-out group-focus-within:w-16 group-focus-within:opacity-100 group-hover:w-16 group-hover:opacity-100" : "w-16",
+ className,
+ )}
+ disabled={isDisabled}
+ value={[effectiveVolume]}
+ onValueChange={onVolumeChange}
+ onValueCommit={onVolumeCommit}
+ >
+ <SliderPrimitive.Track className="overflow-hidden relative w-full h-1 rounded-full grow bg-zinc-500">
+ <SliderPrimitive.Range className="absolute h-full bg-white will-change-[width]" />
+ </SliderPrimitive.Track>
+ <SliderPrimitive.Thumb className="block size-2.5 shrink-0 rounded-full bg-white shadow-sm ring-ring/50 transition-[color,box-shadow] will-change-transform hover:ring-4 focus-visible:outline-hidden focus-visible:ring-4 disabled:pointer-events-none disabled:opacity-50" />
+ </SliderPrimitive.Root>
+ </div>
+ );
+}
+
+interface MediaPlayerTimeProps extends React.ComponentProps<"div"> {
+ variant?: "progress" | "remaining" | "duration";
+ asChild?: boolean;
+}
+
+function MediaPlayerTime(props: MediaPlayerTimeProps) {
+ const { variant = "progress", asChild, className, ...timeProps } = props;
+
+ const context = useMediaPlayerContext("MediaPlayerTime");
+ const mediaCurrentTime = useMediaSelector(
+ (state) => state.mediaCurrentTime ?? 0,
+ );
+ const [, seekableEnd = 0] = useMediaSelector(
+ (state) => state.mediaSeekable ?? [0, 0],
+ );
+
+ const times = React.useMemo(() => {
+ if (variant === "remaining") {
+ return {
+ remaining: timeUtils.formatTime(
+ seekableEnd - mediaCurrentTime,
+ seekableEnd,
+ ),
+ };
+ }
+
+ if (variant === "duration") {
+ return {
+ duration: timeUtils.formatTime(seekableEnd, seekableEnd),
+ };
+ }
+
+ return {
+ current: timeUtils.formatTime(mediaCurrentTime, seekableEnd),
+ duration: timeUtils.formatTime(seekableEnd, seekableEnd),
+ };
+ }, [variant, mediaCurrentTime, seekableEnd]);
+
+ const TimePrimitive = asChild ? Slot : "div";
+
+ if (variant === "remaining" || variant === "duration") {
+ return (
+ <TimePrimitive
+ data-slot="media-player-time"
+ data-variant={variant}
+ dir={context.dir}
+ {...timeProps}
+ className={cn("text-sm tabular-nums text-white", className)}
+ >
+ {times[variant]}
+ </TimePrimitive>
+ );
+ }
+
+ return (
+ <TimePrimitive
+ data-slot="media-player-time"
+ data-variant={variant}
+ dir={context.dir}
+ {...timeProps}
+ className={cn(
+ "flex gap-1 items-center text-sm text-white",
+ className,
+ )}
+ >
+ <span className="tabular-nums text-white">{times.current}</span>
+ <span role="separator" aria-hidden="true" tabIndex={-1}>
+ /
+ </span>
+ <span className="tabular-nums text-white">{times.duration}</span>
+ </TimePrimitive>
+ );
+}
+
+interface MediaPlayerPlaybackSpeedProps
+ extends React.ComponentProps<typeof DropdownMenuTrigger>,
+ React.ComponentProps<typeof Button>,
+ Omit<React.ComponentProps<typeof DropdownMenu>, "dir">,
+ Pick<React.ComponentProps<typeof DropdownMenuContent>, "sideOffset"> {
+ speeds?: number[];
+}
+
+function MediaPlayerPlaybackSpeed(props: MediaPlayerPlaybackSpeedProps) {
+ const {
+ open,
+ defaultOpen,
+ onOpenChange: onOpenChangeProp,
+ sideOffset = FLOATING_MENU_SIDE_OFFSET,
+ speeds = SPEEDS,
+ asChild,
+ modal = false,
+ className,
+ disabled,
+ ...playbackSpeedProps
+ } = props;
+
+ const context = useMediaPlayerContext(PLAYBACK_SPEED_NAME);
+ const store = useStoreContext(PLAYBACK_SPEED_NAME);
+ const dispatch = useMediaDispatch();
+ const mediaPlaybackRate = useMediaSelector(
+ (state) => state.mediaPlaybackRate ?? 1,
+ );
+
+ const isDisabled = disabled || context.disabled;
+
+ const onPlaybackRateChange = React.useCallback(
+ (rate: number) => {
+ dispatch({
+ type: MediaActionTypes.MEDIA_PLAYBACK_RATE_REQUEST,
+ detail: rate,
+ });
+ },
+ [dispatch],
+ );
+
+ const onOpenChange = React.useCallback(
+ (open: boolean) => {
+ store.setState("menuOpen", open);
+ onOpenChangeProp?.(open);
+ },
+ [store.setState, onOpenChangeProp],
+ );
+
+ return (
+ <DropdownMenu
+ modal={modal}
+ open={open}
+ defaultOpen={defaultOpen}
+ onOpenChange={onOpenChange}
+ >
+ <MediaPlayerTooltip tooltip="Playback speed" shortcut={["<", ">"]}>
+ <DropdownMenuTrigger asChild>
+ <PlayerButton
+ type="button"
+ aria-controls={context.mediaId}
+ disabled={isDisabled}
+ {...playbackSpeedProps}
+ variant="ghost"
+ size="icon"
+ className={cn(
+ "h-8 w-16 aria-[expanded=true]:bg-white/50",
+ className,
+ )}
+ >
+ {mediaPlaybackRate}x
+ </PlayerButton>
+ </DropdownMenuTrigger>
+ </MediaPlayerTooltip>
+ <DropdownMenuContent
+ container={context.portalContainer}
+ sideOffset={sideOffset}
+ align="center"
+ className="min-w-[var(--radix-dropdown-menu-trigger-width)] data-[side=top]:mb-3.5"
+ >
+ {speeds.map((speed) => (
+ <DropdownMenuItem
+ key={speed}
+ className="justify-between"
+ onSelect={() => onPlaybackRateChange(speed)}
+ >
+ {speed}x{mediaPlaybackRate === speed && <CheckIcon />}
+ </DropdownMenuItem>
+ ))}
+ </DropdownMenuContent>
+ </DropdownMenu>
+ );
+}
+
+interface MediaPlayerLoopProps extends React.ComponentProps<typeof Button> { }
+
+function MediaPlayerLoop(props: MediaPlayerLoopProps) {
+ const { children, className, disabled, ...loopProps } = props;
+
+ const context = useMediaPlayerContext("MediaPlayerLoop");
+ const isDisabled = disabled || context.disabled;
+
+ const [isLooping, setIsLooping] = React.useState(() => {
+ const mediaElement = context.mediaRef.current;
+ return mediaElement?.loop ?? false;
+ });
+
+ React.useEffect(() => {
+ const mediaElement = context.mediaRef.current;
+ if (!mediaElement) return;
+
+ setIsLooping(mediaElement.loop);
+
+ const checkLoop = () => setIsLooping(mediaElement.loop);
+ const observer = new MutationObserver(checkLoop);
+ observer.observe(mediaElement, {
+ attributes: true,
+ attributeFilter: ["loop"],
+ });
+
+ return () => observer.disconnect();
+ }, [context.mediaRef]);
+
+ const onLoopToggle = React.useCallback(
+ (event: React.MouseEvent<HTMLButtonElement>) => {
+ props.onClick?.(event);
+ if (event.defaultPrevented) return;
+
+ const mediaElement = context.mediaRef.current;
+ if (mediaElement) {
+ const newLoopState = !mediaElement.loop;
+ mediaElement.loop = newLoopState;
+ setIsLooping(newLoopState);
+ }
+ },
+ [context.mediaRef, props.onClick],
+ );
+
+ return (
+ <MediaPlayerTooltip
+ tooltip={isLooping ? "Disable loop" : "Enable loop"}
+ shortcut="R"
+ >
+ <PlayerButton
+ type="button"
+ aria-controls={context.mediaId}
+ aria-label={isLooping ? "Disable loop" : "Enable loop"}
+ aria-pressed={isLooping}
+ data-disabled={isDisabled ? "" : undefined}
+ data-slot="media-player-loop"
+ data-state={isLooping ? "on" : "off"}
+ disabled={isDisabled}
+ {...loopProps}
+ variant="ghost"
+ size="icon"
+ className={cn("size-8", className)}
+ onClick={onLoopToggle}
+ >
+ {children ??
+ (isLooping ? (
+ <RepeatIcon className="text-muted-foreground" />
+ ) : (
+ <RepeatIcon />
+ ))}
+ </PlayerButton>
+ </MediaPlayerTooltip>
+ );
+}
+
+interface MediaPlayerFullscreenProps
+ extends React.ComponentProps<typeof Button> { }
+
+function MediaPlayerFullscreen(props: MediaPlayerFullscreenProps) {
+ const { children, className, disabled, ...fullscreenProps } = props;
+
+ const context = useMediaPlayerContext("MediaPlayerFullscreen");
+ const dispatch = useMediaDispatch();
+ const isFullscreen = useMediaSelector(
+ (state) => state.mediaIsFullscreen ?? false,
+ );
+
+ const isDisabled = disabled || context.disabled;
+
+ const onFullscreen = React.useCallback(
+ (event: React.MouseEvent<HTMLButtonElement>) => {
+ props.onClick?.(event);
+
+ if (event.defaultPrevented) return;
+
+ dispatch({
+ type: isFullscreen
+ ? MediaActionTypes.MEDIA_EXIT_FULLSCREEN_REQUEST
+ : MediaActionTypes.MEDIA_ENTER_FULLSCREEN_REQUEST,
+ });
+ },
+ [dispatch, props.onClick, isFullscreen],
+ );
+
+ return (
+ <MediaPlayerTooltip tooltip="Fullscreen" shortcut="F">
+ <PlayerButton
+ type="button"
+ aria-label={isFullscreen ? "Exit fullscreen" : "Enter fullscreen"}
+ data-disabled={isDisabled ? "" : undefined}
+ data-slot="media-player-fullscreen"
+ data-state={isFullscreen ? "on" : "off"}
+ disabled={isDisabled}
+ {...fullscreenProps}
+ variant="ghost"
+ size="icon"
+ className={cn("size-8", className)}
+ onClick={onFullscreen}
+ >
+ {children ?? (isFullscreen ? <Minimize2Icon /> : <Maximize2Icon />)}
+ </PlayerButton>
+ </MediaPlayerTooltip>
+ );
+}
+
+interface MediaPlayerPiPProps extends React.ComponentProps<typeof Button> {
+ onPipError?: (error: unknown, state: "enter" | "exit") => void;
+}
+
+function MediaPlayerPiP(props: MediaPlayerPiPProps) {
+ const { children, className, onPipError, disabled, ...pipButtonProps } =
+ props;
+
+ const context = useMediaPlayerContext("MediaPlayerPiP");
+ const dispatch = useMediaDispatch();
+ const isPictureInPicture = useMediaSelector(
+ (state) => state.mediaIsPip ?? false,
+ );
+
+ const isDisabled = disabled || context.disabled;
+
+ const onPictureInPicture = React.useCallback(
+ (event: React.MouseEvent<HTMLButtonElement>) => {
+ props.onClick?.(event);
+
+ if (event.defaultPrevented) return;
+
+ dispatch({
+ type: isPictureInPicture
+ ? MediaActionTypes.MEDIA_EXIT_PIP_REQUEST
+ : MediaActionTypes.MEDIA_ENTER_PIP_REQUEST,
+ });
+
+ const mediaElement = context.mediaRef.current;
+
+ if (mediaElement instanceof HTMLVideoElement) {
+ if (isPictureInPicture) {
+ document.exitPictureInPicture().catch((error) => {
+ onPipError?.(error, "exit");
+ });
+ } else {
+ mediaElement.requestPictureInPicture().catch((error) => {
+ onPipError?.(error, "enter");
+ });
+ }
+ }
+ },
+ [dispatch, props.onClick, isPictureInPicture, onPipError, context.mediaRef],
+ );
+
+ return (
+ <MediaPlayerTooltip tooltip="Picture in picture" shortcut="P">
+ <PlayerButton
+ type="button"
+ aria-controls={context.mediaId}
+ aria-label={isPictureInPicture ? "Exit pip" : "Enter pip"}
+ data-disabled={isDisabled ? "" : undefined}
+ data-slot="media-player-pip"
+ data-state={isPictureInPicture ? "on" : "off"}
+ disabled={isDisabled}
+ {...pipButtonProps}
+ variant="ghost"
+ size="icon"
+ className={cn("size-8", className)}
+ onClick={onPictureInPicture}
+ >
+ {isPictureInPicture ? (
+ <PictureInPicture2Icon />
+ ) : (
+ <PictureInPictureIcon />
+ )}
+ </PlayerButton>
+ </MediaPlayerTooltip>
+ );
+}
+
+interface MediaPlayerCaptionsProps
+ extends React.ComponentProps<typeof Button> { setToggleCaptions?: (toggleCaptions: boolean) => void, toggleCaptions?: boolean }
+
+function MediaPlayerCaptions(props: MediaPlayerCaptionsProps) {
+ const { children, className, disabled, toggleCaptions, setToggleCaptions, ...captionsProps } = props;
+
+ const context = useMediaPlayerContext("MediaPlayerCaptions");
+
+ const isDisabled = disabled || context.disabled;
+ const onCaptionsToggle = React.useCallback(
+ () => {
+ setToggleCaptions?.(!toggleCaptions);
+ },
+ [toggleCaptions, setToggleCaptions],
+ );
+
+ return (
+ <MediaPlayerTooltip tooltip="Captions">
+ <PlayerButton
+ type="button"
+ aria-controls={context.mediaId}
+ aria-label={toggleCaptions ? "Disable captions" : "Enable captions"}
+ aria-pressed={toggleCaptions}
+ data-disabled={isDisabled ? "" : undefined}
+ data-slot="media-player-captions"
+ data-state={toggleCaptions ? "on" : "off"}
+ disabled={isDisabled}
+ {...captionsProps}
+ variant="ghost"
+ size="icon"
+ className={cn("size-8", className)}
+ onClick={onCaptionsToggle}
+ >
+ {children ??
+ (toggleCaptions ? <SubtitlesIcon /> : <CaptionsOffIcon />)}
+ </PlayerButton>
+ </MediaPlayerTooltip>
+ );
+}
+
+interface MediaPlayerDownloadProps
+ extends React.ComponentProps<typeof Button> { }
+
+function MediaPlayerDownload(props: MediaPlayerDownloadProps) {
+ const { children, className, disabled, ...downloadProps } = props;
+
+ const context = useMediaPlayerContext("MediaPlayerDownload");
+
+ const isDisabled = disabled || context.disabled;
+
+ const onDownload = React.useCallback(
+ (event: React.MouseEvent<HTMLButtonElement>) => {
+ props.onClick?.(event);
+
+ if (event.defaultPrevented) return;
+
+ const mediaElement = context.mediaRef.current;
+
+ if (!mediaElement || !mediaElement.currentSrc) return;
+
+ const link = document.createElement("a");
+ link.href = mediaElement.currentSrc;
+ link.download = "";
+ document.body.appendChild(link);
+ link.click();
+ document.body.removeChild(link);
+ },
+ [context.mediaRef, props.onClick],
+ );
+
+ return (
+ <MediaPlayerTooltip tooltip="Download" shortcut="D">
+ <PlayerButton
+ type="button"
+ aria-controls={context.mediaId}
+ aria-label="Download"
+ data-disabled={isDisabled ? "" : undefined}
+ data-slot="media-player-download"
+ disabled={isDisabled}
+ {...downloadProps}
+ variant="ghost"
+ size="icon"
+ className={cn("size-8", className)}
+ onClick={onDownload}
+ >
+ {children ?? <DownloadIcon />}
+ </PlayerButton>
+ </MediaPlayerTooltip>
+ );
+}
+
+interface MediaPlayerSettingsProps extends MediaPlayerPlaybackSpeedProps { }
+
+function MediaPlayerSettings(props: MediaPlayerSettingsProps) {
+ const {
+ open,
+ defaultOpen,
+ onOpenChange: onOpenChangeProp,
+ sideOffset = FLOATING_MENU_SIDE_OFFSET,
+ speeds = SPEEDS,
+ asChild,
+ modal = false,
+ className,
+ disabled,
+ ...settingsProps
+ } = props;
+
+ const context = useMediaPlayerContext(SETTINGS_NAME);
+ const store = useStoreContext(SETTINGS_NAME);
+ const dispatch = useMediaDispatch();
+
+ const mediaPlaybackRate = useMediaSelector(
+ (state) => state.mediaPlaybackRate ?? 1,
+ );
+ const mediaSubtitlesList = useMediaSelector(
+ (state) => state.mediaSubtitlesList ?? [],
+ );
+ const mediaSubtitlesShowing = useMediaSelector(
+ (state) => state.mediaSubtitlesShowing ?? [],
+ );
+ const mediaRenditionList = useMediaSelector(
+ (state) => state.mediaRenditionList ?? [],
+ );
+ const selectedRenditionId = useMediaSelector(
+ (state) => state.mediaRenditionSelected,
+ );
+
+ const isDisabled = disabled || context.disabled;
+ const isSubtitlesActive = mediaSubtitlesShowing.length > 0;
+
+ const onPlaybackRateChange = React.useCallback(
+ (rate: number) => {
+ dispatch({
+ type: MediaActionTypes.MEDIA_PLAYBACK_RATE_REQUEST,
+ detail: rate,
+ });
+ },
+ [dispatch],
+ );
+
+ const onRenditionChange = React.useCallback(
+ (renditionId: string) => {
+ dispatch({
+ type: MediaActionTypes.MEDIA_RENDITION_REQUEST,
+ detail: renditionId === "auto" ? undefined : renditionId,
+ });
+ },
+ [dispatch],
+ );
+
+ const onSubtitlesToggle = React.useCallback(() => {
+ dispatch({
+ type: MediaActionTypes.MEDIA_TOGGLE_SUBTITLES_REQUEST,
+ detail: false,
+ });
+ }, [dispatch]);
+
+ const onShowSubtitleTrack = React.useCallback(
+ (subtitleTrack: (typeof mediaSubtitlesList)[number]) => {
+ dispatch({
+ type: MediaActionTypes.MEDIA_TOGGLE_SUBTITLES_REQUEST,
+ detail: false,
+ });
+ dispatch({
+ type: MediaActionTypes.MEDIA_SHOW_SUBTITLES_REQUEST,
+ detail: subtitleTrack,
+ });
+ },
+ [dispatch],
+ );
+
+ const selectedSubtitleLabel = React.useMemo(() => {
+ if (!isSubtitlesActive) return "Off";
+ if (mediaSubtitlesShowing.length > 0) {
+ return mediaSubtitlesShowing[0]?.label ?? "On";
+ }
+ return "Off";
+ }, [isSubtitlesActive, mediaSubtitlesShowing]);
+
+ const selectedRenditionLabel = React.useMemo(() => {
+ if (!selectedRenditionId) return "Auto";
+
+ const currentRendition = mediaRenditionList?.find(
+ (rendition) => rendition.id === selectedRenditionId,
+ );
+ if (!currentRendition) return "Auto";
+
+ if (currentRendition.height) return `${currentRendition.height}p`;
+ if (currentRendition.width) return `${currentRendition.width}p`;
+ return currentRendition.id ?? "Auto";
+ }, [selectedRenditionId, mediaRenditionList]);
+
+ const onOpenChange = React.useCallback(
+ (open: boolean) => {
+ store.setState("menuOpen", open);
+ onOpenChangeProp?.(open);
+ },
+ [store.setState, onOpenChangeProp],
+ );
+
+ return (
+ <DropdownMenu
+ modal={modal}
+ open={open}
+ defaultOpen={defaultOpen}
+ onOpenChange={onOpenChange}
+ >
+ <MediaPlayerTooltip tooltip="Settings">
+ <DropdownMenuTrigger asChild>
+ <PlayerButton
+ type="button"
+ aria-controls={context.mediaId}
+ aria-label="Settings"
+ data-disabled={isDisabled ? "" : undefined}
+ data-slot="media-player-settings"
+ disabled={isDisabled}
+ {...settingsProps}
+ variant="ghost"
+ size="icon"
+ className={cn(
+ "size-8 aria-[expanded=true]:bg-white/50",
+ className,
+ )}
+ >
+ <SettingsIcon />
+ </PlayerButton>
+ </DropdownMenuTrigger>
+ </MediaPlayerTooltip>
+ <DropdownMenuContent
+ align="end"
+ side="top"
+ sideOffset={sideOffset}
+ container={context.portalContainer}
+ className="w-56 data-[side=top]:mb-3.5"
+ >
+ <DropdownMenuLabel className="sr-only">Settings</DropdownMenuLabel>
+ <DropdownMenuSub>
+ <DropdownMenuSubTrigger>
+ <span className="flex-1">Speed</span>
+ <Badge variant="outline" className="rounded-sm">
+ {mediaPlaybackRate}x
+ </Badge>
+ </DropdownMenuSubTrigger>
+ <DropdownMenuSubContent>
+ {speeds.map((speed) => (
+ <DropdownMenuItem
+ key={speed}
+ className="justify-between"
+ onSelect={() => onPlaybackRateChange(speed)}
+ >
+ {speed}x{mediaPlaybackRate === speed && <CheckIcon />}
+ </DropdownMenuItem>
+ ))}
+ </DropdownMenuSubContent>
+ </DropdownMenuSub>
+ {context.isVideo && mediaRenditionList.length > 0 && (
+ <DropdownMenuSub>
+ <DropdownMenuSubTrigger>
+ <span className="flex-1">Quality</span>
+ <Badge variant="outline" className="rounded-sm">
+ {selectedRenditionLabel}
+ </Badge>
+ </DropdownMenuSubTrigger>
+ <DropdownMenuSubContent>
+ <DropdownMenuItem
+ className="justify-between"
+ onSelect={() => onRenditionChange("auto")}
+ >
+ Auto
+ {!selectedRenditionId && <CheckIcon />}
+ </DropdownMenuItem>
+ {mediaRenditionList
+ .slice()
+ .sort((a, b) => {
+ const aHeight = a.height ?? 0;
+ const bHeight = b.height ?? 0;
+ return bHeight - aHeight;
+ })
+ .map((rendition) => {
+ const label = rendition.height
+ ? `${rendition.height}p`
+ : rendition.width
+ ? `${rendition.width}p`
+ : (rendition.id ?? "Unknown");
+
+ const selected = rendition.id === selectedRenditionId;
+
+ return (
+ <DropdownMenuItem
+ key={rendition.id}
+ className="justify-between"
+ onSelect={() => onRenditionChange(rendition.id ?? "")}
+ >
+ {label}
+ {selected && <CheckIcon />}
+ </DropdownMenuItem>
+ );
+ })}
+ </DropdownMenuSubContent>
+ </DropdownMenuSub>
+ )}
+ </DropdownMenuContent>
+ </DropdownMenu>
+ );
+}
+
+interface MediaPlayerPortalProps {
+ container?: Element | DocumentFragment | null;
+ children?: React.ReactNode;
+}
+
+function MediaPlayerPortal(props: MediaPlayerPortalProps) {
+ const { container: containerProp, children } = props;
+
+ const context = useMediaPlayerContext("MediaPlayerPortal");
+ const container = containerProp ?? context.portalContainer;
+
+ if (!container) return null;
+
+ return ReactDOM.createPortal(children, container);
+}
+
+interface MediaPlayerTooltipProps
+ extends React.ComponentProps<typeof Tooltip>,
+ Pick<React.ComponentProps<typeof TooltipContent>, "sideOffset"> {
+ tooltip?: string;
+ shortcut?: string | string[];
+}
+
+function MediaPlayerTooltip(props: MediaPlayerTooltipProps) {
+ const {
+ tooltip,
+ shortcut,
+ delayDuration,
+ sideOffset,
+ children,
+ ...tooltipProps
+ } = props;
+
+ const context = useMediaPlayerContext("MediaPlayerTooltip");
+ const tooltipDelayDuration = delayDuration ?? context.tooltipDelayDuration;
+ const tooltipSideOffset = sideOffset ?? context.tooltipSideOffset;
+
+ if ((!tooltip && !shortcut) || context.withoutTooltip) return <>{children}</>;
+
+ return (
+ <Tooltip {...tooltipProps} delayDuration={tooltipDelayDuration}>
+ <TooltipTrigger
+ className="text-foreground focus-visible:ring-ring/50"
+ asChild
+ >
+ {children}
+ </TooltipTrigger>
+ <TooltipContent
+ container={context.portalContainer}
+ sideOffset={tooltipSideOffset}
+ className="flex items-center gap-2 border bg-white px-2 py-1 font-medium text-black data-[side=top]:mb-3.5 [&>span]:hidden"
+ >
+ <p>{tooltip}</p>
+ {Array.isArray(shortcut) ? (
+ <div className="flex gap-1 items-center">
+ {shortcut.map((shortcutKey) => (
+ <kbd
+ key={shortcutKey}
+ className="select-none rounded border bg-white px-1.5 py-0.5 font-mono text-[11.2px] text-black shadow-xs"
+ >
+ <abbr title={shortcutKey} className="no-underline">
+ {shortcutKey}
+ </abbr>
+ </kbd>
+ ))}
+ </div>
+ ) : (
+ shortcut && (
+ <kbd
+ key={shortcut}
+ className="select-none rounded border bg-white px-1.5 py-px font-mono text-[11.2px] text-foreground shadow-xs"
+ >
+ <abbr title={shortcut} className="no-underline">
+ {shortcut}
+ </abbr>
+ </kbd>
+ )
+ )}
+ </TooltipContent>
+ </Tooltip>
+ );
+}
+
+export {
+ MediaPlayerRoot as MediaPlayer,
+ MediaPlayerVideo,
+ MediaPlayerAudio,
+ MediaPlayerControls,
+ MediaPlayerControlsOverlay,
+ MediaPlayerLoading,
+ MediaPlayerError,
+ MediaPlayerVolumeIndicator,
+ MediaPlayerPlay,
+ MediaPlayerSeekBackward,
+ MediaPlayerSeekForward,
+ MediaPlayerSeek,
+ MediaPlayerVolume,
+ MediaPlayerTime,
+ MediaPlayerPlaybackSpeed,
+ MediaPlayerLoop,
+ MediaPlayerFullscreen,
+ MediaPlayerPiP,
+ MediaPlayerCaptions,
+ MediaPlayerDownload,
+ MediaPlayerSettings,
+ MediaPlayerPortal,
+ MediaPlayerTooltip,
+ //
+ MediaPlayerRoot as Root,
+ MediaPlayerVideo as Video,
+ MediaPlayerAudio as Audio,
+ MediaPlayerControls as Controls,
+ MediaPlayerControlsOverlay as ControlsOverlay,
+ MediaPlayerLoading as Loading,
+ MediaPlayerVolumeIndicator as VolumeIndicator,
+ MediaPlayerError as Error,
+ MediaPlayerPlay as Play,
+ MediaPlayerSeekBackward as SeekBackward,
+ MediaPlayerSeekForward as SeekForward,
+ MediaPlayerSeek as Seek,
+ MediaPlayerVolume as Volume,
+ MediaPlayerTime as Time,
+ MediaPlayerPlaybackSpeed as PlaybackSpeed,
+ MediaPlayerLoop as Loop,
+ MediaPlayerFullscreen as Fullscreen,
+ MediaPlayerPiP as PiP,
+ MediaPlayerCaptions as Captions,
+ MediaPlayerDownload as Download,
+ MediaPlayerSettings as Settings,
+ MediaPlayerPortal as Portal,
+ MediaPlayerTooltip as Tooltip,
+ //
+ useMediaSelector as useMediaPlayer,
+ useStoreSelector as useMediaPlayerStore,
+};
diff --git a/apps/web/app/s/[videoId]/_components/video/select.tsx b/apps/web/app/s/[videoId]/_components/video/select.tsx
new file mode 100644
index 000000000..0acf14445
--- /dev/null
+++ b/apps/web/app/s/[videoId]/_components/video/select.tsx
@@ -0,0 +1,159 @@
+"use client"
+
+import * as React from "react"
+import * as SelectPrimitive from "@radix-ui/react-select"
+import { Check, ChevronDown, ChevronUp } from "lucide-react"
+
+import { cn } from "@/app/lib/utils"
+
+const Select = SelectPrimitive.Root
+
+const SelectGroup = SelectPrimitive.Group
+
+const SelectValue = SelectPrimitive.Value
+
+const SelectTrigger = React.forwardRef<
+ React.ElementRef<typeof SelectPrimitive.Trigger>,
+ React.ComponentPropsWithoutRef<typeof SelectPrimitive.Trigger>
+>(({ className, children, ...props }, ref) => (
+ <SelectPrimitive.Trigger
+ ref={ref}
+ className={cn(
+ "flex h-9 w-full items-center justify-between whitespace-nowrap rounded-md border border-input bg-transparent px-3 py-2 text-sm shadow-sm ring-offset-background data-[placeholder]:text-muted-foreground focus:outline-none focus:ring-1 focus:ring-ring disabled:cursor-not-allowed disabled:opacity-50 [&>span]:line-clamp-1",
+ className
+ )}
+ {...props}
+ >
+ {children}
+ <SelectPrimitive.Icon asChild>
+ <ChevronDown className="h-4 w-4 opacity-50" />
+ </SelectPrimitive.Icon>
+ </SelectPrimitive.Trigger>
+))
+SelectTrigger.displayName = SelectPrimitive.Trigger.displayName
+
+const SelectScrollUpButton = React.forwardRef<
+ React.ElementRef<typeof SelectPrimitive.ScrollUpButton>,
+ React.ComponentPropsWithoutRef<typeof SelectPrimitive.ScrollUpButton>
+>(({ className, ...props }, ref) => (
+ <SelectPrimitive.ScrollUpButton
+ ref={ref}
+ className={cn(
+ "flex cursor-default items-center justify-center py-1",
+ className
+ )}
+ {...props}
+ >
+ <ChevronUp className="h-4 w-4" />
+ </SelectPrimitive.ScrollUpButton>
+))
+SelectScrollUpButton.displayName = SelectPrimitive.ScrollUpButton.displayName
+
+const SelectScrollDownButton = React.forwardRef<
+ React.ElementRef<typeof SelectPrimitive.ScrollDownButton>,
+ React.ComponentPropsWithoutRef<typeof SelectPrimitive.ScrollDownButton>
+>(({ className, ...props }, ref) => (
+ <SelectPrimitive.ScrollDownButton
+ ref={ref}
+ className={cn(
+ "flex cursor-default items-center justify-center py-1",
+ className
+ )}
+ {...props}
+ >
+ <ChevronDown className="h-4 w-4" />
+ </SelectPrimitive.ScrollDownButton>
+))
+SelectScrollDownButton.displayName =
+ SelectPrimitive.ScrollDownButton.displayName
+
+const SelectContent = React.forwardRef<
+ React.ElementRef<typeof SelectPrimitive.Content>,
+ React.ComponentPropsWithoutRef<typeof SelectPrimitive.Content>
+>(({ className, children, position = "popper", ...props }, ref) => (
+ <SelectPrimitive.Portal>
+ <SelectPrimitive.Content
+ ref={ref}
+ className={cn(
+ "relative z-50 max-h-[--radix-select-content-available-height] min-w-[8rem] overflow-y-auto overflow-x-hidden rounded-md border bg-popover text-popover-foreground shadow-md data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0 data-[state=closed]:zoom-out-95 data-[state=open]:zoom-in-95 data-[side=bottom]:slide-in-from-top-2 data-[side=left]:slide-in-from-right-2 data-[side=right]:slide-in-from-left-2 data-[side=top]:slide-in-from-bottom-2 origin-[--radix-select-content-transform-origin]",
+ position === "popper" &&
+ "data-[side=bottom]:translate-y-1 data-[side=left]:-translate-x-1 data-[side=right]:translate-x-1 data-[side=top]:-translate-y-1",
+ className
+ )}
+ position={position}
+ {...props}
+ >
+ <SelectScrollUpButton />
+ <SelectPrimitive.Viewport
+ className={cn(
+ "p-1",
+ position === "popper" &&
+ "h-[var(--radix-select-trigger-height)] w-full min-w-[var(--radix-select-trigger-width)]"
+ )}
+ >
+ {children}
+ </SelectPrimitive.Viewport>
+ <SelectScrollDownButton />
+ </SelectPrimitive.Content>
+ </SelectPrimitive.Portal>
+))
+SelectContent.displayName = SelectPrimitive.Content.displayName
+
+const SelectLabel = React.forwardRef<
+ React.ElementRef<typeof SelectPrimitive.Label>,
+ React.ComponentPropsWithoutRef<typeof SelectPrimitive.Label>
+>(({ className, ...props }, ref) => (
+ <SelectPrimitive.Label
+ ref={ref}
+ className={cn("px-2 py-1.5 text-sm font-semibold", className)}
+ {...props}
+ />
+))
+SelectLabel.displayName = SelectPrimitive.Label.displayName
+
+const SelectItem = React.forwardRef<
+ React.ElementRef<typeof SelectPrimitive.Item>,
+ React.ComponentPropsWithoutRef<typeof SelectPrimitive.Item>
+>(({ className, children, ...props }, ref) => (
+ <SelectPrimitive.Item
+ ref={ref}
+ className={cn(
+ "relative flex w-full cursor-default select-none items-center rounded-sm py-1.5 pl-2 pr-8 text-sm outline-none focus:bg-accent focus:text-accent-foreground data-[disabled]:pointer-events-none data-[disabled]:opacity-50",
+ className
+ )}
+ {...props}
+ >
+ <span className="absolute right-2 flex h-3.5 w-3.5 items-center justify-center">
+ <SelectPrimitive.ItemIndicator>
+ <Check className="h-4 w-4" />
+ </SelectPrimitive.ItemIndicator>
+ </span>
+ <SelectPrimitive.ItemText>{children}</SelectPrimitive.ItemText>
+ </SelectPrimitive.Item>
+))
+SelectItem.displayName = SelectPrimitive.Item.displayName
+
+const SelectSeparator = React.forwardRef<
+ React.ElementRef<typeof SelectPrimitive.Separator>,
+ React.ComponentPropsWithoutRef<typeof SelectPrimitive.Separator>
+>(({ className, ...props }, ref) => (
+ <SelectPrimitive.Separator
+ ref={ref}
+ className={cn("-mx-1 my-1 h-px bg-muted", className)}
+ {...props}
+ />
+))
+SelectSeparator.displayName = SelectPrimitive.Separator.displayName
+
+export {
+ Select,
+ SelectGroup,
+ SelectValue,
+ SelectTrigger,
+ SelectContent,
+ SelectLabel,
+ SelectItem,
+ SelectSeparator,
+ SelectScrollUpButton,
+ SelectScrollDownButton,
+}
diff --git a/apps/web/app/s/[videoId]/_components/video/slider.tsx b/apps/web/app/s/[videoId]/_components/video/slider.tsx
new file mode 100644
index 000000000..25eb73719
--- /dev/null
+++ b/apps/web/app/s/[videoId]/_components/video/slider.tsx
@@ -0,0 +1,28 @@
+"use client"
+
+import * as React from "react"
+import * as SliderPrimitive from "@radix-ui/react-slider"
+
+import { cn } from "@/app/lib/utils"
+
+const Slider = React.forwardRef<
+ React.ElementRef<typeof SliderPrimitive.Root>,
+ React.ComponentPropsWithoutRef<typeof SliderPrimitive.Root>
+>(({ className, ...props }, ref) => (
+ <SliderPrimitive.Root
+ ref={ref}
+ className={cn(
+ "relative flex w-full touch-none select-none items-center",
+ className
+ )}
+ {...props}
+ >
+ <SliderPrimitive.Track className="relative h-1.5 w-full grow overflow-hidden rounded-full bg-primary/20">
+ <SliderPrimitive.Range className="absolute h-full bg-primary" />
+ </SliderPrimitive.Track>
+ <SliderPrimitive.Thumb className="block h-4 w-4 rounded-full border border-primary/50 bg-background shadow transition-colors focus-visible:outline-none focus-visible:ring-1 focus-visible:ring-ring disabled:pointer-events-none disabled:opacity-50" />
+ </SliderPrimitive.Root>
+))
+Slider.displayName = SliderPrimitive.Root.displayName
+
+export { Slider }
diff --git a/apps/web/app/s/[videoId]/_components/video/tooltip.tsx b/apps/web/app/s/[videoId]/_components/video/tooltip.tsx
new file mode 100644
index 000000000..37c1afa2e
--- /dev/null
+++ b/apps/web/app/s/[videoId]/_components/video/tooltip.tsx
@@ -0,0 +1,34 @@
+"use client"
+
+import * as React from "react"
+import * as TooltipPrimitive from "@radix-ui/react-tooltip"
+
+import { cn } from "@/app/lib/utils"
+
+const TooltipProvider = TooltipPrimitive.Provider
+
+const Tooltip = TooltipPrimitive.Root
+
+const TooltipTrigger = TooltipPrimitive.Trigger
+
+const TooltipContent = React.forwardRef<
+ React.ElementRef<typeof TooltipPrimitive.Content>,
+ React.ComponentPropsWithoutRef<typeof TooltipPrimitive.Content> & {
+ container?: TooltipPrimitive.TooltipPortalProps["container"]
+ }
+>(({ className, container, sideOffset = 4, ...props }, ref) => (
+ <TooltipPrimitive.Portal container={container}>
+ <TooltipPrimitive.Content
+ ref={ref}
+ sideOffset={sideOffset}
+ className={cn(
+ "z-50 overflow-hidden rounded-md bg-primary px-3 py-1.5 text-xs text-primary-foreground animate-in fade-in-0 zoom-in-95 data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=closed]:zoom-out-95 data-[side=bottom]:slide-in-from-top-2 data-[side=left]:slide-in-from-right-2 data-[side=right]:slide-in-from-left-2 data-[side=top]:slide-in-from-bottom-2 origin-[--radix-tooltip-content-transform-origin]",
+ className
+ )}
+ {...props}
+ />
+ </TooltipPrimitive.Portal>
+))
+TooltipContent.displayName = TooltipPrimitive.Content.displayName
+
+export { Tooltip, TooltipTrigger, TooltipContent, TooltipProvider }
diff --git a/apps/web/components.json b/apps/web/components.json
new file mode 100644
index 000000000..73320a89c
--- /dev/null
+++ b/apps/web/components.json
@@ -0,0 +1,21 @@
+{
+ "$schema": "https://ui.shadcn.com/schema.json",
+ "style": "new-york",
+ "rsc": true,
+ "tsx": true,
+ "tailwind": {
+ "config": "tailwind.config.js",
+ "css": "app/globals.css",
+ "baseColor": "gray",
+ "cssVariables": true,
+ "prefix": ""
+ },
+ "aliases": {
+ "components": "@/app/components",
+ "utils": "@/app/lib/utils",
+ "ui": "@/app/components/ui",
+ "lib": "@/app/lib",
+ "hooks": "@/app/hooks"
+ },
+ "iconLibrary": "lucide"
+}
\ No newline at end of file
diff --git a/apps/web/components/pages/HomePage/RecordingModes.tsx b/apps/web/components/pages/HomePage/RecordingModes.tsx
index d646d3983..a96b19a93 100644
--- a/apps/web/components/pages/HomePage/RecordingModes.tsx
+++ b/apps/web/components/pages/HomePage/RecordingModes.tsx
@@ -1,3 +1,5 @@
+"use client";
+
import {
getDownloadButtonText,
getDownloadUrl,
diff --git a/apps/web/package.json b/apps/web/package.json
index 6b6ef71b3..80f805ab4 100644
--- a/apps/web/package.json
+++ b/apps/web/package.json
@@ -37,7 +37,11 @@
"@number-flow/react": "^0.5.9",
"@octokit/rest": "^20.0.2",
"@radix-ui/colors": "^3.0.0",
- "@radix-ui/react-tooltip": "^1.2.0",
+ "@radix-ui/react-dropdown-menu": "^2.0.6",
+ "@radix-ui/react-select": "^2.2.5",
+ "@radix-ui/react-slider": "^1.3.5",
+ "@radix-ui/react-slot": "^1.0.2",
+ "@radix-ui/react-tooltip": "^1.2.6",
"@react-email/components": "^0.1.0",
"@react-email/render": "1.1.2",
"@remotion/media-parser": "^4.0.291",
@@ -49,12 +53,11 @@
"@tanstack/react-store": "^0.5.5",
"@tanstack/store": "^0.5.5",
"@ts-rest/core": "^3.52.1",
- "@types/js-cookie": "^3.0.6",
"@uidotdev/usehooks": "^2.4.1",
"@virtual-grid/react": "^2.0.3",
"@workos-inc/node": "^7.34.0",
"aws-sdk": "^2.1530.0",
- "class-variance-authority": "^0.7.0",
+ "class-variance-authority": "^0.7.1",
"clsx": "^2.1.1",
"cookies-next": "^4.1.0",
"date-fns": "^4.1.0",
@@ -72,7 +75,8 @@
"jsdom": "^26.1.0",
"jszip": "^3.10.1",
"lodash": "^4.17.21",
- "lucide-react": "^0.294.0",
+ "lucide-react": "^0.525.0",
+ "media-chrome": "^4.12.0",
"moment": "^2.30.1",
"motion": "^12.18.1",
"next": "14.2.3",
@@ -88,7 +92,6 @@
"react-hls-player": "^3.0.7",
"react-hook-form": "^7.49.2",
"react-hot-toast": "^2.4.1",
- "react-player": "^2.14.1",
"react-rnd": "^10.4.1",
"react-scroll-parallax": "^3.4.5",
"react-tooltip": "^5.26.3",
@@ -97,14 +100,15 @@
"sonner": "^2.0.3",
"subtitles-parser-vtt": "^0.1.0",
"tailwind-merge": "^2.6.0",
- "tailwindcss-animate": "^1.0.6",
+ "tailwindcss-animate": "^1.0.7",
"uuid": "^9.0.1",
- "video.js": "^8.17.3",
+ "video.js": "^8.23.3",
"zod": "^3.24.4"
},
"devDependencies": {
"@smithy/types": "^4.3.1",
"@types/file-saver": "^2.0.7",
+ "@types/js-cookie": "^3.0.6",
"@types/jsdom": "^21.1.7",
"@types/lodash": "^4.17.5",
"@types/node": "^20.11.5",
@@ -112,6 +116,7 @@
"@types/react-dom": "^18",
"@types/react-responsive-masonry": "^2.6.0",
"@types/uuid": "^9.0.8",
+ "@types/video.js": "^7.3.58",
"autoprefixer": "^10.4.14",
"eslint": "^9.30.1",
"eslint-config-next": "14.1.0",
diff --git a/packages/ui/src/components/Button.tsx b/packages/ui/src/components/Button.tsx
index 1d12ceb48..7d69fd496 100644
--- a/packages/ui/src/components/Button.tsx
+++ b/packages/ui/src/components/Button.tsx
@@ -16,7 +16,9 @@ const buttonVariants = cva(
blue: "bg-blue-600 text-white hover:bg-blue-700 disabled:bg-blue-200 disabled:text-gray-8",
destructive:
"bg-red-500 text-white hover:bg-red-600 disabled:bg-red-200",
+ outline: "border border-gray-8 text-gray-12 hover:bg-gray-2 disabled:bg-gray-8",
white: "bg-gray-1 text-gray-12 hover:bg-gray-2 disabled:bg-gray-8",
+ ghost: "hover:bg-white/20 hover:text-white",
gray: "bg-gray-4 text-gray-12 hover:bg-gray-5 disabled:bg-gray-6 disabled:text-gray-9",
dark: "bg-gray-12 text-gray-1 disabled:cursor-not-allowed hover:bg-gray-11 disabled:text-gray-10 disabled:bg-gray-7 disabled:border-gray-8",
darkgradient:
@@ -29,6 +31,7 @@ const buttonVariants = cva(
sm: "text-sm h-[40px]",
md: "text-sm h-[44px]",
lg: "text-md h-[48px]",
+ icon: "h-9 w-9",
},
},
}
diff --git a/packages/ui/src/components/Cmdk.tsx b/packages/ui/src/components/Cmdk.tsx
index ba2ad0f8c..a1665a270 100644
--- a/packages/ui/src/components/Cmdk.tsx
+++ b/packages/ui/src/components/Cmdk.tsx
@@ -15,7 +15,7 @@ const Command = React.forwardRef<
<CommandPrimitive
ref={ref}
className={classNames(
- "flex overflow-hidden flex-col w-full h-full rounded-md bg-popover text-popover-foreground",
+ "flex overflow-hidden flex-col w-full h-full rounded-md",
className
)}
{...props}
@@ -23,7 +23,7 @@ const Command = React.forwardRef<
));
Command.displayName = CommandPrimitive.displayName;
-interface CommandDialogProps extends DialogProps {}
+interface CommandDialogProps extends DialogProps { }
const CommandDialog = ({ children, ...props }: CommandDialogProps) => {
return (
@@ -123,7 +123,7 @@ const CommandItem = React.forwardRef<
<CommandPrimitive.Item
ref={ref}
className={classNames(
- "relative flex cursor-pointer text-gray-8 select-none items-center rounded-sm px-2 py-2 text-[0.875rem] outline-none aria-selected:bg-accent aria-selected:text-accent-foreground data-[disabled]:pointer-events-none data-[disabled]:opacity-50",
+ "relative flex cursor-pointer text-gray-8 select-none items-center rounded-sm px-2 py-2 text-[0.875rem] outline-none data-[disabled]:pointer-events-none data-[disabled]:opacity-50",
className
)}
{...props}
diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml
index 146616c74..9f55b7e8e 100644
--- a/pnpm-lock.yaml
+++ b/pnpm-lock.yaml
@@ -480,8 +480,20 @@ importers:
'@radix-ui/colors':
specifier: ^3.0.0
version: 3.0.0
+ '@radix-ui/react-dropdown-menu':
+ specifier: ^2.0.6
+ '@radix-ui/react-select':
+ specifier: ^2.2.5
+ '@radix-ui/react-slider':
+ specifier: ^1.3.5
+ '@radix-ui/react-slot':
+ specifier: ^1.0.2
+ version: 1.2.3(@types/[email protected])([email protected])
'@radix-ui/react-tooltip':
- specifier: ^1.2.0
+ specifier: ^1.2.6
'@react-email/components':
specifier: ^0.1.0
@@ -516,9 +528,6 @@ importers:
'@ts-rest/core':
specifier: ^3.52.1
version: 3.52.1(@types/[email protected])([email protected])
- '@types/js-cookie':
- specifier: ^3.0.6
- version: 3.0.6
'@uidotdev/usehooks':
specifier: ^2.4.1
@@ -532,7 +541,7 @@ importers:
specifier: ^2.1530.0
version: 2.1692.0
class-variance-authority:
- specifier: ^0.7.0
+ specifier: ^0.7.1
version: 0.7.1
clsx:
specifier: ^2.1.1
@@ -586,8 +595,11 @@ importers:
specifier: ^4.17.21
version: 4.17.21
lucide-react:
- specifier: ^0.294.0
- version: 0.294.0([email protected])
+ specifier: ^0.525.0
+ version: 0.525.0([email protected])
+ media-chrome:
+ specifier: ^4.12.0
+ version: 4.12.0([email protected])
moment:
specifier: ^2.30.1
version: 2.30.1
@@ -633,9 +645,6 @@ importers:
react-hot-toast:
specifier: ^2.4.1
- react-player:
- specifier: ^2.14.1
- version: 2.16.0([email protected])
react-rnd:
specifier: ^10.4.1
@@ -661,14 +670,14 @@ importers:
specifier: ^2.6.0
version: 2.6.0
tailwindcss-animate:
- specifier: ^1.0.6
+ specifier: ^1.0.7
uuid:
specifier: ^9.0.1
version: 9.0.1
video.js:
- specifier: ^8.17.3
- version: 8.22.0
+ specifier: ^8.23.3
+ version: 8.23.3
zod:
specifier: ^3.24.4
version: 3.25.20
@@ -679,6 +688,9 @@ importers:
'@types/file-saver':
specifier: ^2.0.7
version: 2.0.7
+ '@types/js-cookie':
+ specifier: ^3.0.6
+ version: 3.0.6
'@types/jsdom':
specifier: ^21.1.7
version: 21.1.7
@@ -700,6 +712,9 @@ importers:
'@types/uuid':
specifier: ^9.0.8
version: 9.0.8
+ '@types/video.js':
+ specifier: ^7.3.58
+ version: 7.3.58
autoprefixer:
specifier: ^10.4.14
version: 10.4.21([email protected])
@@ -809,7 +824,7 @@ importers:
version: 0.43.1(@cloudflare/[email protected])(@opentelemetry/[email protected])(@planetscale/[email protected])([email protected])
dub:
specifier: ^0.64.0
- version: 0.64.0(@modelcontextprotocol/[email protected])([email protected])
+ version: 0.64.0(@modelcontextprotocol/[email protected])([email protected])
nanoid:
specifier: ^5.0.4
version: 5.1.5
@@ -4463,6 +4478,19 @@ packages:
'@types/react-dom':
optional: true
+ '@radix-ui/[email protected]':
+ resolution: {integrity: sha512-rkfe2pU2NBAYfGaxa3Mqosi7VZEWX5CxKaanRv0vZd4Zhl9fvQrg0VM93dv3xGLGfrHuoTRF3JXH8nb9g+B3fw==}
+ peerDependencies:
+ '@types/react': '*'
+ '@types/react-dom': '*'
+ react: ^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc
+ react-dom: ^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc
+ peerDependenciesMeta:
+ '@types/react':
+ optional: true
+ '@types/react-dom':
+ optional: true
+
'@radix-ui/[email protected]':
resolution: {integrity: sha512-3mrKauI/tWXo1Ll+gN5dHcxDPdm/Df1ufcDLCecn+pnCIVcdWE7CujXo8QaXOWRJyZyQWWbpB8eFwHzWXlv5mQ==}
peerDependencies:
@@ -6144,6 +6172,9 @@ packages:
resolution: {integrity: sha512-jg+97EGIcY9AGHJJRaaPVgetKDsrTgbRjQ5Msgjh/DQKEFl0DtyRr/VCOyD1T2R1MNeWPK/u7JoGhlDZnKBAfA==}
+ '@types/[email protected]':
+ resolution: {integrity: sha512-1CQjuSrgbv1/dhmcfQ83eVyYbvGyqhTvb2Opxr0QCV+iJ4J6/J+XWQ3Om59WiwCd1MN3rDUHasx5XRrpUtewYQ==}
+
resolution: {integrity: sha512-I4q9QU9MQv4oEOz4tAHJtNz1cwuLxn2F3xcc2iV5WdqLPpUnj30aUuxt1mAxYTG+oe8CZMV/+6rU4S4gRDzqtQ==}
@@ -7060,6 +7091,11 @@ packages:
peerDependencies:
react: '>=17.0.0'
+ resolution: {integrity: sha512-84SEDLNHaAjykzlkqgKRq95hA3qnxrsTrwh4hTgBq6tfpINqajxz4bkz9q4orhUfpqDPQRgdCzYTF3bHcvTIlQ==}
+ peerDependencies:
+ react: '>=17.0.0'
+
resolution: {integrity: sha512-mCuXncKXk5iCLhfhwTc0izo0gtEmpz5CtG2y8GiOINBlMVS6v8TMRc5TaLWKS6692m9+dVVfzgeVxR5UxWHTYw==}
engines: {node: '>=12'}
@@ -9776,9 +9812,6 @@ packages:
resolution: {integrity: sha512-I8oW2+QL5KJo8zXNWX046M134WchxsXC7SawLPvRQpogCbkyQIaFxPE89A2HiwR7vAK2Dm2ERBAmyjTYGYEpBg==}
hasBin: true
- resolution: {integrity: sha512-kPEjMFtZvwL9TaZo0uZ2ml+Ye9HUMmPwbYRJ324qF9tqMejwykJ5ggTyvzmrbBeapCAbk98BSbTeovHEEP1uCA==}
-
resolution: {integrity: sha512-9rrA30MRRP3gBD3HTGnC6cDFpaE1kVDWxWgqWJUN0RvDNAo+Nz/9GxB+nHOH0ifbVFy0hSA1V6vFDvnx54lTEQ==}
engines: {node: '>=14'}
@@ -9900,6 +9933,11 @@ packages:
peerDependencies:
react: ^16.5.1 || ^17.0.0 || ^18.0.0
+ resolution: {integrity: sha512-Tm1txJ2OkymCGkvwoHt33Y2JpN5xucVq1slHcgE6Lk0WjDfjgKWor5CdVER8U6DvcfMwh4M8XxmpTiyzfmfDYQ==}
+ peerDependencies:
+ react: ^16.5.1 || ^17.0.0 || ^18.0.0 || ^19.0.0
+
resolution: {integrity: sha512-tJLxrKJhO2ukZ5z0gyjY1zPh3Rh88Ej9P7jNrZiHMUXHae1yvI2imgOZtL1TO8TW6biMMKfTtAOoEJANgtWBMQ==}
engines: {node: '>=12'}
@@ -9998,6 +10036,9 @@ packages:
peerDependencies:
esbuild: 0.*
+ resolution: {integrity: sha512-leItqyy2jn1nk66KGmzeH0z6JXeVUvK95O7ouQTSVdvrTXB/8jtLEI964eXlq5oCZfyPLnPUiuosKrDEfmWDqQ==}
+
resolution: {integrity: sha512-lOdYhWVCYg0Az2VnVKPoE/eUflVrNyauHg8cLa/ibsBg4CB6RhRQBTdQsq36NuiSNSQU0B3vtmaTNFTUFT12RA==}
@@ -10016,9 +10057,6 @@ packages:
resolution: {integrity: sha512-thuTRd7F4m4dReCIy7vv4eNYnU6XI/tHMLSMMHLiortw/Y0QxqKtinG523U2aerzwYWGi606oBP4oMPy4+edag==}
engines: {node: '>= 4.0.0'}
- resolution: {integrity: sha512-zYiwtZUcYyXKo/np96AGZAckk+FWWsUdJ3cHGGmld7+AhvcWmQyGCYUh1hc4Q/pkOhb65dQR/pqCyK0cOaHz4Q==}
-
resolution: {integrity: sha512-/EuHYwAPdLtXwAwSZkh/Gutery6pD2KYd44oQLhAvQp/50mpyduZh8Q7PYHXTCJ+wuXxt7oij2LXyIJOOYFPog==}
@@ -11321,9 +11359,6 @@ packages:
engines: {node: '>=18.0.0'}
hasBin: true
- resolution: {integrity: sha512-nsO+KSNgo1SbJqJEYRE9ERzo7YtYbou/OqjSQKxV7jcKox7+usiUVZOAC+XnDOABXggQTno0Y1CpVnuWEc1boQ==}
-
resolution: {integrity: sha512-i5QWNyLmaUhV/mgnpljRJT0CBfJnylClV/bne8aiXO3ZqU0+D3U/jtTDwdXM4i5qHhyFy9lemyZ179IgadKd0Q==}
peerDependencies:
@@ -11366,11 +11401,6 @@ packages:
peerDependencies:
react: '>=16.8.0'
- resolution: {integrity: sha512-mAIPHfioD7yxO0GNYVFD1303QFtI3lyyQZLY229UEAp/a10cSW+hPcakg0Keq8uWJxT2OiT/4Gt+Lc9bD6bJmQ==}
- peerDependencies:
- react: '>=16.6.0'
-
resolution: {integrity: sha512-I42jl7L3Ze6kZaq+7zXWSunBa3b1on5yfvUW6Eo/3fFOj6dZ5Bqmcd264nJbTK/gn1HjjILAjSwnZbV4RpSaNQ==}
@@ -13033,8 +13063,8 @@ packages:
resolution: {integrity: sha512-KzIbH/9tXat2u30jf+smMwFCsno4wHVdNmzFyL+T/L3UGqqk6JKfVqOFOZEpZSHADH1k40ab6NUIXZq422ov3Q==}
- resolution: {integrity: sha512-xge2kpjsvC0zgFJ1cqt+wTqsi21+huFswlonPFh7qiplypsb4FN/D2Rz6bWdG/S9eQaPHfWHsarmJL/7D3DHoA==}
+ resolution: {integrity: sha512-Toe0VLlDZcUhiaWfcePS1OEdT3ATfktm0hk/PELfD7zUoPDHeT+cJf/wZmCy5M5eGVwtGUg25RWPCj1L/1XufA==}
resolution: {integrity: sha512-TfrXJJg1Bv4t6TOCMEVMwF/CoS8iENYsWNKip8zfhB5kTcegiFYezEA0eHAJPU64ZC8NQbxQgOwAsYU8VXbOWA==}
@@ -13531,8 +13561,8 @@ packages:
resolution: {integrity: sha512-z03fqpTMDF1G02VLKUMt6vyACE7rNWkh3gpXVHgPTw28NPtDFRGvcpTtPwn2kMKtQ0idtYJUTxchytmnqYswcw==}
- resolution: {integrity: sha512-idA2YXwpCdqUSKRCACDE6ItZD9TZzy3OZMtpfLoh6oPR47lipysRrJfjzMqFxQ3uJuUPyUeWe1r9vLH33xO/Qw==}
+ resolution: {integrity: sha512-gzUt/qt81nXsFGKIFcC3YnfEAx5NkunCfnDlvuBSSFS02bcXu4Lmea0AFIUwbLWxWPx3d9p8S5QoaujKcNQxcQ==}
resolution: {integrity: sha512-bXE4cR/kVZhKZX/RjPEflHaKVhUVl85noU3v6b8apfQEc1x4A+zBxjZ4lN8LqGd6WZ3dl98pY4o717VFmoPp+A==}
@@ -14559,7 +14589,7 @@ snapshots:
ts-pattern: 5.7.1
unified: 11.0.5
yaml: 2.8.0
- zod: 3.25.67
+ zod: 3.25.76
transitivePeerDependencies:
- '@effect-ts/otel-node'
- acorn
@@ -15929,8 +15959,8 @@ snapshots:
express-rate-limit: 7.5.0([email protected])
pkce-challenge: 4.1.0
raw-body: 3.0.0
- zod: 3.25.67
- zod-to-json-schema: 3.24.3([email protected])
+ zod: 3.25.76
+ zod-to-json-schema: 3.24.3([email protected])
transitivePeerDependencies:
- supports-color
@@ -16903,6 +16933,15 @@ snapshots:
'@types/react': 18.3.21
'@types/react-dom': 19.1.6(@types/[email protected])
+ dependencies:
+ react: 19.1.0
+ react-dom: 19.1.0([email protected])
+ optionalDependencies:
+ '@types/react': 18.3.21
+ '@types/react-dom': 18.3.7(@types/[email protected])
+
dependencies:
@@ -16912,6 +16951,18 @@ snapshots:
'@types/react': 18.3.21
'@types/react-dom': 19.1.6(@types/[email protected])
+ dependencies:
+ '@radix-ui/react-compose-refs': 1.1.2(@types/[email protected])([email protected])
+ '@radix-ui/react-context': 1.1.2(@types/[email protected])([email protected])
+ '@radix-ui/react-slot': 1.2.2(@types/[email protected])([email protected])
+ react: 19.1.0
+ react-dom: 19.1.0([email protected])
+ optionalDependencies:
+ '@types/react': 18.3.21
+ '@types/react-dom': 18.3.7(@types/[email protected])
+
dependencies:
'@radix-ui/react-compose-refs': 1.1.2(@types/[email protected])([email protected])
@@ -16924,6 +16975,18 @@ snapshots:
'@types/react': 18.3.21
'@types/react-dom': 19.1.6(@types/[email protected])
+ dependencies:
+ '@radix-ui/react-compose-refs': 1.1.2(@types/[email protected])([email protected])
+ '@radix-ui/react-context': 1.1.2(@types/[email protected])([email protected])
+ '@radix-ui/react-slot': 1.2.3(@types/[email protected])([email protected])
+ react: 19.1.0
+ react-dom: 19.1.0([email protected])
+ optionalDependencies:
+ '@types/react': 18.3.21
+ '@types/react-dom': 18.3.7(@types/[email protected])
+
dependencies:
'@radix-ui/react-compose-refs': 1.1.2(@types/[email protected])([email protected])
@@ -17019,6 +17082,19 @@ snapshots:
react: 19.1.0
react-dom: 19.1.0([email protected])
+ dependencies:
+ '@radix-ui/primitive': 1.1.2
+ '@radix-ui/react-compose-refs': 1.1.2(@types/[email protected])([email protected])
+ '@radix-ui/react-use-callback-ref': 1.1.1(@types/[email protected])([email protected])
+ '@radix-ui/react-use-escape-keydown': 1.1.1(@types/[email protected])([email protected])
+ react: 19.1.0
+ react-dom: 19.1.0([email protected])
+ optionalDependencies:
+ '@types/react': 18.3.21
+ '@types/react-dom': 18.3.7(@types/[email protected])
+
dependencies:
'@radix-ui/primitive': 1.1.2
@@ -17058,6 +17134,21 @@ snapshots:
'@types/react': 18.3.21
'@types/react-dom': 19.1.6(@types/[email protected])
+ dependencies:
+ '@radix-ui/primitive': 1.1.2
+ '@radix-ui/react-compose-refs': 1.1.2(@types/[email protected])([email protected])
+ '@radix-ui/react-context': 1.1.2(@types/[email protected])([email protected])
+ '@radix-ui/react-id': 1.1.1(@types/[email protected])([email protected])
+ '@radix-ui/react-use-controllable-state': 1.2.2(@types/[email protected])([email protected])
+ react: 19.1.0
+ react-dom: 19.1.0([email protected])
+ optionalDependencies:
+ '@types/react': 18.3.21
+ '@types/react-dom': 18.3.7(@types/[email protected])
+
dependencies:
'@radix-ui/primitive': 1.1.2
@@ -17093,6 +17184,17 @@ snapshots:
react: 19.1.0
react-dom: 19.1.0([email protected])
+ dependencies:
+ '@radix-ui/react-compose-refs': 1.1.2(@types/[email protected])([email protected])
+ '@radix-ui/react-use-callback-ref': 1.1.1(@types/[email protected])([email protected])
+ react: 19.1.0
+ react-dom: 19.1.0([email protected])
+ optionalDependencies:
+ '@types/react': 18.3.21
+ '@types/react-dom': 18.3.7(@types/[email protected])
+
dependencies:
'@radix-ui/react-compose-refs': 1.1.2(@types/[email protected])([email protected])
@@ -17104,6 +17206,17 @@ snapshots:
'@types/react': 18.3.21
'@types/react-dom': 19.1.6(@types/[email protected])
+ dependencies:
+ '@radix-ui/react-compose-refs': 1.1.2(@types/[email protected])([email protected])
+ '@radix-ui/react-use-callback-ref': 1.1.1(@types/[email protected])([email protected])
+ react: 19.1.0
+ react-dom: 19.1.0([email protected])
+ optionalDependencies:
+ '@types/react': 18.3.21
+ '@types/react-dom': 18.3.7(@types/[email protected])
+
dependencies:
'@radix-ui/react-compose-refs': 1.1.2(@types/[email protected])([email protected])
@@ -17137,6 +17250,32 @@ snapshots:
'@types/react': 18.3.21
'@types/react-dom': 19.1.6(@types/[email protected])
+ dependencies:
+ '@radix-ui/primitive': 1.1.2
+ '@radix-ui/react-compose-refs': 1.1.2(@types/[email protected])([email protected])
+ '@radix-ui/react-context': 1.1.2(@types/[email protected])([email protected])
+ '@radix-ui/react-direction': 1.1.1(@types/[email protected])([email protected])
+ '@radix-ui/react-dismissable-layer': 1.1.9(@types/[email protected](@types/[email protected]))(@types/[email protected])([email protected]([email protected]))([email protected])
+ '@radix-ui/react-focus-guards': 1.1.2(@types/[email protected])([email protected])
+ '@radix-ui/react-id': 1.1.1(@types/[email protected])([email protected])
+ '@radix-ui/react-roving-focus': 1.1.9(@types/[email protected](@types/[email protected]))(@types/[email protected])([email protected]([email protected]))([email protected])
+ '@radix-ui/react-slot': 1.2.2(@types/[email protected])([email protected])
+ '@radix-ui/react-use-callback-ref': 1.1.1(@types/[email protected])([email protected])
+ aria-hidden: 1.2.4
+ react: 19.1.0
+ react-dom: 19.1.0([email protected])
+ react-remove-scroll: 2.6.3(@types/[email protected])([email protected])
+ optionalDependencies:
+ '@types/react': 18.3.21
+ '@types/react-dom': 18.3.7(@types/[email protected])
+
dependencies:
'@radix-ui/primitive': 1.1.2
@@ -17244,6 +17383,24 @@ snapshots:
'@types/react': 18.3.21
'@types/react-dom': 19.1.6(@types/[email protected])
+ dependencies:
+ '@floating-ui/react-dom': 2.1.2([email protected]([email protected]))([email protected])
+ '@radix-ui/react-compose-refs': 1.1.2(@types/[email protected])([email protected])
+ '@radix-ui/react-context': 1.1.2(@types/[email protected])([email protected])
+ '@radix-ui/react-use-callback-ref': 1.1.1(@types/[email protected])([email protected])
+ '@radix-ui/react-use-layout-effect': 1.1.1(@types/[email protected])([email protected])
+ '@radix-ui/react-use-rect': 1.1.1(@types/[email protected])([email protected])
+ '@radix-ui/react-use-size': 1.1.1(@types/[email protected])([email protected])
+ '@radix-ui/rect': 1.1.1
+ react: 19.1.0
+ react-dom: 19.1.0([email protected])
+ optionalDependencies:
+ '@types/react': 18.3.21
+ '@types/react-dom': 18.3.7(@types/[email protected])
+
dependencies:
'@floating-ui/react-dom': 2.1.2([email protected]([email protected]))([email protected])
@@ -17289,6 +17446,16 @@ snapshots:
'@types/react': 18.3.21
'@types/react-dom': 19.1.6(@types/[email protected])
+ dependencies:
+ '@radix-ui/react-use-layout-effect': 1.1.1(@types/[email protected])([email protected])
+ react: 19.1.0
+ react-dom: 19.1.0([email protected])
+ optionalDependencies:
+ '@types/react': 18.3.21
+ '@types/react-dom': 18.3.7(@types/[email protected])
+
dependencies:
@@ -17352,6 +17519,15 @@ snapshots:
'@types/react': 18.3.21
'@types/react-dom': 19.1.6(@types/[email protected])
+ dependencies:
+ '@radix-ui/react-slot': 1.2.3(@types/[email protected])([email protected])
+ react: 19.1.0
+ react-dom: 19.1.0([email protected])
+ optionalDependencies:
+ '@types/react': 18.3.21
+ '@types/react-dom': 18.3.7(@types/[email protected])
+
dependencies:
'@radix-ui/react-slot': 1.2.3(@types/[email protected])([email protected])
@@ -17361,6 +17537,23 @@ snapshots:
'@types/react': 18.3.21
'@types/react-dom': 19.1.6(@types/[email protected])
+ dependencies:
+ '@radix-ui/primitive': 1.1.2
+ '@radix-ui/react-compose-refs': 1.1.2(@types/[email protected])([email protected])
+ '@radix-ui/react-context': 1.1.2(@types/[email protected])([email protected])
+ '@radix-ui/react-direction': 1.1.1(@types/[email protected])([email protected])
+ '@radix-ui/react-id': 1.1.1(@types/[email protected])([email protected])
+ '@radix-ui/react-use-callback-ref': 1.1.1(@types/[email protected])([email protected])
+ '@radix-ui/react-use-controllable-state': 1.2.2(@types/[email protected])([email protected])
+ react: 19.1.0
+ react-dom: 19.1.0([email protected])
+ optionalDependencies:
+ '@types/react': 18.3.21
+ '@types/react-dom': 18.3.7(@types/[email protected])
+
dependencies:
'@radix-ui/primitive': 1.1.2
@@ -17378,6 +17571,35 @@ snapshots:
'@types/react': 18.3.21
'@types/react-dom': 19.1.6(@types/[email protected])
+ dependencies:
+ '@radix-ui/number': 1.1.1
+ '@radix-ui/primitive': 1.1.2
+ '@radix-ui/react-compose-refs': 1.1.2(@types/[email protected])([email protected])
+ '@radix-ui/react-context': 1.1.2(@types/[email protected])([email protected])
+ '@radix-ui/react-direction': 1.1.1(@types/[email protected])([email protected])
+ '@radix-ui/react-dismissable-layer': 1.1.10(@types/[email protected](@types/[email protected]))(@types/[email protected])([email protected]([email protected]))([email protected])
+ '@radix-ui/react-focus-guards': 1.1.2(@types/[email protected])([email protected])
+ '@radix-ui/react-id': 1.1.1(@types/[email protected])([email protected])
+ '@radix-ui/react-slot': 1.2.3(@types/[email protected])([email protected])
+ '@radix-ui/react-use-callback-ref': 1.1.1(@types/[email protected])([email protected])
+ '@radix-ui/react-use-controllable-state': 1.2.2(@types/[email protected])([email protected])
+ '@radix-ui/react-use-layout-effect': 1.1.1(@types/[email protected])([email protected])
+ '@radix-ui/react-use-previous': 1.1.1(@types/[email protected])([email protected])
+ '@radix-ui/react-visually-hidden': 1.2.3(@types/[email protected](@types/[email protected]))(@types/[email protected])([email protected]([email protected]))([email protected])
+ aria-hidden: 1.2.4
+ react: 19.1.0
+ react-dom: 19.1.0([email protected])
+ react-remove-scroll: 2.6.3(@types/[email protected])([email protected])
+ optionalDependencies:
+ '@types/react': 18.3.21
+ '@types/react-dom': 18.3.7(@types/[email protected])
+
dependencies:
'@radix-ui/number': 1.1.1
@@ -17407,6 +17629,25 @@ snapshots:
'@types/react': 18.3.21
'@types/react-dom': 19.1.6(@types/[email protected])
+ dependencies:
+ '@radix-ui/number': 1.1.1
+ '@radix-ui/primitive': 1.1.2
+ '@radix-ui/react-compose-refs': 1.1.2(@types/[email protected])([email protected])
+ '@radix-ui/react-context': 1.1.2(@types/[email protected])([email protected])
+ '@radix-ui/react-direction': 1.1.1(@types/[email protected])([email protected])
+ '@radix-ui/react-use-controllable-state': 1.2.2(@types/[email protected])([email protected])
+ '@radix-ui/react-use-layout-effect': 1.1.1(@types/[email protected])([email protected])
+ '@radix-ui/react-use-previous': 1.1.1(@types/[email protected])([email protected])
+ '@radix-ui/react-use-size': 1.1.1(@types/[email protected])([email protected])
+ react: 19.1.0
+ react-dom: 19.1.0([email protected])
+ optionalDependencies:
+ '@types/react': 18.3.21
+ '@types/react-dom': 18.3.7(@types/[email protected])
+
dependencies:
'@babel/runtime': 7.27.1
@@ -17556,6 +17797,15 @@ snapshots:
'@types/react': 18.3.21
'@types/react-dom': 19.1.6(@types/[email protected])
+ dependencies:
+ react: 19.1.0
+ react-dom: 19.1.0([email protected])
+ optionalDependencies:
+ '@types/react': 18.3.21
+ '@types/react-dom': 18.3.7(@types/[email protected])
+
dependencies:
@@ -19296,6 +19546,8 @@ snapshots:
'@types/[email protected]': {}
+ '@types/[email protected]': {}
+
'@types/[email protected]': {}
@@ -19584,7 +19836,7 @@ snapshots:
- rollup
- supports-color
dependencies:
'@babel/runtime': 7.27.1
'@videojs/vhs-utils': 4.1.1
@@ -19593,7 +19845,7 @@ snapshots:
m3u8-parser: 7.2.0
mpd-parser: 1.3.1
mux.js: 7.1.0
- video.js: 8.22.0
+ video.js: 8.23.3
'@videojs/[email protected]':
dependencies:
@@ -20481,6 +20733,10 @@ snapshots:
dependencies:
react: 19.1.0
+ dependencies:
+ react: 19.1.0
+
dependencies:
assertion-error: 2.0.1
@@ -21131,9 +21387,9 @@ snapshots:
optionalDependencies:
'@modelcontextprotocol/sdk': 1.6.1
dependencies:
- zod: 3.25.67
+ zod: 3.25.76
optionalDependencies:
'@modelcontextprotocol/sdk': 1.6.1
@@ -23878,8 +24134,6 @@ snapshots:
untun: 0.1.3
uqr: 0.1.2
-
dependencies:
mlly: 1.7.4
@@ -23986,6 +24240,10 @@ snapshots:
dependencies:
react: 19.1.0
+ dependencies:
+ react: 19.1.0
+
@@ -24186,6 +24444,12 @@ snapshots:
- acorn
- supports-color
+ dependencies:
+ ce-la-react: 0.3.0([email protected])
+ transitivePeerDependencies:
+ - react
+
dependencies:
'@vercel/edge': 1.2.1
@@ -24206,8 +24470,6 @@ snapshots:
tree-dump: 1.0.2([email protected])
tslib: 2.8.1
-
dependencies:
map-or-similar: 1.5.0
@@ -25847,8 +26109,6 @@ snapshots:
- supports-color
- utf-8-validate
-
dependencies:
hls.js: 0.14.17
@@ -25882,15 +26142,6 @@ snapshots:
dependencies:
react: 19.1.0
- dependencies:
- deepmerge: 4.3.1
- load-script: 1.0.0
- memoize-one: 5.2.1
- prop-types: 15.8.1
- react: 19.1.0
- react-fast-compare: 3.2.2
-
dependencies:
fast-deep-equal: 2.0.1
@@ -27891,10 +28142,10 @@ snapshots:
'@types/unist': 3.0.3
vfile-message: 4.0.2
dependencies:
'@babel/runtime': 7.27.1
- '@videojs/http-streaming': 3.17.0([email protected])
+ '@videojs/http-streaming': 3.17.0([email protected])
'@videojs/vhs-utils': 4.1.1
'@videojs/xhr': 2.7.0
aes-decrypter: 4.0.2
@@ -27902,14 +28153,14 @@ snapshots:
m3u8-parser: 7.2.0
mpd-parser: 1.3.1
mux.js: 7.1.0
- videojs-contrib-quality-levels: 4.1.0([email protected])
+ videojs-contrib-quality-levels: 4.1.0([email protected])
videojs-font: 4.2.0
videojs-vtt.js: 0.15.5
dependencies:
global: 4.4.0
- video.js: 8.22.0
+ video.js: 8.23.3
@@ -28462,9 +28713,9 @@ snapshots:
dependencies:
zod: 3.24.2
dependencies:
- zod: 3.25.67
+ zod: 3.25.76
@@ -28474,6 +28725,6 @@ snapshots: