Compare commits
32 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
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 |
2
.env
2
.env
@@ -2,7 +2,7 @@ GENERATE_SOURCEMAP=false
|
|||||||
|
|
||||||
REACT_APP_NAME=KISS Translator
|
REACT_APP_NAME=KISS Translator
|
||||||
REACT_APP_NAME_CN=简约翻译
|
REACT_APP_NAME_CN=简约翻译
|
||||||
REACT_APP_VERSION=1.7.1
|
REACT_APP_VERSION=1.7.4
|
||||||
|
|
||||||
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
|
|
||||||
29
README.en.md
29
README.en.md
@@ -24,11 +24,17 @@ If you also like a little more simplicity, welcome to pick it up.
|
|||||||
- [x] Supports multiple translation services
|
- [x] Supports multiple translation services
|
||||||
- [x] Google/Microsoft/DeepL/OpenAI
|
- [x] Google/Microsoft/DeepL/OpenAI
|
||||||
- [x] Custom translation interface
|
- [x] Custom translation interface
|
||||||
- [x] Support input box translation
|
- [x] Covers common translation scenarios
|
||||||
- [x] Support YouTube subtitle translation
|
- [x] Web bilingual translation
|
||||||
- [x] Data synchronization function
|
- [x] Input box translation
|
||||||
- [x] Custom rules + rule subscription
|
- [x] Mouseover translation
|
||||||
- [x] Custom style
|
- [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
|
||||||
@@ -36,7 +42,12 @@ If you also like a little more simplicity, welcome to pick it up.
|
|||||||
- `Alt+O` Open Options
|
- `Alt+O` Open Options
|
||||||
- `Alt+I` Input Box Translation
|
- `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)
|
||||||
@@ -48,7 +59,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.
|
||||||
@@ -73,8 +84,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
|
||||||
|
|||||||
31
README.md
31
README.md
@@ -1,6 +1,6 @@
|
|||||||
# 简约翻译
|
# 简约翻译
|
||||||
|
|
||||||
一个简约的 [双语网页翻译扩展 & 油猴脚本](https://github.com/fishjar/kiss-translator)。
|
一个简约的 [网页双语翻译扩展 & 油猴脚本](https://github.com/fishjar/kiss-translator)。
|
||||||
|
|
||||||
[kiss-translator.webm](https://github.com/fishjar/kiss-translator/assets/1157624/f7ba8a5c-e4a8-4d5a-823a-5c5c67a0a47f)
|
[kiss-translator.webm](https://github.com/fishjar/kiss-translator/assets/1157624/f7ba8a5c-e4a8-4d5a-823a-5c5c67a0a47f)
|
||||||
|
|
||||||
@@ -14,7 +14,7 @@
|
|||||||
|
|
||||||
如果你也喜欢简约一点的,欢迎自取。
|
如果你也喜欢简约一点的,欢迎自取。
|
||||||
|
|
||||||
## 特点
|
## 特性
|
||||||
|
|
||||||
- [x] 保持简约
|
- [x] 保持简约
|
||||||
- [x] 开放源代码
|
- [x] 开放源代码
|
||||||
@@ -24,11 +24,17 @@
|
|||||||
- [x] 支持多种翻译服务
|
- [x] 支持多种翻译服务
|
||||||
- [x] Google/Microsoft/DeepL/OpenAI
|
- [x] Google/Microsoft/DeepL/OpenAI
|
||||||
- [x] 自定义翻译接口
|
- [x] 自定义翻译接口
|
||||||
- [x] 支持输入框翻译
|
- [x] 覆盖常见翻译场景
|
||||||
- [x] 支持 YouTube 字幕翻译
|
- [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` 切换样式
|
||||||
@@ -36,7 +42,12 @@
|
|||||||
- `Alt+O` 打开设置
|
- `Alt+O` 打开设置
|
||||||
- `Alt+I` 输入框翻译
|
- `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)
|
||||||
@@ -73,8 +84,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 minimalist 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
|
||||||
@@ -102,6 +102,7 @@ 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 localhost:3000
|
// @connect localhost:3000
|
||||||
// @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.7.1",
|
"version": "1.7.4",
|
||||||
"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": {
|
||||||
@@ -61,5 +64,6 @@
|
|||||||
"@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"
|
"wrangler": "^3.4.0"
|
||||||
}
|
},
|
||||||
|
"packageManager": "yarn@3.6.3"
|
||||||
}
|
}
|
||||||
|
|||||||
10738
pnpm-lock.yaml
generated
Normal file
10738
pnpm-lock.yaml
generated
Normal file
File diff suppressed because it is too large
Load Diff
@@ -3,7 +3,7 @@
|
|||||||
"message": "简约翻译"
|
"message": "简约翻译"
|
||||||
},
|
},
|
||||||
"app_description": {
|
"app_description": {
|
||||||
"message": "一个简约的双语网页翻译扩展 & 油猴脚本"
|
"message": "一个简约的网页双语翻译扩展 & 油猴脚本"
|
||||||
},
|
},
|
||||||
"toggle_translate": {
|
"toggle_translate": {
|
||||||
"message": "开启翻译"
|
"message": "开启翻译"
|
||||||
|
|||||||
@@ -2,7 +2,7 @@
|
|||||||
"manifest_version": 2,
|
"manifest_version": 2,
|
||||||
"name": "__MSG_app_name__",
|
"name": "__MSG_app_name__",
|
||||||
"description": "__MSG_app_description__",
|
"description": "__MSG_app_description__",
|
||||||
"version": "1.7.1",
|
"version": "1.7.4",
|
||||||
"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.7.1",
|
"version": "1.7.4",
|
||||||
"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",
|
||||||
|
|||||||
@@ -21,7 +21,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,16 +29,14 @@ 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);
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* 谷歌翻译
|
* 谷歌翻译
|
||||||
|
|||||||
@@ -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}` });
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -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: `点击测试`,
|
||||||
@@ -568,8 +576,8 @@ export const I18N = {
|
|||||||
en: `Trigger Translation Shortcut Keys`,
|
en: `Trigger Translation Shortcut Keys`,
|
||||||
},
|
},
|
||||||
trigger_trans_shortcut_help: {
|
trigger_trans_shortcut_help: {
|
||||||
zh: `默认为单击“Alt+i”`,
|
zh: `默认为单击“AltLeft+KeyI”`,
|
||||||
en: `Default is "Alt+i"`,
|
en: `Default is "AltLeft+KeyI"`,
|
||||||
},
|
},
|
||||||
shortcut_press_count: {
|
shortcut_press_count: {
|
||||||
zh: `快捷键连击次数`,
|
zh: `快捷键连击次数`,
|
||||||
|
|||||||
@@ -38,9 +38,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 +49,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";
|
||||||
@@ -201,7 +203,7 @@ export const GLOBLA_RULE = {
|
|||||||
|
|
||||||
// 输入框翻译
|
// 输入框翻译
|
||||||
export const OPT_INPUT_TRANS_SIGNS = ["/", "//", "\\", "\\\\", ">", ">>"];
|
export const OPT_INPUT_TRANS_SIGNS = ["/", "//", "\\", "\\\\", ">", ">>"];
|
||||||
export const DEFAULT_INPUT_SHORTCUT = ["Alt", "i"];
|
export const DEFAULT_INPUT_SHORTCUT = ["AltLeft", "KeyI"];
|
||||||
export const DEFAULT_INPUT_RULE = {
|
export const DEFAULT_INPUT_RULE = {
|
||||||
transOpen: true,
|
transOpen: true,
|
||||||
translator: OPT_TRANS_MICROSOFT,
|
translator: OPT_TRANS_MICROSOFT,
|
||||||
@@ -261,15 +263,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, // 深色模式
|
||||||
@@ -287,19 +289,21 @@ export const DEFAULT_SETTING = {
|
|||||||
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, // 输入框设置
|
inputRule: DEFAULT_INPUT_RULE, // 输入框设置
|
||||||
};
|
};
|
||||||
|
|
||||||
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: {}, // 缓存同步时间
|
dataCaches: {}, // 缓存同步时间
|
||||||
};
|
};
|
||||||
|
|||||||
@@ -1,13 +1,22 @@
|
|||||||
import { browser } from "./libs/browser";
|
import { browser } from "./libs/browser";
|
||||||
|
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 {
|
import {
|
||||||
MSG_TRANS_TOGGLE,
|
MSG_TRANS_TOGGLE,
|
||||||
MSG_TRANS_TOGGLE_STYLE,
|
MSG_TRANS_TOGGLE_STYLE,
|
||||||
MSG_TRANS_GETRULE,
|
MSG_TRANS_GETRULE,
|
||||||
MSG_TRANS_PUTRULE,
|
MSG_TRANS_PUTRULE,
|
||||||
} from "./config";
|
} from "./config";
|
||||||
import { getSettingWithDefault, getRulesWithDefault } from "./libs/storage";
|
import {
|
||||||
|
getSettingWithDefault,
|
||||||
|
getRulesWithDefault,
|
||||||
|
getFabWithDefault,
|
||||||
|
} from "./libs/storage";
|
||||||
import { Translator } from "./libs/translator";
|
import { Translator } from "./libs/translator";
|
||||||
import { isIframe } from "./libs/iframe";
|
import { isIframe, sendIframeMsg, sendPrentMsg } from "./libs/iframe";
|
||||||
import { matchRule } from "./libs/rules";
|
import { matchRule } from "./libs/rules";
|
||||||
import { webfix } from "./libs/webfix";
|
import { webfix } from "./libs/webfix";
|
||||||
|
|
||||||
@@ -15,8 +24,34 @@ import { webfix } from "./libs/webfix";
|
|||||||
* 入口函数
|
* 入口函数
|
||||||
*/
|
*/
|
||||||
const init = async () => {
|
const init = async () => {
|
||||||
const href = isIframe ? document.referrer : document.location.href;
|
|
||||||
const setting = await getSettingWithDefault();
|
const setting = await getSettingWithDefault();
|
||||||
|
|
||||||
|
if (isIframe) {
|
||||||
|
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:
|
||||||
|
}
|
||||||
|
});
|
||||||
|
sendPrentMsg(MSG_TRANS_GETRULE);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
const href = document.location.href;
|
||||||
const rules = await getRulesWithDefault();
|
const rules = await getRulesWithDefault();
|
||||||
const rule = await matchRule(rules, href, setting);
|
const rule = await matchRule(rules, href, setting);
|
||||||
const translator = new Translator(rule, setting);
|
const translator = new Translator(rule, setting);
|
||||||
@@ -27,20 +62,57 @@ const init = async () => {
|
|||||||
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 };
|
||||||
});
|
});
|
||||||
|
window.addEventListener("message", (e) => {
|
||||||
|
const { action } = e.data || {};
|
||||||
|
switch (action) {
|
||||||
|
case MSG_TRANS_GETRULE:
|
||||||
|
sendIframeMsg(MSG_TRANS_PUTRULE, rule);
|
||||||
|
break;
|
||||||
|
default:
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
|
// 浮球按钮
|
||||||
|
const fab = await getFabWithDefault();
|
||||||
|
if (!fab.isHide) {
|
||||||
|
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>
|
||||||
|
);
|
||||||
|
}
|
||||||
};
|
};
|
||||||
|
|
||||||
(async () => {
|
(async () => {
|
||||||
|
|||||||
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 };
|
||||||
|
}
|
||||||
@@ -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,27 +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) {
|
||||||
setData(defaultVal);
|
setData(val);
|
||||||
await storage.setObj(key, defaultVal);
|
}
|
||||||
|
} 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 };
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -11,6 +11,23 @@ export function useSync() {
|
|||||||
return { sync: data, updateSync: update, reloadSync: reload };
|
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
|
* caches sync hook
|
||||||
* @param {*} url
|
* @param {*} url
|
||||||
@@ -21,7 +38,7 @@ export function useSyncCaches() {
|
|||||||
|
|
||||||
const updateDataCache = useCallback(
|
const updateDataCache = useCallback(
|
||||||
async (url) => {
|
async (url) => {
|
||||||
const dataCaches = sync.dataCaches || {};
|
const dataCaches = sync?.dataCaches || {};
|
||||||
dataCaches[url] = Date.now();
|
dataCaches[url] = Date.now();
|
||||||
await updateSync({ dataCaches });
|
await updateSync({ dataCaches });
|
||||||
},
|
},
|
||||||
@@ -30,7 +47,7 @@ export function useSyncCaches() {
|
|||||||
|
|
||||||
const deleteDataCache = useCallback(
|
const deleteDataCache = useCallback(
|
||||||
async (url) => {
|
async (url) => {
|
||||||
const dataCaches = sync.dataCaches || {};
|
const dataCaches = sync?.dataCaches || {};
|
||||||
delete dataCaches[url];
|
delete dataCaches[url];
|
||||||
await updateSync({ dataCaches });
|
await updateSync({ dataCaches });
|
||||||
},
|
},
|
||||||
@@ -38,7 +55,7 @@ export function useSyncCaches() {
|
|||||||
);
|
);
|
||||||
|
|
||||||
return {
|
return {
|
||||||
dataCaches: sync.dataCaches || {},
|
dataCaches: sync?.dataCaches || {},
|
||||||
updateDataCache,
|
updateDataCache,
|
||||||
deleteDataCache,
|
deleteDataCache,
|
||||||
reloadSync,
|
reloadSync,
|
||||||
|
|||||||
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";
|
||||||
|
|||||||
@@ -13,6 +13,7 @@ import {
|
|||||||
DEFAULT_FETCH_LIMIT,
|
DEFAULT_FETCH_LIMIT,
|
||||||
} from "../config";
|
} from "../config";
|
||||||
import { msAuth } from "./auth";
|
import { msAuth } from "./auth";
|
||||||
|
import { isBg } from "./browser";
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* 油猴脚本的请求封装
|
* 油猴脚本的请求封装
|
||||||
@@ -28,7 +29,7 @@ export const fetchGM = async (input, { method = "GET", headers, body } = {}) =>
|
|||||||
headers,
|
headers,
|
||||||
data: body,
|
data: body,
|
||||||
onload: (response) => {
|
onload: (response) => {
|
||||||
if (response.status === 200) {
|
if (response.status < 300) {
|
||||||
const headers = new Headers();
|
const headers = new Headers();
|
||||||
response.responseHeaders.split("\n").forEach((line) => {
|
response.responseHeaders.split("\n").forEach((line) => {
|
||||||
const [name, value] = line.split(":").map((item) => item.trim());
|
const [name, value] = line.split(":").map((item) => item.trim());
|
||||||
@@ -66,7 +67,7 @@ const newCacheReq = async (request) => {
|
|||||||
* @param {*} param0
|
* @param {*} param0
|
||||||
* @returns
|
* @returns
|
||||||
*/
|
*/
|
||||||
const fetchApi = async ({ input, init = {}, translator, token }) => {
|
export const fetchApi = async ({ input, init = {}, translator, token }) => {
|
||||||
if (token) {
|
if (token) {
|
||||||
if (translator === OPT_TRANS_DEEPL) {
|
if (translator === OPT_TRANS_DEEPL) {
|
||||||
init.headers["Authorization"] = `DeepL-Auth-Key ${token}`; // DeepL
|
init.headers["Authorization"] = `DeepL-Auth-Key ${token}`; // DeepL
|
||||||
@@ -176,13 +177,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 sendPrentMsg = (action, args) => {
|
||||||
|
window.parent.postMessage({ action, args }, "*");
|
||||||
|
};
|
||||||
|
|||||||
@@ -149,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();
|
||||||
|
|||||||
@@ -119,6 +119,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);
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* 数据同步
|
* 数据同步
|
||||||
|
|||||||
@@ -25,8 +25,8 @@ const updateSyncDataCache = async (url) => {
|
|||||||
* @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)
|
||||||
);
|
);
|
||||||
@@ -41,10 +41,10 @@ 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);
|
await updateSyncDataCache(subrules.url);
|
||||||
} catch (err) {
|
} catch (err) {
|
||||||
console.log(`[sync subrule error]: ${subrules.url}`, err);
|
console.log(`[sync subrule error]: ${subrules.url}`, err);
|
||||||
@@ -57,14 +57,14 @@ 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 });
|
||||||
|
|
||||||
// 同步修复规则
|
// 同步修复规则
|
||||||
|
|||||||
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();
|
||||||
};
|
};
|
||||||
|
|||||||
@@ -91,8 +91,8 @@ function addLoading(node, loadingId) {
|
|||||||
node.offsetParent?.appendChild(div);
|
node.offsetParent?.appendChild(div);
|
||||||
}
|
}
|
||||||
|
|
||||||
function removeLoading(loadingId) {
|
function removeLoading(node, loadingId) {
|
||||||
const div = document.getElementById(loadingId);
|
const div = node.offsetParent.querySelector(`#${loadingId}`);
|
||||||
if (div) {
|
if (div) {
|
||||||
div.remove();
|
div.remove();
|
||||||
}
|
}
|
||||||
@@ -259,6 +259,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)
|
||||||
@@ -281,14 +297,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);
|
||||||
}
|
}
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
@@ -357,8 +374,17 @@ export class Translator {
|
|||||||
stepShortcutRegister(
|
stepShortcutRegister(
|
||||||
triggerShortcut,
|
triggerShortcut,
|
||||||
async () => {
|
async () => {
|
||||||
const node = document.activeElement;
|
let node = document.activeElement;
|
||||||
if (!node || !(isInputNode(node) || isEditAbleNode(node))) {
|
|
||||||
|
if (!node) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
while (node.shadowRoot) {
|
||||||
|
node = node.shadowRoot.activeElement;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (!isInputNode(node) && !isEditAbleNode(node)) {
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -435,7 +461,7 @@ export class Translator {
|
|||||||
} catch (err) {
|
} catch (err) {
|
||||||
console.log("[translate input]", err.message);
|
console.log("[translate input]", err.message);
|
||||||
} finally {
|
} finally {
|
||||||
removeLoading(loadingId);
|
removeLoading(node, loadingId);
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
triggerCount,
|
triggerCount,
|
||||||
|
|||||||
@@ -10,8 +10,13 @@ import {
|
|||||||
} from "./libs/storage";
|
} from "./libs/storage";
|
||||||
import { Translator } from "./libs/translator";
|
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 {
|
||||||
import { isIframe } from "./libs/iframe";
|
MSG_TRANS_TOGGLE,
|
||||||
|
MSG_TRANS_TOGGLE_STYLE,
|
||||||
|
MSG_TRANS_GETRULE,
|
||||||
|
MSG_TRANS_PUTRULE,
|
||||||
|
} from "./config";
|
||||||
|
import { isIframe, sendIframeMsg, sendPrentMsg } from "./libs/iframe";
|
||||||
import { handlePing, injectScript } from "./libs/gm";
|
import { handlePing, injectScript } from "./libs/gm";
|
||||||
import { matchRule } from "./libs/rules";
|
import { matchRule } from "./libs/rules";
|
||||||
import { genEventName } from "./libs/utils";
|
import { genEventName } from "./libs/utils";
|
||||||
@@ -46,29 +51,49 @@ const init = async () => {
|
|||||||
}
|
}
|
||||||
|
|
||||||
// 翻译页面
|
// 翻译页面
|
||||||
const href = isIframe ? document.referrer : document.location.href;
|
|
||||||
const setting = await getSettingWithDefault();
|
const setting = await getSettingWithDefault();
|
||||||
|
|
||||||
|
if (isIframe) {
|
||||||
|
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:
|
||||||
|
}
|
||||||
|
});
|
||||||
|
sendPrentMsg(MSG_TRANS_GETRULE);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
const href = isIframe ? document.referrer : document.location.href;
|
||||||
const rules = await getRulesWithDefault();
|
const rules = await getRulesWithDefault();
|
||||||
const rule = await matchRule(rules, href, setting);
|
const rule = await matchRule(rules, href, setting);
|
||||||
const translator = new Translator(rule, setting);
|
const translator = new Translator(rule, setting);
|
||||||
webfix(href, setting);
|
webfix(href, setting);
|
||||||
|
|
||||||
if (isIframe) {
|
// 监听消息
|
||||||
// iframe
|
window.addEventListener("message", (e) => {
|
||||||
window.addEventListener("message", (e) => {
|
const { action } = e.data || {};
|
||||||
const action = e?.data?.action;
|
switch (action) {
|
||||||
switch (action) {
|
case MSG_TRANS_GETRULE:
|
||||||
case MSG_TRANS_TOGGLE:
|
sendIframeMsg(MSG_TRANS_PUTRULE, rule);
|
||||||
translator.toggle();
|
break;
|
||||||
break;
|
default:
|
||||||
case MSG_TRANS_PUTRULE:
|
}
|
||||||
translator.updateRule(e.data.args || {});
|
});
|
||||||
break;
|
|
||||||
default:
|
|
||||||
}
|
|
||||||
});
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
|
|
||||||
// 浮球按钮
|
// 浮球按钮
|
||||||
const fab = await getFabWithDefault();
|
const fab = await getFabWithDefault();
|
||||||
|
|||||||
@@ -1,7 +1,7 @@
|
|||||||
import { 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 { debounce } from "../../libs/utils";
|
||||||
import Paper from "@mui/material/Paper";
|
import Paper from "@mui/material/Paper";
|
||||||
|
|
||||||
@@ -61,7 +61,7 @@ export default function Draggable({
|
|||||||
const [hover, setHover] = useState(false);
|
const [hover, setHover] = useState(false);
|
||||||
const [origin, setOrigin] = useState(null);
|
const [origin, setOrigin] = useState(null);
|
||||||
const [position, setPosition] = useState({ x: left, y: top });
|
const [position, setPosition] = useState({ x: left, y: top });
|
||||||
const setFabPosition = useMemo(() => debounce(setFab, 500), []);
|
const setFabPosition = useMemo(() => debounce(updateFab, 500), []);
|
||||||
|
|
||||||
const handlePointerDown = (e) => {
|
const handlePointerDown = (e) => {
|
||||||
!isMobile && e.target.setPointerCapture(e.pointerId);
|
!isMobile && e.target.setPointerCapture(e.pointerId);
|
||||||
|
|||||||
@@ -16,8 +16,11 @@ import {
|
|||||||
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;
|
||||||
@@ -52,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], () => {
|
||||||
@@ -91,6 +100,7 @@ export default function Action({ translator, fab }) {
|
|||||||
"Toggle Translate (Alt+q)",
|
"Toggle Translate (Alt+q)",
|
||||||
(event) => {
|
(event) => {
|
||||||
translator.toggle();
|
translator.toggle();
|
||||||
|
sendIframeMsg(MSG_TRANS_TOGGLE);
|
||||||
setShowPopup(false);
|
setShowPopup(false);
|
||||||
},
|
},
|
||||||
"Q"
|
"Q"
|
||||||
@@ -99,6 +109,7 @@ export default function Action({ translator, fab }) {
|
|||||||
"Toggle Style (Alt+c)",
|
"Toggle Style (Alt+c)",
|
||||||
(event) => {
|
(event) => {
|
||||||
translator.toggleStyle();
|
translator.toggleStyle();
|
||||||
|
sendIframeMsg(MSG_TRANS_TOGGLE_STYLE);
|
||||||
setShowPopup(false);
|
setShowPopup(false);
|
||||||
},
|
},
|
||||||
"C"
|
"C"
|
||||||
@@ -191,7 +202,7 @@ export default function Action({ translator, fab }) {
|
|||||||
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={
|
||||||
|
|||||||
@@ -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}
|
||||||
|
|||||||
@@ -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;
|
||||||
|
|||||||
@@ -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";
|
||||||
@@ -445,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;
|
||||||
}
|
}
|
||||||
@@ -526,6 +527,10 @@ function UserRules({ subRules }) {
|
|||||||
}
|
}
|
||||||
}, [showAdd]);
|
}, [showAdd]);
|
||||||
|
|
||||||
|
if (!rules.list) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<Stack spacing={3}>
|
<Stack spacing={3}>
|
||||||
<Stack
|
<Stack
|
||||||
@@ -549,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")}
|
||||||
/>
|
/>
|
||||||
|
|
||||||
|
|||||||
@@ -26,6 +26,7 @@ import {
|
|||||||
} from "../../config";
|
} from "../../config";
|
||||||
import { useShortcut } from "../../hooks/Shortcut";
|
import { useShortcut } from "../../hooks/Shortcut";
|
||||||
import ShortcutInput from "./ShortcutInput";
|
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);
|
||||||
@@ -38,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();
|
||||||
@@ -83,8 +85,8 @@ export default function Settings() {
|
|||||||
clearCache,
|
clearCache,
|
||||||
newlineLength = TRANS_NEWLINE_LENGTH,
|
newlineLength = TRANS_NEWLINE_LENGTH,
|
||||||
mouseKey = OPT_MOUSEKEY_DISABLE,
|
mouseKey = OPT_MOUSEKEY_DISABLE,
|
||||||
hideFab = false,
|
|
||||||
} = setting;
|
} = setting;
|
||||||
|
const { isHide = false } = fab || {};
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<Box>
|
<Box>
|
||||||
@@ -166,6 +168,21 @@ 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>
|
||||||
|
|
||||||
{isExt ? (
|
{isExt ? (
|
||||||
<FormControl size="small">
|
<FormControl size="small">
|
||||||
<InputLabel>{i18n("if_clear_cache")}</InputLabel>
|
<InputLabel>{i18n("if_clear_cache")}</InputLabel>
|
||||||
@@ -186,19 +203,6 @@ export default function Settings() {
|
|||||||
</FormControl>
|
</FormControl>
|
||||||
) : (
|
) : (
|
||||||
<>
|
<>
|
||||||
<FormControl size="small">
|
|
||||||
<InputLabel>{i18n("hide_fab_button")}</InputLabel>
|
|
||||||
<Select
|
|
||||||
name="hideFab"
|
|
||||||
value={hideFab}
|
|
||||||
label={i18n("hide_fab_button")}
|
|
||||||
onChange={handleChange}
|
|
||||||
>
|
|
||||||
<MenuItem value={false}>{i18n("show")}</MenuItem>
|
|
||||||
<MenuItem value={true}>{i18n("hide")}</MenuItem>
|
|
||||||
</Select>
|
|
||||||
</FormControl>
|
|
||||||
|
|
||||||
<Box>
|
<Box>
|
||||||
<Grid container spacing={2} columns={12}>
|
<Grid container spacing={2} columns={12}>
|
||||||
<Grid item xs={12} sm={12} md={3} lg={3}>
|
<Grid item xs={12} sm={12} md={3} lg={3}>
|
||||||
|
|||||||
@@ -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"
|
||||||
|
|||||||
@@ -37,7 +37,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;
|
||||||
}
|
}
|
||||||
@@ -54,7 +54,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;
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -71,39 +73,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 (油猴脚本
|
Install/Update Userscript for Tampermonkey/Violentmonkey
|
||||||
安装地址 1)
|
|
||||||
</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专用
|
Install/Update Userscript for iOS Safari
|
||||||
安装地址 1)
|
|
||||||
</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>
|
||||||
);
|
);
|
||||||
|
|||||||
@@ -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,28 +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 href = window.location.href;
|
let href = window.location.href;
|
||||||
if (isExt) {
|
if (!tran) {
|
||||||
const tab = await getTabInfo();
|
const tab = await getTabInfo();
|
||||||
href = tab.url;
|
href = tab.url;
|
||||||
}
|
}
|
||||||
saveRule({ ...rule, pattern: href });
|
const newRule = { ...rule, pattern: href };
|
||||||
|
if (isExt && tran) {
|
||||||
|
sendBgMsg(MSG_SAVE_RULE, newRule);
|
||||||
|
} else {
|
||||||
|
saveRule(newRule);
|
||||||
|
}
|
||||||
} catch (err) {
|
} catch (err) {
|
||||||
console.log("[save rule]", err);
|
console.log("[save rule]", err);
|
||||||
}
|
}
|
||||||
};
|
};
|
||||||
|
|
||||||
useEffect(() => {
|
useEffect(() => {
|
||||||
if (!isExt) {
|
if (tran) {
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
(async () => {
|
(async () => {
|
||||||
@@ -105,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 />
|
||||||
@@ -129,7 +134,7 @@ export default function Popup({ setShowPopup, translator: tran }) {
|
|||||||
|
|
||||||
return (
|
return (
|
||||||
<Box minWidth={300}>
|
<Box minWidth={300}>
|
||||||
{isExt && (
|
{!tran && (
|
||||||
<>
|
<>
|
||||||
<Header />
|
<Header />
|
||||||
<Divider />
|
<Divider />
|
||||||
|
|||||||
Reference in New Issue
Block a user