nav-tabs.es6.js 2.5 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788
  1. /**
  2. * @file
  3. * Responsive navigation tabs.
  4. *
  5. * This also supports collapsible navigable is the 'is-collapsible' class is
  6. * added to the main element, and a target element is included.
  7. */
  8. (($, Drupal) => {
  9. function init(i, tab) {
  10. const $tab = $(tab);
  11. const $target = $tab.find('[data-drupal-nav-tabs-target]');
  12. const $active = $target.find('.js-active-tab');
  13. const openMenu = () => {
  14. $target.toggleClass('is-open');
  15. };
  16. const toggleOrder = reset => {
  17. const current = $active.index();
  18. const original = $active.data('original-order');
  19. // Do not change order if already first or if already reset.
  20. if (original === 0 || reset === (current === original)) {
  21. return;
  22. }
  23. const siblings = {
  24. first: '[data-original-order="0"]',
  25. previous: `[data-original-order="${original - 1}"]`,
  26. };
  27. const $first = $target.find(siblings.first);
  28. const $previous = $target.find(siblings.previous);
  29. if (reset && current !== original) {
  30. $active.insertAfter($previous);
  31. } else if (!reset && current === original) {
  32. $active.insertBefore($first);
  33. }
  34. };
  35. const toggleCollapsed = () => {
  36. if (window.matchMedia('(min-width: 48em)').matches) {
  37. if ($tab.hasClass('is-horizontal') && !$tab.attr('data-width')) {
  38. let width = 0;
  39. $target.find('.js-tabs-link').each((index, value) => {
  40. width += $(value).outerWidth();
  41. });
  42. $tab.attr('data-width', width);
  43. }
  44. // Collapse the tabs if the combined width of the tabs is greater than
  45. // the width of the parent container.
  46. const isHorizontal = $tab.attr('data-width') <= $tab.outerWidth();
  47. $tab.toggleClass('is-horizontal', isHorizontal);
  48. toggleOrder(isHorizontal);
  49. } else {
  50. toggleOrder(false);
  51. }
  52. };
  53. $tab.addClass('position-container is-horizontal-enabled');
  54. $target.find('.js-tab').each((index, element) => {
  55. const $item = $(element);
  56. $item.attr('data-original-order', $item.index());
  57. });
  58. $tab.on('click.tabs', '[data-drupal-nav-tabs-trigger]', openMenu);
  59. $(window)
  60. .on('resize.tabs', Drupal.debounce(toggleCollapsed, 150))
  61. .trigger('resize.tabs');
  62. }
  63. /**
  64. * Initialize the tabs JS.
  65. */
  66. Drupal.behaviors.navTabs = {
  67. attach(context) {
  68. $(context)
  69. .find('[data-drupal-nav-tabs].is-collapsible')
  70. .once('nav-tabs')
  71. .each((i, value) => {
  72. $(value).each(init);
  73. });
  74. },
  75. };
  76. })(jQuery, Drupal);