Skip to content

Commit

Permalink
Use proper onBlur (focusout) handler in top search form
Browse files Browse the repository at this point in the history
  • Loading branch information
davidmz committed Oct 31, 2024
1 parent 5c207bc commit 8298087
Showing 1 changed file with 6 additions and 27 deletions.
33 changes: 6 additions & 27 deletions src/components/layout-header-search.jsx
Original file line number Diff line number Diff line change
Expand Up @@ -41,13 +41,14 @@ export const HeaderSearchForm = withRouter(function HeaderSearchForm({ router, c
input.current.blur();
});

const onFocus = useEvent(() => {}); // TODO remove
const onKeyDown = useEvent((e) => e.keyCode === KEY_ESCAPE && input.current.blur());
const clearSearchForm = useEvent(() => (setQuery(''), input.current.focus()));

const focusHandlers = useDebouncedFocus({
onFocus,
onBlur: closeSearchForm,
const onBlur = useEvent((e) => {
// When the new focus is outside the search form
if (!e.currentTarget.contains(e.relatedTarget)) {
closeSearchForm();
}
});

useEffect(() => {
Expand All @@ -74,7 +75,7 @@ export const HeaderSearchForm = withRouter(function HeaderSearchForm({ router, c

return (
<form className={styles.searchForm} action="/search" onSubmit={onSubmit}>
<span className={styles.searchInputContainer} {...focusHandlers} tabIndex={0}>
<span className={styles.searchInputContainer} onBlur={onBlur} tabIndex={0}>
<span className={styles.searchInputBox}>
<input
className={styles.searchInput}
Expand Down Expand Up @@ -141,25 +142,3 @@ function useInitialQuery(router) {
}
}, [router.routes, router.params, router.location]);
}

function useDebouncedFocus({ onFocus: onFocusOrig, onBlur: onBlurOrig }, interval = 100) {
const focusTimer = useRef(0);
const blurTimer = useRef(0);

const cleanup = useEvent(() => {
window.clearTimeout(blurTimer.current);
window.clearTimeout(focusTimer.current);
});
useEffect(() => () => cleanup(), [cleanup]);

const onFocus = useEvent(() => {
cleanup();
focusTimer.current = window.setTimeout(onFocusOrig, interval);
});
const onBlur = useEvent(() => {
cleanup();
blurTimer.current = window.setTimeout(onBlurOrig, interval);
});

return { onFocus, onBlur };
}

0 comments on commit 8298087

Please sign in to comment.