Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat(SearchBar): add shortcut (cmd/ctrl + K) support #111

Merged
merged 3 commits into from
Dec 4, 2021
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
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>
);
}