An AI-powered search engine with a generative UI
TypeScript generative-aigenerative-uinextjsollamareactsearxngshadcn-uitailwindcsstavilytypescriptupstashvercel-ai-sdk
feat ui file upload
oussema17h413d92ef5453
diff --git a/components/attachment-preview.tsx b/components/attachment-preview.tsxnew file mode 100644index 00000000..4be9c473--- /dev/null+++ b/components/attachment-preview.tsx@@ -0,0 +1,59 @@+'use client'++import React from 'react'++interface Attachment {+ name: string+ url: string+ contentType: string+}++interface AttachmentPreviewProps {+ attachments: Attachment[]+}++export const AttachmentPreview: React.FC<AttachmentPreviewProps> = ({+ attachments+}) => {+ if (!attachments?.length) return null++ return (+ <div className="mt-3 flex flex-wrap gap-4">+ {attachments.map((att, index) => {+ const isImage = att.contentType.startsWith('image/')+ const isPdf = att.contentType === 'application/pdf'++ return (+ <div key={index} className="max-w-xs break-words">+ {isImage ? (+ // eslint-disable-next-line @next/next/no-img-element+ <img+ src={att.url}+ alt={att.name}+ className="rounded border max-h-60 object-contain"+ />+ ) : isPdf ? (+ <a+ href={att.url}+ target="_blank"+ rel="noopener noreferrer"+ className="text-blue-600 underline"+ >+ π {att.name}+ </a>+ ) : (+ <a+ href={att.url}+ target="_blank"+ rel="noopener noreferrer"+ className="text-blue-600 underline"+ >+ π {att.name}+ </a>+ )}+ </div>+ )+ })}+ </div>+ )+}diff --git a/components/chat-panel.tsx b/components/chat-panel.tsxindex a92c8414..9e352e61 100644--- a/components/chat-panel.tsx+++ b/components/chat-panel.tsx@@ -5,14 +5,17 @@ import { cn } from '@/lib/utils'import { UIMessage, UseChatHelpers } from '@ai-sdk/react'import { ArrowUp, ChevronDown, MessageCirclePlus, Square } from 'lucide-react'import { useRouter } from 'next/navigation'-import { useEffect, useRef, useState } from 'react'+import { useCallback, useEffect, useRef, useState } from 'react'import Textarea from 'react-textarea-autosize'+import { toast } from 'sonner'import { useArtifact } from './artifact/artifact-context'import { EmptyScreen } from './empty-screen'+import { FileUploadButton } from './file-upload-button'import { ModelSelector } from './model-selector'import { SearchModeToggle } from './search-mode-toggle'import { Button } from './ui/button'import { IconLogo } from './ui/icons'+import { UploadedFileList } from './uploaded-fileList'interface ChatPanelProps {input: string@@ -29,6 +32,8 @@ interface ChatPanelProps {showScrollToBottomButton: boolean/** Reference to the scroll container */scrollContainerRef: React.RefObject<HTMLDivElement>+ uploadedFiles: File[]+ setUploadedFiles: React.Dispatch<React.SetStateAction<File[]>>}export function ChatPanel({@@ -43,6 +48,8 @@ export function ChatPanel({append,models,showScrollToBottomButton,+ uploadedFiles,+ setUploadedFiles,scrollContainerRef}: ChatPanelProps) {const [showEmptyScreen, setShowEmptyScreen] = useState(false)@@ -52,7 +59,6 @@ export function ChatPanel({const [isComposing, setIsComposing] = useState(false) // Composition stateconst [enterDisabled, setEnterDisabled] = useState(false) // Disable Enter after composition endsconst { close: closeArtifact } = useArtifact()-const isLoading = status === 'submitted' || status === 'streaming'const handleCompositionStart = () => setIsComposing(true)@@ -98,6 +104,12 @@ export function ChatPanel({// eslint-disable-next-line react-hooks/exhaustive-deps}, [query])+ const handleFileRemove = useCallback(+ (index: number) => {+ setUploadedFiles(prev => prev.filter((_, i) => i !== index))+ },+ [setUploadedFiles]+ )// Scroll to the bottom of the containerconst handleScrollToBottom = () => {const scrollContainer = scrollContainerRef.current@@ -124,6 +136,9 @@ export function ChatPanel({</p></div>)}+ {uploadedFiles.length > 0 && (+ <UploadedFileList files={uploadedFiles} onRemove={handleFileRemove} />+ )}<formonSubmit={handleSubmit}className={cn('max-w-3xl w-full mx-auto relative')}@@ -199,6 +214,17 @@ export function ChatPanel({<MessageCirclePlus className="size-4 group-hover:rotate-12 transition-all" /></Button>)}+ <FileUploadButton+ onFileSelect={files => {+ const total = uploadedFiles.length + files.length++ if (total > 3) {+ return toast.error('You can upload a maximum of 3 files.')+ }+ const allowedFiles = [...uploadedFiles, ...files].slice(0, 3)+ setUploadedFiles(allowedFiles)+ }}+ /><Buttontype={isLoading ? 'button' : 'submit'}size={'icon'}diff --git a/components/chat.tsx b/components/chat.tsxindex 1017cef5..83c5f55f 100644--- a/components/chat.tsx+++ b/components/chat.tsx@@ -10,6 +10,7 @@ import { toast } from 'sonner'import { z } from 'zod'import { ChatMessages } from './chat-messages'import { ChatPanel } from './chat-panel'+import { DragOverlay } from './drag-overlay'// Define section structureinterface ChatSection {@@ -31,6 +32,7 @@ export function Chat({}) {const scrollContainerRef = useRef<HTMLDivElement>(null)const [isAtBottom, setIsAtBottom] = useState(true)+ const [uploadedFiles, setUploadedFiles] = useState<File[]>([])const chatStore: any = defaultChatStore({api: '/api/chat',@@ -279,6 +281,56 @@ 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))+ }+ }+console.log('id', id)return (@@ -288,6 +340,9 @@ export function Chat({messages.length === 0 ? 'items-center justify-center' : '')}data-testid="full-chat"+ onDragOver={handleDragOver}+ onDragLeave={handleDragLeave}+ onDrop={handleDrop}><ChatMessagessections={sections}@@ -311,8 +366,11 @@ export function Chat({append={append}models={models}showScrollToBottomButton={!isAtBottom}+ uploadedFiles={uploadedFiles}+ setUploadedFiles={setUploadedFiles}scrollContainerRef={scrollContainerRef}/>+ <DragOverlay visible={isDragging} /></div>)}diff --git a/components/drag-overlay.tsx b/components/drag-overlay.tsxnew file mode 100644index 00000000..d4149913--- /dev/null+++ b/components/drag-overlay.tsx@@ -0,0 +1,19 @@+'use client'+import { cn } from '@/lib/utils'+import { UploadCloud } from 'lucide-react'++export function DragOverlay({ visible }: { visible: boolean }) {+ return (+ <div+ className={cn(+ 'absolute inset-0 z-40 flex items-center justify-center backdrop-blur-md transition-opacity duration-200 pointer-events-none',+ visible ? 'opacity-100' : 'opacity-0'+ )}+ >+ <div className="text-center text-muted-foreground">+ <UploadCloud className="mx-auto mb-4 w-10 h-10" />+ <p className="text-lg font-semibold">Drop files here</p>+ </div>+ </div>+ )+}diff --git a/components/file-upload-button.tsx b/components/file-upload-button.tsxnew file mode 100644index 00000000..c1c08e46--- /dev/null+++ b/components/file-upload-button.tsx@@ -0,0 +1,88 @@+'use client'++import { cn } from '@/lib/utils'+import { Paperclip } from 'lucide-react'+import { useRef, useState } from 'react'+import { toast } from 'sonner'+import { Button } from './ui/button'++const allowedImageTypes = ['image/png', 'image/jpeg', 'image/gif', 'image/webp']+const allowedOtherTypes = [+ 'application/pdf',+ 'application/msword',+ 'application/vnd.openxmlformats-officedocument.wordprocessingml.document'+]++const isAllowedFileType = (file: File) =>+ allowedImageTypes.includes(file.type) || allowedOtherTypes.includes(file.type)++export function FileUploadButton({+ onFileSelect+}: {+ onFileSelect: (files: File[]) => void+}) {+ const inputRef = useRef<HTMLInputElement>(null)+ const [isDragging, setIsDragging] = useState(false)++ const handleFiles = (files: FileList | null) => {+ if (!files) return++ const fileArray = Array.from(files).slice(0, 4)++ const validFiles = fileArray.filter(isAllowedFileType)+ const rejected = fileArray.filter(f => !isAllowedFileType(f))++ if (rejected.length > 0) {+ toast.error(+ 'Some files were not accepted: ' + rejected.map(f => f.name).join(', ')+ )+ }++ if (validFiles.length > 0) {+ onFileSelect(validFiles)+ }+ }++ const handleDrop = (e: React.DragEvent) => {+ e.preventDefault()+ e.stopPropagation()+ setIsDragging(false)+ handleFiles(e.dataTransfer.files)+ }++ return (+ <div+ onDragOver={e => {+ e.preventDefault()+ setIsDragging(true)+ }}+ onDragLeave={() => setIsDragging(false)}+ onDrop={handleDrop}+ className={cn(+ 'relative rounded-full',+ isDragging && 'ring-2 ring-blue-500 ring-offset-2'+ )}+ title="Drag and drop or click to upload"+ >+ <input+ ref={inputRef}+ type="file"+ accept="image/*,.pdf,.doc,.docx"+ hidden+ multiple+ onChange={e => {+ handleFiles(e.target.files)+ e.target.value = ''+ }}+ />+ <Button+ variant="outline"+ size="icon"+ className="rounded-full"+ onClick={() => inputRef.current?.click()}+ >+ <Paperclip size={18} />+ </Button>+ </div>+ )+}diff --git a/components/render-message.tsx b/components/render-message.tsxindex 297c0466..f4b43533 100644--- a/components/render-message.tsx+++ b/components/render-message.tsx@@ -15,6 +15,11 @@ interface RenderMessageProps {addToolResult?: (params: { toolCallId: string; result: any }) => voidonUpdateMessage?: (messageId: string, newContent: string) => Promise<void>reload?: (messageId: string) => Promise<void | string | null | undefined>+ attachments?: {+ name: string+ url: string+ contentType: string+ }[]}export function RenderMessage({@@ -27,7 +32,8 @@ export function RenderMessage({status,addToolResult,onUpdateMessage,- reload+ reload,+ attachments}: RenderMessageProps) {if (message.role === 'user') {return (@@ -35,6 +41,7 @@ export function RenderMessage({message={message}messageId={messageId}onUpdateMessage={onUpdateMessage}+ attachments={attachments}/>)}diff --git a/components/uploaded-fileList.tsx b/components/uploaded-fileList.tsxnew file mode 100644index 00000000..c7cb82f1--- /dev/null+++ b/components/uploaded-fileList.tsx@@ -0,0 +1,56 @@+'use client'++import { X } from 'lucide-react'+import Image from 'next/image'+import React from 'react'++interface UploadedFileListProps {+ files: File[]+ onRemove: (index: number) => void+}++export const UploadedFileList = React.memo(function UploadedFileList({+ files,+ onRemove+}: UploadedFileListProps) {+ return (+ <div className="w-full flex justify-center py-4">+ <div className="flex gap-6 overflow-x-auto">+ {files.map((file, index) => (+ <div+ key={index}+ className="relative w-28 flex-shrink-0 flex flex-col items-center"+ >+ <div className="relative w-28 h-20 rounded-lg overflow-hidden shadow border bg-muted/20 dark:bg-muted/10">+ {file.type.startsWith('image/') ? (+ <Image+ src={URL.createObjectURL(file)}+ alt={`file-${index}`}+ fill+ className="object-cover"+ sizes="112px"+ />+ ) : (+ <div className="w-full h-full flex items-center justify-center text-sm font-semibold bg-gray-300 dark:bg-gray-700">+ {file.name.split('.').pop()?.toUpperCase()}+ </div>+ )}++ <button+ type="button"+ onClick={() => onRemove(index)}+ className="absolute top-1 right-1 bg-black/40 hover:bg-red-600 text-white rounded-full p-1"+ >+ <X size={12} />+ </button>+ </div>++ <div className="mt-2 text-xs text-center text-foreground truncate w-full">+ {file.name}+ </div>+ </div>+ ))}+ </div>+ </div>+ )+})diff --git a/components/user-message.tsx b/components/user-message.tsxindex a39930cc..a3831d12 100644--- a/components/user-message.tsx+++ b/components/user-message.tsx@@ -5,6 +5,7 @@ import { UIMessage } from '@ai-sdk/react'import { Pencil } from 'lucide-react'import React, { useState } from 'react'import TextareaAutosize from 'react-textarea-autosize'+import { AttachmentPreview } from './attachment-preview'import { CollapsibleMessage } from './collapsible-message'import { Button } from './ui/button'@@ -12,12 +13,18 @@ type UserMessageProps = {message: UIMessagemessageId?: stringonUpdateMessage?: (messageId: string, newContent: string) => Promise<void>+ attachments?: {+ name: string+ url: string+ contentType: string+ }[]}export const UserMessage: React.FC<UserMessageProps> = ({message,messageId,- onUpdateMessage+ onUpdateMessage,+ attachments}) => {const messageText =message.parts@@ -55,6 +62,9 @@ export const UserMessage: React.FC<UserMessageProps> = ({className="flex-1 break-words w-full group outline-none relative"tabIndex={0}>+ {!isEditing && attachments && attachments.length > 0 && (+ <AttachmentPreview attachments={attachments} />+ )}{isEditing ? (<div className="flex flex-col gap-2"><TextareaAutosize