Skip to content

Commit

Permalink
feat: cmd+k or ctrl+k to focus the search input (#86)
Browse files Browse the repository at this point in the history
  • Loading branch information
PatrickDinh authored Jun 8, 2024
1 parent d3df7a1 commit 5a876d2
Show file tree
Hide file tree
Showing 2 changed files with 21 additions and 3 deletions.
23 changes: 20 additions & 3 deletions src/features/search/components/search.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -8,20 +8,22 @@ import {
CommandLoading,
} from '@/features/common/components/command'
import { cn } from '@/features/common/utils'
import { useCallback } from 'react'
import { useCallback, useEffect, useRef } from 'react'
import { RenderLoadable } from '@/features/common/components/render-loadable'
import { useNavigate } from 'react-router-dom'
import { useSearch } from '../data'
import { Loader } from 'lucide-react'
import { Badge } from '@/features/common/components/badge'
import { useLocationChange } from '@/features/common/hooks/use-location-change'
import { isMacOs } from '@/utils/is-mac-platform.ts'

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

export function Search() {
const navigate = useNavigate()
const [term, setTerm, loadableResults] = useSearch()
const searchInputRef = useRef<HTMLInputElement>(null)

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

useLocationChange(clearTerm)

useEffect(() => {
const down = (e: KeyboardEvent) => {
if (e.key === 'k' && (e.metaKey || e.ctrlKey)) {
e.preventDefault()
searchInputRef.current?.focus()
}
if (e.key === 'Escape') {
e.preventDefault()
setTerm('')
}
}
document.addEventListener('keydown', down)
return () => document.removeEventListener('keydown', down)
}, [setTerm])

return (
<Command className={cn('bg-card text-card-foreground w-80 h-auto z-20 border')} shouldFilter={false} loop>
<CommandInput placeholder={searchPlaceholderLabel} value={term} onValueChange={handleInput} />
<CommandInput placeholder={searchPlaceholderLabel} value={term} onValueChange={handleInput} ref={searchInputRef} />
<CommandList>
<RenderLoadable
loadable={loadableResults}
Expand Down
1 change: 1 addition & 0 deletions src/utils/is-mac-platform.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
export const isMacOs = navigator.userAgent.indexOf('Mac') > -1

0 comments on commit 5a876d2

Please sign in to comment.