active-link.js 2.5 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768
  1. /**
  2. * @file
  3. * Attaches behaviors for Drupal's active link marking.
  4. */
  5. (function (Drupal, drupalSettings) {
  6. 'use strict';
  7. /**
  8. * Append is-active class.
  9. *
  10. * The link is only active if its path corresponds to the current path, the
  11. * language of the linked path is equal to the current language, and if the
  12. * query parameters of the link equal those of the current request, since the
  13. * same request with different query parameters may yield a different page
  14. * (e.g. pagers, exposed View filters).
  15. *
  16. * Does not discriminate based on element type, so allows you to set the
  17. * is-active class on any element: a, li…
  18. *
  19. * @type {Drupal~behavior}
  20. */
  21. Drupal.behaviors.activeLinks = {
  22. attach: function (context) {
  23. // Start by finding all potentially active links.
  24. var path = drupalSettings.path;
  25. var queryString = JSON.stringify(path.currentQuery);
  26. var querySelector = path.currentQuery ? "[data-drupal-link-query='" + queryString + "']" : ':not([data-drupal-link-query])';
  27. var originalSelectors = ['[data-drupal-link-system-path="' + path.currentPath + '"]'];
  28. var selectors;
  29. // If this is the front page, we have to check for the <front> path as
  30. // well.
  31. if (path.isFront) {
  32. originalSelectors.push('[data-drupal-link-system-path="<front>"]');
  33. }
  34. // Add language filtering.
  35. selectors = [].concat(
  36. // Links without any hreflang attributes (most of them).
  37. originalSelectors.map(function (selector) { return selector + ':not([hreflang])'; }),
  38. // Links with hreflang equals to the current language.
  39. originalSelectors.map(function (selector) { return selector + '[hreflang="' + path.currentLanguage + '"]'; })
  40. );
  41. // Add query string selector for pagers, exposed filters.
  42. selectors = selectors.map(function (current) { return current + querySelector; });
  43. // Query the DOM.
  44. var activeLinks = context.querySelectorAll(selectors.join(','));
  45. var il = activeLinks.length;
  46. for (var i = 0; i < il; i++) {
  47. activeLinks[i].classList.add('is-active');
  48. }
  49. },
  50. detach: function (context, settings, trigger) {
  51. if (trigger === 'unload') {
  52. var activeLinks = context.querySelectorAll('[data-drupal-link-system-path].is-active');
  53. var il = activeLinks.length;
  54. for (var i = 0; i < il; i++) {
  55. activeLinks[i].classList.remove('is-active');
  56. }
  57. }
  58. }
  59. };
  60. })(Drupal, drupalSettings);