import {AlertContext, AlertContextProps} from "@/context/AlertContext"; import {SessionContext, SessionContextProps} from "@/context/SessionContext"; import {apiPost} from '@/lib/api/client'; import {ChangeEvent, JSX, useContext, useState} from "react"; import {AIDictionary, DictionaryAIResponse} from "@/lib/types/quillsense"; import InputField from "@/components/form/InputField"; import {Search, SpellCheck} from "lucide-react"; import TextInput from "@/components/form/TextInput"; import {useTranslations} from '@/lib/i18n'; import {LangContext, LangContextProps} from "@/context/LangContext"; import {AIUsageContext, AIUsageContextProps} from "@/context/AIUsageContext"; import EmptyState from "@/components/ui/EmptyState"; import PulseLoader from "@/components/ui/PulseLoader"; import LockCard from "@/components/ui/LockCard"; export default function Dictionary({hasKey}: { hasKey: boolean }): JSX.Element { const {session}: SessionContextProps = useContext(SessionContext); const {errorMessage}: AlertContextProps = useContext(AlertContext); const t = useTranslations(); const {lang}: LangContextProps = useContext(LangContext) const {setTotalCredits, setTotalPrice}: AIUsageContextProps = 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 apiPost( `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 ; } return (
): void => setWordToCheck(e.target.value)} placeholder={t("dictionary.searchPlaceholder")} /> } icon={SpellCheck} fieldName={t("dictionary.fieldName")} actionLabel={t("dictionary.searchAction")} actionIcon={Search} action={async (): Promise => handleSearch()} />
{inProgress && ( )} {!inProgress && aiResponse && (

{wordToCheck}

{t("dictionary.definitionHeading")}

{aiResponse.definition}

{t("dictionary.exampleHeading")}

{aiResponse.example}

{t("dictionary.literaryUsageHeading")}

{aiResponse.literaryUsage}

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