Compare commits
42 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
1bfb465fd6 | ||
|
|
d5d5ec3fef | ||
|
|
0a32f94d32 | ||
|
|
8067f34ce6 | ||
|
|
214c189a7c | ||
|
|
1f67afc8d8 | ||
|
|
7d4af27919 | ||
|
|
2d651abfdd | ||
|
|
6e06fe79cd | ||
|
|
6093577591 | ||
|
|
4b23ee733f | ||
|
|
46428b7c7f | ||
|
|
6805340a9a | ||
|
|
df36ca8d8b | ||
|
|
fe13de7c30 | ||
|
|
b00f636b72 | ||
|
|
8d074e63e1 | ||
|
|
37989b0089 | ||
|
|
477361eb40 | ||
|
|
94288b5dc3 | ||
|
|
84de1e0f12 | ||
|
|
06f93c1c10 | ||
|
|
450283b80a | ||
|
|
44aeed03a6 | ||
|
|
fa4569415d | ||
|
|
a341bf30ba | ||
|
|
34a7354c84 | ||
|
|
21b5dfbe98 | ||
|
|
c1920f5cdd | ||
|
|
3e24568df9 | ||
|
|
b785cfe854 | ||
|
|
15367bd117 | ||
|
|
d7eaac5aca | ||
|
|
d4526d605c | ||
|
|
52979356ca | ||
|
|
c6d3d6454f | ||
|
|
0d7112187d | ||
|
|
045ff3c3d9 | ||
|
|
dd68a73efd | ||
|
|
5947dc182e | ||
|
|
e185bbdb4d | ||
|
|
9368320c38 |
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.8
|
REACT_APP_VERSION=1.7.12
|
||||||
|
|
||||||
REACT_APP_HOMEPAGE=https://github.com/fishjar/kiss-translator
|
REACT_APP_HOMEPAGE=https://github.com/fishjar/kiss-translator
|
||||||
|
|
||||||
|
|||||||
@@ -12,12 +12,13 @@ A simple [bilingual translation extension & Greasemonkey script](https://github.
|
|||||||
- [x] Chrome/Edge/Firefox/Kiwi
|
- [x] Chrome/Edge/Firefox/Kiwi
|
||||||
- [ ] Safari
|
- [ ] Safari
|
||||||
- [x] Supports multiple translation services
|
- [x] Supports multiple translation services
|
||||||
- [x] Google/Microsoft/DeepL/OpenAI/Baidu/Tencent
|
- [x] Google/Microsoft/DeepL/OpenAI/CloudflareAI/Baidu/Tencent
|
||||||
- [x] Custom translation interface
|
- [x] Custom translation interface
|
||||||
- [x] Covers common translation scenarios
|
- [x] Covers common translation scenarios
|
||||||
- [x] Web bilingual translation
|
- [x] Web bilingual translation
|
||||||
- [x] Input box translation
|
- [x] Input box translation
|
||||||
- [x] Seletction translation
|
- [x] Seletction translation
|
||||||
|
- [x] Favorite Words
|
||||||
- [x] Mouseover translation
|
- [x] Mouseover translation
|
||||||
- [x] YouTube subtitle translation
|
- [x] YouTube subtitle translation
|
||||||
- [x] Cross-client data synchronization
|
- [x] Cross-client data synchronization
|
||||||
@@ -47,9 +48,9 @@ A simple [bilingual translation extension & Greasemonkey script](https://github.
|
|||||||
- [x] Firefox [Installation address](https://addons.mozilla.org/zh-CN/firefox/addon/kiss-translator/)
|
- [x] Firefox [Installation address](https://addons.mozilla.org/zh-CN/firefox/addon/kiss-translator/)
|
||||||
- [ ] Safari
|
- [ ] Safari
|
||||||
- [x] GreaseMonkey Script
|
- [x] GreaseMonkey Script
|
||||||
- [x] Chrome/Edge/Firefox ([Tampermonkey](https://www.tampermonkey.net/)/[Violentmonkey](https://violentmonkey.github.io/)) [Installation link 1](https://fishjar.github.io/kiss-translator/kiss-translator.user.js)、 [Installation link 2](https://kiss-translator.rayjar.com/kiss-translator.user.js)
|
- [x] Chrome/Edge/Firefox ([Tampermonkey](https://www.tampermonkey.net/)/[Violentmonkey](https://violentmonkey.github.io/)) [Installation link](https://fishjar.github.io/kiss-translator/kiss-translator.user.js)
|
||||||
- Greasy Fork [Installation address](https://greasyfork.org/zh-CN/scripts/472840-kiss-translator)
|
- Greasy Fork [Installation address](https://greasyfork.org/zh-CN/scripts/472840-kiss-translator)
|
||||||
- [x] iOS Safari ([Userscripts Safari](https://github.com/quoid/userscripts)) [Installation link 1](https://fishjar.github.io/kiss-translator/kiss-translator-ios-safari.user.js)、 [Installation link 2](https://kiss-translator.rayjar.com/kiss-translator.user-ios-safari.js)
|
- [x] iOS Safari ([Userscripts Safari](https://github.com/quoid/userscripts)) [Installation link](https://fishjar.github.io/kiss-translator/kiss-translator-ios-safari.user.js)
|
||||||
|
|
||||||
## Associated Projects
|
## Associated Projects
|
||||||
|
|
||||||
|
|||||||
@@ -12,12 +12,13 @@
|
|||||||
- [x] Chrome/Edge/Firefox/Kiwi
|
- [x] Chrome/Edge/Firefox/Kiwi
|
||||||
- [ ] Safari
|
- [ ] Safari
|
||||||
- [x] 支持多种翻译服务
|
- [x] 支持多种翻译服务
|
||||||
- [x] Google/Microsoft/DeepL/OpenAI/Baidu/Tencent
|
- [x] Google/Microsoft/DeepL/OpenAI/CloudflareAI/Baidu/Tencent
|
||||||
- [x] 自定义翻译接口
|
- [x] 自定义翻译接口
|
||||||
- [x] 覆盖常见翻译场景
|
- [x] 覆盖常见翻译场景
|
||||||
- [x] 网页双语对照翻译
|
- [x] 网页双语对照翻译
|
||||||
- [x] 输入框翻译
|
- [x] 输入框翻译
|
||||||
- [x] 划词翻译
|
- [x] 划词翻译
|
||||||
|
- [x] 收藏词汇
|
||||||
- [x] 鼠标悬停翻译
|
- [x] 鼠标悬停翻译
|
||||||
- [x] YouTube 字幕翻译
|
- [x] YouTube 字幕翻译
|
||||||
- [x] 跨客户端数据同步
|
- [x] 跨客户端数据同步
|
||||||
@@ -47,9 +48,9 @@
|
|||||||
- [x] Firefox [安装地址](https://addons.mozilla.org/zh-CN/firefox/addon/kiss-translator/)
|
- [x] Firefox [安装地址](https://addons.mozilla.org/zh-CN/firefox/addon/kiss-translator/)
|
||||||
- [ ] Safari
|
- [ ] Safari
|
||||||
- [x] 油猴脚本
|
- [x] 油猴脚本
|
||||||
- [x] Chrome/Edge/Firefox ([Tampermonkey](https://www.tampermonkey.net/)/[Violentmonkey](https://violentmonkey.github.io/)) [安装链接 1](https://fishjar.github.io/kiss-translator/kiss-translator.user.js)、 [安装链接 2](https://kiss-translator.rayjar.com/kiss-translator.user.js)
|
- [x] Chrome/Edge/Firefox ([Tampermonkey](https://www.tampermonkey.net/)/[Violentmonkey](https://violentmonkey.github.io/)) [安装链接](https://fishjar.github.io/kiss-translator/kiss-translator.user.js)
|
||||||
- Greasy Fork [安装地址](https://greasyfork.org/zh-CN/scripts/472840-kiss-translator)
|
- Greasy Fork [安装地址](https://greasyfork.org/zh-CN/scripts/472840-kiss-translator)
|
||||||
- [x] iOS Safari ([Userscripts Safari](https://github.com/quoid/userscripts)) [安装链接 1](https://fishjar.github.io/kiss-translator/kiss-translator-ios-safari.user.js)、 [安装链接 2](https://kiss-translator.rayjar.com/kiss-translator.user-ios-safari.js)
|
- [x] iOS Safari ([Userscripts Safari](https://github.com/quoid/userscripts)) [安装链接](https://fishjar.github.io/kiss-translator/kiss-translator-ios-safari.user.js)
|
||||||
|
|
||||||
## 关联项目
|
## 关联项目
|
||||||
|
|
||||||
|
|||||||
@@ -1,7 +1,7 @@
|
|||||||
{
|
{
|
||||||
"name": "kiss-translator",
|
"name": "kiss-translator",
|
||||||
"description": "A minimalist bilingual translation Extension & Greasemonkey Script",
|
"description": "A minimalist bilingual translation Extension & Greasemonkey Script",
|
||||||
"version": "1.7.8",
|
"version": "1.7.12",
|
||||||
"author": "Gabe<yugang2002@gmail.com>",
|
"author": "Gabe<yugang2002@gmail.com>",
|
||||||
"private": true,
|
"private": true,
|
||||||
"dependencies": {
|
"dependencies": {
|
||||||
@@ -30,7 +30,6 @@
|
|||||||
"build:userscript": "rm -rf build/userscript && mkdir build/userscript && cp build/web/*.user.js build/userscript/",
|
"build:userscript": "rm -rf build/userscript && mkdir build/userscript && cp build/web/*.user.js build/userscript/",
|
||||||
"build:rules": "babel-node src/rules.js",
|
"build:rules": "babel-node src/rules.js",
|
||||||
"build": "pnpm build:chrome && pnpm build:edge && pnpm build:firefox && pnpm build:web && pnpm build:userscript-ios && pnpm build:userscript && pnpm build:rules",
|
"build": "pnpm build:chrome && pnpm build:edge && pnpm build:firefox && pnpm build:web && pnpm build:userscript-ios && pnpm build:userscript && pnpm build:rules",
|
||||||
"deploy:web": "wrangler pages deploy ./build/web --project-name kiss-translator",
|
|
||||||
"test": "react-app-rewired test",
|
"test": "react-app-rewired test",
|
||||||
"eject": "react-scripts eject"
|
"eject": "react-scripts eject"
|
||||||
},
|
},
|
||||||
|
|||||||
@@ -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.8",
|
"version": "1.7.12",
|
||||||
"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.8",
|
"version": "1.7.12",
|
||||||
"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",
|
||||||
|
|||||||
@@ -9,6 +9,7 @@ import {
|
|||||||
OPT_TRANS_BAIDU,
|
OPT_TRANS_BAIDU,
|
||||||
OPT_TRANS_TENCENT,
|
OPT_TRANS_TENCENT,
|
||||||
OPT_TRANS_OPENAI,
|
OPT_TRANS_OPENAI,
|
||||||
|
OPT_TRANS_CLOUDFLAREAI,
|
||||||
OPT_TRANS_CUSTOMIZE,
|
OPT_TRANS_CUSTOMIZE,
|
||||||
URL_CACHE_TRAN,
|
URL_CACHE_TRAN,
|
||||||
KV_SALT_SYNC,
|
KV_SALT_SYNC,
|
||||||
@@ -110,11 +111,15 @@ export const apiTranslate = async ({
|
|||||||
let trText = "";
|
let trText = "";
|
||||||
let isSame = false;
|
let isSame = false;
|
||||||
|
|
||||||
|
if (!text) {
|
||||||
|
return [trText, true];
|
||||||
|
}
|
||||||
|
|
||||||
const from =
|
const from =
|
||||||
OPT_LANGS_SPECIAL[translator].get(fromLang) ??
|
OPT_LANGS_SPECIAL[translator].get(fromLang) ??
|
||||||
OPT_LANGS_SPECIAL[translator].get("auto");
|
OPT_LANGS_SPECIAL[translator].get("auto");
|
||||||
const to = OPT_LANGS_SPECIAL[translator].get(toLang);
|
const to = OPT_LANGS_SPECIAL[translator].get(toLang);
|
||||||
if (!text || !to) {
|
if (!to) {
|
||||||
console.log(`[trans] target lang: ${toLang} not support`);
|
console.log(`[trans] target lang: ${toLang} not support`);
|
||||||
return [trText, isSame];
|
return [trText, isSame];
|
||||||
}
|
}
|
||||||
@@ -176,12 +181,15 @@ export const apiTranslate = async ({
|
|||||||
trText = res?.choices?.[0].message.content;
|
trText = res?.choices?.[0].message.content;
|
||||||
isSame = text === trText;
|
isSame = text === trText;
|
||||||
break;
|
break;
|
||||||
|
case OPT_TRANS_CLOUDFLAREAI:
|
||||||
|
trText = res?.result?.translated_text;
|
||||||
|
isSame = text === trText;
|
||||||
|
break;
|
||||||
case OPT_TRANS_CUSTOMIZE:
|
case OPT_TRANS_CUSTOMIZE:
|
||||||
trText = res.text;
|
trText = res.text;
|
||||||
isSame = to === res.from;
|
isSame = to === res.from;
|
||||||
break;
|
break;
|
||||||
default:
|
default:
|
||||||
break;
|
|
||||||
}
|
}
|
||||||
|
|
||||||
return [trText, isSame, res];
|
return [trText, isSame, res];
|
||||||
|
|||||||
@@ -60,7 +60,7 @@ browser.runtime.onMessage.addListener(
|
|||||||
sendResponse({ data });
|
sendResponse({ data });
|
||||||
})
|
})
|
||||||
.catch((error) => {
|
.catch((error) => {
|
||||||
sendResponse({ error: error.message });
|
sendResponse({ error: error.message, cause: error.cause });
|
||||||
});
|
});
|
||||||
break;
|
break;
|
||||||
case MSG_FETCH_LIMIT:
|
case MSG_FETCH_LIMIT:
|
||||||
|
|||||||
@@ -16,6 +16,8 @@ import { Translator } from "./libs/translator";
|
|||||||
import { sendIframeMsg, sendParentMsg } from "./libs/iframe";
|
import { sendIframeMsg, sendParentMsg } from "./libs/iframe";
|
||||||
import { matchRule } from "./libs/rules";
|
import { matchRule } from "./libs/rules";
|
||||||
import Slection from "./views/Selection";
|
import Slection from "./views/Selection";
|
||||||
|
import { touchTapListener } from "./libs/touch";
|
||||||
|
import { debounce } from "./libs/utils";
|
||||||
|
|
||||||
export async function runTranslator(setting) {
|
export async function runTranslator(setting) {
|
||||||
const href = document.location.href;
|
const href = document.location.href;
|
||||||
@@ -120,10 +122,22 @@ export function windowListener(rule) {
|
|||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
export function showErr(err) {
|
export function showErr(message) {
|
||||||
console.error("[KISS-Translator]", err);
|
|
||||||
const $err = document.createElement("div");
|
const $err = document.createElement("div");
|
||||||
$err.innerText = `KISS-Translator: ${err.message}`;
|
$err.innerText = `KISS-Translator: ${message}`;
|
||||||
$err.style.cssText = "background:red; color:#fff;";
|
$err.style.cssText = "background:red; color:#fff;";
|
||||||
document.body.prepend($err);
|
document.body.prepend($err);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
export function touchOperation(translator) {
|
||||||
|
const { touchTranslate = 2 } = translator.setting;
|
||||||
|
if (touchTranslate === 0) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
const handleTap = debounce(() => {
|
||||||
|
translator.toggle();
|
||||||
|
sendIframeMsg(MSG_TRANS_TOGGLE);
|
||||||
|
});
|
||||||
|
touchTapListener(handleTap, touchTranslate);
|
||||||
|
}
|
||||||
|
|||||||
@@ -375,6 +375,14 @@ export const I18N = {
|
|||||||
zh: `选择器`,
|
zh: `选择器`,
|
||||||
en: `Selector`,
|
en: `Selector`,
|
||||||
},
|
},
|
||||||
|
root_selector: {
|
||||||
|
zh: `根选择器`,
|
||||||
|
en: `Root Selector`,
|
||||||
|
},
|
||||||
|
fixer_function: {
|
||||||
|
zh: `修复函数`,
|
||||||
|
en: `Fixer Function`,
|
||||||
|
},
|
||||||
import: {
|
import: {
|
||||||
zh: `导入`,
|
zh: `导入`,
|
||||||
en: `Import`,
|
en: `Import`,
|
||||||
@@ -555,11 +563,11 @@ export const I18N = {
|
|||||||
zh: `全局规则`,
|
zh: `全局规则`,
|
||||||
en: `Global Rule`,
|
en: `Global Rule`,
|
||||||
},
|
},
|
||||||
input_setting: {
|
input_translate: {
|
||||||
zh: `输入框设置`,
|
zh: `输入框翻译`,
|
||||||
en: `Input Box Setting`,
|
en: `Input Box Translation`,
|
||||||
},
|
},
|
||||||
input_box_translation: {
|
use_input_box_translation: {
|
||||||
zh: `启用输入框翻译`,
|
zh: `启用输入框翻译`,
|
||||||
en: `Input Box Translation`,
|
en: `Input Box Translation`,
|
||||||
},
|
},
|
||||||
@@ -624,12 +632,12 @@ export const I18N = {
|
|||||||
en: `Toggle Translate Box Shortcut`,
|
en: `Toggle Translate Box Shortcut`,
|
||||||
},
|
},
|
||||||
tranbtn_offset_x: {
|
tranbtn_offset_x: {
|
||||||
zh: `翻译按钮偏移(X)`,
|
zh: `翻译按钮偏移X(0-100)`,
|
||||||
en: `Translate Button Offset (X)`,
|
en: `Translate Button Offset X (0-100)`,
|
||||||
},
|
},
|
||||||
tranbtn_offset_y: {
|
tranbtn_offset_y: {
|
||||||
zh: `翻译按钮偏移(Y)`,
|
zh: `翻译按钮偏移Y(0-100)`,
|
||||||
en: `Translate Button Offset (Y)`,
|
en: `Translate Button Offset Y (0-100)`,
|
||||||
},
|
},
|
||||||
translated_text: {
|
translated_text: {
|
||||||
zh: `译文`,
|
zh: `译文`,
|
||||||
@@ -639,4 +647,28 @@ export const I18N = {
|
|||||||
zh: `原文`,
|
zh: `原文`,
|
||||||
en: `Original Text`,
|
en: `Original Text`,
|
||||||
},
|
},
|
||||||
|
favorite_words: {
|
||||||
|
zh: `收藏词汇`,
|
||||||
|
en: `Favorite Words`,
|
||||||
|
},
|
||||||
|
touch_setting: {
|
||||||
|
zh: `触屏设置`,
|
||||||
|
en: `Touch Setting`,
|
||||||
|
},
|
||||||
|
touch_translate_shortcut: {
|
||||||
|
zh: `触屏翻译快捷方式`,
|
||||||
|
en: `Touch Translate Shortcut`,
|
||||||
|
},
|
||||||
|
touch_tap_0: {
|
||||||
|
zh: `禁用`,
|
||||||
|
en: `Disable`,
|
||||||
|
},
|
||||||
|
touch_tap_2: {
|
||||||
|
zh: `双指轻触`,
|
||||||
|
en: `Two finger tap`,
|
||||||
|
},
|
||||||
|
touch_tap_3: {
|
||||||
|
zh: `三指轻触`,
|
||||||
|
en: `Three finger tap`,
|
||||||
|
},
|
||||||
};
|
};
|
||||||
|
|||||||
@@ -23,6 +23,8 @@ export const STOKEY_MSAUTH = `${APP_NAME}_msauth`;
|
|||||||
export const STOKEY_BDAUTH = `${APP_NAME}_bdauth`;
|
export const STOKEY_BDAUTH = `${APP_NAME}_bdauth`;
|
||||||
export const STOKEY_SETTING = `${APP_NAME}_setting`;
|
export const STOKEY_SETTING = `${APP_NAME}_setting`;
|
||||||
export const STOKEY_RULES = `${APP_NAME}_rules`;
|
export const STOKEY_RULES = `${APP_NAME}_rules`;
|
||||||
|
export const STOKEY_WFRULES = `${APP_NAME}_webfix_rules`;
|
||||||
|
export const STOKEY_WORDS = `${APP_NAME}_words`;
|
||||||
export const STOKEY_SYNC = `${APP_NAME}_sync`;
|
export const STOKEY_SYNC = `${APP_NAME}_sync`;
|
||||||
export const STOKEY_FAB = `${APP_NAME}_fab`;
|
export const STOKEY_FAB = `${APP_NAME}_fab`;
|
||||||
export const STOKEY_RULESCACHE_PREFIX = `${APP_NAME}_rulescache_`;
|
export const STOKEY_RULESCACHE_PREFIX = `${APP_NAME}_rulescache_`;
|
||||||
@@ -40,6 +42,8 @@ export const CLIENT_USERSCRIPT = "userscript";
|
|||||||
export const CLIENT_EXTS = [CLIENT_CHROME, CLIENT_EDGE, CLIENT_FIREFOX];
|
export const CLIENT_EXTS = [CLIENT_CHROME, CLIENT_EDGE, CLIENT_FIREFOX];
|
||||||
|
|
||||||
export const KV_RULES_KEY = "kiss-rules.json";
|
export const KV_RULES_KEY = "kiss-rules.json";
|
||||||
|
export const KV_WFRULES_KEY = "kiss-webfix.json";
|
||||||
|
export const KV_WORDS_KEY = "kiss-words.json";
|
||||||
export const KV_RULES_SHARE_KEY = "kiss-rules-share.json";
|
export const KV_RULES_SHARE_KEY = "kiss-rules-share.json";
|
||||||
export const KV_SETTING_KEY = "kiss-setting.json";
|
export const KV_SETTING_KEY = "kiss-setting.json";
|
||||||
export const KV_SALT_SYNC = "KISS-Translator-SYNC";
|
export const KV_SALT_SYNC = "KISS-Translator-SYNC";
|
||||||
@@ -87,6 +91,7 @@ export const OPT_TRANS_DEEPLFREE = "DeepLFree";
|
|||||||
export const OPT_TRANS_BAIDU = "Baidu";
|
export const OPT_TRANS_BAIDU = "Baidu";
|
||||||
export const OPT_TRANS_TENCENT = "Tencent";
|
export const OPT_TRANS_TENCENT = "Tencent";
|
||||||
export const OPT_TRANS_OPENAI = "OpenAI";
|
export const OPT_TRANS_OPENAI = "OpenAI";
|
||||||
|
export const OPT_TRANS_CLOUDFLAREAI = "CloudflareAI";
|
||||||
export const OPT_TRANS_CUSTOMIZE = "Custom";
|
export const OPT_TRANS_CUSTOMIZE = "Custom";
|
||||||
export const OPT_TRANS_ALL = [
|
export const OPT_TRANS_ALL = [
|
||||||
OPT_TRANS_GOOGLE,
|
OPT_TRANS_GOOGLE,
|
||||||
@@ -97,6 +102,7 @@ export const OPT_TRANS_ALL = [
|
|||||||
OPT_TRANS_BAIDU,
|
OPT_TRANS_BAIDU,
|
||||||
OPT_TRANS_TENCENT,
|
OPT_TRANS_TENCENT,
|
||||||
OPT_TRANS_OPENAI,
|
OPT_TRANS_OPENAI,
|
||||||
|
OPT_TRANS_CLOUDFLAREAI,
|
||||||
OPT_TRANS_CUSTOMIZE,
|
OPT_TRANS_CUSTOMIZE,
|
||||||
];
|
];
|
||||||
|
|
||||||
@@ -218,6 +224,20 @@ export const OPT_LANGS_SPECIAL = {
|
|||||||
[OPT_TRANS_OPENAI]: new Map(
|
[OPT_TRANS_OPENAI]: new Map(
|
||||||
OPT_LANGS_FROM.map(([key, val]) => [key, val.split(" - ")[0]])
|
OPT_LANGS_FROM.map(([key, val]) => [key, val.split(" - ")[0]])
|
||||||
),
|
),
|
||||||
|
[OPT_TRANS_CLOUDFLAREAI]: new Map([
|
||||||
|
["auto", ""],
|
||||||
|
["zh-CN", "chinese"],
|
||||||
|
["zh-TW", "chinese"],
|
||||||
|
["en", "english"],
|
||||||
|
["ar", "arabic"],
|
||||||
|
["de", "german"],
|
||||||
|
["ru", "russian"],
|
||||||
|
["fr", "french"],
|
||||||
|
["pt", "portuguese"],
|
||||||
|
["ja", "japanese"],
|
||||||
|
["es", "spanish"],
|
||||||
|
["hi", "hindi"],
|
||||||
|
]),
|
||||||
[OPT_TRANS_CUSTOMIZE]: new Map([
|
[OPT_TRANS_CUSTOMIZE]: new Map([
|
||||||
...OPT_LANGS_FROM.map(([key]) => [key, key]),
|
...OPT_LANGS_FROM.map(([key]) => [key, key]),
|
||||||
["auto", ""],
|
["auto", ""],
|
||||||
@@ -360,6 +380,10 @@ export const DEFAULT_TRANS_APIS = {
|
|||||||
model: "gpt-4",
|
model: "gpt-4",
|
||||||
prompt: `You will be provided with a sentence in ${PROMPT_PLACE_FROM}, and your task is to translate it into ${PROMPT_PLACE_TO}.`,
|
prompt: `You will be provided with a sentence in ${PROMPT_PLACE_FROM}, and your task is to translate it into ${PROMPT_PLACE_TO}.`,
|
||||||
},
|
},
|
||||||
|
[OPT_TRANS_CLOUDFLAREAI]: {
|
||||||
|
url: "https://api.cloudflare.com/client/v4/accounts/{ACCOUNT_ID}/ai/run/@cf/meta/m2m100-1.2b",
|
||||||
|
key: "",
|
||||||
|
},
|
||||||
[OPT_TRANS_CUSTOMIZE]: {
|
[OPT_TRANS_CUSTOMIZE]: {
|
||||||
url: "",
|
url: "",
|
||||||
key: "",
|
key: "",
|
||||||
@@ -401,6 +425,7 @@ export const DEFAULT_SETTING = {
|
|||||||
shortcuts: DEFAULT_SHORTCUTS, // 快捷键
|
shortcuts: DEFAULT_SHORTCUTS, // 快捷键
|
||||||
inputRule: DEFAULT_INPUT_RULE, // 输入框设置
|
inputRule: DEFAULT_INPUT_RULE, // 输入框设置
|
||||||
tranboxSetting: DEFAULT_TRANBOX_SETTING, // 划词翻译设置
|
tranboxSetting: DEFAULT_TRANBOX_SETTING, // 划词翻译设置
|
||||||
|
touchTranslate: 2, // 触屏翻译
|
||||||
};
|
};
|
||||||
|
|
||||||
export const DEFAULT_RULES = [GLOBLA_RULE];
|
export const DEFAULT_RULES = [GLOBLA_RULE];
|
||||||
|
|||||||
@@ -15,6 +15,7 @@ import {
|
|||||||
showTransbox,
|
showTransbox,
|
||||||
windowListener,
|
windowListener,
|
||||||
showErr,
|
showErr,
|
||||||
|
touchOperation,
|
||||||
} from "./common";
|
} from "./common";
|
||||||
|
|
||||||
function runtimeListener(translator) {
|
function runtimeListener(translator) {
|
||||||
@@ -70,7 +71,11 @@ function runtimeListener(translator) {
|
|||||||
|
|
||||||
// 浮球按钮
|
// 浮球按钮
|
||||||
await showFab(translator);
|
await showFab(translator);
|
||||||
|
|
||||||
|
// 触屏操作
|
||||||
|
touchOperation(translator);
|
||||||
} catch (err) {
|
} catch (err) {
|
||||||
showErr(err);
|
console.error("[KISS-Translator]", err);
|
||||||
|
showErr(err.message);
|
||||||
}
|
}
|
||||||
})();
|
})();
|
||||||
|
|||||||
67
src/hooks/FavWords.js
Normal file
67
src/hooks/FavWords.js
Normal file
@@ -0,0 +1,67 @@
|
|||||||
|
import { KV_WORDS_KEY } from "../config";
|
||||||
|
import { useCallback, useEffect, useState } from "react";
|
||||||
|
import { trySyncWords } from "../libs/sync";
|
||||||
|
import { getWordsWithDefault, setWords } from "../libs/storage";
|
||||||
|
import { useSyncMeta } from "./Sync";
|
||||||
|
|
||||||
|
export function useFavWords() {
|
||||||
|
const [loading, setLoading] = useState(false);
|
||||||
|
const [favWords, setFavWords] = useState({});
|
||||||
|
const { updateSyncMeta } = useSyncMeta();
|
||||||
|
|
||||||
|
const toggleFav = useCallback(
|
||||||
|
async (word) => {
|
||||||
|
const favs = { ...favWords };
|
||||||
|
if (favs[word]) {
|
||||||
|
delete favs[word];
|
||||||
|
} else {
|
||||||
|
favs[word] = { createdAt: Date.now() };
|
||||||
|
}
|
||||||
|
await setWords(favs);
|
||||||
|
await updateSyncMeta(KV_WORDS_KEY);
|
||||||
|
await trySyncWords();
|
||||||
|
setFavWords(favs);
|
||||||
|
},
|
||||||
|
[updateSyncMeta, favWords]
|
||||||
|
);
|
||||||
|
|
||||||
|
const mergeWords = useCallback(
|
||||||
|
async (newWords) => {
|
||||||
|
const favs = { ...favWords };
|
||||||
|
newWords.forEach((word) => {
|
||||||
|
if (!favs[word]) {
|
||||||
|
favs[word] = { createdAt: Date.now() };
|
||||||
|
}
|
||||||
|
});
|
||||||
|
await setWords(favs);
|
||||||
|
await updateSyncMeta(KV_WORDS_KEY);
|
||||||
|
await trySyncWords();
|
||||||
|
setFavWords(favs);
|
||||||
|
},
|
||||||
|
[updateSyncMeta, favWords]
|
||||||
|
);
|
||||||
|
|
||||||
|
const clearWords = useCallback(async () => {
|
||||||
|
await setWords({});
|
||||||
|
await updateSyncMeta(KV_WORDS_KEY);
|
||||||
|
await trySyncWords();
|
||||||
|
setFavWords({});
|
||||||
|
}, [updateSyncMeta]);
|
||||||
|
|
||||||
|
useEffect(() => {
|
||||||
|
(async () => {
|
||||||
|
try {
|
||||||
|
setLoading(true);
|
||||||
|
await trySyncWords();
|
||||||
|
const favWords = await getWordsWithDefault();
|
||||||
|
setFavWords(favWords);
|
||||||
|
} catch (err) {
|
||||||
|
console.log("[query fav]", err);
|
||||||
|
} finally {
|
||||||
|
setLoading(false);
|
||||||
|
}
|
||||||
|
})();
|
||||||
|
}, []);
|
||||||
|
|
||||||
|
return { loading, favWords, toggleFav, mergeWords, clearWords };
|
||||||
|
}
|
||||||
@@ -1,6 +1,12 @@
|
|||||||
import { useCallback, useEffect, useState } from "react";
|
import { useCallback, useEffect, useState } from "react";
|
||||||
import { storage } from "../libs/storage";
|
import { storage } from "../libs/storage";
|
||||||
|
|
||||||
|
/**
|
||||||
|
*
|
||||||
|
* @param {*} key
|
||||||
|
* @param {*} defaultVal 需为调用hook外的常量
|
||||||
|
* @returns
|
||||||
|
*/
|
||||||
export function useStorage(key, defaultVal) {
|
export function useStorage(key, defaultVal) {
|
||||||
const [loading, setLoading] = useState(false);
|
const [loading, setLoading] = useState(false);
|
||||||
const [data, setData] = useState(null);
|
const [data, setData] = useState(null);
|
||||||
|
|||||||
58
src/hooks/WebfixRules.js
Normal file
58
src/hooks/WebfixRules.js
Normal file
@@ -0,0 +1,58 @@
|
|||||||
|
import { STOKEY_WFRULES, KV_WFRULES_KEY } from "../config";
|
||||||
|
import { useStorage } from "./Storage";
|
||||||
|
import { trySyncWebfixRules } from "../libs/sync";
|
||||||
|
import { useCallback } from "react";
|
||||||
|
import { useSyncMeta } from "./Sync";
|
||||||
|
|
||||||
|
const DEFAULT_WFRULES = [];
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 修复规则 hook
|
||||||
|
* @returns
|
||||||
|
*/
|
||||||
|
export function useWebfixRules() {
|
||||||
|
const { data: list, save } = useStorage(STOKEY_WFRULES, DEFAULT_WFRULES);
|
||||||
|
const { updateSyncMeta } = useSyncMeta();
|
||||||
|
|
||||||
|
const updateRules = useCallback(
|
||||||
|
async (rules) => {
|
||||||
|
await save(rules);
|
||||||
|
await updateSyncMeta(KV_WFRULES_KEY);
|
||||||
|
trySyncWebfixRules();
|
||||||
|
},
|
||||||
|
[save, updateSyncMeta]
|
||||||
|
);
|
||||||
|
|
||||||
|
const add = useCallback(
|
||||||
|
async (rule) => {
|
||||||
|
const rules = [...list];
|
||||||
|
if (rules.map((item) => item.pattern).includes(rule.pattern)) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
rules.unshift(rule);
|
||||||
|
await updateRules(rules);
|
||||||
|
},
|
||||||
|
[list, updateRules]
|
||||||
|
);
|
||||||
|
|
||||||
|
const del = useCallback(
|
||||||
|
async (pattern) => {
|
||||||
|
let rules = [...list];
|
||||||
|
rules = rules.filter((item) => item.pattern !== pattern);
|
||||||
|
await updateRules(rules);
|
||||||
|
},
|
||||||
|
[list, updateRules]
|
||||||
|
);
|
||||||
|
|
||||||
|
const put = useCallback(
|
||||||
|
async (pattern, obj) => {
|
||||||
|
const rules = [...list];
|
||||||
|
const rule = rules.find((r) => r.pattern === pattern);
|
||||||
|
rule && Object.assign(rule, obj);
|
||||||
|
await updateRules(rules);
|
||||||
|
},
|
||||||
|
[list, updateRules]
|
||||||
|
);
|
||||||
|
|
||||||
|
return { list, add, del, put };
|
||||||
|
}
|
||||||
@@ -55,6 +55,10 @@ export const fetchApi = async ({ input, init, transOpts, apiSetting }) => {
|
|||||||
[input, init] = await newTransReq(transOpts, apiSetting);
|
[input, init] = await newTransReq(transOpts, apiSetting);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
if (!input) {
|
||||||
|
throw new Error("url is empty");
|
||||||
|
}
|
||||||
|
|
||||||
if (isGm) {
|
if (isGm) {
|
||||||
let info;
|
let info;
|
||||||
if (window.KISS_GM) {
|
if (window.KISS_GM) {
|
||||||
@@ -127,7 +131,13 @@ export const fetchData = async (
|
|||||||
}
|
}
|
||||||
|
|
||||||
if (!res?.ok) {
|
if (!res?.ok) {
|
||||||
throw new Error(`response: ${res.statusText}`);
|
const cause = {
|
||||||
|
status: res.status,
|
||||||
|
};
|
||||||
|
if (res.headers.get("Content-Type")?.includes("json")) {
|
||||||
|
cause.body = await res.json();
|
||||||
|
}
|
||||||
|
throw new Error(`response: [${res.status}] ${res.statusText}`, { cause });
|
||||||
}
|
}
|
||||||
|
|
||||||
// 插入缓存
|
// 插入缓存
|
||||||
@@ -163,7 +173,7 @@ export const fetchPolyfill = async (input, opts) => {
|
|||||||
if (isExt && !isBg()) {
|
if (isExt && !isBg()) {
|
||||||
const res = await sendBgMsg(MSG_FETCH, { input, opts });
|
const res = await sendBgMsg(MSG_FETCH, { input, opts });
|
||||||
if (res.error) {
|
if (res.error) {
|
||||||
throw new Error(res.error);
|
throw new Error(res.error, { cause: res.cause });
|
||||||
}
|
}
|
||||||
return res.data;
|
return res.data;
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -8,6 +8,7 @@ import {
|
|||||||
OPT_TRANS_BAIDU,
|
OPT_TRANS_BAIDU,
|
||||||
OPT_TRANS_TENCENT,
|
OPT_TRANS_TENCENT,
|
||||||
OPT_TRANS_OPENAI,
|
OPT_TRANS_OPENAI,
|
||||||
|
OPT_TRANS_CLOUDFLAREAI,
|
||||||
OPT_TRANS_CUSTOMIZE,
|
OPT_TRANS_CUSTOMIZE,
|
||||||
URL_MICROSOFT_TRAN,
|
URL_MICROSOFT_TRAN,
|
||||||
URL_TENCENT_TRANSMART,
|
URL_TENCENT_TRANSMART,
|
||||||
@@ -143,7 +144,7 @@ const genTencent = ({ text, from, to }) => {
|
|||||||
return [URL_TENCENT_TRANSMART, init];
|
return [URL_TENCENT_TRANSMART, init];
|
||||||
};
|
};
|
||||||
|
|
||||||
const genOpenai = ({ text, from, to, url, key, prompt, model }) => {
|
const genOpenAI = ({ text, from, to, url, key, prompt, model }) => {
|
||||||
prompt = prompt
|
prompt = prompt
|
||||||
.replaceAll(PROMPT_PLACE_FROM, from)
|
.replaceAll(PROMPT_PLACE_FROM, from)
|
||||||
.replaceAll(PROMPT_PLACE_TO, to);
|
.replaceAll(PROMPT_PLACE_TO, to);
|
||||||
@@ -177,6 +178,25 @@ const genOpenai = ({ text, from, to, url, key, prompt, model }) => {
|
|||||||
return [url, init];
|
return [url, init];
|
||||||
};
|
};
|
||||||
|
|
||||||
|
const genCloudflareAI = ({ text, from, to, url, key }) => {
|
||||||
|
const data = {
|
||||||
|
text,
|
||||||
|
source_lang: from,
|
||||||
|
target_lang: to,
|
||||||
|
};
|
||||||
|
|
||||||
|
const init = {
|
||||||
|
headers: {
|
||||||
|
"Content-type": "application/json",
|
||||||
|
Authorization: `Bearer ${key}`,
|
||||||
|
},
|
||||||
|
method: "POST",
|
||||||
|
body: JSON.stringify(data),
|
||||||
|
};
|
||||||
|
|
||||||
|
return [url, init];
|
||||||
|
};
|
||||||
|
|
||||||
const genCustom = ({ text, from, to, url, key }) => {
|
const genCustom = ({ text, from, to, url, key }) => {
|
||||||
const data = {
|
const data = {
|
||||||
text,
|
text,
|
||||||
@@ -197,6 +217,11 @@ const genCustom = ({ text, from, to, url, key }) => {
|
|||||||
return [url, init];
|
return [url, init];
|
||||||
};
|
};
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 构造翻译接口 request
|
||||||
|
* @param {*}
|
||||||
|
* @returns
|
||||||
|
*/
|
||||||
export const newTransReq = ({ translator, text, from, to }, apiSetting) => {
|
export const newTransReq = ({ translator, text, from, to }, apiSetting) => {
|
||||||
const args = { text, from, to, ...apiSetting };
|
const args = { text, from, to, ...apiSetting };
|
||||||
switch (translator) {
|
switch (translator) {
|
||||||
@@ -215,7 +240,9 @@ export const newTransReq = ({ translator, text, from, to }, apiSetting) => {
|
|||||||
case OPT_TRANS_TENCENT:
|
case OPT_TRANS_TENCENT:
|
||||||
return genTencent(args);
|
return genTencent(args);
|
||||||
case OPT_TRANS_OPENAI:
|
case OPT_TRANS_OPENAI:
|
||||||
return genOpenai(args);
|
return genOpenAI(args);
|
||||||
|
case OPT_TRANS_CLOUDFLAREAI:
|
||||||
|
return genCloudflareAI(args);
|
||||||
case OPT_TRANS_CUSTOMIZE:
|
case OPT_TRANS_CUSTOMIZE:
|
||||||
return genCustom(args);
|
return genCustom(args);
|
||||||
default:
|
default:
|
||||||
|
|||||||
@@ -1,6 +1,8 @@
|
|||||||
import {
|
import {
|
||||||
STOKEY_SETTING,
|
STOKEY_SETTING,
|
||||||
STOKEY_RULES,
|
STOKEY_RULES,
|
||||||
|
STOKEY_WFRULES,
|
||||||
|
STOKEY_WORDS,
|
||||||
STOKEY_FAB,
|
STOKEY_FAB,
|
||||||
STOKEY_SYNC,
|
STOKEY_SYNC,
|
||||||
STOKEY_MSAUTH,
|
STOKEY_MSAUTH,
|
||||||
@@ -97,6 +99,21 @@ export const getRulesWithDefault = async () =>
|
|||||||
(await getRules()) || DEFAULT_RULES;
|
(await getRules()) || DEFAULT_RULES;
|
||||||
export const setRules = (val) => setObj(STOKEY_RULES, val);
|
export const setRules = (val) => setObj(STOKEY_RULES, val);
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 修复规则列表
|
||||||
|
*/
|
||||||
|
export const getWebfixRules = () => getObj(STOKEY_WFRULES);
|
||||||
|
export const getWebfixRulesWithDefault = async () =>
|
||||||
|
(await getWebfixRules()) || [];
|
||||||
|
export const setWebfixRules = (val) => setObj(STOKEY_WFRULES, val);
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 词汇列表
|
||||||
|
*/
|
||||||
|
export const getWords = () => getObj(STOKEY_WORDS);
|
||||||
|
export const getWordsWithDefault = async () => (await getWords()) || {};
|
||||||
|
export const setWords = (val) => setObj(STOKEY_WORDS, val);
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* 订阅规则
|
* 订阅规则
|
||||||
*/
|
*/
|
||||||
|
|||||||
@@ -2,6 +2,8 @@ import {
|
|||||||
APP_LCNAME,
|
APP_LCNAME,
|
||||||
KV_SETTING_KEY,
|
KV_SETTING_KEY,
|
||||||
KV_RULES_KEY,
|
KV_RULES_KEY,
|
||||||
|
KV_WFRULES_KEY,
|
||||||
|
KV_WORDS_KEY,
|
||||||
KV_RULES_SHARE_KEY,
|
KV_RULES_SHARE_KEY,
|
||||||
KV_SALT_SHARE,
|
KV_SALT_SHARE,
|
||||||
OPT_SYNCTYPE_WEBDAV,
|
OPT_SYNCTYPE_WEBDAV,
|
||||||
@@ -11,8 +13,12 @@ import {
|
|||||||
updateSync,
|
updateSync,
|
||||||
getSettingWithDefault,
|
getSettingWithDefault,
|
||||||
getRulesWithDefault,
|
getRulesWithDefault,
|
||||||
|
getWordsWithDefault,
|
||||||
|
getWebfixRulesWithDefault,
|
||||||
setSetting,
|
setSetting,
|
||||||
setRules,
|
setRules,
|
||||||
|
setWebfixRules,
|
||||||
|
setWords,
|
||||||
} from "./storage";
|
} from "./storage";
|
||||||
import { apiSyncData } from "../apis";
|
import { apiSyncData } from "../apis";
|
||||||
import { sha256, removeEndchar } from "./utils";
|
import { sha256, removeEndchar } from "./utils";
|
||||||
@@ -135,6 +141,44 @@ export const trySyncRules = async () => {
|
|||||||
}
|
}
|
||||||
};
|
};
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 同步修复规则
|
||||||
|
* @returns
|
||||||
|
*/
|
||||||
|
const syncWebfixRules = async () => {
|
||||||
|
const res = await syncData(KV_WFRULES_KEY, getWebfixRulesWithDefault);
|
||||||
|
if (res?.isNew) {
|
||||||
|
await setWebfixRules(res.value);
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
export const trySyncWebfixRules = async () => {
|
||||||
|
try {
|
||||||
|
await syncWebfixRules();
|
||||||
|
} catch (err) {
|
||||||
|
console.log("[sync user webfix rules]", err);
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 同步词汇
|
||||||
|
* @returns
|
||||||
|
*/
|
||||||
|
const syncWords = async () => {
|
||||||
|
const res = await syncData(KV_WORDS_KEY, getWordsWithDefault);
|
||||||
|
if (res?.isNew) {
|
||||||
|
await setWords(res.value);
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
export const trySyncWords = async () => {
|
||||||
|
try {
|
||||||
|
await syncWords();
|
||||||
|
} catch (err) {
|
||||||
|
console.log("[sync fav words]", err);
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* 同步分享规则
|
* 同步分享规则
|
||||||
* @param {*} param0
|
* @param {*} param0
|
||||||
@@ -163,9 +207,13 @@ export const syncShareRules = async ({ rules, syncUrl, syncKey }) => {
|
|||||||
export const syncSettingAndRules = async () => {
|
export const syncSettingAndRules = async () => {
|
||||||
await syncSetting();
|
await syncSetting();
|
||||||
await syncRules();
|
await syncRules();
|
||||||
|
await syncWebfixRules();
|
||||||
|
await syncWords();
|
||||||
};
|
};
|
||||||
|
|
||||||
export const trySyncSettingAndRules = async () => {
|
export const trySyncSettingAndRules = async () => {
|
||||||
await trySyncSetting();
|
await trySyncSetting();
|
||||||
await trySyncRules();
|
await trySyncRules();
|
||||||
|
await trySyncWebfixRules();
|
||||||
|
await trySyncWords();
|
||||||
};
|
};
|
||||||
|
|||||||
12
src/libs/touch.js
Normal file
12
src/libs/touch.js
Normal file
@@ -0,0 +1,12 @@
|
|||||||
|
export function touchTapListener(fn, touchsLength) {
|
||||||
|
const handleTouchend = (e) => {
|
||||||
|
if (e.touches.length === touchsLength) {
|
||||||
|
fn();
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
document.addEventListener("touchstart", handleTouchend);
|
||||||
|
return () => {
|
||||||
|
document.removeEventListener("touchstart", handleTouchend);
|
||||||
|
};
|
||||||
|
}
|
||||||
@@ -349,8 +349,8 @@ export class Translator {
|
|||||||
// 监听鼠标悬停
|
// 监听鼠标悬停
|
||||||
window.addEventListener("keydown", this._handleKeydown);
|
window.addEventListener("keydown", this._handleKeydown);
|
||||||
this._tranNodes.forEach((_, node) => {
|
this._tranNodes.forEach((_, node) => {
|
||||||
node.addEventListener("mouseover", this._handleMouseover);
|
node.addEventListener("mouseenter", this._handleMouseover);
|
||||||
node.addEventListener("mouseout", this._handleMouseout);
|
node.addEventListener("mouseleave", this._handleMouseout);
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
};
|
};
|
||||||
@@ -475,15 +475,15 @@ export class Translator {
|
|||||||
};
|
};
|
||||||
|
|
||||||
_handleMouseover = (e) => {
|
_handleMouseover = (e) => {
|
||||||
// console.log("mouseover", e);
|
// console.log("mouseenter", e);
|
||||||
if (!this._tranNodes.has(e.target)) {
|
if (!this._tranNodes.has(e.target)) {
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
const key = this._setting.mouseKey.slice(3);
|
const key = this._setting.mouseKey.slice(3);
|
||||||
if (this._setting.mouseKey === OPT_MOUSEKEY_MOUSEOVER || e[key]) {
|
if (this._setting.mouseKey === OPT_MOUSEKEY_MOUSEOVER || e[key]) {
|
||||||
e.target.removeEventListener("mouseover", this._handleMouseover);
|
e.target.removeEventListener("mouseenter", this._handleMouseover);
|
||||||
e.target.removeEventListener("mouseout", this._handleMouseout);
|
e.target.removeEventListener("mouseleave", this._handleMouseout);
|
||||||
this._render(e.target);
|
this._render(e.target);
|
||||||
} else {
|
} else {
|
||||||
this._mouseoverNode = e.target;
|
this._mouseoverNode = e.target;
|
||||||
@@ -491,7 +491,7 @@ export class Translator {
|
|||||||
};
|
};
|
||||||
|
|
||||||
_handleMouseout = (e) => {
|
_handleMouseout = (e) => {
|
||||||
// console.log("mouseout", e);
|
// console.log("mouseleave", e);
|
||||||
if (!this._tranNodes.has(e.target)) {
|
if (!this._tranNodes.has(e.target)) {
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
@@ -504,10 +504,13 @@ export class Translator {
|
|||||||
const key = this._setting.mouseKey.slice(3);
|
const key = this._setting.mouseKey.slice(3);
|
||||||
if (e[key] && this._mouseoverNode) {
|
if (e[key] && this._mouseoverNode) {
|
||||||
this._mouseoverNode.removeEventListener(
|
this._mouseoverNode.removeEventListener(
|
||||||
"mouseover",
|
"mouseenter",
|
||||||
this._handleMouseover
|
this._handleMouseover
|
||||||
);
|
);
|
||||||
this._mouseoverNode.removeEventListener("mouseout", this._handleMouseout);
|
this._mouseoverNode.removeEventListener(
|
||||||
|
"mouseleave",
|
||||||
|
this._handleMouseout
|
||||||
|
);
|
||||||
|
|
||||||
const node = this._mouseoverNode;
|
const node = this._mouseoverNode;
|
||||||
this._render(node);
|
this._render(node);
|
||||||
@@ -536,8 +539,9 @@ export class Translator {
|
|||||||
// 移除鼠标悬停监听
|
// 移除鼠标悬停监听
|
||||||
window.removeEventListener("keydown", this._handleKeydown);
|
window.removeEventListener("keydown", this._handleKeydown);
|
||||||
this._tranNodes.forEach((_, node) => {
|
this._tranNodes.forEach((_, node) => {
|
||||||
node.removeEventListener("mouseover", this._handleMouseover);
|
// node.style.pointerEvents = "none";
|
||||||
node.removeEventListener("mouseout", this._handleMouseout);
|
node.removeEventListener("mouseenter", this._handleMouseover);
|
||||||
|
node.removeEventListener("mouseleave", this._handleMouseout);
|
||||||
// 移除已插入元素
|
// 移除已插入元素
|
||||||
node.querySelector(APP_LCNAME)?.remove();
|
node.querySelector(APP_LCNAME)?.remove();
|
||||||
});
|
});
|
||||||
|
|||||||
@@ -1,5 +1,5 @@
|
|||||||
import { isMatch } from "./utils";
|
import { isMatch } from "./utils";
|
||||||
import { getWebfix, setWebfix } from "./storage";
|
import { getWebfix, setWebfix, getWebfixRulesWithDefault } from "./storage";
|
||||||
import { apiFetch } from "../apis";
|
import { apiFetch } from "../apis";
|
||||||
|
|
||||||
/**
|
/**
|
||||||
@@ -7,7 +7,16 @@ import { apiFetch } from "../apis";
|
|||||||
*/
|
*/
|
||||||
const FIXER_BR = "br";
|
const FIXER_BR = "br";
|
||||||
const FIXER_BN = "bn";
|
const FIXER_BN = "bn";
|
||||||
|
const FIXER_BR_DIV = "brToDiv";
|
||||||
|
const FIXER_BN_DIV = "bnToDiv";
|
||||||
const FIXER_FONTSIZE = "fontSize";
|
const FIXER_FONTSIZE = "fontSize";
|
||||||
|
export const FIXER_ALL = [
|
||||||
|
FIXER_BR,
|
||||||
|
FIXER_BN,
|
||||||
|
FIXER_BR_DIV,
|
||||||
|
FIXER_BN_DIV,
|
||||||
|
FIXER_FONTSIZE,
|
||||||
|
];
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* 需要修复的站点列表
|
* 需要修复的站点列表
|
||||||
@@ -54,7 +63,7 @@ const fixedSign = "kissfixed";
|
|||||||
* @param {*} node
|
* @param {*} node
|
||||||
* @returns
|
* @returns
|
||||||
*/
|
*/
|
||||||
function brFixer(node) {
|
function brFixer(node, tag = "p") {
|
||||||
if (node.hasAttribute(fixedSign)) {
|
if (node.hasAttribute(fixedSign)) {
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
@@ -81,13 +90,13 @@ function brFixer(node) {
|
|||||||
var html = "";
|
var html = "";
|
||||||
node.childNodes.forEach(function (child, index) {
|
node.childNodes.forEach(function (child, index) {
|
||||||
if (index === 0) {
|
if (index === 0) {
|
||||||
html += "<p>";
|
html += `<${tag} class="kiss-p">`;
|
||||||
}
|
}
|
||||||
|
|
||||||
if (gapTags.indexOf(child.nodeName) !== -1) {
|
if (gapTags.indexOf(child.nodeName) !== -1) {
|
||||||
html += "</p><p>";
|
html += `</${tag}><${tag} class="kiss-p">`;
|
||||||
} else if (newlineTags.indexOf(child.nodeName) !== -1) {
|
} else if (newlineTags.indexOf(child.nodeName) !== -1) {
|
||||||
html += "</p>" + child.outerHTML + "<p>";
|
html += `</${tag}>${child.outerHTML}<${tag} class="kiss-p">`;
|
||||||
} else if (child.outerHTML) {
|
} else if (child.outerHTML) {
|
||||||
html += child.outerHTML;
|
html += child.outerHTML;
|
||||||
} else if (child.nodeValue) {
|
} else if (child.nodeValue) {
|
||||||
@@ -95,30 +104,34 @@ function brFixer(node) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
if (index === node.childNodes.length - 1) {
|
if (index === node.childNodes.length - 1) {
|
||||||
html += "</p>";
|
html += `</${tag}>`;
|
||||||
}
|
}
|
||||||
});
|
});
|
||||||
node.innerHTML = html;
|
node.innerHTML = html;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
function brDivFixer(node) {
|
||||||
|
return brFixer(node, "div");
|
||||||
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* 目标是将 `\n` 替换成 `p`
|
* 目标是将 `\n` 替换成 `p`
|
||||||
* @param {*} node
|
* @param {*} node
|
||||||
* @returns
|
* @returns
|
||||||
*/
|
*/
|
||||||
function bnFixer(node) {
|
function bnFixer(node, tag = "p") {
|
||||||
if (node.hasAttribute(fixedSign)) {
|
if (node.hasAttribute(fixedSign)) {
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
node.setAttribute(fixedSign, "true");
|
node.setAttribute(fixedSign, "true");
|
||||||
|
node.innerHTML = node.innerHTML
|
||||||
|
.split("\n")
|
||||||
|
.map((item) => `<${tag} class="kiss-p">${item || " "}</${tag}>`)
|
||||||
|
.join("");
|
||||||
|
}
|
||||||
|
|
||||||
const childs = node.childNodes;
|
function bnDivFixer(node) {
|
||||||
if (childs.length === 1 && childs[0].nodeName === "#text") {
|
return bnFixer(node, "div");
|
||||||
node.innerHTML = node.innerHTML
|
|
||||||
.split("\n")
|
|
||||||
.map((item) => `<p>${item || " "}</p>`)
|
|
||||||
.join("");
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
@@ -135,6 +148,8 @@ function fontSizeFixer(node) {
|
|||||||
const fixerMap = {
|
const fixerMap = {
|
||||||
[FIXER_BR]: brFixer,
|
[FIXER_BR]: brFixer,
|
||||||
[FIXER_BN]: bnFixer,
|
[FIXER_BN]: bnFixer,
|
||||||
|
[FIXER_BR_DIV]: brDivFixer,
|
||||||
|
[FIXER_BN_DIV]: bnDivFixer,
|
||||||
[FIXER_FONTSIZE]: fontSizeFixer,
|
[FIXER_FONTSIZE]: fontSizeFixer,
|
||||||
};
|
};
|
||||||
|
|
||||||
@@ -148,7 +163,11 @@ function run(selector, fixer, rootSelector) {
|
|||||||
var mutaObserver = new MutationObserver(function (mutations) {
|
var mutaObserver = new MutationObserver(function (mutations) {
|
||||||
mutations.forEach(function (mutation) {
|
mutations.forEach(function (mutation) {
|
||||||
mutation.addedNodes.forEach(function (addNode) {
|
mutation.addedNodes.forEach(function (addNode) {
|
||||||
addNode.querySelectorAll(selector).forEach(fixer);
|
if (addNode && addNode.querySelectorAll) {
|
||||||
|
addNode.querySelectorAll(selector).forEach(function (node) {
|
||||||
|
fixer(node);
|
||||||
|
});
|
||||||
|
}
|
||||||
});
|
});
|
||||||
});
|
});
|
||||||
});
|
});
|
||||||
@@ -159,7 +178,9 @@ function run(selector, fixer, rootSelector) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
rootNodes.forEach(function (rootNode) {
|
rootNodes.forEach(function (rootNode) {
|
||||||
rootNode.querySelectorAll(selector).forEach(fixer);
|
rootNode.querySelectorAll(selector).forEach(function (node) {
|
||||||
|
fixer(node);
|
||||||
|
});
|
||||||
mutaObserver.observe(rootNode, {
|
mutaObserver.observe(rootNode, {
|
||||||
childList: true,
|
childList: true,
|
||||||
subtree: true,
|
subtree: true,
|
||||||
@@ -206,7 +227,9 @@ export async function runWebfix({ injectWebfix }) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
const href = document.location.href;
|
const href = document.location.href;
|
||||||
const sites = await loadOrFetchWebfix(process.env.REACT_APP_WEBFIXURL);
|
const userSites = await getWebfixRulesWithDefault();
|
||||||
|
const subSites = await loadOrFetchWebfix(process.env.REACT_APP_WEBFIXURL);
|
||||||
|
const sites = [...userSites, ...subSites];
|
||||||
for (var i = 0; i < sites.length; i++) {
|
for (var i = 0; i < sites.length; i++) {
|
||||||
var site = sites[i];
|
var site = sites[i];
|
||||||
if (isMatch(href, site.pattern)) {
|
if (isMatch(href, site.pattern)) {
|
||||||
|
|||||||
@@ -11,6 +11,7 @@ import {
|
|||||||
showTransbox,
|
showTransbox,
|
||||||
windowListener,
|
windowListener,
|
||||||
showErr,
|
showErr,
|
||||||
|
touchOperation,
|
||||||
} from "./common";
|
} from "./common";
|
||||||
|
|
||||||
function runSettingPage() {
|
function runSettingPage() {
|
||||||
@@ -69,9 +70,13 @@ function runSettingPage() {
|
|||||||
// 浮球按钮
|
// 浮球按钮
|
||||||
await showFab(translator);
|
await showFab(translator);
|
||||||
|
|
||||||
|
// 触屏操作
|
||||||
|
touchOperation(translator);
|
||||||
|
|
||||||
// 同步订阅规则
|
// 同步订阅规则
|
||||||
await trySyncAllSubRules(setting);
|
await trySyncAllSubRules(setting);
|
||||||
} catch (err) {
|
} catch (err) {
|
||||||
showErr(err);
|
console.error("[KISS-Translator]", err);
|
||||||
|
showErr(err.message);
|
||||||
}
|
}
|
||||||
})();
|
})();
|
||||||
|
|||||||
@@ -46,7 +46,20 @@ function TestButton({ translator, api }) {
|
|||||||
}
|
}
|
||||||
alert.success(i18n("test_success"));
|
alert.success(i18n("test_success"));
|
||||||
} catch (err) {
|
} catch (err) {
|
||||||
alert.error(`${i18n("test_failed")}: ${err.message}`);
|
// alert.error(`${i18n("test_failed")}: ${err.message}`);
|
||||||
|
alert.error(
|
||||||
|
<>
|
||||||
|
<div>{`${i18n("test_failed")}: ${err.message}`}</div>
|
||||||
|
<pre
|
||||||
|
style={{
|
||||||
|
maxWidth: 400,
|
||||||
|
overflow: "auto",
|
||||||
|
}}
|
||||||
|
>
|
||||||
|
{JSON.stringify(err.cause || {}, null, 2)}
|
||||||
|
</pre>
|
||||||
|
</>
|
||||||
|
);
|
||||||
} finally {
|
} finally {
|
||||||
setLoading(false);
|
setLoading(false);
|
||||||
}
|
}
|
||||||
|
|||||||
27
src/views/Options/DownloadButton.js
Normal file
27
src/views/Options/DownloadButton.js
Normal file
@@ -0,0 +1,27 @@
|
|||||||
|
import FileDownloadIcon from "@mui/icons-material/FileDownload";
|
||||||
|
import Button from "@mui/material/Button";
|
||||||
|
|
||||||
|
export default function DownloadButton({ data, text, fileName }) {
|
||||||
|
const handleClick = (e) => {
|
||||||
|
e.preventDefault();
|
||||||
|
if (data) {
|
||||||
|
const url = window.URL.createObjectURL(new Blob([data]));
|
||||||
|
const link = document.createElement("a");
|
||||||
|
link.href = url;
|
||||||
|
link.setAttribute("download", fileName || `${Date.now()}.json`);
|
||||||
|
document.body.appendChild(link);
|
||||||
|
link.click();
|
||||||
|
link.remove();
|
||||||
|
}
|
||||||
|
};
|
||||||
|
return (
|
||||||
|
<Button
|
||||||
|
size="small"
|
||||||
|
variant="outlined"
|
||||||
|
onClick={handleClick}
|
||||||
|
startIcon={<FileDownloadIcon />}
|
||||||
|
>
|
||||||
|
{text}
|
||||||
|
</Button>
|
||||||
|
);
|
||||||
|
}
|
||||||
150
src/views/Options/FavWords.js
Normal file
150
src/views/Options/FavWords.js
Normal file
@@ -0,0 +1,150 @@
|
|||||||
|
import Stack from "@mui/material/Stack";
|
||||||
|
import { OPT_TRANS_BAIDU } from "../../config";
|
||||||
|
import { useEffect, useState } from "react";
|
||||||
|
import Typography from "@mui/material/Typography";
|
||||||
|
import Accordion from "@mui/material/Accordion";
|
||||||
|
import AccordionSummary from "@mui/material/AccordionSummary";
|
||||||
|
import AccordionDetails from "@mui/material/AccordionDetails";
|
||||||
|
import ExpandMoreIcon from "@mui/icons-material/ExpandMore";
|
||||||
|
import CircularProgress from "@mui/material/CircularProgress";
|
||||||
|
import { useI18n } from "../../hooks/I18n";
|
||||||
|
import Alert from "@mui/material/Alert";
|
||||||
|
import { apiTranslate } from "../../apis";
|
||||||
|
import Box from "@mui/material/Box";
|
||||||
|
import { useFavWords } from "../../hooks/FavWords";
|
||||||
|
import DictCont from "../Selection/DictCont";
|
||||||
|
import DownloadButton from "./DownloadButton";
|
||||||
|
import UploadButton from "./UploadButton";
|
||||||
|
import Button from "@mui/material/Button";
|
||||||
|
import ClearAllIcon from "@mui/icons-material/ClearAll";
|
||||||
|
import { isValidWord } from "../../libs/utils";
|
||||||
|
|
||||||
|
function DictField({ word }) {
|
||||||
|
const [dictResult, setDictResult] = useState(null);
|
||||||
|
const [loading, setLoading] = useState(false);
|
||||||
|
const [error, setError] = useState("");
|
||||||
|
|
||||||
|
useEffect(() => {
|
||||||
|
(async () => {
|
||||||
|
try {
|
||||||
|
setLoading(true);
|
||||||
|
setError("");
|
||||||
|
const dictRes = await apiTranslate({
|
||||||
|
text: word,
|
||||||
|
translator: OPT_TRANS_BAIDU,
|
||||||
|
fromLang: "en",
|
||||||
|
toLang: "zh-CN",
|
||||||
|
});
|
||||||
|
setDictResult(dictRes[2].dict_result);
|
||||||
|
} catch (err) {
|
||||||
|
setError(err.message);
|
||||||
|
} finally {
|
||||||
|
setLoading(false);
|
||||||
|
}
|
||||||
|
})();
|
||||||
|
}, [word]);
|
||||||
|
|
||||||
|
if (loading) {
|
||||||
|
return <CircularProgress size={24} />;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (error) {
|
||||||
|
return <Alert severity="error">{error}</Alert>;
|
||||||
|
}
|
||||||
|
|
||||||
|
return <DictCont dictResult={dictResult} />;
|
||||||
|
}
|
||||||
|
|
||||||
|
function FavAccordion({ word, index }) {
|
||||||
|
const [expanded, setExpanded] = useState(false);
|
||||||
|
|
||||||
|
const handleChange = (e) => {
|
||||||
|
setExpanded((pre) => !pre);
|
||||||
|
};
|
||||||
|
|
||||||
|
return (
|
||||||
|
<Accordion expanded={expanded} onChange={handleChange}>
|
||||||
|
<AccordionSummary expandIcon={<ExpandMoreIcon />}>
|
||||||
|
{/* <Typography>{`[${new Date(
|
||||||
|
createdAt
|
||||||
|
).toLocaleString()}] ${word}`}</Typography> */}
|
||||||
|
<Typography>{`${index + 1}. ${word}`}</Typography>
|
||||||
|
</AccordionSummary>
|
||||||
|
<AccordionDetails>
|
||||||
|
{expanded && <DictField word={word} />}
|
||||||
|
</AccordionDetails>
|
||||||
|
</Accordion>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
export default function FavWords() {
|
||||||
|
const i18n = useI18n();
|
||||||
|
const { loading, favWords, mergeWords, clearWords } = useFavWords();
|
||||||
|
const favList = Object.entries(favWords).sort((a, b) =>
|
||||||
|
a[0].localeCompare(b[0])
|
||||||
|
);
|
||||||
|
const downloadList = favList.map(([word]) => word);
|
||||||
|
|
||||||
|
const handleImport = async (data) => {
|
||||||
|
try {
|
||||||
|
const newWords = data
|
||||||
|
.split("\n")
|
||||||
|
.map((line) => line.split(",")[0].trim())
|
||||||
|
.filter(isValidWord);
|
||||||
|
await mergeWords(newWords);
|
||||||
|
} catch (err) {
|
||||||
|
console.log("[import rules]", err);
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
return (
|
||||||
|
<Box>
|
||||||
|
<Stack spacing={3}>
|
||||||
|
<Stack
|
||||||
|
direction="row"
|
||||||
|
alignItems="center"
|
||||||
|
spacing={2}
|
||||||
|
useFlexGap
|
||||||
|
flexWrap="wrap"
|
||||||
|
>
|
||||||
|
<UploadButton
|
||||||
|
text={i18n("import")}
|
||||||
|
handleImport={handleImport}
|
||||||
|
fileType="text"
|
||||||
|
fileExts={[".txt", ".csv"]}
|
||||||
|
/>
|
||||||
|
<DownloadButton
|
||||||
|
data={downloadList.join("\n")}
|
||||||
|
text={i18n("export")}
|
||||||
|
fileName={`kiss-words_${Date.now()}.txt`}
|
||||||
|
/>
|
||||||
|
<Button
|
||||||
|
size="small"
|
||||||
|
variant="outlined"
|
||||||
|
onClick={() => {
|
||||||
|
clearWords();
|
||||||
|
}}
|
||||||
|
startIcon={<ClearAllIcon />}
|
||||||
|
>
|
||||||
|
{i18n("clear_all")}
|
||||||
|
</Button>
|
||||||
|
</Stack>
|
||||||
|
|
||||||
|
<Box>
|
||||||
|
{loading ? (
|
||||||
|
<CircularProgress size={24} />
|
||||||
|
) : (
|
||||||
|
favList.map(([word, { createdAt }], index) => (
|
||||||
|
<FavAccordion
|
||||||
|
key={word}
|
||||||
|
index={index}
|
||||||
|
word={word}
|
||||||
|
createdAt={createdAt}
|
||||||
|
/>
|
||||||
|
))
|
||||||
|
)}
|
||||||
|
</Box>
|
||||||
|
</Stack>
|
||||||
|
</Box>
|
||||||
|
);
|
||||||
|
}
|
||||||
@@ -67,7 +67,7 @@ export default function InputSetting() {
|
|||||||
}}
|
}}
|
||||||
/>
|
/>
|
||||||
}
|
}
|
||||||
label={i18n("input_box_translation")}
|
label={i18n("use_input_box_translation")}
|
||||||
/>
|
/>
|
||||||
|
|
||||||
<TextField
|
<TextField
|
||||||
|
|||||||
@@ -13,7 +13,8 @@ import SyncIcon from "@mui/icons-material/Sync";
|
|||||||
import ApiIcon from "@mui/icons-material/Api";
|
import ApiIcon from "@mui/icons-material/Api";
|
||||||
import SendTimeExtensionIcon from "@mui/icons-material/SendTimeExtension";
|
import SendTimeExtensionIcon from "@mui/icons-material/SendTimeExtension";
|
||||||
import InputIcon from "@mui/icons-material/Input";
|
import InputIcon from "@mui/icons-material/Input";
|
||||||
import TranslateIcon from '@mui/icons-material/Translate';
|
import SelectAllIcon from "@mui/icons-material/SelectAll";
|
||||||
|
import EventNoteIcon from "@mui/icons-material/EventNote";
|
||||||
|
|
||||||
function LinkItem({ label, url, icon }) {
|
function LinkItem({ label, url, icon }) {
|
||||||
const match = useMatch(url);
|
const match = useMatch(url);
|
||||||
@@ -41,8 +42,8 @@ export default function Navigator(props) {
|
|||||||
icon: <DesignServicesIcon />,
|
icon: <DesignServicesIcon />,
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
id: "input_setting",
|
id: "input_translate",
|
||||||
label: i18n("input_setting"),
|
label: i18n("input_translate"),
|
||||||
url: "/input",
|
url: "/input",
|
||||||
icon: <InputIcon />,
|
icon: <InputIcon />,
|
||||||
},
|
},
|
||||||
@@ -50,7 +51,7 @@ export default function Navigator(props) {
|
|||||||
id: "selection_translate",
|
id: "selection_translate",
|
||||||
label: i18n("selection_translate"),
|
label: i18n("selection_translate"),
|
||||||
url: "/tranbox",
|
url: "/tranbox",
|
||||||
icon: <TranslateIcon />,
|
icon: <SelectAllIcon />,
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
id: "apis_setting",
|
id: "apis_setting",
|
||||||
@@ -70,6 +71,12 @@ export default function Navigator(props) {
|
|||||||
url: "/webfix",
|
url: "/webfix",
|
||||||
icon: <SendTimeExtensionIcon />,
|
icon: <SendTimeExtensionIcon />,
|
||||||
},
|
},
|
||||||
|
{
|
||||||
|
id: "words",
|
||||||
|
label: i18n("favorite_words"),
|
||||||
|
url: "/words",
|
||||||
|
icon: <EventNoteIcon />,
|
||||||
|
},
|
||||||
{ id: "about", label: i18n("about"), url: "/about", icon: <InfoIcon /> },
|
{ id: "about", label: i18n("about"), url: "/about", icon: <InfoIcon /> },
|
||||||
];
|
];
|
||||||
return (
|
return (
|
||||||
|
|||||||
@@ -16,7 +16,7 @@ import {
|
|||||||
URL_KISS_RULES_NEW_ISSUE,
|
URL_KISS_RULES_NEW_ISSUE,
|
||||||
OPT_SYNCTYPE_WORKER,
|
OPT_SYNCTYPE_WORKER,
|
||||||
} from "../../config";
|
} from "../../config";
|
||||||
import { useState, useRef, useEffect, useMemo } from "react";
|
import { useState, useEffect, useMemo } from "react";
|
||||||
import { useI18n } from "../../hooks/I18n";
|
import { useI18n } from "../../hooks/I18n";
|
||||||
import Typography from "@mui/material/Typography";
|
import Typography from "@mui/material/Typography";
|
||||||
import Accordion from "@mui/material/Accordion";
|
import Accordion from "@mui/material/Accordion";
|
||||||
@@ -26,8 +26,6 @@ import ExpandMoreIcon from "@mui/icons-material/ExpandMore";
|
|||||||
import { useRules } from "../../hooks/Rules";
|
import { useRules } from "../../hooks/Rules";
|
||||||
import MenuItem from "@mui/material/MenuItem";
|
import MenuItem from "@mui/material/MenuItem";
|
||||||
import Grid from "@mui/material/Grid";
|
import Grid from "@mui/material/Grid";
|
||||||
import FileDownloadIcon from "@mui/icons-material/FileDownload";
|
|
||||||
import FileUploadIcon from "@mui/icons-material/FileUpload";
|
|
||||||
import { useSetting } from "../../hooks/Setting";
|
import { useSetting } from "../../hooks/Setting";
|
||||||
import FormControlLabel from "@mui/material/FormControlLabel";
|
import FormControlLabel from "@mui/material/FormControlLabel";
|
||||||
import Switch from "@mui/material/Switch";
|
import Switch from "@mui/material/Switch";
|
||||||
@@ -50,6 +48,8 @@ import OwSubRule from "./OwSubRule";
|
|||||||
import ClearAllIcon from "@mui/icons-material/ClearAll";
|
import ClearAllIcon from "@mui/icons-material/ClearAll";
|
||||||
import HelpButton from "./HelpButton";
|
import HelpButton from "./HelpButton";
|
||||||
import { useSyncCaches } from "../../hooks/Sync";
|
import { useSyncCaches } from "../../hooks/Sync";
|
||||||
|
import DownloadButton from "./DownloadButton";
|
||||||
|
import UploadButton from "./UploadButton";
|
||||||
|
|
||||||
function RuleFields({ rule, rules, setShow, setKeyword }) {
|
function RuleFields({ rule, rules, setShow, setKeyword }) {
|
||||||
const initFormValues = rule || {
|
const initFormValues = rule || {
|
||||||
@@ -375,8 +375,9 @@ function RuleAccordion({ rule, rules }) {
|
|||||||
<Accordion expanded={expanded} onChange={handleChange}>
|
<Accordion expanded={expanded} onChange={handleChange}>
|
||||||
<AccordionSummary expandIcon={<ExpandMoreIcon />}>
|
<AccordionSummary expandIcon={<ExpandMoreIcon />}>
|
||||||
<Typography
|
<Typography
|
||||||
style={{
|
sx={{
|
||||||
opacity: rules ? 1 : 0.5,
|
opacity: rules ? 1 : 0.5,
|
||||||
|
overflowWrap: "anywhere",
|
||||||
}}
|
}}
|
||||||
>
|
>
|
||||||
{rule.pattern === GLOBAL_KEY
|
{rule.pattern === GLOBAL_KEY
|
||||||
@@ -391,56 +392,6 @@ function RuleAccordion({ rule, rules }) {
|
|||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
function DownloadButton({ data, text, fileName }) {
|
|
||||||
const handleClick = (e) => {
|
|
||||||
e.preventDefault();
|
|
||||||
if (data) {
|
|
||||||
const url = window.URL.createObjectURL(new Blob([data]));
|
|
||||||
const link = document.createElement("a");
|
|
||||||
link.href = url;
|
|
||||||
link.setAttribute("download", fileName || `${Date.now()}.json`);
|
|
||||||
document.body.appendChild(link);
|
|
||||||
link.click();
|
|
||||||
link.remove();
|
|
||||||
}
|
|
||||||
};
|
|
||||||
return (
|
|
||||||
<Button
|
|
||||||
size="small"
|
|
||||||
variant="outlined"
|
|
||||||
onClick={handleClick}
|
|
||||||
startIcon={<FileDownloadIcon />}
|
|
||||||
>
|
|
||||||
{text}
|
|
||||||
</Button>
|
|
||||||
);
|
|
||||||
}
|
|
||||||
|
|
||||||
function UploadButton({ onChange, text }) {
|
|
||||||
const inputRef = useRef(null);
|
|
||||||
const handleClick = () => {
|
|
||||||
inputRef.current && inputRef.current.click();
|
|
||||||
};
|
|
||||||
|
|
||||||
return (
|
|
||||||
<Button
|
|
||||||
size="small"
|
|
||||||
variant="outlined"
|
|
||||||
onClick={handleClick}
|
|
||||||
startIcon={<FileUploadIcon />}
|
|
||||||
>
|
|
||||||
{text}
|
|
||||||
<input
|
|
||||||
type="file"
|
|
||||||
accept=".json"
|
|
||||||
ref={inputRef}
|
|
||||||
onChange={onChange}
|
|
||||||
hidden
|
|
||||||
/>
|
|
||||||
</Button>
|
|
||||||
);
|
|
||||||
}
|
|
||||||
|
|
||||||
function ShareButton({ rules, injectRules, selectedUrl }) {
|
function ShareButton({ rules, injectRules, selectedUrl }) {
|
||||||
const alert = useAlert();
|
const alert = useAlert();
|
||||||
const i18n = useI18n();
|
const i18n = useI18n();
|
||||||
@@ -493,26 +444,12 @@ function UserRules({ subRules }) {
|
|||||||
const injectRules = !!setting?.injectRules;
|
const injectRules = !!setting?.injectRules;
|
||||||
const { selectedUrl, selectedRules } = subRules;
|
const { selectedUrl, selectedRules } = subRules;
|
||||||
|
|
||||||
const handleImport = (e) => {
|
const handleImport = async (data) => {
|
||||||
const file = e.target.files[0];
|
try {
|
||||||
if (!file) {
|
await rules.merge(JSON.parse(data));
|
||||||
return;
|
} catch (err) {
|
||||||
|
console.log("[import rules]", err);
|
||||||
}
|
}
|
||||||
|
|
||||||
if (!file.type.includes("json")) {
|
|
||||||
alert(i18n("error_wrong_file_type"));
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
|
|
||||||
const reader = new FileReader();
|
|
||||||
reader.onload = async (e) => {
|
|
||||||
try {
|
|
||||||
await rules.merge(JSON.parse(e.target.result));
|
|
||||||
} catch (err) {
|
|
||||||
console.log("[import rules]", err);
|
|
||||||
}
|
|
||||||
};
|
|
||||||
reader.readAsText(file);
|
|
||||||
};
|
};
|
||||||
|
|
||||||
const handleInject = () => {
|
const handleInject = () => {
|
||||||
@@ -552,10 +489,11 @@ function UserRules({ subRules }) {
|
|||||||
{i18n("add")}
|
{i18n("add")}
|
||||||
</Button>
|
</Button>
|
||||||
|
|
||||||
<UploadButton text={i18n("import")} onChange={handleImport} />
|
<UploadButton text={i18n("import")} handleImport={handleImport} />
|
||||||
<DownloadButton
|
<DownloadButton
|
||||||
data={JSON.stringify([...rules.list].reverse(), null, 2)}
|
data={JSON.stringify([...rules.list].reverse(), null, 2)}
|
||||||
text={i18n("export")}
|
text={i18n("export")}
|
||||||
|
fileName={`kiss-rules_${Date.now()}.json`}
|
||||||
/>
|
/>
|
||||||
|
|
||||||
<ShareButton
|
<ShareButton
|
||||||
@@ -663,7 +601,14 @@ function SubRulesItem({
|
|||||||
|
|
||||||
return (
|
return (
|
||||||
<Stack direction="row" alignItems="center" spacing={2}>
|
<Stack direction="row" alignItems="center" spacing={2}>
|
||||||
<FormControlLabel value={url} control={<Radio />} label={url} />
|
<FormControlLabel
|
||||||
|
value={url}
|
||||||
|
control={<Radio />}
|
||||||
|
sx={{
|
||||||
|
overflowWrap: "anywhere",
|
||||||
|
}}
|
||||||
|
label={url}
|
||||||
|
/>
|
||||||
|
|
||||||
{syncAt && (
|
{syncAt && (
|
||||||
<span style={{ marginLeft: "0.5em", opacity: 0.5 }}>
|
<span style={{ marginLeft: "0.5em", opacity: 0.5 }}>
|
||||||
|
|||||||
@@ -60,6 +60,9 @@ export default function Settings() {
|
|||||||
case "newlineLength":
|
case "newlineLength":
|
||||||
value = limitNumber(value, 1, 1000);
|
value = limitNumber(value, 1, 1000);
|
||||||
break;
|
break;
|
||||||
|
case "touchTranslate":
|
||||||
|
value = limitNumber(value, 0, 3);
|
||||||
|
break;
|
||||||
default:
|
default:
|
||||||
}
|
}
|
||||||
updateSetting({
|
updateSetting({
|
||||||
@@ -86,6 +89,7 @@ export default function Settings() {
|
|||||||
newlineLength = TRANS_NEWLINE_LENGTH,
|
newlineLength = TRANS_NEWLINE_LENGTH,
|
||||||
mouseKey = OPT_MOUSEKEY_DISABLE,
|
mouseKey = OPT_MOUSEKEY_DISABLE,
|
||||||
detectRemote = false,
|
detectRemote = false,
|
||||||
|
touchTranslate = 2,
|
||||||
} = setting;
|
} = setting;
|
||||||
const { isHide = false } = fab || {};
|
const { isHide = false } = fab || {};
|
||||||
|
|
||||||
@@ -169,6 +173,22 @@ export default function Settings() {
|
|||||||
</Select>
|
</Select>
|
||||||
</FormControl>
|
</FormControl>
|
||||||
|
|
||||||
|
<FormControl size="small">
|
||||||
|
<InputLabel>{i18n("touch_translate_shortcut")}</InputLabel>
|
||||||
|
<Select
|
||||||
|
name="touchTranslate"
|
||||||
|
value={touchTranslate}
|
||||||
|
label={i18n("touch_translate_shortcut")}
|
||||||
|
onChange={handleChange}
|
||||||
|
>
|
||||||
|
{[0, 2, 3].map((item) => (
|
||||||
|
<MenuItem key={item} value={item}>
|
||||||
|
{i18n(`touch_tap_${item}`)}
|
||||||
|
</MenuItem>
|
||||||
|
))}
|
||||||
|
</Select>
|
||||||
|
</FormControl>
|
||||||
|
|
||||||
<FormControl size="small">
|
<FormControl size="small">
|
||||||
<InputLabel>{i18n("hide_fab_button")}</InputLabel>
|
<InputLabel>{i18n("hide_fab_button")}</InputLabel>
|
||||||
<Select
|
<Select
|
||||||
|
|||||||
@@ -19,7 +19,10 @@ export default function Tranbox() {
|
|||||||
e.preventDefault();
|
e.preventDefault();
|
||||||
let { name, value } = e.target;
|
let { name, value } = e.target;
|
||||||
switch (name) {
|
switch (name) {
|
||||||
case "btnOffsetX" || "btnOffsetY":
|
case "btnOffsetX":
|
||||||
|
value = limitNumber(value, 0, 100);
|
||||||
|
break;
|
||||||
|
case "btnOffsetY":
|
||||||
value = limitNumber(value, 0, 100);
|
value = limitNumber(value, 0, 100);
|
||||||
break;
|
break;
|
||||||
default:
|
default:
|
||||||
|
|||||||
55
src/views/Options/UploadButton.js
Normal file
55
src/views/Options/UploadButton.js
Normal file
@@ -0,0 +1,55 @@
|
|||||||
|
import { useRef } from "react";
|
||||||
|
import FileUploadIcon from "@mui/icons-material/FileUpload";
|
||||||
|
import { useI18n } from "../../hooks/I18n";
|
||||||
|
import Button from "@mui/material/Button";
|
||||||
|
|
||||||
|
export default function UploadButton({
|
||||||
|
handleImport,
|
||||||
|
text,
|
||||||
|
fileType = "json",
|
||||||
|
fileExts = [".json"],
|
||||||
|
}) {
|
||||||
|
const i18n = useI18n();
|
||||||
|
const inputRef = useRef(null);
|
||||||
|
const handleClick = () => {
|
||||||
|
if (inputRef.current) {
|
||||||
|
inputRef.current.click();
|
||||||
|
inputRef.current.value = null;
|
||||||
|
}
|
||||||
|
};
|
||||||
|
const onChange = (e) => {
|
||||||
|
const file = e.target.files[0];
|
||||||
|
if (!file) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (!file.type.includes(fileType)) {
|
||||||
|
alert(i18n("error_wrong_file_type"));
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
const reader = new FileReader();
|
||||||
|
reader.onload = async (e) => {
|
||||||
|
handleImport(e.target.result);
|
||||||
|
};
|
||||||
|
reader.readAsText(file);
|
||||||
|
};
|
||||||
|
|
||||||
|
return (
|
||||||
|
<Button
|
||||||
|
size="small"
|
||||||
|
variant="outlined"
|
||||||
|
onClick={handleClick}
|
||||||
|
startIcon={<FileUploadIcon />}
|
||||||
|
>
|
||||||
|
{text}
|
||||||
|
<input
|
||||||
|
type="file"
|
||||||
|
accept={fileExts.join(", ")}
|
||||||
|
ref={inputRef}
|
||||||
|
onChange={onChange}
|
||||||
|
hidden
|
||||||
|
/>
|
||||||
|
</Button>
|
||||||
|
);
|
||||||
|
}
|
||||||
@@ -13,43 +13,204 @@ import FormControlLabel from "@mui/material/FormControlLabel";
|
|||||||
import Switch from "@mui/material/Switch";
|
import Switch from "@mui/material/Switch";
|
||||||
import { useSetting } from "../../hooks/Setting";
|
import { useSetting } from "../../hooks/Setting";
|
||||||
import CircularProgress from "@mui/material/CircularProgress";
|
import CircularProgress from "@mui/material/CircularProgress";
|
||||||
import { syncWebfix, loadOrFetchWebfix } from "../../libs/webfix";
|
import { syncWebfix, loadOrFetchWebfix, FIXER_ALL } from "../../libs/webfix";
|
||||||
import Button from "@mui/material/Button";
|
import Button from "@mui/material/Button";
|
||||||
import SyncIcon from "@mui/icons-material/Sync";
|
import SyncIcon from "@mui/icons-material/Sync";
|
||||||
import { useAlert } from "../../hooks/Alert";
|
import { useAlert } from "../../hooks/Alert";
|
||||||
import HelpButton from "./HelpButton";
|
import HelpButton from "./HelpButton";
|
||||||
import { URL_KISS_RULES_NEW_ISSUE } from "../../config";
|
import { URL_KISS_RULES_NEW_ISSUE } from "../../config";
|
||||||
|
import MenuItem from "@mui/material/MenuItem";
|
||||||
|
import { useWebfixRules } from "../../hooks/WebfixRules";
|
||||||
|
|
||||||
|
function WebfixFields({ rule, webfix, setShow }) {
|
||||||
|
const editMode = !!rule;
|
||||||
|
const initFormValues = rule || {
|
||||||
|
pattern: "",
|
||||||
|
selector: "",
|
||||||
|
rootSelector: "",
|
||||||
|
fixer: FIXER_ALL[0],
|
||||||
|
};
|
||||||
|
const i18n = useI18n();
|
||||||
|
const [disabled, setDisabled] = useState(editMode);
|
||||||
|
const [errors, setErrors] = useState({});
|
||||||
|
const [formValues, setFormValues] = useState(initFormValues);
|
||||||
|
|
||||||
|
const { pattern, selector, rootSelector, fixer } = formValues;
|
||||||
|
|
||||||
|
const hasSamePattern = (str) => {
|
||||||
|
for (const item of webfix.list || []) {
|
||||||
|
if (item.pattern === str && rule?.pattern !== str) {
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return false;
|
||||||
|
};
|
||||||
|
|
||||||
|
const handleFocus = (e) => {
|
||||||
|
e.preventDefault();
|
||||||
|
const { name } = e.target;
|
||||||
|
setErrors((pre) => ({ ...pre, [name]: "" }));
|
||||||
|
};
|
||||||
|
|
||||||
|
const handleChange = (e) => {
|
||||||
|
e.preventDefault();
|
||||||
|
const { name, value } = e.target;
|
||||||
|
setFormValues((pre) => ({ ...pre, [name]: value }));
|
||||||
|
};
|
||||||
|
|
||||||
|
const handleCancel = (e) => {
|
||||||
|
e.preventDefault();
|
||||||
|
if (editMode) {
|
||||||
|
setDisabled(true);
|
||||||
|
} else {
|
||||||
|
setShow(false);
|
||||||
|
}
|
||||||
|
setFormValues(initFormValues);
|
||||||
|
};
|
||||||
|
|
||||||
|
const handleSubmit = (e) => {
|
||||||
|
e.preventDefault();
|
||||||
|
const errors = {};
|
||||||
|
if (!pattern.trim()) {
|
||||||
|
errors.pattern = i18n("error_cant_be_blank");
|
||||||
|
}
|
||||||
|
if (hasSamePattern(pattern)) {
|
||||||
|
errors.pattern = i18n("error_duplicate_values");
|
||||||
|
}
|
||||||
|
if (!selector.trim()) {
|
||||||
|
errors.selector = i18n("error_cant_be_blank");
|
||||||
|
}
|
||||||
|
if (Object.keys(errors).length > 0) {
|
||||||
|
setErrors(errors);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (editMode) {
|
||||||
|
// 编辑
|
||||||
|
setDisabled(true);
|
||||||
|
webfix.put(rule.pattern, formValues);
|
||||||
|
} else {
|
||||||
|
// 添加
|
||||||
|
webfix.add(formValues);
|
||||||
|
setShow(false);
|
||||||
|
setFormValues(initFormValues);
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
function ApiFields({ site }) {
|
|
||||||
const { selector, rootSelector, fixer } = site;
|
|
||||||
return (
|
return (
|
||||||
<Stack spacing={3}>
|
<form onSubmit={handleSubmit}>
|
||||||
<TextField
|
<Stack spacing={3}>
|
||||||
size="small"
|
<TextField
|
||||||
label={"rootSelector"}
|
size="small"
|
||||||
name="rootSelector"
|
label={i18n("pattern")}
|
||||||
value={rootSelector || "document"}
|
error={!!errors.pattern}
|
||||||
disabled
|
helperText={errors.pattern}
|
||||||
/>
|
name="pattern"
|
||||||
<TextField
|
value={pattern}
|
||||||
size="small"
|
disabled={disabled}
|
||||||
label={"selector"}
|
onChange={handleChange}
|
||||||
name="selector"
|
onFocus={handleFocus}
|
||||||
value={selector}
|
multiline
|
||||||
disabled
|
/>
|
||||||
/>
|
<TextField
|
||||||
<TextField
|
size="small"
|
||||||
size="small"
|
label={i18n("root_selector")}
|
||||||
label={"fixer"}
|
error={!!errors.rootSelector}
|
||||||
name="fixer"
|
helperText={errors.rootSelector}
|
||||||
value={fixer}
|
name="rootSelector"
|
||||||
disabled
|
value={rootSelector}
|
||||||
/>
|
disabled={disabled}
|
||||||
</Stack>
|
onChange={handleChange}
|
||||||
|
onFocus={handleFocus}
|
||||||
|
multiline
|
||||||
|
/>
|
||||||
|
<TextField
|
||||||
|
size="small"
|
||||||
|
label={i18n("selector")}
|
||||||
|
error={!!errors.selector}
|
||||||
|
helperText={errors.selector}
|
||||||
|
name="selector"
|
||||||
|
value={selector}
|
||||||
|
disabled={disabled}
|
||||||
|
onChange={handleChange}
|
||||||
|
onFocus={handleFocus}
|
||||||
|
multiline
|
||||||
|
/>
|
||||||
|
<TextField
|
||||||
|
select
|
||||||
|
size="small"
|
||||||
|
name="fixer"
|
||||||
|
value={fixer}
|
||||||
|
label={i18n("fixer_function")}
|
||||||
|
disabled={disabled}
|
||||||
|
onChange={handleChange}
|
||||||
|
>
|
||||||
|
{FIXER_ALL.map((item) => (
|
||||||
|
<MenuItem key={item} value={item}>
|
||||||
|
{item}
|
||||||
|
</MenuItem>
|
||||||
|
))}
|
||||||
|
</TextField>
|
||||||
|
|
||||||
|
{webfix &&
|
||||||
|
(editMode ? (
|
||||||
|
// 编辑
|
||||||
|
<Stack direction="row" spacing={2}>
|
||||||
|
{disabled ? (
|
||||||
|
<>
|
||||||
|
<Button
|
||||||
|
size="small"
|
||||||
|
variant="contained"
|
||||||
|
onClick={(e) => {
|
||||||
|
e.preventDefault();
|
||||||
|
setDisabled(false);
|
||||||
|
}}
|
||||||
|
>
|
||||||
|
{i18n("edit")}
|
||||||
|
</Button>
|
||||||
|
<Button
|
||||||
|
size="small"
|
||||||
|
variant="outlined"
|
||||||
|
onClick={(e) => {
|
||||||
|
e.preventDefault();
|
||||||
|
webfix.del(rule.pattern);
|
||||||
|
}}
|
||||||
|
>
|
||||||
|
{i18n("delete")}
|
||||||
|
</Button>
|
||||||
|
</>
|
||||||
|
) : (
|
||||||
|
<>
|
||||||
|
<Button size="small" variant="contained" type="submit">
|
||||||
|
{i18n("save")}
|
||||||
|
</Button>
|
||||||
|
<Button
|
||||||
|
size="small"
|
||||||
|
variant="outlined"
|
||||||
|
onClick={handleCancel}
|
||||||
|
>
|
||||||
|
{i18n("cancel")}
|
||||||
|
</Button>
|
||||||
|
</>
|
||||||
|
)}
|
||||||
|
</Stack>
|
||||||
|
) : (
|
||||||
|
// 添加
|
||||||
|
<Stack direction="row" spacing={2}>
|
||||||
|
<Button size="small" variant="contained" type="submit">
|
||||||
|
{i18n("save")}
|
||||||
|
</Button>
|
||||||
|
<Button size="small" variant="outlined" onClick={handleCancel}>
|
||||||
|
{i18n("cancel")}
|
||||||
|
</Button>
|
||||||
|
</Stack>
|
||||||
|
))}
|
||||||
|
</Stack>
|
||||||
|
</form>
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
function ApiAccordion({ site }) {
|
function WebfixAccordion({ rule, webfix }) {
|
||||||
const [expanded, setExpanded] = useState(false);
|
const [expanded, setExpanded] = useState(false);
|
||||||
|
|
||||||
const handleChange = (e) => {
|
const handleChange = (e) => {
|
||||||
@@ -59,10 +220,17 @@ function ApiAccordion({ site }) {
|
|||||||
return (
|
return (
|
||||||
<Accordion expanded={expanded} onChange={handleChange}>
|
<Accordion expanded={expanded} onChange={handleChange}>
|
||||||
<AccordionSummary expandIcon={<ExpandMoreIcon />}>
|
<AccordionSummary expandIcon={<ExpandMoreIcon />}>
|
||||||
<Typography>{site.pattern}</Typography>
|
<Typography
|
||||||
|
sx={{
|
||||||
|
opacity: webfix ? 1 : 0.5,
|
||||||
|
overflowWrap: "anywhere",
|
||||||
|
}}
|
||||||
|
>
|
||||||
|
{rule.pattern}
|
||||||
|
</Typography>
|
||||||
</AccordionSummary>
|
</AccordionSummary>
|
||||||
<AccordionDetails>
|
<AccordionDetails>
|
||||||
{expanded && <ApiFields site={site} />}
|
{expanded && <WebfixFields rule={rule} webfix={webfix} />}
|
||||||
</AccordionDetails>
|
</AccordionDetails>
|
||||||
</Accordion>
|
</Accordion>
|
||||||
);
|
);
|
||||||
@@ -74,6 +242,8 @@ export default function Webfix() {
|
|||||||
const i18n = useI18n();
|
const i18n = useI18n();
|
||||||
const alert = useAlert();
|
const alert = useAlert();
|
||||||
const { setting, updateSetting } = useSetting();
|
const { setting, updateSetting } = useSetting();
|
||||||
|
const [showAdd, setShowAdd] = useState(false);
|
||||||
|
const webfix = useWebfixRules();
|
||||||
|
|
||||||
const loadSites = useCallback(async () => {
|
const loadSites = useCallback(async () => {
|
||||||
const sites = await loadOrFetchWebfix(process.env.REACT_APP_WEBFIXURL);
|
const sites = await loadOrFetchWebfix(process.env.REACT_APP_WEBFIXURL);
|
||||||
@@ -120,6 +290,18 @@ export default function Webfix() {
|
|||||||
useFlexGap
|
useFlexGap
|
||||||
flexWrap="wrap"
|
flexWrap="wrap"
|
||||||
>
|
>
|
||||||
|
<Button
|
||||||
|
size="small"
|
||||||
|
variant="contained"
|
||||||
|
disabled={showAdd}
|
||||||
|
onClick={(e) => {
|
||||||
|
e.preventDefault();
|
||||||
|
setShowAdd(true);
|
||||||
|
}}
|
||||||
|
>
|
||||||
|
{i18n("add")}
|
||||||
|
</Button>
|
||||||
|
|
||||||
<Button
|
<Button
|
||||||
size="small"
|
size="small"
|
||||||
variant="outlined"
|
variant="outlined"
|
||||||
@@ -146,6 +328,16 @@ export default function Webfix() {
|
|||||||
/>
|
/>
|
||||||
</Stack>
|
</Stack>
|
||||||
|
|
||||||
|
{showAdd && <WebfixFields webfix={webfix} setShow={setShowAdd} />}
|
||||||
|
|
||||||
|
{webfix.list?.length > 0 && (
|
||||||
|
<Box>
|
||||||
|
{webfix.list.map((rule) => (
|
||||||
|
<WebfixAccordion key={rule.pattern} rule={rule} webfix={webfix} />
|
||||||
|
))}
|
||||||
|
</Box>
|
||||||
|
)}
|
||||||
|
|
||||||
{setting.injectWebfix && (
|
{setting.injectWebfix && (
|
||||||
<Box>
|
<Box>
|
||||||
{loading ? (
|
{loading ? (
|
||||||
@@ -153,8 +345,8 @@ export default function Webfix() {
|
|||||||
<CircularProgress size={16} />
|
<CircularProgress size={16} />
|
||||||
</center>
|
</center>
|
||||||
) : (
|
) : (
|
||||||
sites.map((site) => (
|
sites.map((rule) => (
|
||||||
<ApiAccordion key={site.pattern} site={site} />
|
<WebfixAccordion key={rule.pattern} rule={rule} />
|
||||||
))
|
))
|
||||||
)}
|
)}
|
||||||
</Box>
|
</Box>
|
||||||
|
|||||||
@@ -21,6 +21,7 @@ import Apis from "./Apis";
|
|||||||
import Webfix from "./Webfix";
|
import Webfix from "./Webfix";
|
||||||
import InputSetting from "./InputSetting";
|
import InputSetting from "./InputSetting";
|
||||||
import Tranbox from "./Tranbox";
|
import Tranbox from "./Tranbox";
|
||||||
|
import FavWords from "./FavWords";
|
||||||
|
|
||||||
export default function Options() {
|
export default function Options() {
|
||||||
const [error, setError] = useState("");
|
const [error, setError] = useState("");
|
||||||
@@ -125,6 +126,7 @@ export default function Options() {
|
|||||||
<Route path="apis" element={<Apis />} />
|
<Route path="apis" element={<Apis />} />
|
||||||
<Route path="sync" element={<SyncSetting />} />
|
<Route path="sync" element={<SyncSetting />} />
|
||||||
<Route path="webfix" element={<Webfix />} />
|
<Route path="webfix" element={<Webfix />} />
|
||||||
|
<Route path="words" element={<FavWords />} />
|
||||||
<Route path="about" element={<About />} />
|
<Route path="about" element={<About />} />
|
||||||
</Route>
|
</Route>
|
||||||
</Routes>
|
</Routes>
|
||||||
|
|||||||
35
src/views/Selection/CopyBtn.js
Normal file
35
src/views/Selection/CopyBtn.js
Normal file
@@ -0,0 +1,35 @@
|
|||||||
|
import IconButton from "@mui/material/IconButton";
|
||||||
|
import ContentCopyIcon from "@mui/icons-material/ContentCopy";
|
||||||
|
import LibraryAddCheckIcon from "@mui/icons-material/LibraryAddCheck";
|
||||||
|
import { useState } from "react";
|
||||||
|
|
||||||
|
export default function CopyBtn({ text }) {
|
||||||
|
const [copied, setCopied] = useState(false);
|
||||||
|
const handleClick = (e) => {
|
||||||
|
e.stopPropagation();
|
||||||
|
navigator.clipboard.writeText(text);
|
||||||
|
setCopied(true);
|
||||||
|
const timer = setTimeout(() => {
|
||||||
|
clearTimeout(timer);
|
||||||
|
setCopied(false);
|
||||||
|
}, 500);
|
||||||
|
};
|
||||||
|
return (
|
||||||
|
<IconButton
|
||||||
|
size="small"
|
||||||
|
sx={{
|
||||||
|
opacity: 0.5,
|
||||||
|
"&:hover": {
|
||||||
|
opacity: 1,
|
||||||
|
},
|
||||||
|
}}
|
||||||
|
onClick={handleClick}
|
||||||
|
>
|
||||||
|
{copied ? (
|
||||||
|
<LibraryAddCheckIcon fontSize="inherit" />
|
||||||
|
) : (
|
||||||
|
<ContentCopyIcon fontSize="inherit" />
|
||||||
|
)}
|
||||||
|
</IconButton>
|
||||||
|
);
|
||||||
|
}
|
||||||
64
src/views/Selection/DictCont.js
Normal file
64
src/views/Selection/DictCont.js
Normal file
@@ -0,0 +1,64 @@
|
|||||||
|
import Box from "@mui/material/Box";
|
||||||
|
import Chip from "@mui/material/Chip";
|
||||||
|
import Stack from "@mui/material/Stack";
|
||||||
|
import FavBtn from "./FavBtn";
|
||||||
|
|
||||||
|
const exchangeMap = {
|
||||||
|
word_third: "第三人称单数",
|
||||||
|
word_ing: "现在分词",
|
||||||
|
word_done: "过去式",
|
||||||
|
word_past: "过去分词",
|
||||||
|
word_pl: "复数",
|
||||||
|
word_proto: "词源",
|
||||||
|
};
|
||||||
|
|
||||||
|
export default function DictCont({ dictResult }) {
|
||||||
|
if (!dictResult) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
return (
|
||||||
|
<Box>
|
||||||
|
<Stack
|
||||||
|
direction="row"
|
||||||
|
justifyContent="space-between"
|
||||||
|
alignItems="flex-start"
|
||||||
|
>
|
||||||
|
<div style={{ fontWeight: "bold" }}>
|
||||||
|
{dictResult.simple_means?.word_name}
|
||||||
|
</div>
|
||||||
|
<FavBtn word={dictResult.simple_means?.word_name} />
|
||||||
|
</Stack>
|
||||||
|
|
||||||
|
{dictResult.simple_means?.symbols?.map(({ ph_en, ph_am, parts }, idx) => (
|
||||||
|
<div key={idx}>
|
||||||
|
{(ph_en || ph_am) && (
|
||||||
|
<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} flexWrap="wrap" useFlexGap>
|
||||||
|
{Object.values(dictResult.simple_means?.tags || {})
|
||||||
|
.flat()
|
||||||
|
.filter((item) => item)
|
||||||
|
.map((item) => (
|
||||||
|
<Chip label={item} size="small" />
|
||||||
|
))}
|
||||||
|
</Stack>
|
||||||
|
</Box>
|
||||||
|
);
|
||||||
|
}
|
||||||
31
src/views/Selection/FavBtn.js
Normal file
31
src/views/Selection/FavBtn.js
Normal file
@@ -0,0 +1,31 @@
|
|||||||
|
import IconButton from "@mui/material/IconButton";
|
||||||
|
import FavoriteIcon from "@mui/icons-material/Favorite";
|
||||||
|
import FavoriteBorderIcon from "@mui/icons-material/FavoriteBorder";
|
||||||
|
import { useState } from "react";
|
||||||
|
import { useFavWords } from "../../hooks/FavWords";
|
||||||
|
|
||||||
|
export default function FavBtn({ word }) {
|
||||||
|
const { favWords, toggleFav } = useFavWords();
|
||||||
|
const [loading, setLoading] = useState(false);
|
||||||
|
|
||||||
|
const handleClick = async () => {
|
||||||
|
try {
|
||||||
|
setLoading(true);
|
||||||
|
await toggleFav(word);
|
||||||
|
} catch (err) {
|
||||||
|
console.log("[set fav]", err);
|
||||||
|
} finally {
|
||||||
|
setLoading(false);
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
return (
|
||||||
|
<IconButton disabled={loading} size="small" onClick={handleClick}>
|
||||||
|
{favWords[word] ? (
|
||||||
|
<FavoriteIcon fontSize="inherit" />
|
||||||
|
) : (
|
||||||
|
<FavoriteBorderIcon fontSize="inherit" />
|
||||||
|
)}
|
||||||
|
</IconButton>
|
||||||
|
);
|
||||||
|
}
|
||||||
@@ -8,10 +8,13 @@ import MenuItem from "@mui/material/MenuItem";
|
|||||||
import Grid from "@mui/material/Grid";
|
import Grid from "@mui/material/Grid";
|
||||||
import Box from "@mui/material/Box";
|
import Box from "@mui/material/Box";
|
||||||
import Divider from "@mui/material/Divider";
|
import Divider from "@mui/material/Divider";
|
||||||
|
import IconButton from "@mui/material/IconButton";
|
||||||
|
import DoneIcon from "@mui/icons-material/Done";
|
||||||
import { useI18n } from "../../hooks/I18n";
|
import { useI18n } from "../../hooks/I18n";
|
||||||
import { OPT_TRANS_ALL, OPT_LANGS_FROM, OPT_LANGS_TO } from "../../config";
|
import { OPT_TRANS_ALL, OPT_LANGS_FROM, OPT_LANGS_TO } from "../../config";
|
||||||
import { useState, useRef } from "react";
|
import { useState, useRef } from "react";
|
||||||
import TranCont from "./TranCont";
|
import TranCont from "./TranCont";
|
||||||
|
import CopyBtn from "./CopyBtn";
|
||||||
|
|
||||||
function TranForm({ text, setText, tranboxSetting, transApis }) {
|
function TranForm({ text, setText, tranboxSetting, transApis }) {
|
||||||
const i18n = useI18n();
|
const i18n = useI18n();
|
||||||
@@ -113,6 +116,31 @@ function TranForm({ text, setText, tranboxSetting, transApis }) {
|
|||||||
setEditMode(false);
|
setEditMode(false);
|
||||||
setText(editText.trim());
|
setText(editText.trim());
|
||||||
}}
|
}}
|
||||||
|
InputProps={{
|
||||||
|
endAdornment: (
|
||||||
|
<Stack
|
||||||
|
direction="row"
|
||||||
|
sx={{
|
||||||
|
position: "absolute",
|
||||||
|
right: 0,
|
||||||
|
top: 0,
|
||||||
|
}}
|
||||||
|
>
|
||||||
|
{editMode ? (
|
||||||
|
<IconButton
|
||||||
|
size="small"
|
||||||
|
onClick={(e) => {
|
||||||
|
e.stopPropagation();
|
||||||
|
}}
|
||||||
|
>
|
||||||
|
<DoneIcon fontSize="inherit" />
|
||||||
|
</IconButton>
|
||||||
|
) : (
|
||||||
|
<CopyBtn text={text} />
|
||||||
|
)}
|
||||||
|
</Stack>
|
||||||
|
),
|
||||||
|
}}
|
||||||
/>
|
/>
|
||||||
</Box>
|
</Box>
|
||||||
|
|
||||||
@@ -2,61 +2,14 @@ import TextField from "@mui/material/TextField";
|
|||||||
import Box from "@mui/material/Box";
|
import Box from "@mui/material/Box";
|
||||||
import Alert from "@mui/material/Alert";
|
import Alert from "@mui/material/Alert";
|
||||||
import CircularProgress from "@mui/material/CircularProgress";
|
import CircularProgress from "@mui/material/CircularProgress";
|
||||||
import Chip from "@mui/material/Chip";
|
|
||||||
import Stack from "@mui/material/Stack";
|
import Stack from "@mui/material/Stack";
|
||||||
import { useI18n } from "../../hooks/I18n";
|
import { useI18n } from "../../hooks/I18n";
|
||||||
import { DEFAULT_TRANS_APIS, OPT_TRANS_BAIDU } from "../../config";
|
import { DEFAULT_TRANS_APIS, OPT_TRANS_BAIDU } from "../../config";
|
||||||
import { useEffect, useState } from "react";
|
import { useEffect, useState } from "react";
|
||||||
import { apiTranslate } from "../../apis";
|
import { apiTranslate } from "../../apis";
|
||||||
import { isValidWord } from "../../libs/utils";
|
import { isValidWord } from "../../libs/utils";
|
||||||
|
import CopyBtn from "./CopyBtn";
|
||||||
const exchangeMap = {
|
import DictCont from "./DictCont";
|
||||||
word_third: "第三人称单数",
|
|
||||||
word_ing: "现在分词",
|
|
||||||
word_done: "过去式",
|
|
||||||
word_past: "过去分词",
|
|
||||||
word_pl: "复数",
|
|
||||||
word_proto: "原词",
|
|
||||||
};
|
|
||||||
|
|
||||||
function DictCont({ dictResult }) {
|
|
||||||
if (!dictResult) {
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
|
|
||||||
return (
|
|
||||||
<Box>
|
|
||||||
<div style={{ fontWeight: "bold" }}>
|
|
||||||
{dictResult.simple_means?.word_name}
|
|
||||||
</div>
|
|
||||||
{dictResult.simple_means?.symbols?.map(({ ph_en, ph_am, parts }, idx) => (
|
|
||||||
<div key={idx}>
|
|
||||||
<div>{`英[${ph_en}] 美[${ph_am}]`}</div>
|
|
||||||
<ul style={{ margin: "0.5em 0" }}>
|
|
||||||
{parts.map(({ part, means }, idx) => (
|
|
||||||
<li key={idx}>
|
|
||||||
{part ? `[${part}] ${means.join("; ")}` : means.join("; ")}
|
|
||||||
</li>
|
|
||||||
))}
|
|
||||||
</ul>
|
|
||||||
</div>
|
|
||||||
))}
|
|
||||||
<div>
|
|
||||||
{Object.entries(dictResult.simple_means?.exchange || {})
|
|
||||||
.map(([key, val]) => `${exchangeMap[key] || key}: ${val.join(", ")}`)
|
|
||||||
.join("; ")}
|
|
||||||
</div>
|
|
||||||
<Stack direction="row" spacing={1}>
|
|
||||||
{Object.values(dictResult.simple_means?.tags || {})
|
|
||||||
.flat()
|
|
||||||
.filter((item) => item)
|
|
||||||
.map((item) => (
|
|
||||||
<Chip label={item} size="small" />
|
|
||||||
))}
|
|
||||||
</Stack>
|
|
||||||
</Box>
|
|
||||||
);
|
|
||||||
}
|
|
||||||
|
|
||||||
export default function TranCont({
|
export default function TranCont({
|
||||||
text,
|
text,
|
||||||
@@ -79,8 +32,8 @@ export default function TranCont({
|
|||||||
setError("");
|
setError("");
|
||||||
setDictResult(null);
|
setDictResult(null);
|
||||||
|
|
||||||
const apis = { ...transApis, ...DEFAULT_TRANS_APIS };
|
const apiSetting =
|
||||||
const apiSetting = apis[translator];
|
transApis[translator] || DEFAULT_TRANS_APIS[translator];
|
||||||
const tranRes = await apiTranslate({
|
const tranRes = await apiTranslate({
|
||||||
text,
|
text,
|
||||||
translator,
|
translator,
|
||||||
@@ -100,7 +53,6 @@ export default function TranCont({
|
|||||||
translator: OPT_TRANS_BAIDU,
|
translator: OPT_TRANS_BAIDU,
|
||||||
fromLang: "en",
|
fromLang: "en",
|
||||||
toLang: "zh-CN",
|
toLang: "zh-CN",
|
||||||
apiSetting: apis[OPT_TRANS_BAIDU],
|
|
||||||
});
|
});
|
||||||
setDictResult(dictRes[2].dict_result);
|
setDictResult(dictRes[2].dict_result);
|
||||||
}
|
}
|
||||||
@@ -118,9 +70,24 @@ export default function TranCont({
|
|||||||
<Box>
|
<Box>
|
||||||
<TextField
|
<TextField
|
||||||
label={i18n("translated_text")}
|
label={i18n("translated_text")}
|
||||||
|
// disabled
|
||||||
fullWidth
|
fullWidth
|
||||||
multiline
|
multiline
|
||||||
value={trText}
|
value={trText}
|
||||||
|
InputProps={{
|
||||||
|
endAdornment: (
|
||||||
|
<Stack
|
||||||
|
direction="row"
|
||||||
|
sx={{
|
||||||
|
position: "absolute",
|
||||||
|
right: 0,
|
||||||
|
top: 0,
|
||||||
|
}}
|
||||||
|
>
|
||||||
|
<CopyBtn text={trText} />
|
||||||
|
</Stack>
|
||||||
|
),
|
||||||
|
}}
|
||||||
/>
|
/>
|
||||||
</Box>
|
</Box>
|
||||||
|
|
||||||
|
|||||||
@@ -1,7 +1,8 @@
|
|||||||
import { useState, useEffect } from "react";
|
import { useState, useEffect } from "react";
|
||||||
import TranBtn from "./Tranbtn";
|
import TranBtn from "./TranBtn";
|
||||||
import TranBox from "./Tranbox";
|
import TranBox from "./TranBox";
|
||||||
import { shortcutRegister } from "../../libs/shortcut";
|
import { shortcutRegister } from "../../libs/shortcut";
|
||||||
|
import { sleep } from "../../libs/utils";
|
||||||
|
|
||||||
export default function Slection({ tranboxSetting, transApis }) {
|
export default function Slection({ tranboxSetting, transApis }) {
|
||||||
const [showBox, setShowBox] = useState(false);
|
const [showBox, setShowBox] = useState(false);
|
||||||
@@ -15,7 +16,9 @@ export default function Slection({ tranboxSetting, transApis }) {
|
|||||||
y: (window.innerHeight - 400) / 2,
|
y: (window.innerHeight - 400) / 2,
|
||||||
});
|
});
|
||||||
|
|
||||||
function handleMouseup(e) {
|
async function handleMouseup(e) {
|
||||||
|
await sleep(10);
|
||||||
|
|
||||||
const selectedText = window.getSelection()?.toString()?.trim() || "";
|
const selectedText = window.getSelection()?.toString()?.trim() || "";
|
||||||
if (!selectedText) {
|
if (!selectedText) {
|
||||||
setShowBtn(false);
|
setShowBtn(false);
|
||||||
|
|||||||
Reference in New Issue
Block a user