| 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 | // Enhanced search result interface for intelligent sorting |
| 33 | interface EnhancedSearchResult |
| 34 | extends SearchResult, |
| 35 | Omit<ContextSubmenuItemWithProvider, "id"> { |
| 36 | sortPriority: number; |
| 37 | matchQuality: number; |
| 38 | } |
| 39 | |
| 40 | interface SubtextContextProvidersContextType { |
| 41 | getSubmenuContextItems: ( |
| 42 | providerTitle: string | undefined, |
| 43 | query: string, |
| 44 | ) => ContextSubmenuItemWithProvider[]; |
| 45 | } |
| 46 | |
| 47 | const initialContextProviders: SubtextContextProvidersContextType = { |
| 48 | getSubmenuContextItems: () => [], |
| 49 | }; |
| 50 | |
| 51 | const SubmenuContextProvidersContext = |
| 52 | createContext<SubtextContextProvidersContextType>(initialContextProviders); |
| 53 | |
| 54 | // Helper functions for intelligent file sorting |
| 55 | function hasExactWordMatch(text: string, query: string): boolean { |
| 56 | const words = text.split(/[^a-zA-Z0-9]+/); |
| 57 | return words.some((word) => word === query); |
| 58 | } |
| 59 | |
| 60 | function isCommonDevFile(fileName: string): boolean { |
| 61 | const commonExtensions = [ |
| 62 | ".ts", |
| 63 | ".tsx", |
| 64 | ".js", |
| 65 | ".jsx", |
| 66 | ".py", |
| 67 | ".java", |
| 68 | ".cpp", |
| 69 | ".c", |
| 70 | ".h", |
| 71 | ".vue", |
| 72 | ".svelte", |
| 73 | ]; |
| 74 | const commonNames = [ |
| 75 | "index", |
| 76 | "main", |
| 77 | "app", |
| 78 | "component", |
| 79 | "service", |
| 80 | "util", |
| 81 | "helper", |
| 82 | "config", |
| 83 | "types", |
| 84 | ]; |
| 85 | |
| 86 | const extension = fileName.substring(fileName.lastIndexOf(".")); |
| 87 | const baseName = fileName |
| 88 | .substring(0, fileName.lastIndexOf(".")) |
| 89 | .toLowerCase(); |
| 90 | |
| 91 | return commonExtensions.includes(extension) || commonNames.includes(baseName); |
| 92 | } |
| 93 | |
| 94 | function isInCommonDirectory(filePath: string): boolean { |
| 95 | const commonDirs = [ |
| 96 | "src/", |
| 97 | "lib/", |
| 98 | "components/", |
| 99 | "utils/", |
| 100 | "helpers/", |
| 101 | "services/", |
| 102 | "pages/", |
| 103 | "views/", |
| 104 | "hooks/", |
| 105 | "store/", |
| 106 | "types/", |
| 107 | "interfaces/", |
| 108 | "models/", |
| 109 | "api/", |
| 110 | ]; |
| 111 | return commonDirs.some((dir) => filePath.includes(dir)); |
| 112 | } |
| 113 | |
| 114 | function matchesCamelCaseOrAbbreviation( |
| 115 | fileName: string, |
| 116 | query: string, |
| 117 | ): boolean { |
| 118 | // Extract capital letters for camel case matching |
| 119 | const capitals = fileName.match(/[A-Z]/g)?.join("").toLowerCase() || ""; |
| 120 | |
| 121 | // Check if query matches the capital letters pattern |
| 122 | if (capitals.length > 0 && capitals.includes(query)) { |
| 123 | return true; |
| 124 | } |
| 125 | |
| 126 | // Check for abbreviation matches (first letters of words) |
| 127 | const words = fileName.split(/[^a-zA-Z0-9]+/).filter((w) => w.length > 0); |
| 128 | if (words.length > 1) { |
| 129 | const abbreviation = words |
| 130 | .map((word) => word[0]) |
| 131 | .join("") |
| 132 | .toLowerCase(); |
| 133 | return abbreviation.includes(query); |
| 134 | } |
| 135 | |
| 136 | return false; |
| 137 | } |
| 138 | |
| 139 | export const SubmenuContextProvidersProvider = ({ |
| 140 | children, |
| 141 | }: { |
| 142 | children: React.ReactNode; |
| 143 | }) => { |
| 144 | const ideMessenger = useContext(IdeMessengerContext); |
| 145 | const submenuContextProviders = useAppSelector(selectSubmenuContextProviders); |
| 146 | const lastProviders = useRef(submenuContextProviders); |
| 147 | const disableIndexing = useAppSelector( |
| 148 | (store) => store.config.config.disableIndexing, |
| 149 | ); |
| 150 | |
| 151 | const [minisearches, setMinisearches] = useState<{ |
| 152 | [id: string]: MiniSearch<ContextSubmenuItemWithProvider>; |
| 153 | }>({}); |
| 154 | const [fallbackResults, setFallbackResults] = useState<{ |
| 155 | [id: string]: ContextSubmenuItemWithProvider[]; |
| 156 | }>({}); |
| 157 | |
| 158 | // Update open files for file provider on an interval |
| 159 | const lastOpenFilesRef = useRef<ContextSubmenuItemWithProvider[]>([]); |
| 160 | useEffect(() => { |
| 161 | function hasOpenFilesChanged( |
| 162 | newFiles: ContextSubmenuItemWithProvider[], |
| 163 | oldFiles: ContextSubmenuItemWithProvider[], |
| 164 | ) { |
| 165 | const newIds = new Set(newFiles.map((f) => f.id)); |
| 166 | const oldIds = new Set(oldFiles.map((f) => f.id)); |
| 167 | |
| 168 | if (newIds.size !== oldIds.size) return true; |
| 169 | |
| 170 | for (const id of newIds) { |
| 171 | if (!oldIds.has(id)) return true; |
| 172 | } |
| 173 | |
| 174 | for (const id of oldIds) { |
| 175 | if (!newIds.has(id)) return true; |
| 176 | } |
| 177 | return false; |
| 178 | } |
| 179 | |
| 180 | let isMounted = true; |
| 181 | const refreshOpenFiles = async () => { |
| 182 | if (!isMounted) return; |
| 183 | |
| 184 | const openFiles = await ideMessenger.ide.getOpenFiles(); |
| 185 | const workspaceDirs = await ideMessenger.ide.getWorkspaceDirs(); |
| 186 | const withUniquePaths = getShortestUniqueRelativeUriPaths( |
| 187 | openFiles, |
| 188 | workspaceDirs, |
| 189 | ); |
| 190 | const openFileItems = withUniquePaths.map((file) => ({ |
| 191 | id: file.uri, |
| 192 | title: getUriPathBasename(file.uri), |
| 193 | description: file.uniquePath, |
| 194 | providerTitle: "file", |
| 195 | })); |
| 196 | |
| 197 | if (hasOpenFilesChanged(openFileItems, lastOpenFilesRef.current)) { |
| 198 | setFallbackResults((prev) => ({ |
| 199 | ...prev, |
| 200 | file: deduplicateArray( |
| 201 | [...openFileItems, ...(prev.file ?? [])], |
| 202 | (a, b) => a.id === b.id, |
| 203 | ), |
| 204 | })); |
| 205 | } |
| 206 | lastOpenFilesRef.current = openFileItems; |
| 207 | }; |
| 208 | |
| 209 | const interval = setInterval(refreshOpenFiles, 2000); |
| 210 | |
| 211 | void refreshOpenFiles(); // Initial call |
| 212 | |
| 213 | return () => { |
| 214 | isMounted = false; |
| 215 | clearInterval(interval); |
| 216 | }; |
| 217 | }, [ideMessenger]); |
| 218 | |
| 219 | const providersLoading = useRef(new Set<ContextProviderName>()).current; |
| 220 | const abortControllers = useRef( |
| 221 | new Map<ContextProviderName, AbortController>(), |
| 222 | ).current; |
| 223 | |
| 224 | const calculateFileSortPriority = useCallback( |
| 225 | ( |
| 226 | result: SearchResult & ContextSubmenuItemWithProvider, |
| 227 | query: string, |
| 228 | openFiles: ContextSubmenuItemWithProvider[], |
| 229 | ): number => { |
| 230 | const fileName = result.title.toLowerCase(); |
| 231 | const filePath = result.description.toLowerCase(); |
| 232 | const queryLower = query.toLowerCase(); |
| 233 | |
| 234 | // Priority 1: Exact filename match |
| 235 | if (fileName === queryLower) { |
| 236 | return 1; |
| 237 | } |
| 238 | |
| 239 | // Priority 2: Recently opened files |
| 240 | if (openFiles.some((f) => f.id === result.id)) { |
| 241 | return 2; |
| 242 | } |
| 243 | |
| 244 | // Priority 3: Filename starts with query |
| 245 | if (fileName.startsWith(queryLower)) { |
| 246 | return 3; |
| 247 | } |
| 248 | |
| 249 | // Priority 4: Exact word match in filename |
| 250 | if (hasExactWordMatch(fileName, queryLower)) { |
| 251 | return 4; |
| 252 | } |
| 253 | |
| 254 | // Priority 5: Common development files |
| 255 | if (isCommonDevFile(fileName)) { |
| 256 | return 5; |
| 257 | } |
| 258 | |
| 259 | // Priority 6: Files in common directories |
| 260 | if (isInCommonDirectory(filePath)) { |
| 261 | return 6; |
| 262 | } |
| 263 | |
| 264 | // Priority 7: CamelCase/abbreviation matches |
| 265 | if (matchesCamelCaseOrAbbreviation(fileName, queryLower)) { |
| 266 | return 7; |
| 267 | } |
| 268 | |
| 269 | // Priority 8: Path starts with query |
| 270 | if (filePath.startsWith(queryLower)) { |
| 271 | return 8; |
| 272 | } |
| 273 | |
| 274 | // Priority 9: Default |
| 275 | return 9; |
| 276 | }, |
| 277 | [], |
| 278 | ); |
| 279 | |
| 280 | const calculateMatchQuality = useCallback( |
| 281 | ( |
| 282 | result: SearchResult & ContextSubmenuItemWithProvider, |
| 283 | query: string, |
| 284 | ): number => { |
| 285 | const fileName = result.title.toLowerCase(); |
| 286 | const queryLower = query.toLowerCase(); |
| 287 | let quality = 0; |
| 288 | |
| 289 | // Exact match bonus |
| 290 | if (fileName === queryLower) quality += 100; |
| 291 | |
| 292 | // Prefix match bonus |
| 293 | if (fileName.startsWith(queryLower)) quality += 50; |
| 294 | |
| 295 | // Contains match bonus |
| 296 | if (fileName.includes(queryLower)) quality += 25; |
| 297 | |
| 298 | // Shorter filename bonus (prefer concise names) |
| 299 | quality += Math.max(0, 50 - fileName.length); |
| 300 | |
| 301 | // Extension preference (common dev files) |
| 302 | if ( |
| 303 | fileName.endsWith(".ts") || |
| 304 | fileName.endsWith(".tsx") || |
| 305 | fileName.endsWith(".js") || |
| 306 | fileName.endsWith(".jsx") |
| 307 | ) { |
| 308 | quality += 10; |
| 309 | } |
| 310 | |
| 311 | return quality; |
| 312 | }, |
| 313 | [], |
| 314 | ); |
| 315 | |
| 316 | const getSubmenuContextItems = useCallback( |
| 317 | ( |
| 318 | providerTitle: string | undefined, |
| 319 | query: string, |
| 320 | limit: number = MAX_LENGTH, |
| 321 | ): ContextSubmenuItemWithProvider[] => { |
| 322 | try { |
| 323 | // 1. Search using minisearch |
| 324 | let searchResults: (SearchResult & ContextSubmenuItemWithProvider)[] = |
| 325 | []; |
| 326 | |
| 327 | if (providerTitle === undefined) { |
| 328 | // Include results from all providers |
| 329 | searchResults = Object.keys(minisearches).flatMap((providerTitle) => |
| 330 | minisearches[providerTitle] |
| 331 | .search(query, MINISEARCH_OPTIONS) |
| 332 | .map((result) => { |
| 333 | return { |
| 334 | ...result, |
| 335 | providerTitle, |
| 336 | title: result.title, |
| 337 | description: result.description, |
| 338 | }; |
| 339 | }), |
| 340 | ); |
| 341 | } else { |
| 342 | // Only include results from the specified provider |
| 343 | if (minisearches[providerTitle]) { |
| 344 | searchResults = minisearches[providerTitle] |
| 345 | .search(query, MINISEARCH_OPTIONS) |
| 346 | .map((result) => { |
| 347 | return { |
| 348 | ...result, |
| 349 | providerTitle, |
| 350 | title: result.title, |
| 351 | description: result.description, |
| 352 | }; |
| 353 | }); |
| 354 | } |
| 355 | } |
| 356 | |
| 357 | // 2. Enhanced sorting for file provider |
| 358 | if ( |
| 359 | providerTitle === "file" || |
| 360 | (!providerTitle && |
| 361 | searchResults.some((r) => r.providerTitle === "file")) |
| 362 | ) { |
| 363 | const enhancedResults: EnhancedSearchResult[] = searchResults.map( |
| 364 | (result): EnhancedSearchResult => ({ |
| 365 | ...result, |
| 366 | id: result.id, |
| 367 | title: result.title, |
| 368 | description: result.description, |
| 369 | providerTitle: result.providerTitle, |
| 370 | sortPriority: calculateFileSortPriority( |
| 371 | result, |
| 372 | query, |
| 373 | lastOpenFilesRef.current, |
| 374 | ), |
| 375 | matchQuality: calculateMatchQuality(result, query), |
| 376 | }), |
| 377 | ); |
| 378 | |
| 379 | // Sort by multiple criteria |
| 380 | enhancedResults.sort((a, b) => { |
| 381 | // Primary: Sort priority (lower = better) |
| 382 | if (a.sortPriority !== b.sortPriority) { |
| 383 | return a.sortPriority - b.sortPriority; |
| 384 | } |
| 385 | |
| 386 | // Secondary: Match quality (higher = better) |
| 387 | if (a.matchQuality !== b.matchQuality) { |
| 388 | return b.matchQuality - a.matchQuality; |
| 389 | } |
| 390 | |
| 391 | // Tertiary: MiniSearch relevance score (higher = better) |
| 392 | if (a.score !== b.score) { |
| 393 | return b.score - a.score; |
| 394 | } |
| 395 | |
| 396 | // Quaternary: Path length (shorter = better) |
| 397 | return a.description.length - b.description.length; |
| 398 | }); |
| 399 | |
| 400 | searchResults = enhancedResults; |
| 401 | } else { |
| 402 | // Default sorting for non-file providers |
| 403 | searchResults.sort((a, b) => b.score - a.score); |
| 404 | } |
| 405 | |
| 406 | // 3. Add fallback results if no search results |
| 407 | if (searchResults.length === 0) { |
| 408 | const fallbackItems = ( |
| 409 | providerTitle ? (fallbackResults[providerTitle] ?? []) : [] |
| 410 | ) |
| 411 | .slice(0, limit) |
| 412 | .map((result) => { |
| 413 | return { |
| 414 | ...result, |
| 415 | providerTitle: providerTitle || "unknown", |
| 416 | }; |
| 417 | }); |
| 418 | |
| 419 | if (fallbackItems.length === 0) { |
| 420 | const loadingFiller = [ |
| 421 | { |
| 422 | id: "loading", |
| 423 | title: "Loading...", |
| 424 | description: "Please wait while items are being loaded", |
| 425 | providerTitle: providerTitle || "unknown", |
| 426 | }, |
| 427 | ]; |
| 428 | |
| 429 | // If getting for all providers |
| 430 | if (!providerTitle) { |
| 431 | // then show loading if ANY loading |
| 432 | if (providersLoading.size > 0) { |
| 433 | return loadingFiller; |
| 434 | } |
| 435 | } else { |
| 436 | // Otherwise just check if the provider is loading |
| 437 | if (providersLoading.has(providerTitle)) { |
| 438 | return loadingFiller; |
| 439 | } |
| 440 | } |
| 441 | } |
| 442 | |
| 443 | return fallbackItems; |
| 444 | } |
| 445 | const limitedResults = searchResults.slice(0, limit).map((result) => { |
| 446 | return { |
| 447 | id: result.id, |
| 448 | title: result.title, |
| 449 | description: result.description, |
| 450 | providerTitle: result.providerTitle, |
| 451 | }; |
| 452 | }); |
| 453 | return limitedResults; |
| 454 | } catch (error) { |
| 455 | console.error("Error in getSubmenuContextItems:", error); |
| 456 | return []; |
| 457 | } |
| 458 | }, |
| 459 | [ |
| 460 | fallbackResults, |
| 461 | minisearches, |
| 462 | calculateFileSortPriority, |
| 463 | calculateMatchQuality, |
| 464 | ], |
| 465 | ); |
| 466 | |
| 467 | const loadSubmenuItems = useCallback( |
| 468 | async (providers: "dependsOnIndexing" | "all" | ContextProviderName[]) => { |
| 469 | await Promise.allSettled( |
| 470 | submenuContextProviders.map( |
| 471 | async (description: ContextProviderDescription) => { |
| 472 | const controller = new AbortController(); |
| 473 | try { |
| 474 | const refreshProvider = |
| 475 | providers === "all" |
| 476 | ? true |
| 477 | : providers === "dependsOnIndexing" |
| 478 | ? description.dependsOnIndexing && |
| 479 | description.dependsOnIndexing?.length > 0 |
| 480 | : providers.includes(description.title); |
| 481 | |
| 482 | if (!refreshProvider) { |
| 483 | if (providers === "dependsOnIndexing") { |
| 484 | console.debug( |
| 485 | `Skipping ${description.title} provider due to disabled indexing`, |
| 486 | ); |
| 487 | } |
| 488 | return; |
| 489 | } |
| 490 | |
| 491 | // Submenu loading requests cancel existing requests |
| 492 | abortControllers.get(description.title)?.abort(); |
| 493 | abortControllers.set(description.title, controller); |
| 494 | providersLoading.add(description.title); |
| 495 | |
| 496 | const result = await ideMessenger.request( |
| 497 | "context/loadSubmenuItems", |
| 498 | { |
| 499 | title: description.title, |
| 500 | }, |
| 501 | ); |
| 502 | |
| 503 | // IMPORTANT - the controller only prevents invalid loading state |
| 504 | // But does not cancel using data from the request |
| 505 | // Could uncomment this to truly cancel the request |
| 506 | // if (controller.signal.aborted) { |
| 507 | // return console.debug( |
| 508 | // `${description.title} provider loading aborted`, |
| 509 | // ); |
| 510 | // } |
| 511 | |
| 512 | if (result.status === "error") { |
| 513 | throw new Error(result.error); |
| 514 | } |
| 515 | const submenuItems = result.content; |
| 516 | const providerTitle = description.title; |
| 517 | const renderInlineAs = description.renderInlineAs; |
| 518 | |
| 519 | const itemsWithProvider = submenuItems.map((item) => ({ |
| 520 | ...item, |
| 521 | providerTitle, |
| 522 | renderInlineAs, |
| 523 | })); |
| 524 | |
| 525 | const minisearch = new MiniSearch<ContextSubmenuItemWithProvider>( |
| 526 | { |
| 527 | fields: ["title", "description"], |
| 528 | storeFields: ["id", "title", "description", "providerTitle"], |
| 529 | tokenize: (text) => |
| 530 | deduplicateArray( |
| 531 | MiniSearch.getDefault("tokenize")(text).concat( |
| 532 | splitCamelCaseAndNonAlphaNumeric(text), |
| 533 | ), |
| 534 | (a, b) => a === b, |
| 535 | ), |
| 536 | }, |
| 537 | ); |
| 538 | |
| 539 | const deduplicatedItems = deduplicateArray( |
| 540 | submenuItems.map((item) => ({ ...item, providerTitle })), |
| 541 | (a, b) => a.id === b.id, |
| 542 | ); |
| 543 | minisearch.addAll(deduplicatedItems); |
| 544 | |
| 545 | setMinisearches((prev) => ({ |
| 546 | ...prev, |
| 547 | [providerTitle]: minisearch, |
| 548 | })); |
| 549 | |
| 550 | if (providerTitle === "file") { |
| 551 | setFallbackResults((prev) => ({ |
| 552 | ...prev, |
| 553 | file: deduplicateArray( |
| 554 | [...lastOpenFilesRef.current, ...itemsWithProvider], |
| 555 | (a, b) => a.id === b.id, |
| 556 | ), |
| 557 | })); |
| 558 | } else { |
| 559 | setFallbackResults((prev) => ({ |
| 560 | ...prev, |
| 561 | [providerTitle]: itemsWithProvider, |
| 562 | })); |
| 563 | } |
| 564 | } catch (error) { |
| 565 | console.error( |
| 566 | `Error loading items for ${description.title}:`, |
| 567 | error, |
| 568 | ); |
| 569 | console.error( |
| 570 | "Error details:", |
| 571 | JSON.stringify(error, Object.getOwnPropertyNames(error)), |
| 572 | ); |
| 573 | } finally { |
| 574 | if (!controller.signal.aborted) { |
| 575 | providersLoading.delete(description.title); |
| 576 | } |
| 577 | } |
| 578 | }, |
| 579 | ), |
| 580 | ); |
| 581 | }, |
| 582 | [ |
| 583 | submenuContextProviders, |
| 584 | disableIndexing, |
| 585 | providersLoading, |
| 586 | abortControllers, |
| 587 | ], |
| 588 | ); |
| 589 | |
| 590 | useWebviewListener( |
| 591 | "refreshSubmenuItems", |
| 592 | async (data) => { |
| 593 | void loadSubmenuItems(data.providers); |
| 594 | }, |
| 595 | [loadSubmenuItems], |
| 596 | ); |
| 597 | |
| 598 | // Reload all submenu items on the initial config load |
| 599 | useEffect(() => { |
| 600 | if (!submenuContextProviders.length) { |
| 601 | return; |
| 602 | } |
| 603 | // Refresh submenu items when new titles detected |
| 604 | const newTitles = submenuContextProviders |
| 605 | .filter( |
| 606 | (provider) => |
| 607 | !lastProviders.current.find((p) => p.title === provider.title), |
| 608 | ) |
| 609 | .map((provider) => provider.title); |
| 610 | if (newTitles.length > 0) { |
| 611 | void loadSubmenuItems(newTitles); |
| 612 | } |
| 613 | lastProviders.current = submenuContextProviders; |
| 614 | }, [loadSubmenuItems, submenuContextProviders]); |
| 615 | |
| 616 | return ( |
| 617 | <SubmenuContextProvidersContext.Provider |
| 618 | value={{ |
| 619 | getSubmenuContextItems, |
| 620 | }} |
| 621 | > |
| 622 | {children} |
| 623 | </SubmenuContextProvidersContext.Provider> |
| 624 | ); |
| 625 | }; |
| 626 | |
| 627 | export const useSubmenuContextProviders = () => |
| 628 | useContext(SubmenuContextProvidersContext); |