Open source Loom alternative. Beautiful, shareable screen recordings.
Rust appcapcossloommacnextjsnextjs15open-sourceossreactrecordrustscreen-capturescreen-recorderscreenshotsolidjstauritauri-apptypescriptvite
Work in progress for screen capture
Richie McIlroy469cd3767cbe
diff --git a/apps/desktop/src/components/FloatingOptions.tsx b/apps/desktop/src/components/FloatingOptions.tsxindex dd5d8c602..c16f5cf9d 100644--- a/apps/desktop/src/components/FloatingOptions.tsx+++ b/apps/desktop/src/components/FloatingOptions.tsx@@ -1,19 +1,29 @@import { useEffect, useState } from "react";-import { ReactMediaRecorder } from "@/utils/recording/client";+import {+ ReactMediaRecorder,+ useDisplayRecorder,+} from "@/utils/recording/client";import { useMediaDevices } from "@/utils/recording/MediaDeviceContext";import { Video } from "@/components/icons/Video";import { Microphone } from "@/components/icons/Microphone";import { Screen } from "@/components/icons/Screen";+import { Window } from "@/components/icons/Window";import { ActionButton } from "@/components/recording/ActionButton";import { Button } from "@/components/Button";import { Logo } from "@/components/icons/Logo";-// import { Settings } from "@/components/icons/Settings";import { emit } from "@tauri-apps/api/event";import { showMenu } from "tauri-plugin-context-menu";+type DisplayType = {+ label: string;+ track: MediaStreamTrack;+ type: string;+} | null;+export const FloatingOptions = () => {const [foundDevices, setFoundDevices] = useState<MediaDeviceInfo[]>([]);const { selectedVideoDevice, selectedAudioDevice } = useMediaDevices();+ const [selectedDisplay, setSelectedDisplay] = useState<DisplayType>(null);useEffect(() => {const fetchAndEmitDevices = async () => {@@ -70,41 +80,75 @@ export const FloatingOptions = () => {fetchAndEmitDevices();}, []);+ // Helper function to handle "Screen" or "Window" selection+ const selectScreenOrWindow = async (sourceType: string) => {+ try {+ // Use the getDisplayMedia API for screen capture options+ const stream = (await navigator.mediaDevices.getDisplayMedia({+ video: true,+ audio: false,+ })) as MediaStream;++ if (stream.getVideoTracks().length === 0) {+ return;+ }+ // Now you should have access to the id, label and other properties of the chosen screen or window+ const track = stream.getVideoTracks()[0];+ const label = track ? track.label : "No Label";++ // After selection, save it in the state+ setSelectedDisplay({ label, track, type: sourceType });++ // stream.getTracks().forEach((t) => t.stop()); // Stop the stream if you don't need it running+ } catch (error) {+ console.error("Failed to select screen or window:", error);+ }+ };+const handleContextClick = async (option: string) => {- const filteredDevices = foundDevices- .filter((device) =>- option === "video"- ? device.kind === "videoinput"- : device.kind === "audioinput"- )- .map((device) => ({- label: device.label,- disabled:+ if (option === "screen" || option === "window") {+ // Call the selectScreenOrWindow function when "Screen" or "Window" is clicked+ selectScreenOrWindow(option);+ } else {+ // The existing logic to handle selection of video or audio devices+ const filteredDevices = foundDevices+ .filter((device) =>option === "video"- ? device.deviceId === selectedVideoDevice?.deviceId- : device.deviceId === selectedAudioDevice?.deviceId,- event: async () => {- try {- await emit("change-device", { type: option, device });- } catch (error) {- console.error("Failed to emit change-device event:", error);- }- },- }));-- //TODO: Some default item maybe. OR Show an error when filteredDevices length === 0- showMenu({- items: [...filteredDevices],- ...(filteredDevices.length === 0 && {- items: [- {- label: "Nothing found.",+ ? device.kind === "videoinput"+ : device.kind === "audioinput"+ )+ .map((device) => ({+ label: device.label,+ disabled:+ option === "video"+ ? device.deviceId === selectedVideoDevice?.deviceId+ : device.deviceId === selectedAudioDevice?.deviceId,+ event: async () => {+ try {+ await emit("change-device", { type: option, device });+ } catch (error) {+ console.error("Failed to emit change-device event:", error);+ }},- ],- }),- });+ }));++ // Show a context menu or dialog with the filtered devices+ showMenu({+ items: [...filteredDevices],+ ...(filteredDevices.length === 0 && {+ items: [+ {+ label: "Nothing found.",+ },+ ],+ }),+ });+ }};+ console.log("selectedisplayinnner: ");+ console.log(selectedDisplay);+return (<ReactMediaRecordervideo={@@ -118,6 +162,27 @@ export const FloatingOptions = () => {: undefined}render={({ status, startRecording, stopRecording }) => {+ const {+ startRecording: startDisplayRecording,+ stopRecording: stopDisplayRecording,+ screenBlobUrl,+ } = useDisplayRecorder(+ selectedDisplay?.track+ ? new MediaStream([selectedDisplay.track])+ : null+ );++ const handleStartAllRecordings = () => {+ startRecording(); // Starts webcam recording+ startDisplayRecording(); // Starts display recording+ };++ // Similarly, for stopping all recordings+ const handleStopAllRecordings = () => {+ stopRecording(); // Stops webcam recording+ stopDisplayRecording(); // Stops display recording+ };+return (<divdata-tauri-drag-region@@ -139,25 +204,43 @@ export const FloatingOptions = () => {</div> */}</div><div className="space-y-4 w-full">- <div>- <label className="text-sm font-medium">Screen Settings</label>- <ActionButton- handler={() => handleContextClick("screen")}- icon={<Screen className="w-5 h-5" />}- label="Screen"- />- </div><div><label className="text-sm font-medium">- Recording Settings+ Display Settings</label>- <div className="space-y-2">++ <div className="flex items-center space-x-1">+ <ActionButton+ handler={() => handleContextClick("screen")}+ icon={<Screen className="w-5 h-5" />}+ label={+ selectedDisplay?.type === "screen"+ ? selectedDisplay.label+ : "Screen"+ }+ /><ActionButton+ handler={() => handleContextClick("window")}+ icon={<Window className="w-5 h-5" />}+ label={+ selectedDisplay?.type === "window"+ ? selectedDisplay.label+ : "Window"+ }+ />+ </div>+ </div>+ <div>+ <label className="text-sm font-medium">Webcam Settings</label>+ <div className="space-y-1">+ <ActionButton+ width="full"handler={() => handleContextClick("video")}icon={<Video className="w-5 h-5" />}label={selectedVideoDevice?.label || "Video"}/><ActionButton+ width="full"handler={() => handleContextClick("audio")}icon={<Microphone className="w-5 h-5" />}label={selectedAudioDevice?.label || "Mic"}@@ -167,16 +250,19 @@ export const FloatingOptions = () => {{status === "recording" ? (<Buttonvariant="primary"- handler={stopRecording}+ handler={handleStopAllRecordings}label="Stop Recording"/>) : (<Buttonvariant="primary"- handler={startRecording}+ handler={handleStartAllRecordings}label="Start Recording"/>)}+ {screenBlobUrl !== null && (+ <video src={screenBlobUrl} controls />+ )}</div></div></div>diff --git a/apps/desktop/src/components/icons/Window.tsx b/apps/desktop/src/components/icons/Window.tsxnew file mode 100644index 000000000..1260ceeb8--- /dev/null+++ b/apps/desktop/src/components/icons/Window.tsx@@ -0,0 +1,17 @@+export const Window = ({ className }: { className: string }) => {+ return (+ <svg+ xmlns="http://www.w3.org/2000/svg"+ className={className}+ fill="none"+ stroke="currentColor"+ strokeLinecap="round"+ strokeLinejoin="round"+ strokeWidth="2"+ viewBox="0 0 24 24"+ >+ <rect width="20" height="16" x="2" y="4" rx="2"></rect>+ <path d="M10 4v4M2 8h20M6 4v4"></path>+ </svg>+ );+};diff --git a/apps/desktop/src/components/recording/ActionButton.tsx b/apps/desktop/src/components/recording/ActionButton.tsxindex e742fb9ee..fb1aee570 100644--- a/apps/desktop/src/components/recording/ActionButton.tsx+++ b/apps/desktop/src/components/recording/ActionButton.tsx@@ -4,19 +4,27 @@ export const ActionButton = ({handler,icon,label,+ width,}: {handler: () => void;icon?: ReactNode;label?: string;+ width?: string;}) => {return (- <div>+ <div className="flex-grow"><buttononClick={handler}- className="w-full h-[50px] py-2 px-4 bg-gray-100 hover:bg-white text-[15px] border-2 border-gray-300 flex items-center justify-start rounded-[15px] transition-all "+ className="w-full h-[50px] py-2 px-4 bg-gray-100 hover:bg-white text-[15px] border-2 border-gray-300 flex items-center justify-start rounded-[15px] flex-grow transition-all"><span>{icon}</span>- {label && <span className="ml-2">{label}</span>}+ {label && (+ <span+ className={`ml-2 truncate ${width !== "full" && "max-w-[100px]"}`}+ >+ {label}+ </span>+ )}</button></div>);diff --git a/apps/desktop/src/styles.css b/apps/desktop/src/styles.cssindex 49bebdd6e..40f9a8254 100644--- a/apps/desktop/src/styles.css+++ b/apps/desktop/src/styles.css@@ -4,8 +4,8 @@@font-face {font-family: "Geist";- src: url("/public/fonts/Geist-SemiBold.woff2") format("woff2"),- url("/public/fonts/Geist-SemiBold.woff") format("woff");+ src: url("/fonts/Geist-SemiBold.woff2") format("woff2"),+ url("/fonts/Geist-SemiBold.woff") format("woff");font-weight: 500;font-style: normal;font-display: swap;@@ -13,8 +13,8 @@@font-face {font-family: "Geist";- src: url("/public/fonts/Geist-Regular.woff2") format("woff2"),- url("/public/fonts/Geist-Regular.woff") format("woff");+ src: url("/fonts/Geist-Regular.woff2") format("woff2"),+ url("/fonts/Geist-Regular.woff") format("woff");font-weight: 400;font-style: normal;font-display: swap;@@ -22,8 +22,8 @@@font-face {font-family: "Geist";- src: url("/public/fonts/Geist-Light.woff2") format("woff2"),- url("/public/fonts/Geist-Light.woff") format("woff");+ src: url("/fonts/Geist-Light.woff2") format("woff2"),+ url("/fonts/Geist-Light.woff") format("woff");font-weight: 300;font-style: normal;font-display: swap;diff --git a/apps/desktop/src/hooks/useDidMount.ts b/apps/desktop/src/utils/hooks/useDidMount.tssimilarity index 86%rename from apps/desktop/src/hooks/useDidMount.tsrename to apps/desktop/src/utils/hooks/useDidMount.tsindex 0170be79c..54d8a8a4f 100644--- a/apps/desktop/src/hooks/useDidMount.ts+++ b/apps/desktop/src/utils/hooks/useDidMount.ts@@ -14,6 +14,5 @@ export const useDidMountEffect = (return () => {didMount.current = true;};- // eslint-disable-next-line react-hooks/exhaustive-deps}, deps);};diff --git a/apps/desktop/src/utils/recording/client.ts b/apps/desktop/src/utils/recording/client.tsindex e10e1225b..44a692d24 100644--- a/apps/desktop/src/utils/recording/client.ts+++ b/apps/desktop/src/utils/recording/client.ts@@ -5,8 +5,8 @@ import {} from "extendable-media-recorder";import { ReactElement, useCallback, useEffect, useRef, useState } from "react";import { connect } from "extendable-media-recorder-wav-encoder";-import { useMediaDevices } from "./MediaDeviceContext";-import { useDidMountEffect } from "@/hooks/useDidMount";+import { useMediaDevices } from "@/utils/recording/MediaDeviceContext";+import { useDidMountEffect } from "@/utils/hooks/useDidMount";export type ReactMediaRecorderRenderProps = {error: string;@@ -340,5 +340,112 @@ export function useReactMediaRecorder({};}+export const useDisplayRecorder = (+ screenStream: MediaStream | null,+ onStop?: (blobUrl: string, blob: Blob) => void+) => {+ const mediaRecorder = useRef<MediaRecorder | null>(null);+ const mediaChunks = useRef<Blob[]>([]);+ const [status, setStatus] = useState<"idle" | "recording" | "stopped">(+ "idle"+ );+ const [screenBlobUrl, setScreenBlobUrl] = useState<string | undefined>(+ undefined+ );+ const [error, setError] = useState<string>("");+ const mime = MediaRecorder.isTypeSupported("video/webm; codecs=vp9")+ ? "video/webm; codecs=vp9"+ : "video/mp4";++ const startRecording = useCallback(() => {+ if (status !== "idle" || !screenStream) return;++ try {+ mediaRecorder.current = new MediaRecorder(screenStream, {+ mimeType: mime,+ });++ mediaRecorder.current.ondataavailable = (event) => {+ console.log("new event: ", event);+ if (event.data.size > 0) {+ mediaChunks.current.push(event.data);+ }+ };++ mediaRecorder.current.onstart = () => {+ console.log("recording started");+ };++ mediaRecorder.current.onstop = () => {+ const blob = new Blob(mediaChunks.current, { type: mime });+ const url = URL.createObjectURL(blob);+ setScreenBlobUrl(url);+ setStatus("stopped");+ if (onStop) onStop(url, blob);+ };++ mediaRecorder.current.onerror = (event: any) => {+ console.log("recording error2: ", event);+ setError("Error during recording: " + event.error.name);+ setStatus("idle");+ };++ mediaRecorder.current.start();+ setStatus("recording");+ } catch (err) {+ console.log("recording error: ", err);+ setError("Failed to start recording: " + (err as Error).message);+ setStatus("idle");+ }+ }, [screenStream, status, onStop]);++ const stopRecording = useCallback(() => {+ if (status === "recording" && mediaRecorder.current) {+ mediaRecorder.current.stop();+ }+ }, [status]);++ const clearBlobUrl = useCallback(() => {+ if (screenBlobUrl) {+ URL.revokeObjectURL(screenBlobUrl);+ setScreenBlobUrl(undefined);+ }+ }, [screenBlobUrl]);++ // Make sure to clean up media resources when the component using this hook gets unmounted+ useEffect(() => {+ return () => {+ clearBlobUrl();+ if (mediaRecorder.current && mediaRecorder.current.state !== "inactive") {+ mediaRecorder.current.stop();+ }+ if (+ !mediaRecorder.current ||+ mediaRecorder.current.state === "inactive"+ ) {+ screenStream?.getTracks().forEach((track) => track.stop());+ }+ mediaChunks.current = [];+ mediaRecorder.current = null;+ };+ }, [clearBlobUrl, screenStream]);++ console.log("status", status);+ console.log("error", error);+ console.log("screenBlobUrl", screenBlobUrl);+ console.log("mediaChunks", mediaChunks.current);+ console.log(screenStream?.getTracks());+ console.log(mediaRecorder.current);++ return {+ startRecording,+ stopRecording,+ clearBlobUrl,+ screenBlobUrl,+ status,+ error,+ };+};+export const ReactMediaRecorder = (props: ReactMediaRecorderProps) =>props.render(useReactMediaRecorder(props));