import { useEffect, useRef, useState } from "react"; import { toast } from "react-hot-toast"; import TextareaAutosize from "react-textarea-autosize"; import { useChatStore, useMessageStore, useUserStore } from "../../store"; import { generateUUID } from "../../utils"; import Icon from "../Icon"; interface Props { sendMessage: () => Promise; } const MessageTextarea = (props: Props) => { const { sendMessage } = props; 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 () => { if (!chatStore.currentChat) { toast.error("Please select a chat first."); return; } if (!value) { toast.error("Please enter a message."); return; } const currentChat = chatStore.currentChat; if (currentChat.isRequesting) { toast.error("Please wait for the previous message to be sent."); return; } messageStore.addMessage({ id: generateUUID(), chatId: currentChat.id, creatorId: userStore.currentUser.id, createdAt: Date.now(), content: value, }); 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;