88 lines
2.6 KiB
JavaScript
88 lines
2.6 KiB
JavaScript
( 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"]' ),
|
|
button: form.querySelector( '[data-chrnx-search-button]' ),
|
|
} ) )
|
|
.filter( ( control ) => control.input && control.button );
|
|
if ( controls.length === 0 ) {
|
|
cleanupCurrent = null;
|
|
return false;
|
|
}
|
|
|
|
const setExpanded = ( control, expanded, restoreFocus = false ) => {
|
|
control.form.dataset.expanded = String( expanded );
|
|
control.input.hidden = ! 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();
|
|
}
|
|
}
|
|
} )();
|