Skip to content

Commit 6aa19a9

Browse files
Prevent translating search results
1 parent f37905c commit 6aa19a9

File tree

2 files changed

+30
-3
lines changed

2 files changed

+30
-3
lines changed

docs/javascript/translate.js

Lines changed: 29 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -39,9 +39,9 @@ function showGoogleTranslateBar() {
3939

4040
// Add event listener to the language icon when the page loads
4141
document.addEventListener("DOMContentLoaded", function () {
42-
let headerTitle = document.querySelector(".md-header__title");
42+
const headerTitle = document.querySelector(".md-header__title");
4343
if (headerTitle) {
44-
let translateButton = document.createElement("button");
44+
const translateButton = document.createElement("button");
4545

4646
translateButton.innerHTML = translateSvg;
4747
translateButton.className = "md-header__button md-icon";
@@ -57,3 +57,30 @@ document.addEventListener("DOMContentLoaded", function () {
5757
);
5858
}
5959
});
60+
61+
// Search container is added dynamically by mkdocs when search is opened.
62+
// So we need to listen to dom updates to detect the search container.
63+
const observer = new MutationObserver((mutations) => {
64+
mutations.forEach((mutation) => {
65+
console.log(mutation);
66+
if (mutation.addedNodes.length) {
67+
mutation.addedNodes.forEach((node) => {
68+
if (
69+
node.nodeType === 1 &&
70+
node.classList.contains("DocSearch-Container")
71+
) {
72+
// Prevent translating everything inside that component by adding class "notranslate".
73+
// It should be enough to prevent everything inside the component to be translated.
74+
node.classList.add("notranslate");
75+
}
76+
});
77+
}
78+
});
79+
});
80+
const config = { childList: true, subtree: true };
81+
const targetNode = document.body;
82+
observer.observe(targetNode, config);
83+
// Stop observing when the page is unloaded
84+
window.addEventListener("beforeunload", function () {
85+
observer.disconnect();
86+
});

overrides/partials/search.html

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1 +1 @@
1-
<div id="docsearch"></div>
1+
<div id="docsearch"></div>

0 commit comments

Comments
 (0)