search.ts 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367
  1. import {
  2. search as searchExtension,
  3. setSearchQuery,
  4. getSearchQuery,
  5. openSearchPanel,
  6. SearchQuery,
  7. searchPanelOpen,
  8. searchKeymap,
  9. highlightSelectionMatches,
  10. togglePanel,
  11. } from '@codemirror/search'
  12. import { Decoration, EditorView, keymap, ViewPlugin } from '@codemirror/view'
  13. import {
  14. Annotation,
  15. Compartment,
  16. EditorSelection,
  17. EditorState,
  18. SelectionRange,
  19. StateEffect,
  20. StateField,
  21. TransactionSpec,
  22. } from '@codemirror/state'
  23. const restoreSearchQueryAnnotation = Annotation.define<boolean>()
  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. const storedSelectionEffect = StateEffect.define<EditorSelection | null>()
  37. const storedSelectionState = StateField.define<EditorSelection | null>({
  38. create() {
  39. return null
  40. },
  41. update(value, tr) {
  42. if (value) {
  43. value = value.map(tr.changes)
  44. }
  45. for (const effect of tr.effects) {
  46. if (effect.is(storedSelectionEffect)) {
  47. value = effect.value
  48. } else if (effect.is(togglePanel) && effect.value === false) {
  49. value = null // clear the stored selection when closing the search panel
  50. }
  51. }
  52. return value
  53. },
  54. provide(f) {
  55. return [
  56. EditorView.decorations.from(f, selection => {
  57. if (!selection) {
  58. return Decoration.none
  59. }
  60. const decorations = selection.ranges
  61. .filter(range => !range.empty)
  62. .map(range =>
  63. Decoration.mark({
  64. class: 'ol-cm-stored-selection',
  65. }).range(range.from, range.to)
  66. )
  67. return Decoration.set(decorations)
  68. }),
  69. ]
  70. },
  71. })
  72. export const getStoredSelection = (state: EditorState) =>
  73. state.field(storedSelectionState)
  74. export const setStoredSelection = (selection: EditorSelection | null) => {
  75. return {
  76. effects: [
  77. storedSelectionEffect.of(selection),
  78. // TODO: only disable selection highlighting if the current selection is a search match
  79. highlightSelectionMatchesConf.reconfigure(
  80. selection ? [] : highlightSelectionMatchesExtension
  81. ),
  82. ],
  83. }
  84. }
  85. const highlightSelectionMatchesConf = new Compartment()
  86. const highlightSelectionMatchesExtension = highlightSelectionMatches({
  87. wholeWords: true,
  88. })
  89. // store the search query for use when switching between files
  90. // TODO: move this into EditorContext?
  91. let searchQuery: SearchQuery | null
  92. export const search = () => {
  93. let open = false
  94. return [
  95. // keymap for search
  96. keymap.of(searchKeymap),
  97. // highlight text which matches the current selection
  98. highlightSelectionMatchesConf.of(highlightSelectionMatchesExtension),
  99. // a stored selection for use in "within selection" searches
  100. storedSelectionState,
  101. // a wrapper round `search`, which creates a custom panel element and passes it to React by dispatching an event
  102. searchExtension({
  103. literal: true,
  104. // centre the search match if it was outside the visible area
  105. scrollToMatch: (range: SelectionRange, view: EditorView) => {
  106. const coords = {
  107. from: view.coordsAtPos(range.from),
  108. to: view.coordsAtPos(range.to),
  109. }
  110. const scrollRect = view.scrollDOM.getBoundingClientRect()
  111. const strategy =
  112. (coords.from && coords.from.top < scrollRect.top) ||
  113. (coords.to && coords.to.bottom > scrollRect.bottom)
  114. ? 'center'
  115. : 'nearest'
  116. return EditorView.scrollIntoView(range, {
  117. y: strategy,
  118. })
  119. },
  120. createPanel: () => {
  121. const dom = document.createElement('div')
  122. dom.className = 'ol-cm-search'
  123. return {
  124. dom,
  125. mount() {
  126. open = true
  127. // focus the search input when the panel is already open
  128. const searchInput =
  129. dom.querySelector<HTMLInputElement>('[main-field]')
  130. if (searchInput) {
  131. searchInput.focus()
  132. searchInput.select()
  133. }
  134. },
  135. destroy() {
  136. window.setTimeout(() => {
  137. open = false // in a timeout, so the view plugin below can run its destroy method first
  138. }, 0)
  139. },
  140. }
  141. },
  142. }),
  143. // restore a stored search and re-open the search panel
  144. ViewPlugin.define(view => {
  145. if (searchQuery) {
  146. const _searchQuery = searchQuery
  147. window.setTimeout(() => {
  148. openSearchPanel(view)
  149. view.dispatch({
  150. effects: setSearchQuery.of(_searchQuery),
  151. annotations: restoreSearchQueryAnnotation.of(true),
  152. })
  153. }, 0)
  154. }
  155. return {
  156. destroy() {
  157. // persist the current search query if the panel is open
  158. searchQuery = open ? getSearchQuery(view.state) : null
  159. },
  160. }
  161. }),
  162. // select a match while searching
  163. EditorView.updateListener.of(update => {
  164. // if the search panel wasn't open, don't select a match
  165. if (!searchPanelOpen(update.startState)) {
  166. return
  167. }
  168. for (const tr of update.transactions) {
  169. // avoid changing the selection and viewport when switching between files
  170. if (tr.annotation(restoreSearchQueryAnnotation)) {
  171. continue
  172. }
  173. for (const effect of tr.effects) {
  174. if (effect.is(setSearchQuery)) {
  175. const query = effect.value
  176. if (!query) return
  177. // The rest of this messes up searching in Vim, which is handled by
  178. // the Vim extension, so bail out here in Vim mode. Happily, the
  179. // Vim extension sticks an extra property on the query value that
  180. // can be checked
  181. if ('forVim' in query) return
  182. const next = selectNextMatch(query, tr.state)
  183. if (next) {
  184. // select a match if possible
  185. const spec: TransactionSpec = {
  186. selection: { anchor: next.from, head: next.to },
  187. userEvent: 'select.search',
  188. }
  189. // scroll into view if not opening the panel
  190. if (searchPanelOpen(tr.startState)) {
  191. spec.effects = EditorView.scrollIntoView(next.from, {
  192. y: 'center',
  193. })
  194. }
  195. update.view.dispatch(spec)
  196. } else {
  197. // clear the selection if the query became invalid
  198. const prevQuery = getSearchQuery(tr.startState)
  199. if (prevQuery.valid) {
  200. const { from } = tr.startState.selection.main
  201. update.view.dispatch({
  202. selection: { anchor: from },
  203. })
  204. }
  205. }
  206. }
  207. }
  208. }
  209. }),
  210. // search form theme
  211. EditorView.theme({
  212. '.ol-cm-search-form': {
  213. padding: '10px',
  214. display: 'flex',
  215. gap: '10px',
  216. background: 'var(--ol-blue-gray-1)',
  217. '--ol-cm-search-form-focus-shadow':
  218. 'inset 0 1px 1px rgb(0 0 0 / 8%), 0 0 8px rgb(102 175 233 / 60%)',
  219. '--ol-cm-search-form-error-shadow':
  220. 'inset 0 1px 1px rgb(0 0 0 / 8%), 0 0 8px var(--input-shadow-danger-color)',
  221. },
  222. '.ol-cm-search-controls': {
  223. display: 'grid',
  224. gridTemplateColumns: 'auto auto',
  225. gridTemplateRows: 'auto auto',
  226. gap: '10px',
  227. },
  228. '.ol-cm-search-form-row': {
  229. display: 'flex',
  230. gap: '10px',
  231. justifyContent: 'space-between',
  232. },
  233. '.ol-cm-search-form-group': {
  234. display: 'flex',
  235. gap: '10px',
  236. alignItems: 'center',
  237. },
  238. '.ol-cm-search-input-group': {
  239. border: '1px solid var(--input-border)',
  240. borderRadius: '20px',
  241. background: 'white',
  242. width: '100%',
  243. maxWidth: '25em',
  244. '& input[type="text"]': {
  245. background: 'none',
  246. boxShadow: 'none',
  247. },
  248. '& input[type="text"]:focus': {
  249. outline: 'none',
  250. boxShadow: 'none',
  251. },
  252. '& .btn.btn': {
  253. background: 'var(--ol-blue-gray-0)',
  254. color: 'var(--ol-blue-gray-3)',
  255. borderRadius: '50%',
  256. height: '2em',
  257. display: 'inline-flex',
  258. alignItems: 'center',
  259. justifyContent: 'center',
  260. width: '2em',
  261. marginRight: '3px',
  262. '&.checked': {
  263. color: '#fff',
  264. backgroundColor: 'var(--ol-blue)',
  265. },
  266. '&:active': {
  267. boxShadow: 'none',
  268. },
  269. },
  270. '&:focus-within': {
  271. borderColor: 'var(--input-border-focus)',
  272. boxShadow: 'var(--ol-cm-search-form-focus-shadow)',
  273. },
  274. },
  275. '.ol-cm-search-input-group.ol-cm-search-input-error': {
  276. '&:focus-within': {
  277. borderColor: 'var(--input-border-danger)',
  278. boxShadow: 'var(--ol-cm-search-form-error-shadow)',
  279. },
  280. },
  281. '.input-group .ol-cm-search-form-input': {
  282. border: 'none',
  283. },
  284. '.ol-cm-search-input-button': {
  285. background: '#fff',
  286. color: 'inherit',
  287. border: 'none',
  288. },
  289. '.ol-cm-search-input-button.focused': {
  290. borderColor: 'var(--input-border-focus)',
  291. boxShadow: 'var(--ol-cm-search-form-focus-shadow)',
  292. },
  293. '.ol-cm-search-form-button-group': {
  294. flexShrink: 0,
  295. },
  296. '.ol-cm-search-form-position': {
  297. flexShrink: 0,
  298. color: 'var(--ol-blue-gray-4)',
  299. },
  300. '.ol-cm-search-hidden-inputs': {
  301. position: 'absolute',
  302. left: '-10000px',
  303. },
  304. '.ol-cm-search-form-close': {
  305. flex: 1,
  306. },
  307. '.ol-cm-search-replace-input': {
  308. order: 3,
  309. },
  310. '.ol-cm-search-replace-buttons': {
  311. order: 4,
  312. },
  313. '.ol-cm-stored-selection': {
  314. background: 'rgba(125, 125, 125, 0.1)',
  315. paddingTop: 'var(--half-leading)',
  316. paddingBottom: 'var(--half-leading)',
  317. },
  318. // set the default "match" style
  319. '.cm-selectionMatch, .cm-searchMatch': {
  320. backgroundColor: 'transparent',
  321. outlineOffset: '-1px',
  322. paddingTop: 'var(--half-leading)',
  323. paddingBottom: 'var(--half-leading)',
  324. },
  325. // make sure selectionMatch inside searchMatch doesn't have a background colour
  326. '.cm-searchMatch .cm-selectionMatch': {
  327. backgroundColor: 'transparent !important',
  328. },
  329. }),
  330. ]
  331. }