Skip to content

Commit

Permalink
fix: duplicate translate
Browse files Browse the repository at this point in the history
if p inside of li, the content will be translate twice, so instead of
find the element that need to be translate, find the text need to be
translate first, then find the closest element that need to be
translate to avoid this problem.
  • Loading branch information
shana0440 committed May 26, 2023
1 parent bfc5c07 commit b702bdc
Showing 1 changed file with 35 additions and 35 deletions.
70 changes: 35 additions & 35 deletions content.ts
Original file line number Diff line number Diff line change
@@ -1,53 +1,53 @@
import { injectAfter } from "~app/injector"

interface TagForTranslateElements {
elements: NodeListOf<HTMLElement>
tag: keyof HTMLElementTagNameMap
}

const TRANSLATED_KEY = "translated"

chrome.runtime.onMessage.addListener(({ language }) => {
const heads = document.querySelectorAll<HTMLHeadElement>(
Array.apply(null, Array(6))
.map((_, index) => `h${index + 1}`)
.join(",")
)
const paragraphs = document.querySelectorAll<HTMLParagraphElement>(`p`)
const items = document.querySelectorAll<HTMLLIElement>(`li`)
const translateElements: TagForTranslateElements[] = [
{
elements: heads,
tag: "p"
},
{
elements: paragraphs,
tag: "p"
},
{
elements: items,
tag: "li"
}
]
const textNodes = getTextNodes(document.body)

translateElements.forEach(({ elements, tag }) => {
getLeafNodes(elements).forEach((it) => {
if (it.dataset[TRANSLATED_KEY]) {
return
}
textNodes.forEach((it) => {
const translateElement = getTranslatableElement(it.parentElement)
if (!translateElement || translateElement.dataset[TRANSLATED_KEY]) {
return
}
translateElement.dataset[TRANSLATED_KEY] = "true"
getLeafNodes([translateElement]).forEach((it) => {
chrome.runtime.sendMessage({ text: it.innerText, language }, (resp) => {
const injectedNode = injectAfter(it, tag, resp.text)
const injectedNode = injectAfter(it, "p", resp.text)
injectedNode.classList.add(...translateElement.classList)
injectedNode.dataset[TRANSLATED_KEY] = "true"
it.dataset[TRANSLATED_KEY] = "true"
})
})
})
})

function getTextNodes(el: Node) {
var n: Node,
a: Node[] = [],
walk = document.createTreeWalker(el, NodeFilter.SHOW_TEXT, null)
while ((n = walk.nextNode())) {
if (n.textContent?.trim() !== "") {
a.push(n)
}
}
return a
}

function getTranslatableElement(el: HTMLElement): HTMLElement | null {
const tags = ["h1", "h2", "h3", "h4", "h5", "h6", "p", "li"]
const element = tags.reduce<HTMLElement | null>((acc, tag) => {
if (acc) {
return acc
}
return el.closest(tag)
}, null)
return element
}

function getLeafNodes(
nodes: NodeListOf<HTMLElement> | NodeListOf<ChildNode>,
nodes: HTMLElement[] | NodeListOf<ChildNode>,
result = []
) {
): HTMLElement[] {
for (var i = 0, length = nodes.length; i < length; i++) {
const isLeaf = [...nodes[i].childNodes].some(
(it) => it.nodeType === Node.TEXT_NODE && (it as Text).data.trim() !== ""
Expand Down

0 comments on commit b702bdc

Please sign in to comment.