Mercurial > hg > cmmr2012-drupal-site
diff core/misc/active-link.es6.js @ 0:c75dbcec494b
Initial commit from drush-created site
author | Chris Cannam |
---|---|
date | Thu, 05 Jul 2018 14:24:15 +0000 |
parents | |
children | a9cd425dd02b |
line wrap: on
line diff
--- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/core/misc/active-link.es6.js Thu Jul 05 14:24:15 2018 +0000 @@ -0,0 +1,64 @@ +/** + * @file + * Attaches behaviors for Drupal's active link marking. + */ + +(function (Drupal, drupalSettings) { + /** + * Append is-active class. + * + * The link is only active if its path corresponds to the current path, the + * language of the linked path is equal to the current language, and if the + * query parameters of the link equal those of the current request, since the + * same request with different query parameters may yield a different page + * (e.g. pagers, exposed View filters). + * + * Does not discriminate based on element type, so allows you to set the + * is-active class on any element: a, li… + * + * @type {Drupal~behavior} + */ + Drupal.behaviors.activeLinks = { + attach(context) { + // Start by finding all potentially active links. + const path = drupalSettings.path; + const queryString = JSON.stringify(path.currentQuery); + const querySelector = path.currentQuery ? `[data-drupal-link-query='${queryString}']` : ':not([data-drupal-link-query])'; + const originalSelectors = [`[data-drupal-link-system-path="${path.currentPath}"]`]; + let selectors; + + // If this is the front page, we have to check for the <front> path as + // well. + if (path.isFront) { + originalSelectors.push('[data-drupal-link-system-path="<front>"]'); + } + + // Add language filtering. + selectors = [].concat( + // Links without any hreflang attributes (most of them). + originalSelectors.map(selector => `${selector}:not([hreflang])`), + // Links with hreflang equals to the current language. + originalSelectors.map(selector => `${selector}[hreflang="${path.currentLanguage}"]`), + ); + + // Add query string selector for pagers, exposed filters. + selectors = selectors.map(current => current + querySelector); + + // Query the DOM. + const activeLinks = context.querySelectorAll(selectors.join(',')); + const il = activeLinks.length; + for (let i = 0; i < il; i++) { + activeLinks[i].classList.add('is-active'); + } + }, + detach(context, settings, trigger) { + if (trigger === 'unload') { + const activeLinks = context.querySelectorAll('[data-drupal-link-system-path].is-active'); + const il = activeLinks.length; + for (let i = 0; i < il; i++) { + activeLinks[i].classList.remove('is-active'); + } + } + }, + }; +}(Drupal, drupalSettings));