diff --git a/custom.js b/custom.js index acfac3f..8b894a3 100644 --- a/custom.js +++ b/custom.js @@ -96,3 +96,67 @@ document.addEventListener("DOMContentLoaded", iniciar); } })(); + +/* Os métodos HTTP (GET, POST, PATCH...) são identificadores da API, não texto corrido: + traduzi-los muda o significado e ainda estoura a largura fixa da tag na navegação, que + passa a cobrir o nome da página. O tema não marca essas tags, então aqui elas recebem + `translate="no"` — respeitado tanto pelo tradutor embutido do Chrome quanto pelo Google + Tradutor. O método original fica guardado em `data-metodo` para o caso de a tradução + chegar antes desta marcação: aí o valor é devolvido e, já marcado, não traduz de novo. */ +(function () { + // .method-nav-pill: tag da navegação lateral. .method-pill: tag ao lado da URL do endpoint. + var SELETOR = ".method-nav-pill, .method-pill"; + var METODOS = /^(GET|POST|PUT|PATCH|DELETE|DEL|HEAD|OPTIONS)$/; + + /* O texto fica no elemento mais interno — no tema é um com as cores do método, e a + tradução ainda pode embrulhá-lo em . Escrever na raiz apagaria essa estrutura. */ + function elementoDoTexto(pill) { + var no = pill; + while (no.firstElementChild) no = no.firstElementChild; + return no; + } + + function protegerMetodos() { + var pills = document.querySelectorAll(SELETOR); + + Array.prototype.forEach.call(pills, function (pill) { + if (pill.getAttribute("translate") !== "no") { + pill.setAttribute("translate", "no"); + pill.classList.add("notranslate"); + } + + var texto = pill.textContent.trim(); + var original = pill.getAttribute("data-metodo"); + + if (original === null) { + // Só serve de referência se o que está na tela ainda for um método de verdade. + if (METODOS.test(texto)) pill.setAttribute("data-metodo", texto); + return; + } + + if (texto !== original) elementoDoTexto(pill).textContent = original; + }); + } + + function iniciar() { + protegerMetodos(); + + /* A navegação é re-renderizada a cada troca de página (SPA) e a tradução dispara muitas + mutações de uma vez; o quadro agrupa tudo em uma passada só. */ + var agendado = false; + new MutationObserver(function () { + if (agendado) return; + agendado = true; + requestAnimationFrame(function () { + agendado = false; + protegerMetodos(); + }); + }).observe(document.body, { childList: true, subtree: true }); + } + + if (document.body) { + iniciar(); + } else { + document.addEventListener("DOMContentLoaded", iniciar); + } +})();