| 105 | } |
| 106 | |
| 107 | export function useAtCompletion(props: UseAtCompletionProps): void { |
| 108 | const { |
| 109 | enabled, |
| 110 | pattern, |
| 111 | config, |
| 112 | cwd, |
| 113 | setSuggestions, |
| 114 | setIsLoadingSuggestions, |
| 115 | } = props; |
| 116 | const [state, dispatch] = useReducer(atCompletionReducer, initialState); |
| 117 | const fileSearch = useRef<FileSearch | null>(null); |
| 118 | const searchAbortController = useRef<AbortController | null>(null); |
| 119 | const slowSearchTimer = useRef<NodeJS.Timeout | null>(null); |
| 120 | |
| 121 | useEffect(() => { |
| 122 | setSuggestions(state.suggestions); |
| 123 | }, [state.suggestions, setSuggestions]); |
| 124 | |
| 125 | useEffect(() => { |
| 126 | setIsLoadingSuggestions(state.isLoading); |
| 127 | }, [state.isLoading, setIsLoadingSuggestions]); |
| 128 | |
| 129 | useEffect(() => { |
| 130 | dispatch({ type: 'RESET' }); |
| 131 | }, [cwd, config]); |
| 132 | |
| 133 | // Reacts to user input (`pattern`) ONLY. |
| 134 | useEffect(() => { |
| 135 | if (!enabled) { |
| 136 | // reset when first getting out of completion suggestions |
| 137 | if ( |
| 138 | state.status === AtCompletionStatus.READY || |
| 139 | state.status === AtCompletionStatus.ERROR |
| 140 | ) { |
| 141 | dispatch({ type: 'RESET' }); |
| 142 | } |
| 143 | return; |
| 144 | } |
| 145 | if (pattern === null) { |
| 146 | dispatch({ type: 'RESET' }); |
| 147 | return; |
| 148 | } |
| 149 | |
| 150 | if (state.status === AtCompletionStatus.IDLE) { |
| 151 | dispatch({ type: 'INITIALIZE' }); |
| 152 | } else if ( |
| 153 | (state.status === AtCompletionStatus.READY || |
| 154 | state.status === AtCompletionStatus.SEARCHING) && |
| 155 | pattern !== state.pattern // Only search if the pattern has changed |
| 156 | ) { |
| 157 | dispatch({ type: 'SEARCH', payload: pattern }); |
| 158 | } |
| 159 | }, [enabled, pattern, state.status, state.pattern]); |
| 160 | |
| 161 | // The "Worker" that performs async operations based on status. |
| 162 | useEffect(() => { |
| 163 | const initialize = async () => { |
| 164 | try { |