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.

Application form image upload (#3392)

Kiran K3f7f1e6fcba7
diff --git a/apps/web/app/app.dub.co/(dashboard)/[slug]/(ee)/program/resources/program-brand-assets/add-color-modal.tsx b/apps/web/app/app.dub.co/(dashboard)/[slug]/(ee)/program/resources/program-brand-assets/add-color-modal.tsx
index 5fb0a277f6..e8fafb51fb 100644
--- a/apps/web/app/app.dub.co/(dashboard)/[slug]/(ee)/program/resources/program-brand-assets/add-color-modal.tsx
+++ b/apps/web/app/app.dub.co/(dashboard)/[slug]/(ee)/program/resources/program-brand-assets/add-color-modal.tsx
@@ -108,23 +108,26 @@ function ColorModalInner({
},
});
- const { executeAsync: executeUpdate } = useAction(updateProgramResourceAction, {
- onSuccess: () => {
- mutate();
- setShowColorModal(false);
- toast.success("Color updated successfully!");
- },
- onError({ error }) {
- if (error.serverError) {
- setError("root.serverError", {
- message: error.serverError,
- });
- toast.error(error.serverError);
- } else {
- toast.error("Failed to update color");
- }
+ const { executeAsync: executeUpdate } = useAction(
+ updateProgramResourceAction,
+ {
+ onSuccess: () => {
+ mutate();
+ setShowColorModal(false);
+ toast.success("Color updated successfully!");
+ },
+ onError({ error }) {
+ if (error.serverError) {
+ setError("root.serverError", {
+ message: error.serverError,
+ });
+ toast.error(error.serverError);
+ } else {
+ toast.error("Failed to update color");
+ }
+ },
},
- });
+ );
return (
<>
diff --git a/apps/web/app/app.dub.co/(dashboard)/[slug]/(ee)/program/resources/program-brand-assets/add-file-modal.tsx b/apps/web/app/app.dub.co/(dashboard)/[slug]/(ee)/program/resources/program-brand-assets/add-file-modal.tsx
index 77ace6da69..b9efcf4556 100644
--- a/apps/web/app/app.dub.co/(dashboard)/[slug]/(ee)/program/resources/program-brand-assets/add-file-modal.tsx
+++ b/apps/web/app/app.dub.co/(dashboard)/[slug]/(ee)/program/resources/program-brand-assets/add-file-modal.tsx
@@ -89,23 +89,26 @@ function FileModalInner({
},
});
- const { executeAsync: executeUpdate } = useAction(updateProgramResourceAction, {
- onSuccess: () => {
- mutate();
- setShowFileModal(false);
- toast.success("File updated successfully!");
- },
- onError({ error }) {
- if (error.serverError) {
- setError("root.serverError", {
- message: error.serverError,
- });
- toast.error(error.serverError);
- } else {
- toast.error("Failed to update file");
- }
+ const { executeAsync: executeUpdate } = useAction(
+ updateProgramResourceAction,
+ {
+ onSuccess: () => {
+ mutate();
+ setShowFileModal(false);
+ toast.success("File updated successfully!");
+ },
+ onError({ error }) {
+ if (error.serverError) {
+ setError("root.serverError", {
+ message: error.serverError,
+ });
+ toast.error(error.serverError);
+ } else {
+ toast.error("Failed to update file");
+ }
+ },
},
- });
+ );
return (
<>
diff --git a/apps/web/app/app.dub.co/(dashboard)/[slug]/(ee)/program/resources/program-brand-assets/add-link-modal.tsx b/apps/web/app/app.dub.co/(dashboard)/[slug]/(ee)/program/resources/program-brand-assets/add-link-modal.tsx
index 8f581d8115..9c7b88f6d1 100644
--- a/apps/web/app/app.dub.co/(dashboard)/[slug]/(ee)/program/resources/program-brand-assets/add-link-modal.tsx
+++ b/apps/web/app/app.dub.co/(dashboard)/[slug]/(ee)/program/resources/program-brand-assets/add-link-modal.tsx
@@ -81,23 +81,26 @@ function LinkModalInner({
},
});
- const { executeAsync: executeUpdate } = useAction(updateProgramResourceAction, {
- onSuccess: () => {
- mutate();
- setShowLinkModal(false);
- toast.success("Link updated successfully!");
- },
- onError({ error }) {
- if (error.serverError) {
- setError("root.serverError", {
- message: error.serverError,
- });
- toast.error(error.serverError);
- } else {
- toast.error("Failed to update link");
- }
+ const { executeAsync: executeUpdate } = useAction(
+ updateProgramResourceAction,
+ {
+ onSuccess: () => {
+ mutate();
+ setShowLinkModal(false);
+ toast.success("Link updated successfully!");
+ },
+ onError({ error }) {
+ if (error.serverError) {
+ setError("root.serverError", {
+ message: error.serverError,
+ });
+ toast.error(error.serverError);
+ } else {
+ toast.error("Failed to update link");
+ }
+ },
},
- });
+ );
return (
<>
diff --git a/apps/web/app/app.dub.co/(dashboard)/[slug]/(ee)/program/resources/program-brand-assets/add-logo-modal.tsx b/apps/web/app/app.dub.co/(dashboard)/[slug]/(ee)/program/resources/program-brand-assets/add-logo-modal.tsx
index 7c6811f706..cc923ac725 100644
--- a/apps/web/app/app.dub.co/(dashboard)/[slug]/(ee)/program/resources/program-brand-assets/add-logo-modal.tsx
+++ b/apps/web/app/app.dub.co/(dashboard)/[slug]/(ee)/program/resources/program-brand-assets/add-logo-modal.tsx
@@ -89,23 +89,26 @@ function LogoModalInner({
},
});
- const { executeAsync: executeUpdate } = useAction(updateProgramResourceAction, {
- onSuccess: () => {
- mutate();
- setShowLogoModal(false);
- toast.success("Logo updated successfully!");
- },
- onError({ error }) {
- if (error.serverError) {
- setError("root.serverError", {
- message: error.serverError,
- });
- toast.error(error.serverError);
- } else {
- toast.error("Failed to update logo");
- }
+ const { executeAsync: executeUpdate } = useAction(
+ updateProgramResourceAction,
+ {
+ onSuccess: () => {
+ mutate();
+ setShowLogoModal(false);
+ toast.success("Logo updated successfully!");
+ },
+ onError({ error }) {
+ if (error.serverError) {
+ setError("root.serverError", {
+ message: error.serverError,
+ });
+ toast.error(error.serverError);
+ } else {
+ toast.error("Failed to update logo");
+ }
+ },
},
- });
+ );
return (
<>
@@ -154,7 +157,9 @@ function LogoModalInner({
<Controller
control={control}
name="file"
- rules={{ required: !isEditing ? "Logo file is required" : false }}
+ rules={{
+ required: !isEditing ? "Logo file is required" : false,
+ }}
render={({ field }) => (
<FileUpload
accept="programResourceImages"
diff --git a/apps/web/lib/actions/partners/upload-program-application-image.ts b/apps/web/lib/actions/partners/upload-program-application-image.ts
new file mode 100644
index 0000000000..dfb7d24394
--- /dev/null
+++ b/apps/web/lib/actions/partners/upload-program-application-image.ts
@@ -0,0 +1,54 @@
+"use server";
+
+import { getIP } from "@/lib/api/utils/get-ip";
+import { storage } from "@/lib/storage";
+import { ratelimit } from "@/lib/upstash";
+import { RATE_LIMITS } from "@/lib/upstash/ratelimit-policy";
+import { prisma } from "@dub/prisma";
+import { nanoid, R2_URL } from "@dub/utils";
+import * as z from "zod/v4";
+import { actionClient } from "../safe-action";
+
+const inputSchema = z.object({
+ programSlug: z.string().trim().toLowerCase().min(1),
+});
+
+const rateLimitPolicy = RATE_LIMITS.programImageUpload;
+
+export const uploadProgramApplicationImageAction = actionClient
+ .inputSchema(inputSchema)
+ .action(async ({ parsedInput }) => {
+ const { programSlug } = parsedInput;
+
+ const ipAddress = await getIP();
+
+ const { success } = await ratelimit(
+ rateLimitPolicy.attempts,
+ rateLimitPolicy.window,
+ ).limit(`${rateLimitPolicy.keyPrefix}:${ipAddress}`);
+
+ if (!success) {
+ throw new Error(
+ "You've reached the maximum number of attempts to upload images for this application. Please try again later.",
+ );
+ }
+
+ const program = await prisma.program.findUniqueOrThrow({
+ where: {
+ slug: programSlug,
+ },
+ select: {
+ id: true,
+ },
+ });
+
+ const key = `programs/${program.id}/applications/${nanoid(10)}`;
+ const signedUrl = await storage.getSignedUploadUrl({
+ key,
+ });
+
+ return {
+ signedUrl,
+ destinationUrl: `${R2_URL}/${key}`,
+ };
+ });
diff --git a/apps/web/lib/constants/program.ts b/apps/web/lib/constants/program.ts
index b370f2f317..075a7ccbd3 100644
--- a/apps/web/lib/constants/program.ts
+++ b/apps/web/lib/constants/program.ts
@@ -28,3 +28,13 @@ export const PROGRAM_IMPORT_SOURCES = [
helpUrl: "https://dub.co/help/article/migrating-from-firstpromoter",
},
] as const;
+
+export const PROGRAM_APPLICATION_IMAGE_MAX_FILE_SIZE_MB = 5;
+
+export const PROGRAM_APPLICATION_IMAGE_ALLOWED_TYPES = [
+ "image/jpeg",
+ "image/png",
+ "image/webp",
+] as const;
+
+export const PROGRAM_APPLICATION_IMAGE_ALLOWED_TYPES_LABEL = "JPG, PNG, WebP";
diff --git a/apps/web/lib/partners/format-application-form-data.ts b/apps/web/lib/partners/format-application-form-data.ts
index 40757a4442..1807b874ad 100644
--- a/apps/web/lib/partners/format-application-form-data.ts
+++ b/apps/web/lib/partners/format-application-form-data.ts
@@ -4,6 +4,7 @@ import { ProgramApplication } from "@dub/prisma/client";
export interface FormDataKeyValue {
title: string;
value: string;
+ images?: string[];
}
export const formatApplicationFormData = (
@@ -45,6 +46,12 @@ export const formatApplicationFormData = (
title: field.label,
value,
};
+ case "image-upload":
+ return {
+ title: field.label,
+ value: "",
+ images: Array.isArray(field.value) ? field.value : [],
+ };
case "website-and-socials":
return null;
}
diff --git a/apps/web/lib/upstash/ratelimit-policy.ts b/apps/web/lib/upstash/ratelimit-policy.ts
new file mode 100644
index 0000000000..d3a1382796
--- /dev/null
+++ b/apps/web/lib/upstash/ratelimit-policy.ts
@@ -0,0 +1,10 @@
+export const RATE_LIMITS = {
+ programImageUpload: {
+ attempts: 10,
+ window: "24 h",
+ keyPrefix: "rl:program:application:image:upload",
+ },
+
+ // TODO:
+ // Centralize rate limiting policies
+} as const;
diff --git a/apps/web/lib/zod/schemas/program-application-form.ts b/apps/web/lib/zod/schemas/program-application-form.ts
index 8551dcd536..a4f071d40e 100644
--- a/apps/web/lib/zod/schemas/program-application-form.ts
+++ b/apps/web/lib/zod/schemas/program-application-form.ts
@@ -1,4 +1,5 @@
import * as z from "zod/v4";
+import { storedR2ImageUrlSchema } from "./misc";
// Common schema for all fields
export const programApplicationFormFieldCommonSchema = z.object({
@@ -117,6 +118,20 @@ export const programApplicationFormWebsiteAndSocialsFieldWithValueSchema =
data: z.array(programApplicationFormSiteSchemaWithValue),
});
+// Image upload field
+export const programApplicationFormImageUploadFieldSchema =
+ programApplicationFormFieldCommonSchema.extend({
+ type: z.literal("image-upload"),
+ data: z.object({
+ maxImages: z.number(),
+ }),
+ });
+
+export const programApplicationFormImageUploadFieldWithValueSchema =
+ programApplicationFormImageUploadFieldSchema.extend({
+ value: z.array(storedR2ImageUrlSchema),
+ });
+
// All fields
export const programApplicationFormFieldSchema = z.discriminatedUnion("type", [
programApplicationFormShortTextFieldSchema,
@@ -124,6 +139,7 @@ export const programApplicationFormFieldSchema = z.discriminatedUnion("type", [
programApplicationFormSelectFieldSchema,
programApplicationFormMultipleChoiceFieldSchema,
programApplicationFormWebsiteAndSocialsFieldSchema,
+ programApplicationFormImageUploadFieldSchema,
]);
export const programApplicationFormFieldWithValuesSchema = z.discriminatedUnion(
@@ -134,6 +150,7 @@ export const programApplicationFormFieldWithValuesSchema = z.discriminatedUnion(
programApplicationFormSelectFieldWithValueSchema,
programApplicationFormMultipleChoiceFieldWithValueSchema,
programApplicationFormWebsiteAndSocialsFieldWithValueSchema,
+ programApplicationFormImageUploadFieldWithValueSchema,
],
);
diff --git a/apps/web/ui/partners/groups/design/application-form/fields/image-upload-field.tsx b/apps/web/ui/partners/groups/design/application-form/fields/image-upload-field.tsx
new file mode 100644
index 0000000000..bf336f783e
--- /dev/null
+++ b/apps/web/ui/partners/groups/design/application-form/fields/image-upload-field.tsx
@@ -0,0 +1,374 @@
+"use client";
+
+import { parseActionError } from "@/lib/actions/parse-action-errors";
+import { uploadProgramApplicationImageAction } from "@/lib/actions/partners/upload-program-application-image";
+import {
+ PROGRAM_APPLICATION_IMAGE_ALLOWED_TYPES,
+ PROGRAM_APPLICATION_IMAGE_ALLOWED_TYPES_LABEL,
+ PROGRAM_APPLICATION_IMAGE_MAX_FILE_SIZE_MB,
+} from "@/lib/constants/program";
+import { programApplicationFormImageUploadFieldSchema } from "@/lib/zod/schemas/program-application-form";
+import { X } from "@/ui/shared/icons";
+import { FileUpload, LoadingSpinner } from "@dub/ui";
+import { cn } from "@dub/utils";
+import { useAction } from "next-safe-action/hooks";
+import { useParams } from "next/navigation";
+import { useEffect, useRef, useState } from "react";
+import { Controller, useFormContext } from "react-hook-form";
+import { toast } from "sonner";
+import { v4 as uuid } from "uuid";
+import * as z from "zod/v4";
+import { FormControl } from "./form-control";
+
+type ImageUploadFieldData = z.infer<
+ typeof programApplicationFormImageUploadFieldSchema
+>;
+
+interface FileInput {
+ id: string;
+ file?: File;
+ url?: string;
+ uploading: boolean;
+}
+
+function ImageUploadFieldContent({
+ field,
+ preview,
+ programSlug,
+ controllerField,
+ maxImages,
+ error,
+ uploadFile,
+ onStatusChange,
+}: {
+ field: ImageUploadFieldData;
+ preview?: boolean;
+ programSlug: string;
+ controllerField: { value: any; onChange: (value: any) => void };
+ maxImages: number;
+ error: boolean;
+ uploadFile: (params: { programSlug: string }) => Promise<any>;
+ onStatusChange?: (loading: boolean) => void;
+}) {
+ const currentValue = controllerField.value || [];
+
+ // Track if we're updating from an internal change to prevent circular updates
+ const isInternalUpdateRef = useRef(false);
+
+ // Initialize files state from form value
+ const [files, setFiles] = useState<FileInput[]>(() => {
+ if (Array.isArray(currentValue) && currentValue.length > 0) {
+ return currentValue.map((url: string) => ({
+ id: uuid(),
+ url,
+ uploading: false,
+ file: undefined,
+ }));
+ }
+ return [];
+ });
+
+ // Sync files state with form value when it changes externally
+ useEffect(() => {
+ // Skip if this is an internal update
+ if (isInternalUpdateRef.current) {
+ isInternalUpdateRef.current = false;
+ return;
+ }
+
+ if (Array.isArray(currentValue)) {
+ const currentUrls = currentValue.filter(Boolean);
+ const fileUrls = files
+ .filter((f) => f.url && !f.uploading)
+ .map((f) => f.url!)
+ .filter(Boolean);
+
+ // Only update if URLs differ (compare as sets to handle reordering)
+ const currentUrlsSet = new Set(currentUrls);
+ const fileUrlsSet = new Set(fileUrls);
+
+ if (
+ currentUrls.length !== fileUrls.length ||
+ currentUrls.some((url) => !fileUrlsSet.has(url)) ||
+ fileUrls.some((url) => !currentUrlsSet.has(url))
+ ) {
+ // Preserve uploading files when syncing
+ const uploadingFiles = files.filter((f) => f.uploading);
+ const syncedFiles = currentUrls.map((url: string) => ({
+ id: uuid(),
+ url,
+ uploading: false,
+ file: undefined,
+ }));
+ setFiles([...syncedFiles, ...uploadingFiles]);
+ }
+ }
+ // eslint-disable-next-line react-hooks/exhaustive-deps
+ }, [currentValue]);
+
+ // Update form value when files change
+ useEffect(() => {
+ const urls = files.filter((f) => f.url && !f.uploading).map((f) => f.url!);
+
+ // Compare with current form value to avoid unnecessary updates
+ // Read currentValue directly from controllerField to avoid stale closure
+ const formValue = controllerField.value || [];
+ const currentUrls = Array.isArray(formValue)
+ ? formValue.filter(Boolean)
+ : [];
+
+ // Compare as sets to handle reordering
+ const urlsSet = new Set(urls);
+ const currentUrlsSet = new Set(currentUrls);
+
+ // Only update if URLs actually changed
+ if (
+ urls.length !== currentUrls.length ||
+ urls.some((url) => !currentUrlsSet.has(url)) ||
+ currentUrls.some((url) => !urlsSet.has(url))
+ ) {
+ isInternalUpdateRef.current = true;
+ controllerField.onChange(urls);
+ }
+ }, [files, controllerField]);
+
+ const handleUpload = async (file: File) => {
+ if (!programSlug) {
+ toast.error(
+ "Unable to upload image. Please refresh the page and try again.",
+ );
+ return;
+ }
+
+ // Validate file type
+ if (!PROGRAM_APPLICATION_IMAGE_ALLOWED_TYPES.includes(file.type as any)) {
+ toast.error(
+ `Invalid file type. Allowed types: ${PROGRAM_APPLICATION_IMAGE_ALLOWED_TYPES_LABEL}`,
+ );
+ return;
+ }
+
+ // Validate file size
+ if (file.size > PROGRAM_APPLICATION_IMAGE_MAX_FILE_SIZE_MB * 1024 * 1024) {
+ toast.error(
+ `File size exceeds maximum of ${PROGRAM_APPLICATION_IMAGE_MAX_FILE_SIZE_MB}MB`,
+ );
+ return;
+ }
+
+ // Check max images limit
+ const currentUploadedCount = files.filter(
+ (f) => f.url && !f.uploading,
+ ).length;
+ if (currentUploadedCount >= maxImages) {
+ toast.error(
+ `Maximum of ${maxImages} image${maxImages === 1 ? "" : "s"} allowed`,
+ );
+ return;
+ }
+
+ const newFile: FileInput = { id: uuid(), file, uploading: true };
+ setFiles((prev) => [...prev, newFile]);
+
+ try {
+ const result = await uploadFile({
+ programSlug,
+ });
+
+ if (!result?.data) {
+ toast.error("Failed to upload image. Please try again.");
+ setFiles((prev) => prev.filter((f) => f.id !== newFile.id));
+ return;
+ }
+
+ const { signedUrl, destinationUrl } = result.data;
+
+ const uploadResponse = await fetch(signedUrl, {
+ method: "PUT",
+ body: file,
+ headers: {
+ "Content-Type": file.type,
+ "Content-Length": file.size.toString(),
+ },
+ });
+
+ if (!uploadResponse.ok) {
+ const result = await uploadResponse.json();
+ throw new Error(
+ result.error?.message || "Failed to upload image to storage",
+ );
+ }
+
+ toast.success(`${file.name} uploaded!`);
+ setFiles((prev) =>
+ prev.map((f) =>
+ f.id === newFile.id
+ ? { ...f, uploading: false, url: destinationUrl }
+ : f,
+ ),
+ );
+ } catch (error) {
+ toast.error(
+ error instanceof Error
+ ? error.message
+ : "Failed to upload image. Please try again.",
+ );
+ setFiles((prev) => prev.filter((f) => f.id !== newFile.id));
+ }
+ };
+
+ const fileUploading = files.some(({ uploading }) => uploading);
+
+ // Track the callback in a ref to avoid infinite loops from changing function references
+ const onStatusChangeRef = useRef(onStatusChange);
+ useEffect(() => {
+ onStatusChangeRef.current = onStatusChange;
+ }, [onStatusChange]);
+
+ // Notify parent when async state changes
+ useEffect(() => {
+ onStatusChangeRef.current?.(fileUploading);
+ }, [fileUploading]);
+
+ return (
+ <div className="mt-2">
+ <div
+ className={cn(
+ "flex h-12 items-center gap-2 transition-[height]",
+ files.length === 0 && "h-24",
+ )}
+ >
+ {files.map((file, idx) => (
+ <div
+ key={file.id}
+ className="border-border-subtle group relative flex aspect-square h-full items-center justify-center rounded-md border bg-white"
+ >
+ {file.uploading ? (
+ <LoadingSpinner className="size-4" />
+ ) : file.url ? (
+ <div className="relative size-full overflow-hidden rounded-md">
+ <img
+ src={file.url}
+ alt={`Upload ${idx + 1}`}
+ className="size-full object-cover"
+ />
+ </div>
+ ) : null}
+ <span className="sr-only">
+ {file.file?.name || `File ${idx + 1}`}
+ </span>
+ {!preview && (
+ <button
+ type="button"
+ className={cn(
+ "absolute right-0 top-0 flex size-[1.125rem] -translate-y-1/2 translate-x-1/2 items-center justify-center",
+ "rounded-full border border-neutral-200 bg-white shadow-sm hover:bg-neutral-50 active:scale-95",
+ "scale-50 opacity-0 transition-[background-color,transform,opacity] group-hover:scale-100 group-hover:opacity-100",
+ )}
+ onClick={() => {
+ setFiles((prev) => prev.filter((s) => s.id !== file.id));
+ }}
+ >
+ <X className="size-2.5 text-neutral-400" />
+ </button>
+ )}
+ </div>
+ ))}
+
+ <FileUpload
+ accept="images"
+ className={cn(
+ "border-border-subtle h-full w-auto rounded-md border",
+ files.length > 0 ? "aspect-square" : "aspect-[unset] w-full",
+ error && "border-red-400",
+ )}
+ iconClassName="size-5 shrink-0"
+ variant="plain"
+ content={
+ files.length > 0
+ ? null
+ : `${PROGRAM_APPLICATION_IMAGE_ALLOWED_TYPES_LABEL}, max size of ${PROGRAM_APPLICATION_IMAGE_MAX_FILE_SIZE_MB}MB`
+ }
+ onChange={
+ preview ? undefined : async ({ file }) => await handleUpload(file)
+ }
+ disabled={preview || files.length >= maxImages || fileUploading}
+ maxFileSizeMB={PROGRAM_APPLICATION_IMAGE_MAX_FILE_SIZE_MB}
+ />
+ </div>
+ </div>
+ );
+}
+
+export function ImageUploadField({
+ keyPath: keyPathProp,
+ field,
+ preview,
+ onStatusChange,
+}: {
+ keyPath?: string;
+ field: ImageUploadFieldData;
+ preview?: boolean;
+ onStatusChange?: (loading: boolean) => void;
+}) {
+ const { programSlug } = useParams<{ programSlug: string }>();
+ const { getFieldState, control } = useFormContext<any>();
+
+ const keyPath = keyPathProp ? `${keyPathProp}.value` : "value";
+ const state = getFieldState(keyPath);
+
+ const { executeAsync: uploadFile } = useAction(
+ uploadProgramApplicationImageAction,
+ {
+ onError({ error }) {
+ toast.error(parseActionError(error, "Failed to upload image."));
+ onStatusChange?.(false);
+ },
+ },
+ );
+
+ const maxImages = field.data.maxImages || 1;
+ const error = !!state.error;
+
+ return (
+ <FormControl
+ label={field.label}
+ required={field.required}
+ error={state.error?.message}
+ >
+ <Controller
+ control={control}
+ name={keyPath}
+ rules={
+ preview
+ ? {}
+ : {
+ validate: (val: any) => {
+ if (field.required) {
+ const imageUrls = Array.isArray(val)
+ ? val.filter(Boolean)
+ : [];
+ if (imageUrls.length === 0) {
+ return `${field.label} is required`;
+ }
+ }
+ return true;
+ },
+ }
+ }
+ render={({ field: controllerField }) => (
+ <ImageUploadFieldContent
+ field={field}
+ preview={preview}
+ programSlug={programSlug || ""}
+ controllerField={controllerField}
+ maxImages={maxImages}
+ error={error}
+ uploadFile={uploadFile}
+ onStatusChange={onStatusChange}
+ />
+ )}
+ />
+ </FormControl>
+ );
+}
diff --git a/apps/web/ui/partners/groups/design/application-form/fields/index.tsx b/apps/web/ui/partners/groups/design/application-form/fields/index.tsx
index ab241625b4..9aac2dbde3 100644
--- a/apps/web/ui/partners/groups/design/application-form/fields/index.tsx
+++ b/apps/web/ui/partners/groups/design/application-form/fields/index.tsx
@@ -1,5 +1,6 @@
import { programApplicationFormFieldSchema } from "@/lib/zod/schemas/program-application-form";
import * as z from "zod/v4";
+import { ImageUploadField } from "./image-upload-field";
import { LongTextField } from "./long-text-field";
import { MultipleChoiceField } from "./multiple-choice-field";
import { SelectField } from "./select-field";
@@ -15,16 +16,19 @@ const FIELD_COMPONENTS: Record<
"long-text": LongTextField,
select: SelectField,
"website-and-socials": WebsiteAndSocialsField,
+ "image-upload": ImageUploadField,
};
export const ProgramApplicationFormField = ({
field,
keyPath,
preview,
+ onStatusChange,
}: {
field: z.infer<typeof programApplicationFormFieldSchema>;
keyPath?: string;
preview?: boolean;
+ onStatusChange?: (loading: boolean) => void;
}) => {
const Component = FIELD_COMPONENTS[field.type];
@@ -32,5 +36,12 @@ export const ProgramApplicationFormField = ({
return null;
}
- return <Component field={field} keyPath={keyPath} preview={preview} />;
+ return (
+ <Component
+ field={field}
+ keyPath={keyPath}
+ preview={preview}
+ onStatusChange={onStatusChange}
+ />
+ );
};
diff --git a/apps/web/ui/partners/groups/design/application-form/form-data-for-application-form-data.ts b/apps/web/ui/partners/groups/design/application-form/form-data-for-application-form-data.ts
index d44d0b6b9e..4c83c2bc8a 100644
--- a/apps/web/ui/partners/groups/design/application-form/form-data-for-application-form-data.ts
+++ b/apps/web/ui/partners/groups/design/application-form/form-data-for-application-form-data.ts
@@ -1,6 +1,7 @@
import { ProgramApplicationFormDataWithValues } from "@/lib/types";
import {
programApplicationFormFieldSchema,
+ programApplicationFormImageUploadFieldWithValueSchema,
programApplicationFormLongTextFieldWithValueSchema,
programApplicationFormMultipleChoiceFieldSchema,
programApplicationFormMultipleChoiceFieldWithValueSchema,
@@ -45,6 +46,13 @@ export const formDataForApplicationFormData = (
} as z.infer<
typeof programApplicationFormMultipleChoiceFieldWithValueSchema
>;
+ case "image-upload":
+ return {
+ ...field,
+ value: [],
+ } as z.infer<
+ typeof programApplicationFormImageUploadFieldWithValueSchema
+ >;
case "website-and-socials":
return {
...field,
@@ -55,6 +63,8 @@ export const formDataForApplicationFormData = (
} as z.infer<
typeof programApplicationFormWebsiteAndSocialsFieldWithValueSchema
>;
+ default:
+ return field;
}
}),
} as any;
diff --git a/apps/web/ui/partners/groups/design/application-form/modals/add-field-modal.tsx b/apps/web/ui/partners/groups/design/application-form/modals/add-field-modal.tsx
index 5f92afbf0c..dfd591e792 100644
--- a/apps/web/ui/partners/groups/design/application-form/modals/add-field-modal.tsx
+++ b/apps/web/ui/partners/groups/design/application-form/modals/add-field-modal.tsx
@@ -7,6 +7,10 @@ import { Dispatch, Fragment, ReactNode, SetStateAction, useState } from "react";
import { useWatch } from "react-hook-form";
import * as z from "zod/v4";
import { useBrandingFormContext } from "../../branding-form";
+import {
+ ImageUploadFieldModal,
+ ImageUploadFieldThumbnail,
+} from "./image-upload-field-modal";
import {
LongTextFieldModal,
LongTextFieldThumbnail,
@@ -47,6 +51,7 @@ export const DESIGNER_FIELDS: ({
label: string;
description: string;
modal: React.ComponentType<any>;
+ fullWidth?: boolean;
} & (
| { icon: Icon; thumbnail?: never }
| { thumbnail: ReactNode; icon?: never }
@@ -79,12 +84,21 @@ export const DESIGNER_FIELDS: ({
modal: MultipleChoiceFieldModal,
thumbnail: <MultipleChoiceFieldThumbnail />,
},
+ {
+ id: "image-upload",
+ label: "Image Upload",
+ description: "Let applicants upload images",
+ modal: ImageUploadFieldModal,
+ thumbnail: <ImageUploadFieldThumbnail />,
+ fullWidth: true,
+ },
{
id: "website-and-socials",
label: "Website and socials",
description: "Collect website and social media links",
modal: WebsiteAndSocialsFieldModal,
icon: WebsiteAndSocialsFieldIcon,
+ fullWidth: true,
},
];
@@ -145,8 +159,9 @@ function AddFieldModalInner({
type="button"
onClick={() => setModalState(field.id)}
className={cn(
- "flex flex-col gap-4 rounded-md border border-transparent bg-neutral-100 p-4 text-left outline-none ring-black/10 transition-all duration-150 hover:border-neutral-800 hover:ring focus-visible:border-neutral-800",
- field.icon && "col-span-2 flex-row items-center",
+ "flex rounded-md border border-transparent bg-neutral-100 p-4 text-left outline-none ring-black/10 transition-all duration-150 hover:border-neutral-800 hover:ring focus-visible:border-neutral-800",
+ field.fullWidth && "col-span-2 flex-row items-center gap-4",
+ !field.fullWidth && "flex-col gap-4",
)}
>
{field.icon ? (
@@ -154,7 +169,12 @@ function AddFieldModalInner({
<field.icon className="size-5 text-neutral-600" />
</div>
) : (
- <div className="flex h-24 items-center justify-center overflow-hidden rounded-md border border-neutral-200 bg-white">
+ <div
+ className={cn(
+ "flex items-center justify-center overflow-hidden rounded-md border border-neutral-200 bg-white",
+ field.fullWidth ? "size-12" : "h-24 w-full",
+ )}
+ >
{field.thumbnail}
</div>
)}
diff --git a/apps/web/ui/partners/groups/design/application-form/modals/image-upload-field-modal.tsx b/apps/web/ui/partners/groups/design/application-form/modals/image-upload-field-modal.tsx
new file mode 100644
index 0000000000..fea9c3c31f
--- /dev/null
+++ b/apps/web/ui/partners/groups/design/application-form/modals/image-upload-field-modal.tsx
@@ -0,0 +1,285 @@
+"use client";
+
+import { programApplicationFormImageUploadFieldSchema } from "@/lib/zod/schemas/program-application-form";
+import { Button, Modal, Switch, useMediaQuery } from "@dub/ui";
+import { cn } from "@dub/utils";
+import { motion } from "motion/react";
+import { Dispatch, SetStateAction, useId } from "react";
+import { Controller, useForm } from "react-hook-form";
+import { v4 as uuid } from "uuid";
+import * as z from "zod/v4";
+
+const MIN_MAX_IMAGES = 2;
+const MAX_MAX_IMAGES = 20;
+const DEFAULT_MAX_IMAGES = 5;
+
+type ImageUploadFieldData = z.infer<
+ typeof programApplicationFormImageUploadFieldSchema
+>;
+
+type ImageUploadFieldModalProps = {
+ showModal: boolean;
+ setShowModal: Dispatch<SetStateAction<boolean>>;
+ defaultValues?: Partial<ImageUploadFieldData>;
+ onSubmit: (data: ImageUploadFieldData) => void;
+};
+
+export function ImageUploadFieldModal(props: ImageUploadFieldModalProps) {
+ return (
+ <Modal showModal={props.showModal} setShowModal={props.setShowModal}>
+ <ImageUploadFieldModalInner {...props} />
+ </Modal>
+ );
+}
+
+type FormData = Omit<ImageUploadFieldData, "data"> & {
+ data: ImageUploadFieldData["data"] & {
+ allowMultiple: boolean;
+ };
+};
+
+const imageUploadFieldDataFromFormData = (
+ formData: FormData,
+): ImageUploadFieldData => {
+ const { data, ...rest } = formData;
+ const { allowMultiple, maxImages, ...dataRest } = data;
+ return {
+ ...rest,
+ data: {
+ ...dataRest,
+ maxImages: allowMultiple ? maxImages : 1,
+ },
+ };
+};
+
+const formDataForImageUploadFieldData = (
+ imageUploadFieldData?: Partial<ImageUploadFieldData>,
+): FormData => {
+ const maxImages = imageUploadFieldData?.data?.maxImages ?? 1;
+ const allowMultiple = maxImages > 1;
+
+ return {
+ id: imageUploadFieldData?.id ?? uuid(),
+ type: imageUploadFieldData?.type ?? "image-upload",
+ label: imageUploadFieldData?.label ?? "",
+ required: imageUploadFieldData?.required ?? false,
+ data: {
+ allowMultiple,
+ maxImages: allowMultiple ? maxImages : DEFAULT_MAX_IMAGES,
+ },
+ };
+};
+
+function ImageUploadFieldModalInner({
+ setShowModal,
+ onSubmit,
+ defaultValues,
+}: ImageUploadFieldModalProps) {
+ const id = useId();
+ const { isMobile } = useMediaQuery();
+ const {
+ control,
+ handleSubmit,
+ register,
+ watch,
+ formState: { errors },
+ } = useForm<FormData>({
+ defaultValues: formDataForImageUploadFieldData(defaultValues),
+ });
+
+ const allowMultiple = watch("data.allowMultiple");
+
+ return (
+ <>
+ <div className="p-4 pt-3">
+ <h3 className="text-base font-semibold leading-6 text-neutral-800">
+ {defaultValues ? "Edit" : "Add"} image upload
+ </h3>
+ <form
+ className="mt-4 flex flex-col gap-6"
+ onSubmit={(e) => {
+ e.stopPropagation();
+ handleSubmit(async (data) => {
+ setShowModal(false);
+ onSubmit(imageUploadFieldDataFromFormData(data));
+ })(e);
+ }}
+ >
+ {/* Label */}
+ <div>
+ <label
+ htmlFor={`${id}-label`}
+ className="flex items-center gap-2 text-sm font-medium text-neutral-700"
+ >
+ Input label
+ </label>
+ <div className="mt-2 rounded-md shadow-sm">
+ <input
+ id={`${id}-label`}
+ type="text"
+ placeholder=""
+ autoFocus={!isMobile}
+ className={cn(
+ "block w-full rounded-md border-neutral-300 text-neutral-900 placeholder-neutral-400 focus:border-neutral-500 focus:outline-none focus:ring-neutral-500 sm:text-sm",
+ !!errors.label &&
+ "border-red-600 focus:border-red-500 focus:ring-red-600",
+ )}
+ {...register("label", { required: true })}
+ />
+ </div>
+ </div>
+
+ {/* Allow multiple images */}
+ <div className="flex flex-col gap-2">
+ <Controller
+ name="data.allowMultiple"
+ control={control}
+ render={({ field }) => {
+ return (
+ <label
+ className="flex items-center justify-between gap-1.5"
+ htmlFor={`${id}-allow-multiple`}
+ >
+ <span className="text-sm font-medium text-neutral-700">
+ Allow multiple images
+ </span>
+ <Switch
+ id={`${id}-allow-multiple`}
+ checked={field.value}
+ fn={field.onChange}
+ trackDimensions="radix-state-checked:bg-black focus-visible:ring-black/20 w-7 h-4"
+ thumbDimensions="size-3"
+ thumbTranslate="translate-x-3"
+ />
+ </label>
+ );
+ }}
+ />
+
+ <motion.div
+ animate={{
+ height: allowMultiple ? "auto" : 0,
+ overflow: "hidden",
+ }}
+ transition={{
+ duration: 0.15,
+ }}
+ initial={allowMultiple}
+ className="-m-1"
+ >
+ <div className="p-1">
+ <div className="rounded-md shadow-sm">
+ <input
+ id={`${id}-max-images`}
+ type="number"
+ placeholder="Maximum number of images"
+ {...(allowMultiple
+ ? register("data.maxImages", {
+ required: true,
+ min: {
+ value: MIN_MAX_IMAGES,
+ message: `Please enter a number between ${MIN_MAX_IMAGES} and ${MAX_MAX_IMAGES}`,
+ },
+ max: {
+ value: MAX_MAX_IMAGES,
+ message: `Please enter a number between ${MIN_MAX_IMAGES} and ${MAX_MAX_IMAGES}`,
+ },
+ valueAsNumber: true,
+ })
+ : {})}
+ autoFocus={!isMobile}
+ className={cn(
+ "block w-full rounded-md border-neutral-300 text-neutral-900 placeholder-neutral-400 focus:border-neutral-500 focus:outline-none focus:ring-neutral-500 sm:text-sm",
+ !!errors.data?.maxImages &&
+ "border-red-600 focus:border-red-500 focus:ring-red-600",
+ )}
+ />
+ </div>
+ {errors.data?.maxImages?.message && (
+ <div className={cn("ml-1 mt-1 text-xs text-red-500")}>
+ {errors.data.maxImages.message}
+ </div>
+ )}
+ </div>
+ </motion.div>
+ </div>
+
+ {/* Required */}
+ <div>
+ <Controller
+ name="required"
+ control={control}
+ render={({ field }) => (
+ <label
+ className="flex items-center justify-between gap-1.5"
+ htmlFor={`${id}-required`}
+ >
+ <span className="text-sm font-medium text-neutral-700">
+ Required
+ </span>
+ <Switch
+ id={`${id}-required`}
+ checked={field.value}
+ fn={field.onChange}
+ trackDimensions="radix-state-checked:bg-black focus-visible:ring-black/20 w-7 h-4"
+ thumbDimensions="size-3"
+ thumbTranslate="translate-x-3"
+ />
+ </label>
+ )}
+ />
+ </div>
+
+ <div className="flex items-center justify-end gap-2">
+ <Button
+ onClick={() => setShowModal(false)}
+ variant="secondary"
+ text="Cancel"
+ className="h-8 w-fit px-3"
+ />
+ <Button
+ type="submit"
+ variant="primary"
+ text={defaultValues ? "Update" : "Add"}
+ className="h-8 w-fit px-3"
+ />
+ </div>
+ </form>
+ </div>
+ </>
+ );
+}
+
+export function ImageUploadFieldThumbnail() {
+ return (
+ <svg
+ width="48"
+ height="48"
+ viewBox="0 0 48 48"
+ fill="none"
+ xmlns="http://www.w3.org/2000/svg"
+ className="size-full"
+ >
+ <rect x="0.5" y="0.5" width="47" height="47" rx="5.5" fill="white" />
+ <rect x="0.5" y="0.5" width="47" height="47" rx="5.5" stroke="#E5E5E5" />
+ <rect x="6" y="14" width="16" height="20" rx="2" fill="#F5F5F5" />
+ <rect x="6" y="14" width="16" height="20" rx="2" stroke="#E5E5E5" />
+ <circle cx="10" cy="18" r="1.5" fill="#D9D9D9" />
+ <path
+ d="M6 30L10 25L14 30H6Z"
+ fill="#D9D9D9"
+ stroke="#E5E5E5"
+ strokeWidth="0.5"
+ />
+ <rect x="26" y="14" width="16" height="20" rx="2" fill="#F5F5F5" />
+ <rect x="26" y="14" width="16" height="20" rx="2" stroke="#E5E5E5" />
+ <circle cx="30" cy="18" r="1.5" fill="#D9D9D9" />
+ <path
+ d="M26 30L30 25L34 30H26Z"
+ fill="#D9D9D9"
+ stroke="#E5E5E5"
+ strokeWidth="0.5"
+ />
+ </svg>
+ );
+}
diff --git a/apps/web/ui/partners/groups/design/application-form/modals/short-text-field-modal.tsx b/apps/web/ui/partners/groups/design/application-form/modals/short-text-field-modal.tsx
index 154dadd56c..d1c88b4ebb 100644
--- a/apps/web/ui/partners/groups/design/application-form/modals/short-text-field-modal.tsx
+++ b/apps/web/ui/partners/groups/design/application-form/modals/short-text-field-modal.tsx
@@ -81,7 +81,6 @@ function ShortTextFieldModalInner({
control,
handleSubmit,
register,
- unregister,
formState: { errors },
watch,
} = useForm<FormData>({
diff --git a/apps/web/ui/partners/groups/design/application-form/program-application-form.tsx b/apps/web/ui/partners/groups/design/application-form/program-application-form.tsx
index 1729133f47..7b47d565a2 100644
--- a/apps/web/ui/partners/groups/design/application-form/program-application-form.tsx
+++ b/apps/web/ui/partners/groups/design/application-form/program-application-form.tsx
@@ -14,7 +14,7 @@ import { cn } from "@dub/utils";
import { useSession } from "next-auth/react";
import { useAction } from "next-safe-action/hooks";
import { useRouter } from "next/navigation";
-import { useEffect } from "react";
+import { useCallback, useEffect, useState } from "react";
import { Controller, FormProvider, useForm } from "react-hook-form";
import { toast } from "sonner";
import { CountryCombobox } from "../../../country-combobox";
@@ -64,6 +64,24 @@ export function ProgramApplicationForm({
formState: { errors, isSubmitting, isSubmitSuccessful },
} = form;
+ const [fieldStatuses, setFieldStatuses] = useState<Record<string, boolean>>(
+ {},
+ );
+
+ const handleFieldStatusChange = useCallback(
+ (fieldId: string, isLoading: boolean) => {
+ setFieldStatuses((prev) => ({
+ ...prev,
+ [fieldId]: isLoading,
+ }));
+ },
+ [],
+ );
+
+ const hasAnyLoadingStatus = Object.values(fieldStatuses).some(
+ (loading) => loading,
+ );
+
useEffect(() => {
if (preview || !session?.user) return;
@@ -109,7 +127,8 @@ export function ProgramApplicationForm({
},
);
- const isLoading = isSubmitting || isSubmitSuccessful || isPending;
+ const isLoading =
+ isSubmitting || isSubmitSuccessful || isPending || hasAnyLoadingStatus;
return (
<FormProvider {...form}>
@@ -205,6 +224,9 @@ export function ProgramApplicationForm({
key={field.id}
field={field}
keyPath={`formData.fields.${index}`}
+ onStatusChange={(loading) =>
+ handleFieldStatusChange(field.id, loading)
+ }
/>
);
})}
diff --git a/apps/web/ui/partners/partner-application-details.tsx b/apps/web/ui/partners/partner-application-details.tsx
index b291836714..463f0b27f3 100644
--- a/apps/web/ui/partners/partner-application-details.tsx
+++ b/apps/web/ui/partners/partner-application-details.tsx
@@ -35,7 +35,12 @@ export function PartnerApplicationDetails({
<div key={field.title}>
<h4 className="text-content-emphasis font-semibold">{field.title}</h4>
<div className="mt-2">
- {field.value || field.value === "" ? (
+ {field.images && field.images.length > 0 ? (
+ <ApplicationFormImageGrid
+ images={field.images}
+ fieldTitle={field.title}
+ />
+ ) : field.value || field.value === "" ? (
<Linkify
as="p"
options={{
@@ -63,6 +68,39 @@ export function PartnerApplicationDetails({
return <div className="grid grid-cols-1 gap-5 text-sm">{content}</div>;
}
+function ApplicationFormImageGrid({
+ images,
+ fieldTitle,
+}: {
+ images: string[];
+ fieldTitle: string;
+}) {
+ return (
+ <div className="flex flex-wrap gap-4">
+ {images.map((imageUrl, idx) => (
+ <a
+ key={idx}
+ className="border-border-subtle hover:border-border-default group relative flex size-14 items-center justify-center rounded-md border bg-white"
+ target="_blank"
+ href={imageUrl}
+ rel="noopener noreferrer"
+ >
+ <div className="relative size-full overflow-hidden rounded-md">
+ <img
+ src={imageUrl}
+ alt={`${fieldTitle} ${idx + 1}`}
+ className="size-full object-cover"
+ />
+ </div>
+ <span className="sr-only">
+ {fieldTitle} image {idx + 1}
+ </span>
+ </a>
+ ))}
+ </div>
+ );
+}
+
function PartnerApplicationDetailsSkeleton() {
return (
<div className="grid grid-cols-1 gap-5">