Skip to content

Instantly share code, notes, and snippets.

@deleteman
Last active December 19, 2022 11:01
Show Gist options
  • Save deleteman/7ead76f9221605c080ae8d9b98744d8a to your computer and use it in GitHub Desktop.
Save deleteman/7ead76f9221605c080ae8d9b98744d8a to your computer and use it in GitHub Desktop.
---
const VERSIONS = [
{title: "2.6.0", url: "/v2.6.0"},
{title: "2.7.0", url: "/v2.7.0"},
{title: "3.0.0", url: "/v3.0.0"},
{title: "3.1.1", url: ""}
]
---
<div class="container">
<select id="version-selector">
{VERSIONS.map( v => {
return <option value={ v.url } >v{v.title}</option>
})}
</select>
</div>
<script is:inline>
let currentVersion = ""
if(typeof window != "undefined") {
currentVersion = window.location.pathname.split("/")[1]
}
if(currentVersion && currentVersion.indexOf("v") != 0) currentVersion = "";
function updateLocation(evt) {
let selectedVersion = evt.target.value
let versionRegExp = /v[0-9]+.[0-9]+.[0-9]+/
let pathname = window.location.pathname.replace(/\/$/, "") //remove the trailing "/" if there is any
let pathParts = pathname.split("/")
if(pathname.match(versionRegExp)) {
pathParts[1] = selectedVersion.replace("/", "")
} else {
pathParts = [pathParts[0], selectedVersion.replace("/", ""), ...pathParts.slice(2)]
}
//when we're visiting the root of the default version, we ignore the "index" part
//but if we're inside a specific version coming from the default version, we need to add it
if(pathParts[pathParts.length - 1] == 'index' && selectedVersion == "") {
pathParts[pathParts.length - 1] = ""
} else {
if(pathParts[pathParts.length - 1] == '' && pathname === "") {
pathParts[pathParts.length - 1] = "/index"
}
}
let newPath = `${window.location.protocol}//${window.location.host}${pathParts.join("/")}`
window.location.href = newPath
}
function selectCurrentVersion(dropDown) {
if(typeof currentVersion != "undefined") {
dropDown.querySelector("option[value*='" + currentVersion + "']").setAttribute("selected", true)
} else {
dropDown.querySelector("option[value='']").setAttribute("selected", true)
}
}
const dropDown = document.getElementById("version-selector")
selectCurrentVersion(dropDown)
dropDown.addEventListener("change", updateLocation)
</script>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment