From c0dce5c0b15a360ba3397849ddd08612cba9f4e3 Mon Sep 17 00:00:00 2001 From: Gabe Date: Sat, 25 Oct 2025 17:46:29 +0800 Subject: [PATCH] fix: Optimized text scanning logic --- src/libs/translator.js | 38 ++++++++++++++++++++++++++------------ 1 file changed, 26 insertions(+), 12 deletions(-) diff --git a/src/libs/translator.js b/src/libs/translator.js index d57be34..9f2bb39 100644 --- a/src/libs/translator.js +++ b/src/libs/translator.js @@ -77,7 +77,7 @@ export class Translator { "VIDEO", ]), INLINE: new Set([ - "A", + // "A", "ABBR", "ACRONYM", "B", @@ -106,7 +106,7 @@ export class Translator { "SCRIPT", "SELECT", "SMALL", - "SPAN", + // "SPAN", "STRONG", "SUB", "SUP", @@ -223,6 +223,7 @@ export class Translator { if (Translator.TAGS.INLINE.has(el.nodeName)) return false; if (Translator.TAGS.BLOCK.has(el.nodeName)) return true; + if (el.attributes?.display?.value?.includes("inline")) return false; if (Translator.displayCache.has(el)) { return Translator.displayCache.get(el); @@ -233,11 +234,22 @@ export class Translator { 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) { if (!Translator.isElementOrFragment(el)) return false; - for (const node of el.childNodes) { - if (node.nodeType === Node.TEXT_NODE && /\S/.test(node.nodeValue)) { + for (const child of el.childNodes) { + if (child.nodeType === Node.TEXT_NODE && /\S/.test(child.nodeValue)) { return true; } } @@ -795,18 +807,20 @@ export class Translator { return; } - let hasBlock = false; - for (const child of rootNode.children) { - const isBlock = Translator.isBlockNode(child); - if (isBlock) { - hasBlock = true; - this.#scanNode(child); - } - } + const hasBlock = Translator.hasBlockNode(rootNode); if (hasText || !hasBlock) { this.#startObserveNode(rootNode); } + + if (hasBlock) { + for (const child of rootNode.children) { + const isBlock = Translator.isBlockNode(child); + if (!hasText || isBlock) { + this.#scanNode(child); + } + } + } } // 处理一个待翻译的节点