Skip to content

Commit

Permalink
feature: add version switcher
Browse files Browse the repository at this point in the history
  • Loading branch information
cheekyshibe committed Feb 23, 2021
1 parent e807487 commit 3949795
Show file tree
Hide file tree
Showing 2 changed files with 70 additions and 0 deletions.
3 changes: 3 additions & 0 deletions pydata_sphinx_theme/docs-navbar.html
Original file line number Diff line number Diff line change
Expand Up @@ -64,6 +64,9 @@
</a>
</li>
{% endif %}
<li class="version_switcher nav-item dropdown">
{%- include "version-switcher.html" %}
</li>
</ul>
</div>
</div>
67 changes: 67 additions & 0 deletions pydata_sphinx_theme/version-switcher.html
Original file line number Diff line number Diff line change
@@ -0,0 +1,67 @@
<script type="text/javascript">
(function () {

// TODO: Handle with api.json file to get the meta-data.

// Select versions that could be switched by user
var all_versions = {
'latest': 'v1.2.0',
'v1.1': 'v1.1.0',
'v1.0': 'v1.0.0',
};

function change_version(url, new_version) {
var version_regex = /\/(latest|(v\d+\.\d+.\d+))\//;
return url.replace(version_regex, '/' + new_version + '/');
}

function on_switch() {
var selected = $(this).children('option:selected').attr('value');

// original url
var url = window.location.href;
// changed url
var new_url = change_version(url, selected);

if (new_url != url) {
// check beforehand if url exists, otherwise redirect to the version's start page
$.ajax({
url: new_url,
success: function () {
window.location.href = new_url;
},
error: function () {
window.location.href = "https://pydata-sphinx-theme.readthedocs.io/en/" + selected;
}
});
}
}

$(document).ready(function () {
// var version = DOCUMENTATION_OPTIONS.VERSION;
// Take the first 2 parts of the release (e.g. "3.4.5" -> "3.4")
// version = version.split('.').slice(0, 2).join('.');

// fill the current version in the dropdown
document.getElementById("version-dropdown").innerText = 'latest';

const getVersionLink = () => {
return Object.keys(all_versions).map(key => `<button class="dropdown-item">${key}</button>`)
}
// fill the version menu
document.getElementById("version-menu").innerHTML = getVersionLink().join('');

// bind the changes to this menu to trigger the switching function
// TODO: Change this to use the dropdown button's on_select() callback function
$('.version-dropdown select').bind('change', on_switch);
});
})();

</script>

<button id="version-dropdown" class="btn btn-secondary btn-sm dropdown-toggle" type="button" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false">
<!-- placeholder for javascript filling above -->
</button>
<div id="version-menu" class="dropdown-menu" style="min-width: 6rem;">
<!-- placeholder for javascript filling above -->
</div>

0 comments on commit 3949795

Please sign in to comment.