Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
50 changes: 50 additions & 0 deletions docs/docs/javascripts/modify-lang-a-href.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,50 @@
window.addEventListener('DOMContentLoaded', function() {
// Handles language URL rewrites for:
// 1) Versioned docs (e.g. /v0.1.1/...).
// 2) Special channels such as /latest/.
// 3) Pages that already contain a language segment.
// 4) Root-level pages without explicit versioning.
const CONFIG = Object.freeze({
languages: ['en', 'zh'],
langSelector: 'a[hreflang="en"], a[hreflang="zh"]',
versionPattern: /^v?\d+(\.\d+)*$/i,
specialVersions: ['latest'],
});

const langAnchors = document.querySelectorAll(CONFIG.langSelector);
const currentPath = window.location.pathname || '/';
const hasTrailingSlash = currentPath.endsWith('/') && currentPath !== '/';
const rawSegments = currentPath.split('/').filter(Boolean);
let languageRemoved = false;
const sanitizedSegments = rawSegments.filter(function(segment) {
if (!languageRemoved && CONFIG.languages.includes(segment)) {
languageRemoved = true;
return false;
}
return true;
});
const insertIndex =
sanitizedSegments.length &&
(CONFIG.versionPattern.test(sanitizedSegments[0]) ||
CONFIG.specialVersions.includes(sanitizedSegments[0].toLowerCase()))
? 1
: 0;
const searchAndHash = (window.location.search || '') + (window.location.hash || '');

function buildLocalizedPath(lang) {
const segments = sanitizedSegments.slice();
segments.splice(insertIndex, 0, lang);
const basePath = '/' + segments.join('/');
const normalizedPath = segments.length ? basePath : '/';
const finalPath = hasTrailingSlash && normalizedPath !== '/' ? normalizedPath + '/' : normalizedPath;
return finalPath + searchAndHash;
}

langAnchors.forEach(function(anchor) {
const lang = anchor.getAttribute('hreflang');
if (!lang || !CONFIG.languages.includes(lang)) {
return;
}
anchor.setAttribute('href', buildLocalizedPath(lang));
});
});
1 change: 1 addition & 0 deletions docs/scripts/mkdocs_template.yml
Original file line number Diff line number Diff line change
Expand Up @@ -250,3 +250,4 @@ extra_javascript:
- javascripts/mathjax.js
- javascripts/polyfill.min.js
- javascripts/tex-mml-chtml.js
- javascripts/modify-lang-a-href.js