Skip to content

An AI-powered search engine with a generative UI

feat add api route/ seperate drag logic into a hook

oussamadhouib84a7da5ebc1b
diff --git a/app/api/upload/route.ts b/app/api/upload/route.ts
new file mode 100644
index 00000000..3b1d7cbc
--- /dev/null
+++ b/app/api/upload/route.ts
@@ -0,0 +1,83 @@
+import { getCurrentUserId } from '@/lib/auth/get-current-user'
+import { createClient } from '@/lib/supabase/server'
+import { NextRequest, NextResponse } from 'next/server'
+
+const MAX_FILE_SIZE = 5 * 1024 * 1024 // 5MB
+const ALLOWED_TYPES = ['image/jpeg', 'image/png', 'application/pdf']
+
+export async function POST(req: NextRequest) {
+ try {
+ const userId = await getCurrentUserId()
+ if (!userId) {
+ return NextResponse.json({ error: 'Unauthorized' }, { status: 401 })
+ }
+ const contentType = req.headers.get('content-type') || ''
+ if (!contentType.includes('multipart/form-data')) {
+ return NextResponse.json(
+ { error: 'Invalid content type' },
+ { status: 400 }
+ )
+ }
+
+ const formData = await req.formData()
+ const file = formData.get('file') as File
+
+ if (!file) {
+ return NextResponse.json({ error: 'File is required' }, { status: 400 })
+ }
+
+ if (file.size > MAX_FILE_SIZE) {
+ return NextResponse.json(
+ { error: 'File too large (max 5MB)' },
+ { status: 400 }
+ )
+ }
+
+ if (!ALLOWED_TYPES.includes(file.type)) {
+ return NextResponse.json(
+ { error: 'Unsupported file type' },
+ { status: 400 }
+ )
+ }
+ const result = await uploadFileToSupabase(file)
+ return NextResponse.json({ success: true, file: result }, { status: 200 })
+ } catch (err: any) {
+ console.error('Upload Error:', err)
+ return NextResponse.json(
+ { error: 'Upload failed', message: err.message },
+ { status: 500 }
+ )
+ }
+}
+
+function sanitizeFilename(filename: string) {
+ return filename.replace(/[^a-z0-9.\-_]/gi, '_').toLowerCase()
+}
+
+async function uploadFileToSupabase(file: File) {
+ const sanitizedFileName = sanitizeFilename(file.name)
+ const filePath = `${Date.now()}-${sanitizedFileName}`
+ const supabase = await createClient()
+ const { error } = await supabase.storage
+ .from('chat-uploads')
+ .upload(filePath, file, {
+ cacheControl: '3600',
+ upsert: false,
+ contentType: file.type
+ })
+
+ if (error) {
+ throw new Error('Upload failed: ' + error.message)
+ }
+
+ const {
+ data: { publicUrl }
+ } = supabase.storage.from('user-uploads').getPublicUrl(filePath)
+
+ return {
+ name: file.name,
+ url: publicUrl,
+ contentType: file.type,
+ key: filePath
+ }
+}
diff --git a/components/chat.tsx b/components/chat.tsx
index 83c5f55f..3e13f7c5 100644
--- a/components/chat.tsx
+++ b/components/chat.tsx
@@ -1,5 +1,6 @@
'use client'
+import { useFileDropzone } from '@/hooks/use-file-dropzone'
import { deleteTrailingMessages } from '@/lib/actions/chat-db'
import { Model } from '@/lib/types/models'
import { cn, generateUUID } from '@/lib/utils'
@@ -281,56 +282,11 @@ export function Chat({
handleSubmit(e)
}
- const [isDragging, setIsDragging] = useState(false)
-
- const handleDragOver = (e: React.DragEvent<HTMLDivElement>) => {
- e.preventDefault()
- setIsDragging(true)
- }
-
- const handleDragLeave = (e: React.DragEvent<HTMLDivElement>) => {
- if (!e.currentTarget.contains(e.relatedTarget as Node)) {
- setIsDragging(false)
- }
- }
-
- const handleDrop = (e: React.DragEvent<HTMLDivElement>) => {
- e.preventDefault()
- setIsDragging(false)
-
- const files = Array.from(e.dataTransfer.files).slice(0, 4)
-
- const allowed = files.filter(file =>
- [
- 'image/png',
- 'image/jpeg',
- 'image/gif',
- 'image/webp',
- 'application/pdf',
- 'application/msword',
- 'application/vnd.openxmlformats-officedocument.wordprocessingml.document'
- ].includes(file.type)
- )
-
- const rejected = files.filter(file => !allowed.includes(file))
-
- if (rejected.length > 0) {
- toast.error(
- 'Some files were not accepted: ' + rejected.map(f => f.name).join(', ')
- )
- }
-
- const total = uploadedFiles.length + allowed.length
- if (total > 3) {
- toast.error('You can upload a maximum of 3 files.')
- return
- }
-
- if (allowed.length > 0) {
- setUploadedFiles(prev => [...prev, ...allowed].slice(0, 3))
- }
- }
-
+ const { isDragging, handleDragOver, handleDragLeave, handleDrop } =
+ useFileDropzone({
+ uploadedFiles,
+ setUploadedFiles
+ })
console.log('id', id)
return (
diff --git a/hooks/use-file-dropzone.ts b/hooks/use-file-dropzone.ts
new file mode 100644
index 00000000..5db4a796
--- /dev/null
+++ b/hooks/use-file-dropzone.ts
@@ -0,0 +1,65 @@
+import { useCallback, useState } from 'react'
+import { toast } from 'sonner'
+type UseFileDropzoneProps = {
+ uploadedFiles: File[]
+ setUploadedFiles: React.Dispatch<React.SetStateAction<File[]>>
+ maxFiles?: number
+ allowedTypes?: string[]
+}
+
+export function useFileDropzone({
+ uploadedFiles,
+ setUploadedFiles,
+ maxFiles = 3,
+ allowedTypes = ['image/png', 'image/jpeg', 'application/pdf']
+}: UseFileDropzoneProps) {
+ const [isDragging, setIsDragging] = useState(false)
+
+ const handleDragOver = useCallback((e: React.DragEvent<HTMLDivElement>) => {
+ e.preventDefault()
+ setIsDragging(true)
+ }, [])
+
+ const handleDragLeave = useCallback((e: React.DragEvent<HTMLDivElement>) => {
+ if (!e.currentTarget.contains(e.relatedTarget as Node)) {
+ setIsDragging(false)
+ }
+ }, [])
+
+ const handleDrop = useCallback(
+ (e: React.DragEvent<HTMLDivElement>) => {
+ e.preventDefault()
+ setIsDragging(false)
+
+ const files = Array.from(e.dataTransfer.files).slice(0, maxFiles)
+
+ const allowed = files.filter(file => allowedTypes.includes(file.type))
+ const rejected = files.filter(file => !allowed.includes(file))
+
+ if (rejected.length > 0) {
+ toast.error(
+ 'Some files were not accepted: ' +
+ rejected.map(f => f.name).join(', ')
+ )
+ }
+
+ const total = uploadedFiles.length + allowed.length
+ if (total > maxFiles) {
+ toast.error(`You can upload a maximum of ${maxFiles} files.`)
+ return
+ }
+
+ if (allowed.length > 0) {
+ setUploadedFiles(prev => [...prev, ...allowed].slice(0, maxFiles))
+ }
+ },
+ [allowedTypes, maxFiles, uploadedFiles, setUploadedFiles]
+ )
+
+ return {
+ isDragging,
+ handleDragOver,
+ handleDragLeave,
+ handleDrop
+ }
+}