custom.js 1.9 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465
  1. /* vim:fileencoding=utf-8
  2. *
  3. * Copyright (C) 2021 Kovid Goyal <kovid at kovidgoyal.net>
  4. *
  5. * Distributed under terms of the GPLv3 license
  6. */
  7. /*jshint esversion: 6 */
  8. (function() {
  9. "use strict";
  10. function get_sidebar_tree() {
  11. return document.querySelector('.sidebar-tree');
  12. }
  13. function scroll_sidebar_node_into_view(a) {
  14. var ss = get_sidebar_tree().closest('.sidebar-scroll');
  15. if (!ss || !a) return;
  16. ss.style.position = 'relative';
  17. var pos = 0;
  18. while (true) {
  19. pos += a.offsetTop;
  20. a = a.offsetParent;
  21. if (!a || a == ss) break;
  22. }
  23. ss.scrollTo({top: pos, behavior: 'instant'});
  24. }
  25. function mark_current_link(sidebar_tree, a, onload) {
  26. var li = a.closest('li.has-children');
  27. while (li) {
  28. li.querySelector('input[type=checkbox]').setAttribute('checked', 'checked');
  29. li = li.parentNode.closest('li.has-children');
  30. }
  31. sidebar_tree.querySelectorAll('.current').forEach(function (elem) {
  32. elem.classList.remove('current');
  33. });
  34. if (onload) scroll_sidebar_node_into_view(a);
  35. a.classList.add('current');
  36. }
  37. function show_hash_in_sidebar(onload) {
  38. const sidebar_tree = get_sidebar_tree();
  39. if (document.location.hash.length > 1) {
  40. var a = sidebar_tree.querySelector('a[href="' + document.location.hash + '"]');
  41. if (a) mark_current_link(sidebar_tree, a, onload);
  42. } else {
  43. if (onload) scroll_sidebar_node_into_view(sidebar_tree.querySelector('.current-page a'));
  44. }
  45. }
  46. function init_sidebar() {
  47. const sidebar_tree = document.querySelector('.sidebar-tree');
  48. if (!sidebar_tree || sidebar_tree.dataset.inited === 'true') return;
  49. sidebar_tree.dataset.inited = 'true';
  50. show_hash_in_sidebar(true);
  51. window.addEventListener('hashchange', show_hash_in_sidebar.bind(null, false));
  52. }
  53. document.addEventListener("DOMContentLoaded", init_sidebar);
  54. init_sidebar();
  55. }());