tabs.js 2.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475
  1. /**
  2. * Change active tab of tabs.
  3. *
  4. * @param {Element} container
  5. * @param {string} name
  6. */
  7. const changeTab = (container, name) => {
  8. for (const child of container.children) {
  9. if (!(child instanceof HTMLElement)) {
  10. continue;
  11. }
  12. if (child.classList.contains('mdbook-tabs')) {
  13. for (const tab of child.children) {
  14. if (!(tab instanceof HTMLElement)) {
  15. continue;
  16. }
  17. if (tab.dataset.tabname === name) {
  18. tab.classList.add('active');
  19. } else {
  20. tab.classList.remove('active');
  21. }
  22. }
  23. } else if (child.classList.contains('mdbook-tab-content')) {
  24. if (child.dataset.tabname === name) {
  25. child.classList.remove('hidden');
  26. } else {
  27. child.classList.add('hidden');
  28. }
  29. }
  30. }
  31. };
  32. document.addEventListener('DOMContentLoaded', () => {
  33. const tabs = document.querySelectorAll('.mdbook-tab');
  34. for (const tab of tabs) {
  35. tab.addEventListener('click', () => {
  36. if (!(tab instanceof HTMLElement)) {
  37. return;
  38. }
  39. if (!tab.parentElement || !tab.parentElement.parentElement) {
  40. return;
  41. }
  42. const container = tab.parentElement.parentElement;
  43. const name = tab.dataset.tabname;
  44. const global = container.dataset.tabglobal;
  45. changeTab(container, name);
  46. if (global) {
  47. localStorage.setItem(`mdbook-tabs-${global}`, name);
  48. const globalContainers = document.querySelectorAll(
  49. `.mdbook-tabs-container[data-tabglobal="${global}"]`
  50. );
  51. for (const globalContainer of globalContainers) {
  52. changeTab(globalContainer, name);
  53. }
  54. }
  55. });
  56. }
  57. const containers = document.querySelectorAll('.mdbook-tabs-container[data-tabglobal]');
  58. for (const container of containers) {
  59. const global = container.dataset.tabglobal;
  60. const name = localStorage.getItem(`mdbook-tabs-${global}`);
  61. if (name && document.querySelector(`.mdbook-tab[data-tabname="${name}"]`)) {
  62. changeTab(container, name);
  63. }
  64. }
  65. });