import { useContext, useEffect, useRef, useState } from "react"; import { FiSend } from "react-icons/fi"; import { BsPlusLg } from "react-icons/bs"; import { RxHamburgerMenu } from "react-icons/rx"; import Message from "./Message"; import { homePage } from "./ChatUtils"; import MkdSDK from "Utils/MkdSDK"; import { GlobalContext } from "Context/Global"; import { AuthContext, tokenExpireError } from "Context/Auth"; const Chat = (props) => { const { toggleComponentVisibility, index, currentRoom } = props; const { state, dispatch } = useContext(GlobalContext); const { dispatch: authDispatch } = useContext(AuthContext); const [isLoading, setIsLoading] = useState(false); const [errorMessage, setErrorMessage] = useState(""); const [showEmptyChat, setShowEmptyChat] = useState(true); const [conversation, setConversation] = useState([]); const [message, setMessage] = useState(""); const [generating, setGenerating] = useState(false); const bottomOfChatRef = useRef(null); let sdk = new MkdSDK(); useEffect(() => { if (bottomOfChatRef.current) { bottomOfChatRef.current.scrollIntoView({ behavior: "smooth" }); } }, [conversation]); const sendMessage = async (e) => { // Don't send empty messages if (message.length < 1) { setErrorMessage("Please enter a message."); return; } else { setErrorMessage(""); dispatch({ type: "SETROOM", payload: { position: props.index, value: message }, }); } setIsLoading(true); // Add the message to the conversation setConversation([ ...conversation, { content: message, role: "user", content2: null, role2: "system" }, ]); // Clear the message & remove empty chat setMessage(""); setShowEmptyChat(false); try { setGenerating(true); const response = await sdk.chatGPT(message); if (response.ok) { const data = await response.json(); setGenerating(false); // Add the message to the conversation setConversation([ ...conversation, { content: message, role: "user", content2: data.Answer, role2: "system", }, ]); } else { console.error(response); setGenerating(false); setErrorMessage(response.statusText); } setIsLoading(false); } catch (error) { console.error(error); setGenerating(false); setErrorMessage(error.message); tokenExpireError( authDispatch, error?.response?.data?.messsage ? error?.response?.data?.messsage : error?.message ); setIsLoading(false); } }; const handleKeypress = (e) => { // It's triggers by pressing the enter key if (e.keyCode == 13 && !e.shiftKey) { sendMessage(e); e.preventDefault(); } }; return (

New chat

{!showEmptyChat && conversation.length > 0 ? (
) : null} {showEmptyChat ? (

ChatGPT

{homePage.map((item, index) => (
{item.icon}

{item.title}

{item.details.map((details, index) => (
{details}
))}
))}
) : null}