Compare commits
32 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 |
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.12
|
||||
REACT_APP_VERSION=1.7.15
|
||||
|
||||
REACT_APP_HOMEPAGE=https://github.com/fishjar/kiss-translator
|
||||
|
||||
|
||||
10
README.en.md
10
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,7 +12,7 @@ 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
|
||||
@@ -31,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
|
||||
|
||||
@@ -39,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)
|
||||
|
||||
12
README.md
12
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,7 +12,7 @@
|
||||
- [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] 网页双语对照翻译
|
||||
@@ -31,7 +31,7 @@
|
||||
- `Alt+Q` 开启翻译
|
||||
- `Alt+C` 切换样式
|
||||
- `Alt+K` 打开设置弹窗
|
||||
- `Alt+B` 打开翻译弹窗
|
||||
- `Alt+S` 打开翻译弹窗/翻译选中文字
|
||||
- `Alt+O` 打开设置页面
|
||||
- `Alt+I` 输入框翻译
|
||||
|
||||
@@ -39,8 +39,8 @@
|
||||
|
||||
> 注:基于以下原因,建议优先使用浏览器扩展
|
||||
>
|
||||
> - 浏览器扩展可以使用本地的语言识别
|
||||
> - 油猴脚本会遇到更多使用上的问题
|
||||
> - 浏览器扩展的功能更完整(本地语言识别、右键菜单等)
|
||||
> - 油猴脚本会遇到更多使用上的问题(跨域问题、脚本冲突等)
|
||||
|
||||
- [x] 浏览器扩展
|
||||
- [x] Chrome [安装地址](https://chrome.google.com/webstore/detail/kiss-translator/bdiifdefkgmcblbcghdlonllpjhhjgof?hl=zh-CN)
|
||||
@@ -65,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.12",
|
||||
"version": "1.7.15",
|
||||
"author": "Gabe<yugang2002@gmail.com>",
|
||||
"private": true,
|
||||
"dependencies": {
|
||||
|
||||
@@ -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.12",
|
||||
"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.12",
|
||||
"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,
|
||||
@@ -181,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 });
|
||||
});
|
||||
|
||||
/**
|
||||
@@ -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:
|
||||
}
|
||||
});
|
||||
|
||||
180
src/common.js
180
src/common.js
@@ -8,27 +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 } from "./libs/utils";
|
||||
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 || {};
|
||||
@@ -52,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;
|
||||
@@ -80,7 +138,13 @@ export async function showFab(translator) {
|
||||
);
|
||||
}
|
||||
|
||||
export function showTransbox({
|
||||
/**
|
||||
* 划词翻译
|
||||
* @param {*} param0
|
||||
* @returns
|
||||
*/
|
||||
function showTransbox({
|
||||
contextMenus = true,
|
||||
tranboxSetting = DEFAULT_TRANBOX_SETTING,
|
||||
transApis,
|
||||
}) {
|
||||
@@ -104,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) {
|
||||
@@ -122,14 +194,23 @@ export function windowListener(rule) {
|
||||
});
|
||||
}
|
||||
|
||||
export function showErr(message) {
|
||||
/**
|
||||
* 显示错误信息到页面顶部
|
||||
* @param {*} message
|
||||
*/
|
||||
function showErr(message) {
|
||||
const $err = document.createElement("div");
|
||||
$err.innerText = `KISS-Translator: ${message}`;
|
||||
$err.style.cssText = "background:red; color:#fff;";
|
||||
document.body.prepend($err);
|
||||
}
|
||||
|
||||
export function touchOperation(translator) {
|
||||
/**
|
||||
* 监听触屏操作
|
||||
* @param {*} translator
|
||||
* @returns
|
||||
*/
|
||||
function touchOperation(translator) {
|
||||
const { touchTranslate = 2 } = translator.setting;
|
||||
if (touchTranslate === 0) {
|
||||
return;
|
||||
@@ -141,3 +222,66 @@ export function touchOperation(translator) {
|
||||
});
|
||||
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”选择器和内部选择器用“>>>”隔开。`,
|
||||
@@ -547,6 +559,10 @@ export const I18N = {
|
||||
zh: `隐藏悬浮按钮`,
|
||||
en: `Hide Fab Button`,
|
||||
},
|
||||
hide_tran_button: {
|
||||
zh: `隐藏翻译按钮`,
|
||||
en: `Hide Translate Button`,
|
||||
},
|
||||
show: {
|
||||
zh: `显示`,
|
||||
en: `Show`,
|
||||
@@ -628,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)`,
|
||||
@@ -671,4 +687,24 @@ export const I18N = {
|
||||
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`,
|
||||
},
|
||||
};
|
||||
|
||||
@@ -33,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";
|
||||
@@ -58,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";
|
||||
@@ -91,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 = [
|
||||
@@ -102,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,
|
||||
];
|
||||
@@ -224,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"],
|
||||
@@ -265,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,
|
||||
@@ -274,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 = [
|
||||
@@ -282,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";
|
||||
@@ -302,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"; // 默认高亮背景色/线条颜色
|
||||
|
||||
@@ -333,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,
|
||||
};
|
||||
|
||||
// 订阅列表
|
||||
@@ -380,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: "",
|
||||
@@ -399,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, // 深色模式
|
||||
@@ -418,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, // 翻译接口
|
||||
@@ -426,6 +454,8 @@ export const DEFAULT_SETTING = {
|
||||
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,81 +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,
|
||||
touchOperation,
|
||||
} 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);
|
||||
|
||||
// 触屏操作
|
||||
touchOperation(translator);
|
||||
} catch (err) {
|
||||
console.error("[KISS-Translator]", err);
|
||||
showErr(err.message);
|
||||
}
|
||||
})();
|
||||
run();
|
||||
|
||||
@@ -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({
|
||||
|
||||
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()));
|
||||
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);
|
||||
|
||||
@@ -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() {
|
||||
@@ -355,125 +265,6 @@ export class Translator {
|
||||
}
|
||||
};
|
||||
|
||||
_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("mouseenter", e);
|
||||
if (!this._tranNodes.has(e.target)) {
|
||||
|
||||
@@ -15,7 +15,7 @@ export const FIXER_ALL = [
|
||||
FIXER_BN,
|
||||
FIXER_BR_DIV,
|
||||
FIXER_BN_DIV,
|
||||
FIXER_FONTSIZE,
|
||||
// FIXER_FONTSIZE,
|
||||
];
|
||||
|
||||
/**
|
||||
|
||||
@@ -1,82 +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,
|
||||
touchOperation,
|
||||
} 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);
|
||||
|
||||
// 触屏操作
|
||||
touchOperation(translator);
|
||||
|
||||
// 同步订阅规则
|
||||
await trySyncAllSubRules(setting);
|
||||
} catch (err) {
|
||||
console.error("[KISS-Translator]", err);
|
||||
showErr(err.message);
|
||||
}
|
||||
})();
|
||||
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";
|
||||
@@ -115,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>
|
||||
|
||||
@@ -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);
|
||||
@@ -61,7 +65,10 @@ export default function Settings() {
|
||||
value = limitNumber(value, 1, 1000);
|
||||
break;
|
||||
case "touchTranslate":
|
||||
value = limitNumber(value, 0, 3);
|
||||
value = limitNumber(value, 0, 4);
|
||||
break;
|
||||
case "contextMenus":
|
||||
isExt && sendBgMsg(MSG_CONTEXT_MENUS, { contextMenus: value });
|
||||
break;
|
||||
default:
|
||||
}
|
||||
@@ -89,7 +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 || {};
|
||||
|
||||
@@ -181,7 +191,7 @@ export default function Settings() {
|
||||
label={i18n("touch_translate_shortcut")}
|
||||
onChange={handleChange}
|
||||
>
|
||||
{[0, 2, 3].map((item) => (
|
||||
{[0, 2, 3, 4].map((item) => (
|
||||
<MenuItem key={item} value={item}>
|
||||
{i18n(`touch_tap_${item}`)}
|
||||
</MenuItem>
|
||||
@@ -204,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
|
||||
@@ -218,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>
|
||||
@@ -268,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}
|
||||
|
||||
@@ -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: "第三人称单数",
|
||||
@@ -24,16 +25,16 @@ 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}>
|
||||
<Typography key={idx} component="div">
|
||||
{(ph_en || ph_am) && (
|
||||
<div>{`英 /${ph_en || ""}/ 美 /${ph_am || ""}/`}</div>
|
||||
<Typography>{`英 /${ph_en || ""}/ 美 /${ph_am || ""}/`}</Typography>
|
||||
)}
|
||||
<ul style={{ margin: "0.5em 0" }}>
|
||||
{parts.map(({ part, means }, idx) => (
|
||||
@@ -42,14 +43,14 @@ 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} flexWrap="wrap" useFlexGap>
|
||||
{Object.values(dictResult.simple_means?.tags || {})
|
||||
|
||||
@@ -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,6 +35,16 @@ export default function TranCont({
|
||||
setError("");
|
||||
setDictResult(null);
|
||||
|
||||
// 互译
|
||||
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({
|
||||
@@ -63,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,10 +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("");
|
||||
@@ -16,49 +18,96 @@ export default function Slection({ tranboxSetting, transApis }) {
|
||||
y: (window.innerHeight - 400) / 2,
|
||||
});
|
||||
|
||||
async function handleMouseup(e) {
|
||||
await sleep(10);
|
||||
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