Skip to content

armgit / Cap

Public Imported from GitHub
0

Open source Loom alternative. Beautiful, shareable screen recordings.

wip: Metadata moved to export options

Richie McIlroy44bbe11f670b
diff --git a/apps/desktop/src/routes/editor/Header.tsx b/apps/desktop/src/routes/editor/Header.tsx
index f14bf5b89..fa9ec6a20 100644
--- a/apps/desktop/src/routes/editor/Header.tsx
+++ b/apps/desktop/src/routes/editor/Header.tsx
@@ -7,35 +7,90 @@ import {
batch,
createEffect,
createResource,
+ createSignal,
onCleanup,
onMount,
} from "solid-js";
import { type as ostype } from "@tauri-apps/plugin-os";
import { Tooltip } from "@kobalte/core";
+import { Select as KSelect } from "@kobalte/core/select";
+import { createMutation } from "@tanstack/solid-query";
+import { getRequestEvent } from "solid-js/web";
+import { save } from "@tauri-apps/plugin-dialog";
+import { Channel } from "@tauri-apps/api/core";
+import type { UnlistenFn } from "@tauri-apps/api/event";
+import { getCurrentWindow, ProgressBarStatus } from "@tauri-apps/api/window";
import { type RenderProgress, commands } from "~/utils/tauri";
-
-import { useEditorContext } from "./context";
-import { Dialog, DialogContent } from "./ui";
+import {
+ canCreateShareableLink,
+ checkIsUpgradedAndUpdate,
+} from "~/utils/plans";
+import { FPS, useEditorContext } from "./context";
+import {
+ Dialog,
+ DialogContent,
+ MenuItem,
+ MenuItemList,
+ PopperContent,
+ topLeftAnimateClasses,
+} from "./ui";
+import { DEFAULT_PROJECT_CONFIG } from "./projectConfig";
import {
type ProgressState,
progressState,
setProgressState,
} from "~/store/progress";
-
import { events } from "~/utils/tauri";
import Titlebar from "~/components/titlebar/Titlebar";
import { initializeTitlebar, setTitlebar } from "~/utils/titlebar-state";
-import type { UnlistenFn } from "@tauri-apps/api/event";
-import { getCurrentWindow, ProgressBarStatus } from "@tauri-apps/api/window";
-import IconLucideHardDrive from "~icons/lucide/hard-drive";
-import IconLucideCheck from "~icons/lucide/check";
-import IconLucideLoaderCircle from "~icons/lucide/loader-circle";
-import IconLucideRotateCcw from "~icons/lucide/rotate-ccw";
-import IconLucideClock from "~icons/lucide/clock";
+
+type ResolutionOption = {
+ label: string;
+ value: string;
+ width: number;
+ height: number;
+};
+
+const RESOLUTION_OPTIONS: ResolutionOption[] = [
+ { label: "720p", value: "720p", width: 1280, height: 720 },
+ { label: "1080p", value: "1080p", width: 1920, height: 1080 },
+ { label: "4K", value: "4k", width: 3840, height: 2160 },
+];
+
+const FPS_OPTIONS = [
+ { label: "30 FPS", value: 30 },
+ { label: "60 FPS", value: 60 },
+] satisfies Array<{ label: string; value: number }>;
export function Header() {
const currentWindow = getCurrentWindow();
+ const { videoId, project, prettyName } = useEditorContext();
+
+ const [metadata] = createResource(async () => {
+ const result = await commands.getVideoMetadata(videoId, null).catch((e) => {
+ console.error(`Failed to get metadata: ${e}`);
+ });
+ if (!result) return;
+
+ const { duration, size } = result;
+ const estimatedExportTime = Math.ceil(duration * 1.5);
+ console.log(
+ `Metadata for video: duration=${duration}, size=${size}, estimatedExport=${estimatedExportTime}`
+ );
+ return { duration, size, estimatedExportTime };
+ });
+
+ const [showExportOptions, setShowExportOptions] = createSignal(false);
+ const [selectedFps, setSelectedFps] = createSignal(
+ Number(localStorage.getItem("cap-export-fps")) || 30
+ );
+ const [selectedResolution, setSelectedResolution] =
+ createSignal<ResolutionOption>(
+ RESOLUTION_OPTIONS.find(
+ (opt) => opt.value === localStorage.getItem("cap-export-resolution")
+ ) || RESOLUTION_OPTIONS[0]
+ );
let unlistenTitlebar: UnlistenFn | undefined;
onMount(async () => {
@@ -43,6 +98,12 @@ export function Header() {
});
onCleanup(() => unlistenTitlebar?.());
+ // Save settings when they change
+ createEffect(() => {
+ localStorage.setItem("cap-export-fps", selectedFps().toString());
+ localStorage.setItem("cap-export-resolution", selectedResolution().value);
+ });
+
createEffect(() => {
const state = progressState;
if (state === undefined || state.type === "idle") {
@@ -65,6 +126,91 @@ export function Header() {
currentWindow.setProgressBar({ progress: Math.round(percentage) });
});
+ const exportWithSettings = async () => {
+ setShowExportOptions(false);
+
+ const path = await save({
+ filters: [{ name: "mp4 filter", extensions: ["mp4"] }],
+ defaultPath: `~/Desktop/${prettyName()}.mp4`,
+ });
+ if (!path) return;
+
+ setProgressState({
+ type: "saving",
+ progress: 0,
+ renderProgress: 0,
+ totalFrames: 0,
+ message: "Preparing to render...",
+ mediaPath: path,
+ stage: "rendering",
+ });
+
+ const progress = new Channel<RenderProgress>();
+ progress.onmessage = (p) => {
+ if (p.type === "FrameRendered" && progressState.type === "saving") {
+ const percentComplete = Math.min(
+ Math.round(
+ (p.current_frame / (progressState.totalFrames || 1)) * 100
+ ),
+ 100
+ );
+
+ setProgressState({
+ ...progressState,
+ renderProgress: p.current_frame,
+ message: `Rendering video - ${percentComplete}%`,
+ });
+
+ // If rendering is complete, update to finalizing state
+ if (percentComplete === 100) {
+ setProgressState({
+ ...progressState,
+ message: "Finalizing export...",
+ });
+ }
+ }
+ if (
+ p.type === "EstimatedTotalFrames" &&
+ progressState.type === "saving"
+ ) {
+ setProgressState({
+ ...progressState,
+ totalFrames: p.total_frames,
+ message: "Starting render...",
+ });
+ }
+ };
+
+ try {
+ const videoPath = await commands.exportVideo(
+ videoId,
+ project,
+ progress,
+ true,
+ selectedFps(),
+ {
+ x: selectedResolution().width,
+ y: selectedResolution().height,
+ }
+ );
+ await commands.copyFileToPath(videoPath, path);
+
+ setProgressState({
+ type: "saving",
+ progress: 100,
+ message: "Saved successfully!",
+ mediaPath: path,
+ });
+
+ setTimeout(() => {
+ setProgressState({ type: "idle" });
+ }, 1500);
+ } catch (error) {
+ setProgressState({ type: "idle" });
+ throw error;
+ }
+ };
+
batch(() => {
setTitlebar("border", false);
setTitlebar("height", "4rem");
@@ -80,8 +226,151 @@ export function Header() {
>
<div class="flex flex-row items-center gap-[0.5rem] text-[0.875rem]"></div>
<div class="flex flex-row gap-2 font-medium items-center">
- <ShareButton />
- <ExportButton />
+ <ShareButton
+ selectedResolution={selectedResolution}
+ selectedFps={selectedFps}
+ />
+ <div class="relative">
+ <Button
+ variant="primary"
+ onClick={() => setShowExportOptions(!showExportOptions())}
+ >
+ Export
+ </Button>
+ <Show when={showExportOptions()}>
+ <div class="absolute right-0 top-full mt-2 bg-gray-50 dark:bg-gray-800 border border-gray-200 dark:border-gray-700 rounded-lg shadow-lg z-40 p-4 min-w-[240px]">
+ <div class="space-y-4">
+ <div>
+ <label class="block text-sm font-medium mb-1 text-gray-700 dark:text-gray-300">
+ Resolution
+ </label>
+ <KSelect<ResolutionOption>
+ options={RESOLUTION_OPTIONS}
+ optionValue="value"
+ optionTextValue="label"
+ placeholder="Select Resolution"
+ value={selectedResolution()}
+ onChange={setSelectedResolution}
+ itemComponent={(props) => (
+ <MenuItem<typeof KSelect.Item>
+ as={KSelect.Item}
+ item={props.item}
+ >
+ <KSelect.ItemLabel class="flex-1">
+ {props.item.rawValue.label}
+ </KSelect.ItemLabel>
+ </MenuItem>
+ )}
+ >
+ <KSelect.Trigger class="flex flex-row items-center h-[2rem] px-[0.375rem] gap-[0.375rem] border rounded-lg border-gray-200 w-full disabled:text-gray-400 transition-colors KSelect">
+ <KSelect.Value<ResolutionOption> class="flex-1 text-sm text-left truncate">
+ {(state) => (
+ <span>{state.selectedOption()?.label}</span>
+ )}
+ </KSelect.Value>
+ <KSelect.Icon>
+ <IconCapChevronDown class="size-4 shrink-0 transform transition-transform ui-expanded:rotate-180" />
+ </KSelect.Icon>
+ </KSelect.Trigger>
+ <KSelect.Portal>
+ <PopperContent<typeof KSelect.Content>
+ as={KSelect.Content}
+ class={cx(topLeftAnimateClasses, "z-50")}
+ >
+ <MenuItemList<typeof KSelect.Listbox>
+ class="max-h-32 overflow-y-auto"
+ as={KSelect.Listbox}
+ />
+ </PopperContent>
+ </KSelect.Portal>
+ </KSelect>
+ </div>
+ <div>
+ <label class="block text-sm font-medium mb-1 text-gray-700 dark:text-gray-300">
+ Frame Rate
+ </label>
+ <KSelect<(typeof FPS_OPTIONS)[number]>
+ options={FPS_OPTIONS}
+ optionValue="value"
+ optionTextValue="label"
+ placeholder="Select FPS"
+ value={FPS_OPTIONS.find(
+ (opt) => opt.value === selectedFps()
+ )}
+ onChange={(option) => setSelectedFps(option?.value ?? 30)}
+ itemComponent={(props) => (
+ <MenuItem<typeof KSelect.Item>
+ as={KSelect.Item}
+ item={props.item}
+ >
+ <KSelect.ItemLabel class="flex-1">
+ {props.item.rawValue.label}
+ </KSelect.ItemLabel>
+ </MenuItem>
+ )}
+ >
+ <KSelect.Trigger class="flex flex-row items-center h-[2rem] px-[0.375rem] gap-[0.375rem] border rounded-lg border-gray-200 w-full disabled:text-gray-400 transition-colors KSelect">
+ <KSelect.Value<
+ (typeof FPS_OPTIONS)[number]
+ > class="flex-1 text-sm text-left truncate">
+ {(state) => (
+ <span>{state.selectedOption()?.label}</span>
+ )}
+ </KSelect.Value>
+ <KSelect.Icon>
+ <IconCapChevronDown class="size-4 shrink-0 transform transition-transform ui-expanded:rotate-180" />
+ </KSelect.Icon>
+ </KSelect.Trigger>
+ <KSelect.Portal>
+ <PopperContent<typeof KSelect.Content>
+ as={KSelect.Content}
+ class={cx(topLeftAnimateClasses, "z-50")}
+ >
+ <MenuItemList<typeof KSelect.Listbox>
+ class="max-h-32 overflow-y-auto"
+ as={KSelect.Listbox}
+ />
+ </PopperContent>
+ </KSelect.Portal>
+ </KSelect>
+ </div>
+ <Show when={metadata()}>
+ {(meta) => (
+ <div class="text-xs bg-gray-100 dark:bg-gray-600/30 text-gray-500 dark:text-gray-400 flex items-center gap-4 px-3 py-1.5 rounded-full">
+ <span class="flex items-center">
+ <IconCapCamera class="w-3 h-3 mr-1.5 opacity-80" />
+ {Math.floor(meta().duration / 60)}:
+ {Math.floor(meta().duration % 60)
+ .toString()
+ .padStart(2, "0")}
+ </span>
+ <div class="w-[1px] h-2.5 bg-gray-300 dark:bg-gray-500/50"></div>
+ <span class="flex items-center">
+ <IconLucideHardDrive class="w-3 h-3 mr-1.5 opacity-80" />
+ {meta().size.toFixed(2)} MB
+ </span>
+ <div class="w-[1px] h-2.5 bg-gray-300 dark:bg-gray-500/50"></div>
+ <span class="flex items-center">
+ <IconLucideClock class="w-3 h-3 mr-1.5 opacity-80" />~
+ {Math.floor(meta().estimatedExportTime / 60)}:
+ {Math.floor(meta().estimatedExportTime % 60)
+ .toString()
+ .padStart(2, "0")}
+ </span>
+ </div>
+ )}
+ </Show>
+ <Button
+ variant="primary"
+ class="w-full justify-center"
+ onClick={exportWithSettings}
+ >
+ Export Video
+ </Button>
+ </div>
+ </div>
+ </Show>
+ </div>
</div>
</div>
);
@@ -239,149 +528,12 @@ export function Header() {
);
}
-import { Channel } from "@tauri-apps/api/core";
-import { save } from "@tauri-apps/plugin-dialog";
-import { DEFAULT_PROJECT_CONFIG } from "./projectConfig";
-import { createMutation } from "@tanstack/solid-query";
-import { getRequestEvent } from "solid-js/web";
-import { checkIsUpgradedAndUpdate } from "~/utils/plans";
+type ShareButtonProps = {
+ selectedResolution: () => ResolutionOption;
+ selectedFps: () => number;
+};
-function ExportButton() {
- const { videoId, project, prettyName } = useEditorContext();
-
- const [metadata] = createResource(async () => {
- const result = await commands.getVideoMetadata(videoId, null).catch((e) => {
- console.error(`Failed to get metadata: ${e}`);
- });
- if (!result) return;
-
- const { duration, size } = result;
- const estimatedExportTime = Math.ceil(duration * 1.5);
- console.log(`Metadata for video: duration=${duration}, size=${size}, estimatedExport=${estimatedExportTime}`);
- return { duration, size, estimatedExportTime };
- });
-
- const exportVideo = createMutation(() => ({
- mutationFn: async (useCustomMuxer: boolean) => {
- const path = await save({
- filters: [{ name: "mp4 filter", extensions: ["mp4"] }],
- defaultPath: `~/Desktop/${prettyName()}.mp4`,
- });
- if (!path) return;
-
- setProgressState({
- type: "saving",
- progress: 0,
- renderProgress: 0,
- totalFrames: 0,
- message: "Preparing to render...",
- mediaPath: path,
- stage: "rendering",
- });
-
- const progress = new Channel<RenderProgress>();
- progress.onmessage = (p) => {
- if (p.type === "FrameRendered" && progressState.type === "saving") {
- const percentComplete = Math.min(
- Math.round(
- (p.current_frame / (progressState.totalFrames || 1)) * 100
- ),
- 100
- );
-
- setProgressState({
- ...progressState,
- renderProgress: p.current_frame,
- message: `Rendering video - ${percentComplete}%`,
- });
-
- // If rendering is complete, update to finalizing state
- if (percentComplete === 100) {
- setProgressState({
- ...progressState,
- message: "Finalizing export...",
- });
- }
- }
- if (
- p.type === "EstimatedTotalFrames" &&
- progressState.type === "saving"
- ) {
- setProgressState({
- ...progressState,
- totalFrames: p.total_frames,
- message: "Starting render...",
- });
- }
- };
-
- try {
- const videoPath = await commands.exportVideo(
- videoId,
- project,
- progress,
- true,
- useCustomMuxer
- );
- await commands.copyFileToPath(videoPath, path);
-
- setProgressState({
- type: "saving",
- progress: 100,
- message: "Saved successfully!",
- mediaPath: path,
- });
-
- setTimeout(() => {
- setProgressState({ type: "idle" });
- }, 1500);
- } catch (error) {
- setProgressState({ type: "idle" });
- throw error;
- }
- },
- }));
-
- return (
- <div class="flex flex-row items-center gap-2">
- <Button
- variant="primary"
- size="md"
- onClick={(e) =>
- exportVideo.mutate((e.ctrlKey || e.metaKey) && e.shiftKey)
- }
- >
- Export
- </Button>
- <Show when={metadata()}>
- {(meta) => (
- <div class="text-xs bg-gray-100 dark:bg-gray-600/30 text-gray-500 dark:text-gray-400 flex items-center gap-4 px-3 py-1.5 rounded-full">
- <span class="flex items-center">
- <IconCapCamera class="w-3 h-3 mr-1.5 opacity-80" />
- {Math.floor(meta().duration / 60)}:{Math.floor(meta().duration % 60)
- .toString()
- .padStart(2, "0")}
- </span>
- <div class="w-[1px] h-2.5 bg-gray-300 dark:bg-gray-500/50"></div>
- <span class="flex items-center">
- <IconLucideHardDrive class="w-3 h-3 mr-1.5 opacity-80" />
- {meta().size.toFixed(2)} MB
- </span>
- <div class="w-[1px] h-2.5 bg-gray-300 dark:bg-gray-500/50"></div>
- <span class="flex items-center">
- <IconLucideClock class="w-3 h-3 mr-1.5 opacity-80" />
- ~{Math.floor(meta().estimatedExportTime / 60)}:{Math.floor(meta().estimatedExportTime % 60)
- .toString()
- .padStart(2, "0")}
- </span>
- </div>
- )}
- </Show>
- </div>
- );
-}
-
-function ShareButton() {
+function ShareButton(props: ShareButtonProps) {
const { videoId, project, presets } = useEditorContext();
const [recordingMeta, metaActions] = createResource(() =>
commands.getRecordingMeta(videoId, "recording")
@@ -390,16 +542,22 @@ function ShareButton() {
const uploadVideo = createMutation(() => ({
mutationFn: async (useCustomMuxer: boolean) => {
console.log("Starting upload process...");
- if (!recordingMeta()) {
+ const meta = recordingMeta();
+ if (!meta) {
console.error("No recording metadata available");
throw new Error("Recording metadata not available");
}
- // Check for pro access first before starting the export
- const isUpgraded = await checkIsUpgradedAndUpdate();
- if (!isUpgraded) {
- await commands.showWindow("Upgrade");
- throw new Error("Upgrade required to share recordings");
+ const metadata = await commands.getVideoMetadata(videoId, null);
+ const canShare = await canCreateShareableLink(metadata?.duration);
+
+ if (!canShare.allowed) {
+ if (canShare.reason === "upgrade_required") {
+ await commands.showWindow("Upgrade");
+ throw new Error(
+ "Upgrade required to share recordings over 5 minutes"
+ );
+ }
}
let unlisten: (() => void) | undefined;
@@ -443,8 +601,6 @@ function ShareButton() {
});
console.log("Starting actual upload...");
- const projectConfig =
- project ?? presets.getDefaultConfig() ?? DEFAULT_PROJECT_CONFIG;
setProgressState({
type: "uploading",
@@ -487,10 +643,14 @@ function ShareButton() {
await commands.exportVideo(
videoId,
- projectConfig,
+ project,
progress,
true,
- false
+ props.selectedFps(),
+ {
+ x: props.selectedResolution().width,
+ y: props.selectedResolution().height,
+ }
);
// Now proceed with upload
@@ -500,8 +660,6 @@ function ShareButton() {
Initial: { pre_created_video: null },
});
- console.log("Upload result:", result);
-
if (result === "NotAuthenticated") {
throw new Error("You need to sign in to share recordings");
}