Open source Loom alternative. Beautiful, shareable screen recordings.
Rust appcapcossloommacnextjsnextjs15open-sourceossreactrecordrustscreen-capturescreen-recorderscreenshotsolidjstauritauri-apptypescriptvite
perf(web): avoid rebuilding unchanged transcript rows
Aditya Garud0c3367d10dae
diff --git a/apps/web/__tests__/unit/share-transcript-rendering.test.ts b/apps/web/__tests__/unit/share-transcript-rendering.test.tsnew file mode 100644index 000000000..900746d2c--- /dev/null+++ b/apps/web/__tests__/unit/share-transcript-rendering.test.ts@@ -0,0 +1,365 @@+// @vitest-environment jsdom++import {+ act,+ createElement,+ Profiler,+ type ProfilerOnRenderCallback,+} from "react";+import { createRoot, type Root } from "react-dom/client";+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";+import { Transcript } from "@/app/s/[videoId]/_components/tabs/Transcript";+import { parseTranscriptVTT } from "@/app/s/[videoId]/_components/utils/parse-transcript-vtt";+import type { VideoData } from "@/app/s/[videoId]/types";++const mocks = vi.hoisted(() => ({+ content: "",+ rowRenders: 0,+ userId: "owner",+ language: "original",+ edit: vi.fn(),+ invalidate: vi.fn(),+}));++vi.mock("@cap/ui", () => ({ Button: () => null }));+vi.mock("@tanstack/react-query", () => ({+ useQueryClient: () => ({ invalidateQueries: vi.fn() }),+ useMutation: () => ({ isPending: false, isError: false }),+}));+vi.mock("hooks/use-transcript", () => ({+ useTranscript: () => ({ data: mocks.content, isLoading: false }),+ useInvalidateTranscript: () => mocks.invalidate,+}));+vi.mock("hooks/use-live-transcript", () => ({+ useLiveTranscript: () => ({ data: null }),+}));+vi.mock("@/app/Layout/AuthContext", () => ({+ useCurrentUser: () => ({ id: mocks.userId }),+}));+vi.mock("@/app/s/[videoId]/_components/CaptionContext", () => ({+ useCaptionContext: () => ({+ selectedLanguage: mocks.language,+ currentVttContent: mocks.content,+ availableTranslations: [],+ }),+}));+vi.mock("@/actions/videos/edit-transcript", () => ({+ editTranscriptEntry: mocks.edit,+}));+vi.mock("lucide-react", async (importOriginal) => {+ const icons = await importOriginal<typeof import("lucide-react")>();+ return {+ ...icons,+ Edit3: (props: Parameters<typeof icons.Edit3>[0]) => {+ mocks.rowRenders++;+ return createElement(icons.Edit3, props);+ },+ };+});++const video: VideoData = {+ id: "share-transcript" as VideoData["id"],+ owner: { id: "owner" as VideoData["owner"]["id"], isPro: true },+ orgId: "organization" as VideoData["orgId"],+ name: "One-hour recording",+ source: { type: "desktopMP4" },+ duration: 3600,+ width: 1920,+ height: 1080,+ fps: 30,+ public: true,+ isScreenshot: false,+ skipProcessing: false,+ createdAt: new Date("2026-01-01"),+ updatedAt: new Date("2026-01-01"),+ effectiveCreatedAt: new Date("2026-01-01"),+ transcriptionStatus: "COMPLETE",+ bucket: null,+ storageIntegrationId: null,+ metadata: null,+ settings: null,+ folderId: null,+ password: null,+ xStreamInfo: null,+ firstViewEmailSentAt: null,+ awsRegion: null,+ awsBucket: null,+ videoStartTime: null,+ audioStartTime: null,+ jobId: null,+ jobStatus: null,+};++function transcript(cues: number) {+ const timestamp = (seconds: number) =>+ `${new Date(seconds * 1000).toISOString().slice(11, 19)}.000`;+ return `WEBVTT\n\n${Array.from(+ { length: cues },+ (_, i) =>+ `${i + 1}\n${timestamp(i * 3)} --> ${timestamp((i + 1) * 3)}\nCue ${i + 1}: We reviewed the recording and agreed on the next steps.\n`,+ ).join("\n")}`;+}++let root: Root;+let container: HTMLDivElement;+let durations: number[];+const onSeek = vi.fn();+const onRender: ProfilerOnRenderCallback = (_id, phase, actualDuration) => {+ if (phase === "update") durations.push(actualDuration);+};++beforeEach(() => {+ vi.stubGlobal("IS_REACT_ACT_ENVIRONMENT", true);+ mocks.content = transcript(1200);+ mocks.userId = "owner";+ mocks.language = "original";+ mocks.rowRenders = 0;+ mocks.edit.mockResolvedValue({ success: true });+ durations = [];+ container = document.createElement("div");+ document.body.append(container);+ root = createRoot(container);+});++afterEach(async () => {+ await act(async () => root.unmount());+ container.remove();+ vi.unstubAllGlobals();+});++async function render(seek = onSeek) {+ await act(async () => {+ root.render(+ createElement(+ Profiler,+ { id: video.id, onRender },+ createElement(Transcript, { data: video, onSeek: seek }),+ ),+ );+ });+}++function cue(index: number) {+ const button = Array.from(container.querySelectorAll("button")).find(+ (button) => button.textContent?.includes(`Cue ${index}:`),+ );+ if (!button) throw new Error(`Missing cue ${index}`);+ return button;+}++async function click(button: HTMLElement) {+ await act(async () => button.click());+}++function button(text: string) {+ const button = Array.from(container.querySelectorAll("button")).find(+ (button) => button.textContent === text,+ );+ if (!button) throw new Error(`Missing button ${text}`);+ return button;+}++async function editCue(index: number) {+ const edit = cue(index).parentElement?.querySelector<HTMLButtonElement>(+ 'button[title="Edit transcript entry"]',+ );+ if (!edit) throw new Error("Missing edit button");+ await click(edit);+}++async function type(text: string) {+ const textarea = container.querySelector("textarea");+ if (!textarea) throw new Error("Missing transcript editor");+ await act(async () => {+ Object.getOwnPropertyDescriptor(+ HTMLTextAreaElement.prototype,+ "value",+ )?.set?.call(textarea, text);+ textarea.dispatchEvent(new Event("input", { bubbles: true }));+ });+}++describe("share transcript rendering", () => {+ it("only renders the changed rows when selecting a cue in a one-hour transcript", async () => {+ await render();+ expect(mocks.rowRenders).toBe(1200);+ const rows = () =>+ Array.from(+ container.querySelectorAll('button[title="Edit transcript entry"]'),+ (button) => button.parentElement?.textContent,+ );+ const expectedRows = parseTranscriptVTT(mocks.content).map(+ (entry) => `${entry.timestamp}${entry.text}`,+ );+ expect(rows()).toEqual(expectedRows);+ mocks.rowRenders = 0;+ await click(cue(300));+ expect(onSeek).toHaveBeenLastCalledWith(897);+ expect(cue(300).parentElement?.className).toContain("bg-gray-3");+ expect(mocks.rowRenders).toBe(1);+ mocks.rowRenders = 0;+ await click(cue(600));+ expect(cue(300).parentElement?.className).not.toContain("bg-gray-3");+ expect(cue(600).parentElement?.className).toContain("bg-gray-3");+ expect(mocks.rowRenders).toBe(2);+ expect(rows()).toEqual(expectedRows);+ });++ it("does not render other rows while typing and preserves save and cancel", async () => {+ await render();+ await editCue(300);+ mocks.rowRenders = 0;+ await type("Updated cue");+ expect(container.querySelector("textarea")?.value).toBe("Updated cue");+ expect(mocks.rowRenders).toBe(0);+ await click(button("Save"));+ expect(mocks.edit).toHaveBeenCalledWith(video.id, 300, "Updated cue");+ expect(mocks.invalidate).toHaveBeenCalledWith(video.id);+ expect(container.textContent).toContain("Updated cue");+ expect(container.querySelector("textarea")).toBeNull();+ await editCue(600);+ await type("Discarded edit");+ await click(button("Cancel"));+ expect(cue(600).textContent).toContain("We reviewed the recording");+ expect(container.textContent).not.toContain("Discarded edit");+ expect(mocks.edit).toHaveBeenCalledTimes(1);+ });++ it("keeps an unsuccessful edit open without changing the other cues", async () => {+ mocks.content = transcript(3);+ mocks.edit.mockResolvedValue({ success: false, message: "Save failed" });+ vi.spyOn(console, "error").mockImplementation(() => {});+ await render();+ await editCue(2);+ await type("Unsaved edit");+ await click(button("Save"));+ expect(container.querySelector("textarea")?.value).toBe("Unsaved edit");+ expect(button("Save").disabled).toBe(false);+ expect(cue(1).textContent).toContain("We reviewed the recording");+ expect(cue(3).textContent).toContain("We reviewed the recording");+ expect(mocks.invalidate).not.toHaveBeenCalled();+ });++ it("refreshes cue content, language, permissions and seek callbacks", async () => {+ mocks.content = transcript(3);+ await render();+ mocks.content = mocks.content.replace("Cue 2:", "Translated Cue 2:");+ mocks.language = "fr";+ await render();+ expect(container.textContent).toContain("Translated Cue 2:");+ expect(+ container.querySelector('button[title="Edit transcript entry"]'),+ ).toBeNull();+ await click(cue(1));+ expect(onSeek).toHaveBeenLastCalledWith(0);+ mocks.language = "original";+ mocks.userId = "viewer";+ await render();+ expect(+ container.querySelector('button[title="Edit transcript entry"]'),+ ).toBeNull();+ mocks.userId = "owner";+ await render();+ expect(+ container.querySelectorAll('button[title="Edit transcript entry"]'),+ ).toHaveLength(3);+ const updatedSeek = vi.fn();+ await render(updatedSeek);+ await click(cue(2));+ expect(updatedSeek).toHaveBeenCalledWith(3);+ });++ it("starts with the new cue's text when switching editors", async () => {+ mocks.content = transcript(3);+ await render();+ await editCue(1);+ await type("Draft for cue one");+ await editCue(2);+ expect(container.querySelector("textarea")?.value).toMatch(/^Cue 2:/);+ await click(button("Cancel"));+ expect(cue(1).textContent).toContain("We reviewed the recording");+ expect(mocks.edit).not.toHaveBeenCalled();+ });++ it("keeps save and cancel disabled until a pending save completes", async () => {+ mocks.content = transcript(3);+ let finish!: (result: { success: boolean }) => void;+ mocks.edit.mockImplementation(+ () =>+ new Promise((resolve) => {+ finish = resolve;+ }),+ );+ await render();+ await editCue(2);+ await type("Saved after waiting");+ await click(button("Save"));+ expect(button("Save").disabled).toBe(true);+ expect(button("Cancel").disabled).toBe(true);+ await editCue(3);+ expect(container.querySelector("textarea")?.value).toMatch(/^Cue 3:/);+ expect(button("Save").disabled).toBe(true);+ expect(button("Cancel").disabled).toBe(true);+ await act(async () => finish({ success: true }));+ expect(container.querySelector("textarea")).toBeNull();+ expect(container.textContent).toContain("Saved after waiting");+ });++ it("keeps an empty transcript empty", async () => {+ mocks.content = "WEBVTT\n\n";+ await render();+ expect(+ container.querySelector('button[title="Edit transcript entry"]'),+ ).toBeNull();+ expect(container.querySelector("textarea")).toBeNull();+ expect(mocks.rowRenders).toBe(0);+ });++ it.skipIf(!process.env.CAP_TRANSCRIPT_BENCH)(+ "profiles selection and typing with 1200 three-second cues",+ async () => {+ await render();+ const median = (values: number[]) =>+ [...values].sort((a, b) => a - b)[Math.floor(values.length / 2)];+ const selection: number[] = [];+ const typing: number[] = [];+ const selectionElapsed: number[] = [];+ const typingElapsed: number[] = [];+ for (let i = 0; i < 40; i++) {+ durations = [];+ const target = cue(i % 2 ? 300 : 600);+ const start = performance.now();+ await click(target);+ if (i >= 10) {+ selectionElapsed.push(performance.now() - start);+ selection.push(...durations);+ }+ }+ await editCue(300);+ mocks.rowRenders = 0;+ for (let i = 0; i < 40; i++) {+ durations = [];+ const start = performance.now();+ await type(`Updated cue ${i}`);+ if (i >= 10) {+ typingElapsed.push(performance.now() - start);+ typing.push(...durations);+ }+ }+ expect(selection).toHaveLength(30);+ expect(typing).toHaveLength(30);+ console.log(+ JSON.stringify({+ cues: 1200,+ samples: 30,+ selectionMedianMs: median(selection),+ typingMedianMs: median(typing),+ selectionElapsedMedianMs: median(selectionElapsed),+ typingElapsedMedianMs: median(typingElapsed),+ typingRowRenders: mocks.rowRenders,+ }),+ );+ },+ 60000,+ );+});diff --git a/apps/web/app/s/[videoId]/_components/tabs/Transcript.tsx b/apps/web/app/s/[videoId]/_components/tabs/Transcript.tsxindex 2915c4dd2..5bfb575bc 100644--- a/apps/web/app/s/[videoId]/_components/tabs/Transcript.tsx+++ b/apps/web/app/s/[videoId]/_components/tabs/Transcript.tsx@@ -9,12 +9,11 @@ import {ChevronDown,Copy,Download,- Edit3,Globe,LoaderCircle,MessageSquare,} from "lucide-react";-import { useEffect, useMemo, useRef, useState } from "react";+import { useCallback, useEffect, useMemo, useRef, useState } from "react";import { editTranscriptEntry } from "@/actions/videos/edit-transcript";import {type LanguageCode,@@ -27,6 +26,7 @@ import type { VideoData } from "../../types";import { type CaptionLanguage, useCaptionContext } from "../CaptionContext";import type { TranscriptEntry } from "../utils/parse-transcript-vtt";import { parseTranscriptVTT } from "../utils/parse-transcript-vtt";+import { TranscriptEditor, TranscriptRow } from "./transcript-row";interface TranscriptProps {data: VideoData;@@ -49,7 +49,6 @@ export const Transcript: React.FC<TranscriptProps> = ({ data, onSeek }) => {const [selectedEntry, setSelectedEntry] = useState<number | null>(null);const [retryTriggered, setRetryTriggered] = useState(false);const [editingEntry, setEditingEntry] = useState<number | null>(null);- const [editText, setEditText] = useState<string>("");const [isSaving, setIsSaving] = useState(false);const [isCopying, setIsCopying] = useState(false);const [copyPressed, setCopyPressed] = useState(false);@@ -249,37 +248,33 @@ export const Transcript: React.FC<TranscriptProps> = ({ data, onSeek }) => {);}, [data.createdAt, data.transcriptionStatus, retryTriggered]);- const handleTranscriptClick = (entry: TranscriptEntry) => {- if (editingEntry === entry.id) {- return;- }-- setSelectedEntry(entry.id);+ const handleTranscriptClick = useCallback(+ (entry: TranscriptEntry) => {+ if (editingEntry === entry.id) {+ return;+ }- onSeek?.(entry.startTime);- };+ setSelectedEntry(entry.id);+ onSeek?.(entry.startTime);+ },+ [editingEntry, onSeek],+ );- const startEditing = (entry: TranscriptEntry) => {+ const startEditing = useCallback((entry: TranscriptEntry) => {setEditingEntry(entry.id);- setEditText(entry.text);- };+ }, []);const cancelEditing = () => {setEditingEntry(null);- setEditText("");};- const saveEdit = async () => {+ const saveEdit = async (editText: string) => {const normalizedEditText = normalizeTranscriptCueText(editText);if (!editingEntry || !normalizedEditText) {return;}- const _originalEntry = transcriptData.find(- (entry) => entry.id === editingEntry,- );-setIsSaving(true);try {const result = await editTranscriptEntry(@@ -297,7 +292,6 @@ export const Transcript: React.FC<TranscriptProps> = ({ data, onSeek }) => {),);setEditingEntry(null);- setEditText("");invalidateTranscript(data.id);} else {console.error("[Transcript] Failed to save transcript edit:", {@@ -796,87 +790,30 @@ export const Transcript: React.FC<TranscriptProps> = ({ data, onSeek }) => {</div>)}<div className="px-3 py-3">- {transcriptData.map((entry) => (- <div- key={entry.id}- className={`group flex items-start gap-1 rounded-lg px-2 transition-colors ${- editingEntry === entry.id- ? "bg-gray-2"- : selectedEntry === entry.id- ? "bg-gray-3"- : "hover:bg-gray-2"- }`}- >- {editingEntry === entry.id ? (- <div className="min-w-0 flex-1 py-2">- <textarea- value={editText}- onChange={(e) => setEditText(e.target.value)}- className="w-full resize-none rounded-lg border border-gray-4 bg-gray-1 p-2.5 text-[13px] leading-[22px] text-gray-12 outline-none transition placeholder:text-gray-8 focus:border-blue-500/60 focus:ring-2 focus:ring-blue-500/20"- rows={Math.max(2, Math.ceil(editText.length / 60))}- onClick={(e) => e.stopPropagation()}- placeholder="Edit transcript text..."- />- <div className="mt-2 flex justify-end gap-1.5">- <button- type="button"- onClick={(e) => {- e.stopPropagation();- cancelEditing();- }}- disabled={isSaving}- className="inline-flex h-7 items-center rounded-full px-3 text-[11px] font-medium text-gray-11 transition hover:bg-gray-3 hover:text-gray-12 disabled:opacity-50"- >- Cancel- </button>- <button- type="button"- onClick={(e) => {- e.stopPropagation();- saveEdit();- }}- disabled={isSaving || !editText.trim()}- className="inline-flex h-7 items-center gap-1.5 rounded-full bg-gray-12 px-3 text-[11px] font-semibold text-white transition hover:bg-gray-11 disabled:pointer-events-none disabled:opacity-50"- >- {isSaving && (- <LoaderCircle className="size-3 animate-spin" />- )}- Save- </button>- </div>- </div>- ) : (- <>- <button- className="flex min-w-0 flex-1 items-baseline gap-2.5 py-1.5 text-left"- onClick={() => handleTranscriptClick(entry)}- type="button"- >- <span className="min-w-9 shrink-0 font-mono text-[10px] leading-[22px] tabular-nums text-gray-8">- {entry.timestamp}- </span>- <span className="min-w-0 flex-1 text-[13px] leading-[22px] text-gray-11">- {entry.text}- </span>- </button>- {canEdit && (- <button- onClick={(e) => {- e.stopPropagation();- startEditing(entry);- }}- type="button"- aria-label="Edit transcript entry"- title="Edit transcript entry"- className="mt-1.5 flex size-6 shrink-0 items-center justify-center rounded-md text-gray-9 opacity-0 transition-all hover:bg-gray-4 hover:text-gray-12 focus-visible:opacity-100 group-hover:opacity-100"- >- <Edit3 className="size-3" />- </button>- )}- </>- )}- </div>- ))}+ {transcriptData.map((entry) =>+ editingEntry === entry.id ? (+ <div+ key={entry.id}+ className="group flex items-start gap-1 rounded-lg bg-gray-2 px-2 transition-colors"+ >+ <TranscriptEditor+ entry={entry}+ isSaving={isSaving}+ onSave={saveEdit}+ onCancel={cancelEditing}+ />+ </div>+ ) : (+ <TranscriptRow+ key={entry.id}+ entry={entry}+ selected={selectedEntry === entry.id}+ canEdit={canEdit}+ onSelect={handleTranscriptClick}+ onEdit={startEditing}+ />+ ),+ )}</div></div></div>diff --git a/apps/web/app/s/[videoId]/_components/tabs/transcript-row.tsx b/apps/web/app/s/[videoId]/_components/tabs/transcript-row.tsxnew file mode 100644index 000000000..c0bb2d4eb--- /dev/null+++ b/apps/web/app/s/[videoId]/_components/tabs/transcript-row.tsx@@ -0,0 +1,104 @@+import { Edit3, LoaderCircle } from "lucide-react";+import { memo, useState } from "react";+import type { TranscriptEntry } from "../utils/parse-transcript-vtt";++export const TranscriptRow = memo(function TranscriptRow({+ entry,+ selected,+ canEdit,+ onSelect,+ onEdit,+}: {+ entry: TranscriptEntry;+ selected: boolean;+ canEdit: boolean;+ onSelect: (entry: TranscriptEntry) => void;+ onEdit: (entry: TranscriptEntry) => void;+}) {+ return (+ <div+ className={`group flex items-start gap-1 rounded-lg px-2 transition-colors ${+ selected ? "bg-gray-3" : "hover:bg-gray-2"+ }`}+ >+ <button+ className="flex min-w-0 flex-1 items-baseline gap-2.5 py-1.5 text-left"+ onClick={() => onSelect(entry)}+ type="button"+ >+ <span className="min-w-9 shrink-0 font-mono text-[10px] leading-[22px] tabular-nums text-gray-8">+ {entry.timestamp}+ </span>+ <span className="min-w-0 flex-1 text-[13px] leading-[22px] text-gray-11">+ {entry.text}+ </span>+ </button>+ {canEdit && (+ <button+ onClick={(event) => {+ event.stopPropagation();+ onEdit(entry);+ }}+ type="button"+ aria-label="Edit transcript entry"+ title="Edit transcript entry"+ className="mt-1.5 flex size-6 shrink-0 items-center justify-center rounded-md text-gray-9 opacity-0 transition-all hover:bg-gray-4 hover:text-gray-12 focus-visible:opacity-100 group-hover:opacity-100"+ >+ <Edit3 className="size-3" />+ </button>+ )}+ </div>+ );+});++export function TranscriptEditor({+ entry,+ isSaving,+ onSave,+ onCancel,+}: {+ entry: TranscriptEntry;+ isSaving: boolean;+ onSave: (text: string) => Promise<void>;+ onCancel: () => void;+}) {+ const [editText, setEditText] = useState(entry.text);++ return (+ <div className="min-w-0 flex-1 py-2">+ <textarea+ value={editText}+ onChange={(e) => setEditText(e.target.value)}+ className="w-full resize-none rounded-lg border border-gray-4 bg-gray-1 p-2.5 text-[13px] leading-[22px] text-gray-12 outline-none transition placeholder:text-gray-8 focus:border-blue-500/60 focus:ring-2 focus:ring-blue-500/20"+ rows={Math.max(2, Math.ceil(editText.length / 60))}+ onClick={(e) => e.stopPropagation()}+ placeholder="Edit transcript text..."+ />+ <div className="mt-2 flex justify-end gap-1.5">+ <button+ type="button"+ onClick={(e) => {+ e.stopPropagation();+ onCancel();+ }}+ disabled={isSaving}+ className="inline-flex h-7 items-center rounded-full px-3 text-[11px] font-medium text-gray-11 transition hover:bg-gray-3 hover:text-gray-12 disabled:opacity-50"+ >+ Cancel+ </button>+ <button+ type="button"+ onClick={(e) => {+ e.stopPropagation();+ void onSave(editText);+ }}+ disabled={isSaving || !editText.trim()}+ className="inline-flex h-7 items-center gap-1.5 rounded-full bg-gray-12 px-3 text-[11px] font-semibold text-white transition hover:bg-gray-11 disabled:pointer-events-none disabled:opacity-50"+ >+ {isSaving && <LoaderCircle className="size-3 animate-spin" />}+ Save+ </button>+ </div>+ </div>+ );+}