Compare commits
60 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
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 | ||
|
|
c1920f5cdd | ||
|
|
3e24568df9 | ||
|
|
b785cfe854 | ||
|
|
15367bd117 | ||
|
|
d7eaac5aca | ||
|
|
d4526d605c | ||
|
|
52979356ca | ||
|
|
c6d3d6454f | ||
|
|
0d7112187d | ||
|
|
045ff3c3d9 | ||
|
|
dd68a73efd |
2
.env
2
.env
@@ -2,7 +2,7 @@ GENERATE_SOURCEMAP=false
|
|||||||
|
|
||||||
REACT_APP_NAME=KISS Translator
|
REACT_APP_NAME=KISS Translator
|
||||||
REACT_APP_NAME_CN=简约翻译
|
REACT_APP_NAME_CN=简约翻译
|
||||||
REACT_APP_VERSION=1.7.9
|
REACT_APP_VERSION=1.7.14
|
||||||
|
|
||||||
REACT_APP_HOMEPAGE=https://github.com/fishjar/kiss-translator
|
REACT_APP_HOMEPAGE=https://github.com/fishjar/kiss-translator
|
||||||
|
|
||||||
|
|||||||
15
README.en.md
15
README.en.md
@@ -1,6 +1,6 @@
|
|||||||
# KISS Translator
|
# 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)
|
[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
|
- [x] Chrome/Edge/Firefox/Kiwi
|
||||||
- [ ] Safari
|
- [ ] Safari
|
||||||
- [x] Supports multiple translation services
|
- [x] Supports multiple translation services
|
||||||
- [x] Google/Microsoft/DeepL/OpenAI/Baidu/Tencent
|
- [x] Google/Microsoft/DeepL/OpenAI/CloudflareAI/Baidu/Tencent
|
||||||
- [x] Custom translation interface
|
- [x] Custom translation interface
|
||||||
- [x] Covers common translation scenarios
|
- [x] Covers common translation scenarios
|
||||||
- [x] Web bilingual translation
|
- [x] Web bilingual translation
|
||||||
- [x] Input box translation
|
- [x] Input box translation
|
||||||
- [x] Seletction translation
|
- [x] Seletction translation
|
||||||
|
- [x] Favorite Words
|
||||||
- [x] Mouseover translation
|
- [x] Mouseover translation
|
||||||
- [x] YouTube subtitle translation
|
- [x] YouTube subtitle translation
|
||||||
- [x] Cross-client data synchronization
|
- [x] Cross-client data synchronization
|
||||||
@@ -30,7 +31,7 @@ A simple [bilingual translation extension & Greasemonkey script](https://github.
|
|||||||
- `Alt+Q` Toggle Translation
|
- `Alt+Q` Toggle Translation
|
||||||
- `Alt+C` Toggle Styles
|
- `Alt+C` Toggle Styles
|
||||||
- `Alt+K` Open Setting Popup
|
- `Alt+K` Open Setting Popup
|
||||||
- `Alt+B` Open Translate Popup
|
- `Alt+S` Open Translate Popup / Translate Selected Text
|
||||||
- `Alt+O` Open Options Page
|
- `Alt+O` Open Options Page
|
||||||
- `Alt+I` Input Box Translation
|
- `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
|
> Note: For the following reasons, it is recommended to use browser extensions first
|
||||||
>
|
>
|
||||||
> - Browser extension can use local language recognition
|
> - Browser extensions have more complete functions (local language recognition, context menu, etc.)
|
||||||
> - Grease Monkey script will encounter more usage problems
|
> - Grease Monkey script will encounter more usage problems (cross domain issues, script conflicts, etc.)
|
||||||
|
|
||||||
- [x] Browser extension
|
- [x] Browser extension
|
||||||
- [x] Chrome [Installation address](https://chrome.google.com/webstore/detail/kiss-translator/bdiifdefkgmcblbcghdlonllpjhhjgof?hl=zh-CN)
|
- [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/)
|
- [x] Firefox [Installation address](https://addons.mozilla.org/zh-CN/firefox/addon/kiss-translator/)
|
||||||
- [ ] Safari
|
- [ ] Safari
|
||||||
- [x] GreaseMonkey Script
|
- [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)
|
- 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
|
## 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)
|
[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
|
- [x] Chrome/Edge/Firefox/Kiwi
|
||||||
- [ ] Safari
|
- [ ] Safari
|
||||||
- [x] 支持多种翻译服务
|
- [x] 支持多种翻译服务
|
||||||
- [x] Google/Microsoft/DeepL/OpenAI/Baidu/Tencent
|
- [x] Google/Microsoft/DeepL/OpenAI/CloudflareAI/Baidu/Tencent
|
||||||
- [x] 自定义翻译接口
|
- [x] 自定义翻译接口
|
||||||
- [x] 覆盖常见翻译场景
|
- [x] 覆盖常见翻译场景
|
||||||
- [x] 网页双语对照翻译
|
- [x] 网页双语对照翻译
|
||||||
- [x] 输入框翻译
|
- [x] 输入框翻译
|
||||||
- [x] 划词翻译
|
- [x] 划词翻译
|
||||||
|
- [x] 收藏词汇
|
||||||
- [x] 鼠标悬停翻译
|
- [x] 鼠标悬停翻译
|
||||||
- [x] YouTube 字幕翻译
|
- [x] YouTube 字幕翻译
|
||||||
- [x] 跨客户端数据同步
|
- [x] 跨客户端数据同步
|
||||||
@@ -30,7 +31,7 @@
|
|||||||
- `Alt+Q` 开启翻译
|
- `Alt+Q` 开启翻译
|
||||||
- `Alt+C` 切换样式
|
- `Alt+C` 切换样式
|
||||||
- `Alt+K` 打开设置弹窗
|
- `Alt+K` 打开设置弹窗
|
||||||
- `Alt+B` 打开翻译弹窗
|
- `Alt+S` 打开翻译弹窗/翻译选中文字
|
||||||
- `Alt+O` 打开设置页面
|
- `Alt+O` 打开设置页面
|
||||||
- `Alt+I` 输入框翻译
|
- `Alt+I` 输入框翻译
|
||||||
|
|
||||||
@@ -38,8 +39,8 @@
|
|||||||
|
|
||||||
> 注:基于以下原因,建议优先使用浏览器扩展
|
> 注:基于以下原因,建议优先使用浏览器扩展
|
||||||
>
|
>
|
||||||
> - 浏览器扩展可以使用本地的语言识别
|
> - 浏览器扩展的功能更完整(本地语言识别、右键菜单等)
|
||||||
> - 油猴脚本会遇到更多使用上的问题
|
> - 油猴脚本会遇到更多使用上的问题(跨域问题、脚本冲突等)
|
||||||
|
|
||||||
- [x] 浏览器扩展
|
- [x] 浏览器扩展
|
||||||
- [x] Chrome [安装地址](https://chrome.google.com/webstore/detail/kiss-translator/bdiifdefkgmcblbcghdlonllpjhhjgof?hl=zh-CN)
|
- [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/)
|
- [x] Firefox [安装地址](https://addons.mozilla.org/zh-CN/firefox/addon/kiss-translator/)
|
||||||
- [ ] Safari
|
- [ ] Safari
|
||||||
- [x] 油猴脚本
|
- [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)
|
- 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-proxy](https://github.com/fishjar/kiss-proxy)
|
||||||
- 如果访问某个翻译接口遇到网络问题,这个代理服务也许可以帮你到你。
|
- 如果访问某个翻译接口遇到网络问题,这个代理服务也许可以帮到你。
|
||||||
- 自己部署,自己管理。
|
- 自己部署,自己管理。
|
||||||
- 简约词典插件: [https://github.com/fishjar/kiss-dictionary](https://github.com/fishjar/kiss-dictionary)
|
- 简约词典插件: [https://github.com/fishjar/kiss-dictionary](https://github.com/fishjar/kiss-dictionary)
|
||||||
- 搭配本项目一起使用的划词翻译插件。
|
- 搭配本项目一起使用的划词翻译插件。
|
||||||
|
|||||||
@@ -1,7 +1,7 @@
|
|||||||
{
|
{
|
||||||
"name": "kiss-translator",
|
"name": "kiss-translator",
|
||||||
"description": "A minimalist bilingual translation Extension & Greasemonkey Script",
|
"description": "A minimalist bilingual translation Extension & Greasemonkey Script",
|
||||||
"version": "1.7.9",
|
"version": "1.7.14",
|
||||||
"author": "Gabe<yugang2002@gmail.com>",
|
"author": "Gabe<yugang2002@gmail.com>",
|
||||||
"private": true,
|
"private": true,
|
||||||
"dependencies": {
|
"dependencies": {
|
||||||
@@ -30,7 +30,6 @@
|
|||||||
"build:userscript": "rm -rf build/userscript && mkdir build/userscript && cp build/web/*.user.js build/userscript/",
|
"build:userscript": "rm -rf build/userscript && mkdir build/userscript && cp build/web/*.user.js build/userscript/",
|
||||||
"build:rules": "babel-node src/rules.js",
|
"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",
|
"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",
|
"test": "react-app-rewired test",
|
||||||
"eject": "react-scripts eject"
|
"eject": "react-scripts eject"
|
||||||
},
|
},
|
||||||
|
|||||||
@@ -6,12 +6,15 @@
|
|||||||
"message": "A simple bilingual translation extension & Greasemonkey script"
|
"message": "A simple bilingual translation extension & Greasemonkey script"
|
||||||
},
|
},
|
||||||
"toggle_translate": {
|
"toggle_translate": {
|
||||||
"message": "Toggle Translate"
|
"message": "Toggle Translate (Alt+Q)"
|
||||||
},
|
},
|
||||||
"toggle_style": {
|
"toggle_style": {
|
||||||
"message": "Toggle Style"
|
"message": "Toggle Style (Alt+C)"
|
||||||
},
|
},
|
||||||
"open_options": {
|
"open_options": {
|
||||||
"message": "Open Options"
|
"message": "Open Options (Alt+O)"
|
||||||
|
},
|
||||||
|
"open_tranbox": {
|
||||||
|
"message": "Translate Popup/Selected (Alt+S)"
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -6,12 +6,15 @@
|
|||||||
"message": "一个简约的双语对照翻译扩展 & 油猴脚本"
|
"message": "一个简约的双语对照翻译扩展 & 油猴脚本"
|
||||||
},
|
},
|
||||||
"toggle_translate": {
|
"toggle_translate": {
|
||||||
"message": "开启翻译"
|
"message": "开启翻译 (Alt+Q)"
|
||||||
},
|
},
|
||||||
"toggle_style": {
|
"toggle_style": {
|
||||||
"message": "切换样式"
|
"message": "切换样式 (Alt+C)"
|
||||||
},
|
},
|
||||||
"open_options": {
|
"open_options": {
|
||||||
"message": "打开设置"
|
"message": "打开设置 (Alt+O)"
|
||||||
|
},
|
||||||
|
"open_tranbox": {
|
||||||
|
"message": "翻译弹窗/选中文字 (Alt+S)"
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -2,7 +2,7 @@
|
|||||||
"manifest_version": 2,
|
"manifest_version": 2,
|
||||||
"name": "__MSG_app_name__",
|
"name": "__MSG_app_name__",
|
||||||
"description": "__MSG_app_description__",
|
"description": "__MSG_app_description__",
|
||||||
"version": "1.7.9",
|
"version": "1.7.14",
|
||||||
"default_locale": "en",
|
"default_locale": "en",
|
||||||
"author": "Gabe<yugang2002@gmail.com>",
|
"author": "Gabe<yugang2002@gmail.com>",
|
||||||
"homepage_url": "https://github.com/fishjar/kiss-translator",
|
"homepage_url": "https://github.com/fishjar/kiss-translator",
|
||||||
@@ -41,7 +41,7 @@
|
|||||||
"description": "__MSG_open_options__"
|
"description": "__MSG_open_options__"
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
"permissions": ["<all_urls>", "storage"],
|
"permissions": ["<all_urls>", "storage", "contextMenus"],
|
||||||
"icons": {
|
"icons": {
|
||||||
"16": "images/logo16.png",
|
"16": "images/logo16.png",
|
||||||
"32": "images/logo32.png",
|
"32": "images/logo32.png",
|
||||||
|
|||||||
@@ -2,7 +2,7 @@
|
|||||||
"manifest_version": 3,
|
"manifest_version": 3,
|
||||||
"name": "__MSG_app_name__",
|
"name": "__MSG_app_name__",
|
||||||
"description": "__MSG_app_description__",
|
"description": "__MSG_app_description__",
|
||||||
"version": "1.7.9",
|
"version": "1.7.14",
|
||||||
"default_locale": "en",
|
"default_locale": "en",
|
||||||
"author": "Gabe<yugang2002@gmail.com>",
|
"author": "Gabe<yugang2002@gmail.com>",
|
||||||
"homepage_url": "https://github.com/fishjar/kiss-translator",
|
"homepage_url": "https://github.com/fishjar/kiss-translator",
|
||||||
@@ -42,7 +42,7 @@
|
|||||||
"description": "__MSG_open_options__"
|
"description": "__MSG_open_options__"
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
"permissions": ["storage"],
|
"permissions": ["storage", "contextMenus"],
|
||||||
"host_permissions": ["<all_urls>"],
|
"host_permissions": ["<all_urls>"],
|
||||||
"icons": {
|
"icons": {
|
||||||
"16": "images/logo16.png",
|
"16": "images/logo16.png",
|
||||||
|
|||||||
@@ -9,6 +9,7 @@ import {
|
|||||||
OPT_TRANS_BAIDU,
|
OPT_TRANS_BAIDU,
|
||||||
OPT_TRANS_TENCENT,
|
OPT_TRANS_TENCENT,
|
||||||
OPT_TRANS_OPENAI,
|
OPT_TRANS_OPENAI,
|
||||||
|
OPT_TRANS_CLOUDFLAREAI,
|
||||||
OPT_TRANS_CUSTOMIZE,
|
OPT_TRANS_CUSTOMIZE,
|
||||||
URL_CACHE_TRAN,
|
URL_CACHE_TRAN,
|
||||||
KV_SALT_SYNC,
|
KV_SALT_SYNC,
|
||||||
@@ -110,11 +111,15 @@ export const apiTranslate = async ({
|
|||||||
let trText = "";
|
let trText = "";
|
||||||
let isSame = false;
|
let isSame = false;
|
||||||
|
|
||||||
|
if (!text) {
|
||||||
|
return [trText, true];
|
||||||
|
}
|
||||||
|
|
||||||
const from =
|
const from =
|
||||||
OPT_LANGS_SPECIAL[translator].get(fromLang) ??
|
OPT_LANGS_SPECIAL[translator].get(fromLang) ??
|
||||||
OPT_LANGS_SPECIAL[translator].get("auto");
|
OPT_LANGS_SPECIAL[translator].get("auto");
|
||||||
const to = OPT_LANGS_SPECIAL[translator].get(toLang);
|
const to = OPT_LANGS_SPECIAL[translator].get(toLang);
|
||||||
if (!text || !to) {
|
if (!to) {
|
||||||
console.log(`[trans] target lang: ${toLang} not support`);
|
console.log(`[trans] target lang: ${toLang} not support`);
|
||||||
return [trText, isSame];
|
return [trText, isSame];
|
||||||
}
|
}
|
||||||
@@ -176,12 +181,15 @@ export const apiTranslate = async ({
|
|||||||
trText = res?.choices?.[0].message.content;
|
trText = res?.choices?.[0].message.content;
|
||||||
isSame = text === trText;
|
isSame = text === trText;
|
||||||
break;
|
break;
|
||||||
|
case OPT_TRANS_CLOUDFLAREAI:
|
||||||
|
trText = res?.result?.translated_text;
|
||||||
|
isSame = text === trText;
|
||||||
|
break;
|
||||||
case OPT_TRANS_CUSTOMIZE:
|
case OPT_TRANS_CUSTOMIZE:
|
||||||
trText = res.text;
|
trText = res.text;
|
||||||
isSame = to === res.from;
|
isSame = to === res.from;
|
||||||
break;
|
break;
|
||||||
default:
|
default:
|
||||||
break;
|
|
||||||
}
|
}
|
||||||
|
|
||||||
return [trText, isSame, res];
|
return [trText, isSame, res];
|
||||||
|
|||||||
@@ -7,9 +7,11 @@ import {
|
|||||||
MSG_OPEN_OPTIONS,
|
MSG_OPEN_OPTIONS,
|
||||||
MSG_SAVE_RULE,
|
MSG_SAVE_RULE,
|
||||||
MSG_TRANS_TOGGLE_STYLE,
|
MSG_TRANS_TOGGLE_STYLE,
|
||||||
|
MSG_OPEN_TRANBOX,
|
||||||
CMD_TOGGLE_TRANSLATE,
|
CMD_TOGGLE_TRANSLATE,
|
||||||
CMD_TOGGLE_STYLE,
|
CMD_TOGGLE_STYLE,
|
||||||
CMD_OPEN_OPTIONS,
|
CMD_OPEN_OPTIONS,
|
||||||
|
CMD_OPEN_TRANBOX,
|
||||||
} from "./config";
|
} from "./config";
|
||||||
import { getSettingWithDefault, tryInitDefaultData } from "./libs/storage";
|
import { getSettingWithDefault, tryInitDefaultData } from "./libs/storage";
|
||||||
import { trySyncSettingAndRules } from "./libs/sync";
|
import { trySyncSettingAndRules } from "./libs/sync";
|
||||||
@@ -26,14 +28,39 @@ globalThis.ContextType = "BACKGROUND";
|
|||||||
*/
|
*/
|
||||||
browser.runtime.onInstalled.addListener(() => {
|
browser.runtime.onInstalled.addListener(() => {
|
||||||
tryInitDefaultData();
|
tryInitDefaultData();
|
||||||
|
|
||||||
|
// 右键菜单
|
||||||
|
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"],
|
||||||
|
});
|
||||||
});
|
});
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* 浏览器启动
|
* 浏览器启动
|
||||||
*/
|
*/
|
||||||
browser.runtime.onStartup.addListener(async () => {
|
browser.runtime.onStartup.addListener(async () => {
|
||||||
console.log("browser onStartup");
|
|
||||||
|
|
||||||
// 同步数据
|
// 同步数据
|
||||||
await trySyncSettingAndRules();
|
await trySyncSettingAndRules();
|
||||||
|
|
||||||
@@ -60,7 +87,7 @@ browser.runtime.onMessage.addListener(
|
|||||||
sendResponse({ data });
|
sendResponse({ data });
|
||||||
})
|
})
|
||||||
.catch((error) => {
|
.catch((error) => {
|
||||||
sendResponse({ error: error.message });
|
sendResponse({ error: error.message, cause: error.cause });
|
||||||
});
|
});
|
||||||
break;
|
break;
|
||||||
case MSG_FETCH_LIMIT:
|
case MSG_FETCH_LIMIT:
|
||||||
@@ -103,3 +130,21 @@ browser.commands.onCommand.addListener((command) => {
|
|||||||
default:
|
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:
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|||||||
186
src/common.js
186
src/common.js
@@ -8,25 +8,79 @@ import {
|
|||||||
MSG_TRANS_TOGGLE_STYLE,
|
MSG_TRANS_TOGGLE_STYLE,
|
||||||
MSG_TRANS_GETRULE,
|
MSG_TRANS_GETRULE,
|
||||||
MSG_TRANS_PUTRULE,
|
MSG_TRANS_PUTRULE,
|
||||||
|
MSG_OPEN_TRANBOX,
|
||||||
APP_LCNAME,
|
APP_LCNAME,
|
||||||
DEFAULT_TRANBOX_SETTING,
|
DEFAULT_TRANBOX_SETTING,
|
||||||
} from "./config";
|
} from "./config";
|
||||||
import { getRulesWithDefault, getFabWithDefault } from "./libs/storage";
|
import { getFabWithDefault, getSettingWithDefault } from "./libs/storage";
|
||||||
import { Translator } from "./libs/translator";
|
import { Translator } from "./libs/translator";
|
||||||
import { sendIframeMsg, sendParentMsg } from "./libs/iframe";
|
import { isIframe, sendIframeMsg, sendParentMsg } from "./libs/iframe";
|
||||||
import { matchRule } from "./libs/rules";
|
|
||||||
import Slection from "./views/Selection";
|
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";
|
||||||
|
|
||||||
export async function runTranslator(setting) {
|
/**
|
||||||
const href = document.location.href;
|
* 油猴脚本设置页面
|
||||||
const rules = await getRulesWithDefault();
|
*/
|
||||||
const rule = await matchRule(rules, href, setting);
|
function runSettingPage() {
|
||||||
const translator = new Translator(rule, setting);
|
if (GM?.info?.script?.grant?.includes("unsafeWindow")) {
|
||||||
|
unsafeWindow.GM = GM;
|
||||||
return { translator, rule };
|
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;
|
let translator;
|
||||||
window.addEventListener("message", (e) => {
|
window.addEventListener("message", (e) => {
|
||||||
const { action, args } = e.data || {};
|
const { action, args } = e.data || {};
|
||||||
@@ -50,7 +104,12 @@ export function runIframe(setting) {
|
|||||||
sendParentMsg(MSG_TRANS_GETRULE);
|
sendParentMsg(MSG_TRANS_GETRULE);
|
||||||
}
|
}
|
||||||
|
|
||||||
export async function showFab(translator) {
|
/**
|
||||||
|
* 悬浮按钮
|
||||||
|
* @param {*} translator
|
||||||
|
* @returns
|
||||||
|
*/
|
||||||
|
async function showFab(translator) {
|
||||||
const fab = await getFabWithDefault();
|
const fab = await getFabWithDefault();
|
||||||
if (fab.isHide) {
|
if (fab.isHide) {
|
||||||
return;
|
return;
|
||||||
@@ -78,10 +137,12 @@ export async function showFab(translator) {
|
|||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
export function showTransbox({
|
/**
|
||||||
tranboxSetting = DEFAULT_TRANBOX_SETTING,
|
* 划词翻译
|
||||||
transApis,
|
* @param {*} param0
|
||||||
}) {
|
* @returns
|
||||||
|
*/
|
||||||
|
function showTransbox({ tranboxSetting = DEFAULT_TRANBOX_SETTING, transApis }) {
|
||||||
if (!tranboxSetting?.transOpen) {
|
if (!tranboxSetting?.transOpen) {
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
@@ -108,7 +169,11 @@ export function showTransbox({
|
|||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
export function windowListener(rule) {
|
/**
|
||||||
|
* 监听来自iframe页面消息
|
||||||
|
* @param {*} rule
|
||||||
|
*/
|
||||||
|
function windowListener(rule) {
|
||||||
window.addEventListener("message", (e) => {
|
window.addEventListener("message", (e) => {
|
||||||
const { action } = e.data || {};
|
const { action } = e.data || {};
|
||||||
switch (action) {
|
switch (action) {
|
||||||
@@ -120,10 +185,91 @@ export function windowListener(rule) {
|
|||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
export function showErr(err) {
|
/**
|
||||||
console.error("[KISS-Translator]", err);
|
* 显示错误信息到页面顶部
|
||||||
|
* @param {*} message
|
||||||
|
*/
|
||||||
|
function showErr(message) {
|
||||||
const $err = document.createElement("div");
|
const $err = document.createElement("div");
|
||||||
$err.innerText = `KISS-Translator: ${err.message}`;
|
$err.innerText = `KISS-Translator: ${message}`;
|
||||||
$err.style.cssText = "background:red; color:#fff;";
|
$err.style.cssText = "background:red; color:#fff;";
|
||||||
document.body.prepend($err);
|
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);
|
||||||
|
|
||||||
|
// 划词翻译
|
||||||
|
showTransbox(setting);
|
||||||
|
|
||||||
|
// 浮球按钮
|
||||||
|
await showFab(translator);
|
||||||
|
|
||||||
|
// 触屏操作
|
||||||
|
touchOperation(translator);
|
||||||
|
|
||||||
|
// 同步订阅规则
|
||||||
|
isUserscript && (await trySyncAllSubRules(setting));
|
||||||
|
} catch (err) {
|
||||||
|
console.error("[KISS-Translator]", err);
|
||||||
|
showErr(err.message);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|||||||
@@ -335,6 +335,10 @@ export const I18N = {
|
|||||||
zh: `高亮`,
|
zh: `高亮`,
|
||||||
en: `Highlight`,
|
en: `Highlight`,
|
||||||
},
|
},
|
||||||
|
blockquote: {
|
||||||
|
zh: `引用`,
|
||||||
|
en: `Blockquote`,
|
||||||
|
},
|
||||||
diy_style: {
|
diy_style: {
|
||||||
zh: `自定义样式`,
|
zh: `自定义样式`,
|
||||||
en: `Custom Style`,
|
en: `Custom Style`,
|
||||||
@@ -352,8 +356,8 @@ export const I18N = {
|
|||||||
en: `URL pattern`,
|
en: `URL pattern`,
|
||||||
},
|
},
|
||||||
pattern_helper: {
|
pattern_helper: {
|
||||||
zh: `1、支持星号(*)通配符。2、多个URL支持英文逗号“,”分隔。`,
|
zh: `1、支持星号(*)通配符。2、多个URL用英文逗号“,”分隔。`,
|
||||||
en: `1. The asterisk (*) wildcard is supported. 2. Multiple URLs can be separated by English commas ",".`,
|
en: `1. The asterisk (*) wildcard is supported. 2. Multiple URLs separated by English commas ",".`,
|
||||||
},
|
},
|
||||||
selector_helper: {
|
selector_helper: {
|
||||||
zh: `1、遵循CSS选择器语法。2、留空表示采用全局设置。3、多个CSS选择器之间用“;”隔开。4、“shadow root”选择器和内部选择器用“>>>”隔开。`,
|
zh: `1、遵循CSS选择器语法。2、留空表示采用全局设置。3、多个CSS选择器之间用“;”隔开。4、“shadow root”选择器和内部选择器用“>>>”隔开。`,
|
||||||
@@ -375,6 +379,14 @@ export const I18N = {
|
|||||||
zh: `选择器`,
|
zh: `选择器`,
|
||||||
en: `Selector`,
|
en: `Selector`,
|
||||||
},
|
},
|
||||||
|
root_selector: {
|
||||||
|
zh: `根选择器`,
|
||||||
|
en: `Root Selector`,
|
||||||
|
},
|
||||||
|
fixer_function: {
|
||||||
|
zh: `修复函数`,
|
||||||
|
en: `Fixer Function`,
|
||||||
|
},
|
||||||
import: {
|
import: {
|
||||||
zh: `导入`,
|
zh: `导入`,
|
||||||
en: `Import`,
|
en: `Import`,
|
||||||
@@ -539,6 +551,10 @@ export const I18N = {
|
|||||||
zh: `隐藏悬浮按钮`,
|
zh: `隐藏悬浮按钮`,
|
||||||
en: `Hide Fab Button`,
|
en: `Hide Fab Button`,
|
||||||
},
|
},
|
||||||
|
hide_tran_button: {
|
||||||
|
zh: `隐藏翻译按钮`,
|
||||||
|
en: `Hide Translate Button`,
|
||||||
|
},
|
||||||
show: {
|
show: {
|
||||||
zh: `显示`,
|
zh: `显示`,
|
||||||
en: `Show`,
|
en: `Show`,
|
||||||
@@ -555,11 +571,11 @@ export const I18N = {
|
|||||||
zh: `全局规则`,
|
zh: `全局规则`,
|
||||||
en: `Global Rule`,
|
en: `Global Rule`,
|
||||||
},
|
},
|
||||||
input_setting: {
|
input_translate: {
|
||||||
zh: `输入框设置`,
|
zh: `输入框翻译`,
|
||||||
en: `Input Box Setting`,
|
en: `Input Box Translation`,
|
||||||
},
|
},
|
||||||
input_box_translation: {
|
use_input_box_translation: {
|
||||||
zh: `启用输入框翻译`,
|
zh: `启用输入框翻译`,
|
||||||
en: `Input Box Translation`,
|
en: `Input Box Translation`,
|
||||||
},
|
},
|
||||||
@@ -620,8 +636,8 @@ export const I18N = {
|
|||||||
en: `Use Selection Translate`,
|
en: `Use Selection Translate`,
|
||||||
},
|
},
|
||||||
trigger_tranbox_shortcut: {
|
trigger_tranbox_shortcut: {
|
||||||
zh: `显示翻译框快捷键`,
|
zh: `显示翻译框/翻译选中文字快捷键`,
|
||||||
en: `Toggle Translate Box Shortcut`,
|
en: `Open Translate Popup/Translate Selected Shortcut`,
|
||||||
},
|
},
|
||||||
tranbtn_offset_x: {
|
tranbtn_offset_x: {
|
||||||
zh: `翻译按钮偏移X(0-100)`,
|
zh: `翻译按钮偏移X(0-100)`,
|
||||||
@@ -639,4 +655,44 @@ export const I18N = {
|
|||||||
zh: `原文`,
|
zh: `原文`,
|
||||||
en: `Original Text`,
|
en: `Original Text`,
|
||||||
},
|
},
|
||||||
|
favorite_words: {
|
||||||
|
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.`,
|
||||||
|
}
|
||||||
};
|
};
|
||||||
|
|||||||
@@ -23,6 +23,8 @@ export const STOKEY_MSAUTH = `${APP_NAME}_msauth`;
|
|||||||
export const STOKEY_BDAUTH = `${APP_NAME}_bdauth`;
|
export const STOKEY_BDAUTH = `${APP_NAME}_bdauth`;
|
||||||
export const STOKEY_SETTING = `${APP_NAME}_setting`;
|
export const STOKEY_SETTING = `${APP_NAME}_setting`;
|
||||||
export const STOKEY_RULES = `${APP_NAME}_rules`;
|
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_SYNC = `${APP_NAME}_sync`;
|
||||||
export const STOKEY_FAB = `${APP_NAME}_fab`;
|
export const STOKEY_FAB = `${APP_NAME}_fab`;
|
||||||
export const STOKEY_RULESCACHE_PREFIX = `${APP_NAME}_rulescache_`;
|
export const STOKEY_RULESCACHE_PREFIX = `${APP_NAME}_rulescache_`;
|
||||||
@@ -31,6 +33,7 @@ export const STOKEY_WEBFIXCACHE_PREFIX = `${APP_NAME}_webfixcache_`;
|
|||||||
export const CMD_TOGGLE_TRANSLATE = "toggleTranslate";
|
export const CMD_TOGGLE_TRANSLATE = "toggleTranslate";
|
||||||
export const CMD_TOGGLE_STYLE = "toggleStyle";
|
export const CMD_TOGGLE_STYLE = "toggleStyle";
|
||||||
export const CMD_OPEN_OPTIONS = "openOptions";
|
export const CMD_OPEN_OPTIONS = "openOptions";
|
||||||
|
export const CMD_OPEN_TRANBOX = "openTranbox";
|
||||||
|
|
||||||
export const CLIENT_WEB = "web";
|
export const CLIENT_WEB = "web";
|
||||||
export const CLIENT_CHROME = "chrome";
|
export const CLIENT_CHROME = "chrome";
|
||||||
@@ -40,6 +43,8 @@ export const CLIENT_USERSCRIPT = "userscript";
|
|||||||
export const CLIENT_EXTS = [CLIENT_CHROME, CLIENT_EDGE, CLIENT_FIREFOX];
|
export const CLIENT_EXTS = [CLIENT_CHROME, CLIENT_EDGE, CLIENT_FIREFOX];
|
||||||
|
|
||||||
export const KV_RULES_KEY = "kiss-rules.json";
|
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_RULES_SHARE_KEY = "kiss-rules-share.json";
|
||||||
export const KV_SETTING_KEY = "kiss-setting.json";
|
export const KV_SETTING_KEY = "kiss-setting.json";
|
||||||
export const KV_SALT_SYNC = "KISS-Translator-SYNC";
|
export const KV_SALT_SYNC = "KISS-Translator-SYNC";
|
||||||
@@ -54,6 +59,7 @@ export const MSG_OPEN_OPTIONS = "open_options";
|
|||||||
export const MSG_SAVE_RULE = "save_rule";
|
export const MSG_SAVE_RULE = "save_rule";
|
||||||
export const MSG_TRANS_TOGGLE = "trans_toggle";
|
export const MSG_TRANS_TOGGLE = "trans_toggle";
|
||||||
export const MSG_TRANS_TOGGLE_STYLE = "trans_toggle_style";
|
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_GETRULE = "trans_getrule";
|
||||||
export const MSG_TRANS_PUTRULE = "trans_putrule";
|
export const MSG_TRANS_PUTRULE = "trans_putrule";
|
||||||
export const MSG_TRANS_CURRULE = "trans_currule";
|
export const MSG_TRANS_CURRULE = "trans_currule";
|
||||||
@@ -87,6 +93,7 @@ export const OPT_TRANS_DEEPLFREE = "DeepLFree";
|
|||||||
export const OPT_TRANS_BAIDU = "Baidu";
|
export const OPT_TRANS_BAIDU = "Baidu";
|
||||||
export const OPT_TRANS_TENCENT = "Tencent";
|
export const OPT_TRANS_TENCENT = "Tencent";
|
||||||
export const OPT_TRANS_OPENAI = "OpenAI";
|
export const OPT_TRANS_OPENAI = "OpenAI";
|
||||||
|
export const OPT_TRANS_CLOUDFLAREAI = "CloudflareAI";
|
||||||
export const OPT_TRANS_CUSTOMIZE = "Custom";
|
export const OPT_TRANS_CUSTOMIZE = "Custom";
|
||||||
export const OPT_TRANS_ALL = [
|
export const OPT_TRANS_ALL = [
|
||||||
OPT_TRANS_GOOGLE,
|
OPT_TRANS_GOOGLE,
|
||||||
@@ -97,6 +104,7 @@ export const OPT_TRANS_ALL = [
|
|||||||
OPT_TRANS_BAIDU,
|
OPT_TRANS_BAIDU,
|
||||||
OPT_TRANS_TENCENT,
|
OPT_TRANS_TENCENT,
|
||||||
OPT_TRANS_OPENAI,
|
OPT_TRANS_OPENAI,
|
||||||
|
OPT_TRANS_CLOUDFLAREAI,
|
||||||
OPT_TRANS_CUSTOMIZE,
|
OPT_TRANS_CUSTOMIZE,
|
||||||
];
|
];
|
||||||
|
|
||||||
@@ -218,6 +226,20 @@ export const OPT_LANGS_SPECIAL = {
|
|||||||
[OPT_TRANS_OPENAI]: new Map(
|
[OPT_TRANS_OPENAI]: new Map(
|
||||||
OPT_LANGS_FROM.map(([key, val]) => [key, val.split(" - ")[0]])
|
OPT_LANGS_FROM.map(([key, val]) => [key, val.split(" - ")[0]])
|
||||||
),
|
),
|
||||||
|
[OPT_TRANS_CLOUDFLAREAI]: new Map([
|
||||||
|
["auto", ""],
|
||||||
|
["zh-CN", "chinese"],
|
||||||
|
["zh-TW", "chinese"],
|
||||||
|
["en", "english"],
|
||||||
|
["ar", "arabic"],
|
||||||
|
["de", "german"],
|
||||||
|
["ru", "russian"],
|
||||||
|
["fr", "french"],
|
||||||
|
["pt", "portuguese"],
|
||||||
|
["ja", "japanese"],
|
||||||
|
["es", "spanish"],
|
||||||
|
["hi", "hindi"],
|
||||||
|
]),
|
||||||
[OPT_TRANS_CUSTOMIZE]: new Map([
|
[OPT_TRANS_CUSTOMIZE]: new Map([
|
||||||
...OPT_LANGS_FROM.map(([key]) => [key, key]),
|
...OPT_LANGS_FROM.map(([key]) => [key, key]),
|
||||||
["auto", ""],
|
["auto", ""],
|
||||||
@@ -245,6 +267,7 @@ export const OPT_STYLE_DASHLINE = "dash_line"; // 虚线
|
|||||||
export const OPT_STYLE_WAVYLINE = "wavy_line"; // 波浪线
|
export const OPT_STYLE_WAVYLINE = "wavy_line"; // 波浪线
|
||||||
export const OPT_STYLE_FUZZY = "fuzzy"; // 模糊
|
export const OPT_STYLE_FUZZY = "fuzzy"; // 模糊
|
||||||
export const OPT_STYLE_HIGHLIGHT = "highlight"; // 高亮
|
export const OPT_STYLE_HIGHLIGHT = "highlight"; // 高亮
|
||||||
|
export const OPT_STYLE_BLOCKQUOTE = "blockquote"; // 引用
|
||||||
export const OPT_STYLE_DIY = "diy_style"; // 自定义样式
|
export const OPT_STYLE_DIY = "diy_style"; // 自定义样式
|
||||||
export const OPT_STYLE_ALL = [
|
export const OPT_STYLE_ALL = [
|
||||||
OPT_STYLE_NONE,
|
OPT_STYLE_NONE,
|
||||||
@@ -254,6 +277,7 @@ export const OPT_STYLE_ALL = [
|
|||||||
OPT_STYLE_WAVYLINE,
|
OPT_STYLE_WAVYLINE,
|
||||||
OPT_STYLE_FUZZY,
|
OPT_STYLE_FUZZY,
|
||||||
OPT_STYLE_HIGHLIGHT,
|
OPT_STYLE_HIGHLIGHT,
|
||||||
|
OPT_STYLE_BLOCKQUOTE,
|
||||||
OPT_STYLE_DIY,
|
OPT_STYLE_DIY,
|
||||||
];
|
];
|
||||||
export const OPT_STYLE_USE_COLOR = [
|
export const OPT_STYLE_USE_COLOR = [
|
||||||
@@ -262,6 +286,7 @@ export const OPT_STYLE_USE_COLOR = [
|
|||||||
OPT_STYLE_DASHLINE,
|
OPT_STYLE_DASHLINE,
|
||||||
OPT_STYLE_WAVYLINE,
|
OPT_STYLE_WAVYLINE,
|
||||||
OPT_STYLE_HIGHLIGHT,
|
OPT_STYLE_HIGHLIGHT,
|
||||||
|
OPT_STYLE_BLOCKQUOTE,
|
||||||
];
|
];
|
||||||
|
|
||||||
export const OPT_MOUSEKEY_DISABLE = "mk_disable";
|
export const OPT_MOUSEKEY_DISABLE = "mk_disable";
|
||||||
@@ -313,7 +338,7 @@ export const DEFAULT_INPUT_RULE = {
|
|||||||
};
|
};
|
||||||
|
|
||||||
// 划词翻译
|
// 划词翻译
|
||||||
export const DEFAULT_TRANBOX_SHORTCUT = ["AltLeft", "KeyB"];
|
export const DEFAULT_TRANBOX_SHORTCUT = ["AltLeft", "KeyS"];
|
||||||
export const DEFAULT_TRANBOX_SETTING = {
|
export const DEFAULT_TRANBOX_SETTING = {
|
||||||
transOpen: true,
|
transOpen: true,
|
||||||
translator: OPT_TRANS_MICROSOFT,
|
translator: OPT_TRANS_MICROSOFT,
|
||||||
@@ -322,6 +347,7 @@ export const DEFAULT_TRANBOX_SETTING = {
|
|||||||
tranboxShortcut: DEFAULT_TRANBOX_SHORTCUT,
|
tranboxShortcut: DEFAULT_TRANBOX_SHORTCUT,
|
||||||
btnOffsetX: 10,
|
btnOffsetX: 10,
|
||||||
btnOffsetY: 10,
|
btnOffsetY: 10,
|
||||||
|
hideTranBtn: false,
|
||||||
};
|
};
|
||||||
|
|
||||||
// 订阅列表
|
// 订阅列表
|
||||||
@@ -360,6 +386,10 @@ export const DEFAULT_TRANS_APIS = {
|
|||||||
model: "gpt-4",
|
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}.`,
|
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_CLOUDFLAREAI]: {
|
||||||
|
url: "https://api.cloudflare.com/client/v4/accounts/{ACCOUNT_ID}/ai/run/@cf/meta/m2m100-1.2b",
|
||||||
|
key: "",
|
||||||
|
},
|
||||||
[OPT_TRANS_CUSTOMIZE]: {
|
[OPT_TRANS_CUSTOMIZE]: {
|
||||||
url: "",
|
url: "",
|
||||||
key: "",
|
key: "",
|
||||||
@@ -375,12 +405,19 @@ export const DEFAULT_SHORTCUTS = {
|
|||||||
[OPT_SHORTCUT_TRANSLATE]: ["AltLeft", "KeyQ"],
|
[OPT_SHORTCUT_TRANSLATE]: ["AltLeft", "KeyQ"],
|
||||||
[OPT_SHORTCUT_STYLE]: ["AltLeft", "KeyC"],
|
[OPT_SHORTCUT_STYLE]: ["AltLeft", "KeyC"],
|
||||||
[OPT_SHORTCUT_POPUP]: ["AltLeft", "KeyK"],
|
[OPT_SHORTCUT_POPUP]: ["AltLeft", "KeyK"],
|
||||||
[OPT_SHORTCUT_SETTING]: ["AltLeft", "KeyN"],
|
[OPT_SHORTCUT_SETTING]: ["AltLeft", "KeyO"],
|
||||||
};
|
};
|
||||||
|
|
||||||
export const TRANS_MIN_LENGTH = 5; // 最短翻译长度
|
export const TRANS_MIN_LENGTH = 5; // 最短翻译长度
|
||||||
export const TRANS_MAX_LENGTH = 5000; // 最长翻译长度
|
export const TRANS_MAX_LENGTH = 5000; // 最长翻译长度
|
||||||
export const TRANS_NEWLINE_LENGTH = 20; // 换行字符数
|
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 = {
|
export const DEFAULT_SETTING = {
|
||||||
darkMode: false, // 深色模式
|
darkMode: false, // 深色模式
|
||||||
@@ -401,6 +438,9 @@ export const DEFAULT_SETTING = {
|
|||||||
shortcuts: DEFAULT_SHORTCUTS, // 快捷键
|
shortcuts: DEFAULT_SHORTCUTS, // 快捷键
|
||||||
inputRule: DEFAULT_INPUT_RULE, // 输入框设置
|
inputRule: DEFAULT_INPUT_RULE, // 输入框设置
|
||||||
tranboxSetting: DEFAULT_TRANBOX_SETTING, // 划词翻译设置
|
tranboxSetting: DEFAULT_TRANBOX_SETTING, // 划词翻译设置
|
||||||
|
touchTranslate: 2, // 触屏翻译
|
||||||
|
blacklist: DEFAULT_BLACKLIST.join(",\n"), // 禁用翻译名单
|
||||||
|
disableLangs: [], // 不翻译的语言
|
||||||
};
|
};
|
||||||
|
|
||||||
export const DEFAULT_RULES = [GLOBLA_RULE];
|
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(li, p, h1, h2, h3, h4, h5, h6, dd, blockquote)`;
|
||||||
|
|
||||||
export const DEFAULT_SELECTOR = `:is(${els})`;
|
|
||||||
|
|
||||||
export const GLOBAL_KEY = "*";
|
export const GLOBAL_KEY = "*";
|
||||||
export const REMAIN_KEY = "-";
|
export const REMAIN_KEY = "-";
|
||||||
@@ -42,145 +40,66 @@ export const DEFAULT_OW_RULE = {
|
|||||||
textDiyStyle: DEFAULT_DIY_STYLE,
|
textDiyStyle: DEFAULT_DIY_STYLE,
|
||||||
};
|
};
|
||||||
|
|
||||||
const RULES = [
|
const RULES_MAP = {
|
||||||
{
|
"www.google.com/search": `h3, .IsZvec, .VwiC3b`,
|
||||||
pattern: `www.google.com/search`,
|
"news.google.com": `[role="link"], .DY5T1d, .ifw3f, ${DEFAULT_SELECTOR}`,
|
||||||
selector: `h3, .IsZvec, .VwiC3b`,
|
"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}`,
|
||||||
pattern: `news.google.com`,
|
"www.telegraph.co.uk, go.dev/doc/": `article ${DEFAULT_SELECTOR}`,
|
||||||
selector: `h4`,
|
"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`,
|
||||||
pattern: `www.foxnews.com`,
|
"restofworld.org": `${DEFAULT_SELECTOR}, .recirc-story__headline, .recirc-story__dek`,
|
||||||
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"]`,
|
"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`,
|
||||||
pattern: `bearblog.dev, www.theverge.com, www.tampermonkey.net/documentation.php`,
|
"www.dw.com": `.ts-teaser-title a, .news-title a, .title a, .teaser-description a, .hbudab h3, .hbudab p, figcaption ,article ${DEFAULT_SELECTOR}`,
|
||||||
selector: 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"]`,
|
||||||
pattern: `themessenger.com`,
|
"www.reddit.com": `[slot="title"], [slot="text-body"] ${DEFAULT_SELECTOR}, #-post-rtjson-content p`,
|
||||||
selector: `.leading-tight, .leading-tighter, .my-2 p, .font-body p, article ${DEFAULT_SELECTOR}`,
|
"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}`,
|
||||||
pattern: `www.telegraph.co.uk`,
|
"www.bloomberg.com": `[data-component="headline"], [data-component="related-item-headline"], [data-component="title"], article ${DEFAULT_SELECTOR}`,
|
||||||
selector: `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`,
|
||||||
pattern: `www.theguardian.com`,
|
"platform.openai.com/docs": `.docs-body ${DEFAULT_SELECTOR}`,
|
||||||
selector: `.show-underline, .dcr-hup5wm div, .dcr-7vl6y8 div, .dcr-12evv1c, figcaption, article ${DEFAULT_SELECTOR}, [data-cy="mostviewed-footer"] h4`,
|
"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}`,
|
||||||
pattern: `www.semafor.com`,
|
"news.ycombinator.com": `.title, .commtext`,
|
||||||
selector: `${DEFAULT_SELECTOR}, .styles_intro__IYj__, [class*="styles_description"]`,
|
"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`,
|
||||||
pattern: `www.noemamag.com`,
|
"www.youtube.com": `h1, #video-title, #content-text, #title, yt-attributed-string>span>span, #ytp-caption-window-container .ytp-caption-segment`,
|
||||||
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`,
|
"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}`,
|
||||||
pattern: `restofworld.org`,
|
"wx2.qq.com": `.js_message_plain`,
|
||||||
selector: `${DEFAULT_SELECTOR}, .recirc-story__headline, .recirc-story__dek`,
|
"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}`,
|
||||||
pattern: `www.axios.com`,
|
"web.telegram.org/k/": `.message, .bot-commands-list-element-description, .reply-markup-button-text`,
|
||||||
selector: `.h7, ${DEFAULT_SELECTOR}`,
|
"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`,
|
||||||
pattern: `www.newyorker.com`,
|
"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']`,
|
||||||
selector: `.summary-item__hed, .summary-item__dek, .summary-collection-grid__dek, .dqtvfu, .rubric__link, .caption, article ${DEFAULT_SELECTOR}, .HEhan ${DEFAULT_SELECTOR}, .ContributorBioBio-fBolsO`,
|
"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}`,
|
||||||
pattern: `https://time.com/`,
|
"forum.ru-board.com": `.tit, .dats, span.post ${DEFAULT_SELECTOR}`,
|
||||||
selector: `h1, h3, .summary, .video-title, #article-body ${DEFAULT_SELECTOR}, .image-wrap-container .credit.body-caption, .media-heading`,
|
"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`,
|
||||||
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`,
|
|
||||||
},
|
|
||||||
];
|
|
||||||
|
|
||||||
export const BUILTIN_RULES = RULES.sort((a, b) =>
|
export const BUILTIN_RULES = Object.entries(RULES_MAP)
|
||||||
a.pattern.localeCompare(b.pattern)
|
.sort((a, b) => a[0].localeCompare(b[0]))
|
||||||
).map((item) => ({
|
.map(([pattern, selector]) => ({
|
||||||
...DEFAULT_RULE,
|
...DEFAULT_RULE,
|
||||||
...item,
|
pattern,
|
||||||
transOpen: "true",
|
selector,
|
||||||
}));
|
}));
|
||||||
|
|||||||
@@ -1,76 +1,3 @@
|
|||||||
import { browser } from "./libs/browser";
|
import { run } from "./common";
|
||||||
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";
|
|
||||||
|
|
||||||
function runtimeListener(translator) {
|
run();
|
||||||
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);
|
|
||||||
}
|
|
||||||
})();
|
|
||||||
|
|||||||
67
src/hooks/FavWords.js
Normal file
67
src/hooks/FavWords.js
Normal file
@@ -0,0 +1,67 @@
|
|||||||
|
import { KV_WORDS_KEY } from "../config";
|
||||||
|
import { useCallback, useEffect, useState } from "react";
|
||||||
|
import { trySyncWords } from "../libs/sync";
|
||||||
|
import { getWordsWithDefault, setWords } from "../libs/storage";
|
||||||
|
import { useSyncMeta } from "./Sync";
|
||||||
|
|
||||||
|
export function useFavWords() {
|
||||||
|
const [loading, setLoading] = useState(false);
|
||||||
|
const [favWords, setFavWords] = useState({});
|
||||||
|
const { updateSyncMeta } = useSyncMeta();
|
||||||
|
|
||||||
|
const toggleFav = useCallback(
|
||||||
|
async (word) => {
|
||||||
|
const favs = { ...favWords };
|
||||||
|
if (favs[word]) {
|
||||||
|
delete favs[word];
|
||||||
|
} else {
|
||||||
|
favs[word] = { createdAt: Date.now() };
|
||||||
|
}
|
||||||
|
await setWords(favs);
|
||||||
|
await updateSyncMeta(KV_WORDS_KEY);
|
||||||
|
await trySyncWords();
|
||||||
|
setFavWords(favs);
|
||||||
|
},
|
||||||
|
[updateSyncMeta, favWords]
|
||||||
|
);
|
||||||
|
|
||||||
|
const mergeWords = useCallback(
|
||||||
|
async (newWords) => {
|
||||||
|
const favs = { ...favWords };
|
||||||
|
newWords.forEach((word) => {
|
||||||
|
if (!favs[word]) {
|
||||||
|
favs[word] = { createdAt: Date.now() };
|
||||||
|
}
|
||||||
|
});
|
||||||
|
await setWords(favs);
|
||||||
|
await updateSyncMeta(KV_WORDS_KEY);
|
||||||
|
await trySyncWords();
|
||||||
|
setFavWords(favs);
|
||||||
|
},
|
||||||
|
[updateSyncMeta, favWords]
|
||||||
|
);
|
||||||
|
|
||||||
|
const clearWords = useCallback(async () => {
|
||||||
|
await setWords({});
|
||||||
|
await updateSyncMeta(KV_WORDS_KEY);
|
||||||
|
await trySyncWords();
|
||||||
|
setFavWords({});
|
||||||
|
}, [updateSyncMeta]);
|
||||||
|
|
||||||
|
useEffect(() => {
|
||||||
|
(async () => {
|
||||||
|
try {
|
||||||
|
setLoading(true);
|
||||||
|
await trySyncWords();
|
||||||
|
const favWords = await getWordsWithDefault();
|
||||||
|
setFavWords(favWords);
|
||||||
|
} catch (err) {
|
||||||
|
console.log("[query fav]", err);
|
||||||
|
} finally {
|
||||||
|
setLoading(false);
|
||||||
|
}
|
||||||
|
})();
|
||||||
|
}, []);
|
||||||
|
|
||||||
|
return { loading, favWords, toggleFav, mergeWords, clearWords };
|
||||||
|
}
|
||||||
@@ -1,6 +1,12 @@
|
|||||||
import { useCallback, useEffect, useState } from "react";
|
import { useCallback, useEffect, useState } from "react";
|
||||||
import { storage } from "../libs/storage";
|
import { storage } from "../libs/storage";
|
||||||
|
|
||||||
|
/**
|
||||||
|
*
|
||||||
|
* @param {*} key
|
||||||
|
* @param {*} defaultVal 需为调用hook外的常量
|
||||||
|
* @returns
|
||||||
|
*/
|
||||||
export function useStorage(key, defaultVal) {
|
export function useStorage(key, defaultVal) {
|
||||||
const [loading, setLoading] = useState(false);
|
const [loading, setLoading] = useState(false);
|
||||||
const [data, setData] = useState(null);
|
const [data, setData] = useState(null);
|
||||||
|
|||||||
@@ -12,10 +12,24 @@ import { THEME_DARK, THEME_LIGHT } from "../config";
|
|||||||
export default function Theme({ children, options }) {
|
export default function Theme({ children, options }) {
|
||||||
const { darkMode } = useDarkMode();
|
const { darkMode } = useDarkMode();
|
||||||
const theme = useMemo(() => {
|
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({
|
return createTheme({
|
||||||
palette: {
|
palette: {
|
||||||
mode: darkMode ? THEME_DARK : THEME_LIGHT,
|
mode: darkMode ? THEME_DARK : THEME_LIGHT,
|
||||||
},
|
},
|
||||||
|
typography: {
|
||||||
|
htmlFontSize,
|
||||||
|
},
|
||||||
...options,
|
...options,
|
||||||
});
|
});
|
||||||
}, [darkMode, options]);
|
}, [darkMode, options]);
|
||||||
|
|||||||
@@ -24,7 +24,11 @@ export function useTranslate(q, rule, setting) {
|
|||||||
setLoading(true);
|
setLoading(true);
|
||||||
|
|
||||||
const deLang = await tryDetectLang(q, setting.detectRemote);
|
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);
|
setSamelang(true);
|
||||||
} else {
|
} else {
|
||||||
const [trText, isSame] = await apiTranslate({
|
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);
|
[input, init] = await newTransReq(transOpts, apiSetting);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
if (!input) {
|
||||||
|
throw new Error("url is empty");
|
||||||
|
}
|
||||||
|
|
||||||
if (isGm) {
|
if (isGm) {
|
||||||
let info;
|
let info;
|
||||||
if (window.KISS_GM) {
|
if (window.KISS_GM) {
|
||||||
@@ -127,7 +131,13 @@ export const fetchData = async (
|
|||||||
}
|
}
|
||||||
|
|
||||||
if (!res?.ok) {
|
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()) {
|
if (isExt && !isBg()) {
|
||||||
const res = await sendBgMsg(MSG_FETCH, { input, opts });
|
const res = await sendBgMsg(MSG_FETCH, { input, opts });
|
||||||
if (res.error) {
|
if (res.error) {
|
||||||
throw new Error(res.error);
|
throw new Error(res.error, { cause: res.cause });
|
||||||
}
|
}
|
||||||
return res.data;
|
return res.data;
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -8,6 +8,7 @@ import {
|
|||||||
OPT_TRANS_BAIDU,
|
OPT_TRANS_BAIDU,
|
||||||
OPT_TRANS_TENCENT,
|
OPT_TRANS_TENCENT,
|
||||||
OPT_TRANS_OPENAI,
|
OPT_TRANS_OPENAI,
|
||||||
|
OPT_TRANS_CLOUDFLAREAI,
|
||||||
OPT_TRANS_CUSTOMIZE,
|
OPT_TRANS_CUSTOMIZE,
|
||||||
URL_MICROSOFT_TRAN,
|
URL_MICROSOFT_TRAN,
|
||||||
URL_TENCENT_TRANSMART,
|
URL_TENCENT_TRANSMART,
|
||||||
@@ -143,7 +144,7 @@ const genTencent = ({ text, from, to }) => {
|
|||||||
return [URL_TENCENT_TRANSMART, init];
|
return [URL_TENCENT_TRANSMART, init];
|
||||||
};
|
};
|
||||||
|
|
||||||
const genOpenai = ({ text, from, to, url, key, prompt, model }) => {
|
const genOpenAI = ({ text, from, to, url, key, prompt, model }) => {
|
||||||
prompt = prompt
|
prompt = prompt
|
||||||
.replaceAll(PROMPT_PLACE_FROM, from)
|
.replaceAll(PROMPT_PLACE_FROM, from)
|
||||||
.replaceAll(PROMPT_PLACE_TO, to);
|
.replaceAll(PROMPT_PLACE_TO, to);
|
||||||
@@ -177,6 +178,25 @@ const genOpenai = ({ text, from, to, url, key, prompt, model }) => {
|
|||||||
return [url, init];
|
return [url, init];
|
||||||
};
|
};
|
||||||
|
|
||||||
|
const genCloudflareAI = ({ text, from, to, url, key }) => {
|
||||||
|
const data = {
|
||||||
|
text,
|
||||||
|
source_lang: from,
|
||||||
|
target_lang: to,
|
||||||
|
};
|
||||||
|
|
||||||
|
const init = {
|
||||||
|
headers: {
|
||||||
|
"Content-type": "application/json",
|
||||||
|
Authorization: `Bearer ${key}`,
|
||||||
|
},
|
||||||
|
method: "POST",
|
||||||
|
body: JSON.stringify(data),
|
||||||
|
};
|
||||||
|
|
||||||
|
return [url, init];
|
||||||
|
};
|
||||||
|
|
||||||
const genCustom = ({ text, from, to, url, key }) => {
|
const genCustom = ({ text, from, to, url, key }) => {
|
||||||
const data = {
|
const data = {
|
||||||
text,
|
text,
|
||||||
@@ -197,6 +217,11 @@ const genCustom = ({ text, from, to, url, key }) => {
|
|||||||
return [url, init];
|
return [url, init];
|
||||||
};
|
};
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 构造翻译接口 request
|
||||||
|
* @param {*}
|
||||||
|
* @returns
|
||||||
|
*/
|
||||||
export const newTransReq = ({ translator, text, from, to }, apiSetting) => {
|
export const newTransReq = ({ translator, text, from, to }, apiSetting) => {
|
||||||
const args = { text, from, to, ...apiSetting };
|
const args = { text, from, to, ...apiSetting };
|
||||||
switch (translator) {
|
switch (translator) {
|
||||||
@@ -215,7 +240,9 @@ export const newTransReq = ({ translator, text, from, to }, apiSetting) => {
|
|||||||
case OPT_TRANS_TENCENT:
|
case OPT_TRANS_TENCENT:
|
||||||
return genTencent(args);
|
return genTencent(args);
|
||||||
case OPT_TRANS_OPENAI:
|
case OPT_TRANS_OPENAI:
|
||||||
return genOpenai(args);
|
return genOpenAI(args);
|
||||||
|
case OPT_TRANS_CLOUDFLAREAI:
|
||||||
|
return genCloudflareAI(args);
|
||||||
case OPT_TRANS_CUSTOMIZE:
|
case OPT_TRANS_CUSTOMIZE:
|
||||||
return genCustom(args);
|
return genCustom(args);
|
||||||
default:
|
default:
|
||||||
|
|||||||
@@ -21,7 +21,6 @@ import { trySyncRules } from "./sync";
|
|||||||
* @returns
|
* @returns
|
||||||
*/
|
*/
|
||||||
export const matchRule = async (
|
export const matchRule = async (
|
||||||
rules,
|
|
||||||
href,
|
href,
|
||||||
{
|
{
|
||||||
injectRules = true,
|
injectRules = true,
|
||||||
@@ -29,7 +28,7 @@ export const matchRule = async (
|
|||||||
owSubrule = DEFAULT_OW_RULE,
|
owSubrule = DEFAULT_OW_RULE,
|
||||||
}
|
}
|
||||||
) => {
|
) => {
|
||||||
rules = [...rules];
|
const rules = await getRulesWithDefault();
|
||||||
if (injectRules) {
|
if (injectRules) {
|
||||||
try {
|
try {
|
||||||
const selectedSub = subrulesList.find((item) => item.selected);
|
const selectedSub = subrulesList.find((item) => item.selected);
|
||||||
|
|||||||
@@ -1,6 +1,8 @@
|
|||||||
import {
|
import {
|
||||||
STOKEY_SETTING,
|
STOKEY_SETTING,
|
||||||
STOKEY_RULES,
|
STOKEY_RULES,
|
||||||
|
STOKEY_WFRULES,
|
||||||
|
STOKEY_WORDS,
|
||||||
STOKEY_FAB,
|
STOKEY_FAB,
|
||||||
STOKEY_SYNC,
|
STOKEY_SYNC,
|
||||||
STOKEY_MSAUTH,
|
STOKEY_MSAUTH,
|
||||||
@@ -97,6 +99,21 @@ export const getRulesWithDefault = async () =>
|
|||||||
(await getRules()) || DEFAULT_RULES;
|
(await getRules()) || DEFAULT_RULES;
|
||||||
export const setRules = (val) => setObj(STOKEY_RULES, val);
|
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);
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 词汇列表
|
||||||
|
*/
|
||||||
|
export const getWords = () => getObj(STOKEY_WORDS);
|
||||||
|
export const getWordsWithDefault = async () => (await getWords()) || {};
|
||||||
|
export const setWords = (val) => setObj(STOKEY_WORDS, val);
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* 订阅规则
|
* 订阅规则
|
||||||
*/
|
*/
|
||||||
|
|||||||
@@ -2,6 +2,8 @@ import {
|
|||||||
APP_LCNAME,
|
APP_LCNAME,
|
||||||
KV_SETTING_KEY,
|
KV_SETTING_KEY,
|
||||||
KV_RULES_KEY,
|
KV_RULES_KEY,
|
||||||
|
KV_WFRULES_KEY,
|
||||||
|
KV_WORDS_KEY,
|
||||||
KV_RULES_SHARE_KEY,
|
KV_RULES_SHARE_KEY,
|
||||||
KV_SALT_SHARE,
|
KV_SALT_SHARE,
|
||||||
OPT_SYNCTYPE_WEBDAV,
|
OPT_SYNCTYPE_WEBDAV,
|
||||||
@@ -11,8 +13,12 @@ import {
|
|||||||
updateSync,
|
updateSync,
|
||||||
getSettingWithDefault,
|
getSettingWithDefault,
|
||||||
getRulesWithDefault,
|
getRulesWithDefault,
|
||||||
|
getWordsWithDefault,
|
||||||
|
getWebfixRulesWithDefault,
|
||||||
setSetting,
|
setSetting,
|
||||||
setRules,
|
setRules,
|
||||||
|
setWebfixRules,
|
||||||
|
setWords,
|
||||||
} from "./storage";
|
} from "./storage";
|
||||||
import { apiSyncData } from "../apis";
|
import { apiSyncData } from "../apis";
|
||||||
import { sha256, removeEndchar } from "./utils";
|
import { sha256, removeEndchar } from "./utils";
|
||||||
@@ -135,6 +141,44 @@ 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
|
||||||
|
*/
|
||||||
|
const syncWords = async () => {
|
||||||
|
const res = await syncData(KV_WORDS_KEY, getWordsWithDefault);
|
||||||
|
if (res?.isNew) {
|
||||||
|
await setWords(res.value);
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
export const trySyncWords = async () => {
|
||||||
|
try {
|
||||||
|
await syncWords();
|
||||||
|
} catch (err) {
|
||||||
|
console.log("[sync fav words]", err);
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* 同步分享规则
|
* 同步分享规则
|
||||||
* @param {*} param0
|
* @param {*} param0
|
||||||
@@ -163,9 +207,13 @@ export const syncShareRules = async ({ rules, syncUrl, syncKey }) => {
|
|||||||
export const syncSettingAndRules = async () => {
|
export const syncSettingAndRules = async () => {
|
||||||
await syncSetting();
|
await syncSetting();
|
||||||
await syncRules();
|
await syncRules();
|
||||||
|
await syncWebfixRules();
|
||||||
|
await syncWords();
|
||||||
};
|
};
|
||||||
|
|
||||||
export const trySyncSettingAndRules = async () => {
|
export const trySyncSettingAndRules = async () => {
|
||||||
await trySyncSetting();
|
await trySyncSetting();
|
||||||
await trySyncRules();
|
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);
|
||||||
|
};
|
||||||
|
}
|
||||||
@@ -349,8 +349,8 @@ export class Translator {
|
|||||||
// 监听鼠标悬停
|
// 监听鼠标悬停
|
||||||
window.addEventListener("keydown", this._handleKeydown);
|
window.addEventListener("keydown", this._handleKeydown);
|
||||||
this._tranNodes.forEach((_, node) => {
|
this._tranNodes.forEach((_, node) => {
|
||||||
node.addEventListener("mouseover", this._handleMouseover);
|
node.addEventListener("mouseenter", this._handleMouseover);
|
||||||
node.addEventListener("mouseout", this._handleMouseout);
|
node.addEventListener("mouseleave", this._handleMouseout);
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
};
|
};
|
||||||
@@ -475,15 +475,15 @@ export class Translator {
|
|||||||
};
|
};
|
||||||
|
|
||||||
_handleMouseover = (e) => {
|
_handleMouseover = (e) => {
|
||||||
// console.log("mouseover", e);
|
// console.log("mouseenter", e);
|
||||||
if (!this._tranNodes.has(e.target)) {
|
if (!this._tranNodes.has(e.target)) {
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
const key = this._setting.mouseKey.slice(3);
|
const key = this._setting.mouseKey.slice(3);
|
||||||
if (this._setting.mouseKey === OPT_MOUSEKEY_MOUSEOVER || e[key]) {
|
if (this._setting.mouseKey === OPT_MOUSEKEY_MOUSEOVER || e[key]) {
|
||||||
e.target.removeEventListener("mouseover", this._handleMouseover);
|
e.target.removeEventListener("mouseenter", this._handleMouseover);
|
||||||
e.target.removeEventListener("mouseout", this._handleMouseout);
|
e.target.removeEventListener("mouseleave", this._handleMouseout);
|
||||||
this._render(e.target);
|
this._render(e.target);
|
||||||
} else {
|
} else {
|
||||||
this._mouseoverNode = e.target;
|
this._mouseoverNode = e.target;
|
||||||
@@ -491,7 +491,7 @@ export class Translator {
|
|||||||
};
|
};
|
||||||
|
|
||||||
_handleMouseout = (e) => {
|
_handleMouseout = (e) => {
|
||||||
// console.log("mouseout", e);
|
// console.log("mouseleave", e);
|
||||||
if (!this._tranNodes.has(e.target)) {
|
if (!this._tranNodes.has(e.target)) {
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
@@ -504,10 +504,13 @@ export class Translator {
|
|||||||
const key = this._setting.mouseKey.slice(3);
|
const key = this._setting.mouseKey.slice(3);
|
||||||
if (e[key] && this._mouseoverNode) {
|
if (e[key] && this._mouseoverNode) {
|
||||||
this._mouseoverNode.removeEventListener(
|
this._mouseoverNode.removeEventListener(
|
||||||
"mouseover",
|
"mouseenter",
|
||||||
this._handleMouseover
|
this._handleMouseover
|
||||||
);
|
);
|
||||||
this._mouseoverNode.removeEventListener("mouseout", this._handleMouseout);
|
this._mouseoverNode.removeEventListener(
|
||||||
|
"mouseleave",
|
||||||
|
this._handleMouseout
|
||||||
|
);
|
||||||
|
|
||||||
const node = this._mouseoverNode;
|
const node = this._mouseoverNode;
|
||||||
this._render(node);
|
this._render(node);
|
||||||
@@ -536,8 +539,9 @@ export class Translator {
|
|||||||
// 移除鼠标悬停监听
|
// 移除鼠标悬停监听
|
||||||
window.removeEventListener("keydown", this._handleKeydown);
|
window.removeEventListener("keydown", this._handleKeydown);
|
||||||
this._tranNodes.forEach((_, node) => {
|
this._tranNodes.forEach((_, node) => {
|
||||||
node.removeEventListener("mouseover", this._handleMouseover);
|
// node.style.pointerEvents = "none";
|
||||||
node.removeEventListener("mouseout", this._handleMouseout);
|
node.removeEventListener("mouseenter", this._handleMouseover);
|
||||||
|
node.removeEventListener("mouseleave", this._handleMouseout);
|
||||||
// 移除已插入元素
|
// 移除已插入元素
|
||||||
node.querySelector(APP_LCNAME)?.remove();
|
node.querySelector(APP_LCNAME)?.remove();
|
||||||
});
|
});
|
||||||
|
|||||||
@@ -1,5 +1,5 @@
|
|||||||
import { isMatch } from "./utils";
|
import { isMatch } from "./utils";
|
||||||
import { getWebfix, setWebfix } from "./storage";
|
import { getWebfix, setWebfix, getWebfixRulesWithDefault } from "./storage";
|
||||||
import { apiFetch } from "../apis";
|
import { apiFetch } from "../apis";
|
||||||
|
|
||||||
/**
|
/**
|
||||||
@@ -7,7 +7,16 @@ import { apiFetch } from "../apis";
|
|||||||
*/
|
*/
|
||||||
const FIXER_BR = "br";
|
const FIXER_BR = "br";
|
||||||
const FIXER_BN = "bn";
|
const FIXER_BN = "bn";
|
||||||
|
const FIXER_BR_DIV = "brToDiv";
|
||||||
|
const FIXER_BN_DIV = "bnToDiv";
|
||||||
const FIXER_FONTSIZE = "fontSize";
|
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
|
* @param {*} node
|
||||||
* @returns
|
* @returns
|
||||||
*/
|
*/
|
||||||
function brFixer(node) {
|
function brFixer(node, tag = "p") {
|
||||||
if (node.hasAttribute(fixedSign)) {
|
if (node.hasAttribute(fixedSign)) {
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
@@ -81,13 +90,13 @@ function brFixer(node) {
|
|||||||
var html = "";
|
var html = "";
|
||||||
node.childNodes.forEach(function (child, index) {
|
node.childNodes.forEach(function (child, index) {
|
||||||
if (index === 0) {
|
if (index === 0) {
|
||||||
html += "<p>";
|
html += `<${tag} class="kiss-p">`;
|
||||||
}
|
}
|
||||||
|
|
||||||
if (gapTags.indexOf(child.nodeName) !== -1) {
|
if (gapTags.indexOf(child.nodeName) !== -1) {
|
||||||
html += "</p><p>";
|
html += `</${tag}><${tag} class="kiss-p">`;
|
||||||
} else if (newlineTags.indexOf(child.nodeName) !== -1) {
|
} else if (newlineTags.indexOf(child.nodeName) !== -1) {
|
||||||
html += "</p>" + child.outerHTML + "<p>";
|
html += `</${tag}>${child.outerHTML}<${tag} class="kiss-p">`;
|
||||||
} else if (child.outerHTML) {
|
} else if (child.outerHTML) {
|
||||||
html += child.outerHTML;
|
html += child.outerHTML;
|
||||||
} else if (child.nodeValue) {
|
} else if (child.nodeValue) {
|
||||||
@@ -95,30 +104,34 @@ function brFixer(node) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
if (index === node.childNodes.length - 1) {
|
if (index === node.childNodes.length - 1) {
|
||||||
html += "</p>";
|
html += `</${tag}>`;
|
||||||
}
|
}
|
||||||
});
|
});
|
||||||
node.innerHTML = html;
|
node.innerHTML = html;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
function brDivFixer(node) {
|
||||||
|
return brFixer(node, "div");
|
||||||
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* 目标是将 `\n` 替换成 `p`
|
* 目标是将 `\n` 替换成 `p`
|
||||||
* @param {*} node
|
* @param {*} node
|
||||||
* @returns
|
* @returns
|
||||||
*/
|
*/
|
||||||
function bnFixer(node) {
|
function bnFixer(node, tag = "p") {
|
||||||
if (node.hasAttribute(fixedSign)) {
|
if (node.hasAttribute(fixedSign)) {
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
node.setAttribute(fixedSign, "true");
|
node.setAttribute(fixedSign, "true");
|
||||||
|
node.innerHTML = node.innerHTML
|
||||||
|
.split("\n")
|
||||||
|
.map((item) => `<${tag} class="kiss-p">${item || " "}</${tag}>`)
|
||||||
|
.join("");
|
||||||
|
}
|
||||||
|
|
||||||
const childs = node.childNodes;
|
function bnDivFixer(node) {
|
||||||
if (childs.length === 1 && childs[0].nodeName === "#text") {
|
return bnFixer(node, "div");
|
||||||
node.innerHTML = node.innerHTML
|
|
||||||
.split("\n")
|
|
||||||
.map((item) => `<p>${item || " "}</p>`)
|
|
||||||
.join("");
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
@@ -135,6 +148,8 @@ function fontSizeFixer(node) {
|
|||||||
const fixerMap = {
|
const fixerMap = {
|
||||||
[FIXER_BR]: brFixer,
|
[FIXER_BR]: brFixer,
|
||||||
[FIXER_BN]: bnFixer,
|
[FIXER_BN]: bnFixer,
|
||||||
|
[FIXER_BR_DIV]: brDivFixer,
|
||||||
|
[FIXER_BN_DIV]: bnDivFixer,
|
||||||
[FIXER_FONTSIZE]: fontSizeFixer,
|
[FIXER_FONTSIZE]: fontSizeFixer,
|
||||||
};
|
};
|
||||||
|
|
||||||
@@ -148,7 +163,11 @@ function run(selector, fixer, rootSelector) {
|
|||||||
var mutaObserver = new MutationObserver(function (mutations) {
|
var mutaObserver = new MutationObserver(function (mutations) {
|
||||||
mutations.forEach(function (mutation) {
|
mutations.forEach(function (mutation) {
|
||||||
mutation.addedNodes.forEach(function (addNode) {
|
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) {
|
rootNodes.forEach(function (rootNode) {
|
||||||
rootNode.querySelectorAll(selector).forEach(fixer);
|
rootNode.querySelectorAll(selector).forEach(function (node) {
|
||||||
|
fixer(node);
|
||||||
|
});
|
||||||
mutaObserver.observe(rootNode, {
|
mutaObserver.observe(rootNode, {
|
||||||
childList: true,
|
childList: true,
|
||||||
subtree: true,
|
subtree: true,
|
||||||
@@ -206,7 +227,9 @@ export async function runWebfix({ injectWebfix }) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
const href = document.location.href;
|
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++) {
|
for (var i = 0; i < sites.length; i++) {
|
||||||
var site = sites[i];
|
var site = sites[i];
|
||||||
if (isMatch(href, site.pattern)) {
|
if (isMatch(href, site.pattern)) {
|
||||||
|
|||||||
@@ -1,77 +1,3 @@
|
|||||||
import { getSettingWithDefault } from "./libs/storage";
|
import { run } from "./common";
|
||||||
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";
|
|
||||||
|
|
||||||
function runSettingPage() {
|
run(true);
|
||||||
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);
|
|
||||||
}
|
|
||||||
})();
|
|
||||||
|
|||||||
@@ -7,6 +7,7 @@ import {
|
|||||||
OPT_STYLE_WAVYLINE,
|
OPT_STYLE_WAVYLINE,
|
||||||
OPT_STYLE_FUZZY,
|
OPT_STYLE_FUZZY,
|
||||||
OPT_STYLE_HIGHLIGHT,
|
OPT_STYLE_HIGHLIGHT,
|
||||||
|
OPT_STYLE_BLOCKQUOTE,
|
||||||
OPT_STYLE_DIY,
|
OPT_STYLE_DIY,
|
||||||
DEFAULT_COLOR,
|
DEFAULT_COLOR,
|
||||||
MSG_TRANS_CURRULE,
|
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")`
|
const FuzzySpan = styled("span")`
|
||||||
filter: blur(0.2em);
|
filter: blur(0.2em);
|
||||||
-webkit-filter: blur(0.2em);
|
-webkit-filter: blur(0.2em);
|
||||||
@@ -86,6 +99,12 @@ function StyledSpan({ textStyle, textDiyStyle, bgColor, children }) {
|
|||||||
{children}
|
{children}
|
||||||
</HighlightSpan>
|
</HighlightSpan>
|
||||||
);
|
);
|
||||||
|
case OPT_STYLE_BLOCKQUOTE: // 引用
|
||||||
|
return (
|
||||||
|
<BlockquoteSpan $lineColor={bgColor || DEFAULT_COLOR}>
|
||||||
|
{children}
|
||||||
|
</BlockquoteSpan>
|
||||||
|
);
|
||||||
case OPT_STYLE_DIY: // 自定义
|
case OPT_STYLE_DIY: // 自定义
|
||||||
return <DiySpan $diyStyle={textDiyStyle}>{children}</DiySpan>;
|
return <DiySpan $diyStyle={textDiyStyle}>{children}</DiySpan>;
|
||||||
default:
|
default:
|
||||||
|
|||||||
@@ -46,7 +46,20 @@ function TestButton({ translator, api }) {
|
|||||||
}
|
}
|
||||||
alert.success(i18n("test_success"));
|
alert.success(i18n("test_success"));
|
||||||
} catch (err) {
|
} 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 {
|
} finally {
|
||||||
setLoading(false);
|
setLoading(false);
|
||||||
}
|
}
|
||||||
|
|||||||
27
src/views/Options/DownloadButton.js
Normal file
27
src/views/Options/DownloadButton.js
Normal file
@@ -0,0 +1,27 @@
|
|||||||
|
import FileDownloadIcon from "@mui/icons-material/FileDownload";
|
||||||
|
import Button from "@mui/material/Button";
|
||||||
|
|
||||||
|
export default function DownloadButton({ data, text, fileName }) {
|
||||||
|
const handleClick = (e) => {
|
||||||
|
e.preventDefault();
|
||||||
|
if (data) {
|
||||||
|
const url = window.URL.createObjectURL(new Blob([data]));
|
||||||
|
const link = document.createElement("a");
|
||||||
|
link.href = url;
|
||||||
|
link.setAttribute("download", fileName || `${Date.now()}.json`);
|
||||||
|
document.body.appendChild(link);
|
||||||
|
link.click();
|
||||||
|
link.remove();
|
||||||
|
}
|
||||||
|
};
|
||||||
|
return (
|
||||||
|
<Button
|
||||||
|
size="small"
|
||||||
|
variant="outlined"
|
||||||
|
onClick={handleClick}
|
||||||
|
startIcon={<FileDownloadIcon />}
|
||||||
|
>
|
||||||
|
{text}
|
||||||
|
</Button>
|
||||||
|
);
|
||||||
|
}
|
||||||
150
src/views/Options/FavWords.js
Normal file
150
src/views/Options/FavWords.js
Normal file
@@ -0,0 +1,150 @@
|
|||||||
|
import Stack from "@mui/material/Stack";
|
||||||
|
import { OPT_TRANS_BAIDU } from "../../config";
|
||||||
|
import { useEffect, useState } from "react";
|
||||||
|
import Typography from "@mui/material/Typography";
|
||||||
|
import Accordion from "@mui/material/Accordion";
|
||||||
|
import AccordionSummary from "@mui/material/AccordionSummary";
|
||||||
|
import AccordionDetails from "@mui/material/AccordionDetails";
|
||||||
|
import ExpandMoreIcon from "@mui/icons-material/ExpandMore";
|
||||||
|
import CircularProgress from "@mui/material/CircularProgress";
|
||||||
|
import { useI18n } from "../../hooks/I18n";
|
||||||
|
import Alert from "@mui/material/Alert";
|
||||||
|
import { apiTranslate } from "../../apis";
|
||||||
|
import Box from "@mui/material/Box";
|
||||||
|
import { useFavWords } from "../../hooks/FavWords";
|
||||||
|
import DictCont from "../Selection/DictCont";
|
||||||
|
import DownloadButton from "./DownloadButton";
|
||||||
|
import UploadButton from "./UploadButton";
|
||||||
|
import Button from "@mui/material/Button";
|
||||||
|
import ClearAllIcon from "@mui/icons-material/ClearAll";
|
||||||
|
import { isValidWord } from "../../libs/utils";
|
||||||
|
|
||||||
|
function DictField({ word }) {
|
||||||
|
const [dictResult, setDictResult] = useState(null);
|
||||||
|
const [loading, setLoading] = useState(false);
|
||||||
|
const [error, setError] = useState("");
|
||||||
|
|
||||||
|
useEffect(() => {
|
||||||
|
(async () => {
|
||||||
|
try {
|
||||||
|
setLoading(true);
|
||||||
|
setError("");
|
||||||
|
const dictRes = await apiTranslate({
|
||||||
|
text: word,
|
||||||
|
translator: OPT_TRANS_BAIDU,
|
||||||
|
fromLang: "en",
|
||||||
|
toLang: "zh-CN",
|
||||||
|
});
|
||||||
|
setDictResult(dictRes[2].dict_result);
|
||||||
|
} catch (err) {
|
||||||
|
setError(err.message);
|
||||||
|
} finally {
|
||||||
|
setLoading(false);
|
||||||
|
}
|
||||||
|
})();
|
||||||
|
}, [word]);
|
||||||
|
|
||||||
|
if (loading) {
|
||||||
|
return <CircularProgress size={24} />;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (error) {
|
||||||
|
return <Alert severity="error">{error}</Alert>;
|
||||||
|
}
|
||||||
|
|
||||||
|
return <DictCont dictResult={dictResult} />;
|
||||||
|
}
|
||||||
|
|
||||||
|
function FavAccordion({ word, index }) {
|
||||||
|
const [expanded, setExpanded] = useState(false);
|
||||||
|
|
||||||
|
const handleChange = (e) => {
|
||||||
|
setExpanded((pre) => !pre);
|
||||||
|
};
|
||||||
|
|
||||||
|
return (
|
||||||
|
<Accordion expanded={expanded} onChange={handleChange}>
|
||||||
|
<AccordionSummary expandIcon={<ExpandMoreIcon />}>
|
||||||
|
{/* <Typography>{`[${new Date(
|
||||||
|
createdAt
|
||||||
|
).toLocaleString()}] ${word}`}</Typography> */}
|
||||||
|
<Typography>{`${index + 1}. ${word}`}</Typography>
|
||||||
|
</AccordionSummary>
|
||||||
|
<AccordionDetails>
|
||||||
|
{expanded && <DictField word={word} />}
|
||||||
|
</AccordionDetails>
|
||||||
|
</Accordion>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
export default function FavWords() {
|
||||||
|
const i18n = useI18n();
|
||||||
|
const { loading, favWords, mergeWords, clearWords } = useFavWords();
|
||||||
|
const favList = Object.entries(favWords).sort((a, b) =>
|
||||||
|
a[0].localeCompare(b[0])
|
||||||
|
);
|
||||||
|
const downloadList = favList.map(([word]) => word);
|
||||||
|
|
||||||
|
const handleImport = async (data) => {
|
||||||
|
try {
|
||||||
|
const newWords = data
|
||||||
|
.split("\n")
|
||||||
|
.map((line) => line.split(",")[0].trim())
|
||||||
|
.filter(isValidWord);
|
||||||
|
await mergeWords(newWords);
|
||||||
|
} catch (err) {
|
||||||
|
console.log("[import rules]", err);
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
return (
|
||||||
|
<Box>
|
||||||
|
<Stack spacing={3}>
|
||||||
|
<Stack
|
||||||
|
direction="row"
|
||||||
|
alignItems="center"
|
||||||
|
spacing={2}
|
||||||
|
useFlexGap
|
||||||
|
flexWrap="wrap"
|
||||||
|
>
|
||||||
|
<UploadButton
|
||||||
|
text={i18n("import")}
|
||||||
|
handleImport={handleImport}
|
||||||
|
fileType="text"
|
||||||
|
fileExts={[".txt", ".csv"]}
|
||||||
|
/>
|
||||||
|
<DownloadButton
|
||||||
|
data={downloadList.join("\n")}
|
||||||
|
text={i18n("export")}
|
||||||
|
fileName={`kiss-words_${Date.now()}.txt`}
|
||||||
|
/>
|
||||||
|
<Button
|
||||||
|
size="small"
|
||||||
|
variant="outlined"
|
||||||
|
onClick={() => {
|
||||||
|
clearWords();
|
||||||
|
}}
|
||||||
|
startIcon={<ClearAllIcon />}
|
||||||
|
>
|
||||||
|
{i18n("clear_all")}
|
||||||
|
</Button>
|
||||||
|
</Stack>
|
||||||
|
|
||||||
|
<Box>
|
||||||
|
{loading ? (
|
||||||
|
<CircularProgress size={24} />
|
||||||
|
) : (
|
||||||
|
favList.map(([word, { createdAt }], index) => (
|
||||||
|
<FavAccordion
|
||||||
|
key={word}
|
||||||
|
index={index}
|
||||||
|
word={word}
|
||||||
|
createdAt={createdAt}
|
||||||
|
/>
|
||||||
|
))
|
||||||
|
)}
|
||||||
|
</Box>
|
||||||
|
</Stack>
|
||||||
|
</Box>
|
||||||
|
);
|
||||||
|
}
|
||||||
@@ -6,6 +6,7 @@ import Box from "@mui/material/Box";
|
|||||||
import Link from "@mui/material/Link";
|
import Link from "@mui/material/Link";
|
||||||
import { useI18n } from "../../hooks/I18n";
|
import { useI18n } from "../../hooks/I18n";
|
||||||
import DarkModeButton from "./DarkModeButton";
|
import DarkModeButton from "./DarkModeButton";
|
||||||
|
import Typography from "@mui/material/Typography";
|
||||||
|
|
||||||
function Header(props) {
|
function Header(props) {
|
||||||
const i18n = useI18n();
|
const i18n = useI18n();
|
||||||
@@ -30,14 +31,14 @@ function Header(props) {
|
|||||||
<MenuIcon />
|
<MenuIcon />
|
||||||
</IconButton>
|
</IconButton>
|
||||||
</Box>
|
</Box>
|
||||||
<Box sx={{ flexGrow: 1 }}>
|
<Typography component="div" sx={{ flexGrow: 1, fontWeight: "bold" }}>
|
||||||
<Link
|
<Link
|
||||||
underline="none"
|
underline="none"
|
||||||
color="inherit"
|
color="inherit"
|
||||||
href={process.env.REACT_APP_HOMEPAGE}
|
href={process.env.REACT_APP_HOMEPAGE}
|
||||||
target="_blank"
|
target="_blank"
|
||||||
>{`${i18n("app_name")} v${process.env.REACT_APP_VERSION}`}</Link>
|
>{`${i18n("app_name")} v${process.env.REACT_APP_VERSION}`}</Link>
|
||||||
</Box>
|
</Typography>
|
||||||
<DarkModeButton />
|
<DarkModeButton />
|
||||||
</Toolbar>
|
</Toolbar>
|
||||||
</AppBar>
|
</AppBar>
|
||||||
|
|||||||
@@ -67,7 +67,7 @@ export default function InputSetting() {
|
|||||||
}}
|
}}
|
||||||
/>
|
/>
|
||||||
}
|
}
|
||||||
label={i18n("input_box_translation")}
|
label={i18n("use_input_box_translation")}
|
||||||
/>
|
/>
|
||||||
|
|
||||||
<TextField
|
<TextField
|
||||||
|
|||||||
@@ -13,7 +13,8 @@ import SyncIcon from "@mui/icons-material/Sync";
|
|||||||
import ApiIcon from "@mui/icons-material/Api";
|
import ApiIcon from "@mui/icons-material/Api";
|
||||||
import SendTimeExtensionIcon from "@mui/icons-material/SendTimeExtension";
|
import SendTimeExtensionIcon from "@mui/icons-material/SendTimeExtension";
|
||||||
import InputIcon from "@mui/icons-material/Input";
|
import InputIcon from "@mui/icons-material/Input";
|
||||||
import TranslateIcon from '@mui/icons-material/Translate';
|
import SelectAllIcon from "@mui/icons-material/SelectAll";
|
||||||
|
import EventNoteIcon from "@mui/icons-material/EventNote";
|
||||||
|
|
||||||
function LinkItem({ label, url, icon }) {
|
function LinkItem({ label, url, icon }) {
|
||||||
const match = useMatch(url);
|
const match = useMatch(url);
|
||||||
@@ -41,8 +42,8 @@ export default function Navigator(props) {
|
|||||||
icon: <DesignServicesIcon />,
|
icon: <DesignServicesIcon />,
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
id: "input_setting",
|
id: "input_translate",
|
||||||
label: i18n("input_setting"),
|
label: i18n("input_translate"),
|
||||||
url: "/input",
|
url: "/input",
|
||||||
icon: <InputIcon />,
|
icon: <InputIcon />,
|
||||||
},
|
},
|
||||||
@@ -50,7 +51,7 @@ export default function Navigator(props) {
|
|||||||
id: "selection_translate",
|
id: "selection_translate",
|
||||||
label: i18n("selection_translate"),
|
label: i18n("selection_translate"),
|
||||||
url: "/tranbox",
|
url: "/tranbox",
|
||||||
icon: <TranslateIcon />,
|
icon: <SelectAllIcon />,
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
id: "apis_setting",
|
id: "apis_setting",
|
||||||
@@ -70,6 +71,12 @@ export default function Navigator(props) {
|
|||||||
url: "/webfix",
|
url: "/webfix",
|
||||||
icon: <SendTimeExtensionIcon />,
|
icon: <SendTimeExtensionIcon />,
|
||||||
},
|
},
|
||||||
|
{
|
||||||
|
id: "words",
|
||||||
|
label: i18n("favorite_words"),
|
||||||
|
url: "/words",
|
||||||
|
icon: <EventNoteIcon />,
|
||||||
|
},
|
||||||
{ id: "about", label: i18n("about"), url: "/about", icon: <InfoIcon /> },
|
{ id: "about", label: i18n("about"), url: "/about", icon: <InfoIcon /> },
|
||||||
];
|
];
|
||||||
return (
|
return (
|
||||||
|
|||||||
@@ -16,7 +16,7 @@ import {
|
|||||||
URL_KISS_RULES_NEW_ISSUE,
|
URL_KISS_RULES_NEW_ISSUE,
|
||||||
OPT_SYNCTYPE_WORKER,
|
OPT_SYNCTYPE_WORKER,
|
||||||
} from "../../config";
|
} from "../../config";
|
||||||
import { useState, useRef, useEffect, useMemo } from "react";
|
import { useState, useEffect, useMemo } from "react";
|
||||||
import { useI18n } from "../../hooks/I18n";
|
import { useI18n } from "../../hooks/I18n";
|
||||||
import Typography from "@mui/material/Typography";
|
import Typography from "@mui/material/Typography";
|
||||||
import Accordion from "@mui/material/Accordion";
|
import Accordion from "@mui/material/Accordion";
|
||||||
@@ -26,8 +26,6 @@ import ExpandMoreIcon from "@mui/icons-material/ExpandMore";
|
|||||||
import { useRules } from "../../hooks/Rules";
|
import { useRules } from "../../hooks/Rules";
|
||||||
import MenuItem from "@mui/material/MenuItem";
|
import MenuItem from "@mui/material/MenuItem";
|
||||||
import Grid from "@mui/material/Grid";
|
import Grid from "@mui/material/Grid";
|
||||||
import FileDownloadIcon from "@mui/icons-material/FileDownload";
|
|
||||||
import FileUploadIcon from "@mui/icons-material/FileUpload";
|
|
||||||
import { useSetting } from "../../hooks/Setting";
|
import { useSetting } from "../../hooks/Setting";
|
||||||
import FormControlLabel from "@mui/material/FormControlLabel";
|
import FormControlLabel from "@mui/material/FormControlLabel";
|
||||||
import Switch from "@mui/material/Switch";
|
import Switch from "@mui/material/Switch";
|
||||||
@@ -50,6 +48,8 @@ import OwSubRule from "./OwSubRule";
|
|||||||
import ClearAllIcon from "@mui/icons-material/ClearAll";
|
import ClearAllIcon from "@mui/icons-material/ClearAll";
|
||||||
import HelpButton from "./HelpButton";
|
import HelpButton from "./HelpButton";
|
||||||
import { useSyncCaches } from "../../hooks/Sync";
|
import { useSyncCaches } from "../../hooks/Sync";
|
||||||
|
import DownloadButton from "./DownloadButton";
|
||||||
|
import UploadButton from "./UploadButton";
|
||||||
|
|
||||||
function RuleFields({ rule, rules, setShow, setKeyword }) {
|
function RuleFields({ rule, rules, setShow, setKeyword }) {
|
||||||
const initFormValues = rule || {
|
const initFormValues = rule || {
|
||||||
@@ -375,8 +375,9 @@ function RuleAccordion({ rule, rules }) {
|
|||||||
<Accordion expanded={expanded} onChange={handleChange}>
|
<Accordion expanded={expanded} onChange={handleChange}>
|
||||||
<AccordionSummary expandIcon={<ExpandMoreIcon />}>
|
<AccordionSummary expandIcon={<ExpandMoreIcon />}>
|
||||||
<Typography
|
<Typography
|
||||||
style={{
|
sx={{
|
||||||
opacity: rules ? 1 : 0.5,
|
opacity: rules ? 1 : 0.5,
|
||||||
|
overflowWrap: "anywhere",
|
||||||
}}
|
}}
|
||||||
>
|
>
|
||||||
{rule.pattern === GLOBAL_KEY
|
{rule.pattern === GLOBAL_KEY
|
||||||
@@ -391,56 +392,6 @@ function RuleAccordion({ rule, rules }) {
|
|||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
function DownloadButton({ data, text, fileName }) {
|
|
||||||
const handleClick = (e) => {
|
|
||||||
e.preventDefault();
|
|
||||||
if (data) {
|
|
||||||
const url = window.URL.createObjectURL(new Blob([data]));
|
|
||||||
const link = document.createElement("a");
|
|
||||||
link.href = url;
|
|
||||||
link.setAttribute("download", fileName || `${Date.now()}.json`);
|
|
||||||
document.body.appendChild(link);
|
|
||||||
link.click();
|
|
||||||
link.remove();
|
|
||||||
}
|
|
||||||
};
|
|
||||||
return (
|
|
||||||
<Button
|
|
||||||
size="small"
|
|
||||||
variant="outlined"
|
|
||||||
onClick={handleClick}
|
|
||||||
startIcon={<FileDownloadIcon />}
|
|
||||||
>
|
|
||||||
{text}
|
|
||||||
</Button>
|
|
||||||
);
|
|
||||||
}
|
|
||||||
|
|
||||||
function UploadButton({ onChange, text }) {
|
|
||||||
const inputRef = useRef(null);
|
|
||||||
const handleClick = () => {
|
|
||||||
inputRef.current && inputRef.current.click();
|
|
||||||
};
|
|
||||||
|
|
||||||
return (
|
|
||||||
<Button
|
|
||||||
size="small"
|
|
||||||
variant="outlined"
|
|
||||||
onClick={handleClick}
|
|
||||||
startIcon={<FileUploadIcon />}
|
|
||||||
>
|
|
||||||
{text}
|
|
||||||
<input
|
|
||||||
type="file"
|
|
||||||
accept=".json"
|
|
||||||
ref={inputRef}
|
|
||||||
onChange={onChange}
|
|
||||||
hidden
|
|
||||||
/>
|
|
||||||
</Button>
|
|
||||||
);
|
|
||||||
}
|
|
||||||
|
|
||||||
function ShareButton({ rules, injectRules, selectedUrl }) {
|
function ShareButton({ rules, injectRules, selectedUrl }) {
|
||||||
const alert = useAlert();
|
const alert = useAlert();
|
||||||
const i18n = useI18n();
|
const i18n = useI18n();
|
||||||
@@ -493,26 +444,12 @@ function UserRules({ subRules }) {
|
|||||||
const injectRules = !!setting?.injectRules;
|
const injectRules = !!setting?.injectRules;
|
||||||
const { selectedUrl, selectedRules } = subRules;
|
const { selectedUrl, selectedRules } = subRules;
|
||||||
|
|
||||||
const handleImport = (e) => {
|
const handleImport = async (data) => {
|
||||||
const file = e.target.files[0];
|
try {
|
||||||
if (!file) {
|
await rules.merge(JSON.parse(data));
|
||||||
return;
|
} catch (err) {
|
||||||
|
console.log("[import rules]", err);
|
||||||
}
|
}
|
||||||
|
|
||||||
if (!file.type.includes("json")) {
|
|
||||||
alert(i18n("error_wrong_file_type"));
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
|
|
||||||
const reader = new FileReader();
|
|
||||||
reader.onload = async (e) => {
|
|
||||||
try {
|
|
||||||
await rules.merge(JSON.parse(e.target.result));
|
|
||||||
} catch (err) {
|
|
||||||
console.log("[import rules]", err);
|
|
||||||
}
|
|
||||||
};
|
|
||||||
reader.readAsText(file);
|
|
||||||
};
|
};
|
||||||
|
|
||||||
const handleInject = () => {
|
const handleInject = () => {
|
||||||
@@ -552,10 +489,11 @@ function UserRules({ subRules }) {
|
|||||||
{i18n("add")}
|
{i18n("add")}
|
||||||
</Button>
|
</Button>
|
||||||
|
|
||||||
<UploadButton text={i18n("import")} onChange={handleImport} />
|
<UploadButton text={i18n("import")} handleImport={handleImport} />
|
||||||
<DownloadButton
|
<DownloadButton
|
||||||
data={JSON.stringify([...rules.list].reverse(), null, 2)}
|
data={JSON.stringify([...rules.list].reverse(), null, 2)}
|
||||||
text={i18n("export")}
|
text={i18n("export")}
|
||||||
|
fileName={`kiss-rules_${Date.now()}.json`}
|
||||||
/>
|
/>
|
||||||
|
|
||||||
<ShareButton
|
<ShareButton
|
||||||
@@ -663,7 +601,14 @@ function SubRulesItem({
|
|||||||
|
|
||||||
return (
|
return (
|
||||||
<Stack direction="row" alignItems="center" spacing={2}>
|
<Stack direction="row" alignItems="center" spacing={2}>
|
||||||
<FormControlLabel value={url} control={<Radio />} label={url} />
|
<FormControlLabel
|
||||||
|
value={url}
|
||||||
|
control={<Radio />}
|
||||||
|
sx={{
|
||||||
|
overflowWrap: "anywhere",
|
||||||
|
}}
|
||||||
|
label={url}
|
||||||
|
/>
|
||||||
|
|
||||||
{syncAt && (
|
{syncAt && (
|
||||||
<span style={{ marginLeft: "0.5em", opacity: 0.5 }}>
|
<span style={{ marginLeft: "0.5em", opacity: 0.5 }}>
|
||||||
|
|||||||
@@ -23,6 +23,8 @@ import {
|
|||||||
OPT_SHORTCUT_STYLE,
|
OPT_SHORTCUT_STYLE,
|
||||||
OPT_SHORTCUT_POPUP,
|
OPT_SHORTCUT_POPUP,
|
||||||
OPT_SHORTCUT_SETTING,
|
OPT_SHORTCUT_SETTING,
|
||||||
|
OPT_LANGS_TO,
|
||||||
|
DEFAULT_BLACKLIST,
|
||||||
} from "../../config";
|
} from "../../config";
|
||||||
import { useShortcut } from "../../hooks/Shortcut";
|
import { useShortcut } from "../../hooks/Shortcut";
|
||||||
import ShortcutInput from "./ShortcutInput";
|
import ShortcutInput from "./ShortcutInput";
|
||||||
@@ -42,6 +44,7 @@ export default function Settings() {
|
|||||||
const { fab, updateFab } = useFab();
|
const { fab, updateFab } = useFab();
|
||||||
|
|
||||||
const handleChange = (e) => {
|
const handleChange = (e) => {
|
||||||
|
console.log("e", e);
|
||||||
e.preventDefault();
|
e.preventDefault();
|
||||||
let { name, value } = e.target;
|
let { name, value } = e.target;
|
||||||
switch (name) {
|
switch (name) {
|
||||||
@@ -60,6 +63,9 @@ export default function Settings() {
|
|||||||
case "newlineLength":
|
case "newlineLength":
|
||||||
value = limitNumber(value, 1, 1000);
|
value = limitNumber(value, 1, 1000);
|
||||||
break;
|
break;
|
||||||
|
case "touchTranslate":
|
||||||
|
value = limitNumber(value, 0, 3);
|
||||||
|
break;
|
||||||
default:
|
default:
|
||||||
}
|
}
|
||||||
updateSetting({
|
updateSetting({
|
||||||
@@ -86,6 +92,9 @@ export default function Settings() {
|
|||||||
newlineLength = TRANS_NEWLINE_LENGTH,
|
newlineLength = TRANS_NEWLINE_LENGTH,
|
||||||
mouseKey = OPT_MOUSEKEY_DISABLE,
|
mouseKey = OPT_MOUSEKEY_DISABLE,
|
||||||
detectRemote = false,
|
detectRemote = false,
|
||||||
|
touchTranslate = 2,
|
||||||
|
blacklist = DEFAULT_BLACKLIST.join(",\n"),
|
||||||
|
disableLangs = [],
|
||||||
} = setting;
|
} = setting;
|
||||||
const { isHide = false } = fab || {};
|
const { isHide = false } = fab || {};
|
||||||
|
|
||||||
@@ -169,6 +178,22 @@ export default function Settings() {
|
|||||||
</Select>
|
</Select>
|
||||||
</FormControl>
|
</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">
|
<FormControl size="small">
|
||||||
<InputLabel>{i18n("hide_fab_button")}</InputLabel>
|
<InputLabel>{i18n("hide_fab_button")}</InputLabel>
|
||||||
<Select
|
<Select
|
||||||
@@ -198,6 +223,24 @@ export default function Settings() {
|
|||||||
<FormHelperText>{i18n("detect_lang_remote_help")}</FormHelperText>
|
<FormHelperText>{i18n("detect_lang_remote_help")}</FormHelperText>
|
||||||
</FormControl>
|
</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 ? (
|
{isExt ? (
|
||||||
<FormControl size="small">
|
<FormControl size="small">
|
||||||
<InputLabel>{i18n("if_clear_cache")}</InputLabel>
|
<InputLabel>{i18n("if_clear_cache")}</InputLabel>
|
||||||
@@ -248,6 +291,16 @@ export default function Settings() {
|
|||||||
</Box>
|
</Box>
|
||||||
</>
|
</>
|
||||||
)}
|
)}
|
||||||
|
|
||||||
|
<TextField
|
||||||
|
size="small"
|
||||||
|
label={i18n("translate_blacklist")}
|
||||||
|
helperText={i18n("pattern_helper")}
|
||||||
|
name="blacklist"
|
||||||
|
defaultValue={blacklist}
|
||||||
|
onChange={handleChange}
|
||||||
|
multiline
|
||||||
|
/>
|
||||||
</Stack>
|
</Stack>
|
||||||
</Box>
|
</Box>
|
||||||
);
|
);
|
||||||
|
|||||||
@@ -47,6 +47,7 @@ export default function Tranbox() {
|
|||||||
tranboxShortcut,
|
tranboxShortcut,
|
||||||
btnOffsetX,
|
btnOffsetX,
|
||||||
btnOffsetY,
|
btnOffsetY,
|
||||||
|
hideTranBtn = false,
|
||||||
} = tranboxSetting;
|
} = tranboxSetting;
|
||||||
|
|
||||||
return (
|
return (
|
||||||
@@ -129,6 +130,18 @@ export default function Tranbox() {
|
|||||||
onChange={handleChange}
|
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
|
<ShortcutInput
|
||||||
value={tranboxShortcut}
|
value={tranboxShortcut}
|
||||||
onChange={handleShortcutInput}
|
onChange={handleShortcutInput}
|
||||||
|
|||||||
55
src/views/Options/UploadButton.js
Normal file
55
src/views/Options/UploadButton.js
Normal file
@@ -0,0 +1,55 @@
|
|||||||
|
import { useRef } from "react";
|
||||||
|
import FileUploadIcon from "@mui/icons-material/FileUpload";
|
||||||
|
import { useI18n } from "../../hooks/I18n";
|
||||||
|
import Button from "@mui/material/Button";
|
||||||
|
|
||||||
|
export default function UploadButton({
|
||||||
|
handleImport,
|
||||||
|
text,
|
||||||
|
fileType = "json",
|
||||||
|
fileExts = [".json"],
|
||||||
|
}) {
|
||||||
|
const i18n = useI18n();
|
||||||
|
const inputRef = useRef(null);
|
||||||
|
const handleClick = () => {
|
||||||
|
if (inputRef.current) {
|
||||||
|
inputRef.current.click();
|
||||||
|
inputRef.current.value = null;
|
||||||
|
}
|
||||||
|
};
|
||||||
|
const onChange = (e) => {
|
||||||
|
const file = e.target.files[0];
|
||||||
|
if (!file) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (!file.type.includes(fileType)) {
|
||||||
|
alert(i18n("error_wrong_file_type"));
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
const reader = new FileReader();
|
||||||
|
reader.onload = async (e) => {
|
||||||
|
handleImport(e.target.result);
|
||||||
|
};
|
||||||
|
reader.readAsText(file);
|
||||||
|
};
|
||||||
|
|
||||||
|
return (
|
||||||
|
<Button
|
||||||
|
size="small"
|
||||||
|
variant="outlined"
|
||||||
|
onClick={handleClick}
|
||||||
|
startIcon={<FileUploadIcon />}
|
||||||
|
>
|
||||||
|
{text}
|
||||||
|
<input
|
||||||
|
type="file"
|
||||||
|
accept={fileExts.join(", ")}
|
||||||
|
ref={inputRef}
|
||||||
|
onChange={onChange}
|
||||||
|
hidden
|
||||||
|
/>
|
||||||
|
</Button>
|
||||||
|
);
|
||||||
|
}
|
||||||
@@ -13,43 +13,204 @@ import FormControlLabel from "@mui/material/FormControlLabel";
|
|||||||
import Switch from "@mui/material/Switch";
|
import Switch from "@mui/material/Switch";
|
||||||
import { useSetting } from "../../hooks/Setting";
|
import { useSetting } from "../../hooks/Setting";
|
||||||
import CircularProgress from "@mui/material/CircularProgress";
|
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 Button from "@mui/material/Button";
|
||||||
import SyncIcon from "@mui/icons-material/Sync";
|
import SyncIcon from "@mui/icons-material/Sync";
|
||||||
import { useAlert } from "../../hooks/Alert";
|
import { useAlert } from "../../hooks/Alert";
|
||||||
import HelpButton from "./HelpButton";
|
import HelpButton from "./HelpButton";
|
||||||
import { URL_KISS_RULES_NEW_ISSUE } from "../../config";
|
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 (
|
return (
|
||||||
<Stack spacing={3}>
|
<form onSubmit={handleSubmit}>
|
||||||
<TextField
|
<Stack spacing={3}>
|
||||||
size="small"
|
<TextField
|
||||||
label={"rootSelector"}
|
size="small"
|
||||||
name="rootSelector"
|
label={i18n("pattern")}
|
||||||
value={rootSelector || "document"}
|
error={!!errors.pattern}
|
||||||
disabled
|
helperText={errors.pattern}
|
||||||
/>
|
name="pattern"
|
||||||
<TextField
|
value={pattern}
|
||||||
size="small"
|
disabled={disabled}
|
||||||
label={"selector"}
|
onChange={handleChange}
|
||||||
name="selector"
|
onFocus={handleFocus}
|
||||||
value={selector}
|
multiline
|
||||||
disabled
|
/>
|
||||||
/>
|
<TextField
|
||||||
<TextField
|
size="small"
|
||||||
size="small"
|
label={i18n("root_selector")}
|
||||||
label={"fixer"}
|
error={!!errors.rootSelector}
|
||||||
name="fixer"
|
helperText={errors.rootSelector}
|
||||||
value={fixer}
|
name="rootSelector"
|
||||||
disabled
|
value={rootSelector}
|
||||||
/>
|
disabled={disabled}
|
||||||
</Stack>
|
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 [expanded, setExpanded] = useState(false);
|
||||||
|
|
||||||
const handleChange = (e) => {
|
const handleChange = (e) => {
|
||||||
@@ -59,10 +220,17 @@ function ApiAccordion({ site }) {
|
|||||||
return (
|
return (
|
||||||
<Accordion expanded={expanded} onChange={handleChange}>
|
<Accordion expanded={expanded} onChange={handleChange}>
|
||||||
<AccordionSummary expandIcon={<ExpandMoreIcon />}>
|
<AccordionSummary expandIcon={<ExpandMoreIcon />}>
|
||||||
<Typography>{site.pattern}</Typography>
|
<Typography
|
||||||
|
sx={{
|
||||||
|
opacity: webfix ? 1 : 0.5,
|
||||||
|
overflowWrap: "anywhere",
|
||||||
|
}}
|
||||||
|
>
|
||||||
|
{rule.pattern}
|
||||||
|
</Typography>
|
||||||
</AccordionSummary>
|
</AccordionSummary>
|
||||||
<AccordionDetails>
|
<AccordionDetails>
|
||||||
{expanded && <ApiFields site={site} />}
|
{expanded && <WebfixFields rule={rule} webfix={webfix} />}
|
||||||
</AccordionDetails>
|
</AccordionDetails>
|
||||||
</Accordion>
|
</Accordion>
|
||||||
);
|
);
|
||||||
@@ -74,6 +242,8 @@ export default function Webfix() {
|
|||||||
const i18n = useI18n();
|
const i18n = useI18n();
|
||||||
const alert = useAlert();
|
const alert = useAlert();
|
||||||
const { setting, updateSetting } = useSetting();
|
const { setting, updateSetting } = useSetting();
|
||||||
|
const [showAdd, setShowAdd] = useState(false);
|
||||||
|
const webfix = useWebfixRules();
|
||||||
|
|
||||||
const loadSites = useCallback(async () => {
|
const loadSites = useCallback(async () => {
|
||||||
const sites = await loadOrFetchWebfix(process.env.REACT_APP_WEBFIXURL);
|
const sites = await loadOrFetchWebfix(process.env.REACT_APP_WEBFIXURL);
|
||||||
@@ -120,6 +290,18 @@ export default function Webfix() {
|
|||||||
useFlexGap
|
useFlexGap
|
||||||
flexWrap="wrap"
|
flexWrap="wrap"
|
||||||
>
|
>
|
||||||
|
<Button
|
||||||
|
size="small"
|
||||||
|
variant="contained"
|
||||||
|
disabled={showAdd}
|
||||||
|
onClick={(e) => {
|
||||||
|
e.preventDefault();
|
||||||
|
setShowAdd(true);
|
||||||
|
}}
|
||||||
|
>
|
||||||
|
{i18n("add")}
|
||||||
|
</Button>
|
||||||
|
|
||||||
<Button
|
<Button
|
||||||
size="small"
|
size="small"
|
||||||
variant="outlined"
|
variant="outlined"
|
||||||
@@ -146,6 +328,16 @@ export default function Webfix() {
|
|||||||
/>
|
/>
|
||||||
</Stack>
|
</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 && (
|
{setting.injectWebfix && (
|
||||||
<Box>
|
<Box>
|
||||||
{loading ? (
|
{loading ? (
|
||||||
@@ -153,8 +345,8 @@ export default function Webfix() {
|
|||||||
<CircularProgress size={16} />
|
<CircularProgress size={16} />
|
||||||
</center>
|
</center>
|
||||||
) : (
|
) : (
|
||||||
sites.map((site) => (
|
sites.map((rule) => (
|
||||||
<ApiAccordion key={site.pattern} site={site} />
|
<WebfixAccordion key={rule.pattern} rule={rule} />
|
||||||
))
|
))
|
||||||
)}
|
)}
|
||||||
</Box>
|
</Box>
|
||||||
|
|||||||
@@ -21,6 +21,7 @@ import Apis from "./Apis";
|
|||||||
import Webfix from "./Webfix";
|
import Webfix from "./Webfix";
|
||||||
import InputSetting from "./InputSetting";
|
import InputSetting from "./InputSetting";
|
||||||
import Tranbox from "./Tranbox";
|
import Tranbox from "./Tranbox";
|
||||||
|
import FavWords from "./FavWords";
|
||||||
|
|
||||||
export default function Options() {
|
export default function Options() {
|
||||||
const [error, setError] = useState("");
|
const [error, setError] = useState("");
|
||||||
@@ -125,6 +126,7 @@ export default function Options() {
|
|||||||
<Route path="apis" element={<Apis />} />
|
<Route path="apis" element={<Apis />} />
|
||||||
<Route path="sync" element={<SyncSetting />} />
|
<Route path="sync" element={<SyncSetting />} />
|
||||||
<Route path="webfix" element={<Webfix />} />
|
<Route path="webfix" element={<Webfix />} />
|
||||||
|
<Route path="words" element={<FavWords />} />
|
||||||
<Route path="about" element={<About />} />
|
<Route path="about" element={<About />} />
|
||||||
</Route>
|
</Route>
|
||||||
</Routes>
|
</Routes>
|
||||||
|
|||||||
@@ -1,9 +1,9 @@
|
|||||||
import Box from "@mui/material/Box";
|
|
||||||
import IconButton from "@mui/material/IconButton";
|
import IconButton from "@mui/material/IconButton";
|
||||||
import CloseIcon from "@mui/icons-material/Close";
|
import CloseIcon from "@mui/icons-material/Close";
|
||||||
import HomeIcon from "@mui/icons-material/Home";
|
import HomeIcon from "@mui/icons-material/Home";
|
||||||
import Stack from "@mui/material/Stack";
|
import Stack from "@mui/material/Stack";
|
||||||
import DarkModeButton from "../Options/DarkModeButton";
|
import DarkModeButton from "../Options/DarkModeButton";
|
||||||
|
import Typography from "@mui/material/Typography";
|
||||||
|
|
||||||
export default function Header({ setShowPopup }) {
|
export default function Header({ setShowPopup }) {
|
||||||
const handleHomepage = () => {
|
const handleHomepage = () => {
|
||||||
@@ -21,14 +21,16 @@ export default function Header({ setShowPopup }) {
|
|||||||
<IconButton onClick={handleHomepage}>
|
<IconButton onClick={handleHomepage}>
|
||||||
<HomeIcon />
|
<HomeIcon />
|
||||||
</IconButton>
|
</IconButton>
|
||||||
<Box
|
<Typography
|
||||||
|
component="div"
|
||||||
sx={{
|
sx={{
|
||||||
userSelect: "none",
|
userSelect: "none",
|
||||||
WebkitUserSelect: "none",
|
WebkitUserSelect: "none",
|
||||||
|
fontWeight: "bold",
|
||||||
}}
|
}}
|
||||||
>
|
>
|
||||||
{`${process.env.REACT_APP_NAME} v${process.env.REACT_APP_VERSION}`}
|
{`${process.env.REACT_APP_NAME} v${process.env.REACT_APP_VERSION}`}
|
||||||
</Box>
|
</Typography>
|
||||||
</Stack>
|
</Stack>
|
||||||
|
|
||||||
{setShowPopup ? (
|
{setShowPopup ? (
|
||||||
|
|||||||
35
src/views/Selection/CopyBtn.js
Normal file
35
src/views/Selection/CopyBtn.js
Normal file
@@ -0,0 +1,35 @@
|
|||||||
|
import IconButton from "@mui/material/IconButton";
|
||||||
|
import ContentCopyIcon from "@mui/icons-material/ContentCopy";
|
||||||
|
import LibraryAddCheckIcon from "@mui/icons-material/LibraryAddCheck";
|
||||||
|
import { useState } from "react";
|
||||||
|
|
||||||
|
export default function CopyBtn({ text }) {
|
||||||
|
const [copied, setCopied] = useState(false);
|
||||||
|
const handleClick = async (e) => {
|
||||||
|
e.stopPropagation();
|
||||||
|
await navigator.clipboard.writeText(text);
|
||||||
|
setCopied(true);
|
||||||
|
const timer = setTimeout(() => {
|
||||||
|
clearTimeout(timer);
|
||||||
|
setCopied(false);
|
||||||
|
}, 500);
|
||||||
|
};
|
||||||
|
return (
|
||||||
|
<IconButton
|
||||||
|
size="small"
|
||||||
|
sx={{
|
||||||
|
opacity: 0.5,
|
||||||
|
"&:hover": {
|
||||||
|
opacity: 1,
|
||||||
|
},
|
||||||
|
}}
|
||||||
|
onClick={handleClick}
|
||||||
|
>
|
||||||
|
{copied ? (
|
||||||
|
<LibraryAddCheckIcon fontSize="inherit" />
|
||||||
|
) : (
|
||||||
|
<ContentCopyIcon fontSize="inherit" />
|
||||||
|
)}
|
||||||
|
</IconButton>
|
||||||
|
);
|
||||||
|
}
|
||||||
65
src/views/Selection/DictCont.js
Normal file
65
src/views/Selection/DictCont.js
Normal file
@@ -0,0 +1,65 @@
|
|||||||
|
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: "第三人称单数",
|
||||||
|
word_ing: "现在分词",
|
||||||
|
word_done: "过去式",
|
||||||
|
word_past: "过去分词",
|
||||||
|
word_pl: "复数",
|
||||||
|
word_proto: "词源",
|
||||||
|
};
|
||||||
|
|
||||||
|
export default function DictCont({ dictResult }) {
|
||||||
|
if (!dictResult) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
return (
|
||||||
|
<Box>
|
||||||
|
<Stack
|
||||||
|
direction="row"
|
||||||
|
justifyContent="space-between"
|
||||||
|
alignItems="flex-start"
|
||||||
|
>
|
||||||
|
<Typography variant="subtitle1" style={{ fontWeight: "bold" }}>
|
||||||
|
{dictResult.simple_means?.word_name}
|
||||||
|
</Typography>
|
||||||
|
<FavBtn word={dictResult.simple_means?.word_name} />
|
||||||
|
</Stack>
|
||||||
|
|
||||||
|
{dictResult.simple_means?.symbols?.map(({ ph_en, ph_am, parts }, idx) => (
|
||||||
|
<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}>
|
||||||
|
{part ? `[${part}] ${means.join("; ")}` : means.join("; ")}
|
||||||
|
</li>
|
||||||
|
))}
|
||||||
|
</ul>
|
||||||
|
</Typography>
|
||||||
|
))}
|
||||||
|
|
||||||
|
<Typography>
|
||||||
|
{Object.entries(dictResult.simple_means?.exchange || {})
|
||||||
|
.map(([key, val]) => `${exchangeMap[key] || key}: ${val.join(", ")}`)
|
||||||
|
.join("; ")}
|
||||||
|
</Typography>
|
||||||
|
|
||||||
|
<Stack direction="row" spacing={1} flexWrap="wrap" useFlexGap>
|
||||||
|
{Object.values(dictResult.simple_means?.tags || {})
|
||||||
|
.flat()
|
||||||
|
.filter((item) => item)
|
||||||
|
.map((item) => (
|
||||||
|
<Chip label={item} size="small" />
|
||||||
|
))}
|
||||||
|
</Stack>
|
||||||
|
</Box>
|
||||||
|
);
|
||||||
|
}
|
||||||
31
src/views/Selection/FavBtn.js
Normal file
31
src/views/Selection/FavBtn.js
Normal file
@@ -0,0 +1,31 @@
|
|||||||
|
import IconButton from "@mui/material/IconButton";
|
||||||
|
import FavoriteIcon from "@mui/icons-material/Favorite";
|
||||||
|
import FavoriteBorderIcon from "@mui/icons-material/FavoriteBorder";
|
||||||
|
import { useState } from "react";
|
||||||
|
import { useFavWords } from "../../hooks/FavWords";
|
||||||
|
|
||||||
|
export default function FavBtn({ word }) {
|
||||||
|
const { favWords, toggleFav } = useFavWords();
|
||||||
|
const [loading, setLoading] = useState(false);
|
||||||
|
|
||||||
|
const handleClick = async () => {
|
||||||
|
try {
|
||||||
|
setLoading(true);
|
||||||
|
await toggleFav(word);
|
||||||
|
} catch (err) {
|
||||||
|
console.log("[set fav]", err);
|
||||||
|
} finally {
|
||||||
|
setLoading(false);
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
return (
|
||||||
|
<IconButton disabled={loading} size="small" onClick={handleClick}>
|
||||||
|
{favWords[word] ? (
|
||||||
|
<FavoriteIcon fontSize="inherit" />
|
||||||
|
) : (
|
||||||
|
<FavoriteBorderIcon fontSize="inherit" />
|
||||||
|
)}
|
||||||
|
</IconButton>
|
||||||
|
);
|
||||||
|
}
|
||||||
@@ -8,10 +8,13 @@ import MenuItem from "@mui/material/MenuItem";
|
|||||||
import Grid from "@mui/material/Grid";
|
import Grid from "@mui/material/Grid";
|
||||||
import Box from "@mui/material/Box";
|
import Box from "@mui/material/Box";
|
||||||
import Divider from "@mui/material/Divider";
|
import Divider from "@mui/material/Divider";
|
||||||
|
import IconButton from "@mui/material/IconButton";
|
||||||
|
import DoneIcon from "@mui/icons-material/Done";
|
||||||
import { useI18n } from "../../hooks/I18n";
|
import { useI18n } from "../../hooks/I18n";
|
||||||
import { OPT_TRANS_ALL, OPT_LANGS_FROM, OPT_LANGS_TO } from "../../config";
|
import { OPT_TRANS_ALL, OPT_LANGS_FROM, OPT_LANGS_TO } from "../../config";
|
||||||
import { useState, useRef } from "react";
|
import { useState, useRef } from "react";
|
||||||
import TranCont from "./TranCont";
|
import TranCont from "./TranCont";
|
||||||
|
import CopyBtn from "./CopyBtn";
|
||||||
|
|
||||||
function TranForm({ text, setText, tranboxSetting, transApis }) {
|
function TranForm({ text, setText, tranboxSetting, transApis }) {
|
||||||
const i18n = useI18n();
|
const i18n = useI18n();
|
||||||
@@ -92,6 +95,7 @@ function TranForm({ text, setText, tranboxSetting, transApis }) {
|
|||||||
|
|
||||||
<Box>
|
<Box>
|
||||||
<TextField
|
<TextField
|
||||||
|
size="small"
|
||||||
label={i18n("original_text")}
|
label={i18n("original_text")}
|
||||||
inputRef={inputRef}
|
inputRef={inputRef}
|
||||||
fullWidth
|
fullWidth
|
||||||
@@ -113,6 +117,31 @@ function TranForm({ text, setText, tranboxSetting, transApis }) {
|
|||||||
setEditMode(false);
|
setEditMode(false);
|
||||||
setText(editText.trim());
|
setText(editText.trim());
|
||||||
}}
|
}}
|
||||||
|
InputProps={{
|
||||||
|
endAdornment: (
|
||||||
|
<Stack
|
||||||
|
direction="row"
|
||||||
|
sx={{
|
||||||
|
position: "absolute",
|
||||||
|
right: 0,
|
||||||
|
top: 0,
|
||||||
|
}}
|
||||||
|
>
|
||||||
|
{editMode ? (
|
||||||
|
<IconButton
|
||||||
|
size="small"
|
||||||
|
onClick={(e) => {
|
||||||
|
e.stopPropagation();
|
||||||
|
}}
|
||||||
|
>
|
||||||
|
<DoneIcon fontSize="inherit" />
|
||||||
|
</IconButton>
|
||||||
|
) : (
|
||||||
|
<CopyBtn text={text} />
|
||||||
|
)}
|
||||||
|
</Stack>
|
||||||
|
),
|
||||||
|
}}
|
||||||
/>
|
/>
|
||||||
</Box>
|
</Box>
|
||||||
|
|
||||||
@@ -2,61 +2,14 @@ import TextField from "@mui/material/TextField";
|
|||||||
import Box from "@mui/material/Box";
|
import Box from "@mui/material/Box";
|
||||||
import Alert from "@mui/material/Alert";
|
import Alert from "@mui/material/Alert";
|
||||||
import CircularProgress from "@mui/material/CircularProgress";
|
import CircularProgress from "@mui/material/CircularProgress";
|
||||||
import Chip from "@mui/material/Chip";
|
|
||||||
import Stack from "@mui/material/Stack";
|
import Stack from "@mui/material/Stack";
|
||||||
import { useI18n } from "../../hooks/I18n";
|
import { useI18n } from "../../hooks/I18n";
|
||||||
import { DEFAULT_TRANS_APIS, OPT_TRANS_BAIDU } from "../../config";
|
import { DEFAULT_TRANS_APIS, OPT_TRANS_BAIDU } from "../../config";
|
||||||
import { useEffect, useState } from "react";
|
import { useEffect, useState } from "react";
|
||||||
import { apiTranslate } from "../../apis";
|
import { apiTranslate } from "../../apis";
|
||||||
import { isValidWord } from "../../libs/utils";
|
import { isValidWord } from "../../libs/utils";
|
||||||
|
import CopyBtn from "./CopyBtn";
|
||||||
const exchangeMap = {
|
import DictCont from "./DictCont";
|
||||||
word_third: "第三人称单数",
|
|
||||||
word_ing: "现在分词",
|
|
||||||
word_done: "过去式",
|
|
||||||
word_past: "过去分词",
|
|
||||||
word_pl: "复数",
|
|
||||||
word_proto: "原词",
|
|
||||||
};
|
|
||||||
|
|
||||||
function DictCont({ dictResult }) {
|
|
||||||
if (!dictResult) {
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
|
|
||||||
return (
|
|
||||||
<Box>
|
|
||||||
<div style={{ fontWeight: "bold" }}>
|
|
||||||
{dictResult.simple_means?.word_name}
|
|
||||||
</div>
|
|
||||||
{dictResult.simple_means?.symbols?.map(({ ph_en, ph_am, parts }, idx) => (
|
|
||||||
<div key={idx}>
|
|
||||||
<div>{`英[${ph_en}] 美[${ph_am}]`}</div>
|
|
||||||
<ul style={{ margin: "0.5em 0" }}>
|
|
||||||
{parts.map(({ part, means }, idx) => (
|
|
||||||
<li key={idx}>
|
|
||||||
{part ? `[${part}] ${means.join("; ")}` : means.join("; ")}
|
|
||||||
</li>
|
|
||||||
))}
|
|
||||||
</ul>
|
|
||||||
</div>
|
|
||||||
))}
|
|
||||||
<div>
|
|
||||||
{Object.entries(dictResult.simple_means?.exchange || {})
|
|
||||||
.map(([key, val]) => `${exchangeMap[key] || key}: ${val.join(", ")}`)
|
|
||||||
.join("; ")}
|
|
||||||
</div>
|
|
||||||
<Stack direction="row" spacing={1}>
|
|
||||||
{Object.values(dictResult.simple_means?.tags || {})
|
|
||||||
.flat()
|
|
||||||
.filter((item) => item)
|
|
||||||
.map((item) => (
|
|
||||||
<Chip label={item} size="small" />
|
|
||||||
))}
|
|
||||||
</Stack>
|
|
||||||
</Box>
|
|
||||||
);
|
|
||||||
}
|
|
||||||
|
|
||||||
export default function TranCont({
|
export default function TranCont({
|
||||||
text,
|
text,
|
||||||
@@ -79,8 +32,8 @@ export default function TranCont({
|
|||||||
setError("");
|
setError("");
|
||||||
setDictResult(null);
|
setDictResult(null);
|
||||||
|
|
||||||
const apis = { ...transApis, ...DEFAULT_TRANS_APIS };
|
const apiSetting =
|
||||||
const apiSetting = apis[translator];
|
transApis[translator] || DEFAULT_TRANS_APIS[translator];
|
||||||
const tranRes = await apiTranslate({
|
const tranRes = await apiTranslate({
|
||||||
text,
|
text,
|
||||||
translator,
|
translator,
|
||||||
@@ -100,7 +53,6 @@ export default function TranCont({
|
|||||||
translator: OPT_TRANS_BAIDU,
|
translator: OPT_TRANS_BAIDU,
|
||||||
fromLang: "en",
|
fromLang: "en",
|
||||||
toLang: "zh-CN",
|
toLang: "zh-CN",
|
||||||
apiSetting: apis[OPT_TRANS_BAIDU],
|
|
||||||
});
|
});
|
||||||
setDictResult(dictRes[2].dict_result);
|
setDictResult(dictRes[2].dict_result);
|
||||||
}
|
}
|
||||||
@@ -117,10 +69,26 @@ export default function TranCont({
|
|||||||
<>
|
<>
|
||||||
<Box>
|
<Box>
|
||||||
<TextField
|
<TextField
|
||||||
|
size="small"
|
||||||
label={i18n("translated_text")}
|
label={i18n("translated_text")}
|
||||||
|
// disabled
|
||||||
fullWidth
|
fullWidth
|
||||||
multiline
|
multiline
|
||||||
value={trText}
|
value={trText}
|
||||||
|
InputProps={{
|
||||||
|
endAdornment: (
|
||||||
|
<Stack
|
||||||
|
direction="row"
|
||||||
|
sx={{
|
||||||
|
position: "absolute",
|
||||||
|
right: 0,
|
||||||
|
top: 0,
|
||||||
|
}}
|
||||||
|
>
|
||||||
|
<CopyBtn text={trText} />
|
||||||
|
</Stack>
|
||||||
|
),
|
||||||
|
}}
|
||||||
/>
|
/>
|
||||||
</Box>
|
</Box>
|
||||||
|
|
||||||
|
|||||||
@@ -1,7 +1,10 @@
|
|||||||
import { useState, useEffect } from "react";
|
import { useState, useEffect, useCallback } from "react";
|
||||||
import TranBtn from "./Tranbtn";
|
import TranBtn from "./TranBtn";
|
||||||
import TranBox from "./Tranbox";
|
import TranBox from "./TranBox";
|
||||||
import { shortcutRegister } from "../../libs/shortcut";
|
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({ tranboxSetting, transApis }) {
|
||||||
const [showBox, setShowBox] = useState(false);
|
const [showBox, setShowBox] = useState(false);
|
||||||
@@ -15,47 +18,94 @@ export default function Slection({ tranboxSetting, transApis }) {
|
|||||||
y: (window.innerHeight - 400) / 2,
|
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() || "";
|
const selectedText = window.getSelection()?.toString()?.trim() || "";
|
||||||
if (!selectedText) {
|
if (!selectedText) {
|
||||||
setShowBtn(false);
|
setShowBox((pre) => !pre);
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
setSelText(selectedText);
|
setSelText(selectedText);
|
||||||
setShowBtn(true);
|
|
||||||
setPosition({ x: e.clientX, y: e.clientY });
|
|
||||||
}
|
|
||||||
|
|
||||||
const handleClick = (e) => {
|
|
||||||
e.stopPropagation();
|
|
||||||
setShowBtn(false);
|
|
||||||
|
|
||||||
setText(selectedText);
|
setText(selectedText);
|
||||||
if (!showBox) {
|
setShowBox(true);
|
||||||
setShowBox(true);
|
}, []);
|
||||||
}
|
|
||||||
};
|
|
||||||
|
|
||||||
useEffect(() => {
|
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 });
|
||||||
|
}
|
||||||
|
|
||||||
window.addEventListener("mouseup", handleMouseup);
|
window.addEventListener("mouseup", handleMouseup);
|
||||||
return () => {
|
return () => {
|
||||||
window.removeEventListener("mouseup", handleMouseup);
|
window.removeEventListener("mouseup", handleMouseup);
|
||||||
};
|
};
|
||||||
}, []);
|
}, [tranboxSetting.hideTranBtn]);
|
||||||
|
|
||||||
useEffect(() => {
|
useEffect(() => {
|
||||||
const clearShortcut = shortcutRegister(
|
const clearShortcut = shortcutRegister(
|
||||||
tranboxSetting.tranboxShortcut,
|
tranboxSetting.tranboxShortcut || DEFAULT_TRANBOX_SHORTCUT,
|
||||||
() => {
|
handleTranbox
|
||||||
setShowBox((pre) => !pre);
|
|
||||||
}
|
|
||||||
);
|
);
|
||||||
|
|
||||||
return () => {
|
return () => {
|
||||||
clearShortcut();
|
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 = [];
|
||||||
|
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]);
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<>
|
<>
|
||||||
|
|||||||
Reference in New Issue
Block a user