optimize Translator class & EVENT_KISS event

This commit is contained in:
Gabe Yuan
2023-08-09 13:22:10 +08:00
parent 5b38c38feb
commit 8bfd02bbc4
3 changed files with 69 additions and 57 deletions

View File

@@ -1,63 +1,26 @@
import { useEffect } from "react";
import { useState } from "react";
import { transPool } from "../libs/pool";
import { browser } from "../libs/browser";
import { MSG_TRANS_PUTRULE, EVENT_KISS } from "../config";
import { detectLang } from "../libs";
import { isExt } from "../libs/browser";
/**
* 翻译hook
* @param {*} q
* @param {*} rule
* @returns
*/
export function useTranslate(q, initRule) {
export function useTranslate(q, rule) {
const [text, setText] = useState("");
const [loading, setLoading] = useState(false);
const [sameLang, setSamelang] = useState(false);
const [rule, setRule] = useState(initRule);
const { translator, fromLang, toLang, textStyle, bgColor } = rule;
const handleMessage = ({ action, args }) => {
if (action === MSG_TRANS_PUTRULE) {
setRule((pre) => ({ ...pre, ...args }));
}
return true;
};
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:
// console.log(`[popup] kissEvent action skip: ${action}`);
}
};
useEffect(() => {
if (isExt) {
browser?.runtime.onMessage.addListener(handleMessage);
} else {
window.addEventListener(EVENT_KISS, handleKissEvent);
}
return () => {
if (isExt) {
browser?.runtime.onMessage.removeListener(handleMessage);
} else {
window.removeEventListener(EVENT_KISS, handleKissEvent);
}
};
}, []);
const { translator, fromLang, toLang } = rule;
useEffect(() => {
(async () => {
try {
setLoading(true);
const deLang = await detectLang(q);
if (toLang.includes(deLang)) {
setSamelang(true);
@@ -79,5 +42,5 @@ export function useTranslate(q, initRule) {
})();
}, [q, translator, fromLang, toLang]);
return { text, sameLang, loading, textStyle, bgColor };
return { text, sameLang, loading };
}