fix: Optimized text scanning logic

This commit is contained in:
Gabe
2025-10-25 17:46:29 +08:00
parent d56bd2920f
commit c0dce5c0b1

View File

@@ -77,7 +77,7 @@ export class Translator {
"VIDEO", "VIDEO",
]), ]),
INLINE: new Set([ INLINE: new Set([
"A", // "A",
"ABBR", "ABBR",
"ACRONYM", "ACRONYM",
"B", "B",
@@ -106,7 +106,7 @@ export class Translator {
"SCRIPT", "SCRIPT",
"SELECT", "SELECT",
"SMALL", "SMALL",
"SPAN", // "SPAN",
"STRONG", "STRONG",
"SUB", "SUB",
"SUP", "SUP",
@@ -223,6 +223,7 @@ export class Translator {
if (Translator.TAGS.INLINE.has(el.nodeName)) return false; if (Translator.TAGS.INLINE.has(el.nodeName)) return false;
if (Translator.TAGS.BLOCK.has(el.nodeName)) return true; if (Translator.TAGS.BLOCK.has(el.nodeName)) return true;
if (el.attributes?.display?.value?.includes("inline")) return false;
if (Translator.displayCache.has(el)) { if (Translator.displayCache.has(el)) {
return Translator.displayCache.get(el); return Translator.displayCache.get(el);
@@ -233,11 +234,22 @@ export class Translator {
return isBlock; return isBlock;
} }
// 判断是否包含块级子元素
static hasBlockNode(el) {
if (!Translator.isElementOrFragment(el)) return false;
for (const child of el.childNodes) {
if (Translator.isBlockNode(child)) {
return true;
}
}
return false;
}
// 判断是否直接包含非空文本节点 // 判断是否直接包含非空文本节点
static hasTextNode(el) { static hasTextNode(el) {
if (!Translator.isElementOrFragment(el)) return false; if (!Translator.isElementOrFragment(el)) return false;
for (const node of el.childNodes) { for (const child of el.childNodes) {
if (node.nodeType === Node.TEXT_NODE && /\S/.test(node.nodeValue)) { if (child.nodeType === Node.TEXT_NODE && /\S/.test(child.nodeValue)) {
return true; return true;
} }
} }
@@ -795,18 +807,20 @@ export class Translator {
return; return;
} }
let hasBlock = false; const hasBlock = Translator.hasBlockNode(rootNode);
for (const child of rootNode.children) {
const isBlock = Translator.isBlockNode(child);
if (isBlock) {
hasBlock = true;
this.#scanNode(child);
}
}
if (hasText || !hasBlock) { if (hasText || !hasBlock) {
this.#startObserveNode(rootNode); this.#startObserveNode(rootNode);
} }
if (hasBlock) {
for (const child of rootNode.children) {
const isBlock = Translator.isBlockNode(child);
if (!hasText || isBlock) {
this.#scanNode(child);
}
}
}
} }
// 处理一个待翻译的节点 // 处理一个待翻译的节点