search.ts 11 KB

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