|
| 1 | +(() => { |
| 2 | + const script = document.currentScript; |
| 3 | + const scriptUrl = new URL( |
| 4 | + script?.getAttribute("src") ?? "javascripts/language-switcher.js", |
| 5 | + window.location.href |
| 6 | + ); |
| 7 | + const siteBasePath = scriptUrl.pathname.replace(/\/javascripts\/language-switcher\.js$/, "/"); |
| 8 | + |
| 9 | + const trimSlashes = (value) => value.replace(/^\/+|\/+$/g, ""); |
| 10 | + const withTrailingSlash = (value) => value.endsWith("/") ? value : `${value}/`; |
| 11 | + const normalizePagePath = (pathname) => { |
| 12 | + const decoded = decodeURI(pathname) |
| 13 | + .replace(/\/index\.html$/, "/") |
| 14 | + .replace(/\.html$/, "/"); |
| 15 | + return withTrailingSlash(decoded); |
| 16 | + }; |
| 17 | + const sitePath = (relativePath) => { |
| 18 | + const clean = trimSlashes(relativePath); |
| 19 | + return `${siteBasePath}${clean ? `${clean}/` : ""}`.replace(/\/{2,}/g, "/"); |
| 20 | + }; |
| 21 | + const currentRelativePath = () => { |
| 22 | + const pathname = normalizePagePath(window.location.pathname); |
| 23 | + return pathname.startsWith(siteBasePath) |
| 24 | + ? trimSlashes(pathname.slice(siteBasePath.length)) |
| 25 | + : trimSlashes(pathname); |
| 26 | + }; |
| 27 | + const languageTarget = (language) => { |
| 28 | + const current = currentRelativePath(); |
| 29 | + |
| 30 | + if (language === "en") { |
| 31 | + if (!current || current === "zh/home") { |
| 32 | + return sitePath(""); |
| 33 | + } |
| 34 | + if (current === "zh") { |
| 35 | + return sitePath("en"); |
| 36 | + } |
| 37 | + if (current.startsWith("zh/")) { |
| 38 | + return sitePath(`en/${current.slice(3)}`); |
| 39 | + } |
| 40 | + return sitePath(current); |
| 41 | + } |
| 42 | + |
| 43 | + if (language === "zh") { |
| 44 | + if (!current) { |
| 45 | + return sitePath("zh/home"); |
| 46 | + } |
| 47 | + if (current === "en") { |
| 48 | + return sitePath("zh"); |
| 49 | + } |
| 50 | + if (current.startsWith("en/")) { |
| 51 | + return sitePath(`zh/${current.slice(3)}`); |
| 52 | + } |
| 53 | + return sitePath(current); |
| 54 | + } |
| 55 | + |
| 56 | + return sitePath(""); |
| 57 | + }; |
| 58 | + const applyLanguageTargets = () => { |
| 59 | + for (const link of document.querySelectorAll('a[hreflang="en"], a[hreflang="zh"]')) { |
| 60 | + const language = link.getAttribute("hreflang"); |
| 61 | + link.setAttribute("href", languageTarget(language)); |
| 62 | + } |
| 63 | + }; |
| 64 | + |
| 65 | + if (window.document$?.subscribe) { |
| 66 | + window.document$.subscribe(applyLanguageTargets); |
| 67 | + } else { |
| 68 | + document.addEventListener("DOMContentLoaded", applyLanguageTargets); |
| 69 | + applyLanguageTargets(); |
| 70 | + } |
| 71 | +})(); |
0 commit comments