import { useEffect, useRef, useState } from "react" import "./tailwind.css" import { ArrowUpOnSquareIcon, Cog6ToothIcon, XMarkIcon } from "@heroicons/react/20/solid" import { useForm } from "@mantine/form" import { useMutation } from "@tanstack/react-query" import axios from "axios" import logoImage from "data-base64:~assets/icon.png" import ReactMarkdown from "react-markdown" import { Link, useNavigate } from "react-router-dom" function Chat() { type Message = { isBot: boolean message: string } type History = { bot_response: string human_message: string } const [messages, setMessages] = useState([ { isBot: true, message: "Hi, I'm PageAssist Bot. How can I help you?" } ]) const [history, setHistory] = useState([]) const route = useNavigate() const form = useForm({ initialValues: { message: "", isBot: false } }) const divRef = useRef(null) useEffect(() => { divRef.current.scrollIntoView({ behavior: "smooth" }) }) const getHtmlFromParent = () => { window.parent.postMessage("pageassist-html", "*") return new Promise((resolve, reject) => { window.addEventListener("message", (event) => { if (event.data.type === "pageassist-html") { resolve(event.data.html) } else { reject("Error") } }) }) } const sendToBot = async (message: string) => { const html = await getHtmlFromParent() const response = await axios.post(process.env.PLASMO_PUBLIC_API_KEY!, { user_message: message, html: html, history: history }) return response.data } const { mutateAsync: sendToBotAsync, isLoading: isSending } = useMutation( sendToBot, { onSuccess: (data) => { setMessages([...messages, { isBot: true, message: data.bot_response }]) setHistory([...history, data]) }, onError: (error) => { setMessages([ ...messages, { isBot: true, message: "Something went wrong" } ]) } } ) return (
{/* Component Start */}
PageAssist
{messages.map((message, index) => { return (

{message.message}

) })} {isSending && (

Hold on, I'm looking...

)}
{ setMessages([...messages, values]) form.reset() await sendToBotAsync(values.message) })}>
) } export default Chat