Skip to content

Commit

Permalink
feat(SearchBar): open searchBar on Ctrl + k / ⌘ + k keypress (nod…
Browse files Browse the repository at this point in the history
…ejs#2999)

* Feat(SearchBar): open searchBar on `ctrl + k`/ `⌘ + k` keypress

* Fix: tab focus
  • Loading branch information
shanpriyan authored Nov 13, 2022
1 parent 8ac49f3 commit fc2cede
Show file tree
Hide file tree
Showing 2 changed files with 52 additions and 13 deletions.
24 changes: 19 additions & 5 deletions src/components/CommonComponents/SearchBar/index.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -91,11 +91,25 @@ const SearchBar = (): JSX.Element => {
}
};

useKeyPress('/', () => expandContainer());
useKeyPress('Escape', () => {
if (isExpanded) {
collapseContainer();
}
useKeyPress({
targetKey: 'ctrl+k',
callback: expandContainer,
preventDefault: true,
});

useKeyPress({
targetKey: 'meta+k',
callback: expandContainer,
preventDefault: true,
});

useKeyPress({
targetKey: 'Escape',
callback: () => {
if (isExpanded) {
collapseContainer();
}
},
});

return (
Expand Down
41 changes: 33 additions & 8 deletions src/hooks/useKeyPress.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -3,21 +3,46 @@
*/
import { useEffect, useState } from 'react';

function useKeyPress(targetKey: string, cb?: () => void): boolean {
const decorateKey = ({ metaKey, ctrlKey, key }: KeyboardEvent) => {
if (metaKey) {
return `meta+${key}`;
}

if (ctrlKey) {
return `ctrl+${key}`;
}

return key;
};

interface UseKeyPressProps {
targetKey: string;
callback?: () => void;
preventDefault?: boolean;
}

function useKeyPress({
targetKey,
callback,
preventDefault = false,
}: UseKeyPressProps): boolean {
const [keyPressed, setKeyPressed] = useState(false);

useEffect(() => {
const downHandler = ({ key }: KeyboardEvent) => {
if (key === targetKey) {
const downHandler = (e: KeyboardEvent) => {
if (decorateKey(e) === targetKey) {
if (preventDefault) {
e.preventDefault();
}
setKeyPressed(true);
if (cb) {
cb();
if (typeof callback === 'function') {
callback();
}
}
};

const upHandler = ({ key }: KeyboardEvent) => {
if (key === targetKey) {
const upHandler = (e: KeyboardEvent) => {
if (decorateKey(e) === targetKey) {
setKeyPressed(false);
}
};
Expand All @@ -28,7 +53,7 @@ function useKeyPress(targetKey: string, cb?: () => void): boolean {
window.removeEventListener('keydown', downHandler);
window.removeEventListener('keyup', upHandler);
};
}, [cb, targetKey]);
}, [callback, targetKey, preventDefault]);
return keyPressed;
}

Expand Down

0 comments on commit fc2cede

Please sign in to comment.