Skip to content

Commit

Permalink
feat: search hotkey (#91)
Browse files Browse the repository at this point in the history
  • Loading branch information
Flower-F committed Oct 14, 2022
1 parent eacc9ca commit 5ccb930
Showing 1 changed file with 17 additions and 2 deletions.
19 changes: 17 additions & 2 deletions src/theme-default/components/Search/index.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,8 @@ import { SuggestionContent } from './Suggestion';
const KEY_CODE = {
ARROW_UP: 'ArrowUp',
ARROW_DOWN: 'ArrowDown',
ENTER: 'Enter'
ENTER: 'Enter',
SEARCH: 'KeyK'
};

// eslint-disable-next-line @typescript-eslint/no-unused-vars
Expand All @@ -25,6 +26,7 @@ export function Search(
const psRef = useRef<PageSearcher>();
const initPageSearcherPromiseRef = useRef<Promise<void>>();
const [disableInput, setDisableInput] = useState(true);
const searchInputRef = useRef<HTMLInputElement | null>(null);
// initializing or searching
const showLoading = !initialized || searching;
// 1. page searcher has been initialized and finish searching
Expand Down Expand Up @@ -60,6 +62,18 @@ export function Search(
useEffect(() => {
const onKeyDown = throttle((e: KeyboardEvent) => {
switch (e.code) {
case KEY_CODE.SEARCH:
if ((e.ctrlKey || e.metaKey) && searchInputRef.current) {
e.preventDefault();
if (!focused) {
setFocused(true);
searchInputRef.current.focus();
} else {
setFocused(false);
searchInputRef.current.blur();
}
}
break;
case KEY_CODE.ARROW_DOWN:
e.preventDefault();
setCurrentSuggestionIndex(
Expand Down Expand Up @@ -87,7 +101,7 @@ export function Search(
return () => {
document.removeEventListener('keydown', onKeyDown);
};
}, [currentSuggestionIndex, suggestions]);
}, [currentSuggestionIndex, focused, suggestions]);

useEffect(() => {
setDisableInput(false);
Expand Down Expand Up @@ -115,6 +129,7 @@ export function Search(
setFocused(true);
initPageSearcherPromiseRef.current = initPageSearcher();
}}
ref={searchInputRef}
/>
{focused && query && (
<ul
Expand Down

1 comment on commit 5ccb930

@vercel
Copy link

@vercel vercel bot commented on 5ccb930 Oct 14, 2022

Choose a reason for hiding this comment

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

Please sign in to comment.