Compare commits

..

427 Commits

Author SHA1 Message Date
Gabe
2650e5cf7c Update version number: 2.0.12 2025-11-22 21:17:06 +08:00
Gabe
da1fa3e8ed fix: clean content html 2025-11-22 21:16:35 +08:00
Gabe
e256314d4f fix: add context for setting provider 2025-11-22 18:15:07 +08:00
Gabe
f8f7d5955f fix: handle mouseup (#400) 2025-11-22 17:24:02 +08:00
Gabe
fa6f68fec3 fix: add global context type 2025-11-22 01:36:03 +08:00
Gabe
0705e8a65a fix: add baidu audio for youdao dict 2025-11-22 00:20:58 +08:00
Gabe
9d9bbd3821 fix: throw hook error 2025-11-20 22:27:27 +08:00
Gabe
86a312ea6b fix: runtime oninstalled 2025-11-20 17:36:02 +08:00
Gabe
e4771e795b fix: Trigger shortcut key when keyup (#410) 2025-11-20 17:30:55 +08:00
Gabe
1504830142 fix: content does not render elements during loading 2025-11-20 16:33:49 +08:00
XYenon
7e99bc7aad fix: restore context menu configuration after extension update (#408) 2025-11-19 20:03:08 +08:00
Gabe
abca8cb26d fix: default select style 2025-11-16 21:59:01 +08:00
Gabe
d032088415 Update version number: 2.0.11 2025-11-16 21:00:39 +08:00
Gabe
80fb26ad48 doc: update readme 2025-11-16 20:58:20 +08:00
Gabe
017db589d4 feat: add more languages for quotes 2025-11-16 20:51:25 +08:00
Gabe
6e1b842bba fix: query tagname bug 2025-11-16 19:18:54 +08:00
Gabe
0c04ea3a33 fix: skip running in document content types 2025-11-16 15:00:49 +08:00
Gabe
c21ac1aea6 doc: update readme links 2025-11-15 23:23:27 +08:00
Gabe
864e0651b1 fix: set pnpm version 2025-11-15 22:37:26 +08:00
Gabe
65d328eb38 Update version number: 2.0.10 2025-11-15 22:30:17 +08:00
Gabe
731d360323 fix: unavailable action log 2025-11-15 21:09:24 +08:00
Gabe
c4ccdba268 fix: sync bug 2025-11-15 21:05:06 +08:00
Gabe
4f00492e49 fix: Adjust popup UI 2025-11-15 14:39:03 +08:00
Gabe
abcf2baad6 feat: supports plain text translation 2025-11-15 14:25:05 +08:00
Gabe
49a7698993 fix: update ignore selectors 2025-11-15 01:08:17 +08:00
Gabe
8d2548acaf doc: i18n 2025-11-15 00:41:58 +08:00
Gabe
251deb5886 fix: notice text 2025-11-13 01:49:51 +08:00
Gabe
7a15bdeadc fix: from lang bug 2025-11-13 01:45:11 +08:00
Gabe
1e59d57764 fix: from lang bug 2025-11-13 01:38:16 +08:00
Gabe
12b3768598 doc: readme 2025-11-13 00:14:00 +08:00
Gabe
3abe5b98d0 doc: readme 2025-11-12 23:54:27 +08:00
Gabe
ad004105c3 fix: Solidified build environment 2025-11-12 23:38:29 +08:00
Gabe
f70266197e fix: Solidified build environment 2025-11-12 23:37:40 +08:00
Gabe
cc31a8004a fix: try fix workflows error 2025-11-12 23:14:31 +08:00
Gabe
fa14851596 fix: try fix workflows error 2025-11-12 23:08:08 +08:00
Gabe
d56c46e944 Update version number: 2.0.9 2025-11-12 22:25:59 +08:00
Gabe
9f8bcf1fe1 feat: Added Japanese and Korean language support 2025-11-12 21:41:29 +08:00
Gabe
e50387a796 fix: custom apis 2025-11-12 00:56:27 +08:00
Gabe
3d2eac8772 fix: save rule bug 2025-11-12 00:13:41 +08:00
Gabe
343f529cac fix: Optimize subtitle translation 2025-11-11 23:36:06 +08:00
Gabe
3bfa12b61c Update version number: 2.0.8 2025-11-10 01:17:20 +08:00
Gabe
79bd776ef9 fix: format 2025-11-10 01:15:54 +08:00
Gabe
222428ad47 feat: pre translate time 2025-11-10 01:08:09 +08:00
Gabe
4b3853dd22 fix: download subtitle 2025-11-10 00:35:30 +08:00
Gabe
9dd191902c fix: update dependencies 2025-11-10 00:30:37 +08:00
Gabe
3f524ad674 feat: supports download subtitle 2025-11-10 00:21:07 +08:00
Gabe
7e6376fcb7 fix: rules 2025-11-07 23:40:20 +08:00
Gabe
6f35013faf fix: split pattern (#384) 2025-11-07 21:31:11 +08:00
Gabe
e71acdaaa9 fix: truncate doc title 2025-11-07 00:25:25 +08:00
Gabe
fd7c663282 feat: Restore CSS injection functionality 2025-11-06 23:33:49 +08:00
Gabe
89b2bbe9ac fix: tone error (#382) 2025-11-06 20:15:15 +08:00
Gabe
7eb64a463b Update version number: 2.0.7 2025-11-05 23:26:12 +08:00
Gabe
8971a28abc fix: html font size (#378) 2025-11-05 23:15:40 +08:00
Gabe
2ff989429f doc: i18n 2025-11-05 22:08:44 +08:00
Gabe
24369e2581 fix: Some element tagnames are lowercase. (#377) 2025-11-05 21:41:18 +08:00
Gabe
2bb8a5182c fix: Some element tagnames are lowercase. (#377) 2025-11-05 20:48:12 +08:00
Gabe
629bf9461a fix: AI language code 2025-11-05 01:03:44 +08:00
Gabe
a56fb6c8d6 Update version number: 2.0.6 2025-11-04 23:32:59 +08:00
Gabe
efb3529c92 Update version number: 2.0.6 2025-11-04 23:27:21 +08:00
Gabe
a372a4173c doc: reamde 2025-11-04 22:56:31 +08:00
Gabe
5e46832548 fix: i18n 2025-11-04 22:26:01 +08:00
Gabe
91869c42e1 feat: add more styles 2025-11-04 22:21:26 +08:00
Gabe
d421748bed fix: rules 2025-11-04 22:02:42 +08:00
Gabe
7e5cd7e5a6 feat: supports Persian language 2025-11-04 21:55:50 +08:00
Gabe
2b910b2c47 feat: Supports setting multiple custom styles 2025-11-04 21:22:38 +08:00
Gabe
814ce4ca11 feat: add text additional styles to rule 2025-11-03 19:01:57 +08:00
Gabe
1e63fd1e19 fix: transbox class 2025-11-03 18:44:49 +08:00
Gabe
4b19902e5c fix: translation hooks and custom api doc 2025-11-03 18:42:47 +08:00
Gabe
fd014a1d34 fix: change default httptimeout 2025-11-03 01:15:47 +08:00
Gabe
fd91bcf603 fix: Reset fontsize when the fontsize of the html element is changed. (#348) 2025-11-02 23:37:04 +08:00
Gabe
61a4a8f920 fix: styles 2025-11-02 00:27:46 +08:00
Gabe
ed4275a18b opt: Optimize subtitle processing logic 2025-11-02 00:15:38 +08:00
Gabe
7481d65e1e opt: Optimize subtitle processing logic 2025-11-02 00:10:01 +08:00
Gabe
0c49cf1af9 opt: Optimize subtitle processing logic 2025-11-02 00:04:46 +08:00
Gabe
7f04000739 opt: Optimize subtitle processing logic 2025-11-01 23:43:23 +08:00
Gabe
e3da9824b6 fix: subtitle bug 2025-11-01 22:54:45 +08:00
Gabe
34370345cd fix: parse subtitle time string 2025-11-01 22:45:08 +08:00
Gabe
6c1a4e851c fix: styles 2025-11-01 15:25:40 +08:00
Gabe
766e3ce7f9 feat: add more styles 2025-11-01 15:10:39 +08:00
Gabe
30c2cca2e1 Update version number: 2.0.5 2025-10-31 23:14:01 +08:00
Gabe
af3241b773 doc: readme 2025-10-31 23:12:27 +08:00
Gabe
eca0a63273 fix: subtitle 2025-10-31 20:23:58 +08:00
Gabe
f15cdb38d6 fix: put rule can write different pattern (#367) 2025-10-31 15:33:56 +08:00
Gabe
5b8577aaa7 doc: readme 2025-10-31 14:42:55 +08:00
Gabe
0a4a2b46c1 feat: support ai model with no batch 2025-10-31 14:36:33 +08:00
Gabe
53d441b3f5 doc: readme 2025-10-31 11:25:43 +08:00
Gabe
d4c346e40a fix: Increase the Max Tokens limit 2025-10-31 10:42:08 +08:00
Gabe
2dcacf71e4 fix: apitranslate bug 2025-10-31 10:25:53 +08:00
Gabe
9ded6446a7 fix: input translate 2025-10-31 10:05:01 +08:00
Gabe
0a6f4a9f02 fix: input translate (#342) 2025-10-31 01:39:27 +08:00
Gabe
635e588bcc fix: skip builtin ignore selector when autoscan disabled 2025-10-31 00:22:26 +08:00
Gabe
7343db78a5 fix: iframe bugs 2025-10-30 22:02:43 +08:00
Gabe
ccd457c992 fix: iframe bugs 2025-10-30 22:01:08 +08:00
Gabe
97676f114e fix: remove tink from ollama 2025-10-30 20:07:01 +08:00
Gabe
e83c1eb017 fix: throw error msg 2025-10-30 19:42:00 +08:00
Gabe
e417c0106a fix: change default fetchLimit 2025-10-30 19:10:07 +08:00
Gabe
3c09840d35 feat: can set rootMargin for IntersectionObserver. 2025-10-30 01:05:13 +08:00
Gabe
7361a94f8c feat: can set rootMargin for IntersectionObserver. 2025-10-30 01:03:46 +08:00
Gabe
a9bffe3913 feat: can set rootMargin for IntersectionObserver. 2025-10-30 00:55:17 +08:00
Gabe
5322555eba feat: can set whether skip ads. 2025-10-30 00:31:17 +08:00
Gabe
172dce2867 fix: hooks & injectjs 2025-10-30 00:19:13 +08:00
Gabe
5735fee36e fix: set main width 100% 2025-10-28 00:45:10 +08:00
Gabe
91642d8784 feat: support subtitle dragable on mobile 2025-10-28 00:36:38 +08:00
Gabe
9d8f3f4211 feat: add shadowroot injector 2025-10-28 00:07:44 +08:00
Gabe
66d39da80a fix: check io.observe must be element 2025-10-27 20:45:22 +08:00
Gabe
fbd4a31a9c fix: ignore script ellement 2025-10-27 20:00:05 +08:00
Gabe
3d7e03ddaf Update version number: 2.0.4 2025-10-26 20:26:52 +08:00
Gabe
1f213bf257 fix: styles 2025-10-26 20:10:13 +08:00
Gabe
b38f079611 fix: change showNotification duration 2025-10-26 19:59:51 +08:00
Gabe
21e639cacd fix: createMutationObserver 2025-10-26 18:42:59 +08:00
Gabe
bdaf665b7c feat: The translation box can be set to adaptive height 2025-10-26 16:18:56 +08:00
Gabe
61a515c1d2 feat: Support multi-touch selection 2025-10-26 00:06:52 +08:00
Gabe
1b646df908 feat: Remember the tranbox position and size 2025-10-25 23:18:39 +08:00
Gabe
5550f939b2 doc: readme 2025-10-25 18:41:20 +08:00
Gabe
b34fb5a600 doc: readme 2025-10-25 18:38:55 +08:00
Gabe
c0dce5c0b1 fix: Optimized text scanning logic 2025-10-25 17:46:29 +08:00
Gabe
d56bd2920f fix: isQualityPoor 2025-10-24 21:44:54 +08:00
Gabe
48ad100a64 fix: Optimized the scan node logic 2025-10-24 21:37:26 +08:00
Gabe
ef07a172a9 doc: custom api 2025-10-24 20:58:08 +08:00
Gabe
f492d47719 fix: disable field of rule 2025-10-24 20:57:10 +08:00
Gabe
ac8c07deb4 fix: keepselector for twitter 2025-10-24 01:46:36 +08:00
Gabe
ca48ab639e fix: remove stopPropagation for shortcut 2025-10-23 19:52:18 +08:00
Gabe
7c5232c1a1 fix: Make keepSelector effective even if richText is disabled 2025-10-23 19:32:59 +08:00
Gabe
4fac7fdfe1 fix: update custom api 2025-10-23 14:35:21 +08:00
Gabe
f7fc9560d5 fix: update custom api 2025-10-23 14:33:12 +08:00
Gabe
f7ba744e7f fix: ignore selector 2025-10-23 11:07:25 +08:00
Gabe
315164f142 fix: remove logger 2025-10-22 22:34:55 +08:00
Gabe
429cab5223 Update version number: 2.0.3 2025-10-22 22:27:17 +08:00
Gabe
deecbc874b fix: Adapt to the new UI of youtube 2025-10-22 21:39:17 +08:00
Gabe
504f4cafa0 fix: Adapt to the new UI of youtube 2025-10-22 21:14:39 +08:00
Gabe
6d327d17af fix: mousehover translate (close #331) 2025-10-22 21:01:23 +08:00
Gabe
74290eb52b fix: rules 2025-10-22 01:56:47 +08:00
Gabe
60b9653fd3 feat: more touch operations 2025-10-22 01:50:49 +08:00
Gabe
53e32d3031 refactor: add TranslatorManager 2025-10-21 02:07:33 +08:00
Gabe
ed279cf8a1 fix: highlight fav words 2025-10-19 01:28:29 +08:00
Gabe
296b898bda fix: disable preventDefault in shrotcut 2025-10-19 00:42:13 +08:00
Gabe
2325155b1e feat: highlight fav words && split long paragraph 2025-10-19 00:19:47 +08:00
Gabe
b6ff4aae6a docs: custom api 2025-10-18 11:34:16 +08:00
Gabe
f04002fdb8 fix: ycombinator.com rule 2025-10-18 00:37:55 +08:00
Gabe
b8cb254f56 perf: Optimized api find 2025-10-17 23:02:39 +08:00
Gabe
3983477904 fix: setting ui 2025-10-17 13:11:57 +08:00
Gabe
f011f5ae38 fix: api doc 2025-10-17 12:57:58 +08:00
Gabe
18ecab18df fix: api doc 2025-10-17 12:56:26 +08:00
Gabe
793c481221 fix: rules 2025-10-17 11:53:02 +08:00
Gabe
4fee3688ea fix: popup width change to 360 2025-10-17 10:53:13 +08:00
Gabe
b9693436bb Update version number: 2.0.2 2025-10-17 10:31:04 +08:00
Gabe
6b18d8f934 fix: rules 2025-10-17 10:20:42 +08:00
Gabe
65c325de9a fix: custom api example 2025-10-17 10:14:28 +08:00
Gabe
8da5aaf259 fix: add custom api example link 2025-10-17 10:01:02 +08:00
Gabe
00e8fdd3e6 fix: update custom api doc 2025-10-17 09:44:53 +08:00
Gabe
b2eea5d0d7 fix: custom api doc 2025-10-17 01:47:36 +08:00
Gabe
9a8e24f590 fix: sync rules, words 2025-10-17 01:19:24 +08:00
Gabe
32c6d45cb0 feat: add custom api examples 2025-10-16 23:51:49 +08:00
Gabe
74ce6f2f1f fix: youtube live caht rule 2025-10-16 21:29:58 +08:00
Gabe
573865cf10 fix: merge rules 2025-10-16 20:58:27 +08:00
Gabe
56d4733e2a feat: terms style 2025-10-16 20:16:03 +08:00
Gabe
a8965a01e3 fix: change some default setting 2025-10-16 19:35:28 +08:00
Gabe
beef51ef38 fix: default ignore selector 2025-10-16 01:25:52 +08:00
Gabe
b5b3ee8709 update version number: 2.0.1 2025-10-16 00:55:16 +08:00
Gabe
4f1e01dde0 feat: youtube ad skip 2025-10-15 23:58:57 +08:00
Gabe
d42ff51de5 feat: youtube ad skip 2025-10-15 23:44:45 +08:00
Gabe
c39861b7b7 fix: readme 2025-10-15 22:10:17 +08:00
Gabe
d39b9fd73e fix: api name in tranbox(Closes #322) 2025-10-15 22:04:03 +08:00
Gabe
ecab4ab634 feat: support subtitle translate for userscript 2025-10-15 21:41:09 +08:00
Gabe
5e67e15842 feat: clear caches in popup 2025-10-15 14:40:58 +08:00
Gabe
2af1a8b72c fix: remove retranslate subtitle code 2025-10-15 14:08:56 +08:00
Gabe
2510ed0ebb fix: shortcut(alt+tab) bug 2025-10-15 13:55:23 +08:00
XYenon
6827985289 feat: auto dark mode (#321) 2025-10-15 12:43:24 +08:00
Gabe
a095a2c01c fix: temperature limit float 2025-10-15 00:59:32 +08:00
Gabe
2033ff6777 fix: subtitle: retry translation failed 2025-10-14 23:45:30 +08:00
Gabe
0c22288833 Merge remote-tracking branch 'origin/dev' into dev 2025-10-14 23:37:30 +08:00
zxhzxhz
0576150067 Update BilingualSubtitleManager.js (#320)
fix translation style
2025-10-14 23:36:57 +08:00
Gabe
9cdcf616f7 fix: change innerHTML to trustedHTML 2025-10-14 23:36:28 +08:00
Gabe
2de10364f3 fix: try fix subtitle in userscript 2025-10-14 22:41:18 +08:00
Gabe
562559a1b0 update version number 2025-10-14 19:30:33 +08:00
Gabe
0f0b7313bb fix: styles 2025-10-14 19:15:53 +08:00
Gabe
412fc87d1e fix: bugs 2025-10-14 19:03:18 +08:00
Gabe
0a1abab475 fix: add notranslate class 2025-10-14 11:13:03 +08:00
Gabe
b63ef8c1aa fix: throw more errors in translate api 2025-10-14 10:31:49 +08:00
Gabe
c38a3d439d fix: readme 2025-10-13 23:53:34 +08:00
Gabe
dd395e668f fix blacklist 2025-10-13 23:46:04 +08:00
Gabe
8a5ef441f9 fix: rules 2025-10-13 23:32:14 +08:00
Gabe
d9acbe865f fix: rules 2025-10-13 23:26:29 +08:00
Gabe
dc35fef873 feat: add more styles 2025-10-13 22:15:42 +08:00
Gabe
4e9293ae0f fix: stubtitle 2025-10-13 14:15:14 +08:00
Gabe
36973b8693 fix: bing dict 2025-10-13 11:29:22 +08:00
Gabe
0ab734d1a5 fix: update readme 2025-10-13 00:54:02 +08:00
Gabe
bfce9b525a feat: support dynamically set log level 2025-10-12 23:17:50 +08:00
Gabe
f19b6ef02f fix: update readme 2025-10-12 15:40:37 +08:00
Gabe
1992908a85 fix: subtitle 2025-10-12 14:36:28 +08:00
Gabe
a6bcafa8f6 feat: subtitle can be draggleable 2025-10-12 14:16:26 +08:00
Gabe
eabcb06eeb fix: youtube rule 2025-10-12 12:37:29 +08:00
Gabe
21dcbfa4c4 fix: subtitle 2025-10-12 12:25:11 +08:00
Gabe
b6c074a242 fix: subtitle 2025-10-12 12:05:18 +08:00
Gabe
f6d095d533 fix: subtitle 2025-10-12 12:02:41 +08:00
Gabe
7a36251d3f fix: subtitle 2025-10-12 11:51:41 +08:00
Gabe
3fda4d0da9 fix: subtitle 2025-10-12 11:45:31 +08:00
Gabe
2fa8917d5e fix: subtitle 2025-10-12 02:57:45 +08:00
Gabe
67149af64b fix: number input 2025-10-12 02:19:25 +08:00
Gabe
0104cb9f29 feat: add notice for subtitle 2025-10-12 01:41:53 +08:00
Gabe
1afe976777 feat: support subtitle chunks for AI 2025-10-11 21:06:38 +08:00
Gabe
d9b4399c57 feat: support AzureAI 2025-10-11 14:46:14 +08:00
Gabe
ac7b3b9824 fix: switch button 2025-10-11 12:11:13 +08:00
Gabe
359206630d feat: add default styles example 2025-10-11 12:01:36 +08:00
Gabe
96dfee90ab fix: firefox bugs 2025-10-11 11:19:33 +08:00
Gabe
9ace600fce feat: support local html 2025-10-11 01:26:09 +08:00
Gabe
549b945d0f fix: svg 2025-10-11 00:19:48 +08:00
Gabe
4528a79c87 fix: svg 2025-10-11 00:15:10 +08:00
Gabe
951ce985b5 fix: batch queue 2025-10-10 23:07:18 +08:00
Gabe
001f04a9ee fix: subtitle 2025-10-10 21:17:51 +08:00
Gabe
3844d2eb75 fix: rules 2025-10-10 15:05:47 +08:00
Gabe
e593221e02 fix: i18n 2025-10-10 14:17:07 +08:00
Gabe
8cc3801dc5 fix: youtube rule 2025-10-10 13:59:17 +08:00
Gabe
251e57ec61 fix: subtitle 2025-10-10 13:49:04 +08:00
Gabe
769a4f00aa fix: bing dict 2025-10-10 00:08:38 +08:00
Gabe
9bafc937d5 feat: subtitle: support ai segmentation 2025-10-09 23:55:06 +08:00
Gabe
2d0ea09e06 fix: subtitle 2025-10-09 11:55:02 +08:00
Gabe
aeec5e361c fix: subtitle 2025-10-09 09:49:12 +08:00
Gabe
71b2d62c9f feat: format subtitle 2025-10-09 02:15:58 +08:00
Gabe
40b3072e5f fix: subtitles 2025-10-08 00:02:12 +08:00
Gabe
cae9338274 fix: subtitles 2025-10-08 00:01:22 +08:00
Gabe
4c2781b3b6 fix: gemini api 2025-10-07 21:10:51 +08:00
Gabe
b2b5bef9f5 feat: support subtitle translate 2025-10-07 16:35:00 +08:00
Gabe
df8c96569a fix: rename data to body 2025-10-05 17:47:29 +08:00
Gabe
e562f0b851 fix: youdao dict 2025-10-04 22:29:03 +08:00
Gabe
7b2b48f0d1 feat: support builtin AI 2025-10-04 21:25:54 +08:00
Gabe
c353c88db8 feat: support bing dict 2025-10-03 22:07:48 +08:00
Gabe
171dbb7509 feat: support youdao dict 2025-10-03 18:28:50 +08:00
Gabe
65e8fabe7d feat: add playground 2025-10-02 21:59:31 +08:00
Gabe
389f0b6f82 feat: Support for multiple translation services in tranbox 2025-10-02 11:33:33 +08:00
Gabe
039566ded5 fix: deeplfree api 2025-10-01 23:22:14 +08:00
Gabe
d18b31692b fix: Minimize the rule file 2025-10-01 22:46:55 +08:00
Gabe
c993c15c92 feat: support translate all now 2025-10-01 21:18:53 +08:00
Gabe
3c5ffc045f feat: support AI terms 2025-10-01 16:18:19 +08:00
Gabe
261bb7aa6f fix: placeholder 2025-10-01 15:35:20 +08:00
Gabe
96a7a41759 feat: support placeholder selection 2025-10-01 13:22:22 +08:00
Gabe
d563521eb1 feat: confirm_before clear rules 2025-10-01 12:30:58 +08:00
Gabe
a08c42db8b feat: add button tips 2025-10-01 12:08:10 +08:00
Gabe
8e026238ae fix: show error message dom 2025-10-01 11:18:41 +08:00
Gabe
7412b3a5c8 feat: Add more shortcut keys to popup 2025-10-01 01:47:15 +08:00
Gabe
b60b770ed6 feat: move 'remote detect' from rule to setting 2025-09-30 01:38:07 +08:00
Gabe
20c4d6f6eb feat: remove overwrite subrule 2025-09-30 00:51:31 +08:00
Gabe
2437c75d75 feat: support batch langdetect 2025-09-27 23:34:27 +08:00
Gabe
867c2209b1 feat: support batch langdetect 2025-09-27 23:33:33 +08:00
Gabe
fffa448425 fix: lang detect 2025-09-27 21:21:56 +08:00
Gabe
b1142b88f1 feat: add tarnbox title 2025-09-26 21:13:04 +08:00
Gabe
6d95e7debc feat: add import words helper 2025-09-26 20:56:52 +08:00
Gabe
6bafcb0ec0 fix: change default selectors 2025-09-26 20:45:48 +08:00
Gabe
4935abcf33 feat: Merge default items when saving rule 2025-09-26 12:40:19 +08:00
Gabe
14f74b76bb fix: update rules 2025-09-26 01:46:58 +08:00
Gabe
6b9a1a49bb fix: api hooks 2025-09-25 23:08:39 +08:00
Gabe
533a0e2d5b feat: export old setting 2025-09-25 12:53:46 +08:00
Gabe
393f1a29d5 feat: add preinit setting 2025-09-25 11:31:12 +08:00
Gabe
1dabbfc4de fix: slice check 2025-09-25 01:50:22 +08:00
Gabe
7665f8c260 fix: text styles 2025-09-25 01:13:40 +08:00
Gabe
eef5e25a00 fix: text styles 2025-09-25 01:02:38 +08:00
Gabe
261f29c185 fix: mousehover keys can be set blank 2025-09-25 00:21:51 +08:00
Gabe
2a46939aa5 feat: Extensive refactoring and modification to support any number of interfaces 2025-09-24 23:24:00 +08:00
Gabe
779c9fc850 fix: Identify empty text in advance 2025-09-21 20:55:39 +08:00
Gabe
a20a06320d Merge remote-tracking branch 'origin/dev' into dev 2025-09-21 19:52:16 +08:00
Gabe
943a9e86f0 feat: Restructured core logic to support automatic page scanning and rich text translation 2025-09-21 19:51:57 +08:00
Zack C
563242c5f1 添加可以选择悬浮按钮单击操作的设置选项 (#313)
* Add an option in Settings to provide choices for the FAB Single Click action.

* Complete Translation

---------

Co-authored-by: 1030283726 <1030283726@qq.com>
2025-09-20 22:50:39 +08:00
叫我沈同学
d39a016d5f macOS and iOS support (#312)
* Update README.md

* Update README.en.md
2025-09-16 08:47:36 +08:00
@刘羡鱼
fa87d87011 feat(sync): 通过 base64 复制粘贴配置 (#311)
motivation: 同浏览器多个 profile 简化配置流程,通过同一个同步配置即可实现
2025-09-16 08:44:07 +08:00
Gabe
7dc847fca2 refactor: rewrite task pool 2025-09-03 22:07:49 +08:00
Gabe
343edcdbad feat: support ai context 2025-09-03 20:43:07 +08:00
Gabe
b631703aa6 fix: update ollama api 2025-09-03 14:02:55 +08:00
Gabe
6dd6b73c2f refactor: rename fn name 2025-09-03 13:05:41 +08:00
Gabe
2b496bda31 refactor: rename api args 2025-09-03 12:24:18 +08:00
Gabe
17c8d198c3 fix: api settings 2025-09-03 12:16:41 +08:00
Gabe
86f8d9694d fix: update ai format 2025-09-03 12:04:56 +08:00
Gabe
3948cb74ca refactor: optimize batchqueue 2025-09-03 10:16:21 +08:00
Gabe
4ebced1e71 refactor: rename fn 2025-09-03 09:40:25 +08:00
Gabe
d4e58fc925 feat: Support batch fetch, and update AI prompt 2025-09-03 00:37:35 +08:00
Gabe
2bfb27f346 refactor: Split config files 2025-09-01 18:56:48 +08:00
Gabe
c4fba1c905 refactor: Optimize data and cache request logic 2025-08-31 23:37:29 +08:00
Gabe
4a5e6c2a23 fix: Adjust the order of hook function parameters 2025-08-30 18:21:28 +08:00
Gabe
5fb7157f57 feat: can restore default rule in editor 2025-08-29 23:03:41 +08:00
Gabe
a8c38d2a00 fix: change default sub-rules url 2025-08-29 22:40:01 +08:00
Gabe
cbc82fff64 fix: dashbox style 2025-08-27 01:05:35 +08:00
Gabe
5c44ba1da8 feat: enhanced hook function functionality 2025-08-27 01:02:11 +08:00
Gabe
fd2f0e513b fix: i18n text 2025-08-26 21:22:21 +08:00
Gabe
7fd2a0f187 feat: move global rule to a separate tab 2025-08-26 21:19:47 +08:00
Gabe
fd355eeeab fix: revert shadow dom PR (c6f4fe2b7b) 2025-08-26 00:28:31 +08:00
Gabe
c93e370370 fix: rm tsx package 2025-08-25 00:25:25 +08:00
Gabe
57d218a17f Merge remote-tracking branch 'origin/master' into dev 2025-08-25 00:18:13 +08:00
rxliuli
ffc43a67f2 chore: add safari build script (#299) 2025-08-25 00:17:51 +08:00
Gabe
7deb5b885a doc: remove .obsidian files 2025-08-24 22:51:43 +08:00
GoldenXPig
5d5e23482f 添加 OpenRouter 支持 (#300)
* add openrouter provider

* remove package-lock.json
2025-08-23 11:01:54 +08:00
Gabe
36c1e40d64 feat: compatible with json strings with curly braces { 2025-08-23 00:10:42 +08:00
rxliuli
c6f4fe2b7b feat: auto pierce deep shadow dom (#297)
* feat: auto pierce deep shadow dom

* fix: observe all shadow DOM child element changes

* chore: remove >>> selector require note for shadow DOM
2025-08-22 21:58:57 +08:00
Gabe
1a23627193 doc: update readme 2025-08-22 21:50:35 +08:00
Gabe
d73b2377bf Merge remote-tracking branch 'origin/master' into dev 2025-08-22 21:46:07 +08:00
Gabe
4559ab7ec2 Merge pull request #296 from GinWU05/local
fix: `TypeError: Cannot read properties of undefined (reading 'trim')`
2025-08-22 15:38:29 +08:00
ginwu
1d9679e516 fix: prevent TypeError when processing DOM elements without innerText 2025-08-22 14:33:31 +08:00
Gabe
4c30f6b012 Merge pull request #294 from hoilc/patch-1
fix(claude): enable CORS support
2025-08-22 10:47:42 +08:00
Gabe
511210939f Merge pull request #293 from zh1030283726/master
Add zh-TW support
2025-08-22 10:47:17 +08:00
hoilc
d2addf58cb fix(claude): enable CORS support 2025-08-22 08:03:10 +08:00
1030283726
f7db410235 Add zh-TW support 2025-08-21 23:34:28 +10:00
1030283726
dd18b04cea Add zh-TW support 2025-08-21 23:32:56 +10:00
1030283726
58d8009e91 Add zh-TW support 2025-08-21 23:25:06 +10:00
Gabe
663407b95d Merge pull request #291 from lrsister/master 2025-08-19 13:36:51 +08:00
lrsister
f78901603e docs: add future plans section to README 2025-08-19 10:18:31 +08:00
lrsister
5e1101baeb docs: update README with future plans 2025-08-19 10:11:40 +08:00
Gabe
2ba2441900 Merge pull request #281 from dev-soragoto/dev
增加虚线框的翻译样式
2025-08-12 12:00:04 +08:00
soragoto
4446ae3dbd 增加虚线框的翻译样式 2025-08-12 11:23:19 +08:00
Gabe
72668f0386 Merge pull request #272 from FlyLoongZ/master
添加AI API 接口参数自定义(Body和Header)
2025-08-11 22:47:33 +08:00
FlyLoongZ
a9b858ec6f feat: Add AI API Custom Header 2025-08-11 16:28:23 +08:00
FlyLoongZ
e1f902c203 Rename apiCustomParams to customBody 2025-08-11 16:03:30 +08:00
FlyLoongZ
be6e34ba52 feat: Add AI API Custom Params 2025-08-11 12:12:03 +08:00
Gabe
39b3b00117 release: v1.9.2 2025-08-10 23:00:21 +08:00
Gabe
763019f0c5 doc: update custom api help 2025-08-10 22:56:36 +08:00
Gabe
d743271be8 fix: show custom api name 2025-08-10 22:32:38 +08:00
Gabe
992dad26aa doc: update readme 2025-08-10 22:01:50 +08:00
Gabe
9bd0e67474 doc: update readme 2025-08-10 21:57:26 +08:00
Gabe
5767a4afb2 doc: update readme 2025-08-10 21:54:24 +08:00
Gabe
9e4c510684 doc: update custom api help 2025-08-10 21:50:33 +08:00
Gabe
16607fb069 doc: add custom api help 2025-08-10 21:40:58 +08:00
Gabe
e047a06432 doc: update readme 2025-08-10 20:12:12 +08:00
Gabe
9e09fd898a doc: update readme 2025-08-10 17:37:15 +08:00
Gabe
799c32a871 Merge remote-tracking branch 'origin/master' 2025-08-10 17:33:14 +08:00
Gabe
483f33b5c9 Merge pull request #269 from WilliamK7/patch-1
doc: update readme
2025-08-10 17:32:23 +08:00
Gabe
d444fd4fba fix: set max-width to loading svg 2025-08-10 17:28:28 +08:00
Gabe
0aae93ba2e doc: update help text 2025-08-10 16:56:34 +08:00
Gabe
9608bea3bf doc: update warn text 2025-08-10 16:44:57 +08:00
WilliamK7
a038a1ecdc doc: update readme
Remove duplicates in Chinese README
2025-08-10 13:56:29 +08:00
Gabe
c82cdd7f8f doc: update readme 2025-08-10 12:48:40 +08:00
Gabe
0c6d5c3c61 fix: replace deault tag from span to font 2025-08-09 22:32:41 +08:00
Gabe
900426f359 Merge branch 'master' into dev 2025-08-09 22:03:52 +08:00
Gabe
1d760fc93a Merge pull request #258 from mumu-lhl/push-mlqssmoqoqko
API: Replace max_tokens with max_completion_tokens
2025-08-09 22:03:12 +08:00
Gabe
61571e0f61 fix: remove browser contextMenus (issue #262) 2025-08-09 21:36:43 +08:00
Gabe
c9eb423c89 doc: update readme 2025-08-09 21:06:18 +08:00
Gabe
45b294a121 fix: retranslate loadmore text (issue #257) 2025-08-09 20:55:04 +08:00
Gabe
3a3f1fabe1 doc: update readme 2025-08-09 11:41:24 +08:00
Mumulhl
03177a09b3 API: Replace max_tokens with max_completion_tokens 2025-08-09 11:35:47 +08:00
Gabe
cae391f62b fix: zip script 2025-07-23 21:56:54 +08:00
Gabe
2a5e9db079 v1.9.1 2025-07-23 21:03:02 +08:00
Gabe
650d6e8b41 fix: workflows 2025-07-23 20:58:50 +08:00
Gabe
1daf134b31 fix: gemini api 2025-07-23 20:03:54 +08:00
Gabe
e1dfa35c6c v1.9.0 2025-07-23 00:38:33 +08:00
Gabe
73f80692d3 feat: add format script (prettier) 2025-07-03 19:08:33 +08:00
Gabe
42c7dae495 fix: log 2025-07-03 18:08:49 +08:00
Gabe
b2a1309caa feat: add gemini2 api 2025-07-02 21:54:18 +08:00
Gabe
94bf5f9580 fix: gemini api 2025-07-02 16:37:57 +08:00
Gabe
704ebdc9d7 fix: variable name 2025-07-02 13:38:30 +08:00
Gabe
165da4e559 fix: rule page: show more button 2025-07-01 23:34:16 +08:00
Gabe
d3e3b484bf fix: remove excess code 2025-07-01 22:47:04 +08:00
Gabe
192f8faa5b feat: support keypick for customize API 2025-07-01 22:42:57 +08:00
Gabe
579d5cb0a3 fix: update userscript 2025-07-01 17:55:57 +08:00
Gabe
07fca5b9af fix: #209 2025-07-01 17:03:52 +08:00
Gabe
866a63ab6c feat: move selected translation switch from setting to rule 2025-07-01 16:44:46 +08:00
Gabe
97b4935bc4 feat: api fetch timeout 2025-07-01 12:38:06 +08:00
Gabe
30129abef3 feat: custom API name 2025-07-01 10:54:30 +08:00
Gabe
24d904b32c feat: support volcengine api 2025-06-30 21:34:37 +08:00
Gabe
5f0ce57ead feat: qq transmart 2025-06-27 20:03:58 +08:00
Gabe
51f58d095a feat: add new google translate api (issue: 225, by: Bush2021) 2025-06-27 19:29:00 +08:00
Gabe
d22e3838c4 refactor: deepModels -> tinkIgnore 2025-06-27 16:33:30 +08:00
Gabe
adbb421b7b refactor: fetch timeout 2025-06-27 12:31:32 +08:00
Gabe
eaa47af269 fix: revert old google translate api 2025-06-26 11:13:51 +08:00
Gabe
a6cb5544f8 fix: browser.menus -> browser.contextMenus 2025-06-26 10:01:43 +08:00
Gabe
9e91faa660 Merge pull request #240 from unclemcz/dev
feat:ollama接口设置新增是否禁用深度思考参数
2025-06-25 20:42:31 +08:00
mcz
8636fadc72 接口设置ollama新增是否禁用深度思考参数 2025-06-03 23:07:10 +08:00
Gabe
0621957592 chore: thunderbird 2025-05-18 00:34:20 +08:00
Gabe
8ec06b0c84 chore: defined messenger in package.json 2025-05-18 00:29:06 +08:00
Gabe
d47f8d7ee9 Merge remote-tracking branch 'origin/dev' into dev 2025-05-17 23:22:09 +08:00
Gabe
24f8959525 fix: Ignore html comment elements 2025-05-17 23:19:38 +08:00
Gabe
983740578b Merge pull request #235 from unclemcz/dev
feat:基本设置增加请求超时参数&ollama接口配置增加<think>块忽略参数
2025-05-09 14:09:18 +08:00
Gabe
b5f79ed7cd Merge pull request #232 from Bush2021/fix-workflow
build: fix build errors caused by deprecated actions
2025-05-09 14:08:47 +08:00
Gabe
bbb0e79d4e Merge pull request #231 from Bush2021/fix-google-translate
fix: update API for Google Translate
2025-05-09 14:08:16 +08:00
mcz
471dc05897 ollama接口设置增加<think>块忽略参数 2025-05-01 23:41:08 +08:00
mcz
7a772d2459 在基本设置页面增加接口请求超时时间设置 2025-05-01 20:04:58 +08:00
mcz
1d92421960 Remove the <think></think> tags in qwen3 too. 2025-04-29 19:49:14 +08:00
Bush2021
aeaaf429d7 build: fix build errors caused by deprecated actions 2025-04-16 18:45:41 -04:00
Bush2021
84432e98ae fix: update API for Google Translate 2025-04-16 18:00:54 -04:00
Gabe
77c6102de7 Merge pull request #219 from unclemcz/dev
fix:(Ollama)Remove the <think></think> tags in deepseek-r1.
2025-03-12 17:18:26 +08:00
mcz
ab5dd82169 When using the deepseek-r1 model in Ollama, remove the content between the <think></think> tags. 2025-02-23 11:54:48 +08:00
Gabe
23e7b69dc5 Merge pull request #213 from htyxyt/master
采用更好的方式支持thunderbird
2025-02-19 18:09:01 +08:00
htyxyt
3dc8f393f2 Update package.json 2025-02-18 12:56:29 +08:00
htyxyt
8a2144f263 Update background.js 2025-02-18 12:44:06 +08:00
htyxyt
c1c59caa10 Update package.json 2025-02-18 12:29:43 +08:00
htyxyt
d27ebd90b6 Update package.json 2025-02-18 12:14:02 +08:00
htyxyt
467745c1e9 Update package.json 2025-02-18 11:58:39 +08:00
htyxyt
537378a038 Update background.js 2025-02-18 11:45:57 +08:00
htyxyt
4b5ed30e5b Delete src/background.thunderbird.js 2025-02-18 11:42:57 +08:00
htyxyt
52b7f6a225 Update background.js 2025-02-18 11:42:47 +08:00
htyxyt
f31675d8a2 Update index.js 2025-02-18 11:42:05 +08:00
htyxyt
dd46a8450c Update config-overrides.js 2025-02-18 11:41:28 +08:00
htyxyt
b0843f7d66 Update package.json 2025-02-18 11:39:58 +08:00
htyxyt
daadc0195c Update background.thunderbird.js 2025-02-18 10:25:12 +08:00
Gabe
298dec6957 Merge pull request #210 from htyxyt/master
添加对Thunderbird的支持
2025-02-17 23:48:40 +08:00
Gabe
bf39d85dfa Merge pull request #212 from qonmnop/patch-1
允许用户自定义 hooks 中重写signal 参数,自定义超时时间
2025-02-17 23:30:19 +08:00
htyxyt
30a9de25a8 Update config-overrides.js 2025-02-17 14:01:17 +08:00
htyxyt
af1ecf0bd4 Update package.json 2025-02-17 14:00:35 +08:00
qonmnop
fe55a2cd3c 允许用户自定义 hooks 中重写signal 参数,自定义超时时间 2025-02-17 12:14:10 +08:00
htyxyt
5a33d4e57e Add files via upload 2025-02-17 11:57:40 +08:00
htyxyt
7f46a9023c Delete public/background.thunderbird.js 2025-02-17 11:57:12 +08:00
htyxyt
dfd943b621 Rename manifest.thunderfird.json to manifest.thunderbird.json 2025-02-17 11:10:29 +08:00
htyxyt
7007d0d922 Update package.json 2025-02-17 10:39:08 +08:00
htyxyt
601678500d Update package.json 2025-02-14 15:23:03 +08:00
htyxyt
9bfb504381 Add files via upload 2025-02-14 15:13:40 +08:00
htyxyt
8a03b0cf15 Delete src/background.thunderfird.js 2025-02-14 15:12:57 +08:00
htyxyt
11ba89de0a Update manifest.thunderfird.json 2025-02-14 14:57:38 +08:00
htyxyt
bac7f62eea Update background.thunderfird.js 2025-02-14 14:56:58 +08:00
htyxyt
eef90ea02b Delete src/popup.thunderfird.js 2025-02-14 14:56:10 +08:00
htyxyt
0650df534a Delete src/content.thunderfird.js 2025-02-14 14:56:00 +08:00
htyxyt
9ef8c8b823 Delete src/options.thunderfird.js 2025-02-14 14:55:49 +08:00
htyxyt
d7e08da0b2 Add files via upload 2025-02-13 14:53:06 +08:00
htyxyt
ef361e0798 Add files via upload 2025-02-13 14:50:33 +08:00
Gabe
6855332092 fix: modify systemPrompt & userPrompt 2024-11-30 00:41:29 +08:00
Gabe
121d523e02 Merge remote-tracking branch 'origin/dev' into dev 2024-11-30 00:09:48 +08:00
Gabe
42a375c4c7 Merge pull request #188 from unclemcz/dev
给ollama增加system message
2024-11-30 00:07:14 +08:00
Gabe
a1dd705d97 fix: update pnpm-lock file 2024-11-29 21:14:30 +08:00
mcz
71f90b36ca 给ollama增加system message 2024-09-30 16:41:58 +08:00
Gabe
37facdc3c1 Merge pull request #186 from hoilc/dev
feat: enhance openai prompt
2024-09-26 23:38:34 +08:00
hoilc
66b4f547ff feat: enhance openai prompt 2024-09-25 14:03:12 +08:00
Gabe
d27b9c7f2d Merge pull request #185 from hoilc/dev
feat: support claude api
2024-09-24 23:30:00 +08:00
hoilc
278ff9c6bc feat: support claude api 2024-09-23 18:22:19 +08:00
Gabe Yuan
d6fe1ce9d7 fix: try detect language only when fromLang is auto 2024-05-30 21:05:05 +08:00
Gabe Yuan
0bfa5256b8 fix: simplify keepSelector logic 2024-05-30 17:18:39 +08:00
Gabe Yuan
72ccfc8aec v1.8.11 2024-05-23 20:06:48 +08:00
Gabe Yuan
d117c5dc10 feat: baidu dict can be disabled 2024-05-23 00:08:10 +08:00
Gabe Yuan
9312783f44 feat: lang detector can be selected 2024-05-22 23:33:30 +08:00
Gabe Yuan
e5b16ebfd3 Merge remote-tracking branch 'origin/master' into dev 2024-05-22 10:19:04 +08:00
Gabe Yuan
5d1d65c2d3 feat: the temperature and maxTokens of the openai can be configured 2024-05-21 23:15:46 +08:00
Gabe
9ca1309cec Merge pull request #126 from kebyn/master
fix: option translation
2024-05-21 20:02:53 +08:00
kebyn
a03afc05f5 fix: option translation 2024-05-21 08:56:09 +00:00
Gabe Yuan
0198963584 fix: deeplx: replace auto to blank string 2024-05-21 11:55:17 +08:00
158 changed files with 26357 additions and 10964 deletions

8
.env
View File

@@ -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.8.10 REACT_APP_VERSION=2.0.12
REACT_APP_HOMEPAGE=https://github.com/fishjar/kiss-translator REACT_APP_HOMEPAGE=https://github.com/fishjar/kiss-translator
@@ -11,9 +11,9 @@ REACT_APP_OPTIONSPAGE_DEV=http://localhost:3000/options.html
REACT_APP_LOGOURL=https://fishjar.github.io/kiss-translator/images/logo192.png REACT_APP_LOGOURL=https://fishjar.github.io/kiss-translator/images/logo192.png
REACT_APP_RULESURL=https://fishjar.github.io/kiss-rules/kiss-rules.json REACT_APP_RULESURL=https://fishjar.github.io/kiss-rules/kiss-rules_v2.json
REACT_APP_RULESURL_ON=https://fishjar.github.io/kiss-rules/kiss-rules-on.json REACT_APP_RULESURL_ON=https://fishjar.github.io/kiss-rules/kiss-rules-on_v2.json
REACT_APP_RULESURL_OFF=https://fishjar.github.io/kiss-rules/kiss-rules-off.json REACT_APP_RULESURL_OFF=https://fishjar.github.io/kiss-rules/kiss-rules-off_v2.json
REACT_APP_USERSCRIPT_DOWNLOADURL=https://fishjar.github.io/kiss-translator/kiss-translator.user.js REACT_APP_USERSCRIPT_DOWNLOADURL=https://fishjar.github.io/kiss-translator/kiss-translator.user.js
REACT_APP_USERSCRIPT_IOS_DOWNLOADURL=https://fishjar.github.io/kiss-translator/kiss-translator-ios-safari.user.js REACT_APP_USERSCRIPT_IOS_DOWNLOADURL=https://fishjar.github.io/kiss-translator/kiss-translator-ios-safari.user.js

View File

@@ -7,28 +7,28 @@ on:
jobs: jobs:
build: build:
runs-on: ubuntu-22.04 runs-on: ubuntu-24.04
steps: steps:
- uses: actions/checkout@v3 - uses: actions/checkout@v4
- uses: pnpm/action-setup@v2 - uses: pnpm/action-setup@v4
with: with:
version: 8.7.6 version: 9.14.4
- uses: actions/setup-node@v3 - uses: actions/setup-node@v4
with: with:
node-version: "18.17.0" node-version: 24
cache: "pnpm" cache: "pnpm"
- run: pnpm install - run: pnpm install
- run: pnpm build - run: pnpm build+zip
- uses: actions/upload-artifact@v3 - uses: actions/upload-artifact@v4
with: with:
name: build-artifacts name: build-artifacts
path: build path: build
deploy-web: deploy-web:
needs: build needs: build
runs-on: ubuntu-22.04 runs-on: ubuntu-24.04
steps: steps:
- uses: actions/checkout@v3 - uses: actions/checkout@v4
- uses: actions/download-artifact@v3 - uses: actions/download-artifact@v4
with: with:
name: build-artifacts name: build-artifacts
path: build path: build
@@ -37,7 +37,8 @@ jobs:
with: with:
folder: build/web folder: build/web
create-release: create-release:
runs-on: ubuntu-22.04 needs: build
runs-on: ubuntu-24.04
outputs: outputs:
upload_url: ${{ steps.create-release.outputs.upload_url }} upload_url: ${{ steps.create-release.outputs.upload_url }}
steps: steps:
@@ -54,18 +55,14 @@ jobs:
needs: [build, create-release] needs: [build, create-release]
strategy: strategy:
matrix: matrix:
client: ["chrome", "edge", "firefox", "userscript"] client: ["chrome", "edge", "firefox", "userscript", "thunderbird"]
runs-on: ubuntu-22.04 runs-on: ubuntu-24.04
steps: steps:
- uses: actions/checkout@v3 - uses: actions/checkout@v4
- uses: actions/download-artifact@v3 - uses: actions/download-artifact@v4
with: with:
name: build-artifacts name: build-artifacts
path: build path: build
- name: Zip Release
run: |
cd build
zip -r ${{ matrix.client }}.zip ${{ matrix.client }}
- uses: actions/upload-release-asset@v1 - uses: actions/upload-release-asset@v1
env: env:
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }} GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}

1
.gitignore vendored
View File

@@ -3,6 +3,7 @@
# dependencies # dependencies
/node_modules /node_modules
/.pnp /.pnp
/.obsidian
.pnp.js .pnp.js
.yarn .yarn

1
.pnpm-version Normal file
View File

@@ -0,0 +1 @@
9.14.4

4
.prettierignore Normal file
View File

@@ -0,0 +1,4 @@
node_modules
build
public
package.json

24
.prettierrc Normal file
View File

@@ -0,0 +1,24 @@
{
"arrowParens": "always",
"bracketSpacing": true,
"endOfLine": "lf",
"htmlWhitespaceSensitivity": "css",
"insertPragma": false,
"singleAttributePerLine": false,
"bracketSameLine": false,
"jsxBracketSameLine": false,
"jsxSingleQuote": false,
"printWidth": 80,
"proseWrap": "preserve",
"quoteProps": "as-needed",
"requirePragma": false,
"semi": true,
"singleQuote": false,
"tabWidth": 2,
"trailingComma": "es5",
"useTabs": false,
"embeddedLanguageFormatting": "auto",
"vueIndentScriptAndStyle": false,
"experimentalTernaries": false,
"parser": "babel"
}

View File

@@ -1,6 +1,6 @@
# KISS Translator # KISS Translator
English | [简体中文](README.md) [English](README.en.md) | [中文](README.md) | [日本語](README.ja.md) | [한국어](README.ko.md)
A simple, open source [bilingual translation extension & Greasemonkey script](https://github.com/fishjar/kiss-translator). A simple, open source [bilingual translation extension & Greasemonkey script](https://github.com/fishjar/kiss-translator).
@@ -11,25 +11,52 @@ A simple, open source [bilingual translation extension & Greasemonkey script](ht
- [x] Keep it simple, smart - [x] Keep it simple, smart
- [x] Open source - [x] Open source
- [x] Adapt to common browsers - [x] Adapt to common browsers
- [x] Chrome/Edge/Firefox/Kiwi/Orion - [x] Chrome/Edge
- [ ] Safari - [x] Firefox
- [x] Kiwi (Android)
- [x] Orion (iOS)
- [x] Safari
- [x] Thunderbird
- [x] Supports multiple translation services - [x] Supports multiple translation services
- [x] Google/Microsoft/DeepL/NiuTrans/OpenAI/Gemini/CloudflareAI/Baidu/Tencent - [x] Google/Microsoft
- [x] Custom translation interface - [x] Tencent/Volcengine
- [x] OpenAI/Gemini/Claude/Ollama/DeepSeek/OpenRouter
- [x] DeepL/DeepLX/NiuTrans
- [x] AzureAI / CloudflareAI
- [x] Chrome built-in AI translation (BuiltinAI)
- [x] Covers common translation scenarios - [x] Covers common translation scenarios
- [x] Web bilingual translation - [x] Webpage bilingual translation
- [x] Input box translation - [x] Input-box translation
- [x] Seletction translation - Instantly translate text in input fields into other languages via shortcut keys
- [x] Favorite Words - [x] Text selection translation
- [x] Mouseover translation - [x] Open translation popup on any page, support multiple translation services for comparison
- [x] English dictionary lookup
- [x] Save vocabulary
- [x] Hover translation
- [x] YouTube subtitle translation - [x] YouTube subtitle translation
- Support translating video subtitles with any translation service and display bilingually
- Built-in basic subtitle merging and sentence-splitting algorithm to improve translation quality
- Supports AI-powered sentence segmentation for even better translation
- Custom subtitle style
- [x] Supports diverse translation modes
- [x] Supports both automatic text recognition and manual rule modes
- Automatic text recognition mode allows most sites to be translated fully without writing rules
- Manual rule mode enables extreme optimization for specific sites
- [x] Custom translation styling
- [x] Supports rich-text translation and rendering, preserving links and other text styles where possible
- [x] Option to show only translation (hide original text)
- [x] Advanced translation API features
- [x] With custom API support, theoretically works with any translation service
- [x] Batch aggregation of translation requests
- [x] Supports AI conversation context memory to improve translation quality
- [x] Custom AI terminology dictionary
- [x] All APIs support hooks and custom parameters for advanced usage
- [x] Cross-client data synchronization - [x] Cross-client data synchronization
- [x] KISS-Workercloudflare/docker - [x] KISS-Workercloudflare/docker
- [x] WebDAV - [x] WebDAV
- [x] Custom translation rules - [x] Custom translation rules
- [x] Rule subscription/rule sharing - [x] Rule subscription/rule sharing
- [x] Customized terminology - [x] Customized terminology
- [x] Custom translation style
- [x] Custom shortcut keys - [x] Custom shortcut keys
- `Alt+Q` Toggle Translation - `Alt+Q` Toggle Translation
- `Alt+C` Toggle Styles - `Alt+C` Toggle Styles
@@ -46,12 +73,15 @@ A simple, open source [bilingual translation extension & Greasemonkey script](ht
> - Grease Monkey script will encounter more usage problems (cross domain issues, script conflicts, etc.) > - Grease Monkey script will encounter more usage problems (cross domain issues, script conflicts, etc.)
- [x] Browser extension - [x] Browser extension
- [x] Chrome [Installation address](https://chrome.google.com/webstore/detail/kiss-translator/bdiifdefkgmcblbcghdlonllpjhhjgof?hl=zh-CN) - [x] Chrome [Installation address](https://chrome.google.com/webstore/detail/kiss-translator/bdiifdefkgmcblbcghdlonllpjhhjgof?hl=en)
- [x] Kiwi (Android) - [x] Kiwi (Android)
- [x] Orion (iOS) - [x] Orion (iOS)
- [x] Edge [Installation address](https://microsoftedge.microsoft.com/addons/detail/%E7%AE%80%E7%BA%A6%E7%BF%BB%E8%AF%91/jemckldkclkinpjighnoilpbldbdmmlh?hl=zh-CN) - [x] Edge [Installation address](https://microsoftedge.microsoft.com/addons/detail/%E7%AE%80%E7%BA%A6%E7%BF%BB%E8%AF%91/jemckldkclkinpjighnoilpbldbdmmlh?hl=en)
- [x] Firefox [Installation address](https://addons.mozilla.org/zh-CN/firefox/addon/kiss-translator/) - [x] Firefox [Installation address](https://addons.mozilla.org/en-US/firefox/addon/kiss-translator/)
- [ ] Safari - [ ] Safari
- [ ] Safari (Mac)
- [ ] Safari (iOS)
- [x] Thunderbird [Download address](https://github.com/fishjar/kiss-translator/releases)
- [x] GreaseMonkey Script - [x] GreaseMonkey Script
- [x] Chrome/Edge/Firefox ([Tampermonkey](https://www.tampermonkey.net/)/[Violentmonkey](https://violentmonkey.github.io/)) [Installation link](https://fishjar.github.io/kiss-translator/kiss-translator.user.js) - [x] Chrome/Edge/Firefox ([Tampermonkey](https://www.tampermonkey.net/)/[Violentmonkey](https://violentmonkey.github.io/)) [Installation link](https://fishjar.github.io/kiss-translator/kiss-translator.user.js)
- [Greasy Fork](https://greasyfork.org/zh-CN/scripts/472840-kiss-translator) - [Greasy Fork](https://greasyfork.org/zh-CN/scripts/472840-kiss-translator)
@@ -66,19 +96,70 @@ A simple, open source [bilingual translation extension & Greasemonkey script](ht
- Community subscription rules: [https://github.com/fishjar/kiss-rules](https://github.com/fishjar/kiss-rules) - Community subscription rules: [https://github.com/fishjar/kiss-rules](https://github.com/fishjar/kiss-rules)
- Provides the latest and most complete list of subscription rules maintained by the community. - Provides the latest and most complete list of subscription rules maintained by the community.
- Help with rules-related issues. - Help with rules-related issues.
- Translation interface agent: [https://github.com/fishjar/kiss-proxy](https://github.com/fishjar/kiss-proxy)
- If you encounter network problems when accessing a certain translation interface, this proxy service may help you. ## Frequently Asked Questions
- Deploy and manage by yourself.
- Minimalistic Dictionary Plugin: [https://github.com/fishjar/kiss-dictionary](https://github.com/fishjar/kiss-dictionary) ### How to Set Keyboard Shortcuts
- A word-marking translation plug-in used with this project.
- Supports query of English words, sentences and Chinese characters. Set this in the extension management page, for example:
- Supports history records and word collections.
- chrome [chrome://extensions/shortcuts](chrome://extensions/shortcuts)
- firefox [about:addons](about:addons)
### What is the priority order of rule settings?
Personal Rules > Subscription Rules > Global Rules
Among these, Global Rules have the lowest priority but are very important as they serve as the default rules.
### API (Ollama, etc.) Test Failure
Common reasons for API test failures include:
- Incorrect address:
- For example, `Ollama` has a native API address and an `Openai`-compatible address. This plugin currently supports the `Openai`-compatible address and does not support the `Ollama` native API address.
- Some AI models do not support batch translation:
- In this case, you can choose to disable batch translation or use a custom API.
- Alternatively, you can use a custom API. For details, please refer to: [Custom API Example Documentation](https://github.com/fishjar/kiss-translator/blob/master/custom-api_v2.md)
- Some AI models have inconsistent parameters:
- For example, the parameters of the `Gemini` native API are highly inconsistent. Some model versions do not support certain parameters, leading to errors.
- In this case, you can modify the request body using a `Hook`, or replace it with `Gemini2` (an OpenAI-compatible address).
- The server restricts cross-origin access, returning a 403 error:
- For example, `Ollama` requires adding the environment variable `OLLAMA_ORIGINS=*` when starting. See: https://github.com/fishjar/kiss-translator/issues/174
### Custom API doesn't work in Tampermonkey scripts
Tampermonkey scripts require adding domains to the whitelist; otherwise, requests cannot be sent.
### How to set up a hook function for a custom API
Custom APIs are very powerful and flexible, and can theoretically connect to any translation API.
Example reference: [custom-api_v2.md](https://github.com/fishjar/kiss-translator/blob/master/custom-api_v2.md)
### How to directly access the Tampermonkey script settings page
Settings page address: https://fishjar.github.io/kiss-translator/options.html
## Future Plans
This is a side project with no strict timeline. Community contributions are welcome. The following are preliminary feature directions:
- [x] **Batch Text Requests**: Optimize request strategy to reduce translation API calls and improve performance.
- [x] **Enhanced Rich Text Translation**: Support accurate translation of complex page structures and rich text content.
- [x] **Advanced Custom/AI Interfaces**: Add support for context memory, multi-turn conversations, and other advanced AI features.
- [x] **Fallback English Dictionary**: When translation services fail, fall back to a local dictionary lookup.
- [x] **Improved YouTube Subtitle Support**: Enhance merging and translation experience for streaming subtitles, reducing sentence fragmentation.
- [ ] **Upgraded Rule Collaboration System**: Introduce more flexible rule sharing, version management, and community review processes.
If you're interested in any of these directions, feel free to discuss in [Issues](https://github.com/fishjar/kiss-translator/issues) or submit a PR!
## Development Guidelines ## Development Guidelines
```sh ```sh
git clone https://github.com/fishjar/kiss-translator.git git clone https://github.com/fishjar/kiss-translator.git
cd kiss-translator cd kiss-translator
git checkout dev # Submit a PR suggestion to push to the dev branch
pnpm install pnpm install
pnpm build pnpm build
``` ```

173
README.ja.md Normal file
View File

@@ -0,0 +1,173 @@
# KISS Translator シンプル翻訳
[English](README.en.md) | [中文](README.md) | [日本語](README.ja.md) | [한국어](README.ko.md)
シンプルでオープンソースの [バイリンガル対照翻訳拡張機能&ユーザースクリプト](https://github.com/fishjar/kiss-translator)です。
[kiss-translator.webm](https://github.com/fishjar/kiss-translator/assets/1157624/f7ba8a5c-e4a8-4d5a-823a-5c5c67a0a47f)
## 特徴
- [x] シンプルさを維持
- [x] オープンソース
- [x] 主要なブラウザに対応
- [x] Chrome/Edge
- [x] Firefox
- [x] Kiwi (Android)
- [x] Orion (iOS)
- [x] Safari
- [x] Thunderbird
- [x] 複数の翻訳サービスをサポート
- [x] Google/Microsoft
- [x] Tencent/Volcengine
- [x] OpenAI/Gemini/Claude/Ollama/DeepSeek/OpenRouter
- [x] DeepL/DeepLX/NiuTrans
- [x] AzureAI/CloudflareAI
- [x] Chromeブラウザ内蔵AI翻訳(BuiltinAI)
- [x] 一般的な翻訳シナリオをカバー
- [x] Webページのバイリンガル対照翻訳
- [x] 入力ボックス翻訳
- ショートカットキーで入力ボックス内のテキストを即座に他言語に翻訳
- [x] テキスト選択翻訳
- [x] 任意のページで翻訳ボックスを開き、複数の翻訳サービスで比較翻訳が可能
- [x] 英語辞書翻訳
- [x] 単語のブックマーク
- [x] マウスオーバー翻訳
- [x] YouTube 字幕翻訳
- 任意の翻訳サービスを使用してビデオ字幕を翻訳し、バイリンガル表示をサポート
- 基本的な字幕結合・改行アルゴリズムを内蔵し、翻訳品質を向上
- AIによる改行機能をサポートし、翻訳品質をさらに向上
- 字幕スタイルのカスタマイズ
- [x] 多様な翻訳効果をサポート
- [x] テキスト自動認識と手動ルールの2つのモードをサポート
- テキスト自動認識モードにより、ほとんどのWebサイトでルールを記述しなくても完全な翻訳が可能
- 手動ルールモードで、特定のWebサイトに合わせた最適な最適化が可能
- [x] 翻訳テキストスタイルのカスタマイズ
- [x] リッチテキストの翻訳と表示をサポートし、原文のリンクやその他のテキストスタイルを可能な限り保持
- [x] 翻訳文のみの表示(原文を非表示)をサポート
- [x] 翻訳APIの高度な機能
- [x] カスタムAPIにより、理論上あらゆる翻訳インターフェースをサポート
- [x] 翻訳テキストの統合バッチ送信
- [x] AIコンテキスト会話メモリ機能をサポートし、翻訳品質を向上
- [x] カスタムAI用語集
- [x] すべてのインターフェースがフックやカスタムパラメータなどの高度な機能をサポート
- [x] クライアント間のデータ同期
- [x] KISS-Workercloudflare/docker
- [x] WebDAV
- [x] カスタム翻訳ルール
- [x] ルールの購読/ルール共有
- [x] カスタム専門用語
- [x] カスタムショートカットキー
- `Alt+Q` 翻訳をオン
- `Alt+C` スタイル切り替え
- `Alt+K` 設定ポップアップを開く
- `Alt+S` 翻訳ポップアップを開く/選択テキストを翻訳
- `Alt+O` 設定ページを開く
- `Alt+I` 入力ボックス翻訳
## インストール
> 注:以下の理由により、ブラウザ拡張機能の使用を優先することをお勧めします
>
> - ブラウザ拡張機能の方が機能が完全です(ローカル言語認識、右クリックメニューなど)
> - ユーザースクリプトはより多くの問題(クロスドメイン問題、スクリプトの競合など)に遭遇する可能性があります
- [x] ブラウザ拡張機能
- [x] Chrome [インストール](https://chrome.google.com/webstore/detail/kiss-translator/bdiifdefkgmcblbcghdlonllpjhhjgof?hl=ja)
- [x] Kiwi (Android)
- [x] Orion (iOS)
- [x] Edge [インストール](https://microsoftedge.microsoft.com/addons/detail/%E7%AE%80%E7%BA%A6%E7%BF%BB%E8%AF%91/jemckldkclkinpjighnoilpbldbdmmlh?hl=ja)
- [x] Firefox [インストール](https://addons.mozilla.org/ja/firefox/addon/kiss-translator/)
- [ ] Safari
- [ ] Safari (Mac)
- [ ] Safari (iOS)
- [x] Thunderbird [ダウンロード](https://github.com/fishjar/kiss-translator/releases)
- [x] ユーザースクリプト
- [x] Chrome/Edge/Firefox ([Tampermonkey](https://www.tampermonkey.net/)/[Violentmonkey](https://violentmonkey.github.io/)) [インストールリンク](https://fishjar.github.io/kiss-translator/kiss-translator.user.js)
- [Greasy Fork](https://greasyfork.org/zh-CN/scripts/472840-kiss-translator)
- [x] iOS Safari ([Userscripts Safari](https://github.com/quoid/userscripts)) [インストールリンク](https://fishjar.github.io/kiss-translator/kiss-translator-ios-safari.user.js)
## 関連プロジェクト
- データ同期サービス: [https://github.com/fishjar/kiss-worker](https://github.com/fishjar/kiss-worker)
- 本プロジェクトのデータ同期サービスとして使用できます。
- 個人のプライベートなルールリストの共有にも使用できます。
- セルフホスト、セルフマネジメント、データはプライベート。
- コミュニティ購読ルール: [https://github.com/fishjar/kiss-rules](https://github.com/fishjar/kiss-rules)
- コミュニティによってメンテナンスされた、最新かつ最も完全な購読ルールリストを提供します。
- ルール関連の問題についての助けを求める。
## よくある質問FAQ
### ショートカットキーの設定方法
拡張機能の管理ページで設定します。例:
- chrome [chrome://extensions/shortcuts](chrome://extensions/shortcuts)
- firefox [about:addons](about:addons)
### ルール設定の優先順位は?
個人ルール > 購読ルール > グローバルルール
グローバルルールの優先順位は最も低いですが、フォールバックルールとして非常に重要です。
### APIOllamaなどのテストに失敗する
APIテストの失敗には、一般的に以下の原因が考えられます
- アドレスが間違っている:
- 例えば `Ollama` にはネイティブAPIアドレスと `Openai` 互換のアドレスがありますが、本プラグインは現在、`Openai` 互換アドレスをサポートしており、`Ollama` ネイティブAPIアドレスはサポートしていません
- 一部のAIモデルが統合翻訳をサポートしていない
- この場合、統合翻訳を無効にするか、カスタムAPIを使用して対応できます。
- または、カスタムAPIを使用して対応します。詳細は[カスタムAPIサンプルドキュメント](https://github.com/fishjar/kiss-translator/blob/master/custom-api_v2.md)を参照してください
- 一部のAIモデルでパラメータが一致しない
- 例えば `Gemini` のネイティブAPIはパラメータの不一致が大きく、一部のバージョンのモデルが特定のパラメータをサポートしていないためエラーが返されることがあります。
- この場合、`Hook` を使用してリクエスト `body` を変更するか、`Gemini2` (`Openai` 互換アドレス) に切り替えることができます
- サーバーのクロスドメイン制限によりアクセスが拒否され、403エラーが返される
- 例えば `Ollama` を起動する際に、環境変数 `OLLAMA_ORIGINS=*` を追加する必要があります。参考https://github.com/fishjar/kiss-translator/issues/174
### 入力したAPIがユーザースクリプトで使用できない
ユーザースクリプトは、リクエストを送信するためにドメインのホワイトリストを追加する必要があります。
### カスタムAPIのhook関数の設定方法
カスタムAPI機能は非常に強力で柔軟性があり、理論的にはどんな翻訳APIにも接続できます。
サンプル参照: [custom-api_v2.md](https://github.com/fishjar/kiss-translator/blob/master/custom-api_v2.md)
### ユーザースクリプトの設定ページに直接アクセスする方法
設定ページアドレス: https://fishjar.github.io/kiss-translator/options.html
## 今後の計画
本プロジェクトは余暇に開発しており、厳密なタイムスケジュールはありません。コミュニティの共同構築を歓迎します。以下は初期段階の機能の方向性です:
- [x] **テキストの統合送信**リクエスト戦略を最適化し、翻訳APIの呼び出し回数を減らし、パフォーマンスを向上させます。
- [x] **リッチテキスト翻訳の強化**:より複雑なページ構造やリッチテキストコンテンツの正確な翻訳をサポートします。
- [x] **カスタム/AI APIの強化**コンテキストメモリ、複数ラウンドの対話など、高度なAI機能をサポートします。
- [x] **英語辞書のフォールバックメカニズム**:翻訳サービスが利用できない場合、他の辞書に切り替えるか、ローカル辞書での検索にフォールバックします。
- [x] **YouTube字幕サポートの最適化**:ストリーミング字幕の結合と翻訳体験を改善し、途切れを減らします。
- [ ] **ルール共同構築メカニズムのアップグレード**:より柔軟なルールの共有、バージョン管理、コミュニティレビュープロセスを導入します。
特定の方向に興味がある場合は、[Issues](https://github.com/fishjar/kiss-translator/issues) で議論したり、PRを送信したりすることを歓迎します
## 開発ガイド
```sh
git clone [https://github.com/fishjar/kiss-translator.git](https://github.com/fishjar/kiss-translator.git)
cd kiss-translator
git checkout dev # PRを送信する場合はdevブランチにプッシュすることをお勧めします
pnpm install
pnpm build
```
## コミュニケーション
- [Telegram グループ](https://t.me/+RRCu_4oNwrM2NmFl)に参加
## 寄付
![appreciate](https://github.com/fishjar/kiss-translator/assets/1157624/ebaecabe-2934-4172-8085-af236f5ee399)

174
README.ko.md Normal file
View File

@@ -0,0 +1,174 @@
# KISS Translator 심플 번역
[English](README.en.md) | [中文](README.md) | [日本語](README.ja.md) | [한국어](README.ko.md)
심플하고 오픈 소스인 [이중 언어 대조 번역 확장 프로그램 & 유저 스크립트](https://github.com/fishjar/kiss-translator)입니다.
[kiss-translator.webm](https://github.com/fishjar/kiss-translator/assets/1157624/f7ba8a5c-e4a8-4d5a-823a-5c5c67a0a47f)
## 특징
- [x] 심플함 유지
- [x] 오픈 소스
- [x] 주요 브라우저 지원
- [x] Chrome/Edge
- [x] Firefox
- [x] Kiwi (Android)
- [x] Orion (iOS)
- [x] Safari
- [x] Thunderbird
- [x] 다양한 번역 서비스 지원
- [x] Google/Microsoft
- [x] Tencent/Volcengine
- [x] OpenAI/Gemini/Claude/Ollama/DeepSeek/OpenRouter
- [x] DeepL/DeepLX/NiuTrans
- [x] AzureAI/CloudflareAI
- [x] Chrome 브라우저 내장 AI 번역(BuiltinAI)
- [x] 일반적인 번역 시나리오 지원
- [x] 웹페이지 이중 언어 대조 번역
- [x] 입력창 번역
- 단축키를 통해 입력창 내 텍스트를 즉시 다른 언어로 번역
- [x] 텍스트 선택 번역
- [x] 모든 페이지에서 번역창을 열어 여러 번역 서비스로 비교 번역 가능
- [x] 영어 사전 번역
- [x] 단어 즐겨찾기
- [x] 마우스오버 번역
- [x] YouTube 자막 번역
- 모든 번역 서비스를 사용하여 비디오 자막을 번역하고 이중 언어로 표시 지원
- 기본적인 자막 병합 및 줄 바꿈 알고리즘 내장으로 번역 품질 향상
- AI 줄 바꿈 기능 지원으로 번역 품질 추가 향상
- 사용자 정의 자막 스타일
- [x] 다양한 번역 효과 지원
- [x] 자동 텍스트 인식 및 수동 규칙 두 가지 모드 지원
- 자동 텍스트 인식 모드는 대부분의 웹사이트에서 규칙 작성 없이도 완벽한 번역 가능
- 수동 규칙 모드로 특정 웹사이트에 대한 최적의 최적화 가능
- [x] 번역문 스타일 사용자 정의
- [x] 리치 텍스트 번역 및 표시 지원, 원문의 링크 및 기타 텍스트 스타일 최대한 보존
- [x] 번역문만 표시 (원문 숨기기) 지원
- [x] 번역 인터페이스 고급 기능
- [x] 사용자 정의 인터페이스를 통해 이론상 모든 번역 인터페이스 지원
- [x] 번역 텍스트 일괄 통합 전송
- [x] AI 컨텍스트 (대화 기억) 기능 지원으로 번역 품질 향상
- [x] 사용자 정의 AI 용어 사전
- [x] 모든 인터페이스는 후크 및 사용자 정의 파라미터 등 고급 기능 지원
- [x] 클라이언트 간 데이터 동기화
- [x] KISS-Worker (cloudflare/docker)
- [x] WebDAV
- [x] 사용자 정의 번역 규칙
- [x] 규칙 구독 / 규칙 공유
- [x] 사용자 정의 전문 용어
- [x] 사용자 정의 단축키
- `Alt+Q` 번역 켜기
- `Alt+C` 스타일 전환
- `Alt+K` 설정 팝업 열기
- `Alt+S` 번역 팝업 열기 / 선택한 텍스트 번역
- `Alt+O` 설정 페이지 열기
- `Alt+I` 입력창 번역
## 설치
> 참고: 다음과 같은 이유로 브라우저 확장 프로그램 사용을 우선적으로 권장합니다.
>
> - 브라우저 확장 프로그램의 기능이 더 완전합니다 (로컬 언어 인식, 우클릭 메뉴 등).
> - 유저 스크립트는 사용상 더 많은 문제 (크로스 도메인 문제, 스크립트 충돌 등)를 겪을 수 있습니다.
- [x] 브라우저 확장 프로그램
- [x] Chrome [설치 주소](https://chrome.google.com/webstore/detail/kiss-translator/bdiifdefkgmcblbcghdlonllpjhhjgof?hl=ko)
- [x] Kiwi (Android)
- [x] Orion (iOS)
- [x] Edge [설치 주소](https://microsoftedge.microsoft.com/addons/detail/%E7%AE%80%E7%BA%A6%E7%BF%BB%E8%AF%91/jemckldkclkinpjighnoilpbldbdmmlh?hl=ko)
- [x] Firefox [설치 주소](https://addons.mozilla.org/ko/firefox/addon/kiss-translator/)
- [ ] Safari
- [ ] Safari (Mac)
- [ ] Safari (iOS)
- [x] Thunderbird [다운로드 주소](https://github.com/fishjar/kiss-translator/releases)
- [x] 유저 스크립트
- [x] Chrome/Edge/Firefox ([Tampermonkey](https://www.tampermonkey.net/)/[Violentmonkey](https://violentmonkey.github.io/)) [설치 링크](https://fishjar.github.io/kiss-translator/kiss-translator.user.js)
- [Greasy Fork](https://greasyfork.org/zh-CN/scripts/472840-kiss-translator)
- [x] iOS Safari ([Userscripts Safari](https://github.com/quoid/userscripts)) [설치 링크](https://fishjar.github.io/kiss-translator/kiss-translator-ios-safari.user.js)
## 관련 프로젝트
- 데이터 동기화 서비스: [https://github.com/fishjar/kiss-worker](https://github.com/fishjar/kiss-worker)
- 본 프로젝트의 데이터 동기화 서비스로 사용할 수 있습니다.
- 개인의 비공개 규칙 목록을 공유하는 데에도 사용할 수 있습니다.
- 직접 배포, 직접 관리, 데이터 비공개.
- 커뮤니티 구독 규칙: [https://github.com/fishjar/kiss-rules](https://github.com/fishjar/kiss-rules)
- 커뮤니티에서 유지 관리하는 최신의 가장 완벽한 구독 규칙 목록을 제공합니다.
- 규칙 관련 문제에 대한 도움 요청.
## 자주 묻는 질문 (FAQ)
### 단축키는 어떻게 설정하나요?
플러그인 관리 페이지에서 설정합니다. 예:
- chrome [chrome://extensions/shortcuts](chrome://extensions/shortcuts)
- firefox [about:addons](about:addons)
### 규칙 설정의 우선순위는 어떻게 되나요?
개인 규칙 > 구독 규칙 > 전역 규칙
그중 전역 규칙은 우선순위가 가장 낮지만, 예비 규칙으로서 매우 중요합니다.
### 인터페이스 (Ollama 등) 테스트 실패
일반적으로 인터페이스 테스트 실패는 다음과 같은 몇 가지 원인이 있습니다:
- 주소를 잘못 입력한 경우:
- 예를 들어 `Ollama`는 네이티브 인터페이스 주소와 `Openai` 호환 주소가 있습니다. 본 플러그인은 현재 `Openai` 호환 주소를 통일되게 지원하며, `Ollama` 네이티브 인터페이스 주소는 지원하지 않습니다.
- 일부 AI 모델이 통합 번역을 지원하지 않는 경우:
- 이 경우 통합 번역을 비활성화하거나 사용자 정의 인터페이스 방식을 통해 사용할 수 있습니다.
- 또는 사용자 정의 인터페이스 방식을 통해 사용합니다. 자세한 내용은 [사용자 정의 인터페이스 예시 문서](https://github.com/fishjar/kiss-translator/blob/master/custom-api_v2.md)를 참조하세요.
- 일부 AI 모델의 파라미터가 일치하지 않는 경우:
- 예를 들어 `Gemini` 네이티브 인터페이스 파라미터는 매우 불일치하며, 일부 버전의 모델은 특정 파라미터를 지원하지 않아 오류를 반환할 수 있습니다.
- 이 경우 `Hook`을 사용하여 요청 `body`를 수정하거나, `Gemini2` (`Openai` 호환 주소)로 변경할 수 있습니다.
- 서버의 크로스 도메인 접근 제한으로 403 오류가 반환되는 경우:
- 예를 들어 `Ollama` 시작 시 환경 변수 `OLLAMA_ORIGINS=*`를 추가해야 합니다. 참고: https://github.com/fishjar/kiss-translator/issues/174
### 입력한 인터페이스를 유저 스크립트에서 사용할 수 없습니다
유저 스크립트는 도메인 화이트리스트를 추가해야 요청을 보낼 수 있습니다.
### 사용자 정의 인터페이스의 hook 함수는 어떻게 설정하나요?
사용자 정의 인터페이스 기능은 매우 강력하고 유연하며, 이론적으로 어떤 번역 인터페이스든 연결할 수 있습니다.
예시 참고: [custom-api_v2.md](https://github.com/fishjar/kiss-translator/blob/master/custom-api_v2.md)
### 유저 스크립트 설정 페이지로 바로 이동하는 방법
설정 페이지 주소: https://fishjar.github.io/kiss-translator/options.html
## 향후 계획
본 프로젝트는 여가 시간에 개발되며, 엄격한 시간표는 없습니다. 커뮤니티의 공동 구축을 환영합니다. 다음은 초기 구상 중인 기능 방향입니다:
- [x] **텍스트 통합 전송**: 요청 전략을 최적화하여 번역 인터페이스 호출 횟수를 줄이고 성능을 향상시킵니다.
- [x] **리치 텍스트 번역 강화**: 더 복잡한 페이지 구조와 리치 텍스트 콘텐츠의 정확한 번역을 지원합니다.
- [x] **사용자 정의/AI 인터페이스 강화**: 컨텍스트 기억, 다중 턴 대화 등 고급 AI 기능을 지원합니다.
- [x] **영어 사전 예비 메커니즘**: 번역 서비스가 실패할 경우 다른 사전으로 전환하거나 로컬 사전 조회로 대체합니다.
- [x] **YouTube 자막 지원 최적화**: 스트리밍 자막의 병합 및 번역 경험을 개선하고, 끊김을 줄입니다.
- [ ] **규칙 공동 구축 메커니즘 업그레이드**: 더 유연한 규칙 공유, 버전 관리 및 커뮤니티 검토 프로세스를 도입합니다.
특정 방향에 관심이 있다면, [Issues](https://github.com/fishjar/kiss-translator/issues)에서 토론하거나 PR을 제출해 주세요!
## 개발 가이드
```sh
git clone [https://github.com/fishjar/kiss-translator.git](https://github.com/fishjar/kiss-translator.git)
cd kiss-translator
git checkout dev # PR 제출 시 dev 브랜치로 푸시하는 것을 권장합니다
pnpm install
pnpm build
```
## 커뮤니티
- [Telegram 그룹](https://t.me/+RRCu_4oNwrM2NmFl) 가입
## 후원
![appreciate](https://github.com/fishjar/kiss-translator/assets/1157624/ebaecabe-2934-4172-8085-af236f5ee399)

109
README.md
View File

@@ -1,6 +1,6 @@
# 简约翻译 # KISS Translator 简约翻译
[English](README.en.md) | 简体中文 [English](README.en.md) | [中文](README.md) | [日本語](README.ja.md) | [한국어](README.ko.md)
一个简约、开源的 [双语对照翻译扩展 & 油猴脚本](https://github.com/fishjar/kiss-translator)。 一个简约、开源的 [双语对照翻译扩展 & 油猴脚本](https://github.com/fishjar/kiss-translator)。
@@ -11,25 +11,52 @@
- [x] 保持简约 - [x] 保持简约
- [x] 开放源代码 - [x] 开放源代码
- [x] 适配常见浏览器 - [x] 适配常见浏览器
- [x] Chrome/Edge/Firefox/Kiwi/Orion - [x] Chrome/Edge
- [ ] Safari - [x] Firefox
- [x] Kiwi (Android)
- [x] Orion (iOS)
- [x] Safari
- [x] Thunderbird
- [x] 支持多种翻译服务 - [x] 支持多种翻译服务
- [x] Google/Microsoft/DeepL/NiuTrans/OpenAI/Gemini/CloudflareAI/Baidu/Tencent - [x] Google/Microsoft
- [x] 自定义翻译接口 - [x] Tencent/Volcengine
- [x] OpenAI/Gemini/Claude/Ollama/DeepSeek/OpenRouter
- [x] DeepL/DeepLX/NiuTrans
- [x] AzureAI/CloudflareAI
- [x] Chrome浏览器内置AI翻译(BuiltinAI)
- [x] 覆盖常见翻译场景 - [x] 覆盖常见翻译场景
- [x] 网页双语对照翻译 - [x] 网页双语对照翻译
- [x] 输入框翻译 - [x] 输入框翻译
- 通过快捷键立即将输入框内文本翻译成其他语言
- [x] 划词翻译 - [x] 划词翻译
- [x] 任意页面打开翻译框,可用多种翻译服务对比翻译
- [x] 英文词典翻译
- [x] 收藏词汇 - [x] 收藏词汇
- [x] 鼠标悬停翻译 - [x] 鼠标悬停翻译
- [x] YouTube 字幕翻译 - [x] YouTube 字幕翻译
- 支持任意翻译服务对视频字幕进行翻译并双语显示
- 内置基础的字幕合并与断句算法,提升翻译效果
- 支持AI断句功能可进一步提升翻译质量
- 自定义字幕样式
- [x] 支持多样翻译效果
- [x] 支持自动识别文本与手动规则两种模式
- 自动识别文本模式使得绝大部分网站无需编写规则也能翻译完整
- 手动规则模式,可以针对特定网站极致优化
- [x] 自定义译文样式
- [x] 支持富文本翻译及显示,能够尽量保留原文中的链接及其他文本样式
- [x] 支持仅显示译文(隐藏原文)
- [x] 翻译接口高级功能
- [x] 通过自定义接口,理论上支持任何翻译接口
- [x] 聚合批量发送翻译文本
- [x] 支持AI上下文会话记忆功能提升翻译效果
- [x] 自定义AI术语词典
- [x] 所有接口均支持Hook和自定义参数等高级功能
- [x] 跨客户端数据同步 - [x] 跨客户端数据同步
- [x] KISS-Workercloudflare/docker - [x] KISS-Workercloudflare/docker
- [x] WebDAV - [x] WebDAV
- [x] 自定义翻译规则 - [x] 自定义翻译规则
- [x] 规则订阅/规则分享 - [x] 规则订阅/规则分享
- [x] 自定义专业术语 - [x] 自定义专业术语
- [x] 自定义译文样式
- [x] 自定义快捷键 - [x] 自定义快捷键
- `Alt+Q` 开启翻译 - `Alt+Q` 开启翻译
- `Alt+C` 切换样式 - `Alt+C` 切换样式
@@ -52,6 +79,9 @@
- [x] Edge [安装地址](https://microsoftedge.microsoft.com/addons/detail/%E7%AE%80%E7%BA%A6%E7%BF%BB%E8%AF%91/jemckldkclkinpjighnoilpbldbdmmlh?hl=zh-CN) - [x] Edge [安装地址](https://microsoftedge.microsoft.com/addons/detail/%E7%AE%80%E7%BA%A6%E7%BF%BB%E8%AF%91/jemckldkclkinpjighnoilpbldbdmmlh?hl=zh-CN)
- [x] Firefox [安装地址](https://addons.mozilla.org/zh-CN/firefox/addon/kiss-translator/) - [x] Firefox [安装地址](https://addons.mozilla.org/zh-CN/firefox/addon/kiss-translator/)
- [ ] Safari - [ ] Safari
- [ ] Safari (Mac)
- [ ] Safari (iOS)
- [x] Thunderbird [下载地址](https://github.com/fishjar/kiss-translator/releases)
- [x] 油猴脚本 - [x] 油猴脚本
- [x] Chrome/Edge/Firefox ([Tampermonkey](https://www.tampermonkey.net/)/[Violentmonkey](https://violentmonkey.github.io/)) [安装链接](https://fishjar.github.io/kiss-translator/kiss-translator.user.js) - [x] Chrome/Edge/Firefox ([Tampermonkey](https://www.tampermonkey.net/)/[Violentmonkey](https://violentmonkey.github.io/)) [安装链接](https://fishjar.github.io/kiss-translator/kiss-translator.user.js)
- [Greasy Fork](https://greasyfork.org/zh-CN/scripts/472840-kiss-translator) - [Greasy Fork](https://greasyfork.org/zh-CN/scripts/472840-kiss-translator)
@@ -66,19 +96,70 @@
- 社区订阅规则: [https://github.com/fishjar/kiss-rules](https://github.com/fishjar/kiss-rules) - 社区订阅规则: [https://github.com/fishjar/kiss-rules](https://github.com/fishjar/kiss-rules)
- 提供社区维护的,最新最全的订阅规则列表。 - 提供社区维护的,最新最全的订阅规则列表。
- 求助规则相关的问题。 - 求助规则相关的问题。
- 翻译接口代理: [https://github.com/fishjar/kiss-proxy](https://github.com/fishjar/kiss-proxy)
- 如果访问某个翻译接口遇到网络问题,这个代理服务也许可以帮到你。 ## 常见问题
- 自己部署,自己管理。
- 简约词典插件: [https://github.com/fishjar/kiss-dictionary](https://github.com/fishjar/kiss-dictionary) ### 如何设置快捷键
- 搭配本项目一起使用的划词翻译插件。
- 支持英文单词、句子、汉字的查询。 在插件管理那里设置,例如:
- 支持历史记录、单词收藏。
- chrome [chrome://extensions/shortcuts](chrome://extensions/shortcuts)
- firefox [about:addons](about:addons)
### 规则设置的优先级是如何的
个人规则 > 订阅规则 > 全局规则
其中全局规则优先级最低,但非常重要,相当于兜底规则。
### 接口Ollama等测试失败
一般接口测试失败常见有以下几种原因:
- 地址填错了:
- 比如 `Ollama` 有原生接口地址和 `Openai` 兼容的地址,本插件目前统一支持 `Openai` 兼容的地址,不支持 `Ollama` 原生接口地址
- 某些AI模型不支持聚合翻译
- 此种情况可以选择禁用聚合翻译或通过自定义接口的方式来使用。
- 或通过自定义接口的方式来使用,详情参考: [自定义接口示例文档](https://github.com/fishjar/kiss-translator/blob/master/custom-api_v2.md)
- 某些AI模型的参数不一致
- 比如 `Gemini` 原生接口参数非常不一致,部分版本的模型不支持某些参数会导致返回错误。
- 此种情况可以通过 `Hook` 修改请求 `body` ,或者更换为 `Gemini2` (`Openai` 兼容的地址)
- 服务器跨域限制访问返回403错误
- 比如 `Ollama` 启动时须添加环境变量 `OLLAMA_ORIGINS=*`, 参考https://github.com/fishjar/kiss-translator/issues/174
### 填写的接口在油猴脚本不能使用
油猴脚本需要增加域名白名单,否则不能发出请求。
### 如何设置自定义接口的hook函数
自定义接口功能非常强大、灵活,理论可以接入任何翻译接口。
示例参考: [custom-api_v2.md](https://github.com/fishjar/kiss-translator/blob/master/custom-api_v2.md)
### 如何直接进入油猴脚本设置页面
设置页面地址: https://fishjar.github.io/kiss-translator/options.html
## 未来规划
本项目为业余开发,无严格时间表,欢迎社区共建。以下为初步设想的功能方向:
- [x] **聚合发送文本**:优化请求策略,减少翻译接口调用次数,提升性能。
- [x] **增强富文本翻译**:支持更复杂的页面结构和富文本内容的准确翻译。
- [x] **强化自定义/AI 接口**:支持上下文记忆、多轮对话等高级 AI 功能。
- [x] **英文词典备灾机制**:当翻译服务失效时,可切换其他词典或 fallback 到本地词典查询。
- [x] **优化 YouTube 字幕支持**:改进流式字幕的合并与翻译体验,减少断句。
- [ ] **规则共建机制升级**:引入更灵活的规则分享、版本管理与社区评审流程。
如果你对某个方向感兴趣,欢迎在 [Issues](https://github.com/fishjar/kiss-translator/issues) 中讨论或提交 PR
## 开发指引 ## 开发指引
```sh ```sh
git clone https://github.com/fishjar/kiss-translator.git git clone https://github.com/fishjar/kiss-translator.git
cd kiss-translator cd kiss-translator
git checkout dev # 提交PR建议推送到dev分支
pnpm install pnpm install
pnpm build pnpm build
``` ```

View File

@@ -32,6 +32,8 @@ const extWebpack = (config, env) => {
options: paths.appSrc + "/options.js", options: paths.appSrc + "/options.js",
background: paths.appSrc + "/background.js", background: paths.appSrc + "/background.js",
content: paths.appSrc + "/content.js", content: paths.appSrc + "/content.js",
"injector-subtitle": paths.appSrc + "/injector-subtitle.js",
"injector-shadowroot": paths.appSrc + "/injector-shadowroot.js",
}; };
config.output.filename = "[name].js"; config.output.filename = "[name].js";
@@ -92,8 +94,11 @@ const userscriptWebpack = (config, env) => {
// @grant GM.info // @grant GM.info
// @grant unsafeWindow // @grant unsafeWindow
// @connect translate.googleapis.com // @connect translate.googleapis.com
// @connect translate-pa.googleapis.com
// @connect generativelanguage.googleapis.com
// @connect api-edge.cognitive.microsofttranslator.com // @connect api-edge.cognitive.microsofttranslator.com
// @connect edge.microsoft.com // @connect edge.microsoft.com
// @connect bing.com
// @connect api-free.deepl.com // @connect api-free.deepl.com
// @connect api.deepl.com // @connect api.deepl.com
// @connect www2.deepl.com // @connect www2.deepl.com
@@ -102,18 +107,21 @@ const userscriptWebpack = (config, env) => {
// @connect openai.azure.com // @connect openai.azure.com
// @connect workers.dev // @connect workers.dev
// @connect github.io // @connect github.io
// @connect github.com
// @connect githubusercontent.com // @connect githubusercontent.com
// @connect kiss-translator.rayjar.com // @connect kiss-translator.rayjar.com
// @connect ghproxy.com // @connect ghproxy.com
// @connect dav.jianguoyun.com // @connect dav.jianguoyun.com
// @connect fanyi.baidu.com // @connect fanyi.baidu.com
// @connect transmart.qq.com // @connect transmart.qq.com
// @connect localhost:3000 // @connect niutrans.com
// @connect 127.0.0.1:3000 // @connect translate.volcengine.com
// @connect localhost:1188 // @connect dict.youdao.com
// @connect 127.0.0.1:1188 // @connect api.anthropic.com
// @connect localhost:11434 // @connect api.cloudflare.com
// @connect 127.0.0.1:11434 // @connect openrouter.ai
// @connect localhost
// @connect 127.0.0.1
// @run-at document-end // @run-at document-end
// ==/UserScript== // ==/UserScript==

348
custom-api.md Normal file
View File

@@ -0,0 +1,348 @@
# 自定义接口示例(本文档已过期,新版不再适用)
V2版的示例请查看这里[custom-api_v2.md](https://github.com/fishjar/kiss-translator/blob/master/custom-api_v2.md)
以下示例为网友提供,仅供学习参考。
## 本地运行 Seed-X-PPO-7B 量化模型
> 由网友 emptyghost6 提供来源https://linux.do/t/topic/828257
URL
```sh
http://localhost:8000/v1/completions
```
Request Hook
```js
(text, from, to, url, key) => {
// 模型支持的语言代码到完整名称的映射
const langFullNameMap = {
ar: 'Arabic', fr: 'French', ms: 'Malay', ru: 'Russian',
cs: 'Czech', hr: 'Croatian', nb: 'Norwegian Bokmal', sv: 'Swedish',
da: 'Danish', hu: 'Hungarian', nl: 'Dutch', th: 'Thai',
de: 'German', id: 'Indonesian', no: 'Norwegian', tr: 'Turkish',
en: 'English', it: 'Italian', pl: 'Polish', uk: 'Ukrainian',
es: 'Spanish', ja: 'Japanese', pt: 'Portuguese', vi: 'Vietnamese',
fi: 'Finnish', ko: 'Korean', ro: 'Romanian', zh: 'Chinese'
};
// 将 Hook 系统的语言代码转换为模型 API 支持的代码
const getModelLangCode = (lang) => {
if (lang === 'zh-CN' || lang === 'zh-TW') return 'zh';
return lang;
};
const sourceLangCode = getModelLangCode(from);
const targetLangCode = getModelLangCode(to);
const sourceLangName = langFullNameMap[sourceLangCode] || from;
const targetLangName = langFullNameMap[targetLangCode] || to;
const prompt = `Translate it to ${targetLangName}:\n${text} <${targetLangCode}>`;
// 构建请求体对象
const bodyObject = {
model: "./ByteDance-Seed/Seed-X-PPO-7B-AWQ-Int4",
prompt: prompt,
max_tokens: 2048,
temperature: 0.0,
};
// 返回最终的请求配置
return [url, {
method: "POST",
headers: {
"Content-Type": "application/json",
},
// 关键改动:将 JavaScript 对象转换为 JSON 字符串
body: JSON.stringify(bodyObject),
}];
}
```
Response Hook
```js
(res, text, from, to) => {
// 检查返回是否有效
if (res && res.choices && res.choices.length > 0 && res.choices[0].text) {
// 提取译文并去除可能存在的前后空格
const translatedText = res.choices[0].text.trim();
// 比较原文与译文,相同为 true否则为 false。
const areTextsIdentical = text.trim() === translatedText;
// 返回数组:[翻译后的文本, 是否与原文相同]
return [translatedText, areTextsIdentical];
}
// 如果响应格式不正确或没有结果,则抛出错误
throw new Error("Invalid API response format or no translation found.");
}
```
## 接入 openrouter
> 由网友 Rick Sanchez 提供
URL
```sh
https://openrouter.ai/api/v1/chat/completions
```
Request Hook
```js
(text, from, to, url, key) => [url, {
method: "POST",
headers: {
"Authorization": `Bearer ${key}`,
"Content-type": "application/json",
},
body: JSON.stringify({
"model": "deepseek/deepseek-chat-v3-0324:free", //可自定义你的模型
"messages": [
{
"role": "user",
"content": //可自定义你的提示词
`You are a professional ${to} native translator. Your task is to produce a fluent, natural, and culturally appropriate translation of the following text from ${from} to ${to}, fully conveying the meaning, tone, and nuance of the original.
## Translation Rules
1. Output only the final polished translation — no explanations, intermediate drafts, or notes.
2. Translate in a way that reads naturally to a native ${to} audience, adapting idioms, cultural references, and tone when necessary.
3. Preserve proper nouns, technical terms, brand names, and URLs exactly as in the original text unless a widely accepted ${to} equivalent exists.
4. Keep any formatting (Markdown, HTML tags, bullet points, numbering) intact and positioned naturally within the translation.
5. Adapt humor, metaphors, and figurative language to culturally relevant forms in ${to} while keeping the original intent.
6. Maintain the same level of formality or informality as the original.
Source Text: ${text}
Translated Text:`
}
]
})
}]
```
Response Hook
```js
(res, text, from, to) => [
res.choices?.[0]?.message?.content ?? "",
false
]
```
## 接入 gemini-2.5-flash, 关闭思考模式, 去审查
> 由网友 Rick Sanchez 提供
URL
```sh
https://generativelanguage.googleapis.com/v1beta/models
```
Request Hook
```js
(text, from, to, url, key) => [`${url}/gemini-2.5-flash:generateContent?key=${key}`, {
headers: {
"Content-Type": "application/json",
},
method: "POST",
body: JSON.stringify({
"generationConfig": {
"temperature": 0.8,
"thinkingConfig": {
"thinkingBudget": 0, //gemini-2.5-flash设为0关闭思考模式
},
},
"safetySettings": [
{
"category": "HARM_CATEGORY_HARASSMENT",
"threshold": "BLOCK_NONE",
},
{
"category": "HARM_CATEGORY_HATE_SPEECH",
"threshold": "BLOCK_NONE",
},
{
"category": "HARM_CATEGORY_SEXUALLY_EXPLICIT",
"threshold": "BLOCK_NONE",
},
{
"category": "HARM_CATEGORY_DANGEROUS_CONTENT",
"threshold": "BLOCK_NONE",
}
],
"contents": [{
"parts": [{
"text": `自定义提示词`
}]
}],
}),
}]
```
Response Hook
```js
(res, text, from, to) => [
res.candidates?.[0]?.content?.parts?.[0]?.text ?? "",
false
]
```
## 接入 Qwen-MT
> 由网友 atom 提供
URL
```sh
https://dashscope.aliyuncs.com/compatible-mode/v1/chat/completions
```
Request Hook
```js
(text, from, to, url, key) => {
const mapLanguageCode = (lang) => ({
'zh-CN': 'zh',
'zh-TW': 'zh_tw',
})[lang] || lang;
const targetLang = mapLanguageCode(to);
return [
url,
{
method: "POST",
headers: {
"Content-Type": "application/json",
"Authorization": `Bearer ${key}`
},
body: JSON.stringify({
"model": "qwen-mt-turbo",
"messages": [
{
"role": "user",
"content": text
}
],
"translation_options": {
"source_lang": "auto",
"target_lang": targetLang
}
})
}
];
}
```
Response Hook
```js
(res, text, from, to) => [res.choices?.[0]?.message?.content ?? "", false]
```
## 接入 deepl 接口
> 来源: https://github.com/fishjar/kiss-translator/issues/101#issuecomment-2123786236
Request Hook
```js
(text, from, to, url, key) => [
url,
{
headers: {
"Content-type": "application/json",
},
method: "POST",
body: JSON.stringify({
text,
target_lang: "ZH",
source_lang: "auto",
}),
},
]
```
Response Hook
```js
(res, text, from, to) => [res.data, "ZH" === res.source_lang]
```
## 接入智谱AI大模型
> 来源: https://github.com/fishjar/kiss-translator/issues/205#issuecomment-2642422679
Request Hook
```js
(text, from, to, url, key) => [url, {
"method": "POST",
"headers": {
"Content-type": "application/json",
"Authorization": key
},
"body": JSON.stringify({
"model": "glm-4-flash",
"messages": [
{
"role":"system",
"content": "You are a professional, authentic machine translation engine. You only return the translated text, without any explanations."
},
{
"role": "user",
"content": `Translate the following text into ${to}. If translation is unnecessary (e.g. proper nouns, codes, etc.), return the original text. NO explanations. NO notes:\n\n ${text} `
}
]
})
}]
```
## 接入谷歌新接口
> 由网友 Bush2021 提供来源https://github.com/fishjar/kiss-translator/issues/225#issuecomment-2810950717
URL
```sh
https://translate-pa.googleapis.com/v1/translateHtml
```
KEY
```sh
AIzaSyATBXajvzQLTDHEQbcpq0Ihe0vWDHmO520
```
Request Hook
```js
(text, from, to, url, key) => [url, {
method: "POST",
headers: {
"Content-Type": "application/json+protobuf",
"X-Goog-API-Key": key
},
body: JSON.stringify([[[text], from || "auto", to], "wt_lib"])
}]
```
Response Hook
```js
(res, text, from, to) => [res?.[0]?.join(" ") || "Translation unavailable", to === res?.[1]?.[0]]
```

387
custom-api_v2.md Normal file
View File

@@ -0,0 +1,387 @@
# 自定义接口说明及示例
## 默认接口规范
如果接口的请求数据和返回数据符合以下规范,
则无需填写 `Request Hook``Response Hook`
### 非聚合翻译 (v2.0.9)
Request body
```json
{
"text": "hello", // 需要翻译的文本列表
"from":"auto", // 原文语言
"to": "zh-CN" // 目标语言
}
```
Response
```json
{
"text": "你好", // 译文
"src": "en" // 原文语言
}
// 或者
{
"text": "你好", // 译文
"from": "en" // 原文语言
}
```
### 聚合翻译
Request body
```json
{
"texts": ["hello"], // 需要翻译的文本列表
"from":"auto", // 原文语言
"to": "zh-CN" // 目标语言
}
```
Response
```json
[
{
"text": "你好", // 译文
"src": "en" // 原文语言
}
]
```
v2.0.4版后亦支持以下 Response 格式
```json
{
"translations": [ // 译文列表
{
"text": "你好", // 译文
"src": "en" // 原文语言
}
]
}
```
## Prompt 相关
`Prompt` 可替换占位符:
```js
`{{from}}` // 原文语言名称
`{{to}}` // 目标语言名称
`{{fromLang}}` // 原文语言代码
`{{toLang}}` // 目标语言代码
`{{text}}` // 原文
`{{tone}}` // 风格
`{{title}}` // 页面标题
`{{description}}` // 页面描述
```
Hook 中 `Prompt` 类型说明:
```js
`systemPrompt` // 聚合翻译 System Prompt
`nobatchPrompt` // 非聚合翻译 System Prompt
`nobatchUserPrompt` // 非聚合翻译 User Prompt
`subtitlePrompt` // 字幕翻译 System Prompt
```
## 谷歌翻译接口
> 此接口不支持聚合
URL
```
https://translate.googleapis.com/translate_a/single?client=gtx&dj=1&dt=t&ie=UTF-8&q={{text}}&sl=en&tl=zh-CN
```
Request Hook
```js
async (args) => {
const url = args.url.replace("{{text}}", args.texts[0]);
const method = "GET";
return { url, method };
};
```
Response Hook
```js
async ({ res }) => {
return { translations: [[res?.sentences?.[0]?.trans || "", res?.src]] };
};
```
## Ollama
> 此示例为支持聚合的模型类(要支持上下文,需进一步改动)
* 注意 ollama 启动参数需要添加环境变量 `OLLAMA_ORIGINS=*`
* 检查环境变量生效命令:`systemctl show ollama | grep OLLAMA_ORIGINS`
URL
```
http://localhost:11434/v1/chat/completions
```
Request Hook
```js
async (args) => {
const url = args.url;
const method = "POST";
const headers = { "Content-type": "application/json" };
const body = {
model: "gemma3",
messages: [
{
role: "system",
content:
'Act as a translation API. Output a single raw JSON object only. No extra text or fences.\n\nInput:\n{"targetLanguage":"<lang>","title":"<context>","description":"<context>","segments":[{"id":1,"text":"..."}],"glossary":{"sourceTerm":"targetTerm"},"tone":"<formal|casual>"}\n\nOutput:\n{"translations":[{"id":1,"text":"...","sourceLanguage":"<detected>"}]}\n\nRules:\n1. Use title/description for context only; do not output them.\n2. Keep id, order, and count of segments.\n3. Preserve whitespace, HTML entities, and all HTML-like tags (e.g., <i1>, <a1>). Translate inner text only.\n4. Highest priority: Follow \'glossary\'. Use value for translation; if value is "", keep the key.\n5. Do not translate: content in <code>, <pre>, text enclosed in backticks, or placeholders like {1}, {{1}}, [1], [[1]].\n6. Apply the specified tone to the translation.\n7. Detect sourceLanguage for each segment.\n8. Return empty or unchanged inputs as is.\n\nExample:\nInput: {"targetLanguage":"zh-CN","segments":[{"id":1,"text":"A <b>React</b> component."}],"glossary":{"component":"组件","React":""}}\nOutput: {"translations":[{"id":1,"text":"一个<b>React</b>组件","sourceLanguage":"en"}]}\n\nFail-safe: On any error, return {"translations":[]}.',
},
{
role: "user",
content: JSON.stringify({
targetLanguage: args.toLang,
segments: args.texts.map((text, id) => ({ id, text })),
title: "", // 可省略
description: "", // 可省略
glossary: {}, // 可省略
tone: "", // 可省略
}),
},
],
temperature: 0,
max_tokens: 20480,
think: false,
stream: false,
};
return { url, body, headers, method };
};
```
v2.0.2 Request Hook 可以简化为:
```js
async (args) => {
const url = args.url;
const method = "POST";
const headers = { "Content-type": "application/json" };
const body = {
model: "gemma3", // v2.0.2 版后此处可填 args.model
messages: [
{
role: "system",
content: args.defaultSystemPrompt, // 或者 args.systemPrompt
},
{
role: "user",
content: JSON.stringify({
targetLanguage: args.toLang,
segments: args.texts.map((text, id) => ({ id, text })),
title: "", // 可省略
description: "", // 可省略
glossary: {}, // 可省略
tone: "", // 可省略
}),
},
],
temperature: 0,
max_tokens: 20480,
think: false,
stream: false,
};
return { url, body, headers, method };
};
```
Response Hook
```js
async ({ res }) => {
const extractJson = (raw) => {
const jsonRegex = /({.*}|\[.*\])/s;
const match = raw.match(jsonRegex);
return match ? match[0] : null;
};
const parseAIRes = (raw) => {
if (!raw) return [];
try {
const jsonString = extractJson(raw);
if (!jsonString) return [];
const data = JSON.parse(jsonString);
if (Array.isArray(data.translations)) {
return data.translations.map((item) => [
item?.text ?? "",
item?.sourceLanguage ?? "",
]);
}
} catch (err) {
console.log("parseAIRes", err);
}
return [];
};
const translations = parseAIRes(res?.choices?.[0]?.message?.content);
return { translations };
};
```
v2.0.2 版后内置`parseAIRes`函数Response Hook 可以简化为:
```js
async ({ res, parseAIRes }) => {
const translations = parseAIRes(res?.choices?.[0]?.message?.content);
return { translations };
};
```
## 硅基流动
> 此示例为不支持聚合模型类,支持聚合的模型类参考上面 Ollama 的写法
URL
```
https://api.siliconflow.cn/v1/chat/completions
```
Request Hook
```js
async (args) => {
const url = args.url;
const method = "POST";
const headers = {
"Content-type": "application/json",
Authorization: `Bearer ${args.key}`,
};
const body = {
model: "tencent/Hunyuan-MT-7B", // v2.0.2 版后此处可填 args.model
messages: [
{
role: "system",
content:
"You are a professional, authentic machine translation engine.",
},
{
role: "user",
content: `Translate the following source text to ${args.to}. Output translation directly without any additional text.\n\nSource Text: ${args.texts[0]}\n\nTranslated Text:`,
},
],
temperature: 0,
max_tokens: 20480,
};
return { url, body, headers, method };
};
```
v2.0.6 版后内置默认 promptResponse Hook 可以简化为:
```js
async (args) => {
const url = args.url;
const method = "POST";
const headers = {
"Content-type": "application/json",
Authorization: `Bearer ${args.key}`,
};
const body = {
model: "tencent/Hunyuan-MT-7B", // 或 args.model
messages: [
{
role: "system",
content: args.defaultNobatchPrompt, // 或 args.nobatchPrompt
},
{
role: "user",
content: args.defaultNobatchUserPrompt, // 或 args.nobatchUserPrompt
},
],
temperature: 0,
max_tokens: 20480,
};
return { url, body, headers, method };
};
```
Response Hook
```js
async ({ res }) => {
return { translations: [[res?.choices?.[0]?.message?.content || ""]] };
};
```
## 语言代码表及说明
Hook参数里面的语言含义说明
- `toLang`, `fromLang` 是本插件支持的标准语言代码
- `to`, `from` 是转换后的适用于特定接口的语言代码
如果你的自定义接口与下面的标准语言代码不匹配,需要自行映射转换。
```
["en", "English - English"],
["zh-CN", "Simplified Chinese - 简体中文"],
["zh-TW", "Traditional Chinese - 繁體中文"],
["ar", "Arabic - العربية"],
["bg", "Bulgarian - Български"],
["ca", "Catalan - Català"],
["hr", "Croatian - Hrvatski"],
["cs", "Czech - Čeština"],
["da", "Danish - Dansk"],
["nl", "Dutch - Nederlands"],
["fa", "Persian - فارسی"],
["fi", "Finnish - Suomi"],
["fr", "French - Français"],
["de", "German - Deutsch"],
["el", "Greek - Ελληνικά"],
["hi", "Hindi - हिन्दी"],
["hu", "Hungarian - Magyar"],
["id", "Indonesian - Indonesia"],
["it", "Italian - Italiano"],
["ja", "Japanese - 日本語"],
["ko", "Korean - 한국어"],
["ms", "Malay - Melayu"],
["mt", "Maltese - Malti"],
["nb", "Norwegian - Norsk Bokmål"],
["pl", "Polish - Polski"],
["pt", "Portuguese - Português"],
["ro", "Romanian - Română"],
["ru", "Russian - Русский"],
["sk", "Slovak - Slovenčina"],
["sl", "Slovenian - Slovenščina"],
["es", "Spanish - Español"],
["sv", "Swedish - Svenska"],
["ta", "Tamil - தமிழ்"],
["te", "Telugu - తెలుగు"],
["th", "Thai - ไทย"],
["tr", "Turkish - Türkçe"],
["uk", "Ukrainian - Українська"],
["vi", "Vietnamese - Tiếng Việt"],
```

View File

@@ -1,11 +1,12 @@
{ {
"name": "kiss-translator", "name": "kiss-translator",
"description": "A minimalist bilingual translation Extension & Greasemonkey Script", "description": "A minimalist bilingual translation Extension & Greasemonkey Script",
"version": "1.8.10", "version": "2.0.12",
"author": "Gabe<yugang2002@gmail.com>", "author": "Gabe<yugang2002@gmail.com>",
"private": true, "private": true,
"dependencies": { "dependencies": {
"@emotion/cache": "^11.11.0", "@emotion/cache": "^11.11.0",
"@emotion/css": "^11.13.5",
"@emotion/react": "^11.11.1", "@emotion/react": "^11.11.1",
"@emotion/styled": "^11.11.0", "@emotion/styled": "^11.11.0",
"@mui/icons-material": "^5.15.15", "@mui/icons-material": "^5.15.15",
@@ -25,14 +26,19 @@
"start": "REACT_APP_CLIENT=web react-app-rewired start", "start": "REACT_APP_CLIENT=web react-app-rewired start",
"start:userscript": "REACT_APP_CLIENT=userscript react-app-rewired start", "start:userscript": "REACT_APP_CLIENT=userscript react-app-rewired start",
"build:chrome": "rm -rf build/chrome && BUILD_PATH=./build/chrome REACT_APP_CLIENT=chrome react-app-rewired build && rm build/chrome/content.html", "build:chrome": "rm -rf build/chrome && BUILD_PATH=./build/chrome REACT_APP_CLIENT=chrome react-app-rewired build && rm build/chrome/content.html",
"build:safari-output": "rm -rf build/safari && BUILD_PATH=./build/safari REACT_APP_CLIENT=safari react-app-rewired build && rm build/safari/content.html",
"build:safari": "node src/scripts/build-safari.js",
"build:edge": "rm -rf build/edge && cp -r build/chrome build/edge", "build:edge": "rm -rf build/edge && cp -r build/chrome build/edge",
"build:firefox": "rm -rf build/firefox && cp -r build/chrome build/firefox && cat ./build/firefox/manifest.firefox.json > ./build/firefox/manifest.json && rm build/*/manifest.firefox.json", "build:thunderbird": "rm -rf build/thunderbird && BUILD_PATH=./build/thunderbird REACT_APP_CLIENT=thunderbird react-app-rewired build && rm build/thunderbird/content.html && cp ./build/thunderbird/manifest.thunderbird.json ./build/thunderbird/manifest.json && rm build/*/manifest.thunderbird.json",
"build:firefox": "rm -rf build/firefox && BUILD_PATH=./build/firefox REACT_APP_CLIENT=firefox react-app-rewired build && rm build/firefox/content.html && cat ./build/firefox/manifest.firefox.json > ./build/firefox/manifest.json && rm build/*/manifest.firefox.json",
"build:web": "rm -rf build/web && BUILD_PATH=./build/web REACT_APP_CLIENT=userscript react-app-rewired build", "build:web": "rm -rf build/web && BUILD_PATH=./build/web REACT_APP_CLIENT=userscript react-app-rewired build",
"build:userscript-ios": "file1=build/web/kiss-translator.user.js file2=build/web/kiss-translator-ios-safari.user.js && cp $file1 $file2 && sed -i 's|// @grant unsafeWindow|// @inject-into content|g' $file2", "build:userscript-ios": "file1=build/web/kiss-translator.user.js file2=build/web/kiss-translator-ios-safari.user.js && cp $file1 $file2 && sed -i 's|// @grant unsafeWindow|// @inject-into content|g' $file2",
"build:userscript": "rm -rf build/userscript && mkdir build/userscript && cp build/web/*.user.js build/userscript/", "build:userscript": "rm -rf build/userscript && mkdir build/userscript && cp build/web/*.user.js build/userscript/",
"build:rules": "babel-node src/rules.js", "build:rules": "babel-node src/rules.js",
"build": "pnpm build:chrome && pnpm build:edge && pnpm build:firefox && pnpm build:web && pnpm build:userscript-ios && pnpm build:userscript && pnpm build:rules", "build": "pnpm format && pnpm build:chrome && pnpm build:edge && pnpm build:thunderbird && pnpm build:firefox && pnpm build:web && pnpm build:userscript-ios && pnpm build:userscript && pnpm build:rules",
"zip": "cd build && zip -r chrome.zip chrome && zip -r edge.zip edge && cd firefox && zip -r ../firefox.zip .", "zip": "cd build && rm -f *.zip && zip -r chrome.zip chrome && zip -r edge.zip edge && zip -r userscript.zip userscript && (cd firefox && zip -r ../firefox.zip .) && (cd thunderbird && zip -r ../thunderbird.zip .)",
"build+zip": "pnpm build && pnpm zip",
"format": "prettier --write \"**/*.{js,json,html}\"",
"test": "react-app-rewired test", "test": "react-app-rewired test",
"eject": "react-scripts eject" "eject": "react-scripts eject"
}, },
@@ -44,7 +50,10 @@
"globals": { "globals": {
"GM": true, "GM": true,
"unsafeWindow": true, "unsafeWindow": true,
"globalThis": true "globalThis": true,
"messenger": true,
"LanguageDetector": true,
"Translator": true
} }
}, },
"browserslist": { "browserslist": {
@@ -64,6 +73,10 @@
"@babel/node": "^7.22.19", "@babel/node": "^7.22.19",
"@babel/plugin-proposal-private-property-in-object": "^7.21.11", "@babel/plugin-proposal-private-property-in-object": "^7.21.11",
"@babel/preset-env": "^7.22.20", "@babel/preset-env": "^7.22.20",
"react-app-rewired": "^2.2.1" "dotenv": "^17.2.1",
"find-up": "^7.0.0",
"prettier": "3.6.2",
"react-app-rewired": "^2.2.1",
"zx": "^8.8.1"
} }
} }

12544
pnpm-lock.yaml generated

File diff suppressed because it is too large Load Diff

View File

@@ -0,0 +1,20 @@
{
"app_name": {
"message": "KISS Übersetzer"
},
"app_description": {
"message": "Eine einfache zweisprachige Übersetzungs-Erweiterung und Greasemonkey-Skript"
},
"toggle_translate": {
"message": "Übersetzung umschalten"
},
"toggle_style": {
"message": "Stile umschalten"
},
"open_options": {
"message": "Einstellungen öffnen"
},
"open_tranbox": {
"message": "Popup-Fenster öffnen"
}
}

View File

@@ -6,15 +6,15 @@
"message": "A simple bilingual translation extension & Greasemonkey script" "message": "A simple bilingual translation extension & Greasemonkey script"
}, },
"toggle_translate": { "toggle_translate": {
"message": "Toggle Translate" "message": "Toggle Translation"
}, },
"toggle_style": { "toggle_style": {
"message": "Toggle Style" "message": "Toggle Styles"
}, },
"open_options": { "open_options": {
"message": "Open Options" "message": "Open Setting"
}, },
"open_tranbox": { "open_tranbox": {
"message": "Translate Popup/Selected" "message": "Open Popup Box"
} }
} }

View File

@@ -0,0 +1,20 @@
{
"app_name": {
"message": "KISS Traductor"
},
"app_description": {
"message": "Una sencilla extensión y script de Greasemonkey para traducción bilingüe"
},
"toggle_translate": {
"message": "Alternar traducción"
},
"toggle_style": {
"message": "Cambiar estilo"
},
"open_options": {
"message": "Abrir configuración"
},
"open_tranbox": {
"message": "Abrir ventana emergente"
}
}

View File

@@ -0,0 +1,20 @@
{
"app_name": {
"message": "KISS Traducteur"
},
"app_description": {
"message": "Une extension et un script Greasemonkey de traduction bilingue simple"
},
"toggle_translate": {
"message": "Activer/désactiver la traduction"
},
"toggle_style": {
"message": "Changer de style"
},
"open_options": {
"message": "Ouvrir les paramètres"
},
"open_tranbox": {
"message": "Ouvrir la fenêtre contextuelle"
}
}

View File

@@ -0,0 +1,20 @@
{
"app_name": {
"message": "シンプル翻訳"
},
"app_description": {
"message": "シンプルなバイリンガル対訳翻訳拡張機能Tampermonkeyスクリプト"
},
"toggle_translate": {
"message": "翻訳の切り替え"
},
"toggle_style": {
"message": "スタイル切り替え"
},
"open_options": {
"message": "設定を開く"
},
"open_tranbox": {
"message": "ポップアップを開く"
}
}

View File

@@ -0,0 +1,20 @@
{
"app_name": {
"message": "심플 번역"
},
"app_description": {
"message": "심플한 이중 언어 대조 번역 확장 프로그램 & Tampermonkey 스크립트"
},
"toggle_translate": {
"message": "번역 켜기"
},
"toggle_style": {
"message": "스타일 전환"
},
"open_options": {
"message": "설정 열기"
},
"open_tranbox": {
"message": "팝업 열기"
}
}

View File

@@ -15,6 +15,6 @@
"message": "打开设置" "message": "打开设置"
}, },
"open_tranbox": { "open_tranbox": {
"message": "翻译弹窗/选中文字" "message": "打开弹窗"
} }
} }

View File

@@ -0,0 +1,20 @@
{
"app_name": {
"message": "簡約翻譯"
},
"app_description": {
"message": "一個簡約的雙語對照翻譯擴充功能與 Tampermonkey 腳本"
},
"toggle_translate": {
"message": "開啟翻譯"
},
"toggle_style": {
"message": "切換樣式"
},
"open_options": {
"message": "開啟設定"
},
"open_tranbox": {
"message": "開啟彈出視窗"
}
}

View File

@@ -1,337 +1,14 @@
<!DOCTYPE html> <!doctype html>
<html lang="en"> <html lang="en">
<head> <head>
<meta charset="utf-8" /> <meta charset="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1" /> <meta name="viewport" content="width=device-width, initial-scale=1" />
<title>%REACT_APP_NAME%</title> <title>%REACT_APP_NAME%</title>
<style>
img {
width: 1.2em;
height: 1.2em;
}
svg {
max-width: 1.2em;
max-height: 1.2em;
}
</style>
<script>
document.addEventListener("DOMContentLoaded", function () {
// (() => {
// var shadow = document.querySelector("#shadow1");
// var root = shadow.attachShadow({ mode: "open" });
// var newLine = document.createElement("p");
// newLine.innerText = "new line";
// root.appendChild(newLine);
// })();
// setTimeout(function () {
// var shadow = document.querySelector("#shadow2");
// var root = shadow.attachShadow({ mode: "open" });
// }, 1000);
// setTimeout(() => {
// var newLine = document.createElement("p");
// newLine.innerText = "new line";
// var shadow = document.querySelector("#shadow2");
// shadow.shadowRoot.appendChild(newLine);
// }, 2000);
// setTimeout(() => {
// var newLine = document.createElement("div");
// newLine.innerHTML = "<p>second line</p><p>third line</p>";
// var shadow = document.querySelector("#shadow2");
// shadow.shadowRoot.appendChild(newLine);
// }, 3000);
// setTimeout(function () {
// var el = document.querySelector("h2");
// el.innerText = "hello world";
// var title = document.querySelector("#addtitle");
// title.innerHTML =
// "<div><p>second title</p><ul><li>second title</li><li><p>second title</p></li></ul></div>";
// }, 1000);
setTimeout(function () {
var el = document.querySelector("h2>p>span");
el.innerText = "hello world";
}, 1000);
});
</script>
</head> </head>
<body> <body>
<noscript>You need to enable JavaScript to run this app.</noscript> <noscript>You need to enable JavaScript to run this app.</noscript>
<div id="root"> <div id="root">
<p>You need to enable <code>JavaScript</code> to run <span>this app.</span></p>
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<div id="content">
<p>You need to enable JavaScript to run <span>this app.</span></p>
The <span>embargo</span> has just lifted to confirm that AmpereOne is
coming to Google Cloud with the C3A instances.
<br />
But these upcoming instances for now are only in private preview form.
<br />
<br />
Needless to say I also haven't had any AmpereOne access to check out the
performance and power efficiency of these new Arm server processors from
Ampere Computing.
<br />
</div>
<h2>
<p>
<span
>React is a JavaScript library for building user interfaces.</span
>
</p>
</h2>
<hr />
<input id="input1" style="width: 80%;" />
<hr />
<textarea id="textarea1" style="width: 80%;">test</textarea>
<hr />
<div id="addtitle"></div>
<h2>Shadow 1</h2>
<div id="shadow1"></div>
<h2>Shadow 2</h2>
<div id="shadow2"></div>
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<h2>
React Server Components (or RSC) is a new application architecture
designed by the React team.
</h2>
<iframe
id="iframe1"
width="800px"
height="600px"
src="http://localhost:3000/index.html"
></iframe>
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<h2>
Weve first shared our research on RSC in an introductory talk and an
RFC.
</h2>
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<h2>
To recap them, we are introducing a new kind of component—Server
Components—that run ahead of time and are excluded from your JavaScript
bundle.
</h2>
<iframe
id="iframe2"
width="800px"
height="600px"
src="https://react.dev/"
></iframe>
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<div class="cont cont1">
<h2>
Server Components can run during the build, letting you read from the
filesystem or fetch static content.
</h2>
<ul>
<li>
They can also run on the server, letting you access your data layer
without having to build an API. You can pass data by props from
Server Components to the interactive Client Components in the
browser.
</li>
<li>以声明式编写 UI可以让你的代码更加可靠且方便调试。</li>
</ul>
</div>
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<div class="cont cont2">
<h2>
Since our last update, we have merged the React Server Components RFC
to ratify the proposal.
</h2>
<ul>
<li>
RSC combines the simple “request/response” mental model of
server-centric Multi-Page Apps with the seamless interactivity of
client-centric Single-Page Apps, giving you the best of both worlds.
</li>
<li>
React 使创建交互式 UI
变得轻而易举。为你应用的每一个状态设计简洁的视图,当数据变动时 React
能高效更新并渲染合适的组件。
</li>
<li>以声明式编写 UI可以让你的代码更加可靠且方便调试。</li>
</ul>
</div>
</div> </div>
<!-- <!--
This HTML file is a template. This HTML file is a template.

View File

@@ -1,4 +1,4 @@
<!DOCTYPE html> <!doctype html>
<html lang="en"> <html lang="en">
<head> <head>
<meta charset="utf-8" /> <meta charset="utf-8" />

View File

@@ -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.8.10", "version": "2.0.12",
"default_locale": "en", "default_locale": "en",
"author": "Gabe<yugang2002@gmail.com>", "author": "Gabe<yugang2002@gmail.com>",
"homepage_url": "https://github.com/fishjar/kiss-translator", "homepage_url": "https://github.com/fishjar/kiss-translator",
@@ -12,10 +12,14 @@
"content_scripts": [ "content_scripts": [
{ {
"js": ["content.js"], "js": ["content.js"],
"matches": ["<all_urls>"], "matches": ["<all_urls>", "file://*/*"],
"all_frames": true "all_frames": true
} }
], ],
"web_accessible_resources": [
"injector-subtitle.js",
"injector-shadowroot.js"
],
"commands": { "commands": {
"_execute_browser_action": { "_execute_browser_action": {
"suggested_key": { "suggested_key": {

View File

@@ -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.8.10", "version": "2.0.12",
"default_locale": "en", "default_locale": "en",
"author": "Gabe<yugang2002@gmail.com>", "author": "Gabe<yugang2002@gmail.com>",
"homepage_url": "https://github.com/fishjar/kiss-translator", "homepage_url": "https://github.com/fishjar/kiss-translator",
@@ -13,10 +13,20 @@
"content_scripts": [ "content_scripts": [
{ {
"js": ["content.js"], "js": ["content.js"],
"matches": ["<all_urls>"], "matches": ["<all_urls>", "file://*/*"],
"all_frames": true "all_frames": true
} }
], ],
"web_accessible_resources": [
{
"resources": ["injector-subtitle.js"],
"matches": ["https://www.youtube.com/*"]
},
{
"resources": ["injector-shadowroot.js"],
"matches": ["<all_urls>"]
}
],
"commands": { "commands": {
"_execute_action": { "_execute_action": {
"suggested_key": { "suggested_key": {
@@ -45,12 +55,7 @@
"description": "__MSG_open_options__" "description": "__MSG_open_options__"
} }
}, },
"permissions": [ "permissions": ["storage", "contextMenus", "scripting", "declarativeNetRequest", "declarativeNetRequestWithHostAccess"],
"storage",
"contextMenus",
"scripting",
"declarativeNetRequest"
],
"host_permissions": ["<all_urls>"], "host_permissions": ["<all_urls>"],
"icons": { "icons": {
"16": "images/logo16.png", "16": "images/logo16.png",

View File

@@ -0,0 +1,82 @@
{
"manifest_version": 2,
"name": "__MSG_app_name__",
"description": "__MSG_app_description__",
"version": "2.0.12",
"default_locale": "en",
"author": "Gabe<yugang2002@gmail.com>",
"homepage_url": "https://github.com/fishjar/kiss-translator",
"browser_specific_settings": {
"gecko": {
"id": "yugang2002@gmail.com",
"strict_min_version": "78.0"
}
},
"background": {
"scripts": ["background.js"]
},
"content_scripts": [
{
"js": ["content.js"],
"matches": ["<all_urls>", "file://*/*"],
"all_frames": true
}
],
"web_accessible_resources": [
"injector-subtitle.js",
"injector-shadowroot.js"
],
"commands": {
"_execute_browser_action": {
"suggested_key": {
"default": "Alt+K"
}
},
"toggleTranslate": {
"suggested_key": {
"default": "Alt+Q"
},
"description": "__MSG_toggle_translate__"
},
"openTranbox": {
"suggested_key": {
"default": "Alt+S"
},
"description": "__MSG_open_tranbox__"
},
"toggleStyle": {
"suggested_key": {
"default": "Alt+C"
},
"description": "__MSG_toggle_style__"
},
"openOptions": {
"description": "__MSG_open_options__"
}
},
"permissions": [
"<all_urls>",
"storage",
"menus",
"messagesModify",
"scripting",
"declarativeNetRequest"
],
"icons": {
"16": "images/logo16.png",
"32": "images/logo32.png",
"48": "images/logo48.png",
"128": "images/logo128.png"
},
"browser_action": {
"default_icon": {
"128": "images/logo128.png"
},
"default_title": "__MSG_app_name__",
"default_popup": "popup.html"
},
"options_ui": {
"page": "options.html",
"open_in_tab": true
}
}

View File

@@ -1,23 +1,19 @@
import queryString from "query-string"; import { DEFAULT_USER_AGENT } from "../config";
import { URL_BAIDU_TRANSAPI, DEFAULT_USER_AGENT } from "../config";
export const genBaidu = async ({ text, from, to }) => { export const genBaidu = ({ texts, from, to }) => {
const data = { const body = {
from, from,
to, to,
query: text, query: texts.join(" "),
source: "txt", source: "txt",
}; };
const init = { const url = "https://fanyi.baidu.com/transapi";
headers: { const headers = {
// Origin: "https://fanyi.baidu.com", // Origin: "https://fanyi.baidu.com",
"content-type": "application/x-www-form-urlencoded; charset=UTF-8", "content-type": "application/x-www-form-urlencoded; charset=UTF-8",
"User-Agent": DEFAULT_USER_AGENT, "User-Agent": DEFAULT_USER_AGENT,
},
method: "POST",
body: queryString.stringify(data),
}; };
return [URL_BAIDU_TRANSAPI, init]; return { url, body, headers };
}; };

View File

@@ -1,14 +1,15 @@
import { URL_DEEPLFREE_TRAN } from "../config";
let id = 1e4 * Math.round(1e4 * Math.random()); let id = 1e4 * Math.round(1e4 * Math.random());
export const genDeeplFree = ({ text, from, to }) => { export const genDeeplFree = ({ texts, from, to }) => {
const text = texts.join(" ");
const iCount = (text.match(/[i]/g) || []).length + 1; const iCount = (text.match(/[i]/g) || []).length + 1;
let timestamp = Date.now(); let timestamp = Date.now();
timestamp = timestamp + (iCount - (timestamp % iCount)); timestamp = timestamp + (iCount - (timestamp % iCount));
id++; id++;
let body = JSON.stringify({ const url = "https://www2.deepl.com/jsonrpc";
const body = {
jsonrpc: "2.0", jsonrpc: "2.0",
method: "LMT_handle_texts", method: "LMT_handle_texts",
params: { params: {
@@ -30,29 +31,20 @@ export const genDeeplFree = ({ text, from, to }) => {
}, },
], ],
}, },
});
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]; const 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",
};
return { url, body, headers };
}; };

39
src/apis/history.js Normal file
View File

@@ -0,0 +1,39 @@
import { DEFAULT_CONTEXT_SIZE } from "../config";
const historyMap = new Map();
const MsgHistory = (maxSize = DEFAULT_CONTEXT_SIZE) => {
const messages = [];
const add = (...msgs) => {
messages.push(...msgs.filter(Boolean));
const extra = messages.length - maxSize;
if (extra > 0) {
messages.splice(0, extra);
}
};
const getAll = () => {
return [...messages];
};
const clear = () => {
messages.length = 0;
};
return {
add,
getAll,
clear,
};
};
export const getMsgHistory = (apiSlug, maxSize) => {
if (historyMap.has(apiSlug)) {
return historyMap.get(apiSlug);
}
const msgHistory = MsgHistory(maxSize);
historyMap.set(apiSlug, msgHistory);
return msgHistory;
};

View File

@@ -1,39 +1,33 @@
import queryString from "query-string"; import queryString from "query-string";
import { fetchData } from "../libs/fetch"; import { fetchData } from "../libs/fetch";
import { import {
OPT_TRANS_GOOGLE,
OPT_TRANS_MICROSOFT,
OPT_TRANS_DEEPL,
OPT_TRANS_DEEPLFREE,
OPT_TRANS_DEEPLX,
OPT_TRANS_NIUTRANS,
OPT_TRANS_BAIDU,
OPT_TRANS_TENCENT,
OPT_TRANS_OPENAI,
OPT_TRANS_OPENAI_2,
OPT_TRANS_OPENAI_3,
OPT_TRANS_GEMINI,
OPT_TRANS_CLOUDFLAREAI,
OPT_TRANS_OLLAMA,
OPT_TRANS_OLLAMA_2,
OPT_TRANS_OLLAMA_3,
OPT_TRANS_CUSTOMIZE,
OPT_TRANS_CUSTOMIZE_2,
OPT_TRANS_CUSTOMIZE_3,
OPT_TRANS_CUSTOMIZE_4,
OPT_TRANS_CUSTOMIZE_5,
URL_CACHE_TRAN, URL_CACHE_TRAN,
URL_CACHE_DELANG,
URL_CACHE_BINGDICT,
KV_SALT_SYNC, KV_SALT_SYNC,
URL_BAIDU_LANGDETECT, OPT_LANGS_TO_SPEC,
URL_BAIDU_SUGGEST, OPT_LANGS_SPEC_DEFAULT,
URL_BAIDU_TTS, API_SPE_TYPES,
OPT_LANGS_BAIDU, DEFAULT_API_SETTING,
URL_TENCENT_TRANSMART, OPT_TRANS_MICROSOFT,
OPT_LANGS_TENCENT, MSG_BUILTINAI_DETECT,
OPT_LANGS_SPECIAL, MSG_BUILTINAI_TRANSLATE,
OPT_TRANS_BUILTINAI,
URL_CACHE_SUBTITLE,
OPT_LANGS_TO_CODE,
} from "../config"; } from "../config";
import { sha256 } from "../libs/utils"; import { sha256, withTimeout } from "../libs/utils";
import interpreter from "../libs/interpreter"; import {
handleTranslate,
handleSubtitle,
handleMicrosoftLangdetect,
} from "./trans";
import { getHttpCachePolyfill, putHttpCachePolyfill } from "../libs/cache";
import { getBatchQueue } from "../libs/batchQueue";
import { isBuiltinAIAvailable } from "../libs/browser";
import { chromeDetect, chromeTranslate } from "../libs/builtinAI";
import { fnPolyfill } from "../libs/fetch";
import { getFetchPool } from "../libs/pool";
/** /**
* 同步数据 * 同步数据
@@ -59,13 +53,142 @@ export const apiSyncData = async (url, key, data) =>
*/ */
export const apiFetch = (url) => fetchData(url); export const apiFetch = (url) => fetchData(url);
/**
* Microsoft token
* @returns
*/
export const apiMsAuth = async () =>
fetchData("https://edge.microsoft.com/translate/auth");
/**
* Google语言识别
* @param {*} text
* @returns
*/
export const apiGoogleLangdetect = async (text) => {
const params = {
client: "gtx",
dt: "t",
dj: 1,
ie: "UTF-8",
sl: "auto",
tl: "zh-CN",
q: text,
};
const input = `https://translate.googleapis.com/translate_a/single?${queryString.stringify(params)}`;
const init = {
headers: {
"Content-type": "application/json",
},
};
const res = await fetchData(input, init, { useCache: true });
if (res?.src) {
await putHttpCachePolyfill(input, init, res);
return res.src;
}
return "";
};
/**
* Microsoft语言识别
* @param {*} text
* @returns
*/
export const apiMicrosoftLangdetect = async (text) => {
const cacheOpts = { text, detector: OPT_TRANS_MICROSOFT };
const cacheInput = `${URL_CACHE_DELANG}?${queryString.stringify(cacheOpts)}`;
const cache = await getHttpCachePolyfill(cacheInput);
if (cache) {
return cache;
}
const key = `${URL_CACHE_DELANG}_${OPT_TRANS_MICROSOFT}`;
const queue = getBatchQueue(key, handleMicrosoftLangdetect, {
batchInterval: 200,
batchSize: 20,
batchLength: 100000,
});
const lang = await queue.addTask(text);
if (lang) {
putHttpCachePolyfill(cacheInput, null, lang);
return lang;
}
return "";
};
/**
* Microsoft词典
* @param {*} text
* @returns
*/
export const apiMicrosoftDict = async (text) => {
const cacheOpts = { text };
const cacheInput = `${URL_CACHE_BINGDICT}?${queryString.stringify(cacheOpts)}`;
const cache = await getHttpCachePolyfill(cacheInput);
if (cache) {
return cache;
}
const host = "https://www.bing.com";
const url = `${host}/dict/search?q=${text}&FORM=BDVSP6&cc=cn`;
const str = await fetchData(
url,
{ credentials: "include" },
{ useCache: false }
);
if (!str) {
return null;
}
const parser = new DOMParser();
const doc = parser.parseFromString(str, "text/html");
const word = doc.querySelector("#headword > h1")?.textContent.trim();
if (!word) {
return null;
}
const trs = [];
doc.querySelectorAll("div.qdef > ul > li").forEach(($li) => {
const pos = $li.querySelector(".pos")?.textContent?.trim();
const def = $li.querySelector(".def")?.textContent?.trim();
trs.push({ pos, def });
});
const aus = [];
const $audioUK = doc.querySelector("#bigaud_uk");
const $audioUS = doc.querySelector("#bigaud_us");
if ($audioUK) {
const audioUK = host + $audioUK?.dataset?.mp3link;
const $phoneticUK = $audioUK.parentElement?.previousElementSibling;
const phoneticUK = $phoneticUK?.textContent?.trim();
aus.push({ key: "UK", audio: audioUK, phonetic: phoneticUK });
}
if ($audioUS) {
const audioUS = host + $audioUS?.dataset?.mp3link;
const $phoneticUS = $audioUS.parentElement?.previousElementSibling;
const phoneticUS = $phoneticUS?.textContent?.trim();
aus.push({ key: "US", audio: audioUS, phonetic: phoneticUS });
}
const res = { word, trs, aus };
putHttpCachePolyfill(cacheInput, null, res);
return res;
};
/** /**
* 百度语言识别 * 百度语言识别
* @param {*} text * @param {*} text
* @returns * @returns
*/ */
export const apiBaiduLangdetect = async (text) => { export const apiBaiduLangdetect = async (text) => {
const res = await fetchData(URL_BAIDU_LANGDETECT, { const input = "https://fanyi.baidu.com/langdetect";
const init = {
headers: { headers: {
"Content-type": "application/json", "Content-type": "application/json",
}, },
@@ -73,11 +196,12 @@ export const apiBaiduLangdetect = async (text) => {
body: JSON.stringify({ body: JSON.stringify({
query: text, query: text,
}), }),
useCache: true, };
}); const res = await fetchData(input, init, { useCache: true });
if (res.error === 0) { if (res?.error === 0) {
return OPT_LANGS_BAIDU.get(res.lan) ?? res.lan; await putHttpCachePolyfill(input, init, res);
return res.lan;
} }
return ""; return "";
@@ -89,7 +213,8 @@ export const apiBaiduLangdetect = async (text) => {
* @returns * @returns
*/ */
export const apiBaiduSuggest = async (text) => { export const apiBaiduSuggest = async (text) => {
const res = await fetchData(URL_BAIDU_SUGGEST, { const input = "https://fanyi.baidu.com/sug";
const init = {
headers: { headers: {
"Content-type": "application/json", "Content-type": "application/json",
}, },
@@ -97,16 +222,88 @@ export const apiBaiduSuggest = async (text) => {
body: JSON.stringify({ body: JSON.stringify({
kw: text, kw: text,
}), }),
useCache: true, };
}); const res = await fetchData(input, init, { useCache: true });
if (res.errno === 0) { if (res?.errno === 0) {
await putHttpCachePolyfill(input, init, res);
return res.data; return res.data;
} }
return []; return [];
}; };
/**
* 有道翻译建议
* @param {*} text
* @returns
*/
export const apiYoudaoSuggest = async (text) => {
const params = {
num: 5,
ver: 3.0,
doctype: "json",
cache: false,
le: "en",
q: text,
};
const input = `https://dict.youdao.com/suggest?${queryString.stringify(params)}`;
const init = {
headers: {
accept: "application/json, text/plain, */*",
"accept-language": "en-US,en;q=0.9,zh-CN;q=0.8,zh;q=0.7,ja;q=0.6",
"content-type": "application/x-www-form-urlencoded",
},
method: "GET",
};
const res = await fetchData(input, init, { useCache: true });
if (res?.result?.code === 200) {
await putHttpCachePolyfill(input, init, res);
return res.data.entries;
}
return [];
};
/**
* 有道词典
* @param {*} text
* @returns
*/
export const apiYoudaoDict = async (text) => {
const params = {
doctype: "json",
jsonversion: 4,
};
const input = `https://dict.youdao.com/jsonapi_s?${queryString.stringify(params)}`;
const body = queryString.stringify({
q: text,
le: "en",
t: 3,
client: "web",
// sign: "",
keyfrom: "webdict",
});
const init = {
headers: {
accept: "application/json, text/plain, */*",
"accept-language": "en-US,en;q=0.9,zh-CN;q=0.8,zh;q=0.7,ja;q=0.6",
"content-type": "application/x-www-form-urlencoded",
},
method: "POST",
body,
};
const res = await fetchData(input, init, { useCache: true });
if (res) {
await putHttpCachePolyfill(input, init, res);
return res;
}
return null;
};
/** /**
* 百度语音 * 百度语音
* @param {*} text * @param {*} text
@@ -115,10 +312,8 @@ export const apiBaiduSuggest = async (text) => {
* @returns * @returns
*/ */
export const apiBaiduTTS = (text, lan = "uk", spd = 3) => { export const apiBaiduTTS = (text, lan = "uk", spd = 3) => {
const url = `${URL_BAIDU_TTS}?${queryString.stringify({ lan, text, spd })}`; const input = `https://fanyi.baidu.com/gettts?${queryString.stringify({ lan, text, spd })}`;
return fetchData(url, { return fetchData(input);
useCache: false, // 为避免缓存过快增长,禁用缓存语音数据
});
}; };
/** /**
@@ -127,23 +322,90 @@ export const apiBaiduTTS = (text, lan = "uk", spd = 3) => {
* @returns * @returns
*/ */
export const apiTencentLangdetect = async (text) => { export const apiTencentLangdetect = async (text) => {
const input = "https://transmart.qq.com/api/imt";
const body = JSON.stringify({ const body = JSON.stringify({
header: { header: {
fn: "text_analysis", fn: "text_analysis",
client_key:
"browser-chrome-110.0.0-Mac OS-df4bd4c5-a65d-44b2-a40f-42f34f3535f2-1677486696487",
}, },
text, text,
}); });
const init = {
const res = await fetchData(URL_TENCENT_TRANSMART, {
headers: { headers: {
"Content-type": "application/json", "Content-type": "application/json",
"user-agent":
"Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/110.0.0.0 Safari/537.36",
referer: "https://transmart.qq.com/zh-CN/index",
}, },
method: "POST", method: "POST",
body, body,
useCache: true, };
}); const res = await fetchData(input, init, { useCache: true });
return OPT_LANGS_TENCENT.get(res.language) ?? res.language; if (res?.language) {
await putHttpCachePolyfill(input, init, res);
return res.language;
}
return "";
};
/**
* 浏览器内置AI语言识别
* @param {*} text
* @returns
*/
export const apiBuiltinAIDetect = async (text) => {
if (!isBuiltinAIAvailable) {
return "";
}
const [lang, error] = await fnPolyfill({
fn: chromeDetect,
msg: MSG_BUILTINAI_DETECT,
text,
});
if (!error) {
return lang;
}
return "";
};
/**
* 浏览器内置AI翻译
* @param {*} param0
* @returns
*/
const apiBuiltinAITranslate = async ({ text, from, to, apiSetting }) => {
if (!isBuiltinAIAvailable) {
return ["", true];
}
const { fetchInterval, fetchLimit, httpTimeout } = apiSetting;
const fetchPool = getFetchPool(fetchInterval, fetchLimit);
const result = await withTimeout(
fetchPool.push(fnPolyfill, {
fn: chromeTranslate,
msg: MSG_BUILTINAI_TRANSLATE,
text,
from,
to,
}),
httpTimeout
);
if (!result) {
throw new Error("apiBuiltinAITranslate got null reault");
}
const [trText, srLang, error] = result;
if (error) {
throw new Error("apiBuiltinAITranslate got error", error);
}
return [trText, srLang];
}; };
/** /**
@@ -152,141 +414,146 @@ export const apiTencentLangdetect = async (text) => {
* @returns * @returns
*/ */
export const apiTranslate = async ({ export const apiTranslate = async ({
translator,
text, text,
fromLang, fromLang = "auto",
toLang, toLang,
apiSetting = {}, apiSetting = DEFAULT_API_SETTING,
docInfo = {},
glossary,
useCache = true, useCache = true,
usePool = true, usePool = true,
}) => { }) => {
let trText = "";
let isSame = false;
if (!text) { if (!text) {
return [trText, true]; throw new Error("The text cannot be empty.");
} }
const from = const { apiType, apiSlug, useBatchFetch } = apiSetting;
OPT_LANGS_SPECIAL[translator].get(fromLang) ?? const langMap = OPT_LANGS_TO_SPEC[apiType] || OPT_LANGS_SPEC_DEFAULT;
OPT_LANGS_SPECIAL[translator].get("auto"); const from = langMap.get(fromLang);
const to = OPT_LANGS_SPECIAL[translator].get(toLang); const to = langMap.get(toLang);
if (!to) { if (!to) {
console.log(`[trans] target lang: ${toLang} not support`); throw new Error(`The target lang: ${toLang} not support`);
return [trText, isSame];
} }
// 版本号一/二位升级,旧缓存失效 // todo: 优化缓存失效因素
const [v1, v2] = process.env.REACT_APP_VERSION.split("."); const [v1, v2] = process.env.REACT_APP_VERSION.split(".");
const cacheOpts = { const cacheOpts = {
translator, apiSlug,
text, text,
fromLang, fromLang,
toLang, toLang,
version: [v1, v2].join("."), version: [v1, v2].join("."),
}; };
const cacheInput = `${URL_CACHE_TRAN}?${queryString.stringify(cacheOpts)}`;
const transOpts = { // 查询缓存数据
translator, if (useCache) {
text, const cache = await getHttpCachePolyfill(cacheInput);
from, if (cache?.trText) {
to, return cache;
};
const res = await fetchData(
`${URL_CACHE_TRAN}?${queryString.stringify(cacheOpts)}`,
{
useCache,
usePool,
transOpts,
apiSetting,
} }
);
switch (translator) {
case OPT_TRANS_GOOGLE:
trText = res.sentences.map((item) => item.trans).join(" ");
isSame = to === res.src;
break;
case OPT_TRANS_MICROSOFT:
trText = res
.map((item) => item.translations.map((item) => item.text).join(" "))
.join(" ");
isSame = text === trText;
break;
case OPT_TRANS_DEEPL:
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_NIUTRANS:
const json = JSON.parse(res);
if (json.error_msg) {
throw new Error(json.error_msg);
}
trText = json.tgt_text;
isSame = to === json.from;
break;
case OPT_TRANS_BAIDU:
// trText = res.trans_result?.data.map((item) => item.dst).join(" ");
// isSame = res.trans_result?.to === res.trans_result?.from;
if (res.type === 1) {
trText = Object.keys(JSON.parse(res.result).content[0].mean[0].cont)[0];
isSame = to === res.from;
} else if (res.type === 2) {
trText = res.data.map((item) => item.dst).join(" ");
isSame = to === res.from;
}
break;
case OPT_TRANS_TENCENT:
trText = res.auto_translation;
isSame = text === trText;
break;
case OPT_TRANS_OPENAI:
case OPT_TRANS_OPENAI_2:
case OPT_TRANS_OPENAI_3:
trText = res?.choices?.map((item) => item.message.content).join(" ");
isSame = text === trText;
break;
case OPT_TRANS_GEMINI:
trText = res?.candidates
?.map((item) => item.content?.parts.map((item) => item.text).join(" "))
.join(" ");
isSame = text === trText;
break;
case OPT_TRANS_CLOUDFLAREAI:
trText = res?.result?.translated_text;
isSame = text === trText;
break;
case OPT_TRANS_OLLAMA:
case OPT_TRANS_OLLAMA_2:
case OPT_TRANS_OLLAMA_3:
trText = res?.response;
isSame = text === trText;
break;
case OPT_TRANS_CUSTOMIZE:
case OPT_TRANS_CUSTOMIZE_2:
case OPT_TRANS_CUSTOMIZE_3:
case OPT_TRANS_CUSTOMIZE_4:
case OPT_TRANS_CUSTOMIZE_5:
const { resHook } = apiSetting;
if (resHook?.trim()) {
interpreter.run(`exports.resHook = ${resHook}`);
[trText, isSame] = interpreter.exports.resHook(res, text, from, to);
} else {
trText = res.text;
isSame = to === res.from;
}
break;
default:
} }
return [trText, isSame, res]; // 请求接口数据
let tranlation = [];
if (apiType === OPT_TRANS_BUILTINAI) {
tranlation = await apiBuiltinAITranslate({
text,
from,
to,
apiSetting,
});
} else if (useBatchFetch && API_SPE_TYPES.batch.has(apiType)) {
const { apiSlug, batchInterval, batchSize, batchLength } = apiSetting;
const key = `${apiSlug}_${fromLang}_${toLang}`;
const queue = getBatchQueue(key, handleTranslate, {
batchInterval,
batchSize,
batchLength,
});
tranlation = await queue.addTask(text, {
from,
to,
fromLang,
toLang,
langMap,
docInfo,
glossary,
apiSetting,
usePool,
});
} else {
[tranlation] = await handleTranslate([text], {
from,
to,
fromLang,
toLang,
langMap,
docInfo,
glossary,
apiSetting,
usePool,
});
}
let trText = "";
let srLang = "";
let srCode = "";
if (Array.isArray(tranlation)) {
[trText, srLang = ""] = tranlation;
if (srLang) {
srCode = OPT_LANGS_TO_CODE[apiType].get(srLang) || "";
}
} else if (typeof tranlation === "string") {
trText = tranlation;
}
if (!trText) {
throw new Error("tanslate api got empty trtext");
}
const isSame = fromLang === "auto" && srLang === to;
// 插入缓存
if (useCache) {
putHttpCachePolyfill(cacheInput, null, { trText, isSame, srLang, srCode });
}
return { trText, srLang, srCode, isSame };
};
// 字幕处理/翻译
export const apiSubtitle = async ({
videoId,
chunkSign,
fromLang = "auto",
toLang,
events = [],
apiSetting,
}) => {
const cacheOpts = {
apiSlug: apiSetting.apiSlug,
videoId,
chunkSign,
fromLang,
toLang,
};
const cacheInput = `${URL_CACHE_SUBTITLE}?${queryString.stringify(cacheOpts)}`;
const cache = await getHttpCachePolyfill(cacheInput);
if (cache) {
return cache;
}
const subtitles = await handleSubtitle({
events,
from: fromLang,
to: toLang,
apiSetting,
});
if (subtitles?.length) {
putHttpCachePolyfill(cacheInput, null, subtitles);
return subtitles;
}
return [];
}; };

File diff suppressed because it is too large Load Diff

View File

@@ -2,6 +2,7 @@ import browser from "webextension-polyfill";
import { import {
MSG_FETCH, MSG_FETCH,
MSG_GET_HTTPCACHE, MSG_GET_HTTPCACHE,
MSG_PUT_HTTPCACHE,
MSG_TRANS_TOGGLE, MSG_TRANS_TOGGLE,
MSG_OPEN_OPTIONS, MSG_OPEN_OPTIONS,
MSG_SAVE_RULE, MSG_SAVE_RULE,
@@ -12,26 +13,33 @@ import {
MSG_INJECT_JS, MSG_INJECT_JS,
MSG_INJECT_CSS, MSG_INJECT_CSS,
MSG_UPDATE_CSP, MSG_UPDATE_CSP,
DEFAULT_CSPLIST, MSG_BUILTINAI_DETECT,
MSG_BUILTINAI_TRANSLATE,
CMD_TOGGLE_TRANSLATE, CMD_TOGGLE_TRANSLATE,
CMD_TOGGLE_STYLE, CMD_TOGGLE_STYLE,
CMD_OPEN_OPTIONS, CMD_OPEN_OPTIONS,
CMD_OPEN_TRANBOX, CMD_OPEN_TRANBOX,
CLIENT_THUNDERBIRD,
MSG_SET_LOGLEVEL,
MSG_CLEAR_CACHES,
} from "./config"; } from "./config";
import { getSettingWithDefault, tryInitDefaultData } from "./libs/storage"; import { getSettingWithDefault, tryInitDefaultData } from "./libs/storage";
import { trySyncSettingAndRules } from "./libs/sync"; import { trySyncSettingAndRules } from "./libs/sync";
import { fetchHandle, getHttpCache } from "./libs/fetch"; import { fetchHandle } from "./libs/fetch";
import { tryClearCaches, getHttpCache, putHttpCache } from "./libs/cache";
import { sendTabMsg } from "./libs/msg"; import { sendTabMsg } from "./libs/msg";
import { trySyncAllSubRules } from "./libs/subRules"; import { trySyncAllSubRules } from "./libs/subRules";
import { tryClearCaches } from "./libs";
import { saveRule } from "./libs/rules"; import { saveRule } from "./libs/rules";
import { getCurTabId } from "./libs/msg"; import { getCurTabId } from "./libs/msg";
import { injectInlineJs, injectInternalCss } from "./libs/injector"; import { injectInlineJsBg, injectInternalCss } from "./libs/injector";
import { kissLog } from "./libs/log"; import { kissLog, logger } from "./libs/log";
import { chromeDetect, chromeTranslate } from "./libs/builtinAI";
globalThis.ContextType = "BACKGROUND"; globalThis.__KISS_CONTEXT__ = "background";
const REMOVE_HEADERS = [ const CSP_RULE_START_ID = 1;
const ORI_RULE_START_ID = 10000;
const CSP_REMOVE_HEADERS = [
`content-security-policy`, `content-security-policy`,
`content-security-policy-report-only`, `content-security-policy-report-only`,
`x-webkit-csp`, `x-webkit-csp`,
@@ -46,7 +54,7 @@ async function addContextMenus(contextMenuType = 1) {
try { try {
await browser.contextMenus.removeAll(); await browser.contextMenus.removeAll();
} catch (err) { } catch (err) {
// kissLog("remove contextMenus", err);
} }
switch (contextMenuType) { switch (contextMenuType) {
@@ -92,17 +100,34 @@ async function addContextMenus(contextMenuType = 1) {
* 更新CSP策略 * 更新CSP策略
* @param {*} csplist * @param {*} csplist
*/ */
async function updateCspRules(csplist = DEFAULT_CSPLIST.join(",\n")) { async function updateCspRules({ csplist, orilist }) {
try { try {
const newRules = csplist const oldRules = await browser.declarativeNetRequest.getDynamicRules();
.split(/\n|,/)
.map((url) => url.trim()) const rulesToAdd = [];
.filter(Boolean) const idsToRemove = [];
.map((url, idx) => ({
id: idx + 1, if (csplist !== undefined) {
let processedCspList = csplist;
if (typeof processedCspList === "string") {
processedCspList = processedCspList
.split(/\n|,/)
.map((url) => url.trim())
.filter(Boolean);
}
const oldCspRuleIds = oldRules
.filter(
(rule) => rule.id >= CSP_RULE_START_ID && rule.id < ORI_RULE_START_ID
)
.map((rule) => rule.id);
idsToRemove.push(...oldCspRuleIds);
const newCspRules = processedCspList.map((url, index) => ({
id: CSP_RULE_START_ID + index,
action: { action: {
type: "modifyHeaders", type: "modifyHeaders",
responseHeaders: REMOVE_HEADERS.map((header) => ({ responseHeaders: CSP_REMOVE_HEADERS.map((header) => ({
operation: "remove", operation: "remove",
header, header,
})), })),
@@ -112,93 +137,159 @@ async function updateCspRules(csplist = DEFAULT_CSPLIST.join(",\n")) {
resourceTypes: ["main_frame", "sub_frame"], resourceTypes: ["main_frame", "sub_frame"],
}, },
})); }));
const oldRules = await browser.declarativeNetRequest.getDynamicRules(); rulesToAdd.push(...newCspRules);
const oldRuleIds = oldRules.map((rule) => rule.id); }
await browser.declarativeNetRequest.updateDynamicRules({
removeRuleIds: oldRuleIds, if (orilist !== undefined) {
addRules: newRules, let processedOriList = orilist;
}); if (typeof processedOriList === "string") {
processedOriList = processedOriList
.split(/\n|,/)
.map((url) => url.trim())
.filter(Boolean);
}
const oldOriRuleIds = oldRules
.filter((rule) => rule.id >= ORI_RULE_START_ID)
.map((rule) => rule.id);
idsToRemove.push(...oldOriRuleIds);
const newOriRules = processedOriList.map((url, index) => ({
id: ORI_RULE_START_ID + index,
action: {
type: "modifyHeaders",
requestHeaders: [{ header: "Origin", operation: "set", value: url }],
},
condition: {
urlFilter: url,
resourceTypes: ["xmlhttprequest"],
},
}));
rulesToAdd.push(...newOriRules);
}
if (idsToRemove.length > 0 || rulesToAdd.length > 0) {
await browser.declarativeNetRequest.updateDynamicRules({
removeRuleIds: idsToRemove,
addRules: rulesToAdd,
});
}
} catch (err) { } catch (err) {
kissLog(err, "update csp rules"); kissLog("update csp rules", err);
} }
} }
/**
* 注册邮件显示脚本
*/
async function registerMsgDisplayScript() {
await messenger.messageDisplayScripts.register({
js: [{ file: "/content.js" }],
});
}
/** /**
* 插件安装 * 插件安装
*/ */
browser.runtime.onInstalled.addListener(() => { browser.runtime.onInstalled.addListener(async () => {
tryInitDefaultData(); await tryInitDefaultData();
//在thunderbird中注册脚本
if (process.env.REACT_APP_CLIENT === CLIENT_THUNDERBIRD) {
registerMsgDisplayScript();
}
const { contextMenuType, csplist, orilist } = await getSettingWithDefault();
// 右键菜单 // 右键菜单
addContextMenus(); addContextMenus(contextMenuType);
// 禁用CSP // 禁用CSP
updateCspRules(); updateCspRules({ csplist, orilist });
}); });
/** /**
* 浏览器启动 * 浏览器启动
*/ */
browser.runtime.onStartup.addListener(async () => { browser.runtime.onStartup.addListener(async () => {
// 同步数据 const {
await trySyncSettingAndRules(); clearCache,
contextMenuType,
subrulesList,
csplist,
orilist,
logLevel,
} = await getSettingWithDefault();
const { clearCache, contextMenuType, subrulesList, csplist } = // 设置日志
await getSettingWithDefault(); logger.setLevel(logLevel);
// 清除缓存 // 清除缓存
if (clearCache) { if (clearCache) {
tryClearCaches(); tryClearCaches();
} }
//在thunderbird中注册脚本
if (process.env.REACT_APP_CLIENT === CLIENT_THUNDERBIRD) {
registerMsgDisplayScript();
}
// 右键菜单 // 右键菜单
// firefox重启后菜单会消失,故重复添加 // firefox重启后菜单会消失,故重复添加
addContextMenus(contextMenuType); addContextMenus(contextMenuType);
// 禁用CSP // 禁用CSP
updateCspRules(csplist); updateCspRules({ csplist, orilist });
// 同步数据
trySyncSettingAndRules();
// 同步订阅规则 // 同步订阅规则
trySyncAllSubRules({ subrulesList }); trySyncAllSubRules({ subrulesList });
}); });
/**
* 向当前活动标签页注入脚本或CSS
*/
const injectToCurrentTab = async (func, args) => {
const tabId = await getCurTabId();
return browser.scripting.executeScript({
target: { tabId, allFrames: true },
func: func,
args: [args],
world: "MAIN",
});
};
// 动作处理器映射表
const messageHandlers = {
[MSG_FETCH]: (args) => fetchHandle(args),
[MSG_GET_HTTPCACHE]: (args) => getHttpCache(args),
[MSG_PUT_HTTPCACHE]: (args) => putHttpCache(args),
[MSG_OPEN_OPTIONS]: () => browser.runtime.openOptionsPage(),
[MSG_SAVE_RULE]: (args) => saveRule(args),
[MSG_INJECT_JS]: (args) => injectToCurrentTab(injectInlineJsBg, args),
[MSG_INJECT_CSS]: (args) => injectToCurrentTab(injectInternalCss, args),
[MSG_UPDATE_CSP]: (args) => updateCspRules(args),
[MSG_CONTEXT_MENUS]: (args) => addContextMenus(args),
[MSG_COMMAND_SHORTCUTS]: () => browser.commands.getAll(),
[MSG_BUILTINAI_DETECT]: (args) => chromeDetect(args),
[MSG_BUILTINAI_TRANSLATE]: (args) => chromeTranslate(args),
[MSG_SET_LOGLEVEL]: (args) => logger.setLevel(args),
[MSG_CLEAR_CACHES]: () => tryClearCaches(),
};
/** /**
* 监听消息 * 监听消息
* todo: 返回含错误的结构化信息
*/ */
browser.runtime.onMessage.addListener(async ({ action, args }) => { browser.runtime.onMessage.addListener(async ({ action, args }) => {
switch (action) { const handler = messageHandlers[action];
case MSG_FETCH: if (!handler) {
return await fetchHandle(args); throw new Error(`Message action is unavailable: ${action}`);
case MSG_GET_HTTPCACHE:
const { input, init } = args;
return await getHttpCache(input, init);
case MSG_OPEN_OPTIONS:
return await browser.runtime.openOptionsPage();
case MSG_SAVE_RULE:
return await saveRule(args);
case MSG_INJECT_JS:
return await browser.scripting.executeScript({
target: { tabId: await getCurTabId(), allFrames: true },
func: injectInlineJs,
args: [args],
world: "MAIN",
});
case MSG_INJECT_CSS:
return await browser.scripting.executeScript({
target: { tabId: await getCurTabId(), allFrames: true },
func: injectInternalCss,
args: [args],
world: "MAIN",
});
case MSG_UPDATE_CSP:
return await updateCspRules(args);
case MSG_CONTEXT_MENUS:
return await addContextMenus(args);
case MSG_COMMAND_SHORTCUTS:
return await browser.commands.getAll();
default:
throw new Error(`message action is unavailable: ${action}`);
} }
return handler(args);
}); });
/** /**

View File

@@ -1,29 +1,19 @@
import React from "react"; import { OPT_HIGHLIGHT_WORDS_DISABLE } from "./config";
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, getFabWithDefault,
MSG_TRANS_TOGGLE_STYLE, getSettingWithDefault,
MSG_TRANS_GETRULE, getWordsWithDefault,
MSG_TRANS_PUTRULE, } from "./libs/storage";
MSG_OPEN_TRANBOX, import { isIframe } from "./libs/iframe";
APP_LCNAME, import { genEventName } from "./libs/utils";
DEFAULT_TRANBOX_SETTING,
} from "./config";
import { getFabWithDefault, getSettingWithDefault } from "./libs/storage";
import { Translator } from "./libs/translator";
import { isIframe, sendIframeMsg } from "./libs/iframe";
import Slection from "./views/Selection";
import { touchTapListener } from "./libs/touch";
import { debounce, genEventName } from "./libs/utils";
import { handlePing, injectScript } from "./libs/gm"; import { handlePing, injectScript } from "./libs/gm";
import { browser } from "./libs/browser";
import { matchRule } from "./libs/rules"; import { matchRule } from "./libs/rules";
import { trySyncAllSubRules } from "./libs/subRules"; import { trySyncAllSubRules } from "./libs/subRules";
import { isInBlacklist } from "./libs/blacklist"; import { isInBlacklist } from "./libs/blacklist";
import inputTranslate from "./libs/inputTranslate"; import { runSubtitle } from "./subtitle/subtitle";
import { logger } from "./libs/log";
import { injectInlineJs } from "./libs/injector";
import TranslatorManager from "./libs/translatorManager";
/** /**
* 油猴脚本设置页面 * 油猴脚本设置页面
@@ -39,172 +29,88 @@ function runSettingPage() {
const ping = genEventName(); const ping = genEventName();
window.addEventListener(ping, handlePing); window.addEventListener(ping, handlePing);
// window.eval(`(${injectScript})("${ping}")`); // eslint-disable-line // window.eval(`(${injectScript})("${ping}")`); // eslint-disable-line
const script = document.createElement("script"); injectInlineJs(
script.textContent = `(${injectScript})("${ping}")`; `(${injectScript})("${ping}")`,
document.head.append(script); "kiss-translator-options-injector"
);
} }
} }
/**
* 插件监听后端事件
* @param {*} translator
*/
function runtimeListener(translator) {
browser?.runtime.onMessage.addListener(async ({ action, args }) => {
switch (action) {
case MSG_TRANS_TOGGLE:
translator.toggle();
sendIframeMsg(MSG_TRANS_TOGGLE);
break;
case MSG_TRANS_TOGGLE_STYLE:
translator.toggleStyle();
sendIframeMsg(MSG_TRANS_TOGGLE_STYLE);
break;
case MSG_TRANS_GETRULE:
break;
case MSG_TRANS_PUTRULE:
translator.updateRule(args);
sendIframeMsg(MSG_TRANS_PUTRULE, args);
break;
case MSG_OPEN_TRANBOX:
window.dispatchEvent(new CustomEvent(MSG_OPEN_TRANBOX));
break;
default:
return { error: `message action is unavailable: ${action}` };
}
return { data: translator.rule };
});
}
/**
* iframe 页面执行
* @param {*} translator
*/
function runIframe(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:
translator.updateRule(args || {});
break;
default:
}
});
}
/**
* 悬浮按钮
* @param {*} translator
* @returns
*/
async function showFab(translator) {
const fab = await getFabWithDefault();
const $action = document.createElement("div");
$action.setAttribute("id", APP_LCNAME);
$action.style.fontSize = "0";
$action.style.width = "0";
$action.style.height = "0";
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>
);
}
/**
* 划词翻译
* @param {*} param0
* @returns
*/
function showTransbox({
contextMenuType,
tranboxSetting = DEFAULT_TRANBOX_SETTING,
transApis,
darkMode,
uiLang,
}) {
if (!tranboxSetting?.transOpen) {
return;
}
const $tranbox = document.createElement("div");
$tranbox.setAttribute("id", "kiss-transbox");
$tranbox.style.fontSize = "0";
$tranbox.style.width = "0";
$tranbox.style.height = "0";
document.body.parentElement.appendChild($tranbox);
const shadowContainer = $tranbox.attachShadow({ mode: "closed" });
const emotionRoot = document.createElement("style");
const shadowRootElement = document.createElement("div");
shadowRootElement.classList.add(`KT-transbox`);
shadowRootElement.classList.add(`KT-transbox_${darkMode ? "dark" : "light"}`);
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
contextMenuType={contextMenuType}
tranboxSetting={tranboxSetting}
transApis={transApis}
uiLang={uiLang}
/>
</CacheProvider>
</React.StrictMode>
);
}
/** /**
* 显示错误信息到页面顶部 * 显示错误信息到页面顶部
* @param {*} message * @param {*} message
*/ */
function showErr(message) { function showErr(message) {
const $err = document.createElement("div"); const bannerId = "KISS-Translator-Message";
$err.innerText = `KISS-Translator: ${message}`; const existingBanner = document.getElementById(bannerId);
$err.style.cssText = "background:red; color:#fff;"; if (existingBanner) {
document.body.prepend($err); existingBanner.remove();
}
/**
* 监听触屏操作
* @param {*} translator
* @returns
*/
function touchOperation(translator) {
const { touchTranslate = 2 } = translator.setting;
if (touchTranslate === 0) {
return;
} }
const handleTap = debounce(() => { const banner = document.createElement("div");
translator.toggle(); banner.id = bannerId;
sendIframeMsg(MSG_TRANS_TOGGLE);
Object.assign(banner.style, {
position: "fixed",
top: "0",
left: "0",
width: "100%",
backgroundColor: "#f44336",
color: "white",
textAlign: "center",
padding: "8px 16px",
zIndex: "1001",
boxSizing: "border-box",
fontSize: "16px",
boxShadow: "0 2px 5px rgba(0,0,0,0.2)",
}); });
touchTapListener(handleTap, touchTranslate);
const closeButton = document.createElement("span");
closeButton.textContent = "×";
Object.assign(closeButton.style, {
position: "absolute",
top: "50%",
right: "20px",
transform: "translateY(-50%)",
cursor: "pointer",
fontSize: "22px",
fontWeight: "bold",
});
const messageText = document.createTextNode(`KISS-Translator: ${message}`);
banner.appendChild(messageText);
banner.appendChild(closeButton);
document.body.appendChild(banner);
const removeBanner = () => {
banner.style.transition = "opacity 0.5s ease";
banner.style.opacity = "0";
setTimeout(() => {
if (banner && banner.parentNode) {
banner.parentNode.removeChild(banner);
}
}, 500);
};
closeButton.onclick = removeBanner;
setTimeout(removeBanner, 10000);
}
async function getFavWords(rule) {
if (
rule.highlightWords &&
rule.highlightWords !== OPT_HIGHLIGHT_WORDS_DISABLE
) {
try {
return Object.keys(await getWordsWithDefault());
} catch (err) {
logger.info("get fav words", err);
}
}
return [];
} }
/** /**
@@ -212,7 +118,22 @@ function touchOperation(translator) {
*/ */
export async function run(isUserscript = false) { export async function run(isUserscript = false) {
try { try {
const href = document.location.href; // 读取设置信息
const setting = await getSettingWithDefault();
// 日志
logger.setLevel(setting.logLevel);
// if (document?.documentElement?.tagName?.toUpperCase() !== "HTML") {
// return;
// }
const contentType = document?.contentType?.toLowerCase() || "";
if (!contentType.includes("text") && !contentType.includes("html")) {
logger.info("Skip running in document content type: ", contentType);
return;
}
const href = document?.location?.href || "";
// 设置页面 // 设置页面
if ( if (
@@ -224,9 +145,6 @@ export async function run(isUserscript = false) {
return; return;
} }
// 读取设置信息
const setting = await getSettingWithDefault();
// 黑名单 // 黑名单
if (isInBlacklist(href, setting)) { if (isInBlacklist(href, setting)) {
return; return;
@@ -234,31 +152,28 @@ export async function run(isUserscript = false) {
// 翻译网页 // 翻译网页
const rule = await matchRule(href, setting); const rule = await matchRule(href, setting);
const translator = new Translator(rule, setting); const favWords = await getFavWords(rule);
const fabConfig = await getFabWithDefault();
const translatorManager = new TranslatorManager({
setting,
rule,
fabConfig,
favWords,
isIframe,
isUserscript,
});
translatorManager.start();
// 适配iframe
if (isIframe) { if (isIframe) {
runIframe(translator);
return; return;
} }
// 监听消息 // 字幕翻译
!isUserscript && runtimeListener(translator); runSubtitle({ href, setting, rule, isUserscript });
// 输入框翻译 if (isUserscript) {
inputTranslate(setting); trySyncAllSubRules(setting);
}
// 划词翻译
showTransbox(setting);
// 浮球按钮
await showFab(translator);
// 触屏操作
touchOperation(translator);
// 同步订阅规则
isUserscript && (await trySyncAllSubRules(setting));
} catch (err) { } catch (err) {
console.error("[KISS-Translator]", err); console.error("[KISS-Translator]", err);
showErr(err.message); showErr(err.message);

578
src/config/api.js Normal file
View File

@@ -0,0 +1,578 @@
export const DEFAULT_HTTP_TIMEOUT = 10000; // 调用超时时间
export const DEFAULT_FETCH_LIMIT = 10; // 默认最大任务数量
export const DEFAULT_FETCH_INTERVAL = 100; // 默认任务间隔时间
export const DEFAULT_BATCH_INTERVAL = 400; // 批处理请求间隔时间
export const DEFAULT_BATCH_SIZE = 10; // 每次最多发送段落数量
export const DEFAULT_BATCH_LENGTH = 10000; // 每次发送最大文字数量
export const DEFAULT_CONTEXT_SIZE = 3; // 上下文会话数量
export const INPUT_PLACE_URL = "{{url}}"; // 占位符
export const INPUT_PLACE_FROM = "{{from}}"; // 占位符
export const INPUT_PLACE_TO = "{{to}}"; // 占位符
export const INPUT_PLACE_FROM_LANG = "{{fromLang}}"; // 占位符
export const INPUT_PLACE_TO_LANG = "{{toLang}}"; // 占位符
export const INPUT_PLACE_TEXT = "{{text}}"; // 占位符
export const INPUT_PLACE_TONE = "{{tone}}"; // 占位符
export const INPUT_PLACE_TITLE = "{{title}}"; // 占位符
export const INPUT_PLACE_DESCRIPTION = "{{description}}"; // 占位符
export const INPUT_PLACE_KEY = "{{key}}"; // 占位符
export const INPUT_PLACE_MODEL = "{{model}}"; // 占位符
// export const OPT_DICT_BAIDU = "Baidu";
export const OPT_DICT_BING = "Bing";
export const OPT_DICT_YOUDAO = "Youdao";
export const OPT_DICT_ALL = [OPT_DICT_BING, OPT_DICT_YOUDAO];
export const OPT_DICT_MAP = new Set(OPT_DICT_ALL);
export const OPT_SUG_BAIDU = "Baidu";
export const OPT_SUG_YOUDAO = "Youdao";
export const OPT_SUG_ALL = [OPT_SUG_BAIDU, OPT_SUG_YOUDAO];
export const OPT_SUG_MAP = new Set(OPT_SUG_ALL);
export const OPT_TRANS_BUILTINAI = "BuiltinAI";
export const OPT_TRANS_GOOGLE = "Google";
export const OPT_TRANS_GOOGLE_2 = "Google2";
export const OPT_TRANS_MICROSOFT = "Microsoft";
export const OPT_TRANS_AZUREAI = "AzureAI";
export const OPT_TRANS_DEEPL = "DeepL";
export const OPT_TRANS_DEEPLX = "DeepLX";
export const OPT_TRANS_DEEPLFREE = "DeepLFree";
export const OPT_TRANS_NIUTRANS = "NiuTrans";
export const OPT_TRANS_BAIDU = "Baidu";
export const OPT_TRANS_TENCENT = "Tencent";
export const OPT_TRANS_VOLCENGINE = "Volcengine";
export const OPT_TRANS_OPENAI = "OpenAI";
export const OPT_TRANS_GEMINI = "Gemini";
export const OPT_TRANS_GEMINI_2 = "Gemini2";
export const OPT_TRANS_CLAUDE = "Claude";
export const OPT_TRANS_CLOUDFLAREAI = "CloudflareAI";
export const OPT_TRANS_OLLAMA = "Ollama";
export const OPT_TRANS_OPENROUTER = "OpenRouter";
export const OPT_TRANS_CUSTOMIZE = "Custom";
// 内置支持的翻译引擎
export const OPT_ALL_TRANS_TYPES = [
OPT_TRANS_BUILTINAI,
OPT_TRANS_GOOGLE,
OPT_TRANS_GOOGLE_2,
OPT_TRANS_MICROSOFT,
OPT_TRANS_AZUREAI,
// OPT_TRANS_BAIDU,
OPT_TRANS_TENCENT,
OPT_TRANS_VOLCENGINE,
OPT_TRANS_DEEPL,
OPT_TRANS_DEEPLFREE,
OPT_TRANS_DEEPLX,
OPT_TRANS_NIUTRANS,
OPT_TRANS_OPENAI,
OPT_TRANS_GEMINI,
OPT_TRANS_GEMINI_2,
OPT_TRANS_CLAUDE,
OPT_TRANS_CLOUDFLAREAI,
OPT_TRANS_OLLAMA,
OPT_TRANS_OPENROUTER,
OPT_TRANS_CUSTOMIZE,
];
export const OPT_LANGDETECTOR_ALL = [
OPT_TRANS_BUILTINAI,
OPT_TRANS_GOOGLE,
OPT_TRANS_MICROSOFT,
OPT_TRANS_BAIDU,
OPT_TRANS_TENCENT,
];
export const OPT_LANGDETECTOR_MAP = new Set(OPT_LANGDETECTOR_ALL);
// 翻译引擎特殊集合
export const API_SPE_TYPES = {
// 内置翻译
builtin: new Set(OPT_ALL_TRANS_TYPES),
// 机器翻译
machine: new Set([
OPT_TRANS_MICROSOFT,
OPT_TRANS_DEEPLFREE,
OPT_TRANS_BAIDU,
OPT_TRANS_TENCENT,
OPT_TRANS_VOLCENGINE,
]),
// AI翻译
ai: new Set([
OPT_TRANS_OPENAI,
OPT_TRANS_GEMINI,
OPT_TRANS_GEMINI_2,
OPT_TRANS_CLAUDE,
OPT_TRANS_OLLAMA,
OPT_TRANS_OPENROUTER,
]),
// 支持多key
mulkeys: new Set([
OPT_TRANS_AZUREAI,
OPT_TRANS_DEEPL,
OPT_TRANS_OPENAI,
OPT_TRANS_GEMINI,
OPT_TRANS_GEMINI_2,
OPT_TRANS_CLAUDE,
OPT_TRANS_CLOUDFLAREAI,
OPT_TRANS_OLLAMA,
OPT_TRANS_OPENROUTER,
OPT_TRANS_NIUTRANS,
OPT_TRANS_CUSTOMIZE,
]),
// 支持批处理
batch: new Set([
OPT_TRANS_AZUREAI,
OPT_TRANS_GOOGLE_2,
OPT_TRANS_MICROSOFT,
OPT_TRANS_TENCENT,
OPT_TRANS_DEEPL,
OPT_TRANS_OPENAI,
OPT_TRANS_GEMINI,
OPT_TRANS_GEMINI_2,
OPT_TRANS_CLAUDE,
OPT_TRANS_OLLAMA,
OPT_TRANS_OPENROUTER,
OPT_TRANS_CUSTOMIZE,
]),
// 支持上下文
context: new Set([
OPT_TRANS_OPENAI,
OPT_TRANS_GEMINI,
OPT_TRANS_GEMINI_2,
OPT_TRANS_CLAUDE,
OPT_TRANS_OLLAMA,
OPT_TRANS_OPENROUTER,
OPT_TRANS_CUSTOMIZE,
]),
};
export const BUILTIN_STONES = [
"formal", // 正式风格
"casual", // 口语风格
"neutral", // 中性风格
"technical", // 技术风格
"marketing", // 营销风格
"Literary", // 文学风格
"academic", // 学术风格
"legal", // 法律风格
"literal", // 直译风格
"ldiomatic", // 意译风格
"transcreation", // 创译风格
"machine-like", // 机器风格
"concise", // 简明风格
];
export const BUILTIN_PLACEHOLDERS = ["{ }", "{{ }}", "[ ]", "[[ ]]"];
export const BUILTIN_PLACETAGS = ["i", "a", "b", "x"];
export const OPT_LANGS_TO = [
["en", "English - English"],
["zh-CN", "Simplified Chinese - 简体中文"],
["zh-TW", "Traditional Chinese - 繁體中文"],
["ar", "Arabic - العربية"],
["bg", "Bulgarian - Български"],
["ca", "Catalan - Català"],
["hr", "Croatian - Hrvatski"],
["cs", "Czech - Čeština"],
["da", "Danish - Dansk"],
["nl", "Dutch - Nederlands"],
["fa", "Persian - فارسی"],
["fi", "Finnish - Suomi"],
["fr", "French - Français"],
["de", "German - Deutsch"],
["el", "Greek - Ελληνικά"],
["hi", "Hindi - हिन्दी"],
["hu", "Hungarian - Magyar"],
["id", "Indonesian - Indonesia"],
["it", "Italian - Italiano"],
["ja", "Japanese - 日本語"],
["ko", "Korean - 한국어"],
["ms", "Malay - Melayu"],
["mt", "Maltese - Malti"],
["nb", "Norwegian - Norsk Bokmål"],
["pl", "Polish - Polski"],
["pt", "Portuguese - Português"],
["ro", "Romanian - Română"],
["ru", "Russian - Русский"],
["sk", "Slovak - Slovenčina"],
["sl", "Slovenian - Slovenščina"],
["es", "Spanish - Español"],
["sv", "Swedish - Svenska"],
["ta", "Tamil - தமிழ்"],
["te", "Telugu - తెలుగు"],
["th", "Thai - ไทย"],
["tr", "Turkish - Türkçe"],
["uk", "Ukrainian - Українська"],
["vi", "Vietnamese - Tiếng Việt"],
];
export const OPT_LANGS_LIST = OPT_LANGS_TO.map(([lang]) => lang);
export const OPT_LANGS_FROM = [["auto", "Auto-detect"], ...OPT_LANGS_TO];
export const OPT_LANGS_MAP = new Map(OPT_LANGS_TO);
// CODE->名称
export const OPT_LANGS_SPEC_NAME = new Map(
OPT_LANGS_FROM.map(([key, val]) => [key, val.split(" - ")[0]])
);
export const OPT_LANGS_SPEC_DEFAULT = new Map(
OPT_LANGS_FROM.map(([key]) => [key, key])
);
export const OPT_LANGS_SPEC_DEFAULT_UC = new Map(
OPT_LANGS_FROM.map(([key]) => [key, key.toUpperCase()])
);
export const OPT_LANGS_TO_SPEC = {
[OPT_TRANS_BUILTINAI]: new Map([
...OPT_LANGS_SPEC_DEFAULT,
["zh-CN", "zh"],
["zh-TW", "zh"],
]),
[OPT_TRANS_GOOGLE]: OPT_LANGS_SPEC_DEFAULT,
[OPT_TRANS_GOOGLE_2]: OPT_LANGS_SPEC_DEFAULT,
[OPT_TRANS_MICROSOFT]: new Map([
...OPT_LANGS_SPEC_DEFAULT,
["auto", ""],
["zh-CN", "zh-Hans"],
["zh-TW", "zh-Hant"],
]),
[OPT_TRANS_AZUREAI]: new Map([
...OPT_LANGS_SPEC_DEFAULT,
["auto", ""],
["zh-CN", "zh-Hans"],
["zh-TW", "zh-Hant"],
]),
[OPT_TRANS_DEEPL]: new Map([
...OPT_LANGS_SPEC_DEFAULT_UC,
["auto", ""],
["zh-CN", "ZH"],
["zh-TW", "ZH"],
]),
[OPT_TRANS_DEEPLFREE]: new Map([
...OPT_LANGS_SPEC_DEFAULT_UC,
["auto", "auto"],
["zh-CN", "ZH"],
["zh-TW", "ZH"],
]),
[OPT_TRANS_DEEPLX]: new Map([
...OPT_LANGS_SPEC_DEFAULT_UC,
["auto", "auto"],
["zh-CN", "ZH"],
["zh-TW", "ZH"],
]),
[OPT_TRANS_NIUTRANS]: new Map([
...OPT_LANGS_SPEC_DEFAULT,
["auto", "auto"],
["zh-CN", "zh"],
["zh-TW", "cht"],
]),
[OPT_TRANS_VOLCENGINE]: new Map([
...OPT_LANGS_SPEC_DEFAULT,
["auto", "auto"],
["zh-CN", "zh"],
["zh-TW", "zh-Hant"],
]),
[OPT_TRANS_BAIDU]: new Map([
...OPT_LANGS_SPEC_DEFAULT,
["zh-CN", "zh"],
["zh-TW", "cht"],
["ar", "ara"],
["bg", "bul"],
["ca", "cat"],
["hr", "hrv"],
["da", "dan"],
["fi", "fin"],
["fr", "fra"],
["hi", "mai"],
["ja", "jp"],
["ko", "kor"],
["ms", "may"],
["mt", "mlt"],
["nb", "nor"],
["ro", "rom"],
["ru", "ru"],
["sl", "slo"],
["es", "spa"],
["sv", "swe"],
["ta", "tam"],
["te", "tel"],
["uk", "ukr"],
["vi", "vie"],
]),
[OPT_TRANS_TENCENT]: new Map([
["auto", "auto"],
["zh-CN", "zh"],
["zh-TW", "zh"],
["en", "en"],
["ar", "ar"],
["de", "de"],
["ru", "ru"],
["fr", "fr"],
["fi", "fil"],
["ko", "ko"],
["ms", "ms"],
["pt", "pt"],
["ja", "ja"],
["th", "th"],
["tr", "tr"],
["es", "es"],
["it", "it"],
["hi", "hi"],
["id", "id"],
["vi", "vi"],
]),
[OPT_TRANS_OPENAI]: OPT_LANGS_SPEC_NAME,
[OPT_TRANS_GEMINI]: OPT_LANGS_SPEC_NAME,
[OPT_TRANS_GEMINI_2]: OPT_LANGS_SPEC_NAME,
[OPT_TRANS_CLAUDE]: OPT_LANGS_SPEC_NAME,
[OPT_TRANS_OLLAMA]: OPT_LANGS_SPEC_NAME,
[OPT_TRANS_OPENROUTER]: OPT_LANGS_SPEC_NAME,
[OPT_TRANS_CLOUDFLAREAI]: OPT_LANGS_SPEC_NAME,
[OPT_TRANS_CUSTOMIZE]: OPT_LANGS_SPEC_NAME,
};
const specToCode = (m) =>
new Map(
Array.from(m.entries()).map(([k, v]) => {
if (v === "") {
return ["auto", "auto"];
}
if (v === "zh" || v === "ZH") {
return [v, "zh-CN"];
}
return [v, k];
})
);
// 名称->CODE
export const OPT_LANGS_TO_CODE = {};
Object.entries(OPT_LANGS_TO_SPEC).forEach(([t, m]) => {
OPT_LANGS_TO_CODE[t] = specToCode(m);
});
export const defaultNobatchPrompt = `You are a professional, authentic machine translation engine.`;
export const defaultNobatchUserPrompt = `Translate the following source text to ${INPUT_PLACE_TO}. Output translation directly without any additional text.\n\nSource Text: ${INPUT_PLACE_TEXT}\n\nTranslated Text:`;
export const defaultSystemPrompt = `Act as a translation API. Output a single raw JSON object only. No extra text or fences.
Input:
{"targetLanguage":"<lang>","title":"<context>","description":"<context>","segments":[{"id":1,"text":"..."}],"glossary":{"sourceTerm":"targetTerm"},"tone":"<formal|casual>"}
Output:
{"translations":[{"id":1,"text":"...","sourceLanguage":"<detected>"}]}
Rules:
1. Use title/description for context only; do not output them.
2. Keep id, order, and count of segments.
3. Preserve whitespace, HTML entities, and all HTML-like tags (e.g., <i1>, <a1>). Translate inner text only.
4. Highest priority: Follow 'glossary'. Use value for translation; if value is "", keep the key.
5. Do not translate: content in <code>, <pre>, text enclosed in backticks, or placeholders like {1}, {{1}}, [1], [[1]].
6. Apply the specified tone to the translation.
7. Detect sourceLanguage for each segment.
8. Return empty or unchanged inputs as is.
Example:
Input: {"targetLanguage":"zh-CN","segments":[{"id":1,"text":"A <b>React</b> component."}],"glossary":{"component":"组件","React":""}}
Output: {"translations":[{"id":1,"text":"一个<b>React</b>组件","sourceLanguage":"en"}]}
Fail-safe: On any error, return {"translations":[]}.`;
// const defaultSubtitlePrompt = `Goal: Convert raw subtitle event JSON into a clean, sentence-based JSON array.
// Output (valid JSON array, output ONLY this array):
// [{
// "text": "string", // Full sentence with correct punctuation
// "translation": "string", // Translation in ${INPUT_PLACE_TO}
// "start": int, // Start time (ms)
// "end": int, // End time (ms)
// }]
// Guidelines:
// 1. **Segmentation**: Merge sequential 'utf8' strings from 'segs' into full sentences, merging groups logically.
// 2. **Punctuation**: Ensure proper sentence-final punctuation (., ?, !); add if missing.
// 3. **Translation**: Translate 'text' into ${INPUT_PLACE_TO}, place result in 'translation'.
// 4. **Special Cases**: '[Music]' (and similar cues) are standalone entries. Translate appropriately (e.g., '[音乐]', '[Musique]').
// `;
export const defaultSubtitlePrompt = `You are an expert AI for subtitle generation. Convert a JSON array of word-level timestamps into a bilingual VTT file.
**Workflow:**
1. Merge \`text\` fields into complete sentences; ignore empty text.
2. Split long sentences into smaller, manageable subtitle cues (one sentence per cue).
3. Translate each cue into ${INPUT_PLACE_TO}.
4. Format as VTT:
- Start with \`WEBVTT\`.
- Each cue: timestamps (\`start --> end\` in milliseconds), original text, translated text.
- Keep non-speech text (e.g., \`[Music]\`) untranslated.
- Separate cues with a blank line.
**Output:** Only the pure VTT content.
**Example:**
\`\`\`vtt
WEBVTT
1000 --> 3500
Hello world!
你好,世界!
4000 --> 6000
Good morning.
早上好。
\`\`\``;
const defaultRequestHook = `async (args, { url, body, headers, userMsg, method } = {}) => {
console.log("request hook args:", { args, url, body, headers, userMsg, method });
// return { url, body, headers, userMsg, method };
};`;
const defaultResponseHook = `async ({ res, ...args }) => {
console.log("reaponse hook args:", { res, args });
// const translations = [["你好", "zh"]];
// const modelMsg = "";
// return { translations, modelMsg };
};`;
// 翻译接口默认参数
const defaultApi = {
apiSlug: "", // 唯一标识
apiName: "", // 接口名称
apiType: "", // 接口类型
url: "",
key: "",
model: "", // 模型名称
systemPrompt: defaultSystemPrompt,
subtitlePrompt: defaultSubtitlePrompt,
nobatchPrompt: defaultNobatchPrompt,
nobatchUserPrompt: defaultNobatchUserPrompt,
userPrompt: "",
tone: BUILTIN_STONES[0], // 翻译风格
placeholder: BUILTIN_PLACEHOLDERS[0], // 占位符
placetag: [BUILTIN_PLACETAGS[0]], // 占位标签
// aiTerms: false, // AI智能专业术语 todo: 备用)
customHeader: "",
customBody: "",
reqHook: "", // request 钩子函数
resHook: "", // response 钩子函数
fetchLimit: DEFAULT_FETCH_LIMIT, // 最大请求数量
fetchInterval: DEFAULT_FETCH_INTERVAL, // 请求间隔时间
httpTimeout: DEFAULT_HTTP_TIMEOUT * 3, // 请求超时时间
batchInterval: DEFAULT_BATCH_INTERVAL, // 批处理请求间隔时间
batchSize: DEFAULT_BATCH_SIZE, // 每次最多发送段落数量
batchLength: DEFAULT_BATCH_LENGTH, // 每次发送最大文字数量
useBatchFetch: false, // 是否启用聚合发送请求
useContext: false, // 是否启用智能上下文
contextSize: DEFAULT_CONTEXT_SIZE, // 智能上下文保留会话数
temperature: 0.0,
maxTokens: 20480,
// think: false, // (OpenAI 兼容接口未支持,暂时移除)
// thinkIgnore: "qwen3,deepseek-r1", // (OpenAI 兼容接口未支持,暂时移除)
isDisabled: false, // 是否不显示,
region: "", // Azure 专用
};
const defaultApiOpts = {
[OPT_TRANS_BUILTINAI]: defaultApi,
[OPT_TRANS_GOOGLE]: {
...defaultApi,
url: "https://translate.googleapis.com/translate_a/single",
},
[OPT_TRANS_GOOGLE_2]: {
...defaultApi,
url: "https://translate-pa.googleapis.com/v1/translateHtml",
key: "AIzaSyATBXajvzQLTDHEQbcpq0Ihe0vWDHmO520",
useBatchFetch: true,
},
[OPT_TRANS_MICROSOFT]: {
...defaultApi,
useBatchFetch: true,
},
[OPT_TRANS_AZUREAI]: {
...defaultApi,
url: "https://api.cognitive.microsofttranslator.com/translate?api-version=3.0",
useBatchFetch: true,
},
[OPT_TRANS_BAIDU]: {
...defaultApi,
},
[OPT_TRANS_TENCENT]: {
...defaultApi,
useBatchFetch: true,
},
[OPT_TRANS_VOLCENGINE]: {
...defaultApi,
},
[OPT_TRANS_DEEPL]: {
...defaultApi,
url: "https://api-free.deepl.com/v2/translate",
useBatchFetch: true,
},
[OPT_TRANS_DEEPLFREE]: {
...defaultApi,
fetchLimit: 1,
},
[OPT_TRANS_DEEPLX]: {
...defaultApi,
url: "http://localhost:1188/translate",
},
[OPT_TRANS_NIUTRANS]: {
...defaultApi,
url: "https://api.niutrans.com/NiuTransServer/translation",
dictNo: "",
memoryNo: "",
},
[OPT_TRANS_OPENAI]: {
...defaultApi,
url: "https://api.openai.com/v1/chat/completions",
model: "gpt-4",
useBatchFetch: true,
},
[OPT_TRANS_GEMINI]: {
...defaultApi,
url: `https://generativelanguage.googleapis.com/v1/models/${INPUT_PLACE_MODEL}:generateContent?key=${INPUT_PLACE_KEY}`,
model: "gemini-2.5-flash",
useBatchFetch: true,
},
[OPT_TRANS_GEMINI_2]: {
...defaultApi,
url: `https://generativelanguage.googleapis.com/v1beta/openai/chat/completions`,
model: "gemini-2.0-flash",
useBatchFetch: true,
},
[OPT_TRANS_CLAUDE]: {
...defaultApi,
url: "https://api.anthropic.com/v1/messages",
model: "claude-3-haiku-20240307",
useBatchFetch: true,
},
[OPT_TRANS_CLOUDFLAREAI]: {
...defaultApi,
url: "https://api.cloudflare.com/client/v4/accounts/{{ACCOUNT_ID}}/ai/run/@cf/meta/m2m100-1.2b",
},
[OPT_TRANS_OLLAMA]: {
...defaultApi,
url: "http://localhost:11434/v1/chat/completions",
model: "llama3.1",
useBatchFetch: true,
},
[OPT_TRANS_OPENROUTER]: {
...defaultApi,
url: "https://openrouter.ai/api/v1/chat/completions",
model: "openai/gpt-4o",
useBatchFetch: true,
},
[OPT_TRANS_CUSTOMIZE]: {
...defaultApi,
reqHook: defaultRequestHook,
resHook: defaultResponseHook,
},
};
// 内置翻译接口列表(带参数)
export const DEFAULT_API_LIST = OPT_ALL_TRANS_TYPES.map((apiType) => ({
...defaultApiOpts[apiType],
apiSlug: apiType,
apiName: apiType,
apiType,
}));
export const DEFAULT_API_TYPE = OPT_TRANS_MICROSOFT;
export const DEFAULT_API_SETTING = DEFAULT_API_LIST.find(
(a) => a.apiType === DEFAULT_API_TYPE
);

View File

@@ -2,3 +2,14 @@ export const APP_NAME = process.env.REACT_APP_NAME.trim()
.split(/\s+/) .split(/\s+/)
.join("-"); .join("-");
export const APP_LCNAME = APP_NAME.toLowerCase(); export const APP_LCNAME = APP_NAME.toLowerCase();
export const APP_UPNAME = APP_NAME.toUpperCase();
export const APP_CONSTS = {
fabID: `${APP_LCNAME}-fab`,
boxID: `${APP_LCNAME}-box`,
popupID: `${APP_LCNAME}-popup`,
};
export const APP_VERSION = process.env.REACT_APP_VERSION.split(".");
export const THEME_LIGHT = "light";
export const THEME_DARK = "dark";

15
src/config/client.js Normal file
View File

@@ -0,0 +1,15 @@
export const CLIENT_WEB = "web";
export const CLIENT_CHROME = "chrome";
export const CLIENT_EDGE = "edge";
export const CLIENT_FIREFOX = "firefox";
export const CLIENT_USERSCRIPT = "userscript";
export const CLIENT_THUNDERBIRD = "thunderbird";
export const CLIENT_EXTS = [
CLIENT_CHROME,
CLIENT_EDGE,
CLIENT_FIREFOX,
CLIENT_THUNDERBIRD,
];
export const DEFAULT_USER_AGENT =
"Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/123.0.0.0 Safari/537.36";

File diff suppressed because it is too large Load Diff

View File

@@ -1,653 +1,10 @@
import { export * from "./app";
DEFAULT_SELECTOR, export * from "./rules";
DEFAULT_KEEP_SELECTOR, export * from "./api";
GLOBAL_KEY, export * from "./setting";
REMAIN_KEY, export * from "./i18n";
SHADOW_KEY, export * from "./storage";
DEFAULT_RULE, export * from "./url";
DEFAULT_OW_RULE, export * from "./msg";
BUILTIN_RULES, export * from "./client";
} from "./rules"; export * from "./styles";
import { APP_NAME, APP_LCNAME } from "./app";
export { I18N, UI_LANGS } from "./i18n";
export {
GLOBAL_KEY,
REMAIN_KEY,
SHADOW_KEY,
DEFAULT_RULE,
DEFAULT_OW_RULE,
BUILTIN_RULES,
APP_LCNAME,
};
export const STOKEY_MSAUTH = `${APP_NAME}_msauth`;
export const STOKEY_BDAUTH = `${APP_NAME}_bdauth`;
export const STOKEY_SETTING = `${APP_NAME}_setting`;
export const STOKEY_RULES = `${APP_NAME}_rules`;
export const STOKEY_WORDS = `${APP_NAME}_words`;
export const STOKEY_SYNC = `${APP_NAME}_sync`;
export const STOKEY_FAB = `${APP_NAME}_fab`;
export const STOKEY_RULESCACHE_PREFIX = `${APP_NAME}_rulescache_`;
export const CMD_TOGGLE_TRANSLATE = "toggleTranslate";
export const CMD_TOGGLE_STYLE = "toggleStyle";
export const CMD_OPEN_OPTIONS = "openOptions";
export const CMD_OPEN_TRANBOX = "openTranbox";
export const CLIENT_WEB = "web";
export const CLIENT_CHROME = "chrome";
export const CLIENT_EDGE = "edge";
export const CLIENT_FIREFOX = "firefox";
export const CLIENT_USERSCRIPT = "userscript";
export const CLIENT_EXTS = [CLIENT_CHROME, CLIENT_EDGE, CLIENT_FIREFOX];
export const KV_RULES_KEY = "kiss-rules.json";
export const KV_WORDS_KEY = "kiss-words.json";
export const KV_RULES_SHARE_KEY = "kiss-rules-share.json";
export const KV_SETTING_KEY = "kiss-setting.json";
export const KV_SALT_SYNC = "KISS-Translator-SYNC";
export const KV_SALT_SHARE = "KISS-Translator-SHARE";
export const CACHE_NAME = `${APP_NAME}_cache`;
export const MSG_FETCH = "fetch";
export const MSG_GET_HTTPCACHE = "get_httpcache";
export const MSG_OPEN_OPTIONS = "open_options";
export const MSG_SAVE_RULE = "save_rule";
export const MSG_TRANS_TOGGLE = "trans_toggle";
export const MSG_TRANS_TOGGLE_STYLE = "trans_toggle_style";
export const MSG_OPEN_TRANBOX = "open_tranbox";
export const MSG_TRANS_GETRULE = "trans_getrule";
export const MSG_TRANS_PUTRULE = "trans_putrule";
export const MSG_TRANS_CURRULE = "trans_currule";
export const MSG_CONTEXT_MENUS = "context_menus";
export const MSG_COMMAND_SHORTCUTS = "command_shortcuts";
export const MSG_INJECT_JS = "inject_js";
export const MSG_INJECT_CSS = "inject_css";
export const MSG_UPDATE_CSP = "update_csp";
export const THEME_LIGHT = "light";
export const THEME_DARK = "dark";
export const URL_KISS_WORKER = "https://github.com/fishjar/kiss-worker";
export const URL_KISS_PROXY = "https://github.com/fishjar/kiss-proxy";
export const URL_KISS_RULES = "https://github.com/fishjar/kiss-rules";
export const URL_KISS_RULES_NEW_ISSUE =
"https://github.com/fishjar/kiss-rules/issues/new";
export const URL_RAW_PREFIX =
"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_BAIDU_LANGDETECT = "https://fanyi.baidu.com/langdetect";
export const URL_BAIDU_SUGGEST = "https://fanyi.baidu.com/sug";
export const URL_BAIDU_TTS = "https://fanyi.baidu.com/gettts";
export const URL_BAIDU_WEB = "https://fanyi.baidu.com/";
export const URL_BAIDU_TRANSAPI = "https://fanyi.baidu.com/transapi";
export const URL_BAIDU_TRANSAPI_V2 = "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 URL_NIUTRANS_REG =
"https://niutrans.com/login?active=3&userSource=kiss-translator";
export const DEFAULT_USER_AGENT =
"Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/123.0.0.0 Safari/537.36";
export const OPT_TRANS_GOOGLE = "Google";
export const OPT_TRANS_MICROSOFT = "Microsoft";
export const OPT_TRANS_DEEPL = "DeepL";
export const OPT_TRANS_DEEPLX = "DeepLX";
export const OPT_TRANS_DEEPLFREE = "DeepLFree";
export const OPT_TRANS_NIUTRANS = "NiuTrans";
export const OPT_TRANS_BAIDU = "Baidu";
export const OPT_TRANS_TENCENT = "Tencent";
export const OPT_TRANS_OPENAI = "OpenAI";
export const OPT_TRANS_OPENAI_2 = "OpenAI2";
export const OPT_TRANS_OPENAI_3 = "OpenAI3";
export const OPT_TRANS_GEMINI = "Gemini";
export const OPT_TRANS_CLOUDFLAREAI = "CloudflareAI";
export const OPT_TRANS_OLLAMA = "Ollama";
export const OPT_TRANS_OLLAMA_2 = "Ollama2";
export const OPT_TRANS_OLLAMA_3 = "Ollama3";
export const OPT_TRANS_CUSTOMIZE = "Custom";
export const OPT_TRANS_CUSTOMIZE_2 = "Custom2";
export const OPT_TRANS_CUSTOMIZE_3 = "Custom3";
export const OPT_TRANS_CUSTOMIZE_4 = "Custom4";
export const OPT_TRANS_CUSTOMIZE_5 = "Custom5";
export const OPT_TRANS_ALL = [
OPT_TRANS_GOOGLE,
OPT_TRANS_MICROSOFT,
OPT_TRANS_BAIDU,
OPT_TRANS_TENCENT,
OPT_TRANS_DEEPL,
OPT_TRANS_DEEPLFREE,
OPT_TRANS_DEEPLX,
OPT_TRANS_NIUTRANS,
OPT_TRANS_OPENAI,
OPT_TRANS_OPENAI_2,
OPT_TRANS_OPENAI_3,
OPT_TRANS_GEMINI,
OPT_TRANS_CLOUDFLAREAI,
OPT_TRANS_OLLAMA,
OPT_TRANS_OLLAMA_2,
OPT_TRANS_OLLAMA_3,
OPT_TRANS_CUSTOMIZE,
OPT_TRANS_CUSTOMIZE_2,
OPT_TRANS_CUSTOMIZE_3,
OPT_TRANS_CUSTOMIZE_4,
OPT_TRANS_CUSTOMIZE_5,
];
export const OPT_LANGS_TO = [
["en", "English - English"],
["zh-CN", "Simplified Chinese - 简体中文"],
["zh-TW", "Traditional Chinese - 繁體中文"],
["ar", "Arabic - العربية"],
["bg", "Bulgarian - Български"],
["ca", "Catalan - Català"],
["hr", "Croatian - Hrvatski"],
["cs", "Czech - Čeština"],
["da", "Danish - Dansk"],
["nl", "Dutch - Nederlands"],
["fi", "Finnish - Suomi"],
["fr", "French - Français"],
["de", "German - Deutsch"],
["el", "Greek - Ελληνικά"],
["hi", "Hindi - हिन्दी"],
["hu", "Hungarian - Magyar"],
["id", "Indonesian - Indonesia"],
["it", "Italian - Italiano"],
["ja", "Japanese - 日本語"],
["ko", "Korean - 한국어"],
["ms", "Malay - Melayu"],
["mt", "Maltese - Malti"],
["nb", "Norwegian - Norsk Bokmål"],
["pl", "Polish - Polski"],
["pt", "Portuguese - Português"],
["ro", "Romanian - Română"],
["ru", "Russian - Русский"],
["sk", "Slovak - Slovenčina"],
["sl", "Slovenian - Slovenščina"],
["es", "Spanish - Español"],
["sv", "Swedish - Svenska"],
["ta", "Tamil - தமிழ்"],
["te", "Telugu - తెలుగు"],
["th", "Thai - ไทย"],
["tr", "Turkish - Türkçe"],
["uk", "Ukrainian - Українська"],
["vi", "Vietnamese - Tiếng Việt"],
];
export const OPT_LANGS_FROM = [["auto", "Auto-detect"], ...OPT_LANGS_TO];
export const OPT_LANGS_SPECIAL = {
[OPT_TRANS_GOOGLE]: new Map(OPT_LANGS_FROM.map(([key]) => [key, key])),
[OPT_TRANS_MICROSOFT]: new Map([
...OPT_LANGS_FROM.map(([key]) => [key, key]),
["auto", ""],
["zh-CN", "zh-Hans"],
["zh-TW", "zh-Hant"],
]),
[OPT_TRANS_DEEPL]: new Map([
...OPT_LANGS_FROM.map(([key]) => [key, key.toUpperCase()]),
["auto", ""],
["zh-CN", "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_NIUTRANS]: new Map([
...OPT_LANGS_FROM.map(([key]) => [key, key]),
["auto", "auto"],
["zh-CN", "zh"],
["zh-TW", "cht"],
]),
[OPT_TRANS_BAIDU]: new Map([
...OPT_LANGS_FROM.map(([key]) => [key, key]),
["zh-CN", "zh"],
["zh-TW", "cht"],
["ar", "ara"],
["bg", "bul"],
["ca", "cat"],
["hr", "hrv"],
["da", "dan"],
["fi", "fin"],
["fr", "fra"],
["hi", "mai"],
["ja", "jp"],
["ko", "kor"],
["ms", "may"],
["mt", "mlt"],
["nb", "nor"],
["ro", "rom"],
["ru", "ru"],
["sl", "slo"],
["es", "spa"],
["sv", "swe"],
["ta", "tam"],
["te", "tel"],
["uk", "ukr"],
["vi", "vie"],
]),
[OPT_TRANS_TENCENT]: new Map([
["auto", "auto"],
["zh-CN", "zh"],
["zh-TW", "zh"],
["en", "en"],
["ar", "ar"],
["de", "de"],
["ru", "ru"],
["fr", "fr"],
["fi", "fil"],
["ko", "ko"],
["ms", "ms"],
["pt", "pt"],
["ja", "ja"],
["th", "th"],
["tr", "tr"],
["es", "es"],
["it", "it"],
["hi", "hi"],
["id", "id"],
["vi", "vi"],
]),
[OPT_TRANS_OPENAI]: new Map(
OPT_LANGS_FROM.map(([key, val]) => [key, val.split(" - ")[0]])
),
[OPT_TRANS_OPENAI_2]: new Map(
OPT_LANGS_FROM.map(([key, val]) => [key, val.split(" - ")[0]])
),
[OPT_TRANS_OPENAI_3]: new Map(
OPT_LANGS_FROM.map(([key, val]) => [key, val.split(" - ")[0]])
),
[OPT_TRANS_GEMINI]: new Map(
OPT_LANGS_FROM.map(([key, val]) => [key, val.split(" - ")[0]])
),
[OPT_TRANS_OLLAMA]: new Map(
OPT_LANGS_FROM.map(([key, val]) => [key, val.split(" - ")[0]])
),
[OPT_TRANS_OLLAMA_2]: new Map(
OPT_LANGS_FROM.map(([key, val]) => [key, val.split(" - ")[0]])
),
[OPT_TRANS_OLLAMA_3]: new Map(
OPT_LANGS_FROM.map(([key, val]) => [key, val.split(" - ")[0]])
),
[OPT_TRANS_CLOUDFLAREAI]: new Map([
["auto", ""],
["zh-CN", "chinese"],
["zh-TW", "chinese"],
["en", "english"],
["ar", "arabic"],
["de", "german"],
["ru", "russian"],
["fr", "french"],
["pt", "portuguese"],
["ja", "japanese"],
["es", "spanish"],
["hi", "hindi"],
]),
[OPT_TRANS_CUSTOMIZE]: new Map([
...OPT_LANGS_FROM.map(([key]) => [key, key]),
["auto", ""],
]),
[OPT_TRANS_CUSTOMIZE_2]: new Map([
...OPT_LANGS_FROM.map(([key]) => [key, key]),
["auto", ""],
]),
[OPT_TRANS_CUSTOMIZE_3]: new Map([
...OPT_LANGS_FROM.map(([key]) => [key, key]),
["auto", ""],
]),
[OPT_TRANS_CUSTOMIZE_4]: new Map([
...OPT_LANGS_FROM.map(([key]) => [key, key]),
["auto", ""],
]),
[OPT_TRANS_CUSTOMIZE_5]: new Map([
...OPT_LANGS_FROM.map(([key]) => [key, key]),
["auto", ""],
]),
};
export const OPT_LANGS_LIST = OPT_LANGS_TO.map(([lang]) => lang);
export const OPT_LANGS_BAIDU = new Map(
Array.from(OPT_LANGS_SPECIAL[OPT_TRANS_BAIDU].entries()).map(([k, v]) => [
v,
k,
])
);
export const OPT_LANGS_TENCENT = new Map(
Array.from(OPT_LANGS_SPECIAL[OPT_TRANS_TENCENT].entries()).map(([k, v]) => [
v,
k,
])
);
OPT_LANGS_TENCENT.set("zh", "zh-CN");
export const OPT_STYLE_NONE = "style_none"; // 无
export const OPT_STYLE_LINE = "under_line"; // 下划线
export const OPT_STYLE_DOTLINE = "dot_line"; // 点状线
export const OPT_STYLE_DASHLINE = "dash_line"; // 虚线
export const OPT_STYLE_WAVYLINE = "wavy_line"; // 波浪线
export const OPT_STYLE_FUZZY = "fuzzy"; // 模糊
export const OPT_STYLE_HIGHLIGHT = "highlight"; // 高亮
export const OPT_STYLE_BLOCKQUOTE = "blockquote"; // 引用
export const OPT_STYLE_DIY = "diy_style"; // 自定义样式
export const OPT_STYLE_ALL = [
OPT_STYLE_NONE,
OPT_STYLE_LINE,
OPT_STYLE_DOTLINE,
OPT_STYLE_DASHLINE,
OPT_STYLE_WAVYLINE,
OPT_STYLE_FUZZY,
OPT_STYLE_HIGHLIGHT,
OPT_STYLE_BLOCKQUOTE,
OPT_STYLE_DIY,
];
export const OPT_STYLE_USE_COLOR = [
OPT_STYLE_LINE,
OPT_STYLE_DOTLINE,
OPT_STYLE_DASHLINE,
OPT_STYLE_WAVYLINE,
OPT_STYLE_HIGHLIGHT,
OPT_STYLE_BLOCKQUOTE,
];
export const OPT_TIMING_PAGESCROLL = "mk_pagescroll"; // 滚动加载翻译
export const OPT_TIMING_PAGEOPEN = "mk_pageopen"; // 直接翻译到底
export const OPT_TIMING_MOUSEOVER = "mk_mouseover";
export const OPT_TIMING_CONTROL = "mk_ctrlKey";
export const OPT_TIMING_SHIFT = "mk_shiftKey";
export const OPT_TIMING_ALT = "mk_altKey";
export const OPT_TIMING_ALL = [
OPT_TIMING_PAGESCROLL,
OPT_TIMING_PAGEOPEN,
OPT_TIMING_MOUSEOVER,
OPT_TIMING_CONTROL,
OPT_TIMING_SHIFT,
OPT_TIMING_ALT,
];
export const DEFAULT_FETCH_LIMIT = 10; // 默认最大任务数量
export const DEFAULT_FETCH_INTERVAL = 100; // 默认任务间隔时间
export const INPUT_PLACE_URL = "{{url}}"; // 占位符
export const INPUT_PLACE_FROM = "{{from}}"; // 占位符
export const INPUT_PLACE_TO = "{{to}}"; // 占位符
export const INPUT_PLACE_TEXT = "{{text}}"; // 占位符
export const INPUT_PLACE_KEY = "{{key}}"; // 占位符
export const INPUT_PLACE_MODEL = "{{model}}"; // 占位符
export const DEFAULT_COLOR = "#209CEE"; // 默认高亮背景色/线条颜色
export const DEFAULT_TRANS_TAG = "span";
export const DEFAULT_SELECT_STYLE =
"-webkit-line-clamp: unset; max-height: none; height: auto;";
// 全局规则
export const GLOBLA_RULE = {
pattern: "*", // 匹配网址
selector: DEFAULT_SELECTOR, // 选择器
keepSelector: DEFAULT_KEEP_SELECTOR, // 保留元素选择器
terms: "", // 专业术语
translator: OPT_TRANS_MICROSOFT, // 翻译服务
fromLang: "auto", // 源语言
toLang: "zh-CN", // 目标语言
textStyle: OPT_STYLE_DASHLINE, // 译文样式
transOpen: "false", // 开启翻译
bgColor: "", // 译文颜色
textDiyStyle: "", // 自定义译文样式
selectStyle: DEFAULT_SELECT_STYLE, // 选择器节点样式
parentStyle: DEFAULT_SELECT_STYLE, // 选择器父节点样式
injectJs: "", // 注入JS
injectCss: "", // 注入CSS
transOnly: "false", // 是否仅显示译文
transTiming: OPT_TIMING_PAGESCROLL, // 翻译时机/鼠标悬停翻译
transTag: DEFAULT_TRANS_TAG, // 译文元素标签
transTitle: "false", // 是否同时翻译页面标题
detectRemote: "false", // 是否使用远程语言检测
skipLangs: [], // 不翻译的语言
fixerSelector: "", // 修复函数选择器
fixerFunc: "-", // 修复函数
transStartHook: "", // 钩子函数
transEndHook: "", // 钩子函数
transRemoveHook: "", // 钩子函数
};
// 输入框翻译
export const OPT_INPUT_TRANS_SIGNS = ["/", "//", "\\", "\\\\", ">", ">>"];
export const DEFAULT_INPUT_SHORTCUT = ["AltLeft", "KeyI"];
export const DEFAULT_INPUT_RULE = {
transOpen: true,
translator: OPT_TRANS_MICROSOFT,
fromLang: "auto",
toLang: "en",
triggerShortcut: DEFAULT_INPUT_SHORTCUT,
triggerCount: 1,
triggerTime: 200,
transSign: OPT_INPUT_TRANS_SIGNS[0],
};
// 划词翻译
export const PHONIC_MAP = {
en_phonic: ["英", "uk"],
us_phonic: ["美", "en"],
};
export const OPT_TRANBOX_TRIGGER_CLICK = "click";
export const OPT_TRANBOX_TRIGGER_HOVER = "hover";
export const OPT_TRANBOX_TRIGGER_SELECT = "select";
export const OPT_TRANBOX_TRIGGER_ALL = [
OPT_TRANBOX_TRIGGER_CLICK,
OPT_TRANBOX_TRIGGER_HOVER,
OPT_TRANBOX_TRIGGER_SELECT,
];
export const DEFAULT_TRANBOX_SHORTCUT = ["AltLeft", "KeyS"];
export const DEFAULT_TRANBOX_SETTING = {
transOpen: true,
translator: OPT_TRANS_MICROSOFT,
fromLang: "auto",
toLang: "zh-CN",
toLang2: "en",
tranboxShortcut: DEFAULT_TRANBOX_SHORTCUT,
btnOffsetX: 10,
btnOffsetY: 10,
boxOffsetX: 0,
boxOffsetY: 10,
hideTranBtn: false, // 是否隐藏翻译按钮
hideClickAway: false, // 是否点击外部关闭弹窗
simpleStyle: false, // 是否简洁界面
followSelection: false, // 翻译框是否跟随选中文本
triggerMode: OPT_TRANBOX_TRIGGER_CLICK, // 触发翻译方式
extStyles: "", // 附加样式
};
// 订阅列表
export const DEFAULT_SUBRULES_LIST = [
{
url: process.env.REACT_APP_RULESURL,
selected: false,
},
{
url: process.env.REACT_APP_RULESURL_ON,
selected: true,
},
{
url: process.env.REACT_APP_RULESURL_OFF,
selected: false,
},
];
// 翻译接口
const defaultCustomApi = {
url: "",
key: "",
customOption: "", // (作废)
reqHook: "", // request 钩子函数
resHook: "", // response 钩子函数
fetchLimit: DEFAULT_FETCH_LIMIT,
fetchInterval: DEFAULT_FETCH_INTERVAL,
};
const defaultOpenaiApi = {
url: "https://api.openai.com/v1/chat/completions",
key: "",
model: "gpt-4",
prompt: `You will be provided with a sentence in ${INPUT_PLACE_FROM}, and your task is to translate it into ${INPUT_PLACE_TO}.`,
fetchLimit: 1,
fetchInterval: 500,
};
const defaultOllamaApi = {
url: "http://localhost:11434/api/generate",
key: "",
model: "llama3",
prompt: `Translate the following text from ${INPUT_PLACE_FROM} to ${INPUT_PLACE_TO}:\n\n${INPUT_PLACE_TEXT}`,
fetchLimit: 1,
fetchInterval: 500,
};
export const DEFAULT_TRANS_APIS = {
[OPT_TRANS_GOOGLE]: {
url: "https://translate.googleapis.com/translate_a/single",
key: "",
fetchLimit: DEFAULT_FETCH_LIMIT, // 最大任务数量
fetchInterval: DEFAULT_FETCH_INTERVAL, // 任务间隔时间
},
[OPT_TRANS_MICROSOFT]: {
fetchLimit: DEFAULT_FETCH_LIMIT,
fetchInterval: DEFAULT_FETCH_INTERVAL,
},
[OPT_TRANS_BAIDU]: {
fetchLimit: DEFAULT_FETCH_LIMIT,
fetchInterval: DEFAULT_FETCH_INTERVAL,
},
[OPT_TRANS_TENCENT]: {
fetchLimit: DEFAULT_FETCH_LIMIT,
fetchInterval: DEFAULT_FETCH_INTERVAL,
},
[OPT_TRANS_DEEPL]: {
url: "https://api-free.deepl.com/v2/translate",
key: "",
fetchLimit: 1,
fetchInterval: 500,
},
[OPT_TRANS_DEEPLFREE]: {
fetchLimit: 1,
fetchInterval: 500,
},
[OPT_TRANS_DEEPLX]: {
url: "http://localhost:1188/translate",
key: "",
fetchLimit: 1,
fetchInterval: 500,
},
[OPT_TRANS_NIUTRANS]: {
url: "https://api.niutrans.com/NiuTransServer/translation",
key: "",
dictNo: "",
memoryNo: "",
fetchLimit: DEFAULT_FETCH_LIMIT,
fetchInterval: DEFAULT_FETCH_INTERVAL,
},
[OPT_TRANS_OPENAI]: defaultOpenaiApi,
[OPT_TRANS_OPENAI_2]: defaultOpenaiApi,
[OPT_TRANS_OPENAI_3]: defaultOpenaiApi,
[OPT_TRANS_GEMINI]: {
url: `https://generativelanguage.googleapis.com/v1/models/${INPUT_PLACE_MODEL}:generateContent?key=${INPUT_PLACE_KEY}`,
key: "",
model: "gemini-pro",
prompt: `Translate the following text from ${INPUT_PLACE_FROM} to ${INPUT_PLACE_TO}:\n\n${INPUT_PLACE_TEXT}`,
fetchLimit: 1,
fetchInterval: 500,
},
[OPT_TRANS_CLOUDFLAREAI]: {
url: "https://api.cloudflare.com/client/v4/accounts/{{ACCOUNT_ID}}/ai/run/@cf/meta/m2m100-1.2b",
key: "",
fetchLimit: 1,
fetchInterval: 500,
},
[OPT_TRANS_OLLAMA]: defaultOllamaApi,
[OPT_TRANS_OLLAMA_2]: defaultOllamaApi,
[OPT_TRANS_OLLAMA_3]: defaultOllamaApi,
[OPT_TRANS_CUSTOMIZE]: defaultCustomApi,
[OPT_TRANS_CUSTOMIZE_2]: defaultCustomApi,
[OPT_TRANS_CUSTOMIZE_3]: defaultCustomApi,
[OPT_TRANS_CUSTOMIZE_4]: defaultCustomApi,
[OPT_TRANS_CUSTOMIZE_5]: defaultCustomApi,
};
// 默认快捷键
export const OPT_SHORTCUT_TRANSLATE = "toggleTranslate";
export const OPT_SHORTCUT_STYLE = "toggleStyle";
export const OPT_SHORTCUT_POPUP = "togglePopup";
export const OPT_SHORTCUT_SETTING = "openSetting";
export const DEFAULT_SHORTCUTS = {
[OPT_SHORTCUT_TRANSLATE]: ["AltLeft", "KeyQ"],
[OPT_SHORTCUT_STYLE]: ["AltLeft", "KeyC"],
[OPT_SHORTCUT_POPUP]: ["AltLeft", "KeyK"],
[OPT_SHORTCUT_SETTING]: ["AltLeft", "KeyO"],
};
export const TRANS_MIN_LENGTH = 5; // 最短翻译长度
export const TRANS_MAX_LENGTH = 5000; // 最长翻译长度
export const TRANS_NEWLINE_LENGTH = 20; // 换行字符数
export const DEFAULT_BLACKLIST = [
"https://fishjar.github.io/kiss-translator/options.html",
"https://translate.google.com",
"https://www.deepl.com/translator",
"oapi.dingtalk.com",
"login.dingtalk.com",
]; // 禁用翻译名单
export const DEFAULT_CSPLIST = ["https://github.com"]; // 禁用CSP名单
export const DEFAULT_SETTING = {
darkMode: false, // 深色模式
uiLang: "en", // 界面语言
// fetchLimit: DEFAULT_FETCH_LIMIT, // 最大任务数量(移至transApis作废)
// fetchInterval: DEFAULT_FETCH_INTERVAL, // 任务间隔时间(移至transApis作废)
minLength: TRANS_MIN_LENGTH,
maxLength: TRANS_MAX_LENGTH,
newlineLength: TRANS_NEWLINE_LENGTH,
clearCache: false, // 是否在浏览器下次启动时清除缓存
injectRules: true, // 是否注入订阅规则
// injectWebfix: true, // 是否注入修复补丁(作废)
// detectRemote: false, // 是否使用远程语言检测(移至rule作废)
// contextMenus: true, // 是否添加右键菜单(作废)
contextMenuType: 1, // 右键菜单类型(0不显示1简单菜单2多级菜单)
// transTag: DEFAULT_TRANS_TAG, // 译文元素标签(移至rule作废)
// transOnly: false, // 是否仅显示译文(移至rule作废)
// transTitle: false, // 是否同时翻译页面标题(移至rule作废)
subrulesList: DEFAULT_SUBRULES_LIST, // 订阅列表
owSubrule: DEFAULT_OW_RULE, // 覆写订阅规则
transApis: DEFAULT_TRANS_APIS, // 翻译接口
// mouseKey: OPT_TIMING_PAGESCROLL, // 翻译时机/鼠标悬停翻译(移至rule作废)
shortcuts: DEFAULT_SHORTCUTS, // 快捷键
inputRule: DEFAULT_INPUT_RULE, // 输入框设置
tranboxSetting: DEFAULT_TRANBOX_SETTING, // 划词翻译设置
touchTranslate: 2, // 触屏翻译
blacklist: DEFAULT_BLACKLIST.join(",\n"), // 禁用翻译名单
csplist: DEFAULT_CSPLIST.join(",\n"), // 禁用CSP名单
// disableLangs: [], // 不翻译的语言(移至rule作废)
transInterval: 500, // 翻译间隔时间
};
export const DEFAULT_RULES = [GLOBLA_RULE];
export const OPT_SYNCTYPE_WORKER = "KISS-Worker";
export const OPT_SYNCTYPE_WEBDAV = "WebDAV";
export const OPT_SYNCTYPE_ALL = [OPT_SYNCTYPE_WORKER, OPT_SYNCTYPE_WEBDAV];
export const DEFAULT_SYNC = {
syncType: OPT_SYNCTYPE_WORKER, // 同步方式
syncUrl: "", // 数据同步接口
syncUser: "", // 数据同步用户名
syncKey: "", // 数据同步密钥
syncMeta: {}, // 数据更新及同步信息
subRulesSyncAt: 0, // 订阅规则同步时间
dataCaches: {}, // 缓存同步时间
};

38
src/config/msg.js Normal file
View File

@@ -0,0 +1,38 @@
export const CMD_TOGGLE_TRANSLATE = "toggleTranslate";
export const CMD_TOGGLE_STYLE = "toggleStyle";
export const CMD_OPEN_OPTIONS = "openOptions";
export const CMD_OPEN_TRANBOX = "openTranbox";
export const MSG_FETCH = "kiss_fetch";
export const MSG_GET_HTTPCACHE = "get_httpcache";
export const MSG_PUT_HTTPCACHE = "put_httpcache";
export const MSG_OPEN_OPTIONS = "open_options";
export const MSG_SAVE_RULE = "save_rule";
export const MSG_TRANS_TOGGLE = "trans_toggle";
export const MSG_TRANS_TOGGLE_STYLE = "trans_toggle_style";
export const MSG_OPEN_TRANBOX = "open_tranbox";
export const MSG_TRANS_GETRULE = "trans_getrule";
export const MSG_TRANS_PUTRULE = "trans_putrule";
export const MSG_TRANS_CURRULE = "trans_currule";
export const MSG_TRANSBOX_TOGGLE = "transbox_toggle";
export const MSG_POPUP_TOGGLE = "popup_toggle";
export const MSG_MOUSEHOVER_TOGGLE = "mousehover_toggle";
export const MSG_TRANSINPUT_TOGGLE = "transinput_toggle";
export const MSG_CONTEXT_MENUS = "context_menus";
export const MSG_COMMAND_SHORTCUTS = "command_shortcuts";
export const MSG_INJECT_JS = "inject_js";
export const MSG_INJECT_CSS = "inject_css";
export const MSG_UPDATE_CSP = "update_csp";
export const MSG_BUILTINAI_DETECT = "builtinai_detect";
export const MSG_BUILTINAI_TRANSLATE = "builtinai_translte";
export const MSG_SET_LOGLEVEL = "set_loglevel";
export const MSG_CLEAR_CACHES = "clear_caches";
export const EVENT_KISS = "event_kiss_translate";
export const MSG_XHR_DATA_YOUTUBE = "KISS_XHR_DATA_YOUTUBE";
// export const MSG_GLOBAL_VAR_FETCH = "KISS_GLOBAL_VAR_FETCH";
// export const MSG_GLOBAL_VAR_BACK = "KISS_GLOBAL_VAR_BACK";
export const MSG_MENUS_PROGRESSED = "progressed";
export const MSG_MENUS_UPDATEFORM = "updateFormData";

713
src/config/quotes.js Normal file
View File

@@ -0,0 +1,713 @@
const quotes = [
{
en: "The unexamined life is not worth living.",
zh: "未经审视的人生不值得过。",
zh_TW: "未經審視的人生不值得過。",
ja: "吟味されない人生は生きるに値しない。",
ko: "성찰하지 않는 삶은 살 가치가 없다。",
},
{
en: "I think, therefore I am.",
zh: "我思故我在。",
zh_TW: "我思故我在。",
ja: "我思う、ゆえに我あり。",
ko: "나는 생각한다, 고로 존재한다。",
},
{
en: "He who has a why to live for can bear almost any how.",
zh: "知道为何而活的人,几乎能忍受任何一种生活。",
zh_TW: "知道為何而活的人,幾乎能忍受任何一種生活。",
ja: "生きるための「なぜ」を持つ者は、ほとんどあらゆる「どのように」にも耐えることができる。",
ko: "살아야 할 이유를 아는 사람은 거의 모든 상황을 견딜 수 있다。",
},
{
en: "Life is what happens when you're busy making other plans.",
zh: "生活就是当你忙着制定其他计划时所发生的事情。",
zh_TW: "生活就是當你忙著制定其他計劃時所發生的事情。",
ja: "人生とは、他の計画を立てるのに忙しいときに起こるものだ。",
ko: "인생은 다른 계획을 세우느라 바쁠 때 일어나는 일이다。",
},
{
en: "Get busy living or get busy dying.",
zh: "要么忙着活,要么忙着死。",
zh_TW: "要么忙著活,要么忙著死。",
ja: "必死に生きるか、必死に死ぬかだ。",
ko: "바쁘게 살거나, 바쁘게 죽거나。",
},
{
en: "We are what we repeatedly do. Excellence, then, is not an act, but a habit.",
zh: "我们由我们反复做的事情构成的。因此,卓越不是一种行为,而是一种习惯。",
zh_TW:
"我們由我們反覆做的事情構成的。因此,卓越不是一種行為,而是一種習慣。",
ja: "我々は繰り返し行うことの集大成である。卓越とは行為ではなく、習慣なのだ。",
ko: "우리는 우리가 반복적으로 하는 일의 결과물이다. 그렇다면 탁월함은 행동이 아니라 습관이다。",
},
{
en: "Man is condemned to be free.",
zh: "人注定是自由的。",
zh_TW: "人註定是自由的。",
ja: "人間は自由であるように呪われている。",
ko: "인간은 자유롭도록 저주받았다。",
},
{
en: "To be, or not to be: that is the question.",
zh: "生存还是毁灭,这是一个问题。",
zh_TW: "生存還是毀滅,這是一個問題。",
ja: "生きるべきか、死ぬべきか、それが問題だ。",
ko: "죽느냐 사느냐, 그것이 문제로다。",
},
{
en: "The purpose of life is not to be happy. It is to be useful, to be honorable, to be compassionate, to have it make some difference that you have lived and lived well.",
zh: "人生的目的不是快乐,而是有用、高尚、富有同情心,让你活过并且活得好,从而使世界有所不同。",
zh_TW:
"人生的目的不是快樂,而是有用、高尚、富有同情心,讓你活過並且活得好,從而使世界有所不同。",
ja: "人生(じんせい)の目的(もくてき)は幸(しあわ)せになることではない。役(やく)に立(た)つこと、名誉(めいよ)あること、思(おも)いやりを持(も)つこと、そして自分(じぶん)が生(い)きてきたこと、よく生(い)きたことが何(なに)かの違(ちが)いをもたらすようにすることだ。",
ko: "삶의 목적은 행복해지는 것이 아니다. 유용하고, 명예롭고, 자비로우며, 당신이 살았고 잘 살았다는 것이 어떤 차이를 만들도록 하는 것이다。",
},
{
en: "Life is 10% what happens to us and 90% how we react to it.",
zh: "生活 10% 取决于发生在我们身上的事90% 取决于我们如何反应。",
zh_TW: "生活 10% 取決於發生在我們身上的事90% 取決於我們如何反應。",
ja: "人生は、我々に起こることが10で、それにどう反応するかが90だ。",
ko: "인생은 우리에게 일어나는 일이 10%이고, 그 일에 대해 우리가 어떻게 반응하느냐가 90%이다。",
},
{
en: "The two most important days in your life are the day you are born and the day you find out why.",
zh: "你一生中最重要的两天是:你出生的那天和你明白你为何出生的那天。",
zh_TW: "你一生中最重要的兩天是:你出生的那天和你明白你為何出生的那天。",
ja: "人生で最も重要な日は二日ある。生まれた日と、なぜ生まれたかを悟る日だ。",
ko: "당신의 인생에서 가장 중요한 날은 두 번이다. 당신이 태어난 날과 그 이유를 깨닫는 날이다。",
},
{
en: "In three words I can sum up everything I've learned about life: it goes on.",
zh: "关于人生,我所学到的一切可以总结为三个词:它在继续。",
zh_TW: "關於人生,我所學到的一切可以總結為三個詞:它在繼續。",
ja: "人生について学んだすべてを3語でまとめることができる。それは「それでも続く」ということだ。",
ko: "내가 인생에 대해 배운 모든 것을 세 단어로 요약할 수 있다: '삶은 계속된다'는 것이다。",
},
{
en: "Not all those who wander are lost.",
zh: "并非所有流浪者都迷失了方向。",
zh_TW: "並非所有流浪者都迷失了方向。",
ja: "さまよう者がすべて道に迷っているわけではない。",
ko: "방황하는 자가 다 길을 잃은 것은 아니다。",
},
{
en: "Life is simple, but we insist on making it complicated.",
zh: "生活本简单,但我们坚持要把它弄复杂。",
zh_TW: "生活本簡單,但我們堅持要把它弄複雜。",
ja: "人生はシンプルだ。だが我々はそれを複雑にしようと躍起になる。",
ko: "인생은 단순하지만, 우리가 복잡하게 만들기를 고집한다。",
},
{
en: "Our life is what our thoughts make it.",
zh: "我们的生活是由我们的思想造成的。",
zh_TW: "我們的生活是由我們的思想造成的。",
ja: "我々の人生は、我々の思考が作るものだ。",
ko: "우리의 삶은 우리의 생각이 만드는 것이다。",
},
{
en: "Find purpose, the means will follow.",
zh: "找到目标,方法自会随之而来。",
zh_TW: "找到目標,方法自會隨之而來。",
ja: "目的を見つけよ、手段は後からついてくる。",
ko: "목적을 찾으라, 수단은 따라올 것이다。",
},
{
en: "The goal of life is living in agreement with nature.",
zh: "生活的目标是与自然和谐相处。",
zh_TW: "生活的目標是與自然和諧相處。",
ja: "人生の目標は、自然と調和して生きることである。",
ko: "삶의 목표는 자연과 조화를 이루며 사는 것이다。",
},
{
en: "The only true wisdom is in knowing you know nothing.",
zh: "唯一的真正智慧在于知道自己一无所有。",
zh_TW: "唯一的真正智慧在於知道自己一無所有。",
ja: "唯一真の知恵は、自分が何も知らないことを知ることにある。",
ko: "유일한 참된 지혜는 자신이 아무것도 모른다는 것을 아는 것이다。",
},
{
en: "Knowledge is power.",
zh: "知识就是力量。",
zh_TW: "知識就是力量。",
ja: "知識は力なり。",
ko: "아는 것이 힘이다。",
},
{
en: "Knowing yourself is the beginning of all wisdom.",
zh: "了解自己是所有智慧的开端。",
zh_TW: "了解自己是所有智慧的開端。",
ja: "自分自身を知ることが、すべての知恵の始まりである。",
ko: "자신을 아는 것이 모든 지혜의 시작이다。",
},
{
en: "The journey of a thousand miles begins with a single step.",
zh: "千里之行,始于足下。",
zh_TW: "千里之行,始於足下。",
ja: "千里の道も一歩から。",
ko: "천 리 길도 한 걸음부터。",
},
{
en: "The only source of knowledge is experience.",
zh: "知识的唯一来源是经验。",
zh_TW: "知識的唯一來源是經驗。",
ja: "知識の唯一の源泉は経験である。",
ko: "지식의 유일한 원천은 경험이다。",
},
{
en: "A fool thinks himself to be wise, but a wise man knows himself to be a fool.",
zh: "愚者自以为聪明,智者自知愚蠢。",
zh_TW: "愚者自以為聰明,智者自知愚蠢。",
ja: "愚か者は自分を賢いと思うが、賢い者は自分が愚かであることを知っている。",
ko: "바보는 자신이 현명하다고 생각하지만, 현명한 사람은 자신이 바보라는 것을 안다。",
},
{
en: "We learn from failure, not from success!",
zh: "我们从失败中学习,而不是从成功中!",
zh_TW: "我們從失敗中學習,而不是從成功中!",
ja: "我々は成功からではなく、失敗から学ぶ!",
ko: "우리는 성공이 아닌, 실패로부터 배운다!",
},
{
en: "The wise man is one who knows what he does not know.",
zh: "智者,知其所不知。",
zh_TW: "智者,知其所不知。",
ja: "賢い者とは、自分が何を知らないかを知っている者である。",
ko: "현명한 사람은 자신이 모르는 것을 아는 사람이다。",
},
{
en: "To know that we know what we know, and that we do not know what we do not know, that is true knowledge.",
zh: "知之为知之,不知为不知,是知也。",
zh_TW: "知之為知之,不知為不知,是知也。",
ja: "知るを知るとなし、知らざるを知らずとなす、これ知るなり。",
ko: "아는 것을 안다고 하고, 모르는 것을 모른다고 하는 것, 그것이 참된 앎이다。",
},
{
en: "Curiosity is the wick in the candle of learning.",
zh: "好奇心是学习这支蜡烛的灯芯。",
zh_TW: "好奇心是學習這支蠟燭的燈芯。",
ja: "好奇心は、学習というロウソクの芯である。",
ko: "호기심은 배움이라는 촛불의 심지이다。",
},
{
en: "It is the mark of an educated mind to be able to entertain a thought without accepting it.",
zh: "能够容纳一种思想而不同意它,这是一个受过教育的头脑的标志。",
zh_TW: "能夠容納一種思想而不同意它,這是一個受過教育的頭腦的標誌。",
ja: "ある考えを受け入れずに、その考えを持ち続けることができるのが、教育ある精神の証である。",
ko: "어떤 생각을 받아들이지 않고도 그 생각을 해볼 수 있는 것이 교육받은 마음의 특징이다。",
},
{
en: "Never stop questioning.",
zh: "永远不要停止提问。",
zh_TW: "永遠不要停止提問。",
ja: "疑問を持つことを決してやめるな。",
ko: "질문하는 것을 절대 멈추지 마라。",
},
{
en: "The man who asks a question is a fool for a minute, the man who does not ask is a fool for life.",
zh: "问问题的人,只傻一分钟;不问的人,傻一生。",
zh_TW: "問問題的人,只傻一分鐘;不問的人,傻一生。",
ja: "問う者は一時の恥、問わぬ者は一生の恥。",
ko: "질문하는 사람은 1분 동안 바보가 되지만, 질문하지 않는 사람은 평생 바보가 된다。",
},
{
en: "Wisdom is not a product of schooling but of the lifelong attempt to acquire it.",
zh: "智慧不是学校教育的产物,而是终生努力获得的产物。",
zh_TW: "智慧不是學校教育的產物,而是終生努力獲得的產物。",
ja: "知恵とは学校教育の産物ではなく、生涯をかけて獲得しようと試みることで得られるものである。",
ko: "지혜는 학교 교육의 산물이 아니라, 평생에 걸쳐 그것을 얻으려는 노력의 산물이다。",
},
{
en: "The greatest enemy of knowledge is not ignorance, it is the illusion of knowledge.",
zh: "知识最大的敌人不是无知,而是自以为拥有知识的幻觉。",
zh_TW: "知識最大的敵人不是無知,而是自以為擁有知識的幻覺。",
ja: "知識の最大の敵は無知ではなく、知っているという幻想である。",
ko: "지식의 가장 큰 적은 무지가 아니라, 안다는 착각이다。",
},
{
en: "True wisdom comes to each of us when we realize how little we understand about life, ourselves, and the world around us.",
zh: "当我们认识到自己对生命、对自身、对周围世界了解得多么少时,真正的智慧才会降临到我们每个人身上。",
zh_TW:
"當我們認識到自己對生命、對自身、對周圍世界了解得多麼少時,真正的智慧才會降臨到我們每個人身上。",
ja: "真の知恵は、我々が人生や自分自身、そして我々を取り巻く世界について、いかにわずかしか理解していないかを悟ったときに訪れる。",
ko: "진정한 지혜는 우리가 삶과 우리 자신, 그리고 우리를 둘러싼 세계에 대해 얼마나 아는 것이 없는지를 깨달을 때 찾아온다。",
},
{
en: "Beware of false knowledge; it is more dangerous than ignorance.",
zh: "谨防虚假的知识;它比无知更危险。",
zh_TW: "謹防虛假的知識;它比無知更危險。",
ja: "偽りの知識に用心せよ。それは無知よりも危険である。",
ko: "거짓된 지식을 경계하라. 그것은 무지보다 더 위험하다。",
},
{
en: "What does not kill me makes me stronger.",
zh: "杀不死我的,使我更强大。",
zh_TW: "殺不死我的,使我更強大。",
ja: "私を殺さないものは、私をより強くする。",
ko: "나를 죽이지 못하는 것은 나를 더 강하게 만든다。",
},
{
en: "The only constant in life is change.",
zh: "生活中唯一不变的就是变化。",
zh_TW: "生活中唯一不變的就是變化。",
ja: "人生で唯一変わらないものは、変化そのものである。",
ko: "삶에서 유일하게 변하지 않는 것은 변화뿐이다。",
},
{
en: "If you are going through hell, keep going.",
zh: "如果你正在经历地狱,那就继续走下去。",
zh_TW: "如果你正在經歷地獄,那就繼續走下去。",
ja: "地獄を経験しているなら、進み続けろ。",
ko: "지옥을 겪고 있다면, 계속 나아가라。",
},
{
en: "In the middle of difficulty lies opportunity.",
zh: "机会蕴藏在困难之中。",
zh_TW: "機會蘊藏在困難之中。",
ja: "困難の真っ只中に、好機がある。",
ko: "어려움의 한가운데에 기회가 있다。",
},
{
en: "It is not the strongest of the species that survive, nor the most intelligent, but the one most responsive to change.",
zh: "存活下来的物种不是最强壮的,也不是最聪明的,而是最能适应变化的。",
zh_TW: "存活下來的物種不是最强壯的,也不是最聰明的,而是最能適應變化的。",
ja: "生き残る種とは、最も強いものでも、最も知的なものでもない。最も変化に対応できるものである。",
ko: "살아남는 종은 가장 강한 종도, 가장 지능이 높은 종도 아니다. 변화에 가장 잘 적응하는 종이다。",
},
{
en: "We must become the change we wish to see in the world.",
zh: "我们必须成为我们希望在世界上看到的改变。",
zh_TW: "我們必須成為我們希望在世界上看到的改變。",
ja: "世界に変化を望むなら、まず自らがその変化となれ。",
ko: "우리는 세상에서 보고 싶은 변화가 되어야 한다。",
},
{
en: "A smooth sea never made a skilled sailor.",
zh: "平静的大海练不出熟练的水手。",
zh_TW: "平靜的大海練不出熟練的水手。",
ja: "穏やかな海は、熟練した船乗りを育てない。",
ko: "순탄한 바다는 노련한 뱃사공을 만들지 못한다。",
},
{
en: "Obstacles don't block the path, they are the path.",
zh: "障碍不是挡住了路,障碍本身就是路。",
zh_TW: "障礙不是擋住了路,障礙本身就是路。",
ja: "障害は道を塞ぐものではなく、道そのものである。",
ko: "장애물은 길을 막는 것이 아니라, 그 자체가 길이다。",
},
{
en: "Fall seven times, stand up eight.",
zh: "七次跌倒,八次站起。",
zh_TW: "七次跌倒,八次站起。",
ja: "七転び八起き。",
ko: "일곱 번 넘어져도, 여덟 번 일어선다。",
},
{
en: "The art of life lies in a constant readjustment to our surroundings.",
zh: "生活的艺术在于不断地调整自己以适应环境。",
zh_TW: "生活的藝術在於不斷地調整自己以適應環境。",
ja: "人生(じんせい)の芸術(げいじゅつ)は、我々(われわれ)の環境(かんきょう)に対(たい)する絶(た)え間(ま)ない再調整(さいちょうせい)にある。",
ko: "삶의 기술은 우리를 둘러싼 환경에 끊임없이 재적응하는 데 있다。",
},
{
en: "Adversity introduces a man to himself.",
zh: "逆境使人认识自己。",
zh_TW: "逆境使人認識自己。",
ja: "逆境は、人に自分自身を教えてくれる。",
ko: "역경은 사람에게 자기 자신을 소개한다。",
},
{
en: "The wound is the place where the Light enters you.",
zh: "伤口是光进入你内心的入口。",
zh_TW: "傷口是光進入你內心的入口。",
ja: "傷口は、光があなたの中に入る場所だ。",
ko: "상처는 빛이 당신에게 들어오는 곳이다。",
},
{
en: "When we are no longer able to change a situation, we are challenged to change ourselves.",
zh: "当我们无法改变现状时,我们就需要改变自己。",
zh_TW: "當我們無法改變現狀時,我們就需要改變自己。",
ja: "状況を変えることができなくなったとき、我々は自分自身を変えることを求められる。",
ko: "상황을 더 이상 바꿀 수 없을 때, 우리는 자신을 바꿔야 하는 도전에 직면한다。",
},
{
en: "Be the change you wish to see in the world.",
zh: "成为你希望在世界上看到的改变。",
zh_TW: "成為你希望在世界上看到的改變。",
ja: "あなたが世界に見たいと願う変化に、あなた自身がなりなさい。",
ko: "세상에서 보고 싶은 변화가 있다면, 당신 자신이 그 변화가 되어라。",
},
{
en: "Do not pray for an easy life, pray for the strength to endure a difficult one.",
zh: "不要祈祷生活安逸,要祈祷有力量去忍受艰难的生活。",
zh_TW: "不要祈禱生活安逸,要祈禱有力量去忍受艱難的生活。",
ja: "楽な人生を祈るな。困難な人生を耐え抜く強さを祈れ。",
ko: "편안한 삶을 기도하지 말고, 어려운 삶을 견뎌낼 힘을 기도하라。",
},
{
en: "A pessimist sees the difficulty in every opportunity; an optimist sees the opportunity in every difficulty.",
zh: "悲观者在每个机会中都看到困难;乐观者在每个困难中都看到机会。",
zh_TW: "悲觀者在每個機會中都看到困難;樂觀者在每個困難中都看到機會。",
ja: "悲観主義者はあらゆる好機の中に困難を見る。楽観主義者はあらゆる困難の中に好機を見る。",
ko: "비관론자는 모든 기회에서 어려움을 보고, 낙관론자는 모든 어려움에서 기회를 본다。",
},
{
en: "It's not what happens to you, but how you react to it that matters.",
zh: "重要的不是发生在你身上的事,而是你如何应对它。",
zh_TW: "重要的不是發生在你身上的事,而是你如何應對它。",
ja: "あなたに何が起こるかではなく、それにどう反応するかが重要だ。",
ko: "당신에게 무슨 일이 일어났는지가 중요한 것이 아니라, 당신이 그것에 어떻게 반응하는지가 중요하다。",
},
{
en: "To love oneself is the beginning of a lifelong romance.",
zh: "爱自己是终身浪漫的开始。",
zh_TW: "愛自己是終身浪漫的開始。",
ja: "自分自身を愛することは、一生続くロマンスの始まりだ。",
ko: "자신을 사랑하는 것은 평생 지속되는 로맨스의 시작이다。",
},
{
en: "Love is composed of a single soul inhabiting two bodies.",
zh: "爱是栖息于两个身体中的同一个灵魂。",
zh_TW: "愛是棲息於兩個身體中的同一個靈魂。",
ja: "愛とは、二つの体に宿る一つの魂で構成されている。",
ko: "사랑은 두 개의 몸에 깃든 하나의 영혼으로 이루어져 있다。",
},
{
en: "Man is the measure of all things.",
zh: "人是万物的尺度。",
zh_TW: "人是萬物的尺度。",
ja: "人間は万物の尺度である。",
ko: "인간은 만물의 척도이다。",
},
{
en: "The best and most beautiful things in this world cannot be seen or even heard, but must be felt with the heart.",
zh: "世界上最好最美的东西是看不见也听不见的,必须用心去感受。",
zh_TW: "世界上最好最美的東西是看不見也聽不見的,必須用心去感受。",
ja: "この世で最も素晴らしく、最も美しいものは、目で見たり聞いたりすることはできない。心で感じなければならない。",
ko: "이 세상에서 가장 좋고 가장 아름다운 것들은 보이거나 들리지 않는다. 오직 마음으로만 느껴야 한다。",
},
{
en: "Where there is love there is life.",
zh: "有爱的地方就有生命。",
zh_TW: "有愛的地方就有生命。",
ja: "愛があるところに人生がある。",
ko: "사랑이 있는 곳에 삶이 있다。",
},
{
en: "If you want to be loved, be lovable.",
zh: "如果你想被爱,就要变得可爱。",
zh_TW: "如果你想被愛,就要變得可愛。",
ja: "愛されたいなら、愛らしくあれ。",
ko: "사랑받고 싶다면, 사랑스러워져라。",
},
{
en: "We are all in the gutter, but some of us are looking at the stars.",
zh: "我们都身处沟渠,但仍有人仰望星空。",
zh_TW: "我們都身處溝渠,但仍有人仰望星空。",
ja: "我々はみな溝の中にいる。だが、そこから星を見上げている者もいるのだ。",
ko: "우리는 모두 시궁창에 있지만, 우리 중 일부는 별을 바라보고 있다。",
},
{
en: "The only thing we have to fear is fear itself.",
zh: "我们唯一需要恐惧的就是恐惧本身。",
zh_TW: "我們唯一需要恐懼的就是恐懼本身。",
ja: "我々が恐れるべき唯一のものは、恐れそのものである。",
ko: "우리가 두려워해야 할 유일한 것은 두려움 그 자체이다。",
},
{
en: "Be kind, for everyone you meet is fighting a hard battle.",
zh: "要友善,因为你遇到的每个人都在打一场艰苦的战斗。",
zh_TW: "要友善,因為你遇到的每個人都在打一場艱苦的戰鬥。",
ja: "親切にしなさい。あなたが出会う誰もが、困難な戦いを戦っているのだから。",
ko: "친절하라. 당신이 만나는 모든 사람은 힘겨운 싸움을 하고 있기 때문이다。",
},
{
en: "Man is born free, and everywhere he is in chains.",
zh: "人生而自由,却无往不在枷锁之中。",
zh_TW: "人生而自由,卻無往不在枷鎖之中。",
ja: "人は生まれながらにして自由だが、いたるところで鎖につながれている。",
ko: "인간은 자유롭게 태어났으나, 어디에서나 쇠사슬에 묶여 있다。",
},
{
en: "We love the things we love for what they are.",
zh: "我们爱我们所爱之物,只因它们本来的样子。",
zh_TW: "我們愛我們所愛之物,只因它們本來的樣子。",
ja: "我々が愛するものを愛するのは、それがそれであるからだ。",
ko: "우리는 우리가 사랑하는 것들을 그 자체로 사랑한다。",
},
{
en: "Darkness cannot drive out darkness; only light can do that. Hate cannot drive out hate; only love can do that.",
zh: "黑暗无法驱逐黑暗,只有光明可以;仇恨无法驱逐仇恨,只有爱可以。",
zh_TW: "黑暗無法驅逐黑暗,只有光明可以;仇恨無法驅逐仇恨,只有愛可以。",
ja: "闇は闇を追い払うことはできない。光だけがそれを可能にする。憎しみは憎しみを追い払うことはできない。愛だけがそれを可能にする。",
ko: "어둠은 어둠을 몰아낼 수 없다. 오직 빛만이 할 수 있다. 증오는 증오를 몰아낼 수 없다. 오직 사랑만이 할 수 있다。",
},
{
en: "An eye for an eye only ends up making the whole world blind.",
zh: "以眼还眼,只会让整个世界都盲目。",
zh_TW: "以眼還眼,只會讓整個世界都盲目。",
ja: "「目には目を」は、全世界を盲目にするだけだ。",
ko: "'눈에는 눈'은 결국 온 세상을 눈멀게 할 뿐이다。",
},
{
en: "Hell is other people.",
zh: "他人即地狱。",
zh_TW: "他人即地獄。",
ja: "地獄とは、他人である。",
ko: "타인은 지옥이다。",
},
{
en: "You will not be punished for your anger, you will be punished by your anger.",
zh: "你不会因为你的愤怒而受到惩罚,你会被你的愤怒所惩罚。",
zh_TW: "你不會因為你的憤怒而受到懲罰,你會被你的憤怒所懲罰。",
ja: "あなたは怒りのために罰せられるのではない。怒りによって罰せられるのだ。",
ko: "당신은 당신의 분노 때문에 벌을 받는 것이 아니라, 당신의 분노에 의해 벌을 받을 것이다。",
},
{
en: "To err is human, to forgive divine.",
zh: "犯错是人性,宽恕是神性。",
zh_TW: "犯錯是人性,寬恕是神性。",
ja: "過つは人の常、許すは神の業。",
ko: "실수하는 것은 인간이고, 용서하는 것은 신이다。",
},
{
en: "Man is the only creature who refuses to be what he is.",
zh: "人是唯一拒绝承认自己本质的生物。",
zh_TW: "人是唯一拒絕承認自己本質的生物。",
ja: "人間は、自分が何者であるかを拒否する唯一の生き物である。",
ko: "인간은 자신이 무엇인지를 거부하는 유일한 생물이다。",
},
{
en: "Beauty is in the eye of the beholder.",
zh: "情人眼里出西施。",
zh_TW: "情人眼裡出西施。",
ja: "美は見る人の目の中にある。",
ko: "아름다움은 보는 사람의 눈에 달려 있다。",
},
{
en: "All that we see or seem is but a dream within a dream.",
zh: "我们所见所感,皆如梦中之梦。",
zh_TW: "我們所見所感,皆如夢中之夢。",
ja: "我々が見たり感じたりするすべては、夢の中の夢にすぎない。",
ko: "우리가 보거나 보이는 모든 것은 꿈속의 꿈일 뿐이다。",
},
{
en: "Everything you can imagine is real.",
zh: "你能想象的一切都是真实的。",
zh_TW: "你能想像的一切都是真實的。",
ja: "想像できることは、すべて現実なのだ。",
ko: "당신이 상상할 수 있는 모든 것은 현실이다。",
},
{
en: "The map is not the territory.",
zh: "地图并非领土。",
zh_TW: "地圖並非領土。",
ja: "地図は領土ではない。",
ko: "지도는 영토가 아니다。",
},
{
en: "We don't see things as they are, we see them as we are.",
zh: "我们看到的不是事物的原貌,而是我们自己的样子。",
zh_TW: "我們看到的不是事物的原貌,而是我們自己的樣子。",
ja: "我々は物事をあるがままに見ているのではない。我々があるがままに見ているのだ。",
ko: "우리는 사물을 있는 그대로 보지 않고, 우리 자신(의 모습)대로 본다。",
},
{
en: "There are two ways to be fooled. One is to believe what isn't true; the other is to refuse to believe what is true.",
zh: "被愚弄有两种方式。一种是相信不真实的东西;另一种是拒绝相信真实的东西。",
zh_TW:
"被愚弄有兩種方式。一種是相信不真實的東西;另一種是拒絕相信真實的東西。",
ja: "騙される方法は二つある。一つは真実でないことを信じること。もう一つは真実であることを信じようとしないことだ。",
ko: "속는 방법에는 두 가지가 있다. 하나는 사실이 아닌 것을 믿는 것이고, 다른 하나는 사실인 것을 믿기를 거부하는 것이다。",
},
{
en: "Simplicity is the ultimate sophistication.",
zh: "简约是极致的复杂。",
zh_TW: "簡約是極致的複雜。",
ja: "シンプルさは、究極の洗練である。",
ko: "단순함은 궁극의 정교함이다。",
},
{
en: "The truth will set you free.",
zh: "真相将使你自由。",
zh_TW: "真相將使你自由。",
ja: "真実は、あなたを自由にする。",
ko: "진리가 너희를 자유롭게 하리라。",
},
{
en: "Reality is merely an illusion, albeit a very persistent one.",
zh: "现实只是一种幻觉,尽管是一种非常持久的幻觉。",
zh_TW: "現實只是一種幻覺,儘管是一種非常持久的幻覺。",
ja: "現実とは、非常に根強いただの幻想にすぎない。",
ko: "현실은 단지 환상일 뿐이다. 비록 매우 집요한 환상이긴 하지만。",
},
{
en: "What is rational is actual and what is actual is rational.",
zh: "凡是合乎理性的东西都是现实的,凡是现实的东西都是合乎理性的。",
zh_TW: "凡是合乎理性的東西都是現實的,凡是現實的東西都是合乎理性的。",
ja: "理性的なものは現実的であり、現実的なものは理性的である。",
ko: "이성적인 것은 현실적이고, 현실적인 것은 이성적이다。",
},
{
en: "Truth is like the sun. You can shut it out for a time, but it ain't goin' away.",
zh: "真相就像太阳。你可以暂时将它遮住,但它不会消失。",
zh_TW: "真相就像太陽。你可以暫時將它遮住,但它不會消失。",
ja: "真実は太陽のようなものだ。一時的に隠すことはできても、決してなくなりはしない。",
ko: "진실은 태양과 같다. 잠시 가릴 수는 있지만, 사라지게 할 수는 없다。",
},
{
en: "Everything we hear is an opinion, not a fact. Everything we see is a perspective, not the truth.",
zh: "我们听到的一切都只是观点,而非事实。我们看到的一切都只是视角,而非真相。",
zh_TW:
"我們聽到的一切都只是觀點,而非事實。我們看到的一切都只是視角,而非真相。",
ja: "我々が聞くことすべてが意見であり、事実ではない。我々が見ることすべてが視点であり、真実ではない。",
ko: "우리가 듣는 모든 것은 의견이지, 사실이 아니다. 우리가 보는 모든 것은 관점이지, 진실이 아니다。",
},
{
en: "There is no truth. There is only perception.",
zh: "没有真相,只有认知。",
zh_TW: "沒有真相,只有認知。",
ja: "真実などない。ただ認識があるだけだ。",
ko: "진실은 없다. 오직 인식만이 있을 뿐이다。",
},
{
en: "If you look deep enough into anything, you will find mathematics.",
zh: "如果你对任何事物看得足够深入,你都会发现数学。",
zh_TW: "如果你對任何事物看得足夠深入,你都會發現數學。",
ja: "何事も深く見つめれば、そこには数学がある。",
ko: "무엇이든 충분히 깊이 들여다보면, 수학을 발견하게 될 것이다。",
},
{
en: "The medium is the message.",
zh: "媒介即信息。",
zh_TW: "媒介即訊息。",
ja: "メディアはメッセージである。",
ko: "미디어는 메시지다。",
},
{
en: "Nothing is true, everything is permitted.",
zh: "没有什么是真实的,一切都被允许。",
zh_TW: "沒有什麼是真實的,一切都被允許。",
ja: "真実などない、すべては許されている。",
ko: "진실은 없으며, 모든 것이 허용된다。",
},
{
en: "We are what we believe we are.",
zh: "我们相信自己是什么,我们就是什么。",
zh_TW: "我們相信自己是什麼,我們就是什麼。",
ja: "我々は、我々が信じる通りの人間である。",
ko: "우리는 우리가 그렇다고 믿는 존재이다。",
},
{
en: "Yesterday is history, tomorrow is a mystery, but today is a gift. That is why it is called the present.",
zh: "昨天是历史,明天是谜团,但今天是礼物。这就是为什么它被称为‘现在’(Present)。",
zh_TW:
"昨天是歷史,明天是謎團,但今天是禮物。這就是為什麼它被稱為‘現在’(Present)。",
ja: "昨日は歴史、明日はミステリー、しかし今日は贈り物だ。だからこそ、それは『プレゼント (現在)』と呼ばれる。",
ko: "어제는 역사이고, 내일은 미스터리이며, 오늘은 선물이다. 그래서 오늘을 '선물(present)'이라고 부른다。",
},
{
en: "Time is money.",
zh: "时间就是金钱。",
zh_TW: "時間就是金錢。",
ja: "時は金なり。",
ko: "시간은 돈이다。",
},
{
en: "The only thing necessary for the triumph of evil is for good men to do nothing.",
zh: "邪恶得逞的唯一条件是好人袖手旁观。",
zh_TW: "邪惡得逞的唯一條件是好人袖手旁觀。",
ja: "悪が勝利するために必要なのは、善人が何もしないことだけである。",
ko: "악의 승리를 위해 필요한 유일한 것은 선한 사람들이 아무것도 하지 않는 것이다。",
},
{
en: "Carpe diem.",
zh: "活在当下。",
zh_TW: "活在當下。",
ja: "今を生きよ(カルペ・ディエム)。",
ko: "현재를 즐겨라 (카르페 디엠)。",
},
{
en: "Do not dwell in the past, do not dream of the future, concentrate the mind on the present moment.",
zh: "不要沉湎于过去,不要幻想未来,集中精神活在当下。",
zh_TW: "不要沉湎於過去,不要幻想未來,集中精神活在當下。",
ja: "過去に生きるな、未来を夢見るな、現在の瞬間に心を集中させよ。",
ko: "과거에 머물지 말고, 미래를 꿈꾸지 말며, 현재 이 순간에 마음을 집중하라。",
},
{
en: "The best time to plant a tree was 20 years ago. The second best time is now.",
zh: "种树的最佳时机是20年前。其次是现在。",
zh_TW: "種樹的最佳時機是20年前。其次是現在。",
ja: "木を植えるのに最適な時期は20年前だった。二番目に最適な時期は、今だ。",
ko: "나무를 심기에 가장 좋은 때는 20년 전이었다. 두 번째로 좋은 때는 바로 지금이다。",
},
{
en: "Action speaks louder than words.",
zh: "事实胜于雄辩。",
zh_TW: "事實勝於雄辯。",
ja: "行動は言葉よりも雄弁である。",
ko: "말보다 행동이 더 중요하다。",
},
{
en: "Honesty is the first chapter in the book of wisdom.",
zh: "诚实是智慧之书的第一章。",
zh_TW: "誠實是智慧之書的第一章。",
ja: "誠実さは、知恵という本の第一章である。",
ko: "정직은 지혜라는 책의 첫 장이다。",
},
{
en: "Two things are infinite: the universe and human stupidity; and I'm not sure about the universe.",
zh: "有两样东西是无限的:宇宙和人类的愚蠢;而且我不太确定宇宙是否无限。",
zh_TW: "有兩樣東西是無限的:宇宙和人類的愚蠢;而且我不太確定宇宙是否無限。",
ja: "無限なものは二つある。宇宙と人間の愚かさだ。ただ、宇宙については私にもよく分からない。",
ko: "무한한 것은 두 가지뿐이다. 우주와 인간의 어리석음. 그런데 우주에 대해선 나도 확신이 없다。",
},
{
en: "You cannot step twice into the same river.",
zh: "人不能两次踏进同一条河流。",
zh_TW: "人不能兩次踏進同一條河流。",
ja: "同(おな)じ川(かわ)に二度(にど)入(はい)ることはできない。",
ko: "같은 강물에 두 번 발을 담글 수 없다。",
},
{
en: "The future belongs to those who believe in the beauty of their dreams.",
zh: "未来属于那些相信梦想之美的人。",
zh_TW: "未來屬於那些相信夢想之美的人。",
ja: "未来は、自分の夢の美しさを信じる者のものである。",
ko: "미래는 자신의 꿈의 아름다움을 믿는 사람들의 것이다。",
},
{
en: "Procrastination is the thief of time.",
zh: "拖延是时间的大敌。",
zh_TW: "拖延是時間的大敵。",
ja: "先延ばしは時間泥棒である。",
ko: "미루는 습관은 시간 도둑이다。",
},
{
en: "An investment in knowledge pays the best interest.",
zh: "投资知识,收益最佳。",
zh_TW: "投資知識,收益最佳。",
ja: "知識への投資は、最良の利息を生む。",
ko: "지식에 대한 투자는 최고의 이자를 지불한다。",
},
{
en: "I have not failed. I've just found 10,000 ways that won't work.",
zh: "我没有失败。我只是找到了一万种行不通的方法。",
zh_TW: "我沒有失敗。我只是找到了一萬種行不通的方法。",
ja: "私は失敗したことがない。ただ、うまくいかない1万通りの方法を見つけただけだ。",
ko: "나는 실패하지 않았다. 단지 작동하지 않는 1만 가지 방법을 찾았을 뿐이다。",
},
{
en: "That which is done, is done.",
zh: "木已成舟。",
zh_TW: "木已成舟。",
ja: "なされたことは、なされたことだ。(覆水盆に返らず)",
ko: "일어난 일은 일어난 일이다. (이미 엎질러진 물이다.)",
},
];
export function getRandomQuote() {
const randomIndex = Math.floor(Math.random() * quotes.length);
return quotes[randomIndex];
}

View File

@@ -1,321 +1,185 @@
import { FIXER_BR, FIXER_BN, FIXER_BR_DIV, FIXER_BN_DIV } from "../libs/webfix"; import { OPT_TRANS_MICROSOFT } from "./api";
import { OPT_STYLE_NONE } from "./styles";
export const GLOBAL_KEY = "*"; export const GLOBAL_KEY = "*";
export const REMAIN_KEY = "-"; export const REMAIN_KEY = "-";
export const SHADOW_KEY = ">>>"; export const SHADOW_KEY = ">>>";
export const DEFAULT_SELECTOR = `:is(li, p, h1, h2, h3, h4, h5, h6, dd, blockquote, .kiss-p)`; export const DEFAULT_COLOR = "#209CEE"; // 默认高亮背景色/线条颜色
export const DEFAULT_KEEP_SELECTOR = `code, img, svg, pre`;
export const DEFAULT_TRANS_TAG = "font";
export const DEFAULT_SELECT_STYLE =
"-webkit-line-clamp: unset; max-height: none; height: auto;";
export const OPT_TIMING_PAGESCROLL = "mk_pagescroll"; // 滚动加载翻译
export const OPT_TIMING_PAGEOPEN = "mk_pageopen"; // 直接翻译到底
export const OPT_TIMING_MOUSEOVER = "mk_mouseover";
export const OPT_TIMING_CONTROL = "mk_ctrlKey";
export const OPT_TIMING_SHIFT = "mk_shiftKey";
export const OPT_TIMING_ALT = "mk_altKey";
export const OPT_TIMING_ALL = [
OPT_TIMING_PAGESCROLL,
OPT_TIMING_PAGEOPEN,
OPT_TIMING_MOUSEOVER,
OPT_TIMING_CONTROL,
OPT_TIMING_SHIFT,
OPT_TIMING_ALT,
];
export const OPT_SPLIT_PARAGRAPH_DISABLE = "split_disable";
export const OPT_SPLIT_PARAGRAPH_TEXTLENGTH = "split_textlength";
export const OPT_SPLIT_PARAGRAPH_PUNCTUATION = "split_punctuation";
export const OPT_SPLIT_PARAGRAPH_ALL = [
OPT_SPLIT_PARAGRAPH_DISABLE,
OPT_SPLIT_PARAGRAPH_PUNCTUATION,
OPT_SPLIT_PARAGRAPH_TEXTLENGTH,
];
export const OPT_HIGHLIGHT_WORDS_DISABLE = "highlight_disable";
export const OPT_HIGHLIGHT_WORDS_BEFORETRANS = "highlight_beforetrans";
export const OPT_HIGHLIGHT_WORDS_AFTERTRANS = "highlight_aftertrans";
export const OPT_HIGHLIGHT_WORDS_ALL = [
OPT_HIGHLIGHT_WORDS_DISABLE,
OPT_HIGHLIGHT_WORDS_BEFORETRANS,
OPT_HIGHLIGHT_WORDS_AFTERTRANS,
];
export const DEFAULT_SELECTOR =
"h1, h2, h3, h4, h5, h6, li, p, dd, blockquote, figcaption, label, legend";
export const DEFAULT_IGNORE_SELECTOR = "button, footer, pre, mark, nav";
export const DEFAULT_KEEP_SELECTOR = `code, cite, math, .math, a:has(code)`;
export const DEFAULT_RULE = { export const DEFAULT_RULE = {
pattern: "", // 匹配网址 pattern: "", // 匹配网址
selector: "", // 选择器 selector: "", // 选择器
keepSelector: "", // 保留元素选择器 keepSelector: "", // 保留元素选择器
terms: "", // 专业术语 terms: "", // 专业术语
translator: GLOBAL_KEY, // 翻译服务 aiTerms: "", // AI专业术语
apiSlug: GLOBAL_KEY, // 翻译服务
fromLang: GLOBAL_KEY, // 源语言 fromLang: GLOBAL_KEY, // 源语言
toLang: GLOBAL_KEY, // 目标语言 toLang: GLOBAL_KEY, // 目标语言
textStyle: GLOBAL_KEY, // 译文样式 textStyle: GLOBAL_KEY, // 译文样式
transOpen: GLOBAL_KEY, // 开启翻译 transOpen: GLOBAL_KEY, // 开启翻译
bgColor: "", // 译文颜色 // bgColor: "", // 译文颜色 (作废)
textDiyStyle: "", // 自定义译文样式 // textDiyStyle: "", // 自定义译文样式 (作废)
textExtStyle: "", // 译文附加样式
termsStyle: "", // 专业术语样式
highlightStyle: "", // 高亮词汇样式
selectStyle: "", // 选择器节点样式 selectStyle: "", // 选择器节点样式
parentStyle: "", // 选择器父节点样式 parentStyle: "", // 选择器父节点样式
grandStyle: "", // 选择器父节点样式
injectJs: "", // 注入JS injectJs: "", // 注入JS
injectCss: "", // 注入CSS // injectCss: "", // 注入CSS (作废)
transOnly: GLOBAL_KEY, // 是否仅显示译文 transOnly: GLOBAL_KEY, // 是否仅显示译文
transTiming: GLOBAL_KEY, // 翻译时机/鼠标悬停翻译 // transTiming: GLOBAL_KEY, // 翻译时机/鼠标悬停翻译 (暂时作废)
transTag: GLOBAL_KEY, // 译文元素标签 transTag: GLOBAL_KEY, // 译文元素标签
transTitle: GLOBAL_KEY, // 是否同时翻译页面标题 transTitle: GLOBAL_KEY, // 是否同时翻译页面标题
detectRemote: GLOBAL_KEY, // 是否使用远程语言检测 // transSelected: GLOBAL_KEY, // 是否启用划词翻译 (移回setting)
skipLangs: [], // 不翻译的语言 // detectRemote: GLOBAL_KEY, // 是否使用远程语言检测 (移回setting)
fixerSelector: "", // 修复函数选择器 // skipLangs: [], // 不翻译的语言 (移回setting)
fixerFunc: GLOBAL_KEY, // 修复函数 // fixerSelector: "", // 修复函数选择器 (暂时作废)
// fixerFunc: GLOBAL_KEY, // 修复函数 (暂时作废)
transStartHook: "", // 钩子函数 transStartHook: "", // 钩子函数
transEndHook: "", // 钩子函数 transEndHook: "", // 钩子函数
transRemoveHook: "", // 钩子函数 // transRemoveHook: "", // 钩子函数 (暂时作废)
autoScan: GLOBAL_KEY, // 是否自动识别文本节点
hasRichText: GLOBAL_KEY, // 是否启用富文本翻译
hasShadowroot: GLOBAL_KEY, // 是否包含shadowroot
rootsSelector: "", // 翻译范围选择器
ignoreSelector: "", // 不翻译的选择器
splitParagraph: GLOBAL_KEY, // 切分段落
splitLength: 0, // 切分段落长度
highlightWords: GLOBAL_KEY, // 高亮词汇
}; };
const DEFAULT_DIY_STYLE = `color: #666; // 全局规则
background: linear-gradient( export const GLOBLA_RULE = {
45deg, pattern: "*", // 匹配网址
LightGreen 20%, selector: DEFAULT_SELECTOR, // 选择器
LightPink 20% 40%, keepSelector: DEFAULT_KEEP_SELECTOR, // 保留元素选择器
LightSalmon 40% 60%, terms: "", // 专业术语
LightSeaGreen 60% 80%, aiTerms: "", // AI专业术语
LightSkyBlue 80% apiSlug: OPT_TRANS_MICROSOFT, // 翻译服务
); fromLang: "auto", // 源语言
&:hover { toLang: "zh-CN", // 目标语言
color: #333; textStyle: OPT_STYLE_NONE, // 译文样式
};`; transOpen: "false", // 开启翻译
// bgColor: DEFAULT_COLOR, // 译文颜色 (作废)
export const DEFAULT_OW_RULE = { // textDiyStyle: DEFAULT_DIY_STYLE, // 自定义译文样式 (作废)
translator: REMAIN_KEY, textExtStyle: "", // 译文附加样式
fromLang: REMAIN_KEY, termsStyle: "font-weight: bold;", // 专业术语样式
toLang: REMAIN_KEY, highlightStyle: "color: red;", // 高亮词汇样式
textStyle: REMAIN_KEY, selectStyle: DEFAULT_SELECT_STYLE, // 选择器节点样式
transOpen: REMAIN_KEY, parentStyle: "", // 选择器父节点样式
bgColor: "", grandStyle: "", // 选择器祖节点样式
textDiyStyle: DEFAULT_DIY_STYLE, injectJs: "", // 注入JS
injectCss: "", // 注入CSS
transOnly: "false", // 是否仅显示译文
// transTiming: OPT_TIMING_PAGESCROLL, // 翻译时机/鼠标悬停翻译 (暂时作废)
transTag: DEFAULT_TRANS_TAG, // 译文元素标签
transTitle: "false", // 是否同时翻译页面标题
// transSelected: "true", // 是否启用划词翻译 (移回setting)
// detectRemote: "true", // 是否使用远程语言检测 (移回setting)
// skipLangs: [], // 不翻译的语言 (移回setting)
// fixerSelector: "", // 修复函数选择器 (暂时作废)
// fixerFunc: "-", // 修复函数 (暂时作废)
transStartHook: "", // 钩子函数
transEndHook: "", // 钩子函数
// transRemoveHook: "", // 钩子函数 (暂时作废)
autoScan: "true", // 是否自动识别文本节点
hasRichText: "true", // 是否启用富文本翻译
hasShadowroot: "false", // 是否包含shadowroot
rootsSelector: "body", // 翻译范围选择器
ignoreSelector: DEFAULT_IGNORE_SELECTOR, // 不翻译的选择器
splitParagraph: OPT_SPLIT_PARAGRAPH_DISABLE, // 切分段落
splitLength: 100, // 切分段落长度
highlightWords: OPT_HIGHLIGHT_WORDS_DISABLE, // 高亮词汇
}; };
export const DEFAULT_RULES = [GLOBLA_RULE];
// todo: 校验几个内置规则
const RULES_MAP = { const RULES_MAP = {
"www.google.com/search": { // "www.google.com/search": {
selector: `h3, .IsZvec, .VwiC3b`, // rootsSelector: `#rcnt`,
}, // },
"news.google.com": {
selector: `[data-n-tid], ${DEFAULT_SELECTOR}`,
},
"www.foxnews.com": {
selector: `h1, h2, .title, .sidebar [data-type="Title"], .article-content ${DEFAULT_SELECTOR}; [data-spotim-module="conversation"]>div >>> [data-spot-im-class="message-text"] p, [data-spot-im-class="message-text"]`,
},
"bearblog.dev, www.theverge.com, www.tampermonkey.net/documentation.php": {
selector: `${DEFAULT_SELECTOR}`,
},
"themessenger.com": {
selector: `.leading-tight, .leading-tighter, .my-2 p, .font-body p, article ${DEFAULT_SELECTOR}`,
},
"www.telegraph.co.uk, go.dev/doc/": {
selector: `article ${DEFAULT_SELECTOR}`,
},
"www.theguardian.com": {
selector: `.show-underline, .dcr-hup5wm div, .dcr-7vl6y8 div, .dcr-12evv1c, figcaption, article ${DEFAULT_SELECTOR}, [data-cy="mostviewed-footer"] h4`,
},
"www.semafor.com": {
selector: `${DEFAULT_SELECTOR}, .styles_intro__IYj__, [class*="styles_description"]`,
},
"www.noemamag.com": {
selector: `.splash__title, .single-card__title, .single-card__type, .single-card__topic, .highlighted-content__title, .single-card__author, article ${DEFAULT_SELECTOR}, .quote__text, .wp-caption-text div`,
},
"restofworld.org": {
selector: `${DEFAULT_SELECTOR}, .recirc-story__headline, .recirc-story__dek`,
},
"www.axios.com": {
selector: `.h7, ${DEFAULT_SELECTOR}`,
},
"www.newyorker.com": {
selector: `.summary-item__hed, .summary-item__dek, .summary-collection-grid__dek, .dqtvfu, .rubric__link, .caption, article ${DEFAULT_SELECTOR}, .HEhan ${DEFAULT_SELECTOR}, .ContributorBioBio-fBolsO, .BaseText-ewhhUZ`,
},
"time.com": {
selector: `h1, h3, .summary, .video-title, #article-body ${DEFAULT_SELECTOR}, .image-wrap-container .credit.body-caption, .media-heading`,
},
"www.dw.com": {
selector: `.ts-teaser-title a, .news-title a, .title a, .teaser-description a, .hbudab h3, .hbudab p, figcaption ,article ${DEFAULT_SELECTOR}`,
},
"www.bbc.com": {
selector: `h1, h2, .media__link, .media__summary, article ${DEFAULT_SELECTOR}, .ssrcss-y7krbn-Stack, .ssrcss-17zglt8-PromoHeadline, .ssrcss-18cjaf3-Headline, .gs-c-promo-heading__title, .gs-c-promo-summary, .media__content h3, .article__intro, .lx-c-summary-points>li`,
},
"www.chinadaily.com.cn": {
selector: `h1, .tMain [shape="rect"], .cMain [shape="rect"], .photo_art [shape="rect"], .mai_r [shape="rect"], .lisBox li, #Content ${DEFAULT_SELECTOR}`,
},
"www.facebook.com": {
selector: `[role="main"] [dir="auto"]`,
},
"www.reddit.com, new.reddit.com, sh.reddit.com": {
selector: `:is(#AppRouter-main-content, #overlayScrollContainer) :is([class^=tbIA],[class^=_1zP],[class^=ULWj],[class^=_2Jj], [class^=_334],[class^=_2Gr],[class^=_7T4],[class^=_1WO], ${DEFAULT_SELECTOR}); [id^="post-title"], :is([slot="text-body"], [slot="comment"]) ${DEFAULT_SELECTOR}, recent-posts h3, aside :is(span:has(>h2), p); shreddit-subreddit-header >>> :is(#title, #description)`,
},
"www.quora.com": {
selector: `.qu-wordBreak--break-word`,
},
"edition.cnn.com": {
selector: `.container__title, .container__headline, .headline__text, .image__caption, [data-type="Title"], .article__content ${DEFAULT_SELECTOR}`,
},
"www.reuters.com": {
selector: `#main-content [data-testid="Heading"], #main-content [data-testid="Body"], .article-body__content__17Yit ${DEFAULT_SELECTOR}`,
},
"www.bloomberg.com": {
selector: `[data-component="headline"], [data-component="related-item-headline"], [data-component="title"], article ${DEFAULT_SELECTOR}`,
},
"deno.land, docs.github.com": {
selector: `main ${DEFAULT_SELECTOR}`,
keepSelector: DEFAULT_KEEP_SELECTOR,
},
"doc.rust-lang.org": {
selector: `.content ${DEFAULT_SELECTOR}`,
keepSelector: DEFAULT_KEEP_SELECTOR,
},
"www.indiehackers.com": {
selector: `h1, h3, .content ${DEFAULT_SELECTOR}, .feed-item__title-link`,
},
"platform.openai.com/docs": {
selector: `.docs-body ${DEFAULT_SELECTOR}`,
keepSelector: DEFAULT_KEEP_SELECTOR,
},
"en.wikipedia.org": { "en.wikipedia.org": {
selector: `h1, .mw-parser-output ${DEFAULT_SELECTOR}`, ignoreSelector: `.button, code, footer, form, mark, pre, .mwe-math-element, .mw-editsection`,
keepSelector: `.mwe-math-element`,
}, },
"stackoverflow.com, serverfault.com, superuser.com, stackexchange.com, askubuntu.com, stackapps.com, mathoverflow.net":
{
selector: `.s-prose ${DEFAULT_SELECTOR}, .comment-copy, .question-hyperlink, .s-post-summary--content-title, .s-post-summary--content-excerpt`,
keepSelector: `${DEFAULT_KEEP_SELECTOR}, .math-container`,
},
"www.npmjs.com/package, developer.chrome.com/docs, medium.com, react.dev, create-react-app.dev, pytorch.org":
{
selector: `article ${DEFAULT_SELECTOR}`,
},
"news.ycombinator.com": { "news.ycombinator.com": {
selector: `.title, p`, selector: `p, .titleline, .commtext, .hn-item-title, .hn-comment-text, .hn-story-title`,
fixerSelector: `.toptext, .commtext`, keepSelector: `code, img, svg, pre, .sitebit`,
fixerFunc: FIXER_BR, ignoreSelector: `button, code, footer, form, header, mark, nav, pre, .reply`,
autoScan: `false`,
}, },
"github.com": { "twitter.com, https://x.com": {
selector: `.markdown-body ${DEFAULT_SELECTOR}, .repo-description p, .Layout-sidebar .f4, .container-lg .py-4 .f5, .container-lg .my-4 .f5, .Box-row .pr-4, .Box-row article .mt-1, [itemprop="description"], .markdown-title, bdi, .ws-pre-wrap, .status-meta, span.status-meta, .col-10.color-fg-muted, .TimelineItem-body, .pinned-item-list-item-content .color-fg-muted, .markdown-body td, .markdown-body th`, selector: `[data-testid='tweetText'], [data-testid='twitter-article-title'], .public-DraftStyleDefault-block`,
keepSelector: DEFAULT_KEEP_SELECTOR, keepSelector: `img, svg, a, span:has(a), div:has(a)`,
ignoreSelector: `button, [data-testid='videoPlayer'], [role='group']`,
autoScan: `false`,
}, },
"twitter.com": { "www.youtube.com/live_chat": {
selector: `[data-testid="tweetText"], [data-testid="birdwatch-pivot"]>div.css-1rynq56`, rootsSelector: `div#items`,
keepSelector: `img, a, .r-18u37iz, .css-175oi2r`, selector: `span.yt-live-chat-text-message-renderer`,
}, autoScan: `false`,
"m.youtube.com": {
selector: `.slim-video-information-title .yt-core-attributed-string, .media-item-headline .yt-core-attributed-string, .comment-text .yt-core-attributed-string, .typography-body-2b .yt-core-attributed-string, #ytp-caption-window-container .ytp-caption-segment`,
selectStyle: `-webkit-line-clamp: unset; max-height: none; height: auto;`,
parentStyle: `-webkit-line-clamp: unset; max-height: none; height: auto;`,
keepSelector: `img, #content-text>a`,
}, },
"www.youtube.com": { "www.youtube.com": {
selector: `h1, #video-title, #content-text, #title, yt-attributed-string>span>span, #ytp-caption-window-container .ytp-caption-segment`, rootsSelector: `ytd-page-manager`,
ignoreSelector: `aside, button, footer, form, header, pre, mark, nav, #player, #container, .caption-window, .ytp-settings-menu`,
selectStyle: `-webkit-line-clamp: unset; max-height: none; height: auto;`, selectStyle: `-webkit-line-clamp: unset; max-height: none; height: auto;`,
parentStyle: `-webkit-line-clamp: unset; max-height: none; height: auto;`, parentStyle: `-webkit-line-clamp: unset; max-height: none; height: auto;`,
keepSelector: `img, #content-text>a`, grandStyle: `-webkit-line-clamp: unset; max-height: none; height: auto;`,
}, },
"bard.google.com": { "web.telegram.org": {
selector: `.query-content ${DEFAULT_SELECTOR}, message-content ${DEFAULT_SELECTOR}`, autoScan: `false`,
}, selector: ".text-content, .embedded-text-wrapper",
"www.bing.com, copilot.microsoft.com": { rootsSelector: ".Transition",
selector: `.b_algoSlug, .rwrl_padref; .cib-serp-main >>> .ac-textBlock ${DEFAULT_SELECTOR}, .text-message-content div`,
},
"www.phoronix.com": {
selector: `article ${DEFAULT_SELECTOR}`,
fixerSelector: `.content`,
fixerFunc: FIXER_BR,
},
"wx2.qq.com": {
selector: `.js_message_plain`,
},
"app.slack.com/client/": {
selector: `.p-rich_text_section, .c-message_attachment__text, .p-rich_text_list li`,
},
"discord.com/channels/": {
selector: `div[class^=message], div[class^=headerText], div[class^=name_], section[aria-label='Search Results'] div[id^=message-content], div[id^=message]`,
keepSelector: `li[class^='card'] div[class^='message'], [class^='embedFieldValue'], [data-list-item-id^='forum-channel-list'] div[class^='headerText']`,
},
"t.me/s/": {
selector: `.js-message_text ${DEFAULT_SELECTOR}`,
fixerSelector: `.tgme_widget_message_text`,
fixerFunc: FIXER_BR,
},
"web.telegram.org/k": {
selector: `div.kiss-p`,
keepSelector: `div[class^=time], .peer-title, .document-wrapper, .message.spoilers-container custom-emoji-element, reactions-element`,
fixerSelector: `.message`,
fixerFunc: FIXER_BN_DIV,
},
"web.telegram.org/a": {
selector: `.text-content > .kiss-p`,
keepSelector: `.Reactions, .time, .peer-title, .document-wrapper, .message.spoilers-container custom-emoji-element`,
fixerSelector: `.text-content`,
fixerFunc: FIXER_BR_DIV,
},
"www.instagram.com/": {
selector: `h1, article span[dir=auto] > span[dir=auto], ._ab1y`,
},
"www.instagram.com/p/,www.instagram.com/reels/": {
selector: `h1, div[class='x9f619 xjbqb8w x78zum5 x168nmei x13lgxp2 x5pf9jr xo71vjh x1uhb9sk x1plvlek xryxfnj x1c4vz4f x2lah0s xdt5ytf xqjyukv x1cy8zhl x1oa3qoh x1nhvcw1'] > span[class='x1lliihq x1plvlek xryxfnj x1n2onr6 x193iq5w xeuugli x1fj9vlw x13faqbe x1vvkbs x1s928wv xhkezso x1gmr53x x1cpjm7i x1fgarty x1943h6x x1i0vuye xvs91rp xo1l8bm x5n08af x10wh9bi x1wdrske x8viiok x18hxmgj'], span[class='x193iq5w xeuugli x1fj9vlw x13faqbe x1vvkbs xt0psk2 x1i0vuye xvs91rp xo1l8bm x5n08af x10wh9bi x1wdrske x8viiok x18hxmgj']`,
},
"mail.google.com": {
selector: `.a3s.aiL ${DEFAULT_SELECTOR}, span[data-thread-id]`,
fixerSelector: `.a3s.aiL`,
fixerFunc: FIXER_BR,
},
"web.whatsapp.com": {
selector: `.copyable-text > span`,
},
"chat.openai.com": {
selector: `div[data-message-author-role] > div ${DEFAULT_SELECTOR}`,
fixerSelector: `div[data-message-author-role='user'] > div`,
fixerFunc: FIXER_BN,
},
"forum.ru-board.com": {
selector: `.tit, .dats, .kiss-p, .lgf ${DEFAULT_SELECTOR}`,
fixerSelector: `span.post`,
fixerFunc: FIXER_BR,
},
"education.github.com": {
selector: `${DEFAULT_SELECTOR}, a, summary, span.Button-content`,
},
"blogs.windows.com": {
selector: `${DEFAULT_SELECTOR}, .c-uhf-nav-link, figcaption`,
fixerSelector: `.t-content>div>ul>li`,
fixerFunc: FIXER_BR,
},
"developer.apple.com/documentation/": {
selector: `#main ${DEFAULT_SELECTOR}, #main .abstract .content, #main .abstract.content, #main .link span`,
keepSelector: DEFAULT_KEEP_SELECTOR,
},
"greasyfork.org": {
selector: `h2, .script-link, .script-description, #additional-info ${DEFAULT_SELECTOR}`,
},
"www.fmkorea.com": {
selector: `#container ${DEFAULT_SELECTOR}`,
},
"forum.arduino.cc": {
selector: `.top-row>.title, .featured-topic>.title, .link-top-line>.title, .category-description, .topic-excerpt, .fancy-title, .cooked ${DEFAULT_SELECTOR}`,
},
"docs.arduino.cc": {
selector: `[class^="tutorial-module--left"] ${DEFAULT_SELECTOR}`,
},
"www.historydefined.net": {
selector: `.wp-element-caption, ${DEFAULT_SELECTOR}`,
},
"gobyexample.com": {
selector: `.docs p`,
keepSelector: `code`,
},
"go.dev/tour": {
selector: `#left-side ${DEFAULT_SELECTOR}`,
keepSelector: `code, img, svg >>> code`,
},
"pkg.go.dev": {
selector: `.Documentation-content ${DEFAULT_SELECTOR}`,
keepSelector: `${DEFAULT_KEEP_SELECTOR}, a, span`,
},
"docs.rs": {
selector: `.docblock ${DEFAULT_SELECTOR}, .docblock-short`,
keepSelector: `code >>> code`,
},
"randomnerdtutorials.com": {
selector: `article ${DEFAULT_SELECTOR}`,
},
"notebooks.githubusercontent.com/view/ipynb": {
selector: `#notebook-container ${DEFAULT_SELECTOR}`,
keepSelector: DEFAULT_KEEP_SELECTOR,
},
"developers.cloudflare.com": {
selector: `article ${DEFAULT_SELECTOR}, .WorkerStarter--description`,
keepSelector: `a[rel='noopener'], code`,
},
"ubuntuforums.org": {
fixerSelector: `.postcontent`,
fixerFunc: FIXER_BR,
},
"play.google.com/store/apps/details": {
fixerSelector: `[data-g-id="description"]`,
fixerFunc: FIXER_BR,
},
"news.yahoo.co.jp/articles/": {
fixerSelector: `.sc-cTsKDU`,
fixerFunc: FIXER_BN,
},
"chromereleases.googleblog.com": {
fixerSelector: `.post-content, .post-content > span, li > span`,
fixerFunc: FIXER_BR,
}, },
}; };
export const BUILTIN_RULES = Object.entries(RULES_MAP) export const BUILTIN_RULES = Object.entries(RULES_MAP).map(
.sort((a, b) => a[0].localeCompare(b[0])) ([pattern, rule]) => ({
.map(([pattern, rule]) => ({ // ...DEFAULT_RULE,
...DEFAULT_RULE,
...rule, ...rule,
pattern, pattern,
})); })
);

190
src/config/setting.js Normal file
View File

@@ -0,0 +1,190 @@
import { LogLevel } from "../libs/log";
import {
OPT_DICT_BING,
OPT_SUG_YOUDAO,
DEFAULT_HTTP_TIMEOUT,
OPT_TRANS_MICROSOFT,
DEFAULT_API_LIST,
} from "./api";
import { DEFAULT_CUSTOM_STYLES } from "./styles";
// 默认快捷键
export const OPT_SHORTCUT_TRANSLATE = "toggleTranslate";
export const OPT_SHORTCUT_STYLE = "toggleStyle";
export const OPT_SHORTCUT_POPUP = "togglePopup";
export const OPT_SHORTCUT_SETTING = "openSetting";
export const DEFAULT_SHORTCUTS = {
[OPT_SHORTCUT_TRANSLATE]: ["AltLeft", "KeyQ"],
[OPT_SHORTCUT_STYLE]: ["AltLeft", "KeyC"],
[OPT_SHORTCUT_POPUP]: ["AltLeft", "KeyK"],
[OPT_SHORTCUT_SETTING]: ["AltLeft", "KeyO"],
};
export const TRANS_MIN_LENGTH = 2; // 最短翻译长度
export const TRANS_MAX_LENGTH = 100000; // 最长翻译长度
export const TRANS_NEWLINE_LENGTH = 20; // 换行字符数
export const DEFAULT_BLACKLIST = [
"https://fishjar.github.io/kiss-translator/options.html",
"https://translate.google.com",
"https://www.deepl.com/translator",
]; // 禁用翻译名单
export const DEFAULT_CSPLIST = []; // 禁用CSP名单
export const DEFAULT_ORILIST = ["https://dict.youdao.com"]; // 移除Origin名单
// 同步设置
export const OPT_SYNCTYPE_WORKER = "KISS-Worker";
export const OPT_SYNCTYPE_WEBDAV = "WebDAV";
export const OPT_SYNCTOKEN_PERFIX = "kt_";
export const OPT_SYNCTYPE_ALL = [OPT_SYNCTYPE_WORKER, OPT_SYNCTYPE_WEBDAV];
export const DEFAULT_SYNC = {
syncType: OPT_SYNCTYPE_WORKER, // 同步方式
syncUrl: "", // 数据同步接口
syncUser: "", // 数据同步用户名
syncKey: "", // 数据同步密钥
syncMeta: {}, // 数据更新及同步信息
subRulesSyncAt: 0, // 订阅规则同步时间
dataCaches: {}, // 缓存同步时间
};
// 输入框翻译
export const OPT_INPUT_TRANS_SIGNS = ["/", "//", "\\", "\\\\", ">", ">>"];
export const DEFAULT_INPUT_SHORTCUT = ["AltLeft", "KeyI"];
export const DEFAULT_INPUT_RULE = {
transOpen: true,
apiSlug: OPT_TRANS_MICROSOFT,
fromLang: "auto",
toLang: "en",
triggerShortcut: DEFAULT_INPUT_SHORTCUT,
triggerCount: 1,
triggerTime: 200,
transSign: OPT_INPUT_TRANS_SIGNS[0],
};
// 划词翻译
export const PHONIC_MAP = {
en_phonic: ["英", "uk"],
us_phonic: ["美", "en"],
};
export const OPT_TRANBOX_TRIGGER_CLICK = "click";
export const OPT_TRANBOX_TRIGGER_HOVER = "hover";
export const OPT_TRANBOX_TRIGGER_SELECT = "select";
export const OPT_TRANBOX_TRIGGER_ALL = [
OPT_TRANBOX_TRIGGER_CLICK,
OPT_TRANBOX_TRIGGER_HOVER,
OPT_TRANBOX_TRIGGER_SELECT,
];
export const DEFAULT_TRANBOX_SHORTCUT = ["AltLeft", "KeyS"];
export const DEFAULT_TRANBOX_SETTING = {
transOpen: true, // 是否启用划词翻译
apiSlugs: [OPT_TRANS_MICROSOFT],
fromLang: "auto",
toLang: "zh-CN",
toLang2: "en",
tranboxShortcut: DEFAULT_TRANBOX_SHORTCUT,
btnOffsetX: 10,
btnOffsetY: 10,
boxOffsetX: 0,
boxOffsetY: 10,
hideTranBtn: false, // 是否隐藏翻译按钮
hideClickAway: false, // 是否点击外部关闭弹窗
simpleStyle: false, // 是否简洁界面
followSelection: false, // 翻译框是否跟随选中文本
autoHeight: false, // 自适应高度
triggerMode: OPT_TRANBOX_TRIGGER_CLICK, // 触发翻译方式
// extStyles: "", // 附加样式
enDict: OPT_DICT_BING, // 英文词典
enSug: OPT_SUG_YOUDAO, // 英文建议
};
const SUBTITLE_WINDOW_STYLE = `padding: 0.5em 1em;
background-color: rgba(0, 0, 0, 0.5);
color: white;
line-height: 1.3;
text-shadow: 1px 1px 2px black;
display: inline-block`;
const SUBTITLE_ORIGIN_STYLE = `font-size: clamp(1rem, 2cqw, 3rem);`;
const SUBTITLE_TRANSLATION_STYLE = `font-size: clamp(1rem, 2cqw, 3rem);`;
export const DEFAULT_SUBTITLE_SETTING = {
enabled: true, // 是否开启
apiSlug: OPT_TRANS_MICROSOFT,
segSlug: "-", // AI智能断句
chunkLength: 1000, // AI处理切割长度
preTrans: 90, // 提前翻译时长
throttleTrans: 30, // 节流翻译间隔
// fromLang: "en",
toLang: "zh-CN",
isBilingual: true, // 是否双语显示
skipAd: false, // 是否快进广告
windowStyle: SUBTITLE_WINDOW_STYLE, // 背景样式
originStyle: SUBTITLE_ORIGIN_STYLE, // 原文样式
translationStyle: SUBTITLE_TRANSLATION_STYLE, // 译文样式
};
// 订阅列表
export const DEFAULT_SUBRULES_LIST = [
{
url: process.env.REACT_APP_RULESURL,
selected: true,
},
{
url: process.env.REACT_APP_RULESURL_ON,
selected: false,
},
{
url: process.env.REACT_APP_RULESURL_OFF,
selected: false,
},
];
export const DEFAULT_MOUSEHOVER_KEY = ["ControlLeft"];
export const DEFAULT_MOUSE_HOVER_SETTING = {
useMouseHover: false, // 是否启用鼠标悬停翻译
mouseHoverKey: DEFAULT_MOUSEHOVER_KEY, // 鼠标悬停翻译组合键
};
export const DEFAULT_SETTING = {
darkMode: "auto", // 深色模式
uiLang: "en", // 界面语言
// fetchLimit: DEFAULT_FETCH_LIMIT, // 最大任务数量(移至rule作废)
// fetchInterval: DEFAULT_FETCH_INTERVAL, // 任务间隔时间(移至rule作废)
minLength: TRANS_MIN_LENGTH,
maxLength: TRANS_MAX_LENGTH,
newlineLength: TRANS_NEWLINE_LENGTH,
httpTimeout: DEFAULT_HTTP_TIMEOUT,
clearCache: false, // 是否在浏览器下次启动时清除缓存
injectRules: true, // 是否注入订阅规则
fabClickAction: 0, // 悬浮按钮点击行为
// injectWebfix: true, // 是否注入修复补丁(作废)
// detectRemote: false, // 是否使用远程语言检测 从rule移回
// contextMenus: true, // 是否添加右键菜单(作废)
contextMenuType: 1, // 右键菜单类型(0不显示1简单菜单2多级菜单)
// transTag: DEFAULT_TRANS_TAG, // 译文元素标签(移至rule作废)
// transOnly: false, // 是否仅显示译文(移至rule作废)
// transTitle: false, // 是否同时翻译页面标题(移至rule作废)
subrulesList: DEFAULT_SUBRULES_LIST, // 订阅列表
// owSubrule: DEFAULT_OW_RULE, // 覆写订阅规则 (作废)
transApis: DEFAULT_API_LIST, // 翻译接口 (v2.0 对象改为数组)
// mouseKey: OPT_TIMING_PAGESCROLL, // 翻译时机/鼠标悬停翻译(移至rule作废)
shortcuts: DEFAULT_SHORTCUTS, // 快捷键
inputRule: DEFAULT_INPUT_RULE, // 输入框设置
tranboxSetting: DEFAULT_TRANBOX_SETTING, // 划词翻译设置
// touchTranslate: 2, // 触屏翻译 {5:单指双击6:单指三击7:双指双击} (作废)
touchModes: [2], // 触屏翻译 {5:单指双击6:单指三击7:双指双击} (多选)
blacklist: DEFAULT_BLACKLIST.join(",\n"), // 禁用翻译名单
csplist: DEFAULT_CSPLIST.join(",\n"), // 禁用CSP名单
orilist: DEFAULT_ORILIST.join(",\n"), // 禁用CSP名单
// disableLangs: [], // 不翻译的语言(移至rule作废)
skipLangs: [], // 不翻译的语言从rule移回
transInterval: 100, // 翻译等待时间
langDetector: "-", // 远程语言识别服务
mouseHoverSetting: DEFAULT_MOUSE_HOVER_SETTING, // 鼠标悬停翻译
preInit: true, // 是否预加载脚本
transAllnow: false, // 是否立即全部翻译
subtitleSetting: DEFAULT_SUBTITLE_SETTING, // 字幕设置
logLevel: LogLevel.INFO.value, // 日志级别
rootMargin: 500, // 提前触发翻译
customStyles: DEFAULT_CUSTOM_STYLES, // 自定义样式列表
};

23
src/config/storage.js Normal file
View File

@@ -0,0 +1,23 @@
import { APP_NAME, APP_VERSION } from "./app";
export const KV_RULES_KEY = `kiss-rules_v${APP_VERSION[0]}.json`;
export const KV_WORDS_KEY = "kiss-words.json";
export const KV_RULES_SHARE_KEY = `kiss-rules-share_v${APP_VERSION[0]}.json`;
export const KV_SETTING_KEY = `kiss-setting_v${APP_VERSION[0]}.json`;
export const KV_SALT_SYNC = "KISS-Translator-SYNC";
export const KV_SALT_SHARE = "KISS-Translator-SHARE";
export const STOKEY_MSAUTH = `${APP_NAME}_msauth`;
export const STOKEY_BDAUTH = `${APP_NAME}_bdauth`;
export const STOKEY_SETTING_OLD = `${APP_NAME}_setting`;
export const STOKEY_RULES_OLD = `${APP_NAME}_rules`;
export const STOKEY_SETTING = `${APP_NAME}_setting_v${APP_VERSION[0]}`;
export const STOKEY_RULES = `${APP_NAME}_rules_v${APP_VERSION[0]}`;
export const STOKEY_WORDS = `${APP_NAME}_words`;
export const STOKEY_SYNC = `${APP_NAME}_sync`;
export const STOKEY_FAB = `${APP_NAME}_fab`;
export const STOKEY_TRANBOX = `${APP_NAME}_tranbox`;
export const STOKEY_RULESCACHE_PREFIX = `${APP_NAME}_rulescache_`;
export const CACHE_NAME = `${APP_NAME}_cache`;
export const DEFAULT_CACHE_TIMEOUT = 3600 * 24 * 7; // 缓存超时时间(7天)

46
src/config/styles.js Normal file
View File

@@ -0,0 +1,46 @@
export const OPT_STYLE_NONE = "style_none"; // 无
export const OPT_STYLE_LINE = "under_line"; // 下划线
export const OPT_STYLE_DOTLINE = "dot_line"; // 点状线
export const OPT_STYLE_DASHLINE = "dash_line"; // 虚线
export const OPT_STYLE_DASHLINE_BOLD = "dash_line_bold"; // 虚线加粗
export const OPT_STYLE_DASHBOX = "dash_box"; // 虚线框
export const OPT_STYLE_DASHBOX_BOLD = "dash_box_bold"; // 虚线框加粗
export const OPT_STYLE_WAVYLINE = "wavy_line"; // 波浪线
export const OPT_STYLE_WAVYLINE_BOLD = "wavy_line_bold"; // 波浪线加粗
export const OPT_STYLE_MARKER = "marker"; // 马克笔
export const OPT_STYLE_GRADIENT_MARKER = "gradient_marker"; // 渐变马克笔
export const OPT_STYLE_FUZZY = "fuzzy"; // 模糊
export const OPT_STYLE_HIGHLIGHT = "highlight"; // 高亮
export const OPT_STYLE_BLOCKQUOTE = "blockquote"; // 引用
export const OPT_STYLE_GRADIENT = "gradient"; // 渐变
export const OPT_STYLE_BLINK = "blink"; // 闪现
export const OPT_STYLE_GLOW = "glow"; // 发光
export const OPT_STYLE_COLORFUL = "colorful"; // 多彩
export const OPT_STYLE_ALL = [
OPT_STYLE_NONE,
OPT_STYLE_LINE,
OPT_STYLE_DOTLINE,
OPT_STYLE_DASHLINE,
OPT_STYLE_DASHLINE_BOLD,
OPT_STYLE_WAVYLINE,
OPT_STYLE_WAVYLINE_BOLD,
OPT_STYLE_DASHBOX,
OPT_STYLE_DASHBOX_BOLD,
OPT_STYLE_MARKER,
OPT_STYLE_GRADIENT_MARKER,
OPT_STYLE_FUZZY,
OPT_STYLE_HIGHLIGHT,
OPT_STYLE_BLOCKQUOTE,
OPT_STYLE_GRADIENT,
OPT_STYLE_BLINK,
OPT_STYLE_GLOW,
OPT_STYLE_COLORFUL,
];
export const DEFAULT_CUSTOM_STYLES = [
{
styleSlug: "custom",
styleName: "Custom Style",
styleCode: `color: #209CEE;`,
},
];

14
src/config/url.js Normal file
View File

@@ -0,0 +1,14 @@
import { APP_LCNAME } from "./app";
export const URL_CACHE_TRAN = `https://${APP_LCNAME}/translate`;
export const URL_CACHE_SUBTITLE = `https://${APP_LCNAME}/subtitle`;
export const URL_CACHE_DELANG = `https://${APP_LCNAME}/detectlang`;
export const URL_CACHE_BINGDICT = `https://${APP_LCNAME}/bingdict`;
export const URL_KISS_WORKER = "https://github.com/fishjar/kiss-worker";
export const URL_KISS_PROXY = "https://github.com/fishjar/kiss-proxy";
export const URL_KISS_RULES = "https://github.com/fishjar/kiss-rules";
export const URL_KISS_RULES_NEW_ISSUE =
"https://github.com/fishjar/kiss-rules/issues/new";
export const URL_RAW_PREFIX =
"https://raw.githubusercontent.com/fishjar/kiss-translator/master";

View File

@@ -1,3 +1,5 @@
import { run } from "./common"; import { run } from "./common";
globalThis.__KISS_CONTEXT__ = "content";
run(); run();

View File

@@ -1,4 +1,11 @@
import { createContext, useContext, useState, forwardRef } from "react"; import {
createContext,
useContext,
useState,
forwardRef,
useCallback,
useMemo,
} from "react";
import Snackbar from "@mui/material/Snackbar"; import Snackbar from "@mui/material/Snackbar";
import MuiAlert from "@mui/material/Alert"; import MuiAlert from "@mui/material/Alert";
@@ -18,36 +25,45 @@ export function AlertProvider({ children }) {
const horizontal = "center"; const horizontal = "center";
const [open, setOpen] = useState(false); const [open, setOpen] = useState(false);
const [severity, setSeverity] = useState("info"); const [severity, setSeverity] = useState("info");
const [message, setMessage] = useState(""); const [message, setMessage] = useState(null);
const showAlert = (msg, type) => { const showAlert = useCallback((msg, type) => {
setOpen(true); setOpen(true);
setMessage(msg); setMessage(msg);
setSeverity(type); setSeverity(type);
}; }, []);
const handleClose = (_, reason) => { const handleClose = useCallback((_, reason) => {
if (reason === "clickaway") { if (reason === "clickaway") {
return; return;
} }
setOpen(false); setOpen(false);
}; }, []);
const error = (msg) => showAlert(msg, "error"); const value = useMemo(
const warning = (msg) => showAlert(msg, "warning"); () => ({
const info = (msg) => showAlert(msg, "info"); error: (msg) => showAlert(msg, "error"),
const success = (msg) => showAlert(msg, "success"); warning: (msg) => showAlert(msg, "warning"),
info: (msg) => showAlert(msg, "info"),
success: (msg) => showAlert(msg, "success"),
}),
[showAlert]
);
return ( return (
<AlertContext.Provider value={{ error, warning, info, success }}> <AlertContext.Provider value={value}>
{children} {children}
<Snackbar <Snackbar
open={open} open={open}
autoHideDuration={3000} autoHideDuration={10000}
onClose={handleClose} onClose={handleClose}
anchorOrigin={{ vertical, horizontal }} anchorOrigin={{ vertical, horizontal }}
> >
<Alert onClose={handleClose} severity={severity} sx={{ width: "100%" }}> <Alert
onClose={handleClose}
severity={severity}
sx={{ minWidth: "300px", maxWidth: "80%" }}
>
{message} {message}
</Alert> </Alert>
</Snackbar> </Snackbar>

View File

@@ -1,34 +1,136 @@
import { useCallback } from "react"; import { useCallback, useEffect, useMemo } from "react";
import { DEFAULT_TRANS_APIS } from "../config"; import { DEFAULT_API_LIST, API_SPE_TYPES } from "../config";
import { useSetting } from "./Setting"; import { useSetting } from "./Setting";
export function useApi(translator) { function useApiState() {
const { setting, updateSetting } = useSetting(); const { setting, updateSetting } = useSetting();
const transApis = setting?.transApis || DEFAULT_TRANS_APIS; const transApis = setting?.transApis || [];
const updateApi = useCallback( return { transApis, updateSetting };
async (obj) => { }
const api = {
...DEFAULT_TRANS_APIS[translator], export function useApiList() {
...(transApis[translator] || {}), const { transApis, updateSetting } = useApiState();
};
Object.assign(transApis, { [translator]: { ...api, ...obj } }); useEffect(() => {
await updateSetting({ transApis }); const curSlugs = new Set(transApis.map((api) => api.apiSlug));
}, const missApis = DEFAULT_API_LIST.filter(
[translator, transApis, updateSetting] (api) => !curSlugs.has(api.apiSlug)
);
if (missApis.length > 0) {
updateSetting((prev) => ({
...prev,
transApis: [...(prev?.transApis || []), ...missApis],
}));
}
}, [transApis, updateSetting]);
const userApis = useMemo(
() =>
transApis
.filter((api) => !API_SPE_TYPES.builtin.has(api.apiSlug))
.sort((a, b) => a.apiSlug.localeCompare(b.apiSlug)),
[transApis]
); );
const resetApi = useCallback(async () => { const builtinApis = useMemo(
Object.assign(transApis, { [translator]: DEFAULT_TRANS_APIS[translator] }); () => transApis.filter((api) => API_SPE_TYPES.builtin.has(api.apiSlug)),
await updateSetting({ transApis }); [transApis]
}, [translator, transApis, updateSetting]); );
const enabledApis = useMemo(
() => transApis.filter((api) => !api.isDisabled),
[transApis]
);
const aiEnabledApis = useMemo(
() => enabledApis.filter((api) => API_SPE_TYPES.ai.has(api.apiType)),
[enabledApis]
);
const addApi = useCallback(
(apiType) => {
const defaultApiOpt =
DEFAULT_API_LIST.find((da) => da.apiType === apiType) || {};
const uuid = crypto.randomUUID();
const apiSlug = `${apiType}_${crypto.randomUUID()}`;
const apiName = `${apiType}_${uuid.slice(0, 8)}`;
const newApi = {
...defaultApiOpt,
apiSlug,
apiName,
apiType,
};
updateSetting((prev) => ({
...prev,
transApis: [...(prev?.transApis || []), newApi],
}));
},
[updateSetting]
);
const deleteApi = useCallback(
(apiSlug) => {
updateSetting((prev) => ({
...prev,
transApis: (prev?.transApis || []).filter(
(api) => api.apiSlug !== apiSlug
),
}));
},
[updateSetting]
);
return { return {
api: { transApis,
...DEFAULT_TRANS_APIS[translator], userApis,
...(transApis[translator] || {}), builtinApis,
}, enabledApis,
updateApi, aiEnabledApis,
resetApi, addApi,
deleteApi,
}; };
} }
export function useApiItem(apiSlug) {
const { transApis, updateSetting } = useApiState();
const api = useMemo(
() => transApis.find((a) => a.apiSlug === apiSlug),
[transApis, apiSlug]
);
const update = useCallback(
(updateData) => {
updateSetting((prev) => ({
...prev,
transApis: (prev?.transApis || []).map((item) =>
item.apiSlug === apiSlug ? { ...item, ...updateData, apiSlug } : item
),
}));
},
[apiSlug, updateSetting]
);
const reset = useCallback(() => {
updateSetting((prev) => ({
...prev,
transApis: (prev?.transApis || []).map((item) => {
if (item.apiSlug === apiSlug) {
const defaultApiOpt =
DEFAULT_API_LIST.find((da) => da.apiType === item.apiType) || {};
return {
...defaultApiOpt,
apiSlug: item.apiSlug,
apiName: item.apiName,
apiType: item.apiType,
key: item.key,
};
}
return item;
}),
}));
}, [apiSlug, updateSetting]);
return { api, update, reset };
}

View File

@@ -1,6 +1,6 @@
import { useCallback, useEffect, useRef, useState } from "react"; import { useCallback, useEffect, useRef, useState } from "react";
import { apiBaiduTTS } from "../apis"; import { logger } from "../libs/log";
import { kissLog } from "../libs/log"; import { fetchData } from "../libs/fetch";
/** /**
* 声音播放hook * 声音播放hook
@@ -12,50 +12,97 @@ export function useAudio(src) {
const [error, setError] = useState(null); const [error, setError] = useState(null);
const [ready, setReady] = useState(false); const [ready, setReady] = useState(false);
const [playing, setPlaying] = useState(false); const [playing, setPlaying] = useState(false);
const [loading, setLoading] = useState(false);
const onPlay = useCallback(() => { const onPlay = useCallback(async () => {
audioRef.current?.play(); if (!audioRef.current) return;
try {
await audioRef.current.play();
} catch (err) {
logger.info("Playback failed:", err);
setPlaying(false);
}
}, []);
const onPause = useCallback(() => {
audioRef.current?.pause();
}, []); }, []);
useEffect(() => { useEffect(() => {
if (!src) { if (!src) return;
return;
} let ignore = false;
const audio = new Audio(src); let objectUrl = null;
audio.addEventListener("error", (err) => setError(err));
audio.addEventListener("canplaythrough", () => setReady(true)); setReady(false);
audio.addEventListener("play", () => setPlaying(true)); setError(null);
audio.addEventListener("ended", () => setPlaying(false)); setPlaying(false);
setLoading(true);
const audio = new Audio();
audioRef.current = audio; audioRef.current = audio;
const handleCanPlay = () => setReady(true);
const handlePlay = () => setPlaying(true);
const handlePause = () => setPlaying(false);
const handleEnded = () => setPlaying(false);
const handleError = (e) => {
if (!ignore) {
setError(audio.error || e);
setReady(false);
setLoading(false);
}
};
audio.addEventListener("canplaythrough", handleCanPlay);
audio.addEventListener("play", handlePlay);
audio.addEventListener("pause", handlePause);
audio.addEventListener("ended", handleEnded);
audio.addEventListener("error", handleError);
const loadAudio = async () => {
try {
const data = await fetchData(src, {}, { expect: "audio" });
if (ignore) return;
audio.src = data;
setLoading(false);
} catch (err) {
if (!ignore) {
logger.info("Audio fetch failed:", err);
setError(err);
setLoading(false);
}
}
};
loadAudio();
return () => {
ignore = true;
audio.pause();
audio.removeAttribute("src");
if (objectUrl) {
URL.revokeObjectURL(objectUrl);
}
audio.removeEventListener("canplaythrough", handleCanPlay);
audio.removeEventListener("play", handlePlay);
audio.removeEventListener("pause", handlePause);
audio.removeEventListener("ended", handleEnded);
audio.removeEventListener("error", handleError);
};
}, [src]); }, [src]);
return { return {
loading,
error, error,
ready, ready,
playing, playing,
onPlay, onPlay,
onPause,
}; };
} }
/**
* 获取语音hook
* @param {*} text
* @param {*} lan
* @param {*} spd
* @returns
*/
export function useTextAudio(text, lan = "uk", spd = 3) {
const [src, setSrc] = useState("");
useEffect(() => {
(async () => {
try {
setSrc(await apiBaiduTTS(text, lan, spd));
} catch (err) {
kissLog(err, "baidu tts");
}
})();
}, [text, lan, spd]);
return useAudio(src);
}

View File

@@ -11,8 +11,13 @@ export function useDarkMode() {
updateSetting, updateSetting,
} = useSetting(); } = useSetting();
const toggleDarkMode = useCallback(async () => { const toggleDarkMode = useCallback(() => {
await updateSetting({ darkMode: !darkMode }); const nextMode = {
light: "dark",
dark: "auto",
auto: "light",
};
updateSetting({ darkMode: nextMode[darkMode] || "light" });
}, [darkMode, updateSetting]); }, [darkMode, updateSetting]);
return { darkMode, toggleDarkMode }; return { darkMode, toggleDarkMode };

97
src/hooks/Confirm.js Normal file
View File

@@ -0,0 +1,97 @@
import {
useState,
useContext,
createContext,
useCallback,
useRef,
useMemo,
} from "react";
import Dialog from "@mui/material/Dialog";
import DialogActions from "@mui/material/DialogActions";
import DialogContent from "@mui/material/DialogContent";
import DialogContentText from "@mui/material/DialogContentText";
import DialogTitle from "@mui/material/DialogTitle";
import Button from "@mui/material/Button";
import { useI18n } from "./I18n";
const ConfirmContext = createContext(null);
export function ConfirmProvider({ children }) {
const [dialogConfig, setDialogConfig] = useState(null);
const resolveRef = useRef(null);
const i18n = useI18n();
const translatedDefaults = useMemo(
() => ({
title: i18n("confirm_title", "Confirm"),
message: i18n("confirm_message", "Are you sure you want to proceed?"),
confirmText: i18n("confirm_action", "Confirm"),
cancelText: i18n("cancel_action", "Cancel"),
}),
[i18n]
);
const confirm = useCallback(
(config) => {
return new Promise((resolve) => {
setDialogConfig({ ...translatedDefaults, ...config });
resolveRef.current = resolve;
});
},
[translatedDefaults]
);
const handleClose = () => {
if (resolveRef.current) {
resolveRef.current(false);
}
setDialogConfig(null);
};
const handleConfirm = () => {
if (resolveRef.current) {
resolveRef.current(true);
}
setDialogConfig(null);
};
return (
<ConfirmContext.Provider value={confirm}>
{children}
<Dialog
open={!!dialogConfig}
onClose={handleClose}
aria-labelledby="confirm-dialog-title"
aria-describedby="confirm-dialog-description"
>
{dialogConfig && (
<>
<DialogTitle id="confirm-dialog-title">
{dialogConfig.title}
</DialogTitle>
<DialogContent>
<DialogContentText id="confirm-dialog-description">
{dialogConfig.message}
</DialogContentText>
</DialogContent>
<DialogActions>
<Button onClick={handleClose}>{dialogConfig.cancelText}</Button>
<Button onClick={handleConfirm} color="primary" autoFocus>
{dialogConfig.confirmText}
</Button>
</DialogActions>
</>
)}
</Dialog>
</ConfirmContext.Provider>
);
}
export function useConfirm() {
const context = useContext(ConfirmContext);
if (!context) {
throw new Error("useConfirm must be used within a ConfirmProvider");
}
return context;
}

84
src/hooks/CustomStyles.js Normal file
View File

@@ -0,0 +1,84 @@
import { useCallback, useMemo } from "react";
import { useSetting } from "./Setting";
import { DEFAULT_CUSTOM_STYLES, OPT_STYLE_ALL } from "../config/styles";
import { builtinStylesMap } from "../libs/style";
import { useI18n } from "./I18n";
function useStyleState() {
const { setting, updateSetting } = useSetting();
const customStyles = setting?.customStyles || [];
return { customStyles, updateSetting };
}
export function useStyleList() {
const { customStyles, updateSetting } = useStyleState();
const addStyle = useCallback(() => {
const defaultStyle = DEFAULT_CUSTOM_STYLES[0];
const uuid = crypto.randomUUID();
const styleSlug = `custom_${crypto.randomUUID()}`;
const styleName = `Style_${uuid.slice(0, 8)}`;
const newStyle = {
...defaultStyle,
styleSlug,
styleName,
};
updateSetting((prev) => ({
...prev,
customStyles: [...(prev?.customStyles || []), newStyle],
}));
}, [updateSetting]);
const deleteStyle = useCallback(
(styleSlug) => {
updateSetting((prev) => ({
...prev,
customStyles: (prev?.customStyles || []).filter(
(item) => item.styleSlug !== styleSlug
),
}));
},
[updateSetting]
);
const updateStyle = useCallback(
(styleSlug, updateData) => {
updateSetting((prev) => ({
...prev,
customStyles: (prev?.customStyles || []).map((item) =>
item.styleSlug === styleSlug ? { ...item, ...updateData } : item
),
}));
},
[updateSetting]
);
return {
customStyles,
addStyle,
deleteStyle,
updateStyle,
};
}
export function useAllTextStyles() {
const { customStyles } = useStyleList();
const i18n = useI18n();
const builtinStyles = useMemo(
() =>
OPT_STYLE_ALL.map((styleSlug) => ({
styleSlug,
styleName: i18n(styleSlug),
styleCode: builtinStylesMap[styleSlug] || "",
})),
[i18n]
);
const allTextStyles = useMemo(() => {
return [...builtinStyles, ...customStyles];
}, [builtinStyles, customStyles]);
return { builtinStyles, customStyles, allTextStyles };
}

View File

@@ -0,0 +1,23 @@
import { useMemo, useEffect, useRef } from "react";
import { debounce } from "../libs/utils";
export function useDebouncedCallback(callback, delay) {
const callbackRef = useRef(callback);
useEffect(() => {
callbackRef.current = callback;
}, [callback]);
const debouncedCallback = useMemo(
() => debounce((...args) => callbackRef.current(...args), delay),
[delay]
);
useEffect(() => {
return () => {
debouncedCallback.cancel();
};
}, [debouncedCallback]);
return debouncedCallback;
}

View File

@@ -1,11 +1,13 @@
import { STOKEY_FAB } from "../config"; import { STOKEY_FAB } from "../config";
import { useStorage } from "./Storage"; import { useStorage } from "./Storage";
const DEFAULT_FAB = {};
/** /**
* fab hook * fab hook
* @returns * @returns
*/ */
export function useFab() { export function useFab() {
const { data, update } = useStorage(STOKEY_FAB); const { data, update } = useStorage(STOKEY_FAB, DEFAULT_FAB);
return { fab: data, updateFab: update }; return { fab: data, updateFab: update };
} }

View File

@@ -1,68 +1,64 @@
import { KV_WORDS_KEY } from "../config"; import { STOKEY_WORDS, KV_WORDS_KEY } from "../config";
import { useCallback, useEffect, useState } from "react"; import { useCallback, useMemo } from "react";
import { trySyncWords } from "../libs/sync"; import { useStorage } from "./Storage";
import { getWordsWithDefault, setWords } from "../libs/storage"; import { debounceSyncMeta } from "../libs/storage";
import { useSyncMeta } from "./Sync";
import { kissLog } from "../libs/log"; const DEFAULT_FAVWORDS = {};
export function useFavWords() { export function useFavWords() {
const [loading, setLoading] = useState(false); const { data: favWords, save: saveWords } = useStorage(
const [favWords, setFavWords] = useState({}); STOKEY_WORDS,
const { updateSyncMeta } = useSyncMeta(); DEFAULT_FAVWORDS,
KV_WORDS_KEY
);
const save = useCallback(
(objOrFn) => {
saveWords(objOrFn);
debounceSyncMeta(KV_WORDS_KEY);
},
[saveWords]
);
const toggleFav = useCallback( const toggleFav = useCallback(
async (word) => { (word) => {
const favs = { ...favWords }; save((prev) => {
if (favs[word]) { if (!prev[word]) {
return { ...prev, [word]: { createdAt: Date.now() } };
}
const favs = { ...prev };
delete favs[word]; delete favs[word];
} else { return favs;
favs[word] = { createdAt: Date.now() }; });
}
await setWords(favs);
await updateSyncMeta(KV_WORDS_KEY);
await trySyncWords();
setFavWords(favs);
}, },
[updateSyncMeta, favWords] [save]
); );
const mergeWords = useCallback( const mergeWords = useCallback(
async (newWords) => { (words) => {
const favs = { ...favWords }; save((prev) => ({
newWords.forEach((word) => { ...words.reduce((acc, key) => {
if (!favs[word]) { acc[key] = { createdAt: Date.now() };
favs[word] = { createdAt: Date.now() }; return acc;
} }, {}),
}); ...prev,
await setWords(favs); }));
await updateSyncMeta(KV_WORDS_KEY);
await trySyncWords();
setFavWords(favs);
}, },
[updateSyncMeta, favWords] [save]
); );
const clearWords = useCallback(async () => { const clearWords = useCallback(() => {
await setWords({}); save({});
await updateSyncMeta(KV_WORDS_KEY); }, [save]);
await trySyncWords();
setFavWords({});
}, [updateSyncMeta]);
useEffect(() => { const favList = useMemo(
(async () => { () =>
try { Object.entries(favWords || {}).sort((a, b) => a[0].localeCompare(b[0])),
setLoading(true); [favWords]
await trySyncWords(); );
const favWords = await getWordsWithDefault();
setFavWords(favWords);
} catch (err) {
kissLog(err, "query fav");
} finally {
setLoading(false);
}
})();
}, []);
return { loading, favWords, toggleFav, mergeWords, clearWords }; const wordList = useMemo(() => favList.map(([word]) => word), [favList]);
return { favWords, favList, wordList, toggleFav, mergeWords, clearWords };
} }

View File

@@ -1,40 +1,152 @@
import { useEffect, useState } from "react"; import { useEffect, useState, useCallback } from "react";
/** export const useAsync = () => {
* fetch data hook
* @returns
*/
export const useFetch = (url) => {
const [data, setData] = useState(null); const [data, setData] = useState(null);
const [loading, setLoading] = useState(false); const [loading, setLoading] = useState(false);
const [error, setError] = useState(null); const [error, setError] = useState(null);
useEffect(() => { const execute = useCallback(async (fn, ...args) => {
if (!url) { if (!fn) {
return; return;
} }
(async () => { setLoading(true);
setLoading(true); setError(null);
try {
const res = await fetch(url);
if (!res.ok) {
throw new Error(`[${res.status}] ${res.statusText}`);
}
let data;
if (res.headers.get("Content-Type")?.includes("json")) {
data = await res.json();
} else {
data = await res.text();
}
setData(data);
} catch (err) {
setError(err);
} finally {
setLoading(false);
}
})();
}, [url]);
return [data, loading, error]; try {
const res = await fn(...args);
setData(res);
setLoading(false);
return res;
} catch (err) {
setError(err?.message || "An unknown error occurred");
setLoading(false);
// throw err;
}
}, []);
const reset = useCallback(() => {
setData(null);
setLoading(false);
setError(null);
}, []);
return { data, loading, error, execute, reset };
};
export const useAsyncNow = (fn, arg) => {
const { execute, ...asyncState } = useAsync();
useEffect(() => {
if (fn) {
execute(fn, arg);
}
}, [execute, fn, arg]);
return { ...asyncState };
};
export const useFetch = () => {
const { execute, ...asyncState } = useAsync();
const requester = useCallback(async (url, options) => {
const response = await fetch(url, options);
if (!response.ok) {
const errorInfo = await response.text();
throw new Error(
`Request failed: ${response.status} ${response.statusText} - ${errorInfo}`
);
}
if (response.status === 204) {
return null;
}
if (response.headers.get("Content-Type")?.includes("json")) {
return response.json();
}
return response.text();
}, []);
const get = useCallback(
async (url, options = {}) => {
try {
const result = await execute(requester, url, {
...options,
method: "GET",
});
return result;
} catch (err) {
return null;
}
},
[execute, requester]
);
const post = useCallback(
async (url, body, options = {}) => {
try {
const result = await execute(requester, url, {
...options,
method: "POST",
headers: { "Content-Type": "application/json", ...options.headers },
body: JSON.stringify(body),
});
return result;
} catch (err) {
return null;
}
},
[execute, requester]
);
const put = useCallback(
async (url, body, options = {}) => {
try {
const result = await execute(requester, url, {
...options,
method: "PUT",
headers: { "Content-Type": "application/json", ...options.headers },
body: JSON.stringify(body),
});
return result;
} catch (err) {
return null;
}
},
[execute, requester]
);
const del = useCallback(
async (url, options = {}) => {
try {
const result = await execute(requester, url, {
...options,
method: "DELETE",
});
return result;
} catch (err) {
return null;
}
},
[execute, requester]
);
return {
...asyncState,
get,
post,
put,
del,
};
};
export const useGet = (url) => {
const { get, ...fetchState } = useFetch();
useEffect(() => {
if (url) get(url);
}, [url, get]);
return { ...fetchState };
}; };

View File

@@ -1,6 +1,6 @@
import { useSetting } from "./Setting"; import { useSetting } from "./Setting";
import { I18N, URL_RAW_PREFIX } from "../config"; import { I18N, URL_RAW_PREFIX } from "../config";
import { useFetch } from "./Fetch"; import { useGet } from "./Fetch";
export const getI18n = (uiLang, key, defaultText = "") => { export const getI18n = (uiLang, key, defaultText = "") => {
return I18N?.[key]?.[uiLang] ?? defaultText; return I18N?.[key]?.[uiLang] ?? defaultText;
@@ -25,5 +25,5 @@ export const useI18nMd = (key) => {
const i18n = useI18n(); const i18n = useI18n();
const fileName = i18n(key); const fileName = i18n(key);
const url = fileName ? `${URL_RAW_PREFIX}/${fileName}` : ""; const url = fileName ? `${URL_RAW_PREFIX}/${fileName}` : "";
return useFetch(url); return useGet(url);
}; };

View File

@@ -1,18 +1,10 @@
import { useCallback } from "react";
import { DEFAULT_INPUT_RULE } from "../config"; import { DEFAULT_INPUT_RULE } from "../config";
import { useSetting } from "./Setting"; import { useSetting } from "./Setting";
export function useInputRule() { export function useInputRule() {
const { setting, updateSetting } = useSetting(); const { setting, updateChild } = useSetting();
const inputRule = setting?.inputRule || DEFAULT_INPUT_RULE; const inputRule = setting?.inputRule || DEFAULT_INPUT_RULE;
const updateInputRule = updateChild("inputRule");
const updateInputRule = useCallback(
async (obj) => {
Object.assign(inputRule, obj);
await updateSetting({ inputRule });
},
[inputRule, updateSetting]
);
return { inputRule, updateInputRule }; return { inputRule, updateInputRule };
} }

16
src/hooks/Loading.js Normal file
View File

@@ -0,0 +1,16 @@
import CircularProgress from "@mui/material/CircularProgress";
import Link from "@mui/material/Link";
import Divider from "@mui/material/Divider";
export default function Loading() {
return (
<center>
<Divider>
<Link
href={process.env.REACT_APP_HOMEPAGE}
>{`KISS Translator v${process.env.REACT_APP_VERSION}`}</Link>
</Divider>
<CircularProgress />
</center>
);
}

11
src/hooks/MouseHover.js Normal file
View File

@@ -0,0 +1,11 @@
import { DEFAULT_MOUSE_HOVER_SETTING } from "../config";
import { useSetting } from "./Setting";
export function useMouseHoverSetting() {
const { setting, updateChild } = useSetting();
const mouseHoverSetting =
setting?.mouseHoverSetting || DEFAULT_MOUSE_HOVER_SETTING;
const updateMouseHoverSetting = updateChild("mouseHoverSetting");
return { mouseHoverSetting, updateMouseHoverSetting };
}

View File

@@ -1,90 +1,104 @@
import { STOKEY_RULES, DEFAULT_RULES, KV_RULES_KEY } from "../config"; import { STOKEY_RULES, DEFAULT_RULES, KV_RULES_KEY } from "../config";
import { useStorage } from "./Storage"; import { useStorage } from "./Storage";
import { trySyncRules } from "../libs/sync";
import { checkRules } from "../libs/rules"; import { checkRules } from "../libs/rules";
import { useCallback } from "react"; import { useCallback } from "react";
import { useSyncMeta } from "./Sync"; import { debounceSyncMeta } from "../libs/storage";
/** /**
* 规则 hook * 规则 hook
* @returns * @returns
*/ */
export function useRules() { export function useRules() {
const { data: list, save } = useStorage(STOKEY_RULES, DEFAULT_RULES); const { data: list = [], save: saveRules } = useStorage(
const { updateSyncMeta } = useSyncMeta(); STOKEY_RULES,
DEFAULT_RULES,
KV_RULES_KEY
);
const updateRules = useCallback( const save = useCallback(
async (rules) => { (objOrFn) => {
await save(rules); saveRules(objOrFn);
await updateSyncMeta(KV_RULES_KEY); debounceSyncMeta(KV_RULES_KEY);
trySyncRules();
}, },
[save, updateSyncMeta] [saveRules]
); );
const add = useCallback( const add = useCallback(
async (rule) => { (rule) => {
const rules = [...list]; save((prev) => {
if (rule.pattern === "*") { if (
return; rule.pattern === "*" ||
} prev.some((item) => item.pattern === rule.pattern)
if (rules.map((item) => item.pattern).includes(rule.pattern)) { ) {
return; return prev;
} }
rules.unshift(rule); return [rule, ...prev];
await updateRules(rules); });
}, },
[list, updateRules] [save]
); );
const del = useCallback( const del = useCallback(
async (pattern) => { (pattern) => {
let rules = [...list]; save((prev) => {
if (pattern === "*") { if (pattern === "*") {
return; return prev;
} }
rules = rules.filter((item) => item.pattern !== pattern); return prev.filter((item) => item.pattern !== pattern);
await updateRules(rules); });
}, },
[list, updateRules] [save]
); );
const clear = useCallback(async () => { const clear = useCallback(() => {
let rules = [...list]; save((prev) => prev.filter((item) => item.pattern === "*"));
rules = rules.filter((item) => item.pattern === "*"); }, [save]);
await updateRules(rules);
}, [list, updateRules]);
const put = useCallback( const put = useCallback(
async (pattern, obj) => { (pattern, obj) => {
const rules = [...list]; save((prev) => {
if (pattern === "*") { // if (pattern !== obj.pattern) {
obj.pattern = "*"; // return prev;
} // }
const rule = rules.find((r) => r.pattern === pattern); return prev.map((item) =>
rule && Object.assign(rule, obj); item.pattern === pattern ? { ...item, ...obj } : item
await updateRules(rules); );
});
}, },
[list, updateRules] [save]
); );
const merge = useCallback( const merge = useCallback(
async (newRules) => { (rules) => {
const rules = [...list]; save((prev) => {
newRules = checkRules(newRules); const adds = checkRules(rules);
newRules.forEach((newRule) => { if (adds.length === 0) {
const rule = rules.find( return prev;
(oldRule) => oldRule.pattern === newRule.pattern
);
if (rule) {
Object.assign(rule, newRule);
} else {
rules.unshift(newRule);
} }
// const map = new Map();
// // 不进行深度合并
// // [...prev, ...adds].forEach((item) => {
// // const k = item.pattern;
// // map.set(k, { ...(map.get(k) || {}), ...item });
// // });
// prev.forEach((item) => map.set(item.pattern, item));
// adds.forEach((item) => map.set(item.pattern, item));
// return [...map.values()];
const addsMap = new Map(adds.map((item) => [item.pattern, item]));
const prevPatterns = new Set(prev.map((item) => item.pattern));
const updatedPrev = prev.map(
(prevItem) => addsMap.get(prevItem.pattern) || prevItem
);
const newItems = adds.filter(
(addItem) => !prevPatterns.has(addItem.pattern)
);
return [...newItems, ...updatedPrev];
}); });
await updateRules(rules);
}, },
[list, updateRules] [save]
); );
return { list, add, del, clear, put, merge }; return { list, add, del, clear, put, merge };

View File

@@ -1,51 +1,113 @@
import { STOKEY_SETTING, DEFAULT_SETTING, KV_SETTING_KEY } from "../config"; import {
createContext,
useCallback,
useContext,
useMemo,
useEffect,
} from "react";
import Alert from "@mui/material/Alert";
import {
STOKEY_SETTING,
DEFAULT_SETTING,
KV_SETTING_KEY,
MSG_SET_LOGLEVEL,
} from "../config";
import { useStorage } from "./Storage"; import { useStorage } from "./Storage";
import { trySyncSetting } from "../libs/sync"; import { debounceSyncMeta } from "../libs/storage";
import { createContext, useCallback, useContext, useMemo } from "react"; import Loading from "./Loading";
import { debounce } from "../libs/utils"; import { logger } from "../libs/log";
import { useSyncMeta } from "./Sync"; import { sendBgMsg } from "../libs/msg";
import { isExt } from "../libs/client";
const SettingContext = createContext({ const SettingContext = createContext({
setting: null, setting: DEFAULT_SETTING,
updateSetting: async () => {}, updateSetting: () => {},
reloadSetting: async () => {}, reloadSetting: () => {},
}); });
export function SettingProvider({ children }) { export function SettingProvider({ children, context }) {
const { data, update, reload } = useStorage(STOKEY_SETTING, DEFAULT_SETTING); const isOptionsPage = useMemo(() => context === "options", [context]);
const { updateSyncMeta } = useSyncMeta();
const syncSetting = useMemo( const {
() => data: setting,
debounce(() => { isLoading,
trySyncSetting(); update,
}, [2000]), reload,
[] } = useStorage(STOKEY_SETTING, DEFAULT_SETTING, KV_SETTING_KEY);
);
useEffect(() => {
if (typeof setting?.darkMode === "boolean") {
update((currentSetting) => ({
...currentSetting,
darkMode: currentSetting.darkMode ? "dark" : "light",
}));
}
}, [setting?.darkMode, update]);
useEffect(() => {
if (!isOptionsPage) return;
(async () => {
try {
logger.setLevel(setting?.logLevel);
if (isExt) {
await sendBgMsg(MSG_SET_LOGLEVEL, setting?.logLevel);
}
} catch (error) {
logger.error("Failed to fetch log level, using default.", error);
}
})();
}, [isOptionsPage, setting?.logLevel]);
const updateSetting = useCallback( const updateSetting = useCallback(
async (obj) => { (objOrFn) => {
await update(obj); update(objOrFn);
await updateSyncMeta(KV_SETTING_KEY); debounceSyncMeta(KV_SETTING_KEY);
syncSetting();
}, },
[update, syncSetting, updateSyncMeta] [update]
); );
if (!data) { const updateChild = useCallback(
return; (key) => async (obj) => {
updateSetting((prev) => ({
...prev,
[key]: { ...(prev?.[key] || {}), ...obj },
}));
},
[updateSetting]
);
const value = useMemo(
() => ({
context,
setting,
updateSetting,
updateChild,
reloadSetting: reload,
}),
[context, setting, updateSetting, updateChild, reload]
);
if (isLoading) {
return isOptionsPage ? <Loading /> : null;
}
if (!setting) {
return isOptionsPage ? (
<center>
<Alert severity="error" sx={{ maxWidth: 600, margin: "60px auto" }}>
<p>数据加载出错请刷新页面或卸载后重新安装</p>
<p>
Data loading error, please refresh the page or uninstall and
reinstall.
</p>
</Alert>
</center>
) : null;
} }
return ( return (
<SettingContext.Provider <SettingContext.Provider value={value}>{children}</SettingContext.Provider>
value={{
setting: data,
updateSetting,
reloadSetting: reload,
}}
>
{children}
</SettingContext.Provider>
); );
} }

View File

@@ -6,13 +6,14 @@ export function useShortcut(action) {
const { setting, updateSetting } = useSetting(); const { setting, updateSetting } = useSetting();
const shortcuts = setting?.shortcuts || DEFAULT_SHORTCUTS; const shortcuts = setting?.shortcuts || DEFAULT_SHORTCUTS;
const shortcut = shortcuts[action] || []; const shortcut = shortcuts[action] || [];
const setShortcut = useCallback( const setShortcut = useCallback(
async (val) => { (val) => {
Object.assign(shortcuts, { [action]: val }); updateSetting((prev) => ({
await updateSetting({ shortcuts }); ...prev,
shortcuts: { ...(prev?.shortcuts || {}), [action]: val },
}));
}, },
[action, shortcuts, updateSetting] [action, updateSetting]
); );
return { shortcut, setShortcut }; return { shortcut, setShortcut };

View File

@@ -1,70 +1,145 @@
import { useCallback, useEffect, useState } from "react"; import { useCallback, useEffect, useState } from "react";
import { storage } from "../libs/storage"; import { storage } from "../libs/storage";
import { kissLog } from "../libs/log"; import { kissLog } from "../libs/log";
import { syncData } from "../libs/sync";
import { useDebouncedCallback } from "./DebouncedCallback";
import { isOptions } from "../libs/browser";
/** /**
* 用于将组件状态与 Storage 同步
* *
* @param {*} key * @param {string} key 用于在 Storage 中存取值的键
* @param {*} defaultVal 需为调用hook外的常量 * @param {*} defaultVal 默认值。建议在组件外定义为常量
* @returns * @param {string} [syncKey=""] 用于远端同步的可选键名
* @returns {{
* data: *,
* save: (valueOrFn: any | ((prevData: any) => any)) => void,
* update: (partialDataOrFn: object | ((prevData: object) => object)) => void,
* remove: () => Promise<void>,
* reload: () => Promise<void>
* }}
*/ */
export function useStorage(key, defaultVal) { export function useStorage(key, defaultVal = null, syncKey = "") {
const [loading, setLoading] = useState(false); const [isLoading, setIsLoading] = useState(true);
const [data, setData] = useState(null); const [data, setData] = useState(defaultVal);
const save = useCallback( // 首次加载数据
async (val) => { useEffect(() => {
setData(val); let isMounted = true;
await storage.setObj(key, val);
},
[key]
);
const update = useCallback( const loadInitialData = async () => {
async (obj) => { try {
setData((pre = {}) => ({ ...pre, ...obj })); const storedVal = await storage.getObj(key);
await storage.putObj(key, obj); if (storedVal === undefined || storedVal === null) {
}, await storage.setObj(key, defaultVal);
[key] } else if (isMounted) {
); setData(storedVal);
}
const remove = useCallback(async () => { } catch (err) {
setData(null); kissLog(`storage load error for key: ${key}`, err);
await storage.del(key); } finally {
}, [key]); if (isMounted) {
setIsLoading(false);
const reload = useCallback(async () => { }
try {
setLoading(true);
const val = await storage.getObj(key);
if (val) {
setData(val);
} }
};
loadInitialData();
return () => {
isMounted = false;
};
}, [key, defaultVal]);
// 远端同步
const runSync = useCallback(async (keyToSync, valueToSync) => {
try {
const res = await syncData(keyToSync, valueToSync);
if (res?.isNew) {
setData(res.value);
}
} catch (error) {
kissLog("Sync failed", keyToSync);
}
}, []);
const debouncedSync = useDebouncedCallback(runSync, 3000);
// 持久化
useEffect(() => {
if (isLoading) {
return;
}
if (data === null) {
return;
}
storage.setObj(key, data).catch((err) => {
kissLog(`storage save error for key: ${key}`, err);
});
// 触发远端同步
if (syncKey && isOptions()) {
debouncedSync(syncKey, data);
}
}, [key, syncKey, isLoading, data, debouncedSync]);
/**
* 全量替换状态值
* @param {any | ((prevData: any) => any)} valueOrFn 新的值或一个返回新值的函数。
*/
const save = useCallback((valueOrFn) => {
// kissLog("save storage:", valueOrFn);
setData((prevData) =>
typeof valueOrFn === "function" ? valueOrFn(prevData) : valueOrFn
);
}, []);
/**
* 合并对象到当前状态(假设状态是一个对象)。
* @param {object | ((prevData: object) => object)} partialDataOrFn 要合并的对象或一个返回该对象的函数。
*/
const update = useCallback((partialDataOrFn) => {
// kissLog("update storage:", partialDataOrFn);
setData((prevData) => {
const partialData =
typeof partialDataOrFn === "function"
? partialDataOrFn(prevData)
: partialDataOrFn;
// 确保 preData 是一个对象,避免展开 null 或 undefined
const baseObj =
typeof prevData === "object" && prevData !== null ? prevData : {};
return { ...baseObj, ...partialData };
});
}, []);
/**
* 从 Storage 中删除该值,并将状态重置为 null。
*/
const remove = useCallback(async () => {
// kissLog("remove storage:");
try {
await storage.del(key);
setData(null);
} catch (err) { } catch (err) {
kissLog(err, "storage reload"); kissLog(`storage remove error for key: ${key}`, err);
} finally {
setLoading(false);
} }
}, [key]); }, [key]);
useEffect(() => { /**
(async () => { * 从 Storage 重新加载数据以覆盖当前状态。
try { */
setLoading(true); const reload = useCallback(async () => {
const val = await storage.getObj(key); // kissLog("reload storage:");
if (val) { try {
setData(val); const storedVal = await storage.getObj(key);
} else if (defaultVal) { setData(storedVal ?? defaultVal);
setData(defaultVal); } catch (err) {
await storage.setObj(key, defaultVal); kissLog(`storage reload error for key: ${key}`, err);
} // setData(defaultVal);
} catch (err) { }
kissLog(err, "storage load");
} finally {
setLoading(false);
}
})();
}, [key, defaultVal]); }, [key, defaultVal]);
return { data, save, update, remove, reload, loading }; return { data, save, update, remove, reload, isLoading };
} }

View File

@@ -1,8 +1,7 @@
import { DEFAULT_SUBRULES_LIST, DEFAULT_OW_RULE } from "../config"; import { DEFAULT_SUBRULES_LIST } from "../config";
import { useSetting } from "./Setting"; import { useSetting } from "./Setting";
import { useCallback, useEffect, useMemo, useState } from "react"; import { useCallback, useEffect, useMemo, useState } from "react";
import { loadOrFetchSubRules } from "../libs/subRules"; import { loadOrFetchSubRules } from "../libs/subRules";
import { delSubRules } from "../libs/storage";
import { kissLog } from "../libs/log"; import { kissLog } from "../libs/log";
/** /**
@@ -19,50 +18,36 @@ export function useSubRules() {
const selectedUrl = selectedSub.url; const selectedUrl = selectedSub.url;
const selectSub = useCallback( const selectSub = useCallback(
async (url) => { (url) => {
const subrulesList = [...list]; updateSetting((prev) => ({
subrulesList.forEach((item) => { ...prev,
if (item.url === url) { subrulesList: prev.subrulesList.map((item) => ({
item.selected = true; ...item,
} else { selected: item.url === url,
item.selected = false; })),
} }));
});
await updateSetting({ subrulesList });
}, },
[list, updateSetting] [updateSetting]
);
const updateSub = useCallback(
async (url, obj) => {
const subrulesList = [...list];
subrulesList.forEach((item) => {
if (item.url === url) {
Object.assign(item, obj);
}
});
await updateSetting({ subrulesList });
},
[list, updateSetting]
); );
const addSub = useCallback( const addSub = useCallback(
async (url) => { (url) => {
const subrulesList = [...list]; updateSetting((prev) => ({
subrulesList.push({ url, selected: false }); ...prev,
await updateSetting({ subrulesList }); subrulesList: [...prev.subrulesList, { url, selected: false }],
}));
}, },
[list, updateSetting] [updateSetting]
); );
const delSub = useCallback( const delSub = useCallback(
async (url) => { (url) => {
let subrulesList = [...list]; updateSetting((prev) => ({
subrulesList = subrulesList.filter((item) => item.url !== url); ...prev,
await updateSetting({ subrulesList }); subrulesList: prev.subrulesList.filter((item) => item.url !== url),
await delSubRules(url); }));
}, },
[list, updateSetting] [updateSetting]
); );
useEffect(() => { useEffect(() => {
@@ -73,7 +58,7 @@ export function useSubRules() {
const rules = await loadOrFetchSubRules(selectedUrl); const rules = await loadOrFetchSubRules(selectedUrl);
setSelectedRules(rules); setSelectedRules(rules);
} catch (err) { } catch (err) {
kissLog(err, "loadOrFetchSubRules"); kissLog("loadOrFetchSubRules", err);
} finally { } finally {
setLoading(false); setLoading(false);
} }
@@ -84,7 +69,6 @@ export function useSubRules() {
return { return {
subList: list, subList: list,
selectSub, selectSub,
updateSub,
addSub, addSub,
delSub, delSub,
selectedSub, selectedSub,
@@ -94,21 +78,3 @@ export function useSubRules() {
loading, loading,
}; };
} }
/**
* 覆写订阅规则
* @returns
*/
export function useOwSubRule() {
const { setting, updateSetting } = useSetting();
const { owSubrule = DEFAULT_OW_RULE } = setting;
const updateOwSubrule = useCallback(
async (obj) => {
await updateSetting({ owSubrule: { ...owSubrule, ...obj } });
},
[owSubrule, updateSetting]
);
return { owSubrule, updateOwSubrule };
}

10
src/hooks/Subtitle.js Normal file
View File

@@ -0,0 +1,10 @@
import { DEFAULT_SUBTITLE_SETTING } from "../config";
import { useSetting } from "./Setting";
export function useSubtitle() {
const { setting, updateChild } = useSetting();
const subtitleSetting = setting?.subtitleSetting || DEFAULT_SUBTITLE_SETTING;
const updateSubtitle = updateChild("subtitleSetting");
return { subtitleSetting, updateSubtitle };
}

View File

@@ -1,4 +1,4 @@
import { useCallback } from "react"; import { useCallback, useMemo } from "react";
import { STOKEY_SYNC, DEFAULT_SYNC } from "../config"; import { STOKEY_SYNC, DEFAULT_SYNC } from "../config";
import { useStorage } from "./Storage"; import { useStorage } from "./Storage";
@@ -16,15 +16,24 @@ export function useSync() {
* @returns * @returns
*/ */
export function useSyncMeta() { export function useSyncMeta() {
const { sync, updateSync } = useSync(); const { updateSync } = useSync();
const updateSyncMeta = useCallback( const updateSyncMeta = useCallback(
async (key) => { (key) => {
const syncMeta = sync?.syncMeta || {}; updateSync((prevSync) => {
syncMeta[key] = { ...(syncMeta[key] || {}), updateAt: Date.now() }; const newSyncMeta = {
await updateSync({ syncMeta }); ...(prevSync?.syncMeta || {}),
[key]: {
...(prevSync?.syncMeta?.[key] || {}),
updateAt: Date.now(),
},
};
return { syncMeta: newSyncMeta };
});
}, },
[sync?.syncMeta, updateSync] [updateSync]
); );
return { updateSyncMeta }; return { updateSyncMeta };
} }
@@ -37,25 +46,32 @@ export function useSyncCaches() {
const { sync, updateSync, reloadSync } = useSync(); const { sync, updateSync, reloadSync } = useSync();
const updateDataCache = useCallback( const updateDataCache = useCallback(
async (url) => { (url) => {
const dataCaches = sync?.dataCaches || {}; updateSync((prevSync) => ({
dataCaches[url] = Date.now(); dataCaches: {
await updateSync({ dataCaches }); ...(prevSync?.dataCaches || {}),
[url]: Date.now(),
},
}));
}, },
[sync, updateSync] [updateSync]
); );
const deleteDataCache = useCallback( const deleteDataCache = useCallback(
async (url) => { (url) => {
const dataCaches = sync?.dataCaches || {}; updateSync((prevSync) => {
delete dataCaches[url]; const newDataCaches = { ...(prevSync?.dataCaches || {}) };
await updateSync({ dataCaches }); delete newDataCaches[url];
return { dataCaches: newDataCaches };
});
}, },
[sync, updateSync] [updateSync]
); );
const dataCaches = useMemo(() => sync?.dataCaches || {}, [sync?.dataCaches]);
return { return {
dataCaches: sync?.dataCaches || {}, dataCaches,
updateDataCache, updateDataCache,
deleteDataCache, deleteDataCache,
reloadSync, reloadSync,

View File

@@ -1,4 +1,4 @@
import { useMemo } from "react"; import { useEffect, useMemo, useState } from "react";
import { ThemeProvider, createTheme } from "@mui/material/styles"; import { ThemeProvider, createTheme } from "@mui/material/styles";
import { CssBaseline, GlobalStyles } from "@mui/material"; import { CssBaseline, GlobalStyles } from "@mui/material";
import { useDarkMode } from "./ColorMode"; import { useDarkMode } from "./ColorMode";
@@ -9,30 +9,45 @@ import { THEME_DARK, THEME_LIGHT } from "../config";
* @param {*} param0 * @param {*} param0
* @returns * @returns
*/ */
export default function Theme({ children, options, styles }) { export default function Theme({ children, options = {}, styles = {} }) {
const { darkMode } = useDarkMode(); const { darkMode } = useDarkMode();
const [systemMode, setSystemMode] = useState(THEME_LIGHT);
useEffect(() => {
if (typeof window.matchMedia !== "function") {
return;
}
const mediaQuery = window.matchMedia("(prefers-color-scheme: dark)");
const handleChange = () => {
setSystemMode(mediaQuery.matches ? THEME_DARK : THEME_LIGHT);
};
handleChange(); // Set initial value
mediaQuery.addEventListener("change", handleChange);
return () => mediaQuery.removeEventListener("change", handleChange);
}, []);
const theme = useMemo(() => { const theme = useMemo(() => {
let htmlFontSize = 16; let htmlFontSize = 16;
try { try {
const s = window.getComputedStyle(document.body.parentNode).fontSize; const s = window.getComputedStyle(document.documentElement).fontSize;
const fontSize = parseInt(s.replace("px", "")); htmlFontSize = parseInt(s.replace("px", ""));
if (fontSize > 0 && fontSize < 1000) {
htmlFontSize = fontSize;
}
} catch (err) { } catch (err) {
// //
} }
const isDarkMode =
darkMode === "dark" || (darkMode === "auto" && systemMode === THEME_DARK);
return createTheme({ return createTheme({
palette: { palette: {
mode: darkMode ? THEME_DARK : THEME_LIGHT, mode: isDarkMode ? THEME_DARK : THEME_LIGHT,
}, },
typography: { typography: {
htmlFontSize, htmlFontSize,
}, },
...options, ...options,
}); });
}, [darkMode, options]); }, [darkMode, options, systemMode]);
return ( return (
<ThemeProvider theme={theme}> <ThemeProvider theme={theme}>

View File

@@ -1,18 +1,10 @@
import { useCallback } from "react";
import { DEFAULT_TRANBOX_SETTING } from "../config"; import { DEFAULT_TRANBOX_SETTING } from "../config";
import { useSetting } from "./Setting"; import { useSetting } from "./Setting";
export function useTranbox() { export function useTranbox() {
const { setting, updateSetting } = useSetting(); const { setting, updateChild } = useSetting();
const tranboxSetting = setting?.tranboxSetting || DEFAULT_TRANBOX_SETTING; const tranboxSetting = setting?.tranboxSetting || DEFAULT_TRANBOX_SETTING;
const updateTranbox = updateChild("tranboxSetting");
const updateTranbox = useCallback(
async (obj) => {
Object.assign(tranboxSetting, obj);
await updateSetting({ tranboxSetting });
},
[tranboxSetting, updateSetting]
);
return { tranboxSetting, updateTranbox }; return { tranboxSetting, updateTranbox };
} }

View File

@@ -1,59 +0,0 @@
import { useEffect } from "react";
import { useState } from "react";
import { tryDetectLang } from "../libs";
import { apiTranslate } from "../apis";
import { DEFAULT_TRANS_APIS } from "../config";
import { kissLog } from "../libs/log";
/**
* 翻译hook
* @param {*} q
* @param {*} rule
* @param {*} setting
* @returns
*/
export function useTranslate(q, rule, setting) {
const [text, setText] = useState("");
const [loading, setLoading] = useState(false);
const [sameLang, setSamelang] = useState(false);
const { translator, fromLang, toLang, detectRemote, skipLangs = [] } = rule;
useEffect(() => {
(async () => {
try {
setLoading(true);
if (!q.replace(/\[(\d+)\]/g, "").trim()) {
setText(q);
setSamelang(false);
return;
}
const deLang = await tryDetectLang(q, detectRemote === "true");
if (deLang && (toLang.includes(deLang) || skipLangs.includes(deLang))) {
setSamelang(true);
} else {
const [trText, isSame] = await apiTranslate({
translator,
text: q,
fromLang,
toLang,
apiSetting: {
...DEFAULT_TRANS_APIS[translator],
...(setting.transApis[translator] || {}),
},
});
setText(trText);
setSamelang(isSame);
}
} catch (err) {
kissLog(err, "translate");
} finally {
setLoading(false);
}
})();
}, [q, translator, fromLang, toLang, detectRemote, skipLangs, setting]);
return { text, sameLang, loading };
}

View File

@@ -0,0 +1,61 @@
import { useState, useEffect } from "react";
import TextField from "@mui/material/TextField";
import { limitNumber, limitFloat } from "../libs/utils";
function ValidationInput({
value,
onChange,
name,
min,
max,
isFloat = false,
...props
}) {
const [localValue, setLocalValue] = useState(value);
useEffect(() => {
setLocalValue(value);
}, [value]);
const handleLocalChange = (e) => {
setLocalValue(e.target.value);
};
const handleBlur = () => {
const numValue = Number(localValue);
if (isNaN(numValue)) {
setLocalValue(value);
return;
}
const validatedValue = isFloat
? limitFloat(numValue, min, max)
: limitNumber(numValue, min, max);
if (validatedValue !== numValue) {
setLocalValue(validatedValue);
}
onChange({
target: {
name: name,
value: validatedValue,
},
preventDefault: () => {},
});
};
return (
<TextField
{...props}
type="number"
name={name}
value={localValue}
onChange={handleLocalChange}
onBlur={handleBlur}
/>
);
}
export default ValidationInput;

29
src/hooks/WindowSize.js Normal file
View File

@@ -0,0 +1,29 @@
import { useState, useEffect } from "react";
import { useDebouncedCallback } from "./DebouncedCallback";
function useWindowSize() {
const [windowSize, setWindowSize] = useState({
w: window.innerWidth,
h: window.innerHeight,
});
const debounceWindowResize = useDebouncedCallback(() => {
setWindowSize({
w: window.innerWidth,
h: window.innerHeight,
});
}, 200);
useEffect(() => {
debounceWindowResize();
window.addEventListener("resize", debounceWindowResize);
return () => {
window.removeEventListener("resize", debounceWindowResize);
};
}, [debounceWindowResize]);
return windowSize;
}
export default useWindowSize;

View File

@@ -7,14 +7,15 @@ import Paper from "@mui/material/Paper";
import Stack from "@mui/material/Stack"; import Stack from "@mui/material/Stack";
import Button from "@mui/material/Button"; import Button from "@mui/material/Button";
import Link from "@mui/material/Link"; import Link from "@mui/material/Link";
import { useFetch } from "./hooks/Fetch"; import { useGet } from "./hooks/Fetch";
import { I18N, URL_RAW_PREFIX } from "./config"; import { I18N, URL_RAW_PREFIX } from "./config";
function App() { function App() {
const [lang, setLang] = useState("zh"); const [lang, setLang] = useState("zh");
const [data, loading, error] = useFetch( const { data, loading, error } = useGet(
`${URL_RAW_PREFIX}/${I18N?.["about_md"]?.[lang]}` `${URL_RAW_PREFIX}/${I18N?.["about_md"]?.[lang]}`
); );
return ( return (
<Paper sx={{ padding: 2, margin: 2 }}> <Paper sx={{ padding: 2, margin: 2 }}>
<Stack spacing={2} direction="row" justifyContent="flex-end"> <Stack spacing={2} direction="row" justifyContent="flex-end">
@@ -47,7 +48,7 @@ function App() {
<CircularProgress /> <CircularProgress />
</center> </center>
) : ( ) : (
<ReactMarkdown children={error ? error.message : data} /> <ReactMarkdown children={error || data} />
)} )}
</Paper> </Paper>
); );

View File

@@ -0,0 +1,3 @@
import { shadowRootInjector } from "./injectors/shadowroot";
shadowRootInjector();

3
src/injector-subtitle.js Normal file
View File

@@ -0,0 +1,3 @@
import { XMLHttpRequestInjector } from "./injectors/xmlhttp";
XMLHttpRequestInjector();

27
src/injectors/index.js Normal file
View File

@@ -0,0 +1,27 @@
import { browser } from "../libs/browser";
import { isExt } from "../libs/client";
import { injectExternalJs, injectInlineJs } from "../libs/injector";
import { shadowRootInjector } from "./shadowroot";
import { XMLHttpRequestInjector } from "./xmlhttp";
export const INJECTOR = {
subtitle: "injector-subtitle.js",
shadowroot: "injector-shadowroot.js",
};
const injectorMap = {
[INJECTOR.subtitle]: XMLHttpRequestInjector,
[INJECTOR.shadowroot]: shadowRootInjector,
};
export function injectJs(name, id = "kiss-translator-inject-js") {
const injector = injectorMap[name];
if (!injector) return;
if (isExt) {
const src = browser.runtime.getURL(name);
injectExternalJs(src, id);
} else {
injectInlineJs(`(${injector})()`, id);
}
}

View File

@@ -0,0 +1,12 @@
export const shadowRootInjector = () => {
try {
const orig = Element.prototype.attachShadow;
Element.prototype.attachShadow = function (...args) {
const root = orig.apply(this, args);
window.postMessage({ type: "KISS_SHADOW_ROOT_CREATED" }, "*");
return root;
};
} catch (err) {
console.log("shadowRootInjector", err);
}
};

23
src/injectors/xmlhttp.js Normal file
View File

@@ -0,0 +1,23 @@
export const XMLHttpRequestInjector = () => {
try {
const originalOpen = XMLHttpRequest.prototype.open;
XMLHttpRequest.prototype.open = function (...args) {
const url = args[1];
if (typeof url === "string" && url.includes("timedtext")) {
this.addEventListener("load", function () {
window.postMessage(
{
type: "KISS_XHR_DATA_YOUTUBE",
url: this.responseURL,
response: this.responseText,
},
window.location.origin
);
});
}
return originalOpen.apply(this, args);
};
} catch (err) {
console.log("XMLHttpRequestInjector", err);
}
};

View File

@@ -1,13 +1,12 @@
import { getMsauth, setMsauth } from "./storage"; import { getMsauth, setMsauth } from "./storage";
import { URL_MICROSOFT_AUTH } from "../config";
import { fetchHandle } from "./fetch";
import { kissLog } from "./log"; import { kissLog } from "./log";
import { apiMsAuth } from "../apis";
const parseMSToken = (token) => { const parseMSToken = (token) => {
try { try {
return JSON.parse(atob(token.split(".")[1])).exp; return JSON.parse(atob(token.split(".")[1])).exp;
} catch (err) { } catch (err) {
kissLog(err, "parseMSToken"); kissLog("parseMSToken", err);
} }
return 0; return 0;
}; };
@@ -17,28 +16,55 @@ const parseMSToken = (token) => {
* @returns * @returns
*/ */
const _msAuth = () => { const _msAuth = () => {
let { token, exp } = {}; let tokenPromise = null;
const EXPIRATION_MS = 1000;
const fetchNewToken = async () => {
try {
const now = Date.now();
// 1. 查询storage缓存
const storageToken = await getMsauth();
if (storageToken) {
const storageExp = parseMSToken(storageToken);
const storageExpiresAt = storageExp * 1000;
if (storageExpiresAt > now + EXPIRATION_MS) {
return { token: storageToken, expiresAt: storageExpiresAt };
}
}
// 2. 缓存没有或失效,查询接口
const apiToken = await apiMsAuth();
if (!apiToken) {
throw new Error("Failed to fetch ms token");
}
const apiExp = parseMSToken(apiToken);
const apiExpiresAt = apiExp * 1000;
await setMsauth(apiToken);
return { token: apiToken, expiresAt: apiExpiresAt };
} catch (error) {
kissLog("get msauth failed", error);
throw error;
}
};
return async () => { return async () => {
// 查询内存缓存 // 检查是否有缓存的 Promise
const now = Date.now(); if (tokenPromise) {
if (token && exp * 1000 > now + 1000) { try {
return [token, exp]; const cachedResult = await tokenPromise;
if (cachedResult.expiresAt > Date.now() + EXPIRATION_MS) {
return cachedResult.token;
}
} catch (error) {
//
}
} }
// 查询storage缓存 tokenPromise = fetchNewToken();
const res = await getMsauth(); const result = await tokenPromise;
token = res?.token; return result.token;
exp = res?.exp;
if (token && exp * 1000 > now + 1000) {
return [token, exp];
}
// 缓存没有或失效,查询接口
token = await fetchHandle({ input: URL_MICROSOFT_AUTH });
exp = parseMSToken(token);
await setMsauth({ token, exp });
return [token, exp];
}; };
}; };

152
src/libs/batchQueue.js Normal file
View File

@@ -0,0 +1,152 @@
import {
DEFAULT_BATCH_INTERVAL,
DEFAULT_BATCH_SIZE,
DEFAULT_BATCH_LENGTH,
} from "../config";
/**
* 批处理队列
* @param {*} args
* @param {*} param1
* @returns
*/
const BatchQueue = (
taskFn,
{
batchInterval = DEFAULT_BATCH_INTERVAL,
batchSize = DEFAULT_BATCH_SIZE,
batchLength = DEFAULT_BATCH_LENGTH,
} = {}
) => {
const queue = [];
let isProcessing = false;
let timer = null;
const sendBatchRequest = async (payloads, batchArgs) => {
return taskFn(payloads, batchArgs);
};
const processQueue = async () => {
if (timer) {
clearTimeout(timer);
timer = null;
}
if (queue.length === 0 || isProcessing) {
return;
}
isProcessing = true;
let tasksToProcess = [];
let currentBatchLength = 0;
let endIndex = 0;
for (const task of queue) {
const textLength = task.payload?.length || 0;
if (
endIndex >= batchSize ||
(currentBatchLength + textLength > batchLength && endIndex > 0)
) {
break;
}
currentBatchLength += textLength;
endIndex++;
}
if (endIndex > 0) {
tasksToProcess = queue.splice(0, endIndex);
}
if (tasksToProcess.length === 0) {
isProcessing = false;
return;
}
try {
const payloads = tasksToProcess.map((item) => item.payload);
const batchArgs = tasksToProcess[0].args;
const responses = await sendBatchRequest(payloads, batchArgs);
if (!Array.isArray(responses)) {
throw new Error("responses format error");
}
tasksToProcess.forEach((taskItem, index) => {
const response = responses[index];
if (response) {
taskItem.resolve(response);
} else {
taskItem.reject(new Error(`No response for item at index ${index}`));
}
});
} catch (error) {
tasksToProcess.forEach((taskItem) => taskItem.reject(error));
} finally {
isProcessing = false;
if (queue.length > 0) {
if (queue.length >= batchSize) {
setTimeout(processQueue, 0);
} else {
scheduleProcessing();
}
}
}
};
const scheduleProcessing = () => {
if (!isProcessing && !timer && queue.length > 0) {
timer = setTimeout(processQueue, batchInterval);
}
};
const addTask = (data, args) => {
return new Promise((resolve, reject) => {
const payload = data;
queue.push({ payload, resolve, reject, args });
if (queue.length >= batchSize) {
processQueue();
} else {
scheduleProcessing();
}
});
};
const destroy = () => {
if (timer) {
clearTimeout(timer);
timer = null;
}
queue.forEach((task) =>
task.reject(new Error("Queue instance was destroyed."))
);
queue.length = 0;
};
return { addTask, destroy };
};
// 实例字典
const queueMap = new Map();
/**
* 获取批处理实例
*/
export const getBatchQueue = (key, taskFn, options) => {
if (queueMap.has(key)) {
return queueMap.get(key);
}
const queue = BatchQueue(taskFn, options);
queueMap.set(key, queue);
return queue;
};
/**
* 清除所有任务
*/
export const clearAllBatchQueue = () => {
for (const queue of queueMap.values()) {
queue.destroy();
}
};

View File

@@ -8,10 +8,36 @@ function _browser() {
try { try {
return require("webextension-polyfill"); return require("webextension-polyfill");
} catch (err) { } catch (err) {
// kissLog(err, "browser"); // kissLog("browser", err);
} }
} }
export const browser = _browser(); export const browser = _browser();
export const isBg = () => globalThis?.ContextType === "BACKGROUND"; export const getContext = () => {
const context = globalThis.__KISS_CONTEXT__;
if (context) return context;
// if (typeof window === "undefined" || typeof document === "undefined") {
// return "background";
// }
// const extensionOrigin = browser.runtime.getURL("");
// if (!window.location.href.startsWith(extensionOrigin)) {
// return "content";
// }
// const pathname = window.location.pathname;
// if (pathname.includes("popup")) return "popup";
// if (pathname.includes("options")) return "options";
// if (pathname.includes("sidepanel")) return "sidepanel";
// if (pathname.includes("background")) return "background";
return "undefined";
};
export const isBg = () => getContext() === "background";
export const isOptions = () => getContext() === "options";
export const isBuiltinAIAvailable =
"LanguageDetector" in globalThis && "Translator" in globalThis;

168
src/libs/builtinAI.js Normal file
View File

@@ -0,0 +1,168 @@
import { kissLog, logger } from "./log";
/**
* Chrome 浏览器内置翻译
*/
class ChromeTranslator {
#translatorMap = new Map();
#detectorPromise = null;
constructor(options = {}) {
this.onProgress = options.onProgress || this.#defaultProgressHandler;
}
#defaultProgressHandler(type, progress) {
kissLog(`Downloading ${type} model: ${progress}%`);
}
#getDetectorPromise() {
if (!this.#detectorPromise) {
this.#detectorPromise = (async () => {
try {
const availability = await LanguageDetector.availability();
if (availability === "unavailable") {
throw new Error("LanguageDetector unavailable");
}
return await LanguageDetector.create({
monitor: (m) => this._monitorProgress(m, "detector"),
});
} catch (error) {
this.#detectorPromise = null;
throw error;
}
})();
}
return this.#detectorPromise;
}
#createTranslator(sourceLanguage, targetLanguage) {
const key = `${sourceLanguage}_${targetLanguage}`;
if (this.#translatorMap.has(key)) {
return this.#translatorMap.get(key);
}
const translatorPromise = (async () => {
try {
const avail = await Translator.availability({
sourceLanguage,
targetLanguage,
});
if (avail === "unavailable") {
throw new Error(
`Translator ${sourceLanguage}_${targetLanguage} unavailable`
);
}
const translator = await Translator.create({
sourceLanguage,
targetLanguage,
monitor: (m) => this._monitorProgress(m, `translator (${key})`),
});
this.#translatorMap.set(key, translator);
return translator;
} catch (error) {
this.#translatorMap.delete(key);
throw error;
}
})();
this.#translatorMap.set(key, translatorPromise);
return translatorPromise;
}
_monitorProgress(monitorable, type) {
monitorable.addEventListener("downloadprogress", (e) => {
const progress = e.total > 0 ? Math.round((e.loaded / e.total) * 100) : 0;
this.onProgress(type, progress);
});
}
async detectLanguage(text, confidenceThreshold = 0.4) {
if (!text) {
return ["", "Input text cannot be empty."];
}
try {
const detector = await this.#getDetectorPromise();
const results = await detector.detect(text);
if (!results || results.length === 0) {
return ["", "No language could be detected."];
}
const { detectedLanguage, confidence } = results[0];
if (confidence < confidenceThreshold) {
return [
"",
`Confidence of test results (${detectedLanguage} ${confidence.toFixed(
2
)}) below the set threshold ${confidenceThreshold}`,
];
}
return [detectedLanguage, ""];
} catch (error) {
kissLog("detectLanguage", error, `(${text})`);
return ["", error.message];
}
}
async translateText(text, targetLanguage, sourceLanguage = "auto") {
if (!text || !targetLanguage || typeof text !== "string") {
return ["", sourceLanguage, "Input text cannot be empty."];
}
try {
let finalSourceLanguage = sourceLanguage;
if (sourceLanguage === "auto") {
const [detectedLanguage, detectionError] =
await this.detectLanguage(text);
if (detectionError || !detectedLanguage) {
const reason =
detectionError || "Unable to determine source language.";
return [
"",
finalSourceLanguage,
`Automatic detection of source language failed: ${reason}`,
];
}
finalSourceLanguage = detectedLanguage;
}
if (finalSourceLanguage === targetLanguage) {
return ["", finalSourceLanguage, "Same lang"];
}
const translator = await this.#createTranslator(
finalSourceLanguage,
targetLanguage
);
const translatedText = await translator.translate(text);
return [translatedText, finalSourceLanguage, ""];
} catch (error) {
kissLog("translateText", error, `(${text})`);
if (
error &&
error.message &&
error.message.includes("Other generic failures occurred")
) {
logger.info("Generic failure detected, resetting translator cache.");
this.#translatorMap.clear();
}
return ["", sourceLanguage, error.message];
}
}
}
const chromeTranslator = new ChromeTranslator();
export const chromeDetect = (args) =>
chromeTranslator.detectLanguage(args.text);
export const chromeTranslate = (args) =>
chromeTranslator.translateText(args.text, args.to, args.from);

183
src/libs/cache.js Normal file
View File

@@ -0,0 +1,183 @@
import {
CACHE_NAME,
DEFAULT_CACHE_TIMEOUT,
MSG_CLEAR_CACHES,
MSG_GET_HTTPCACHE,
MSG_PUT_HTTPCACHE,
} from "../config";
import { kissLog } from "./log";
import { isExt } from "./client";
import { isBg } from "./browser";
import { sendBgMsg } from "./msg";
import { blobToBase64 } from "./utils";
/**
* 清除缓存数据
*/
export const tryClearCaches = async () => {
try {
if (isExt && !isBg()) {
await sendBgMsg(MSG_CLEAR_CACHES);
} else {
await caches.delete(CACHE_NAME);
}
} catch (err) {
kissLog("clean caches", err);
}
};
/**
* 构造缓存 request
* @param {*} input
* @param {*} init
* @returns
*/
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;
};
/**
* 查询 caches
* @param {*} input
* @param {*} init
* @returns
*/
export const getHttpCache = async ({ input, init, expect }) => {
try {
const request = await newCacheReq(input, init);
const cache = await caches.open(CACHE_NAME);
const response = await cache.match(request);
if (response) {
const res = await parseResponse(response, expect);
return res;
}
} catch (err) {
kissLog("get cache", err);
}
return null;
};
/**
* 插入 caches
* @param {*} input
* @param {*} init
* @param {*} data
*/
export const putHttpCache = async ({
input,
init,
data,
maxAge = DEFAULT_CACHE_TIMEOUT, // todo: 从设置里面读取最大缓存时间
}) => {
try {
const req = await newCacheReq(input, init);
const cache = await caches.open(CACHE_NAME);
const res = new Response(JSON.stringify(data), {
status: 200,
headers: {
"Content-Type": "application/json",
"Cache-Control": `max-age=${maxAge}`,
},
});
// res.headers.set("Cache-Control", `max-age=${maxAge}`);
await cache.put(req, res);
} catch (err) {
kissLog("put cache", err);
}
};
/**
* 解析 response
* @param {*} res
* @returns
*/
export const parseResponse = async (res, expect = null) => {
if (!res) {
throw new Error("Response object does not exist");
}
if (!res.ok) {
const msg = {
url: res.url,
status: res.status,
statusText: res.statusText,
};
try {
const errorText = await res.clone().text();
try {
msg.response = JSON.parse(errorText);
} catch {
msg.response = errorText;
}
} catch (e) {
msg.response = "Unable to read error body";
}
throw new Error(JSON.stringify(msg));
}
const contentType = res.headers.get("Content-Type") || "";
if (expect === "blob") return res.blob();
if (expect === "text") return res.text();
if (expect === "json") return res.json();
if (
expect === "audio" ||
contentType.includes("audio") ||
contentType.includes("image") ||
contentType.includes("video")
) {
const blob = await res.blob();
return blobToBase64(blob);
}
const text = await res.text();
if (!text) return null;
try {
return JSON.parse(text);
} catch (err) {
return text;
}
};
/**
* getHttpCache 兼容性封装
* @param {*} input
* @param {*} init
* @returns
*/
export const getHttpCachePolyfill = (input, init) => {
// 插件
if (isExt && !isBg()) {
return sendBgMsg(MSG_GET_HTTPCACHE, { input, init });
}
// 油猴/网页/BackgroundPage
return getHttpCache({ input, init });
};
/**
* putHttpCache 兼容性封装
* @param {*} input
* @param {*} init
* @param {*} data
* @returns
*/
export const putHttpCachePolyfill = (input, init, data) => {
// 插件
if (isExt && !isBg()) {
return sendBgMsg(MSG_PUT_HTTPCACHE, { input, init, data });
}
// 油猴/网页/BackgroundPage
return putHttpCache({ input, init, data });
};

View File

@@ -1,6 +1,12 @@
import { CLIENT_EXTS, CLIENT_USERSCRIPT, CLIENT_WEB } from "../config"; import {
CLIENT_EXTS,
CLIENT_USERSCRIPT,
CLIENT_WEB,
CLIENT_FIREFOX,
} from "../config";
export const client = process.env.REACT_APP_CLIENT; export const client = process.env.REACT_APP_CLIENT;
export const isExt = CLIENT_EXTS.includes(client); export const isExt = CLIENT_EXTS.includes(client);
export const isGm = client === CLIENT_USERSCRIPT; export const isGm = client === CLIENT_USERSCRIPT;
export const isWeb = client === CLIENT_WEB; export const isWeb = client === CLIENT_WEB;
export const isFirefox = client === CLIENT_FIREFOX;

65
src/libs/detect.js Normal file
View File

@@ -0,0 +1,65 @@
import {
OPT_TRANS_GOOGLE,
OPT_TRANS_MICROSOFT,
OPT_TRANS_BAIDU,
OPT_TRANS_TENCENT,
OPT_LANGS_TO_CODE,
OPT_LANGS_MAP,
OPT_TRANS_BUILTINAI,
OPT_LANGDETECTOR_MAP,
} from "../config";
import { browser } from "./browser";
import {
apiGoogleLangdetect,
apiMicrosoftLangdetect,
apiBaiduLangdetect,
apiTencentLangdetect,
apiBuiltinAIDetect,
} from "../apis";
import { kissLog } from "./log";
const langdetectFns = {
[OPT_TRANS_GOOGLE]: apiGoogleLangdetect,
[OPT_TRANS_MICROSOFT]: apiMicrosoftLangdetect,
[OPT_TRANS_BAIDU]: apiBaiduLangdetect,
[OPT_TRANS_TENCENT]: apiTencentLangdetect,
[OPT_TRANS_BUILTINAI]: apiBuiltinAIDetect,
};
/**
* 语言识别
* @param {*} text
* @returns
*/
export const tryDetectLang = async (text, langDetector = "-") => {
let deLang = "";
// 内置AI/远程识别
if (OPT_LANGDETECTOR_MAP.has(langDetector)) {
try {
const lang = await langdetectFns[langDetector](text);
if (lang) {
deLang = OPT_LANGS_TO_CODE[langDetector].get(lang) || "";
}
} catch (err) {
kissLog("detect lang remote", err);
}
}
// 本地识别
if (!deLang) {
try {
const res = await browser?.i18n?.detectLanguage(text);
const lang = res?.languages?.[0]?.language;
if (lang && OPT_LANGS_MAP.has(lang)) {
deLang = lang;
} else if (lang?.startsWith("zh")) {
deLang = "zh-CN";
}
} catch (err) {
kissLog("detect lang local", err);
}
}
return deLang;
};

18
src/libs/fabManager.js Normal file
View File

@@ -0,0 +1,18 @@
import ShadowDomManager from "./shadowDomManager";
import { APP_CONSTS } from "../config";
import ContentFab from "../views/Action/ContentFab";
export class FabManager extends ShadowDomManager {
constructor({ processActions, fabConfig }) {
super({
id: APP_CONSTS.fabID,
className: "notranslate",
reactComponent: ContentFab,
props: { processActions, fabConfig },
});
if (!fabConfig?.isHide) {
this.show();
}
}
}

View File

@@ -1,37 +1,11 @@
import { isExt, isGm } from "./client"; import { isExt, isGm } from "./client";
import { sendBgMsg } from "./msg"; import { sendBgMsg } from "./msg";
import { taskPool } from "./pool"; import { getSettingWithDefault } from "./storage";
import { import { MSG_FETCH, DEFAULT_HTTP_TIMEOUT } from "../config";
MSG_FETCH,
MSG_GET_HTTPCACHE,
CACHE_NAME,
DEFAULT_FETCH_INTERVAL,
DEFAULT_FETCH_LIMIT,
} from "../config";
import { isBg } from "./browser"; import { isBg } from "./browser";
import { genTransReq } from "../apis/trans";
import { kissLog } from "./log"; import { kissLog } from "./log";
import { blobToBase64 } from "./utils"; import { getFetchPool } from "./pool";
import { getHttpCachePolyfill, parseResponse } from "./cache";
const TIMEOUT = 5000;
/**
* 构造缓存 request
* @param {*} input
* @param {*} init
* @returns
*/
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;
};
/** /**
* 油猴脚本的请求封装 * 油猴脚本的请求封装
@@ -39,7 +13,10 @@ const newCacheReq = async (input, init) => {
* @param {*} init * @param {*} init
* @returns * @returns
*/ */
export const fetchGM = async (input, { method = "GET", headers, body } = {}) => export const fetchGM = async (
input,
{ method = "GET", headers, body, timeout } = {}
) =>
new Promise((resolve, reject) => { new Promise((resolve, reject) => {
GM.xmlHttpRequest({ GM.xmlHttpRequest({
method, method,
@@ -47,7 +24,7 @@ export const fetchGM = async (input, { method = "GET", headers, body } = {}) =>
headers, headers,
data: body, data: body,
// withCredentials: true, // withCredentials: true,
timeout: TIMEOUT, timeout,
onload: ({ response, responseHeaders, status, statusText }) => { onload: ({ response, responseHeaders, status, statusText }) => {
const headers = {}; const headers = {};
responseHeaders.split("\n").forEach((line) => { responseHeaders.split("\n").forEach((line) => {
@@ -64,144 +41,65 @@ export const fetchGM = async (input, { method = "GET", headers, body } = {}) =>
}); });
}, },
onerror: reject, onerror: reject,
onabort: () => {
reject(new Error("GM request onabort."));
},
ontimeout: () => {
reject(new Error("GM request timeout."));
},
}); });
}); });
/** /**
* 发起请求 * 发起请求
* @param {*} param0 * @param {*} input
* @param {*} init
* @param {*} opts
* @returns * @returns
*/ */
export const fetchPatcher = async (input, init, transOpts, apiSetting) => { export const fetchPatcher = async (input, init = {}, opts) => {
if (transOpts?.translator) { let timeout = opts?.httpTimeout;
[input, init] = await genTransReq(transOpts, apiSetting); if (!timeout) {
try {
timeout = (await getSettingWithDefault()).httpTimeout;
} catch (err) {
kissLog("getSettingWithDefault", err);
}
} }
if (!timeout) {
if (!input) { timeout = DEFAULT_HTTP_TIMEOUT;
throw new Error("url is empty");
} }
if (isGm) { if (isGm) {
let info; // todo: 自定义接口 init 可能包含了 signal
if (window.KISS_GM) { Object.assign(init, { timeout });
info = await window.KISS_GM.getInfo();
} else {
info = GM.info;
}
// Tampermonkey --> .connects const { body, headers, status, statusText } = window.KISS_GM
// Violentmonkey --> .connect ? await window.KISS_GM.fetch(input, init)
const connects = info?.script?.connects || info?.script?.connect || []; : await fetchGM(input, init);
const url = new URL(input);
const isSafe = connects.find((item) => url.hostname.endsWith(item));
if (isSafe) { return new Response(body, {
const { body, headers, status, statusText } = window.KISS_GM headers: new Headers(headers),
? await window.KISS_GM.fetch(input, init) status,
: await fetchGM(input, init); statusText,
});
return new Response(body, {
headers: new Headers(headers),
status,
statusText,
});
}
} }
if (AbortSignal?.timeout) { if (AbortSignal?.timeout && !init.signal) {
Object.assign(init, { signal: AbortSignal.timeout(TIMEOUT) }); Object.assign(init, { signal: AbortSignal.timeout(timeout) });
} }
return fetch(input, init); return fetch(input, init);
}; };
/**
* 解析 response
* @param {*} res
* @returns
*/
const parseResponse = async (res) => {
if (!res) {
return null;
}
const contentType = res.headers.get("Content-Type");
if (contentType?.includes("json")) {
return await res.json();
} else if (contentType?.includes("audio")) {
const blob = await res.blob();
return await blobToBase64(blob);
}
return await res.text();
};
/**
* 查询 caches
* @param {*} input
* @param {*} param1
* @returns
*/
export const getHttpCache = async (input, { method, headers, body }) => {
try {
const req = await newCacheReq(input, { method, headers, body });
const cache = await caches.open(CACHE_NAME);
const res = await cache.match(req);
return parseResponse(res);
} catch (err) {
kissLog(err, "get cache");
}
return null;
};
/**
* 插入 caches
* @param {*} input
* @param {*} param1
* @param {*} res
*/
export const putHttpCache = async (input, { method, headers, body }, res) => {
try {
const req = await newCacheReq(input, { method, headers, body });
const cache = await caches.open(CACHE_NAME);
await cache.put(req, res);
} catch (err) {
kissLog(err, "put cache");
}
};
/** /**
* 处理请求 * 处理请求
* @param {*} param0 * @param {*} param0
* @returns * @returns
*/ */
export const fetchHandle = async ({ export const fetchHandle = async ({ input, init, opts }) => {
input, const res = await fetchPatcher(input, init, opts);
useCache, return parseResponse(res, opts.expect);
transOpts,
apiSetting,
...init
}) => {
// 发送请求
const res = await fetchPatcher(input, init, transOpts, apiSetting);
if (!res) {
throw new Error("Unknow error");
} else if (!res.ok) {
const msg = {
url: res.url,
status: res.status,
};
if (res.headers.get("Content-Type")?.includes("json")) {
msg.response = await res.json();
}
throw new Error(JSON.stringify(msg));
}
// 插入缓存
if (useCache) {
await putHttpCache(input, init, res.clone());
}
return parseResponse(res);
}; };
/** /**
@@ -209,82 +107,46 @@ export const fetchHandle = async ({
* @param {*} args * @param {*} args
* @returns * @returns
*/ */
export const fetchPolyfill = (args) => { export const fnPolyfill = ({ fn, msg = MSG_FETCH, ...args }) => {
// 插件 // 插件
if (isExt && !isBg()) { if (isExt && !isBg()) {
return sendBgMsg(MSG_FETCH, args); return sendBgMsg(msg, { ...args });
} }
// 油猴/网页/BackgroundPage // 油猴/网页/BackgroundPage
return fetchHandle(args); return fn({ ...args });
}; };
/**
* getHttpCache 兼容性封装
* @param {*} input
* @param {*} init
* @returns
*/
export const getHttpCachePolyfill = (input, init) => {
// 插件
if (isExt && !isBg()) {
return sendBgMsg(MSG_GET_HTTPCACHE, { input, init });
}
// 油猴/网页/BackgroundPage
return getHttpCache(input, init);
};
/**
* 请求池实例
*/
export const fetchPool = taskPool(
fetchPolyfill,
null,
DEFAULT_FETCH_INTERVAL,
DEFAULT_FETCH_LIMIT
);
/** /**
* 数据请求 * 数据请求
* @param {*} input * @param {*} input
* @param {*} init
* @param {*} param1 * @param {*} param1
* @returns * @returns
*/ */
export const fetchData = async (input, { useCache, usePool, ...args } = {}) => { export const fetchData = async (
input,
init,
{ useCache, usePool, fetchInterval, fetchLimit, ...opts } = {}
) => {
if (!input?.trim()) { if (!input?.trim()) {
throw new Error("URL is empty"); throw new Error("URL is empty");
} }
// 查询缓存 // 使用缓存数据
if (useCache) { if (useCache) {
const cache = await getHttpCachePolyfill(input, args); const resCache = await getHttpCachePolyfill(input, init);
if (cache) { if (resCache) {
return cache; return resCache;
} }
} }
// 通过任务池发送请求 // 通过任务池发送请求
if (usePool) { if (usePool) {
return fetchPool.push({ input, useCache, ...args }); const fetchPool = getFetchPool(fetchInterval, fetchLimit);
return fetchPool.push(fnPolyfill, { fn: fetchHandle, input, init, opts });
} }
// 直接请求 // 直接请求
return fetchPolyfill({ input, useCache, ...args }); return fnPolyfill({ fn: fetchHandle, input, init, opts });
};
/**
* 更新 fetch pool 参数
* @param {*} interval
* @param {*} limit
*/
export const updateFetchPool = (interval, limit) => {
fetchPool.update(interval, limit);
};
/**
* 清空任务池
*/
export const clearFetchPool = () => {
fetchPool.clear();
}; };

View File

@@ -1,43 +0,0 @@
import { CACHE_NAME } from "../config";
import { browser } from "./browser";
import { apiBaiduLangdetect } from "../apis";
import { kissLog } from "./log";
/**
* 清除缓存数据
*/
export const tryClearCaches = async () => {
try {
caches.delete(CACHE_NAME);
} catch (err) {
kissLog(err, "clean caches");
}
};
/**
* 语言识别
* @param {*} q
* @returns
*/
export const tryDetectLang = async (q, useRemote = false) => {
let lang = "";
if (useRemote) {
try {
lang = await apiBaiduLangdetect(q);
} catch (err) {
kissLog(err, "detect lang remote");
}
}
if (!lang) {
try {
const res = await browser?.i18n?.detectLanguage(q);
lang = res?.languages?.[0]?.language;
} catch (err) {
kissLog(err, "detect lang local");
}
}
return lang;
};

View File

@@ -1,25 +1,50 @@
import { trustedTypesHelper } from "./trustedTypes";
// Function to inject inline JavaScript code // Function to inject inline JavaScript code
export const injectInlineJs = (code) => { export const injectInlineJs = (code, id = "kiss-translator-inline-js") => {
if (document.getElementById(id)) {
return;
}
const el = document.createElement("script"); const el = document.createElement("script");
el.setAttribute("data-source", "KISS-Calendar injectInlineJs"); el.setAttribute("data-source", "kiss-inject injectInlineJs");
el.setAttribute("type", "text/javascript"); el.type = "text/javascript";
el.id = id;
el.textContent = trustedTypesHelper.createScript(code);
(document.head || document.documentElement).appendChild(el);
};
export const injectInlineJsBg = (code, id = "kiss-translator-inline-js") => {
if (document.getElementById(id)) {
return;
}
const el = document.createElement("script");
el.setAttribute("data-source", "kiss-inject injectInlineJsBg");
el.type = "text/javascript";
el.id = id;
el.textContent = code; el.textContent = code;
document.body?.appendChild(el); (document.head || document.documentElement).appendChild(el);
}; };
// Function to inject external JavaScript file // Function to inject external JavaScript file
export const injectExternalJs = (src) => { export const injectExternalJs = (src, id = "kiss-translator-external-js") => {
if (document.getElementById(id)) {
return;
}
const el = document.createElement("script"); const el = document.createElement("script");
el.setAttribute("data-source", "KISS-Calendar injectExternalJs"); el.setAttribute("data-source", "kiss-inject injectExternalJs");
el.setAttribute("type", "text/javascript"); el.type = "text/javascript";
el.setAttribute("src", src); el.id = id;
document.body?.appendChild(el); el.src = trustedTypesHelper.createScriptURL(src);
(document.head || document.documentElement).appendChild(el);
}; };
// Function to inject internal CSS code // Function to inject internal CSS code
export const injectInternalCss = (styles) => { export const injectInternalCss = (styles) => {
const el = document.createElement("style"); const el = document.createElement("style");
el.setAttribute("data-source", "KISS-Calendar injectInternalCss"); el.setAttribute("data-source", "kiss-inject injectInternalCss");
el.textContent = styles; el.textContent = styles;
document.head?.appendChild(el); document.head?.appendChild(el);
}; };
@@ -27,7 +52,7 @@ export const injectInternalCss = (styles) => {
// Function to inject external CSS file // Function to inject external CSS file
export const injectExternalCss = (href) => { export const injectExternalCss = (href) => {
const el = document.createElement("link"); const el = document.createElement("link");
el.setAttribute("data-source", "KISS-Calendar injectExternalCss"); el.setAttribute("data-source", "kiss-inject injectExternalCss");
el.setAttribute("rel", "stylesheet"); el.setAttribute("rel", "stylesheet");
el.setAttribute("type", "text/css"); el.setAttribute("type", "text/css");
el.setAttribute("href", href); el.setAttribute("href", href);

View File

@@ -1,52 +1,114 @@
import { import {
DEFAULT_INPUT_RULE, DEFAULT_INPUT_RULE,
DEFAULT_TRANS_APIS,
DEFAULT_INPUT_SHORTCUT, DEFAULT_INPUT_SHORTCUT,
OPT_LANGS_LIST, OPT_LANGS_LIST,
DEFAULT_API_SETTING,
} from "../config"; } from "../config";
import { genEventName, removeEndchar, matchInputStr, sleep } from "./utils"; import { genEventName, removeEndchar, matchInputStr, sleep } from "./utils";
import { stepShortcutRegister } from "./shortcut"; import { stepShortcutRegister } from "./shortcut";
import { apiTranslate } from "../apis"; import { apiTranslate } from "../apis";
import { loadingSvg } from "./svg"; import { createLoadingSVG } from "./svg";
import { kissLog } from "./log"; import { logger } from "./log";
function isInputNode(node) { function isInputNode(node) {
return node.nodeName === "INPUT" || node.nodeName === "TEXTAREA"; return (
node.nodeName?.toUpperCase() === "INPUT" ||
node.nodeName?.toUpperCase() === "TEXTAREA"
);
} }
function isEditAbleNode(node) { function isEditAbleNode(node) {
return node.hasAttribute("contenteditable"); return node.hasAttribute("contenteditable");
} }
function selectContent(node) { async function replaceContentEditableText(node, newText) {
node.focus(); try {
const range = document.createRange(); logger.debug("try replace editable 1: pasteEvent");
range.selectNodeContents(node);
const selection = window.getSelection(); node.focus();
selection.removeAllRanges();
selection.addRange(range);
}
function pasteContentEvent(node, text) { const selection = window.getSelection();
node.focus(); if (!selection) throw new Error("window.getSelection() is not available.");
const data = new DataTransfer();
data.setData("text/plain", text);
const event = new ClipboardEvent("paste", { clipboardData: data }); const targetNode = node.querySelector("p") || node;
document.dispatchEvent(event); const range = document.createRange();
data.clearData(); range.selectNodeContents(targetNode);
} selection.removeAllRanges();
selection.addRange(range);
function pasteContentCommand(node, text) { const dataTransfer = new DataTransfer();
node.focus(); dataTransfer.setData("text/plain", newText);
document.execCommand("insertText", false, text);
}
function collapseToEnd(node) { const pasteEvent = new ClipboardEvent("paste", {
node.focus(); clipboardData: dataTransfer,
const selection = window.getSelection(); bubbles: true,
selection.collapseToEnd(); cancelable: true,
});
node.dispatchEvent(pasteEvent);
await sleep(50);
if (node.innerText.trim() === newText) {
return true;
}
throw new Error("Strategy 1 failed to replace text correctly.");
} catch (error) {
logger.debug("Strategy 1 Failed:", error.message);
}
try {
logger.debug("try replace editable 2: execCommand");
node.focus();
const selection = window.getSelection();
if (!selection) throw new Error("window.getSelection() is not available.");
const targetNode = node.querySelector("p") || node;
const range = document.createRange();
range.selectNodeContents(targetNode);
selection.removeAllRanges();
selection.addRange(range);
document.execCommand("insertText", false, newText);
await sleep(50);
if (node.innerText.trim() === newText) {
return true;
}
throw new Error("Strategy 2 failed to replace text correctly.");
} catch (error) {
logger.debug("Strategy 2 Failed:", error.message);
}
try {
logger.debug("try replace editable 3: textContent");
node.focus();
const targetNode = node.querySelector("p") || node;
const textSpan = targetNode.querySelector('span[data-lexical-text="true"]');
if (textSpan) {
textSpan.textContent = newText;
} else {
targetNode.textContent = newText;
}
node.dispatchEvent(new Event("input", { bubbles: true, cancelable: true }));
await sleep(50);
if (node.innerText.trim() === newText) {
return true;
}
throw new Error("Strategy 3 failed to replace text correctly.");
} catch (error) {
logger.debug("Strategy 3 Failed:", error.message);
}
return false;
} }
function getNodeText(node) { function getNodeText(node) {
@@ -57,143 +119,209 @@ function getNodeText(node) {
} }
function addLoading(node, loadingId) { function addLoading(node, loadingId) {
const rect = node.getBoundingClientRect();
const div = document.createElement("div"); const div = document.createElement("div");
div.id = loadingId; div.id = loadingId;
div.innerHTML = loadingSvg; div.appendChild(createLoadingSVG());
div.style.cssText = ` div.style.cssText = `
width: ${node.offsetWidth}px; position: fixed;
height: ${node.offsetHeight}px; left: ${rect.left}px;
line-height: ${node.offsetHeight}px; top: ${rect.top}px;
position: absolute; width: ${rect.width}px;
text-align: center; height: ${rect.height}px;
left: ${node.offsetLeft}px; line-height: ${rect.height}px;
top: ${node.offsetTop}px; text-align: center;
z-index: 2147483647; z-index: 2147483647;
pointer-events: none; /* 允许点击穿透 */
`; `;
node.offsetParent?.appendChild(div); document.body.appendChild(div);
} }
function removeLoading(node, loadingId) { function removeLoading(loadingId) {
const div = node.offsetParent.querySelector(`#${loadingId}`); const div = document.getElementById(loadingId);
if (div) { if (div) div.remove();
div.remove();
}
} }
/** /**
* 输入框翻译 * 输入框翻译
*/ */
export default function inputTranslate({ export class InputTranslator {
inputRule: { #config;
transOpen, #unregisterShortcut = null;
triggerShortcut, #isEnabled = false;
translator, #triggerShortcut; // 用于缓存快捷键
fromLang,
toLang, constructor({ inputRule = DEFAULT_INPUT_RULE, transApis = [] } = {}) {
triggerCount, this.#config = { inputRule, transApis };
triggerTime,
transSign, const { triggerShortcut: initialTriggerShortcut } = this.#config.inputRule;
} = DEFAULT_INPUT_RULE, if (initialTriggerShortcut && initialTriggerShortcut.length > 0) {
transApis, this.#triggerShortcut = initialTriggerShortcut;
}) { } else {
if (!transOpen) { this.#triggerShortcut = DEFAULT_INPUT_SHORTCUT;
return; }
if (this.#config.inputRule.transOpen) {
this.enable();
}
} }
const apiSetting = transApis?.[translator] || DEFAULT_TRANS_APIS[translator]; /**
if (triggerShortcut.length === 0) { * 启用输入翻译功能
triggerShortcut = DEFAULT_INPUT_SHORTCUT; */
triggerCount = 1; enable() {
if (this.#isEnabled || !this.#config.inputRule.transOpen) {
return;
}
const { triggerCount, triggerTime } = this.#config.inputRule;
this.#unregisterShortcut = stepShortcutRegister(
this.#triggerShortcut,
this.#handleTranslate.bind(this),
triggerCount,
triggerTime
);
this.#isEnabled = true;
logger.info("Input Translator enabled.");
} }
stepShortcutRegister( /**
triggerShortcut, * 禁用输入翻译功能
async () => { */
let node = document.activeElement; disable() {
if (!this.#isEnabled) {
return;
}
if (this.#unregisterShortcut) {
this.#unregisterShortcut();
this.#unregisterShortcut = null;
}
this.#isEnabled = false;
logger.info("Input Translator disabled.");
}
if (!node) { /**
return; * 切换启用/禁用状态
} */
toggle() {
if (this.#isEnabled) {
this.disable();
} else {
this.enable();
}
}
while (node.shadowRoot) { /**
node = node.shadowRoot.activeElement; * 翻译核心逻辑
} * @private
*/
async #handleTranslate() {
let node = document.activeElement;
if (!node) return;
if (!isInputNode(node) && !isEditAbleNode(node)) { while (node.shadowRoot && node.shadowRoot.activeElement) {
return; node = node.shadowRoot.activeElement;
} }
let initText = getNodeText(node); if (!isInputNode(node) && !isEditAbleNode(node)) {
if (triggerShortcut.length === 1 && triggerShortcut[0].length === 1) { return;
// todo: remove multiple char }
initText = removeEndchar(initText, triggerShortcut[0], triggerCount);
}
if (!initText.trim()) {
return;
}
let text = initText; const { apiSlug, transSign, triggerCount } = this.#config.inputRule;
if (transSign) { let { fromLang, toLang } = this.#config.inputRule;
const res = matchInputStr(text, transSign);
if (res) { let initText = getNodeText(node);
let lang = res[1];
if (lang === "zh" || lang === "cn") { if (
lang = "zh-CN"; this.#triggerShortcut.length === 1 &&
} else if (lang === "tw" || lang === "hk") { this.#triggerShortcut[0].length === 1
lang = "zh-TW"; ) {
} initText = removeEndchar(
if (lang && OPT_LANGS_LIST.includes(lang)) { initText,
toLang = lang; this.#triggerShortcut[0],
} triggerCount
text = res[2]; );
}
if (!initText.trim()) return;
let text = initText;
if (transSign) {
const res = matchInputStr(text, transSign);
if (res) {
let lang = res[1];
if (lang === "zh" || lang === "cn") lang = "zh-CN";
else if (lang === "tw" || lang === "hk") lang = "zh-TW";
if (lang && OPT_LANGS_LIST.includes(lang)) {
toLang = lang;
}
text = res[2];
}
}
const apiSetting =
this.#config.transApis.find((api) => api.apiSlug === apiSlug) ||
DEFAULT_API_SETTING;
const loadingId = "kiss-loading-" + genEventName();
try {
addLoading(node, loadingId);
const { trText, isSame } = await apiTranslate({
text,
fromLang,
toLang,
apiSetting,
});
const newText = trText?.trim() || "";
if (!newText || isSame) return;
if (isInputNode(node)) {
node.value = newText;
node.dispatchEvent(
new Event("input", { bubbles: true, cancelable: true })
);
} else {
const success = await replaceContentEditableText(node, newText);
if (!success) {
// todo: 提示可以黏贴
logger.info("Replace editable text failed");
} }
} }
} catch (err) {
logger.info("Translate input error:", err);
} finally {
removeLoading(loadingId);
}
}
// console.log("input -->", text); /**
* 更新配置
*/
updateConfig({ inputRule, transApis }) {
const wasEnabled = this.#isEnabled;
if (wasEnabled) {
this.disable();
}
const loadingId = "kiss-" + genEventName(); if (inputRule) {
try { this.#config.inputRule = inputRule;
addLoading(node, loadingId); }
if (transApis) {
this.#config.transApis = transApis;
}
const [trText, isSame] = await apiTranslate({ const { triggerShortcut: initialTriggerShortcut } = this.#config.inputRule;
translator, this.#triggerShortcut =
text, initialTriggerShortcut && initialTriggerShortcut.length > 0
fromLang, ? initialTriggerShortcut
toLang, : DEFAULT_INPUT_SHORTCUT;
apiSetting,
});
if (!trText || isSame) {
return;
}
if (isInputNode(node)) { if (wasEnabled) {
node.value = trText; this.enable();
node.dispatchEvent( }
new Event("input", { bubbles: true, cancelable: true }) }
);
return;
}
selectContent(node);
await sleep(200);
pasteContentEvent(node, trText);
await sleep(200);
// todo: use includes?
if (getNodeText(node).startsWith(initText)) {
pasteContentCommand(node, trText);
await sleep(100);
} else {
collapseToEnd(node);
}
} catch (err) {
kissLog(err, "translate input");
} finally {
removeLoading(node, loadingId);
}
},
triggerCount,
triggerTime
);
} }

View File

@@ -1,6 +1,6 @@
import Sval from "sval"; import Sval from "sval";
const interpreter = new Sval({ export const interpreter = new Sval({
// ECMA Version of the code // ECMA Version of the code
// 3 | 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 | 14 | 15 // 3 | 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 | 14 | 15
// or 2015 | 2016 | 2017 | 2018 | 2019 | 2020 | 2021 | 2022 | 2023 | 2024 // or 2015 | 2016 | 2017 | 2018 | 2019 | 2020 | 2021 | 2022 | 2023 | 2024
@@ -12,5 +12,3 @@ const interpreter = new Sval({
// Whether the code runs in a sandbox // Whether the code runs in a sandbox
sandBox: true, sandBox: true,
}); });
export default interpreter;

View File

@@ -1,12 +1,163 @@
/** // 定义日志级别
* 日志函数 export const LogLevel = {
* @param {*} msg DEBUG: { value: 0, name: "DEBUG", color: "#6495ED" }, // 宝蓝色
* @param {*} type INFO: { value: 1, name: "INFO", color: "#4CAF50" }, // 绿色
*/ WARN: { value: 2, name: "WARN", color: "#FFC107" }, // 琥珀色
export const kissLog = (msg, type) => { ERROR: { value: 3, name: "ERROR", color: "#F44336" }, // 红色
let prefix = `[KISS-Translator]`; SILENT: { value: 4, name: "SILENT" }, // 特殊级别,用于关闭所有日志
if (type) {
prefix += `[${type}]`;
}
console.log(`${prefix} ${msg}`);
}; };
function findLogLevelByValue(value) {
return Object.values(LogLevel).find((level) => level.value === value);
}
function findLogLevelByName(name) {
if (typeof name !== "string" || name.length === 0) return undefined;
const upperCaseName = name.toUpperCase();
return Object.values(LogLevel).find((level) => level.name === upperCaseName);
}
class Logger {
/**
* @param {object} [options={}] 配置选项
* @param {LogLevel} [options.level=LogLevel.INFO] 要显示的最低日志级别
* @param {string} [options.prefix='App'] 日志前缀,用于区分模块
*/
constructor(options = {}) {
this.config = {
level: options.level || LogLevel.INFO,
prefix: options.prefix || "KISS-Translator",
};
}
/**
* 动态设置日志级别
* @param {LogLevel} level - 新的日志级别
*/
setLevel(level) {
let newLevelObject;
if (typeof level === "string") {
newLevelObject = findLogLevelByName(level);
if (!newLevelObject) {
this.warn(
`Invalid log level name provided: "${level}". Keeping current level.`
);
return;
}
} else if (typeof level === "number") {
newLevelObject = findLogLevelByValue(level);
if (!newLevelObject) {
this.warn(
`Invalid log level value provided: ${level}. Keeping current level.`
);
return;
}
} else if (level && typeof level.value === "number") {
newLevelObject = level;
} else {
this.warn(
"Invalid argument passed to setLevel. Must be a LogLevel object, number, or string."
);
return;
}
if (this.config.level.value !== newLevelObject.value) {
this.config.level = newLevelObject;
console.log(
`[${this.config.prefix}] Log level dynamically set to ${this.config.level.name}`
);
}
}
/**
* 核心日志记录方法
* @private
* @param {LogLevel} level - 当前消息的日志级别
* @param {...any} args - 要记录的多个参数,可以是任何类型
*/
_log(level, ...args) {
// 如果当前级别低于配置的最低级别,则不打印
if (level.value < this.config.level.value) {
return;
}
const timestamp = new Date().toISOString();
const prefixStr = `[${this.config.prefix}]`;
const levelStr = `[${level.name}]`;
// 判断是否在浏览器环境并且浏览器支持 console 样式
const isBrowser =
typeof window !== "undefined" && typeof window.document !== "undefined";
if (isBrowser) {
// 在浏览器中使用颜色高亮
const consoleMethod = this._getConsoleMethod(level);
consoleMethod(
`%c${timestamp} %c${prefixStr} %c${levelStr}`,
"color: gray; font-weight: lighter;", // 时间戳样式
"color: #7c57e0; font-weight: bold;", // 前缀样式 (紫色)
`color: ${level.color}; font-weight: bold;`, // 日志级别样式
...args
);
} else {
// 在 Node.js 或不支持样式的环境中,输出纯文本
const consoleMethod = this._getConsoleMethod(level);
consoleMethod(timestamp, prefixStr, levelStr, ...args);
}
}
/**
* 根据日志级别获取对应的 console 方法
* @private
*/
_getConsoleMethod(level) {
switch (level) {
case LogLevel.ERROR:
return console.error;
case LogLevel.WARN:
return console.warn;
case LogLevel.INFO:
return console.info;
default:
return console.log;
}
}
/**
* 记录 DEBUG 级别的日志
* @param {...any} args
*/
debug(...args) {
this._log(LogLevel.DEBUG, ...args);
}
/**
* 记录 INFO 级别的日志
* @param {...any} args
*/
info(...args) {
this._log(LogLevel.INFO, ...args);
}
/**
* 记录 WARN 级别的日志
* @param {...any} args
*/
warn(...args) {
this._log(LogLevel.WARN, ...args);
}
/**
* 记录 ERROR 级别的日志
* @param {...any} args
*/
error(...args) {
this._log(LogLevel.ERROR, ...args);
}
}
export const logger = new Logger();
export const kissLog = logger.info.bind(logger);
// tododebug日志埋点

View File

@@ -1,80 +1,170 @@
import { DEFAULT_FETCH_INTERVAL, DEFAULT_FETCH_LIMIT } from "../config";
import { kissLog } from "./log"; import { kissLog } from "./log";
/** /**
* 任务池 * 任务池
* @param {*} fn
* @param {*} preFn
* @param {*} _interval
* @param {*} _limit
* @returns
*/ */
export const taskPool = ( class TaskPool {
fn, #pool = [];
preFn,
_interval = 100,
_limit = 100,
_retryInteral = 1000
) => {
const pool = [];
const maxRetry = 2; // 最大重试次数
let maxCount = _limit; // 最大数量
let curCount = 0; // 当前数量
let interval = _interval; // 间隔时间
let timer = null;
const run = async () => { #maxRetry = 2; // 最大重试次数
// console.log("timer", timer); #retryInterval = 1000; // 重试间隔时间
timer && clearTimeout(timer); #limit; // 最大并发数
timer = setTimeout(run, interval); #interval; // 任务最小启动间隔
if (curCount < maxCount) { #currentConcurrent = 0; // 当前正在执行的任务数
const item = pool.shift(); #lastExecutionTime = 0; // 上一个任务的启动时间
if (item) { #schedulerTimer = null; // 用于调度下一个任务的定时器
curCount++;
const { args, resolve, reject, retry } = item; constructor(
try { interval = DEFAULT_FETCH_INTERVAL,
const preArgs = preFn ? await preFn(item.args) : {}; limit = DEFAULT_FETCH_LIMIT,
const res = await fn({ ...args, ...preArgs }); retryInterval = 1000
resolve(res); ) {
} catch (err) { this.#interval = interval;
kissLog(err, "task"); this.#limit = limit;
if (retry < maxRetry) { this.#retryInterval = retryInterval;
const retryTimer = setTimeout(() => { }
clearTimeout(retryTimer);
pool.push({ args, resolve, reject, retry: retry + 1 }); /**
}, _retryInteral); * 调度器
} else { */
reject(err); #scheduleNext() {
} if (this.#schedulerTimer) {
} finally { return;
curCount--; }
if (this.#currentConcurrent >= this.#limit || this.#pool.length === 0) {
return;
}
const now = Date.now();
const timeSinceLast = now - this.#lastExecutionTime;
const delay = Math.max(0, this.#interval - timeSinceLast);
this.#schedulerTimer = setTimeout(() => {
this.#schedulerTimer = null;
if (this.#currentConcurrent < this.#limit && this.#pool.length > 0) {
const task = this.#pool.shift();
if (task) {
this.#lastExecutionTime = Date.now();
this.#execute(task);
} }
} }
}
};
return { if (this.#pool.length > 0) {
push: async (args) => { this.#scheduleNext();
if (!timer) {
run();
} }
return new Promise((resolve, reject) => { }, delay);
pool.push({ args, resolve, reject, retry: 0 }); }
});
}, /**
update: (_interval = 100, _limit = 100) => { * 执行单个任务
if (_interval >= 0 && _interval <= 5000 && _interval !== interval) { * @param {object} task - 任务对象
interval = _interval; */
async #execute(task) {
this.#currentConcurrent++;
const { fn, args, resolve, reject, retry } = task;
try {
const res = await fn(args);
resolve(res);
} catch (err) {
kissLog("task pool", err);
if (retry < this.#maxRetry) {
setTimeout(() => {
this.#pool.unshift({ ...task, retry: retry + 1 }); // unshift 保证重试任务优先
this.#scheduleNext();
}, this.#retryInterval);
} else {
reject(err);
} }
if (_limit >= 1 && _limit <= 100 && _limit !== maxCount) { } finally {
maxCount = _limit; this.#currentConcurrent--;
} this.#scheduleNext();
}, }
clear: () => { }
pool.length = 0;
curCount = 0; /**
timer && clearTimeout(timer); * 向任务池中添加一个新任务
timer = null; * @param {Function} fn - 要执行的异步函数
}, * @param {*} args - 函数的参数
}; * @returns {Promise}
*/
push(fn, args) {
return new Promise((resolve, reject) => {
this.#pool.push({ fn, args, resolve, reject, retry: 0 });
this.#scheduleNext();
});
}
/**
* 更新任务池的配置
* @param {number} interval - 新的最小任务间隔
* @param {number} limit - 新的最大并发数
*/
update(interval, limit) {
if (interval >= 0) {
this.#interval = interval;
}
if (limit >= 1) {
this.#limit = limit;
}
this.#scheduleNext();
}
/**
* 清空任务池
*/
clear() {
for (const task of this.#pool) {
task.reject("the task pool was cleared");
}
this.#pool.length = 0;
if (this.#schedulerTimer) {
clearTimeout(this.#schedulerTimer);
this.#schedulerTimer = null;
}
}
}
/**
* 请求池实例
*/
let fetchPool;
/**
* 获取请求池实例
* @param interval
* @param limit
* @returns
*/
export const getFetchPool = (interval, limit) => {
if (!fetchPool) {
fetchPool = new TaskPool(
interval ?? DEFAULT_FETCH_INTERVAL,
limit ?? DEFAULT_FETCH_LIMIT
);
} else if (interval && limit) {
updateFetchPool(interval, limit);
}
return fetchPool;
};
/**
* 更新请求池参数
* @param {*} interval
* @param {*} limit
*/
export const updateFetchPool = (interval, limit) => {
fetchPool?.update(interval, limit);
};
/**
* 清空请求池
*/
export const clearFetchPool = () => {
fetchPool?.clear();
}; };

26
src/libs/popupManager.js Normal file
View File

@@ -0,0 +1,26 @@
import ShadowDomManager from "./shadowDomManager";
import { APP_CONSTS, EVENT_KISS, MSG_POPUP_TOGGLE } from "../config";
import Action from "../views/Action";
export class PopupManager extends ShadowDomManager {
constructor({ translator, processActions }) {
super({
id: APP_CONSTS.popupID,
className: "notranslate",
reactComponent: Action,
props: { translator, processActions },
});
}
toggle(props) {
if (this.isVisible) {
document.dispatchEvent(
new CustomEvent(EVENT_KISS, {
detail: { action: MSG_POPUP_TOGGLE },
})
);
} else {
this.show(props || this._props);
}
}
}

View File

@@ -1,18 +1,16 @@
import { matchValue, type, isMatch } from "./utils"; import { matchValue, type, isMatch } from "./utils";
import { import {
GLOBAL_KEY, GLOBAL_KEY,
REMAIN_KEY,
OPT_TRANS_ALL,
OPT_STYLE_ALL,
OPT_LANGS_FROM, OPT_LANGS_FROM,
OPT_LANGS_TO, OPT_LANGS_TO,
OPT_TIMING_ALL, DEFAULT_RULE,
GLOBLA_RULE, GLOBLA_RULE,
OPT_SPLIT_PARAGRAPH_ALL,
OPT_HIGHLIGHT_WORDS_ALL,
} from "../config"; } from "../config";
import { loadOrFetchSubRules } from "./subRules"; import { loadOrFetchSubRules } from "./subRules";
import { getRulesWithDefault, setRules } from "./storage"; import { getRulesWithDefault, setRules } from "./storage";
import { trySyncRules } from "./sync"; import { trySyncRules } from "./sync";
import { FIXER_ALL } from "./webfix";
import { kissLog } from "./log"; import { kissLog } from "./log";
/** /**
@@ -21,41 +19,22 @@ import { kissLog } from "./log";
* @param {string} href * @param {string} href
* @returns * @returns
*/ */
export const matchRule = async ( export const matchRule = async (href, { injectRules, subrulesList }) => {
href,
{ injectRules, subrulesList, owSubrule }
) => {
const rules = await getRulesWithDefault(); const rules = await getRulesWithDefault();
if (injectRules) { if (injectRules) {
try { try {
const selectedSub = subrulesList.find((item) => item.selected); const selectedSub = subrulesList.find((item) => item.selected);
if (selectedSub?.url) { if (selectedSub?.url) {
const mixRule = {}; const subRules = await loadOrFetchSubRules(selectedSub.url);
Object.entries(owSubrule)
.filter(([key, val]) => {
if (
owSubrule.textStyle === REMAIN_KEY &&
(key === "bgColor" || key === "textDiyStyle")
) {
return false;
}
return val !== REMAIN_KEY;
})
.forEach(([key, val]) => {
mixRule[key] = val;
});
let subRules = await loadOrFetchSubRules(selectedSub.url);
subRules = subRules.map((item) => ({ ...item, ...mixRule }));
rules.splice(-1, 0, ...subRules); rules.splice(-1, 0, ...subRules);
} }
} catch (err) { } catch (err) {
kissLog(err, "load injectRules"); kissLog("load injectRules", err);
} }
} }
const rule = rules.find((r) => const rule = rules.find((r) =>
r.pattern.split(",").some((p) => isMatch(href, p.trim())) r.pattern.split(/\n|,/).some((p) => isMatch(href, p.trim()))
); );
const globalRule = { const globalRule = {
...GLOBLA_RULE, ...GLOBLA_RULE,
@@ -68,15 +47,21 @@ export const matchRule = async (
[ [
"selector", "selector",
"keepSelector", "keepSelector",
"rootsSelector",
"ignoreSelector",
"terms", "terms",
"aiTerms",
"termsStyle",
"highlightStyle",
"textExtStyle",
"selectStyle", "selectStyle",
"parentStyle", "parentStyle",
"grandStyle",
"injectJs", "injectJs",
"injectCss", "injectCss",
"fixerSelector",
"transStartHook", "transStartHook",
"transEndHook", "transEndHook",
"transRemoveHook", // "transRemoveHook",
].forEach((key) => { ].forEach((key) => {
if (!rule[key]?.trim()) { if (!rule[key]?.trim()) {
rule[key] = globalRule[key]; rule[key] = globalRule[key];
@@ -84,33 +69,30 @@ export const matchRule = async (
}); });
[ [
"translator", "apiSlug",
"fromLang", "fromLang",
"toLang", "toLang",
"transOpen", "transOpen",
"transOnly", "transOnly",
"transTiming", "autoScan",
"hasRichText",
"hasShadowroot",
"transTag", "transTag",
"transTitle", "transTitle",
"detectRemote", "splitParagraph",
"fixerFunc", "highlightWords",
"textStyle",
].forEach((key) => { ].forEach((key) => {
if (rule[key] === undefined || rule[key] === GLOBAL_KEY) { if (!rule[key] || rule[key] === GLOBAL_KEY) {
rule[key] = globalRule[key]; rule[key] = globalRule[key];
} }
}); });
if (!rule.skipLangs || rule.skipLangs.length === 0) { ["splitLength"].forEach((key) => {
rule.skipLangs = globalRule.skipLangs; if (!rule[key]) {
} rule[key] = globalRule[key];
if (rule.textStyle === GLOBAL_KEY) { }
rule.textStyle = globalRule.textStyle; });
rule.bgColor = globalRule.bgColor;
rule.textDiyStyle = globalRule.textDiyStyle;
} else {
rule.bgColor = rule.bgColor?.trim() || globalRule.bgColor;
rule.textDiyStyle = rule.textDiyStyle?.trim() || globalRule.textDiyStyle;
}
return rule; return rule;
}; };
@@ -145,57 +127,82 @@ export const checkRules = (rules) => {
pattern, pattern,
selector, selector,
keepSelector, keepSelector,
rootsSelector,
ignoreSelector,
terms, terms,
aiTerms,
termsStyle,
highlightStyle,
textExtStyle,
selectStyle, selectStyle,
parentStyle, parentStyle,
grandStyle,
injectJs, injectJs,
injectCss, injectCss,
translator, apiSlug,
fromLang, fromLang,
toLang, toLang,
textStyle, textStyle,
transOpen, transOpen,
bgColor,
textDiyStyle,
transOnly, transOnly,
transTiming, autoScan,
hasRichText,
hasShadowroot,
transTag, transTag,
transTitle, transTitle,
detectRemote,
skipLangs,
fixerSelector,
fixerFunc,
transStartHook, transStartHook,
transEndHook, transEndHook,
transRemoveHook, // transRemoveHook,
splitParagraph,
splitLength,
highlightWords,
}) => ({ }) => ({
pattern: pattern.trim(), pattern: pattern.trim(),
selector: type(selector) === "string" ? selector : "", selector: type(selector) === "string" ? selector : "",
keepSelector: type(keepSelector) === "string" ? keepSelector : "", keepSelector: type(keepSelector) === "string" ? keepSelector : "",
rootsSelector: type(rootsSelector) === "string" ? rootsSelector : "",
ignoreSelector: type(ignoreSelector) === "string" ? ignoreSelector : "",
terms: type(terms) === "string" ? terms : "", terms: type(terms) === "string" ? terms : "",
aiTerms: type(aiTerms) === "string" ? aiTerms : "",
termsStyle: type(termsStyle) === "string" ? termsStyle : "",
highlightStyle: type(highlightStyle) === "string" ? highlightStyle : "",
textExtStyle: type(textExtStyle) === "string" ? textExtStyle : "",
selectStyle: type(selectStyle) === "string" ? selectStyle : "", selectStyle: type(selectStyle) === "string" ? selectStyle : "",
parentStyle: type(parentStyle) === "string" ? parentStyle : "", parentStyle: type(parentStyle) === "string" ? parentStyle : "",
grandStyle: type(grandStyle) === "string" ? grandStyle : "",
injectJs: type(injectJs) === "string" ? injectJs : "", injectJs: type(injectJs) === "string" ? injectJs : "",
injectCss: type(injectCss) === "string" ? injectCss : "", injectCss: type(injectCss) === "string" ? injectCss : "",
bgColor: type(bgColor) === "string" ? bgColor : "", apiSlug:
textDiyStyle: type(textDiyStyle) === "string" ? textDiyStyle : "", type(apiSlug) === "string" && apiSlug.trim() !== ""
translator: matchValue([GLOBAL_KEY, ...OPT_TRANS_ALL], translator), ? apiSlug.trim()
: GLOBAL_KEY,
fromLang: matchValue([GLOBAL_KEY, ...fromLangs], fromLang), fromLang: matchValue([GLOBAL_KEY, ...fromLangs], fromLang),
toLang: matchValue([GLOBAL_KEY, ...toLangs], toLang), toLang: matchValue([GLOBAL_KEY, ...toLangs], toLang),
textStyle: matchValue([GLOBAL_KEY, ...OPT_STYLE_ALL], textStyle), // textStyle: matchValue([GLOBAL_KEY, ...OPT_STYLE_ALL], textStyle),
textStyle:
type(textStyle) === "string" && textStyle.trim() !== ""
? textStyle.trim()
: GLOBAL_KEY,
transOpen: matchValue([GLOBAL_KEY, "true", "false"], transOpen), transOpen: matchValue([GLOBAL_KEY, "true", "false"], transOpen),
transOnly: matchValue([GLOBAL_KEY, "true", "false"], transOnly), transOnly: matchValue([GLOBAL_KEY, "true", "false"], transOnly),
transTiming: matchValue([GLOBAL_KEY, ...OPT_TIMING_ALL], transTiming), autoScan: matchValue([GLOBAL_KEY, "true", "false"], autoScan),
hasRichText: matchValue([GLOBAL_KEY, "true", "false"], hasRichText),
hasShadowroot: matchValue([GLOBAL_KEY, "true", "false"], hasShadowroot),
transTag: matchValue([GLOBAL_KEY, "span", "font"], transTag), transTag: matchValue([GLOBAL_KEY, "span", "font"], transTag),
transTitle: matchValue([GLOBAL_KEY, "true", "false"], transTitle), transTitle: matchValue([GLOBAL_KEY, "true", "false"], transTitle),
detectRemote: matchValue([GLOBAL_KEY, "true", "false"], detectRemote),
skipLangs: type(skipLangs) === "array" ? skipLangs : [],
fixerSelector: type(fixerSelector) === "string" ? fixerSelector : "",
transStartHook: type(transStartHook) === "string" ? transStartHook : "", transStartHook: type(transStartHook) === "string" ? transStartHook : "",
transEndHook: type(transEndHook) === "string" ? transEndHook : "", transEndHook: type(transEndHook) === "string" ? transEndHook : "",
transRemoveHook: // transRemoveHook:
type(transRemoveHook) === "string" ? transRemoveHook : "", // type(transRemoveHook) === "string" ? transRemoveHook : "",
fixerFunc: matchValue([GLOBAL_KEY, ...FIXER_ALL], fixerFunc), splitParagraph: matchValue(
[GLOBAL_KEY, ...OPT_SPLIT_PARAGRAPH_ALL],
splitParagraph
),
splitLength: Number.isInteger(splitLength) ? splitLength : 0,
highlightWords: matchValue(
[GLOBAL_KEY, ...OPT_HIGHLIGHT_WORDS_ALL],
highlightWords
),
}) })
); );
@@ -204,16 +211,34 @@ export const checkRules = (rules) => {
/** /**
* 保存或更新rule * 保存或更新rule
* @param {*} newRule * @param {*} curRule
*/ */
export const saveRule = async (newRule) => { export const saveRule = async (curRule) => {
const rules = await getRulesWithDefault(); const rules = await getRulesWithDefault();
const rule = rules.find((item) => isMatch(newRule.pattern, item.pattern));
if (rule && rule.pattern !== GLOBAL_KEY) { const index = rules.findIndex(
Object.assign(rule, { ...newRule, pattern: rule.pattern }); (item) =>
} else { item.pattern !== GLOBAL_KEY && isMatch(curRule.pattern, item.pattern)
rules.unshift(newRule); );
if (index !== -1) {
const rule = rules.splice(index, 1)[0];
curRule = { ...rule, ...curRule, pattern: rule.pattern };
} }
const newRule = {};
const globalRule = {
...GLOBLA_RULE,
...(rules.find((r) => r.pattern === GLOBAL_KEY) || {}),
};
Object.keys(GLOBLA_RULE).forEach((key) => {
newRule[key] =
!curRule[key] || curRule[key] === globalRule[key]
? DEFAULT_RULE[key]
: curRule[key];
});
rules.unshift(newRule);
await setRules(rules); await setRules(rules);
trySyncRules(); trySyncRules();
}; };

View File

@@ -0,0 +1,131 @@
import React from "react";
import ReactDOM from "react-dom/client";
import { CacheProvider } from "@emotion/react";
import createCache from "@emotion/cache";
import { logger } from "./log";
export default class ShadowDomManager {
#hostElement = null;
#reactRoot = null;
#isVisible = false;
#isProcessing = false;
_id;
_className;
_ReactComponent;
_props;
constructor({
id,
className = "",
reactComponent,
props = {},
rootElement = document.body,
}) {
if (!id || !reactComponent) {
throw new Error("ID and a React Component must be provided.");
}
this._id = id;
this._className = className;
this._ReactComponent = reactComponent;
this._props = props;
this._rootElement = rootElement;
}
get isVisible() {
return this.#isVisible;
}
show(props) {
if (this.#isVisible || this.#isProcessing) {
return;
}
if (!this.#hostElement) {
this.#isProcessing = true;
try {
this.#mount(props || this._props);
} catch (error) {
logger.warn(`Failed to mount component with id "${this._id}":`, error);
this.#isProcessing = false;
return;
} finally {
this.#isProcessing = false;
}
}
this.#hostElement.style.display = "";
this.#isVisible = true;
}
hide() {
if (!this.#isVisible || !this.#hostElement) {
return;
}
this.#hostElement.style.display = "none";
this.#isVisible = false;
}
destroy() {
if (!this.#hostElement) {
return;
}
this.#isProcessing = true;
if (this.#reactRoot) {
this.#reactRoot.unmount();
}
this.#hostElement.remove();
this.#hostElement = null;
this.#reactRoot = null;
this.#isVisible = false;
this.#isProcessing = false;
logger.info(`Component with id "${this._id}" has been destroyed.`);
}
toggle(props) {
if (this.#isVisible) {
this.hide();
} else {
this.show(props || this._props);
}
}
#mount(props) {
const host = document.createElement("div");
host.id = this._id;
if (this._className) {
host.className = this._className;
}
this._rootElement.appendChild(host);
this.#hostElement = host;
const shadowContainer = host.attachShadow({ mode: "open" });
const appRoot = document.createElement("div");
appRoot.className = `${this._id}_wrapper notranslate`;
shadowContainer.appendChild(appRoot);
const cache = createCache({
key: this._id,
prepend: true,
container: shadowContainer,
});
const enhancedProps = {
...props,
onClose: this.hide.bind(this),
};
const ComponentToRender = this._ReactComponent;
this.#reactRoot = ReactDOM.createRoot(appRoot);
this.#reactRoot.render(
<React.StrictMode>
<CacheProvider value={cache}>
<ComponentToRender {...enhancedProps} />
</CacheProvider>
</React.StrictMode>
);
}
}

View File

@@ -1,112 +1,131 @@
import { isSameSet } from "./utils"; import { isSameSet } from "./utils";
/** /**
* 键盘快捷键监听 * 键盘快捷键监听
* @param {*} fn * @param {(pressedKeys: Set<string>, event: KeyboardEvent) => void} onKeyDown - Keydown 回调
* @param {*} target * @param {(pressedKeys: Set<string>, event: KeyboardEvent) => void} onKeyUp - Keyup 回调
* @param {*} timeout * @param {EventTarget} target - 监听的目标元素
* @returns * @returns {() => void} - 用于注销监听的函数
*/ */
export const shortcutListener = (fn, target = document, timeout = 3000) => { export const shortcutListener = (
const allkeys = new Set(); onKeyDown = () => {},
const curkeys = new Set(); onKeyUp = () => {},
let timer = null; target = document
) => {
const pressedKeys = new Set();
const handleKeydown = (e) => { const handleKeyDown = (e) => {
timer && clearTimeout(timer); if (!e.code) {
timer = setTimeout(() => { return;
allkeys.clear();
curkeys.clear();
clearTimeout(timer);
timer = null;
}, timeout);
if (e.code) {
allkeys.add(e.code);
curkeys.add(e.code);
fn([...curkeys], [...allkeys]);
} }
if (pressedKeys.has(e.code)) return;
pressedKeys.add(e.code);
onKeyDown(new Set(pressedKeys), e);
}; };
const handleKeyup = (e) => { const handleKeyUp = (e) => {
curkeys.delete(e.code); if (!e.code) {
if (curkeys.size === 0) { return;
fn([...curkeys], [...allkeys]);
allkeys.clear();
} }
// onKeyUp 应该在 key 从集合中移除前触发,以便判断组合键
onKeyUp(new Set(pressedKeys), e);
pressedKeys.delete(e.code);
}; };
target.addEventListener("keydown", handleKeydown, true); const handleBlur = () => {
target.addEventListener("keyup", handleKeyup, true); pressedKeys.clear();
};
target.addEventListener("keydown", handleKeyDown);
target.addEventListener("keyup", handleKeyUp);
window.addEventListener("blur", handleBlur);
return () => { return () => {
if (timer) { target.removeEventListener("keydown", handleKeyDown);
clearTimeout(timer); target.removeEventListener("keyup", handleKeyUp);
timer = null; window.removeEventListener("blur", handleBlur);
} pressedKeys.clear();
target.removeEventListener("keydown", handleKeydown);
target.removeEventListener("keyup", handleKeyup);
}; };
}; };
/** /**
* 注册键盘快捷键 * 注册键盘快捷键
* @param {*} targetKeys * @param {string[]} targetKeys - 目标快捷键数组
* @param {*} fn * @param {() => void} fn - 匹配成功后执行的回调
* @param {*} target * @param {EventTarget} target - 监听目标
* @returns * @returns {() => void} - 注销函数
*/ */
export const shortcutRegister = (targetKeys = [], fn, target = document) => { export const shortcutRegister = (targetKeys = [], fn, target = document) => {
return shortcutListener((curkeys) => { if (targetKeys.length === 0) return () => {};
if (
targetKeys.length > 0 && const targetKeySet = new Set(targetKeys);
isSameSet(new Set(targetKeys), new Set(curkeys)) let hasInterference = false;
) { const onKeyDown = (pressedKeys, event) => {
// if (isSameSet(targetKeySet, pressedKeys)) {
// // event.preventDefault(); // 阻止浏览器的默认行为
// // event.stopPropagation(); // 阻止事件继续(向父元素)冒泡
// fn();
// }
if (!targetKeySet.has(event.code)) {
hasInterference = true;
}
};
const onKeyUp = (pressedKeys, event) => {
if (isSameSet(targetKeySet, pressedKeys) && !hasInterference) {
fn(); fn();
} }
}, target); if (pressedKeys.size === 1) {
hasInterference = false;
}
};
return shortcutListener(onKeyDown, onKeyUp, target);
};
/**
* 高阶函数:为目标函数增加计次和超时重置功能
* @param {() => void} fn - 需要被包装的函数
* @param {number} step - 需要触发的次数
* @param {number} timeout - 超时毫秒数
* @returns {() => void} - 包装后的新函数
*/
const withStepCounter = (fn, step, timeout) => {
let count = 0;
let timer = null;
return () => {
timer && clearTimeout(timer);
timer = setTimeout(() => {
count = 0;
}, timeout);
count++;
if (count === step) {
count = 0;
clearTimeout(timer);
fn();
}
};
}; };
/** /**
* 注册连续快捷键 * 注册连续快捷键
* @param {*} targetKeys * @param {string[]} targetKeys - 目标快捷键数组
* @param {*} fn * @param {() => void} fn - 成功回调
* @param {*} step * @param {number} step - 连续触发次数
* @param {*} timeout * @param {number} timeout - 每次触发的间隔超时
* @param {*} target * @param {EventTarget} target - 监听目标
* @returns * @returns {() => void} - 注销函数
*/ */
export const stepShortcutRegister = ( export const stepShortcutRegister = (
targetKeys = [], targetKeys = [],
fn, fn,
step = 3, step = 2,
timeout = 500, timeout = 500,
target = document target = document
) => { ) => {
let count = 0; const steppedFn = withStepCounter(fn, step, timeout);
let pre = Date.now(); return shortcutRegister(targetKeys, steppedFn, target);
let timer;
return shortcutListener((curkeys, allkeys) => {
timer && clearTimeout(timer);
timer = setTimeout(() => {
clearTimeout(timer);
count = 0;
}, timeout);
if (targetKeys.length > 0 && curkeys.length === 0) {
const now = Date.now();
if (
(count === 0 || now - pre < timeout) &&
isSameSet(new Set(targetKeys), new Set(allkeys))
) {
count++;
if (count === step) {
count = 0;
fn();
}
} else {
count = 0;
}
pre = now;
}
}, target);
}; };

View File

@@ -1,8 +1,11 @@
import { import {
STOKEY_SETTING, STOKEY_SETTING,
STOKEY_SETTING_OLD,
STOKEY_RULES, STOKEY_RULES,
STOKEY_RULES_OLD,
STOKEY_WORDS, STOKEY_WORDS,
STOKEY_FAB, STOKEY_FAB,
STOKEY_TRANBOX,
STOKEY_SYNC, STOKEY_SYNC,
STOKEY_MSAUTH, STOKEY_MSAUTH,
STOKEY_BDAUTH, STOKEY_BDAUTH,
@@ -15,6 +18,7 @@ import {
import { isExt, isGm } from "./client"; import { isExt, isGm } from "./client";
import { browser } from "./browser"; import { browser } from "./browser";
import { kissLog } from "./log"; import { kissLog } from "./log";
import { debounce } from "./utils";
async function set(key, val) { async function set(key, val) {
if (isExt) { if (isExt) {
@@ -59,7 +63,13 @@ async function trySetObj(key, obj) {
async function getObj(key) { async function getObj(key) {
const val = await get(key); const val = await get(key);
return val && JSON.parse(val); if (val === null || val === undefined) return null;
try {
return JSON.parse(val);
} catch (err) {
kissLog("parse json in storage err: ", key);
}
return null;
} }
async function putObj(key, obj) { async function putObj(key, obj) {
@@ -85,17 +95,19 @@ export const storage = {
* 设置信息 * 设置信息
*/ */
export const getSetting = () => getObj(STOKEY_SETTING); export const getSetting = () => getObj(STOKEY_SETTING);
export const getSettingOld = () => getObj(STOKEY_SETTING_OLD);
export const getSettingWithDefault = async () => ({ export const getSettingWithDefault = async () => ({
...DEFAULT_SETTING, ...DEFAULT_SETTING,
...((await getSetting()) || {}), ...((await getSetting()) || {}),
}); });
export const setSetting = (val) => setObj(STOKEY_SETTING, val); export const setSetting = (val) => setObj(STOKEY_SETTING, val);
export const updateSetting = (obj) => putObj(STOKEY_SETTING, obj); export const putSetting = (obj) => putObj(STOKEY_SETTING, obj);
/** /**
* 规则列表 * 规则列表
*/ */
export const getRules = () => getObj(STOKEY_RULES); export const getRules = () => getObj(STOKEY_RULES);
export const getRulesOld = () => getObj(STOKEY_RULES_OLD);
export const getRulesWithDefault = async () => export const getRulesWithDefault = async () =>
(await getRules()) || DEFAULT_RULES; (await getRules()) || DEFAULT_RULES;
export const setRules = (val) => setObj(STOKEY_RULES, val); export const setRules = (val) => setObj(STOKEY_RULES, val);
@@ -122,14 +134,27 @@ export const setSubRules = (url, val) =>
export const getFab = () => getObj(STOKEY_FAB); export const getFab = () => getObj(STOKEY_FAB);
export const getFabWithDefault = async () => (await getFab()) || {}; export const getFabWithDefault = async () => (await getFab()) || {};
export const setFab = (obj) => setObj(STOKEY_FAB, obj); export const setFab = (obj) => setObj(STOKEY_FAB, obj);
export const updateFab = (obj) => putObj(STOKEY_FAB, obj); export const putFab = (obj) => putObj(STOKEY_FAB, obj);
/**
* tranbox位置大小
*/
export const getTranBox = () => getObj(STOKEY_TRANBOX);
export const putTranBox = (obj) => putObj(STOKEY_TRANBOX, obj);
export const debouncePutTranBox = debounce(putTranBox, 300);
/** /**
* 数据同步 * 数据同步
*/ */
export const getSync = () => getObj(STOKEY_SYNC); export const getSync = () => getObj(STOKEY_SYNC);
export const getSyncWithDefault = async () => (await getSync()) || DEFAULT_SYNC; export const getSyncWithDefault = async () => (await getSync()) || DEFAULT_SYNC;
export const updateSync = (obj) => putObj(STOKEY_SYNC, obj); export const putSync = (obj) => putObj(STOKEY_SYNC, obj);
export const putSyncMeta = async (key) => {
const { syncMeta = {} } = await getSyncWithDefault();
syncMeta[key] = { ...(syncMeta[key] || {}), updateAt: Date.now() };
await putSync({ syncMeta });
};
export const debounceSyncMeta = debounce(putSyncMeta, 300);
/** /**
* ms auth * ms auth
@@ -156,6 +181,6 @@ export const tryInitDefaultData = async () => {
BUILTIN_RULES BUILTIN_RULES
); );
} catch (err) { } catch (err) {
kissLog(err, "init default"); kissLog("init default", err);
} }
}; };

Some files were not shown because too many files have changed in this diff Show More