Skip to content

Commit

Permalink
ref(js): Re-use useOnClickOutside from utils (#7397)
Browse files Browse the repository at this point in the history
  • Loading branch information
evanpurkhiser authored Jul 11, 2023
1 parent 43290f6 commit f30ecfe
Show file tree
Hide file tree
Showing 2 changed files with 9 additions and 30 deletions.
35 changes: 7 additions & 28 deletions src/components/search.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,8 @@ import DOMPurify from 'dompurify';
import {Link, navigate} from 'gatsby';
import algoliaInsights from 'search-insights';

import {useOnClickOutside} from 'sentry-docs/utils';

import {useKeyboardNavigate} from './hooks/useKeyboardNavigate';
import {Logo} from './logo';

Expand Down Expand Up @@ -46,32 +48,6 @@ const search = new SentryGlobalSearch([
'blog',
]);

const useClickOutside = (
ref: React.RefObject<HTMLElement>,
handler: () => void,
events?: string[]
) => {
if (!events) {
events = [`mousedown`, `touchstart`];
}

const detectClickOutside = (event: MouseEvent) => {
return !ref.current.contains(event.target as HTMLElement) && handler();
};

useEffect(() => {
for (const event of events) {
document.addEventListener(event, detectClickOutside);
}

return () => {
for (const event of events) {
document.removeEventListener(event, detectClickOutside);
}
};
});
};

function relativizeUrl(url: string) {
return url.replace(/^.*:\/\/docs\.sentry\.io/, '');
}
Expand All @@ -89,10 +65,13 @@ export function Search({path, autoFocus, platforms = []}: Props) {
const [inputFocus, setInputFocus] = useState(false);
const [showOffsiteResults, setShowOffsiteResults] = useState(false);
const [loading, setLoading] = useState(true);
useClickOutside(ref, () => {

const handleClickOutside = useCallback(() => {
setInputFocus(false);
setShowOffsiteResults(false);
});
}, []);

useOnClickOutside({ref, handler: handleClickOutside});

const inputRef = useRef<HTMLInputElement>(null);

Expand Down
4 changes: 2 additions & 2 deletions src/utils.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,14 +5,14 @@ import qs from 'query-string';
type ClickOutsideCallback = (event: MouseEvent) => void;

interface UseClickOutsideOpts<E extends HTMLElement> {
enabled: boolean;
handler: ClickOutsideCallback;
ref: React.RefObject<E>;
enabled?: boolean;
}

export function useOnClickOutside<E extends HTMLElement>({
ref,
enabled,
enabled = true,
handler,
}: UseClickOutsideOpts<E>) {
useEffect(() => {
Expand Down

1 comment on commit f30ecfe

@vercel
Copy link

@vercel vercel bot commented on f30ecfe Jul 11, 2023

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Successfully deployed to the following URLs:

sentry-docs – ./

docs.sentry.io
sentry-docs-git-master.sentry.dev
sentry-docs.sentry.dev

Please sign in to comment.