import axios from "axios"; import { useEffect, useRef, useState } from "react"; import TextareaAutosize from "react-textarea-autosize"; import { useChatStore, useMessageStore, useUserStore } from "../../store"; import { UserRole } from "../../types"; import { generateUUID } from "../../utils"; import Icon from "../Icon"; const MessageTextarea = () => { const userStore = useUserStore(); const chatStore = useChatStore(); const messageStore = useMessageStore(); const [value, setValue] = useState(""); const textareaRef = useRef(null); useEffect(() => { if (textareaRef.current) { textareaRef.current.focus(); } }, []); const handleChange = (e: React.ChangeEvent) => { setValue(e.target.value); }; const handleSend = async () => { if (!chatStore.currentChat) { return; } const currentChat = chatStore.currentChat; messageStore.addMessage({ id: generateUUID(), chatId: currentChat.id, creatorId: userStore.currentUser.id, createdAt: Date.now(), content: value, }); setValue(""); textareaRef.current!.value = ""; const messageList = messageStore.getState().messageList.filter((message) => message.chatId === currentChat.id); const { data } = await axios.post("/api/chat", { messages: messageList.map((message) => ({ role: message.creatorId === userStore.currentUser.id ? UserRole.User : UserRole.Assistant, content: message.content, })), }); messageStore.addMessage({ id: generateUUID(), chatId: currentChat.id, creatorId: currentChat.userId, createdAt: Date.now(), content: data, }); }; return (
); }; export default MessageTextarea;