Skip to content

Commit

Permalink
Search: Clicking outside now closes overlay
Browse files Browse the repository at this point in the history
  • Loading branch information
jsnmoon committed Feb 5, 2022
1 parent 301c0f5 commit 6f8492a
Show file tree
Hide file tree
Showing 2 changed files with 22 additions and 4 deletions.
Original file line number Diff line number Diff line change
@@ -0,0 +1,4 @@
Significance: minor
Type: added

Clicking outside overlay now closes overlay
22 changes: 18 additions & 4 deletions projects/packages/search/src/instant-search/components/overlay.jsx
Original file line number Diff line number Diff line change
Expand Up @@ -11,24 +11,38 @@ import { OVERLAY_CLASS_NAME } from '../lib/constants';
import './overlay.scss';

const callOnEscapeKey = callback => event => {
// IE11 uses 'Esc'
if ( event.key === 'Escape' || event.key === 'Esc' ) {
if ( event.key === 'Escape' ) {
event.preventDefault();
callback();
}
};

const callOnOutsideClick = callback => {
// TODO: Make this the actual overlay element in the future.
const overlayContainer = document.getElementsByClassName(
'jetpack-instant-search__search-results'
)[ 0 ];
return event => {
if ( overlayContainer && ! overlayContainer.contains( event.target ) ) {
callback();
}
};
};

const Overlay = props => {
const { children, closeOverlay, colorTheme, hasOverlayWidgets, isVisible } = props;

const closeWithEscape = callOnEscapeKey( closeOverlay );
const closeWithOutsideClick = callOnOutsideClick( closeOverlay );
useEffect( () => {
window.addEventListener( 'keydown', closeWithEscape );
window.addEventListener( 'click', closeWithOutsideClick );
return () => {
// Cleanup after event
// Cleanup on component dismount
window.removeEventListener( 'keydown', closeWithEscape );
window.addEventListener( 'click', closeWithOutsideClick );
};
}, [ closeWithEscape ] );
}, [ closeWithEscape, closeWithOutsideClick ] );

return (
<div
Expand Down

0 comments on commit 6f8492a

Please sign in to comment.