Skip to content

armgit / Cap

Public Imported from GitHub
0

Open source Loom alternative. Beautiful, shareable screen recordings.

feat: Memo thumbnails, recording performance upgrades

Richie McIlroy1732b4413406
diff --git a/apps/web/app/dashboard/caps/Caps.tsx b/apps/web/app/dashboard/caps/Caps.tsx
index 1046eb512..186d3443f 100644
--- a/apps/web/app/dashboard/caps/Caps.tsx
+++ b/apps/web/app/dashboard/caps/Caps.tsx
@@ -23,6 +23,7 @@ import {
PaginationNext,
PaginationPrevious,
} from "@cap/ui";
+import { debounce } from "lodash";
type videoData = {
id: string;
@@ -42,6 +43,43 @@ export const Caps = ({ data, count }: { data: videoData; count: number }) => {
const { user } = useSharedContext();
const limit = 16;
const totalPages = Math.ceil(count / limit);
+ const [isEditing, setIsEditing] = useState<null | string>(null);
+ const [titles, setTitles] = useState<Record<string, string>>({});
+
+ const handleTitleBlur = async ({ id }: { id: string }) => {
+ setIsEditing(id);
+
+ if (!titles[id]) {
+ setIsEditing(null);
+ return;
+ }
+
+ const response = await fetch(
+ `${process.env.NEXT_PUBLIC_URL}/api/video/title`,
+ {
+ method: "PUT",
+ headers: { "Content-Type": "application/json" },
+ body: JSON.stringify({ title: titles[id], videoId: id }),
+ }
+ );
+ if (!response.ok) {
+ toast.error("Failed to update title - please try again.");
+ return;
+ }
+
+ toast.success("Video title updated");
+
+ setIsEditing(null);
+ };
+
+ const handleTitleKeyDown = debounce(
+ async ({ key, id }: { key: string; id: string }) => {
+ if (key === "Enter") {
+ handleTitleBlur({ id });
+ }
+ },
+ 300
+ );
useEffect(() => {
const fetchAnalytics = async () => {
@@ -180,8 +218,41 @@ export const Caps = ({ data, count }: { data: videoData; count: number }) => {
alt={`${cap.name} Thumbnail`}
/>
</a>
- <div className="p-4">
- <p className="font-medium">{cap.name}</p>
+ <div className="flex flex-col p-4">
+ {isEditing !== null && isEditing === cap.id ? (
+ <textarea
+ rows={1}
+ value={titles[cap.id] || cap.name}
+ onChange={(e) =>
+ setTitles({
+ ...titles,
+ [cap.id]: e.target.value,
+ })
+ }
+ onBlur={() => {
+ handleTitleBlur({ id: cap.id });
+ }}
+ onKeyDown={(e) => {
+ handleTitleKeyDown({ key: e.key, id: cap.id });
+ }}
+ autoFocus
+ className="font-medium box-border"
+ />
+ ) : (
+ <p
+ className="font-medium"
+ onClick={() => {
+ if (
+ user !== null &&
+ user.id.toString() === cap.ownerId
+ ) {
+ setIsEditing(cap.id);
+ }
+ }}
+ >
+ {titles[cap.id] || cap.name}
+ </p>
+ )}
<p className="text-sm text-gray-400">
{moment(cap.createdAt).fromNow()}
</p>
diff --git a/apps/web/app/record/Record.tsx b/apps/web/app/record/Record.tsx
index f2656cf12..54623049c 100644
--- a/apps/web/app/record/Record.tsx
+++ b/apps/web/app/record/Record.tsx
@@ -37,6 +37,7 @@ import { fetchFile } from "@ffmpeg/util";
import { getLatestVideoId, saveLatestVideoId } from "@cap/utils";
import { isUserOnProPlan } from "@cap/utils";
import { LogoBadge } from "@cap/ui";
+import { set } from "lodash";
class AsyncTaskQueue {
private queue: (() => Promise<void>)[];
@@ -240,6 +241,16 @@ export const Record = ({
const stream = await navigator.mediaDevices.getDisplayMedia(
displayMediaOptions
);
+ if (stream) {
+ stream.getTracks().forEach((track: MediaStreamTrack) => {
+ track.onended = async () => {
+ if (isRecording === true) {
+ await stopRecording();
+ }
+ };
+ });
+ }
+
const videoElement = document.createElement("video");
videoElement.srcObject = stream;
@@ -387,7 +398,7 @@ export const Record = ({
saveLatestVideoId(videoCreateData.id);
- setStartingRecording(true);
+ setStartingRecording(false);
const combinedStream = new MediaStream();
const canvas = document.createElement("canvas");
@@ -599,12 +610,17 @@ export const Record = ({
console.log("Segment duration:", segmentDuration);
console.log("Start:", Math.max(videoDuration - segmentDuration, 0));
+ console.log(
+ "Final segment? ",
+ videoRecorder.state !== "recording" || stoppingRecording
+ );
+
muxQueue.enqueue(async () => {
try {
await muxSegment({
data: chunks,
mimeType: videoRecorderOptions.mimeType,
- final: videoRecorder.state !== "recording",
+ final: videoRecorder.state !== "recording" || stoppingRecording,
start: Math.max(videoDuration - segmentDuration, 0),
end: videoDuration,
segmentTime: segmentDuration,
@@ -789,42 +805,52 @@ export const Record = ({
const videoId = await getLatestVideoId();
if (segmentIndex === 0) {
+ console.log("Generating screenshot...");
const video = document.createElement("video");
video.src = URL.createObjectURL(videoSegment);
video.muted = true;
video.autoplay = true;
+ video.playsInline = true;
+
+ video.addEventListener("loadeddata", async () => {
+ const canvas = document.createElement("canvas");
+ canvas.width = video.videoWidth;
+ canvas.height = video.videoHeight;
+
+ const context = canvas.getContext("2d");
+ context?.drawImage(
+ video,
+ 0,
+ 0,
+ video.videoWidth,
+ video.videoHeight
+ );
+
+ canvas.toBlob(
+ async (screenshotBlob) => {
+ if (screenshotBlob) {
+ const screenshotFile = await fetchFile(
+ URL.createObjectURL(screenshotBlob)
+ );
+
+ const screenshotFilename = "screenshot/screen-capture.jpg";
+ await uploadSegment({
+ file: screenshotFile,
+ filename: screenshotFilename,
+ videoId,
+ });
+ }
+ },
+ "image/jpeg",
+ 0.5
+ );
+ video.remove();
+ canvas.remove();
+ });
+
video.play().catch((error) => {
console.error("Video play failed:", error);
});
-
- const canvas = document.createElement("canvas");
-
- canvas.width = video.videoWidth;
- canvas.height = video.videoHeight;
-
- const context = canvas.getContext("2d");
- context?.drawImage(video, 0, 0, video.videoWidth, video.videoHeight);
-
- canvas.toBlob(
- async (screenshotBlob) => {
- if (screenshotBlob) {
- const screenshotFile = await fetchFile(
- URL.createObjectURL(screenshotBlob)
- );
-
- const screenshotFilename = "screenshot/screen-capture.jpg";
- await uploadSegment({
- file: screenshotFile,
- filename: screenshotFilename,
- videoId,
- });
- }
- },
- "image/jpeg",
- 0.5
- );
- video.remove();
- canvas.remove();
}
try {
@@ -850,13 +876,6 @@ export const Record = ({
console.log("herelast: ", await ffmpegRef.current.listDir("/"));
- // tempInput: `temp_segment_${segmentIndexString}${
- // mimeType.includes("mp4") ? ".mp4" : ".webm"
- // }`,
- // videoInput: `input_segment_${segmentIndexString}.ts`,
- // videoOutput: `video_segment_${segmentIndexString}.ts`,
- // audioOutput: `audio_segment_${segmentIndexString}.aac`,
-
try {
await ffmpegRef.current.deleteFile(segmentPaths.tempInput);
} catch (error) {
@@ -947,7 +966,7 @@ export const Record = ({
}
while (readyToStopRecording.current === false) {
- await new Promise((resolve) => setTimeout(resolve, 1000));
+ await new Promise((resolve) => setTimeout(resolve, 250));
console.log("Waiting for readyToStopRecording");
}
@@ -971,7 +990,6 @@ export const Record = ({
setIsRecording(false);
setStoppingRecording(false);
-
totalSegments.current = 0;
readyToStopRecording.current = false;
};
@@ -1146,7 +1164,7 @@ export const Record = ({
}, [screenStream, videoStream]);
useEffect(() => {
- if (stoppingRecording) {
+ if (stoppingRecording === true) {
const messages = ["Processing video", "Almost done", "Finishing up"];
let messageIndex = 0;
@@ -1157,7 +1175,7 @@ export const Record = ({
nextMessage();
- const intervalId = setInterval(nextMessage, 2500);
+ const intervalId = setInterval(nextMessage, 2000);
return () => clearInterval(intervalId);
} else {
@@ -1284,19 +1302,19 @@ export const Record = ({
<Button
className="min-w-[175px]"
{...(isRecording && { variant: "destructive" })}
- onClick={() => {
+ onClick={async () => {
if (isRecording) {
- stopRecording();
+ await stopRecording();
} else {
- startRecording();
+ await startRecording();
}
}}
spinner={startingRecording || stoppingRecording}
>
- {startingRecording
+ {startingRecording === true
? "Starting..."
- : isRecording
- ? stoppingRecording
+ : isRecording === true
+ ? stoppingRecording === true
? currentStoppingMessage
: `Stop - ${recordingTime}`
: "Start Recording"}
diff --git a/apps/web/components/VideoThumbnail.tsx b/apps/web/components/VideoThumbnail.tsx
index 66a5baaf1..b5196e34a 100644
--- a/apps/web/components/VideoThumbnail.tsx
+++ b/apps/web/components/VideoThumbnail.tsx
@@ -1,6 +1,6 @@
import { LogoSpinner } from "@cap/ui";
import Image from "next/image";
-import { useEffect, useState } from "react";
+import { useEffect, useState, memo } from "react";
interface VideoThumbnailProps {
userId: string;
@@ -17,68 +17,66 @@ function generateRandomGrayScaleColor() {
return `rgb(${grayScaleValue}, ${grayScaleValue}, ${grayScaleValue})`;
}
-export const VideoThumbnail = ({
- userId,
- videoId,
- alt,
-}: VideoThumbnailProps) => {
- const [imageUrls, setImageUrls] = useState({ screen: "" });
- const [loading, setLoading] = useState(true);
- const [failed, setFailed] = useState(false);
+export const VideoThumbnail: React.FC<VideoThumbnailProps> = memo(
+ ({ userId, videoId, alt }) => {
+ const [imageUrls, setImageUrls] = useState({ screen: "" });
+ const [loading, setLoading] = useState(true);
+ const [failed, setFailed] = useState(false);
- useEffect(() => {
- const fetchPreSignedUrls = async () => {
- try {
- const response = await fetch(
- `/api/thumbnail?userId=${userId}&videoId=${videoId}`
- );
- if (response.ok) {
- const data = await response.json();
- setImageUrls({ screen: data.screen });
- } else {
- console.error("Failed to fetch pre-signed URLs");
+ useEffect(() => {
+ const fetchPreSignedUrls = async () => {
+ try {
+ const response = await fetch(
+ `/api/thumbnail?userId=${userId}&videoId=${videoId}`
+ );
+ if (response.ok) {
+ const data = await response.json();
+ setImageUrls({ screen: data.screen });
+ } else {
+ console.error("Failed to fetch pre-signed URLs");
+ }
+ } catch (error) {
+ console.error("Error fetching pre-signed URLs:", error);
}
- } catch (error) {
- console.error("Error fetching pre-signed URLs:", error);
- }
- };
+ };
- fetchPreSignedUrls();
- }, [userId, videoId]);
+ fetchPreSignedUrls();
+ }, [userId, videoId]);
- const randomGradient = `linear-gradient(to right, ${generateRandomGrayScaleColor()}, ${generateRandomGrayScaleColor()})`;
+ const randomGradient = `linear-gradient(to right, ${generateRandomGrayScaleColor()}, ${generateRandomGrayScaleColor()})`;
- return (
- <div
- className={`aspect-video relative overflow-hidden rounded-tr-lg rounded-tl-lg bg-black`}
- >
- <div className="absolute top-0 left-0 flex items-center justify-center w-full h-full z-10">
- {failed ? (
- <div
- className="w-full h-full"
- style={{ backgroundImage: randomGradient }}
- ></div>
- ) : (
- loading === true && (
- <LogoSpinner className="w-5 md:w-8 h-auto animate-spin" />
- )
+ return (
+ <div
+ className={`aspect-video relative overflow-hidden rounded-tr-lg rounded-tl-lg bg-black`}
+ >
+ <div className="absolute top-0 left-0 flex items-center justify-center w-full h-full z-10">
+ {failed ? (
+ <div
+ className="w-full h-full"
+ style={{ backgroundImage: randomGradient }}
+ ></div>
+ ) : (
+ loading === true && (
+ <LogoSpinner className="w-5 md:w-8 h-auto animate-spin" />
+ )
+ )}
+ </div>
+ {imageUrls.screen && (
+ <Image
+ src={imageUrls.screen}
+ alt={alt}
+ layout="fill"
+ objectFit="cover"
+ className="group-hover:scale-[1.02] transition-all w-full h-full"
+ onLoad={() => setLoading(false)}
+ onError={() => {
+ setFailed(true);
+ setLoading(false);
+ }}
+ />
)}
+ <div className="bg-black opacity-0 z-10 absolute top-0 left-0 w-full h-full group-hover:opacity-50 transition-all"></div>
</div>
- {imageUrls.screen && (
- <Image
- src={imageUrls.screen}
- alt={alt}
- layout="fill"
- objectFit="cover"
- className="group-hover:scale-[1.02] transition-all w-full h-full"
- onLoad={() => setLoading(false)}
- onError={() => {
- setFailed(true);
- setLoading(false);
- }}
- />
- )}
- <div className="bg-black opacity-0 z-10 absolute top-0 left-0 w-full h-full group-hover:opacity-50 transition-all"></div>
- </div>
- );
-};
+ );
+ }
+);
diff --git a/apps/web/package.json b/apps/web/package.json
index 32384fdf7..14e6cdb0a 100644
--- a/apps/web/package.json
+++ b/apps/web/package.json
@@ -59,6 +59,7 @@
"zod": "^3.22.4"
},
"devDependencies": {
+ "@types/lodash": "^4.17.5",
"@types/node": "^20.11.5",
"@types/react": "^18.2.7",
"@types/react-dom": "^18",
diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml
index d5cf49394..48f88a479 100644
--- a/pnpm-lock.yaml
+++ b/pnpm-lock.yaml
@@ -231,6 +231,9 @@ importers:
react-hot-toast:
specifier: ^2.4.1
+ react-lottie:
+ specifier: ^1.2.4
+ version: 1.2.4([email protected])
react-player:
specifier: ^2.14.1
version: 2.14.1([email protected])
@@ -256,6 +259,9 @@ importers:
specifier: ^3.22.4
version: 3.22.4
devDependencies:
+ '@types/lodash':
+ specifier: ^4.17.5
+ version: 4.17.5
'@types/node':
specifier: ^20.11.5
version: 20.11.5
@@ -5712,6 +5718,10 @@ packages:
resolution: {integrity: sha512-dRLjCWHYg4oaA77cxO64oO+7JwCwnIzkZPdrrC71jQmQtlhM556pwKo5bUzqvZndkVbeFLIIi+9TC40JNF5hNQ==}
dev: true
+ resolution: {integrity: sha512-MBIOHVZqVqgfro1euRDWX7OO0fBVUUMrN6Pwm8LQsz8cWhEpihlvR70ENj3f40j58TNxZaWv2ndSkInykNBBJw==}
+ dev: true
+
resolution: {integrity: sha512-MqTGEo5bj5t157U6fA/BiDynNkn0YknVdh48CMPkTSpFTVmvao5UQmm7uEF6xBEo7qIMAlY/JSleYaE6VOdpaA==}
dev: false
@@ -6369,6 +6379,13 @@ packages:
dequal: 2.0.3
dev: true
+ resolution: {integrity: sha512-ITKNuq2wKlW1fJg9sSW52eepoYgZBggvOAHC0u/CYu/qxQ9EVzThCgR69BnSXLHjy2f7SY5zaQ4yt7H9ZVxY2g==}
+ dependencies:
+ core-js: 2.6.12
+ regenerator-runtime: 0.11.1
+ dev: false
+
resolution: {integrity: sha512-0xO6mYd7JB2YesxDKplafRpsiOzPt9V02ddPCLbY1xYGPOX24NTyN50qnUxgCPcSoYMhKpAuBTjQoRZCAkUDRw==}
dev: false
@@ -6828,6 +6845,12 @@ packages:
requiresBuild: true
dev: true
+ resolution: {integrity: sha512-Kb2wC0fvsWfQrgk8HU5lW6U/Lcs8+9aaYcy4ZFc6DDlo4nZ7n70dEgE5rtR0oG6ufKDUnrwfWL1mXR5ljDatrQ==}
+ deprecated: core-js@<3.23.3 is no longer maintained and not recommended for usage due to the number of issues. Because of the V8 engine whims, feature detection in old core-js versions could cause a slowdown up to 100x even if nothing is polyfilled. Some versions have web compatibility issues. Please, upgrade your dependencies to the actual version of core-js.
+ requiresBuild: true
+ dev: false
+
resolution: {integrity: sha512-+jwgnhg6cQxKYIIjGtAHq2nwUOolo9eoFZ4sHfUH09BLXBgxnH4gA0zEd+t+BO2cNB8idaBtZFcFTRjQJRJmAw==}
requiresBuild: true
@@ -9505,6 +9528,10 @@ packages:
dependencies:
js-tokens: 4.0.0
+ resolution: {integrity: sha512-uvhvYPC8kGPjXT3MyKMrL3JitEAmDMp30lVkuq/590Mw9ok6pWcFCwXJveo0t5uqYw1UREQHofD+jVpdjBv8wg==}
+ dev: false
+
resolution: {integrity: sha512-UuxaYakO7XeONbKrZf5FEgkantPf5DUqDayzP5VXZrtRPdH86s4kN47I8B3TW10S4QKiE3ziHNf3kRN//okHjA==}
dependencies:
@@ -11087,6 +11114,17 @@ packages:
react: 18.2.0
dev: false
+ resolution: {integrity: sha512-kBGxI+MIZGBf4wZhNCWwHkMcVP+kbpmrLWH/SkO0qCKc7D7eSPcxQbfpsmsCo8v2KCBYjuGSou+xTqK44D/jMg==}
+ engines: {npm: ^3.0.0}
+ peerDependencies:
+ react: '>=15.0.0'
+ dependencies:
+ babel-runtime: 6.26.0
+ lottie-web: 5.12.2
+ react: 18.2.0
+ dev: false
+
resolution: {integrity: sha512-jILj7F9o+6NHzrJ1GqZIxfJgskvGmKeJ05FNhPvgiCpvMZFmFneKEkukywHcULDO2lqITm+zcEkLSq42mX0FbA==}
peerDependencies:
@@ -11314,6 +11352,10 @@ packages:
which-builtin-type: 1.1.3
dev: true
+ resolution: {integrity: sha512-MguG95oij0fC3QV3URf4V2SDYGJhJnJGqvIIgdECeODCT98wSWDAJ94SSuVpYQUoTcGUIL6L4yNB7j1DFFHSBg==}
+ dev: false
+
resolution: {integrity: sha512-kY1AZVr2Ra+t+piVaJ4gxaFaReZVH40AKNo7UCX6W+dEwBo/2oZJzqfuN1qLq1oL45o56cPaTXELwrTh8Fpggg==}
dev: false