feature: on pressing ctrl+k on windows and cmd+k on mac search bar will be focused

This commit is contained in:
Harry 2024-10-05 17:01:33 +05:30
parent 651f984e52
commit 78d5ab5499

View file

@ -9,6 +9,25 @@ import { toast } from "@/components/ui/use-toast"
interface DocsSearchProps extends React.HTMLAttributes<HTMLFormElement> {}
export function DocsSearch({ className, ...props }: DocsSearchProps) {
const inputRef = React.useRef<HTMLInputElement>(null)
// if user presses ctrl+k, focus the search input on windows and cmd+k on mac
React.useEffect(() => {
const handleKeyDown = (event: KeyboardEvent) => {
if (
(event.ctrlKey || event.metaKey) &&
event.key === "k" &&
document.activeElement !== inputRef.current
) {
event.preventDefault()
inputRef.current?.focus()
}
}
document.addEventListener("keydown", handleKeyDown)
return () => {
document.removeEventListener("keydown", handleKeyDown)
}
}, [])
function onSubmit(event: React.SyntheticEvent) {
event.preventDefault()
@ -28,6 +47,7 @@ export function DocsSearch({ className, ...props }: DocsSearchProps) {
type="search"
placeholder="Search documentation..."
className="h-8 w-full sm:w-64 sm:pr-12"
ref={inputRef}
/>
<kbd className="pointer-events-none absolute right-1.5 top-1.5 hidden h-5 select-none items-center gap-1 rounded border bg-background px-1.5 font-mono text-[10px] font-medium text-muted-foreground opacity-100 sm:flex">
<span className="text-xs"></span>K