diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index bee6043e00c..6c13776ab43 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -105,6 +105,7 @@ jobs: __tests__/unit/caps-analytics-round-trips.test.ts __tests__/unit/caps-keyboard.test.ts __tests__/unit/caption-translation-ownership.test.ts + __tests__/unit/clock-hours.test.ts __tests__/unit/comment-composer-composition.test.ts __tests__/unit/currency-hook.test.ts __tests__/unit/dashboard-analytics-cap-access.test.ts diff --git a/apps/web/__tests__/unit/clock-hours.test.ts b/apps/web/__tests__/unit/clock-hours.test.ts new file mode 100644 index 00000000000..65bafa47b9e --- /dev/null +++ b/apps/web/__tests__/unit/clock-hours.test.ts @@ -0,0 +1,166 @@ +// @vitest-environment jsdom + +import { Video } from "@cap/web-domain"; +import { act, createElement, type RefObject } from "react"; +import { createRoot, type Root } from "react-dom/client"; +import { afterEach, describe, expect, it, vi } from "vitest"; + +const mocks = vi.hoisted(() => ({ + getEditTranscript: vi.fn(), +})); + +vi.mock("@cap/env", () => ({ + serverEnv: () => ({ WEB_URL: "https://cap.so" }), +})); + +vi.mock("@/actions/videos/get-edit-transcript", () => ({ + getEditTranscript: mocks.getEditTranscript, + requestEditTranscript: vi.fn(), +})); + +vi.mock("@/app/s/[videoId]/edit/use-active-transcript-word-index", () => ({ + useActiveTranscriptWordIndex: () => -1, +})); + +vi.mock("@virtual-grid/react", () => ({ + useVirtualizer: ({ count }: { count: number }) => ({ + getTotalSize: () => count * 100, + getVirtualItems: () => + Array.from({ length: count }, (_, index) => ({ + index, + key: index, + start: index * 100, + })), + measureElement: vi.fn(), + scrollToIndex: vi.fn(), + }), +})); + +import { TranscriptSidebar } from "@/app/s/[videoId]/edit/TranscriptSidebar"; +import { formatClock, formatClockWithHundredths } from "@/lib/player-time"; +import { buildSlackVideoBlock } from "@/lib/slack/unfurl"; + +describe("formatClock", () => { + it("keeps M:SS under an hour", () => { + expect(formatClock(0)).toBe("0:00"); + expect(formatClock(44.9)).toBe("0:44"); + expect(formatClock(95)).toBe("1:35"); + expect(formatClock(3599.9)).toBe("59:59"); + }); + + it("rolls over into hours instead of counting past 59 minutes", () => { + expect(formatClock(3600)).toBe("1:00:00"); + expect(formatClock(3905)).toBe("1:05:05"); + expect(formatClock(36000)).toBe("10:00:00"); + }); + + it("falls back to zero for negative or non-finite input", () => { + expect(formatClock(-3)).toBe("0:00"); + expect(formatClock(Number.NaN)).toBe("0:00"); + expect(formatClock(Number.POSITIVE_INFINITY)).toBe("0:00"); + }); +}); + +describe("formatClockWithHundredths", () => { + it("keeps MM:SS.ss under an hour and adds hours after", () => { + expect(formatClockWithHundredths(0)).toBe("00:00.00"); + expect(formatClockWithHundredths(75.25)).toBe("01:15.25"); + expect(formatClockWithHundredths(3599.5)).toBe("59:59.50"); + expect(formatClockWithHundredths(3600)).toBe("1:00:00.00"); + expect(formatClockWithHundredths(3905.5)).toBe("1:05:05.50"); + }); +}); + +describe("Slack previews", () => { + const preview = (duration: number) => + buildSlackVideoBlock({ + video: { + id: Video.VideoId.make("abc123"), + name: "Cap walkthrough", + ownerId: "owner123", + ownerName: "Richie", + sourceType: "desktopMP4", + width: 1920, + height: 1080, + duration, + }, + shareUrl: "https://cap.so/s/abc123", + webUrl: "https://cap.so", + }).description.text; + + it("shows hours for recordings an hour or longer", () => { + expect(preview(64)).toBe("Watch this 1:04 recording on Cap"); + expect(preview(3905)).toBe("Watch this 1:05:05 recording on Cap"); + expect(preview(3904.6)).toBe("Watch this 1:05:05 recording on Cap"); + }); +}); + +describe("web editor transcript", () => { + let container: HTMLDivElement; + let root: Root; + + afterEach(async () => { + await act(async () => root.unmount()); + container.remove(); + vi.unstubAllGlobals(); + vi.clearAllMocks(); + }); + + it("shows hours on lines past the hour mark", async () => { + vi.stubGlobal("IS_REACT_ACT_ENVIRONMENT", true); + vi.stubGlobal("requestAnimationFrame", (callback: FrameRequestCallback) => { + callback(0); + return 1; + }); + HTMLElement.prototype.scrollIntoView = vi.fn(); + const word = (id: string, text: string, startMs: number) => ({ + id, + text, + startMs, + endMs: startMs + 400, + confidence: 1, + speaker: null, + channel: null, + }); + mocks.getEditTranscript.mockResolvedValue({ + status: "ready", + transcript: { + version: 3 as const, + speechModelUsed: "fixture", + durationMs: 3_910_000, + languageCode: "en", + words: [ + word("word-0", "Early.", 95_000), + word("word-1", "Late.", 3_905_000), + ], + }, + }); + container = document.createElement("div"); + document.body.append(container); + root = createRoot(container); + const videoRef: RefObject = { + current: document.createElement("video"), + }; + + await act(async () => { + root.render( + createElement(TranscriptSidebar, { + videoId: "video-id" as Video.VideoId, + videoRef, + keepRanges: [{ start: 0, end: 3910 }], + onDeleteRanges: vi.fn(), + }), + ); + }); + for (let attempt = 0; attempt < 50; attempt++) { + if (container.textContent?.includes("Late.")) break; + await act(async () => { + await new Promise((resolve) => setTimeout(resolve, 10)); + }); + } + + expect(container.textContent).toContain("1:35"); + expect(container.textContent).toContain("1:05:05"); + expect(container.textContent).not.toContain("65:05"); + }); +}); diff --git a/apps/web/__tests__/unit/speed-controller.test.ts b/apps/web/__tests__/unit/speed-controller.test.ts index b3c26efbd78..46f6b3bd4b1 100644 --- a/apps/web/__tests__/unit/speed-controller.test.ts +++ b/apps/web/__tests__/unit/speed-controller.test.ts @@ -43,8 +43,10 @@ let downloads: string[]; let originalCreate: typeof URL.createObjectURL; let originalRevoke: typeof URL.revokeObjectURL; let captureDescriptor: PropertyDescriptor | undefined; +let videoDuration: number; beforeEach(() => { + videoDuration = 3; vi.stubGlobal("IS_REACT_ACT_ENVIRONMENT", false); vi.stubGlobal("MediaRecorder", Recorder); vi.stubGlobal("requestAnimationFrame", () => 1); @@ -61,7 +63,7 @@ beforeEach(() => { const element = create(tag, options); if (element instanceof HTMLVideoElement) { Object.defineProperties(element, { - duration: { value: 3 }, + duration: { value: videoDuration }, videoWidth: { value: 320 }, videoHeight: { value: 180 }, }); @@ -150,6 +152,16 @@ async function finishProcessing() { ); } +it("shows hours for a video an hour or longer", async () => { + videoDuration = 5_400; + await selectFile(); + videos[0]?.dispatchEvent(new Event("loadedmetadata")); + await vi.waitFor(() => + expect(container.textContent).toContain("Duration: 1:30:00"), + ); + expect(container.textContent).toContain("Estimated output duration: 1:00:00"); +}); + it("keeps the selected file and speed fixed while processing", async () => { const input = await selectFile(); button("Speed Up Video (1.5x)").click(); diff --git a/apps/web/app/(org)/dashboard/caps/components/web-recorder-dialog/InProgressRecordingBar.tsx b/apps/web/app/(org)/dashboard/caps/components/web-recorder-dialog/InProgressRecordingBar.tsx index 08a52b42174..874e6499e6d 100644 --- a/apps/web/app/(org)/dashboard/caps/components/web-recorder-dialog/InProgressRecordingBar.tsx +++ b/apps/web/app/(org)/dashboard/caps/components/web-recorder-dialog/InProgressRecordingBar.tsx @@ -28,6 +28,7 @@ import { PopoverContent, PopoverTrigger, } from "@/components/ui/popover"; +import { formatClock } from "@/lib/player-time"; const phaseMessages: Partial> = { recording: "Recording", @@ -43,13 +44,6 @@ const clamp = (value: number, min: number, max: number) => { return Math.min(Math.max(value, min), max); }; -const formatDuration = (durationMs: number) => { - const totalSeconds = Math.max(0, Math.floor(durationMs / 1000)); - const minutes = Math.floor(totalSeconds / 60); - const seconds = totalSeconds % 60; - return `${minutes}:${seconds.toString().padStart(2, "0")}`; -}; - interface InProgressRecordingBarProps { phase: RecorderPhase; durationMs: number; @@ -198,7 +192,7 @@ export const InProgressRecordingBar = ({ const canStop = (phase === "recording" || isPaused) && !isErrorState; const showTimer = (phase === "recording" || isPaused) && !isErrorState; const statusText = showTimer - ? formatDuration(durationMs) + ? formatClock(durationMs / 1000) : (phaseMessages[phase] ?? "Processing"); const handleStop = () => { diff --git a/apps/web/app/s/[videoId]/_components/early-playback.ts b/apps/web/app/s/[videoId]/_components/early-playback.ts index 77f9d6be408..be52ce65ba2 100644 --- a/apps/web/app/s/[videoId]/_components/early-playback.ts +++ b/apps/web/app/s/[videoId]/_components/early-playback.ts @@ -3,6 +3,8 @@ import { type RefObject, useEffect, useRef, useState } from "react"; import { setFullLength } from "./early-length"; +export { formatClock } from "@/lib/player-time"; + // The playlist only holds what has uploaded, so a seek past it is held until // that part arrives instead of letting the browser clamp it to the end. @@ -114,16 +116,6 @@ export function isAtUploadEdge({ ); } -export function formatClock(seconds: number): string { - const whole = Math.max(0, Math.floor(seconds)); - const hours = Math.floor(whole / 3600); - const minutes = Math.floor((whole % 3600) / 60); - const secs = String(whole % 60).padStart(2, "0"); - return hours > 0 - ? `${hours}:${String(minutes).padStart(2, "0")}:${secs}` - : `${minutes}:${secs}`; -} - export function useEarlyPlayback({ enabled, statusUrl, diff --git a/apps/web/app/s/[videoId]/_components/timeline/timeline-format.ts b/apps/web/app/s/[videoId]/_components/timeline/timeline-format.ts index fb9fe9e3adb..5501c982b8c 100644 --- a/apps/web/app/s/[videoId]/_components/timeline/timeline-format.ts +++ b/apps/web/app/s/[videoId]/_components/timeline/timeline-format.ts @@ -1,12 +1 @@ -/** `M:SS`, or `H:MM:SS` once the video is an hour or longer. */ -export const formatClock = (seconds: number): string => { - const total = - Number.isFinite(seconds) && seconds > 0 ? Math.floor(seconds) : 0; - const secs = total % 60; - const mins = Math.floor(total / 60) % 60; - const hours = Math.floor(total / 3600); - const pad = (value: number) => String(value).padStart(2, "0"); - return hours > 0 - ? `${hours}:${pad(mins)}:${pad(secs)}` - : `${mins}:${pad(secs)}`; -}; +export { formatClock } from "@/lib/player-time"; diff --git a/apps/web/app/s/[videoId]/edit/EditVideoClient.tsx b/apps/web/app/s/[videoId]/edit/EditVideoClient.tsx index 8fd02c2be21..8eb284c4b07 100644 --- a/apps/web/app/s/[videoId]/edit/EditVideoClient.tsx +++ b/apps/web/app/s/[videoId]/edit/EditVideoClient.tsx @@ -38,6 +38,7 @@ import { restoreVideoToOriginal, saveVideoEdits, } from "@/actions/videos/save-edits"; +import { formatClock, formatClockWithHundredths } from "@/lib/player-time"; import { clearTimelineDraft, getTimelineDraftKey, @@ -112,21 +113,6 @@ type TimelineThumbnailRequest = { time: number; }; -function formatTime(seconds: number) { - const safeSeconds = Math.max(0, Math.floor(seconds)); - const minutes = Math.floor(safeSeconds / 60); - const remainingSeconds = safeSeconds % 60; - return `${minutes}:${String(remainingSeconds).padStart(2, "0")}`; -} - -function formatTimeDetailed(seconds: number) { - const safe = Math.max(0, seconds); - const minutes = Math.floor(safe / 60); - const remainingSeconds = safe - minutes * 60; - const padded = remainingSeconds.toFixed(2).padStart(5, "0"); - return `${String(minutes).padStart(2, "0")}:${padded}`; -} - function getTimePercent(time: number, duration: number) { if (duration <= 0) return 0; return Math.min(100, Math.max(0, (time / duration) * 100)); @@ -1903,7 +1889,7 @@ export function EditVideoClient({ }} >
- {formatTimeDetailed(outputPlayhead)} + {formatClockWithHundredths(outputPlayhead)}
@@ -1927,7 +1913,7 @@ export function EditVideoClient({
- {formatTime(outputPlayhead)} + {formatClock(outputPlayhead)} / - {formatTime(outputDuration)} + {formatClock(outputDuration)}
diff --git a/apps/web/app/s/[videoId]/edit/TranscriptSidebar.tsx b/apps/web/app/s/[videoId]/edit/TranscriptSidebar.tsx index 0c54fcf6215..4e8956dd60c 100644 --- a/apps/web/app/s/[videoId]/edit/TranscriptSidebar.tsx +++ b/apps/web/app/s/[videoId]/edit/TranscriptSidebar.tsx @@ -38,6 +38,7 @@ import { planFillerCuts, planTranscriptCut, } from "@/lib/edit-transcript"; +import { formatClock } from "@/lib/player-time"; import { useActiveTranscriptWordIndex } from "./use-active-transcript-word-index"; type TranscriptResponse = Awaited>; @@ -61,13 +62,6 @@ const SKELETON_LINE_WIDTHS = [ ["w-10/12", "w-1/2"], ]; -function formatTimestamp(milliseconds: number) { - const totalSeconds = Math.max(0, Math.floor(milliseconds / 1000)); - const minutes = Math.floor(totalSeconds / 60); - const seconds = totalSeconds % 60; - return `${minutes}:${String(seconds).padStart(2, "0")}`; -} - function isTimeKept(timeMs: number, keepRanges: readonly VideoEditRange[]) { const timeSeconds = timeMs / 1000; return keepRanges.some( @@ -155,10 +149,10 @@ const TranscriptGroupRow = memo(function TranscriptGroupRow({

{words @@ -643,7 +637,7 @@ export function TranscriptSidebar({ Transcript

- {formatTimestamp(transcript.durationMs)} ·{" "} + {formatClock(transcript.durationMs / 1000)} ·{" "} {transcript.words.length} words

diff --git a/apps/web/components/tools/SpeedController.tsx b/apps/web/components/tools/SpeedController.tsx index 1cac5d906ae..438cc93c83d 100644 --- a/apps/web/components/tools/SpeedController.tsx +++ b/apps/web/components/tools/SpeedController.tsx @@ -3,6 +3,7 @@ import { Button } from "@cap/ui"; import { useEffect, useRef, useState } from "react"; import { trackEvent } from "@/app/utils/analytics"; +import { formatClock } from "@/lib/player-time"; const SPEED_OPTIONS = [ { value: 0.25, label: "0.25x (Very Slow)" }, @@ -504,16 +505,10 @@ export const SpeedController = () => { } }; - const formatDuration = (seconds: number) => { - const minutes = Math.floor(seconds / 60); - const remainingSeconds = Math.floor(seconds % 60); - return `${minutes}:${remainingSeconds.toString().padStart(2, "0")}`; - }; - const getEstimatedOutputDuration = () => { if (!videoInfo) return null; const estimatedDuration = videoInfo.duration / selectedSpeed; - return formatDuration(estimatedDuration); + return formatClock(estimatedDuration); }; useEffect(() => { @@ -623,7 +618,7 @@ export const SpeedController = () => {

{videoInfo && (
-

Duration: {formatDuration(videoInfo.duration)}

+

Duration: {formatClock(videoInfo.duration)}

Resolution: {videoInfo.dimensions}

Estimated output duration: {getEstimatedOutputDuration()} diff --git a/apps/web/components/tools/TrimmingTool.tsx b/apps/web/components/tools/TrimmingTool.tsx index 143354143d9..ef8dddead0d 100644 --- a/apps/web/components/tools/TrimmingTool.tsx +++ b/apps/web/components/tools/TrimmingTool.tsx @@ -3,6 +3,7 @@ import { Button } from "@cap/ui"; import { useEffect, useRef, useState } from "react"; import { trackEvent } from "@/app/utils/analytics"; +import { formatClock } from "@/lib/player-time"; const SUPPORTED_VIDEO_FORMATS = ["mp4", "webm", "mov", "avi", "mkv"]; @@ -266,12 +267,6 @@ export const TrimmingTool = () => { })); }; - const formatTime = (seconds: number) => { - const minutes = Math.floor(seconds / 60); - const remainingSeconds = Math.floor(seconds % 60); - return `${minutes}:${remainingSeconds.toString().padStart(2, "0")}`; - }; - const trimVideo = async () => { if (!fileState.file || !videoState.info) return; @@ -852,12 +847,12 @@ export const TrimmingTool = () => {

- Current: {formatTime(videoState.currentTime)} + Current: {formatClock(videoState.currentTime)}
Duration:{" "} {videoState.info - ? formatTime(videoState.info.duration) + ? formatClock(videoState.info.duration) : "--:--"}
@@ -865,7 +860,7 @@ export const TrimmingTool = () => {
{
{
Selected segment:{" "} - {formatTime(trimState.startTime)} to{" "} - {formatTime(trimState.endTime)} ( - {formatTime(trimState.endTime - trimState.startTime)} duration) + {formatClock(trimState.startTime)} to{" "} + {formatClock(trimState.endTime)} ( + {formatClock(trimState.endTime - trimState.startTime)} duration)
diff --git a/apps/web/lib/mcp-card-client.ts b/apps/web/lib/mcp-card-client.ts index 41dc9971337..287ccb204fd 100644 --- a/apps/web/lib/mcp-card-client.ts +++ b/apps/web/lib/mcp-card-client.ts @@ -1,4 +1,5 @@ import { App, applyDocumentTheme } from "@modelcontextprotocol/ext-apps"; +import { formatClock } from "./player-time"; type Cue = { startMs: number; text: string; url: string }; type Card = { @@ -46,8 +47,7 @@ const render = (data: Card) => { button.type = "button"; button.className = "cue"; const time = document.createElement("strong"); - const seconds = Math.floor(cue.startMs / 1_000); - time.textContent = `${Math.floor(seconds / 60)}:${String(seconds % 60).padStart(2, "0")}`; + time.textContent = formatClock(cue.startMs / 1_000); const text = document.createElement("span"); text.textContent = cue.text; button.append(time, text); diff --git a/apps/web/lib/mcp-card-html.json b/apps/web/lib/mcp-card-html.json index 6d0c7f4ce84..79d4bb6ed1b 100644 --- a/apps/web/lib/mcp-card-html.json +++ b/apps/web/lib/mcp-card-html.json @@ -1,3 +1,3 @@ { - "html": "
Cap

Recording

Loading recording context…

Transcript

" + "html": "
Cap

Recording

Loading recording context…

Transcript

" } diff --git a/apps/web/lib/player-time.ts b/apps/web/lib/player-time.ts index 48129686756..2d1fe91147f 100644 --- a/apps/web/lib/player-time.ts +++ b/apps/web/lib/player-time.ts @@ -13,3 +13,25 @@ export function formatPlayerTime(totalSeconds: number): string { return `${minutes.toString().padStart(2, "0")}:${paddedSeconds}`; } + +export function formatClock(seconds: number): string { + const total = + Number.isFinite(seconds) && seconds > 0 ? Math.floor(seconds) : 0; + const secs = total % 60; + const mins = Math.floor(total / 60) % 60; + const hours = Math.floor(total / 3600); + const pad = (value: number) => String(value).padStart(2, "0"); + return hours > 0 + ? `${hours}:${pad(mins)}:${pad(secs)}` + : `${mins}:${pad(secs)}`; +} + +export function formatClockWithHundredths(seconds: number): string { + const safe = Math.max(0, seconds); + const hours = Math.floor(safe / 3600); + const minutes = Math.floor((safe - hours * 3600) / 60); + const remainingSeconds = safe - hours * 3600 - minutes * 60; + const padded = remainingSeconds.toFixed(2).padStart(5, "0"); + const clock = `${String(minutes).padStart(2, "0")}:${padded}`; + return hours > 0 ? `${hours}:${clock}` : clock; +} diff --git a/apps/web/lib/slack/unfurl.ts b/apps/web/lib/slack/unfurl.ts index 042fad45dd4..70d902f0d5a 100644 --- a/apps/web/lib/slack/unfurl.ts +++ b/apps/web/lib/slack/unfurl.ts @@ -1,5 +1,6 @@ import { Video } from "@cap/web-domain"; import { parseCapShareUrl } from "@/lib/oembed"; +import { formatClock } from "@/lib/player-time"; import { getPublicShareVideo, type PublicShareVideo, @@ -41,10 +42,7 @@ const truncate = (value: string, maxLength: number) => const formatDuration = (duration: number | null) => { if (!duration || duration <= 0) return "Watch this recording on Cap"; - const seconds = Math.round(duration); - const minutes = Math.floor(seconds / 60); - const remainder = seconds % 60; - return `Watch this ${minutes}:${remainder.toString().padStart(2, "0")} recording on Cap`; + return `Watch this ${formatClock(Math.round(duration))} recording on Cap`; }; export const buildSlackVideoBlock = ({