Skip to content

The Postgres development platform. Supabase gives you a dedicated Postgres database to build your web, mobile, and AI applications.

Update dropzone component for UI Library (#34369)

Joshen Lime0b2c605d290
diff --git a/apps/ui-library/package.json b/apps/ui-library/package.json
index e726f214a3a..aa11ebc5ef9 100644
--- a/apps/ui-library/package.json
+++ b/apps/ui-library/package.json
@@ -18,7 +18,7 @@
"dependencies": {
"@radix-ui/react-label": "^2.0.2",
"@radix-ui/react-progress": "^1.0.3",
- "@radix-ui/react-slot": "^1.0.2",
+ "@radix-ui/react-slot": "^1.1.2",
"@radix-ui/react-tooltip": "^1.0.7",
"class-variance-authority": "^0.6.0",
"contentlayer2": "0.4.6",
diff --git a/apps/ui-library/public/r/dropzone-nextjs.json b/apps/ui-library/public/r/dropzone-nextjs.json
index 3cc30ca5191..f6eca7ec8e3 100644
--- a/apps/ui-library/public/r/dropzone-nextjs.json
+++ b/apps/ui-library/public/r/dropzone-nextjs.json
@@ -17,12 +17,12 @@
"files": [
{
"path": "registry/default/blocks/dropzone/components/dropzone.tsx",
- "content": "'use client'\n\nimport { cn } from '@/lib/utils'\nimport { UseSupabaseUploadReturn } from '@/registry/default/blocks/dropzone/hooks/use-supabase-upload'\nimport { Button } from '@/registry/default/components/ui/button'\nimport { Tooltip, TooltipContent, TooltipTrigger } from '@/registry/default/components/ui/tooltip'\nimport { CheckCircle, CircleAlert, File, Loader2, Trash, Upload } from 'lucide-react'\nimport { createContext, PropsWithChildren, useCallback, useContext } from 'react'\n\ntype DropzoneContextType = Omit<UseSupabaseUploadReturn, 'getRootProps' | 'getInputProps'>\n\nconst DropzoneContext = createContext<DropzoneContextType | undefined>(undefined)\n\ntype DropzoneProps = UseSupabaseUploadReturn & {\n className?: string\n}\n\nconst Dropzone = ({\n className,\n children,\n getRootProps,\n getInputProps,\n ...restProps\n}: PropsWithChildren<DropzoneProps>) => {\n const isActive = restProps.isDragActive\n const isInvalid =\n (restProps.isDragActive && restProps.isDragReject) ||\n restProps.error ||\n restProps.files.some((file) => file.errors.length !== 0)\n\n return (\n <DropzoneContext.Provider value={{ ...restProps }}>\n <div\n {...getRootProps({\n className: cn(\n 'border-2 border-dashed border-gray-300 rounded-lg p-6 text-center bg-card transition-colors duration-300',\n className,\n isActive && 'border-primary bg-primary/10',\n isInvalid && 'border-destructive bg-destructive/10'\n ),\n })}\n >\n <input {...getInputProps()} />\n {children}\n </div>\n </DropzoneContext.Provider>\n )\n}\nconst DropzoneContent = ({ className }: { className?: string }) => {\n const { error, files, setFiles, onUpload, loading, success } = useDropzoneContext()\n\n const handleRemoveFile = useCallback(\n (fileName: string) => {\n setFiles(files.filter((file) => file.name !== fileName))\n },\n [files, setFiles]\n )\n\n if (success) {\n return (\n <div className={cn('flex flex-row items-center gap-1 justify-center', className)}>\n <CheckCircle className=\"text-primary text-lg font-medium\" />\n <p className=\"text-primary text-lg font-medium\">Files uploaded successfully</p>\n </div>\n )\n }\n\n return (\n <div className={cn('flex flex-col', className)}>\n {files.map((file) => {\n return (\n <div\n key={file.name}\n className=\"flex items-center gap-2 border-b p-2 first:mt-4 last:mb-4 \"\n >\n {file.type.startsWith('image/') ? (\n <div className=\"h-12 w-12 rounded border overflow-hidden flex-shrink-0 bg-muted\">\n <img src={file.preview} alt={file.name} className=\"object-cover\" />\n </div>\n ) : (\n <div className=\"h-12 w-12 rounded border bg-muted flex items-center justify-center\">\n <File />\n </div>\n )}\n <div className=\"grow flex items-center gap-2 justify-start\">\n <span className=\"text-sm\">{file.name}</span>\n {file.errors.length !== 0 && (\n <Tooltip>\n <TooltipTrigger asChild>\n <CircleAlert className=\"text-destructive\" />\n </TooltipTrigger>\n <TooltipContent>{file.errors.map((e) => e.message).join(', ')}</TooltipContent>\n </Tooltip>\n )}\n </div>\n\n <Button\n size=\"icon\"\n variant=\"destructive\"\n className=\"justify-self-end\"\n onClick={() => handleRemoveFile(file.name)}\n >\n <Trash />\n </Button>\n </div>\n )\n })}\n {files.length > 0 && (\n <div className=\"mt-2\">\n <Button\n variant=\"default\"\n onClick={onUpload}\n disabled={files.some((file) => file.errors.length !== 0) || loading}\n >\n {loading ? (\n <>\n <Loader2 className=\"mr-2 h-4 w-4 animate-spin\" />\n Uploading...\n </>\n ) : (\n <>Upload</>\n )}\n </Button>\n </div>\n )}\n {error && <p className=\"text-destructive text-lg font-medium\">{error}</p>}\n </div>\n )\n}\n\nconst DropzoneEmptyState = ({ className }: { className?: string }) => {\n const { files, maxFiles, maxFileSize, inputRef, success } = useDropzoneContext()\n\n if ((maxFiles !== 0 && files.length >= maxFiles) || success) {\n return null\n }\n\n return (\n <div className={cn('flex flex-col items-center', className)}>\n <div className=\"rounded-full bg-primary text-primary-foreground p-2\">\n <Upload />\n </div>\n <p className=\"text-lg font-medium\">\n Add or{' '}\n <a onClick={() => inputRef.current?.click()} className=\"underline cursor-pointer\">\n drop {maxFiles === 1 ? `file` : 'files'}\n </a>\n </p>\n {maxFileSize !== Number.POSITIVE_INFINITY && (\n <p className=\"text-sm text-muted-foreground mt-2\">Maximum file size: {maxFileSize} MB</p>\n )}\n </div>\n )\n}\n\nconst useDropzoneContext = () => {\n const context = useContext(DropzoneContext)\n\n if (!context) {\n throw new Error('useDropzoneContext must be used within a Dropzone')\n }\n\n return context\n}\n\nexport { Dropzone, DropzoneContent, DropzoneEmptyState, useDropzoneContext }\n",
+ "content": "'use client'\n\nimport { cn } from '@/lib/utils'\nimport { type UseSupabaseUploadReturn } from '@/registry/default/blocks/dropzone/hooks/use-supabase-upload'\nimport { Button } from '@/registry/default/components/ui/button'\nimport { CheckCircle, File, Loader2, Upload, X } from 'lucide-react'\nimport { createContext, type PropsWithChildren, useCallback, useContext } from 'react'\n\nexport const formatBytes = (\n bytes: number,\n decimals = 2,\n size?: 'bytes' | 'KB' | 'MB' | 'GB' | 'TB' | 'PB' | 'EB' | 'ZB' | 'YB'\n) => {\n const k = 1000\n const dm = decimals < 0 ? 0 : decimals\n const sizes = ['bytes', 'KB', 'MB', 'GB', 'TB', 'PB', 'EB', 'ZB', 'YB']\n\n if (bytes === 0 || bytes === undefined) return size !== undefined ? `0 ${size}` : '0 bytes'\n const i = size !== undefined ? sizes.indexOf(size) : Math.floor(Math.log(bytes) / Math.log(k))\n return parseFloat((bytes / Math.pow(k, i)).toFixed(dm)) + ' ' + sizes[i]\n}\n\ntype DropzoneContextType = Omit<UseSupabaseUploadReturn, 'getRootProps' | 'getInputProps'>\n\nconst DropzoneContext = createContext<DropzoneContextType | undefined>(undefined)\n\ntype DropzoneProps = UseSupabaseUploadReturn & {\n className?: string\n}\n\nconst Dropzone = ({\n className,\n children,\n getRootProps,\n getInputProps,\n ...restProps\n}: PropsWithChildren<DropzoneProps>) => {\n const isSuccess = restProps.isSuccess\n const isActive = restProps.isDragActive\n const isInvalid =\n (restProps.isDragActive && restProps.isDragReject) ||\n (restProps.errors.length > 0 && !restProps.isSuccess) ||\n restProps.files.some((file) => file.errors.length !== 0)\n\n return (\n <DropzoneContext.Provider value={{ ...restProps }}>\n <div\n {...getRootProps({\n className: cn(\n 'border-2 border-gray-300 rounded-lg p-6 text-center bg-card transition-colors duration-300 text-foreground',\n className,\n isSuccess ? 'border-solid' : 'border-dashed',\n isActive && 'border-primary bg-primary/10',\n isInvalid && 'border-destructive bg-destructive/10'\n ),\n })}\n >\n <input {...getInputProps()} />\n {children}\n </div>\n </DropzoneContext.Provider>\n )\n}\nconst DropzoneContent = ({ className }: { className?: string }) => {\n const {\n files,\n setFiles,\n onUpload,\n loading,\n successes,\n errors,\n maxFileSize,\n maxFiles,\n isSuccess,\n } = useDropzoneContext()\n\n const exceedMaxFiles = files.length > maxFiles\n\n const handleRemoveFile = useCallback(\n (fileName: string) => {\n setFiles(files.filter((file) => file.name !== fileName))\n },\n [files, setFiles]\n )\n\n if (isSuccess) {\n return (\n <div className={cn('flex flex-row items-center gap-x-2 justify-center', className)}>\n <CheckCircle size={16} className=\"text-primary\" />\n <p className=\"text-primary text-sm\">\n Successfully uploaded {files.length} file{files.length > 1 ? 's' : ''}\n </p>\n </div>\n )\n }\n\n return (\n <div className={cn('flex flex-col', className)}>\n {files.map((file, idx) => {\n const fileError = errors.find((e) => e.name === file.name)\n const isSuccessfullyUploaded = !!successes.find((e) => e === file.name)\n\n return (\n <div\n key={`${file.name}-${idx}`}\n className=\"flex items-center gap-x-4 border-b py-2 first:mt-4 last:mb-4 \"\n >\n {file.type.startsWith('image/') ? (\n <div className=\"h-10 w-10 rounded border overflow-hidden shrink-0 bg-muted flex items-center justify-center\">\n <img src={file.preview} alt={file.name} className=\"object-cover\" />\n </div>\n ) : (\n <div className=\"h-10 w-10 rounded border bg-muted flex items-center justify-center\">\n <File size={18} />\n </div>\n )}\n\n <div className=\"shrink grow flex flex-col items-start truncate\">\n <p title={file.name} className=\"text-sm truncate max-w-full\">\n {file.name}\n </p>\n {file.errors.length > 0 ? (\n <p className=\"text-xs text-destructive\">\n {file.errors\n .map((e) =>\n e.message.startsWith('File is larger than')\n ? `File is larger than ${formatBytes(maxFileSize, 2)} (Size: ${formatBytes(file.size, 2)})`\n : e.message\n )\n .join(', ')}\n </p>\n ) : loading && !isSuccessfullyUploaded ? (\n <p className=\"text-xs text-muted-foreground\">Uploading file...</p>\n ) : !!fileError ? (\n <p className=\"text-xs text-destructive\">Failed to upload: {fileError.message}</p>\n ) : isSuccessfullyUploaded ? (\n <p className=\"text-xs text-primary\">Successfully uploaded file</p>\n ) : (\n <p className=\"text-xs text-muted-foreground\">{formatBytes(file.size, 2)}</p>\n )}\n </div>\n\n {!loading && !isSuccessfullyUploaded && (\n <Button\n size=\"icon\"\n variant=\"link\"\n className=\"shrink-0 justify-self-end text-muted-foreground hover:text-foreground\"\n onClick={() => handleRemoveFile(file.name)}\n >\n <X />\n </Button>\n )}\n </div>\n )\n })}\n {exceedMaxFiles && (\n <p className=\"text-sm text-left mt-2 text-destructive\">\n You may upload only up to {maxFiles} files, please remove {files.length - maxFiles} file\n {files.length - maxFiles > 1 ? 's' : ''}.\n </p>\n )}\n {files.length > 0 && !exceedMaxFiles && (\n <div className=\"mt-2\">\n <Button\n variant=\"outline\"\n onClick={onUpload}\n disabled={files.some((file) => file.errors.length !== 0) || loading}\n >\n {loading ? (\n <>\n <Loader2 className=\"mr-2 h-4 w-4 animate-spin\" />\n Uploading...\n </>\n ) : (\n <>Upload files</>\n )}\n </Button>\n </div>\n )}\n </div>\n )\n}\n\nconst DropzoneEmptyState = ({ className }: { className?: string }) => {\n const { maxFiles, maxFileSize, inputRef, isSuccess } = useDropzoneContext()\n\n if (isSuccess) {\n return null\n }\n\n return (\n <div className={cn('flex flex-col items-center gap-y-2', className)}>\n <Upload size={20} className=\"text-muted-foreground\" />\n <p className=\"text-sm\">\n Upload{!!maxFiles && maxFiles > 1 ? ` ${maxFiles}` : ''} file\n {!maxFiles || maxFiles > 1 ? 's' : ''}\n </p>\n <div className=\"flex flex-col items-center gap-y-1\">\n <p className=\"text-xs text-muted-foreground\">\n Drag and drop or{' '}\n <a\n onClick={() => inputRef.current?.click()}\n className=\"underline cursor-pointer transition hover:text-foreground\"\n >\n select {maxFiles === 1 ? `file` : 'files'}\n </a>{' '}\n to upload\n </p>\n {maxFileSize !== Number.POSITIVE_INFINITY && (\n <p className=\"text-xs text-muted-foreground\">\n Maximum file size: {formatBytes(maxFileSize, 2)}\n </p>\n )}\n </div>\n </div>\n )\n}\n\nconst useDropzoneContext = () => {\n const context = useContext(DropzoneContext)\n\n if (!context) {\n throw new Error('useDropzoneContext must be used within a Dropzone')\n }\n\n return context\n}\n\nexport { Dropzone, DropzoneContent, DropzoneEmptyState, useDropzoneContext }\n",
"type": "registry:component"
},
{
"path": "registry/default/blocks/dropzone/hooks/use-supabase-upload.ts",
- "content": "import { createClient } from '@/registry/default/clients/nextjs/lib/supabase/client'\nimport { useCallback, useEffect, useState } from 'react'\nimport { FileError, FileRejection, useDropzone } from 'react-dropzone'\n\nconst supabase = createClient()\n\ninterface FileWithPreview extends File {\n preview?: string\n errors: readonly FileError[]\n}\n\ntype UseSupabaseUploadOptions = {\n bucketName: string\n path: string\n allowedMimeTypes?: string[]\n maxFileSize?: number\n maxFiles?: number\n}\n\ntype UseSupabaseUploadReturn = ReturnType<typeof useSupabaseUpload>\n\nconst useSupabaseUpload = (options: UseSupabaseUploadOptions) => {\n const {\n bucketName,\n path,\n allowedMimeTypes = [],\n maxFileSize = Number.POSITIVE_INFINITY,\n maxFiles = 0,\n } = options\n\n const [files, setFiles] = useState<FileWithPreview[]>([])\n const [loading, setLoading] = useState<boolean>(false)\n const [error, setError] = useState<string | null>(null)\n const [success, setSuccess] = useState(false)\n\n const onDrop = useCallback(\n (acceptedFiles: File[], fileRejections: FileRejection[]) => {\n const validFiles = acceptedFiles.map((file) => {\n ;(file as FileWithPreview).preview = URL.createObjectURL(file)\n ;(file as FileWithPreview).errors = []\n return file as FileWithPreview\n })\n\n const invalidFiles = fileRejections.map(({ file, errors }) => {\n ;(file as FileWithPreview).preview = URL.createObjectURL(file)\n ;(file as FileWithPreview).errors = errors\n return file as FileWithPreview\n })\n\n const newFiles = [...files, ...validFiles, ...invalidFiles]\n\n setFiles(newFiles)\n },\n [files, setFiles]\n )\n\n const dropzoneProps = useDropzone({\n onDrop,\n noClick: true,\n accept: allowedMimeTypes.reduce((acc, type) => ({ ...acc, [type]: [] }), {}),\n maxSize: maxFileSize,\n maxFiles: maxFiles,\n multiple: maxFiles !== 1,\n })\n\n const onUpload = useCallback(async () => {\n setError(null)\n setLoading(true)\n await Promise.all(\n files.map(async (file) => {\n const { error } = await supabase.storage\n .from(bucketName)\n .upload(`${path}/${file.name}`, file, {\n cacheControl: '3600',\n upsert: false,\n })\n if (error) {\n setError(error.message)\n } else {\n setSuccess(true)\n }\n })\n )\n setLoading(false)\n }, [files, path, bucketName, setError, setLoading])\n\n useEffect(() => {\n if (files.length === 0) {\n setError(null)\n }\n\n // If the number of files doesn't exceed the maxFiles parameter, remove the error 'Too many files' from each file\n if (files.length <= maxFiles) {\n let changed = false\n const newFiles = files.map((file) => {\n if (file.errors.some((e) => e.code === 'too-many-files')) {\n file.errors = file.errors.filter((e) => e.code !== 'too-many-files')\n changed = true\n }\n return file\n })\n if (changed) {\n setFiles(newFiles)\n }\n }\n }, [files.length, setFiles, maxFiles])\n\n return {\n files,\n setFiles,\n success,\n loading,\n error,\n setError,\n onUpload,\n maxFileSize: maxFileSize,\n maxFiles: maxFiles,\n ...dropzoneProps,\n }\n}\n\nexport { useSupabaseUpload, type UseSupabaseUploadOptions, type UseSupabaseUploadReturn }\n",
+ "content": "import { createClient } from '@/registry/default/clients/nextjs/lib/supabase/client'\nimport { useCallback, useEffect, useMemo, useState } from 'react'\nimport { type FileError, type FileRejection, useDropzone } from 'react-dropzone'\n\nconst supabase = createClient()\n\ninterface FileWithPreview extends File {\n preview?: string\n errors: readonly FileError[]\n}\n\ntype UseSupabaseUploadOptions = {\n /**\n * Name of bucket to upload files to in your Supabase project\n */\n bucketName: string\n /**\n * Folder to upload files to in the specified bucket within your Supabase project.\n *\n * Defaults to uploading files to the root of the bucket\n *\n * e.g If specified path is `test`, your file will be uploaded as `test/file_name`\n */\n path?: string\n /**\n * Allowed MIME types for each file upload (e.g `image/png`, `text/html`, etc). Wildcards are also supported (e.g `image/*`).\n *\n * Defaults to allowing uploading of all MIME types.\n */\n allowedMimeTypes?: string[]\n /**\n * Maximum upload size of each file allowed in bytes. (e.g 1000 bytes = 1 KB)\n */\n maxFileSize?: number\n /**\n * Maximum number of files allowed per upload.\n */\n maxFiles?: number\n /**\n * The number of seconds the asset is cached in the browser and in the Supabase CDN.\n *\n * This is set in the Cache-Control: max-age=<seconds> header. Defaults to 3600 seconds.\n */\n cacheControl?: number\n /**\n * When set to true, the file is overwritten if it exists.\n *\n * When set to false, an error is thrown if the object already exists. Defaults to `false`\n */\n upsert?: boolean\n}\n\ntype UseSupabaseUploadReturn = ReturnType<typeof useSupabaseUpload>\n\nconst useSupabaseUpload = (options: UseSupabaseUploadOptions) => {\n const {\n bucketName,\n path,\n allowedMimeTypes = [],\n maxFileSize = Number.POSITIVE_INFINITY,\n maxFiles = 1,\n cacheControl = 3600,\n upsert = false,\n } = options\n\n const [files, setFiles] = useState<FileWithPreview[]>([])\n const [loading, setLoading] = useState<boolean>(false)\n const [errors, setErrors] = useState<{ name: string; message: string }[]>([])\n const [successes, setSuccesses] = useState<string[]>([])\n\n const isSuccess = useMemo(() => {\n if (errors.length === 0 && successes.length === 0) {\n return false\n }\n if (errors.length === 0 && successes.length === files.length) {\n return true\n }\n return false\n }, [errors.length, successes.length, files.length])\n\n const onDrop = useCallback(\n (acceptedFiles: File[], fileRejections: FileRejection[]) => {\n const validFiles = acceptedFiles\n .filter((file) => !files.find((x) => x.name === file.name))\n .map((file) => {\n ;(file as FileWithPreview).preview = URL.createObjectURL(file)\n ;(file as FileWithPreview).errors = []\n return file as FileWithPreview\n })\n\n const invalidFiles = fileRejections.map(({ file, errors }) => {\n ;(file as FileWithPreview).preview = URL.createObjectURL(file)\n ;(file as FileWithPreview).errors = errors\n return file as FileWithPreview\n })\n\n const newFiles = [...files, ...validFiles, ...invalidFiles]\n\n setFiles(newFiles)\n },\n [files, setFiles]\n )\n\n const dropzoneProps = useDropzone({\n onDrop,\n noClick: true,\n accept: allowedMimeTypes.reduce((acc, type) => ({ ...acc, [type]: [] }), {}),\n maxSize: maxFileSize,\n maxFiles: maxFiles,\n multiple: maxFiles !== 1,\n })\n\n const onUpload = useCallback(async () => {\n setLoading(true)\n\n // [Joshen] This is to support handling partial successes\n // If any files didn't upload for any reason, hitting \"Upload\" again will only upload the files that had errors\n const filesWithErrors = errors.map((x) => x.name)\n const filesToUpload =\n filesWithErrors.length > 0\n ? [\n ...files.filter((f) => filesWithErrors.includes(f.name)),\n ...files.filter((f) => !successes.includes(f.name)),\n ]\n : files\n\n const responses = await Promise.all(\n filesToUpload.map(async (file) => {\n const { error } = await supabase.storage\n .from(bucketName)\n .upload(!!path ? `${path}/${file.name}` : file.name, file, {\n cacheControl: cacheControl.toString(),\n upsert,\n })\n if (error) {\n return { name: file.name, message: error.message }\n } else {\n return { name: file.name, message: undefined }\n }\n })\n )\n\n const responseErrors = responses.filter((x) => x.message !== undefined)\n // if there were errors previously, this function tried to upload the files again so we should clear/overwrite the existing errors.\n setErrors(responseErrors)\n\n const responseSuccesses = responses.filter((x) => x.message === undefined)\n const newSuccesses = Array.from(\n new Set([...successes, ...responseSuccesses.map((x) => x.name)])\n )\n setSuccesses(newSuccesses)\n\n setLoading(false)\n }, [files, path, bucketName, errors, successes])\n\n useEffect(() => {\n if (files.length === 0) {\n setErrors([])\n }\n\n // If the number of files doesn't exceed the maxFiles parameter, remove the error 'Too many files' from each file\n if (files.length <= maxFiles) {\n let changed = false\n const newFiles = files.map((file) => {\n if (file.errors.some((e) => e.code === 'too-many-files')) {\n file.errors = file.errors.filter((e) => e.code !== 'too-many-files')\n changed = true\n }\n return file\n })\n if (changed) {\n setFiles(newFiles)\n }\n }\n }, [files.length, setFiles, maxFiles])\n\n return {\n files,\n setFiles,\n successes,\n isSuccess,\n loading,\n errors,\n setErrors,\n onUpload,\n maxFileSize: maxFileSize,\n maxFiles: maxFiles,\n allowedMimeTypes,\n ...dropzoneProps,\n }\n}\n\nexport { useSupabaseUpload, type UseSupabaseUploadOptions, type UseSupabaseUploadReturn }\n",
"type": "registry:hook"
},
{
diff --git a/apps/ui-library/public/r/dropzone-react-router.json b/apps/ui-library/public/r/dropzone-react-router.json
index 6f8e1aa3446..6b4e6dc66f9 100644
--- a/apps/ui-library/public/r/dropzone-react-router.json
+++ b/apps/ui-library/public/r/dropzone-react-router.json
@@ -17,12 +17,12 @@
"files": [
{
"path": "registry/default/blocks/dropzone/components/dropzone.tsx",
- "content": "'use client'\n\nimport { cn } from '@/lib/utils'\nimport { UseSupabaseUploadReturn } from '@/registry/default/blocks/dropzone/hooks/use-supabase-upload'\nimport { Button } from '@/registry/default/components/ui/button'\nimport { Tooltip, TooltipContent, TooltipTrigger } from '@/registry/default/components/ui/tooltip'\nimport { CheckCircle, CircleAlert, File, Loader2, Trash, Upload } from 'lucide-react'\nimport { createContext, PropsWithChildren, useCallback, useContext } from 'react'\n\ntype DropzoneContextType = Omit<UseSupabaseUploadReturn, 'getRootProps' | 'getInputProps'>\n\nconst DropzoneContext = createContext<DropzoneContextType | undefined>(undefined)\n\ntype DropzoneProps = UseSupabaseUploadReturn & {\n className?: string\n}\n\nconst Dropzone = ({\n className,\n children,\n getRootProps,\n getInputProps,\n ...restProps\n}: PropsWithChildren<DropzoneProps>) => {\n const isActive = restProps.isDragActive\n const isInvalid =\n (restProps.isDragActive && restProps.isDragReject) ||\n restProps.error ||\n restProps.files.some((file) => file.errors.length !== 0)\n\n return (\n <DropzoneContext.Provider value={{ ...restProps }}>\n <div\n {...getRootProps({\n className: cn(\n 'border-2 border-dashed border-gray-300 rounded-lg p-6 text-center bg-card transition-colors duration-300',\n className,\n isActive && 'border-primary bg-primary/10',\n isInvalid && 'border-destructive bg-destructive/10'\n ),\n })}\n >\n <input {...getInputProps()} />\n {children}\n </div>\n </DropzoneContext.Provider>\n )\n}\nconst DropzoneContent = ({ className }: { className?: string }) => {\n const { error, files, setFiles, onUpload, loading, success } = useDropzoneContext()\n\n const handleRemoveFile = useCallback(\n (fileName: string) => {\n setFiles(files.filter((file) => file.name !== fileName))\n },\n [files, setFiles]\n )\n\n if (success) {\n return (\n <div className={cn('flex flex-row items-center gap-1 justify-center', className)}>\n <CheckCircle className=\"text-primary text-lg font-medium\" />\n <p className=\"text-primary text-lg font-medium\">Files uploaded successfully</p>\n </div>\n )\n }\n\n return (\n <div className={cn('flex flex-col', className)}>\n {files.map((file) => {\n return (\n <div\n key={file.name}\n className=\"flex items-center gap-2 border-b p-2 first:mt-4 last:mb-4 \"\n >\n {file.type.startsWith('image/') ? (\n <div className=\"h-12 w-12 rounded border overflow-hidden flex-shrink-0 bg-muted\">\n <img src={file.preview} alt={file.name} className=\"object-cover\" />\n </div>\n ) : (\n <div className=\"h-12 w-12 rounded border bg-muted flex items-center justify-center\">\n <File />\n </div>\n )}\n <div className=\"grow flex items-center gap-2 justify-start\">\n <span className=\"text-sm\">{file.name}</span>\n {file.errors.length !== 0 && (\n <Tooltip>\n <TooltipTrigger asChild>\n <CircleAlert className=\"text-destructive\" />\n </TooltipTrigger>\n <TooltipContent>{file.errors.map((e) => e.message).join(', ')}</TooltipContent>\n </Tooltip>\n )}\n </div>\n\n <Button\n size=\"icon\"\n variant=\"destructive\"\n className=\"justify-self-end\"\n onClick={() => handleRemoveFile(file.name)}\n >\n <Trash />\n </Button>\n </div>\n )\n })}\n {files.length > 0 && (\n <div className=\"mt-2\">\n <Button\n variant=\"default\"\n onClick={onUpload}\n disabled={files.some((file) => file.errors.length !== 0) || loading}\n >\n {loading ? (\n <>\n <Loader2 className=\"mr-2 h-4 w-4 animate-spin\" />\n Uploading...\n </>\n ) : (\n <>Upload</>\n )}\n </Button>\n </div>\n )}\n {error && <p className=\"text-destructive text-lg font-medium\">{error}</p>}\n </div>\n )\n}\n\nconst DropzoneEmptyState = ({ className }: { className?: string }) => {\n const { files, maxFiles, maxFileSize, inputRef, success } = useDropzoneContext()\n\n if ((maxFiles !== 0 && files.length >= maxFiles) || success) {\n return null\n }\n\n return (\n <div className={cn('flex flex-col items-center', className)}>\n <div className=\"rounded-full bg-primary text-primary-foreground p-2\">\n <Upload />\n </div>\n <p className=\"text-lg font-medium\">\n Add or{' '}\n <a onClick={() => inputRef.current?.click()} className=\"underline cursor-pointer\">\n drop {maxFiles === 1 ? `file` : 'files'}\n </a>\n </p>\n {maxFileSize !== Number.POSITIVE_INFINITY && (\n <p className=\"text-sm text-muted-foreground mt-2\">Maximum file size: {maxFileSize} MB</p>\n )}\n </div>\n )\n}\n\nconst useDropzoneContext = () => {\n const context = useContext(DropzoneContext)\n\n if (!context) {\n throw new Error('useDropzoneContext must be used within a Dropzone')\n }\n\n return context\n}\n\nexport { Dropzone, DropzoneContent, DropzoneEmptyState, useDropzoneContext }\n",
+ "content": "'use client'\n\nimport { cn } from '@/lib/utils'\nimport { type UseSupabaseUploadReturn } from '@/registry/default/blocks/dropzone/hooks/use-supabase-upload'\nimport { Button } from '@/registry/default/components/ui/button'\nimport { CheckCircle, File, Loader2, Upload, X } from 'lucide-react'\nimport { createContext, type PropsWithChildren, useCallback, useContext } from 'react'\n\nexport const formatBytes = (\n bytes: number,\n decimals = 2,\n size?: 'bytes' | 'KB' | 'MB' | 'GB' | 'TB' | 'PB' | 'EB' | 'ZB' | 'YB'\n) => {\n const k = 1000\n const dm = decimals < 0 ? 0 : decimals\n const sizes = ['bytes', 'KB', 'MB', 'GB', 'TB', 'PB', 'EB', 'ZB', 'YB']\n\n if (bytes === 0 || bytes === undefined) return size !== undefined ? `0 ${size}` : '0 bytes'\n const i = size !== undefined ? sizes.indexOf(size) : Math.floor(Math.log(bytes) / Math.log(k))\n return parseFloat((bytes / Math.pow(k, i)).toFixed(dm)) + ' ' + sizes[i]\n}\n\ntype DropzoneContextType = Omit<UseSupabaseUploadReturn, 'getRootProps' | 'getInputProps'>\n\nconst DropzoneContext = createContext<DropzoneContextType | undefined>(undefined)\n\ntype DropzoneProps = UseSupabaseUploadReturn & {\n className?: string\n}\n\nconst Dropzone = ({\n className,\n children,\n getRootProps,\n getInputProps,\n ...restProps\n}: PropsWithChildren<DropzoneProps>) => {\n const isSuccess = restProps.isSuccess\n const isActive = restProps.isDragActive\n const isInvalid =\n (restProps.isDragActive && restProps.isDragReject) ||\n (restProps.errors.length > 0 && !restProps.isSuccess) ||\n restProps.files.some((file) => file.errors.length !== 0)\n\n return (\n <DropzoneContext.Provider value={{ ...restProps }}>\n <div\n {...getRootProps({\n className: cn(\n 'border-2 border-gray-300 rounded-lg p-6 text-center bg-card transition-colors duration-300 text-foreground',\n className,\n isSuccess ? 'border-solid' : 'border-dashed',\n isActive && 'border-primary bg-primary/10',\n isInvalid && 'border-destructive bg-destructive/10'\n ),\n })}\n >\n <input {...getInputProps()} />\n {children}\n </div>\n </DropzoneContext.Provider>\n )\n}\nconst DropzoneContent = ({ className }: { className?: string }) => {\n const {\n files,\n setFiles,\n onUpload,\n loading,\n successes,\n errors,\n maxFileSize,\n maxFiles,\n isSuccess,\n } = useDropzoneContext()\n\n const exceedMaxFiles = files.length > maxFiles\n\n const handleRemoveFile = useCallback(\n (fileName: string) => {\n setFiles(files.filter((file) => file.name !== fileName))\n },\n [files, setFiles]\n )\n\n if (isSuccess) {\n return (\n <div className={cn('flex flex-row items-center gap-x-2 justify-center', className)}>\n <CheckCircle size={16} className=\"text-primary\" />\n <p className=\"text-primary text-sm\">\n Successfully uploaded {files.length} file{files.length > 1 ? 's' : ''}\n </p>\n </div>\n )\n }\n\n return (\n <div className={cn('flex flex-col', className)}>\n {files.map((file, idx) => {\n const fileError = errors.find((e) => e.name === file.name)\n const isSuccessfullyUploaded = !!successes.find((e) => e === file.name)\n\n return (\n <div\n key={`${file.name}-${idx}`}\n className=\"flex items-center gap-x-4 border-b py-2 first:mt-4 last:mb-4 \"\n >\n {file.type.startsWith('image/') ? (\n <div className=\"h-10 w-10 rounded border overflow-hidden shrink-0 bg-muted flex items-center justify-center\">\n <img src={file.preview} alt={file.name} className=\"object-cover\" />\n </div>\n ) : (\n <div className=\"h-10 w-10 rounded border bg-muted flex items-center justify-center\">\n <File size={18} />\n </div>\n )}\n\n <div className=\"shrink grow flex flex-col items-start truncate\">\n <p title={file.name} className=\"text-sm truncate max-w-full\">\n {file.name}\n </p>\n {file.errors.length > 0 ? (\n <p className=\"text-xs text-destructive\">\n {file.errors\n .map((e) =>\n e.message.startsWith('File is larger than')\n ? `File is larger than ${formatBytes(maxFileSize, 2)} (Size: ${formatBytes(file.size, 2)})`\n : e.message\n )\n .join(', ')}\n </p>\n ) : loading && !isSuccessfullyUploaded ? (\n <p className=\"text-xs text-muted-foreground\">Uploading file...</p>\n ) : !!fileError ? (\n <p className=\"text-xs text-destructive\">Failed to upload: {fileError.message}</p>\n ) : isSuccessfullyUploaded ? (\n <p className=\"text-xs text-primary\">Successfully uploaded file</p>\n ) : (\n <p className=\"text-xs text-muted-foreground\">{formatBytes(file.size, 2)}</p>\n )}\n </div>\n\n {!loading && !isSuccessfullyUploaded && (\n <Button\n size=\"icon\"\n variant=\"link\"\n className=\"shrink-0 justify-self-end text-muted-foreground hover:text-foreground\"\n onClick={() => handleRemoveFile(file.name)}\n >\n <X />\n </Button>\n )}\n </div>\n )\n })}\n {exceedMaxFiles && (\n <p className=\"text-sm text-left mt-2 text-destructive\">\n You may upload only up to {maxFiles} files, please remove {files.length - maxFiles} file\n {files.length - maxFiles > 1 ? 's' : ''}.\n </p>\n )}\n {files.length > 0 && !exceedMaxFiles && (\n <div className=\"mt-2\">\n <Button\n variant=\"outline\"\n onClick={onUpload}\n disabled={files.some((file) => file.errors.length !== 0) || loading}\n >\n {loading ? (\n <>\n <Loader2 className=\"mr-2 h-4 w-4 animate-spin\" />\n Uploading...\n </>\n ) : (\n <>Upload files</>\n )}\n </Button>\n </div>\n )}\n </div>\n )\n}\n\nconst DropzoneEmptyState = ({ className }: { className?: string }) => {\n const { maxFiles, maxFileSize, inputRef, isSuccess } = useDropzoneContext()\n\n if (isSuccess) {\n return null\n }\n\n return (\n <div className={cn('flex flex-col items-center gap-y-2', className)}>\n <Upload size={20} className=\"text-muted-foreground\" />\n <p className=\"text-sm\">\n Upload{!!maxFiles && maxFiles > 1 ? ` ${maxFiles}` : ''} file\n {!maxFiles || maxFiles > 1 ? 's' : ''}\n </p>\n <div className=\"flex flex-col items-center gap-y-1\">\n <p className=\"text-xs text-muted-foreground\">\n Drag and drop or{' '}\n <a\n onClick={() => inputRef.current?.click()}\n className=\"underline cursor-pointer transition hover:text-foreground\"\n >\n select {maxFiles === 1 ? `file` : 'files'}\n </a>{' '}\n to upload\n </p>\n {maxFileSize !== Number.POSITIVE_INFINITY && (\n <p className=\"text-xs text-muted-foreground\">\n Maximum file size: {formatBytes(maxFileSize, 2)}\n </p>\n )}\n </div>\n </div>\n )\n}\n\nconst useDropzoneContext = () => {\n const context = useContext(DropzoneContext)\n\n if (!context) {\n throw new Error('useDropzoneContext must be used within a Dropzone')\n }\n\n return context\n}\n\nexport { Dropzone, DropzoneContent, DropzoneEmptyState, useDropzoneContext }\n",
"type": "registry:component"
},
{
"path": "registry/default/blocks/dropzone/hooks/use-supabase-upload.ts",
- "content": "import { createClient } from '@/registry/default/clients/nextjs/lib/supabase/client'\nimport { useCallback, useEffect, useState } from 'react'\nimport { FileError, FileRejection, useDropzone } from 'react-dropzone'\n\nconst supabase = createClient()\n\ninterface FileWithPreview extends File {\n preview?: string\n errors: readonly FileError[]\n}\n\ntype UseSupabaseUploadOptions = {\n bucketName: string\n path: string\n allowedMimeTypes?: string[]\n maxFileSize?: number\n maxFiles?: number\n}\n\ntype UseSupabaseUploadReturn = ReturnType<typeof useSupabaseUpload>\n\nconst useSupabaseUpload = (options: UseSupabaseUploadOptions) => {\n const {\n bucketName,\n path,\n allowedMimeTypes = [],\n maxFileSize = Number.POSITIVE_INFINITY,\n maxFiles = 0,\n } = options\n\n const [files, setFiles] = useState<FileWithPreview[]>([])\n const [loading, setLoading] = useState<boolean>(false)\n const [error, setError] = useState<string | null>(null)\n const [success, setSuccess] = useState(false)\n\n const onDrop = useCallback(\n (acceptedFiles: File[], fileRejections: FileRejection[]) => {\n const validFiles = acceptedFiles.map((file) => {\n ;(file as FileWithPreview).preview = URL.createObjectURL(file)\n ;(file as FileWithPreview).errors = []\n return file as FileWithPreview\n })\n\n const invalidFiles = fileRejections.map(({ file, errors }) => {\n ;(file as FileWithPreview).preview = URL.createObjectURL(file)\n ;(file as FileWithPreview).errors = errors\n return file as FileWithPreview\n })\n\n const newFiles = [...files, ...validFiles, ...invalidFiles]\n\n setFiles(newFiles)\n },\n [files, setFiles]\n )\n\n const dropzoneProps = useDropzone({\n onDrop,\n noClick: true,\n accept: allowedMimeTypes.reduce((acc, type) => ({ ...acc, [type]: [] }), {}),\n maxSize: maxFileSize,\n maxFiles: maxFiles,\n multiple: maxFiles !== 1,\n })\n\n const onUpload = useCallback(async () => {\n setError(null)\n setLoading(true)\n await Promise.all(\n files.map(async (file) => {\n const { error } = await supabase.storage\n .from(bucketName)\n .upload(`${path}/${file.name}`, file, {\n cacheControl: '3600',\n upsert: false,\n })\n if (error) {\n setError(error.message)\n } else {\n setSuccess(true)\n }\n })\n )\n setLoading(false)\n }, [files, path, bucketName, setError, setLoading])\n\n useEffect(() => {\n if (files.length === 0) {\n setError(null)\n }\n\n // If the number of files doesn't exceed the maxFiles parameter, remove the error 'Too many files' from each file\n if (files.length <= maxFiles) {\n let changed = false\n const newFiles = files.map((file) => {\n if (file.errors.some((e) => e.code === 'too-many-files')) {\n file.errors = file.errors.filter((e) => e.code !== 'too-many-files')\n changed = true\n }\n return file\n })\n if (changed) {\n setFiles(newFiles)\n }\n }\n }, [files.length, setFiles, maxFiles])\n\n return {\n files,\n setFiles,\n success,\n loading,\n error,\n setError,\n onUpload,\n maxFileSize: maxFileSize,\n maxFiles: maxFiles,\n ...dropzoneProps,\n }\n}\n\nexport { useSupabaseUpload, type UseSupabaseUploadOptions, type UseSupabaseUploadReturn }\n",
+ "content": "import { createClient } from '@/registry/default/clients/nextjs/lib/supabase/client'\nimport { useCallback, useEffect, useMemo, useState } from 'react'\nimport { type FileError, type FileRejection, useDropzone } from 'react-dropzone'\n\nconst supabase = createClient()\n\ninterface FileWithPreview extends File {\n preview?: string\n errors: readonly FileError[]\n}\n\ntype UseSupabaseUploadOptions = {\n /**\n * Name of bucket to upload files to in your Supabase project\n */\n bucketName: string\n /**\n * Folder to upload files to in the specified bucket within your Supabase project.\n *\n * Defaults to uploading files to the root of the bucket\n *\n * e.g If specified path is `test`, your file will be uploaded as `test/file_name`\n */\n path?: string\n /**\n * Allowed MIME types for each file upload (e.g `image/png`, `text/html`, etc). Wildcards are also supported (e.g `image/*`).\n *\n * Defaults to allowing uploading of all MIME types.\n */\n allowedMimeTypes?: string[]\n /**\n * Maximum upload size of each file allowed in bytes. (e.g 1000 bytes = 1 KB)\n */\n maxFileSize?: number\n /**\n * Maximum number of files allowed per upload.\n */\n maxFiles?: number\n /**\n * The number of seconds the asset is cached in the browser and in the Supabase CDN.\n *\n * This is set in the Cache-Control: max-age=<seconds> header. Defaults to 3600 seconds.\n */\n cacheControl?: number\n /**\n * When set to true, the file is overwritten if it exists.\n *\n * When set to false, an error is thrown if the object already exists. Defaults to `false`\n */\n upsert?: boolean\n}\n\ntype UseSupabaseUploadReturn = ReturnType<typeof useSupabaseUpload>\n\nconst useSupabaseUpload = (options: UseSupabaseUploadOptions) => {\n const {\n bucketName,\n path,\n allowedMimeTypes = [],\n maxFileSize = Number.POSITIVE_INFINITY,\n maxFiles = 1,\n cacheControl = 3600,\n upsert = false,\n } = options\n\n const [files, setFiles] = useState<FileWithPreview[]>([])\n const [loading, setLoading] = useState<boolean>(false)\n const [errors, setErrors] = useState<{ name: string; message: string }[]>([])\n const [successes, setSuccesses] = useState<string[]>([])\n\n const isSuccess = useMemo(() => {\n if (errors.length === 0 && successes.length === 0) {\n return false\n }\n if (errors.length === 0 && successes.length === files.length) {\n return true\n }\n return false\n }, [errors.length, successes.length, files.length])\n\n const onDrop = useCallback(\n (acceptedFiles: File[], fileRejections: FileRejection[]) => {\n const validFiles = acceptedFiles\n .filter((file) => !files.find((x) => x.name === file.name))\n .map((file) => {\n ;(file as FileWithPreview).preview = URL.createObjectURL(file)\n ;(file as FileWithPreview).errors = []\n return file as FileWithPreview\n })\n\n const invalidFiles = fileRejections.map(({ file, errors }) => {\n ;(file as FileWithPreview).preview = URL.createObjectURL(file)\n ;(file as FileWithPreview).errors = errors\n return file as FileWithPreview\n })\n\n const newFiles = [...files, ...validFiles, ...invalidFiles]\n\n setFiles(newFiles)\n },\n [files, setFiles]\n )\n\n const dropzoneProps = useDropzone({\n onDrop,\n noClick: true,\n accept: allowedMimeTypes.reduce((acc, type) => ({ ...acc, [type]: [] }), {}),\n maxSize: maxFileSize,\n maxFiles: maxFiles,\n multiple: maxFiles !== 1,\n })\n\n const onUpload = useCallback(async () => {\n setLoading(true)\n\n // [Joshen] This is to support handling partial successes\n // If any files didn't upload for any reason, hitting \"Upload\" again will only upload the files that had errors\n const filesWithErrors = errors.map((x) => x.name)\n const filesToUpload =\n filesWithErrors.length > 0\n ? [\n ...files.filter((f) => filesWithErrors.includes(f.name)),\n ...files.filter((f) => !successes.includes(f.name)),\n ]\n : files\n\n const responses = await Promise.all(\n filesToUpload.map(async (file) => {\n const { error } = await supabase.storage\n .from(bucketName)\n .upload(!!path ? `${path}/${file.name}` : file.name, file, {\n cacheControl: cacheControl.toString(),\n upsert,\n })\n if (error) {\n return { name: file.name, message: error.message }\n } else {\n return { name: file.name, message: undefined }\n }\n })\n )\n\n const responseErrors = responses.filter((x) => x.message !== undefined)\n // if there were errors previously, this function tried to upload the files again so we should clear/overwrite the existing errors.\n setErrors(responseErrors)\n\n const responseSuccesses = responses.filter((x) => x.message === undefined)\n const newSuccesses = Array.from(\n new Set([...successes, ...responseSuccesses.map((x) => x.name)])\n )\n setSuccesses(newSuccesses)\n\n setLoading(false)\n }, [files, path, bucketName, errors, successes])\n\n useEffect(() => {\n if (files.length === 0) {\n setErrors([])\n }\n\n // If the number of files doesn't exceed the maxFiles parameter, remove the error 'Too many files' from each file\n if (files.length <= maxFiles) {\n let changed = false\n const newFiles = files.map((file) => {\n if (file.errors.some((e) => e.code === 'too-many-files')) {\n file.errors = file.errors.filter((e) => e.code !== 'too-many-files')\n changed = true\n }\n return file\n })\n if (changed) {\n setFiles(newFiles)\n }\n }\n }, [files.length, setFiles, maxFiles])\n\n return {\n files,\n setFiles,\n successes,\n isSuccess,\n loading,\n errors,\n setErrors,\n onUpload,\n maxFileSize: maxFileSize,\n maxFiles: maxFiles,\n allowedMimeTypes,\n ...dropzoneProps,\n }\n}\n\nexport { useSupabaseUpload, type UseSupabaseUploadOptions, type UseSupabaseUploadReturn }\n",
"type": "registry:hook"
},
{
diff --git a/apps/ui-library/public/r/dropzone-react.json b/apps/ui-library/public/r/dropzone-react.json
index 496fb4bc8ea..e43f655c85e 100644
--- a/apps/ui-library/public/r/dropzone-react.json
+++ b/apps/ui-library/public/r/dropzone-react.json
@@ -17,12 +17,12 @@
"files": [
{
"path": "registry/default/blocks/dropzone/components/dropzone.tsx",
- "content": "'use client'\n\nimport { cn } from '@/lib/utils'\nimport { UseSupabaseUploadReturn } from '@/registry/default/blocks/dropzone/hooks/use-supabase-upload'\nimport { Button } from '@/registry/default/components/ui/button'\nimport { Tooltip, TooltipContent, TooltipTrigger } from '@/registry/default/components/ui/tooltip'\nimport { CheckCircle, CircleAlert, File, Loader2, Trash, Upload } from 'lucide-react'\nimport { createContext, PropsWithChildren, useCallback, useContext } from 'react'\n\ntype DropzoneContextType = Omit<UseSupabaseUploadReturn, 'getRootProps' | 'getInputProps'>\n\nconst DropzoneContext = createContext<DropzoneContextType | undefined>(undefined)\n\ntype DropzoneProps = UseSupabaseUploadReturn & {\n className?: string\n}\n\nconst Dropzone = ({\n className,\n children,\n getRootProps,\n getInputProps,\n ...restProps\n}: PropsWithChildren<DropzoneProps>) => {\n const isActive = restProps.isDragActive\n const isInvalid =\n (restProps.isDragActive && restProps.isDragReject) ||\n restProps.error ||\n restProps.files.some((file) => file.errors.length !== 0)\n\n return (\n <DropzoneContext.Provider value={{ ...restProps }}>\n <div\n {...getRootProps({\n className: cn(\n 'border-2 border-dashed border-gray-300 rounded-lg p-6 text-center bg-card transition-colors duration-300',\n className,\n isActive && 'border-primary bg-primary/10',\n isInvalid && 'border-destructive bg-destructive/10'\n ),\n })}\n >\n <input {...getInputProps()} />\n {children}\n </div>\n </DropzoneContext.Provider>\n )\n}\nconst DropzoneContent = ({ className }: { className?: string }) => {\n const { error, files, setFiles, onUpload, loading, success } = useDropzoneContext()\n\n const handleRemoveFile = useCallback(\n (fileName: string) => {\n setFiles(files.filter((file) => file.name !== fileName))\n },\n [files, setFiles]\n )\n\n if (success) {\n return (\n <div className={cn('flex flex-row items-center gap-1 justify-center', className)}>\n <CheckCircle className=\"text-primary text-lg font-medium\" />\n <p className=\"text-primary text-lg font-medium\">Files uploaded successfully</p>\n </div>\n )\n }\n\n return (\n <div className={cn('flex flex-col', className)}>\n {files.map((file) => {\n return (\n <div\n key={file.name}\n className=\"flex items-center gap-2 border-b p-2 first:mt-4 last:mb-4 \"\n >\n {file.type.startsWith('image/') ? (\n <div className=\"h-12 w-12 rounded border overflow-hidden flex-shrink-0 bg-muted\">\n <img src={file.preview} alt={file.name} className=\"object-cover\" />\n </div>\n ) : (\n <div className=\"h-12 w-12 rounded border bg-muted flex items-center justify-center\">\n <File />\n </div>\n )}\n <div className=\"grow flex items-center gap-2 justify-start\">\n <span className=\"text-sm\">{file.name}</span>\n {file.errors.length !== 0 && (\n <Tooltip>\n <TooltipTrigger asChild>\n <CircleAlert className=\"text-destructive\" />\n </TooltipTrigger>\n <TooltipContent>{file.errors.map((e) => e.message).join(', ')}</TooltipContent>\n </Tooltip>\n )}\n </div>\n\n <Button\n size=\"icon\"\n variant=\"destructive\"\n className=\"justify-self-end\"\n onClick={() => handleRemoveFile(file.name)}\n >\n <Trash />\n </Button>\n </div>\n )\n })}\n {files.length > 0 && (\n <div className=\"mt-2\">\n <Button\n variant=\"default\"\n onClick={onUpload}\n disabled={files.some((file) => file.errors.length !== 0) || loading}\n >\n {loading ? (\n <>\n <Loader2 className=\"mr-2 h-4 w-4 animate-spin\" />\n Uploading...\n </>\n ) : (\n <>Upload</>\n )}\n </Button>\n </div>\n )}\n {error && <p className=\"text-destructive text-lg font-medium\">{error}</p>}\n </div>\n )\n}\n\nconst DropzoneEmptyState = ({ className }: { className?: string }) => {\n const { files, maxFiles, maxFileSize, inputRef, success } = useDropzoneContext()\n\n if ((maxFiles !== 0 && files.length >= maxFiles) || success) {\n return null\n }\n\n return (\n <div className={cn('flex flex-col items-center', className)}>\n <div className=\"rounded-full bg-primary text-primary-foreground p-2\">\n <Upload />\n </div>\n <p className=\"text-lg font-medium\">\n Add or{' '}\n <a onClick={() => inputRef.current?.click()} className=\"underline cursor-pointer\">\n drop {maxFiles === 1 ? `file` : 'files'}\n </a>\n </p>\n {maxFileSize !== Number.POSITIVE_INFINITY && (\n <p className=\"text-sm text-muted-foreground mt-2\">Maximum file size: {maxFileSize} MB</p>\n )}\n </div>\n )\n}\n\nconst useDropzoneContext = () => {\n const context = useContext(DropzoneContext)\n\n if (!context) {\n throw new Error('useDropzoneContext must be used within a Dropzone')\n }\n\n return context\n}\n\nexport { Dropzone, DropzoneContent, DropzoneEmptyState, useDropzoneContext }\n",
+ "content": "'use client'\n\nimport { cn } from '@/lib/utils'\nimport { type UseSupabaseUploadReturn } from '@/registry/default/blocks/dropzone/hooks/use-supabase-upload'\nimport { Button } from '@/registry/default/components/ui/button'\nimport { CheckCircle, File, Loader2, Upload, X } from 'lucide-react'\nimport { createContext, type PropsWithChildren, useCallback, useContext } from 'react'\n\nexport const formatBytes = (\n bytes: number,\n decimals = 2,\n size?: 'bytes' | 'KB' | 'MB' | 'GB' | 'TB' | 'PB' | 'EB' | 'ZB' | 'YB'\n) => {\n const k = 1000\n const dm = decimals < 0 ? 0 : decimals\n const sizes = ['bytes', 'KB', 'MB', 'GB', 'TB', 'PB', 'EB', 'ZB', 'YB']\n\n if (bytes === 0 || bytes === undefined) return size !== undefined ? `0 ${size}` : '0 bytes'\n const i = size !== undefined ? sizes.indexOf(size) : Math.floor(Math.log(bytes) / Math.log(k))\n return parseFloat((bytes / Math.pow(k, i)).toFixed(dm)) + ' ' + sizes[i]\n}\n\ntype DropzoneContextType = Omit<UseSupabaseUploadReturn, 'getRootProps' | 'getInputProps'>\n\nconst DropzoneContext = createContext<DropzoneContextType | undefined>(undefined)\n\ntype DropzoneProps = UseSupabaseUploadReturn & {\n className?: string\n}\n\nconst Dropzone = ({\n className,\n children,\n getRootProps,\n getInputProps,\n ...restProps\n}: PropsWithChildren<DropzoneProps>) => {\n const isSuccess = restProps.isSuccess\n const isActive = restProps.isDragActive\n const isInvalid =\n (restProps.isDragActive && restProps.isDragReject) ||\n (restProps.errors.length > 0 && !restProps.isSuccess) ||\n restProps.files.some((file) => file.errors.length !== 0)\n\n return (\n <DropzoneContext.Provider value={{ ...restProps }}>\n <div\n {...getRootProps({\n className: cn(\n 'border-2 border-gray-300 rounded-lg p-6 text-center bg-card transition-colors duration-300 text-foreground',\n className,\n isSuccess ? 'border-solid' : 'border-dashed',\n isActive && 'border-primary bg-primary/10',\n isInvalid && 'border-destructive bg-destructive/10'\n ),\n })}\n >\n <input {...getInputProps()} />\n {children}\n </div>\n </DropzoneContext.Provider>\n )\n}\nconst DropzoneContent = ({ className }: { className?: string }) => {\n const {\n files,\n setFiles,\n onUpload,\n loading,\n successes,\n errors,\n maxFileSize,\n maxFiles,\n isSuccess,\n } = useDropzoneContext()\n\n const exceedMaxFiles = files.length > maxFiles\n\n const handleRemoveFile = useCallback(\n (fileName: string) => {\n setFiles(files.filter((file) => file.name !== fileName))\n },\n [files, setFiles]\n )\n\n if (isSuccess) {\n return (\n <div className={cn('flex flex-row items-center gap-x-2 justify-center', className)}>\n <CheckCircle size={16} className=\"text-primary\" />\n <p className=\"text-primary text-sm\">\n Successfully uploaded {files.length} file{files.length > 1 ? 's' : ''}\n </p>\n </div>\n )\n }\n\n return (\n <div className={cn('flex flex-col', className)}>\n {files.map((file, idx) => {\n const fileError = errors.find((e) => e.name === file.name)\n const isSuccessfullyUploaded = !!successes.find((e) => e === file.name)\n\n return (\n <div\n key={`${file.name}-${idx}`}\n className=\"flex items-center gap-x-4 border-b py-2 first:mt-4 last:mb-4 \"\n >\n {file.type.startsWith('image/') ? (\n <div className=\"h-10 w-10 rounded border overflow-hidden shrink-0 bg-muted flex items-center justify-center\">\n <img src={file.preview} alt={file.name} className=\"object-cover\" />\n </div>\n ) : (\n <div className=\"h-10 w-10 rounded border bg-muted flex items-center justify-center\">\n <File size={18} />\n </div>\n )}\n\n <div className=\"shrink grow flex flex-col items-start truncate\">\n <p title={file.name} className=\"text-sm truncate max-w-full\">\n {file.name}\n </p>\n {file.errors.length > 0 ? (\n <p className=\"text-xs text-destructive\">\n {file.errors\n .map((e) =>\n e.message.startsWith('File is larger than')\n ? `File is larger than ${formatBytes(maxFileSize, 2)} (Size: ${formatBytes(file.size, 2)})`\n : e.message\n )\n .join(', ')}\n </p>\n ) : loading && !isSuccessfullyUploaded ? (\n <p className=\"text-xs text-muted-foreground\">Uploading file...</p>\n ) : !!fileError ? (\n <p className=\"text-xs text-destructive\">Failed to upload: {fileError.message}</p>\n ) : isSuccessfullyUploaded ? (\n <p className=\"text-xs text-primary\">Successfully uploaded file</p>\n ) : (\n <p className=\"text-xs text-muted-foreground\">{formatBytes(file.size, 2)}</p>\n )}\n </div>\n\n {!loading && !isSuccessfullyUploaded && (\n <Button\n size=\"icon\"\n variant=\"link\"\n className=\"shrink-0 justify-self-end text-muted-foreground hover:text-foreground\"\n onClick={() => handleRemoveFile(file.name)}\n >\n <X />\n </Button>\n )}\n </div>\n )\n })}\n {exceedMaxFiles && (\n <p className=\"text-sm text-left mt-2 text-destructive\">\n You may upload only up to {maxFiles} files, please remove {files.length - maxFiles} file\n {files.length - maxFiles > 1 ? 's' : ''}.\n </p>\n )}\n {files.length > 0 && !exceedMaxFiles && (\n <div className=\"mt-2\">\n <Button\n variant=\"outline\"\n onClick={onUpload}\n disabled={files.some((file) => file.errors.length !== 0) || loading}\n >\n {loading ? (\n <>\n <Loader2 className=\"mr-2 h-4 w-4 animate-spin\" />\n Uploading...\n </>\n ) : (\n <>Upload files</>\n )}\n </Button>\n </div>\n )}\n </div>\n )\n}\n\nconst DropzoneEmptyState = ({ className }: { className?: string }) => {\n const { maxFiles, maxFileSize, inputRef, isSuccess } = useDropzoneContext()\n\n if (isSuccess) {\n return null\n }\n\n return (\n <div className={cn('flex flex-col items-center gap-y-2', className)}>\n <Upload size={20} className=\"text-muted-foreground\" />\n <p className=\"text-sm\">\n Upload{!!maxFiles && maxFiles > 1 ? ` ${maxFiles}` : ''} file\n {!maxFiles || maxFiles > 1 ? 's' : ''}\n </p>\n <div className=\"flex flex-col items-center gap-y-1\">\n <p className=\"text-xs text-muted-foreground\">\n Drag and drop or{' '}\n <a\n onClick={() => inputRef.current?.click()}\n className=\"underline cursor-pointer transition hover:text-foreground\"\n >\n select {maxFiles === 1 ? `file` : 'files'}\n </a>{' '}\n to upload\n </p>\n {maxFileSize !== Number.POSITIVE_INFINITY && (\n <p className=\"text-xs text-muted-foreground\">\n Maximum file size: {formatBytes(maxFileSize, 2)}\n </p>\n )}\n </div>\n </div>\n )\n}\n\nconst useDropzoneContext = () => {\n const context = useContext(DropzoneContext)\n\n if (!context) {\n throw new Error('useDropzoneContext must be used within a Dropzone')\n }\n\n return context\n}\n\nexport { Dropzone, DropzoneContent, DropzoneEmptyState, useDropzoneContext }\n",
"type": "registry:component"
},
{
"path": "registry/default/blocks/dropzone/hooks/use-supabase-upload.ts",
- "content": "import { createClient } from '@/registry/default/clients/nextjs/lib/supabase/client'\nimport { useCallback, useEffect, useState } from 'react'\nimport { FileError, FileRejection, useDropzone } from 'react-dropzone'\n\nconst supabase = createClient()\n\ninterface FileWithPreview extends File {\n preview?: string\n errors: readonly FileError[]\n}\n\ntype UseSupabaseUploadOptions = {\n bucketName: string\n path: string\n allowedMimeTypes?: string[]\n maxFileSize?: number\n maxFiles?: number\n}\n\ntype UseSupabaseUploadReturn = ReturnType<typeof useSupabaseUpload>\n\nconst useSupabaseUpload = (options: UseSupabaseUploadOptions) => {\n const {\n bucketName,\n path,\n allowedMimeTypes = [],\n maxFileSize = Number.POSITIVE_INFINITY,\n maxFiles = 0,\n } = options\n\n const [files, setFiles] = useState<FileWithPreview[]>([])\n const [loading, setLoading] = useState<boolean>(false)\n const [error, setError] = useState<string | null>(null)\n const [success, setSuccess] = useState(false)\n\n const onDrop = useCallback(\n (acceptedFiles: File[], fileRejections: FileRejection[]) => {\n const validFiles = acceptedFiles.map((file) => {\n ;(file as FileWithPreview).preview = URL.createObjectURL(file)\n ;(file as FileWithPreview).errors = []\n return file as FileWithPreview\n })\n\n const invalidFiles = fileRejections.map(({ file, errors }) => {\n ;(file as FileWithPreview).preview = URL.createObjectURL(file)\n ;(file as FileWithPreview).errors = errors\n return file as FileWithPreview\n })\n\n const newFiles = [...files, ...validFiles, ...invalidFiles]\n\n setFiles(newFiles)\n },\n [files, setFiles]\n )\n\n const dropzoneProps = useDropzone({\n onDrop,\n noClick: true,\n accept: allowedMimeTypes.reduce((acc, type) => ({ ...acc, [type]: [] }), {}),\n maxSize: maxFileSize,\n maxFiles: maxFiles,\n multiple: maxFiles !== 1,\n })\n\n const onUpload = useCallback(async () => {\n setError(null)\n setLoading(true)\n await Promise.all(\n files.map(async (file) => {\n const { error } = await supabase.storage\n .from(bucketName)\n .upload(`${path}/${file.name}`, file, {\n cacheControl: '3600',\n upsert: false,\n })\n if (error) {\n setError(error.message)\n } else {\n setSuccess(true)\n }\n })\n )\n setLoading(false)\n }, [files, path, bucketName, setError, setLoading])\n\n useEffect(() => {\n if (files.length === 0) {\n setError(null)\n }\n\n // If the number of files doesn't exceed the maxFiles parameter, remove the error 'Too many files' from each file\n if (files.length <= maxFiles) {\n let changed = false\n const newFiles = files.map((file) => {\n if (file.errors.some((e) => e.code === 'too-many-files')) {\n file.errors = file.errors.filter((e) => e.code !== 'too-many-files')\n changed = true\n }\n return file\n })\n if (changed) {\n setFiles(newFiles)\n }\n }\n }, [files.length, setFiles, maxFiles])\n\n return {\n files,\n setFiles,\n success,\n loading,\n error,\n setError,\n onUpload,\n maxFileSize: maxFileSize,\n maxFiles: maxFiles,\n ...dropzoneProps,\n }\n}\n\nexport { useSupabaseUpload, type UseSupabaseUploadOptions, type UseSupabaseUploadReturn }\n",
+ "content": "import { createClient } from '@/registry/default/clients/nextjs/lib/supabase/client'\nimport { useCallback, useEffect, useMemo, useState } from 'react'\nimport { type FileError, type FileRejection, useDropzone } from 'react-dropzone'\n\nconst supabase = createClient()\n\ninterface FileWithPreview extends File {\n preview?: string\n errors: readonly FileError[]\n}\n\ntype UseSupabaseUploadOptions = {\n /**\n * Name of bucket to upload files to in your Supabase project\n */\n bucketName: string\n /**\n * Folder to upload files to in the specified bucket within your Supabase project.\n *\n * Defaults to uploading files to the root of the bucket\n *\n * e.g If specified path is `test`, your file will be uploaded as `test/file_name`\n */\n path?: string\n /**\n * Allowed MIME types for each file upload (e.g `image/png`, `text/html`, etc). Wildcards are also supported (e.g `image/*`).\n *\n * Defaults to allowing uploading of all MIME types.\n */\n allowedMimeTypes?: string[]\n /**\n * Maximum upload size of each file allowed in bytes. (e.g 1000 bytes = 1 KB)\n */\n maxFileSize?: number\n /**\n * Maximum number of files allowed per upload.\n */\n maxFiles?: number\n /**\n * The number of seconds the asset is cached in the browser and in the Supabase CDN.\n *\n * This is set in the Cache-Control: max-age=<seconds> header. Defaults to 3600 seconds.\n */\n cacheControl?: number\n /**\n * When set to true, the file is overwritten if it exists.\n *\n * When set to false, an error is thrown if the object already exists. Defaults to `false`\n */\n upsert?: boolean\n}\n\ntype UseSupabaseUploadReturn = ReturnType<typeof useSupabaseUpload>\n\nconst useSupabaseUpload = (options: UseSupabaseUploadOptions) => {\n const {\n bucketName,\n path,\n allowedMimeTypes = [],\n maxFileSize = Number.POSITIVE_INFINITY,\n maxFiles = 1,\n cacheControl = 3600,\n upsert = false,\n } = options\n\n const [files, setFiles] = useState<FileWithPreview[]>([])\n const [loading, setLoading] = useState<boolean>(false)\n const [errors, setErrors] = useState<{ name: string; message: string }[]>([])\n const [successes, setSuccesses] = useState<string[]>([])\n\n const isSuccess = useMemo(() => {\n if (errors.length === 0 && successes.length === 0) {\n return false\n }\n if (errors.length === 0 && successes.length === files.length) {\n return true\n }\n return false\n }, [errors.length, successes.length, files.length])\n\n const onDrop = useCallback(\n (acceptedFiles: File[], fileRejections: FileRejection[]) => {\n const validFiles = acceptedFiles\n .filter((file) => !files.find((x) => x.name === file.name))\n .map((file) => {\n ;(file as FileWithPreview).preview = URL.createObjectURL(file)\n ;(file as FileWithPreview).errors = []\n return file as FileWithPreview\n })\n\n const invalidFiles = fileRejections.map(({ file, errors }) => {\n ;(file as FileWithPreview).preview = URL.createObjectURL(file)\n ;(file as FileWithPreview).errors = errors\n return file as FileWithPreview\n })\n\n const newFiles = [...files, ...validFiles, ...invalidFiles]\n\n setFiles(newFiles)\n },\n [files, setFiles]\n )\n\n const dropzoneProps = useDropzone({\n onDrop,\n noClick: true,\n accept: allowedMimeTypes.reduce((acc, type) => ({ ...acc, [type]: [] }), {}),\n maxSize: maxFileSize,\n maxFiles: maxFiles,\n multiple: maxFiles !== 1,\n })\n\n const onUpload = useCallback(async () => {\n setLoading(true)\n\n // [Joshen] This is to support handling partial successes\n // If any files didn't upload for any reason, hitting \"Upload\" again will only upload the files that had errors\n const filesWithErrors = errors.map((x) => x.name)\n const filesToUpload =\n filesWithErrors.length > 0\n ? [\n ...files.filter((f) => filesWithErrors.includes(f.name)),\n ...files.filter((f) => !successes.includes(f.name)),\n ]\n : files\n\n const responses = await Promise.all(\n filesToUpload.map(async (file) => {\n const { error } = await supabase.storage\n .from(bucketName)\n .upload(!!path ? `${path}/${file.name}` : file.name, file, {\n cacheControl: cacheControl.toString(),\n upsert,\n })\n if (error) {\n return { name: file.name, message: error.message }\n } else {\n return { name: file.name, message: undefined }\n }\n })\n )\n\n const responseErrors = responses.filter((x) => x.message !== undefined)\n // if there were errors previously, this function tried to upload the files again so we should clear/overwrite the existing errors.\n setErrors(responseErrors)\n\n const responseSuccesses = responses.filter((x) => x.message === undefined)\n const newSuccesses = Array.from(\n new Set([...successes, ...responseSuccesses.map((x) => x.name)])\n )\n setSuccesses(newSuccesses)\n\n setLoading(false)\n }, [files, path, bucketName, errors, successes])\n\n useEffect(() => {\n if (files.length === 0) {\n setErrors([])\n }\n\n // If the number of files doesn't exceed the maxFiles parameter, remove the error 'Too many files' from each file\n if (files.length <= maxFiles) {\n let changed = false\n const newFiles = files.map((file) => {\n if (file.errors.some((e) => e.code === 'too-many-files')) {\n file.errors = file.errors.filter((e) => e.code !== 'too-many-files')\n changed = true\n }\n return file\n })\n if (changed) {\n setFiles(newFiles)\n }\n }\n }, [files.length, setFiles, maxFiles])\n\n return {\n files,\n setFiles,\n successes,\n isSuccess,\n loading,\n errors,\n setErrors,\n onUpload,\n maxFileSize: maxFileSize,\n maxFiles: maxFiles,\n allowedMimeTypes,\n ...dropzoneProps,\n }\n}\n\nexport { useSupabaseUpload, type UseSupabaseUploadOptions, type UseSupabaseUploadReturn }\n",
"type": "registry:hook"
},
{
diff --git a/apps/ui-library/public/r/dropzone-tanstack.json b/apps/ui-library/public/r/dropzone-tanstack.json
index da0de6cb718..76898f4264b 100644
--- a/apps/ui-library/public/r/dropzone-tanstack.json
+++ b/apps/ui-library/public/r/dropzone-tanstack.json
@@ -18,12 +18,12 @@
"files": [
{
"path": "registry/default/blocks/dropzone/components/dropzone.tsx",
- "content": "'use client'\n\nimport { cn } from '@/lib/utils'\nimport { UseSupabaseUploadReturn } from '@/registry/default/blocks/dropzone/hooks/use-supabase-upload'\nimport { Button } from '@/registry/default/components/ui/button'\nimport { Tooltip, TooltipContent, TooltipTrigger } from '@/registry/default/components/ui/tooltip'\nimport { CheckCircle, CircleAlert, File, Loader2, Trash, Upload } from 'lucide-react'\nimport { createContext, PropsWithChildren, useCallback, useContext } from 'react'\n\ntype DropzoneContextType = Omit<UseSupabaseUploadReturn, 'getRootProps' | 'getInputProps'>\n\nconst DropzoneContext = createContext<DropzoneContextType | undefined>(undefined)\n\ntype DropzoneProps = UseSupabaseUploadReturn & {\n className?: string\n}\n\nconst Dropzone = ({\n className,\n children,\n getRootProps,\n getInputProps,\n ...restProps\n}: PropsWithChildren<DropzoneProps>) => {\n const isActive = restProps.isDragActive\n const isInvalid =\n (restProps.isDragActive && restProps.isDragReject) ||\n restProps.error ||\n restProps.files.some((file) => file.errors.length !== 0)\n\n return (\n <DropzoneContext.Provider value={{ ...restProps }}>\n <div\n {...getRootProps({\n className: cn(\n 'border-2 border-dashed border-gray-300 rounded-lg p-6 text-center bg-card transition-colors duration-300',\n className,\n isActive && 'border-primary bg-primary/10',\n isInvalid && 'border-destructive bg-destructive/10'\n ),\n })}\n >\n <input {...getInputProps()} />\n {children}\n </div>\n </DropzoneContext.Provider>\n )\n}\nconst DropzoneContent = ({ className }: { className?: string }) => {\n const { error, files, setFiles, onUpload, loading, success } = useDropzoneContext()\n\n const handleRemoveFile = useCallback(\n (fileName: string) => {\n setFiles(files.filter((file) => file.name !== fileName))\n },\n [files, setFiles]\n )\n\n if (success) {\n return (\n <div className={cn('flex flex-row items-center gap-1 justify-center', className)}>\n <CheckCircle className=\"text-primary text-lg font-medium\" />\n <p className=\"text-primary text-lg font-medium\">Files uploaded successfully</p>\n </div>\n )\n }\n\n return (\n <div className={cn('flex flex-col', className)}>\n {files.map((file) => {\n return (\n <div\n key={file.name}\n className=\"flex items-center gap-2 border-b p-2 first:mt-4 last:mb-4 \"\n >\n {file.type.startsWith('image/') ? (\n <div className=\"h-12 w-12 rounded border overflow-hidden flex-shrink-0 bg-muted\">\n <img src={file.preview} alt={file.name} className=\"object-cover\" />\n </div>\n ) : (\n <div className=\"h-12 w-12 rounded border bg-muted flex items-center justify-center\">\n <File />\n </div>\n )}\n <div className=\"grow flex items-center gap-2 justify-start\">\n <span className=\"text-sm\">{file.name}</span>\n {file.errors.length !== 0 && (\n <Tooltip>\n <TooltipTrigger asChild>\n <CircleAlert className=\"text-destructive\" />\n </TooltipTrigger>\n <TooltipContent>{file.errors.map((e) => e.message).join(', ')}</TooltipContent>\n </Tooltip>\n )}\n </div>\n\n <Button\n size=\"icon\"\n variant=\"destructive\"\n className=\"justify-self-end\"\n onClick={() => handleRemoveFile(file.name)}\n >\n <Trash />\n </Button>\n </div>\n )\n })}\n {files.length > 0 && (\n <div className=\"mt-2\">\n <Button\n variant=\"default\"\n onClick={onUpload}\n disabled={files.some((file) => file.errors.length !== 0) || loading}\n >\n {loading ? (\n <>\n <Loader2 className=\"mr-2 h-4 w-4 animate-spin\" />\n Uploading...\n </>\n ) : (\n <>Upload</>\n )}\n </Button>\n </div>\n )}\n {error && <p className=\"text-destructive text-lg font-medium\">{error}</p>}\n </div>\n )\n}\n\nconst DropzoneEmptyState = ({ className }: { className?: string }) => {\n const { files, maxFiles, maxFileSize, inputRef, success } = useDropzoneContext()\n\n if ((maxFiles !== 0 && files.length >= maxFiles) || success) {\n return null\n }\n\n return (\n <div className={cn('flex flex-col items-center', className)}>\n <div className=\"rounded-full bg-primary text-primary-foreground p-2\">\n <Upload />\n </div>\n <p className=\"text-lg font-medium\">\n Add or{' '}\n <a onClick={() => inputRef.current?.click()} className=\"underline cursor-pointer\">\n drop {maxFiles === 1 ? `file` : 'files'}\n </a>\n </p>\n {maxFileSize !== Number.POSITIVE_INFINITY && (\n <p className=\"text-sm text-muted-foreground mt-2\">Maximum file size: {maxFileSize} MB</p>\n )}\n </div>\n )\n}\n\nconst useDropzoneContext = () => {\n const context = useContext(DropzoneContext)\n\n if (!context) {\n throw new Error('useDropzoneContext must be used within a Dropzone')\n }\n\n return context\n}\n\nexport { Dropzone, DropzoneContent, DropzoneEmptyState, useDropzoneContext }\n",
+ "content": "'use client'\n\nimport { cn } from '@/lib/utils'\nimport { type UseSupabaseUploadReturn } from '@/registry/default/blocks/dropzone/hooks/use-supabase-upload'\nimport { Button } from '@/registry/default/components/ui/button'\nimport { CheckCircle, File, Loader2, Upload, X } from 'lucide-react'\nimport { createContext, type PropsWithChildren, useCallback, useContext } from 'react'\n\nexport const formatBytes = (\n bytes: number,\n decimals = 2,\n size?: 'bytes' | 'KB' | 'MB' | 'GB' | 'TB' | 'PB' | 'EB' | 'ZB' | 'YB'\n) => {\n const k = 1000\n const dm = decimals < 0 ? 0 : decimals\n const sizes = ['bytes', 'KB', 'MB', 'GB', 'TB', 'PB', 'EB', 'ZB', 'YB']\n\n if (bytes === 0 || bytes === undefined) return size !== undefined ? `0 ${size}` : '0 bytes'\n const i = size !== undefined ? sizes.indexOf(size) : Math.floor(Math.log(bytes) / Math.log(k))\n return parseFloat((bytes / Math.pow(k, i)).toFixed(dm)) + ' ' + sizes[i]\n}\n\ntype DropzoneContextType = Omit<UseSupabaseUploadReturn, 'getRootProps' | 'getInputProps'>\n\nconst DropzoneContext = createContext<DropzoneContextType | undefined>(undefined)\n\ntype DropzoneProps = UseSupabaseUploadReturn & {\n className?: string\n}\n\nconst Dropzone = ({\n className,\n children,\n getRootProps,\n getInputProps,\n ...restProps\n}: PropsWithChildren<DropzoneProps>) => {\n const isSuccess = restProps.isSuccess\n const isActive = restProps.isDragActive\n const isInvalid =\n (restProps.isDragActive && restProps.isDragReject) ||\n (restProps.errors.length > 0 && !restProps.isSuccess) ||\n restProps.files.some((file) => file.errors.length !== 0)\n\n return (\n <DropzoneContext.Provider value={{ ...restProps }}>\n <div\n {...getRootProps({\n className: cn(\n 'border-2 border-gray-300 rounded-lg p-6 text-center bg-card transition-colors duration-300 text-foreground',\n className,\n isSuccess ? 'border-solid' : 'border-dashed',\n isActive && 'border-primary bg-primary/10',\n isInvalid && 'border-destructive bg-destructive/10'\n ),\n })}\n >\n <input {...getInputProps()} />\n {children}\n </div>\n </DropzoneContext.Provider>\n )\n}\nconst DropzoneContent = ({ className }: { className?: string }) => {\n const {\n files,\n setFiles,\n onUpload,\n loading,\n successes,\n errors,\n maxFileSize,\n maxFiles,\n isSuccess,\n } = useDropzoneContext()\n\n const exceedMaxFiles = files.length > maxFiles\n\n const handleRemoveFile = useCallback(\n (fileName: string) => {\n setFiles(files.filter((file) => file.name !== fileName))\n },\n [files, setFiles]\n )\n\n if (isSuccess) {\n return (\n <div className={cn('flex flex-row items-center gap-x-2 justify-center', className)}>\n <CheckCircle size={16} className=\"text-primary\" />\n <p className=\"text-primary text-sm\">\n Successfully uploaded {files.length} file{files.length > 1 ? 's' : ''}\n </p>\n </div>\n )\n }\n\n return (\n <div className={cn('flex flex-col', className)}>\n {files.map((file, idx) => {\n const fileError = errors.find((e) => e.name === file.name)\n const isSuccessfullyUploaded = !!successes.find((e) => e === file.name)\n\n return (\n <div\n key={`${file.name}-${idx}`}\n className=\"flex items-center gap-x-4 border-b py-2 first:mt-4 last:mb-4 \"\n >\n {file.type.startsWith('image/') ? (\n <div className=\"h-10 w-10 rounded border overflow-hidden shrink-0 bg-muted flex items-center justify-center\">\n <img src={file.preview} alt={file.name} className=\"object-cover\" />\n </div>\n ) : (\n <div className=\"h-10 w-10 rounded border bg-muted flex items-center justify-center\">\n <File size={18} />\n </div>\n )}\n\n <div className=\"shrink grow flex flex-col items-start truncate\">\n <p title={file.name} className=\"text-sm truncate max-w-full\">\n {file.name}\n </p>\n {file.errors.length > 0 ? (\n <p className=\"text-xs text-destructive\">\n {file.errors\n .map((e) =>\n e.message.startsWith('File is larger than')\n ? `File is larger than ${formatBytes(maxFileSize, 2)} (Size: ${formatBytes(file.size, 2)})`\n : e.message\n )\n .join(', ')}\n </p>\n ) : loading && !isSuccessfullyUploaded ? (\n <p className=\"text-xs text-muted-foreground\">Uploading file...</p>\n ) : !!fileError ? (\n <p className=\"text-xs text-destructive\">Failed to upload: {fileError.message}</p>\n ) : isSuccessfullyUploaded ? (\n <p className=\"text-xs text-primary\">Successfully uploaded file</p>\n ) : (\n <p className=\"text-xs text-muted-foreground\">{formatBytes(file.size, 2)}</p>\n )}\n </div>\n\n {!loading && !isSuccessfullyUploaded && (\n <Button\n size=\"icon\"\n variant=\"link\"\n className=\"shrink-0 justify-self-end text-muted-foreground hover:text-foreground\"\n onClick={() => handleRemoveFile(file.name)}\n >\n <X />\n </Button>\n )}\n </div>\n )\n })}\n {exceedMaxFiles && (\n <p className=\"text-sm text-left mt-2 text-destructive\">\n You may upload only up to {maxFiles} files, please remove {files.length - maxFiles} file\n {files.length - maxFiles > 1 ? 's' : ''}.\n </p>\n )}\n {files.length > 0 && !exceedMaxFiles && (\n <div className=\"mt-2\">\n <Button\n variant=\"outline\"\n onClick={onUpload}\n disabled={files.some((file) => file.errors.length !== 0) || loading}\n >\n {loading ? (\n <>\n <Loader2 className=\"mr-2 h-4 w-4 animate-spin\" />\n Uploading...\n </>\n ) : (\n <>Upload files</>\n )}\n </Button>\n </div>\n )}\n </div>\n )\n}\n\nconst DropzoneEmptyState = ({ className }: { className?: string }) => {\n const { maxFiles, maxFileSize, inputRef, isSuccess } = useDropzoneContext()\n\n if (isSuccess) {\n return null\n }\n\n return (\n <div className={cn('flex flex-col items-center gap-y-2', className)}>\n <Upload size={20} className=\"text-muted-foreground\" />\n <p className=\"text-sm\">\n Upload{!!maxFiles && maxFiles > 1 ? ` ${maxFiles}` : ''} file\n {!maxFiles || maxFiles > 1 ? 's' : ''}\n </p>\n <div className=\"flex flex-col items-center gap-y-1\">\n <p className=\"text-xs text-muted-foreground\">\n Drag and drop or{' '}\n <a\n onClick={() => inputRef.current?.click()}\n className=\"underline cursor-pointer transition hover:text-foreground\"\n >\n select {maxFiles === 1 ? `file` : 'files'}\n </a>{' '}\n to upload\n </p>\n {maxFileSize !== Number.POSITIVE_INFINITY && (\n <p className=\"text-xs text-muted-foreground\">\n Maximum file size: {formatBytes(maxFileSize, 2)}\n </p>\n )}\n </div>\n </div>\n )\n}\n\nconst useDropzoneContext = () => {\n const context = useContext(DropzoneContext)\n\n if (!context) {\n throw new Error('useDropzoneContext must be used within a Dropzone')\n }\n\n return context\n}\n\nexport { Dropzone, DropzoneContent, DropzoneEmptyState, useDropzoneContext }\n",
"type": "registry:component"
},
{
"path": "registry/default/blocks/dropzone/hooks/use-supabase-upload.ts",
- "content": "import { createClient } from '@/registry/default/clients/nextjs/lib/supabase/client'\nimport { useCallback, useEffect, useState } from 'react'\nimport { FileError, FileRejection, useDropzone } from 'react-dropzone'\n\nconst supabase = createClient()\n\ninterface FileWithPreview extends File {\n preview?: string\n errors: readonly FileError[]\n}\n\ntype UseSupabaseUploadOptions = {\n bucketName: string\n path: string\n allowedMimeTypes?: string[]\n maxFileSize?: number\n maxFiles?: number\n}\n\ntype UseSupabaseUploadReturn = ReturnType<typeof useSupabaseUpload>\n\nconst useSupabaseUpload = (options: UseSupabaseUploadOptions) => {\n const {\n bucketName,\n path,\n allowedMimeTypes = [],\n maxFileSize = Number.POSITIVE_INFINITY,\n maxFiles = 0,\n } = options\n\n const [files, setFiles] = useState<FileWithPreview[]>([])\n const [loading, setLoading] = useState<boolean>(false)\n const [error, setError] = useState<string | null>(null)\n const [success, setSuccess] = useState(false)\n\n const onDrop = useCallback(\n (acceptedFiles: File[], fileRejections: FileRejection[]) => {\n const validFiles = acceptedFiles.map((file) => {\n ;(file as FileWithPreview).preview = URL.createObjectURL(file)\n ;(file as FileWithPreview).errors = []\n return file as FileWithPreview\n })\n\n const invalidFiles = fileRejections.map(({ file, errors }) => {\n ;(file as FileWithPreview).preview = URL.createObjectURL(file)\n ;(file as FileWithPreview).errors = errors\n return file as FileWithPreview\n })\n\n const newFiles = [...files, ...validFiles, ...invalidFiles]\n\n setFiles(newFiles)\n },\n [files, setFiles]\n )\n\n const dropzoneProps = useDropzone({\n onDrop,\n noClick: true,\n accept: allowedMimeTypes.reduce((acc, type) => ({ ...acc, [type]: [] }), {}),\n maxSize: maxFileSize,\n maxFiles: maxFiles,\n multiple: maxFiles !== 1,\n })\n\n const onUpload = useCallback(async () => {\n setError(null)\n setLoading(true)\n await Promise.all(\n files.map(async (file) => {\n const { error } = await supabase.storage\n .from(bucketName)\n .upload(`${path}/${file.name}`, file, {\n cacheControl: '3600',\n upsert: false,\n })\n if (error) {\n setError(error.message)\n } else {\n setSuccess(true)\n }\n })\n )\n setLoading(false)\n }, [files, path, bucketName, setError, setLoading])\n\n useEffect(() => {\n if (files.length === 0) {\n setError(null)\n }\n\n // If the number of files doesn't exceed the maxFiles parameter, remove the error 'Too many files' from each file\n if (files.length <= maxFiles) {\n let changed = false\n const newFiles = files.map((file) => {\n if (file.errors.some((e) => e.code === 'too-many-files')) {\n file.errors = file.errors.filter((e) => e.code !== 'too-many-files')\n changed = true\n }\n return file\n })\n if (changed) {\n setFiles(newFiles)\n }\n }\n }, [files.length, setFiles, maxFiles])\n\n return {\n files,\n setFiles,\n success,\n loading,\n error,\n setError,\n onUpload,\n maxFileSize: maxFileSize,\n maxFiles: maxFiles,\n ...dropzoneProps,\n }\n}\n\nexport { useSupabaseUpload, type UseSupabaseUploadOptions, type UseSupabaseUploadReturn }\n",
+ "content": "import { createClient } from '@/registry/default/clients/nextjs/lib/supabase/client'\nimport { useCallback, useEffect, useMemo, useState } from 'react'\nimport { type FileError, type FileRejection, useDropzone } from 'react-dropzone'\n\nconst supabase = createClient()\n\ninterface FileWithPreview extends File {\n preview?: string\n errors: readonly FileError[]\n}\n\ntype UseSupabaseUploadOptions = {\n /**\n * Name of bucket to upload files to in your Supabase project\n */\n bucketName: string\n /**\n * Folder to upload files to in the specified bucket within your Supabase project.\n *\n * Defaults to uploading files to the root of the bucket\n *\n * e.g If specified path is `test`, your file will be uploaded as `test/file_name`\n */\n path?: string\n /**\n * Allowed MIME types for each file upload (e.g `image/png`, `text/html`, etc). Wildcards are also supported (e.g `image/*`).\n *\n * Defaults to allowing uploading of all MIME types.\n */\n allowedMimeTypes?: string[]\n /**\n * Maximum upload size of each file allowed in bytes. (e.g 1000 bytes = 1 KB)\n */\n maxFileSize?: number\n /**\n * Maximum number of files allowed per upload.\n */\n maxFiles?: number\n /**\n * The number of seconds the asset is cached in the browser and in the Supabase CDN.\n *\n * This is set in the Cache-Control: max-age=<seconds> header. Defaults to 3600 seconds.\n */\n cacheControl?: number\n /**\n * When set to true, the file is overwritten if it exists.\n *\n * When set to false, an error is thrown if the object already exists. Defaults to `false`\n */\n upsert?: boolean\n}\n\ntype UseSupabaseUploadReturn = ReturnType<typeof useSupabaseUpload>\n\nconst useSupabaseUpload = (options: UseSupabaseUploadOptions) => {\n const {\n bucketName,\n path,\n allowedMimeTypes = [],\n maxFileSize = Number.POSITIVE_INFINITY,\n maxFiles = 1,\n cacheControl = 3600,\n upsert = false,\n } = options\n\n const [files, setFiles] = useState<FileWithPreview[]>([])\n const [loading, setLoading] = useState<boolean>(false)\n const [errors, setErrors] = useState<{ name: string; message: string }[]>([])\n const [successes, setSuccesses] = useState<string[]>([])\n\n const isSuccess = useMemo(() => {\n if (errors.length === 0 && successes.length === 0) {\n return false\n }\n if (errors.length === 0 && successes.length === files.length) {\n return true\n }\n return false\n }, [errors.length, successes.length, files.length])\n\n const onDrop = useCallback(\n (acceptedFiles: File[], fileRejections: FileRejection[]) => {\n const validFiles = acceptedFiles\n .filter((file) => !files.find((x) => x.name === file.name))\n .map((file) => {\n ;(file as FileWithPreview).preview = URL.createObjectURL(file)\n ;(file as FileWithPreview).errors = []\n return file as FileWithPreview\n })\n\n const invalidFiles = fileRejections.map(({ file, errors }) => {\n ;(file as FileWithPreview).preview = URL.createObjectURL(file)\n ;(file as FileWithPreview).errors = errors\n return file as FileWithPreview\n })\n\n const newFiles = [...files, ...validFiles, ...invalidFiles]\n\n setFiles(newFiles)\n },\n [files, setFiles]\n )\n\n const dropzoneProps = useDropzone({\n onDrop,\n noClick: true,\n accept: allowedMimeTypes.reduce((acc, type) => ({ ...acc, [type]: [] }), {}),\n maxSize: maxFileSize,\n maxFiles: maxFiles,\n multiple: maxFiles !== 1,\n })\n\n const onUpload = useCallback(async () => {\n setLoading(true)\n\n // [Joshen] This is to support handling partial successes\n // If any files didn't upload for any reason, hitting \"Upload\" again will only upload the files that had errors\n const filesWithErrors = errors.map((x) => x.name)\n const filesToUpload =\n filesWithErrors.length > 0\n ? [\n ...files.filter((f) => filesWithErrors.includes(f.name)),\n ...files.filter((f) => !successes.includes(f.name)),\n ]\n : files\n\n const responses = await Promise.all(\n filesToUpload.map(async (file) => {\n const { error } = await supabase.storage\n .from(bucketName)\n .upload(!!path ? `${path}/${file.name}` : file.name, file, {\n cacheControl: cacheControl.toString(),\n upsert,\n })\n if (error) {\n return { name: file.name, message: error.message }\n } else {\n return { name: file.name, message: undefined }\n }\n })\n )\n\n const responseErrors = responses.filter((x) => x.message !== undefined)\n // if there were errors previously, this function tried to upload the files again so we should clear/overwrite the existing errors.\n setErrors(responseErrors)\n\n const responseSuccesses = responses.filter((x) => x.message === undefined)\n const newSuccesses = Array.from(\n new Set([...successes, ...responseSuccesses.map((x) => x.name)])\n )\n setSuccesses(newSuccesses)\n\n setLoading(false)\n }, [files, path, bucketName, errors, successes])\n\n useEffect(() => {\n if (files.length === 0) {\n setErrors([])\n }\n\n // If the number of files doesn't exceed the maxFiles parameter, remove the error 'Too many files' from each file\n if (files.length <= maxFiles) {\n let changed = false\n const newFiles = files.map((file) => {\n if (file.errors.some((e) => e.code === 'too-many-files')) {\n file.errors = file.errors.filter((e) => e.code !== 'too-many-files')\n changed = true\n }\n return file\n })\n if (changed) {\n setFiles(newFiles)\n }\n }\n }, [files.length, setFiles, maxFiles])\n\n return {\n files,\n setFiles,\n successes,\n isSuccess,\n loading,\n errors,\n setErrors,\n onUpload,\n maxFileSize: maxFileSize,\n maxFiles: maxFiles,\n allowedMimeTypes,\n ...dropzoneProps,\n }\n}\n\nexport { useSupabaseUpload, type UseSupabaseUploadOptions, type UseSupabaseUploadReturn }\n",
"type": "registry:hook"
},
{
diff --git a/apps/ui-library/registry/default/blocks/dropzone/components/dropzone.tsx b/apps/ui-library/registry/default/blocks/dropzone/components/dropzone.tsx
index 7004b3889ad..f60521afd9c 100644
--- a/apps/ui-library/registry/default/blocks/dropzone/components/dropzone.tsx
+++ b/apps/ui-library/registry/default/blocks/dropzone/components/dropzone.tsx
@@ -1,11 +1,24 @@
'use client'
import { cn } from '@/lib/utils'
-import { UseSupabaseUploadReturn } from '@/registry/default/blocks/dropzone/hooks/use-supabase-upload'
+import { type UseSupabaseUploadReturn } from '@/registry/default/blocks/dropzone/hooks/use-supabase-upload'
import { Button } from '@/registry/default/components/ui/button'
-import { Tooltip, TooltipContent, TooltipTrigger } from '@/registry/default/components/ui/tooltip'
-import { CheckCircle, CircleAlert, File, Loader2, Trash, Upload } from 'lucide-react'
-import { createContext, PropsWithChildren, useCallback, useContext } from 'react'
+import { CheckCircle, File, Loader2, Upload, X } from 'lucide-react'
+import { createContext, type PropsWithChildren, useCallback, useContext } from 'react'
+
+export const formatBytes = (
+ bytes: number,
+ decimals = 2,
+ size?: 'bytes' | 'KB' | 'MB' | 'GB' | 'TB' | 'PB' | 'EB' | 'ZB' | 'YB'
+) => {
+ const k = 1000
+ const dm = decimals < 0 ? 0 : decimals
+ const sizes = ['bytes', 'KB', 'MB', 'GB', 'TB', 'PB', 'EB', 'ZB', 'YB']
+
+ if (bytes === 0 || bytes === undefined) return size !== undefined ? `0 ${size}` : '0 bytes'
+ const i = size !== undefined ? sizes.indexOf(size) : Math.floor(Math.log(bytes) / Math.log(k))
+ return parseFloat((bytes / Math.pow(k, i)).toFixed(dm)) + ' ' + sizes[i]
+}
type DropzoneContextType = Omit<UseSupabaseUploadReturn, 'getRootProps' | 'getInputProps'>
@@ -22,10 +35,11 @@ const Dropzone = ({
getInputProps,
...restProps
}: PropsWithChildren<DropzoneProps>) => {
+ const isSuccess = restProps.isSuccess
const isActive = restProps.isDragActive
const isInvalid =
(restProps.isDragActive && restProps.isDragReject) ||
- restProps.error ||
+ (restProps.errors.length > 0 && !restProps.isSuccess) ||
restProps.files.some((file) => file.errors.length !== 0)
return (
@@ -33,8 +47,9 @@ const Dropzone = ({
<div
{...getRootProps({
className: cn(
- 'border-2 border-dashed border-gray-300 rounded-lg p-6 text-center bg-card transition-colors duration-300',
+ 'border-2 border-gray-300 rounded-lg p-6 text-center bg-card transition-colors duration-300 text-foreground',
className,
+ isSuccess ? 'border-solid' : 'border-dashed',
isActive && 'border-primary bg-primary/10',
isInvalid && 'border-destructive bg-destructive/10'
),
@@ -47,7 +62,19 @@ const Dropzone = ({
)
}
const DropzoneContent = ({ className }: { className?: string }) => {
- const { error, files, setFiles, onUpload, loading, success } = useDropzoneContext()
+ const {
+ files,
+ setFiles,
+ onUpload,
+ loading,
+ successes,
+ errors,
+ maxFileSize,
+ maxFiles,
+ isSuccess,
+ } = useDropzoneContext()
+
+ const exceedMaxFiles = files.length > maxFiles
const handleRemoveFile = useCallback(
(fileName: string) => {
@@ -56,59 +83,86 @@ const DropzoneContent = ({ className }: { className?: string }) => {
[files, setFiles]
)
- if (success) {
+ if (isSuccess) {
return (
- <div className={cn('flex flex-row items-center gap-1 justify-center', className)}>
- <CheckCircle className="text-primary text-lg font-medium" />
- <p className="text-primary text-lg font-medium">Files uploaded successfully</p>
+ <div className={cn('flex flex-row items-center gap-x-2 justify-center', className)}>
+ <CheckCircle size={16} className="text-primary" />
+ <p className="text-primary text-sm">
+ Successfully uploaded {files.length} file{files.length > 1 ? 's' : ''}
+ </p>
</div>
)
}
return (
<div className={cn('flex flex-col', className)}>
- {files.map((file) => {
+ {files.map((file, idx) => {
+ const fileError = errors.find((e) => e.name === file.name)
+ const isSuccessfullyUploaded = !!successes.find((e) => e === file.name)
+
return (
<div
- key={file.name}
- className="flex items-center gap-2 border-b p-2 first:mt-4 last:mb-4 "
+ key={`${file.name}-${idx}`}
+ className="flex items-center gap-x-4 border-b py-2 first:mt-4 last:mb-4 "
>
{file.type.startsWith('image/') ? (
- <div className="h-12 w-12 rounded border overflow-hidden flex-shrink-0 bg-muted">
+ <div className="h-10 w-10 rounded border overflow-hidden shrink-0 bg-muted flex items-center justify-center">
<img src={file.preview} alt={file.name} className="object-cover" />
</div>
) : (
- <div className="h-12 w-12 rounded border bg-muted flex items-center justify-center">
- <File />
+ <div className="h-10 w-10 rounded border bg-muted flex items-center justify-center">
+ <File size={18} />
</div>
)}
- <div className="grow flex items-center gap-2 justify-start">
- <span className="text-sm">{file.name}</span>
- {file.errors.length !== 0 && (
- <Tooltip>
- <TooltipTrigger asChild>
- <CircleAlert className="text-destructive" />
- </TooltipTrigger>
- <TooltipContent>{file.errors.map((e) => e.message).join(', ')}</TooltipContent>
- </Tooltip>
+
+ <div className="shrink grow flex flex-col items-start truncate">
+ <p title={file.name} className="text-sm truncate max-w-full">
+ {file.name}
+ </p>
+ {file.errors.length > 0 ? (
+ <p className="text-xs text-destructive">
+ {file.errors
+ .map((e) =>
+ e.message.startsWith('File is larger than')
+ ? `File is larger than ${formatBytes(maxFileSize, 2)} (Size: ${formatBytes(file.size, 2)})`
+ : e.message
+ )
+ .join(', ')}
+ </p>
+ ) : loading && !isSuccessfullyUploaded ? (
+ <p className="text-xs text-muted-foreground">Uploading file...</p>
+ ) : !!fileError ? (
+ <p className="text-xs text-destructive">Failed to upload: {fileError.message}</p>
+ ) : isSuccessfullyUploaded ? (
+ <p className="text-xs text-primary">Successfully uploaded file</p>
+ ) : (
+ <p className="text-xs text-muted-foreground">{formatBytes(file.size, 2)}</p>
)}
</div>
- <Button
- size="icon"
- variant="destructive"
- className="justify-self-end"
- onClick={() => handleRemoveFile(file.name)}
- >
- <Trash />
- </Button>
+ {!loading && !isSuccessfullyUploaded && (
+ <Button
+ size="icon"
+ variant="link"
+ className="shrink-0 justify-self-end text-muted-foreground hover:text-foreground"
+ onClick={() => handleRemoveFile(file.name)}
+ >
+ <X />
+ </Button>
+ )}
</div>
)
})}
- {files.length > 0 && (
+ {exceedMaxFiles && (
+ <p className="text-sm text-left mt-2 text-destructive">
+ You may upload only up to {maxFiles} files, please remove {files.length - maxFiles} file
+ {files.length - maxFiles > 1 ? 's' : ''}.
+ </p>
+ )}
+ {files.length > 0 && !exceedMaxFiles && (
<div className="mt-2">
<Button
- variant="default"
+ variant="outline"
onClick={onUpload}
disabled={files.some((file) => file.errors.length !== 0) || loading}
>
@@ -118,37 +172,46 @@ const DropzoneContent = ({ className }: { className?: string }) => {
Uploading...
</>
) : (
- <>Upload</>
+ <>Upload files</>
)}
</Button>
</div>
)}
- {error && <p className="text-destructive text-lg font-medium">{error}</p>}
</div>
)
}
const DropzoneEmptyState = ({ className }: { className?: string }) => {
- const { files, maxFiles, maxFileSize, inputRef, success } = useDropzoneContext()
+ const { maxFiles, maxFileSize, inputRef, isSuccess } = useDropzoneContext()
- if ((maxFiles !== 0 && files.length >= maxFiles) || success) {
+ if (isSuccess) {
return null
}
return (
- <div className={cn('flex flex-col items-center', className)}>
- <div className="rounded-full bg-primary text-primary-foreground p-2">
- <Upload />
- </div>
- <p className="text-lg font-medium">
- Add or{' '}
- <a onClick={() => inputRef.current?.click()} className="underline cursor-pointer">
- drop {maxFiles === 1 ? `file` : 'files'}
- </a>
+ <div className={cn('flex flex-col items-center gap-y-2', className)}>
+ <Upload size={20} className="text-muted-foreground" />
+ <p className="text-sm">
+ Upload{!!maxFiles && maxFiles > 1 ? ` ${maxFiles}` : ''} file
+ {!maxFiles || maxFiles > 1 ? 's' : ''}
</p>
- {maxFileSize !== Number.POSITIVE_INFINITY && (
- <p className="text-sm text-muted-foreground mt-2">Maximum file size: {maxFileSize} MB</p>
- )}
+ <div className="flex flex-col items-center gap-y-1">
+ <p className="text-xs text-muted-foreground">
+ Drag and drop or{' '}
+ <a
+ onClick={() => inputRef.current?.click()}
+ className="underline cursor-pointer transition hover:text-foreground"
+ >
+ select {maxFiles === 1 ? `file` : 'files'}
+ </a>{' '}
+ to upload
+ </p>
+ {maxFileSize !== Number.POSITIVE_INFINITY && (
+ <p className="text-xs text-muted-foreground">
+ Maximum file size: {formatBytes(maxFileSize, 2)}
+ </p>
+ )}
+ </div>
</div>
)
}
diff --git a/apps/ui-library/registry/default/blocks/dropzone/hooks/use-supabase-upload.ts b/apps/ui-library/registry/default/blocks/dropzone/hooks/use-supabase-upload.ts
index 437218d495c..113f6f75653 100644
--- a/apps/ui-library/registry/default/blocks/dropzone/hooks/use-supabase-upload.ts
+++ b/apps/ui-library/registry/default/blocks/dropzone/hooks/use-supabase-upload.ts
@@ -1,6 +1,6 @@
import { createClient } from '@/registry/default/clients/nextjs/lib/supabase/client'
-import { useCallback, useEffect, useState } from 'react'
-import { FileError, FileRejection, useDropzone } from 'react-dropzone'
+import { useCallback, useEffect, useMemo, useState } from 'react'
+import { type FileError, type FileRejection, useDropzone } from 'react-dropzone'
const supabase = createClient()
@@ -10,11 +10,44 @@ interface FileWithPreview extends File {
}
type UseSupabaseUploadOptions = {
+ /**
+ * Name of bucket to upload files to in your Supabase project
+ */
bucketName: string
- path: string
+ /**
+ * Folder to upload files to in the specified bucket within your Supabase project.
+ *
+ * Defaults to uploading files to the root of the bucket
+ *
+ * e.g If specified path is `test`, your file will be uploaded as `test/file_name`
+ */
+ path?: string
+ /**
+ * Allowed MIME types for each file upload (e.g `image/png`, `text/html`, etc). Wildcards are also supported (e.g `image/*`).
+ *
+ * Defaults to allowing uploading of all MIME types.
+ */
allowedMimeTypes?: string[]
+ /**
+ * Maximum upload size of each file allowed in bytes. (e.g 1000 bytes = 1 KB)
+ */
maxFileSize?: number
+ /**
+ * Maximum number of files allowed per upload.
+ */
maxFiles?: number
+ /**
+ * The number of seconds the asset is cached in the browser and in the Supabase CDN.
+ *
+ * This is set in the Cache-Control: max-age=<seconds> header. Defaults to 3600 seconds.
+ */
+ cacheControl?: number
+ /**
+ * When set to true, the file is overwritten if it exists.
+ *
+ * When set to false, an error is thrown if the object already exists. Defaults to `false`
+ */
+ upsert?: boolean
}
type UseSupabaseUploadReturn = ReturnType<typeof useSupabaseUpload>
@@ -25,21 +58,35 @@ const useSupabaseUpload = (options: UseSupabaseUploadOptions) => {
path,
allowedMimeTypes = [],
maxFileSize = Number.POSITIVE_INFINITY,
- maxFiles = 0,
+ maxFiles = 1,
+ cacheControl = 3600,
+ upsert = false,
} = options
const [files, setFiles] = useState<FileWithPreview[]>([])
const [loading, setLoading] = useState<boolean>(false)
- const [error, setError] = useState<string | null>(null)
- const [success, setSuccess] = useState(false)
+ const [errors, setErrors] = useState<{ name: string; message: string }[]>([])
+ const [successes, setSuccesses] = useState<string[]>([])
+
+ const isSuccess = useMemo(() => {
+ if (errors.length === 0 && successes.length === 0) {
+ return false
+ }
+ if (errors.length === 0 && successes.length === files.length) {
+ return true
+ }
+ return false
+ }, [errors.length, successes.length, files.length])
const onDrop = useCallback(
(acceptedFiles: File[], fileRejections: FileRejection[]) => {
- const validFiles = acceptedFiles.map((file) => {
- ;(file as FileWithPreview).preview = URL.createObjectURL(file)
- ;(file as FileWithPreview).errors = []
- return file as FileWithPreview
- })
+ const validFiles = acceptedFiles
+ .filter((file) => !files.find((x) => x.name === file.name))
+ .map((file) => {
+ ;(file as FileWithPreview).preview = URL.createObjectURL(file)
+ ;(file as FileWithPreview).errors = []
+ return file as FileWithPreview
+ })
const invalidFiles = fileRejections.map(({ file, errors }) => {
;(file as FileWithPreview).preview = URL.createObjectURL(file)
@@ -64,29 +111,51 @@ const useSupabaseUpload = (options: UseSupabaseUploadOptions) => {
})
const onUpload = useCallback(async () => {
- setError(null)
setLoading(true)
- await Promise.all(
- files.map(async (file) => {
+
+ // [Joshen] This is to support handling partial successes
+ // If any files didn't upload for any reason, hitting "Upload" again will only upload the files that had errors
+ const filesWithErrors = errors.map((x) => x.name)
+ const filesToUpload =
+ filesWithErrors.length > 0
+ ? [
+ ...files.filter((f) => filesWithErrors.includes(f.name)),
+ ...files.filter((f) => !successes.includes(f.name)),
+ ]
+ : files
+
+ const responses = await Promise.all(
+ filesToUpload.map(async (file) => {
const { error } = await supabase.storage
.from(bucketName)
- .upload(`${path}/${file.name}`, file, {
- cacheControl: '3600',
- upsert: false,
+ .upload(!!path ? `${path}/${file.name}` : file.name, file, {
+ cacheControl: cacheControl.toString(),
+ upsert,
})
if (error) {
- setError(error.message)
+ return { name: file.name, message: error.message }
} else {
- setSuccess(true)
+ return { name: file.name, message: undefined }
}
})
)
+
+ const responseErrors = responses.filter((x) => x.message !== undefined)
+ // if there were errors previously, this function tried to upload the files again so we should clear/overwrite the existing errors.
+ setErrors(responseErrors)
+
+ const responseSuccesses = responses.filter((x) => x.message === undefined)
+ const newSuccesses = Array.from(
+ new Set([...successes, ...responseSuccesses.map((x) => x.name)])
+ )
+ setSuccesses(newSuccesses)
+
setLoading(false)
- }, [files, path, bucketName, setError, setLoading])
+ }, [files, path, bucketName, errors, successes])
useEffect(() => {
if (files.length === 0) {
- setError(null)
+ setErrors([])
}
// If the number of files doesn't exceed the maxFiles parameter, remove the error 'Too many files' from each file
@@ -108,13 +177,15 @@ const useSupabaseUpload = (options: UseSupabaseUploadOptions) => {
return {
files,
setFiles,
- success,
+ successes,
+ isSuccess,
loading,
- error,
- setError,
+ errors,
+ setErrors,
onUpload,
maxFileSize: maxFileSize,
maxFiles: maxFiles,
+ allowedMimeTypes,
...dropzoneProps,
}
}
diff --git a/apps/ui-library/registry/default/components/ui/button.tsx b/apps/ui-library/registry/default/components/ui/button.tsx
index a5c07b2acaa..f8dd6acec5d 100644
--- a/apps/ui-library/registry/default/components/ui/button.tsx
+++ b/apps/ui-library/registry/default/components/ui/button.tsx
@@ -1,6 +1,6 @@
-import * as React from 'react'
import { Slot } from '@radix-ui/react-slot'
import { cva, type VariantProps } from 'class-variance-authority'
+import * as React from 'react'
import { cn } from '@/lib/utils'
diff --git a/apps/ui-library/registry/default/examples/dropzone-demo.tsx b/apps/ui-library/registry/default/examples/dropzone-demo.tsx
index efe3d6ceaf5..d67968d207b 100644
--- a/apps/ui-library/registry/default/examples/dropzone-demo.tsx
+++ b/apps/ui-library/registry/default/examples/dropzone-demo.tsx
@@ -13,10 +13,11 @@ const FileUploadDemo = () => {
path: 'test',
allowedMimeTypes: ['image/*'],
maxFiles: 2,
+ maxFileSize: 1000 * 1000 * 10, // 10MB,
})
return (
- <div>
+ <div className="w-[500px]">
<Dropzone {...props}>
<DropzoneEmptyState />
<DropzoneContent />
diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml
index 2242731b9c0..e7176f03423 100644
--- a/pnpm-lock.yaml
+++ b/pnpm-lock.yaml
@@ -88,10 +88,10 @@ importers:
version: 1.2.0
next:
specifier: 'catalog:'
next-contentlayer2:
specifier: 0.4.6
next-themes:
specifier: ^0.3.0
@@ -868,7 +868,7 @@ importers:
version: 9.3.4
'@testing-library/jest-dom':
specifier: ^6.4.6
'@testing-library/react':
specifier: ^14.0.0
@@ -1011,7 +1011,7 @@ importers:
specifier: ^1.0.3
'@radix-ui/react-slot':
- specifier: ^1.0.2
+ specifier: ^1.1.2
version: 1.1.2(@types/[email protected])([email protected])
'@radix-ui/react-tooltip':
specifier: ^1.0.7
@@ -1036,10 +1036,10 @@ importers:
version: 0.436.0([email protected])
next:
specifier: 'catalog:'
next-contentlayer2:
specifier: 0.4.6
next-themes:
specifier: ^0.3.0
@@ -1124,7 +1124,7 @@ importers:
version: link:../../packages/config
fumadocs-ui:
specifier: ^15.1.0
lodash:
specifier: ^4.17.21
version: 4.17.21
@@ -1930,7 +1930,7 @@ importers:
version: 3.6.1
'@testing-library/jest-dom':
specifier: ^6.1.3
'@testing-library/react':
specifier: ^14.0.0
@@ -2147,7 +2147,7 @@ importers:
version: link:../api-types
next-router-mock:
specifier: ^0.9.13
typescript:
specifier: ~5.5.0
version: 5.5.2
@@ -9026,7 +9026,6 @@ packages:
resolution: {integrity: sha512-t0q23FIpvHDTtnORW+bDJziGsal5uh9RJTJ1fyH8drd4lICOoXhJ5pLMUZ5C0VQei6dNmwTzzoTRgMkO9JgHEQ==}
peerDependencies:
eslint: '>= 5'
- bundledDependencies: []
resolution: {integrity: sha512-BbPC0cuExzhiMo4Ff1BTVwHpjjv28C5R+btTOGaCRC7UEz801up0JadwkeSk5Ued6TG34uaczuVuH6qyy5YUxw==}
@@ -21071,22 +21070,6 @@ snapshots:
lz-string: 1.5.0
pretty-format: 27.5.1
- dependencies:
- '@adobe/css-tools': 4.4.0
- '@babel/runtime': 7.24.7
- aria-query: 5.3.0
- chalk: 3.0.0
- css.escape: 1.5.1
- dom-accessibility-api: 0.6.3
- lodash: 4.17.21
- redent: 3.0.0
- optionalDependencies:
- '@jest/globals': 29.7.0([email protected])
- '@types/jest': 29.5.5
-
dependencies:
'@adobe/css-tools': 4.4.0
@@ -21918,7 +21901,7 @@ snapshots:
sirv: 3.0.0
tinyglobby: 0.2.10
tinyrainbow: 2.0.0
'@vitest/[email protected]':
dependencies:
@@ -24655,7 +24638,7 @@ snapshots:
optional: true
dependencies:
'@formatjs/intl-localematcher': 0.6.0
'@orama/orama': 3.1.3
@@ -24673,14 +24656,14 @@ snapshots:
shiki: 3.2.1
unist-util-visit: 5.0.0
optionalDependencies:
react: 18.2.0
react-dom: 18.2.0([email protected])
transitivePeerDependencies:
- '@types/react'
- supports-color
dependencies:
'@radix-ui/react-collapsible': 1.1.3(@types/[email protected])(@types/[email protected])([email protected]([email protected]))([email protected])
@@ -24692,10 +24675,10 @@ snapshots:
'@radix-ui/react-slot': 1.1.2(@types/[email protected])([email protected])
class-variance-authority: 0.7.1
lodash.merge: 4.6.2
lucide-react: 0.482.0([email protected])
postcss-selector-parser: 7.1.0
react: 18.2.0
@@ -27999,7 +27982,7 @@ snapshots:
- markdown-wasm
- supports-color
dependencies:
'@contentlayer2/utils': 0.4.3
@@ -28047,7 +28030,7 @@ snapshots:
react: 18.2.0
dependencies:
react: 18.2.0