Translating beta
by Outrora
HTML
<!DOCTYPE html>
<html lang="en" dir="ltr">
<head>
<meta charset="utf-8">
<title></title>
</head>
<body>
<div class="message"></div>
<div class="title translate-text">
What is this ? Head, and what is this ? Shoulder
<h1 class="translate-text">This is a real nice title</h1>
</div>
<hr/>
<div class="body translate-all translate-text">
This is a childNode[0]
<p>Here we have the main subject of this page man!</p>
<p>Everything here should be translated</p>
<p>We are using translate-all</p>
</div>
<hr/>
<div class="foot translate-all">
<p>Foots are used to have ads on it, so no one cares</p>
</div>
</body>
</html>
JavaScript
let translate = {
from: 'enUS',
to: 'ptBR'
}
let textsToTranslate = [
// { type: 'first-line', element: '', originalText: ''}
]
let translatedTexts = [
// { type: 'first-line', element: '', originalText: '', translatedText: '' }
]
function getTextsToTranslate() {
let translateText = document.querySelectorAll('.translate-text')
let translateAll = document.querySelectorAll('.translate-all')
//it filters each child of the father, removing all unecessary content
translateAll = Array.from(translateAll).map((father) => {
let children = father.children
return Array.from(children).filter(child => {
if (!child.textContent) return false
return child.textContent.search(/[a-z0-9]/gi) !== -1 ? true : false
})
})
//it goes through each child and fix the content,
//removing new lines and duplicated space.
//And append the result to be translated later on
for (let father of translateAll) {
for (let child of father ) {
let originalText = child.textContent
.replace(/\s$/gm, '').replace(/(\n)|(\r)|(\t)/gm, ' ')
.replace(/\s{2,*}/gm, ' ').trim()
textsToTranslate.push({
type: 'all',
element: child,
originalText
})
}
}
//get the childNode[0] of the class .translate-text
//remove craps, and put it inside an object to translate later on
for (let ele of translateText) {
let originalText = ele.innerText.split(/\n|\r|\t/gm)[0].trim()
textsToTranslate.push({
type: 'text',
element: ele.childNodes[0],
originalText
})
}
//it goes through each pendences to translate then and append
//the result inside the atribute translatedText
for (let ele of textsToTranslate) {
// console.log('findPath: ',findPath(ele.originalText))
ele.translatedText = findPath(ele.originalText)
}
//put translated text in the DOM
for (let ele of textsToTranslate) {
if (ele.type === 'text') {
console.log(ele.element)
ele.element.textContent = ele.translatedText.ptBR
}...