search-snapshot.ts 2.3 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192
  1. import { Text } from '@codemirror/state'
  2. import { RegExpCursor, SearchCursor, SearchQuery } from '@codemirror/search'
  3. import { ProjectSnapshot } from '@/infrastructure/project-snapshot'
  4. import { categorizer, regexpWordTest, stringWordTest } from './search'
  5. import { sendSearchEvent } from '@/features/event-tracking/search-events'
  6. export type Hit = {
  7. lineIndex: number
  8. matchIndex: number
  9. length: number
  10. }
  11. export type MatchedFile = {
  12. path: string
  13. lines: string[]
  14. hits: Hit[]
  15. }
  16. const toLowerCase = (string: string) => string.toLowerCase()
  17. export const searchSnapshot = async (
  18. projectSnapshot: ProjectSnapshot,
  19. searchQuery: SearchQuery
  20. ) => {
  21. if (!searchQuery.search.trim().length) {
  22. return
  23. }
  24. const matchedFiles = new Map<string, MatchedFile>()
  25. const createCursor = (text: Text) => {
  26. if (searchQuery.regexp) {
  27. return new RegExpCursor(text, searchQuery.search, {
  28. ignoreCase: !searchQuery.caseSensitive,
  29. test: searchQuery.wholeWord ? regexpWordTest(categorizer) : undefined,
  30. })
  31. }
  32. return new SearchCursor(
  33. text,
  34. searchQuery.search,
  35. undefined,
  36. undefined,
  37. searchQuery.caseSensitive ? undefined : toLowerCase,
  38. searchQuery.wholeWord ? stringWordTest(text, categorizer) : undefined
  39. )
  40. }
  41. const docPaths = projectSnapshot.getDocPaths()
  42. for (const path of docPaths) {
  43. const content = projectSnapshot.getDocContents(path)
  44. if (content) {
  45. const lines = content.split('\n')
  46. const text = Text.of(lines)
  47. const cursor = createCursor(text)
  48. while (!cursor.next().done) {
  49. const { from, to } = cursor.value
  50. const matchedFile: MatchedFile = matchedFiles.get(path) ?? {
  51. path,
  52. lines,
  53. hits: [],
  54. }
  55. const line = text.lineAt(from)
  56. matchedFile.hits.push({
  57. lineIndex: line.number - 1,
  58. matchIndex: from - line.from,
  59. length: to - from,
  60. })
  61. matchedFiles.set(path, matchedFile)
  62. }
  63. }
  64. }
  65. const results = [...matchedFiles.values()].sort((a, b) =>
  66. a.path.localeCompare(b.path)
  67. )
  68. sendSearchEvent('search-execute', {
  69. searchType: 'full-project',
  70. totalDocs: docPaths.length,
  71. totalResults: results.flatMap(file => file.hits).length,
  72. })
  73. return results
  74. }