Compare commits
60 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
beca31f55d | ||
|
|
c7df103950 | ||
|
|
4bf7972ad5 | ||
|
|
534eaed1ed | ||
|
|
7e014e7385 | ||
|
|
34adb2660b | ||
|
|
b6bc165cf0 | ||
|
|
bdd5ed7fc7 | ||
|
|
95d19417c3 | ||
|
|
30ebebdd71 | ||
|
|
e9c557776d | ||
|
|
535a43b698 | ||
|
|
59752ed4aa | ||
|
|
b3e7b8f3f1 | ||
|
|
c4e9365512 | ||
|
|
7d3972d3a8 | ||
|
|
52ca4306fd | ||
|
|
da368ee612 | ||
|
|
22c50e7765 | ||
|
|
7bc39dd1bc | ||
|
|
c80ead6116 | ||
|
|
67e76e4009 | ||
|
|
b213218a30 | ||
|
|
c629a1252c | ||
|
|
64d2481e93 | ||
|
|
e7d6a6add8 | ||
|
|
edc25f7da4 | ||
|
|
5bff84ace1 | ||
|
|
f8bfcba317 | ||
|
|
013a05201b | ||
|
|
433e811821 | ||
|
|
df4cfc0fbc | ||
|
|
1bfb465fd6 | ||
|
|
d5d5ec3fef | ||
|
|
0a32f94d32 | ||
|
|
8067f34ce6 | ||
|
|
214c189a7c | ||
|
|
1f67afc8d8 | ||
|
|
7d4af27919 | ||
|
|
2d651abfdd | ||
|
|
6e06fe79cd | ||
|
|
6093577591 | ||
|
|
4b23ee733f | ||
|
|
46428b7c7f | ||
|
|
6805340a9a | ||
|
|
df36ca8d8b | ||
|
|
fe13de7c30 | ||
|
|
b00f636b72 | ||
|
|
8d074e63e1 | ||
|
|
37989b0089 | ||
|
|
477361eb40 | ||
|
|
94288b5dc3 | ||
|
|
84de1e0f12 | ||
|
|
06f93c1c10 | ||
|
|
450283b80a | ||
|
|
44aeed03a6 | ||
|
|
fa4569415d | ||
|
|
a341bf30ba | ||
|
|
34a7354c84 | ||
|
|
21b5dfbe98 |
2
.env
2
.env
@@ -2,7 +2,7 @@ GENERATE_SOURCEMAP=false
|
||||
|
||||
REACT_APP_NAME=KISS Translator
|
||||
REACT_APP_NAME_CN=简约翻译
|
||||
REACT_APP_VERSION=1.7.10
|
||||
REACT_APP_VERSION=1.7.15
|
||||
|
||||
REACT_APP_HOMEPAGE=https://github.com/fishjar/kiss-translator
|
||||
|
||||
|
||||
15
README.en.md
15
README.en.md
@@ -1,6 +1,6 @@
|
||||
# KISS Translator
|
||||
|
||||
A simple [bilingual translation extension & Greasemonkey script](https://github.com/fishjar/kiss-translator).
|
||||
A simple, open source [bilingual translation extension & Greasemonkey script](https://github.com/fishjar/kiss-translator).
|
||||
|
||||
[kiss-translator.webm](https://github.com/fishjar/kiss-translator/assets/1157624/f7ba8a5c-e4a8-4d5a-823a-5c5c67a0a47f)
|
||||
|
||||
@@ -12,12 +12,13 @@ A simple [bilingual translation extension & Greasemonkey script](https://github.
|
||||
- [x] Chrome/Edge/Firefox/Kiwi
|
||||
- [ ] Safari
|
||||
- [x] Supports multiple translation services
|
||||
- [x] Google/Microsoft/DeepL/OpenAI/CloudflareAI/Baidu/Tencent
|
||||
- [x] Google/Microsoft/DeepL/OpenAI/Gemini/CloudflareAI/Baidu/Tencent
|
||||
- [x] Custom translation interface
|
||||
- [x] Covers common translation scenarios
|
||||
- [x] Web bilingual translation
|
||||
- [x] Input box translation
|
||||
- [x] Seletction translation
|
||||
- [x] Favorite Words
|
||||
- [x] Mouseover translation
|
||||
- [x] YouTube subtitle translation
|
||||
- [x] Cross-client data synchronization
|
||||
@@ -30,7 +31,7 @@ A simple [bilingual translation extension & Greasemonkey script](https://github.
|
||||
- `Alt+Q` Toggle Translation
|
||||
- `Alt+C` Toggle Styles
|
||||
- `Alt+K` Open Setting Popup
|
||||
- `Alt+B` Open Translate Popup
|
||||
- `Alt+S` Open Translate Popup / Translate Selected Text
|
||||
- `Alt+O` Open Options Page
|
||||
- `Alt+I` Input Box Translation
|
||||
|
||||
@@ -38,8 +39,8 @@ A simple [bilingual translation extension & Greasemonkey script](https://github.
|
||||
|
||||
> Note: For the following reasons, it is recommended to use browser extensions first
|
||||
>
|
||||
> - Browser extension can use local language recognition
|
||||
> - Grease Monkey script will encounter more usage problems
|
||||
> - Browser extensions have more complete functions (local language recognition, context menu, etc.)
|
||||
> - Grease Monkey script will encounter more usage problems (cross domain issues, script conflicts, etc.)
|
||||
|
||||
- [x] Browser extension
|
||||
- [x] Chrome [Installation address](https://chrome.google.com/webstore/detail/kiss-translator/bdiifdefkgmcblbcghdlonllpjhhjgof?hl=zh-CN)
|
||||
@@ -47,9 +48,9 @@ A simple [bilingual translation extension & Greasemonkey script](https://github.
|
||||
- [x] Firefox [Installation address](https://addons.mozilla.org/zh-CN/firefox/addon/kiss-translator/)
|
||||
- [ ] Safari
|
||||
- [x] GreaseMonkey Script
|
||||
- [x] Chrome/Edge/Firefox ([Tampermonkey](https://www.tampermonkey.net/)/[Violentmonkey](https://violentmonkey.github.io/)) [Installation link 1](https://fishjar.github.io/kiss-translator/kiss-translator.user.js)、 [Installation link 2](https://kiss-translator.rayjar.com/kiss-translator.user.js)
|
||||
- [x] Chrome/Edge/Firefox ([Tampermonkey](https://www.tampermonkey.net/)/[Violentmonkey](https://violentmonkey.github.io/)) [Installation link](https://fishjar.github.io/kiss-translator/kiss-translator.user.js)
|
||||
- Greasy Fork [Installation address](https://greasyfork.org/zh-CN/scripts/472840-kiss-translator)
|
||||
- [x] iOS Safari ([Userscripts Safari](https://github.com/quoid/userscripts)) [Installation link 1](https://fishjar.github.io/kiss-translator/kiss-translator-ios-safari.user.js)、 [Installation link 2](https://kiss-translator.rayjar.com/kiss-translator.user-ios-safari.js)
|
||||
- [x] iOS Safari ([Userscripts Safari](https://github.com/quoid/userscripts)) [Installation link](https://fishjar.github.io/kiss-translator/kiss-translator-ios-safari.user.js)
|
||||
|
||||
## Associated Projects
|
||||
|
||||
|
||||
17
README.md
17
README.md
@@ -1,6 +1,6 @@
|
||||
# 简约翻译
|
||||
|
||||
一个简约的 [双语对照翻译扩展 & 油猴脚本](https://github.com/fishjar/kiss-translator)。
|
||||
一个简约、开源的 [双语对照翻译扩展 & 油猴脚本](https://github.com/fishjar/kiss-translator)。
|
||||
|
||||
[kiss-translator.webm](https://github.com/fishjar/kiss-translator/assets/1157624/f7ba8a5c-e4a8-4d5a-823a-5c5c67a0a47f)
|
||||
|
||||
@@ -12,12 +12,13 @@
|
||||
- [x] Chrome/Edge/Firefox/Kiwi
|
||||
- [ ] Safari
|
||||
- [x] 支持多种翻译服务
|
||||
- [x] Google/Microsoft/DeepL/OpenAI/CloudflareAI/Baidu/Tencent
|
||||
- [x] Google/Microsoft/DeepL/OpenAI/Gemini/CloudflareAI/Baidu/Tencent
|
||||
- [x] 自定义翻译接口
|
||||
- [x] 覆盖常见翻译场景
|
||||
- [x] 网页双语对照翻译
|
||||
- [x] 输入框翻译
|
||||
- [x] 划词翻译
|
||||
- [x] 收藏词汇
|
||||
- [x] 鼠标悬停翻译
|
||||
- [x] YouTube 字幕翻译
|
||||
- [x] 跨客户端数据同步
|
||||
@@ -30,7 +31,7 @@
|
||||
- `Alt+Q` 开启翻译
|
||||
- `Alt+C` 切换样式
|
||||
- `Alt+K` 打开设置弹窗
|
||||
- `Alt+B` 打开翻译弹窗
|
||||
- `Alt+S` 打开翻译弹窗/翻译选中文字
|
||||
- `Alt+O` 打开设置页面
|
||||
- `Alt+I` 输入框翻译
|
||||
|
||||
@@ -38,8 +39,8 @@
|
||||
|
||||
> 注:基于以下原因,建议优先使用浏览器扩展
|
||||
>
|
||||
> - 浏览器扩展可以使用本地的语言识别
|
||||
> - 油猴脚本会遇到更多使用上的问题
|
||||
> - 浏览器扩展的功能更完整(本地语言识别、右键菜单等)
|
||||
> - 油猴脚本会遇到更多使用上的问题(跨域问题、脚本冲突等)
|
||||
|
||||
- [x] 浏览器扩展
|
||||
- [x] Chrome [安装地址](https://chrome.google.com/webstore/detail/kiss-translator/bdiifdefkgmcblbcghdlonllpjhhjgof?hl=zh-CN)
|
||||
@@ -47,9 +48,9 @@
|
||||
- [x] Firefox [安装地址](https://addons.mozilla.org/zh-CN/firefox/addon/kiss-translator/)
|
||||
- [ ] Safari
|
||||
- [x] 油猴脚本
|
||||
- [x] Chrome/Edge/Firefox ([Tampermonkey](https://www.tampermonkey.net/)/[Violentmonkey](https://violentmonkey.github.io/)) [安装链接 1](https://fishjar.github.io/kiss-translator/kiss-translator.user.js)、 [安装链接 2](https://kiss-translator.rayjar.com/kiss-translator.user.js)
|
||||
- [x] Chrome/Edge/Firefox ([Tampermonkey](https://www.tampermonkey.net/)/[Violentmonkey](https://violentmonkey.github.io/)) [安装链接](https://fishjar.github.io/kiss-translator/kiss-translator.user.js)
|
||||
- Greasy Fork [安装地址](https://greasyfork.org/zh-CN/scripts/472840-kiss-translator)
|
||||
- [x] iOS Safari ([Userscripts Safari](https://github.com/quoid/userscripts)) [安装链接 1](https://fishjar.github.io/kiss-translator/kiss-translator-ios-safari.user.js)、 [安装链接 2](https://kiss-translator.rayjar.com/kiss-translator.user-ios-safari.js)
|
||||
- [x] iOS Safari ([Userscripts Safari](https://github.com/quoid/userscripts)) [安装链接](https://fishjar.github.io/kiss-translator/kiss-translator-ios-safari.user.js)
|
||||
|
||||
## 关联项目
|
||||
|
||||
@@ -64,7 +65,7 @@
|
||||
- 针对一些特殊网站的修正脚本。
|
||||
- 以便翻译软件得到更好的展示效果。
|
||||
- 翻译接口代理: [https://github.com/fishjar/kiss-proxy](https://github.com/fishjar/kiss-proxy)
|
||||
- 如果访问某个翻译接口遇到网络问题,这个代理服务也许可以帮你到你。
|
||||
- 如果访问某个翻译接口遇到网络问题,这个代理服务也许可以帮到你。
|
||||
- 自己部署,自己管理。
|
||||
- 简约词典插件: [https://github.com/fishjar/kiss-dictionary](https://github.com/fishjar/kiss-dictionary)
|
||||
- 搭配本项目一起使用的划词翻译插件。
|
||||
|
||||
@@ -85,6 +85,7 @@ const userscriptWebpack = (config, env) => {
|
||||
// @updateURL ${process.env.REACT_APP_USERSCRIPT_DOWNLOADURL}
|
||||
// @grant GM.xmlHttpRequest
|
||||
// @grant GM.registerMenuCommand
|
||||
// @grant GM.unregisterMenuCommand
|
||||
// @grant GM.setValue
|
||||
// @grant GM.getValue
|
||||
// @grant GM.deleteValue
|
||||
@@ -97,6 +98,7 @@ const userscriptWebpack = (config, env) => {
|
||||
// @connect api.deepl.com
|
||||
// @connect www2.deepl.com
|
||||
// @connect api.openai.com
|
||||
// @connect generativelanguage.googleapis.com
|
||||
// @connect openai.azure.com
|
||||
// @connect workers.dev
|
||||
// @connect github.io
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
{
|
||||
"name": "kiss-translator",
|
||||
"description": "A minimalist bilingual translation Extension & Greasemonkey Script",
|
||||
"version": "1.7.10",
|
||||
"version": "1.7.15",
|
||||
"author": "Gabe<yugang2002@gmail.com>",
|
||||
"private": true,
|
||||
"dependencies": {
|
||||
@@ -30,7 +30,6 @@
|
||||
"build:userscript": "rm -rf build/userscript && mkdir build/userscript && cp build/web/*.user.js build/userscript/",
|
||||
"build:rules": "babel-node src/rules.js",
|
||||
"build": "pnpm build:chrome && pnpm build:edge && pnpm build:firefox && pnpm build:web && pnpm build:userscript-ios && pnpm build:userscript && pnpm build:rules",
|
||||
"deploy:web": "wrangler pages deploy ./build/web --project-name kiss-translator",
|
||||
"test": "react-app-rewired test",
|
||||
"eject": "react-scripts eject"
|
||||
},
|
||||
|
||||
@@ -6,12 +6,15 @@
|
||||
"message": "A simple bilingual translation extension & Greasemonkey script"
|
||||
},
|
||||
"toggle_translate": {
|
||||
"message": "Toggle Translate"
|
||||
"message": "Toggle Translate (Alt+Q)"
|
||||
},
|
||||
"toggle_style": {
|
||||
"message": "Toggle Style"
|
||||
"message": "Toggle Style (Alt+C)"
|
||||
},
|
||||
"open_options": {
|
||||
"message": "Open Options"
|
||||
"message": "Open Options (Alt+O)"
|
||||
},
|
||||
"open_tranbox": {
|
||||
"message": "Translate Popup/Selected (Alt+S)"
|
||||
}
|
||||
}
|
||||
|
||||
@@ -6,12 +6,15 @@
|
||||
"message": "一个简约的双语对照翻译扩展 & 油猴脚本"
|
||||
},
|
||||
"toggle_translate": {
|
||||
"message": "开启翻译"
|
||||
"message": "开启翻译 (Alt+Q)"
|
||||
},
|
||||
"toggle_style": {
|
||||
"message": "切换样式"
|
||||
"message": "切换样式 (Alt+C)"
|
||||
},
|
||||
"open_options": {
|
||||
"message": "打开设置"
|
||||
"message": "打开设置 (Alt+O)"
|
||||
},
|
||||
"open_tranbox": {
|
||||
"message": "翻译弹窗/选中文字 (Alt+S)"
|
||||
}
|
||||
}
|
||||
|
||||
@@ -2,7 +2,7 @@
|
||||
"manifest_version": 2,
|
||||
"name": "__MSG_app_name__",
|
||||
"description": "__MSG_app_description__",
|
||||
"version": "1.7.10",
|
||||
"version": "1.7.15",
|
||||
"default_locale": "en",
|
||||
"author": "Gabe<yugang2002@gmail.com>",
|
||||
"homepage_url": "https://github.com/fishjar/kiss-translator",
|
||||
@@ -41,7 +41,7 @@
|
||||
"description": "__MSG_open_options__"
|
||||
}
|
||||
},
|
||||
"permissions": ["<all_urls>", "storage"],
|
||||
"permissions": ["<all_urls>", "storage", "contextMenus"],
|
||||
"icons": {
|
||||
"16": "images/logo16.png",
|
||||
"32": "images/logo32.png",
|
||||
|
||||
@@ -2,7 +2,7 @@
|
||||
"manifest_version": 3,
|
||||
"name": "__MSG_app_name__",
|
||||
"description": "__MSG_app_description__",
|
||||
"version": "1.7.10",
|
||||
"version": "1.7.15",
|
||||
"default_locale": "en",
|
||||
"author": "Gabe<yugang2002@gmail.com>",
|
||||
"homepage_url": "https://github.com/fishjar/kiss-translator",
|
||||
@@ -42,7 +42,7 @@
|
||||
"description": "__MSG_open_options__"
|
||||
}
|
||||
},
|
||||
"permissions": ["storage"],
|
||||
"permissions": ["storage", "contextMenus"],
|
||||
"host_permissions": ["<all_urls>"],
|
||||
"icons": {
|
||||
"16": "images/logo16.png",
|
||||
|
||||
@@ -9,6 +9,7 @@ import {
|
||||
OPT_TRANS_BAIDU,
|
||||
OPT_TRANS_TENCENT,
|
||||
OPT_TRANS_OPENAI,
|
||||
OPT_TRANS_GEMINI,
|
||||
OPT_TRANS_CLOUDFLAREAI,
|
||||
OPT_TRANS_CUSTOMIZE,
|
||||
URL_CACHE_TRAN,
|
||||
@@ -111,11 +112,15 @@ export const apiTranslate = async ({
|
||||
let trText = "";
|
||||
let isSame = false;
|
||||
|
||||
if (!text) {
|
||||
return [trText, true];
|
||||
}
|
||||
|
||||
const from =
|
||||
OPT_LANGS_SPECIAL[translator].get(fromLang) ??
|
||||
OPT_LANGS_SPECIAL[translator].get("auto");
|
||||
const to = OPT_LANGS_SPECIAL[translator].get(toLang);
|
||||
if (!text || !to) {
|
||||
if (!to) {
|
||||
console.log(`[trans] target lang: ${toLang} not support`);
|
||||
return [trText, isSame];
|
||||
}
|
||||
@@ -177,6 +182,10 @@ export const apiTranslate = async ({
|
||||
trText = res?.choices?.[0].message.content;
|
||||
isSame = text === trText;
|
||||
break;
|
||||
case OPT_TRANS_GEMINI:
|
||||
trText = res?.candidates?.[0].content.parts[0].text;
|
||||
isSame = text === trText;
|
||||
break;
|
||||
case OPT_TRANS_CLOUDFLAREAI:
|
||||
trText = res?.result?.translated_text;
|
||||
isSame = text === trText;
|
||||
|
||||
@@ -7,9 +7,12 @@ import {
|
||||
MSG_OPEN_OPTIONS,
|
||||
MSG_SAVE_RULE,
|
||||
MSG_TRANS_TOGGLE_STYLE,
|
||||
MSG_OPEN_TRANBOX,
|
||||
MSG_CONTEXT_MENUS,
|
||||
CMD_TOGGLE_TRANSLATE,
|
||||
CMD_TOGGLE_STYLE,
|
||||
CMD_OPEN_OPTIONS,
|
||||
CMD_OPEN_TRANBOX,
|
||||
} from "./config";
|
||||
import { getSettingWithDefault, tryInitDefaultData } from "./libs/storage";
|
||||
import { trySyncSettingAndRules } from "./libs/sync";
|
||||
@@ -21,30 +24,79 @@ import { saveRule } from "./libs/rules";
|
||||
|
||||
globalThis.ContextType = "BACKGROUND";
|
||||
|
||||
/**
|
||||
* 添加右键菜单
|
||||
*/
|
||||
function addContextMenus() {
|
||||
browser.contextMenus.create({
|
||||
id: CMD_TOGGLE_TRANSLATE,
|
||||
title: browser.i18n.getMessage("toggle_translate"),
|
||||
contexts: ["all"],
|
||||
});
|
||||
browser.contextMenus.create({
|
||||
id: CMD_TOGGLE_STYLE,
|
||||
title: browser.i18n.getMessage("toggle_style"),
|
||||
contexts: ["all"],
|
||||
});
|
||||
browser.contextMenus.create({
|
||||
id: CMD_OPEN_TRANBOX,
|
||||
title: browser.i18n.getMessage("open_tranbox"),
|
||||
contexts: ["all"],
|
||||
});
|
||||
browser.contextMenus.create({
|
||||
id: "options_separator",
|
||||
type: "separator",
|
||||
contexts: ["all"],
|
||||
});
|
||||
browser.contextMenus.create({
|
||||
id: CMD_OPEN_OPTIONS,
|
||||
title: browser.i18n.getMessage("open_options"),
|
||||
contexts: ["all"],
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* 清除右键菜单
|
||||
*/
|
||||
function removeContextMenus() {
|
||||
browser.contextMenus.removeAll();
|
||||
}
|
||||
|
||||
/**
|
||||
* 插件安装
|
||||
*/
|
||||
browser.runtime.onInstalled.addListener(() => {
|
||||
tryInitDefaultData();
|
||||
|
||||
// 右键菜单
|
||||
addContextMenus();
|
||||
});
|
||||
|
||||
/**
|
||||
* 浏览器启动
|
||||
*/
|
||||
browser.runtime.onStartup.addListener(async () => {
|
||||
console.log("browser onStartup");
|
||||
|
||||
// 同步数据
|
||||
await trySyncSettingAndRules();
|
||||
|
||||
const {
|
||||
clearCache,
|
||||
contextMenus = true,
|
||||
subrulesList,
|
||||
} = await getSettingWithDefault();
|
||||
|
||||
// 清除缓存
|
||||
const setting = await getSettingWithDefault();
|
||||
if (setting.clearCache) {
|
||||
if (clearCache) {
|
||||
tryClearCaches();
|
||||
}
|
||||
|
||||
// 右键菜单
|
||||
if (!contextMenus) {
|
||||
removeContextMenus();
|
||||
}
|
||||
|
||||
// 同步订阅规则
|
||||
trySyncAllSubRules(setting);
|
||||
trySyncAllSubRules({ subrulesList });
|
||||
});
|
||||
|
||||
/**
|
||||
@@ -60,7 +112,7 @@ browser.runtime.onMessage.addListener(
|
||||
sendResponse({ data });
|
||||
})
|
||||
.catch((error) => {
|
||||
sendResponse({ error: error.message });
|
||||
sendResponse({ error: error.message, cause: error.cause });
|
||||
});
|
||||
break;
|
||||
case MSG_FETCH_LIMIT:
|
||||
@@ -78,6 +130,14 @@ browser.runtime.onMessage.addListener(
|
||||
case MSG_SAVE_RULE:
|
||||
saveRule(args);
|
||||
break;
|
||||
case MSG_CONTEXT_MENUS:
|
||||
const { contextMenus } = args;
|
||||
if (contextMenus) {
|
||||
addContextMenus();
|
||||
} else {
|
||||
removeContextMenus();
|
||||
}
|
||||
break;
|
||||
default:
|
||||
sendResponse({ error: `message action is unavailable: ${action}` });
|
||||
}
|
||||
@@ -103,3 +163,24 @@ browser.commands.onCommand.addListener((command) => {
|
||||
default:
|
||||
}
|
||||
});
|
||||
|
||||
/**
|
||||
* 监听右键菜单
|
||||
*/
|
||||
browser.contextMenus.onClicked.addListener(({ menuItemId }) => {
|
||||
switch (menuItemId) {
|
||||
case CMD_TOGGLE_TRANSLATE:
|
||||
sendTabMsg(MSG_TRANS_TOGGLE);
|
||||
break;
|
||||
case CMD_TOGGLE_STYLE:
|
||||
sendTabMsg(MSG_TRANS_TOGGLE_STYLE);
|
||||
break;
|
||||
case CMD_OPEN_TRANBOX:
|
||||
sendTabMsg(MSG_OPEN_TRANBOX);
|
||||
break;
|
||||
case CMD_OPEN_OPTIONS:
|
||||
browser.runtime.openOptionsPage();
|
||||
break;
|
||||
default:
|
||||
}
|
||||
});
|
||||
|
||||
194
src/common.js
194
src/common.js
@@ -8,25 +8,80 @@ import {
|
||||
MSG_TRANS_TOGGLE_STYLE,
|
||||
MSG_TRANS_GETRULE,
|
||||
MSG_TRANS_PUTRULE,
|
||||
MSG_OPEN_TRANBOX,
|
||||
APP_LCNAME,
|
||||
DEFAULT_TRANBOX_SETTING,
|
||||
} from "./config";
|
||||
import { getRulesWithDefault, getFabWithDefault } from "./libs/storage";
|
||||
import { getFabWithDefault, getSettingWithDefault } from "./libs/storage";
|
||||
import { Translator } from "./libs/translator";
|
||||
import { sendIframeMsg, sendParentMsg } from "./libs/iframe";
|
||||
import { matchRule } from "./libs/rules";
|
||||
import { isIframe, sendIframeMsg, sendParentMsg } from "./libs/iframe";
|
||||
import Slection from "./views/Selection";
|
||||
import { touchTapListener } from "./libs/touch";
|
||||
import { debounce, genEventName } from "./libs/utils";
|
||||
import { handlePing, injectScript } from "./libs/gm";
|
||||
import { browser } from "./libs/browser";
|
||||
import { runWebfix } from "./libs/webfix";
|
||||
import { matchRule } from "./libs/rules";
|
||||
import { trySyncAllSubRules } from "./libs/subRules";
|
||||
import { isInBlacklist } from "./libs/blacklist";
|
||||
import inputTranslate from "./libs/inputTranslate";
|
||||
|
||||
export async function runTranslator(setting) {
|
||||
const href = document.location.href;
|
||||
const rules = await getRulesWithDefault();
|
||||
const rule = await matchRule(rules, href, setting);
|
||||
const translator = new Translator(rule, setting);
|
||||
|
||||
return { translator, rule };
|
||||
/**
|
||||
* 油猴脚本设置页面
|
||||
*/
|
||||
function runSettingPage() {
|
||||
if (GM?.info?.script?.grant?.includes("unsafeWindow")) {
|
||||
unsafeWindow.GM = GM;
|
||||
unsafeWindow.APP_INFO = {
|
||||
name: process.env.REACT_APP_NAME,
|
||||
version: process.env.REACT_APP_VERSION,
|
||||
};
|
||||
} else {
|
||||
const ping = genEventName();
|
||||
window.addEventListener(ping, handlePing);
|
||||
// window.eval(`(${injectScript})("${ping}")`); // eslint-disable-line
|
||||
const script = document.createElement("script");
|
||||
script.textContent = `(${injectScript})("${ping}")`;
|
||||
document.head.append(script);
|
||||
}
|
||||
}
|
||||
|
||||
export function runIframe(setting) {
|
||||
/**
|
||||
* 插件监听后端事件
|
||||
* @param {*} translator
|
||||
*/
|
||||
function runtimeListener(translator) {
|
||||
browser?.runtime.onMessage.addListener(async ({ action, args }) => {
|
||||
switch (action) {
|
||||
case MSG_TRANS_TOGGLE:
|
||||
translator.toggle();
|
||||
sendIframeMsg(MSG_TRANS_TOGGLE);
|
||||
break;
|
||||
case MSG_TRANS_TOGGLE_STYLE:
|
||||
translator.toggleStyle();
|
||||
sendIframeMsg(MSG_TRANS_TOGGLE_STYLE);
|
||||
break;
|
||||
case MSG_TRANS_GETRULE:
|
||||
break;
|
||||
case MSG_TRANS_PUTRULE:
|
||||
translator.updateRule(args);
|
||||
sendIframeMsg(MSG_TRANS_PUTRULE, args);
|
||||
break;
|
||||
case MSG_OPEN_TRANBOX:
|
||||
window.dispatchEvent(new CustomEvent(MSG_OPEN_TRANBOX));
|
||||
break;
|
||||
default:
|
||||
return { error: `message action is unavailable: ${action}` };
|
||||
}
|
||||
return { data: translator.rule };
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* iframe 页面执行
|
||||
* @param {*} setting
|
||||
*/
|
||||
function runIframe(setting) {
|
||||
let translator;
|
||||
window.addEventListener("message", (e) => {
|
||||
const { action, args } = e.data || {};
|
||||
@@ -50,7 +105,12 @@ export function runIframe(setting) {
|
||||
sendParentMsg(MSG_TRANS_GETRULE);
|
||||
}
|
||||
|
||||
export async function showFab(translator) {
|
||||
/**
|
||||
* 悬浮按钮
|
||||
* @param {*} translator
|
||||
* @returns
|
||||
*/
|
||||
async function showFab(translator) {
|
||||
const fab = await getFabWithDefault();
|
||||
if (fab.isHide) {
|
||||
return;
|
||||
@@ -78,7 +138,13 @@ export async function showFab(translator) {
|
||||
);
|
||||
}
|
||||
|
||||
export function showTransbox({
|
||||
/**
|
||||
* 划词翻译
|
||||
* @param {*} param0
|
||||
* @returns
|
||||
*/
|
||||
function showTransbox({
|
||||
contextMenus = true,
|
||||
tranboxSetting = DEFAULT_TRANBOX_SETTING,
|
||||
transApis,
|
||||
}) {
|
||||
@@ -102,13 +168,21 @@ export function showTransbox({
|
||||
ReactDOM.createRoot(shadowRootElement).render(
|
||||
<React.StrictMode>
|
||||
<CacheProvider value={cache}>
|
||||
<Slection tranboxSetting={tranboxSetting} transApis={transApis} />
|
||||
<Slection
|
||||
contextMenus={contextMenus}
|
||||
tranboxSetting={tranboxSetting}
|
||||
transApis={transApis}
|
||||
/>
|
||||
</CacheProvider>
|
||||
</React.StrictMode>
|
||||
);
|
||||
}
|
||||
|
||||
export function windowListener(rule) {
|
||||
/**
|
||||
* 监听来自iframe页面消息
|
||||
* @param {*} rule
|
||||
*/
|
||||
function windowListener(rule) {
|
||||
window.addEventListener("message", (e) => {
|
||||
const { action } = e.data || {};
|
||||
switch (action) {
|
||||
@@ -120,10 +194,94 @@ export function windowListener(rule) {
|
||||
});
|
||||
}
|
||||
|
||||
export function showErr(err) {
|
||||
console.error("[KISS-Translator]", err);
|
||||
/**
|
||||
* 显示错误信息到页面顶部
|
||||
* @param {*} message
|
||||
*/
|
||||
function showErr(message) {
|
||||
const $err = document.createElement("div");
|
||||
$err.innerText = `KISS-Translator: ${err.message}`;
|
||||
$err.innerText = `KISS-Translator: ${message}`;
|
||||
$err.style.cssText = "background:red; color:#fff;";
|
||||
document.body.prepend($err);
|
||||
}
|
||||
|
||||
/**
|
||||
* 监听触屏操作
|
||||
* @param {*} translator
|
||||
* @returns
|
||||
*/
|
||||
function touchOperation(translator) {
|
||||
const { touchTranslate = 2 } = translator.setting;
|
||||
if (touchTranslate === 0) {
|
||||
return;
|
||||
}
|
||||
|
||||
const handleTap = debounce(() => {
|
||||
translator.toggle();
|
||||
sendIframeMsg(MSG_TRANS_TOGGLE);
|
||||
});
|
||||
touchTapListener(handleTap, touchTranslate);
|
||||
}
|
||||
|
||||
/**
|
||||
* 入口函数
|
||||
*/
|
||||
export async function run(isUserscript = false) {
|
||||
try {
|
||||
const href = document.location.href;
|
||||
|
||||
// 设置页面
|
||||
if (
|
||||
isUserscript &&
|
||||
(href.includes(process.env.REACT_APP_OPTIONSPAGE_DEV) ||
|
||||
href.includes(process.env.REACT_APP_OPTIONSPAGE) ||
|
||||
href.includes(process.env.REACT_APP_OPTIONSPAGE2))
|
||||
) {
|
||||
runSettingPage();
|
||||
return;
|
||||
}
|
||||
|
||||
// 读取设置信息
|
||||
const setting = await getSettingWithDefault();
|
||||
|
||||
// 黑名单
|
||||
if (isInBlacklist(href, setting)) {
|
||||
return;
|
||||
}
|
||||
|
||||
// 适配iframe
|
||||
if (isIframe) {
|
||||
runIframe(setting);
|
||||
return;
|
||||
}
|
||||
|
||||
// 不规范网页修复
|
||||
await runWebfix(setting);
|
||||
|
||||
// 翻译网页
|
||||
const rule = await matchRule(href, setting);
|
||||
const translator = new Translator(rule, setting);
|
||||
|
||||
// 监听消息
|
||||
windowListener(rule);
|
||||
!isUserscript && runtimeListener(translator);
|
||||
|
||||
// 输入框翻译
|
||||
inputTranslate(setting);
|
||||
|
||||
// 划词翻译
|
||||
showTransbox(setting);
|
||||
|
||||
// 浮球按钮
|
||||
await showFab(translator);
|
||||
|
||||
// 触屏操作
|
||||
touchOperation(translator);
|
||||
|
||||
// 同步订阅规则
|
||||
isUserscript && (await trySyncAllSubRules(setting));
|
||||
} catch (err) {
|
||||
console.error("[KISS-Translator]", err);
|
||||
showErr(err.message);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -215,6 +215,14 @@ export const I18N = {
|
||||
zh: `目标语言`,
|
||||
en: `Target Language`,
|
||||
},
|
||||
to_lang2: {
|
||||
zh: `第二目标语言`,
|
||||
en: `Target Language 2`,
|
||||
},
|
||||
to_lang2_helper: {
|
||||
zh: `设定后,与目标语言产生互译效果,但依赖远程语言识别。`,
|
||||
en: `After setting, it will produce mutual translation effect with the target language, but it relies on remote language recognition.`,
|
||||
},
|
||||
text_style: {
|
||||
zh: `文字样式`,
|
||||
en: `Text Style`,
|
||||
@@ -335,6 +343,10 @@ export const I18N = {
|
||||
zh: `高亮`,
|
||||
en: `Highlight`,
|
||||
},
|
||||
blockquote: {
|
||||
zh: `引用`,
|
||||
en: `Blockquote`,
|
||||
},
|
||||
diy_style: {
|
||||
zh: `自定义样式`,
|
||||
en: `Custom Style`,
|
||||
@@ -352,8 +364,8 @@ export const I18N = {
|
||||
en: `URL pattern`,
|
||||
},
|
||||
pattern_helper: {
|
||||
zh: `1、支持星号(*)通配符。2、多个URL支持英文逗号“,”分隔。`,
|
||||
en: `1. The asterisk (*) wildcard is supported. 2. Multiple URLs can be separated by English commas ",".`,
|
||||
zh: `1、支持星号(*)通配符。2、多个URL用英文逗号“,”分隔。`,
|
||||
en: `1. The asterisk (*) wildcard is supported. 2. Multiple URLs separated by English commas ",".`,
|
||||
},
|
||||
selector_helper: {
|
||||
zh: `1、遵循CSS选择器语法。2、留空表示采用全局设置。3、多个CSS选择器之间用“;”隔开。4、“shadow root”选择器和内部选择器用“>>>”隔开。`,
|
||||
@@ -375,6 +387,14 @@ export const I18N = {
|
||||
zh: `选择器`,
|
||||
en: `Selector`,
|
||||
},
|
||||
root_selector: {
|
||||
zh: `根选择器`,
|
||||
en: `Root Selector`,
|
||||
},
|
||||
fixer_function: {
|
||||
zh: `修复函数`,
|
||||
en: `Fixer Function`,
|
||||
},
|
||||
import: {
|
||||
zh: `导入`,
|
||||
en: `Import`,
|
||||
@@ -539,6 +559,10 @@ export const I18N = {
|
||||
zh: `隐藏悬浮按钮`,
|
||||
en: `Hide Fab Button`,
|
||||
},
|
||||
hide_tran_button: {
|
||||
zh: `隐藏翻译按钮`,
|
||||
en: `Hide Translate Button`,
|
||||
},
|
||||
show: {
|
||||
zh: `显示`,
|
||||
en: `Show`,
|
||||
@@ -620,8 +644,8 @@ export const I18N = {
|
||||
en: `Use Selection Translate`,
|
||||
},
|
||||
trigger_tranbox_shortcut: {
|
||||
zh: `显示翻译框快捷键`,
|
||||
en: `Toggle Translate Box Shortcut`,
|
||||
zh: `显示翻译框/翻译选中文字快捷键`,
|
||||
en: `Open Translate Popup/Translate Selected Shortcut`,
|
||||
},
|
||||
tranbtn_offset_x: {
|
||||
zh: `翻译按钮偏移X(0-100)`,
|
||||
@@ -643,4 +667,44 @@ export const I18N = {
|
||||
zh: `收藏词汇`,
|
||||
en: `Favorite Words`,
|
||||
},
|
||||
touch_setting: {
|
||||
zh: `触屏设置`,
|
||||
en: `Touch Setting`,
|
||||
},
|
||||
touch_translate_shortcut: {
|
||||
zh: `触屏翻译快捷方式`,
|
||||
en: `Touch Translate Shortcut`,
|
||||
},
|
||||
touch_tap_0: {
|
||||
zh: `禁用`,
|
||||
en: `Disable`,
|
||||
},
|
||||
touch_tap_2: {
|
||||
zh: `双指轻触`,
|
||||
en: `Two finger tap`,
|
||||
},
|
||||
touch_tap_3: {
|
||||
zh: `三指轻触`,
|
||||
en: `Three finger tap`,
|
||||
},
|
||||
touch_tap_4: {
|
||||
zh: `四指轻触`,
|
||||
en: `Four finger tap`,
|
||||
},
|
||||
translate_blacklist: {
|
||||
zh: `禁用翻译名单`,
|
||||
en: `Translate Blacklist`,
|
||||
},
|
||||
disable_langs: {
|
||||
zh: `不翻译的语言`,
|
||||
en: `Disable Languages`,
|
||||
},
|
||||
disable_langs_helper: {
|
||||
zh: `此功能依赖准确的语言检测,建议启用远程语言检测。`,
|
||||
en: `This feature relies on accurate language detection. It is recommended to enable remote language detection.`,
|
||||
},
|
||||
add_context_menus: {
|
||||
zh: `添加右键菜单`,
|
||||
en: `Add Context Menus`,
|
||||
},
|
||||
};
|
||||
|
||||
@@ -23,6 +23,7 @@ export const STOKEY_MSAUTH = `${APP_NAME}_msauth`;
|
||||
export const STOKEY_BDAUTH = `${APP_NAME}_bdauth`;
|
||||
export const STOKEY_SETTING = `${APP_NAME}_setting`;
|
||||
export const STOKEY_RULES = `${APP_NAME}_rules`;
|
||||
export const STOKEY_WFRULES = `${APP_NAME}_webfix_rules`;
|
||||
export const STOKEY_WORDS = `${APP_NAME}_words`;
|
||||
export const STOKEY_SYNC = `${APP_NAME}_sync`;
|
||||
export const STOKEY_FAB = `${APP_NAME}_fab`;
|
||||
@@ -32,6 +33,7 @@ export const STOKEY_WEBFIXCACHE_PREFIX = `${APP_NAME}_webfixcache_`;
|
||||
export const CMD_TOGGLE_TRANSLATE = "toggleTranslate";
|
||||
export const CMD_TOGGLE_STYLE = "toggleStyle";
|
||||
export const CMD_OPEN_OPTIONS = "openOptions";
|
||||
export const CMD_OPEN_TRANBOX = "openTranbox";
|
||||
|
||||
export const CLIENT_WEB = "web";
|
||||
export const CLIENT_CHROME = "chrome";
|
||||
@@ -41,6 +43,7 @@ export const CLIENT_USERSCRIPT = "userscript";
|
||||
export const CLIENT_EXTS = [CLIENT_CHROME, CLIENT_EDGE, CLIENT_FIREFOX];
|
||||
|
||||
export const KV_RULES_KEY = "kiss-rules.json";
|
||||
export const KV_WFRULES_KEY = "kiss-webfix.json";
|
||||
export const KV_WORDS_KEY = "kiss-words.json";
|
||||
export const KV_RULES_SHARE_KEY = "kiss-rules-share.json";
|
||||
export const KV_SETTING_KEY = "kiss-setting.json";
|
||||
@@ -56,9 +59,11 @@ export const MSG_OPEN_OPTIONS = "open_options";
|
||||
export const MSG_SAVE_RULE = "save_rule";
|
||||
export const MSG_TRANS_TOGGLE = "trans_toggle";
|
||||
export const MSG_TRANS_TOGGLE_STYLE = "trans_toggle_style";
|
||||
export const MSG_OPEN_TRANBOX = "open_tranbox";
|
||||
export const MSG_TRANS_GETRULE = "trans_getrule";
|
||||
export const MSG_TRANS_PUTRULE = "trans_putrule";
|
||||
export const MSG_TRANS_CURRULE = "trans_currule";
|
||||
export const MSG_CONTEXT_MENUS = "context_menus";
|
||||
|
||||
export const THEME_LIGHT = "light";
|
||||
export const THEME_DARK = "dark";
|
||||
@@ -89,6 +94,7 @@ export const OPT_TRANS_DEEPLFREE = "DeepLFree";
|
||||
export const OPT_TRANS_BAIDU = "Baidu";
|
||||
export const OPT_TRANS_TENCENT = "Tencent";
|
||||
export const OPT_TRANS_OPENAI = "OpenAI";
|
||||
export const OPT_TRANS_GEMINI = "Gemini";
|
||||
export const OPT_TRANS_CLOUDFLAREAI = "CloudflareAI";
|
||||
export const OPT_TRANS_CUSTOMIZE = "Custom";
|
||||
export const OPT_TRANS_ALL = [
|
||||
@@ -100,6 +106,7 @@ export const OPT_TRANS_ALL = [
|
||||
OPT_TRANS_BAIDU,
|
||||
OPT_TRANS_TENCENT,
|
||||
OPT_TRANS_OPENAI,
|
||||
OPT_TRANS_GEMINI,
|
||||
OPT_TRANS_CLOUDFLAREAI,
|
||||
OPT_TRANS_CUSTOMIZE,
|
||||
];
|
||||
@@ -222,6 +229,9 @@ export const OPT_LANGS_SPECIAL = {
|
||||
[OPT_TRANS_OPENAI]: new Map(
|
||||
OPT_LANGS_FROM.map(([key, val]) => [key, val.split(" - ")[0]])
|
||||
),
|
||||
[OPT_TRANS_GEMINI]: new Map(
|
||||
OPT_LANGS_FROM.map(([key, val]) => [key, val.split(" - ")[0]])
|
||||
),
|
||||
[OPT_TRANS_CLOUDFLAREAI]: new Map([
|
||||
["auto", ""],
|
||||
["zh-CN", "chinese"],
|
||||
@@ -263,6 +273,7 @@ export const OPT_STYLE_DASHLINE = "dash_line"; // 虚线
|
||||
export const OPT_STYLE_WAVYLINE = "wavy_line"; // 波浪线
|
||||
export const OPT_STYLE_FUZZY = "fuzzy"; // 模糊
|
||||
export const OPT_STYLE_HIGHLIGHT = "highlight"; // 高亮
|
||||
export const OPT_STYLE_BLOCKQUOTE = "blockquote"; // 引用
|
||||
export const OPT_STYLE_DIY = "diy_style"; // 自定义样式
|
||||
export const OPT_STYLE_ALL = [
|
||||
OPT_STYLE_NONE,
|
||||
@@ -272,6 +283,7 @@ export const OPT_STYLE_ALL = [
|
||||
OPT_STYLE_WAVYLINE,
|
||||
OPT_STYLE_FUZZY,
|
||||
OPT_STYLE_HIGHLIGHT,
|
||||
OPT_STYLE_BLOCKQUOTE,
|
||||
OPT_STYLE_DIY,
|
||||
];
|
||||
export const OPT_STYLE_USE_COLOR = [
|
||||
@@ -280,6 +292,7 @@ export const OPT_STYLE_USE_COLOR = [
|
||||
OPT_STYLE_DASHLINE,
|
||||
OPT_STYLE_WAVYLINE,
|
||||
OPT_STYLE_HIGHLIGHT,
|
||||
OPT_STYLE_BLOCKQUOTE,
|
||||
];
|
||||
|
||||
export const OPT_MOUSEKEY_DISABLE = "mk_disable";
|
||||
@@ -300,6 +313,7 @@ export const DEFAULT_FETCH_INTERVAL = 100; // 默认任务间隔时间
|
||||
|
||||
export const PROMPT_PLACE_FROM = "{{from}}"; // 占位符
|
||||
export const PROMPT_PLACE_TO = "{{to}}"; // 占位符
|
||||
export const PROMPT_PLACE_TEXT = "{{text}}"; // 占位符
|
||||
|
||||
export const DEFAULT_COLOR = "#209CEE"; // 默认高亮背景色/线条颜色
|
||||
|
||||
@@ -331,15 +345,17 @@ export const DEFAULT_INPUT_RULE = {
|
||||
};
|
||||
|
||||
// 划词翻译
|
||||
export const DEFAULT_TRANBOX_SHORTCUT = ["AltLeft", "KeyB"];
|
||||
export const DEFAULT_TRANBOX_SHORTCUT = ["AltLeft", "KeyS"];
|
||||
export const DEFAULT_TRANBOX_SETTING = {
|
||||
transOpen: true,
|
||||
translator: OPT_TRANS_MICROSOFT,
|
||||
fromLang: "auto",
|
||||
toLang: "zh-CN",
|
||||
toLang2: "en",
|
||||
tranboxShortcut: DEFAULT_TRANBOX_SHORTCUT,
|
||||
btnOffsetX: 10,
|
||||
btnOffsetY: 10,
|
||||
hideTranBtn: false,
|
||||
};
|
||||
|
||||
// 订阅列表
|
||||
@@ -378,6 +394,12 @@ export const DEFAULT_TRANS_APIS = {
|
||||
model: "gpt-4",
|
||||
prompt: `You will be provided with a sentence in ${PROMPT_PLACE_FROM}, and your task is to translate it into ${PROMPT_PLACE_TO}.`,
|
||||
},
|
||||
[OPT_TRANS_GEMINI]: {
|
||||
url: "https://generativelanguage.googleapis.com/v1/models",
|
||||
key: "",
|
||||
model: "gemini-pro",
|
||||
prompt: `Translate the following text from ${PROMPT_PLACE_FROM} to ${PROMPT_PLACE_TO}:\n\n${PROMPT_PLACE_TEXT}`,
|
||||
},
|
||||
[OPT_TRANS_CLOUDFLAREAI]: {
|
||||
url: "https://api.cloudflare.com/client/v4/accounts/{ACCOUNT_ID}/ai/run/@cf/meta/m2m100-1.2b",
|
||||
key: "",
|
||||
@@ -397,12 +419,19 @@ export const DEFAULT_SHORTCUTS = {
|
||||
[OPT_SHORTCUT_TRANSLATE]: ["AltLeft", "KeyQ"],
|
||||
[OPT_SHORTCUT_STYLE]: ["AltLeft", "KeyC"],
|
||||
[OPT_SHORTCUT_POPUP]: ["AltLeft", "KeyK"],
|
||||
[OPT_SHORTCUT_SETTING]: ["AltLeft", "KeyN"],
|
||||
[OPT_SHORTCUT_SETTING]: ["AltLeft", "KeyO"],
|
||||
};
|
||||
|
||||
export const TRANS_MIN_LENGTH = 5; // 最短翻译长度
|
||||
export const TRANS_MAX_LENGTH = 5000; // 最长翻译长度
|
||||
export const TRANS_NEWLINE_LENGTH = 20; // 换行字符数
|
||||
export const DEFAULT_BLACKLIST = [
|
||||
"https://fishjar.github.io/kiss-translator/options.html",
|
||||
"https://translate.google.com",
|
||||
"https://www.deepl.com/translator",
|
||||
"oapi.dingtalk.com",
|
||||
"login.dingtalk.com",
|
||||
]; // 禁用翻译名单
|
||||
|
||||
export const DEFAULT_SETTING = {
|
||||
darkMode: false, // 深色模式
|
||||
@@ -416,6 +445,7 @@ export const DEFAULT_SETTING = {
|
||||
injectRules: true, // 是否注入订阅规则
|
||||
injectWebfix: true, // 是否注入修复补丁
|
||||
detectRemote: false, // 是否使用远程语言检测
|
||||
contextMenus: true, // 是否添加右键菜单
|
||||
subrulesList: DEFAULT_SUBRULES_LIST, // 订阅列表
|
||||
owSubrule: DEFAULT_OW_RULE, // 覆写订阅规则
|
||||
transApis: DEFAULT_TRANS_APIS, // 翻译接口
|
||||
@@ -423,6 +453,9 @@ export const DEFAULT_SETTING = {
|
||||
shortcuts: DEFAULT_SHORTCUTS, // 快捷键
|
||||
inputRule: DEFAULT_INPUT_RULE, // 输入框设置
|
||||
tranboxSetting: DEFAULT_TRANBOX_SETTING, // 划词翻译设置
|
||||
touchTranslate: 2, // 触屏翻译
|
||||
blacklist: DEFAULT_BLACKLIST.join(",\n"), // 禁用翻译名单
|
||||
disableLangs: [], // 不翻译的语言
|
||||
};
|
||||
|
||||
export const DEFAULT_RULES = [GLOBLA_RULE];
|
||||
|
||||
@@ -1,6 +1,4 @@
|
||||
const els = `li, p, h1, h2, h3, h4, h5, h6, dd, blockquote`;
|
||||
|
||||
export const DEFAULT_SELECTOR = `:is(${els})`;
|
||||
export const DEFAULT_SELECTOR = `:is(li, p, h1, h2, h3, h4, h5, h6, dd, blockquote)`;
|
||||
|
||||
export const GLOBAL_KEY = "*";
|
||||
export const REMAIN_KEY = "-";
|
||||
@@ -42,145 +40,66 @@ export const DEFAULT_OW_RULE = {
|
||||
textDiyStyle: DEFAULT_DIY_STYLE,
|
||||
};
|
||||
|
||||
const RULES = [
|
||||
{
|
||||
pattern: `www.google.com/search`,
|
||||
selector: `h3, .IsZvec, .VwiC3b`,
|
||||
},
|
||||
{
|
||||
pattern: `news.google.com`,
|
||||
selector: `h4`,
|
||||
},
|
||||
{
|
||||
pattern: `www.foxnews.com`,
|
||||
selector: `h1, h2, .title, .sidebar [data-type="Title"], .article-content ${DEFAULT_SELECTOR}; [data-spotim-module="conversation"]>div >>> [data-spot-im-class="message-text"] p, [data-spot-im-class="message-text"]`,
|
||||
},
|
||||
{
|
||||
pattern: `bearblog.dev, www.theverge.com, www.tampermonkey.net/documentation.php`,
|
||||
selector: DEFAULT_SELECTOR,
|
||||
},
|
||||
{
|
||||
pattern: `themessenger.com`,
|
||||
selector: `.leading-tight, .leading-tighter, .my-2 p, .font-body p, article ${DEFAULT_SELECTOR}`,
|
||||
},
|
||||
{
|
||||
pattern: `www.telegraph.co.uk`,
|
||||
selector: `article ${DEFAULT_SELECTOR}`,
|
||||
},
|
||||
{
|
||||
pattern: `www.theguardian.com`,
|
||||
selector: `.show-underline, .dcr-hup5wm div, .dcr-7vl6y8 div, .dcr-12evv1c, figcaption, article ${DEFAULT_SELECTOR}, [data-cy="mostviewed-footer"] h4`,
|
||||
},
|
||||
{
|
||||
pattern: `www.semafor.com`,
|
||||
selector: `${DEFAULT_SELECTOR}, .styles_intro__IYj__, [class*="styles_description"]`,
|
||||
},
|
||||
{
|
||||
pattern: `www.noemamag.com`,
|
||||
selector: `.splash__title, .single-card__title, .single-card__type, .single-card__topic, .highlighted-content__title, .single-card__author, article ${DEFAULT_SELECTOR}, .quote__text, .wp-caption-text div`,
|
||||
},
|
||||
{
|
||||
pattern: `restofworld.org`,
|
||||
selector: `${DEFAULT_SELECTOR}, .recirc-story__headline, .recirc-story__dek`,
|
||||
},
|
||||
{
|
||||
pattern: `www.axios.com`,
|
||||
selector: `.h7, ${DEFAULT_SELECTOR}`,
|
||||
},
|
||||
{
|
||||
pattern: `www.newyorker.com`,
|
||||
selector: `.summary-item__hed, .summary-item__dek, .summary-collection-grid__dek, .dqtvfu, .rubric__link, .caption, article ${DEFAULT_SELECTOR}, .HEhan ${DEFAULT_SELECTOR}, .ContributorBioBio-fBolsO`,
|
||||
},
|
||||
{
|
||||
pattern: `https://time.com/`,
|
||||
selector: `h1, h3, .summary, .video-title, #article-body ${DEFAULT_SELECTOR}, .image-wrap-container .credit.body-caption, .media-heading`,
|
||||
},
|
||||
{
|
||||
pattern: `www.dw.com`,
|
||||
selector: `.ts-teaser-title a, .news-title a, .title a, .teaser-description a, .hbudab h3, .hbudab p, figcaption ,article ${DEFAULT_SELECTOR}`,
|
||||
},
|
||||
{
|
||||
pattern: `www.bbc.com`,
|
||||
selector: `h1, h2, .media__link, .media__summary, article ${DEFAULT_SELECTOR}, .ssrcss-y7krbn-Stack, .ssrcss-1mrs5ns-PromoLink, .ssrcss-18cjaf3-Headline, .gs-c-promo-heading__title, .gs-c-promo-summary, .media__content h3, .article__intro`,
|
||||
},
|
||||
{
|
||||
pattern: `www.chinadaily.com.cn`,
|
||||
selector: `h1, .tMain [shape="rect"], .cMain [shape="rect"], .photo_art [shape="rect"], .mai_r [shape="rect"], .lisBox li, #Content ${DEFAULT_SELECTOR}`,
|
||||
},
|
||||
{
|
||||
pattern: `www.facebook.com`,
|
||||
selector: `[role="main"] [dir="auto"]`,
|
||||
},
|
||||
{
|
||||
pattern: `www.reddit.com`,
|
||||
selector: `[slot="title"], [slot="text-body"] ${DEFAULT_SELECTOR}, #-post-rtjson-content p`,
|
||||
},
|
||||
{
|
||||
pattern: `www.quora.com`,
|
||||
selector: `.qu-wordBreak--break-word`,
|
||||
},
|
||||
{
|
||||
pattern: `edition.cnn.com`,
|
||||
selector: `.container__title, .container__headline, .headline__text, .image__caption, [data-type="Title"], .article__content ${DEFAULT_SELECTOR}`,
|
||||
},
|
||||
{
|
||||
pattern: `www.reuters.com`,
|
||||
selector: `#main-content [data-testid="Heading"], #main-content [data-testid="Body"], .article-body__content__17Yit ${DEFAULT_SELECTOR}`,
|
||||
},
|
||||
{
|
||||
pattern: `www.bloomberg.com`,
|
||||
selector: `[data-component="headline"], [data-component="related-item-headline"], [data-component="title"], article ${DEFAULT_SELECTOR}`,
|
||||
},
|
||||
{
|
||||
pattern: `deno.land, docs.github.com`,
|
||||
selector: `main ${DEFAULT_SELECTOR}`,
|
||||
},
|
||||
{
|
||||
pattern: `doc.rust-lang.org`,
|
||||
selector: `#content ${DEFAULT_SELECTOR}`,
|
||||
},
|
||||
{
|
||||
pattern: `www.indiehackers.com`,
|
||||
selector: `h1, h3, .content ${DEFAULT_SELECTOR}, .feed-item__title-link`,
|
||||
},
|
||||
{
|
||||
pattern: `platform.openai.com/docs`,
|
||||
selector: `.docs-body ${DEFAULT_SELECTOR}`,
|
||||
},
|
||||
{
|
||||
pattern: `en.wikipedia.org`,
|
||||
selector: `h1, .mw-parser-output ${DEFAULT_SELECTOR}`,
|
||||
},
|
||||
{
|
||||
pattern: `stackoverflow.com`,
|
||||
selector: `h1, .s-prose p, .comment-body .comment-copy`,
|
||||
},
|
||||
{
|
||||
pattern: `www.npmjs.com/package/, developer.chrome.com/docs, medium.com, developers.cloudflare.com, react.dev, create-react-app.dev, pytorch.org/`,
|
||||
selector: `article ${DEFAULT_SELECTOR}`,
|
||||
},
|
||||
{
|
||||
pattern: `news.ycombinator.com`,
|
||||
selector: `.title, .commtext`,
|
||||
},
|
||||
{
|
||||
pattern: `https://github.com/`,
|
||||
selector: `.markdown-body ${DEFAULT_SELECTOR}, .repo-description p, .Layout-sidebar .f4, .container-lg .py-4 .f5, .container-lg .my-4 .f5, .Box-row .pr-4, .Box-row article .mt-1, [itemprop='description'], .markdown-title, bdi`,
|
||||
},
|
||||
{
|
||||
pattern: `twitter.com`,
|
||||
selector: `[data-testid='tweetText']`,
|
||||
},
|
||||
{
|
||||
pattern: `youtube.com`,
|
||||
selector: `h1, #video-title, #content-text, #title, yt-attributed-string>span>span`,
|
||||
},
|
||||
];
|
||||
const RULES_MAP = {
|
||||
"www.google.com/search": `h3, .IsZvec, .VwiC3b`,
|
||||
"news.google.com": `[role="link"], .DY5T1d, .ifw3f, ${DEFAULT_SELECTOR}`,
|
||||
"www.foxnews.com": `h1, h2, .title, .sidebar [data-type="Title"], .article-content ${DEFAULT_SELECTOR}; [data-spotim-module="conversation"]>div >>> [data-spot-im-class="message-text"] p, [data-spot-im-class="message-text"]`,
|
||||
"bearblog.dev, www.theverge.com, www.tampermonkey.net/documentation.php": `${DEFAULT_SELECTOR}`,
|
||||
"themessenger.com": `.leading-tight, .leading-tighter, .my-2 p, .font-body p, article ${DEFAULT_SELECTOR}`,
|
||||
"www.telegraph.co.uk, go.dev/doc/": `article ${DEFAULT_SELECTOR}`,
|
||||
"www.theguardian.com": `.show-underline, .dcr-hup5wm div, .dcr-7vl6y8 div, .dcr-12evv1c, figcaption, article ${DEFAULT_SELECTOR}, [data-cy="mostviewed-footer"] h4`,
|
||||
"www.semafor.com": `${DEFAULT_SELECTOR}, .styles_intro__IYj__, [class*="styles_description"]`,
|
||||
"www.noemamag.com": `.splash__title, .single-card__title, .single-card__type, .single-card__topic, .highlighted-content__title, .single-card__author, article ${DEFAULT_SELECTOR}, .quote__text, .wp-caption-text div`,
|
||||
"restofworld.org": `${DEFAULT_SELECTOR}, .recirc-story__headline, .recirc-story__dek`,
|
||||
"www.axios.com": `.h7, ${DEFAULT_SELECTOR}`,
|
||||
"www.newyorker.com": `.summary-item__hed, .summary-item__dek, .summary-collection-grid__dek, .dqtvfu, .rubric__link, .caption, article ${DEFAULT_SELECTOR}, .HEhan ${DEFAULT_SELECTOR}, .ContributorBioBio-fBolsO`,
|
||||
"time.com": `h1, h3, .summary, .video-title, #article-body ${DEFAULT_SELECTOR}, .image-wrap-container .credit.body-caption, .media-heading`,
|
||||
"www.dw.com": `.ts-teaser-title a, .news-title a, .title a, .teaser-description a, .hbudab h3, .hbudab p, figcaption ,article ${DEFAULT_SELECTOR}`,
|
||||
"www.bbc.com": `h1, h2, .media__link, .media__summary, article ${DEFAULT_SELECTOR}, .ssrcss-y7krbn-Stack, .ssrcss-17zglt8-PromoHeadline, .ssrcss-18cjaf3-Headline, .gs-c-promo-heading__title, .gs-c-promo-summary, .media__content h3, .article__intro`,
|
||||
"www.chinadaily.com.cn": `h1, .tMain [shape="rect"], .cMain [shape="rect"], .photo_art [shape="rect"], .mai_r [shape="rect"], .lisBox li, #Content ${DEFAULT_SELECTOR}`,
|
||||
"www.facebook.com": `[role="main"] [dir="auto"]`,
|
||||
"www.reddit.com": `[slot="title"], [slot="text-body"] ${DEFAULT_SELECTOR}, #-post-rtjson-content p`,
|
||||
"www.quora.com": `.qu-wordBreak--break-word`,
|
||||
"edition.cnn.com": `.container__title, .container__headline, .headline__text, .image__caption, [data-type="Title"], .article__content ${DEFAULT_SELECTOR}`,
|
||||
"www.reuters.com": `#main-content [data-testid="Heading"], #main-content [data-testid="Body"], .article-body__content__17Yit ${DEFAULT_SELECTOR}`,
|
||||
"www.bloomberg.com": `[data-component="headline"], [data-component="related-item-headline"], [data-component="title"], article ${DEFAULT_SELECTOR}`,
|
||||
"deno.land, docs.github.com": `main ${DEFAULT_SELECTOR}`,
|
||||
"doc.rust-lang.org": `.content ${DEFAULT_SELECTOR}`,
|
||||
"www.indiehackers.com": `h1, h3, .content ${DEFAULT_SELECTOR}, .feed-item__title-link`,
|
||||
"platform.openai.com/docs": `.docs-body ${DEFAULT_SELECTOR}`,
|
||||
"en.wikipedia.org": `h1, .mw-parser-output ${DEFAULT_SELECTOR}`,
|
||||
"stackoverflow.com": `h1, .s-prose p, .comment-body .comment-copy`,
|
||||
"www.npmjs.com/package, developer.chrome.com/docs, medium.com, developers.cloudflare.com, react.dev, create-react-app.dev, pytorch.org": `article ${DEFAULT_SELECTOR}`,
|
||||
"news.ycombinator.com": `.title, .commtext`,
|
||||
"github.com": `.markdown-body ${DEFAULT_SELECTOR}, .repo-description p, .Layout-sidebar .f4, .container-lg .py-4 .f5, .container-lg .my-4 .f5, .Box-row .pr-4, .Box-row article .mt-1, [itemprop="description"], .markdown-title, bdi, .ws-pre-wrap, .status-meta, span.status-meta, .col-10.color-fg-muted, .TimelineItem-body, .pinned-item-list-item-content .color-fg-muted, .markdown-body td, .markdown-body th`,
|
||||
"twitter.com": `[data-testid="tweetText"]`,
|
||||
"m.youtube.com": `.slim-video-information-title .yt-core-attributed-string, .media-item-headline .yt-core-attributed-string, .comment-text .yt-core-attributed-string, .typography-body-2b .yt-core-attributed-string, #ytp-caption-window-container .ytp-caption-segment`,
|
||||
"www.youtube.com": `h1, #video-title, #content-text, #title, yt-attributed-string>span>span, #ytp-caption-window-container .ytp-caption-segment`,
|
||||
"bard.google.com": `.query-content ${DEFAULT_SELECTOR}, message-content ${DEFAULT_SELECTOR}`,
|
||||
"www.bing.com": `.b_algoSlug, .rwrl_padref; .cib-serp-main >>> .ac-textBlock ${DEFAULT_SELECTOR}, .text-message-content div`,
|
||||
"www.phoronix.com": `article ${DEFAULT_SELECTOR}`,
|
||||
"wx2.qq.com": `.js_message_plain`,
|
||||
"app.slack.com/client/": `.p-rich_text_section, .c-message_attachment__text, .p-rich_text_list li`,
|
||||
"discord.com/channels/": `div[id^=message-content]`,
|
||||
"t.me/s/": `.js-message_text ${DEFAULT_SELECTOR}`,
|
||||
"web.telegram.org/k/": `.message, .bot-commands-list-element-description, .reply-markup-button-text`,
|
||||
"web.telegram.org/a/": `.message, .text-content, .bot-commands-list-element-description, .reply-markup-button-text`,
|
||||
"chromereleases.googleblog.com": `.title, .publishdate, p, i, .header-desc, .header-title, .text`,
|
||||
"www.instagram.com/": `h1, article span[dir=auto] > span[dir=auto], ._ab1y`,
|
||||
"www.instagram.com/p/,www.instagram.com/reels/": `h1, div[class='x9f619 xjbqb8w x78zum5 x168nmei x13lgxp2 x5pf9jr xo71vjh x1uhb9sk x1plvlek xryxfnj x1c4vz4f x2lah0s xdt5ytf xqjyukv x1cy8zhl x1oa3qoh x1nhvcw1'] > span[class='x1lliihq x1plvlek xryxfnj x1n2onr6 x193iq5w xeuugli x1fj9vlw x13faqbe x1vvkbs x1s928wv xhkezso x1gmr53x x1cpjm7i x1fgarty x1943h6x x1i0vuye xvs91rp xo1l8bm x5n08af x10wh9bi x1wdrske x8viiok x18hxmgj'], span[class='x193iq5w xeuugli x1fj9vlw x13faqbe x1vvkbs xt0psk2 x1i0vuye xvs91rp xo1l8bm x5n08af x10wh9bi x1wdrske x8viiok x18hxmgj']`,
|
||||
"mail.google.com": `${DEFAULT_SELECTOR}, h2[data-thread-perm-id], span[data-thread-id], div[data-message-id] div[class=''], .messageBody, #views`,
|
||||
"web.whatsapp.com": `.copyable-text > span`,
|
||||
"chat.openai.com": `div[data-message-author-role] > div ${DEFAULT_SELECTOR}`,
|
||||
"forum.ru-board.com": `.tit, .dats, span.post ${DEFAULT_SELECTOR}`,
|
||||
"education.github.com": `${DEFAULT_SELECTOR}, a, summary, span.Button-content`,
|
||||
"blogs.windows.com": `${DEFAULT_SELECTOR}, .c-uhf-nav-link, figcaption`,
|
||||
"developer.apple.com/documentation/": `#main ${DEFAULT_SELECTOR}, #main .abstract .content, #main .abstract.content, #main .link span`,
|
||||
};
|
||||
|
||||
export const BUILTIN_RULES = RULES.sort((a, b) =>
|
||||
a.pattern.localeCompare(b.pattern)
|
||||
).map((item) => ({
|
||||
...DEFAULT_RULE,
|
||||
...item,
|
||||
transOpen: "true",
|
||||
}));
|
||||
export const BUILTIN_RULES = Object.entries(RULES_MAP)
|
||||
.sort((a, b) => a[0].localeCompare(b[0]))
|
||||
.map(([pattern, selector]) => ({
|
||||
...DEFAULT_RULE,
|
||||
pattern,
|
||||
selector,
|
||||
}));
|
||||
|
||||
@@ -1,76 +1,3 @@
|
||||
import { browser } from "./libs/browser";
|
||||
import {
|
||||
MSG_TRANS_TOGGLE,
|
||||
MSG_TRANS_TOGGLE_STYLE,
|
||||
MSG_TRANS_GETRULE,
|
||||
MSG_TRANS_PUTRULE,
|
||||
} from "./config";
|
||||
import { getSettingWithDefault } from "./libs/storage";
|
||||
import { isIframe, sendIframeMsg } from "./libs/iframe";
|
||||
import { runWebfix } from "./libs/webfix";
|
||||
import {
|
||||
runIframe,
|
||||
runTranslator,
|
||||
showFab,
|
||||
showTransbox,
|
||||
windowListener,
|
||||
showErr,
|
||||
} from "./common";
|
||||
import { run } from "./common";
|
||||
|
||||
function runtimeListener(translator) {
|
||||
browser?.runtime.onMessage.addListener(async ({ action, args }) => {
|
||||
switch (action) {
|
||||
case MSG_TRANS_TOGGLE:
|
||||
translator.toggle();
|
||||
sendIframeMsg(MSG_TRANS_TOGGLE);
|
||||
break;
|
||||
case MSG_TRANS_TOGGLE_STYLE:
|
||||
translator.toggleStyle();
|
||||
sendIframeMsg(MSG_TRANS_TOGGLE_STYLE);
|
||||
break;
|
||||
case MSG_TRANS_GETRULE:
|
||||
break;
|
||||
case MSG_TRANS_PUTRULE:
|
||||
translator.updateRule(args);
|
||||
sendIframeMsg(MSG_TRANS_PUTRULE, args);
|
||||
break;
|
||||
default:
|
||||
return { error: `message action is unavailable: ${action}` };
|
||||
}
|
||||
return { data: translator.rule };
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* 入口函数
|
||||
*/
|
||||
(async () => {
|
||||
try {
|
||||
// 读取设置信息
|
||||
const setting = await getSettingWithDefault();
|
||||
|
||||
// 适配iframe
|
||||
if (isIframe) {
|
||||
runIframe(setting);
|
||||
return;
|
||||
}
|
||||
|
||||
// 不规范网页修复
|
||||
await runWebfix(setting);
|
||||
|
||||
// 翻译网页
|
||||
const { translator, rule } = await runTranslator(setting);
|
||||
|
||||
// 监听消息
|
||||
windowListener(rule);
|
||||
runtimeListener(translator);
|
||||
|
||||
// 划词翻译
|
||||
showTransbox(setting);
|
||||
|
||||
// 浮球按钮
|
||||
await showFab(translator);
|
||||
} catch (err) {
|
||||
showErr(err);
|
||||
}
|
||||
})();
|
||||
run();
|
||||
|
||||
@@ -1,6 +1,12 @@
|
||||
import { useCallback, useEffect, useState } from "react";
|
||||
import { storage } from "../libs/storage";
|
||||
|
||||
/**
|
||||
*
|
||||
* @param {*} key
|
||||
* @param {*} defaultVal 需为调用hook外的常量
|
||||
* @returns
|
||||
*/
|
||||
export function useStorage(key, defaultVal) {
|
||||
const [loading, setLoading] = useState(false);
|
||||
const [data, setData] = useState(null);
|
||||
|
||||
@@ -12,10 +12,24 @@ import { THEME_DARK, THEME_LIGHT } from "../config";
|
||||
export default function Theme({ children, options }) {
|
||||
const { darkMode } = useDarkMode();
|
||||
const theme = useMemo(() => {
|
||||
let htmlFontSize = 16;
|
||||
try {
|
||||
const s = window.getComputedStyle(document.body.parentNode).fontSize;
|
||||
const fontSize = parseInt(s.replace("px", ""));
|
||||
if (fontSize > 0 && fontSize < 1000) {
|
||||
htmlFontSize = fontSize;
|
||||
}
|
||||
} catch (err) {
|
||||
//
|
||||
}
|
||||
|
||||
return createTheme({
|
||||
palette: {
|
||||
mode: darkMode ? THEME_DARK : THEME_LIGHT,
|
||||
},
|
||||
typography: {
|
||||
htmlFontSize,
|
||||
},
|
||||
...options,
|
||||
});
|
||||
}, [darkMode, options]);
|
||||
|
||||
@@ -24,7 +24,11 @@ export function useTranslate(q, rule, setting) {
|
||||
setLoading(true);
|
||||
|
||||
const deLang = await tryDetectLang(q, setting.detectRemote);
|
||||
if (deLang && toLang.includes(deLang)) {
|
||||
const disableLangs = setting.disableLangs || [];
|
||||
if (
|
||||
deLang &&
|
||||
(toLang.includes(deLang) || disableLangs.includes(deLang))
|
||||
) {
|
||||
setSamelang(true);
|
||||
} else {
|
||||
const [trText, isSame] = await apiTranslate({
|
||||
|
||||
58
src/hooks/WebfixRules.js
Normal file
58
src/hooks/WebfixRules.js
Normal file
@@ -0,0 +1,58 @@
|
||||
import { STOKEY_WFRULES, KV_WFRULES_KEY } from "../config";
|
||||
import { useStorage } from "./Storage";
|
||||
import { trySyncWebfixRules } from "../libs/sync";
|
||||
import { useCallback } from "react";
|
||||
import { useSyncMeta } from "./Sync";
|
||||
|
||||
const DEFAULT_WFRULES = [];
|
||||
|
||||
/**
|
||||
* 修复规则 hook
|
||||
* @returns
|
||||
*/
|
||||
export function useWebfixRules() {
|
||||
const { data: list, save } = useStorage(STOKEY_WFRULES, DEFAULT_WFRULES);
|
||||
const { updateSyncMeta } = useSyncMeta();
|
||||
|
||||
const updateRules = useCallback(
|
||||
async (rules) => {
|
||||
await save(rules);
|
||||
await updateSyncMeta(KV_WFRULES_KEY);
|
||||
trySyncWebfixRules();
|
||||
},
|
||||
[save, updateSyncMeta]
|
||||
);
|
||||
|
||||
const add = useCallback(
|
||||
async (rule) => {
|
||||
const rules = [...list];
|
||||
if (rules.map((item) => item.pattern).includes(rule.pattern)) {
|
||||
return;
|
||||
}
|
||||
rules.unshift(rule);
|
||||
await updateRules(rules);
|
||||
},
|
||||
[list, updateRules]
|
||||
);
|
||||
|
||||
const del = useCallback(
|
||||
async (pattern) => {
|
||||
let rules = [...list];
|
||||
rules = rules.filter((item) => item.pattern !== pattern);
|
||||
await updateRules(rules);
|
||||
},
|
||||
[list, updateRules]
|
||||
);
|
||||
|
||||
const put = useCallback(
|
||||
async (pattern, obj) => {
|
||||
const rules = [...list];
|
||||
const rule = rules.find((r) => r.pattern === pattern);
|
||||
rule && Object.assign(rule, obj);
|
||||
await updateRules(rules);
|
||||
},
|
||||
[list, updateRules]
|
||||
);
|
||||
|
||||
return { list, add, del, put };
|
||||
}
|
||||
13
src/libs/blacklist.js
Normal file
13
src/libs/blacklist.js
Normal file
@@ -0,0 +1,13 @@
|
||||
import { isMatch } from "./utils";
|
||||
import { DEFAULT_BLACKLIST } from "../config";
|
||||
|
||||
/**
|
||||
* 检查是否在黑名单中
|
||||
* @param {*} href
|
||||
* @param {*} param1
|
||||
* @returns
|
||||
*/
|
||||
export const isInBlacklist = (
|
||||
href,
|
||||
{ blacklist = DEFAULT_BLACKLIST.join(",\n") }
|
||||
) => blacklist.split(",").some((url) => isMatch(href, url.trim()));
|
||||
@@ -55,6 +55,10 @@ export const fetchApi = async ({ input, init, transOpts, apiSetting }) => {
|
||||
[input, init] = await newTransReq(transOpts, apiSetting);
|
||||
}
|
||||
|
||||
if (!input) {
|
||||
throw new Error("url is empty");
|
||||
}
|
||||
|
||||
if (isGm) {
|
||||
let info;
|
||||
if (window.KISS_GM) {
|
||||
@@ -127,7 +131,13 @@ export const fetchData = async (
|
||||
}
|
||||
|
||||
if (!res?.ok) {
|
||||
throw new Error(`response: ${res.statusText}`);
|
||||
const cause = {
|
||||
status: res.status,
|
||||
};
|
||||
if (res.headers.get("Content-Type")?.includes("json")) {
|
||||
cause.body = await res.json();
|
||||
}
|
||||
throw new Error(`response: [${res.status}] ${res.statusText}`, { cause });
|
||||
}
|
||||
|
||||
// 插入缓存
|
||||
@@ -163,7 +173,7 @@ export const fetchPolyfill = async (input, opts) => {
|
||||
if (isExt && !isBg()) {
|
||||
const res = await sendBgMsg(MSG_FETCH, { input, opts });
|
||||
if (res.error) {
|
||||
throw new Error(res.error);
|
||||
throw new Error(res.error, { cause: res.cause });
|
||||
}
|
||||
return res.data;
|
||||
}
|
||||
|
||||
205
src/libs/inputTranslate.js
Normal file
205
src/libs/inputTranslate.js
Normal file
@@ -0,0 +1,205 @@
|
||||
import {
|
||||
DEFAULT_INPUT_RULE,
|
||||
DEFAULT_TRANS_APIS,
|
||||
DEFAULT_INPUT_SHORTCUT,
|
||||
OPT_LANGS_LIST,
|
||||
} from "../config";
|
||||
import { genEventName, removeEndchar, matchInputStr, sleep } from "./utils";
|
||||
import { stepShortcutRegister } from "./shortcut";
|
||||
import { apiTranslate } from "../apis";
|
||||
import { tryDetectLang } from ".";
|
||||
import { loadingSvg } from "./svg";
|
||||
|
||||
function isInputNode(node) {
|
||||
return node.nodeName === "INPUT" || node.nodeName === "TEXTAREA";
|
||||
}
|
||||
|
||||
function isEditAbleNode(node) {
|
||||
return node.hasAttribute("contenteditable");
|
||||
}
|
||||
|
||||
function selectContent(node) {
|
||||
node.focus();
|
||||
const range = document.createRange();
|
||||
range.selectNodeContents(node);
|
||||
|
||||
const selection = window.getSelection();
|
||||
selection.removeAllRanges();
|
||||
selection.addRange(range);
|
||||
}
|
||||
|
||||
function pasteContentEvent(node, text) {
|
||||
node.focus();
|
||||
const data = new DataTransfer();
|
||||
data.setData("text/plain", text);
|
||||
|
||||
const event = new ClipboardEvent("paste", { clipboardData: data });
|
||||
document.dispatchEvent(event);
|
||||
data.clearData();
|
||||
}
|
||||
|
||||
function pasteContentCommand(node, text) {
|
||||
node.focus();
|
||||
document.execCommand("insertText", false, text);
|
||||
}
|
||||
|
||||
function collapseToEnd(node) {
|
||||
node.focus();
|
||||
const selection = window.getSelection();
|
||||
selection.collapseToEnd();
|
||||
}
|
||||
|
||||
function getNodeText(node) {
|
||||
if (isInputNode(node)) {
|
||||
return node.value;
|
||||
}
|
||||
return node.innerText || node.textContent || "";
|
||||
}
|
||||
|
||||
function addLoading(node, loadingId) {
|
||||
const div = document.createElement("div");
|
||||
div.id = loadingId;
|
||||
div.innerHTML = loadingSvg;
|
||||
div.style.cssText = `
|
||||
width: ${node.offsetWidth}px;
|
||||
height: ${node.offsetHeight}px;
|
||||
line-height: ${node.offsetHeight}px;
|
||||
position: absolute;
|
||||
text-align: center;
|
||||
left: ${node.offsetLeft}px;
|
||||
top: ${node.offsetTop}px;
|
||||
z-index: 2147483647;
|
||||
`;
|
||||
node.offsetParent?.appendChild(div);
|
||||
}
|
||||
|
||||
function removeLoading(node, loadingId) {
|
||||
const div = node.offsetParent.querySelector(`#${loadingId}`);
|
||||
if (div) {
|
||||
div.remove();
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 输入框翻译
|
||||
*/
|
||||
export default function inputTranslate ({
|
||||
inputRule: {
|
||||
transOpen,
|
||||
triggerShortcut,
|
||||
translator,
|
||||
fromLang,
|
||||
toLang,
|
||||
triggerCount,
|
||||
triggerTime,
|
||||
transSign,
|
||||
} = DEFAULT_INPUT_RULE,
|
||||
transApis,
|
||||
detectRemote,
|
||||
}) {
|
||||
if (!transOpen) {
|
||||
return;
|
||||
}
|
||||
|
||||
const apiSetting = transApis?.[translator] || DEFAULT_TRANS_APIS[translator];
|
||||
if (triggerShortcut.length === 0) {
|
||||
triggerShortcut = DEFAULT_INPUT_SHORTCUT;
|
||||
triggerCount = 1;
|
||||
}
|
||||
|
||||
stepShortcutRegister(
|
||||
triggerShortcut,
|
||||
async () => {
|
||||
let node = document.activeElement;
|
||||
|
||||
if (!node) {
|
||||
return;
|
||||
}
|
||||
|
||||
while (node.shadowRoot) {
|
||||
node = node.shadowRoot.activeElement;
|
||||
}
|
||||
|
||||
if (!isInputNode(node) && !isEditAbleNode(node)) {
|
||||
return;
|
||||
}
|
||||
|
||||
let initText = getNodeText(node);
|
||||
if (triggerShortcut.length === 1 && triggerShortcut[0].length === 1) {
|
||||
// todo: remove multiple char
|
||||
initText = removeEndchar(initText, triggerShortcut[0], triggerCount);
|
||||
}
|
||||
if (!initText.trim()) {
|
||||
return;
|
||||
}
|
||||
|
||||
let text = initText;
|
||||
if (transSign) {
|
||||
const res = matchInputStr(text, transSign);
|
||||
if (res) {
|
||||
let lang = res[1];
|
||||
if (lang === "zh" || lang === "cn") {
|
||||
lang = "zh-CN";
|
||||
} else if (lang === "tw" || lang === "hk") {
|
||||
lang = "zh-TW";
|
||||
}
|
||||
if (lang && OPT_LANGS_LIST.includes(lang)) {
|
||||
toLang = lang;
|
||||
}
|
||||
text = res[2];
|
||||
}
|
||||
}
|
||||
|
||||
// console.log("input -->", text);
|
||||
|
||||
const loadingId = "kiss-" + genEventName();
|
||||
try {
|
||||
addLoading(node, loadingId);
|
||||
|
||||
const deLang = await tryDetectLang(text, detectRemote);
|
||||
if (deLang && toLang.includes(deLang)) {
|
||||
return;
|
||||
}
|
||||
|
||||
const [trText, isSame] = await apiTranslate({
|
||||
translator,
|
||||
text,
|
||||
fromLang,
|
||||
toLang,
|
||||
apiSetting,
|
||||
});
|
||||
if (!trText || isSame) {
|
||||
return;
|
||||
}
|
||||
|
||||
if (isInputNode(node)) {
|
||||
node.value = trText;
|
||||
node.dispatchEvent(
|
||||
new Event("input", { bubbles: true, cancelable: true })
|
||||
);
|
||||
return;
|
||||
}
|
||||
|
||||
selectContent(node);
|
||||
await sleep(200);
|
||||
|
||||
pasteContentEvent(node, trText);
|
||||
await sleep(200);
|
||||
|
||||
// todo: use includes?
|
||||
if (getNodeText(node).startsWith(initText)) {
|
||||
pasteContentCommand(node, trText);
|
||||
await sleep(100);
|
||||
} else {
|
||||
collapseToEnd(node);
|
||||
}
|
||||
} catch (err) {
|
||||
console.log("[translate input]", err.message);
|
||||
} finally {
|
||||
removeLoading(node, loadingId);
|
||||
}
|
||||
},
|
||||
triggerCount,
|
||||
triggerTime
|
||||
);
|
||||
}
|
||||
@@ -8,12 +8,14 @@ import {
|
||||
OPT_TRANS_BAIDU,
|
||||
OPT_TRANS_TENCENT,
|
||||
OPT_TRANS_OPENAI,
|
||||
OPT_TRANS_GEMINI,
|
||||
OPT_TRANS_CLOUDFLAREAI,
|
||||
OPT_TRANS_CUSTOMIZE,
|
||||
URL_MICROSOFT_TRAN,
|
||||
URL_TENCENT_TRANSMART,
|
||||
PROMPT_PLACE_FROM,
|
||||
PROMPT_PLACE_TO,
|
||||
PROMPT_PLACE_TEXT,
|
||||
} from "../config";
|
||||
import { msAuth } from "./auth";
|
||||
import { genDeeplFree } from "../apis/deepl";
|
||||
@@ -178,6 +180,37 @@ const genOpenAI = ({ text, from, to, url, key, prompt, model }) => {
|
||||
return [url, init];
|
||||
};
|
||||
|
||||
const genGemini = ({ text, from, to, url, key, prompt, model }) => {
|
||||
prompt = prompt
|
||||
.replaceAll(PROMPT_PLACE_FROM, from)
|
||||
.replaceAll(PROMPT_PLACE_TO, to)
|
||||
.replaceAll(PROMPT_PLACE_TEXT, text);
|
||||
|
||||
const data = {
|
||||
contents: [
|
||||
{
|
||||
// role: "user",
|
||||
parts: [
|
||||
{
|
||||
text: prompt,
|
||||
},
|
||||
],
|
||||
},
|
||||
],
|
||||
};
|
||||
|
||||
const input = `${url}/${model}:generateContent?key=${key}`;
|
||||
const init = {
|
||||
headers: {
|
||||
"Content-type": "application/json",
|
||||
},
|
||||
method: "POST",
|
||||
body: JSON.stringify(data),
|
||||
};
|
||||
|
||||
return [input, init];
|
||||
};
|
||||
|
||||
const genCloudflareAI = ({ text, from, to, url, key }) => {
|
||||
const data = {
|
||||
text,
|
||||
@@ -241,6 +274,8 @@ export const newTransReq = ({ translator, text, from, to }, apiSetting) => {
|
||||
return genTencent(args);
|
||||
case OPT_TRANS_OPENAI:
|
||||
return genOpenAI(args);
|
||||
case OPT_TRANS_GEMINI:
|
||||
return genGemini(args);
|
||||
case OPT_TRANS_CLOUDFLAREAI:
|
||||
return genCloudflareAI(args);
|
||||
case OPT_TRANS_CUSTOMIZE:
|
||||
|
||||
@@ -21,7 +21,6 @@ import { trySyncRules } from "./sync";
|
||||
* @returns
|
||||
*/
|
||||
export const matchRule = async (
|
||||
rules,
|
||||
href,
|
||||
{
|
||||
injectRules = true,
|
||||
@@ -29,7 +28,7 @@ export const matchRule = async (
|
||||
owSubrule = DEFAULT_OW_RULE,
|
||||
}
|
||||
) => {
|
||||
rules = [...rules];
|
||||
const rules = await getRulesWithDefault();
|
||||
if (injectRules) {
|
||||
try {
|
||||
const selectedSub = subrulesList.find((item) => item.selected);
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
import {
|
||||
STOKEY_SETTING,
|
||||
STOKEY_RULES,
|
||||
STOKEY_WFRULES,
|
||||
STOKEY_WORDS,
|
||||
STOKEY_FAB,
|
||||
STOKEY_SYNC,
|
||||
@@ -98,6 +99,14 @@ export const getRulesWithDefault = async () =>
|
||||
(await getRules()) || DEFAULT_RULES;
|
||||
export const setRules = (val) => setObj(STOKEY_RULES, val);
|
||||
|
||||
/**
|
||||
* 修复规则列表
|
||||
*/
|
||||
export const getWebfixRules = () => getObj(STOKEY_WFRULES);
|
||||
export const getWebfixRulesWithDefault = async () =>
|
||||
(await getWebfixRules()) || [];
|
||||
export const setWebfixRules = (val) => setObj(STOKEY_WFRULES, val);
|
||||
|
||||
/**
|
||||
* 词汇列表
|
||||
*/
|
||||
|
||||
@@ -2,6 +2,7 @@ import {
|
||||
APP_LCNAME,
|
||||
KV_SETTING_KEY,
|
||||
KV_RULES_KEY,
|
||||
KV_WFRULES_KEY,
|
||||
KV_WORDS_KEY,
|
||||
KV_RULES_SHARE_KEY,
|
||||
KV_SALT_SHARE,
|
||||
@@ -13,8 +14,10 @@ import {
|
||||
getSettingWithDefault,
|
||||
getRulesWithDefault,
|
||||
getWordsWithDefault,
|
||||
getWebfixRulesWithDefault,
|
||||
setSetting,
|
||||
setRules,
|
||||
setWebfixRules,
|
||||
setWords,
|
||||
} from "./storage";
|
||||
import { apiSyncData } from "../apis";
|
||||
@@ -138,6 +141,25 @@ export const trySyncRules = async () => {
|
||||
}
|
||||
};
|
||||
|
||||
/**
|
||||
* 同步修复规则
|
||||
* @returns
|
||||
*/
|
||||
const syncWebfixRules = async () => {
|
||||
const res = await syncData(KV_WFRULES_KEY, getWebfixRulesWithDefault);
|
||||
if (res?.isNew) {
|
||||
await setWebfixRules(res.value);
|
||||
}
|
||||
};
|
||||
|
||||
export const trySyncWebfixRules = async () => {
|
||||
try {
|
||||
await syncWebfixRules();
|
||||
} catch (err) {
|
||||
console.log("[sync user webfix rules]", err);
|
||||
}
|
||||
};
|
||||
|
||||
/**
|
||||
* 同步词汇
|
||||
* @returns
|
||||
@@ -185,11 +207,13 @@ export const syncShareRules = async ({ rules, syncUrl, syncKey }) => {
|
||||
export const syncSettingAndRules = async () => {
|
||||
await syncSetting();
|
||||
await syncRules();
|
||||
await syncWebfixRules();
|
||||
await syncWords();
|
||||
};
|
||||
|
||||
export const trySyncSettingAndRules = async () => {
|
||||
await trySyncSetting();
|
||||
await trySyncRules();
|
||||
await trySyncWebfixRules();
|
||||
await trySyncWords();
|
||||
};
|
||||
|
||||
12
src/libs/touch.js
Normal file
12
src/libs/touch.js
Normal file
@@ -0,0 +1,12 @@
|
||||
export function touchTapListener(fn, touchsLength) {
|
||||
const handleTouchend = (e) => {
|
||||
if (e.touches.length === touchsLength) {
|
||||
fn();
|
||||
}
|
||||
};
|
||||
|
||||
document.addEventListener("touchstart", handleTouchend);
|
||||
return () => {
|
||||
document.removeEventListener("touchstart", handleTouchend);
|
||||
};
|
||||
}
|
||||
@@ -9,101 +9,16 @@ import {
|
||||
SHADOW_KEY,
|
||||
OPT_MOUSEKEY_DISABLE,
|
||||
OPT_MOUSEKEY_MOUSEOVER,
|
||||
DEFAULT_INPUT_RULE,
|
||||
DEFAULT_TRANS_APIS,
|
||||
DEFAULT_INPUT_SHORTCUT,
|
||||
OPT_LANGS_LIST,
|
||||
} from "../config";
|
||||
import Content from "../views/Content";
|
||||
import { updateFetchPool, clearFetchPool } from "./fetch";
|
||||
import {
|
||||
debounce,
|
||||
genEventName,
|
||||
removeEndchar,
|
||||
matchInputStr,
|
||||
sleep,
|
||||
} from "./utils";
|
||||
import { stepShortcutRegister } from "./shortcut";
|
||||
import { apiTranslate } from "../apis";
|
||||
import { tryDetectLang } from ".";
|
||||
import { loadingSvg } from "./svg";
|
||||
|
||||
function isInputNode(node) {
|
||||
return node.nodeName === "INPUT" || node.nodeName === "TEXTAREA";
|
||||
}
|
||||
|
||||
function isEditAbleNode(node) {
|
||||
return node.hasAttribute("contenteditable");
|
||||
}
|
||||
|
||||
function selectContent(node) {
|
||||
node.focus();
|
||||
const range = document.createRange();
|
||||
range.selectNodeContents(node);
|
||||
|
||||
const selection = window.getSelection();
|
||||
selection.removeAllRanges();
|
||||
selection.addRange(range);
|
||||
}
|
||||
|
||||
function pasteContentEvent(node, text) {
|
||||
node.focus();
|
||||
const data = new DataTransfer();
|
||||
data.setData("text/plain", text);
|
||||
|
||||
const event = new ClipboardEvent("paste", { clipboardData: data });
|
||||
document.dispatchEvent(event);
|
||||
data.clearData();
|
||||
}
|
||||
|
||||
function pasteContentCommand(node, text) {
|
||||
node.focus();
|
||||
document.execCommand("insertText", false, text);
|
||||
}
|
||||
|
||||
function collapseToEnd(node) {
|
||||
node.focus();
|
||||
const selection = window.getSelection();
|
||||
selection.collapseToEnd();
|
||||
}
|
||||
|
||||
function getNodeText(node) {
|
||||
if (isInputNode(node)) {
|
||||
return node.value;
|
||||
}
|
||||
return node.innerText || node.textContent || "";
|
||||
}
|
||||
|
||||
function addLoading(node, loadingId) {
|
||||
const div = document.createElement("div");
|
||||
div.id = loadingId;
|
||||
div.innerHTML = loadingSvg;
|
||||
div.style.cssText = `
|
||||
width: ${node.offsetWidth}px;
|
||||
height: ${node.offsetHeight}px;
|
||||
line-height: ${node.offsetHeight}px;
|
||||
position: absolute;
|
||||
text-align: center;
|
||||
left: ${node.offsetLeft}px;
|
||||
top: ${node.offsetTop}px;
|
||||
z-index: 2147483647;
|
||||
`;
|
||||
node.offsetParent?.appendChild(div);
|
||||
}
|
||||
|
||||
function removeLoading(node, loadingId) {
|
||||
const div = node.offsetParent.querySelector(`#${loadingId}`);
|
||||
if (div) {
|
||||
div.remove();
|
||||
}
|
||||
}
|
||||
import { debounce, genEventName } from "./utils";
|
||||
|
||||
/**
|
||||
* 翻译类
|
||||
*/
|
||||
export class Translator {
|
||||
_rule = {};
|
||||
_inputRule = {};
|
||||
_setting = {};
|
||||
_rootNodes = new Set();
|
||||
_tranNodes = new Map();
|
||||
@@ -187,11 +102,6 @@ export class Translator {
|
||||
if (rule.transOpen === "true") {
|
||||
this._register();
|
||||
}
|
||||
|
||||
this._inputRule = setting.inputRule || DEFAULT_INPUT_RULE;
|
||||
if (this._inputRule.transOpen) {
|
||||
this._registerInput();
|
||||
}
|
||||
}
|
||||
|
||||
get setting() {
|
||||
@@ -349,141 +259,22 @@ export class Translator {
|
||||
// 监听鼠标悬停
|
||||
window.addEventListener("keydown", this._handleKeydown);
|
||||
this._tranNodes.forEach((_, node) => {
|
||||
node.addEventListener("mouseover", this._handleMouseover);
|
||||
node.addEventListener("mouseout", this._handleMouseout);
|
||||
node.addEventListener("mouseenter", this._handleMouseover);
|
||||
node.addEventListener("mouseleave", this._handleMouseout);
|
||||
});
|
||||
}
|
||||
};
|
||||
|
||||
_registerInput = () => {
|
||||
const {
|
||||
triggerShortcut: initTriggerShortcut,
|
||||
translator,
|
||||
fromLang,
|
||||
toLang: initToLang,
|
||||
triggerCount: initTriggerCount,
|
||||
triggerTime,
|
||||
transSign,
|
||||
} = this._inputRule;
|
||||
const apiSetting =
|
||||
this._setting.transApis?.[translator] || DEFAULT_TRANS_APIS[translator];
|
||||
const { detectRemote } = this._setting;
|
||||
|
||||
let triggerShortcut = initTriggerShortcut;
|
||||
let triggerCount = initTriggerCount;
|
||||
if (triggerShortcut.length === 0) {
|
||||
triggerShortcut = DEFAULT_INPUT_SHORTCUT;
|
||||
triggerCount = 1;
|
||||
}
|
||||
|
||||
stepShortcutRegister(
|
||||
triggerShortcut,
|
||||
async () => {
|
||||
let node = document.activeElement;
|
||||
|
||||
if (!node) {
|
||||
return;
|
||||
}
|
||||
|
||||
while (node.shadowRoot) {
|
||||
node = node.shadowRoot.activeElement;
|
||||
}
|
||||
|
||||
if (!isInputNode(node) && !isEditAbleNode(node)) {
|
||||
return;
|
||||
}
|
||||
|
||||
let initText = getNodeText(node);
|
||||
if (triggerShortcut.length === 1 && triggerShortcut[0].length === 1) {
|
||||
// todo: remove multiple char
|
||||
initText = removeEndchar(initText, triggerShortcut[0], triggerCount);
|
||||
}
|
||||
if (!initText.trim()) {
|
||||
return;
|
||||
}
|
||||
|
||||
let text = initText;
|
||||
let toLang = initToLang;
|
||||
if (transSign) {
|
||||
const res = matchInputStr(text, transSign);
|
||||
if (res) {
|
||||
let lang = res[1];
|
||||
if (lang === "zh" || lang === "cn") {
|
||||
lang = "zh-CN";
|
||||
} else if (lang === "tw" || lang === "hk") {
|
||||
lang = "zh-TW";
|
||||
}
|
||||
if (lang && OPT_LANGS_LIST.includes(lang)) {
|
||||
toLang = lang;
|
||||
}
|
||||
text = res[2];
|
||||
}
|
||||
}
|
||||
|
||||
// console.log("input -->", text);
|
||||
|
||||
const loadingId = "kiss-" + genEventName();
|
||||
try {
|
||||
addLoading(node, loadingId);
|
||||
|
||||
const deLang = await tryDetectLang(text, detectRemote);
|
||||
if (deLang && toLang.includes(deLang)) {
|
||||
return;
|
||||
}
|
||||
|
||||
const [trText, isSame] = await apiTranslate({
|
||||
translator,
|
||||
text,
|
||||
fromLang,
|
||||
toLang,
|
||||
apiSetting,
|
||||
});
|
||||
if (!trText || isSame) {
|
||||
return;
|
||||
}
|
||||
|
||||
if (isInputNode(node)) {
|
||||
node.value = trText;
|
||||
node.dispatchEvent(
|
||||
new Event("input", { bubbles: true, cancelable: true })
|
||||
);
|
||||
return;
|
||||
}
|
||||
|
||||
selectContent(node);
|
||||
await sleep(200);
|
||||
|
||||
pasteContentEvent(node, trText);
|
||||
await sleep(200);
|
||||
|
||||
// todo: use includes?
|
||||
if (getNodeText(node).startsWith(initText)) {
|
||||
pasteContentCommand(node, trText);
|
||||
await sleep(100);
|
||||
} else {
|
||||
collapseToEnd(node);
|
||||
}
|
||||
} catch (err) {
|
||||
console.log("[translate input]", err.message);
|
||||
} finally {
|
||||
removeLoading(node, loadingId);
|
||||
}
|
||||
},
|
||||
triggerCount,
|
||||
triggerTime
|
||||
);
|
||||
};
|
||||
|
||||
_handleMouseover = (e) => {
|
||||
// console.log("mouseover", e);
|
||||
// console.log("mouseenter", e);
|
||||
if (!this._tranNodes.has(e.target)) {
|
||||
return;
|
||||
}
|
||||
|
||||
const key = this._setting.mouseKey.slice(3);
|
||||
if (this._setting.mouseKey === OPT_MOUSEKEY_MOUSEOVER || e[key]) {
|
||||
e.target.removeEventListener("mouseover", this._handleMouseover);
|
||||
e.target.removeEventListener("mouseout", this._handleMouseout);
|
||||
e.target.removeEventListener("mouseenter", this._handleMouseover);
|
||||
e.target.removeEventListener("mouseleave", this._handleMouseout);
|
||||
this._render(e.target);
|
||||
} else {
|
||||
this._mouseoverNode = e.target;
|
||||
@@ -491,7 +282,7 @@ export class Translator {
|
||||
};
|
||||
|
||||
_handleMouseout = (e) => {
|
||||
// console.log("mouseout", e);
|
||||
// console.log("mouseleave", e);
|
||||
if (!this._tranNodes.has(e.target)) {
|
||||
return;
|
||||
}
|
||||
@@ -504,10 +295,13 @@ export class Translator {
|
||||
const key = this._setting.mouseKey.slice(3);
|
||||
if (e[key] && this._mouseoverNode) {
|
||||
this._mouseoverNode.removeEventListener(
|
||||
"mouseover",
|
||||
"mouseenter",
|
||||
this._handleMouseover
|
||||
);
|
||||
this._mouseoverNode.removeEventListener("mouseout", this._handleMouseout);
|
||||
this._mouseoverNode.removeEventListener(
|
||||
"mouseleave",
|
||||
this._handleMouseout
|
||||
);
|
||||
|
||||
const node = this._mouseoverNode;
|
||||
this._render(node);
|
||||
@@ -536,8 +330,9 @@ export class Translator {
|
||||
// 移除鼠标悬停监听
|
||||
window.removeEventListener("keydown", this._handleKeydown);
|
||||
this._tranNodes.forEach((_, node) => {
|
||||
node.removeEventListener("mouseover", this._handleMouseover);
|
||||
node.removeEventListener("mouseout", this._handleMouseout);
|
||||
// node.style.pointerEvents = "none";
|
||||
node.removeEventListener("mouseenter", this._handleMouseover);
|
||||
node.removeEventListener("mouseleave", this._handleMouseout);
|
||||
// 移除已插入元素
|
||||
node.querySelector(APP_LCNAME)?.remove();
|
||||
});
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
import { isMatch } from "./utils";
|
||||
import { getWebfix, setWebfix } from "./storage";
|
||||
import { getWebfix, setWebfix, getWebfixRulesWithDefault } from "./storage";
|
||||
import { apiFetch } from "../apis";
|
||||
|
||||
/**
|
||||
@@ -7,7 +7,16 @@ import { apiFetch } from "../apis";
|
||||
*/
|
||||
const FIXER_BR = "br";
|
||||
const FIXER_BN = "bn";
|
||||
const FIXER_BR_DIV = "brToDiv";
|
||||
const FIXER_BN_DIV = "bnToDiv";
|
||||
const FIXER_FONTSIZE = "fontSize";
|
||||
export const FIXER_ALL = [
|
||||
FIXER_BR,
|
||||
FIXER_BN,
|
||||
FIXER_BR_DIV,
|
||||
FIXER_BN_DIV,
|
||||
// FIXER_FONTSIZE,
|
||||
];
|
||||
|
||||
/**
|
||||
* 需要修复的站点列表
|
||||
@@ -54,7 +63,7 @@ const fixedSign = "kissfixed";
|
||||
* @param {*} node
|
||||
* @returns
|
||||
*/
|
||||
function brFixer(node) {
|
||||
function brFixer(node, tag = "p") {
|
||||
if (node.hasAttribute(fixedSign)) {
|
||||
return;
|
||||
}
|
||||
@@ -81,13 +90,13 @@ function brFixer(node) {
|
||||
var html = "";
|
||||
node.childNodes.forEach(function (child, index) {
|
||||
if (index === 0) {
|
||||
html += "<p>";
|
||||
html += `<${tag} class="kiss-p">`;
|
||||
}
|
||||
|
||||
if (gapTags.indexOf(child.nodeName) !== -1) {
|
||||
html += "</p><p>";
|
||||
html += `</${tag}><${tag} class="kiss-p">`;
|
||||
} else if (newlineTags.indexOf(child.nodeName) !== -1) {
|
||||
html += "</p>" + child.outerHTML + "<p>";
|
||||
html += `</${tag}>${child.outerHTML}<${tag} class="kiss-p">`;
|
||||
} else if (child.outerHTML) {
|
||||
html += child.outerHTML;
|
||||
} else if (child.nodeValue) {
|
||||
@@ -95,30 +104,34 @@ function brFixer(node) {
|
||||
}
|
||||
|
||||
if (index === node.childNodes.length - 1) {
|
||||
html += "</p>";
|
||||
html += `</${tag}>`;
|
||||
}
|
||||
});
|
||||
node.innerHTML = html;
|
||||
}
|
||||
|
||||
function brDivFixer(node) {
|
||||
return brFixer(node, "div");
|
||||
}
|
||||
|
||||
/**
|
||||
* 目标是将 `\n` 替换成 `p`
|
||||
* @param {*} node
|
||||
* @returns
|
||||
*/
|
||||
function bnFixer(node) {
|
||||
function bnFixer(node, tag = "p") {
|
||||
if (node.hasAttribute(fixedSign)) {
|
||||
return;
|
||||
}
|
||||
node.setAttribute(fixedSign, "true");
|
||||
node.innerHTML = node.innerHTML
|
||||
.split("\n")
|
||||
.map((item) => `<${tag} class="kiss-p">${item || " "}</${tag}>`)
|
||||
.join("");
|
||||
}
|
||||
|
||||
const childs = node.childNodes;
|
||||
if (childs.length === 1 && childs[0].nodeName === "#text") {
|
||||
node.innerHTML = node.innerHTML
|
||||
.split("\n")
|
||||
.map((item) => `<p>${item || " "}</p>`)
|
||||
.join("");
|
||||
}
|
||||
function bnDivFixer(node) {
|
||||
return bnFixer(node, "div");
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -135,6 +148,8 @@ function fontSizeFixer(node) {
|
||||
const fixerMap = {
|
||||
[FIXER_BR]: brFixer,
|
||||
[FIXER_BN]: bnFixer,
|
||||
[FIXER_BR_DIV]: brDivFixer,
|
||||
[FIXER_BN_DIV]: bnDivFixer,
|
||||
[FIXER_FONTSIZE]: fontSizeFixer,
|
||||
};
|
||||
|
||||
@@ -148,7 +163,11 @@ function run(selector, fixer, rootSelector) {
|
||||
var mutaObserver = new MutationObserver(function (mutations) {
|
||||
mutations.forEach(function (mutation) {
|
||||
mutation.addedNodes.forEach(function (addNode) {
|
||||
addNode.querySelectorAll(selector).forEach(fixer);
|
||||
if (addNode && addNode.querySelectorAll) {
|
||||
addNode.querySelectorAll(selector).forEach(function (node) {
|
||||
fixer(node);
|
||||
});
|
||||
}
|
||||
});
|
||||
});
|
||||
});
|
||||
@@ -159,7 +178,9 @@ function run(selector, fixer, rootSelector) {
|
||||
}
|
||||
|
||||
rootNodes.forEach(function (rootNode) {
|
||||
rootNode.querySelectorAll(selector).forEach(fixer);
|
||||
rootNode.querySelectorAll(selector).forEach(function (node) {
|
||||
fixer(node);
|
||||
});
|
||||
mutaObserver.observe(rootNode, {
|
||||
childList: true,
|
||||
subtree: true,
|
||||
@@ -206,7 +227,9 @@ export async function runWebfix({ injectWebfix }) {
|
||||
}
|
||||
|
||||
const href = document.location.href;
|
||||
const sites = await loadOrFetchWebfix(process.env.REACT_APP_WEBFIXURL);
|
||||
const userSites = await getWebfixRulesWithDefault();
|
||||
const subSites = await loadOrFetchWebfix(process.env.REACT_APP_WEBFIXURL);
|
||||
const sites = [...userSites, ...subSites];
|
||||
for (var i = 0; i < sites.length; i++) {
|
||||
var site = sites[i];
|
||||
if (isMatch(href, site.pattern)) {
|
||||
|
||||
@@ -1,77 +1,3 @@
|
||||
import { getSettingWithDefault } from "./libs/storage";
|
||||
import { trySyncAllSubRules } from "./libs/subRules";
|
||||
import { isIframe } from "./libs/iframe";
|
||||
import { handlePing, injectScript } from "./libs/gm";
|
||||
import { genEventName } from "./libs/utils";
|
||||
import { runWebfix } from "./libs/webfix";
|
||||
import {
|
||||
runIframe,
|
||||
runTranslator,
|
||||
showFab,
|
||||
showTransbox,
|
||||
windowListener,
|
||||
showErr,
|
||||
} from "./common";
|
||||
import { run } from "./common";
|
||||
|
||||
function runSettingPage() {
|
||||
if (GM?.info?.script?.grant?.includes("unsafeWindow")) {
|
||||
unsafeWindow.GM = GM;
|
||||
unsafeWindow.APP_INFO = {
|
||||
name: process.env.REACT_APP_NAME,
|
||||
version: process.env.REACT_APP_VERSION,
|
||||
};
|
||||
} else {
|
||||
const ping = genEventName();
|
||||
window.addEventListener(ping, handlePing);
|
||||
// window.eval(`(${injectScript})("${ping}")`); // eslint-disable-line
|
||||
const script = document.createElement("script");
|
||||
script.textContent = `(${injectScript})("${ping}")`;
|
||||
document.head.append(script);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 入口函数
|
||||
*/
|
||||
(async () => {
|
||||
try {
|
||||
// 设置页面
|
||||
if (
|
||||
document.location.href.includes(process.env.REACT_APP_OPTIONSPAGE_DEV) ||
|
||||
document.location.href.includes(process.env.REACT_APP_OPTIONSPAGE) ||
|
||||
document.location.href.includes(process.env.REACT_APP_OPTIONSPAGE2)
|
||||
) {
|
||||
runSettingPage();
|
||||
return;
|
||||
}
|
||||
|
||||
// 读取设置信息
|
||||
const setting = await getSettingWithDefault();
|
||||
|
||||
// 适配iframe
|
||||
if (isIframe) {
|
||||
runIframe(setting);
|
||||
return;
|
||||
}
|
||||
|
||||
// 不规范网页修复
|
||||
await runWebfix(setting);
|
||||
|
||||
// 翻译网页
|
||||
const { translator, rule } = await runTranslator(setting);
|
||||
|
||||
// 监听消息
|
||||
windowListener(rule);
|
||||
|
||||
// 划词翻译
|
||||
showTransbox(setting);
|
||||
|
||||
// 浮球按钮
|
||||
await showFab(translator);
|
||||
|
||||
// 同步订阅规则
|
||||
await trySyncAllSubRules(setting);
|
||||
} catch (err) {
|
||||
showErr(err);
|
||||
}
|
||||
})();
|
||||
run(true);
|
||||
|
||||
@@ -95,40 +95,42 @@ export default function Action({ translator, fab }) {
|
||||
// 注册菜单
|
||||
try {
|
||||
const menuCommandIds = [];
|
||||
menuCommandIds.push(
|
||||
GM.registerMenuCommand(
|
||||
"Toggle Translate (Alt+q)",
|
||||
(event) => {
|
||||
translator.toggle();
|
||||
sendIframeMsg(MSG_TRANS_TOGGLE);
|
||||
setShowPopup(false);
|
||||
},
|
||||
"Q"
|
||||
),
|
||||
GM.registerMenuCommand(
|
||||
"Toggle Style (Alt+c)",
|
||||
(event) => {
|
||||
translator.toggleStyle();
|
||||
sendIframeMsg(MSG_TRANS_TOGGLE_STYLE);
|
||||
setShowPopup(false);
|
||||
},
|
||||
"C"
|
||||
),
|
||||
GM.registerMenuCommand(
|
||||
"Open Menu (Alt+k)",
|
||||
(event) => {
|
||||
setShowPopup((pre) => !pre);
|
||||
},
|
||||
"K"
|
||||
),
|
||||
GM.registerMenuCommand(
|
||||
"Open Setting (Alt+o)",
|
||||
(event) => {
|
||||
window.open(process.env.REACT_APP_OPTIONSPAGE, "_blank");
|
||||
},
|
||||
"O"
|
||||
)
|
||||
);
|
||||
const { contextMenus = true } = translator.setting;
|
||||
contextMenus &&
|
||||
menuCommandIds.push(
|
||||
GM.registerMenuCommand(
|
||||
"Toggle Translate (Alt+q)",
|
||||
(event) => {
|
||||
translator.toggle();
|
||||
sendIframeMsg(MSG_TRANS_TOGGLE);
|
||||
setShowPopup(false);
|
||||
},
|
||||
"Q"
|
||||
),
|
||||
GM.registerMenuCommand(
|
||||
"Toggle Style (Alt+c)",
|
||||
(event) => {
|
||||
translator.toggleStyle();
|
||||
sendIframeMsg(MSG_TRANS_TOGGLE_STYLE);
|
||||
setShowPopup(false);
|
||||
},
|
||||
"C"
|
||||
),
|
||||
GM.registerMenuCommand(
|
||||
"Open Menu (Alt+k)",
|
||||
(event) => {
|
||||
setShowPopup((pre) => !pre);
|
||||
},
|
||||
"K"
|
||||
),
|
||||
GM.registerMenuCommand(
|
||||
"Open Setting (Alt+o)",
|
||||
(event) => {
|
||||
window.open(process.env.REACT_APP_OPTIONSPAGE, "_blank");
|
||||
},
|
||||
"O"
|
||||
)
|
||||
);
|
||||
|
||||
return () => {
|
||||
menuCommandIds.forEach((id) => {
|
||||
@@ -215,7 +217,12 @@ export default function Action({ translator, fab }) {
|
||||
}
|
||||
}}
|
||||
>
|
||||
<TranslateIcon />
|
||||
<TranslateIcon
|
||||
sx={{
|
||||
width: 24,
|
||||
height: 24,
|
||||
}}
|
||||
/>
|
||||
</Fab>
|
||||
}
|
||||
/>
|
||||
|
||||
@@ -7,6 +7,7 @@ import {
|
||||
OPT_STYLE_WAVYLINE,
|
||||
OPT_STYLE_FUZZY,
|
||||
OPT_STYLE_HIGHLIGHT,
|
||||
OPT_STYLE_BLOCKQUOTE,
|
||||
OPT_STYLE_DIY,
|
||||
DEFAULT_COLOR,
|
||||
MSG_TRANS_CURRULE,
|
||||
@@ -34,6 +35,18 @@ const LineSpan = styled("span")`
|
||||
}
|
||||
`;
|
||||
|
||||
const BlockquoteSpan = styled("span")`
|
||||
opacity: 0.6;
|
||||
-webkit-opacity: 0.6;
|
||||
display: block;
|
||||
padding: 0 0.75em;
|
||||
border-left: 0.25em solid ${(props) => props.$lineColor};
|
||||
&:hover {
|
||||
opacity: 1;
|
||||
-webkit-opacity: 1;
|
||||
}
|
||||
`;
|
||||
|
||||
const FuzzySpan = styled("span")`
|
||||
filter: blur(0.2em);
|
||||
-webkit-filter: blur(0.2em);
|
||||
@@ -86,6 +99,12 @@ function StyledSpan({ textStyle, textDiyStyle, bgColor, children }) {
|
||||
{children}
|
||||
</HighlightSpan>
|
||||
);
|
||||
case OPT_STYLE_BLOCKQUOTE: // 引用
|
||||
return (
|
||||
<BlockquoteSpan $lineColor={bgColor || DEFAULT_COLOR}>
|
||||
{children}
|
||||
</BlockquoteSpan>
|
||||
);
|
||||
case OPT_STYLE_DIY: // 自定义
|
||||
return <DiySpan $diyStyle={textDiyStyle}>{children}</DiySpan>;
|
||||
default:
|
||||
|
||||
@@ -9,6 +9,7 @@ import {
|
||||
OPT_TRANS_BAIDU,
|
||||
OPT_TRANS_TENCENT,
|
||||
OPT_TRANS_OPENAI,
|
||||
OPT_TRANS_GEMINI,
|
||||
OPT_TRANS_CUSTOMIZE,
|
||||
URL_KISS_PROXY,
|
||||
} from "../../config";
|
||||
@@ -46,7 +47,20 @@ function TestButton({ translator, api }) {
|
||||
}
|
||||
alert.success(i18n("test_success"));
|
||||
} catch (err) {
|
||||
alert.error(`${i18n("test_failed")}: ${err.message}`);
|
||||
// alert.error(`${i18n("test_failed")}: ${err.message}`);
|
||||
alert.error(
|
||||
<>
|
||||
<div>{`${i18n("test_failed")}: ${err.message}`}</div>
|
||||
<pre
|
||||
style={{
|
||||
maxWidth: 400,
|
||||
overflow: "auto",
|
||||
}}
|
||||
>
|
||||
{JSON.stringify(err.cause || {}, null, 2)}
|
||||
</pre>
|
||||
</>
|
||||
);
|
||||
} finally {
|
||||
setLoading(false);
|
||||
}
|
||||
@@ -102,7 +116,7 @@ function ApiFields({ translator }) {
|
||||
/>
|
||||
</>
|
||||
)}
|
||||
{translator === OPT_TRANS_OPENAI && (
|
||||
{(translator === OPT_TRANS_OPENAI || translator === OPT_TRANS_GEMINI) && (
|
||||
<>
|
||||
<TextField
|
||||
size="small"
|
||||
|
||||
@@ -6,6 +6,7 @@ import Box from "@mui/material/Box";
|
||||
import Link from "@mui/material/Link";
|
||||
import { useI18n } from "../../hooks/I18n";
|
||||
import DarkModeButton from "./DarkModeButton";
|
||||
import Typography from "@mui/material/Typography";
|
||||
|
||||
function Header(props) {
|
||||
const i18n = useI18n();
|
||||
@@ -30,14 +31,14 @@ function Header(props) {
|
||||
<MenuIcon />
|
||||
</IconButton>
|
||||
</Box>
|
||||
<Box sx={{ flexGrow: 1 }}>
|
||||
<Typography component="div" sx={{ flexGrow: 1, fontWeight: "bold" }}>
|
||||
<Link
|
||||
underline="none"
|
||||
color="inherit"
|
||||
href={process.env.REACT_APP_HOMEPAGE}
|
||||
target="_blank"
|
||||
>{`${i18n("app_name")} v${process.env.REACT_APP_VERSION}`}</Link>
|
||||
</Box>
|
||||
</Typography>
|
||||
<DarkModeButton />
|
||||
</Toolbar>
|
||||
</AppBar>
|
||||
|
||||
@@ -13,8 +13,8 @@ import SyncIcon from "@mui/icons-material/Sync";
|
||||
import ApiIcon from "@mui/icons-material/Api";
|
||||
import SendTimeExtensionIcon from "@mui/icons-material/SendTimeExtension";
|
||||
import InputIcon from "@mui/icons-material/Input";
|
||||
import SelectAllIcon from '@mui/icons-material/SelectAll';
|
||||
import EventNoteIcon from '@mui/icons-material/EventNote';
|
||||
import SelectAllIcon from "@mui/icons-material/SelectAll";
|
||||
import EventNoteIcon from "@mui/icons-material/EventNote";
|
||||
|
||||
function LinkItem({ label, url, icon }) {
|
||||
const match = useMatch(url);
|
||||
|
||||
@@ -23,10 +23,14 @@ import {
|
||||
OPT_SHORTCUT_STYLE,
|
||||
OPT_SHORTCUT_POPUP,
|
||||
OPT_SHORTCUT_SETTING,
|
||||
OPT_LANGS_TO,
|
||||
DEFAULT_BLACKLIST,
|
||||
MSG_CONTEXT_MENUS,
|
||||
} from "../../config";
|
||||
import { useShortcut } from "../../hooks/Shortcut";
|
||||
import ShortcutInput from "./ShortcutInput";
|
||||
import { useFab } from "../../hooks/Fab";
|
||||
import { sendBgMsg } from "../../libs/msg";
|
||||
|
||||
function ShortcutItem({ action, label }) {
|
||||
const { shortcut, setShortcut } = useShortcut(action);
|
||||
@@ -60,6 +64,12 @@ export default function Settings() {
|
||||
case "newlineLength":
|
||||
value = limitNumber(value, 1, 1000);
|
||||
break;
|
||||
case "touchTranslate":
|
||||
value = limitNumber(value, 0, 4);
|
||||
break;
|
||||
case "contextMenus":
|
||||
isExt && sendBgMsg(MSG_CONTEXT_MENUS, { contextMenus: value });
|
||||
break;
|
||||
default:
|
||||
}
|
||||
updateSetting({
|
||||
@@ -86,6 +96,10 @@ export default function Settings() {
|
||||
newlineLength = TRANS_NEWLINE_LENGTH,
|
||||
mouseKey = OPT_MOUSEKEY_DISABLE,
|
||||
detectRemote = false,
|
||||
contextMenus = true,
|
||||
touchTranslate = 2,
|
||||
blacklist = DEFAULT_BLACKLIST.join(",\n"),
|
||||
disableLangs = [],
|
||||
} = setting;
|
||||
const { isHide = false } = fab || {};
|
||||
|
||||
@@ -169,6 +183,22 @@ export default function Settings() {
|
||||
</Select>
|
||||
</FormControl>
|
||||
|
||||
<FormControl size="small">
|
||||
<InputLabel>{i18n("touch_translate_shortcut")}</InputLabel>
|
||||
<Select
|
||||
name="touchTranslate"
|
||||
value={touchTranslate}
|
||||
label={i18n("touch_translate_shortcut")}
|
||||
onChange={handleChange}
|
||||
>
|
||||
{[0, 2, 3, 4].map((item) => (
|
||||
<MenuItem key={item} value={item}>
|
||||
{i18n(`touch_tap_${item}`)}
|
||||
</MenuItem>
|
||||
))}
|
||||
</Select>
|
||||
</FormControl>
|
||||
|
||||
<FormControl size="small">
|
||||
<InputLabel>{i18n("hide_fab_button")}</InputLabel>
|
||||
<Select
|
||||
@@ -184,6 +214,19 @@ export default function Settings() {
|
||||
</Select>
|
||||
</FormControl>
|
||||
|
||||
<FormControl size="small">
|
||||
<InputLabel>{i18n("add_context_menus")}</InputLabel>
|
||||
<Select
|
||||
name="contextMenus"
|
||||
value={contextMenus}
|
||||
label={i18n("add_context_menus")}
|
||||
onChange={handleChange}
|
||||
>
|
||||
<MenuItem value={false}>{i18n("disable")}</MenuItem>
|
||||
<MenuItem value={true}>{i18n("enable")}</MenuItem>
|
||||
</Select>
|
||||
</FormControl>
|
||||
|
||||
<FormControl size="small">
|
||||
<InputLabel>{i18n("detect_lang_remote")}</InputLabel>
|
||||
<Select
|
||||
@@ -198,24 +241,44 @@ export default function Settings() {
|
||||
<FormHelperText>{i18n("detect_lang_remote_help")}</FormHelperText>
|
||||
</FormControl>
|
||||
|
||||
<FormControl size="small">
|
||||
<InputLabel>{i18n("disable_langs")}</InputLabel>
|
||||
<Select
|
||||
multiple
|
||||
name="disableLangs"
|
||||
value={disableLangs}
|
||||
label={i18n("disable_langs")}
|
||||
onChange={handleChange}
|
||||
>
|
||||
{OPT_LANGS_TO.map(([langKey, langName]) => (
|
||||
<MenuItem key={langKey} value={langKey}>
|
||||
{langName}
|
||||
</MenuItem>
|
||||
))}
|
||||
</Select>
|
||||
<FormHelperText>{i18n("disable_langs_helper")}</FormHelperText>
|
||||
</FormControl>
|
||||
|
||||
{isExt ? (
|
||||
<FormControl size="small">
|
||||
<InputLabel>{i18n("if_clear_cache")}</InputLabel>
|
||||
<Select
|
||||
name="clearCache"
|
||||
value={clearCache}
|
||||
label={i18n("if_clear_cache")}
|
||||
onChange={handleChange}
|
||||
>
|
||||
<MenuItem value={false}>{i18n("clear_cache_never")}</MenuItem>
|
||||
<MenuItem value={true}>{i18n("clear_cache_restart")}</MenuItem>
|
||||
</Select>
|
||||
<FormHelperText>
|
||||
<Link component="button" onClick={handleClearCache}>
|
||||
{i18n("clear_all_cache_now")}
|
||||
</Link>
|
||||
</FormHelperText>
|
||||
</FormControl>
|
||||
<>
|
||||
<FormControl size="small">
|
||||
<InputLabel>{i18n("if_clear_cache")}</InputLabel>
|
||||
<Select
|
||||
name="clearCache"
|
||||
value={clearCache}
|
||||
label={i18n("if_clear_cache")}
|
||||
onChange={handleChange}
|
||||
>
|
||||
<MenuItem value={false}>{i18n("clear_cache_never")}</MenuItem>
|
||||
<MenuItem value={true}>{i18n("clear_cache_restart")}</MenuItem>
|
||||
</Select>
|
||||
<FormHelperText>
|
||||
<Link component="button" onClick={handleClearCache}>
|
||||
{i18n("clear_all_cache_now")}
|
||||
</Link>
|
||||
</FormHelperText>
|
||||
</FormControl>
|
||||
</>
|
||||
) : (
|
||||
<>
|
||||
<Box>
|
||||
@@ -248,6 +311,16 @@ export default function Settings() {
|
||||
</Box>
|
||||
</>
|
||||
)}
|
||||
|
||||
<TextField
|
||||
size="small"
|
||||
label={i18n("translate_blacklist")}
|
||||
helperText={i18n("pattern_helper")}
|
||||
name="blacklist"
|
||||
defaultValue={blacklist}
|
||||
onChange={handleChange}
|
||||
multiline
|
||||
/>
|
||||
</Stack>
|
||||
</Box>
|
||||
);
|
||||
|
||||
@@ -44,9 +44,11 @@ export default function Tranbox() {
|
||||
translator,
|
||||
fromLang,
|
||||
toLang,
|
||||
toLang2 = "en",
|
||||
tranboxShortcut,
|
||||
btnOffsetX,
|
||||
btnOffsetY,
|
||||
hideTranBtn = false,
|
||||
} = tranboxSetting;
|
||||
|
||||
return (
|
||||
@@ -111,6 +113,22 @@ export default function Tranbox() {
|
||||
))}
|
||||
</TextField>
|
||||
|
||||
<TextField
|
||||
select
|
||||
size="small"
|
||||
name="toLang2"
|
||||
value={toLang2}
|
||||
label={i18n("to_lang2")}
|
||||
helperText={i18n("to_lang2_helper")}
|
||||
onChange={handleChange}
|
||||
>
|
||||
{[["none", "None"], ...OPT_LANGS_TO].map(([lang, name]) => (
|
||||
<MenuItem key={lang} value={lang}>
|
||||
{name}
|
||||
</MenuItem>
|
||||
))}
|
||||
</TextField>
|
||||
|
||||
<TextField
|
||||
size="small"
|
||||
label={i18n("tranbtn_offset_x")}
|
||||
@@ -129,6 +147,18 @@ export default function Tranbox() {
|
||||
onChange={handleChange}
|
||||
/>
|
||||
|
||||
<TextField
|
||||
select
|
||||
size="small"
|
||||
name="hideTranBtn"
|
||||
value={hideTranBtn}
|
||||
label={i18n("hide_tran_button")}
|
||||
onChange={handleChange}
|
||||
>
|
||||
<MenuItem value={false}>{i18n("show")}</MenuItem>
|
||||
<MenuItem value={true}>{i18n("hide")}</MenuItem>
|
||||
</TextField>
|
||||
|
||||
<ShortcutInput
|
||||
value={tranboxShortcut}
|
||||
onChange={handleShortcutInput}
|
||||
|
||||
@@ -13,43 +13,204 @@ import FormControlLabel from "@mui/material/FormControlLabel";
|
||||
import Switch from "@mui/material/Switch";
|
||||
import { useSetting } from "../../hooks/Setting";
|
||||
import CircularProgress from "@mui/material/CircularProgress";
|
||||
import { syncWebfix, loadOrFetchWebfix } from "../../libs/webfix";
|
||||
import { syncWebfix, loadOrFetchWebfix, FIXER_ALL } from "../../libs/webfix";
|
||||
import Button from "@mui/material/Button";
|
||||
import SyncIcon from "@mui/icons-material/Sync";
|
||||
import { useAlert } from "../../hooks/Alert";
|
||||
import HelpButton from "./HelpButton";
|
||||
import { URL_KISS_RULES_NEW_ISSUE } from "../../config";
|
||||
import MenuItem from "@mui/material/MenuItem";
|
||||
import { useWebfixRules } from "../../hooks/WebfixRules";
|
||||
|
||||
function WebfixFields({ rule, webfix, setShow }) {
|
||||
const editMode = !!rule;
|
||||
const initFormValues = rule || {
|
||||
pattern: "",
|
||||
selector: "",
|
||||
rootSelector: "",
|
||||
fixer: FIXER_ALL[0],
|
||||
};
|
||||
const i18n = useI18n();
|
||||
const [disabled, setDisabled] = useState(editMode);
|
||||
const [errors, setErrors] = useState({});
|
||||
const [formValues, setFormValues] = useState(initFormValues);
|
||||
|
||||
const { pattern, selector, rootSelector, fixer } = formValues;
|
||||
|
||||
const hasSamePattern = (str) => {
|
||||
for (const item of webfix.list || []) {
|
||||
if (item.pattern === str && rule?.pattern !== str) {
|
||||
return true;
|
||||
}
|
||||
}
|
||||
return false;
|
||||
};
|
||||
|
||||
const handleFocus = (e) => {
|
||||
e.preventDefault();
|
||||
const { name } = e.target;
|
||||
setErrors((pre) => ({ ...pre, [name]: "" }));
|
||||
};
|
||||
|
||||
const handleChange = (e) => {
|
||||
e.preventDefault();
|
||||
const { name, value } = e.target;
|
||||
setFormValues((pre) => ({ ...pre, [name]: value }));
|
||||
};
|
||||
|
||||
const handleCancel = (e) => {
|
||||
e.preventDefault();
|
||||
if (editMode) {
|
||||
setDisabled(true);
|
||||
} else {
|
||||
setShow(false);
|
||||
}
|
||||
setFormValues(initFormValues);
|
||||
};
|
||||
|
||||
const handleSubmit = (e) => {
|
||||
e.preventDefault();
|
||||
const errors = {};
|
||||
if (!pattern.trim()) {
|
||||
errors.pattern = i18n("error_cant_be_blank");
|
||||
}
|
||||
if (hasSamePattern(pattern)) {
|
||||
errors.pattern = i18n("error_duplicate_values");
|
||||
}
|
||||
if (!selector.trim()) {
|
||||
errors.selector = i18n("error_cant_be_blank");
|
||||
}
|
||||
if (Object.keys(errors).length > 0) {
|
||||
setErrors(errors);
|
||||
return;
|
||||
}
|
||||
|
||||
if (editMode) {
|
||||
// 编辑
|
||||
setDisabled(true);
|
||||
webfix.put(rule.pattern, formValues);
|
||||
} else {
|
||||
// 添加
|
||||
webfix.add(formValues);
|
||||
setShow(false);
|
||||
setFormValues(initFormValues);
|
||||
}
|
||||
};
|
||||
|
||||
function ApiFields({ site }) {
|
||||
const { selector, rootSelector, fixer } = site;
|
||||
return (
|
||||
<Stack spacing={3}>
|
||||
<TextField
|
||||
size="small"
|
||||
label={"rootSelector"}
|
||||
name="rootSelector"
|
||||
value={rootSelector || "document"}
|
||||
disabled
|
||||
/>
|
||||
<TextField
|
||||
size="small"
|
||||
label={"selector"}
|
||||
name="selector"
|
||||
value={selector}
|
||||
disabled
|
||||
/>
|
||||
<TextField
|
||||
size="small"
|
||||
label={"fixer"}
|
||||
name="fixer"
|
||||
value={fixer}
|
||||
disabled
|
||||
/>
|
||||
</Stack>
|
||||
<form onSubmit={handleSubmit}>
|
||||
<Stack spacing={3}>
|
||||
<TextField
|
||||
size="small"
|
||||
label={i18n("pattern")}
|
||||
error={!!errors.pattern}
|
||||
helperText={errors.pattern}
|
||||
name="pattern"
|
||||
value={pattern}
|
||||
disabled={disabled}
|
||||
onChange={handleChange}
|
||||
onFocus={handleFocus}
|
||||
multiline
|
||||
/>
|
||||
<TextField
|
||||
size="small"
|
||||
label={i18n("root_selector")}
|
||||
error={!!errors.rootSelector}
|
||||
helperText={errors.rootSelector}
|
||||
name="rootSelector"
|
||||
value={rootSelector}
|
||||
disabled={disabled}
|
||||
onChange={handleChange}
|
||||
onFocus={handleFocus}
|
||||
multiline
|
||||
/>
|
||||
<TextField
|
||||
size="small"
|
||||
label={i18n("selector")}
|
||||
error={!!errors.selector}
|
||||
helperText={errors.selector}
|
||||
name="selector"
|
||||
value={selector}
|
||||
disabled={disabled}
|
||||
onChange={handleChange}
|
||||
onFocus={handleFocus}
|
||||
multiline
|
||||
/>
|
||||
<TextField
|
||||
select
|
||||
size="small"
|
||||
name="fixer"
|
||||
value={fixer}
|
||||
label={i18n("fixer_function")}
|
||||
disabled={disabled}
|
||||
onChange={handleChange}
|
||||
>
|
||||
{FIXER_ALL.map((item) => (
|
||||
<MenuItem key={item} value={item}>
|
||||
{item}
|
||||
</MenuItem>
|
||||
))}
|
||||
</TextField>
|
||||
|
||||
{webfix &&
|
||||
(editMode ? (
|
||||
// 编辑
|
||||
<Stack direction="row" spacing={2}>
|
||||
{disabled ? (
|
||||
<>
|
||||
<Button
|
||||
size="small"
|
||||
variant="contained"
|
||||
onClick={(e) => {
|
||||
e.preventDefault();
|
||||
setDisabled(false);
|
||||
}}
|
||||
>
|
||||
{i18n("edit")}
|
||||
</Button>
|
||||
<Button
|
||||
size="small"
|
||||
variant="outlined"
|
||||
onClick={(e) => {
|
||||
e.preventDefault();
|
||||
webfix.del(rule.pattern);
|
||||
}}
|
||||
>
|
||||
{i18n("delete")}
|
||||
</Button>
|
||||
</>
|
||||
) : (
|
||||
<>
|
||||
<Button size="small" variant="contained" type="submit">
|
||||
{i18n("save")}
|
||||
</Button>
|
||||
<Button
|
||||
size="small"
|
||||
variant="outlined"
|
||||
onClick={handleCancel}
|
||||
>
|
||||
{i18n("cancel")}
|
||||
</Button>
|
||||
</>
|
||||
)}
|
||||
</Stack>
|
||||
) : (
|
||||
// 添加
|
||||
<Stack direction="row" spacing={2}>
|
||||
<Button size="small" variant="contained" type="submit">
|
||||
{i18n("save")}
|
||||
</Button>
|
||||
<Button size="small" variant="outlined" onClick={handleCancel}>
|
||||
{i18n("cancel")}
|
||||
</Button>
|
||||
</Stack>
|
||||
))}
|
||||
</Stack>
|
||||
</form>
|
||||
);
|
||||
}
|
||||
|
||||
function ApiAccordion({ site }) {
|
||||
function WebfixAccordion({ rule, webfix }) {
|
||||
const [expanded, setExpanded] = useState(false);
|
||||
|
||||
const handleChange = (e) => {
|
||||
@@ -59,10 +220,17 @@ function ApiAccordion({ site }) {
|
||||
return (
|
||||
<Accordion expanded={expanded} onChange={handleChange}>
|
||||
<AccordionSummary expandIcon={<ExpandMoreIcon />}>
|
||||
<Typography>{site.pattern}</Typography>
|
||||
<Typography
|
||||
sx={{
|
||||
opacity: webfix ? 1 : 0.5,
|
||||
overflowWrap: "anywhere",
|
||||
}}
|
||||
>
|
||||
{rule.pattern}
|
||||
</Typography>
|
||||
</AccordionSummary>
|
||||
<AccordionDetails>
|
||||
{expanded && <ApiFields site={site} />}
|
||||
{expanded && <WebfixFields rule={rule} webfix={webfix} />}
|
||||
</AccordionDetails>
|
||||
</Accordion>
|
||||
);
|
||||
@@ -74,6 +242,8 @@ export default function Webfix() {
|
||||
const i18n = useI18n();
|
||||
const alert = useAlert();
|
||||
const { setting, updateSetting } = useSetting();
|
||||
const [showAdd, setShowAdd] = useState(false);
|
||||
const webfix = useWebfixRules();
|
||||
|
||||
const loadSites = useCallback(async () => {
|
||||
const sites = await loadOrFetchWebfix(process.env.REACT_APP_WEBFIXURL);
|
||||
@@ -120,6 +290,18 @@ export default function Webfix() {
|
||||
useFlexGap
|
||||
flexWrap="wrap"
|
||||
>
|
||||
<Button
|
||||
size="small"
|
||||
variant="contained"
|
||||
disabled={showAdd}
|
||||
onClick={(e) => {
|
||||
e.preventDefault();
|
||||
setShowAdd(true);
|
||||
}}
|
||||
>
|
||||
{i18n("add")}
|
||||
</Button>
|
||||
|
||||
<Button
|
||||
size="small"
|
||||
variant="outlined"
|
||||
@@ -146,6 +328,16 @@ export default function Webfix() {
|
||||
/>
|
||||
</Stack>
|
||||
|
||||
{showAdd && <WebfixFields webfix={webfix} setShow={setShowAdd} />}
|
||||
|
||||
{webfix.list?.length > 0 && (
|
||||
<Box>
|
||||
{webfix.list.map((rule) => (
|
||||
<WebfixAccordion key={rule.pattern} rule={rule} webfix={webfix} />
|
||||
))}
|
||||
</Box>
|
||||
)}
|
||||
|
||||
{setting.injectWebfix && (
|
||||
<Box>
|
||||
{loading ? (
|
||||
@@ -153,8 +345,8 @@ export default function Webfix() {
|
||||
<CircularProgress size={16} />
|
||||
</center>
|
||||
) : (
|
||||
sites.map((site) => (
|
||||
<ApiAccordion key={site.pattern} site={site} />
|
||||
sites.map((rule) => (
|
||||
<WebfixAccordion key={rule.pattern} rule={rule} />
|
||||
))
|
||||
)}
|
||||
</Box>
|
||||
|
||||
@@ -1,9 +1,9 @@
|
||||
import Box from "@mui/material/Box";
|
||||
import IconButton from "@mui/material/IconButton";
|
||||
import CloseIcon from "@mui/icons-material/Close";
|
||||
import HomeIcon from "@mui/icons-material/Home";
|
||||
import Stack from "@mui/material/Stack";
|
||||
import DarkModeButton from "../Options/DarkModeButton";
|
||||
import Typography from "@mui/material/Typography";
|
||||
|
||||
export default function Header({ setShowPopup }) {
|
||||
const handleHomepage = () => {
|
||||
@@ -21,14 +21,16 @@ export default function Header({ setShowPopup }) {
|
||||
<IconButton onClick={handleHomepage}>
|
||||
<HomeIcon />
|
||||
</IconButton>
|
||||
<Box
|
||||
<Typography
|
||||
component="div"
|
||||
sx={{
|
||||
userSelect: "none",
|
||||
WebkitUserSelect: "none",
|
||||
fontWeight: "bold",
|
||||
}}
|
||||
>
|
||||
{`${process.env.REACT_APP_NAME} v${process.env.REACT_APP_VERSION}`}
|
||||
</Box>
|
||||
</Typography>
|
||||
</Stack>
|
||||
|
||||
{setShowPopup ? (
|
||||
|
||||
@@ -5,9 +5,9 @@ import { useState } from "react";
|
||||
|
||||
export default function CopyBtn({ text }) {
|
||||
const [copied, setCopied] = useState(false);
|
||||
const handleClick = (e) => {
|
||||
const handleClick = async (e) => {
|
||||
e.stopPropagation();
|
||||
navigator.clipboard.writeText(text);
|
||||
await navigator.clipboard.writeText(text);
|
||||
setCopied(true);
|
||||
const timer = setTimeout(() => {
|
||||
clearTimeout(timer);
|
||||
|
||||
@@ -2,6 +2,7 @@ import Box from "@mui/material/Box";
|
||||
import Chip from "@mui/material/Chip";
|
||||
import Stack from "@mui/material/Stack";
|
||||
import FavBtn from "./FavBtn";
|
||||
import Typography from "@mui/material/Typography";
|
||||
|
||||
const exchangeMap = {
|
||||
word_third: "第三人称单数",
|
||||
@@ -9,7 +10,7 @@ const exchangeMap = {
|
||||
word_done: "过去式",
|
||||
word_past: "过去分词",
|
||||
word_pl: "复数",
|
||||
word_proto: "原词",
|
||||
word_proto: "词源",
|
||||
};
|
||||
|
||||
export default function DictCont({ dictResult }) {
|
||||
@@ -24,15 +25,17 @@ export default function DictCont({ dictResult }) {
|
||||
justifyContent="space-between"
|
||||
alignItems="flex-start"
|
||||
>
|
||||
<div style={{ fontWeight: "bold" }}>
|
||||
<Typography variant="subtitle1" style={{ fontWeight: "bold" }}>
|
||||
{dictResult.simple_means?.word_name}
|
||||
</div>
|
||||
</Typography>
|
||||
<FavBtn word={dictResult.simple_means?.word_name} />
|
||||
</Stack>
|
||||
|
||||
{dictResult.simple_means?.symbols?.map(({ ph_en, ph_am, parts }, idx) => (
|
||||
<div key={idx}>
|
||||
<div>{`英[${ph_en}] 美[${ph_am}]`}</div>
|
||||
<Typography key={idx} component="div">
|
||||
{(ph_en || ph_am) && (
|
||||
<Typography>{`英 /${ph_en || ""}/ 美 /${ph_am || ""}/`}</Typography>
|
||||
)}
|
||||
<ul style={{ margin: "0.5em 0" }}>
|
||||
{parts.map(({ part, means }, idx) => (
|
||||
<li key={idx}>
|
||||
@@ -40,16 +43,16 @@ export default function DictCont({ dictResult }) {
|
||||
</li>
|
||||
))}
|
||||
</ul>
|
||||
</div>
|
||||
</Typography>
|
||||
))}
|
||||
|
||||
<div>
|
||||
<Typography>
|
||||
{Object.entries(dictResult.simple_means?.exchange || {})
|
||||
.map(([key, val]) => `${exchangeMap[key] || key}: ${val.join(", ")}`)
|
||||
.join("; ")}
|
||||
</div>
|
||||
</Typography>
|
||||
|
||||
<Stack direction="row" spacing={1}>
|
||||
<Stack direction="row" spacing={1} flexWrap="wrap" useFlexGap>
|
||||
{Object.values(dictResult.simple_means?.tags || {})
|
||||
.flat()
|
||||
.filter((item) => item)
|
||||
|
||||
@@ -24,6 +24,7 @@ function TranForm({ text, setText, tranboxSetting, transApis }) {
|
||||
const [translator, setTranslator] = useState(tranboxSetting.translator);
|
||||
const [fromLang, setFromLang] = useState(tranboxSetting.fromLang);
|
||||
const [toLang, setToLang] = useState(tranboxSetting.toLang);
|
||||
const [toLang2, setToLang2] = useState(tranboxSetting.toLang2);
|
||||
const inputRef = useRef(null);
|
||||
|
||||
return (
|
||||
@@ -95,6 +96,7 @@ function TranForm({ text, setText, tranboxSetting, transApis }) {
|
||||
|
||||
<Box>
|
||||
<TextField
|
||||
size="small"
|
||||
label={i18n("original_text")}
|
||||
inputRef={inputRef}
|
||||
fullWidth
|
||||
@@ -149,6 +151,9 @@ function TranForm({ text, setText, tranboxSetting, transApis }) {
|
||||
translator={translator}
|
||||
fromLang={fromLang}
|
||||
toLang={toLang}
|
||||
toLang2={toLang2}
|
||||
setToLang={setToLang}
|
||||
setToLang2={setToLang2}
|
||||
transApis={transApis}
|
||||
/>
|
||||
</Stack>
|
||||
|
||||
@@ -3,7 +3,7 @@ export default function TranBtn({ onClick, position, tranboxSetting }) {
|
||||
<div
|
||||
style={{
|
||||
cursor: "pointer",
|
||||
position: "fixed",
|
||||
position: "absolute",
|
||||
left: position.x + tranboxSetting.btnOffsetX,
|
||||
top: position.y + tranboxSetting.btnOffsetY,
|
||||
zIndex: 2147483647,
|
||||
|
||||
@@ -6,7 +6,7 @@ import Stack from "@mui/material/Stack";
|
||||
import { useI18n } from "../../hooks/I18n";
|
||||
import { DEFAULT_TRANS_APIS, OPT_TRANS_BAIDU } from "../../config";
|
||||
import { useEffect, useState } from "react";
|
||||
import { apiTranslate } from "../../apis";
|
||||
import { apiTranslate, apiBaiduLangdetect } from "../../apis";
|
||||
import { isValidWord } from "../../libs/utils";
|
||||
import CopyBtn from "./CopyBtn";
|
||||
import DictCont from "./DictCont";
|
||||
@@ -16,6 +16,9 @@ export default function TranCont({
|
||||
translator,
|
||||
fromLang,
|
||||
toLang,
|
||||
toLang2 = "en",
|
||||
setToLang,
|
||||
setToLang2,
|
||||
transApis,
|
||||
}) {
|
||||
const i18n = useI18n();
|
||||
@@ -32,8 +35,18 @@ export default function TranCont({
|
||||
setError("");
|
||||
setDictResult(null);
|
||||
|
||||
const apis = { ...transApis, ...DEFAULT_TRANS_APIS };
|
||||
const apiSetting = apis[translator];
|
||||
// 互译
|
||||
if (toLang !== toLang2 && toLang2 !== "none") {
|
||||
const detectLang = await apiBaiduLangdetect(text);
|
||||
if (detectLang === toLang) {
|
||||
setToLang(toLang2);
|
||||
setToLang2(toLang);
|
||||
return;
|
||||
}
|
||||
}
|
||||
|
||||
const apiSetting =
|
||||
transApis[translator] || DEFAULT_TRANS_APIS[translator];
|
||||
const tranRes = await apiTranslate({
|
||||
text,
|
||||
translator,
|
||||
@@ -53,7 +66,6 @@ export default function TranCont({
|
||||
translator: OPT_TRANS_BAIDU,
|
||||
fromLang: "en",
|
||||
toLang: "zh-CN",
|
||||
apiSetting: apis[OPT_TRANS_BAIDU],
|
||||
});
|
||||
setDictResult(dictRes[2].dict_result);
|
||||
}
|
||||
@@ -64,12 +76,22 @@ export default function TranCont({
|
||||
setLoading(false);
|
||||
}
|
||||
})();
|
||||
}, [text, translator, fromLang, toLang, transApis]);
|
||||
}, [
|
||||
text,
|
||||
translator,
|
||||
fromLang,
|
||||
toLang,
|
||||
toLang2,
|
||||
setToLang,
|
||||
setToLang2,
|
||||
transApis,
|
||||
]);
|
||||
|
||||
return (
|
||||
<>
|
||||
<Box>
|
||||
<TextField
|
||||
size="small"
|
||||
label={i18n("translated_text")}
|
||||
// disabled
|
||||
fullWidth
|
||||
|
||||
@@ -1,9 +1,12 @@
|
||||
import { useState, useEffect } from "react";
|
||||
import { useState, useEffect, useCallback } from "react";
|
||||
import TranBtn from "./TranBtn";
|
||||
import TranBox from "./TranBox";
|
||||
import { shortcutRegister } from "../../libs/shortcut";
|
||||
import { sleep } from "../../libs/utils";
|
||||
import { isGm } from "../../libs/client";
|
||||
import { MSG_OPEN_TRANBOX, DEFAULT_TRANBOX_SHORTCUT } from "../../config";
|
||||
|
||||
export default function Slection({ tranboxSetting, transApis }) {
|
||||
export default function Slection({ contextMenus, tranboxSetting, transApis }) {
|
||||
const [showBox, setShowBox] = useState(false);
|
||||
const [showBtn, setShowBtn] = useState(false);
|
||||
const [selectedText, setSelText] = useState("");
|
||||
@@ -15,47 +18,96 @@ export default function Slection({ tranboxSetting, transApis }) {
|
||||
y: (window.innerHeight - 400) / 2,
|
||||
});
|
||||
|
||||
function handleMouseup(e) {
|
||||
const handleClick = (e) => {
|
||||
e.stopPropagation();
|
||||
|
||||
setShowBtn(false);
|
||||
setText(selectedText);
|
||||
setShowBox(true);
|
||||
};
|
||||
|
||||
const handleTranbox = useCallback(() => {
|
||||
setShowBtn(false);
|
||||
|
||||
const selectedText = window.getSelection()?.toString()?.trim() || "";
|
||||
if (!selectedText) {
|
||||
setShowBtn(false);
|
||||
setShowBox((pre) => !pre);
|
||||
return;
|
||||
}
|
||||
|
||||
setSelText(selectedText);
|
||||
setShowBtn(true);
|
||||
setPosition({ x: e.clientX, y: e.clientY });
|
||||
}
|
||||
|
||||
const handleClick = (e) => {
|
||||
e.stopPropagation();
|
||||
setShowBtn(false);
|
||||
|
||||
setText(selectedText);
|
||||
if (!showBox) {
|
||||
setShowBox(true);
|
||||
}
|
||||
};
|
||||
setShowBox(true);
|
||||
}, []);
|
||||
|
||||
useEffect(() => {
|
||||
async function handleMouseup(e) {
|
||||
await sleep(10);
|
||||
|
||||
const selectedText = window.getSelection()?.toString()?.trim() || "";
|
||||
setSelText(selectedText);
|
||||
if (!selectedText) {
|
||||
setShowBtn(false);
|
||||
return;
|
||||
}
|
||||
|
||||
!tranboxSetting.hideTranBtn && setShowBtn(true);
|
||||
// setPosition({ x: e.clientX, y: e.clientY });
|
||||
setPosition({ x: e.pageX, y: e.pageY });
|
||||
}
|
||||
|
||||
window.addEventListener("mouseup", handleMouseup);
|
||||
return () => {
|
||||
window.removeEventListener("mouseup", handleMouseup);
|
||||
};
|
||||
}, []);
|
||||
}, [tranboxSetting.hideTranBtn]);
|
||||
|
||||
useEffect(() => {
|
||||
const clearShortcut = shortcutRegister(
|
||||
tranboxSetting.tranboxShortcut,
|
||||
() => {
|
||||
setShowBox((pre) => !pre);
|
||||
}
|
||||
tranboxSetting.tranboxShortcut || DEFAULT_TRANBOX_SHORTCUT,
|
||||
handleTranbox
|
||||
);
|
||||
|
||||
return () => {
|
||||
clearShortcut();
|
||||
};
|
||||
}, [tranboxSetting.tranboxShortcut, setShowBox]);
|
||||
}, [tranboxSetting.tranboxShortcut, handleTranbox]);
|
||||
|
||||
useEffect(() => {
|
||||
window.addEventListener(MSG_OPEN_TRANBOX, handleTranbox);
|
||||
return () => {
|
||||
window.removeEventListener(MSG_OPEN_TRANBOX, handleTranbox);
|
||||
};
|
||||
}, [handleTranbox]);
|
||||
|
||||
useEffect(() => {
|
||||
if (!isGm) {
|
||||
return;
|
||||
}
|
||||
|
||||
// 注册菜单
|
||||
try {
|
||||
const menuCommandIds = [];
|
||||
contextMenus &&
|
||||
menuCommandIds.push(
|
||||
GM.registerMenuCommand(
|
||||
"Translate Selected Text (Alt+S)",
|
||||
(event) => {
|
||||
handleTranbox();
|
||||
},
|
||||
"S"
|
||||
)
|
||||
);
|
||||
|
||||
return () => {
|
||||
menuCommandIds.forEach((id) => {
|
||||
GM.unregisterMenuCommand(id);
|
||||
});
|
||||
};
|
||||
} catch (err) {
|
||||
console.log("[registerMenuCommand]", err);
|
||||
}
|
||||
}, [handleTranbox, contextMenus]);
|
||||
|
||||
return (
|
||||
<>
|
||||
|
||||
Reference in New Issue
Block a user