sidebar.js 2.5 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970
  1. /*
  2. * sidebar.js
  3. * ~~~~~~~~~~
  4. *
  5. * This script makes the Sphinx sidebar collapsible.
  6. *
  7. * .sphinxsidebar contains .sphinxsidebarwrapper. This script adds
  8. * in .sphixsidebar, after .sphinxsidebarwrapper, the #sidebarbutton
  9. * used to collapse and expand the sidebar.
  10. *
  11. * When the sidebar is collapsed the .sphinxsidebarwrapper is hidden
  12. * and the width of the sidebar and the margin-left of the document
  13. * are decreased. When the sidebar is expanded the opposite happens.
  14. * This script saves a per-browser/per-session cookie used to
  15. * remember the position of the sidebar among the pages.
  16. * Once the browser is closed the cookie is deleted and the position
  17. * reset to the default (expanded).
  18. *
  19. * :copyright: Copyright 2007-2022 by the Sphinx team, see AUTHORS.
  20. * :license: BSD, see LICENSE for details.
  21. *
  22. */
  23. const initialiseSidebar = () => {
  24. // global elements used by the functions.
  25. const bodyWrapper = document.getElementsByClassName("bodywrapper")[0]
  26. const sidebar = document.getElementsByClassName("sphinxsidebar")[0]
  27. const sidebarWrapper = document.getElementsByClassName('sphinxsidebarwrapper')[0]
  28. const sidebarButton = document.getElementById("sidebarbutton")
  29. const sidebarArrow = sidebarButton.querySelector('span')
  30. // for some reason, the document has no sidebar; do not run into errors
  31. if (typeof sidebar === "undefined") return;
  32. const flipArrow = element => element.innerText = (element.innerText === "»") ? "«" : "»"
  33. const collapse_sidebar = () => {
  34. bodyWrapper.style.marginLeft = ".8em";
  35. sidebar.style.width = ".8em"
  36. sidebarWrapper.style.display = "none"
  37. flipArrow(sidebarArrow)
  38. sidebarButton.title = _('Expand sidebar')
  39. window.localStorage.setItem("sidebar", "collapsed")
  40. }
  41. const expand_sidebar = () => {
  42. bodyWrapper.style.marginLeft = ""
  43. sidebar.style.removeProperty("width")
  44. sidebarWrapper.style.display = ""
  45. flipArrow(sidebarArrow)
  46. sidebarButton.title = _('Collapse sidebar')
  47. window.localStorage.setItem("sidebar", "expanded")
  48. }
  49. sidebarButton.addEventListener("click", () => {
  50. (sidebarWrapper.style.display === "none") ? expand_sidebar() : collapse_sidebar()
  51. })
  52. if (!window.localStorage.getItem("sidebar")) return
  53. const value = window.localStorage.getItem("sidebar")
  54. if (value === "collapsed") collapse_sidebar();
  55. else if (value === "expanded") expand_sidebar();
  56. }
  57. if (document.readyState !== "loading") initialiseSidebar()
  58. else document.addEventListener("DOMContentLoaded", initialiseSidebar)