|
| 1 | +// Version selector for mdBook |
| 2 | +// Reads versions.json and creates a dropdown in the menu bar |
| 3 | + |
| 4 | +(function() { |
| 5 | + 'use strict'; |
| 6 | + |
| 7 | + // Get current version from URL path |
| 8 | + function getCurrentVersion() { |
| 9 | + const path = window.location.pathname; |
| 10 | + const match = path.match(/^\/(v[\d.]+|latest)\//); |
| 11 | + return match ? match[1] : 'latest'; |
| 12 | + } |
| 13 | + |
| 14 | + // Fetch versions and create dropdown |
| 15 | + async function initVersionSelect() { |
| 16 | + try { |
| 17 | + const response = await fetch('/versions.json'); |
| 18 | + if (!response.ok) return; |
| 19 | + |
| 20 | + const versions = await response.json(); |
| 21 | + if (!versions || versions.length === 0) return; |
| 22 | + |
| 23 | + const currentVersion = getCurrentVersion(); |
| 24 | + |
| 25 | + // Create dropdown HTML |
| 26 | + const dropdown = document.createElement('div'); |
| 27 | + dropdown.className = 'version-select'; |
| 28 | + dropdown.innerHTML = ` |
| 29 | + <label for="version-selector">Version: </label> |
| 30 | + <select id="version-selector"> |
| 31 | + ${versions.map(v => `<option value="${v}" ${v === currentVersion ? 'selected' : ''}>${v}</option>`).join('')} |
| 32 | + </select> |
| 33 | + `; |
| 34 | + |
| 35 | + // Add change handler |
| 36 | + dropdown.querySelector('select').addEventListener('change', function(e) { |
| 37 | + const newVersion = e.target.value; |
| 38 | + const currentPath = window.location.pathname; |
| 39 | + const newPath = currentPath.replace(/^\/(v[\d.]+|latest)\//, `/${newVersion}/`); |
| 40 | + window.location.href = newPath; |
| 41 | + }); |
| 42 | + |
| 43 | + // Insert into menu bar |
| 44 | + const menuBar = document.querySelector('.left-buttons'); |
| 45 | + if (menuBar) { |
| 46 | + menuBar.appendChild(dropdown); |
| 47 | + } |
| 48 | + } catch (e) { |
| 49 | + console.log('Version selector not available:', e.message); |
| 50 | + } |
| 51 | + } |
| 52 | + |
| 53 | + // Run when DOM is ready |
| 54 | + if (document.readyState === 'loading') { |
| 55 | + document.addEventListener('DOMContentLoaded', initVersionSelect); |
| 56 | + } else { |
| 57 | + initVersionSelect(); |
| 58 | + } |
| 59 | +})(); |
0 commit comments