Skip to content

armgit / Cap

Public Imported from GitHub
0

Open source Loom alternative. Beautiful, shareable screen recordings.

Add UI + update collapsible animations with a little blur

Ilyab1e4a603c503
diff --git a/apps/desktop/src-tauri/src/lib.rs b/apps/desktop/src-tauri/src/lib.rs
index 6088842a1..9ffc8f03d 100644
--- a/apps/desktop/src-tauri/src/lib.rs
+++ b/apps/desktop/src-tauri/src/lib.rs
@@ -1902,6 +1902,7 @@ pub async fn run(recording_logging_handle: LoggingHandle, logs_dir: PathBuf) {
target_select_overlay::focus_window,
editor_delete_project,
format_project_name,
+ sanitize_filename,
])
.events(tauri_specta::collect_events![
RecordingOptionsChanged,
@@ -2648,7 +2649,7 @@ async fn format_project_name(
target_name: String,
target_kind: String,
recording_mode: RecordingMode,
- datetime: chrono::DateTime<chrono::Local>,
+ datetime: Option<chrono::DateTime<chrono::Local>>,
) -> String {
recording::format_project_name(
template.as_deref(),
@@ -2659,6 +2660,18 @@ async fn format_project_name(
)
}
+#[tauri::command]
+#[specta::specta]
+async fn sanitize_filename(filename: String) -> String {
+ sanitize_filename::sanitize_with_options(
+ filename,
+ sanitize_filename::Options {
+ replacement: "-",
+ ..Default::default()
+ },
+ )
+}
+
trait EventExt: tauri_specta::Event {
fn listen_any_spawn<Fut>(
app: &AppHandle,
diff --git a/apps/desktop/src-tauri/src/recording.rs b/apps/desktop/src-tauri/src/recording.rs
index 31e1b5ae4..bc285a22d 100644
--- a/apps/desktop/src-tauri/src/recording.rs
+++ b/apps/desktop/src-tauri/src/recording.rs
@@ -25,6 +25,7 @@ use lazy_static::lazy_static;
use regex::Regex;
use serde::{Deserialize, Serialize};
use specta::Type;
+use std::borrow::Cow;
use std::{
collections::{HashMap, VecDeque},
path::PathBuf,
@@ -259,15 +260,6 @@ pub enum RecordingAction {
UpgradeRequired,
}
-lazy_static! {
- static ref DATE_REGEX: Regex = Regex::new(r"\{date(?::([^}]+))?\}").unwrap();
- static ref TIME_REGEX: Regex = Regex::new(r"\{time(?::([^}]+))?\}").unwrap();
- static ref DATETIME_REGEX: Regex = Regex::new(r"\{datetime(?::([^}]+))?\}").unwrap();
- static ref TIMESTAMP_REGEX: Regex = Regex::new(r"\{timestamp(?::([^}]+))?\}").unwrap();
-}
-
-pub const DEFAULT_FILENAME_TEMPLATE: &str = "{target} {datetime}";
-
/// Formats the project name using a template string.
///
/// # Template Variables
@@ -285,25 +277,20 @@ pub const DEFAULT_FILENAME_TEMPLATE: &str = "{target} {datetime}";
/// ## Date/Time Variables
/// - `{date}` - Current date in YYYY-MM-DD format (e.g., "2025-09-11")
/// - `{time}` - Current time in HH:MM AM/PM format (e.g., "3:23 PM")
-/// - `{datetime}` - Combined date and time (e.g., "2025-09-11 3:23 PM")
-/// - `{timestamp}` - Unix timestamp (e.g., "1705326783")
///
/// ## Customizable Date/Time Formats
/// You can customize date and time formats by adding moment format specifiers:
-/// - `{date:YYYY-MM-DD}` - Custom date format
-/// - `{time:HH:mm}` - 24-hour time format
-/// - `{time:hh:mm A}` - 12-hour time with AM/PM
-/// - `{datetime:YYYY-MM-DD HH:mm}` - Combined custom format
+/// - `{moment:YYYY-MM-DD}` - Custom date format
+/// - `{moment:HH:mm}` - 24-hour time format
+/// - `{moment:hh:mm A}` - 12-hour time with AM/PM
+/// - `{moment:YYYY-MM-DD HH:mm}` - Combined custom format
///
/// ## Examples
///
/// `{recording_mode} Recording {target_kind} ({target_name}) {date} {time}`
/// -> "Instant Recording Display (Built-in Retina Display) 2025-11-12 3:23 PM"
///
-/// `{recording_mode} Recording {target_kind} ({target_name}) {date} {time}`
-/// -> "instant_display_20250115_1523"
-///
-/// `Cap {target} - {datetime:YYYY-MM-DD HH:mm}`
+/// `Cap {target} - {date} {time}`
/// -> "Cap Display (Built-in Retina Display) - 2025-11-12 15:23"
///
///
@@ -320,9 +307,15 @@ pub fn format_project_name<'a>(
target_name: &'a str,
target_kind: &'a str,
recording_mode: RecordingMode,
- datetime: chrono::DateTime<chrono::Local>,
+ datetime: Option<chrono::DateTime<chrono::Local>>,
) -> String {
+ const DEFAULT_FILENAME_TEMPLATE: &str = "{target_name} ({target_kind}) {date} {time}";
+ let datetime = datetime.unwrap_or(chrono::Local::now());
+
lazy_static! {
+ static ref DATE_REGEX: Regex = Regex::new(r"\{date(?::([^}]+))?\}").unwrap();
+ static ref TIME_REGEX: Regex = Regex::new(r"\{time(?::([^}]+))?\}").unwrap();
+ static ref MOMENT_REGEX: Regex = Regex::new(r"\{moment(?::([^}]+))?\}").unwrap();
static ref AC: aho_corasick::AhoCorasick = {
aho_corasick::AhoCorasick::new(&[
"{recording_mode}",
@@ -333,7 +326,7 @@ pub fn format_project_name<'a>(
.expect("Failed to build AhoCorasick automaton")
};
}
- let template = template.unwrap_or(DEFAULT_FILENAME_TEMPLATE);
+ let haystack = template.unwrap_or(DEFAULT_FILENAME_TEMPLATE);
// Get recording mode information
let (recording_mode, mode) = match recording_mode {
@@ -342,31 +335,43 @@ pub fn format_project_name<'a>(
};
let result = AC
- .try_replace_all(&template, &[recording_mode, mode, target_kind, target_name])
+ .try_replace_all(&haystack, &[recording_mode, mode, target_kind, target_name])
.expect("AhoCorasick replace should never fail with default configuration");
let result = DATE_REGEX.replace_all(&result, |caps: &regex::Captures| {
- let format = caps.get(1).map(|m| m.as_str()).unwrap_or("%Y-%m-%d");
- let chrono_format = moment_format_to_chrono(format);
- datetime.format(&chrono_format).to_string()
+ datetime
+ .format(
+ &caps
+ .get(1)
+ .map(|m| m.as_str())
+ .map(moment_format_to_chrono)
+ .unwrap_or(Cow::Borrowed("%Y-%m-%d")),
+ )
+ .to_string()
});
let result = TIME_REGEX.replace_all(&result, |caps: &regex::Captures| {
- let format = caps.get(1).map(|m| m.as_str()).unwrap_or("%l:%M %p");
- let chrono_format = moment_format_to_chrono(format);
- datetime.format(&chrono_format).to_string()
- });
-
- let result = DATETIME_REGEX.replace_all(&result, |caps: &regex::Captures| {
- let format = caps.get(1).map(|m| m.as_str()).unwrap_or("%Y-%m-%d %H:%M");
- let chrono_format = moment_format_to_chrono(format);
- datetime.format(&chrono_format).to_string()
+ datetime
+ .format(
+ &caps
+ .get(1)
+ .map(|m| m.as_str())
+ .map(moment_format_to_chrono)
+ .unwrap_or(Cow::Borrowed("%I:%M %p")),
+ )
+ .to_string()
});
- let result = TIMESTAMP_REGEX.replace_all(&result, |caps: &regex::Captures| {
- caps.get(1)
- .map(|m| datetime.format(m.as_str()).to_string())
- .unwrap_or_else(|| datetime.timestamp().to_string())
+ let result = MOMENT_REGEX.replace_all(&result, |caps: &regex::Captures| {
+ datetime
+ .format(
+ &caps
+ .get(1)
+ .map(|m| m.as_str())
+ .map(moment_format_to_chrono)
+ .unwrap_or(Cow::Borrowed("%Y-%m-%d %H:%M")),
+ )
+ .to_string()
});
result.into_owned()
@@ -398,7 +403,7 @@ pub async fn start_recording(
.unwrap_or("Unknown"),
inputs.capture_target.kind_str(),
inputs.mode,
- chrono::Local::now(),
+ None,
);
let filename = project_name.replace(":", ".");
diff --git a/apps/desktop/src/routes/(window-chrome)/settings/general.tsx b/apps/desktop/src/routes/(window-chrome)/settings/general.tsx
index 52cd6384b..7495791f0 100644
--- a/apps/desktop/src/routes/(window-chrome)/settings/general.tsx
+++ b/apps/desktop/src/routes/(window-chrome)/settings/general.tsx
@@ -6,6 +6,7 @@ import {
} from "@tauri-apps/plugin-notification";
import { type OsType, type } from "@tauri-apps/plugin-os";
import "@total-typescript/ts-reset/filter-boolean";
+import { Collapsible } from "@kobalte/core/collapsible";
import { CheckMenuItem, Menu, MenuItem } from "@tauri-apps/api/menu";
import { confirm } from "@tauri-apps/plugin-dialog";
import { cx } from "cva";
@@ -13,7 +14,9 @@ import {
createEffect,
createMemo,
createResource,
+ createSignal,
For,
+ onMount,
type ParentProps,
Show,
} from "solid-js";
@@ -98,6 +101,9 @@ const INSTANT_MODE_RESOLUTION_OPTIONS = [
label: string;
}[];
+const DEFAULT_PROJECT_NAME_TEMPLATE =
+ "{target_name} ({target_kind}) {date} {time}";
+
export default function GeneralSettings() {
const [store] = createResource(() => generalSettingsStore.get());
@@ -498,6 +504,13 @@ function Inner(props: { initialStore: GeneralSettingsStore | null }) {
/>
</SettingGroup>
+ <DefaultProjectNameCard
+ onChange={(value) =>
+ handleChange("defaultProjectNameTemplate", value)
+ }
+ value={settings.defaultProjectNameTemplate ?? null}
+ />
+
<ExcludedWindowsCard
excludedWindows={excludedWindows()}
availableWindows={availableWindows()}
@@ -583,6 +596,210 @@ function ServerURLSetting(props: {
);
}
+function DefaultProjectNameCard(props: {
+ value: string | null;
+ onChange: (name: string | null) => Promise<void>;
+}) {
+ const MOMENT_EXAMPLE_TEMPLATE = "{moment:DDDD, MMMM D, YYYY h:mm A}";
+ const macos = type() === "macos";
+ const today = new Date();
+ const datetime = new Date(
+ today.getFullYear(),
+ today.getMonth(),
+ today.getDate(),
+ macos ? 9 : 12,
+ macos ? 41 : 0,
+ 0,
+ 0,
+ ).toISOString();
+
+ let inputRef: HTMLInputElement | undefined;
+
+ const dateString = today.toISOString().split("T")[0];
+ const initialTemplate = () => props.value ?? DEFAULT_PROJECT_NAME_TEMPLATE;
+
+ const [inputValue, setInputValue] = createSignal<string>(initialTemplate());
+ const [preview, setPreview] = createSignal<string | null>(null);
+ const [momentExample, setMomentExample] = createSignal("");
+
+ async function updatePreview(val = inputValue()) {
+ const formatted = await commands.formatProjectName(
+ val,
+ macos ? "Safari" : "Chrome",
+ "Window",
+ "instant",
+ datetime,
+ );
+ setPreview(formatted);
+ }
+
+ onMount(() => {
+ commands
+ .formatProjectName(
+ MOMENT_EXAMPLE_TEMPLATE,
+ macos ? "Safari" : "Chrome",
+ "Window",
+ "instant",
+ datetime,
+ )
+ .then(setMomentExample);
+
+ const seed = initialTemplate();
+ setInputValue(seed);
+ if (inputRef) inputRef.value = seed;
+ updatePreview(seed);
+ });
+
+ const isSaveDisabled = () => {
+ const input = inputValue();
+ return (
+ !input ||
+ input === (props.value ?? DEFAULT_PROJECT_NAME_TEMPLATE) ||
+ input.length <= 3
+ );
+ };
+
+ function CodeView(props: { children: string }) {
+ return (
+ <button
+ type="button"
+ title="Click to copy"
+ class="bg-gray-1 hover:bg-gray-5 rounded-md m-0.5 p-0.5 cursor-pointer transition-[color,background-color,transform] ease-out duration-200 active:scale-95"
+ onClick={() => commands.writeClipboardString(props.children)}
+ >
+ <code>{props.children}</code>
+ </button>
+ );
+ }
+
+ return (
+ <div class="flex flex-col gap-3 px-4 py-3 mt-6 rounded-xl border border-gray-3 bg-gray-2">
+ <div class="flex flex-col gap-3 sm:flex-row sm:items-start sm:justify-between sm:gap-4">
+ <div class="flex flex-col gap-2 w-full">
+ <p class="text-sm text-gray-12">Default Project Name</p>
+ <p class="text-xs text-gray-10 pb-1">
+ Choose the template to use as the default project name.
+ <br />
+ This will also be used as the default file name for new projects.
+ </p>
+
+ <Input
+ autocorrect="off"
+ ref={inputRef}
+ type="text"
+ class="bg-gray-3 font-mono"
+ value={inputValue()}
+ onInput={(e) => {
+ setInputValue(e.currentTarget.value);
+ updatePreview(e.currentTarget.value);
+ }}
+ />
+
+ <div class="w-full flex items-center py-2 px-2 rounded-lg bg-gray-transparent-50 border border-dashed border-gray-5">
+ <IconCapLogo class="size-4 pointer-events-none mr-2" />
+ <p class="whitespace-pre-wrap">{preview()}</p>
+ </div>
+
+ <Collapsible class="w-full rounded-lg">
+ <Collapsible.Trigger class="group inline-flex items-center w-full text-xs rounded-lg outline-none px-0.5 py-1">
+ <IconCapChevronDown class="size-4 ui-group-expanded:rotate-180 transition-transform duration-300 ease-in-out" />
+ <p class="py-0.5 px-1">How to customize?</p>
+ </Collapsible.Trigger>
+
+ <Collapsible.Content class="opacity-0 transition animate-collapsible-up ui-expanded:animate-collapsible-down ui-expanded:opacity-100 text-xs text-gray-12 space-y-3 px-1 pb-2">
+ <p class="border-t pt-3">
+ Use placeholders in your template that will be automatically
+ filled in.
+ </p>
+
+ <div class="space-y-1">
+ <p class="font-medium text-foreground">Recording Mode</p>
+ <p>
+ <CodeView>{"{recording_mode}"}</CodeView> → "Studio" or
+ "Instant"
+ </p>
+ <p>
+ <CodeView>{"{mode}"}</CodeView> → "studio" or "instant"
+ </p>
+ </div>
+
+ <div class="space-y-1">
+ <p class="font-medium text-foreground">Target</p>
+ <p>
+ <CodeView>{"{target_kind}"}</CodeView> → "Display", "Window",
+ or "Area"
+ </p>
+ <p>
+ <CodeView>{"{target_name}"}</CodeView> → The name of the
+ monitor or the title of the app depending on the recording
+ mode.
+ </p>
+ </div>
+
+ <div class="space-y-1">
+ <p class="font-medium text-foreground">Date &amp; Time</p>
+ <p>
+ <CodeView>{"{date}"}</CodeView> → {dateString}
+ </p>
+ <p>
+ <CodeView>{"{time}"}</CodeView> →{" "}
+ {macos ? "09:41 AM" : "12:00 PM"}
+ </p>
+ </div>
+
+ <div class="space-y-1">
+ <p class="font-medium text-foreground">Custom Formats</p>
+ <p>
+ You can also use a custom format for time. The placeholders
+ are case-sensitive. For 24-hour time, use{" "}
+ <CodeView>{"{moment:HH:mm}"}</CodeView> or use lower cased{" "}
+ <code>hh</code> for 12-hour format.
+ </p>
+ <p class="flex flex-col items-start pt-1">
+ <CodeView>{MOMENT_EXAMPLE_TEMPLATE}</CodeView> →{" "}
+ {momentExample()}
+ </p>
+ </div>
+ </Collapsible.Content>
+ </Collapsible>
+
+ <div class="flex justify-end gap-2 pt-1">
+ <Button
+ size="sm"
+ variant="gray"
+ disabled={
+ inputValue() === DEFAULT_PROJECT_NAME_TEMPLATE &&
+ inputValue() !== props.value
+ }
+ onClick={async () => {
+ await props.onChange(null);
+ const newTemplate = initialTemplate();
+ setInputValue(newTemplate);
+ if (inputRef) inputRef.value = newTemplate;
+ await updatePreview(newTemplate);
+ }}
+ >
+ Reset
+ </Button>
+
+ <Button
+ size="sm"
+ variant="dark"
+ disabled={isSaveDisabled()}
+ onClick={() => {
+ props.onChange(inputValue() ?? null);
+ updatePreview();
+ }}
+ >
+ Save
+ </Button>
+ </div>
+ </div>
+ </div>
+ </div>
+ );
+}
+
function ExcludedWindowsCard(props: {
excludedWindows: WindowExclusion[];
availableWindows: CaptureWindow[];
diff --git a/apps/desktop/src/utils/tauri.ts b/apps/desktop/src/utils/tauri.ts
index 0a0199912..6dd1c2dce 100644
--- a/apps/desktop/src/utils/tauri.ts
+++ b/apps/desktop/src/utils/tauri.ts
@@ -288,6 +288,12 @@ async focusWindow(windowId: WindowId) : Promise<null> {
},
async editorDeleteProject() : Promise<null> {
return await TAURI_INVOKE("editor_delete_project");
+},
+async formatProjectName(template: string | null, targetName: string, targetKind: string, recordingMode: RecordingMode, datetime: string | null) : Promise<string> {
+ return await TAURI_INVOKE("format_project_name", { template, targetName, targetKind, recordingMode, datetime });
+},
+async sanitizeFilename(filename: string) : Promise<string> {
+ return await TAURI_INVOKE("sanitize_filename", { filename });
}
}
@@ -401,7 +407,7 @@ export type ExportSettings = ({ format: "Mp4" } & Mp4ExportSettings) | ({ format
export type FileType = "recording" | "screenshot"
export type Flags = { captions: boolean }
export type FramesRendered = { renderedCount: number; totalFrames: number; type: "FramesRendered" }
-export type GeneralSettingsStore = { instanceId?: string; uploadIndividualFiles?: boolean; hideDockIcon?: boolean; autoCreateShareableLink?: boolean; enableNotifications?: boolean; disableAutoOpenLinks?: boolean; hasCompletedStartup?: boolean; theme?: AppTheme; commercialLicense?: CommercialLicense | null; lastVersion?: string | null; windowTransparency?: boolean; postStudioRecordingBehaviour?: PostStudioRecordingBehaviour; mainWindowRecordingStartBehaviour?: MainWindowRecordingStartBehaviour; custom_cursor_capture2?: boolean; serverUrl?: string; recordingCountdown?: number | null; enableNativeCameraPreview: boolean; autoZoomOnClicks?: boolean; enableNewRecordingFlow: boolean; postDeletionBehaviour?: PostDeletionBehaviour; excludedWindows?: WindowExclusion[]; deleteInstantRecordingsAfterUpload?: boolean; instantModeMaxResolution?: number }
+export type GeneralSettingsStore = { instanceId?: string; uploadIndividualFiles?: boolean; hideDockIcon?: boolean; autoCreateShareableLink?: boolean; enableNotifications?: boolean; disableAutoOpenLinks?: boolean; hasCompletedStartup?: boolean; theme?: AppTheme; commercialLicense?: CommercialLicense | null; lastVersion?: string | null; windowTransparency?: boolean; postStudioRecordingBehaviour?: PostStudioRecordingBehaviour; mainWindowRecordingStartBehaviour?: MainWindowRecordingStartBehaviour; custom_cursor_capture2?: boolean; serverUrl?: string; recordingCountdown?: number | null; enableNativeCameraPreview: boolean; autoZoomOnClicks?: boolean; enableNewRecordingFlow: boolean; postDeletionBehaviour?: PostDeletionBehaviour; excludedWindows?: WindowExclusion[]; deleteInstantRecordingsAfterUpload?: boolean; instantModeMaxResolution?: number; defaultProjectNameTemplate?: string | null }
export type GifExportSettings = { fps: number; resolution_base: XY<number>; quality: GifQuality | null }
export type GifQuality = {
/**
diff --git a/packages/ui-solid/src/auto-imports.d.ts b/packages/ui-solid/src/auto-imports.d.ts
index 57ce5370b..7d8000b7f 100644
--- a/packages/ui-solid/src/auto-imports.d.ts
+++ b/packages/ui-solid/src/auto-imports.d.ts
@@ -8,7 +8,7 @@ export {}
declare global {
const IconCapArrows: typeof import('~icons/cap/arrows.jsx')['default']
const IconCapAudioOn: typeof import('~icons/cap/audio-on.jsx')['default']
- const IconCapAuto: typeof import("~icons/cap/auto.jsx")["default"]
+ const IconCapAuto: typeof import('~icons/cap/auto.jsx')['default']
const IconCapBgBlur: typeof import('~icons/cap/bg-blur.jsx')['default']
const IconCapBlur: typeof import("~icons/cap/blur.jsx")["default"]
const IconCapCamera: typeof import('~icons/cap/camera.jsx')['default']
diff --git a/packages/ui-solid/tailwind.config.js b/packages/ui-solid/tailwind.config.js
index 77adf2658..009246705 100644
--- a/packages/ui-solid/tailwind.config.js
+++ b/packages/ui-solid/tailwind.config.js
@@ -89,12 +89,12 @@ module.exports = {
},
keyframes: {
"collapsible-down": {
- from: { height: 0 },
- to: { height: "var(--kb-collapsible-content-height)" },
+ from: { height: 0, filter: "blur(4px)" },
+ to: { height: "var(--kb-collapsible-content-height)", filter: "blur(0px)" },
},
"collapsible-up": {
- from: { height: "var(--kb-collapsible-content-height)" },
- to: { height: 0 },
+ from: { height: "var(--kb-collapsible-content-height)", filter: "blur(0px)" },
+ to: { height: 0, filter: "blur(4px)" },
},
},
animation: {