Skip to content

Commit

Permalink
feat(docsearch): support typing query when search button is focused (#54
Browse files Browse the repository at this point in the history
)
  • Loading branch information
francoischalifour committed Jul 7, 2020
1 parent 43ea375 commit 929b1c6
Show file tree
Hide file tree
Showing 2 changed files with 24 additions and 7 deletions.
16 changes: 11 additions & 5 deletions src/DocSearchButton.tsx
Expand Up @@ -14,12 +14,13 @@ function isAppleDevice() {
return /(Mac|iPhone|iPod|iPad)/i.test(navigator.platform);
}

export function DocSearchButton(
props: React.DetailedHTMLProps<
export const DocSearchButton = React.forwardRef<
HTMLButtonElement,
React.DetailedHTMLProps<
React.ButtonHTMLAttributes<HTMLButtonElement>,
HTMLButtonElement
>
) {
>((props, ref) => {
const [key, setKey] = useState(() =>
isAppleDevice() ? ACTION_KEY_APPLE : ACTION_KEY_DEFAULT
);
Expand All @@ -31,7 +32,12 @@ export function DocSearchButton(
}, []);

return (
<button type="button" className="DocSearch-SearchButton" {...props}>
<button
type="button"
className="DocSearch-SearchButton"
{...props}
ref={ref}
>
<SearchIcon />
<span className="DocSearch-SearchButton-Placeholder">Search</span>

Expand All @@ -41,4 +47,4 @@ export function DocSearchButton(
<span className="DocSearch-SearchButton-Key">K</span>
</button>
);
}
});
15 changes: 13 additions & 2 deletions src/useDocSearchKeyboardEvents.ts
@@ -1,6 +1,11 @@
import React from 'react';

export function useDocSearchKeyboardEvents({ isOpen, onOpen, onClose }) {
export function useDocSearchKeyboardEvents({
isOpen,
onOpen,
onClose,
searchButtonRef,
}) {
React.useEffect(() => {
function onKeyDown(event: KeyboardEvent) {
if (
Expand All @@ -19,12 +24,18 @@ export function useDocSearchKeyboardEvents({ isOpen, onOpen, onClose }) {
onOpen();
}
}

if (searchButtonRef.current === document.activeElement) {
if (/[a-zA-Z0-9]/.test(String.fromCharCode(event.keyCode))) {
onOpen();
}
}
}

window.addEventListener('keydown', onKeyDown);

return () => {
window.removeEventListener('keydown', onKeyDown);
};
}, [isOpen, onOpen, onClose]);
}, [isOpen, onOpen, onClose, searchButtonRef]);
}

0 comments on commit 929b1c6

Please sign in to comment.