Files
supabase/packages/ui-patterns/CommandMenu/api/hooks/useHistoryKeys.ts
Charis 1b89fa0b5c feat: command menu v2 ui components (#27761)
Co-authored-by: Francesco Sansalvadore <f.sansalvadore@gmail.com>
2024-07-16 14:14:03 -04:00

47 lines
1.0 KiB
TypeScript

'use client'
import { useCallback, useEffect, useState } from 'react'
import { useSetQuery } from './queryHooks'
interface UseHistoryKeysOptions {
stack: string[]
enable?: boolean
}
/**
* Enables shell-style message history when hitting up/down on the keyboard
*/
function useHistoryKeys({ stack, enable = true }: UseHistoryKeysOptions) {
const [idx, setIdx] = useState(0)
const setQuery = useSetQuery()
const navigateIdx = useCallback((newIdx: number) => {
if (!enable) return
setQuery(stack[newIdx] ?? '')
setIdx(newIdx)
}, [])
useEffect(() => {
function onKeyDown(e: KeyboardEvent) {
switch (e.key) {
case 'ArrowUp':
return navigateIdx(Math.max(idx - 1, 0))
case 'ArrowDown':
return navigateIdx(Math.min(idx + 1, stack.length - 1))
default:
return
}
}
window.addEventListener('keydown', onKeyDown)
return () => {
window.removeEventListener('keydown', onKeyDown)
}
}, [navigateIdx, stack])
}
export { useHistoryKeys }