drupal/core/themes/olivero/js/search.js

104 lines
3.1 KiB
JavaScript

/**
* DO NOT EDIT THIS FILE.
* See the following change record for more information,
* https://www.drupal.org/node/2815083
* @preserve
**/
(Drupal => {
const searchWideButtonSelector = '[data-drupal-selector="block-search-wide-button"]';
const searchWideButton = document.querySelector(searchWideButtonSelector);
const searchWideWrapperSelector = '[data-drupal-selector="block-search-wide-wrapper"]';
const searchWideWrapper = document.querySelector(searchWideWrapperSelector);
function searchIsVisible() {
return searchWideWrapper.classList.contains('is-active');
}
Drupal.olivero.searchIsVisible = searchIsVisible;
function watchForClickOut(e) {
const clickInSearchArea = e.target.matches(`
${searchWideWrapperSelector},
${searchWideWrapperSelector} *,
${searchWideButtonSelector},
${searchWideButtonSelector} *
`);
if (!clickInSearchArea && searchIsVisible()) {
toggleSearchVisibility(false);
}
}
function watchForFocusOut(e) {
if (e.relatedTarget) {
const inSearchBar = e.relatedTarget.matches(`${searchWideWrapperSelector}, ${searchWideWrapperSelector} *`);
const inSearchButton = e.relatedTarget.matches(`${searchWideButtonSelector}, ${searchWideButtonSelector} *`);
if (!inSearchBar && !inSearchButton) {
toggleSearchVisibility(false);
}
}
}
function watchForEscapeOut(e) {
if (e.key === 'Escape') {
toggleSearchVisibility(false);
}
}
function handleFocus() {
if (searchIsVisible()) {
searchWideWrapper.querySelector('input[type="search"]').focus();
} else if (searchWideWrapper.contains(document.activeElement)) {
searchWideButton.focus();
}
}
function toggleSearchVisibility(visibility) {
searchWideButton.setAttribute('aria-expanded', visibility === true);
searchWideWrapper.addEventListener('transitionend', handleFocus, {
once: true
});
if (visibility === true) {
Drupal.olivero.closeAllSubNav();
searchWideWrapper.classList.add('is-active');
document.addEventListener('click', watchForClickOut, {
capture: true
});
document.addEventListener('focusout', watchForFocusOut, {
capture: true
});
document.addEventListener('keyup', watchForEscapeOut, {
capture: true
});
} else {
searchWideWrapper.classList.remove('is-active');
document.removeEventListener('click', watchForClickOut, {
capture: true
});
document.removeEventListener('focusout', watchForFocusOut, {
capture: true
});
document.removeEventListener('keyup', watchForEscapeOut, {
capture: true
});
}
}
Drupal.olivero.toggleSearchVisibility = toggleSearchVisibility;
Drupal.behaviors.searchWide = {
attach(context) {
const searchWideButtonEl = once('search-wide', searchWideButtonSelector, context).shift();
if (searchWideButtonEl) {
searchWideButtonEl.setAttribute('aria-expanded', searchIsVisible());
searchWideButtonEl.addEventListener('click', () => {
toggleSearchVisibility(!searchIsVisible());
});
}
}
};
})(Drupal);