chatbot-template/components/multimodal-input.tsx

298 lines
7.7 KiB
TypeScript
Raw Normal View History

'use client';
2024-10-11 18:00:22 +05:30
2024-11-15 12:18:17 -05:00
import type {
Attachment,
ChatRequestOptions,
CreateMessage,
Message,
} from 'ai';
2024-10-30 16:01:24 +05:30
import cx from 'classnames';
2024-11-15 12:18:17 -05:00
import type React from 'react';
import {
2024-10-11 18:00:22 +05:30
useRef,
useEffect,
useState,
useCallback,
2024-11-15 12:18:17 -05:00
type Dispatch,
type SetStateAction,
type ChangeEvent,
memo,
} from 'react';
import { toast } from 'sonner';
import { useLocalStorage, useWindowSize } from 'usehooks-ts';
2024-10-11 18:00:22 +05:30
2024-10-30 16:01:24 +05:30
import { sanitizeUIMessages } from '@/lib/utils';
import { ArrowUpIcon, PaperclipIcon, StopIcon } from './icons';
import { PreviewAttachment } from './preview-attachment';
2024-11-15 10:14:25 -05:00
import { Button } from './ui/button';
import { Textarea } from './ui/textarea';
import { SuggestedActions } from './suggested-actions';
import equal from 'fast-deep-equal';
2024-10-11 18:00:22 +05:30
function PureMultimodalInput({
2024-11-05 17:15:51 +03:00
chatId,
2024-10-11 18:00:22 +05:30
input,
setInput,
isLoading,
stop,
attachments,
setAttachments,
messages,
2024-10-30 16:01:24 +05:30
setMessages,
2024-10-11 18:00:22 +05:30
append,
handleSubmit,
2024-10-30 16:01:24 +05:30
className,
2024-10-11 18:00:22 +05:30
}: {
2024-11-05 17:15:51 +03:00
chatId: string;
2024-10-11 18:00:22 +05:30
input: string;
setInput: (value: string) => void;
isLoading: boolean;
stop: () => void;
attachments: Array<Attachment>;
setAttachments: Dispatch<SetStateAction<Array<Attachment>>>;
messages: Array<Message>;
2024-10-30 16:01:24 +05:30
setMessages: Dispatch<SetStateAction<Array<Message>>>;
2024-10-11 18:00:22 +05:30
append: (
message: Message | CreateMessage,
2024-11-15 13:00:15 -05:00
chatRequestOptions?: ChatRequestOptions,
2024-10-11 18:00:22 +05:30
) => Promise<string | null | undefined>;
handleSubmit: (
event?: {
preventDefault?: () => void;
},
2024-11-15 13:00:15 -05:00
chatRequestOptions?: ChatRequestOptions,
2024-10-11 18:00:22 +05:30
) => void;
2024-10-30 16:01:24 +05:30
className?: string;
2024-10-11 18:00:22 +05:30
}) {
const textareaRef = useRef<HTMLTextAreaElement>(null);
const { width } = useWindowSize();
2024-10-11 18:00:22 +05:30
useEffect(() => {
if (textareaRef.current) {
adjustHeight();
}
}, []);
const adjustHeight = () => {
if (textareaRef.current) {
textareaRef.current.style.height = 'auto';
2024-10-11 18:00:22 +05:30
textareaRef.current.style.height = `${textareaRef.current.scrollHeight + 2}px`;
}
};
const [localStorageInput, setLocalStorageInput] = useLocalStorage(
'input',
2024-11-15 13:00:15 -05:00
'',
);
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]);
2024-10-11 18:00:22 +05:30
const handleInput = (event: React.ChangeEvent<HTMLTextAreaElement>) => {
setInput(event.target.value);
adjustHeight();
};
const fileInputRef = useRef<HTMLInputElement>(null);
const [uploadQueue, setUploadQueue] = useState<Array<string>>([]);
const submitForm = useCallback(() => {
2024-11-05 17:15:51 +03:00
window.history.replaceState({}, '', `/chat/${chatId}`);
2024-10-11 18:00:22 +05:30
handleSubmit(undefined, {
experimental_attachments: attachments,
});
setAttachments([]);
setLocalStorageInput('');
if (width && width > 768) {
textareaRef.current?.focus();
}
2024-11-05 17:15:51 +03:00
}, [
attachments,
handleSubmit,
setAttachments,
setLocalStorageInput,
width,
chatId,
]);
2024-10-11 18:00:22 +05:30
const uploadFile = async (file: File) => {
const formData = new FormData();
formData.append('file', file);
2024-10-11 18:00:22 +05:30
try {
2024-11-15 12:18:17 -05:00
const response = await fetch('/api/files/upload', {
method: 'POST',
2024-10-11 18:00:22 +05:30
body: formData,
});
if (response.ok) {
const data = await response.json();
const { url, pathname, contentType } = data;
return {
url,
name: pathname,
contentType: contentType,
};
}
2024-11-15 12:18:17 -05:00
const { error } = await response.json();
toast.error(error);
2024-10-11 18:00:22 +05:30
} catch (error) {
toast.error('Failed to upload file, please try again!');
2024-10-11 18:00:22 +05:30
}
};
const handleFileChange = useCallback(
async (event: ChangeEvent<HTMLInputElement>) => {
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(
2024-11-15 13:00:15 -05:00
(attachment) => attachment !== undefined,
2024-10-11 18:00:22 +05:30
);
setAttachments((currentAttachments) => [
...currentAttachments,
...successfullyUploadedAttachments,
]);
} catch (error) {
console.error('Error uploading files!', error);
2024-10-11 18:00:22 +05:30
} finally {
setUploadQueue([]);
}
},
2024-11-15 13:00:15 -05:00
[setAttachments],
2024-10-11 18:00:22 +05:30
);
return (
<div className="relative w-full flex flex-col gap-4">
{messages.length === 0 &&
attachments.length === 0 &&
uploadQueue.length === 0 && (
<SuggestedActions append={append} chatId={chatId} />
2024-10-11 18:00:22 +05:30
)}
<input
type="file"
className="fixed -top-4 -left-4 size-0.5 opacity-0 pointer-events-none"
ref={fileInputRef}
multiple
onChange={handleFileChange}
tabIndex={-1}
/>
{(attachments.length > 0 || uploadQueue.length > 0) && (
2024-11-07 01:14:11 +03:00
<div className="flex flex-row gap-2 overflow-x-scroll items-end">
2024-10-11 18:00:22 +05:30
{attachments.map((attachment) => (
<PreviewAttachment key={attachment.url} attachment={attachment} />
))}
{uploadQueue.map((filename) => (
<PreviewAttachment
key={filename}
attachment={{
url: '',
2024-10-11 18:00:22 +05:30
name: filename,
contentType: '',
2024-10-11 18:00:22 +05:30
}}
isUploading={true}
/>
))}
</div>
)}
<Textarea
ref={textareaRef}
placeholder="Send a message..."
value={input}
onChange={handleInput}
2024-10-30 16:01:24 +05:30
className={cx(
'min-h-[24px] max-h-[calc(75dvh)] overflow-hidden resize-none rounded-xl !text-base bg-muted',
2024-11-15 13:00:15 -05:00
className,
2024-10-30 16:01:24 +05:30
)}
2024-10-11 18:00:22 +05:30
rows={3}
2024-11-05 11:54:57 +03:00
autoFocus
2024-10-11 18:00:22 +05:30
onKeyDown={(event) => {
if (event.key === 'Enter' && !event.shiftKey) {
2024-10-11 18:00:22 +05:30
event.preventDefault();
if (isLoading) {
toast.error('Please wait for the model to finish its response!');
2024-10-11 18:00:22 +05:30
} else {
submitForm();
}
}
}}
/>
{isLoading ? (
<Button
2024-11-06 19:12:46 +03:00
className="rounded-full p-1.5 h-fit absolute bottom-2 right-2 m-0.5 border dark:border-zinc-600"
2024-10-11 18:00:22 +05:30
onClick={(event) => {
event.preventDefault();
stop();
2024-10-30 16:01:24 +05:30
setMessages((messages) => sanitizeUIMessages(messages));
2024-10-11 18:00:22 +05:30
}}
>
<StopIcon size={14} />
</Button>
) : (
<Button
2024-11-06 19:12:46 +03:00
className="rounded-full p-1.5 h-fit absolute bottom-2 right-2 m-0.5 border dark:border-zinc-600"
2024-10-11 18:00:22 +05:30
onClick={(event) => {
event.preventDefault();
submitForm();
2024-10-11 18:00:22 +05:30
}}
disabled={input.length === 0 || uploadQueue.length > 0}
>
<ArrowUpIcon size={14} />
</Button>
)}
<Button
2024-11-06 19:12:46 +03:00
className="rounded-full p-1.5 h-fit absolute bottom-2 right-11 m-0.5 dark:border-zinc-700"
2024-10-11 18:00:22 +05:30
onClick={(event) => {
event.preventDefault();
fileInputRef.current?.click();
}}
variant="outline"
disabled={isLoading}
>
<PaperclipIcon size={14} />
</Button>
</div>
);
}
export const MultimodalInput = memo(
PureMultimodalInput,
(prevProps, nextProps) => {
if (prevProps.input !== nextProps.input) return false;
if (prevProps.isLoading !== nextProps.isLoading) return false;
if (!equal(prevProps.attachments, nextProps.attachments)) return false;
return true;
},
);