Skip to content

armgit / Cap

Public Imported from GitHub
0

Open source Loom alternative. Beautiful, shareable screen recordings.

feat: add CaptionsTrack and KeyboardTrack timeline components with full drag/resize/split support

Cursor Agent78763c23b8fa
diff --git a/apps/desktop/src/routes/editor/Timeline/CaptionsTrack.tsx b/apps/desktop/src/routes/editor/Timeline/CaptionsTrack.tsx
new file mode 100644
index 000000000..f950260bb
--- /dev/null
+++ b/apps/desktop/src/routes/editor/Timeline/CaptionsTrack.tsx
@@ -0,0 +1,280 @@
+import { createEventListenerMap } from "@solid-primitives/event-listener";
+import { cx } from "cva";
+import { createMemo, createRoot, For } from "solid-js";
+import { produce } from "solid-js/store";
+
+import { useEditorContext } from "../context";
+import { useTimelineContext } from "./context";
+import { SegmentContent, SegmentHandle, SegmentRoot, TrackRoot } from "./Track";
+
+export type CaptionSegmentDragState =
+ | { type: "idle" }
+ | { type: "movePending" }
+ | { type: "moving" };
+
+const MIN_SEGMENT_SECS = 0.5;
+const MIN_SEGMENT_PIXELS = 40;
+
+export function CaptionsTrack(props: {
+ onDragStateChanged: (v: CaptionSegmentDragState) => void;
+ handleUpdatePlayhead: (e: MouseEvent) => void;
+}) {
+ const {
+ project,
+ setProject,
+ editorState,
+ setEditorState,
+ totalDuration,
+ projectHistory,
+ projectActions,
+ } = useEditorContext();
+ const { secsPerPixel, timelineBounds } = useTimelineContext();
+
+ const minDuration = () =>
+ Math.max(MIN_SEGMENT_SECS, secsPerPixel() * MIN_SEGMENT_PIXELS);
+
+ const captionSegments = () => project.timeline?.captionSegments ?? [];
+
+ const neighborBounds = (index: number) => {
+ const segments = captionSegments();
+ return {
+ prevEnd: segments[index - 1]?.end ?? 0,
+ nextStart: segments[index + 1]?.start ?? totalDuration(),
+ };
+ };
+
+ function createMouseDownDrag<T>(
+ segmentIndex: () => number,
+ setup: () => T,
+ update: (e: MouseEvent, value: T, initialMouseX: number) => void,
+ ) {
+ return (downEvent: MouseEvent) => {
+ if (editorState.timeline.interactMode !== "seek") return;
+ downEvent.stopPropagation();
+ const initial = setup();
+ let moved = false;
+ let initialMouseX: number | null = null;
+
+ const resumeHistory = projectHistory.pause();
+ props.onDragStateChanged({ type: "movePending" });
+
+ function finish(e: MouseEvent) {
+ resumeHistory();
+ if (!moved) {
+ e.stopPropagation();
+ const index = segmentIndex();
+ const isMultiSelect = e.ctrlKey || e.metaKey;
+
+ if (isMultiSelect) {
+ const currentSelection = editorState.timeline.selection;
+ if (currentSelection?.type === "caption") {
+ const base = currentSelection.indices;
+ const exists = base.includes(index);
+ const next = exists
+ ? base.filter((i) => i !== index)
+ : [...base, index];
+ setEditorState(
+ "timeline",
+ "selection",
+ next.length > 0
+ ? { type: "caption", indices: next }
+ : null,
+ );
+ } else {
+ setEditorState("timeline", "selection", {
+ type: "caption",
+ indices: [index],
+ });
+ }
+ } else {
+ setEditorState("timeline", "selection", {
+ type: "caption",
+ indices: [index],
+ });
+ }
+ props.handleUpdatePlayhead(e);
+ }
+ props.onDragStateChanged({ type: "idle" });
+ }
+
+ function handleUpdate(event: MouseEvent) {
+ if (Math.abs(event.clientX - downEvent.clientX) > 2) {
+ if (!moved) {
+ moved = true;
+ initialMouseX = event.clientX;
+ props.onDragStateChanged({ type: "moving" });
+ }
+ }
+ if (initialMouseX === null) return;
+ update(event, initial, initialMouseX);
+ }
+
+ createRoot((dispose) => {
+ createEventListenerMap(window, {
+ mousemove: (e) => handleUpdate(e),
+ mouseup: (e) => {
+ handleUpdate(e);
+ finish(e);
+ dispose();
+ },
+ });
+ });
+ };
+ }
+
+ return (
+ <TrackRoot
+ onMouseEnter={() =>
+ setEditorState("timeline", "hoveredTrack", "caption")
+ }
+ onMouseLeave={() => setEditorState("timeline", "hoveredTrack", null)}
+ >
+ <For
+ each={captionSegments()}
+ fallback={
+ <div class="text-center text-sm text-[--text-tertiary] flex flex-col justify-center items-center inset-0 w-full bg-gray-3/20 dark:bg-gray-3/10 rounded-xl pointer-events-none">
+ <div>No captions</div>
+ <div class="text-[10px] text-[--text-tertiary]/40 mt-0.5">
+ Generate captions in the sidebar
+ </div>
+ </div>
+ }
+ >
+ {(segment, i) => {
+ const isSelected = createMemo(() => {
+ const selection = editorState.timeline.selection;
+ if (!selection || selection.type !== "caption") return false;
+ return selection.indices.includes(i());
+ });
+
+ const segmentWidth = () => segment.end - segment.start;
+
+ return (
+ <SegmentRoot
+ data-caption-segment
+ data-index={i()}
+ class={cx(
+ "border duration-200 hover:border-green-6 transition-colors group",
+ "bg-gradient-to-r from-[#0d1f12] via-[#162618] to-[#0d1f12]",
+ isSelected() ? "border-green-7" : "border-transparent",
+ )}
+ innerClass="ring-green-6"
+ segment={segment}
+ onMouseDown={(e) => {
+ e.stopPropagation();
+ if (editorState.timeline.interactMode === "split") {
+ const rect = e.currentTarget.getBoundingClientRect();
+ const fraction = (e.clientX - rect.left) / rect.width;
+ const splitTime = fraction * segmentWidth();
+ projectActions.splitCaptionSegment(i(), splitTime);
+ }
+ }}
+ >
+ <SegmentHandle
+ position="start"
+ onMouseDown={createMouseDownDrag(
+ i,
+ () => {
+ const bounds = neighborBounds(i());
+ const start = segment.start;
+ const minValue = bounds.prevEnd;
+ const maxValue = Math.max(
+ minValue,
+ Math.min(
+ segment.end - minDuration(),
+ bounds.nextStart - minDuration(),
+ ),
+ );
+ return { start, minValue, maxValue };
+ },
+ (e, value, initialMouseX) => {
+ const delta = (e.clientX - initialMouseX) * secsPerPixel();
+ const next = Math.max(
+ value.minValue,
+ Math.min(value.maxValue, value.start + delta),
+ );
+ setProject(
+ "timeline",
+ "captionSegments",
+ i(),
+ "start",
+ next,
+ );
+ },
+ )}
+ />
+ <SegmentContent
+ class="flex justify-center items-center cursor-grab px-2 overflow-hidden"
+ onMouseDown={createMouseDownDrag(
+ i,
+ () => {
+ const original = { ...segment };
+ const bounds = neighborBounds(i());
+ const minDelta = bounds.prevEnd - original.start;
+ const maxDelta = bounds.nextStart - original.end;
+ return { original, minDelta, maxDelta };
+ },
+ (e, value, initialMouseX) => {
+ const delta = (e.clientX - initialMouseX) * secsPerPixel();
+ const lowerBound = Math.min(
+ value.minDelta,
+ value.maxDelta,
+ );
+ const upperBound = Math.max(
+ value.minDelta,
+ value.maxDelta,
+ );
+ const clampedDelta = Math.min(
+ upperBound,
+ Math.max(lowerBound, delta),
+ );
+ setProject("timeline", "captionSegments", i(), {
+ ...value.original,
+ start: value.original.start + clampedDelta,
+ end: value.original.end + clampedDelta,
+ });
+ },
+ )}
+ >
+ <div class="flex flex-col gap-0.5 justify-center items-center text-xs text-gray-1 dark:text-gray-12 w-full min-w-0 overflow-hidden">
+ <div class="flex gap-1 items-center text-[10px] w-full min-w-0 justify-center">
+ <span class="truncate max-w-full opacity-80">
+ {segment.text || "Caption"}
+ </span>
+ </div>
+ </div>
+ </SegmentContent>
+ <SegmentHandle
+ position="end"
+ onMouseDown={createMouseDownDrag(
+ i,
+ () => {
+ const bounds = neighborBounds(i());
+ const end = segment.end;
+ const minValue = segment.start + minDuration();
+ const maxValue = Math.max(minValue, bounds.nextStart);
+ return { end, minValue, maxValue };
+ },
+ (e, value, initialMouseX) => {
+ const delta = (e.clientX - initialMouseX) * secsPerPixel();
+ const next = Math.max(
+ value.minValue,
+ Math.min(value.maxValue, value.end + delta),
+ );
+ setProject(
+ "timeline",
+ "captionSegments",
+ i(),
+ "end",
+ next,
+ );
+ },
+ )}
+ />
+ </SegmentRoot>
+ );
+ }}
+ </For>
+ </TrackRoot>
+ );
+}
diff --git a/apps/desktop/src/routes/editor/Timeline/KeyboardTrack.tsx b/apps/desktop/src/routes/editor/Timeline/KeyboardTrack.tsx
new file mode 100644
index 000000000..0fc543dd9
--- /dev/null
+++ b/apps/desktop/src/routes/editor/Timeline/KeyboardTrack.tsx
@@ -0,0 +1,280 @@
+import { createEventListenerMap } from "@solid-primitives/event-listener";
+import { cx } from "cva";
+import { createMemo, createRoot, For } from "solid-js";
+import { produce } from "solid-js/store";
+
+import { useEditorContext } from "../context";
+import { useTimelineContext } from "./context";
+import { SegmentContent, SegmentHandle, SegmentRoot, TrackRoot } from "./Track";
+
+export type KeyboardSegmentDragState =
+ | { type: "idle" }
+ | { type: "movePending" }
+ | { type: "moving" };
+
+const MIN_SEGMENT_SECS = 0.3;
+const MIN_SEGMENT_PIXELS = 30;
+
+export function KeyboardTrack(props: {
+ onDragStateChanged: (v: KeyboardSegmentDragState) => void;
+ handleUpdatePlayhead: (e: MouseEvent) => void;
+}) {
+ const {
+ project,
+ setProject,
+ editorState,
+ setEditorState,
+ totalDuration,
+ projectHistory,
+ projectActions,
+ } = useEditorContext();
+ const { secsPerPixel, timelineBounds } = useTimelineContext();
+
+ const minDuration = () =>
+ Math.max(MIN_SEGMENT_SECS, secsPerPixel() * MIN_SEGMENT_PIXELS);
+
+ const keyboardSegments = () => project.timeline?.keyboardSegments ?? [];
+
+ const neighborBounds = (index: number) => {
+ const segments = keyboardSegments();
+ return {
+ prevEnd: segments[index - 1]?.end ?? 0,
+ nextStart: segments[index + 1]?.start ?? totalDuration(),
+ };
+ };
+
+ function createMouseDownDrag<T>(
+ segmentIndex: () => number,
+ setup: () => T,
+ update: (e: MouseEvent, value: T, initialMouseX: number) => void,
+ ) {
+ return (downEvent: MouseEvent) => {
+ if (editorState.timeline.interactMode !== "seek") return;
+ downEvent.stopPropagation();
+ const initial = setup();
+ let moved = false;
+ let initialMouseX: number | null = null;
+
+ const resumeHistory = projectHistory.pause();
+ props.onDragStateChanged({ type: "movePending" });
+
+ function finish(e: MouseEvent) {
+ resumeHistory();
+ if (!moved) {
+ e.stopPropagation();
+ const index = segmentIndex();
+ const isMultiSelect = e.ctrlKey || e.metaKey;
+
+ if (isMultiSelect) {
+ const currentSelection = editorState.timeline.selection;
+ if (currentSelection?.type === "keyboard") {
+ const base = currentSelection.indices;
+ const exists = base.includes(index);
+ const next = exists
+ ? base.filter((i) => i !== index)
+ : [...base, index];
+ setEditorState(
+ "timeline",
+ "selection",
+ next.length > 0
+ ? { type: "keyboard", indices: next }
+ : null,
+ );
+ } else {
+ setEditorState("timeline", "selection", {
+ type: "keyboard",
+ indices: [index],
+ });
+ }
+ } else {
+ setEditorState("timeline", "selection", {
+ type: "keyboard",
+ indices: [index],
+ });
+ }
+ props.handleUpdatePlayhead(e);
+ }
+ props.onDragStateChanged({ type: "idle" });
+ }
+
+ function handleUpdate(event: MouseEvent) {
+ if (Math.abs(event.clientX - downEvent.clientX) > 2) {
+ if (!moved) {
+ moved = true;
+ initialMouseX = event.clientX;
+ props.onDragStateChanged({ type: "moving" });
+ }
+ }
+ if (initialMouseX === null) return;
+ update(event, initial, initialMouseX);
+ }
+
+ createRoot((dispose) => {
+ createEventListenerMap(window, {
+ mousemove: (e) => handleUpdate(e),
+ mouseup: (e) => {
+ handleUpdate(e);
+ finish(e);
+ dispose();
+ },
+ });
+ });
+ };
+ }
+
+ return (
+ <TrackRoot
+ onMouseEnter={() =>
+ setEditorState("timeline", "hoveredTrack", "keyboard")
+ }
+ onMouseLeave={() => setEditorState("timeline", "hoveredTrack", null)}
+ >
+ <For
+ each={keyboardSegments()}
+ fallback={
+ <div class="text-center text-sm text-[--text-tertiary] flex flex-col justify-center items-center inset-0 w-full bg-gray-3/20 dark:bg-gray-3/10 rounded-xl pointer-events-none">
+ <div>No keyboard events</div>
+ <div class="text-[10px] text-[--text-tertiary]/40 mt-0.5">
+ Record keyboard presses or generate from recording
+ </div>
+ </div>
+ }
+ >
+ {(segment, i) => {
+ const isSelected = createMemo(() => {
+ const selection = editorState.timeline.selection;
+ if (!selection || selection.type !== "keyboard") return false;
+ return selection.indices.includes(i());
+ });
+
+ const segmentWidth = () => segment.end - segment.start;
+
+ return (
+ <SegmentRoot
+ data-keyboard-segment
+ data-index={i()}
+ class={cx(
+ "border duration-200 hover:border-purple-6 transition-colors group",
+ "bg-gradient-to-r from-[#1a0d2e] via-[#231540] to-[#1a0d2e]",
+ isSelected() ? "border-purple-7" : "border-transparent",
+ )}
+ innerClass="ring-purple-6"
+ segment={segment}
+ onMouseDown={(e) => {
+ e.stopPropagation();
+ if (editorState.timeline.interactMode === "split") {
+ const rect = e.currentTarget.getBoundingClientRect();
+ const fraction = (e.clientX - rect.left) / rect.width;
+ const splitTime = fraction * segmentWidth();
+ projectActions.splitKeyboardSegment(i(), splitTime);
+ }
+ }}
+ >
+ <SegmentHandle
+ position="start"
+ onMouseDown={createMouseDownDrag(
+ i,
+ () => {
+ const bounds = neighborBounds(i());
+ const start = segment.start;
+ const minValue = bounds.prevEnd;
+ const maxValue = Math.max(
+ minValue,
+ Math.min(
+ segment.end - minDuration(),
+ bounds.nextStart - minDuration(),
+ ),
+ );
+ return { start, minValue, maxValue };
+ },
+ (e, value, initialMouseX) => {
+ const delta = (e.clientX - initialMouseX) * secsPerPixel();
+ const next = Math.max(
+ value.minValue,
+ Math.min(value.maxValue, value.start + delta),
+ );
+ setProject(
+ "timeline",
+ "keyboardSegments",
+ i(),
+ "start",
+ next,
+ );
+ },
+ )}
+ />
+ <SegmentContent
+ class="flex justify-center items-center cursor-grab px-2 overflow-hidden"
+ onMouseDown={createMouseDownDrag(
+ i,
+ () => {
+ const original = { ...segment };
+ const bounds = neighborBounds(i());
+ const minDelta = bounds.prevEnd - original.start;
+ const maxDelta = bounds.nextStart - original.end;
+ return { original, minDelta, maxDelta };
+ },
+ (e, value, initialMouseX) => {
+ const delta = (e.clientX - initialMouseX) * secsPerPixel();
+ const lowerBound = Math.min(
+ value.minDelta,
+ value.maxDelta,
+ );
+ const upperBound = Math.max(
+ value.minDelta,
+ value.maxDelta,
+ );
+ const clampedDelta = Math.min(
+ upperBound,
+ Math.max(lowerBound, delta),
+ );
+ setProject("timeline", "keyboardSegments", i(), {
+ ...value.original,
+ start: value.original.start + clampedDelta,
+ end: value.original.end + clampedDelta,
+ });
+ },
+ )}
+ >
+ <div class="flex flex-col gap-0.5 justify-center items-center text-xs text-gray-1 dark:text-gray-12 w-full min-w-0 overflow-hidden">
+ <div class="flex gap-1 items-center text-[10px] w-full min-w-0 justify-center font-mono">
+ <span class="truncate max-w-full opacity-80">
+ {segment.displayText || "⌨"}
+ </span>
+ </div>
+ </div>
+ </SegmentContent>
+ <SegmentHandle
+ position="end"
+ onMouseDown={createMouseDownDrag(
+ i,
+ () => {
+ const bounds = neighborBounds(i());
+ const end = segment.end;
+ const minValue = segment.start + minDuration();
+ const maxValue = Math.max(minValue, bounds.nextStart);
+ return { end, minValue, maxValue };
+ },
+ (e, value, initialMouseX) => {
+ const delta = (e.clientX - initialMouseX) * secsPerPixel();
+ const next = Math.max(
+ value.minValue,
+ Math.min(value.maxValue, value.end + delta),
+ );
+ setProject(
+ "timeline",
+ "keyboardSegments",
+ i(),
+ "end",
+ next,
+ );
+ },
+ )}
+ />
+ </SegmentRoot>
+ );
+ }}
+ </For>
+ </TrackRoot>
+ );
+}
diff --git a/apps/desktop/src/routes/editor/Timeline/index.tsx b/apps/desktop/src/routes/editor/Timeline/index.tsx
index c02868807..9df302a75 100644
--- a/apps/desktop/src/routes/editor/Timeline/index.tsx
+++ b/apps/desktop/src/routes/editor/Timeline/index.tsx
@@ -18,8 +18,10 @@ import Tooltip from "~/components/Tooltip";
import { commands } from "~/utils/tauri";
import { FPS, type TimelineTrackType, useEditorContext } from "../context";
import { formatTime } from "../utils";
+import { type CaptionSegmentDragState, CaptionsTrack } from "./CaptionsTrack";
import { ClipTrack } from "./ClipTrack";
import { TimelineContextProvider, useTimelineContext } from "./context";
+import { type KeyboardSegmentDragState, KeyboardTrack } from "./KeyboardTrack";
import { type MaskSegmentDragState, MaskTrack } from "./MaskTrack";
import { type SceneSegmentDragState, SceneTrack } from "./SceneTrack";
import { type TextSegmentDragState, TextTrack } from "./TextTrack";
@@ -36,6 +38,8 @@ const trackIcons: Record<TimelineTrackType, JSX.Element> = {
mask: <IconLucideBoxSelect class="size-4" />,
zoom: <IconLucideSearch class="size-4" />,
scene: <IconLucideVideo class="size-4" />,
+ caption: <IconLucideSubtitles class="size-4" />,
+ keyboard: <IconLucideKeyboard class="size-4" />,
};
type TrackDefinition = {
@@ -52,6 +56,18 @@ const trackDefinitions: TrackDefinition[] = [
icon: trackIcons.clip,
locked: true,
},
+ {
+ type: "caption",
+ label: "Captions",
+ icon: trackIcons.caption,
+ locked: false,
+ },
+ {
+ type: "keyboard",
+ label: "Keyboard",
+ icon: trackIcons.keyboard,
+ locked: false,
+ },
{
type: "text",
label: "Text",
@@ -112,7 +128,11 @@ export function Timeline() {
? trackState().mask
: definition.type === "text"
? trackState().text
- : true,
+ : definition.type === "caption"
+ ? trackState().caption
+ : definition.type === "keyboard"
+ ? trackState().keyboard
+ : true,
available: definition.type === "scene" ? sceneAvailable() : true,
}));
const sceneTrackVisible = () => trackState().scene && sceneAvailable();
@@ -120,6 +140,8 @@ export function Timeline() {
2 +
(trackState().text ? 1 : 0) +
(trackState().mask ? 1 : 0) +
+ (trackState().caption ? 1 : 0) +
+ (trackState().keyboard ? 1 : 0) +
(sceneTrackVisible() ? 1 : 0);
const trackHeight = () => (visibleTrackCount() > 2 ? "3rem" : "3.25rem");
@@ -142,6 +164,22 @@ export function Timeline() {
if (!next && editorState.timeline.selection?.type === "mask") {
setEditorState("timeline", "selection", null);
}
+ return;
+ }
+
+ if (type === "caption") {
+ setEditorState("timeline", "tracks", "caption", next);
+ if (!next && editorState.timeline.selection?.type === "caption") {
+ setEditorState("timeline", "selection", null);
+ }
+ return;
+ }
+
+ if (type === "keyboard") {
+ setEditorState("timeline", "tracks", "keyboard", next);
+ if (!next && editorState.timeline.selection?.type === "keyboard") {
+ setEditorState("timeline", "selection", null);
+ }
}
}
@@ -220,6 +258,8 @@ export function Timeline() {
let sceneSegmentDragState = { type: "idle" } as SceneSegmentDragState;
let maskSegmentDragState = { type: "idle" } as MaskSegmentDragState;
let textSegmentDragState = { type: "idle" } as TextSegmentDragState;
+ let captionSegmentDragState = { type: "idle" } as CaptionSegmentDragState;
+ let keyboardSegmentDragState = { type: "idle" } as KeyboardSegmentDragState;
let pendingZoomDelta = 0;
let pendingZoomOrigin: number | null = null;
@@ -278,7 +318,9 @@ export function Timeline() {
zoomSegmentDragState.type !== "moving" &&
sceneSegmentDragState.type !== "moving" &&
maskSegmentDragState.type !== "moving" &&
- textSegmentDragState.type !== "moving"
+ textSegmentDragState.type !== "moving" &&
+ captionSegmentDragState.type !== "moving" &&
+ keyboardSegmentDragState.type !== "moving"
) {
// Guard against missing bounds and clamp computed time to [0, totalDuration()]
if (left == null) return;
@@ -332,15 +374,17 @@ export function Timeline() {
projectActions.deleteMaskSegments(selection.indices);
} else if (selection.type === "text") {
projectActions.deleteTextSegments(selection.indices);
+ } else if (selection.type === "caption") {
+ projectActions.deleteCaptionSegments(selection.indices);
+ } else if (selection.type === "keyboard") {
+ projectActions.deleteKeyboardSegments(selection.indices);
} else if (selection.type === "clip") {
- // Delete all selected clips in reverse order
[...selection.indices]
.sort((a, b) => b - a)
.forEach((idx) => {
projectActions.deleteClipSegment(idx);
});
} else if (selection.type === "scene") {
- // Delete all selected scenes in reverse order
[...selection.indices]
.sort((a, b) => b - a)
.forEach((idx) => {
@@ -541,6 +585,26 @@ export function Timeline() {
handleUpdatePlayhead={handleUpdatePlayhead}
/>
</TrackRow>
+ <Show when={trackState().caption}>
+ <TrackRow icon={trackIcons.caption}>
+ <CaptionsTrack
+ onDragStateChanged={(v) => {
+ captionSegmentDragState = v;
+ }}
+ handleUpdatePlayhead={handleUpdatePlayhead}
+ />
+ </TrackRow>
+ </Show>
+ <Show when={trackState().keyboard}>
+ <TrackRow icon={trackIcons.keyboard}>
+ <KeyboardTrack
+ onDragStateChanged={(v) => {
+ keyboardSegmentDragState = v;
+ }}
+ handleUpdatePlayhead={handleUpdatePlayhead}
+ />
+ </TrackRow>
+ </Show>
<Show when={trackState().text}>
<TrackRow icon={trackIcons.text}>
<TextTrack