|
| 1 | +function insertTranslationWidget() { |
| 2 | + const header = document.querySelector(".md-header__inner"); |
| 3 | + if (!header || document.getElementById("lang-select")) return; |
| 4 | + |
| 5 | + const select = document.createElement("select"); |
| 6 | + select.id = "lang-select"; |
| 7 | + select.style.marginLeft = "auto"; |
| 8 | + select.innerHTML = ` |
| 9 | + <option value="pt">PT</option> |
| 10 | + <option value="en">EN</option> |
| 11 | + <option value="es">ES</option> |
| 12 | + `; |
| 13 | + |
| 14 | + select.addEventListener("change", () => { |
| 15 | + translatePage(select.value); |
| 16 | + }); |
| 17 | + |
| 18 | + header.appendChild(select); |
| 19 | +} |
| 20 | + |
| 21 | +async function translateText(text, target) { |
| 22 | + try { |
| 23 | + const url = |
| 24 | + "https://translate.googleapis.com/translate_a/single?client=gtx&sl=auto&tl=" + |
| 25 | + target + |
| 26 | + "&dt=t&q=" + |
| 27 | + encodeURIComponent(text); |
| 28 | + const response = await fetch(url); |
| 29 | + if (!response.ok) return text; |
| 30 | + const data = await response.json(); |
| 31 | + return data[0]?.map((part) => part[0]).join("") || text; |
| 32 | + } catch (e) { |
| 33 | + console.error("Translation error", e); |
| 34 | + return text; |
| 35 | + } |
| 36 | +} |
| 37 | + |
| 38 | +async function translatePage(target) { |
| 39 | + const elements = document.querySelectorAll( |
| 40 | + "main .md-content p, main .md-content li" |
| 41 | + ); |
| 42 | + for (const el of elements) { |
| 43 | + const originalText = el.innerText.trim(); |
| 44 | + if (!originalText) continue; |
| 45 | + const translated = await translateText(originalText, target); |
| 46 | + el.innerText = translated; |
| 47 | + } |
| 48 | +} |
| 49 | + |
| 50 | +document$.subscribe(() => { |
| 51 | + insertTranslationWidget(); |
| 52 | +}); |
0 commit comments