Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions .github/workflows/ci.yml
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
166 changes: 166 additions & 0 deletions apps/web/__tests__/unit/clock-hours.test.ts
Original file line number Diff line number Diff line change
@@ -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<HTMLVideoElement | null> = {
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");
});
});
14 changes: 13 additions & 1 deletion apps/web/__tests__/unit/speed-controller.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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);
Expand All @@ -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 },
});
Expand Down Expand Up @@ -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();
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -28,6 +28,7 @@ import {
PopoverContent,
PopoverTrigger,
} from "@/components/ui/popover";
import { formatClock } from "@/lib/player-time";

const phaseMessages: Partial<Record<RecorderPhase, string>> = {
recording: "Recording",
Expand All @@ -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;
Expand Down Expand Up @@ -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 = () => {
Expand Down
12 changes: 2 additions & 10 deletions apps/web/app/s/[videoId]/_components/early-playback.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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.

Expand Down Expand Up @@ -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,
Expand Down
13 changes: 1 addition & 12 deletions apps/web/app/s/[videoId]/_components/timeline/timeline-format.ts
Original file line number Diff line number Diff line change
@@ -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";
22 changes: 4 additions & 18 deletions apps/web/app/s/[videoId]/edit/EditVideoClient.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -38,6 +38,7 @@ import {
restoreVideoToOriginal,
saveVideoEdits,
} from "@/actions/videos/save-edits";
import { formatClock, formatClockWithHundredths } from "@/lib/player-time";
import {
clearTimelineDraft,
getTimelineDraftKey,
Expand Down Expand Up @@ -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));
Expand Down Expand Up @@ -1903,7 +1889,7 @@ export function EditVideoClient({
}}
>
<div className="absolute left-1/2 top-0 -translate-x-1/2 whitespace-nowrap rounded-md bg-white px-1.5 py-0.5 font-mono text-[10px] font-semibold tabular-nums text-black shadow-[0_2px_8px_rgba(0,0,0,0.45)]">
{formatTimeDetailed(outputPlayhead)}
{formatClockWithHundredths(outputPlayhead)}
</div>

<div className="absolute left-1/2 top-6 size-2.5 -translate-x-1/2 rounded-full bg-white shadow-[0_0_0_1.5px_rgba(0,0,0,0.55),0_2px_4px_rgba(0,0,0,0.45)]" />
Expand All @@ -1927,7 +1913,7 @@ export function EditVideoClient({
<div className="flex items-center gap-3">
<div className="inline-flex items-baseline gap-1.5 font-mono text-[12px] tabular-nums">
<span className="font-semibold text-gray-12">
{formatTime(outputPlayhead)}
{formatClock(outputPlayhead)}
</span>
<span className="text-gray-9">/</span>
<span
Expand All @@ -1937,7 +1923,7 @@ export function EditVideoClient({
: "text-gray-10"
}
>
{formatTime(outputDuration)}
{formatClock(outputDuration)}
</span>
</div>

Expand Down
14 changes: 4 additions & 10 deletions apps/web/app/s/[videoId]/edit/TranscriptSidebar.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -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<ReturnType<typeof getEditTranscript>>;
Expand All @@ -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(
Expand Down Expand Up @@ -155,10 +149,10 @@ const TranscriptGroupRow = memo(function TranscriptGroupRow({
<button
type="button"
onClick={() => onSeek(group.startIndex)}
title={`Play from ${formatTimestamp(group.startMs)}`}
title={`Play from ${formatClock(group.startMs / 1000)}`}
className="w-9 shrink-0 text-left font-mono text-[10px] leading-none tabular-nums text-gray-8 transition-colors hover:text-blue-500"
>
{formatTimestamp(group.startMs)}
{formatClock(group.startMs / 1000)}
</button>
<p className="min-w-0 flex-1 select-none text-[13.5px] leading-[26px] text-gray-11">
{words
Expand Down Expand Up @@ -643,7 +637,7 @@ export function TranscriptSidebar({
Transcript
</h2>
<p className="mt-0.5 text-[11px] tabular-nums text-gray-9">
{formatTimestamp(transcript.durationMs)} ·{" "}
{formatClock(transcript.durationMs / 1000)} ·{" "}
{transcript.words.length} words
</p>
</div>
Expand Down
Loading
Loading