Skip to content

armgit / Cap

Public Imported from GitHub
0

Open source Loom alternative. Beautiful, shareable screen recordings.

feat(desktop): integrate new tracks into editor shell and playback

Richie McIlroy40a71bc249c8
diff --git a/apps/desktop/src/routes/editor/Editor.tsx b/apps/desktop/src/routes/editor/Editor.tsx
index 5b252e5f2..ddf85cb5c 100644
--- a/apps/desktop/src/routes/editor/Editor.tsx
+++ b/apps/desktop/src/routes/editor/Editor.tsx
@@ -13,6 +13,7 @@ import {
createMemo,
createResource,
createSignal,
+ ErrorBoundary,
Match,
on,
onCleanup,
@@ -56,14 +57,48 @@ const MIN_TIMELINE_HEIGHT = 240;
const RESIZE_HANDLE_HEIGHT = 8;
const MIN_PLAYER_HEIGHT = MIN_PLAYER_CONTENT_HEIGHT + RESIZE_HANDLE_HEIGHT;
+function getEditorErrorMessage(error: unknown) {
+ return error instanceof Error ? error.message : String(error);
+}
+
+function getPreviewProjectConfig(
+ project: ReturnType<typeof useEditorContext>["project"],
+ editorState: ReturnType<typeof useEditorContext>["editorState"],
+) {
+ const config = serializeProjectConfiguration(project);
+
+ if (!editorState.timeline.tracks.caption && config.captions) {
+ config.captions = {
+ ...config.captions,
+ settings: {
+ ...config.captions.settings,
+ enabled: false,
+ },
+ };
+ }
+
+ if (!editorState.timeline.tracks.keyboard && config.keyboard) {
+ config.keyboard = {
+ ...config.keyboard,
+ settings: {
+ ...config.keyboard.settings,
+ enabled: false,
+ },
+ };
+ }
+
+ return config;
+}
+
export function Editor() {
const [projectPath] = createResource(() => commands.getEditorProjectPath());
const rawMetaQuery = createQuery(() => ({
queryKey: ["editor", "raw-meta", projectPath()],
- queryFn: projectPath()
- ? () => commands.getRecordingMetaByPath(projectPath()!)
- : skipToken,
+ queryFn: (() => {
+ const path = projectPath();
+ return path ? () => commands.getRecordingMetaByPath(path) : skipToken;
+ })(),
staleTime: Infinity,
gcTime: 0,
refetchOnWindowFocus: false,
@@ -134,17 +169,32 @@ export function Editor() {
</div>
}
>
- <Match when={importStatus() === "importing" && projectPath()}>
- <ImportProgress
- projectPath={projectPath()!}
- onComplete={handleImportComplete}
- onError={(error) => console.error("Import failed:", error)}
- />
+ <Match
+ when={importStatus() === "importing" ? (projectPath() ?? null) : null}
+ >
+ {(path) => (
+ <ImportProgress
+ projectPath={path()}
+ onComplete={handleImportComplete}
+ onError={(error) => console.error("Import failed:", error)}
+ />
+ )}
</Match>
- <Match when={importStatus() === "ready" && projectPath()}>
- <EditorInstanceContextProvider>
- <EditorContent projectPath={projectPath()!} />
- </EditorInstanceContextProvider>
+ <Match when={importStatus() === "ready" ? (projectPath() ?? null) : null}>
+ {(path) => (
+ <ErrorBoundary
+ fallback={(error) => (
+ <EditorErrorScreen
+ error={getEditorErrorMessage(error)}
+ projectPath={path()}
+ />
+ )}
+ >
+ <EditorInstanceContextProvider>
+ <EditorContent projectPath={path()} />
+ </EditorInstanceContextProvider>
+ </ErrorBoundary>
+ )}
</Match>
</Switch>
);
@@ -156,12 +206,12 @@ function EditorContent(props: { projectPath: string }) {
const errorInfo = () => {
const error = ctx.editorInstance.error;
if (!error) return null;
- const errorMessage = error instanceof Error ? error.message : String(error);
+ const errorMessage = getEditorErrorMessage(error);
return { error: errorMessage, projectPath: props.projectPath };
};
const readyData = () => {
- const editorInstance = ctx.editorInstance();
+ const editorInstance = ctx.editorInstance.latest;
if (!editorInstance || !ctx.metaQuery.data) return null;
return {
@@ -329,7 +379,7 @@ function Inner() {
);
const doConfigUpdate = async (time: number) => {
- const config = serializeProjectConfiguration(project);
+ const config = getPreviewProjectConfig(project, editorState);
const frameNumber = Math.max(Math.floor(time * FPS), 0);
const resBase = previewResolutionBase();
try {
@@ -356,6 +406,10 @@ function Inner() {
on(
() => {
trackDeep(project);
+ return {
+ caption: editorState.timeline.tracks.caption,
+ keyboard: editorState.timeline.tracks.keyboard,
+ };
},
() => {
updateConfigAndRender(frameNumberToRender());
@@ -501,7 +555,7 @@ function Dialogs() {
>
{(dialog) => {
const [name, setName] = createSignal(
- presets.query.data?.presets[dialog().presetIndex].name!,
+ presets.query.data?.presets[dialog().presetIndex]?.name ?? "",
);
const renamePreset = createMutation(() => ({
diff --git a/apps/desktop/src/routes/editor/ExportPage.tsx b/apps/desktop/src/routes/editor/ExportPage.tsx
index 817d36e36..be0f313f5 100644
--- a/apps/desktop/src/routes/editor/ExportPage.tsx
+++ b/apps/desktop/src/routes/editor/ExportPage.tsx
@@ -233,7 +233,7 @@ export function ExportPage() {
);
};
- const matchingPreset = () => {
+ const _matchingPreset = () => {
const currentBpp = compressionBpp();
return COMPRESSION_OPTIONS.find(
(opt) => Math.abs(opt.bpp - currentBpp) < 0.001,
diff --git a/apps/desktop/src/routes/editor/MaskOverlay.tsx b/apps/desktop/src/routes/editor/MaskOverlay.tsx
index cde6faeb5..9bb03dc84 100644
--- a/apps/desktop/src/routes/editor/MaskOverlay.tsx
+++ b/apps/desktop/src/routes/editor/MaskOverlay.tsx
@@ -31,6 +31,13 @@ export function MaskOverlay(props: MaskOverlayProps) {
return selection.indices[0] ?? null;
});
+ const hoveredMaskIndex = createMemo(
+ () => editorState.timeline.hoveredMaskIndex,
+ );
+ const hoveredMaskTime = createMemo(
+ () => editorState.timeline.hoveredMaskTime,
+ );
+
const selectedMask = createMemo(() => {
const index = selectedMaskIndex();
if (index === null) return;
@@ -39,6 +46,14 @@ export function MaskOverlay(props: MaskOverlayProps) {
return { index, segment };
});
+ const hoveredMask = createMemo(() => {
+ const index = hoveredMaskIndex();
+ if (index === null) return null;
+ const segment = project.timeline?.maskSegments?.[index];
+ if (!segment) return null;
+ return { index, segment };
+ });
+
const updateSegment = (fn: (segment: MaskSegment) => void) => {
const index = selectedMask()?.index;
if (index === undefined) return;
@@ -64,8 +79,27 @@ export function MaskOverlay(props: MaskOverlayProps) {
});
};
- const getMaskRect = (segment: MaskSegment) => {
- const state = evaluateMask(segment, currentAbsoluteTime());
+ const displayedMaskSegments = createMemo(() => {
+ const visible = visibleMaskSegments();
+ const hoveredIndex = hoveredMaskIndex();
+ if (
+ hoveredIndex === null ||
+ visible.some(({ index }) => index === hoveredIndex)
+ ) {
+ return visible;
+ }
+ const segment = project.timeline?.maskSegments?.[hoveredIndex];
+ if (!segment) return visible;
+ return [...visible, { segment, index: hoveredIndex }];
+ });
+
+ const getMaskTime = (index: number) =>
+ hoveredMaskIndex() === index && hoveredMaskTime() !== null
+ ? hoveredMaskTime()
+ : currentAbsoluteTime();
+
+ const getMaskRectAtTime = (segment: MaskSegment, time: number) => {
+ const state = evaluateMask(segment, time);
const width = state.size.x * props.size.width;
const height = state.size.y * props.size.height;
const left = state.position.x * props.size.width - width / 2;
@@ -73,6 +107,15 @@ export function MaskOverlay(props: MaskOverlayProps) {
return { width, height, left, top };
};
+ const shouldRenderHoveredMask = () => {
+ const hovered = hoveredMask();
+ return (
+ hovered !== null &&
+ selectedMaskIndex() !== hovered.index &&
+ hoveredMaskTime() !== null
+ );
+ };
+
const handleBackgroundClick = (e: MouseEvent) => {
if (e.target === e.currentTarget && selectedMaskIndex() !== null) {
e.preventDefault();
@@ -91,13 +134,34 @@ export function MaskOverlay(props: MaskOverlayProps) {
onMouseDown={handleBackgroundClick}
/>
</Show>
- <For each={visibleMaskSegments()}>
+ <Show when={shouldRenderHoveredMask() ? hoveredMask() : null}>
+ {(hovered) => {
+ const rect = () =>
+ getMaskRectAtTime(hovered().segment, getMaskTime(hovered().index));
+ return (
+ <div
+ class="absolute z-20 pointer-events-none rounded-md border-2 border-gray-11/65 bg-gray-9/5 shadow-[0_0_0_1px_rgba(255,255,255,0.03)]"
+ style={{
+ left: `${rect().left}px`,
+ top: `${rect().top}px`,
+ width: `${rect().width}px`,
+ height: `${rect().height}px`,
+ }}
+ />
+ );
+ }}
+ </Show>
+ <For each={displayedMaskSegments()}>
{({ segment, index }) => {
const isSelected = () => selectedMaskIndex() === index;
- const rect = () => getMaskRect(segment);
- const maskState = () => evaluateMask(segment, currentAbsoluteTime());
+ const isHovered = () => hoveredMaskIndex() === index;
+ const rect = () => getMaskRectAtTime(segment, getMaskTime(index));
+ const maskState = () => evaluateMask(segment, getMaskTime(index));
const overlayClass = () =>
- "border-gray-12/60 bg-gray-9/5 hover:border-gray-12 hover:bg-gray-9/10";
+ cx(
+ "border-transparent bg-transparent hover:border-gray-11/65 hover:bg-gray-9/5",
+ isHovered() && "border-gray-11/65 bg-gray-9/5",
+ );
return (
<Show
diff --git a/apps/desktop/src/routes/editor/Player.tsx b/apps/desktop/src/routes/editor/Player.tsx
index 0d46b1e14..e6feccb35 100644
--- a/apps/desktop/src/routes/editor/Player.tsx
+++ b/apps/desktop/src/routes/editor/Player.tsx
@@ -11,6 +11,7 @@ import Tooltip from "~/components/Tooltip";
import { captionsStore } from "~/store/captions";
import { commands } from "~/utils/tauri";
import AspectRatioSelect from "./AspectRatioSelect";
+import { createCaptionTrackSegments } from "./captions";
import {
type EditorPreviewQuality,
FPS,
@@ -61,21 +62,17 @@ export function PlayerContent() {
// Load captions on mount
onMount(async () => {
if (editorInstance?.path) {
- // Still load captions into the store since they will be used by the GPU renderer
await captionsStore.loadCaptions(editorInstance.path);
- // Synchronize captions settings with project configuration
- // This ensures the GPU renderer will receive the caption settings
if (editorInstance && project) {
const updatedProject = { ...project };
+ let projectDidChange = false;
+ const captionSegments = captionsStore.state.segments;
+ const hasStoredCaptions = captionSegments.length > 0;
- // Add captions data to project configuration if it doesn't exist
- if (
- !updatedProject.captions &&
- captionsStore.state.segments.length > 0
- ) {
+ if (!updatedProject.captions && hasStoredCaptions) {
updatedProject.captions = {
- segments: captionsStore.state.segments.map((segment) => ({
+ segments: captionSegments.map((segment) => ({
id: segment.id,
start: segment.start,
end: segment.end,
@@ -83,11 +80,47 @@ export function PlayerContent() {
})),
settings: { ...captionsStore.state.settings },
};
+ projectDidChange = true;
+ }
- // Update the project with captions data
- setProject(updatedProject);
+ if (
+ hasStoredCaptions &&
+ (updatedProject.timeline?.captionSegments?.length ?? 0) === 0
+ ) {
+ updatedProject.timeline = {
+ ...(updatedProject.timeline ?? {
+ segments: [
+ {
+ start: 0,
+ end: editorInstance.recordingDuration,
+ timescale: 1,
+ },
+ ],
+ zoomSegments: [],
+ sceneSegments: [],
+ maskSegments: [],
+ textSegments: [],
+ }),
+ captionSegments: createCaptionTrackSegments(captionSegments),
+ };
+ projectDidChange = true;
+ }
+
+ const hasCaptionTrackData =
+ hasStoredCaptions ||
+ (updatedProject.timeline?.captionSegments?.length ?? 0) > 0;
+
+ if (hasCaptionTrackData) {
+ setEditorState(
+ "timeline",
+ "tracks",
+ "caption",
+ updatedProject.captions?.settings?.enabled ?? true,
+ );
+ }
- // Save the updated project configuration
+ if (projectDidChange) {
+ setProject(updatedProject);
await commands.setProjectConfig(
serializeProjectConfiguration(updatedProject),
);
diff --git a/apps/desktop/src/routes/editor/ShareButton.tsx b/apps/desktop/src/routes/editor/ShareButton.tsx
index aa84f21a8..a8e7c9818 100644
--- a/apps/desktop/src/routes/editor/ShareButton.tsx
+++ b/apps/desktop/src/routes/editor/ShareButton.tsx
@@ -298,8 +298,8 @@ function ShareButton() {
<Dialog.Root open={!upload.isIdle}>
<DialogContent
title={"Reupload Recording"}
- confirm={<></>}
- close={<></>}
+ confirm={null}
+ close={null}
class="text-gray-12 dark:text-gray-12"
>
<div class="w-[80%] text-center mx-auto relative z-10 space-y-6 py-4">
diff --git a/apps/desktop/src/routes/in-progress-recording.tsx b/apps/desktop/src/routes/in-progress-recording.tsx
index 44d51e313..f9b9df3e2 100644
--- a/apps/desktop/src/routes/in-progress-recording.tsx
+++ b/apps/desktop/src/routes/in-progress-recording.tsx
@@ -108,6 +108,7 @@ function InProgressRecordingInner() {
const [issuePanelVisible, setIssuePanelVisible] = createSignal(false);
const [issueKey, setIssueKey] = createSignal("");
const [cameraWindowOpen, setCameraWindowOpen] = createSignal(false);
+ const [startingDismissed, setStartingDismissed] = createSignal(false);
const [interactiveAreaRef, setInteractiveAreaRef] =
createSignal<HTMLDivElement | null>(null);
const interactiveBounds = createElementBounds(interactiveAreaRef);
@@ -125,7 +126,7 @@ function InProgressRecordingInner() {
);
});
- const hasDisconnectedInput = () =>
+ const _hasDisconnectedInput = () =>
disconnectedInputs.microphone || disconnectedInputs.camera;
const issueMessages = createMemo(() => {
@@ -184,6 +185,7 @@ function InProgressRecordingInner() {
createTauriEventListener(events.recordingEvent, (payload) => {
switch (payload.variant) {
case "Countdown":
+ setStartingDismissed(false);
setDisconnectedInputs({ microphone: false, camera: false });
setRecordingFailure(null);
setDegradedReason(null);
@@ -194,7 +196,9 @@ function InProgressRecordingInner() {
current: payload.value,
});
break;
- case "Started":
+ case "Started": {
+ const wasStartingDismissed = startingDismissed();
+ setStartingDismissed(false);
setDisconnectedInputs({ microphone: false, camera: false });
setRecordingFailure(null);
setDegradedReason(null);
@@ -202,7 +206,11 @@ function InProgressRecordingInner() {
setState({ variant: "recording" });
setStart(Date.now());
setTime(Date.now());
+ if (wasStartingDismissed) {
+ void getCurrentWindow().show();
+ }
break;
+ }
case "Paused":
if (state().variant === "recording") {
setPauseResumes((a) => [...a, { pause: Date.now() }]);
@@ -243,14 +251,24 @@ function InProgressRecordingInner() {
createEffect(() => {
const s = state();
- if (s.variant === "initializing" || s.variant === "countdown") {
- const recording = currentRecording.data as CurrentRecording | undefined;
- if (recording?.status === "recording") {
- setDisconnectedInputs({ microphone: false, camera: false });
- setRecordingFailure(null);
- setState({ variant: "recording" });
- setStart(Date.now());
- }
+ const recording = currentRecording.data as
+ | CurrentRecording
+ | null
+ | undefined;
+ if (s.variant !== "initializing" && s.variant !== "countdown") return;
+ if (currentRecording.isPending) return;
+ if (recording?.status === "recording") {
+ setStartingDismissed(false);
+ setDisconnectedInputs({ microphone: false, camera: false });
+ setRecordingFailure(null);
+ setState({ variant: "recording" });
+ setStart(Date.now());
+ setTime(Date.now());
+ return;
+ }
+ if (s.variant === "initializing" && !recording) {
+ setState({ variant: "stopped" });
+ void getCurrentWindow().hide();
}
});
@@ -556,6 +574,11 @@ function InProgressRecordingInner() {
};
const isInitializing = () => state().variant === "initializing";
+ const closeStartingBar = async () => {
+ setStartingDismissed(true);
+ setState({ variant: "stopped" });
+ await getCurrentWindow().hide();
+ };
const isCountdown = () => state().variant === "countdown";
const countdownCurrent = () => {
const s = state();
@@ -587,19 +610,27 @@ function InProgressRecordingInner() {
<div class="flex h-full w-full flex-row items-stretch overflow-hidden rounded-2xl bg-gray-1 border border-gray-5 shadow-[0_1px_3px_rgba(0,0,0,0.1)] animate-in fade-in">
<div class="flex flex-1 flex-col gap-2 p-[0.25rem]">
<div class="flex flex-1 flex-row justify-between">
- <button
- disabled={
- stopRecording.isPending || isInitializing() || isCountdown()
+ <Show
+ when={!isInitializing()}
+ fallback={
+ <div class="flex flex-row items-center gap-[0.375rem] rounded-lg py-[0.25rem] px-[0.5rem] text-gray-12">
+ <IconLucideLoader2 class="size-4 animate-spin" />
+ <span class="text-[0.875rem] font-[500] tabular-nums">
+ Starting
+ </span>
+ </div>
}
- class="flex flex-row items-center gap-[0.25rem] rounded-lg py-[0.25rem] px-[0.5rem] text-red-300 transition-colors duration-100 hover:bg-red-500/[0.08] active:bg-red-500/[0.12] disabled:opacity-60 disabled:hover:bg-transparent"
- type="button"
- onClick={() => stopRecording.mutate()}
- title="Stop recording"
- aria-label="Stop recording"
>
- <IconCapStopCircle />
- <span class="text-[0.875rem] font-[500] tabular-nums">
- <Show when={!isInitializing()} fallback="Starting">
+ <button
+ disabled={stopRecording.isPending || isCountdown()}
+ class="flex flex-row items-center gap-[0.25rem] rounded-lg py-[0.25rem] px-[0.5rem] text-red-300 transition-colors duration-100 hover:bg-red-500/[0.08] active:bg-red-500/[0.12] disabled:opacity-60 disabled:hover:bg-transparent"
+ type="button"
+ onClick={() => stopRecording.mutate()}
+ title="Stop recording"
+ aria-label="Stop recording"
+ >
+ <IconCapStopCircle />
+ <span class="text-[0.875rem] font-[500] tabular-nums">
<Show
when={!isCountdown()}
fallback={
@@ -656,9 +687,9 @@ function InProgressRecordingInner() {
{formatTime(remainingRecordingTime() / 1000)}
</Show>
</Show>
- </Show>
- </span>
- </button>
+ </span>
+ </button>
+ </Show>
<div class="flex items-center gap-1">
<div
@@ -709,72 +740,88 @@ function InProgressRecordingInner() {
</div>
)}
</Show>
- <Show when={hasRecordingIssue()}>
+ <Show
+ when={!isInitializing()}
+ fallback={
+ <ActionButton
+ onClick={() => {
+ void closeStartingBar();
+ }}
+ title="Close recording controls"
+ aria-label="Close recording controls"
+ >
+ <IconLucideX class="size-5" />
+ </ActionButton>
+ }
+ >
+ <Show when={hasRecordingIssue()}>
+ <ActionButton
+ class={cx(
+ "text-red-10 hover:bg-red-3/40",
+ issuePanelVisible() &&
+ "bg-red-3/40 ring-1 ring-red-8",
+ )}
+ onClick={() => toggleIssuePanel()}
+ title={issueMessages().join(", ")}
+ aria-pressed={issuePanelVisible() ? "true" : "false"}
+ aria-label="Recording issues"
+ >
+ <IconLucideAlertTriangle class="size-5" />
+ </ActionButton>
+ </Show>
+
+ {canPauseRecording() && (
+ <ActionButton
+ disabled={togglePause.isPending || isCountdown()}
+ onClick={() => togglePause.mutate()}
+ title={
+ state().variant === "paused"
+ ? "Resume recording"
+ : "Pause recording"
+ }
+ aria-label={
+ state().variant === "paused"
+ ? "Resume recording"
+ : "Pause recording"
+ }
+ >
+ {state().variant === "paused" ? (
+ <IconCapPlayCircle />
+ ) : (
+ <IconCapPauseCircle />
+ )}
+ </ActionButton>
+ )}
+
<ActionButton
- class={cx(
- "text-red-10 hover:bg-red-3/40",
- issuePanelVisible() && "bg-red-3/40 ring-1 ring-red-8",
- )}
- onClick={() => toggleIssuePanel()}
- title={issueMessages().join(", ")}
- aria-pressed={issuePanelVisible() ? "true" : "false"}
- aria-label="Recording issues"
+ disabled={restartRecording.isPending || isCountdown()}
+ onClick={() => restartRecording.mutate()}
+ title="Restart recording"
+ aria-label="Restart recording"
>
- <IconLucideAlertTriangle class="size-5" />
+ <IconCapRestart />
</ActionButton>
- </Show>
-
- {canPauseRecording() && (
<ActionButton
- disabled={togglePause.isPending || isCountdown()}
- onClick={() => togglePause.mutate()}
- title={
- state().variant === "paused"
- ? "Resume recording"
- : "Pause recording"
- }
- aria-label={
- state().variant === "paused"
- ? "Resume recording"
- : "Pause recording"
- }
+ disabled={deleteRecording.isPending || isCountdown()}
+ onClick={() => deleteRecording.mutate()}
+ title="Delete recording"
+ aria-label="Delete recording"
>
- {state().variant === "paused" ? (
- <IconCapPlayCircle />
- ) : (
- <IconCapPauseCircle />
- )}
+ <IconCapTrash />
</ActionButton>
- )}
-
- <ActionButton
- disabled={restartRecording.isPending || isCountdown()}
- onClick={() => restartRecording.mutate()}
- title="Restart recording"
- aria-label="Restart recording"
- >
- <IconCapRestart />
- </ActionButton>
- <ActionButton
- disabled={deleteRecording.isPending || isCountdown()}
- onClick={() => deleteRecording.mutate()}
- title="Delete recording"
- aria-label="Delete recording"
- >
- <IconCapTrash />
- </ActionButton>
- <ActionButton
- ref={(el) => {
- settingsButtonRef = el ?? undefined;
- }}
- onClick={() => {
- void openRecordingSettingsMenu();
- }}
- title="Recording settings"
- aria-label="Recording settings"
- >
- <IconCapSettings class="size-5" />
- </ActionButton>
+ <ActionButton
+ ref={(el) => {
+ settingsButtonRef = el ?? undefined;
+ }}
+ onClick={() => {
+ void openRecordingSettingsMenu();
+ }}
+ title="Recording settings"
+ aria-label="Recording settings"
+ >
+ <IconCapSettings class="size-5" />
+ </ActionButton>
+ </Show>
</div>
</div>
</div>