// ==UserScript== // @name GitHub 中文化,汉化GitHub界面的部分菜单及内容🔥 // @namespace https://github.com/maboloshi/github-chinese // @description 中文化 GitHub 界面的部分菜单及内容 // @copyright https://261998.xyz // @icon https://github.githubassets.com/pinned-octocat.svg // @version 1.1 // @author https://chatshare.ren // @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://mirror.nju.edu.cn/github-chinese/locals.js?v=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:), * 以这个「提交结束」事件为准,提交后再挂。机制与实测见 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) { // //enterprise_plan 与 //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 === '/'; // 元数据优先;Turbo 暂时拿掉 analytics-location 时再按仓库路径回退 const isRepository = /\/\//.test(metaLocation) || !!readRepositoryNwo() || (!metaUsable && isFallbackRepositoryPath(pathname)); const isOrganization = /\//.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) { // 获取时间文本 const text = element.textContent; if (!text) return; // 移除时间文本中的"on" const result = text.replace(/\bon\s+/gi, (match, offset) => offset === 0 ? " " : ""); if (result !== text) { element.textContent = result; // 应用翻译 } } /** * 翻译元素的单个属性 * @param {Object} target - 元素对象或元素数据集 * @param {string} attrName - 要翻译的属性名 */ function transElementAttr(target, attrName) { const text = target[attrName]; if (!text) return; const result = transText(text); if (result) { target[attrName] = result; } } /** * 批量翻译元素的多个属性 * @param {Object} target - 元素对象或元素数据集 * @param {string|string[]} attrs - 要翻译的属性名或属性名数组 */ function transElementAttrs(target, attrs) { if (Array.isArray(attrs)) { for (const attrName of attrs) transElementAttr(target, attrName); } else { transElementAttr(target, attrs); } } /** * 通过选择器翻译特定元素 */ function transBySelector() { State.pageConfig.transSelectors?.forEach(([selector, result]) => { const element = document.querySelector(selector); if (element) { element.textContent = result; // 应用翻译 } }); } /** * 翻译文本内容 * @param {string} text - 要翻译的文本 * @returns {string|boolean} 翻译后的文本或 false */ function transText(text) { // 跳过不需要翻译的文本:不含英文字母和 , . 的文本一律不查词库 //(空文本、纯数字、纯中文都落在这里;有英文的文本才可能命中词条或正则) if (!/[a-zA-Z,.]/.test(text)) { return false; } // 清理文本:去除首尾空格和多余空白(\s 已覆盖不换行空格 \u00a0) const trimmedText = text.trim(); const cleanedText = trimmedText.replace(/\s+/g, ' '); // 获取翻译 const result = fetchTransResult(cleanedText); if (result && result !== cleanedText) { return text.replace(trimmedText, result); } return false; } // 单页翻译结果缓存上限:文本重复率高(导航、按钮、时间),缓存命中率远高于随机内容, // 上限只是防止长时间会话里无限增长。 const TRANS_CACHE_LIMIT = 5000; /** * 清空当前页面的翻译结果缓存 — 正则功能开关变化后必须调用, * 否则会命中「关闭正则时算出的未命中结果」而漏翻。 */ function resetTransCache() { if (State.pageConfig) State.pageConfig.transCache = new Map(); } /** * 提取正则规则「一旦匹配就必然出现在文本里」的字面量,用来跳过不可能命中的规则。 * 只认长度 >= 4 的纯字母连续段,并保守放弃以下情况: * - 带 i 标志(大小写不敏感,includes 会误判) * - 任意位置的 `|`(分支不共享字面量) * - 前后向断言 / 被可选量词修饰的组(字面量可能不出现) * - 字面量本身后跟可选量词(可能零次出现) * 返回 null 表示这条规则必须照常执行。 * @param {RegExp} pattern * @returns {string|null} */ function getRequiredLiteral(pattern) { if (!pattern || pattern.flags.includes('i')) return null; const source = pattern.source; if (source.includes('|')) return null; if (/\(\? char === '?' || char === '*' || char === String.fromCharCode(123); let best = ''; let run = ''; let inClass = false; const flush = end => { if (run.length >= 4 && !optional(source[end]) && run.length > best.length) { best = run; } run = ''; }; for (let i = 0; i < source.length; i += 1) { const char = source[i]; if (char === '\\') { if (!inClass) flush(i); // 转义序列不是字面量字母 i += 1; } else if (inClass) { if (char === ']') inClass = false; } else if (char === '[') { flush(i); inClass = true; } else if (char === ')') { if (optional(source[i + 1])) return null; // 整个组被可选量词修饰 flush(i); } else if (char === '(' || char === '^' || char === '$') { flush(i); } else if (/[A-Za-z]/.test(char)) { run += char; } else { flush(i); } } flush(source.length); return best || null; } /** * 从词库获取翻译 — 直接读取 State.pageConfig * @param {string} text - 要翻译的文本 * @returns {string|boolean} 翻译结果或 false */ function fetchTransResult(text) { if (!State.pageConfig) return false; const pageConfig = State.pageConfig; // 未命中词条记录依赖「每次查询都记账」,开启时绕开缓存以保证行为不变(仅开发者模式)。 const cache = State.featureSet.enable_missedTerms ? null : pageConfig.transCache; if (cache) { const cached = cache.get(text); if (cached !== undefined) return cached; } let result = false; // 静态词典查找 const staticResult = pageConfig.staticDict[text]; if (typeof staticResult === 'string') { result = staticResult; } else if (State.featureSet.enable_RegExp) { // 正则规则查找:先用「必然出现的字面量」跳过不可能命中的规则 const { regexpPrefilters, regexpRules } = pageConfig; for (let index = 0; index < regexpRules.length; index += 1) { const required = regexpPrefilters?.[index]; if (required && !text.includes(required)) continue; const [pattern, replacement] = regexpRules[index]; const translated = text.replace(pattern, replacement); if (translated !== text) { result = translated; break; } } } if (result !== false) { // 命中的词条可能还挂在未命中记录里:命中即清理 MissedTermsManager.cleanup(text, pageConfig.currentPath); } else if (State.featureSet.enable_missedTerms) { // 未命中才记账,并刷新菜单里的计数 MissedTermsManager.record(text, pageConfig.currentPath); refreshMenuStates(); } if (cache) { if (cache.size >= TRANS_CACHE_LIMIT) cache.clear(); cache.set(text, result); } return result; } /* =========================== 远程翻译 =========================== */ /** * 为每个还没挂载的描述元素添加翻译按钮 * @param {string} selector - 描述元素的选择器 */ function transDesc(selector) { for (const host of document.querySelectorAll(selector)) { // 按钮或翻译结果已在描述后面:重复调用不叠按钮 if (host.nextElementSibling?.matches('.translate-button, .translation-result')) { continue; } const button = document.createElement('div'); button.classList.add('translate-button'); button.textContent = '翻译'; button.addEventListener('click', () => handleTransClick(button, host)); host.after(button); } } /** * 处理翻译按钮点击事件 * @param {Element} button - 翻译按钮元素 * @param {Element} element - 要翻译的元素 */ function handleTransClick(button, element) { if (button.disabled) return; button.disabled = true; // 防止重复点击 const descText = element.textContent.trim(); if (!descText) { button.disabled = false; return; } // 发起远程翻译请求 requestRemoteTrans(descText) .then(result => { showTransResult(element, button, result); }) .catch(error => { console.error('翻译失败:', error); button.disabled = false; // 启用按钮以允许重试 }); } /** * 显示翻译结果 * @param {Element} element - 原始元素 * @param {Element} button - 翻译按钮 * @param {string} result - 翻译结果 */ function showTransResult(element, button, result) { const { name, url } = CONFIG.TRANS_ENGINES[State.transEngine]; // 创建结果容器 — 结构与不可信文本分离,防止 XSS const resultContainer = document.createElement('div'); resultContainer.className = 'translation-result'; resultContainer.innerHTML = ` 由 ${name} 翻译👇
`; // API 响应文本使用 textContent,禁止 HTML 解析 resultContainer.querySelector('.translation-content').textContent = result; // 移除按钮并显示结果 button.remove(); element.after(resultContainer); } /** * 请求远程翻译API * @param {string} text - 要翻译的文本 * @returns {Promise} 翻译结果 */ async function requestRemoteTrans(text) { const { url_api, method, headers, getRequestData, responseIdentifier } = CONFIG.TRANS_ENGINES[State.transEngine]; const requestData = getRequestData(text); // 使用GM_xmlhttpRequest发起跨域请求 const responseText = await new Promise((resolve, reject) => { GM_xmlhttpRequest({ method, url: url_api, headers, data: method === 'POST' ? JSON.stringify(requestData) : null, params: method === 'GET' ? requestData : null, // For GET requests timeout: 10000, // 10秒超时 onload: res => resolve(res.responseText), onerror: reject, }); }); // 从响应中提取翻译结果;解析失败与结果缺失都以 reject 结束 const result = getNestedProperty(JSON.parse(responseText), responseIdentifier); if (!result) throw new Error('翻译结果无效'); return result; } /** * 安全获取嵌套对象属性 * 支持路径格式如 'biz[0]?.sectionResult[0]?.dst' * - '?.' 在路径中作为可选链标记被忽略,实际按强制访问处理 * @param {Object} obj - 目标对象 * @param {string} path - 属性路径 * @returns {*} 属性值或 undefined */ function getNestedProperty(obj, path) { // 移除路径中的 ?. 标记(讯飞API返回的路径表示可选,但此处按强制处理) const cleanPath = path.replace(/\?\./g, '.'); return cleanPath.split('.').reduce((acc, part) => { if (!acc) return undefined; const match = part.match(/^(\w+)(?:\[(\d+)\])?$/); if (!match) return undefined; const key = match[1]; const index = match[2]; // 处理数组索引或对象属性 return index !== undefined ? acc[key]?.[index] : acc[key]; }, obj); } /* =========================== 未命中词条管理器 =========================== */ const MissedTermsManager = { /** * 未命中词条数据结构(简洁模式) * { * [pathname]: { * "原始文本1": "", * "原始文本2": "", * ... * } * } */ data: GM_getValue("missedTerms", {}), /** * 记录未命中词条 * @param {string} text - 未翻译的文本 * @param {string} path - 当前页面路径 */ record(text, path) { if (!path) return false; const bucket = this.data[path] || (this.data[path] = {}); if (text in bucket) return false; // 词条已存在 bucket[text] = ""; this.save(); return true; // 新增词条 }, /** * 清理已命中的词条 * @param {string} text - 已翻译的文本 * @param {string} path - 当前页面路径 */ cleanup(text, path) { const bucket = path ? this.data[path] : null; if (!bucket || !(text in bucket)) return false; delete bucket[text]; // 如果该路径下没有词条了,删除路径条目 if (Object.keys(bucket).length === 0) delete this.data[path]; this.save(); return true; }, /** * 清空所有词条 */ clearAll() { this.data = {}; this.save(); }, /** * 获取统计信息 * @returns {Object} 统计信息 */ getStats() { const paths = Object.keys(this.data); const totalTerms = paths.reduce((sum, path) => sum + Object.keys(this.data[path]).length, 0 ); return { totalPaths: paths.length, totalTerms: totalTerms }; }, /** * 导出数据 * @returns {Object} 导出数据 */ exportData() { const data = this.data; const stats = this.getStats(); return { metadata: { exportedAt: new Date().toISOString(), version: "1.0", ...stats }, data }; }, /** * 保存数据到存储 */ save() { GM_setValue("missedTerms", this.data); } }; /* =========================== 用户菜单 =========================== */ /** * 1. 动态菜单管理 */ function refreshMenuStates() { // 注销所有动态菜单 Object.values(State.dynamicMenus).forEach(id => GM_unregisterMenuCommand(id)); State.dynamicMenus = {}; // 仅开发者模式下显示未命中词条相关菜单 if (!CONFIG.DEV) return; // 切换菜单 const toggleLabel = `${State.featureSet.enable_missedTerms ? "禁用" : "启用"} 未命中词条记录`; State.dynamicMenus.toggle = GM_registerMenuCommand(toggleLabel, () => { const newState = !State.featureSet.enable_missedTerms; State.featureSet.enable_missedTerms = newState; GM_setValue("enable_missedTerms", newState); if (!newState) { MissedTermsManager.clearAll(); GM_notification("未命中词条记录已禁用,所有记录已清空"); } else { GM_notification("未命中词条记录已启用"); } refreshMenuStates(); }); // 启用 + 有词条时显示导出和清空菜单 if (State.featureSet.enable_missedTerms) { const stats = MissedTermsManager.getStats(); const hasData = stats.totalTerms > 0; if (hasData) { // 导出菜单 State.dynamicMenus.export = GM_registerMenuCommand( `📥 导出未命中词条 (${stats.totalTerms}条)`, () => { const exportData = MissedTermsManager.exportData(); const blob = new Blob([JSON.stringify(exportData, null, 2)], { type: "application/json" }); const url = URL.createObjectURL(blob); const a = document.createElement("a"); a.href = url; a.download = `GitHub_未命中词条_${new Date().toISOString().split('T')[0]}.json`; a.click(); URL.revokeObjectURL(url); } ); // 清空菜单 State.dynamicMenus.clear = GM_registerMenuCommand( "🗑️ 清空未命中词条", () => { if (confirm(`确定要清空所有未命中词条吗?\n共 ${stats.totalPaths} 个页面,${stats.totalTerms} 个词条`)) { MissedTermsManager.clearAll(); GM_notification("未命中词条记录已清空"); refreshMenuStates(); } } ); // 查看统计菜单 State.dynamicMenus.stats = GM_registerMenuCommand( "📊 查看统计", () => { const s = MissedTermsManager.getStats(); GM_notification({ title: "未命中词条统计", text: `页面数: ${s.totalPaths}\n词条数: ${s.totalTerms}`, timeout: 5000 }); } ); } } } /** * 2. 静态菜单创建 * @param {Object} config - 菜单配置 */ function createMenuCommand(config) { const { label, key, callback } = config; let menuId; // 生成菜单标签(根据当前状态) const getMenuLabel = () => `${State.featureSet[key] ? "禁用" : "启用"} ${label}`; // 切换功能状态 const toggle = () => { const newState = !State.featureSet[key]; // 保存到存储 GM_setValue(key, newState); State.featureSet[key] = newState; // 显示通知 GM_notification(`${label}已${newState ? '启用' : '禁用'}`); // 执行回调 callback?.(newState); // 重新注册菜单(更新标签) GM_unregisterMenuCommand(menuId); menuId = GM_registerMenuCommand(getMenuLabel(), toggle); }; // 初始注册菜单 menuId = GM_registerMenuCommand(getMenuLabel(), toggle); } /** * 3. 主菜单设置 */ function setupMenuCommands() { const menuConfigs = [ { label: "正则功能", key: "enable_RegExp", callback: (enabled) => { // 缓存里可能存着「关闭正则时算出的未命中结果」,切换后必须先失效 resetTransCache(); if (enabled && State.pageConfig) traversePage('菜单触发遍历'); } }, { label: "描述翻译", key: "enable_transDesc", callback: (enabled) => { if (enabled) { mountDescButton(); } else { // 禁用描述翻译,移除所有按钮;重新启用时再挂 document.querySelectorAll('.translate-button') .forEach(button => button.remove()); } } } ]; // 为每个配置创建静态菜单 menuConfigs.forEach(config => createMenuCommand(config)); // 初始化动态菜单 refreshMenuStates(); } /* =========================== 启动 =========================== */ init(); })(window, document);