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.

Start using `ImageUpload` everywhere

Tim Wilson261f8ea3ab17
diff --git a/apps/web/ui/account/upload-avatar.tsx b/apps/web/ui/account/upload-avatar.tsx
index 7dddfba68d..b1ea18f654 100644
--- a/apps/web/ui/account/upload-avatar.tsx
+++ b/apps/web/ui/account/upload-avatar.tsx
@@ -1,7 +1,6 @@
"use client";
-import { Button } from "@dub/ui";
-import { UploadCloud } from "lucide-react";
+import { Button, ImageUpload } from "@dub/ui";
import { useSession } from "next-auth/react";
import { useCallback, useEffect, useState } from "react";
import { toast } from "sonner";
@@ -73,86 +72,17 @@ export default function UploadAvatar() {
<p className="text-sm text-gray-500">
This is your avatar image on {process.env.NEXT_PUBLIC_APP_NAME}.
</p>
- <div>
- <label
- htmlFor="image"
- className="group relative mt-1 flex h-24 w-24 cursor-pointer flex-col items-center justify-center rounded-full border border-gray-300 bg-white shadow-sm transition-all hover:bg-gray-50"
- >
- <div
- className="absolute z-[5] h-full w-full rounded-full"
- onDragOver={(e) => {
- e.preventDefault();
- e.stopPropagation();
- setDragActive(true);
- }}
- onDragEnter={(e) => {
- e.preventDefault();
- e.stopPropagation();
- setDragActive(true);
- }}
- onDragLeave={(e) => {
- e.preventDefault();
- e.stopPropagation();
- setDragActive(false);
- }}
- onDrop={(e) => {
- e.preventDefault();
- e.stopPropagation();
- setDragActive(false);
- const file = e.dataTransfer.files && e.dataTransfer.files[0];
- if (file) {
- if (file.size / 1024 / 1024 > 2) {
- toast.error("File size too big (max 2MB)");
- } else if (
- file.type !== "image/png" &&
- file.type !== "image/jpeg"
- ) {
- toast.error("File type not supported (.png or .jpg only)");
- } else {
- const reader = new FileReader();
- reader.onload = (e) => {
- setImage(e.target?.result as string);
- };
- reader.readAsDataURL(file);
- }
- }
- }}
- />
- <div
- className={`${
- dragActive
- ? "cursor-copy border-2 border-black bg-gray-50 opacity-100"
- : ""
- } absolute z-[3] flex h-full w-full flex-col items-center justify-center rounded-full bg-white transition-all ${
- image
- ? "opacity-0 group-hover:opacity-100"
- : "group-hover:bg-gray-50"
- }`}
- >
- <UploadCloud
- className={`${
- dragActive ? "scale-110" : "scale-100"
- } h-5 w-5 text-gray-500 transition-all duration-75 group-hover:scale-110 group-active:scale-95`}
- />
- </div>
- {image && (
- <img
- src={image}
- alt="Preview"
- className="h-full w-full rounded-full object-cover"
- />
- )}
- </label>
- <div className="mt-1 flex rounded-full shadow-sm">
- <input
- id="image"
- name="image"
- type="file"
- accept="image/*"
- className="sr-only"
- onChange={onChangePicture}
- />
- </div>
+ <div className="mt-1">
+ <ImageUpload
+ 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}
+ content={null}
+ maxFileSizeMB={2}
+ />
</div>
</div>
diff --git a/apps/web/ui/layout/help/contact-form.tsx b/apps/web/ui/layout/help/contact-form.tsx
index f8101b0cf4..063d746d22 100644
--- a/apps/web/ui/layout/help/contact-form.tsx
+++ b/apps/web/ui/layout/help/contact-form.tsx
@@ -1,9 +1,8 @@
import { CheckCircleFill } from "@/ui/shared/icons";
-import { Button, LoadingSpinner, useEnterSubmit } from "@dub/ui";
-import { cn } from "@dub/utils";
+import { Button, ImageUpload, LoadingSpinner, useEnterSubmit } from "@dub/ui";
import { useCompletion } from "ai/react";
import { AnimatePresence, motion } from "framer-motion";
-import { ChevronLeft, Image, Trash2, UploadCloud } from "lucide-react";
+import { ChevronLeft, Image, Trash2 } from "lucide-react";
import { Dispatch, SetStateAction, useEffect, useRef, useState } from "react";
import TextareaAutosize from "react-textarea-autosize";
import { toast } from "sonner";
@@ -225,68 +224,15 @@ export function ContactForm({
</div>
))}
</div>
-
- <label
- htmlFor="image"
- className="group relative flex aspect-[5/1] w-full cursor-pointer flex-col items-center justify-center rounded-md border border-dashed border-gray-300 bg-white transition-all"
- >
- <div
- className="absolute z-[5] h-full w-full rounded-md"
- onDragOver={(e) => {
- e.preventDefault();
- e.stopPropagation();
- setDragActive(true);
- }}
- onDragEnter={(e) => {
- e.preventDefault();
- e.stopPropagation();
- setDragActive(true);
- }}
- onDragLeave={(e) => {
- e.preventDefault();
- e.stopPropagation();
- setDragActive(false);
- }}
- onDrop={async (e) => {
- e.preventDefault();
- e.stopPropagation();
- setDragActive(false);
- const file = e.dataTransfer.files && e.dataTransfer.files[0];
- if (!file) return;
- await handleUpload(file);
- }}
- />
- <div
- className={cn(
- "absolute z-[3] flex h-full w-full flex-col items-center justify-center rounded-md bg-white transition-all",
- {
- "cursor-copy border-2 border-black bg-gray-50 opacity-100":
- dragActive,
- },
- )}
- >
- <UploadCloud
- className={`${
- dragActive ? "scale-110" : "scale-100"
- } h-5 w-5 text-gray-500 transition-all duration-75 group-hover:scale-110 group-active:scale-95`}
- />
- <p className="mt-2 text-center text-sm text-gray-500">
- Drag and drop or click to upload.
- </p>
- <span className="sr-only">Image upload</span>
- </div>
- </label>
- <input
- id="image"
- name="image"
- type="file"
- accept="image/*"
- className="sr-only"
- onChange={async (e) => {
- const file = e.target.files && e.target.files[0];
- if (!file) return;
- await handleUpload(file);
- }}
+ <ImageUpload
+ key={images.length}
+ 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}
+ content="Drag and drop or click to upload."
/>
<div className="fixed bottom-0 left-0 z-10 flex h-16 w-full items-center justify-center rounded-b-lg bg-white px-3 sm:px-6">
diff --git a/apps/web/ui/workspaces/upload-logo.tsx b/apps/web/ui/workspaces/upload-logo.tsx
index e9362373f0..21002f28a4 100644
--- a/apps/web/ui/workspaces/upload-logo.tsx
+++ b/apps/web/ui/workspaces/upload-logo.tsx
@@ -1,8 +1,7 @@
"use client";
import useWorkspace from "@/lib/swr/use-workspace";
-import { Button } from "@dub/ui";
-import { UploadCloud } from "lucide-react";
+import { Button, ImageUpload } from "@dub/ui";
import { useCallback, useEffect, useState } from "react";
import { toast } from "sonner";
import { mutate } from "swr";
@@ -72,86 +71,17 @@ export default function UploadLogo() {
<p className="text-sm text-gray-500">
This is your workspace's logo on {process.env.NEXT_PUBLIC_APP_NAME}
</p>
- <div>
- <label
- htmlFor="image"
- className="group relative mt-1 flex h-24 w-24 cursor-pointer flex-col items-center justify-center rounded-full border border-gray-300 bg-white shadow-sm transition-all hover:bg-gray-50"
- >
- <div
- className="absolute z-[5] h-full w-full rounded-full"
- onDragOver={(e) => {
- e.preventDefault();
- e.stopPropagation();
- setDragActive(true);
- }}
- onDragEnter={(e) => {
- e.preventDefault();
- e.stopPropagation();
- setDragActive(true);
- }}
- onDragLeave={(e) => {
- e.preventDefault();
- e.stopPropagation();
- setDragActive(false);
- }}
- onDrop={(e) => {
- e.preventDefault();
- e.stopPropagation();
- setDragActive(false);
- const file = e.dataTransfer.files && e.dataTransfer.files[0];
- if (file) {
- if (file.size / 1024 / 1024 > 2) {
- toast.error("File size too big (max 2MB)");
- } else if (
- file.type !== "image/png" &&
- file.type !== "image/jpeg"
- ) {
- toast.error("File type not supported (.png or .jpg only)");
- } else {
- const reader = new FileReader();
- reader.onload = (e) => {
- setImage(e.target?.result as string);
- };
- reader.readAsDataURL(file);
- }
- }
- }}
- />
- <div
- className={`${
- dragActive
- ? "cursor-copy border-2 border-black bg-gray-50 opacity-100"
- : ""
- } absolute z-[3] flex h-full w-full flex-col items-center justify-center rounded-full bg-white transition-all ${
- image
- ? "opacity-0 group-hover:opacity-100"
- : "group-hover:bg-gray-50"
- }`}
- >
- <UploadCloud
- className={`${
- dragActive ? "scale-110" : "scale-100"
- } h-5 w-5 text-gray-500 transition-all duration-75 group-hover:scale-110 group-active:scale-95`}
- />
- </div>
- {image && (
- <img
- src={image}
- alt="Preview"
- className="h-full w-full rounded-full object-cover"
- />
- )}
- </label>
- <div className="mt-1 flex rounded-full shadow-sm">
- <input
- id="image"
- name="image"
- type="file"
- accept="image/*"
- className="sr-only"
- onChange={onChangePicture}
- />
- </div>
+ <div className="mt-1">
+ <ImageUpload
+ 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}
+ content={null}
+ maxFileSizeMB={2}
+ />
</div>
</div>
diff --git a/packages/ui/src/image-upload.tsx b/packages/ui/src/image-upload.tsx
index 5c030f4e3e..d08cd4cedd 100644
--- a/packages/ui/src/image-upload.tsx
+++ b/packages/ui/src/image-upload.tsx
@@ -1,10 +1,10 @@
import { cn, resizeImage } from "@dub/utils";
+import { VariantProps, cva } from "class-variance-authority";
import { UploadCloud } from "lucide-react";
-import { DragEvent, ReactNode, useId, useState } from "react";
+import { DragEvent, ReactNode, useState } from "react";
+import { toast } from "sonner";
import { LoadingCircle, LoadingSpinner } from "./icons";
-import { cva, VariantProps } from "class-variance-authority";
-
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",
{
@@ -22,7 +22,7 @@ const imageUploadVariants = cva(
export type ImageUploadProps = {
src: string | null;
- onChange?: (src: string) => void;
+ onChange?: (src: string, file: File) => void;
className?: string;
iconClassName?: string;
@@ -56,6 +56,11 @@ export type ImageUploadProps = {
*/
resize?: boolean;
+ /**
+ * A maximum file size (in megabytes) to check upon file selection
+ */
+ maxFileSizeMB?: number;
+
/**
* Accessibility label for screen readers
*/
@@ -74,10 +79,9 @@ export function ImageUpload({
content,
targetResolution = { width: 1200, height: 630 },
resize = true,
+ maxFileSizeMB = 0,
accessibilityLabel = "Image upload",
}: ImageUploadProps) {
- const inputId = useId();
-
const [resizing, setResizing] = useState(false);
const [dragActive, setDragActive] = useState(false);
@@ -90,10 +94,18 @@ export function ImageUpload({
: e.target.files && e.target.files[0];
if (!file) return;
+ if (maxFileSizeMB > 0 && file.size / 1024 / 1024 > maxFileSizeMB) {
+ toast.error(`File size too big (max ${maxFileSizeMB} MB)`);
+ return;
+ }
+
if (resize) {
setResizing(true);
- onChange?.(await resizeImage(file, { ...targetResolution, quality: 1 }));
+ onChange?.(
+ await resizeImage(file, { ...targetResolution, quality: 1 }),
+ file,
+ );
// Delay to prevent flickering
setTimeout(() => {
@@ -101,14 +113,13 @@ export function ImageUpload({
}, 500);
} else {
const reader = new FileReader();
- reader.onload = (e) => onChange?.(e.target?.result as string);
+ reader.onload = (e) => onChange?.(e.target?.result as string, file);
reader.readAsDataURL(file);
}
};
return (
<label
- htmlFor={inputId}
className={cn(
imageUploadVariants({ variant }),
clickToUpload && "cursor-pointer",
@@ -200,7 +211,6 @@ export function ImageUpload({
<div className="sr-only mt-1 flex shadow-sm">
<input
key={src}
- id={inputId}
type="file"
accept="image/*"
onChange={onImageChange}