Spaces:
Running

File size: 1,371 Bytes
660e352
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
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<Language>("zh");
  const [error, setError] = useState<string | null>(null);
  // The last sentence that translated, kept while the box holds one that doesn't
  const [translation, setTranslation] = useState<Translation | null>(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,
  };
}