Compare commits
93 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
f65314bc2d | ||
|
|
1791e36038 | ||
|
|
8d93094af5 | ||
|
|
43f34fe6ed | ||
|
|
83911b2164 | ||
|
|
94c7494e90 | ||
|
|
65f2177299 | ||
|
|
f033b11e63 | ||
|
|
02f26af592 | ||
|
|
4125aba808 | ||
|
|
e89da9120c | ||
|
|
160fc218fc | ||
|
|
507d54dba0 | ||
|
|
f3029a0f76 | ||
|
|
53181588cf | ||
|
|
f88aa159fc | ||
|
|
fb2b517a67 | ||
|
|
6e952a9530 | ||
|
|
d9acef8d56 | ||
|
|
113a4d8eca | ||
|
|
6d5b93c01b | ||
|
|
5746911651 | ||
|
|
7173692db7 | ||
|
|
b13a63e568 | ||
|
|
791ec65579 | ||
|
|
dd99fddc07 | ||
|
|
5cd6977a6e | ||
|
|
5af66204c4 | ||
|
|
595efe808f | ||
|
|
7b4b3b020c | ||
|
|
3e96540b56 | ||
|
|
88b791bd73 | ||
|
|
7817019e70 | ||
|
|
6013bbd32c | ||
|
|
40e0b96f39 | ||
|
|
16560fbdf0 | ||
|
|
16fdd704aa | ||
|
|
44e84d9259 | ||
|
|
18d29461ce | ||
|
|
31fb749e93 | ||
|
|
e17931493b | ||
|
|
a395f0b31b | ||
|
|
c819896b43 | ||
|
|
733ec92c9c | ||
|
|
7c67bb7181 | ||
|
|
87f099dd7f | ||
|
|
5306d81284 | ||
|
|
471a4a3159 | ||
|
|
a2f99da3b4 | ||
|
|
accab22d56 | ||
|
|
6ea5228a5f | ||
|
|
a07d2cafb6 | ||
|
|
1b38f19cc1 | ||
|
|
aa5b286e0b | ||
|
|
6b6bbed330 | ||
|
|
489bc9534b | ||
|
|
01ebc184ad | ||
|
|
f591d66365 | ||
|
|
80782287d8 | ||
|
|
3494bb1297 | ||
|
|
92ffda5220 | ||
|
|
fbaeff6b7b | ||
|
|
248d3726dd | ||
|
|
1553559b1a | ||
|
|
8935ced75a | ||
|
|
a865d6d74f | ||
|
|
6d976554fd | ||
|
|
189b7f480a | ||
|
|
5e3aa7e2d1 | ||
|
|
730be678ef | ||
|
|
9293f422f3 | ||
|
|
6e8158bb34 | ||
|
|
3078d3ca91 | ||
|
|
947e1c7f08 | ||
|
|
938c123412 | ||
|
|
e7a57ad3b2 | ||
|
|
1e40f81bf7 | ||
|
|
72b2f44e32 | ||
|
|
76f54461e7 | ||
|
|
14ca13e31d | ||
|
|
556fd71275 | ||
|
|
a8002bba9f | ||
|
|
ddd9371fbd | ||
|
|
0ea97b73e3 | ||
|
|
f8c8a4ebeb | ||
|
|
5f613ab558 | ||
|
|
56281f9e82 | ||
|
|
5e8743dbb7 | ||
|
|
f4e4c84712 | ||
|
|
c57a0a11fa | ||
|
|
fa244b2097 | ||
|
|
79612f8a1b | ||
|
|
2bf79dbc51 |
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.6.12
|
REACT_APP_VERSION=1.7.8
|
||||||
|
|
||||||
REACT_APP_HOMEPAGE=https://github.com/fishjar/kiss-translator
|
REACT_APP_HOMEPAGE=https://github.com/fishjar/kiss-translator
|
||||||
|
|
||||||
|
|||||||
9
.github/workflows/release.yml
vendored
9
.github/workflows/release.yml
vendored
@@ -10,12 +10,15 @@ jobs:
|
|||||||
runs-on: ubuntu-22.04
|
runs-on: ubuntu-22.04
|
||||||
steps:
|
steps:
|
||||||
- uses: actions/checkout@v3
|
- uses: actions/checkout@v3
|
||||||
|
- uses: pnpm/action-setup@v2
|
||||||
|
with:
|
||||||
|
version: 8.7.6
|
||||||
- uses: actions/setup-node@v3
|
- uses: actions/setup-node@v3
|
||||||
with:
|
with:
|
||||||
node-version: "18.17.0"
|
node-version: "18.17.0"
|
||||||
cache: "yarn"
|
cache: "pnpm"
|
||||||
- run: yarn install
|
- run: pnpm install
|
||||||
- run: yarn build
|
- run: pnpm build
|
||||||
- uses: actions/upload-artifact@v3
|
- uses: actions/upload-artifact@v3
|
||||||
with:
|
with:
|
||||||
name: build-artifacts
|
name: build-artifacts
|
||||||
|
|||||||
@@ -1 +0,0 @@
|
|||||||
nodeLinker: node-modules
|
|
||||||
48
README.en.md
48
README.en.md
@@ -1,19 +1,9 @@
|
|||||||
# KISS Translator
|
# KISS Translator
|
||||||
|
|
||||||
A minimalist [bilingual translation Extension & Greasemonkey Script](https://github.com/fishjar/kiss-translator).
|
A simple [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)
|
||||||
|
|
||||||
## Inspiration
|
|
||||||
|
|
||||||
The inspiration for this project comes from [Immersive Translate](https://github.com/immersive-translate/immersive-translate). After trying it out, I found that it can be used together with the [Webpage Word Translation Extension](https://github.com/fishjar/kiss-dictionary) developed by me earlier, which just forms a very good supplement.
|
|
||||||
|
|
||||||
But the function of this extension is a bit complicated for me, and only the compiled and obfuscated installation package is provided, and the source code is not provided, which cannot meet some of my personalized customization needs.
|
|
||||||
|
|
||||||
It just so happens that I am obsessed with translation tools. Based on the concept of "mainly for personal use, as long as you can use it", I made one. At present, the first version is completed, which basically meets the needs of personal use.
|
|
||||||
|
|
||||||
If you also like a little more simplicity, welcome to pick it up.
|
|
||||||
|
|
||||||
## Features
|
## Features
|
||||||
|
|
||||||
- [x] Keep it simple, smart
|
- [x] Keep it simple, smart
|
||||||
@@ -22,18 +12,34 @@ If you also like a little more simplicity, welcome to pick it up.
|
|||||||
- [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
|
- [x] Google/Microsoft/DeepL/OpenAI/Baidu/Tencent
|
||||||
- [x] Custom translation interface
|
- [x] Custom translation interface
|
||||||
- [x] Data synchronization function
|
- [x] Covers common translation scenarios
|
||||||
- [x] Custom rules + rule subscription
|
- [x] Web bilingual translation
|
||||||
- [x] Custom style
|
- [x] Input box translation
|
||||||
|
- [x] Seletction translation
|
||||||
|
- [x] Mouseover translation
|
||||||
|
- [x] YouTube subtitle translation
|
||||||
|
- [x] Cross-client data synchronization
|
||||||
|
- [x] KISS-Worker(cloudflare/docker)
|
||||||
|
- [x] WebDAV
|
||||||
|
- [x] Custom translation rules
|
||||||
|
- [x] Rule subscription/rule sharing
|
||||||
|
- [x] Custom translation style
|
||||||
- [x] Custom shortcut keys
|
- [x] Custom shortcut keys
|
||||||
- `Alt+Q` Toggle Translation
|
- `Alt+Q` Toggle Translation
|
||||||
- `Alt+C` Toggle Styles
|
- `Alt+C` Toggle Styles
|
||||||
- `Alt+K` Open Popup
|
- `Alt+K` Open Setting Popup
|
||||||
- `Alt+O` Open Options
|
- `Alt+B` Open Translate Popup
|
||||||
|
- `Alt+O` Open Options Page
|
||||||
|
- `Alt+I` Input Box Translation
|
||||||
|
|
||||||
## Download
|
## Install
|
||||||
|
|
||||||
|
> Note: For the following reasons, it is recommended to use browser extensions first
|
||||||
|
>
|
||||||
|
> - Browser extension can use local language recognition
|
||||||
|
> - Grease Monkey script will encounter more usage problems
|
||||||
|
|
||||||
- [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)
|
||||||
@@ -45,7 +51,7 @@ If you also like a little more simplicity, welcome to pick it up.
|
|||||||
- 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 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)
|
||||||
|
|
||||||
## Associated ProjectS
|
## Associated Projects
|
||||||
|
|
||||||
- Data synchronization service: [https://github.com/fishjar/kiss-worker](https://github.com/fishjar/kiss-worker)
|
- Data synchronization service: [https://github.com/fishjar/kiss-worker](https://github.com/fishjar/kiss-worker)
|
||||||
- Data synchronization service available for this project.
|
- Data synchronization service available for this project.
|
||||||
@@ -70,8 +76,8 @@ If you also like a little more simplicity, welcome to pick it up.
|
|||||||
```sh
|
```sh
|
||||||
git clone https://github.com/fishjar/kiss-translator.git
|
git clone https://github.com/fishjar/kiss-translator.git
|
||||||
cd kiss-translator
|
cd kiss-translator
|
||||||
yarn install
|
pnpm install
|
||||||
yarn build
|
pnpm build
|
||||||
```
|
```
|
||||||
|
|
||||||
## Discussion
|
## Discussion
|
||||||
|
|||||||
48
README.md
48
README.md
@@ -1,20 +1,10 @@
|
|||||||
# 简约翻译
|
# 简约翻译
|
||||||
|
|
||||||
一个简约的 [双语网页翻译扩展 & 油猴脚本](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)
|
||||||
|
|
||||||
## 缘由
|
## 特性
|
||||||
|
|
||||||
本项目灵感来源于 [Immersive Translate](https://github.com/immersive-translate/immersive-translate),在试用了后,发现搭配本人早前开发的 [网页划词翻译扩展](https://github.com/fishjar/kiss-dictionary) 一起使用,刚好形成很好补充。
|
|
||||||
|
|
||||||
但该扩展的功能对我来说有些繁杂了,而且只提供编译混淆后的安装包,没有提供源代码,无法满足我的一些个性化定制需求。
|
|
||||||
|
|
||||||
恰巧本人对翻译类工具有些执念,本着`“自用为主,能用就行”`的理念,于是动手撸了一个,目前初版完成,基本达到个人使用需求。
|
|
||||||
|
|
||||||
如果你也喜欢简约一点的,欢迎自取。
|
|
||||||
|
|
||||||
## 特点
|
|
||||||
|
|
||||||
- [x] 保持简约
|
- [x] 保持简约
|
||||||
- [x] 开放源代码
|
- [x] 开放源代码
|
||||||
@@ -22,18 +12,34 @@
|
|||||||
- [x] Chrome/Edge/Firefox/Kiwi
|
- [x] Chrome/Edge/Firefox/Kiwi
|
||||||
- [ ] Safari
|
- [ ] Safari
|
||||||
- [x] 支持多种翻译服务
|
- [x] 支持多种翻译服务
|
||||||
- [x] Google/Microsoft/DeepL/OpenAI
|
- [x] Google/Microsoft/DeepL/OpenAI/Baidu/Tencent
|
||||||
- [x] 自定义翻译接口
|
- [x] 自定义翻译接口
|
||||||
- [x] 数据同步功能
|
- [x] 覆盖常见翻译场景
|
||||||
- [x] 自定义规则 + 规则订阅
|
- [x] 网页双语对照翻译
|
||||||
- [x] 自定义样式
|
- [x] 输入框翻译
|
||||||
|
- [x] 划词翻译
|
||||||
|
- [x] 鼠标悬停翻译
|
||||||
|
- [x] YouTube 字幕翻译
|
||||||
|
- [x] 跨客户端数据同步
|
||||||
|
- [x] KISS-Worker(cloudflare/docker)
|
||||||
|
- [x] WebDAV
|
||||||
|
- [x] 自定义翻译规则
|
||||||
|
- [x] 规则订阅/规则分享
|
||||||
|
- [x] 自定义译文样式
|
||||||
- [x] 自定义快捷键
|
- [x] 自定义快捷键
|
||||||
- `Alt+Q` 开启翻译
|
- `Alt+Q` 开启翻译
|
||||||
- `Alt+C` 切换样式
|
- `Alt+C` 切换样式
|
||||||
- `Alt+K` 打开弹窗
|
- `Alt+K` 打开设置弹窗
|
||||||
- `Alt+O` 打开设置
|
- `Alt+B` 打开翻译弹窗
|
||||||
|
- `Alt+O` 打开设置页面
|
||||||
|
- `Alt+I` 输入框翻译
|
||||||
|
|
||||||
## 下载
|
## 安装
|
||||||
|
|
||||||
|
> 注:基于以下原因,建议优先使用浏览器扩展
|
||||||
|
>
|
||||||
|
> - 浏览器扩展可以使用本地的语言识别
|
||||||
|
> - 油猴脚本会遇到更多使用上的问题
|
||||||
|
|
||||||
- [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)
|
||||||
@@ -70,8 +76,8 @@
|
|||||||
```sh
|
```sh
|
||||||
git clone https://github.com/fishjar/kiss-translator.git
|
git clone https://github.com/fishjar/kiss-translator.git
|
||||||
cd kiss-translator
|
cd kiss-translator
|
||||||
yarn install
|
pnpm install
|
||||||
yarn build
|
pnpm build
|
||||||
```
|
```
|
||||||
|
|
||||||
## 交流
|
## 交流
|
||||||
|
|||||||
@@ -75,7 +75,7 @@ const userscriptWebpack = (config, env) => {
|
|||||||
// @name ${process.env.REACT_APP_NAME}
|
// @name ${process.env.REACT_APP_NAME}
|
||||||
// @namespace ${process.env.REACT_APP_HOMEPAGE}
|
// @namespace ${process.env.REACT_APP_HOMEPAGE}
|
||||||
// @version ${process.env.REACT_APP_VERSION}
|
// @version ${process.env.REACT_APP_VERSION}
|
||||||
// @description A minimalist bilingual translation Extension & Greasemonkey Script (一个简约的双语网页翻译扩展 & 油猴脚本)
|
// @description A simple bilingual translation extension & Greasemonkey script (一个简约的双语对照翻译扩展 & 油猴脚本)
|
||||||
// @author Gabe<yugang2002@gmail.com>
|
// @author Gabe<yugang2002@gmail.com>
|
||||||
// @homepageURL ${process.env.REACT_APP_HOMEPAGE}
|
// @homepageURL ${process.env.REACT_APP_HOMEPAGE}
|
||||||
// @license GPL-3.0
|
// @license GPL-3.0
|
||||||
@@ -95,6 +95,7 @@ const userscriptWebpack = (config, env) => {
|
|||||||
// @connect edge.microsoft.com
|
// @connect edge.microsoft.com
|
||||||
// @connect api-free.deepl.com
|
// @connect api-free.deepl.com
|
||||||
// @connect api.deepl.com
|
// @connect api.deepl.com
|
||||||
|
// @connect www2.deepl.com
|
||||||
// @connect api.openai.com
|
// @connect api.openai.com
|
||||||
// @connect openai.azure.com
|
// @connect openai.azure.com
|
||||||
// @connect workers.dev
|
// @connect workers.dev
|
||||||
@@ -102,7 +103,13 @@ const userscriptWebpack = (config, env) => {
|
|||||||
// @connect githubusercontent.com
|
// @connect githubusercontent.com
|
||||||
// @connect kiss-translator.rayjar.com
|
// @connect kiss-translator.rayjar.com
|
||||||
// @connect ghproxy.com
|
// @connect ghproxy.com
|
||||||
|
// @connect dav.jianguoyun.com
|
||||||
|
// @connect fanyi.baidu.com
|
||||||
|
// @connect transmart.qq.com
|
||||||
// @connect localhost:3000
|
// @connect localhost:3000
|
||||||
|
// @connect 127.0.0.1:3000
|
||||||
|
// @connect localhost:1188
|
||||||
|
// @connect 127.0.0.1:1188
|
||||||
// @run-at document-end
|
// @run-at document-end
|
||||||
// ==/UserScript==
|
// ==/UserScript==
|
||||||
|
|
||||||
|
|||||||
12
package.json
12
package.json
@@ -1,10 +1,11 @@
|
|||||||
{
|
{
|
||||||
"name": "kiss-translator",
|
"name": "kiss-translator",
|
||||||
"description": "A minimalist bilingual translation Extension & Greasemonkey Script",
|
"description": "A minimalist bilingual translation Extension & Greasemonkey Script",
|
||||||
"version": "1.6.12",
|
"version": "1.7.8",
|
||||||
"author": "Gabe<yugang2002@gmail.com>",
|
"author": "Gabe<yugang2002@gmail.com>",
|
||||||
"private": true,
|
"private": true,
|
||||||
"dependencies": {
|
"dependencies": {
|
||||||
|
"@emotion/cache": "^11.11.0",
|
||||||
"@emotion/react": "^11.11.1",
|
"@emotion/react": "^11.11.1",
|
||||||
"@emotion/styled": "^11.10.8",
|
"@emotion/styled": "^11.10.8",
|
||||||
"@mui/icons-material": "^5.11.11",
|
"@mui/icons-material": "^5.11.11",
|
||||||
@@ -15,6 +16,7 @@
|
|||||||
"react-markdown": "^8.0.7",
|
"react-markdown": "^8.0.7",
|
||||||
"react-router-dom": "^6.10.0",
|
"react-router-dom": "^6.10.0",
|
||||||
"react-scripts": "5.0.1",
|
"react-scripts": "5.0.1",
|
||||||
|
"webdav": "^5.3.0",
|
||||||
"webextension-polyfill": "^0.10.0"
|
"webextension-polyfill": "^0.10.0"
|
||||||
},
|
},
|
||||||
"scripts": {
|
"scripts": {
|
||||||
@@ -27,7 +29,7 @@
|
|||||||
"build:userscript-ios": "file1=build/web/kiss-translator.user.js file2=build/web/kiss-translator-ios-safari.user.js && cp $file1 $file2 && sed -i 's|// @grant unsafeWindow|// @inject-into content|g' $file2",
|
"build:userscript-ios": "file1=build/web/kiss-translator.user.js file2=build/web/kiss-translator-ios-safari.user.js && cp $file1 $file2 && sed -i 's|// @grant unsafeWindow|// @inject-into content|g' $file2",
|
||||||
"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": "yarn build:chrome && yarn build:edge && yarn build:firefox && yarn build:web && yarn build:userscript-ios && yarn build:userscript && yarn 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",
|
"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"
|
||||||
@@ -39,7 +41,8 @@
|
|||||||
],
|
],
|
||||||
"globals": {
|
"globals": {
|
||||||
"GM": true,
|
"GM": true,
|
||||||
"unsafeWindow": true
|
"unsafeWindow": true,
|
||||||
|
"globalThis": true
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
"browserslist": {
|
"browserslist": {
|
||||||
@@ -59,7 +62,6 @@
|
|||||||
"@babel/node": "^7.22.10",
|
"@babel/node": "^7.22.10",
|
||||||
"@babel/plugin-proposal-private-property-in-object": "^7.21.11",
|
"@babel/plugin-proposal-private-property-in-object": "^7.21.11",
|
||||||
"@babel/preset-env": "^7.22.10",
|
"@babel/preset-env": "^7.22.10",
|
||||||
"react-app-rewired": "^2.2.1",
|
"react-app-rewired": "^2.2.1"
|
||||||
"wrangler": "^3.4.0"
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
10267
pnpm-lock.yaml
generated
Normal file
10267
pnpm-lock.yaml
generated
Normal file
File diff suppressed because it is too large
Load Diff
@@ -3,7 +3,7 @@
|
|||||||
"message": "KISS Translator"
|
"message": "KISS Translator"
|
||||||
},
|
},
|
||||||
"app_description": {
|
"app_description": {
|
||||||
"message": "A minimalist bilingual translation Extension & Greasemonkey Script"
|
"message": "A simple bilingual translation extension & Greasemonkey script"
|
||||||
},
|
},
|
||||||
"toggle_translate": {
|
"toggle_translate": {
|
||||||
"message": "Toggle Translate"
|
"message": "Toggle Translate"
|
||||||
|
|||||||
@@ -3,7 +3,7 @@
|
|||||||
"message": "简约翻译"
|
"message": "简约翻译"
|
||||||
},
|
},
|
||||||
"app_description": {
|
"app_description": {
|
||||||
"message": "一个简约的双语网页翻译扩展 & 油猴脚本"
|
"message": "一个简约的双语对照翻译扩展 & 油猴脚本"
|
||||||
},
|
},
|
||||||
"toggle_translate": {
|
"toggle_translate": {
|
||||||
"message": "开启翻译"
|
"message": "开启翻译"
|
||||||
|
|||||||
@@ -84,6 +84,11 @@
|
|||||||
>
|
>
|
||||||
</p>
|
</p>
|
||||||
</h2>
|
</h2>
|
||||||
|
<hr />
|
||||||
|
<input id="input1" style="width: 80%;" />
|
||||||
|
<hr />
|
||||||
|
<textarea id="textarea1" style="width: 80%;">test</textarea>
|
||||||
|
<hr />
|
||||||
<div id="addtitle"></div>
|
<div id="addtitle"></div>
|
||||||
<h2>Shadow 1</h2>
|
<h2>Shadow 1</h2>
|
||||||
<div id="shadow1"></div>
|
<div id="shadow1"></div>
|
||||||
|
|||||||
@@ -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.6.12",
|
"version": "1.7.8",
|
||||||
"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",
|
||||||
|
|||||||
@@ -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.6.12",
|
"version": "1.7.8",
|
||||||
"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",
|
||||||
|
|||||||
230
src/apis/baidu.js
Normal file
230
src/apis/baidu.js
Normal file
@@ -0,0 +1,230 @@
|
|||||||
|
import queryString from "query-string";
|
||||||
|
import { getBdauth, setBdauth } from "../libs/storage";
|
||||||
|
import { URL_BAIDU_WEB, URL_BAIDU_TRAN } from "../config";
|
||||||
|
import { fetchApi } from "../libs/fetch";
|
||||||
|
|
||||||
|
/* eslint-disable */
|
||||||
|
function n(t, e) {
|
||||||
|
for (var n = 0; n < e.length - 2; n += 3) {
|
||||||
|
var r = e.charAt(n + 2);
|
||||||
|
(r = "a" <= r ? r.charCodeAt(0) - 87 : Number(r)),
|
||||||
|
(r = "+" === e.charAt(n + 1) ? t >>> r : t << r),
|
||||||
|
(t = "+" === e.charAt(n) ? (t + r) & 4294967295 : t ^ r);
|
||||||
|
}
|
||||||
|
return t;
|
||||||
|
}
|
||||||
|
|
||||||
|
function e(t, e) {
|
||||||
|
(null == e || e > t.length) && (e = t.length);
|
||||||
|
for (var n = 0, r = new Array(e); n < e; n++) r[n] = t[n];
|
||||||
|
return r;
|
||||||
|
}
|
||||||
|
|
||||||
|
/* eslint-disable */
|
||||||
|
function getSign(t, gtk, r = null) {
|
||||||
|
var o,
|
||||||
|
i = t.match(/[\uD800-\uDBFF][\uDC00-\uDFFF]/g);
|
||||||
|
if (null === i) {
|
||||||
|
var a = t.length;
|
||||||
|
a > 30 &&
|
||||||
|
(t = ""
|
||||||
|
.concat(t.substr(0, 10))
|
||||||
|
.concat(t.substr(Math.floor(a / 2) - 5, 10))
|
||||||
|
.concat(t.substr(-10, 10)));
|
||||||
|
} else {
|
||||||
|
for (
|
||||||
|
var s = t.split(/[\uD800-\uDBFF][\uDC00-\uDFFF]/),
|
||||||
|
c = 0,
|
||||||
|
u = s.length,
|
||||||
|
l = [];
|
||||||
|
c < u;
|
||||||
|
c++
|
||||||
|
)
|
||||||
|
"" !== s[c] &&
|
||||||
|
l.push.apply(
|
||||||
|
l,
|
||||||
|
(function (t) {
|
||||||
|
if (Array.isArray(t)) return e(t);
|
||||||
|
})((o = s[c].split(""))) ||
|
||||||
|
(function (t) {
|
||||||
|
if (
|
||||||
|
("undefined" != typeof Symbol && null != t[Symbol.iterator]) ||
|
||||||
|
null != t["@@iterator"]
|
||||||
|
)
|
||||||
|
return Array.from(t);
|
||||||
|
})(o) ||
|
||||||
|
(function (t, n) {
|
||||||
|
if (t) {
|
||||||
|
if ("string" == typeof t) return e(t, n);
|
||||||
|
var r = Object.prototype.toString.call(t).slice(8, -1);
|
||||||
|
return (
|
||||||
|
"Object" === r && t.constructor && (r = t.constructor.name),
|
||||||
|
"Map" === r || "Set" === r
|
||||||
|
? Array.from(t)
|
||||||
|
: "Arguments" === r ||
|
||||||
|
/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(r)
|
||||||
|
? e(t, n)
|
||||||
|
: void 0
|
||||||
|
);
|
||||||
|
}
|
||||||
|
})(o) ||
|
||||||
|
(function () {
|
||||||
|
throw new TypeError(
|
||||||
|
"Invalid attempt to spread non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method."
|
||||||
|
);
|
||||||
|
})()
|
||||||
|
),
|
||||||
|
c !== u - 1 && l.push(i[c]);
|
||||||
|
var p = l.length;
|
||||||
|
p > 30 &&
|
||||||
|
(t =
|
||||||
|
l.slice(0, 10).join("") +
|
||||||
|
l.slice(Math.floor(p / 2) - 5, Math.floor(p / 2) + 5).join("") +
|
||||||
|
l.slice(-10).join(""));
|
||||||
|
}
|
||||||
|
for (
|
||||||
|
var d = ""
|
||||||
|
.concat(String.fromCharCode(103))
|
||||||
|
.concat(String.fromCharCode(116))
|
||||||
|
.concat(String.fromCharCode(107)),
|
||||||
|
h = (null !== r ? r : (r = gtk || "") || "").split("."),
|
||||||
|
f = Number(h[0]) || 0,
|
||||||
|
m = Number(h[1]) || 0,
|
||||||
|
g = [],
|
||||||
|
y = 0,
|
||||||
|
v = 0;
|
||||||
|
v < t.length;
|
||||||
|
v++
|
||||||
|
) {
|
||||||
|
var _ = t.charCodeAt(v);
|
||||||
|
_ < 128
|
||||||
|
? (g[y++] = _)
|
||||||
|
: (_ < 2048
|
||||||
|
? (g[y++] = (_ >> 6) | 192)
|
||||||
|
: (55296 == (64512 & _) &&
|
||||||
|
v + 1 < t.length &&
|
||||||
|
56320 == (64512 & t.charCodeAt(v + 1))
|
||||||
|
? ((_ = 65536 + ((1023 & _) << 10) + (1023 & t.charCodeAt(++v))),
|
||||||
|
(g[y++] = (_ >> 18) | 240),
|
||||||
|
(g[y++] = ((_ >> 12) & 63) | 128))
|
||||||
|
: (g[y++] = (_ >> 12) | 224),
|
||||||
|
(g[y++] = ((_ >> 6) & 63) | 128)),
|
||||||
|
(g[y++] = (63 & _) | 128));
|
||||||
|
}
|
||||||
|
for (
|
||||||
|
var b = f,
|
||||||
|
w =
|
||||||
|
""
|
||||||
|
.concat(String.fromCharCode(43))
|
||||||
|
.concat(String.fromCharCode(45))
|
||||||
|
.concat(String.fromCharCode(97)) +
|
||||||
|
""
|
||||||
|
.concat(String.fromCharCode(94))
|
||||||
|
.concat(String.fromCharCode(43))
|
||||||
|
.concat(String.fromCharCode(54)),
|
||||||
|
k =
|
||||||
|
""
|
||||||
|
.concat(String.fromCharCode(43))
|
||||||
|
.concat(String.fromCharCode(45))
|
||||||
|
.concat(String.fromCharCode(51)) +
|
||||||
|
""
|
||||||
|
.concat(String.fromCharCode(94))
|
||||||
|
.concat(String.fromCharCode(43))
|
||||||
|
.concat(String.fromCharCode(98)) +
|
||||||
|
""
|
||||||
|
.concat(String.fromCharCode(43))
|
||||||
|
.concat(String.fromCharCode(45))
|
||||||
|
.concat(String.fromCharCode(102)),
|
||||||
|
x = 0;
|
||||||
|
x < g.length;
|
||||||
|
x++
|
||||||
|
)
|
||||||
|
b = n((b += g[x]), w);
|
||||||
|
return (
|
||||||
|
(b = n(b, k)),
|
||||||
|
(b ^= m) < 0 && (b = 2147483648 + (2147483647 & b)),
|
||||||
|
"".concat((b %= 1e6).toString(), ".").concat(b ^ f)
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
const getToken = async () => {
|
||||||
|
const res = await fetchApi({
|
||||||
|
input: URL_BAIDU_WEB,
|
||||||
|
init: {
|
||||||
|
headers: {
|
||||||
|
"Content-type": "text/html; charset=utf-8",
|
||||||
|
},
|
||||||
|
},
|
||||||
|
});
|
||||||
|
|
||||||
|
if (!res.ok) {
|
||||||
|
throw new Error(res.statusText);
|
||||||
|
}
|
||||||
|
|
||||||
|
const text = await res.text();
|
||||||
|
const token = text.match(/token: '(.*)',/)[1];
|
||||||
|
const gtk = text.match(/gtk = "(.*)";/)[1];
|
||||||
|
const exp = Date.now() + 8 * 60 * 60 * 1000;
|
||||||
|
|
||||||
|
if (!token || !gtk) {
|
||||||
|
throw new Error("[baidu] get token error");
|
||||||
|
}
|
||||||
|
|
||||||
|
return { token, gtk, exp };
|
||||||
|
};
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 闭包缓存token,减少对storage查询
|
||||||
|
* @returns
|
||||||
|
*/
|
||||||
|
const _bdAuth = () => {
|
||||||
|
let store;
|
||||||
|
|
||||||
|
return async () => {
|
||||||
|
const now = Date.now();
|
||||||
|
|
||||||
|
// 查询内存缓存
|
||||||
|
if (store && store.exp > now) {
|
||||||
|
return store;
|
||||||
|
}
|
||||||
|
|
||||||
|
// 查询storage缓存
|
||||||
|
store = await getBdauth();
|
||||||
|
if (store && store.exp > now) {
|
||||||
|
return store;
|
||||||
|
}
|
||||||
|
|
||||||
|
// 缓存没有或失效,查询接口
|
||||||
|
store = await getToken();
|
||||||
|
await setBdauth(store);
|
||||||
|
return store;
|
||||||
|
};
|
||||||
|
};
|
||||||
|
|
||||||
|
const bdAuth = _bdAuth();
|
||||||
|
|
||||||
|
export const genBaidu = async ({ text, from, to }) => {
|
||||||
|
const { token, gtk } = await bdAuth();
|
||||||
|
const sign = getSign(text, gtk);
|
||||||
|
const data = {
|
||||||
|
from,
|
||||||
|
to,
|
||||||
|
query: text,
|
||||||
|
simple_means_flag: 3,
|
||||||
|
sign,
|
||||||
|
token,
|
||||||
|
domain: "common",
|
||||||
|
ts: Date.now(),
|
||||||
|
};
|
||||||
|
|
||||||
|
const input = `${URL_BAIDU_TRAN}?from=${from}&to=${to}`;
|
||||||
|
const init = {
|
||||||
|
headers: {
|
||||||
|
"content-type": "application/x-www-form-urlencoded; charset=UTF-8",
|
||||||
|
},
|
||||||
|
method: "POST",
|
||||||
|
body: queryString.stringify(data),
|
||||||
|
};
|
||||||
|
|
||||||
|
return [input, init];
|
||||||
|
};
|
||||||
58
src/apis/deepl.js
Normal file
58
src/apis/deepl.js
Normal file
@@ -0,0 +1,58 @@
|
|||||||
|
import { URL_DEEPLFREE_TRAN } from "../config";
|
||||||
|
|
||||||
|
let id = 1e4 * Math.round(1e4 * Math.random());
|
||||||
|
|
||||||
|
export const genDeeplFree = ({ text, from, to }) => {
|
||||||
|
const iCount = (text.match(/[i]/g) || []).length + 1;
|
||||||
|
let timestamp = Date.now();
|
||||||
|
timestamp = timestamp + (iCount - (timestamp % iCount));
|
||||||
|
id++;
|
||||||
|
|
||||||
|
let body = JSON.stringify({
|
||||||
|
jsonrpc: "2.0",
|
||||||
|
method: "LMT_handle_texts",
|
||||||
|
params: {
|
||||||
|
splitting: "newlines",
|
||||||
|
lang: {
|
||||||
|
target_lang: to,
|
||||||
|
source_lang_user_selected: from,
|
||||||
|
},
|
||||||
|
commonJobParams: {
|
||||||
|
wasSpoken: false,
|
||||||
|
transcribe_as: "",
|
||||||
|
},
|
||||||
|
id,
|
||||||
|
timestamp,
|
||||||
|
texts: [
|
||||||
|
{
|
||||||
|
text,
|
||||||
|
requestAlternatives: 3,
|
||||||
|
},
|
||||||
|
],
|
||||||
|
},
|
||||||
|
});
|
||||||
|
|
||||||
|
body = body.replace(
|
||||||
|
'method":"',
|
||||||
|
(id + 3) % 13 === 0 || (id + 5) % 29 === 0 ? 'method" : "' : 'method": "'
|
||||||
|
);
|
||||||
|
|
||||||
|
const init = {
|
||||||
|
headers: {
|
||||||
|
"Content-Type": "application/json",
|
||||||
|
Accept: "*/*",
|
||||||
|
"x-app-os-name": "iOS",
|
||||||
|
"x-app-os-version": "16.3.0",
|
||||||
|
"Accept-Language": "en-US,en;q=0.9",
|
||||||
|
"Accept-Encoding": "gzip, deflate, br",
|
||||||
|
"x-app-device": "iPhone13,2",
|
||||||
|
"User-Agent": "DeepL-iOS/2.9.1 iOS 16.3.0 (iPhone13,2)",
|
||||||
|
"x-app-build": "510265",
|
||||||
|
"x-app-version": "2.9.1",
|
||||||
|
},
|
||||||
|
method: "POST",
|
||||||
|
body,
|
||||||
|
};
|
||||||
|
|
||||||
|
return [URL_DEEPLFREE_TRAN, init];
|
||||||
|
};
|
||||||
@@ -4,14 +4,20 @@ import {
|
|||||||
OPT_TRANS_GOOGLE,
|
OPT_TRANS_GOOGLE,
|
||||||
OPT_TRANS_MICROSOFT,
|
OPT_TRANS_MICROSOFT,
|
||||||
OPT_TRANS_DEEPL,
|
OPT_TRANS_DEEPL,
|
||||||
|
OPT_TRANS_DEEPLFREE,
|
||||||
|
OPT_TRANS_DEEPLX,
|
||||||
|
OPT_TRANS_BAIDU,
|
||||||
|
OPT_TRANS_TENCENT,
|
||||||
OPT_TRANS_OPENAI,
|
OPT_TRANS_OPENAI,
|
||||||
OPT_TRANS_CUSTOMIZE,
|
OPT_TRANS_CUSTOMIZE,
|
||||||
OPT_LANGS_SPECIAL,
|
URL_CACHE_TRAN,
|
||||||
PROMPT_PLACE_FROM,
|
|
||||||
PROMPT_PLACE_TO,
|
|
||||||
KV_SALT_SYNC,
|
KV_SALT_SYNC,
|
||||||
|
URL_BAIDU_LANGDETECT,
|
||||||
|
OPT_LANGS_BAIDU,
|
||||||
|
URL_TENCENT_TRANSMART,
|
||||||
|
OPT_LANGS_TENCENT,
|
||||||
|
OPT_LANGS_SPECIAL,
|
||||||
} from "../config";
|
} from "../config";
|
||||||
import { tryDetectLang } from "../libs";
|
|
||||||
import { sha256 } from "../libs/utils";
|
import { sha256 } from "../libs/utils";
|
||||||
|
|
||||||
/**
|
/**
|
||||||
@@ -21,7 +27,7 @@ import { sha256 } from "../libs/utils";
|
|||||||
* @param {*} data
|
* @param {*} data
|
||||||
* @returns
|
* @returns
|
||||||
*/
|
*/
|
||||||
export const apiSyncData = async (url, key, data, isBg = false) =>
|
export const apiSyncData = async (url, key, data) =>
|
||||||
fetchPolyfill(url, {
|
fetchPolyfill(url, {
|
||||||
headers: {
|
headers: {
|
||||||
"Content-type": "application/json",
|
"Content-type": "application/json",
|
||||||
@@ -29,214 +35,62 @@ export const apiSyncData = async (url, key, data, isBg = false) =>
|
|||||||
},
|
},
|
||||||
method: "POST",
|
method: "POST",
|
||||||
body: JSON.stringify(data),
|
body: JSON.stringify(data),
|
||||||
isBg,
|
|
||||||
});
|
});
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* 下载数据
|
* 下载数据
|
||||||
* @param {*} url
|
* @param {*} url
|
||||||
* @param {*} isBg
|
|
||||||
* @returns
|
* @returns
|
||||||
*/
|
*/
|
||||||
export const apiFetch = (url, isBg = false) => fetchPolyfill(url, { isBg });
|
export const apiFetch = (url) => fetchPolyfill(url);
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* 谷歌翻译
|
* 百度语言识别
|
||||||
* @param {*} text
|
* @param {*} text
|
||||||
* @param {*} to
|
|
||||||
* @param {*} from
|
|
||||||
* @returns
|
* @returns
|
||||||
*/
|
*/
|
||||||
const apiGoogleTranslate = async (
|
export const apiBaiduLangdetect = async (text) => {
|
||||||
translator,
|
const res = await fetchPolyfill(URL_BAIDU_LANGDETECT, {
|
||||||
text,
|
|
||||||
to,
|
|
||||||
from,
|
|
||||||
{ url, key, useCache = true }
|
|
||||||
) => {
|
|
||||||
const params = {
|
|
||||||
client: "gtx",
|
|
||||||
dt: "t",
|
|
||||||
dj: 1,
|
|
||||||
ie: "UTF-8",
|
|
||||||
sl: from,
|
|
||||||
tl: to,
|
|
||||||
q: text,
|
|
||||||
};
|
|
||||||
const input = `${url}?${queryString.stringify(params)}`;
|
|
||||||
const res = await fetchPolyfill(input, {
|
|
||||||
headers: {
|
|
||||||
"Content-type": "application/json",
|
|
||||||
},
|
|
||||||
useCache,
|
|
||||||
usePool: true,
|
|
||||||
translator,
|
|
||||||
token: key,
|
|
||||||
});
|
|
||||||
const trText = res.sentences.map((item) => item.trans).join(" ");
|
|
||||||
const isSame = to === res.src;
|
|
||||||
|
|
||||||
return [trText, isSame];
|
|
||||||
};
|
|
||||||
|
|
||||||
/**
|
|
||||||
* 微软翻译
|
|
||||||
* @param {*} text
|
|
||||||
* @param {*} to
|
|
||||||
* @param {*} from
|
|
||||||
* @returns
|
|
||||||
*/
|
|
||||||
const apiMicrosoftTranslate = async (
|
|
||||||
translator,
|
|
||||||
text,
|
|
||||||
to,
|
|
||||||
from,
|
|
||||||
{ url, useCache = true }
|
|
||||||
) => {
|
|
||||||
const params = {
|
|
||||||
from,
|
|
||||||
to,
|
|
||||||
"api-version": "3.0",
|
|
||||||
};
|
|
||||||
const input = `${url}?${queryString.stringify(params)}`;
|
|
||||||
const res = await fetchPolyfill(input, {
|
|
||||||
headers: {
|
headers: {
|
||||||
"Content-type": "application/json",
|
"Content-type": "application/json",
|
||||||
},
|
},
|
||||||
method: "POST",
|
method: "POST",
|
||||||
body: JSON.stringify([{ Text: text }]),
|
body: JSON.stringify({
|
||||||
useCache,
|
query: text,
|
||||||
usePool: true,
|
}),
|
||||||
translator,
|
useCache: true,
|
||||||
});
|
});
|
||||||
const trText = res[0].translations[0].text;
|
|
||||||
const isSame = to === res[0].detectedLanguage?.language;
|
|
||||||
|
|
||||||
return [trText, isSame];
|
if (res.error === 0) {
|
||||||
};
|
return OPT_LANGS_BAIDU.get(res.lan) ?? res.lan;
|
||||||
|
|
||||||
/**
|
|
||||||
* DeepL翻译
|
|
||||||
* @param {*} text
|
|
||||||
* @param {*} to
|
|
||||||
* @param {*} from
|
|
||||||
* @returns
|
|
||||||
*/
|
|
||||||
const apiDeepLTranslate = async (
|
|
||||||
translator,
|
|
||||||
text,
|
|
||||||
to,
|
|
||||||
from,
|
|
||||||
{ url, key, useCache = true }
|
|
||||||
) => {
|
|
||||||
const data = {
|
|
||||||
text: [text],
|
|
||||||
target_lang: to,
|
|
||||||
split_sentences: "0",
|
|
||||||
};
|
|
||||||
if (from) {
|
|
||||||
data.source_lang = from;
|
|
||||||
}
|
}
|
||||||
const res = await fetchPolyfill(url, {
|
|
||||||
headers: {
|
|
||||||
"Content-type": "application/json",
|
|
||||||
},
|
|
||||||
method: "POST",
|
|
||||||
body: JSON.stringify(data),
|
|
||||||
useCache,
|
|
||||||
usePool: true,
|
|
||||||
translator,
|
|
||||||
token: key,
|
|
||||||
});
|
|
||||||
const trText = res.translations.map((item) => item.text).join(" ");
|
|
||||||
const isSame = to === res.translations[0].detected_source_language;
|
|
||||||
|
|
||||||
return [trText, isSame];
|
return "";
|
||||||
};
|
};
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* OpenAI 翻译
|
* 腾讯语言识别
|
||||||
* @param {*} text
|
* @param {*} text
|
||||||
* @param {*} to
|
|
||||||
* @param {*} from
|
|
||||||
* @returns
|
* @returns
|
||||||
*/
|
*/
|
||||||
const apiOpenaiTranslate = async (
|
export const apiTencentLangdetect = async (text) => {
|
||||||
translator,
|
const body = JSON.stringify({
|
||||||
text,
|
header: {
|
||||||
to,
|
fn: "text_analysis",
|
||||||
from,
|
},
|
||||||
{ url, key, model, prompt, useCache = true }
|
text,
|
||||||
) => {
|
});
|
||||||
prompt = prompt
|
|
||||||
.replaceAll(PROMPT_PLACE_FROM, from)
|
const res = await fetchPolyfill(URL_TENCENT_TRANSMART, {
|
||||||
.replaceAll(PROMPT_PLACE_TO, to);
|
|
||||||
const res = await fetchPolyfill(url, {
|
|
||||||
headers: {
|
headers: {
|
||||||
"Content-type": "application/json",
|
"Content-type": "application/json",
|
||||||
},
|
},
|
||||||
method: "POST",
|
method: "POST",
|
||||||
body: JSON.stringify({
|
body,
|
||||||
model: model,
|
useCache: true,
|
||||||
messages: [
|
|
||||||
{
|
|
||||||
role: "system",
|
|
||||||
content: prompt,
|
|
||||||
},
|
|
||||||
{
|
|
||||||
role: "user",
|
|
||||||
content: text,
|
|
||||||
},
|
|
||||||
],
|
|
||||||
temperature: 0,
|
|
||||||
max_tokens: 256,
|
|
||||||
}),
|
|
||||||
useCache,
|
|
||||||
usePool: true,
|
|
||||||
translator,
|
|
||||||
token: key,
|
|
||||||
});
|
});
|
||||||
const trText = res?.choices?.[0].message.content;
|
|
||||||
const sLang = await tryDetectLang(text);
|
|
||||||
const tLang = await tryDetectLang(trText);
|
|
||||||
const isSame = text === trText || (sLang && tLang && sLang === tLang);
|
|
||||||
|
|
||||||
return [trText, isSame];
|
return OPT_LANGS_TENCENT.get(res.language) ?? res.language;
|
||||||
};
|
|
||||||
|
|
||||||
/**
|
|
||||||
* 自定义接口 翻译
|
|
||||||
* @param {*} text
|
|
||||||
* @param {*} to
|
|
||||||
* @param {*} from
|
|
||||||
* @returns
|
|
||||||
*/
|
|
||||||
const apiCustomTranslate = async (
|
|
||||||
translator,
|
|
||||||
text,
|
|
||||||
to,
|
|
||||||
from,
|
|
||||||
{ url, key, useCache = true }
|
|
||||||
) => {
|
|
||||||
const res = await fetchPolyfill(url, {
|
|
||||||
headers: {
|
|
||||||
"Content-type": "application/json",
|
|
||||||
},
|
|
||||||
method: "POST",
|
|
||||||
body: JSON.stringify({
|
|
||||||
text,
|
|
||||||
from,
|
|
||||||
to,
|
|
||||||
}),
|
|
||||||
useCache,
|
|
||||||
usePool: true,
|
|
||||||
translator,
|
|
||||||
token: key,
|
|
||||||
});
|
|
||||||
const trText = res.text;
|
|
||||||
const isSame = to === res.from;
|
|
||||||
|
|
||||||
return [trText, isSame];
|
|
||||||
};
|
};
|
||||||
|
|
||||||
/**
|
/**
|
||||||
@@ -244,29 +98,91 @@ const apiCustomTranslate = async (
|
|||||||
* @param {*} param0
|
* @param {*} param0
|
||||||
* @returns
|
* @returns
|
||||||
*/
|
*/
|
||||||
export const apiTranslate = ({
|
export const apiTranslate = async ({
|
||||||
translator,
|
translator,
|
||||||
text,
|
text,
|
||||||
fromLang,
|
fromLang,
|
||||||
toLang,
|
toLang,
|
||||||
apiSetting,
|
apiSetting = {},
|
||||||
|
useCache = true,
|
||||||
|
usePool = true,
|
||||||
}) => {
|
}) => {
|
||||||
const from = OPT_LANGS_SPECIAL[translator]?.get(fromLang) ?? fromLang;
|
let trText = "";
|
||||||
const to = OPT_LANGS_SPECIAL[translator]?.get(toLang) ?? toLang;
|
let isSame = false;
|
||||||
const callApi = (api) => api(translator, text, to, from, apiSetting);
|
|
||||||
|
const from =
|
||||||
|
OPT_LANGS_SPECIAL[translator].get(fromLang) ??
|
||||||
|
OPT_LANGS_SPECIAL[translator].get("auto");
|
||||||
|
const to = OPT_LANGS_SPECIAL[translator].get(toLang);
|
||||||
|
if (!text || !to) {
|
||||||
|
console.log(`[trans] target lang: ${toLang} not support`);
|
||||||
|
return [trText, isSame];
|
||||||
|
}
|
||||||
|
|
||||||
|
const cacheOpts = {
|
||||||
|
translator,
|
||||||
|
text,
|
||||||
|
fromLang,
|
||||||
|
toLang,
|
||||||
|
};
|
||||||
|
|
||||||
|
const transOpts = {
|
||||||
|
translator,
|
||||||
|
text,
|
||||||
|
from,
|
||||||
|
to,
|
||||||
|
};
|
||||||
|
|
||||||
|
const res = await fetchPolyfill(
|
||||||
|
`${URL_CACHE_TRAN}?${queryString.stringify(cacheOpts)}`,
|
||||||
|
{
|
||||||
|
useCache,
|
||||||
|
usePool,
|
||||||
|
transOpts,
|
||||||
|
apiSetting,
|
||||||
|
}
|
||||||
|
);
|
||||||
|
|
||||||
switch (translator) {
|
switch (translator) {
|
||||||
case OPT_TRANS_GOOGLE:
|
case OPT_TRANS_GOOGLE:
|
||||||
return callApi(apiGoogleTranslate);
|
trText = res.sentences.map((item) => item.trans).join(" ");
|
||||||
|
isSame = to === res.src;
|
||||||
|
break;
|
||||||
case OPT_TRANS_MICROSOFT:
|
case OPT_TRANS_MICROSOFT:
|
||||||
return callApi(apiMicrosoftTranslate);
|
trText = res[0].translations.map((item) => item.text).join(" ");
|
||||||
|
isSame = text === trText;
|
||||||
|
break;
|
||||||
case OPT_TRANS_DEEPL:
|
case OPT_TRANS_DEEPL:
|
||||||
return callApi(apiDeepLTranslate);
|
trText = res.translations.map((item) => item.text).join(" ");
|
||||||
|
isSame = to === res.translations[0].detected_source_language;
|
||||||
|
break;
|
||||||
|
case OPT_TRANS_DEEPLFREE:
|
||||||
|
trText = res.result?.texts.map((item) => item.text).join(" ");
|
||||||
|
isSame = to === res.result?.lang;
|
||||||
|
break;
|
||||||
|
case OPT_TRANS_DEEPLX:
|
||||||
|
trText = res.data;
|
||||||
|
isSame = to === res.source_lang;
|
||||||
|
break;
|
||||||
|
case OPT_TRANS_BAIDU:
|
||||||
|
trText = res.trans_result?.data.map((item) => item.dst).join(" ");
|
||||||
|
isSame = res.trans_result?.to === res.trans_result?.from;
|
||||||
|
break;
|
||||||
|
case OPT_TRANS_TENCENT:
|
||||||
|
trText = res.auto_translation;
|
||||||
|
isSame = text === trText;
|
||||||
|
break;
|
||||||
case OPT_TRANS_OPENAI:
|
case OPT_TRANS_OPENAI:
|
||||||
return callApi(apiOpenaiTranslate);
|
trText = res?.choices?.[0].message.content;
|
||||||
|
isSame = text === trText;
|
||||||
|
break;
|
||||||
case OPT_TRANS_CUSTOMIZE:
|
case OPT_TRANS_CUSTOMIZE:
|
||||||
return callApi(apiCustomTranslate);
|
trText = res.text;
|
||||||
|
isSame = to === res.from;
|
||||||
|
break;
|
||||||
default:
|
default:
|
||||||
return ["", false];
|
break;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
return [trText, isSame, res];
|
||||||
};
|
};
|
||||||
|
|||||||
@@ -4,6 +4,8 @@ import {
|
|||||||
MSG_FETCH_LIMIT,
|
MSG_FETCH_LIMIT,
|
||||||
MSG_FETCH_CLEAR,
|
MSG_FETCH_CLEAR,
|
||||||
MSG_TRANS_TOGGLE,
|
MSG_TRANS_TOGGLE,
|
||||||
|
MSG_OPEN_OPTIONS,
|
||||||
|
MSG_SAVE_RULE,
|
||||||
MSG_TRANS_TOGGLE_STYLE,
|
MSG_TRANS_TOGGLE_STYLE,
|
||||||
CMD_TOGGLE_TRANSLATE,
|
CMD_TOGGLE_TRANSLATE,
|
||||||
CMD_TOGGLE_STYLE,
|
CMD_TOGGLE_STYLE,
|
||||||
@@ -15,6 +17,9 @@ import { fetchData, fetchPool } from "./libs/fetch";
|
|||||||
import { sendTabMsg } from "./libs/msg";
|
import { sendTabMsg } from "./libs/msg";
|
||||||
import { trySyncAllSubRules } from "./libs/subRules";
|
import { trySyncAllSubRules } from "./libs/subRules";
|
||||||
import { tryClearCaches } from "./libs";
|
import { tryClearCaches } from "./libs";
|
||||||
|
import { saveRule } from "./libs/rules";
|
||||||
|
|
||||||
|
globalThis.ContextType = "BACKGROUND";
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* 插件安装
|
* 插件安装
|
||||||
@@ -30,7 +35,7 @@ browser.runtime.onStartup.addListener(async () => {
|
|||||||
console.log("browser onStartup");
|
console.log("browser onStartup");
|
||||||
|
|
||||||
// 同步数据
|
// 同步数据
|
||||||
await trySyncSettingAndRules(true);
|
await trySyncSettingAndRules();
|
||||||
|
|
||||||
// 清除缓存
|
// 清除缓存
|
||||||
const setting = await getSettingWithDefault();
|
const setting = await getSettingWithDefault();
|
||||||
@@ -39,7 +44,7 @@ browser.runtime.onStartup.addListener(async () => {
|
|||||||
}
|
}
|
||||||
|
|
||||||
// 同步订阅规则
|
// 同步订阅规则
|
||||||
trySyncAllSubRules(setting, true);
|
trySyncAllSubRules(setting);
|
||||||
});
|
});
|
||||||
|
|
||||||
/**
|
/**
|
||||||
@@ -67,6 +72,12 @@ browser.runtime.onMessage.addListener(
|
|||||||
fetchPool.clear();
|
fetchPool.clear();
|
||||||
sendResponse({ data: "ok" });
|
sendResponse({ data: "ok" });
|
||||||
break;
|
break;
|
||||||
|
case MSG_OPEN_OPTIONS:
|
||||||
|
browser.runtime.openOptionsPage();
|
||||||
|
break;
|
||||||
|
case MSG_SAVE_RULE:
|
||||||
|
saveRule(args);
|
||||||
|
break;
|
||||||
default:
|
default:
|
||||||
sendResponse({ error: `message action is unavailable: ${action}` });
|
sendResponse({ error: `message action is unavailable: ${action}` });
|
||||||
}
|
}
|
||||||
|
|||||||
129
src/common.js
Normal file
129
src/common.js
Normal file
@@ -0,0 +1,129 @@
|
|||||||
|
import React from "react";
|
||||||
|
import ReactDOM from "react-dom/client";
|
||||||
|
import Action from "./views/Action";
|
||||||
|
import createCache from "@emotion/cache";
|
||||||
|
import { CacheProvider } from "@emotion/react";
|
||||||
|
import {
|
||||||
|
MSG_TRANS_TOGGLE,
|
||||||
|
MSG_TRANS_TOGGLE_STYLE,
|
||||||
|
MSG_TRANS_GETRULE,
|
||||||
|
MSG_TRANS_PUTRULE,
|
||||||
|
APP_LCNAME,
|
||||||
|
DEFAULT_TRANBOX_SETTING,
|
||||||
|
} from "./config";
|
||||||
|
import { getRulesWithDefault, getFabWithDefault } from "./libs/storage";
|
||||||
|
import { Translator } from "./libs/translator";
|
||||||
|
import { sendIframeMsg, sendParentMsg } from "./libs/iframe";
|
||||||
|
import { matchRule } from "./libs/rules";
|
||||||
|
import Slection from "./views/Selection";
|
||||||
|
|
||||||
|
export async function runTranslator(setting) {
|
||||||
|
const href = document.location.href;
|
||||||
|
const rules = await getRulesWithDefault();
|
||||||
|
const rule = await matchRule(rules, href, setting);
|
||||||
|
const translator = new Translator(rule, setting);
|
||||||
|
|
||||||
|
return { translator, rule };
|
||||||
|
}
|
||||||
|
|
||||||
|
export function runIframe(setting) {
|
||||||
|
let translator;
|
||||||
|
window.addEventListener("message", (e) => {
|
||||||
|
const { action, args } = e.data || {};
|
||||||
|
switch (action) {
|
||||||
|
case MSG_TRANS_TOGGLE:
|
||||||
|
translator?.toggle();
|
||||||
|
break;
|
||||||
|
case MSG_TRANS_TOGGLE_STYLE:
|
||||||
|
translator?.toggleStyle();
|
||||||
|
break;
|
||||||
|
case MSG_TRANS_PUTRULE:
|
||||||
|
if (!translator) {
|
||||||
|
translator = new Translator(args, setting);
|
||||||
|
} else {
|
||||||
|
translator.updateRule(args || {});
|
||||||
|
}
|
||||||
|
break;
|
||||||
|
default:
|
||||||
|
}
|
||||||
|
});
|
||||||
|
sendParentMsg(MSG_TRANS_GETRULE);
|
||||||
|
}
|
||||||
|
|
||||||
|
export async function showFab(translator) {
|
||||||
|
const fab = await getFabWithDefault();
|
||||||
|
if (fab.isHide) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
const $action = document.createElement("div");
|
||||||
|
$action.setAttribute("id", APP_LCNAME);
|
||||||
|
document.body.parentElement.appendChild($action);
|
||||||
|
const shadowContainer = $action.attachShadow({ mode: "closed" });
|
||||||
|
const emotionRoot = document.createElement("style");
|
||||||
|
const shadowRootElement = document.createElement("div");
|
||||||
|
shadowContainer.appendChild(emotionRoot);
|
||||||
|
shadowContainer.appendChild(shadowRootElement);
|
||||||
|
const cache = createCache({
|
||||||
|
key: APP_LCNAME,
|
||||||
|
prepend: true,
|
||||||
|
container: emotionRoot,
|
||||||
|
});
|
||||||
|
ReactDOM.createRoot(shadowRootElement).render(
|
||||||
|
<React.StrictMode>
|
||||||
|
<CacheProvider value={cache}>
|
||||||
|
<Action translator={translator} fab={fab} />
|
||||||
|
</CacheProvider>
|
||||||
|
</React.StrictMode>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
export function showTransbox({
|
||||||
|
tranboxSetting = DEFAULT_TRANBOX_SETTING,
|
||||||
|
transApis,
|
||||||
|
}) {
|
||||||
|
if (!tranboxSetting?.transOpen) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
const $tranbox = document.createElement("div");
|
||||||
|
$tranbox.setAttribute("id", "kiss-transbox");
|
||||||
|
document.body.parentElement.appendChild($tranbox);
|
||||||
|
const shadowContainer = $tranbox.attachShadow({ mode: "closed" });
|
||||||
|
const emotionRoot = document.createElement("style");
|
||||||
|
const shadowRootElement = document.createElement("div");
|
||||||
|
shadowContainer.appendChild(emotionRoot);
|
||||||
|
shadowContainer.appendChild(shadowRootElement);
|
||||||
|
const cache = createCache({
|
||||||
|
key: "kiss-transbox",
|
||||||
|
prepend: true,
|
||||||
|
container: emotionRoot,
|
||||||
|
});
|
||||||
|
ReactDOM.createRoot(shadowRootElement).render(
|
||||||
|
<React.StrictMode>
|
||||||
|
<CacheProvider value={cache}>
|
||||||
|
<Slection tranboxSetting={tranboxSetting} transApis={transApis} />
|
||||||
|
</CacheProvider>
|
||||||
|
</React.StrictMode>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
export function windowListener(rule) {
|
||||||
|
window.addEventListener("message", (e) => {
|
||||||
|
const { action } = e.data || {};
|
||||||
|
switch (action) {
|
||||||
|
case MSG_TRANS_GETRULE:
|
||||||
|
sendIframeMsg(MSG_TRANS_PUTRULE, rule);
|
||||||
|
break;
|
||||||
|
default:
|
||||||
|
}
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
export function showErr(err) {
|
||||||
|
console.error("[KISS-Translator]", err);
|
||||||
|
const $err = document.createElement("div");
|
||||||
|
$err.innerText = `KISS-Translator: ${err.message}`;
|
||||||
|
$err.style.cssText = "background:red; color:#fff;";
|
||||||
|
document.body.prepend($err);
|
||||||
|
}
|
||||||
@@ -50,20 +50,20 @@ const customApiHelpZH = `/// 自定义翻译源接口说明
|
|||||||
method: "POST",
|
method: "POST",
|
||||||
headers: {
|
headers: {
|
||||||
"Content-type": "application/json",
|
"Content-type": "application/json",
|
||||||
"Authorization" = "Bearer {{YOUR_KEY}}"
|
"Authorization": "Bearer {{YOUR_KEY}}",
|
||||||
},
|
},
|
||||||
body: {
|
body: {
|
||||||
text, // 需要翻译的文字
|
text: "", // 需要翻译的文字
|
||||||
from, // 源语言,可能为空,表示需要接口自动识别语言
|
from: "", // 源语言,可能为空,表示需要接口自动识别语言
|
||||||
to, // 目标语言
|
to: "", // 目标语言
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
// 返回(Response)数据需符合下面的JSON规范
|
// 返回(Response)数据需符合下面的JSON规范
|
||||||
{
|
{
|
||||||
text, // 翻译后的文字
|
text: "", // 翻译后的文字
|
||||||
from, // 识别的源语言
|
from: "", // 识别的源语言
|
||||||
to, // 目标语言(可选)
|
to: "", // 目标语言(可选)
|
||||||
}
|
}
|
||||||
|
|
||||||
// 支持的语言代码如下
|
// 支持的语言代码如下
|
||||||
@@ -78,20 +78,20 @@ const customApiHelpEN = `/// Custom translation source interface description
|
|||||||
method: "POST",
|
method: "POST",
|
||||||
headers: {
|
headers: {
|
||||||
"Content-type": "application/json",
|
"Content-type": "application/json",
|
||||||
"Authorization" = "Bearer {{YOUR_KEY}}"
|
"Authorization": "Bearer {{YOUR_KEY}}",
|
||||||
},
|
},
|
||||||
body: {
|
body: {
|
||||||
text, // text to be translated
|
text: "", // text to be translated
|
||||||
from, // Source language, may be empty
|
from: "", // Source language, may be empty
|
||||||
to, // Target language
|
to: "", // Target language
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
// The returned data must conform to the following JSON specification
|
// The returned data must conform to the following JSON specification
|
||||||
{
|
{
|
||||||
text, // translated text
|
text: "", // translated text
|
||||||
from, // Recognized source language
|
from: "", // Recognized source language
|
||||||
to, // Target language (optional)
|
to: "", // Target language (optional)
|
||||||
}
|
}
|
||||||
|
|
||||||
// The supported language codes are as follows
|
// The supported language codes are as follows
|
||||||
@@ -435,10 +435,18 @@ export const I18N = {
|
|||||||
zh: `重启浏览器时清除缓存`,
|
zh: `重启浏览器时清除缓存`,
|
||||||
en: `Clear cache when restarting browser`,
|
en: `Clear cache when restarting browser`,
|
||||||
},
|
},
|
||||||
|
data_sync_type: {
|
||||||
|
zh: `数据同步方式`,
|
||||||
|
en: `Data Sync Type`,
|
||||||
|
},
|
||||||
data_sync_url: {
|
data_sync_url: {
|
||||||
zh: `数据同步接口`,
|
zh: `数据同步接口`,
|
||||||
en: `Data Sync API`,
|
en: `Data Sync API`,
|
||||||
},
|
},
|
||||||
|
data_sync_user: {
|
||||||
|
zh: `数据同步账户`,
|
||||||
|
en: `Data Sync User`,
|
||||||
|
},
|
||||||
data_sync_key: {
|
data_sync_key: {
|
||||||
zh: `数据同步密钥`,
|
zh: `数据同步密钥`,
|
||||||
en: `Data Sync Key`,
|
en: `Data Sync Key`,
|
||||||
@@ -460,8 +468,8 @@ export const I18N = {
|
|||||||
en: `Sorry, something went wrong!`,
|
en: `Sorry, something went wrong!`,
|
||||||
},
|
},
|
||||||
error_sync_setting: {
|
error_sync_setting: {
|
||||||
zh: `您的同步设置未填写,无法在线分享。`,
|
zh: `您的同步类型必须为“KISS-Worker”,且需填写完整`,
|
||||||
en: `Your sync settings are missing and cannot be shared online.`,
|
en: `Your sync type must be "KISS-Worker" and must be filled in completely`,
|
||||||
},
|
},
|
||||||
click_test: {
|
click_test: {
|
||||||
zh: `点击测试`,
|
zh: `点击测试`,
|
||||||
@@ -547,4 +555,88 @@ export const I18N = {
|
|||||||
zh: `全局规则`,
|
zh: `全局规则`,
|
||||||
en: `Global Rule`,
|
en: `Global Rule`,
|
||||||
},
|
},
|
||||||
|
input_setting: {
|
||||||
|
zh: `输入框设置`,
|
||||||
|
en: `Input Box Setting`,
|
||||||
|
},
|
||||||
|
input_box_translation: {
|
||||||
|
zh: `启用输入框翻译`,
|
||||||
|
en: `Input Box Translation`,
|
||||||
|
},
|
||||||
|
input_selector: {
|
||||||
|
zh: `输入框选择器`,
|
||||||
|
en: `Input Selector`,
|
||||||
|
},
|
||||||
|
input_selector_helper: {
|
||||||
|
zh: `用于输入框翻译。`,
|
||||||
|
en: `Used for input box translation.`,
|
||||||
|
},
|
||||||
|
trigger_trans_shortcut: {
|
||||||
|
zh: `触发翻译快捷键`,
|
||||||
|
en: `Trigger Translation Shortcut Keys`,
|
||||||
|
},
|
||||||
|
trigger_trans_shortcut_help: {
|
||||||
|
zh: `默认为单击“AltLeft+KeyI”`,
|
||||||
|
en: `Default is "AltLeft+KeyI"`,
|
||||||
|
},
|
||||||
|
shortcut_press_count: {
|
||||||
|
zh: `快捷键连击次数`,
|
||||||
|
en: `Shortcut Press Number`,
|
||||||
|
},
|
||||||
|
combo_timeout: {
|
||||||
|
zh: `连击超时时间 (10-1000ms)`,
|
||||||
|
en: `Combo Timeout (10-1000ms)`,
|
||||||
|
},
|
||||||
|
input_trans_start_sign: {
|
||||||
|
zh: `翻译起始标识`,
|
||||||
|
en: `Translation Start Sign`,
|
||||||
|
},
|
||||||
|
input_trans_start_sign_help: {
|
||||||
|
zh: `标识后面可以加目标语言代码,如: “/en 你好”、“/zh hello”`,
|
||||||
|
en: `The target language code can be added after the sign, such as: "/en 你好", "/zh hello"`,
|
||||||
|
},
|
||||||
|
detect_lang_remote: {
|
||||||
|
zh: `远程语言检测`,
|
||||||
|
en: `Remote language detection`,
|
||||||
|
},
|
||||||
|
detect_lang_remote_help: {
|
||||||
|
zh: `启用后检测准确度增加,但会降低翻译速度,请酌情开启`,
|
||||||
|
en: `After enabling, the detection accuracy will increase, but it will reduce the translation speed. Please enable it as appropriate.`,
|
||||||
|
},
|
||||||
|
disable: {
|
||||||
|
zh: `禁用`,
|
||||||
|
en: `Disable`,
|
||||||
|
},
|
||||||
|
enable: {
|
||||||
|
zh: `启用`,
|
||||||
|
en: `Enable`,
|
||||||
|
},
|
||||||
|
selection_translate: {
|
||||||
|
zh: `划词翻译`,
|
||||||
|
en: `Selection Translate`,
|
||||||
|
},
|
||||||
|
toggle_selection_translate: {
|
||||||
|
zh: `启用划词翻译`,
|
||||||
|
en: `Use Selection Translate`,
|
||||||
|
},
|
||||||
|
trigger_tranbox_shortcut: {
|
||||||
|
zh: `显示翻译框快捷键`,
|
||||||
|
en: `Toggle Translate Box Shortcut`,
|
||||||
|
},
|
||||||
|
tranbtn_offset_x: {
|
||||||
|
zh: `翻译按钮偏移(X)`,
|
||||||
|
en: `Translate Button Offset (X)`,
|
||||||
|
},
|
||||||
|
tranbtn_offset_y: {
|
||||||
|
zh: `翻译按钮偏移(Y)`,
|
||||||
|
en: `Translate Button Offset (Y)`,
|
||||||
|
},
|
||||||
|
translated_text: {
|
||||||
|
zh: `译文`,
|
||||||
|
en: `Translated Text`,
|
||||||
|
},
|
||||||
|
original_text: {
|
||||||
|
zh: `原文`,
|
||||||
|
en: `Original Text`,
|
||||||
|
},
|
||||||
};
|
};
|
||||||
|
|||||||
@@ -20,6 +20,7 @@ export {
|
|||||||
};
|
};
|
||||||
|
|
||||||
export const STOKEY_MSAUTH = `${APP_NAME}_msauth`;
|
export const STOKEY_MSAUTH = `${APP_NAME}_msauth`;
|
||||||
|
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_SYNC = `${APP_NAME}_sync`;
|
export const STOKEY_SYNC = `${APP_NAME}_sync`;
|
||||||
@@ -38,9 +39,9 @@ export const CLIENT_FIREFOX = "firefox";
|
|||||||
export const CLIENT_USERSCRIPT = "userscript";
|
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 = "KT_RULES";
|
export const KV_RULES_KEY = "kiss-rules.json";
|
||||||
export const KV_RULES_SHARE_KEY = "KT_RULES_SHARE";
|
export const KV_RULES_SHARE_KEY = "kiss-rules-share.json";
|
||||||
export const KV_SETTING_KEY = "KT_SETTING";
|
export const KV_SETTING_KEY = "kiss-setting.json";
|
||||||
export const KV_SALT_SYNC = "KISS-Translator-SYNC";
|
export const KV_SALT_SYNC = "KISS-Translator-SYNC";
|
||||||
export const KV_SALT_SHARE = "KISS-Translator-SHARE";
|
export const KV_SALT_SHARE = "KISS-Translator-SHARE";
|
||||||
|
|
||||||
@@ -49,6 +50,8 @@ export const CACHE_NAME = `${APP_NAME}_cache`;
|
|||||||
export const MSG_FETCH = "fetch";
|
export const MSG_FETCH = "fetch";
|
||||||
export const MSG_FETCH_LIMIT = "fetch_limit";
|
export const MSG_FETCH_LIMIT = "fetch_limit";
|
||||||
export const MSG_FETCH_CLEAR = "fetch_clear";
|
export const MSG_FETCH_CLEAR = "fetch_clear";
|
||||||
|
export const MSG_OPEN_OPTIONS = "open_options";
|
||||||
|
export const MSG_SAVE_RULE = "save_rule";
|
||||||
export const MSG_TRANS_TOGGLE = "trans_toggle";
|
export const MSG_TRANS_TOGGLE = "trans_toggle";
|
||||||
export const MSG_TRANS_TOGGLE_STYLE = "trans_toggle_style";
|
export const MSG_TRANS_TOGGLE_STYLE = "trans_toggle_style";
|
||||||
export const MSG_TRANS_GETRULE = "trans_getrule";
|
export const MSG_TRANS_GETRULE = "trans_getrule";
|
||||||
@@ -65,17 +68,34 @@ export const URL_KISS_RULES_NEW_ISSUE =
|
|||||||
"https://github.com/fishjar/kiss-rules/issues/new";
|
"https://github.com/fishjar/kiss-rules/issues/new";
|
||||||
export const URL_RAW_PREFIX =
|
export const URL_RAW_PREFIX =
|
||||||
"https://raw.githubusercontent.com/fishjar/kiss-translator/master";
|
"https://raw.githubusercontent.com/fishjar/kiss-translator/master";
|
||||||
|
|
||||||
|
export const URL_CACHE_TRAN = `https://${APP_LCNAME}/translate`;
|
||||||
|
export const URL_MICROSOFT_TRAN =
|
||||||
|
"https://api-edge.cognitive.microsofttranslator.com/translate";
|
||||||
export const URL_MICROSOFT_AUTH = "https://edge.microsoft.com/translate/auth";
|
export const URL_MICROSOFT_AUTH = "https://edge.microsoft.com/translate/auth";
|
||||||
|
export const URL_BAIDU_LANGDETECT = "https://fanyi.baidu.com/langdetect";
|
||||||
|
export const URL_BAIDU_WEB = "https://fanyi.baidu.com/";
|
||||||
|
export const URL_BAIDU_TRAN = "https://fanyi.baidu.com/v2transapi";
|
||||||
|
export const URL_DEEPLFREE_TRAN = "https://www2.deepl.com/jsonrpc";
|
||||||
|
export const URL_TENCENT_TRANSMART = "https://transmart.qq.com/api/imt";
|
||||||
|
|
||||||
export const OPT_TRANS_GOOGLE = "Google";
|
export const OPT_TRANS_GOOGLE = "Google";
|
||||||
export const OPT_TRANS_MICROSOFT = "Microsoft";
|
export const OPT_TRANS_MICROSOFT = "Microsoft";
|
||||||
export const OPT_TRANS_DEEPL = "DeepL";
|
export const OPT_TRANS_DEEPL = "DeepL";
|
||||||
|
export const OPT_TRANS_DEEPLX = "DeepLX";
|
||||||
|
export const OPT_TRANS_DEEPLFREE = "DeepLFree";
|
||||||
|
export const OPT_TRANS_BAIDU = "Baidu";
|
||||||
|
export const OPT_TRANS_TENCENT = "Tencent";
|
||||||
export const OPT_TRANS_OPENAI = "OpenAI";
|
export const OPT_TRANS_OPENAI = "OpenAI";
|
||||||
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,
|
||||||
OPT_TRANS_MICROSOFT,
|
OPT_TRANS_MICROSOFT,
|
||||||
OPT_TRANS_DEEPL,
|
OPT_TRANS_DEEPL,
|
||||||
|
OPT_TRANS_DEEPLFREE,
|
||||||
|
OPT_TRANS_DEEPLX,
|
||||||
|
OPT_TRANS_BAIDU,
|
||||||
|
OPT_TRANS_TENCENT,
|
||||||
OPT_TRANS_OPENAI,
|
OPT_TRANS_OPENAI,
|
||||||
OPT_TRANS_CUSTOMIZE,
|
OPT_TRANS_CUSTOMIZE,
|
||||||
];
|
];
|
||||||
@@ -121,7 +141,9 @@ export const OPT_LANGS_TO = [
|
|||||||
];
|
];
|
||||||
export const OPT_LANGS_FROM = [["auto", "Auto-detect"], ...OPT_LANGS_TO];
|
export const OPT_LANGS_FROM = [["auto", "Auto-detect"], ...OPT_LANGS_TO];
|
||||||
export const OPT_LANGS_SPECIAL = {
|
export const OPT_LANGS_SPECIAL = {
|
||||||
|
[OPT_TRANS_GOOGLE]: new Map(OPT_LANGS_FROM.map(([key]) => [key, key])),
|
||||||
[OPT_TRANS_MICROSOFT]: new Map([
|
[OPT_TRANS_MICROSOFT]: new Map([
|
||||||
|
...OPT_LANGS_FROM.map(([key]) => [key, key]),
|
||||||
["auto", ""],
|
["auto", ""],
|
||||||
["zh-CN", "zh-Hans"],
|
["zh-CN", "zh-Hans"],
|
||||||
["zh-TW", "zh-Hant"],
|
["zh-TW", "zh-Hant"],
|
||||||
@@ -132,11 +154,89 @@ export const OPT_LANGS_SPECIAL = {
|
|||||||
["zh-CN", "ZH"],
|
["zh-CN", "ZH"],
|
||||||
["zh-TW", "ZH"],
|
["zh-TW", "ZH"],
|
||||||
]),
|
]),
|
||||||
|
[OPT_TRANS_DEEPLFREE]: new Map([
|
||||||
|
...OPT_LANGS_FROM.map(([key]) => [key, key.toUpperCase()]),
|
||||||
|
["auto", "auto"],
|
||||||
|
["zh-CN", "ZH"],
|
||||||
|
["zh-TW", "ZH"],
|
||||||
|
]),
|
||||||
|
[OPT_TRANS_DEEPLX]: new Map([
|
||||||
|
...OPT_LANGS_FROM.map(([key]) => [key, key.toUpperCase()]),
|
||||||
|
["auto", ""],
|
||||||
|
["zh-CN", "ZH"],
|
||||||
|
["zh-TW", "ZH"],
|
||||||
|
]),
|
||||||
|
[OPT_TRANS_BAIDU]: new Map([
|
||||||
|
...OPT_LANGS_FROM.map(([key]) => [key, key]),
|
||||||
|
["zh-CN", "zh"],
|
||||||
|
["zh-TW", "cht"],
|
||||||
|
["ar", "ara"],
|
||||||
|
["bg", "bul"],
|
||||||
|
["ca", "cat"],
|
||||||
|
["hr", "hrv"],
|
||||||
|
["da", "dan"],
|
||||||
|
["fi", "fin"],
|
||||||
|
["fr", "fra"],
|
||||||
|
["hi", "mai"],
|
||||||
|
["ja", "jp"],
|
||||||
|
["ko", "kor"],
|
||||||
|
["ms", "may"],
|
||||||
|
["mt", "mlt"],
|
||||||
|
["nb", "nor"],
|
||||||
|
["ro", "rom"],
|
||||||
|
["ru", "ru"],
|
||||||
|
["sl", "slo"],
|
||||||
|
["es", "spa"],
|
||||||
|
["sv", "swe"],
|
||||||
|
["ta", "tam"],
|
||||||
|
["te", "tel"],
|
||||||
|
["uk", "ukr"],
|
||||||
|
["vi", "vie"],
|
||||||
|
]),
|
||||||
|
[OPT_TRANS_TENCENT]: new Map([
|
||||||
|
["auto", "auto"],
|
||||||
|
["zh-CN", "zh"],
|
||||||
|
["zh-TW", "zh"],
|
||||||
|
["en", "en"],
|
||||||
|
["ar", "ar"],
|
||||||
|
["de", "de"],
|
||||||
|
["ru", "ru"],
|
||||||
|
["fr", "fr"],
|
||||||
|
["fi", "fil"],
|
||||||
|
["ko", "ko"],
|
||||||
|
["ms", "ms"],
|
||||||
|
["pt", "pt"],
|
||||||
|
["ja", "ja"],
|
||||||
|
["th", "th"],
|
||||||
|
["tr", "tr"],
|
||||||
|
["es", "es"],
|
||||||
|
["it", "it"],
|
||||||
|
["hi", "hi"],
|
||||||
|
["id", "id"],
|
||||||
|
["vi", "vi"],
|
||||||
|
]),
|
||||||
[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_CUSTOMIZE]: new Map([["auto", ""]]),
|
[OPT_TRANS_CUSTOMIZE]: new Map([
|
||||||
|
...OPT_LANGS_FROM.map(([key]) => [key, key]),
|
||||||
|
["auto", ""],
|
||||||
|
]),
|
||||||
};
|
};
|
||||||
|
export const OPT_LANGS_LIST = OPT_LANGS_TO.map(([lang]) => lang);
|
||||||
|
export const OPT_LANGS_BAIDU = new Map(
|
||||||
|
Array.from(OPT_LANGS_SPECIAL[OPT_TRANS_BAIDU].entries()).map(([k, v]) => [
|
||||||
|
v,
|
||||||
|
k,
|
||||||
|
])
|
||||||
|
);
|
||||||
|
export const OPT_LANGS_TENCENT = new Map(
|
||||||
|
Array.from(OPT_LANGS_SPECIAL[OPT_TRANS_TENCENT].entries()).map(([k, v]) => [
|
||||||
|
v,
|
||||||
|
k,
|
||||||
|
])
|
||||||
|
);
|
||||||
|
OPT_LANGS_TENCENT.set("zh", "zh-CN");
|
||||||
|
|
||||||
export const OPT_STYLE_NONE = "style_none"; // 无
|
export const OPT_STYLE_NONE = "style_none"; // 无
|
||||||
export const OPT_STYLE_LINE = "under_line"; // 下划线
|
export const OPT_STYLE_LINE = "under_line"; // 下划线
|
||||||
@@ -198,6 +298,32 @@ export const GLOBLA_RULE = {
|
|||||||
textDiyStyle: "",
|
textDiyStyle: "",
|
||||||
};
|
};
|
||||||
|
|
||||||
|
// 输入框翻译
|
||||||
|
export const OPT_INPUT_TRANS_SIGNS = ["/", "//", "\\", "\\\\", ">", ">>"];
|
||||||
|
export const DEFAULT_INPUT_SHORTCUT = ["AltLeft", "KeyI"];
|
||||||
|
export const DEFAULT_INPUT_RULE = {
|
||||||
|
transOpen: true,
|
||||||
|
translator: OPT_TRANS_MICROSOFT,
|
||||||
|
fromLang: "auto",
|
||||||
|
toLang: "en",
|
||||||
|
triggerShortcut: DEFAULT_INPUT_SHORTCUT,
|
||||||
|
triggerCount: 1,
|
||||||
|
triggerTime: 200,
|
||||||
|
transSign: OPT_INPUT_TRANS_SIGNS[0],
|
||||||
|
};
|
||||||
|
|
||||||
|
// 划词翻译
|
||||||
|
export const DEFAULT_TRANBOX_SHORTCUT = ["AltLeft", "KeyB"];
|
||||||
|
export const DEFAULT_TRANBOX_SETTING = {
|
||||||
|
transOpen: true,
|
||||||
|
translator: OPT_TRANS_MICROSOFT,
|
||||||
|
fromLang: "auto",
|
||||||
|
toLang: "zh-CN",
|
||||||
|
tranboxShortcut: DEFAULT_TRANBOX_SHORTCUT,
|
||||||
|
btnOffsetX: 10,
|
||||||
|
btnOffsetY: 10,
|
||||||
|
};
|
||||||
|
|
||||||
// 订阅列表
|
// 订阅列表
|
||||||
export const DEFAULT_SUBRULES_LIST = [
|
export const DEFAULT_SUBRULES_LIST = [
|
||||||
{
|
{
|
||||||
@@ -220,16 +346,16 @@ export const DEFAULT_TRANS_APIS = {
|
|||||||
url: "https://translate.googleapis.com/translate_a/single",
|
url: "https://translate.googleapis.com/translate_a/single",
|
||||||
key: "",
|
key: "",
|
||||||
},
|
},
|
||||||
[OPT_TRANS_MICROSOFT]: {
|
|
||||||
url: "https://api-edge.cognitive.microsofttranslator.com/translate",
|
|
||||||
authUrl: "https://edge.microsoft.com/translate/auth",
|
|
||||||
},
|
|
||||||
[OPT_TRANS_DEEPL]: {
|
[OPT_TRANS_DEEPL]: {
|
||||||
url: "https://api-free.deepl.com/v2/translate",
|
url: "https://api-free.deepl.com/v2/translate",
|
||||||
key: "",
|
key: "",
|
||||||
},
|
},
|
||||||
|
[OPT_TRANS_DEEPLX]: {
|
||||||
|
url: "http://localhost:1188/translate",
|
||||||
|
key: "",
|
||||||
|
},
|
||||||
[OPT_TRANS_OPENAI]: {
|
[OPT_TRANS_OPENAI]: {
|
||||||
url: "https://api.openai.com/v1/chat/completion",
|
url: "https://api.openai.com/v1/chat/completions",
|
||||||
key: "",
|
key: "",
|
||||||
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}.`,
|
||||||
@@ -246,15 +372,15 @@ export const OPT_SHORTCUT_STYLE = "toggleStyle";
|
|||||||
export const OPT_SHORTCUT_POPUP = "togglePopup";
|
export const OPT_SHORTCUT_POPUP = "togglePopup";
|
||||||
export const OPT_SHORTCUT_SETTING = "openSetting";
|
export const OPT_SHORTCUT_SETTING = "openSetting";
|
||||||
export const DEFAULT_SHORTCUTS = {
|
export const DEFAULT_SHORTCUTS = {
|
||||||
[OPT_SHORTCUT_TRANSLATE]: ["Alt", "q"],
|
[OPT_SHORTCUT_TRANSLATE]: ["AltLeft", "KeyQ"],
|
||||||
[OPT_SHORTCUT_STYLE]: ["Alt", "c"],
|
[OPT_SHORTCUT_STYLE]: ["AltLeft", "KeyC"],
|
||||||
[OPT_SHORTCUT_POPUP]: ["Alt", "k"],
|
[OPT_SHORTCUT_POPUP]: ["AltLeft", "KeyK"],
|
||||||
[OPT_SHORTCUT_SETTING]: ["Alt", "o"],
|
[OPT_SHORTCUT_SETTING]: ["AltLeft", "KeyN"],
|
||||||
};
|
};
|
||||||
|
|
||||||
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 = 40; // 换行字符数
|
export const TRANS_NEWLINE_LENGTH = 20; // 换行字符数
|
||||||
|
|
||||||
export const DEFAULT_SETTING = {
|
export const DEFAULT_SETTING = {
|
||||||
darkMode: false, // 深色模式
|
darkMode: false, // 深色模式
|
||||||
@@ -267,22 +393,28 @@ export const DEFAULT_SETTING = {
|
|||||||
clearCache: false, // 是否在浏览器下次启动时清除缓存
|
clearCache: false, // 是否在浏览器下次启动时清除缓存
|
||||||
injectRules: true, // 是否注入订阅规则
|
injectRules: true, // 是否注入订阅规则
|
||||||
injectWebfix: true, // 是否注入修复补丁
|
injectWebfix: true, // 是否注入修复补丁
|
||||||
|
detectRemote: false, // 是否使用远程语言检测
|
||||||
subrulesList: DEFAULT_SUBRULES_LIST, // 订阅列表
|
subrulesList: DEFAULT_SUBRULES_LIST, // 订阅列表
|
||||||
owSubrule: DEFAULT_OW_RULE, // 覆写订阅规则
|
owSubrule: DEFAULT_OW_RULE, // 覆写订阅规则
|
||||||
transApis: DEFAULT_TRANS_APIS, // 翻译接口
|
transApis: DEFAULT_TRANS_APIS, // 翻译接口
|
||||||
mouseKey: OPT_MOUSEKEY_DISABLE, // 鼠标悬停翻译
|
mouseKey: OPT_MOUSEKEY_DISABLE, // 鼠标悬停翻译
|
||||||
shortcuts: DEFAULT_SHORTCUTS, // 快捷键
|
shortcuts: DEFAULT_SHORTCUTS, // 快捷键
|
||||||
hideFab: false, // 是否隐藏按钮
|
inputRule: DEFAULT_INPUT_RULE, // 输入框设置
|
||||||
|
tranboxSetting: DEFAULT_TRANBOX_SETTING, // 划词翻译设置
|
||||||
};
|
};
|
||||||
|
|
||||||
export const DEFAULT_RULES = [GLOBLA_RULE];
|
export const DEFAULT_RULES = [GLOBLA_RULE];
|
||||||
|
|
||||||
|
export const OPT_SYNCTYPE_WORKER = "KISS-Worker";
|
||||||
|
export const OPT_SYNCTYPE_WEBDAV = "WebDAV";
|
||||||
|
export const OPT_SYNCTYPE_ALL = [OPT_SYNCTYPE_WORKER, OPT_SYNCTYPE_WEBDAV];
|
||||||
|
|
||||||
export const DEFAULT_SYNC = {
|
export const DEFAULT_SYNC = {
|
||||||
|
syncType: OPT_SYNCTYPE_WORKER, // 同步方式
|
||||||
syncUrl: "", // 数据同步接口
|
syncUrl: "", // 数据同步接口
|
||||||
|
syncUser: "", // 数据同步用户名
|
||||||
syncKey: "", // 数据同步密钥
|
syncKey: "", // 数据同步密钥
|
||||||
settingUpdateAt: 0,
|
syncMeta: {}, // 数据更新及同步信息
|
||||||
settingSyncAt: 0,
|
|
||||||
rulesUpdateAt: 0,
|
|
||||||
rulesSyncAt: 0,
|
|
||||||
subRulesSyncAt: 0, // 订阅规则同步时间
|
subRulesSyncAt: 0, // 订阅规则同步时间
|
||||||
|
dataCaches: {}, // 缓存同步时间
|
||||||
};
|
};
|
||||||
|
|||||||
@@ -5,52 +5,72 @@ import {
|
|||||||
MSG_TRANS_GETRULE,
|
MSG_TRANS_GETRULE,
|
||||||
MSG_TRANS_PUTRULE,
|
MSG_TRANS_PUTRULE,
|
||||||
} from "./config";
|
} from "./config";
|
||||||
import { getSettingWithDefault, getRulesWithDefault } from "./libs/storage";
|
import { getSettingWithDefault } from "./libs/storage";
|
||||||
import { Translator } from "./libs/translator";
|
import { isIframe, sendIframeMsg } from "./libs/iframe";
|
||||||
import { isIframe } from "./libs/iframe";
|
import { runWebfix } from "./libs/webfix";
|
||||||
import { matchRule } from "./libs/rules";
|
import {
|
||||||
import { webfix } from "./libs/webfix";
|
runIframe,
|
||||||
|
runTranslator,
|
||||||
|
showFab,
|
||||||
|
showTransbox,
|
||||||
|
windowListener,
|
||||||
|
showErr,
|
||||||
|
} from "./common";
|
||||||
|
|
||||||
/**
|
function runtimeListener(translator) {
|
||||||
* 入口函数
|
|
||||||
*/
|
|
||||||
const init = async () => {
|
|
||||||
const href = isIframe ? document.referrer : document.location.href;
|
|
||||||
const setting = await getSettingWithDefault();
|
|
||||||
const rules = await getRulesWithDefault();
|
|
||||||
const rule = await matchRule(rules, href, setting);
|
|
||||||
const translator = new Translator(rule, setting);
|
|
||||||
webfix(href, setting);
|
|
||||||
|
|
||||||
// 监听消息
|
|
||||||
browser?.runtime.onMessage.addListener(async ({ action, args }) => {
|
browser?.runtime.onMessage.addListener(async ({ action, args }) => {
|
||||||
switch (action) {
|
switch (action) {
|
||||||
case MSG_TRANS_TOGGLE:
|
case MSG_TRANS_TOGGLE:
|
||||||
translator.toggle();
|
translator.toggle();
|
||||||
|
sendIframeMsg(MSG_TRANS_TOGGLE);
|
||||||
break;
|
break;
|
||||||
case MSG_TRANS_TOGGLE_STYLE:
|
case MSG_TRANS_TOGGLE_STYLE:
|
||||||
translator.toggleStyle();
|
translator.toggleStyle();
|
||||||
|
sendIframeMsg(MSG_TRANS_TOGGLE_STYLE);
|
||||||
break;
|
break;
|
||||||
case MSG_TRANS_GETRULE:
|
case MSG_TRANS_GETRULE:
|
||||||
break;
|
break;
|
||||||
case MSG_TRANS_PUTRULE:
|
case MSG_TRANS_PUTRULE:
|
||||||
translator.updateRule(args);
|
translator.updateRule(args);
|
||||||
|
sendIframeMsg(MSG_TRANS_PUTRULE, args);
|
||||||
break;
|
break;
|
||||||
default:
|
default:
|
||||||
return { error: `message action is unavailable: ${action}` };
|
return { error: `message action is unavailable: ${action}` };
|
||||||
}
|
}
|
||||||
return { data: translator.rule };
|
return { data: translator.rule };
|
||||||
});
|
});
|
||||||
};
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 入口函数
|
||||||
|
*/
|
||||||
(async () => {
|
(async () => {
|
||||||
try {
|
try {
|
||||||
await init();
|
// 读取设置信息
|
||||||
|
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) {
|
} catch (err) {
|
||||||
console.error("[KISS-Translator]", err);
|
showErr(err);
|
||||||
const $err = document.createElement("div");
|
|
||||||
$err.innerText = `KISS-Translator: ${err.message}`;
|
|
||||||
$err.style.cssText = "background:red; color:#fff;";
|
|
||||||
document.body.prepend($err);
|
|
||||||
}
|
}
|
||||||
})();
|
})();
|
||||||
|
|||||||
11
src/hooks/Fab.js
Normal file
11
src/hooks/Fab.js
Normal file
@@ -0,0 +1,11 @@
|
|||||||
|
import { STOKEY_FAB } from "../config";
|
||||||
|
import { useStorage } from "./Storage";
|
||||||
|
|
||||||
|
/**
|
||||||
|
* fab hook
|
||||||
|
* @returns
|
||||||
|
*/
|
||||||
|
export function useFab() {
|
||||||
|
const { data, update } = useStorage(STOKEY_FAB);
|
||||||
|
return { fab: data, updateFab: update };
|
||||||
|
}
|
||||||
18
src/hooks/InputRule.js
Normal file
18
src/hooks/InputRule.js
Normal file
@@ -0,0 +1,18 @@
|
|||||||
|
import { useCallback } from "react";
|
||||||
|
import { DEFAULT_INPUT_RULE } from "../config";
|
||||||
|
import { useSetting } from "./Setting";
|
||||||
|
|
||||||
|
export function useInputRule() {
|
||||||
|
const { setting, updateSetting } = useSetting();
|
||||||
|
const inputRule = setting?.inputRule || DEFAULT_INPUT_RULE;
|
||||||
|
|
||||||
|
const updateInputRule = useCallback(
|
||||||
|
async (obj) => {
|
||||||
|
Object.assign(inputRule, obj);
|
||||||
|
await updateSetting({ inputRule });
|
||||||
|
},
|
||||||
|
[inputRule, updateSetting]
|
||||||
|
);
|
||||||
|
|
||||||
|
return { inputRule, updateInputRule };
|
||||||
|
}
|
||||||
@@ -1,8 +1,9 @@
|
|||||||
import { STOKEY_RULES, DEFAULT_RULES } from "../config";
|
import { STOKEY_RULES, DEFAULT_RULES, KV_RULES_KEY } from "../config";
|
||||||
import { useStorage } from "./Storage";
|
import { useStorage } from "./Storage";
|
||||||
import { trySyncRules } from "../libs/sync";
|
import { trySyncRules } from "../libs/sync";
|
||||||
import { checkRules } from "../libs/rules";
|
import { checkRules } from "../libs/rules";
|
||||||
import { useCallback } from "react";
|
import { useCallback } from "react";
|
||||||
|
import { useSyncMeta } from "./Sync";
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* 规则 hook
|
* 规则 hook
|
||||||
@@ -10,13 +11,15 @@ import { useCallback } from "react";
|
|||||||
*/
|
*/
|
||||||
export function useRules() {
|
export function useRules() {
|
||||||
const { data: list, save } = useStorage(STOKEY_RULES, DEFAULT_RULES);
|
const { data: list, save } = useStorage(STOKEY_RULES, DEFAULT_RULES);
|
||||||
|
const { updateSyncMeta } = useSyncMeta();
|
||||||
|
|
||||||
const updateRules = useCallback(
|
const updateRules = useCallback(
|
||||||
async (rules) => {
|
async (rules) => {
|
||||||
await save(rules);
|
await save(rules);
|
||||||
trySyncRules(false, true);
|
await updateSyncMeta(KV_RULES_KEY);
|
||||||
|
trySyncRules();
|
||||||
},
|
},
|
||||||
[save]
|
[save, updateSyncMeta]
|
||||||
);
|
);
|
||||||
|
|
||||||
const add = useCallback(
|
const add = useCallback(
|
||||||
|
|||||||
@@ -1,25 +1,24 @@
|
|||||||
import { STOKEY_SETTING, DEFAULT_SETTING } from "../config";
|
import { STOKEY_SETTING, DEFAULT_SETTING, KV_SETTING_KEY } from "../config";
|
||||||
import { useStorage } from "./Storage";
|
import { useStorage } from "./Storage";
|
||||||
import { trySyncSetting } from "../libs/sync";
|
import { trySyncSetting } from "../libs/sync";
|
||||||
import { createContext, useCallback, useContext, useMemo } from "react";
|
import { createContext, useCallback, useContext, useMemo } from "react";
|
||||||
import { debounce } from "../libs/utils";
|
import { debounce } from "../libs/utils";
|
||||||
|
import { useSyncMeta } from "./Sync";
|
||||||
|
|
||||||
const SettingContext = createContext({
|
const SettingContext = createContext({
|
||||||
setting: {},
|
setting: null,
|
||||||
updateSetting: async () => {},
|
updateSetting: async () => {},
|
||||||
reloadSetting: async () => {},
|
reloadSetting: async () => {},
|
||||||
});
|
});
|
||||||
|
|
||||||
export function SettingProvider({ children }) {
|
export function SettingProvider({ children }) {
|
||||||
const { data, update, reload, loading } = useStorage(
|
const { data, update, reload } = useStorage(STOKEY_SETTING, DEFAULT_SETTING);
|
||||||
STOKEY_SETTING,
|
const { updateSyncMeta } = useSyncMeta();
|
||||||
DEFAULT_SETTING
|
|
||||||
);
|
|
||||||
|
|
||||||
const syncSetting = useMemo(
|
const syncSetting = useMemo(
|
||||||
() =>
|
() =>
|
||||||
debounce(() => {
|
debounce(() => {
|
||||||
trySyncSetting(false, true);
|
trySyncSetting();
|
||||||
}, [2000]),
|
}, [2000]),
|
||||||
[]
|
[]
|
||||||
);
|
);
|
||||||
@@ -27,12 +26,13 @@ export function SettingProvider({ children }) {
|
|||||||
const updateSetting = useCallback(
|
const updateSetting = useCallback(
|
||||||
async (obj) => {
|
async (obj) => {
|
||||||
await update(obj);
|
await update(obj);
|
||||||
|
await updateSyncMeta(KV_SETTING_KEY);
|
||||||
syncSetting();
|
syncSetting();
|
||||||
},
|
},
|
||||||
[update, syncSetting]
|
[update, syncSetting, updateSyncMeta]
|
||||||
);
|
);
|
||||||
|
|
||||||
if (loading) {
|
if (!data) {
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -1,9 +1,9 @@
|
|||||||
import { useCallback, useEffect, useState } from "react";
|
import { useCallback, useEffect, useState } from "react";
|
||||||
import { storage } from "../libs/storage";
|
import { storage } from "../libs/storage";
|
||||||
|
|
||||||
export function useStorage(key, defaultVal = null) {
|
export function useStorage(key, defaultVal) {
|
||||||
const [loading, setLoading] = useState(true);
|
const [loading, setLoading] = useState(false);
|
||||||
const [data, setData] = useState(defaultVal);
|
const [data, setData] = useState(null);
|
||||||
|
|
||||||
const save = useCallback(
|
const save = useCallback(
|
||||||
async (val) => {
|
async (val) => {
|
||||||
@@ -15,7 +15,7 @@ export function useStorage(key, defaultVal = null) {
|
|||||||
|
|
||||||
const update = useCallback(
|
const update = useCallback(
|
||||||
async (obj) => {
|
async (obj) => {
|
||||||
setData((pre) => ({ ...pre, ...obj }));
|
setData((pre = {}) => ({ ...pre, ...obj }));
|
||||||
await storage.putObj(key, obj);
|
await storage.putObj(key, obj);
|
||||||
},
|
},
|
||||||
[key]
|
[key]
|
||||||
@@ -27,26 +27,37 @@ export function useStorage(key, defaultVal = null) {
|
|||||||
}, [key]);
|
}, [key]);
|
||||||
|
|
||||||
const reload = useCallback(async () => {
|
const reload = useCallback(async () => {
|
||||||
const val = await storage.getObj(key);
|
try {
|
||||||
if (val) {
|
setLoading(true);
|
||||||
setData(val);
|
const val = await storage.getObj(key);
|
||||||
} else if (defaultVal) {
|
if (val) {
|
||||||
await storage.setObj(key, defaultVal);
|
setData(val);
|
||||||
|
}
|
||||||
|
} catch (err) {
|
||||||
|
console.log("[storage reload]", err.message);
|
||||||
|
} finally {
|
||||||
|
setLoading(false);
|
||||||
}
|
}
|
||||||
}, [key, defaultVal]);
|
}, [key]);
|
||||||
|
|
||||||
useEffect(() => {
|
useEffect(() => {
|
||||||
(async () => {
|
(async () => {
|
||||||
try {
|
try {
|
||||||
setLoading(true);
|
setLoading(true);
|
||||||
await reload();
|
const val = await storage.getObj(key);
|
||||||
|
if (val) {
|
||||||
|
setData(val);
|
||||||
|
} else if (defaultVal) {
|
||||||
|
setData(defaultVal);
|
||||||
|
await storage.setObj(key, defaultVal);
|
||||||
|
}
|
||||||
} catch (err) {
|
} catch (err) {
|
||||||
//
|
console.log("[storage load]", err.message);
|
||||||
} finally {
|
} finally {
|
||||||
setLoading(false);
|
setLoading(false);
|
||||||
}
|
}
|
||||||
})();
|
})();
|
||||||
}, [reload]);
|
}, [key, defaultVal]);
|
||||||
|
|
||||||
return { data, save, update, remove, reload, loading };
|
return { data, save, update, remove, reload, loading };
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -48,7 +48,7 @@ export function useSubRules() {
|
|||||||
const addSub = useCallback(
|
const addSub = useCallback(
|
||||||
async (url) => {
|
async (url) => {
|
||||||
const subrulesList = [...list];
|
const subrulesList = [...list];
|
||||||
subrulesList.push({ url, selected: false, syncAt: Date.now() });
|
subrulesList.push({ url, selected: false });
|
||||||
await updateSetting({ subrulesList });
|
await updateSetting({ subrulesList });
|
||||||
},
|
},
|
||||||
[list, updateSetting]
|
[list, updateSetting]
|
||||||
|
|||||||
@@ -1,3 +1,4 @@
|
|||||||
|
import { useCallback } from "react";
|
||||||
import { STOKEY_SYNC, DEFAULT_SYNC } from "../config";
|
import { STOKEY_SYNC, DEFAULT_SYNC } from "../config";
|
||||||
import { useStorage } from "./Storage";
|
import { useStorage } from "./Storage";
|
||||||
|
|
||||||
@@ -6,6 +7,57 @@ import { useStorage } from "./Storage";
|
|||||||
* @returns
|
* @returns
|
||||||
*/
|
*/
|
||||||
export function useSync() {
|
export function useSync() {
|
||||||
const { data, update } = useStorage(STOKEY_SYNC, DEFAULT_SYNC);
|
const { data, update, reload } = useStorage(STOKEY_SYNC, DEFAULT_SYNC);
|
||||||
return { sync: data, updateSync: update };
|
return { sync: data, updateSync: update, reloadSync: reload };
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* update syncmeta hook
|
||||||
|
* @returns
|
||||||
|
*/
|
||||||
|
export function useSyncMeta() {
|
||||||
|
const { sync, updateSync } = useSync();
|
||||||
|
const updateSyncMeta = useCallback(
|
||||||
|
async (key) => {
|
||||||
|
const syncMeta = sync?.syncMeta || {};
|
||||||
|
syncMeta[key] = { ...(syncMeta[key] || {}), updateAt: Date.now() };
|
||||||
|
await updateSync({ syncMeta });
|
||||||
|
},
|
||||||
|
[sync?.syncMeta, updateSync]
|
||||||
|
);
|
||||||
|
return { updateSyncMeta };
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* caches sync hook
|
||||||
|
* @param {*} url
|
||||||
|
* @returns
|
||||||
|
*/
|
||||||
|
export function useSyncCaches() {
|
||||||
|
const { sync, updateSync, reloadSync } = useSync();
|
||||||
|
|
||||||
|
const updateDataCache = useCallback(
|
||||||
|
async (url) => {
|
||||||
|
const dataCaches = sync?.dataCaches || {};
|
||||||
|
dataCaches[url] = Date.now();
|
||||||
|
await updateSync({ dataCaches });
|
||||||
|
},
|
||||||
|
[sync, updateSync]
|
||||||
|
);
|
||||||
|
|
||||||
|
const deleteDataCache = useCallback(
|
||||||
|
async (url) => {
|
||||||
|
const dataCaches = sync?.dataCaches || {};
|
||||||
|
delete dataCaches[url];
|
||||||
|
await updateSync({ dataCaches });
|
||||||
|
},
|
||||||
|
[sync, updateSync]
|
||||||
|
);
|
||||||
|
|
||||||
|
return {
|
||||||
|
dataCaches: sync?.dataCaches || {},
|
||||||
|
updateDataCache,
|
||||||
|
deleteDataCache,
|
||||||
|
reloadSync,
|
||||||
|
};
|
||||||
}
|
}
|
||||||
|
|||||||
18
src/hooks/Tranbox.js
Normal file
18
src/hooks/Tranbox.js
Normal file
@@ -0,0 +1,18 @@
|
|||||||
|
import { useCallback } from "react";
|
||||||
|
import { DEFAULT_TRANBOX_SETTING } from "../config";
|
||||||
|
import { useSetting } from "./Setting";
|
||||||
|
|
||||||
|
export function useTranbox() {
|
||||||
|
const { setting, updateSetting } = useSetting();
|
||||||
|
const tranboxSetting = setting?.tranboxSetting || DEFAULT_TRANBOX_SETTING;
|
||||||
|
|
||||||
|
const updateTranbox = useCallback(
|
||||||
|
async (obj) => {
|
||||||
|
Object.assign(tranboxSetting, obj);
|
||||||
|
await updateSetting({ tranboxSetting });
|
||||||
|
},
|
||||||
|
[tranboxSetting, updateSetting]
|
||||||
|
);
|
||||||
|
|
||||||
|
return { tranboxSetting, updateTranbox };
|
||||||
|
}
|
||||||
@@ -23,7 +23,7 @@ export function useTranslate(q, rule, setting) {
|
|||||||
try {
|
try {
|
||||||
setLoading(true);
|
setLoading(true);
|
||||||
|
|
||||||
const deLang = await tryDetectLang(q);
|
const deLang = await tryDetectLang(q, setting.detectRemote);
|
||||||
if (deLang && toLang.includes(deLang)) {
|
if (deLang && toLang.includes(deLang)) {
|
||||||
setSamelang(true);
|
setSamelang(true);
|
||||||
} else {
|
} else {
|
||||||
@@ -32,7 +32,8 @@ export function useTranslate(q, rule, setting) {
|
|||||||
text: q,
|
text: q,
|
||||||
fromLang,
|
fromLang,
|
||||||
toLang,
|
toLang,
|
||||||
apiSetting: (setting.transApis || DEFAULT_TRANS_APIS)[translator],
|
apiSetting:
|
||||||
|
setting.transApis?.[translator] || DEFAULT_TRANS_APIS[translator],
|
||||||
});
|
});
|
||||||
setText(trText);
|
setText(trText);
|
||||||
setSamelang(isSame);
|
setSamelang(isSame);
|
||||||
|
|||||||
26
src/index.js
26
src/index.js
@@ -32,25 +32,23 @@ function App() {
|
|||||||
href={process.env.REACT_APP_HOMEPAGE}
|
href={process.env.REACT_APP_HOMEPAGE}
|
||||||
>{`KISS Translator v${process.env.REACT_APP_VERSION}`}</Link>
|
>{`KISS Translator v${process.env.REACT_APP_VERSION}`}</Link>
|
||||||
</Divider>
|
</Divider>
|
||||||
<Stack spacing={2} direction="row" useFlexGap flexWrap="wrap">
|
<Stack spacing={2}>
|
||||||
<Link href={process.env.REACT_APP_USERSCRIPT_DOWNLOADURL}>
|
<Link href={process.env.REACT_APP_USERSCRIPT_DOWNLOADURL}>
|
||||||
Install Userscript 1
|
Install/Update Userscript for Tampermonkey/Violentmonkey
|
||||||
</Link>
|
|
||||||
<Link href={process.env.REACT_APP_USERSCRIPT_DOWNLOADURL2}>
|
|
||||||
Install Userscript 2
|
|
||||||
</Link>
|
</Link>
|
||||||
|
{/* <Link href={process.env.REACT_APP_USERSCRIPT_DOWNLOADURL2}>
|
||||||
|
Install/Update Userscript for Tampermonkey/Violentmonkey 2
|
||||||
|
</Link> */}
|
||||||
<Link href={process.env.REACT_APP_USERSCRIPT_IOS_DOWNLOADURL}>
|
<Link href={process.env.REACT_APP_USERSCRIPT_IOS_DOWNLOADURL}>
|
||||||
Install Userscript Safari 1
|
Install/Update Userscript for iOS Safari
|
||||||
</Link>
|
</Link>
|
||||||
<Link href={process.env.REACT_APP_USERSCRIPT_IOS_DOWNLOADURL2}>
|
{/* <Link href={process.env.REACT_APP_USERSCRIPT_IOS_DOWNLOADURL2}>
|
||||||
Install Userscript Safari 2
|
Install/Update Userscript for iOS Safari 2
|
||||||
</Link>
|
</Link> */}
|
||||||
<Link href={process.env.REACT_APP_OPTIONSPAGE}>
|
<Link href={process.env.REACT_APP_OPTIONSPAGE}>Open Options Page</Link>
|
||||||
Open Options Page 1
|
{/* <Link href={process.env.REACT_APP_OPTIONSPAGE2}>
|
||||||
</Link>
|
|
||||||
<Link href={process.env.REACT_APP_OPTIONSPAGE2}>
|
|
||||||
Open Options Page 2
|
Open Options Page 2
|
||||||
</Link>
|
</Link> */}
|
||||||
</Stack>
|
</Stack>
|
||||||
|
|
||||||
{loading ? (
|
{loading ? (
|
||||||
|
|||||||
@@ -13,3 +13,5 @@ function _browser() {
|
|||||||
}
|
}
|
||||||
|
|
||||||
export const browser = _browser();
|
export const browser = _browser();
|
||||||
|
|
||||||
|
export const isBg = () => globalThis?.ContextType === "BACKGROUND";
|
||||||
|
|||||||
@@ -6,13 +6,11 @@ import {
|
|||||||
MSG_FETCH_LIMIT,
|
MSG_FETCH_LIMIT,
|
||||||
MSG_FETCH_CLEAR,
|
MSG_FETCH_CLEAR,
|
||||||
CACHE_NAME,
|
CACHE_NAME,
|
||||||
OPT_TRANS_MICROSOFT,
|
|
||||||
OPT_TRANS_DEEPL,
|
|
||||||
OPT_TRANS_OPENAI,
|
|
||||||
DEFAULT_FETCH_INTERVAL,
|
DEFAULT_FETCH_INTERVAL,
|
||||||
DEFAULT_FETCH_LIMIT,
|
DEFAULT_FETCH_LIMIT,
|
||||||
} from "../config";
|
} from "../config";
|
||||||
import { msAuth } from "./auth";
|
import { isBg } from "./browser";
|
||||||
|
import { newCacheReq, newTransReq } from "./req";
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* 油猴脚本的请求封装
|
* 油猴脚本的请求封装
|
||||||
@@ -27,55 +25,34 @@ export const fetchGM = async (input, { method = "GET", headers, body } = {}) =>
|
|||||||
url: input,
|
url: input,
|
||||||
headers,
|
headers,
|
||||||
data: body,
|
data: body,
|
||||||
onload: (response) => {
|
// withCredentials: true,
|
||||||
if (response.status === 200) {
|
onload: ({ response, responseHeaders, status, statusText, ...opts }) => {
|
||||||
const headers = new Headers();
|
const headers = {};
|
||||||
response.responseHeaders.split("\n").forEach((line) => {
|
responseHeaders.split("\n").forEach((line) => {
|
||||||
const [name, value] = line.split(":").map((item) => item.trim());
|
const [name, value] = line.split(":").map((item) => item.trim());
|
||||||
if (name && value) {
|
if (name && value) {
|
||||||
headers.append(name, value);
|
headers[name] = value;
|
||||||
}
|
}
|
||||||
});
|
});
|
||||||
resolve(new Response(response.response, { headers }));
|
resolve({
|
||||||
} else {
|
body: response,
|
||||||
reject(new Error(`[${response.status}] ${response.responseText}`));
|
headers,
|
||||||
}
|
status,
|
||||||
|
statusText,
|
||||||
|
});
|
||||||
},
|
},
|
||||||
onerror: reject,
|
onerror: reject,
|
||||||
});
|
});
|
||||||
});
|
});
|
||||||
|
|
||||||
/**
|
|
||||||
* 构造缓存 request
|
|
||||||
* @param {*} request
|
|
||||||
* @returns
|
|
||||||
*/
|
|
||||||
const newCacheReq = async (request) => {
|
|
||||||
if (request.method !== "GET") {
|
|
||||||
const body = await request.text();
|
|
||||||
const cacheUrl = new URL(request.url);
|
|
||||||
cacheUrl.pathname += body;
|
|
||||||
request = new Request(cacheUrl.toString(), { method: "GET" });
|
|
||||||
}
|
|
||||||
|
|
||||||
return request;
|
|
||||||
};
|
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* 发起请求
|
* 发起请求
|
||||||
* @param {*} param0
|
* @param {*} param0
|
||||||
* @returns
|
* @returns
|
||||||
*/
|
*/
|
||||||
const fetchApi = async ({ input, init = {}, translator, token }) => {
|
export const fetchApi = async ({ input, init, transOpts, apiSetting }) => {
|
||||||
if (token) {
|
if (transOpts?.translator) {
|
||||||
if (translator === OPT_TRANS_DEEPL) {
|
[input, init] = await newTransReq(transOpts, apiSetting);
|
||||||
init.headers["Authorization"] = `DeepL-Auth-Key ${token}`; // DeepL
|
|
||||||
} else if (translator === OPT_TRANS_OPENAI) {
|
|
||||||
init.headers["Authorization"] = `Bearer ${token}`; // OpenAI
|
|
||||||
init.headers["api-key"] = token; // Azure OpenAI
|
|
||||||
} else {
|
|
||||||
init.headers["Authorization"] = `Bearer ${token}`; // Microsoft & others
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|
||||||
if (isGm) {
|
if (isGm) {
|
||||||
@@ -85,19 +62,26 @@ const fetchApi = async ({ input, init = {}, translator, token }) => {
|
|||||||
} else {
|
} else {
|
||||||
info = GM.info;
|
info = GM.info;
|
||||||
}
|
}
|
||||||
|
|
||||||
// Tampermonkey --> .connects
|
// Tampermonkey --> .connects
|
||||||
// Violentmonkey --> .connect
|
// Violentmonkey --> .connect
|
||||||
const connects = info?.script?.connects || info?.script?.connect || [];
|
const connects = info?.script?.connects || info?.script?.connect || [];
|
||||||
const url = new URL(input);
|
const url = new URL(input);
|
||||||
const isSafe = connects.find((item) => url.hostname.endsWith(item));
|
const isSafe = connects.find((item) => url.hostname.endsWith(item));
|
||||||
|
|
||||||
if (isSafe) {
|
if (isSafe) {
|
||||||
if (window.KISS_GM) {
|
const { body, headers, status, statusText } = window.KISS_GM
|
||||||
return window.KISS_GM.fetch(input, init);
|
? await window.KISS_GM.fetch(input, init)
|
||||||
} else {
|
: await fetchGM(input, init);
|
||||||
return fetchGM(input, init);
|
|
||||||
}
|
return new Response(body, {
|
||||||
|
headers: new Headers(headers),
|
||||||
|
status,
|
||||||
|
statusText,
|
||||||
|
});
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
return fetch(input, init);
|
return fetch(input, init);
|
||||||
};
|
};
|
||||||
|
|
||||||
@@ -106,13 +90,7 @@ const fetchApi = async ({ input, init = {}, translator, token }) => {
|
|||||||
*/
|
*/
|
||||||
export const fetchPool = taskPool(
|
export const fetchPool = taskPool(
|
||||||
fetchApi,
|
fetchApi,
|
||||||
async ({ translator }) => {
|
null,
|
||||||
if (translator === OPT_TRANS_MICROSOFT) {
|
|
||||||
const [token] = await msAuth();
|
|
||||||
return { token };
|
|
||||||
}
|
|
||||||
return {};
|
|
||||||
},
|
|
||||||
DEFAULT_FETCH_INTERVAL,
|
DEFAULT_FETCH_INTERVAL,
|
||||||
DEFAULT_FETCH_LIMIT
|
DEFAULT_FETCH_LIMIT
|
||||||
);
|
);
|
||||||
@@ -125,9 +103,9 @@ export const fetchPool = taskPool(
|
|||||||
*/
|
*/
|
||||||
export const fetchData = async (
|
export const fetchData = async (
|
||||||
input,
|
input,
|
||||||
{ useCache, usePool, translator, token, ...init } = {}
|
{ useCache, usePool, transOpts, apiSetting, ...init } = {}
|
||||||
) => {
|
) => {
|
||||||
const cacheReq = await newCacheReq(new Request(input, init));
|
const cacheReq = await newCacheReq(input, init);
|
||||||
let res;
|
let res;
|
||||||
|
|
||||||
// 查询缓存
|
// 查询缓存
|
||||||
@@ -143,9 +121,9 @@ export const fetchData = async (
|
|||||||
if (!res) {
|
if (!res) {
|
||||||
// 发送请求
|
// 发送请求
|
||||||
if (usePool) {
|
if (usePool) {
|
||||||
res = await fetchPool.push({ input, init, translator, token });
|
res = await fetchPool.push({ input, init, transOpts, apiSetting });
|
||||||
} else {
|
} else {
|
||||||
res = await fetchApi({ input, init, translator, token });
|
res = await fetchApi({ input, init, transOpts, apiSetting });
|
||||||
}
|
}
|
||||||
|
|
||||||
if (!res?.ok) {
|
if (!res?.ok) {
|
||||||
@@ -176,13 +154,13 @@ export const fetchData = async (
|
|||||||
* @param {*} opts
|
* @param {*} opts
|
||||||
* @returns
|
* @returns
|
||||||
*/
|
*/
|
||||||
export const fetchPolyfill = async (input, { isBg = false, ...opts } = {}) => {
|
export const fetchPolyfill = async (input, opts) => {
|
||||||
if (!input.trim()) {
|
if (!input?.trim()) {
|
||||||
throw new Error("URL is empty");
|
throw new Error("URL is empty");
|
||||||
}
|
}
|
||||||
|
|
||||||
// 插件
|
// 插件
|
||||||
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);
|
||||||
|
|||||||
@@ -5,3 +5,7 @@ export const sendIframeMsg = (action, args) => {
|
|||||||
iframe.contentWindow.postMessage({ action, args }, "*");
|
iframe.contentWindow.postMessage({ action, args }, "*");
|
||||||
});
|
});
|
||||||
};
|
};
|
||||||
|
|
||||||
|
export const sendParentMsg = (action, args) => {
|
||||||
|
window.parent.postMessage({ action, args }, "*");
|
||||||
|
};
|
||||||
|
|||||||
@@ -1,5 +1,6 @@
|
|||||||
import { CACHE_NAME } from "../config";
|
import { CACHE_NAME } from "../config";
|
||||||
import { browser } from "./browser";
|
import { browser } from "./browser";
|
||||||
|
import { apiBaiduLangdetect } from "../apis";
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* 清除缓存数据
|
* 清除缓存数据
|
||||||
@@ -13,15 +14,29 @@ export const tryClearCaches = async () => {
|
|||||||
};
|
};
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* 本地语言识别
|
* 语言识别
|
||||||
* @param {*} q
|
* @param {*} q
|
||||||
* @returns
|
* @returns
|
||||||
*/
|
*/
|
||||||
export const tryDetectLang = async (q) => {
|
export const tryDetectLang = async (q, useRemote = false) => {
|
||||||
try {
|
let lang = "";
|
||||||
const res = await browser?.i18n?.detectLanguage(q);
|
|
||||||
return res?.languages?.[0]?.language;
|
if (useRemote) {
|
||||||
} catch (err) {
|
try {
|
||||||
console.log("[detect lang]", err.message);
|
lang = await apiBaiduLangdetect(q);
|
||||||
|
} catch (err) {
|
||||||
|
console.log("[detect lang remote]", err.message);
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
if (!lang) {
|
||||||
|
try {
|
||||||
|
const res = await browser?.i18n?.detectLanguage(q);
|
||||||
|
lang = res?.languages?.[0]?.language;
|
||||||
|
} catch (err) {
|
||||||
|
console.log("[detect lang local]", err.message);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
return lang;
|
||||||
};
|
};
|
||||||
|
|||||||
@@ -6,7 +6,13 @@
|
|||||||
* @param {*} _limit
|
* @param {*} _limit
|
||||||
* @returns
|
* @returns
|
||||||
*/
|
*/
|
||||||
export const taskPool = (fn, preFn, _interval = 100, _limit = 100) => {
|
export const taskPool = (
|
||||||
|
fn,
|
||||||
|
preFn,
|
||||||
|
_interval = 100,
|
||||||
|
_limit = 100,
|
||||||
|
_retryInteral = 1000
|
||||||
|
) => {
|
||||||
const pool = [];
|
const pool = [];
|
||||||
const maxRetry = 2; // 最大重试次数
|
const maxRetry = 2; // 最大重试次数
|
||||||
let maxCount = _limit; // 最大数量
|
let maxCount = _limit; // 最大数量
|
||||||
@@ -14,23 +20,6 @@ export const taskPool = (fn, preFn, _interval = 100, _limit = 100) => {
|
|||||||
let interval = _interval; // 间隔时间
|
let interval = _interval; // 间隔时间
|
||||||
let timer = null;
|
let timer = null;
|
||||||
|
|
||||||
const handleTask = async (item, preArgs) => {
|
|
||||||
curCount++;
|
|
||||||
const { args, resolve, reject, retry } = item;
|
|
||||||
try {
|
|
||||||
const res = await fn({ ...args, ...preArgs });
|
|
||||||
resolve(res);
|
|
||||||
} catch (err) {
|
|
||||||
if (retry < maxRetry) {
|
|
||||||
pool.push({ args, resolve, reject, retry: retry + 1 });
|
|
||||||
} else {
|
|
||||||
reject(err);
|
|
||||||
}
|
|
||||||
} finally {
|
|
||||||
curCount--;
|
|
||||||
}
|
|
||||||
};
|
|
||||||
|
|
||||||
const run = async () => {
|
const run = async () => {
|
||||||
// console.log("timer", timer);
|
// console.log("timer", timer);
|
||||||
timer && clearTimeout(timer);
|
timer && clearTimeout(timer);
|
||||||
@@ -39,12 +28,24 @@ export const taskPool = (fn, preFn, _interval = 100, _limit = 100) => {
|
|||||||
if (curCount < maxCount) {
|
if (curCount < maxCount) {
|
||||||
const item = pool.shift();
|
const item = pool.shift();
|
||||||
if (item) {
|
if (item) {
|
||||||
|
curCount++;
|
||||||
|
const { args, resolve, reject, retry } = item;
|
||||||
try {
|
try {
|
||||||
const preArgs = await preFn(item.args);
|
const preArgs = preFn ? await preFn(item.args) : {};
|
||||||
handleTask(item, preArgs);
|
const res = await fn({ ...args, ...preArgs });
|
||||||
|
resolve(res);
|
||||||
} catch (err) {
|
} catch (err) {
|
||||||
console.log("[preFn]", err);
|
console.log("[task]", retry, err);
|
||||||
pool.push(item);
|
if (retry < maxRetry) {
|
||||||
|
const retryTimer = setTimeout(() => {
|
||||||
|
clearTimeout(retryTimer);
|
||||||
|
pool.push({ args, resolve, reject, retry: retry + 1 });
|
||||||
|
}, _retryInteral);
|
||||||
|
} else {
|
||||||
|
reject(err);
|
||||||
|
}
|
||||||
|
} finally {
|
||||||
|
curCount--;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
224
src/libs/req.js
Normal file
224
src/libs/req.js
Normal file
@@ -0,0 +1,224 @@
|
|||||||
|
import queryString from "query-string";
|
||||||
|
import {
|
||||||
|
OPT_TRANS_GOOGLE,
|
||||||
|
OPT_TRANS_MICROSOFT,
|
||||||
|
OPT_TRANS_DEEPL,
|
||||||
|
OPT_TRANS_DEEPLFREE,
|
||||||
|
OPT_TRANS_DEEPLX,
|
||||||
|
OPT_TRANS_BAIDU,
|
||||||
|
OPT_TRANS_TENCENT,
|
||||||
|
OPT_TRANS_OPENAI,
|
||||||
|
OPT_TRANS_CUSTOMIZE,
|
||||||
|
URL_MICROSOFT_TRAN,
|
||||||
|
URL_TENCENT_TRANSMART,
|
||||||
|
PROMPT_PLACE_FROM,
|
||||||
|
PROMPT_PLACE_TO,
|
||||||
|
} from "../config";
|
||||||
|
import { msAuth } from "./auth";
|
||||||
|
import { genDeeplFree } from "../apis/deepl";
|
||||||
|
import { genBaidu } from "../apis/baidu";
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 构造缓存 request
|
||||||
|
* @param {*} request
|
||||||
|
* @returns
|
||||||
|
*/
|
||||||
|
export const newCacheReq = async (input, init) => {
|
||||||
|
let request = new Request(input, init);
|
||||||
|
if (request.method !== "GET") {
|
||||||
|
const body = await request.text();
|
||||||
|
const cacheUrl = new URL(request.url);
|
||||||
|
cacheUrl.pathname += body;
|
||||||
|
request = new Request(cacheUrl.toString(), { method: "GET" });
|
||||||
|
}
|
||||||
|
|
||||||
|
return request;
|
||||||
|
};
|
||||||
|
|
||||||
|
const genGoogle = ({ text, from, to, url, key }) => {
|
||||||
|
const params = {
|
||||||
|
client: "gtx",
|
||||||
|
dt: "t",
|
||||||
|
dj: 1,
|
||||||
|
ie: "UTF-8",
|
||||||
|
sl: from,
|
||||||
|
tl: to,
|
||||||
|
q: text,
|
||||||
|
};
|
||||||
|
const input = `${url}?${queryString.stringify(params)}`;
|
||||||
|
const init = {
|
||||||
|
headers: {
|
||||||
|
"Content-type": "application/json",
|
||||||
|
},
|
||||||
|
};
|
||||||
|
if (key) {
|
||||||
|
init.headers.Authorization = `Bearer ${key}`;
|
||||||
|
}
|
||||||
|
|
||||||
|
return [input, init];
|
||||||
|
};
|
||||||
|
|
||||||
|
const genMicrosoft = async ({ text, from, to }) => {
|
||||||
|
const [token] = await msAuth();
|
||||||
|
const params = {
|
||||||
|
from,
|
||||||
|
to,
|
||||||
|
"api-version": "3.0",
|
||||||
|
};
|
||||||
|
const input = `${URL_MICROSOFT_TRAN}?${queryString.stringify(params)}`;
|
||||||
|
const init = {
|
||||||
|
headers: {
|
||||||
|
"Content-type": "application/json",
|
||||||
|
Authorization: `Bearer ${token}`,
|
||||||
|
},
|
||||||
|
method: "POST",
|
||||||
|
body: JSON.stringify([{ Text: text }]),
|
||||||
|
};
|
||||||
|
|
||||||
|
return [input, init];
|
||||||
|
};
|
||||||
|
|
||||||
|
const genDeepl = ({ text, from, to, url, key }) => {
|
||||||
|
const data = {
|
||||||
|
text: [text],
|
||||||
|
target_lang: to,
|
||||||
|
source_lang: from,
|
||||||
|
// split_sentences: "0",
|
||||||
|
};
|
||||||
|
const init = {
|
||||||
|
headers: {
|
||||||
|
"Content-type": "application/json",
|
||||||
|
Authorization: `DeepL-Auth-Key ${key}`,
|
||||||
|
},
|
||||||
|
method: "POST",
|
||||||
|
body: JSON.stringify(data),
|
||||||
|
};
|
||||||
|
|
||||||
|
return [url, init];
|
||||||
|
};
|
||||||
|
|
||||||
|
const genDeeplX = ({ text, from, to, url, key }) => {
|
||||||
|
const data = {
|
||||||
|
text,
|
||||||
|
target_lang: to,
|
||||||
|
source_lang: from,
|
||||||
|
};
|
||||||
|
|
||||||
|
const init = {
|
||||||
|
headers: {
|
||||||
|
"Content-type": "application/json",
|
||||||
|
},
|
||||||
|
method: "POST",
|
||||||
|
body: JSON.stringify(data),
|
||||||
|
};
|
||||||
|
if (key) {
|
||||||
|
init.headers.Authorization = `Bearer ${key}`;
|
||||||
|
}
|
||||||
|
|
||||||
|
return [url, init];
|
||||||
|
};
|
||||||
|
|
||||||
|
const genTencent = ({ text, from, to }) => {
|
||||||
|
const data = {
|
||||||
|
header: {
|
||||||
|
fn: "auto_translation_block",
|
||||||
|
},
|
||||||
|
source: {
|
||||||
|
text_block: text,
|
||||||
|
lang: from,
|
||||||
|
},
|
||||||
|
target: {
|
||||||
|
lang: to,
|
||||||
|
},
|
||||||
|
};
|
||||||
|
|
||||||
|
const init = {
|
||||||
|
headers: {
|
||||||
|
"Content-Type": "application/json",
|
||||||
|
},
|
||||||
|
method: "POST",
|
||||||
|
body: JSON.stringify(data),
|
||||||
|
};
|
||||||
|
|
||||||
|
return [URL_TENCENT_TRANSMART, init];
|
||||||
|
};
|
||||||
|
|
||||||
|
const genOpenai = ({ text, from, to, url, key, prompt, model }) => {
|
||||||
|
prompt = prompt
|
||||||
|
.replaceAll(PROMPT_PLACE_FROM, from)
|
||||||
|
.replaceAll(PROMPT_PLACE_TO, to);
|
||||||
|
|
||||||
|
const data = {
|
||||||
|
model,
|
||||||
|
messages: [
|
||||||
|
{
|
||||||
|
role: "system",
|
||||||
|
content: prompt,
|
||||||
|
},
|
||||||
|
{
|
||||||
|
role: "user",
|
||||||
|
content: text,
|
||||||
|
},
|
||||||
|
],
|
||||||
|
temperature: 0,
|
||||||
|
max_tokens: 256,
|
||||||
|
};
|
||||||
|
|
||||||
|
const init = {
|
||||||
|
headers: {
|
||||||
|
"Content-type": "application/json",
|
||||||
|
Authorization: `Bearer ${key}`, // OpenAI
|
||||||
|
"api-key": key, // Azure OpenAI
|
||||||
|
},
|
||||||
|
method: "POST",
|
||||||
|
body: JSON.stringify(data),
|
||||||
|
};
|
||||||
|
|
||||||
|
return [url, init];
|
||||||
|
};
|
||||||
|
|
||||||
|
const genCustom = ({ text, from, to, url, key }) => {
|
||||||
|
const data = {
|
||||||
|
text,
|
||||||
|
from,
|
||||||
|
to,
|
||||||
|
};
|
||||||
|
const init = {
|
||||||
|
headers: {
|
||||||
|
"Content-type": "application/json",
|
||||||
|
},
|
||||||
|
method: "POST",
|
||||||
|
body: JSON.stringify(data),
|
||||||
|
};
|
||||||
|
if (key) {
|
||||||
|
init.headers.Authorization = `Bearer ${key}`;
|
||||||
|
}
|
||||||
|
|
||||||
|
return [url, init];
|
||||||
|
};
|
||||||
|
|
||||||
|
export const newTransReq = ({ translator, text, from, to }, apiSetting) => {
|
||||||
|
const args = { text, from, to, ...apiSetting };
|
||||||
|
switch (translator) {
|
||||||
|
case OPT_TRANS_GOOGLE:
|
||||||
|
return genGoogle(args);
|
||||||
|
case OPT_TRANS_MICROSOFT:
|
||||||
|
return genMicrosoft(args);
|
||||||
|
case OPT_TRANS_DEEPL:
|
||||||
|
return genDeepl(args);
|
||||||
|
case OPT_TRANS_DEEPLFREE:
|
||||||
|
return genDeeplFree(args);
|
||||||
|
case OPT_TRANS_DEEPLX:
|
||||||
|
return genDeeplX(args);
|
||||||
|
case OPT_TRANS_BAIDU:
|
||||||
|
return genBaidu(args);
|
||||||
|
case OPT_TRANS_TENCENT:
|
||||||
|
return genTencent(args);
|
||||||
|
case OPT_TRANS_OPENAI:
|
||||||
|
return genOpenai(args);
|
||||||
|
case OPT_TRANS_CUSTOMIZE:
|
||||||
|
return genCustom(args);
|
||||||
|
default:
|
||||||
|
throw new Error(`[trans] translator: ${translator} not support`);
|
||||||
|
}
|
||||||
|
};
|
||||||
@@ -49,9 +49,8 @@ export const matchRule = async (
|
|||||||
mixRule[key] = val;
|
mixRule[key] = val;
|
||||||
});
|
});
|
||||||
|
|
||||||
const subRules = (await loadOrFetchSubRules(selectedSub.url)).map(
|
let subRules = await loadOrFetchSubRules(selectedSub.url);
|
||||||
(item) => ({ ...item, ...mixRule })
|
subRules = subRules.map((item) => ({ ...item, ...mixRule }));
|
||||||
);
|
|
||||||
rules.splice(-1, 0, ...subRules);
|
rules.splice(-1, 0, ...subRules);
|
||||||
}
|
}
|
||||||
} catch (err) {
|
} catch (err) {
|
||||||
@@ -150,5 +149,5 @@ export const saveRule = async (newRule) => {
|
|||||||
rules.unshift(newRule);
|
rules.unshift(newRule);
|
||||||
}
|
}
|
||||||
await setRules(rules);
|
await setRules(rules);
|
||||||
trySyncRules(false, true);
|
trySyncRules();
|
||||||
};
|
};
|
||||||
|
|||||||
@@ -22,14 +22,14 @@ export const shortcutListener = (fn, target = document, timeout = 3000) => {
|
|||||||
}, timeout);
|
}, timeout);
|
||||||
|
|
||||||
if (e.code) {
|
if (e.code) {
|
||||||
allkeys.add(e.key);
|
allkeys.add(e.code);
|
||||||
curkeys.add(e.key);
|
curkeys.add(e.code);
|
||||||
fn([...curkeys], [...allkeys]);
|
fn([...curkeys], [...allkeys]);
|
||||||
}
|
}
|
||||||
};
|
};
|
||||||
|
|
||||||
const handleKeyup = (e) => {
|
const handleKeyup = (e) => {
|
||||||
curkeys.delete(e.key);
|
curkeys.delete(e.code);
|
||||||
if (curkeys.size === 0) {
|
if (curkeys.size === 0) {
|
||||||
fn([...curkeys], [...allkeys]);
|
fn([...curkeys], [...allkeys]);
|
||||||
allkeys.clear();
|
allkeys.clear();
|
||||||
@@ -65,3 +65,48 @@ export const shortcutRegister = (targetKeys = [], fn, target = document) => {
|
|||||||
}
|
}
|
||||||
}, target);
|
}, target);
|
||||||
};
|
};
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 注册连续快捷键
|
||||||
|
* @param {*} targetKeys
|
||||||
|
* @param {*} fn
|
||||||
|
* @param {*} step
|
||||||
|
* @param {*} timeout
|
||||||
|
* @param {*} target
|
||||||
|
* @returns
|
||||||
|
*/
|
||||||
|
export const stepShortcutRegister = (
|
||||||
|
targetKeys = [],
|
||||||
|
fn,
|
||||||
|
step = 3,
|
||||||
|
timeout = 500,
|
||||||
|
target = document
|
||||||
|
) => {
|
||||||
|
let count = 0;
|
||||||
|
let pre = Date.now();
|
||||||
|
let timer;
|
||||||
|
return shortcutListener((curkeys, allkeys) => {
|
||||||
|
timer && clearTimeout(timer);
|
||||||
|
timer = setTimeout(() => {
|
||||||
|
clearTimeout(timer);
|
||||||
|
count = 0;
|
||||||
|
}, timeout);
|
||||||
|
|
||||||
|
if (targetKeys.length > 0 && curkeys.length === 0) {
|
||||||
|
const now = Date.now();
|
||||||
|
if (
|
||||||
|
(count === 0 || now - pre < timeout) &&
|
||||||
|
isSameSet(new Set(targetKeys), new Set(allkeys))
|
||||||
|
) {
|
||||||
|
count++;
|
||||||
|
if (count === step) {
|
||||||
|
count = 0;
|
||||||
|
fn();
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
count = 0;
|
||||||
|
}
|
||||||
|
pre = now;
|
||||||
|
}
|
||||||
|
}, target);
|
||||||
|
};
|
||||||
|
|||||||
@@ -4,6 +4,7 @@ import {
|
|||||||
STOKEY_FAB,
|
STOKEY_FAB,
|
||||||
STOKEY_SYNC,
|
STOKEY_SYNC,
|
||||||
STOKEY_MSAUTH,
|
STOKEY_MSAUTH,
|
||||||
|
STOKEY_BDAUTH,
|
||||||
STOKEY_RULESCACHE_PREFIX,
|
STOKEY_RULESCACHE_PREFIX,
|
||||||
STOKEY_WEBFIXCACHE_PREFIX,
|
STOKEY_WEBFIXCACHE_PREFIX,
|
||||||
DEFAULT_SETTING,
|
DEFAULT_SETTING,
|
||||||
@@ -119,6 +120,7 @@ export const setWebfix = (url, val) =>
|
|||||||
export const getFab = () => getObj(STOKEY_FAB);
|
export const getFab = () => getObj(STOKEY_FAB);
|
||||||
export const getFabWithDefault = async () => (await getFab()) || {};
|
export const getFabWithDefault = async () => (await getFab()) || {};
|
||||||
export const setFab = (obj) => setObj(STOKEY_FAB, obj);
|
export const setFab = (obj) => setObj(STOKEY_FAB, obj);
|
||||||
|
export const updateFab = (obj) => putObj(STOKEY_FAB, obj);
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* 数据同步
|
* 数据同步
|
||||||
@@ -133,6 +135,12 @@ export const updateSync = (obj) => putObj(STOKEY_SYNC, obj);
|
|||||||
export const getMsauth = () => getObj(STOKEY_MSAUTH);
|
export const getMsauth = () => getObj(STOKEY_MSAUTH);
|
||||||
export const setMsauth = (val) => setObj(STOKEY_MSAUTH, val);
|
export const setMsauth = (val) => setObj(STOKEY_MSAUTH, val);
|
||||||
|
|
||||||
|
/**
|
||||||
|
* baidu auth
|
||||||
|
*/
|
||||||
|
export const getBdauth = () => getObj(STOKEY_BDAUTH);
|
||||||
|
export const setBdauth = (val) => setObj(STOKEY_BDAUTH, val);
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* 存入默认数据
|
* 存入默认数据
|
||||||
*/
|
*/
|
||||||
|
|||||||
@@ -4,19 +4,29 @@ import {
|
|||||||
updateSync,
|
updateSync,
|
||||||
setSubRules,
|
setSubRules,
|
||||||
getSubRules,
|
getSubRules,
|
||||||
updateSetting,
|
|
||||||
} from "./storage";
|
} from "./storage";
|
||||||
import { apiFetch } from "../apis";
|
import { apiFetch } from "../apis";
|
||||||
import { checkRules } from "./rules";
|
import { checkRules } from "./rules";
|
||||||
import { isAllchar } from "./utils";
|
import { isAllchar } from "./utils";
|
||||||
|
import { syncWebfix } from "./webfix";
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 更新缓存同步时间
|
||||||
|
* @param {*} url
|
||||||
|
*/
|
||||||
|
const updateSyncDataCache = async (url) => {
|
||||||
|
const { dataCaches = {} } = await getSyncWithDefault();
|
||||||
|
dataCaches[url] = Date.now();
|
||||||
|
await updateSync({ dataCaches });
|
||||||
|
};
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* 同步订阅规则
|
* 同步订阅规则
|
||||||
* @param {*} url
|
* @param {*} url
|
||||||
* @returns
|
* @returns
|
||||||
*/
|
*/
|
||||||
export const syncSubRules = async (url, isBg = false) => {
|
export const syncSubRules = async (url) => {
|
||||||
const res = await apiFetch(url, isBg);
|
const res = await apiFetch(url);
|
||||||
const rules = checkRules(res).filter(
|
const rules = checkRules(res).filter(
|
||||||
({ pattern }) => !isAllchar(pattern, GLOBAL_KEY)
|
({ pattern }) => !isAllchar(pattern, GLOBAL_KEY)
|
||||||
);
|
);
|
||||||
@@ -31,10 +41,11 @@ export const syncSubRules = async (url, isBg = false) => {
|
|||||||
* @param {*} url
|
* @param {*} url
|
||||||
* @returns
|
* @returns
|
||||||
*/
|
*/
|
||||||
export const syncAllSubRules = async (subrulesList, isBg = false) => {
|
export const syncAllSubRules = async (subrulesList) => {
|
||||||
for (let subrules of subrulesList) {
|
for (let subrules of subrulesList) {
|
||||||
try {
|
try {
|
||||||
await syncSubRules(subrules.url, isBg);
|
await syncSubRules(subrules.url);
|
||||||
|
await updateSyncDataCache(subrules.url);
|
||||||
} catch (err) {
|
} catch (err) {
|
||||||
console.log(`[sync subrule error]: ${subrules.url}`, err);
|
console.log(`[sync subrule error]: ${subrules.url}`, err);
|
||||||
}
|
}
|
||||||
@@ -46,19 +57,19 @@ export const syncAllSubRules = async (subrulesList, isBg = false) => {
|
|||||||
* @param {*} url
|
* @param {*} url
|
||||||
* @returns
|
* @returns
|
||||||
*/
|
*/
|
||||||
export const trySyncAllSubRules = async ({ subrulesList }, isBg = false) => {
|
export const trySyncAllSubRules = async ({ subrulesList }) => {
|
||||||
try {
|
try {
|
||||||
const { subRulesSyncAt } = await getSyncWithDefault();
|
const { subRulesSyncAt } = await getSyncWithDefault();
|
||||||
const now = Date.now();
|
const now = Date.now();
|
||||||
const interval = 24 * 60 * 60 * 1000; // 间隔一天
|
const interval = 24 * 60 * 60 * 1000; // 间隔一天
|
||||||
if (now - subRulesSyncAt > interval) {
|
if (now - subRulesSyncAt > interval) {
|
||||||
await syncAllSubRules(subrulesList, isBg);
|
// 同步订阅规则
|
||||||
|
await syncAllSubRules(subrulesList);
|
||||||
await updateSync({ subRulesSyncAt: now });
|
await updateSync({ subRulesSyncAt: now });
|
||||||
|
|
||||||
|
// 同步修复规则
|
||||||
|
await syncWebfix(process.env.REACT_APP_WEBFIXURL);
|
||||||
}
|
}
|
||||||
subrulesList.forEach((item) => {
|
|
||||||
item.syncAt = now;
|
|
||||||
});
|
|
||||||
await updateSetting({ subrulesList });
|
|
||||||
} catch (err) {
|
} catch (err) {
|
||||||
console.log("[try sync all subrules]", err);
|
console.log("[try sync all subrules]", err);
|
||||||
}
|
}
|
||||||
@@ -70,9 +81,10 @@ export const trySyncAllSubRules = async ({ subrulesList }, isBg = false) => {
|
|||||||
* @returns
|
* @returns
|
||||||
*/
|
*/
|
||||||
export const loadOrFetchSubRules = async (url) => {
|
export const loadOrFetchSubRules = async (url) => {
|
||||||
const rules = await getSubRules(url);
|
let rules = await getSubRules(url);
|
||||||
if (rules?.length) {
|
if (!rules || rules.length === 0) {
|
||||||
return rules;
|
rules = await syncSubRules(url);
|
||||||
|
await updateSyncDataCache(url);
|
||||||
}
|
}
|
||||||
return syncSubRules(url);
|
return rules || [];
|
||||||
};
|
};
|
||||||
|
|||||||
34
src/libs/svg.js
Normal file
34
src/libs/svg.js
Normal file
@@ -0,0 +1,34 @@
|
|||||||
|
export const loadingSvg = `
|
||||||
|
<svg viewBox="0 0 100 100" style="display:inline-block; width:100%; height: 100%;">
|
||||||
|
<circle fill="#209CEE" stroke="none" cx="6" cy="50" r="6">
|
||||||
|
<animateTransform
|
||||||
|
attributeName="transform"
|
||||||
|
dur="1s"
|
||||||
|
type="translate"
|
||||||
|
values="0 15 ; 0 -15; 0 15"
|
||||||
|
repeatCount="indefinite"
|
||||||
|
begin="0.1"
|
||||||
|
/>
|
||||||
|
</circle>
|
||||||
|
<circle fill="#209CEE" stroke="none" cx="30" cy="50" r="6">
|
||||||
|
<animateTransform
|
||||||
|
attributeName="transform"
|
||||||
|
dur="1s"
|
||||||
|
type="translate"
|
||||||
|
values="0 10 ; 0 -10; 0 10"
|
||||||
|
repeatCount="indefinite"
|
||||||
|
begin="0.2"
|
||||||
|
/>
|
||||||
|
</circle>
|
||||||
|
<circle fill="#209CEE" stroke="none" cx="54" cy="50" r="6">
|
||||||
|
<animateTransform
|
||||||
|
attributeName="transform"
|
||||||
|
dur="1s"
|
||||||
|
type="translate"
|
||||||
|
values="0 5 ; 0 -5; 0 5"
|
||||||
|
repeatCount="indefinite"
|
||||||
|
begin="0.3"
|
||||||
|
/>
|
||||||
|
</circle>
|
||||||
|
</svg>
|
||||||
|
`;
|
||||||
189
src/libs/sync.js
189
src/libs/sync.js
@@ -1,8 +1,10 @@
|
|||||||
import {
|
import {
|
||||||
|
APP_LCNAME,
|
||||||
KV_SETTING_KEY,
|
KV_SETTING_KEY,
|
||||||
KV_RULES_KEY,
|
KV_RULES_KEY,
|
||||||
KV_RULES_SHARE_KEY,
|
KV_RULES_SHARE_KEY,
|
||||||
KV_SALT_SHARE,
|
KV_SALT_SHARE,
|
||||||
|
OPT_SYNCTYPE_WEBDAV,
|
||||||
} from "../config";
|
} from "../config";
|
||||||
import {
|
import {
|
||||||
getSyncWithDefault,
|
getSyncWithDefault,
|
||||||
@@ -13,53 +15,102 @@ import {
|
|||||||
setRules,
|
setRules,
|
||||||
} from "./storage";
|
} from "./storage";
|
||||||
import { apiSyncData } from "../apis";
|
import { apiSyncData } from "../apis";
|
||||||
import { sha256 } from "./utils";
|
import { sha256, removeEndchar } from "./utils";
|
||||||
|
import { createClient, getPatcher } from "webdav";
|
||||||
|
import { fetchApi } from "./fetch";
|
||||||
|
|
||||||
|
getPatcher().patch("request", (opts) => {
|
||||||
|
return fetchApi({
|
||||||
|
input: opts.url,
|
||||||
|
init: { method: opts.method, headers: opts.headers, body: opts.data },
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
const syncByWebdav = async (data, { syncUrl, syncUser, syncKey }) => {
|
||||||
|
const client = createClient(syncUrl, {
|
||||||
|
username: syncUser,
|
||||||
|
password: syncKey,
|
||||||
|
});
|
||||||
|
const pathname = `/${APP_LCNAME}`;
|
||||||
|
const filename = `/${APP_LCNAME}/${data.key}`;
|
||||||
|
|
||||||
|
if ((await client.exists(pathname)) === false) {
|
||||||
|
await client.createDirectory(pathname);
|
||||||
|
}
|
||||||
|
|
||||||
|
const isExist = await client.exists(filename);
|
||||||
|
if (isExist) {
|
||||||
|
const cont = await client.getFileContents(filename, { format: "text" });
|
||||||
|
const webData = JSON.parse(cont);
|
||||||
|
if (webData.updateAt >= data.updateAt) {
|
||||||
|
return webData;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
await client.putFileContents(filename, JSON.stringify(data, null, 2));
|
||||||
|
return data;
|
||||||
|
};
|
||||||
|
|
||||||
|
const syncByWorker = async (data, { syncUrl, syncKey }) => {
|
||||||
|
syncUrl = removeEndchar(syncUrl, "/");
|
||||||
|
return await apiSyncData(`${syncUrl}/sync`, syncKey, data);
|
||||||
|
};
|
||||||
|
|
||||||
|
const syncData = async (key, valueFn) => {
|
||||||
|
const {
|
||||||
|
syncType,
|
||||||
|
syncUrl,
|
||||||
|
syncUser,
|
||||||
|
syncKey,
|
||||||
|
syncMeta = {},
|
||||||
|
} = await getSyncWithDefault();
|
||||||
|
if (!syncUrl || !syncKey || (syncType === OPT_SYNCTYPE_WEBDAV && !syncUser)) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
let { updateAt = 0, syncAt = 0 } = syncMeta[key] || {};
|
||||||
|
syncAt === 0 && (updateAt = 0);
|
||||||
|
|
||||||
|
const value = await valueFn();
|
||||||
|
const data = {
|
||||||
|
key,
|
||||||
|
value: JSON.stringify(value),
|
||||||
|
updateAt,
|
||||||
|
};
|
||||||
|
const args = {
|
||||||
|
syncUrl,
|
||||||
|
syncUser,
|
||||||
|
syncKey,
|
||||||
|
};
|
||||||
|
|
||||||
|
const res =
|
||||||
|
syncType === OPT_SYNCTYPE_WEBDAV
|
||||||
|
? await syncByWebdav(data, args)
|
||||||
|
: await syncByWorker(data, args);
|
||||||
|
|
||||||
|
syncMeta[key] = {
|
||||||
|
updateAt: res.updateAt,
|
||||||
|
syncAt: Date.now(),
|
||||||
|
};
|
||||||
|
await updateSync({ syncMeta });
|
||||||
|
|
||||||
|
return { value: JSON.parse(res.value), isNew: res.updateAt > updateAt };
|
||||||
|
};
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* 同步设置
|
* 同步设置
|
||||||
* @returns
|
* @returns
|
||||||
*/
|
*/
|
||||||
const syncSetting = async (isBg = false, isForce = false) => {
|
const syncSetting = async () => {
|
||||||
let {
|
const res = await syncData(KV_SETTING_KEY, getSettingWithDefault);
|
||||||
syncUrl,
|
if (res?.isNew) {
|
||||||
syncKey,
|
|
||||||
settingUpdateAt = 0,
|
|
||||||
settingSyncAt = 0,
|
|
||||||
} = await getSyncWithDefault();
|
|
||||||
if (!syncUrl || !syncKey) {
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
|
|
||||||
if (isForce) {
|
|
||||||
settingUpdateAt = Date.now();
|
|
||||||
}
|
|
||||||
|
|
||||||
const setting = await getSettingWithDefault();
|
|
||||||
const res = await apiSyncData(
|
|
||||||
syncUrl,
|
|
||||||
syncKey,
|
|
||||||
{
|
|
||||||
key: KV_SETTING_KEY,
|
|
||||||
value: setting,
|
|
||||||
updateAt: settingSyncAt === 0 ? 0 : settingUpdateAt,
|
|
||||||
},
|
|
||||||
isBg
|
|
||||||
);
|
|
||||||
|
|
||||||
if (res.updateAt > settingUpdateAt) {
|
|
||||||
await setSetting(res.value);
|
await setSetting(res.value);
|
||||||
}
|
}
|
||||||
await updateSync({
|
|
||||||
settingUpdateAt: res.updateAt,
|
|
||||||
settingSyncAt: Date.now(),
|
|
||||||
});
|
|
||||||
|
|
||||||
return res.value;
|
|
||||||
};
|
};
|
||||||
|
|
||||||
export const trySyncSetting = async (isBg = false, isForce = false) => {
|
export const trySyncSetting = async () => {
|
||||||
try {
|
try {
|
||||||
return await syncSetting(isBg, isForce);
|
await syncSetting();
|
||||||
} catch (err) {
|
} catch (err) {
|
||||||
console.log("[sync setting]", err);
|
console.log("[sync setting]", err);
|
||||||
}
|
}
|
||||||
@@ -69,47 +120,16 @@ export const trySyncSetting = async (isBg = false, isForce = false) => {
|
|||||||
* 同步规则
|
* 同步规则
|
||||||
* @returns
|
* @returns
|
||||||
*/
|
*/
|
||||||
const syncRules = async (isBg = false, isForce = false) => {
|
const syncRules = async () => {
|
||||||
let {
|
const res = await syncData(KV_RULES_KEY, getRulesWithDefault);
|
||||||
syncUrl,
|
if (res?.isNew) {
|
||||||
syncKey,
|
|
||||||
rulesUpdateAt = 0,
|
|
||||||
rulesSyncAt = 0,
|
|
||||||
} = await getSyncWithDefault();
|
|
||||||
if (!syncUrl || !syncKey) {
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
|
|
||||||
if (isForce) {
|
|
||||||
rulesUpdateAt = Date.now();
|
|
||||||
}
|
|
||||||
|
|
||||||
const rules = await getRulesWithDefault();
|
|
||||||
const res = await apiSyncData(
|
|
||||||
syncUrl,
|
|
||||||
syncKey,
|
|
||||||
{
|
|
||||||
key: KV_RULES_KEY,
|
|
||||||
value: rules,
|
|
||||||
updateAt: rulesSyncAt === 0 ? 0 : rulesUpdateAt,
|
|
||||||
},
|
|
||||||
isBg
|
|
||||||
);
|
|
||||||
|
|
||||||
if (res.updateAt > rulesUpdateAt) {
|
|
||||||
await setRules(res.value);
|
await setRules(res.value);
|
||||||
}
|
}
|
||||||
await updateSync({
|
|
||||||
rulesUpdateAt: res.updateAt,
|
|
||||||
rulesSyncAt: Date.now(),
|
|
||||||
});
|
|
||||||
|
|
||||||
return res.value;
|
|
||||||
};
|
};
|
||||||
|
|
||||||
export const trySyncRules = async (isBg = false, isForce = false) => {
|
export const trySyncRules = async () => {
|
||||||
try {
|
try {
|
||||||
return await syncRules(isBg, isForce);
|
await syncRules();
|
||||||
} catch (err) {
|
} catch (err) {
|
||||||
console.log("[sync user rules]", err);
|
console.log("[sync user rules]", err);
|
||||||
}
|
}
|
||||||
@@ -121,13 +141,18 @@ export const trySyncRules = async (isBg = false, isForce = false) => {
|
|||||||
* @returns
|
* @returns
|
||||||
*/
|
*/
|
||||||
export const syncShareRules = async ({ rules, syncUrl, syncKey }) => {
|
export const syncShareRules = async ({ rules, syncUrl, syncKey }) => {
|
||||||
await apiSyncData(syncUrl, syncKey, {
|
const data = {
|
||||||
key: KV_RULES_SHARE_KEY,
|
key: KV_RULES_SHARE_KEY,
|
||||||
value: rules,
|
value: JSON.stringify(rules, null, 2),
|
||||||
updateAt: Date.now(),
|
updateAt: Date.now(),
|
||||||
});
|
};
|
||||||
|
const args = {
|
||||||
|
syncUrl,
|
||||||
|
syncKey,
|
||||||
|
};
|
||||||
|
await syncByWorker(data, args);
|
||||||
const psk = await sha256(syncKey, KV_SALT_SHARE);
|
const psk = await sha256(syncKey, KV_SALT_SHARE);
|
||||||
const shareUrl = `${syncUrl}?psk=${psk}`;
|
const shareUrl = `${syncUrl}/rules?psk=${psk}`;
|
||||||
return shareUrl;
|
return shareUrl;
|
||||||
};
|
};
|
||||||
|
|
||||||
@@ -135,10 +160,12 @@ export const syncShareRules = async ({ rules, syncUrl, syncKey }) => {
|
|||||||
* 同步个人设置和规则
|
* 同步个人设置和规则
|
||||||
* @returns
|
* @returns
|
||||||
*/
|
*/
|
||||||
export const syncSettingAndRules = async (isBg = false) => {
|
export const syncSettingAndRules = async () => {
|
||||||
return [await syncSetting(isBg), await syncRules(isBg)];
|
await syncSetting();
|
||||||
|
await syncRules();
|
||||||
};
|
};
|
||||||
|
|
||||||
export const trySyncSettingAndRules = async (isBg = false) => {
|
export const trySyncSettingAndRules = async () => {
|
||||||
return [await trySyncSetting(isBg), await trySyncRules(isBg)];
|
await trySyncSetting();
|
||||||
|
await trySyncRules();
|
||||||
};
|
};
|
||||||
|
|||||||
@@ -9,16 +9,101 @@ import {
|
|||||||
SHADOW_KEY,
|
SHADOW_KEY,
|
||||||
OPT_MOUSEKEY_DISABLE,
|
OPT_MOUSEKEY_DISABLE,
|
||||||
OPT_MOUSEKEY_MOUSEOVER,
|
OPT_MOUSEKEY_MOUSEOVER,
|
||||||
|
DEFAULT_INPUT_RULE,
|
||||||
|
DEFAULT_TRANS_APIS,
|
||||||
|
DEFAULT_INPUT_SHORTCUT,
|
||||||
|
OPT_LANGS_LIST,
|
||||||
} from "../config";
|
} from "../config";
|
||||||
import Content from "../views/Content";
|
import Content from "../views/Content";
|
||||||
import { updateFetchPool, clearFetchPool } from "./fetch";
|
import { updateFetchPool, clearFetchPool } from "./fetch";
|
||||||
import { debounce, genEventName } from "./utils";
|
import {
|
||||||
|
debounce,
|
||||||
|
genEventName,
|
||||||
|
removeEndchar,
|
||||||
|
matchInputStr,
|
||||||
|
sleep,
|
||||||
|
} from "./utils";
|
||||||
|
import { stepShortcutRegister } from "./shortcut";
|
||||||
|
import { apiTranslate } from "../apis";
|
||||||
|
import { tryDetectLang } from ".";
|
||||||
|
import { loadingSvg } from "./svg";
|
||||||
|
|
||||||
|
function isInputNode(node) {
|
||||||
|
return node.nodeName === "INPUT" || node.nodeName === "TEXTAREA";
|
||||||
|
}
|
||||||
|
|
||||||
|
function isEditAbleNode(node) {
|
||||||
|
return node.hasAttribute("contenteditable");
|
||||||
|
}
|
||||||
|
|
||||||
|
function selectContent(node) {
|
||||||
|
node.focus();
|
||||||
|
const range = document.createRange();
|
||||||
|
range.selectNodeContents(node);
|
||||||
|
|
||||||
|
const selection = window.getSelection();
|
||||||
|
selection.removeAllRanges();
|
||||||
|
selection.addRange(range);
|
||||||
|
}
|
||||||
|
|
||||||
|
function pasteContentEvent(node, text) {
|
||||||
|
node.focus();
|
||||||
|
const data = new DataTransfer();
|
||||||
|
data.setData("text/plain", text);
|
||||||
|
|
||||||
|
const event = new ClipboardEvent("paste", { clipboardData: data });
|
||||||
|
document.dispatchEvent(event);
|
||||||
|
data.clearData();
|
||||||
|
}
|
||||||
|
|
||||||
|
function pasteContentCommand(node, text) {
|
||||||
|
node.focus();
|
||||||
|
document.execCommand("insertText", false, text);
|
||||||
|
}
|
||||||
|
|
||||||
|
function collapseToEnd(node) {
|
||||||
|
node.focus();
|
||||||
|
const selection = window.getSelection();
|
||||||
|
selection.collapseToEnd();
|
||||||
|
}
|
||||||
|
|
||||||
|
function getNodeText(node) {
|
||||||
|
if (isInputNode(node)) {
|
||||||
|
return node.value;
|
||||||
|
}
|
||||||
|
return node.innerText || node.textContent || "";
|
||||||
|
}
|
||||||
|
|
||||||
|
function addLoading(node, loadingId) {
|
||||||
|
const div = document.createElement("div");
|
||||||
|
div.id = loadingId;
|
||||||
|
div.innerHTML = loadingSvg;
|
||||||
|
div.style.cssText = `
|
||||||
|
width: ${node.offsetWidth}px;
|
||||||
|
height: ${node.offsetHeight}px;
|
||||||
|
line-height: ${node.offsetHeight}px;
|
||||||
|
position: absolute;
|
||||||
|
text-align: center;
|
||||||
|
left: ${node.offsetLeft}px;
|
||||||
|
top: ${node.offsetTop}px;
|
||||||
|
z-index: 2147483647;
|
||||||
|
`;
|
||||||
|
node.offsetParent?.appendChild(div);
|
||||||
|
}
|
||||||
|
|
||||||
|
function removeLoading(node, loadingId) {
|
||||||
|
const div = node.offsetParent.querySelector(`#${loadingId}`);
|
||||||
|
if (div) {
|
||||||
|
div.remove();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* 翻译类
|
* 翻译类
|
||||||
*/
|
*/
|
||||||
export class Translator {
|
export class Translator {
|
||||||
_rule = {};
|
_rule = {};
|
||||||
|
_inputRule = {};
|
||||||
_setting = {};
|
_setting = {};
|
||||||
_rootNodes = new Set();
|
_rootNodes = new Set();
|
||||||
_tranNodes = new Map();
|
_tranNodes = new Map();
|
||||||
@@ -39,6 +124,7 @@ export class Translator {
|
|||||||
"iframe",
|
"iframe",
|
||||||
];
|
];
|
||||||
_eventName = genEventName();
|
_eventName = genEventName();
|
||||||
|
_mouseoverNode = null;
|
||||||
|
|
||||||
// 显示
|
// 显示
|
||||||
_interseObserver = new IntersectionObserver(
|
_interseObserver = new IntersectionObserver(
|
||||||
@@ -101,6 +187,11 @@ export class Translator {
|
|||||||
if (rule.transOpen === "true") {
|
if (rule.transOpen === "true") {
|
||||||
this._register();
|
this._register();
|
||||||
}
|
}
|
||||||
|
|
||||||
|
this._inputRule = setting.inputRule || DEFAULT_INPUT_RULE;
|
||||||
|
if (this._inputRule.transOpen) {
|
||||||
|
this._registerInput();
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
get setting() {
|
get setting() {
|
||||||
@@ -169,6 +260,22 @@ export class Translator {
|
|||||||
);
|
);
|
||||||
};
|
};
|
||||||
|
|
||||||
|
_queryShadowNodes = (selector, rootNode) => {
|
||||||
|
this._rootNodes.add(rootNode);
|
||||||
|
this._queryFilter(selector, rootNode).forEach((item) => {
|
||||||
|
if (!this._tranNodes.has(item)) {
|
||||||
|
this._tranNodes.set(item, "");
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
|
Array.from(rootNode.querySelectorAll("*"))
|
||||||
|
.map((item) => item.shadowRoot)
|
||||||
|
.filter(Boolean)
|
||||||
|
.forEach((item) => {
|
||||||
|
this._queryShadowNodes(selector, item);
|
||||||
|
});
|
||||||
|
};
|
||||||
|
|
||||||
_queryNodes = (rootNode = document) => {
|
_queryNodes = (rootNode = document) => {
|
||||||
// const childRoots = Array.from(rootNode.querySelectorAll("*"))
|
// const childRoots = Array.from(rootNode.querySelectorAll("*"))
|
||||||
// .map((item) => item.shadowRoot)
|
// .map((item) => item.shadowRoot)
|
||||||
@@ -191,14 +298,15 @@ export class Translator {
|
|||||||
const outNodes = this._querySelectorAll(outSelector, rootNode);
|
const outNodes = this._querySelectorAll(outSelector, rootNode);
|
||||||
outNodes.forEach((outNode) => {
|
outNodes.forEach((outNode) => {
|
||||||
if (outNode.shadowRoot) {
|
if (outNode.shadowRoot) {
|
||||||
this._rootNodes.add(outNode.shadowRoot);
|
// this._rootNodes.add(outNode.shadowRoot);
|
||||||
this._queryFilter(inSelector, outNode.shadowRoot).forEach(
|
// this._queryFilter(inSelector, outNode.shadowRoot).forEach(
|
||||||
(item) => {
|
// (item) => {
|
||||||
if (!this._tranNodes.has(item)) {
|
// if (!this._tranNodes.has(item)) {
|
||||||
this._tranNodes.set(item, "");
|
// this._tranNodes.set(item, "");
|
||||||
}
|
// }
|
||||||
}
|
// }
|
||||||
);
|
// );
|
||||||
|
this._queryShadowNodes(inSelector, outNode.shadowRoot);
|
||||||
}
|
}
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
@@ -229,25 +337,181 @@ export class Translator {
|
|||||||
});
|
});
|
||||||
});
|
});
|
||||||
|
|
||||||
this._tranNodes.forEach((_, node) => {
|
if (
|
||||||
if (
|
!this._setting.mouseKey ||
|
||||||
!this._setting.mouseKey ||
|
this._setting.mouseKey === OPT_MOUSEKEY_DISABLE
|
||||||
this._setting.mouseKey === OPT_MOUSEKEY_DISABLE
|
) {
|
||||||
) {
|
// 监听节点显示
|
||||||
// 监听节点显示
|
this._tranNodes.forEach((_, node) => {
|
||||||
this._interseObserver.observe(node);
|
this._interseObserver.observe(node);
|
||||||
} else {
|
});
|
||||||
// 监听鼠标悬停
|
} else {
|
||||||
|
// 监听鼠标悬停
|
||||||
|
window.addEventListener("keydown", this._handleKeydown);
|
||||||
|
this._tranNodes.forEach((_, node) => {
|
||||||
node.addEventListener("mouseover", this._handleMouseover);
|
node.addEventListener("mouseover", this._handleMouseover);
|
||||||
}
|
node.addEventListener("mouseout", this._handleMouseout);
|
||||||
});
|
});
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
_registerInput = () => {
|
||||||
|
const {
|
||||||
|
triggerShortcut: initTriggerShortcut,
|
||||||
|
translator,
|
||||||
|
fromLang,
|
||||||
|
toLang: initToLang,
|
||||||
|
triggerCount: initTriggerCount,
|
||||||
|
triggerTime,
|
||||||
|
transSign,
|
||||||
|
} = this._inputRule;
|
||||||
|
const apiSetting =
|
||||||
|
this._setting.transApis?.[translator] || DEFAULT_TRANS_APIS[translator];
|
||||||
|
const { detectRemote } = this._setting;
|
||||||
|
|
||||||
|
let triggerShortcut = initTriggerShortcut;
|
||||||
|
let triggerCount = initTriggerCount;
|
||||||
|
if (triggerShortcut.length === 0) {
|
||||||
|
triggerShortcut = DEFAULT_INPUT_SHORTCUT;
|
||||||
|
triggerCount = 1;
|
||||||
|
}
|
||||||
|
|
||||||
|
stepShortcutRegister(
|
||||||
|
triggerShortcut,
|
||||||
|
async () => {
|
||||||
|
let node = document.activeElement;
|
||||||
|
|
||||||
|
if (!node) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
while (node.shadowRoot) {
|
||||||
|
node = node.shadowRoot.activeElement;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (!isInputNode(node) && !isEditAbleNode(node)) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
let initText = getNodeText(node);
|
||||||
|
if (triggerShortcut.length === 1 && triggerShortcut[0].length === 1) {
|
||||||
|
// todo: remove multiple char
|
||||||
|
initText = removeEndchar(initText, triggerShortcut[0], triggerCount);
|
||||||
|
}
|
||||||
|
if (!initText.trim()) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
let text = initText;
|
||||||
|
let toLang = initToLang;
|
||||||
|
if (transSign) {
|
||||||
|
const res = matchInputStr(text, transSign);
|
||||||
|
if (res) {
|
||||||
|
let lang = res[1];
|
||||||
|
if (lang === "zh" || lang === "cn") {
|
||||||
|
lang = "zh-CN";
|
||||||
|
} else if (lang === "tw" || lang === "hk") {
|
||||||
|
lang = "zh-TW";
|
||||||
|
}
|
||||||
|
if (lang && OPT_LANGS_LIST.includes(lang)) {
|
||||||
|
toLang = lang;
|
||||||
|
}
|
||||||
|
text = res[2];
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// console.log("input -->", text);
|
||||||
|
|
||||||
|
const loadingId = "kiss-" + genEventName();
|
||||||
|
try {
|
||||||
|
addLoading(node, loadingId);
|
||||||
|
|
||||||
|
const deLang = await tryDetectLang(text, detectRemote);
|
||||||
|
if (deLang && toLang.includes(deLang)) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
const [trText, isSame] = await apiTranslate({
|
||||||
|
translator,
|
||||||
|
text,
|
||||||
|
fromLang,
|
||||||
|
toLang,
|
||||||
|
apiSetting,
|
||||||
|
});
|
||||||
|
if (!trText || isSame) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (isInputNode(node)) {
|
||||||
|
node.value = trText;
|
||||||
|
node.dispatchEvent(
|
||||||
|
new Event("input", { bubbles: true, cancelable: true })
|
||||||
|
);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
selectContent(node);
|
||||||
|
await sleep(200);
|
||||||
|
|
||||||
|
pasteContentEvent(node, trText);
|
||||||
|
await sleep(200);
|
||||||
|
|
||||||
|
// todo: use includes?
|
||||||
|
if (getNodeText(node).startsWith(initText)) {
|
||||||
|
pasteContentCommand(node, trText);
|
||||||
|
await sleep(100);
|
||||||
|
} else {
|
||||||
|
collapseToEnd(node);
|
||||||
|
}
|
||||||
|
} catch (err) {
|
||||||
|
console.log("[translate input]", err.message);
|
||||||
|
} finally {
|
||||||
|
removeLoading(node, loadingId);
|
||||||
|
}
|
||||||
|
},
|
||||||
|
triggerCount,
|
||||||
|
triggerTime
|
||||||
|
);
|
||||||
};
|
};
|
||||||
|
|
||||||
_handleMouseover = (e) => {
|
_handleMouseover = (e) => {
|
||||||
|
// console.log("mouseover", e);
|
||||||
|
if (!this._tranNodes.has(e.target)) {
|
||||||
|
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("mouseover", this._handleMouseover);
|
||||||
|
e.target.removeEventListener("mouseout", this._handleMouseout);
|
||||||
this._render(e.target);
|
this._render(e.target);
|
||||||
|
} else {
|
||||||
|
this._mouseoverNode = e.target;
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
_handleMouseout = (e) => {
|
||||||
|
// console.log("mouseout", e);
|
||||||
|
if (!this._tranNodes.has(e.target)) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
this._mouseoverNode = null;
|
||||||
|
};
|
||||||
|
|
||||||
|
_handleKeydown = (e) => {
|
||||||
|
// console.log("keydown", e);
|
||||||
|
const key = this._setting.mouseKey.slice(3);
|
||||||
|
if (e[key] && this._mouseoverNode) {
|
||||||
|
this._mouseoverNode.removeEventListener(
|
||||||
|
"mouseover",
|
||||||
|
this._handleMouseover
|
||||||
|
);
|
||||||
|
this._mouseoverNode.removeEventListener("mouseout", this._handleMouseout);
|
||||||
|
|
||||||
|
const node = this._mouseoverNode;
|
||||||
|
this._render(node);
|
||||||
|
this._mouseoverNode = null;
|
||||||
}
|
}
|
||||||
};
|
};
|
||||||
|
|
||||||
@@ -258,21 +522,26 @@ export class Translator {
|
|||||||
// 解除节点显示监听
|
// 解除节点显示监听
|
||||||
// this._interseObserver.disconnect();
|
// this._interseObserver.disconnect();
|
||||||
|
|
||||||
this._tranNodes.forEach((_, node) => {
|
if (
|
||||||
if (
|
!this._setting.mouseKey ||
|
||||||
!this._setting.mouseKey ||
|
this._setting.mouseKey === OPT_MOUSEKEY_DISABLE
|
||||||
this._setting.mouseKey === OPT_MOUSEKEY_DISABLE
|
) {
|
||||||
) {
|
// 解除节点显示监听
|
||||||
// 解除节点显示监听
|
this._tranNodes.forEach((_, node) => {
|
||||||
this._interseObserver.unobserve(node);
|
this._interseObserver.unobserve(node);
|
||||||
} else {
|
// 移除已插入元素
|
||||||
// 移除鼠标悬停监听
|
node.querySelector(APP_LCNAME)?.remove();
|
||||||
|
});
|
||||||
|
} else {
|
||||||
|
// 移除鼠标悬停监听
|
||||||
|
window.removeEventListener("keydown", this._handleKeydown);
|
||||||
|
this._tranNodes.forEach((_, node) => {
|
||||||
node.removeEventListener("mouseover", this._handleMouseover);
|
node.removeEventListener("mouseover", this._handleMouseover);
|
||||||
}
|
node.removeEventListener("mouseout", this._handleMouseout);
|
||||||
|
// 移除已插入元素
|
||||||
// 移除已插入元素
|
node.querySelector(APP_LCNAME)?.remove();
|
||||||
node.querySelector(APP_LCNAME)?.remove();
|
});
|
||||||
});
|
}
|
||||||
|
|
||||||
// 清空节点集合
|
// 清空节点集合
|
||||||
this._rootNodes.clear();
|
this._rootNodes.clear();
|
||||||
|
|||||||
@@ -179,3 +179,57 @@ export const isSameSet = (a, b) => {
|
|||||||
const s = new Set([...a, ...b]);
|
const s = new Set([...a, ...b]);
|
||||||
return s.size === a.size && s.size === b.size;
|
return s.size === a.size && s.size === b.size;
|
||||||
};
|
};
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 去掉字符串末尾某个字符
|
||||||
|
* @param {*} s
|
||||||
|
* @param {*} c
|
||||||
|
* @param {*} count
|
||||||
|
* @returns
|
||||||
|
*/
|
||||||
|
export const removeEndchar = (s, c, count = 1) => {
|
||||||
|
let i = s.length;
|
||||||
|
while (i > s.length - count && s[i - 1] === c) {
|
||||||
|
i--;
|
||||||
|
}
|
||||||
|
return s.slice(0, i);
|
||||||
|
};
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 匹配字符串及语言标识
|
||||||
|
* @param {*} str
|
||||||
|
* @param {*} sign
|
||||||
|
* @returns
|
||||||
|
*/
|
||||||
|
export const matchInputStr = (str, sign) => {
|
||||||
|
let reg = /\/([\w-]+)\s+([^]+)/;
|
||||||
|
switch (sign) {
|
||||||
|
case "//":
|
||||||
|
reg = /\/\/([\w-]+)\s+([^]+)/;
|
||||||
|
break;
|
||||||
|
case "\\":
|
||||||
|
reg = /\\([\w-]+)\s+([^]+)/;
|
||||||
|
break;
|
||||||
|
case "\\\\":
|
||||||
|
reg = /\\\\([\w-]+)\s+([^]+)/;
|
||||||
|
break;
|
||||||
|
case ">":
|
||||||
|
reg = />([\w-]+)\s+([^]+)/;
|
||||||
|
break;
|
||||||
|
case ">>":
|
||||||
|
reg = />>([\w-]+)\s+([^]+)/;
|
||||||
|
break;
|
||||||
|
default:
|
||||||
|
}
|
||||||
|
return str.match(reg);
|
||||||
|
};
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 判断是否英文单词
|
||||||
|
* @param {*} str
|
||||||
|
* @returns
|
||||||
|
*/
|
||||||
|
export const isValidWord = (str) => {
|
||||||
|
const regex = /^[a-zA-Z-]+$/;
|
||||||
|
return regex.test(str);
|
||||||
|
};
|
||||||
|
|||||||
@@ -6,34 +6,41 @@ import { apiFetch } from "../apis";
|
|||||||
* 修复程序类型
|
* 修复程序类型
|
||||||
*/
|
*/
|
||||||
const FIXER_BR = "br";
|
const FIXER_BR = "br";
|
||||||
|
const FIXER_BN = "bn";
|
||||||
const FIXER_FONTSIZE = "fontSize";
|
const FIXER_FONTSIZE = "fontSize";
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* 需要修复的站点列表
|
* 需要修复的站点列表
|
||||||
* - pattern 匹配网址
|
* - pattern 匹配网址
|
||||||
* - selector 需要修复的选择器
|
* - selector 需要修复的选择器
|
||||||
* - rootSlector 需要监听的选择器,可留空
|
* - rootSelector 需要监听的选择器,可留空
|
||||||
* - fixer 修复函数,可针对不同网址,选用不同修复函数
|
* - fixer 修复函数,可针对不同网址,选用不同修复函数
|
||||||
*/
|
*/
|
||||||
const DEFAULT_SITES = [
|
const DEFAULT_SITES = [
|
||||||
{
|
{
|
||||||
pattern: "www.phoronix.com",
|
pattern: "www.phoronix.com",
|
||||||
selector: ".content",
|
selector: ".content",
|
||||||
rootSlector: "",
|
rootSelector: "",
|
||||||
fixer: FIXER_BR,
|
fixer: FIXER_BR,
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
pattern: "t.me/s/",
|
pattern: "t.me/s/",
|
||||||
selector: ".tgme_widget_message_text",
|
selector: ".tgme_widget_message_text",
|
||||||
rootSlector: ".tgme_channel_history",
|
rootSelector: ".tgme_channel_history",
|
||||||
fixer: FIXER_BR,
|
fixer: FIXER_BR,
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
pattern: "baidu.com",
|
pattern: "baidu.com",
|
||||||
selector: "html",
|
selector: "html",
|
||||||
rootSlector: "",
|
rootSelector: "",
|
||||||
fixer: FIXER_FONTSIZE,
|
fixer: FIXER_FONTSIZE,
|
||||||
},
|
},
|
||||||
|
{
|
||||||
|
pattern: "chat.openai.com",
|
||||||
|
selector: "div[data-testid^=conversation-turn] .items-start > div",
|
||||||
|
rootSelector: "",
|
||||||
|
fixer: FIXER_BN,
|
||||||
|
},
|
||||||
];
|
];
|
||||||
|
|
||||||
/**
|
/**
|
||||||
@@ -94,6 +101,26 @@ function brFixer(node) {
|
|||||||
node.innerHTML = html;
|
node.innerHTML = html;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 目标是将 `\n` 替换成 `p`
|
||||||
|
* @param {*} node
|
||||||
|
* @returns
|
||||||
|
*/
|
||||||
|
function bnFixer(node) {
|
||||||
|
if (node.hasAttribute(fixedSign)) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
node.setAttribute(fixedSign, "true");
|
||||||
|
|
||||||
|
const childs = node.childNodes;
|
||||||
|
if (childs.length === 1 && childs[0].nodeName === "#text") {
|
||||||
|
node.innerHTML = node.innerHTML
|
||||||
|
.split("\n")
|
||||||
|
.map((item) => `<p>${item || " "}</p>`)
|
||||||
|
.join("");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* 修复字体大小问题,如 baidu.com
|
* 修复字体大小问题,如 baidu.com
|
||||||
* @param {*} node
|
* @param {*} node
|
||||||
@@ -107,6 +134,7 @@ function fontSizeFixer(node) {
|
|||||||
*/
|
*/
|
||||||
const fixerMap = {
|
const fixerMap = {
|
||||||
[FIXER_BR]: brFixer,
|
[FIXER_BR]: brFixer,
|
||||||
|
[FIXER_BN]: bnFixer,
|
||||||
[FIXER_FONTSIZE]: fontSizeFixer,
|
[FIXER_FONTSIZE]: fontSizeFixer,
|
||||||
};
|
};
|
||||||
|
|
||||||
@@ -114,9 +142,9 @@ const fixerMap = {
|
|||||||
* 查找、监听节点,并执行修复函数
|
* 查找、监听节点,并执行修复函数
|
||||||
* @param {*} selector
|
* @param {*} selector
|
||||||
* @param {*} fixer
|
* @param {*} fixer
|
||||||
* @param {*} rootSlector
|
* @param {*} rootSelector
|
||||||
*/
|
*/
|
||||||
function run(selector, fixer, rootSlector) {
|
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) {
|
||||||
@@ -126,14 +154,15 @@ function run(selector, fixer, rootSlector) {
|
|||||||
});
|
});
|
||||||
|
|
||||||
var rootNodes = [document];
|
var rootNodes = [document];
|
||||||
if (rootSlector) {
|
if (rootSelector) {
|
||||||
rootNodes = document.querySelectorAll(rootSlector);
|
rootNodes = document.querySelectorAll(rootSelector);
|
||||||
}
|
}
|
||||||
|
|
||||||
rootNodes.forEach(function (rootNode) {
|
rootNodes.forEach(function (rootNode) {
|
||||||
rootNode.querySelectorAll(selector).forEach(fixer);
|
rootNode.querySelectorAll(selector).forEach(fixer);
|
||||||
mutaObserver.observe(rootNode, {
|
mutaObserver.observe(rootNode, {
|
||||||
childList: true,
|
childList: true,
|
||||||
|
subtree: true,
|
||||||
});
|
});
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
@@ -170,18 +199,19 @@ export const loadOrFetchWebfix = async (url) => {
|
|||||||
/**
|
/**
|
||||||
* 匹配站点
|
* 匹配站点
|
||||||
*/
|
*/
|
||||||
export async function webfix(href, { injectWebfix }) {
|
export async function runWebfix({ injectWebfix }) {
|
||||||
try {
|
try {
|
||||||
if (!injectWebfix) {
|
if (!injectWebfix) {
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
const href = document.location.href;
|
||||||
const sites = await loadOrFetchWebfix(process.env.REACT_APP_WEBFIXURL);
|
const sites = await loadOrFetchWebfix(process.env.REACT_APP_WEBFIXURL);
|
||||||
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)) {
|
||||||
if (fixerMap[site.fixer]) {
|
if (fixerMap[site.fixer]) {
|
||||||
run(site.selector, fixerMap[site.fixer], site.rootSlector);
|
run(site.selector, fixerMap[site.fixer], site.rootSelector);
|
||||||
}
|
}
|
||||||
break;
|
break;
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,110 +1,77 @@
|
|||||||
import React from "react";
|
import { getSettingWithDefault } from "./libs/storage";
|
||||||
import ReactDOM from "react-dom/client";
|
|
||||||
import Action from "./views/Action";
|
|
||||||
import createCache from "@emotion/cache";
|
|
||||||
import { CacheProvider } from "@emotion/react";
|
|
||||||
import {
|
|
||||||
getSettingWithDefault,
|
|
||||||
getRulesWithDefault,
|
|
||||||
getFabWithDefault,
|
|
||||||
} from "./libs/storage";
|
|
||||||
import { Translator } from "./libs/translator";
|
|
||||||
import { trySyncAllSubRules } from "./libs/subRules";
|
import { trySyncAllSubRules } from "./libs/subRules";
|
||||||
import { MSG_TRANS_TOGGLE, MSG_TRANS_PUTRULE } from "./config";
|
|
||||||
import { isIframe } from "./libs/iframe";
|
import { isIframe } from "./libs/iframe";
|
||||||
import { handlePing, injectScript } from "./libs/gm";
|
import { handlePing, injectScript } from "./libs/gm";
|
||||||
import { matchRule } from "./libs/rules";
|
|
||||||
import { genEventName } from "./libs/utils";
|
import { genEventName } from "./libs/utils";
|
||||||
import { webfix } from "./libs/webfix";
|
import { runWebfix } from "./libs/webfix";
|
||||||
|
import {
|
||||||
|
runIframe,
|
||||||
|
runTranslator,
|
||||||
|
showFab,
|
||||||
|
showTransbox,
|
||||||
|
windowListener,
|
||||||
|
showErr,
|
||||||
|
} from "./common";
|
||||||
|
|
||||||
|
function runSettingPage() {
|
||||||
|
if (GM?.info?.script?.grant?.includes("unsafeWindow")) {
|
||||||
|
unsafeWindow.GM = GM;
|
||||||
|
unsafeWindow.APP_INFO = {
|
||||||
|
name: process.env.REACT_APP_NAME,
|
||||||
|
version: process.env.REACT_APP_VERSION,
|
||||||
|
};
|
||||||
|
} else {
|
||||||
|
const ping = genEventName();
|
||||||
|
window.addEventListener(ping, handlePing);
|
||||||
|
// window.eval(`(${injectScript})("${ping}")`); // eslint-disable-line
|
||||||
|
const script = document.createElement("script");
|
||||||
|
script.textContent = `(${injectScript})("${ping}")`;
|
||||||
|
document.head.append(script);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* 入口函数
|
* 入口函数
|
||||||
*/
|
*/
|
||||||
const init = async () => {
|
|
||||||
// 设置页面
|
|
||||||
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)
|
|
||||||
) {
|
|
||||||
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);
|
|
||||||
}
|
|
||||||
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
|
|
||||||
// 翻译页面
|
|
||||||
const href = isIframe ? document.referrer : document.location.href;
|
|
||||||
const setting = await getSettingWithDefault();
|
|
||||||
const rules = await getRulesWithDefault();
|
|
||||||
const rule = await matchRule(rules, href, setting);
|
|
||||||
const translator = new Translator(rule, setting);
|
|
||||||
webfix(href, setting);
|
|
||||||
|
|
||||||
if (isIframe) {
|
|
||||||
// iframe
|
|
||||||
window.addEventListener("message", (e) => {
|
|
||||||
const action = e?.data?.action;
|
|
||||||
switch (action) {
|
|
||||||
case MSG_TRANS_TOGGLE:
|
|
||||||
translator.toggle();
|
|
||||||
break;
|
|
||||||
case MSG_TRANS_PUTRULE:
|
|
||||||
translator.updateRule(e.data.args || {});
|
|
||||||
break;
|
|
||||||
default:
|
|
||||||
}
|
|
||||||
});
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
|
|
||||||
// 浮球按钮
|
|
||||||
const fab = await getFabWithDefault();
|
|
||||||
const $action = document.createElement("div");
|
|
||||||
$action.setAttribute("id", "kiss-translator");
|
|
||||||
document.body.parentElement.appendChild($action);
|
|
||||||
const shadowContainer = $action.attachShadow({ mode: "closed" });
|
|
||||||
const emotionRoot = document.createElement("style");
|
|
||||||
const shadowRootElement = document.createElement("div");
|
|
||||||
shadowContainer.appendChild(emotionRoot);
|
|
||||||
shadowContainer.appendChild(shadowRootElement);
|
|
||||||
const cache = createCache({
|
|
||||||
key: "css",
|
|
||||||
prepend: true,
|
|
||||||
container: emotionRoot,
|
|
||||||
});
|
|
||||||
ReactDOM.createRoot(shadowRootElement).render(
|
|
||||||
<React.StrictMode>
|
|
||||||
<CacheProvider value={cache}>
|
|
||||||
<Action translator={translator} fab={fab} />
|
|
||||||
</CacheProvider>
|
|
||||||
</React.StrictMode>
|
|
||||||
);
|
|
||||||
|
|
||||||
// 同步订阅规则
|
|
||||||
trySyncAllSubRules(setting);
|
|
||||||
};
|
|
||||||
|
|
||||||
(async () => {
|
(async () => {
|
||||||
try {
|
try {
|
||||||
await init();
|
// 设置页面
|
||||||
|
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) {
|
} catch (err) {
|
||||||
console.error("[KISS-Translator]", err);
|
showErr(err);
|
||||||
const $err = document.createElement("div");
|
|
||||||
$err.innerText = `KISS-Translator: ${err.message}`;
|
|
||||||
$err.style.cssText = "background:red; color:#fff;";
|
|
||||||
document.body.prepend($err);
|
|
||||||
}
|
}
|
||||||
})();
|
})();
|
||||||
|
|||||||
@@ -1,65 +1,51 @@
|
|||||||
import { useCallback, useEffect, useMemo, useState } from "react";
|
import { useEffect, useMemo, useState } from "react";
|
||||||
import { limitNumber } from "../../libs/utils";
|
import { limitNumber } from "../../libs/utils";
|
||||||
import { isMobile } from "../../libs/mobile";
|
import { isMobile } from "../../libs/mobile";
|
||||||
import { setFab } from "../../libs/storage";
|
import { updateFab } from "../../libs/storage";
|
||||||
|
import { debounce } from "../../libs/utils";
|
||||||
|
import Paper from "@mui/material/Paper";
|
||||||
|
|
||||||
const getEdgePosition = (
|
const getEdgePosition = ({
|
||||||
{ x: left, y: top, edge },
|
x: left,
|
||||||
|
y: top,
|
||||||
|
width,
|
||||||
|
height,
|
||||||
windowWidth,
|
windowWidth,
|
||||||
windowHeight,
|
windowHeight,
|
||||||
width,
|
hover,
|
||||||
height
|
}) => {
|
||||||
) => {
|
|
||||||
const right = windowWidth - left - width;
|
const right = windowWidth - left - width;
|
||||||
const bottom = windowHeight - top - height;
|
const bottom = windowHeight - top - height;
|
||||||
const min = Math.min(left, top, right, bottom);
|
const min = Math.min(left, top, right, bottom);
|
||||||
switch (min) {
|
switch (min) {
|
||||||
case right:
|
case right:
|
||||||
edge = "right";
|
left = hover ? windowWidth - width : windowWidth - width / 2;
|
||||||
left = windowWidth - width;
|
|
||||||
break;
|
break;
|
||||||
case left:
|
case left:
|
||||||
edge = "left";
|
left = hover ? 0 : -width / 2;
|
||||||
left = 0;
|
|
||||||
break;
|
break;
|
||||||
case bottom:
|
case bottom:
|
||||||
edge = "bottom";
|
top = hover ? windowHeight - height : windowHeight - height / 2;
|
||||||
top = windowHeight - height;
|
|
||||||
break;
|
break;
|
||||||
default:
|
default:
|
||||||
edge = "top";
|
top = hover ? 0 : -height / 2;
|
||||||
top = 0;
|
|
||||||
}
|
}
|
||||||
left = limitNumber(left, 0, windowWidth - width);
|
return { x: left, y: top };
|
||||||
top = limitNumber(top, 0, windowHeight - height);
|
|
||||||
return { x: left, y: top, edge, hide: false };
|
|
||||||
};
|
};
|
||||||
|
|
||||||
const getHidePosition = (
|
function DraggableWrapper({ children, usePaper, ...props }) {
|
||||||
{ x: left, y: top, edge },
|
if (usePaper) {
|
||||||
windowWidth,
|
return (
|
||||||
windowHeight,
|
<Paper {...props} elevation={4}>
|
||||||
width,
|
{children}
|
||||||
height
|
</Paper>
|
||||||
) => {
|
);
|
||||||
switch (edge) {
|
|
||||||
case "right":
|
|
||||||
left = windowWidth - width / 2;
|
|
||||||
break;
|
|
||||||
case "left":
|
|
||||||
left = -width / 2;
|
|
||||||
break;
|
|
||||||
case "bottom":
|
|
||||||
top = windowHeight - height / 2;
|
|
||||||
break;
|
|
||||||
default:
|
|
||||||
top = -height / 2;
|
|
||||||
}
|
}
|
||||||
return { x: left, y: top, edge, hide: true };
|
return <div {...props}>{children}</div>;
|
||||||
};
|
}
|
||||||
|
|
||||||
export default function Draggable({
|
export default function Draggable({
|
||||||
windowSize,
|
windowSize: { w: windowWidth, h: windowHeight },
|
||||||
width,
|
width,
|
||||||
height,
|
height,
|
||||||
left,
|
left,
|
||||||
@@ -70,66 +56,38 @@ export default function Draggable({
|
|||||||
onMove,
|
onMove,
|
||||||
handler,
|
handler,
|
||||||
children,
|
children,
|
||||||
|
usePaper,
|
||||||
}) {
|
}) {
|
||||||
const [origin, setOrigin] = useState({
|
const [hover, setHover] = useState(false);
|
||||||
x: left,
|
const [origin, setOrigin] = useState(null);
|
||||||
y: top,
|
const [position, setPosition] = useState({ x: left, y: top });
|
||||||
px: left,
|
const setFabPosition = useMemo(() => debounce(updateFab, 500), []);
|
||||||
py: top,
|
|
||||||
});
|
|
||||||
const [position, setPosition] = useState({
|
|
||||||
x: left,
|
|
||||||
y: top,
|
|
||||||
edge: null,
|
|
||||||
hide: false,
|
|
||||||
});
|
|
||||||
const [edgeTimer, setEdgeTimer] = useState(null);
|
|
||||||
|
|
||||||
const goEdge = useCallback((w, h, width, height) => {
|
|
||||||
setPosition((pre) => getEdgePosition(pre, w, h, width, height));
|
|
||||||
|
|
||||||
setEdgeTimer(
|
|
||||||
setTimeout(() => {
|
|
||||||
setPosition((pre) => getHidePosition(pre, w, h, width, height));
|
|
||||||
}, 1500)
|
|
||||||
);
|
|
||||||
}, []);
|
|
||||||
|
|
||||||
const handlePointerDown = (e) => {
|
const handlePointerDown = (e) => {
|
||||||
!isMobile && e.target.setPointerCapture(e.pointerId);
|
!isMobile && e.target.setPointerCapture(e.pointerId);
|
||||||
onStart && onStart();
|
onStart && onStart();
|
||||||
edgeTimer && clearTimeout(edgeTimer);
|
const { x, y } = position;
|
||||||
const { clientX, clientY } = isMobile ? e.targetTouches[0] : e;
|
const { clientX, clientY } = isMobile ? e.targetTouches[0] : e;
|
||||||
setOrigin({
|
setOrigin({ x, y, clientX, clientY });
|
||||||
x: position.x,
|
|
||||||
y: position.y,
|
|
||||||
px: clientX,
|
|
||||||
py: clientY,
|
|
||||||
});
|
|
||||||
};
|
};
|
||||||
|
|
||||||
const handlePointerMove = (e) => {
|
const handlePointerMove = (e) => {
|
||||||
onMove && onMove();
|
onMove && onMove();
|
||||||
const { clientX, clientY } = isMobile ? e.targetTouches[0] : e;
|
const { clientX, clientY } = isMobile ? e.targetTouches[0] : e;
|
||||||
if (origin) {
|
if (origin) {
|
||||||
const dx = clientX - origin.px;
|
const dx = clientX - origin.clientX;
|
||||||
const dy = clientY - origin.py;
|
const dy = clientY - origin.clientY;
|
||||||
let x = origin.x + dx;
|
let x = origin.x + dx;
|
||||||
let y = origin.y + dy;
|
let y = origin.y + dy;
|
||||||
const { w, h } = windowSize;
|
x = limitNumber(x, -width / 2, windowWidth - width / 2);
|
||||||
x = limitNumber(x, 0, w - width);
|
y = limitNumber(y, 0, windowHeight - height / 2);
|
||||||
y = limitNumber(y, 0, h - height);
|
setPosition({ x, y });
|
||||||
setPosition({ x, y, edge: null, hide: false });
|
|
||||||
}
|
}
|
||||||
};
|
};
|
||||||
|
|
||||||
const handlePointerUp = (e) => {
|
const handlePointerUp = (e) => {
|
||||||
e.stopPropagation();
|
e.stopPropagation();
|
||||||
setOrigin(null);
|
setOrigin(null);
|
||||||
if (!snapEdge) {
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
goEdge(windowSize.w, windowSize.h, width, height);
|
|
||||||
};
|
};
|
||||||
|
|
||||||
const handleClick = (e) => {
|
const handleClick = (e) => {
|
||||||
@@ -138,35 +96,48 @@ export default function Draggable({
|
|||||||
|
|
||||||
const handleMouseEnter = (e) => {
|
const handleMouseEnter = (e) => {
|
||||||
e.stopPropagation();
|
e.stopPropagation();
|
||||||
if (snapEdge && position.hide) {
|
setHover(true);
|
||||||
edgeTimer && clearTimeout(edgeTimer);
|
};
|
||||||
goEdge(windowSize.w, windowSize.h, width, height);
|
|
||||||
}
|
const handleMouseLeave = (e) => {
|
||||||
|
e.stopPropagation();
|
||||||
|
setHover(false);
|
||||||
};
|
};
|
||||||
|
|
||||||
useEffect(() => {
|
useEffect(() => {
|
||||||
setOrigin(null);
|
if (!snapEdge || !!origin) {
|
||||||
if (!snapEdge) {
|
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
goEdge(windowSize.w, windowSize.h, width, height);
|
|
||||||
}, [snapEdge, goEdge, windowSize.w, windowSize.h, width, height]);
|
|
||||||
|
|
||||||
useEffect(() => {
|
setPosition((pre) => {
|
||||||
if (position.hide) {
|
const edgePosition = getEdgePosition({
|
||||||
setFab({
|
...pre,
|
||||||
x: position.x,
|
width,
|
||||||
y: position.y,
|
height,
|
||||||
|
windowWidth,
|
||||||
|
windowHeight,
|
||||||
|
hover,
|
||||||
});
|
});
|
||||||
}
|
setFabPosition(edgePosition);
|
||||||
}, [position.x, position.y, position.hide]);
|
return edgePosition;
|
||||||
|
});
|
||||||
|
}, [
|
||||||
|
origin,
|
||||||
|
hover,
|
||||||
|
width,
|
||||||
|
height,
|
||||||
|
windowWidth,
|
||||||
|
windowHeight,
|
||||||
|
snapEdge,
|
||||||
|
setFabPosition,
|
||||||
|
]);
|
||||||
|
|
||||||
const opacity = useMemo(() => {
|
const opacity = useMemo(() => {
|
||||||
if (snapEdge) {
|
if (snapEdge) {
|
||||||
return position.hide ? 0.2 : 1;
|
return hover || origin ? 1 : 0.2;
|
||||||
}
|
}
|
||||||
return origin ? 0.8 : 1;
|
return origin ? 0.8 : 1;
|
||||||
}, [origin, snapEdge, position.hide]);
|
}, [origin, snapEdge, hover]);
|
||||||
|
|
||||||
const touchProps = isMobile
|
const touchProps = isMobile
|
||||||
? {
|
? {
|
||||||
@@ -181,7 +152,8 @@ export default function Draggable({
|
|||||||
};
|
};
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<div
|
<DraggableWrapper
|
||||||
|
usePaper={usePaper}
|
||||||
style={{
|
style={{
|
||||||
opacity,
|
opacity,
|
||||||
position: "fixed",
|
position: "fixed",
|
||||||
@@ -191,6 +163,7 @@ export default function Draggable({
|
|||||||
display: show ? "block" : "none",
|
display: show ? "block" : "none",
|
||||||
}}
|
}}
|
||||||
onMouseEnter={handleMouseEnter}
|
onMouseEnter={handleMouseEnter}
|
||||||
|
onMouseLeave={handleMouseLeave}
|
||||||
onClick={handleClick}
|
onClick={handleClick}
|
||||||
>
|
>
|
||||||
<div
|
<div
|
||||||
@@ -202,6 +175,6 @@ export default function Draggable({
|
|||||||
{handler}
|
{handler}
|
||||||
</div>
|
</div>
|
||||||
<div>{children}</div>
|
<div>{children}</div>
|
||||||
</div>
|
</DraggableWrapper>
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,4 +1,3 @@
|
|||||||
import Paper from "@mui/material/Paper";
|
|
||||||
import Fab from "@mui/material/Fab";
|
import Fab from "@mui/material/Fab";
|
||||||
import TranslateIcon from "@mui/icons-material/Translate";
|
import TranslateIcon from "@mui/icons-material/Translate";
|
||||||
import ThemeProvider from "../../hooks/Theme";
|
import ThemeProvider from "../../hooks/Theme";
|
||||||
@@ -9,14 +8,19 @@ import Popup from "../Popup";
|
|||||||
import { debounce } from "../../libs/utils";
|
import { debounce } from "../../libs/utils";
|
||||||
import { isGm } from "../../libs/client";
|
import { isGm } from "../../libs/client";
|
||||||
import Header from "../Popup/Header";
|
import Header from "../Popup/Header";
|
||||||
|
import Box from "@mui/material/Box";
|
||||||
|
import Divider from "@mui/material/Divider";
|
||||||
import {
|
import {
|
||||||
DEFAULT_SHORTCUTS,
|
DEFAULT_SHORTCUTS,
|
||||||
OPT_SHORTCUT_TRANSLATE,
|
OPT_SHORTCUT_TRANSLATE,
|
||||||
OPT_SHORTCUT_STYLE,
|
OPT_SHORTCUT_STYLE,
|
||||||
OPT_SHORTCUT_POPUP,
|
OPT_SHORTCUT_POPUP,
|
||||||
OPT_SHORTCUT_SETTING,
|
OPT_SHORTCUT_SETTING,
|
||||||
|
MSG_TRANS_TOGGLE,
|
||||||
|
MSG_TRANS_TOGGLE_STYLE,
|
||||||
} from "../../config";
|
} from "../../config";
|
||||||
import { shortcutRegister } from "../../libs/shortcut";
|
import { shortcutRegister } from "../../libs/shortcut";
|
||||||
|
import { sendIframeMsg } from "../../libs/iframe";
|
||||||
|
|
||||||
export default function Action({ translator, fab }) {
|
export default function Action({ translator, fab }) {
|
||||||
const fabWidth = 40;
|
const fabWidth = 40;
|
||||||
@@ -51,15 +55,21 @@ export default function Action({ translator, fab }) {
|
|||||||
}, []);
|
}, []);
|
||||||
|
|
||||||
useEffect(() => {
|
useEffect(() => {
|
||||||
|
if (!isGm) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
// 注册快捷键
|
// 注册快捷键
|
||||||
const shortcuts = translator.setting.shortcuts || DEFAULT_SHORTCUTS;
|
const shortcuts = translator.setting.shortcuts || DEFAULT_SHORTCUTS;
|
||||||
const clearShortcuts = [
|
const clearShortcuts = [
|
||||||
shortcutRegister(shortcuts[OPT_SHORTCUT_TRANSLATE], () => {
|
shortcutRegister(shortcuts[OPT_SHORTCUT_TRANSLATE], () => {
|
||||||
translator.toggle();
|
translator.toggle();
|
||||||
|
sendIframeMsg(MSG_TRANS_TOGGLE);
|
||||||
setShowPopup(false);
|
setShowPopup(false);
|
||||||
}),
|
}),
|
||||||
shortcutRegister(shortcuts[OPT_SHORTCUT_STYLE], () => {
|
shortcutRegister(shortcuts[OPT_SHORTCUT_STYLE], () => {
|
||||||
translator.toggleStyle();
|
translator.toggleStyle();
|
||||||
|
sendIframeMsg(MSG_TRANS_TOGGLE_STYLE);
|
||||||
setShowPopup(false);
|
setShowPopup(false);
|
||||||
}),
|
}),
|
||||||
shortcutRegister(shortcuts[OPT_SHORTCUT_POPUP], () => {
|
shortcutRegister(shortcuts[OPT_SHORTCUT_POPUP], () => {
|
||||||
@@ -78,58 +88,56 @@ export default function Action({ translator, fab }) {
|
|||||||
}, [translator]);
|
}, [translator]);
|
||||||
|
|
||||||
useEffect(() => {
|
useEffect(() => {
|
||||||
// 注册菜单
|
if (!isGm) {
|
||||||
const menuCommandIds = [];
|
return;
|
||||||
if (isGm) {
|
|
||||||
try {
|
|
||||||
menuCommandIds.push(
|
|
||||||
GM.registerMenuCommand(
|
|
||||||
"Toggle Translate (Alt+q)",
|
|
||||||
(event) => {
|
|
||||||
translator.toggle();
|
|
||||||
setShowPopup(false);
|
|
||||||
},
|
|
||||||
"Q"
|
|
||||||
),
|
|
||||||
GM.registerMenuCommand(
|
|
||||||
"Toggle Style (Alt+c)",
|
|
||||||
(event) => {
|
|
||||||
translator.toggleStyle();
|
|
||||||
setShowPopup(false);
|
|
||||||
},
|
|
||||||
"C"
|
|
||||||
),
|
|
||||||
GM.registerMenuCommand(
|
|
||||||
"Open Menu (Alt+k)",
|
|
||||||
(event) => {
|
|
||||||
setShowPopup((pre) => !pre);
|
|
||||||
},
|
|
||||||
"K"
|
|
||||||
),
|
|
||||||
GM.registerMenuCommand(
|
|
||||||
"Open Setting (Alt+o)",
|
|
||||||
(event) => {
|
|
||||||
window.open(process.env.REACT_APP_OPTIONSPAGE, "_blank");
|
|
||||||
},
|
|
||||||
"O"
|
|
||||||
)
|
|
||||||
);
|
|
||||||
} catch (err) {
|
|
||||||
console.log("[registerMenuCommand]", err);
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|
||||||
return () => {
|
// 注册菜单
|
||||||
if (isGm) {
|
try {
|
||||||
try {
|
const menuCommandIds = [];
|
||||||
menuCommandIds.forEach((id) => {
|
menuCommandIds.push(
|
||||||
GM.unregisterMenuCommand(id);
|
GM.registerMenuCommand(
|
||||||
});
|
"Toggle Translate (Alt+q)",
|
||||||
} catch (err) {
|
(event) => {
|
||||||
//
|
translator.toggle();
|
||||||
}
|
sendIframeMsg(MSG_TRANS_TOGGLE);
|
||||||
}
|
setShowPopup(false);
|
||||||
};
|
},
|
||||||
|
"Q"
|
||||||
|
),
|
||||||
|
GM.registerMenuCommand(
|
||||||
|
"Toggle Style (Alt+c)",
|
||||||
|
(event) => {
|
||||||
|
translator.toggleStyle();
|
||||||
|
sendIframeMsg(MSG_TRANS_TOGGLE_STYLE);
|
||||||
|
setShowPopup(false);
|
||||||
|
},
|
||||||
|
"C"
|
||||||
|
),
|
||||||
|
GM.registerMenuCommand(
|
||||||
|
"Open Menu (Alt+k)",
|
||||||
|
(event) => {
|
||||||
|
setShowPopup((pre) => !pre);
|
||||||
|
},
|
||||||
|
"K"
|
||||||
|
),
|
||||||
|
GM.registerMenuCommand(
|
||||||
|
"Open Setting (Alt+o)",
|
||||||
|
(event) => {
|
||||||
|
window.open(process.env.REACT_APP_OPTIONSPAGE, "_blank");
|
||||||
|
},
|
||||||
|
"O"
|
||||||
|
)
|
||||||
|
);
|
||||||
|
|
||||||
|
return () => {
|
||||||
|
menuCommandIds.forEach((id) => {
|
||||||
|
GM.unregisterMenuCommand(id);
|
||||||
|
});
|
||||||
|
};
|
||||||
|
} catch (err) {
|
||||||
|
console.log("[registerMenuCommand]", err);
|
||||||
|
}
|
||||||
}, [translator]);
|
}, [translator]);
|
||||||
|
|
||||||
useEffect(() => {
|
useEffect(() => {
|
||||||
@@ -165,7 +173,7 @@ export default function Action({ translator, fab }) {
|
|||||||
windowSize,
|
windowSize,
|
||||||
width: fabWidth,
|
width: fabWidth,
|
||||||
height: fabWidth,
|
height: fabWidth,
|
||||||
left: fab.x ?? 0,
|
left: fab.x ?? -fabWidth,
|
||||||
top: fab.y ?? windowSize.h / 2,
|
top: fab.y ?? windowSize.h / 2,
|
||||||
};
|
};
|
||||||
|
|
||||||
@@ -178,23 +186,23 @@ export default function Action({ translator, fab }) {
|
|||||||
show={showPopup}
|
show={showPopup}
|
||||||
onStart={handleStart}
|
onStart={handleStart}
|
||||||
onMove={handleMove}
|
onMove={handleMove}
|
||||||
|
usePaper
|
||||||
handler={
|
handler={
|
||||||
<Paper style={{ cursor: "move" }} elevation={3}>
|
<Box style={{ cursor: "move" }}>
|
||||||
<Header setShowPopup={setShowPopup} />
|
<Header setShowPopup={setShowPopup} />
|
||||||
</Paper>
|
<Divider />
|
||||||
|
</Box>
|
||||||
}
|
}
|
||||||
>
|
>
|
||||||
<Paper>
|
{showPopup && (
|
||||||
{showPopup && (
|
<Popup setShowPopup={setShowPopup} translator={translator} />
|
||||||
<Popup setShowPopup={setShowPopup} translator={translator} />
|
)}
|
||||||
)}
|
|
||||||
</Paper>
|
|
||||||
</Draggable>
|
</Draggable>
|
||||||
<Draggable
|
<Draggable
|
||||||
key="fab"
|
key="fab"
|
||||||
snapEdge
|
snapEdge
|
||||||
{...fabProps}
|
{...fabProps}
|
||||||
show={translator.setting.hideFab ? false : !showPopup}
|
show={fab.isHide ? false : !showPopup}
|
||||||
onStart={handleStart}
|
onStart={handleStart}
|
||||||
onMove={handleMove}
|
onMove={handleMove}
|
||||||
handler={
|
handler={
|
||||||
|
|||||||
@@ -1,44 +1,14 @@
|
|||||||
import { DEFAULT_COLOR } from "../../config";
|
import { loadingSvg } from "../../libs/svg";
|
||||||
|
|
||||||
export default function LoadingIcon() {
|
export default function LoadingIcon() {
|
||||||
return (
|
return (
|
||||||
<svg
|
<div
|
||||||
viewBox="0 0 100 100"
|
|
||||||
style={{
|
style={{
|
||||||
maxWidth: "1.2em",
|
display: "inline-block",
|
||||||
maxHeight: "1.2em",
|
width: "1.2em",
|
||||||
|
height: "1em",
|
||||||
}}
|
}}
|
||||||
>
|
dangerouslySetInnerHTML={{ __html: loadingSvg }}
|
||||||
<circle fill={DEFAULT_COLOR} stroke="none" cx="6" cy="50" r="6">
|
/>
|
||||||
<animateTransform
|
|
||||||
attributeName="transform"
|
|
||||||
dur="1s"
|
|
||||||
type="translate"
|
|
||||||
values="0 15 ; 0 -15; 0 15"
|
|
||||||
repeatCount="indefinite"
|
|
||||||
begin="0.1"
|
|
||||||
/>
|
|
||||||
</circle>
|
|
||||||
<circle fill={DEFAULT_COLOR} stroke="none" cx="30" cy="50" r="6">
|
|
||||||
<animateTransform
|
|
||||||
attributeName="transform"
|
|
||||||
dur="1s"
|
|
||||||
type="translate"
|
|
||||||
values="0 10 ; 0 -10; 0 10"
|
|
||||||
repeatCount="indefinite"
|
|
||||||
begin="0.2"
|
|
||||||
/>
|
|
||||||
</circle>
|
|
||||||
<circle fill={DEFAULT_COLOR} stroke="none" cx="54" cy="50" r="6">
|
|
||||||
<animateTransform
|
|
||||||
attributeName="transform"
|
|
||||||
dur="1s"
|
|
||||||
type="translate"
|
|
||||||
values="0 5 ; 0 -5; 0 5"
|
|
||||||
repeatCount="indefinite"
|
|
||||||
begin="0.3"
|
|
||||||
/>
|
|
||||||
</circle>
|
|
||||||
</svg>
|
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -120,7 +120,7 @@ export default function Content({ q, translator }) {
|
|||||||
if (loading) {
|
if (loading) {
|
||||||
return (
|
return (
|
||||||
<>
|
<>
|
||||||
{q.length > newlineLength ? <br /> : " "}
|
{q.length >= newlineLength ? <br /> : " "}
|
||||||
<LoadingIcon />
|
<LoadingIcon />
|
||||||
</>
|
</>
|
||||||
);
|
);
|
||||||
@@ -129,7 +129,7 @@ export default function Content({ q, translator }) {
|
|||||||
if (text && !sameLang) {
|
if (text && !sameLang) {
|
||||||
return (
|
return (
|
||||||
<>
|
<>
|
||||||
{q.length > newlineLength ? <br /> : " "}
|
{q.length >= newlineLength ? <br /> : " "}
|
||||||
<StyledSpan
|
<StyledSpan
|
||||||
textStyle={textStyle}
|
textStyle={textStyle}
|
||||||
textDiyStyle={textDiyStyle}
|
textDiyStyle={textDiyStyle}
|
||||||
|
|||||||
@@ -5,6 +5,9 @@ import CircularProgress from "@mui/material/CircularProgress";
|
|||||||
import {
|
import {
|
||||||
OPT_TRANS_ALL,
|
OPT_TRANS_ALL,
|
||||||
OPT_TRANS_MICROSOFT,
|
OPT_TRANS_MICROSOFT,
|
||||||
|
OPT_TRANS_DEEPLFREE,
|
||||||
|
OPT_TRANS_BAIDU,
|
||||||
|
OPT_TRANS_TENCENT,
|
||||||
OPT_TRANS_OPENAI,
|
OPT_TRANS_OPENAI,
|
||||||
OPT_TRANS_CUSTOMIZE,
|
OPT_TRANS_CUSTOMIZE,
|
||||||
URL_KISS_PROXY,
|
URL_KISS_PROXY,
|
||||||
@@ -35,7 +38,8 @@ function TestButton({ translator, api }) {
|
|||||||
text: "hello world",
|
text: "hello world",
|
||||||
fromLang: "en",
|
fromLang: "en",
|
||||||
toLang: "zh-CN",
|
toLang: "zh-CN",
|
||||||
apiSetting: { ...api, useCache: false },
|
apiSetting: api,
|
||||||
|
useCache: false,
|
||||||
});
|
});
|
||||||
if (!text) {
|
if (!text) {
|
||||||
throw new Error("empty reault");
|
throw new Error("empty reault");
|
||||||
@@ -71,9 +75,16 @@ function ApiFields({ translator }) {
|
|||||||
});
|
});
|
||||||
};
|
};
|
||||||
|
|
||||||
|
const buildinTranslators = [
|
||||||
|
OPT_TRANS_MICROSOFT,
|
||||||
|
OPT_TRANS_DEEPLFREE,
|
||||||
|
OPT_TRANS_BAIDU,
|
||||||
|
OPT_TRANS_TENCENT,
|
||||||
|
];
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<Stack spacing={3}>
|
<Stack spacing={3}>
|
||||||
{translator !== OPT_TRANS_MICROSOFT && (
|
{!buildinTranslators.includes(translator) && (
|
||||||
<>
|
<>
|
||||||
<TextField
|
<TextField
|
||||||
size="small"
|
size="small"
|
||||||
@@ -113,7 +124,7 @@ function ApiFields({ translator }) {
|
|||||||
|
|
||||||
<Stack direction="row" spacing={2}>
|
<Stack direction="row" spacing={2}>
|
||||||
<TestButton translator={translator} api={api} />
|
<TestButton translator={translator} api={api} />
|
||||||
{translator !== OPT_TRANS_MICROSOFT && (
|
{!buildinTranslators.includes(translator) && (
|
||||||
<Button
|
<Button
|
||||||
size="small"
|
size="small"
|
||||||
variant="outlined"
|
variant="outlined"
|
||||||
|
|||||||
@@ -1,4 +1,3 @@
|
|||||||
import PropTypes from "prop-types";
|
|
||||||
import AppBar from "@mui/material/AppBar";
|
import AppBar from "@mui/material/AppBar";
|
||||||
import IconButton from "@mui/material/IconButton";
|
import IconButton from "@mui/material/IconButton";
|
||||||
import MenuIcon from "@mui/icons-material/Menu";
|
import MenuIcon from "@mui/icons-material/Menu";
|
||||||
@@ -45,8 +44,4 @@ function Header(props) {
|
|||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
Header.propTypes = {
|
|
||||||
onDrawerToggle: PropTypes.func.isRequired,
|
|
||||||
};
|
|
||||||
|
|
||||||
export default Header;
|
export default Header;
|
||||||
|
|||||||
178
src/views/Options/InputSetting.js
Normal file
178
src/views/Options/InputSetting.js
Normal file
@@ -0,0 +1,178 @@
|
|||||||
|
import Box from "@mui/material/Box";
|
||||||
|
import Stack from "@mui/material/Stack";
|
||||||
|
import TextField from "@mui/material/TextField";
|
||||||
|
import MenuItem from "@mui/material/MenuItem";
|
||||||
|
import { useI18n } from "../../hooks/I18n";
|
||||||
|
import {
|
||||||
|
OPT_TRANS_ALL,
|
||||||
|
OPT_LANGS_FROM,
|
||||||
|
OPT_LANGS_TO,
|
||||||
|
OPT_INPUT_TRANS_SIGNS,
|
||||||
|
} from "../../config";
|
||||||
|
import ShortcutInput from "./ShortcutInput";
|
||||||
|
import FormControlLabel from "@mui/material/FormControlLabel";
|
||||||
|
import Switch from "@mui/material/Switch";
|
||||||
|
import { useInputRule } from "../../hooks/InputRule";
|
||||||
|
import { useCallback } from "react";
|
||||||
|
import Grid from "@mui/material/Grid";
|
||||||
|
import { limitNumber } from "../../libs/utils";
|
||||||
|
|
||||||
|
export default function InputSetting() {
|
||||||
|
const i18n = useI18n();
|
||||||
|
const { inputRule, updateInputRule } = useInputRule();
|
||||||
|
|
||||||
|
const handleChange = (e) => {
|
||||||
|
e.preventDefault();
|
||||||
|
let { name, value } = e.target;
|
||||||
|
switch (name) {
|
||||||
|
case "triggerTime":
|
||||||
|
value = limitNumber(value, 10, 1000);
|
||||||
|
break;
|
||||||
|
default:
|
||||||
|
}
|
||||||
|
updateInputRule({
|
||||||
|
[name]: value,
|
||||||
|
});
|
||||||
|
};
|
||||||
|
|
||||||
|
const handleShortcutInput = useCallback(
|
||||||
|
(val) => {
|
||||||
|
updateInputRule({ triggerShortcut: val });
|
||||||
|
},
|
||||||
|
[updateInputRule]
|
||||||
|
);
|
||||||
|
|
||||||
|
const {
|
||||||
|
transOpen,
|
||||||
|
translator,
|
||||||
|
fromLang,
|
||||||
|
toLang,
|
||||||
|
triggerShortcut,
|
||||||
|
triggerCount,
|
||||||
|
triggerTime,
|
||||||
|
transSign,
|
||||||
|
} = inputRule;
|
||||||
|
|
||||||
|
return (
|
||||||
|
<Box>
|
||||||
|
<Stack spacing={3}>
|
||||||
|
<FormControlLabel
|
||||||
|
control={
|
||||||
|
<Switch
|
||||||
|
size="small"
|
||||||
|
name="transOpen"
|
||||||
|
checked={transOpen}
|
||||||
|
onChange={() => {
|
||||||
|
updateInputRule({ transOpen: !transOpen });
|
||||||
|
}}
|
||||||
|
/>
|
||||||
|
}
|
||||||
|
label={i18n("input_box_translation")}
|
||||||
|
/>
|
||||||
|
|
||||||
|
<TextField
|
||||||
|
select
|
||||||
|
size="small"
|
||||||
|
name="translator"
|
||||||
|
value={translator}
|
||||||
|
label={i18n("translate_service")}
|
||||||
|
onChange={handleChange}
|
||||||
|
>
|
||||||
|
{OPT_TRANS_ALL.map((item) => (
|
||||||
|
<MenuItem key={item} value={item}>
|
||||||
|
{item}
|
||||||
|
</MenuItem>
|
||||||
|
))}
|
||||||
|
</TextField>
|
||||||
|
|
||||||
|
<TextField
|
||||||
|
select
|
||||||
|
size="small"
|
||||||
|
name="fromLang"
|
||||||
|
value={fromLang}
|
||||||
|
label={i18n("from_lang")}
|
||||||
|
onChange={handleChange}
|
||||||
|
>
|
||||||
|
{OPT_LANGS_FROM.map(([lang, name]) => (
|
||||||
|
<MenuItem key={lang} value={lang}>
|
||||||
|
{name}
|
||||||
|
</MenuItem>
|
||||||
|
))}
|
||||||
|
</TextField>
|
||||||
|
|
||||||
|
<TextField
|
||||||
|
select
|
||||||
|
size="small"
|
||||||
|
name="toLang"
|
||||||
|
value={toLang}
|
||||||
|
label={i18n("to_lang")}
|
||||||
|
onChange={handleChange}
|
||||||
|
>
|
||||||
|
{OPT_LANGS_TO.map(([lang, name]) => (
|
||||||
|
<MenuItem key={lang} value={lang}>
|
||||||
|
{name}
|
||||||
|
</MenuItem>
|
||||||
|
))}
|
||||||
|
</TextField>
|
||||||
|
|
||||||
|
<TextField
|
||||||
|
select
|
||||||
|
size="small"
|
||||||
|
name="transSign"
|
||||||
|
value={transSign}
|
||||||
|
label={i18n("input_trans_start_sign")}
|
||||||
|
onChange={handleChange}
|
||||||
|
helperText={i18n("input_trans_start_sign_help")}
|
||||||
|
>
|
||||||
|
<MenuItem value={""}>{i18n("style_none")}</MenuItem>
|
||||||
|
{OPT_INPUT_TRANS_SIGNS.map((item) => (
|
||||||
|
<MenuItem key={item} value={item}>
|
||||||
|
{item}
|
||||||
|
</MenuItem>
|
||||||
|
))}
|
||||||
|
</TextField>
|
||||||
|
|
||||||
|
<Box>
|
||||||
|
<Grid container spacing={2} columns={12}>
|
||||||
|
<Grid item xs={12} sm={12} md={4} lg={4}>
|
||||||
|
<ShortcutInput
|
||||||
|
value={triggerShortcut}
|
||||||
|
onChange={handleShortcutInput}
|
||||||
|
label={i18n("trigger_trans_shortcut")}
|
||||||
|
helperText={i18n("trigger_trans_shortcut_help")}
|
||||||
|
/>
|
||||||
|
</Grid>
|
||||||
|
<Grid item xs={12} sm={12} md={4} lg={4}>
|
||||||
|
<TextField
|
||||||
|
select
|
||||||
|
fullWidth
|
||||||
|
size="small"
|
||||||
|
name="triggerCount"
|
||||||
|
value={triggerCount}
|
||||||
|
label={i18n("shortcut_press_count")}
|
||||||
|
onChange={handleChange}
|
||||||
|
>
|
||||||
|
{[1, 2, 3, 4, 5].map((val) => (
|
||||||
|
<MenuItem key={val} value={val}>
|
||||||
|
{val}
|
||||||
|
</MenuItem>
|
||||||
|
))}
|
||||||
|
</TextField>
|
||||||
|
</Grid>
|
||||||
|
<Grid item xs={12} sm={12} md={4} lg={4}>
|
||||||
|
<TextField
|
||||||
|
fullWidth
|
||||||
|
size="small"
|
||||||
|
label={i18n("combo_timeout")}
|
||||||
|
type="number"
|
||||||
|
name="triggerTime"
|
||||||
|
defaultValue={triggerTime}
|
||||||
|
onChange={handleChange}
|
||||||
|
/>
|
||||||
|
</Grid>
|
||||||
|
</Grid>
|
||||||
|
</Box>
|
||||||
|
</Stack>
|
||||||
|
</Box>
|
||||||
|
);
|
||||||
|
}
|
||||||
@@ -12,6 +12,8 @@ import { useI18n } from "../../hooks/I18n";
|
|||||||
import SyncIcon from "@mui/icons-material/Sync";
|
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 TranslateIcon from '@mui/icons-material/Translate';
|
||||||
|
|
||||||
function LinkItem({ label, url, icon }) {
|
function LinkItem({ label, url, icon }) {
|
||||||
const match = useMatch(url);
|
const match = useMatch(url);
|
||||||
@@ -38,6 +40,18 @@ export default function Navigator(props) {
|
|||||||
url: "/rules",
|
url: "/rules",
|
||||||
icon: <DesignServicesIcon />,
|
icon: <DesignServicesIcon />,
|
||||||
},
|
},
|
||||||
|
{
|
||||||
|
id: "input_setting",
|
||||||
|
label: i18n("input_setting"),
|
||||||
|
url: "/input",
|
||||||
|
icon: <InputIcon />,
|
||||||
|
},
|
||||||
|
{
|
||||||
|
id: "selection_translate",
|
||||||
|
label: i18n("selection_translate"),
|
||||||
|
url: "/tranbox",
|
||||||
|
icon: <TranslateIcon />,
|
||||||
|
},
|
||||||
{
|
{
|
||||||
id: "apis_setting",
|
id: "apis_setting",
|
||||||
label: i18n("apis_setting"),
|
label: i18n("apis_setting"),
|
||||||
|
|||||||
@@ -14,6 +14,7 @@ import {
|
|||||||
OPT_STYLE_DIY,
|
OPT_STYLE_DIY,
|
||||||
OPT_STYLE_USE_COLOR,
|
OPT_STYLE_USE_COLOR,
|
||||||
URL_KISS_RULES_NEW_ISSUE,
|
URL_KISS_RULES_NEW_ISSUE,
|
||||||
|
OPT_SYNCTYPE_WORKER,
|
||||||
} from "../../config";
|
} from "../../config";
|
||||||
import { useState, useRef, useEffect, useMemo } from "react";
|
import { useState, useRef, useEffect, useMemo } from "react";
|
||||||
import { useI18n } from "../../hooks/I18n";
|
import { useI18n } from "../../hooks/I18n";
|
||||||
@@ -48,6 +49,7 @@ import { delSubRules, getSyncWithDefault } from "../../libs/storage";
|
|||||||
import OwSubRule from "./OwSubRule";
|
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";
|
||||||
|
|
||||||
function RuleFields({ rule, rules, setShow, setKeyword }) {
|
function RuleFields({ rule, rules, setShow, setKeyword }) {
|
||||||
const initFormValues = rule || {
|
const initFormValues = rule || {
|
||||||
@@ -444,8 +446,8 @@ function ShareButton({ rules, injectRules, selectedUrl }) {
|
|||||||
const i18n = useI18n();
|
const i18n = useI18n();
|
||||||
const handleClick = async () => {
|
const handleClick = async () => {
|
||||||
try {
|
try {
|
||||||
const { syncUrl, syncKey } = await getSyncWithDefault();
|
const { syncType, syncUrl, syncKey } = await getSyncWithDefault();
|
||||||
if (!syncUrl || !syncKey) {
|
if (syncType !== OPT_SYNCTYPE_WORKER || !syncUrl || !syncKey) {
|
||||||
alert.warning(i18n("error_sync_setting"));
|
alert.warning(i18n("error_sync_setting"));
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
@@ -525,6 +527,10 @@ function UserRules({ subRules }) {
|
|||||||
}
|
}
|
||||||
}, [showAdd]);
|
}, [showAdd]);
|
||||||
|
|
||||||
|
if (!rules.list) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<Stack spacing={3}>
|
<Stack spacing={3}>
|
||||||
<Stack
|
<Stack
|
||||||
@@ -548,7 +554,7 @@ function UserRules({ subRules }) {
|
|||||||
|
|
||||||
<UploadButton text={i18n("import")} onChange={handleImport} />
|
<UploadButton text={i18n("import")} onChange={handleImport} />
|
||||||
<DownloadButton
|
<DownloadButton
|
||||||
data={JSON.stringify([...rules.list].reverse(), null, "\t")}
|
data={JSON.stringify([...rules.list].reverse(), null, 2)}
|
||||||
text={i18n("export")}
|
text={i18n("export")}
|
||||||
/>
|
/>
|
||||||
|
|
||||||
@@ -624,8 +630,9 @@ function SubRulesItem({
|
|||||||
syncAt,
|
syncAt,
|
||||||
selectedUrl,
|
selectedUrl,
|
||||||
delSub,
|
delSub,
|
||||||
updateSub,
|
|
||||||
setSelectedRules,
|
setSelectedRules,
|
||||||
|
updateDataCache,
|
||||||
|
deleteDataCache,
|
||||||
}) {
|
}) {
|
||||||
const [loading, setLoading] = useState(false);
|
const [loading, setLoading] = useState(false);
|
||||||
|
|
||||||
@@ -633,6 +640,7 @@ function SubRulesItem({
|
|||||||
try {
|
try {
|
||||||
await delSub(url);
|
await delSub(url);
|
||||||
await delSubRules(url);
|
await delSubRules(url);
|
||||||
|
await deleteDataCache(url);
|
||||||
} catch (err) {
|
} catch (err) {
|
||||||
console.log("[del subrules]", err);
|
console.log("[del subrules]", err);
|
||||||
}
|
}
|
||||||
@@ -645,7 +653,7 @@ function SubRulesItem({
|
|||||||
if (rules.length > 0 && url === selectedUrl) {
|
if (rules.length > 0 && url === selectedUrl) {
|
||||||
setSelectedRules(rules);
|
setSelectedRules(rules);
|
||||||
}
|
}
|
||||||
await updateSub(url, { syncAt: Date.now() });
|
await updateDataCache(url);
|
||||||
} catch (err) {
|
} catch (err) {
|
||||||
console.log("[sync sub rules]", err);
|
console.log("[sync sub rules]", err);
|
||||||
} finally {
|
} finally {
|
||||||
@@ -680,7 +688,7 @@ function SubRulesItem({
|
|||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
function SubRulesEdit({ subList, addSub }) {
|
function SubRulesEdit({ subList, addSub, updateDataCache }) {
|
||||||
const i18n = useI18n();
|
const i18n = useI18n();
|
||||||
const [inputText, setInputText] = useState("");
|
const [inputText, setInputText] = useState("");
|
||||||
const [inputError, setInputError] = useState("");
|
const [inputError, setInputError] = useState("");
|
||||||
@@ -715,6 +723,7 @@ function SubRulesEdit({ subList, addSub }) {
|
|||||||
throw new Error("empty rules");
|
throw new Error("empty rules");
|
||||||
}
|
}
|
||||||
await addSub(url);
|
await addSub(url);
|
||||||
|
await updateDataCache(url);
|
||||||
setShowInput(false);
|
setShowInput(false);
|
||||||
setInputText("");
|
setInputText("");
|
||||||
} catch (err) {
|
} catch (err) {
|
||||||
@@ -787,7 +796,6 @@ function SubRules({ subRules }) {
|
|||||||
const {
|
const {
|
||||||
subList,
|
subList,
|
||||||
selectSub,
|
selectSub,
|
||||||
updateSub,
|
|
||||||
addSub,
|
addSub,
|
||||||
delSub,
|
delSub,
|
||||||
selectedUrl,
|
selectedUrl,
|
||||||
@@ -795,27 +803,38 @@ function SubRules({ subRules }) {
|
|||||||
setSelectedRules,
|
setSelectedRules,
|
||||||
loading,
|
loading,
|
||||||
} = subRules;
|
} = subRules;
|
||||||
|
const { dataCaches, updateDataCache, deleteDataCache, reloadSync } =
|
||||||
|
useSyncCaches();
|
||||||
|
|
||||||
const handleSelect = (e) => {
|
const handleSelect = (e) => {
|
||||||
const url = e.target.value;
|
const url = e.target.value;
|
||||||
selectSub(url);
|
selectSub(url);
|
||||||
};
|
};
|
||||||
|
|
||||||
|
useEffect(() => {
|
||||||
|
reloadSync();
|
||||||
|
}, [selectedRules, reloadSync]);
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<Stack spacing={3}>
|
<Stack spacing={3}>
|
||||||
<SubRulesEdit subList={subList} addSub={addSub} />
|
<SubRulesEdit
|
||||||
|
subList={subList}
|
||||||
|
addSub={addSub}
|
||||||
|
updateDataCache={updateDataCache}
|
||||||
|
/>
|
||||||
|
|
||||||
<RadioGroup value={selectedUrl} onChange={handleSelect}>
|
<RadioGroup value={selectedUrl} onChange={handleSelect}>
|
||||||
{subList.map((item, index) => (
|
{subList.map((item, index) => (
|
||||||
<SubRulesItem
|
<SubRulesItem
|
||||||
key={item.url}
|
key={item.url}
|
||||||
url={item.url}
|
url={item.url}
|
||||||
syncAt={item.syncAt}
|
syncAt={dataCaches[item.url]}
|
||||||
index={index}
|
index={index}
|
||||||
selectedUrl={selectedUrl}
|
selectedUrl={selectedUrl}
|
||||||
delSub={delSub}
|
delSub={delSub}
|
||||||
updateSub={updateSub}
|
|
||||||
setSelectedRules={setSelectedRules}
|
setSelectedRules={setSelectedRules}
|
||||||
|
updateDataCache={updateDataCache}
|
||||||
|
deleteDataCache={deleteDataCache}
|
||||||
/>
|
/>
|
||||||
))}
|
))}
|
||||||
</RadioGroup>
|
</RadioGroup>
|
||||||
|
|||||||
@@ -12,8 +12,6 @@ import { limitNumber } from "../../libs/utils";
|
|||||||
import { useI18n } from "../../hooks/I18n";
|
import { useI18n } from "../../hooks/I18n";
|
||||||
import { useAlert } from "../../hooks/Alert";
|
import { useAlert } from "../../hooks/Alert";
|
||||||
import { isExt } from "../../libs/client";
|
import { isExt } from "../../libs/client";
|
||||||
import IconButton from "@mui/material/IconButton";
|
|
||||||
import EditIcon from "@mui/icons-material/Edit";
|
|
||||||
import Grid from "@mui/material/Grid";
|
import Grid from "@mui/material/Grid";
|
||||||
import {
|
import {
|
||||||
UI_LANGS,
|
UI_LANGS,
|
||||||
@@ -26,57 +24,14 @@ import {
|
|||||||
OPT_SHORTCUT_POPUP,
|
OPT_SHORTCUT_POPUP,
|
||||||
OPT_SHORTCUT_SETTING,
|
OPT_SHORTCUT_SETTING,
|
||||||
} from "../../config";
|
} from "../../config";
|
||||||
import { useEffect, useState, useRef } from "react";
|
|
||||||
import { useShortcut } from "../../hooks/Shortcut";
|
import { useShortcut } from "../../hooks/Shortcut";
|
||||||
import { shortcutListener } from "../../libs/shortcut";
|
import ShortcutInput from "./ShortcutInput";
|
||||||
|
import { useFab } from "../../hooks/Fab";
|
||||||
|
|
||||||
function ShortcutItem({ action, label }) {
|
function ShortcutItem({ action, label }) {
|
||||||
const { shortcut, setShortcut } = useShortcut(action);
|
const { shortcut, setShortcut } = useShortcut(action);
|
||||||
const [disabled, setDisabled] = useState(true);
|
|
||||||
const inputRef = useRef(null);
|
|
||||||
|
|
||||||
useEffect(() => {
|
|
||||||
if (disabled) {
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
|
|
||||||
inputRef.current.focus();
|
|
||||||
setShortcut([]);
|
|
||||||
|
|
||||||
const clearShortcut = shortcutListener((curkeys, allkeys) => {
|
|
||||||
setShortcut(allkeys);
|
|
||||||
if (curkeys.length === 0) {
|
|
||||||
setDisabled(true);
|
|
||||||
}
|
|
||||||
}, inputRef.current);
|
|
||||||
|
|
||||||
return () => {
|
|
||||||
clearShortcut();
|
|
||||||
};
|
|
||||||
}, [disabled, setShortcut]);
|
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<Stack direction="row">
|
<ShortcutInput value={shortcut} onChange={setShortcut} label={label} />
|
||||||
<TextField
|
|
||||||
size="small"
|
|
||||||
label={label}
|
|
||||||
name={label}
|
|
||||||
value={shortcut.join(" + ")}
|
|
||||||
fullWidth
|
|
||||||
inputRef={inputRef}
|
|
||||||
disabled={disabled}
|
|
||||||
onBlur={() => {
|
|
||||||
setDisabled(true);
|
|
||||||
}}
|
|
||||||
/>
|
|
||||||
<IconButton
|
|
||||||
onClick={() => {
|
|
||||||
setDisabled(false);
|
|
||||||
}}
|
|
||||||
>
|
|
||||||
{<EditIcon />}
|
|
||||||
</IconButton>
|
|
||||||
</Stack>
|
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -84,6 +39,7 @@ export default function Settings() {
|
|||||||
const i18n = useI18n();
|
const i18n = useI18n();
|
||||||
const { setting, updateSetting } = useSetting();
|
const { setting, updateSetting } = useSetting();
|
||||||
const alert = useAlert();
|
const alert = useAlert();
|
||||||
|
const { fab, updateFab } = useFab();
|
||||||
|
|
||||||
const handleChange = (e) => {
|
const handleChange = (e) => {
|
||||||
e.preventDefault();
|
e.preventDefault();
|
||||||
@@ -129,8 +85,9 @@ export default function Settings() {
|
|||||||
clearCache,
|
clearCache,
|
||||||
newlineLength = TRANS_NEWLINE_LENGTH,
|
newlineLength = TRANS_NEWLINE_LENGTH,
|
||||||
mouseKey = OPT_MOUSEKEY_DISABLE,
|
mouseKey = OPT_MOUSEKEY_DISABLE,
|
||||||
hideFab = false,
|
detectRemote = false,
|
||||||
} = setting;
|
} = setting;
|
||||||
|
const { isHide = false } = fab || {};
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<Box>
|
<Box>
|
||||||
@@ -156,7 +113,7 @@ export default function Settings() {
|
|||||||
label={i18n("fetch_limit")}
|
label={i18n("fetch_limit")}
|
||||||
type="number"
|
type="number"
|
||||||
name="fetchLimit"
|
name="fetchLimit"
|
||||||
value={fetchLimit}
|
defaultValue={fetchLimit}
|
||||||
onChange={handleChange}
|
onChange={handleChange}
|
||||||
/>
|
/>
|
||||||
|
|
||||||
@@ -165,7 +122,7 @@ export default function Settings() {
|
|||||||
label={i18n("fetch_interval")}
|
label={i18n("fetch_interval")}
|
||||||
type="number"
|
type="number"
|
||||||
name="fetchInterval"
|
name="fetchInterval"
|
||||||
value={fetchInterval}
|
defaultValue={fetchInterval}
|
||||||
onChange={handleChange}
|
onChange={handleChange}
|
||||||
/>
|
/>
|
||||||
|
|
||||||
@@ -174,7 +131,7 @@ export default function Settings() {
|
|||||||
label={i18n("min_translate_length")}
|
label={i18n("min_translate_length")}
|
||||||
type="number"
|
type="number"
|
||||||
name="minLength"
|
name="minLength"
|
||||||
value={minLength}
|
defaultValue={minLength}
|
||||||
onChange={handleChange}
|
onChange={handleChange}
|
||||||
/>
|
/>
|
||||||
|
|
||||||
@@ -183,7 +140,7 @@ export default function Settings() {
|
|||||||
label={i18n("max_translate_length")}
|
label={i18n("max_translate_length")}
|
||||||
type="number"
|
type="number"
|
||||||
name="maxLength"
|
name="maxLength"
|
||||||
value={maxLength}
|
defaultValue={maxLength}
|
||||||
onChange={handleChange}
|
onChange={handleChange}
|
||||||
/>
|
/>
|
||||||
|
|
||||||
@@ -192,7 +149,7 @@ export default function Settings() {
|
|||||||
label={i18n("num_of_newline_characters")}
|
label={i18n("num_of_newline_characters")}
|
||||||
type="number"
|
type="number"
|
||||||
name="newlineLength"
|
name="newlineLength"
|
||||||
value={newlineLength}
|
defaultValue={newlineLength}
|
||||||
onChange={handleChange}
|
onChange={handleChange}
|
||||||
/>
|
/>
|
||||||
|
|
||||||
@@ -212,6 +169,35 @@ export default function Settings() {
|
|||||||
</Select>
|
</Select>
|
||||||
</FormControl>
|
</FormControl>
|
||||||
|
|
||||||
|
<FormControl size="small">
|
||||||
|
<InputLabel>{i18n("hide_fab_button")}</InputLabel>
|
||||||
|
<Select
|
||||||
|
name="isHide"
|
||||||
|
value={isHide}
|
||||||
|
label={i18n("hide_fab_button")}
|
||||||
|
onChange={(e) => {
|
||||||
|
updateFab({ isHide: e.target.value });
|
||||||
|
}}
|
||||||
|
>
|
||||||
|
<MenuItem value={false}>{i18n("show")}</MenuItem>
|
||||||
|
<MenuItem value={true}>{i18n("hide")}</MenuItem>
|
||||||
|
</Select>
|
||||||
|
</FormControl>
|
||||||
|
|
||||||
|
<FormControl size="small">
|
||||||
|
<InputLabel>{i18n("detect_lang_remote")}</InputLabel>
|
||||||
|
<Select
|
||||||
|
name="detectRemote"
|
||||||
|
value={detectRemote}
|
||||||
|
label={i18n("detect_lang_remote")}
|
||||||
|
onChange={handleChange}
|
||||||
|
>
|
||||||
|
<MenuItem value={false}>{i18n("disable")}</MenuItem>
|
||||||
|
<MenuItem value={true}>{i18n("enable")}</MenuItem>
|
||||||
|
</Select>
|
||||||
|
<FormHelperText>{i18n("detect_lang_remote_help")}</FormHelperText>
|
||||||
|
</FormControl>
|
||||||
|
|
||||||
{isExt ? (
|
{isExt ? (
|
||||||
<FormControl size="small">
|
<FormControl size="small">
|
||||||
<InputLabel>{i18n("if_clear_cache")}</InputLabel>
|
<InputLabel>{i18n("if_clear_cache")}</InputLabel>
|
||||||
@@ -232,44 +218,34 @@ export default function Settings() {
|
|||||||
</FormControl>
|
</FormControl>
|
||||||
) : (
|
) : (
|
||||||
<>
|
<>
|
||||||
<FormControl size="small">
|
<Box>
|
||||||
<InputLabel>{i18n("hide_fab_button")}</InputLabel>
|
<Grid container spacing={2} columns={12}>
|
||||||
<Select
|
<Grid item xs={12} sm={12} md={3} lg={3}>
|
||||||
name="hideFab"
|
<ShortcutItem
|
||||||
value={hideFab}
|
action={OPT_SHORTCUT_TRANSLATE}
|
||||||
label={i18n("hide_fab_button")}
|
label={i18n("toggle_translate_shortcut")}
|
||||||
onChange={handleChange}
|
/>
|
||||||
>
|
</Grid>
|
||||||
<MenuItem value={false}>{i18n("show")}</MenuItem>
|
<Grid item xs={12} sm={12} md={3} lg={3}>
|
||||||
<MenuItem value={true}>{i18n("hide")}</MenuItem>
|
<ShortcutItem
|
||||||
</Select>
|
action={OPT_SHORTCUT_STYLE}
|
||||||
</FormControl>
|
label={i18n("toggle_style_shortcut")}
|
||||||
<Grid container rowSpacing={2} columns={12}>
|
/>
|
||||||
<Grid item xs={12} sm={12} md={3} lg={3}>
|
</Grid>
|
||||||
<ShortcutItem
|
<Grid item xs={12} sm={12} md={3} lg={3}>
|
||||||
action={OPT_SHORTCUT_TRANSLATE}
|
<ShortcutItem
|
||||||
label={i18n("toggle_translate_shortcut")}
|
action={OPT_SHORTCUT_POPUP}
|
||||||
/>
|
label={i18n("toggle_popup_shortcut")}
|
||||||
|
/>
|
||||||
|
</Grid>
|
||||||
|
<Grid item xs={12} sm={12} md={3} lg={3}>
|
||||||
|
<ShortcutItem
|
||||||
|
action={OPT_SHORTCUT_SETTING}
|
||||||
|
label={i18n("open_setting_shortcut")}
|
||||||
|
/>
|
||||||
|
</Grid>
|
||||||
</Grid>
|
</Grid>
|
||||||
<Grid item xs={12} sm={12} md={3} lg={3}>
|
</Box>
|
||||||
<ShortcutItem
|
|
||||||
action={OPT_SHORTCUT_STYLE}
|
|
||||||
label={i18n("toggle_style_shortcut")}
|
|
||||||
/>
|
|
||||||
</Grid>
|
|
||||||
<Grid item xs={12} sm={12} md={3} lg={3}>
|
|
||||||
<ShortcutItem
|
|
||||||
action={OPT_SHORTCUT_POPUP}
|
|
||||||
label={i18n("toggle_popup_shortcut")}
|
|
||||||
/>
|
|
||||||
</Grid>
|
|
||||||
<Grid item xs={12} sm={12} md={3} lg={3}>
|
|
||||||
<ShortcutItem
|
|
||||||
action={OPT_SHORTCUT_SETTING}
|
|
||||||
label={i18n("open_setting_shortcut")}
|
|
||||||
/>
|
|
||||||
</Grid>
|
|
||||||
</Grid>
|
|
||||||
</>
|
</>
|
||||||
)}
|
)}
|
||||||
</Stack>
|
</Stack>
|
||||||
|
|||||||
56
src/views/Options/ShortcutInput.js
Normal file
56
src/views/Options/ShortcutInput.js
Normal file
@@ -0,0 +1,56 @@
|
|||||||
|
import Stack from "@mui/material/Stack";
|
||||||
|
import TextField from "@mui/material/TextField";
|
||||||
|
import IconButton from "@mui/material/IconButton";
|
||||||
|
import EditIcon from "@mui/icons-material/Edit";
|
||||||
|
import { useEffect, useState, useRef } from "react";
|
||||||
|
import { shortcutListener } from "../../libs/shortcut";
|
||||||
|
|
||||||
|
export default function ShortcutInput({ value, onChange, label, helperText }) {
|
||||||
|
const [disabled, setDisabled] = useState(true);
|
||||||
|
const inputRef = useRef(null);
|
||||||
|
|
||||||
|
useEffect(() => {
|
||||||
|
if (disabled) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
inputRef.current.focus();
|
||||||
|
onChange([]);
|
||||||
|
|
||||||
|
const clearShortcut = shortcutListener((curkeys, allkeys) => {
|
||||||
|
onChange(allkeys);
|
||||||
|
if (curkeys.length === 0) {
|
||||||
|
setDisabled(true);
|
||||||
|
}
|
||||||
|
}, inputRef.current);
|
||||||
|
|
||||||
|
return () => {
|
||||||
|
clearShortcut();
|
||||||
|
};
|
||||||
|
}, [disabled, onChange]);
|
||||||
|
|
||||||
|
return (
|
||||||
|
<Stack direction="row" alignItems="flex-start">
|
||||||
|
<TextField
|
||||||
|
size="small"
|
||||||
|
label={label}
|
||||||
|
name={label}
|
||||||
|
value={value.map((item) => (item === " " ? "Space" : item)).join(" + ")}
|
||||||
|
fullWidth
|
||||||
|
inputRef={inputRef}
|
||||||
|
disabled={disabled}
|
||||||
|
onBlur={() => {
|
||||||
|
setDisabled(true);
|
||||||
|
}}
|
||||||
|
helperText={helperText}
|
||||||
|
/>
|
||||||
|
<IconButton
|
||||||
|
onClick={() => {
|
||||||
|
setDisabled(false);
|
||||||
|
}}
|
||||||
|
>
|
||||||
|
{<EditIcon />}
|
||||||
|
</IconButton>
|
||||||
|
</Stack>
|
||||||
|
);
|
||||||
|
}
|
||||||
@@ -5,7 +5,13 @@ import { useI18n } from "../../hooks/I18n";
|
|||||||
import { useSync } from "../../hooks/Sync";
|
import { useSync } from "../../hooks/Sync";
|
||||||
import Alert from "@mui/material/Alert";
|
import Alert from "@mui/material/Alert";
|
||||||
import Link from "@mui/material/Link";
|
import Link from "@mui/material/Link";
|
||||||
import { URL_KISS_WORKER } from "../../config";
|
import MenuItem from "@mui/material/MenuItem";
|
||||||
|
import {
|
||||||
|
URL_KISS_WORKER,
|
||||||
|
OPT_SYNCTYPE_ALL,
|
||||||
|
OPT_SYNCTYPE_WORKER,
|
||||||
|
OPT_SYNCTYPE_WEBDAV,
|
||||||
|
} from "../../config";
|
||||||
import { useState } from "react";
|
import { useState } from "react";
|
||||||
import { syncSettingAndRules } from "../../libs/sync";
|
import { syncSettingAndRules } from "../../libs/sync";
|
||||||
import Button from "@mui/material/Button";
|
import Button from "@mui/material/Button";
|
||||||
@@ -44,13 +50,37 @@ export default function SyncSetting() {
|
|||||||
}
|
}
|
||||||
};
|
};
|
||||||
|
|
||||||
const { syncUrl, syncKey } = sync;
|
if (!sync) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
const {
|
||||||
|
syncType = OPT_SYNCTYPE_WORKER,
|
||||||
|
syncUrl = "",
|
||||||
|
syncUser = "",
|
||||||
|
syncKey = "",
|
||||||
|
} = sync;
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<Box>
|
<Box>
|
||||||
<Stack spacing={3}>
|
<Stack spacing={3}>
|
||||||
<Alert severity="warning">{i18n("sync_warn")}</Alert>
|
<Alert severity="warning">{i18n("sync_warn")}</Alert>
|
||||||
|
|
||||||
|
<TextField
|
||||||
|
select
|
||||||
|
size="small"
|
||||||
|
name="syncType"
|
||||||
|
value={syncType}
|
||||||
|
label={i18n("data_sync_type")}
|
||||||
|
onChange={handleChange}
|
||||||
|
>
|
||||||
|
{OPT_SYNCTYPE_ALL.map((item) => (
|
||||||
|
<MenuItem key={item} value={item}>
|
||||||
|
{item}
|
||||||
|
</MenuItem>
|
||||||
|
))}
|
||||||
|
</TextField>
|
||||||
|
|
||||||
<TextField
|
<TextField
|
||||||
size="small"
|
size="small"
|
||||||
label={i18n("data_sync_url")}
|
label={i18n("data_sync_url")}
|
||||||
@@ -58,12 +88,24 @@ export default function SyncSetting() {
|
|||||||
value={syncUrl}
|
value={syncUrl}
|
||||||
onChange={handleChange}
|
onChange={handleChange}
|
||||||
helperText={
|
helperText={
|
||||||
<Link href={URL_KISS_WORKER} target="_blank">
|
syncType === OPT_SYNCTYPE_WORKER && (
|
||||||
{i18n("about_sync_api")}
|
<Link href={URL_KISS_WORKER} target="_blank">
|
||||||
</Link>
|
{i18n("about_sync_api")}
|
||||||
|
</Link>
|
||||||
|
)
|
||||||
}
|
}
|
||||||
/>
|
/>
|
||||||
|
|
||||||
|
{syncType === OPT_SYNCTYPE_WEBDAV && (
|
||||||
|
<TextField
|
||||||
|
size="small"
|
||||||
|
label={i18n("data_sync_user")}
|
||||||
|
name="syncUser"
|
||||||
|
value={syncUser}
|
||||||
|
onChange={handleChange}
|
||||||
|
/>
|
||||||
|
)}
|
||||||
|
|
||||||
<TextField
|
<TextField
|
||||||
size="small"
|
size="small"
|
||||||
type="password"
|
type="password"
|
||||||
|
|||||||
137
src/views/Options/Tranbox.js
Normal file
137
src/views/Options/Tranbox.js
Normal file
@@ -0,0 +1,137 @@
|
|||||||
|
import Box from "@mui/material/Box";
|
||||||
|
import Stack from "@mui/material/Stack";
|
||||||
|
import TextField from "@mui/material/TextField";
|
||||||
|
import MenuItem from "@mui/material/MenuItem";
|
||||||
|
import { useI18n } from "../../hooks/I18n";
|
||||||
|
import { OPT_TRANS_ALL, OPT_LANGS_FROM, OPT_LANGS_TO } from "../../config";
|
||||||
|
import ShortcutInput from "./ShortcutInput";
|
||||||
|
import FormControlLabel from "@mui/material/FormControlLabel";
|
||||||
|
import Switch from "@mui/material/Switch";
|
||||||
|
import { useCallback } from "react";
|
||||||
|
import { limitNumber } from "../../libs/utils";
|
||||||
|
import { useTranbox } from "../../hooks/Tranbox";
|
||||||
|
|
||||||
|
export default function Tranbox() {
|
||||||
|
const i18n = useI18n();
|
||||||
|
const { tranboxSetting, updateTranbox } = useTranbox();
|
||||||
|
|
||||||
|
const handleChange = (e) => {
|
||||||
|
e.preventDefault();
|
||||||
|
let { name, value } = e.target;
|
||||||
|
switch (name) {
|
||||||
|
case "btnOffsetX" || "btnOffsetY":
|
||||||
|
value = limitNumber(value, 0, 100);
|
||||||
|
break;
|
||||||
|
default:
|
||||||
|
}
|
||||||
|
updateTranbox({
|
||||||
|
[name]: value,
|
||||||
|
});
|
||||||
|
};
|
||||||
|
|
||||||
|
const handleShortcutInput = useCallback(
|
||||||
|
(val) => {
|
||||||
|
updateTranbox({ tranboxShortcut: val });
|
||||||
|
},
|
||||||
|
[updateTranbox]
|
||||||
|
);
|
||||||
|
|
||||||
|
const {
|
||||||
|
transOpen,
|
||||||
|
translator,
|
||||||
|
fromLang,
|
||||||
|
toLang,
|
||||||
|
tranboxShortcut,
|
||||||
|
btnOffsetX,
|
||||||
|
btnOffsetY,
|
||||||
|
} = tranboxSetting;
|
||||||
|
|
||||||
|
return (
|
||||||
|
<Box>
|
||||||
|
<Stack spacing={3}>
|
||||||
|
<FormControlLabel
|
||||||
|
control={
|
||||||
|
<Switch
|
||||||
|
size="small"
|
||||||
|
name="transOpen"
|
||||||
|
checked={transOpen}
|
||||||
|
onChange={() => {
|
||||||
|
updateTranbox({ transOpen: !transOpen });
|
||||||
|
}}
|
||||||
|
/>
|
||||||
|
}
|
||||||
|
label={i18n("toggle_selection_translate")}
|
||||||
|
/>
|
||||||
|
|
||||||
|
<TextField
|
||||||
|
select
|
||||||
|
size="small"
|
||||||
|
name="translator"
|
||||||
|
value={translator}
|
||||||
|
label={i18n("translate_service")}
|
||||||
|
onChange={handleChange}
|
||||||
|
>
|
||||||
|
{OPT_TRANS_ALL.map((item) => (
|
||||||
|
<MenuItem key={item} value={item}>
|
||||||
|
{item}
|
||||||
|
</MenuItem>
|
||||||
|
))}
|
||||||
|
</TextField>
|
||||||
|
|
||||||
|
<TextField
|
||||||
|
select
|
||||||
|
size="small"
|
||||||
|
name="fromLang"
|
||||||
|
value={fromLang}
|
||||||
|
label={i18n("from_lang")}
|
||||||
|
onChange={handleChange}
|
||||||
|
>
|
||||||
|
{OPT_LANGS_FROM.map(([lang, name]) => (
|
||||||
|
<MenuItem key={lang} value={lang}>
|
||||||
|
{name}
|
||||||
|
</MenuItem>
|
||||||
|
))}
|
||||||
|
</TextField>
|
||||||
|
|
||||||
|
<TextField
|
||||||
|
select
|
||||||
|
size="small"
|
||||||
|
name="toLang"
|
||||||
|
value={toLang}
|
||||||
|
label={i18n("to_lang")}
|
||||||
|
onChange={handleChange}
|
||||||
|
>
|
||||||
|
{OPT_LANGS_TO.map(([lang, name]) => (
|
||||||
|
<MenuItem key={lang} value={lang}>
|
||||||
|
{name}
|
||||||
|
</MenuItem>
|
||||||
|
))}
|
||||||
|
</TextField>
|
||||||
|
|
||||||
|
<TextField
|
||||||
|
size="small"
|
||||||
|
label={i18n("tranbtn_offset_x")}
|
||||||
|
type="number"
|
||||||
|
name="btnOffsetX"
|
||||||
|
defaultValue={btnOffsetX}
|
||||||
|
onChange={handleChange}
|
||||||
|
/>
|
||||||
|
|
||||||
|
<TextField
|
||||||
|
size="small"
|
||||||
|
label={i18n("tranbtn_offset_y")}
|
||||||
|
type="number"
|
||||||
|
name="btnOffsetY"
|
||||||
|
defaultValue={btnOffsetY}
|
||||||
|
onChange={handleChange}
|
||||||
|
/>
|
||||||
|
|
||||||
|
<ShortcutInput
|
||||||
|
value={tranboxShortcut}
|
||||||
|
onChange={handleShortcutInput}
|
||||||
|
label={i18n("trigger_tranbox_shortcut")}
|
||||||
|
/>
|
||||||
|
</Stack>
|
||||||
|
</Box>
|
||||||
|
);
|
||||||
|
}
|
||||||
@@ -21,14 +21,14 @@ import HelpButton from "./HelpButton";
|
|||||||
import { URL_KISS_RULES_NEW_ISSUE } from "../../config";
|
import { URL_KISS_RULES_NEW_ISSUE } from "../../config";
|
||||||
|
|
||||||
function ApiFields({ site }) {
|
function ApiFields({ site }) {
|
||||||
const { selector, rootSlector, fixer } = site;
|
const { selector, rootSelector, fixer } = site;
|
||||||
return (
|
return (
|
||||||
<Stack spacing={3}>
|
<Stack spacing={3}>
|
||||||
<TextField
|
<TextField
|
||||||
size="small"
|
size="small"
|
||||||
label={"rootSlector"}
|
label={"rootSelector"}
|
||||||
name="rootSlector"
|
name="rootSelector"
|
||||||
value={rootSlector || "document"}
|
value={rootSelector || "document"}
|
||||||
disabled
|
disabled
|
||||||
/>
|
/>
|
||||||
<TextField
|
<TextField
|
||||||
|
|||||||
@@ -19,6 +19,8 @@ import { adaptScript } from "../../libs/gm";
|
|||||||
import Alert from "@mui/material/Alert";
|
import Alert from "@mui/material/Alert";
|
||||||
import Apis from "./Apis";
|
import Apis from "./Apis";
|
||||||
import Webfix from "./Webfix";
|
import Webfix from "./Webfix";
|
||||||
|
import InputSetting from "./InputSetting";
|
||||||
|
import Tranbox from "./Tranbox";
|
||||||
|
|
||||||
export default function Options() {
|
export default function Options() {
|
||||||
const [error, setError] = useState("");
|
const [error, setError] = useState("");
|
||||||
@@ -36,7 +38,7 @@ export default function Options() {
|
|||||||
// 检查版本是否一致
|
// 检查版本是否一致
|
||||||
if (version !== process.env.REACT_APP_VERSION) {
|
if (version !== process.env.REACT_APP_VERSION) {
|
||||||
setError(
|
setError(
|
||||||
`The version is inconsistent, please check whether the script(v${version}) is the latest version(v${process.env.REACT_APP_VERSION}). (版本不一致,请检查脚本(v${version})是否为最新版(v${process.env.REACT_APP_VERSION}))`
|
`The version of the local script(v${version}) is not the latest version(v${process.env.REACT_APP_VERSION}). 本地脚本之版本(v${version})非最新版(v${process.env.REACT_APP_VERSION})。`
|
||||||
);
|
);
|
||||||
break;
|
break;
|
||||||
}
|
}
|
||||||
@@ -53,7 +55,9 @@ export default function Options() {
|
|||||||
}
|
}
|
||||||
|
|
||||||
if (++i > 8) {
|
if (++i > 8) {
|
||||||
setError("Time out. (连接超时)");
|
setError(
|
||||||
|
"Time out. Please confirm whether to install or enable KISS Translator GreaseMonkey script? 连接超时,请检查是否安装或启用简约翻译油猴脚本。"
|
||||||
|
);
|
||||||
break;
|
break;
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -70,35 +74,25 @@ export default function Options() {
|
|||||||
if (error) {
|
if (error) {
|
||||||
return (
|
return (
|
||||||
<center>
|
<center>
|
||||||
<Alert severity="error">{error}</Alert>
|
|
||||||
<Divider>
|
<Divider>
|
||||||
<Link
|
<Link
|
||||||
href={process.env.REACT_APP_HOMEPAGE}
|
href={process.env.REACT_APP_HOMEPAGE}
|
||||||
>{`KISS Translator v${process.env.REACT_APP_VERSION}`}</Link>
|
>{`KISS Translator v${process.env.REACT_APP_VERSION}`}</Link>
|
||||||
</Divider>
|
</Divider>
|
||||||
<h2>
|
<Alert severity="error">{error}</Alert>
|
||||||
Please confirm whether to install or enable KISS Translator
|
|
||||||
GreaseMonkey script? (请检查是否安装或启用简约翻译油猴脚本)
|
|
||||||
</h2>
|
|
||||||
<Stack spacing={2}>
|
<Stack spacing={2}>
|
||||||
<Link href={process.env.REACT_APP_USERSCRIPT_DOWNLOADURL}>
|
<Link href={process.env.REACT_APP_USERSCRIPT_DOWNLOADURL}>
|
||||||
Install Userscript for Tampermonkey/Violentmonkey 1 (油猴脚本 安装地址 1)
|
Install/Update Userscript for Tampermonkey/Violentmonkey
|
||||||
</Link>
|
|
||||||
<Link href={process.env.REACT_APP_USERSCRIPT_DOWNLOADURL2}>
|
|
||||||
Install Userscript for Tampermonkey/Violentmonkey 2 (油猴脚本 安装地址 2)
|
|
||||||
</Link>
|
</Link>
|
||||||
|
{/* <Link href={process.env.REACT_APP_USERSCRIPT_DOWNLOADURL2}>
|
||||||
|
Install/Update Userscript for Tampermonkey/Violentmonkey 2
|
||||||
|
</Link> */}
|
||||||
<Link href={process.env.REACT_APP_USERSCRIPT_IOS_DOWNLOADURL}>
|
<Link href={process.env.REACT_APP_USERSCRIPT_IOS_DOWNLOADURL}>
|
||||||
Install Userscript for iOS Safari 1 (油猴脚本 iOS Safari专用 安装地址 1)
|
Install/Update Userscript for iOS Safari
|
||||||
</Link>
|
|
||||||
<Link href={process.env.REACT_APP_USERSCRIPT_IOS_DOWNLOADURL2}>
|
|
||||||
Install Userscript for iOS Safari 2 (油猴脚本 iOS Safari专用 安装地址 2)
|
|
||||||
</Link>
|
|
||||||
<Link href={process.env.REACT_APP_OPTIONSPAGE}>
|
|
||||||
Open Options Page 1 (打开设置页面 1)
|
|
||||||
</Link>
|
|
||||||
<Link href={process.env.REACT_APP_OPTIONSPAGE2}>
|
|
||||||
Open Options Page 2 (打开设置页面 2)
|
|
||||||
</Link>
|
</Link>
|
||||||
|
{/* <Link href={process.env.REACT_APP_USERSCRIPT_IOS_DOWNLOADURL2}>
|
||||||
|
Install/Update Userscript for iOS Safari 2
|
||||||
|
</Link> */}
|
||||||
</Stack>
|
</Stack>
|
||||||
</center>
|
</center>
|
||||||
);
|
);
|
||||||
@@ -126,6 +120,8 @@ export default function Options() {
|
|||||||
<Route path="/" element={<Layout />}>
|
<Route path="/" element={<Layout />}>
|
||||||
<Route index element={<Setting />} />
|
<Route index element={<Setting />} />
|
||||||
<Route path="rules" element={<Rules />} />
|
<Route path="rules" element={<Rules />} />
|
||||||
|
<Route path="input" element={<InputSetting />} />
|
||||||
|
<Route path="tranbox" element={<Tranbox />} />
|
||||||
<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 />} />
|
||||||
|
|||||||
@@ -21,7 +21,12 @@ export default function Header({ setShowPopup }) {
|
|||||||
<IconButton onClick={handleHomepage}>
|
<IconButton onClick={handleHomepage}>
|
||||||
<HomeIcon />
|
<HomeIcon />
|
||||||
</IconButton>
|
</IconButton>
|
||||||
<Box>
|
<Box
|
||||||
|
sx={{
|
||||||
|
userSelect: "none",
|
||||||
|
WebkitUserSelect: "none",
|
||||||
|
}}
|
||||||
|
>
|
||||||
{`${process.env.REACT_APP_NAME} v${process.env.REACT_APP_VERSION}`}
|
{`${process.env.REACT_APP_NAME} v${process.env.REACT_APP_VERSION}`}
|
||||||
</Box>
|
</Box>
|
||||||
</Stack>
|
</Stack>
|
||||||
|
|||||||
@@ -5,7 +5,7 @@ import MenuItem from "@mui/material/MenuItem";
|
|||||||
import FormControlLabel from "@mui/material/FormControlLabel";
|
import FormControlLabel from "@mui/material/FormControlLabel";
|
||||||
import Switch from "@mui/material/Switch";
|
import Switch from "@mui/material/Switch";
|
||||||
import Button from "@mui/material/Button";
|
import Button from "@mui/material/Button";
|
||||||
import { sendTabMsg, getTabInfo } from "../../libs/msg";
|
import { sendBgMsg, sendTabMsg, getTabInfo } from "../../libs/msg";
|
||||||
import { browser } from "../../libs/browser";
|
import { browser } from "../../libs/browser";
|
||||||
import { isExt } from "../../libs/client";
|
import { isExt } from "../../libs/client";
|
||||||
import { useI18n } from "../../hooks/I18n";
|
import { useI18n } from "../../hooks/I18n";
|
||||||
@@ -16,23 +16,27 @@ import {
|
|||||||
MSG_TRANS_TOGGLE,
|
MSG_TRANS_TOGGLE,
|
||||||
MSG_TRANS_GETRULE,
|
MSG_TRANS_GETRULE,
|
||||||
MSG_TRANS_PUTRULE,
|
MSG_TRANS_PUTRULE,
|
||||||
|
MSG_OPEN_OPTIONS,
|
||||||
|
MSG_SAVE_RULE,
|
||||||
OPT_TRANS_ALL,
|
OPT_TRANS_ALL,
|
||||||
OPT_LANGS_FROM,
|
OPT_LANGS_FROM,
|
||||||
OPT_LANGS_TO,
|
OPT_LANGS_TO,
|
||||||
OPT_STYLE_ALL,
|
OPT_STYLE_ALL,
|
||||||
OPT_STYLE_USE_COLOR,
|
OPT_STYLE_USE_COLOR,
|
||||||
CACHE_NAME,
|
|
||||||
} from "../../config";
|
} from "../../config";
|
||||||
import { sendIframeMsg } from "../../libs/iframe";
|
import { sendIframeMsg } from "../../libs/iframe";
|
||||||
import { saveRule } from "../../libs/rules";
|
import { saveRule } from "../../libs/rules";
|
||||||
|
import { tryClearCaches } from "../../libs";
|
||||||
|
|
||||||
export default function Popup({ setShowPopup, translator: tran }) {
|
export default function Popup({ setShowPopup, translator: tran }) {
|
||||||
const i18n = useI18n();
|
const i18n = useI18n();
|
||||||
const [rule, setRule] = useState(tran?.rule);
|
const [rule, setRule] = useState(tran?.rule);
|
||||||
|
|
||||||
const handleOpenSetting = () => {
|
const handleOpenSetting = () => {
|
||||||
if (isExt) {
|
if (!tran) {
|
||||||
browser?.runtime.openOptionsPage();
|
browser?.runtime.openOptionsPage();
|
||||||
|
} else if (isExt) {
|
||||||
|
sendBgMsg(MSG_OPEN_OPTIONS);
|
||||||
} else {
|
} else {
|
||||||
window.open(process.env.REACT_APP_OPTIONSPAGE, "_blank");
|
window.open(process.env.REACT_APP_OPTIONSPAGE, "_blank");
|
||||||
}
|
}
|
||||||
@@ -43,7 +47,7 @@ export default function Popup({ setShowPopup, translator: tran }) {
|
|||||||
try {
|
try {
|
||||||
setRule({ ...rule, transOpen: e.target.checked ? "true" : "false" });
|
setRule({ ...rule, transOpen: e.target.checked ? "true" : "false" });
|
||||||
|
|
||||||
if (isExt) {
|
if (!tran) {
|
||||||
await sendTabMsg(MSG_TRANS_TOGGLE);
|
await sendTabMsg(MSG_TRANS_TOGGLE);
|
||||||
} else {
|
} else {
|
||||||
tran.toggle();
|
tran.toggle();
|
||||||
@@ -59,7 +63,7 @@ export default function Popup({ setShowPopup, translator: tran }) {
|
|||||||
const { name, value } = e.target;
|
const { name, value } = e.target;
|
||||||
setRule((pre) => ({ ...pre, [name]: value }));
|
setRule((pre) => ({ ...pre, [name]: value }));
|
||||||
|
|
||||||
if (isExt) {
|
if (!tran) {
|
||||||
await sendTabMsg(MSG_TRANS_PUTRULE, { [name]: value });
|
await sendTabMsg(MSG_TRANS_PUTRULE, { [name]: value });
|
||||||
} else {
|
} else {
|
||||||
tran.updateRule({ [name]: value });
|
tran.updateRule({ [name]: value });
|
||||||
@@ -71,29 +75,29 @@ export default function Popup({ setShowPopup, translator: tran }) {
|
|||||||
};
|
};
|
||||||
|
|
||||||
const handleClearCache = () => {
|
const handleClearCache = () => {
|
||||||
try {
|
tryClearCaches();
|
||||||
caches.delete(CACHE_NAME);
|
|
||||||
} catch (err) {
|
|
||||||
console.log("[clear cache]", err);
|
|
||||||
}
|
|
||||||
};
|
};
|
||||||
|
|
||||||
const handleSaveRule = async () => {
|
const handleSaveRule = async () => {
|
||||||
try {
|
try {
|
||||||
let host = window.location.host;
|
let href = window.location.href;
|
||||||
if (isExt) {
|
if (!tran) {
|
||||||
const tab = await getTabInfo();
|
const tab = await getTabInfo();
|
||||||
const url = new URL(tab.url);
|
href = tab.url;
|
||||||
host = url.host;
|
}
|
||||||
|
const newRule = { ...rule, pattern: href };
|
||||||
|
if (isExt && tran) {
|
||||||
|
sendBgMsg(MSG_SAVE_RULE, newRule);
|
||||||
|
} else {
|
||||||
|
saveRule(newRule);
|
||||||
}
|
}
|
||||||
saveRule({ ...rule, pattern: host });
|
|
||||||
} catch (err) {
|
} catch (err) {
|
||||||
console.log("[save rule]", err);
|
console.log("[save rule]", err);
|
||||||
}
|
}
|
||||||
};
|
};
|
||||||
|
|
||||||
useEffect(() => {
|
useEffect(() => {
|
||||||
if (!isExt) {
|
if (tran) {
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
(async () => {
|
(async () => {
|
||||||
@@ -106,12 +110,12 @@ export default function Popup({ setShowPopup, translator: tran }) {
|
|||||||
console.log("[query rule]", err);
|
console.log("[query rule]", err);
|
||||||
}
|
}
|
||||||
})();
|
})();
|
||||||
}, []);
|
}, [tran]);
|
||||||
|
|
||||||
if (!rule) {
|
if (!rule) {
|
||||||
return (
|
return (
|
||||||
<Box minWidth={300}>
|
<Box minWidth={300}>
|
||||||
{isExt && (
|
{!tran && (
|
||||||
<>
|
<>
|
||||||
<Header />
|
<Header />
|
||||||
<Divider />
|
<Divider />
|
||||||
@@ -130,7 +134,7 @@ export default function Popup({ setShowPopup, translator: tran }) {
|
|||||||
|
|
||||||
return (
|
return (
|
||||||
<Box minWidth={300}>
|
<Box minWidth={300}>
|
||||||
{isExt && (
|
{!tran && (
|
||||||
<>
|
<>
|
||||||
<Header />
|
<Header />
|
||||||
<Divider />
|
<Divider />
|
||||||
|
|||||||
258
src/views/Selection/DraggableResizable.js
Normal file
258
src/views/Selection/DraggableResizable.js
Normal file
@@ -0,0 +1,258 @@
|
|||||||
|
import { useEffect, useState } from "react";
|
||||||
|
import Paper from "@mui/material/Paper";
|
||||||
|
import Box from "@mui/material/Box";
|
||||||
|
|
||||||
|
function Pointer({
|
||||||
|
direction,
|
||||||
|
size,
|
||||||
|
setSize,
|
||||||
|
position,
|
||||||
|
setPosition,
|
||||||
|
children,
|
||||||
|
minSize,
|
||||||
|
maxSize,
|
||||||
|
...props
|
||||||
|
}) {
|
||||||
|
const [origin, setOrigin] = useState(null);
|
||||||
|
|
||||||
|
function handlePointerDown(e) {
|
||||||
|
e.target.setPointerCapture(e.pointerId);
|
||||||
|
setOrigin({
|
||||||
|
x: position.x,
|
||||||
|
y: position.y,
|
||||||
|
w: size.w,
|
||||||
|
h: size.h,
|
||||||
|
clientX: e.clientX,
|
||||||
|
clientY: e.clientY,
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
function handlePointerMove(e) {
|
||||||
|
if (origin) {
|
||||||
|
const dx = e.clientX - origin.clientX;
|
||||||
|
const dy = e.clientY - origin.clientY;
|
||||||
|
let x = position.x;
|
||||||
|
let y = position.y;
|
||||||
|
let w = size.w;
|
||||||
|
let h = size.h;
|
||||||
|
|
||||||
|
switch (direction) {
|
||||||
|
case "Header":
|
||||||
|
x = origin.x + dx;
|
||||||
|
y = origin.y + dy;
|
||||||
|
break;
|
||||||
|
case "TopLeft":
|
||||||
|
x = origin.x + dx;
|
||||||
|
y = origin.y + dy;
|
||||||
|
w = origin.w - dx;
|
||||||
|
h = origin.h - dy;
|
||||||
|
break;
|
||||||
|
case "Top":
|
||||||
|
y = origin.y + dy;
|
||||||
|
h = origin.h - dy;
|
||||||
|
break;
|
||||||
|
case "TopRight":
|
||||||
|
y = origin.y + dy;
|
||||||
|
w = origin.w + dx;
|
||||||
|
h = origin.h - dy;
|
||||||
|
break;
|
||||||
|
case "Left":
|
||||||
|
x = origin.x + dx;
|
||||||
|
w = origin.w - dx;
|
||||||
|
break;
|
||||||
|
case "Right":
|
||||||
|
w = origin.w + dx;
|
||||||
|
break;
|
||||||
|
case "BottomLeft":
|
||||||
|
x = origin.x + dx;
|
||||||
|
w = origin.w - dx;
|
||||||
|
h = origin.h + dy;
|
||||||
|
break;
|
||||||
|
case "Bottom":
|
||||||
|
h = origin.h + dy;
|
||||||
|
break;
|
||||||
|
case "BottomRight":
|
||||||
|
w = origin.w + dx;
|
||||||
|
h = origin.h + dy;
|
||||||
|
break;
|
||||||
|
default:
|
||||||
|
}
|
||||||
|
|
||||||
|
if (w < minSize.w) {
|
||||||
|
w = minSize.w;
|
||||||
|
x = position.x;
|
||||||
|
}
|
||||||
|
if (w > maxSize.w) {
|
||||||
|
w = maxSize.w;
|
||||||
|
x = position.x;
|
||||||
|
}
|
||||||
|
if (h < minSize.h) {
|
||||||
|
h = minSize.h;
|
||||||
|
y = position.y;
|
||||||
|
}
|
||||||
|
if (h > maxSize.h) {
|
||||||
|
h = maxSize.h;
|
||||||
|
y = position.y;
|
||||||
|
}
|
||||||
|
|
||||||
|
setPosition({ x, y });
|
||||||
|
setSize({ w, h });
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
function handlePointerUp(e) {
|
||||||
|
setOrigin(null);
|
||||||
|
}
|
||||||
|
|
||||||
|
return (
|
||||||
|
<div
|
||||||
|
{...props}
|
||||||
|
onPointerDown={handlePointerDown}
|
||||||
|
onPointerMove={handlePointerMove}
|
||||||
|
onPointerUp={handlePointerUp}
|
||||||
|
>
|
||||||
|
{children}
|
||||||
|
</div>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
export default function DraggableResizable({
|
||||||
|
header,
|
||||||
|
children,
|
||||||
|
defaultPosition = {
|
||||||
|
x: 0,
|
||||||
|
y: 0,
|
||||||
|
},
|
||||||
|
defaultSize = {
|
||||||
|
w: 600,
|
||||||
|
h: 400,
|
||||||
|
},
|
||||||
|
minSize = {
|
||||||
|
w: 300,
|
||||||
|
h: 200,
|
||||||
|
},
|
||||||
|
maxSize = {
|
||||||
|
w: 1200,
|
||||||
|
h: 1200,
|
||||||
|
},
|
||||||
|
onChangeSize,
|
||||||
|
onChangePosition,
|
||||||
|
}) {
|
||||||
|
const lineWidth = 4;
|
||||||
|
const [position, setPosition] = useState(defaultPosition);
|
||||||
|
const [size, setSize] = useState(defaultSize);
|
||||||
|
|
||||||
|
const opts = {
|
||||||
|
size,
|
||||||
|
setSize,
|
||||||
|
position,
|
||||||
|
setPosition,
|
||||||
|
minSize,
|
||||||
|
maxSize,
|
||||||
|
};
|
||||||
|
|
||||||
|
useEffect(() => {
|
||||||
|
onChangeSize && onChangeSize(size);
|
||||||
|
}, [size, onChangeSize]);
|
||||||
|
|
||||||
|
useEffect(() => {
|
||||||
|
onChangePosition && onChangePosition(position);
|
||||||
|
}, [position, onChangePosition]);
|
||||||
|
|
||||||
|
return (
|
||||||
|
<Box
|
||||||
|
style={{
|
||||||
|
position: "fixed",
|
||||||
|
left: position.x,
|
||||||
|
top: position.y,
|
||||||
|
display: "grid",
|
||||||
|
gridTemplateColumns: `${lineWidth * 2}px auto ${lineWidth * 2}px`,
|
||||||
|
gridTemplateRows: `${lineWidth * 2}px auto ${lineWidth * 2}px`,
|
||||||
|
zIndex: 2147483647,
|
||||||
|
}}
|
||||||
|
>
|
||||||
|
<Pointer
|
||||||
|
direction="TopLeft"
|
||||||
|
style={{
|
||||||
|
transform: `translate(${lineWidth}px, ${lineWidth}px)`,
|
||||||
|
cursor: "nw-resize",
|
||||||
|
}}
|
||||||
|
{...opts}
|
||||||
|
/>
|
||||||
|
<Pointer
|
||||||
|
direction="Top"
|
||||||
|
style={{
|
||||||
|
margin: `0 ${lineWidth}px`,
|
||||||
|
transform: `translate(0px, ${lineWidth}px)`,
|
||||||
|
cursor: "row-resize",
|
||||||
|
}}
|
||||||
|
{...opts}
|
||||||
|
/>
|
||||||
|
<Pointer
|
||||||
|
direction="TopRight"
|
||||||
|
style={{
|
||||||
|
transform: `translate(-${lineWidth}px, ${lineWidth}px)`,
|
||||||
|
cursor: "ne-resize",
|
||||||
|
}}
|
||||||
|
{...opts}
|
||||||
|
/>
|
||||||
|
<Pointer
|
||||||
|
direction="Left"
|
||||||
|
style={{
|
||||||
|
margin: `${lineWidth}px 0`,
|
||||||
|
transform: `translate(${lineWidth}px, 0px)`,
|
||||||
|
cursor: "col-resize",
|
||||||
|
}}
|
||||||
|
{...opts}
|
||||||
|
/>
|
||||||
|
<Paper elevation={4}>
|
||||||
|
<Pointer direction="Header" style={{ cursor: "move" }} {...opts}>
|
||||||
|
{header}
|
||||||
|
</Pointer>
|
||||||
|
<div
|
||||||
|
style={{
|
||||||
|
width: size.w,
|
||||||
|
height: size.h,
|
||||||
|
overflow: "hidden auto",
|
||||||
|
}}
|
||||||
|
>
|
||||||
|
{children}
|
||||||
|
</div>
|
||||||
|
</Paper>
|
||||||
|
<Pointer
|
||||||
|
direction="Right"
|
||||||
|
style={{
|
||||||
|
margin: `${lineWidth}px 0`,
|
||||||
|
transform: `translate(-${lineWidth}px, 0px)`,
|
||||||
|
cursor: "col-resize",
|
||||||
|
}}
|
||||||
|
{...opts}
|
||||||
|
/>
|
||||||
|
<Pointer
|
||||||
|
direction="BottomLeft"
|
||||||
|
style={{
|
||||||
|
transform: `translate(${lineWidth}px, -${lineWidth}px)`,
|
||||||
|
cursor: "ne-resize",
|
||||||
|
}}
|
||||||
|
{...opts}
|
||||||
|
/>
|
||||||
|
<Pointer
|
||||||
|
direction="Bottom"
|
||||||
|
style={{
|
||||||
|
margin: `0 ${lineWidth}px`,
|
||||||
|
transform: `translate(0px, -${lineWidth}px)`,
|
||||||
|
cursor: "row-resize",
|
||||||
|
}}
|
||||||
|
{...opts}
|
||||||
|
/>
|
||||||
|
<Pointer
|
||||||
|
direction="BottomRight"
|
||||||
|
style={{
|
||||||
|
transform: `translate(-${lineWidth}px, -${lineWidth}px)`,
|
||||||
|
cursor: "nw-resize",
|
||||||
|
}}
|
||||||
|
{...opts}
|
||||||
|
/>
|
||||||
|
</Box>
|
||||||
|
);
|
||||||
|
}
|
||||||
132
src/views/Selection/TranCont.js
Normal file
132
src/views/Selection/TranCont.js
Normal file
@@ -0,0 +1,132 @@
|
|||||||
|
import TextField from "@mui/material/TextField";
|
||||||
|
import Box from "@mui/material/Box";
|
||||||
|
import Alert from "@mui/material/Alert";
|
||||||
|
import CircularProgress from "@mui/material/CircularProgress";
|
||||||
|
import Chip from "@mui/material/Chip";
|
||||||
|
import Stack from "@mui/material/Stack";
|
||||||
|
import { useI18n } from "../../hooks/I18n";
|
||||||
|
import { DEFAULT_TRANS_APIS, OPT_TRANS_BAIDU } from "../../config";
|
||||||
|
import { useEffect, useState } from "react";
|
||||||
|
import { apiTranslate } from "../../apis";
|
||||||
|
import { isValidWord } from "../../libs/utils";
|
||||||
|
|
||||||
|
const exchangeMap = {
|
||||||
|
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({
|
||||||
|
text,
|
||||||
|
translator,
|
||||||
|
fromLang,
|
||||||
|
toLang,
|
||||||
|
transApis,
|
||||||
|
}) {
|
||||||
|
const i18n = useI18n();
|
||||||
|
const [trText, setTrText] = useState("");
|
||||||
|
const [loading, setLoading] = useState(false);
|
||||||
|
const [error, setError] = useState("");
|
||||||
|
const [dictResult, setDictResult] = useState(null);
|
||||||
|
|
||||||
|
useEffect(() => {
|
||||||
|
(async () => {
|
||||||
|
try {
|
||||||
|
setLoading(true);
|
||||||
|
setTrText("");
|
||||||
|
setError("");
|
||||||
|
setDictResult(null);
|
||||||
|
|
||||||
|
const apis = { ...transApis, ...DEFAULT_TRANS_APIS };
|
||||||
|
const apiSetting = apis[translator];
|
||||||
|
const tranRes = await apiTranslate({
|
||||||
|
text,
|
||||||
|
translator,
|
||||||
|
fromLang,
|
||||||
|
toLang,
|
||||||
|
apiSetting,
|
||||||
|
});
|
||||||
|
setTrText(tranRes[0]);
|
||||||
|
|
||||||
|
// 词典
|
||||||
|
if (isValidWord(text) && toLang.startsWith("zh")) {
|
||||||
|
if (fromLang === "en" && translator === OPT_TRANS_BAIDU) {
|
||||||
|
setDictResult(tranRes[2].dict_result);
|
||||||
|
} else {
|
||||||
|
const dictRes = await apiTranslate({
|
||||||
|
text,
|
||||||
|
translator: OPT_TRANS_BAIDU,
|
||||||
|
fromLang: "en",
|
||||||
|
toLang: "zh-CN",
|
||||||
|
apiSetting: apis[OPT_TRANS_BAIDU],
|
||||||
|
});
|
||||||
|
setDictResult(dictRes[2].dict_result);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
} catch (err) {
|
||||||
|
setError(err.message);
|
||||||
|
} finally {
|
||||||
|
setLoading(false);
|
||||||
|
}
|
||||||
|
})();
|
||||||
|
}, [text, translator, fromLang, toLang, transApis]);
|
||||||
|
|
||||||
|
return (
|
||||||
|
<>
|
||||||
|
<Box>
|
||||||
|
<TextField
|
||||||
|
label={i18n("translated_text")}
|
||||||
|
fullWidth
|
||||||
|
multiline
|
||||||
|
value={trText}
|
||||||
|
/>
|
||||||
|
</Box>
|
||||||
|
|
||||||
|
{loading && <CircularProgress size={24} />}
|
||||||
|
{error && <Alert severity="error">{error}</Alert>}
|
||||||
|
{dictResult && <DictCont dictResult={dictResult} />}
|
||||||
|
</>
|
||||||
|
);
|
||||||
|
}
|
||||||
162
src/views/Selection/Tranbox.js
Normal file
162
src/views/Selection/Tranbox.js
Normal file
@@ -0,0 +1,162 @@
|
|||||||
|
import { SettingProvider } from "../../hooks/Setting";
|
||||||
|
import ThemeProvider from "../../hooks/Theme";
|
||||||
|
import DraggableResizable from "./DraggableResizable";
|
||||||
|
import Header from "../Popup/Header";
|
||||||
|
import Stack from "@mui/material/Stack";
|
||||||
|
import TextField from "@mui/material/TextField";
|
||||||
|
import MenuItem from "@mui/material/MenuItem";
|
||||||
|
import Grid from "@mui/material/Grid";
|
||||||
|
import Box from "@mui/material/Box";
|
||||||
|
import Divider from "@mui/material/Divider";
|
||||||
|
import { useI18n } from "../../hooks/I18n";
|
||||||
|
import { OPT_TRANS_ALL, OPT_LANGS_FROM, OPT_LANGS_TO } from "../../config";
|
||||||
|
import { useState, useRef } from "react";
|
||||||
|
import TranCont from "./TranCont";
|
||||||
|
|
||||||
|
function TranForm({ text, setText, tranboxSetting, transApis }) {
|
||||||
|
const i18n = useI18n();
|
||||||
|
|
||||||
|
const [editMode, setEditMode] = useState(false);
|
||||||
|
const [editText, setEditText] = useState("");
|
||||||
|
const [translator, setTranslator] = useState(tranboxSetting.translator);
|
||||||
|
const [fromLang, setFromLang] = useState(tranboxSetting.fromLang);
|
||||||
|
const [toLang, setToLang] = useState(tranboxSetting.toLang);
|
||||||
|
const inputRef = useRef(null);
|
||||||
|
|
||||||
|
return (
|
||||||
|
<Stack sx={{ p: 2 }} spacing={2}>
|
||||||
|
<Box>
|
||||||
|
<Grid container spacing={2} columns={12}>
|
||||||
|
<Grid item xs={4} sm={4} md={4} lg={4}>
|
||||||
|
<TextField
|
||||||
|
select
|
||||||
|
SelectProps={{ MenuProps: { disablePortal: true } }}
|
||||||
|
fullWidth
|
||||||
|
size="small"
|
||||||
|
name="fromLang"
|
||||||
|
value={fromLang}
|
||||||
|
label={i18n("from_lang")}
|
||||||
|
onChange={(e) => {
|
||||||
|
setFromLang(e.target.value);
|
||||||
|
}}
|
||||||
|
>
|
||||||
|
{OPT_LANGS_FROM.map(([lang, name]) => (
|
||||||
|
<MenuItem key={lang} value={lang}>
|
||||||
|
{name}
|
||||||
|
</MenuItem>
|
||||||
|
))}
|
||||||
|
</TextField>
|
||||||
|
</Grid>
|
||||||
|
<Grid item xs={4} sm={4} md={4} lg={4}>
|
||||||
|
<TextField
|
||||||
|
select
|
||||||
|
SelectProps={{ MenuProps: { disablePortal: true } }}
|
||||||
|
fullWidth
|
||||||
|
size="small"
|
||||||
|
name="toLang"
|
||||||
|
value={toLang}
|
||||||
|
label={i18n("to_lang")}
|
||||||
|
onChange={(e) => {
|
||||||
|
setToLang(e.target.value);
|
||||||
|
}}
|
||||||
|
>
|
||||||
|
{OPT_LANGS_TO.map(([lang, name]) => (
|
||||||
|
<MenuItem key={lang} value={lang}>
|
||||||
|
{name}
|
||||||
|
</MenuItem>
|
||||||
|
))}
|
||||||
|
</TextField>
|
||||||
|
</Grid>
|
||||||
|
<Grid item xs={4} sm={4} md={4} lg={4}>
|
||||||
|
<TextField
|
||||||
|
select
|
||||||
|
SelectProps={{ MenuProps: { disablePortal: true } }}
|
||||||
|
fullWidth
|
||||||
|
size="small"
|
||||||
|
value={translator}
|
||||||
|
name="translator"
|
||||||
|
label={i18n("translate_service")}
|
||||||
|
onChange={(e) => {
|
||||||
|
setTranslator(e.target.value);
|
||||||
|
}}
|
||||||
|
>
|
||||||
|
{OPT_TRANS_ALL.map((item) => (
|
||||||
|
<MenuItem key={item} value={item}>
|
||||||
|
{item}
|
||||||
|
</MenuItem>
|
||||||
|
))}
|
||||||
|
</TextField>
|
||||||
|
</Grid>
|
||||||
|
</Grid>
|
||||||
|
</Box>
|
||||||
|
|
||||||
|
<Box>
|
||||||
|
<TextField
|
||||||
|
label={i18n("original_text")}
|
||||||
|
inputRef={inputRef}
|
||||||
|
fullWidth
|
||||||
|
multiline
|
||||||
|
value={editMode ? editText : text}
|
||||||
|
disabled={!editMode}
|
||||||
|
onChange={(e) => {
|
||||||
|
setEditText(e.target.value);
|
||||||
|
}}
|
||||||
|
onClick={() => {
|
||||||
|
setEditMode(true);
|
||||||
|
setEditText(text);
|
||||||
|
const timer = setTimeout(() => {
|
||||||
|
clearTimeout(timer);
|
||||||
|
inputRef.current?.focus();
|
||||||
|
}, 100);
|
||||||
|
}}
|
||||||
|
onBlur={() => {
|
||||||
|
setEditMode(false);
|
||||||
|
setText(editText.trim());
|
||||||
|
}}
|
||||||
|
/>
|
||||||
|
</Box>
|
||||||
|
|
||||||
|
<TranCont
|
||||||
|
text={text}
|
||||||
|
translator={translator}
|
||||||
|
fromLang={fromLang}
|
||||||
|
toLang={toLang}
|
||||||
|
transApis={transApis}
|
||||||
|
/>
|
||||||
|
</Stack>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
export default function TranBox({
|
||||||
|
text,
|
||||||
|
setText,
|
||||||
|
setShowBox,
|
||||||
|
tranboxSetting,
|
||||||
|
transApis,
|
||||||
|
boxSize,
|
||||||
|
setBoxSize,
|
||||||
|
boxPosition,
|
||||||
|
setBoxPosition,
|
||||||
|
}) {
|
||||||
|
return (
|
||||||
|
<SettingProvider>
|
||||||
|
<ThemeProvider>
|
||||||
|
<DraggableResizable
|
||||||
|
defaultPosition={boxPosition}
|
||||||
|
defaultSize={boxSize}
|
||||||
|
header={<Header setShowPopup={setShowBox} />}
|
||||||
|
onChangeSize={setBoxSize}
|
||||||
|
onChangePosition={setBoxPosition}
|
||||||
|
>
|
||||||
|
<Divider />
|
||||||
|
<TranForm
|
||||||
|
text={text}
|
||||||
|
setText={setText}
|
||||||
|
tranboxSetting={tranboxSetting}
|
||||||
|
transApis={transApis}
|
||||||
|
/>
|
||||||
|
</DraggableResizable>
|
||||||
|
</ThemeProvider>
|
||||||
|
</SettingProvider>
|
||||||
|
);
|
||||||
|
}
|
||||||
36
src/views/Selection/Tranbtn.js
Normal file
36
src/views/Selection/Tranbtn.js
Normal file
@@ -0,0 +1,36 @@
|
|||||||
|
export default function TranBtn({ onClick, position, tranboxSetting }) {
|
||||||
|
return (
|
||||||
|
<div
|
||||||
|
style={{
|
||||||
|
cursor: "pointer",
|
||||||
|
position: "fixed",
|
||||||
|
left: position.x + tranboxSetting.btnOffsetX,
|
||||||
|
top: position.y + tranboxSetting.btnOffsetY,
|
||||||
|
zIndex: 2147483647,
|
||||||
|
}}
|
||||||
|
onClick={onClick}
|
||||||
|
onMouseUp={(e) => {
|
||||||
|
e.stopPropagation();
|
||||||
|
}}
|
||||||
|
>
|
||||||
|
<svg
|
||||||
|
xmlns="http://www.w3.org/2000/svg"
|
||||||
|
width="20"
|
||||||
|
height="20"
|
||||||
|
viewBox="0 0 32 32"
|
||||||
|
version="1.1"
|
||||||
|
>
|
||||||
|
<path
|
||||||
|
d="M0 0 C10.56 0 21.12 0 32 0 C32 10.56 32 21.12 32 32 C21.44 32 10.88 32 0 32 C0 21.44 0 10.88 0 0 Z "
|
||||||
|
fill="#209CEE"
|
||||||
|
transform="translate(0,0)"
|
||||||
|
/>
|
||||||
|
<path
|
||||||
|
d="M0 0 C0.66 0 1.32 0 2 0 C2 2.97 2 5.94 2 9 C2.969375 8.2575 3.93875 7.515 4.9375 6.75 C5.48277344 6.33234375 6.02804688 5.9146875 6.58984375 5.484375 C8.39053593 3.83283924 8.39053593 3.83283924 9 0 C13.95 0 18.9 0 24 0 C24 0.99 24 1.98 24 3 C22.68 3 21.36 3 20 3 C20 9.27 20 15.54 20 22 C19.01 22 18.02 22 17 22 C17 15.73 17 9.46 17 3 C15.35 3 13.7 3 12 3 C11.731875 3.598125 11.46375 4.19625 11.1875 4.8125 C10.01506533 6.97224808 8.80630718 8.35790256 7 10 C8.01790655 12.27071461 8.77442829 13.80784632 10.6875 15.4375 C11.120625 15.953125 11.55375 16.46875 12 17 C11.6875 19.6875 11.6875 19.6875 11 22 C10.34 22 9.68 22 9 22 C8.773125 21.236875 8.54625 20.47375 8.3125 19.6875 C6.73268318 16.45263699 5.16717283 15.58358642 2 14 C2 16.64 2 19.28 2 22 C1.34 22 0.68 22 0 22 C0 14.74 0 7.48 0 0 Z "
|
||||||
|
fill="#E9F5FD"
|
||||||
|
transform="translate(4,5)"
|
||||||
|
/>
|
||||||
|
</svg>
|
||||||
|
</div>
|
||||||
|
);
|
||||||
|
}
|
||||||
85
src/views/Selection/index.js
Normal file
85
src/views/Selection/index.js
Normal file
@@ -0,0 +1,85 @@
|
|||||||
|
import { useState, useEffect } from "react";
|
||||||
|
import TranBtn from "./Tranbtn";
|
||||||
|
import TranBox from "./Tranbox";
|
||||||
|
import { shortcutRegister } from "../../libs/shortcut";
|
||||||
|
|
||||||
|
export default function Slection({ tranboxSetting, transApis }) {
|
||||||
|
const [showBox, setShowBox] = useState(false);
|
||||||
|
const [showBtn, setShowBtn] = useState(false);
|
||||||
|
const [selectedText, setSelText] = useState("");
|
||||||
|
const [text, setText] = useState("");
|
||||||
|
const [position, setPosition] = useState({ x: 0, y: 0 });
|
||||||
|
const [boxSize, setBoxSize] = useState({ w: 600, h: 400 });
|
||||||
|
const [boxPosition, setBoxPosition] = useState({
|
||||||
|
x: (window.innerWidth - 600) / 2,
|
||||||
|
y: (window.innerHeight - 400) / 2,
|
||||||
|
});
|
||||||
|
|
||||||
|
function handleMouseup(e) {
|
||||||
|
const selectedText = window.getSelection()?.toString()?.trim() || "";
|
||||||
|
if (!selectedText) {
|
||||||
|
setShowBtn(false);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
setSelText(selectedText);
|
||||||
|
setShowBtn(true);
|
||||||
|
setPosition({ x: e.clientX, y: e.clientY });
|
||||||
|
}
|
||||||
|
|
||||||
|
const handleClick = (e) => {
|
||||||
|
e.stopPropagation();
|
||||||
|
setShowBtn(false);
|
||||||
|
|
||||||
|
setText(selectedText);
|
||||||
|
if (!showBox) {
|
||||||
|
setShowBox(true);
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
useEffect(() => {
|
||||||
|
window.addEventListener("mouseup", handleMouseup);
|
||||||
|
return () => {
|
||||||
|
window.removeEventListener("mouseup", handleMouseup);
|
||||||
|
};
|
||||||
|
}, []);
|
||||||
|
|
||||||
|
useEffect(() => {
|
||||||
|
const clearShortcut = shortcutRegister(
|
||||||
|
tranboxSetting.tranboxShortcut,
|
||||||
|
() => {
|
||||||
|
setShowBox((pre) => !pre);
|
||||||
|
}
|
||||||
|
);
|
||||||
|
|
||||||
|
return () => {
|
||||||
|
clearShortcut();
|
||||||
|
};
|
||||||
|
}, [tranboxSetting.tranboxShortcut, setShowBox]);
|
||||||
|
|
||||||
|
return (
|
||||||
|
<>
|
||||||
|
{showBox && (
|
||||||
|
<TranBox
|
||||||
|
text={text}
|
||||||
|
setText={setText}
|
||||||
|
boxSize={boxSize}
|
||||||
|
setBoxSize={setBoxSize}
|
||||||
|
boxPosition={boxPosition}
|
||||||
|
setBoxPosition={setBoxPosition}
|
||||||
|
tranboxSetting={tranboxSetting}
|
||||||
|
transApis={transApis}
|
||||||
|
setShowBox={setShowBox}
|
||||||
|
/>
|
||||||
|
)}
|
||||||
|
|
||||||
|
{showBtn && (
|
||||||
|
<TranBtn
|
||||||
|
position={position}
|
||||||
|
tranboxSetting={tranboxSetting}
|
||||||
|
onClick={handleClick}
|
||||||
|
/>
|
||||||
|
)}
|
||||||
|
</>
|
||||||
|
);
|
||||||
|
}
|
||||||
Reference in New Issue
Block a user