diff --git a/ui/src/common/useSearchRefocus.js b/ui/src/common/useSearchRefocus.js index 27898b969..4e8c22d2b 100644 --- a/ui/src/common/useSearchRefocus.js +++ b/ui/src/common/useSearchRefocus.js @@ -1,19 +1,32 @@ -import { useEffect } from 'react' +import { useEffect, useRef } from 'react' +import { useLocation } from 'react-router-dom' export const useSearchRefocus = () => { + const location = useLocation() + const prevSearchValue = useRef(null) + useEffect(() => { - const handleClick = (e) => { - const clearButton = e.target.closest('[aria-label*="clear" i]') - if (clearButton) { - setTimeout(() => { - const searchInput = document.querySelector('[class*="RaSearchInput"] input') - if (searchInput) { - searchInput.focus() - } - }, 800) - } + const params = new URLSearchParams(location.search) + const filterStr = params.get('filter') || '{}' + + let filter = {} + try { + filter = JSON.parse(filterStr) + } catch (e) { + // Invalid JSON, ignore } - document.addEventListener('click', handleClick, true) - return () => document.removeEventListener('click', handleClick, true) - }, []) + + const searchValue = filter.name || filter.title || filter.q || '' + + if (prevSearchValue.current && !searchValue) { + setTimeout(() => { + const input = document.querySelector('[class*="RaSearchInput"] input') + if (input) { + input.focus() + } + }, 100) + } + + prevSearchValue.current = searchValue + }, [location.search]) } diff --git a/ui/src/common/useSearchRefocus.test.js b/ui/src/common/useSearchRefocus.test.js index 8498633fa..20f1cfb90 100644 --- a/ui/src/common/useSearchRefocus.test.js +++ b/ui/src/common/useSearchRefocus.test.js @@ -2,6 +2,11 @@ import { vi, describe, it, expect, beforeEach, afterEach } from 'vitest' import { renderHook } from '@testing-library/react-hooks' import { useSearchRefocus } from './useSearchRefocus' +const mockLocation = { search: '' } +vi.mock('react-router-dom', () => ({ + useLocation: () => mockLocation, +})) + describe('useSearchRefocus', () => { let container @@ -9,12 +14,12 @@ describe('useSearchRefocus', () => { vi.useFakeTimers() container = document.createElement('div') container.innerHTML = ` -