| 1 | import { |
| 2 | ContextProviderDescription, |
| 3 | ContextProviderName, |
| 4 | ContextSubmenuItemWithProvider, |
| 5 | } from "core"; |
| 6 | import { deduplicateArray, splitCamelCaseAndNonAlphaNumeric } from "core/util"; |
| 7 | import { |
| 8 | getShortestUniqueRelativeUriPaths, |
| 9 | getUriPathBasename, |
| 10 | } from "core/util/uri"; |
| 11 | import MiniSearch, { SearchResult } from "minisearch"; |
| 12 | import { |
| 13 | createContext, |
| 14 | useCallback, |
| 15 | useContext, |
| 16 | useEffect, |
| 17 | useRef, |
| 18 | useState, |
| 19 | } from "react"; |
| 20 | import { useWebviewListener } from "../hooks/useWebviewListener"; |
| 21 | import { useAppSelector } from "../redux/hooks"; |
| 22 | import { selectSubmenuContextProviders } from "../redux/selectors"; |
| 23 | import { IdeMessengerContext } from "./IdeMessenger"; |
| 24 | |
| 25 | const MINISEARCH_OPTIONS = { |
| 26 | prefix: true, |
| 27 | fuzzy: 2, |
| 28 | }; |
| 29 | |
| 30 | const MAX_LENGTH = 70; |
| 31 | |
| 32 | interface SubtextContextProvidersContextType { |
| 33 | getSubmenuContextItems: ( |
| 34 | providerTitle: string | undefined, |
| 35 | query: string, |
| 36 | ) => ContextSubmenuItemWithProvider[]; |
| 37 | } |
| 38 | |
| 39 | const initialContextProviders: SubtextContextProvidersContextType = { |
| 40 | getSubmenuContextItems: () => [], |
| 41 | }; |
| 42 | |
| 43 | const SubmenuContextProvidersContext = |
| 44 | createContext<SubtextContextProvidersContextType>(initialContextProviders); |
| 45 | |
| 46 | export const SubmenuContextProvidersProvider = ({ |
| 47 | children, |
| 48 | }: { |
| 49 | children: React.ReactNode; |
| 50 | }) => { |
| 51 | const ideMessenger = useContext(IdeMessengerContext); |
| 52 | const submenuContextProviders = useAppSelector(selectSubmenuContextProviders); |
| 53 | const lastProviders = useRef(submenuContextProviders); |
| 54 | const disableIndexing = useAppSelector( |
| 55 | (store) => store.config.config.disableIndexing, |
| 56 | ); |
| 57 | |
| 58 | const [minisearches, setMinisearches] = useState<{ |
| 59 | [id: string]: MiniSearch<ContextSubmenuItemWithProvider>; |
| 60 | }>({}); |
| 61 | const [fallbackResults, setFallbackResults] = useState<{ |
| 62 | [id: string]: ContextSubmenuItemWithProvider[]; |
| 63 | }>({}); |
| 64 | |
| 65 | // Update open files for file provider on an interval |
| 66 | const lastOpenFilesRef = useRef<ContextSubmenuItemWithProvider[]>([]); |
| 67 | useEffect(() => { |
| 68 | function hasOpenFilesChanged( |
| 69 | newFiles: ContextSubmenuItemWithProvider[], |
| 70 | oldFiles: ContextSubmenuItemWithProvider[], |
| 71 | ) { |
| 72 | const newIds = new Set(newFiles.map((f) => f.id)); |
| 73 | const oldIds = new Set(oldFiles.map((f) => f.id)); |
| 74 | |
| 75 | if (newIds.size !== oldIds.size) return true; |
| 76 | |
| 77 | for (const id of newIds) { |
| 78 | if (!oldIds.has(id)) return true; |
| 79 | } |
| 80 | |
| 81 | for (const id of oldIds) { |
| 82 | if (!newIds.has(id)) return true; |
| 83 | } |
| 84 | return false; |
| 85 | } |
| 86 | |
| 87 | let isMounted = true; |
| 88 | const refreshOpenFiles = async () => { |
| 89 | if (!isMounted) return; |
| 90 | |
| 91 | const openFiles = await ideMessenger.ide.getOpenFiles(); |
| 92 | const workspaceDirs = await ideMessenger.ide.getWorkspaceDirs(); |
| 93 | const withUniquePaths = getShortestUniqueRelativeUriPaths( |
| 94 | openFiles, |
| 95 | workspaceDirs, |
| 96 | ); |
| 97 | const openFileItems = withUniquePaths.map((file) => ({ |
| 98 | id: file.uri, |
| 99 | title: getUriPathBasename(file.uri), |
| 100 | description: file.uniquePath, |
| 101 | providerTitle: "file", |
| 102 | })); |
| 103 | |
| 104 | if (hasOpenFilesChanged(openFileItems, lastOpenFilesRef.current)) { |
| 105 | setFallbackResults((prev) => ({ |
| 106 | ...prev, |
| 107 | file: deduplicateArray( |
| 108 | [...openFileItems, ...(prev.file ?? [])], |
| 109 | (a, b) => a.id === b.id, |
| 110 | ), |
| 111 | })); |
| 112 | } |
| 113 | lastOpenFilesRef.current = openFileItems; |
| 114 | }; |
| 115 | |
| 116 | const interval = setInterval(refreshOpenFiles, 2000); |
| 117 | |
| 118 | refreshOpenFiles(); // Initial call |
| 119 | |
| 120 | return () => { |
| 121 | isMounted = false; |
| 122 | clearInterval(interval); |
| 123 | }; |
| 124 | }, [ideMessenger]); |
| 125 | |
| 126 | const providersLoading = useRef(new Set<ContextProviderName>()).current; |
| 127 | const abortControllers = useRef( |
| 128 | new Map<ContextProviderName, AbortController>(), |
| 129 | ).current; |
| 130 | |
| 131 | const getSubmenuContextItems = useCallback( |
| 132 | ( |
| 133 | providerTitle: string | undefined, |
| 134 | query: string, |
| 135 | limit: number = MAX_LENGTH, |
| 136 | ): ContextSubmenuItemWithProvider[] => { |
| 137 | try { |
| 138 | // 1. Search using minisearch |
| 139 | let searchResults: (SearchResult & ContextSubmenuItemWithProvider)[] = |
| 140 | []; |
| 141 | |
| 142 | if (providerTitle === undefined) { |
| 143 | // Include results from all providers |
| 144 | searchResults = Object.keys(minisearches).flatMap((providerTitle) => |
| 145 | minisearches[providerTitle] |
| 146 | .search(query, MINISEARCH_OPTIONS) |
| 147 | .map((result) => { |
| 148 | return { |
| 149 | ...result, |
| 150 | providerTitle, |
| 151 | title: result.title, |
| 152 | description: result.description, |
| 153 | }; |
| 154 | }), |
| 155 | ); |
| 156 | } else { |
| 157 | // Only include results from the specified provider |
| 158 | if (minisearches[providerTitle]) { |
| 159 | searchResults = minisearches[providerTitle] |
| 160 | .search(query, MINISEARCH_OPTIONS) |
| 161 | .map((result) => { |
| 162 | return { |
| 163 | ...result, |
| 164 | providerTitle, |
| 165 | title: result.title, |
| 166 | description: result.description, |
| 167 | }; |
| 168 | }); |
| 169 | } |
| 170 | } |
| 171 | searchResults.sort((a, b) => b.score - a.score); |
| 172 | |
| 173 | // 2. Add fallback results if no search results |
| 174 | if (searchResults.length === 0) { |
| 175 | const fallbackItems = ( |
| 176 | providerTitle ? (fallbackResults[providerTitle] ?? []) : [] |
| 177 | ) |
| 178 | .slice(0, limit) |
| 179 | .map((result) => { |
| 180 | return { |
| 181 | ...result, |
| 182 | providerTitle: providerTitle || "unknown", |
| 183 | }; |
| 184 | }); |
| 185 | |
| 186 | if (fallbackItems.length === 0) { |
| 187 | const loadingFiller = [ |
| 188 | { |
| 189 | id: "loading", |
| 190 | title: "Loading...", |
| 191 | description: "Please wait while items are being loaded", |
| 192 | providerTitle: providerTitle || "unknown", |
| 193 | }, |
| 194 | ]; |
| 195 | |
| 196 | // If getting for all providers |
| 197 | if (!providerTitle) { |
| 198 | // then show loading if ANY loading |
| 199 | if (providersLoading.size > 0) { |
| 200 | return loadingFiller; |
| 201 | } |
| 202 | } else { |
| 203 | // Otherwise just check if the provider is loading |
| 204 | if (providersLoading.has(providerTitle)) { |
| 205 | return loadingFiller; |
| 206 | } |
| 207 | } |
| 208 | } |
| 209 | |
| 210 | return fallbackItems; |
| 211 | } |
| 212 | const limitedResults = searchResults.slice(0, limit).map((result) => { |
| 213 | return { |
| 214 | id: result.id, |
| 215 | title: result.title, |
| 216 | description: result.description, |
| 217 | providerTitle: result.providerTitle, |
| 218 | }; |
| 219 | }); |
| 220 | return limitedResults; |
| 221 | } catch (error) { |
| 222 | console.error("Error in getSubmenuContextItems:", error); |
| 223 | return []; |
| 224 | } |
| 225 | }, |
| 226 | [fallbackResults, minisearches], |
| 227 | ); |
| 228 | |
| 229 | const loadSubmenuItems = useCallback( |
| 230 | async (providers: "dependsOnIndexing" | "all" | ContextProviderName[]) => { |
| 231 | await Promise.allSettled( |
| 232 | submenuContextProviders.map( |
| 233 | async (description: ContextProviderDescription) => { |
| 234 | const controller = new AbortController(); |
| 235 | try { |
| 236 | const refreshProvider = |
| 237 | providers === "all" |
| 238 | ? true |
| 239 | : providers === "dependsOnIndexing" |
| 240 | ? description.dependsOnIndexing |
| 241 | : providers.includes(description.title); |
| 242 | |
| 243 | if (!refreshProvider) { |
| 244 | if (providers === "dependsOnIndexing") { |
| 245 | console.debug( |
| 246 | `Skipping ${description.title} provider due to disabled indexing`, |
| 247 | ); |
| 248 | } |
| 249 | return; |
| 250 | } |
| 251 | |
| 252 | // Submenu loading requests cancel existing requests |
| 253 | abortControllers.get(description.title)?.abort(); |
| 254 | abortControllers.set(description.title, controller); |
| 255 | providersLoading.add(description.title); |
| 256 | |
| 257 | const result = await ideMessenger.request( |
| 258 | "context/loadSubmenuItems", |
| 259 | { |
| 260 | title: description.title, |
| 261 | }, |
| 262 | ); |
| 263 | |
| 264 | // IMPORTANT - the controller only prevents invalid loading state |
| 265 | // But does not cancel using data from the request |
| 266 | // Could uncomment this to truly cancel the request |
| 267 | // if (controller.signal.aborted) { |
| 268 | // return console.debug( |
| 269 | // `${description.title} provider loading aborted`, |
| 270 | // ); |
| 271 | // } |
| 272 | |
| 273 | if (result.status === "error") { |
| 274 | throw new Error(result.error); |
| 275 | } |
| 276 | const submenuItems = result.content; |
| 277 | const providerTitle = description.title; |
| 278 | const renderInlineAs = description.renderInlineAs; |
| 279 | |
| 280 | const itemsWithProvider = submenuItems.map((item) => ({ |
| 281 | ...item, |
| 282 | providerTitle, |
| 283 | renderInlineAs, |
| 284 | })); |
| 285 | |
| 286 | const minisearch = new MiniSearch<ContextSubmenuItemWithProvider>( |
| 287 | { |
| 288 | fields: ["title", "description"], |
| 289 | storeFields: ["id", "title", "description", "providerTitle"], |
| 290 | tokenize: (text) => |
| 291 | deduplicateArray( |
| 292 | MiniSearch.getDefault("tokenize")(text).concat( |
| 293 | splitCamelCaseAndNonAlphaNumeric(text), |
| 294 | ), |
| 295 | (a, b) => a === b, |
| 296 | ), |
| 297 | }, |
| 298 | ); |
| 299 | |
| 300 | const deduplicatedItems = deduplicateArray( |
| 301 | submenuItems.map((item) => ({ ...item, providerTitle })), |
| 302 | (a, b) => a.id === b.id, |
| 303 | ); |
| 304 | minisearch.addAll(deduplicatedItems); |
| 305 | |
| 306 | setMinisearches((prev) => ({ |
| 307 | ...prev, |
| 308 | [providerTitle]: minisearch, |
| 309 | })); |
| 310 | |
| 311 | if (providerTitle === "file") { |
| 312 | setFallbackResults((prev) => ({ |
| 313 | ...prev, |
| 314 | file: deduplicateArray( |
| 315 | [...lastOpenFilesRef.current, ...itemsWithProvider], |
| 316 | (a, b) => a.id === b.id, |
| 317 | ), |
| 318 | })); |
| 319 | } else { |
| 320 | setFallbackResults((prev) => ({ |
| 321 | ...prev, |
| 322 | [providerTitle]: itemsWithProvider, |
| 323 | })); |
| 324 | } |
| 325 | } catch (error) { |
| 326 | console.error( |
| 327 | `Error loading items for ${description.title}:`, |
| 328 | error, |
| 329 | ); |
| 330 | console.error( |
| 331 | "Error details:", |
| 332 | JSON.stringify(error, Object.getOwnPropertyNames(error)), |
| 333 | ); |
| 334 | } finally { |
| 335 | if (!controller.signal.aborted) { |
| 336 | providersLoading.delete(description.title); |
| 337 | } |
| 338 | } |
| 339 | }, |
| 340 | ), |
| 341 | ); |
| 342 | }, |
| 343 | [ |
| 344 | submenuContextProviders, |
| 345 | disableIndexing, |
| 346 | providersLoading, |
| 347 | abortControllers, |
| 348 | ], |
| 349 | ); |
| 350 | |
| 351 | useWebviewListener( |
| 352 | "refreshSubmenuItems", |
| 353 | async (data) => { |
| 354 | loadSubmenuItems(data.providers); |
| 355 | }, |
| 356 | [loadSubmenuItems], |
| 357 | ); |
| 358 | |
| 359 | // Reload all submenu items on the initial config load |
| 360 | useEffect(() => { |
| 361 | if (!submenuContextProviders.length) { |
| 362 | return; |
| 363 | } |
| 364 | // Refresh submenu items when new titles detected |
| 365 | const newTitles = submenuContextProviders |
| 366 | .filter( |
| 367 | (provider) => |
| 368 | !lastProviders.current.find((p) => p.title === provider.title), |
| 369 | ) |
| 370 | .map((provider) => provider.title); |
| 371 | if (newTitles.length > 0) { |
| 372 | loadSubmenuItems(newTitles); |
| 373 | } |
| 374 | lastProviders.current = submenuContextProviders; |
| 375 | }, [loadSubmenuItems, submenuContextProviders]); |
| 376 | |
| 377 | return ( |
| 378 | <SubmenuContextProvidersContext.Provider |
| 379 | value={{ |
| 380 | getSubmenuContextItems, |
| 381 | }} |
| 382 | > |
| 383 | {children} |
| 384 | </SubmenuContextProvidersContext.Provider> |
| 385 | ); |
| 386 | }; |
| 387 | |
| 388 | export const useSubmenuContextProviders = () => |
| 389 | useContext(SubmenuContextProvidersContext); |