Skip to content
This repository was archived by the owner on Apr 26, 2024. It is now read-only.

Commit fc2cede

Browse files
authored
feat(SearchBar): open searchBar on Ctrl + k / ⌘ + k keypress (#2999)
* Feat(SearchBar): open searchBar on `ctrl + k`/ `⌘ + k` keypress * Fix: tab focus
1 parent 8ac49f3 commit fc2cede

2 files changed

Lines changed: 52 additions & 13 deletions

File tree

src/components/CommonComponents/SearchBar/index.tsx

Lines changed: 19 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -91,11 +91,25 @@ const SearchBar = (): JSX.Element => {
9191
}
9292
};
9393

94-
useKeyPress('/', () => expandContainer());
95-
useKeyPress('Escape', () => {
96-
if (isExpanded) {
97-
collapseContainer();
98-
}
94+
useKeyPress({
95+
targetKey: 'ctrl+k',
96+
callback: expandContainer,
97+
preventDefault: true,
98+
});
99+
100+
useKeyPress({
101+
targetKey: 'meta+k',
102+
callback: expandContainer,
103+
preventDefault: true,
104+
});
105+
106+
useKeyPress({
107+
targetKey: 'Escape',
108+
callback: () => {
109+
if (isExpanded) {
110+
collapseContainer();
111+
}
112+
},
99113
});
100114

101115
return (

src/hooks/useKeyPress.tsx

Lines changed: 33 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -3,21 +3,46 @@
33
*/
44
import { useEffect, useState } from 'react';
55

6-
function useKeyPress(targetKey: string, cb?: () => void): boolean {
6+
const decorateKey = ({ metaKey, ctrlKey, key }: KeyboardEvent) => {
7+
if (metaKey) {
8+
return `meta+${key}`;
9+
}
10+
11+
if (ctrlKey) {
12+
return `ctrl+${key}`;
13+
}
14+
15+
return key;
16+
};
17+
18+
interface UseKeyPressProps {
19+
targetKey: string;
20+
callback?: () => void;
21+
preventDefault?: boolean;
22+
}
23+
24+
function useKeyPress({
25+
targetKey,
26+
callback,
27+
preventDefault = false,
28+
}: UseKeyPressProps): boolean {
729
const [keyPressed, setKeyPressed] = useState(false);
830

931
useEffect(() => {
10-
const downHandler = ({ key }: KeyboardEvent) => {
11-
if (key === targetKey) {
32+
const downHandler = (e: KeyboardEvent) => {
33+
if (decorateKey(e) === targetKey) {
34+
if (preventDefault) {
35+
e.preventDefault();
36+
}
1237
setKeyPressed(true);
13-
if (cb) {
14-
cb();
38+
if (typeof callback === 'function') {
39+
callback();
1540
}
1641
}
1742
};
1843

19-
const upHandler = ({ key }: KeyboardEvent) => {
20-
if (key === targetKey) {
44+
const upHandler = (e: KeyboardEvent) => {
45+
if (decorateKey(e) === targetKey) {
2146
setKeyPressed(false);
2247
}
2348
};
@@ -28,7 +53,7 @@ function useKeyPress(targetKey: string, cb?: () => void): boolean {
2853
window.removeEventListener('keydown', downHandler);
2954
window.removeEventListener('keyup', upHandler);
3055
};
31-
}, [cb, targetKey]);
56+
}, [callback, targetKey, preventDefault]);
3257
return keyPressed;
3358
}
3459

0 commit comments

Comments
 (0)