Skip to content

armgit / Cap

Public Imported from GitHub
0

Open source Loom alternative. Beautiful, shareable screen recordings.

feat: Delete multiple caps UI + refactor delete endpoint to action (#483)

Richie McIlroy23fca700ba13
diff --git a/apps/web/actions/videos/delete.ts b/apps/web/actions/videos/delete.ts
new file mode 100644
index 000000000..7c77904fe
--- /dev/null
+++ b/apps/web/actions/videos/delete.ts
@@ -0,0 +1,85 @@
+"use server";
+
+import { getCurrentUser } from "@cap/database/auth/session";
+import { s3Buckets, videos } from "@cap/database/schema";
+import { db } from "@cap/database";
+import { and, eq } from "drizzle-orm";
+import {
+ DeleteObjectsCommand,
+ ListObjectsV2Command,
+} from "@aws-sdk/client-s3";
+import { createS3Client, getS3Bucket } from "@/utils/s3";
+
+export async function deleteVideo(videoId: string) {
+ try {
+ const user = await getCurrentUser();
+ const userId = user?.id;
+
+ if (!videoId || !userId) {
+ return {
+ success: false,
+ message: "Missing required data",
+ };
+ }
+
+ const query = await db
+ .select({ video: videos, bucket: s3Buckets })
+ .from(videos)
+ .leftJoin(s3Buckets, eq(videos.bucket, s3Buckets.id))
+ .where(eq(videos.id, videoId));
+
+ if (query.length === 0) {
+ return {
+ success: false,
+ message: "Video does not exist",
+ };
+ }
+
+ const result = query[0];
+ if (!result) {
+ return {
+ success: false,
+ message: "Video not found",
+ };
+ }
+
+ await db
+ .delete(videos)
+ .where(and(eq(videos.id, videoId), eq(videos.ownerId, userId)));
+
+ const [s3Client] = await createS3Client(result.bucket);
+ const Bucket = await getS3Bucket(result.bucket);
+ const prefix = `${userId}/${videoId}/`;
+
+ const listObjectsCommand = new ListObjectsV2Command({
+ Bucket,
+ Prefix: prefix,
+ });
+
+ const listedObjects = await s3Client.send(listObjectsCommand);
+
+ if (listedObjects.Contents?.length) {
+ const deleteObjectsCommand = new DeleteObjectsCommand({
+ Bucket,
+ Delete: {
+ Objects: listedObjects.Contents.map((content: any) => ({
+ Key: content.Key,
+ })),
+ },
+ });
+
+ await s3Client.send(deleteObjectsCommand);
+ }
+
+ return {
+ success: true,
+ message: "Video deleted successfully",
+ };
+ } catch (error) {
+ console.error("Error deleting video:", error);
+ return {
+ success: false,
+ message: "Failed to delete video",
+ };
+ }
+}
\ No newline at end of file
diff --git a/apps/web/app/api/video/delete/route.ts b/apps/web/app/api/video/delete/route.ts
index b78831583..7f82a8d12 100644
--- a/apps/web/app/api/video/delete/route.ts
+++ b/apps/web/app/api/video/delete/route.ts
@@ -55,7 +55,7 @@ export async function DELETE(request: NextRequest) {
.delete(videos)
.where(and(eq(videos.id, videoId), eq(videos.ownerId, userId)));
- const s3Client = await createS3Client(result.bucket);
+ const [s3Client] = await createS3Client(result.bucket);
const Bucket = await getS3Bucket(result.bucket);
const prefix = `${userId}/${videoId}/`;
@@ -70,7 +70,7 @@ export async function DELETE(request: NextRequest) {
const deleteObjectsCommand = new DeleteObjectsCommand({
Bucket,
Delete: {
- Objects: listedObjects.Contents.map((content) => ({
+ Objects: listedObjects.Contents.map((content: any) => ({
Key: content.Key,
})),
},
diff --git a/apps/web/app/dashboard/caps/Caps.tsx b/apps/web/app/dashboard/caps/Caps.tsx
index de0033bdd..1c14a9565 100644
--- a/apps/web/app/dashboard/caps/Caps.tsx
+++ b/apps/web/app/dashboard/caps/Caps.tsx
@@ -5,9 +5,13 @@ import { VideoMetadata } from "@cap/database/types";
import { useRouter, useSearchParams } from "next/navigation";
import { useEffect, useState } from "react";
import toast from "react-hot-toast";
-import { CapCard } from "./components/CapCard";
+import { CapCard, CapCardProps } from "./components/CapCard";
import { CapPagination } from "./components/CapPagination";
import { EmptyCapState } from "./components/EmptyCapState";
+import { Button } from "@cap/ui";
+import { FontAwesomeIcon } from "@fortawesome/react-fontawesome";
+import { faTrash } from "@fortawesome/free-solid-svg-icons";
+import { deleteVideo } from "@/actions/videos/delete";
type VideoData = {
id: string;
@@ -37,6 +41,10 @@ export const Caps = ({
const { user } = useSharedContext();
const limit = 15;
const totalPages = Math.ceil(count / limit);
+ const [selectedCaps, setSelectedCaps] = useState<string[]>([]);
+ const [isDeleting, setIsDeleting] = useState(false);
+
+ const anyCapSelected = selectedCaps.length > 0;
useEffect(() => {
const fetchAnalytics = async () => {
@@ -69,13 +77,81 @@ export const Caps = ({
return;
}
- const response = await apiClient.video.delete({ query: { videoId } });
+ const response = await deleteVideo(videoId);
- if (response.status === 200) {
+ if (response.success) {
refresh();
toast.success("Cap deleted successfully");
} else {
- toast.error("Failed to delete Cap - please try again later");
+ toast.error(
+ response.message || "Failed to delete Cap - please try again later"
+ );
+ }
+ };
+
+ const toggleCapSelection = (capId: string) => {
+ setSelectedCaps((prevSelected) =>
+ prevSelected.includes(capId)
+ ? prevSelected.filter((id) => id !== capId)
+ : [...prevSelected, capId]
+ );
+ };
+
+ const deleteSelectedCaps = async () => {
+ if (selectedCaps.length === 0) return;
+
+ if (
+ !window.confirm(
+ `Are you sure you want to delete ${selectedCaps.length} cap${
+ selectedCaps.length === 1 ? "" : "s"
+ }? This cannot be undone.`
+ )
+ ) {
+ return;
+ }
+
+ setIsDeleting(true);
+
+ const loadingToast = toast.loading(
+ `Deleting ${selectedCaps.length} cap${
+ selectedCaps.length === 1 ? "" : "s"
+ }...`
+ );
+
+ try {
+ const results = await Promise.allSettled(
+ selectedCaps.map((capId) => deleteVideo(capId))
+ );
+
+ toast.dismiss(loadingToast);
+
+ const successCount = results.filter(
+ (result) => result.status === "fulfilled" && result.value.success
+ ).length;
+
+ const errorCount = selectedCaps.length - successCount;
+
+ if (successCount > 0) {
+ toast.success(
+ `Successfully deleted ${successCount} cap${
+ successCount === 1 ? "" : "s"
+ }`
+ );
+ }
+
+ if (errorCount > 0) {
+ toast.error(
+ `Failed to delete ${errorCount} cap${errorCount === 1 ? "" : "s"}`
+ );
+ }
+
+ setSelectedCaps([]);
+ refresh();
+ } catch (error) {
+ toast.dismiss(loadingToast);
+ toast.error("An error occurred while deleting caps");
+ } finally {
+ setIsDeleting(false);
}
};
@@ -84,7 +160,7 @@ export const Caps = ({
}
return (
- <div className="flex flex-col w-full">
+ <div className="flex flex-col w-full relative">
<div className="grid grid-cols-1 gap-4 sm:gap-6 sm:grid-cols-2 lg:grid-cols-3 xl:grid-cols-4 2xl:grid-cols-5">
{data.map((cap) => (
<CapCard
@@ -94,6 +170,9 @@ export const Caps = ({
onDelete={deleteCap}
userId={user?.id}
userSpaces={userSpaces}
+ isSelected={selectedCaps.includes(cap.id)}
+ onSelectToggle={() => toggleCapSelection(cap.id)}
+ anyCapSelected={anyCapSelected}
/>
))}
</div>
@@ -102,6 +181,34 @@ export const Caps = ({
<CapPagination currentPage={page} totalPages={totalPages} />
</div>
)}
+
+ {selectedCaps.length > 0 && (
+ <div className="fixed bottom-4 left-1/2 transform -translate-x-1/2 bg-white shadow-lg rounded-xl border border-gray-200 px-6 py-4 flex justify-between items-center z-50 w-full max-w-xl mx-auto">
+ <div className="text-sm font-medium text-gray-400">
+ {selectedCaps.length} cap{selectedCaps.length !== 1 ? "s" : ""}{" "}
+ selected
+ </div>
+ <div className="flex gap-2 ml-4">
+ <Button
+ style={{ minWidth: "auto" }}
+ variant="destructive"
+ onClick={deleteSelectedCaps}
+ disabled={isDeleting}
+ className="text-sm w-[50px]"
+ spinner={isDeleting}
+ >
+ <FontAwesomeIcon icon={faTrash} />
+ </Button>
+ <Button
+ variant="white"
+ onClick={() => setSelectedCaps([])}
+ className="text-sm"
+ >
+ Cancel
+ </Button>
+ </div>
+ </div>
+ )}
</div>
);
};
diff --git a/apps/web/app/dashboard/caps/components/CapCard.tsx b/apps/web/app/dashboard/caps/components/CapCard.tsx
index 80a616112..7082bf4f8 100644
--- a/apps/web/app/dashboard/caps/components/CapCard.tsx
+++ b/apps/web/app/dashboard/caps/components/CapCard.tsx
@@ -12,6 +12,7 @@ import {
faChevronDown,
faLink,
faTrash,
+ faCheck,
} from "@fortawesome/free-solid-svg-icons";
import { FontAwesomeIcon } from "@fortawesome/react-fontawesome";
import moment from "moment";
@@ -20,7 +21,7 @@ import { useRouter } from "next/navigation";
import { useState } from "react";
import { toast } from "react-hot-toast";
-interface CapCardProps {
+export interface CapCardProps {
cap: {
id: string;
ownerId: string;
@@ -36,6 +37,9 @@ interface CapCardProps {
onDelete: (videoId: string) => Promise<void>;
userId: string;
userSpaces: { id: string; name: string }[];
+ isSelected?: boolean;
+ onSelectToggle?: () => void;
+ anyCapSelected?: boolean;
}
export const CapCard: React.FC<CapCardProps> = ({
@@ -44,6 +48,9 @@ export const CapCard: React.FC<CapCardProps> = ({
onDelete,
userId,
userSpaces,
+ isSelected = false,
+ onSelectToggle,
+ anyCapSelected = false,
}) => {
const effectiveDate = cap.metadata?.customCreatedAt
? new Date(cap.metadata.customCreatedAt)
@@ -203,6 +210,14 @@ export const CapCard: React.FC<CapCardProps> = ({
}
};
+ const handleSelectClick = (e: React.MouseEvent) => {
+ e.preventDefault();
+ e.stopPropagation();
+ if (onSelectToggle) {
+ onSelectToggle();
+ }
+ };
+
return (
<>
<SharingDialog
@@ -214,8 +229,20 @@ export const CapCard: React.FC<CapCardProps> = ({
userSpaces={userSpaces}
onSharingUpdated={handleSharingUpdated}
/>
- <div className="flex relative flex-col gap-4 w-full h-full bg-gray-50 rounded-2xl border-gray-200 transition-colors duration-300 group hover:border-blue-300 border-[1px]">
- <div className="flex absolute duration-200 group-hover:opacity-100 opacity-0 top-2 right-2 z-[20] flex-col gap-2">
+ <div
+ className={`flex relative flex-col gap-4 w-full h-full bg-gray-50 rounded-2xl border-gray-200 transition-colors duration-300 group ${
+ isSelected
+ ? "border-blue-500 border-[1px]"
+ : anyCapSelected
+ ? "border-blue-300 border-[1px]"
+ : "hover:border-blue-300 border-[1px]"
+ }`}
+ >
+ <div
+ className={`flex absolute duration-200 ${
+ anyCapSelected ? "opacity-100" : "group-hover:opacity-100 opacity-0"
+ } top-2 right-2 z-[20] flex-col gap-2`}
+ >
<Tooltip content="Copy link">
<Button
onClick={() =>
@@ -244,9 +271,9 @@ export const CapCard: React.FC<CapCardProps> = ({
viewBox="0 0 24 24"
fill="none"
stroke="currentColor"
- stroke-width="2"
- stroke-linecap="round"
- stroke-linejoin="round"
+ strokeWidth="2"
+ strokeLinecap="round"
+ strokeLinejoin="round"
className="text-gray-400 size-5 svgpathanimation"
>
<path d="M20 6 9 17l-5-5" />
@@ -268,6 +295,29 @@ export const CapCard: React.FC<CapCardProps> = ({
</Button>
</Tooltip>
</div>
+
+ {/* Selection checkbox */}
+ <div
+ className={`absolute top-2 left-2 z-[20] duration-200 ${
+ isSelected || anyCapSelected
+ ? "opacity-100"
+ : "group-hover:opacity-100 opacity-0"
+ }`}
+ onClick={handleSelectClick}
+ >
+ <div
+ className={`flex items-center justify-center w-6 h-6 rounded-md border cursor-pointer hover:bg-gray-200/60 transition-colors ${
+ isSelected
+ ? "bg-blue-500 border-blue-500"
+ : "border-gray-400 bg-white/80"
+ }`}
+ >
+ {isSelected && (
+ <FontAwesomeIcon icon={faCheck} className="text-white size-3" />
+ )}
+ </div>
+ </div>
+
<Link
className="block group"
href={
@@ -279,7 +329,9 @@ export const CapCard: React.FC<CapCardProps> = ({
}
>
<VideoThumbnail
- imageClass="group-hover:opacity-50 transition-opacity duration-200"
+ imageClass={`${
+ anyCapSelected ? "opacity-50" : "group-hover:opacity-50"
+ } transition-opacity duration-200`}
userId={cap.ownerId}
videoId={cap.id}
alt={`${cap.name} Thumbnail`}