Skip to content

armgit / dub

Public Imported from GitHub
0

The modern link attribution platform. Loved by world-class engineering teams at Twilio, Zillow, Jobber, Vercel, Raycast, and more.

Add resource deletion

Tim Wilsoned7b212fdc31
diff --git a/apps/web/app/app.dub.co/(dashboard)/[slug]/programs/[programId]/resources/page-client.tsx b/apps/web/app/app.dub.co/(dashboard)/[slug]/programs/[programId]/resources/page-client.tsx
index d788f83aa1..d5bbe345dd 100644
--- a/apps/web/app/app.dub.co/(dashboard)/[slug]/programs/[programId]/resources/page-client.tsx
+++ b/apps/web/app/app.dub.co/(dashboard)/[slug]/programs/[programId]/resources/page-client.tsx
@@ -1,13 +1,25 @@
"use client";
+import { deleteProgramResourceAction } from "@/lib/actions/partners/program-resources/delete-program-resource";
import useProgramResources from "@/lib/swr/use-program-resources";
-import { Button } from "@dub/ui";
-import { formatFileSize } from "@dub/utils";
-import { PropsWithChildren, ReactNode } from "react";
+import useWorkspace from "@/lib/swr/use-workspace";
+import { ThreeDots } from "@/ui/shared/icons";
+import {
+ AnimatedSizeContainer,
+ Button,
+ LoadingSpinner,
+ Popover,
+ Trash,
+} from "@dub/ui";
+import { capitalize, cn, formatFileSize } from "@dub/utils";
+import { useAction } from "next-safe-action/hooks";
+import { useParams } from "next/navigation";
+import { PropsWithChildren, ReactNode, useState } from "react";
+import { toast } from "sonner";
import { useAddLogoModal } from "./add-logo-modal";
export function ProgramResourcesPageClient() {
- const { resources, loading } = useProgramResources();
+ const { resources, mutate } = useProgramResources();
const { setShowAddLogoModal, AddLogoModal } = useAddLogoModal();
return (
@@ -23,6 +35,8 @@ export function ProgramResourcesPageClient() {
{resources?.logos?.map((logo) => (
<ResourceCard
key={logo.id}
+ resourceId={logo.id}
+ resourceType="logo"
icon={
<div className="relative size-8 overflow-hidden">
<img
@@ -34,6 +48,7 @@ export function ProgramResourcesPageClient() {
}
title={logo.name || "Logo"}
description={formatFileSize(logo.size, 0)}
+ onDelete={() => mutate()}
/>
))}
</Section>
@@ -56,42 +71,88 @@ function Section({
resource,
title,
description,
- children,
onAdd,
+ children,
}: PropsWithChildren<{
resource: string;
title: string;
description: string;
onAdd?: () => void;
}>) {
+ const { isLoading, isValidating } = useProgramResources();
+
return (
<div className="grid grid-cols-1 rounded-lg border border-neutral-200 p-6 sm:grid-cols-2">
<div>
<h2 className="text-lg font-semibold text-neutral-900">{title}</h2>
<p className="text-sm text-neutral-600">{description}</p>
</div>
- <div className="flex flex-col items-end gap-4">
- {children}
- <Button
- type="button"
- text={`Add ${resource}`}
- onClick={onAdd || (() => alert("WIP"))}
- className="h-8 w-fit px-3"
- />
+ <div className="-m-1">
+ <AnimatedSizeContainer
+ height
+ transition={{ duration: 0.2, ease: "easeInOut" }}
+ >
+ <div
+ className={cn(
+ "flex flex-col items-end gap-4 p-1 transition-opacity",
+ isValidating && "opacity-50",
+ )}
+ >
+ {children}
+ <Button
+ type="button"
+ text={`Add ${resource}`}
+ onClick={onAdd || (() => alert("WIP"))}
+ className="h-8 w-fit px-3"
+ />
+ </div>
+ </AnimatedSizeContainer>
</div>
</div>
);
}
function ResourceCard({
+ resourceId,
+ resourceType,
title,
description,
icon,
+ onDelete,
}: {
+ resourceId: string;
+ resourceType: "logo" | "color" | "file";
title: string;
description: string;
icon: ReactNode;
+ onDelete?: () => void;
}) {
+ const { programId } = useParams();
+ const { id: workspaceId } = useWorkspace();
+ const [openPopover, setOpenPopover] = useState(false);
+ const [isDeleting, setIsDeleting] = useState(false);
+
+ const { executeAsync } = useAction(deleteProgramResourceAction, {
+ onSuccess: () => {
+ toast.success(`${capitalize(resourceType)} deleted successfully`);
+ onDelete?.();
+ },
+ onError: ({ error }) => {
+ toast.error(error.serverError || `Failed to delete ${resourceType}`);
+ setIsDeleting(false);
+ },
+ });
+
+ const handleDelete = async () => {
+ setIsDeleting(true);
+ await executeAsync({
+ workspaceId: workspaceId as string,
+ programId: programId as string,
+ resourceType,
+ resourceId,
+ });
+ };
+
return (
<div className="flex w-full items-center justify-between gap-4 rounded-lg border border-neutral-200 p-4">
<div className="flex items-center gap-4">
@@ -103,7 +164,53 @@ function ResourceCard({
<span className="text-xs text-neutral-500">{description}</span>
</div>
</div>
- {/* TODO: Menu button */}
+ <div className="relative">
+ <Popover
+ content={
+ <div className="w-full sm:w-48">
+ <div className="grid gap-px p-2">
+ <Button
+ text={`Delete ${resourceType}`}
+ variant="danger-outline"
+ onClick={() => {
+ setOpenPopover(false);
+
+ if (
+ !confirm("Are you sure you want to delete this resource?")
+ )
+ return;
+
+ handleDelete();
+ }}
+ icon={<Trash className="size-4" />}
+ className="h-9 justify-start px-2 font-medium"
+ />
+ </div>
+ </div>
+ }
+ align="end"
+ openPopover={openPopover}
+ setOpenPopover={setOpenPopover}
+ >
+ <Button
+ variant="secondary"
+ className={cn(
+ "h-8 px-1.5 text-neutral-500 outline-none transition-all duration-200",
+ "border-transparent data-[state=open]:border-neutral-500 sm:group-hover/card:data-[state=closed]:border-neutral-200",
+ )}
+ icon={
+ isDeleting ? (
+ <LoadingSpinner className="size-4 shrink-0" />
+ ) : (
+ <ThreeDots className="size-4 shrink-0" />
+ )
+ }
+ onClick={() => {
+ setOpenPopover(!openPopover);
+ }}
+ />
+ </Popover>
+ </div>
</div>
);
}
diff --git a/apps/web/lib/actions/partners/program-resources/delete-program-resource.ts b/apps/web/lib/actions/partners/program-resources/delete-program-resource.ts
new file mode 100644
index 0000000000..fec912bfff
--- /dev/null
+++ b/apps/web/lib/actions/partners/program-resources/delete-program-resource.ts
@@ -0,0 +1,81 @@
+"use server";
+
+import { storage } from "@/lib/storage";
+import {
+ PROGRAM_RESOURCE_TYPES,
+ programResourcesSchema,
+} from "@/lib/zod/schemas/program-resources";
+import { prisma } from "@dub/prisma";
+import { R2_URL } from "@dub/utils";
+import { z } from "zod";
+import { authActionClient } from "../../safe-action";
+
+// Schema for deleting a program resource
+const deleteProgramResourceSchema = z.object({
+ workspaceId: z.string(),
+ programId: z.string(),
+ resourceType: z.enum(PROGRAM_RESOURCE_TYPES),
+ resourceId: z.string(),
+});
+
+export const deleteProgramResourceAction = authActionClient
+ .schema(deleteProgramResourceSchema)
+ .action(async ({ ctx, parsedInput }) => {
+ const { workspace } = ctx;
+ const { programId, resourceType, resourceId } = parsedInput;
+
+ // Verify the program exists and belongs to the workspace
+ const program = await prisma.program.findUnique({
+ where: {
+ id: programId,
+ workspaceId: workspace.id,
+ },
+ select: {
+ id: true,
+ resources: true,
+ },
+ });
+
+ if (!program) throw new Error("Program not found");
+ if (!program.resources) throw new Error("Program resources not found");
+
+ // Create a copy of the current resources to update
+ const updatedResources = { ...program.resources };
+
+ // Find the resource to delete
+ const resourceKey = `${resourceType}s`;
+ const resourceArray = updatedResources[resourceKey] || [];
+ const resource = resourceArray.find(({ id }) => id === resourceId);
+
+ if (!resource) throw new Error(`Resource not found`);
+
+ // Delete file-based resources from storage
+ if ((resourceType === "logo" || resourceType === "file") && resource.url) {
+ try {
+ await storage.delete(resource.url.replace(`${R2_URL}/`, ""));
+ } catch (error) {
+ console.error(
+ "Failed to delete program resource file from storage:",
+ error,
+ );
+ }
+ }
+
+ // Remove the resource from the array
+ updatedResources[resourceKey] = resourceArray.filter(
+ ({ id }) => id !== resourceId,
+ );
+
+ await prisma.program.update({
+ where: {
+ id: programId,
+ },
+ data: {
+ resources: programResourcesSchema.parse(updatedResources) as any,
+ },
+ });
+
+ return {
+ success: true,
+ };
+ });
diff --git a/apps/web/lib/swr/use-program-resources.ts b/apps/web/lib/swr/use-program-resources.ts
index 19a38af1e0..eb34cd21a0 100644
--- a/apps/web/lib/swr/use-program-resources.ts
+++ b/apps/web/lib/swr/use-program-resources.ts
@@ -14,6 +14,7 @@ export default function useProgramResources() {
const {
data: resources,
error,
+ isValidating,
mutate,
} = useSWR<ProgramResourcesProps>(
programId && workspaceId
@@ -22,6 +23,8 @@ export default function useProgramResources() {
fetcher,
{
dedupingInterval: 60000,
+ revalidateOnFocus: false,
+ keepPreviousData: true,
},
);
@@ -29,6 +32,7 @@ export default function useProgramResources() {
resources,
error,
mutate,
- loading: programId && !resources && !error,
+ isValidating,
+ isLoading: programId && !resources && !error,
};
}
diff --git a/apps/web/lib/zod/schemas/program-resources.ts b/apps/web/lib/zod/schemas/program-resources.ts
index 118f74694d..8cbe4c35e4 100644
--- a/apps/web/lib/zod/schemas/program-resources.ts
+++ b/apps/web/lib/zod/schemas/program-resources.ts
@@ -1,5 +1,7 @@
import { z } from "zod";
+export const PROGRAM_RESOURCE_TYPES = ["logo", "file", "color"] as const;
+
export const programResourceFileSchema = z.object({
id: z.string(),
name: z.string(),