( function () { 'use strict'; let cleanupCurrent = null; function initialize( options = {} ) { if ( cleanupCurrent ) { cleanupCurrent(); } const doc = options.document || ( typeof document === 'undefined' ? null : document ); if ( ! doc ) { return false; } const forms = [ ...doc.querySelectorAll( '[data-chrnx-search]' ) ]; const controls = forms .map( ( form ) => ( { form, input: form.querySelector( 'input[name="s"]' ), panel: form.querySelector( '[data-chrnx-search-panel]' ), button: form.querySelector( '[data-chrnx-search-button]' ), } ) ) .filter( ( control ) => control.input && control.panel && control.button ); if ( controls.length === 0 ) { cleanupCurrent = null; return false; } const setExpanded = ( control, expanded, restoreFocus = false ) => { control.form.dataset.expanded = String( expanded ); control.panel.hidden = ! expanded; control.button.setAttribute( 'aria-expanded', String( expanded ) ); control.button.setAttribute( 'aria-label', expanded ? control.button.dataset.labelSubmit : control.button.dataset.labelOpen, ); if ( expanded ) { control.input.focus(); } else if ( restoreFocus ) { control.button.focus(); } }; const onSubmit = ( event ) => { const control = controls.find( ( candidate ) => candidate.form === event.currentTarget ); if ( ! control.input.value.trim() ) { event.preventDefault(); setExpanded( control, true ); } }; const onKeydown = ( event ) => { if ( event.key !== 'Escape' ) { return; } const control = controls.find( ( candidate ) => candidate.form.dataset.expanded === 'true' && candidate.form.contains( event.target ), ); if ( control ) { event.preventDefault(); setExpanded( control, false, true ); } }; controls.forEach( ( control ) => { setExpanded( control, false ); control.form.addEventListener( 'submit', onSubmit ); } ); doc.addEventListener( 'keydown', onKeydown ); cleanupCurrent = () => { controls.forEach( ( control ) => control.form.removeEventListener( 'submit', onSubmit ) ); doc.removeEventListener( 'keydown', onKeydown ); cleanupCurrent = null; }; return true; } const helpers = { initialize }; if ( typeof module !== 'undefined' && module.exports ) { module.exports = helpers; } else if ( typeof document !== 'undefined' ) { if ( document.readyState === 'loading' ) { document.addEventListener( 'DOMContentLoaded', () => initialize(), { once: true } ); } else { initialize(); } } } )();