active-link.es6.js 2.4 KB

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