Skip to content

Commit 5a876d2

Browse files
authored
feat: cmd+k or ctrl+k to focus the search input (#86)
1 parent d3df7a1 commit 5a876d2

File tree

2 files changed

+21
-3
lines changed

2 files changed

+21
-3
lines changed

src/features/search/components/search.tsx

Lines changed: 20 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -8,20 +8,22 @@ import {
88
CommandLoading,
99
} from '@/features/common/components/command'
1010
import { cn } from '@/features/common/utils'
11-
import { useCallback } from 'react'
11+
import { useCallback, useEffect, useRef } from 'react'
1212
import { RenderLoadable } from '@/features/common/components/render-loadable'
1313
import { useNavigate } from 'react-router-dom'
1414
import { useSearch } from '../data'
1515
import { Loader } from 'lucide-react'
1616
import { Badge } from '@/features/common/components/badge'
1717
import { useLocationChange } from '@/features/common/hooks/use-location-change'
18+
import { isMacOs } from '@/utils/is-mac-platform.ts'
1819

19-
export const searchPlaceholderLabel = 'Search by ID or Address'
20+
export const searchPlaceholderLabel = `Search by ID or Address ${isMacOs ? '(⌘K)' : '(Ctrl+K)'}`
2021
export const noSearchResultsMessage = 'No results.'
2122

2223
export function Search() {
2324
const navigate = useNavigate()
2425
const [term, setTerm, loadableResults] = useSearch()
26+
const searchInputRef = useRef<HTMLInputElement>(null)
2527

2628
const handleInput = useCallback(
2729
(id: string) => {
@@ -41,9 +43,24 @@ export function Search() {
4143

4244
useLocationChange(clearTerm)
4345

46+
useEffect(() => {
47+
const down = (e: KeyboardEvent) => {
48+
if (e.key === 'k' && (e.metaKey || e.ctrlKey)) {
49+
e.preventDefault()
50+
searchInputRef.current?.focus()
51+
}
52+
if (e.key === 'Escape') {
53+
e.preventDefault()
54+
setTerm('')
55+
}
56+
}
57+
document.addEventListener('keydown', down)
58+
return () => document.removeEventListener('keydown', down)
59+
}, [setTerm])
60+
4461
return (
4562
<Command className={cn('bg-card text-card-foreground w-80 h-auto z-20 border')} shouldFilter={false} loop>
46-
<CommandInput placeholder={searchPlaceholderLabel} value={term} onValueChange={handleInput} />
63+
<CommandInput placeholder={searchPlaceholderLabel} value={term} onValueChange={handleInput} ref={searchInputRef} />
4764
<CommandList>
4865
<RenderLoadable
4966
loadable={loadableResults}

src/utils/is-mac-platform.ts

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1 @@
1+
export const isMacOs = navigator.userAgent.indexOf('Mac') > -1

0 commit comments

Comments
 (0)