Skip to content

armgit / Cap

Public Imported from GitHub
0

Open source Loom alternative. Beautiful, shareable screen recordings.

feat: Improved webcam loading state

Richie McIlroy6de08e60d6a7
diff --git a/apps/desktop/src/routes/(window-chrome)/index.tsx b/apps/desktop/src/routes/(window-chrome)/index.tsx
index 4da415dbc..5d525cdfe 100644
--- a/apps/desktop/src/routes/(window-chrome)/index.tsx
+++ b/apps/desktop/src/routes/(window-chrome)/index.tsx
@@ -11,6 +11,7 @@ import {
createEffect,
createResource,
createSignal,
+ onCleanup,
onMount,
} from "solid-js";
import { createStore } from "solid-js/store";
@@ -33,6 +34,7 @@ import {
topLeftAnimateClasses,
topRightAnimateClasses,
} from "../editor/ui";
+import { stopMediaStream } from "~/utils/media";
const getAuth = cache(async () => {
const value = await authStore.get();
@@ -47,13 +49,16 @@ export const route = {
export default function () {
const options = createOptionsQuery();
const windows = createWindowsQuery();
- const audioDevices = createAudioDevicesQuery();
- const videoDevices = createVideoDevicesQuery();
+ const videoDevicesQuery = createVideoDevicesQuery();
+ const audioDevicesQuery = createAudioDevicesQuery();
const currentRecording = createCurrentRecordingQuery();
const [windowSelectOpen, setWindowSelectOpen] = createSignal(false);
const permissions = createPermissionsQuery();
+ const [cameraSelectOpen, setCameraSelectOpen] = createSignal(false);
+ const [microphoneSelectOpen, setMicrophoneSelectOpen] = createSignal(false);
+
events.showCapturesPanel.listen(() => {
commands.showPreviousRecordingsWindow();
});
@@ -68,8 +73,12 @@ export default function () {
const toggleRecording = createMutation(() => ({
mutationFn: async () => {
- if (!isRecording()) await commands.startRecording();
- else await commands.stopRecording();
+ if (!isRecording()) {
+ await commands.startRecording();
+ } else {
+ await commands.stopRecording();
+ await stopMediaStream("both");
+ }
},
}));
@@ -141,7 +150,7 @@ export default function () {
};
const camera = () =>
- videoDevices?.data.find((d) => d.label === options.data?.cameraLabel);
+ videoDevicesQuery?.data.find((d) => d.label === options.data?.cameraLabel);
const selectedWindow = () => {
const d = options.data?.captureTarget;
@@ -150,7 +159,9 @@ export default function () {
};
const audioDevice = () =>
- audioDevices.data?.find((d) => d.name === options.data?.audioInputName);
+ audioDevicesQuery?.data?.find(
+ (d) => d.name === options.data?.audioInputName
+ ) ?? { name: "No Audio", deviceId: "" };
const requestPermission = async (type: "camera" | "microphone") => {
try {
@@ -168,6 +179,53 @@ export default function () {
}
};
+ const handleCameraChange = async (item: CameraOption | null) => {
+ if (!item && permissions?.data?.camera !== "granted") {
+ return requestPermission("camera");
+ }
+
+ if (!options.data) return;
+
+ // Stop the current camera stream before changing
+ await stopMediaStream("video");
+
+ if (!item || item.label === "No Camera") {
+ await commands.setRecordingOptions({
+ ...options.data,
+ cameraLabel: null,
+ });
+ } else {
+ await commands.setRecordingOptions({
+ ...options.data,
+ cameraLabel: item.label,
+ });
+ }
+ };
+
+ const handleMicrophoneChange = async (
+ item: { name: string; deviceId: string } | null
+ ) => {
+ if (!item && permissions?.data?.microphone !== "granted") {
+ return requestPermission("microphone");
+ }
+
+ if (!item || !options.data) return;
+
+ // Stop the current audio stream before changing
+ if (options.data.audioInputName) {
+ await stopMediaStream("audio");
+ }
+
+ commands.setRecordingOptions({
+ ...options.data,
+ audioInputName: item.name !== "No Audio" ? item.name : null,
+ });
+ };
+
+ onCleanup(() => {
+ stopMediaStream("both");
+ });
+
return (
<div class="flex justify-center flex-col p-[1rem] gap-[0.75rem] text-[0.875rem] font-[400] bg-gray-50 h-full">
<div class="absolute top-3 right-3">
@@ -214,13 +272,13 @@ export default function () {
placeholder="Window"
gutter={8}
open={windowSelectOpen()}
- onOpenChange={(o) => {
+ onOpenChange={(o: boolean) => {
// prevents tab onChange from interfering with dropdown trigger click
if (o === false && options.data?.captureTarget.type === "screen")
return;
setWindowSelectOpen(o);
}}
- itemComponent={(props) => (
+ itemComponent={(props: { item: any }) => (
<MenuItem<typeof KSelect.Item> as={KSelect.Item} item={props.item}>
<KSelect.ItemLabel class="flex-1">
{props.item.rawValue?.name}
@@ -228,7 +286,7 @@ export default function () {
</MenuItem>
)}
value={selectedWindow() ?? null}
- onChange={(d) => {
+ onChange={(d: CaptureWindow | null) => {
if (!d || !options.data) return;
commands.setRecordingOptions({
...options.data,
@@ -304,32 +362,14 @@ export default function () {
<KSelect<CameraOption>
options={[
{ deviceId: "", label: "No Camera" },
- ...(videoDevices.data ?? []),
+ ...(videoDevicesQuery.data ?? []),
]}
optionValue="deviceId"
optionTextValue="label"
placeholder="No Camera"
value={camera() ?? { deviceId: "", label: "No Camera" }}
disabled={isRecording()}
- onChange={(device: MediaDeviceInfo | null) => {
- if (!device && permissions?.data?.camera !== "granted") {
- return requestPermission("camera");
- }
- if (options.data?.captureTarget) {
- if (device) {
- commands.setRecordingOptions({
- ...options.data,
- cameraLabel: device?.deviceId ? device?.label : null,
- });
- } else {
- commands.setRecordingOptions({
- cameraLabel: null,
- captureTarget: options.data.captureTarget,
- audioInputName: options.data.audioInputName,
- });
- }
- }
- }}
+ onChange={handleCameraChange}
itemComponent={(props) => (
<MenuItem<typeof KSelect.Item> as={KSelect.Item} item={props.item}>
<KSelect.ItemLabel class="flex-1">
@@ -337,56 +377,58 @@ export default function () {
</KSelect.ItemLabel>
</MenuItem>
)}
+ open={cameraSelectOpen()}
+ onOpenChange={async (isOpen: boolean) => {
+ if (isOpen) {
+ if (camera()) {
+ setCameraSelectOpen(true);
+ } else {
+ setCameraSelectOpen(false);
+ await videoDevicesQuery.refetch();
+ setCameraSelectOpen(true);
+ }
+ } else {
+ setCameraSelectOpen(false);
+ }
+ }}
>
<KSelect.Trigger
- class="h-[2rem] px-[0.375rem] flex flex-row gap-[0.375rem] border rounded-lg border-gray-200 w-full items-center disabled:text-gray-400 transition-colors KSelect"
- onClick={() => {
+ 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"
+ onClick={(e) => {
if (permissions?.data?.camera !== "granted") {
requestPermission("camera");
}
}}
>
<IconCapCamera class="text-gray-400 size-[1.25rem]" />
- <KSelect.Value<
- CameraOption | undefined
- > class="flex-1 text-left truncate">
- {(state) => (
- <span
- onPointerDown={(e) => {
- e.stopPropagation();
- }}
- >
- {state.selectedOption()?.label}
- </span>
- )}
+ <KSelect.Value<{
+ label: string;
+ }> class="flex-1 text-left truncate">
+ {(state) => <span>{state.selectedOption().label}</span>}
</KSelect.Value>
<button
type="button"
class={cx(
"px-[0.375rem] rounded-full text-[0.75rem]",
- camera()?.deviceId
+ options.data?.cameraLabel
? "bg-blue-50 text-blue-300"
: "bg-red-50 text-red-300"
)}
- onPointerDown={(e) => {
+ onClick={(e) => {
e.stopPropagation();
- }}
- onClick={() => {
if (permissions?.data?.camera !== "granted") {
return requestPermission("camera");
}
- if (options.data && camera()?.deviceId) {
- commands.setRecordingOptions({
- captureTarget: options.data.captureTarget,
- audioInputName: options.data.audioInputName,
- cameraLabel: null,
- });
- }
+ if (!options.data?.cameraLabel) return;
+ commands.setRecordingOptions({
+ ...options.data,
+ cameraLabel: null,
+ });
}}
>
{permissions?.data?.camera !== "granted"
? "Request Permission"
- : camera()?.deviceId
+ : options.data?.cameraLabel
? "On"
: "Off"}
</button>
@@ -406,24 +448,17 @@ export default function () {
</div>
<div class="flex flex-col gap-[0.25rem] items-stretch">
<label class="text-gray-400">Microphone</label>
- <KSelect<{ name: string }>
- options={[{ name: "No Audio" }, ...(audioDevices.data ?? [])]}
- optionValue="name"
+ <KSelect<{ name: string; deviceId: string }>
+ options={[
+ { name: "No Audio", deviceId: "" },
+ ...(audioDevicesQuery.data ?? []),
+ ]}
+ optionValue="deviceId"
optionTextValue="name"
placeholder="No Audio"
- value={audioDevice() ?? { name: "No Audio" }}
+ value={audioDevice()}
disabled={isRecording()}
- onChange={(item: { name: string } | null) => {
- if (!item && permissions?.data?.microphone !== "granted") {
- return requestPermission("microphone");
- }
-
- if (!item || !options.data) return;
- commands.setRecordingOptions({
- ...options.data,
- audioInputName: item.name !== "No Audio" ? item.name : null,
- });
- }}
+ onChange={handleMicrophoneChange}
itemComponent={(props) => (
<MenuItem<typeof KSelect.Item> as={KSelect.Item} item={props.item}>
<KSelect.ItemLabel class="flex-1">
@@ -431,10 +466,22 @@ export default function () {
</KSelect.ItemLabel>
</MenuItem>
)}
+ open={microphoneSelectOpen()}
+ onOpenChange={async (isOpen: boolean) => {
+ if (isOpen) {
+ if (audioDevice().name === "No Audio") {
+ setMicrophoneSelectOpen(false);
+ await audioDevicesQuery.refetch();
+ }
+ setMicrophoneSelectOpen(true);
+ } else {
+ setMicrophoneSelectOpen(false);
+ }
+ }}
>
<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"
- onClick={() => {
+ onClick={(e) => {
if (permissions?.data?.microphone !== "granted") {
requestPermission("microphone");
}
@@ -445,9 +492,7 @@ export default function () {
name: string;
}> class="flex-1 text-left truncate">
{(state) => (
- <span onPointerDown={(e) => e.stopPropagation()}>
- {state.selectedOption().name}
- </span>
+ <span>{state.selectedOption()?.name ?? "No Audio"}</span>
)}
</KSelect.Value>
<button
@@ -458,16 +503,23 @@ export default function () {
? "bg-blue-50 text-blue-300"
: "bg-red-50 text-red-300"
)}
- onPointerDown={(e) => e.stopPropagation()}
- onClick={() => {
+ onClick={async (e) => {
+ e.stopPropagation();
if (permissions?.data?.microphone !== "granted") {
- return requestPermission("microphone");
+ await requestPermission("microphone");
+ if (permissions?.data?.microphone === "granted") {
+ commands.setRecordingOptions({
+ ...options.data,
+ audioInputName: audioDevice().name,
+ });
+ }
+ } else {
+ if (!options.data?.audioInputName) return;
+ commands.setRecordingOptions({
+ ...options.data,
+ audioInputName: null,
+ });
}
- if (!options.data?.audioInputName) return;
- commands.setRecordingOptions({
- ...options.data,
- audioInputName: null,
- });
}}
>
{permissions?.data?.microphone !== "granted"
diff --git a/apps/desktop/src/routes/camera.tsx b/apps/desktop/src/routes/camera.tsx
index abb917882..b9f54d405 100644
--- a/apps/desktop/src/routes/camera.tsx
+++ b/apps/desktop/src/routes/camera.tsx
@@ -38,7 +38,7 @@ export default function () {
const camera = createCameraForLabel(() => options.data?.cameraLabel ?? "");
- const [cameraPreviewRef, setCameraStream] = createCameraPreview(
+ const [cameraPreviewRef, getCameraStream] = createCameraPreview(
() => camera()?.deviceId
);
@@ -53,15 +53,42 @@ export default function () {
createEffect(on(() => state.size, resizeWindow));
const [isLoading, setIsLoading] = createSignal(true);
+ const [loadingText, setLoadingText] = createSignal("Camera is loading");
createEffect(() => {
- if (setCameraStream()) {
+ const stream = getCameraStream();
+ if (stream) {
setIsLoading(false);
+ } else {
+ setIsLoading(true);
+ }
+ });
+
+ createEffect(() => {
+ if (isLoading()) {
+ const loadingMessages = [
+ "Camera is loading",
+ "Acquiring lock on camera",
+ "Camera is starting",
+ "Almost there...",
+ "Just a moment longer",
+ ];
+ let index = 0;
+ const interval = setInterval(() => {
+ setLoadingText(loadingMessages[index]);
+ index = (index + 1) % loadingMessages.length;
+ }, 1000);
+
+ onCleanup(() => clearInterval(interval));
}
});
return (
- <Suspense fallback={<CameraLoadingState shape={state.shape} />}>
+ <Suspense
+ fallback={
+ <CameraLoadingState shape={state.shape} loadingText={loadingText()} />
+ }
+ >
<Show when={options.data}>
{(options) => (
<div
@@ -73,7 +100,12 @@ export default function () {
<div class="flex flex-col flex-1 relative" data-tauri-drag-region>
<Show
when={!isLoading()}
- fallback={<CameraLoadingState shape={state.shape} />}
+ fallback={
+ <CameraLoadingState
+ shape={state.shape}
+ loadingText={loadingText()}
+ />
+ }
>
<video
data-tauri-drag-region
@@ -136,15 +168,21 @@ export default function () {
);
}
-function CameraLoadingState({ shape }: { shape: CameraWindow.Shape }) {
+function CameraLoadingState({
+ shape,
+ loadingText,
+}: {
+ shape: CameraWindow.Shape;
+ loadingText: string;
+}) {
return (
<div
class={cx(
- "w-full h-full bg-[#000000] flex items-center justify-center",
+ "w-full h-full bg-gray-500 flex items-center justify-center",
shape === "round" ? "rounded-full" : "rounded-3xl"
)}
>
- <IconLucideLoaderCircle class="size-[4rem] animate-spin text-gray-300" />
+ <div class="text-gray-300 text-sm">{loadingText}</div>
</div>
);
}
@@ -174,44 +212,47 @@ async function resizeWindow(size: CameraWindow.Size) {
}
function createCameraPreview(deviceId: () => string | undefined) {
- const [cameraStream, { refetch }] = createResource(
- deviceId,
- async (cameraInputId) => {
- if (!cameraInputId) return null;
- try {
- const stream = await navigator.mediaDevices.getUserMedia({
- video: {
- deviceId: cameraInputId,
- width: { ideal: 1920 },
- height: { ideal: 1080 },
- frameRate: { ideal: 30 },
- },
- });
-
- // Get the actual settings of the stream
- const videoTrack = stream.getVideoTracks()[0];
- const settings = videoTrack.getSettings();
- console.log("Camera settings:", settings);
-
- return stream;
- } catch (error) {
- console.error("Error accessing camera:", error);
- return null;
- }
- }
+ const [cameraStream, setCameraStream] = createSignal<MediaStream | null>(
+ null
);
-
const [cameraRef, setCameraRef] = createSignal<HTMLVideoElement>();
+ createEffect(async () => {
+ const id = deviceId();
+ if (!id) {
+ setCameraStream(null);
+ return;
+ }
+
+ try {
+ const stream = await navigator.mediaDevices.getUserMedia({
+ video: {
+ deviceId: { exact: id },
+ height: 720,
+ },
+ });
+
+ setCameraStream(stream);
+
+ // Get the actual settings of the stream
+ const videoTrack = stream.getVideoTracks()[0];
+ const settings = videoTrack.getSettings();
+ console.log("Camera settings:", settings);
+ } catch (error) {
+ console.error("Error accessing camera:", error);
+ setCameraStream(null);
+ }
+ });
+
createEffect(() => {
const stream = cameraStream();
const ref = cameraRef();
if (ref && stream) {
- if (ref.srcObject !== stream) {
- ref.srcObject = stream;
- ref.play().catch(console.error);
- }
+ ref.srcObject = stream;
+ ref.play().catch(console.error);
+ } else if (ref) {
+ ref.srcObject = null;
}
});
diff --git a/apps/desktop/src/utils/media.ts b/apps/desktop/src/utils/media.ts
index 2cdec3ad9..0dadee447 100644
--- a/apps/desktop/src/utils/media.ts
+++ b/apps/desktop/src/utils/media.ts
@@ -66,3 +66,18 @@ export function createCameraForLabel(label: Accessor<string>) {
return camera || null;
};
}
+
+export async function stopMediaStream(kind: "audio" | "video" | "both") {
+ const streams = await navigator.mediaDevices.getUserMedia({
+ audio: kind === "audio" || kind === "both",
+ video: kind === "video" || kind === "both",
+ });
+
+ streams.getTracks().forEach((track) => {
+ if ((kind === "audio" && track.kind === "audio") ||
+ (kind === "video" && track.kind === "video") ||
+ kind === "both") {
+ track.stop();
+ }
+ });
+}
diff --git a/apps/desktop/src/utils/queries.ts b/apps/desktop/src/utils/queries.ts
index c7881d53b..a26fdb247 100644
--- a/apps/desktop/src/utils/queries.ts
+++ b/apps/desktop/src/utils/queries.ts
@@ -30,7 +30,7 @@ export const listAudioDevices = queryOptions({
queryKey: ["audioDevices"] as const,
queryFn: async () => {
const r = await commands.listAudioDevices();
- if (r.status === "ok") return r.data.map((name) => ({ name }));
+ if (r.status === "ok") return r.data.map((name) => ({ name, deviceId: name }));
},
reconcile: "name",
refetchInterval: 1000
diff --git a/apps/web/components/pages/DownloadPage.tsx b/apps/web/components/pages/DownloadPage.tsx
index d8e56a770..4837da9a1 100644
--- a/apps/web/components/pages/DownloadPage.tsx
+++ b/apps/web/components/pages/DownloadPage.tsx
@@ -49,7 +49,7 @@ export const DownloadPage = () => {
)}
</div>
<div className="fade-in-up animate-delay-2">
- <p className="text-xs">macOS 12.3+ or later recommended.</p>
+ <p className="text-xs">macOS 13+ or later recommended.</p>
</div>
{!showOtherOptions && (
<button