The modern link attribution platform. Loved by world-class engineering teams at Twilio, Zillow, Jobber, Vercel, Raycast, and more.
TypeScript clickhousemysqlnextjsopen-sourceplanetscaleprismatailwindcsstinybirdtypescriptupstashvercel
WIP logos management
Tim Wilsonb0c81e45596c
diff --git a/apps/web/app/app.dub.co/(dashboard)/[slug]/programs/[programId]/resources/add-logo-modal.tsx b/apps/web/app/app.dub.co/(dashboard)/[slug]/programs/[programId]/resources/add-logo-modal.tsxnew file mode 100644index 0000000000..aacf192a09--- /dev/null+++ b/apps/web/app/app.dub.co/(dashboard)/[slug]/programs/[programId]/resources/add-logo-modal.tsx@@ -0,0 +1,216 @@+"use client";++import { addProgramResourceAction } from "@/lib/actions/partners/program-resources/add-program-resource";+import useProgramResources from "@/lib/swr/use-program-resources";+import useWorkspace from "@/lib/swr/use-workspace";+import { Button, FileUpload, Modal } from "@dub/ui";+import { cn } from "@dub/utils";+import { useAction } from "next-safe-action/hooks";+import { useParams } from "next/navigation";+import {+ Dispatch,+ SetStateAction,+ useCallback,+ useMemo,+ useState,+} from "react";+import { Controller, useForm } from "react-hook-form";+import { toast } from "sonner";+import { z } from "zod";++type AddLogoModalProps = {+ showAddLogoModal: boolean;+ setShowAddLogoModal: Dispatch<SetStateAction<boolean>>;+};++// Define the form schema+const logoFormSchema = z.object({+ name: z.string(),+ file: z.string().min(1, "Logo file is required"),+});++type LogoFormData = z.infer<typeof logoFormSchema>;++function AddLogoModal(props: AddLogoModalProps) {+ return (+ <Modal+ showModal={props.showAddLogoModal}+ setShowModal={props.setShowAddLogoModal}+ >+ <AddLogoModalInner {...props} />+ </Modal>+ );+}++function AddLogoModalInner({ setShowAddLogoModal }: AddLogoModalProps) {+ const { programId } = useParams();+ const { id: workspaceId } = useWorkspace();+ const { mutate } = useProgramResources();++ const {+ register,+ handleSubmit,+ control,+ setValue,+ getValues,+ setError,+ formState: { errors, isSubmitting, isSubmitSuccessful },+ } = useForm<LogoFormData>({+ defaultValues: {+ name: "",+ file: "",+ },+ });++ const { executeAsync } = useAction(addProgramResourceAction, {+ onSuccess: () => {+ mutate();+ setShowAddLogoModal(false);+ toast.success("Logo added successfully!");+ },+ onError({ error }) {+ if (error.serverError) {+ setError("root.serverError", {+ message: error.serverError,+ });+ toast.error(error.serverError);+ } else {+ toast.error("Failed to upload logo");+ }+ },+ });++ return (+ <>+ <div className="space-y-2 border-b border-neutral-200 p-4 sm:p-6">+ <h3 className="text-lg font-medium leading-none">Add logo</h3>+ </div>++ <form+ onSubmit={handleSubmit(async (data: LogoFormData) => {+ await executeAsync({+ workspaceId: workspaceId!,+ programId: programId as string,+ name: data.name,+ resourceType: "logo",+ file: data.file,+ });+ })}+ >+ <div className="bg-neutral-50 p-4 sm:p-6">+ <div className="space-y-4">+ <div>+ <label+ htmlFor="logo-file"+ className="mb-1 block text-sm font-medium text-neutral-700"+ >+ Logo+ </label>+ <Controller+ control={control}+ name="file"+ rules={{ required: "Logo file is required" }}+ render={({ field }) => (+ <FileUpload+ accept="images"+ className={cn(+ "aspect-[4.2] w-full rounded-md border border-neutral-300",+ errors.file && "border-red-300 ring-1 ring-red-500",+ )}+ iconClassName="size-5"+ previewClassName="object-contain"+ variant="plain"+ imageSrc={field.value}+ readFile+ onChange={({ file, src }) => {+ field.onChange(src);++ // Set the logo name to the file name without extension if no name is provided+ const currentName = getValues("name");+ if (!currentName && file.name) {+ const nameWithoutExtension = file.name+ .split(".")+ .slice(0, -1)+ .join(".");+ setValue("name", nameWithoutExtension || file.name);+ }+ }}+ content="SVG, JPG, or PNG, max size of 10MB"+ maxFileSizeMB={10}+ />+ )}+ />+ {errors.file && (+ <p className="mt-1 text-xs text-red-600">+ {errors.file.message}+ </p>+ )}+ </div>++ <div>+ <label+ htmlFor="name"+ className="mb-1 block text-sm font-medium text-neutral-700"+ >+ File name+ </label>+ <input+ id="name"+ type="text"+ className={cn(+ "block w-full rounded-md border-neutral-300 shadow-sm focus:border-neutral-500 focus:ring-neutral-500 sm:text-sm",+ errors.name &&+ "border-red-300 pr-10 text-red-900 placeholder-red-300 focus:border-red-500 focus:ring-red-500",+ )}+ {...register("name", { required: "Name is required" })}+ />+ {errors.name && (+ <p className="mt-1 text-xs text-red-600">+ {errors.name.message}+ </p>+ )}+ </div>+ </div>+ </div>++ <div className="flex items-center justify-end gap-2 border-t border-neutral-200 bg-neutral-50 px-4 py-5 sm:px-6">+ <Button+ onClick={() => setShowAddLogoModal(false)}+ variant="secondary"+ text="Cancel"+ className="h-8 w-fit px-3"+ type="button"+ />+ <Button+ type="submit"+ autoFocus+ loading={isSubmitting || isSubmitSuccessful}+ text="Add Logo"+ className="h-8 w-fit px-3"+ />+ </div>+ </form>+ </>+ );+}++export function useAddLogoModal() {+ const [showAddLogoModal, setShowAddLogoModal] = useState(false);++ const AddLogoModalCallback = useCallback(() => {+ return (+ <AddLogoModal+ showAddLogoModal={showAddLogoModal}+ setShowAddLogoModal={setShowAddLogoModal}+ />+ );+ }, [showAddLogoModal, setShowAddLogoModal]);++ return useMemo(+ () => ({+ setShowAddLogoModal,+ AddLogoModal: AddLogoModalCallback,+ }),+ [setShowAddLogoModal, AddLogoModalCallback],+ );+}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.tsxindex b0b0cba31f..d788f83aa1 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@@ -4,37 +4,51 @@ import useProgramResources from "@/lib/swr/use-program-resources";import { Button } from "@dub/ui";import { formatFileSize } from "@dub/utils";import { PropsWithChildren, ReactNode } from "react";+import { useAddLogoModal } from "./add-logo-modal";export function ProgramResourcesPageClient() {const { resources, loading } = useProgramResources();+ const { setShowAddLogoModal, AddLogoModal } = useAddLogoModal();return (- <div className="flex flex-col gap-10">- <Section- resource="logo"- title="Brand logos"- description="SVG, JPG, or PNG, max size of 10 MB"- >- {resources?.logos?.map((logo) => (- <ResourceCard- key={logo.id}- icon={<div />}- title={logo.name}- description={formatFileSize(logo.size)}- />- ))}- </Section>- <Section- resource="color"- title="Colors"- description="Provide affiliates with official colors"- ></Section>- <Section- resource="file"- title="Additional files"- description="Any document file format, max size 10 MB"- ></Section>- </div>+ <>+ <AddLogoModal />+ <div className="flex flex-col gap-10">+ <Section+ resource="logo"+ title="Brand logos"+ description="SVG, JPG, or PNG, max size of 10 MB"+ onAdd={() => setShowAddLogoModal(true)}+ >+ {resources?.logos?.map((logo) => (+ <ResourceCard+ key={logo.id}+ icon={+ <div className="relative size-8 overflow-hidden">+ <img+ src={logo.url}+ alt="thumbnail"+ className="size-full object-contain"+ />+ </div>+ }+ title={logo.name || "Logo"}+ description={formatFileSize(logo.size, 0)}+ />+ ))}+ </Section>+ <Section+ resource="color"+ title="Colors"+ description="Provide affiliates with official colors"+ ></Section>+ <Section+ resource="file"+ title="Additional files"+ description="Any document file format, max size 10 MB"+ ></Section>+ </div>+ </>);}@@ -43,10 +57,12 @@ function Section({title,description,children,+ onAdd,}: PropsWithChildren<{resource: string;title: string;description: string;+ onAdd?: () => void;}>) {return (<div className="grid grid-cols-1 rounded-lg border border-neutral-200 p-6 sm:grid-cols-2">@@ -59,7 +75,7 @@ function Section({<Buttontype="button"text={`Add ${resource}`}- onClick={() => alert("WIP")}+ onClick={onAdd || (() => alert("WIP"))}className="h-8 w-fit px-3"/></div>@@ -77,9 +93,9 @@ function ResourceCard({icon: ReactNode;}) {return (- <div className="flex items-center justify-between gap-4 rounded border border-neutral-200">+ <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">- <div className="flex size-10 rounded-md border border-neutral-200">+ <div className="flex size-10 items-center justify-center rounded-md border border-neutral-200">{icon}</div><div className="flex flex-col">diff --git a/apps/web/lib/actions/partners/program-resources/add-program-resource.ts b/apps/web/lib/actions/partners/program-resources/add-program-resource.tsnew file mode 100644index 0000000000..74f61f2046--- /dev/null+++ b/apps/web/lib/actions/partners/program-resources/add-program-resource.ts@@ -0,0 +1,148 @@+"use server";++import { storage } from "@/lib/storage";+import {+ programResourceColorSchema,+ programResourceFileSchema,+} from "@/lib/zod/schemas/program-resources";+import { prisma } from "@dub/prisma";+import { nanoid } from "@dub/utils";+import { z } from "zod";+import { authActionClient } from "../../safe-action";++// Base schema for all resource types+const baseResourceSchema = z.object({+ workspaceId: z.string(),+ programId: z.string(),+ name: z.string().min(1, "Name is required"),+});++// Schema for file-based resources (logos and files)+const fileResourceSchema = baseResourceSchema.extend({+ resourceType: z.enum(["logo", "file"]),+ file: z.string(), // Base64 encoded file+});++// Schema for color resources+const colorResourceSchema = baseResourceSchema.extend({+ resourceType: z.literal("color"),+ color: z.string(), // Hex color code+});++// Combined schema that can handle any resource type+const addResourceSchema = z.discriminatedUnion("resourceType", [+ fileResourceSchema,+ colorResourceSchema,+]);++export const addProgramResourceAction = authActionClient+ .schema(addResourceSchema)+ .action(async ({ ctx, parsedInput }) => {+ const { workspace } = ctx;+ const { programId, name, resourceType } = 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");+ }++ // Get current resources or initialize empty structure+ const currentResources = (program.resources as any) || {+ logos: [],+ colors: [],+ files: [],+ };++ // Create a copy of the current resources to update+ const updatedResources = { ...currentResources };++ // Handle different resource types+ if (resourceType === "logo" || resourceType === "file") {+ const { file } = parsedInput;++ // Upload the file to storage+ const fileKey = `programs/${programId}/${resourceType}s/${nanoid(7)}`;+ const uploadResult = await storage.upload(fileKey, file);++ if (!uploadResult || !uploadResult.url) {+ throw new Error(`Failed to upload ${resourceType}`);+ }++ // Extract file size from base64 string+ const base64Data = file.replace(/^data:.+;base64,/, "");+ const fileSize = Math.ceil((base64Data.length * 3) / 4);++ // Create the new resource object using the schema+ const newResource = programResourceFileSchema.parse({+ id: nanoid(10),+ name,+ size: fileSize,+ url: uploadResult.url,+ });++ // Update the appropriate array in the resources object+ const resourceKey = resourceType === "logo" ? "logos" : "files";+ updatedResources[resourceKey] = [+ ...(updatedResources[resourceKey] || []),+ newResource,+ ];++ // Update the program with the new resources+ await prisma.program.update({+ where: {+ id: programId,+ },+ data: {+ resources: updatedResources,+ },+ });++ return {+ success: true,+ resource: newResource,+ };+ } else if (resourceType === "color") {+ const { color } = parsedInput;++ // Create the new color resource using the schema+ const newResource = programResourceColorSchema.parse({+ id: nanoid(10),+ name,+ color,+ });++ // Update the colors array in the resources object+ updatedResources.colors = [+ ...(updatedResources.colors || []),+ newResource,+ ];++ // Update the program with the new resources+ await prisma.program.update({+ where: {+ id: programId,+ },+ data: {+ resources: updatedResources,+ },+ });++ return {+ success: true,+ resource: newResource,+ };+ }++ throw new Error("Invalid resource type");+ });diff --git a/packages/utils/src/functions/format-file-size.ts b/packages/utils/src/functions/format-file-size.tsindex bfb54bc1df..1abf1bf2b5 100644--- a/packages/utils/src/functions/format-file-size.ts+++ b/packages/utils/src/functions/format-file-size.ts@@ -1,8 +1,17 @@-export function formatFileSize(bytes: number) {- var i = bytes == 0 ? 0 : Math.floor(Math.log(bytes) / Math.log(1024));+/**+ * Formats a file size in bytes to a human-readable string (KB, MB, GB)+ * @param bytes File size in bytes+ * @param decimals Number of decimal places to show+ * @returns Formatted file size string+ */+export function formatFileSize(bytes: number, decimals: number = 2): string {+ if (bytes === 0) return "0 Bytes";++ const k = 1024;+ const sizes = ["B", "KB", "MB", "GB", "TB", "PB", "EB", "ZB", "YB"];+ const i = Math.floor(Math.log(bytes) / Math.log(k));+return (- +(bytes / Math.pow(1024, i)).toFixed(2) * 1 +- " " +- ["B", "KB", "MB", "GB", "TB"][i]+ parseFloat((bytes / Math.pow(k, i)).toFixed(decimals)) + " " + sizes[i]);}