import {AlertContext} from "@/context/AlertContext"; import {SessionContext} from "@/context/SessionContext"; import System from "@/lib/models/System"; import {ChangeEvent, JSX, useContext, useState} from "react"; import {AIDictionary, DictionaryAIResponse} from "@/lib/models/QuillSense"; import InputField from "@/components/form/InputField"; import {faLock, faMagnifyingGlass, faSpellCheck} from "@fortawesome/free-solid-svg-icons"; import TextInput from "@/components/form/TextInput"; import {FontAwesomeIcon} from "@fortawesome/react-fontawesome"; import {useTranslations} from "next-intl"; import {LangContext, LangContextProps} from "@/context/LangContext"; import {AIUsageContext, AIUsageContextProps} from "@/context/AIUsageContext"; export default function Dictionary({hasKey}: { hasKey: boolean }): JSX.Element { const {session} = useContext(SessionContext); const {errorMessage} = useContext(AlertContext); const t = useTranslations(); const {lang} = useContext(LangContext) const {setTotalCredits,setTotalPrice} = useContext(AIUsageContext) const [wordToCheck, setWordToCheck] = useState(''); const [inProgress, setInProgress] = useState(false); const [aiResponse, setAiResponse] = useState(null); async function handleSearch(): Promise { if (wordToCheck.trim() === '') { return; } setInProgress(true); try { const response: AIDictionary = await System.authPostToServer( `quillsense/dictionary`, {word: wordToCheck}, session.accessToken, lang ); if (!response) { errorMessage(t("dictionary.errorNoResponse")); return; } if (response.useYourKey){ setTotalPrice((prevState:number):number => prevState + response.totalPrice) } else { setTotalCredits(response.totalPrice) } setAiResponse(response.data); } catch (e: unknown) { if (e instanceof Error) { errorMessage(e.message); } else { errorMessage(t("dictionary.errorUnknown")); } } finally { setInProgress(false); } } if (!hasKey) { return (

Accès requis

Un abonnement de niveau de base de QuillSense ou une clé API OpenAI est requis pour activer le dictionnaire intelligent.

); } return (
) => setWordToCheck(e.target.value)} placeholder={t("dictionary.searchPlaceholder")} /> } icon={faSpellCheck} fieldName={t("dictionary.fieldName")} actionLabel={t("dictionary.searchAction")} actionIcon={faMagnifyingGlass} action={async (): Promise => handleSearch()} />
{inProgress && (

{t("dictionary.loading")}

)} {!inProgress && aiResponse && (

{wordToCheck}

{t("dictionary.definitionHeading")}

{aiResponse.definition}

{t("dictionary.exampleHeading")}

{aiResponse.example}

{t("dictionary.literaryUsageHeading")}

{aiResponse.literaryUsage}

)} {!inProgress && !aiResponse && (

{t("dictionary.fieldName")}

{t("dictionary.description")}

)}
); }