dify/web/app/components/goto-anything/hooks/use-goto-anything-modal.ts
Stephen Zhou 36e840cd87
chore: knip fix (#34481)
Co-authored-by: autofix-ci[bot] <114827586+autofix-ci[bot]@users.noreply.github.com>
2026-04-02 15:03:42 +00:00

60 lines
1.5 KiB
TypeScript

'use client'
import type { RefObject } from 'react'
import { useKeyPress } from 'ahooks'
import { useCallback, useEffect, useRef, useState } from 'react'
import { getKeyboardKeyCodeBySystem, isEventTargetInputArea } from '@/app/components/workflow/utils/common'
type UseGotoAnythingModalReturn = {
show: boolean
setShow: (show: boolean | ((prev: boolean) => boolean)) => void
inputRef: RefObject<HTMLInputElement | null>
handleClose: () => void
}
export const useGotoAnythingModal = (): UseGotoAnythingModalReturn => {
const [show, setShow] = useState<boolean>(false)
const inputRef = useRef<HTMLInputElement>(null)
// Handle keyboard shortcuts
const handleToggleModal = useCallback((e: KeyboardEvent) => {
// Allow closing when modal is open, even if focus is in the search input
if (!show && isEventTargetInputArea(e.target as HTMLElement))
return
e.preventDefault()
setShow(prev => !prev)
}, [show])
useKeyPress(`${getKeyboardKeyCodeBySystem('ctrl')}.k`, handleToggleModal, {
exactMatch: true,
useCapture: true,
})
useKeyPress(['esc'], (e) => {
if (show) {
e.preventDefault()
setShow(false)
}
})
const handleClose = useCallback(() => {
setShow(false)
}, [])
// Focus input when modal opens
useEffect(() => {
if (show) {
requestAnimationFrame(() => {
inputRef.current?.focus()
})
}
}, [show])
return {
show,
setShow,
inputRef,
handleClose,
}
}