Open source Loom alternative. Beautiful, shareable screen recordings.
Rust appcapcossloommacnextjsnextjs15open-sourceossreactrecordrustscreen-capturescreen-recorderscreenshotsolidjstauritauri-apptypescriptvite
Add caption translation, context, and UI
Richie McIlroy4c9e3e21f0dc
diff --git a/apps/web/actions/videos/get-available-translations.ts b/apps/web/actions/videos/get-available-translations.tsnew file mode 100644index 000000000..82ca2eddd--- /dev/null+++ b/apps/web/actions/videos/get-available-translations.ts@@ -0,0 +1,111 @@+"use server";++import { db } from "@cap/database";+import { s3Buckets, videos } from "@cap/database/schema";+import { S3Buckets } from "@cap/web-backend";+import type { Video } from "@cap/web-domain";+import { eq } from "drizzle-orm";+import { Effect, Option } from "effect";+import { runPromise } from "@/lib/server";+import { type LanguageCode, SUPPORTED_LANGUAGES } from "./translate-transcript";++interface AvailableTranslation {+ code: LanguageCode;+ name: string;+}++interface GetAvailableTranslationsResult {+ success: boolean;+ hasOriginal: boolean;+ translations: AvailableTranslation[];+ message?: string;+}++export async function getAvailableTranslations(+ videoId: Video.VideoId,+): Promise<GetAvailableTranslationsResult> {+ if (!videoId) {+ return {+ success: false,+ hasOriginal: false,+ translations: [],+ message: "Missing video ID",+ };+ }++ const query = await db()+ .select({+ video: videos,+ bucket: s3Buckets,+ })+ .from(videos)+ .leftJoin(s3Buckets, eq(videos.bucket, s3Buckets.id))+ .where(eq(videos.id, videoId));++ if (query.length === 0 || !query[0]?.video) {+ return {+ success: false,+ hasOriginal: false,+ translations: [],+ message: "Video not found",+ };+ }++ const { video } = query[0];+ const prefix = `${video.ownerId}/${videoId}/transcription`;++ try {+ const result = await Effect.gen(function* () {+ const [bucket] = yield* S3Buckets.getBucketAccess(+ Option.fromNullable(query[0]?.bucket?.id),+ );++ const listResult = yield* bucket.listObjects({+ prefix,+ maxKeys: 50,+ });++ return listResult;+ }).pipe(runPromise);++ const contents = result.Contents || [];++ let hasOriginal = false;+ const translations: AvailableTranslation[] = [];++ for (const obj of contents) {+ const key = obj.Key;+ if (!key) continue;++ if (key.endsWith("/transcription.vtt")) {+ hasOriginal = true;+ continue;+ }++ const match = key.match(/transcription\.([a-z]{2})\.vtt$/);+ if (match) {+ const langCode = match[1] as LanguageCode;+ if (SUPPORTED_LANGUAGES[langCode]) {+ translations.push({+ code: langCode,+ name: SUPPORTED_LANGUAGES[langCode],+ });+ }+ }+ }++ return {+ success: true,+ hasOriginal,+ translations,+ };+ } catch (error) {+ console.error("[getAvailableTranslations] Error:", error);+ return {+ success: false,+ hasOriginal: false,+ translations: [],+ message: "Failed to list translations",+ };+ }+}diff --git a/apps/web/actions/videos/translate-transcript.ts b/apps/web/actions/videos/translate-transcript.tsnew file mode 100644index 000000000..25b730a00--- /dev/null+++ b/apps/web/actions/videos/translate-transcript.ts@@ -0,0 +1,182 @@+"use server";++import { db } from "@cap/database";+import { s3Buckets, videos } from "@cap/database/schema";+import { S3Buckets } from "@cap/web-backend";+import type { Video } from "@cap/web-domain";+import { eq } from "drizzle-orm";+import { Effect, Option } from "effect";+import { GROQ_MODEL, getGroqClient } from "@/lib/groq-client";+import { runPromise } from "@/lib/server";++export const SUPPORTED_LANGUAGES = {+ en: "English",+ es: "Spanish",+ fr: "French",+ de: "German",+ pt: "Portuguese",+ it: "Italian",+ nl: "Dutch",+ pl: "Polish",+ ru: "Russian",+ ja: "Japanese",+ ko: "Korean",+ zh: "Chinese (Simplified)",+ ar: "Arabic",+ hi: "Hindi",+} as const;++export type LanguageCode = keyof typeof SUPPORTED_LANGUAGES;++interface TranslateResult {+ success: boolean;+ translatedVtt?: string;+ message: string;+}++export async function translateTranscript(+ videoId: Video.VideoId,+ targetLanguage: LanguageCode,+): Promise<TranslateResult> {+ if (!videoId || !targetLanguage) {+ return {+ success: false,+ message: "Missing required parameters",+ };+ }++ if (!SUPPORTED_LANGUAGES[targetLanguage]) {+ return {+ success: false,+ message: "Unsupported language",+ };+ }++ const groq = getGroqClient();+ if (!groq) {+ return {+ success: false,+ message: "Translation service not configured",+ };+ }++ const query = await db()+ .select({+ video: videos,+ bucket: s3Buckets,+ })+ .from(videos)+ .leftJoin(s3Buckets, eq(videos.bucket, s3Buckets.id))+ .where(eq(videos.id, videoId));++ if (query.length === 0 || !query[0]?.video) {+ return { success: false, message: "Video not found" };+ }++ const { video } = query[0];++ const translatedKey = `${video.ownerId}/${videoId}/transcription.${targetLanguage}.vtt`;++ try {+ const existingTranslation = await Effect.gen(function* () {+ const [bucket] = yield* S3Buckets.getBucketAccess(+ Option.fromNullable(query[0]?.bucket?.id),+ );+ return yield* bucket.getObject(translatedKey);+ }).pipe(runPromise);++ if (Option.isSome(existingTranslation)) {+ return {+ success: true,+ translatedVtt: existingTranslation.value,+ message: "Retrieved cached translation",+ };+ }+ } catch (e) {+ console.debug("[translateTranscript] No cached translation found:", e);+ }++ const originalVtt = await Effect.gen(function* () {+ const [bucket] = yield* S3Buckets.getBucketAccess(+ Option.fromNullable(query[0]?.bucket?.id),+ );+ return yield* bucket.getObject(+ `${video.ownerId}/${videoId}/transcription.vtt`,+ );+ }).pipe(runPromise);++ if (Option.isNone(originalVtt)) {+ return { success: false, message: "Original transcript not found" };+ }++ const translatedVtt = await translateVttContent(+ originalVtt.value,+ targetLanguage,+ groq,+ );++ if (!translatedVtt) {+ return { success: false, message: "Translation failed" };+ }++ try {+ await Effect.gen(function* () {+ const [bucket] = yield* S3Buckets.getBucketAccess(+ Option.fromNullable(query[0]?.bucket?.id),+ );+ yield* bucket.putObject(translatedKey, translatedVtt, {+ contentType: "text/vtt",+ });+ }).pipe(runPromise);+ } catch (error) {+ console.error("[translateTranscript] Failed to cache translation:", error);+ }++ return {+ success: true,+ translatedVtt,+ message: "Translation completed",+ };+}++async function translateVttContent(+ vttContent: string,+ targetLanguage: LanguageCode,+ groq: NonNullable<ReturnType<typeof getGroqClient>>,+): Promise<string | null> {+ const targetLanguageName = SUPPORTED_LANGUAGES[targetLanguage];++ const prompt = `Translate the following WebVTT subtitle file to ${targetLanguageName}.++IMPORTANT RULES:+1. Keep the "WEBVTT" header exactly as is+2. Keep all timestamp lines exactly as they are (e.g., "00:00:01.234 --> 00:00:03.456")+3. Keep all cue numbers exactly as they are+4. Only translate the actual text content on each line+5. Preserve all newlines and formatting+6. Do not add any explanations or comments+7. Return ONLY the translated VTT content++VTT content to translate:++${vttContent}`;++ try {+ const response = await groq.chat.completions.create({+ model: GROQ_MODEL,+ messages: [{ role: "user", content: prompt }],+ temperature: 0.3,+ max_tokens: 8000,+ });++ const content = response.choices[0]?.message?.content;+ if (content?.includes("WEBVTT")) {+ return content.trim();+ }++ return null;+ } catch (error) {+ console.error("[translateVttContent] Translation error:", error);+ return null;+ }+}diff --git a/apps/web/app/s/[videoId]/Share.tsx b/apps/web/app/s/[videoId]/Share.tsxindex 614098011..6250d18cd 100644--- a/apps/web/app/s/[videoId]/Share.tsx+++ b/apps/web/app/s/[videoId]/Share.tsx@@ -18,6 +18,7 @@ import {type VideoStatusResult,} from "@/actions/videos/get-status";import type { OrganizationSettings } from "@/app/(org)/dashboard/dashboard-data";+import { CaptionProvider } from "./_components/CaptionContext";import { ShareVideo } from "./_components/ShareVideo";import { Sidebar } from "./_components/Sidebar";import SummaryChapters from "./_components/SummaryChapters";@@ -420,111 +421,116 @@ export const Share = ({isDisabled("disableTranscript");return (- <div className="mt-4">- <div className="flex flex-col gap-4 lg:flex-row">- <div className="flex-1">- <div className="overflow-visible relative bg-white rounded-2xl border aspect-video border-gray-5">- <div className="absolute inset-3 w-[calc(100%-1.5rem)] h-[calc(100%-1.5rem)] overflow-visible rounded-xl">- <ShareVideo- data={{ ...data, transcriptionStatus }}- comments={comments}- areChaptersDisabled={areChaptersDisabled}- areCaptionsDisabled={areCaptionsDisabled}- areCommentStampsDisabled={areCommentStampsDisabled}- areReactionStampsDisabled={areReactionStampsDisabled}- chapters={aiData?.chapters || []}- aiGenerationStatus={aiData?.aiGenerationStatus}- ref={playerRef}+ <CaptionProvider+ videoId={data.id}+ transcriptionStatus={transcriptionStatus}+ >+ <div className="mt-4">+ <div className="flex flex-col gap-4 lg:flex-row">+ <div className="flex-1">+ <div className="overflow-visible relative bg-white rounded-2xl border aspect-video border-gray-5">+ <div className="absolute inset-3 w-[calc(100%-1.5rem)] h-[calc(100%-1.5rem)] overflow-visible rounded-xl">+ <ShareVideo+ data={{ ...data, transcriptionStatus }}+ comments={comments}+ areChaptersDisabled={areChaptersDisabled}+ areCaptionsDisabled={areCaptionsDisabled}+ areCommentStampsDisabled={areCommentStampsDisabled}+ areReactionStampsDisabled={areReactionStampsDisabled}+ chapters={aiData?.chapters || []}+ aiGenerationStatus={aiData?.aiGenerationStatus}+ ref={playerRef}+ />+ </div>+ </div>+ <div className="mt-4 lg:hidden">+ <Toolbar+ onOptimisticComment={handleOptimisticComment}+ onCommentSuccess={handleCommentSuccess}+ data={data}/></div></div>- <div className="mt-4 lg:hidden">++ {!allSettingsDisabled && (+ <div className="flex flex-col lg:w-80">+ <Sidebar+ data={{+ ...data,+ createdAt: effectiveDate,+ transcriptionStatus,+ }}+ videoSettings={videoSettings}+ commentsData={commentsData}+ setCommentsData={setCommentsData}+ optimisticComments={optimisticComments}+ setOptimisticComments={setOptimisticComments}+ handleCommentSuccess={handleCommentSuccess}+ views={views}+ onSeek={handleSeek}+ videoId={data.id}+ aiData={aiData}+ aiGenerationEnabled={aiGenerationEnabled}+ ref={activityRef}+ />+ </div>+ )}+ </div>++ <div className="hidden mt-4 lg:block">+ <div><ToolbaronOptimisticComment={handleOptimisticComment}onCommentSuccess={handleCommentSuccess}+ disableReactions={+ videoSettings?.disableReactions ??+ data.orgSettings?.disableReactions+ }data={data}/></div></div>- {!allSettingsDisabled && (- <div className="flex flex-col lg:w-80">- <Sidebar- data={{- ...data,- createdAt: effectiveDate,- transcriptionStatus,- }}- videoSettings={videoSettings}- commentsData={commentsData}- setCommentsData={setCommentsData}- optimisticComments={optimisticComments}- setOptimisticComments={setOptimisticComments}- handleCommentSuccess={handleCommentSuccess}- views={views}- onSeek={handleSeek}- videoId={data.id}- aiData={aiData}- aiGenerationEnabled={aiGenerationEnabled}- ref={activityRef}- />- </div>- )}- </div>-- <div className="hidden mt-4 lg:block">- <div>- <Toolbar- onOptimisticComment={handleOptimisticComment}- onCommentSuccess={handleCommentSuccess}- disableReactions={- videoSettings?.disableReactions ??- data.orgSettings?.disableReactions- }- data={data}- />- </div>- </div>-- <div className="hidden mt-4 lg:block">- {aiLoading && (- <div className="p-4 animate-pulse new-card-style">- <div className="space-y-6">- <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="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 className="hidden mt-4 lg:block">+ {aiLoading && (+ <div className="p-4 animate-pulse new-card-style">+ <div className="space-y-6">+ <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="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>- <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="mr-3 w-12 h-4 bg-gray-200 rounded"></div>- <div className="flex-1 h-4 bg-gray-200 rounded"></div>- </div>- ))}+ <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="mr-3 w-12 h-4 bg-gray-200 rounded"></div>+ <div className="flex-1 h-4 bg-gray-200 rounded"></div>+ </div>+ ))}+ </div></div></div></div>- </div>- )}-- <SummaryChapters- isSummaryDisabled={isSummaryDisabled}- areChaptersDisabled={areChaptersDisabled}- handleSeek={handleSeek}- aiData={aiData}- aiLoading={aiLoading}- />+ )}++ <SummaryChapters+ isSummaryDisabled={isSummaryDisabled}+ areChaptersDisabled={areChaptersDisabled}+ handleSeek={handleSeek}+ aiData={aiData}+ aiLoading={aiLoading}+ />+ </div></div>- </div>+ </CaptionProvider>);};diff --git a/apps/web/app/s/[videoId]/_components/CapVideoPlayer.tsx b/apps/web/app/s/[videoId]/_components/CapVideoPlayer.tsxindex f0471e3f4..0850de299 100644--- a/apps/web/app/s/[videoId]/_components/CapVideoPlayer.tsx+++ b/apps/web/app/s/[videoId]/_components/CapVideoPlayer.tsx@@ -52,6 +52,11 @@ function getProgressStatusText(type EnhancedAudioStatus = "PROCESSING" | "COMPLETE" | "ERROR" | "SKIPPED";+interface CaptionOption {+ code: string;+ name: string;+}+interface Props {videoSrc: string;videoId: Video.VideoId;@@ -75,6 +80,11 @@ interface Props {onSeek?: (time: number) => void;enhancedAudioUrl?: string | null;enhancedAudioStatus?: EnhancedAudioStatus | null;+ captionLanguage?: string;+ onCaptionLanguageChange?: (language: string) => void;+ availableCaptions?: CaptionOption[];+ isCaptionLoading?: boolean;+ hasCaptions?: boolean;}export function CapVideoPlayer({@@ -94,6 +104,11 @@ export function CapVideoPlayer({onSeek,enhancedAudioUrl,enhancedAudioStatus,+ captionLanguage,+ onCaptionLanguageChange,+ availableCaptions = [],+ isCaptionLoading = false,+ hasCaptions = false,}: Props) {const [currentCue, setCurrentCue] = useState<string>("");const [controlsVisible, setControlsVisible] = useState(false);@@ -778,6 +793,11 @@ export function CapVideoPlayer({enhancedAudioStatus={enhancedAudioStatus}enhancedAudioEnabled={enhancedAudioEnabled}setEnhancedAudioEnabled={setEnhancedAudioEnabled}+ captionLanguage={captionLanguage}+ onCaptionLanguageChange={onCaptionLanguageChange}+ availableCaptions={availableCaptions}+ isCaptionLoading={isCaptionLoading}+ hasCaptions={hasCaptions}/><MediaPlayerPiP /><MediaPlayerFullscreen />diff --git a/apps/web/app/s/[videoId]/_components/CaptionContext.tsx b/apps/web/app/s/[videoId]/_components/CaptionContext.tsxnew file mode 100644index 000000000..3300327ce--- /dev/null+++ b/apps/web/app/s/[videoId]/_components/CaptionContext.tsx@@ -0,0 +1,178 @@+"use client";++import type { Video } from "@cap/web-domain";+import { useQuery } from "@tanstack/react-query";+import {+ createContext,+ type ReactNode,+ useCallback,+ useContext,+ useMemo,+ useState,+} from "react";+import { getAvailableTranslations } from "@/actions/videos/get-available-translations";+import {+ type LanguageCode,+ SUPPORTED_LANGUAGES,+ translateTranscript,+} from "@/actions/videos/translate-transcript";++export type CaptionLanguage = LanguageCode | "original" | "off";++interface AvailableTranslation {+ code: LanguageCode;+ name: string;+}++interface CaptionContextValue {+ selectedLanguage: CaptionLanguage;+ setSelectedLanguage: (language: CaptionLanguage) => void;+ isTranslating: boolean;+ availableTranslations: AvailableTranslation[];+ hasOriginal: boolean;+ isLoadingAvailable: boolean;+ translatedVttContent: Map<LanguageCode, string>;+ currentVttContent: string | null;+ setOriginalVttContent: (content: string | null) => void;+ requestTranslation: (language: LanguageCode) => Promise<string | null>;+}++const CaptionContext = createContext<CaptionContextValue | null>(null);++interface CaptionProviderProps {+ children: ReactNode;+ videoId: Video.VideoId;+ transcriptionStatus?: string | null;+}++export function CaptionProvider({+ children,+ videoId,+ transcriptionStatus,+}: CaptionProviderProps) {+ const [selectedLanguage, setSelectedLanguage] =+ useState<CaptionLanguage>("original");+ const [isTranslating, setIsTranslating] = useState(false);+ const [translatedVttContent, setTranslatedVttContent] = useState<+ Map<LanguageCode, string>+ >(new Map());+ const [originalVttContent, setOriginalVttContent] = useState<string | null>(+ null,+ );++ const { data: availableData, isLoading: isLoadingAvailable } = useQuery({+ queryKey: ["availableTranslations", videoId],+ queryFn: () => getAvailableTranslations(videoId),+ enabled: transcriptionStatus === "COMPLETE",+ staleTime: 5 * 60 * 1000,+ });++ const availableTranslations = useMemo(+ () => availableData?.translations ?? [],+ [availableData],+ );++ const hasOriginal = availableData?.hasOriginal ?? false;++ const requestTranslation = useCallback(+ async (language: LanguageCode): Promise<string | null> => {+ return new Promise((resolve) => {+ setTranslatedVttContent((prev) => {+ const cached = prev.get(language);+ if (cached) {+ resolve(cached);+ return prev;+ }++ setIsTranslating(true);+ translateTranscript(videoId, language)+ .then((result) => {+ if (result.success && result.translatedVtt) {+ const vtt = result.translatedVtt;+ setTranslatedVttContent((p) => new Map(p).set(language, vtt));+ resolve(vtt);+ } else {+ resolve(null);+ }+ })+ .finally(() => {+ setIsTranslating(false);+ });++ return prev;+ });+ });+ },+ [videoId],+ );++ const currentVttContent = useMemo(() => {+ if (selectedLanguage === "off") {+ return null;+ }+ if (selectedLanguage === "original") {+ return originalVttContent;+ }+ return translatedVttContent.get(selectedLanguage) ?? null;+ }, [selectedLanguage, originalVttContent, translatedVttContent]);++ const handleSetSelectedLanguage = useCallback(+ async (language: CaptionLanguage) => {+ setSelectedLanguage(language);++ if (+ language !== "off" &&+ language !== "original" &&+ !translatedVttContent.has(language)+ ) {+ await requestTranslation(language);+ }+ },+ [translatedVttContent, requestTranslation],+ );++ const value: CaptionContextValue = useMemo(+ () => ({+ selectedLanguage,+ setSelectedLanguage: handleSetSelectedLanguage,+ isTranslating,+ availableTranslations,+ hasOriginal,+ isLoadingAvailable,+ translatedVttContent,+ currentVttContent,+ setOriginalVttContent,+ requestTranslation,+ }),+ [+ selectedLanguage,+ handleSetSelectedLanguage,+ isTranslating,+ availableTranslations,+ hasOriginal,+ isLoadingAvailable,+ translatedVttContent,+ currentVttContent,+ requestTranslation,+ ],+ );++ return (+ <CaptionContext.Provider value={value}>{children}</CaptionContext.Provider>+ );+}++export function useCaptionContext(): CaptionContextValue {+ const context = useContext(CaptionContext);+ if (!context) {+ throw new Error("useCaptionContext must be used within a CaptionProvider");+ }+ return context;+}++export function useCaptionContextOptional(): CaptionContextValue | null {+ return useContext(CaptionContext);+}++export { SUPPORTED_LANGUAGES };+export type { LanguageCode };diff --git a/apps/web/app/s/[videoId]/_components/HLSVideoPlayer.tsx b/apps/web/app/s/[videoId]/_components/HLSVideoPlayer.tsxindex 99ddf268d..65a81829c 100644--- a/apps/web/app/s/[videoId]/_components/HLSVideoPlayer.tsx+++ b/apps/web/app/s/[videoId]/_components/HLSVideoPlayer.tsx@@ -51,6 +51,11 @@ import {type EnhancedAudioStatus = "PROCESSING" | "COMPLETE" | "ERROR" | "SKIPPED";+interface CaptionOption {+ code: string;+ name: string;+}+interface Props {videoSrc: string;videoId: Video.VideoId;@@ -63,6 +68,11 @@ interface Props {hasActiveUpload?: boolean;enhancedAudioUrl?: string | null;enhancedAudioStatus?: EnhancedAudioStatus | null;+ captionLanguage?: string;+ onCaptionLanguageChange?: (language: string) => void;+ availableCaptions?: CaptionOption[];+ isCaptionLoading?: boolean;+ hasCaptions?: boolean;}export function HLSVideoPlayer({@@ -77,6 +87,11 @@ export function HLSVideoPlayer({disableCaptions,enhancedAudioUrl,enhancedAudioStatus,+ captionLanguage,+ onCaptionLanguageChange,+ availableCaptions = [],+ isCaptionLoading = false,+ hasCaptions = false,}: Props) {const hlsInstance = useRef<Hls | null>(null);const [currentCue, setCurrentCue] = useState<string>("");@@ -496,6 +511,11 @@ export function HLSVideoPlayer({enhancedAudioStatus={enhancedAudioStatus}enhancedAudioEnabled={enhancedAudioEnabled}setEnhancedAudioEnabled={setEnhancedAudioEnabled}+ captionLanguage={captionLanguage}+ onCaptionLanguageChange={onCaptionLanguageChange}+ availableCaptions={availableCaptions}+ isCaptionLoading={isCaptionLoading}+ hasCaptions={hasCaptions}/><MediaPlayerPiP /><MediaPlayerFullscreen />diff --git a/apps/web/app/s/[videoId]/_components/ShareVideo.tsx b/apps/web/app/s/[videoId]/_components/ShareVideo.tsxindex fb1b8f1d7..797559a10 100644--- a/apps/web/app/s/[videoId]/_components/ShareVideo.tsx+++ b/apps/web/app/s/[videoId]/_components/ShareVideo.tsx@@ -14,14 +14,10 @@ import {} from "react";import { UpgradeModal } from "@/components/UpgradeModal";import type { VideoData } from "../types";+import { type CaptionLanguage, useCaptionContext } from "./CaptionContext";import { CapVideoPlayer } from "./CapVideoPlayer";import { HLSVideoPlayer } from "./HLSVideoPlayer";-import {- formatChaptersAsVTT,- formatTranscriptAsVTT,- parseVTT,- type TranscriptEntry,-} from "./utils/transcript-utils";+import { formatChaptersAsVTT } from "./utils/transcript-utils";declare global {interface Window {@@ -71,8 +67,13 @@ export const ShareVideo = forwardRef<const videoRef = useRef<HTMLVideoElement | null>(null);useImperativeHandle(ref, () => videoRef.current as HTMLVideoElement, []);+ const captionContext = useCaptionContext();++ const handleCaptionLanguageChange = (language: string) => {+ captionContext.setSelectedLanguage(language as CaptionLanguage);+ };+const [upgradeModalOpen, setUpgradeModalOpen] = useState(false);- const [transcriptData, setTranscriptData] = useState<TranscriptEntry[]>([]);const [subtitleUrl, setSubtitleUrl] = useState<string | null>(null);const [chaptersUrl, setChaptersUrl] = useState<string | null>(null);const [commentsData, setCommentsData] = useState<CommentWithAuthor[]>([]);@@ -102,23 +103,33 @@ export const ShareVideo = forwardRef<useEffect(() => {if (transcriptContent) {- const parsed = parseVTT(transcriptContent);- setTranscriptData(parsed);+ captionContext.setOriginalVttContent(transcriptContent);} else if (transcriptError) {console.error("[Transcript] Transcript error from React Query:",transcriptError.message,);}- }, [transcriptContent, transcriptError]);+ }, [+ transcriptContent,+ transcriptError,+ captionContext.setOriginalVttContent,+ ]);useEffect(() => {- if (- data.transcriptionStatus === "COMPLETE" &&- transcriptData &&- transcriptData.length > 0- ) {- const vttContent = formatTranscriptAsVTT(transcriptData);+ const vttContent = captionContext.currentVttContent;++ if (captionContext.selectedLanguage === "off") {+ setSubtitleUrl((prev) => {+ if (prev) {+ URL.revokeObjectURL(prev);+ }+ return null;+ });+ return;+ }++ if (data.transcriptionStatus === "COMPLETE" && vttContent) {const blob = new Blob([vttContent], { type: "text/vtt" });const newUrl = URL.createObjectURL(blob);setSubtitleUrl((prev) => {@@ -138,7 +149,11 @@ export const ShareVideo = forwardRef<}return null;});- }, [data.transcriptionStatus, transcriptData]);+ }, [+ data.transcriptionStatus,+ captionContext.currentVttContent,+ captionContext.selectedLanguage,+ ]);useEffect(() => {if (chapters?.length > 0) {@@ -221,6 +236,11 @@ export const ShareVideo = forwardRef<onSeek={handleSeek}enhancedAudioUrl={enhancedAudioUrl}enhancedAudioStatus={enhancedAudioStatus}+ captionLanguage={captionContext.selectedLanguage}+ onCaptionLanguageChange={handleCaptionLanguageChange}+ availableCaptions={captionContext.availableTranslations}+ isCaptionLoading={captionContext.isTranslating}+ hasCaptions={data.transcriptionStatus === "COMPLETE"}/>) : (<HLSVideoPlayer@@ -234,6 +254,11 @@ export const ShareVideo = forwardRef<hasActiveUpload={data.hasActiveUpload}enhancedAudioUrl={enhancedAudioUrl}enhancedAudioStatus={enhancedAudioStatus}+ captionLanguage={captionContext.selectedLanguage}+ onCaptionLanguageChange={handleCaptionLanguageChange}+ availableCaptions={captionContext.availableTranslations}+ isCaptionLoading={captionContext.isTranslating}+ hasCaptions={data.transcriptionStatus === "COMPLETE"}/>)}</div>diff --git a/apps/web/app/s/[videoId]/_components/tabs/Transcript.tsx b/apps/web/app/s/[videoId]/_components/tabs/Transcript.tsxindex 722302d4b..2ccee0f30 100644--- a/apps/web/app/s/[videoId]/_components/tabs/Transcript.tsx+++ b/apps/web/app/s/[videoId]/_components/tabs/Transcript.tsx@@ -3,11 +3,25 @@import { Button } from "@cap/ui";import { useMutation } from "@tanstack/react-query";import { useInvalidateTranscript, useTranscript } from "hooks/use-transcript";-import { Check, Copy, Download, Edit3, MessageSquare, X } from "lucide-react";-import { useEffect, useMemo, useState } from "react";+import {+ Check,+ ChevronDown,+ Copy,+ Download,+ Edit3,+ Globe,+ MessageSquare,+ X,+} from "lucide-react";+import { useEffect, useMemo, useRef, useState } from "react";import { editTranscriptEntry } from "@/actions/videos/edit-transcript";+import {+ type LanguageCode,+ SUPPORTED_LANGUAGES,+} from "@/actions/videos/translate-transcript";import { useCurrentUser } from "@/app/Layout/AuthContext";import type { VideoData } from "../../types";+import { type CaptionLanguage, useCaptionContext } from "../CaptionContext";interface TranscriptProps {data: VideoData;@@ -121,6 +135,7 @@ const parseVTT = (vttContent: string): TranscriptEntry[] => {export const Transcript: React.FC<TranscriptProps> = ({ data, onSeek }) => {const user = useCurrentUser();+ const captionContext = useCaptionContext();const [transcriptData, setTranscriptData] = useState<TranscriptEntry[]>([]);const [selectedEntry, setSelectedEntry] = useState<number | null>(null);const [retryTriggered, setRetryTriggered] = useState(false);@@ -130,6 +145,34 @@ export const Transcript: React.FC<TranscriptProps> = ({ data, onSeek }) => {const [isCopying, setIsCopying] = useState(false);const [copyPressed, setCopyPressed] = useState(false);const [downloadPressed, setDownloadPressed] = useState(false);+ const [showLanguageMenu, setShowLanguageMenu] = useState(false);+ const languageMenuRef = useRef<HTMLDivElement>(null);++ const selectedLanguage =+ captionContext.selectedLanguage === "off"+ ? "original"+ : captionContext.selectedLanguage;+ const isTranslating = captionContext.isTranslating;+ const translatedContent = captionContext.translatedVttContent;++ useEffect(() => {+ const handleClickOutside = (event: MouseEvent) => {+ if (+ languageMenuRef.current &&+ !languageMenuRef.current.contains(event.target as Node)+ ) {+ setShowLanguageMenu(false);+ }+ };++ if (showLanguageMenu) {+ document.addEventListener("mousedown", handleClickOutside);+ }++ return () => {+ document.removeEventListener("mousedown", handleClickOutside);+ };+ }, [showLanguageMenu]);const {data: transcriptContent,@@ -166,11 +209,20 @@ export const Transcript: React.FC<TranscriptProps> = ({ data, onSeek }) => {});useEffect(() => {- if (transcriptContent) {+ const vttContent = captionContext.currentVttContent;+ if (vttContent) {+ const parsed = parseVTT(vttContent);+ setTranscriptData(parsed);+ } else if (transcriptContent && selectedLanguage === "original") {const parsed = parseVTT(transcriptContent);setTranscriptData(parsed);}- }, [transcriptContent]);+ }, [captionContext.currentVttContent, transcriptContent, selectedLanguage]);++ const handleLanguageChange = async (language: CaptionLanguage) => {+ setShowLanguageMenu(false);+ captionContext.setSelectedLanguage(language);+ };const isTranscriptionProcessing = useMemo(() => {if (@@ -326,9 +378,11 @@ export const Transcript: React.FC<TranscriptProps> = ({ data, onSeek }) => {const blob = new Blob([vttContent], { type: "text/vtt" });const url = URL.createObjectURL(blob);+ const langSuffix =+ selectedLanguage === "original" ? "" : `.${selectedLanguage}`;const link = document.createElement("a");link.href = url;- link.download = `transcript-${data.id}.vtt`;+ link.download = `transcript-${data.id}${langSuffix}.vtt`;document.body.appendChild(link);link.click();document.body.removeChild(link);@@ -341,7 +395,7 @@ export const Transcript: React.FC<TranscriptProps> = ({ data, onSeek }) => {}, 2000);};- const canEdit = user?.id === data.owner.id;+ const canEdit = user?.id === data.owner.id && selectedLanguage === "original";if (isTranscriptionProcessing && !hasTimedOut) {return (@@ -479,64 +533,153 @@ export const Transcript: React.FC<TranscriptProps> = ({ data, onSeek }) => {return (<div className="flex flex-col h-full"><div className="p-4 border-b border-gray-3">- <div className="flex gap-2 justify-end">- <Button- onClick={copyTranscriptToClipboard}- disabled={isCopying || transcriptData.length === 0}- variant="white"- size="xs"- spinner={isCopying}- >- {!copyPressed ? (- <Copy className="mr-1 w-3 h-3" />- ) : (- <svg- xmlns="http://www.w3.org/2000/svg"- width="12"- height="12"- viewBox="0 0 24 24"- fill="none"- stroke="currentColor"- strokeWidth="2"- strokeLinecap="round"- strokeLinejoin="round"- className="mr-1 w-3 h-3 svgpathanimation"- >- <path d="M20 6 9 17l-5-5" />- </svg>+ <div className="flex gap-2 justify-between items-center">+ <div className="relative" ref={languageMenuRef}>+ <button+ onClick={() => setShowLanguageMenu(!showLanguageMenu)}+ disabled={isTranslating || transcriptData.length === 0}+ className="flex items-center gap-1.5 px-2.5 py-1.5 text-xs font-medium rounded-lg border border-gray-3 bg-gray-1 hover:bg-gray-2 disabled:opacity-50 disabled:cursor-not-allowed transition-colors"+ type="button"+ >+ <Globe className="w-3 h-3 text-gray-9" />+ <span className="text-gray-12">+ {isTranslating+ ? "Translating..."+ : selectedLanguage === "original"+ ? "Original"+ : SUPPORTED_LANGUAGES[selectedLanguage]}+ </span>+ <ChevronDown className="w-3 h-3 text-gray-9" />+ </button>+ {showLanguageMenu && (+ <div className="absolute left-0 top-full mt-1 z-50 w-48 py-1 bg-gray-1 border border-gray-3 rounded-lg shadow-lg max-h-64 overflow-y-auto">+ <button+ onClick={() => handleLanguageChange("original")}+ className={`w-full px-3 py-1.5 text-left text-xs hover:bg-gray-2 transition-colors ${+ selectedLanguage === "original"+ ? "text-blue-500 font-medium"+ : "text-gray-12"+ }`}+ type="button"+ >+ Original+ </button>+ <div className="my-1 border-t border-gray-3" />+ {(+ Object.entries(SUPPORTED_LANGUAGES) as [+ LanguageCode,+ string,+ ][]+ ).map(([code, name]) => (+ <button+ key={code}+ onClick={() => handleLanguageChange(code)}+ className={`w-full px-3 py-1.5 text-left text-xs hover:bg-gray-2 transition-colors ${+ selectedLanguage === code+ ? "text-blue-500 font-medium"+ : "text-gray-12"+ }`}+ type="button"+ >+ {name}+ {captionContext.translatedVttContent.has(code) && (+ <span className="ml-1.5 text-gray-9">(cached)</span>+ )}+ </button>+ ))}+ </div>)}- {copyPressed ? "Copied" : "Copy Transcript"}- </Button>- <Button- onClick={downloadTranscriptFile}- disabled={transcriptData.length === 0}- variant="white"- size="xs"- >- {!downloadPressed ? (- <Download className="mr-1 w-3 h-3" />- ) : (+ </div>+ <div className="flex gap-2">+ <Button+ onClick={copyTranscriptToClipboard}+ disabled={isCopying || transcriptData.length === 0}+ variant="white"+ size="xs"+ spinner={isCopying}+ >+ {!copyPressed ? (+ <Copy className="mr-1 w-3 h-3" />+ ) : (+ <svg+ xmlns="http://www.w3.org/2000/svg"+ width="12"+ height="12"+ viewBox="0 0 24 24"+ fill="none"+ stroke="currentColor"+ strokeWidth="2"+ strokeLinecap="round"+ strokeLinejoin="round"+ className="mr-1 w-3 h-3 svgpathanimation"+ >+ <path d="M20 6 9 17l-5-5" />+ </svg>+ )}+ {copyPressed ? "Copied" : "Copy Transcript"}+ </Button>+ <Button+ onClick={downloadTranscriptFile}+ disabled={transcriptData.length === 0}+ variant="white"+ size="xs"+ >+ {!downloadPressed ? (+ <Download className="mr-1 w-3 h-3" />+ ) : (+ <svg+ xmlns="http://www.w3.org/2000/svg"+ width="12"+ height="12"+ viewBox="0 0 24 24"+ fill="none"+ stroke="currentColor"+ strokeWidth="2"+ strokeLinecap="round"+ strokeLinejoin="round"+ className="mr-1 w-3 h-3 svgpathanimation"+ >+ <path d="M20 6 9 17l-5-5" />+ </svg>+ )}+ {downloadPressed ? "Downloaded" : "Download"}+ </Button>+ </div>+ </div>+ </div>++ <div className="overflow-y-auto flex-1 relative">+ {isTranslating && (+ <div className="absolute inset-0 bg-gray-1/80 flex items-center justify-center z-10">+ <div className="text-center"><svgxmlns="http://www.w3.org/2000/svg"- width="12"- height="12"+ className="mx-auto w-8 h-8"viewBox="0 0 24 24"- fill="none"- stroke="currentColor"- strokeWidth="2"- strokeLinecap="round"- strokeLinejoin="round"- className="mr-1 w-3 h-3 svgpathanimation">- <path d="M20 6 9 17l-5-5" />+ <style>+ {"@keyframes spinner_AtaB{to{transform:rotate(360deg)}}"}+ </style>+ <path+ fill="#9CA3AF"+ 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="#9CA3AF"+ 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>- )}- {downloadPressed ? "Downloaded" : "Download"}- </Button>- </div>- </div>-- <div className="overflow-y-auto flex-1">+ <p className="mt-2 text-sm text-gray-11">+ Translating transcript...+ </p>+ </div>+ </div>+ )}<div className="p-4 space-y-3">{transcriptData.map((entry) => (<divdiff --git a/apps/web/app/s/[videoId]/_components/video/media-player.tsx b/apps/web/app/s/[videoId]/_components/video/media-player.tsxindex 269d5f31a..64a216cbd 100644--- a/apps/web/app/s/[videoId]/_components/video/media-player.tsx+++ b/apps/web/app/s/[videoId]/_components/video/media-player.tsx@@ -19,6 +19,7 @@ import {CheckIcon,DownloadIcon,FastForwardIcon,+ GlobeIcon,Loader2Icon,Maximize2Icon,Minimize2Icon,@@ -3063,10 +3064,22 @@ function MediaPlayerDownload(props: MediaPlayerDownloadProps) {);}+type CaptionLanguage = string;++interface CaptionOption {+ code: CaptionLanguage;+ name: string;+}+interface MediaPlayerSettingsProps extends MediaPlayerPlaybackSpeedProps {enhancedAudioStatus?: EnhancedAudioStatus | null;enhancedAudioEnabled?: boolean;setEnhancedAudioEnabled?: (enabled: boolean) => void;+ captionLanguage?: CaptionLanguage;+ onCaptionLanguageChange?: (language: CaptionLanguage) => void;+ availableCaptions?: CaptionOption[];+ isCaptionLoading?: boolean;+ hasCaptions?: boolean;}function MediaPlayerSettings(props: MediaPlayerSettingsProps) {@@ -3083,6 +3096,11 @@ function MediaPlayerSettings(props: MediaPlayerSettingsProps) {enhancedAudioStatus,enhancedAudioEnabled,setEnhancedAudioEnabled,+ captionLanguage = "original",+ onCaptionLanguageChange,+ availableCaptions = [],+ isCaptionLoading = false,+ hasCaptions = false,...settingsProps} = props;@@ -3289,6 +3307,53 @@ function MediaPlayerSettings(props: MediaPlayerSettingsProps) {</DropdownMenuSubContent></DropdownMenuSub>)}+ {hasCaptions && (+ <DropdownMenuSub>+ <DropdownMenuSubTrigger disabled={isCaptionLoading}>+ <span className="flex items-center gap-2 flex-1">+ <GlobeIcon className="size-4" />+ Captions+ </span>+ <Badge variant="outline" className="rounded-sm">+ {isCaptionLoading+ ? "..."+ : captionLanguage === "off"+ ? "Off"+ : captionLanguage === "original"+ ? "Original"+ : (availableCaptions.find(+ (c) => c.code === captionLanguage,+ )?.name ?? captionLanguage)}+ </Badge>+ </DropdownMenuSubTrigger>+ <DropdownMenuSubContent className="max-h-64 overflow-y-auto">+ <DropdownMenuItem+ className="justify-between"+ onSelect={() => onCaptionLanguageChange?.("off")}+ >+ Off+ {captionLanguage === "off" && <CheckIcon />}+ </DropdownMenuItem>+ <DropdownMenuItem+ className="justify-between"+ onSelect={() => onCaptionLanguageChange?.("original")}+ >+ Original+ {captionLanguage === "original" && <CheckIcon />}+ </DropdownMenuItem>+ {availableCaptions.map((caption) => (+ <DropdownMenuItem+ key={caption.code}+ className="justify-between"+ onSelect={() => onCaptionLanguageChange?.(caption.code)}+ >+ {caption.name}+ {captionLanguage === caption.code && <CheckIcon />}+ </DropdownMenuItem>+ ))}+ </DropdownMenuSubContent>+ </DropdownMenuSub>+ )}</DropdownMenuContent></DropdownMenu>);@@ -3430,3 +3495,5 @@ export {useMediaSelector as useMediaPlayer,useStoreSelector as useMediaPlayerStore,};++export type { CaptionOption, CaptionLanguage };diff --git a/bun.lock b/bun.lockindex fd657dbac..e46b40849 100644--- a/bun.lock+++ b/bun.lock@@ -1,5 +1,6 @@{"lockfileVersion": 1,+ "configVersion": 0,"workspaces": {"": {"name": "cap",