Files
kiss-translator/src/hooks/Translate.js

84 lines
2.1 KiB
JavaScript
Raw Normal View History

2023-07-20 13:45:41 +08:00
import { useEffect } from "react";
import { useState } from "react";
2023-08-04 16:05:14 +08:00
import { transPool } from "../libs/pool";
2023-08-04 16:48:40 +08:00
import { browser } from "../libs/browser";
2023-08-06 21:12:01 +08:00
import { MSG_TRANS_PUTRULE, EVENT_KISS } from "../config";
2023-07-20 13:45:41 +08:00
import { detectLang } from "../libs";
2023-08-06 21:12:01 +08:00
import { isExt } from "../libs/browser";
2023-07-20 13:45:41 +08:00
/**
* 翻译hook
* @param {*} q
* @returns
*/
export function useTranslate(q, initRule) {
const [text, setText] = useState("");
const [loading, setLoading] = useState(false);
const [sameLang, setSamelang] = useState(false);
const [rule, setRule] = useState(initRule);
2023-08-08 16:41:47 +08:00
const { translator, fromLang, toLang, textStyle, bgColor } = rule;
2023-07-20 13:45:41 +08:00
const handleMessage = ({ action, args }) => {
if (action === MSG_TRANS_PUTRULE) {
setRule((pre) => ({ ...pre, ...args }));
}
return true;
};
2023-08-06 21:12:01 +08:00
const handleKissEvent = (e) => {
const action = e?.detail?.action;
const args = e?.detail?.args || {};
switch (action) {
case MSG_TRANS_PUTRULE:
setRule((pre) => ({ ...pre, ...args }));
break;
default:
2023-08-08 16:41:47 +08:00
// console.log(`[popup] kissEvent action skip: ${action}`);
2023-08-06 21:12:01 +08:00
}
};
2023-07-20 13:45:41 +08:00
useEffect(() => {
2023-08-06 21:12:01 +08:00
if (isExt) {
browser?.runtime.onMessage.addListener(handleMessage);
} else {
window.addEventListener(EVENT_KISS, handleKissEvent);
}
2023-07-20 13:45:41 +08:00
return () => {
2023-08-06 21:12:01 +08:00
if (isExt) {
browser?.runtime.onMessage.removeListener(handleMessage);
} else {
window.removeEventListener(EVENT_KISS, handleKissEvent);
}
2023-07-20 13:45:41 +08:00
};
}, []);
useEffect(() => {
(async () => {
try {
setLoading(true);
const deLang = await detectLang(q);
if (toLang.includes(deLang)) {
setSamelang(true);
} else {
2023-08-04 16:05:14 +08:00
const [trText, isSame] = await transPool.push({
2023-07-20 13:45:41 +08:00
translator,
q,
fromLang,
toLang,
});
setText(trText);
setSamelang(isSame);
}
} catch (err) {
console.log("[translate]", err);
} finally {
setLoading(false);
}
})();
}, [q, translator, fromLang, toLang]);
2023-08-08 16:41:47 +08:00
return { text, sameLang, loading, textStyle, bgColor };
2023-07-20 13:45:41 +08:00
}