simple-translate/src/common/translate.js

85 lines
2.3 KiB
JavaScript
Raw Normal View History

2019-02-21 16:43:45 +00:00
let translationHistory = [];
2018-06-02 12:42:29 +00:00
2019-02-21 16:43:45 +00:00
const getHistory = (sourceWord, sourceLang, targetLang) => {
const history = translationHistory.find(
history =>
history.sourceWord == sourceWord &&
history.sourceLang == sourceLang &&
history.targetLang == targetLang &&
history.result.statusText == "OK"
);
return history;
};
2019-02-21 16:43:45 +00:00
const setHistory = (sourceWord, sourceLang, targetLang, formattedResult) => {
translationHistory.push({
sourceWord: sourceWord,
sourceLang: sourceLang,
targetLang: targetLang,
result: formattedResult
});
};
2018-11-15 12:24:18 +00:00
2019-02-21 16:43:45 +00:00
const sendRequest = (word, sourceLang, targetLang) => {
const url = `https://translate.googleapis.com/translate_a/single?client=gtx&sl=${sourceLang}&tl=${targetLang}&dt=t&dt=bd&dj=1&q=${encodeURIComponent(
word
)}`;
const xhr = new XMLHttpRequest();
xhr.responseType = "json";
xhr.open("GET", url);
xhr.send();
2019-02-21 16:43:45 +00:00
return new Promise((resolve, reject) => {
xhr.onload = () => {
resolve(xhr);
};
xhr.onerror = () => {
resolve(xhr);
};
});
};
2019-02-21 16:43:45 +00:00
const formatResult = result => {
const resultData = {
resultText: "",
candidateText: "",
sourceLanguage: "",
percentage: 0,
statusText: ""
};
2018-06-02 12:29:38 +00:00
2019-02-21 16:43:45 +00:00
resultData.statusText = result.statusText;
if (resultData.statusText !== "OK") return resultData;
2018-06-02 12:29:38 +00:00
2019-02-21 16:43:45 +00:00
resultData.sourceLanguage = result.response.src;
resultData.percentage = result.response.confidence;
resultData.resultText = result.response.sentences.map(sentence => sentence.trans).join("");
if (result.response.dict) {
resultData.candidateText = result.response.dict
.map(dict => `${dict.pos}${dict.pos != "" ? ": " : ""}${dict.terms.join(", ")}\n`)
.join("");
2018-07-31 11:35:03 +00:00
}
2018-06-02 12:29:38 +00:00
2019-02-21 16:43:45 +00:00
return resultData;
};
2018-06-02 12:29:38 +00:00
2019-02-21 16:43:45 +00:00
export default async (sourceWord, sourceLang = "auto", targetLang) => {
sourceWord = sourceWord.trim();
2019-02-22 15:21:55 +00:00
if (sourceWord === "")
return {
resultText: "",
candidateText: "",
sourceLanguage: "en",
percentage: 0,
statusText: "OK"
};
2019-02-21 16:43:45 +00:00
const history = getHistory(sourceWord, sourceLang, targetLang);
if (history) return history.result;
2018-07-31 15:50:10 +00:00
2019-02-21 16:43:45 +00:00
const result = await sendRequest(sourceWord, sourceLang, targetLang);
const formattedResult = formatResult(result);
setHistory(sourceWord, sourceLang, targetLang, formattedResult);
return formattedResult;
};