({
items,
resetKey,
filterFn,
}: UseSearchableListOptions<T>)
| 41 | * Handles search filtering, focus management, and automatic index clamping. |
| 42 | */ |
| 43 | export function useSearchableList<T extends SearchableItem>({ |
| 44 | items, |
| 45 | resetKey, |
| 46 | filterFn, |
| 47 | }: UseSearchableListOptions<T>): UseSearchableListReturn<T> { |
| 48 | const [searchQuery, setSearchQuery] = useState('') |
| 49 | const [focusedIndex, setFocusedIndex] = useState(0) |
| 50 | |
| 51 | // Default filter function: case-insensitive label matching |
| 52 | const defaultFilterFn = useCallback( |
| 53 | (item: T, query: string) => |
| 54 | item.label.toLowerCase().includes(query.toLowerCase()), |
| 55 | [], |
| 56 | ) |
| 57 | |
| 58 | const filterFunction = filterFn ?? defaultFilterFn |
| 59 | |
| 60 | // Filter items based on search query |
| 61 | // Skip filtering for path-like queries (starting with / or ~) - those are for navigation, not filtering |
| 62 | const filteredItems = useMemo(() => { |
| 63 | const trimmedQuery = searchQuery.trim() |
| 64 | if (!trimmedQuery) return items |
| 65 | // Path-like queries should not filter the directory list |
| 66 | if (trimmedQuery.startsWith('/') || trimmedQuery.startsWith('~')) return items |
| 67 | // Always keep parent directory entry (..) visible, filter others |
| 68 | return items.filter((item) => |
| 69 | item.label === '..' || filterFunction(item, trimmedQuery) |
| 70 | ) |
| 71 | }, [items, searchQuery, filterFunction]) |
| 72 | |
| 73 | // Reset focus when resetKey changes (but keep search query) |
| 74 | useEffect(() => { |
| 75 | setFocusedIndex(0) |
| 76 | }, [resetKey]) |
| 77 | |
| 78 | // Clamp focused index when filtered list changes |
| 79 | useEffect(() => { |
| 80 | if (focusedIndex >= filteredItems.length) { |
| 81 | setFocusedIndex(Math.max(0, filteredItems.length - 1)) |
| 82 | } |
| 83 | }, [filteredItems.length, focusedIndex]) |
| 84 | |
| 85 | // Handle focus change from hover |
| 86 | const handleFocusChange = useCallback((index: number) => { |
| 87 | setFocusedIndex(index) |
| 88 | }, []) |
| 89 | |
| 90 | return { |
| 91 | searchQuery, |
| 92 | setSearchQuery, |
| 93 | focusedIndex, |
| 94 | setFocusedIndex, |
| 95 | filteredItems, |
| 96 | handleFocusChange, |
| 97 | } |
| 98 | } |
no outgoing calls
no test coverage detected