'use client'; import type { UIMessage } from 'ai'; import type { UseChatHelpers } from '@ai-sdk/react'; import cx from 'classnames'; import type React from 'react'; import { useRef, useEffect, useState, useCallback, type Dispatch, type SetStateAction, type ChangeEvent, memo, } from 'react'; import { toast } from 'sonner'; import { useLocalStorage, useWindowSize } from 'usehooks-ts'; import { type Attachment, sanitizeUIMessages } from '@/lib/utils'; import { ArrowUpIcon, PaperclipIcon, StopIcon } from './icons'; import { PreviewAttachment } from './preview-attachment'; import { Button } from './ui/button'; import { Textarea } from './ui/textarea'; import { SuggestedActions } from './suggested-actions'; import equal from 'fast-deep-equal'; import { useGT } from 'gt-next'; type UploadResponse = { url: string; pathname: string; contentType: string; }; function PureMultimodalInput({ chatId, input, setInput, isLoading, stop, attachments, setAttachments, messages, setMessages, append, className, }: { chatId: string; input: string; setInput: (value: string) => void; isLoading: boolean; stop: () => void; attachments: Array; setAttachments: Dispatch>>; messages: Array; setMessages: UseChatHelpers['setMessages']; append: UseChatHelpers['sendMessage']; className?: string; }) { const textareaRef = useRef(null); const hasFocusedTextareaRef = useRef(false); const t = useGT(); const { width } = useWindowSize(); const setTextareaRef = useCallback((textarea: HTMLTextAreaElement | null) => { textareaRef.current = textarea; if (textarea && !hasFocusedTextareaRef.current) { textarea.focus(); hasFocusedTextareaRef.current = true; } }, []); useEffect(() => { if (textareaRef.current) { adjustHeight(); } }, []); const adjustHeight = () => { if (textareaRef.current) { textareaRef.current.style.height = 'auto'; textareaRef.current.style.height = `${ textareaRef.current.scrollHeight + 2 }px`; } }; const resetHeight = () => { if (textareaRef.current) { textareaRef.current.style.height = 'auto'; textareaRef.current.style.height = '98px'; } }; const [localStorageInput, setLocalStorageInput] = useLocalStorage( 'input', '' ); useEffect(() => { if (textareaRef.current) { const domValue = textareaRef.current.value; // Prefer DOM value over localStorage to handle hydration const finalValue = domValue || localStorageInput || ''; setInput(finalValue); adjustHeight(); } // Only run once after hydration // eslint-disable-next-line react-hooks/exhaustive-deps }, []); useEffect(() => { setLocalStorageInput(input); }, [input, setLocalStorageInput]); const handleInput = (event: React.ChangeEvent) => { setInput(event.target.value); adjustHeight(); }; const fileInputRef = useRef(null); const [uploadQueue, setUploadQueue] = useState>([]); const submitForm = useCallback(() => { window.history.replaceState({}, '', `/chat/${chatId}`); append({ text: input, files: attachments.map((attachment) => ({ type: 'file' as const, url: attachment.url, filename: attachment.name, mediaType: attachment.contentType, })), }); setInput(''); setAttachments([]); setLocalStorageInput(''); resetHeight(); if (width && width > 768) { textareaRef.current?.focus(); } }, [ input, setInput, attachments, append, setAttachments, setLocalStorageInput, width, chatId, ]); const uploadFile = useCallback( async (file: File): Promise => { const formData = new FormData(); formData.append('file', file); try { const response = await fetch('/api/files/upload', { method: 'POST', body: formData, }); if (response.ok) { const data = (await response.json()) as UploadResponse; const { url, pathname, contentType } = data; return { url, name: pathname, contentType: contentType, }; } const { error } = (await response.json()) as { error?: string }; toast.error(error ?? t('Upload failed')); } catch { toast.error(t('Failed to upload file, please try again!')); } }, [t] ); const handleFileChange = useCallback( async (event: ChangeEvent) => { const files = Array.from(event.target.files || []); setUploadQueue(files.map((file) => file.name)); try { const uploadPromises = files.map((file) => uploadFile(file)); const uploadedAttachments = await Promise.all(uploadPromises); const successfullyUploadedAttachments = uploadedAttachments.filter( (attachment) => attachment !== undefined ); setAttachments((currentAttachments) => [ ...currentAttachments, ...successfullyUploadedAttachments, ]); } catch (error) { console.error('Error uploading files!', error); } finally { setUploadQueue([]); } }, [setAttachments, uploadFile] ); return (
{messages.length === 0 && attachments.length === 0 && uploadQueue.length === 0 && ( )} {(attachments.length > 0 || uploadQueue.length > 0) && (
{attachments.map((attachment) => ( ))} {uploadQueue.map((filename) => ( ))}
)}