fix: focus command palette ai mode immediately

This commit is contained in:
lucaronin
2026-04-13 13:42:46 +02:00
parent 71df363bb6
commit d4aacf1bea
2 changed files with 22 additions and 10 deletions

View File

@@ -235,6 +235,16 @@ describe('CommandPalette', () => {
expect(screen.queryByText('Search Notes')).not.toBeInTheDocument()
})
it('focuses the AI editor immediately when the leading space triggers AI mode', () => {
render(<CommandPalette open={true} commands={commands} entries={entries} onClose={onClose} />)
const input = screen.getByPlaceholderText('Type a command...')
input.focus()
fireEvent.change(input, { target: { value: ' ' } })
expect(screen.getByTestId('command-palette-ai-input')).toHaveFocus()
})
it('returns to command mode when the leading space is deleted', () => {
render(
<CommandPalette open={true} commands={commands} entries={entries} onClose={onClose} />,

View File

@@ -1,4 +1,4 @@
import { useEffect, useMemo, useRef, useState } from 'react'
import { useEffect, useLayoutEffect, useMemo, useRef, useState } from 'react'
import { cn } from '@/lib/utils'
import type { VaultEntry } from '../types'
import { fuzzyMatch } from '../utils/fuzzyMatch'
@@ -205,15 +205,17 @@ function OpenCommandPalette({
const aiMode = aiValue.startsWith(' ')
const { groups, flatList } = usePaletteResults(commands, query)
useEffect(() => {
const focusTimer = window.setTimeout(() => {
if (aiMode) {
aiInputRef.current?.focus()
return
}
inputRef.current?.focus()
}, 50)
return () => window.clearTimeout(focusTimer)
useLayoutEffect(() => {
const target = aiMode ? aiInputRef.current : inputRef.current
if (!target) return
target.focus()
if (document.activeElement === target) return
const focusRetry = window.requestAnimationFrame(() => {
target.focus()
})
return () => window.cancelAnimationFrame(focusRetry)
}, [aiMode])
useEffect(() => {