Skip to content

Commit

Permalink
feat(SearchBar): add shortcut (cmd/ctrl + K) support
Browse files Browse the repository at this point in the history
  • Loading branch information
ksarlou committed Oct 13, 2021
1 parent 08b9967 commit c66851d
Show file tree
Hide file tree
Showing 2 changed files with 63 additions and 0 deletions.
18 changes: 18 additions & 0 deletions src/client/theme/SearchBar/SearchBar.module.css
Original file line number Diff line number Diff line change
Expand Up @@ -205,6 +205,24 @@ html[data-theme="dark"] .noResultsIcon {
display: inline-block;
}

.search_hint_container {
display: inline-block;
background: white;
height: 2rem;
padding: 5px;
}

.search_hint {
color: #bec3c8;
margin: 2px;
}

@media only screen and (max-width: 600px) {
.search_hint_container {
display: none;
}
}

/* For autocomplete.js only. */
.input {
}
Expand Down
45 changes: 45 additions & 0 deletions src/client/theme/SearchBar/SearchBar.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -58,6 +58,7 @@ export default function SearchBar({
const focusAfterIndexLoaded = useRef(false);
const [loading, setLoading] = useState(false);
const [inputChanged, setInputChanged] = useState(false);
const [modifierKey, setModifierKey] = useState("");

const loadIndex = useCallback(async () => {
if (indexState.current !== "empty") {
Expand Down Expand Up @@ -200,6 +201,46 @@ export default function SearchBar({
},
[]
);
//add shortcuts command/ctrl + K
function handleShortcut(event: any) {
if (event.ctrlKey && event.code === "KeyK") {
event.preventDefault();
searchBarRef?.current?.focus();
}
}

// we added this extra function because "keydown" is the only way to capture the "command" key on mac. Then we use the metaKey boolean prop to see if the "command" key was pressed.
function handleShortcutOnMac(event: any) {
if (event.metaKey && event.code === "KeyK") {
event.preventDefault();
searchBarRef?.current?.focus();
}
}

useEffect(() => {
const userOS = navigator.platform;
setKeyShortcutsPerOS(userOS);

if (userOS.includes("Mac")) {
document.addEventListener("keydown", handleShortcutOnMac);
} else {
document.addEventListener("keypress", handleShortcut);
}

return () => {
document.removeEventListener("keydown", handleShortcutOnMac);
document.removeEventListener("keypress", handleShortcut);
};
}, []);

//impement hint icons for the search shortcuts on mac and the rest operating systems
function setKeyShortcutsPerOS(userOS: string) {
if (userOS.includes("Mac")) {
setModifierKey("⌘");
} else {
setModifierKey("ctrl");
}
}

return (
<div
Expand All @@ -218,6 +259,10 @@ export default function SearchBar({
ref={searchBarRef}
/>
<LoadingRing className={styles.searchBarLoadingRing} />
<div className={styles.search_hint_container}>
<kbd className={styles.search_hint}>{modifierKey}</kbd>
<kbd className={styles.search_hint}>K</kbd>
</div>
</div>
);
}

0 comments on commit c66851d

Please sign in to comment.