Files
kiss-translator/src/userscript.js

66 lines
1.9 KiB
JavaScript
Raw Normal View History

2023-08-05 20:11:02 +08:00
import React from "react";
import ReactDOM from "react-dom/client";
import Options from "./views/Options";
2023-08-05 23:56:16 +08:00
import Action from "./views/Action";
import createCache from "@emotion/cache";
import { CacheProvider } from "@emotion/react";
2023-08-05 20:11:02 +08:00
2023-08-05 15:32:51 +08:00
import { getRules, matchRule } from "./libs";
import { getSetting } from "./libs";
import { transPool } from "./libs/pool";
import { Translator } from "./libs/translator";
/**
* 入口函数
*/
(async () => {
2023-08-05 20:11:02 +08:00
// 设置页面
2023-08-06 21:12:01 +08:00
if (
document.location.href.includes("http://localhost:3000/options.html") ||
2023-08-07 11:53:44 +08:00
document.location.href.includes(process.env.REACT_APP_OPTIONSPAGE) ||
document.location.href.includes(process.env.REACT_APP_OPTIONSPAGE2)
2023-08-06 21:12:01 +08:00
) {
2023-08-05 20:11:02 +08:00
const root = ReactDOM.createRoot(document.getElementById("root"));
root.render(
<React.StrictMode>
<Options />
</React.StrictMode>
);
return;
}
2023-08-09 14:57:51 +08:00
// skip iframe
2023-08-06 22:01:47 +08:00
if (window.self !== window.top) {
return;
}
2023-08-09 14:57:51 +08:00
// 翻译页面
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);
2023-08-09 14:57:51 +08:00
// 浮球按钮
const $action = document.createElement("div");
$action.setAttribute("id", "kiss-translator");
2023-08-05 23:56:16 +08:00
document.body.parentElement.appendChild($action);
const shadowContainer = $action.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}>
2023-08-09 14:57:51 +08:00
<Action translator={translator} />
</CacheProvider>
</React.StrictMode>
);
2023-08-05 15:32:51 +08:00
})();