full-project-search-ui.tsx 7.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246
  1. import React, {
  2. FC,
  3. FormEventHandler,
  4. memo,
  5. useCallback,
  6. useEffect,
  7. useMemo,
  8. useRef,
  9. useState,
  10. } from 'react'
  11. import { useTranslation } from 'react-i18next'
  12. import { useLayoutContext } from '@/shared/context/layout-context'
  13. import { useProjectContext } from '@/shared/context/project-context'
  14. import {
  15. MatchedFile as MatchedFileType,
  16. searchSnapshot,
  17. } from '../util/search-snapshot'
  18. import { SearchQuery } from '@codemirror/search'
  19. import { debugConsole } from '@/utils/debugging'
  20. import useEventListener from '@/shared/hooks/use-event-listener'
  21. import { Col, Form, Row } from 'react-bootstrap'
  22. import OLFormControl from '@/shared/components/ol/ol-form-control'
  23. import Button from '@/shared/components/button/button'
  24. import Notification from '@/shared/components/notification'
  25. import '../../stylesheets/full-project-search.scss'
  26. import { userStyles } from '@/shared/utils/styles'
  27. import { useUserSettingsContext } from '@/shared/context/user-settings-context'
  28. import { FullProjectMatchCounts } from './full-project-match-counts'
  29. import { FullProjectSearchModifiers } from './full-project-search-modifiers'
  30. import { isMac } from '@/shared/utils/os'
  31. import { useEditorManagerContext } from '@/features/ide-react/context/editor-manager-context'
  32. import { createRegExp } from '@/features/source-editor/utils/regexp'
  33. import { useEditorOpenDocContext } from '@/features/ide-react/context/editor-open-doc-context'
  34. import { useFileTreePathContext } from '@/features/file-tree/contexts/file-tree-path'
  35. import { FullProjectSearchResults } from './full-project-search-results'
  36. import { signalWithTimeout } from '@/utils/abort-signal'
  37. import RailPanelHeader from '@/features/ide-react/components/rail/rail-panel-header'
  38. import { useActiveOverallTheme } from '@/shared/hooks/use-active-overall-theme'
  39. const FullProjectSearchUI: FC = () => {
  40. const { t } = useTranslation()
  41. const { setProjectSearchIsOpen } = useLayoutContext()
  42. const { projectSnapshot } = useProjectContext()
  43. const { openDocs } = useEditorManagerContext()
  44. const { pathInFolder } = useFileTreePathContext()
  45. const { currentDocument: currentDoc } = useEditorOpenDocContext()
  46. const [loading, setLoading] = useState(false)
  47. const [error, setError] = useState<string>()
  48. const [matchedFiles, setMatchedFiles] = useState<MatchedFileType[]>()
  49. const { userSettings } = useUserSettingsContext()
  50. const { fontFamily, fontSize } = useMemo(
  51. () => userStyles(userSettings),
  52. [userSettings]
  53. )
  54. const activeOverallTheme = useActiveOverallTheme()
  55. const abortControllerRef = useRef<AbortController | null>(null)
  56. // start fetching the snapshot when the project search UI opens
  57. useEffect(() => {
  58. projectSnapshot.refresh().catch(error => {
  59. debugConsole.error(error)
  60. })
  61. }, [projectSnapshot])
  62. const currentDocPath = useMemo(() => {
  63. return currentDoc && pathInFolder(currentDoc.doc_id)
  64. }, [currentDoc, pathInFolder])
  65. const handleSubmit: React.FormEventHandler<HTMLFormElement> = useCallback(
  66. async event => {
  67. event.preventDefault()
  68. setMatchedFiles(undefined)
  69. abortControllerRef.current?.abort()
  70. abortControllerRef.current = new AbortController()
  71. const data = new FormData(event.target as HTMLFormElement)
  72. const searchQuery = new SearchQuery({
  73. search: data.get('search') as string,
  74. // replace: data.get('replace') as string,
  75. caseSensitive: data.get('caseSensitive') === 'on',
  76. regexp: data.get('regexp') === 'on',
  77. wholeWord: data.get('wholeWord') === 'on',
  78. literal: data.get('regexp') !== 'on',
  79. })
  80. if (searchQuery.regexp) {
  81. try {
  82. createRegExp(searchQuery)
  83. } catch (error) {
  84. setError(t('invalid_regular_expression'))
  85. return
  86. }
  87. }
  88. setLoading(true)
  89. setError(undefined)
  90. try {
  91. await openDocs.awaitBufferedOps(
  92. signalWithTimeout(abortControllerRef.current.signal, 5000)
  93. )
  94. await projectSnapshot.refresh()
  95. if (!abortControllerRef.current.signal.aborted) {
  96. const results = await searchSnapshot(projectSnapshot, searchQuery)
  97. setMatchedFiles(results)
  98. }
  99. } catch (error) {
  100. debugConsole.error(error)
  101. setError(t('generic_something_went_wrong'))
  102. } finally {
  103. setLoading(false)
  104. }
  105. },
  106. [openDocs, projectSnapshot, t]
  107. )
  108. const searchInputRef = useRef<HTMLInputElement>(null)
  109. useEffect(() => {
  110. if (!document.activeElement?.closest('.ide-rail')) {
  111. searchInputRef.current?.focus()
  112. }
  113. }, [])
  114. const handleKeyDown: React.KeyboardEventHandler<HTMLElement> = useCallback(
  115. event => {
  116. if (event.key === 'Escape') {
  117. setProjectSearchIsOpen(false)
  118. }
  119. },
  120. [setProjectSearchIsOpen]
  121. )
  122. useEventListener(
  123. 'keydown',
  124. useCallback((event: KeyboardEvent) => {
  125. if (
  126. (isMac ? event.metaKey : event.ctrlKey) &&
  127. event.shiftKey &&
  128. event.code === 'KeyF'
  129. ) {
  130. searchInputRef.current?.focus()
  131. }
  132. }, [])
  133. )
  134. const modifiersRef = useRef<{ setQuery(query: SearchQuery): void }>(null)
  135. useEventListener(
  136. 'editor:full-project-search',
  137. useCallback((event: CustomEvent<SearchQuery>) => {
  138. if (modifiersRef.current != null) {
  139. modifiersRef.current.setQuery(event.detail)
  140. }
  141. if (searchInputRef.current != null) {
  142. searchInputRef.current.value = event.detail.search
  143. searchInputRef.current.form?.dispatchEvent(
  144. new Event('submit', { cancelable: true, bubbles: true })
  145. )
  146. }
  147. }, [])
  148. )
  149. // clear the results when the form is cleared
  150. const handleInput: FormEventHandler<HTMLInputElement> = useCallback(event => {
  151. if (
  152. event instanceof InputEvent &&
  153. event.inputType === undefined &&
  154. (event.target as HTMLInputElement).value.length === 0
  155. ) {
  156. setMatchedFiles(undefined)
  157. }
  158. }, [])
  159. const variableStyle = {
  160. '--font-family': fontFamily,
  161. '--font-size': fontSize,
  162. } as React.CSSProperties
  163. return (
  164. <div
  165. className="full-project-search"
  166. style={variableStyle}
  167. data-bs-theme={activeOverallTheme === 'light' ? 'light' : 'dark'}
  168. >
  169. <RailPanelHeader title={t('search')} />
  170. <div // eslint-disable-line jsx-a11y/no-static-element-interactions
  171. className="full-project-search-form"
  172. onKeyDown={handleKeyDown}
  173. >
  174. <Form
  175. onSubmit={handleSubmit}
  176. role="search"
  177. id="full-project-search"
  178. aria-label={t('search_all_project_files')}
  179. >
  180. <Row className="g-1">
  181. <Col>
  182. <OLFormControl
  183. type="search"
  184. name="search"
  185. size="sm"
  186. aria-label={t('search')}
  187. spellCheck={false}
  188. autoComplete="off"
  189. ref={searchInputRef}
  190. onInput={handleInput}
  191. placeholder={`${t('search_all_project_files')}…`}
  192. />
  193. </Col>
  194. <Col className="col-auto">
  195. <Button type="submit" className="btn btn-primary" size="sm">
  196. {t('search')}
  197. </Button>
  198. </Col>
  199. </Row>
  200. <FullProjectSearchModifiers ref={modifiersRef} />
  201. </Form>
  202. </div>
  203. {error && <Notification type="error" content={error} />}
  204. <div className="match-counts">
  205. <FullProjectMatchCounts loading={loading} matchedFiles={matchedFiles} />
  206. </div>
  207. {matchedFiles && (
  208. <FullProjectSearchResults
  209. matchedFiles={matchedFiles}
  210. currentDocPath={currentDocPath}
  211. />
  212. )}
  213. </div>
  214. )
  215. }
  216. export default memo(FullProjectSearchUI)