|
| 1 | +(function () { |
| 2 | + const userSelectedLang = localStorage.getItem("userSelectedLang"); |
| 3 | + const currentPath = window.location.pathname; |
| 4 | + |
| 5 | + if (userSelectedLang) { |
| 6 | + if (userSelectedLang === "en" && !currentPath.startsWith("/en/")) { |
| 7 | + const newPath = "/en" + (currentPath === "/" ? "" : currentPath); |
| 8 | + window.location.replace(newPath); |
| 9 | + return; |
| 10 | + } else if (userSelectedLang === "zh" && currentPath.startsWith("/en/")) { |
| 11 | + const newPath = currentPath.replace(/^\/en/, "") || "/"; |
| 12 | + window.location.replace(newPath); |
| 13 | + return; |
| 14 | + } |
| 15 | + return; |
| 16 | + } |
| 17 | + |
| 18 | + const userLang = ( |
| 19 | + navigator.language || |
| 20 | + navigator.userLanguage || |
| 21 | + "en" |
| 22 | + ).toLowerCase(); |
| 23 | + const langPrefix = userLang.split("-")[0]; |
| 24 | + |
| 25 | + if (langPrefix === "zh") { |
| 26 | + if (currentPath.startsWith("/en/")) { |
| 27 | + const newPath = currentPath.replace(/^\/en/, "") || "/"; |
| 28 | + window.location.replace(newPath); |
| 29 | + } |
| 30 | + } else { |
| 31 | + if (!currentPath.startsWith("/en/")) { |
| 32 | + const newPath = "/en" + (currentPath === "/" ? "" : currentPath); |
| 33 | + window.location.replace(newPath); |
| 34 | + } |
| 35 | + } |
| 36 | +})(); |
| 37 | + |
| 38 | +document.addEventListener("click", function (event) { |
| 39 | + const langSwitcher = event.target.closest(".md-select__link[hreflang]"); |
| 40 | + if (langSwitcher) { |
| 41 | + event.preventDefault(); |
| 42 | + |
| 43 | + const newLang = langSwitcher.getAttribute("hreflang"); |
| 44 | + localStorage.setItem("userSelectedLang", newLang); |
| 45 | + |
| 46 | + const currentPath = window.location.pathname; |
| 47 | + let newPath; |
| 48 | + |
| 49 | + if (newLang === "en") { |
| 50 | + newPath = currentPath.startsWith("/en/") |
| 51 | + ? currentPath |
| 52 | + : "/en" + (currentPath === "/" ? "" : currentPath); |
| 53 | + } else { |
| 54 | + newPath = currentPath.startsWith("/en/") |
| 55 | + ? currentPath.replace(/^\/en/, "") || "/" |
| 56 | + : currentPath; |
| 57 | + } |
| 58 | + |
| 59 | + const queryAndHash = window.location.search + window.location.hash; |
| 60 | + |
| 61 | + window.location.href = newPath + queryAndHash; |
| 62 | + } |
| 63 | +}); |
0 commit comments