Skip to content

Commit

Permalink
Merge pull request #111 from ksarlou/feature-add-shortcut-support
Browse files Browse the repository at this point in the history
feat(SearchBar): add shortcut (cmd/ctrl + K) support
  • Loading branch information
weareoutman authored Dec 4, 2021
2 parents 9093d71 + 6aafb2d commit 942a815
Show file tree
Hide file tree
Showing 2 changed files with 52 additions and 1 deletion.
24 changes: 23 additions & 1 deletion src/client/theme/SearchBar/SearchBar.module.css
Original file line number Diff line number Diff line change
Expand Up @@ -189,7 +189,7 @@ html[data-theme="dark"] .noResultsIcon {
.searchBarContainer .searchBarLoadingRing {
display: none;
position: absolute;
left: calc(var(--ifm-navbar-padding-horizontal) + 10px);
left: 10px;
top: 6px;
}

Expand All @@ -205,6 +205,28 @@ html[data-theme="dark"] .noResultsIcon {
display: inline-block;
}

.searchHintContainer {
position: absolute;
right: 10px;
top: 0px;
display: flex;
align-items: center;
justify-content: center;
height: 100%;
pointer-events: none;
gap: 4px;
}

.searchHint {
color: var(--ifm-navbar-search-input-placeholder-color);
}

@media (max-width: 576px) {
.searchHintContainer {
display: none;
}
}

/* For autocomplete.js only. */
.input {
}
Expand Down
29 changes: 29 additions & 0 deletions src/client/theme/SearchBar/SearchBar.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -201,6 +201,31 @@ export default function SearchBar({
[]
);

// Implement hint icons for the search shortcuts on mac and the rest operating systems.
const isMac = ExecutionEnvironment.canUseDOM
? /mac/i.test(
(navigator as any).userAgentData?.platform ?? navigator.platform
)
: false;

useEffect(() => {
// Add shortcuts command/ctrl + K
function handleShortcut(event: KeyboardEvent): void {
if ((isMac ? event.metaKey : event.ctrlKey) && event.code === "KeyK") {
event.preventDefault();
searchBarRef.current?.focus();
}
}
// "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.
const eventType = isMac ? "keydown" : "keypress";
document.addEventListener(eventType, handleShortcut);

return () => {
document.removeEventListener(eventType, handleShortcut);
};
}, [isMac]);

return (
<div
className={clsx("navbar__search", styles.searchBarContainer, {
Expand All @@ -218,6 +243,10 @@ export default function SearchBar({
ref={searchBarRef}
/>
<LoadingRing className={styles.searchBarLoadingRing} />
<div className={styles.searchHintContainer}>
<kbd className={styles.searchHint}>{isMac ? "⌘" : "ctrl"}</kbd>
<kbd className={styles.searchHint}>K</kbd>
</div>
</div>
);
}

0 comments on commit 942a815

Please sign in to comment.