Repository navigation
Expand file tree
/
Copy pathmain.user.js
More file actions
1565 lines (1401 loc) · 60.7 KB
/
Copy pathmain.user.js
File metadata and controls
1565 lines (1401 loc) · 60.7 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
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// ==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.4.6-2026-11-15
// @author 沙漠之子
// @license GPL-3.0
// @match https://github.com/*
// @match https://skills.github.com/*
// @match https://gist.github.com/*
// @match https://education.github.com/*
// @match https://www.githubstatus.com/*
// @require https://raw.githubusercontent.com/maboloshi/github-chinese/gh-pages/locals.js?v1.9.4.6-2026-11-15
// @run-at document-start
// @grant GM_addStyle
// @grant GM_xmlhttpRequest
// @grant GM_getValue
// @grant GM_setValue
// @grant GM_registerMenuCommand
// @grant GM_unregisterMenuCommand
// @grant GM_notification
// @connect fanyi.iflyrec.com
// @supportURL https://github.com/maboloshi/github-chinese/issues
// ==/UserScript==
(function (window, document, undefined) {
'use strict';
/* =========================== 全局配置常量 =========================== */
const CONFIG = {
LANG: 'zh-CN', // 默认语言
DEV: false, // 默认不开启开发者模式
PAGE_MAP: { // 站点域名 -> 类型映射
'gist.github.com': 'gist',
'www.githubstatus.com': 'status',
'skills.github.com': 'skills',
'education.github.com': 'education'
},
DESC_SELECTORS: { // 简介元素的CSS选择器
repository: [
// 登录态是独立的 React 组件,类名形如 SidebarAbout-module_xxxx_description,
// 不含未登录态的 description__(#811)
'p[class*="SidebarAbout-module_"][class*="_description"]', // 登录态 React UI(issue #811)
'[class*="borderGrid__"] p[class*="description__"]', // 未登录/桌面 About 侧栏
].join(", "),
gist: ".gist-content [itemprop='about']"
},
OBSERVER_CONFIG: { // MutationObserver配置
childList: true,
subtree: true,
characterData: true,
attributeFilter: ['value', 'placeholder', 'aria-label', 'data-confirm']
},
TRANS_ENGINES: { // 翻译引擎配置
iflyrec: {
name: '讯飞听见',
url: 'https://fanyi.iflyrec.com/text-translate',
url_api: 'https://fanyi.iflyrec.com/TJHZTranslationService/v2/textAutoTranslation',
method: 'POST',
headers: {
'Content-Type': 'application/json',
'Origin': 'https://fanyi.iflyrec.com'
},
getRequestData: (text) => ({
from: 2, // 英语
to: 1, // 简体中文
type: 1,
contents: [{ text: text }]
}),
responseIdentifier: 'biz[0]?.sectionResult[0]?.dst', // 翻译结果在响应中的路径
},
},
STYLES: `
/* 基础样式变量 */
:root {
--ghc-primary-color: #1b95e0;
--ghc-bg-color: #f8f9fa;
--ghc-border-color: #e1e4e8;
--ghc-button-bg: #f6f8fa;
}
/* 浅色主题样式(默认) */
.translate-button {
color: var(--ghc-primary-color);
font-size: small;
cursor: pointer;
margin-top: 5px;
display: inline-block;
}
.translation-result {
margin-top: 10px;
padding: 8px;
border: 1px solid var(--ghc-border-color);
background-color: var(--ghc-button-bg);
border-radius: 6px;
}
.translation-credit {
font-size: small;
color: var(--ghc-primary-color);
}
.translation-content {
margin-top: 5px;
white-space: pre-wrap;
}
/* 暗色主题适配 - 使用 prefers-color-scheme */
@media (prefers-color-scheme: dark) {
:root {
--ghc-primary-color: #58a6ff;
--ghc-bg-color: #0d1117;
--ghc-border-color: #30363d;
--ghc-button-bg: #21262d;
}
}
`
};
/* =========================== 状态管理器 =========================== */
const State = {
// 功能开关
featureSet: {
enable_RegExp: GM_getValue("enable_RegExp", true),
enable_transDesc: GM_getValue("enable_transDesc", true),
enable_missedTerms: GM_getValue("enable_missedTerms", false),
enable_onurlchange: false,
},
// 当前运行时状态
pageConfig: null, // 当前页面配置(null 表示无有效页面)
currentURL: window.location.href, // 当前页面URL
transEngine: 'iflyrec', // 当前翻译引擎
mutationObserver: null, // DOM变化观察器
observedBody: null, // 当前观察的页面主体
visitAction: null, // 当前 Turbo 访问动作:advance / replace / restore
idleSweep: null, // 恢复访问时的空闲补扫句柄
urlChangeHandler: null, // 存储URL变化处理器
dynamicMenus: {}, // 动态菜单ID记录
pendingMutations: [], // 一帧内攒下的 mutation 记录
mutationFlush: null, // 已排期的批次处理句柄
lastTraversal: null, // 最近一次全量遍历的 {url, body},避免同一次载入遍历两遍
};
/* =========================== 安全检查 =========================== */
/**
* 检查词库文件是否加载 — 未加载则抛出错误阻止继续执行
*/
function checkI18NLoaded() {
if (typeof I18N === 'undefined') {
alert('GitHub 汉化插件:词库文件 locals.js 未加载,脚本无法运行!');
throw new Error('[GitHub 中文化插件] 词库文件 locals.js 未加载');
}
}
/**
* 错误边界 — 包装函数,捕获异常避免阻断页面正常使用
* @param {Function} fn - 要执行的函数
* @param {string} label - 错误标签
* @returns {Function} 包装后的函数
*/
function safe(fn, label) {
return function (...args) {
try {
return fn.apply(this, args);
} catch (e) {
console.error(`[GitHub 中文化插件] ${label} 出错:`, e);
}
};
}
/* =========================== 初始化入口 =========================== */
function init() {
checkI18NLoaded();
initLangEnv();
injectStyles();
setupMenuCommands();
watchReactCommits();
setupInitTrans();
setupUrlChangeListener();
setupTurboEvents();
}
/**
* 初始化并保护中文语言环境
*/
function initLangEnv() {
// 设置初始语言
document.documentElement.lang = CONFIG.LANG;
// 监视语言属性变化,防止被改回英文
const langObserver = new MutationObserver(() => {
// 如果检测到语言被改回英文,重新设置
if (document.documentElement.lang === "en") {
document.documentElement.lang = CONFIG.LANG;
}
});
langObserver.observe(document.documentElement, { attributeFilter: ['lang'] });
}
/**
* 注入自定义样式到页面
*/
function injectStyles() {
GM_addStyle(CONFIG.STYLES);
}
/**
* 设置初始翻译
*
* 即使 @run-at document-start,Tampermonkey 注入脚本也可能晚于 DOMContentLoaded
*(扩展冷启动、bfcache 恢复等场景)。因此不能假设注册监听器时事件尚未触发:
* readyState 已是 interactive/complete 则直接执行,否则才注册一次性监听器。
*/
function setupInitTrans() {
function doInitTrans() {
applyPage('首次载入');
}
if (document.readyState === 'interactive' || document.readyState === 'complete') {
// 文档已就绪,直接执行
doInitTrans();
} else {
// 等待 DOMContentLoaded
window.addEventListener('DOMContentLoaded', doInitTrans, { once: true });
}
}
/* =========================== URL 变化监听 =========================== */
/**
* 设置URL变化监听器
* Tampermonkey 环境使用 onurlchange 事件,其他环境回退到 MutationObserver URL 检测
*/
function setupUrlChangeListener() {
// 合并同一轮历史事件,在当前事件结束后读取最终的 URL 与 body
let historyTimer = null;
function scheduleHistoryRefresh() {
if (historyTimer !== null) clearTimeout(historyTimer);
historyTimer = setTimeout(() => {
historyTimer = null;
handleUrlChange();
}, 0);
}
// 只处理同文档历史(Turbo/SPA 的 pushState 回退)。
// bfcache 的跨文档恢复不触发 popstate,而且 DOM 与观察器都原样还原,
// 缓存里的文字已经是译文——不需要也不应该再全量重翻,故不监听 pageshow。
window.addEventListener('popstate', scheduleHistoryRefresh);
// Tampermonkey 环境下 window.onurlchange 为 null(支持),其他环境为 undefined
if (State.featureSet.enable_onurlchange && window.onurlchange === null) {
// 创建URL变化处理函数
State.urlChangeHandler = function (event) {
console.log("URL变化检测 (Tampermonkey onurlchange)", event);
handleUrlChange();
};
window.addEventListener('urlchange', State.urlChangeHandler);
console.log("🛠️ 开发者模式:已启用 onurlchange 事件监听");
} else {
console.log("当前环境不支持 onurlchange 事件,使用传统URL检测方式");
}
}
/**
* 处理URL变化
*/
function handleUrlChange() {
const currentURL = window.location.href;
const sameRoute = currentURL.split('#')[0] === State.currentURL.split('#')[0];
// 同一路由且 body 未更换(含 bfcache 原样恢复):译文与观察器都还在,直接返回。
// 判断依据不是「有没有缓存」,而是 body 是否还是我们观察的那一个:
// Turbo 的快照恢复会替换 body(cloneNode 丢弃监听器),那种才需要重新遍历与挂载。
if (sameRoute && document.body === State.observedBody) {
State.currentURL = currentURL;
return;
}
handleTurboLoad();
}
/* =========================== Turbo 事件 =========================== */
/**
* 设置Turbo框架事件监听
* 处理GitHub的Turbolinks页面切换
*/
function setupTurboEvents() {
// Turbo 的访问动作:advance(点链接)/ replace / restore(前进后退)
document.addEventListener('turbo:visit', event => {
State.visitAction = event.detail?.action || null;
});
// 新 body 还没插入文档时就把观察器挂上去:
// React 水合把译文写回英文的那批变更,从第一帧就被接住
document.addEventListener('turbo:before-render', event => {
const newBody = event.detail?.newBody;
if (newBody) attachMutationObserver(newBody);
});
document.addEventListener('turbo:render', () => handleTurboLoad());
document.addEventListener('turbo:load', () => {
handleTurboLoad();
State.visitAction = null;
});
}
/**
* 恢复访问不必同步全量遍历:缓存快照里已经是译文,
* 水合回写的英文由预挂的观察器接住;再安排一次空闲补扫,
* 兜住「离开时还没翻完」的快照,同时不阻塞渲染。
*/
function scheduleIdleTraversal() {
if (State.idleSweep !== null) return;
const run = () => {
State.idleSweep = null;
// 等空闲期间又换页了:新导航已经负责过,别再扫一遍
if (State.observedBody !== document.body) return;
traversePage('恢复补扫');
};
if (typeof window.requestIdleCallback === 'function') {
State.idleSweep = window.requestIdleCallback(run, { timeout: 1500 });
} else {
State.idleSweep = setTimeout(run, 200);
}
}
/**
* 页面载入 / 导航时挂描述翻译按钮(非 React 页面,如 gist)。
*
* GitHub 仓库页同时渲染窄屏(NarrowOnly)与桌面侧栏(HideWhenNarrow)两份 About 描述,
* 由 CSS 决定显示哪一份;两份都要挂,否则宽屏没有按钮。
* 仓库页不在这里挂:SSR 树还没被 React 接管,插入节点会触发 hydration mismatch,
* 由 watchReactCommits 在 React 提交之后挂。
*/
function mountDescButton() {
if (!State.featureSet.enable_transDesc) return;
const descSelector = CONFIG.DESC_SELECTORS[State.pageConfig?.currentPageType];
if (!descSelector) return;
transDesc(descSelector);
}
/**
* React 提交之后补挂描述翻译按钮。
*
* GitHub 新版 UI 是 SSR HTML + 客户端 React app(React 19,react-core)。
* 载入时往 SSR 描述后面插按钮会造成 hydration mismatch,React 丢弃 SSR 树重渲染,按钮随之消失。
* react-core 在每次 root 提交后记 performance mark(react-root:commit:<app>),
* 以这个「提交结束」事件为准,提交后再挂。机制与实测见 docs/github-react.md。
* 浮层 / 下拉里后来渲染的描述不走 root 提交,由突变批次补挂(batchAddedDesc)。
*/
function watchReactCommits() {
if (typeof PerformanceObserver !== 'function') return;
try {
// Chromium 不支持 entryTypes + buffered 的组合(控制台会报错),
// 且该组合下 buffered 被忽略;只有单个 type 才能回放注册前的 mark。
new PerformanceObserver((list) => {
if (list.getEntries().some(entry => entry.name.startsWith('react-root:commit:'))) {
safe(mountDescButton, '描述翻译')();
}
}).observe({ type: 'mark', buffered: true });
} catch (e) {
console.error('[GitHub 中文化插件] React 提交监听失败:', e);
}
}
/**
* 处理Turbo页面加载事件
* 在新页面加载后执行必要的翻译
*/
function handleTurboLoad() {
applyPage('页面导航');
}
/* =========================== 页面应用入口 =========================== */
/**
* 应用当前页面 —— 首次载入与 Turbo 换页共用这一条路径。
*
* 两条路径曾经各写一份:首次载入不翻标题 / 选择器(晚注入时一直缺译文),
* Turbo 载入又会在同一次载入里把整棵树走两遍(DOMContentLoaded + turbo:load)。
* 现在统一到这里,由 hasFreshTraversal() 决定还要不要重走 DOM。
* @param {string} reason - 触发原因(用于调试日志)
*/
function applyPage(reason) {
if (!document.body) return;
State.currentURL = window.location.href;
updatePageConfig(reason);
// before-render 已经挂好的观察器直接沿用;没有页面配置时也要挂上
const preAttached = State.observedBody === document.body && !!State.mutationObserver;
if (!preAttached) setupMutationObserver();
const pageConfig = State.pageConfig;
if (!pageConfig) return;
// 恢复访问时快照里已是译文:交给预挂的观察器和空闲补扫,不做同步全量遍历
if (State.visitAction === 'restore' && preAttached) {
scheduleIdleTraversal();
} else if (!hasFreshTraversal()) {
traversePage('页面遍历');
}
safe(transTitle, '标题翻译')(); // 翻译页面标题
safe(transBySelector, '选择器翻译')(); // 通过选择器翻译特定元素
// 仓库页等 React 提交后再挂(watchReactCommits);gist 等非 React 页面载入即挂
if (pageConfig.currentPageType !== 'repository' || typeof PerformanceObserver !== 'function') {
safe(mountDescButton, '描述翻译')();
}
}
/**
* 全量遍历当前 body,成功后才记为「已遍历」;失败留给下一次导航重试
* @param {string} label - 错误标签
*/
function traversePage(label) {
try {
traverseNode(document.body);
markPageTraversed();
} catch (e) {
console.error(`[GitHub 中文化插件] ${label} 出错:`, e);
}
}
/**
* 当前 body 是否已按当前 URL 完整遍历过。
* DOMContentLoaded 与 turbo:load 会先后触发同一次页面载入,第二次不必再走一遍树;
* 两次之间的增量变化由 MutationObserver 负责,不依赖这里重扫。
*/
function hasFreshTraversal() {
return State.lastTraversal !== null
&& State.lastTraversal.body === document.body
&& State.lastTraversal.url === window.location.href;
}
/**
* 记录「当前 URL + body 已完整遍历」,供 hasFreshTraversal() 判定
*/
function markPageTraversed() {
State.lastTraversal = { url: window.location.href, body: document.body };
}
/* =========================== 页面配置管理 =========================== */
/**
* 更新页面配置 — 页面类型变化时重建 State.pageConfig
* 同一页面类型内只更新路径:词库、正则规则和翻译缓存都与具体路径无关,
* 站内翻页(议题列表、仓库之间)不必重新展开词库和重算前置过滤。
* @param {string} trigger - 触发更新的原因(用于调试)
*/
function updatePageConfig(trigger) {
const newType = detectPageType();
if (!newType) {
State.pageConfig = null;
} else if (newType !== State.pageConfig?.currentPageType) {
State.pageConfig = buildPageConfig(newType);
} else {
State.pageConfig.currentPath = window.location.pathname;
}
console.log(`【Debug】${trigger}触发, 页面类型为 ${State.pageConfig?.currentPageType}`);
}
/**
* 构建页面配置对象
* @param {string} pageType - 页面类型
* @returns {Object} 页面配置对象
*/
function buildPageConfig(pageType) {
const conf = I18N.conf;
const dict = I18N[CONFIG.LANG];
const pageDict = dict[pageType] || {};
// 合并公共('*')与页面特定的选择器列表
const pickSelectors = key => [...(conf[key]['*'] || []), ...(conf[key][pageType] || [])];
const regexpRules = [ // 合并公共和页面特定的正则规则
...(pageDict.regexp || []),
...(dict.public.regexp || [])
];
return {
currentPageType: pageType, // 当前页面类型
currentPath: window.location.pathname, // 当前路径
titleStaticDict: pageDict.title?.static || {},
titleRegexpRules: pageDict.title?.regexp || [],
staticDict: { // 合并公共和页面特定的静态词典
...dict.public.static,
...(pageDict.static || {})
},
regexpRules,
// 与 regexpRules 一一对应的「匹配时必然出现的字面量」,用于跳过不可能命中的规则
regexpPrefilters: regexpRules.map(([pattern]) => getRequiredLiteral(pattern)),
ignoreMutationSelectors: pickSelectors('ignoreMutationSelectorPage').join(', '), // 忽略的突变选择器
ignoreSelectors: pickSelectors('ignoreSelectorPage').join(', '), // 忽略的选择器
characterData: (conf.characterDataPage || []).includes(pageType), // 是否监视文本节点变化
transSelectors: [ // 翻译选择器规则
...(dict.public.selector || []),
...(pageDict.selector || [])
],
transCache: new Map(), // 当前页面类型的翻译结果缓存(文本 -> 译文/false)
};
}
/* =========================== 页面类型检测 =========================== */
/**
* 全局路由保留首段(与 rePagePath 的全局首段一致,并包含组织页别名 organizations)。
* 这些首段是站点固定路径,不可能是账号名 / 组织名。
*/
const RESERVED_ROOTS = new Set([
'home', 'dashboard', 'feed', 'copilot', 'spark', 'signup', 'account_verifications',
'login', 'logout', 'session', 'sessions', 'password_reset', 'orgs', 'organizations',
'explore', 'topics', 'notifications', 'watching', 'stars', 'issues', 'pulls', 'repos',
'search', 'trending', 'showcases', 'new', 'import', 'settings', 'installations',
'marketplace', 'apps', 'account', 'projects', 'redeem', 'discussions', 'collections',
'sponsors', 'sponsoring', 'github-copilot', 'codespaces', 'developer', 'features',
'security', 'sitemap', 'education', 'mcp', 'users',
]);
/**
* 当前页面对应的仓库(owner/repo),取自 GitHub 的 octolytics 元数据。
* Turbo 导航期间元数据会短暂缺失,调用方自行处理空串。
* @returns {string} 形如 "owner/repo" 的小写串;缺失时为空串
*/
function readRepositoryNwo() {
const content = document.head
.querySelector('meta[name="octolytics-dimension-repository_nwo"]')
?.content;
return (content || '').trim().toLowerCase();
}
/**
* 从 pathname 推断当前页面归属的账号 / 组织名。
* 保留首段(settings / notifications 等)是站点固定路径,返回 null。
* @returns {string|null} 小写的账号 / 组织名
*/
function getOwnerFromPath() {
const segments = window.location.pathname.toLowerCase().split('/').filter(Boolean);
if (!segments.length) return null;
if (segments[0] === 'orgs' || segments[0] === 'organizations') {
return segments[1] || null;
}
// notifications / settings / marketplace 这类保留路径的首段不是账号名
if (RESERVED_ROOTS.has(segments[0])) return null;
return segments[0];
}
/**
* Turbo 导航会暂时拿掉 analytics-location。
* 仅在元数据缺失或无法识别时按路径回退,已有元数据仍优先。
* 全局路由按完整首段排除,避免没有结尾锚点的 rePagePath 把 settings-tools 当成 settings。
*/
function isFallbackRepositoryPath(pathname) {
const segments = pathname.split('/');
if (segments.length < 3) return false;
const owner = segments[1];
const repo = segments[2];
function isSegment(segment) {
return /^[A-Za-z0-9._-]+$/.test(segment) && !/^\.+$/.test(segment);
}
if (!isSegment(owner) || !isSegment(repo)) return false;
if (RESERVED_ROOTS.has(owner.toLowerCase())) return false;
const extra = segments.slice(3);
const isRoot = extra.length === 0 || (extra.length === 1 && extra[0] === '');
if (isRoot) {
// /<org>/enterprise_plan 与 /<org>/sponsoring 属于组织路径,不是仓库根路径
const repoName = repo.toLowerCase();
return repoName !== 'enterprise_plan' && repoName !== 'sponsoring';
}
if (extra.some(segment => segment === '' || segment === '.' || segment === '..')) return false;
return I18N.conf.rePagePathRepo.test(pathname);
}
/**
* 检测当前页面类型
* @returns {string|boolean} 页面类型或false(如果未识别)
*/
function detectPageType() {
const { PAGE_MAP } = CONFIG;
const { hostname, pathname, search } = window.location;
// 基础配置
const site = PAGE_MAP[hostname] || 'github'; // 通过站点映射获取基础类型
const isLogin = document.body.classList.contains("logged-in");
const metaLocation = (document.head.querySelector('meta[name="analytics-location"]')?.content || '').trim();
const metaUsable = /\/<(?:user-name|org-login)>/.test(metaLocation);
// 页面特征检测
const isSession = document.body.classList.contains("session-authentication");
const isHomepage = pathname === '/' && site === 'github';
const isProfile = document.body.classList.contains("page-profile") || metaLocation === '/<user-name>';
// 元数据优先;Turbo 暂时拿掉 analytics-location 时再按仓库路径回退
const isRepository = /\/<user-name>\/<repo-name>/.test(metaLocation)
|| !!readRepositoryNwo()
|| (!metaUsable && isFallbackRepositoryPath(pathname));
const isOrganization = /\/<org-login>/.test(metaLocation) || /^\/(?:orgs|organizations)/.test(pathname);
let pageType;
// 根据页面特征确定页面类型
switch (true) { // 使用 switch(true) 模式处理多条件分支
case isSession: // 登录/认证页面
pageType = 'session-authentication';
break;
case site !== 'github': // 特殊站点(gist / status / skills / education)
pageType = site;
break;
case isProfile: { // 用户资料页面
const tabParam = new URLSearchParams(search).get('tab');
pageType = pathname.includes('/stars') ? 'page-profile/stars'
: tabParam ? `page-profile/${tabParam}`
: 'page-profile';
break;
}
case isHomepage: // 首页/仪表盘
pageType = isLogin ? 'dashboard' : 'homepage';
break;
case isRepository: { // 代码仓库页面
const repoMatch = pathname.match(I18N.conf.rePagePathRepo);
pageType = repoMatch ? `repository/${repoMatch[1]}` : 'repository';
break;
}
case isOrganization: { // 组织页面
const orgMatch = pathname.match(I18N.conf.rePagePathOrg);
pageType = orgMatch ? `orgs/${orgMatch[1] || orgMatch.slice(-1)[0]}` : 'orgs';
break;
}
default: { // 默认页面类型
const pathMatch = pathname.match(I18N.conf.rePagePath);
pageType = pathMatch ? (pathMatch[1] || pathMatch.slice(-1)[0]) : false;
}
}
// 验证页面类型是否有效
if (pageType === false || !I18N[CONFIG.LANG]?.[pageType]) {
const reason = pageType === false
? '路径未匹配任何页面规则'
: `词库中缺少 "${pageType}" 的翻译`;
console.warn('[i18n] %s', reason, {
url: window.location.href,
hostname,
pathname,
site,
pageType,
isLogin,
metaLocation
});
return false;
}
return pageType;
}
/* =========================== MutationObserver =========================== */
/**
* 批次里是否新增了描述节点(含包着描述的祖先子树)。
* react-root:commit 只覆盖 React root 的提交:浮层、下拉菜单、侧栏等运行时渲染
* 走的是普通状态更新,不会重新打 commit mark。这些新插入的描述节点只能靠这份
* 「新增节点」事件补挂(插入发生在 React 已渲染的 DOM 上,不会再触发 hydration mismatch)。
* @param {MutationRecord[]} batch
* @param {string} selector - 描述元素的选择器
* @returns {boolean}
*/
function batchAddedDesc(batch, selector) {
return batch.some(({ addedNodes }) =>
[...addedNodes].some(node =>
node.nodeType === 1 &&
(node.matches(selector) || node.querySelector(selector))));
}
/**
* 处理攒下的突变批次(一帧一次)
*/
function flushMutationBatch() {
State.mutationFlush = null;
if (!State.pendingMutations.length) return;
const batch = State.pendingMutations;
State.pendingMutations = [];
if (!State.pageConfig) return;
try {
processMutations(batch);
// 只有仓库首页会渲染 About 浮层;gist 等页面在载入时挂载即可
if (State.pageConfig.currentPageType === 'repository' &&
batchAddedDesc(batch, CONFIG.DESC_SELECTORS.repository)) {
mountDescButton();
}
} finally {
// 本次遍历产生的写入会再次进入观察器队列,若不丢弃,下一帧会重复遍历自己的译文。
// 这里的记录都来自同步执行的本次批次;页面自己的异步渲染在回调之后才会发生。
State.mutationObserver?.takeRecords();
}
}
/**
* 安排一次批次处理;没有 requestAnimationFrame 的环境(测试/极老浏览器)
* 保持同步处理,避免行为变化。
*/
function scheduleMutationFlush() {
if (State.mutationFlush) return;
if (typeof window.requestAnimationFrame === 'function') {
const id = window.requestAnimationFrame(flushMutationBatch);
State.mutationFlush = {
cancel() {
window.cancelAnimationFrame?.(id);
},
};
} else {
flushMutationBatch();
}
}
/**
* 换 body 时丢弃上一份文档攒下的突变,避免继续处理已断开的节点。
*/
function resetMutationBatch() {
State.pendingMutations = [];
if (State.mutationFlush) {
State.mutationFlush.cancel();
State.mutationFlush = null;
}
}
/**
* 创建DOM变化观察器
* 监听页面变化并触发翻译
*/
function createMutationObserver() {
return new MutationObserver(
safe((mutations) => {
const currentURL = window.location.href;
// 当没有 onurlchange 支持时,通过 Observer 检测 URL 变化
if (!State.urlChangeHandler && currentURL !== State.currentURL) {
State.currentURL = currentURL;
updatePageConfig("URL变化 (MutationObserver)");
}
State.pendingMutations.push(...mutations);
scheduleMutationFlush();
}, 'MutationObserver')
);
}
/**
* 把观察器挂到指定 body 上 — 允许传入尚未插入文档的新 body,
* 这样 Turbo 换 body 时,React 水合产生的那批变更从第一帧就被接住。
* @param {Element} body
*/
function attachMutationObserver(body) {
resetMutationBatch();
State.mutationObserver?.disconnect();
State.mutationObserver = createMutationObserver();
State.mutationObserver.observe(body, CONFIG.OBSERVER_CONFIG);
State.observedBody = body;
}
/**
* 设置DOM变化观察器(当前文档 body)
*/
function setupMutationObserver() {
State.observedBody = null;
if (!document.body) return;
attachMutationObserver(document.body);
}
/**
* 处理MutationObserver检测到的变化
* 收集突变节点、过滤忽略选择器、对祖先-后代关系去重,仅遍历顶层节点
* @param {Array} mutations - 变化记录数组
*/
function shouldIgnoreMutationNode(node) {
const element = node?.nodeType === Node.ELEMENT_NODE ? node : node?.parentElement;
if (!element) return true;
const ignoredSelectors = State.pageConfig?.ignoreMutationSelectors;
return !!(ignoredSelectors && element.closest?.(ignoredSelectors));
}
function processMutations(mutations) {
const { characterData } = State.pageConfig;
const nodesToProcess = new Set();
const collect = node => {
if (!shouldIgnoreMutationNode(node)) nodesToProcess.add(node);
};
// 收集需要处理的节点:新增节点、变化的属性、文本变化(页面开启时)
for (const { target, addedNodes, type } of mutations) {
if (type === 'childList') {
for (const node of addedNodes) collect(node);
} else if (type === 'attributes' || (type === 'characterData' && characterData)) {
collect(target);
}
}
// 祖先也在集合里时只遍历祖先:后代已在它的子树内,不必重复走
const topNodes = new Set();
for (const node of nodesToProcess) {
let ancestor = node.parentElement;
while (ancestor && !nodesToProcess.has(ancestor)) ancestor = ancestor.parentElement;
if (!ancestor) topNodes.add(node);
}
if (CONFIG.DEV) console.log("DOM变化(已过滤)", topNodes);
// 仅遍历顶层节点
topNodes.forEach(node => {
traverseNode(node);
});
}
/* =========================== DOM 遍历与节点处理 =========================== */
/**
* 面包屑里的账号名 / 仓库名是标识符,不是界面文案(#824)
* 例:github.com/community/community 不应显示成「社区 / 社区」
* @param {Element} element
* @returns {boolean} 是否应跳过该链接
*/
function isBreadcrumbIdentifierLink(element) {
if (element.tagName !== 'A') return false;
if (!element.closest?.('nav[data-component="Breadcrumbs"]')) return false;
const linkPath = element.pathname?.toLowerCase().replace(/\/+$/, '');
if (!linkPath) return false;
const repository = readRepositoryNwo();
if (repository) {
const [owner] = repository.split('/');
return linkPath === `/${owner}` || linkPath === `/${repository}`;
}
// 元数据缺失时按 pathname 推断:只有「/首段」是账号名时首项才是标识符;
// notifications / settings / marketplace 这类保留路径的首项是界面文案,不能拒翻。
const owner = getOwnerFromPath();
return !!owner && linkPath === `/${owner}`;
}
/**
* 遍历节点树并进行翻译
* @param {Node} rootNode - 要遍历的根节点
*/
function traverseNode(rootNode) {
const start = performance.now();
// 文本节点直接处理
if (rootNode.nodeType === Node.TEXT_NODE) {
handleTextNode(rootNode);
return;
}
// 忽略选择器在遍历期间不变,提到过滤器外,避免每个节点都读一遍配置
const ignoreSelectors = State.pageConfig.ignoreSelectors;
// 创建TreeWalker遍历节点树
const treeWalker = document.createTreeWalker(
rootNode,
NodeFilter.SHOW_ELEMENT | NodeFilter.SHOW_TEXT,
node => {
if (node.nodeType === Node.ELEMENT_NODE) {
if (ignoreSelectors && node.matches(ignoreSelectors)) {
return NodeFilter.FILTER_REJECT; // 跳过忽略的选择器
}
if (isBreadcrumbIdentifierLink(node)) {
return NodeFilter.FILTER_REJECT; // 跳过账号名 / 仓库名
}
}
return NodeFilter.FILTER_ACCEPT; // 接受其他节点
}
);
let currentNode;
// 遍历所有节点
while ((currentNode = treeWalker.nextNode())) {
if (currentNode.nodeType === Node.ELEMENT_NODE) {
handleElementNode(currentNode);
} else if (currentNode.nodeType === Node.TEXT_NODE) {
handleTextNode(currentNode);
}
}
// 性能监控
const duration = performance.now() - start;
if (duration > 10) {
console.log(`节点遍历耗时: ${duration.toFixed(2)}ms`);
}
}
/**
* 处理文本节点
* @param {Node} node - 文本节点
*/
function handleTextNode(node) {
if (node.length > 500) return; // 跳过长文本节点
// 文本域的子文本是它的默认值(用户内容),翻了就破坏编辑器内容(#727)
if (node.parentElement?.tagName === 'TEXTAREA') return;
transElementAttrs(node, 'data'); // 翻译文本内容
}
/**
* 处理元素节点
* @param {Element} node - 元素节点
*/
function handleElementNode(node) {
// 按标签分派;只有需要继续检查 tooltipped 的分支才走到末尾
switch (node.tagName) {
case "RELATIVE-TIME": { // 相对时间元素
if (node.shadowRoot) transTimeElement(node.shadowRoot);
return;
}
case "INPUT":
case "TEXTAREA": { // 输入框和文本域
// 标签本身已由通用遍历到达(不在忽略表里),这里只碰界面文案属性:
// 文本域的子文本是默认值,由 handleTextNode 拦截,不在这里处理。
//
// 注意:这段在 #774(2026-08 把 input/textarea 加进忽略表)之前一直是生效的,
// 后来被忽略表挡成死代码、改由旁路补翻;单管线重构后又回到这里。
// 它翻译 value 是长期行为,不是误留的死代码——不要因为“看起来走不到”就删。
transElementAttrs(node, 'ariaLabel'); // 可访问名称(占位符之外的屏幕阅读器文案)
if (/^(?:button|submit|reset)$/.test(node.type)) {
// value 是按钮文案;只有 submit 带 name 时它同时是原生表单的提交值,
// GitHub 现在基本不用原生表单提交,暂不特判——若遇到提交异常先查这里
transElementAttrs(node.dataset, 'confirm'); // 确认对话框文本
transElementAttrs(node, 'value'); // 值属性
} else {
transElementAttrs(node, 'placeholder'); // 占位符
}
return;
}
case "OPTGROUP": // 选项组
transElementAttrs(node, 'label'); // 标签文本
return;
case "BUTTON": // 按钮
transElementAttrs(node, [
'title',
'cancelConfirmText'
]);
transElementAttrs(node.dataset, [
'confirm', // 确认文本
'confirmText', // 确认按钮文本
'confirmCancelText', // 取消按钮文本
'disableWith', // 禁用提示
'visibleText'
]);
break;
case "A":
case "SPAN":
transElementAttrs(node, 'title'); // 标题提示
transElementAttrs(node.dataset, 'visibleText'); // 可见文本
break;
}
// 带有 tooltipped 样式的元素
if (typeof node.className === 'string' && node.className.includes('tooltipped')) {
transElementAttrs(node, 'ariaLabel');
}
}
/* =========================== 翻译功能 =========================== */
/**
* 翻译页面标题
*/
function transTitle() {
const { titleStaticDict, titleRegexpRules } = State.pageConfig;
const text = document.title;
let result = titleStaticDict[text];
// 静态词条未命中才跑正则
if (!result) {
for (const [pattern, replacement] of titleRegexpRules) {
const translated = text.replace(pattern, replacement);
if (translated !== text) {
result = translated;
break;
}
}
}
// 应用翻译结果
if (result) {
document.title = result;
}
}
/**
* 翻译时间元素
* @param {Element} element - 时间元素
*/
function transTimeElement(element) {
// 获取时间文本