optimize userscript events

This commit is contained in:
Gabe Yuan
2023-08-09 14:57:51 +08:00
parent 8bfd02bbc4
commit 7c50ff146f
3 changed files with 16 additions and 119 deletions

View File

@@ -5,45 +5,11 @@ import Action from "./views/Action";
import createCache from "@emotion/cache"; import createCache from "@emotion/cache";
import { CacheProvider } from "@emotion/react"; import { CacheProvider } from "@emotion/react";
import {
MSG_TRANS_TOGGLE,
MSG_TRANS_GETRULE,
MSG_TRANS_PUTRULE,
MSG_TRANS_CURRULE,
EVENT_KISS,
} from "./config";
import { getRules, matchRule } from "./libs"; import { getRules, matchRule } from "./libs";
import { getSetting } from "./libs"; import { getSetting } from "./libs";
import { transPool } from "./libs/pool"; import { transPool } from "./libs/pool";
import { Translator } from "./libs/translator"; import { Translator } from "./libs/translator";
/**
* 自定义元素
*/
// class ActionElement extends HTMLElement {
// connectedCallback() {
// const shadowContainer = this.attachShadow({ mode: "open" });
// const emotionRoot = document.createElement("style");
// const shadowRootElement = document.createElement("div");
// shadowContainer.appendChild(emotionRoot);
// shadowContainer.appendChild(shadowRootElement);
// const cache = createCache({
// key: "css",
// prepend: true,
// container: emotionRoot,
// });
// ReactDOM.createRoot(shadowRootElement).render(
// <React.StrictMode>
// <CacheProvider value={cache}>
// <Action />
// </CacheProvider>
// </React.StrictMode>
// );
// }
// }
/** /**
* 入口函数 * 入口函数
*/ */
@@ -63,18 +29,19 @@ import { Translator } from "./libs/translator";
return; return;
} }
// iframe // skip iframe
if (window.self !== window.top) { if (window.self !== window.top) {
return; return;
} }
// 插入按钮 // 翻译页面
// const actionName = "kiss-action"; const { fetchInterval, fetchLimit } = await getSetting();
// customElements.define(actionName, ActionElement); transPool.update(fetchInterval, fetchLimit);
// const $action = document.createElement(actionName); const rules = await getRules();
// document.body.parentElement.appendChild($action); const rule = matchRule(rules, document.location.href);
const translator = new Translator(rule);
// 插入按钮,兼容性更好 // 浮球按钮
const $action = document.createElement("div"); const $action = document.createElement("div");
$action.setAttribute("id", "kiss-translator"); $action.setAttribute("id", "kiss-translator");
document.body.parentElement.appendChild($action); document.body.parentElement.appendChild($action);
@@ -91,41 +58,8 @@ import { Translator } from "./libs/translator";
ReactDOM.createRoot(shadowRootElement).render( ReactDOM.createRoot(shadowRootElement).render(
<React.StrictMode> <React.StrictMode>
<CacheProvider value={cache}> <CacheProvider value={cache}>
<Action /> <Action translator={translator} />
</CacheProvider> </CacheProvider>
</React.StrictMode> </React.StrictMode>
); );
// 翻译页面
const { fetchInterval, fetchLimit } = await getSetting();
transPool.update(fetchInterval, fetchLimit);
const rules = await getRules();
const rule = matchRule(rules, document.location.href);
const translator = new Translator(rule);
// 监听消息
window.addEventListener(EVENT_KISS, (e) => {
const action = e?.detail?.action;
const args = e?.detail?.args || {};
switch (action) {
case MSG_TRANS_TOGGLE:
translator.toggle();
break;
case MSG_TRANS_GETRULE:
window.dispatchEvent(
new CustomEvent(EVENT_KISS, {
detail: {
action: MSG_TRANS_CURRULE,
args: translator.rule,
},
})
);
break;
case MSG_TRANS_PUTRULE:
translator.updateRule(args);
break;
default:
// console.log(`[entry] kissEvent action skip: ${action}`);
}
});
})(); })();

View File

@@ -11,7 +11,7 @@ import { useEffect, useState, useMemo, useCallback } from "react";
import { StoragesProvider } from "../../hooks/Storage"; import { StoragesProvider } from "../../hooks/Storage";
import Popup from "../Popup"; import Popup from "../Popup";
export default function Action() { export default function Action({ translator }) {
const fabWidth = 56; const fabWidth = 56;
const [showPopup, setShowPopup] = useState(false); const [showPopup, setShowPopup] = useState(false);
const [windowSize, setWindowSize] = useState({ const [windowSize, setWindowSize] = useState({
@@ -103,7 +103,7 @@ export default function Action() {
} }
> >
<Paper> <Paper>
<Popup setShowPopup={setShowPopup} /> <Popup setShowPopup={setShowPopup} translator={translator} />
</Paper> </Paper>
</Draggable> </Draggable>
<Draggable <Draggable

View File

@@ -17,13 +17,11 @@ import {
OPT_LANGS_FROM, OPT_LANGS_FROM,
OPT_LANGS_TO, OPT_LANGS_TO,
OPT_STYLE_ALL, OPT_STYLE_ALL,
EVENT_KISS,
MSG_TRANS_CURRULE,
} from "../../config"; } from "../../config";
export default function Popup({ setShowPopup }) { export default function Popup({ setShowPopup, translator: tran }) {
const i18n = useI18n(); const i18n = useI18n();
const [rule, setRule] = useState(null); const [rule, setRule] = useState(tran.rule);
const handleOpenSetting = () => { const handleOpenSetting = () => {
if (isExt) { if (isExt) {
@@ -41,13 +39,7 @@ export default function Popup({ setShowPopup }) {
if (isExt) { if (isExt) {
await sendTabMsg(MSG_TRANS_TOGGLE); await sendTabMsg(MSG_TRANS_TOGGLE);
} else { } else {
window.dispatchEvent( tran.toggle();
new CustomEvent(EVENT_KISS, {
detail: {
action: MSG_TRANS_TOGGLE,
},
})
);
} }
} catch (err) { } catch (err) {
console.log("[toggle trans]", err); console.log("[toggle trans]", err);
@@ -62,46 +54,17 @@ export default function Popup({ setShowPopup }) {
if (isExt) { if (isExt) {
await sendTabMsg(MSG_TRANS_PUTRULE, { [name]: value }); await sendTabMsg(MSG_TRANS_PUTRULE, { [name]: value });
} else { } else {
window.dispatchEvent( tran.updateRule({ [name]: value });
new CustomEvent(EVENT_KISS, {
detail: {
action: MSG_TRANS_PUTRULE,
args: { [name]: value },
},
})
);
} }
} catch (err) { } catch (err) {
console.log("[update rule]", err); console.log("[update rule]", err);
} }
}; };
const handleKissEvent = (e) => {
const action = e?.detail?.action;
const args = e?.detail?.args || {};
switch (action) {
case MSG_TRANS_CURRULE:
setRule(args);
break;
default:
// console.log(`[popup] kissEvent action skip: ${action}`);
}
};
useEffect(() => { useEffect(() => {
if (!isExt) { if (!isExt) {
window.addEventListener(EVENT_KISS, handleKissEvent); return;
window.dispatchEvent(
new CustomEvent(EVENT_KISS, {
detail: { action: MSG_TRANS_GETRULE },
})
);
return () => {
window.removeEventListener(EVENT_KISS, handleKissEvent);
};
} }
(async () => { (async () => {
try { try {
const res = await sendTabMsg(MSG_TRANS_GETRULE); const res = await sendTabMsg(MSG_TRANS_GETRULE);