import { useState } from "react"; import { RiSparkling2Fill } from "react-icons/ri"; import { GrSend } from "react-icons/gr"; import classNames from "classnames"; import { toast } from "react-toastify"; import Login from "../login/login"; import { defaultHTML } from "../../utils/consts"; function AskAI({ html, setHtml, onScrollToBottom, isAiWorking, setisAiWorking, }: { html: string; setHtml: (html: string) => void; onScrollToBottom: () => void; isAiWorking: boolean; setisAiWorking: React.Dispatch>; }) { const [open, setOpen] = useState(false); const [prompt, setPrompt] = useState(""); const [hasAsked, setHasAsked] = useState(false); const callAi = async () => { if (isAiWorking) return; setisAiWorking(true); let contentResponse = ""; try { const request = await fetch("/api/ask-ai", { method: "POST", body: JSON.stringify({ prompt, ...(html === defaultHTML ? {} : { html }), }), headers: { "Content-Type": "application/json", }, }); if (request && request.body) { if (!request.ok) { const res = await request.json(); if (res.openLogin) { setOpen(true); } else { // don't show toast if it's a login error toast.error(res.message); } setisAiWorking(false); return; } const reader = request.body.getReader(); const decoder = new TextDecoder("utf-8"); const read = async () => { const { done, value } = await reader.read(); if (done) { toast.success("AI responded successfully"); setPrompt(""); setisAiWorking(false); setHasAsked(true); return; } const chunk = decoder.decode(value, { stream: true }); contentResponse += chunk; const newHtml = contentResponse.match(/[\s\S]*/)?.[0]; if (newHtml) { setHtml(newHtml); if (newHtml?.length > 200) { onScrollToBottom(); } } read(); }; read(); } // eslint-disable-next-line @typescript-eslint/no-explicit-any } catch (error: any) { setisAiWorking(false); toast.error(error.message); if (error.openLogin) { setOpen(true); } } }; return (
setPrompt(e.target.value)} onKeyDown={(e) => { if (e.key === "Enter") { callAi(); } }} />
setOpen(false)} >

You reached the limit of free AI usage. Please login to continue.

); } export default AskAI;