tabs.es6.js 1.9 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071
  1. /**
  2. * @file
  3. * Provides interactivity for showing and hiding the primary tabs at mobile widths.
  4. */
  5. ((Drupal, once) => {
  6. /**
  7. * Initialize the primary tabs.
  8. *
  9. * @param {HTMLElement} el
  10. * The DOM element containing the primary tabs.
  11. */
  12. function init(el) {
  13. const tabs = el.querySelector('.tabs');
  14. const expandedClass = 'is-expanded';
  15. const activeTab = tabs.querySelector('.is-active');
  16. /**
  17. * Determines if primary tabs are expanded for mobile layouts.
  18. *
  19. * @return {boolean}
  20. * Whether the tabs trigger element is expanded.
  21. */
  22. function isTabsMobileLayout() {
  23. return tabs.querySelector('.tabs__trigger').clientHeight > 0;
  24. }
  25. /**
  26. * Controls primary tab visibility on click events.
  27. *
  28. * @param {Event} e
  29. * The event object.
  30. */
  31. function handleTriggerClick(e) {
  32. if (!tabs.classList.contains(expandedClass)) {
  33. e.currentTarget.setAttribute('aria-expanded', 'true');
  34. tabs.classList.add(expandedClass);
  35. } else {
  36. e.currentTarget.setAttribute('aria-expanded', 'false');
  37. tabs.classList.remove(expandedClass);
  38. }
  39. }
  40. if (isTabsMobileLayout() && !activeTab.matches('.tabs__tab:first-child')) {
  41. const newActiveTab = activeTab.cloneNode(true);
  42. const firstTab = tabs.querySelector('.tabs__tab:first-child');
  43. tabs.insertBefore(newActiveTab, firstTab);
  44. tabs.removeChild(activeTab);
  45. }
  46. tabs
  47. .querySelector('.tabs__trigger')
  48. .addEventListener('click', handleTriggerClick);
  49. }
  50. /**
  51. * Initialize the primary tabs.
  52. *
  53. * @type {Drupal~behavior}
  54. *
  55. * @prop {Drupal~behaviorAttach} attach
  56. * Display primary tabs according to the screen width.
  57. */
  58. Drupal.behaviors.primaryTabs = {
  59. attach(context) {
  60. once('olivero-tabs', '[data-drupal-nav-primary-tabs]', context).forEach(
  61. init,
  62. );
  63. },
  64. };
  65. })(Drupal, once);