Chris@0: /** Chris@0: * @file Chris@0: * Attaches behaviors for Drupal's active link marking. Chris@0: */ Chris@0: Chris@17: (function(Drupal, drupalSettings) { Chris@0: /** Chris@0: * Append is-active class. Chris@0: * Chris@0: * The link is only active if its path corresponds to the current path, the Chris@0: * language of the linked path is equal to the current language, and if the Chris@0: * query parameters of the link equal those of the current request, since the Chris@0: * same request with different query parameters may yield a different page Chris@0: * (e.g. pagers, exposed View filters). Chris@0: * Chris@0: * Does not discriminate based on element type, so allows you to set the Chris@0: * is-active class on any element: a, li… Chris@0: * Chris@0: * @type {Drupal~behavior} Chris@0: */ Chris@0: Drupal.behaviors.activeLinks = { Chris@0: attach(context) { Chris@0: // Start by finding all potentially active links. Chris@0: const path = drupalSettings.path; Chris@0: const queryString = JSON.stringify(path.currentQuery); Chris@17: const querySelector = path.currentQuery Chris@17: ? `[data-drupal-link-query='${queryString}']` Chris@17: : ':not([data-drupal-link-query])'; Chris@17: const originalSelectors = [ Chris@17: `[data-drupal-link-system-path="${path.currentPath}"]`, Chris@17: ]; Chris@0: let selectors; Chris@0: Chris@0: // If this is the front page, we have to check for the path as Chris@0: // well. Chris@0: if (path.isFront) { Chris@0: originalSelectors.push('[data-drupal-link-system-path=""]'); Chris@0: } Chris@0: Chris@0: // Add language filtering. Chris@0: selectors = [].concat( Chris@0: // Links without any hreflang attributes (most of them). Chris@0: originalSelectors.map(selector => `${selector}:not([hreflang])`), Chris@0: // Links with hreflang equals to the current language. Chris@17: originalSelectors.map( Chris@17: selector => `${selector}[hreflang="${path.currentLanguage}"]`, Chris@17: ), Chris@0: ); Chris@0: Chris@0: // Add query string selector for pagers, exposed filters. Chris@0: selectors = selectors.map(current => current + querySelector); Chris@0: Chris@0: // Query the DOM. Chris@0: const activeLinks = context.querySelectorAll(selectors.join(',')); Chris@0: const il = activeLinks.length; Chris@0: for (let i = 0; i < il; i++) { Chris@0: activeLinks[i].classList.add('is-active'); Chris@0: } Chris@0: }, Chris@0: detach(context, settings, trigger) { Chris@0: if (trigger === 'unload') { Chris@17: const activeLinks = context.querySelectorAll( Chris@17: '[data-drupal-link-system-path].is-active', Chris@17: ); Chris@0: const il = activeLinks.length; Chris@0: for (let i = 0; i < il; i++) { Chris@0: activeLinks[i].classList.remove('is-active'); Chris@0: } Chris@0: } Chris@0: }, Chris@0: }; Chris@17: })(Drupal, drupalSettings);