search.ts 8.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285
  1. import {
  2. searchKeymap,
  3. search as searchExtension,
  4. setSearchQuery,
  5. getSearchQuery,
  6. openSearchPanel,
  7. SearchQuery,
  8. searchPanelOpen,
  9. } from '@codemirror/search'
  10. import { EditorView, keymap, ViewPlugin } from '@codemirror/view'
  11. import {
  12. Annotation,
  13. EditorState,
  14. SelectionRange,
  15. TransactionSpec,
  16. } from '@codemirror/state'
  17. import { highlightSelectionMatches } from './highlight-selection-matches'
  18. const restoreSearchQueryAnnotation = Annotation.define<boolean>()
  19. const ignoredSearchKeybindings = new Set([
  20. // This keybinding causes issues with entering @ on certain keyboard layouts
  21. // https://github.com/overleaf/internal/issues/12119
  22. 'Alt-g',
  23. ])
  24. const selectNextMatch = (query: SearchQuery, state: EditorState) => {
  25. if (!query.valid) {
  26. return false
  27. }
  28. let cursor = query.getCursor(state.doc, state.selection.main.from)
  29. let result = cursor.next()
  30. if (result.done) {
  31. cursor = query.getCursor(state.doc)
  32. result = cursor.next()
  33. }
  34. return result.done ? null : result.value
  35. }
  36. let searchQuery: SearchQuery | null
  37. export const search = () => {
  38. let open = false
  39. return [
  40. // keymap for search
  41. keymap.of(
  42. searchKeymap.filter(
  43. item => !item.key || !ignoredSearchKeybindings.has(item.key)
  44. )
  45. ),
  46. // highlight text which matches the current selection
  47. highlightSelectionMatches(),
  48. // a wrapper round `search`, which creates a custom panel element and passes it to React by dispatching an event
  49. searchExtension({
  50. literal: true,
  51. // centre the search match if it was outside the visible area
  52. scrollToMatch: (range: SelectionRange, view: EditorView) => {
  53. const coords = {
  54. from: view.coordsAtPos(range.from),
  55. to: view.coordsAtPos(range.to),
  56. }
  57. const scrollRect = view.scrollDOM.getBoundingClientRect()
  58. const strategy =
  59. (coords.from && coords.from.top < scrollRect.top) ||
  60. (coords.to && coords.to.bottom > scrollRect.bottom)
  61. ? 'center'
  62. : 'nearest'
  63. return EditorView.scrollIntoView(range, {
  64. y: strategy,
  65. })
  66. },
  67. createPanel: () => {
  68. const dom = document.createElement('div')
  69. dom.className = 'ol-cm-search'
  70. return {
  71. dom,
  72. mount() {
  73. open = true
  74. // focus the search input when the panel is already open
  75. const searchInput =
  76. dom.querySelector<HTMLInputElement>('[main-field]')
  77. if (searchInput) {
  78. searchInput.focus()
  79. searchInput.select()
  80. }
  81. },
  82. destroy() {
  83. window.setTimeout(() => {
  84. open = false // in a timeout, so the view plugin below can run its destroy method first
  85. }, 0)
  86. },
  87. }
  88. },
  89. }),
  90. // restore a stored search and re-open the search panel
  91. ViewPlugin.define(view => {
  92. if (searchQuery) {
  93. const _searchQuery = searchQuery
  94. window.setTimeout(() => {
  95. openSearchPanel(view)
  96. view.dispatch({
  97. effects: setSearchQuery.of(_searchQuery),
  98. annotations: restoreSearchQueryAnnotation.of(true),
  99. })
  100. }, 0)
  101. }
  102. return {
  103. destroy() {
  104. // persist the current search query if the panel is open
  105. searchQuery = open ? getSearchQuery(view.state) : null
  106. },
  107. }
  108. }),
  109. // select a match while searching
  110. EditorView.updateListener.of(update => {
  111. for (const tr of update.transactions) {
  112. // avoid changing the selection and viewport when switching between files
  113. if (tr.annotation(restoreSearchQueryAnnotation)) {
  114. continue
  115. }
  116. for (const effect of tr.effects) {
  117. if (effect.is(setSearchQuery)) {
  118. const query = effect.value
  119. if (!query) return
  120. // The rest of this messes up searching in Vim, which is handled by
  121. // the Vim extension, so bail out here in Vim mode. Happily, the
  122. // Vim extension sticks an extra property on the query value that
  123. // can be checked
  124. if ('forVim' in query) return
  125. const next = selectNextMatch(query, tr.state)
  126. if (next) {
  127. // select a match if possible
  128. const spec: TransactionSpec = {
  129. selection: { anchor: next.from, head: next.to },
  130. userEvent: 'select.search',
  131. }
  132. // scroll into view if not opening the panel
  133. if (searchPanelOpen(tr.startState)) {
  134. spec.effects = EditorView.scrollIntoView(next.from, {
  135. y: 'center',
  136. })
  137. }
  138. update.view.dispatch(spec)
  139. } else {
  140. // clear the selection if the query became invalid
  141. const prevQuery = getSearchQuery(tr.startState)
  142. if (prevQuery.valid) {
  143. const { from } = tr.startState.selection.main
  144. update.view.dispatch({
  145. selection: { anchor: from },
  146. })
  147. }
  148. }
  149. }
  150. }
  151. }
  152. }),
  153. // search form theme
  154. EditorView.theme({
  155. '.ol-cm-search-form': {
  156. padding: '10px',
  157. display: 'flex',
  158. gap: '10px',
  159. background: 'var(--ol-blue-gray-1)',
  160. '--ol-cm-search-form-focus-shadow':
  161. 'inset 0 1px 1px rgb(0 0 0 / 8%), 0 0 8px rgb(102 175 233 / 60%)',
  162. '--ol-cm-search-form-error-shadow':
  163. 'inset 0 1px 1px rgb(0 0 0 / 8%), 0 0 8px var(--input-shadow-danger-color)',
  164. },
  165. '.ol-cm-search-controls': {
  166. display: 'grid',
  167. gridTemplateColumns: 'auto auto',
  168. gridTemplateRows: 'auto auto',
  169. gap: '10px',
  170. },
  171. '.ol-cm-search-form-row': {
  172. display: 'flex',
  173. gap: '10px',
  174. justifyContent: 'space-between',
  175. },
  176. '.ol-cm-search-form-group': {
  177. display: 'flex',
  178. gap: '10px',
  179. alignItems: 'center',
  180. },
  181. '.ol-cm-search-input-group': {
  182. border: '1px solid var(--input-border)',
  183. borderRadius: '20px',
  184. background: 'white',
  185. width: '100%',
  186. maxWidth: '25em',
  187. '& input[type="text"]': {
  188. background: 'none',
  189. boxShadow: 'none',
  190. },
  191. '& input[type="text"]:focus': {
  192. outline: 'none',
  193. boxShadow: 'none',
  194. },
  195. '& .btn.btn': {
  196. background: 'var(--ol-blue-gray-0)',
  197. color: 'var(--ol-blue-gray-3)',
  198. borderRadius: '50%',
  199. height: '2em',
  200. display: 'inline-flex',
  201. alignItems: 'center',
  202. justifyContent: 'center',
  203. width: '2em',
  204. marginRight: '3px',
  205. '&.checked': {
  206. color: '#fff',
  207. backgroundColor: 'var(--ol-blue)',
  208. },
  209. '&:active': {
  210. boxShadow: 'none',
  211. },
  212. },
  213. '&:focus-within': {
  214. borderColor: 'var(--input-border-focus)',
  215. boxShadow: 'var(--ol-cm-search-form-focus-shadow)',
  216. },
  217. },
  218. '.ol-cm-search-input-group.ol-cm-search-input-error': {
  219. '&:focus-within': {
  220. borderColor: 'var(--input-border-danger)',
  221. boxShadow: 'var(--ol-cm-search-form-error-shadow)',
  222. },
  223. },
  224. '.input-group .ol-cm-search-form-input': {
  225. border: 'none',
  226. },
  227. '.ol-cm-search-input-button': {
  228. background: '#fff',
  229. color: 'inherit',
  230. border: 'none',
  231. },
  232. '.ol-cm-search-input-button.focused': {
  233. borderColor: 'var(--input-border-focus)',
  234. boxShadow: 'var(--ol-cm-search-form-focus-shadow)',
  235. },
  236. '.ol-cm-search-form-button-group': {
  237. flexShrink: 0,
  238. },
  239. '.ol-cm-search-form-position': {
  240. flexShrink: 0,
  241. color: 'var(--ol-blue-gray-4)',
  242. },
  243. '.ol-cm-search-hidden-inputs': {
  244. position: 'absolute',
  245. left: '-10000px',
  246. },
  247. '.ol-cm-search-form-close': {
  248. flex: 1,
  249. },
  250. '.ol-cm-search-replace-input': {
  251. order: 3,
  252. },
  253. '.ol-cm-search-replace-buttons': {
  254. order: 4,
  255. },
  256. }),
  257. ]
  258. }