import { useEffect, useState } from "react"; import { usePythonStatus } from "@elvis/pyodide"; import { python } from "./python"; import type { Language, Translation } from "./types"; const DEFAULT_SENTENCE = "I will go to school tomorrow."; // After typing stops, wait this long before translating const TYPING_DELAY_MS = 500; export default function useTranslation() { const status = usePythonStatus(python); const [sentence, setSentence] = useState(DEFAULT_SENTENCE); const [language, setLanguage] = useState("zh"); const [error, setError] = useState(null); // The last sentence that translated, kept while the box holds one that doesn't const [translation, setTranslation] = useState(null); useEffect(() => { let current = true; const timer = setTimeout(async () => { const result = await python.call("handle_translate", { sentence, language, }); if (!current) { return; } setError(result.ok ? null : result.error.message); if (result.ok) { setTranslation(result.data); } }, TYPING_DELAY_MS); return () => { current = false; clearTimeout(timer); }; }, [sentence, language]); return { status, sentence, setSentence, language, setLanguage, error, translation, }; }