Open source Loom alternative. Beautiful, shareable screen recordings.
Rust appcapcossloommacnextjsnextjs15open-sourceossreactrecordrustscreen-capturescreen-recorderscreenshotsolidjstauritauri-apptypescriptvite
RecordingDeleted event + createTauriEventListener
Brendan Allanc2d4475db76c
diff --git a/apps/desktop/src-tauri/src/lib.rs b/apps/desktop/src-tauri/src/lib.rsindex 92d98c31f..3515323f4 100644--- a/apps/desktop/src-tauri/src/lib.rs+++ b/apps/desktop/src-tauri/src/lib.rs@@ -347,6 +347,12 @@ pub struct NewStudioRecordingAdded {path: PathBuf,}+#[derive(specta::Type, tauri_specta::Event, Debug, Clone)]+pub struct RecordingDeleted {+ #[allow(unused)]+ path: PathBuf,+}+#[derive(Deserialize, specta::Type, Serialize, tauri_specta::Event, Debug, Clone)]pub struct NewScreenshotAdded {path: PathBuf,@@ -1979,7 +1985,8 @@ pub async fn run(recording_logging_handle: LoggingHandle) {audio_meter::AudioInputLevelChange,UploadProgress,captions::DownloadProgress,- recording::RecordingEvent+ recording::RecordingEvent,+ RecordingDeleted]).error_handling(tauri_specta::ErrorHandlingMode::Throw).typ::<ProjectConfiguration>()diff --git a/apps/desktop/src-tauri/src/windows.rs b/apps/desktop/src-tauri/src/windows.rsindex e0f9e3824..e03fed367 100644--- a/apps/desktop/src-tauri/src/windows.rs+++ b/apps/desktop/src-tauri/src/windows.rs@@ -539,7 +539,7 @@ impl ShowCapWindow {}}- #[cfg(target_os = "windows")]+ #[cfg(windows)]{builder = builder.decorations(false);}diff --git a/apps/desktop/src/routes/(window-chrome)/(main).tsx b/apps/desktop/src/routes/(window-chrome)/(main).tsxindex 62c0e99e2..17a1ec429 100644--- a/apps/desktop/src/routes/(window-chrome)/(main).tsx+++ b/apps/desktop/src/routes/(window-chrome)/(main).tsx@@ -523,6 +523,7 @@ import {RecordingOptionsProvider,useRecordingOptions,} from "./OptionsContext";+import { createTauriEventListener } from "~/utils/createEventListener";let hasChecked = false;function createUpdateCheck() {@@ -797,22 +798,9 @@ function MicrophoneSelect(props: {});};- // Create a single event listener using onMount- onMount(() => {- const listener = (event: Event) => {- const dbs = (event as CustomEvent<number>).detail;- if (!props.value) setDbs();- else setDbs(dbs);- };-- events.audioInputLevelChange.listen((dbs) => {- if (!props.value) setDbs();- else setDbs(dbs.payload);- });-- return () => {- window.removeEventListener("audioLevelChange", listener);- };+ createTauriEventListener(events.audioInputLevelChange, (dbs) => {+ if (!props.value) setDbs();+ else setDbs(dbs);});// visual audio level from 0 -> 1diff --git a/apps/desktop/src/routes/(window-chrome)/settings/recordings.tsx b/apps/desktop/src/routes/(window-chrome)/settings/recordings.tsxindex 3c920d684..5153b0133 100644--- a/apps/desktop/src/routes/(window-chrome)/settings/recordings.tsx+++ b/apps/desktop/src/routes/(window-chrome)/settings/recordings.tsx@@ -16,11 +16,13 @@ import {createSignal,For,JSX,+ onCleanup,ParentProps,Show,} from "solid-js";import { trackEvent } from "~/utils/analytics";+import { createTauriEventListener } from "~/utils/createEventListener";import { commands, events, RecordingMetaWithType } from "~/utils/tauri";type Recording = {@@ -75,6 +77,8 @@ export default function Recordings() {);const recordings = createQuery(() => recordingsQuery);+ createTauriEventListener(events.recordingDeleted, () => recordings.refetch());+const filteredRecordings = createMemo(() => {if (!recordings.data) {return [];diff --git a/apps/desktop/src/routes/editor/Editor.tsx b/apps/desktop/src/routes/editor/Editor.tsxindex e3ec5cbd2..b8f735f5f 100644--- a/apps/desktop/src/routes/editor/Editor.tsx+++ b/apps/desktop/src/routes/editor/Editor.tsx@@ -35,6 +35,7 @@ import { Header } from "./Header";import { Player } from "./Player";import { Timeline } from "./Timeline";import { Dialog, DialogContent, EditorButton, Input, Subfield } from "./ui";+import { createTauriEventListener } from "~/utils/createEventListener";export function Editor() {return (@@ -75,12 +76,10 @@ export function Editor() {function Inner() {const { project, editorState, setEditorState } = useEditorContext();- onMount(() =>- events.editorStateChanged.listen((e) => {- renderFrame.clear();- setEditorState("playbackTime", e.payload.playhead_position / FPS);- })- );+ createTauriEventListener(events.editorStateChanged, (payload) => {+ renderFrame.clear();+ setEditorState("playbackTime", payload.playhead_position / FPS);+ });const renderFrame = throttle((time: number) => {if (!editorState.playing) {@@ -399,7 +398,14 @@ function Dialogs() {setCropOptions("showGrid", (s) => !s)}>- <IconCapPadding class={cx("w-4", cropOptions.showGrid ? "text-blue-9" : "text-gray-12")} />+ <IconCapPadding+ class={cx(+ "w-4",+ cropOptions.showGrid+ ? "text-blue-9"+ : "text-gray-12"+ )}+ /></Button></Tooltip></div>diff --git a/apps/desktop/src/routes/editor/Header.tsx b/apps/desktop/src/routes/editor/Header.tsxindex 520612b20..3ab835c87 100644--- a/apps/desktop/src/routes/editor/Header.tsx+++ b/apps/desktop/src/routes/editor/Header.tsx@@ -18,7 +18,7 @@ import { Button } from "@cap/ui-solid";import CaptionControlsWindows11 from "~/components/titlebar/controls/CaptionControlsWindows11";import Tooltip from "~/components/Tooltip";import { trackEvent } from "~/utils/analytics";-import { commands } from "~/utils/tauri";+import { commands, events } from "~/utils/tauri";import { initializeTitlebar } from "~/utils/titlebar-state";import { useEditorContext } from "./context";import PresetsDropdown from "./PresetsDropdown";@@ -80,6 +80,7 @@ export function Header() {await remove(editorInstance.path, {recursive: true,});+ events.recordingDeleted.emit({ path: editorInstance.path });await currentWindow.close();}}tooltipText="Delete recording"diff --git a/apps/desktop/src/routes/in-progress-recording.tsx b/apps/desktop/src/routes/in-progress-recording.tsxindex 0973571d4..1b4063b16 100644--- a/apps/desktop/src/routes/in-progress-recording.tsx+++ b/apps/desktop/src/routes/in-progress-recording.tsx@@ -20,6 +20,7 @@ import {} from "~/utils/queries";import { commands, events } from "~/utils/tauri";import { createMemo } from "solid-js";+import { createTauriEventListener } from "~/utils/createEventListener";type State =| { variant: "countdown"; from: number; current: number }@@ -58,8 +59,7 @@ export default function () {]>([]);- const unlisten = events.recordingEvent.listen((data) => {- const payload = data.payload;+ createTauriEventListener(events.recordingEvent, (payload) => {if (payload.variant === "Countdown") {setState((s) => {if (s.variant === "countdown") return { ...s, current: payload.value };@@ -71,7 +71,6 @@ export default function () {setStart(Date.now());}});- onCleanup(() => unlisten.then((f) => f()));createTimer(() => {@@ -288,11 +287,11 @@ function formatTime(secs: number) {function createAudioInputLevel() {const [level, setLevel] = createSignal(0);- events.audioInputLevelChange.listen((dbs) => {+ createTauriEventListener(events.audioInputLevelChange, (dbs) => {const DB_MIN = -60;const DB_MAX = 0;- const dbValue = dbs.payload ?? DB_MIN;+ const dbValue = dbs ?? DB_MIN;const normalizedLevel = Math.max(0,Math.min(1, (dbValue - DB_MIN) / (DB_MAX - DB_MIN))diff --git a/apps/desktop/src/routes/notifications.tsx b/apps/desktop/src/routes/notifications.tsxindex 5028091b8..8c3b28a43 100644--- a/apps/desktop/src/routes/notifications.tsx+++ b/apps/desktop/src/routes/notifications.tsx@@ -1,6 +1,7 @@import { events } from "~/utils/tauri";import toast, { Toaster } from "solid-toast";import { onCleanup, onMount } from "solid-js";+import { createTauriEventListener } from "~/utils/createEventListener";export default function Page() {let unlisten: (() => void) | undefined;@@ -31,35 +32,29 @@ export default function Page() {</svg>);- onMount(async () => {- unlisten = await events.newNotification.listen((e) => {- if (e.payload.is_error) {- toast.error(e.payload.body, {- style: {- background: "#FEE2E2",- color: "#991B1B",- border: "1px solid #F87171",- },- iconTheme: {- primary: "#991B1B",- secondary: "#FEE2E2",- },- });- } else {- toast.success(e.payload.body, {- icon: <SuccessIcon />,- style: {- background: "#FFFFFF",- color: "#000000",- border: "1px solid #FFFFFF",- },- });- }- });- });-- onCleanup(() => {- unlisten?.();+ createTauriEventListener(events.newNotification, (payload) => {+ if (payload.is_error) {+ toast.error(payload.body, {+ style: {+ background: "#FEE2E2",+ color: "#991B1B",+ border: "1px solid #F87171",+ },+ iconTheme: {+ primary: "#991B1B",+ secondary: "#FEE2E2",+ },+ });+ } else {+ toast.success(payload.body, {+ icon: <SuccessIcon />,+ style: {+ background: "#FFFFFF",+ color: "#000000",+ border: "1px solid #FFFFFF",+ },+ });+ }});return (diff --git a/apps/desktop/src/routes/recordings-overlay.tsx b/apps/desktop/src/routes/recordings-overlay.tsxindex 2c342df4d..e752a0461 100644--- a/apps/desktop/src/routes/recordings-overlay.tsx+++ b/apps/desktop/src/routes/recordings-overlay.tsx@@ -29,6 +29,7 @@ import { authStore } from "~/store";import { exportVideo } from "~/utils/export";import { commands, events, FramesRendered, UploadResult } from "~/utils/tauri";import { FPS, OUTPUT_SIZE } from "./editor/context";+import { createTauriEventListener } from "~/utils/createEventListener";type MediaEntry = {path: string;@@ -78,12 +79,12 @@ export default function () {}, 3000);};- events.newStudioRecordingAdded.listen((event) => {- addMediaEntry(event.payload.path, "recording");+ createTauriEventListener(events.newStudioRecordingAdded, (payload) => {+ addMediaEntry(payload.path, "recording");});- events.newScreenshotAdded.listen((event) => {- addMediaEntry(event.payload.path, "screenshot");+ createTauriEventListener(events.newScreenshotAdded, (payload) => {+ addMediaEntry(payload.path, "screenshot");});const allMedia = createMemo(() => [...recordings, ...screenshots]);diff --git a/apps/desktop/src/utils/createEventListener.ts b/apps/desktop/src/utils/createEventListener.tsnew file mode 100644index 000000000..120337be6--- /dev/null+++ b/apps/desktop/src/utils/createEventListener.ts@@ -0,0 +1,64 @@+import { onCleanup } from "solid-js";+import { events } from "./tauri";++type EventListener<T> = {+ listen: (cb: (event: { payload: T }) => void) => Promise<() => void>;+};++type EventKey = keyof typeof events;++/**+ * A SolidJS utility function that creates an event listener with automatic cleanup on unmount.+ *+ * @param eventListener - An event listener object from the events proxy (e.g., events.recordingDeleted)+ * @param callback - The callback function to execute when the event is received+ *+ * @example+ * ```tsx+ * import { createEventListener } from "~/utils/createEventListener";+ * import { events } from "~/utils/tauri";+ *+ * function MyComponent() {+ * createEventListener(events.recordingDeleted, () => {+ * console.log("Recording was deleted!");+ * });+ *+ * return <div>My Component</div>;+ * }+ * ```+ */+export function createTauriEventListener<T>(+ eventListener: EventListener<T>,+ callback: (payload: T) => void+): void {+ const unlisten = eventListener.listen((event) => {+ callback(event.payload);+ });++ onCleanup(() => {+ unlisten.then((cleanup) => cleanup());+ });+}++/**+ * Alternative version that accepts the event key directly for more flexibility.+ *+ * @param eventKey - The key of the event from the events object (e.g., "recordingDeleted")+ * @param callback - The callback function to execute when the event is received+ *+ * @example+ * ```tsx+ * createEventListenerByKey("recordingDeleted", (payload) => {+ * console.log("Recording deleted:", payload);+ * });+ * ```+ */+export function createEventListenerByKey<K extends EventKey>(+ eventKey: K,+ callback: (+ payload: (typeof events)[K] extends EventListener<infer T> ? T : never+ ) => void+): void {+ const eventListener = events[eventKey] as EventListener<any>;+ createTauriEventListener(eventListener, callback);+}diff --git a/apps/desktop/src/utils/events.ts b/apps/desktop/src/utils/events.tsindex 8f1a550e3..90b050432 100644--- a/apps/desktop/src/utils/events.ts+++ b/apps/desktop/src/utils/events.ts@@ -2,20 +2,6 @@ import { onCleanup, onMount, type ResourceReturn } from "solid-js";import { events } from "./tauri";import { CreateQueryResult } from "@tanstack/solid-query";-export function makeInvalidated<R>(- resource: ResourceReturn<R>,- event: keyof typeof events-) {- const [_, { refetch }] = resource;-- onMount(() => {- const cleanup = events[event].listen(() => refetch());- onCleanup(() => cleanup.then((c) => c()));- });-- return resource;-}-export function createQueryInvalidate<T extends CreateQueryResult>(query: T,event: keyof typeof eventsdiff --git a/apps/desktop/src/utils/tauri.ts b/apps/desktop/src/utils/tauri.tsindex cc3289239..5e292684d 100644--- a/apps/desktop/src/utils/tauri.ts+++ b/apps/desktop/src/utils/tauri.ts@@ -265,6 +265,7 @@ editorStateChanged: EditorStateChanged,newNotification: NewNotification,newScreenshotAdded: NewScreenshotAdded,newStudioRecordingAdded: NewStudioRecordingAdded,+recordingDeleted: RecordingDeleted,recordingEvent: RecordingEvent,recordingOptionsChanged: RecordingOptionsChanged,recordingStarted: RecordingStarted,@@ -283,6 +284,7 @@ editorStateChanged: "editor-state-changed",newNotification: "new-notification",newScreenshotAdded: "new-screenshot-added",newStudioRecordingAdded: "new-studio-recording-added",+recordingDeleted: "recording-deleted",recordingEvent: "recording-event",recordingOptionsChanged: "recording-options-changed",recordingStarted: "recording-started",@@ -385,6 +387,7 @@ export type Preset = { name: string; config: ProjectConfiguration }export type PresetsStore = { presets: Preset[]; default: number | null }export type ProjectConfiguration = { aspectRatio: AspectRatio | null; background: BackgroundConfiguration; camera: Camera; audio: AudioConfiguration; cursor: CursorConfiguration; hotkeys: HotkeysConfiguration; timeline?: TimelineConfiguration | null; captions?: CaptionsData | null }export type ProjectRecordingsMeta = { segments: SegmentRecordings[] }+export type RecordingDeleted = { path: string }export type RecordingEvent = { variant: "Countdown"; value: number } | { variant: "Started" } | { variant: "Stopped" } | { variant: "Failed"; error: string }export type RecordingMeta = (StudioRecordingMeta | InstantRecordingMeta) & { platform?: Platform | null; pretty_name: string; sharing?: SharingMeta | null }export type RecordingMetaWithType = ((StudioRecordingMeta | InstantRecordingMeta) & { platform?: Platform | null; pretty_name: string; sharing?: SharingMeta | null }) & { type: RecordingType }diff --git a/crates/rendering/src/layers/camera.rs b/crates/rendering/src/layers/camera.rsindex 9fa14f514..e743113cc 100644--- a/crates/rendering/src/layers/camera.rs+++ b/crates/rendering/src/layers/camera.rs@@ -11,6 +11,7 @@ pub struct CameraLayer {uniforms_buffer: wgpu::Buffer,bind_group: Option<wgpu::BindGroup>,pipeline: CompositeVideoFramePipeline,+ hidden: bool,}impl CameraLayer {@@ -36,6 +37,7 @@ impl CameraLayer {uniforms_buffer,bind_group,pipeline,+ hidden: false,}}@@ -43,10 +45,16 @@ impl CameraLayer {&mut self,device: &wgpu::Device,queue: &wgpu::Queue,- uniforms: CompositeVideoFrameUniforms,+ uniforms: Option<CompositeVideoFrameUniforms>,frame_size: XY<u32>,camera_frame: &DecodedFrame,) {+ self.hidden = uniforms.is_none();++ let Some(uniforms) = uniforms else {+ return;+ };+if self.frame_texture.width() != frame_size.x || self.frame_texture.height() != frame_size.y{self.frame_texture = CompositeVideoFramePipeline::create_frame_texture(@@ -87,7 +95,9 @@ impl CameraLayer {}pub fn render(&self, pass: &mut wgpu::RenderPass<'_>) {- if let Some(bind_group) = &self.bind_group {+ if !self.hidden+ && let Some(bind_group) = &self.bind_group+ {pass.set_pipeline(&self.pipeline.render_pipeline);pass.set_bind_group(0, bind_group, &[]);pass.draw(0..4, 0..1);diff --git a/crates/rendering/src/lib.rs b/crates/rendering/src/lib.rsindex aa7ac878b..253b4d1fb 100644--- a/crates/rendering/src/lib.rs+++ b/crates/rendering/src/lib.rs@@ -869,15 +869,13 @@ impl RendererLayers {constants,);- if let (Some(camera_size), Some(camera_frame), Some(uniforms)) = (- constants.options.camera_size,- &segment_frames.camera_frame,- &uniforms.camera,- ) {+ if let (Some(camera_size), Some(camera_frame)) =+ (constants.options.camera_size, &segment_frames.camera_frame)+ {self.camera.prepare(&constants.device,&constants.queue,- *uniforms,+ uniforms.camera,camera_size,camera_frame,);diff --git a/packages/ui-solid/src/auto-imports.d.ts b/packages/ui-solid/src/auto-imports.d.tsindex 619c7a939..a247206bb 100644--- a/packages/ui-solid/src/auto-imports.d.ts+++ b/packages/ui-solid/src/auto-imports.d.ts@@ -47,18 +47,18 @@ declare global {const IconCapMoreVertical: typeof import('~icons/cap/more-vertical.jsx')['default']const IconCapMoveLeft: typeof import("~icons/cap/move-left.jsx")["default"]const IconCapMoveRight: typeof import("~icons/cap/move-right.jsx")["default"]- const IconCapNext: typeof import("~icons/cap/next.jsx")["default"]- const IconCapPadding: typeof import("~icons/cap/padding.jsx")["default"]- const IconCapPause: typeof import("~icons/cap/pause.jsx")["default"]+ const IconCapNext: typeof import('~icons/cap/next.jsx')['default']+ const IconCapPadding: typeof import('~icons/cap/padding.jsx')['default']+ const IconCapPause: typeof import('~icons/cap/pause.jsx')['default']const IconCapPauseCircle: typeof import('~icons/cap/pause-circle.jsx')['default']- const IconCapPlay: typeof import("~icons/cap/play.jsx")["default"]+ const IconCapPlay: typeof import('~icons/cap/play.jsx')['default']const IconCapPlayCircle: typeof import('~icons/cap/play-circle.jsx')['default']- const IconCapPresets: typeof import("~icons/cap/presets.jsx")["default"]- const IconCapPrev: typeof import("~icons/cap/prev.jsx")["default"]- const IconCapRedo: typeof import("~icons/cap/redo.jsx")["default"]+ const IconCapPresets: typeof import('~icons/cap/presets.jsx')['default']+ const IconCapPrev: typeof import('~icons/cap/prev.jsx')['default']+ const IconCapRedo: typeof import('~icons/cap/redo.jsx')['default']const IconCapRefresh: typeof import("~icons/cap/refresh.jsx")["default"]const IconCapRestart: typeof import('~icons/cap/restart.jsx')['default']- const IconCapScissors: typeof import("~icons/cap/scissors.jsx")["default"]+ const IconCapScissors: typeof import('~icons/cap/scissors.jsx')['default']const IconCapSettings: typeof import('~icons/cap/settings.jsx')['default']const IconCapShadow: typeof import('~icons/cap/shadow.jsx')['default']const IconCapSize: typeof import("~icons/cap/size.jsx")["default"]@@ -66,7 +66,7 @@ declare global {const IconCapStop: typeof import("~icons/cap/stop.jsx")["default"]const IconCapStopCircle: typeof import('~icons/cap/stop-circle.jsx')['default']const IconCapTrash: typeof import('~icons/cap/trash.jsx')['default']- const IconCapUndo: typeof import("~icons/cap/undo.jsx")["default"]+ const IconCapUndo: typeof import('~icons/cap/undo.jsx')['default']const IconCapUpload: typeof import("~icons/cap/upload.jsx")["default"]const IconCapWindow: typeof import("~icons/cap/window.jsx")["default"]const IconCapX: typeof import("~icons/cap/x.jsx")["default"]@@ -93,7 +93,7 @@ declare global {const IconLucideMessageSquare: typeof import("~icons/lucide/message-square.jsx")["default"]const IconLucideMessageSquarePlus: typeof import('~icons/lucide/message-square-plus.jsx')['default']const IconLucideMicOff: typeof import('~icons/lucide/mic-off.jsx')['default']- const IconLucideMonitor: typeof import("~icons/lucide/monitor.jsx")["default"]+ const IconLucideMonitor: typeof import('~icons/lucide/monitor.jsx')['default']const IconLucideRabbit: typeof import("~icons/lucide/rabbit.jsx")["default"]const IconLucideRectangle: typeof import("~icons/lucide/rectangle.jsx")["default"]const IconLucideRectangleHorizontal: typeof import('~icons/lucide/rectangle-horizontal.jsx')['default']