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.

Replace `ImageUpload` with `FileUpload`

Tim Wilson739c550198c8
diff --git a/apps/web/ui/account/upload-avatar.tsx b/apps/web/ui/account/upload-avatar.tsx
index 347cc6bfe1..4fdee7ba97 100644
--- a/apps/web/ui/account/upload-avatar.tsx
+++ b/apps/web/ui/account/upload-avatar.tsx
@@ -1,6 +1,6 @@
"use client";
-import { Button, ImageUpload } from "@dub/ui";
+import { Button, FileUpload } from "@dub/ui";
import { useSession } from "next-auth/react";
import { useEffect, useState } from "react";
import { toast } from "sonner";
@@ -51,13 +51,14 @@ export default function UploadAvatar() {
This is your avatar image on {process.env.NEXT_PUBLIC_APP_NAME}.
</p>
<div className="mt-1">
- <ImageUpload
+ <FileUpload
+ accept="images"
className="h-24 w-24 rounded-full border border-gray-300"
iconClassName="w-5 h-5"
variant="plain"
- src={image ?? null}
- onChange={(src) => setImage(src)}
- resize={false}
+ imageSrc={image}
+ readFile
+ onChange={({ src }) => setImage(src)}
content={null}
maxFileSizeMB={2}
/>
diff --git a/apps/web/ui/layout/help/contact-form.tsx b/apps/web/ui/layout/help/contact-form.tsx
index 40d4e7e40e..50e43c3171 100644
--- a/apps/web/ui/layout/help/contact-form.tsx
+++ b/apps/web/ui/layout/help/contact-form.tsx
@@ -1,5 +1,5 @@
import { CheckCircleFill } from "@/ui/shared/icons";
-import { Button, ImageUpload, LoadingSpinner, useEnterSubmit } from "@dub/ui";
+import { Button, FileUpload, LoadingSpinner, useEnterSubmit } from "@dub/ui";
import { useCompletion } from "ai/react";
import { AnimatePresence, motion } from "framer-motion";
import { ChevronLeft, Image, Trash2 } from "lucide-react";
@@ -22,7 +22,7 @@ export function ContactForm({
attachmentIds: [],
});
- const [images, setImages] = useState<
+ const [uploads, setUploads] = useState<
{
file: File;
uploading: boolean;
@@ -31,7 +31,7 @@ export function ContactForm({
>([]);
const handleUpload = async (file: File) => {
- setImages((prev) => [...prev, { file, uploading: true }]);
+ setUploads((prev) => [...prev, { file, uploading: true }]);
const {
attachment: { id: attachmentId },
@@ -60,11 +60,11 @@ export function ContactForm({
console.error("Error uploading file:", err.message ? err.message : err);
});
- setImages((prev) =>
- prev.map((image) =>
- image.file === file
- ? { ...image, uploading: false, attachmentId }
- : image,
+ setUploads((prev) =>
+ prev.map((upload) =>
+ upload.file === file
+ ? { ...upload, uploading: false, attachmentId }
+ : upload,
),
);
setData((prev) => ({
@@ -188,31 +188,31 @@ export function ContactForm({
</label>
<div className="grid w-full gap-2">
- {images.map((image) => (
+ {uploads.map((upload) => (
<div
- key={image.attachmentId}
+ key={upload.attachmentId}
className="flex w-full items-center justify-between rounded-md border border-gray-200"
>
<div className="flex flex-1 items-center space-x-2 p-2">
- {image.uploading ? (
+ {upload.uploading ? (
<LoadingSpinner className="h-4 w-4" />
) : (
<Image className="h-4 w-4 text-gray-500" />
)}
<p className="text-center text-sm text-gray-500">
- {image.file.name}
+ {upload.file.name}
</p>
</div>
<button
className="h-full rounded-r-md border-l border-gray-200 p-2"
onClick={() => {
- setImages((prev) =>
- prev.filter((i) => i.file.name !== image.file.name),
+ setUploads((prev) =>
+ prev.filter((i) => i.file.name !== upload.file.name),
);
setData((prev) => ({
...prev,
attachmentIds: prev.attachmentIds.filter(
- (id) => id !== image.attachmentId,
+ (id) => id !== upload.attachmentId,
),
}));
}}
@@ -222,14 +222,12 @@ export function ContactForm({
</div>
))}
</div>
- <ImageUpload
- key={images.length}
+ <FileUpload
+ accept="any"
className="aspect-[5/1] w-full rounded-md border border-dashed border-gray-300"
iconClassName="w-5 h-5"
variant="plain"
- src={null}
- onChange={async (_, file) => await handleUpload(file)}
- resize={false}
+ onChange={async ({ file }) => await handleUpload(file)}
content="Drag and drop or click to upload."
/>
diff --git a/apps/web/ui/modals/add-edit-link-modal/og-section.tsx b/apps/web/ui/modals/add-edit-link-modal/og-section.tsx
index 901909c77c..dda7759e71 100644
--- a/apps/web/ui/modals/add-edit-link-modal/og-section.tsx
+++ b/apps/web/ui/modals/add-edit-link-modal/og-section.tsx
@@ -4,7 +4,7 @@ import { ProBadgeTooltip } from "@/ui/shared/pro-badge-tooltip";
import { UpgradeToProToast } from "@/ui/shared/upgrade-to-pro-toast";
import {
ButtonTooltip,
- ImageUpload,
+ FileUpload,
LoadingCircle,
Magic,
Popover,
@@ -12,7 +12,7 @@ import {
Switch,
Unsplash,
} from "@dub/ui";
-import { FADE_IN_ANIMATION_SETTINGS, truncate } from "@dub/utils";
+import { FADE_IN_ANIMATION_SETTINGS, resizeImage, truncate } from "@dub/utils";
import va from "@vercel/analytics";
import { useCompletion } from "ai/react";
import { motion } from "framer-motion";
@@ -154,6 +154,8 @@ export default function OGSection({
}
}, [proxy]);
+ const [resizingImage, setResizingImage] = useState(false);
+
const [cooldown, setCooldown] = useState(false);
const [openPopover, setOpenPopover] = useState(false);
@@ -228,11 +230,29 @@ export default function OGSection({
</div>
</div>
<div className="mt-1">
- <ImageUpload
- src={image}
- onChange={(image) => setData((prev) => ({ ...prev, image }))}
- loading={generatingMetatags}
+ <FileUpload
+ accept="images"
+ imageSrc={image}
+ onChange={async ({ file }) => {
+ setResizingImage(true);
+
+ const image = await resizeImage(file);
+ setData((prev) => ({
+ ...prev,
+ image,
+ }));
+
+ // Delay to prevent flickering
+ setTimeout(() => setResizingImage(false), 500);
+ }}
+ loading={generatingMetatags || resizingImage}
accessibilityLabel="OG image upload"
+ content={
+ <>
+ <p>Drag and drop or click to upload.</p>
+ <p className="mt-2">Recommended: 1200 x 630 pixels</p>
+ </>
+ }
/>
</div>
</div>
diff --git a/apps/web/ui/modals/add-edit-link-modal/preview.tsx b/apps/web/ui/modals/add-edit-link-modal/preview.tsx
index 5c7e4c492e..d8b15b689c 100644
--- a/apps/web/ui/modals/add-edit-link-modal/preview.tsx
+++ b/apps/web/ui/modals/add-edit-link-modal/preview.tsx
@@ -1,7 +1,7 @@
import { LinkProps } from "@/lib/types";
import {
Facebook,
- ImageUpload,
+ FileUpload,
LinkedIn,
LoadingCircle,
Photo,
@@ -25,6 +25,7 @@ import {
useRef,
useState,
} from "react";
+import { toast } from "sonner";
import { useDebounce } from "use-debounce";
import { usePromptModal } from "../prompt-modal";
import UnsplashSearch from "./unsplash-search";
@@ -215,15 +216,18 @@ const ImagePreview = ({
const file = e.target.files && e.target.files[0];
if (!file) return;
+ if (file.size / 1024 / 1024 > 2) {
+ toast.error(`File size too big (max 2 MB)`);
+ return;
+ }
+
setResizing(true);
const src = await resizeImage(file);
onImageChange(src);
// Delay to prevent flickering
- setTimeout(() => {
- setResizing(false);
- }, 500);
+ setTimeout(() => setResizing(false), 500);
},
[],
);
@@ -238,13 +242,22 @@ const ImagePreview = ({
}
if (image) {
return (
- <ImageUpload
+ <FileUpload
+ accept="images"
variant="plain"
- src={image}
- onChange={onImageChange}
- loading={generatingMetatags}
+ imageSrc={image}
+ onChange={async ({ file }) => {
+ setResizing(true);
+
+ onImageChange(await resizeImage(file));
+
+ // Delay to prevent flickering
+ setTimeout(() => setResizing(false), 500);
+ }}
+ loading={generatingMetatags || resizing}
clickToUpload={false}
showHoverOverlay={false}
+ accessibilityLabel="OG image upload"
/>
);
} else {
@@ -289,7 +302,7 @@ const ImagePreview = ({
ref={inputFileRef}
onChange={onInputFileChange}
type="file"
- accept="image/*"
+ accept="image/png,image/jpeg"
className="hidden"
/>
<PromptModal />
diff --git a/apps/web/ui/workspaces/upload-logo.tsx b/apps/web/ui/workspaces/upload-logo.tsx
index 54372fae4a..a728732009 100644
--- a/apps/web/ui/workspaces/upload-logo.tsx
+++ b/apps/web/ui/workspaces/upload-logo.tsx
@@ -1,7 +1,7 @@
"use client";
import useWorkspace from "@/lib/swr/use-workspace";
-import { Button, ImageUpload } from "@dub/ui";
+import { Button, FileUpload } from "@dub/ui";
import { useEffect, useState } from "react";
import { toast } from "sonner";
import { mutate } from "swr";
@@ -50,13 +50,14 @@ export default function UploadLogo() {
This is your workspace's logo on {process.env.NEXT_PUBLIC_APP_NAME}
</p>
<div className="mt-1">
- <ImageUpload
+ <FileUpload
+ accept="images"
className="h-24 w-24 rounded-full border border-gray-300"
iconClassName="w-5 h-5"
variant="plain"
- src={image ?? null}
- onChange={(src) => setImage(src)}
- resize={false}
+ imageSrc={image}
+ readFile
+ onChange={({ src }) => setImage(src)}
content={null}
maxFileSizeMB={2}
/>
diff --git a/packages/ui/src/image-upload.tsx b/packages/ui/src/file-upload.tsx
similarity index 61%
rename from packages/ui/src/image-upload.tsx
rename to packages/ui/src/file-upload.tsx
index d08cd4cedd..3dbe664b8b 100644
--- a/packages/ui/src/image-upload.tsx
+++ b/packages/ui/src/file-upload.tsx
@@ -1,9 +1,20 @@
-import { cn, resizeImage } from "@dub/utils";
+import { cn } from "@dub/utils";
import { VariantProps, cva } from "class-variance-authority";
import { UploadCloud } from "lucide-react";
import { DragEvent, ReactNode, useState } from "react";
import { toast } from "sonner";
-import { LoadingCircle, LoadingSpinner } from "./icons";
+import { LoadingCircle } from "./icons";
+
+const acceptFileTypes: Record<
+ string,
+ { types: string[]; errorMessage?: string }
+> = {
+ any: { types: [] },
+ images: {
+ types: ["image/png", "image/jpeg"],
+ errorMessage: "File type not supported (.png or .jpg only)",
+ },
+};
const imageUploadVariants = cva(
"group relative isolate flex aspect-[1200/630] w-full flex-col items-center justify-center overflow-hidden bg-white transition-all hover:bg-gray-50",
@@ -20,12 +31,33 @@ const imageUploadVariants = cva(
},
);
-export type ImageUploadProps = {
- src: string | null;
- onChange?: (src: string, file: File) => void;
+type FileUploadReadFileProps =
+ | {
+ /**
+ * Whether to automatically read the file and return the result as `src` to onChange
+ */
+ readFile?: false;
+ onChange?: (data: { file: File }) => void;
+ }
+ | {
+ /**
+ * Whether to automatically read the file and return the result as `src` to onChange
+ */
+ readFile: true;
+ onChange?: (data: { file: File; src: string }) => void;
+ };
+
+export type FileUploadProps = FileUploadReadFileProps & {
+ accept: keyof typeof acceptFileTypes;
+
className?: string;
iconClassName?: string;
+ /**
+ * Image to display (generally for image uploads)
+ */
+ imageSrc?: string | null;
+
/**
* Whether to display a loading spinner
*/
@@ -51,11 +83,6 @@ export type ImageUploadProps = {
*/
targetResolution?: { width: number; height: number };
- /**
- * Whether to automatically resize the uploaded image to the target resolution
- */
- resize?: boolean;
-
/**
* A maximum file size (in megabytes) to check upon file selection
*/
@@ -67,25 +94,25 @@ export type ImageUploadProps = {
accessibilityLabel?: string;
} & VariantProps<typeof imageUploadVariants>;
-export function ImageUpload({
- src,
+export function FileUpload({
+ readFile,
onChange,
variant,
className,
iconClassName,
+ accept = "any",
+ imageSrc,
loading = false,
clickToUpload = true,
showHoverOverlay = true,
content,
- targetResolution = { width: 1200, height: 630 },
- resize = true,
maxFileSizeMB = 0,
- accessibilityLabel = "Image upload",
-}: ImageUploadProps) {
- const [resizing, setResizing] = useState(false);
+ accessibilityLabel = "File upload",
+}: FileUploadProps) {
const [dragActive, setDragActive] = useState(false);
+ const [fileName, setFileName] = useState<string | null>(null);
- const onImageChange = async (
+ const onFileChange = async (
e: React.ChangeEvent<HTMLInputElement> | DragEvent,
) => {
const file =
@@ -94,28 +121,32 @@ export function ImageUpload({
: e.target.files && e.target.files[0];
if (!file) return;
+ setFileName(file.name);
+
if (maxFileSizeMB > 0 && file.size / 1024 / 1024 > maxFileSizeMB) {
toast.error(`File size too big (max ${maxFileSizeMB} MB)`);
return;
}
- if (resize) {
- setResizing(true);
+ const acceptedTypes = acceptFileTypes[accept].types;
- onChange?.(
- await resizeImage(file, { ...targetResolution, quality: 1 }),
- file,
+ if (acceptedTypes.length && !acceptedTypes.includes(file.type)) {
+ toast.error(
+ acceptFileTypes[accept].errorMessage ?? "File type not supported",
);
+ return;
+ }
- // Delay to prevent flickering
- setTimeout(() => {
- setResizing(false);
- }, 500);
- } else {
+ if (readFile) {
const reader = new FileReader();
- reader.onload = (e) => onChange?.(e.target?.result as string, file);
+ reader.onload = (e) =>
+ onChange?.({ src: e.target?.result as string, file });
reader.readAsDataURL(file);
+
+ return;
}
+
+ onChange?.({ file });
};
return (
@@ -151,7 +182,7 @@ export function ImageUpload({
onDrop={async (e) => {
e.preventDefault();
e.stopPropagation();
- onImageChange(e);
+ onFileChange(e);
setDragActive(false);
}}
/>
@@ -160,49 +191,32 @@ export function ImageUpload({
"absolute inset-0 z-[3] flex flex-col items-center justify-center rounded-[inherit] bg-white transition-all",
dragActive &&
"cursor-copy border-2 border-black bg-gray-50 opacity-100",
- src
+ imageSrc
? cn("opacity-0", showHoverOverlay && "group-hover:opacity-100")
: "group-hover:bg-gray-50",
)}
>
- {resizing ? (
- <>
- <LoadingSpinner />
- <p className="mt-2 text-center text-sm text-gray-500">
- Resizing image...
- </p>
- </>
- ) : (
- <>
- <UploadCloud
- className={cn(
- "h-7 w-7 text-gray-500 transition-all duration-75 group-hover:scale-110 group-active:scale-95",
- dragActive ? "scale-110" : "scale-100",
- iconClassName,
- )}
- />
- {content !== null && (
- <div className="mt-2 text-center text-sm text-gray-500">
- {content ?? (
- <>
- <p>
- Drag and drop {clickToUpload && "or click"} to upload.
- </p>
- <p className="mt-2">
- Recommended: {targetResolution.width} x{" "}
- {targetResolution.height} pixels
- </p>
- </>
- )}
- </div>
+ <UploadCloud
+ className={cn(
+ "h-7 w-7 text-gray-500 transition-all duration-75 group-hover:scale-110 group-active:scale-95",
+ dragActive ? "scale-110" : "scale-100",
+ iconClassName,
+ )}
+ />
+ {content !== null && (
+ <div className="mt-2 text-center text-sm text-gray-500">
+ {content ?? (
+ <>
+ <p>Drag and drop {clickToUpload && "or click"} to upload.</p>
+ </>
)}
- </>
+ </div>
)}
<span className="sr-only">{accessibilityLabel}</span>
</div>
- {src && (
+ {imageSrc && (
<img
- src={src}
+ src={imageSrc}
alt="Preview"
className="h-full w-full rounded-[inherit] object-cover"
/>
@@ -210,10 +224,10 @@ export function ImageUpload({
{clickToUpload && (
<div className="sr-only mt-1 flex shadow-sm">
<input
- key={src}
+ key={fileName} // Gets us a fresh input every time a file is uploaded
type="file"
- accept="image/*"
- onChange={onImageChange}
+ accept={acceptFileTypes[accept].types.join(",")}
+ onChange={onFileChange}
/>
</div>
)}
diff --git a/packages/ui/src/index.tsx b/packages/ui/src/index.tsx
index eb5d469847..768549002a 100644
--- a/packages/ui/src/index.tsx
+++ b/packages/ui/src/index.tsx
@@ -7,8 +7,8 @@ export * from "./avatar";
export * from "./badge";
export * from "./button";
export * from "./checkbox";
+export * from "./file-upload";
export * from "./form";
-export * from "./image-upload";
export * from "./input-select";
export * from "./label";
export * from "./modal";