()
| 21 | * 全局搜索 Hook |
| 22 | */ |
| 23 | export function useGlobalSearch(): UseGlobalSearchResult { |
| 24 | const { |
| 25 | query, |
| 26 | options, |
| 27 | setResults, |
| 28 | setSearching, |
| 29 | selectedIndex, |
| 30 | setSelectedIndex, |
| 31 | results, |
| 32 | setHighlightMatch, |
| 33 | searchTrigger |
| 34 | } = useGlobalSearchStore() |
| 35 | const { pages } = usePagesStore() |
| 36 | const { load } = useMessagesStore() |
| 37 | |
| 38 | const debounceRef = useRef<ReturnType<typeof setTimeout> | null>(null) |
| 39 | const abortControllerRef = useRef<AbortController | null>(null) |
| 40 | |
| 41 | // 加载消息的函数 |
| 42 | const loadMessages = useCallback( |
| 43 | async (pageId: string) => { |
| 44 | return load(pageId) |
| 45 | }, |
| 46 | [load] |
| 47 | ) |
| 48 | |
| 49 | // 执行搜索 |
| 50 | const executeSearch = useCallback(async () => { |
| 51 | const generation = getSwitchGeneration() |
| 52 | // 取消之前的搜索 |
| 53 | if (abortControllerRef.current) { |
| 54 | abortControllerRef.current.abort() |
| 55 | } |
| 56 | abortControllerRef.current = new AbortController() |
| 57 | |
| 58 | if (!query.trim()) { |
| 59 | setResults([], 0) |
| 60 | setSearching(false) |
| 61 | return |
| 62 | } |
| 63 | |
| 64 | setSearching(true) |
| 65 | |
| 66 | try { |
| 67 | const result = await performGlobalSearch(query, options, pages, loadMessages) |
| 68 | if (generation !== getSwitchGeneration()) { |
| 69 | return |
| 70 | } |
| 71 | setResults(result.groups, result.totalCount) |
| 72 | } catch (error) { |
| 73 | if (error instanceof Error && error.name !== 'AbortError') { |
| 74 | console.error('Global search error:', error) |
| 75 | } |
| 76 | if (generation !== getSwitchGeneration()) { |
| 77 | return |
| 78 | } |
| 79 | setResults([], 0) |
| 80 | } finally { |
no test coverage detected