Skip to content

armgit / Cap

Public Imported from GitHub
0

Open source Loom alternative. Beautiful, shareable screen recordings.

feat: add summary and chapter editing to share pages

Richie McIlroydd4b0141e2cb
diff --git a/apps/web/__tests__/unit/summary-editor.test.ts b/apps/web/__tests__/unit/summary-editor.test.ts
new file mode 100644
index 000000000..c395f6e40
--- /dev/null
+++ b/apps/web/__tests__/unit/summary-editor.test.ts
@@ -0,0 +1,276 @@
+// @vitest-environment jsdom
+
+import type { Video } from "@cap/web-domain";
+import { QueryClient, QueryClientProvider } from "@tanstack/react-query";
+import { act, type ComponentProps, createElement, type ReactNode } from "react";
+import { createRoot, type Root } from "react-dom/client";
+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
+import { editAiContent } from "@/actions/videos/edit-ai-content";
+import { Summary } from "@/app/s/[videoId]/_components/tabs/Summary";
+import { SummaryEditor } from "@/app/s/[videoId]/_components/tabs/SummaryEditor";
+
+vi.mock("@/actions/videos/edit-ai-content", () => ({ editAiContent: vi.fn() }));
+vi.mock("@cap/ui", async () => ({
+ Button: (await import("../../../../packages/ui/src/components/Button"))
+ .Button,
+}));
+
+let root: Root;
+let container: HTMLDivElement;
+let queryClient: QueryClient;
+const initialContent = {
+ summary: "Original **summary**",
+ chapters: [
+ { title: "Introduction", start: 0 },
+ { title: "Next steps", start: 60 },
+ ],
+};
+const videoId = "video-id" as Video.VideoId;
+const onClose = vi.fn();
+
+beforeEach(() => {
+ vi.stubGlobal("IS_REACT_ACT_ENVIRONMENT", true);
+ container = document.createElement("div");
+ document.body.append(container);
+ root = createRoot(container);
+ queryClient = new QueryClient({
+ defaultOptions: { queries: { retry: false } },
+ });
+ queryClient.setQueryData(["videoStatus", videoId], {
+ ...initialContent,
+ aiGenerationStatus: "COMPLETE",
+ name: "Video name",
+ });
+ vi.mocked(editAiContent).mockReset();
+});
+afterEach(async () => {
+ await act(async () => root.unmount());
+ queryClient.clear();
+ container.remove();
+ vi.unstubAllGlobals();
+});
+const render = async (
+ element: ReactNode = createElement(SummaryEditor, {
+ videoId,
+ initialContent,
+ duration: 120,
+ onClose,
+ }),
+) => {
+ await act(async () =>
+ root.render(
+ createElement(QueryClientProvider, { client: queryClient }, element),
+ ),
+ );
+};
+const button = (text: string) => {
+ const found = Array.from(container.querySelectorAll("button")).find(
+ (node) => node.textContent?.trim() === text,
+ );
+ if (!found) throw new Error(`Button missing: ${text}`);
+ return found;
+};
+const change = async (
+ element: HTMLInputElement | HTMLTextAreaElement,
+ value: string,
+) => {
+ await act(async () => {
+ const setter = Object.getOwnPropertyDescriptor(
+ element instanceof HTMLTextAreaElement
+ ? HTMLTextAreaElement.prototype
+ : HTMLInputElement.prototype,
+ "value",
+ )?.set;
+ setter?.call(element, value);
+ element.dispatchEvent(new Event("input", { bubbles: true }));
+ });
+};
+const summary = () => {
+ const element = container.querySelector("textarea");
+ if (!element) throw new Error("Summary editor missing");
+ return element;
+};
+
+describe("summary and chapter editor", () => {
+ it("starts clean with MySQL chapter key ordering", async () => {
+ await render(
+ createElement(SummaryEditor, {
+ videoId,
+ initialContent: {
+ ...initialContent,
+ chapters: [{ start: 0, title: "Intro" }],
+ },
+ duration: 120,
+ onClose,
+ }),
+ );
+ expect(button("Save changes").disabled).toBe(true);
+ });
+ it("focuses the summary and cancels without a write", async () => {
+ await render();
+ expect(document.activeElement).toBe(summary());
+ expect(button("Save changes").disabled).toBe(true);
+ await change(summary(), "Draft");
+ await act(async () => button("Cancel").click());
+ expect(onClose).toHaveBeenCalledWith(false);
+ expect(editAiContent).not.toHaveBeenCalled();
+ });
+ it("saves once, updates the shared cache, and preserves unrelated status", async () => {
+ let finish: (value: Awaited<ReturnType<typeof editAiContent>>) => void =
+ () => {};
+ vi.mocked(editAiContent).mockReturnValue(
+ new Promise((resolve) => {
+ finish = resolve;
+ }),
+ );
+ await render();
+ await change(summary(), "Edited");
+ await act(async () => {
+ button("Save changes").click();
+ });
+ expect(button("Saving…").disabled).toBe(true);
+ expect(button("Cancel").disabled).toBe(true);
+ expect(summary().disabled).toBe(true);
+ await act(async () => {
+ finish({ success: true, data: { ...initialContent, summary: "Edited" } });
+ });
+ expect(editAiContent).toHaveBeenCalledTimes(1);
+ expect(queryClient.getQueryData(["videoStatus", videoId])).toMatchObject({
+ summary: "Edited",
+ name: "Video name",
+ aiGenerationStatus: "COMPLETE",
+ });
+ expect(onClose).toHaveBeenCalledWith(true);
+ });
+ it("retains a failed draft and allows retry", async () => {
+ vi.mocked(editAiContent).mockResolvedValue({
+ success: false,
+ message: "Conflict: content changed",
+ });
+ await render();
+ await change(summary(), "Unsaved draft");
+ await act(async () => button("Save changes").click());
+ expect(summary().value).toBe("Unsaved draft");
+ expect(container.querySelector('[role="alert"]')?.textContent).toContain(
+ "Conflict",
+ );
+ expect(button("Save changes").disabled).toBe(false);
+ expect(onClose).not.toHaveBeenCalled();
+ });
+ it("adds and removes chapters and rejects out-of-range timestamps", async () => {
+ await render();
+ await act(async () => button("Add chapter").click());
+ expect(container.querySelectorAll("input")).toHaveLength(6);
+ expect(button("Save changes").disabled).toBe(true);
+ const inputs = Array.from(container.querySelectorAll("input"));
+ const time = inputs[4];
+ const title = inputs[5];
+ if (!time || !title) throw new Error("New chapter missing");
+ await change(title, "Conclusion");
+ await change(time, "02:00");
+ expect(container.textContent).toContain("before the video ends");
+ await change(time, "01:30");
+ expect(button("Save changes").disabled).toBe(false);
+ await act(async () =>
+ container
+ .querySelector<HTMLButtonElement>('[aria-label="Remove chapter 3"]')
+ ?.click(),
+ );
+ expect(container.querySelectorAll("input")).toHaveLength(4);
+ });
+ it("keeps a draft when incoming content changes", async () => {
+ await render();
+ await change(summary(), "My draft");
+ await render(
+ createElement(SummaryEditor, {
+ videoId,
+ initialContent: { ...initialContent, summary: "New remote content" },
+ duration: 120,
+ onClose,
+ }),
+ );
+ expect(summary().value).toBe("My draft");
+ vi.mocked(editAiContent).mockResolvedValue({
+ success: false,
+ message: "Conflict",
+ });
+ await act(async () => button("Save changes").click());
+ expect(editAiContent).toHaveBeenCalledWith(
+ videoId,
+ expect.objectContaining({ expected: initialContent }),
+ );
+ });
+ it("does not change fractional chapter times when editing only text", async () => {
+ const content = {
+ ...initialContent,
+ chapters: [{ title: "Intro", start: 1.123456 }],
+ };
+ await render(
+ createElement(SummaryEditor, {
+ videoId,
+ initialContent: content,
+ duration: 120,
+ onClose,
+ }),
+ );
+ await change(summary(), "Edited summary");
+ vi.mocked(editAiContent).mockResolvedValue({
+ success: false,
+ message: "Try again",
+ });
+ await act(async () => button("Save changes").click());
+ expect(editAiContent).toHaveBeenCalledWith(
+ videoId,
+ expect.objectContaining({
+ value: { ...content, summary: "Edited summary" },
+ }),
+ );
+ });
+});
+
+describe("summary permissions", () => {
+ const props: ComponentProps<typeof Summary> = {
+ videoId,
+ ownerIsPro: true,
+ isOwner: true,
+ initialAiData: { ...initialContent, aiGenerationStatus: "COMPLETE" },
+ };
+ it.each([
+ { isOwner: false },
+ { ownerIsPro: false },
+ {
+ initialAiData: {
+ ...initialContent,
+ aiGenerationStatus: "PROCESSING" as const,
+ },
+ },
+ ])("hides editing when unavailable", async (overrides) => {
+ await render(createElement(Summary, { ...props, ...overrides }));
+ expect(
+ container.querySelector('[aria-label="Edit summary and chapters"]'),
+ ).toBeNull();
+ });
+ it("allows restoring a deliberately empty summary and chapters", async () => {
+ await render(
+ createElement(Summary, {
+ ...props,
+ initialAiData: {
+ summary: "",
+ chapters: [],
+ aiGenerationStatus: "COMPLETE",
+ },
+ }),
+ );
+ await act(async () => button("Edit").click());
+ expect(summary().value).toBe("");
+ });
+ it("uses keyboard-accessible chapter seek buttons", async () => {
+ const onSeek = vi.fn();
+ await render(createElement(Summary, { ...props, onSeek }));
+ const chapter = Array.from(container.querySelectorAll("button")).find(
+ (node) => node.textContent?.includes("Next steps"),
+ );
+ await act(async () => chapter?.click());
+ expect(onSeek).toHaveBeenCalledWith(60);
+ });
+});
diff --git a/apps/web/app/s/[videoId]/_components/Sidebar.tsx b/apps/web/app/s/[videoId]/_components/Sidebar.tsx
index 1716ec58c..8dab24e07 100644
--- a/apps/web/app/s/[videoId]/_components/Sidebar.tsx
+++ b/apps/web/app/s/[videoId]/_components/Sidebar.tsx
@@ -9,6 +9,7 @@ import type { OrganizationSettings } from "@/app/(org)/dashboard/dashboard-data"
import { useCurrentUser } from "@/app/Layout/AuthContext";
import type { VideoData } from "../types";
import { Activity } from "./tabs/Activity";
+import type { SummaryEditingState } from "./tabs/SummaryEditor";
// Activity is the default tab, so it stays in the entry chunk; the other tabs
// (and their deps — react-markdown for Summary, the 1000-line transcript view)
@@ -143,6 +144,13 @@ export const Sidebar = forwardRef<{ scrollToBottom: () => void }, SidebarProps>(
? "transcript"
: "activity";
+ const [summaryEditingState, setSummaryEditingState] =
+ useState<SummaryEditingState>("clean");
+ const canLeaveSummary = () =>
+ summaryEditingState !== "saving" &&
+ (summaryEditingState !== "dirty" ||
+ window.confirm("Discard your unsaved summary and chapter changes?"));
+
const [activeTab, setActiveTab] = useState<TabType>(defaultTab);
const [[page, direction], setPage] = useState([0, 0]);
@@ -174,6 +182,7 @@ export const Sidebar = forwardRef<{ scrollToBottom: () => void }, SidebarProps>(
];
const paginate = (tabId: TabType) => {
+ if (tabId === activeTab || !canLeaveSummary()) return;
const currentIndex = tabs.findIndex((tab) => tab.id === activeTab);
const newIndex = tabs.findIndex((tab) => tab.id === tabId);
const direction = newIndex > currentIndex ? 1 : -1;
@@ -216,6 +225,10 @@ export const Sidebar = forwardRef<{ scrollToBottom: () => void }, SidebarProps>(
<Summary
videoId={data.id}
ownerIsPro={data.owner.isPro}
+ isOwner={isOwner}
+ transcriptionStatus={data.transcriptionStatus}
+ duration={data.duration}
+ onEditingStateChange={setSummaryEditingState}
onSeek={onSeek}
isSummaryDisabled={videoSettings?.disableSummary}
initialAiData={aiData || undefined}
@@ -284,7 +297,9 @@ export const Sidebar = forwardRef<{ scrollToBottom: () => void }, SidebarProps>(
{onCollapse && (
<button
type="button"
- onClick={onCollapse}
+ onClick={() => {
+ if (canLeaveSummary()) onCollapse();
+ }}
aria-label="Hide comments"
title="Hide comments"
className="hidden shrink-0 items-center justify-center px-3 text-gray-9 transition-colors hover:bg-gray-1 hover:text-gray-12 lg:flex"
diff --git a/apps/web/app/s/[videoId]/_components/SummaryChapters.tsx b/apps/web/app/s/[videoId]/_components/SummaryChapters.tsx
index 52b90061f..c1b8f9d68 100644
--- a/apps/web/app/s/[videoId]/_components/SummaryChapters.tsx
+++ b/apps/web/app/s/[videoId]/_components/SummaryChapters.tsx
@@ -46,11 +46,6 @@ const SummaryChapters = ({
{hasSummary && (
<>
<h3 className="text-lg font-medium">Summary</h3>
- <div className="mb-2">
- <span className="text-xs font-semibold text-gray-8">
- Generated by Cap AI
- </span>
- </div>
<div className="text-sm prose prose-sm prose-gray max-w-none prose-p:my-2 prose-ul:my-2 prose-li:my-0 prose-strong:text-gray-12">
<ReactMarkdown>{aiData.summary}</ReactMarkdown>
</div>
@@ -62,16 +57,17 @@ const SummaryChapters = ({
<h3 className="mb-2 text-lg font-medium">Chapters</h3>
<div className="divide-y">
{aiData.chapters?.map((chapter) => (
- <div
+ <button
+ type="button"
key={chapter.start}
- className="flex items-center p-2 rounded transition-colors cursor-pointer hover:bg-gray-100"
+ className="flex items-center w-full p-2 text-left rounded transition-colors hover:bg-gray-3 focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-blue-9"
onClick={() => handleSeek(chapter.start)}
>
<span className="w-16 text-xs text-gray-500">
{formatTimeMinutes(chapter.start)}
</span>
<span className="ml-2 text-sm">{chapter.title}</span>
- </div>
+ </button>
))}
</div>
</div>
diff --git a/apps/web/app/s/[videoId]/_components/tabs/Summary.tsx b/apps/web/app/s/[videoId]/_components/tabs/Summary.tsx
index 9a5ca75a6..a5cd915f4 100644
--- a/apps/web/app/s/[videoId]/_components/tabs/Summary.tsx
+++ b/apps/web/app/s/[videoId]/_components/tabs/Summary.tsx
@@ -7,8 +7,10 @@ import {
faRotateRight,
} from "@fortawesome/free-solid-svg-icons";
import { FontAwesomeIcon } from "@fortawesome/react-fontawesome";
-import { useState } from "react";
+import { Edit3 } from "lucide-react";
+import { useRef, useState } from "react";
import ReactMarkdown from "react-markdown";
+import { type SummaryEditingState, SummaryEditor } from "./SummaryEditor";
type AiGenerationStatus =
| "QUEUED"
@@ -34,6 +36,10 @@ interface SummaryProps {
aiGenerationEnabled?: boolean;
isSummaryDisabled?: boolean;
ownerIsPro: boolean;
+ isOwner?: boolean;
+ transcriptionStatus?: string | null;
+ duration?: number | null;
+ onEditingStateChange?: (state: SummaryEditingState) => void;
}
const formatTime = (time: number) => {
@@ -79,7 +85,14 @@ export const Summary: React.FC<SummaryProps> = ({
isSummaryDisabled = false,
aiGenerationEnabled = false,
ownerIsPro,
+ isOwner = false,
+ transcriptionStatus,
+ duration,
+ onEditingStateChange,
}) => {
+ const [isEditing, setIsEditing] = useState(false);
+ const [saved, setSaved] = useState(false);
+ const editButtonRef = useRef<HTMLButtonElement>(null);
const [isRetrying, setIsRetrying] = useState(false);
const [retryError, setRetryError] = useState<string | null>(null);
@@ -93,7 +106,28 @@ export const Summary: React.FC<SummaryProps> = ({
!aiData?.chapters?.length;
const canRetry =
- aiGenerationStatus === "ERROR" || aiGenerationStatus === "SKIPPED";
+ isOwner &&
+ (aiGenerationStatus === "ERROR" || aiGenerationStatus === "SKIPPED");
+ const canEdit =
+ isOwner &&
+ transcriptionStatus !== "PROCESSING" &&
+ aiGenerationStatus !== "QUEUED" &&
+ aiGenerationStatus !== "PROCESSING";
+ const editButton = canEdit ? (
+ <Button
+ ref={editButtonRef}
+ type="button"
+ variant="gray"
+ size="sm"
+ aria-label="Edit summary and chapters"
+ onClick={() => {
+ setSaved(false);
+ setIsEditing(true);
+ }}
+ >
+ <Edit3 className="mr-1.5 size-3.5" /> Edit
+ </Button>
+ ) : null;
const handleSeek = (time: number) => {
if (onSeek) {
@@ -134,6 +168,7 @@ export const Summary: React.FC<SummaryProps> = ({
<div className="p-6 bg-gradient-to-br from-blue-50 to-purple-50 rounded-lg border border-blue-100">
<div className="mb-3 text-blue-600">
<svg
+ aria-hidden="true"
xmlns="http://www.w3.org/2000/svg"
className="mx-auto w-12 h-12"
fill="none"
@@ -172,6 +207,25 @@ export const Summary: React.FC<SummaryProps> = ({
if (isSummaryDisabled) return null;
+ if (isEditing && isOwner) {
+ return (
+ <SummaryEditor
+ videoId={videoId}
+ initialContent={{
+ summary: aiData?.summary || "",
+ chapters: aiData?.chapters ?? [],
+ }}
+ duration={duration}
+ onEditingStateChange={onEditingStateChange}
+ onClose={(didSave) => {
+ setIsEditing(false);
+ setSaved(didSave);
+ requestAnimationFrame(() => editButtonRef.current?.focus());
+ }}
+ />
+ );
+ }
+
if (isLoading) {
return (
<div className="flex flex-col h-full">
@@ -204,6 +258,9 @@ export const Summary: React.FC<SummaryProps> = ({
? "The video was too short or had no speech detected."
: "AI summary has not been generated for this video yet."}
</p>
+ {canEdit && (
+ <div className="flex justify-center pt-4">{editButton}</div>
+ )}
{canRetry && (
<div className="pt-4">
<Button
@@ -232,14 +289,17 @@ export const Summary: React.FC<SummaryProps> = ({
<div className="flex flex-col h-full">
<div className="overflow-y-auto flex-1">
<div className="p-4 space-y-6">
+ {canEdit && (
+ <div className="flex items-center justify-between gap-2">
+ <output className="text-xs text-gray-10">
+ {saved ? "Changes saved" : "Summary and chapters"}
+ </output>
+ {editButton}
+ </div>
+ )}
{aiData?.summary && (
<div>
<h3 className="text-lg font-medium">Summary</h3>
- <div className="mb-2">
- <span className="text-xs font-semibold text-gray-8">
- Generated by Cap AI
- </span>
- </div>
<div className="text-sm text-gray-12 prose prose-sm prose-gray max-w-none prose-p:my-2 prose-ul:my-2 prose-li:my-0 prose-strong:text-gray-12">
<ReactMarkdown>{aiData.summary}</ReactMarkdown>
</div>
@@ -251,16 +311,17 @@ export const Summary: React.FC<SummaryProps> = ({
<h3 className="mb-2 text-lg font-medium">Chapters</h3>
<div className="divide-y">
{aiData.chapters.map((chapter) => (
- <div
+ <button
+ type="button"
key={chapter.start}
- className="flex items-center p-2 rounded transition-colors cursor-pointer hover:bg-gray-100"
+ className="flex items-center w-full p-2 text-left rounded transition-colors hover:bg-gray-3 focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-blue-9"
onClick={() => handleSeek(chapter.start)}
>
<span className="w-16 text-xs text-gray-500">
{formatTime(chapter.start)}
</span>
<span className="ml-2 text-sm">{chapter.title}</span>
- </div>
+ </button>
))}
</div>
</div>
diff --git a/apps/web/app/s/[videoId]/_components/tabs/SummaryEditor.tsx b/apps/web/app/s/[videoId]/_components/tabs/SummaryEditor.tsx
new file mode 100644
index 000000000..c6fd7752d
--- /dev/null
+++ b/apps/web/app/s/[videoId]/_components/tabs/SummaryEditor.tsx
@@ -0,0 +1,274 @@
+"use client";
+
+import { Button } from "@cap/ui";
+import type { Video } from "@cap/web-domain";
+import { useQueryClient } from "@tanstack/react-query";
+import { LoaderCircle, Plus, Trash2 } from "lucide-react";
+import { useEffect, useId, useRef, useState } from "react";
+import { editAiContent } from "@/actions/videos/edit-ai-content";
+import type { VideoStatusResult } from "@/actions/videos/get-status";
+import {
+ type AiContent,
+ chaptersEqual,
+ formatChapterTime,
+ MAX_CHAPTER_TITLE_LENGTH,
+ MAX_CHAPTERS,
+ MAX_SUMMARY_LENGTH,
+ parseChapterTime,
+ validateAiContent,
+} from "@/lib/ai-content";
+
+export type SummaryEditingState = "clean" | "dirty" | "saving";
+
+export function SummaryEditor({
+ videoId,
+ initialContent,
+ duration,
+ onClose,
+ onEditingStateChange,
+}: {
+ videoId: Video.VideoId;
+ initialContent: AiContent;
+ duration?: number | null;
+ onClose: (saved: boolean) => void;
+ onEditingStateChange?: (state: SummaryEditingState) => void;
+}) {
+ const queryClient = useQueryClient();
+ const id = useId();
+ const [expected] = useState(initialContent);
+ const [summary, setSummary] = useState(initialContent.summary);
+ const nextId = useRef(initialContent.chapters.length);
+ const [chapters, setChapters] = useState<
+ { id: number; title: string; time: string; originalStart?: number }[]
+ >(() =>
+ initialContent.chapters.map((chapter, index) => ({
+ id: index,
+ title: chapter.title,
+ time: formatChapterTime(chapter.start),
+ originalStart: chapter.start,
+ })),
+ );
+ const [isSaving, setIsSaving] = useState(false);
+ const savingRef = useRef(false);
+ const [error, setError] = useState<string | null>(null);
+ const summaryRef = useRef<HTMLTextAreaElement>(null);
+ const value: AiContent = {
+ summary: summary.trim(),
+ chapters: chapters.map((chapter) => ({
+ title: chapter.title.trim(),
+ start: chapter.originalStart ?? parseChapterTime(chapter.time),
+ })),
+ };
+ const dirty =
+ value.summary !== expected.summary ||
+ !chaptersEqual(value.chapters, expected.chapters);
+ const validationError = validateAiContent(value, duration);
+
+ useEffect(() => {
+ summaryRef.current?.focus();
+ }, []);
+
+ useEffect(() => {
+ onEditingStateChange?.(isSaving ? "saving" : dirty ? "dirty" : "clean");
+ return () => onEditingStateChange?.("clean");
+ }, [dirty, isSaving, onEditingStateChange]);
+
+ useEffect(() => {
+ if (!dirty) return;
+ const handleUnload = (event: BeforeUnloadEvent) => event.preventDefault();
+ window.addEventListener("beforeunload", handleUnload);
+ return () => window.removeEventListener("beforeunload", handleUnload);
+ }, [dirty]);
+
+ const save = async () => {
+ if (savingRef.current || validationError || !dirty) return;
+ savingRef.current = true;
+ setIsSaving(true);
+ setError(null);
+ try {
+ const queryKey = ["videoStatus", videoId];
+ await queryClient.cancelQueries({ queryKey });
+ const result = await editAiContent(videoId, { value, expected });
+ if (!result.success) {
+ setError(result.message);
+ void queryClient.invalidateQueries({ queryKey });
+ return;
+ }
+ await queryClient.cancelQueries({ queryKey });
+ queryClient.setQueryData<VideoStatusResult>(queryKey, (current) =>
+ current ? { ...current, ...result.data } : current,
+ );
+ void queryClient.invalidateQueries({ queryKey });
+ onClose(true);
+ } catch {
+ setError("Couldn't save your changes. Please try again.");
+ } finally {
+ savingRef.current = false;
+ setIsSaving(false);
+ }
+ };
+
+ return (
+ <form
+ className="flex flex-col h-full min-h-0"
+ onSubmit={(event) => {
+ event.preventDefault();
+ void save();
+ }}
+ onKeyDown={(event) => {
+ if ((event.metaKey || event.ctrlKey) && event.key === "Enter") {
+ event.preventDefault();
+ void save();
+ }
+ }}
+ >
+ <div className="overflow-y-auto flex-1 p-4 space-y-6">
+ <div className="space-y-2">
+ <label
+ htmlFor={`${id}-summary`}
+ className="block text-sm font-medium text-gray-12"
+ >
+ Summary
+ </label>
+ <p id={`${id}-summary-help`} className="text-xs text-gray-10">
+ Edit the summary below. Markdown formatting is supported.
+ </p>
+ <textarea
+ ref={summaryRef}
+ id={`${id}-summary`}
+ aria-describedby={`${id}-summary-help`}
+ value={summary}
+ onChange={(event) => setSummary(event.target.value)}
+ maxLength={MAX_SUMMARY_LENGTH}
+ disabled={isSaving}
+ rows={10}
+ className="w-full min-h-40 p-3 text-sm leading-relaxed text-gray-12 bg-gray-1 border border-gray-5 rounded-lg resize-y focus:outline-none focus:ring-2 focus:ring-blue-9 disabled:opacity-60"
+ />
+ </div>
+ <fieldset disabled={isSaving} className="space-y-3">
+ <legend className="text-sm font-medium text-gray-12">Chapters</legend>
+ <p id={`${id}-time-help`} className="text-xs text-gray-10">
+ Use MM:SS or HH:MM:SS. Keep timestamps in order.
+ </p>
+ {chapters.map((chapter, index) => (
+ <div key={chapter.id} className="flex gap-2 items-start">
+ <div className="w-24 shrink-0">
+ <label htmlFor={`${id}-time-${chapter.id}`} className="sr-only">
+ Chapter {index + 1} timestamp
+ </label>
+ <input
+ id={`${id}-time-${chapter.id}`}
+ aria-describedby={`${id}-time-help`}
+ value={chapter.time}
+ onChange={(event) =>
+ setChapters((current) =>
+ current.map((item) =>
+ item.id === chapter.id
+ ? {
+ ...item,
+ time: event.target.value,
+ originalStart: undefined,
+ }
+ : item,
+ ),
+ )
+ }
+ placeholder="00:00"
+ className="w-full px-2 py-2 text-sm font-mono bg-gray-1 border border-gray-5 rounded-lg focus:outline-none focus:ring-2 focus:ring-blue-9"
+ />
+ </div>
+ <div className="flex-1 min-w-0">
+ <label
+ htmlFor={`${id}-title-${chapter.id}`}
+ className="sr-only"
+ >
+ Chapter {index + 1} title
+ </label>
+ <input
+ id={`${id}-title-${chapter.id}`}
+ value={chapter.title}
+ onChange={(event) =>
+ setChapters((current) =>
+ current.map((item) =>
+ item.id === chapter.id
+ ? { ...item, title: event.target.value }
+ : item,
+ ),
+ )
+ }
+ maxLength={MAX_CHAPTER_TITLE_LENGTH}
+ placeholder="Chapter title"
+ className="w-full px-2 py-2 text-sm bg-gray-1 border border-gray-5 rounded-lg focus:outline-none focus:ring-2 focus:ring-blue-9"
+ />
+ </div>
+ <button
+ type="button"
+ aria-label={`Remove chapter ${index + 1}`}
+ onClick={() =>
+ setChapters((current) =>
+ current.filter((item) => item.id !== chapter.id),
+ )
+ }
+ className="p-2 text-gray-10 rounded-lg hover:bg-gray-3 hover:text-red-9 focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-blue-9"
+ >
+ <Trash2 className="size-4" />
+ </button>
+ </div>
+ ))}
+ <Button
+ type="button"
+ variant="gray"
+ size="sm"
+ disabled={chapters.length >= MAX_CHAPTERS || isSaving}
+ onClick={() => {
+ const chapterId = nextId.current++;
+ setChapters((current) => [
+ ...current,
+ {
+ id: chapterId,
+ title: "",
+ time: current.length ? "" : "00:00",
+ originalStart: undefined,
+ },
+ ]);
+ requestAnimationFrame(() =>
+ document.getElementById(`${id}-title-${chapterId}`)?.focus(),
+ );
+ }}
+ >
+ <Plus className="mr-1.5 size-4" /> Add chapter
+ </Button>
+ </fieldset>
+ </div>
+ <div className="shrink-0 p-4 space-y-3 border-t border-gray-4 bg-gray-1">
+ {(error || validationError) && (
+ <p role="alert" className="text-xs text-red-10">
+ {error || validationError}
+ </p>
+ )}
+ <div className="flex justify-end gap-2">
+ <Button
+ type="button"
+ variant="gray"
+ size="sm"
+ disabled={isSaving}
+ onClick={() => onClose(false)}
+ >
+ Cancel
+ </Button>
+ <Button
+ type="submit"
+ variant="primary"
+ size="sm"
+ disabled={isSaving || !dirty || !!validationError}
+ >
+ {isSaving && (
+ <LoaderCircle className="mr-1.5 size-4 animate-spin" />
+ )}
+ {isSaving ? "Saving…" : "Save changes"}
+ </Button>
+ </div>
+ </div>
+ </form>
+ );
+}