Skip to content

Commit 756c7f4

Browse files
committed
Refactor utility exports and update node handling in content scripts
- Reorganized exports in utils/index.ts to include new formatting functions and maintain a cleaner structure. - Removed the obsolete query.ts file to streamline the codebase. - Updated content scripts to replace handleNode with parseNode for improved readability and consistency in class naming conventions. - Adjusted CSS class names in injectcss.ts to follow camelCase convention for better alignment with JavaScript standards.
1 parent d17a3ae commit 756c7f4

File tree

9 files changed

+97
-96
lines changed

9 files changed

+97
-96
lines changed
Lines changed: 16 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,16 @@
1+
export const formatQueryText = (text: string) => {
2+
// 统一处理所有方括号引用格式:
3+
// - [12] 单个数字
4+
// - [1,2,3] 多个数字(无空格)
5+
// - [1, 2, 3] 多个数字(有空格)
6+
// - [citation needed] 引用需要
7+
// - [1-5] 数字范围
8+
// - [1, 2, 3; 4, 5] 复杂组合
9+
const citationRegex = /\[[^\]]*\]/g;
10+
let _text = text.replace(citationRegex, '').trim();
11+
_text = _text.replace(/\n\n/g, '\n');
12+
while (_text.includes('\n\n')) {
13+
_text = _text.replace('\n\n', '\n');
14+
}
15+
return _text;
16+
};
Lines changed: 11 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,11 @@
1+
export const formatTranslation = (translation: string) => {
2+
// 去掉 `[12]` 这种形式
3+
const regex = /\[(\d+)\]/g;
4+
// 去掉 `[citation needed]`
5+
const regex2 = /\[citation needed\]/g;
6+
// 在中文和英文之间添加空格
7+
const addSpaceBetweenChineseAndEnglish = (str: string) =>
8+
str.replace(/([a-zA-Z0-9])([\u4e00-\u9fa5])/g, '$1 $2').replace(/([\u4e00-\u9fa5])([a-zA-Z])/g, '$1 $2');
9+
10+
return addSpaceBetweenChineseAndEnglish(translation.replace(regex, '').replace(regex2, '').trim());
11+
};

packages/shared/lib/utils/index.ts

Lines changed: 5 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -1,8 +1,10 @@
1-
export * from './helpers.js';
21
export * from './colorful-logger.js';
3-
export * from './init-app-with-shadow.js';
4-
export * from './query.js';
2+
export * from './formatQueryText.js';
3+
export * from './formatTranslation.js';
4+
export * from './helpers.js';
55
export * from './ignoreHref.js';
6+
export * from './init-app-with-shadow.js';
67
export * from './is-chinese.js';
78
export * from './is-url.js';
9+
export * from './queryTranslation.js';
810
export type * from './types.js';

packages/shared/lib/utils/query.ts

Lines changed: 0 additions & 39 deletions
This file was deleted.
Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,10 @@
1+
import type { QueryRequest, QueryResponse } from './types.js';
2+
3+
export const queryTranslation = async (body: QueryRequest['body']): Promise<QueryResponse> => {
4+
const msgBody: QueryRequest = {
5+
func: 'QueryRequest',
6+
body,
7+
};
8+
const res = await chrome.runtime.sendMessage<QueryRequest, QueryResponse>(msgBody);
9+
return res;
10+
};

pages/content/src/checkBreakLineHappened.ts

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,4 @@
1-
import { forceBreakLineTagsUpper, forceBreakLineTags } from './handleNode';
1+
import { forceBreakLineTagsUpper, forceBreakLineTags } from './parseNode';
22

