Compare commits
21 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
5947dc182e | ||
|
|
e185bbdb4d | ||
|
|
9368320c38 | ||
|
|
f65314bc2d | ||
|
|
1791e36038 | ||
|
|
8d93094af5 | ||
|
|
43f34fe6ed | ||
|
|
83911b2164 | ||
|
|
94c7494e90 | ||
|
|
65f2177299 | ||
|
|
f033b11e63 | ||
|
|
02f26af592 | ||
|
|
4125aba808 | ||
|
|
e89da9120c | ||
|
|
160fc218fc | ||
|
|
507d54dba0 | ||
|
|
f3029a0f76 | ||
|
|
53181588cf | ||
|
|
f88aa159fc | ||
|
|
fb2b517a67 | ||
|
|
6e952a9530 |
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.7
|
REACT_APP_VERSION=1.7.9
|
||||||
|
|
||||||
REACT_APP_HOMEPAGE=https://github.com/fishjar/kiss-translator
|
REACT_APP_HOMEPAGE=https://github.com/fishjar/kiss-translator
|
||||||
|
|
||||||
|
|||||||
18
README.en.md
18
README.en.md
@@ -4,16 +4,6 @@ A simple [bilingual translation extension & Greasemonkey script](https://github.
|
|||||||
|
|
||||||
[kiss-translator.webm](https://github.com/fishjar/kiss-translator/assets/1157624/f7ba8a5c-e4a8-4d5a-823a-5c5c67a0a47f)
|
[kiss-translator.webm](https://github.com/fishjar/kiss-translator/assets/1157624/f7ba8a5c-e4a8-4d5a-823a-5c5c67a0a47f)
|
||||||
|
|
||||||
## Inspiration
|
|
||||||
|
|
||||||
The inspiration for this project comes from [Immersive Translate](https://github.com/immersive-translate/immersive-translate). After trying it out, I found that it can be used together with the [Webpage Word Translation Extension](https://github.com/fishjar/kiss-dictionary) developed by me earlier, which just forms a very good supplement.
|
|
||||||
|
|
||||||
But the function of this extension is a bit complicated for me, and only the compiled and obfuscated installation package is provided, and the source code is not provided, which cannot meet some of my personalized customization needs.
|
|
||||||
|
|
||||||
It just so happens that I am obsessed with translation tools. Based on the concept of "mainly for personal use, as long as you can use it", I made one. At present, the first version is completed, which basically meets the needs of personal use.
|
|
||||||
|
|
||||||
If you also like a little more simplicity, welcome to pick it up.
|
|
||||||
|
|
||||||
## Features
|
## Features
|
||||||
|
|
||||||
- [x] Keep it simple, smart
|
- [x] Keep it simple, smart
|
||||||
@@ -22,11 +12,12 @@ If you also like a little more simplicity, welcome to pick it up.
|
|||||||
- [x] Chrome/Edge/Firefox/Kiwi
|
- [x] Chrome/Edge/Firefox/Kiwi
|
||||||
- [ ] Safari
|
- [ ] Safari
|
||||||
- [x] Supports multiple translation services
|
- [x] Supports multiple translation services
|
||||||
- [x] Google/Microsoft/DeepL/OpenAI
|
- [x] Google/Microsoft/DeepL/OpenAI/Baidu/Tencent
|
||||||
- [x] Custom translation interface
|
- [x] Custom translation interface
|
||||||
- [x] 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] Mouseover translation
|
- [x] Mouseover translation
|
||||||
- [x] YouTube subtitle translation
|
- [x] YouTube subtitle translation
|
||||||
- [x] Cross-client data synchronization
|
- [x] Cross-client data synchronization
|
||||||
@@ -38,8 +29,9 @@ If you also like a little more simplicity, welcome to pick it up.
|
|||||||
- [x] Custom shortcut keys
|
- [x] Custom shortcut keys
|
||||||
- `Alt+Q` Toggle Translation
|
- `Alt+Q` Toggle Translation
|
||||||
- `Alt+C` Toggle Styles
|
- `Alt+C` Toggle Styles
|
||||||
- `Alt+K` Open Popup
|
- `Alt+K` Open Setting Popup
|
||||||
- `Alt+O` Open Options
|
- `Alt+B` Open Translate Popup
|
||||||
|
- `Alt+O` Open Options Page
|
||||||
- `Alt+I` Input Box Translation
|
- `Alt+I` Input Box Translation
|
||||||
|
|
||||||
## Install
|
## Install
|
||||||
|
|||||||
@@ -12,11 +12,12 @@
|
|||||||
- [x] Chrome/Edge/Firefox/Kiwi
|
- [x] Chrome/Edge/Firefox/Kiwi
|
||||||
- [ ] Safari
|
- [ ] Safari
|
||||||
- [x] 支持多种翻译服务
|
- [x] 支持多种翻译服务
|
||||||
- [x] Google/Microsoft/DeepL/OpenAI
|
- [x] Google/Microsoft/DeepL/OpenAI/Baidu/Tencent
|
||||||
- [x] 自定义翻译接口
|
- [x] 自定义翻译接口
|
||||||
- [x] 覆盖常见翻译场景
|
- [x] 覆盖常见翻译场景
|
||||||
- [x] 网页双语对照翻译
|
- [x] 网页双语对照翻译
|
||||||
- [x] 输入框翻译
|
- [x] 输入框翻译
|
||||||
|
- [x] 划词翻译
|
||||||
- [x] 鼠标悬停翻译
|
- [x] 鼠标悬停翻译
|
||||||
- [x] YouTube 字幕翻译
|
- [x] YouTube 字幕翻译
|
||||||
- [x] 跨客户端数据同步
|
- [x] 跨客户端数据同步
|
||||||
@@ -28,8 +29,9 @@
|
|||||||
- [x] 自定义快捷键
|
- [x] 自定义快捷键
|
||||||
- `Alt+Q` 开启翻译
|
- `Alt+Q` 开启翻译
|
||||||
- `Alt+C` 切换样式
|
- `Alt+C` 切换样式
|
||||||
- `Alt+K` 打开弹窗
|
- `Alt+K` 打开设置弹窗
|
||||||
- `Alt+O` 打开设置
|
- `Alt+B` 打开翻译弹窗
|
||||||
|
- `Alt+O` 打开设置页面
|
||||||
- `Alt+I` 输入框翻译
|
- `Alt+I` 输入框翻译
|
||||||
|
|
||||||
## 安装
|
## 安装
|
||||||
|
|||||||
@@ -95,6 +95,7 @@ const userscriptWebpack = (config, env) => {
|
|||||||
// @connect edge.microsoft.com
|
// @connect edge.microsoft.com
|
||||||
// @connect api-free.deepl.com
|
// @connect api-free.deepl.com
|
||||||
// @connect api.deepl.com
|
// @connect api.deepl.com
|
||||||
|
// @connect www2.deepl.com
|
||||||
// @connect api.openai.com
|
// @connect api.openai.com
|
||||||
// @connect openai.azure.com
|
// @connect openai.azure.com
|
||||||
// @connect workers.dev
|
// @connect workers.dev
|
||||||
@@ -104,7 +105,11 @@ const userscriptWebpack = (config, env) => {
|
|||||||
// @connect ghproxy.com
|
// @connect ghproxy.com
|
||||||
// @connect dav.jianguoyun.com
|
// @connect dav.jianguoyun.com
|
||||||
// @connect fanyi.baidu.com
|
// @connect fanyi.baidu.com
|
||||||
|
// @connect transmart.qq.com
|
||||||
// @connect localhost:3000
|
// @connect localhost:3000
|
||||||
|
// @connect 127.0.0.1:3000
|
||||||
|
// @connect localhost:1188
|
||||||
|
// @connect 127.0.0.1:1188
|
||||||
// @run-at document-end
|
// @run-at document-end
|
||||||
// ==/UserScript==
|
// ==/UserScript==
|
||||||
|
|
||||||
|
|||||||
@@ -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.7",
|
"version": "1.7.9",
|
||||||
"author": "Gabe<yugang2002@gmail.com>",
|
"author": "Gabe<yugang2002@gmail.com>",
|
||||||
"private": true,
|
"private": true,
|
||||||
"dependencies": {
|
"dependencies": {
|
||||||
|
|||||||
@@ -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.7",
|
"version": "1.7.9",
|
||||||
"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.7",
|
"version": "1.7.9",
|
||||||
"default_locale": "en",
|
"default_locale": "en",
|
||||||
"author": "Gabe<yugang2002@gmail.com>",
|
"author": "Gabe<yugang2002@gmail.com>",
|
||||||
"homepage_url": "https://github.com/fishjar/kiss-translator",
|
"homepage_url": "https://github.com/fishjar/kiss-translator",
|
||||||
|
|||||||
230
src/apis/baidu.js
Normal file
230
src/apis/baidu.js
Normal file
@@ -0,0 +1,230 @@
|
|||||||
|
import queryString from "query-string";
|
||||||
|
import { getBdauth, setBdauth } from "../libs/storage";
|
||||||
|
import { URL_BAIDU_WEB, URL_BAIDU_TRAN } from "../config";
|
||||||
|
import { fetchApi } from "../libs/fetch";
|
||||||
|
|
||||||
|
/* eslint-disable */
|
||||||
|
function n(t, e) {
|
||||||
|
for (var n = 0; n < e.length - 2; n += 3) {
|
||||||
|
var r = e.charAt(n + 2);
|
||||||
|
(r = "a" <= r ? r.charCodeAt(0) - 87 : Number(r)),
|
||||||
|
(r = "+" === e.charAt(n + 1) ? t >>> r : t << r),
|
||||||
|
(t = "+" === e.charAt(n) ? (t + r) & 4294967295 : t ^ r);
|
||||||
|
}
|
||||||
|
return t;
|
||||||
|
}
|
||||||
|
|
||||||
|
function e(t, e) {
|
||||||
|
(null == e || e > t.length) && (e = t.length);
|
||||||
|
for (var n = 0, r = new Array(e); n < e; n++) r[n] = t[n];
|
||||||
|
return r;
|
||||||
|
}
|
||||||
|
|
||||||
|
/* eslint-disable */
|
||||||
|
function getSign(t, gtk, r = null) {
|
||||||
|
var o,
|
||||||
|
i = t.match(/[\uD800-\uDBFF][\uDC00-\uDFFF]/g);
|
||||||
|
if (null === i) {
|
||||||
|
var a = t.length;
|
||||||
|
a > 30 &&
|
||||||
|
(t = ""
|
||||||
|
.concat(t.substr(0, 10))
|
||||||
|
.concat(t.substr(Math.floor(a / 2) - 5, 10))
|
||||||
|
.concat(t.substr(-10, 10)));
|
||||||
|
} else {
|
||||||
|
for (
|
||||||
|
var s = t.split(/[\uD800-\uDBFF][\uDC00-\uDFFF]/),
|
||||||
|
c = 0,
|
||||||
|
u = s.length,
|
||||||
|
l = [];
|
||||||
|
c < u;
|
||||||
|
c++
|
||||||
|
)
|
||||||
|
"" !== s[c] &&
|
||||||
|
l.push.apply(
|
||||||
|
l,
|
||||||
|
(function (t) {
|
||||||
|
if (Array.isArray(t)) return e(t);
|
||||||
|
})((o = s[c].split(""))) ||
|
||||||
|
(function (t) {
|
||||||
|
if (
|
||||||
|
("undefined" != typeof Symbol && null != t[Symbol.iterator]) ||
|
||||||
|
null != t["@@iterator"]
|
||||||
|
)
|
||||||
|
return Array.from(t);
|
||||||
|
})(o) ||
|
||||||
|
(function (t, n) {
|
||||||
|
if (t) {
|
||||||
|
if ("string" == typeof t) return e(t, n);
|
||||||
|
var r = Object.prototype.toString.call(t).slice(8, -1);
|
||||||
|
return (
|
||||||
|
"Object" === r && t.constructor && (r = t.constructor.name),
|
||||||
|
"Map" === r || "Set" === r
|
||||||
|
? Array.from(t)
|
||||||
|
: "Arguments" === r ||
|
||||||
|
/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(r)
|
||||||
|
? e(t, n)
|
||||||
|
: void 0
|
||||||
|
);
|
||||||
|
}
|
||||||
|
})(o) ||
|
||||||
|
(function () {
|
||||||
|
throw new TypeError(
|
||||||
|
"Invalid attempt to spread non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method."
|
||||||
|
);
|
||||||
|
})()
|
||||||
|
),
|
||||||
|
c !== u - 1 && l.push(i[c]);
|
||||||
|
var p = l.length;
|
||||||
|
p > 30 &&
|
||||||
|
(t =
|
||||||
|
l.slice(0, 10).join("") +
|
||||||
|
l.slice(Math.floor(p / 2) - 5, Math.floor(p / 2) + 5).join("") +
|
||||||
|
l.slice(-10).join(""));
|
||||||
|
}
|
||||||
|
for (
|
||||||
|
var d = ""
|
||||||
|
.concat(String.fromCharCode(103))
|
||||||
|
.concat(String.fromCharCode(116))
|
||||||
|
.concat(String.fromCharCode(107)),
|
||||||
|
h = (null !== r ? r : (r = gtk || "") || "").split("."),
|
||||||
|
f = Number(h[0]) || 0,
|
||||||
|
m = Number(h[1]) || 0,
|
||||||
|
g = [],
|
||||||
|
y = 0,
|
||||||
|
v = 0;
|
||||||
|
v < t.length;
|
||||||
|
v++
|
||||||
|
) {
|
||||||
|
var _ = t.charCodeAt(v);
|
||||||
|
_ < 128
|
||||||
|
? (g[y++] = _)
|
||||||
|
: (_ < 2048
|
||||||
|
? (g[y++] = (_ >> 6) | 192)
|
||||||
|
: (55296 == (64512 & _) &&
|
||||||
|
v + 1 < t.length &&
|
||||||
|
56320 == (64512 & t.charCodeAt(v + 1))
|
||||||
|
? ((_ = 65536 + ((1023 & _) << 10) + (1023 & t.charCodeAt(++v))),
|
||||||
|
(g[y++] = (_ >> 18) | 240),
|
||||||
|
(g[y++] = ((_ >> 12) & 63) | 128))
|
||||||
|
: (g[y++] = (_ >> 12) | 224),
|
||||||
|
(g[y++] = ((_ >> 6) & 63) | 128)),
|
||||||
|
(g[y++] = (63 & _) | 128));
|
||||||
|
}
|
||||||
|
for (
|
||||||
|
var b = f,
|
||||||
|
w =
|
||||||
|
""
|
||||||
|
.concat(String.fromCharCode(43))
|
||||||
|
.concat(String.fromCharCode(45))
|
||||||
|
.concat(String.fromCharCode(97)) +
|
||||||
|
""
|
||||||
|
.concat(String.fromCharCode(94))
|
||||||
|
.concat(String.fromCharCode(43))
|
||||||
|
.concat(String.fromCharCode(54)),
|
||||||
|
k =
|
||||||
|
""
|
||||||
|
.concat(String.fromCharCode(43))
|
||||||
|
.concat(String.fromCharCode(45))
|
||||||
|
.concat(String.fromCharCode(51)) +
|
||||||
|
""
|
||||||
|
.concat(String.fromCharCode(94))
|
||||||
|
.concat(String.fromCharCode(43))
|
||||||
|
.concat(String.fromCharCode(98)) +
|
||||||
|
""
|
||||||
|
.concat(String.fromCharCode(43))
|
||||||
|
.concat(String.fromCharCode(45))
|
||||||
|
.concat(String.fromCharCode(102)),
|
||||||
|
x = 0;
|
||||||
|
x < g.length;
|
||||||
|
x++
|
||||||
|
)
|
||||||
|
b = n((b += g[x]), w);
|
||||||
|
return (
|
||||||
|
(b = n(b, k)),
|
||||||
|
(b ^= m) < 0 && (b = 2147483648 + (2147483647 & b)),
|
||||||
|
"".concat((b %= 1e6).toString(), ".").concat(b ^ f)
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
const getToken = async () => {
|
||||||
|
const res = await fetchApi({
|
||||||
|
input: URL_BAIDU_WEB,
|
||||||
|
init: {
|
||||||
|
headers: {
|
||||||
|
"Content-type": "text/html; charset=utf-8",
|
||||||
|
},
|
||||||
|
},
|
||||||
|
});
|
||||||
|
|
||||||
|
if (!res.ok) {
|
||||||
|
throw new Error(res.statusText);
|
||||||
|
}
|
||||||
|
|
||||||
|
const text = await res.text();
|
||||||
|
const token = text.match(/token: '(.*)',/)[1];
|
||||||
|
const gtk = text.match(/gtk = "(.*)";/)[1];
|
||||||
|
const exp = Date.now() + 8 * 60 * 60 * 1000;
|
||||||
|
|
||||||
|
if (!token || !gtk) {
|
||||||
|
throw new Error("[baidu] get token error");
|
||||||
|
}
|
||||||
|
|
||||||
|
return { token, gtk, exp };
|
||||||
|
};
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 闭包缓存token,减少对storage查询
|
||||||
|
* @returns
|
||||||
|
*/
|
||||||
|
const _bdAuth = () => {
|
||||||
|
let store;
|
||||||
|
|
||||||
|
return async () => {
|
||||||
|
const now = Date.now();
|
||||||
|
|
||||||
|
// 查询内存缓存
|
||||||
|
if (store && store.exp > now) {
|
||||||
|
return store;
|
||||||
|
}
|
||||||
|
|
||||||
|
// 查询storage缓存
|
||||||
|
store = await getBdauth();
|
||||||
|
if (store && store.exp > now) {
|
||||||
|
return store;
|
||||||
|
}
|
||||||
|
|
||||||
|
// 缓存没有或失效,查询接口
|
||||||
|
store = await getToken();
|
||||||
|
await setBdauth(store);
|
||||||
|
return store;
|
||||||
|
};
|
||||||
|
};
|
||||||
|
|
||||||
|
const bdAuth = _bdAuth();
|
||||||
|
|
||||||
|
export const genBaidu = async ({ text, from, to }) => {
|
||||||
|
const { token, gtk } = await bdAuth();
|
||||||
|
const sign = getSign(text, gtk);
|
||||||
|
const data = {
|
||||||
|
from,
|
||||||
|
to,
|
||||||
|
query: text,
|
||||||
|
simple_means_flag: 3,
|
||||||
|
sign,
|
||||||
|
token,
|
||||||
|
domain: "common",
|
||||||
|
ts: Date.now(),
|
||||||
|
};
|
||||||
|
|
||||||
|
const input = `${URL_BAIDU_TRAN}?from=${from}&to=${to}`;
|
||||||
|
const init = {
|
||||||
|
headers: {
|
||||||
|
"content-type": "application/x-www-form-urlencoded; charset=UTF-8",
|
||||||
|
},
|
||||||
|
method: "POST",
|
||||||
|
body: queryString.stringify(data),
|
||||||
|
};
|
||||||
|
|
||||||
|
return [input, init];
|
||||||
|
};
|
||||||
58
src/apis/deepl.js
Normal file
58
src/apis/deepl.js
Normal file
@@ -0,0 +1,58 @@
|
|||||||
|
import { URL_DEEPLFREE_TRAN } from "../config";
|
||||||
|
|
||||||
|
let id = 1e4 * Math.round(1e4 * Math.random());
|
||||||
|
|
||||||
|
export const genDeeplFree = ({ text, from, to }) => {
|
||||||
|
const iCount = (text.match(/[i]/g) || []).length + 1;
|
||||||
|
let timestamp = Date.now();
|
||||||
|
timestamp = timestamp + (iCount - (timestamp % iCount));
|
||||||
|
id++;
|
||||||
|
|
||||||
|
let body = JSON.stringify({
|
||||||
|
jsonrpc: "2.0",
|
||||||
|
method: "LMT_handle_texts",
|
||||||
|
params: {
|
||||||
|
splitting: "newlines",
|
||||||
|
lang: {
|
||||||
|
target_lang: to,
|
||||||
|
source_lang_user_selected: from,
|
||||||
|
},
|
||||||
|
commonJobParams: {
|
||||||
|
wasSpoken: false,
|
||||||
|
transcribe_as: "",
|
||||||
|
},
|
||||||
|
id,
|
||||||
|
timestamp,
|
||||||
|
texts: [
|
||||||
|
{
|
||||||
|
text,
|
||||||
|
requestAlternatives: 3,
|
||||||
|
},
|
||||||
|
],
|
||||||
|
},
|
||||||
|
});
|
||||||
|
|
||||||
|
body = body.replace(
|
||||||
|
'method":"',
|
||||||
|
(id + 3) % 13 === 0 || (id + 5) % 29 === 0 ? 'method" : "' : 'method": "'
|
||||||
|
);
|
||||||
|
|
||||||
|
const init = {
|
||||||
|
headers: {
|
||||||
|
"Content-Type": "application/json",
|
||||||
|
Accept: "*/*",
|
||||||
|
"x-app-os-name": "iOS",
|
||||||
|
"x-app-os-version": "16.3.0",
|
||||||
|
"Accept-Language": "en-US,en;q=0.9",
|
||||||
|
"Accept-Encoding": "gzip, deflate, br",
|
||||||
|
"x-app-device": "iPhone13,2",
|
||||||
|
"User-Agent": "DeepL-iOS/2.9.1 iOS 16.3.0 (iPhone13,2)",
|
||||||
|
"x-app-build": "510265",
|
||||||
|
"x-app-version": "2.9.1",
|
||||||
|
},
|
||||||
|
method: "POST",
|
||||||
|
body,
|
||||||
|
};
|
||||||
|
|
||||||
|
return [URL_DEEPLFREE_TRAN, init];
|
||||||
|
};
|
||||||
@@ -4,16 +4,20 @@ import {
|
|||||||
OPT_TRANS_GOOGLE,
|
OPT_TRANS_GOOGLE,
|
||||||
OPT_TRANS_MICROSOFT,
|
OPT_TRANS_MICROSOFT,
|
||||||
OPT_TRANS_DEEPL,
|
OPT_TRANS_DEEPL,
|
||||||
|
OPT_TRANS_DEEPLFREE,
|
||||||
|
OPT_TRANS_DEEPLX,
|
||||||
|
OPT_TRANS_BAIDU,
|
||||||
|
OPT_TRANS_TENCENT,
|
||||||
OPT_TRANS_OPENAI,
|
OPT_TRANS_OPENAI,
|
||||||
OPT_TRANS_CUSTOMIZE,
|
OPT_TRANS_CUSTOMIZE,
|
||||||
OPT_LANGS_SPECIAL,
|
URL_CACHE_TRAN,
|
||||||
PROMPT_PLACE_FROM,
|
|
||||||
PROMPT_PLACE_TO,
|
|
||||||
KV_SALT_SYNC,
|
KV_SALT_SYNC,
|
||||||
URL_BAIDU_LANGDETECT,
|
URL_BAIDU_LANGDETECT,
|
||||||
OPT_LANGS_BAIDU,
|
OPT_LANGS_BAIDU,
|
||||||
|
URL_TENCENT_TRANSMART,
|
||||||
|
OPT_LANGS_TENCENT,
|
||||||
|
OPT_LANGS_SPECIAL,
|
||||||
} from "../config";
|
} from "../config";
|
||||||
import { tryDetectLang } from "../libs";
|
|
||||||
import { sha256 } from "../libs/utils";
|
import { sha256 } from "../libs/utils";
|
||||||
|
|
||||||
/**
|
/**
|
||||||
@@ -40,205 +44,6 @@ export const apiSyncData = async (url, key, data) =>
|
|||||||
*/
|
*/
|
||||||
export const apiFetch = (url) => fetchPolyfill(url);
|
export const apiFetch = (url) => fetchPolyfill(url);
|
||||||
|
|
||||||
/**
|
|
||||||
* 谷歌翻译
|
|
||||||
* @param {*} text
|
|
||||||
* @param {*} to
|
|
||||||
* @param {*} from
|
|
||||||
* @returns
|
|
||||||
*/
|
|
||||||
const apiGoogleTranslate = async (
|
|
||||||
translator,
|
|
||||||
text,
|
|
||||||
to,
|
|
||||||
from,
|
|
||||||
{ url, key, useCache = true }
|
|
||||||
) => {
|
|
||||||
const params = {
|
|
||||||
client: "gtx",
|
|
||||||
dt: "t",
|
|
||||||
dj: 1,
|
|
||||||
ie: "UTF-8",
|
|
||||||
sl: from,
|
|
||||||
tl: to,
|
|
||||||
q: text,
|
|
||||||
};
|
|
||||||
const input = `${url}?${queryString.stringify(params)}`;
|
|
||||||
const res = await fetchPolyfill(input, {
|
|
||||||
headers: {
|
|
||||||
"Content-type": "application/json",
|
|
||||||
},
|
|
||||||
useCache,
|
|
||||||
usePool: true,
|
|
||||||
translator,
|
|
||||||
token: key,
|
|
||||||
});
|
|
||||||
const trText = res.sentences.map((item) => item.trans).join(" ");
|
|
||||||
const isSame = to === res.src;
|
|
||||||
|
|
||||||
return [trText, isSame];
|
|
||||||
};
|
|
||||||
|
|
||||||
/**
|
|
||||||
* 微软翻译
|
|
||||||
* @param {*} text
|
|
||||||
* @param {*} to
|
|
||||||
* @param {*} from
|
|
||||||
* @returns
|
|
||||||
*/
|
|
||||||
const apiMicrosoftTranslate = async (
|
|
||||||
translator,
|
|
||||||
text,
|
|
||||||
to,
|
|
||||||
from,
|
|
||||||
{ url, useCache = true }
|
|
||||||
) => {
|
|
||||||
const params = {
|
|
||||||
from,
|
|
||||||
to,
|
|
||||||
"api-version": "3.0",
|
|
||||||
};
|
|
||||||
const input = `${url}?${queryString.stringify(params)}`;
|
|
||||||
const res = await fetchPolyfill(input, {
|
|
||||||
headers: {
|
|
||||||
"Content-type": "application/json",
|
|
||||||
},
|
|
||||||
method: "POST",
|
|
||||||
body: JSON.stringify([{ Text: text }]),
|
|
||||||
useCache,
|
|
||||||
usePool: true,
|
|
||||||
translator,
|
|
||||||
});
|
|
||||||
const trText = res[0].translations[0].text;
|
|
||||||
const isSame = to === res[0].detectedLanguage?.language;
|
|
||||||
|
|
||||||
return [trText, isSame];
|
|
||||||
};
|
|
||||||
|
|
||||||
/**
|
|
||||||
* DeepL翻译
|
|
||||||
* @param {*} text
|
|
||||||
* @param {*} to
|
|
||||||
* @param {*} from
|
|
||||||
* @returns
|
|
||||||
*/
|
|
||||||
const apiDeepLTranslate = async (
|
|
||||||
translator,
|
|
||||||
text,
|
|
||||||
to,
|
|
||||||
from,
|
|
||||||
{ url, key, useCache = true }
|
|
||||||
) => {
|
|
||||||
const data = {
|
|
||||||
text: [text],
|
|
||||||
target_lang: to,
|
|
||||||
split_sentences: "0",
|
|
||||||
};
|
|
||||||
if (from) {
|
|
||||||
data.source_lang = from;
|
|
||||||
}
|
|
||||||
const res = await fetchPolyfill(url, {
|
|
||||||
headers: {
|
|
||||||
"Content-type": "application/json",
|
|
||||||
},
|
|
||||||
method: "POST",
|
|
||||||
body: JSON.stringify(data),
|
|
||||||
useCache,
|
|
||||||
usePool: true,
|
|
||||||
translator,
|
|
||||||
token: key,
|
|
||||||
});
|
|
||||||
const trText = res.translations.map((item) => item.text).join(" ");
|
|
||||||
const isSame = to === res.translations[0].detected_source_language;
|
|
||||||
|
|
||||||
return [trText, isSame];
|
|
||||||
};
|
|
||||||
|
|
||||||
/**
|
|
||||||
* OpenAI 翻译
|
|
||||||
* @param {*} text
|
|
||||||
* @param {*} to
|
|
||||||
* @param {*} from
|
|
||||||
* @returns
|
|
||||||
*/
|
|
||||||
const apiOpenaiTranslate = async (
|
|
||||||
translator,
|
|
||||||
text,
|
|
||||||
to,
|
|
||||||
from,
|
|
||||||
{ url, key, model, prompt, useCache = true }
|
|
||||||
) => {
|
|
||||||
prompt = prompt
|
|
||||||
.replaceAll(PROMPT_PLACE_FROM, from)
|
|
||||||
.replaceAll(PROMPT_PLACE_TO, to);
|
|
||||||
const res = await fetchPolyfill(url, {
|
|
||||||
headers: {
|
|
||||||
"Content-type": "application/json",
|
|
||||||
},
|
|
||||||
method: "POST",
|
|
||||||
body: JSON.stringify({
|
|
||||||
model: model,
|
|
||||||
messages: [
|
|
||||||
{
|
|
||||||
role: "system",
|
|
||||||
content: prompt,
|
|
||||||
},
|
|
||||||
{
|
|
||||||
role: "user",
|
|
||||||
content: text,
|
|
||||||
},
|
|
||||||
],
|
|
||||||
temperature: 0,
|
|
||||||
max_tokens: 256,
|
|
||||||
}),
|
|
||||||
useCache,
|
|
||||||
usePool: true,
|
|
||||||
translator,
|
|
||||||
token: key,
|
|
||||||
});
|
|
||||||
const trText = res?.choices?.[0].message.content;
|
|
||||||
const sLang = await tryDetectLang(text);
|
|
||||||
const tLang = await tryDetectLang(trText);
|
|
||||||
const isSame = text === trText || (sLang && tLang && sLang === tLang);
|
|
||||||
|
|
||||||
return [trText, isSame];
|
|
||||||
};
|
|
||||||
|
|
||||||
/**
|
|
||||||
* 自定义接口 翻译
|
|
||||||
* @param {*} text
|
|
||||||
* @param {*} to
|
|
||||||
* @param {*} from
|
|
||||||
* @returns
|
|
||||||
*/
|
|
||||||
const apiCustomTranslate = async (
|
|
||||||
translator,
|
|
||||||
text,
|
|
||||||
to,
|
|
||||||
from,
|
|
||||||
{ url, key, useCache = true }
|
|
||||||
) => {
|
|
||||||
const res = await fetchPolyfill(url, {
|
|
||||||
headers: {
|
|
||||||
"Content-type": "application/json",
|
|
||||||
},
|
|
||||||
method: "POST",
|
|
||||||
body: JSON.stringify({
|
|
||||||
text,
|
|
||||||
from,
|
|
||||||
to,
|
|
||||||
}),
|
|
||||||
useCache,
|
|
||||||
usePool: true,
|
|
||||||
translator,
|
|
||||||
token: key,
|
|
||||||
});
|
|
||||||
const trText = res.text;
|
|
||||||
const isSame = to === res.from;
|
|
||||||
|
|
||||||
return [trText, isSame];
|
|
||||||
};
|
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* 百度语言识别
|
* 百度语言识别
|
||||||
* @param {*} text
|
* @param {*} text
|
||||||
@@ -263,39 +68,121 @@ export const apiBaiduLangdetect = async (text) => {
|
|||||||
return "";
|
return "";
|
||||||
};
|
};
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 腾讯语言识别
|
||||||
|
* @param {*} text
|
||||||
|
* @returns
|
||||||
|
*/
|
||||||
|
export const apiTencentLangdetect = async (text) => {
|
||||||
|
const body = JSON.stringify({
|
||||||
|
header: {
|
||||||
|
fn: "text_analysis",
|
||||||
|
},
|
||||||
|
text,
|
||||||
|
});
|
||||||
|
|
||||||
|
const res = await fetchPolyfill(URL_TENCENT_TRANSMART, {
|
||||||
|
headers: {
|
||||||
|
"Content-type": "application/json",
|
||||||
|
},
|
||||||
|
method: "POST",
|
||||||
|
body,
|
||||||
|
useCache: true,
|
||||||
|
});
|
||||||
|
|
||||||
|
return OPT_LANGS_TENCENT.get(res.language) ?? res.language;
|
||||||
|
};
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* 统一翻译接口
|
* 统一翻译接口
|
||||||
* @param {*} param0
|
* @param {*} param0
|
||||||
* @returns
|
* @returns
|
||||||
*/
|
*/
|
||||||
export const apiTranslate = ({
|
export const apiTranslate = async ({
|
||||||
translator,
|
translator,
|
||||||
text,
|
text,
|
||||||
fromLang,
|
fromLang,
|
||||||
toLang,
|
toLang,
|
||||||
apiSetting,
|
apiSetting = {},
|
||||||
|
useCache = true,
|
||||||
|
usePool = true,
|
||||||
}) => {
|
}) => {
|
||||||
const from = OPT_LANGS_SPECIAL[translator].get(fromLang);
|
let trText = "";
|
||||||
const to = OPT_LANGS_SPECIAL[translator].get(toLang);
|
let isSame = false;
|
||||||
|
|
||||||
if (!to) {
|
const from =
|
||||||
return ["", from === to];
|
OPT_LANGS_SPECIAL[translator].get(fromLang) ??
|
||||||
|
OPT_LANGS_SPECIAL[translator].get("auto");
|
||||||
|
const to = OPT_LANGS_SPECIAL[translator].get(toLang);
|
||||||
|
if (!text || !to) {
|
||||||
|
console.log(`[trans] target lang: ${toLang} not support`);
|
||||||
|
return [trText, isSame];
|
||||||
}
|
}
|
||||||
|
|
||||||
const callApi = (api) => api(translator, text, to, from, apiSetting);
|
const cacheOpts = {
|
||||||
|
translator,
|
||||||
|
text,
|
||||||
|
fromLang,
|
||||||
|
toLang,
|
||||||
|
};
|
||||||
|
|
||||||
|
const transOpts = {
|
||||||
|
translator,
|
||||||
|
text,
|
||||||
|
from,
|
||||||
|
to,
|
||||||
|
};
|
||||||
|
|
||||||
|
const res = await fetchPolyfill(
|
||||||
|
`${URL_CACHE_TRAN}?${queryString.stringify(cacheOpts)}`,
|
||||||
|
{
|
||||||
|
useCache,
|
||||||
|
usePool,
|
||||||
|
transOpts,
|
||||||
|
apiSetting,
|
||||||
|
}
|
||||||
|
);
|
||||||
|
|
||||||
switch (translator) {
|
switch (translator) {
|
||||||
case OPT_TRANS_GOOGLE:
|
case OPT_TRANS_GOOGLE:
|
||||||
return callApi(apiGoogleTranslate);
|
trText = res.sentences.map((item) => item.trans).join(" ");
|
||||||
|
isSame = to === res.src;
|
||||||
|
break;
|
||||||
case OPT_TRANS_MICROSOFT:
|
case OPT_TRANS_MICROSOFT:
|
||||||
return callApi(apiMicrosoftTranslate);
|
trText = res[0].translations.map((item) => item.text).join(" ");
|
||||||
|
isSame = text === trText;
|
||||||
|
break;
|
||||||
case OPT_TRANS_DEEPL:
|
case OPT_TRANS_DEEPL:
|
||||||
return callApi(apiDeepLTranslate);
|
trText = res.translations.map((item) => item.text).join(" ");
|
||||||
|
isSame = to === res.translations[0].detected_source_language;
|
||||||
|
break;
|
||||||
|
case OPT_TRANS_DEEPLFREE:
|
||||||
|
trText = res.result?.texts.map((item) => item.text).join(" ");
|
||||||
|
isSame = to === res.result?.lang;
|
||||||
|
break;
|
||||||
|
case OPT_TRANS_DEEPLX:
|
||||||
|
trText = res.data;
|
||||||
|
isSame = to === res.source_lang;
|
||||||
|
break;
|
||||||
|
case OPT_TRANS_BAIDU:
|
||||||
|
trText = res.trans_result?.data.map((item) => item.dst).join(" ");
|
||||||
|
isSame = res.trans_result?.to === res.trans_result?.from;
|
||||||
|
break;
|
||||||
|
case OPT_TRANS_TENCENT:
|
||||||
|
trText = res.auto_translation;
|
||||||
|
isSame = text === trText;
|
||||||
|
break;
|
||||||
case OPT_TRANS_OPENAI:
|
case OPT_TRANS_OPENAI:
|
||||||
return callApi(apiOpenaiTranslate);
|
trText = res?.choices?.[0].message.content;
|
||||||
|
isSame = text === trText;
|
||||||
|
break;
|
||||||
case OPT_TRANS_CUSTOMIZE:
|
case OPT_TRANS_CUSTOMIZE:
|
||||||
return callApi(apiCustomTranslate);
|
trText = res.text;
|
||||||
|
isSame = to === res.from;
|
||||||
|
break;
|
||||||
default:
|
default:
|
||||||
return ["", false];
|
break;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
return [trText, isSame, res];
|
||||||
};
|
};
|
||||||
|
|||||||
129
src/common.js
Normal file
129
src/common.js
Normal file
@@ -0,0 +1,129 @@
|
|||||||
|
import React from "react";
|
||||||
|
import ReactDOM from "react-dom/client";
|
||||||
|
import Action from "./views/Action";
|
||||||
|
import createCache from "@emotion/cache";
|
||||||
|
import { CacheProvider } from "@emotion/react";
|
||||||
|
import {
|
||||||
|
MSG_TRANS_TOGGLE,
|
||||||
|
MSG_TRANS_TOGGLE_STYLE,
|
||||||
|
MSG_TRANS_GETRULE,
|
||||||
|
MSG_TRANS_PUTRULE,
|
||||||
|
APP_LCNAME,
|
||||||
|
DEFAULT_TRANBOX_SETTING,
|
||||||
|
} from "./config";
|
||||||
|
import { getRulesWithDefault, getFabWithDefault } from "./libs/storage";
|
||||||
|
import { Translator } from "./libs/translator";
|
||||||
|
import { sendIframeMsg, sendParentMsg } from "./libs/iframe";
|
||||||
|
import { matchRule } from "./libs/rules";
|
||||||
|
import Slection from "./views/Selection";
|
||||||
|
|
||||||
|
export async function runTranslator(setting) {
|
||||||
|
const href = document.location.href;
|
||||||
|
const rules = await getRulesWithDefault();
|
||||||
|
const rule = await matchRule(rules, href, setting);
|
||||||
|
const translator = new Translator(rule, setting);
|
||||||
|
|
||||||
|
return { translator, rule };
|
||||||
|
}
|
||||||
|
|
||||||
|
export function runIframe(setting) {
|
||||||
|
let translator;
|
||||||
|
window.addEventListener("message", (e) => {
|
||||||
|
const { action, args } = e.data || {};
|
||||||
|
switch (action) {
|
||||||
|
case MSG_TRANS_TOGGLE:
|
||||||
|
translator?.toggle();
|
||||||
|
break;
|
||||||
|
case MSG_TRANS_TOGGLE_STYLE:
|
||||||
|
translator?.toggleStyle();
|
||||||
|
break;
|
||||||
|
case MSG_TRANS_PUTRULE:
|
||||||
|
if (!translator) {
|
||||||
|
translator = new Translator(args, setting);
|
||||||
|
} else {
|
||||||
|
translator.updateRule(args || {});
|
||||||
|
}
|
||||||
|
break;
|
||||||
|
default:
|
||||||
|
}
|
||||||
|
});
|
||||||
|
sendParentMsg(MSG_TRANS_GETRULE);
|
||||||
|
}
|
||||||
|
|
||||||
|
export async function showFab(translator) {
|
||||||
|
const fab = await getFabWithDefault();
|
||||||
|
if (fab.isHide) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
const $action = document.createElement("div");
|
||||||
|
$action.setAttribute("id", APP_LCNAME);
|
||||||
|
document.body.parentElement.appendChild($action);
|
||||||
|
const shadowContainer = $action.attachShadow({ mode: "closed" });
|
||||||
|
const emotionRoot = document.createElement("style");
|
||||||
|
const shadowRootElement = document.createElement("div");
|
||||||
|
shadowContainer.appendChild(emotionRoot);
|
||||||
|
shadowContainer.appendChild(shadowRootElement);
|
||||||
|
const cache = createCache({
|
||||||
|
key: APP_LCNAME,
|
||||||
|
prepend: true,
|
||||||
|
container: emotionRoot,
|
||||||
|
});
|
||||||
|
ReactDOM.createRoot(shadowRootElement).render(
|
||||||
|
<React.StrictMode>
|
||||||
|
<CacheProvider value={cache}>
|
||||||
|
<Action translator={translator} fab={fab} />
|
||||||
|
</CacheProvider>
|
||||||
|
</React.StrictMode>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
export function showTransbox({
|
||||||
|
tranboxSetting = DEFAULT_TRANBOX_SETTING,
|
||||||
|
transApis,
|
||||||
|
}) {
|
||||||
|
if (!tranboxSetting?.transOpen) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
const $tranbox = document.createElement("div");
|
||||||
|
$tranbox.setAttribute("id", "kiss-transbox");
|
||||||
|
document.body.parentElement.appendChild($tranbox);
|
||||||
|
const shadowContainer = $tranbox.attachShadow({ mode: "closed" });
|
||||||
|
const emotionRoot = document.createElement("style");
|
||||||
|
const shadowRootElement = document.createElement("div");
|
||||||
|
shadowContainer.appendChild(emotionRoot);
|
||||||
|
shadowContainer.appendChild(shadowRootElement);
|
||||||
|
const cache = createCache({
|
||||||
|
key: "kiss-transbox",
|
||||||
|
prepend: true,
|
||||||
|
container: emotionRoot,
|
||||||
|
});
|
||||||
|
ReactDOM.createRoot(shadowRootElement).render(
|
||||||
|
<React.StrictMode>
|
||||||
|
<CacheProvider value={cache}>
|
||||||
|
<Slection tranboxSetting={tranboxSetting} transApis={transApis} />
|
||||||
|
</CacheProvider>
|
||||||
|
</React.StrictMode>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
export function windowListener(rule) {
|
||||||
|
window.addEventListener("message", (e) => {
|
||||||
|
const { action } = e.data || {};
|
||||||
|
switch (action) {
|
||||||
|
case MSG_TRANS_GETRULE:
|
||||||
|
sendIframeMsg(MSG_TRANS_PUTRULE, rule);
|
||||||
|
break;
|
||||||
|
default:
|
||||||
|
}
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
export function showErr(err) {
|
||||||
|
console.error("[KISS-Translator]", err);
|
||||||
|
const $err = document.createElement("div");
|
||||||
|
$err.innerText = `KISS-Translator: ${err.message}`;
|
||||||
|
$err.style.cssText = "background:red; color:#fff;";
|
||||||
|
document.body.prepend($err);
|
||||||
|
}
|
||||||
@@ -611,4 +611,32 @@ export const I18N = {
|
|||||||
zh: `启用`,
|
zh: `启用`,
|
||||||
en: `Enable`,
|
en: `Enable`,
|
||||||
},
|
},
|
||||||
|
selection_translate: {
|
||||||
|
zh: `划词翻译`,
|
||||||
|
en: `Selection Translate`,
|
||||||
|
},
|
||||||
|
toggle_selection_translate: {
|
||||||
|
zh: `启用划词翻译`,
|
||||||
|
en: `Use Selection Translate`,
|
||||||
|
},
|
||||||
|
trigger_tranbox_shortcut: {
|
||||||
|
zh: `显示翻译框快捷键`,
|
||||||
|
en: `Toggle Translate Box Shortcut`,
|
||||||
|
},
|
||||||
|
tranbtn_offset_x: {
|
||||||
|
zh: `翻译按钮偏移X(0-100)`,
|
||||||
|
en: `Translate Button Offset X (0-100)`,
|
||||||
|
},
|
||||||
|
tranbtn_offset_y: {
|
||||||
|
zh: `翻译按钮偏移Y(0-100)`,
|
||||||
|
en: `Translate Button Offset Y (0-100)`,
|
||||||
|
},
|
||||||
|
translated_text: {
|
||||||
|
zh: `译文`,
|
||||||
|
en: `Translated Text`,
|
||||||
|
},
|
||||||
|
original_text: {
|
||||||
|
zh: `原文`,
|
||||||
|
en: `Original Text`,
|
||||||
|
},
|
||||||
};
|
};
|
||||||
|
|||||||
@@ -20,6 +20,7 @@ export {
|
|||||||
};
|
};
|
||||||
|
|
||||||
export const STOKEY_MSAUTH = `${APP_NAME}_msauth`;
|
export const STOKEY_MSAUTH = `${APP_NAME}_msauth`;
|
||||||
|
export const STOKEY_BDAUTH = `${APP_NAME}_bdauth`;
|
||||||
export const STOKEY_SETTING = `${APP_NAME}_setting`;
|
export const STOKEY_SETTING = `${APP_NAME}_setting`;
|
||||||
export const STOKEY_RULES = `${APP_NAME}_rules`;
|
export const STOKEY_RULES = `${APP_NAME}_rules`;
|
||||||
export const STOKEY_SYNC = `${APP_NAME}_sync`;
|
export const STOKEY_SYNC = `${APP_NAME}_sync`;
|
||||||
@@ -67,19 +68,34 @@ export const URL_KISS_RULES_NEW_ISSUE =
|
|||||||
"https://github.com/fishjar/kiss-rules/issues/new";
|
"https://github.com/fishjar/kiss-rules/issues/new";
|
||||||
export const URL_RAW_PREFIX =
|
export const URL_RAW_PREFIX =
|
||||||
"https://raw.githubusercontent.com/fishjar/kiss-translator/master";
|
"https://raw.githubusercontent.com/fishjar/kiss-translator/master";
|
||||||
|
|
||||||
|
export const URL_CACHE_TRAN = `https://${APP_LCNAME}/translate`;
|
||||||
|
export const URL_MICROSOFT_TRAN =
|
||||||
|
"https://api-edge.cognitive.microsofttranslator.com/translate";
|
||||||
export const URL_MICROSOFT_AUTH = "https://edge.microsoft.com/translate/auth";
|
export const URL_MICROSOFT_AUTH = "https://edge.microsoft.com/translate/auth";
|
||||||
export const URL_BAIDU_LANGDETECT = "https://fanyi.baidu.com/langdetect";
|
export const URL_BAIDU_LANGDETECT = "https://fanyi.baidu.com/langdetect";
|
||||||
|
export const URL_BAIDU_WEB = "https://fanyi.baidu.com/";
|
||||||
|
export const URL_BAIDU_TRAN = "https://fanyi.baidu.com/v2transapi";
|
||||||
|
export const URL_DEEPLFREE_TRAN = "https://www2.deepl.com/jsonrpc";
|
||||||
|
export const URL_TENCENT_TRANSMART = "https://transmart.qq.com/api/imt";
|
||||||
|
|
||||||
export const OPT_TRANS_GOOGLE = "Google";
|
export const OPT_TRANS_GOOGLE = "Google";
|
||||||
export const OPT_TRANS_MICROSOFT = "Microsoft";
|
export const OPT_TRANS_MICROSOFT = "Microsoft";
|
||||||
export const OPT_TRANS_DEEPL = "DeepL";
|
export const OPT_TRANS_DEEPL = "DeepL";
|
||||||
|
export const OPT_TRANS_DEEPLX = "DeepLX";
|
||||||
|
export const OPT_TRANS_DEEPLFREE = "DeepLFree";
|
||||||
export const OPT_TRANS_BAIDU = "Baidu";
|
export const OPT_TRANS_BAIDU = "Baidu";
|
||||||
|
export const OPT_TRANS_TENCENT = "Tencent";
|
||||||
export const OPT_TRANS_OPENAI = "OpenAI";
|
export const OPT_TRANS_OPENAI = "OpenAI";
|
||||||
export const OPT_TRANS_CUSTOMIZE = "Custom";
|
export const OPT_TRANS_CUSTOMIZE = "Custom";
|
||||||
export const OPT_TRANS_ALL = [
|
export const OPT_TRANS_ALL = [
|
||||||
OPT_TRANS_GOOGLE,
|
OPT_TRANS_GOOGLE,
|
||||||
OPT_TRANS_MICROSOFT,
|
OPT_TRANS_MICROSOFT,
|
||||||
OPT_TRANS_DEEPL,
|
OPT_TRANS_DEEPL,
|
||||||
|
OPT_TRANS_DEEPLFREE,
|
||||||
|
OPT_TRANS_DEEPLX,
|
||||||
|
OPT_TRANS_BAIDU,
|
||||||
|
OPT_TRANS_TENCENT,
|
||||||
OPT_TRANS_OPENAI,
|
OPT_TRANS_OPENAI,
|
||||||
OPT_TRANS_CUSTOMIZE,
|
OPT_TRANS_CUSTOMIZE,
|
||||||
];
|
];
|
||||||
@@ -138,6 +154,18 @@ export const OPT_LANGS_SPECIAL = {
|
|||||||
["zh-CN", "ZH"],
|
["zh-CN", "ZH"],
|
||||||
["zh-TW", "ZH"],
|
["zh-TW", "ZH"],
|
||||||
]),
|
]),
|
||||||
|
[OPT_TRANS_DEEPLFREE]: new Map([
|
||||||
|
...OPT_LANGS_FROM.map(([key]) => [key, key.toUpperCase()]),
|
||||||
|
["auto", "auto"],
|
||||||
|
["zh-CN", "ZH"],
|
||||||
|
["zh-TW", "ZH"],
|
||||||
|
]),
|
||||||
|
[OPT_TRANS_DEEPLX]: new Map([
|
||||||
|
...OPT_LANGS_FROM.map(([key]) => [key, key.toUpperCase()]),
|
||||||
|
["auto", ""],
|
||||||
|
["zh-CN", "ZH"],
|
||||||
|
["zh-TW", "ZH"],
|
||||||
|
]),
|
||||||
[OPT_TRANS_BAIDU]: new Map([
|
[OPT_TRANS_BAIDU]: new Map([
|
||||||
...OPT_LANGS_FROM.map(([key]) => [key, key]),
|
...OPT_LANGS_FROM.map(([key]) => [key, key]),
|
||||||
["zh-CN", "zh"],
|
["zh-CN", "zh"],
|
||||||
@@ -165,6 +193,28 @@ export const OPT_LANGS_SPECIAL = {
|
|||||||
["uk", "ukr"],
|
["uk", "ukr"],
|
||||||
["vi", "vie"],
|
["vi", "vie"],
|
||||||
]),
|
]),
|
||||||
|
[OPT_TRANS_TENCENT]: new Map([
|
||||||
|
["auto", "auto"],
|
||||||
|
["zh-CN", "zh"],
|
||||||
|
["zh-TW", "zh"],
|
||||||
|
["en", "en"],
|
||||||
|
["ar", "ar"],
|
||||||
|
["de", "de"],
|
||||||
|
["ru", "ru"],
|
||||||
|
["fr", "fr"],
|
||||||
|
["fi", "fil"],
|
||||||
|
["ko", "ko"],
|
||||||
|
["ms", "ms"],
|
||||||
|
["pt", "pt"],
|
||||||
|
["ja", "ja"],
|
||||||
|
["th", "th"],
|
||||||
|
["tr", "tr"],
|
||||||
|
["es", "es"],
|
||||||
|
["it", "it"],
|
||||||
|
["hi", "hi"],
|
||||||
|
["id", "id"],
|
||||||
|
["vi", "vi"],
|
||||||
|
]),
|
||||||
[OPT_TRANS_OPENAI]: new Map(
|
[OPT_TRANS_OPENAI]: new Map(
|
||||||
OPT_LANGS_FROM.map(([key, val]) => [key, val.split(" - ")[0]])
|
OPT_LANGS_FROM.map(([key, val]) => [key, val.split(" - ")[0]])
|
||||||
),
|
),
|
||||||
@@ -180,6 +230,13 @@ export const OPT_LANGS_BAIDU = new Map(
|
|||||||
k,
|
k,
|
||||||
])
|
])
|
||||||
);
|
);
|
||||||
|
export const OPT_LANGS_TENCENT = new Map(
|
||||||
|
Array.from(OPT_LANGS_SPECIAL[OPT_TRANS_TENCENT].entries()).map(([k, v]) => [
|
||||||
|
v,
|
||||||
|
k,
|
||||||
|
])
|
||||||
|
);
|
||||||
|
OPT_LANGS_TENCENT.set("zh", "zh-CN");
|
||||||
|
|
||||||
export const OPT_STYLE_NONE = "style_none"; // 无
|
export const OPT_STYLE_NONE = "style_none"; // 无
|
||||||
export const OPT_STYLE_LINE = "under_line"; // 下划线
|
export const OPT_STYLE_LINE = "under_line"; // 下划线
|
||||||
@@ -255,6 +312,18 @@ export const DEFAULT_INPUT_RULE = {
|
|||||||
transSign: OPT_INPUT_TRANS_SIGNS[0],
|
transSign: OPT_INPUT_TRANS_SIGNS[0],
|
||||||
};
|
};
|
||||||
|
|
||||||
|
// 划词翻译
|
||||||
|
export const DEFAULT_TRANBOX_SHORTCUT = ["AltLeft", "KeyB"];
|
||||||
|
export const DEFAULT_TRANBOX_SETTING = {
|
||||||
|
transOpen: true,
|
||||||
|
translator: OPT_TRANS_MICROSOFT,
|
||||||
|
fromLang: "auto",
|
||||||
|
toLang: "zh-CN",
|
||||||
|
tranboxShortcut: DEFAULT_TRANBOX_SHORTCUT,
|
||||||
|
btnOffsetX: 10,
|
||||||
|
btnOffsetY: 10,
|
||||||
|
};
|
||||||
|
|
||||||
// 订阅列表
|
// 订阅列表
|
||||||
export const DEFAULT_SUBRULES_LIST = [
|
export const DEFAULT_SUBRULES_LIST = [
|
||||||
{
|
{
|
||||||
@@ -277,14 +346,14 @@ export const DEFAULT_TRANS_APIS = {
|
|||||||
url: "https://translate.googleapis.com/translate_a/single",
|
url: "https://translate.googleapis.com/translate_a/single",
|
||||||
key: "",
|
key: "",
|
||||||
},
|
},
|
||||||
[OPT_TRANS_MICROSOFT]: {
|
|
||||||
url: "https://api-edge.cognitive.microsofttranslator.com/translate",
|
|
||||||
authUrl: "https://edge.microsoft.com/translate/auth",
|
|
||||||
},
|
|
||||||
[OPT_TRANS_DEEPL]: {
|
[OPT_TRANS_DEEPL]: {
|
||||||
url: "https://api-free.deepl.com/v2/translate",
|
url: "https://api-free.deepl.com/v2/translate",
|
||||||
key: "",
|
key: "",
|
||||||
},
|
},
|
||||||
|
[OPT_TRANS_DEEPLX]: {
|
||||||
|
url: "http://localhost:1188/translate",
|
||||||
|
key: "",
|
||||||
|
},
|
||||||
[OPT_TRANS_OPENAI]: {
|
[OPT_TRANS_OPENAI]: {
|
||||||
url: "https://api.openai.com/v1/chat/completions",
|
url: "https://api.openai.com/v1/chat/completions",
|
||||||
key: "",
|
key: "",
|
||||||
@@ -331,6 +400,7 @@ export const DEFAULT_SETTING = {
|
|||||||
mouseKey: OPT_MOUSEKEY_DISABLE, // 鼠标悬停翻译
|
mouseKey: OPT_MOUSEKEY_DISABLE, // 鼠标悬停翻译
|
||||||
shortcuts: DEFAULT_SHORTCUTS, // 快捷键
|
shortcuts: DEFAULT_SHORTCUTS, // 快捷键
|
||||||
inputRule: DEFAULT_INPUT_RULE, // 输入框设置
|
inputRule: DEFAULT_INPUT_RULE, // 输入框设置
|
||||||
|
tranboxSetting: DEFAULT_TRANBOX_SETTING, // 划词翻译设置
|
||||||
};
|
};
|
||||||
|
|
||||||
export const DEFAULT_RULES = [GLOBLA_RULE];
|
export const DEFAULT_RULES = [GLOBLA_RULE];
|
||||||
|
|||||||
131
src/content.js
131
src/content.js
@@ -1,64 +1,23 @@
|
|||||||
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,
|
||||||
APP_LCNAME,
|
|
||||||
} from "./config";
|
} from "./config";
|
||||||
|
import { getSettingWithDefault } from "./libs/storage";
|
||||||
|
import { isIframe, sendIframeMsg } from "./libs/iframe";
|
||||||
|
import { runWebfix } from "./libs/webfix";
|
||||||
import {
|
import {
|
||||||
getSettingWithDefault,
|
runIframe,
|
||||||
getRulesWithDefault,
|
runTranslator,
|
||||||
getFabWithDefault,
|
showFab,
|
||||||
} from "./libs/storage";
|
showTransbox,
|
||||||
import { Translator } from "./libs/translator";
|
windowListener,
|
||||||
import { isIframe, sendIframeMsg, sendParentMsg } from "./libs/iframe";
|
showErr,
|
||||||
import { matchRule } from "./libs/rules";
|
} from "./common";
|
||||||
import { webfix } from "./libs/webfix";
|
|
||||||
|
|
||||||
/**
|
function runtimeListener(translator) {
|
||||||
* 入口函数
|
|
||||||
*/
|
|
||||||
const init = async () => {
|
|
||||||
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:
|
|
||||||
}
|
|
||||||
});
|
|
||||||
sendParentMsg(MSG_TRANS_GETRULE);
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
|
|
||||||
const href = document.location.href;
|
|
||||||
const rules = await getRulesWithDefault();
|
|
||||||
const rule = await matchRule(rules, href, setting);
|
|
||||||
const translator = new Translator(rule, setting);
|
|
||||||
webfix(href, setting);
|
|
||||||
|
|
||||||
// 监听消息
|
|
||||||
browser?.runtime.onMessage.addListener(async ({ action, args }) => {
|
browser?.runtime.onMessage.addListener(async ({ action, args }) => {
|
||||||
switch (action) {
|
switch (action) {
|
||||||
case MSG_TRANS_TOGGLE:
|
case MSG_TRANS_TOGGLE:
|
||||||
@@ -80,50 +39,38 @@ const init = async () => {
|
|||||||
}
|
}
|
||||||
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", APP_LCNAME);
|
|
||||||
document.body.parentElement.appendChild($action);
|
|
||||||
const shadowContainer = $action.attachShadow({ mode: "closed" });
|
|
||||||
const emotionRoot = document.createElement("style");
|
|
||||||
const shadowRootElement = document.createElement("div");
|
|
||||||
shadowContainer.appendChild(emotionRoot);
|
|
||||||
shadowContainer.appendChild(shadowRootElement);
|
|
||||||
const cache = createCache({
|
|
||||||
key: APP_LCNAME,
|
|
||||||
prepend: true,
|
|
||||||
container: emotionRoot,
|
|
||||||
});
|
|
||||||
ReactDOM.createRoot(shadowRootElement).render(
|
|
||||||
<React.StrictMode>
|
|
||||||
<CacheProvider value={cache}>
|
|
||||||
<Action translator={translator} fab={fab} />
|
|
||||||
</CacheProvider>
|
|
||||||
</React.StrictMode>
|
|
||||||
);
|
|
||||||
}
|
|
||||||
};
|
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 入口函数
|
||||||
|
*/
|
||||||
(async () => {
|
(async () => {
|
||||||
try {
|
try {
|
||||||
await init();
|
// 读取设置信息
|
||||||
|
const setting = await getSettingWithDefault();
|
||||||
|
|
||||||
|
// 适配iframe
|
||||||
|
if (isIframe) {
|
||||||
|
runIframe(setting);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
// 不规范网页修复
|
||||||
|
await runWebfix(setting);
|
||||||
|
|
||||||
|
// 翻译网页
|
||||||
|
const { translator, rule } = await runTranslator(setting);
|
||||||
|
|
||||||
|
// 监听消息
|
||||||
|
windowListener(rule);
|
||||||
|
runtimeListener(translator);
|
||||||
|
|
||||||
|
// 划词翻译
|
||||||
|
showTransbox(setting);
|
||||||
|
|
||||||
|
// 浮球按钮
|
||||||
|
await showFab(translator);
|
||||||
} catch (err) {
|
} catch (err) {
|
||||||
console.error("[KISS-Translator]", err);
|
showErr(err);
|
||||||
const $err = document.createElement("div");
|
|
||||||
$err.innerText = `KISS-Translator: ${err.message}`;
|
|
||||||
$err.style.cssText = "background:red; color:#fff;";
|
|
||||||
document.body.prepend($err);
|
|
||||||
}
|
}
|
||||||
})();
|
})();
|
||||||
|
|||||||
18
src/hooks/Tranbox.js
Normal file
18
src/hooks/Tranbox.js
Normal file
@@ -0,0 +1,18 @@
|
|||||||
|
import { useCallback } from "react";
|
||||||
|
import { DEFAULT_TRANBOX_SETTING } from "../config";
|
||||||
|
import { useSetting } from "./Setting";
|
||||||
|
|
||||||
|
export function useTranbox() {
|
||||||
|
const { setting, updateSetting } = useSetting();
|
||||||
|
const tranboxSetting = setting?.tranboxSetting || DEFAULT_TRANBOX_SETTING;
|
||||||
|
|
||||||
|
const updateTranbox = useCallback(
|
||||||
|
async (obj) => {
|
||||||
|
Object.assign(tranboxSetting, obj);
|
||||||
|
await updateSetting({ tranboxSetting });
|
||||||
|
},
|
||||||
|
[tranboxSetting, updateSetting]
|
||||||
|
);
|
||||||
|
|
||||||
|
return { tranboxSetting, updateTranbox };
|
||||||
|
}
|
||||||
@@ -32,7 +32,8 @@ export function useTranslate(q, rule, setting) {
|
|||||||
text: q,
|
text: q,
|
||||||
fromLang,
|
fromLang,
|
||||||
toLang,
|
toLang,
|
||||||
apiSetting: (setting.transApis || DEFAULT_TRANS_APIS)[translator],
|
apiSetting:
|
||||||
|
setting.transApis?.[translator] || DEFAULT_TRANS_APIS[translator],
|
||||||
});
|
});
|
||||||
setText(trText);
|
setText(trText);
|
||||||
setSamelang(isSame);
|
setSamelang(isSame);
|
||||||
|
|||||||
@@ -6,14 +6,11 @@ import {
|
|||||||
MSG_FETCH_LIMIT,
|
MSG_FETCH_LIMIT,
|
||||||
MSG_FETCH_CLEAR,
|
MSG_FETCH_CLEAR,
|
||||||
CACHE_NAME,
|
CACHE_NAME,
|
||||||
OPT_TRANS_MICROSOFT,
|
|
||||||
OPT_TRANS_DEEPL,
|
|
||||||
OPT_TRANS_OPENAI,
|
|
||||||
DEFAULT_FETCH_INTERVAL,
|
DEFAULT_FETCH_INTERVAL,
|
||||||
DEFAULT_FETCH_LIMIT,
|
DEFAULT_FETCH_LIMIT,
|
||||||
} from "../config";
|
} from "../config";
|
||||||
import { msAuth } from "./auth";
|
|
||||||
import { isBg } from "./browser";
|
import { isBg } from "./browser";
|
||||||
|
import { newCacheReq, newTransReq } from "./req";
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* 油猴脚本的请求封装
|
* 油猴脚本的请求封装
|
||||||
@@ -28,57 +25,34 @@ export const fetchGM = async (input, { method = "GET", headers, body } = {}) =>
|
|||||||
url: input,
|
url: input,
|
||||||
headers,
|
headers,
|
||||||
data: body,
|
data: body,
|
||||||
onload: ({ response, responseHeaders, status, statusText }) => {
|
// withCredentials: true,
|
||||||
const headers = new Headers();
|
onload: ({ response, responseHeaders, status, statusText, ...opts }) => {
|
||||||
|
const headers = {};
|
||||||
responseHeaders.split("\n").forEach((line) => {
|
responseHeaders.split("\n").forEach((line) => {
|
||||||
const [name, value] = line.split(":").map((item) => item.trim());
|
const [name, value] = line.split(":").map((item) => item.trim());
|
||||||
if (name && value) {
|
if (name && value) {
|
||||||
headers.append(name, value);
|
headers[name] = value;
|
||||||
}
|
}
|
||||||
});
|
});
|
||||||
resolve(
|
resolve({
|
||||||
new Response(response, {
|
body: response,
|
||||||
headers,
|
headers,
|
||||||
status,
|
status,
|
||||||
statusText,
|
statusText,
|
||||||
})
|
});
|
||||||
);
|
|
||||||
},
|
},
|
||||||
onerror: reject,
|
onerror: reject,
|
||||||
});
|
});
|
||||||
});
|
});
|
||||||
|
|
||||||
/**
|
|
||||||
* 构造缓存 request
|
|
||||||
* @param {*} request
|
|
||||||
* @returns
|
|
||||||
*/
|
|
||||||
const newCacheReq = async (request) => {
|
|
||||||
if (request.method !== "GET") {
|
|
||||||
const body = await request.text();
|
|
||||||
const cacheUrl = new URL(request.url);
|
|
||||||
cacheUrl.pathname += body;
|
|
||||||
request = new Request(cacheUrl.toString(), { method: "GET" });
|
|
||||||
}
|
|
||||||
|
|
||||||
return request;
|
|
||||||
};
|
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* 发起请求
|
* 发起请求
|
||||||
* @param {*} param0
|
* @param {*} param0
|
||||||
* @returns
|
* @returns
|
||||||
*/
|
*/
|
||||||
export const fetchApi = async ({ input, init = {}, translator, token }) => {
|
export const fetchApi = async ({ input, init, transOpts, apiSetting }) => {
|
||||||
if (token) {
|
if (transOpts?.translator) {
|
||||||
if (translator === OPT_TRANS_DEEPL) {
|
[input, init] = await newTransReq(transOpts, apiSetting);
|
||||||
init.headers["Authorization"] = `DeepL-Auth-Key ${token}`; // DeepL
|
|
||||||
} else if (translator === OPT_TRANS_OPENAI) {
|
|
||||||
init.headers["Authorization"] = `Bearer ${token}`; // OpenAI
|
|
||||||
init.headers["api-key"] = token; // Azure OpenAI
|
|
||||||
} else {
|
|
||||||
init.headers["Authorization"] = `Bearer ${token}`; // Microsoft & others
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|
||||||
if (isGm) {
|
if (isGm) {
|
||||||
@@ -88,19 +62,26 @@ export const fetchApi = async ({ input, init = {}, translator, token }) => {
|
|||||||
} else {
|
} else {
|
||||||
info = GM.info;
|
info = GM.info;
|
||||||
}
|
}
|
||||||
|
|
||||||
// Tampermonkey --> .connects
|
// Tampermonkey --> .connects
|
||||||
// Violentmonkey --> .connect
|
// Violentmonkey --> .connect
|
||||||
const connects = info?.script?.connects || info?.script?.connect || [];
|
const connects = info?.script?.connects || info?.script?.connect || [];
|
||||||
const url = new URL(input);
|
const url = new URL(input);
|
||||||
const isSafe = connects.find((item) => url.hostname.endsWith(item));
|
const isSafe = connects.find((item) => url.hostname.endsWith(item));
|
||||||
|
|
||||||
if (isSafe) {
|
if (isSafe) {
|
||||||
if (window.KISS_GM) {
|
const { body, headers, status, statusText } = window.KISS_GM
|
||||||
return window.KISS_GM.fetch(input, init);
|
? await window.KISS_GM.fetch(input, init)
|
||||||
} else {
|
: await fetchGM(input, init);
|
||||||
return fetchGM(input, init);
|
|
||||||
}
|
return new Response(body, {
|
||||||
|
headers: new Headers(headers),
|
||||||
|
status,
|
||||||
|
statusText,
|
||||||
|
});
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
return fetch(input, init);
|
return fetch(input, init);
|
||||||
};
|
};
|
||||||
|
|
||||||
@@ -109,13 +90,7 @@ export const fetchApi = async ({ input, init = {}, translator, token }) => {
|
|||||||
*/
|
*/
|
||||||
export const fetchPool = taskPool(
|
export const fetchPool = taskPool(
|
||||||
fetchApi,
|
fetchApi,
|
||||||
async ({ translator }) => {
|
null,
|
||||||
if (translator === OPT_TRANS_MICROSOFT) {
|
|
||||||
const [token] = await msAuth();
|
|
||||||
return { token };
|
|
||||||
}
|
|
||||||
return {};
|
|
||||||
},
|
|
||||||
DEFAULT_FETCH_INTERVAL,
|
DEFAULT_FETCH_INTERVAL,
|
||||||
DEFAULT_FETCH_LIMIT
|
DEFAULT_FETCH_LIMIT
|
||||||
);
|
);
|
||||||
@@ -128,9 +103,9 @@ export const fetchPool = taskPool(
|
|||||||
*/
|
*/
|
||||||
export const fetchData = async (
|
export const fetchData = async (
|
||||||
input,
|
input,
|
||||||
{ useCache, usePool, translator, token, ...init } = {}
|
{ useCache, usePool, transOpts, apiSetting, ...init } = {}
|
||||||
) => {
|
) => {
|
||||||
const cacheReq = await newCacheReq(new Request(input, init));
|
const cacheReq = await newCacheReq(input, init);
|
||||||
let res;
|
let res;
|
||||||
|
|
||||||
// 查询缓存
|
// 查询缓存
|
||||||
@@ -146,9 +121,9 @@ export const fetchData = async (
|
|||||||
if (!res) {
|
if (!res) {
|
||||||
// 发送请求
|
// 发送请求
|
||||||
if (usePool) {
|
if (usePool) {
|
||||||
res = await fetchPool.push({ input, init, translator, token });
|
res = await fetchPool.push({ input, init, transOpts, apiSetting });
|
||||||
} else {
|
} else {
|
||||||
res = await fetchApi({ input, init, translator, token });
|
res = await fetchApi({ input, init, transOpts, apiSetting });
|
||||||
}
|
}
|
||||||
|
|
||||||
if (!res?.ok) {
|
if (!res?.ok) {
|
||||||
@@ -180,7 +155,7 @@ export const fetchData = async (
|
|||||||
* @returns
|
* @returns
|
||||||
*/
|
*/
|
||||||
export const fetchPolyfill = async (input, 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");
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -6,7 +6,13 @@
|
|||||||
* @param {*} _limit
|
* @param {*} _limit
|
||||||
* @returns
|
* @returns
|
||||||
*/
|
*/
|
||||||
export const taskPool = (fn, preFn, _interval = 100, _limit = 100) => {
|
export const taskPool = (
|
||||||
|
fn,
|
||||||
|
preFn,
|
||||||
|
_interval = 100,
|
||||||
|
_limit = 100,
|
||||||
|
_retryInteral = 1000
|
||||||
|
) => {
|
||||||
const pool = [];
|
const pool = [];
|
||||||
const maxRetry = 2; // 最大重试次数
|
const maxRetry = 2; // 最大重试次数
|
||||||
let maxCount = _limit; // 最大数量
|
let maxCount = _limit; // 最大数量
|
||||||
@@ -14,23 +20,6 @@ export const taskPool = (fn, preFn, _interval = 100, _limit = 100) => {
|
|||||||
let interval = _interval; // 间隔时间
|
let interval = _interval; // 间隔时间
|
||||||
let timer = null;
|
let timer = null;
|
||||||
|
|
||||||
const handleTask = async (item, preArgs) => {
|
|
||||||
curCount++;
|
|
||||||
const { args, resolve, reject, retry } = item;
|
|
||||||
try {
|
|
||||||
const res = await fn({ ...args, ...preArgs });
|
|
||||||
resolve(res);
|
|
||||||
} catch (err) {
|
|
||||||
if (retry < maxRetry) {
|
|
||||||
pool.push({ args, resolve, reject, retry: retry + 1 });
|
|
||||||
} else {
|
|
||||||
reject(err);
|
|
||||||
}
|
|
||||||
} finally {
|
|
||||||
curCount--;
|
|
||||||
}
|
|
||||||
};
|
|
||||||
|
|
||||||
const run = async () => {
|
const run = async () => {
|
||||||
// console.log("timer", timer);
|
// console.log("timer", timer);
|
||||||
timer && clearTimeout(timer);
|
timer && clearTimeout(timer);
|
||||||
@@ -39,12 +28,24 @@ export const taskPool = (fn, preFn, _interval = 100, _limit = 100) => {
|
|||||||
if (curCount < maxCount) {
|
if (curCount < maxCount) {
|
||||||
const item = pool.shift();
|
const item = pool.shift();
|
||||||
if (item) {
|
if (item) {
|
||||||
|
curCount++;
|
||||||
|
const { args, resolve, reject, retry } = item;
|
||||||
try {
|
try {
|
||||||
const preArgs = await preFn(item.args);
|
const preArgs = preFn ? await preFn(item.args) : {};
|
||||||
handleTask(item, preArgs);
|
const res = await fn({ ...args, ...preArgs });
|
||||||
|
resolve(res);
|
||||||
} catch (err) {
|
} catch (err) {
|
||||||
console.log("[preFn]", err);
|
console.log("[task]", retry, err);
|
||||||
pool.push(item);
|
if (retry < maxRetry) {
|
||||||
|
const retryTimer = setTimeout(() => {
|
||||||
|
clearTimeout(retryTimer);
|
||||||
|
pool.push({ args, resolve, reject, retry: retry + 1 });
|
||||||
|
}, _retryInteral);
|
||||||
|
} else {
|
||||||
|
reject(err);
|
||||||
|
}
|
||||||
|
} finally {
|
||||||
|
curCount--;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
224
src/libs/req.js
Normal file
224
src/libs/req.js
Normal file
@@ -0,0 +1,224 @@
|
|||||||
|
import queryString from "query-string";
|
||||||
|
import {
|
||||||
|
OPT_TRANS_GOOGLE,
|
||||||
|
OPT_TRANS_MICROSOFT,
|
||||||
|
OPT_TRANS_DEEPL,
|
||||||
|
OPT_TRANS_DEEPLFREE,
|
||||||
|
OPT_TRANS_DEEPLX,
|
||||||
|
OPT_TRANS_BAIDU,
|
||||||
|
OPT_TRANS_TENCENT,
|
||||||
|
OPT_TRANS_OPENAI,
|
||||||
|
OPT_TRANS_CUSTOMIZE,
|
||||||
|
URL_MICROSOFT_TRAN,
|
||||||
|
URL_TENCENT_TRANSMART,
|
||||||
|
PROMPT_PLACE_FROM,
|
||||||
|
PROMPT_PLACE_TO,
|
||||||
|
} from "../config";
|
||||||
|
import { msAuth } from "./auth";
|
||||||
|
import { genDeeplFree } from "../apis/deepl";
|
||||||
|
import { genBaidu } from "../apis/baidu";
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 构造缓存 request
|
||||||
|
* @param {*} request
|
||||||
|
* @returns
|
||||||
|
*/
|
||||||
|
export const newCacheReq = async (input, init) => {
|
||||||
|
let request = new Request(input, init);
|
||||||
|
if (request.method !== "GET") {
|
||||||
|
const body = await request.text();
|
||||||
|
const cacheUrl = new URL(request.url);
|
||||||
|
cacheUrl.pathname += body;
|
||||||
|
request = new Request(cacheUrl.toString(), { method: "GET" });
|
||||||
|
}
|
||||||
|
|
||||||
|
return request;
|
||||||
|
};
|
||||||
|
|
||||||
|
const genGoogle = ({ text, from, to, url, key }) => {
|
||||||
|
const params = {
|
||||||
|
client: "gtx",
|
||||||
|
dt: "t",
|
||||||
|
dj: 1,
|
||||||
|
ie: "UTF-8",
|
||||||
|
sl: from,
|
||||||
|
tl: to,
|
||||||
|
q: text,
|
||||||
|
};
|
||||||
|
const input = `${url}?${queryString.stringify(params)}`;
|
||||||
|
const init = {
|
||||||
|
headers: {
|
||||||
|
"Content-type": "application/json",
|
||||||
|
},
|
||||||
|
};
|
||||||
|
if (key) {
|
||||||
|
init.headers.Authorization = `Bearer ${key}`;
|
||||||
|
}
|
||||||
|
|
||||||
|
return [input, init];
|
||||||
|
};
|
||||||
|
|
||||||
|
const genMicrosoft = async ({ text, from, to }) => {
|
||||||
|
const [token] = await msAuth();
|
||||||
|
const params = {
|
||||||
|
from,
|
||||||
|
to,
|
||||||
|
"api-version": "3.0",
|
||||||
|
};
|
||||||
|
const input = `${URL_MICROSOFT_TRAN}?${queryString.stringify(params)}`;
|
||||||
|
const init = {
|
||||||
|
headers: {
|
||||||
|
"Content-type": "application/json",
|
||||||
|
Authorization: `Bearer ${token}`,
|
||||||
|
},
|
||||||
|
method: "POST",
|
||||||
|
body: JSON.stringify([{ Text: text }]),
|
||||||
|
};
|
||||||
|
|
||||||
|
return [input, init];
|
||||||
|
};
|
||||||
|
|
||||||
|
const genDeepl = ({ text, from, to, url, key }) => {
|
||||||
|
const data = {
|
||||||
|
text: [text],
|
||||||
|
target_lang: to,
|
||||||
|
source_lang: from,
|
||||||
|
// split_sentences: "0",
|
||||||
|
};
|
||||||
|
const init = {
|
||||||
|
headers: {
|
||||||
|
"Content-type": "application/json",
|
||||||
|
Authorization: `DeepL-Auth-Key ${key}`,
|
||||||
|
},
|
||||||
|
method: "POST",
|
||||||
|
body: JSON.stringify(data),
|
||||||
|
};
|
||||||
|
|
||||||
|
return [url, init];
|
||||||
|
};
|
||||||
|
|
||||||
|
const genDeeplX = ({ text, from, to, url, key }) => {
|
||||||
|
const data = {
|
||||||
|
text,
|
||||||
|
target_lang: to,
|
||||||
|
source_lang: from,
|
||||||
|
};
|
||||||
|
|
||||||
|
const init = {
|
||||||
|
headers: {
|
||||||
|
"Content-type": "application/json",
|
||||||
|
},
|
||||||
|
method: "POST",
|
||||||
|
body: JSON.stringify(data),
|
||||||
|
};
|
||||||
|
if (key) {
|
||||||
|
init.headers.Authorization = `Bearer ${key}`;
|
||||||
|
}
|
||||||
|
|
||||||
|
return [url, init];
|
||||||
|
};
|
||||||
|
|
||||||
|
const genTencent = ({ text, from, to }) => {
|
||||||
|
const data = {
|
||||||
|
header: {
|
||||||
|
fn: "auto_translation_block",
|
||||||
|
},
|
||||||
|
source: {
|
||||||
|
text_block: text,
|
||||||
|
lang: from,
|
||||||
|
},
|
||||||
|
target: {
|
||||||
|
lang: to,
|
||||||
|
},
|
||||||
|
};
|
||||||
|
|
||||||
|
const init = {
|
||||||
|
headers: {
|
||||||
|
"Content-Type": "application/json",
|
||||||
|
},
|
||||||
|
method: "POST",
|
||||||
|
body: JSON.stringify(data),
|
||||||
|
};
|
||||||
|
|
||||||
|
return [URL_TENCENT_TRANSMART, init];
|
||||||
|
};
|
||||||
|
|
||||||
|
const genOpenai = ({ text, from, to, url, key, prompt, model }) => {
|
||||||
|
prompt = prompt
|
||||||
|
.replaceAll(PROMPT_PLACE_FROM, from)
|
||||||
|
.replaceAll(PROMPT_PLACE_TO, to);
|
||||||
|
|
||||||
|
const data = {
|
||||||
|
model,
|
||||||
|
messages: [
|
||||||
|
{
|
||||||
|
role: "system",
|
||||||
|
content: prompt,
|
||||||
|
},
|
||||||
|
{
|
||||||
|
role: "user",
|
||||||
|
content: text,
|
||||||
|
},
|
||||||
|
],
|
||||||
|
temperature: 0,
|
||||||
|
max_tokens: 256,
|
||||||
|
};
|
||||||
|
|
||||||
|
const init = {
|
||||||
|
headers: {
|
||||||
|
"Content-type": "application/json",
|
||||||
|
Authorization: `Bearer ${key}`, // OpenAI
|
||||||
|
"api-key": key, // Azure OpenAI
|
||||||
|
},
|
||||||
|
method: "POST",
|
||||||
|
body: JSON.stringify(data),
|
||||||
|
};
|
||||||
|
|
||||||
|
return [url, init];
|
||||||
|
};
|
||||||
|
|
||||||
|
const genCustom = ({ text, from, to, url, key }) => {
|
||||||
|
const data = {
|
||||||
|
text,
|
||||||
|
from,
|
||||||
|
to,
|
||||||
|
};
|
||||||
|
const init = {
|
||||||
|
headers: {
|
||||||
|
"Content-type": "application/json",
|
||||||
|
},
|
||||||
|
method: "POST",
|
||||||
|
body: JSON.stringify(data),
|
||||||
|
};
|
||||||
|
if (key) {
|
||||||
|
init.headers.Authorization = `Bearer ${key}`;
|
||||||
|
}
|
||||||
|
|
||||||
|
return [url, init];
|
||||||
|
};
|
||||||
|
|
||||||
|
export const newTransReq = ({ translator, text, from, to }, apiSetting) => {
|
||||||
|
const args = { text, from, to, ...apiSetting };
|
||||||
|
switch (translator) {
|
||||||
|
case OPT_TRANS_GOOGLE:
|
||||||
|
return genGoogle(args);
|
||||||
|
case OPT_TRANS_MICROSOFT:
|
||||||
|
return genMicrosoft(args);
|
||||||
|
case OPT_TRANS_DEEPL:
|
||||||
|
return genDeepl(args);
|
||||||
|
case OPT_TRANS_DEEPLFREE:
|
||||||
|
return genDeeplFree(args);
|
||||||
|
case OPT_TRANS_DEEPLX:
|
||||||
|
return genDeeplX(args);
|
||||||
|
case OPT_TRANS_BAIDU:
|
||||||
|
return genBaidu(args);
|
||||||
|
case OPT_TRANS_TENCENT:
|
||||||
|
return genTencent(args);
|
||||||
|
case OPT_TRANS_OPENAI:
|
||||||
|
return genOpenai(args);
|
||||||
|
case OPT_TRANS_CUSTOMIZE:
|
||||||
|
return genCustom(args);
|
||||||
|
default:
|
||||||
|
throw new Error(`[trans] translator: ${translator} not support`);
|
||||||
|
}
|
||||||
|
};
|
||||||
@@ -4,6 +4,7 @@ import {
|
|||||||
STOKEY_FAB,
|
STOKEY_FAB,
|
||||||
STOKEY_SYNC,
|
STOKEY_SYNC,
|
||||||
STOKEY_MSAUTH,
|
STOKEY_MSAUTH,
|
||||||
|
STOKEY_BDAUTH,
|
||||||
STOKEY_RULESCACHE_PREFIX,
|
STOKEY_RULESCACHE_PREFIX,
|
||||||
STOKEY_WEBFIXCACHE_PREFIX,
|
STOKEY_WEBFIXCACHE_PREFIX,
|
||||||
DEFAULT_SETTING,
|
DEFAULT_SETTING,
|
||||||
@@ -134,6 +135,12 @@ export const updateSync = (obj) => putObj(STOKEY_SYNC, obj);
|
|||||||
export const getMsauth = () => getObj(STOKEY_MSAUTH);
|
export const getMsauth = () => getObj(STOKEY_MSAUTH);
|
||||||
export const setMsauth = (val) => setObj(STOKEY_MSAUTH, val);
|
export const setMsauth = (val) => setObj(STOKEY_MSAUTH, val);
|
||||||
|
|
||||||
|
/**
|
||||||
|
* baidu auth
|
||||||
|
*/
|
||||||
|
export const getBdauth = () => getObj(STOKEY_BDAUTH);
|
||||||
|
export const setBdauth = (val) => setObj(STOKEY_BDAUTH, val);
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* 存入默认数据
|
* 存入默认数据
|
||||||
*/
|
*/
|
||||||
|
|||||||
@@ -124,6 +124,7 @@ export class Translator {
|
|||||||
"iframe",
|
"iframe",
|
||||||
];
|
];
|
||||||
_eventName = genEventName();
|
_eventName = genEventName();
|
||||||
|
_mouseoverNode = null;
|
||||||
|
|
||||||
// 显示
|
// 显示
|
||||||
_interseObserver = new IntersectionObserver(
|
_interseObserver = new IntersectionObserver(
|
||||||
@@ -336,18 +337,22 @@ export class Translator {
|
|||||||
});
|
});
|
||||||
});
|
});
|
||||||
|
|
||||||
this._tranNodes.forEach((_, node) => {
|
|
||||||
if (
|
if (
|
||||||
!this._setting.mouseKey ||
|
!this._setting.mouseKey ||
|
||||||
this._setting.mouseKey === OPT_MOUSEKEY_DISABLE
|
this._setting.mouseKey === OPT_MOUSEKEY_DISABLE
|
||||||
) {
|
) {
|
||||||
// 监听节点显示
|
// 监听节点显示
|
||||||
|
this._tranNodes.forEach((_, node) => {
|
||||||
this._interseObserver.observe(node);
|
this._interseObserver.observe(node);
|
||||||
|
});
|
||||||
} else {
|
} else {
|
||||||
// 监听鼠标悬停
|
// 监听鼠标悬停
|
||||||
|
window.addEventListener("keydown", this._handleKeydown);
|
||||||
|
this._tranNodes.forEach((_, node) => {
|
||||||
node.addEventListener("mouseover", this._handleMouseover);
|
node.addEventListener("mouseover", this._handleMouseover);
|
||||||
}
|
node.addEventListener("mouseout", this._handleMouseout);
|
||||||
});
|
});
|
||||||
|
}
|
||||||
};
|
};
|
||||||
|
|
||||||
_registerInput = () => {
|
_registerInput = () => {
|
||||||
@@ -360,9 +365,8 @@ export class Translator {
|
|||||||
triggerTime,
|
triggerTime,
|
||||||
transSign,
|
transSign,
|
||||||
} = this._inputRule;
|
} = this._inputRule;
|
||||||
const apiSetting = (this._setting.transApis || DEFAULT_TRANS_APIS)[
|
const apiSetting =
|
||||||
translator
|
this._setting.transApis?.[translator] || DEFAULT_TRANS_APIS[translator];
|
||||||
];
|
|
||||||
const { detectRemote } = this._setting;
|
const { detectRemote } = this._setting;
|
||||||
|
|
||||||
let triggerShortcut = initTriggerShortcut;
|
let triggerShortcut = initTriggerShortcut;
|
||||||
@@ -471,10 +475,43 @@ export class Translator {
|
|||||||
};
|
};
|
||||||
|
|
||||||
_handleMouseover = (e) => {
|
_handleMouseover = (e) => {
|
||||||
|
// console.log("mouseover", e);
|
||||||
|
if (!this._tranNodes.has(e.target)) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
const key = this._setting.mouseKey.slice(3);
|
const key = this._setting.mouseKey.slice(3);
|
||||||
if (this._setting.mouseKey === OPT_MOUSEKEY_MOUSEOVER || e[key]) {
|
if (this._setting.mouseKey === OPT_MOUSEKEY_MOUSEOVER || e[key]) {
|
||||||
e.target.removeEventListener("mouseover", this._handleMouseover);
|
e.target.removeEventListener("mouseover", this._handleMouseover);
|
||||||
|
e.target.removeEventListener("mouseout", this._handleMouseout);
|
||||||
this._render(e.target);
|
this._render(e.target);
|
||||||
|
} else {
|
||||||
|
this._mouseoverNode = e.target;
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
_handleMouseout = (e) => {
|
||||||
|
// console.log("mouseout", e);
|
||||||
|
if (!this._tranNodes.has(e.target)) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
this._mouseoverNode = null;
|
||||||
|
};
|
||||||
|
|
||||||
|
_handleKeydown = (e) => {
|
||||||
|
// console.log("keydown", e);
|
||||||
|
const key = this._setting.mouseKey.slice(3);
|
||||||
|
if (e[key] && this._mouseoverNode) {
|
||||||
|
this._mouseoverNode.removeEventListener(
|
||||||
|
"mouseover",
|
||||||
|
this._handleMouseover
|
||||||
|
);
|
||||||
|
this._mouseoverNode.removeEventListener("mouseout", this._handleMouseout);
|
||||||
|
|
||||||
|
const node = this._mouseoverNode;
|
||||||
|
this._render(node);
|
||||||
|
this._mouseoverNode = null;
|
||||||
}
|
}
|
||||||
};
|
};
|
||||||
|
|
||||||
@@ -485,21 +522,26 @@ export class Translator {
|
|||||||
// 解除节点显示监听
|
// 解除节点显示监听
|
||||||
// this._interseObserver.disconnect();
|
// this._interseObserver.disconnect();
|
||||||
|
|
||||||
this._tranNodes.forEach((_, node) => {
|
|
||||||
if (
|
if (
|
||||||
!this._setting.mouseKey ||
|
!this._setting.mouseKey ||
|
||||||
this._setting.mouseKey === OPT_MOUSEKEY_DISABLE
|
this._setting.mouseKey === OPT_MOUSEKEY_DISABLE
|
||||||
) {
|
) {
|
||||||
// 解除节点显示监听
|
// 解除节点显示监听
|
||||||
|
this._tranNodes.forEach((_, node) => {
|
||||||
this._interseObserver.unobserve(node);
|
this._interseObserver.unobserve(node);
|
||||||
} else {
|
|
||||||
// 移除鼠标悬停监听
|
|
||||||
node.removeEventListener("mouseover", this._handleMouseover);
|
|
||||||
}
|
|
||||||
|
|
||||||
// 移除已插入元素
|
// 移除已插入元素
|
||||||
node.querySelector(APP_LCNAME)?.remove();
|
node.querySelector(APP_LCNAME)?.remove();
|
||||||
});
|
});
|
||||||
|
} else {
|
||||||
|
// 移除鼠标悬停监听
|
||||||
|
window.removeEventListener("keydown", this._handleKeydown);
|
||||||
|
this._tranNodes.forEach((_, node) => {
|
||||||
|
node.removeEventListener("mouseover", this._handleMouseover);
|
||||||
|
node.removeEventListener("mouseout", this._handleMouseout);
|
||||||
|
// 移除已插入元素
|
||||||
|
node.querySelector(APP_LCNAME)?.remove();
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
// 清空节点集合
|
// 清空节点集合
|
||||||
this._rootNodes.clear();
|
this._rootNodes.clear();
|
||||||
|
|||||||
@@ -223,3 +223,13 @@ export const matchInputStr = (str, sign) => {
|
|||||||
}
|
}
|
||||||
return str.match(reg);
|
return str.match(reg);
|
||||||
};
|
};
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 判断是否英文单词
|
||||||
|
* @param {*} str
|
||||||
|
* @returns
|
||||||
|
*/
|
||||||
|
export const isValidWord = (str) => {
|
||||||
|
const regex = /^[a-zA-Z-]+$/;
|
||||||
|
return regex.test(str);
|
||||||
|
};
|
||||||
|
|||||||
@@ -6,6 +6,7 @@ import { apiFetch } from "../apis";
|
|||||||
* 修复程序类型
|
* 修复程序类型
|
||||||
*/
|
*/
|
||||||
const FIXER_BR = "br";
|
const FIXER_BR = "br";
|
||||||
|
const FIXER_BN = "bn";
|
||||||
const FIXER_FONTSIZE = "fontSize";
|
const FIXER_FONTSIZE = "fontSize";
|
||||||
|
|
||||||
/**
|
/**
|
||||||
@@ -34,6 +35,12 @@ const DEFAULT_SITES = [
|
|||||||
rootSelector: "",
|
rootSelector: "",
|
||||||
fixer: FIXER_FONTSIZE,
|
fixer: FIXER_FONTSIZE,
|
||||||
},
|
},
|
||||||
|
{
|
||||||
|
pattern: "chat.openai.com",
|
||||||
|
selector: "div[data-testid^=conversation-turn] .items-start > div",
|
||||||
|
rootSelector: "",
|
||||||
|
fixer: FIXER_BN,
|
||||||
|
},
|
||||||
];
|
];
|
||||||
|
|
||||||
/**
|
/**
|
||||||
@@ -94,6 +101,26 @@ function brFixer(node) {
|
|||||||
node.innerHTML = html;
|
node.innerHTML = html;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 目标是将 `\n` 替换成 `p`
|
||||||
|
* @param {*} node
|
||||||
|
* @returns
|
||||||
|
*/
|
||||||
|
function bnFixer(node) {
|
||||||
|
if (node.hasAttribute(fixedSign)) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
node.setAttribute(fixedSign, "true");
|
||||||
|
|
||||||
|
const childs = node.childNodes;
|
||||||
|
if (childs.length === 1 && childs[0].nodeName === "#text") {
|
||||||
|
node.innerHTML = node.innerHTML
|
||||||
|
.split("\n")
|
||||||
|
.map((item) => `<p>${item || " "}</p>`)
|
||||||
|
.join("");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* 修复字体大小问题,如 baidu.com
|
* 修复字体大小问题,如 baidu.com
|
||||||
* @param {*} node
|
* @param {*} node
|
||||||
@@ -107,6 +134,7 @@ function fontSizeFixer(node) {
|
|||||||
*/
|
*/
|
||||||
const fixerMap = {
|
const fixerMap = {
|
||||||
[FIXER_BR]: brFixer,
|
[FIXER_BR]: brFixer,
|
||||||
|
[FIXER_BN]: bnFixer,
|
||||||
[FIXER_FONTSIZE]: fontSizeFixer,
|
[FIXER_FONTSIZE]: fontSizeFixer,
|
||||||
};
|
};
|
||||||
|
|
||||||
@@ -134,6 +162,7 @@ function run(selector, fixer, rootSelector) {
|
|||||||
rootNode.querySelectorAll(selector).forEach(fixer);
|
rootNode.querySelectorAll(selector).forEach(fixer);
|
||||||
mutaObserver.observe(rootNode, {
|
mutaObserver.observe(rootNode, {
|
||||||
childList: true,
|
childList: true,
|
||||||
|
subtree: true,
|
||||||
});
|
});
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
@@ -170,12 +199,13 @@ export const loadOrFetchWebfix = async (url) => {
|
|||||||
/**
|
/**
|
||||||
* 匹配站点
|
* 匹配站点
|
||||||
*/
|
*/
|
||||||
export async function webfix(href, { injectWebfix }) {
|
export async function runWebfix({ injectWebfix }) {
|
||||||
try {
|
try {
|
||||||
if (!injectWebfix) {
|
if (!injectWebfix) {
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
const href = document.location.href;
|
||||||
const sites = await loadOrFetchWebfix(process.env.REACT_APP_WEBFIXURL);
|
const sites = await loadOrFetchWebfix(process.env.REACT_APP_WEBFIXURL);
|
||||||
for (var i = 0; i < sites.length; i++) {
|
for (var i = 0; i < sites.length; i++) {
|
||||||
var site = sites[i];
|
var site = sites[i];
|
||||||
|
|||||||
@@ -1,38 +1,19 @@
|
|||||||
import React from "react";
|
import { getSettingWithDefault } from "./libs/storage";
|
||||||
import ReactDOM from "react-dom/client";
|
|
||||||
import Action from "./views/Action";
|
|
||||||
import createCache from "@emotion/cache";
|
|
||||||
import { CacheProvider } from "@emotion/react";
|
|
||||||
import {
|
|
||||||
getSettingWithDefault,
|
|
||||||
getRulesWithDefault,
|
|
||||||
getFabWithDefault,
|
|
||||||
} from "./libs/storage";
|
|
||||||
import { Translator } from "./libs/translator";
|
|
||||||
import { trySyncAllSubRules } from "./libs/subRules";
|
import { trySyncAllSubRules } from "./libs/subRules";
|
||||||
import {
|
import { isIframe } from "./libs/iframe";
|
||||||
MSG_TRANS_TOGGLE,
|
|
||||||
MSG_TRANS_TOGGLE_STYLE,
|
|
||||||
MSG_TRANS_GETRULE,
|
|
||||||
MSG_TRANS_PUTRULE,
|
|
||||||
APP_LCNAME,
|
|
||||||
} from "./config";
|
|
||||||
import { isIframe, sendIframeMsg, sendParentMsg } from "./libs/iframe";
|
|
||||||
import { handlePing, injectScript } from "./libs/gm";
|
import { handlePing, injectScript } from "./libs/gm";
|
||||||
import { matchRule } from "./libs/rules";
|
|
||||||
import { genEventName } from "./libs/utils";
|
import { genEventName } from "./libs/utils";
|
||||||
import { webfix } from "./libs/webfix";
|
import { runWebfix } from "./libs/webfix";
|
||||||
|
import {
|
||||||
|
runIframe,
|
||||||
|
runTranslator,
|
||||||
|
showFab,
|
||||||
|
showTransbox,
|
||||||
|
windowListener,
|
||||||
|
showErr,
|
||||||
|
} from "./common";
|
||||||
|
|
||||||
/**
|
function runSettingPage() {
|
||||||
* 入口函数
|
|
||||||
*/
|
|
||||||
const init = async () => {
|
|
||||||
// 设置页面
|
|
||||||
if (
|
|
||||||
document.location.href.includes(process.env.REACT_APP_OPTIONSPAGE_DEV) ||
|
|
||||||
document.location.href.includes(process.env.REACT_APP_OPTIONSPAGE) ||
|
|
||||||
document.location.href.includes(process.env.REACT_APP_OPTIONSPAGE2)
|
|
||||||
) {
|
|
||||||
if (GM?.info?.script?.grant?.includes("unsafeWindow")) {
|
if (GM?.info?.script?.grant?.includes("unsafeWindow")) {
|
||||||
unsafeWindow.GM = GM;
|
unsafeWindow.GM = GM;
|
||||||
unsafeWindow.APP_INFO = {
|
unsafeWindow.APP_INFO = {
|
||||||
@@ -47,90 +28,50 @@ const init = async () => {
|
|||||||
script.textContent = `(${injectScript})("${ping}")`;
|
script.textContent = `(${injectScript})("${ping}")`;
|
||||||
document.head.append(script);
|
document.head.append(script);
|
||||||
}
|
}
|
||||||
|
|
||||||
return;
|
|
||||||
}
|
}
|
||||||
|
|
||||||
// 翻译页面
|
/**
|
||||||
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:
|
|
||||||
}
|
|
||||||
});
|
|
||||||
sendParentMsg(MSG_TRANS_GETRULE);
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
|
|
||||||
const href = isIframe ? document.referrer : document.location.href;
|
|
||||||
const rules = await getRulesWithDefault();
|
|
||||||
const rule = await matchRule(rules, href, setting);
|
|
||||||
const translator = new Translator(rule, setting);
|
|
||||||
webfix(href, setting);
|
|
||||||
|
|
||||||
// 监听消息
|
|
||||||
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();
|
|
||||||
const $action = document.createElement("div");
|
|
||||||
$action.setAttribute("id", APP_LCNAME);
|
|
||||||
document.body.parentElement.appendChild($action);
|
|
||||||
const shadowContainer = $action.attachShadow({ mode: "closed" });
|
|
||||||
const emotionRoot = document.createElement("style");
|
|
||||||
const shadowRootElement = document.createElement("div");
|
|
||||||
shadowContainer.appendChild(emotionRoot);
|
|
||||||
shadowContainer.appendChild(shadowRootElement);
|
|
||||||
const cache = createCache({
|
|
||||||
key: APP_LCNAME,
|
|
||||||
prepend: true,
|
|
||||||
container: emotionRoot,
|
|
||||||
});
|
|
||||||
ReactDOM.createRoot(shadowRootElement).render(
|
|
||||||
<React.StrictMode>
|
|
||||||
<CacheProvider value={cache}>
|
|
||||||
<Action translator={translator} fab={fab} />
|
|
||||||
</CacheProvider>
|
|
||||||
</React.StrictMode>
|
|
||||||
);
|
|
||||||
|
|
||||||
// 同步订阅规则
|
|
||||||
trySyncAllSubRules(setting);
|
|
||||||
};
|
|
||||||
|
|
||||||
(async () => {
|
(async () => {
|
||||||
try {
|
try {
|
||||||
await init();
|
// 设置页面
|
||||||
|
if (
|
||||||
|
document.location.href.includes(process.env.REACT_APP_OPTIONSPAGE_DEV) ||
|
||||||
|
document.location.href.includes(process.env.REACT_APP_OPTIONSPAGE) ||
|
||||||
|
document.location.href.includes(process.env.REACT_APP_OPTIONSPAGE2)
|
||||||
|
) {
|
||||||
|
runSettingPage();
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
// 读取设置信息
|
||||||
|
const setting = await getSettingWithDefault();
|
||||||
|
|
||||||
|
// 适配iframe
|
||||||
|
if (isIframe) {
|
||||||
|
runIframe(setting);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
// 不规范网页修复
|
||||||
|
await runWebfix(setting);
|
||||||
|
|
||||||
|
// 翻译网页
|
||||||
|
const { translator, rule } = await runTranslator(setting);
|
||||||
|
|
||||||
|
// 监听消息
|
||||||
|
windowListener(rule);
|
||||||
|
|
||||||
|
// 划词翻译
|
||||||
|
showTransbox(setting);
|
||||||
|
|
||||||
|
// 浮球按钮
|
||||||
|
await showFab(translator);
|
||||||
|
|
||||||
|
// 同步订阅规则
|
||||||
|
await trySyncAllSubRules(setting);
|
||||||
} catch (err) {
|
} catch (err) {
|
||||||
console.error("[KISS-Translator]", err);
|
showErr(err);
|
||||||
const $err = document.createElement("div");
|
|
||||||
$err.innerText = `KISS-Translator: ${err.message}`;
|
|
||||||
$err.style.cssText = "background:red; color:#fff;";
|
|
||||||
document.body.prepend($err);
|
|
||||||
}
|
}
|
||||||
})();
|
})();
|
||||||
|
|||||||
@@ -5,6 +5,9 @@ import CircularProgress from "@mui/material/CircularProgress";
|
|||||||
import {
|
import {
|
||||||
OPT_TRANS_ALL,
|
OPT_TRANS_ALL,
|
||||||
OPT_TRANS_MICROSOFT,
|
OPT_TRANS_MICROSOFT,
|
||||||
|
OPT_TRANS_DEEPLFREE,
|
||||||
|
OPT_TRANS_BAIDU,
|
||||||
|
OPT_TRANS_TENCENT,
|
||||||
OPT_TRANS_OPENAI,
|
OPT_TRANS_OPENAI,
|
||||||
OPT_TRANS_CUSTOMIZE,
|
OPT_TRANS_CUSTOMIZE,
|
||||||
URL_KISS_PROXY,
|
URL_KISS_PROXY,
|
||||||
@@ -35,7 +38,8 @@ function TestButton({ translator, api }) {
|
|||||||
text: "hello world",
|
text: "hello world",
|
||||||
fromLang: "en",
|
fromLang: "en",
|
||||||
toLang: "zh-CN",
|
toLang: "zh-CN",
|
||||||
apiSetting: { ...api, useCache: false },
|
apiSetting: api,
|
||||||
|
useCache: false,
|
||||||
});
|
});
|
||||||
if (!text) {
|
if (!text) {
|
||||||
throw new Error("empty reault");
|
throw new Error("empty reault");
|
||||||
@@ -71,9 +75,16 @@ function ApiFields({ translator }) {
|
|||||||
});
|
});
|
||||||
};
|
};
|
||||||
|
|
||||||
|
const buildinTranslators = [
|
||||||
|
OPT_TRANS_MICROSOFT,
|
||||||
|
OPT_TRANS_DEEPLFREE,
|
||||||
|
OPT_TRANS_BAIDU,
|
||||||
|
OPT_TRANS_TENCENT,
|
||||||
|
];
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<Stack spacing={3}>
|
<Stack spacing={3}>
|
||||||
{translator !== OPT_TRANS_MICROSOFT && (
|
{!buildinTranslators.includes(translator) && (
|
||||||
<>
|
<>
|
||||||
<TextField
|
<TextField
|
||||||
size="small"
|
size="small"
|
||||||
@@ -113,7 +124,7 @@ function ApiFields({ translator }) {
|
|||||||
|
|
||||||
<Stack direction="row" spacing={2}>
|
<Stack direction="row" spacing={2}>
|
||||||
<TestButton translator={translator} api={api} />
|
<TestButton translator={translator} api={api} />
|
||||||
{translator !== OPT_TRANS_MICROSOFT && (
|
{!buildinTranslators.includes(translator) && (
|
||||||
<Button
|
<Button
|
||||||
size="small"
|
size="small"
|
||||||
variant="outlined"
|
variant="outlined"
|
||||||
|
|||||||
@@ -13,6 +13,7 @@ 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';
|
||||||
|
|
||||||
function LinkItem({ label, url, icon }) {
|
function LinkItem({ label, url, icon }) {
|
||||||
const match = useMatch(url);
|
const match = useMatch(url);
|
||||||
@@ -45,6 +46,12 @@ export default function Navigator(props) {
|
|||||||
url: "/input",
|
url: "/input",
|
||||||
icon: <InputIcon />,
|
icon: <InputIcon />,
|
||||||
},
|
},
|
||||||
|
{
|
||||||
|
id: "selection_translate",
|
||||||
|
label: i18n("selection_translate"),
|
||||||
|
url: "/tranbox",
|
||||||
|
icon: <TranslateIcon />,
|
||||||
|
},
|
||||||
{
|
{
|
||||||
id: "apis_setting",
|
id: "apis_setting",
|
||||||
label: i18n("apis_setting"),
|
label: i18n("apis_setting"),
|
||||||
|
|||||||
140
src/views/Options/Tranbox.js
Normal file
140
src/views/Options/Tranbox.js
Normal file
@@ -0,0 +1,140 @@
|
|||||||
|
import Box from "@mui/material/Box";
|
||||||
|
import Stack from "@mui/material/Stack";
|
||||||
|
import TextField from "@mui/material/TextField";
|
||||||
|
import MenuItem from "@mui/material/MenuItem";
|
||||||
|
import { useI18n } from "../../hooks/I18n";
|
||||||
|
import { OPT_TRANS_ALL, OPT_LANGS_FROM, OPT_LANGS_TO } from "../../config";
|
||||||
|
import ShortcutInput from "./ShortcutInput";
|
||||||
|
import FormControlLabel from "@mui/material/FormControlLabel";
|
||||||
|
import Switch from "@mui/material/Switch";
|
||||||
|
import { useCallback } from "react";
|
||||||
|
import { limitNumber } from "../../libs/utils";
|
||||||
|
import { useTranbox } from "../../hooks/Tranbox";
|
||||||
|
|
||||||
|
export default function Tranbox() {
|
||||||
|
const i18n = useI18n();
|
||||||
|
const { tranboxSetting, updateTranbox } = useTranbox();
|
||||||
|
|
||||||
|
const handleChange = (e) => {
|
||||||
|
e.preventDefault();
|
||||||
|
let { name, value } = e.target;
|
||||||
|
switch (name) {
|
||||||
|
case "btnOffsetX":
|
||||||
|
value = limitNumber(value, 0, 100);
|
||||||
|
break;
|
||||||
|
case "btnOffsetY":
|
||||||
|
value = limitNumber(value, 0, 100);
|
||||||
|
break;
|
||||||
|
default:
|
||||||
|
}
|
||||||
|
updateTranbox({
|
||||||
|
[name]: value,
|
||||||
|
});
|
||||||
|
};
|
||||||
|
|
||||||
|
const handleShortcutInput = useCallback(
|
||||||
|
(val) => {
|
||||||
|
updateTranbox({ tranboxShortcut: val });
|
||||||
|
},
|
||||||
|
[updateTranbox]
|
||||||
|
);
|
||||||
|
|
||||||
|
const {
|
||||||
|
transOpen,
|
||||||
|
translator,
|
||||||
|
fromLang,
|
||||||
|
toLang,
|
||||||
|
tranboxShortcut,
|
||||||
|
btnOffsetX,
|
||||||
|
btnOffsetY,
|
||||||
|
} = tranboxSetting;
|
||||||
|
|
||||||
|
return (
|
||||||
|
<Box>
|
||||||
|
<Stack spacing={3}>
|
||||||
|
<FormControlLabel
|
||||||
|
control={
|
||||||
|
<Switch
|
||||||
|
size="small"
|
||||||
|
name="transOpen"
|
||||||
|
checked={transOpen}
|
||||||
|
onChange={() => {
|
||||||
|
updateTranbox({ transOpen: !transOpen });
|
||||||
|
}}
|
||||||
|
/>
|
||||||
|
}
|
||||||
|
label={i18n("toggle_selection_translate")}
|
||||||
|
/>
|
||||||
|
|
||||||
|
<TextField
|
||||||
|
select
|
||||||
|
size="small"
|
||||||
|
name="translator"
|
||||||
|
value={translator}
|
||||||
|
label={i18n("translate_service")}
|
||||||
|
onChange={handleChange}
|
||||||
|
>
|
||||||
|
{OPT_TRANS_ALL.map((item) => (
|
||||||
|
<MenuItem key={item} value={item}>
|
||||||
|
{item}
|
||||||
|
</MenuItem>
|
||||||
|
))}
|
||||||
|
</TextField>
|
||||||
|
|
||||||
|
<TextField
|
||||||
|
select
|
||||||
|
size="small"
|
||||||
|
name="fromLang"
|
||||||
|
value={fromLang}
|
||||||
|
label={i18n("from_lang")}
|
||||||
|
onChange={handleChange}
|
||||||
|
>
|
||||||
|
{OPT_LANGS_FROM.map(([lang, name]) => (
|
||||||
|
<MenuItem key={lang} value={lang}>
|
||||||
|
{name}
|
||||||
|
</MenuItem>
|
||||||
|
))}
|
||||||
|
</TextField>
|
||||||
|
|
||||||
|
<TextField
|
||||||
|
select
|
||||||
|
size="small"
|
||||||
|
name="toLang"
|
||||||
|
value={toLang}
|
||||||
|
label={i18n("to_lang")}
|
||||||
|
onChange={handleChange}
|
||||||
|
>
|
||||||
|
{OPT_LANGS_TO.map(([lang, name]) => (
|
||||||
|
<MenuItem key={lang} value={lang}>
|
||||||
|
{name}
|
||||||
|
</MenuItem>
|
||||||
|
))}
|
||||||
|
</TextField>
|
||||||
|
|
||||||
|
<TextField
|
||||||
|
size="small"
|
||||||
|
label={i18n("tranbtn_offset_x")}
|
||||||
|
type="number"
|
||||||
|
name="btnOffsetX"
|
||||||
|
defaultValue={btnOffsetX}
|
||||||
|
onChange={handleChange}
|
||||||
|
/>
|
||||||
|
|
||||||
|
<TextField
|
||||||
|
size="small"
|
||||||
|
label={i18n("tranbtn_offset_y")}
|
||||||
|
type="number"
|
||||||
|
name="btnOffsetY"
|
||||||
|
defaultValue={btnOffsetY}
|
||||||
|
onChange={handleChange}
|
||||||
|
/>
|
||||||
|
|
||||||
|
<ShortcutInput
|
||||||
|
value={tranboxShortcut}
|
||||||
|
onChange={handleShortcutInput}
|
||||||
|
label={i18n("trigger_tranbox_shortcut")}
|
||||||
|
/>
|
||||||
|
</Stack>
|
||||||
|
</Box>
|
||||||
|
);
|
||||||
|
}
|
||||||
@@ -20,6 +20,7 @@ import Alert from "@mui/material/Alert";
|
|||||||
import Apis from "./Apis";
|
import Apis from "./Apis";
|
||||||
import Webfix from "./Webfix";
|
import Webfix from "./Webfix";
|
||||||
import InputSetting from "./InputSetting";
|
import InputSetting from "./InputSetting";
|
||||||
|
import Tranbox from "./Tranbox";
|
||||||
|
|
||||||
export default function Options() {
|
export default function Options() {
|
||||||
const [error, setError] = useState("");
|
const [error, setError] = useState("");
|
||||||
@@ -120,6 +121,7 @@ export default function Options() {
|
|||||||
<Route index element={<Setting />} />
|
<Route index element={<Setting />} />
|
||||||
<Route path="rules" element={<Rules />} />
|
<Route path="rules" element={<Rules />} />
|
||||||
<Route path="input" element={<InputSetting />} />
|
<Route path="input" element={<InputSetting />} />
|
||||||
|
<Route path="tranbox" element={<Tranbox />} />
|
||||||
<Route path="apis" element={<Apis />} />
|
<Route path="apis" element={<Apis />} />
|
||||||
<Route path="sync" element={<SyncSetting />} />
|
<Route path="sync" element={<SyncSetting />} />
|
||||||
<Route path="webfix" element={<Webfix />} />
|
<Route path="webfix" element={<Webfix />} />
|
||||||
|
|||||||
258
src/views/Selection/DraggableResizable.js
Normal file
258
src/views/Selection/DraggableResizable.js
Normal file
@@ -0,0 +1,258 @@
|
|||||||
|
import { useEffect, useState } from "react";
|
||||||
|
import Paper from "@mui/material/Paper";
|
||||||
|
import Box from "@mui/material/Box";
|
||||||
|
|
||||||
|
function Pointer({
|
||||||
|
direction,
|
||||||
|
size,
|
||||||
|
setSize,
|
||||||
|
position,
|
||||||
|
setPosition,
|
||||||
|
children,
|
||||||
|
minSize,
|
||||||
|
maxSize,
|
||||||
|
...props
|
||||||
|
}) {
|
||||||
|
const [origin, setOrigin] = useState(null);
|
||||||
|
|
||||||
|
function handlePointerDown(e) {
|
||||||
|
e.target.setPointerCapture(e.pointerId);
|
||||||
|
setOrigin({
|
||||||
|
x: position.x,
|
||||||
|
y: position.y,
|
||||||
|
w: size.w,
|
||||||
|
h: size.h,
|
||||||
|
clientX: e.clientX,
|
||||||
|
clientY: e.clientY,
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
function handlePointerMove(e) {
|
||||||
|
if (origin) {
|
||||||
|
const dx = e.clientX - origin.clientX;
|
||||||
|
const dy = e.clientY - origin.clientY;
|
||||||
|
let x = position.x;
|
||||||
|
let y = position.y;
|
||||||
|
let w = size.w;
|
||||||
|
let h = size.h;
|
||||||
|
|
||||||
|
switch (direction) {
|
||||||
|
case "Header":
|
||||||
|
x = origin.x + dx;
|
||||||
|
y = origin.y + dy;
|
||||||
|
break;
|
||||||
|
case "TopLeft":
|
||||||
|
x = origin.x + dx;
|
||||||
|
y = origin.y + dy;
|
||||||
|
w = origin.w - dx;
|
||||||
|
h = origin.h - dy;
|
||||||
|
break;
|
||||||
|
case "Top":
|
||||||
|
y = origin.y + dy;
|
||||||
|
h = origin.h - dy;
|
||||||
|
break;
|
||||||
|
case "TopRight":
|
||||||
|
y = origin.y + dy;
|
||||||
|
w = origin.w + dx;
|
||||||
|
h = origin.h - dy;
|
||||||
|
break;
|
||||||
|
case "Left":
|
||||||
|
x = origin.x + dx;
|
||||||
|
w = origin.w - dx;
|
||||||
|
break;
|
||||||
|
case "Right":
|
||||||
|
w = origin.w + dx;
|
||||||
|
break;
|
||||||
|
case "BottomLeft":
|
||||||
|
x = origin.x + dx;
|
||||||
|
w = origin.w - dx;
|
||||||
|
h = origin.h + dy;
|
||||||
|
break;
|
||||||
|
case "Bottom":
|
||||||
|
h = origin.h + dy;
|
||||||
|
break;
|
||||||
|
case "BottomRight":
|
||||||
|
w = origin.w + dx;
|
||||||
|
h = origin.h + dy;
|
||||||
|
break;
|
||||||
|
default:
|
||||||
|
}
|
||||||
|
|
||||||
|
if (w < minSize.w) {
|
||||||
|
w = minSize.w;
|
||||||
|
x = position.x;
|
||||||
|
}
|
||||||
|
if (w > maxSize.w) {
|
||||||
|
w = maxSize.w;
|
||||||
|
x = position.x;
|
||||||
|
}
|
||||||
|
if (h < minSize.h) {
|
||||||
|
h = minSize.h;
|
||||||
|
y = position.y;
|
||||||
|
}
|
||||||
|
if (h > maxSize.h) {
|
||||||
|
h = maxSize.h;
|
||||||
|
y = position.y;
|
||||||
|
}
|
||||||
|
|
||||||
|
setPosition({ x, y });
|
||||||
|
setSize({ w, h });
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
function handlePointerUp(e) {
|
||||||
|
setOrigin(null);
|
||||||
|
}
|
||||||
|
|
||||||
|
return (
|
||||||
|
<div
|
||||||
|
{...props}
|
||||||
|
onPointerDown={handlePointerDown}
|
||||||
|
onPointerMove={handlePointerMove}
|
||||||
|
onPointerUp={handlePointerUp}
|
||||||
|
>
|
||||||
|
{children}
|
||||||
|
</div>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
export default function DraggableResizable({
|
||||||
|
header,
|
||||||
|
children,
|
||||||
|
defaultPosition = {
|
||||||
|
x: 0,
|
||||||
|
y: 0,
|
||||||
|
},
|
||||||
|
defaultSize = {
|
||||||
|
w: 600,
|
||||||
|
h: 400,
|
||||||
|
},
|
||||||
|
minSize = {
|
||||||
|
w: 300,
|
||||||
|
h: 200,
|
||||||
|
},
|
||||||
|
maxSize = {
|
||||||
|
w: 1200,
|
||||||
|
h: 1200,
|
||||||
|
},
|
||||||
|
onChangeSize,
|
||||||
|
onChangePosition,
|
||||||
|
}) {
|
||||||
|
const lineWidth = 4;
|
||||||
|
const [position, setPosition] = useState(defaultPosition);
|
||||||
|
const [size, setSize] = useState(defaultSize);
|
||||||
|
|
||||||
|
const opts = {
|
||||||
|
size,
|
||||||
|
setSize,
|
||||||
|
position,
|
||||||
|
setPosition,
|
||||||
|
minSize,
|
||||||
|
maxSize,
|
||||||
|
};
|
||||||
|
|
||||||
|
useEffect(() => {
|
||||||
|
onChangeSize && onChangeSize(size);
|
||||||
|
}, [size, onChangeSize]);
|
||||||
|
|
||||||
|
useEffect(() => {
|
||||||
|
onChangePosition && onChangePosition(position);
|
||||||
|
}, [position, onChangePosition]);
|
||||||
|
|
||||||
|
return (
|
||||||
|
<Box
|
||||||
|
style={{
|
||||||
|
position: "fixed",
|
||||||
|
left: position.x,
|
||||||
|
top: position.y,
|
||||||
|
display: "grid",
|
||||||
|
gridTemplateColumns: `${lineWidth * 2}px auto ${lineWidth * 2}px`,
|
||||||
|
gridTemplateRows: `${lineWidth * 2}px auto ${lineWidth * 2}px`,
|
||||||
|
zIndex: 2147483647,
|
||||||
|
}}
|
||||||
|
>
|
||||||
|
<Pointer
|
||||||
|
direction="TopLeft"
|
||||||
|
style={{
|
||||||
|
transform: `translate(${lineWidth}px, ${lineWidth}px)`,
|
||||||
|
cursor: "nw-resize",
|
||||||
|
}}
|
||||||
|
{...opts}
|
||||||
|
/>
|
||||||
|
<Pointer
|
||||||
|
direction="Top"
|
||||||
|
style={{
|
||||||
|
margin: `0 ${lineWidth}px`,
|
||||||
|
transform: `translate(0px, ${lineWidth}px)`,
|
||||||
|
cursor: "row-resize",
|
||||||
|
}}
|
||||||
|
{...opts}
|
||||||
|
/>
|
||||||
|
<Pointer
|
||||||
|
direction="TopRight"
|
||||||
|
style={{
|
||||||
|
transform: `translate(-${lineWidth}px, ${lineWidth}px)`,
|
||||||
|
cursor: "ne-resize",
|
||||||
|
}}
|
||||||
|
{...opts}
|
||||||
|
/>
|
||||||
|
<Pointer
|
||||||
|
direction="Left"
|
||||||
|
style={{
|
||||||
|
margin: `${lineWidth}px 0`,
|
||||||
|
transform: `translate(${lineWidth}px, 0px)`,
|
||||||
|
cursor: "col-resize",
|
||||||
|
}}
|
||||||
|
{...opts}
|
||||||
|
/>
|
||||||
|
<Paper elevation={4}>
|
||||||
|
<Pointer direction="Header" style={{ cursor: "move" }} {...opts}>
|
||||||
|
{header}
|
||||||
|
</Pointer>
|
||||||
|
<div
|
||||||
|
style={{
|
||||||
|
width: size.w,
|
||||||
|
height: size.h,
|
||||||
|
overflow: "hidden auto",
|
||||||
|
}}
|
||||||
|
>
|
||||||
|
{children}
|
||||||
|
</div>
|
||||||
|
</Paper>
|
||||||
|
<Pointer
|
||||||
|
direction="Right"
|
||||||
|
style={{
|
||||||
|
margin: `${lineWidth}px 0`,
|
||||||
|
transform: `translate(-${lineWidth}px, 0px)`,
|
||||||
|
cursor: "col-resize",
|
||||||
|
}}
|
||||||
|
{...opts}
|
||||||
|
/>
|
||||||
|
<Pointer
|
||||||
|
direction="BottomLeft"
|
||||||
|
style={{
|
||||||
|
transform: `translate(${lineWidth}px, -${lineWidth}px)`,
|
||||||
|
cursor: "ne-resize",
|
||||||
|
}}
|
||||||
|
{...opts}
|
||||||
|
/>
|
||||||
|
<Pointer
|
||||||
|
direction="Bottom"
|
||||||
|
style={{
|
||||||
|
margin: `0 ${lineWidth}px`,
|
||||||
|
transform: `translate(0px, -${lineWidth}px)`,
|
||||||
|
cursor: "row-resize",
|
||||||
|
}}
|
||||||
|
{...opts}
|
||||||
|
/>
|
||||||
|
<Pointer
|
||||||
|
direction="BottomRight"
|
||||||
|
style={{
|
||||||
|
transform: `translate(-${lineWidth}px, -${lineWidth}px)`,
|
||||||
|
cursor: "nw-resize",
|
||||||
|
}}
|
||||||
|
{...opts}
|
||||||
|
/>
|
||||||
|
</Box>
|
||||||
|
);
|
||||||
|
}
|
||||||
132
src/views/Selection/TranCont.js
Normal file
132
src/views/Selection/TranCont.js
Normal file
@@ -0,0 +1,132 @@
|
|||||||
|
import TextField from "@mui/material/TextField";
|
||||||
|
import Box from "@mui/material/Box";
|
||||||
|
import Alert from "@mui/material/Alert";
|
||||||
|
import CircularProgress from "@mui/material/CircularProgress";
|
||||||
|
import Chip from "@mui/material/Chip";
|
||||||
|
import Stack from "@mui/material/Stack";
|
||||||
|
import { useI18n } from "../../hooks/I18n";
|
||||||
|
import { DEFAULT_TRANS_APIS, OPT_TRANS_BAIDU } from "../../config";
|
||||||
|
import { useEffect, useState } from "react";
|
||||||
|
import { apiTranslate } from "../../apis";
|
||||||
|
import { isValidWord } from "../../libs/utils";
|
||||||
|
|
||||||
|
const exchangeMap = {
|
||||||
|
word_third: "第三人称单数",
|
||||||
|
word_ing: "现在分词",
|
||||||
|
word_done: "过去式",
|
||||||
|
word_past: "过去分词",
|
||||||
|
word_pl: "复数",
|
||||||
|
word_proto: "原词",
|
||||||
|
};
|
||||||
|
|
||||||
|
function DictCont({ dictResult }) {
|
||||||
|
if (!dictResult) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
return (
|
||||||
|
<Box>
|
||||||
|
<div style={{ fontWeight: "bold" }}>
|
||||||
|
{dictResult.simple_means?.word_name}
|
||||||
|
</div>
|
||||||
|
{dictResult.simple_means?.symbols?.map(({ ph_en, ph_am, parts }, idx) => (
|
||||||
|
<div key={idx}>
|
||||||
|
<div>{`英[${ph_en}] 美[${ph_am}]`}</div>
|
||||||
|
<ul style={{ margin: "0.5em 0" }}>
|
||||||
|
{parts.map(({ part, means }, idx) => (
|
||||||
|
<li key={idx}>
|
||||||
|
{part ? `[${part}] ${means.join("; ")}` : means.join("; ")}
|
||||||
|
</li>
|
||||||
|
))}
|
||||||
|
</ul>
|
||||||
|
</div>
|
||||||
|
))}
|
||||||
|
<div>
|
||||||
|
{Object.entries(dictResult.simple_means?.exchange || {})
|
||||||
|
.map(([key, val]) => `${exchangeMap[key] || key}: ${val.join(", ")}`)
|
||||||
|
.join("; ")}
|
||||||
|
</div>
|
||||||
|
<Stack direction="row" spacing={1}>
|
||||||
|
{Object.values(dictResult.simple_means?.tags || {})
|
||||||
|
.flat()
|
||||||
|
.filter((item) => item)
|
||||||
|
.map((item) => (
|
||||||
|
<Chip label={item} size="small" />
|
||||||
|
))}
|
||||||
|
</Stack>
|
||||||
|
</Box>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
export default function TranCont({
|
||||||
|
text,
|
||||||
|
translator,
|
||||||
|
fromLang,
|
||||||
|
toLang,
|
||||||
|
transApis,
|
||||||
|
}) {
|
||||||
|
const i18n = useI18n();
|
||||||
|
const [trText, setTrText] = useState("");
|
||||||
|
const [loading, setLoading] = useState(false);
|
||||||
|
const [error, setError] = useState("");
|
||||||
|
const [dictResult, setDictResult] = useState(null);
|
||||||
|
|
||||||
|
useEffect(() => {
|
||||||
|
(async () => {
|
||||||
|
try {
|
||||||
|
setLoading(true);
|
||||||
|
setTrText("");
|
||||||
|
setError("");
|
||||||
|
setDictResult(null);
|
||||||
|
|
||||||
|
const apis = { ...transApis, ...DEFAULT_TRANS_APIS };
|
||||||
|
const apiSetting = apis[translator];
|
||||||
|
const tranRes = await apiTranslate({
|
||||||
|
text,
|
||||||
|
translator,
|
||||||
|
fromLang,
|
||||||
|
toLang,
|
||||||
|
apiSetting,
|
||||||
|
});
|
||||||
|
setTrText(tranRes[0]);
|
||||||
|
|
||||||
|
// 词典
|
||||||
|
if (isValidWord(text) && toLang.startsWith("zh")) {
|
||||||
|
if (fromLang === "en" && translator === OPT_TRANS_BAIDU) {
|
||||||
|
setDictResult(tranRes[2].dict_result);
|
||||||
|
} else {
|
||||||
|
const dictRes = await apiTranslate({
|
||||||
|
text,
|
||||||
|
translator: OPT_TRANS_BAIDU,
|
||||||
|
fromLang: "en",
|
||||||
|
toLang: "zh-CN",
|
||||||
|
apiSetting: apis[OPT_TRANS_BAIDU],
|
||||||
|
});
|
||||||
|
setDictResult(dictRes[2].dict_result);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
} catch (err) {
|
||||||
|
setError(err.message);
|
||||||
|
} finally {
|
||||||
|
setLoading(false);
|
||||||
|
}
|
||||||
|
})();
|
||||||
|
}, [text, translator, fromLang, toLang, transApis]);
|
||||||
|
|
||||||
|
return (
|
||||||
|
<>
|
||||||
|
<Box>
|
||||||
|
<TextField
|
||||||
|
label={i18n("translated_text")}
|
||||||
|
fullWidth
|
||||||
|
multiline
|
||||||
|
value={trText}
|
||||||
|
/>
|
||||||
|
</Box>
|
||||||
|
|
||||||
|
{loading && <CircularProgress size={24} />}
|
||||||
|
{error && <Alert severity="error">{error}</Alert>}
|
||||||
|
{dictResult && <DictCont dictResult={dictResult} />}
|
||||||
|
</>
|
||||||
|
);
|
||||||
|
}
|
||||||
162
src/views/Selection/Tranbox.js
Normal file
162
src/views/Selection/Tranbox.js
Normal file
@@ -0,0 +1,162 @@
|
|||||||
|
import { SettingProvider } from "../../hooks/Setting";
|
||||||
|
import ThemeProvider from "../../hooks/Theme";
|
||||||
|
import DraggableResizable from "./DraggableResizable";
|
||||||
|
import Header from "../Popup/Header";
|
||||||
|
import Stack from "@mui/material/Stack";
|
||||||
|
import TextField from "@mui/material/TextField";
|
||||||
|
import MenuItem from "@mui/material/MenuItem";
|
||||||
|
import Grid from "@mui/material/Grid";
|
||||||
|
import Box from "@mui/material/Box";
|
||||||
|
import Divider from "@mui/material/Divider";
|
||||||
|
import { useI18n } from "../../hooks/I18n";
|
||||||
|
import { OPT_TRANS_ALL, OPT_LANGS_FROM, OPT_LANGS_TO } from "../../config";
|
||||||
|
import { useState, useRef } from "react";
|
||||||
|
import TranCont from "./TranCont";
|
||||||
|
|
||||||
|
function TranForm({ text, setText, tranboxSetting, transApis }) {
|
||||||
|
const i18n = useI18n();
|
||||||
|
|
||||||
|
const [editMode, setEditMode] = useState(false);
|
||||||
|
const [editText, setEditText] = useState("");
|
||||||
|
const [translator, setTranslator] = useState(tranboxSetting.translator);
|
||||||
|
const [fromLang, setFromLang] = useState(tranboxSetting.fromLang);
|
||||||
|
const [toLang, setToLang] = useState(tranboxSetting.toLang);
|
||||||
|
const inputRef = useRef(null);
|
||||||
|
|
||||||
|
return (
|
||||||
|
<Stack sx={{ p: 2 }} spacing={2}>
|
||||||
|
<Box>
|
||||||
|
<Grid container spacing={2} columns={12}>
|
||||||
|
<Grid item xs={4} sm={4} md={4} lg={4}>
|
||||||
|
<TextField
|
||||||
|
select
|
||||||
|
SelectProps={{ MenuProps: { disablePortal: true } }}
|
||||||
|
fullWidth
|
||||||
|
size="small"
|
||||||
|
name="fromLang"
|
||||||
|
value={fromLang}
|
||||||
|
label={i18n("from_lang")}
|
||||||
|
onChange={(e) => {
|
||||||
|
setFromLang(e.target.value);
|
||||||
|
}}
|
||||||
|
>
|
||||||
|
{OPT_LANGS_FROM.map(([lang, name]) => (
|
||||||
|
<MenuItem key={lang} value={lang}>
|
||||||
|
{name}
|
||||||
|
</MenuItem>
|
||||||
|
))}
|
||||||
|
</TextField>
|
||||||
|
</Grid>
|
||||||
|
<Grid item xs={4} sm={4} md={4} lg={4}>
|
||||||
|
<TextField
|
||||||
|
select
|
||||||
|
SelectProps={{ MenuProps: { disablePortal: true } }}
|
||||||
|
fullWidth
|
||||||
|
size="small"
|
||||||
|
name="toLang"
|
||||||
|
value={toLang}
|
||||||
|
label={i18n("to_lang")}
|
||||||
|
onChange={(e) => {
|
||||||
|
setToLang(e.target.value);
|
||||||
|
}}
|
||||||
|
>
|
||||||
|
{OPT_LANGS_TO.map(([lang, name]) => (
|
||||||
|
<MenuItem key={lang} value={lang}>
|
||||||
|
{name}
|
||||||
|
</MenuItem>
|
||||||
|
))}
|
||||||
|
</TextField>
|
||||||
|
</Grid>
|
||||||
|
<Grid item xs={4} sm={4} md={4} lg={4}>
|
||||||
|
<TextField
|
||||||
|
select
|
||||||
|
SelectProps={{ MenuProps: { disablePortal: true } }}
|
||||||
|
fullWidth
|
||||||
|
size="small"
|
||||||
|
value={translator}
|
||||||
|
name="translator"
|
||||||
|
label={i18n("translate_service")}
|
||||||
|
onChange={(e) => {
|
||||||
|
setTranslator(e.target.value);
|
||||||
|
}}
|
||||||
|
>
|
||||||
|
{OPT_TRANS_ALL.map((item) => (
|
||||||
|
<MenuItem key={item} value={item}>
|
||||||
|
{item}
|
||||||
|
</MenuItem>
|
||||||
|
))}
|
||||||
|
</TextField>
|
||||||
|
</Grid>
|
||||||
|
</Grid>
|
||||||
|
</Box>
|
||||||
|
|
||||||
|
<Box>
|
||||||
|
<TextField
|
||||||
|
label={i18n("original_text")}
|
||||||
|
inputRef={inputRef}
|
||||||
|
fullWidth
|
||||||
|
multiline
|
||||||
|
value={editMode ? editText : text}
|
||||||
|
disabled={!editMode}
|
||||||
|
onChange={(e) => {
|
||||||
|
setEditText(e.target.value);
|
||||||
|
}}
|
||||||
|
onClick={() => {
|
||||||
|
setEditMode(true);
|
||||||
|
setEditText(text);
|
||||||
|
const timer = setTimeout(() => {
|
||||||
|
clearTimeout(timer);
|
||||||
|
inputRef.current?.focus();
|
||||||
|
}, 100);
|
||||||
|
}}
|
||||||
|
onBlur={() => {
|
||||||
|
setEditMode(false);
|
||||||
|
setText(editText.trim());
|
||||||
|
}}
|
||||||
|
/>
|
||||||
|
</Box>
|
||||||
|
|
||||||
|
<TranCont
|
||||||
|
text={text}
|
||||||
|
translator={translator}
|
||||||
|
fromLang={fromLang}
|
||||||
|
toLang={toLang}
|
||||||
|
transApis={transApis}
|
||||||
|
/>
|
||||||
|
</Stack>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
export default function TranBox({
|
||||||
|
text,
|
||||||
|
setText,
|
||||||
|
setShowBox,
|
||||||
|
tranboxSetting,
|
||||||
|
transApis,
|
||||||
|
boxSize,
|
||||||
|
setBoxSize,
|
||||||
|
boxPosition,
|
||||||
|
setBoxPosition,
|
||||||
|
}) {
|
||||||
|
return (
|
||||||
|
<SettingProvider>
|
||||||
|
<ThemeProvider>
|
||||||
|
<DraggableResizable
|
||||||
|
defaultPosition={boxPosition}
|
||||||
|
defaultSize={boxSize}
|
||||||
|
header={<Header setShowPopup={setShowBox} />}
|
||||||
|
onChangeSize={setBoxSize}
|
||||||
|
onChangePosition={setBoxPosition}
|
||||||
|
>
|
||||||
|
<Divider />
|
||||||
|
<TranForm
|
||||||
|
text={text}
|
||||||
|
setText={setText}
|
||||||
|
tranboxSetting={tranboxSetting}
|
||||||
|
transApis={transApis}
|
||||||
|
/>
|
||||||
|
</DraggableResizable>
|
||||||
|
</ThemeProvider>
|
||||||
|
</SettingProvider>
|
||||||
|
);
|
||||||
|
}
|
||||||
36
src/views/Selection/Tranbtn.js
Normal file
36
src/views/Selection/Tranbtn.js
Normal file
@@ -0,0 +1,36 @@
|
|||||||
|
export default function TranBtn({ onClick, position, tranboxSetting }) {
|
||||||
|
return (
|
||||||
|
<div
|
||||||
|
style={{
|
||||||
|
cursor: "pointer",
|
||||||
|
position: "fixed",
|
||||||
|
left: position.x + tranboxSetting.btnOffsetX,
|
||||||
|
top: position.y + tranboxSetting.btnOffsetY,
|
||||||
|
zIndex: 2147483647,
|
||||||
|
}}
|
||||||
|
onClick={onClick}
|
||||||
|
onMouseUp={(e) => {
|
||||||
|
e.stopPropagation();
|
||||||
|
}}
|
||||||
|
>
|
||||||
|
<svg
|
||||||
|
xmlns="http://www.w3.org/2000/svg"
|
||||||
|
width="20"
|
||||||
|
height="20"
|
||||||
|
viewBox="0 0 32 32"
|
||||||
|
version="1.1"
|
||||||
|
>
|
||||||
|
<path
|
||||||
|
d="M0 0 C10.56 0 21.12 0 32 0 C32 10.56 32 21.12 32 32 C21.44 32 10.88 32 0 32 C0 21.44 0 10.88 0 0 Z "
|
||||||
|
fill="#209CEE"
|
||||||
|
transform="translate(0,0)"
|
||||||
|
/>
|
||||||
|
<path
|
||||||
|
d="M0 0 C0.66 0 1.32 0 2 0 C2 2.97 2 5.94 2 9 C2.969375 8.2575 3.93875 7.515 4.9375 6.75 C5.48277344 6.33234375 6.02804688 5.9146875 6.58984375 5.484375 C8.39053593 3.83283924 8.39053593 3.83283924 9 0 C13.95 0 18.9 0 24 0 C24 0.99 24 1.98 24 3 C22.68 3 21.36 3 20 3 C20 9.27 20 15.54 20 22 C19.01 22 18.02 22 17 22 C17 15.73 17 9.46 17 3 C15.35 3 13.7 3 12 3 C11.731875 3.598125 11.46375 4.19625 11.1875 4.8125 C10.01506533 6.97224808 8.80630718 8.35790256 7 10 C8.01790655 12.27071461 8.77442829 13.80784632 10.6875 15.4375 C11.120625 15.953125 11.55375 16.46875 12 17 C11.6875 19.6875 11.6875 19.6875 11 22 C10.34 22 9.68 22 9 22 C8.773125 21.236875 8.54625 20.47375 8.3125 19.6875 C6.73268318 16.45263699 5.16717283 15.58358642 2 14 C2 16.64 2 19.28 2 22 C1.34 22 0.68 22 0 22 C0 14.74 0 7.48 0 0 Z "
|
||||||
|
fill="#E9F5FD"
|
||||||
|
transform="translate(4,5)"
|
||||||
|
/>
|
||||||
|
</svg>
|
||||||
|
</div>
|
||||||
|
);
|
||||||
|
}
|
||||||
85
src/views/Selection/index.js
Normal file
85
src/views/Selection/index.js
Normal file
@@ -0,0 +1,85 @@
|
|||||||
|
import { useState, useEffect } from "react";
|
||||||
|
import TranBtn from "./Tranbtn";
|
||||||
|
import TranBox from "./Tranbox";
|
||||||
|
import { shortcutRegister } from "../../libs/shortcut";
|
||||||
|
|
||||||
|
export default function Slection({ tranboxSetting, transApis }) {
|
||||||
|
const [showBox, setShowBox] = useState(false);
|
||||||
|
const [showBtn, setShowBtn] = useState(false);
|
||||||
|
const [selectedText, setSelText] = useState("");
|
||||||
|
const [text, setText] = useState("");
|
||||||
|
const [position, setPosition] = useState({ x: 0, y: 0 });
|
||||||
|
const [boxSize, setBoxSize] = useState({ w: 600, h: 400 });
|
||||||
|
const [boxPosition, setBoxPosition] = useState({
|
||||||
|
x: (window.innerWidth - 600) / 2,
|
||||||
|
y: (window.innerHeight - 400) / 2,
|
||||||
|
});
|
||||||
|
|
||||||
|
function handleMouseup(e) {
|
||||||
|
const selectedText = window.getSelection()?.toString()?.trim() || "";
|
||||||
|
if (!selectedText) {
|
||||||
|
setShowBtn(false);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
setSelText(selectedText);
|
||||||
|
setShowBtn(true);
|
||||||
|
setPosition({ x: e.clientX, y: e.clientY });
|
||||||
|
}
|
||||||
|
|
||||||
|
const handleClick = (e) => {
|
||||||
|
e.stopPropagation();
|
||||||
|
setShowBtn(false);
|
||||||
|
|
||||||
|
setText(selectedText);
|
||||||
|
if (!showBox) {
|
||||||
|
setShowBox(true);
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
useEffect(() => {
|
||||||
|
window.addEventListener("mouseup", handleMouseup);
|
||||||
|
return () => {
|
||||||
|
window.removeEventListener("mouseup", handleMouseup);
|
||||||
|
};
|
||||||
|
}, []);
|
||||||
|
|
||||||
|
useEffect(() => {
|
||||||
|
const clearShortcut = shortcutRegister(
|
||||||
|
tranboxSetting.tranboxShortcut,
|
||||||
|
() => {
|
||||||
|
setShowBox((pre) => !pre);
|
||||||
|
}
|
||||||
|
);
|
||||||
|
|
||||||
|
return () => {
|
||||||
|
clearShortcut();
|
||||||
|
};
|
||||||
|
}, [tranboxSetting.tranboxShortcut, setShowBox]);
|
||||||
|
|
||||||
|
return (
|
||||||
|
<>
|
||||||
|
{showBox && (
|
||||||
|
<TranBox
|
||||||
|
text={text}
|
||||||
|
setText={setText}
|
||||||
|
boxSize={boxSize}
|
||||||
|
setBoxSize={setBoxSize}
|
||||||
|
boxPosition={boxPosition}
|
||||||
|
setBoxPosition={setBoxPosition}
|
||||||
|
tranboxSetting={tranboxSetting}
|
||||||
|
transApis={transApis}
|
||||||
|
setShowBox={setShowBox}
|
||||||
|
/>
|
||||||
|
)}
|
||||||
|
|
||||||
|
{showBtn && (
|
||||||
|
<TranBtn
|
||||||
|
position={position}
|
||||||
|
tranboxSetting={tranboxSetting}
|
||||||
|
onClick={handleClick}
|
||||||
|
/>
|
||||||
|
)}
|
||||||
|
</>
|
||||||
|
);
|
||||||
|
}
|
||||||
Reference in New Issue
Block a user