Skip to content

armgit / Cap

Public Imported from GitHub
0

Open source Loom alternative. Beautiful, shareable screen recordings.

feat(desktop): add transcript word editing and caption creation

Richie McIlroyd3d75549d9eb
diff --git a/apps/desktop/src/routes/editor/TranscriptPage.tsx b/apps/desktop/src/routes/editor/TranscriptPage.tsx
index 1c903efe6..5c950c3a6 100644
--- a/apps/desktop/src/routes/editor/TranscriptPage.tsx
+++ b/apps/desktop/src/routes/editor/TranscriptPage.tsx
@@ -11,10 +11,12 @@ import {
Show,
} from "solid-js";
import { produce } from "solid-js/store";
-import { commands } from "~/utils/tauri";
+import { defaultCaptionSettings } from "~/store/captions";
+import { type CaptionTrackSegment, commands } from "~/utils/tauri";
import {
createCaptionTrackSegments,
getCaptionTextFromWords,
+ syncCaptionWordsWithText,
} from "./captions";
import { FPS, useEditorContext } from "./context";
import {
@@ -39,7 +41,6 @@ interface FlatWord {
interface TranscriptSegmentGroup {
segmentIndex: number;
- startTime: number;
words: FlatWord[];
}
@@ -85,24 +86,143 @@ export function TranscriptPanel() {
});
const segmentGroups = createMemo((): TranscriptSegmentGroup[] => {
- const words = allWords();
- const groups: TranscriptSegmentGroup[] = [];
- let currentGroup: TranscriptSegmentGroup | null = null;
-
- for (const word of words) {
- if (!currentGroup || currentGroup.segmentIndex !== word.segmentIndex) {
- currentGroup = {
- segmentIndex: word.segmentIndex,
- startTime: word.start,
- words: [],
- };
- groups.push(currentGroup);
- }
- currentGroup.words.push(word);
+ const flatWords = allWords();
+ return (project.captions?.segments ?? []).map((_segment, segmentIndex) => ({
+ segmentIndex,
+ words: flatWords.filter((word) => word.segmentIndex === segmentIndex),
+ }));
+ });
+
+ const syncCaptionTracks = (p: typeof project) => {
+ if (p.timeline && p.captions) {
+ const existingSegments = new Map(
+ (p.timeline.captionSegments ?? []).map((segment) => [
+ segment.id,
+ segment,
+ ]),
+ );
+ p.timeline.captionSegments = createCaptionTrackSegments(
+ p.captions.segments,
+ ).map((segment) => {
+ const existing = existingSegments.get(segment.id);
+ return existing
+ ? ({
+ ...segment,
+ fadeDurationOverride: existing.fadeDurationOverride,
+ lingerDurationOverride: existing.lingerDurationOverride,
+ positionOverride: existing.positionOverride,
+ colorOverride: existing.colorOverride,
+ backgroundColorOverride: existing.backgroundColorOverride,
+ fontSizeOverride: existing.fontSizeOverride,
+ } satisfies CaptionTrackSegment)
+ : segment;
+ });
}
+ };
- return groups;
- });
+ const updateWordText = (flatIndex: number, rawText: string) => {
+ const target = allWords()[flatIndex];
+ if (!target) return;
+
+ const tokens = rawText
+ .trim()
+ .split(/\s+/)
+ .map((token) => token.trim())
+ .filter((token) => token.length > 0);
+
+ setProject(
+ produce((p) => {
+ const segment = p.captions?.segments?.[target.segmentIndex];
+ if (!segment?.words) return;
+
+ const existing = segment.words[target.wordIndex];
+ if (!existing) return;
+
+ if (tokens.length === 0) {
+ segment.words.splice(target.wordIndex, 1);
+ } else if (tokens.length === 1) {
+ existing.text = tokens[0];
+ } else {
+ const start = existing.start;
+ const end = existing.end;
+ const step = (end - start) / tokens.length;
+ const replacements = tokens.map((token, index) => ({
+ text: token,
+ start: start + step * index,
+ end: index === tokens.length - 1 ? end : start + step * (index + 1),
+ }));
+ segment.words.splice(target.wordIndex, 1, ...replacements);
+ }
+
+ if (!p.captions?.segments) return;
+ for (let i = p.captions.segments.length - 1; i >= 0; i--) {
+ const seg = p.captions.segments[i];
+ if (!seg.words || seg.words.length === 0) {
+ p.captions.segments.splice(i, 1);
+ } else {
+ seg.text = getCaptionTextFromWords(seg.words);
+ seg.start = seg.words[0].start;
+ seg.end = seg.words[seg.words.length - 1].end;
+ }
+ }
+
+ syncCaptionTracks(p);
+ }),
+ );
+ setEditorState("captions", "isStale", false);
+ };
+
+ const addCaptionAtPlayhead = () => {
+ const total = totalDuration();
+ const defaultDuration = 2;
+ const start =
+ total > 0
+ ? Math.min(
+ Math.max(editorState.playbackTime, 0),
+ Math.max(total - 0.25, 0),
+ )
+ : Math.max(editorState.playbackTime, 0);
+ const end =
+ total > 0
+ ? Math.min(Math.max(start + defaultDuration, start + 0.25), total)
+ : start + defaultDuration;
+ const text = "New caption";
+
+ setProject(
+ produce((p) => {
+ p.captions ??= {
+ segments: [],
+ settings: { ...defaultCaptionSettings, enabled: true },
+ };
+ p.captions.settings = {
+ ...defaultCaptionSettings,
+ ...p.captions.settings,
+ enabled: true,
+ };
+ p.timeline ??= {
+ segments: [{ start: 0, end: total || end, timescale: 1 }],
+ zoomSegments: [],
+ sceneSegments: [],
+ maskSegments: [],
+ textSegments: [],
+ captionSegments: [],
+ keyboardSegments: [],
+ };
+
+ p.captions.segments.push({
+ id: `caption-${Date.now()}-${Math.random().toString(36).slice(2)}`,
+ start,
+ end,
+ text,
+ words: syncCaptionWordsWithText(text, undefined, start, end),
+ });
+ p.captions.segments.sort((a, b) => a.start - b.start);
+ syncCaptionTracks(p);
+ }),
+ );
+ setEditorState("timeline", "tracks", "caption", true);
+ setEditorState("captions", "isStale", false);
+ };
const activeWordIndex = createMemo(() => {
const time = editorState.playbackTime;
@@ -296,6 +416,14 @@ export function TranscriptPanel() {
<div class="px-3 py-2 border-b border-gray-3 flex items-center justify-between shrink-0">
<span class="text-xs font-medium text-gray-12">Transcript</span>
<div class="flex items-center gap-1">
+ <button
+ type="button"
+ class="flex items-center gap-1 rounded-sm px-2 h-6 hover:bg-gray-3 text-gray-9 hover:text-gray-12 transition-colors text-xs"
+ onClick={addCaptionAtPlayhead}
+ >
+ <IconLucidePlus class="size-3" />
+ Add
+ </button>
<button
type="button"
class="flex items-center justify-center size-5 rounded-sm hover:bg-gray-3 text-gray-9 hover:text-gray-12 transition-colors disabled:opacity-30 disabled:pointer-events-none"
@@ -328,22 +456,30 @@ export function TranscriptPanel() {
onWordClick={handleWordClick}
onDeleteWord={handleDeleteWord}
onDeleteWords={handleDeleteWords}
+ onEditWord={updateWordText}
+ onAddCaption={addCaptionAtPlayhead}
/>
</div>
);
}
-function WordWithTooltip(props: {
+function TranscriptWord(props: {
word: FlatWord;
isActive: boolean;
isSelected: boolean;
+ isEditing: boolean;
selectedCount: number;
+ textSizeClass: string;
ref: (el: HTMLSpanElement) => void;
onClick: (e: MouseEvent) => void;
+ onStartEdit: () => void;
+ onCommitEdit: (text: string) => void;
+ onCancelEdit: () => void;
onDelete: () => void;
}) {
const [hovering, setHovering] = createSignal(false);
let hoverTimer: number | undefined;
+ let inputRef: HTMLInputElement | undefined;
const onEnter = () => {
hoverTimer = window.setTimeout(() => setHovering(true), 350);
@@ -354,48 +490,108 @@ function WordWithTooltip(props: {
};
const showTip = () =>
- hovering() || (props.isSelected && props.selectedCount === 1);
+ !props.isEditing &&
+ (hovering() || (props.isSelected && props.selectedCount === 1));
+
+ const sizeInput = (value: string) => {
+ if (inputRef) {
+ inputRef.style.width = `${Math.max(value.length, 1) + 1}ch`;
+ }
+ };
+
+ createEffect(() => {
+ if (props.isEditing && inputRef) {
+ sizeInput(inputRef.value);
+ inputRef.focus();
+ inputRef.select();
+ }
+ });
+
+ const commit = () => {
+ if (inputRef) props.onCommitEdit(inputRef.value);
+ };
return (
- <span
- ref={props.ref}
- class={cx(
- "cursor-pointer transition-colors duration-100 rounded-xs relative",
- props.isSelected && "bg-blue-4/50",
- props.isActive
- ? "text-blue-11"
- : props.isSelected
- ? "text-blue-11"
- : "text-gray-9 hover:text-gray-12",
- )}
- onClick={(e) => props.onClick(e)}
- onMouseEnter={onEnter}
- onMouseLeave={onLeave}
- >
- {props.word.text}
- <Show when={showTip()}>
+ <Show
+ when={props.isEditing}
+ fallback={
<span
- class="absolute left-1/2 -translate-x-1/2 top-full mt-1 flex items-center gap-2 whitespace-nowrap border border-gray-3 bg-gray-12 rounded-lg shadow-lg animate-in fade-in slide-in-from-top-1 duration-100 z-50 px-2 py-1.5"
- style={{ "pointer-events": props.isSelected ? "auto" : "none" }}
+ ref={props.ref}
+ class={cx(
+ "cursor-pointer transition-colors duration-100 rounded-xs relative",
+ props.isSelected && "bg-blue-4/50",
+ props.isActive
+ ? "text-blue-11"
+ : props.isSelected
+ ? "text-blue-11"
+ : "text-gray-9 hover:text-gray-12",
+ )}
+ onClick={(e) => props.onClick(e)}
+ onDblClick={(e) => {
+ e.preventDefault();
+ e.stopPropagation();
+ props.onStartEdit();
+ }}
+ onMouseEnter={onEnter}
+ onMouseLeave={onLeave}
>
- <span class="text-xs tabular-nums text-gray-1">
- {formatTimePrecise(props.word.start)}
- </span>
- <Show when={props.isSelected}>
- <button
- type="button"
- class="flex items-center justify-center size-6 rounded-md bg-red-9 text-white hover:bg-red-10 transition-colors"
- onClick={(e) => {
- e.stopPropagation();
- props.onDelete();
- }}
+ {props.word.text}
+ <Show when={showTip()}>
+ <span
+ class="absolute left-1/2 -translate-x-1/2 top-full mt-1 flex items-center gap-2 whitespace-nowrap border border-gray-3 bg-gray-12 rounded-lg shadow-lg animate-in fade-in slide-in-from-top-1 duration-100 z-50 px-2 py-1.5"
+ style={{ "pointer-events": props.isSelected ? "auto" : "none" }}
>
- <IconCapTrash class="size-3.5" />
- </button>
+ <span class="text-xs tabular-nums text-gray-1">
+ {formatTimePrecise(props.word.start)}
+ </span>
+ <Show when={props.isSelected}>
+ <button
+ type="button"
+ class="flex items-center justify-center size-6 rounded-md bg-blue-9 text-white hover:bg-blue-10 transition-colors"
+ onClick={(e) => {
+ e.stopPropagation();
+ props.onStartEdit();
+ }}
+ >
+ <IconLucidePencil class="size-3.5" />
+ </button>
+ <button
+ type="button"
+ class="flex items-center justify-center size-6 rounded-md bg-red-9 text-white hover:bg-red-10 transition-colors"
+ onClick={(e) => {
+ e.stopPropagation();
+ props.onDelete();
+ }}
+ >
+ <IconCapTrash class="size-3.5" />
+ </button>
+ </Show>
+ </span>
</Show>
</span>
- </Show>
- </span>
+ }
+ >
+ <input
+ ref={inputRef}
+ class={cx(
+ "rounded-xs bg-blue-4/40 text-gray-12 ring-1 ring-blue-9 outline-hidden px-0.5",
+ props.textSizeClass,
+ )}
+ value={props.word.text}
+ onInput={(e) => sizeInput(e.currentTarget.value)}
+ onKeyDown={(e) => {
+ e.stopPropagation();
+ if (e.key === "Enter") {
+ e.preventDefault();
+ commit();
+ } else if (e.key === "Escape") {
+ e.preventDefault();
+ props.onCancelEdit();
+ }
+ }}
+ onBlur={commit}
+ />
+ </Show>
);
}
@@ -407,11 +603,14 @@ function TranscriptEditor(props: {
onWordClick: (word: FlatWord) => void;
onDeleteWord: (flatIndex: number) => void;
onDeleteWords: (flatIndices: number[]) => void;
+ onEditWord: (flatIndex: number, text: string) => void;
+ onAddCaption: () => void;
}) {
const [selectedIndices, setSelectedIndices] = createSignal<Set<number>>(
new Set(),
);
const [anchorIndex, setAnchorIndex] = createSignal<number>(-1);
+ const [editingIndex, setEditingIndex] = createSignal<number>(-1);
let scrollContainerRef: HTMLDivElement | undefined;
let activeWordRef: HTMLSpanElement | undefined;
@@ -457,7 +656,11 @@ function TranscriptEditor(props: {
const selected = selectedIndices();
if (selected.size === 0) return;
- if (e.key === "Backspace" || e.key === "Delete") {
+ if (e.key === "Enter" && selected.size === 1 && editingIndex() === -1) {
+ e.preventDefault();
+ const word = props.allWords[[...selected][0]];
+ if (word) startEditing(word);
+ } else if (e.key === "Backspace" || e.key === "Delete") {
e.preventDefault();
const indices = [...selected];
if (indices.length === 1) {
@@ -548,6 +751,23 @@ function TranscriptEditor(props: {
setAnchorIndex(-1);
};
+ const startEditing = (word: FlatWord) => {
+ const idx = flatIndexOf(word);
+ setSelectedIndices(new Set([idx]));
+ setAnchorIndex(idx);
+ setEditingIndex(idx);
+ };
+
+ const commitEditing = (word: FlatWord, text: string) => {
+ if (editingIndex() === -1) return;
+ setEditingIndex(-1);
+ props.onEditWord(flatIndexOf(word), text);
+ };
+
+ const cancelEditing = () => {
+ setEditingIndex(-1);
+ };
+
return (
<div
ref={scrollContainerRef}
@@ -565,6 +785,14 @@ function TranscriptEditor(props: {
<span class="text-xs mt-1">
Generate captions in the editor first
</span>
+ <button
+ type="button"
+ class="mt-4 flex items-center gap-1 rounded-md border border-gray-3 bg-gray-2 px-3 py-1.5 text-xs text-gray-12 hover:bg-gray-3 transition-colors"
+ onClick={props.onAddCaption}
+ >
+ <IconLucidePlus class="size-3.5" />
+ Add caption at playhead
+ </button>
</div>
}
>
@@ -578,17 +806,23 @@ function TranscriptEditor(props: {
const flatIdx = () => flatIndexOf(word);
const isActive = () => props.activeWordIndex === flatIdx();
const isSelected = () => selectedIndices().has(flatIdx());
+ const isEditing = () => editingIndex() === flatIdx();
return (
- <WordWithTooltip
+ <TranscriptWord
word={word}
isActive={isActive()}
isSelected={isSelected()}
+ isEditing={isEditing()}
selectedCount={selectedCount()}
+ textSizeClass={props.textSizeClass}
ref={(el: HTMLSpanElement) => {
if (isActive()) activeWordRef = el;
}}
onClick={(e: MouseEvent) => handleWordSelect(word, e)}
+ onStartEdit={() => startEditing(word)}
+ onCommitEdit={(text: string) => commitEditing(word, text)}
+ onCancelEdit={cancelEditing}
onDelete={() => handleWordDelete(word)}
/>
);