MCPcopy
hub / github.com/Bistutu/FluentRead / autoTranslateEnglishPage

Function autoTranslateEnglishPage

entrypoints/main/trans.ts:78–162  ·  view source on GitHub ↗
()

Source from the content-addressed store, hash-verified

76
77// 自动翻译整个页面的功能
78export function autoTranslateEnglishPage() {
79 // 如果已经在翻译中,则返回
80 if (isAutoTranslating) return;
81
82 // 获取当前页面的语言(暂时注释,存在识别问题)
83 // const text = document.documentElement.innerText || '';
84 // const cleanText = text.replace(/[\s\u3000]+/g, ' ').trim().slice(0, 500);
85 // const language = detectlang(cleanText);
86 // console.log('当前页面语言:', language);
87 // const to = config.to;
88 // if (to.includes(language)) {
89 // console.log('目标语言与当前页面语言相同,不进行翻译');
90 // return;
91 // }
92 // console.log('当前页面非目标语言,开始翻译');
93
94 // 获取所有需要翻译的节点
95 const nodes = grabAllNode(document.body);
96 if (!nodes.length) return;
97
98 isAutoTranslating = true;
99
100 // 创建观察器
101 observer = new IntersectionObserver((entries, observer) => {
102 entries.forEach(entry => {
103 if (entry.isIntersecting && isAutoTranslating) {
104 const node = entry.target as Element;
105
106 // 去重
107 if (node.hasAttribute(TRANSLATED_ATTR)) return;
108
109 // 为节点分配唯一ID
110 const nodeId = `fr-node-${nodeIdCounter++}`;
111 node.setAttribute(TRANSLATED_ID_ATTR, nodeId);
112
113 // 保存原始内容
114 originalContents.set(nodeId, node.innerHTML);
115
116 // 标记为已翻译
117 node.setAttribute(TRANSLATED_ATTR, 'true');
118
119 if (config.display === styles.bilingualTranslation) {
120 handleBilingualTranslation(node, false);
121 } else {
122 handleSingleTranslation(node, false);
123 }
124
125 // 停止观察该节点
126 observer.unobserve(node);
127 }
128 });
129 }, {
130 root: null,
131 rootMargin: '50px',
132 threshold: 0.1 // 只要出现10%就开始翻译
133 });
134
135 // 开始观察所有节点

Callers 5

mainFunction · 0.90
autoTranslationEventFunction · 0.90
mountFloatingBallFunction · 0.90
handleFloatingBallClickFunction · 0.90

Calls 3

grabAllNodeFunction · 0.90
handleSingleTranslationFunction · 0.85

Tested by

no test coverage detected