({ pageId, messages, containerRef }: SearchBarProps)
| 15 | } |
| 16 | |
| 17 | export function SearchBar({ pageId, messages, containerRef }: SearchBarProps): React.JSX.Element { |
| 18 | const inputRef = useRef<InputRef>(null) |
| 19 | |
| 20 | const searchState = useChatUIStore((state) => state.getState(pageId).search) |
| 21 | const setSearchQuery = useChatUIStore((state) => state.setSearchQuery) |
| 22 | const setSearchCurrentIndex = useChatUIStore((state) => state.setSearchCurrentIndex) |
| 23 | const setSearchOptions = useChatUIStore((state) => state.setSearchOptions) |
| 24 | const setSearchOpen = useChatUIStore((state) => state.setSearchOpen) |
| 25 | |
| 26 | // 使用搜索高亮 Hook |
| 27 | const { total, scrollToMatch } = useSearchHighlight({ |
| 28 | containerRef, |
| 29 | messages, |
| 30 | searchState, |
| 31 | pageId |
| 32 | }) |
| 33 | |
| 34 | // 自动聚焦并选中输入框 |
| 35 | useEffect(() => { |
| 36 | const timer = setTimeout(() => { |
| 37 | inputRef.current?.focus() |
| 38 | inputRef.current?.select() |
| 39 | }, 50) |
| 40 | return () => clearTimeout(timer) |
| 41 | }, [searchState.focusRequestKey]) |
| 42 | |
| 43 | // 当 currentIndex 变化时滚动到对应位置 |
| 44 | useEffect(() => { |
| 45 | if (total > 0) { |
| 46 | scrollToMatch(searchState.currentIndex) |
| 47 | } |
| 48 | }, [searchState.currentIndex, total, scrollToMatch]) |
| 49 | |
| 50 | // 导航到下一个匹配 |
| 51 | const goToNext = useCallback(() => { |
| 52 | if (total === 0) return |
| 53 | const nextIndex = (searchState.currentIndex + 1) % total |
| 54 | setSearchCurrentIndex(pageId, nextIndex) |
| 55 | }, [pageId, searchState.currentIndex, total, setSearchCurrentIndex]) |
| 56 | |
| 57 | // 导航到上一个匹配 |
| 58 | const goToPrev = useCallback(() => { |
| 59 | if (total === 0) return |
| 60 | const prevIndex = (searchState.currentIndex - 1 + total) % total |
| 61 | setSearchCurrentIndex(pageId, prevIndex) |
| 62 | }, [pageId, searchState.currentIndex, total, setSearchCurrentIndex]) |
| 63 | |
| 64 | // 关闭搜索栏 |
| 65 | const handleClose = useCallback(() => { |
| 66 | setSearchOpen(pageId, false) |
| 67 | }, [pageId, setSearchOpen]) |
| 68 | |
| 69 | // 处理输入变化 |
| 70 | const handleInputChange = useCallback( |
| 71 | (e: React.ChangeEvent<HTMLInputElement>) => { |
| 72 | setSearchQuery(pageId, e.target.value) |
| 73 | }, |
| 74 | [pageId, setSearchQuery] |
nothing calls this directly
no test coverage detected