33
export const checkBreakLineHappened = (node: HTMLElement) => {
44
const computedStyle = window.getComputedStyle(node);

pages/content/src/contentStart.ts

Lines changed: 26 additions & 26 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,5 @@
1-
import { handleNode } from './handleNode';
21
import { injectCss } from './injectcss';
2+
import { parseNode } from './parseNode';
33
import { state } from './state';
44
import { ignoreHref } from '@extension/shared';
55
import type { AllMessage } from '@extension/shared';
@@ -20,43 +20,43 @@ export const contentStart = () => {
2020

2121
if (inspectingChanged) {
2222
console.log('inspectingChanged', inspecting);
23-
document.body.querySelectorAll('.rwkv_offline_target').forEach(node => {
24-
if (inspecting && !node.classList.contains('rwkv_inspecting')) {
25-
node.classList.add('rwkv_inspecting');
26-
} else if (!inspecting && node.classList.contains('rwkv_inspecting')) {
27-
node.classList.remove('rwkv_inspecting');
23+
document.body.querySelectorAll('.rwkvOfflineTarget').forEach(node => {
24+
if (inspecting && !node.classList.contains('rwkvInspecting')) {
25+
node.classList.add('rwkvInspecting');
26+
} else if (!inspecting && node.classList.contains('rwkvInspecting')) {
27+
node.classList.remove('rwkvInspecting');
2828
}
2929
});
30-
document.body.querySelectorAll('.rwkv_offline_translation_done').forEach(node => {
31-
if (inspecting && !node.classList.contains('rwkv_inspecting')) {
32-
node.classList.add('rwkv_inspecting');
33-
} else if (!inspecting && node.classList.contains('rwkv_inspecting')) {
34-
node.classList.remove('rwkv_inspecting');
30+
document.body.querySelectorAll('.rwkvOfflineTranslationDone').forEach(node => {
31+
if (inspecting && !node.classList.contains('rwkvInspecting')) {
32+
node.classList.add('rwkvInspecting');
33+
} else if (!inspecting && node.classList.contains('rwkvInspecting')) {
34+
node.classList.remove('rwkvInspecting');
3535
}
3636
});
37-
document.body.querySelectorAll('.rwkv_offline_translation_result').forEach(node => {
38-
if (inspecting && !node.classList.contains('rwkv_inspecting')) {
39-
node.classList.add('rwkv_inspecting');
40-
} else if (!inspecting && node.classList.contains('rwkv_inspecting')) {
41-
node.classList.remove('rwkv_inspecting');
37+
document.body.querySelectorAll('.rwkvOfflineTranslationResult').forEach(node => {
38+
if (inspecting && !node.classList.contains('rwkvInspecting')) {
39+
node.classList.add('rwkvInspecting');
40+
} else if (!inspecting && node.classList.contains('rwkvInspecting')) {
41+
node.classList.remove('rwkvInspecting');
4242
}
4343
});
44-
document.body.querySelectorAll('.rwkv_loading_spinner').forEach(node => {
45-
if (inspecting && !node.classList.contains('rwkv_inspecting')) {
46-
node.classList.add('rwkv_inspecting');
47-
} else if (!inspecting && node.classList.contains('rwkv_inspecting')) {
48-
node.classList.remove('rwkv_inspecting');
44+
document.body.querySelectorAll('.rwkvLoadingSpinner').forEach(node => {
45+
if (inspecting && !node.classList.contains('rwkvInspecting')) {
46+
node.classList.add('rwkvInspecting');
47+
} else if (!inspecting && node.classList.contains('rwkvInspecting')) {
48+
node.classList.remove('rwkvInspecting');
4949
}
5050
});
5151
}
5252

5353
if (runningChanged) {
5454
if (!running) {
55-
document.body.querySelectorAll('.rwkv_loading_spinner').forEach(node => {
55+
document.body.querySelectorAll('.rwkvLoadingSpinner').forEach(node => {
5656
node.remove();
5757
});
5858
} else {
59-
document.body.querySelectorAll('*').forEach(handleNode);
59+
document.body.querySelectorAll('*').forEach(parseNode);
6060
}
6161
}
6262
};
@@ -105,7 +105,7 @@ export const contentStart = () => {
105105

106106
const handleMouseOver = (event: MouseEvent) => {
107107
const target = event.target as HTMLElement;
108-
const isTarget = target.classList.contains('rwkv_offline_target');
108+
const isTarget = target.classList.contains('rwkvOfflineTarget');
109109

110110
if (isTarget && target && target.innerText) {
111111
const text = target.innerText.trim();
@@ -187,8 +187,8 @@ export const contentStart = () => {
187187
const addedNodes = Array.from(mutation.addedNodes);
188188
for (const addedNode of addedNodes) {
189189
if (addedNode.nodeType === 1) {
190-
const shouldHandleChildNodes = handleNode(addedNode);
191-
if (shouldHandleChildNodes) (addedNode as Element).querySelectorAll('*').forEach(handleNode);
190+
const shouldHandleChildNodes = parseNode(addedNode);
191+
if (shouldHandleChildNodes) (addedNode as Element).querySelectorAll('*').forEach(parseNode);
192192
}
193193
}
194194
}

pages/content/src/injectcss.ts

Lines changed: 12 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -1,61 +1,61 @@
11
export const injectCss = () => {
22
const style = document.createElement('style');
33
style.textContent = `
4-
.rwkv_loading_spinner {
4+
.rwkvLoadingSpinner {
55
display: inline-block;
66
width: 12px;
77
height: 12px;
88
border: 2px solid rgba(0, 0, 0, 0.1);
99
border-radius: 50%;
1010
border-top-color: currentColor;
11-
animation: rwkv_spin 1s ease-in-out infinite;
11+
animation: rwkvSpin 1s ease-in-out infinite;
1212
margin-left: 5px;
1313
vertical-align: middle;
1414
}
1515
16-
@keyframes rwkv_spin {
16+
@keyframes rwkvSpin {
1717
to {
1818
transform: rotate(360deg);
1919
}
2020
}
2121
22-
.rwkv_loading_spinner.rwkv_inspecting {
22+
.rwkvLoadingSpinner.rwkvInspecting {
2323
background-color: rgba(255, 0, 0, 0.5) !important;
2424
}
2525
26-
.rwkv_offline_target {
26+
.rwkvOfflineTarget {
2727
/* */
2828
}
2929
30-
.rwkv_offline_target.rwkv_inspecting {
30+
.rwkvOfflineTarget.rwkvInspecting {
3131
background-color: rgba(0, 255, 255, 0.5) !important;
3232
outline: 1px solid rgba(0, 255, 255, 1) !important;
3333
}
3434
35-
.rwkv_offline_translation_done {
35+
.rwkvOfflineTranslationDone {
3636
/* */
3737
}
3838
39-
.rwkv_offline_translation_done.rwkv_inspecting {
39+
.rwkvOfflineTranslationDone.rwkvInspecting {
4040
background-color: rgba(0, 0, 255, 0.5) !important;
4141
outline: 1px solid rgba(0, 0, 255, 1) !important;
4242
}
4343
44-
.rwkv_offline_translation_result {
44+
.rwkvOfflineTranslationResult {
4545
/* */
4646
}
4747
48-
.rwkv_offline_translation_result.rwkv_inspecting {
48+
.rwkvOfflineTranslationResult.rwkvInspecting {
4949
background-color: rgba(0, 255, 0, 0.5) !important;
5050
outline: 1px solid rgba(0, 255, 0, 1) !important;
5151
}
5252
5353
54-
.rwkv_offline_wrapper {
54+
.rwkvOfflineWrapper {
5555
/* */
5656
}
5757
58-
.rwkv_offline_wrapper.rwkv_inspecting {
58+
.rwkvOfflineWrapper.rwkvInspecting {
5959
background-color: rgba(255, 0, 0, 0.5) !important;
6060
outline: 1px solid rgba(255, 0, 0, 1) !important;
6161
}
Lines changed: 16 additions & 15 deletions
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,7 @@
11
import { checkBreakLineHappened } from './checkBreakLineHappened';
22
import { getPriority } from './getPriority';
33
import { state } from './state';
4-
import { ignoreHref, isChinese, isUrl, queryWS, formatTranslation } from '@extension/shared';
4+
import { formatTranslation, ignoreHref, isChinese, isUrl, queryTranslation } from '@extension/shared';
55

66
const ignoreTypeLower = ['path', 'script', 'style', 'svg', 'noscript', 'head', 'pre', 'code', 'math', 'textarea'];
77
const ignoreTypeUpper = ignoreTypeLower.map(item => item.toUpperCase());
@@ -15,7 +15,7 @@ let tick = 0;
1515
export const forceBreakLineTags = ['ul', 'ol', 'li'];
1616
export const forceBreakLineTagsUpper = forceBreakLineTags.map(item => item.toUpperCase());
1717

18-
export const handleNode = (_node: Node): boolean => {
18+
export const parseNode = (_node: Node): boolean => {
1919
const currentUrl = window.location.href;
2020
for (const href of ignoreHref) {
2121
const startWith = currentUrl.startsWith(href);
@@ -25,6 +25,7 @@ export const handleNode = (_node: Node): boolean => {
2525
const node = _node as HTMLElement;
2626
const nodeName = node.nodeName;
2727

28+
// eslint-disable-next-line @typescript-eslint/no-unused-vars
2829
const checking = checkingTypes.includes(nodeName);
2930

3031
if (!state.running) {
@@ -48,7 +49,7 @@ export const handleNode = (_node: Node): boolean => {
4849

4950
// if (checking) console.log({ nodeName, step: 2 });
5051

51-
if (parentNode.classList.contains('rwkv_offline_target')) return false;
52+
if (parentNode.classList.contains('rwkvOfflineTarget')) return false;
5253

5354
// if (checking) console.log({ nodeName, step: 3 });
5455

@@ -120,7 +121,7 @@ export const handleNode = (_node: Node): boolean => {
120121

121122
// if (checking) console.log({ nodeName, step: 8 });
122123

123-
if (node.classList.contains('rwkv_offline_translation_done')) return false;
124+
if (node.classList.contains('rwkvOfflineTranslationDone')) return false;
124125

125126
// if (checking) console.log({ nodeName, step: 9 });
126127

@@ -153,35 +154,35 @@ export const handleNode = (_node: Node): boolean => {
153154

154155
// if (checking) console.log({ nodeName, step: 11 });
155156

156-
node.classList.add('rwkv_offline_target');
157-
if (state.inspecting) node.classList.add('rwkv_inspecting');
157+
node.classList.add('rwkvOfflineTarget');
158+
if (state.inspecting) node.classList.add('rwkvInspecting');
158159
const breakLineHappened = checkBreakLineHappened(node);
159160
const nodeNameToBeAdded = breakLineHappened ? 'div' : 'span';
160161

161162
const loadingSpinner = document.createElement('span');
162-
if (node.querySelector('.rwkv_loading_spinner') === null) {
163-
loadingSpinner.classList.add('rwkv_loading_spinner');
164-
if (state.inspecting) loadingSpinner.classList.add('rwkv_inspecting');
163+
if (node.querySelector('.rwkvLoadingSpinner') === null) {
164+
loadingSpinner.classList.add('rwkvLoadingSpinner');
165+
if (state.inspecting) loadingSpinner.classList.add('rwkvInspecting');
165166
node.appendChild(loadingSpinner);
166167
}
167168

168169
const nodeToBeAdded = document.createElement(nodeNameToBeAdded);
169-
nodeToBeAdded.classList.add('rwkv_offline_translation_result');
170-
if (state.inspecting) nodeToBeAdded.classList.add('rwkv_inspecting');
170+
nodeToBeAdded.classList.add('rwkvOfflineTranslationResult');
171+
if (state.inspecting) nodeToBeAdded.classList.add('rwkvInspecting');
171172
const priority = getPriority(node);
172173
tick++;
173-
queryWS({ source: textContent, logic: 'translate', url: currentUrl, nodeName, priority, tick })
174+
queryTranslation({ source: textContent, logic: 'translate', url: currentUrl, nodeName, priority, tick })
174175
.then(json => {
175-
if (node.classList.contains('rwkv_offline_translation_done')) return;
176+
if (node.classList.contains('rwkvOfflineTranslationDone')) return;
176177

177178
const { translation, source } = json.body;
178179
if (translation && translation !== source) {
179180
let inner = formatTranslation(translation);
180181
if (!breakLineHappened) inner = ' ' + inner;
181182
nodeToBeAdded.textContent = inner;
182183
node.appendChild(nodeToBeAdded);
183-
node.classList.add('rwkv_offline_translation_done');
184-
if (state.inspecting) node.classList.add('rwkv_inspecting');
184+
node.classList.add('rwkvOfflineTranslationDone');
185+
if (state.inspecting) node.classList.add('rwkvInspecting');
185186
}
186187
})
187188
.finally(() => {

0 commit comments

Comments
 (0)