import { useEffect, useRef, useState } from "react"; import { toast } from "react-hot-toast"; import TextareaAutosize from "react-textarea-autosize"; import { useChatStore, useConnectionStore, useMessageStore, useUserStore } from "@/store"; import { CreatorRole } from "@/types"; import { generateUUID } from "@/utils"; import Icon from "../Icon"; interface Props { disabled?: boolean; sendMessage: () => Promise; } const MessageTextarea = (props: Props) => { const { disabled, sendMessage } = props; const connectionStore = useConnectionStore(); const userStore = useUserStore(); const chatStore = useChatStore(); const messageStore = useMessageStore(); const [value, setValue] = useState(""); const [isInIME, setIsInIME] = useState(false); const textareaRef = useRef(null); useEffect(() => { if (textareaRef.current) { textareaRef.current.focus(); } }, []); const handleChange = (e: React.ChangeEvent) => { setValue(e.target.value); }; const handleSend = async () => { let chat = chatStore.currentChat; if (!chat) { const currentConnectionCtx = connectionStore.currentConnectionCtx; if (!currentConnectionCtx) { chat = chatStore.createChat(); } else { chat = chatStore.createChat(currentConnectionCtx.connection.id, currentConnectionCtx.database?.name); } } if (!value) { toast.error("Please enter a message."); return; } if (disabled) { return; } messageStore.addMessage({ id: generateUUID(), chatId: chat.id, creatorId: userStore.currentUser.id, creatorRole: CreatorRole.User, createdAt: Date.now(), content: value, isGenerated: true, }); setValue(""); textareaRef.current!.value = ""; await sendMessage(); }; const handleKeyDown = (event: React.KeyboardEvent) => { if (event.key === "Enter" && !event.shiftKey && !isInIME) { event.preventDefault(); handleSend(); } }; return (
setIsInIME(true)} onCompositionEnd={() => setIsInIME(false)} onChange={handleChange} onKeyDown={handleKeyDown} />
); }; export default MessageTextarea;