-
Notifications
You must be signed in to change notification settings - Fork 1.6k
Expand file tree
/
Copy pathmain(greasyfork).user.js
More file actions
879 lines (761 loc) · 34.9 KB
/
Copy pathmain(greasyfork).user.js
File metadata and controls
879 lines (761 loc) · 34.9 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
// ==UserScript==
// @name GitHub 中文化插件
// @namespace https://github.com/maboloshi/github-chinese
// @description 中文化 GitHub 界面的部分菜单及内容。原作者为楼教主(http://www.52cik.com/)。
// @copyright 2021, 沙漠之子 (https://maboloshi.github.io/Blog)
// @icon https://github.githubassets.com/pinned-octocat.svg
// @version 1.9.2.4-2026-06-21
// @author 沙漠之子
// @license GPL-3.0
// @match https://github.com/*
// @match https://skills.github.com/*
// @match https://gist.github.com/*
// @match https://www.githubstatus.com/*
// @require https://greasyfork.org/scripts/435207-github-%E4%B8%AD%E6%96%87%E5%8C%96%E6%8F%92%E4%BB%B6-%E4%B8%AD%E6%96%87%E8%AF%8D%E5%BA%93%E8%A7%84%E5%88%99/code/GitHub%20%E4%B8%AD%E6%96%87%E5%8C%96%E6%8F%92%E4%BB%B6%20-%20%E4%B8%AD%E6%96%87%E8%AF%8D%E5%BA%93%E8%A7%84%E5%88%99.js?v1.9.2.4-2026-06-21
// @run-at document-end
// @grant GM_xmlhttpRequest
// @grant GM_getValue
// @grant GM_setValue
// @grant GM_registerMenuCommand
// @grant GM_unregisterMenuCommand
// @grant GM_notification
// @connect www.iflyrec.com
// @supportURL https://github.com/maboloshi/github-chinese/issues
// ==/UserScript==
(function (window, document, undefined) {
'use strict';
const lang = I18N.zh ? 'zh' : 'zh-CN'; // 设置默认语言
let page;
let enable_RegExp = GM_getValue("enable_RegExp", 1);
function isReactGlobalNavPortalNode(node) {
const element = node?.nodeType === 1 ? node : node?.parentElement;
const portalRoot = element?.closest?.('#__primerPortalRoot__');
if (!portalRoot) return false;
const portal = element.closest?.('[data-component="Portal"]')
|| element.querySelector?.('[data-component="Portal"]')
|| portalRoot;
if (portal.matches?.('#search-suggestions-dialog')
|| portal.querySelector?.('#search-suggestions-dialog')) return true;
const referenceAttributes = ['aria-labelledby', 'aria-describedby', 'aria-controls', 'aria-owns'];
const referenceElements = [
portal,
...portal.querySelectorAll?.(
referenceAttributes.map(attribute => `[${attribute}]`).join(', ')
) || [],
];
for (const referenceElement of referenceElements) {
for (const attribute of referenceAttributes) {
const ids = referenceElement.getAttribute?.(attribute)?.split(/\s+/) || [];
if (ids.some(id => document.getElementById(id)?.closest?.('header.GlobalNav'))) {
return true;
}
}
}
const portalIds = new Set([
portal.id,
...Array.from(portal.querySelectorAll?.('[id]') || [], item => item.id),
].filter(Boolean));
if (portalIds.size) {
const headerReferences = document.querySelectorAll(
'header.GlobalNav [aria-describedby], header.GlobalNav [aria-controls], header.GlobalNav [aria-owns]'
);
for (const headerReference of headerReferences) {
for (const attribute of ['aria-describedby', 'aria-controls', 'aria-owns']) {
const ids = headerReference.getAttribute(attribute)?.split(/\s+/) || [];
if (ids.some(id => portalIds.has(id))) return true;
}
}
}
const hasControlledSurface = portal.matches?.('[role="menu"], [role="dialog"], [role="tooltip"]')
|| portal.querySelector?.('[role="menu"], [role="dialog"], [role="tooltip"]');
return !!hasControlledSurface
&& !!document.activeElement?.closest?.('header.GlobalNav, qbsearch-input');
}
function setupReactGlobalNavTranslation() {
if (typeof document === 'undefined' || typeof window === 'undefined') return;
const labels = I18N.conf.reactGlobalNavLabels || {};
const dataContentLabelSelector = 'header.GlobalNav [data-component="text"][data-content]';
const controlledSurfaceSelector = [
'header.GlobalNav',
'#__primerPortalRoot__ [role="menu"]',
'#__primerPortalRoot__ [role="dialog"]',
'#__primerPortalRoot__ [role="tooltip"]',
].join(', ');
const portalSurfaceSelector = '#__primerPortalRoot__ [role="menu"], #__primerPortalRoot__ [role="dialog"], #__primerPortalRoot__ [role="tooltip"]';
const searchSurfaceSelector = 'qbsearch-input';
const searchModuleSelector = 'header.GlobalNav [class*="Search-module__"]';
const unsafeTextSelector = [
'textarea',
'[contenteditable="true"]',
'code',
'pre',
'kbd',
'svg',
'img',
'canvas',
'video',
].join(', ');
const searchSelector = `${searchModuleSelector}, ${searchSurfaceSelector}, #__primerPortalRoot__ [role="dialog"]`;
const translatableAttributeNames = ['title', 'aria-label', 'data-visible-text', 'placeholder'];
const reactGlobalNavIdleMs = 700;
const reactGlobalNavRetryMs = 400;
let timer = null;
let headerObserver = null;
let lastReactGlobalNavMutationAt = Date.now();
let lastReactGlobalNavPortalMutationAt = Date.now();
const observedSurfaces = new WeakSet();
function isReactGlobalNavSearchActive() {
const active = document.activeElement;
return !!active?.closest?.(searchSelector)
|| !!document.querySelector('#__primerPortalRoot__ [role="dialog"]');
}
function isReactGlobalNavSurfaceIdle(surfaceType = 'header') {
const lastMutationAt = surfaceType === 'portal'
? lastReactGlobalNavPortalMutationAt
: lastReactGlobalNavMutationAt;
return Date.now() - lastMutationAt >= reactGlobalNavIdleMs;
}
function canTranslateReactGlobalNavHeader() {
return document.readyState === 'complete'
&& isReactGlobalNavSurfaceIdle('header')
&& !isReactGlobalNavSearchActive();
}
function findStaticGlobalNavLabel(source) {
const locale = I18N["zh-CN"] || I18N.zh;
if (!locale) return null;
for (const section of Object.values(locale)) {
const label = section?.static?.[source];
if (typeof label === 'string' && label && label !== source) {
return label;
}
}
return null;
}
function findRegexpGlobalNavLabel(source) {
const locale = I18N["zh-CN"] || I18N.zh;
if (!locale) return null;
for (const section of Object.values(locale)) {
for (const [pattern, replacement] of section?.regexp || []) {
const match = source.match(pattern);
if (!match || match.index !== 0 || match[0] !== source) continue;
const label = source.replace(pattern, replacement);
if (label !== source) return label;
}
}
return null;
}
function resolveReactGlobalNavLabel(source) {
return labels[source] || findStaticGlobalNavLabel(source) || findRegexpGlobalNavLabel(source);
}
function normalizeReactGlobalNavText(text) {
return text?.replace(/\s+/g, ' ').trim();
}
function translateReactGlobalNavText(text) {
const source = normalizeReactGlobalNavText(text);
return source ? resolveReactGlobalNavLabel(source) : null;
}
function translateReactGlobalNavElement(element, source) {
const label = translateReactGlobalNavText(source ?? element.textContent);
if (label && element.textContent !== label) {
element.textContent = label;
}
}
function shouldSkipReactGlobalNavNode(node) {
const element = node.nodeType === Node.ELEMENT_NODE ? node : node.parentElement;
if (!element) return true;
if (element.closest?.(unsafeTextSelector)) return true;
if (element.closest?.(searchModuleSelector)) return true;
if (element.closest?.(searchSurfaceSelector)) return true;
return false;
}
function translateReactGlobalNavAttributes(element) {
translatableAttributeNames.forEach(attributeName => {
const value = element.getAttribute?.(attributeName);
const label = translateReactGlobalNavText(value);
if (label && value !== label) {
element.setAttribute(attributeName, label);
}
});
}
function translateReactGlobalNavTextNode(node) {
const label = translateReactGlobalNavText(node.data);
if (label) {
node.data = node.data.replace(node.data.trim(), label);
}
}
function translateReactGlobalNavSurface(surface) {
if (!surface || shouldSkipReactGlobalNavNode(surface)) return;
if (surface.nodeType === Node.ELEMENT_NODE) {
translateReactGlobalNavAttributes(surface);
}
const walker = document.createTreeWalker(
surface,
NodeFilter.SHOW_ELEMENT | NodeFilter.SHOW_TEXT,
{
acceptNode(node) {
return shouldSkipReactGlobalNavNode(node)
? NodeFilter.FILTER_REJECT
: NodeFilter.FILTER_ACCEPT;
}
}
);
let node;
while ((node = walker.nextNode())) {
if (node.nodeType === Node.ELEMENT_NODE) {
translateReactGlobalNavAttributes(node);
} else if (node.nodeType === Node.TEXT_NODE) {
translateReactGlobalNavTextNode(node);
}
}
}
function translateReactGlobalNavHeader() {
const header = document.querySelector('header.GlobalNav');
if (!header) return true;
if (!canTranslateReactGlobalNavHeader()) return false;
document.querySelectorAll(dataContentLabelSelector).forEach(element => {
if (!shouldSkipReactGlobalNavNode(element)) {
translateReactGlobalNavElement(element, element.getAttribute('data-content'));
}
});
translateReactGlobalNavSurface(header);
return true;
}
function isReactGlobalNavSearchPortal(surface) {
return surface.matches?.('[role="dialog"]')
|| !!surface.querySelector?.('#search-suggestions-dialog, qbsearch-input, [role="dialog"]');
}
function translateReactGlobalNavPortals() {
const surfaces = Array.from(document.querySelectorAll(portalSurfaceSelector))
.filter(isReactGlobalNavPortalNode);
if (!surfaces.length) return true;
let searchPortalPending = false;
surfaces.forEach(surface => {
if (isReactGlobalNavSearchPortal(surface) && !isReactGlobalNavSurfaceIdle('portal')) {
searchPortalPending = true;
return;
}
translateReactGlobalNavSurface(surface);
});
return !searchPortalPending;
}
function translateReactGlobalNavLabels(options = { requireSettledHeader: true }) {
observeReactGlobalNav();
const headerTranslated = translateReactGlobalNavHeader();
const portalsTranslated = translateReactGlobalNavPortals();
if ((options.requireSettledHeader && !headerTranslated) || !portalsTranslated) {
scheduleReactGlobalNavTranslation(reactGlobalNavRetryMs, options);
}
}
function scheduleReactGlobalNavTranslation(delay = 800, options = {}) {
window.clearTimeout(timer);
timer = window.setTimeout(() => translateReactGlobalNavLabels(options), delay);
}
function scheduleReactGlobalNavSeries() {
[800, 1600, 3000].forEach(delay => {
window.setTimeout(translateReactGlobalNavLabels, delay);
});
}
function recordReactGlobalNavMutation(surface) {
if (surface?.id === '__primerPortalRoot__' || surface?.closest?.('#__primerPortalRoot__')) {
lastReactGlobalNavPortalMutationAt = Date.now();
return;
}
lastReactGlobalNavMutationAt = Date.now();
}
function observeReactGlobalNav() {
if (!headerObserver) {
headerObserver = new MutationObserver(mutations => {
mutations.forEach(mutation => recordReactGlobalNavMutation(mutation.target));
translateReactGlobalNavPortals();
scheduleReactGlobalNavTranslation(reactGlobalNavRetryMs, { requireSettledHeader: true });
});
}
[
document.querySelector('header.GlobalNav'),
document.querySelector('#__primerPortalRoot__'),
].forEach(surface => {
if (!surface || observedSurfaces.has(surface)) return;
observedSurfaces.add(surface);
recordReactGlobalNavMutation(surface);
headerObserver.observe(surface, {
childList: true,
subtree: true,
characterData: true,
});
});
}
function startReactGlobalNavTranslation() {
observeReactGlobalNav();
scheduleReactGlobalNavSeries();
}
if (document.readyState === 'loading') {
document.addEventListener('DOMContentLoaded', startReactGlobalNavTranslation, { once: true });
} else {
startReactGlobalNavTranslation();
}
window.addEventListener('turbo:load', scheduleReactGlobalNavSeries);
window.addEventListener('urlchange', scheduleReactGlobalNavSeries);
document.addEventListener('click', () => scheduleReactGlobalNavTranslation(reactGlobalNavRetryMs, { requireSettledHeader: true }), true);
document.addEventListener('focusin', () => scheduleReactGlobalNavTranslation(reactGlobalNavRetryMs, { requireSettledHeader: true }), true);
document.addEventListener('focusout', () => scheduleReactGlobalNavTranslation(reactGlobalNavRetryMs, { requireSettledHeader: true }), true);
document.addEventListener('pointerover', () => scheduleReactGlobalNavTranslation(reactGlobalNavRetryMs, { requireSettledHeader: true }), true);
}
function getElementFromNode(node) {
if (!node) return null;
return node.nodeType === Node.ELEMENT_NODE ? node : node.parentElement;
}
function getIgnoreMutationSelectors() {
const selectorPage = I18N.conf.ignoreMutationSelectorPage || {};
return [
...(selectorPage['*'] || []),
...((page && selectorPage[page]) || []),
].join(', ');
}
function shouldIgnoreMutationNode(node, ignoreMutationSelectors) {
const element = getElementFromNode(node);
if (!element) return true;
if (ignoreMutationSelectors &&
(element.matches?.(ignoreMutationSelectors) ||
element.closest?.(ignoreMutationSelectors))) {
return true;
}
return isReactGlobalNavPortalNode(element);
}
/**
* watchUpdate 函数:监视页面变化,根据变化的节点进行翻译
*/
function watchUpdate() {
// 检测浏览器是否支持 MutationObserver
const MutationObserver =
window.MutationObserver ||
window.WebKitMutationObserver ||
window.MozMutationObserver;
// 获取当前页面的 URL
const getCurrentURL = () => location.href;
getCurrentURL.previousURL = getCurrentURL();
// 创建 MutationObserver 实例,监听 DOM 变化
const observer = new MutationObserver((mutations, observer) => {
const currentURL = getCurrentURL();
// 如果页面的 URL 发生变化
if (currentURL !== getCurrentURL.previousURL) {
getCurrentURL.previousURL = currentURL;
page = getPage(); // 当页面地址发生变化时,更新全局变量 page
console.log(`链接变化 page= ${page}`);
transTitle(); // 翻译页面标题
if (page) {
setTimeout(() => {
// 使用 CSS 选择器找到页面上的元素,并将其文本内容替换为预定义的翻译
transBySelector();
if (page === "repository") { //仓库简介翻译
transDesc(".f4.my-3");
} else if (page === "gist") { // Gist 简介翻译
transDesc(".gist-content [itemprop='about']");
}
}, 500);
}
}
if (page) {
const ignoreMutationSelectors = getIgnoreMutationSelectors();
mutations.forEach(mutation => {
if (mutation.type === 'childList' && mutation.addedNodes.length > 0) {
mutation.addedNodes.forEach(node => {
if (!shouldIgnoreMutationNode(node, ignoreMutationSelectors)) {
traverseNode(node);
}
});
} else if (
(mutation.type === 'attributes' || mutation.type === 'characterData') &&
!shouldIgnoreMutationNode(mutation.target, ignoreMutationSelectors)
) {
traverseNode(mutation.target);
}
});
}
});
// 配置 MutationObserver
const config = {
characterData: true,
subtree: true,
childList: true,
attributeFilter: ['value', 'placeholder', 'aria-label', 'data-confirm'], // 仅观察特定属性变化
};
// 开始观察 document.body 的变化
observer.observe(document.body, config);
}
/**
* traverseNode 函数:遍历指定的节点,并对节点进行翻译。
* @param {Node} node - 需要遍历的节点。
*/
function traverseNode(node) {
// 跳过忽略
if (I18N.conf.reIgnoreId.test(node.id) ||
I18N.conf.reIgnoreClass.test(node.className) ||
I18N.conf.reIgnoreTag.includes(node.tagName) ||
(node.getAttribute && I18N.conf.reIgnoreItemprop.test(node.getAttribute("itemprop")))
) {
return;
}
if (node.nodeType === Node.ELEMENT_NODE) { // 元素节点处理
// 翻译时间元素
if (
["RELATIVE-TIME", "TIME-AGO", "TIME", "LOCAL-TIME"].includes(node.tagName)
) {
if (node.shadowRoot) {
transTimeElement(node.shadowRoot);
watchTimeElement(node.shadowRoot);
} else {
transTimeElement(node);
}
return;
}
// 元素节点属性翻译
if (["INPUT", "TEXTAREA"].includes(node.tagName)) { // 输入框 按钮 文本域
if (["button", "submit", "reset"].includes(node.type)) {
if (node.hasAttribute('data-confirm')) { // 翻译 浏览器 提示对话框
transElement(node, 'data-confirm', true);
}
transElement(node, 'value');
} else {
transElement(node, 'placeholder');
}
} else if (node.tagName === 'BUTTON') {
if (node.hasAttribute('aria-label') && /tooltipped/.test(node.className)) {
transElement(node, 'aria-label', true); // 翻译 浏览器 提示对话框
}
if (node.hasAttribute('title')) {
transElement(node, 'title', true); // 翻译 浏览器 提示对话框
}
if (node.hasAttribute('data-confirm')) {
transElement(node, 'data-confirm', true); // 翻译 浏览器 提示对话框 ok
}
if (node.hasAttribute('data-confirm-text')) {
transElement(node, 'data-confirm-text', true); // 翻译 浏览器 提示对话框 ok
}
if (node.hasAttribute('data-confirm-cancel-text')) {
transElement(node, 'data-confirm-cancel-text', true); // 取消按钮 提醒
}
if (node.hasAttribute('cancel-confirm-text')) {
transElement(node, 'cancel-confirm-text', true); // 取消按钮 提醒
}
if (node.hasAttribute('data-disable-with')) { // 按钮等待提示
transElement(node, 'data-disable-with', true);
}
} else if (node.tagName === 'OPTGROUP') { // 翻译 <optgroup> 的 label 属性
transElement(node, 'label');
} else if (/tooltipped/.test(node.className)) { // 仅当 元素存在'tooltipped'样式 aria-label 才起效果
transElement(node, 'aria-label', true); // 带提示的元素,类似 tooltip 效果的
} else if (node.tagName === 'A') {
if (node.hasAttribute('title')) {
transElement(node, 'title', true); // 翻译 浏览器 提示对话框
}
if (node.hasAttribute('data-hovercard-type')) {
return; // 不翻译
}
}
let childNodes = node.childNodes;
childNodes.forEach(traverseNode); // 遍历子节点
} else if (node.nodeType === Node.TEXT_NODE) { // 文本节点翻译
if (node.length <= 500) { // 修复 许可证编辑框初始化载入内容被翻译
transElement(node, 'data');
}
}
}
/**
* getPage 函数:获取当前页面的类型。
* @returns {string|boolean} 当前页面的类型,如果无法确定类型,那么返回 false。
*/
function getPage() {
// 站点,如 gist, developer, help 等,默认主站是 github
const siteMapping = {
'gist.github.com': 'gist',
'www.githubstatus.com': 'status',
'skills.github.com': 'skills'
};
const site = siteMapping[location.hostname] || 'github'; // 站点
const pathname = location.pathname; // 当前路径
// 是否登录
const isLogin = document.body.classList.contains("logged-in");
// 用于确定 个人首页,组织首页,仓库页 然后做判断
const analyticsLocation = (document.getElementsByName('analytics-location')[0] || {}).content || '';
// 组织页
const isOrganization = /\/<org-login>/.test(analyticsLocation) || /^\/(?:orgs|organizations)/.test(pathname);
// 仓库页
const isRepository = /\/<user-name>\/<repo-name>/.test(analyticsLocation);
// 优先匹配 body 的 class
let page, t = document.body.className.match(I18N.conf.rePageClass);
if (t) {
if (t[1] === 'page-profile') {
let matchResult = location.search.match(/tab=(\w+)/);
if (matchResult) {
page = 'page-profile/' + matchResult[1];
} else {
page = pathname.match(/\/(stars)/) ? 'page-profile/stars' : 'page-profile';
}
} else {
page = t[1];
}
} else if (site === 'gist') { // Gist 站点
page = 'gist';
} else if (site === 'status') { // GitHub Status 页面
page = 'status';
} else if (site === 'skills') { // GitHub Skills 页面
page = 'skills';
} else if (pathname === '/' && site === 'github') { // github.com 首页
page = isLogin ? 'page-dashboard' : 'homepage';
} else if (isRepository) { // 仓库页
t = pathname.match(I18N.conf.rePagePathRepo);
page = t ? 'repository/' + t[1] : 'repository';
} else if (isOrganization) { // 组织页
t = pathname.match(I18N.conf.rePagePathOrg);
page = t ? 'orgs/' + (t[1] || t.slice(-1)[0]) : 'orgs';
} else {
t = pathname.match(I18N.conf.rePagePath);
page = t ? (t[1] || t.slice(-1)[0]) : false; // 取页面 key
}
if (!page || !I18N[lang][page]) {
console.log(`请注意对应 page ${page} 词库节点不存在`);
page = false;
}
return page;
}
/**
* transTitle 函数:翻译页面标题
*/
function transTitle() {
let key = document.title; // 标题文本内容
let str = I18N[lang]['title']['static'][key] || '';
if (!str) {
let res = I18N[lang]['title'].regexp || [];
for (let [a, b] of res) {
str = key.replace(a, b);
if (str !== key) {
break;
}
}
}
document.title = str;
}
/**
* transTimeElement 函数:翻译时间元素文本内容。
* @param {Element} el - 需要翻译的元素。
*/
function transTimeElement(el) {
let key = el.childNodes.length > 0 ? el.lastChild.textContent : el.textContent;
let res = I18N[lang]['public']['time-regexp']; // 时间正则规则
for (let [a, b] of res) {
let str = key.replace(a, b);
if (str !== key) {
el.textContent = str;
break;
}
}
}
/**
* watchTimeElement 函数:监视时间元素变化, 触发和调用时间元素翻译
* @param {Element} el - 需要监视的元素。
*/
function watchTimeElement(el) {
const MutationObserver =
window.MutationObserver ||
window.WebKitMutationObserver ||
window.MozMutationObserver;
new MutationObserver(mutations => {
transTimeElement(mutations[0].addedNodes[0]);
}).observe(el, {
childList: true
});
}
/**
* transElement 函数:翻译指定元素的文本内容或属性。
* @param {Element} el - 需要翻译的元素。
* @param {string} field - 需要翻译的文本内容或属性的名称。
* @param {boolean} isAttr - 是否需要翻译属性。
*/
function transElement(el, field, isAttr = false) {
let text = isAttr ? el.getAttribute(field) : el[field]; // 需要翻译的文本
let str = translateText(text); // 翻译后的文本
// 替换翻译后的内容
if (str) {
if (!isAttr) {
el[field] = str;
} else {
el.setAttribute(field, str);
}
}
}
/**
* translateText 函数:翻译文本内容。
* @param {string} text - 需要翻译的文本内容。
* @returns {string|boolean} 翻译后的文本内容,如果没有找到对应的翻译,那么返回 false。
*/
function translateText(text) { // 翻译
// 内容为空, 空白字符和或数字, 不存在英文字母和符号,. 跳过
if (!isNaN(text) || !/[a-zA-Z,.]+/.test(text)) {
return false;
}
let _key = text.trim(); // 去除首尾空格的 key
let _key_neat = _key.replace(/\xa0|[\s]+/g, ' ') // 去除多余空白字符( 空格 换行符)
let str = fetchTranslatedText(_key_neat); // 翻译已知页面 (局部优先)
if (str && str !== _key_neat) { // 已知页面翻译完成
return text.replace(_key, str); // 替换原字符,保留首尾空白部分
}
return false;
}
/**
* fetchTranslatedText 函数:从特定页面的词库中获得翻译文本内容。
* @param {string} key - 需要翻译的文本内容。
* @returns {string|boolean} 翻译后的文本内容,如果没有找到对应的翻译,那么返回 false。
*/
function fetchTranslatedText(key) {
// 静态翻译
let str = I18N[lang][page]['static'][key] || I18N[lang]['public']['static'][key]; // 默认翻译 公共部分
if (typeof str === 'string') {
return str;
}
// 正则翻译
if (enable_RegExp) {
let res = (I18N[lang][page].regexp || []).concat(I18N[lang]['public'].regexp || []); // 正则数组
for (let [a, b] of res) {
str = key.replace(a, b);
if (str !== key) {
return str;
}
}
}
return false; // 没有翻译条目
}
/**
* transDesc 函数:为指定的元素添加一个翻译按钮,并为该按钮添加点击事件。
* @param {string} el - CSS选择器,用于选择需要添加翻译按钮的元素。
*/
function transDesc(el) {
// 使用 CSS 选择器选择元素
let element = document.querySelector(el);
// 如果元素不存在 或者 translate-me 元素已存在,那么直接返回
if (!element || document.getElementById('translate-me')) {
return false;
}
// 在元素后面插入一个翻译按钮
const buttonHTML = `<div id='translate-me' style='color: rgb(27, 149, 224); font-size: small; cursor: pointer'>翻译</div>`;
element.insertAdjacentHTML('afterend', buttonHTML);
let button = element.nextSibling;
// 为翻译按钮添加点击事件
button.addEventListener('click', () => {
// 获取元素的文本内容
const desc = element.textContent.trim();
// 如果文本内容为空,那么直接返回
if (!desc) {
return false;
}
// 调用 translateDescText 函数进行翻译
translateDescText(desc, text => {
// 翻译完成后,隐藏翻译按钮,并在元素后面插入翻译结果
button.style.display = "none";
const resultContainer = document.createElement('span');
resultContainer.innerHTML = `<span style='font-size: small'>由 <a target='_blank' style='color:rgb(27, 149, 224);' href='https://www.iflyrec.com/html/translate.html'>讯飞听见</a> 翻译👇</span><br/>`;
resultContainer.appendChild(document.createTextNode(text));
element.after(resultContainer);
});
});
}
/**
* translateDescText 函数:将指定的文本发送到讯飞的翻译服务进行翻译。
* @param {string} text - 需要翻译的文本。
* @param {function} callback - 翻译完成后的回调函数,该函数接受一个参数,即翻译后的文本。
*/
function translateDescText(text, callback) {
// 使用 GM_xmlhttpRequest 函数发送 HTTP 请求
GM_xmlhttpRequest({
method: "POST", // 请求方法为 POST
url: "https://www.iflyrec.com/TranslationService/v1/textTranslation", // 请求的 URL
headers: { // 请求头
'Content-Type': 'application/json',
'Origin': 'https://www.iflyrec.com',
},
data: JSON.stringify({
"from": "2",
"to": "1",
"contents": [{
"text": text,
"frontBlankLine": 0
}]
}), // 请求的数据
responseType: "json", // 响应的数据类型为 JSON
onload: (res) => {
try {
const { status, response } = res;
const translatedText = (status === 200) ? response.biz[0].translateResult : "翻译失败";
callback(translatedText);
} catch (error) {
console.error('翻译失败', error);
callback("翻译失败");
}
},
onerror: (error) => {
console.error('网络请求失败', error);
callback("网络请求失败");
}
});
}
/**
* transBySelector 函数:通过 CSS 选择器找到页面上的元素,并将其文本内容替换为预定义的翻译。
*/
function transBySelector() {
// 获取当前页面的翻译规则,如果没有找到,那么使用公共的翻译规则
let res = (I18N[lang][page]?.selector || []).concat(I18N[lang]['public'].selector || []); // 数组
// 如果找到了翻译规则
if (res.length > 0) {
// 遍历每个翻译规则
for (let [selector, translation] of res) {
// 使用 CSS 选择器找到对应的元素
let element = document.querySelector(selector)
// 如果找到了元素,那么将其文本内容替换为翻译后的文本
if (element) {
element.textContent = translation;
}
}
}
}
function registerMenuCommand() {
const toggleRegExp = () => {
enable_RegExp = !enable_RegExp;
GM_setValue("enable_RegExp", enable_RegExp);
GM_notification(`已${enable_RegExp ? '开启' : '关闭'}正则功能`);
if (enable_RegExp) {
location.reload();
}
GM_unregisterMenuCommand(id);
id = GM_registerMenuCommand(`${enable_RegExp ? '关闭' : '开启'}正则功能`, toggleRegExp);
};
let id = GM_registerMenuCommand(`${enable_RegExp ? '关闭' : '开启'}正则功能`, toggleRegExp);
}
/**
* init 函数:初始化翻译功能。
*/
function init() {
setupReactGlobalNavTranslation();
// 获取当前页面的翻译规则
page = getPage();
console.log(`开始page= ${page}`);
// 翻译页面标题
transTitle();
if (page) {
// 立即翻译页面
traverseNode(document.body);
setTimeout(() => {
// 使用 CSS 选择器找到页面上的元素,并将其文本内容替换为预定义的翻译
transBySelector();
if (page === "repository") { //仓库简介翻译
transDesc(".f4.my-3");
} else if (page === "gist") { // Gist 简介翻译
transDesc(".gist-content [itemprop='about']");
}
}, 100);
}
// 监视页面变化
watchUpdate();
}
// 执行初始化
registerMenuCommand();
init();
})(window, document);